2014-11-03 53 views
2

如果上传的文件包含不在硬编码列表中的扩展名,我有一个基本模型字段验证程序以引发ValidationError。测试不会引发Django模型字段上的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() 
+0

你在哪里希望错误得到提升? – 2014-11-03 19:56:44

+0

好问题。我想在ClientTest的setUp函数中。 – 2014-11-03 19:57:28

+0

此外,这个问题暗示我使用类似.txt而不是.png显然。 – 2014-11-03 20:11:17

回答

7

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

啊。那么你会说我正在接近模型字段验证吗?这是我想用于其他模型的验证器。 – 2014-11-03 20:27:46