【问题标题】:DRF How to test file uploads?DRF 如何测试文件上传?
【发布时间】:2021-01-27 01:28:58
【问题描述】:

我有一个简单的模型、一个序列化程序和一个视图。我想通过视图上传文件,但没有找到有效的方法。

这是我的代码:

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 

我尝试使用with open() as file,也尝试使用path.read_bytes()。没有任何效果。

How can I test binary file uploading with django-rest-framework's test client? 不起作用,https://gist.github.com/guillaumepiot/817a70706587da3bd862835c59ef584e 不起作用,how to unit test file upload in django 也不起作用。

【问题讨论】:

  • 你得到什么错误?
  • status_code = 400。没有datacontent 是一些 html 说 Bad Request

标签: python django django-rest-framework


【解决方案1】:

我已经解决了这个问题:

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")
]

服务器端示例(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})

来源:https://gist.github.com/nghiaht/682c2d8d40272c52dbf7adf214f1c0f1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-29
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 2020-03-11
    相关资源
    最近更新 更多