在 pytest skip-if 条件中使用命令行选项 [英] Using a command-line option in a pytest skip-if condition

查看:84
本文介绍了在 pytest skip-if 条件中使用命令行选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

长话短说,如果会话是针对我们的生产 API 运行的,我希望能够跳过一些测试.运行测试的环境是使用命令行选项设置的.

Long story short, I want to be able to skip some tests if the session is being run against our production API. The environment that the tests are run against is set with a command-line option.

我想到了使用 pytest_namespace 来跟踪全局变量的想法,所以我在我的 conftest.py 文件中进行了设置.

I came across the idea of using the pytest_namespace to track global variables, so I set that up in my conftest.py file.

def pytest_namespace():
    return {'global_env': ''}

我接受命令行选项并在 conftest.py 的夹具中设置各种 API url(来自 config.ini 文件).

I take in the command line option and set various API urls (from a config.ini file) in a fixture in conftest.py.

@pytest.fixture(scope='session', autouse=True)
def configInfo(pytestconfig):
    global data
    environment = pytestconfig.getoption('--ENV')
    print(environment)
    environment = str.lower(environment)

    pytest.global_env = environment

    config = configparser.ConfigParser()
    config.read('config.ini') # local config file
    configData = config['QA-CONFIG']
    if environment == 'qa':
            configData = config['QA-CONFIG']
    if environment == 'prod':
            configData = config['PROD-CONFIG']

(...)

然后我有一个我想跳过的测试,它是这样装饰的:

Then I've got the test I want to skip, and it's decorated like so:

@pytest.mark.skipif(pytest.global_env in 'prod',
                reason="feature not in Prod yet")

然而,每当我对 prod 运行测试时,它们都不会被跳过.我做了一些摆弄,发现:

However, whenever I run the tests against prod, they don't get skipped. I did some fiddling around, and found that:

a) global_env 变量可以通过另一个设备访问

a) the global_env variable is accessible through another fixture

@pytest.fixture(scope="session", autouse=True)
def mod_header(request):
    log.info('\n-----\n| '+pytest.global_env+' |\n-----\n')

在我的日志中正确显示

b) global_env 变量可在测试中访问,正确记录环境.

b) the global_env variable is accessible in a test, correctly logging the env.

c) pytest_namespace 已弃用

所以,我假设这与skipif 何时访问global_env 与夹具在测试会话中何时访问有关.我还发现使用已弃用的功能并不理想.

So, I'm assuming this has to do with when the skipif accesses that global_env vs. when the fixtures do in the test session. I also find it non-ideal to use a deprecated functionality.

我的问题是:

  • 如何从 pytest 命令行选项中获取值到 skipif 中?
  • 有没有比 pytest_namespace 更好的尝试方法?
  • how do I get a value from the pytest command line option into a skipif?
  • Is there a better way to be trying this than the pytest_namespace?

推荐答案

看起来像 根据命令行选项控制跳过测试是动态标记测试为skip:

Looks like true way to Control skipping of tests according to command line option is mark tests as skip dynamically:

  1. 使用 pytest_addoption 钩子添加 option 如下:
  1. add option using pytest_addoption hook like this:

def pytest_addoption(parser):
    parser.addoption(
        "--runslow", action="store_true", default=False, help="run slow tests"
    )

  1. 使用 pytest_collection_modifyitems 钩子添加如下标记:
  1. Use pytest_collection_modifyitems hook to add marker like this:

def pytest_collection_modifyitems(config, items):
    if config.getoption("--runslow"):
        # --runslow given in cli: do not skip slow tests
        return
    skip_slow = pytest.mark.skip(reason="need --runslow option to run")
    for item in items:
        if "slow" in item.keywords:
            item.add_marker(skip_slow)

  1. 为您的测试添加标记:

@pytest.mark.slow
def test_func_slow():
    pass

如果您想在测试中使用来自 CLI 的数据,例如,它是凭据,足以指定一个 skip optionpytestconfig:

If you want to use the data from the CLI in a test, for example, it`s credentials, enough to specify a skip option when retrieving them from the pytestconfig:

  1. 使用 pytest_addoption 钩子添加 option 如下:
  1. add option using pytest_addoption hook like this:

def pytest_addoption(parser):
    parser.addoption(
        "--credentials",
        action="store",
        default=None,
        help="credentials to ..."
    )

  1. 从 pytestconfig 获取时使用 skip 选项

@pytest.fixture(scope="session")
def super_secret_fixture(pytestconfig):
    credentials = pytestconfig.getoption('--credentials', skip=True)
    ...

  1. 在测试中照常使用夹具:

def test_with_fixture(super_secret_fixture):
    ...

在这种情况下,你会得到这样的东西,你不需要向 CLI 发送 --credentials 选项:

In this case you will got something like this it you not send --credentials option to CLI:

Skipped: no 'credentials' option found

最好使用 _pytest.config.get_config 而不是已弃用的 pytest.config 如果您仍然不想使用 pytest.mark.skipif 像这样:

It is better to use _pytest.config.get_config instead of deprecated pytest.config If you still wont to use pytest.mark.skipif like this:

@pytest.mark.skipif(not _pytest.config.get_config().getoption('--credentials'), reason="--credentials was not specified")

这篇关于在 pytest skip-if 条件中使用命令行选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆