request method

Future<TestResponse> request(
  1. String method,
  2. String path, {
  3. Object? json,
  4. Map<String, String>? form,
  5. Object? body,
  6. String? contentType,
  7. Map<String, Object?>? query,
  8. Map<String, String>? headers,
})

Sends one request. Give at most one body: json (encoded, with application/json), form (url-encoded), or a raw body (String or bytes) with its contentType. query values may be lists for repeated keys.

Implementation

Future<TestResponse> request(
  String method,
  String path, {
  Object? json,
  Map<String, String>? form,
  Object? body,
  String? contentType,
  Map<String, Object?>? query,
  Map<String, String>? headers,
}) async {
  if ([json, form, body].whereType<Object>().length > 1) {
    throw ArgumentError('Give at most one of json, form and body.');
  }
  final Object? payload;
  String? type = contentType;
  if (json != null) {
    payload = jsonEncode(json);
    type ??= 'application/json';
  } else if (form != null) {
    payload = Uri(queryParameters: form).query;
    type ??= 'application/x-www-form-urlencoded';
  } else {
    payload = body;
  }

  final res = await _handler(Request(
    method,
    _uri(path, query),
    headers: {
      ...this.headers,
      if (type != null) 'content-type': type,
      ..._lower(headers ?? const {}),
    },
    body: payload,
  ));
  final bytes = <int>[];
  await for (final chunk in res.read()) {
    bytes.addAll(chunk);
  }
  return TestResponse._(res.statusCode, res.headers, bytes);
}