PIL - The submitted file is empty Test Case

1.9k views Asked by At

I have a file upload which works perfectly, however I want to write a test for it so I did the following....

   def test_post_ok(self):

    image = Image.new('RGB', (100, 100)
    tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg')
    image.save(tmp_file)
    payload = {
        "name": "Test",
        "thumbnail_image": tmp_file
    }
   api = APIClient()
   api.credentials(Authorization='Bearer ' + self.token)
   response = api.post(url, payload, format='multipart')

However, the test gives the error...

<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=1024x768 at 0x108A5DCF8>
{'thumbnail_image': [u'The submitted file is empty.']}

I assume I'm not doing this correctly, if not why?

1

There are 1 answers

0
Wouter Klein Heerenbrink On

My earlier guess is wrong. You are using the Rest Framework with the multipart functionality (awesome!) so you can send the file as-is and the file will be encoded multipart.

The error here is the following:

  1. You open the file tmp_file
  2. You write the image contents to this file
  3. The filepointer is now at the end of the document
  4. You pass on the document to APIClient() which is a simple test wrapper which passes the argument up through the rest_framework where eventually your call is encoded
  5. The encoding will call tmp_file.read(). Since the pointer is still at the end of the file, read() will return 0 bytes, leaving you with an empty document.

Solutions: tmp_file.seek(0) or reopen the file before calling post()