Skip to content

Commit 36a1adf

Browse files
committed
TEST: Use matches or comments to make clear expected warnings
1 parent dae2f86 commit 36a1adf

12 files changed

+48
-63
lines changed

nibabel/freesurfer/tests/test_io.py

+6-8
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 pytest.warns(Warning) 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 pytest.warns(Warning) 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 pytest.warns(Warning) 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

+5-5
Original file line numberDiff line numberDiff line change
@@ -345,13 +345,13 @@ 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-
with pytest.deprecated_call():
348+
with pytest.deprecated_call(match="from version: 2.3"):
349349
assert_array_equal(hdr['mrparams'], 0)
350350
assert_array_equal(hdr_data['mrparams'], 0)
351351

352-
with pytest.deprecated_call():
352+
with pytest.deprecated_call(match="from version: 2.3"):
353353
hdr['mrparams'] = [1, 2, 3, 4]
354-
with pytest.deprecated_call():
354+
with pytest.deprecated_call(match="from version: 2.3"):
355355
assert_array_almost_equal(hdr['mrparams'], [1, 2, 3, 4])
356356
assert hdr['tr'] == 1
357357
assert hdr['flip_angle'] == 2
@@ -369,15 +369,15 @@ def test_deprecated_fields():
369369
hdr['flip_angle'] = 6
370370
hdr['te'] = 7
371371
hdr['ti'] = 8
372-
with pytest.deprecated_call():
372+
with pytest.deprecated_call(match="from version: 2.3"):
373373
assert_array_almost_equal(hdr['mrparams'], [5, 6, 7, 8])
374374
assert_array_almost_equal(hdr_data['mrparams'], [5, 6, 7, 8])
375375

376376
hdr_data['tr'] = 9
377377
hdr_data['flip_angle'] = 10
378378
hdr_data['te'] = 11
379379
hdr_data['ti'] = 12
380-
with pytest.deprecated_call():
380+
with pytest.deprecated_call(match="from version: 2.3"):
381381
assert_array_almost_equal(hdr['mrparams'], [9, 10, 11, 12])
382382
assert_array_almost_equal(hdr_data['mrparams'], [9, 10, 11, 12])
383383

nibabel/nicom/tests/test_dicomwrappers.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -660,14 +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-
with pytest.warns(UserWarning):
663+
with pytest.warns(UserWarning, match="Derived images found and removed"):
664664
assert dw.image_shape == (96, 96, 60, 33)
665665

666666
@dicom_test
667667
@needs_nibabel_data('nitest-dicom')
668668
def test_data_unreadable_private_headers(self):
669669
# Test CT image with unreadable CSA tags
670-
with pytest.warns(UserWarning):
670+
with pytest.warns(UserWarning, match="Error while attempting to read CSA header"):
671671
dw = didw.wrapper_from_file(DATA_FILE_CT)
672672
assert dw.image_shape == (512, 571)
673673

nibabel/streamlines/tests/test_array_sequence.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -94,14 +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-
with pytest.warns(Warning):
104-
assert seq_with_buffer.data.shape == seq.data.shape
108+
assert seq_with_buffer.get_data().shape == seq.get_data().shape
105109
assert seq_with_buffer._buffer_size > seq._buffer_size
106110

107111
# Check generator result

nibabel/streamlines/tests/test_streamlines.py

+3-9
Original file line numberDiff line numberDiff line change
@@ -201,14 +201,11 @@ def test_save_tractogram_file(self):
201201
nib.streamlines.save(trk_file, "dummy.trk", header={})
202202

203203
# Wrong extension.
204-
with pytest.warns(ExtensionWarning) as w:
204+
with pytest.warns(ExtensionWarning, match="extension"):
205205
trk_file = trk.TrkFile(tractogram)
206206
with self.assertRaises(ValueError):
207207
nib.streamlines.save(trk_file, "dummy.tck", header={})
208208

209-
assert len(w) == 1
210-
assert "extension" in str(w[0].message)
211-
212209
with InTemporaryDirectory():
213210
nib.streamlines.save(trk_file, "dummy.trk")
214211
tfile = nib.streamlines.load("dummy.trk", lazy_load=False)
@@ -243,19 +240,16 @@ def test_save_complex_file(self):
243240
with InTemporaryDirectory():
244241
filename = 'streamlines' + ext
245242

246-
with pytest.warns(None) as w:
247-
nib.streamlines.save(complex_tractogram, filename)
248-
249243
# If streamlines format does not support saving data
250244
# per point or data per streamline, warning messages
251245
# should be issued.
252246
nb_expected_warnings = \
253247
((not cls.SUPPORTS_DATA_PER_POINT) +
254248
(not cls.SUPPORTS_DATA_PER_STREAMLINE))
255249

250+
with pytest.warns(Warning if nb_expected_warnings else None) as w:
251+
nib.streamlines.save(complex_tractogram, filename)
256252
assert len(w) == nb_expected_warnings
257-
for i in range(nb_expected_warnings):
258-
assert issubclass(w[i].category, Warning)
259253

260254
tractogram = Tractogram(DATA['streamlines'],
261255
affine_to_rasmm=np.eye(4))

nibabel/streamlines/tests/test_tck.py

+2-6
Original file line numberDiff line numberDiff line change
@@ -113,18 +113,14 @@ def test_load_file_with_wrong_information(self):
113113
new_tck_file = tck_file.replace(b"datatype: Float32LE\n", b"")
114114
# Need to adjust data offset.
115115
new_tck_file = new_tck_file.replace(b"file: . 67\n", b"file: . 47\n")
116-
with pytest.warns(HeaderWarning) as w:
116+
with pytest.warns(HeaderWarning, match="Missing 'datatype'"):
117117
tck = TckFile.load(BytesIO(new_tck_file))
118-
assert len(w) == 1
119-
assert "Missing 'datatype'" in str(w[0].message)
120118
assert_array_equal(tck.header['datatype'], "Float32LE")
121119

122120
# Simulate a TCK file with no `file` field.
123121
new_tck_file = tck_file.replace(b"\nfile: . 67", b"")
124-
with pytest.warns(HeaderWarning) as w:
122+
with pytest.warns(HeaderWarning, matches="Missing 'file'") as w:
125123
tck = TckFile.load(BytesIO(new_tck_file))
126-
assert len(w) == 1
127-
assert "Missing 'file'" in str(w[0].message)
128124
assert_array_equal(tck.header['file'], ". 56")
129125

130126
# Simulate a TCK file with `file` field pointing to another file.

nibabel/streamlines/tests/test_tractogram.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -811,7 +811,7 @@ def test_lazy_tractogram_creation(self):
811811

812812
# Empty `LazyTractogram`
813813
tractogram = LazyTractogram()
814-
with pytest.warns(Warning):
814+
with pytest.warns(Warning, match="Number of streamlines will be determined manually"):
815815
check_tractogram(tractogram)
816816
assert tractogram.affine_to_rasmm is None
817817

@@ -833,7 +833,7 @@ def test_lazy_tractogram_creation(self):
833833
def test_lazy_tractogram_from_data_func(self):
834834
# Create an empty `LazyTractogram` yielding nothing.
835835
tractogram = LazyTractogram.from_data_func(lambda: iter([]))
836-
with pytest.warns(Warning):
836+
with pytest.warns(Warning, match="Number of streamlines will be determined manually"):
837837
check_tractogram(tractogram)
838838

839839
# Create `LazyTractogram` from a generator function yielding
@@ -854,7 +854,7 @@ def _data_gen():
854854
data_for_points)
855855

856856
tractogram = LazyTractogram.from_data_func(_data_gen)
857-
with pytest.warns(Warning):
857+
with pytest.warns(Warning, match="Number of streamlines will be determined manually"):
858858
assert_tractogram_equal(tractogram, DATA['tractogram'])
859859

860860
# Creating a LazyTractogram from not a corouting should raise an error.
@@ -924,7 +924,7 @@ def test_lazy_tractogram_apply_affine(self):
924924
assert_array_equal(transformed_tractogram._affine_to_apply, affine)
925925
assert_array_equal(transformed_tractogram.affine_to_rasmm,
926926
np.dot(np.eye(4), np.linalg.inv(affine)))
927-
with pytest.warns(Warning):
927+
with pytest.warns(Warning, match="Number of streamlines will be determined manually"):
928928
check_tractogram(transformed_tractogram,
929929
streamlines=[s*scaling for s in DATA['streamlines']],
930930
data_per_streamline=DATA['data_per_streamline'],
@@ -950,7 +950,7 @@ def test_lazy_tractogram_apply_affine(self):
950950
transformed_tractogram = tractogram.apply_affine(affine)
951951
assert_array_equal(transformed_tractogram._affine_to_apply, affine)
952952
assert transformed_tractogram.affine_to_rasmm is None
953-
with pytest.warns(Warning):
953+
with pytest.warns(Warning, match="Number of streamlines will be determined manually"):
954954
check_tractogram(transformed_tractogram,
955955
streamlines=[s*scaling for s in DATA['streamlines']],
956956
data_per_streamline=DATA['data_per_streamline'],
@@ -1024,5 +1024,5 @@ def test_lazy_tractogram_copy(self):
10241024
DATA['lazy_tractogram']._affine_to_apply)
10251025

10261026
# Check the data are the equivalent.
1027-
with pytest.warns(Warning):
1027+
with pytest.warns(Warning, match="Number of streamlines will be determined manually"):
10281028
assert_tractogram_equal(tractogram, DATA['tractogram'])

nibabel/streamlines/tests/test_trk.py

+3-10
Original file line numberDiff line numberDiff line change
@@ -135,10 +135,8 @@ def test_load_file_with_wrong_information(self):
135135
# Simulate a TRK where `vox_to_ras` is not recorded (i.e. all zeros).
136136
trk_struct, trk_bytes = self.trk_with_bytes()
137137
trk_struct[Field.VOXEL_TO_RASMM] = np.zeros((4, 4))
138-
with pytest.warns(HeaderWarning) as w:
138+
with pytest.warns(HeaderWarning, match="identity"):
139139
trk = TrkFile.load(BytesIO(trk_bytes))
140-
assert len(w) == 1
141-
assert "identity" in str(w[0].message)
142140
assert_array_equal(trk.affine, np.eye(4))
143141

144142
# Simulate a TRK where `vox_to_ras` is invalid.
@@ -151,17 +149,14 @@ def test_load_file_with_wrong_information(self):
151149
# Simulate a TRK file where `voxel_order` was not provided.
152150
trk_struct, trk_bytes = self.trk_with_bytes()
153151
trk_struct[Field.VOXEL_ORDER] = b''
154-
with pytest.warns(HeaderWarning) as w:
152+
with pytest.warns(HeaderWarning, match="LPS"):
155153
TrkFile.load(BytesIO(trk_bytes))
156-
assert len(w) == 1
157-
assert "LPS" in str(w[0].message)
158154

159155
# Simulate a TRK file with an unsupported version.
160156
trk_struct, trk_bytes = self.trk_with_bytes()
161157
trk_struct['version'] = 123
162158
with pytest.raises(HeaderError):
163159
TrkFile.load(BytesIO(trk_bytes))
164-
165160

166161
# Simulate a TRK file with a wrong hdr_size.
167162
trk_struct, trk_bytes = self.trk_with_bytes()
@@ -190,10 +185,8 @@ def test_load_trk_version_1(self):
190185
assert_array_equal(trk.affine, np.diag([2, 3, 4, 1]))
191186
# Next check that affine assumed identity if version 1.
192187
trk_struct['version'] = 1
193-
with pytest.warns(HeaderWarning) as w:
188+
with pytest.warns(HeaderWarning, match="identity"):
194189
trk = TrkFile.load(BytesIO(trk_bytes))
195-
assert len(w) == 1
196-
assert "identity" in str(w[0].message)
197190
assert_array_equal(trk.affine, np.eye(4))
198191
assert_array_equal(trk.header['version'], 1)
199192

nibabel/tests/test_analyze.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -734,10 +734,10 @@ def test_data_hdr_cache(self):
734734
assert_array_equal(np.asanyarray(img2.dataobj), data)
735735
# now check read_img_data function - here we do see the changed
736736
# header
737-
with pytest.deprecated_call():
737+
with pytest.deprecated_call(match="from version: 3.2"):
738738
sc_data = read_img_data(img2)
739739
assert sc_data.shape == (3, 2, 2)
740-
with pytest.deprecated_call():
740+
with pytest.deprecated_call(match="from version: 3.2"):
741741
us_data = read_img_data(img2, prefer='unscaled')
742742
assert us_data.shape == (3, 2, 2)
743743

nibabel/tests/test_ecat.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -240,7 +240,7 @@ def test_isolation(self):
240240
assert not np.all(img.affine == aff)
241241

242242
def test_get_affine_deprecated(self):
243-
with pytest.deprecated_call():
243+
with pytest.deprecated_call(match="from version: 2.1"):
244244
aff = self.img.get_affine()
245245
assert np.array_equal(aff, self.img.affine)
246246

nibabel/tests/test_parrec.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -671,11 +671,11 @@ def assert_copy_ok(hdr1, hdr2):
671671
PARRECHeader.from_fileobj(fobj)
672672
with open(TRUNC_PAR, 'rt') as fobj:
673673
# Parse but warn on inconsistent header
674-
with pytest.warns(UserWarning):
674+
with pytest.warns(UserWarning, match="Header inconsistency"):
675675
trunc_hdr = PARRECHeader.from_fileobj(fobj, True)
676676
assert trunc_hdr.permit_truncated
677677
# Warn on inconsistent header when copying
678-
with pytest.warns(UserWarning):
678+
with pytest.warns(UserWarning, match="Header inconsistency"):
679679
trunc_hdr2 = trunc_hdr.copy()
680680
assert_copy_ok(trunc_hdr, trunc_hdr2)
681681

@@ -716,13 +716,13 @@ def test_image_creation():
716716
func(trunc_param)
717717
with pytest.raises(PARRECError):
718718
func(trunc_param, permit_truncated=False)
719-
with pytest.warns(UserWarning):
719+
with pytest.warns(UserWarning, match="Header inconsistency"):
720720
img = func(trunc_param, permit_truncated=True)
721721
assert_array_equal(img.dataobj, arr_prox_dv)
722-
with pytest.warns(UserWarning):
722+
with pytest.warns(UserWarning, match="Header inconsistency"):
723723
img = func(trunc_param, permit_truncated=True, scaling='dv')
724724
assert_array_equal(img.dataobj, arr_prox_dv)
725-
with pytest.warns(UserWarning):
725+
with pytest.warns(UserWarning, match="Header inconsistency"):
726726
img = func(trunc_param, permit_truncated=True, scaling='fp')
727727
assert_array_equal(img.dataobj, arr_prox_fp)
728728

nibabel/tests/test_processing.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ def test_resample_from_to(caplog):
148148
exp_out[1:, :, :] = data[1, :, :]
149149
assert_almost_equal(out.dataobj, exp_out)
150150
out = resample_from_to(img, trans_p_25_img)
151-
with pytest.warns(UserWarning):
151+
with pytest.warns(UserWarning): # Suppress scipy warning
152152
exp_out = spnd.affine_transform(data, [1, 1, 1], [-0.25, 0, 0], order=3)
153153
assert_almost_equal(out.dataobj, exp_out)
154154
# Test cval
@@ -161,7 +161,7 @@ def test_resample_from_to(caplog):
161161
assert out.__class__ == Nifti1Image
162162
# By default, type of from_img makes no difference
163163
n1_img = Nifti2Image(data, affine)
164-
with caplog.at_level(logging.CRITICAL):
164+
with caplog.at_level(logging.CRITICAL): # Here and below, suppress logs when changing classes
165165
out = resample_from_to(n1_img, trans_img)
166166
assert out.__class__ == Nifti1Image
167167
# Passed as keyword arg
@@ -254,7 +254,7 @@ def test_resample_to_output(caplog):
254254
assert_array_equal(out_img.dataobj, np.flipud(data))
255255
# Subsample voxels
256256
out_img = resample_to_output(Nifti1Image(data, np.diag([4, 5, 6, 1])))
257-
with pytest.warns(UserWarning):
257+
with pytest.warns(UserWarning): # Suppress scipy warning
258258
exp_out = spnd.affine_transform(data,
259259
[1/4, 1/5, 1/6],
260260
output_shape = (5, 11, 19))
@@ -293,7 +293,7 @@ def test_resample_to_output(caplog):
293293
img_ni1 = Nifti2Image(data, np.eye(4))
294294
img_ni2 = Nifti2Image(data, np.eye(4))
295295
# Default is Nifti1Image
296-
with caplog.at_level(logging.CRITICAL):
296+
with caplog.at_level(logging.CRITICAL): # Here and below, suppress logs when changing classes
297297
assert resample_to_output(img_ni2).__class__ == Nifti1Image
298298
# Can be overriden
299299
with caplog.at_level(logging.CRITICAL):
@@ -349,7 +349,7 @@ def test_smooth_image(caplog):
349349
img_ni1 = Nifti1Image(data, np.eye(4))
350350
img_ni2 = Nifti2Image(data, np.eye(4))
351351
# Default is Nifti1Image
352-
with caplog.at_level(logging.CRITICAL):
352+
with caplog.at_level(logging.CRITICAL): # Here and below, suppress logs when changing classes
353353
assert smooth_image(img_ni2, 0).__class__ == Nifti1Image
354354
# Can be overriden
355355
with caplog.at_level(logging.CRITICAL):
@@ -362,7 +362,7 @@ def test_smooth_image(caplog):
362362
def test_spatial_axes_check(caplog):
363363
for fname in MINC_3DS + OTHER_IMGS:
364364
img = nib.load(pjoin(DATA_DIR, fname))
365-
with caplog.at_level(logging.CRITICAL):
365+
with caplog.at_level(logging.CRITICAL): # Suppress logs when changing classes
366366
s_img = smooth_image(img, 0)
367367
assert_array_equal(img.dataobj, s_img.dataobj)
368368
with caplog.at_level(logging.CRITICAL):
@@ -447,7 +447,7 @@ def test_conform(caplog):
447447
assert isinstance(c, Nifti1Image)
448448

449449
# Test with non-default arguments.
450-
with caplog.at_level(logging.CRITICAL):
450+
with caplog.at_level(logging.CRITICAL): # Suppress logs when changing classes
451451
c = conform(anat, out_shape=(100, 100, 200), voxel_size=(2, 2, 1.5),
452452
orientation="LPI", out_class=Nifti2Image)
453453
assert c.shape == (100, 100, 200)

0 commit comments

Comments
 (0)