Reputation: 668
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 = "[email protected]"
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'
Upvotes: 1
Views: 697
Reputation: 668
For those seeing this issue in the future, this was the problem:
class SignUpTokenFactory(factory.django.DjangoModelFactory):
class Meta:
model = SignUpToken
token = fake.random_number()
user = UserFactory()
There was another factory elsewhere creating and assigning an instance of the User class. This should've been user = Subfactory(UserFactory)
Upvotes: 1