Provide trace in single transformer (#1607)

This commit is contained in:
Simon Binder 2021-12-29 11:26:50 +01:00
parent 70e83b5a74
commit bce13f150f
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
2 changed files with 25 additions and 11 deletions

View File

@ -4,16 +4,17 @@ import 'dart:async';
/// that each list is a singleton or empty. /// that each list is a singleton or empty.
StreamTransformer<List<T>, T?> singleElementsOrNull<T>() { StreamTransformer<List<T>, T?> singleElementsOrNull<T>() {
return StreamTransformer.fromHandlers(handleData: (data, sink) { return StreamTransformer.fromHandlers(handleData: (data, sink) {
T? result;
try { try {
if (data.isEmpty) { if (data.isNotEmpty) {
sink.add(null); result = data.single;
} else {
sink.add(data.single);
} }
} catch (e) { } catch (e) {
sink.addError( throw StateError('Expected exactly one element, but got ${data.length}');
StateError('Expected exactly one element, but got ${data.length}'));
} }
sink.add(result);
}); });
} }
@ -21,11 +22,14 @@ StreamTransformer<List<T>, T?> singleElementsOrNull<T>() {
/// that each list is a singleton. /// that each list is a singleton.
StreamTransformer<List<T>, T> singleElements<T>() { StreamTransformer<List<T>, T> singleElements<T>() {
return StreamTransformer.fromHandlers(handleData: (data, sink) { return StreamTransformer.fromHandlers(handleData: (data, sink) {
T single;
try { try {
sink.add(data.single); single = data.single;
} catch (e) { } catch (e) {
sink.addError( throw StateError('Expected exactly one element, but got ${data.length}');
StateError('Expected exactly one element, but got ${data.length}'));
} }
sink.add(single);
}); });
} }

View File

@ -22,8 +22,15 @@ void main() {
final controller = StreamController<List<int>>(); final controller = StreamController<List<int>>();
final stream = controller.stream.transform(singleElements()); final stream = controller.stream.transform(singleElements());
expectLater(stream, expectLater(
emitsInOrder([1, emitsError(anything), 2, emitsError(anything)])); stream,
emitsInOrder([
1,
emitsError(_stateErrorWithTrace),
2,
emitsError(_stateErrorWithTrace)
]),
);
controller controller
..add([1]) ..add([1])
@ -38,3 +45,6 @@ void main() {
expect(stream.transform(singleElementsOrNull()), emits(isNull)); expect(stream.transform(singleElementsOrNull()), emits(isNull));
}); });
} }
Matcher _stateErrorWithTrace =
isStateError.having((e) => e.stackTrace, 'stackTrace', isNotNull);