python - Test doesn't raise ValidationError on Django model field -
i have basic model field validator raise validationerror if uploaded file contains extension not in hard-coded list.
the model form used administrative perspective. in tests, can't exception raise despite giving in invalid file extension. doing wrong?
validator:
import os django.core.exceptions import validationerror def validate_file_type(value): accepted_extensions = ['.png', '.jpg', '.jpeg', '.pdf'] extension = os.path.splitext(value.name)[1] if extension not in accepted_extensions: raise validationerror(u'{} not accepted file type'.format(value))
model:
from agency.utils.validators import validate_file_type django.db import models sorl.thumbnail import imagefield class client(models.model): """ past or current client of agency. """ logo = imagefield( help_text='please utilize jpg (jpeg) or png files only. resized \ public display.', upload_to='clients/logos', default='', validators=[validate_file_type]
test:
from django.test import testcase import tempfile import os settings import base of operations clients.models import client class clienttest(testcase): def setup(self): tempfile.tempdir = os.path.join(base.media_root, 'clients/logos') tf = tempfile.namedtemporaryfile(delete=false, suffix='.png') tf.close() self.logo = tf.name client.objects.create( name='coca-cola', logo=self.logo, website='http://us.coca-cola.com/home/' ) def test_can_create_client(self): client = client.objects.get(name='coca-cola') expected = 'coca-cola' self.assertequal(client.name, expected) def teardown(self): os.remove(self.logo) clients = client.objects.all() clients.delete()
see documentation on model validators:
note validators not run automatically when save model
you need phone call them manually:
client = client( name='coca-cola', logo=self.logo, website='http://us.coca-cola.com/home/' ) client.full_clean() client.logo = '#something invalid' self.assertraises(validationerror, client.full_clean))
python django unit-testing model
No comments:
Post a Comment