pythonpython-3.xenvironment-variablespytestparametrized-testing

How to use `fixture` and `parametrize` to set environmental variable for pytest tests


I have pytest tests which result may depend on environmental variable. I want to test them for multiple values of this environmental variable.

I want to have only one fixture which sets this environment variable but I want to be able to configure those values for each test, not per fixture.

How can I do it?


Solution

  • It can be achieved by using fixtures with indirect parametrization:

    conftest.py

    import pytest, os
    
    @pytest.fixture(scope="function")
    def my_variable(request, monkeypatch):
        """Set MY_VARIABLE environment variable, this fixture must be used with `parametrize`"""
        monkeypatch.setenv("MY_VARIABLE", request.param)
        yield request.param
    

    test_something.py

    import pytest, os
    
    @pytest.mark.parametrize("my_variable", ["value1", "value2", "abc"], indirect=True)
    class TestSomethingClassTests:
        """a few test with the same `parametrize` values"""
    
        def test_aaa_1(self, my_variable):
            """test 1"""
            assert os.environ["MY_VARIABLE"] == my_variable
    
        def test_aaa_2(self, my_variable):
            """test 2"""
            assert True
    
    @pytest.mark.parametrize("my_variable", ["value2", "value5", "qwerty"], indirect=True)
    def test_bbb(my_variable):
        """test bbb"""
        assert os.environ["MY_VARIABLE"] == my_variable
    

    How it looks in VSCode:

    enter image description here