gpt4 book ai didi

testing - 如何使用 Aqueduct harness 测试文件上传?

转载 作者:行者123 更新时间:2023-11-28 21:35:55 26 4
gpt4 key购买 nike

我按照 Aqueduct 教程创建测试,但缺少一个我迫切需要的示例;我无法使用我的 Controller 测试文件上传端点。

我已经实现了这样的 Controller :

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({});
}
}

使用 Postman 上传文件时效果很好。

现在我正在尝试为此端点编写测试:

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);
});

然后在 vscode 调试器中获取:

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

最佳答案

415 状态代码响应表示 ResourceController 已拒绝请求的内容类型。您已经正确设置了 acceptedContentTypes,但是,Agent.headers 的文档中隐藏了测试代理的细微差别(诚然令人困惑):

Default headers to be added to requests made by this agent.

By default, this value is the empty map.

Do not provide a 'content-type' key. If the key 'content-type' is present, it will be removed prior to sending the request. It is replaced by the value of TestRequest.contentType, which also controls body encoding.

See also setBasicAuthorization, bearerAuthorization, accept, contentType for setting common headers.

请参阅 API 引用 here .至于为什么会这样存在:就像您的响应一样,TestRequest 的内容类型(它是您使用代理发出请求时创建和执行的对象)决定了 CodecRegistry 中的哪个编解码器用作编码器。这允许您始终处理“Dart 对象”并让 Aqueduct 处理编码/解码。

关于testing - 如何使用 Aqueduct harness 测试文件上传?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58839496/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com