单元使用没有外部文件的ImageField测试Django表单

时间:2018-01-03 10:40:58

标签: python django unit-testing

django版本:1.11,python版本:3.6.3

我发现了这个stackoverflow问题:

Unit Testing a Django Form with a FileField

我喜欢没有用于unittest的实际图像/外部文件;但是我尝试了这些方法:

from django.test import TestCase
from io import BytesIO
from PIL import Image
from my_app.forms import MyForm
from django.core.files.uploadedfile import InMemoryUploadedFile

class MyModelTest(TestCase):                    
    def test_valid_form_data(self):                    
        im_io = BytesIO() # BytesIO has to be used, StrinIO isn't working         
        im = Image.new(mode='RGB', size=(200, 200))         
        im.save(im_io, 'JPEG')                                  
        form_data = {
                'some_field': 'some_data'
            }                                               
        image_data = {   
                InMemoryUploadedFile(im_io, None, 'random.jpg', 'image/jpeg', len(im_io.getvalue()), None) 
            }    
        form = MyForm(data=form_data, files=image_data)             
        self.assertTrue(form.is_valid()) 

但是,这总是会导致以下错误消息:

Traceback (most recent call last):
  File "/home/my_user/projects/my_app/products/tests/test_forms.py", line 44, in test_valid_form_data
    self.assertTrue(form.is_valid())
  File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/forms.py", line 183, in is_valid
    return self.is_bound and not self.errors
  File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/forms.py", line 175, in errors
    self.full_clean()
  File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/forms.py", line 384, in full_clean
    self._clean_fields()
  File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/forms.py", line 396, in _clean_fields
    value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
  File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/widgets.py", line 423, in value_from_datadict
    upload = super(ClearableFileInput, self).value_from_datadict(data, files, name)
  File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/widgets.py", line 367, in value_from_datadict
    return files.get(name)
AttributeError: 'set' object has no attribute 'get'

为什么呢?我知道.get()是一个字典方法,但我没有看到它创建一个集合的位置。

2 个答案:

答案 0 :(得分:2)

image_data应该是dict,不提供密钥{value}将创建set对象。您需要像{key: value}一样定义它。修复此问题:

image_data = {   
            'image_field': InMemoryUploadedFile(im_io, None, 'random.jpg', 'image/jpeg', len(im_io.getvalue()), None) 
        }   

答案 1 :(得分:0)

没有外部文件代码

from django.core.files.uploadedfile import SimpleUploadedFile
testfile = (
b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x00\x00\x00\x21\xf9\x04'
b'\x01\x0a\x00\x01\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02'
b'\x02\x4c\x01\x00\x3b')

avatar = SimpleUploadedFile('small.gif', testfile, content_type='image/gif')