Karol Zlot
Karol Zlot

Reputation: 4055

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?

Upvotes: 4

Views: 6998

Answers (2)

Karol Zlot
Karol Zlot

Reputation: 4055

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

Upvotes: 10

Devang Sanghani
Devang Sanghani

Reputation: 780

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

Upvotes: 0

Related Questions