Skip to content

Commit 04ec0a0

Browse files
committed
Test simplifications.
- `assert_produces_warning` is now unused and has been replaced in the test suite by `pytest.warns`. - Replace `assert x, y` by `assert x` when the information in `y` is clearly redundant with what pytest's assert rewrite would produce. (There are a few cases where the message actually provides more information, these are left as is.)
1 parent 473e25c commit 04ec0a0

File tree

6 files changed

+40
-114
lines changed

6 files changed

+40
-114
lines changed

lib/matplotlib/testing/__init__.py

Lines changed: 0 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -51,63 +51,6 @@ def _copy_metadata(src_func, tgt_func):
5151
return tgt_func
5252

5353

54-
# stolen from pandas
55-
@contextmanager
56-
def assert_produces_warning(expected_warning=Warning, filter_level="always",
57-
clear=None):
58-
"""
59-
Context manager for running code that expects to raise (or not raise)
60-
warnings. Checks that code raises the expected warning and only the
61-
expected warning. Pass ``False`` or ``None`` to check that it does *not*
62-
raise a warning. Defaults to ``exception.Warning``, baseclass of all
63-
Warnings. (basically a wrapper around ``warnings.catch_warnings``).
64-
65-
>>> import warnings
66-
>>> with assert_produces_warning():
67-
... warnings.warn(UserWarning())
68-
...
69-
>>> with assert_produces_warning(False):
70-
... warnings.warn(RuntimeWarning())
71-
...
72-
Traceback (most recent call last):
73-
...
74-
AssertionError: Caused unexpected warning(s): ['RuntimeWarning'].
75-
>>> with assert_produces_warning(UserWarning):
76-
... warnings.warn(RuntimeWarning())
77-
Traceback (most recent call last):
78-
...
79-
AssertionError: Did not see expected warning of class 'UserWarning'.
80-
81-
..warn:: This is *not* thread-safe.
82-
"""
83-
with warnings.catch_warnings(record=True) as w:
84-
85-
if clear is not None:
86-
# make sure that we are clearning these warnings
87-
# if they have happened before
88-
# to guarantee that we will catch them
89-
if not _is_list_like(clear):
90-
clear = [clear]
91-
for m in clear:
92-
getattr(m, "__warningregistry__", {}).clear()
93-
94-
saw_warning = False
95-
warnings.simplefilter(filter_level)
96-
yield w
97-
extra_warnings = []
98-
for actual_warning in w:
99-
if (expected_warning and issubclass(actual_warning.category,
100-
expected_warning)):
101-
saw_warning = True
102-
else:
103-
extra_warnings.append(actual_warning.category.__name__)
104-
if expected_warning:
105-
assert saw_warning, ("Did not see expected warning of class %r."
106-
% expected_warning.__name__)
107-
assert not extra_warnings, ("Caused unexpected warning(s): %r."
108-
% extra_warnings)
109-
110-
11154
def set_font_settings_for_testing():
11255
rcParams['font.family'] = 'DejaVu Sans'
11356
rcParams['text.hinting'] = False

lib/matplotlib/tests/test_axes.py

Lines changed: 18 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1712,33 +1712,29 @@ def _as_mpl_axes(self):
17121712

17131713
# testing axes creation with plt.axes
17141714
ax = plt.axes([0, 0, 1, 1], projection=prj)
1715-
assert type(ax) == PolarAxes, \
1716-
'Expected a PolarAxes, got %s' % type(ax)
1715+
assert type(ax) == PolarAxes
17171716
ax_via_gca = plt.gca(projection=prj)
17181717
assert ax_via_gca is ax
17191718
plt.close()
17201719

17211720
# testing axes creation with gca
17221721
ax = plt.gca(projection=prj)
1723-
assert type(ax) == maxes._subplots._subplot_classes[PolarAxes], \
1724-
'Expected a PolarAxesSubplot, got %s' % type(ax)
1722+
assert type(ax) == maxes._subplots._subplot_classes[PolarAxes]
17251723
ax_via_gca = plt.gca(projection=prj)
17261724
assert ax_via_gca is ax
17271725
# try getting the axes given a different polar projection
17281726
ax_via_gca = plt.gca(projection=prj2)
17291727
assert ax_via_gca is not ax
1730-
assert ax.get_theta_offset() == 0, ax.get_theta_offset()
1731-
assert ax_via_gca.get_theta_offset() == np.pi, \
1732-
ax_via_gca.get_theta_offset()
1728+
assert ax.get_theta_offset() == 0
1729+
assert ax_via_gca.get_theta_offset() == np.pi
17331730
# try getting the axes given an == (not is) polar projection
17341731
ax_via_gca = plt.gca(projection=prj3)
17351732
assert ax_via_gca is ax
17361733
plt.close()
17371734

17381735
# testing axes creation with subplot
17391736
ax = plt.subplot(121, projection=prj)
1740-
assert type(ax) == maxes._subplots._subplot_classes[PolarAxes], \
1741-
'Expected a PolarAxesSubplot, got %s' % type(ax)
1737+
assert type(ax) == maxes._subplots._subplot_classes[PolarAxes]
17421738
plt.close()
17431739

17441740

@@ -4956,32 +4952,24 @@ def _helper_y(ax):
49564952
r = ax.yaxis.get_major_locator()()
49574953
assert r[-1] > 14
49584954

4959-
if request.param == 'x':
4960-
return _helper_x
4961-
elif request.param == 'y':
4962-
return _helper_y
4963-
else:
4964-
assert False, 'Request param %s is invalid.' % (request.param, )
4955+
return {"x": _helper_x, "y": _helper_y}[request.param]
49654956

49664957

49674958
@pytest.fixture(params=['gca', 'subplots', 'subplots_shared', 'add_axes'])
49684959
def shared_axes_generator(request):
49694960
# test all of the ways to get fig/ax sets
4970-
if request.param == 'gca':
4971-
fig = plt.figure()
4972-
ax = fig.gca()
4973-
elif request.param == 'subplots':
4974-
fig, ax = plt.subplots()
4975-
elif request.param == 'subplots_shared':
4976-
fig, ax_lst = plt.subplots(2, 2, sharex='all', sharey='all')
4977-
ax = ax_lst[0][0]
4978-
elif request.param == 'add_axes':
4979-
fig = plt.figure()
4980-
ax = fig.add_axes([.1, .1, .8, .8])
4981-
else:
4982-
assert False, 'Request param %s is invalid.' % (request.param, )
4983-
4984-
return fig, ax
4961+
fig = plt.figure()
4962+
make_ax = {
4963+
"gca":
4964+
lambda fig: fig.gca(),
4965+
"subplots":
4966+
lambda fig: fig.subplots(),
4967+
"subplots_shared":
4968+
lambda fig: fig.subplots(2, 2, sharex="all", sharey="all")[0, 0],
4969+
"add_axes":
4970+
lambda fig: fig.add_axes([.1, .1, .8, .8]),
4971+
}[request.param]
4972+
return fig, make_ax(fig)
49854973

49864974

49874975
def test_remove_shared_axes(shared_axes_generator, shared_axis_remover):

lib/matplotlib/tests/test_cycles.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ def test_cycle_reset():
179179
assert prop != next(ax._get_lines.prop_cycler)
180180
ax.set_prop_cycle(None)
181181
got = next(ax._get_lines.prop_cycler)
182-
assert prop == got, "expected %s, got %s" % (prop, got)
182+
assert prop == got
183183

184184
fig, ax = plt.subplots()
185185
# Need to double-check the old set/get_color_cycle(), too
@@ -190,7 +190,7 @@ def test_cycle_reset():
190190
assert prop != next(ax._get_lines.prop_cycler)
191191
ax.set_color_cycle(None)
192192
got = next(ax._get_lines.prop_cycler)
193-
assert prop == got, "expected %s, got %s" % (prop, got)
193+
assert prop == got
194194

195195

196196
def test_invalid_input_forms():

lib/matplotlib/tests/test_image.py

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -201,17 +201,15 @@ def test_cursor_data():
201201
xdisp, ydisp = ax.transData.transform_point([x, y])
202202

203203
event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
204-
z = im.get_cursor_data(event)
205-
assert z == 44, "Did not get 44, got %d" % z
204+
assert im.get_cursor_data(event) == 44
206205

207206
# Now try for a point outside the image
208207
# Tests issue #4957
209208
x, y = 10.1, 4
210209
xdisp, ydisp = ax.transData.transform_point([x, y])
211210

212211
event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
213-
z = im.get_cursor_data(event)
214-
assert z is None, "Did not get None, got %d" % z
212+
assert im.get_cursor_data(event) is None
215213

216214
# Hmm, something is wrong here... I get 0, not None...
217215
# But, this works further down in the tests with extents flipped
@@ -229,8 +227,7 @@ def test_cursor_data():
229227
xdisp, ydisp = ax.transData.transform_point([x, y])
230228

231229
event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
232-
z = im.get_cursor_data(event)
233-
assert z == 44, "Did not get 44, got %d" % z
230+
assert im.get_cursor_data(event) == 44
234231

235232
fig, ax = plt.subplots()
236233
im = ax.imshow(np.arange(100).reshape(10, 10), extent=[0, 0.5, 0, 0.5])
@@ -239,24 +236,21 @@ def test_cursor_data():
239236
xdisp, ydisp = ax.transData.transform_point([x, y])
240237

241238
event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
242-
z = im.get_cursor_data(event)
243-
assert z == 55, "Did not get 55, got %d" % z
239+
assert im.get_cursor_data(event) == 55
244240

245241
# Now try for a point outside the image
246242
# Tests issue #4957
247243
x, y = 0.75, 0.25
248244
xdisp, ydisp = ax.transData.transform_point([x, y])
249245

250246
event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
251-
z = im.get_cursor_data(event)
252-
assert z is None, "Did not get None, got %d" % z
247+
assert im.get_cursor_data(event) is None
253248

254249
x, y = 0.01, -0.01
255250
xdisp, ydisp = ax.transData.transform_point([x, y])
256251

257252
event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
258-
z = im.get_cursor_data(event)
259-
assert z is None, "Did not get None, got %d" % z
253+
assert im.get_cursor_data(event) is None
260254

261255

262256
@image_comparison(baseline_images=['image_clip'], style='mpl20')
@@ -295,15 +289,19 @@ def test_imshow():
295289
ax.set_xlim(0,3)
296290
ax.set_ylim(0,3)
297291

298-
@image_comparison(baseline_images=['no_interpolation_origin'], remove_text=True)
292+
293+
@image_comparison(baseline_images=['no_interpolation_origin'],
294+
remove_text=True)
299295
def test_no_interpolation_origin():
300296
fig = plt.figure()
301297
ax = fig.add_subplot(211)
302-
ax.imshow(np.arange(100).reshape((2, 50)), origin="lower", interpolation='none')
298+
ax.imshow(np.arange(100).reshape((2, 50)), origin="lower",
299+
interpolation='none')
303300

304301
ax = fig.add_subplot(212)
305302
ax.imshow(np.arange(100).reshape((2, 50)), interpolation='none')
306303

304+
307305
@image_comparison(baseline_images=['image_shift'], remove_text=True,
308306
extensions=['pdf', 'svg'])
309307
def test_image_shift():
@@ -319,6 +317,7 @@ def test_image_shift():
319317
extent=(tMin, tMax, 1, 100))
320318
ax.set_aspect('auto')
321319

320+
322321
def test_image_edges():
323322
f = plt.figure(figsize=[1, 1])
324323
ax = f.add_axes([0, 0, 1, 1], frameon=False)
@@ -514,11 +513,10 @@ def test_jpeg_alpha():
514513
# If this fails, there will be only one color (all black). If this
515514
# is working, we should have all 256 shades of grey represented.
516515
num_colors = len(image.getcolors(256))
517-
assert 175 <= num_colors <= 185, 'num colors: %d' % (num_colors, )
518-
# The fully transparent part should be red, not white or black
519-
# or anything else
516+
assert 175 <= num_colors <= 185
517+
# The fully transparent part should be red.
520518
corner_pixel = image.getpixel((0, 0))
521-
assert corner_pixel == (254, 0, 0), "corner pixel: %r" % (corner_pixel, )
519+
assert corner_pixel == (254, 0, 0)
522520

523521

524522
def test_nonuniformimage_setdata():

lib/matplotlib/tests/test_patheffects.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -111,10 +111,7 @@ def test_PathEffect_points_to_pixels():
111111
renderer = fig.canvas.get_renderer()
112112
pe_renderer = path_effects.SimpleLineShadow().get_proxy_renderer(renderer)
113113

114-
assert isinstance(pe_renderer, path_effects.PathEffectRenderer), (
115-
'Expected a PathEffectRendere instance, got '
116-
'a {0} instance.'.format(type(pe_renderer)))
117-
114+
assert isinstance(pe_renderer, path_effects.PathEffectRenderer)
118115
# Confirm that using a path effects renderer maintains point sizes
119116
# appropriately. Otherwise rendered font would be the wrong size.
120117
assert renderer.points_to_pixels(15) == pe_renderer.points_to_pixels(15)

lib/matplotlib/tests/test_widgets.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ def onselect(epress, erelease):
128128
key=' ')
129129
do_event(tool, 'onmove', xdata=30, ydata=30, button=1)
130130
do_event(tool, 'release', xdata=30, ydata=30, button=1)
131-
assert tool.extents == (120, 170, 120, 170), tool.extents
131+
assert tool.extents == (120, 170, 120, 170)
132132

133133
# create from center
134134
do_event(tool, 'on_key_press', xdata=100, ydata=100, button=1,
@@ -138,7 +138,7 @@ def onselect(epress, erelease):
138138
do_event(tool, 'release', xdata=125, ydata=125, button=1)
139139
do_event(tool, 'on_key_release', xdata=100, ydata=100, button=1,
140140
key='control')
141-
assert tool.extents == (75, 125, 75, 125), tool.extents
141+
assert tool.extents == (75, 125, 75, 125)
142142

143143
# create a square
144144
do_event(tool, 'on_key_press', xdata=10, ydata=10, button=1,
@@ -160,7 +160,7 @@ def onselect(epress, erelease):
160160
do_event(tool, 'on_key_release', xdata=100, ydata=100, button=1,
161161
key='ctrl+shift')
162162
extents = [int(e) for e in tool.extents]
163-
assert extents == [70, 129, 70, 130], extents
163+
assert extents == [70, 129, 70, 130]
164164

165165
assert tool.geometry.shape == (2, 73)
166166
assert_allclose(tool.geometry[:, 0], [70., 100])

0 commit comments

Comments
 (0)