Repository navigation
Expand file tree
/
Copy pathclose_test.dart
More file actions
72 lines (63 loc) · 2.19 KB
/
Copy pathclose_test.dart
File metadata and controls
72 lines (63 loc) · 2.19 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
import 'dart:async';
import 'package:cms/cms.dart';
import 'package:test/test.dart';
void main() {
/// close 取消 emitter 而非底层 Future:无需额外停止信号,迟到的 kernel 结果不会发出。
test(
'Closing completes before pending work and ignores its late state',
() async {
// dart format off
final operation = PendingOperation();
final cms = CloseProbe(operation);
addTearDown(() async {
operation.complete(42);
await cms.close();
});
final states = <int>[];
final subscription = cms.stream.listen(states.add);
addTearDown(subscription.cancel);
final streamClosed = expectLater(cms.stream, emitsDone);
cms.add(.execute);
await operation.started; expect(operation.isCompleted, isFalse);
await cms.close();
await streamClosed; expect(cms.isClosed, isTrue);
expect(operation.isCompleted, isFalse);
expect(states, isEmpty);
operation.complete(42);
await operation.finished;
await Future<void>.delayed(.zero); expect(operation.result, 42);
expect(cms.state, 0);
expect(states, isEmpty);
// dart format on
},
);
}
enum Action { execute }
class CloseProbe(final PendingOperation operation) extends Cms<int, Action> {
this : super(0);
// dart format off
@override
Future<int?> kernel(int s, Action a) => switch ((s, a)) {
(_, Action.execute) => operation.run(),
};
// dart format on
}
class PendingOperation {
final _started = Completer<void>();
final _pending = Completer<int>();
final _finished = Completer<void>();
int? result;
Future<void> get started => _started.future;
Future<void> get finished => _finished.future;
bool get isCompleted => _finished.isCompleted;
Future<int> run() async {
_started.complete();
final value = await _pending.future;
result = value;
_finished.complete();
return value;
}
void complete(int value) {
if (!_pending.isCompleted) _pending.complete(value);
}
}