我有 pytest 测试,其结果可能取决于环境变量。我想测试它们是否有这个环境变量的多个值。
我只想拥有一个设置此环境变量的夹具,但我希望能够为每个测试配置这些值,而不是每个夹具。
我该怎么做?
我有 pytest 测试,其结果可能取决于环境变量。我想测试它们是否有这个环境变量的多个值。
我只想拥有一个设置此环境变量的夹具,但我希望能够为每个测试配置这些值,而不是每个夹具。
我该怎么做?
它可以通过使用具有间接参数化的夹具来实现:
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 中的外观:
试试这个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")
--env=xxx
使用命令行参数运行测试:
python -m pytest foo_test.py --env=sit
在测试中使用env
变量