I am testing a class based view using mock to raise an exception. On exception, a message should be created and then a redirect executed. Whilst I am able to test that the redirect has been executed, I am unable as yet to retrieve the message to be able to verify it.
view
CustomUser = get_user_model()
class SignUpView(FormView):
template_name = 'accounts/signup.html'
form_class = SignUpForm
def form_valid(self, form):
try:
self.user = CustomUser.objects.filter(email=form.cleaned_data['email']).first()
if not self.user:
self.user = CustomUser.objects.create_user(email=form.cleaned_data['email'],
full_name=form.cleaned_data['full_name'],
password=form.cleaned_data['password'],
is_verified=False
)
else:
if self.user.is_verified:
self.send_reminder()
return super().form_valid(form)
self.send_code()
except:
messages.error(self.request, _('Something went wrong, please try to register again'))
return redirect(reverse('accounts:signup'))
return super().form_valid(form)
My test so far:
class SignUpViewTest(TestCase):
def setUp(self):
self.factory = RequestFactory()
def test_database_fail(self):
with patch.object(CustomUserManager, 'create_user') as mock_method:
mock_method.side_effect = Exception(ValueError)
view = SignUpView.as_view()
url = reverse('accounts:signup')
data = {'email': 'test@test.com', 'full_name': 'Test Tester', 'password': 'Abnm1234'}
request = self.factory.post(url, data)
setattr(request, 'session', 'session')
messages = FallbackStorage(request)
request._messages = messages
response = view(request)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.url, '/accounts/signup/')
My question is, how do I retrieve the message so that I can make an assertEqual against the message: 'Something went wrong, please try to register again'?
After digging a little deeper the message(s) can be found here:
request._messages._queued_messages[0]
And therefore the assertEqual would be:
self.assertEqual(str(request._messages._queued_messages[0]), 'Something went wrong, please try to register again')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.