The user creation is using an email address as USERNAME_FIELD
and it is extracted from session and save in the form save()
. It seems it is not going further down to the redirection. How can I test the redirection in this case?
tests.py:
class RegistraionViewTest(TestCase):
valid_data = {
'email': '[email protected]',
'password1': 'test1234',
}
kwargs = {
'email': '[email protected]'
}
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'))
In views.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'))
In forms.py:
def save(self, **kwargs):
user = super(RegistrationForm, self).save(commit=False)
user.email = kwargs.pop('email')
user.save()
return user
It seems there is no url in the response in tests.py
. What went wrong here?
Your response may be a 500, not a 302, which would mean there is no Location header.
The call for request.session.get('email') will likely throw a KeyError, as your test does not appear to set the session['email'] field, and there is no default.
Note that when using a session in a test case, you need to assign it to a variable in the beginning, as in the example below (from Django Testing Tool docs):
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
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加