两个测试。 首先,检查文件是否存在。 其次,当文件存在时,检查是否有内容。
共 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."
结果:
答案 0 :(得分:1)
问题在于参数化测试不是一个,而是多个测试。要在参数化测试上使用 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 中。