使用 codeception 测试文件上传

Testing file uploads with codeception

问题:

当使用带有 PhpBrowser 的 REST 模块从代码接收测试发出请求时,没有数据和文件传送到 Silex 应用程序 driver。

    // ApiTester $I
    $I->wantTo('Submit files');

    // prepare:
    $data = ['key' => 'value'];
    $files = [
        'file_key' => 'path/to/file.doc',
        'file2_key' => 'path/to/file2.doc'
    ];

    // act:
    $I->haveHttpHeader('Content-Type', 'multipart/form-data');
    $I->sendPOST('/attachments/', $data, $files);

当前回复

 I have http header "Content-Type","multipart/form-data"
 I send post "/attachments/",{"key":"value"},{"file_key":"/path/to/file/...}
  [Request] POST http://localhost/attachments/ {"key":"value"}
  [Request Headers] {"Content-Type":"multipart/form-data"}
  [Page] http://localhost/attachments/
  [Response] 400
  [Request Cookies] []
  [Response Headers] {"Date":["Tue, 25 Oct 2016 09:15:31 GMT"],"Server":["Apache/2.4.10 (Debian)"],"Cache-Control":["no-cache"],"Access-Control-Allow-Origin":["*"],"Access-Control-Allow-Headers":["Content-Type, Authorization"],"Access-Control-Allow-Methods":["GET,PATCH,PUT,POST,HEAD,DELETE,OPTIONS"],"Content-Length":["1235"],"Connection":["close"],"Content-Type":["application/json"]}
  [Response] {"status":400,"meta":{"time":"2016-10-25 09:15:31"},"title":"Invalid Request","errors":"No data received","details":{"error_class":"Symfony\Component\HttpKernel\Exception\BadRequestHttpException"

尝试过:

该测试适用于 Silex driver,但在 CI 服务器上不可用。我们还检查了 Postman,API 路由按预期工作,文件已发送,一切正常。

实际问题:

  • $I->haveHttpHeader('Content-Type', 'multipart/form-data'); 覆盖 Content-Type 因为它应该由 http 库设置(在 phpbrowser 中是 guzzle)以包含边界, 它与 this.
  • 有关
  • 另请注意,$I->header 不会在每次请求后重置,要取消设置,请使用 $I->deleteHeader('Content-Type');

解决方案

  • 发送文件时不要设置'Content-Type'headers