Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test doesn't raise ValidationError on Django model field

I have a basic model field validator to raise a ValidationError if an uploaded file contains an extension not in a hard-coded list.

The model form will only be used from an administrative perspective. But in my tests, I can't get the exception to raise despite giving in an invalid file extension. What am I doing wrong?

Validator:

import os
from 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'{} is not an accepted file type'.format(value))

Model:

from agency.utils.validators import validate_file_type
from django.db import models
from sorl.thumbnail import ImageField


class Client(models.Model):
    """
    A past or current client of the agency.
    """
    logo = ImageField(
        help_text='Please use jpg (jpeg) or png files only. Will be resized \
            for public display.',
        upload_to='clients/logos',
        default='',
        validators=[validate_file_type]

Test:

from django.test import TestCase
import tempfile
import os
from settings import base
from 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()
like image 741
Patrick Beeson Avatar asked Nov 03 '14 19:11

Patrick Beeson


1 Answers

See the documentation on model validators:

Note that validators will not be run automatically when you save a model

You need to 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))
like image 82
Daniel Roseman Avatar answered Sep 30 '22 19:09

Daniel Roseman