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

How to patch settings attributes after fixtures will be loaded but before apps imports

Open mihalt opened this issue 2 years ago • 1 comments

So, I have few strings in settings.py like

DELIVERED_FILES_DIR = os.path.join(MEDIA_ROOT, 'csv_files')
INVOICES_DIR = os.path.join(MEDIA_ROOT, 'invoices')

I use them in few parts of my app. When I created test, I wanted to patch them by manual like

@pytest.fixture
def change_paths(settings, tmp_path):
    settings.DELIVERED_FILES_DIR = tmp_path
    settings.INVOICES_DIR = tmp_path

But it does nothing because settings attributes where already imported before running a code from test, if I understand correct.

I tried to use

@pytest.hookimpl(tryfirst=True)
def pytest_load_initial_conftests(early_config, parser, settings, tmp_path, args):
    settings.DELIVERED_FILES_DIR = tmp_path
    settings.INVOICES_DIR = tmp_path

and got Argument(s) {'settings', 'tmp_path'} are declared in the hookimpl but can not be found in the hookspec

With session scoped fixtures I got error lik ScopeMismatch: You tried to access the function scoped fixtures settings, tmp_path with a session scoped request object, involved factories:

So, would like to know how can I achieve my goals.

mihalt avatar Apr 08 '23 15:04 mihalt

I ran into this just now.

My niche anecdote with TEMPLATES

settings.TEMPLATES, post-initialization is effectively immutable.

Editing settings.TEMPLATES directly before rendering won't change what views use EngineHandler (its cached library/registry object)

I went from directly use DJANGO_SETTINGS_MODULE to going to pytest_configure to initialize settings, and I found that I can't use DIRS + tmp_path derived fixtures when running settings.configure().

The only choice may end up being having pre-determined .gitignore'd / temporary directory for writing temporary files to, but it may not end up being pytest's own temporary directory fixtures.

tony avatar Oct 29 '23 10:10 tony