Testing File uploads in Symfony2

18,603

Solution 1

This was an error in the documentation.

Fixed here:

use Symfony\Component\HttpFoundation\File\UploadedFile;

$photo = new UploadedFile('/path/to/photo.jpg', 'photo.jpg', 'image/jpeg', 123);
// or
$photo = array('tmp_name' => '/path/to/photo.jpg', 'name' => 'photo.jpg', 'type' => 'image/jpeg', 'size' => 123, 'error' => UPLOAD_ERR_OK);

$client = static::createClient();
$client->request('POST', '/submit', array('name' => 'Fabien'), array('photo' => $photo));

Documentation here

Solution 2

Here is a code which works with Symfony 2.3 (I didn't tried with another version):

I created an photo.jpg image file and put it in Acme\Bundle\Tests\uploads.

Here is an excerpt from Acme\Bundle\Tests\Controller\AcmeTest.php:

function testUpload()
{
    // Open the page
    ...

    // Select the file from the filesystem
    $image = new UploadedFile(
        // Path to the file to send
        dirname(__FILE__).'/../uploads/photo.jpg',
        // Name of the sent file
        'filename.jpg',
        // MIME type
        'image/jpeg',
        // Size of the file
        9988
    );

    // Select the form (adapt it for your needs)
    $form = $crawler->filter('input[type=submit]...')->form();

    // Put the file in the upload field
    $form['... name of your field ....']->upload($image);

    // Send it
    $crawler = $this->client->submit($form);

    // Check that the file has been successfully sent
    //  (in my case the filename is displayed in a <a> link so I check
    //  that it appears on the page)
    $this->assertEquals(
        1,
        $crawler->filter('a:contains("filename.jpg")')->count()
    );
}

Solution 3

if you want to mock a UploadedFile without a client request, you can use:

    $path = 'path/to/file.test';
    $originalName = 'original_name.test';
    $file = new UploadedFile($path, $originalName, null, UPLOAD_ERR_OK, true);
    $testSubject->method($file);

Solution 4

I found this article, https://coderwall.com/p/vp52ew/symfony2-unit-testing-uploaded-file, and works perfect.

Regards

Solution 5

Even if the question is related to Symfony2, it appears in the top results when searching for Symfony4 in Google.

Instancing an UploadedFile works, but the shortest way I found was also actually in the official documentation:

$crawler = $client->request('GET', '/post/hello-world');
$buttonCrawlerNode = $crawler->selectButton('submit');
$form = $buttonCrawlerNode->form();
$form['photo']->upload('/path/to/lucas.jpg');

https://symfony.com/doc/current/testing.html#forms

Share:
18,603
johnwards
Author by

johnwards

Updated on July 17, 2022

Comments

  • johnwards
    johnwards almost 2 years

    In the Symfony2 documentation it gives the simple example of:

    $client->request('POST', '/submit', array('name' => 'Fabien'), array('photo' => '/path/to/photo'));
    

    To simulate a file upload.

    However in all my tests I am getting nothing in the $request object in the app and nothing in the $_FILES array.

    Here is a simple WebTestCase which is failing. It is self contained and tests the request that the $client constructs based on the parameters you pass in. It's not testing the app.

    class UploadTest extends WebTestCase {
    
        public function testNewPhotos() {
            $client = $this->createClient();
            $client->request(
                'POST', 
                '/submit', 
                array('name' => 'Fabien'), 
                array('photo' => __FILE__)
            );
    
            $this->assertEquals(1, count($client->getRequest()->files->all()));
        }
    }
    

    Just to be clear. This is not a question about how to do file uploads, that I can do. It is about how to test them in Symfony2.

    Edit

    I'm convinced I'm doing it right. So I've created a test for the Framework and made a pull request. https://github.com/symfony/symfony/pull/1891

  • astroanu
    astroanu over 8 years
    on the created UploadedFile object $file->isValid() fails. any idea why?
  • A.L
    A.L over 8 years
    @astroanu please add a new question to explain your problem.
  • DevDonkey
    DevDonkey about 7 years
    this is a much better solution. Unit test where you can!
  • A.L
    A.L about 7 years
    Please include the code in your answer so your answer will be still valid if the page disappear.
  • AymDev
    AymDev about 4 years
    Still works on Symfony 5.0, except the UploadedFile constructor removes the file size and added error & test.
  • chadyred
    chadyred over 2 years
    The fifth parameter active the "test" mode, in order to not trigger HTTP real upload in test.