我有以下单元测试,并且无法弄清楚为什么失败(如果删除if(request.META.get('HTTP_REFERER') != request.build_absolute_uri(reverse('page1'))):
,则测试通过),尽管我无法弄清楚如何使测试仍然通过。
def test_redirects_after_POST(self):
user = User.objects.create_superuser('username')
self.client.force_login(user)
response = self.client.post(
reverse('page1'), data={
'first_name': 'testuser',
'dob': UnitTest.set_age(20)}
)
self.assertRedirects(response, reverse('page2'))
我尝试添加它,但这没有帮助:
referer = 'http://testserver{}'.format(reverse('page1'))
# Also tried: referer = 'http://testserver{}'.format(reverse('page2'))
response = self.client.post(
reverse('page1'), data={
'first_name': 'testuser',
'dob': UnitTest.set_age(20)}
, HTTP_REFERER=referer)
@login_required
@allowed_users(allowed_roles=['admin', 'registered_user'])
def page1(request):
if request.method == 'POST':
form = Page1Form(request.POST, request.FILES, instance=request.user.page1)
if form.is_valid():
form.save()
return redirect('page2')
else:
form = Page1Form(instance=request.user.page1)
context = {
'form' : form,
}
return render(request, 'website/page1.html', context)
@login_required
@allowed_users(allowed_roles=['admin', 'registered_user'])
def page2(request):
if request.method == 'POST':
form = Page2Form(request.POST, request.FILES, instance=request.user.page2)
if form.is_valid():
form.save()
return redirect('page3')
else:
# redirect if user didnt access the page from page1
if(request.META.get('HTTP_REFERER') != request.build_absolute_uri(reverse('page1'))):
return redirect('page1')
else:
form = Page2Form(instance=request.user.page2)
context = {
'form' : form
}
return render(request, 'website/page2.html', context)
AssertionError: 302 != 200 : Couldn't retrieve redirection page '/website/page2/': response code was 302 (expected 200)
答案 0 :(得分:3)
您的请求成功,但测试失败,因为您输入了错误的expectations:
如果您的请求使用了follow参数,则Expected_url和target_status_code将是重定向链最后一点的url和状态代码。
但是,您的请求未设置为true,因为它的默认值为false。