Specify configuration settings per pytest test


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'

def test_2(config):
    config.foo = 'bleh'

Asked By: Greg



I ended up using monkeypatch and going with this approach:

from my_library.settings import Config

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')

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.

Answered By: Greg

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

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!

Answered By: rc.adhikari
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.