测试不会在Django模型字段上引发ValidationError

时间:2014-11-03 19:52:35

标签: python django unit-testing model

如果上传的文件包含不在硬编码列表中的扩展名,我有一个基本的模型字段验证器来引发ValidationError。

仅从管理角度使用模型表单。但是在我的测试中,尽管给出了无效的文件扩展名,但我无法获得异常。我做错了什么?

验证

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))

模型

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]

测试

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()

1 个答案:

答案 0 :(得分:9)

请参阅documentation on model validators

  

请注意,保存模型时不会自动运行验证程序

您需要手动调用它们:

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))