kero_zen
kero_zen

Reputation: 694

Manipulate Symfony 2 UploadFile object in a unit test

I'm working on a Symfony2 project. I created a simple TempFile class to manipulate an UploadFile. Here is my constructor :

public function __construct(UploadedFile $file, $destination, $suffix)
{
    $this->file             = $file;
    $this->destination      = $destination;
    $this->fileId           = sprintf('%s_%s', uniqid(), (string) $suffix);
}

And my move method

public function move()
{
    $extension = $this->file->guessExtension();
    if (!$extension) {
        throw new \Exception(__METHOD__ . ' -> Unable to detect extension');
    }

    $this->tmpFileName = sprintf('%s.%s', $this->fileId, $extension);
    $this->file->move($this->destination, $this->tmpFileName);
}

I try to create an UploadFile object in my test and here is what I did :

protected function setUp()
{
    $this->file = tempnam(sys_get_temp_dir(), 'upload');
    imagepng(imagecreatetruecolor(10, 10), $this->file);
    $this->uploadedFile = new UploadedFile($this->file, "test.png");
}

public function testMoveWithAValidUploadedFile()
{
    $tempFile = new TempFile($this->uploadedFile, '/tmp', 'tmp');
    $tempFile->move();
    // Future assertion
}

I have the following error :

Symfony\Component\HttpFoundation\File\Exception\FileException: The file "test.png" was not uploaded due to an unknown error

Any ideas ?

Thx, Regards

Upvotes: 1

Views: 279

Answers (1)

Ryan
Ryan

Reputation: 5026

From memory, Symfony2 checks if a file was uploaded as part of the request using is_uploaded_file(). This can be overridden using the test mode of the UploadedFile class. You can also define which PHP upload error code constitutes success.

copy(__DIR__ . '/Fixtures/test.pdf', '/tmp/test.pdf');
new UploadedFile(
    '/tmp/test.pdf',
    'original.pdf',
    null,
    null,
    UPLOAD_ERR_OK,
    true /* test */
)

Upvotes: 4

Related Questions