Y
Y
YuriyCherniy2020-02-22 23:04:18
Django
YuriyCherniy, 2020-02-22 23:04:18

How to test clean a Django form method?

There is this simple Django form:

from django.forms import ModelForm, ValidationError
from django.core.files.images import get_image_dimensions

from .models import Item


class ItemModelForm(ModelForm):
    class Meta:
        model = Item
        fields = ['title', 'description', 'image', 'price']

    def clean_image(self):
        '''
        Only 1:1 format is allowed
        '''
        image = self.cleaned_data.get('image')
        width, height = get_image_dimensions(image)
        if width == height:
            return image
        raise ValidationError('Формат изображения должен быть 1:1!')

Can't upload test image file to form. I'm trying to test something like this:
from io import BytesIO

from PIL import Image

from django.test import SimpleTestCase
from django.core.files.uploadedfile import InMemoryUploadedFile

from showcase.forms import ItemModelForm


def create_test_image():
    file = BytesIO()
    image = Image.new('RGBA', size=(50, 50), color=(155, 0, 0))
    image.save(file, 'png')
    file.name = 'test.png'
    file.seek(0)
    return file


class TestForms(SimpleTestCase):
    def test_item_model_form_valid_data(self):
        form = ItemModelForm(
            data={
                'title': 'test_title`',
                'description': 'test_description' * 10,
                'price': 500,
                'image': InMemoryUploadedFile(
                    file=create_test_image(),
                    field_name='image',
                    name='test.png',
                    content_type='image/png',
                    size=45,
                    charset='utf-8'
                )
            }
        )
        self.assertTrue(form.is_valid())

This test form.errorsswears that the image field is required. Tell me where to dig? Or maybe there is some other approach to solving the problem of testing the clean method?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
YuriyCherniy, 2020-02-23
@YuriyCherniy

In general, I answered myself, the working test looks like this:

def test_item_model_form_valid_data(self):
        data = {
                'title': 'test_title`',
                'description': 'test_description' * 10,
                'price': 500
            }

        file_data = {
            'image': InMemoryUploadedFile(
                    file=create_test_image(),
                    field_name='image',
                    name='test.png',
                    content_type='image/png',
                    size=45,
                    charset='utf-8'
            )
        }

        form = ItemModelForm(data=data, files=files_data)
        self.assertTrue(form.is_valid())

The input data dataand the file file_datamust be transferred to the form separately, the problem was in this. It seems to me that this is not the best way to test the form, but the gurus unfortunately did not connect. It will be necessary to play around with mock, the truth must be somewhere there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question