Myzel394
Myzel394

Reputation: 1317

DRF How to test file uploads?

I have a simple model, a serializer and a view. I want to upload a file over the view but no method I found worked.

Here's my code:

def test_api_post(self):
    lesson = self.Create_lesson()
    file = SimpleUploadedFile(
        "file.txt",
        "".join(random.choices(string.ascii_letters + string.digits, k=1024 * 5)).encode(),
        "text/plain"
    )
    
    response = self.client.post(
        "/api/submission/",
        {
            "lesson": lesson.id,
            "file": file
        },
        format="multipart"
    )
    self.assertStatusOk(response.status_code)  # Error 

I tried it using with open() as file and I also tried using path.read_bytes(). Nothing worked.

How can I test binary file uploading with django-rest-framework's test client? doesn't work, https://gist.github.com/guillaumepiot/817a70706587da3bd862835c59ef584e doesn't work and how to unit test file upload in django also doesn't work.

Upvotes: 2

Views: 499

Answers (2)

rzrka
rzrka

Reputation: 1

work for me

from rest_framework.test import APIRequestFactory
from apps.Some.SomeViewSet import SomeViewSet

c = APIRequestFactory()
url = 'someurl/'
view = SomeViewSet.as_view()

file = 'path/to/file'
q = {'filename': file}
request = c.post(url, q)
response = view(request)

Upvotes: 0

I have fixed the problem with that:

import io
from django.test import TestCase

class test(TestCase):
    def test_upload_file(self):
        with open('/path/to/file.txt', 'rb') as fp :
            fio  = io.FileIO(fp.fileno())
            fio.name = 'file.txt'
            r = self.client.post('/url/', {'filename': fio, 'extraparameter': 5})
        self.assertEqual(r.headers['Content-Type'], 'application/json')

url.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'/url/$', views.serverside_method, name="serverside_method")
]

Example on the server-side (view.py)

def serverside_method(request):    
    if 'filename' in request.FILES:
        file_request = request.FILES['filename']
        file_size = file_request.size
        file_request_name = file_request.name
        return JsonResponse({'Success': True})
    else:
        return JsonResponse({'Success': False})

source: https://gist.github.com/nghiaht/682c2d8d40272c52dbf7adf214f1c0f1

Upvotes: 1

Related Questions