Files
galaxy-game/internal/router/command_test.go
T
2026-02-10 18:31:53 +03:00

113 lines
3.1 KiB
Go

package router_test
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/iliadenisov/galaxy/internal/model/rest"
"github.com/stretchr/testify/assert"
)
var (
commandNoErrorCode = http.StatusNoContent
)
func TestCommand(t *testing.T) {
r := setupRouter()
payload := &rest.Command{
Actor: "SomeRace",
Commands: []json.RawMessage{
encodeCommand(&rest.CommandRaceVote{
CommandMeta: rest.CommandMeta{Type: rest.CommandTypeRaceVote},
Recipient: "AnotherRace",
}),
},
}
w := httptest.NewRecorder()
req, _ := http.NewRequest("PUT", "/api/v1/command", asBody(payload))
r.ServeHTTP(w, req)
assert.Equal(t, commandNoErrorCode, w.Code, w.Body)
// error: notblank validator
payload.Actor = ""
w = httptest.NewRecorder()
req, _ = http.NewRequest("PUT", "/api/v1/command", asBody(payload))
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code, w.Body)
payload.Actor = " "
w = httptest.NewRecorder()
req, _ = http.NewRequest("PUT", "/api/v1/command", asBody(payload))
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code, w.Body)
// error: no commands
payload = &rest.Command{
Actor: "SomeRace",
}
w = httptest.NewRecorder()
req, _ = http.NewRequest("PUT", "/api/v1/command", asBody(payload))
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code, w.Body)
}
func TestCommandShipClassCreate(t *testing.T) {
r := setupRouter()
for _, tc := range []struct {
D float64
A int
W, S, C float64
expectStatus int
description string
}{
{1, 0, 0, 0, 0, commandNoErrorCode, "Simple Drone"},
{1, 1, 1, 0, 0, commandNoErrorCode, "Armed Drone"},
{1, 0, 0, 1, 0, commandNoErrorCode, "Shielded Drone"},
{1, 0, 0, 0, 1, commandNoErrorCode, "Carrying Drone"},
{-0.5, 0, 0, 0, 0, http.StatusBadRequest, "Drive less than 0"},
{0.9, 0, 0, 0, 0, http.StatusBadRequest, "Drive less than 1"},
{1, 1, 0, 0, 0, http.StatusBadRequest, "Ammo without Weapons"},
{1, 0, 1, 0, 0, http.StatusBadRequest, "Weapons without Ammo"},
{1, -1, 1, 0, 0, http.StatusBadRequest, "Ammo less than 0"},
{1, 1, 0.9, 0, 0, http.StatusBadRequest, "Weapons less than 1"},
{1, 1, -0.5, 0, 0, http.StatusBadRequest, "Weapons less than 0"},
{1, 0, 0, -0.5, 0, http.StatusBadRequest, "Shields less than 0"},
{1, 0, 0, 0.9, 0, http.StatusBadRequest, "Shields less than 1"},
{1, 0, 0, 0, -0.5, http.StatusBadRequest, "Cargo less than 0"},
{1, 0, 0, 0, 0.9, http.StatusBadRequest, "Cargo less than 1"},
} {
t.Run(tc.description, func(t *testing.T) {
payload := &rest.Command{
Actor: "SomeRace",
Commands: []json.RawMessage{
encodeCommand(&rest.CommandShipClassCreate{
CommandMeta: rest.CommandMeta{Type: rest.CommandTypeShipClassCreate},
Name: "Ship",
Drive: tc.D,
Armament: tc.A,
Weapons: tc.W,
Shields: tc.S,
Cargo: tc.C,
}),
},
}
w := httptest.NewRecorder()
req, _ := http.NewRequest("PUT", "/api/v1/command", asBody(payload))
r.ServeHTTP(w, req)
assert.Equal(t, tc.expectStatus, w.Code, w.Body)
})
}
}