用户创建使用电子邮件地址作为USERNAME_FIELD
,它从会话中提取并保存为save()
形式。它似乎不会进一步归结为重定向。在这种情况下,我如何测试重定向?
测试.py:
class RegistraionViewTest(TestCase):
valid_data = {
'email': 'good@day.com',
'password1': 'test1234',
}
kwargs = {
'email': 'good@day.com'
}
def test_registration(self):
response = self.client.post(reverse('registration'), data=self.valid_data, follow=True)
self.assertTrue(response.context['form'].is_valid())
# mocking the session input
response.context['form'].save(email=self.kwargs['email'])
self.assertTrue(account.check_password(self.valid_data['password1']))
# working so far, but it seems there is no redirect url in response
self.assertRedirects(response, reverse('next_url'))
在视图中.py:
if request.method == 'POST':
form = RegistraionForm(request.POST)
if form.is_valid():
email = request.session.get('email')
try:
account = form.save(email=email)
return HttpResponseRedirect('next_url'))
形式.py:
def save(self, **kwargs):
user = super(RegistrationForm, self).save(commit=False)
user.email = kwargs.pop('email')
user.save()
return user
tests.py
中的响应中似乎没有url。这里出了什么问题?
您的响应可能是500,而不是302,这意味着没有Location标头。
request.seession.get('email'(的调用可能会抛出KeyError,因为您的测试似乎没有设置session['email']字段,并且没有默认值。
请注意,当在测试用例中使用会话时,您需要在开始时将其分配给一个变量,如下例所示(来自Django Testing Tool文档(:
def test_registration(self):
session = self.client.session
session['email'] = self.kwargs['email']
session.save()
# and now make your call to self.client.post
response = self.client.post(...)
self.assertEqual(response.status_code,302)
# .. and the rest