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

标签 python python-3.x environment-variables pytest parametrized-testing

我有 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 中的样子:

enter image description here

关于python - 如何使用 `fixture` 和 `parametrize` 为 pytest 测试设置环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70829370/

相关文章:

python - 在 Python Pandas 中将月份和日期保留为日期格式

python - 使用 Tortoise-ORM 在 FastAPI 中进行测试

python-3.x - 属性错误: module 'tensorflow.app' has no attribute 'flags'

python - 打印家庭表情符号,使用 U+200D 零宽度连接符,直接打印,对比通过列表

variables - ansible docker env var 在容器中不可用

linux - 需要相当于 windows "echo %date% %time% %COMPUTERNAME%"的 linux

tomcat - 从 context.xml 获取 catalina.base 环境变量值

python - 确定天空中的 eclipse

python - 创建不同类型的嵌套列表的快速方法: numpy, pandas或列表串联?

python - Python的多处理池完成后未释放内存