Search code examples
djangodjango-testing

Problems testing user verification view


I'm writing tests for my user verification view and I faced some problem that I don't know how to solve yet. So, here is a view I'm testing:

def verify(request, uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=uid)
    except(TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None
    if user is not None and account_activation_token.check_token(user, token):
        user.is_verified = True
        user.save()
        print(user.is_verified)
        return HttpResponse('Your account was activated!')
    else:
        return HttpResponse('Activation link is invalid!')

It's working fine when I run server and user gets his is_activated set to True

But, here is a test:

    def test_new_user_verification(self):
        new_user = User.objects.create_user('[email protected]', 'Abc1234567')
        # visit activation link
        link = reverse('verify',
                       kwargs={'uidb64': urlsafe_base64_encode(force_bytes(new_user.pk)).decode(),
                               'token': account_activation_token.make_token(new_user)})
        resp = self.client.get(link)

        self.assertEqual(resp.status_code, 200)
        self.assertTrue(new_user.is_verified) 

First test passes fine, but the second one fails because in the test new_user.is_verified equals to False. I don't get why is that, when I add print(user.is_verified) to the view, it prints True, but in test it's False.

Any ideas why?


Solution

  • You need to refresh the object after performing the validation:

    resp = self.client.get(link)
    
    new_user.refresh_from_db()
    

    The reason is that it is a simple value field. Such non-deferred fields do not refresh from the database automatically after the object has been created/retrieved. In other words, the value is what it was set to initially in create_user. To get the new value you have to refresh it.

    Refer to the documentation.