moxlib/test/awaitabledatasender_test.dart

70 lines
2.0 KiB
Dart
Raw Permalink Normal View History

import 'package:moxlib/moxlib.dart';
2023-06-17 19:14:17 +00:00
import 'package:test/test.dart';
2022-04-27 19:49:36 +00:00
class TestDataType implements JsonImplementation {
TestDataType(this.data);
2023-06-17 19:14:17 +00:00
factory TestDataType.fromJson(Map<String, dynamic> json) =>
TestDataType(json['data']! as String);
final String data;
2022-04-27 19:49:36 +00:00
2023-06-17 19:14:17 +00:00
@override
Map<String, dynamic> toJson() => {'data': data};
2022-04-27 19:49:36 +00:00
}
2023-06-17 19:14:17 +00:00
class FakeAwaitableDataSender<S extends JsonImplementation,
R extends JsonImplementation> extends AwaitableDataSender<S, R> {
FakeAwaitableDataSender({this.onAddFunc}) : super();
2022-04-27 19:49:36 +00:00
2023-06-17 19:14:17 +00:00
final void Function()? onAddFunc;
2022-04-27 19:49:36 +00:00
@override
Future<void> sendDataImpl(DataWrapper data) async {}
@override
void onAdd() {
onAddFunc?.call();
}
}
void main() {
2023-06-17 19:14:17 +00:00
test('Sending an event without awaiting it', () async {
final handler = FakeAwaitableDataSender<TestDataType, TestDataType>();
final result =
await handler.sendData(TestDataType('hallo'), awaitable: false);
2022-04-27 19:49:36 +00:00
2023-06-17 19:14:17 +00:00
expect(result, null);
expect(handler.getAwaitables().length, 0);
2022-04-27 19:49:36 +00:00
});
2023-06-17 19:14:17 +00:00
test('Sending an event without awaiting it', () async {
final handler = FakeAwaitableDataSender<TestDataType, TestDataType>();
const id = 'abc123';
final result =
handler.sendData(TestDataType('hallo'), awaitable: true, id: id);
await handler.onData(DataWrapper(id, TestDataType('welt')));
2022-04-27 19:49:36 +00:00
2023-06-17 19:14:17 +00:00
expect((await result)!.data, 'welt');
expect(handler.getAwaitables().length, 0);
2022-04-27 19:49:36 +00:00
});
2023-06-17 19:14:17 +00:00
test('Queue multiple data packets and resolve in reverse order', () async {
var i = 0;
final handler = FakeAwaitableDataSender<TestDataType, TestDataType>(
onAddFunc: () {
i++;
expect(i <= 2, true);
},
);
final a = handler.sendData(TestDataType('1'), id: '1');
final b = handler.sendData(TestDataType('2'), id: '2');
await handler.onData(DataWrapper('2', TestDataType('4')));
await handler.onData(DataWrapper('1', TestDataType('1')));
expect((await a)!.data, '1');
expect((await b)!.data, '4');
2022-04-27 19:49:36 +00:00
});
}