Redhya
Redhya

Reputation: 683

Test case removing original file while uploading a file through test case

This is my test case

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

But the problem is that it is deleting the original file from the folder i.e sample1.jpg

Help me out. Am i missing something here? Although the test case is running fine.

Upvotes: 3

Views: 1432

Answers (2)

user15202845
user15202845

Reputation: 1

This works for me.
You have to store in both public_path and storage_path the same file:

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

Upvotes: 0

Mihai Ocneanu
Mihai Ocneanu

Reputation: 797

When having the same problem, after looking in the source code, I couldn't find a flag that fixes it.

As I workaround, I created a copy when running the test, which gets deleted but it's no longer a problem.

$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;
}

You might want to refine this depending on your needs.

Upvotes: 2

Related Questions