summaryrefslogtreecommitdiff
path: root/server/test/net/app_test.dart
blob: 4a02c1599d3a7b7e2cdfe2d1d83fd451de2b55a9 (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
/// Phase 2: HTTP endpoints (healthz, session, static) and the WS protocol
/// basics — handshake, version check, ping/pong, error responses.
library;

import 'dart:convert';
import 'dart:io';

import 'package:test/test.dart';
import 'package:x_haven_server/net/protocol.dart';
import 'package:x_haven_server/net/sessions.dart';

import 'ws_test_helpers.dart';

void main() {
  late TestGameServer server;

  setUp(() async {
    server = await TestGameServer.boot();
  });

  tearDown(() async {
    await server.shutdown();
  });

  Future<String> httpGet(Uri url, {Map<String, String> headers = const {}}) async {
    final client = HttpClient();
    addTearDown(client.close);
    final request = await client.getUrl(url);
    headers.forEach(request.headers.set);
    final response = await request.close();
    final body = await response.transform(utf8.decoder).join();
    return body;
  }

  test('serves a stub page at / when the static dir is missing', () async {
    final body = await httpGet(server.httpUrl.replace(path: '/'));
    expect(body, contains('X-Haven server'));
  });

  test('answers healthz', () async {
    final body = await httpGet(server.httpUrl.replace(path: '/healthz'));
    expect(jsonDecode(body), {'status': 'ok'});
  });

  test('session endpoint mints a session and sets the cookie', () async {
    final client = HttpClient();
    addTearDown(client.close);
    final request = await client.getUrl(server.httpUrl.replace(path: '/session'));
    final response = await request.close();
    expect(response.statusCode, 200);
    final setCookie = response.headers.value('set-cookie');
    expect(setCookie, isNotNull);
    expect(setCookie, startsWith('x-haven-session='));
    final id = setCookie!.substring('x-haven-session='.length).split(';').first;
    expect(SessionManager.isKnownFormat(id), isTrue);
    expect(
      jsonDecode(await response.transform(utf8.decoder).join()),
      {'session': id},
    );

    // Same cookie in → same session out, no new cookie.
    final request2 = await client.getUrl(
      server.httpUrl.replace(path: '/session'),
    );
    request2.headers.set('Cookie', 'x-haven-session=$id');
    final response2 = await request2.close();
    expect(response2.headers.value('set-cookie'), isNull);
    expect(
      jsonDecode(await response2.transform(utf8.decoder).join()),
      {'session': id},
    );
  });

  test('answers hello with a welcome carrying the real state', () async {
    final client = await TestClient.connect(server.wsUrl);
    client.sendHello();
    final welcome = await client.nextOf('welcome');

    expect(welcome['v'], Protocol.version);
    expect(welcome['session'], isA<String>());
    expect(SessionManager.isKnownFormat(welcome['session'] as String), isTrue);
    expect(welcome['role'], Protocol.roleSpectator);
    expect(welcome['index'], -1, reason: 'no actions executed yet');
    expect(welcome['description'], isNull);
    final state = welcome['state'] as Map<String, dynamic>;
    expect(state['roundState'], 0, reason: 'chooseInitiative');
    expect(state['currentList'], isEmpty);
    expect(welcome['seats'], isEmpty);
  });

  test('a re-sent hello re-answers with a fresh welcome', () async {
    final client = await TestClient.connect(server.wsUrl);
    client.sendHello();
    await client.nextOf('welcome');
    client.sendHello();
    expect((await client.nextOf('welcome'))['t'], 'welcome');
  });

  test('answers ping with pong', () async {
    final client = await TestClient.connect(server.wsUrl);
    client.send({'t': 'ping'});
    expect(await client.next(), {'t': 'pong'});
  });

  test('rejects messages sent before hello with badRequest', () async {
    final client = await TestClient.connect(server.wsUrl);
    client.send(Protocol.commandMessage('draw'));
    final error = await client.nextOf('error');
    expect(error['code'], Protocol.errBadRequest);
    expect(error['message'], 'send hello first');
  });

  test('rejects a protocol version mismatch and closes the connection',
      () async {
    final client = await TestClient.connect(server.wsUrl);
    client.send({'t': 'hello', 'v': 999});
    final error = await client.nextOf('error');
    expect(error['code'], Protocol.errProtocol);
    expect(error['message'], contains('version mismatch'));
    await client.closedFuture.timeout(
      const Duration(seconds: 5),
      onTimeout: () => fail('the connection was not closed'),
    );
    expect(client.closed, isTrue, reason: 'the connection is closed');
  });

  test('rejects malformed and unknown messages with error', () async {
    final client = await TestClient.connect(server.wsUrl);
    client.sendHello();
    await client.nextOf('welcome');

    client.sendRaw('this is not json');
    expect((await client.nextOf('error'))['code'], Protocol.errBadRequest);

    client.send({'t': 'warpSpeed'});
    final error = await client.nextOf('error');
    expect(error['code'], Protocol.errUnknownMessage);
    expect(error['message'], contains('warpSpeed'));
  });
}