Skip to content

Commit 7fe8048

Browse files
PIG208gnprice
authored andcommitted
fake_api: Support preparing a queue of responses.
An issue that exists prior to this change is that there can be unused prepared responses when the test ends, but we don't have a way to detect that. We can potentially do something like what testWidgets does with pending timers. Signed-off-by: Zixuan James Li <[email protected]>
1 parent d458496 commit 7fe8048

File tree

1 file changed

+10
-11
lines changed

1 file changed

+10
-11
lines changed

test/api/fake_api.dart

+10-11
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import 'dart:collection';
12
import 'dart:convert';
23

34
import 'package:flutter/foundation.dart';
@@ -38,10 +39,9 @@ class FakeHttpClient extends http.BaseClient {
3839
return result;
3940
}
4041

41-
_PreparedResponse? _nextResponse;
42+
final Queue<_PreparedResponse> _preparedResponses = Queue();
4243

43-
// Please add more features to this mocking API as needed. For example:
44-
// * preparing more than one request, and logging more than one request
44+
// Please add more features to this mocking API as needed.
4545

4646
/// Prepare the response for the next request.
4747
///
@@ -59,31 +59,31 @@ class FakeHttpClient extends http.BaseClient {
5959
String? body,
6060
Duration delay = Duration.zero,
6161
}) {
62-
assert(_nextResponse == null,
63-
'FakeApiConnection.prepare was called while already expecting a request');
62+
// TODO: Prevent a source of bugs by ensuring that there are no outstanding
63+
// prepared responses when the test ends.
6464
if (exception != null) {
6565
assert(httpStatus == null && json == null && body == null);
66-
_nextResponse = _PreparedException(exception: exception, delay: delay);
66+
_preparedResponses.addLast(_PreparedException(exception: exception, delay: delay));
6767
} else {
6868
assert((json == null) || (body == null));
6969
final String resolvedBody = switch ((body, json)) {
7070
(var body?, _) => body,
7171
(_, var json?) => jsonEncode(json),
7272
_ => '',
7373
};
74-
_nextResponse = _PreparedSuccess(
74+
_preparedResponses.addLast(_PreparedSuccess(
7575
httpStatus: httpStatus ?? 200,
7676
bytes: utf8.encode(resolvedBody),
7777
delay: delay,
78-
);
78+
));
7979
}
8080
}
8181

8282
@override
8383
Future<http.StreamedResponse> send(http.BaseRequest request) {
8484
_requestHistory.add(request);
8585

86-
if (_nextResponse == null) {
86+
if (_preparedResponses.isEmpty) {
8787
throw FlutterError.fromParts([
8888
ErrorSummary(
8989
'An API request was attempted in a test when no response was prepared.'),
@@ -92,8 +92,7 @@ class FakeHttpClient extends http.BaseClient {
9292
'call to [FakeApiConnection.prepare].'),
9393
]);
9494
}
95-
final response = _nextResponse!;
96-
_nextResponse = null;
95+
final response = _preparedResponses.removeFirst();
9796

9897
final http.StreamedResponse Function() computation;
9998
switch (response) {

0 commit comments

Comments
 (0)