想我已经用了单元测试,形式将验证文件格式的表格:如何使用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