如何测试clean_ <fieldname>方法?

时间:2019-01-21 12:53:11

标签: django django-forms django-testing

我尝试为我的clean_方法编写测试。

这是我测试的代码

def test_clean_restraints(self):
    form = NewTaskForm(dict(restraints="90 20 <>"))
    form.clean_restraints()

在这一步,我收到一个错误:

Error
Traceback (most recent call last):
  File "/home/user/django_projects/my_webservice/tasks/tests/test_forms.py", line 12, in test_clean_restraints
    form.clean_restraints()
  File "/home/user/django_projects/my_webservice/tasks/forms.py", line 22, in clean_restraints
    if self.cleaned_data.get('restraints') == '':
AttributeError: 'NewTaskForm' object has no attribute 'cleaned_data'

NewTaskForm看起来像这样:

class NewTaskForm(ModelForm):
    class Meta:
        model = Task

    restraints = forms.CharField()
    region = forms.CharField()
    interactions = forms.CharField()

    def clean_restraints(self):
        if self.cleaned_data.get('restraints') == '':
            return self.cleaned_data.get('restraints')
        data = self.cleaned_data.get('restraints').strip().split('\n')
        regexp = re.compile(r'^(\d+)[\t ]+(\d+)[ \t]+([><]{2})?$')
        cleaned_data = []
        for i, line in enumerate(data):
            match = regexp.match(line)
            if not match:
                raise forms.ValidationError(f"Error in restraints in line {i + 1}")
            else:
                rst_1, rst_2, loop_type = match.groups()
                rst_1 = int(rst_1)
                rst_2 = int(rst_2)
                cleaned_data.append((rst_1, rst_2, loop_type))
        return cleaned_data

我正在使用Django 2.1,python 3.7.1,PyCharm 2018.3.3 Professional 我试图在PyCharm中的调试器下运行它,但是事情变得疯狂了。我收到其他错误消息。看起来好像调试器在完全验证表单后忽略了断点而停止了。我不知道发生了什么。

2 个答案:

答案 0 :(得分:2)

您应该测试验证过程的结果。

form = NewTaskForm(dict(restraints="90 20 <>"))
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['restraints'], "Error in restraints in line 1")

答案 1 :(得分:0)

好,我发现了问题所在。

form.cleaned_datafull_clean()中创建。不像我想的那样在构造函数中。它还会调用每个clean_fieldname()。因此,丑陋的解决方法是这样的:

def test_clean_restraints(self):
    initial_data = dict(restraints="90 20 <>")
    form = NewTaskForm()
    form.cleaned_data = initial_data
    form.clean_restraints()
    (...)