샘플
http 1.6.0: Test code that calls an HTTP API with package:http using MockClient, with no network, and see what the client actually sends and decodes
검증된 샘플 — pub http 1.6.0: Test code that calls an HTTP API with package:http using MockClient, with no network, and see what the client actually sends and…
sha256:ed3c594714b9ed323ec4da016bdf6f9e47b615cc78872cab62588dd0532e98b7
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 2
- 빌드한 서명 키
- 2
선언된 환경
dart 3 linux x64 dart 3 dart pub
검증 실행 환경
| 환경 | 컨트랙트 | 단계 | 실행일 |
|---|---|---|---|
| dart 3 · linux alpine/x64 · docker ed25519:a2ec939a4c60e243 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · pub@1 |
2026-08-14 |
| dart 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · pub@1 |
2026-08-18 |
케이스
HOW- 목표
- Test code that calls an HTTP API with package:http using MockClient, with no network, and see what the client actually sends and decodes
- 패키지
- 심벌
-
- MockClient
- Client.get
- Client.post
- Client.read
- Response.body
- Response.bodyBytes
- Request.bodyFields
- MultipartRequest
- ClientException
- 환경
- dart 3
- 생성일
- 2026-08-14T09:40:43Z
컨트랙트
- assert the MockClient handler receives the finalized request the client built, with its url and query, headers that look up case-insensitively but keep the case you wrote, and an empty GET body
- assert the handler argument is a rebuilt plain Request rather than your object, so a MultipartRequest arrives flattened to its encoded body and boundary header, and the request you sent comes back finalized
- assert a 404 does not throw from get: the Future completes, the error body decodes like any payload, and only statusCode and reasonPhrase report it
- assert read and readBytes are the exception and throw a ClientException at status 400 and above, with the server's error body no longer reachable, while 399 is read back as a body
- assert response.body decodes application/json without a charset as utf8 but falls back to latin1 for text/plain, text/html, application/xml, a vendor +json subtype and a missing content-type, while bodyBytes stays raw
- assert a Map body is form-encoded as application/x-www-form-urlencoded with percent-encoded utf8 and no charset parameter appended
- assert a declared JSON content-type stays exactly application/json with utf8 bytes on the wire, while an undeclared String body is announced as text/plain; charset=utf-8 and a declared application/xml gains charset=utf-8
- assert passing a Map under a JSON content-type throws StateError from Request.bodyFields instead of silently mis-encoding
- assert a ClientException thrown by the handler propagates unwrapped with its message and uri, and any other exception type propagates with its own type
파일
- csx.json
- lib/users.dart
- pubspec.lock
- pubspec.yaml
- test/contract_test.dart
소스
{"case":{"caseId":"case:sha256:72b8a784a4a75811976db0ae9c855ab2f7ad3e2b0a9e7c2069d8fee33a2b2e27","constraints":{"runtime":"dart"},"contract":["assert the MockClient handler receives the finalized request the client built, with its url and query, headers that look up case-insensitively but keep the case you wrote, and an empty GET body","assert the handler argument is a rebuilt plain Request rather than your object, so a MultipartRequest arrives flattened to its encoded body and boundary header, and the request you sent comes back finalized","assert a 404 does not throw from get: the Future completes, the error body decodes like any payload, and only statusCode and reasonPhrase report it","assert read and readBytes are the exception and throw a ClientException at status 400 and above, with the server's error body no longer reachable, while 399 is read back as a body","assert response.body decodes application/json without a charset as utf8 but falls back to latin1 for text/plain, text/html, application/xml, a vendor +json subtype and a missing content-type, while bodyBytes stays raw","assert a Map body is form-encoded as application/x-www-form-urlencoded with percent-encoded utf8 and no charset parameter appended","assert a declared JSON content-type stays exactly application/json with utf8 bytes on the wire, while an undeclared String body is announced as text/plain; charset=utf-8 and a declared application/xml gains charset=utf-8","assert passing a Map under a JSON content-type throws StateError from Request.bodyFields instead of silently mis-encoding","assert a ClientException thrown by the handler propagates unwrapped with its message and uri, and any other exception type propagates with its own type"],"goal":"Test code that calls an HTTP API with package:http using MockClient, with no network, and see what the client actually sends and decodes","kind":"HOW","packages":["pkg:pub/http@1.6.0"],"schemaVersion":1,"symbols":["MockClient","Client.get","Client.post","Client.read","Response.body","Response.bodyBytes","Request.bodyFields","MultipartRequest","ClientException"]},"contractCommand":["dart","test","--reporter=expanded"],"environment":{"arch":"x64","ecosystem":"pub","executionContext":"dart","language":"dart","os":"linux","packageManager":"pub","runtime":"dart","runtimeVersion":"3","schemaVersion":1},"license":"MIT-0","packages":["pkg:pub/http@1.6.0"],"schemaVersion":1,"symbols":["MockClient","Client.get","Client.post","Client.read","Response.body","Response.bodyBytes","Request.bodyFields","MultipartRequest","ClientException"],"verifierAdapter":"pub@1"}
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
/// Testing HTTP code with package:http and no network, plus the defaults that
/// make people misread what their code is actually sending and receiving.
///
/// MockClient takes a plain function from Request to Response, so nothing is
/// stubbed or monkeypatched. What the handler receives is not your object:
/// MockClient finalizes whatever BaseRequest the client produced and rebuilds
/// it as a plain Request carrying the same method, url, headers and bytes.
/// Assert on that copy rather than on your own call arguments and the client is
/// under test too. The flattening is total — a MultipartRequest arrives as a
/// plain Request, so casting the handler argument back to MultipartRequest to
/// read .fields fails. The one thing you must do to get here is inject the
/// Client instead of constructing one inside the function.
///
/// Four traps, all of them silent:
///
/// 1. A 4xx or 5xx is not an error. get, post and send return the Response and
/// only response.statusCode tells you, which is the opposite of package:dio,
/// so code ported from dio — or from any language whose client throws —
/// parses an error page as data and reports success. read and readBytes are
/// the exception: they are the only members that check, and they throw
/// ClientException for any status at or above 400. Everything else hands
/// back the response whatever it says.
///
/// 2. response.body is bodyBytes decoded with the charset from the response
/// content-type, and the fallback when no charset is given is latin1, NOT
/// utf8 — with one exception that is easy to generalise from and get wrong.
/// The special case is the exact type application/json, decoded as utf8
/// because RFC 8259 defines JSON as UTF-8. text/plain, text/html,
/// application/xml, a vendor subtype like application/vnd.api+json, and a
/// response with no content-type at all all fall back to latin1, so UTF-8
/// text arrives as mojibake through .body. bodyBytes never guesses, which
/// makes utf8.decode(response.bodyBytes) the read that always means what you
/// wrote.
///
/// 3. post(body: someMap) is form-encoded. A Map is assigned to
/// Request.bodyFields, which forces application/x-www-form-urlencoded and
/// throws a StateError if you declared any other content-type. JSON is
/// jsonEncode plus the header, by hand. A String body with no header at all
/// is announced as text/plain; charset=utf-8, which is how a correct JSON
/// payload earns a 415.
///
/// 4. ClientException is the transport failure a real client raises, and it is
/// the one thing worth catching around an http call. A MockClient handler is
/// not wrapped at all: whatever it throws reaches the caller with its own
/// type, which is how you test the socket-died path, and also why a broken
/// fixture surfaces as itself rather than as a network error.
/// The code under test. The Client is a parameter, which is the whole trick.
Future<http.Response> fetchUser(http.Client client, String id) => client.get(
Uri.parse('https://api.example.com/users/$id?verbose=true'),
headers: {'Authorization': 'Bearer t0ken'},
);
/// The same call through read, the one member that does check the status.
Future<String> readUserBody(http.Client client, String id) => client.read(
Uri.parse('https://api.example.com/users/$id?verbose=true'),
headers: {'Authorization': 'Bearer t0ken'},
);
/// What people write when they mean JSON. It is a form post.
Future<http.Response> createUserWithMapBody(
http.Client client,
Map<String, String> fields,
) =>
client.post(Uri.parse('https://api.example.com/users'), body: fields);
/// JSON, spelled out: encode the payload and declare the type.
Future<http.Response> createUserAsJson(
http.Client client,
Map<String, Object?> payload,
) =>
client.post(
Uri.parse('https://api.example.com/users'),
headers: {'content-type': 'application/json'},
body: jsonEncode(payload),
);
/// The same JSON with the header forgotten. http fills in text/plain.
Future<http.Response> createUserUndeclared(
http.Client client,
Map<String, Object?> payload,
) =>
client.post(
Uri.parse('https://api.example.com/users'),
body: jsonEncode(payload),
);
/// Keep the Requests the client actually built so the test can inspect them.
MockClient recordingClient(
List<http.Request> seen,
Future<http.Response> Function(http.Request request) respond,
) =>
MockClient((request) {
seen.add(request);
return respond(request);
});
/// A server that always answers with the same bytes and headers.
MockClient fixedBytesClient(List<int> bytes, Map<String, String> headers) =>
MockClient((_) async => http.Response.bytes(bytes, 200, headers: headers));
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
_fe_analyzer_shared:
dependency: transitive
description:
name: _fe_analyzer_shared
sha256: "9a3386eea899815698dd55995277cf7cb8572ee52b399a6edfb7ae2b50e5fc19"
url: "https://pub.dev"
source: hosted
version: "105.0.0"
analyzer:
dependency: transitive
description:
name: analyzer
sha256: "62993bed6eadbe9596c5c20d5c167e7bc563c5fe266657a04ddeb93bdb84f4c9"
url: "https://pub.dev"
source: hosted
version: "14.1.0"
args:
dependency: transitive
description:
name: args
sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04
url: "https://pub.dev"
source: hosted
version: "2.7.0"
async:
dependency: transitive
description:
name: async
sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37
url: "https://pub.dev"
source: hosted
version: "2.13.1"
boolean_selector:
dependency: transitive
description:
name: boolean_selector
sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea"
url: "https://pub.dev"
source: hosted
version: "2.1.2"
cli_config:
dependency: transitive
description:
name: cli_config
sha256: ac20a183a07002b700f0c25e61b7ee46b23c309d76ab7b7640a028f18e4d99ec
url: "https://pub.dev"
source: hosted
version: "0.2.0"
collection:
dependency: transitive
description:
name: collection
sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
url: "https://pub.dev"
source: hosted
version: "1.19.1"
convert:
dependency: transitive
description:
name: convert
sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68
url: "https://pub.dev"
source: hosted
version: "3.1.2"
coverage:
dependency: transitive
description:
name: coverage
sha256: "956a3de0725ca232ad353565a8290d3357592bf4250f6f298a185e2d949c5d3d"
url: "https://pub.dev"
source: hosted
version: "1.15.1"
crypto:
dependency: transitive
description:
name: crypto
sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
url: "https://pub.dev"
source: hosted
version: "3.0.7"
file:
dependency: transitive
description:
name: file
sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4
url: "https://pub.dev"
source: hosted
version: "7.0.1"
frontend_server_client:
dependency: transitive
description:
name: frontend_server_client
sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694
url: "https://pub.dev"
source: hosted
version: "4.0.0"
glob:
dependency: transitive
description:
name: glob
sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de
url: "https://pub.dev"
source: hosted
version: "2.1.3"
http:
dependency: "direct main"
description:
name: http
sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412"
url: "https://pub.dev"
source: hosted
version: "1.6.0"
http_multi_server:
dependency: transitive
description:
name: http_multi_server
sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8
url: "https://pub.dev"
source: hosted
version: "3.2.2"
http_parser:
dependency: transitive
description:
name: http_parser
sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"
url: "https://pub.dev"
source: hosted
version: "4.1.2"
io:
dependency: transitive
description:
name: io
sha256: dfd5a80599cf0165756e3181807ed3e77daf6dd4137caaad72d0b7931597650b
url: "https://pub.dev"
source: hosted
version: "1.0.5"
logging:
dependency: transitive
description:
name: logging
sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61
url: "https://pub.dev"
source: hosted
version: "1.3.0"
matcher:
dependency: transitive
description:
name: matcher
sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd"
url: "https://pub.dev"
source: hosted
version: "0.12.20"
meta:
dependency: transitive
description:
name: meta
sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
url: "https://pub.dev"
source: hosted
version: "1.19.0"
mime:
dependency: transitive
description:
name: mime
sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6"
url: "https://pub.dev"
source: hosted
version: "2.0.0"
node_preamble:
dependency: transitive
description:
name: node_preamble
sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db"
url: "https://pub.dev"
source: hosted
version: "2.0.2"
package_config:
dependency: transitive
description:
name: package_config
sha256: ffcf4cf3d6c0b74ac43708d9f56625506e8a68aa935abe9d267a7330f320eb5d
url: "https://pub.dev"
source: hosted
version: "3.0.0"
path:
dependency: transitive
description:
name: path
sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
url: "https://pub.dev"
source: hosted
version: "1.9.1"
pool:
dependency: transitive
description:
name: pool
sha256: "978783255c543aa3586a1b3c21f6e9d720eb315376a915872c61ef8b5c20177d"
url: "https://pub.dev"
source: hosted
version: "1.5.2"
pub_semver:
dependency: transitive
description:
name: pub_semver
sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585"
url: "https://pub.dev"
source: hosted
version: "2.2.0"
shelf:
dependency: transitive
description:
name: shelf
sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12
url: "https://pub.dev"
source: hosted
version: "1.4.2"
shelf_packages_handler:
dependency: transitive
description:
name: shelf_packages_handler
sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e"
url: "https://pub.dev"
source: hosted
version: "3.0.2"
shelf_static:
dependency: transitive
description:
name: shelf_static
sha256: c87c3875f91262785dade62d135760c2c69cb217ac759485334c5857ad89f6e3
url: "https://pub.dev"
source: hosted
version: "1.1.3"
shelf_web_socket:
dependency: transitive
description:
name: shelf_web_socket
sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925"
url: "https://pub.dev"
source: hosted
version: "3.0.0"
source_map_stack_trace:
dependency: transitive
description:
name: source_map_stack_trace
sha256: c0713a43e323c3302c2abe2a1cc89aa057a387101ebd280371d6a6c9fa68516b
url: "https://pub.dev"
source: hosted
version: "2.1.2"
source_maps:
dependency: transitive
description:
name: source_maps
sha256: "190222579a448b03896e0ca6eca5998fa810fda630c1d65e2f78b3f638f54812"
url: "https://pub.dev"
source: hosted
version: "0.10.13"
source_span:
dependency: transitive
description:
name: source_span
sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab"
url: "https://pub.dev"
source: hosted
version: "1.10.2"
stack_trace:
dependency: transitive
description:
name: stack_trace
sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1"
url: "https://pub.dev"
source: hosted
version: "1.12.1"
stream_channel:
dependency: transitive
description:
name: stream_channel
sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"
url: "https://pub.dev"
source: hosted
version: "2.1.4"
string_scanner:
dependency: transitive
description:
name: string_scanner
sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43"
url: "https://pub.dev"
source: hosted
version: "1.4.1"
term_glyph:
dependency: transitive
description:
name: term_glyph
sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e"
url: "https://pub.dev"
source: hosted
version: "1.2.2"
test:
dependency: "direct dev"
description:
name: test
sha256: "0d5ba5602ec3baa28c8ce365e1efc5575969c765f45c554a3e167dc7945b9c30"
url: "https://pub.dev"
source: hosted
version: "1.31.2"
test_api:
dependency: transitive
description:
name: test_api
sha256: "475610b2aa23c19687cce2961e44b0cc57cafe220f67c2b80201231b2a07fbe7"
url: "https://pub.dev"
source: hosted
version: "0.7.13"
test_core:
dependency: transitive
description:
name: test_core
sha256: a39c204a4fc7a7ccb04a2b985e359fda3cc37e45e0b8ac61c3fb1a05aa832132
url: "https://pub.dev"
source: hosted
version: "0.6.19"
typed_data:
dependency: transitive
description:
name: typed_data
sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006
url: "https://pub.dev"
source: hosted
version: "1.4.0"
vm_service:
dependency: transitive
description:
name: vm_service
sha256: "0016aef94fc66495ac78af5859181e3f3bf2026bd8eecc72b9565601e19ab360"
url: "https://pub.dev"
source: hosted
version: "15.2.0"
watcher:
dependency: transitive
description:
name: watcher
sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635"
url: "https://pub.dev"
source: hosted
version: "1.2.1"
web:
dependency: transitive
description:
name: web
sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
url: "https://pub.dev"
source: hosted
version: "1.1.1"
web_socket:
dependency: transitive
description:
name: web_socket
sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c"
url: "https://pub.dev"
source: hosted
version: "1.0.1"
web_socket_channel:
dependency: transitive
description:
name: web_socket_channel
sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8
url: "https://pub.dev"
source: hosted
version: "3.0.3"
webkit_inspection_protocol:
dependency: transitive
description:
name: webkit_inspection_protocol
sha256: "87d3f2333bb240704cd3f1c6b5b7acd8a10e7f0bc28c28dcf14e782014f4a572"
url: "https://pub.dev"
source: hosted
version: "1.2.1"
yaml:
dependency: transitive
description:
name: yaml
sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce
url: "https://pub.dev"
source: hosted
version: "3.1.3"
sdks:
dart: ">=3.11.0 <4.0.0"
name: csx_http_mock
description: Testing package:http with MockClient, and the four defaults that surprise people.
publish_to: none
environment:
sdk: ^3.5.0
dependencies:
http: 1.6.0
dev_dependencies:
test: 1.31.2
import 'dart:convert';
import 'package:csx_http_mock/users.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:test/test.dart';
void main() {
test('the handler is handed a finalized copy of the built Request', () async {
final seen = <http.Request>[];
final client = recordingClient(seen, (_) async => http.Response('{}', 200));
await fetchUser(client, 'u42');
final sent = seen.single;
expect(sent, isA<http.Request>());
expect(sent.method, equals('GET'));
// The url is the one the client assembled, query string included, so a
// wrong path or a dropped parameter fails here and not in production.
expect(
sent.url,
equals(Uri.parse('https://api.example.com/users/u42?verbose=true')),
);
expect(sent.url.queryParameters['verbose'], equals('true'));
// BaseRequest.headers looks up case-insensitively but stores the case you
// wrote, so assert with either spelling and never with .keys.first.
expect(sent.headers['authorization'], equals('Bearer t0ken'));
expect(sent.headers['AUTHORIZATION'], equals('Bearer t0ken'));
expect(sent.headers.keys, contains('Authorization'));
expect(sent.body, isEmpty);
expect(sent.finalized, isTrue);
});
test('the copy is a plain Request, so a MultipartRequest arrives flat',
() async {
final seen = <http.Request>[];
final client = recordingClient(seen, (_) async => http.Response('', 200));
final mine = http.MultipartRequest(
'POST',
Uri.parse('https://api.example.com/uploads'),
)..fields['name'] = 'Ada Lovelace';
await client.send(mine);
// Not your object: MockClient rebuilds the finalized request. Everything
// that made it a MultipartRequest is gone by the time the handler runs, so
// read the encoded body, not .fields.
expect(identical(seen.single, mine), isFalse);
expect(seen.single, isNot(isA<http.MultipartRequest>()));
expect(seen.single.headers['content-type'],
startsWith('multipart/form-data; boundary='));
expect(seen.single.body, contains('name="name"'));
expect(seen.single.body, contains('Ada Lovelace'));
// Your request was finalized on the way through and cannot be sent twice.
expect(mine.finalized, isTrue);
});
test('a 404 does not throw; only statusCode says so', () async {
// The single most common mistake in Dart HTTP code: waiting for an
// exception that never arrives. The Future completes normally.
final client = MockClient((_) async => http.Response(
'{"error":"no such user"}',
404,
headers: {'content-type': 'application/json'},
reasonPhrase: 'Not Found',
));
final response = await fetchUser(client, 'ghost');
expect(response.statusCode, equals(404));
expect(response.reasonPhrase, equals('Not Found'));
// The error page decodes exactly like a success payload would, which is
// why a missing status check reads as valid data.
expect(jsonDecode(response.body), equals({'error': 'no such user'}));
// A 503 is equally uneventful, so checking the status is not optional.
final boom = MockClient((_) async => http.Response('down', 503));
expect((await fetchUser(boom, 'ghost')).statusCode, equals(503));
});
test('read and readBytes are the only members that check the status',
() async {
final client = MockClient((_) async => http.Response(
'{"error":"no such user"}',
404,
headers: {'content-type': 'application/json'},
reasonPhrase: 'Not Found',
));
// The same 404 that get returned quietly is a ClientException here, which
// is as close to raise_for_status as package:http gets. It costs you the
// response: ClientException carries a message and a uri, so the error body
// the server sent is gone.
await expectLater(
readUserBody(client, 'ghost'),
throwsA(isA<http.ClientException>().having(
(e) => e.message,
'message',
allOf(contains('failed with status 404: Not Found'),
isNot(contains('no such user'))),
)),
);
await expectLater(
client.readBytes(Uri.parse('https://api.example.com/users/ghost')),
throwsA(isA<http.ClientException>()),
);
// The cut is at 400, not at 2xx: a 399 is read back as a body.
final odd = MockClient((_) async => http.Response('still fine', 399));
expect(await readUserBody(odd, 'u42'), equals('still fine'));
});
test('response.body guesses an encoding, bodyBytes does not', () async {
final utf8Bytes = utf8.encode('café ☕');
Future<http.Response> read(Map<String, String> headers) =>
fetchUser(fixedBytesClient(utf8Bytes, headers), 'u42');
// Measured, against the expectation: application/json with no charset is
// special-cased to utf8 because RFC 8259 defines JSON as UTF-8. So the
// most common case is safe and teaches the wrong lesson.
expect((await read({'content-type': 'application/json'})).body,
equals('café ☕'));
// Every other type without a charset falls back to latin1, and so does a
// response with no content-type at all. Same bytes, mangled string. The
// special case is the exact type application/json and nothing else, so a
// JSON:API or any other +json vendor subtype is mojibake — which is the
// generalisation the line above invites and the reason to check it.
for (final headers in [
{'content-type': 'text/plain'},
{'content-type': 'text/html'},
{'content-type': 'application/xml'},
{'content-type': 'application/vnd.api+json'},
<String, String>{},
]) {
final mangled = await read(headers);
expect(mangled.body, equals(latin1.decode(utf8Bytes)));
expect(mangled.body, isNot(equals('café ☕')));
// bodyBytes is untouched, so the fix never depends on the server.
expect(mangled.bodyBytes, equals(utf8Bytes));
expect(utf8.decode(mangled.bodyBytes), equals('café ☕'));
}
// Declaring the charset is the other fix.
expect((await read({'content-type': 'text/plain; charset=utf-8'})).body,
equals('café ☕'));
});
test('a Map body is form-encoded, and JSON has to be spelled out', () async {
final seen = <http.Request>[];
final client = recordingClient(seen, (_) async => http.Response('', 201));
await createUserWithMapBody(client, {'name': 'Ada Lovelace', 'w': 'café'});
// Exactly this, with no charset parameter appended.
expect(seen.single.headers['content-type'],
equals('application/x-www-form-urlencoded'));
// Percent-encoded UTF-8, with + for the space. Nothing about it is JSON.
expect(seen.single.body, equals('name=Ada+Lovelace&w=caf%C3%A9'));
seen.clear();
await createUserAsJson(client, {'name': 'Ada Lovelace', 'w': 'café'});
// Also exactly this: charset is undefined for JSON, so http leaves the
// header alone.
expect(seen.single.headers['content-type'], equals('application/json'));
// The bytes on the wire are utf8, because a Request's default encoding is
// utf8 — the mirror image of the Response's latin1 fallback. Assert the
// bytes: jsonDecode(request.body) round-trips through the same encoding it
// was written with, so it would pass under latin1 too and prove nothing.
expect(
seen.single.bodyBytes,
equals(utf8.encode(jsonEncode({'name': 'Ada Lovelace', 'w': 'café'}))),
);
seen.clear();
await createUserUndeclared(client, {'name': 'Ada Lovelace'});
// Correct JSON bytes announced as text/plain. This is the 415.
expect(seen.single.headers['content-type'],
equals('text/plain; charset=utf-8'));
seen.clear();
await client.post(
Uri.parse('https://api.example.com/users'),
headers: {'content-type': 'application/xml'},
body: '<user name="Ada Lovelace"/>',
);
// The rule behind all four headers: a charset is appended only to text/*
// and the XML types, which is why XML gets one and JSON does not.
expect(seen.single.headers['content-type'],
equals('application/xml; charset=utf-8'));
// Declaring JSON and passing a Map is a StateError, not a silent
// mis-encode: bodyFields refuses any other content-type.
await expectLater(
client.post(
Uri.parse('https://api.example.com/users'),
headers: {'content-type': 'application/json'},
body: {'name': 'Ada Lovelace'},
),
throwsA(isA<StateError>().having(
(e) => e.message,
'message',
contains('content-type "application/json"'),
)),
);
});
test('a ClientException from the handler reaches the caller', () async {
final client = MockClient((request) async =>
throw http.ClientException('Connection reset by peer', request.url));
// Unwrapped, with the uri intact: this is the shape of a real transport
// failure and the one exception worth catching around an http call.
await expectLater(
fetchUser(client, 'u42'),
throwsA(isA<http.ClientException>()
.having((e) => e.message, 'message', 'Connection reset by peer')
.having((e) => e.uri, 'uri',
Uri.parse('https://api.example.com/users/u42?verbose=true'))),
);
// Nothing is wrapped on the way out, so a handler that throws something
// else delivers that type verbatim. Useful, and the reason a mistake in a
// fixture never disguises itself as a network failure.
await expectLater(
fetchUser(
MockClient((_) async => throw const FormatException('bad fixture')),
'u42'),
throwsA(isA<FormatException>()),
);
});
}