[Solved]-How to test file upload in Django rest framework using PUT?

10👍

Hi you need to use the SimpleUploadedFile wrapper for that :

from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.files import File

data = File(open('path/bond-data.dump', 'rb'))
upload_file = SimpleUploadedFile('data.dump', data.read(),content_type='multipart/form-data')
request = factory.put( '/data-packages/upload/ka',
   {'file':upload_file,other_params},
    content_type='application/octet-stream',
    content_disposition="attachment; filename=data.dump")

Ps : I am using APITestCase

7👍

from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase

from rest_framework.test import APIClient


class MyTest(TestCase):
    client_class = APIClient

    def test_it(self):
        file = SimpleUploadedFile("file.txt", b"abc", content_type="text/plain")
        payload = {"file": file}
        response = self.client.post("/some/api/path/", payload, format="multipart")
        self.assertEqual(response.status_code, 201)

        # If you do more calls in this method with the same file then seek to zero
        file.seek(0)

Leave a comment