想我已經用了單元測試,形式將驗證文件格式的表格:如何使用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)
只是想知道正在使用錯誤的方法來上傳我一份文件?
謝謝。
其實我發現了這個問題。我把圖像字段作爲字符字段。這解決了unicode問題,但現在我面臨的形式總是返回False,它看起來像它永遠不會調用clean_pic函數。 – 2013-02-19 04:12:32