首页 > 解决方案 > InvalidArgumentException:假 UploadedFile 需要“内容”键

问题描述

您好,我正在尝试使用伪造的上传文件来测试 HTTP 附加,但是我一直在抱怨InvalidArgumentException: A 'contents' key is required

我错过了什么吗?

当我尝试转储伪造的上传文件时,我得到了 ff.

Illuminate\Http\Testing\File^ {#1808
  +name: "test.docx"
  +tempFile: stream resource {@706
    timed_out: false
    blocked: true
    eof: false
    wrapper_type: "plainfile"
    stream_type: "STDIO"
    mode: "r+b"
    unread_bytes: 0
    seekable: true
    uri: "/private/var/folders/88/qdbqbd6j657_3cr43nw29ywh0000gp/T/phpZ7vpwW"
    options: []
  }
  +sizeToReport: 102400
  +mimeTypeToReport: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  name: "test.docx"
  tempFile: stream resource @706
  sizeToReport: 102400
  mimeTypeToReport: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  -test: true
  -originalName: "test.docx"
  -mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  -error: 0
  #hashName: null
  path: "/private/var/folders/88/qdbqbd6j657_3cr43nw29ywh0000gp/T"
  filename: "phpZ7vpwW"
  basename: "phpZ7vpwW"
  pathname: "/private/var/folders/88/qdbqbd6j657_3cr43nw29ywh0000gp/T/phpZ7vpwW"
  extension: ""
  realPath: "/private/var/folders/88/qdbqbd6j657_3cr43nw29ywh0000gp/T/phpZ7vpwW"
  aTime: 2021-10-05 12:47:58
  mTime: 2021-10-05 12:47:58
  cTime: 2021-10-05 12:47:58
  inode: 94773635
  size: 102400
  perms: 0100600
  owner: 502
  group: 20
  type: "file"
  writable: true
  readable: true
  executable: false
  file: true
  dir: false
  link: false
}

但是,当我尝试转储时,$file->get()我得到了一个空字符串

文件上传器类

class FileUploader implements IFileScanner {
  public function upload(UploadedFile $file) {
    $response = Http::withHeaders([
      'X-Request-ID' => Str::random(6),
    ])
    ->attach('file', $file->get(), $file->getFilename())
    ->post('http://example.com/upload');

    if ($response->successful()) {
      return $response->object();
    }

    if ($response->clientError() || $response->serverError()) {
      $response->throw();
    }
  }
}

FileUploaderTest 类

public function testShouldReturnOkWhenFileIsUninfected() {
    Http::fake([
      'http://example.com/upload' => Http::response([
        'infected'=> false,
        'result' => '',
        'error' => '',
        'executionTimeMS' => '',
      ]),
    ], 200);

    $uploadedFile = UploadedFile::fake()->create(
      'test.docx',
      1000,
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    );
    
    $fileScanner = new FileUploader();
    $response = $fileScanner->scan($uploadedFile);

    $this->assertEquals($response, [
      'infected'=> false,
      'result' => '',
      'error' => '',
      'executionTimeMS' => '',
    ]);
  }

标签: phplaravellaravel-8

解决方案


经过几个小时的挖掘,我终于能够解决它。以防万一有人遇到这种错误。我发现有createWithContent.

$uploadedFile = UploadedFile::fake()->createWithContent('test.docx', 'test only')


推荐阅读