Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 359f76a

Browse filesBrowse files
committed
Cleanup warnings handling in tests.
This caught two "incorrect" tests: - in test_style.py::test_invalid_rc_warning_includes_filename, the `for w in warns: ...` assertion did nothing as no warning was emitted so `warns` was empty (instead, the message is just print()ed to stderr. - in test_image.py::test_empty_imshow, the caught warning message was missing spaces around the equals.
1 parent a45712e commit 359f76a
Copy full SHA for 359f76a

File tree

Expand file treeCollapse file tree

9 files changed

+42
-87
lines changed
Filter options
Expand file treeCollapse file tree

9 files changed

+42
-87
lines changed

‎lib/matplotlib/tests/test_axes.py

Copy file name to clipboardExpand all lines: lib/matplotlib/tests/test_axes.py
+2-3Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5233,9 +5233,8 @@ def generate_errorbar_inputs():
52335233

52345234
@pytest.mark.parametrize('kwargs', generate_errorbar_inputs())
52355235
def test_errorbar_inputs_shotgun(kwargs):
5236-
with warnings.catch_warnings():
5237-
# (n, 1)-shaped error deprecation already tested by test_errorbar.
5238-
warnings.simplefilter("ignore", MatplotlibDeprecationWarning)
5236+
# (n, 1)-shaped error deprecation already tested by test_errorbar.
5237+
with mpl.cbook._suppress_matplotlib_deprecation_warning():
52395238
ax = plt.gca()
52405239
eb = ax.errorbar(**kwargs)
52415240
eb.remove()

‎lib/matplotlib/tests/test_figure.py

Copy file name to clipboardExpand all lines: lib/matplotlib/tests/test_figure.py
+2-7Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from pathlib import Path
22
import platform
3-
import warnings
43

54
from matplotlib import rcParams
65
from matplotlib.testing.decorators import image_comparison, check_figures_equal
@@ -154,11 +153,9 @@ def test_gca():
154153

155154
# the final request for a polar axes will end up creating one
156155
# with a spec of 111.
157-
with warnings.catch_warnings(record=True) as w:
158-
warnings.simplefilter('always')
156+
with pytest.warns(UserWarning):
159157
# Changing the projection will throw a warning
160158
assert fig.gca(polar=True) is not ax3
161-
assert len(w) == 1
162159
assert fig.gca(polar=True) is not ax2
163160
assert fig.gca().get_geometry() == (1, 1, 1)
164161

@@ -204,11 +201,9 @@ def test_alpha():
204201

205202

206203
def test_too_many_figures():
207-
with warnings.catch_warnings(record=True) as w:
208-
warnings.simplefilter("always")
204+
with pytest.warns(RuntimeWarning):
209205
for i in range(rcParams['figure.max_open_warning'] + 1):
210206
plt.figure()
211-
assert len(w) == 1
212207

213208

214209
def test_iterability_axes_argument():

‎lib/matplotlib/tests/test_image.py

Copy file name to clipboardExpand all lines: lib/matplotlib/tests/test_image.py
+2-3Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -894,9 +894,8 @@ def test_imshow_bignumbers_real():
894894
lambda: colors.PowerNorm(1)])
895895
def test_empty_imshow(make_norm):
896896
fig, ax = plt.subplots()
897-
with warnings.catch_warnings():
898-
warnings.filterwarnings(
899-
"ignore", "Attempting to set identical left==right")
897+
with pytest.warns(UserWarning,
898+
match="Attempting to set identical left == right"):
900899
im = ax.imshow([[]], norm=make_norm())
901900
im.set_extent([-5, 5, -5, 5])
902901
fig.canvas.draw()

‎lib/matplotlib/tests/test_mlab.py

Copy file name to clipboardExpand all lines: lib/matplotlib/tests/test_mlab.py
+2-7Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import tempfile
2-
import warnings
32

43
from numpy.testing import (assert_allclose, assert_almost_equal,
54
assert_array_equal, assert_array_almost_equal_nulp)
@@ -1859,13 +1858,9 @@ def test_specgram_phase(self):
18591858
assert spec.shape[1] == self.t_specgram.shape[0]
18601859

18611860
def test_specgram_warn_only1seg(self):
1862-
"""Warning should be raised if len(x) <= NFFT. """
1863-
with warnings.catch_warnings(record=True) as w:
1864-
warnings.simplefilter("always", category=UserWarning)
1861+
"""Warning should be raised if len(x) <= NFFT."""
1862+
with pytest.warns(UserWarning, match="Only one segment is calculated"):
18651863
mlab.specgram(x=self.y, NFFT=len(self.y), Fs=self.Fs)
1866-
assert len(w) == 1
1867-
assert issubclass(w[0].category, UserWarning)
1868-
assert str(w[0].message).startswith("Only one segment is calculated")
18691864

18701865
def test_psd_csd_equal(self):
18711866
freqs = self.freqs_density

‎lib/matplotlib/tests/test_rcparams.py

Copy file name to clipboardExpand all lines: lib/matplotlib/tests/test_rcparams.py
+8-18Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,12 @@
22
import copy
33
import os
44
from unittest import mock
5-
import warnings
65

76
from cycler import cycler, Cycler
87
import pytest
98

109
import matplotlib as mpl
11-
from matplotlib.cbook import MatplotlibDeprecationWarning
10+
from matplotlib import cbook
1211
import matplotlib.pyplot as plt
1312
import matplotlib.colors as mcolors
1413
import numpy as np
@@ -91,22 +90,15 @@ def test_rcparams_update():
9190
rc = mpl.RcParams({'figure.figsize': (3.5, 42)})
9291
bad_dict = {'figure.figsize': (3.5, 42, 1)}
9392
# make sure validation happens on input
94-
with pytest.raises(ValueError):
95-
96-
with warnings.catch_warnings():
97-
warnings.filterwarnings('ignore',
98-
message='.*(validate)',
99-
category=UserWarning)
100-
rc.update(bad_dict)
93+
with pytest.raises(ValueError), \
94+
pytest.warns(UserWarning, match="validate"):
95+
rc.update(bad_dict)
10196

10297

10398
def test_rcparams_init():
104-
with pytest.raises(ValueError):
105-
with warnings.catch_warnings():
106-
warnings.filterwarnings('ignore',
107-
message='.*(validate)',
108-
category=UserWarning)
109-
mpl.RcParams({'figure.figsize': (3.5, 42, 1)})
99+
with pytest.raises(ValueError), \
100+
pytest.warns(UserWarning, match="validate"):
101+
mpl.RcParams({'figure.figsize': (3.5, 42, 1)})
110102

111103

112104
def test_Bug_2543():
@@ -117,9 +109,7 @@ def test_Bug_2543():
117109
# We filter warnings at this stage since a number of them are raised
118110
# for deprecated rcparams as they should. We don't want these in the
119111
# printed in the test suite.
120-
with warnings.catch_warnings():
121-
warnings.filterwarnings('ignore',
122-
category=MatplotlibDeprecationWarning)
112+
with cbook._suppress_matplotlib_deprecation_warning():
123113
with mpl.rc_context():
124114
_copy = mpl.rcParams.copy()
125115
for key in _copy:

‎lib/matplotlib/tests/test_style.py

Copy file name to clipboardExpand all lines: lib/matplotlib/tests/test_style.py
+5-9Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import gc
44
from pathlib import Path
55
from tempfile import TemporaryDirectory
6-
import warnings
76

87
import pytest
98

@@ -36,16 +35,13 @@ def temp_style(style_name, settings=None):
3635
style.reload_library()
3736

3837

39-
def test_invalid_rc_warning_includes_filename():
38+
def test_invalid_rc_warning_includes_filename(capsys):
4039
SETTINGS = {'foo': 'bar'}
4140
basename = 'basename'
42-
with warnings.catch_warnings(record=True) as warns:
43-
with temp_style(basename, SETTINGS):
44-
# style.reload_library() in temp_style() triggers the warning
45-
pass
46-
47-
for w in warns:
48-
assert basename in str(w.message)
41+
with temp_style(basename, SETTINGS):
42+
# style.reload_library() in temp_style() triggers the warning
43+
pass
44+
assert basename in capsys.readouterr().err
4945

5046

5147
def test_available():

‎lib/matplotlib/tests/test_subplots.py

Copy file name to clipboardExpand all lines: lib/matplotlib/tests/test_subplots.py
+9-11Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import itertools
2-
import warnings
32

43
import numpy
54
import matplotlib.pyplot as plt
@@ -122,16 +121,15 @@ def test_exceptions():
122121
plt.subplots(2, 2, sharey='blah')
123122
# We filter warnings in this test which are genuine since
124123
# the point of this test is to ensure that this raises.
125-
with warnings.catch_warnings():
126-
warnings.filterwarnings('ignore',
127-
message='.*sharex argument to subplots',
128-
category=UserWarning)
129-
with pytest.raises(ValueError):
130-
plt.subplots(2, 2, -1)
131-
with pytest.raises(ValueError):
132-
plt.subplots(2, 2, 0)
133-
with pytest.raises(ValueError):
134-
plt.subplots(2, 2, 5)
124+
with pytest.warns(UserWarning, match='.*sharex argument to subplots'), \
125+
pytest.raises(ValueError):
126+
plt.subplots(2, 2, -1)
127+
with pytest.warns(UserWarning, match='.*sharex argument to subplots'), \
128+
pytest.raises(ValueError):
129+
plt.subplots(2, 2, 0)
130+
with pytest.warns(UserWarning, match='.*sharex argument to subplots'), \
131+
pytest.raises(ValueError):
132+
plt.subplots(2, 2, 5)
135133

136134

137135
@image_comparison(baseline_images=['subplots_offset_text'], remove_text=False)

‎lib/matplotlib/tests/test_ticker.py

Copy file name to clipboardExpand all lines: lib/matplotlib/tests/test_ticker.py
+1-3Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -233,10 +233,8 @@ def test_set_params(self):
233233
Should not exception, and should raise a warning.
234234
"""
235235
loc = mticker.NullLocator()
236-
with warnings.catch_warnings(record=True) as w:
237-
warnings.simplefilter("always")
236+
with pytest.warns(UserWarning):
238237
loc.set_params()
239-
assert len(w) == 1
240238

241239

242240
class TestLogitLocator(object):

‎lib/matplotlib/tests/test_tightlayout.py

Copy file name to clipboardExpand all lines: lib/matplotlib/tests/test_tightlayout.py
+11-26Lines changed: 11 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import numpy as np
44
from numpy.testing import assert_array_equal
5+
import pytest
56

67
from matplotlib.testing.decorators import image_comparison
78
import matplotlib.pyplot as plt
@@ -267,50 +268,36 @@ def _subplots():
267268

268269

269270
def test_empty_layout():
270-
"""Tests that tight layout doesn't cause an error when there are
271-
no axes.
272-
"""
273-
271+
"""Test that tight layout doesn't cause an error when there are no axes."""
274272
fig = plt.gcf()
275273
fig.tight_layout()
276274

277275

278-
def test_verybig_decorators_horizontal():
279-
"Test that warning emitted when xlabel too big"
280-
fig, ax = plt.subplots(figsize=(3, 2))
281-
ax.set_xlabel('a' * 100)
282-
with warnings.catch_warnings(record=True) as w:
283-
fig.tight_layout()
284-
assert len(w) == 1
285-
286-
287-
def test_verybig_decorators_vertical():
288-
"Test that warning emitted when xlabel too big"
276+
@pytest.mark.parametrize("label", ["xlabel", "ylabel"])
277+
def test_verybig_decorators(label):
278+
"""Test that warning emitted when xlabel/ylabel too big."""
289279
fig, ax = plt.subplots(figsize=(3, 2))
290-
ax.set_ylabel('a' * 100)
291-
with warnings.catch_warnings(record=True) as w:
280+
ax.set(**{label: 'a' * 100})
281+
with pytest.warns(UserWarning):
292282
fig.tight_layout()
293-
assert len(w) == 1
294283

295284

296285
def test_big_decorators_horizontal():
297286
"Test that warning emitted when xlabel too big"
298287
fig, axs = plt.subplots(1, 2, figsize=(3, 2))
299288
axs[0].set_xlabel('a' * 30)
300289
axs[1].set_xlabel('b' * 30)
301-
with warnings.catch_warnings(record=True) as w:
290+
with pytest.warns(UserWarning):
302291
fig.tight_layout()
303-
assert len(w) == 1
304292

305293

306294
def test_big_decorators_vertical():
307295
"Test that warning emitted when xlabel too big"
308296
fig, axs = plt.subplots(2, 1, figsize=(3, 2))
309297
axs[0].set_ylabel('a' * 20)
310298
axs[1].set_ylabel('b' * 20)
311-
with warnings.catch_warnings(record=True) as w:
299+
with pytest.warns(UserWarning):
312300
fig.tight_layout()
313-
assert len(w) == 1
314301

315302

316303
def test_badsubplotgrid():
@@ -319,9 +306,8 @@ def test_badsubplotgrid():
319306
ax1 = plt.subplot2grid((4, 5), (0, 0))
320307
# this is the bad entry:
321308
ax5 = plt.subplot2grid((5, 5), (0, 3), colspan=3, rowspan=5)
322-
with warnings.catch_warnings(record=True) as w:
309+
with pytest.warns(UserWarning):
323310
plt.tight_layout()
324-
assert len(w) == 1
325311

326312

327313
def test_collapsed():
@@ -333,8 +319,7 @@ def test_collapsed():
333319

334320
ax.annotate('BIG LONG STRING', xy=(1.25, 2), xytext=(10.5, 1.75),)
335321
p1 = ax.get_position()
336-
with warnings.catch_warnings(record=True) as w:
322+
with pytest.warns(UserWarning):
337323
plt.tight_layout()
338324
p2 = ax.get_position()
339325
assert p1.width == p2.width
340-
assert len(w) == 1

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.