简体   繁体   English

如何使用 `fixture` 和 `parametrize` 为 pytest 测试设置环境变量

[英]How to use `fixture` and `parametrize` to set environmental variable for pytest tests

I have pytest tests which result may depend on environmental variable.我有 pytest 测试,结果可能取决于环境变量。 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?我该怎么做?

It can be achieved by using fixtures with indirect parametrization:它可以通过使用具有间接参数化的夹具来实现:

conftest.py

import pytest, os

@pytest.fixture(scope="function")
def my_variable(request):
    """Set MY_VARIABLE environment variable, this fixture must be used with `parametrize`"""
    os.environ["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:它在 VSCode 中的外观:

在此处输入图像描述

Try this in conftest.py :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:使用--env=xxx作为命令行参数运行测试:

python -m pytest foo_test.py --env=sit

Use the env variable in the test在测试中使用env变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM