fake_http_client.dart 13.2 KB
Newer Older
1 2 3 4 5 6 7 8 9
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
import 'dart:convert';

import 'dart:io';

10 11
import 'package:collection/collection.dart';

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 73
/// The HTTP verb for a [FakeRequest].
enum HttpMethod {
  get,
  put,
  delete,
  post,
  patch,
  head,
}

HttpMethod _fromMethodString(String value) {
  final String name = value.toLowerCase();
  switch (name) {
    case 'get':
      return HttpMethod.get;
    case 'put':
      return HttpMethod.put;
    case 'delete':
      return HttpMethod.delete;
    case 'post':
      return HttpMethod.post;
    case 'patch':
      return HttpMethod.patch;
    case 'head':
      return HttpMethod.head;
    default:
      throw StateError('Unrecognized HTTP method $value');
  }
}

String _toMethodString(HttpMethod method) {
  switch (method) {
    case HttpMethod.get:
      return 'GET';
    case HttpMethod.put:
      return 'PUT';
    case HttpMethod.delete:
      return 'DELETE';
    case HttpMethod.post:
      return 'POST';
    case HttpMethod.patch:
      return 'PATCH';
    case HttpMethod.head:
      return 'HEAD';
  }
}

/// Override the creation of all [HttpClient] objects with a zone injection.
///
/// This should only be used when the http client cannot be set directly, such as
/// when testing `package:http` code.
Future<void> overrideHttpClients(Future<void> Function() callback,  FakeHttpClient httpClient) async {
  final HttpOverrides overrides = _FakeHttpClientOverrides(httpClient);
  await HttpOverrides.runWithHttpOverrides(callback, overrides);
}

class _FakeHttpClientOverrides extends HttpOverrides {
  _FakeHttpClientOverrides(this.httpClient);

  final FakeHttpClient httpClient;

  @override
74
  HttpClient createHttpClient(SecurityContext? context) {
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
    return httpClient;
  }
}

/// Create a fake request that configures the [FakeHttpClient] to respond
/// with the provided [response].
///
/// By default, returns a response with a 200 OK status code and an
/// empty response. If [responseError] is non-null, will throw this instead
/// of returning the response when closing the request.
class FakeRequest {
  const FakeRequest(this.uri, {
    this.method = HttpMethod.get,
    this.response = FakeResponse.empty,
    this.responseError,
90
    this.body,
91 92 93 94 95
  });

  final Uri uri;
  final HttpMethod method;
  final FakeResponse response;
96
  final Object? responseError;
97
  final List<int>? body;
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138

  @override
  String toString() => 'Request{${_toMethodString(method)}, $uri}';
}

/// The response the server will create for a given [FakeRequest].
class FakeResponse {
  const FakeResponse({
    this.statusCode = HttpStatus.ok,
    this.body = const <int>[],
    this.headers = const <String, List<String>>{},
  });

  static const FakeResponse empty = FakeResponse();

  final int statusCode;
  final List<int> body;
  final Map<String, List<String>> headers;
}

/// A fake implementation of the HttpClient used for testing.
///
/// This does not fully implement the HttpClient. If an additional method
/// is actually needed by the test script, then it should be added here
/// instead of in another fake.
class FakeHttpClient implements HttpClient {
  /// Creates an HTTP client that responses to each provided
  /// fake request with the provided fake response.
  ///
  /// This does not enforce any order on the requests, but if multiple
  /// requests match then the first will be selected;
  FakeHttpClient.list(List<FakeRequest> requests)
    : _requests = requests.toList();

  /// Creates an HTTP client that always returns an empty 200 request.
  FakeHttpClient.any() : _any = true, _requests = <FakeRequest>[];

  bool _any = false;
  final List<FakeRequest> _requests;

  @override
139
  bool autoUncompress = true;
140 141

  @override
142
  Duration? connectionTimeout;
143 144

  @override
145
  Duration idleTimeout = Duration.zero;
146 147

  @override
148
  int? maxConnectionsPerHost;
149 150

  @override
151
  String? userAgent;
152 153 154 155 156 157 158 159 160 161 162 163

  @override
  void addCredentials(Uri url, String realm, HttpClientCredentials credentials) {
    throw UnimplementedError();
  }

  @override
  void addProxyCredentials(String host, int port, String realm, HttpClientCredentials credentials) {
    throw UnimplementedError();
  }

  @override
164
  Future<bool> Function(Uri url, String scheme, String realm)? authenticate;
165 166

  @override
167
  Future<bool> Function(String host, int port, String scheme, String realm)? authenticateProxy;
168 169

  @override
170
  bool Function(X509Certificate cert, String host, int port)? badCertificateCallback;
171 172 173 174 175 176 177 178 179 180 181 182

  @override
  void close({bool force = false}) { }

  @override
  Future<HttpClientRequest> delete(String host, int port, String path) {
    final Uri uri = Uri(host: host, port: port, path: path);
    return deleteUrl(uri);
  }

  @override
  Future<HttpClientRequest> deleteUrl(Uri url) async {
183
    return _findRequest(HttpMethod.delete, url, StackTrace.current);
184 185 186
  }

  @override
187
  String Function(Uri url)? findProxy;
188 189 190 191 192 193 194 195 196

  @override
  Future<HttpClientRequest> get(String host, int port, String path) {
    final Uri uri = Uri(host: host, port: port, path: path);
    return getUrl(uri);
  }

  @override
  Future<HttpClientRequest> getUrl(Uri url) async {
197
    return _findRequest(HttpMethod.get, url, StackTrace.current);
198 199 200 201 202 203 204 205 206 207
  }

  @override
  Future<HttpClientRequest> head(String host, int port, String path) {
    final Uri uri = Uri(host: host, port: port, path: path);
    return headUrl(uri);
  }

  @override
  Future<HttpClientRequest> headUrl(Uri url) async {
208
    return _findRequest(HttpMethod.head, url, StackTrace.current);
209 210 211 212 213 214 215 216 217 218
  }

  @override
  Future<HttpClientRequest> open(String method, String host, int port, String path) {
    final Uri uri = Uri(host: host, port: port, path: path);
    return openUrl(method, uri);
  }

  @override
  Future<HttpClientRequest> openUrl(String method, Uri url) async {
219
    return _findRequest(_fromMethodString(method), url, StackTrace.current);
220 221 222 223 224 225 226 227 228 229
  }

  @override
  Future<HttpClientRequest> patch(String host, int port, String path) {
    final Uri uri = Uri(host: host, port: port, path: path);
    return patchUrl(uri);
  }

  @override
  Future<HttpClientRequest> patchUrl(Uri url) async {
230
    return _findRequest(HttpMethod.patch, url, StackTrace.current);
231 232 233 234 235 236 237 238 239 240
  }

  @override
  Future<HttpClientRequest> post(String host, int port, String path) {
    final Uri uri = Uri(host: host, port: port, path: path);
    return postUrl(uri);
  }

  @override
  Future<HttpClientRequest> postUrl(Uri url) async {
241
    return _findRequest(HttpMethod.post, url, StackTrace.current);
242 243 244 245 246 247 248 249 250 251
  }

  @override
  Future<HttpClientRequest> put(String host, int port, String path) {
    final Uri uri = Uri(host: host, port: port, path: path);
    return putUrl(uri);
  }

  @override
  Future<HttpClientRequest> putUrl(Uri url) async {
252
    return _findRequest(HttpMethod.put, url, StackTrace.current);
253 254 255 256
  }

  int _requestCount = 0;

257
  _FakeHttpClientRequest _findRequest(HttpMethod method, Uri uri, StackTrace stackTrace) {
258 259 260 261 262 263
    // Ensure the fake client throws similar errors to the real client.
    if (uri.host.isEmpty) {
      throw ArgumentError('No host specified in URI $uri');
    } else if (uri.scheme != 'http' && uri.scheme != 'https') {
      throw ArgumentError("Unsupported scheme '${uri.scheme}' in URI $uri");
    }
264 265 266 267 268 269 270
    final String methodString = _toMethodString(method);
    if (_any) {
      return _FakeHttpClientRequest(
        FakeResponse.empty,
        uri,
        methodString,
        null,
271 272
        null,
        stackTrace,
273 274
      );
    }
275
    FakeRequest? matchedRequest;
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
    for (final FakeRequest request in _requests) {
      if (request.method == method && request.uri.toString() == uri.toString()) {
        matchedRequest = request;
        break;
      }
    }
    if (matchedRequest == null) {
      throw StateError(
        'Unexpected request for $method to $uri after $_requestCount requests.\n'
        'Pending requests: ${_requests.join(',')}'
      );
    }
    _requestCount += 1;
    _requests.remove(matchedRequest);
    return _FakeHttpClientRequest(
      matchedRequest.response,
      uri,
      methodString,
      matchedRequest.responseError,
295 296
      matchedRequest.body,
      stackTrace,
297 298 299 300 301
    );
  }
}

class _FakeHttpClientRequest implements HttpClientRequest {
302
  _FakeHttpClientRequest(this._response, this._uri, this._method, this._responseError, this._expectedBody, this._stackTrace);
303 304 305 306

  final FakeResponse _response;
  final String _method;
  final Uri _uri;
307
  final Object? _responseError;
308 309 310
  final List<int> _body = <int>[];
  final List<int>? _expectedBody;
  final StackTrace _stackTrace;
311 312

  @override
313
  bool bufferOutput = true;
314 315 316 317 318

  @override
  int contentLength = 0;

  @override
319
  late Encoding encoding;
320 321

  @override
322
  bool followRedirects = true;
323 324

  @override
325
  int maxRedirects = 5;
326 327

  @override
328
  bool persistentConnection = true;
329 330

  @override
331
  void abort([Object? exception, StackTrace? stackTrace]) {
332 333 334 335
    throw UnimplementedError();
  }

  @override
336 337 338
  void add(List<int> data) {
    _body.addAll(data);
  }
339 340

  @override
341
  void addError(Object error, [StackTrace? stackTrace]) { }
342 343

  @override
344 345 346 347 348
  Future<void> addStream(Stream<List<int>> stream) async {
    final Completer<void> completer = Completer<void>();
    stream.listen(_body.addAll, onDone: completer.complete);
    await completer.future;
  }
349 350 351

  @override
  Future<HttpClientResponse> close() async {
352 353 354 355 356 357 358 359 360 361 362
    final Completer<void> completer = Completer<void>();
    Timer.run(() {
      if (_expectedBody != null && !const ListEquality<int>().equals(_expectedBody, _body)) {
        completer.completeError(StateError(
          'Expected a request with the following body:\n$_expectedBody\n but found:\n$_body'
        ), _stackTrace);
      } else {
        completer.complete();
      }
    });
    await completer.future;
363
    if (_responseError != null) {
364
      return Future<HttpClientResponse>.error(_responseError!);
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
    }
    return _FakeHttpClientResponse(_response);
  }

  @override
  HttpConnectionInfo get connectionInfo => throw UnimplementedError();

  @override
  List<Cookie> get cookies => throw UnimplementedError();

  @override
  Future<HttpClientResponse> get done => throw UnimplementedError();

  @override
  Future<void> flush() async { }

  @override
  final HttpHeaders headers = _FakeHttpHeaders(<String, List<String>>{});

  @override
  String get method => _method;

  @override
  Uri get uri => _uri;

  @override
391 392 393
  void write(Object? object) {
    _body.addAll(utf8.encode(object.toString()));
  }
394 395

  @override
396 397 398
  void writeAll(Iterable<dynamic> objects, [String separator = '']) {
    _body.addAll(utf8.encode(objects.join(separator)));
  }
399 400

  @override
401 402 403
  void writeCharCode(int charCode) {
    _body.add(charCode);
  }
404 405

  @override
406
  void writeln([Object? object = '']) {
407
    _body.addAll(utf8.encode('$object\n'));
408
  }
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
}

class _FakeHttpClientResponse extends Stream<List<int>> implements HttpClientResponse {
  _FakeHttpClientResponse(this._response)
      : headers = _FakeHttpHeaders(Map<String, List<String>>.from(_response.headers));

  final FakeResponse _response;

  @override
  X509Certificate get certificate => throw UnimplementedError();

  @override
  HttpClientResponseCompressionState get compressionState => throw UnimplementedError();

  @override
  HttpConnectionInfo get connectionInfo => throw UnimplementedError();

  @override
  int get contentLength => _response.body.length;

  @override
  List<Cookie> get cookies => throw UnimplementedError();

  @override
  Future<Socket> detachSocket() {
    throw UnimplementedError();
  }

  @override
  final HttpHeaders headers;

  @override
  bool get isRedirect => throw UnimplementedError();

  @override
  StreamSubscription<List<int>> listen(
445 446 447 448
    void Function(List<int> event)? onData, {
    Function? onError,
    void Function()? onDone,
    bool? cancelOnError,
449 450 451 452 453 454 455 456 457 458 459 460 461 462
  }) {
    final Stream<List<int>> response = Stream<List<int>>.fromIterable(<List<int>>[
      _response.body,
    ]);
    return response.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError);
  }

  @override
  bool get persistentConnection => throw UnimplementedError();

  @override
  String get reasonPhrase => 'OK';

  @override
463
  Future<HttpClientResponse> redirect([String? method, Uri? url, bool? followLoops]) {
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
    throw UnimplementedError();
  }

  @override
  List<RedirectInfo> get redirects => throw UnimplementedError();

  @override
  int get statusCode => _response.statusCode;
}

class _FakeHttpHeaders extends HttpHeaders {
  _FakeHttpHeaders(this._backingData);

  final Map<String, List<String>> _backingData;

  @override
480
  List<String>? operator [](String name) => _backingData[name];
481 482 483 484

  @override
  void add(String name, Object value, {bool preserveHeaderCase = false}) {
    _backingData[name] ??= <String>[];
485
    _backingData[name]!.add(value.toString());
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
  }

  @override
  void clear() {
    _backingData.clear();
  }

  @override
  void forEach(void Function(String name, List<String> values) action) { }

  @override
  void noFolding(String name) {  }

  @override
  void remove(String name, Object value) {
    _backingData[name]?.remove(value.toString());
  }

  @override
  void removeAll(String name) {
    _backingData.remove(name);
  }

  @override
  void set(String name, Object value, {bool preserveHeaderCase = false}) {
    _backingData[name] = <String>[value.toString()];
  }

  @override
515
  String? value(String name) {
516 517 518
    return _backingData[name]?.join('; ');
  }
}