2

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

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)

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

谢谢。

4

1 回答 1

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)
于 2013-02-19T10:20:16.610 回答