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

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

最佳答案

参见 documentation on model validators :

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

你需要手动调用它们:

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 模型字段上引发 ValidationError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26721989/

相关文章:

unit-testing - Cognos 上的自动化单元测试是否可行?

angularjs - Karma-Coverage 和 Istanbul HTML 报告未输出到预期目录

python - 当我使用Thrift将C++中的映射序列化到磁盘,然后使用Python反序列化时,我没有得到相同的对象

python - 获取 numpy 二维数组中与零相邻的所有元素的索引

python - 自定义选项卡中的 Django admin StackedInline

python - 如何使用枚举或字符串进行过滤并获得相同的结果?

unit-testing - 生产中的 NJasmine

python - 管理日常购物 list , 'list' 对象不可调用

python - 使用 python-pptx 创建 PPT 时如何使用我公司的 PPT 幻灯片布局?

python - 如何替换或编辑 django rest 框架路由器中的查找参数?