如果form.is_valid()如何测试重定向

时间:2019-04-12 15:05:58

标签: django django-testing

我已经构建了一个视图,该视图可以发布数据并重定向到联系人/成功。我的问题是如何使用assertRedirects测试重定向?

我的Views.py:

def emailView(request):
    form = ContactForm(request.POST)
    if form.is_valid():
        gender = form.cleaned_data['gender']
        first_name = form.cleaned_data['first_name']
        last_name = form.cleaned_data['last_name']
        gender = request.POST['gender']
        first_name = request.POST['first_name']
        last_name = request.POST['last_name']
        context = {
             'form': form,
        } 
    return redirect('success_contact')

'success_contact'重定向到URL'contact / success'。在我的tests.py中,我尝试过这种方式:

 form_data = {'gender': '1, 'first_name': 'Luke',
              'last_name': 'Skywalker'}
 form = ContactForm(form_data)
 response = self.client.post('/contact', form_data)
 self.assertRedirects(response, '/contact/success/',
                      status_code=302, target_status_code=200)

不幸的是,我刚遇到这个AssertationError:

 Traceback (most recent call last):
 File 
 "/Users/user/Django/contactproj/contact/tests/test_views.py", line 126, in test_view_form_valid
target_status_code=200)
 File "/Users/user/anaconda3/envs/contactproj/lib/python3.6/site-packages/django/test/testcases.py", line 283, in assertRedirects
% (response.status_code, status_code)

AssertionError: 301 != 302 : Response didn't redirect as expected: Response code was 301 (expected 302)

1 个答案:

答案 0 :(得分:1)

您在测试中发布到错误的URL,它应该是/contact/,并带有斜杠。更好的是,使用reverse()函数来查找URL。