Django unit testing - authenticated user check in model method

I am using Django 3.2

I am trying to test a model that checks if a user is authenticated. The model code looks something like this:

class Foo(Model):
    def do_something(user, **kwargs):
        if user.is_authenticated():
            do_one_thing(user, **kwargs)

My test code looks something like this:

from model_bakery import baker
from django.contrib.auth import authenticate, get_user_model

User = get_user_model()

class FooModelTest(TestCase):
    def setUp(self):

        self.user1 = baker.make(User, username='testuser_1', password='testexample1', email='', is_active = True, is_superuser=False) 
        baker.make(User, username='testuser_2', password='testexample2', email='', is_active = True, is_superuser=True)         
        self.unauthorised_user = authenticate(username='testuser_2', password='wrongone')

    def test_user(self):
        self.assertTrue(self.user1.is_validated)  # why is this true? - I haven't "logged in" yet?
        self.assertFalse(self.unauthorised.is_validated) # Barfs here since authenticate returned a None

So, How am I to mock an unauthenticated user, for testing purposes? - since it appears that the is_authenticated property is read only?

[[ Update ]]

I've just done a little more research + testing, and it looks like the solution to this would be to use AnnonymousUser as follows:

from django.contrib.auth.models import AnonymousUser

self.unaunthorised_user = AnonymousUser()

I am waiting to see if someone can confirm this (preferably, with a link to documentation)

Back to Top