I'm writing a set of tests for methods of the object whose initialization may be altered by environment variables. I started by putting object creation into a fixture and making a bunch of tests
@pytest.fixture()
def my_object():
# Initialise and return my object
return new_object
def test_method_1(my_object): ...
def test_method_2(my_object): ... # etc.
One of the tests needs to check the object's behaviour with an environment variable set, so I naively wrote:
def test_method_with_env(my_object):
os.environ['VARIABLE'] = 'SPECIAL_VALUE'
assert my_object.method_under_test()
which obviously fails because the variable must be set during object initialization, not after it.
I also tried
@pytest.fixture
def patch_env(request):
marker = request.node.get_closest_marker('env')
if marker and marker.kwargs:
os.environ.update(marker.kwargs)
@pytest.mark.env(VARIABLE='SPECIAL_VALUE')
def test_method_with_env(patch_env, my_object):
assert my_object.method_under_test()
but that also fails, because there is no guarantee that patch_env
is applied before my_object
fixture.
In the end, I could make my_object
depend on patch_env
but I only need to modify the env variable for this one test, not all of them.
Is there any pytest-recommended way to go about it or am I misusing fixtures here?