Files
scrabble-game/gateway/internal/transcode/transcode_test.go
T
Ilia Denisov 6b6baf5710
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 8s
CI / integration (pull_request) Successful in 11s
CI / ui (pull_request) Successful in 31s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m19s
Stage 17 round 6 (#16/#17, PR C): lobby sort + server-derived in-game friend state
Lobby: group the my-games list into your-turn / opponent-turn / finished
(empty sections hidden), ordered by last activity (your-turn oldest-first,
the other two newest-first), as a compact line-separated list. gameDTO and
FB GameView gain last_activity_unix (turn start while active, finish time
once finished); a pure lib/lobbysort.ts holds the grouping/ordering.

Friends: the in-game 'add to friends' item is now server-derived via a new
GET /user/friends/outgoing (+ friends.outgoing op), returning addressees with
a pending OR declined request (both read as 'request sent'), so it is correct
across reloads; it shows a disabled '✓ in friends' once accepted. It
live-updates when the opponent answers: RespondFriendRequest now publishes
friend_added (accept) / friend_declined (new notify sub-kind, decline) to the
original requester, whose open game re-derives its friend state.

Tests: lobbysort unit test; gateway outgoing + last_activity transcode tests;
backend integration ListOutgoingRequests + respond-publishes-to-requester;
e2e updated for the new lobby section labels + a non-friend active opponent.
Docs: ARCHITECTURE notify catalog, FUNCTIONAL(+ru) lobby/friends, PLAN.
2026-06-08 19:23:48 +02:00

238 lines
8.0 KiB
Go

package transcode_test
import (
"context"
"net/http"
"net/http/httptest"
"testing"
flatbuffers "github.com/google/flatbuffers/go"
"scrabble/gateway/internal/backendclient"
"scrabble/gateway/internal/transcode"
fb "scrabble/pkg/fbs/scrabblefb"
)
// fakeBackend serves the subset of backend endpoints the slice handlers call.
func fakeBackend(t *testing.T, h http.HandlerFunc) (*backendclient.Client, func()) {
t.Helper()
srv := httptest.NewServer(h)
c, err := backendclient.New(srv.URL, "localhost:9090", 2_000_000_000)
if err != nil {
t.Fatalf("backendclient: %v", err)
}
return c, func() {
_ = c.Close()
srv.Close()
}
}
func TestGuestAuthRoundTrip(t *testing.T) {
backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/v1/internal/sessions/guest" {
t.Errorf("unexpected path %q", r.URL.Path)
}
_, _ = w.Write([]byte(`{"token":"tok-1","user_id":"u-1","is_guest":true,"display_name":"Guest"}`))
})
defer cleanup()
reg := transcode.NewRegistry(backend, nil)
op, ok := reg.Lookup(transcode.MsgAuthGuest)
if !ok {
t.Fatal("auth.guest not registered")
}
payload, err := op.Handler(context.Background(), transcode.Request{})
if err != nil {
t.Fatalf("handler: %v", err)
}
sess := fb.GetRootAsSession(payload, 0)
if string(sess.Token()) != "tok-1" || string(sess.UserId()) != "u-1" || !sess.IsGuest() {
t.Fatalf("session decoded wrong: token=%q user=%q guest=%v", sess.Token(), sess.UserId(), sess.IsGuest())
}
}
func TestGameStateRoundTripForwardsUserID(t *testing.T) {
backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("X-User-ID"); got != "u-7" {
t.Errorf("X-User-ID = %q, want u-7", got)
}
if r.URL.Path != "/api/v1/user/games/g-1/state" {
t.Errorf("unexpected path %q", r.URL.Path)
}
_, _ = w.Write([]byte(`{"game":{"id":"g-1","variant":"english","status":"active","players":2,"to_move":1,"seats":[{"seat":0,"account_id":"u-7","score":5}]},"seat":0,"rack":[0,1],"bag_len":80,"hints_remaining":1}`))
})
defer cleanup()
reg := transcode.NewRegistry(backend, nil)
op, _ := reg.Lookup(transcode.MsgGameState)
b := flatbuffers.NewBuilder(32)
gid := b.CreateString("g-1")
fb.StateRequestStart(b)
fb.StateRequestAddGameId(b, gid)
b.Finish(fb.StateRequestEnd(b))
payload, err := op.Handler(context.Background(), transcode.Request{Payload: b.FinishedBytes(), UserID: "u-7"})
if err != nil {
t.Fatalf("handler: %v", err)
}
st := fb.GetRootAsStateView(payload, 0)
if st.BagLen() != 80 || st.RackLength() != 2 || st.HintsRemaining() != 1 {
t.Fatalf("state decoded wrong: bag=%d rack=%d hints=%d", st.BagLen(), st.RackLength(), st.HintsRemaining())
}
game := st.Game(nil)
if game == nil || string(game.Id()) != "g-1" || string(game.Variant()) != "english" || game.ToMove() != 1 {
t.Fatalf("nested game decoded wrong: %+v", game)
}
}
func TestEnqueueRoundTripEncodesMatch(t *testing.T) {
backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(`{"matched":true,"game":{"id":"g-9","variant":"english","status":"active","players":2,"to_move":0,"seats":[]}}`))
})
defer cleanup()
reg := transcode.NewRegistry(backend, nil)
op, _ := reg.Lookup(transcode.MsgLobbyEnqueue)
b := flatbuffers.NewBuilder(32)
v := b.CreateString("english")
fb.EnqueueRequestStart(b)
fb.EnqueueRequestAddVariant(b, v)
b.Finish(fb.EnqueueRequestEnd(b))
payload, err := op.Handler(context.Background(), transcode.Request{Payload: b.FinishedBytes(), UserID: "u-1"})
if err != nil {
t.Fatalf("handler: %v", err)
}
m := fb.GetRootAsMatchResult(payload, 0)
if !m.Matched() {
t.Fatal("match result should be matched")
}
if g := m.Game(nil); g == nil || string(g.Id()) != "g-9" {
t.Fatalf("match game decoded wrong: %+v", g)
}
}
func TestDomainErrorSurfacesBackendCode(t *testing.T) {
backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusConflict)
_, _ = w.Write([]byte(`{"error":{"code":"not_your_turn","message":"nope"}}`))
})
defer cleanup()
reg := transcode.NewRegistry(backend, nil)
op, _ := reg.Lookup(transcode.MsgGameState)
b := flatbuffers.NewBuilder(32)
gid := b.CreateString("g-1")
fb.StateRequestStart(b)
fb.StateRequestAddGameId(b, gid)
b.Finish(fb.StateRequestEnd(b))
_, err := op.Handler(context.Background(), transcode.Request{Payload: b.FinishedBytes(), UserID: "u-1"})
if err == nil {
t.Fatal("expected backend error")
}
code, ok := transcode.DomainCode(err)
if !ok || code != "not_your_turn" {
t.Fatalf("DomainCode = (%q, %v), want (not_your_turn, true)", code, ok)
}
}
// gameActionPayload builds a GameActionRequest payload (pass / resign / hint / etc.).
func gameActionPayload(gameID string) []byte {
b := flatbuffers.NewBuilder(32)
gid := b.CreateString(gameID)
fb.GameActionRequestStart(b)
fb.GameActionRequestAddGameId(b, gid)
b.Finish(fb.GameActionRequestEnd(b))
return b.FinishedBytes()
}
func TestGamesListRoundTripDecodesSeatNames(t *testing.T) {
backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("X-User-ID"); got != "u-9" {
t.Errorf("X-User-ID = %q, want u-9", got)
}
if r.URL.Path != "/api/v1/user/games" {
t.Errorf("unexpected path %q", r.URL.Path)
}
_, _ = w.Write([]byte(`{"games":[{"id":"g-1","variant":"english","status":"active","players":2,"to_move":0,"last_activity_unix":1717000000,"seats":[{"seat":0,"account_id":"u-9","display_name":"You","score":10},{"seat":1,"account_id":"a-1","display_name":"Ann","score":7}]}]}`))
})
defer cleanup()
reg := transcode.NewRegistry(backend, nil)
op, _ := reg.Lookup(transcode.MsgGamesList)
payload, err := op.Handler(context.Background(), transcode.Request{UserID: "u-9"})
if err != nil {
t.Fatalf("handler: %v", err)
}
gl := fb.GetRootAsGameList(payload, 0)
if gl.GamesLength() != 1 {
t.Fatalf("games length = %d, want 1", gl.GamesLength())
}
var g fb.GameView
gl.Games(&g, 0)
if string(g.Id()) != "g-1" {
t.Errorf("game id = %q, want g-1", g.Id())
}
if g.LastActivityUnix() != 1717000000 {
t.Errorf("last activity = %d, want 1717000000", g.LastActivityUnix())
}
var seat fb.SeatView
g.Seats(&seat, 1)
if string(seat.DisplayName()) != "Ann" {
t.Errorf("seat display name = %q, want Ann", seat.DisplayName())
}
}
func TestPassRoundTrip(t *testing.T) {
backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/v1/user/games/g-2/pass" {
t.Errorf("unexpected path %q", r.URL.Path)
}
_, _ = w.Write([]byte(`{"move":{"player":0,"action":"pass"},"game":{"id":"g-2","status":"active","seats":[{"seat":0,"account_id":"u-1","display_name":"You"}]}}`))
})
defer cleanup()
reg := transcode.NewRegistry(backend, nil)
op, _ := reg.Lookup(transcode.MsgGamePass)
payload, err := op.Handler(context.Background(), transcode.Request{UserID: "u-1", Payload: gameActionPayload("g-2")})
if err != nil {
t.Fatalf("handler: %v", err)
}
mr := fb.GetRootAsMoveResult(payload, 0)
var move fb.MoveRecord
mr.Move(&move)
if string(move.Action()) != "pass" {
t.Errorf("action = %q, want pass", move.Action())
}
}
func TestHintRoundTrip(t *testing.T) {
backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/v1/user/games/g-3/hint" {
t.Errorf("unexpected path %q", r.URL.Path)
}
_, _ = w.Write([]byte(`{"move":{"player":0,"action":"play","words":["CAT"],"score":9},"hints_remaining":2}`))
})
defer cleanup()
reg := transcode.NewRegistry(backend, nil)
op, _ := reg.Lookup(transcode.MsgGameHint)
payload, err := op.Handler(context.Background(), transcode.Request{UserID: "u-1", Payload: gameActionPayload("g-3")})
if err != nil {
t.Fatalf("handler: %v", err)
}
hr := fb.GetRootAsHintResult(payload, 0)
if hr.HintsRemaining() != 2 {
t.Errorf("hints remaining = %d, want 2", hr.HintsRemaining())
}
var move fb.MoveRecord
hr.Move(&move)
if move.Score() != 9 {
t.Errorf("hint move score = %d, want 9", move.Score())
}
}