feat: command validation

This commit is contained in:
IliaDenisov
2026-02-10 18:31:53 +03:00
parent b5400bd61e
commit 6c8384ce7a
6 changed files with 178 additions and 30 deletions
+56 -9
View File
@@ -10,13 +10,17 @@ import (
"github.com/stretchr/testify/assert"
)
var (
commandNoErrorCode = http.StatusNoContent
)
func TestCommand(t *testing.T) {
r := setupRouter()
payload := rest.Command{
payload := &rest.Command{
Actor: "SomeRace",
Commands: []json.RawMessage{
encodeCommand(&rest.CommandVote{
encodeCommand(&rest.CommandRaceVote{
CommandMeta: rest.CommandMeta{Type: rest.CommandTypeRaceVote},
Recipient: "AnotherRace",
}),
@@ -27,7 +31,7 @@ func TestCommand(t *testing.T) {
req, _ := http.NewRequest("PUT", "/api/v1/command", asBody(payload))
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusNoContent, w.Code, w.Body)
assert.Equal(t, commandNoErrorCode, w.Code, w.Body)
// error: notblank validator
payload.Actor = ""
@@ -45,7 +49,7 @@ func TestCommand(t *testing.T) {
assert.Equal(t, http.StatusBadRequest, w.Code, w.Body)
// error: no commands
payload = rest.Command{
payload = &rest.Command{
Actor: "SomeRace",
}
@@ -56,10 +60,53 @@ func TestCommand(t *testing.T) {
assert.Equal(t, http.StatusBadRequest, w.Code, w.Body)
}
func encodeCommand(cmd any) json.RawMessage {
v, err := json.Marshal(cmd)
if err != nil {
panic(err)
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)
})
}
return v
}