postMultipart method

Future<TestResponse> postMultipart(
  1. String path, {
  2. Map<String, String> fields = const {},
  3. List<TestUpload> files = const [],
  4. Map<String, String>? headers,
})

Sends a multipart/form-data request, the way a browser form does.

The boundary is fixed rather than random: a test that fails is easier to read when its body is identical on every run, and nothing here is adversarial.

Implementation

Future<TestResponse> postMultipart(
  String path, {
  Map<String, String> fields = const {},
  List<TestUpload> files = const [],
  Map<String, String>? headers,
}) {
  const boundary = 'MaatTestBoundary';
  final body = <int>[
    for (final field in fields.entries)
      ...utf8.encode(
        '--$boundary\r\n'
        'content-disposition: form-data; name="${field.key}"\r\n'
        '\r\n'
        '${field.value}\r\n',
      ),
    for (final file in files) ...[
      ...utf8.encode(
        '--$boundary\r\n'
        'content-disposition: form-data; name="${file.field}"; '
        'filename="${file.filename}"\r\n'
        'content-type: ${file.contentType}\r\n'
        '\r\n',
      ),
      ...file.bytes,
      ...utf8.encode('\r\n'),
    ],
    ...utf8.encode('--$boundary--\r\n'),
  ];

  return _send(
    'POST',
    path,
    bytes: body,
    headers: {
      'content-type': 'multipart/form-data; boundary=$boundary',
      'accept': 'application/json',
      ...?headers,
    },
  );
}