I set up ~100 unit test for a django app, and later realized each unit test run was creating test users in my local database, instead of the test database. Any idea why?
apps/user/tests/factories.py
class CompanyFactory(factory.django.DjangoModelFactory):
class Meta:
model = Company
title = fake.name()
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
auth0_id = fake.random_number()
email = "unit_test_user@cart.com"
company = SubFactory(CompanyFactory)
When running a test that uses the factory like this, fake users are being persisted in the local DB:
Anyone know why this behavior might be happening?
Here's what my database looks like in local settings:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": "mia",
"USER": "mia_dev",
"PASSWORD": "test123",
"HOST": "localhost",
"PORT": 5432,
}
}
And the unit tests appears to be using the right database during the test run, appending "test" to the existing local db:
(Pdb) from django.db import connection
(Pdb) connection.settings_dict['NAME']
'test_mia'
factory.django.DjangoModelFactory
it uses the default databasedjango.db.DEFAULT_DB_ALIAS
because you don't specify the test database inMeta
. Not quite sure why inheriting fromfactory.Factory
solves your problem though.