Parameterizing Django Settings with Pytest Fixtures

Parameterizing Django Settings with Pytest Fixtures

July 10, 2023 · 1 min · 352 words

I am currently working on a Django Rest Framework project and need a way to test different behaviors for a particular setting. After checking the pytest-django docs, I saw that the library provides a settings fixture - a great starting point.

Now, how do I parameterize this settings fixture? My first attempt, albeit wrong, was:

import pytest

@pytest.mark.parametrize("settings", [
    {"DEBUG": True},
    {"DEBUG": False}
])
def test_settings_debug(settings):
    print(settings)
    assert settings.DEBUG in (True, False)

This changes the settings fixture from type pytest_django.fixtures.SettingsWrapper into a dict, which isn’t the result I expected. But it’s a step in the right direction.

To achieve my intended result, I introduced two additional fixtures:

@pytest.fixture()
def custom_settings():
    return {}

@pytest.fixture(autouse=True)
def override_django_settings(custom_settings, settings):
    for k, v in custom_settings.items():
        setattr(settings, k, v)

@pytest.mark.parametrize("custom_settings", [
    {"DEBUG": True},
    {"DEBUG": False}
])
def test_settings_debug(settings):
    print(settings)
    assert settings.DEBUG in (True, False)

What do these fixtures do?

To learn more about pytest, check out their docs.