Skip to content

Commit fb605c9

Browse files
committed
ENH: Add suppress_warnings
1 parent 1c6738d commit fb605c9

File tree

11 files changed

+48
-40
lines changed

11 files changed

+48
-40
lines changed

nibabel/testing/__init__.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from os.path import dirname, abspath, join as pjoin
1111

1212
import numpy as np
13+
from warnings import catch_warnings, simplefilter
1314

1415
# set path to example data
1516
data_path = abspath(pjoin(dirname(__file__), '..', 'tests', 'data'))
@@ -49,3 +50,12 @@ def assert_allclose_safely(a, b, match_nans=True):
4950
if b.dtype.kind in 'ui':
5051
b = b.astype(float)
5152
assert_true(np.allclose(a, b))
53+
54+
55+
class suppress_warnings(catch_warnings):
56+
""" Version of ``catch_warnings`` class that suppresses warnings
57+
"""
58+
def __enter__(self):
59+
res = super(suppress_warnings, self).__enter__()
60+
simplefilter('ignore')
61+
return res

nibabel/tests/test_analyze.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
import logging
1818
import pickle
1919
import itertools
20-
import warnings
2120

2221
import numpy as np
2322

@@ -36,7 +35,8 @@
3635
assert_array_almost_equal)
3736

3837
from ..testing import (assert_equal, assert_not_equal, assert_true,
39-
assert_false, assert_raises, data_path)
38+
assert_false, assert_raises, data_path,
39+
suppress_warnings)
4040

4141
from .test_wrapstruct import _TestLabeledWrapStruct
4242
from . import test_spatialimages as tsi
@@ -99,7 +99,7 @@ def test_empty(self):
9999

100100
def _set_something_into_hdr(self, hdr):
101101
# Called from test_bytes test method. Specific to the header data type
102-
with warnings.catch_warnings(record=True):
102+
with suppress_warnings():
103103
hdr.set_data_shape((1, 2, 3))
104104

105105
def test_checks(self):
@@ -109,7 +109,7 @@ def test_checks(self):
109109
assert_equal(self._dxer(hdr_t), '')
110110
hdr = hdr_t.copy()
111111
hdr['sizeof_hdr'] = 1
112-
with warnings.catch_warnings(record=True):
112+
with suppress_warnings():
113113
assert_equal(self._dxer(hdr), 'sizeof_hdr should be ' +
114114
str(self.sizeof_hdr))
115115
hdr = hdr_t.copy()
@@ -129,7 +129,7 @@ def test_log_checks(self):
129129
HC = self.header_class
130130
# magic
131131
hdr = HC()
132-
with warnings.catch_warnings(record=True):
132+
with suppress_warnings():
133133
hdr['sizeof_hdr'] = 350 # severity 30
134134
fhdr, message, raiser = self.log_chk(hdr, 30)
135135
assert_equal(fhdr['sizeof_hdr'], self.sizeof_hdr)
@@ -144,7 +144,7 @@ def test_log_checks(self):
144144
# datatype not recognized
145145
hdr = HC()
146146
hdr['datatype'] = -1 # severity 40
147-
with warnings.catch_warnings(record=True):
147+
with suppress_warnings():
148148
fhdr, message, raiser = self.log_chk(hdr, 40)
149149
assert_equal(message, 'data code -1 not recognized; '
150150
'not attempting fix')

nibabel/tests/test_arraywriters.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
from platform import python_compiler, machine
99
from distutils.version import LooseVersion
1010
import itertools
11-
import warnings
1211
import numpy as np
1312

1413
from ..externals.six import BytesIO
@@ -28,7 +27,7 @@
2827
assert_equal, assert_not_equal,
2928
assert_raises)
3029

31-
from ..testing import assert_allclose_safely
30+
from ..testing import assert_allclose_safely, suppress_warnings
3231
from ..checkwarns import ErrorWarnings
3332

3433

@@ -135,7 +134,7 @@ def test_no_scaling():
135134
kwargs = (dict(check_scaling=False) if awt == ArrayWriter
136135
else dict(calc_scale=False))
137136
aw = awt(arr, out_dtype, **kwargs)
138-
with warnings.catch_warnings(record=True): # cast to real from cplx
137+
with suppress_warnings(): # cast to real from cplx
139138
back_arr = round_trip(aw)
140139
exp_back = arr.astype(float)
141140
if out_dtype in IUINT_TYPES:
@@ -643,7 +642,7 @@ def test_float_int_min_max():
643642
continue
644643
for out_dt in IUINT_TYPES:
645644
try:
646-
with warnings.catch_warnings(record=True): # overflow
645+
with suppress_warnings(): # overflow
647646
aw = SlopeInterArrayWriter(arr, out_dt)
648647
except ScalingError:
649648
continue

nibabel/tests/test_casting.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,12 @@
33
import os
44

55
from platform import machine
6-
import warnings
76
import numpy as np
87

98
from ..casting import (float_to_int, shared_range, CastingError, int_to_float,
109
as_int, int_abs, floor_log2, able_int_type, best_float,
1110
ulp, longdouble_precision_improved)
11+
from ..testing import suppress_warnings
1212

1313
from numpy.testing import (assert_array_almost_equal, assert_array_equal)
1414

@@ -23,7 +23,7 @@ def test_shared_range():
2323
# (if this system generates that) or something smaller (because of
2424
# overflow)
2525
mn, mx = shared_range(ft, it)
26-
with warnings.catch_warnings(record=True):
26+
with suppress_warnings():
2727
ovs = ft(mx) + np.arange(2048, dtype=ft)
2828
# Float16 can overflow to inf
2929
bit_bigger = ovs[np.isfinite(ovs)].astype(it)
@@ -52,7 +52,7 @@ def test_shared_range():
5252
assert_equal(mn, 0)
5353
continue
5454
# And something larger for the minimum
55-
with warnings.catch_warnings(record=True): # overflow
55+
with suppress_warnings(): # overflow
5656
ovs = ft(mn) - np.arange(2048, dtype=ft)
5757
# Float16 can overflow to inf
5858
bit_smaller = ovs[np.isfinite(ovs)].astype(it)

nibabel/tests/test_ecat.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,12 @@
1616
from ..ecat import EcatHeader, EcatMlist, EcatSubHeader, EcatImage
1717

1818
from unittest import TestCase
19-
import warnings
2019
from nose.tools import (assert_true, assert_false, assert_equal,
2120
assert_not_equal, assert_raises)
2221

2322
from numpy.testing import assert_array_equal, assert_array_almost_equal
2423

25-
from ..testing import data_path
24+
from ..testing import data_path, suppress_warnings
2625
from ..tmpdirs import InTemporaryDirectory
2726

2827
from .test_wrapstruct import _TestWrapStructBase
@@ -112,7 +111,7 @@ def test_mlist(self):
112111
6.01670000e+04, 1.00000000e+00],
113112
[ 1.68427580e+07, 6.01680000e+04,
114113
7.22000000e+04, 1.00000000e+00]])
115-
with warnings.catch_warnings(record=True): # STORED order
114+
with suppress_warnings(): # STORED order
116115
assert_true(badordermlist.get_frame_order()[0][0] == 1)
117116

118117
def test_mlist_errors(self):
@@ -132,19 +131,19 @@ def test_mlist_errors(self):
132131
6.01670000e+04, 1.00000000e+00],
133132
[ 1.68427580e+07, 6.01680000e+04,
134133
7.22000000e+04, 1.00000000e+00]])
135-
with warnings.catch_warnings(record=True): # STORED order
134+
with suppress_warnings(): # STORED order
136135
series_framenumbers = mlist.get_series_framenumbers()
137136
# first frame stored was actually 2nd frame acquired
138137
assert_true(series_framenumbers[0] == 2)
139138
order = [series_framenumbers[x] for x in sorted(series_framenumbers)]
140139
# true series order is [2,1,3,4,5,6], note counting starts at 1
141140
assert_true(order == [2, 1, 3, 4, 5, 6])
142141
mlist._mlist[0,0] = 0
143-
with warnings.catch_warnings(record=True):
142+
with suppress_warnings():
144143
frames_order = mlist.get_frame_order()
145144
neworder =[frames_order[x][0] for x in sorted(frames_order)]
146145
assert_true(neworder == [1, 2, 3, 4, 5])
147-
with warnings.catch_warnings(record=True):
146+
with suppress_warnings():
148147
assert_raises(IOError,
149148
mlist.get_series_framenumbers)
150149

nibabel/tests/test_floating.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,12 @@
55
PY2 = sys.version_info[0] < 3
66

77
import numpy as np
8-
import warnings
98

109
from ..casting import (floor_exact, ceil_exact, as_int, FloatingError,
1110
int_to_float, floor_log2, type_info, _check_nmant,
1211
_check_maxexp, ok_floats, on_powerpc, have_binary128,
1312
longdouble_precision_improved)
13+
from ..testing import suppress_warnings
1414

1515
from nose import SkipTest
1616
from nose.tools import assert_equal, assert_raises, assert_true, assert_false
@@ -93,10 +93,10 @@ def test_check_nmant_nexp():
9393
assert_true(_check_nmant(t, nmant))
9494
assert_false(_check_nmant(t, nmant - 1))
9595
assert_false(_check_nmant(t, nmant + 1))
96-
with warnings.catch_warnings(record=True): # overflow
96+
with suppress_warnings(): # overflow
9797
assert_true(_check_maxexp(t, maxexp))
9898
assert_false(_check_maxexp(t, maxexp - 1))
99-
with warnings.catch_warnings(record=True):
99+
with suppress_warnings():
100100
assert_false(_check_maxexp(t, maxexp + 1))
101101
# Check against type_info
102102
for t in ok_floats():

nibabel/tests/test_nifti1.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
from nose.tools import (assert_true, assert_false, assert_equal,
3333
assert_raises)
3434

35-
from ..testing import data_path
35+
from ..testing import data_path, suppress_warnings
3636

3737
from . import test_analyze as tana
3838
from . import test_spm99analyze as tspm
@@ -256,7 +256,7 @@ def test_freesurfer_hack(self):
256256
hdr.set_data_shape((too_big-1, 1, 1))
257257
assert_equal(hdr.get_data_shape(), (too_big-1, 1, 1))
258258
# The freesurfer case
259-
with warnings.catch_warnings(record=True):
259+
with suppress_warnings():
260260
hdr.set_data_shape((too_big, 1, 1))
261261
assert_equal(hdr.get_data_shape(), (too_big, 1, 1))
262262
assert_array_equal(hdr['dim'][:4], [3, -1, 1, 1])
@@ -271,7 +271,7 @@ def test_freesurfer_hack(self):
271271
assert_raises(HeaderDataError, hdr.set_data_shape, (1, 1, too_big))
272272
# Outside range of glmin raises error
273273
far_too_big = int(np.iinfo(glmin).max) + 1
274-
with warnings.catch_warnings(record=True):
274+
with suppress_warnings():
275275
hdr.set_data_shape((far_too_big-1, 1, 1))
276276
assert_equal(hdr.get_data_shape(), (far_too_big-1, 1, 1))
277277
assert_raises(HeaderDataError, hdr.set_data_shape, (far_too_big,1,1))
@@ -282,7 +282,7 @@ def test_freesurfer_hack(self):
282282
# Lists or tuples or arrays will work for setting shape
283283
for shape in ((too_big-1, 1, 1), (too_big, 1, 1)):
284284
for constructor in (list, tuple, np.array):
285-
with warnings.catch_warnings(record=True):
285+
with suppress_warnings():
286286
hdr.set_data_shape(constructor(shape))
287287
assert_equal(hdr.get_data_shape(), shape)
288288

nibabel/tests/test_scaling.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@
1010
from __future__ import division, print_function, absolute_import
1111

1212
import numpy as np
13-
import warnings
1413

1514
from ..externals.six import BytesIO
1615
from ..volumeutils import (calculate_scale, scale_min_max, finite_range,
1716
apply_read_scaling, array_to_file, array_from_file)
1817
from ..casting import type_info
18+
from ..testing import suppress_warnings
1919

2020
from numpy.testing import (assert_array_almost_equal, assert_array_equal)
2121

@@ -242,7 +242,7 @@ def test_scaling_in_abstract():
242242
):
243243
for in_type in np.sctypes[category0]:
244244
for out_type in np.sctypes[category1]:
245-
with warnings.catch_warnings(record=True): # overflow
245+
with suppress_warnings(): # overflow
246246
check_int_a2f(in_type, out_type)
247247

248248

nibabel/tests/test_spatialimages.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
1111
"""
1212
from ..externals.six import BytesIO
13-
import warnings
1413
import numpy as np
1514

1615
from ..spatialimages import (Header, SpatialImage, HeaderDataError,
@@ -24,6 +23,7 @@
2423
from numpy.testing import assert_array_equal, assert_array_almost_equal
2524

2625
from .test_helpers import bytesio_round_trip
26+
from ..testing import suppress_warnings
2727

2828

2929
def test_header_init():
@@ -292,7 +292,7 @@ def test_get_shape(self):
292292
# Assumes all possible images support int16
293293
# See https://github.com/nipy/nibabel/issues/58
294294
img = img_klass(np.arange(1, dtype=np.int16), np.eye(4))
295-
with warnings.catch_warnings(record=True):
295+
with suppress_warnings():
296296
assert_equal(img.get_shape(), (1,))
297297
img = img_klass(np.zeros((2,3,4), np.int16), np.eye(4))
298298
assert_equal(img.get_shape(), (2,3,4))

nibabel/tests/test_spm99analyze.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99

1010
import numpy as np
1111
import itertools
12-
import warnings
1312

1413
from ..externals.six import BytesIO
1514

@@ -33,7 +32,7 @@
3332

3433
from nose.tools import assert_true, assert_false, assert_equal, assert_raises
3534

36-
from ..testing import assert_allclose_safely
35+
from ..testing import assert_allclose_safely, suppress_warnings
3736

3837
from . import test_analyze
3938
from .test_helpers import (bytesio_round_trip, bytesio_filemap, bz2_mio_error)
@@ -331,7 +330,7 @@ def test_no_scaling(self):
331330
img.set_data_dtype(out_dtype)
332331
img.header.set_slope_inter(slope, inter)
333332
rt_img = bytesio_round_trip(img)
334-
with warnings.catch_warnings(record=True): # invalid mult
333+
with suppress_warnings(): # invalid mult
335334
back_arr = rt_img.get_data()
336335
exp_back = arr.copy()
337336
if in_dtype not in COMPLEX_TYPES:
@@ -343,7 +342,7 @@ def test_no_scaling(self):
343342
else:
344343
exp_back = exp_back.astype(out_dtype)
345344
# Allow for small differences in large numbers
346-
with warnings.catch_warnings(record=True): # invalid value
345+
with suppress_warnings(): # invalid value
347346
assert_allclose_safely(back_arr,
348347
exp_back * slope + inter)
349348

0 commit comments

Comments
 (0)