Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 787
Karol Zlot Avatar asked Oct 19 '25 10:10

Karol Zlot


1 Answers

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

like image 137
Karol Zlot Avatar answered Oct 22 '25 02:10

Karol Zlot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!