Last active
November 14, 2024 10:41
-
-
Save chmouel/0a4a1a1ad54eec8eb5803255679a7d74 to your computer and use it in GitHub Desktop.
golden files comparaison and update on python with pytest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import os | |
import pathlib | |
import pytest | |
@pytest.fixture | |
def fixtdir(request): | |
return pathlib.Path(request.module.__file__).parent / "fixtures" | |
@pytest.fixture | |
def goldenfile(fixtdir, request): | |
return fixtdir / f"{request.node.name}.golden" | |
def test_golden(goldenfile: pathlib.Path, output: str | dict | list, extras=None): | |
johnmode = False | |
if extras: | |
goldenfile = goldenfile.with_suffix(f".{extras}.golden") | |
if isinstance(output, (dict, list)): | |
johnmode = True | |
output = json.dumps(output, indent=4) | |
goldenfile = goldenfile.with_suffix(".golden.json") | |
if "UPDATE_GOLDEN" in os.environ: | |
goldenfile.parent.mkdir(exist_ok=True, parents=True) | |
goldenfile.write_text(output) | |
return | |
if not goldenfile.exists(): | |
raise FileNotFoundError(f"Golden file {goldenfile} does not exist") | |
goldenoutput = goldenfile.read_text() | |
if johnmode: | |
assert json.loads(goldenoutput) == json.loads(output) | |
else: | |
assert goldenoutput == output | |
def test_me(golden_file): | |
output = "hello" | |
# Update the golden file with the output instead of testing | |
# __import__("os").environ["UPDATE_GOLDEN"] = "1" | |
test_golden(golden_file, output) | |
# Another test with another file | |
anotheroutput = {"hello": "moto"} | |
test_golden(golden_file, anotheroutput, "another") | |
# Check the files | |
# cat fixtures/test_me.another.golden.json fixtures/test_me.golden |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment