跳过所有测试而不是用 @pytest.mark.skipif() 修饰每个测试函数?

问题描述 投票:0回答:2

我有一个 pytest 文件,需要设置环境。所以我在每个函数上添加以下装饰器。

@pytest.mark.skipif('password' not in os.environ,
                    reason='Environment variable "password" not set.')
def test_1(mock):
    ....

@pytest.mark.skipif('password' not in os.environ,
                    reason='Environment variable "password" not set.')
def test_2(mock):
    ....

@pytest.mark.skipif('password' not in os.environ,
                    reason='Environment variable "password" not set.')
def test_3(mock):
    ....

这是一种跳过所有测试而不是装饰每个测试函数的方法吗?

顺便说一句,它只是跳过测试并显示以下消息。有没有办法显示缺少环境变量的警告信息?

====== 25 skipped in 5.96s =======
python pytest
2个回答
3
投票

您可以使用具有

autouse=True
的夹具来为您进行跳跃:

@pytest.fixture(autouse=True)
def skip_if_no_password():
    if 'password' in os.environ:
        yield
    else:
        pytest.skip('Environment variable "password" not set.')

另一种可能性是将测试放入一个类中,然后将标记放在类上,正如 Luke Nelson 在评论中提到的那样。


0
投票

如果该条件适用于文件中的所有测试,您可以尝试此操作。

if 'password' not in os.environ:
  pytest.skip(allow_module_level=True, reason='Environment variable "password" not set.'

然后您可以使用

pytest -r s
运行以显示有关跳过的测试的信息。

参考:https://docs.pytest.org/en/stable/how-to/skipping.html#skipping-test-functions

© www.soinside.com 2019 - 2024. All rights reserved.