Kintarō
Kintarō

Reputation: 3187

How to use image field in Django unit test

Suppose I have a form with has a unit test, the form will validate the file format:

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

I tried to write an unit test but it always return this error:

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

And my unit test looks like this:

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)

Just wonder am I using a wrong method to upload a file?

Thanks.

Upvotes: 2

Views: 1811

Answers (1)

Andrew Ingram
Andrew Ingram

Reputation: 5240

If you're handling files with forms you need a separate files value passed to the constructor. See here in the Django docs:

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)

Upvotes: 3

Related Questions