send method
Sends an HTTP request and asynchronously returns the response.
Implementers should call BaseRequest.finalize to get the body of the
request as a ByteStream. They shouldn't make any assumptions about the
state of the stream; it could have data written to it asynchronously at a
later point, or it could already be closed when it's returned. Any
internal HTTP errors should be wrapped as ClientExceptions.
Implementation
@override
Future<http.StreamedResponse> send(http.BaseRequest request) async {
final body = request is http.Request ? request.body : null;
final headers = <String, String>{};
request.headers.forEach((k, v) => headers[k.toLowerCase()] = v);
final req = MockRequest(
method: request.method,
url: request.url,
headers: headers,
body: body,
);
history.add(req);
for (final h in _handlers.reversed) {
if (h.method != request.method.toUpperCase()) continue;
final matches = h.matcher is RegExp
? (h.matcher as RegExp).hasMatch(request.url.path)
: request.url.path == h.matcher;
if (!matches) continue;
final resp = await h.responder(req);
final bytes = resp.body == null
? <int>[]
: resp.body is String
? utf8.encode(resp.body! as String)
: utf8.encode(jsonEncode(resp.body));
return http.StreamedResponse(
Stream<List<int>>.fromIterable([bytes]),
resp.status,
headers: resp.headers,
contentLength: bytes.length,
);
}
final fallback = utf8.encode(
jsonEncode({
'error': {
'code': 'no_mock_handler',
'message': 'No handler matched ${request.method} ${request.url.path}',
},
}),
);
return http.StreamedResponse(
Stream<List<int>>.fromIterable([fallback]),
599,
headers: const {'content-type': 'application/json'},
contentLength: fallback.length,
);
}