python - 可以根据 fixture 值跳过测试吗?

标签 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")

我觉得这有点难看,希望有更好的方法来做到这一点。有没有办法使用skip装饰器来实现这一点?如果没有,是否可以纠正我自己的装饰器来做到这一点?

最佳答案

正如 @abarnert 的评论之一,您可以使用 functools.wraps 专门为此目的编写一个自定义装饰器。在下面的示例中,如果报告类型的固定装置configs(某些配置字典)值是增强,则我将跳过测试,而不是>标准(但它可以是您想要检查的任何条件)。

例如,下面是我们将用来确定是否跳过测试的 fixture 示例:

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

现在我们编写一个装饰器,它将通过检查固定装置 configs 内容的 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") 将 fixture 拉出此处。

在测试本身下面,其逻辑无关紧要,只是测试是否运行:

@skip_if_report_enhanced
def test_that_it_ran(configs):
   print("The test ran!") # shouldn't get here if the report type is set to enhanced

运行此测试的输出:

============================== 1 skipped in 0.55s ==============================

Process finished with exit code 0 SKIPPED
[100%] Skipped: Skipping test_that_it_ran

关于python - 可以根据 fixture 值跳过测试吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50937075/

相关文章:

python - 如何在 Delphi 应用程序中创建图形

python - 在 CX_Freeze 中从 Python 3.6 脚本创建单个 exe

python - 搜索框已填满时,搜索按钮不起作用

python-3.x - PyTest: "no tests ran",即使测试已明确运行

python - pytest 日志记录到文件和标准输出

Python 在运行时从函数中提取主体

python - 除非编辑字段不为空,否则如何禁用按钮?

pytest - 使用 pytest.mark.parametrize 从列表中读取动态生成测试

python - Pytest 警告 : Module already imported so cannot be rewritten: pytest_remotedata

python - OSError : pytest: reading from stdin while output is captured! 考虑使用 `-s`