0

我正在尝试测试包含 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())
4

1 回答 1

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))
于 2013-11-05T20:35:14.580 回答