【问题标题】:Test case removing original file while uploading a file through test case测试用例通过测试用例上传文件时删除原始文件
【发布时间】:2017-08-30 14:12:36
【问题描述】:

这是我的测试用例

public function testSelfieFileUpload()
{
    $path = public_path().'/uploads/sample1.jpg';
    $name = 'sample1.jpg';
    $file = new UploadedFile($path, $name, 'image/png', filesize($path), null, true);
    $response = $this->post($this->endpoint, ['file' => $file], $this->setHeaders());
    $response->assertStatus(200)
        ->assertJsonFragment(array("status" => "success"));
}

但问题是它正在从文件夹中删除原始文件,即 sample1.jpg

帮帮我。我在这里错过了什么吗?虽然测试用例运行良好。

【问题讨论】:

  • 你对那些文件使用了 unset 吗?
  • 什么未设置..?如果你的意思是删除。那么我没有明确地这样做
  • 如果您想在必须使用 PHP 取消设置函数删除之前删除正在存储的文件
  • 不,我不想删除它。我的源文件被删除了,这让我很困扰。
  • 啊,好的。我认为 UploadedFile 只是移动那些文件。所以我猜有一些额外的参数可以让你复制文件而不是移动它。不确定 - 只是我的猜测

标签: laravel testing file-upload laravel-5 phpunit


【解决方案1】:

当遇到同样的问题时,在查看源代码后,我找不到修复它的标志。

作为解决方法,我在运行测试时创建了一个副本,该副本被删除但不再是问题。

$temporaryFilePath = $this->createTempFile($this->testFilePath);
$file = new \Illuminate\Http\UploadedFile($path, $name, $mime, filesize($path), null, true);
//do your test logic

...

private function createTempFile($path) {

    $tempFilePath = $this->basePath . 'temp.xlsx';
    copy($path, $tempFilePath);

    return $tempFilePath;
}

您可能希望根据自己的需要对其进行细化。

【讨论】:

  • 在 Laravel 8 中,$file = new \Illuminate\Http\UploadedFile($path, $name, $mime, null, true);
【解决方案2】:

这对我有用。
您必须将public_pathstorage_path 存储在同一个文件中:

 $filename = storage_path('app/pdfstest/COVID 19.pdf');

 $pdf = new UploadedFile($filename, $name, 'application/pdf');

 $response = $this->post('/gallery', [
   'user_id' => $this->user->id,
   'doc' => [$pdf],
   'from_tab' => 'test'
 ]);

 $temp_pdf = file_get_contents(public_path('pdfstest/COVID 19.pdf'));
 Storage::put('pdfstest/COVID 19.pdf', $temp_pdf);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-14
    • 2017-10-07
    • 2019-09-12
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多