一尘不染

使用FileField对Django表单进行单元测试

django

我有一个像这样的表格:

#forms.py
from django import forms

class MyForm(forms.Form):
    title = forms.CharField()
    file = forms.FileField()


#tests.py
from django.test import TestCase
from forms import MyForm

class FormTestCase(TestCase)
    def test_form(self):
        upload_file = open('path/to/file', 'r')
        post_dict = {'title': 'Test Title'}
        file_dict = {} #??????
        form = MyForm(post_dict, file_dict)
        self.assertTrue(form.is_valid())

如何构造file_dict以将upload_file传递到表单?


阅读 441

收藏
2020-04-04

共1个答案

一尘不染

到目前为止,我发现这种方式有效

from django.core.files.uploadedfile import SimpleUploadedFile
 ...
def test_form(self):
        upload_file = open('path/to/file', 'rb')
        post_dict = {'title': 'Test Title'}
        file_dict = {'file': SimpleUploadedFile(upload_file.name, upload_file.read())}
        form = MyForm(post_dict, file_dict)
        self.assertTrue(form.is_valid())
2020-04-04