3

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?

Karol Zlot
  • 2,887
  • 2
  • 20
  • 37

2 Answers2

8

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

Karol Zlot
  • 2,887
  • 2
  • 20
  • 37
  • 2
    Better use `monkeypatch.setenv`, this will revert the environment change after the test. This may not matter in your case, but is generally good practice to avoid side effects from the tests. – MrBean Bremen Jan 24 '22 at 07:37
  • @MrBeanBremen Thank you, I modified my answer so `monkeypatch.setenv` is used. – Karol Zlot Jan 24 '22 at 20:52
0

Try this in conftest.py:

def pytest_addoption(parser):
    parser.addoption("--env", action="store", default="sit")


@pytest.fixture(scope="session")
def env(request):
   return request.config.getoption("--env")

Run the tests with --env=xxx as the command line argument:

python -m pytest foo_test.py --env=sit

Use the env variable in the test

Devang Sanghani
  • 731
  • 5
  • 14