Skip to content

Customising django_db_modify_db_settings is superseeded by Django's own caching. #643

Open
@cameronmaske

Description

@cameronmaske

Hey all,

I ran into an issue trying to customize django_db_modify_db_settings.

In my root level conftest.py I tried to make the tests run a sqlite in-memory database using (instead of my project settings.py which point to a postgres database).

@pytest.fixture(scope='session')
def django_db_modify_db_settings():
    from django.conf import settings
    settings.DATABASES = {
        'default': {
            'ENGINE':'django.db.backends.sqlite3',
            'NAME': ':memory:'
        }
    }

However, when the tests were run, any database interaction (Model's get, create, etc) would attempt to reach out to the original postgres database setting (aka

Doing a bit of digging, I think I can see what is happening.

When setup_databases (from here) is called, it in turn calls:

After ConnectionHandler is initalized, which I believe is at django.setup() it is fixed and stays pointed to whatever database settings it initalized with, even if they change down the line.

My current work around to this, is to override the DATABASE settings in my own pytest_configure in my project's conftest.py AND to set DJANGO_SETTINGS_MODULE there (e.g. no pytest.ini).
e.g.

os.environ['DJANGO_SETTINGS_MODULE'] = 'app.config.settings'

def pytest_configure():
   settings.DATABASES = {
        'default': {
            'ENGINE':'django.db.backends.sqlite3',
            'NAME': ':memory:'
        }
    }

I believe setting the DJANGO_SETTINGS_MODULE there causes the _setup_django in pytest_load_initial_conftests to be skipped over, thus the it is called later, in the plugin's pytest_configure.

Resource:

Here is a sample project with it in action. It's a bit big, so here are the important bits.

I'm using Python: 3.6.6 and the following package versions...

Django==2.1
pytest==3.7.4
pytest-django==3.0.0

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions