pytest-dev / pytest-dev/pytest-django

django_db_setup not working as expected

Open
#394 1 comment 6 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
1.5k
Forks
367
PR merge metrics
No merged PRs in 30d

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the custom django_db_setup fixture and trace how django_db_blocker and settings.DATABASES interact with the existing database connection. Reproduce the test using the provided database setup commands and model operations; done means establishing whether changing the database name is supported and ensuring the tests consistently use test_db or documenting the expected setup.

Written by the indexing model from the issue text.

Assessment

Tech stack
django, mysql, python
Domain
backend, databases, testing
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.