Skip to content

Commit 27c2427

Browse files
authored
Merge pull request #1297 from effigies/fix/pytest
TEST: Accommodate pytest 8 changes
2 parents 5d884bd + cff2936 commit 27c2427

13 files changed

+70
-74
lines changed

nibabel/_compression.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from .optpkg import optional_package
1818

1919
if ty.TYPE_CHECKING: # pragma: no cover
20-
import indexed_gzip # type: ignore[import-not-found]
20+
import indexed_gzip # type: ignore[import]
2121
import pyzstd
2222

2323
HAVE_INDEXED_GZIP = True

nibabel/benchmarks/bench_arrayproxy_slicing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626

2727
# if memory_profiler is installed, we get memory usage results
2828
try:
29-
from memory_profiler import memory_usage # type: ignore[import-not-found]
29+
from memory_profiler import memory_usage # type: ignore[import]
3030
except ImportError:
3131
memory_usage = None
3232

nibabel/cmdline/dicomfs.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ class dummy_fuse:
2525

2626

2727
try:
28-
import fuse # type: ignore[import-not-found]
28+
import fuse # type: ignore[import]
2929

3030
uid = os.getuid()
3131
gid = os.getgid()

nibabel/gifti/tests/test_gifti.py

+9-7
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
from ... import load
1515
from ...fileholders import FileHolder
1616
from ...nifti1 import data_type_codes
17-
from ...testing import get_test_data
17+
from ...testing import deprecated_to, expires, get_test_data
1818
from .. import (
1919
GiftiCoordSystem,
2020
GiftiDataArray,
@@ -275,27 +275,29 @@ def test_labeltable():
275275
assert len(img.labeltable.labels) == 2
276276

277277

278+
@expires('6.0.0')
278279
def test_metadata():
279280
md = GiftiMetaData(key='value')
280281
# Old initialization methods
281-
with pytest.warns(DeprecationWarning) as w:
282+
with deprecated_to('6.0.0'):
282283
nvpair = GiftiNVPairs('key', 'value')
283284
with pytest.warns(FutureWarning) as w:
284285
md2 = GiftiMetaData(nvpair=nvpair)
285286
assert len(w) == 1
286-
with pytest.warns(DeprecationWarning) as w:
287+
with deprecated_to('6.0.0'):
287288
md3 = GiftiMetaData.from_dict({'key': 'value'})
288289
assert md == md2 == md3 == {'key': 'value'}
289290
# .data as a list of NVPairs is going away
290-
with pytest.warns(DeprecationWarning) as w:
291+
with deprecated_to('6.0.0'):
291292
assert md.data[0].name == 'key'
293+
with deprecated_to('6.0.0'):
292294
assert md.data[0].value == 'value'
293-
assert len(w) == 2
294295

295296

297+
@expires('6.0.0')
296298
def test_metadata_list_interface():
297299
md = GiftiMetaData(key='value')
298-
with pytest.warns(DeprecationWarning):
300+
with deprecated_to('6.0.0'):
299301
mdlist = md.data
300302
assert len(mdlist) == 1
301303
assert mdlist[0].name == 'key'
@@ -312,7 +314,7 @@ def test_metadata_list_interface():
312314
assert md['foo'] == 'bar'
313315

314316
# Append new NVPair
315-
with pytest.warns(DeprecationWarning) as w:
317+
with deprecated_to('6.0.0'):
316318
nvpair = GiftiNVPairs('key', 'value')
317319
mdlist.append(nvpair)
318320
assert len(mdlist) == 2

nibabel/minc2.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ class Minc2Image(Minc1Image):
163163
def from_file_map(klass, file_map, *, mmap=True, keep_file_open=None):
164164
# Import of h5py might take awhile for MPI-enabled builds
165165
# So we are importing it here "on demand"
166-
import h5py # type: ignore[import-not-found]
166+
import h5py # type: ignore[import]
167167

168168
holder = file_map['image']
169169
if holder.filename is None:

nibabel/spm99analyze.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -275,7 +275,7 @@ def from_file_map(klass, file_map, *, mmap=True, keep_file_open=None):
275275
contents = matf.read()
276276
if len(contents) == 0:
277277
return ret
278-
import scipy.io as sio # type: ignore[import-not-found]
278+
import scipy.io as sio # type: ignore[import]
279279

280280
mats = sio.loadmat(BytesIO(contents))
281281
if 'mat' in mats: # this overrides a 'M', and includes any flip

nibabel/testing/__init__.py

+12
Original file line numberDiff line numberDiff line change
@@ -233,3 +233,15 @@ def expires(version):
233233
return lambda x: x
234234

235235
return pytest.mark.xfail(raises=ExpiredDeprecationError)
236+
237+
238+
def deprecated_to(version):
239+
"""Context manager to expect DeprecationWarnings until a given version"""
240+
from packaging.version import Version
241+
242+
from nibabel import __version__ as nbver
243+
244+
if Version(nbver) < Version(version):
245+
return pytest.deprecated_call()
246+
247+
return nullcontext()

nibabel/tests/test_image_api.py

+19-37
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
bytesio_filemap,
4949
bytesio_round_trip,
5050
clear_and_catch_warnings,
51+
deprecated_to,
5152
expires,
5253
nullcontext,
5354
)
@@ -80,10 +81,6 @@
8081
from .test_parrec import EXAMPLE_IMAGES as PARREC_EXAMPLE_IMAGES
8182

8283

83-
def maybe_deprecated(meth_name):
84-
return pytest.deprecated_call() if meth_name == 'get_data' else nullcontext()
85-
86-
8784
class GenericImageAPI(ValidateAPI):
8885
"""General image validation API"""
8986

@@ -194,7 +191,7 @@ def validate_no_slicing(self, imaker, params):
194191
@expires('5.0.0')
195192
def validate_get_data_deprecated(self, imaker, params):
196193
img = imaker()
197-
with pytest.deprecated_call():
194+
with deprecated_to('5.0.0'):
198195
data = img.get_data()
199196
assert_array_equal(np.asanyarray(img.dataobj), data)
200197

@@ -246,14 +243,12 @@ def validate_data_interface(self, imaker, params):
246243
self._check_array_interface(imaker, meth_name)
247244
method = getattr(img, meth_name)
248245
# Data shape is same as image shape
249-
with maybe_deprecated(meth_name):
250-
assert img.shape == method().shape
246+
assert img.shape == method().shape
251247
# Data ndim is same as image ndim
252-
with maybe_deprecated(meth_name):
253-
assert img.ndim == method().ndim
248+
assert img.ndim == method().ndim
254249
# Values to get_data caching parameter must be 'fill' or
255250
# 'unchanged'
256-
with maybe_deprecated(meth_name), pytest.raises(ValueError):
251+
with pytest.raises(ValueError):
257252
method(caching='something')
258253
# dataobj is read only
259254
fake_data = np.zeros(img.shape, dtype=img.get_data_dtype())
@@ -277,13 +272,11 @@ def _check_proxy_interface(self, imaker, meth_name):
277272
assert not img.in_memory
278273
# Load with caching='unchanged'
279274
method = getattr(img, meth_name)
280-
with maybe_deprecated(meth_name):
281-
data = method(caching='unchanged')
275+
data = method(caching='unchanged')
282276
# Still not cached
283277
assert not img.in_memory
284278
# Default load, does caching
285-
with maybe_deprecated(meth_name):
286-
data = method()
279+
data = method()
287280
# Data now cached. in_memory is True if either of the get_data
288281
# or get_fdata caches are not-None
289282
assert img.in_memory
@@ -295,36 +288,30 @@ def _check_proxy_interface(self, imaker, meth_name):
295288
# integers, but lets assume that's not true here.
296289
assert_array_equal(proxy_data, data)
297290
# Now caching='unchanged' does nothing, returns cached version
298-
with maybe_deprecated(meth_name):
299-
data_again = method(caching='unchanged')
291+
data_again = method(caching='unchanged')
300292
assert data is data_again
301293
# caching='fill' does nothing because the cache is already full
302-
with maybe_deprecated(meth_name):
303-
data_yet_again = method(caching='fill')
294+
data_yet_again = method(caching='fill')
304295
assert data is data_yet_again
305296
# changing array data does not change proxy data, or reloaded
306297
# data
307298
data[:] = 42
308299
assert_array_equal(proxy_data, proxy_copy)
309300
assert_array_equal(np.asarray(img.dataobj), proxy_copy)
310-
# It does change the result of get_data
311-
with maybe_deprecated(meth_name):
312-
assert_array_equal(method(), 42)
301+
# It does change the result of get_fdata
302+
assert_array_equal(method(), 42)
313303
# until we uncache
314304
img.uncache()
315305
# Which unsets in_memory
316306
assert not img.in_memory
317-
with maybe_deprecated(meth_name):
318-
assert_array_equal(method(), proxy_copy)
307+
assert_array_equal(method(), proxy_copy)
319308
# Check caching='fill' does cache data
320309
img = imaker()
321310
method = getattr(img, meth_name)
322311
assert not img.in_memory
323-
with maybe_deprecated(meth_name):
324-
data = method(caching='fill')
312+
data = method(caching='fill')
325313
assert img.in_memory
326-
with maybe_deprecated(meth_name):
327-
data_again = method()
314+
data_again = method()
328315
assert data is data_again
329316
# Check that caching refreshes for new floating point type.
330317
img.uncache()
@@ -368,17 +355,15 @@ def _check_array_caching(self, imaker, meth_name, caching):
368355
get_data_func = method if caching is None else partial(method, caching=caching)
369356
assert isinstance(img.dataobj, np.ndarray)
370357
assert img.in_memory
371-
with maybe_deprecated(meth_name):
372-
data = get_data_func()
358+
data = get_data_func()
373359
# Returned data same object as underlying dataobj if using
374360
# old ``get_data`` method, or using newer ``get_fdata``
375361
# method, where original array was float64.
376362
arr_dtype = img.dataobj.dtype
377363
dataobj_is_data = arr_dtype == np.float64 or method == img.get_data
378364
# Set something to the output array.
379365
data[:] = 42
380-
with maybe_deprecated(meth_name):
381-
get_result_changed = np.all(get_data_func() == 42)
366+
get_result_changed = np.all(get_data_func() == 42)
382367
assert get_result_changed == (dataobj_is_data or caching != 'unchanged')
383368
if dataobj_is_data:
384369
assert data is img.dataobj
@@ -387,15 +372,13 @@ def _check_array_caching(self, imaker, meth_name, caching):
387372
assert_array_equal(np.asarray(img.dataobj), 42)
388373
# Uncache has no effect
389374
img.uncache()
390-
with maybe_deprecated(meth_name):
391-
assert_array_equal(get_data_func(), 42)
375+
assert_array_equal(get_data_func(), 42)
392376
else:
393377
assert not data is img.dataobj
394378
assert not np.all(np.asarray(img.dataobj) == 42)
395379
# Uncache does have an effect
396380
img.uncache()
397-
with maybe_deprecated(meth_name):
398-
assert not np.all(get_data_func() == 42)
381+
assert not np.all(get_data_func() == 42)
399382
# in_memory is always true for array images, regardless of
400383
# cache state.
401384
img.uncache()
@@ -408,8 +391,7 @@ def _check_array_caching(self, imaker, meth_name, caching):
408391
if arr_dtype not in float_types:
409392
return
410393
for float_type in float_types:
411-
with maybe_deprecated(meth_name):
412-
data = get_data_func(dtype=float_type)
394+
data = get_data_func(dtype=float_type)
413395
assert (data is img.dataobj) == (arr_dtype == float_type)
414396

415397
def validate_shape(self, imaker, params):

nibabel/tests/test_image_load_save.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
from .. import spm99analyze as spm99
4141
from ..optpkg import optional_package
4242
from ..spatialimages import SpatialImage
43-
from ..testing import expires
43+
from ..testing import deprecated_to, expires
4444
from ..tmpdirs import InTemporaryDirectory
4545
from ..volumeutils import native_code, swapped_code
4646

@@ -285,7 +285,7 @@ def test_filename_save():
285285
@expires('5.0.0')
286286
def test_guessed_image_type():
287287
# Test whether we can guess the image type from example files
288-
with pytest.deprecated_call():
288+
with deprecated_to('5.0.0'):
289289
assert nils.guessed_image_type(pjoin(DATA_PATH, 'example4d.nii.gz')) == Nifti1Image
290290
assert nils.guessed_image_type(pjoin(DATA_PATH, 'nifti1.hdr')) == Nifti1Pair
291291
assert nils.guessed_image_type(pjoin(DATA_PATH, 'example_nifti2.nii.gz')) == Nifti2Image

nibabel/tests/test_loadsave.py

+13-13
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from ..loadsave import _signature_matches_extension, load, read_img_data
2222
from ..openers import Opener
2323
from ..optpkg import optional_package
24-
from ..testing import expires
24+
from ..testing import deprecated_to, expires
2525
from ..tmpdirs import InTemporaryDirectory
2626

2727
_, have_scipy, _ = optional_package('scipy')
@@ -50,14 +50,14 @@ def test_read_img_data():
5050
fpath = pathlib.Path(fpath)
5151
img = load(fpath)
5252
data = img.get_fdata()
53-
with pytest.deprecated_call():
53+
with deprecated_to('5.0.0'):
5454
data2 = read_img_data(img)
5555
assert_array_equal(data, data2)
5656
# These examples have null scaling - assert prefer=unscaled is the same
5757
dao = img.dataobj
5858
if hasattr(dao, 'slope') and hasattr(img.header, 'raw_data_from_fileobj'):
5959
assert (dao.slope, dao.inter) == (1, 0)
60-
with pytest.deprecated_call():
60+
with deprecated_to('5.0.0'):
6161
assert_array_equal(read_img_data(img, prefer='unscaled'), data)
6262
# Assert all caps filename works as well
6363
with TemporaryDirectory() as tmpdir:
@@ -140,21 +140,21 @@ def test_read_img_data_nifti():
140140
img = img_class(data, np.eye(4))
141141
img.set_data_dtype(out_dtype)
142142
# No filemap => error
143-
with pytest.deprecated_call(), pytest.raises(ImageFileError):
143+
with deprecated_to('5.0.0'), pytest.raises(ImageFileError):
144144
read_img_data(img)
145145
# Make a filemap
146146
froot = f'an_image_{i}'
147147
img.file_map = img.filespec_to_file_map(froot)
148148
# Trying to read from this filemap will generate an error because
149149
# we are going to read from files that do not exist
150-
with pytest.deprecated_call(), pytest.raises(OSError):
150+
with deprecated_to('5.0.0'), pytest.raises(OSError):
151151
read_img_data(img)
152152
img.to_file_map()
153153
# Load - now the scaling and offset correctly applied
154154
img_fname = img.file_map['image'].filename
155155
img_back = load(img_fname)
156156
data_back = img_back.get_fdata()
157-
with pytest.deprecated_call():
157+
with deprecated_to('5.0.0'):
158158
assert_array_equal(data_back, read_img_data(img_back))
159159
# This is the same as if we loaded the image and header separately
160160
hdr_fname = img.file_map['header'].filename if 'header' in img.file_map else img_fname
@@ -166,16 +166,16 @@ def test_read_img_data_nifti():
166166
# Unscaled is the same as returned from raw_data_from_fileobj
167167
with open(img_fname, 'rb') as fobj:
168168
unscaled_back = hdr_back.raw_data_from_fileobj(fobj)
169-
with pytest.deprecated_call():
169+
with deprecated_to('5.0.0'):
170170
assert_array_equal(unscaled_back, read_img_data(img_back, prefer='unscaled'))
171171
# If we futz with the scaling in the header, the result changes
172-
with pytest.deprecated_call():
172+
with deprecated_to('5.0.0'):
173173
assert_array_equal(data_back, read_img_data(img_back))
174174
has_inter = hdr_back.has_data_intercept
175175
old_slope = hdr_back['scl_slope']
176176
old_inter = hdr_back['scl_inter'] if has_inter else 0
177177
est_unscaled = (data_back - old_inter) / old_slope
178-
with pytest.deprecated_call():
178+
with deprecated_to('5.0.0'):
179179
actual_unscaled = read_img_data(img_back, prefer='unscaled')
180180
assert_almost_equal(est_unscaled, actual_unscaled)
181181
img_back.header['scl_slope'] = 2.1
@@ -185,10 +185,10 @@ def test_read_img_data_nifti():
185185
else:
186186
new_inter = 0
187187
# scaled scaling comes from new parameters in header
188-
with pytest.deprecated_call():
188+
with deprecated_to('5.0.0'):
189189
assert np.allclose(actual_unscaled * 2.1 + new_inter, read_img_data(img_back))
190190
# Unscaled array didn't change
191-
with pytest.deprecated_call():
191+
with deprecated_to('5.0.0'):
192192
assert_array_equal(actual_unscaled, read_img_data(img_back, prefer='unscaled'))
193193
# Check the offset too
194194
img.header.set_data_offset(1024)
@@ -200,14 +200,14 @@ def test_read_img_data_nifti():
200200
fobj.write(b'\x00\x00')
201201
img_back = load(img_fname)
202202
data_back = img_back.get_fdata()
203-
with pytest.deprecated_call():
203+
with deprecated_to('5.0.0'):
204204
assert_array_equal(data_back, read_img_data(img_back))
205205
img_back.header.set_data_offset(1026)
206206
# Check we pick up new offset
207207
exp_offset = np.zeros((data.size,), data.dtype) + old_inter
208208
exp_offset[:-1] = np.ravel(data_back, order='F')[1:]
209209
exp_offset = np.reshape(exp_offset, shape, order='F')
210-
with pytest.deprecated_call():
210+
with deprecated_to('5.0.0'):
211211
assert_array_equal(exp_offset, read_img_data(img_back))
212212
# Delete stuff that might hold onto file references
213213
del img, img_back, data_back

0 commit comments

Comments
 (0)