如果特定参数的依赖失败则跳过测试

Skip test if dependency failed for particular parameter

两个测试。 首先,检查文件是否存在。 第二,当文件存在时,检查是否有任何内容。

共3个文件。

我想跳过 file_1 的第二次测试(当文件不存在时,看不到检查内容的理由)- 怎么做?

当前代码:

import os
from pathlib import Path
import pytest

file_0 = Path('C:\file_0.txt')
file_1 = Path('C:\file_1.txt')
file_2 = Path('C:\file_2.txt')


@pytest.mark.parametrize('file_path', [file_0, file_1, file_2])
@pytest.mark.dependency(name='test_check_file_exists')
def test_file_exists(file_path):
    assert file_path.is_file(), "File does not exists."


@pytest.mark.parametrize('file_path', [file_0, file_1, file_2])
@pytest.mark.dependency(depends=['test_check_file_exists'])
def test_file_has_any_data(file_path):
    assert os.path.getsize(file_path) > 0, "File is empty."

结果:

问题是参数化测试不是一个,而是几个测试。要在参数化测试上使用 dependency 标记,您必须在特定参数化测试之间建立依赖关系,在您的情况下,从 test_file_has_any_data[file_0]test_file_exists[file_0] 等等。
这可以通过为每个参数添加依赖来完成:

@pytest.mark.parametrize("file_path", [
    pytest.param(file_0, marks=pytest.mark.dependency(name="f0")),
    pytest.param(file_1, marks=pytest.mark.dependency(name="f1")),
    pytest.param(file_2, marks=pytest.mark.dependency(name="f2"))
])
def test_file_exists(file_path):
    assert file_path.is_file(), "File does not exists."


@pytest.mark.parametrize("file_path", [
    pytest.param(file_0, marks=pytest.mark.dependency(depends=["f0"])),
    pytest.param(file_1, marks=pytest.mark.dependency(depends=["f1"])),
    pytest.param(file_2, marks=pytest.mark.dependency(depends=["f2"]))
])
def test_file_has_any_data(file_path):
    assert os.path.getsize(file_path) > 0, "File is empty."

pytest.param 包装单个参数并允许专门为该参数添加标记,如所见。

pytest-dependency documentation 中也有介绍。