Reputation: 313
I manage my configuration for a Python application with https://github.com/theskumar/python-dotenv and I use pytest
for my tests.
For a particular set of tests, I want custom configuration specific to each test. Now I know of https://github.com/quiqua/pytest-dotenv, which gives me the ability to set a config per environment (prod/test), but I want finer granularity on a per-test basis. So far, I've handled this by mocking the Config
object that contains all of my configuration. This is messy because for each test, I need to mock this Config
object for each module where it's loaded.
Ideally, I'd have something like this:
def test_1(config):
config.foo = 'bar'
run_code_that_uses_config()
def test_2(config):
config.foo = 'bleh'
run_code_that_uses_config()
Upvotes: 1
Views: 2407
Reputation: 2222
I had similar situation, however I set as a config variable and use the current_app
to modify at the test, for eg.
import pytest
from flask import current_app
@pytest.mark.usefixtures(...)
def test_my_method(client, session)
# Initially, it was False, but I modified here as True
current_app.config['MY_CONFIG_VARIABLE'] = True
...
# Then, do your test here
Hope it helps!
Upvotes: 0
Reputation: 313
I ended up using monkeypatch
and going with this approach:
from my_library.settings import Config
@pytest.fixture
def config(monkeypatch):
monkeypatch.setattr(Config, 'foo', 'bar')
return Config
def test_1(config, monkeypatch):
monkeypatch.setattr(config, 'foo', 'some value specific to this test')
run_code_that_uses_config()
With monkeypatch
I was able to pass around the Config
object via a pytest fixture to create a default and override it for each test. The code that uses the config was able to pick up the change. Previously, I'd used patch
from the standard mock
library, but I had to patch every single place where the config was looked up (https://docs.python.org/3/library/unittest.mock.html#where-to-patch), which made maintenance difficult.
Upvotes: 2