Pytest - 除非声明选项/标志,否则如何跳过测试? [英] Pytest - how to skip tests unless you declare an option/flag?

查看:33
本文介绍了Pytest - 除非声明选项/标志,否则如何跳过测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些单元测试,但我正在寻找一种方法来标记一些特定的单元测试以跳过它们,除非您在调用测试时声明一个选项.

I have some unit tests, but I'm looking for a way to tag some specific unit tests to have them skipped unless you declare an option when you call the tests.

示例:如果我调用 pytest test_reports.py,我希望不运行几个特定的​​单元测试.

Example: If I call pytest test_reports.py, I'd want a couple specific unit tests to not be run.

但是如果我调用 pytest -test_reports,然后我希望运行所有测试.

But if I call pytest -<something> test_reports, then I want all my tests to be run.

我查看了 @pytest.mark.skipif(condition) 标签,但无法弄清楚,所以不确定我是否在正确的轨道上.这里的任何指导都会很棒!

I looked into the @pytest.mark.skipif(condition) tag but couldn't quite figure it out, so not sure if I'm on the right track or not. Any guidance here would be great!

推荐答案

我们在 conftest.py 中使用带 addoption 的标记

We are using markers with addoption in conftest.py

测试用例:

@pytest.mark.no_cmd
def test_skip_if_no_command_line():
    assert True

conftest.py:功能上

def pytest_addoption(parser):
    parser.addoption("--no_cmd", action="store_true",
                     help="run the tests only in case of that command line (marked with marker @no_cmd)")

在函数中

def pytest_runtest_setup(item):
    if 'no_cmd' in item.keywords and not item.config.getoption("--no_cmd"):
        pytest.skip("need --no_cmd option to run this test")

pytest 调用:

    py.test test_the_marker 
    -> test will be skipped

   py.test test_the_marker --no_cmd
   -> test will run

这篇关于Pytest - 除非声明选项/标志,否则如何跳过测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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