2013-02-19 46 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