oprypin / pytest-golden

Plugin for pytest that offloads expected outputs to data files
MIT License
23 stars 2 forks source link

Support `GoldenTestFixture.__contains__` (or show better error) #3

Open The-Compiler opened 1 year ago

The-Compiler commented 1 year ago

If a test should do something different depending on whether a key is in golden or not:

import pytest

@pytest.mark.golden_test("basic.yml")
def test_bar(golden):
    if "exit_code" in golden:
        # ...
        pass
    else:
        # ...
        pass

then pytest fails with:

====================================================== FAILURES ======================================================
________________________________________________ test_bar[basic.yml] _________________________________________________

golden = GoldenTestFixture(path=PosixPath('/home/florian/tmp/golden/basic.yml'), func=<function test_bar at 0x7f3b62a39240>, update_goldens=False, assertions_enabled=True)

    @pytest.mark.golden_test("basic.yml")
    def test_bar(golden):
>       if "exit_code" in golden:

test_golden.py:5: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = GoldenTestFixture(path=PosixPath('/home/florian/tmp/golden/basic.yml'), func=<function test_bar at 0x7f3b62a39240>, update_goldens=False, assertions_enabled=True)
key = 0

    def __getitem__(self, key: str) -> Any:
        self._used_fields.add(key)
>       return self._inputs[key]
E       KeyError: 0

.venv/lib/python3.10/site-packages/pytest_golden/plugin.py:126: KeyError
============================================== short test summary info ===============================================
FAILED test_golden.py::test_bar[basic.yml] - KeyError: 0
================================================= 1 failed in 0.02s ==================================================

This should either be supported (returning key in self._inputs I suppose), or be explicitly overridden and failing in a more obvious way.