我有 pytest 测试,结果可能取决于环境变量。我想针对此环境变量的多个值测试它们。
我只想拥有一个设置此环境变量的 fixture ,但我希望能够为每个测试配置这些值,而不是每个 fixture 。
我该怎么做?
最佳答案
可以通过使用具有间接参数化的 fixture 来实现:
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
它在 VSCode 中的样子:
关于python - 如何使用 `fixture` 和 `parametrize` 为 pytest 测试设置环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70829370/