单元使用FileField测试Django表单

Jas*_*sta 49 django unit-testing django-forms

我的表格如下:

#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())
Run Code Online (Sandbox Code Playgroud)

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

Jas*_*sta 83

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

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())
Run Code Online (Sandbox Code Playgroud)

  • 我想说的是,应该使用“ with”构造来完成此操作,以避免必须显式关闭“ upload_file”。 (2认同)

dra*_*oon 22

可能这不太正确,但我正在使用StringIO在单元测试中创建图像文件:

imgfile = StringIO('GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00'
                     '\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;')
imgfile.name = 'test_img_file.gif'

response = self.client.post(url, {'file': imgfile})
Run Code Online (Sandbox Code Playgroud)

  • +1,不必使用外部文件 (7认同)
  • 我尝试从视图中单独测试表单.实际上,我还没有提出这个观点. (3认同)

xyr*_*res 6

这是另一种不需要您使用实际图像的方法。

编辑:为Python 3更新。

from PIL import Image
from io import BytesIO # Python 2: from StringIO import StringIO
from django.core.files.uploadedfile import InMemoryUploadedFile

...

def test_form(self):
    im = Image.new(mode='RGB', size=(200, 200)) # create a new image using PIL
    im_io = BytesIO() # a BytesIO object for saving image
    im.save(im_io, 'JPEG') # save the image to im_io
    im_io.seek(0) # seek to the beginning

    image = InMemoryUploadedFile(
        im_io, None, 'random-name.jpg', 'image/jpeg', len(im_io.getvalue()), None
    )

    post_dict = {'title': 'Test Title'}
    file_dict = {'picture': image}

    form = MyForm(data=post_dict, files=file_dict)
Run Code Online (Sandbox Code Playgroud)

  • 当前存在下一个,但是:`TypeError:预期的字符串参数,得到了'bytes'。我使用BytesIO而不是StringIO来解决它,而不使用im_io.len,因为BytesIO对象没有length属性。 (4认同)