如何使用 API 平台对 GraphQL 文件上传进行单元测试?

问题描述

除了针对我的 GraphQL API 平台后端进行的其他测试之外,我还尝试测试文件上传。我不太确定 ApiPlatform\Core\Bridge\Symfony\Bundle\Test\Client 类是否有能力促进此测试,或者是否应该使用 Symfony\Component\HttpFoundation\File\UploadedFile 来提供测试文件,因为它用于 REST 操作。

这就是我在整理这个测试方面的大致情况。 (为了简化去掉了一些不相关的部分)

 public function testCreateMediaObject(): void {
    $file = new UploadedFile('fixtures/files/logo.png','logo.png');
    $client = self::createClient();

    $gql = <<<GQL
    mutation UploadMediaObject(\$file: Upload!) {
      uploadMediaObject(input: {file: \$file}) {
        mediaObject {
          id
          contentUrl
        }
      }
    }
    GQL;

    $response = $client->request('POST','/api/graphql',[
      'headers' => ['Content-Type' => 'application/json'],'json' => [
        'query' => $gql,'variables' => ["file" => null],'map' => ['0' => ['variables.file']],'0' => $file,]
    ]);
    dd($response);

  }

我得到的响应似乎表明该文件未按预期包含在内。像……

Variable "$file" of non-null type "Upload!" must not be null.

或者...如果我尝试通过直接在 variables 属性中分配文件来附加文件...

    $response = $client->request('POST','variables' => ["file" => $file],]
    ]);

然后...

Variable "$file" got invalid value []; Expected type Upload; Could not get uploaded file,be sure to conform to GraphQL multipart request specification. Instead got: []

在我最近的尝试中,我在筛选了 graphql 代码后做了很多改变......

    $formFields = [
      'operations' => '{ "query": "mutation ($file: Upload!) { uploadMediaObject(input: {file: $file}) { mediaObject { id contentUrl } } }","variables": { "file": null } }','map' => "{'0': ['variables.file']}",'0' => DataPart::fromPath(__DIR__.'/../../fixtures/files/logo.png'),];
    $formData = new FormDataPart($formFields);
    $response = $client->request('POST',[
      'headers' => $formData->getPreparedHeaders()->toArray(),'body' => $formData->bodyToString(),]);

最后一次尝试的问题是服务器没有看到任何正文参数。所以我收到了异常

'GraphQL multipart request does not respect the specification.'

可在 /api-platform/core/src/GraphQl/Action/EntrypointAction.PHP 方法中的 parseMultipartRequest 中找到。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)