On , I learnt ...
How to override Django’s settings for every method in a test class
Django’s override_settings
decorator only works on
functions and methods in subclasses of unittest.TestCase
.
But it’s common to group tests in plain Python classes when using Pytest, which
means override_settings
can’t be used to decorate a class and override
settings for every test method.
Instead, do this with an autouse=True
fixture and the settings
fixture provided by the pytest-django
package.
For example:
import pytest
from django.conf import settings as django_settings
class TestAutouseFixture:
@pytest.fixture(autouse=True)
def configure_settings(self, settings):
# The `settings` argument is a fixture provided by pytest-django.
settings.FOO = "bar"
def test_one(self):
assert django_settings.FOO == "bar"
def test_two(self):
assert django_settings.FOO == "bar"
🤦♂️ Oops — turns out I learnt this
last year too,
although my example then used override_settings
as a context manager.