2

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.

Myzel394
  • 1,155
  • 3
  • 16
  • 40

2 Answers2

1

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

0

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)
rzrka
  • 1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center. – Anurag A S Jun 26 '22 at 15:52