测试包含ImageField的表单导致类型错误

时间:2013-11-05 20:28:06

标签: django django-forms

我正在尝试测试包含ImageField的表单,但是我收到了错误。我试过单步执行Django代码,但我一直迷路,我看不出问题。我已经研究过如何做到这一点,我认为我正在做正确的事情。

以下是我的测试中assertTrue语句发生的错误:

TypeError: is_valid() takes exactly 2 arguments (1 given)

以下是我的文件:

# forms.py
class UploadMainPhotoForm(forms.Form):
    photo = forms.ImageField(error_messages={'required': err_msg__did_not_choose_photo})

    def is_valid(self, request):

        # Run parent validation first
        valid = super(UploadMainPhotoForm, self).is_valid()
        if not valid:
            return valid

        if request.FILES:
            photo_file = request.FILES['photo']
            file_name, file_ext = os.path.splitext(photo_file.name)
        else:
            self._errors['photo'] = 'You forgot to select a photo.'
            return False

        # Return an error if the photo file has no extension
        if not file_ext:
            self._errors['photo'] = err_msg__photo_file_must_be_jpeg
            return False

        return True

# upload_photo.html (template)
<form method="post" enctype="multipart/form-data" action=".">{% csrf_token %}
    <input type="file" name="photo" />
    <input type="submit" name="skip_photo" value="Skip Photo" />
    <input type="submit" name="upload_photo" value="Upload Photo">
</form>

# form_tests.py
class TestUploadMainPhotoForm(TestCase):
    def initial_test(self):
        post_inputs = {'upload_photo': '[Upload Photo]'}
        test_photo = open('photo.jpg', 'rb')
        file_data = {'file': SimpleUploadedFile(test_photo.name, test_photo.read())}
        self.assertTrue(UploadMainPhotoForm(post_inputs, file_data).is_valid())

1 个答案:

答案 0 :(得分:0)

下面:

 def is_valid(self, request):

您已使用参数is_valid定义request方法并在调用时

self.assertTrue(UploadMainPhotoForm(post_inputs, file_data).is_valid())

您尚未指定参数。因此错误。

您可以使用RequestFactory获取单元测试中的request对象。

from django.utils import unittest
from django.test.client import RequestFactory

class TestUploadMainPhotoForm(TestCase):
    def setUp(self):
        self.request = RequestFactory()

    def initial_test(self):
        post_inputs = {'upload_photo': '[Upload Photo]'}
        test_photo = open('photo.jpg', 'rb')
        file_data = {'file': SimpleUploadedFile(test_photo.name, test_photo.read())}
        self.assertTrue(UploadMainPhotoForm(post_inputs, file_data).is_valid(self.request))