2013-02-19 38 views
1

想我已经用了单元测试,形式将验证文件格式的表格:如何使用Django的单元测试图像领域

class QForm(forms.ModelForm): 
    error_messages = { 
    'title_too_short': 'Title is too short', 
    'invalid_image_format': 'Invalid image format: Only jpg, gif and png are allowed', 
    } 

    VALID_IMAGE_FORMATS = ('jpg', 'gif', 'png') 

    title = forms.CharField(label="Title") 

    pic = forms.CharField(label="Picture") 

    class Meta: 
     model = Q 
     fields = ("title",) 

    def clean_title(self): 
     title = self.cleaned_data["title"] 
     if len(title) < 11: 
      raise forms.ValidationError(self.error_messages['title_too_short']) 
     return title 

    def clean_pic(self): 
     pic = self.cleaned_data["pic"] 
     if pic: 
      from django.core.files.images import get_image_dimensions 
      if not pic.content_type in VALID_IMAGE_FORMATS: 
       raise forms.ValidationError(self.error_messages['invalid_image_format']) 

     return pic 

我试着写一个单元测试,但它总是返回此错误:

AttributeError: 'unicode' object has no attribute 'content_type' 

而且我的单元测试是这样的:

class FormTests(TestCase): 
    def test_add(self): 
     upload_file = open(os.path.join(settings.PROJECT_ROOT, 'static/img/pier.jpg'), "rb") 
     data = { 
      'title': 'Test', 
      'pic': SimpleUploadedFile(upload_file.name, upload_file.read()) 
     } 

     q = QForm(data) 

     self.assertEqual(q.is_valid(), True) 

只是想知道正在使用错误的方法来上传我一份文件?

谢谢。

+0

其实我发现了这个问题。我把图像字段作为字符字段。这解决了unicode问题,但现在我面临的形式总是返回False,它看起来像它永远不会调用clean_pic函数。 – 2013-02-19 04:12:32

回答

3

如果您使用表单处理文件,则需要传递给构造函数的单独的files值。看到这里Django文档:

https://docs.djangoproject.com/en/dev/ref/forms/api/#binding-uploaded-files-to-a-form

class FormTests(TestCase): 
    def test_add(self): 
     upload_file = open(os.path.join(settings.PROJECT_ROOT, 'static/img/pier.jpg'), "rb") 
     data = { 
      'title': 'Test', 
     } 
     file_data = { 
      'pic': upload_file 
     } 

     q = QForm(data, file_data) 

     self.assertEqual(q.is_valid(), True) 
+0

我试过,但仍然给我这个错误:你上传的文件不是图像或损坏的图像。 – 2013-02-23 10:50:33

+0

只记得你不需要做任何特殊的文件,一个普通的python文件就可以工作。更新我的答案。 – 2013-02-23 23:37:44

+0

它仍然不起作用。它返回:

  • pic
    • 未提交任何文件。检查表单上的编码类型。
2013-03-02 19:21:16