0

我有 pytest 测试,其结果可能取决于环境变量。我想测试它们是否有这个环境变量的多个值。

我只想拥有一个设置此环境变量的夹具,但我希望能够为每个测试配置这些值,而不是每个夹具。

我该怎么做?

4

2 回答 2

0

它可以通过使用具有间接参数化的夹具来实现:

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 中的外观:

在此处输入图像描述

于 2022-01-24T05:29:00.410 回答
0

试试这个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变量

于 2022-01-24T08:50:31.377 回答