Skip to content

Commit 36a1adf

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

File tree

12 files changed

+48
-63
lines changed

12 files changed

+48
-63
lines changed

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 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

Lines changed: 5 additions & 5 deletions
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

Lines changed: 2 additions & 2 deletions
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

Lines changed: 6 additions & 2 deletions
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

Lines changed: 3 additions & 9 deletions
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

Lines changed: 2 additions & 6 deletions
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

Lines changed: 6 additions & 6 deletions
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

Lines changed: 3 additions & 10 deletions
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

Lines changed: 2 additions & 2 deletions
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

Lines changed: 1 addition & 1 deletion
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

0 commit comments

Comments
 (0)