可以根据夹具的值跳过测试吗?

时间:2018-06-19 21:17:51

标签: python pytest

我有很多测试分为许多不同的文件。在我的conftest.py中,我有这样的东西:

@pytest.fixture(scope="session",
                params=["foo", "bar", "baz"])
def special_param(request):
    return request.param

尽管大多数测试都适用于所有值,但有些测试仅适用于foo和baz。这意味着我在几个测试中都拥有这个功能:

def test_example(special_param):
    if special_param == "bar":
        pytest.skip("Test doesn't work with bar")

我觉得这有点丑陋,希望能有更好的方法。无论如何,有没有使用跳过装饰器来实现这一目标?如果没有,是否可以正确设置我自己的装饰器?

2 个答案:

答案 0 :(得分:0)

一种解决方案是使用@pytest.mark.parametrize覆盖灯具。例如

@pytest.mark.parametrize("special_param", ["foo"])
def test_example(special_param):
    # do test

另一种可能性是根本不使用special_param固定装置,并在需要时显式使用值"foo"。不利之处在于,这只有在没有其他也依赖于special_param的装置时才有效。

答案 1 :(得分:0)

作为@abarnert的评论之一,您可以为此使用functools.wraps编写自定义装饰器。在下面的示例中,我跳过了一个测试,即报告类型的灯具 configs (某些配置字典)的值是 enhanced ,还是 standard < / strong>(但这可能是您要检查的任何条件)。

例如,这是一个夹具的示例,我们将使用它来确定是否跳过测试:

@pytest.fixture
def configs()-> Dict:
   return {"report_type": "enhanced", "some_other_fixture_params": 123}

现在,我们编写一个装饰器,该装饰器将通过检查灯具configs的{​​{1}}键值来跳过测试:

report_type

请注意,我正在使用def skip_if_report_enhanced(test_function: Callable) -> Callable: @wraps(test_function) def wrapper(*args, **kwargs): configs = kwargs.get("configs") # configs is a fixture passed into the pytest function report_type = configs.get("report_type", "standard") if report_type is ReportType.ENHANCED: return pytest.skip(f"Skipping {test_function.__name__}") # skip! return test_function(*args, **kwargs) # otherwise, run the pytest return wrapper # return the decorated callable pytest 将固定装置拉出此处。

下面的测试本身(与测试的逻辑无关),只是测试是否运行:

kwargs.get("configs")

运行此测试的输出:

  

============================== 1跳了0.55秒============= ==================

     

以退出代码0 SKIPPED完成的过程
  [100%]跳过:跳过test_that_it_ran