| 1 |
import io |
| 2 |
from functools import partial |
| 3 |
|
| 4 |
from pytest_regressions.testing import check_regression_fixture_workflow |
| 5 |
|
| 6 |
|
| 7 |
def test_image_regression(image_regression, datadir): |
| 8 |
import matplotlib |
| 9 |
|
| 10 |
|
| 11 |
matplotlib.use("Agg") |
| 12 |
|
| 13 |
import matplotlib.pyplot as plt |
| 14 |
import numpy as np |
| 15 |
|
| 16 |
t = np.arange(0.0, 2.0, 0.01) |
| 17 |
s = 1 + np.sin(2 * np.pi * t) |
| 18 |
|
| 19 |
fig, ax = plt.subplots() |
| 20 |
ax.plot(t, s) |
| 21 |
|
| 22 |
ax.set( |
| 23 |
xlabel="time (s)", |
| 24 |
ylabel="voltage (mV)", |
| 25 |
title="About as simple as it gets, folks", |
| 26 |
) |
| 27 |
ax.grid() |
| 28 |
|
| 29 |
image_filename = datadir / "test.png" |
| 30 |
fig.savefig(str(image_filename)) |
| 31 |
|
| 32 |
image_regression.check(image_filename.read_bytes(), diff_threshold=1.0) |
| 33 |
|
| 34 |
|
| 35 |
def test_image_regression_workflow(pytester, monkeypatch, datadir): |
| 36 |
import sys |
| 37 |
from PIL import Image |
| 38 |
|
| 39 |
def get_image(color): |
| 40 |
f = io.BytesIO() |
| 41 |
img = Image.new("RGB", (100, 100), color) |
| 42 |
img.save(f, "PNG") |
| 43 |
return f.getvalue() |
| 44 |
|
| 45 |
monkeypatch.setattr(sys, "get_image", partial(get_image, "white"), raising=False) |
| 46 |
source = """ |
| 47 |
import sys |
| 48 |
def test_1(image_regression): |
| 49 |
contents = sys.get_image() |
| 50 |
image_regression.check(contents) |
| 51 |
""" |
| 52 |
|
| 53 |
def get_file_contents(): |
| 54 |
fn = pytester.path / "test_file" / "test_1.png" |
| 55 |
assert fn.is_file() |
| 56 |
return fn.read_bytes() |
| 57 |
|
| 58 |
check_regression_fixture_workflow( |
| 59 |
pytester, |
| 60 |
source, |
| 61 |
data_getter=get_file_contents, |
| 62 |
data_modifier=lambda: monkeypatch.setattr( |
| 63 |
sys, "get_image", partial(get_image, "black"), raising=False |
| 64 |
), |
| 65 |
expected_data_1=get_image("white"), |
| 66 |
expected_data_2=get_image("black"), |
| 67 |
) |