Answer the question
In order to leave comments, you need to log in
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!')
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())
form.errors
swears 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
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())
data
and the file file_data
must 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 questionAsk a Question
731 491 924 answers to any question