如何在Django单元测试中使用图像字段

时间:2013-02-19 02:32:57

标签: django

假设我有一个单元测试表单,表单将验证文件格式:

class QForm(forms.ModelForm):
    error_messages = {
    'title_too_short': 'Title is too short',
    'invalid_image_format': 'Invalid image format: Only jpg, gif and png are allowed',
    }

    VALID_IMAGE_FORMATS = ('jpg', 'gif', 'png')

    title  = forms.CharField(label="Title")

    pic = forms.CharField(label="Picture")

    class Meta:
        model = Q
        fields = ("title", )

    def clean_title(self):
        title = self.cleaned_data["title"]
        if len(title) < 11:
           raise forms.ValidationError(self.error_messages['title_too_short'])
        return title

    def clean_pic(self):
        pic = self.cleaned_data["pic"]
        if pic:
            from django.core.files.images import get_image_dimensions
            if not pic.content_type in VALID_IMAGE_FORMATS:
                raise forms.ValidationError(self.error_messages['invalid_image_format'])

        return pic

我尝试编写单元测试但总是返回此错误:

AttributeError: 'unicode' object has no attribute 'content_type'

我的单元测试看起来像这样:

class FormTests(TestCase):
    def test_add(self):
        upload_file = open(os.path.join(settings.PROJECT_ROOT, 'static/img/pier.jpg'), "rb")
        data = {
            'title': 'Test', 
            'pic': SimpleUploadedFile(upload_file.name, upload_file.read())
        }

        q = QForm(data)

        self.assertEqual(q.is_valid(), True)

我想知道我使用错误的方法上传文件吗?

感谢。

1 个答案:

答案 0 :(得分:3)

如果您正在处理带有表单的文件,则需要将单独的files值传递给构造函数。请参阅Django文档:

https://docs.djangoproject.com/en/dev/ref/forms/api/#binding-uploaded-files-to-a-form

class FormTests(TestCase):
    def test_add(self):
        upload_file = open(os.path.join(settings.PROJECT_ROOT, 'static/img/pier.jpg'), "rb")
        data = {
            'title': 'Test', 
        }
        file_data = {
            'pic': upload_file
        }

        q = QForm(data, file_data)

        self.assertEqual(q.is_valid(), True)