File: test_image_regression.py

package info (click to toggle)
pytest-regressions 2.5.0%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,012 kB
  • sloc: python: 2,367; makefile: 18
file content (67 lines) | stat: -rw-r--r-- 1,774 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import io
from functools import partial

from pytest_regressions.testing import check_regression_fixture_workflow


def test_image_regression(image_regression, datadir):
    import matplotlib

    # this ensures matplot lib does not use a GUI backend (such as Tk)
    matplotlib.use("Agg")

    import matplotlib.pyplot as plt
    import numpy as np

    t = np.arange(0.0, 2.0, 0.01)
    s = 1 + np.sin(2 * np.pi * t)

    fig, ax = plt.subplots()
    ax.plot(t, s)

    ax.set(
        xlabel="time (s)",
        ylabel="voltage (mV)",
        title="About as simple as it gets, folks",
    )
    ax.grid()

    image_filename = datadir / "test.png"
    fig.savefig(str(image_filename))

    image_regression.check(image_filename.read_bytes(), diff_threshold=1.0)


def test_image_regression_workflow(pytester, monkeypatch, datadir):
    import sys
    from PIL import Image

    def get_image(color):
        f = io.BytesIO()
        img = Image.new("RGB", (100, 100), color)
        img.save(f, "PNG")
        return f.getvalue()

    monkeypatch.setattr(sys, "get_image", partial(get_image, "white"), raising=False)
    source = """
        import sys
        def test_1(image_regression):
            contents = sys.get_image()
            image_regression.check(contents)
    """

    def get_file_contents():
        fn = pytester.path / "test_file" / "test_1.png"
        assert fn.is_file()
        return fn.read_bytes()

    check_regression_fixture_workflow(
        pytester,
        source,
        data_getter=get_file_contents,
        data_modifier=lambda: monkeypatch.setattr(
            sys, "get_image", partial(get_image, "black"), raising=False
        ),
        expected_data_1=get_image("white"),
        expected_data_2=get_image("black"),
    )