def test_simple(self): image_field = ImageField() django_image = image_field.clean(self._payload) self.assertIsInstance(django_image, File) self.assertEqual(django_image.size, 12412) self.assertEqual(django_image.content_type, 'image/jpeg') self.assertIsNotNone(django_image.image)
def test_invalid(self): file_field = ImageField() with open(f"{settings.BASE_DIR}/data/invalid_image.txt") as f: kitten = f.read() with self.assertRaises(ValidationError): log_input(kitten) file_field.clean(kitten)
def test_mime_mismatch(self): file_field = ImageField(mime=['image/png', 'image/gif']) with open(f"{settings.BASE_DIR}/data/kitten_mismatch.txt") as f: kitten = f.read() expected_error = FileField.default_error_messages['invalid_mime'] expected_error = expected_error.format('image/png, image/gif', 'image/jpeg') with self.assertRaisesMessage(ValidationError, expected_error): log_input(kitten) file_field.clean(kitten)
class EntryForm(Form): language_code = forms.CharField(max_length=3) author_id = forms.ModelChoiceField(queryset=Author.objects.all(), required=False) author = FormField(AuthorForm, required=False) category_ids = forms.ModelMultipleChoiceField( queryset=Category.objects.all(), required=False) contributors = FormFieldList(AuthorForm, required=False) contributor_ids = forms.ModelMultipleChoiceField( queryset=Author.objects.all(), required=False) feeds = forms.ModelMultipleChoiceField(queryset=Feed.objects.all(), required=False) categories = FormFieldList(CategoryForm, required=False) title = forms.CharField(max_length=255) summary = forms.CharField(required=False) content = forms.CharField(required=False) acquisitions = FormFieldList(AcquisitionForm, required=False) identifiers = DictionaryField( required=False, validators=[AvailableKeysValidator(keys=settings.OPDS['IDENTIFIERS'])], value_field=forms.CharField(max_length=100)) image = ImageField(max_length=settings.OPDS['IMAGE_UPLOAD_MAX_SIZE'], mime=settings.OPDS['IMAGE_MIME'], required=False) def clean_language_code(self) -> Language: language = Language.objects.filter( Q(alpha2=self.cleaned_data['language_code']) | Q(alpha3=self.cleaned_data['language_code'])).first() if not language: raise ValidationError( "Language not found. Use valid alpha2 or alpha3 code.", 'not-found') return language def clean(self): if 'author_id' in self.cleaned_data.keys( ) and 'author' in self.cleaned_data.keys(): raise ValidationError( _("You have to provide author_id or author object (not both)"), 'invalid') if 'category_ids' in self.cleaned_data.keys( ) and 'categories' in self.cleaned_data.keys(): raise ValidationError( _("You have to provide category_ids or categories object (not both)" ), 'invalid') if 'contributor_ids' in self.cleaned_data.keys( ) and 'contributors' in self.cleaned_data.keys(): raise ValidationError( _("You have to provide contributor_ids or contributors object (not both)" ), 'invalid') return self.cleaned_data