简体   繁体   English

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

[英]How can I Unit Test GraphQL file Upload with API Platform?

In addition to my other tests against my GraphQL API Platform backend, I am attempting to test file uploads.除了针对 GraphQL API 平台后端的其他测试之外,我还尝试测试文件上传。 I'm not quite sure whether the ApiPlatform\\Core\\Bridge\\Symfony\\Bundle\\Test\\Client class has the ability to facilitate this test, or if Symfony\\Component\\HttpFoundation\\File\\UploadedFile should be used to provide the test file as it is for a REST operation.我不太确定ApiPlatform\\Core\\Bridge\\Symfony\\Bundle\\Test\\Client类是否有能力促进这个测试,或者是否应该使用Symfony\\Component\\HttpFoundation\\File\\UploadedFile来提供测试文件作为它用于 REST 操作。

Here is roughly where I am at in terms of putting together this test.这就是我在整理这个测试方面的大致情况。 (With some irrelevant parts removed for simplification) (为了简化,去掉了一些不相关的部分)

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

  }

The response I get seems to indicate that the file isn't being included as expected.我得到的响应似乎表明该文件未按预期包含在内。 Something like...就像是...

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

Or.. if I try to attach the file by simply assigning it directly in the variables property...或者..如果我尝试通过直接在variables属性中分配文件来附加文件......

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

then...然后...

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

In my most recent attempt, I changed things up quite a bit after sifting through the graphql code...在我最近的尝试中,在筛选了 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', '/api/graphql', [
      'headers' => $formData->getPreparedHeaders()->toArray(),
      'body' => $formData->bodyToString(),
    ]);

The problem with this last attempt is that the server isn't seeing any body parameters.最后一次尝试的问题在于服务器没有看到任何正文参数。 So I receiving the exception所以我收到异常

'GraphQL multipart request does not respect the specification.'

Which is found in /api-platform/core/src/GraphQl/Action/EntrypointAction.php within the parseMultipartRequest method.它位于/api-platform/core/src/GraphQl/Action/EntrypointAction.php中的parseMultipartRequest方法中。

After a few hours of debugging I found this solution:经过几个小时的调试,我找到了这个解决方案:

$formData = new FormDataPart();
$file = new UploadedFile('src/DataFixtures/files/test.txt', 'test.txt');
    
$response = $this->$client->request('POST', 'api/graphql', [
    'headers' => $formData->getPreparedHeaders()->toArray(),
    'extra' => [
        'parameters' => [
        'operations' => '{ "query": "mutation UploadMediaObject($file: Upload!) { uploadMediaObject(input: {file: $file}) { mediaObject { id contentUrl } } }", "variables": { "file": null } }',
            'map' => '{ "0": ["variables.file"] }',
            '0' => @$file,
        ],
        'files' => [
            $file,
        ],
    ],
]);

Refrence:参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM