I’m finding that when a TestCase is constructed, an <User: AnonymousUser> is automatically created in the test database. This was discovered when I queried all users with get_user_model().objects.all()
within multiple TestCases that I have written; it is also considered a type of User oddly enough (see below)
class TestUserProfileContext(TestCase):
@classmethod
def setUpTestData(cls):
cls.viewed_user = get_user_model().objects.create_user("ItsYou")
request = RequestFactory().get(reverse("authors:profile", kwargs={'id': 1}))
cls.view = UserProfilePage()
cls.view.setup(request, id=1)
cls.view_context = cls.view.get_context_data()
stored_users = get_user_model().objects.all()
print(stored_users)
def test_viewed_profile_of_user(self):
self.assertIsInstance(self.view, Page)
self.assertIn('user', self.view_context)
self.assertEqual(self.view_context['object'], self.viewed_user)
-> stored_users = get_user_model().objects.all()
(Pdb) n
> c:\..\authors\test\test_views.py(129)setUpTestData()
-> print(stored_users)
(Pdb) n
<QuerySet [<User: AnonymousUser>, <User: ItsYou>]>
--Return--
> c:\..\authors\test\test_views.py(129)setUpTestData()->None
-> print(stored_users)
(Pdb) anon_user = stored_users[0]
(Pdb) type(anon_user)
<class 'authors.models.User'>
To address the User model, I have created a custom User:
class User(AbstractUser):
username = CharField(
unique=True, max_length=16,
error_messages={
"unique": "Username not available"
}
)
Upon investigating further, I queried all users in python manage.py shell
. The queryset returned in fact included <User: AnonymousUser>
, and I deleted it from within the shell.
(venv) λ python manage.py shell
Python 3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021, 15:26:21) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth import get_user_model
>>> get_user_model().objects.all()
<QuerySet [<User: Python$!>, <User: y_i_am_nobody>, <User: User_00B>, <User: BinnyBot>, <User: supreextreme>, <User: AnonymousUser>, <User: itsmedummy>, <User: itsmestupid>]>
After deleting the anonymous user, my test cases still have <User: AnonymousUser>
when querying the User model. Why is the AnonymousUser being stored in the test database and how can I resolve this so it’s no longer stored?