aboutsummaryrefslogtreecommitdiffhomepage
path: root/backend/api/handler_test.go
blob: a68dfa08f67b465bdbf50d9a9624bf71fc29f6aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package api

import (
	"context"
	"errors"
	"testing"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgtype"

	"albatross-2026-backend/config"
	"albatross-2026-backend/db"
)

// mockQuerier implements db.Querier for testing.
type mockQuerier struct {
	db.Querier
	getGameByIDFunc     func(ctx context.Context, gameID int32) (db.GetGameByIDRow, error)
	listMainPlayersFunc func(ctx context.Context, gameIDs []int32) ([]db.ListMainPlayersRow, error)
}

func (m *mockQuerier) GetGameByID(ctx context.Context, gameID int32) (db.GetGameByIDRow, error) {
	if m.getGameByIDFunc != nil {
		return m.getGameByIDFunc(ctx, gameID)
	}
	return db.GetGameByIDRow{}, pgx.ErrNoRows
}

func (m *mockQuerier) ListMainPlayers(ctx context.Context, gameIDs []int32) ([]db.ListMainPlayersRow, error) {
	if m.listMainPlayersFunc != nil {
		return m.listMainPlayersFunc(ctx, gameIDs)
	}
	return nil, nil
}

// mockTxManager implements db.TxManager for testing.
type mockTxManager struct{}

func (m *mockTxManager) RunInTx(_ context.Context, fn func(q db.Querier) error) error {
	return fn(&mockQuerier{})
}

// mockGameHub implements GameHubInterface for testing.
type mockGameHub struct {
	calcCodeSizeResult int
	enqueueErr         error
}

func (m *mockGameHub) CalcCodeSize(_ string, _ string) int {
	return m.calcCodeSizeResult
}

func (m *mockGameHub) EnqueueTestTasks(_ context.Context, _, _, _ int, _, _ string) error {
	return m.enqueueErr
}

// mockAuthenticator implements AuthenticatorInterface for testing.
type mockAuthenticator struct {
	loginResult int
	loginErr    error
}

func (m *mockAuthenticator) Login(_ context.Context, _, _ string) (int, error) {
	return m.loginResult, m.loginErr
}

func TestPostGamePlaySubmit_GameNotFound(t *testing.T) {
	h := Handler{
		q:    &mockQuerier{},
		txm:  &mockTxManager{},
		hub:  &mockGameHub{},
		auth: &mockAuthenticator{},
		conf: &config.Config{},
	}
	user := &db.User{UserID: 1}
	resp, err := h.PostGamePlaySubmit(context.Background(), PostGamePlaySubmitRequestObject{
		GameID: 999,
		Body:   &PostGamePlaySubmitJSONRequestBody{Code: "test"},
	}, user)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if _, ok := resp.(PostGamePlaySubmit404JSONResponse); !ok {
		t.Errorf("expected 404 response, got %T", resp)
	}
}

func TestPostGamePlaySubmit_GameNotRunning(t *testing.T) {
	h := Handler{
		q: &mockQuerier{
			getGameByIDFunc: func(_ context.Context, _ int32) (db.GetGameByIDRow, error) {
				return db.GetGameByIDRow{
					GameID:   1,
					Language: "php",
					StartedAt: pgtype.Timestamp{
						Valid: false,
					},
				}, nil
			},
		},
		txm:  &mockTxManager{},
		hub:  &mockGameHub{calcCodeSizeResult: 10},
		auth: &mockAuthenticator{},
		conf: &config.Config{},
	}
	user := &db.User{UserID: 1}
	resp, err := h.PostGamePlaySubmit(context.Background(), PostGamePlaySubmitRequestObject{
		GameID: 1,
		Body:   &PostGamePlaySubmitJSONRequestBody{Code: "<?php echo 1;"},
	}, user)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if r, ok := resp.(PostGamePlaySubmit403JSONResponse); !ok {
		t.Errorf("expected 403 response, got %T", resp)
	} else if r.Message != "Game is not running" {
		t.Errorf("unexpected message: %s", r.Message)
	}
}

func TestIsGameRunning(t *testing.T) {
	now := time.Now()
	tests := []struct {
		name string
		game db.GetGameByIDRow
		want bool
	}{
		{
			name: "not started",
			game: db.GetGameByIDRow{
				StartedAt:       pgtype.Timestamp{Valid: false},
				DurationSeconds: 300,
			},
			want: false,
		},
		{
			name: "running",
			game: db.GetGameByIDRow{
				StartedAt:       pgtype.Timestamp{Time: now.Add(-1 * time.Minute), Valid: true},
				DurationSeconds: 300,
			},
			want: true,
		},
		{
			name: "finished",
			game: db.GetGameByIDRow{
				StartedAt:       pgtype.Timestamp{Time: now.Add(-10 * time.Minute), Valid: true},
				DurationSeconds: 300,
			},
			want: false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := isGameRunning(tt.game)
			if got != tt.want {
				t.Errorf("isGameRunning() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestIsGameFinished(t *testing.T) {
	now := time.Now()
	tests := []struct {
		name string
		game db.GetGameByIDRow
		want bool
	}{
		{
			name: "not started",
			game: db.GetGameByIDRow{
				StartedAt:       pgtype.Timestamp{Valid: false},
				DurationSeconds: 300,
			},
			want: false,
		},
		{
			name: "still running",
			game: db.GetGameByIDRow{
				StartedAt:       pgtype.Timestamp{Time: now.Add(-1 * time.Minute), Valid: true},
				DurationSeconds: 300,
			},
			want: false,
		},
		{
			name: "finished",
			game: db.GetGameByIDRow{
				StartedAt:       pgtype.Timestamp{Time: now.Add(-10 * time.Minute), Valid: true},
				DurationSeconds: 300,
			},
			want: true,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := isGameFinished(tt.game)
			if got != tt.want {
				t.Errorf("isGameFinished() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestToNullable(t *testing.T) {
	t.Run("nil value", func(t *testing.T) {
		result := toNullable[string](nil)
		if !result.IsNull() {
			t.Error("expected null for nil input")
		}
	})
	t.Run("non-nil value", func(t *testing.T) {
		s := "hello"
		result := toNullable(&s)
		if result.IsNull() {
			t.Error("expected non-null for non-nil input")
		}
		v, err := result.Get()
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if v != "hello" {
			t.Errorf("expected 'hello', got %q", v)
		}
	})
}

func TestGetMe(t *testing.T) {
	h := Handler{
		q:    &mockQuerier{},
		txm:  &mockTxManager{},
		hub:  &mockGameHub{},
		auth: &mockAuthenticator{},
		conf: &config.Config{},
	}
	user := &db.User{
		UserID:      1,
		Username:    "testuser",
		DisplayName: "Test User",
		IsAdmin:     false,
	}
	resp, err := h.GetMe(context.Background(), GetMeRequestObject{}, user)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	okResp, ok := resp.(GetMe200JSONResponse)
	if !ok {
		t.Fatalf("expected 200 response, got %T", resp)
	}
	if okResp.User.UserID != 1 {
		t.Errorf("expected user ID 1, got %d", okResp.User.UserID)
	}
	if okResp.User.Username != "testuser" {
		t.Errorf("expected username 'testuser', got %q", okResp.User.Username)
	}
	if okResp.User.IsAdmin {
		t.Error("expected non-admin user")
	}
}

func TestGetGame_NotFound(t *testing.T) {
	h := Handler{
		q:    &mockQuerier{},
		txm:  &mockTxManager{},
		hub:  &mockGameHub{},
		auth: &mockAuthenticator{},
		conf: &config.Config{},
	}
	user := &db.User{UserID: 1}
	resp, err := h.GetGame(context.Background(), GetGameRequestObject{GameID: 999}, user)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if _, ok := resp.(GetGame404JSONResponse); !ok {
		t.Errorf("expected 404 response, got %T", resp)
	}
}

func TestGetGame_NonPublicAsNonAdmin(t *testing.T) {
	h := Handler{
		q: &mockQuerier{
			getGameByIDFunc: func(_ context.Context, _ int32) (db.GetGameByIDRow, error) {
				return db.GetGameByIDRow{
					GameID:   1,
					IsPublic: false,
					Language: "php",
				}, nil
			},
		},
		txm:  &mockTxManager{},
		hub:  &mockGameHub{},
		auth: &mockAuthenticator{},
		conf: &config.Config{},
	}
	user := &db.User{UserID: 1, IsAdmin: false}
	resp, err := h.GetGame(context.Background(), GetGameRequestObject{GameID: 1}, user)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if _, ok := resp.(GetGame404JSONResponse); !ok {
		t.Errorf("expected 404 for non-public game as non-admin, got %T", resp)
	}
}

func TestGetGame_PublicGameSuccess(t *testing.T) {
	now := time.Now()
	h := Handler{
		q: &mockQuerier{
			getGameByIDFunc: func(_ context.Context, _ int32) (db.GetGameByIDRow, error) {
				return db.GetGameByIDRow{
					GameID:          1,
					IsPublic:        true,
					Language:        "php",
					DisplayName:     "Test Game",
					DurationSeconds: 300,
					StartedAt:       pgtype.Timestamp{Time: now, Valid: true},
					GameType:        "golf",
					ProblemID:       10,
					Title:           "Test Problem",
					Description:     "desc",
					SampleCode:      "<?php",
				}, nil
			},
			listMainPlayersFunc: func(_ context.Context, _ []int32) ([]db.ListMainPlayersRow, error) {
				return []db.ListMainPlayersRow{
					{UserID: 1, Username: "player1", DisplayName: "Player 1", IsAdmin: false},
				}, nil
			},
		},
		txm:  &mockTxManager{},
		hub:  &mockGameHub{},
		auth: &mockAuthenticator{},
		conf: &config.Config{},
	}
	user := &db.User{UserID: 1, IsAdmin: false}
	resp, err := h.GetGame(context.Background(), GetGameRequestObject{GameID: 1}, user)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	okResp, ok := resp.(GetGame200JSONResponse)
	if !ok {
		t.Fatalf("expected 200 response, got %T", resp)
	}
	if okResp.Game.GameID != 1 {
		t.Errorf("expected game ID 1, got %d", okResp.Game.GameID)
	}
	if len(okResp.Game.MainPlayers) != 1 {
		t.Fatalf("expected 1 main player, got %d", len(okResp.Game.MainPlayers))
	}
	if okResp.Game.MainPlayers[0].Username != "player1" {
		t.Errorf("expected username 'player1', got %q", okResp.Game.MainPlayers[0].Username)
	}
}

func TestPostLogin_AuthFailure(t *testing.T) {
	h := Handler{
		q:    &mockQuerier{},
		txm:  &mockTxManager{},
		hub:  &mockGameHub{},
		auth: &mockAuthenticator{loginErr: errors.New("invalid credentials")},
		conf: &config.Config{},
	}
	resp, err := h.PostLogin(context.Background(), PostLoginRequestObject{
		Body: &PostLoginJSONRequestBody{Username: "user", Password: "wrong"},
	})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if _, ok := resp.(PostLogin401JSONResponse); !ok {
		t.Errorf("expected 401 response, got %T", resp)
	}
}