我需要解释工作assertRedirects函数。我的看法:
def login_view(request):
if request.user.is_authenticated:
return redirect('account:profile')
else:
form = UserLoginForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
cd = form.cleaned_data
user = authenticate(username=cd['username'],
password=cd['password'])
if user is None:
messages.error(request,
'something.')
else:
if user.is_active:
login(request, user)
next_url = request.POST.get('next',
reverse('account:profile'))
return HttpResponseRedirect(next_url)
else:
messages.error(request,
'something')
else:
messages.error(request, 'something.')
context = {'form': form,
'next': request.GET.get('next')}
return render(request, 'account/login.html', context)
现在我写了2个测试。
def test_login_view_valid_data_username(self):
path = reverse('account:login')
response = self.client.post(path=path,
data={'username': 'test123',
'password': 'everything123'})
# is logged
self.assertTrue(self.user.is_authenticated)
# is redirect and good redirected
self.assertRedirects(response, reverse('account:profile'))
我的观点通过了这项测试。我的第二项测试:
def test_redirect_url_if_not_login(self):
path = '{}?next={}'.format(reverse('account:login'),
reverse('orders:create'))
response = self.client.post(path=path,
data={'username': 'test123',
'password': 'everything123',
'next': reverse('orders:create')})
print('RESPONSE CODE', response.status_code)
print('RESPONSE URL', response.url)
self.assertRedirects(response, reverse('orders:create'))
在这里我有问题。我收到错误消息:
AssertionError:302!= 200:无法检索重定向页面'/ orders / create /':响应代码为302(预期为200)
但是我的响应代码和响应url可以正确转换路径。我有点困惑,因为这不是第一种情况。有正式的解释吗?
编辑:
@login_required
def create_view(request):
cart = Cart(request)
if len(cart) == 0 or not cart:
return redirect('shop:overview')
if request.method == 'POST':
form = OrderCreateForm(request.POST)
if form.is_valid():
order = form.save(commit=False)
order.user = request.user
order.save()
for item in cart:
OrderItem.objects.create(order=order,
product=item['product'],
price=item['price'],
quantity=item['quantity'])
cart.clear()
return redirect('orders:payment', id=order.id)
else:
data = model_to_dict(request.user.shippingdetails)
form = OrderCreateForm(data)
return render(request, 'orders/create.html', {'cart': cart,
'form': form})
感谢您的回答
马格努斯
答案 0 :(得分:0)
默认情况下,assertRedirects
获取目标URL并期望其状态为200。
在您的情况下,您的视图将重定向到1.
,然后重定向到/orders/create/
。您可以设置/
来阻止测试客户端获取fetch_redirect_response=False
,也可以设置/orders/create/
。