Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit cb1dbc2

Browse files
Shangwu Yaolesteve
Shangwu Yao
authored andcommitted
MNT: reduce the number of warnings in test_common.py (#11151)
Improve handling of warning filters in sklearn.utils.testing by avoiding to reset warnings.filters.
1 parent b03caaa commit cb1dbc2

File tree

5 files changed

+31
-30
lines changed

5 files changed

+31
-30
lines changed

sklearn/gaussian_process/tests/test_gaussian_process.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from sklearn.datasets import make_regression
1616
from sklearn.utils.testing import assert_greater, assert_true, assert_raises
1717

18+
pytestmark = pytest.mark.filterwarnings('ignore', category=DeprecationWarning)
1819

1920
f = lambda x: x * np.sin(x)
2021
X = np.atleast_2d([1., 3., 5., 6., 7., 8.]).T

sklearn/tests/test_common.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from sklearn.utils.testing import assert_greater
2323
from sklearn.utils.testing import assert_in
2424
from sklearn.utils.testing import ignore_warnings
25+
from sklearn.exceptions import ConvergenceWarning
2526

2627
import sklearn
2728
from sklearn.cluster.bicluster import BiclusterMixin
@@ -91,18 +92,22 @@ def _rename_partial(val):
9192
)
9293
def test_non_meta_estimators(name, Estimator, check):
9394
# Common tests for non-meta estimators
94-
estimator = Estimator()
95-
set_checking_parameters(estimator)
96-
check(name, estimator)
95+
with ignore_warnings(category=(DeprecationWarning, ConvergenceWarning,
96+
UserWarning, FutureWarning)):
97+
estimator = Estimator()
98+
set_checking_parameters(estimator)
99+
check(name, estimator)
97100

98101

99102
@pytest.mark.parametrize("name, Estimator",
100103
_tested_non_meta_estimators())
101104
def test_no_attributes_set_in_init(name, Estimator):
102105
# input validation etc for non-meta estimators
103-
estimator = Estimator()
104-
# check this on class
105-
check_no_attributes_set_in_init(name, estimator)
106+
with ignore_warnings(category=(DeprecationWarning, ConvergenceWarning,
107+
UserWarning, FutureWarning)):
108+
estimator = Estimator()
109+
# check this on class
110+
check_no_attributes_set_in_init(name, estimator)
106111

107112

108113
def test_configure():

sklearn/utils/estimator_checks.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -301,10 +301,10 @@ def check_estimator(Estimator):
301301
for check in _yield_all_checks(name, estimator):
302302
try:
303303
check(name, estimator)
304-
except SkipTest as message:
304+
except SkipTest as exception:
305305
# the only SkipTest thrown currently results from not
306306
# being able to import pandas.
307-
warnings.warn(message, SkipTestWarning)
307+
warnings.warn(str(exception), SkipTestWarning)
308308

309309

310310
def _boston_subset(n_samples=200):
@@ -327,7 +327,6 @@ def set_checking_parameters(estimator):
327327
and not isinstance(estimator, BaseSGD)):
328328
estimator.set_params(n_iter=5)
329329
if "max_iter" in params:
330-
warnings.simplefilter("ignore", ConvergenceWarning)
331330
if estimator.max_iter is not None:
332331
estimator.set_params(max_iter=min(5, estimator.max_iter))
333332
# LinearSVR, LinearSVC

sklearn/utils/testing.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,6 @@ def assert_warns(warning_class, func, *args, **kw):
137137
result : the return value of `func`
138138
139139
"""
140-
# very important to avoid uncontrolled state propagation
141140
clean_warning_registry()
142141
with warnings.catch_warnings(record=True) as w:
143142
# Cause all warnings to always be triggered.
@@ -321,7 +320,6 @@ def __call__(self, fn):
321320
"""Decorator to catch and hide warnings without visual nesting."""
322321
@wraps(fn)
323322
def wrapper(*args, **kwargs):
324-
# very important to avoid uncontrolled state propagation
325323
clean_warning_registry()
326324
with warnings.catch_warnings():
327325
warnings.simplefilter("ignore", self.category)
@@ -339,22 +337,22 @@ def __repr__(self):
339337
return "%s(%s)" % (name, ", ".join(args))
340338

341339
def __enter__(self):
342-
clean_warning_registry() # be safe and not propagate state + chaos
343-
warnings.simplefilter("ignore", self.category)
344340
if self._entered:
345341
raise RuntimeError("Cannot enter %r twice" % self)
346342
self._entered = True
347343
self._filters = self._module.filters
348344
self._module.filters = self._filters[:]
349345
self._showwarning = self._module.showwarning
346+
clean_warning_registry()
347+
warnings.simplefilter("ignore", self.category)
350348

351349
def __exit__(self, *exc_info):
352350
if not self._entered:
353351
raise RuntimeError("Cannot exit %r without entering first" % self)
354352
self._module.filters = self._filters
355353
self._module.showwarning = self._showwarning
356354
self.log[:] = []
357-
clean_warning_registry() # be safe and not propagate state + chaos
355+
clean_warning_registry()
358356

359357

360358
assert_less = _dummy.assertLess
@@ -724,8 +722,13 @@ def run_test(*args, **kwargs):
724722

725723

726724
def clean_warning_registry():
727-
"""Safe way to reset warnings."""
728-
warnings.resetwarnings()
725+
"""Clean Python warning registry for easier testing of warning messages.
726+
727+
We may not need to do this any more when getting rid of Python 2, not
728+
entirely sure. See https://bugs.python.org/issue4180 and
729+
https://bugs.python.org/issue21724 for more details.
730+
731+
"""
729732
reg = "__warningregistry__"
730733
for mod_name, mod in list(sys.modules.items()):
731734
if 'six.moves' in mod_name:

sklearn/utils/tests/test_testing.py

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -211,26 +211,19 @@ def context_manager_no_user_multiple_warning():
211211
assert_warns(DeprecationWarning, context_manager_no_user_multiple_warning)
212212

213213

214-
# This class is inspired from numpy 1.7 with an alteration to check
215-
# the reset warning filters after calls to assert_warns.
216-
# This assert_warns behavior is specific to scikit-learn because
217-
# `clean_warning_registry()` is called internally by assert_warns
218-
# and clears all previous filters.
219214
class TestWarns(unittest.TestCase):
220215
def test_warn(self):
221216
def f():
222217
warnings.warn("yo")
223218
return 3
224219

225-
# Test that assert_warns is not impacted by externally set
226-
# filters and is reset internally.
227-
# This is because `clean_warning_registry()` is called internally by
228-
# assert_warns and clears all previous filters.
229-
warnings.simplefilter("ignore", UserWarning)
230-
assert_equal(assert_warns(UserWarning, f), 3)
231-
232-
# Test that the warning registry is empty after assert_warns
233-
assert_equal(sys.modules['warnings'].filters, [])
220+
with warnings.catch_warnings():
221+
warnings.simplefilter("ignore", UserWarning)
222+
filters_orig = warnings.filters[:]
223+
assert_equal(assert_warns(UserWarning, f), 3)
224+
# test that assert_warns doesn't have side effects on warnings
225+
# filters
226+
assert_equal(warnings.filters, filters_orig)
234227

235228
assert_raises(AssertionError, assert_no_warnings, f)
236229
assert_equal(assert_no_warnings(lambda x: x, 1), 1)

0 commit comments

Comments
 (0)