Skip to content

Commit acd69ea

Browse files
authored
Merge pull request #949 from effigies/test/reduce_warnings
TEST: Suppress expected warnings
2 parents e65b865 + 1dc4e8d commit acd69ea

40 files changed

+410
-274
lines changed

.travis.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ script:
147147
mkdir for_testing
148148
cd for_testing
149149
cp ../.coveragerc .
150-
pytest --doctest-modules --cov nibabel -v --pyargs nibabel
150+
pytest --doctest-modules --doctest-plus --cov nibabel -v --pyargs nibabel
151151
else
152152
false
153153
fi

nibabel/casting.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
casting. Others work round numpy casting to and from python ints
55
"""
66

7+
import warnings
78
from numbers import Integral
89
from platform import processor, machine
910

@@ -349,8 +350,9 @@ def _check_maxexp(np_type, maxexp):
349350
dt = np.dtype(np_type)
350351
np_type = dt.type
351352
two = np_type(2).reshape((1,)) # to avoid upcasting
352-
return (np.isfinite(two ** (maxexp - 1)) and
353-
not np.isfinite(two ** maxexp))
353+
with warnings.catch_warnings():
354+
warnings.simplefilter("ignore", RuntimeWarning) # Expected overflow warning
355+
return np.isfinite(two ** (maxexp - 1)) and not np.isfinite(two ** maxexp)
354356

355357

356358
def as_int(x, check=True):

nibabel/cifti2/cifti2.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1492,7 +1492,7 @@ def update_headers(self):
14921492
14931493
>>> import numpy as np
14941494
>>> data = np.zeros((2,3,4))
1495-
>>> img = Cifti2Image(data)
1495+
>>> img = Cifti2Image(data) # doctest: +IGNORE_WARNINGS
14961496
>>> img.shape == (2, 3, 4)
14971497
True
14981498
>>> img.update_headers()

nibabel/conftest.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import pytest
2+
3+
# Pre-load deprecated modules to avoid cluttering warnings
4+
with pytest.deprecated_call():
5+
import nibabel.keywordonly
6+
with pytest.deprecated_call():
7+
import nibabel.trackvis
8+
with pytest.warns(FutureWarning):
9+
import nibabel.py3k
10+
11+
# Ignore warning requesting help with nicom
12+
with pytest.warns(UserWarning):
13+
import nibabel.nicom

nibabel/deprecator.py

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,26 @@
77

88
_LEADING_WHITE = re.compile(r'^(\s*)')
99

10+
TESTSETUP = """
11+
12+
.. testsetup::
13+
14+
>>> import pytest
15+
>>> import warnings
16+
>>> _suppress_warnings = pytest.deprecated_call()
17+
>>> _ = _suppress_warnings.__enter__()
18+
19+
"""
20+
21+
TESTCLEANUP = """
22+
23+
.. testcleanup::
24+
25+
>>> warnings.warn("Avoid error if no doctests to run...", DeprecationWarning)
26+
>>> _ = _suppress_warnings.__exit__(None, None, None)
27+
28+
"""
29+
1030

1131
class ExpiredDeprecationError(RuntimeError):
1232
""" Error for expired deprecation
@@ -25,7 +45,7 @@ def _ensure_cr(text):
2545
return text.rstrip() + '\n'
2646

2747

28-
def _add_dep_doc(old_doc, dep_doc):
48+
def _add_dep_doc(old_doc, dep_doc, setup='', cleanup=''):
2949
""" Add deprecation message `dep_doc` to docstring in `old_doc`
3050
3151
Parameters
@@ -56,8 +76,11 @@ def _add_dep_doc(old_doc, dep_doc):
5676
# nothing following first paragraph, just append message
5777
return old_doc + '\n' + dep_doc
5878
indent = _LEADING_WHITE.match(old_lines[next_line]).group()
79+
setup_lines = [indent + L for L in setup.splitlines()]
5980
dep_lines = [indent + L for L in [''] + dep_doc.splitlines() + ['']]
60-
return '\n'.join(new_lines + dep_lines + old_lines[next_line:]) + '\n'
81+
cleanup_lines = [indent + L for L in cleanup.splitlines()]
82+
return '\n'.join(new_lines + dep_lines + setup_lines +
83+
old_lines[next_line:] + cleanup_lines + [''])
6184

6285

6386
class Deprecator(object):
@@ -160,7 +183,7 @@ def deprecated_func(*args, **kwargs):
160183
return func(*args, **kwargs)
161184

162185
deprecated_func.__doc__ = _add_dep_doc(deprecated_func.__doc__,
163-
message)
186+
message, TESTSETUP, TESTCLEANUP)
164187
return deprecated_func
165188

166189
return deprecator

nibabel/freesurfer/tests/test_io.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -86,16 +86,15 @@ def test_geometry():
8686

8787
# now write an incomplete file
8888
write_geometry(surf_path, coords, faces)
89-
with clear_and_catch_warnings() as w:
90-
warnings.filterwarnings('always', category=DeprecationWarning)
89+
with pytest.warns(UserWarning) as w:
9190
read_geometry(surf_path, read_metadata=True)
92-
9391
assert any('volume information contained' in str(ww.message) for ww in w)
9492
assert any('extension code' in str(ww.message) for ww in w)
93+
9594
volume_info['head'] = [1, 2]
96-
with clear_and_catch_warnings() as w:
95+
with pytest.warns(UserWarning, match="Unknown extension"):
9796
write_geometry(surf_path, coords, faces, create_stamp, volume_info)
98-
assert any('Unknown extension' in str(ww.message) for ww in w)
97+
9998
volume_info['a'] = 0
10099
with pytest.raises(ValueError):
101100
write_geometry(surf_path, coords, faces, create_stamp, volume_info)
@@ -266,10 +265,9 @@ def test_write_annot_fill_ctab():
266265
# values back.
267266
badannot = (10 * np.arange(nlabels, dtype=np.int32)).reshape(-1, 1)
268267
rgbal = np.hstack((rgba, badannot))
269-
with clear_and_catch_warnings() as w:
268+
with pytest.warns(UserWarning,
269+
match=f'Annotation values in {annot_path} will be incorrect'):
270270
write_annot(annot_path, labels, rgbal, names, fill_ctab=False)
271-
assert any(f'Annotation values in {annot_path} will be incorrect' == str(ww.message)
272-
for ww in w)
273271
labels2, rgbal2, names2 = read_annot(annot_path, orig_ids=True)
274272
names2 = [n.decode('ascii') for n in names2]
275273
assert np.all(np.isclose(rgbal2[:, :4], rgba))

nibabel/freesurfer/tests/test_mghformat.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -345,11 +345,14 @@ def test_deprecated_fields():
345345

346346
# mrparams is the only deprecated field at the moment
347347
# Accessing hdr_data is equivalent to accessing hdr, so double all checks
348-
assert_array_equal(hdr['mrparams'], 0)
348+
with pytest.deprecated_call(match="from version: 2.3"):
349+
assert_array_equal(hdr['mrparams'], 0)
349350
assert_array_equal(hdr_data['mrparams'], 0)
350351

351-
hdr['mrparams'] = [1, 2, 3, 4]
352-
assert_array_almost_equal(hdr['mrparams'], [1, 2, 3, 4])
352+
with pytest.deprecated_call(match="from version: 2.3"):
353+
hdr['mrparams'] = [1, 2, 3, 4]
354+
with pytest.deprecated_call(match="from version: 2.3"):
355+
assert_array_almost_equal(hdr['mrparams'], [1, 2, 3, 4])
353356
assert hdr['tr'] == 1
354357
assert hdr['flip_angle'] == 2
355358
assert hdr['te'] == 3
@@ -366,14 +369,16 @@ def test_deprecated_fields():
366369
hdr['flip_angle'] = 6
367370
hdr['te'] = 7
368371
hdr['ti'] = 8
369-
assert_array_almost_equal(hdr['mrparams'], [5, 6, 7, 8])
372+
with pytest.deprecated_call(match="from version: 2.3"):
373+
assert_array_almost_equal(hdr['mrparams'], [5, 6, 7, 8])
370374
assert_array_almost_equal(hdr_data['mrparams'], [5, 6, 7, 8])
371375

372376
hdr_data['tr'] = 9
373377
hdr_data['flip_angle'] = 10
374378
hdr_data['te'] = 11
375379
hdr_data['ti'] = 12
376-
assert_array_almost_equal(hdr['mrparams'], [9, 10, 11, 12])
380+
with pytest.deprecated_call(match="from version: 2.3"):
381+
assert_array_almost_equal(hdr['mrparams'], [9, 10, 11, 12])
377382
assert_array_almost_equal(hdr_data['mrparams'], [9, 10, 11, 12])
378383

379384

nibabel/keywordonly.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from functools import wraps
55
import warnings
66

7-
warnings.warn("We will remove this module from nibabel 5.0. "
7+
warnings.warn("We will remove the 'keywordonly' module from nibabel 5.0. "
88
"Please use the built-in Python `*` argument to ensure "
99
"keyword-only parameters (see PEP 3102).",
1010
DeprecationWarning,

nibabel/loadsave.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,7 @@ def load(filename, **kwargs):
5555
raise ImageFileError(f'Cannot work out file type of "{filename}"')
5656

5757

58-
@deprecate_with_version('guessed_image_type deprecated.'
59-
'2.1',
60-
'4.0')
58+
@deprecate_with_version('guessed_image_type deprecated.', '3.2', '5.0')
6159
def guessed_image_type(filename):
6260
""" Guess image type from file `filename`
6361
@@ -149,10 +147,10 @@ def save(img, filename):
149147
converted.to_filename(filename)
150148

151149

152-
@deprecate_with_version('read_img_data deprecated.'
153-
'Please use ``img.dataobj.get_unscaled()`` instead.'
154-
'2.0.1',
155-
'4.0')
150+
@deprecate_with_version('read_img_data deprecated. '
151+
'Please use ``img.dataobj.get_unscaled()`` instead.',
152+
'3.2',
153+
'5.0')
156154
def read_img_data(img, prefer='scaled'):
157155
""" Read data from image associated with files
158156
@@ -236,9 +234,7 @@ def read_img_data(img, prefer='scaled'):
236234
return hdr.raw_data_from_fileobj(fileobj)
237235

238236

239-
@deprecate_with_version('which_analyze_type deprecated.'
240-
'2.1',
241-
'4.0')
237+
@deprecate_with_version('which_analyze_type deprecated.', '3.2', '4.0')
242238
def which_analyze_type(binaryblock):
243239
""" Is `binaryblock` from NIfTI1, NIfTI2 or Analyze header?
244240

nibabel/nicom/ascconv.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ def parse_ascconv(ascconv_str, str_delim='"'):
205205
attrs, content = ASCCONV_RE.match(ascconv_str).groups()
206206
attrs = OrderedDict((tuple(x.split('=')) for x in attrs.split()))
207207
# Normalize string start / end markers to something Python understands
208-
content = content.replace(str_delim, '"""')
208+
content = content.replace(str_delim, '"""').replace("\\", "\\\\")
209209
# Use Python's own parser to parse modified ASCCONV assignments
210210
tree = ast.parse(content)
211211

nibabel/nicom/dicomreaders.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def mosaic_to_nii(dcm_data):
3232
if not dcm_w.is_mosaic:
3333
raise DicomReadError('data does not appear to be in mosaic format')
3434
data = dcm_w.get_data()
35-
aff = np.dot(DPCS_TO_TAL, dcm_w.get_affine())
35+
aff = np.dot(DPCS_TO_TAL, dcm_w.affine)
3636
return Nifti1Image(data, aff)
3737

3838

@@ -106,7 +106,7 @@ def read_mosaic_dir(dicom_path,
106106
g = dcm_w.b_vector
107107
b_values.append(b)
108108
gradients.append(g)
109-
affine = np.dot(DPCS_TO_TAL, dcm_w.get_affine())
109+
affine = np.dot(DPCS_TO_TAL, dcm_w.affine)
110110
return (np.concatenate(arrays, -1),
111111
affine,
112112
np.array(b_values),

nibabel/nicom/tests/test_dicomreaders.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
@dicom_test
2121
def test_read_dwi():
2222
img = didr.mosaic_to_nii(DATA)
23-
arr = img.get_data()
23+
arr = img.get_fdata()
2424
assert arr.shape == (128, 128, 48)
2525
assert_array_almost_equal(img.affine, EXPECTED_AFFINE)
2626

nibabel/nicom/tests/test_dicomwrappers.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -660,13 +660,14 @@ def test_data_derived_shape(self):
660660
# Test 4D diffusion data with an additional trace volume included
661661
# Excludes the trace volume and generates the correct shape
662662
dw = didw.wrapper_from_file(DATA_FILE_4D_DERIVED)
663-
assert dw.image_shape == (96, 96, 60, 33)
663+
with pytest.warns(UserWarning, match="Derived images found and removed"):
664+
assert dw.image_shape == (96, 96, 60, 33)
664665

665666
@dicom_test
666667
@needs_nibabel_data('nitest-dicom')
667668
def test_data_unreadable_private_headers(self):
668669
# Test CT image with unreadable CSA tags
669-
with pytest.warns(UserWarning):
670+
with pytest.warns(UserWarning, match="Error while attempting to read CSA header"):
670671
dw = didw.wrapper_from_file(DATA_FILE_CT)
671672
assert dw.image_shape == (512, 571)
672673

nibabel/processing.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,7 @@ def smooth_image(img,
300300
fwhm = np.zeros((n_dim,))
301301
fwhm[:3] = fwhm_scalar
302302
# Voxel sizes
303-
RZS = img.affine[:-1, :n_dim]
303+
RZS = img.affine[:, :n_dim]
304304
vox = np.sqrt(np.sum(RZS ** 2, 0))
305305
# Smoothing in terms of voxels
306306
vox_fwhm = fwhm / vox

nibabel/streamlines/tests/test_array_sequence.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,13 +94,18 @@ def test_creating_arraysequence_from_list(self):
9494
check_arr_seq(ArraySequence(iter(SEQ_DATA['data']), buffer_size),
9595
SEQ_DATA['data'])
9696

97+
def test_deprecated_data_attribute(self):
98+
seq = ArraySequence(SEQ_DATA['data'])
99+
with pytest.deprecated_call(match="from version: 3.0"):
100+
seq.data
101+
97102
def test_creating_arraysequence_from_generator(self):
98103
gen_1, gen_2 = itertools.tee((e for e in SEQ_DATA['data']))
99104
seq = ArraySequence(gen_1)
100105
seq_with_buffer = ArraySequence(gen_2, buffer_size=256)
101106

102107
# Check buffer size effect
103-
assert seq_with_buffer.data.shape == seq.data.shape
108+
assert seq_with_buffer.get_data().shape == seq.get_data().shape
104109
assert seq_with_buffer._buffer_size > seq._buffer_size
105110

106111
# Check generator result

0 commit comments

Comments
 (0)