Skip to content

Commit 0aaf239

Browse files
authored
Merge pull request #9497 from anntzer/pytest-fixes
Test simplifications.
2 parents e344d21 + af4bddd commit 0aaf239

File tree

6 files changed

+28
-102
lines changed

6 files changed

+28
-102
lines changed

lib/matplotlib/testing/__init__.py

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

3030

31-
# stolen from pandas
32-
@contextmanager
33-
def assert_produces_warning(expected_warning=Warning, filter_level="always",
34-
clear=None):
35-
"""
36-
Context manager for running code that expects to raise (or not raise)
37-
warnings. Checks that code raises the expected warning and only the
38-
expected warning. Pass ``False`` or ``None`` to check that it does *not*
39-
raise a warning. Defaults to ``exception.Warning``, baseclass of all
40-
Warnings. (basically a wrapper around ``warnings.catch_warnings``).
41-
42-
>>> import warnings
43-
>>> with assert_produces_warning():
44-
... warnings.warn(UserWarning())
45-
...
46-
>>> with assert_produces_warning(False):
47-
... warnings.warn(RuntimeWarning())
48-
...
49-
Traceback (most recent call last):
50-
...
51-
AssertionError: Caused unexpected warning(s): ['RuntimeWarning'].
52-
>>> with assert_produces_warning(UserWarning):
53-
... warnings.warn(RuntimeWarning())
54-
Traceback (most recent call last):
55-
...
56-
AssertionError: Did not see expected warning of class 'UserWarning'.
57-
58-
..warn:: This is *not* thread-safe.
59-
"""
60-
with warnings.catch_warnings(record=True) as w:
61-
62-
if clear is not None:
63-
# make sure that we are clearning these warnings
64-
# if they have happened before
65-
# to guarantee that we will catch them
66-
if not _is_list_like(clear):
67-
clear = [clear]
68-
for m in clear:
69-
getattr(m, "__warningregistry__", {}).clear()
70-
71-
saw_warning = False
72-
warnings.simplefilter(filter_level)
73-
yield w
74-
extra_warnings = []
75-
for actual_warning in w:
76-
if (expected_warning and issubclass(actual_warning.category,
77-
expected_warning)):
78-
saw_warning = True
79-
else:
80-
extra_warnings.append(actual_warning.category.__name__)
81-
if expected_warning:
82-
assert saw_warning, ("Did not see expected warning of class %r."
83-
% expected_warning.__name__)
84-
assert not extra_warnings, ("Caused unexpected warning(s): %r."
85-
% extra_warnings)
86-
87-
8831
def set_font_settings_for_testing():
8932
rcParams['font.family'] = 'DejaVu Sans'
9033
rcParams['text.hinting'] = False

lib/matplotlib/tests/test_axes.py

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1723,33 +1723,29 @@ def _as_mpl_axes(self):
17231723

17241724
# testing axes creation with plt.axes
17251725
ax = plt.axes([0, 0, 1, 1], projection=prj)
1726-
assert type(ax) == PolarAxes, \
1727-
'Expected a PolarAxes, got %s' % type(ax)
1726+
assert type(ax) == PolarAxes
17281727
ax_via_gca = plt.gca(projection=prj)
17291728
assert ax_via_gca is ax
17301729
plt.close()
17311730

17321731
# testing axes creation with gca
17331732
ax = plt.gca(projection=prj)
1734-
assert type(ax) == maxes._subplots._subplot_classes[PolarAxes], \
1735-
'Expected a PolarAxesSubplot, got %s' % type(ax)
1733+
assert type(ax) == maxes._subplots._subplot_classes[PolarAxes]
17361734
ax_via_gca = plt.gca(projection=prj)
17371735
assert ax_via_gca is ax
17381736
# try getting the axes given a different polar projection
17391737
ax_via_gca = plt.gca(projection=prj2)
17401738
assert ax_via_gca is not ax
1741-
assert ax.get_theta_offset() == 0, ax.get_theta_offset()
1742-
assert ax_via_gca.get_theta_offset() == np.pi, \
1743-
ax_via_gca.get_theta_offset()
1739+
assert ax.get_theta_offset() == 0
1740+
assert ax_via_gca.get_theta_offset() == np.pi
17441741
# try getting the axes given an == (not is) polar projection
17451742
ax_via_gca = plt.gca(projection=prj3)
17461743
assert ax_via_gca is ax
17471744
plt.close()
17481745

17491746
# testing axes creation with subplot
17501747
ax = plt.subplot(121, projection=prj)
1751-
assert type(ax) == maxes._subplots._subplot_classes[PolarAxes], \
1752-
'Expected a PolarAxesSubplot, got %s' % type(ax)
1748+
assert type(ax) == maxes._subplots._subplot_classes[PolarAxes]
17531749
plt.close()
17541750

17551751

@@ -4967,12 +4963,7 @@ def _helper_y(ax):
49674963
r = ax.yaxis.get_major_locator()()
49684964
assert r[-1] > 14
49694965

4970-
if request.param == 'x':
4971-
return _helper_x
4972-
elif request.param == 'y':
4973-
return _helper_y
4974-
else:
4975-
assert False, 'Request param %s is invalid.' % (request.param, )
4966+
return {"x": _helper_x, "y": _helper_y}[request.param]
49764967

49774968

49784969
@pytest.fixture(params=['gca', 'subplots', 'subplots_shared', 'add_axes'])
@@ -4989,9 +4980,6 @@ def shared_axes_generator(request):
49894980
elif request.param == 'add_axes':
49904981
fig = plt.figure()
49914982
ax = fig.add_axes([.1, .1, .8, .8])
4992-
else:
4993-
assert False, 'Request param %s is invalid.' % (request.param, )
4994-
49954983
return fig, ax
49964984

49974985

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)