Skip to content

Commit b5dfebc

Browse files
committed
Add histogram test for changing layers
1 parent 014e34f commit b5dfebc

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
from io import BytesIO
2+
3+
import numpy as np
4+
from matplotlib.figure import Figure
5+
6+
import pytest
7+
8+
9+
def fig_to_array(fig: Figure) -> np.ndarray:
10+
"""
11+
Convert a figure to an RGB array.
12+
"""
13+
with BytesIO() as io_buf:
14+
fig.savefig(io_buf, format="raw")
15+
io_buf.seek(0)
16+
img_arr = np.reshape(
17+
np.frombuffer(io_buf.getvalue(), dtype=np.uint8),
18+
newshape=(int(fig.bbox.bounds[3]), int(fig.bbox.bounds[2]), -1),
19+
)
20+
return img_arr
21+
22+
23+
def assert_figures_equal(fig1: Figure, fig2: Figure) -> None:
24+
np.testing.assert_equal(fig_to_array(fig1), fig_to_array(fig2))
25+
26+
27+
def assert_figures_not_equal(fig1: Figure, fig2: Figure) -> None:
28+
with pytest.raises(AssertionError, match="Arrays are not equal"):
29+
assert_figures_equal(fig1, fig2)

src/napari_matplotlib/tests/test_histogram.py

+27
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@
33
import pytest
44

55
from napari_matplotlib import HistogramWidget
6+
from napari_matplotlib.tests.helpers import (
7+
assert_figures_equal,
8+
assert_figures_not_equal,
9+
)
610

711

812
@pytest.mark.mpl_image_compare
@@ -23,3 +27,26 @@ def test_histogram_3D(make_napari_viewer, brain_data):
2327
# Need to return a copy, as original figure is too eagerley garbage
2428
# collected by the widget
2529
return deepcopy(fig)
30+
31+
32+
def test_change_layer(make_napari_viewer, brain_data, astronaut_data):
33+
viewer = make_napari_viewer()
34+
widget = HistogramWidget(viewer)
35+
36+
viewer.add_image(brain_data[0], **brain_data[1])
37+
viewer.add_image(astronaut_data[0], **astronaut_data[1])
38+
39+
# Select first layer
40+
viewer.layers.selection.clear()
41+
viewer.layers.selection.add(viewer.layers[0])
42+
fig1 = deepcopy(widget.figure)
43+
44+
# Re-selecting first layer should produce identical plot
45+
viewer.layers.selection.clear()
46+
viewer.layers.selection.add(viewer.layers[0])
47+
assert_figures_equal(widget.figure, fig1)
48+
49+
# Plotting the second layer should produce a different plot
50+
viewer.layers.selection.clear()
51+
viewer.layers.selection.add(viewer.layers[1])
52+
assert_figures_not_equal(widget.figure, fig1)

0 commit comments

Comments
 (0)