PyTest fixtures on custom/dynamic testcases

Viewed 31

Following the non-python pytest example, I would like to know how to add fixtures to my custom tests.

For instance, given the followingconftest.py:

import pytest
import yaml


def pytest_collect_file(parent, file_path):
    if file_path.suffix == ".yaml":
        return YamlFile.from_parent(parent, path=file_path)


class YamlFile(pytest.File):
    def collect(self):
        for name, condition in yaml.safe_load(self.path.open()).items():
            yield TestCase.from_parent(self, name=name, condition=condition)


class TestCase(pytest.Item):
    def __init__(self, *, condition, **kwargs):
        super().__init__(**kwargs)
        self.condition = condition

    def runtest(self):
        assert eval(self.condition)

which I can run as:

$ cat stackoverflow.yaml
---
test_different: "1 != 2"
test_equal: "1 == 1"

$ pytest --no-header stackoverflow.yaml -v
================== test session starts ================== 
collected 2 items

stackoverflow.yaml::test_different PASSED          [ 50%]
stackoverflow.yaml::test_equal PASSED              [100%]

================== 2 passed in 0.00s ==================== 

I would like to have a fixture to use it from my custom test function, something like:

@pytest.fixture
def evaluate_condition():
    return eval


class TestCase(pytest.Item):
    ...

    def runtest(self, evaluate_condition):
        assert evaluate_condition(self.condition)

Is that possible? If so, how?

0 Answers
Related