add integration test for game-server

This commit is contained in:
2026-11-15 18:26:52 +03:00
parent 1bc688055a
commit 93b883dfba
@@ -0,0 +1,423 @@
package ws_test
import (
"context"
"encoding/json"
"log/slog"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
"github.com/coder/websocket"
"github.com/golang-jwt/jwt/v5"
"github.com/ruby-sea-battle/game-server/internal/auth"
"github.com/ruby-sea-battle/game-server/internal/game"
"github.com/ruby-sea-battle/game-server/internal/protocol"
"github.com/ruby-sea-battle/game-server/internal/ws"
)
// testKey loads the shared test secret from contracts/test_signature_vectors.json.
// It is the single source of truth for the wire format shared with main-server,
// so the integration tests below exercise the same key the real deployment uses
// for both JWTs and match-result HMAC signatures.
func testKey(t *testing.T) []byte {
t.Helper()
_, file, _, ok := runtime.Caller(0)
if !ok {
t.Fatal("cannot locate test file")
}
path := filepath.Join(filepath.Dir(file), "..", "..", "..", "contracts", "test_signature_vectors.json")
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read signature vectors: %v", err)
}
var doc struct {
Vectors []struct {
Secret string `json:"secret"`
} `json:"vectors"`
}
if err := json.Unmarshal(data, &doc); err != nil {
t.Fatalf("parse signature vectors: %v", err)
}
if len(doc.Vectors) == 0 || doc.Vectors[0].Secret == "" {
t.Fatal("no secret found in signature vectors")
}
return []byte(doc.Vectors[0].Secret)
}
// startServerWithKey mirrors startServerWithManager from handler_test.go but
// signs tokens with the shared test key instead of the hardcoded one.
func startServerWithKey(t *testing.T, joinTimeout time.Duration, key []byte) string {
t.Helper()
manager := game.NewManager(joinTimeout)
tw := &testWriter{t: t}
log := slog.New(slog.NewTextHandler(tw, nil))
handler := ws.NewHandler(manager, key, publicAddr, []string{"*"}, log)
srv := httptest.NewServer(handler)
t.Cleanup(func() {
srv.Close()
tw.mu.Lock()
tw.done = true
tw.mu.Unlock()
})
return "ws" + strings.TrimPrefix(srv.URL, "http")
}
func gameTokenWithKey(t *testing.T, key []byte, matchID string, p1, p2 int64, exp time.Time) string {
t.Helper()
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, &auth.GameClaims{
MatchID: matchID,
Player1ID: p1,
Player2ID: p2,
GameServer: publicAddr,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(exp),
},
}).SignedString(key)
if err != nil {
t.Fatalf("sign game token: %v", err)
}
return token
}
func userTokenWithKey(t *testing.T, key []byte, userID int64) string {
t.Helper()
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, &auth.UserClaims{
UserID: userID,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
},
}).SignedString(key)
if err != nil {
t.Fatalf("sign user token: %v", err)
}
return token
}
// startGame connects both players with the shared test key and acknowledges the
// initial StatePlacingShips (seq 1). Returns the server URL and the connections:
// c1 is player1, c2 is player2.
func startGame(t *testing.T, key []byte, matchID string) (string, *websocket.Conn, *websocket.Conn) {
t.Helper()
url := startServerWithKey(t, time.Minute, key)
gt := gameTokenWithKey(t, key, matchID, 1, 2, time.Now().Add(time.Hour))
c1, c2 := dial(t, url), dial(t, url)
join(t, c1, gt, userTokenWithKey(t, key, 1))
join(t, c2, gt, userTokenWithKey(t, key, 2))
for i, c := range []*websocket.Conn{c1, c2} {
v := readMsg(t, c)
if v[0] != float64(protocol.OpState) || v[1] != float64(1) || v[2] != float64(protocol.StatePlacingShips) {
t.Fatalf("player %d: unexpected initial state: %v", i+1, v)
}
ack(t, c, 1)
}
return url, c1, c2
}
// ack acknowledges a message with the given sequence number (best effort).
func ack(t *testing.T, c *websocket.Conn, seq int64) {
t.Helper()
_ = c.Write(context.Background(), websocket.MessageText, protocol.BuildAck(seq))
}
// placeShipsFirst submits a valid placement for the first player and asserts the
// per-player "waiting for opponent" state (seq 2).
func placeShipsFirst(t *testing.T, c1, c2 *websocket.Conn, firstIsPlayer1 bool) {
t.Helper()
ships := validTestShips()
first, second := c1, c2
if !firstIsPlayer1 {
first, second = c2, c1
}
if err := first.Write(context.Background(), websocket.MessageText, protocol.BuildPlaceShips(ships)); err != nil {
t.Fatalf("write PlaceShips: %v", err)
}
vFirst := readMsg(t, first)
if vFirst[0] != float64(protocol.OpState) || vFirst[1] != float64(2) || vFirst[2] != float64(protocol.StateWaitOpponentReady) {
t.Fatalf("first player got %v, want [3,2,3] StateWaitOpponentReady", vFirst)
}
vSecond := readMsg(t, second)
if vSecond[0] != float64(protocol.OpState) || vSecond[1] != float64(2) || vSecond[2] != float64(protocol.StateOpponentReady) {
t.Fatalf("second player got %v, want [3,2,2] StateOpponentReady", vSecond)
}
ack(t, first, 2)
ack(t, second, 2)
}
// placeShipsSecond submits a valid placement for the remaining player, starts the
// battle phase (seq 3) and returns the connection of the player whose turn it is
// (the one who placed ships first).
func placeShipsSecond(t *testing.T, c1, c2 *websocket.Conn, firstIsPlayer1 bool) *websocket.Conn {
t.Helper()
ships := validTestShips()
first, second := c1, c2
if !firstIsPlayer1 {
first, second = c2, c1
}
if err := second.Write(context.Background(), websocket.MessageText, protocol.BuildPlaceShips(ships)); err != nil {
t.Fatalf("write PlaceShips: %v", err)
}
vFirst := readMsg(t, first)
if vFirst[0] != float64(protocol.OpState) || vFirst[1] != float64(3) || vFirst[2] != float64(protocol.StateYourTurn) {
t.Fatalf("first player got %v, want [3,3,4] StateYourTurn", vFirst)
}
vSecond := readMsg(t, second)
if vSecond[0] != float64(protocol.OpState) || vSecond[1] != float64(3) || vSecond[2] != float64(protocol.StateWaitOpponentTurn) {
t.Fatalf("second player got %v, want [3,3,5] StateWaitOpponentTurn", vSecond)
}
ack(t, first, 3)
ack(t, second, 3)
return first
}
// fireResult sends a FIRE and reads back the FIRE_RESULT, returning its seq and
// result code. It does not acknowledge the message.
func fireResult(t *testing.T, shooter *websocket.Conn, x, y int) (int64, int) {
t.Helper()
if err := shooter.Write(context.Background(), websocket.MessageText, protocol.BuildFire(x, y)); err != nil {
t.Fatalf("write FIRE: %v", err)
}
v := readMsg(t, shooter)
if v[0] != float64(protocol.OpFireResult) {
t.Fatalf("expected FIRE_RESULT, got %v", v)
}
return int64(v[1].(float64)), int(v[2].(float64))
}
// missAndHandoff fires at a known-water cell, asserts the miss and the turn
// handoff to the opponent (STATE messages are acknowledged).
func missAndHandoff(t *testing.T, shooter, opponent *websocket.Conn, x, y int) {
t.Helper()
seq, result := fireResult(t, shooter, x, y)
if result != protocol.FireResultMiss {
t.Fatalf("result=%d, want Miss", result)
}
ack(t, shooter, seq)
vs := readMsg(t, shooter)
if vs[0] != float64(protocol.OpState) || vs[2] != float64(protocol.StateWaitOpponentTurn) {
t.Fatalf("shooter state after miss = %v, want StateWaitOpponentTurn", vs)
}
ack(t, shooter, int64(vs[1].(float64)))
vo := readMsg(t, opponent)
if vo[0] != float64(protocol.OpState) || vo[2] != float64(protocol.StateYourTurn) {
t.Fatalf("opponent state after miss = %v, want StateYourTurn", vo)
}
ack(t, opponent, int64(vo[1].(float64)))
}
// sinkAllShips fires at every cell of the canonical placement, expecting hits
// followed by a sink on the last cell of each ship. The final shot sinks the
// last ship and ends the match; END messages are read by the caller.
func sinkAllShips(t *testing.T, shooter *websocket.Conn) {
t.Helper()
ships := validTestShips()
for i, ship := range ships {
cells := ship.Cells()
for j, c := range cells {
seq, result := fireResult(t, shooter, c.X, c.Y)
if j < len(cells)-1 {
if result != protocol.FireResultHit {
t.Fatalf("ship %d cell %d: result=%d, want Hit", i, j, result)
}
} else if result != protocol.FireResultSunk {
t.Fatalf("ship %d last cell: result=%d, want Sunk", i, result)
}
ack(t, shooter, seq)
}
}
}
// readEnd reads an END message and returns its end code and reason.
func readEnd(t *testing.T, c *websocket.Conn) (int, string) {
t.Helper()
v := readMsg(t, c)
if v[0] != float64(protocol.OpEnd) {
t.Fatalf("expected END, got %v", v)
}
return int(v[2].(float64)), v[3].(string)
}
// expectClosed asserts the connection is closed with the given close code.
func expectClosed(t *testing.T, c *websocket.Conn, want websocket.StatusCode) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_, _, err := c.Read(ctx)
if err == nil {
t.Fatal("expected connection to be closed")
}
if code := websocket.CloseStatus(err); code != want {
t.Fatalf("close status = %d, want %d", code, want)
}
}
// TestFullGamePlayer2Wins covers a complete match from join to end where the
// player who goes second wins: player 1 opens fire but misses, player 2 then
// sinks every one of player 1's ships.
func TestFullGamePlayer2Wins(t *testing.T) {
key := testKey(t)
_, c1, c2 := startGame(t, key, "full-game-p2-wins")
// Player 1 places first, so player 1 gets the first turn.
placeShipsFirst(t, c1, c2, true)
placeShipsSecond(t, c1, c2, true)
// Player 1's opening shot misses at (9,9); the turn passes to player 2.
missAndHandoff(t, c1, c2, 9, 9)
// Player 2 sinks all of player 1's ships.
sinkAllShips(t, c2)
// Player 2 receives victory, player 1 receives defeat.
if code, reason := readEnd(t, c2); code != protocol.EndCodeVictory || reason != "victory" {
t.Fatalf("c2 got END code=%d reason=%q, want victory", code, reason)
}
if code, reason := readEnd(t, c1); code != protocol.EndCodeDefeat || reason != "defeat" {
t.Fatalf("c1 got END code=%d reason=%q, want defeat", code, reason)
}
// Both connections are closed normally after END.
expectClosed(t, c1, websocket.StatusNormalClosure)
expectClosed(t, c2, websocket.StatusNormalClosure)
}
// TestFullGamePlayer2PlacesFirstAndWins covers the mirror scenario: player 2
// places ships first and therefore gets the first turn, then wins without ever
// giving player 1 a shot.
func TestFullGamePlayer2PlacesFirstAndWins(t *testing.T) {
key := testKey(t)
_, c1, c2 := startGame(t, key, "full-game-p2-first")
// Player 2 places first, so player 2 gets the first turn.
placeShipsFirst(t, c1, c2, false)
if shooter := placeShipsSecond(t, c1, c2, false); shooter != c2 {
t.Fatal("expected player 2 to have the first turn")
}
sinkAllShips(t, c2)
if code, reason := readEnd(t, c2); code != protocol.EndCodeVictory || reason != "victory" {
t.Fatalf("c2 got END code=%d reason=%q, want victory", code, reason)
}
if code, reason := readEnd(t, c1); code != protocol.EndCodeDefeat || reason != "defeat" {
t.Fatalf("c1 got END code=%d reason=%q, want defeat", code, reason)
}
expectClosed(t, c1, websocket.StatusNormalClosure)
expectClosed(t, c2, websocket.StatusNormalClosure)
}
// TestReconnectDuringBattleReplaysUnackedFireResult drops a player mid-battle
// after an unacknowledged shot and verifies the FIRE_RESULT is replayed on
// reconnect so the client can catch up.
func TestReconnectDuringBattleReplaysUnackedFireResult(t *testing.T) {
key := testKey(t)
url, c1, c2 := startGame(t, key, "reconnect-battle")
placeShipsFirst(t, c1, c2, true)
placeShipsSecond(t, c1, c2, true)
// Player 1 hits ship 9 at (0,0) but does NOT acknowledge the result.
seq, result := fireResult(t, c1, 0, 0)
if result != protocol.FireResultHit {
t.Fatalf("result=%d, want Hit", result)
}
if seq != 4 {
t.Fatalf("fire result seq=%d, want 4", seq)
}
// Simulate a dropped connection.
c1.Close(websocket.StatusAbnormalClosure, "network gone")
// Reconnect with the same tokens: the unacknowledged FIRE_RESULT is replayed.
c1b := dial(t, url)
join(t, c1b, gameTokenWithKey(t, key, "reconnect-battle", 1, 2, time.Now().Add(time.Hour)), userTokenWithKey(t, key, 1))
v := readMsg(t, c1b)
if v[0] != float64(protocol.OpFireResult) || v[1] != float64(4) || v[2] != float64(protocol.FireResultHit) {
t.Fatalf("replayed message = %v, want [7,4,2]", v)
}
// The game is still alive: player 1 keeps the turn after a hit and can sink
// the rest of the ship (cells (1,0), (2,0), (3,0)).
for _, pt := range [][2]int{{1, 0}, {2, 0}} {
if _, result := fireResult(t, c1b, pt[0], pt[1]); result != protocol.FireResultHit {
t.Fatalf("cell %v: result=%d, want Hit", pt, result)
}
}
}
// TestInvalidShipPlacementOverWebSocket verifies an invalid placement is ignored
// without closing the connection: the state does not advance and a subsequent
// valid placement is accepted.
func TestInvalidShipPlacementOverWebSocket(t *testing.T) {
key := testKey(t)
_, c1, c2 := startGame(t, key, "invalid-placement")
// Two size-1 ships overlapping at (7,4) is invalid.
overlapping := validTestShips()
overlapping[0].X = 7
overlapping[0].Y = 4
if err := c1.Write(context.Background(), websocket.MessageText, protocol.BuildPlaceShips(overlapping)); err != nil {
t.Fatalf("write invalid PlaceShips: %v", err)
}
// No message is sent for the rejected placement. A valid placement must now
// still produce seq 2 (the rejected one must not have consumed a sequence).
ships := validTestShips()
if err := c1.Write(context.Background(), websocket.MessageText, protocol.BuildPlaceShips(ships)); err != nil {
t.Fatalf("write valid PlaceShips: %v", err)
}
v1 := readMsg(t, c1)
if v1[0] != float64(protocol.OpState) || v1[1] != float64(2) || v1[2] != float64(protocol.StateWaitOpponentReady) {
t.Fatalf("c1 got %v, want [3,2,3] StateWaitOpponentReady", v1)
}
v2 := readMsg(t, c2)
if v2[0] != float64(protocol.OpState) || v2[1] != float64(2) || v2[2] != float64(protocol.StateOpponentReady) {
t.Fatalf("c2 got %v, want [3,2,2] StateOpponentReady", v2)
}
ack(t, c1, 2)
ack(t, c2, 2)
}
// TestFireAtAlreadyStruckCellOverWebSocket verifies that shooting a cell that was
// already struck (the sunk ship itself or its surrounding halo) yields
// invalid_position while the shooter keeps the turn.
func TestFireAtAlreadyStruckCellOverWebSocket(t *testing.T) {
key := testKey(t)
_, c1, c2 := startGame(t, key, "already-struck")
placeShipsFirst(t, c1, c2, true)
placeShipsSecond(t, c1, c2, true)
// Sink ship 0 (size 1 at (9,4)). Its halo marks (8,3),(8,4),(8,5),(9,3),(9,4),(9,5).
if _, result := fireResult(t, c1, 9, 4); result != protocol.FireResultSunk {
t.Fatalf("first shot: result=%d, want Sunk", result)
}
// The sunk cell itself is already struck.
if _, result := fireResult(t, c1, 9, 4); result != protocol.FireResultInvalidPosition {
t.Fatalf("sunk cell: result=%d, want InvalidPosition", result)
}
// A halo cell is already struck too.
if _, result := fireResult(t, c1, 8, 4); result != protocol.FireResultInvalidPosition {
t.Fatalf("halo cell: result=%d, want InvalidPosition", result)
}
// Player 1 still has the turn: a fresh cell is a valid hit.
if _, result := fireResult(t, c1, 0, 0); result != protocol.FireResultHit {
t.Fatalf("fresh cell: result=%d, want Hit", result)
}
}