pytest-django icon indicating copy to clipboard operation
pytest-django copied to clipboard

django_db_setup not working as expected

Open afosterw opened this issue 9 years ago • 1 comments
trafficstars

I'm not sure if this is a bug or if I'm just not understanding how django_db_setup is supposed to work:

I'm attempting to load a .sql file into the test database and then use that database for the tests.

I am able to do all of that with no problem.

def django_db_setup(django_db_modify_db_settings, django_db_keepdb, django_db_use_migrations, django_db_blocker):
    with django_db_blocker.unblock():
        settings.DATABASES['NAME'] = 'test_db'
        if not django_db_keepdb:
            print(subprocess.check_output('echo "DROP DATABASE IF EXISTS test_$MYSQL_NAME;" | mysql -h$MYSQL_HOST -u$MYSQL_USER -p$MYSQL_PASSWORD', shell=True))
            print(subprocess.check_output('echo "CREATE DATABASE test_$MYSQL_NAME;" | mysql -h$MYSQL_HOST -u$MYSQL_USER -p$MYSQL_PASSWORD', shell=True))
            print(subprocess.check_output('cat ./tests/data/sql/test_db.sql | mysql -h$MYSQL_HOST -u$MYSQL_USER -p$MYSQL_PASSWORD test_$MYSQL_NAME', shell=True))
        if django_db_use_migrations:
             print(subprocess.check_output('../scripts/migrate_test_db.sh --no-load', shell=True))

This all works as expected. When I print the settings from the tests the database name is correct.

However when I create or use models in tests they use the original database connection that points at the normal database.

Is this the expected behavior? I assumed that overriding the database name in the settings would ensure that database is the one used in all of the tests.

afosterw avatar Sep 12 '16 14:09 afosterw

I am also trying to use django_db_setup to override the database Django uses so that Django runs a test database. However, what I observe is that django_db_setup is called AFTER Django settings are loaded. So, it has no effect. Am I missing something? Surely, you should be able to set the test database dynamically. Is there another fixture I should be using? I have tried several, all to no avail.

swehba avatar Jun 06 '22 22:06 swehba