I am new to testing and need help testing a method in Django.
I have tried test the method using Client() and RequestFactory(), but because of the method’s reliance on other methods, I feel that it is easier to test the method in isolation. Here is the test:
class EmailVerificationViewTest(TestCase):
def setUp(self):
User = get_user_model()
self.view = EmailVerificationCode()
self.view.time_diff = Mock(return_value=False)
self.view.user_code = '0000000000'
self.view.code = '0000000000'
def test_library(self):
self.view.check_code()
The problem is that I keep getting an error whenever self.request is called:
user_record = User.objects.get(pk=self.request.user.pk)
AttributeError: 'EmailVerificationCode' object has no attribute 'request'
OR (depending whether time_diff is set to True or False)
messages.info(self.request,
AttributeError: 'EmailVerificationCode' object has no attribute 'request'
The class and method to be tested:
class EmailVerificationCode(OTPRequiredMixin, FormView):
def check_code(self):
try:
if self.time_diff():
if str(self.user_code) == str(self.code):
user_record = User.objects.get(pk=self.request.user.pk)
user_record.is_user_verified = True
user_record.save()
messages.success(self.request,
_('Your email has been verified - thank you'
))
return redirect(reverse('account:user_profile'))
else:
messages.error(self.request, mark_safe(_(
'Sorry, but your code did not match.'
)))
return redirect(reverse('account:verify_email_code'))
else:
messages.info(self.request,
mark_safe(_('Sorry, but your code has expired.<br>'
)))
return redirect(reverse('account:verify_email'))
except (AttributeError, ObjectDoesNotExist):
messages.warning(self.request,
mark_safe(_('We are very sorry, but something went wrong.
'Please try to login again'
)))
return redirect(reverse('two_factor:login'))
My question is, how do I mock the attribute ‘self.request’ so that the AttributeError’s listed above are not called?