Piotrek Leśniak
Piotrek Leśniak

Reputation: 83

Skip test if dependency failed for particular parameter

Two tests. First, check if file exists. Second, when file exist, check if has any content.

3 files in total.

I want to skip second test for file_1 (do not see reason to check content, when file not exist) - how to do it?

Current code:

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."

Result:

enter image description here

Upvotes: 0

Views: 132

Answers (1)

MrBean Bremen
MrBean Bremen

Reputation: 16815

The problem is that parametrized tests are not one, but several tests. To use dependency marks on parametrized tests, you have to make the dependency between specific parametrized tests, in your case from test_file_has_any_data[file_0] to test_file_exists[file_0] and so on.
This can be done by adding a dependency to each parameter:

@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 wraps a single parameter and allows to add marks specifically to that parameter, as can be seen.

This is also covered in the pytest-dependency documentation.

Upvotes: 1

Related Questions