mercredi 13 novembre 2019

How to test file upload with Aqueduct harness?

I followed the Aqueduct tutorial for creating tests, but it was missing one example that I am in a dire need; I am unable to test a file uploading endpoint with my controller.

I have implemented a controller as such:

class FileController extends ResourceController {

  FileController() {
    acceptedContentTypes = [ContentType("multipart", "form-data")];
  }

  @Operation.post()
  Future<Response> postForm() async {

    final transformer = MimeMultipartTransformer(request.raw.headers.contentType.parameters["boundary"]);
    final bodyStream = Stream.fromIterable([await request.body.decode<List<int>>()]);
    final parts = await transformer.bind(bodyStream).toList();

    for (var part in parts) {
      final headers = part.headers;

      HttpMultipartFormData multipart = HttpMultipartFormData.parse(part);
      final content = multipart.cast<List<int>>();

      final filePath = "uploads/test.txt";

      await new File(filePath).create(recursive: true);

      IOSink sink = File(filePath).openWrite();
      await content.forEach(sink.add);

      await sink.flush();
      await sink.close();
    }

    return Response.ok({});   
  }
}

And it works fine when using Postman for a file upload.

Now I am trying to write a test for this endpoint:

test("POST /upload-file uploads a file to the server", () async {

    final file = File('test.txt');
    final sink = file.openWrite();
    sink.write('test');
    await sink.close();

    final bytes = file.readAsBytesSync();

    harness.agent.headers['Content-Type'] = 'multipart/form-data; boundary=MultipartBoundry';
    harness.agent.headers['Content-Disposition'] = 'form-data; name="file"; filename="test.txt"';


    final response = await harness.agent.post("/upload-file", body: bytes);

    expectResponse(response, 200);
  });

And get this in the vscode debugger:

Expected: --- HTTP Response ---
          - Status code must be 200
          - Headers can be anything
          - Body can be anything
          ---------------------
  Actual: TestResponse:<-----------
          - Status code is 415
          - Headers are the following:
            - x-frame-options: SAMEORIGIN
            - x-xss-protection: 1; mode=block
            - x-content-type-options: nosniff
            - server: aqueduct/1
            - content-length: 0
          - Body is empty
          -------------------------
          >
   Which: Status codes are different. Expected: 200. Actual: 415

Aucun commentaire:

Enregistrer un commentaire