-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_helpers.dart
More file actions
358 lines (299 loc) · 9.22 KB
/
test_helpers.dart
File metadata and controls
358 lines (299 loc) · 9.22 KB
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
/// E2E Test Helper Utilities
///
/// Provides reusable helper classes for end-to-end testing
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:test/test.dart';
/// Helper for managing daemon lifecycle in tests
class DaemonTestHelper {
Process? _daemonProcess;
String? _daemonPath;
bool _isRunning = false;
DaemonTestHelper({String? daemonPath})
: _daemonPath = daemonPath ?? '../daemon/bin/daemon.dart';
/// Start the daemon
Future<void> start({
String mode = 'personal',
Duration startupDelay = const Duration(seconds: 3),
}) async {
if (_isRunning) {
throw StateError('Daemon already running');
}
print('🚀 Starting daemon...');
_daemonProcess = await Process.start(
'dart',
['run', _daemonPath!, '--mode', mode],
runInShell: true,
);
// Listen to output for debugging
_daemonProcess!.stdout
.transform(utf8.decoder)
.listen((data) => print('📤 Daemon: $data'));
_daemonProcess!.stderr
.transform(utf8.decoder)
.listen((data) => print('❌ Daemon Error: $data'));
// Wait for daemon to start
await Future.delayed(startupDelay);
_isRunning = true;
print('✅ Daemon started');
}
/// Stop the daemon
Future<void> stop() async {
if (!_isRunning || _daemonProcess == null) {
return;
}
print('🛑 Stopping daemon...');
_daemonProcess!.kill(ProcessSignal.sigterm);
await _daemonProcess!.exitCode.timeout(
const Duration(seconds: 5),
onTimeout: () {
print('⚠️ Daemon did not stop gracefully, forcing kill');
_daemonProcess!.kill(ProcessSignal.sigkill);
return -1;
},
);
_isRunning = false;
_daemonProcess = null;
print('✅ Daemon stopped');
}
/// Check if daemon is responding on HTTP
Future<bool> isHealthy() async {
try {
final client = HttpClient();
final request = await client.get('localhost', 9875, '/health');
final response = await request.close();
client.close();
return response.statusCode == 200;
} catch (e) {
return false;
}
}
/// Force kill daemon (for crash testing)
void forceKill() {
if (_daemonProcess != null) {
print('💥 Force killing daemon');
_daemonProcess!.kill(ProcessSignal.sigkill);
_isRunning = false;
}
}
/// Wait until daemon is healthy
Future<void> waitUntilHealthy({
Duration timeout = const Duration(seconds: 30),
Duration pollInterval = const Duration(milliseconds: 500),
}) async {
final deadline = DateTime.now().add(timeout);
while (DateTime.now().isBefore(deadline)) {
if (await isHealthy()) {
print('✅ Daemon is healthy');
return;
}
await Future.delayed(pollInterval);
}
throw TimeoutException('Daemon did not become healthy within $timeout');
}
bool get isRunning => _isRunning;
}
/// Helper for WebSocket client testing
class WebSocketClientHelper {
WebSocketChannel? _channel;
final List<Map<String, dynamic>> _receivedMessages = [];
final String _host;
final int _port;
final String _path;
String? _clientId;
bool _isConnected = false;
StreamSubscription? _subscription;
WebSocketClientHelper({
String host = 'localhost',
int port = 9875,
String path = '/ws',
}) : _host = host,
_port = port,
_path = path;
/// Connect to WebSocket
Future<void> connect() async {
if (_isConnected) {
throw StateError('Already connected');
}
final url = 'ws://$_host:$_port$_path';
print('🔌 Connecting to $url...');
_channel = WebSocketChannel.connect(Uri.parse(url));
_subscription = _channel!.stream.listen(
(message) {
final data = jsonDecode(message as String) as Map<String, dynamic>;
_receivedMessages.add(data);
// Extract client ID from welcome message
if (data['type'] == 'notification' &&
data['payload']?['event'] == 'connected') {
_clientId = data['payload']['clientId'] as String?;
}
print('📨 Received: ${jsonEncode(data)}');
},
onError: (error) {
print('❌ WebSocket error: $error');
},
onDone: () {
print('🔌 WebSocket closed');
_isConnected = false;
},
);
_isConnected = true;
// Wait for welcome message
await waitForMessage(
(msg) => msg['type'] == 'notification' &&
msg['payload']?['event'] == 'connected',
timeout: const Duration(seconds: 5),
);
print('✅ Connected, client ID: $_clientId');
}
/// Disconnect from WebSocket
Future<void> disconnect() async {
await _subscription?.cancel();
await _channel?.sink.close();
_channel = null;
_subscription = null;
_isConnected = false;
print('✅ Disconnected');
}
/// Send a message
void send(Map<String, dynamic> message) {
if (!_isConnected) {
throw StateError('Not connected');
}
final json = jsonEncode(message);
_channel!.sink.add(json);
print('📤 Sent: $json');
}
/// Send raw data (for testing invalid JSON)
void sendRaw(String data) {
if (!_isConnected) {
throw StateError('Not connected');
}
_channel!.sink.add(data);
print('📤 Sent raw: $data');
}
/// Wait for a message matching predicate
Future<Map<String, dynamic>> waitForMessage(
bool Function(Map<String, dynamic>) predicate, {
Duration timeout = const Duration(seconds: 10),
}) async {
final deadline = DateTime.now().add(timeout);
while (DateTime.now().isBefore(deadline)) {
// Check existing messages
for (var msg in _receivedMessages) {
if (predicate(msg)) {
return msg;
}
}
// Wait a bit before checking again
await Future.delayed(const Duration(milliseconds: 100));
}
throw TimeoutException(
'Message not received within $timeout. '
'Received: ${_receivedMessages.length} messages'
);
}
/// Get all received messages
List<Map<String, dynamic>> get receivedMessages =>
List.unmodifiable(_receivedMessages);
/// Clear received messages
void clearMessages() => _receivedMessages.clear();
/// Check if connected
bool get isConnected => _isConnected;
/// Get client ID
String? get clientId => _clientId;
}
/// Helper for making assertions
class AssertionHelper {
/// Assert message has expected structure
static void assertMessageStructure(
Map<String, dynamic> message, {
String? expectedType,
Map<String, dynamic>? expectedPayload,
}) {
expect(message, isA<Map<String, dynamic>>());
if (expectedType != null) {
expect(message['type'], equals(expectedType));
}
if (expectedPayload != null) {
expect(message['payload'], isA<Map<String, dynamic>>());
expectedPayload.forEach((key, value) {
expect(message['payload'][key], equals(value));
});
}
}
/// Assert task progress notifications
static void assertTaskProgress(
List<Map<String, dynamic>> messages,
String taskId,
) {
final taskMessages = messages.where(
(msg) => msg['payload']?['taskId'] == taskId
).toList();
expect(taskMessages, isNotEmpty,
reason: 'Should have received task messages');
// Should have at least started and completed
final events = taskMessages
.map((m) => m['payload']?['event'] as String?)
.toList();
expect(events, contains('task_started'));
expect(events, contains('task_completed'));
}
/// Assert response is successful
static void assertSuccessResponse(Map<String, dynamic> message) {
expect(message['type'], equals('response'));
expect(message['payload']['status'], equals('success'));
}
/// Assert error response
static void assertErrorResponse(
Map<String, dynamic> message, {
String? expectedError,
}) {
expect(message['type'], equals('response'));
expect(message['payload']['status'], equals('error'));
if (expectedError != null) {
expect(message['payload']['error'], contains(expectedError));
}
}
}
/// Helper for performance measurements
class PerformanceHelper {
final Map<String, Stopwatch> _stopwatches = {};
/// Start timing an operation
void start(String operation) {
_stopwatches[operation] = Stopwatch()..start();
}
/// Stop timing and return duration
Duration stop(String operation) {
final stopwatch = _stopwatches[operation];
if (stopwatch == null) {
throw StateError('Timer for $operation not started');
}
stopwatch.stop();
final duration = stopwatch.elapsed;
print('⏱️ $operation took ${duration.inMilliseconds}ms');
return duration;
}
/// Assert operation completed within time limit
void assertWithinTime(
String operation,
Duration maxDuration,
) {
final duration = stop(operation);
expect(
duration,
lessThan(maxDuration),
reason: '$operation took ${duration.inMilliseconds}ms, '
'expected < ${maxDuration.inMilliseconds}ms',
);
}
/// Get all measurements
Map<String, Duration> get measurements =>
Map.fromEntries(
_stopwatches.entries.map(
(e) => MapEntry(e.key, e.value.elapsed)
)
);
}