diff options
author | Sebastian Berg <sebastian@sipsolutions.net> | 2016-06-19 14:18:35 +0200 |
---|---|---|
committer | Sebastian Berg <sebastian@sipsolutions.net> | 2016-09-02 10:10:55 +0200 |
commit | 308161c80f4450f05f8399343034308bd18b4e1e (patch) | |
tree | ba3778d778e1222e93246ca7842e8f060e411173 | |
parent | c1ddf841f6a48248b946a990ae750505b8b91686 (diff) | |
download | numpy-308161c80f4450f05f8399343034308bd18b4e1e.tar.gz |
TST: Use new warnings context manager in all tests
In some places, just remove aparently unnecessary filters.
After this, all cases of ignore filters should be removed from
the tests, making testing (even multiple runs) normally fully
predictable.
-rw-r--r-- | numpy/core/tests/test_einsum.py | 9 | ||||
-rw-r--r-- | numpy/core/tests/test_function_base.py | 8 | ||||
-rw-r--r-- | numpy/core/tests/test_memmap.py | 16 | ||||
-rw-r--r-- | numpy/core/tests/test_multiarray.py | 26 | ||||
-rw-r--r-- | numpy/core/tests/test_nditer.py | 9 | ||||
-rw-r--r-- | numpy/core/tests/test_numeric.py | 43 | ||||
-rw-r--r-- | numpy/core/tests/test_regression.py | 38 | ||||
-rw-r--r-- | numpy/core/tests/test_scalarmath.py | 9 | ||||
-rw-r--r-- | numpy/core/tests/test_umath.py | 7 | ||||
-rw-r--r-- | numpy/lib/tests/test_function_base.py | 33 | ||||
-rw-r--r-- | numpy/lib/tests/test_io.py | 29 | ||||
-rw-r--r-- | numpy/linalg/tests/test_linalg.py | 10 | ||||
-rw-r--r-- | numpy/ma/tests/test_core.py | 88 | ||||
-rw-r--r-- | numpy/ma/tests/test_extras.py | 36 | ||||
-rw-r--r-- | numpy/ma/tests/test_mrecords.py | 8 | ||||
-rw-r--r-- | numpy/ma/tests/test_old_ma.py | 120 | ||||
-rw-r--r-- | numpy/ma/tests/test_regression.py | 8 | ||||
-rw-r--r-- | numpy/random/tests/test_random.py | 26 |
18 files changed, 266 insertions, 257 deletions
diff --git a/numpy/core/tests/test_einsum.py b/numpy/core/tests/test_einsum.py index 77fb75f10..c31d281e9 100644 --- a/numpy/core/tests/test_einsum.py +++ b/numpy/core/tests/test_einsum.py @@ -1,13 +1,12 @@ from __future__ import division, absolute_import, print_function -import warnings - import numpy as np from numpy.testing import ( TestCase, run_module_suite, assert_, assert_equal, assert_array_equal, - assert_raises + assert_raises, suppress_warnings ) + class TestEinSum(TestCase): def test_einsum_errors(self): # Need enough arguments @@ -282,8 +281,8 @@ class TestEinSum(TestCase): assert_equal(np.einsum(a, [0], b, [1]), np.outer(a, b)) # Suppress the complex warnings for the 'as f8' tests - with warnings.catch_warnings(): - warnings.simplefilter('ignore', np.ComplexWarning) + with suppress_warnings() as sup: + sup.filter(np.ComplexWarning) # matvec(a,b) / a.dot(b) where a is matrix, b is vector for n in range(1, 17): diff --git a/numpy/core/tests/test_function_base.py b/numpy/core/tests/test_function_base.py index 0fabb2588..9b20c4ff5 100644 --- a/numpy/core/tests/test_function_base.py +++ b/numpy/core/tests/test_function_base.py @@ -4,7 +4,7 @@ from numpy import (logspace, linspace, geomspace, dtype, array, finfo, typecodes, arange, isnan, ndarray, sqrt) from numpy.testing import ( TestCase, run_module_suite, assert_, assert_equal, assert_raises, - assert_array_equal, assert_allclose + assert_array_equal, assert_allclose, suppress_warnings ) @@ -205,8 +205,10 @@ class TestLinspace(TestCase): def test_corner(self): y = list(linspace(0, 1, 1)) assert_(y == [0.0], y) - y = list(linspace(0, 1, 2.5)) - assert_(y == [0.0, 1.0]) + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, ".*safely interpreted as an integer") + y = list(linspace(0, 1, 2.5)) + assert_(y == [0.0, 1.0]) def test_type(self): t1 = linspace(0, 1, 0).dtype diff --git a/numpy/core/tests/test_memmap.py b/numpy/core/tests/test_memmap.py index 4aa02e26f..30c8b7c54 100644 --- a/numpy/core/tests/test_memmap.py +++ b/numpy/core/tests/test_memmap.py @@ -12,7 +12,7 @@ from numpy.compat import Path from numpy import arange, allclose, asarray from numpy.testing import ( TestCase, run_module_suite, assert_, assert_equal, assert_array_equal, - dec + dec, suppress_warnings ) class TestMemmap(TestCase): @@ -146,13 +146,15 @@ class TestMemmap(TestCase): fp = memmap(self.tmpfp, dtype=self.dtype, shape=self.shape) fp[:] = self.data - for unary_op in [sum, average, product]: - result = unary_op(fp) - assert_(isscalar(result)) - assert_(result.__class__ is self.data[0, 0].__class__) + with suppress_warnings() as sup: + sup.filter(FutureWarning, "np.average currently does not preserve") + for unary_op in [sum, average, product]: + result = unary_op(fp) + assert_(isscalar(result)) + assert_(result.__class__ is self.data[0, 0].__class__) - assert_(unary_op(fp, axis=0).__class__ is ndarray) - assert_(unary_op(fp, axis=1).__class__ is ndarray) + assert_(unary_op(fp, axis=0).__class__ is ndarray) + assert_(unary_op(fp, axis=1).__class__ is ndarray) for binary_op in [add, subtract, multiply]: assert_(binary_op(fp, self.data).__class__ is ndarray) diff --git a/numpy/core/tests/test_multiarray.py b/numpy/core/tests/test_multiarray.py index 977378cfa..2b585f4dc 100644 --- a/numpy/core/tests/test_multiarray.py +++ b/numpy/core/tests/test_multiarray.py @@ -29,7 +29,7 @@ from numpy.testing import ( TestCase, run_module_suite, assert_, assert_raises, assert_equal, assert_almost_equal, assert_array_equal, assert_array_almost_equal, assert_allclose, IS_PYPY, HAS_REFCOUNT, - assert_array_less, runstring, dec, SkipTest, temppath + assert_array_less, runstring, dec, SkipTest, temppath, suppress_warnings ) # Need to test an object that does not fully implement math interface @@ -826,8 +826,8 @@ class TestStructured(TestCase): # This comparison invokes deprecated behaviour, and will probably # start raising an error eventually. What we really care about in this # test is just that it doesn't return True. - with warnings.catch_warnings(): - warnings.filterwarnings("ignore", category=DeprecationWarning) + with suppress_warnings() as sup: + sup.filter(FutureWarning, "elementwise == comparison failed") assert_equal(x == y, False) x = np.zeros((1,), dtype=[('a', ('f4', (2, 1))), ('b', 'i1')]) @@ -835,8 +835,8 @@ class TestStructured(TestCase): # This comparison invokes deprecated behaviour, and will probably # start raising an error eventually. What we really care about in this # test is just that it doesn't return True. - with warnings.catch_warnings(): - warnings.filterwarnings("ignore", category=DeprecationWarning) + with suppress_warnings() as sup: + sup.filter(FutureWarning, "elementwise == comparison failed") assert_equal(x == y, False) # Check that structured arrays that are different only in @@ -3818,11 +3818,11 @@ class TestIO(object): def fail(*args, **kwargs): raise io.IOError('Can not tell or seek') - f = io.open(self.filename, 'rb', buffering=0) - f.seek = fail - f.tell = fail - y = np.fromfile(self.filename, dtype=self.dtype) - assert_array_equal(y, self.x.flat) + with io.open(self.filename, 'rb', buffering=0) as f: + f.seek = fail + f.tell = fail + y = np.fromfile(self.filename, dtype=self.dtype) + assert_array_equal(y, self.x.flat) def test_largish_file(self): # check the fallocate path on files > 16MB @@ -6039,11 +6039,11 @@ class TestNewBufferProtocol(object): class TestArrayAttributeDeletion(object): def test_multiarray_writable_attributes_deletion(self): - """ticket #2046, should not seqfault, raise AttributeError""" + # ticket #2046, should not seqfault, raise AttributeError a = np.ones(2) attr = ['shape', 'strides', 'data', 'dtype', 'real', 'imag', 'flat'] - with warnings.catch_warnings(): - warnings.simplefilter('ignore') + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, "Assigning the 'data' attribute") for s in attr: assert_raises(AttributeError, delattr, a, s) diff --git a/numpy/core/tests/test_nditer.py b/numpy/core/tests/test_nditer.py index f83d81624..3b5aaa28d 100644 --- a/numpy/core/tests/test_nditer.py +++ b/numpy/core/tests/test_nditer.py @@ -1,7 +1,6 @@ from __future__ import division, absolute_import, print_function import sys -import warnings import numpy as np from numpy import array, arange, nditer, all @@ -9,7 +8,7 @@ from numpy.compat import asbytes, sixu from numpy.core.multiarray_tests import test_nditer_too_large from numpy.testing import ( run_module_suite, assert_, assert_equal, assert_array_equal, - assert_raises, dec, HAS_REFCOUNT + assert_raises, dec, HAS_REFCOUNT, suppress_warnings ) @@ -1624,8 +1623,8 @@ def test_iter_buffered_cast_byteswapped(): assert_equal(a, 2*np.arange(10, dtype='f4')) - try: - warnings.simplefilter("ignore", np.ComplexWarning) + with suppress_warnings() as sup: + sup.filter(np.ComplexWarning) a = np.arange(10, dtype='f8').newbyteorder().byteswap() i = nditer(a, ['buffered', 'external_loop'], @@ -1637,8 +1636,6 @@ def test_iter_buffered_cast_byteswapped(): v[...] *= 2 assert_equal(a, 2*np.arange(10, dtype='f8')) - finally: - warnings.simplefilter("default", np.ComplexWarning) def test_iter_buffered_cast_byteswapped_complex(): # Test that buffering can handle a cast which requires swap->cast->copy diff --git a/numpy/core/tests/test_numeric.py b/numpy/core/tests/test_numeric.py index 990d13a3e..c31e9e07c 100644 --- a/numpy/core/tests/test_numeric.py +++ b/numpy/core/tests/test_numeric.py @@ -12,7 +12,7 @@ from numpy.random import rand, randint, randn from numpy.testing import ( TestCase, run_module_suite, assert_, assert_equal, assert_raises, assert_raises_regex, assert_array_equal, assert_almost_equal, - assert_array_almost_equal, dec, HAS_REFCOUNT + assert_array_almost_equal, dec, HAS_REFCOUNT, suppress_warnings ) @@ -1976,27 +1976,26 @@ class TestCreationFuncs(TestCase): fill_kwarg = {} if fill_value is not None: fill_kwarg = {'fill_value': fill_value} - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - for size, ndims, order, dtype in itertools.product(*par): - shape = ndims * [size] - - # do not fill void type - if fill_kwarg and dtype.str.startswith('|V'): - continue - - arr = func(shape, order=order, dtype=dtype, - **fill_kwarg) - - assert_equal(arr.dtype, dtype) - assert_(getattr(arr.flags, self.orders[order])) - - if fill_value is not None: - if dtype.str.startswith('|S'): - val = str(fill_value) - else: - val = fill_value - assert_equal(arr, dtype.type(val)) + + for size, ndims, order, dtype in itertools.product(*par): + shape = ndims * [size] + + # do not fill void type + if fill_kwarg and dtype.str.startswith('|V'): + continue + + arr = func(shape, order=order, dtype=dtype, + **fill_kwarg) + + assert_equal(arr.dtype, dtype) + assert_(getattr(arr.flags, self.orders[order])) + + if fill_value is not None: + if dtype.str.startswith('|S'): + val = str(fill_value) + else: + val = fill_value + assert_equal(arr, dtype.type(val)) def test_zeros(self): self.check_function(np.zeros) diff --git a/numpy/core/tests/test_regression.py b/numpy/core/tests/test_regression.py index 022438ab1..b1d1673dd 100644 --- a/numpy/core/tests/test_regression.py +++ b/numpy/core/tests/test_regression.py @@ -15,7 +15,7 @@ import numpy as np from numpy.testing import ( run_module_suite, TestCase, assert_, assert_equal, assert_almost_equal, assert_array_equal, assert_array_almost_equal, - assert_raises, assert_warns, dec + assert_raises, assert_warns, dec, suppress_warnings ) from numpy.testing.utils import _assert_valid_refcount, HAS_REFCOUNT from numpy.compat import asbytes, asunicode, asbytes_nested, long, sixu @@ -138,8 +138,8 @@ class TestRegression(TestCase): self.assertTrue(a[0] != 'auto') b = np.linspace(0, 10, 11) # This should return true for now, but will eventually raise an error: - with warnings.catch_warnings(): - warnings.filterwarnings("ignore", category=DeprecationWarning) + with suppress_warnings() as sup: + sup.filter(DeprecationWarning) self.assertTrue(b != 'auto') self.assertTrue(b[0] != 'auto') @@ -811,9 +811,9 @@ class TestRegression(TestCase): # This might seem odd as compared to the value error below. This # is due to the fact that the new code always uses "nonzero" logic # and the boolean special case is not taken. - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - warnings.simplefilter('ignore', np.VisibleDeprecationWarning) + with suppress_warnings() as sup: + sup.filter(DeprecationWarning) + sup.filter(np.VisibleDeprecationWarning) self.assertRaises(IndexError, ia, x, s, np.zeros(9, dtype=float)) self.assertRaises(IndexError, ia, x, s, np.zeros(11, dtype=float)) # Old special case (different code path): @@ -1518,19 +1518,17 @@ class TestRegression(TestCase): dtypes = [x for x in np.typeDict.values() if (issubclass(x, np.number) and not issubclass(x, np.timedelta64))] - a = np.array([], dtypes[0]) + a = np.array([], np.bool_) # not x[0] because it is unordered failures = [] - # ignore complex warnings - with warnings.catch_warnings(): - warnings.simplefilter('ignore', np.ComplexWarning) - for x in dtypes: - b = a.astype(x) - for y in dtypes: - c = a.astype(y) - try: - np.dot(b, c) - except TypeError: - failures.append((x, y)) + + for x in dtypes: + b = a.astype(x) + for y in dtypes: + c = a.astype(y) + try: + np.dot(b, c) + except TypeError: + failures.append((x, y)) if failures: raise AssertionError("Failures: %r" % failures) @@ -1621,8 +1619,8 @@ class TestRegression(TestCase): for tp in [np.csingle, np.cdouble, np.clongdouble]: x = tp(1+2j) assert_warns(np.ComplexWarning, float, x) - with warnings.catch_warnings(): - warnings.simplefilter('ignore') + with suppress_warnings() as sup: + sup.filter(np.ComplexWarning) assert_equal(float(x), float(x.real)) def test_complex_scalar_complex_cast(self): diff --git a/numpy/core/tests/test_scalarmath.py b/numpy/core/tests/test_scalarmath.py index 1c71565f4..6b55f0101 100644 --- a/numpy/core/tests/test_scalarmath.py +++ b/numpy/core/tests/test_scalarmath.py @@ -2,14 +2,14 @@ from __future__ import division, absolute_import, print_function import sys import itertools -import warnings import operator import numpy as np from numpy.testing.utils import _gen_alignment_data from numpy.testing import ( TestCase, run_module_suite, assert_, assert_equal, assert_raises, - assert_almost_equal, assert_allclose, assert_array_equal, IS_PYPY + assert_almost_equal, assert_allclose, assert_array_equal, IS_PYPY, + suppress_warnings ) types = [np.bool_, np.byte, np.ubyte, np.short, np.ushort, np.intc, np.uintc, @@ -238,9 +238,8 @@ class TestModulus(TestCase): assert_(rem >= -b, 'dt: %s' % dt) # Check nans, inf - with warnings.catch_warnings(): - warnings.simplefilter('always') - warnings.simplefilter('ignore', RuntimeWarning) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in remainder") for dt in np.typecodes['Float']: fone = np.array(1.0, dtype=dt) fzer = np.array(0.0, dtype=dt) diff --git a/numpy/core/tests/test_umath.py b/numpy/core/tests/test_umath.py index 759e996e3..20bcec241 100644 --- a/numpy/core/tests/test_umath.py +++ b/numpy/core/tests/test_umath.py @@ -11,7 +11,7 @@ import numpy as np from numpy.testing import ( TestCase, run_module_suite, assert_, assert_equal, assert_raises, assert_array_equal, assert_almost_equal, assert_array_almost_equal, - dec, assert_allclose, assert_no_warnings + dec, assert_allclose, assert_no_warnings, suppress_warnings ) @@ -300,9 +300,8 @@ class TestRemainder(TestCase): assert_(rem >= -b, 'dt: %s' % dt) # Check nans, inf - with warnings.catch_warnings(): - warnings.simplefilter('always') - warnings.simplefilter('ignore', RuntimeWarning) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in remainder") for dt in np.typecodes['Float']: fone = np.array(1.0, dtype=dt) fzer = np.array(0.0, dtype=dt) diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py index 0d7b11c44..4535c1e7f 100644 --- a/numpy/lib/tests/test_function_base.py +++ b/numpy/lib/tests/test_function_base.py @@ -8,7 +8,7 @@ from numpy.testing import ( run_module_suite, TestCase, assert_, assert_equal, assert_array_equal, assert_almost_equal, assert_array_almost_equal, assert_raises, assert_allclose, assert_array_max_ulp, assert_warns, - assert_raises_regex, dec, clear_and_catch_warnings + assert_raises_regex, dec, suppress_warnings ) from numpy.testing.utils import HAS_REFCOUNT import numpy.lib.function_base as nfb @@ -320,7 +320,11 @@ class TestAverage(TestCase): a = np.array([[1,2],[3,4]]).view(subclass) w = np.array([[1,2],[3,4]]).view(subclass) - assert_equal(type(np.average(a, weights=w)), subclass) + with suppress_warnings() as sup: + # Note that the warning is spurious, because the test checks + # for weights while a is ignored. + sup.filter(FutureWarning, "np.average currently does not preserve") + assert_equal(type(np.average(a, weights=w)), subclass) # also test matrices a = np.matrix([[1,2],[3,4]]) @@ -1457,12 +1461,12 @@ class TestHistogram(TestCase): a, b = histogram([], bins=([0, 1])) assert_array_equal(a, np.array([0])) assert_array_equal(b, np.array([0, 1])) - + def test_error_binnum_type (self): # Tests if right Error is raised if bins argument is float vals = np.linspace(0.0, 1.0, num=100) histogram(vals, 5) - assert_raises(TypeError, histogram, vals, 2.4) + assert_raises(TypeError, histogram, vals, 2.4) def test_finite_range(self): # Normal ranges should be fine @@ -1792,15 +1796,6 @@ class TestCheckFinite(TestCase): assert_(a.dtype == np.float64) -class catch_warn_nfb(clear_and_catch_warnings): - - """ - Context manager to catch, reset warnings in function_base module - - """ - class_modules = (nfb,) - - class TestCorrCoef(TestCase): A = np.array( [[0.15391142, 0.18045767, 0.14197213], @@ -1837,10 +1832,10 @@ class TestCorrCoef(TestCase): def test_ddof(self): # ddof raises DeprecationWarning - with catch_warn_nfb(): + with suppress_warnings() as sup: warnings.simplefilter("always") assert_warns(DeprecationWarning, corrcoef, self.A, ddof=-1) - warnings.simplefilter("ignore") + sup.filter(DeprecationWarning) # ddof has no or negligible effect on the function assert_almost_equal(corrcoef(self.A, ddof=-1), self.res1) assert_almost_equal(corrcoef(self.A, self.B, ddof=-1), self.res2) @@ -1849,11 +1844,11 @@ class TestCorrCoef(TestCase): def test_bias(self): # bias raises DeprecationWarning - with catch_warn_nfb(): + with suppress_warnings() as sup: warnings.simplefilter("always") assert_warns(DeprecationWarning, corrcoef, self.A, self.B, 1, 0) assert_warns(DeprecationWarning, corrcoef, self.A, bias=0) - warnings.simplefilter("ignore") + sup.filter(DeprecationWarning) # bias has no or negligible effect on the function assert_almost_equal(corrcoef(self.A, bias=1), self.res1) @@ -2316,7 +2311,7 @@ class TestInterp(TestCase): assert_almost_equal(np.interp(x0, x, y), x0) x0 = np.nan assert_almost_equal(np.interp(x0, x, y), x0) - + def test_complex_interp(self): # test complex interpolation x = np.linspace(0, 1, 5) @@ -2335,7 +2330,7 @@ class TestInterp(TestCase): x = [-180, -170, -185, 185, -10, -5, 0, 365] xp = [190, -190, 350, -350] fp = [5+1.0j, 10+2j, 3+3j, 4+4j] - y = [7.5+1.5j, 5.+1.0j, 8.75+1.75j, 6.25+1.25j, 3.+3j, 3.25+3.25j, + y = [7.5+1.5j, 5.+1.0j, 8.75+1.75j, 6.25+1.25j, 3.+3j, 3.25+3.25j, 3.5+3.5j, 3.75+3.75j] assert_almost_equal(np.interp(x, xp, fp, period=360), y) diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py index 1474349de..333891d46 100644 --- a/numpy/lib/tests/test_io.py +++ b/numpy/lib/tests/test_io.py @@ -19,7 +19,7 @@ from numpy.ma.testutils import assert_equal from numpy.testing import ( TestCase, run_module_suite, assert_warns, assert_, assert_raises_regex, assert_raises, assert_allclose, - assert_array_equal, temppath, dec, IS_PYPY + assert_array_equal, temppath, dec, IS_PYPY, suppress_warnings ) @@ -282,8 +282,8 @@ class TestSavezLoad(RoundtripTest, TestCase): # collector, so we catch the warnings. Because ResourceWarning # is unknown in Python < 3.x, we take the easy way out and # catch all warnings. - with warnings.catch_warnings(): - warnings.simplefilter("ignore") + with suppress_warnings() as sup: + sup.filter(Warning) # TODO: specify exact message for i in range(1, 1025): try: np.load(tmp)["data"] @@ -687,9 +687,8 @@ class TestLoadTxt(TestCase): assert_array_equal(x, a) def test_empty_file(self): - with warnings.catch_warnings(): - warnings.filterwarnings("ignore", - message="loadtxt: Empty input file:") + with suppress_warnings() as sup: + sup.filter(message="loadtxt: Empty input file:") c = TextIO() x = np.loadtxt(c) assert_equal(x.shape, (0,)) @@ -826,9 +825,8 @@ class TestLoadTxt(TestCase): assert_(x.shape == (3,)) # Test ndmin kw with empty file. - with warnings.catch_warnings(): - warnings.filterwarnings("ignore", - message="loadtxt: Empty input file:") + with suppress_warnings() as sup: + sup.filter(message="loadtxt: Empty input file:") f = TextIO() assert_(np.loadtxt(f, ndmin=2).shape == (0, 1,)) assert_(np.loadtxt(f, ndmin=1).shape == (0,)) @@ -974,8 +972,8 @@ class TestFromTxt(TestCase): assert_equal(test, ctrl) def test_skip_footer_with_invalid(self): - with warnings.catch_warnings(): - warnings.filterwarnings("ignore") + with suppress_warnings() as sup: + sup.filter(ConversionWarning) basestr = '1 1\n2 2\n3 3\n4 4\n5 \n6 \n7 \n' # Footer too small to get rid of all invalid values assert_raises(ValueError, np.genfromtxt, @@ -1302,9 +1300,8 @@ M 33 21.99 def test_empty_file(self): # Test that an empty file raises the proper warning. - with warnings.catch_warnings(): - warnings.filterwarnings("ignore", - message="genfromtxt: Empty input file:") + with suppress_warnings() as sup: + sup.filter(message="genfromtxt: Empty input file:") data = TextIO() test = np.genfromtxt(data) assert_equal(test, np.array([])) @@ -1751,8 +1748,8 @@ M 33 21.99 assert_raises(ValueError, np.genfromtxt, TextIO(data), max_rows=4) # Test with invalid not raise - with warnings.catch_warnings(): - warnings.filterwarnings("ignore") + with suppress_warnings() as sup: + sup.filter(ConversionWarning) test = np.genfromtxt(TextIO(data), max_rows=4, invalid_raise=False) control = np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]]) diff --git a/numpy/linalg/tests/test_linalg.py b/numpy/linalg/tests/test_linalg.py index a89378acd..a353271de 100644 --- a/numpy/linalg/tests/test_linalg.py +++ b/numpy/linalg/tests/test_linalg.py @@ -18,7 +18,7 @@ from numpy.linalg.linalg import _multi_dot_matrix_chain_order from numpy.testing import ( assert_, assert_equal, assert_raises, assert_array_equal, assert_almost_equal, assert_allclose, run_module_suite, - dec, SkipTest + dec, SkipTest, suppress_warnings ) @@ -861,8 +861,8 @@ class _TestNorm(object): assert_(issubclass(an.dtype.type, np.floating)) assert_almost_equal(an, 0.0) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", RuntimeWarning) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "divide by zero encountered") an = norm(at, -1) assert_(issubclass(an.dtype.type, np.floating)) assert_almost_equal(an, 0.0) @@ -906,8 +906,8 @@ class _TestNorm(object): assert_(issubclass(an.dtype.type, np.floating)) assert_almost_equal(an, 2.0) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", RuntimeWarning) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "divide by zero encountered") an = norm(at, -1) assert_(issubclass(an.dtype.type, np.floating)) assert_almost_equal(an, 1.0) diff --git a/numpy/ma/tests/test_core.py b/numpy/ma/tests/test_core.py index b3965000d..6719ed618 100644 --- a/numpy/ma/tests/test_core.py +++ b/numpy/ma/tests/test_core.py @@ -19,13 +19,14 @@ import numpy as np import numpy.ma.core import numpy.core.fromnumeric as fromnumeric import numpy.core.umath as umath -from numpy.testing import TestCase, run_module_suite, assert_raises +from numpy.testing import ( + TestCase, run_module_suite, assert_raises, suppress_warnings) from numpy import ndarray from numpy.compat import asbytes, asbytes_nested from numpy.ma.testutils import ( assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, - assert_mask_equal, + assert_mask_equal ) from numpy.ma.core import ( MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, @@ -48,6 +49,12 @@ from numpy.ma.core import ( pi = np.pi +suppress_copy_mask_on_assignment = suppress_warnings() +suppress_copy_mask_on_assignment.filter( + numpy.ma.core.MaskedArrayFutureWarning, + "setting an item on a masked array which has a shared mask will not copy") + + class TestMaskedArray(TestCase): # Base test class for MaskedArrays. @@ -366,6 +373,7 @@ class TestMaskedArray(TestCase): assert_(allequal(array([0, 0, 0, 1, 0], MaskType), x2.mask)) assert_equal(3.0, x2.fill_value) + @suppress_copy_mask_on_assignment def test_copy(self): # Tests of some subtle points of copying and sizing. n = [0, 0, 1, 0, 0] @@ -524,14 +532,14 @@ class TestMaskedArray(TestCase): assert_equal(1.0, float(array([[1]]))) self.assertRaises(TypeError, float, array([1, 1])) - with warnings.catch_warnings(): - warnings.simplefilter('ignore', UserWarning) + with suppress_warnings() as sup: + sup.filter(UserWarning, 'Warning: converting a masked element') assert_(np.isnan(float(array([1], mask=[1])))) - a = array([1, 2, 3], mask=[1, 0, 0]) - self.assertRaises(TypeError, lambda:float(a)) - assert_equal(float(a[-1]), 3.) - self.assertTrue(np.isnan(float(a[0]))) + a = array([1, 2, 3], mask=[1, 0, 0]) + self.assertRaises(TypeError, lambda: float(a)) + assert_equal(float(a[-1]), 3.) + self.assertTrue(np.isnan(float(a[0]))) self.assertRaises(TypeError, int, a) assert_equal(int(a[-1]), 3) self.assertRaises(MAError, lambda:int(a[0])) @@ -578,6 +586,7 @@ class TestMaskedArray(TestCase): assert_(z[1] is not masked) assert_(z[2] is masked) + @suppress_copy_mask_on_assignment def test_oddfeatures_3(self): # Tests some generic features atest = array([10], mask=True) @@ -1335,24 +1344,28 @@ class TestMaskedArrayArithmetic(TestCase): def test_eq_w_None(self): # Really, comparisons with None should not be done, but check them # anyway. Note that pep8 will flag these tests. + # Deprecation is in place for arrays, and when it happens this + # test will fail (and have to be changed accordingly). # With partial mask - a = array([1, 2], mask=[0, 1]) - assert_equal(a == None, False) - assert_equal(a.data == None, False) - assert_equal(a.mask == None, False) - assert_equal(a != None, True) - # With nomask - a = array([1, 2], mask=False) - assert_equal(a == None, False) - assert_equal(a != None, True) - # With complete mask - a = array([1, 2], mask=True) - assert_equal(a == None, False) - assert_equal(a != None, True) - # Fully masked, even comparison to None should return "masked" - a = masked - assert_equal(a == None, masked) + with suppress_warnings() as sup: + sup.filter(FutureWarning, "Comparison to `None`") + a = array([1, 2], mask=[0, 1]) + assert_equal(a == None, False) + assert_equal(a.data == None, False) + assert_equal(a.mask == None, False) + assert_equal(a != None, True) + # With nomask + a = array([1, 2], mask=False) + assert_equal(a == None, False) + assert_equal(a != None, True) + # With complete mask + a = array([1, 2], mask=True) + assert_equal(a == None, False) + assert_equal(a != None, True) + # Fully masked, even comparison to None should return "masked" + a = masked + assert_equal(a == None, masked) def test_eq_w_scalar(self): a = array(1) @@ -2416,8 +2429,9 @@ class TestMaskedArrayInPlaceArithmetics(TestCase): def test_inplace_division_scalar_type(self): # Test of inplace division for t in self.othertypes: - with warnings.catch_warnings(record=True) as w: - warnings.filterwarnings("always") + with suppress_warnings() as sup: + sup.record(UserWarning) + (x, y, xm) = (_.astype(t) for _ in self.uint8data) x = arange(10, dtype=t) * t(2) xm = arange(10, dtype=t) * t(2) @@ -2444,15 +2458,15 @@ class TestMaskedArrayInPlaceArithmetics(TestCase): warnings.warn(str(e)) if issubclass(t, np.integer): - assert_equal(len(w), 2, "Failed on type=%s." % t) + assert_equal(len(sup.log), 2, "Failed on type=%s." % t) else: - assert_equal(len(w), 0, "Failed on type=%s." % t) + assert_equal(len(sup.log), 0, "Failed on type=%s." % t) def test_inplace_division_array_type(self): # Test of inplace division for t in self.othertypes: - with warnings.catch_warnings(record=True) as w: - warnings.filterwarnings("always") + with suppress_warnings() as sup: + sup.record(UserWarning) (x, y, xm) = (_.astype(t) for _ in self.uint8data) m = xm.mask a = arange(10, dtype=t) @@ -2483,9 +2497,9 @@ class TestMaskedArrayInPlaceArithmetics(TestCase): warnings.warn(str(e)) if issubclass(t, np.integer): - assert_equal(len(w), 2, "Failed on type=%s." % t) + assert_equal(len(sup.log), 2, "Failed on type=%s." % t) else: - assert_equal(len(w), 0, "Failed on type=%s." % t) + assert_equal(len(sup.log), 0, "Failed on type=%s." % t) def test_inplace_pow_type(self): # Test keeping data w/ (inplace) power @@ -2762,6 +2776,7 @@ class TestMaskedArrayMethods(TestCase): b = a.view(masked_array) assert_(np.may_share_memory(a.mask, b.mask)) + @suppress_copy_mask_on_assignment def test_put(self): # Tests put. d = arange(5) @@ -3347,6 +3362,7 @@ class TestMaskedArrayMathMethods(TestCase): assert_almost_equal(np.sqrt(mXvar0[k]), mX[:, k].compressed().std()) + @suppress_copy_mask_on_assignment def test_varstd_specialcases(self): # Test a special case for var nout = np.array(-1, dtype=float) @@ -3359,15 +3375,11 @@ class TestMaskedArrayMathMethods(TestCase): self.assertTrue(method(0) is masked) self.assertTrue(method(-1) is masked) # Using a masked array as explicit output - with warnings.catch_warnings(): - warnings.simplefilter('ignore') - method(out=mout) + method(out=mout) self.assertTrue(mout is not masked) assert_equal(mout.mask, True) # Using a ndarray as explicit output - with warnings.catch_warnings(): - warnings.simplefilter('ignore') - method(out=nout) + method(out=nout) self.assertTrue(np.isnan(nout)) x = array(arange(10), mask=True) diff --git a/numpy/ma/tests/test_extras.py b/numpy/ma/tests/test_extras.py index 33c4b1922..45c7e2e8a 100644 --- a/numpy/ma/tests/test_extras.py +++ b/numpy/ma/tests/test_extras.py @@ -13,7 +13,7 @@ import warnings import numpy as np from numpy.testing import ( - TestCase, run_module_suite, assert_warns, clear_and_catch_warnings + TestCase, run_module_suite, assert_warns, suppress_warnings ) from numpy.ma.testutils import ( assert_, assert_array_equal, assert_equal, assert_almost_equal @@ -826,12 +826,6 @@ class TestCov(TestCase): x.shape[0] / frac)) -class catch_warn_mae(clear_and_catch_warnings): - """ Context manager to catch, reset warnings in ma.extras module - """ - class_modules = (mae,) - - class TestCorrcoef(TestCase): def setUp(self): @@ -843,10 +837,10 @@ class TestCorrcoef(TestCase): x, y = self.data, self.data2 expected = np.corrcoef(x) expected2 = np.corrcoef(x, y) - with catch_warn_mae(): + with suppress_warnings() as sup: warnings.simplefilter("always") assert_warns(DeprecationWarning, corrcoef, x, ddof=-1) - warnings.simplefilter("ignore") + sup.filter(DeprecationWarning, "bias and ddof have no effect") # ddof has no or negligible effect on the function assert_almost_equal(np.corrcoef(x, ddof=0), corrcoef(x, ddof=0)) assert_almost_equal(corrcoef(x, ddof=-1), expected) @@ -858,12 +852,12 @@ class TestCorrcoef(TestCase): x, y = self.data, self.data2 expected = np.corrcoef(x) # bias raises DeprecationWarning - with catch_warn_mae(): + with suppress_warnings() as sup: warnings.simplefilter("always") assert_warns(DeprecationWarning, corrcoef, x, y, True, False) assert_warns(DeprecationWarning, corrcoef, x, y, True, True) assert_warns(DeprecationWarning, corrcoef, x, bias=False) - warnings.simplefilter("ignore") + sup.filter(DeprecationWarning, "bias and ddof have no effect") # bias has no or negligible effect on the function assert_almost_equal(corrcoef(x, bias=1), expected) @@ -873,8 +867,8 @@ class TestCorrcoef(TestCase): assert_almost_equal(np.corrcoef(x), corrcoef(x)) assert_almost_equal(np.corrcoef(x, rowvar=False), corrcoef(x, rowvar=False)) - with catch_warn_mae(): - warnings.simplefilter("ignore") + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, "bias and ddof have no effect") assert_almost_equal(np.corrcoef(x, rowvar=False, bias=True), corrcoef(x, rowvar=False, bias=True)) @@ -884,8 +878,8 @@ class TestCorrcoef(TestCase): assert_almost_equal(np.corrcoef(x), corrcoef(x)) assert_almost_equal(np.corrcoef(x, rowvar=False), corrcoef(x, rowvar=False)) - with catch_warn_mae(): - warnings.simplefilter("ignore") + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, "bias and ddof have no effect") assert_almost_equal(np.corrcoef(x, rowvar=False, bias=True), corrcoef(x, rowvar=False, bias=True)) @@ -898,8 +892,8 @@ class TestCorrcoef(TestCase): assert_almost_equal(np.corrcoef(nx), corrcoef(x)) assert_almost_equal(np.corrcoef(nx, rowvar=False), corrcoef(x, rowvar=False)) - with catch_warn_mae(): - warnings.simplefilter("ignore") + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, "bias and ddof have no effect") assert_almost_equal(np.corrcoef(nx, rowvar=False, bias=True), corrcoef(x, rowvar=False, bias=True)) try: @@ -911,8 +905,8 @@ class TestCorrcoef(TestCase): assert_almost_equal(np.corrcoef(nx, nx[::-1]), corrcoef(x, x[::-1])) assert_almost_equal(np.corrcoef(nx, nx[::-1], rowvar=False), corrcoef(x, x[::-1], rowvar=False)) - with catch_warn_mae(): - warnings.simplefilter("ignore") + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, "bias and ddof have no effect") # ddof and bias have no or negligible effect on the function assert_almost_equal(np.corrcoef(nx, nx[::-1]), corrcoef(x, x[::-1], bias=1)) @@ -928,8 +922,8 @@ class TestCorrcoef(TestCase): test = corrcoef(x) control = np.corrcoef(x) assert_almost_equal(test[:-1, :-1], control[:-1, :-1]) - with catch_warn_mae(): - warnings.simplefilter("ignore") + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, "bias and ddof have no effect") # ddof and bias have no or negligible effect on the function assert_almost_equal(corrcoef(x, ddof=-2)[:-1, :-1], control[:-1, :-1]) diff --git a/numpy/ma/tests/test_mrecords.py b/numpy/ma/tests/test_mrecords.py index e97f337f5..ea5d14de0 100644 --- a/numpy/ma/tests/test_mrecords.py +++ b/numpy/ma/tests/test_mrecords.py @@ -148,11 +148,9 @@ class TestMRecords(TestCase): rdata = data.view(MaskedRecords) val = ma.array([10, 20, 30], mask=[1, 0, 0]) - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - rdata['num'] = val - assert_equal(rdata.num, val) - assert_equal(rdata.num.mask, [1, 0, 0]) + rdata['num'] = val + assert_equal(rdata.num, val) + assert_equal(rdata.num.mask, [1, 0, 0]) def test_set_fields_mask(self): # Tests setting the mask of a field. diff --git a/numpy/ma/tests/test_old_ma.py b/numpy/ma/tests/test_old_ma.py index ed8304d63..2ea53683d 100644 --- a/numpy/ma/tests/test_old_ma.py +++ b/numpy/ma/tests/test_old_ma.py @@ -5,7 +5,8 @@ from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.fromnumeric as fromnumeric -from numpy.testing import TestCase, run_module_suite, assert_ +from numpy.testing import ( + TestCase, run_module_suite, assert_, suppress_warnings) from numpy.ma.testutils import assert_array_equal from numpy.ma import ( MaskType, MaskedArray, absolute, add, all, allclose, allequal, alltrue, @@ -257,62 +258,73 @@ class TestMa(TestCase): def test_testCopySize(self): # Tests of some subtle points of copying and sizing. - n = [0, 0, 1, 0, 0] - m = make_mask(n) - m2 = make_mask(m) - self.assertTrue(m is m2) - m3 = make_mask(m, copy=1) - self.assertTrue(m is not m3) - - x1 = np.arange(5) - y1 = array(x1, mask=m) - self.assertTrue(y1._data is not x1) - self.assertTrue(allequal(x1, y1._data)) - self.assertTrue(y1.mask is m) - - y1a = array(y1, copy=0) - self.assertTrue(y1a.mask is y1.mask) - - y2 = array(x1, mask=m, copy=0) - self.assertTrue(y2.mask is m) - self.assertTrue(y2[2] is masked) - y2[2] = 9 - self.assertTrue(y2[2] is not masked) - self.assertTrue(y2.mask is not m) - self.assertTrue(allequal(y2.mask, 0)) - - y3 = array(x1 * 1.0, mask=m) - self.assertTrue(filled(y3).dtype is (x1 * 1.0).dtype) - - x4 = arange(4) - x4[2] = masked - y4 = resize(x4, (8,)) - self.assertTrue(eq(concatenate([x4, x4]), y4)) - self.assertTrue(eq(getmask(y4), [0, 0, 1, 0, 0, 0, 1, 0])) - y5 = repeat(x4, (2, 2, 2, 2), axis=0) - self.assertTrue(eq(y5, [0, 0, 1, 1, 2, 2, 3, 3])) - y6 = repeat(x4, 2, axis=0) - self.assertTrue(eq(y5, y6)) + with suppress_warnings() as sup: + sup.filter( + np.ma.core.MaskedArrayFutureWarning, + "setting an item on a masked array which has a " + "shared mask will not copy") + + n = [0, 0, 1, 0, 0] + m = make_mask(n) + m2 = make_mask(m) + self.assertTrue(m is m2) + m3 = make_mask(m, copy=1) + self.assertTrue(m is not m3) + + x1 = np.arange(5) + y1 = array(x1, mask=m) + self.assertTrue(y1._data is not x1) + self.assertTrue(allequal(x1, y1._data)) + self.assertTrue(y1.mask is m) + + y1a = array(y1, copy=0) + self.assertTrue(y1a.mask is y1.mask) + + y2 = array(x1, mask=m, copy=0) + self.assertTrue(y2.mask is m) + self.assertTrue(y2[2] is masked) + y2[2] = 9 + self.assertTrue(y2[2] is not masked) + self.assertTrue(y2.mask is not m) + self.assertTrue(allequal(y2.mask, 0)) + + y3 = array(x1 * 1.0, mask=m) + self.assertTrue(filled(y3).dtype is (x1 * 1.0).dtype) + + x4 = arange(4) + x4[2] = masked + y4 = resize(x4, (8,)) + self.assertTrue(eq(concatenate([x4, x4]), y4)) + self.assertTrue(eq(getmask(y4), [0, 0, 1, 0, 0, 0, 1, 0])) + y5 = repeat(x4, (2, 2, 2, 2), axis=0) + self.assertTrue(eq(y5, [0, 0, 1, 1, 2, 2, 3, 3])) + y6 = repeat(x4, 2, axis=0) + self.assertTrue(eq(y5, y6)) def test_testPut(self): # Test of put - d = arange(5) - n = [0, 0, 0, 1, 1] - m = make_mask(n) - x = array(d, mask=m) - self.assertTrue(x[3] is masked) - self.assertTrue(x[4] is masked) - x[[1, 4]] = [10, 40] - self.assertTrue(x.mask is not m) - self.assertTrue(x[3] is masked) - self.assertTrue(x[4] is not masked) - self.assertTrue(eq(x, [0, 10, 2, -1, 40])) - - x = array(d, mask=m) - x.put([0, 1, 2], [-1, 100, 200]) - self.assertTrue(eq(x, [-1, 100, 200, 0, 0])) - self.assertTrue(x[3] is masked) - self.assertTrue(x[4] is masked) + with suppress_warnings() as sup: + sup.filter( + np.ma.core.MaskedArrayFutureWarning, + "setting an item on a masked array which has a " + "shared mask will not copy") + d = arange(5) + n = [0, 0, 0, 1, 1] + m = make_mask(n) + x = array(d, mask=m) + self.assertTrue(x[3] is masked) + self.assertTrue(x[4] is masked) + x[[1, 4]] = [10, 40] + self.assertTrue(x.mask is not m) + self.assertTrue(x[3] is masked) + self.assertTrue(x[4] is not masked) + self.assertTrue(eq(x, [0, 10, 2, -1, 40])) + + x = array(d, mask=m) + x.put([0, 1, 2], [-1, 100, 200]) + self.assertTrue(eq(x, [-1, 100, 200, 0, 0])) + self.assertTrue(x[3] is masked) + self.assertTrue(x[4] is masked) def test_testMaPut(self): (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d diff --git a/numpy/ma/tests/test_regression.py b/numpy/ma/tests/test_regression.py index dba74d357..fc6cdfaff 100644 --- a/numpy/ma/tests/test_regression.py +++ b/numpy/ma/tests/test_regression.py @@ -4,7 +4,8 @@ import warnings import numpy as np from numpy.testing import (assert_, TestCase, assert_array_equal, - assert_allclose, run_module_suite) + assert_allclose, run_module_suite, + suppress_warnings) from numpy.compat import sixu rlevel = 1 @@ -69,8 +70,9 @@ class TestRegression(TestCase): # See gh-3336 x = np.ma.masked_equal([1, 2, 3, 4, 5], 4) y = np.array([2, 2.5, 3.1, 3, 5]) - with warnings.catch_warnings(): - warnings.simplefilter("ignore") + # this test can be removed after deprecation. + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, "bias and ddof have no effect") r0 = np.ma.corrcoef(x, y, ddof=0) r1 = np.ma.corrcoef(x, y, ddof=1) # ddof should not have an effect (it gets cancelled out) diff --git a/numpy/random/tests/test_random.py b/numpy/random/tests/test_random.py index a06de58e3..012bf4826 100644 --- a/numpy/random/tests/test_random.py +++ b/numpy/random/tests/test_random.py @@ -3,7 +3,8 @@ from __future__ import division, absolute_import, print_function import numpy as np from numpy.testing import ( TestCase, run_module_suite, assert_, assert_raises, assert_equal, - assert_warns, assert_array_equal, assert_array_almost_equal) + assert_warns, assert_array_equal, assert_array_almost_equal, + suppress_warnings) from numpy import random from numpy.compat import asbytes import sys @@ -260,13 +261,14 @@ class TestRandomDist(TestCase): def test_random_integers(self): np.random.seed(self.seed) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) + with suppress_warnings() as sup: + w = sup.record(DeprecationWarning) actual = np.random.random_integers(-99, 99, size=(3, 2)) - desired = np.array([[31, 3], - [-52, 41], - [-48, -66]]) - assert_array_equal(actual, desired) + assert_(len(w) == 1) + desired = np.array([[31, 3], + [-52, 41], + [-48, -66]]) + assert_array_equal(actual, desired) def test_random_integers_max_int(self): # Tests whether random_integers can generate the @@ -274,12 +276,14 @@ class TestRandomDist(TestCase): # into a C long. Previous implementations of this # method have thrown an OverflowError when attempting # to generate this integer. - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) + with suppress_warnings() as sup: + w = sup.record(DeprecationWarning) actual = np.random.random_integers(np.iinfo('l').max, np.iinfo('l').max) - desired = np.iinfo('l').max - assert_equal(actual, desired) + assert_(len(w) == 1) + + desired = np.iinfo('l').max + assert_equal(actual, desired) def test_random_integers_deprecated(self): with warnings.catch_warnings(): |