From 5f8d68daaded798361d8a1e951da80de3f2e4a9b Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Mon, 11 Nov 2019 18:04:19 -0500 Subject: [PATCH 001/223] converting tests with tests/test_a*.py and test_wrapstruct (for some reason cant run the tests in one pytest command, so added an extra line to travis for now --- .travis.yml | 2 + nibabel/tests/test_analyze.py | 289 ++++++++++++++------------- nibabel/tests/test_api_validators.py | 7 +- nibabel/tests/test_arrayproxy.py | 96 +++++---- nibabel/tests/test_arraywriters.py | 235 ++++++++++++---------- nibabel/tests/test_wrapstruct.py | 178 +++++++++-------- 6 files changed, 430 insertions(+), 377 deletions(-) diff --git a/.travis.yml b/.travis.yml index 81d3589769..def7ca2369 100644 --- a/.travis.yml +++ b/.travis.yml @@ -130,6 +130,8 @@ script: cd for_testing cp ../.coveragerc . nosetests --with-doctest --with-coverage --cover-package nibabel nibabel + pytest -v ../nibabel/tests/test_a*.py + pytest -v ../nibabel/tests/test_w*.py else false fi diff --git a/nibabel/tests/test_analyze.py b/nibabel/tests/test_analyze.py index 6b05df83e3..b0cc566979 100644 --- a/nibabel/tests/test_analyze.py +++ b/nibabel/tests/test_analyze.py @@ -31,14 +31,10 @@ from ..tmpdirs import InTemporaryDirectory from ..arraywriters import WriterError -from nose.tools import (assert_equal, assert_not_equal, assert_true, - assert_false, assert_raises) - +import pytest from numpy.testing import (assert_array_equal, assert_array_almost_equal) -from ..testing import (assert_equal, assert_not_equal, assert_true, - assert_false, assert_raises, data_path, - suppress_warnings, assert_dt_equal) +from ..testing_pytest import (data_path, suppress_warnings, assert_dt_equal) from .test_wrapstruct import _TestLabeledWrapStruct from . import test_spatialimages as tsi @@ -71,7 +67,7 @@ class TestAnalyzeHeader(_TestLabeledWrapStruct): def test_supported_types(self): hdr = self.header_class() - assert_equal(self.supported_np_types, + assert (self.supported_np_types == supported_np_types(hdr)) def get_bad_bb(self): @@ -84,7 +80,7 @@ def test_general_init(self): hdr = self.header_class() # an empty header has shape (0,) - like an empty array # (np.array([])) - assert_equal(hdr.get_data_shape(), (0,)) + assert hdr.get_data_shape() == (0,) # The affine is always homogenous 3D regardless of shape. The # default affine will have -1 as the X zoom iff default_x_flip # is True (which it is by default). We have to be careful of the @@ -93,20 +89,20 @@ def test_general_init(self): assert_array_equal(np.diag(hdr.get_base_affine()), [-1, 1, 1, 1]) # But zooms only go with number of dimensions - assert_equal(hdr.get_zooms(), (1.0,)) + assert hdr.get_zooms() == (1.0,) def test_header_size(self): - assert_equal(self.header_class.template_dtype.itemsize, self.sizeof_hdr) + assert self.header_class.template_dtype.itemsize == self.sizeof_hdr def test_empty(self): hdr = self.header_class() - assert_true(len(hdr.binaryblock) == self.sizeof_hdr) - assert_true(hdr['sizeof_hdr'] == self.sizeof_hdr) - assert_true(np.all(hdr['dim'][1:] == 1)) - assert_true(hdr['dim'][0] == 0) - assert_true(np.all(hdr['pixdim'] == 1)) - assert_true(hdr['datatype'] == 16) # float32 - assert_true(hdr['bitpix'] == 32) + assert len(hdr.binaryblock) == self.sizeof_hdr + assert hdr['sizeof_hdr'] == self.sizeof_hdr + assert np.all(hdr['dim'][1:] == 1) + assert hdr['dim'][0] == 0 + assert np.all(hdr['pixdim'] == 1) + assert hdr['datatype'] == 16 # float32 + assert hdr['bitpix'] == 32 def _set_something_into_hdr(self, hdr): # Called from test_bytes test method. Specific to the header data type @@ -117,26 +113,26 @@ def test_checks(self): # Test header checks hdr_t = self.header_class() # _dxer just returns the diagnostics as a string - assert_equal(self._dxer(hdr_t), '') + assert self._dxer(hdr_t) == '' hdr = hdr_t.copy() hdr['sizeof_hdr'] = 1 with suppress_warnings(): - assert_equal(self._dxer(hdr), 'sizeof_hdr should be ' + + assert (self._dxer(hdr) == 'sizeof_hdr should be ' + str(self.sizeof_hdr)) hdr = hdr_t.copy() hdr['datatype'] = 0 - assert_equal(self._dxer(hdr), 'data code 0 not supported\n' + assert (self._dxer(hdr) == 'data code 0 not supported\n' 'bitpix does not match datatype') hdr = hdr_t.copy() hdr['bitpix'] = 0 - assert_equal(self._dxer(hdr), 'bitpix does not match datatype') + assert self._dxer(hdr) == 'bitpix does not match datatype' def test_pixdim_checks(self): hdr_t = self.header_class() for i in (1, 2, 3): hdr = hdr_t.copy() hdr['pixdim'][i] = -1 - assert_equal(self._dxer(hdr), 'pixdim[1,2,3] should be positive') + assert self._dxer(hdr) == 'pixdim[1,2,3] should be positive' def test_log_checks(self): # Test logging, fixing, errors for header checking @@ -146,11 +142,13 @@ def test_log_checks(self): with suppress_warnings(): hdr['sizeof_hdr'] = 350 # severity 30 fhdr, message, raiser = self.log_chk(hdr, 30) - assert_equal(fhdr['sizeof_hdr'], self.sizeof_hdr) - assert_equal(message, + + assert fhdr['sizeof_hdr'] == self.sizeof_hdr + assert (message == 'sizeof_hdr should be {0}; set sizeof_hdr to {0}'.format( self.sizeof_hdr)) - assert_raises(*raiser) + with pytest.raises(raiser[0]): + raiser[1](*raiser[2:]) # RGB datatype does not raise error hdr = HC() hdr.set_data_dtype('RGB') @@ -160,25 +158,28 @@ def test_log_checks(self): hdr['datatype'] = -1 # severity 40 with suppress_warnings(): fhdr, message, raiser = self.log_chk(hdr, 40) - assert_equal(message, 'data code -1 not recognized; ' + assert (message == 'data code -1 not recognized; ' 'not attempting fix') - assert_raises(*raiser) + with pytest.raises(raiser[0]): + raiser[1](*raiser[2:]) # datatype not supported hdr['datatype'] = 255 # severity 40 fhdr, message, raiser = self.log_chk(hdr, 40) - assert_equal(message, 'data code 255 not supported; ' + assert (message == 'data code 255 not supported; ' 'not attempting fix') - assert_raises(*raiser) + with pytest.raises(raiser[0]): + raiser[1](*raiser[2:]) # bitpix hdr = HC() hdr['datatype'] = 16 # float32 hdr['bitpix'] = 16 # severity 10 fhdr, message, raiser = self.log_chk(hdr, 10) - assert_equal(fhdr['bitpix'], 32) - assert_equal(message, 'bitpix does not match datatype; ' + assert fhdr['bitpix'] == 32 + assert (message == 'bitpix does not match datatype; ' 'setting bitpix to match datatype') - assert_raises(*raiser) + with pytest.raises(raiser[0]): + raiser[1](*raiser[2:]) def test_pixdim_log_checks(self): # pixdim positive @@ -186,28 +187,31 @@ def test_pixdim_log_checks(self): hdr = HC() hdr['pixdim'][1] = -2 # severity 35 fhdr, message, raiser = self.log_chk(hdr, 35) - assert_equal(fhdr['pixdim'][1], 2) - assert_equal(message, 'pixdim[1,2,3] should be positive; ' + assert fhdr['pixdim'][1] == 2 + assert (message == 'pixdim[1,2,3] should be positive; ' 'setting to abs of pixdim values') - assert_raises(*raiser) + with pytest.raises(raiser[0]): + raiser[1](*raiser[2:]) hdr = HC() hdr['pixdim'][1] = 0 # severity 30 fhdr, message, raiser = self.log_chk(hdr, 30) - assert_equal(fhdr['pixdim'][1], 1) - assert_equal(message, PIXDIM0_MSG) - assert_raises(*raiser) + assert fhdr['pixdim'][1] == 1 + assert message == PIXDIM0_MSG + with pytest.raises(raiser[0]): + raiser[1](*raiser[2:]) # both hdr = HC() hdr['pixdim'][1] = 0 # severity 30 hdr['pixdim'][2] = -2 # severity 35 fhdr, message, raiser = self.log_chk(hdr, 35) - assert_equal(fhdr['pixdim'][1], 1) - assert_equal(fhdr['pixdim'][2], 2) - assert_equal(message, 'pixdim[1,2,3] should be ' + assert fhdr['pixdim'][1] == 1 + assert fhdr['pixdim'][2] == 2 + assert (message == 'pixdim[1,2,3] should be ' 'non-zero and pixdim[1,2,3] should ' 'be positive; setting 0 dims to 1 ' 'and setting to abs of pixdim values') - assert_raises(*raiser) + with pytest.raises(raiser[0]): + raiser[1](*raiser[2:]) def test_no_scaling_fixes(self): # Check we do not fix slope or intercept @@ -248,12 +252,13 @@ def test_logger_error(self): # Check log message appears in new logger imageglobals.logger = logger hdr.copy().check_fix() - assert_equal(str_io.getvalue(), + assert (str_io.getvalue() == 'bitpix does not match datatype; ' 'setting bitpix to match datatype\n') # Check that error_level in fact causes error to be raised imageglobals.error_level = 10 - assert_raises(HeaderDataError, hdr.copy().check_fix) + with pytest.raises(HeaderDataError): + hdr.copy().check_fix() finally: imageglobals.logger, imageglobals.error_level = log_cache @@ -304,55 +309,58 @@ def assert_set_dtype(dt_spec, np_dtype): assert_set_dtype(int, np_sys_int) hdr = self.header_class() for inp in all_unsupported_types: - assert_raises(HeaderDataError, hdr.set_data_dtype, inp) + with pytest.raises(HeaderDataError): + hdr.set_data_dtype(inp) def test_shapes(self): # Test that shape checks work hdr = self.header_class() for shape in ((2, 3, 4), (2, 3, 4, 5), (2, 3), (2,)): hdr.set_data_shape(shape) - assert_equal(hdr.get_data_shape(), shape) + assert hdr.get_data_shape() == shape # Check max works, but max+1 raises error dim_dtype = hdr.structarr['dim'].dtype # as_int for safety to deal with numpy 1.4.1 int conversion errors mx = as_int(np.iinfo(dim_dtype).max) shape = (mx,) hdr.set_data_shape(shape) - assert_equal(hdr.get_data_shape(), shape) + assert hdr.get_data_shape() == shape shape = (mx + 1,) - assert_raises(HeaderDataError, hdr.set_data_shape, shape) + with pytest.raises(HeaderDataError): + hdr.set_data_shape(shape) # Lists or tuples or arrays will work for setting shape shape = (2, 3, 4) for constructor in (list, tuple, np.array): hdr.set_data_shape(constructor(shape)) - assert_equal(hdr.get_data_shape(), shape) + assert hdr.get_data_shape() == shape def test_read_write_data(self): # Check reading and writing of data hdr = self.header_class() # Trying to read data from an empty header gives no data bytes = hdr.data_from_fileobj(BytesIO()) - assert_equal(len(bytes), 0) + assert len(bytes) == 0 # Setting no data into an empty header results in - no data str_io = BytesIO() hdr.data_to_fileobj([], str_io) - assert_equal(str_io.getvalue(), b'') + assert str_io.getvalue() == b'' # Setting more data then there should be gives an error - assert_raises(HeaderDataError, - hdr.data_to_fileobj, - np.zeros(3), - str_io) + with pytest.raises(HeaderDataError): + hdr.data_to_fileobj(np.zeros(3), str_io) # Test valid write hdr.set_data_shape((1, 2, 3)) hdr.set_data_dtype(np.float32) S = BytesIO() data = np.arange(6, dtype=np.float64) # data have to be the right shape - assert_raises(HeaderDataError, hdr.data_to_fileobj, data, S) + with pytest.raises(HeaderDataError): + hdr.data_to_fileobj(data, S) data = data.reshape((1, 2, 3)) # and size - assert_raises(HeaderDataError, hdr.data_to_fileobj, data[:, :, :-1], S) - assert_raises(HeaderDataError, hdr.data_to_fileobj, data[:, :-1, :], S) + with pytest.raises(HeaderDataError): + hdr.data_to_fileobj(data[:, :, :-1], S) + with pytest.raises(HeaderDataError): + hdr.data_to_fileobj(data[:, :-1, :], S) # OK if so hdr.data_to_fileobj(data, S) # Read it back @@ -360,7 +368,7 @@ def test_read_write_data(self): # Should be about the same assert_array_almost_equal(data, data_back) # but with the header dtype, not the data dtype - assert_equal(hdr.get_data_dtype(), data_back.dtype) + assert hdr.get_data_dtype() == data_back.dtype # this is with native endian, not so for swapped S2 = BytesIO() hdr2 = hdr.as_byteswapped() @@ -371,9 +379,9 @@ def test_read_write_data(self): # Compares the same assert_array_almost_equal(data_back, data_back2) # Same dtype names - assert_equal(data_back.dtype.name, data_back2.dtype.name) + assert data_back.dtype.name == data_back2.dtype.name # But not the same endianness - assert_not_equal(data.dtype.byteorder, data_back2.dtype.byteorder) + assert data.dtype.byteorder != data_back2.dtype.byteorder # Try scaling down to integer hdr.set_data_dtype(np.uint8) S3 = BytesIO() @@ -385,15 +393,16 @@ def test_read_write_data(self): assert_array_almost_equal(data, data_back) # If the header can't do scaling, rescale raises an error if not hdr.has_data_slope: - assert_raises(HeaderTypeError, hdr.data_to_fileobj, data, S3) - assert_raises(HeaderTypeError, hdr.data_to_fileobj, data, S3, - rescale=True) + with pytest.raises(HeaderTypeError): + hdr.data_to_fileobj(data, S3) + with pytest.raises(HeaderTypeError): + hdr.data_to_fileobj(data, S3, rescale=True) # If not scaling we lose precision from rounding data = np.arange(6, dtype=np.float64).reshape((1, 2, 3)) + 0.5 with np.errstate(invalid='ignore'): hdr.data_to_fileobj(data, S3, rescale=False) data_back = hdr.data_from_fileobj(S3) - assert_false(np.allclose(data, data_back)) + assert not np.allclose(data, data_back) # Test RGB image dtype = np.dtype([('R', 'uint8'), ('G', 'uint8'), ('B', 'uint8')]) data = np.ones((1, 2, 3), dtype) @@ -409,26 +418,24 @@ def test_datatype(self): for code in codes.value_set(): npt = codes.type[code] if npt is np.void: - assert_raises( - HeaderDataError, - ehdr.set_data_dtype, - code) + with pytest.raises(HeaderDataError): + ehdr.set_data_dtype(code) continue dt = codes.dtype[code] ehdr.set_data_dtype(npt) - assert_true(ehdr['datatype'] == code) - assert_true(ehdr['bitpix'] == dt.itemsize * 8) + assert ehdr['datatype'] == code + assert ehdr['bitpix'] == dt.itemsize * 8 ehdr.set_data_dtype(code) - assert_true(ehdr['datatype'] == code) + assert ehdr['datatype'] == code ehdr.set_data_dtype(dt) - assert_true(ehdr['datatype'] == code) + assert ehdr['datatype'] == code def test_offset(self): # Test get / set offset hdr = self.header_class() offset = hdr.get_data_offset() hdr.set_data_offset(offset + 16) - assert_equal(hdr.get_data_offset(), offset + 16) + assert hdr.get_data_offset() == offset + 16 def test_data_shape_zooms_affine(self): hdr = self.header_class() @@ -436,27 +443,23 @@ def test_data_shape_zooms_affine(self): L = len(shape) hdr.set_data_shape(shape) if L: - assert_equal(hdr.get_data_shape(), shape) + assert hdr.get_data_shape() == shape else: - assert_equal(hdr.get_data_shape(), (0,)) + assert hdr.get_data_shape() == (0,) # Default zoom - for 3D - is 1(()) - assert_equal(hdr.get_zooms(), (1,) * L) + assert hdr.get_zooms() == (1,) * L # errors if zooms do not match shape if len(shape): - assert_raises(HeaderDataError, - hdr.set_zooms, - (1,) * (L - 1)) + with pytest.raises(HeaderDataError): + hdr.set_zooms((1,) * (L - 1)) # Errors for negative zooms - assert_raises(HeaderDataError, - hdr.set_zooms, - (-1,) + (1,) * (L - 1)) - assert_raises(HeaderDataError, - hdr.set_zooms, - (1,) * (L + 1)) + with pytest.raises(HeaderDataError): + hdr.set_zooms((-1,) + (1,) * (L - 1)) + with pytest.raises(HeaderDataError): + hdr.set_zooms((1,) * (L + 1)) # Errors for negative zooms - assert_raises(HeaderDataError, - hdr.set_zooms, - (-1,) * L) + with pytest.raises(HeaderDataError): + hdr.set_zooms((-1,) * L) # reducing the dimensionality of the array and then increasing # it again reverts the previously set zoom values to 1.0 hdr = self.header_class() @@ -489,20 +492,20 @@ def test_default_x_flip(self): def test_from_eg_file(self): fileobj = open(self.example_file, 'rb') hdr = self.header_class.from_fileobj(fileobj, check=False) - assert_equal(hdr.endianness, '>') - assert_equal(hdr['sizeof_hdr'], self.sizeof_hdr) + assert hdr.endianness == '>' + assert hdr['sizeof_hdr'] == self.sizeof_hdr def test_orientation(self): # Test flips hdr = self.header_class() - assert_true(hdr.default_x_flip) + assert hdr.default_x_flip hdr.set_data_shape((3, 5, 7)) hdr.set_zooms((4, 5, 6)) aff = np.diag((-4, 5, 6, 1)) aff[:3, 3] = np.array([1, 2, 3]) * np.array([-4, 5, 6]) * -1 assert_array_equal(hdr.get_base_affine(), aff) hdr.default_x_flip = False - assert_false(hdr.default_x_flip) + assert not hdr.default_x_flip aff[0] *= -1 assert_array_equal(hdr.get_base_affine(), aff) @@ -512,23 +515,23 @@ def test_str(self): s1 = str(hdr) # check the datacode recoding rexp = re.compile('^datatype +: float32', re.MULTILINE) - assert_true(rexp.search(s1) is not None) + assert rexp.search(s1) is not None def test_from_header(self): # check from header class method. klass = self.header_class empty = klass.from_header() - assert_equal(klass(), empty) + assert klass() == empty empty = klass.from_header(None) - assert_equal(klass(), empty) + assert klass() == empty hdr = klass() hdr.set_data_dtype(np.float64) hdr.set_data_shape((1, 2, 3)) hdr.set_zooms((3.0, 2.0, 1.0)) for check in (True, False): copy = klass.from_header(hdr, check=check) - assert_equal(hdr, copy) - assert_false(hdr is copy) + assert hdr == copy + assert not hdr is copy class C(object): @@ -538,17 +541,17 @@ def get_data_shape(self): return (5, 4, 3) def get_zooms(self): return (10.0, 9.0, 8.0) converted = klass.from_header(C()) - assert_true(isinstance(converted, klass)) - assert_equal(converted.get_data_dtype(), np.dtype('i2')) - assert_equal(converted.get_data_shape(), (5, 4, 3)) - assert_equal(converted.get_zooms(), (10.0, 9.0, 8.0)) + assert isinstance(converted, klass) + assert converted.get_data_dtype() == np.dtype('i2') + assert converted.get_data_shape() == (5, 4, 3) + assert converted.get_zooms() == (10.0, 9.0, 8.0) def test_base_affine(self): klass = self.header_class hdr = klass() hdr.set_data_shape((3, 5, 7)) hdr.set_zooms((3, 2, 1)) - assert_true(hdr.default_x_flip) + assert hdr.default_x_flip assert_array_almost_equal( hdr.get_base_affine(), [[-3., 0., 0., 3.], @@ -574,7 +577,7 @@ def test_scaling(self): # Test integer scaling from float # Analyze headers cannot do float-integer scaling hdr = self.header_class() - assert_true(hdr.default_x_flip) + assert hdr.default_x_flip shape = (1, 2, 3) hdr.set_data_shape(shape) hdr.set_data_dtype(np.float32) @@ -588,22 +591,23 @@ def test_scaling(self): hdr.set_data_dtype(np.int32) # Writing to int needs scaling, and raises an error if we can't scale if not hdr.has_data_slope: - assert_raises(HeaderTypeError, hdr.data_to_fileobj, data, BytesIO()) + with pytest.raises(HeaderTypeError): + hdr.data_to_fileobj(data, BytesIO()) # But if we aren't scaling, convert the floats to integers and write with np.errstate(invalid='ignore'): hdr.data_to_fileobj(data, S, rescale=False) rdata = hdr.data_from_fileobj(S) - assert_true(np.allclose(data, rdata)) + assert np.allclose(data, rdata) # This won't work for floats that aren't close to integers data_p5 = data + 0.5 with np.errstate(invalid='ignore'): hdr.data_to_fileobj(data_p5, S, rescale=False) rdata = hdr.data_from_fileobj(S) - assert_false(np.allclose(data_p5, rdata)) + assert not np.allclose(data_p5, rdata) def test_slope_inter(self): hdr = self.header_class() - assert_equal(hdr.get_slope_inter(), (None, None)) + assert hdr.get_slope_inter() == (None, None) for slinter in ((None,), (None, None), (np.nan, np.nan), @@ -614,9 +618,11 @@ def test_slope_inter(self): (None, 0), (1.0, 0)): hdr.set_slope_inter(*slinter) - assert_equal(hdr.get_slope_inter(), (None, None)) - assert_raises(HeaderTypeError, hdr.set_slope_inter, 1.1) - assert_raises(HeaderTypeError, hdr.set_slope_inter, 1.0, 0.1) + assert hdr.get_slope_inter() == (None, None) + with pytest.raises(HeaderTypeError): + hdr.set_slope_inter(1.1) + with pytest.raises(HeaderTypeError): + hdr.set_slope_inter(1.0, 0.1) def test_from_analyze_map(self): # Test that any header can pass values from a mapping @@ -625,19 +631,22 @@ def test_from_analyze_map(self): class H1(object): pass - assert_raises(AttributeError, klass.from_header, H1()) + with pytest.raises(AttributeError): + klass.from_header(H1()) class H2(object): def get_data_dtype(self): return np.dtype('u1') - assert_raises(AttributeError, klass.from_header, H2()) + with pytest.raises(AttributeError): + klass.from_header(H2()) class H3(H2): def get_data_shape(self): return (2, 3, 4) - assert_raises(AttributeError, klass.from_header, H3()) + with pytest.raises(AttributeError): + klass.from_header(H3()) class H4(H3): @@ -647,7 +656,7 @@ def get_zooms(self): exp_hdr.set_data_dtype(np.dtype('u1')) exp_hdr.set_data_shape((2, 3, 4)) exp_hdr.set_zooms((4, 5, 6)) - assert_equal(klass.from_header(H4()), exp_hdr) + assert klass.from_header(H4()) == exp_hdr # cal_max, cal_min get properly set from ``as_analyze_map`` class H5(H4): @@ -656,7 +665,7 @@ def as_analyze_map(self): return dict(cal_min=-100, cal_max=100) exp_hdr['cal_min'] = -100 exp_hdr['cal_max'] = 100 - assert_equal(klass.from_header(H5()), exp_hdr) + assert klass.from_header(H5()) == exp_hdr # set_* methods override fields fron header class H6(H5): @@ -664,7 +673,7 @@ class H6(H5): def as_analyze_map(self): return dict(datatype=4, bitpix=32, cal_min=-100, cal_max=100) - assert_equal(klass.from_header(H6()), exp_hdr) + assert klass.from_header(H6()) == exp_hdr # Any mapping will do, including a Nifti header class H7(H5): @@ -677,7 +686,7 @@ def as_analyze_map(self): return n_hdr # Values from methods still override values from header (shape, dtype, # zooms still at defaults from n_hdr header fields above) - assert_equal(klass.from_header(H7()), exp_hdr) + assert klass.from_header(H7()) == exp_hdr def test_best_affine(): @@ -691,7 +700,8 @@ def test_data_code_error(): # test analyze raising error for unsupported codes hdr = Nifti1Header() hdr['datatype'] = 256 - assert_raises(HeaderDataError, AnalyzeHeader.from_header, hdr) + with pytest.raises(HeaderDataError): + AnalyzeHeader.from_header(hdr) class TestAnalyzeImage(tsi.TestSpatialImage, tsi.MmapImageMixin): @@ -701,7 +711,7 @@ class TestAnalyzeImage(tsi.TestSpatialImage, tsi.MmapImageMixin): def test_supported_types(self): img = self.image_class(np.zeros((2, 3, 4)), np.eye(4)) - assert_equal(self.supported_np_types, + assert (self.supported_np_types == supported_np_types(img)) def test_default_header(self): @@ -713,7 +723,7 @@ def test_default_header(self): hdr.set_data_dtype(arr.dtype) hdr.set_data_offset(0) hdr.set_slope_inter(np.nan, np.nan) - assert_equal(img.header, hdr) + assert img.header == hdr def test_data_hdr_cache(self): # test the API for loaded images, such that the data returned @@ -732,21 +742,21 @@ def test_data_hdr_cache(self): img = IC(data, affine, hdr) img.to_file_map(fm) img2 = IC.from_file_map(fm) - assert_equal(img2.shape, shape) - assert_equal(img2.get_data_dtype().type, np.int16) + assert img2.shape == shape + assert img2.get_data_dtype().type == np.int16 hdr = img2.header hdr.set_data_shape((3, 2, 2)) - assert_equal(hdr.get_data_shape(), (3, 2, 2)) + assert hdr.get_data_shape() == (3, 2, 2) hdr.set_data_dtype(np.uint8) - assert_equal(hdr.get_data_dtype(), np.dtype(np.uint8)) + assert hdr.get_data_dtype() == np.dtype(np.uint8) assert_array_equal(img2.get_fdata(), data) assert_array_equal(np.asanyarray(img2.dataobj), data) # now check read_img_data function - here we do see the changed # header sc_data = read_img_data(img2) - assert_equal(sc_data.shape, (3, 2, 2)) + assert sc_data.shape == (3, 2, 2) us_data = read_img_data(img2, prefer='unscaled') - assert_equal(us_data.shape, (3, 2, 2)) + assert us_data.shape == (3, 2, 2) def test_affine_44(self): IC = self.image_class @@ -760,7 +770,8 @@ def test_affine_44(self): img = IC(data, affine.tolist()) assert_array_equal(affine, img.affine) # Not OK - affine wrong shape - assert_raises(ValueError, IC, data, np.diag([2, 3, 4])) + with pytest.raises(ValueError): + IC(data, np.diag([2, 3, 4])) def test_offset_to_zero(self): # Check offset is always set to zero when creating images @@ -768,24 +779,24 @@ def test_offset_to_zero(self): arr = np.arange(24, dtype=np.int16).reshape((2, 3, 4)) aff = np.eye(4) img = img_klass(arr, aff) - assert_equal(img.header.get_data_offset(), 0) + assert img.header.get_data_offset() == 0 # Save to BytesIO object(s), make sure offset still zero bytes_map = bytesio_filemap(img_klass) img.to_file_map(bytes_map) - assert_equal(img.header.get_data_offset(), 0) + assert img.header.get_data_offset() == 0 # Set offset in in-memory image big_off = 1024 img.header.set_data_offset(big_off) - assert_equal(img.header.get_data_offset(), big_off) + assert img.header.get_data_offset() == big_off # Offset is in proxy but not in image after saving to fileobj img_rt = bytesio_round_trip(img) - assert_equal(img_rt.dataobj.offset, big_off) - assert_equal(img_rt.header.get_data_offset(), 0) + assert img_rt.dataobj.offset == big_off + assert img_rt.header.get_data_offset() == 0 # The original header still has the big_off value img.header.set_data_offset(big_off) # Making a new image with this header resets to zero img_again = img_klass(arr, aff, img.header) - assert_equal(img_again.header.get_data_offset(), 0) + assert img_again.header.get_data_offset() == 0 def test_big_offset_exts(self): # Check writing offset beyond data works for different file extensions @@ -845,7 +856,7 @@ def test_pickle(self): img_str = pickle.dumps(img) img2 = pickle.loads(img_str) assert_array_equal(img.get_fdata(), img2.get_fdata()) - assert_equal(img.header, img2.header) + assert img.header == img2.header # Save / reload using bytes IO objects for key, value in img.file_map.items(): value.fileobj = BytesIO() @@ -864,10 +875,11 @@ def test_no_finite_values(self): data[:, 2] = -np.inf img = self.image_class(data, None) img.set_data_dtype(np.int16) - assert_equal(img.get_data_dtype(), np.dtype(np.int16)) + assert img.get_data_dtype() == np.dtype(np.int16) fm = bytesio_filemap(img) if not img.header.has_data_slope: - assert_raises(WriterError, img.to_file_map, fm) + with pytest.raises(WriterError): + img.to_file_map(fm) return img.to_file_map(fm) img_back = self.image_class.from_file_map(fm) @@ -879,4 +891,5 @@ def test_unsupported(): data = np.arange(24, dtype=np.int32).reshape((2, 3, 4)) affine = np.eye(4) data = np.arange(24, dtype=np.uint32).reshape((2, 3, 4)) - assert_raises(HeaderDataError, AnalyzeImage, data, affine) + with pytest.raises(HeaderDataError): + AnalyzeImage(data, affine) diff --git a/nibabel/tests/test_api_validators.py b/nibabel/tests/test_api_validators.py index 41d3f41110..a4d23aaefd 100644 --- a/nibabel/tests/test_api_validators.py +++ b/nibabel/tests/test_api_validators.py @@ -1,7 +1,6 @@ """ Metaclass and class for validating instance APIs """ -from nose.tools import assert_equal class validator2test(type): @@ -79,8 +78,8 @@ def validate_something(self, obj, params): The metaclass sets up a ``test_something`` function that runs these checks on each ( """ - assert_equal(obj.var, params['var']) - assert_equal(obj.get_var(), params['var']) + assert obj.var == params['var'] + assert obj.get_var() == params['var'] class TestRunAllTests(ValidateAPI): @@ -102,4 +101,4 @@ def validate_second(self, obj, param): def teardown(): # Check that both validate_xxx tests got run - assert_equal(TestRunAllTests.run_tests, ['first', 'second']) + assert TestRunAllTests.run_tests == ['first', 'second'] diff --git a/nibabel/tests/test_arrayproxy.py b/nibabel/tests/test_arrayproxy.py index 527f9b8f91..b00af7d90f 100644 --- a/nibabel/tests/test_arrayproxy.py +++ b/nibabel/tests/test_arrayproxy.py @@ -26,9 +26,8 @@ from unittest import mock from numpy.testing import assert_array_equal, assert_array_almost_equal -from nose.tools import (assert_true, assert_false, assert_equal, - assert_not_equal, assert_raises) -from nibabel.testing import memmap_after_ufunc +import pytest +from ..testing_pytest import memmap_after_ufunc from .test_fileslice import slicer_samples from .test_openers import patch_indexed_gzip @@ -70,15 +69,16 @@ def test_init(): bio.write(arr.tostring(order='F')) hdr = FunkyHeader(shape) ap = ArrayProxy(bio, hdr) - assert_true(ap.file_like is bio) - assert_equal(ap.shape, shape) + assert ap.file_like is bio + assert ap.shape == shape # shape should be read only - assert_raises(AttributeError, setattr, ap, 'shape', shape) + with pytest.raises(AttributeError): + setattr(ap, 'shape', shape) # Get the data assert_array_equal(np.asarray(ap), arr) # Check we can modify the original header without changing the ap version hdr.shape[0] = 6 - assert_not_equal(ap.shape, shape) + assert ap.shape != shape # Data stays the same, also assert_array_equal(np.asarray(ap), arr) # C order also possible @@ -88,7 +88,8 @@ def test_init(): ap = CArrayProxy(bio, FunkyHeader((2, 3, 4))) assert_array_equal(np.asarray(ap), arr) # Illegal init - assert_raises(TypeError, ArrayProxy, bio, object()) + with pytest.raises(TypeError): + ArrayProxy(bio, object()) def test_tuplespec(): @@ -106,7 +107,7 @@ def test_tuplespec(): ap_tuple = ArrayProxy(bio, tuple_spec) # Header and tuple specs produce identical behavior for prop in ('shape', 'dtype', 'offset', 'slope', 'inter', 'is_proxy'): - assert_equal(getattr(ap_header, prop), getattr(ap_tuple, prop)) + assert getattr(ap_header, prop) == getattr(ap_tuple, prop) for method, args in (('get_unscaled', ()), ('__array__', ()), ('__getitem__', ((0, 2, 1), )) ): @@ -116,9 +117,12 @@ def test_tuplespec(): for n in range(2, 5): ArrayProxy(bio, tuple_spec[:n]) # Bad tuple lengths - assert_raises(TypeError, ArrayProxy, bio, ()) - assert_raises(TypeError, ArrayProxy, bio, tuple_spec[:1]) - assert_raises(TypeError, ArrayProxy, bio, tuple_spec + ('error',)) + with pytest.raises(TypeError): + ArrayProxy(bio, ()) + with pytest.raises(TypeError): + ArrayProxy(bio, tuple_spec[:1]) + with pytest.raises(TypeError): + ArrayProxy(bio, tuple_spec + ('error',)) def write_raw_data(arr, hdr, fileobj): @@ -136,8 +140,8 @@ def test_nifti1_init(): write_raw_data(arr, hdr, bio) hdr.set_slope_inter(2, 10) ap = ArrayProxy(bio, hdr) - assert_true(ap.file_like == bio) - assert_equal(ap.shape, shape) + assert ap.file_like == bio + assert ap.shape == shape # Get the data assert_array_equal(np.asarray(ap), arr * 2.0 + 10) with InTemporaryDirectory(): @@ -145,8 +149,8 @@ def test_nifti1_init(): write_raw_data(arr, hdr, f) f.close() ap = ArrayProxy('test.nii', hdr) - assert_true(ap.file_like == 'test.nii') - assert_equal(ap.shape, shape) + assert ap.file_like == 'test.nii' + assert ap.shape == shape assert_array_equal(np.asarray(ap), arr * 2.0 + 10) @@ -182,14 +186,14 @@ def test_is_proxy(): hdr = FunkyHeader((2, 3, 4)) bio = BytesIO() prox = ArrayProxy(bio, hdr) - assert_true(is_proxy(prox)) - assert_false(is_proxy(bio)) - assert_false(is_proxy(hdr)) - assert_false(is_proxy(np.zeros((2, 3, 4)))) + assert is_proxy(prox) + assert not is_proxy(bio) + assert not is_proxy(hdr) + assert not is_proxy(np.zeros((2, 3, 4))) class NP(object): is_proxy = False - assert_false(is_proxy(NP())) + assert not is_proxy(NP()) def test_reshape_dataobj(): @@ -203,11 +207,11 @@ def test_reshape_dataobj(): assert_array_equal(prox, arr) assert_array_equal(reshape_dataobj(prox, (2, 3, 4)), np.reshape(arr, (2, 3, 4))) - assert_equal(prox.shape, shape) - assert_equal(arr.shape, shape) + assert prox.shape == shape + assert arr.shape == shape assert_array_equal(reshape_dataobj(arr, (2, 3, 4)), np.reshape(arr, (2, 3, 4))) - assert_equal(arr.shape, shape) + assert arr.shape == shape class ArrGiver(object): @@ -216,7 +220,7 @@ def __array__(self): assert_array_equal(reshape_dataobj(ArrGiver(), (2, 3, 4)), np.reshape(arr, (2, 3, 4))) - assert_equal(arr.shape, shape) + assert arr.shape == shape def test_reshaped_is_proxy(): @@ -224,13 +228,16 @@ def test_reshaped_is_proxy(): hdr = FunkyHeader(shape) bio = BytesIO() prox = ArrayProxy(bio, hdr) - assert_true(isinstance(prox.reshape((2, 3, 4)), ArrayProxy)) + assert isinstance(prox.reshape((2, 3, 4)), ArrayProxy) minus1 = prox.reshape((2, -1, 4)) - assert_true(isinstance(minus1, ArrayProxy)) - assert_equal(minus1.shape, (2, 3, 4)) - assert_raises(ValueError, prox.reshape, (-1, -1, 4)) - assert_raises(ValueError, prox.reshape, (2, 3, 5)) - assert_raises(ValueError, prox.reshape, (2, -1, 5)) + assert isinstance(minus1, ArrayProxy) + assert minus1.shape == (2, 3, 4) + with pytest.raises(ValueError): + prox.reshape((-1, -1, 4)) + with pytest.raises(ValueError): + prox.reshape((2, 3, 5)) + with pytest.raises(ValueError): + prox.reshape((2, -1, 5)) def test_get_unscaled(): @@ -313,21 +320,24 @@ def check_mmap(hdr, offset, proxy_class, unscaled_is_mmap = isinstance(unscaled, np.memmap) back_is_mmap = isinstance(back_data, np.memmap) if expected_mode is None: - assert_false(unscaled_is_mmap) - assert_false(back_is_mmap) + assert not unscaled_is_mmap + assert not back_is_mmap else: - assert_equal(unscaled_is_mmap, - viral_memmap or unscaled_really_mmap) - assert_equal(back_is_mmap, - viral_memmap or scaled_really_mmap) + assert (unscaled_is_mmap == + (viral_memmap or unscaled_really_mmap)) + assert (back_is_mmap == + (viral_memmap or scaled_really_mmap)) if scaled_really_mmap: - assert_equal(back_data.mode, expected_mode) + assert back_data.mode == expected_mode del prox, back_data # Check that mmap is keyword-only - assert_raises(TypeError, proxy_class, fname, hdr, True) + with pytest.raises(TypeError): + proxy_class(fname, hdr, True) # Check invalid values raise error - assert_raises(ValueError, proxy_class, fname, hdr, mmap='rw') - assert_raises(ValueError, proxy_class, fname, hdr, mmap='r+') + with pytest.raises(ValueError): + proxy_class(fname, hdr, mmap='rw') + with pytest.raises(ValueError): + proxy_class(fname, hdr, mmap='r+') # An image opener class which counts how many instances of itself have been @@ -462,11 +472,11 @@ def test_keep_file_open_true_false_invalid(): fobj.write(data.tostring(order='F')) for invalid_kfo in (55, 'auto', 'cauto'): - with assert_raises(ValueError): + with pytest.raises(ValueError): ArrayProxy(fname, ((10, 10, 10), dtype), keep_file_open=invalid_kfo) with patch_keep_file_open_default(invalid_kfo): - with assert_raises(ValueError): + with pytest.raises(ValueError): ArrayProxy(fname, ((10, 10, 10), dtype)) diff --git a/nibabel/tests/test_arraywriters.py b/nibabel/tests/test_arraywriters.py index d5547e875f..fa24b37102 100644 --- a/nibabel/tests/test_arraywriters.py +++ b/nibabel/tests/test_arraywriters.py @@ -16,10 +16,8 @@ from numpy.testing import (assert_array_almost_equal, assert_array_equal) -from nose.tools import (assert_true, assert_false, - assert_equal, assert_not_equal, - assert_raises) -from ..testing import (assert_allclose_safely, suppress_warnings, +import pytest +from ..testing_pytest import (assert_allclose_safely, suppress_warnings, error_warnings) @@ -56,8 +54,8 @@ def test_arraywriters(): for type in test_types: arr = np.arange(10, dtype=type) aw = klass(arr) - assert_true(aw.array is arr) - assert_equal(aw.out_dtype, arr.dtype) + assert aw.array is arr + assert aw.out_dtype == arr.dtype assert_array_equal(arr, round_trip(aw)) # Byteswapped should be OK bs_arr = arr.byteswap().newbyteorder('S') @@ -80,7 +78,7 @@ def test_arraywriters(): # C order works as well arr_back = round_trip(a2w, 'C') assert_array_equal(arr2, arr_back) - assert_true(arr_back.flags.c_contiguous) + assert arr_back.flags.c_contiguous def test_arraywriter_check_scaling(): @@ -89,14 +87,17 @@ def test_arraywriter_check_scaling(): arr = np.array([0, 1, 128, 255], np.uint8) aw = ArrayWriter(arr) # Out of range, scaling needed, default is error - assert_raises(WriterError, ArrayWriter, arr, np.int8) + with pytest.raises(WriterError): + ArrayWriter(arr, np.int8) # Make default explicit - assert_raises(WriterError, ArrayWriter, arr, np.int8, check_scaling=True) + with pytest.raises(WriterError): + ArrayWriter(arr, np.int8, check_scaling=True) # Turn off scaling check aw = ArrayWriter(arr, np.int8, check_scaling=False) assert_array_equal(round_trip(aw), np.clip(arr, 0, 127)) # Has to be keyword - assert_raises(TypeError, ArrayWriter, arr, np.int8, False) + with pytest.raises(TypeError): + ArrayWriter(arr, np.int8, False) def test_no_scaling(): @@ -154,39 +155,42 @@ def test_scaling_needed(): dt_def = [('f', 'i4')] arr = np.ones(10, dt_def) for t in NUMERIC_TYPES: - assert_raises(WriterError, ArrayWriter, arr, t) + with pytest.raises(WriterError): + ArrayWriter(arr, t) narr = np.ones(10, t) - assert_raises(WriterError, ArrayWriter, narr, dt_def) - assert_false(ArrayWriter(arr).scaling_needed()) - assert_false(ArrayWriter(arr, dt_def).scaling_needed()) + with pytest.raises(WriterError): + ArrayWriter(narr, dt_def) + assert not ArrayWriter(arr).scaling_needed() + assert not ArrayWriter(arr, dt_def).scaling_needed() # Any numeric type that can cast, needs no scaling for in_t in NUMERIC_TYPES: for out_t in NUMERIC_TYPES: if np.can_cast(in_t, out_t): aw = ArrayWriter(np.ones(10, in_t), out_t) - assert_false(aw.scaling_needed()) + assert not aw.scaling_needed() for in_t in NUMERIC_TYPES: # Numeric types to complex never need scaling arr = np.ones(10, in_t) for out_t in COMPLEX_TYPES: - assert_false(ArrayWriter(arr, out_t).scaling_needed()) + assert not ArrayWriter(arr, out_t).scaling_needed() # Attempts to scale from complex to anything else fails for in_t in COMPLEX_TYPES: for out_t in FLOAT_TYPES + IUINT_TYPES: arr = np.ones(10, in_t) - assert_raises(WriterError, ArrayWriter, arr, out_t) + with pytest.raises(WriterError): + ArrayWriter(arr, out_t) # Scaling from anything but complex to floats is OK for in_t in FLOAT_TYPES + IUINT_TYPES: arr = np.ones(10, in_t) for out_t in FLOAT_TYPES: - assert_false(ArrayWriter(arr, out_t).scaling_needed()) + assert not ArrayWriter(arr, out_t).scaling_needed() # For any other output type, arrays with no data don't need scaling for in_t in FLOAT_TYPES + IUINT_TYPES: arr_0 = np.zeros(10, in_t) arr_e = [] for out_t in IUINT_TYPES: - assert_false(ArrayWriter(arr_0, out_t).scaling_needed()) - assert_false(ArrayWriter(arr_e, out_t).scaling_needed()) + assert not ArrayWriter(arr_0, out_t).scaling_needed() + assert not ArrayWriter(arr_e, out_t).scaling_needed() # Going to (u)ints, non-finite arrays don't need scaling for writers that # can do scaling because these use finite_range to threshold the input data, # but ArrayWriter does not do this. so scaling_needed is True @@ -197,17 +201,16 @@ def test_scaling_needed(): arr_mix = np.array([np.nan, np.inf, -np.inf], dtype=in_t) for out_t in IUINT_TYPES: for arr in (arr_nan, arr_inf, arr_minf, arr_mix): - assert_true( - ArrayWriter(arr, out_t, check_scaling=False).scaling_needed()) - assert_false(SlopeArrayWriter(arr, out_t).scaling_needed()) - assert_false(SlopeInterArrayWriter(arr, out_t).scaling_needed()) + assert ArrayWriter(arr, out_t, check_scaling=False).scaling_needed() + assert not SlopeArrayWriter(arr, out_t).scaling_needed() + assert not SlopeInterArrayWriter(arr, out_t).scaling_needed() # Floats as input always need scaling for in_t in FLOAT_TYPES: arr = np.ones(10, in_t) for out_t in IUINT_TYPES: # We need an arraywriter that will tolerate construction when # scaling is needed - assert_true(SlopeArrayWriter(arr, out_t).scaling_needed()) + assert SlopeArrayWriter(arr, out_t).scaling_needed() # in-range (u)ints don't need scaling for in_t in IUINT_TYPES: in_info = np.iinfo(in_t) @@ -217,18 +220,18 @@ def test_scaling_needed(): out_min, out_max = out_info.min, out_info.max if in_min >= out_min and in_max <= out_max: arr = np.array([in_min, in_max], in_t) - assert_true(np.can_cast(arr.dtype, out_t)) + assert np.can_cast(arr.dtype, out_t) # We've already tested this with can_cast above, but... - assert_false(ArrayWriter(arr, out_t).scaling_needed()) + assert not ArrayWriter(arr, out_t).scaling_needed() continue # The output data type does not include the input data range max_min = max(in_min, out_min) # 0 for input or output uint min_max = min(in_max, out_max) arr = np.array([max_min, min_max], in_t) - assert_false(ArrayWriter(arr, out_t).scaling_needed()) - assert_true(SlopeInterArrayWriter(arr + 1, out_t).scaling_needed()) + assert not ArrayWriter(arr, out_t).scaling_needed() + assert SlopeInterArrayWriter(arr + 1, out_t).scaling_needed() if in_t in INT_TYPES: - assert_true(SlopeInterArrayWriter(arr - 1, out_t).scaling_needed()) + assert SlopeInterArrayWriter(arr - 1, out_t).scaling_needed() def test_special_rt(): @@ -239,14 +242,15 @@ def test_special_rt(): for in_dtt in FLOAT_TYPES: for out_dtt in IUINT_TYPES: in_arr = arr.astype(in_dtt) - assert_raises(WriterError, ArrayWriter, in_arr, out_dtt) + with pytest.raises(WriterError): + ArrayWriter(in_arr, out_dtt) aw = ArrayWriter(in_arr, out_dtt, check_scaling=False) mn, mx = shared_range(float, out_dtt) - assert_true(np.allclose(round_trip(aw).astype(float), - [mx, 0, mn])) + assert np.allclose(round_trip(aw).astype(float), + [mx, 0, mn]) for klass in (SlopeArrayWriter, SlopeInterArrayWriter): aw = klass(in_arr, out_dtt) - assert_equal(get_slope_inter(aw), (1, 0)) + assert get_slope_inter(aw) == (1, 0) assert_array_equal(round_trip(aw), 0) for in_dtt, out_dtt, awt in itertools.product( FLOAT_TYPES, @@ -254,7 +258,7 @@ def test_special_rt(): (ArrayWriter, SlopeArrayWriter, SlopeInterArrayWriter)): arr = np.zeros((3,), dtype=in_dtt) aw = awt(arr, out_dtt) - assert_equal(get_slope_inter(aw), (1, 0)) + assert get_slope_inter(aw) == (1, 0) assert_array_equal(round_trip(aw), 0) @@ -265,7 +269,7 @@ def test_high_int2uint(): arr = np.array([2**63], dtype=np.uint64) out_type = np.int64 aw = SlopeInterArrayWriter(arr, out_type) - assert_equal(aw.inter, 2**63) + assert aw.inter == 2**63 def test_slope_inter_castable(): @@ -282,7 +286,8 @@ def test_slope_inter_castable(): for in_dtt in FLOAT_TYPES: for out_dtt in IUINT_TYPES: in_arr = arr.astype(in_dtt) - assert_raises(WriterError, ArrayWriter, in_arr, out_dtt) + with pytest.raises(WriterError): + ArrayWriter(in_arr, out_dtt) aw = SlopeArrayWriter(arr.astype(in_dtt), out_dtt) # no error aw = SlopeInterArrayWriter(arr.astype(in_dtt), out_dtt) # no error for in_dtt, out_dtt, arr, slope_only, slope_inter, neither in ( @@ -313,17 +318,20 @@ def test_slope_inter_castable(): if slope_only: SlopeArrayWriter(data, out_dtt) else: - assert_raises(WriterError, SlopeArrayWriter, data, out_dtt) + with pytest.raises(WriterError): + SlopeArrayWriter(data, out_dtt) # With scaling and intercept if slope_inter: SlopeInterArrayWriter(data, out_dtt) else: - assert_raises(WriterError, SlopeInterArrayWriter, data, out_dtt) + with pytest.raises(WriterError): + SlopeInterArrayWriter(data, out_dtt) # With neither if neither: ArrayWriter(data, out_dtt) else: - assert_raises(WriterError, ArrayWriter, data, out_dtt) + with pytest.raises(WriterError): + ArrayWriter(data, out_dtt) def test_calculate_scale(): @@ -333,27 +341,28 @@ def test_calculate_scale(): SAW = SlopeArrayWriter # Offset handles scaling when it can aw = SIAW(npa([-2, -1], dtype=np.int8), np.uint8) - assert_equal(get_slope_inter(aw), (1.0, -2.0)) + assert get_slope_inter(aw) == (1.0, -2.0) # Sign flip handles these cases aw = SAW(npa([-2, -1], dtype=np.int8), np.uint8) - assert_equal(get_slope_inter(aw), (-1.0, 0.0)) + assert get_slope_inter(aw) == (-1.0, 0.0) aw = SAW(npa([-2, 0], dtype=np.int8), np.uint8) - assert_equal(get_slope_inter(aw), (-1.0, 0.0)) + assert get_slope_inter(aw) == (-1.0, 0.0) # But not when min magnitude is too large (scaling mechanism kicks in) aw = SAW(npa([-510, 0], dtype=np.int16), np.uint8) - assert_equal(get_slope_inter(aw), (-2.0, 0.0)) + assert get_slope_inter(aw) == (-2.0, 0.0) # Or for floats (attempts to expand across range) aw = SAW(npa([-2, 0], dtype=np.float32), np.uint8) - assert_not_equal(get_slope_inter(aw), (-1.0, 0.0)) + assert get_slope_inter(aw) != (-1.0, 0.0) # Case where offset handles scaling aw = SIAW(npa([-1, 1], dtype=np.int8), np.uint8) - assert_equal(get_slope_inter(aw), (1.0, -1.0)) + assert get_slope_inter(aw) == (1.0, -1.0) # Can't work for no offset case - assert_raises(WriterError, SAW, npa([-1, 1], dtype=np.int8), np.uint8) + with pytest.raises(WriterError): + SAW(npa([-1, 1], dtype=np.int8), np.uint8) # Offset trick can't work when max is out of range aw = SIAW(npa([-1, 255], dtype=np.int16), np.uint8) slope_inter = get_slope_inter(aw) - assert_not_equal(slope_inter, (1.0, -1.0)) + assert slope_inter != (1.0, -1.0) def test_resets(): @@ -391,11 +400,11 @@ def test_no_offset_scale(): (126, 127), (-127, 127)): aw = SAW(np.array(data, dtype=np.float32), np.int8) - assert_equal(aw.slope, 1.0) + assert aw.slope == 1.0 aw = SAW(np.array([-126, 127 * 2.0], dtype=np.float32), np.int8) - assert_equal(aw.slope, 2) + assert aw.slope == 2 aw = SAW(np.array([-128 * 2.0, 127], dtype=np.float32), np.int8) - assert_equal(aw.slope, 2) + assert aw.slope == 2 # Test that nasty abs behavior does not upset us n = -2**15 aw = SAW(np.array([n, n], dtype=np.int16), np.uint8) @@ -406,17 +415,17 @@ def test_with_offset_scale(): # Tests of specific cases in slope, inter SIAW = SlopeInterArrayWriter aw = SIAW(np.array([0, 127], dtype=np.int8), np.uint8) - assert_equal((aw.slope, aw.inter), (1, 0)) # in range + assert (aw.slope, aw.inter) == (1, 0) # in range aw = SIAW(np.array([-1, 126], dtype=np.int8), np.uint8) - assert_equal((aw.slope, aw.inter), (1, -1)) # offset only + assert (aw.slope, aw.inter) == (1, -1) # offset only aw = SIAW(np.array([-1, 254], dtype=np.int16), np.uint8) - assert_equal((aw.slope, aw.inter), (1, -1)) # offset only + assert (aw.slope, aw.inter) == (1, -1) # offset only aw = SIAW(np.array([-1, 255], dtype=np.int16), np.uint8) - assert_not_equal((aw.slope, aw.inter), (1, -1)) # Too big for offset only + assert (aw.slope, aw.inter) != (1, -1) # Too big for offset only aw = SIAW(np.array([-256, -2], dtype=np.int16), np.uint8) - assert_equal((aw.slope, aw.inter), (1, -256)) # offset only + assert (aw.slope, aw.inter) == (1, -256) # offset only aw = SIAW(np.array([-256, -2], dtype=np.int16), np.int8) - assert_equal((aw.slope, aw.inter), (1, -129)) # offset only + assert (aw.slope, aw.inter) == (1, -129) # offset only def test_io_scaling(): @@ -450,10 +459,10 @@ def test_io_scaling(): # Slope might be negative max_miss = np.abs(aw.slope) / 2. abs_err = np.abs(arr - arr3) - assert_true(np.all(abs_err <= max_miss)) + assert np.all(abs_err <= max_miss) if out_type in UINT_TYPES and 0 in (min(arr), max(arr)): # Check that error is minimized for 0 as min or max - assert_true(min(abs_err) == abs_err[arr == 0]) + assert min(abs_err) == abs_err[arr == 0] bio.truncate(0) bio.seek(0) @@ -476,10 +485,10 @@ def test_input_ranges(): max_miss = np.abs(aw.slope) / working_type(2.) + work_eps * 10 abs_err = np.abs(arr - arr3) max_err = np.abs(arr) * work_eps + max_miss - assert_true(np.all(abs_err <= max_err)) + assert np.all(abs_err <= max_err) if out_type in UINT_TYPES and 0 in (min(arr), max(arr)): # Check that error is minimized for 0 as min or max - assert_true(min(abs_err) == abs_err[arr == 0]) + assert min(abs_err) == abs_err[arr == 0] bio.truncate(0) bio.seek(0) @@ -500,12 +509,13 @@ def test_nan2zero(): assert_array_equal(np.isnan(data_back), [True, False]) # Deprecation warning for nan2zero as argument to `to_fileobj` with error_warnings(): - assert_raises(DeprecationWarning, - aw.to_fileobj, BytesIO(), 'F', True) - assert_raises(DeprecationWarning, - aw.to_fileobj, BytesIO(), 'F', nan2zero=True) + with pytest.raises(DeprecationWarning): + aw.to_fileobj(BytesIO(), 'F', True) + with pytest.raises(DeprecationWarning): + aw.to_fileobj(BytesIO(), 'F', nan2zero=True) # Error if nan2zero is not the value set at initialization - assert_raises(WriterError, aw.to_fileobj, BytesIO(), 'F', False) + with pytest.raises(WriterError): + aw.to_fileobj(BytesIO(), 'F', False) # set explicitly aw = awt(arr, np.float32, nan2zero=True, **kwargs) data_back = round_trip(aw) @@ -521,12 +531,13 @@ def test_nan2zero(): assert_array_equal(data_back, [astype_res, 99]) # Deprecation warning for nan2zero as argument to `to_fileobj` with error_warnings(): - assert_raises(DeprecationWarning, - aw.to_fileobj, BytesIO(), 'F', False) - assert_raises(DeprecationWarning, - aw.to_fileobj, BytesIO(), 'F', nan2zero=False) + with pytest.raises(DeprecationWarning): + aw.to_fileobj(BytesIO(), 'F', False) + with pytest.raises(DeprecationWarning): + aw.to_fileobj(BytesIO(), 'F', nan2zero=False) # Error if nan2zero is not the value set at initialization - assert_raises(WriterError, aw.to_fileobj, BytesIO(), 'F', True) + with pytest.raises(WriterError): + aw.to_fileobj(BytesIO(), 'F', True) def test_byte_orders(): @@ -580,55 +591,62 @@ def test_to_float(): for klass in (SlopeInterArrayWriter, SlopeArrayWriter, ArrayWriter): if in_type in COMPLEX_TYPES and out_type in FLOAT_TYPES: - assert_raises(WriterError, klass, arr, out_type) + with pytest.raises(WriterError): + klass(arr, out_type) continue aw = klass(arr, out_type) - assert_true(aw.array is arr) - assert_equal(aw.out_dtype, out_type) + assert aw.array is arr + assert aw.out_dtype == out_type arr_back = round_trip(aw) assert_array_equal(arr.astype(out_type), arr_back) # Check too-big values overflowed correctly out_min, out_max = out_info['min'], out_info['max'] - assert_true(np.all(arr_back[arr > out_max] == np.inf)) - assert_true(np.all(arr_back[arr < out_min] == -np.inf)) + assert np.all(arr_back[arr > out_max] == np.inf) + assert np.all(arr_back[arr < out_min] == -np.inf) def test_dumber_writers(): arr = np.arange(10, dtype=np.float64) aw = SlopeArrayWriter(arr) aw.slope = 2.0 - assert_equal(aw.slope, 2.0) - assert_raises(AttributeError, getattr, aw, 'inter') + assert aw.slope == 2.0 + with pytest.raises(AttributeError): + getattr(aw, 'inter') aw = ArrayWriter(arr) - assert_raises(AttributeError, getattr, aw, 'slope') - assert_raises(AttributeError, getattr, aw, 'inter') + with pytest.raises(AttributeError): + getattr(aw, 'slope') + with pytest.raises(AttributeError): + getattr(aw, 'inter') # Attempt at scaling should raise error for dumb type - assert_raises(WriterError, ArrayWriter, arr, np.int16) + with pytest.raises(WriterError): + ArrayWriter(arr, np.int16) def test_writer_maker(): arr = np.arange(10, dtype=np.float64) aw = make_array_writer(arr, np.float64) - assert_true(isinstance(aw, SlopeInterArrayWriter)) + assert isinstance(aw, SlopeInterArrayWriter) aw = make_array_writer(arr, np.float64, True, True) - assert_true(isinstance(aw, SlopeInterArrayWriter)) + assert isinstance(aw, SlopeInterArrayWriter) aw = make_array_writer(arr, np.float64, True, False) - assert_true(isinstance(aw, SlopeArrayWriter)) + assert isinstance(aw, SlopeArrayWriter) aw = make_array_writer(arr, np.float64, False, False) - assert_true(isinstance(aw, ArrayWriter)) - assert_raises(ValueError, make_array_writer, arr, np.float64, False) - assert_raises(ValueError, make_array_writer, arr, np.float64, False, True) + assert isinstance(aw, ArrayWriter) + with pytest.raises(ValueError): + make_array_writer(arr, np.float64, False) + with pytest.raises(ValueError): + make_array_writer(arr, np.float64, False, True) # Does calc_scale get run by default? aw = make_array_writer(arr, np.int16, calc_scale=False) - assert_equal((aw.slope, aw.inter), (1, 0)) + assert (aw.slope, aw.inter) == (1, 0) aw.calc_scale() slope, inter = aw.slope, aw.inter - assert_false((slope, inter) == (1, 0)) + assert not (slope, inter) == (1, 0) # Should run by default aw = make_array_writer(arr, np.int16) - assert_equal((aw.slope, aw.inter), (slope, inter)) + assert (aw.slope, aw.inter) == (slope, inter) aw = make_array_writer(arr, np.int16, calc_scale=True) - assert_equal((aw.slope, aw.inter), (slope, inter)) + assert (aw.slope, aw.inter) == (slope, inter) def test_float_int_min_max(): @@ -647,7 +665,7 @@ def test_float_int_min_max(): except ScalingError: continue arr_back_sc = round_trip(aw) - assert_true(np.allclose(arr, arr_back_sc)) + assert np.allclose(arr, arr_back_sc) def test_int_int_min_max(): @@ -666,7 +684,7 @@ def test_int_int_min_max(): # integer allclose adiff = int_abs(arr - arr_back_sc) rdiff = adiff / (arr + eps) - assert_true(np.all(rdiff < rtol)) + assert np.all(rdiff < rtol) def test_int_int_slope(): @@ -687,12 +705,12 @@ def test_int_int_slope(): aw = SlopeArrayWriter(arr, out_dt) except ScalingError: continue - assert_false(aw.slope == 0) + assert not aw.slope == 0 arr_back_sc = round_trip(aw) # integer allclose adiff = int_abs(arr - arr_back_sc) rdiff = adiff / (arr + eps) - assert_true(np.all(rdiff < rtol)) + assert np.all(rdiff < rtol) def test_float_int_spread(): @@ -712,7 +730,7 @@ def test_float_int_spread(): # Simulate allclose test with large atol diff = np.abs(arr_t - arr_back_sc) rdiff = diff / np.abs(arr_t) - assert_true(np.all((diff <= max_miss) | (rdiff <= 1e-5))) + assert np.all((diff <= max_miss) | (rdiff <= 1e-5)) def rt_err_estimate(arr_t, out_dtype, slope, inter): @@ -749,7 +767,7 @@ def test_rt_bias(): aw.inter) # Hokey use of max_miss as a std estimate bias_thresh = np.max([max_miss / np.sqrt(count), eps]) - assert_true(np.abs(bias) < bias_thresh) + assert np.abs(bias) < bias_thresh def test_nan2zero_scaling(): @@ -789,10 +807,10 @@ def test_nan2zero_scaling(): back_nan_0 = round_trip(nan_0_aw) * float(sign) zero_aw = awt(zero_arr, out_dt, nan2zero=True) back_zero = round_trip(zero_aw) * float(sign) - assert_true(np.allclose(back_nan[1:], back_zero[1:])) + assert np.allclose(back_nan[1:], back_zero[1:]) assert_array_equal(back_nan[1:], back_nan_0[2:]) - assert_true(np.abs(back_nan[0] - back_zero[0]) < 1e-2) - assert_equal(*back_nan_0[:2]) + assert np.abs(back_nan[0] - back_zero[0]) < 1e-2 + assert back_nan_0[0] == back_nan_0[1] def test_finite_range_nan(): @@ -834,11 +852,11 @@ def test_finite_range_nan(): continue # Should not matter about the order of finite range method call # and has_nan property - test this is true - assert_equal(aw.has_nan, has_nan) - assert_equal(aw.finite_range(), res) + assert aw.has_nan == has_nan + assert aw.finite_range() == res aw = awt(in_arr, out_type, **kwargs) - assert_equal(aw.finite_range(), res) - assert_equal(aw.has_nan, has_nan) + assert aw.finite_range() == res + assert aw.has_nan == has_nan # Check float types work as complex in_arr = np.array(in_arr) if in_arr.dtype.kind == 'f': @@ -848,10 +866,11 @@ def test_finite_range_nan(): except WriterError: continue aw = awt(c_arr, out_type, **kwargs) - assert_equal(aw.has_nan, has_nan) - assert_equal(aw.finite_range(), res) + assert aw.has_nan == has_nan + assert aw.finite_range() == res # Structured type cannot be nan and we can test this a = np.array([[1., 0, 1], [2, 3, 4]]).view([('f1', 'f')]) aw = awt(a, a.dtype, **kwargs) - assert_raises(TypeError, aw.finite_range) - assert_false(aw.has_nan) + with pytest.raises(TypeError): + aw.finite_range() + assert not aw.has_nan diff --git a/nibabel/tests/test_wrapstruct.py b/nibabel/tests/test_wrapstruct.py index 45e8c28a52..b5ccdd2907 100644 --- a/nibabel/tests/test_wrapstruct.py +++ b/nibabel/tests/test_wrapstruct.py @@ -34,12 +34,11 @@ from ..spatialimages import HeaderDataError from .. import imageglobals -from unittest import TestCase +from unittest import TestCase, SkipTest from numpy.testing import assert_array_equal +import pytest -from ..testing import (assert_equal, assert_true, assert_false, - assert_raises, assert_not_equal) INTEGER_TYPES = np.sctypes['int'] + np.sctypes['uint'] @@ -80,7 +79,7 @@ def log_chk(hdr, level): if level == 0: # Should never log or raise error logger.setLevel(0) hdrc.check_fix(logger=logger, error_level=0) - assert_equal(str_io.getvalue(), '') + assert str_io.getvalue() == '' logger.removeHandler(handler) return hdrc, '', () # Non zero defect level, test above and below threshold. @@ -90,12 +89,12 @@ def log_chk(hdr, level): # Logging level above threshold, no log. logger.setLevel(level + 1) hdrc.check_fix(logger=logger, error_level=e_lev) - assert_equal(str_io.getvalue(), '') + assert str_io.getvalue() == '' # Logging level below threshold, log appears, store logged message logger.setLevel(level - 1) hdrc = hdr.copy() hdrc.check_fix(logger=logger, error_level=e_lev) - assert_true(str_io.getvalue() != '') + assert str_io.getvalue() != '' message = str_io.getvalue().strip() logger.removeHandler(handler) # When error level == level, check_fix should raise an error @@ -119,16 +118,22 @@ def get_bad_bb(self): # means do not check return None + @classmethod + def setUpClass(cls): + if cls.header_class is None: + raise SkipTest("no testing methods from the abstract class") + + def test_general_init(self): hdr = self.header_class() # binaryblock has length given by header data dtype binblock = hdr.binaryblock - assert_equal(len(binblock), hdr.structarr.dtype.itemsize) + assert len(binblock) == hdr.structarr.dtype.itemsize # Endianness will be native by default for empty header - assert_equal(hdr.endianness, native_code) + assert hdr.endianness == native_code # But you can change this if you want hdr = self.header_class(endianness='swapped') - assert_equal(hdr.endianness, swapped_code) + assert hdr.endianness == swapped_code # You can also pass in a check flag, without data this has no # effect hdr = self.header_class(check=False) @@ -141,17 +146,17 @@ def test__eq__(self): # Test equal and not equal hdr1 = self.header_class() hdr2 = self.header_class() - assert_equal(hdr1, hdr2) + assert hdr1 == hdr2 self._set_something_into_hdr(hdr1) - assert_not_equal(hdr1, hdr2) + assert hdr1 != hdr2 self._set_something_into_hdr(hdr2) - assert_equal(hdr1, hdr2) + assert hdr1 == hdr2 # Check byteswapping maintains equality hdr3 = hdr2.as_byteswapped() - assert_equal(hdr2, hdr3) + assert hdr2 == hdr3 # Check comparing to funny thing says no - assert_not_equal(hdr1, None) - assert_not_equal(hdr1, 1) + assert hdr1 != None + assert hdr1 != 1 def test_to_from_fileobj(self): # Successful write using write_to @@ -160,28 +165,26 @@ def test_to_from_fileobj(self): hdr.write_to(str_io) str_io.seek(0) hdr2 = self.header_class.from_fileobj(str_io) - assert_equal(hdr2.endianness, native_code) - assert_equal(hdr2.binaryblock, hdr.binaryblock) + assert hdr2.endianness == native_code + assert hdr2.binaryblock == hdr.binaryblock def test_mappingness(self): hdr = self.header_class() - assert_raises(ValueError, - hdr.__setitem__, - 'nonexistent key', - 0.1) + with pytest.raises(ValueError): + hdr.__setitem__('nonexistent key', 0.1) hdr_dt = hdr.structarr.dtype keys = hdr.keys() - assert_equal(keys, list(hdr)) + assert keys == list(hdr) vals = hdr.values() - assert_equal(len(vals), len(keys)) - assert_equal(keys, list(hdr_dt.names)) + assert len(vals) == len(keys) + assert keys == list(hdr_dt.names) for key, val in hdr.items(): assert_array_equal(hdr[key], val) # verify that .get operates as destined - assert_equal(hdr.get('nonexistent key'), None) - assert_equal(hdr.get('nonexistent key', 'default'), 'default') - assert_equal(hdr.get(keys[0]), vals[0]) - assert_equal(hdr.get(keys[0], 'default'), vals[0]) + assert hdr.get('nonexistent key') == None + assert hdr.get('nonexistent key', 'default') == 'default' + assert hdr.get(keys[0]) == vals[0] + assert hdr.get(keys[0], 'default') == vals[0] # make sure .get returns values which evaluate to False. We have to # use a different falsy value depending on the data type of the first @@ -189,9 +192,9 @@ def test_mappingness(self): falsyval = 0 if np.issubdtype(hdr_dt[0], np.number) else b'' hdr[keys[0]] = falsyval - assert_equal(hdr[keys[0]], falsyval) - assert_equal(hdr.get(keys[0]), falsyval) - assert_equal(hdr.get(keys[0], -1), falsyval) + assert hdr[keys[0]] == falsyval + assert hdr.get(keys[0]) == falsyval + assert hdr.get(keys[0], -1) == falsyval def test_endianness_ro(self): @@ -203,16 +206,17 @@ def test_endianness_ro(self): data) - but this is done via via the as_byteswapped method ''' hdr = self.header_class() - assert_raises(AttributeError, hdr.__setattr__, 'endianness', '<') + with pytest.raises(AttributeError): + hdr.__setattr__('endianness', '<') def test_endian_guess(self): # Check guesses of endian eh = self.header_class() - assert_equal(eh.endianness, native_code) + assert eh.endianness == native_code hdr_data = eh.structarr.copy() hdr_data = hdr_data.byteswap(swapped_code) eh_swapped = self.header_class(hdr_data.tostring()) - assert_equal(eh_swapped.endianness, swapped_code) + assert eh_swapped.endianness == swapped_code def test_binblock_is_file(self): # Checks that the binary string respresentation is the whole of the @@ -224,7 +228,7 @@ def test_binblock_is_file(self): hdr = self.header_class() str_io = BytesIO() hdr.write_to(str_io) - assert_equal(str_io.getvalue(), hdr.binaryblock) + assert str_io.getvalue() == hdr.binaryblock def test_structarr(self): # structarr attribute also read only @@ -232,7 +236,8 @@ def test_structarr(self): # Just check we can get structarr hdr.structarr # That it's read only - assert_raises(AttributeError, hdr.__setattr__, 'structarr', 0) + with pytest.raises(AttributeError): + hdr.__setattr__('structarr', 0) def log_chk(self, hdr, level): return log_chk(hdr, level) @@ -241,50 +246,49 @@ def assert_no_log_err(self, hdr): """ Assert that no logging or errors result from this `hdr` """ fhdr, message, raiser = self.log_chk(hdr, 0) - assert_equal((fhdr, message), (hdr, '')) + assert (fhdr, message) == (hdr, '') def test_bytes(self): # Test get of bytes hdr1 = self.header_class() bb = hdr1.binaryblock hdr2 = self.header_class(hdr1.binaryblock) - assert_equal(hdr1, hdr2) - assert_equal(hdr1.binaryblock, hdr2.binaryblock) + assert hdr1 == hdr2 + assert hdr1.binaryblock == hdr2.binaryblock # Do a set into the header, and try again. The specifics of 'setting # something' will depend on the nature of the bytes object self._set_something_into_hdr(hdr1) hdr2 = self.header_class(hdr1.binaryblock) - assert_equal(hdr1, hdr2) - assert_equal(hdr1.binaryblock, hdr2.binaryblock) + assert hdr1 == hdr2 + assert hdr1.binaryblock == hdr2.binaryblock # Short and long binaryblocks give errors # (here set through init) - assert_raises(WrapStructError, - self.header_class, - bb[:-1]) - assert_raises(WrapStructError, - self.header_class, - bb + b'\x00') + with pytest.raises(WrapStructError): + self.header_class(bb[:-1]) + with pytest.raises(WrapStructError): + self.header_class(bb + b'\x00') # Checking set to true by default, and prevents nonsense being # set into the header. bb_bad = self.get_bad_bb() if bb_bad is None: return with imageglobals.LoggingOutputSuppressor(): - assert_raises(HeaderDataError, self.header_class, bb_bad) + with pytest.raises(HeaderDataError): + self.header_class(bb_bad) # now slips past without check _ = self.header_class(bb_bad, check=False) def test_as_byteswapped(self): # Check byte swapping hdr = self.header_class() - assert_equal(hdr.endianness, native_code) + assert hdr.endianness == native_code # same code just returns a copy hdr2 = hdr.as_byteswapped(native_code) - assert_false(hdr is hdr2) + assert not hdr is hdr2 # Different code gives byteswapped copy hdr_bs = hdr.as_byteswapped(swapped_code) - assert_equal(hdr_bs.endianness, swapped_code) - assert_not_equal(hdr.binaryblock, hdr_bs.binaryblock) + assert hdr_bs.endianness == swapped_code + assert hdr.binaryblock != hdr_bs.binaryblock # Note that contents is not rechecked on swap / copy class DC(self.header_class): @@ -292,7 +296,8 @@ class DC(self.header_class): def check_fix(self, *args, **kwargs): raise Exception # Assumes check=True default - assert_raises(Exception, DC, hdr.binaryblock) + with pytest.raises(Exception): + DC(hdr.binaryblock) hdr = DC(hdr.binaryblock, check=False) hdr2 = hdr.as_byteswapped(native_code) hdr_bs = hdr.as_byteswapped(swapped_code) @@ -311,7 +316,8 @@ def test_str(self): hdr = self.header_class() # Check something returns from str s1 = str(hdr) - assert_true(len(s1) > 0) + assert len(s1) > 0 + class _TestLabeledWrapStruct(_TestWrapStructBase): @@ -324,27 +330,30 @@ class MyHdr(self.header_class): _field_recoders = {} hdr = MyHdr() # Key not existing raises error - assert_raises(ValueError, hdr.get_value_label, 'improbable') + with pytest.raises(ValueError): + hdr.get_value_label('improbable') # Even if there is a recoder - assert_true('improbable' not in hdr.keys()) + assert 'improbable' not in hdr.keys() rec = Recoder([[0, 'fullness of heart']], ('code', 'label')) hdr._field_recoders['improbable'] = rec - assert_raises(ValueError, hdr.get_value_label, 'improbable') + with pytest.raises(ValueError): + hdr.get_value_label('improbable') # If the key exists in the structure, and is intable, then we can recode for key, value in hdr.items(): # No recoder at first - assert_raises(ValueError, hdr.get_value_label, 0) + with pytest.raises(ValueError): + hdr.get_value_label(0) if not value.dtype.type in INTEGER_TYPES or not np.isscalar(value): continue code = int(value) rec = Recoder([[code, 'fullness of heart']], ('code', 'label')) hdr._field_recoders[key] = rec - assert_equal(hdr.get_value_label(key), 'fullness of heart') + assert hdr.get_value_label(key) == 'fullness of heart' # If key exists, but value is missing, we get 'unknown code' # Speculating that we can set code value 0 or 1 new_code = 1 if code == 0 else 0 hdr[key] = new_code - assert_equal(hdr.get_value_label(key), + assert (hdr.get_value_label(key) == ''.format(new_code)) @@ -418,48 +427,48 @@ def _set_something_into_hdr(self, hdr): def test_empty(self): # Test contents of default header hdr = self.header_class() - assert_equal(hdr['an_integer'], 1) - assert_equal(hdr['a_str'], b'a string') + assert hdr['an_integer'] == 1 + assert hdr['a_str'] == b'a string' def test_str(self): hdr = self.header_class() s1 = str(hdr) - assert_true(len(s1) > 0) - assert_true('an_integer' in s1) - assert_true('a_str' in s1) + assert len(s1) > 0 + assert 'an_integer' in s1 + assert 'a_str' in s1 def test_copy(self): hdr = self.header_class() hdr2 = hdr.copy() - assert_equal(hdr, hdr2) + assert hdr == hdr2 self._set_something_into_hdr(hdr) - assert_not_equal(hdr, hdr2) + assert hdr != hdr2 self._set_something_into_hdr(hdr2) - assert_equal(hdr, hdr2) + assert hdr == hdr2 def test_copy(self): hdr = self.header_class() hdr2 = hdr.copy() - assert_equal(hdr, hdr2) + assert hdr == hdr2 self._set_something_into_hdr(hdr) - assert_not_equal(hdr, hdr2) + assert hdr != hdr2 self._set_something_into_hdr(hdr2) - assert_equal(hdr, hdr2) + assert hdr == hdr2 def test_checks(self): # Test header checks hdr_t = self.header_class() # _dxer just returns the diagnostics as a string # Default hdr is OK - assert_equal(self._dxer(hdr_t), '') + assert self._dxer(hdr_t) == '' # An integer should be 1 hdr = hdr_t.copy() hdr['an_integer'] = 2 - assert_equal(self._dxer(hdr), 'an_integer should be 1') + assert self._dxer(hdr) == 'an_integer should be 1' # String should be lower case hdr = hdr_t.copy() hdr['a_str'] = 'My Name' - assert_equal(self._dxer(hdr), 'a_str should be lower case') + assert self._dxer(hdr) == 'a_str should be lower case' def test_log_checks(self): # Test logging, fixing, errors for header checking @@ -470,15 +479,15 @@ def test_log_checks(self): hdr['an_integer'] = 2 # severity 40 fhdr, message, raiser = self.log_chk(hdr, 40) return - assert_equal(fhdr['an_integer'], 1) - assert_equal(message, + assert fhdr['an_integer'] == 1 + assert (message == 'an_integer should be 1; set an_integer to 1') assert_raises(*raiser) # lower case string hdr = HC() hdr['a_str'] = 'Hello' # severity = 20 fhdr, message, raiser = self.log_chk(hdr, 20) - assert_equal(message, 'a_str should be lower case; ' + assert (message == 'a_str should be lower case; ' 'set a_str to lower case') assert_raises(*raiser) @@ -499,12 +508,13 @@ def test_logger_error(self): # Check log message appears in new logger imageglobals.logger = logger hdr.copy().check_fix() - assert_equal(str_io.getvalue(), + assert (str_io.getvalue() == 'a_str should be lower case; ' 'set a_str to lower case\n') # Check that error_level in fact causes error to be raised imageglobals.error_level = 20 - assert_raises(HeaderDataError, hdr.copy().check_fix) + with pytest.raises(HeaderDataError): + hdr.copy().check_fix() finally: imageglobals.logger, imageglobals.error_level = log_cache @@ -518,13 +528,13 @@ class MyHdr(self.header_class): _field_recoders = {} hdr = MyHdr() s1 = str(hdr) - assert_true(len(s1) > 0) - assert_true('an_integer : 1' in s1) - assert_true('fullness of heart' not in s1) + assert len(s1) > 0 + assert 'an_integer : 1' in s1 + assert 'fullness of heart' not in s1 rec = Recoder([[1, 'fullness of heart']], ('code', 'label')) hdr._field_recoders['an_integer'] = rec s2 = str(hdr) - assert_true('fullness of heart' in s2) + assert 'fullness of heart' in s2 hdr['an_integer'] = 10 s1 = str(hdr) - assert_true('' in s1) + assert '' in s1 From d65e325f876241e15f264916780bbbce3928870e Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 12 Nov 2019 09:10:14 -0500 Subject: [PATCH 002/223] converting test_b* and test_c* --- nibabel/tests/test_batteryrunners.py | 61 ++++++++------- nibabel/tests/test_brikhead.py | 30 +++---- nibabel/tests/test_casting.py | 112 ++++++++++++++------------- 3 files changed, 103 insertions(+), 100 deletions(-) diff --git a/nibabel/tests/test_batteryrunners.py b/nibabel/tests/test_batteryrunners.py index 1130c2f4cb..883054ff96 100644 --- a/nibabel/tests/test_batteryrunners.py +++ b/nibabel/tests/test_batteryrunners.py @@ -15,9 +15,7 @@ from ..batteryrunners import BatteryRunner, Report -from ..testing import (assert_true, assert_false, assert_equal, - assert_not_equal, assert_raises) - +import pytest # define some trivial functions as checks def chk1(obj, fix=False): @@ -80,64 +78,67 @@ def chk_error(obj, fix=False): def test_init_basic(): # With no args, raise - assert_raises(TypeError, BatteryRunner) + with pytest.raises(TypeError): + BatteryRunner() # Len returns number of checks battrun = BatteryRunner((chk1,)) - assert_equal(len(battrun), 1) + assert len(battrun) == 1 battrun = BatteryRunner((chk1, chk2)) - assert_equal(len(battrun), 2) + assert len(battrun) == 2 def test_init_report(): rep = Report() - assert_equal(rep, Report(Exception, 0, '', '')) + assert rep == Report(Exception, 0, '', '') def test_report_strings(): rep = Report() - assert_not_equal(rep.__str__(), '') - assert_equal(rep.message, '') + assert rep.__str__() != '' + assert rep.message == '' str_io = StringIO() rep.write_raise(str_io) - assert_equal(str_io.getvalue(), '') + assert str_io.getvalue() == '' rep = Report(ValueError, 20, 'msg', 'fix') rep.write_raise(str_io) - assert_equal(str_io.getvalue(), '') + assert str_io.getvalue() == '' rep.problem_level = 30 rep.write_raise(str_io) - assert_equal(str_io.getvalue(), 'Level 30: msg; fix\n') + assert str_io.getvalue() == 'Level 30: msg; fix\n' str_io.truncate(0) str_io.seek(0) # No fix string, no fix message rep.fix_msg = '' rep.write_raise(str_io) - assert_equal(str_io.getvalue(), 'Level 30: msg\n') + assert str_io.getvalue() == 'Level 30: msg\n' rep.fix_msg = 'fix' str_io.truncate(0) str_io.seek(0) # If we drop the level, nothing goes to the log rep.problem_level = 20 rep.write_raise(str_io) - assert_equal(str_io.getvalue(), '') + assert str_io.getvalue() == '' # Unless we set the default log level in the call rep.write_raise(str_io, log_level=20) - assert_equal(str_io.getvalue(), 'Level 20: msg; fix\n') + assert str_io.getvalue() == 'Level 20: msg; fix\n' str_io.truncate(0) str_io.seek(0) # If we set the error level down this low, we raise an error - assert_raises(ValueError, rep.write_raise, str_io, 20) + with pytest.raises(ValueError): + rep.write_raise(str_io, 20) # But the log level wasn't low enough to do a log entry - assert_equal(str_io.getvalue(), '') + assert str_io.getvalue() == '' # Error still raised with lower log threshold, but now we do get a # log entry - assert_raises(ValueError, rep.write_raise, str_io, 20, 20) - assert_equal(str_io.getvalue(), 'Level 20: msg; fix\n') + with pytest.raises(ValueError): + rep.write_raise(str_io, 20, 20) + assert str_io.getvalue() == 'Level 20: msg; fix\n' # If there's no error, we can't raise str_io.truncate(0) str_io.seek(0) rep.error = None rep.write_raise(str_io, 20) - assert_equal(str_io.getvalue(), '') + assert str_io.getvalue() == '' def test_logging(): @@ -147,10 +148,10 @@ def test_logging(): logger.setLevel(30) # defaultish level logger.addHandler(logging.StreamHandler(str_io)) rep.log_raise(logger) - assert_equal(str_io.getvalue(), '') + assert str_io.getvalue() == '' rep.problem_level = 30 rep.log_raise(logger) - assert_equal(str_io.getvalue(), 'msg; fix\n') + assert str_io.getvalue() == 'msg; fix\n' str_io.truncate(0) str_io.seek(0) @@ -158,26 +159,26 @@ def test_logging(): def test_checks(): battrun = BatteryRunner((chk1,)) reports = battrun.check_only({}) - assert_equal(reports[0], + assert (reports[0] == Report(KeyError, 20, 'no "testkey"', '')) obj, reports = battrun.check_fix({}) - assert_equal(reports[0], + assert (reports[0] == Report(KeyError, 20, 'no "testkey"', 'added "testkey"')) - assert_equal(obj, {'testkey': 1}) + assert obj == {'testkey': 1} battrun = BatteryRunner((chk1, chk2)) reports = battrun.check_only({}) - assert_equal(reports[0], + assert (reports[0] == Report(KeyError, 20, 'no "testkey"', '')) - assert_equal(reports[1], + assert (reports[1] == Report(KeyError, 20, 'no "testkey"', @@ -187,14 +188,14 @@ def test_checks(): # Note, because obj is mutable, first and second point to modified # (and final) dictionary output_obj = {'testkey': 0} - assert_equal(reports[0], + assert (reports[0] == Report(KeyError, 20, 'no "testkey"', 'added "testkey"')) - assert_equal(reports[1], + assert (reports[1] == Report(ValueError, 10, '"testkey" != 0', 'set "testkey" to 0')) - assert_equal(obj, output_obj) + assert obj == output_obj diff --git a/nibabel/tests/test_brikhead.py b/nibabel/tests/test_brikhead.py index d09023d248..078193ce48 100644 --- a/nibabel/tests/test_brikhead.py +++ b/nibabel/tests/test_brikhead.py @@ -14,9 +14,9 @@ from .. import load, Nifti1Image from .. import brikhead -from nose.tools import (assert_true, assert_equal, assert_raises) +import pytest from numpy.testing import assert_array_equal -from ..testing import data_path +from ..testing_pytest import data_path from .test_fileslice import slicer_samples from .test_helpers import assert_data_similar @@ -80,10 +80,10 @@ def test_makehead(self): for tp in self.test_files: head1 = self.module.AFNIHeader.from_fileobj(tp['head']) head2 = self.module.AFNIHeader.from_header(head1) - assert_equal(head1, head2) - with assert_raises(self.module.AFNIHeaderError): + assert head1 == head2 + with pytest.raises(self.module.AFNIHeaderError): self.module.AFNIHeader.from_header(header=None) - with assert_raises(self.module.AFNIHeaderError): + with pytest.raises(self.module.AFNIHeaderError): self.module.AFNIHeader.from_header(tp['fname']) @@ -94,22 +94,22 @@ class TestAFNIImage(object): def test_brikheadfile(self): for tp in self.test_files: brik = self.module.load(tp['fname']) - assert_equal(brik.get_data_dtype().type, tp['dtype']) - assert_equal(brik.shape, tp['shape']) - assert_equal(brik.header.get_zooms(), tp['zooms']) + assert brik.get_data_dtype().type == tp['dtype'] + assert brik.shape == tp['shape'] + assert brik.header.get_zooms() == tp['zooms'] assert_array_equal(brik.affine, tp['affine']) - assert_equal(brik.header.get_space(), tp['space']) + assert brik.header.get_space() == tp['space'] data = brik.get_fdata() - assert_equal(data.shape, tp['shape']) + assert data.shape == tp['shape'] assert_array_equal(brik.dataobj.scaling, tp['scaling']) - assert_equal(brik.header.get_volume_labels(), tp['labels']) + assert brik.header.get_volume_labels() == tp['labels'] def test_load(self): # Check highest level load of brikhead works for tp in self.test_files: img = self.module.load(tp['head']) data = img.get_fdata() - assert_equal(data.shape, tp['shape']) + assert data.shape == tp['shape'] # min, max, mean values assert_data_similar(data, tp) # check if file can be converted to nifti @@ -123,7 +123,7 @@ def test_array_proxy_slicing(self): img = self.module.load(tp['fname']) arr = img.get_fdata() prox = img.dataobj - assert_true(prox.is_proxy) + assert prox.is_proxy for sliceobj in slicer_samples(img.shape): assert_array_equal(arr[sliceobj], prox[sliceobj]) @@ -134,7 +134,7 @@ class TestBadFiles(object): def test_brikheadfile(self): for tp in self.test_files: - with assert_raises(tp['err']): + with pytest.raises(tp['err']): self.module.load(tp['head']) @@ -145,5 +145,5 @@ class TestBadVars(object): def test_unpack_var(self): for var in self.vars: - with assert_raises(self.module.AFNIHeaderError): + with pytest.raises(self.module.AFNIHeaderError): self.module._unpack_var(var) diff --git a/nibabel/tests/test_casting.py b/nibabel/tests/test_casting.py index c9d3645ad1..791cdacedb 100644 --- a/nibabel/tests/test_casting.py +++ b/nibabel/tests/test_casting.py @@ -8,11 +8,11 @@ from ..casting import (float_to_int, shared_range, CastingError, int_to_float, as_int, int_abs, floor_log2, able_int_type, best_float, ulp, longdouble_precision_improved) -from ..testing import suppress_warnings +from ..testing_pytest import suppress_warnings from numpy.testing import (assert_array_almost_equal, assert_array_equal) -from nose.tools import (assert_true, assert_false, assert_equal, assert_raises) +import pytest def test_shared_range(): @@ -35,7 +35,7 @@ def test_shared_range(): # not have an exact representation. fimax = int_to_float(imax, ft) if np.isfinite(fimax): - assert_true(int(fimax) != imax) + assert int(fimax) != imax # Therefore the imax, cast back to float, and to integer, will # overflow. If it overflows to the imax, we need to allow for # that possibility in the testing of our overflowed values @@ -43,13 +43,13 @@ def test_shared_range(): if imax_roundtrip == imax: thresh_overflow = True if thresh_overflow: - assert_true(np.all( + assert np.all( (bit_bigger == casted_mx) | - (bit_bigger == imax))) + (bit_bigger == imax)) else: - assert_true(np.all((bit_bigger <= casted_mx))) + assert np.all((bit_bigger <= casted_mx)) if it in np.sctypes['uint']: - assert_equal(mn, 0) + assert mn == 0 continue # And something larger for the minimum with suppress_warnings(): # overflow @@ -63,7 +63,7 @@ def test_shared_range(): # not have an exact representation. fimin = int_to_float(imin, ft) if np.isfinite(fimin): - assert_true(int(fimin) != imin) + assert int(fimin) != imin # Therefore the imin, cast back to float, and to integer, will # overflow. If it overflows to the imin, we need to allow for # that possibility in the testing of our overflowed values @@ -71,11 +71,11 @@ def test_shared_range(): if imin_roundtrip == imin: thresh_overflow = True if thresh_overflow: - assert_true(np.all( + assert np.all( (bit_smaller == casted_mn) | - (bit_smaller == imin))) + (bit_smaller == imin)) else: - assert_true(np.all((bit_smaller >= casted_mn))) + assert np.all((bit_smaller >= casted_mn)) def test_shared_range_inputs(): @@ -114,7 +114,8 @@ def test_casting(): im_exp[1] = ii.max assert_array_equal(iarr, im_exp) # NaNs, with nan2zero False, gives error - assert_raises(CastingError, float_to_int, farr, it, False) + with pytest.raises(CastingError): + float_to_int(farr, it, False) # We can pass through NaNs if we really want exp_arr[arr.index(np.nan)] = ft(np.nan).astype(it) with np.errstate(invalid='ignore'): @@ -130,7 +131,8 @@ def test_casting(): with np.errstate(invalid='ignore'): assert_array_equal(float_to_int(np.nan, np.int16), [0]) # Test nans give error if not nan2zero - assert_raises(CastingError, float_to_int, np.nan, np.int16, False) + with pytest.raises(CastingError): + float_to_int(np.nan, np.int16, False) def test_int_abs(): @@ -139,25 +141,25 @@ def test_int_abs(): in_arr = np.array([info.min, info.max], dtype=itype) idtype = np.dtype(itype) udtype = np.dtype(idtype.str.replace('i', 'u')) - assert_equal(udtype.kind, 'u') - assert_equal(idtype.itemsize, udtype.itemsize) + assert udtype.kind == 'u' + assert idtype.itemsize == udtype.itemsize mn, mx = in_arr e_mn = as_int(mx) + 1 # as_int needed for numpy 1.4.1 casting - assert_equal(int_abs(mx), mx) - assert_equal(int_abs(mn), e_mn) + assert int_abs(mx) == mx + assert int_abs(mn) == e_mn assert_array_equal(int_abs(in_arr), [e_mn, mx]) def test_floor_log2(): - assert_equal(floor_log2(2**9 + 1), 9) - assert_equal(floor_log2(-2**9 + 1), 8) - assert_equal(floor_log2(2), 1) - assert_equal(floor_log2(1), 0) - assert_equal(floor_log2(0.5), -1) - assert_equal(floor_log2(0.75), -1) - assert_equal(floor_log2(0.25), -2) - assert_equal(floor_log2(0.24), -3) - assert_equal(floor_log2(0), None) + assert floor_log2(2**9 + 1) == 9 + assert floor_log2(-2**9 + 1) == 8 + assert floor_log2(2) == 1 + assert floor_log2(1) == 0 + assert floor_log2(0.5) == -1 + assert floor_log2(0.75) == -1 + assert floor_log2(0.25) == -2 + assert floor_log2(0.24) == -3 + assert floor_log2(0) == None def test_able_int_type(): @@ -176,7 +178,7 @@ def test_able_int_type(): ([-1, 2**64 - 1], None), ([0, 2**64 - 1], np.uint64), ([0, 2**64], None)): - assert_equal(able_int_type(vals), exp_out) + assert able_int_type(vals) == exp_out def test_able_casting(): @@ -193,11 +195,11 @@ def test_able_casting(): ApBt = (A + B).dtype.type able_type = able_int_type([in_mn, in_mx, out_mn, out_mx]) if able_type is None: - assert_equal(ApBt, np.float64) + assert ApBt == np.float64 continue # Use str for comparison to avoid int32/64 vs intp comparison # failures - assert_equal(np.dtype(ApBt).str, np.dtype(able_type).str) + assert np.dtype(ApBt).str == np.dtype(able_type).str def test_best_float(): @@ -212,51 +214,51 @@ def test_best_float(): best = best_float() end_of_ints = np.float64(2**53) # float64 has continuous integers up to 2**53 - assert_equal(end_of_ints, end_of_ints + 1) + assert end_of_ints == end_of_ints + 1 # longdouble may have more, but not on 32 bit windows, at least end_of_ints = np.longdouble(2**53) if (end_of_ints == (end_of_ints + 1) or # off continuous integers machine() == 'sparc64' or # crippling slow longdouble on sparc longdouble_precision_improved()): # Windows precisions can change - assert_equal(best, np.float64) + assert best == np.float64 else: - assert_equal(best, np.longdouble) + assert best == np.longdouble def test_longdouble_precision_improved(): # Just check that this can only be True on windows, msvc from numpy.distutils.ccompiler import get_default_compiler if not (os.name == 'nt' and get_default_compiler() == 'msvc'): - assert_false(longdouble_precision_improved()) + assert not longdouble_precision_improved() def test_ulp(): - assert_equal(ulp(), np.finfo(np.float64).eps) - assert_equal(ulp(1.0), np.finfo(np.float64).eps) - assert_equal(ulp(np.float32(1.0)), np.finfo(np.float32).eps) - assert_equal(ulp(np.float32(1.999)), np.finfo(np.float32).eps) + assert ulp() == np.finfo(np.float64).eps + assert ulp(1.0) == np.finfo(np.float64).eps + assert ulp(np.float32(1.0)) == np.finfo(np.float32).eps + assert ulp(np.float32(1.999)) == np.finfo(np.float32).eps # Integers always return 1 - assert_equal(ulp(1), 1) - assert_equal(ulp(2**63 - 1), 1) + assert ulp(1) == 1 + assert ulp(2**63 - 1) == 1 # negative / positive same - assert_equal(ulp(-1), 1) - assert_equal(ulp(7.999), ulp(4.0)) - assert_equal(ulp(-7.999), ulp(4.0)) - assert_equal(ulp(np.float64(2**54 - 2)), 2) - assert_equal(ulp(np.float64(2**54)), 4) - assert_equal(ulp(np.float64(2**54)), 4) + assert ulp(-1) == 1 + assert ulp(7.999) == ulp(4.0) + assert ulp(-7.999) == ulp(4.0) + assert ulp(np.float64(2**54 - 2)) == 2 + assert ulp(np.float64(2**54)) == 4 + assert ulp(np.float64(2**54)) == 4 # Infs, NaNs return nan - assert_true(np.isnan(ulp(np.inf))) - assert_true(np.isnan(ulp(-np.inf))) - assert_true(np.isnan(ulp(np.nan))) + assert np.isnan(ulp(np.inf)) + assert np.isnan(ulp(-np.inf)) + assert np.isnan(ulp(np.nan)) # 0 gives subnormal smallest subn64 = np.float64(2**(-1022 - 52)) subn32 = np.float32(2**(-126 - 23)) - assert_equal(ulp(0.0), subn64) - assert_equal(ulp(np.float64(0)), subn64) - assert_equal(ulp(np.float32(0)), subn32) + assert ulp(0.0) == subn64 + assert ulp(np.float64(0)) == subn64 + assert ulp(np.float32(0)) == subn32 # as do multiples of subnormal smallest - assert_equal(ulp(subn64 * np.float64(2**52)), subn64) - assert_equal(ulp(subn64 * np.float64(2**53)), subn64 * 2) - assert_equal(ulp(subn32 * np.float32(2**23)), subn32) - assert_equal(ulp(subn32 * np.float32(2**24)), subn32 * 2) + assert ulp(subn64 * np.float64(2**52)) == subn64 + assert ulp(subn64 * np.float64(2**53)) == subn64 * 2 + assert ulp(subn32 * np.float32(2**23)) == subn32 + assert ulp(subn32 * np.float32(2**24)) == subn32 * 2 From 5f07260e00204a80ae5d4784058880f6c6e537e1 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 12 Nov 2019 09:12:29 -0500 Subject: [PATCH 003/223] updating travis --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index def7ca2369..944ec7e014 100644 --- a/.travis.yml +++ b/.travis.yml @@ -130,7 +130,7 @@ script: cd for_testing cp ../.coveragerc . nosetests --with-doctest --with-coverage --cover-package nibabel nibabel - pytest -v ../nibabel/tests/test_a*.py + pytest -v ../nibabel/tests/test_a*.py ../nibabel/tests/test_b*.py ../nibabel/tests/test_c*.py pytest -v ../nibabel/tests/test_w*.py else false From 16187e2b12229b947a8ce1d59fac9d6aa3f67595 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 12 Nov 2019 15:09:53 -0500 Subject: [PATCH 004/223] adding converted test_d* --- .travis.yml | 2 +- nibabel/tests/test_data.py | 151 ++++++++++++------------------- nibabel/tests/test_deprecated.py | 25 +++-- nibabel/tests/test_deprecator.py | 113 ++++++++++++----------- nibabel/tests/test_dft.py | 71 +++++++-------- 5 files changed, 163 insertions(+), 199 deletions(-) diff --git a/.travis.yml b/.travis.yml index 944ec7e014..63176ce581 100644 --- a/.travis.yml +++ b/.travis.yml @@ -130,7 +130,7 @@ script: cd for_testing cp ../.coveragerc . nosetests --with-doctest --with-coverage --cover-package nibabel nibabel - pytest -v ../nibabel/tests/test_a*.py ../nibabel/tests/test_b*.py ../nibabel/tests/test_c*.py + pytest -v ../nibabel/tests/test_a*.py ../nibabel/tests/test_b*.py ../nibabel/tests/test_c*.py ../nibabel/tests/test_d*.py pytest -v ../nibabel/tests/test_w*.py else false diff --git a/nibabel/tests/test_data.py b/nibabel/tests/test_data.py index 641d6e55cd..0fc0bdc40d 100644 --- a/nibabel/tests/test_data.py +++ b/nibabel/tests/test_data.py @@ -16,93 +16,80 @@ from .. import data as nibd -from nose import with_setup -from nose.tools import (assert_equal, assert_raises, raises, assert_false) +import pytest from .test_environment import (setup_environment, teardown_environment, DATA_KEY, USER_KEY) -DATA_FUNCS = {} - - -def setup_data_env(): +@pytest.fixture() +def with_environment(request): setup_environment() - global DATA_FUNCS + DATA_FUNCS = {} DATA_FUNCS['home_dir_func'] = nibd.get_nipy_user_dir DATA_FUNCS['sys_dir_func'] = nibd.get_nipy_system_dir DATA_FUNCS['path_func'] = nibd.get_data_path + def teardown_data_env(): + teardown_environment() + nibd.get_nipy_user_dir = DATA_FUNCS['home_dir_func'] + nibd.get_nipy_system_dir = DATA_FUNCS['sys_dir_func'] + nibd.get_data_path = DATA_FUNCS['path_func'] -def teardown_data_env(): - teardown_environment() - nibd.get_nipy_user_dir = DATA_FUNCS['home_dir_func'] - nibd.get_nipy_system_dir = DATA_FUNCS['sys_dir_func'] - nibd.get_data_path = DATA_FUNCS['path_func'] - - -# decorator to use setup, teardown environment -with_environment = with_setup(setup_data_env, teardown_data_env) + request.addfinalizer(teardown_data_env) def test_datasource(): # Tests for DataSource pth = pjoin('some', 'path') ds = Datasource(pth) - yield assert_equal, ds.get_filename('unlikeley'), pjoin(pth, 'unlikeley') - yield (assert_equal, ds.get_filename('un', 'like', 'ley'), - pjoin(pth, 'un', 'like', 'ley')) + assert ds.get_filename('unlikeley') == pjoin(pth, 'unlikeley') + assert ds.get_filename('un', 'like', 'ley') == pjoin(pth, 'un', 'like', 'ley') def test_versioned(): with TemporaryDirectory() as tmpdir: - yield (assert_raises, - DataError, - VersionedDatasource, - tmpdir) + with pytest.raises(DataError): + VersionedDatasource(tmpdir) tmpfile = pjoin(tmpdir, 'config.ini') # ini file, but wrong section with open(tmpfile, 'wt') as fobj: fobj.write('[SOMESECTION]\n') fobj.write('version = 0.1\n') - yield (assert_raises, - DataError, - VersionedDatasource, - tmpdir) + with pytest.raises(DataError): + VersionedDatasource(tmpdir) # ini file, but right section, wrong key with open(tmpfile, 'wt') as fobj: fobj.write('[DEFAULT]\n') fobj.write('somekey = 0.1\n') - yield (assert_raises, - DataError, - VersionedDatasource, - tmpdir) + with pytest.raises(DataError): + VersionedDatasource(tmpdir) # ini file, right section and key with open(tmpfile, 'wt') as fobj: fobj.write('[DEFAULT]\n') fobj.write('version = 0.1\n') vds = VersionedDatasource(tmpdir) - yield assert_equal, vds.version, '0.1' - yield assert_equal, vds.version_no, 0.1 - yield assert_equal, vds.major_version, 0 - yield assert_equal, vds.minor_version, 1 - yield assert_equal, vds.get_filename('config.ini'), tmpfile + assert vds.version == '0.1' + assert vds.version_no == 0.1 + assert vds.major_version == 0 + assert vds.minor_version == 1 + assert vds.get_filename('config.ini') == tmpfile # ini file, right section and key, funny value with open(tmpfile, 'wt') as fobj: fobj.write('[DEFAULT]\n') fobj.write('version = 0.1.2.dev\n') vds = VersionedDatasource(tmpdir) - yield assert_equal, vds.version, '0.1.2.dev' - yield assert_equal, vds.version_no, 0.1 - yield assert_equal, vds.major_version, 0 - yield assert_equal, vds.minor_version, 1 + assert vds.version == '0.1.2.dev' + assert vds.version_no == 0.1 + assert vds.major_version == 0 + assert vds.minor_version == 1 def test__cfg_value(): # no file, return '' - yield assert_equal, _cfg_value('/implausible_file'), '' + assert _cfg_value('/implausible_file') == '' # try files try: fd, tmpfile = tempfile.mkstemp() @@ -111,16 +98,16 @@ def test__cfg_value(): fobj.write('[strange section]\n') fobj.write('path = /some/path\n') fobj.flush() - yield assert_equal, _cfg_value(tmpfile), '' + assert _cfg_value(tmpfile) == '' # right section, wrong key fobj.write('[DATA]\n') fobj.write('funnykey = /some/path\n') fobj.flush() - yield assert_equal, _cfg_value(tmpfile), '' + assert _cfg_value(tmpfile) == '' # right section, right key fobj.write('path = /some/path\n') fobj.flush() - yield assert_equal, _cfg_value(tmpfile), '/some/path' + assert _cfg_value(tmpfile) == '/some/path' fobj.close() finally: try: @@ -129,8 +116,7 @@ def test__cfg_value(): pass -@with_environment -def test_data_path(): +def test_data_path(with_environment): # wipe out any sources of data paths if DATA_KEY in env: del env[DATA_KEY] @@ -147,15 +133,15 @@ def test_data_path(): def_dirs = [pjoin(sys.prefix, 'share', 'nipy')] if sys.prefix == '/usr': def_dirs.append(pjoin('/usr/local', 'share', 'nipy')) - assert_equal(old_pth, def_dirs + ['/user/path']) + assert old_pth == def_dirs + ['/user/path'] # then we'll try adding some of our own tst_pth = '/a/path' + os.path.pathsep + '/b/ path' tst_list = ['/a/path', '/b/ path'] # First, an environment variable os.environ[DATA_KEY] = tst_list[0] - assert_equal(get_data_path(), tst_list[:1] + old_pth) + assert get_data_path() == tst_list[:1] + old_pth os.environ[DATA_KEY] = tst_pth - assert_equal(get_data_path(), tst_list + old_pth) + assert get_data_path() == tst_list + old_pth del os.environ[DATA_KEY] # Next, make a fake user directory, and put a file in there with TemporaryDirectory() as tmpdir: @@ -164,9 +150,9 @@ def test_data_path(): fobj.write('[DATA]\n') fobj.write('path = %s' % tst_pth) nibd.get_nipy_user_dir = lambda: tmpdir - assert_equal(get_data_path(), tst_list + def_dirs + [tmpdir]) + assert get_data_path() == tst_list + def_dirs + [tmpdir] nibd.get_nipy_user_dir = lambda: fake_user_dir - assert_equal(get_data_path(), old_pth) + assert get_data_path() == old_pth # with some trepidation, the system config files with TemporaryDirectory() as tmpdir: nibd.get_nipy_system_dir = lambda: tmpdir @@ -178,7 +164,7 @@ def test_data_path(): with open(tmpfile, 'wt') as fobj: fobj.write('[DATA]\n') fobj.write('path = %s\n' % '/path/two') - assert_equal(get_data_path(), + assert (get_data_path() == tst_list + ['/path/two'] + old_pth) @@ -189,74 +175,58 @@ def test_find_data_dir(): # under_here == '/nipy/utils' # subhere = 'tests' # fails with non-existant path - yield (assert_raises, - DataError, - find_data_dir, - [here], - 'implausible', - 'directory') + with pytest.raises(DataError): + find_data_dir([here], 'implausible', 'directory') # fails with file, when directory expected - yield (assert_raises, - DataError, - find_data_dir, - [here], - fname) + with pytest.raises(DataError): + find_data_dir([here], fname) # passes with directory that exists dd = find_data_dir([under_here], subhere) - yield assert_equal, dd, here + assert dd == here # and when one path in path list does not work dud_dir = pjoin(under_here, 'implausible') dd = find_data_dir([dud_dir, under_here], subhere) - yield assert_equal, dd, here + assert dd == here -@with_environment -def test_make_datasource(): +def test_make_datasource(with_environment): pkg_def = dict( relpath='pkg') with TemporaryDirectory() as tmpdir: nibd.get_data_path = lambda: [tmpdir] - yield (assert_raises, - DataError, - make_datasource, - pkg_def) + with pytest.raises(DataError): + make_datasource(pkg_def) pkg_dir = pjoin(tmpdir, 'pkg') os.mkdir(pkg_dir) - yield (assert_raises, - DataError, - make_datasource, - pkg_def) + with pytest.raises(DataError): + make_datasource(pkg_def) tmpfile = pjoin(pkg_dir, 'config.ini') with open(tmpfile, 'wt') as fobj: fobj.write('[DEFAULT]\n') fobj.write('version = 0.1\n') ds = make_datasource(pkg_def, data_path=[tmpdir]) - yield assert_equal, ds.version, '0.1' + assert ds.version == '0.1' -@raises(DataError) def test_bomber(): - b = Bomber('bomber example', 'a message') - b.any_attribute # no error + with pytest.raises(DataError): + b = Bomber('bomber example', 'a message') + b.any_attribute # no error def test_bomber_inspect(): b = Bomber('bomber example', 'a message') - assert_false(hasattr(b, 'any_attribute')) + assert not hasattr(b, 'any_attribute') -@with_environment -def test_datasource_or_bomber(): +def test_datasource_or_bomber(with_environment): pkg_def = dict( relpath='pkg') with TemporaryDirectory() as tmpdir: nibd.get_data_path = lambda: [tmpdir] ds = datasource_or_bomber(pkg_def) - yield (assert_raises, - DataError, - getattr, - ds, - 'get_filename') + with pytest.raises(DataError): + getattr(ds, 'get_filename') pkg_dir = pjoin(tmpdir, 'pkg') os.mkdir(pkg_dir) tmpfile = pjoin(pkg_dir, 'config.ini') @@ -271,8 +241,5 @@ def test_datasource_or_bomber(): ds.get_filename('some_file.txt') pkg_def['min version'] = '0.3' ds = datasource_or_bomber(pkg_def) # not OK - yield (assert_raises, - DataError, - getattr, - ds, - 'get_filename') + with pytest.raises(DataError): + getattr(ds, 'get_filename') diff --git a/nibabel/tests/test_deprecated.py b/nibabel/tests/test_deprecated.py index 2964707717..c031a0c60d 100644 --- a/nibabel/tests/test_deprecated.py +++ b/nibabel/tests/test_deprecated.py @@ -7,7 +7,6 @@ from nibabel.deprecated import (ModuleProxy, FutureWarningMixin, deprecate_with_version) -from nose.tools import (assert_true, assert_equal) from nibabel.tests.test_deprecator import TestDeprecatorFunc as _TestDF @@ -25,9 +24,9 @@ def teardown(): def test_module_proxy(): # Test proxy for module mp = ModuleProxy('nibabel.deprecated') - assert_true(hasattr(mp, 'ModuleProxy')) - assert_true(mp.ModuleProxy is ModuleProxy) - assert_equal(repr(mp), '') + assert hasattr(mp, 'ModuleProxy') + assert mp.ModuleProxy is ModuleProxy + assert repr(mp) == '' def test_futurewarning_mixin(): @@ -47,19 +46,19 @@ class E(FutureWarningMixin, C): warn_message = "Oh no, not this one" with warnings.catch_warnings(record=True) as warns: c = C(42) - assert_equal(c.meth(), 42) - assert_equal(warns, []) + assert c.meth() == 42 + assert warns == [] d = D(42) - assert_equal(d.meth(), 42) + assert d.meth() == 42 warn = warns.pop(0) - assert_equal(warn.category, FutureWarning) - assert_equal(str(warn.message), + assert warn.category == FutureWarning + assert (str(warn.message) == 'This class will be removed in future versions') e = E(42) - assert_equal(e.meth(), 42) + assert e.meth() == 42 warn = warns.pop(0) - assert_equal(warn.category, FutureWarning) - assert_equal(str(warn.message), 'Oh no, not this one') + assert warn.category == FutureWarning + assert str(warn.message) == 'Oh no, not this one' class TestNibabelDeprecator(_TestDF): @@ -78,6 +77,6 @@ def func(): try: pkg_info.cmp_pkg_version.__defaults__ = ('2.0dev',) # No error, even though version is dev version of current - assert_equal(func(), 99) + assert func() == 99 finally: pkg_info.cmp_pkg_version.__defaults__ = ('2.0',) diff --git a/nibabel/tests/test_deprecator.py b/nibabel/tests/test_deprecator.py index c4dc2437a4..14255da4b4 100644 --- a/nibabel/tests/test_deprecator.py +++ b/nibabel/tests/test_deprecator.py @@ -5,37 +5,37 @@ import warnings from functools import partial -from nose.tools import (assert_true, assert_raises, assert_equal) +import pytest from nibabel.deprecator import (_ensure_cr, _add_dep_doc, ExpiredDeprecationError, Deprecator) -from ..testing import clear_and_catch_warnings +from ..testing_pytest import clear_and_catch_warnings _OWN_MODULE = sys.modules[__name__] def test__ensure_cr(): # Make sure text ends with carriage return - assert_equal(_ensure_cr(' foo'), ' foo\n') - assert_equal(_ensure_cr(' foo\n'), ' foo\n') - assert_equal(_ensure_cr(' foo '), ' foo\n') - assert_equal(_ensure_cr('foo '), 'foo\n') - assert_equal(_ensure_cr('foo \n bar'), 'foo \n bar\n') - assert_equal(_ensure_cr('foo \n\n'), 'foo\n') + assert _ensure_cr(' foo') == ' foo\n' + assert _ensure_cr(' foo\n') == ' foo\n' + assert _ensure_cr(' foo ') == ' foo\n' + assert _ensure_cr('foo ') == 'foo\n' + assert _ensure_cr('foo \n bar') == 'foo \n bar\n' + assert _ensure_cr('foo \n\n') == 'foo\n' def test__add_dep_doc(): # Test utility function to add deprecation message to docstring - assert_equal(_add_dep_doc('', 'foo'), 'foo\n') - assert_equal(_add_dep_doc('bar', 'foo'), 'bar\n\nfoo\n') - assert_equal(_add_dep_doc(' bar', 'foo'), ' bar\n\nfoo\n') - assert_equal(_add_dep_doc(' bar', 'foo\n'), ' bar\n\nfoo\n') - assert_equal(_add_dep_doc('bar\n\n', 'foo'), 'bar\n\nfoo\n') - assert_equal(_add_dep_doc('bar\n \n', 'foo'), 'bar\n\nfoo\n') - assert_equal(_add_dep_doc(' bar\n\nSome explanation', 'foo\nbaz'), + assert _add_dep_doc('', 'foo') == 'foo\n' + assert _add_dep_doc('bar', 'foo') == 'bar\n\nfoo\n' + assert _add_dep_doc(' bar', 'foo') == ' bar\n\nfoo\n' + assert _add_dep_doc(' bar', 'foo\n') == ' bar\n\nfoo\n' + assert _add_dep_doc('bar\n\n', 'foo') == 'bar\n\nfoo\n' + assert _add_dep_doc('bar\n \n', 'foo') == 'bar\n\nfoo\n' + assert (_add_dep_doc(' bar\n\nSome explanation', 'foo\nbaz') == ' bar\n\nfoo\nbaz\n\nSome explanation\n') - assert_equal(_add_dep_doc(' bar\n\n Some explanation', 'foo\nbaz'), + assert (_add_dep_doc(' bar\n\n Some explanation', 'foo\nbaz') == ' bar\n \n foo\n baz\n \n Some explanation\n') @@ -71,75 +71,79 @@ def test_dep_func(self): func = dec('foo')(func_no_doc) with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: warnings.simplefilter('always') - assert_equal(func(), None) - assert_equal(len(w), 1) - assert_true(w[0].category is DeprecationWarning) - assert_equal(func.__doc__, 'foo\n') + assert func() == None + assert len(w) == 1 + assert w[0].category is DeprecationWarning + assert func.__doc__ == 'foo\n' func = dec('foo')(func_doc) with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: warnings.simplefilter('always') - assert_equal(func(1), None) - assert_equal(len(w), 1) - assert_equal(func.__doc__, 'A docstring\n\nfoo\n') + assert func(1) == None + assert len(w) == 1 + assert func.__doc__ == 'A docstring\n\nfoo\n' func = dec('foo')(func_doc_long) with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: warnings.simplefilter('always') - assert_equal(func(1, 2), None) - assert_equal(len(w), 1) - assert_equal(func.__doc__, 'A docstring\n \n foo\n \n Some text\n') + assert func(1, 2) == None + assert len(w) == 1 + assert func.__doc__ == 'A docstring\n \n foo\n \n Some text\n' # Try some since and until versions func = dec('foo', '1.1')(func_no_doc) - assert_equal(func.__doc__, 'foo\n\n* deprecated from version: 1.1\n') + assert func.__doc__ == 'foo\n\n* deprecated from version: 1.1\n' with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: warnings.simplefilter('always') - assert_equal(func(), None) - assert_equal(len(w), 1) - func = dec('foo', until='2.4')(func_no_doc) + assert func() == None + assert len(w) == 1 + func = dec('foo', until='99.4')(func_no_doc) with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: warnings.simplefilter('always') - assert_equal(func(), None) - assert_equal(len(w), 1) - assert_equal(func.__doc__, - 'foo\n\n* Will raise {} as of version: 2.4\n' + assert func() == None + assert len(w) == 1 + assert (func.__doc__ == + 'foo\n\n* Will raise {} as of version: 99.4\n' .format(ExpiredDeprecationError)) func = dec('foo', until='1.8')(func_no_doc) - assert_raises(ExpiredDeprecationError, func) - assert_equal(func.__doc__, + with pytest.raises(ExpiredDeprecationError): + func() + assert (func.__doc__ == 'foo\n\n* Raises {} as of version: 1.8\n' .format(ExpiredDeprecationError)) func = dec('foo', '1.2', '1.8')(func_no_doc) - assert_raises(ExpiredDeprecationError, func) - assert_equal(func.__doc__, + with pytest.raises(ExpiredDeprecationError): + func() + assert (func.__doc__ == 'foo\n\n* deprecated from version: 1.2\n' '* Raises {} as of version: 1.8\n' .format(ExpiredDeprecationError)) func = dec('foo', '1.2', '1.8')(func_doc_long) - assert_equal(func.__doc__, + assert (func.__doc__ == 'A docstring\n \n foo\n \n' ' * deprecated from version: 1.2\n' ' * Raises {} as of version: 1.8\n \n' ' Some text\n' .format(ExpiredDeprecationError)) - assert_raises(ExpiredDeprecationError, func) + with pytest.raises(ExpiredDeprecationError): + func() # Check different warnings and errors func = dec('foo', warn_class=UserWarning)(func_no_doc) with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: warnings.simplefilter('always') - assert_equal(func(), None) - assert_equal(len(w), 1) - assert_true(w[0].category is UserWarning) + assert func() == None + assert len(w) == 1 + assert w[0].category is UserWarning func = dec('foo', error_class=CustomError)(func_no_doc) with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: warnings.simplefilter('always') - assert_equal(func(), None) - assert_equal(len(w), 1) - assert_true(w[0].category is DeprecationWarning) + assert func() == None + assert len(w) == 1 + assert w[0].category is DeprecationWarning func = dec('foo', until='1.8', error_class=CustomError)(func_no_doc) - assert_raises(CustomError, func) + with pytest.raises(CustomError): + func() class TestDeprecatorMaker(object): @@ -152,17 +156,18 @@ def test_deprecator_maker(self): func = dec('foo')(func_no_doc) with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: warnings.simplefilter('always') - assert_equal(func(), None) - assert_equal(len(w), 1) - assert_true(w[0].category is UserWarning) + assert func() == None + assert len(w) == 1 + assert w[0].category is UserWarning dec = self.dep_maker(error_class=CustomError) func = dec('foo')(func_no_doc) with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: warnings.simplefilter('always') - assert_equal(func(), None) - assert_equal(len(w), 1) - assert_true(w[0].category is DeprecationWarning) + assert func() == None + assert len(w) == 1 + assert w[0].category is DeprecationWarning func = dec('foo', until='1.8')(func_no_doc) - assert_raises(CustomError, func) + with pytest.raises(CustomError): + func() diff --git a/nibabel/tests/test_dft.py b/nibabel/tests/test_dft.py index 0285b01575..d50ba4023e 100644 --- a/nibabel/tests/test_dft.py +++ b/nibabel/tests/test_dft.py @@ -4,35 +4,28 @@ import os from os.path import join as pjoin, dirname from io import BytesIO -from ..testing import suppress_warnings - -import numpy as np +from ..testing_pytest import suppress_warnings with suppress_warnings(): from .. import dft from .. import nifti1 -from nose import SkipTest -from nose.tools import (assert_true, assert_false, assert_equal, assert_raises) +import pytest # Shield optional package imports from ..optpkg import optional_package -# setup_module will raise SkipTest if no dicom to import from nibabel.pydicom_compat import have_dicom PImage, have_pil, _ = optional_package('PIL.Image') -pil_test = np.testing.dec.skipif(not have_pil, 'could not import PIL.Image') data_dir = pjoin(dirname(__file__), 'data') -def setup_module(): - if os.name == 'nt': - raise SkipTest('FUSE not available for windows, skipping dft tests') - if not have_dicom: - raise SkipTest('Need pydicom for dft tests, skipping') - +pytestmark = [ + pytest.mark.skipif(os.name == 'nt', reason='FUSE not available for windows, skipping dft tests'), + pytest.mark.skipif(not have_dicom, reason='Need pydicom for dft tests, skipping') +] def test_init(): dft.clear_cache() @@ -41,41 +34,41 @@ def test_init(): def test_study(): studies = dft.get_studies(data_dir) - assert_equal(len(studies), 1) - assert_equal(studies[0].uid, + assert len(studies) == 1 + assert (studies[0].uid == '1.3.12.2.1107.5.2.32.35119.30000010011408520750000000022') - assert_equal(studies[0].date, '20100114') - assert_equal(studies[0].time, '121314.000000') - assert_equal(studies[0].comments, 'dft study comments') - assert_equal(studies[0].patient_name, 'dft patient name') - assert_equal(studies[0].patient_id, '1234') - assert_equal(studies[0].patient_birth_date, '19800102') - assert_equal(studies[0].patient_sex, 'F') + assert studies[0].date == '20100114' + assert studies[0].time == '121314.000000' + assert studies[0].comments == 'dft study comments' + assert studies[0].patient_name == 'dft patient name' + assert studies[0].patient_id == '1234' + assert studies[0].patient_birth_date == '19800102' + assert studies[0].patient_sex == 'F' def test_series(): studies = dft.get_studies(data_dir) - assert_equal(len(studies[0].series), 1) + assert len(studies[0].series) == 1 ser = studies[0].series[0] - assert_equal(ser.uid, + assert (ser.uid == '1.3.12.2.1107.5.2.32.35119.2010011420292594820699190.0.0.0') - assert_equal(ser.number, '12') - assert_equal(ser.description, 'CBU_DTI_64D_1A') - assert_equal(ser.rows, 256) - assert_equal(ser.columns, 256) - assert_equal(ser.bits_allocated, 16) - assert_equal(ser.bits_stored, 12) + assert ser.number == '12' + assert ser.description == 'CBU_DTI_64D_1A' + assert ser.rows == 256 + assert ser.columns == 256 + assert ser.bits_allocated == 16 + assert ser.bits_stored == 12 def test_storage_instances(): studies = dft.get_studies(data_dir) sis = studies[0].series[0].storage_instances - assert_equal(len(sis), 2) - assert_equal(sis[0].instance_number, 1) - assert_equal(sis[1].instance_number, 2) - assert_equal(sis[0].uid, + assert len(sis) == 2 + assert sis[0].instance_number == 1 + assert sis[1].instance_number == 2 + assert (sis[0].uid == '1.3.12.2.1107.5.2.32.35119.2010011420300180088599504.0') - assert_equal(sis[1].uid, + assert (sis[1].uid == '1.3.12.2.1107.5.2.32.35119.2010011420300180088599504.1') @@ -83,17 +76,17 @@ def test_storage_instance(): pass -@pil_test +@pytest.mark.skipif(not have_pil, reason='could not import PIL.Image') def test_png(): studies = dft.get_studies(data_dir) data = studies[0].series[0].as_png() im = PImage.open(BytesIO(data)) - assert_equal(im.size, (256, 256)) + assert im.size == (256, 256) def test_nifti(): studies = dft.get_studies(data_dir) data = studies[0].series[0].as_nifti() - assert_equal(len(data), 352 + 2 * 256 * 256 * 2) + assert len(data) == 352 + 2 * 256 * 256 * 2 h = nifti1.Nifti1Header(data[:348]) - assert_equal(h.get_data_shape(), (256, 256, 2)) + assert h.get_data_shape() == (256, 256, 2) From 4ee404b63e4a9314a3ee3e3b3b27dc26a20b0281 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Fri, 15 Nov 2019 14:41:30 -0500 Subject: [PATCH 005/223] converting more tests to pytest --- nibabel/tests/test_ecat.py | 94 ++--- nibabel/tests/test_ecat_data.py | 7 +- nibabel/tests/test_endiancodes.py | 24 +- nibabel/tests/test_environment.py | 52 +-- nibabel/tests/test_euler.py | 86 ++-- nibabel/tests/test_filebasedimages.py | 21 +- nibabel/tests/test_filehandles.py | 4 - nibabel/tests/test_fileholders.py | 45 +-- nibabel/tests/test_filename_parser.py | 81 ++-- nibabel/tests/test_files_interface.py | 32 +- nibabel/tests/test_fileslice.py | 556 +++++++++++++------------- nibabel/tests/test_fileutils.py | 23 +- nibabel/tests/test_floating.py | 156 ++++---- nibabel/tests/test_funcs.py | 42 +- nibabel/tests/test_h5py_compat.py | 21 +- nibabel/tests/test_helpers.py | 7 +- 16 files changed, 614 insertions(+), 637 deletions(-) diff --git a/nibabel/tests/test_ecat.py b/nibabel/tests/test_ecat.py index a3a40b2904..b681a59b0e 100644 --- a/nibabel/tests/test_ecat.py +++ b/nibabel/tests/test_ecat.py @@ -17,11 +17,11 @@ get_frame_order, get_series_framenumbers) from unittest import TestCase -from nose.tools import (assert_true, assert_false, assert_equal, assert_raises) +import pytest from numpy.testing import assert_array_equal, assert_array_almost_equal -from ..testing import data_path, suppress_warnings, clear_and_catch_warnings +from ..testing_pytest import data_path, suppress_warnings, clear_and_catch_warnings from ..tmpdirs import InTemporaryDirectory from .test_wrapstruct import _TestWrapStructBase @@ -35,16 +35,16 @@ class TestEcatHeader(_TestWrapStructBase): example_file = ecat_file def test_header_size(self): - assert_equal(self.header_class.template_dtype.itemsize, 512) + assert self.header_class.template_dtype.itemsize == 512 def test_empty(self): hdr = self.header_class() - assert_true(len(hdr.binaryblock) == 512) - assert_true(hdr['magic_number'] == b'MATRIX72') - assert_true(hdr['sw_version'] == 74) - assert_true(hdr['num_frames'] == 0) - assert_true(hdr['file_type'] == 0) - assert_true(hdr['ecat_calibration_factor'] == 1.0) + assert len(hdr.binaryblock) == 512 + assert hdr['magic_number'] == b'MATRIX72' + assert hdr['sw_version'] == 74 + assert hdr['num_frames'] == 0 + assert hdr['file_type'] == 0 + assert hdr['ecat_calibration_factor'] == 1.0 def _set_something_into_hdr(self, hdr): # Called from test_bytes test method. Specific to the header data type @@ -53,28 +53,29 @@ def _set_something_into_hdr(self, hdr): def test_dtype(self): # dtype not specified in header, only in subheaders hdr = self.header_class() - assert_raises(NotImplementedError, hdr.get_data_dtype) + with pytest.raises(NotImplementedError): + hdr.get_data_dtype() def test_header_codes(self): fid = open(ecat_file, 'rb') hdr = self.header_class() newhdr = hdr.from_fileobj(fid) fid.close() - assert_true(newhdr.get_filetype() == 'ECAT7_VOLUME16') - assert_equal(newhdr.get_patient_orient(), + assert newhdr.get_filetype() == 'ECAT7_VOLUME16' + assert (newhdr.get_patient_orient() == 'ECAT7_Unknown_Orientation') def test_update(self): hdr = self.header_class() - assert_true(hdr['num_frames'] == 0) + assert hdr['num_frames'] == 0 hdr['num_frames'] = 2 - assert_true(hdr['num_frames'] == 2) + assert hdr['num_frames'] == 2 def test_from_eg_file(self): # Example header is big-endian with Opener(self.example_file) as fileobj: hdr = self.header_class.from_fileobj(fileobj, check=False) - assert_equal(hdr.endianness, '>') + assert hdr.endianness == '>' class TestEcatMlist(TestCase): @@ -93,9 +94,9 @@ def test_mlist(self): mats = np.recarray(shape=(32, 4), dtype=dt, buf=dat) fid.close() # tests - assert_true(mats['matlist'][0, 0] + mats['matlist'][0, 3] == 31) - assert_true(get_frame_order(mlist)[0][0] == 0) - assert_true(get_frame_order(mlist)[0][1] == 16842758.0) + assert mats['matlist'][0, 0] + mats['matlist'][0, 3] == 31 + assert get_frame_order(mlist)[0][0] == 0 + assert get_frame_order(mlist)[0][1] == 16842758.0 # test badly ordered mlist badordermlist = np.array([[1.68427540e+07, 3.00000000e+00, 1.20350000e+04, 1.00000000e+00], @@ -110,7 +111,7 @@ def test_mlist(self): [1.68427580e+07, 6.01680000e+04, 7.22000000e+04, 1.00000000e+00]]) with suppress_warnings(): # STORED order - assert_true(get_frame_order(badordermlist)[0][0] == 1) + assert get_frame_order(badordermlist)[0][0] == 1 def test_mlist_errors(self): fid = open(self.example_file, 'rb') @@ -132,17 +133,18 @@ def test_mlist_errors(self): with suppress_warnings(): # STORED order series_framenumbers = get_series_framenumbers(mlist) # first frame stored was actually 2nd frame acquired - assert_true(series_framenumbers[0] == 2) + assert series_framenumbers[0] == 2 order = [series_framenumbers[x] for x in sorted(series_framenumbers)] # true series order is [2,1,3,4,5,6], note counting starts at 1 - assert_true(order == [2, 1, 3, 4, 5, 6]) + assert order == [2, 1, 3, 4, 5, 6] mlist[0, 0] = 0 with suppress_warnings(): frames_order = get_frame_order(mlist) neworder = [frames_order[x][0] for x in sorted(frames_order)] - assert_true(neworder == [1, 2, 3, 4, 5]) + assert neworder == [1, 2, 3, 4, 5] with suppress_warnings(): - assert_raises(IOError, get_series_framenumbers, mlist) + with pytest.raises(IOError): + get_series_framenumbers(mlist) class TestEcatSubHeader(TestCase): @@ -155,26 +157,26 @@ class TestEcatSubHeader(TestCase): subhdr = subhdr_class(hdr, mlist, fid) def test_subheader_size(self): - assert_equal(self.subhdr_class._subhdrdtype.itemsize, 510) + assert self.subhdr_class._subhdrdtype.itemsize == 510 def test_subheader(self): - assert_equal(self.subhdr.get_shape(), (10, 10, 3)) - assert_equal(self.subhdr.get_nframes(), 1) - assert_equal(self.subhdr.get_nframes(), + assert self.subhdr.get_shape() == (10, 10, 3) + assert self.subhdr.get_nframes() == 1 + assert (self.subhdr.get_nframes() == len(self.subhdr.subheaders)) - assert_equal(self.subhdr._check_affines(), True) + assert self.subhdr._check_affines() == True assert_array_almost_equal(np.diag(self.subhdr.get_frame_affine()), np.array([2.20241979, 2.20241979, 3.125, 1.])) - assert_equal(self.subhdr.get_zooms()[0], 2.20241978764534) - assert_equal(self.subhdr.get_zooms()[2], 3.125) - assert_equal(self.subhdr._get_data_dtype(0), np.int16) + assert self.subhdr.get_zooms()[0] == 2.20241978764534 + assert self.subhdr.get_zooms()[2] == 3.125 + assert self.subhdr._get_data_dtype(0) == np.int16 #assert_equal(self.subhdr._get_frame_offset(), 1024) - assert_equal(self.subhdr._get_frame_offset(), 1536) + assert self.subhdr._get_frame_offset() == 1536 dat = self.subhdr.raw_data_from_fileobj() - assert_equal(dat.shape, self.subhdr.get_shape()) - assert_equal(self.subhdr.subheaders[0]['scale_factor'].item(), 1.0) + assert dat.shape == self.subhdr.get_shape() + assert self.subhdr.subheaders[0]['scale_factor'].item() == 1.0 ecat_calib_factor = self.hdr['ecat_calibration_factor'] - assert_equal(ecat_calib_factor, 25007614.0) + assert ecat_calib_factor == 25007614.0 class TestEcatImage(TestCase): @@ -183,9 +185,9 @@ class TestEcatImage(TestCase): img = image_class.load(example_file) def test_file(self): - assert_equal(self.img.file_map['header'].filename, + assert (self.img.file_map['header'].filename == self.example_file) - assert_equal(self.img.file_map['image'].filename, + assert (self.img.file_map['image'].filename == self.example_file) def test_save(self): @@ -200,7 +202,7 @@ def test_save(self): def test_data(self): dat = self.img.get_fdata() - assert_equal(dat.shape, self.img.shape) + assert dat.shape == self.img.shape frame = self.img.get_frame(0) assert_array_equal(frame, dat[:, :, :, 0]) @@ -220,7 +222,7 @@ def test_array_proxy_slicing(self): # Test slicing of array proxy arr = self.img.get_fdata() prox = self.img.dataobj - assert_true(prox.is_proxy) + assert prox.is_proxy for sliceobj in slicer_samples(self.img.shape): assert_array_equal(arr[sliceobj], prox[sliceobj]) @@ -235,7 +237,7 @@ def test_isolation(self): img = img_klass(arr, aff, hdr, sub_hdr, mlist) assert_array_equal(img.affine, aff) aff[0, 0] = 99 - assert_false(np.all(img.affine == aff)) + assert not np.all(img.affine == aff) def test_float_affine(self): # Check affines get converted to float @@ -246,9 +248,9 @@ def test_float_affine(self): self.img.get_subheaders(), self.img.get_mlist()) img = img_klass(arr, aff.astype(np.float32), hdr, sub_hdr, mlist) - assert_equal(img.get_affine().dtype, np.dtype(np.float64)) + assert img.get_affine().dtype == np.dtype(np.float64) img = img_klass(arr, aff.astype(np.int16), hdr, sub_hdr, mlist) - assert_equal(img.get_affine().dtype, np.dtype(np.float64)) + assert img.get_affine().dtype == np.dtype(np.float64) def test_data_regression(self): # Test whether data read has changed since 1.3.0 @@ -257,8 +259,8 @@ def test_data_regression(self): min=1125342630.0, mean=117907565661.46666) data = self.img.get_fdata() - assert_equal(data.max(), vals['max']) - assert_equal(data.min(), vals['min']) + assert data.max() == vals['max'] + assert data.min() == vals['min'] assert_array_almost_equal(data.mean(), vals['mean']) def test_mlist_regression(self): @@ -273,8 +275,8 @@ def test_from_filespec_deprecation(): warnings.simplefilter('always', DeprecationWarning) # No warning for standard load img_loaded = EcatImage.load(ecat_file) - assert_equal(len(w), 0) + assert len(w) == 0 # Warning for from_filespec img_speced = EcatImage.from_filespec(ecat_file) - assert_equal(len(w), 1) + assert len(w) == 1 assert_array_equal(img_loaded.get_fdata(), img_speced.get_fdata()) diff --git a/nibabel/tests/test_ecat_data.py b/nibabel/tests/test_ecat_data.py index 4b187bf855..1accd01a14 100644 --- a/nibabel/tests/test_ecat_data.py +++ b/nibabel/tests/test_ecat_data.py @@ -17,7 +17,6 @@ from .nibabel_data import get_nibabel_data, needs_nibabel_data from ..ecat import load -from nose.tools import assert_equal from numpy.testing import (assert_array_equal, assert_almost_equal) ECAT_TEST_PATH = pjoin(get_nibabel_data(), 'nipy-ecattest') @@ -40,11 +39,11 @@ class TestNegatives(object): def test_load(self): # Check highest level load of minc works img = self.opener(self.example_params['fname']) - assert_equal(img.shape, self.example_params['shape']) - assert_equal(img.get_data_dtype(0).type, self.example_params['type']) + assert img.shape == self.example_params['shape'] + assert img.get_data_dtype(0).type == self.example_params['type'] # Check correspondence of data and recorded shape data = img.get_fdata() - assert_equal(data.shape, self.example_params['shape']) + assert data.shape == self.example_params['shape'] # min, max, mean values from given parameters assert_almost_equal(data.min(), self.example_params['min'], 4) assert_almost_equal(data.max(), self.example_params['max'], 4) diff --git a/nibabel/tests/test_endiancodes.py b/nibabel/tests/test_endiancodes.py index 805de0d572..94c9ea0344 100644 --- a/nibabel/tests/test_endiancodes.py +++ b/nibabel/tests/test_endiancodes.py @@ -10,31 +10,27 @@ import sys - -from nose.tools import assert_equal -from nose.tools import assert_true - from ..volumeutils import (endian_codes, native_code, swapped_code) def test_native_swapped(): native_is_le = sys.byteorder == 'little' if native_is_le: - assert_equal((native_code, swapped_code), ('<', '>')) + assert (native_code, swapped_code) == ('<', '>') else: - assert_equal((native_code, swapped_code), ('>', '<')) + assert (native_code, swapped_code) == ('>', '<') def test_to_numpy(): if sys.byteorder == 'little': - yield assert_true, endian_codes['native'] == '<' - yield assert_true, endian_codes['swapped'] == '>' + assert endian_codes['native'] == '<' + assert endian_codes['swapped'] == '>' else: - yield assert_true, endian_codes['native'] == '>' - yield assert_true, endian_codes['swapped'] == '<' - yield assert_true, endian_codes['native'] == endian_codes['='] - yield assert_true, endian_codes['big'] == '>' + assert endian_codes['native'] == '>' + assert endian_codes['swapped'] == '<' + assert endian_codes['native'] == endian_codes['='] + assert endian_codes['big'] == '>' for code in ('little', '<', 'l', 'L', 'le'): - yield assert_true, endian_codes[code] == '<' + assert endian_codes[code] == '<' for code in ('big', '>', 'b', 'B', 'be'): - yield assert_true, endian_codes[code] == '>' + assert endian_codes[code] == '>' diff --git a/nibabel/tests/test_environment.py b/nibabel/tests/test_environment.py index 7b02ea866f..6dc127c95f 100644 --- a/nibabel/tests/test_environment.py +++ b/nibabel/tests/test_environment.py @@ -8,52 +8,44 @@ from .. import environment as nibe -from numpy.testing import (assert_array_almost_equal, - assert_array_equal) +import pytest -from nose.tools import assert_equal - -from nose import with_setup - -GIVEN_ENV = {} DATA_KEY = 'NIPY_DATA_PATH' USER_KEY = 'NIPY_USER_DIR' -def setup_environment(): +@pytest.fixture() +def with_environment(request): """Setup test environment for some functions that are tested in this module. In particular this functions stores attributes and other things that we need to stub in some test functions. This needs to be done on a function level and not module level because each testfunction needs a pristine environment. """ - global GIVEN_ENV + GIVEN_ENV = {} GIVEN_ENV['env'] = env.copy() -def teardown_environment(): - """Restore things that were remembered by the setup_environment function - """ - orig_env = GIVEN_ENV['env'] - # Pull keys out into list to avoid altering dictionary during iteration, - # causing python 3 error - for key in list(env.keys()): - if key not in orig_env: - del env[key] - env.update(orig_env) - + def teardown_environment(): + """Restore things that were remembered by the setup_environment function + """ + orig_env = GIVEN_ENV['env'] + # Pull keys out into list to avoid altering dictionary during iteration, + # causing python 3 error + for key in list(env.keys()): + if key not in orig_env: + del env[key] + env.update(orig_env) -# decorator to use setup, teardown environment -with_environment = with_setup(setup_environment, teardown_environment) + request.addfinalizer(teardown_environment) def test_nipy_home(): # Test logic for nipy home directory - assert_equal(nibe.get_home_dir(), os.path.expanduser('~')) + assert nibe.get_home_dir() == os.path.expanduser('~') -@with_environment -def test_user_dir(): +def test_user_dir(with_environment): if USER_KEY in env: del env[USER_KEY] home_dir = nibe.get_home_dir() @@ -61,16 +53,16 @@ def test_user_dir(): exp = pjoin(home_dir, '.nipy') else: exp = pjoin(home_dir, '_nipy') - assert_equal(exp, nibe.get_nipy_user_dir()) + assert exp == nibe.get_nipy_user_dir() env[USER_KEY] = '/a/path' - assert_equal(abspath('/a/path'), nibe.get_nipy_user_dir()) + assert abspath('/a/path') == nibe.get_nipy_user_dir() def test_sys_dir(): sys_dir = nibe.get_nipy_system_dir() if os.name == 'nt': - assert_equal(sys_dir, r'C:\etc\nipy') + assert sys_dir == r'C:\etc\nipy' elif os.name == 'posix': - assert_equal(sys_dir, r'/etc/nipy') + assert sys_dir == r'/etc/nipy' else: - assert_equal(sys_dir, None) + assert sys_dir == None diff --git a/nibabel/tests/test_euler.py b/nibabel/tests/test_euler.py index 0d7027222f..915e65e552 100644 --- a/nibabel/tests/test_euler.py +++ b/nibabel/tests/test_euler.py @@ -15,9 +15,7 @@ from .. import eulerangles as nea from .. import quaternions as nq -from nose.tools import assert_false -from nose.tools import assert_true - +import pytest from numpy.testing import assert_array_equal, assert_array_almost_equal FLOAT_EPS = np.finfo(np.float).eps @@ -90,36 +88,38 @@ def test_basic_euler(): M2 = nea.euler2mat(0, yr) M3 = nea.euler2mat(0, 0, xr) # which are all valid rotation matrices - yield assert_true, is_valid_rotation(M) - yield assert_true, is_valid_rotation(M1) - yield assert_true, is_valid_rotation(M2) - yield assert_true, is_valid_rotation(M3) + assert is_valid_rotation(M) + assert is_valid_rotation(M1) + assert is_valid_rotation(M2) + assert is_valid_rotation(M3) # Full matrix is composition of three individual matrices - yield assert_true, np.allclose(M, np.dot(M3, np.dot(M2, M1))) + assert np.allclose(M, np.dot(M3, np.dot(M2, M1))) # Rotations can be specified with named args, default 0 - yield assert_true, np.all(nea.euler2mat(zr) == nea.euler2mat(z=zr)) - yield assert_true, np.all(nea.euler2mat(0, yr) == nea.euler2mat(y=yr)) - yield assert_true, np.all(nea.euler2mat(0, 0, xr) == nea.euler2mat(x=xr)) + assert np.all(nea.euler2mat(zr) == nea.euler2mat(z=zr)) + assert np.all(nea.euler2mat(0, yr) == nea.euler2mat(y=yr)) + assert np.all(nea.euler2mat(0, 0, xr) == nea.euler2mat(x=xr)) # Applying an opposite rotation same as inverse (the inverse is # the same as the transpose, but just for clarity) - yield assert_true, np.allclose(nea.euler2mat(x=-xr), + assert np.allclose(nea.euler2mat(x=-xr), np.linalg.inv(nea.euler2mat(x=xr))) -def test_euler_mat(): +def test_euler_mat_1(): M = nea.euler2mat() - yield assert_array_equal, M, np.eye(3) - for x, y, z in eg_rots: - M1 = nea.euler2mat(z, y, x) - M2 = sympy_euler(z, y, x) - yield assert_array_almost_equal, M1, M2 - M3 = np.dot(x_only(x), np.dot(y_only(y), z_only(z))) - yield assert_array_almost_equal, M1, M3 - zp, yp, xp = nea.mat2euler(M1) - # The parameters may not be the same as input, but they give the - # same rotation matrix - M4 = nea.euler2mat(zp, yp, xp) - yield assert_array_almost_equal, M1, M4 + assert_array_equal(M, np.eye(3)) + +@pytest.mark.parametrize("x, y, z", eg_rots) +def test_euler_mat_2(x, y, z): + M1 = nea.euler2mat(z, y, x) + M2 = sympy_euler(z, y, x) + assert_array_almost_equal(M1, M2) + M3 = np.dot(x_only(x), np.dot(y_only(y), z_only(z))) + assert_array_almost_equal(M1, M3) + zp, yp, xp = nea.mat2euler(M1) + # The parameters may not be the same as input, but they give the + # same rotation matrix + M4 = nea.euler2mat(zp, yp, xp) + assert_array_almost_equal(M1, M4) def sympy_euler2quat(z=0, y=0, x=0): @@ -148,27 +148,27 @@ def test_euler_instability(): M = nea.euler2mat(*zyx) # Round trip M_back = nea.euler2mat(*nea.mat2euler(M)) - yield assert_true, np.allclose(M, M_back) + assert np.allclose(M, M_back) # disturb matrix slightly M_e = M - FLOAT_EPS # round trip to test - OK M_e_back = nea.euler2mat(*nea.mat2euler(M_e)) - yield assert_true, np.allclose(M_e, M_e_back) + assert np.allclose(M_e, M_e_back) # not so with crude routine M_e_back = nea.euler2mat(*crude_mat2euler(M_e)) - yield assert_false, np.allclose(M_e, M_e_back) - - -def test_quats(): - for x, y, z in eg_rots: - M1 = nea.euler2mat(z, y, x) - quatM = nq.mat2quat(M1) - quat = nea.euler2quat(z, y, x) - yield nq.nearly_equivalent, quatM, quat - quatS = sympy_euler2quat(z, y, x) - yield nq.nearly_equivalent, quat, quatS - zp, yp, xp = nea.quat2euler(quat) - # The parameters may not be the same as input, but they give the - # same rotation matrix - M2 = nea.euler2mat(zp, yp, xp) - yield assert_array_almost_equal, M1, M2 + assert not np.allclose(M_e, M_e_back) + + +@pytest.mark.parametrize("x, y, z", eg_rots) +def test_quats(x, y, z): + M1 = nea.euler2mat(z, y, x) + quatM = nq.mat2quat(M1) + quat = nea.euler2quat(z, y, x) + assert nq.nearly_equivalent(quatM, quat) + quatS = sympy_euler2quat(z, y, x) + assert nq.nearly_equivalent(quat, quatS) + zp, yp, xp = nea.quat2euler(quat) + # The parameters may not be the same as input, but they give the + # same rotation matrix + M2 = nea.euler2mat(zp, yp, xp) + assert_array_almost_equal(M1, M2) diff --git a/nibabel/tests/test_filebasedimages.py b/nibabel/tests/test_filebasedimages.py index a9c5668508..efac76a65a 100644 --- a/nibabel/tests/test_filebasedimages.py +++ b/nibabel/tests/test_filebasedimages.py @@ -10,9 +10,6 @@ from .test_image_api import GenericImageAPI, SerializeMixin -from nose.tools import (assert_true, assert_false, assert_equal, - assert_not_equal) - class FBNumpyImage(FileBasedImage): header_class = FileBasedHeader @@ -113,20 +110,20 @@ def __init__(self, seq=None): in_list = [1, 3, 2] hdr = H(in_list) hdr_c = hdr.copy() - assert_equal(hdr_c.a_list, hdr.a_list) + assert hdr_c.a_list == hdr.a_list # Copy is independent of original hdr_c.a_list[0] = 99 - assert_not_equal(hdr_c.a_list, hdr.a_list) + assert hdr_c.a_list != hdr.a_list # From header does a copy hdr2 = H.from_header(hdr) - assert_true(isinstance(hdr2, H)) - assert_equal(hdr2.a_list, hdr.a_list) + assert isinstance(hdr2, H) + assert hdr2.a_list == hdr.a_list hdr2.a_list[0] = 42 - assert_not_equal(hdr2.a_list, hdr.a_list) + assert hdr2.a_list != hdr.a_list # Default header input to from_heder gives new empty header hdr3 = H.from_header() - assert_true(isinstance(hdr3, H)) - assert_equal(hdr3.a_list, []) + assert isinstance(hdr3, H) + assert hdr3.a_list == [] hdr4 = H.from_header(None) - assert_true(isinstance(hdr4, H)) - assert_equal(hdr4.a_list, []) + assert isinstance(hdr4, H) + assert hdr4.a_list == [] diff --git a/nibabel/tests/test_filehandles.py b/nibabel/tests/test_filehandles.py index 1533b7c4f8..23ae573a70 100644 --- a/nibabel/tests/test_filehandles.py +++ b/nibabel/tests/test_filehandles.py @@ -20,10 +20,6 @@ from ..loadsave import load, save from ..nifti1 import Nifti1Image -from numpy.testing import (assert_array_almost_equal, - assert_array_equal) - - def test_multiload(): # Make a tiny image, save, load many times. If we are leaking filehandles, diff --git a/nibabel/tests/test_fileholders.py b/nibabel/tests/test_fileholders.py index b28727a47e..e31a6efcbc 100644 --- a/nibabel/tests/test_fileholders.py +++ b/nibabel/tests/test_fileholders.py @@ -6,56 +6,49 @@ from ..fileholders import FileHolder -from numpy.testing import (assert_array_almost_equal, - assert_array_equal) - -from nose.tools import assert_equal -from nose.tools import assert_false -from nose.tools import assert_true - def test_init(): fh = FileHolder('a_fname') - assert_equal(fh.filename, 'a_fname') - assert_true(fh.fileobj is None) - assert_equal(fh.pos, 0) + assert fh.filename == 'a_fname' + assert fh.fileobj is None + assert fh.pos == 0 sio0 = BytesIO() fh = FileHolder('a_test', sio0) - assert_equal(fh.filename, 'a_test') - assert_true(fh.fileobj is sio0) - assert_equal(fh.pos, 0) + assert fh.filename == 'a_test' + assert fh.fileobj is sio0 + assert fh.pos == 0 fh = FileHolder('a_test_2', sio0, 3) - assert_equal(fh.filename, 'a_test_2') - assert_true(fh.fileobj is sio0) - assert_equal(fh.pos, 3) + assert fh.filename == 'a_test_2' + assert fh.fileobj is sio0 + assert fh.pos == 3 def test_same_file_as(): fh = FileHolder('a_fname') - assert_true(fh.same_file_as(fh)) + assert fh.same_file_as(fh) fh2 = FileHolder('a_test') - assert_false(fh.same_file_as(fh2)) + assert not fh.same_file_as(fh2) sio0 = BytesIO() fh3 = FileHolder('a_fname', sio0) fh4 = FileHolder('a_fname', sio0) - assert_true(fh3.same_file_as(fh4)) - assert_false(fh3.same_file_as(fh)) + assert fh3.same_file_as(fh4) + assert not fh3.same_file_as(fh) fh5 = FileHolder(fileobj=sio0) fh6 = FileHolder(fileobj=sio0) - assert_true(fh5.same_file_as(fh6)) + assert fh5.same_file_as(fh6) # Not if the filename is the same - assert_false(fh5.same_file_as(fh3)) + assert not fh5.same_file_as(fh3) # pos doesn't matter fh4_again = FileHolder('a_fname', sio0, pos=4) - assert_true(fh3.same_file_as(fh4_again)) + assert fh3.same_file_as(fh4_again) def test_file_like(): # Test returning file object or filename fh = FileHolder('a_fname') - assert_equal(fh.file_like, 'a_fname') + assert fh.file_like == 'a_fname' bio = BytesIO() fh = FileHolder(fileobj=bio) - assert_true(fh.file_like is bio) + assert fh.file_like is bio fh = FileHolder('a_fname', fileobj=bio) - assert_true(fh.file_like is bio) + assert fh.file_like is bio diff --git a/nibabel/tests/test_filename_parser.py b/nibabel/tests/test_filename_parser.py index f7317ac183..22178a4349 100644 --- a/nibabel/tests/test_filename_parser.py +++ b/nibabel/tests/test_filename_parser.py @@ -11,58 +11,53 @@ from ..filename_parser import (types_filenames, TypesFilenamesError, parse_filename, splitext_addext) -from nose.tools import (assert_equal, assert_true, assert_false, - assert_raises) +import pytest def test_filenames(): types_exts = (('image', '.img'), ('header', '.hdr')) for t_fname in ('test.img', 'test.hdr', 'test', 'test.'): tfns = types_filenames(t_fname, types_exts) - assert_equal(tfns, + assert (tfns == {'image': 'test.img', 'header': 'test.hdr'}) # enforcing extensions raises an error for bad extension - assert_raises(TypesFilenamesError, - types_filenames, - 'test.funny', - types_exts) + with pytest.raises(TypesFilenamesError): + types_filenames('test.funny', types_exts) # If not enforcing extensions, it does the best job it can, # assuming the passed filename is for the first type (in this case # 'image') tfns = types_filenames('test.funny', types_exts, enforce_extensions=False) - assert_equal(tfns, + assert (tfns == {'header': 'test.hdr', 'image': 'test.funny'}) # .gz and .bz2 suffixes to extensions, by default, are removed # before extension checking etc, and then put back onto every # returned filename. tfns = types_filenames('test.img.gz', types_exts) - assert_equal(tfns, + assert (tfns == {'header': 'test.hdr.gz', 'image': 'test.img.gz'}) tfns = types_filenames('test.img.bz2', types_exts) - assert_equal(tfns, + assert (tfns == {'header': 'test.hdr.bz2', 'image': 'test.img.bz2'}) # of course, if we don't know about e.g. gz, and enforce_extensions # is on, we get an errror - assert_raises(TypesFilenamesError, - types_filenames, - 'test.img.gz', - types_exts, ()) + with pytest.raises(TypesFilenamesError): + types_filenames('test.img.gz', types_exts, ()) # if we don't know about .gz extension, and not enforcing, then we # get something a bit odd tfns = types_filenames('test.img.gz', types_exts, trailing_suffixes=(), enforce_extensions=False) - assert_equal(tfns, + assert (tfns == {'header': 'test.img.hdr', 'image': 'test.img.gz'}) # the suffixes we remove and replaces can be any suffixes. tfns = types_filenames('test.img.bzr', types_exts, ('.bzr',)) - assert_equal(tfns, + assert (tfns == {'header': 'test.hdr.bzr', 'image': 'test.img.bzr'}) # If we specifically pass the remove / replace suffixes, then we @@ -71,37 +66,33 @@ def test_filenames(): tfns = types_filenames('test.img.bzr', types_exts, trailing_suffixes=('.bzr',), enforce_extensions=False) - assert_equal(tfns, + assert (tfns == {'header': 'test.hdr.bzr', 'image': 'test.img.bzr'}) # but, just .gz or .bz2 as extension gives an error, if enforcing is on - assert_raises(TypesFilenamesError, - types_filenames, - 'test.gz', - types_exts) - assert_raises(TypesFilenamesError, - types_filenames, - 'test.bz2', - types_exts) + with pytest.raises(TypesFilenamesError): + types_filenames('test.gz', types_exts) + with pytest.raises(TypesFilenamesError): + types_filenames('test.bz2', types_exts) # if enforcing is off, it tries to work out what the other files # should be assuming the passed filename is of the first input type tfns = types_filenames('test.gz', types_exts, enforce_extensions=False) - assert_equal(tfns, + assert (tfns == {'image': 'test.gz', 'header': 'test.hdr.gz'}) # case (in)sensitivity, and effect of uppercase, lowercase tfns = types_filenames('test.IMG', types_exts) - assert_equal(tfns, + assert (tfns == {'image': 'test.IMG', 'header': 'test.HDR'}) tfns = types_filenames('test.img', (('image', '.IMG'), ('header', '.HDR'))) - assert_equal(tfns, + assert (tfns == {'header': 'test.hdr', 'image': 'test.img'}) tfns = types_filenames('test.IMG.Gz', types_exts) - assert_equal(tfns, + assert (tfns == {'image': 'test.IMG.Gz', 'header': 'test.HDR.Gz'}) @@ -121,52 +112,52 @@ def test_parse_filename(): for inps, exps in exp_in_outs: pth, sufs = inps res = parse_filename(pth, types_exts, sufs) - assert_equal(res, exps) + assert res == exps upth = pth.upper() uexps = (exps[0].upper(), exps[1].upper(), exps[2].upper() if exps[2] else None, exps[3]) res = parse_filename(upth, types_exts, sufs) - assert_equal(res, uexps) + assert res == uexps # test case sensitivity res = parse_filename('/path/fnameext2.GZ', types_exts, ('.gz',), False) # case insensitive again - assert_equal(res, ('/path/fname', 'ext2', '.GZ', 't2')) + assert res == ('/path/fname', 'ext2', '.GZ', 't2') res = parse_filename('/path/fnameext2.GZ', types_exts, ('.gz',), True) # case sensitive - assert_equal(res, ('/path/fnameext2', '.GZ', None, None)) + assert res == ('/path/fnameext2', '.GZ', None, None) res = parse_filename('/path/fnameEXT2.gz', types_exts, ('.gz',), False) # case insensitive - assert_equal(res, ('/path/fname', 'EXT2', '.gz', 't2')) + assert res == ('/path/fname', 'EXT2', '.gz', 't2') res = parse_filename('/path/fnameEXT2.gz', types_exts, ('.gz',), True) # case sensitive - assert_equal(res, ('/path/fnameEXT2', '', '.gz', None)) + assert res == ('/path/fnameEXT2', '', '.gz', None) def test_splitext_addext(): res = splitext_addext('fname.ext.gz') - assert_equal(res, ('fname', '.ext', '.gz')) + assert res == ('fname', '.ext', '.gz') res = splitext_addext('fname.ext') - assert_equal(res, ('fname', '.ext', '')) + assert res == ('fname', '.ext', '') res = splitext_addext('fname.ext.foo', ('.foo', '.bar')) - assert_equal(res, ('fname', '.ext', '.foo')) + assert res == ('fname', '.ext', '.foo') res = splitext_addext('fname.ext.FOO', ('.foo', '.bar')) - assert_equal(res, ('fname', '.ext', '.FOO')) + assert res == ('fname', '.ext', '.FOO') # case sensitive res = splitext_addext('fname.ext.FOO', ('.foo', '.bar'), True) - assert_equal(res, ('fname.ext', '.FOO', '')) + assert res == ('fname.ext', '.FOO', '') # edge cases res = splitext_addext('.nii') - assert_equal(res, ('', '.nii', '')) + assert res == ('', '.nii', '') res = splitext_addext('...nii') - assert_equal(res, ('..', '.nii', '')) + assert res == ('..', '.nii', '') res = splitext_addext('.') - assert_equal(res, ('.', '', '')) + assert res == ('.', '', '') res = splitext_addext('..') - assert_equal(res, ('..', '', '')) + assert res == ('..', '', '') res = splitext_addext('...') - assert_equal(res, ('...', '', '')) + assert res == ('...', '', '') diff --git a/nibabel/tests/test_files_interface.py b/nibabel/tests/test_files_interface.py index 1994741a1a..a75484159e 100644 --- a/nibabel/tests/test_files_interface.py +++ b/nibabel/tests/test_files_interface.py @@ -17,10 +17,8 @@ from ..fileholders import FileHolderError from ..spatialimages import SpatialImage -from nose.tools import (assert_true, assert_false, assert_equal, assert_raises) - from numpy.testing import assert_array_equal - +import pytest def test_files_spatialimages(): # test files creation in image classes @@ -31,9 +29,9 @@ def test_files_spatialimages(): for klass in klasses: file_map = klass.make_file_map() for key, value in file_map.items(): - assert_equal(value.filename, None) - assert_equal(value.fileobj, None) - assert_equal(value.pos, 0) + assert value.filename == None + assert value.fileobj == None + assert value.pos == 0 # If we can't create new images in memory without loading, bail here if not klass.makeable: continue @@ -44,9 +42,9 @@ def test_files_spatialimages(): else: img = klass(arr, aff) for key, value in img.file_map.items(): - assert_equal(value.filename, None) - assert_equal(value.fileobj, None) - assert_equal(value.pos, 0) + assert value.filename == None + assert value.fileobj == None + assert value.pos == 0 def test_files_interface(): @@ -56,15 +54,16 @@ def test_files_interface(): img = Nifti1Image(arr, aff) # single image img.set_filename('test') - assert_equal(img.get_filename(), 'test.nii') - assert_equal(img.file_map['image'].filename, 'test.nii') - assert_raises(KeyError, img.file_map.__getitem__, 'header') + assert img.get_filename() == 'test.nii' + assert img.file_map['image'].filename == 'test.nii' + with pytest.raises(KeyError): + img.file_map.__getitem__('header') # pair - note new class img = Nifti1Pair(arr, aff) img.set_filename('test') - assert_equal(img.get_filename(), 'test.img') - assert_equal(img.file_map['image'].filename, 'test.img') - assert_equal(img.file_map['header'].filename, 'test.hdr') + assert img.get_filename() == 'test.img' + assert img.file_map['image'].filename == 'test.img' + assert img.file_map['header'].filename == 'test.hdr' # fileobjs - single image img = Nifti1Image(arr, aff) img.file_map['image'].fileobj = BytesIO() @@ -76,7 +75,8 @@ def test_files_interface(): img = Nifti1Pair(arr, aff) img.file_map['image'].fileobj = BytesIO() # no header yet - assert_raises(FileHolderError, img.to_file_map) + with pytest.raises(FileHolderError): + img.to_file_map() img.file_map['header'].fileobj = BytesIO() img.to_file_map() # saves to files img2 = Nifti1Pair.from_file_map(img.file_map) diff --git a/nibabel/tests/test_fileslice.py b/nibabel/tests/test_fileslice.py index 19735200eb..5c80ae01b5 100644 --- a/nibabel/tests/test_fileslice.py +++ b/nibabel/tests/test_fileslice.py @@ -1,11 +1,9 @@ """ Test slicing of file-like objects """ -import sys from io import BytesIO from itertools import product from functools import partial -from distutils.version import LooseVersion from threading import Thread, Lock import time @@ -18,10 +16,7 @@ calc_slicedefs, _simple_fileslice, slice2outax, strided_scalar) -from nose.tools import assert_equal -from nose.tools import assert_false -from nose.tools import assert_raises - +import pytest from numpy.testing import assert_array_equal @@ -34,7 +29,7 @@ def _check_slice(sliceobj): # Check if this is a view a[:] = 99 b_is_view = np.all(b == 99) - assert_equal(not is_fancy(sliceobj), b_is_view) + assert (not is_fancy(sliceobj)) == b_is_view def test_is_fancy(): @@ -48,11 +43,11 @@ def test_is_fancy(): if maybe_bad and slice1 is Ellipsis: continue _check_slice((slice0, slice1)) - assert_false(is_fancy((None,))) - assert_false(is_fancy((None, 1))) - assert_false(is_fancy((1, None))) + assert not is_fancy((None,)) + assert not is_fancy((None, 1)) + assert not is_fancy((1, None)) # Chack that actual False returned (rather than falsey) - assert_equal(is_fancy(1), False) + assert is_fancy(1) == False def test_canonical_slicers(): @@ -65,90 +60,96 @@ def test_canonical_slicers(): 2) shape = (10, 10) for slice0 in slicers: - assert_equal(canonical_slicers((slice0,), shape), (slice0, slice(None))) + assert canonical_slicers((slice0,), shape) == (slice0, slice(None)) for slice1 in slicers: sliceobj = (slice0, slice1) - assert_equal(canonical_slicers(sliceobj, shape), sliceobj) - assert_equal(canonical_slicers(sliceobj, shape + (2, 3, 4)), + assert canonical_slicers(sliceobj, shape) == sliceobj + assert (canonical_slicers(sliceobj, shape + (2, 3, 4)) == sliceobj + (slice(None),) * 3) - assert_equal(canonical_slicers(sliceobj * 3, shape * 3), + assert (canonical_slicers(sliceobj * 3, shape * 3) == sliceobj * 3) # Check None passes through - assert_equal(canonical_slicers(sliceobj + (None,), shape), + assert (canonical_slicers(sliceobj + (None,), shape) == sliceobj + (None,)) - assert_equal(canonical_slicers((None,) + sliceobj, shape), + assert (canonical_slicers((None,) + sliceobj, shape) == (None,) + sliceobj) - assert_equal(canonical_slicers((None,) + sliceobj + (None,), shape), + assert (canonical_slicers((None,) + sliceobj + (None,), shape) == (None,) + sliceobj + (None,)) # Check Ellipsis - assert_equal(canonical_slicers((Ellipsis,), shape), + assert (canonical_slicers((Ellipsis,), shape) == (slice(None), slice(None))) - assert_equal(canonical_slicers((Ellipsis, None), shape), + assert (canonical_slicers((Ellipsis, None), shape) == (slice(None), slice(None), None)) - assert_equal(canonical_slicers((Ellipsis, 1), shape), + assert (canonical_slicers((Ellipsis, 1), shape) == (slice(None), 1)) - assert_equal(canonical_slicers((1, Ellipsis), shape), + assert (canonical_slicers((1, Ellipsis), shape) == (1, slice(None))) # Ellipsis at end does nothing - assert_equal(canonical_slicers((1, 1, Ellipsis), shape), + assert (canonical_slicers((1, 1, Ellipsis), shape) == (1, 1)) - assert_equal(canonical_slicers((1, Ellipsis, 2), (10, 1, 2, 3, 11)), + assert (canonical_slicers((1, Ellipsis, 2), (10, 1, 2, 3, 11)) == (1, slice(None), slice(None), slice(None), 2)) - assert_raises(ValueError, - canonical_slicers, (Ellipsis, 1, Ellipsis), (2, 3, 4, 5)) + with pytest.raises(ValueError): + canonical_slicers((Ellipsis, 1, Ellipsis), (2, 3, 4, 5)) # Check full slices get expanded for slice0 in (slice(10), slice(0, 10), slice(0, 10, 1)): - assert_equal(canonical_slicers((slice0, 1), shape), + assert (canonical_slicers((slice0, 1), shape) == (slice(None), 1)) for slice0 in (slice(10), slice(0, 10), slice(0, 10, 1)): - assert_equal(canonical_slicers((slice0, 1), shape), + assert (canonical_slicers((slice0, 1), shape) == (slice(None), 1)) - assert_equal(canonical_slicers((1, slice0), shape), + assert (canonical_slicers((1, slice0), shape) == (1, slice(None))) # Check ints etc get parsed through to tuples - assert_equal(canonical_slicers(1, shape), (1, slice(None))) - assert_equal(canonical_slicers(slice(None), shape), + assert canonical_slicers(1, shape) == (1, slice(None)) + assert (canonical_slicers(slice(None), shape) == (slice(None), slice(None))) # Check fancy indexing raises error - assert_raises(ValueError, canonical_slicers, (np.array(1), 1), shape) - assert_raises(ValueError, canonical_slicers, (1, np.array(1)), shape) + with pytest.raises(ValueError): + canonical_slicers((np.array(1), 1), shape) + with pytest.raises(ValueError): + canonical_slicers((1, np.array(1)), shape) # Check out of range integer raises error - assert_raises(ValueError, canonical_slicers, (10,), shape) - assert_raises(ValueError, canonical_slicers, (1, 10), shape) - assert_raises(ValueError, canonical_slicers, (10,), shape, True) - assert_raises(ValueError, canonical_slicers, (1, 10), shape, True) + with pytest.raises(ValueError): + canonical_slicers((10,), shape) + with pytest.raises(ValueError): + canonical_slicers((1, 10), shape) + with pytest.raises(ValueError): + canonical_slicers((10,), shape, True) + with pytest.raises(ValueError): + canonical_slicers((1, 10), shape, True) # Unless check_inds is False - assert_equal(canonical_slicers((10,), shape, False), (10, slice(None))) - assert_equal(canonical_slicers((1, 10,), shape, False), (1, 10)) + assert canonical_slicers((10,), shape, False) == (10, slice(None)) + assert canonical_slicers((1, 10,), shape, False) == (1, 10) # Check negative -> positive - assert_equal(canonical_slicers(-1, shape), (9, slice(None))) - assert_equal(canonical_slicers((slice(None), -1), shape), (slice(None), 9)) + assert canonical_slicers(-1, shape) == (9, slice(None)) + assert canonical_slicers((slice(None), -1), shape) == (slice(None), 9) def test_slice2outax(): # Test function giving output axes from input ndims and slice sn = slice(None) - assert_equal(slice2outax(1, (sn,)), (0,)) - assert_equal(slice2outax(1, (1,)), (None,)) - assert_equal(slice2outax(1, (None,)), (1,)) - assert_equal(slice2outax(1, (None, 1)), (None,)) - assert_equal(slice2outax(1, (None, 1, None)), (None,)) - assert_equal(slice2outax(1, (None, sn)), (1,)) - assert_equal(slice2outax(2, (sn,)), (0, 1)) - assert_equal(slice2outax(2, (sn, sn)), (0, 1)) - assert_equal(slice2outax(2, (1,)), (None, 0)) - assert_equal(slice2outax(2, (sn, 1)), (0, None)) - assert_equal(slice2outax(2, (None,)), (1, 2)) - assert_equal(slice2outax(2, (None, 1)), (None, 1)) - assert_equal(slice2outax(2, (None, 1, None)), (None, 2)) - assert_equal(slice2outax(2, (None, 1, None, 2)), (None, None)) - assert_equal(slice2outax(2, (None, sn, None, 1)), (1, None)) - assert_equal(slice2outax(3, (sn,)), (0, 1, 2)) - assert_equal(slice2outax(3, (sn, sn)), (0, 1, 2)) - assert_equal(slice2outax(3, (sn, None, sn)), (0, 2, 3)) - assert_equal(slice2outax(3, (sn, None, sn, None, sn)), (0, 2, 4)) - assert_equal(slice2outax(3, (1,)), (None, 0, 1)) - assert_equal(slice2outax(3, (None, sn, None, 1)), (1, None, 3)) + assert slice2outax(1, (sn,)) == (0,) + assert slice2outax(1, (1,)) == (None,) + assert slice2outax(1, (None,)) == (1,) + assert slice2outax(1, (None, 1)) == (None,) + assert slice2outax(1, (None, 1, None)) == (None,) + assert slice2outax(1, (None, sn)) == (1,) + assert slice2outax(2, (sn,)) == (0, 1) + assert slice2outax(2, (sn, sn)) == (0, 1) + assert slice2outax(2, (1,)) == (None, 0) + assert slice2outax(2, (sn, 1)) == (0, None) + assert slice2outax(2, (None,)) == (1, 2) + assert slice2outax(2, (None, 1)) == (None, 1) + assert slice2outax(2, (None, 1, None)) == (None, 2) + assert slice2outax(2, (None, 1, None, 2)) == (None, None) + assert slice2outax(2, (None, sn, None, 1)) == (1, None) + assert slice2outax(3, (sn,)) == (0, 1, 2) + assert slice2outax(3, (sn, sn)) == (0, 1, 2) + assert slice2outax(3, (sn, None, sn)) == (0, 2, 3) + assert slice2outax(3, (sn, None, sn, None, sn)) == (0, 2, 4) + assert slice2outax(3, (1,)) == (None, 0, 1) + assert slice2outax(3, (None, sn, None, 1)) == (1, None, 3) def _slices_for_len(L): @@ -174,108 +175,108 @@ def _slices_for_len(L): def test_slice2len(): # Test slice length calculation - assert_equal(slice2len(slice(None), 10), 10) - assert_equal(slice2len(slice(11), 10), 10) - assert_equal(slice2len(slice(1, 11), 10), 9) - assert_equal(slice2len(slice(1, 1), 10), 0) - assert_equal(slice2len(slice(1, 11, 2), 10), 5) - assert_equal(slice2len(slice(0, 11, 3), 10), 4) - assert_equal(slice2len(slice(1, 11, 3), 10), 3) - assert_equal(slice2len(slice(None, None, -1), 10), 10) - assert_equal(slice2len(slice(11, None, -1), 10), 10) - assert_equal(slice2len(slice(None, 1, -1), 10), 8) - assert_equal(slice2len(slice(None, None, -2), 10), 5) - assert_equal(slice2len(slice(None, None, -3), 10), 4) - assert_equal(slice2len(slice(None, 0, -3), 10), 3) + assert slice2len(slice(None), 10) == 10 + assert slice2len(slice(11), 10) == 10 + assert slice2len(slice(1, 11), 10) == 9 + assert slice2len(slice(1, 1), 10) == 0 + assert slice2len(slice(1, 11, 2), 10) == 5 + assert slice2len(slice(0, 11, 3), 10) == 4 + assert slice2len(slice(1, 11, 3), 10) == 3 + assert slice2len(slice(None, None, -1), 10) == 10 + assert slice2len(slice(11, None, -1), 10) == 10 + assert slice2len(slice(None, 1, -1), 10) == 8 + assert slice2len(slice(None, None, -2), 10) == 5 + assert slice2len(slice(None, None, -3), 10) == 4 + assert slice2len(slice(None, 0, -3), 10) == 3 # Start, end are always taken to be relative if negative - assert_equal(slice2len(slice(None, -4, -1), 10), 3) - assert_equal(slice2len(slice(-4, -2, 1), 10), 2) + assert slice2len(slice(None, -4, -1), 10) == 3 + assert slice2len(slice(-4, -2, 1), 10) == 2 # start after stop - assert_equal(slice2len(slice(3, 2, 1), 10), 0) - assert_equal(slice2len(slice(2, 3, -1), 10), 0) + assert slice2len(slice(3, 2, 1), 10) == 0 + assert slice2len(slice(2, 3, -1), 10) == 0 def test_fill_slicer(): # Test slice length calculation - assert_equal(fill_slicer(slice(None), 10), slice(0, 10, 1)) - assert_equal(fill_slicer(slice(11), 10), slice(0, 10, 1)) - assert_equal(fill_slicer(slice(1, 11), 10), slice(1, 10, 1)) - assert_equal(fill_slicer(slice(1, 1), 10), slice(1, 1, 1)) - assert_equal(fill_slicer(slice(1, 11, 2), 10), slice(1, 10, 2)) - assert_equal(fill_slicer(slice(0, 11, 3), 10), slice(0, 10, 3)) - assert_equal(fill_slicer(slice(1, 11, 3), 10), slice(1, 10, 3)) - assert_equal(fill_slicer(slice(None, None, -1), 10), + assert fill_slicer(slice(None), 10) == slice(0, 10, 1) + assert fill_slicer(slice(11), 10) == slice(0, 10, 1) + assert fill_slicer(slice(1, 11), 10) == slice(1, 10, 1) + assert fill_slicer(slice(1, 1), 10) == slice(1, 1, 1) + assert fill_slicer(slice(1, 11, 2), 10) == slice(1, 10, 2) + assert fill_slicer(slice(0, 11, 3), 10) == slice(0, 10, 3) + assert fill_slicer(slice(1, 11, 3), 10) == slice(1, 10, 3) + assert (fill_slicer(slice(None, None, -1), 10) == slice(9, None, -1)) - assert_equal(fill_slicer(slice(11, None, -1), 10), + assert (fill_slicer(slice(11, None, -1), 10) == slice(9, None, -1)) - assert_equal(fill_slicer(slice(None, 1, -1), 10), + assert (fill_slicer(slice(None, 1, -1), 10) == slice(9, 1, -1)) - assert_equal(fill_slicer(slice(None, None, -2), 10), + assert (fill_slicer(slice(None, None, -2), 10) == slice(9, None, -2)) - assert_equal(fill_slicer(slice(None, None, -3), 10), + assert (fill_slicer(slice(None, None, -3), 10) == slice(9, None, -3)) - assert_equal(fill_slicer(slice(None, 0, -3), 10), + assert (fill_slicer(slice(None, 0, -3), 10) == slice(9, 0, -3)) # Start, end are always taken to be relative if negative - assert_equal(fill_slicer(slice(None, -4, -1), 10), + assert (fill_slicer(slice(None, -4, -1), 10) == slice(9, 6, -1)) - assert_equal(fill_slicer(slice(-4, -2, 1), 10), + assert (fill_slicer(slice(-4, -2, 1), 10) == slice(6, 8, 1)) # start after stop - assert_equal(fill_slicer(slice(3, 2, 1), 10), + assert (fill_slicer(slice(3, 2, 1), 10) == slice(3, 2, 1)) - assert_equal(fill_slicer(slice(2, 3, -1), 10), + assert (fill_slicer(slice(2, 3, -1), 10) == slice(2, 3, -1)) def test__positive_slice(): # Reverse slice direction to be positive - assert_equal(_positive_slice(slice(0, 5, 1)), slice(0, 5, 1)) - assert_equal(_positive_slice(slice(1, 5, 3)), slice(1, 5, 3)) - assert_equal(_positive_slice(slice(4, None, -2)), slice(0, 5, 2)) - assert_equal(_positive_slice(slice(4, None, -1)), slice(0, 5, 1)) - assert_equal(_positive_slice(slice(4, 1, -1)), slice(2, 5, 1)) - assert_equal(_positive_slice(slice(4, 1, -2)), slice(2, 5, 2)) + assert _positive_slice(slice(0, 5, 1)) == slice(0, 5, 1) + assert _positive_slice(slice(1, 5, 3)) == slice(1, 5, 3) + assert _positive_slice(slice(4, None, -2)) == slice(0, 5, 2) + assert _positive_slice(slice(4, None, -1)) == slice(0, 5, 1) + assert _positive_slice(slice(4, 1, -1)) == slice(2, 5, 1) + assert _positive_slice(slice(4, 1, -2)) == slice(2, 5, 2) def test_threshold_heuristic(): # Test for default skip / read heuristic # int - assert_equal(threshold_heuristic(1, 9, 1, skip_thresh=8), 'full') - assert_equal(threshold_heuristic(1, 9, 1, skip_thresh=7), None) - assert_equal(threshold_heuristic(1, 9, 2, skip_thresh=16), 'full') - assert_equal(threshold_heuristic(1, 9, 2, skip_thresh=15), None) + assert threshold_heuristic(1, 9, 1, skip_thresh=8) == 'full' + assert threshold_heuristic(1, 9, 1, skip_thresh=7) == None + assert threshold_heuristic(1, 9, 2, skip_thresh=16) == 'full' + assert threshold_heuristic(1, 9, 2, skip_thresh=15) == None # full slice, smallest step size - assert_equal(threshold_heuristic( - slice(0, 9, 1), 9, 2, skip_thresh=2), + assert (threshold_heuristic( + slice(0, 9, 1), 9, 2, skip_thresh=2) == 'full') # Dropping skip thresh below step size gives None - assert_equal(threshold_heuristic( - slice(0, 9, 1), 9, 2, skip_thresh=1), + assert (threshold_heuristic( + slice(0, 9, 1), 9, 2, skip_thresh=1) == None) # As does increasing step size - assert_equal(threshold_heuristic( - slice(0, 9, 2), 9, 2, skip_thresh=3), + assert (threshold_heuristic( + slice(0, 9, 2), 9, 2, skip_thresh=3) == None) # Negative step size same as positive - assert_equal(threshold_heuristic( - slice(9, None, -1), 9, 2, skip_thresh=2), + assert (threshold_heuristic( + slice(9, None, -1), 9, 2, skip_thresh=2) == 'full') # Add a gap between start and end. Now contiguous because of step size - assert_equal(threshold_heuristic( - slice(2, 9, 1), 9, 2, skip_thresh=2), + assert (threshold_heuristic( + slice(2, 9, 1), 9, 2, skip_thresh=2) == 'contiguous') # To not-contiguous, even with step size 1 - assert_equal(threshold_heuristic( - slice(2, 9, 1), 9, 2, skip_thresh=1), + assert (threshold_heuristic( + slice(2, 9, 1), 9, 2, skip_thresh=1) == None) # Back to full when skip covers gap - assert_equal(threshold_heuristic( - slice(2, 9, 1), 9, 2, skip_thresh=4), + assert (threshold_heuristic( + slice(2, 9, 1), 9, 2, skip_thresh=4) == 'full') # Until it doesn't cover the gap - assert_equal(threshold_heuristic( - slice(2, 9, 1), 9, 2, skip_thresh=3), + assert (threshold_heuristic( + slice(2, 9, 1), 9, 2, skip_thresh=3) == 'contiguous') @@ -307,226 +308,233 @@ def test_optimize_slicer(): for is_slowest in (True, False): # following tests not affected by all_full or optimization # full - always passes through - assert_equal( - optimize_slicer(slice(None), 10, all_full, 4, heuristic), + assert ( + optimize_slicer(slice(None), 10, all_full, 4, heuristic) == (slice(None), slice(None))) # Even if full specified with explicit values - assert_equal( - optimize_slicer(slice(10), 10, all_full, 4, heuristic), + assert ( + optimize_slicer(slice(10), 10, all_full, 4, heuristic) == (slice(None), slice(None))) - assert_equal( - optimize_slicer(slice(0, 10), 10, all_full, 4, heuristic), + assert ( + optimize_slicer(slice(0, 10), 10, all_full, 4, heuristic) == (slice(None), slice(None))) - assert_equal( - optimize_slicer(slice(0, 10, 1), 10, all_full, 4, heuristic), + assert ( + optimize_slicer(slice(0, 10, 1), 10, all_full, 4, heuristic) == (slice(None), slice(None))) # Reversed full is still full, but with reversed post_slice - assert_equal( + assert ( optimize_slicer( - slice(None, None, -1), 10, all_full, 4, heuristic), + slice(None, None, -1), 10, all_full, 4, heuristic) == (slice(None), slice(None, None, -1))) # Contiguous is contiguous unless heuristic kicks in, in which case it may # be 'full' - assert_equal( - optimize_slicer(slice(9), 10, False, False, 4, _always), + assert ( + optimize_slicer(slice(9), 10, False, False, 4, _always) == (slice(0, 9, 1), slice(None))) - assert_equal( - optimize_slicer(slice(9), 10, True, False, 4, _always), + assert ( + optimize_slicer(slice(9), 10, True, False, 4, _always) == (slice(None), slice(0, 9, 1))) # Unless this is the slowest dimenion, and all_true is True, in which case # we don't update to full - assert_equal( - optimize_slicer(slice(9), 10, True, True, 4, _always), + assert ( + optimize_slicer(slice(9), 10, True, True, 4, _always) == (slice(0, 9, 1), slice(None))) # Nor if the heuristic won't update - assert_equal( - optimize_slicer(slice(9), 10, True, False, 4, _never), + assert ( + optimize_slicer(slice(9), 10, True, False, 4, _never) == (slice(0, 9, 1), slice(None))) - assert_equal( - optimize_slicer(slice(1, 10), 10, True, False, 4, _never), + assert ( + optimize_slicer(slice(1, 10), 10, True, False, 4, _never) == (slice(1, 10, 1), slice(None))) # Reversed contiguous still contiguous - assert_equal( - optimize_slicer(slice(8, None, -1), 10, False, False, 4, _never), + assert ( + optimize_slicer(slice(8, None, -1), 10, False, False, 4, _never) == (slice(0, 9, 1), slice(None, None, -1))) - assert_equal( - optimize_slicer(slice(8, None, -1), 10, True, False, 4, _always), + assert ( + optimize_slicer(slice(8, None, -1), 10, True, False, 4, _always) == (slice(None), slice(8, None, -1))) - assert_equal( - optimize_slicer(slice(8, None, -1), 10, False, False, 4, _never), + assert ( + optimize_slicer(slice(8, None, -1), 10, False, False, 4, _never) == (slice(0, 9, 1), slice(None, None, -1))) - assert_equal( - optimize_slicer(slice(9, 0, -1), 10, False, False, 4, _never), + assert ( + optimize_slicer(slice(9, 0, -1), 10, False, False, 4, _never) == (slice(1, 10, 1), slice(None, None, -1))) # Non-contiguous - assert_equal( - optimize_slicer(slice(0, 10, 2), 10, False, False, 4, _never), + assert ( + optimize_slicer(slice(0, 10, 2), 10, False, False, 4, _never) == (slice(0, 10, 2), slice(None))) # all_full triggers optimization, but optimization does nothing - assert_equal( - optimize_slicer(slice(0, 10, 2), 10, True, False, 4, _never), + assert ( + optimize_slicer(slice(0, 10, 2), 10, True, False, 4, _never) == (slice(0, 10, 2), slice(None))) # all_full triggers optimization, optimization does something - assert_equal( - optimize_slicer(slice(0, 10, 2), 10, True, False, 4, _always), + assert ( + optimize_slicer(slice(0, 10, 2), 10, True, False, 4, _always) == (slice(None), slice(0, 10, 2))) # all_full disables optimization, optimization does something - assert_equal( - optimize_slicer(slice(0, 10, 2), 10, False, False, 4, _always), + assert ( + optimize_slicer(slice(0, 10, 2), 10, False, False, 4, _always) == (slice(0, 10, 2), slice(None))) # Non contiguous, reversed - assert_equal( - optimize_slicer(slice(10, None, -2), 10, False, False, 4, _never), + assert ( + optimize_slicer(slice(10, None, -2), 10, False, False, 4, _never) == (slice(1, 10, 2), slice(None, None, -1))) - assert_equal( - optimize_slicer(slice(10, None, -2), 10, True, False, 4, _always), + assert ( + optimize_slicer(slice(10, None, -2), 10, True, False, 4, _always) == (slice(None), slice(9, None, -2))) # Short non-contiguous - assert_equal( - optimize_slicer(slice(2, 8, 2), 10, False, False, 4, _never), + assert ( + optimize_slicer(slice(2, 8, 2), 10, False, False, 4, _never) == (slice(2, 8, 2), slice(None))) # with partial read - assert_equal( - optimize_slicer(slice(2, 8, 2), 10, True, False, 4, _partial), + assert ( + optimize_slicer(slice(2, 8, 2), 10, True, False, 4, _partial) == (slice(2, 8, 1), slice(None, None, 2))) # If this is the slowest changing dimension, heuristic can upgrade None to # contiguous, but not (None, contiguous) to full - assert_equal( # we've done this one already - optimize_slicer(slice(0, 10, 2), 10, True, False, 4, _always), - (slice(None), slice(0, 10, 2))) - assert_equal( # if slowest, just upgrade to contiguous - optimize_slicer(slice(0, 10, 2), 10, True, True, 4, _always), + # we've done this one already + assert optimize_slicer(slice(0, 10, 2), 10, True, False, 4, _always) \ + == (slice(None), slice(0, 10, 2)) + # if slowest, just upgrade to contiguous + assert ( + optimize_slicer(slice(0, 10, 2), 10, True, True, 4, _always) == (slice(0, 10, 1), slice(None, None, 2))) - assert_equal( # contiguous does not upgrade to full - optimize_slicer(slice(9), 10, True, True, 4, _always), + # contiguous does not upgrade to full + assert ( + optimize_slicer(slice(9), 10, True, True, 4, _always) == (slice(0, 9, 1), slice(None))) # integer - assert_equal( - optimize_slicer(0, 10, True, False, 4, _never), + assert ( + optimize_slicer(0, 10, True, False, 4, _never) == (0, 'dropped')) - assert_equal( # can be negative - optimize_slicer(-1, 10, True, False, 4, _never), + # can be negative + assert ( + optimize_slicer(-1, 10, True, False, 4, _never) == (9, 'dropped')) - assert_equal( # or float - optimize_slicer(0.9, 10, True, False, 4, _never), + # or float + assert ( + optimize_slicer(0.9, 10, True, False, 4, _never) == (0, 'dropped')) - assert_raises(ValueError, # should never get 'contiguous' - optimize_slicer, 0, 10, True, False, 4, _partial) - assert_equal( # full can be forced with heuristic - optimize_slicer(0, 10, True, False, 4, _always), + # should never get 'contiguous' + with pytest.raises(ValueError): + optimize_slicer(0, 10, True, False, 4, _partial) + # full can be forced with heuristic + assert ( + optimize_slicer(0, 10, True, False, 4, _always) == (slice(None), 0)) - assert_equal( # but disabled for slowest changing dimension - optimize_slicer(0, 10, True, True, 4, _always), + # but disabled for slowest changing dimension + assert ( + optimize_slicer(0, 10, True, True, 4, _always) == (0, 'dropped')) def test_optimize_read_slicers(): # Test function to optimize read slicers - assert_equal(optimize_read_slicers((1,), (10,), 4, _never), + assert (optimize_read_slicers((1,), (10,), 4, _never) == ((1,), ())) - assert_equal(optimize_read_slicers((slice(None),), (10,), 4, _never), + assert (optimize_read_slicers((slice(None),), (10,), 4, _never) == ((slice(None),), (slice(None),))) - assert_equal(optimize_read_slicers((slice(9),), (10,), 4, _never), + assert (optimize_read_slicers((slice(9),), (10,), 4, _never) == ((slice(0, 9, 1),), (slice(None),))) # optimize cannot update a continuous to a full if last - assert_equal(optimize_read_slicers((slice(9),), (10,), 4, _always), + assert (optimize_read_slicers((slice(9),), (10,), 4, _always) == ((slice(0, 9, 1),), (slice(None),))) # optimize can update non-contiguous to continuous even if last # not optimizing - assert_equal(optimize_read_slicers((slice(0, 9, 2),), (10,), 4, _never), + assert (optimize_read_slicers((slice(0, 9, 2),), (10,), 4, _never) == ((slice(0, 9, 2),), (slice(None),))) # optimizing - assert_equal(optimize_read_slicers((slice(0, 9, 2),), (10,), 4, _always), + assert (optimize_read_slicers((slice(0, 9, 2),), (10,), 4, _always) == ((slice(0, 9, 1),), (slice(None, None, 2),))) # Optimize does nothing for integer when last - assert_equal(optimize_read_slicers((1,), (10,), 4, _always), + assert (optimize_read_slicers((1,), (10,), 4, _always) == ((1,), ())) # 2D - assert_equal(optimize_read_slicers( - (slice(None), slice(None)), (10, 6), 4, _never), + assert (optimize_read_slicers( + (slice(None), slice(None)), (10, 6), 4, _never) == ((slice(None), slice(None)), (slice(None), slice(None)))) - assert_equal(optimize_read_slicers((slice(None), 1), (10, 6), 4, _never), + assert (optimize_read_slicers((slice(None), 1), (10, 6), 4, _never) == ((slice(None), 1), (slice(None),))) - assert_equal(optimize_read_slicers((1, slice(None)), (10, 6), 4, _never), + assert (optimize_read_slicers((1, slice(None)), (10, 6), 4, _never) == ((1, slice(None)), (slice(None),))) # Not optimizing a partial slice - assert_equal(optimize_read_slicers( - (slice(9), slice(None)), (10, 6), 4, _never), + assert (optimize_read_slicers( + (slice(9), slice(None)), (10, 6), 4, _never) == ((slice(0, 9, 1), slice(None)), (slice(None), slice(None)))) # Optimizing a partial slice - assert_equal(optimize_read_slicers( - (slice(9), slice(None)), (10, 6), 4, _always), + assert (optimize_read_slicers( + (slice(9), slice(None)), (10, 6), 4, _always) == ((slice(None), slice(None)), (slice(0, 9, 1), slice(None)))) # Optimize cannot update a continuous to a full if last - assert_equal(optimize_read_slicers( - (slice(None), slice(5)), (10, 6), 4, _always), + assert (optimize_read_slicers( + (slice(None), slice(5)), (10, 6), 4, _always) == ((slice(None), slice(0, 5, 1)), (slice(None), slice(None)))) # optimize can update non-contiguous to full if not last # not optimizing - assert_equal(optimize_read_slicers( - (slice(0, 9, 3), slice(None)), (10, 6), 4, _never), + assert (optimize_read_slicers( + (slice(0, 9, 3), slice(None)), (10, 6), 4, _never) == ((slice(0, 9, 3), slice(None)), (slice(None), slice(None)))) # optimizing full - assert_equal(optimize_read_slicers( - (slice(0, 9, 3), slice(None)), (10, 6), 4, _always), + assert (optimize_read_slicers( + (slice(0, 9, 3), slice(None)), (10, 6), 4, _always) == ((slice(None), slice(None)), (slice(0, 9, 3), slice(None)))) # optimizing partial - assert_equal(optimize_read_slicers( - (slice(0, 9, 3), slice(None)), (10, 6), 4, _partial), + assert (optimize_read_slicers( + (slice(0, 9, 3), slice(None)), (10, 6), 4, _partial) == ((slice(0, 9, 1), slice(None)), (slice(None, None, 3), slice(None)))) # optimize can update non-contiguous to continuous even if last # not optimizing - assert_equal(optimize_read_slicers( - (slice(None), slice(0, 5, 2)), (10, 6), 4, _never), + assert (optimize_read_slicers( + (slice(None), slice(0, 5, 2)), (10, 6), 4, _never) == ((slice(None), slice(0, 5, 2)), (slice(None), slice(None)))) # optimizing - assert_equal(optimize_read_slicers( - (slice(None), slice(0, 5, 2),), (10, 6), 4, _always), + assert (optimize_read_slicers( + (slice(None), slice(0, 5, 2),), (10, 6), 4, _always) == ((slice(None), slice(0, 5, 1)), (slice(None), slice(None, None, 2)))) # Optimize does nothing for integer when last - assert_equal(optimize_read_slicers( - (slice(None), 1), (10, 6), 4, _always), + assert (optimize_read_slicers( + (slice(None), 1), (10, 6), 4, _always) == ((slice(None), 1), (slice(None),))) # Check gap threshold with 3D _depends0 = partial(threshold_heuristic, skip_thresh=10 * 4 - 1) _depends1 = partial(threshold_heuristic, skip_thresh=10 * 4) - assert_equal(optimize_read_slicers( - (slice(9), slice(None), slice(None)), (10, 6, 2), 4, _depends0), + assert (optimize_read_slicers( + (slice(9), slice(None), slice(None)), (10, 6, 2), 4, _depends0) == ((slice(None), slice(None), slice(None)), (slice(0, 9, 1), slice(None), slice(None)))) - assert_equal(optimize_read_slicers( - (slice(None), slice(5), slice(None)), (10, 6, 2), 4, _depends0), + assert (optimize_read_slicers( + (slice(None), slice(5), slice(None)), (10, 6, 2), 4, _depends0) == ((slice(None), slice(0, 5, 1), slice(None)), (slice(None), slice(None), slice(None)))) - assert_equal(optimize_read_slicers( - (slice(None), slice(5), slice(None)), (10, 6, 2), 4, _depends1), + assert (optimize_read_slicers( + (slice(None), slice(5), slice(None)), (10, 6, 2), 4, _depends1) == ((slice(None), slice(None), slice(None)), (slice(None), slice(0, 5, 1), slice(None)))) # Check longs as integer slices sn = slice(None) - assert_equal(optimize_read_slicers( - (1, 2, 3), (2, 3, 4), 4, _always), + assert (optimize_read_slicers( + (1, 2, 3), (2, 3, 4), 4, _always) == ((sn, sn, 3), (1, 2))) def test_slicers2segments(): # Test function to construct segments from slice objects - assert_equal(slicers2segments((0,), (10,), 7, 4), + assert (slicers2segments((0,), (10,), 7, 4) == [[7, 4]]) - assert_equal(slicers2segments((0, 1), (10, 6), 7, 4), + assert (slicers2segments((0, 1), (10, 6), 7, 4) == [[7 + 10 * 4, 4]]) - assert_equal(slicers2segments((0, 1, 2), (10, 6, 4), 7, 4), + assert (slicers2segments((0, 1, 2), (10, 6, 4), 7, 4) == [[7 + 10 * 4 + 10 * 6 * 2 * 4, 4]]) - assert_equal(slicers2segments((slice(None),), (10,), 7, 4), + assert (slicers2segments((slice(None),), (10,), 7, 4) == [[7, 10 * 4]]) - assert_equal(slicers2segments((0, slice(None)), (10, 6), 7, 4), + assert (slicers2segments((0, slice(None)), (10, 6), 7, 4) == [[7 + 10 * 4 * i, 4] for i in range(6)]) - assert_equal(slicers2segments((slice(None), 0), (10, 6), 7, 4), + assert (slicers2segments((slice(None), 0), (10, 6), 7, 4) == [[7, 10 * 4]]) - assert_equal(slicers2segments((slice(None), slice(None)), (10, 6), 7, 4), + assert (slicers2segments((slice(None), slice(None)), (10, 6), 7, 4) == [[7, 10 * 6 * 4]]) - assert_equal(slicers2segments( - (slice(None), slice(None), 2), (10, 6, 4), 7, 4), + assert (slicers2segments( + (slice(None), slice(None), 2), (10, 6, 4), 7, 4) == [[7 + 10 * 6 * 2 * 4, 10 * 6 * 4]]) @@ -535,71 +543,71 @@ def test_calc_slicedefs(): # wrote them after the code. We live and (fail to) learn segments, out_shape, new_slicing = calc_slicedefs( (1,), (10,), 4, 7, 'F', _never) - assert_equal(segments, [[11, 4]]) - assert_equal(new_slicing, ()) - assert_equal(out_shape, ()) - assert_equal( - calc_slicedefs((slice(None),), (10,), 4, 7, 'F', _never), + assert segments == [[11, 4]] + assert new_slicing == () + assert out_shape == () + assert ( + calc_slicedefs((slice(None),), (10,), 4, 7, 'F', _never) == ([[7, 40]], (10,), (), )) - assert_equal( - calc_slicedefs((slice(9),), (10,), 4, 7, 'F', _never), + assert ( + calc_slicedefs((slice(9),), (10,), 4, 7, 'F', _never) == ([[7, 36]], (9,), (), )) - assert_equal( - calc_slicedefs((slice(1, 9),), (10,), 4, 7, 'F', _never), + assert ( + calc_slicedefs((slice(1, 9),), (10,), 4, 7, 'F', _never) == ([[11, 32]], (8,), (), )) # Two dimensions, single slice - assert_equal( - calc_slicedefs((0,), (10, 6), 4, 7, 'F', _never), + assert ( + calc_slicedefs((0,), (10, 6), 4, 7, 'F', _never) == ([[7, 4], [47, 4], [87, 4], [127, 4], [167, 4], [207, 4]], (6,), (), )) - assert_equal( - calc_slicedefs((0,), (10, 6), 4, 7, 'C', _never), + assert ( + calc_slicedefs((0,), (10, 6), 4, 7, 'C', _never) == ([[7, 6 * 4]], (6,), (), )) # Two dimensions, contiguous not full - assert_equal( - calc_slicedefs((1, slice(1, 5)), (10, 6), 4, 7, 'F', _never), + assert ( + calc_slicedefs((1, slice(1, 5)), (10, 6), 4, 7, 'F', _never) == ([[51, 4], [91, 4], [131, 4], [171, 4]], (4,), (), )) - assert_equal( - calc_slicedefs((1, slice(1, 5)), (10, 6), 4, 7, 'C', _never), + assert ( + calc_slicedefs((1, slice(1, 5)), (10, 6), 4, 7, 'C', _never) == ([[7 + 7 * 4, 16]], (4,), (), )) # With full slice first - assert_equal( - calc_slicedefs((slice(None), slice(1, 5)), (10, 6), 4, 7, 'F', _never), + assert ( + calc_slicedefs((slice(None), slice(1, 5)), (10, 6), 4, 7, 'F', _never) == ([[47, 160]], (10, 4), (), )) # Check effect of heuristic on calc_slicedefs # Even integer slices can generate full when heuristic says so - assert_equal( - calc_slicedefs((1, slice(None)), (10, 6), 4, 7, 'F', _always), + assert ( + calc_slicedefs((1, slice(None)), (10, 6), 4, 7, 'F', _always) == ([[7, 10 * 6 * 4]], (10, 6), (1, slice(None)), )) # Except when last - assert_equal( - calc_slicedefs((slice(None), 1), (10, 6), 4, 7, 'F', _always), + assert ( + calc_slicedefs((slice(None), 1), (10, 6), 4, 7, 'F', _always) == ([[7 + 10 * 4, 10 * 4]], (10,), (), @@ -615,17 +623,17 @@ def test_predict_shape(): for i in range(n_dim): slicers_list.append(_slices_for_len(shape[i])) for sliceobj in product(*slicers_list): - assert_equal(predict_shape(sliceobj, shape), + assert (predict_shape(sliceobj, shape) == arr[sliceobj].shape) # Try some Nones and ellipses - assert_equal(predict_shape((Ellipsis,), (2, 3)), (2, 3)) - assert_equal(predict_shape((Ellipsis, 1), (2, 3)), (2,)) - assert_equal(predict_shape((1, Ellipsis), (2, 3)), (3,)) - assert_equal(predict_shape((1, slice(None), Ellipsis), (2, 3)), (3,)) - assert_equal(predict_shape((None,), (2, 3)), (1, 2, 3)) - assert_equal(predict_shape((None, 1), (2, 3)), (1, 3)) - assert_equal(predict_shape((1, None, slice(None)), (2, 3)), (1, 3)) - assert_equal(predict_shape((1, slice(None), None), (2, 3)), (3, 1)) + assert predict_shape((Ellipsis,), (2, 3)) == (2, 3) + assert predict_shape((Ellipsis, 1), (2, 3)) == (2,) + assert predict_shape((1, Ellipsis), (2, 3)) == (3,) + assert predict_shape((1, slice(None), Ellipsis), (2, 3)) == (3,) + assert predict_shape((None,), (2, 3)) == (1, 2, 3) + assert predict_shape((None, 1), (2, 3)) == (1, 3) + assert predict_shape((1, None, slice(None)), (2, 3)) == (1, 3) + assert predict_shape((1, slice(None), None), (2, 3)) == (3, 1) def test_strided_scalar(): @@ -636,18 +644,19 @@ def test_strided_scalar(): expected = np.zeros(shape, dtype=np.array(scalar).dtype) + scalar observed = strided_scalar(shape, scalar) assert_array_equal(observed, expected) - assert_equal(observed.shape, shape) - assert_equal(observed.dtype, expected.dtype) + assert observed.shape == shape + assert observed.dtype == expected.dtype assert_array_equal(observed.strides, 0) # Strided scalars are set as not writeable # This addresses a numpy 1.10 breakage of broadcasting a strided # array without resizing (see GitHub PR #358) - assert_false(observed.flags.writeable) + assert not observed.flags.writeable def setval(x): x[..., 0] = 99 # RuntimeError for numpy < 1.10 - assert_raises((RuntimeError, ValueError), setval, observed) + with pytest.raises((RuntimeError, ValueError)): + setval(observed) # Default scalar value is 0 assert_array_equal(strided_scalar((2, 3, 4)), np.zeros((2, 3, 4))) @@ -670,9 +679,12 @@ def test_read_segments(): np.r_[arr[5:25], arr[50:75]]) _check_bytes(read_segments(fobj, [], 0), arr[0:0]) # Error conditions - assert_raises(ValueError, read_segments, fobj, [], 1) - assert_raises(ValueError, read_segments, fobj, [(0, 200)], 199) - assert_raises(Exception, read_segments, fobj, [(0, 100), (100, 200)], 199) + with pytest.raises(ValueError): + read_segments(fobj, [], 1) + with pytest.raises(ValueError): + read_segments(fobj, [(0, 200)], 199) + with pytest.raises(Exception): + read_segments(fobj, [(0, 100), (100, 200)], 199) def test_read_segments_lock(): @@ -798,8 +810,8 @@ def test_fileslice_errors(): fobj = BytesIO(arr.tostring()) _check_slicer((1,), arr, fobj, 0, 'C') # Fancy indexing raises error - assert_raises(ValueError, - fileslice, fobj, (np.array(1),), (2, 3, 4), arr.dtype) + with pytest.raises(ValueError): + fileslice(fobj, (np.array(1),), (2, 3, 4), arr.dtype) def test_fileslice_heuristic(): diff --git a/nibabel/tests/test_fileutils.py b/nibabel/tests/test_fileutils.py index 63ecc8ee34..edc8384d4d 100644 --- a/nibabel/tests/test_fileutils.py +++ b/nibabel/tests/test_fileutils.py @@ -12,12 +12,7 @@ from ..fileutils import read_zt_byte_strings -from numpy.testing import (assert_almost_equal, - assert_array_equal) - -from nose.tools import (assert_true, assert_false, assert_raises, - assert_equal, assert_not_equal) - +import pytest from ..tmpdirs import InTemporaryDirectory @@ -35,22 +30,24 @@ def test_read_zt_byte_strings(): # open it again fread = open(path, 'rb') # test readout of one string - assert_equal(read_zt_byte_strings(fread), [b'test.fmr']) + assert read_zt_byte_strings(fread) == [b'test.fmr'] # test new file position - assert_equal(fread.tell(), 9) + assert fread.tell() == 9 # manually rewind fread.seek(0) # test readout of two strings - assert_equal(read_zt_byte_strings(fread, 2), + assert (read_zt_byte_strings(fread, 2) == [b'test.fmr', b'test.prt']) - assert_equal(fread.tell(), 18) + assert fread.tell() == 18 # test readout of more strings than present fread.seek(0) - assert_raises(ValueError, read_zt_byte_strings, fread, 3) + with pytest.raises(ValueError): + read_zt_byte_strings(fread, 3) fread.seek(9) - assert_raises(ValueError, read_zt_byte_strings, fread, 2) + with pytest.raises(ValueError): + read_zt_byte_strings(fread, 2) # Try with a small bufsize fread.seek(0) - assert_equal(read_zt_byte_strings(fread, 2, 4), + assert (read_zt_byte_strings(fread, 2, 4) == [b'test.fmr', b'test.prt']) fread.close() diff --git a/nibabel/tests/test_floating.py b/nibabel/tests/test_floating.py index 0c4b5a8cb3..94d3a396b2 100644 --- a/nibabel/tests/test_floating.py +++ b/nibabel/tests/test_floating.py @@ -2,7 +2,6 @@ """ import sys -from distutils.version import LooseVersion import numpy as np @@ -10,10 +9,9 @@ int_to_float, floor_log2, type_info, _check_nmant, _check_maxexp, ok_floats, on_powerpc, have_binary128, longdouble_precision_improved) -from ..testing import suppress_warnings +from ..testing_pytest import suppress_warnings -from nose import SkipTest -from nose.tools import assert_equal, assert_raises, assert_true, assert_false +import pytest IEEE_floats = [np.float16, np.float32, np.float64] @@ -35,17 +33,17 @@ def test_type_info(): for dtt in np.sctypes['int'] + np.sctypes['uint']: info = np.iinfo(dtt) infod = type_info(dtt) - assert_equal(dict(min=info.min, max=info.max, + assert dict(min=info.min, max=info.max, nexp=None, nmant=None, minexp=None, maxexp=None, - width=np.dtype(dtt).itemsize), infod) - assert_equal(infod['min'].dtype.type, dtt) - assert_equal(infod['max'].dtype.type, dtt) + width=np.dtype(dtt).itemsize) == infod + assert infod['min'].dtype.type == dtt + assert infod['max'].dtype.type == dtt for dtt in IEEE_floats + [np.complex64, np.complex64]: infod = type_info(dtt) - assert_equal(dtt2dict(dtt), infod) - assert_equal(infod['min'].dtype.type, dtt) - assert_equal(infod['max'].dtype.type, dtt) + assert dtt2dict(dtt) == infod + assert infod['min'].dtype.type == dtt + assert infod['max'].dtype.type == dtt # What is longdouble? ld_dict = dtt2dict(np.longdouble) dbl_dict = dtt2dict(np.float64) @@ -70,14 +68,14 @@ def test_type_info(): ld_dict['width'] = width else: raise ValueError("Unexpected float type {} to test".format(np.longdouble)) - assert_equal(ld_dict, infod) + assert ld_dict == infod def test_nmant(): for t in IEEE_floats: - assert_equal(type_info(t)['nmant'], np.finfo(t).nmant) + assert type_info(t)['nmant'] == np.finfo(t).nmant if (LD_INFO['nmant'], LD_INFO['nexp']) == (63, 15): - assert_equal(type_info(np.longdouble)['nmant'], 63) + assert type_info(np.longdouble)['nmant'] == 63 def test_check_nmant_nexp(): @@ -85,35 +83,37 @@ def test_check_nmant_nexp(): for t in IEEE_floats: nmant = np.finfo(t).nmant maxexp = np.finfo(t).maxexp - assert_true(_check_nmant(t, nmant)) - assert_false(_check_nmant(t, nmant - 1)) - assert_false(_check_nmant(t, nmant + 1)) + assert _check_nmant(t, nmant) + assert not _check_nmant(t, nmant - 1) + assert not _check_nmant(t, nmant + 1) with suppress_warnings(): # overflow - assert_true(_check_maxexp(t, maxexp)) - assert_false(_check_maxexp(t, maxexp - 1)) + assert _check_maxexp(t, maxexp) + assert not _check_maxexp(t, maxexp - 1) with suppress_warnings(): - assert_false(_check_maxexp(t, maxexp + 1)) + assert not _check_maxexp(t, maxexp + 1) # Check against type_info for t in ok_floats(): ti = type_info(t) if ti['nmant'] not in (105, 106): # This check does not work for PPC double pair - assert_true(_check_nmant(t, ti['nmant'])) + assert _check_nmant(t, ti['nmant']) # Test fails for longdouble after blacklisting of OSX powl as of numpy # 1.12 - see https://github.com/numpy/numpy/issues/8307 if t != np.longdouble or sys.platform != 'darwin': - assert_true(_check_maxexp(t, ti['maxexp'])) + assert _check_maxexp(t, ti['maxexp']) def test_as_int(): # Integer representation of number - assert_equal(as_int(2.0), 2) - assert_equal(as_int(-2.0), -2) - assert_raises(FloatingError, as_int, 2.1) - assert_raises(FloatingError, as_int, -2.1) - assert_equal(as_int(2.1, False), 2) - assert_equal(as_int(-2.1, False), -2) + assert as_int(2.0) == 2 + assert as_int(-2.0) == -2 + with pytest.raises(FloatingError): + as_int(2.1) + with pytest.raises(FloatingError): + as_int(-2.1) + assert as_int(2.1, False) == 2 + assert as_int(-2.1, False) == -2 v = np.longdouble(2**64) - assert_equal(as_int(v), 2**64) + assert as_int(v) == 2**64 # Have all long doubles got 63+1 binary bits of precision? Windows 32-bit # longdouble appears to have 52 bit precision, but we avoid that by checking # for known precisions that are less than that required @@ -122,13 +122,15 @@ def test_as_int(): except FloatingError: nmant = 63 # Unknown precision, let's hope it's at least 63 v = np.longdouble(2) ** (nmant + 1) - 1 - assert_equal(as_int(v), 2**(nmant + 1) - 1) + assert as_int(v) == 2**(nmant + 1) - 1 # Check for predictable overflow nexp64 = floor_log2(type_info(np.float64)['max']) with np.errstate(over='ignore'): val = np.longdouble(2**nexp64) * 2 # outside float64 range - assert_raises(OverflowError, as_int, val) - assert_raises(OverflowError, as_int, -val) + with pytest.raises(OverflowError): + as_int(val) + with pytest.raises(OverflowError): + as_int(-val) def test_int_to_float(): @@ -138,18 +140,20 @@ def test_int_to_float(): nmant = type_info(ie3)['nmant'] for p in range(nmant + 3): i = 2**p + 1 - assert_equal(int_to_float(i, ie3), ie3(i)) - assert_equal(int_to_float(-i, ie3), ie3(-i)) + assert int_to_float(i, ie3) == ie3(i) + assert int_to_float(-i, ie3) == ie3(-i) # IEEEs in this case are binary formats only nexp = floor_log2(type_info(ie3)['max']) # Values too large for the format smn, smx = -2**(nexp + 1), 2**(nexp + 1) if ie3 is np.float64: - assert_raises(OverflowError, int_to_float, smn, ie3) - assert_raises(OverflowError, int_to_float, smx, ie3) + with pytest.raises(OverflowError): + int_to_float(smn, ie3) + with pytest.raises(OverflowError): + int_to_float(smx, ie3) else: - assert_equal(int_to_float(smn, ie3), ie3(smn)) - assert_equal(int_to_float(smx, ie3), ie3(smx)) + assert int_to_float(smn, ie3) == ie3(smn) + assert int_to_float(smx, ie3) == ie3(smx) # Longdoubles do better than int, we hope LD = np.longdouble # up to integer precision of float64 nmant, we get the same result as for @@ -157,29 +161,31 @@ def test_int_to_float(): nmant = type_info(np.float64)['nmant'] for p in range(nmant + 2): # implicit i = 2**p - 1 - assert_equal(int_to_float(i, LD), LD(i)) - assert_equal(int_to_float(-i, LD), LD(-i)) + assert int_to_float(i, LD) == LD(i) + assert int_to_float(-i, LD) == LD(-i) # Above max of float64, we're hosed nexp64 = floor_log2(type_info(np.float64)['max']) smn64, smx64 = -2**(nexp64 + 1), 2**(nexp64 + 1) # The algorithm here implemented goes through float64, so supermax and # supermin will cause overflow errors - assert_raises(OverflowError, int_to_float, smn64, LD) - assert_raises(OverflowError, int_to_float, smx64, LD) + with pytest.raises(OverflowError): + int_to_float(smn64, LD) + with pytest.raises(OverflowError): + int_to_float(smx64, LD) try: nmant = type_info(np.longdouble)['nmant'] except FloatingError: # don't know where to test return # test we recover precision just above nmant i = 2**(nmant + 1) - 1 - assert_equal(as_int(int_to_float(i, LD)), i) - assert_equal(as_int(int_to_float(-i, LD)), -i) + assert as_int(int_to_float(i, LD)) == i + assert as_int(int_to_float(-i, LD)) == -i # If longdouble can cope with 2**64, test if nmant >= 63: # Check conversion to int; the line below causes an error subtracting # ints / uint64 values, at least for Python 3.3 and numpy dev 1.8 big_int = np.uint64(2**64 - 1) - assert_equal(as_int(int_to_float(big_int, LD)), big_int) + assert as_int(int_to_float(big_int, LD)) == big_int def test_as_int_np_fix(): @@ -188,13 +194,13 @@ def test_as_int_np_fix(): for t in np.sctypes['int'] + np.sctypes['uint']: info = np.iinfo(t) mn, mx = np.array([info.min, info.max], dtype=t) - assert_equal((mn, mx), (as_int(mn), as_int(mx))) + assert (mn, mx) == (as_int(mn), as_int(mx)) def test_floor_exact_16(): # A normal integer can generate an inf in float16 - assert_equal(floor_exact(2**31, np.float16), np.inf) - assert_equal(floor_exact(-2**31, np.float16), -np.inf) + assert floor_exact(2**31, np.float16) == np.inf + assert floor_exact(-2**31, np.float16) == -np.inf def test_floor_exact_64(): @@ -203,11 +209,11 @@ def test_floor_exact_64(): start = np.float64(2**e) across = start + np.arange(2048, dtype=np.float64) gaps = set(np.diff(across)).difference([0]) - assert_equal(len(gaps), 1) + assert len(gaps) == 1 gap = gaps.pop() - assert_equal(gap, int(gap)) + assert gap == int(gap) test_val = 2**(e + 1) - 1 - assert_equal(floor_exact(test_val, np.float64), 2**(e + 1) - int(gap)) + assert floor_exact(test_val, np.float64) == 2**(e + 1) - int(gap) def test_floor_exact(): @@ -226,21 +232,21 @@ def test_floor_exact(): for t in to_test: # A number bigger than the range returns the max info = type_info(t) - assert_equal(floor_exact(2**5000, t), np.inf) - assert_equal(ceil_exact(2**5000, t), np.inf) + assert floor_exact(2**5000, t) == np.inf + assert ceil_exact(2**5000, t) == np.inf # A number more negative returns -inf - assert_equal(floor_exact(-2**5000, t), -np.inf) - assert_equal(ceil_exact(-2**5000, t), -np.inf) + assert floor_exact(-2**5000, t) == -np.inf + assert ceil_exact(-2**5000, t) == -np.inf # Check around end of integer precision nmant = info['nmant'] for i in range(nmant + 1): iv = 2**i # up to 2**nmant should be exactly representable for func in (int_flex, int_ceex): - assert_equal(func(iv, t), iv) - assert_equal(func(-iv, t), -iv) - assert_equal(func(iv - 1, t), iv - 1) - assert_equal(func(-iv + 1, t), -iv + 1) + assert func(iv, t) == iv + assert func(-iv, t) == -iv + assert func(iv - 1, t) == iv - 1 + assert func(-iv + 1, t) == -iv + 1 if t is np.longdouble and ( on_powerpc() or longdouble_precision_improved()): @@ -251,28 +257,28 @@ def test_floor_exact(): continue # Confirm to ourselves that 2**(nmant+1) can't be exactly represented iv = 2**(nmant + 1) - assert_equal(int_flex(iv + 1, t), iv) - assert_equal(int_ceex(iv + 1, t), iv + 2) + assert int_flex(iv + 1, t) == iv + assert int_ceex(iv + 1, t) == iv + 2 # negatives - assert_equal(int_flex(-iv - 1, t), -iv - 2) - assert_equal(int_ceex(-iv - 1, t), -iv) + assert int_flex(-iv - 1, t) == -iv - 2 + assert int_ceex(-iv - 1, t) == -iv # The gap in representable numbers is 2 above 2**(nmant+1), 4 above # 2**(nmant+2), and so on. for i in range(5): iv = 2**(nmant + 1 + i) gap = 2**(i + 1) - assert_equal(as_int(t(iv) + t(gap)), iv + gap) + assert as_int(t(iv) + t(gap)) == iv + gap for j in range(1, gap): - assert_equal(int_flex(iv + j, t), iv) - assert_equal(int_flex(iv + gap + j, t), iv + gap) - assert_equal(int_ceex(iv + j, t), iv + gap) - assert_equal(int_ceex(iv + gap + j, t), iv + 2 * gap) + assert int_flex(iv + j, t) == iv + assert int_flex(iv + gap + j, t) == iv + gap + assert int_ceex(iv + j, t) == iv + gap + assert int_ceex(iv + gap + j, t) == iv + 2 * gap # negatives for j in range(1, gap): - assert_equal(int_flex(-iv - j, t), -iv - gap) - assert_equal(int_flex(-iv - gap - j, t), -iv - 2 * gap) - assert_equal(int_ceex(-iv - j, t), -iv) - assert_equal(int_ceex(-iv - gap - j, t), -iv - gap) + assert int_flex(-iv - j, t) == -iv - gap + assert int_flex(-iv - gap - j, t) == -iv - 2 * gap + assert int_ceex(-iv - j, t) == -iv + assert int_ceex(-iv - gap - j, t) == -iv - gap def test_usable_binary128(): @@ -280,7 +286,7 @@ def test_usable_binary128(): yes = have_binary128() with np.errstate(over='ignore'): exp_test = np.longdouble(2) ** 16383 - assert_equal(yes, - exp_test.dtype.itemsize == 16 and + assert (yes == + (exp_test.dtype.itemsize == 16 and np.isfinite(exp_test) and - _check_nmant(np.longdouble, 112)) + _check_nmant(np.longdouble, 112))) diff --git a/nibabel/tests/test_funcs.py b/nibabel/tests/test_funcs.py index 447555d6d0..94645f2839 100644 --- a/nibabel/tests/test_funcs.py +++ b/nibabel/tests/test_funcs.py @@ -18,7 +18,7 @@ from ..tmpdirs import InTemporaryDirectory from numpy.testing import assert_array_equal -from nose.tools import (assert_true, assert_false, assert_equal, assert_raises) +import pytest _counter = 0 @@ -33,7 +33,8 @@ def _as_fname(img): def test_concat(): # Smoke test: concat empty list. - assert_raises(ValueError, concat_images, []) + with pytest.raises(ValueError): + concat_images([]) # Build combinations of 3D, 4D w/size[3] == 1, and 4D w/size[3] == 3 all_shapes_5D = ((1, 4, 5, 3, 3), @@ -104,25 +105,23 @@ def test_concat(): all_imgs = concat_images([img0, img1], **concat_imgs_kwargs) except ValueError as ve: - assert_true(expect_error, str(ve)) + assert expect_error, str(ve) else: - assert_false( - expect_error, "Expected a concatenation error, but got none.") + assert not expect_error, "Expected a concatenation error, but got none." assert_array_equal(all_imgs.get_fdata(), all_data) assert_array_equal(all_imgs.affine, affine) # check that not-matching affines raise error - assert_raises(ValueError, concat_images, [ - img0, img2], **concat_imgs_kwargs) + with pytest.raises(ValueError): + concat_images([img0, img2], **concat_imgs_kwargs) # except if check_affines is False try: all_imgs = concat_images([img0, img1], **concat_imgs_kwargs) except ValueError as ve: - assert_true(expect_error, str(ve)) + assert expect_error, str(ve) else: - assert_false( - expect_error, "Expected a concatenation error, but got none.") + assert not expect_error, "Expected a concatenation error, but got none." assert_array_equal(all_imgs.get_fdata(), all_data) assert_array_equal(all_imgs.affine, affine) @@ -134,12 +133,12 @@ def test_closest_canonical(): # Test with an AnalyzeImage first img = AnalyzeImage(arr, np.eye(4)) xyz_img = as_closest_canonical(img) - assert_true(img is xyz_img) + assert img is xyz_img # And a case where the Analyze image has to be flipped img = AnalyzeImage(arr, np.diag([-1, 1, 1, 1])) xyz_img = as_closest_canonical(img) - assert_false(img is xyz_img) + assert not img is xyz_img out_arr = xyz_img.get_fdata() assert_array_equal(out_arr, np.flipud(arr)) @@ -151,14 +150,14 @@ def test_closest_canonical(): # re-order them properly img.header.set_dim_info(0, 1, 2) xyz_img = as_closest_canonical(img) - assert_true(img is xyz_img) + assert img is xyz_img # a axis flip img = Nifti1Image(arr, np.diag([-1, 1, 1, 1])) img.header.set_dim_info(0, 1, 2) xyz_img = as_closest_canonical(img) - assert_false(img is xyz_img) - assert_true(img.header.get_dim_info() == xyz_img.header.get_dim_info()) + assert not img is xyz_img + assert img.header.get_dim_info() == xyz_img.header.get_dim_info() out_arr = xyz_img.get_fdata() assert_array_equal(out_arr, np.flipud(arr)) @@ -170,9 +169,10 @@ def test_closest_canonical(): # although it's more or less canonical already img = Nifti1Image(arr, aff) xyz_img = as_closest_canonical(img) - assert_true(img is xyz_img) + assert img is xyz_img # it's still not diagnonal - assert_raises(OrientationError, as_closest_canonical, img, True) + with pytest.raises(OrientationError): + as_closest_canonical(img, True) # an axis swap aff = np.diag([1, 0, 0, 1]) @@ -181,14 +181,14 @@ def test_closest_canonical(): img.header.set_dim_info(0, 1, 2) xyz_img = as_closest_canonical(img) - assert_false(img is xyz_img) + assert not img is xyz_img # Check both the original and new objects - assert_true(img.header.get_dim_info() == (0, 1, 2)) - assert_true(xyz_img.header.get_dim_info() == (0, 2, 1)) + assert img.header.get_dim_info() == (0, 1, 2) + assert xyz_img.header.get_dim_info() == (0, 2, 1) out_arr = xyz_img.get_fdata() assert_array_equal(out_arr, np.transpose(arr, (0, 2, 1, 3))) # same axis swap but with None dim info (except for slice dim) img.header.set_dim_info(None, None, 2) xyz_img = as_closest_canonical(img) - assert_true(xyz_img.header.get_dim_info() == (None, None, 1)) + assert xyz_img.header.get_dim_info() == (None, None, 1) diff --git a/nibabel/tests/test_h5py_compat.py b/nibabel/tests/test_h5py_compat.py index af5c50989c..325645a18c 100644 --- a/nibabel/tests/test_h5py_compat.py +++ b/nibabel/tests/test_h5py_compat.py @@ -10,7 +10,6 @@ from ..optpkg import optional_package from .. import _h5py_compat as compat -from ..testing import assert_equal, assert_true, assert_false, assert_not_equal h5py, have_h5py, _ = optional_package('h5py') @@ -18,30 +17,30 @@ def test_optpkg_equivalence(): # No effect on Linux/OSX if os.name == 'posix': - assert_equal(have_h5py, compat.have_h5py) + assert have_h5py == compat.have_h5py # No effect on Python 2.7 or 3.6+ if sys.version_info >= (3, 6) or sys.version_info < (3,): - assert_equal(have_h5py, compat.have_h5py) + assert have_h5py == compat.have_h5py # Available in a strict subset of cases if not have_h5py: - assert_false(compat.have_h5py) + assert not compat.have_h5py # Available when version is high enough elif LooseVersion(h5py.__version__) >= '2.10': - assert_true(compat.have_h5py) + assert compat.have_h5py def test_disabled_h5py_cases(): # On mismatch if have_h5py and not compat.have_h5py: # Recapitulate min_h5py conditions from _h5py_compat - assert_equal(os.name, 'nt') - assert_true((3,) <= sys.version_info < (3, 6)) - assert_true(LooseVersion(h5py.__version__) < '2.10') + assert os.name == 'nt' + assert (3,) <= sys.version_info < (3, 6) + assert LooseVersion(h5py.__version__) < '2.10' # Verify that the root cause is present # If any tests fail, they will likely be these, so they may be # ill-advised... if LooseVersion(np.__version__) < '1.18': - assert_equal(str(np.longdouble), str(np.float64)) + assert str(np.longdouble) == str(np.float64) else: - assert_not_equal(str(np.longdouble), str(np.float64)) - assert_not_equal(np.longdouble, np.float64) + assert str(np.longdouble) != str(np.float64) + assert np.longdouble != np.float64 diff --git a/nibabel/tests/test_helpers.py b/nibabel/tests/test_helpers.py index 928b4bd1a3..49112fddfb 100644 --- a/nibabel/tests/test_helpers.py +++ b/nibabel/tests/test_helpers.py @@ -4,12 +4,9 @@ import numpy as np -from ..openers import ImageOpener -from ..tmpdirs import InTemporaryDirectory from ..optpkg import optional_package _, have_scipy, _ = optional_package('scipy.io') -from nose.tools import assert_true from numpy.testing import assert_array_equal @@ -51,6 +48,6 @@ def assert_data_similar(arr, params): return summary = params['data_summary'] real_arr = np.asarray(arr) - assert_true(np.allclose( + assert np.allclose( (real_arr.min(), real_arr.max(), real_arr.mean()), - (summary['min'], summary['max'], summary['mean']))) + (summary['min'], summary['max'], summary['mean'])) From 50de669184375ce3cc551fda270204a296ed3abe Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Fri, 15 Nov 2019 15:23:20 -0500 Subject: [PATCH 006/223] fixing interaction between fixtures --- nibabel/tests/test_data.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/nibabel/tests/test_data.py b/nibabel/tests/test_data.py index 0fc0bdc40d..e48356eb50 100644 --- a/nibabel/tests/test_data.py +++ b/nibabel/tests/test_data.py @@ -19,21 +19,19 @@ import pytest -from .test_environment import (setup_environment, - teardown_environment, +from .test_environment import (with_environment, DATA_KEY, USER_KEY) + @pytest.fixture() -def with_environment(request): - setup_environment() +def with_nimd_env(request, with_environment): DATA_FUNCS = {} DATA_FUNCS['home_dir_func'] = nibd.get_nipy_user_dir DATA_FUNCS['sys_dir_func'] = nibd.get_nipy_system_dir DATA_FUNCS['path_func'] = nibd.get_data_path def teardown_data_env(): - teardown_environment() nibd.get_nipy_user_dir = DATA_FUNCS['home_dir_func'] nibd.get_nipy_system_dir = DATA_FUNCS['sys_dir_func'] nibd.get_data_path = DATA_FUNCS['path_func'] @@ -116,7 +114,7 @@ def test__cfg_value(): pass -def test_data_path(with_environment): +def test_data_path(with_nimd_env): # wipe out any sources of data paths if DATA_KEY in env: del env[DATA_KEY] @@ -189,7 +187,7 @@ def test_find_data_dir(): assert dd == here -def test_make_datasource(with_environment): +def test_make_datasource(with_nimd_env): pkg_def = dict( relpath='pkg') with TemporaryDirectory() as tmpdir: @@ -219,7 +217,7 @@ def test_bomber_inspect(): assert not hasattr(b, 'any_attribute') -def test_datasource_or_bomber(with_environment): +def test_datasource_or_bomber(with_nimd_env): pkg_def = dict( relpath='pkg') with TemporaryDirectory() as tmpdir: From def8ceb7259434cc42bf07d2921e3b90a1579556 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Fri, 15 Nov 2019 15:24:41 -0500 Subject: [PATCH 007/223] moving test_helpers to testing/helpers.py (it contains no tests, but helping functions) --- nibabel/testing_pytest/__init__.py | 5 ++--- nibabel/{tests/test_helpers.py => testing_pytest/helpers.py} | 0 nibabel/tests/test_analyze.py | 2 +- nibabel/tests/test_brikhead.py | 3 +-- nibabel/tests/test_image_api.py | 4 ++-- nibabel/tests/test_minc1.py | 2 +- nibabel/tests/test_nifti1.py | 2 +- nibabel/tests/test_scripts.py | 2 +- nibabel/tests/test_spatialimages.py | 2 +- nibabel/tests/test_spm99analyze.py | 2 +- 10 files changed, 11 insertions(+), 13 deletions(-) rename nibabel/{tests/test_helpers.py => testing_pytest/helpers.py} (100%) diff --git a/nibabel/testing_pytest/__init__.py b/nibabel/testing_pytest/__init__.py index 675c506e3b..38143d9c38 100644 --- a/nibabel/testing_pytest/__init__.py +++ b/nibabel/testing_pytest/__init__.py @@ -22,7 +22,8 @@ slow = dec.slow from ..deprecated import deprecate_with_version as _deprecate_with_version - +from .np_features import memmap_after_ufunc +from .helpers import bytesio_filemap, bytesio_round_trip, assert_data_similar from itertools import zip_longest @@ -45,8 +46,6 @@ def test_data(subdir=None, fname=None): data_path = test_data() -from .np_features import memmap_after_ufunc - def assert_dt_equal(a, b): """ Assert two numpy dtype specifiers are equal diff --git a/nibabel/tests/test_helpers.py b/nibabel/testing_pytest/helpers.py similarity index 100% rename from nibabel/tests/test_helpers.py rename to nibabel/testing_pytest/helpers.py diff --git a/nibabel/tests/test_analyze.py b/nibabel/tests/test_analyze.py index b0cc566979..9032f136c5 100644 --- a/nibabel/tests/test_analyze.py +++ b/nibabel/tests/test_analyze.py @@ -38,7 +38,7 @@ from .test_wrapstruct import _TestLabeledWrapStruct from . import test_spatialimages as tsi -from .test_helpers import bytesio_filemap, bytesio_round_trip +from ..testing_pytest import bytesio_filemap, bytesio_round_trip header_file = os.path.join(data_path, 'analyze.hdr') diff --git a/nibabel/tests/test_brikhead.py b/nibabel/tests/test_brikhead.py index 078193ce48..60bd008a46 100644 --- a/nibabel/tests/test_brikhead.py +++ b/nibabel/tests/test_brikhead.py @@ -16,10 +16,9 @@ import pytest from numpy.testing import assert_array_equal -from ..testing_pytest import data_path +from ..testing_pytest import data_path, assert_data_similar from .test_fileslice import slicer_samples -from .test_helpers import assert_data_similar EXAMPLE_IMAGES = [ dict( diff --git a/nibabel/tests/test_image_api.py b/nibabel/tests/test_image_api.py index f91b61af9e..b9a066f598 100644 --- a/nibabel/tests/test_image_api.py +++ b/nibabel/tests/test_image_api.py @@ -46,12 +46,12 @@ from numpy.testing import assert_almost_equal, assert_array_equal, assert_warns, assert_allclose from ..testing import clear_and_catch_warnings +from ..testing_pytest import (bytesio_round_trip, bytesio_filemap, + assert_data_similar) from ..tmpdirs import InTemporaryDirectory from ..deprecator import ExpiredDeprecationError from .test_api_validators import ValidateAPI -from .test_helpers import (bytesio_round_trip, bytesio_filemap, - assert_data_similar) from .test_minc1 import EXAMPLE_IMAGES as MINC1_EXAMPLE_IMAGES from .test_minc2 import EXAMPLE_IMAGES as MINC2_EXAMPLE_IMAGES from .test_parrec import EXAMPLE_IMAGES as PARREC_EXAMPLE_IMAGES diff --git a/nibabel/tests/test_minc1.py b/nibabel/tests/test_minc1.py index eb9ff15cab..c7b044ed9b 100644 --- a/nibabel/tests/test_minc1.py +++ b/nibabel/tests/test_minc1.py @@ -27,10 +27,10 @@ from ..testing import (assert_true, assert_equal, assert_false, assert_raises, assert_warns, assert_array_equal, data_path, clear_and_catch_warnings) from ..deprecator import ExpiredDeprecationError +from ..testing_pytest import assert_data_similar from . import test_spatialimages as tsi from .test_fileslice import slicer_samples -from .test_helpers import assert_data_similar EG_FNAME = pjoin(data_path, 'tiny.mnc') diff --git a/nibabel/tests/test_nifti1.py b/nibabel/tests/test_nifti1.py index 0213b615f1..dd98972df5 100644 --- a/nibabel/tests/test_nifti1.py +++ b/nibabel/tests/test_nifti1.py @@ -29,8 +29,8 @@ from .test_arraywriters import rt_err_estimate, IUINT_TYPES from .test_orientations import ALL_ORNTS -from .test_helpers import bytesio_filemap, bytesio_round_trip from .nibabel_data import get_nibabel_data, needs_nibabel_data +from ..testing_pytest import bytesio_filemap, bytesio_round_trip from numpy.testing import (assert_array_equal, assert_array_almost_equal, assert_almost_equal) diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 6d46e57c5c..431e606380 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -31,7 +31,7 @@ from .test_parrec import (DTI_PAR_BVECS, DTI_PAR_BVALS, EXAMPLE_IMAGES as PARREC_EXAMPLES) from .test_parrec_data import BALLS, AFF_OFF -from .test_helpers import assert_data_similar +from ..testing_pytest import assert_data_similar def _proc_stdout(stdout): diff --git a/nibabel/tests/test_spatialimages.py b/nibabel/tests/test_spatialimages.py index 8b11e5cc51..3f9c8b4b97 100644 --- a/nibabel/tests/test_spatialimages.py +++ b/nibabel/tests/test_spatialimages.py @@ -24,9 +24,9 @@ assert_not_equal, assert_raises) from numpy.testing import assert_array_equal, assert_array_almost_equal, assert_warns -from .test_helpers import bytesio_round_trip from ..testing import (clear_and_catch_warnings, suppress_warnings, memmap_after_ufunc) +from ..testing_pytest import bytesio_round_trip from ..tmpdirs import InTemporaryDirectory from ..deprecator import ExpiredDeprecationError from .. import load as top_load diff --git a/nibabel/tests/test_spm99analyze.py b/nibabel/tests/test_spm99analyze.py index 86143f35ab..71fe41e2ec 100644 --- a/nibabel/tests/test_spm99analyze.py +++ b/nibabel/tests/test_spm99analyze.py @@ -29,9 +29,9 @@ from nose.tools import assert_true, assert_false, assert_equal, assert_raises from ..testing import assert_allclose_safely, suppress_warnings +from ..testing_pytest import bytesio_round_trip, bytesio_filemap from . import test_analyze -from .test_helpers import bytesio_round_trip, bytesio_filemap FLOAT_TYPES = np.sctypes['float'] COMPLEX_TYPES = np.sctypes['complex'] From 629dc57549e598491151caea76f6f026e56ad713 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Fri, 15 Nov 2019 15:26:34 -0500 Subject: [PATCH 008/223] adding new tests to travis --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 63176ce581..d3d49e1853 100644 --- a/.travis.yml +++ b/.travis.yml @@ -130,7 +130,7 @@ script: cd for_testing cp ../.coveragerc . nosetests --with-doctest --with-coverage --cover-package nibabel nibabel - pytest -v ../nibabel/tests/test_a*.py ../nibabel/tests/test_b*.py ../nibabel/tests/test_c*.py ../nibabel/tests/test_d*.py + pytest -v ../nibabel/tests/test_a*.py ../nibabel/tests/test_b*.py ../nibabel/tests/test_c*.py ../nibabel/tests/test_d*.py ../nibabel/tests/test_e*.py ../nibabel/tests/test_f*.py ../nibabel/tests/test_h*.py pytest -v ../nibabel/tests/test_w*.py else false From 51cc6aa73297f8573ccf179e97ab173501752481 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Fri, 15 Nov 2019 16:56:01 -0500 Subject: [PATCH 009/223] adding more tests --- .travis.yml | 4 +- nibabel/tests/test_image_api.py | 155 ++++++++++++++------------ nibabel/tests/test_image_load_save.py | 120 ++++++++++---------- nibabel/tests/test_image_types.py | 5 +- nibabel/tests/test_imageclasses.py | 21 ++-- nibabel/tests/test_imageglobals.py | 8 +- nibabel/tests/test_keywordonly.py | 42 ++++--- nibabel/tests/test_loadsave.py | 22 ++-- nibabel/tests/test_minc1.py | 39 +++---- nibabel/tests/test_minc2.py | 4 +- nibabel/tests/test_minc2_data.py | 7 +- nibabel/tests/test_mriutils.py | 14 +-- 12 files changed, 225 insertions(+), 216 deletions(-) diff --git a/.travis.yml b/.travis.yml index d3d49e1853..43ddf9dde1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -130,7 +130,9 @@ script: cd for_testing cp ../.coveragerc . nosetests --with-doctest --with-coverage --cover-package nibabel nibabel - pytest -v ../nibabel/tests/test_a*.py ../nibabel/tests/test_b*.py ../nibabel/tests/test_c*.py ../nibabel/tests/test_d*.py ../nibabel/tests/test_e*.py ../nibabel/tests/test_f*.py ../nibabel/tests/test_h*.py + pytest -v ../nibabel/tests/test_a*.py ../nibabel/tests/test_b*.py ../nibabel/tests/test_c*.py ../nibabel/tests/test_d*.py + pytest -v../nibabel/tests/test_e*.py ../nibabel/tests/test_f*.py ../nibabel/tests/test_h*.py + pytest -v../nibabel/tests/test_i*.py ../nibabel/tests/test_k*.py ../nibabel/tests/test_l*.py ../nibabel/tests/test_m*.py pytest -v ../nibabel/tests/test_w*.py else false diff --git a/nibabel/tests/test_image_api.py b/nibabel/tests/test_image_api.py index b9a066f598..ee8c287df2 100644 --- a/nibabel/tests/test_image_api.py +++ b/nibabel/tests/test_image_api.py @@ -41,13 +41,11 @@ from ..spatialimages import SpatialImage from .. import minc1, minc2, parrec, brikhead -from nose import SkipTest -from nose.tools import (assert_true, assert_false, assert_raises, assert_equal) +import pytest from numpy.testing import assert_almost_equal, assert_array_equal, assert_warns, assert_allclose -from ..testing import clear_and_catch_warnings from ..testing_pytest import (bytesio_round_trip, bytesio_filemap, - assert_data_similar) + assert_data_similar, clear_and_catch_warnings) from ..tmpdirs import InTemporaryDirectory from ..deprecator import ExpiredDeprecationError @@ -109,7 +107,8 @@ def validate_header(self, imaker, params): img = imaker() hdr = img.header # we can fetch it # Read only - assert_raises(AttributeError, setattr, img, 'header', hdr) + with pytest.raises(AttributeError): + setattr(img, 'header', hdr) def validate_header_deprecated(self, imaker, params): # Check deprecated header API @@ -117,13 +116,14 @@ def validate_header_deprecated(self, imaker, params): with clear_and_catch_warnings() as w: warnings.simplefilter('always', DeprecationWarning) hdr = img.get_header() - assert_equal(len(w), 1) - assert_true(hdr is img.header) + assert len(w) == 1 + assert hdr is img.header def validate_filenames(self, imaker, params): # Validate the filename, file_map interface + if not self.can_save: - raise SkipTest + pytest.skip() img = imaker() img.set_data_dtype(np.float32) # to avoid rounding in load / save # Make sure the object does not have a file_map @@ -145,8 +145,8 @@ def validate_filenames(self, imaker, params): fname = 'an_image' + self.standard_extension for path in (fname, pathlib.Path(fname)): img.set_filename(path) - assert_equal(img.get_filename(), str(path)) - assert_equal(img.file_map['image'].filename, str(path)) + assert img.get_filename() == str(path) + assert img.file_map['image'].filename == str(path) # to_ / from_ filename fname = 'another_image' + self.standard_extension for path in (fname, pathlib.Path(fname)): @@ -163,8 +163,10 @@ def validate_filenames(self, imaker, params): def validate_no_slicing(self, imaker, params): img = imaker() - assert_raises(TypeError, img.__getitem__, 'string') - assert_raises(TypeError, img.__getitem__, slice(None)) + with pytest.raises(TypeError): + img.__getitem__('string') + with pytest.raises(TypeError): + img.__getitem__(slice(None)) def validate_get_data_deprecated(self, imaker, params): # Check deprecated header API @@ -184,19 +186,19 @@ def validate_dtype(self, imaker, params): # data / storage dtype img = imaker() # Need to rename this one - assert_equal(img.get_data_dtype().type, params['dtype']) + assert img.get_data_dtype().type == params['dtype'] # dtype survives round trip if self.has_scaling and self.can_save: with np.errstate(invalid='ignore'): rt_img = bytesio_round_trip(img) - assert_equal(rt_img.get_data_dtype().type, params['dtype']) + assert rt_img.get_data_dtype().type == params['dtype'] # Setting to a different dtype img.set_data_dtype(np.float32) # assumed supported for all formats - assert_equal(img.get_data_dtype().type, np.float32) + assert img.get_data_dtype().type == np.float32 # dtype survives round trip if self.can_save: rt_img = bytesio_round_trip(img) - assert_equal(rt_img.get_data_dtype().type, np.float32) + assert rt_img.get_data_dtype().type == np.float32 class DataInterfaceMixin(GetSetDtypeMixin): @@ -210,8 +212,8 @@ class DataInterfaceMixin(GetSetDtypeMixin): def validate_data_interface(self, imaker, params): # Check get data returns array, and caches img = imaker() - assert_equal(img.shape, img.dataobj.shape) - assert_equal(img.ndim, len(img.shape)) + assert img.shape == img.dataobj.shape + assert img.ndim == len(img.shape) assert_data_similar(img.dataobj, params) for meth_name in self.meth_names: if params['is_proxy']: @@ -219,53 +221,56 @@ def validate_data_interface(self, imaker, params): else: # Array image self._check_array_interface(imaker, meth_name) # Data shape is same as image shape - assert_equal(img.shape, getattr(img, meth_name)().shape) + assert img.shape == getattr(img, meth_name)().shape # Data ndim is same as image ndim - assert_equal(img.ndim, getattr(img, meth_name)().ndim) + assert img.ndim == getattr(img, meth_name)().ndim # Values to get_data caching parameter must be 'fill' or # 'unchanged' - assert_raises(ValueError, img.get_data, caching='something') + with pytest.raises(ValueError): + img.get_data(caching='something') # dataobj is read only fake_data = np.zeros(img.shape).astype(img.get_data_dtype()) - assert_raises(AttributeError, setattr, img, 'dataobj', fake_data) + with pytest.raises(AttributeError): + setattr(img, 'dataobj', fake_data) # So is in_memory - assert_raises(AttributeError, setattr, img, 'in_memory', False) + with pytest.raises(AttributeError): + setattr(img, 'in_memory', False) def _check_proxy_interface(self, imaker, meth_name): # Parameters assert this is an array proxy img = imaker() # Does is_proxy agree? - assert_true(is_proxy(img.dataobj)) + assert is_proxy(img.dataobj) # Confirm it is not a numpy array - assert_false(isinstance(img.dataobj, np.ndarray)) + assert not isinstance(img.dataobj, np.ndarray) # Confirm it can be converted to a numpy array with asarray proxy_data = np.asarray(img.dataobj) proxy_copy = proxy_data.copy() # Not yet cached, proxy image: in_memory is False - assert_false(img.in_memory) + assert not img.in_memory # Load with caching='unchanged' method = getattr(img, meth_name) data = method(caching='unchanged') # Still not cached - assert_false(img.in_memory) + assert not img.in_memory # Default load, does caching data = method() # Data now cached. in_memory is True if either of the get_data # or get_fdata caches are not-None - assert_true(img.in_memory) + assert img.in_memory # We previously got proxy_data from disk, but data, which we # have just fetched, is a fresh copy. - assert_false(proxy_data is data) + assert not proxy_data is data # asarray on dataobj, applied above, returns same numerical # values. This might not be true get_fdata operating on huge # integers, but lets assume that's not true here. assert_array_equal(proxy_data, data) # Now caching='unchanged' does nothing, returns cached version data_again = method(caching='unchanged') - assert_true(data is data_again) + assert data is data_again # caching='fill' does nothing because the cache is already full data_yet_again = method(caching='fill') - assert_true(data is data_yet_again) + assert data is data_yet_again # changing array data does not change proxy data, or reloaded # data data[:] = 42 @@ -276,16 +281,16 @@ def _check_proxy_interface(self, imaker, meth_name): # until we uncache img.uncache() # Which unsets in_memory - assert_false(img.in_memory) + assert not img.in_memory assert_array_equal(method(), proxy_copy) # Check caching='fill' does cache data img = imaker() method = getattr(img, meth_name) - assert_false(img.in_memory) + assert not img.in_memory data = method(caching='fill') - assert_true(img.in_memory) + assert img.in_memory data_again = method() - assert_true(data is data_again) + assert data is data_again # Check the interaction of caching with get_data, get_fdata. # Caching for `get_data` should have no effect on caching for # get_fdata, and vice versa. @@ -297,21 +302,21 @@ def _check_proxy_interface(self, imaker, meth_name): other_data = other_method() # We get the original data, not the modified cache assert_array_equal(proxy_data, other_data) - assert_false(np.all(data == other_data)) + assert not np.all(data == other_data) # We can modify the other cache, without affecting the first other_data[:] = 44 assert_array_equal(other_method(), 44) - assert_false(np.all(method() == other_method())) + assert not np.all(method() == other_method()) if meth_name != 'get_fdata': return # Check that caching refreshes for new floating point type. img.uncache() fdata = img.get_fdata() - assert_equal(fdata.dtype, np.float64) + assert fdata.dtype == np.float64 fdata[:] = 42 fdata_back = img.get_fdata() assert_array_equal(fdata_back, 42) - assert_equal(fdata_back.dtype, np.float64) + assert fdata_back.dtype == np.float64 # New data dtype, no caching, doesn't use or alter cache fdata_new_dt = img.get_fdata(caching='unchanged', dtype='f4') # We get back the original read, not the modified cache @@ -319,7 +324,7 @@ def _check_proxy_interface(self, imaker, meth_name): # factors, rather than 64-bit factors and then cast to float-32 # Use rtol/atol from numpy.allclose assert_allclose(fdata_new_dt, proxy_data.astype('f4'), rtol=1e-05, atol=1e-08) - assert_equal(fdata_new_dt.dtype, np.float32) + assert fdata_new_dt.dtype == np.float32 # The original cache stays in place, for default float64 assert_array_equal(img.get_fdata(), 42) # And for not-default float32, because we haven't cached @@ -345,8 +350,8 @@ def _check_array_caching(self, imaker, meth_name, caching): method = getattr(img, meth_name) get_data_func = (method if caching is None else partial(method, caching=caching)) - assert_true(isinstance(img.dataobj, np.ndarray)) - assert_true(img.in_memory) + assert isinstance(img.dataobj, np.ndarray) + assert img.in_memory data = get_data_func() # Returned data same object as underlying dataobj if using # old ``get_data`` method, or using newer ``get_fdata`` @@ -356,10 +361,10 @@ def _check_array_caching(self, imaker, meth_name, caching): # Set something to the output array. data[:] = 42 get_result_changed = np.all(get_data_func() == 42) - assert_equal(get_result_changed, - dataobj_is_data or caching != 'unchanged') + assert (get_result_changed == + (dataobj_is_data or caching != 'unchanged')) if dataobj_is_data: - assert_true(data is img.dataobj) + assert data is img.dataobj # Changing array data changes # data assert_array_equal(np.asarray(img.dataobj), 42) @@ -367,15 +372,15 @@ def _check_array_caching(self, imaker, meth_name, caching): img.uncache() assert_array_equal(get_data_func(), 42) else: - assert_false(data is img.dataobj) - assert_false(np.all(np.asarray(img.dataobj) == 42)) + assert not data is img.dataobj + assert not np.all(np.asarray(img.dataobj) == 42) # Uncache does have an effect img.uncache() - assert_false(np.all(get_data_func() == 42)) + assert not np.all(get_data_func() == 42) # in_memory is always true for array images, regardless of # cache state. img.uncache() - assert_true(img.in_memory) + assert img.in_memory if meth_name != 'get_fdata': return # Return original array from get_fdata only if the input array is the @@ -385,7 +390,7 @@ def _check_array_caching(self, imaker, meth_name, caching): return for float_type in float_types: data = get_data_func(dtype=float_type) - assert_equal(data is img.dataobj, arr_dtype == float_type) + assert (data is img.dataobj) == (arr_dtype == float_type) def validate_data_deprecated(self, imaker, params): # Check _data property still exists, but raises warning @@ -393,37 +398,40 @@ def validate_data_deprecated(self, imaker, params): with warnings.catch_warnings(record=True) as warns: warnings.simplefilter("always") assert_data_similar(img._data, params) - assert_equal(warns.pop(0).category, DeprecationWarning) + assert warns.pop(0).category == DeprecationWarning # Check setting _data raises error fake_data = np.zeros(img.shape).astype(img.get_data_dtype()) - assert_raises(AttributeError, setattr, img, '_data', fake_data) + with pytest.raises(AttributeError): + setattr(img, '_data', fake_data) def validate_shape(self, imaker, params): # Validate shape img = imaker() # Same as expected shape - assert_equal(img.shape, params['shape']) + assert img.shape == params['shape'] # Same as array shape if passed if 'data' in params: - assert_equal(img.shape, params['data'].shape) + assert img.shape == params['data'].shape # Read only - assert_raises(AttributeError, setattr, img, 'shape', np.eye(4)) + with pytest.raises(AttributeError): + setattr(img, 'shape', np.eye(4)) def validate_ndim(self, imaker, params): # Validate shape img = imaker() # Same as expected ndim - assert_equal(img.ndim, len(params['shape'])) + assert img.ndim == len(params['shape']) # Same as array ndim if passed if 'data' in params: - assert_equal(img.ndim, params['data'].ndim) + assert img.ndim == params['data'].ndim # Read only - assert_raises(AttributeError, setattr, img, 'ndim', 5) + with pytest.raises(AttributeError): + setattr(img, 'ndim', 5) def validate_shape_deprecated(self, imaker, params): # Check deprecated get_shape API img = imaker() - with assert_raises(ExpiredDeprecationError): + with pytest.raises(ExpiredDeprecationError): img.get_shape() def validate_mmap_parameter(self, imaker, params): @@ -448,10 +456,10 @@ def validate_mmap_parameter(self, imaker, params): rt_img = img.__class__.from_filename(fname, mmap='r') assert_almost_equal(img.get_fdata(), rt_img.get_fdata()) # r+ is specifically not valid for images - assert_raises(ValueError, - img.__class__.from_filename, fname, mmap='r+') - assert_raises(ValueError, - img.__class__.from_filename, fname, mmap='invalid') + with pytest.raises(ValueError): + img.__class__.from_filename(fname, mmap='r+') + with pytest.raises(ValueError): + img.__class__.from_filename(fname, mmap='invalid') del rt_img # to allow windows to delete the directory @@ -469,8 +477,8 @@ def validate_header_shape(self, imaker, params): shape = hdr.get_data_shape() new_shape = (shape[0] + 1,) + shape[1:] hdr.set_data_shape(new_shape) - assert_true(img.header is hdr) - assert_equal(img.header.get_data_shape(), new_shape) + assert img.header is hdr + assert img.header.get_data_shape() == new_shape class AffineMixin(object): @@ -484,11 +492,12 @@ def validate_affine(self, imaker, params): # Check affine API img = imaker() assert_almost_equal(img.affine, params['affine'], 6) - assert_equal(img.affine.dtype, np.float64) + assert img.affine.dtype == np.float64 img.affine[0, 0] = 1.5 - assert_equal(img.affine[0, 0], 1.5) + assert img.affine[0, 0] == 1.5 # Read only - assert_raises(AttributeError, setattr, img, 'affine', np.eye(4)) + with pytest.raises(AttributeError): + setattr(img, 'affine', np.eye(4)) def validate_affine_deprecated(self, imaker, params): # Check deprecated affine API @@ -496,11 +505,11 @@ def validate_affine_deprecated(self, imaker, params): with clear_and_catch_warnings() as w: warnings.simplefilter('always', DeprecationWarning) assert_almost_equal(img.get_affine(), params['affine'], 6) - assert_equal(len(w), 1) - assert_equal(img.get_affine().dtype, np.float64) + assert len(w) == 1 + assert img.get_affine().dtype == np.float64 aff = img.get_affine() aff[0, 0] = 1.5 - assert_true(aff is img.get_affine()) + assert aff is img.get_affine() class SerializeMixin(object): @@ -584,7 +593,7 @@ def obj_params(self): def validate_path_maybe_image(self, imaker, params): for img_params in self.example_images: test, sniff = self.klass.path_maybe_image(img_params['fname']) - assert_true(isinstance(test, bool)) + assert isinstance(test, bool) if sniff is not None: assert isinstance(sniff[0], bytes) assert isinstance(sniff[1], str) @@ -707,7 +716,7 @@ class TestMinc2API(TestMinc1API): def __init__(self): if not have_h5py: - raise SkipTest('Need h5py for these tests') + pytest.skip('Need h5py for these tests') klass = image_maker = Minc2Image loader = minc2.load diff --git a/nibabel/tests/test_image_load_save.py b/nibabel/tests/test_image_load_save.py index 9d58a3ed60..8dd64f8185 100644 --- a/nibabel/tests/test_image_load_save.py +++ b/nibabel/tests/test_image_load_save.py @@ -30,7 +30,7 @@ from ..spatialimages import SpatialImage from numpy.testing import assert_array_equal, assert_array_almost_equal -from nose.tools import assert_true, assert_equal, assert_not_equal, assert_raises +import pytest _, have_scipy, _ = optional_package('scipy') # No scipy=>no SPM-format writing DATA_PATH = pjoin(dirname(__file__), 'data') @@ -68,15 +68,15 @@ def test_save_load_endian(): data = np.arange(np.prod(shape), dtype='f4').reshape(shape) # Native endian image img = Nifti1Image(data, affine) - assert_equal(img.header.endianness, native_code) + assert img.header.endianness == native_code img2 = round_trip(img) - assert_equal(img2.header.endianness, native_code) + assert img2.header.endianness == native_code assert_array_equal(img2.get_fdata(), data) assert_array_equal(np.asanyarray(img2.dataobj), data) # byte swapped endian image bs_hdr = img.header.as_byteswapped() bs_img = Nifti1Image(data, affine, bs_hdr) - assert_equal(bs_img.header.endianness, swapped_code) + assert bs_img.header.endianness == swapped_code # of course the data is the same because it's not written to disk assert_array_equal(bs_img.get_fdata(), data) assert_array_equal(np.asanyarray(bs_img.dataobj), data) @@ -84,27 +84,27 @@ def test_save_load_endian(): cbs_img = AnalyzeImage.from_image(bs_img) # this will make the header native by doing the header conversion cbs_hdr = cbs_img.header - assert_equal(cbs_hdr.endianness, native_code) + assert cbs_hdr.endianness == native_code # and the byte order follows it back into another image cbs_img2 = Nifti1Image.from_image(cbs_img) cbs_hdr2 = cbs_img2.header - assert_equal(cbs_hdr2.endianness, native_code) + assert cbs_hdr2.endianness == native_code # Try byteswapped round trip bs_img2 = round_trip(bs_img) bs_data2 = np.asanyarray(bs_img2.dataobj) bs_fdata2 = bs_img2.get_fdata() # now the data dtype was swapped endian, so the read data is too - assert_equal(bs_data2.dtype.byteorder, swapped_code) - assert_equal(bs_img2.header.endianness, swapped_code) + assert bs_data2.dtype.byteorder == swapped_code + assert bs_img2.header.endianness == swapped_code assert_array_equal(bs_data2, data) # but get_fdata uses native endian - assert_not_equal(bs_fdata2.dtype.byteorder, swapped_code) + assert bs_fdata2.dtype.byteorder != swapped_code assert_array_equal(bs_fdata2, data) # Now mix up byteswapped data and non-byteswapped header mixed_img = Nifti1Image(bs_data2, affine) - assert_equal(mixed_img.header.endianness, native_code) + assert mixed_img.header.endianness == native_code m_img2 = round_trip(mixed_img) - assert_equal(m_img2.header.endianness, native_code) + assert m_img2.header.endianness == native_code assert_array_equal(m_img2.get_fdata(), data) @@ -121,7 +121,7 @@ def test_save_load(): sifn = 'another_image.img' ni1.save(img, nifn) re_img = nils.load(nifn) - assert_true(isinstance(re_img, ni1.Nifti1Image)) + assert isinstance(re_img, ni1.Nifti1Image) assert_array_equal(re_img.get_fdata(), data) assert_array_equal(re_img.affine, affine) # These and subsequent del statements are to prevent confusing @@ -131,20 +131,20 @@ def test_save_load(): if have_scipy: # skip we we cannot read .mat files spm2.save(img, sifn) re_img2 = nils.load(sifn) - assert_true(isinstance(re_img2, spm2.Spm2AnalyzeImage)) + assert isinstance(re_img2, spm2.Spm2AnalyzeImage) assert_array_equal(re_img2.get_fdata(), data) assert_array_equal(re_img2.affine, affine) del re_img2 spm99.save(img, sifn) re_img3 = nils.load(sifn) - assert_true(isinstance(re_img3, - spm99.Spm99AnalyzeImage)) + assert isinstance(re_img3, + spm99.Spm99AnalyzeImage) assert_array_equal(re_img3.get_fdata(), data) assert_array_equal(re_img3.affine, affine) ni1.save(re_img3, nifn) del re_img3 re_img = nils.load(nifn) - assert_true(isinstance(re_img, ni1.Nifti1Image)) + assert isinstance(re_img, ni1.Nifti1Image) assert_array_equal(re_img.get_fdata(), data) assert_array_equal(re_img.affine, affine) del re_img @@ -159,13 +159,13 @@ def test_two_to_one(): affine[:3, 3] = [3, 2, 1] # single file format img = ni1.Nifti1Image(data, affine) - assert_equal(img.header['magic'], b'n+1') + assert img.header['magic'] == b'n+1' str_io = BytesIO() img.file_map['image'].fileobj = str_io # check that the single format vox offset stays at zero img.to_file_map() - assert_equal(img.header['magic'], b'n+1') - assert_equal(img.header['vox_offset'], 0) + assert img.header['magic'] == b'n+1' + assert img.header['vox_offset'] == 0 # make a new pair image, with the single image header pimg = ni1.Nifti1Pair(data, affine, img.header) isio = BytesIO() @@ -174,32 +174,32 @@ def test_two_to_one(): pimg.file_map['header'].fileobj = hsio pimg.to_file_map() # the offset stays at zero (but is 352 on disk) - assert_equal(pimg.header['magic'], b'ni1') - assert_equal(pimg.header['vox_offset'], 0) + assert pimg.header['magic'] == b'ni1' + assert pimg.header['vox_offset'] == 0 assert_array_equal(pimg.get_fdata(), data) # same for from_image, going from single image to pair format ana_img = ana.AnalyzeImage.from_image(img) - assert_equal(ana_img.header['vox_offset'], 0) + assert ana_img.header['vox_offset'] == 0 # back to the single image, save it again to a stringio str_io = BytesIO() img.file_map['image'].fileobj = str_io img.to_file_map() - assert_equal(img.header['vox_offset'], 0) + assert img.header['vox_offset'] == 0 aimg = ana.AnalyzeImage.from_image(img) - assert_equal(aimg.header['vox_offset'], 0) + assert aimg.header['vox_offset'] == 0 aimg = spm99.Spm99AnalyzeImage.from_image(img) - assert_equal(aimg.header['vox_offset'], 0) + assert aimg.header['vox_offset'] == 0 aimg = spm2.Spm2AnalyzeImage.from_image(img) - assert_equal(aimg.header['vox_offset'], 0) + assert aimg.header['vox_offset'] == 0 nfimg = ni1.Nifti1Pair.from_image(img) - assert_equal(nfimg.header['vox_offset'], 0) + assert nfimg.header['vox_offset'] == 0 # now set the vox offset directly hdr = nfimg.header hdr['vox_offset'] = 16 - assert_equal(nfimg.header['vox_offset'], 16) + assert nfimg.header['vox_offset'] == 16 # check it gets properly set by the nifti single image nfimg = ni1.Nifti1Image.from_image(img) - assert_equal(nfimg.header['vox_offset'], 0) + assert nfimg.header['vox_offset'] == 0 def test_negative_load_save(): @@ -260,7 +260,7 @@ def test_filename_save(): nils.save(img, path) rt_img = nils.load(path) assert_array_almost_equal(rt_img.get_fdata(), data) - assert_true(type(rt_img) is loadklass) + assert type(rt_img) is loadklass # delete image to allow file close. Otherwise windows # raises an error when trying to delete the directory del rt_img @@ -274,56 +274,56 @@ def test_analyze_detection(): def wat(hdr): return nils.which_analyze_type(hdr.binaryblock) n1_hdr = Nifti1Header(b'\0' * 348, check=False) - assert_equal(wat(n1_hdr), None) + assert wat(n1_hdr) == None n1_hdr['sizeof_hdr'] = 540 - assert_equal(wat(n1_hdr), 'nifti2') - assert_equal(wat(n1_hdr.as_byteswapped()), 'nifti2') + assert wat(n1_hdr) == 'nifti2' + assert wat(n1_hdr.as_byteswapped()) == 'nifti2' n1_hdr['sizeof_hdr'] = 348 - assert_equal(wat(n1_hdr), 'analyze') - assert_equal(wat(n1_hdr.as_byteswapped()), 'analyze') + assert wat(n1_hdr) == 'analyze' + assert wat(n1_hdr.as_byteswapped()) == 'analyze' n1_hdr['magic'] = b'n+1' - assert_equal(wat(n1_hdr), 'nifti1') - assert_equal(wat(n1_hdr.as_byteswapped()), 'nifti1') + assert wat(n1_hdr) == 'nifti1' + assert wat(n1_hdr.as_byteswapped()) == 'nifti1' n1_hdr['magic'] = b'ni1' - assert_equal(wat(n1_hdr), 'nifti1') - assert_equal(wat(n1_hdr.as_byteswapped()), 'nifti1') + assert wat(n1_hdr) == 'nifti1' + assert wat(n1_hdr.as_byteswapped()) == 'nifti1' # Doesn't matter what magic is if it's not a nifti1 magic n1_hdr['magic'] = b'ni2' - assert_equal(wat(n1_hdr), 'analyze') + assert wat(n1_hdr) == 'analyze' n1_hdr['sizeof_hdr'] = 0 n1_hdr['magic'] = b'' - assert_equal(wat(n1_hdr), None) + assert wat(n1_hdr) == None n1_hdr['magic'] = 'n+1' - assert_equal(wat(n1_hdr), 'nifti1') + assert wat(n1_hdr) == 'nifti1' n1_hdr['magic'] = 'ni1' - assert_equal(wat(n1_hdr), 'nifti1') + assert wat(n1_hdr) == 'nifti1' def test_guessed_image_type(): # Test whether we can guess the image type from example files - assert_equal(nils.guessed_image_type( - pjoin(DATA_PATH, 'example4d.nii.gz')), + assert (nils.guessed_image_type( + pjoin(DATA_PATH, 'example4d.nii.gz')) == Nifti1Image) - assert_equal(nils.guessed_image_type( - pjoin(DATA_PATH, 'nifti1.hdr')), + assert (nils.guessed_image_type( + pjoin(DATA_PATH, 'nifti1.hdr')) == Nifti1Pair) - assert_equal(nils.guessed_image_type( - pjoin(DATA_PATH, 'example_nifti2.nii.gz')), + assert (nils.guessed_image_type( + pjoin(DATA_PATH, 'example_nifti2.nii.gz')) == Nifti2Image) - assert_equal(nils.guessed_image_type( - pjoin(DATA_PATH, 'nifti2.hdr')), + assert (nils.guessed_image_type( + pjoin(DATA_PATH, 'nifti2.hdr')) == Nifti2Pair) - assert_equal(nils.guessed_image_type( - pjoin(DATA_PATH, 'tiny.mnc')), + assert (nils.guessed_image_type( + pjoin(DATA_PATH, 'tiny.mnc')) == Minc1Image) - assert_equal(nils.guessed_image_type( - pjoin(DATA_PATH, 'small.mnc')), + assert (nils.guessed_image_type( + pjoin(DATA_PATH, 'small.mnc')) == Minc2Image) - assert_equal(nils.guessed_image_type( - pjoin(DATA_PATH, 'test.mgz')), + assert (nils.guessed_image_type( + pjoin(DATA_PATH, 'test.mgz')) == MGHImage) - assert_equal(nils.guessed_image_type( - pjoin(DATA_PATH, 'analyze.hdr')), + assert (nils.guessed_image_type( + pjoin(DATA_PATH, 'analyze.hdr')) == Spm2AnalyzeImage) @@ -333,6 +333,6 @@ def test_fail_save(): affine = np.eye(4, dtype=np.float32) img = SpatialImage(dataobj, affine) # Fails because float16 is not supported. - with assert_raises(AttributeError): + with pytest.raises(AttributeError): nils.save(img, 'foo.nii.gz') del img diff --git a/nibabel/tests/test_image_types.py b/nibabel/tests/test_image_types.py index 3ffc65eead..632e23224d 100644 --- a/nibabel/tests/test_image_types.py +++ b/nibabel/tests/test_image_types.py @@ -20,7 +20,6 @@ Spm2AnalyzeImage, Spm99AnalyzeImage, MGHImage, all_image_classes) -from nose.tools import assert_true DATA_PATH = pjoin(dirname(__file__), 'data') @@ -64,7 +63,7 @@ def check_img(img_path, img_klass, sniff_mode, sniff, expect_success, 'sizeof_hdr', 0) current_sizeof_hdr = 0 if new_sniff is None else \ len(new_sniff[0]) - assert_true(current_sizeof_hdr >= expected_sizeof_hdr, new_msg) + assert current_sizeof_hdr >= expected_sizeof_hdr, new_msg # Check that the image type was recognized. new_msg = '%s (%s) image is%s a %s image.' % ( @@ -72,7 +71,7 @@ def check_img(img_path, img_klass, sniff_mode, sniff, expect_success, msg, '' if is_img else ' not', img_klass.__name__) - assert_true(is_img, new_msg) + assert is_img, new_msg if sniff_mode == 'vanilla': return new_sniff diff --git a/nibabel/tests/test_imageclasses.py b/nibabel/tests/test_imageclasses.py index 12232c42e4..8fc0da4908 100644 --- a/nibabel/tests/test_imageclasses.py +++ b/nibabel/tests/test_imageclasses.py @@ -15,9 +15,8 @@ from nibabel import imageclasses from nibabel.imageclasses import spatial_axes_first, class_map, ext_map -from nose.tools import (assert_true, assert_false, assert_equal) -from nibabel.testing import clear_and_catch_warnings +from nibabel.testing_pytest import clear_and_catch_warnings DATA_DIR = pjoin(dirname(__file__), 'data') @@ -37,26 +36,26 @@ def test_spatial_axes_first(): for img_class in (AnalyzeImage, Nifti1Image, Nifti2Image): data = np.zeros(shape) img = img_class(data, affine) - assert_true(spatial_axes_first(img)) + assert spatial_axes_first(img) # True for MINC images < 4D for fname in MINC_3DS: img = nib.load(pjoin(DATA_DIR, fname)) - assert_true(len(img.shape) == 3) - assert_true(spatial_axes_first(img)) + assert len(img.shape) == 3 + assert spatial_axes_first(img) # False for MINC images < 4D for fname in MINC_4DS: img = nib.load(pjoin(DATA_DIR, fname)) - assert_true(len(img.shape) == 4) - assert_false(spatial_axes_first(img)) + assert len(img.shape) == 4 + assert not spatial_axes_first(img) def test_deprecations(): with clear_and_catch_warnings(modules=[imageclasses]) as w: warnings.filterwarnings('always', category=DeprecationWarning) nifti_single = class_map['nifti_single'] - assert_equal(nifti_single['class'], Nifti1Image) - assert_equal(len(w), 1) + assert nifti_single['class'] == Nifti1Image + assert len(w) == 1 nifti_ext = ext_map['.nii'] - assert_equal(nifti_ext, 'nifti_single') - assert_equal(len(w), 2) + assert nifti_ext == 'nifti_single' + assert len(w) == 2 diff --git a/nibabel/tests/test_imageglobals.py b/nibabel/tests/test_imageglobals.py index f730a4db01..42cbe6fdce 100644 --- a/nibabel/tests/test_imageglobals.py +++ b/nibabel/tests/test_imageglobals.py @@ -8,10 +8,6 @@ ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## """ Tests for imageglobals module """ - -from nose.tools import (assert_true, assert_false, assert_raises, - assert_equal, assert_not_equal) - from .. import imageglobals as igs @@ -19,5 +15,5 @@ def test_errorlevel(): orig_level = igs.error_level for level in (10, 20, 30): with igs.ErrorLevel(level): - assert_equal(igs.error_level, level) - assert_equal(igs.error_level, orig_level) + assert igs.error_level == level + assert igs.error_level == orig_level diff --git a/nibabel/tests/test_keywordonly.py b/nibabel/tests/test_keywordonly.py index 0ef63d9b13..26e21ce02d 100644 --- a/nibabel/tests/test_keywordonly.py +++ b/nibabel/tests/test_keywordonly.py @@ -2,8 +2,7 @@ from ..keywordonly import kw_only_func, kw_only_meth -from nose.tools import assert_equal -from nose.tools import assert_raises +import pytest def test_kw_only_func(): @@ -11,23 +10,28 @@ def test_kw_only_func(): def func(an_arg): "My docstring" return an_arg - assert_equal(func(1), 1) - assert_raises(TypeError, func, 1, 2) + assert func(1) == 1 + with pytest.raises(TypeError): + func(1, 2) dec_func = kw_only_func(1)(func) - assert_equal(dec_func(1), 1) - assert_raises(TypeError, dec_func, 1, 2) - assert_raises(TypeError, dec_func, 1, akeyarg=3) - assert_equal(dec_func.__doc__, 'My docstring') + assert dec_func(1) == 1 + with pytest.raises(TypeError): + dec_func(1, 2) + with pytest.raises(TypeError): + dec_func(1, akeyarg=3) + assert dec_func.__doc__ == 'My docstring' @kw_only_func(1) def kw_func(an_arg, a_kwarg='thing'): "Another docstring" return an_arg, a_kwarg - assert_equal(kw_func(1), (1, 'thing')) - assert_raises(TypeError, kw_func, 1, 2) - assert_equal(kw_func(1, a_kwarg=2), (1, 2)) - assert_raises(TypeError, kw_func, 1, akeyarg=3) - assert_equal(kw_func.__doc__, 'Another docstring') + assert kw_func(1) == (1, 'thing') + with pytest.raises(TypeError): + kw_func(1, 2) + assert kw_func(1, a_kwarg=2) == (1, 2) + with pytest.raises(TypeError): + kw_func(1, akeyarg=3) + assert kw_func.__doc__ == 'Another docstring' class C(object): @@ -36,8 +40,10 @@ def kw_meth(self, an_arg, a_kwarg='thing'): "Method docstring" return an_arg, a_kwarg c = C() - assert_equal(c.kw_meth(1), (1, 'thing')) - assert_raises(TypeError, c.kw_meth, 1, 2) - assert_equal(c.kw_meth(1, a_kwarg=2), (1, 2)) - assert_raises(TypeError, c.kw_meth, 1, akeyarg=3) - assert_equal(c.kw_meth.__doc__, 'Method docstring') + assert c.kw_meth(1) == (1, 'thing') + with pytest.raises(TypeError): + c.kw_meth(1, 2) + assert c.kw_meth(1, a_kwarg=2) == (1, 2) + with pytest.raises(TypeError): + c.kw_meth(1, akeyarg=3) + assert c.kw_meth.__doc__ == 'Method docstring' diff --git a/nibabel/tests/test_loadsave.py b/nibabel/tests/test_loadsave.py index 3d7101b6d3..71f0435f1a 100644 --- a/nibabel/tests/test_loadsave.py +++ b/nibabel/tests/test_loadsave.py @@ -20,8 +20,7 @@ from numpy.testing import (assert_almost_equal, assert_array_equal) -from nose.tools import (assert_true, assert_false, assert_raises, - assert_equal, assert_not_equal) +import pytest data_path = pjoin(dirname(__file__), 'data') @@ -48,7 +47,7 @@ def test_read_img_data(): # These examples have null scaling - assert prefer=unscaled is the same dao = img.dataobj if hasattr(dao, 'slope') and hasattr(img.header, 'raw_data_from_fileobj'): - assert_equal((dao.slope, dao.inter), (1, 0)) + assert (dao.slope, dao.inter) == (1, 0) assert_array_equal(read_img_data(img, prefer='unscaled'), data) # Assert all caps filename works as well with TemporaryDirectory() as tmpdir: @@ -63,15 +62,16 @@ def test_read_img_data(): def test_file_not_found(): - assert_raises(FileNotFoundError, load, 'does_not_exist.nii.gz') + with pytest.raises(FileNotFoundError): + load('does_not_exist.nii.gz') def test_load_empty_image(): with InTemporaryDirectory(): open('empty.nii', 'w').close() - with assert_raises(ImageFileError) as err: + with pytest.raises(ImageFileError) as err: load('empty.nii') - assert_true(err.exception.args[0].startswith('Empty file: ')) + assert str(err.value).startswith('Empty file: ') def test_read_img_data_nifti(): @@ -86,13 +86,15 @@ def test_read_img_data_nifti(): img = img_class(data, np.eye(4)) img.set_data_dtype(out_dtype) # No filemap => error - assert_raises(ImageFileError, read_img_data, img) + with pytest.raises(ImageFileError): + read_img_data(img) # Make a filemap froot = 'an_image_{0}'.format(i) img.file_map = img.filespec_to_file_map(froot) # Trying to read from this filemap will generate an error because # we are going to read from files that do not exist - assert_raises(IOError, read_img_data, img) + with pytest.raises(IOError): + read_img_data(img) img.to_file_map() # Load - now the scaling and offset correctly applied img_fname = img.file_map['image'].filename @@ -127,8 +129,8 @@ def test_read_img_data_nifti(): else: new_inter = 0 # scaled scaling comes from new parameters in header - assert_true(np.allclose(actual_unscaled * 2.1 + new_inter, - read_img_data(img_back))) + assert np.allclose(actual_unscaled * 2.1 + new_inter, + read_img_data(img_back)) # Unscaled array didn't change assert_array_equal(actual_unscaled, read_img_data(img_back, prefer='unscaled')) diff --git a/nibabel/tests/test_minc1.py b/nibabel/tests/test_minc1.py index c7b044ed9b..5b53d021c4 100644 --- a/nibabel/tests/test_minc1.py +++ b/nibabel/tests/test_minc1.py @@ -24,10 +24,10 @@ from ..minc1 import Minc1File, Minc1Image, MincHeader from ..tmpdirs import InTemporaryDirectory -from ..testing import (assert_true, assert_equal, assert_false, assert_raises, assert_warns, - assert_array_equal, data_path, clear_and_catch_warnings) from ..deprecator import ExpiredDeprecationError -from ..testing_pytest import assert_data_similar +from ..testing_pytest import assert_data_similar, data_path, clear_and_catch_warnings +from numpy.testing import assert_array_equal +import pytest from . import test_spatialimages as tsi from .test_fileslice import slicer_samples @@ -107,14 +107,13 @@ def test_old_namespace(): aff = np.diag([2, 3, 4, 1]) from .. import Minc1Image, MincImage - assert_false(Minc1Image is MincImage) - with assert_raises(ExpiredDeprecationError): + assert Minc1Image is not MincImage + with pytest.raises(ExpiredDeprecationError): MincImage(arr, aff) - assert_equal(warns, []) # Another old name from ..minc1 import MincFile, Minc1File assert_false(MincFile is Minc1File) - with assert_raises(ExpiredDeprecationError): + with pytest.raises(ExpiredDeprecationError): mf = MincFile(netcdf_file(EG_FNAME)) @@ -129,12 +128,12 @@ def test_mincfile(self): for tp in self.test_files: mnc_obj = self.opener(tp['fname'], 'r') mnc = self.file_class(mnc_obj) - assert_equal(mnc.get_data_dtype().type, tp['dtype']) - assert_equal(mnc.get_data_shape(), tp['shape']) - assert_equal(mnc.get_zooms(), tp['zooms']) + assert mnc.get_data_dtype().type == tp['dtype'] + assert mnc.get_data_shape() == tp['shape'] + assert mnc.get_zooms() == tp['zooms'] assert_array_equal(mnc.get_affine(), tp['affine']) data = mnc.get_scaled_data() - assert_equal(data.shape, tp['shape']) + assert data.shape == tp['shape'] def test_mincfile_slicing(self): # Test slicing and scaling of mincfile data @@ -158,7 +157,7 @@ def test_load(self): for tp in self.test_files: img = load(tp['fname']) data = img.get_fdata() - assert_equal(data.shape, tp['shape']) + assert data.shape == tp['shape'] # min, max, mean values from read in SPM2 / minctools assert_data_similar(data, tp) # check if mnc can be converted to nifti @@ -172,7 +171,7 @@ def test_array_proxy_slicing(self): img = load(tp['fname']) arr = img.get_fdata() prox = img.dataobj - assert_true(prox.is_proxy) + assert prox.is_proxy for sliceobj in slicer_samples(img.shape): assert_array_equal(arr[sliceobj], prox[sliceobj]) @@ -202,8 +201,10 @@ def test_header_data_io(): bio = BytesIO() hdr = MincHeader() arr = np.arange(24).reshape((2, 3, 4)) - assert_raises(NotImplementedError, hdr.data_to_fileobj, arr, bio) - assert_raises(NotImplementedError, hdr.data_from_fileobj, bio) + with pytest.raises(NotImplementedError): + hdr.data_to_fileobj(arr, bio) + with pytest.raises(NotImplementedError): + hdr.data_from_fileobj(bio) class TestMinc1Image(tsi.TestSpatialImage): @@ -217,7 +218,7 @@ def test_data_to_from_fileobj(self): img = self.module.load(fpath) bio = BytesIO() arr = np.arange(24).reshape((2, 3, 4)) - assert_raises(NotImplementedError, - img.header.data_to_fileobj, arr, bio) - assert_raises(NotImplementedError, - img.header.data_from_fileobj, bio) + with pytest.raises(NotImplementedError): + img.header.data_to_fileobj(arr, bio) + with pytest.raises(NotImplementedError): + img.header.data_from_fileobj(bio) diff --git a/nibabel/tests/test_minc2.py b/nibabel/tests/test_minc2.py index f4367cbc11..5032f01480 100644 --- a/nibabel/tests/test_minc2.py +++ b/nibabel/tests/test_minc2.py @@ -15,9 +15,7 @@ from ..minc2 import Minc2File, Minc2Image from .._h5py_compat import h5py, have_h5py, setup_module -from nose.tools import (assert_true, assert_equal, assert_false, assert_raises) - -from ..testing import data_path +from ..testing_pytest import data_path from . import test_minc1 as tm2 diff --git a/nibabel/tests/test_minc2_data.py b/nibabel/tests/test_minc2_data.py index ebfafa938f..6d5a4b0e35 100644 --- a/nibabel/tests/test_minc2_data.py +++ b/nibabel/tests/test_minc2_data.py @@ -19,7 +19,6 @@ from .nibabel_data import get_nibabel_data, needs_nibabel_data from .. import load as top_load, Nifti1Image -from nose.tools import assert_equal from numpy.testing import (assert_array_equal, assert_almost_equal) MINC2_PATH = pjoin(get_nibabel_data(), 'nitest-minc2') @@ -58,14 +57,14 @@ class TestEPIFrame(object): def test_load(self): # Check highest level load of minc works img = self.opener(self.example_params['fname']) - assert_equal(img.shape, self.example_params['shape']) + assert img.shape == self.example_params['shape'] assert_almost_equal(img.header.get_zooms(), self.example_params['zooms'], 5) assert_almost_equal(img.affine, self.example_params['affine'], 4) - assert_equal(img.get_data_dtype().type, self.example_params['type']) + assert img.get_data_dtype().type == self.example_params['type'] # Check correspondence of data and recorded shape data = img.get_fdata() - assert_equal(data.shape, self.example_params['shape']) + assert data.shape == self.example_params['shape'] # min, max, mean values from read in SPM2 assert_almost_equal(data.min(), self.example_params['min'], 4) assert_almost_equal(data.max(), self.example_params['max'], 4) diff --git a/nibabel/tests/test_mriutils.py b/nibabel/tests/test_mriutils.py index 527afc61ba..8c6b198c95 100644 --- a/nibabel/tests/test_mriutils.py +++ b/nibabel/tests/test_mriutils.py @@ -10,12 +10,8 @@ """ -from numpy.testing import (assert_almost_equal, - assert_array_equal) - -from nose.tools import (assert_true, assert_false, assert_raises, - assert_equal, assert_not_equal) - +from numpy.testing import assert_almost_equal +import pytest from ..mriutils import calculate_dwell_time, MRIError @@ -28,5 +24,7 @@ def test_calculate_dwell_time(): 3.3 / (42.576 * 3.4 * 3 * 3)) # Echo train length of 1 is valid, but returns 0 dwell time assert_almost_equal(calculate_dwell_time(3.3, 1, 3), 0) - assert_raises(MRIError, calculate_dwell_time, 3.3, 0, 3.0) - assert_raises(MRIError, calculate_dwell_time, 3.3, 2, -0.1) + with pytest.raises(MRIError): + calculate_dwell_time(3.3, 0, 3.0) + with pytest.raises(MRIError): + calculate_dwell_time(3.3, 2, -0.1) From ab2f5dcc09e6b52f4b0cd7936862349bf51b46ac Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Fri, 15 Nov 2019 20:01:52 -0500 Subject: [PATCH 010/223] converting more tests --- .travis.yml | 1 + nibabel/optpkg.py | 1 + nibabel/tests/test_nibabel_data.py | 9 +- nibabel/tests/test_nifti1.py | 690 +++++++++++++++-------------- nibabel/tests/test_nifti2.py | 13 +- nibabel/tests/test_openers.py | 109 ++--- nibabel/tests/test_optpkg.py | 26 +- nibabel/tests/test_orientations.py | 99 ++--- nibabel/tests/test_parrec.py | 228 +++++----- nibabel/tests/test_parrec_data.py | 20 +- nibabel/tests/test_pkg_info.py | 92 ++-- nibabel/tests/test_processing.py | 77 ++-- nibabel/tests/test_proxy_api.py | 43 +- nibabel/tests/test_quaternions.py | 132 +++--- 14 files changed, 797 insertions(+), 743 deletions(-) diff --git a/.travis.yml b/.travis.yml index 43ddf9dde1..f4fff97719 100644 --- a/.travis.yml +++ b/.travis.yml @@ -133,6 +133,7 @@ script: pytest -v ../nibabel/tests/test_a*.py ../nibabel/tests/test_b*.py ../nibabel/tests/test_c*.py ../nibabel/tests/test_d*.py pytest -v../nibabel/tests/test_e*.py ../nibabel/tests/test_f*.py ../nibabel/tests/test_h*.py pytest -v../nibabel/tests/test_i*.py ../nibabel/tests/test_k*.py ../nibabel/tests/test_l*.py ../nibabel/tests/test_m*.py + pytest -v../nibabel/tests/test_n*.py ../nibabel/tests/test_o*.py ../nibabel/tests/test_p*.py ../nibabel/tests/test_q*.py pytest -v ../nibabel/tests/test_w*.py else false diff --git a/nibabel/optpkg.py b/nibabel/optpkg.py index d52329f186..f87f64da9f 100644 --- a/nibabel/optpkg.py +++ b/nibabel/optpkg.py @@ -115,6 +115,7 @@ def optional_package(name, trip_msg=None, min_version=None): % (name, name, exc)) pkg = TripWire(trip_msg) + # TODO dj: no clue why is it needed... def setup_module(): if have_nose: import nose diff --git a/nibabel/tests/test_nibabel_data.py b/nibabel/tests/test_nibabel_data.py index f804f7499f..86e94f5c34 100644 --- a/nibabel/tests/test_nibabel_data.py +++ b/nibabel/tests/test_nibabel_data.py @@ -6,7 +6,6 @@ from . import nibabel_data as nibd -from nose.tools import assert_equal MY_DIR = dirname(__file__) @@ -23,10 +22,10 @@ def test_get_nibabel_data(): # Test getting directory local_data = realpath(pjoin(MY_DIR, '..', '..', 'nibabel-data')) if isdir(local_data): - assert_equal(nibd.get_nibabel_data(), local_data) + assert nibd.get_nibabel_data() == local_data else: - assert_equal(nibd.get_nibabel_data(), '') + assert nibd.get_nibabel_data() == '' nibd.environ['NIBABEL_DATA_DIR'] = 'not_a_path' - assert_equal(nibd.get_nibabel_data(), '') + assert nibd.get_nibabel_data() == '' nibd.environ['NIBABEL_DATA_DIR'] = MY_DIR - assert_equal(nibd.get_nibabel_data(), MY_DIR) + assert nibd.get_nibabel_data() == MY_DIR diff --git a/nibabel/tests/test_nifti1.py b/nibabel/tests/test_nifti1.py index dd98972df5..ef663f6e7b 100644 --- a/nibabel/tests/test_nifti1.py +++ b/nibabel/tests/test_nifti1.py @@ -34,15 +34,14 @@ from numpy.testing import (assert_array_equal, assert_array_almost_equal, assert_almost_equal) -from nose.tools import (assert_true, assert_false, assert_equal, - assert_raises) -from ..testing import ( +from ..testing_pytest import ( clear_and_catch_warnings, data_path, runif_extra_has, suppress_warnings, ) +import pytest from . import test_analyze as tana from . import test_spm99analyze as tspm @@ -61,7 +60,43 @@ A[:3, :3] = np.array(R) * Z # broadcasting does the job A[:3, 3] = T - +HDE = HeaderDataError +header_examples_list = \ + [ + ((None, None), None, (None, None), (np.nan, np.nan)), + ((np.nan, None), None, (None, None), (np.nan, np.nan)), + ((None, np.nan), None, (None, None), (np.nan, np.nan)), + ((np.nan, np.nan), None, (None, None), (np.nan, np.nan)), + # Can only be one null + ((None, 0), HDE, (None, None), (np.nan, 0)), + ((np.nan, 0), HDE, (None, None), (np.nan, 0)), + ((1, None), HDE, (None, None), (1, np.nan)), + ((1, np.nan), HDE, (None, None), (1, np.nan)), + # Bad slope plus anything generates an error + ((0, 0), HDE, (None, None), (0, 0)), + ((0, None), HDE, (None, None), (0, np.nan)), + ((0, np.nan), HDE, (None, None), (0, np.nan)), + ((0, np.inf), HDE, (None, None), (0, np.inf)), + ((0, -np.inf), HDE, (None, None), (0, -np.inf)), + ((np.inf, 0), HDE, (None, None), (np.inf, 0)), + ((np.inf, None), HDE, (None, None), (np.inf, np.nan)), + ((np.inf, np.nan), HDE, (None, None), (np.inf, np.nan)), + ((np.inf, np.inf), HDE, (None, None), (np.inf, np.inf)), + ((np.inf, -np.inf), HDE, (None, None), (np.inf, -np.inf)), + ((-np.inf, 0), HDE, (None, None), (-np.inf, 0)), + ((-np.inf, None), HDE, (None, None), (-np.inf, np.nan)), + ((-np.inf, np.nan), HDE, (None, None), (-np.inf, np.nan)), + ((-np.inf, np.inf), HDE, (None, None), (-np.inf, np.inf)), + ((-np.inf, -np.inf), HDE, (None, None), (-np.inf, -np.inf)), + # Good slope and bad inter generates error for get_slope_inter + ((2, None), HDE, HDE, (2, np.nan)), + ((2, np.nan), HDE, HDE, (2, np.nan)), + ((2, np.inf), HDE, HDE, (2, np.inf)), + ((2, -np.inf), HDE, HDE, (2, -np.inf)), + # Good slope and inter - you guessed it + ((2, 0), None, (2, 0), (2, 0)), + ((2, 1), None, (2, 1), (2, 1)) + ] class TestNifti1PairHeader(tana.TestAnalyzeHeader, tspm.HeaderScalingMixin): header_class = Nifti1PairHeader example_file = header_file @@ -82,15 +117,15 @@ class TestNifti1PairHeader(tana.TestAnalyzeHeader, tspm.HeaderScalingMixin): def test_empty(self): tana.TestAnalyzeHeader.test_empty(self) hdr = self.header_class() - assert_equal(hdr['magic'], hdr.pair_magic) - assert_equal(hdr['scl_slope'], 1) - assert_equal(hdr['vox_offset'], 0) + assert hdr['magic'] == hdr.pair_magic + assert hdr['scl_slope'] == 1 + assert hdr['vox_offset'] == 0 def test_from_eg_file(self): hdr = self.header_class.from_fileobj(open(self.example_file, 'rb')) - assert_equal(hdr.endianness, '<') - assert_equal(hdr['magic'], hdr.pair_magic) - assert_equal(hdr['sizeof_hdr'], self.sizeof_hdr) + assert hdr.endianness == '<' + assert hdr['magic'] == hdr.pair_magic + assert hdr['sizeof_hdr'] == self.sizeof_hdr def test_data_scaling(self): # Test scaling in header @@ -109,7 +144,7 @@ def test_data_scaling(self): hdr.set_data_dtype(np.int8) hdr.set_slope_inter(1, 0) hdr.data_to_fileobj(data, S, rescale=True) - assert_false(np.allclose(hdr.get_slope_inter(), (1, 0))) + assert not np.allclose(hdr.get_slope_inter(), (1, 0)) rdata = hdr.data_from_fileobj(S) assert_array_almost_equal(data, rdata) # Without scaling does rounding, doesn't alter scaling @@ -133,62 +168,29 @@ def test_big_scaling(self): data = np.array([finf['min'], finf['max']], dtype=dtt)[:, None, None] hdr.data_to_fileobj(data, sio) data_back = hdr.data_from_fileobj(sio) - assert_true(np.allclose(data, data_back)) + assert np.allclose(data, data_back) def test_slope_inter(self): hdr = self.header_class() - nan, inf, minf = np.nan, np.inf, -np.inf - HDE = HeaderDataError - assert_equal(hdr.get_slope_inter(), (1.0, 0.0)) - for in_tup, exp_err, out_tup, raw_values in ( + assert hdr.get_slope_inter() == (1.0, 0.0) + for in_tup, exp_err, out_tup, raw_values in header_examples_list: # Null scalings - ((None, None), None, (None, None), (nan, nan)), - ((nan, None), None, (None, None), (nan, nan)), - ((None, nan), None, (None, None), (nan, nan)), - ((nan, nan), None, (None, None), (nan, nan)), - # Can only be one null - ((None, 0), HDE, (None, None), (nan, 0)), - ((nan, 0), HDE, (None, None), (nan, 0)), - ((1, None), HDE, (None, None), (1, nan)), - ((1, nan), HDE, (None, None), (1, nan)), - # Bad slope plus anything generates an error - ((0, 0), HDE, (None, None), (0, 0)), - ((0, None), HDE, (None, None), (0, nan)), - ((0, nan), HDE, (None, None), (0, nan)), - ((0, inf), HDE, (None, None), (0, inf)), - ((0, minf), HDE, (None, None), (0, minf)), - ((inf, 0), HDE, (None, None), (inf, 0)), - ((inf, None), HDE, (None, None), (inf, nan)), - ((inf, nan), HDE, (None, None), (inf, nan)), - ((inf, inf), HDE, (None, None), (inf, inf)), - ((inf, minf), HDE, (None, None), (inf, minf)), - ((minf, 0), HDE, (None, None), (minf, 0)), - ((minf, None), HDE, (None, None), (minf, nan)), - ((minf, nan), HDE, (None, None), (minf, nan)), - ((minf, inf), HDE, (None, None), (minf, inf)), - ((minf, minf), HDE, (None, None), (minf, minf)), - # Good slope and bad inter generates error for get_slope_inter - ((2, None), HDE, HDE, (2, nan)), - ((2, nan), HDE, HDE, (2, nan)), - ((2, inf), HDE, HDE, (2, inf)), - ((2, minf), HDE, HDE, (2, minf)), - # Good slope and inter - you guessed it - ((2, 0), None, (2, 0), (2, 0)), - ((2, 1), None, (2, 1), (2, 1))): hdr = self.header_class() if not exp_err is None: - assert_raises(exp_err, hdr.set_slope_inter, *in_tup) + with pytest.raises(exp_err): + hdr.set_slope_inter(*in_tup) in_list = [v if not v is None else np.nan for v in in_tup] hdr['scl_slope'], hdr['scl_inter'] = in_list else: hdr.set_slope_inter(*in_tup) if isinstance(out_tup, Exception): - assert_raises(out_tup, hdr.get_slope_inter) + with pytest.raises(out_tup): + hdr.get_slope_inter() else: - assert_equal(hdr.get_slope_inter(), out_tup) + assert hdr.get_slope_inter() == out_tup # Check set survives through checking hdr = self.header_class.from_header(hdr, check=True) - assert_equal(hdr.get_slope_inter(), out_tup) + assert hdr.get_slope_inter() == out_tup assert_array_equal([hdr['scl_slope'], hdr['scl_inter']], raw_values) @@ -203,8 +205,8 @@ def test_nifti_qfac_checks(self): # 0 is not hdr['pixdim'][0] = 0 fhdr, message, raiser = self.log_chk(hdr, 20) - assert_equal(fhdr['pixdim'][0], 1) - assert_equal(message, + assert fhdr['pixdim'][0] == 1 + assert (message == 'pixdim[0] (qfac) should be 1 ' '(default) or -1; setting qfac to 1') @@ -215,14 +217,14 @@ def test_nifti_qsform_checks(self): hdr = HC() hdr['qform_code'] = -1 fhdr, message, raiser = self.log_chk(hdr, 30) - assert_equal(fhdr['qform_code'], 0) - assert_equal(message, + assert fhdr['qform_code'] == 0 + assert (message == 'qform_code -1 not valid; setting to 0') hdr = HC() hdr['sform_code'] = -1 fhdr, message, raiser = self.log_chk(hdr, 30) - assert_equal(fhdr['sform_code'], 0) - assert_equal(message, + assert fhdr['sform_code'] == 0 + assert (message == 'sform_code -1 not valid; setting to 0') def test_nifti_xform_codes(self): @@ -231,14 +233,16 @@ def test_nifti_xform_codes(self): affine = np.eye(4) for code in nifti1.xform_codes.keys(): hdr.set_qform(affine, code) - assert_equal(hdr['qform_code'], nifti1.xform_codes[code]) + assert hdr['qform_code'] == nifti1.xform_codes[code] hdr.set_sform(affine, code) - assert_equal(hdr['sform_code'], nifti1.xform_codes[code]) + assert hdr['sform_code'] == nifti1.xform_codes[code] # Raise KeyError on unknown code for bad_code in (-1, 6, 10): - assert_raises(KeyError, hdr.set_qform, affine, bad_code) - assert_raises(KeyError, hdr.set_sform, affine, bad_code) + with pytest.raises(KeyError): + hdr.set_qform(affine, bad_code) + with pytest.raises(KeyError): + hdr.set_sform(affine, bad_code) def test_magic_offset_checks(self): # magic and offset @@ -246,8 +250,8 @@ def test_magic_offset_checks(self): hdr = HC() hdr['magic'] = 'ooh' fhdr, message, raiser = self.log_chk(hdr, 45) - assert_equal(fhdr['magic'], b'ooh') - assert_equal(message, + assert fhdr['magic'] == b'ooh' + assert (message == 'magic string "ooh" is not valid; ' 'leaving as is, but future errors are likely') # For pairs, any offset is OK, but should be divisible by 16 @@ -263,8 +267,8 @@ def test_magic_offset_checks(self): self.assert_no_log_err(hdr) hdr['vox_offset'] = bad_spm fhdr, message, raiser = self.log_chk(hdr, 30) - assert_equal(fhdr['vox_offset'], bad_spm) - assert_equal(message, + assert fhdr['vox_offset'] == bad_spm + assert (message == 'vox offset (={0:g}) not divisible by 16, ' 'not SPM compatible; leaving at current ' 'value'.format(bad_spm)) @@ -272,8 +276,8 @@ def test_magic_offset_checks(self): hdr['magic'] = hdr.single_magic hdr['vox_offset'] = 10 fhdr, message, raiser = self.log_chk(hdr, 40) - assert_equal(fhdr['vox_offset'], hdr.single_vox_offset) - assert_equal(message, + assert fhdr['vox_offset'] == hdr.single_vox_offset + assert (message == 'vox offset 10 too low for single ' 'file nifti1; setting to minimum value ' 'of ' + str(hdr.single_vox_offset)) @@ -285,14 +289,14 @@ def test_freesurfer_large_vector_hack(self): # The standard case hdr = HC() hdr.set_data_shape((2, 3, 4)) - assert_equal(hdr.get_data_shape(), (2, 3, 4)) - assert_equal(hdr['glmin'], 0) + assert hdr.get_data_shape() == (2, 3, 4) + assert hdr['glmin'] == 0 # Just left of the freesurfer case dim_type = hdr.template_dtype['dim'].base glmin = hdr.template_dtype['glmin'].base too_big = int(np.iinfo(dim_type).max) + 1 hdr.set_data_shape((too_big - 1, 1, 1)) - assert_equal(hdr.get_data_shape(), (too_big - 1, 1, 1)) + assert hdr.get_data_shape() == (too_big - 1, 1, 1) # The freesurfer case full_shape = (too_big, 1, 1, 1, 1, 1, 1) for dim in range(3, 8): @@ -300,39 +304,37 @@ def test_freesurfer_large_vector_hack(self): expected_dim = np.array([dim, -1, 1, 1, 1, 1, 1, 1]) with suppress_warnings(): hdr.set_data_shape(full_shape[:dim]) - assert_equal(hdr.get_data_shape(), full_shape[:dim]) + assert hdr.get_data_shape() == full_shape[:dim] assert_array_equal(hdr['dim'], expected_dim) - assert_equal(hdr['glmin'], too_big) + assert hdr['glmin'] == too_big # Allow the fourth dimension to vary with suppress_warnings(): hdr.set_data_shape((too_big, 1, 1, 4)) - assert_equal(hdr.get_data_shape(), (too_big, 1, 1, 4)) + assert hdr.get_data_shape() == (too_big, 1, 1, 4) assert_array_equal(hdr['dim'][:5], np.array([4, -1, 1, 1, 4])) # This only works when the first 3 dimensions are -1, 1, 1 - assert_raises(HeaderDataError, hdr.set_data_shape, (too_big,)) - assert_raises(HeaderDataError, hdr.set_data_shape, (too_big, 1)) - assert_raises(HeaderDataError, hdr.set_data_shape, (too_big, 1, 2)) - assert_raises(HeaderDataError, hdr.set_data_shape, (too_big, 2, 1)) - assert_raises(HeaderDataError, hdr.set_data_shape, (1, too_big)) - assert_raises(HeaderDataError, hdr.set_data_shape, (1, too_big, 1)) - assert_raises(HeaderDataError, hdr.set_data_shape, (1, 1, too_big)) - assert_raises(HeaderDataError, hdr.set_data_shape, (1, 1, 1, too_big)) + for args in [(too_big,), (too_big, 1), (too_big, 1, 2), (too_big, 2, 1), + (1, too_big), (1, too_big, 1), (1, 1, too_big), (1, 1, 1, too_big)]: + with pytest.raises(HeaderDataError): + hdr.set_data_shape(args) # Outside range of glmin raises error far_too_big = int(np.iinfo(glmin).max) + 1 with suppress_warnings(): hdr.set_data_shape((far_too_big - 1, 1, 1)) - assert_equal(hdr.get_data_shape(), (far_too_big - 1, 1, 1)) - assert_raises(HeaderDataError, hdr.set_data_shape, (far_too_big, 1, 1)) + assert hdr.get_data_shape() == (far_too_big - 1, 1, 1) + with pytest.raises(HeaderDataError): + hdr.set_data_shape((far_too_big, 1, 1)) # glmin of zero raises error (implausible vector length) hdr.set_data_shape((-1, 1, 1)) hdr['glmin'] = 0 - assert_raises(HeaderDataError, hdr.get_data_shape) + with pytest.raises(HeaderDataError): + hdr.get_data_shape() # Lists or tuples or arrays will work for setting shape for shape in ((too_big - 1, 1, 1), (too_big, 1, 1)): for constructor in (list, tuple, np.array): with suppress_warnings(): hdr.set_data_shape(constructor(shape)) - assert_equal(hdr.get_data_shape(), shape) + assert hdr.get_data_shape() == shape @needs_nibabel_data('nitest-freesurfer') def test_freesurfer_ico7_hack(self): @@ -343,24 +345,24 @@ def test_freesurfer_ico7_hack(self): for dim in range(3, 8): expected_dim = np.array([dim, 27307, 1, 6, 1, 1, 1, 1]) hdr.set_data_shape(full_shape[:dim]) - assert_equal(hdr.get_data_shape(), full_shape[:dim]) + assert hdr.get_data_shape() == full_shape[:dim] assert_array_equal(hdr._structarr['dim'], expected_dim) # Only works on dimensions >= 3 - assert_raises(HeaderDataError, hdr.set_data_shape, full_shape[:1]) - assert_raises(HeaderDataError, hdr.set_data_shape, full_shape[:2]) - # Bad shapes - assert_raises(HeaderDataError, hdr.set_data_shape, (163842, 2, 1)) - assert_raises(HeaderDataError, hdr.set_data_shape, (163842, 1, 2)) - assert_raises(HeaderDataError, hdr.set_data_shape, (1, 163842, 1)) - assert_raises(HeaderDataError, hdr.set_data_shape, (1, 1, 163842)) - assert_raises(HeaderDataError, hdr.set_data_shape, (1, 1, 1, 163842)) + for args in [ + # Only works on dimensions >= 3 + full_shape[:1], full_shape[:2], + # Bad shapes + (163842, 2, 1), (163842, 1, 2), (1, 163842, 1), + (1, 1, 163842), (1, 1, 1, 163842)]: + with pytest.raises(HeaderDataError): + hdr.set_data_shape(args) # Test consistency of data in .mgh and mri_convert produced .nii nitest_path = os.path.join(get_nibabel_data(), 'nitest-freesurfer') mgh = mghload(os.path.join(nitest_path, 'fsaverage', 'surf', 'lh.orig.avg.area.mgh')) nii = load(os.path.join(nitest_path, 'derivative', 'fsaverage', 'surf', 'lh.orig.avg.area.nii')) - assert_equal(mgh.shape, nii.shape) + assert mgh.shape == nii.shape assert_array_equal(mgh.get_fdata(), nii.get_fdata()) assert_array_equal(nii.header._structarr['dim'][1:4], np.array([27307, 1, 6])) @@ -368,7 +370,7 @@ def test_freesurfer_ico7_hack(self): with InTemporaryDirectory(): nii.to_filename('test.nii') nii2 = load('test.nii') - assert_equal(nii.shape, nii2.shape) + assert nii.shape == nii2.shape assert_array_equal(nii.get_fdata(), nii2.get_fdata()) assert_array_equal(nii.affine, nii2.affine) @@ -379,8 +381,8 @@ def test_qform_sform(self): empty_sform = np.zeros((4, 4)) empty_sform[-1, -1] = 1 assert_array_equal(hdr.get_sform(), empty_sform) - assert_equal(hdr.get_qform(coded=True), (None, 0)) - assert_equal(hdr.get_sform(coded=True), (None, 0)) + assert hdr.get_qform(coded=True) == (None, 0) + assert hdr.get_sform(coded=True) == (None, 0) # Affines with no shears nice_aff = np.diag([2, 3, 4, 1]) another_aff = np.diag([3, 4, 5, 1]) @@ -388,39 +390,39 @@ def test_qform_sform(self): nasty_aff = from_matvec(np.arange(9).reshape((3, 3)), [9, 10, 11]) nasty_aff[0, 0] = 1 # Make full rank fixed_aff = unshear_44(nasty_aff) - assert_false(np.allclose(fixed_aff, nasty_aff)) + assert not np.allclose(fixed_aff, nasty_aff) for in_meth, out_meth in ((hdr.set_qform, hdr.get_qform), (hdr.set_sform, hdr.get_sform)): in_meth(nice_aff, 2) aff, code = out_meth(coded=True) assert_array_equal(aff, nice_aff) - assert_equal(code, 2) + assert code == 2 assert_array_equal(out_meth(), nice_aff) # non coded # Affine may be passed if code == 0, and will get set into header, # but the returned affine with 'coded=True' will be None. in_meth(another_aff, 0) - assert_equal(out_meth(coded=True), (None, 0)) # coded -> None + assert out_meth(coded=True) == (None, 0) # coded -> None assert_array_almost_equal(out_meth(), another_aff) # else -> input # Default qform code when previous == 0 is 2 in_meth(nice_aff) aff, code = out_meth(coded=True) - assert_equal(code, 2) + assert code == 2 # Unless code was non-zero before in_meth(nice_aff, 1) in_meth(nice_aff) aff, code = out_meth(coded=True) - assert_equal(code, 1) + assert code == 1 # Can set code without modifying affine, by passing affine=None assert_array_equal(aff, nice_aff) # affine same as before in_meth(None, 3) aff, code = out_meth(coded=True) assert_array_equal(aff, nice_aff) # affine same as before - assert_equal(code, 3) + assert code == 3 # affine is None on its own, or with code==0, resets code to 0 in_meth(None, 0) - assert_equal(out_meth(coded=True), (None, 0)) + assert out_meth(coded=True) == (None, 0) in_meth(None) - assert_equal(out_meth(coded=True), (None, 0)) + assert out_meth(coded=True) == (None, 0) # List works as input in_meth(nice_aff.tolist()) assert_array_equal(out_meth(), nice_aff) @@ -429,17 +431,18 @@ def test_qform_sform(self): hdr.set_qform(nasty_aff, 1) assert_array_almost_equal(hdr.get_qform(), fixed_aff) # Unless allow_shears is False - assert_raises(HeaderDataError, hdr.set_qform, nasty_aff, 1, False) + with pytest.raises(HeaderDataError): + hdr.set_qform(nasty_aff, 1, False) # Reset sform, give qform a code, to test sform hdr.set_sform(None) hdr.set_qform(nice_aff, 1) # Check sform unchanged by setting qform - assert_equal(hdr.get_sform(coded=True), (None, 0)) + assert hdr.get_sform(coded=True) == (None, 0) # Setting does change the sform ouput hdr.set_sform(nasty_aff, 1) aff, code = hdr.get_sform(coded=True) assert_array_equal(aff, nasty_aff) - assert_equal(code, 1) + assert code == 1 def test_datatypes(self): hdr = self.header_class() @@ -448,9 +451,7 @@ def test_datatypes(self): if dt == np.void: continue hdr.set_data_dtype(code) - (assert_equal, - hdr.get_data_dtype(), - data_type_codes.dtype[code]) + assert hdr.get_data_dtype(), data_type_codes.dtype[code] # Check that checks also see new datatypes hdr.set_data_dtype(np.complex128) hdr.check_fix() @@ -460,11 +461,11 @@ def test_quaternion(self): hdr['quatern_b'] = 0 hdr['quatern_c'] = 0 hdr['quatern_d'] = 0 - assert_true(np.allclose(hdr.get_qform_quaternion(), [1.0, 0, 0, 0])) + assert np.allclose(hdr.get_qform_quaternion(), [1.0, 0, 0, 0]) hdr['quatern_b'] = 1 hdr['quatern_c'] = 0 hdr['quatern_d'] = 0 - assert_true(np.allclose(hdr.get_qform_quaternion(), [0, 1, 0, 0])) + assert np.allclose(hdr.get_qform_quaternion(), [0, 1, 0, 0]) # Check threshold set correctly for float32 hdr['quatern_b'] = 1 + np.finfo(self.quat_dtype).eps assert_array_almost_equal(hdr.get_qform_quaternion(), [0, 1, 0, 0]) @@ -474,35 +475,36 @@ def test_qform(self): ehdr = self.header_class() ehdr.set_qform(A) qA = ehdr.get_qform() - assert_true, np.allclose(A, qA, atol=1e-5) - assert_true, np.allclose(Z, ehdr['pixdim'][1:4]) + assert np.allclose(A, qA, atol=1e-5) + assert np.allclose(Z, ehdr['pixdim'][1:4]) xfas = nifti1.xform_codes - assert_true, ehdr['qform_code'] == xfas['aligned'] + assert ehdr['qform_code'] == xfas['aligned'] ehdr.set_qform(A, 'scanner') - assert_true, ehdr['qform_code'] == xfas['scanner'] + assert ehdr['qform_code'] == xfas['scanner'] ehdr.set_qform(A, xfas['aligned']) - assert_true, ehdr['qform_code'] == xfas['aligned'] + assert ehdr['qform_code'] == xfas['aligned'] # Test pixdims[1,2,3] are checked for negatives for dims in ((-1, 1, 1), (1, -1, 1), (1, 1, -1)): ehdr['pixdim'][1:4] = dims - assert_raises(HeaderDataError, ehdr.get_qform) + with pytest.raises(HeaderDataError): + ehdr.get_qform() def test_sform(self): # Test roundtrip case ehdr = self.header_class() ehdr.set_sform(A) sA = ehdr.get_sform() - assert_true, np.allclose(A, sA, atol=1e-5) + assert np.allclose(A, sA, atol=1e-5) xfas = nifti1.xform_codes - assert_true, ehdr['sform_code'] == xfas['aligned'] + assert ehdr['sform_code'] == xfas['aligned'] ehdr.set_sform(A, 'scanner') - assert_true, ehdr['sform_code'] == xfas['scanner'] + assert ehdr['sform_code'] == xfas['scanner'] ehdr.set_sform(A, xfas['aligned']) - assert_true, ehdr['sform_code'] == xfas['aligned'] + assert ehdr['sform_code'] == xfas['aligned'] def test_dim_info(self): ehdr = self.header_class() - assert_true(ehdr.get_dim_info() == (None, None, None)) + assert ehdr.get_dim_info() == (None, None, None) for info in ((0, 2, 1), (None, None, None), (0, 2, None), @@ -511,18 +513,21 @@ def test_dim_info(self): (None, None, 1), ): ehdr.set_dim_info(*info) - assert_true(ehdr.get_dim_info() == info) + assert ehdr.get_dim_info() == info def test_slice_times(self): hdr = self.header_class() # error if slice dimension not specified - assert_raises(HeaderDataError, hdr.get_slice_times) + with pytest.raises(HeaderDataError): + hdr.get_slice_times() hdr.set_dim_info(slice=2) # error if slice dimension outside shape - assert_raises(HeaderDataError, hdr.get_slice_times) + with pytest.raises(HeaderDataError): + hdr.get_slice_times() hdr.set_data_shape((1, 1, 7)) # error if slice duration not set - assert_raises(HeaderDataError, hdr.get_slice_times) + with pytest.raises(HeaderDataError): + hdr.get_slice_times() hdr.set_slice_duration(0.1) # We need a function to print out the Nones and floating point # values in a predictable way, for the tests below. @@ -530,51 +535,56 @@ def test_slice_times(self): _print_me = lambda s: list(map(_stringer, s)) # The following examples are from the nifti1.h documentation. hdr['slice_code'] = slice_order_codes['sequential increasing'] - assert_equal(_print_me(hdr.get_slice_times()), + assert (_print_me(hdr.get_slice_times()) == ['0.0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6']) hdr['slice_start'] = 1 hdr['slice_end'] = 5 - assert_equal(_print_me(hdr.get_slice_times()), + assert (_print_me(hdr.get_slice_times()) == [None, '0.0', '0.1', '0.2', '0.3', '0.4', None]) hdr['slice_code'] = slice_order_codes['sequential decreasing'] - assert_equal(_print_me(hdr.get_slice_times()), + assert (_print_me(hdr.get_slice_times()) == [None, '0.4', '0.3', '0.2', '0.1', '0.0', None]) hdr['slice_code'] = slice_order_codes['alternating increasing'] - assert_equal(_print_me(hdr.get_slice_times()), + assert (_print_me(hdr.get_slice_times()) == [None, '0.0', '0.3', '0.1', '0.4', '0.2', None]) hdr['slice_code'] = slice_order_codes['alternating decreasing'] - assert_equal(_print_me(hdr.get_slice_times()), + assert (_print_me(hdr.get_slice_times()) == [None, '0.2', '0.4', '0.1', '0.3', '0.0', None]) hdr['slice_code'] = slice_order_codes['alternating increasing 2'] - assert_equal(_print_me(hdr.get_slice_times()), + assert (_print_me(hdr.get_slice_times()) == [None, '0.2', '0.0', '0.3', '0.1', '0.4', None]) hdr['slice_code'] = slice_order_codes['alternating decreasing 2'] - assert_equal(_print_me(hdr.get_slice_times()), + assert (_print_me(hdr.get_slice_times()) == [None, '0.4', '0.1', '0.3', '0.0', '0.2', None]) # test set hdr = self.header_class() hdr.set_dim_info(slice=2) # need slice dim to correspond with shape times = [None, 0.2, 0.4, 0.1, 0.3, 0.0, None] - assert_raises(HeaderDataError, hdr.set_slice_times, times) + with pytest.raises(HeaderDataError): + hdr.set_slice_times(times) hdr.set_data_shape([1, 1, 7]) - assert_raises(HeaderDataError, hdr.set_slice_times, - times[:-1]) # wrong length - assert_raises(HeaderDataError, hdr.set_slice_times, - (None,) * len(times)) # all None + with pytest.raises(HeaderDataError): + # wrong length + hdr.set_slice_times(times[:-1]) + with pytest.raises(HeaderDataError): + # all None + hdr.set_slice_times((None,) * len(times)) n_mid_times = times[:] n_mid_times[3] = None - assert_raises(HeaderDataError, hdr.set_slice_times, - n_mid_times) # None in middle + with pytest.raises(HeaderDataError): + # None in middle + hdr.set_slice_times(n_mid_times) funny_times = times[:] funny_times[3] = 0.05 - assert_raises(HeaderDataError, hdr.set_slice_times, - funny_times) # can't get single slice duration + with pytest.raises(HeaderDataError): + # can't get single slice duration + hdr.set_slice_times(funny_times) hdr.set_slice_times(times) - assert_equal(hdr.get_value_label('slice_code'), + assert (hdr.get_value_label('slice_code') == 'alternating decreasing') - assert_equal(hdr['slice_start'], 1) - assert_equal(hdr['slice_end'], 5) + assert hdr['slice_start'] == 1 + assert hdr['slice_end'] == 5 assert_array_almost_equal(hdr['slice_duration'], 0.1) # Ambiguous case @@ -587,121 +597,119 @@ def test_slice_times(self): hdr2.set_slice_times([0.1, 0]) assert len(w) == 1 # but always must be choosing sequential one first - assert_equal(hdr2.get_value_label('slice_code'), 'sequential decreasing') + assert hdr2.get_value_label('slice_code') == 'sequential decreasing' # and the other direction hdr2.set_slice_times([0, 0.1]) - assert_equal(hdr2.get_value_label('slice_code'), 'sequential increasing') + assert hdr2.get_value_label('slice_code') == 'sequential increasing' def test_intents(self): ehdr = self.header_class() ehdr.set_intent('t test', (10,), name='some score') - assert_equal(ehdr.get_intent(), + assert (ehdr.get_intent() == ('t test', (10.0,), 'some score')) # unknown intent name or code - unknown name will fail even when # allow_unknown=True - assert_raises(KeyError, ehdr.set_intent, 'no intention') - assert_raises(KeyError, ehdr.set_intent, 'no intention', - allow_unknown=True) - assert_raises(KeyError, ehdr.set_intent, 32767) + with pytest.raises(KeyError): + ehdr.set_intent('no intention') + with pytest.raises(KeyError): + ehdr.set_intent('no intention', allow_unknown=True) + with pytest.raises(KeyError): + ehdr.set_intent(32767) # too many parameters - assert_raises(HeaderDataError, ehdr.set_intent, 't test', (10, 10)) + with pytest.raises(HeaderDataError): + ehdr.set_intent('t test', (10, 10)) # too few parameters - assert_raises(HeaderDataError, ehdr.set_intent, 'f test', (10,)) + with pytest.raises(HeaderDataError): + ehdr.set_intent('f test', (10,)) # check unset parameters are set to 0, and name to '' ehdr.set_intent('t test') - assert_equal((ehdr['intent_p1'], ehdr['intent_p2'], ehdr['intent_p3']), + assert ((ehdr['intent_p1'], ehdr['intent_p2'], ehdr['intent_p3']) == (0, 0, 0)) - assert_equal(ehdr['intent_name'], b'') + assert ehdr['intent_name'] == b'' ehdr.set_intent('t test', (10,)) - assert_equal((ehdr['intent_p2'], ehdr['intent_p3']), (0, 0)) + assert (ehdr['intent_p2'], ehdr['intent_p3']) == (0, 0) # store intent that is not in nifti1.intent_codes recoder ehdr.set_intent(9999, allow_unknown=True) - assert_equal(ehdr.get_intent(), ('unknown code 9999', (), '')) - assert_equal(ehdr.get_intent('code'), (9999, (), '')) + assert ehdr.get_intent() == ('unknown code 9999', (), '') + assert ehdr.get_intent('code') == (9999, (), '') ehdr.set_intent(9999, name='custom intent', allow_unknown=True) - assert_equal(ehdr.get_intent(), + assert (ehdr.get_intent() == ('unknown code 9999', (), 'custom intent')) - assert_equal(ehdr.get_intent('code'), (9999, (), 'custom intent')) + assert ehdr.get_intent('code') == (9999, (), 'custom intent') # store unknown intent with parameters. set_intent will set the # parameters, but get_intent won't return them ehdr.set_intent(code=9999, params=(1, 2, 3), allow_unknown=True) - assert_equal(ehdr.get_intent(), ('unknown code 9999', (), '')) - assert_equal(ehdr.get_intent('code'), (9999, (), '')) + assert ehdr.get_intent() == ('unknown code 9999', (), '') + assert ehdr.get_intent('code') == (9999, (), '') # unknown intent requires either zero, or three, parameters - assert_raises(HeaderDataError, ehdr.set_intent, 999, (1,), - allow_unknown=True) - assert_raises(HeaderDataError, ehdr.set_intent, 999, (1,2), - allow_unknown=True) + with pytest.raises(HeaderDataError): + ehdr.set_intent(999, (1,), allow_unknown=True) + with pytest.raises(HeaderDataError): + ehdr.set_intent(999, (1,2), allow_unknown=True) def test_set_slice_times(self): hdr = self.header_class() hdr.set_dim_info(slice=2) hdr.set_data_shape([1, 1, 7]) hdr.set_slice_duration(0.1) - times = [0] * 6 - assert_raises(HeaderDataError, hdr.set_slice_times, times) - times = [None] * 7 - assert_raises(HeaderDataError, hdr.set_slice_times, times) - times = [None, 0, 1, None, 3, 4, None] - assert_raises(HeaderDataError, hdr.set_slice_times, times) - times = [None, 0, 1, 2.1, 3, 4, None] - assert_raises(HeaderDataError, hdr.set_slice_times, times) - times = [None, 0, 4, 3, 2, 1, None] - assert_raises(HeaderDataError, hdr.set_slice_times, times) + for times in [[0] * 6, [None] * 7, [None, 0, 1, None, 3, 4, None], + [None, 0, 1, 2.1, 3, 4, None], [None, 0, 4, 3, 2, 1, None]]: + with pytest.raises(HeaderDataError): + hdr.set_slice_times(times) times = [0, 1, 2, 3, 4, 5, 6] hdr.set_slice_times(times) - assert_equal(hdr['slice_code'], 1) - assert_equal(hdr['slice_start'], 0) - assert_equal(hdr['slice_end'], 6) - assert_equal(hdr['slice_duration'], 1.0) + assert hdr['slice_code'] == 1 + assert hdr['slice_start'] == 0 + assert hdr['slice_end'] == 6 + assert hdr['slice_duration'] == 1.0 times = [None, 0, 1, 2, 3, 4, None] hdr.set_slice_times(times) - assert_equal(hdr['slice_code'], 1) - assert_equal(hdr['slice_start'], 1) - assert_equal(hdr['slice_end'], 5) - assert_equal(hdr['slice_duration'], 1.0) + assert hdr['slice_code'] == 1 + assert hdr['slice_start'] == 1 + assert hdr['slice_end'] == 5 + assert hdr['slice_duration'] == 1.0 times = [None, 0.4, 0.3, 0.2, 0.1, 0, None] hdr.set_slice_times(times) - assert_true(np.allclose(hdr['slice_duration'], 0.1)) + assert np.allclose(hdr['slice_duration'], 0.1) times = [None, 4, 3, 2, 1, 0, None] hdr.set_slice_times(times) - assert_equal(hdr['slice_code'], 2) + assert hdr['slice_code'] == 2 times = [None, 0, 3, 1, 4, 2, None] hdr.set_slice_times(times) - assert_equal(hdr['slice_code'], 3) + assert hdr['slice_code'] == 3 times = [None, 2, 4, 1, 3, 0, None] hdr.set_slice_times(times) - assert_equal(hdr['slice_code'], 4) + assert hdr['slice_code'] == 4 times = [None, 2, 0, 3, 1, 4, None] hdr.set_slice_times(times) - assert_equal(hdr['slice_code'], 5) + assert hdr['slice_code'] == 5 times = [None, 4, 1, 3, 0, 2, None] hdr.set_slice_times(times) - assert_equal(hdr['slice_code'], 6) + assert hdr['slice_code'] == 6 def test_xyzt_units(self): hdr = self.header_class() - assert_equal(hdr.get_xyzt_units(), ('unknown', 'unknown')) + assert hdr.get_xyzt_units() == ('unknown', 'unknown') hdr.set_xyzt_units('mm', 'sec') - assert_equal(hdr.get_xyzt_units(), ('mm', 'sec')) + assert hdr.get_xyzt_units() == ('mm', 'sec') hdr.set_xyzt_units() - assert_equal(hdr.get_xyzt_units(), ('unknown', 'unknown')) + assert hdr.get_xyzt_units() == ('unknown', 'unknown') def test_recoded_fields(self): hdr = self.header_class() - assert_equal(hdr.get_value_label('qform_code'), 'unknown') + assert hdr.get_value_label('qform_code') == 'unknown' hdr['qform_code'] = 3 - assert_equal(hdr.get_value_label('qform_code'), 'talairach') - assert_equal(hdr.get_value_label('sform_code'), 'unknown') + assert hdr.get_value_label('qform_code') == 'talairach' + assert hdr.get_value_label('sform_code') == 'unknown' hdr['sform_code'] = 3 - assert_equal(hdr.get_value_label('sform_code'), 'talairach') - assert_equal(hdr.get_value_label('intent_code'), 'none') + assert hdr.get_value_label('sform_code') == 'talairach' + assert hdr.get_value_label('intent_code') == 'none' hdr.set_intent('t test', (10,), name='some score') - assert_equal(hdr.get_value_label('intent_code'), 't test') - assert_equal(hdr.get_value_label('slice_code'), 'unknown') + assert hdr.get_value_label('intent_code') == 't test' + assert hdr.get_value_label('slice_code') == 'unknown' hdr['slice_code'] = 4 # alternating decreasing - assert_equal(hdr.get_value_label('slice_code'), + assert (hdr.get_value_label('slice_code') == 'alternating decreasing') @@ -721,9 +729,9 @@ class TestNifti1SingleHeader(TestNifti1PairHeader): def test_empty(self): tana.TestAnalyzeHeader.test_empty(self) hdr = self.header_class() - assert_equal(hdr['magic'], hdr.single_magic) - assert_equal(hdr['scl_slope'], 1) - assert_equal(hdr['vox_offset'], 0) + assert hdr['magic'] == hdr.single_magic + assert hdr['scl_slope'] == 1 + assert hdr['vox_offset'] == 0 def test_binblock_is_file(self): # Override test that binary string is the same as the file on disk; in @@ -732,7 +740,7 @@ def test_binblock_is_file(self): hdr = self.header_class() str_io = BytesIO() hdr.write_to(str_io) - assert_equal(str_io.getvalue(), hdr.binaryblock + b'\x00' * 4) + assert str_io.getvalue() == hdr.binaryblock + b'\x00' * 4 def test_float128(self): hdr = self.header_class() @@ -740,9 +748,10 @@ def test_float128(self): ld_dt = np.dtype(np.longdouble) if have_binary128() or ld_dt == np.dtype(np.float64): hdr.set_data_dtype(np.longdouble) - assert_equal(hdr.get_data_dtype(), ld_dt) + assert hdr.get_data_dtype() == ld_dt else: - assert_raises(HeaderDataError, hdr.set_data_dtype, np.longdouble) + with pytest.raises(HeaderDataError): + hdr.set_data_dtype(np.longdouble) class TestNifti1Pair(tana.TestAnalyzeImage, tspm.ImageScalingMixin): @@ -792,13 +801,13 @@ def test_qform_cycle(self): # None affine img = img_klass(np.zeros((2, 3, 4)), None) hdr_back = self._qform_rt(img).header - assert_equal(hdr_back['qform_code'], 3) - assert_equal(hdr_back['sform_code'], 4) + assert hdr_back['qform_code'] == 3 + assert hdr_back['sform_code'] == 4 # Try non-None affine img = img_klass(np.zeros((2, 3, 4)), np.eye(4)) hdr_back = self._qform_rt(img).header - assert_equal(hdr_back['qform_code'], 3) - assert_equal(hdr_back['sform_code'], 4) + assert hdr_back['qform_code'] == 3 + assert hdr_back['sform_code'] == 4 # Modify affine in-place - does it hold? img.affine[0, 0] = 9 img.to_file_map() @@ -818,8 +827,8 @@ def test_header_update_affine(self): hdr.set_qform(aff, 2) hdr.set_sform(aff, 2) img.update_header() - assert_equal(hdr['sform_code'], 2) - assert_equal(hdr['qform_code'], 2) + assert hdr['sform_code'] == 2 + assert hdr['qform_code'] == 2 def test_set_qform(self): img = self.image_class(np.zeros((2, 3, 4)), @@ -835,12 +844,12 @@ def test_set_qform(self): # Set qform using new_affine img.set_qform(new_affine, 1) assert_array_almost_equal(img.get_qform(), new_affine) - assert_equal(hdr['qform_code'], 1) + assert hdr['qform_code'] == 1 # Image get is same as header get assert_array_almost_equal(img.get_qform(), new_affine) # Coded version of get gets same information qaff, code = img.get_qform(coded=True) - assert_equal(code, 1) + assert code == 1 assert_array_almost_equal(qaff, new_affine) # Image affine now reset to best affine (which is sform) assert_array_almost_equal(img.affine, hdr.get_best_affine()) @@ -852,7 +861,7 @@ def test_set_qform(self): assert_array_almost_equal(hdr.get_zooms(), [1.1, 1.1, 1.1]) img.set_qform(None) qaff, code = img.get_qform(coded=True) - assert_equal((qaff, code), (None, 0)) + assert (qaff, code) == (None, 0) assert_array_almost_equal(hdr.get_zooms(), [1.1, 1.1, 1.1]) # Best affine similarly assert_array_almost_equal(img.affine, hdr.get_best_affine()) @@ -860,14 +869,16 @@ def test_set_qform(self): img.set_sform(None) img.set_qform(new_affine, 1) qaff, code = img.get_qform(coded=True) - assert_equal(code, 1) + assert code == 1 assert_array_almost_equal(img.affine, new_affine) new_affine[0, 1] = 2 # If affine has has shear, should raise Error if strip_shears=False img.set_qform(new_affine, 2) - assert_raises(HeaderDataError, img.set_qform, new_affine, 2, False) + with pytest.raises(HeaderDataError): + img.set_qform(new_affine, 2, False) # Unexpected keyword raises error - assert_raises(TypeError, img.get_qform, strange=True) + with pytest.raises(TypeError): + img.get_qform(strange=True) # updating None affine, None header does not work, because None header # results in setting the sform to default img = self.image_class(np.zeros((2, 3, 4)), None) @@ -889,16 +900,16 @@ def test_set_sform(self): img.affine[:] = aff_affine assert_array_almost_equal(img.affine, aff_affine) # Sform, Qform codes are 'aligned', 'unknown' by default - assert_equal((hdr['sform_code'], hdr['qform_code']), (2, 0)) + assert (hdr['sform_code'], hdr['qform_code']) == (2, 0) # Set sform using new_affine when qform is 0 img.set_sform(new_affine, 1) - assert_equal(hdr['sform_code'], 1) + assert hdr['sform_code'] == 1 assert_array_almost_equal(hdr.get_sform(), new_affine) # Image get is same as header get assert_array_almost_equal(img.get_sform(), new_affine) # Coded version gives same result saff, code = img.get_sform(coded=True) - assert_equal(code, 1) + assert code == 1 assert_array_almost_equal(saff, new_affine) # Because we've reset the sform with update_affine, the affine changes assert_array_almost_equal(img.affine, hdr.get_best_affine()) @@ -915,22 +926,23 @@ def test_set_sform(self): img.set_qform(qform_affine, 1) img.set_sform(new_affine, 1) saff, code = img.get_sform(coded=True) - assert_equal(code, 1) + assert code == 1 assert_array_almost_equal(saff, new_affine) assert_array_almost_equal(img.affine, new_affine) # zooms follow qform assert_array_almost_equal(hdr.get_zooms(), [1.2, 1.2, 1.2]) # Clear sform using None, best_affine should fall back on qform img.set_sform(None) - assert_equal(hdr['sform_code'], 0) - assert_equal(hdr['qform_code'], 1) + assert hdr['sform_code'] == 0 + assert hdr['qform_code'] == 1 # Sform holds previous affine from last set assert_array_almost_equal(hdr.get_sform(), saff) # Image affine follows qform assert_array_almost_equal(img.affine, qform_affine) assert_array_almost_equal(hdr.get_best_affine(), img.affine) # Unexpected keyword raises error - assert_raises(TypeError, img.get_sform, strange=True) + with pytest.raises(TypeError): + img.get_sform(strange=True) # updating None affine should also work img = self.image_class(np.zeros((2, 3, 4)), None) new_affine = np.eye(4) @@ -971,8 +983,8 @@ def test_load_save(self): data = np.arange(np.prod(shape), dtype=npt).reshape(shape) affine = np.diag([1, 2, 3, 1]) img = IC(data, affine) - assert_equal(img.header.get_data_offset(), 0) - assert_equal(img.shape, shape) + assert img.header.get_data_offset() == 0 + assert img.shape == shape img.set_data_dtype(npt) img2 = bytesio_round_trip(img) assert_array_equal(img2.get_fdata(), data) @@ -981,11 +993,11 @@ def test_load_save(self): fname = os.path.join(tmpdir, 'test' + img_ext + ext) img.to_filename(fname) img3 = IC.load(fname) - assert_true(isinstance(img3, img.__class__)) + assert isinstance(img3, img.__class__) assert_array_equal(img3.get_fdata(), data) - assert_equal(img3.header, img.header) - assert_true(isinstance(np.asanyarray(img3.dataobj), - np.memmap if ext == '' else np.ndarray)) + assert img3.header == img.header + assert isinstance(np.asanyarray(img3.dataobj), + np.memmap if ext == '' else np.ndarray) # del to avoid windows errors of form 'The process cannot # access the file because it is being used' del img3 @@ -1027,8 +1039,8 @@ def test_affines_init(self): # Default is sform set, qform not set img = IC(arr, aff) hdr = img.header - assert_equal(hdr['qform_code'], 0) - assert_equal(hdr['sform_code'], 2) + assert hdr['qform_code'] == 0 + assert hdr['sform_code'] == 2 assert_array_equal(hdr.get_zooms(), [2, 3, 4]) # This is also true for affines with header passed qaff = np.diag([3, 4, 5, 1]) @@ -1039,16 +1051,16 @@ def test_affines_init(self): img = IC(arr, aff, hdr) new_hdr = img.header # Again affine is sort of anonymous space - assert_equal(new_hdr['qform_code'], 0) - assert_equal(new_hdr['sform_code'], 2) + assert new_hdr['qform_code'] == 0 + assert new_hdr['sform_code'] == 2 assert_array_equal(new_hdr.get_sform(), aff) assert_array_equal(new_hdr.get_zooms(), [2, 3, 4]) # But if no affine passed, codes and matrices stay the same img = IC(arr, None, hdr) new_hdr = img.header - assert_equal(new_hdr['qform_code'], 1) # scanner + assert new_hdr['qform_code'] == 1 # scanner assert_array_equal(new_hdr.get_qform(), qaff) - assert_equal(new_hdr['sform_code'], 3) # Still talairach + assert new_hdr['sform_code'] == 3 # Still talairach assert_array_equal(new_hdr.get_sform(), saff) # Pixdims as in the original header assert_array_equal(new_hdr.get_zooms(), [3, 4, 5]) @@ -1057,13 +1069,13 @@ def test_read_no_extensions(self): IC = self.image_class arr = np.arange(24).reshape((2, 3, 4)) img = IC(arr, np.eye(4)) - assert_equal(len(img.header.extensions), 0) + assert len(img.header.extensions) == 0 img_rt = bytesio_round_trip(img) - assert_equal(len(img_rt.header.extensions), 0) + assert len(img_rt.header.extensions) == 0 # Check simple round trip with large offset img.header.set_data_offset(1024) img_rt = bytesio_round_trip(img) - assert_equal(len(img_rt.header.extensions), 0) + assert len(img_rt.header.extensions) == 0 def _get_raw_scaling(self, hdr): return hdr['scl_slope'], hdr['scl_inter'] @@ -1094,34 +1106,35 @@ def test_offset_errors(self): IC = self.image_class arr = np.arange(24).reshape((2, 3, 4)) img = IC(arr, np.eye(4)) - assert_equal(img.header.get_data_offset(), 0) + assert img.header.get_data_offset() == 0 # Saving with zero offset is OK img_rt = bytesio_round_trip(img) - assert_equal(img_rt.header.get_data_offset(), 0) + assert img_rt.header.get_data_offset() == 0 # Saving with too low offset explicitly set gives error fm = bytesio_filemap(IC) img.header.set_data_offset(16) - assert_raises(HeaderDataError, img.to_file_map, fm) + with pytest.raises(HeaderDataError): + img.to_file_map(fm) def test_extension_basics(): raw = '123' ext = Nifti1Extension('comment', raw) - assert_true(ext.get_sizeondisk() == 16) - assert_true(ext.get_content() == raw) - assert_true(ext.get_code() == 6) + assert ext.get_sizeondisk() == 16 + assert ext.get_content() == raw + assert ext.get_code() == 6 # Test that extensions already aligned to 16 bytes are not padded ext = Nifti1Extension('comment', b'x' * 24) - assert_true(ext.get_sizeondisk() == 32) + assert ext.get_sizeondisk() == 32 def test_ext_eq(): ext = Nifti1Extension('comment', '123') - assert_true(ext == ext) - assert_false(ext != ext) + assert ext == ext + assert not ext != ext ext2 = Nifti1Extension('comment', '124') - assert_false(ext == ext2) - assert_true(ext != ext2) + assert not ext == ext2 + assert ext != ext2 def test_extension_codes(): @@ -1132,12 +1145,12 @@ def test_extension_codes(): def test_extension_list(): ext_c0 = Nifti1Extensions() ext_c1 = Nifti1Extensions() - assert_equal(ext_c0, ext_c1) + assert ext_c0 == ext_c1 ext = Nifti1Extension('comment', '123') ext_c1.append(ext) - assert_false(ext_c0 == ext_c1) + assert not ext_c0 == ext_c1 ext_c0.append(ext) - assert_true(ext_c0 == ext_c1) + assert ext_c0 == ext_c1 def test_extension_io(): @@ -1146,23 +1159,23 @@ def test_extension_io(): ext1.write_to(bio, False) bio.seek(0) ebacks = Nifti1Extensions.from_fileobj(bio, -1, False) - assert_equal(len(ebacks), 1) - assert_equal(ext1, ebacks[0]) + assert len(ebacks) == 1 + assert ext1 == ebacks[0] # Check the start is what we expect exp_dtype = np.dtype([('esize', 'i4'), ('ecode', 'i4')]) bio.seek(0) buff = np.ndarray(shape=(), dtype=exp_dtype, buffer=bio.read(16)) - assert_equal(buff['esize'], 32) - assert_equal(buff['ecode'], 6) + assert buff['esize'] == 32 + assert buff['ecode'] == 6 # Try another extension on top bio.seek(32) ext2 = Nifti1Extension(6, b'Comment') ext2.write_to(bio, False) bio.seek(0) ebacks = Nifti1Extensions.from_fileobj(bio, -1, False) - assert_equal(len(ebacks), 2) - assert_equal(ext1, ebacks[0]) - assert_equal(ext2, ebacks[1]) + assert len(ebacks) == 2 + assert ext1 == ebacks[0] + assert ext2 == ebacks[1] # Rewrite but deliberately setting esize wrongly bio.truncate(0) bio.seek(0) @@ -1178,11 +1191,11 @@ def test_extension_io(): bio.seek(0) with warnings.catch_warnings(record=True) as warns: ebacks = Nifti1Extensions.from_fileobj(bio, -1, False) - assert_equal(len(warns), 1) - assert_equal(warns[0].category, UserWarning) - assert_equal(len(ebacks), 2) - assert_equal(ext1, ebacks[0]) - assert_equal(ext2, ebacks[1]) + assert len(warns) == 1 + assert warns[0].category == UserWarning + assert len(ebacks) == 2 + assert ext1 == ebacks[0] + assert ext2 == ebacks[1] def test_nifti_extensions(): @@ -1190,25 +1203,25 @@ def test_nifti_extensions(): # basic checks of the available extensions hdr = nim.header exts_container = hdr.extensions - assert_equal(len(exts_container), 2) - assert_equal(exts_container.count('comment'), 2) - assert_equal(exts_container.count('afni'), 0) - assert_equal(exts_container.get_codes(), [6, 6]) - assert_equal((exts_container.get_sizeondisk()) % 16, 0) + assert len(exts_container) == 2 + assert exts_container.count('comment') == 2 + assert exts_container.count('afni') == 0 + assert exts_container.get_codes() == [6, 6] + assert (exts_container.get_sizeondisk()) % 16 == 0 # first extension should be short one - assert_equal(exts_container[0].get_content(), b'extcomment1') + assert exts_container[0].get_content() == b'extcomment1' # add one afniext = Nifti1Extension('afni', '') exts_container.append(afniext) - assert_true(exts_container.get_codes() == [6, 6, 4]) - assert_true(exts_container.count('comment') == 2) - assert_true(exts_container.count('afni') == 1) - assert_true((exts_container.get_sizeondisk()) % 16 == 0) + assert exts_container.get_codes() == [6, 6, 4] + assert exts_container.count('comment') == 2 + assert exts_container.count('afni') == 1 + assert (exts_container.get_sizeondisk()) % 16 == 0 # delete one del exts_container[1] - assert_true(exts_container.get_codes() == [6, 4]) - assert_true(exts_container.count('comment') == 1) - assert_true(exts_container.count('afni') == 1) + assert exts_container.get_codes() == [6, 4] + assert exts_container.count('comment') == 1 + assert exts_container.count('afni') == 1 @dicom_test @@ -1219,47 +1232,47 @@ def test_nifti_dicom_extension(): # create an empty dataset if no content provided (to write a new header) dcmext = Nifti1DicomExtension(2, b'') - assert_equal(dcmext.get_content().__class__, pydicom.dataset.Dataset) - assert_equal(len(dcmext.get_content().values()), 0) + assert dcmext.get_content().__class__ == pydicom.dataset.Dataset + assert len(dcmext.get_content().values()) == 0 # create an empty dataset if no content provided (to write a new header) dcmext = Nifti1DicomExtension(2, None) - assert_equal(dcmext.get_content().__class__, pydicom.dataset.Dataset) - assert_equal(len(dcmext.get_content().values()), 0) + assert dcmext.get_content().__class__ == pydicom.dataset.Dataset + assert len(dcmext.get_content().values()) == 0 # use a dataset if provided ds = pydicom.dataset.Dataset() ds.add_new((0x10, 0x20), 'LO', 'NiPy') dcmext = Nifti1DicomExtension(2, ds) - assert_equal(dcmext.get_content().__class__, pydicom.dataset.Dataset) - assert_equal(len(dcmext.get_content().values()), 1) - assert_equal(dcmext.get_content().PatientID, 'NiPy') + assert dcmext.get_content().__class__ == pydicom.dataset.Dataset + assert len(dcmext.get_content().values()) == 1 + assert dcmext.get_content().PatientID == 'NiPy' # create a single dicom tag (Patient ID, [0010,0020]) with Explicit VR / LE dcmbytes_explicit = struct.pack('2H2sH4s', 0x10, 0x20, @@ -1267,30 +1280,31 @@ def test_nifti_dicom_extension(): 'NiPy'.encode('utf-8')) hdr_be = Nifti1Header(endianness='>') # Big Endian Nifti1Header dcmext = Nifti1DicomExtension(2, dcmbytes_explicit_be, parent_hdr=hdr_be) - assert_equal(dcmext.__class__, Nifti1DicomExtension) - assert_equal(dcmext._guess_implicit_VR(), False) - assert_equal(dcmext.get_code(), 2) - assert_equal(dcmext.get_content().PatientID, 'NiPy') - assert_equal(dcmext.get_content()[0x10, 0x20].value, 'NiPy') - assert_equal(len(dcmext.get_content().values()), 1) - assert_equal(dcmext._mangle(dcmext.get_content()), dcmbytes_explicit_be) - assert_equal(dcmext.get_sizeondisk() % 16, 0) + assert dcmext.__class__ == Nifti1DicomExtension + assert dcmext._guess_implicit_VR() == False + assert dcmext.get_code() == 2 + assert dcmext.get_content().PatientID == 'NiPy' + assert dcmext.get_content()[0x10, 0x20].value == 'NiPy' + assert len(dcmext.get_content().values()) == 1 + assert dcmext._mangle(dcmext.get_content()) == dcmbytes_explicit_be + assert dcmext.get_sizeondisk() % 16 == 0 # Check that a dicom dataset is written w/ BE encoding when not created # using BE bytestring when given a BE nifti header dcmext = Nifti1DicomExtension(2, ds, parent_hdr=hdr_be) - assert_equal(dcmext._mangle(dcmext.get_content()), dcmbytes_explicit_be) + assert dcmext._mangle(dcmext.get_content()) == dcmbytes_explicit_be # dicom extension access from nifti extensions - assert_equal(exts_container.count('dicom'), 0) + assert exts_container.count('dicom') == 0 exts_container.append(dcmext) - assert_equal(exts_container.count('dicom'), 1) - assert_equal(exts_container.get_codes(), [6, 6, 2]) - assert_equal(dcmext._mangle(dcmext.get_content()), dcmbytes_explicit_be) - assert_equal(dcmext.get_sizeondisk() % 16, 0) + assert exts_container.count('dicom') == 1 + assert exts_container.get_codes() == [6, 6, 2] + assert dcmext._mangle(dcmext.get_content()) == dcmbytes_explicit_be + assert dcmext.get_sizeondisk() % 16 == 0 # creating an extension with bad content should raise - assert_raises(TypeError, Nifti1DicomExtension, 2, 0) + with pytest.raises(TypeError): + Nifti1DicomExtension(2, 0) class TestNifti1General(object): @@ -1309,38 +1323,38 @@ def test_loadsave_cycle(self): # ensure we have extensions hdr = nim.header exts_container = hdr.extensions - assert_true(len(exts_container) > 0) + assert len(exts_container) > 0 # write into the air ;-) lnim = bytesio_round_trip(nim) hdr = lnim.header lexts_container = hdr.extensions - assert_equal(exts_container, lexts_container) + assert exts_container == lexts_container # build int16 image data = np.ones((2, 3, 4, 5), dtype='int16') img = self.single_class(data, np.eye(4)) hdr = img.header - assert_equal(hdr.get_data_dtype(), np.int16) + assert hdr.get_data_dtype() == np.int16 # default should have no scaling assert_array_equal(hdr.get_slope_inter(), (None, None)) # set scaling hdr.set_slope_inter(2, 8) - assert_equal(hdr.get_slope_inter(), (2, 8)) + assert hdr.get_slope_inter() == (2, 8) # now build new image with updated header wnim = self.single_class(data, np.eye(4), header=hdr) - assert_equal(wnim.get_data_dtype(), np.int16) + assert wnim.get_data_dtype() == np.int16 # Header scaling reset to default by image creation - assert_equal(wnim.header.get_slope_inter(), (None, None)) + assert wnim.header.get_slope_inter() == (None, None) # But we can reset it again after image creation wnim.header.set_slope_inter(2, 8) - assert_equal(wnim.header.get_slope_inter(), (2, 8)) + assert wnim.header.get_slope_inter() == (2, 8) # write into the air again ;-) lnim = bytesio_round_trip(wnim) - assert_equal(lnim.get_data_dtype(), np.int16) + assert lnim.get_data_dtype() == np.int16 # Scaling applied assert_array_equal(lnim.get_fdata(), data * 2. + 8.) # slope, inter reset by image creation, but saved in proxy - assert_equal(lnim.header.get_slope_inter(), (None, None)) - assert_equal((lnim.dataobj.slope, lnim.dataobj.inter), (2, 8)) + assert lnim.header.get_slope_inter() == (None, None) + assert (lnim.dataobj.slope, lnim.dataobj.inter) == (2, 8) def test_load(self): # test module level load. We try to load a nii and an .img and a .hdr @@ -1371,7 +1385,7 @@ def test_float_int_min_max(self): img = self.single_class(arr, aff) img_back = bytesio_round_trip(img) arr_back_sc = img_back.get_fdata() - assert_true(np.allclose(arr, arr_back_sc)) + assert np.allclose(arr, arr_back_sc) def test_float_int_spread(self): # Test rounding error for spread of values @@ -1392,7 +1406,7 @@ def test_float_int_spread(self): # Simulate allclose test with large atol diff = np.abs(arr_t - arr_back_sc) rdiff = diff / np.abs(arr_t) - assert_true(np.all((diff <= max_miss) | (rdiff <= 1e-5))) + assert np.all((diff <= max_miss) | (rdiff <= 1e-5)) def test_rt_bias(self): # Check for bias in round trip @@ -1415,7 +1429,7 @@ def test_rt_bias(self): inter) # Hokey use of max_miss as a std estimate bias_thresh = np.max([max_miss / np.sqrt(count), eps]) - assert_true(np.abs(bias) < bias_thresh) + assert np.abs(bias) < bias_thresh def test_reoriented_dim_info(self): # Check that dim_info is reoriented correctly @@ -1445,7 +1459,7 @@ def test_reoriented_dim_info(self): new_fdir = dirs[new_freq] if new_freq is not None else None new_pdir = dirs[new_phas] if new_phas is not None else None new_sdir = dirs[new_slic] if new_slic is not None else None - assert_equal((new_fdir, new_pdir, new_sdir), (fdir, pdir, sdir)) + assert (new_fdir, new_pdir, new_sdir) == (fdir, pdir, sdir) @runif_extra_has('slow') @@ -1459,6 +1473,6 @@ def test_large_nifti1(): del img data = load('test.nii.gz').get_fdata() # Check that the data are all ones - assert_equal(image_shape, data.shape) + assert image_shape == data.shape n_ones = np.sum((data == 1.)) - assert_equal(np.prod(image_shape), n_ones) + assert np.prod(image_shape) == n_ones diff --git a/nibabel/tests/test_nifti2.py b/nibabel/tests/test_nifti2.py index 730e30a689..7f9d32b6b9 100644 --- a/nibabel/tests/test_nifti2.py +++ b/nibabel/tests/test_nifti2.py @@ -19,10 +19,9 @@ from .test_nifti1 import (TestNifti1PairHeader, TestNifti1SingleHeader, TestNifti1Pair, TestNifti1Image, TestNifti1General) -from nose.tools import assert_equal from numpy.testing import assert_array_equal -from ..testing import data_path +from ..testing_pytest import data_path header_file = os.path.join(data_path, 'nifti2.hdr') image_file = os.path.join(data_path, 'example_nifti2.nii.gz') @@ -50,13 +49,13 @@ def test_eol_check(self): hdr['eol_check'] = 0 fhdr, message, raiser = self.log_chk(hdr, 20) assert_array_equal(fhdr['eol_check'], good_eol) - assert_equal(message, + assert (message == 'EOL check all 0; ' 'setting EOL check to 13, 10, 26, 10') hdr['eol_check'] = (13, 10, 0, 10) fhdr, message, raiser = self.log_chk(hdr, 40) assert_array_equal(fhdr['eol_check'], good_eol) - assert_equal(message, + assert (message == 'EOL check not 0 or 13, 10, 26, 10; ' 'data may be corrupted by EOL conversion; ' 'setting EOL check to 13, 10, 26, 10') @@ -110,6 +109,6 @@ def test_nifti12_conversion(): in_hdr.set_data_dtype(dtype_type) in_hdr.extensions[:] = [ext1, ext2] out_hdr = out_type.from_header(in_hdr) - assert_equal(out_hdr.get_data_shape(), shape) - assert_equal(out_hdr.get_data_dtype(), dtype_type) - assert_equal(in_hdr.extensions, out_hdr.extensions) + assert out_hdr.get_data_shape() == shape + assert out_hdr.get_data_dtype() == dtype_type + assert in_hdr.extensions == out_hdr.extensions diff --git a/nibabel/tests/test_openers.py b/nibabel/tests/test_openers.py index 6d1baab734..eac73dd92b 100644 --- a/nibabel/tests/test_openers.py +++ b/nibabel/tests/test_openers.py @@ -19,9 +19,8 @@ from ..volumeutils import BinOpener from unittest import mock -from nose.tools import (assert_true, assert_false, assert_equal, - assert_not_equal, assert_raises) -from ..testing import error_warnings +import pytest +from ..testing_pytest import error_warnings class Lunk(object): @@ -41,24 +40,24 @@ def read(self): def test_Opener(): # Test default mode is 'rb' fobj = Opener(__file__) - assert_equal(fobj.mode, 'rb') + assert fobj.mode == 'rb' fobj.close() # That it's a context manager with Opener(__file__) as fobj: - assert_equal(fobj.mode, 'rb') + assert fobj.mode == 'rb' # That we can set the mode with Opener(__file__, 'r') as fobj: - assert_equal(fobj.mode, 'r') + assert fobj.mode == 'r' # with keyword arguments with Opener(__file__, mode='r') as fobj: - assert_equal(fobj.mode, 'r') + assert fobj.mode == 'r' # fileobj returns fileobj passed through message = b"Wine? Wouldn't you?" for obj in (BytesIO(message), Lunk(message)): with Opener(obj) as fobj: - assert_equal(fobj.read(), message) + assert fobj.read() == message # Which does not close the object - assert_false(obj.closed) + assert not obj.closed # mode is gently ignored fobj = Opener(obj, mode='r') @@ -77,31 +76,34 @@ def test_Opener_various(): sobj): with Opener(input, 'wb') as fobj: fobj.write(message) - assert_equal(fobj.tell(), len(message)) + assert fobj.tell() == len(message) if input == sobj: input.seek(0) with Opener(input, 'rb') as fobj: message_back = fobj.read() - assert_equal(message, message_back) + assert message == message_back if input == sobj: # Fileno is unsupported for BytesIO - assert_raises(UnsupportedOperation, fobj.fileno) + with pytest.raises(UnsupportedOperation): + fobj.fileno() elif input.endswith('.bz2') and not bz2_fileno: - assert_raises(AttributeError, fobj.fileno) + with pytest.raises(AttributeError): + fobj.fileno() # indexed gzip is used by default, and drops file # handles by default, so we don't have a fileno. elif input.endswith('gz') and HAVE_INDEXED_GZIP and \ StrictVersion(igzip.__version__) >= StrictVersion('0.7.0'): - assert_raises(igzip.NoHandleError, fobj.fileno) + with pytest.raises(igzip.NoHandleError): + fobj.fileno() else: # Just check there is a fileno - assert_not_equal(fobj.fileno(), 0) + assert fobj.fileno() != 0 def test_BinOpener(): with error_warnings(): - assert_raises(DeprecationWarning, - BinOpener, 'test.txt', 'r') + with pytest.raises(DeprecationWarning): + BinOpener('test.txt', 'r') class MockIndexedGzipFile(GzipFile): @@ -158,22 +160,26 @@ def test_Opener_gzip_type(): with patch_indexed_gzip(igzip_present): assert isinstance(Opener(fname, **kwargs).fobj, expected) +@pytest.fixture(scope="class") +def image_opener_setup(request): + compress_ext_map = ImageOpener.compress_ext_map.copy() + request.cls.compress_ext_map = compress_ext_map -class TestImageOpener: + def teardown(): + ImageOpener.compress_ext_map = request.cls.compress_ext_map + request.addfinalizer(teardown) - def setUp(self): - self.compress_ext_map = ImageOpener.compress_ext_map.copy() - def teardown(self): - ImageOpener.compress_ext_map = self.compress_ext_map +@pytest.mark.usefixtures("image_opener_setup") +class TestImageOpener: def test_vanilla(self): # Test that ImageOpener does add '.mgz' as gzipped file type with InTemporaryDirectory(): with ImageOpener('test.gz', 'w') as fobj: - assert_true(hasattr(fobj.fobj, 'compress')) + assert hasattr(fobj.fobj, 'compress') with ImageOpener('test.mgz', 'w') as fobj: - assert_true(hasattr(fobj.fobj, 'compress')) + assert hasattr(fobj.fobj, 'compress') def test_new_association(self): def file_opener(fileish, mode): @@ -182,16 +188,16 @@ def file_opener(fileish, mode): # Add the association n_associations = len(ImageOpener.compress_ext_map) ImageOpener.compress_ext_map['.foo'] = (file_opener, ('mode',)) - assert_equal(n_associations + 1, len(ImageOpener.compress_ext_map)) - assert_true('.foo' in ImageOpener.compress_ext_map) + assert n_associations + 1 == len(ImageOpener.compress_ext_map) + assert '.foo' in ImageOpener.compress_ext_map with InTemporaryDirectory(): with ImageOpener('test.foo', 'w'): pass - assert_true(os.path.exists('test.foo')) + assert os.path.exists('test.foo') # Check this doesn't add anything to parent - assert_false('.foo' in Opener.compress_ext_map) + assert not '.foo' in Opener.compress_ext_map def test_file_like_wrapper(): @@ -199,17 +205,17 @@ def test_file_like_wrapper(): message = b"History of the nude in" sobj = BytesIO() fobj = Opener(sobj) - assert_equal(fobj.tell(), 0) + assert fobj.tell() == 0 fobj.write(message) - assert_equal(fobj.tell(), len(message)) + assert fobj.tell() == len(message) fobj.seek(0) - assert_equal(fobj.tell(), 0) - assert_equal(fobj.read(6), message[:6]) - assert_false(fobj.closed) + assert fobj.tell() == 0 + assert fobj.read(6) == message[:6] + assert not fobj.closed fobj.close() - assert_true(fobj.closed) + assert fobj.closed # Added the fileobj name - assert_equal(fobj.name, None) + assert fobj.name == None def test_compressionlevel(): @@ -236,8 +242,8 @@ class MyOpener(Opener): with open(fname, 'rb') as fobj: my_selves_smaller = fobj.read() sizes[compresslevel] = len(my_selves_smaller) - assert_equal(sizes['default'], sizes[default_val]) - assert_true(sizes[1] > sizes[5]) + assert sizes['default'] == sizes[default_val] + assert sizes[1] > sizes[5] def test_compressed_ext_case(): @@ -256,23 +262,23 @@ class StrictOpener(Opener): with Opener(fname, 'wb') as fobj: fobj.write(contents) with Opener(fname, 'rb') as fobj: - assert_equal(fobj.read(), contents) + assert fobj.read() == contents os.unlink(fname) with StrictOpener(fname, 'wb') as fobj: fobj.write(contents) with StrictOpener(fname, 'rb') as fobj: - assert_equal(fobj.read(), contents) + assert fobj.read() == contents lext = ext.lower() if lext != ext: # extension should not be recognized -> file - assert_true(isinstance(fobj.fobj, file_class)) + assert isinstance(fobj.fobj, file_class) elif lext == 'gz': try: from ..openers import IndexedGzipFile except ImportError: IndexedGzipFile = GzipFile - assert_true(isinstance(fobj.fobj, (GzipFile, IndexedGzipFile))) + assert isinstance(fobj.fobj, (GzipFile, IndexedGzipFile)) else: - assert_true(isinstance(fobj.fobj, BZ2File)) + assert isinstance(fobj.fobj, BZ2File) def test_name(): @@ -287,22 +293,22 @@ def test_name(): lunk): exp_name = input if type(input) == type('') else None with Opener(input, 'wb') as fobj: - assert_equal(fobj.name, exp_name) + assert fobj.name == exp_name def test_set_extensions(): # Test that we can add extensions that are compressed with InTemporaryDirectory(): with Opener('test.gz', 'w') as fobj: - assert_true(hasattr(fobj.fobj, 'compress')) + assert hasattr(fobj.fobj, 'compress') with Opener('test.glrph', 'w') as fobj: - assert_false(hasattr(fobj.fobj, 'compress')) + assert not hasattr(fobj.fobj, 'compress') class MyOpener(Opener): compress_ext_map = Opener.compress_ext_map.copy() compress_ext_map['.glrph'] = Opener.gz_def with MyOpener('test.glrph', 'w') as fobj: - assert_true(hasattr(fobj.fobj, 'compress')) + assert hasattr(fobj.fobj, 'compress') def test_close_if_mine(): @@ -319,11 +325,11 @@ def test_close_if_mine(): # gzip objects have no 'closed' attribute has_closed = hasattr(fobj.fobj, 'closed') if has_closed: - assert_false(fobj.closed) + assert not fobj.closed fobj.close_if_mine() is_str = type(input) is type('') if has_closed: - assert_equal(fobj.closed, is_str) + assert fobj.closed == is_str def test_iter(): @@ -345,11 +351,12 @@ def test_iter(): fobj.write(asbytes(line + os.linesep)) with Opener(input, 'rb') as fobj: for back_line, line in zip(fobj, lines): - assert_equal(asstr(back_line).rstrip(), line) + assert asstr(back_line).rstrip() == line if not does_t: continue with Opener(input, 'rt') as fobj: for back_line, line in zip(fobj, lines): - assert_equal(back_line.rstrip(), line) + assert back_line.rstrip() == line lobj = Opener(Lunk('')) - assert_raises(TypeError, list, lobj) + with pytest.raises(TypeError): + list(lobj) diff --git a/nibabel/tests/test_optpkg.py b/nibabel/tests/test_optpkg.py index 17c0816e70..5603fc5127 100644 --- a/nibabel/tests/test_optpkg.py +++ b/nibabel/tests/test_optpkg.py @@ -7,10 +7,9 @@ import builtins from distutils.version import LooseVersion +# TODO: remove (have to be coordinated with optpkg) from nose import SkipTest -from nose.tools import (assert_true, assert_false, assert_raises, - assert_equal) - +import pytest from nibabel.optpkg import optional_package from nibabel.tripwire import TripWire, TripWireError @@ -18,17 +17,20 @@ def assert_good(pkg_name, min_version=None): pkg, have_pkg, setup = optional_package(pkg_name, min_version=min_version) - assert_true(have_pkg) - assert_equal(sys.modules[pkg_name], pkg) - assert_equal(setup(), None) + assert have_pkg + assert sys.modules[pkg_name] == pkg + assert setup() == None def assert_bad(pkg_name, min_version=None): pkg, have_pkg, setup = optional_package(pkg_name, min_version=min_version) - assert_false(have_pkg) - assert_true(isinstance(pkg, TripWire)) - assert_raises(TripWireError, getattr, pkg, 'a_method') - assert_raises(SkipTest, setup) + assert not have_pkg + assert isinstance(pkg, TripWire) + with pytest.raises(TripWireError): + getattr(pkg, 'a_method') + # TODO: remove + with pytest.raises(SkipTest): + setup() def test_basic(): @@ -54,7 +56,7 @@ def raise_Exception(*args, **kwargs): def test_versions(): fake_name = '_a_fake_package' fake_pkg = types.ModuleType(fake_name) - assert_false('fake_pkg' in sys.modules) + assert not 'fake_pkg' in sys.modules # Not inserted yet assert_bad(fake_name) try: @@ -77,7 +79,7 @@ def test_versions(): try: pkg.some_method except TripWireError as err: - assert_equal(str(err), + assert (str(err) == 'These functions need _a_fake_package version >= 3.0') finally: del sys.modules[fake_name] diff --git a/nibabel/tests/test_orientations.py b/nibabel/tests/test_orientations.py index 798f595fc7..5013828757 100644 --- a/nibabel/tests/test_orientations.py +++ b/nibabel/tests/test_orientations.py @@ -11,7 +11,7 @@ import numpy as np import warnings -from nose.tools import assert_true, assert_equal, assert_raises +import pytest from numpy.testing import assert_array_equal @@ -128,15 +128,12 @@ def test_apply(): # Test 4D with an example orientation ornt = OUT_ORNTS[-1] t_arr = apply_orientation(a[:, :, :, None], ornt) - assert_equal(t_arr.ndim, 4) + assert t_arr.ndim == 4 # Orientation errors - assert_raises(OrientationError, - apply_orientation, - a[:, :, 1], ornt) - assert_raises(OrientationError, - apply_orientation, - a, - [[0, 1], [np.nan, np.nan], [2, 1]]) + with pytest.raises(OrientationError): + apply_orientation(a[:, :, 1], ornt) + with pytest.raises(OrientationError): + apply_orientation(a, [[0, 1], [np.nan, np.nan], [2, 1]]) shape = np.array(a.shape) for ornt in ALL_ORNTS: t_arr = apply_orientation(a, ornt) @@ -171,7 +168,7 @@ def test_io_orientation(): ornt = io_orientation(in_arr) assert_array_equal(ornt, out_ornt) taff = inv_ornt_aff(ornt, shape) - assert_true(same_transform(taff, ornt, shape)) + assert same_transform(taff, ornt, shape) for axno in range(3): arr = in_arr.copy() ex_ornt = out_ornt.copy() @@ -182,7 +179,7 @@ def test_io_orientation(): ornt = io_orientation(arr) assert_array_equal(ornt, ex_ornt) taff = inv_ornt_aff(ornt, shape) - assert_true(same_transform(taff, ornt, shape)) + assert same_transform(taff, ornt, shape) # Test nasty hang for zero columns rzs = np.c_[np.diag([2, 3, 4, 5]), np.zeros((4, 3))] arr = from_matvec(rzs, [15, 16, 17, 18]) @@ -252,54 +249,52 @@ def test_ornt_transform(): [[1, -1], [2, 1], [0, 1]] ) # Must have same shape - assert_raises(ValueError, - ornt_transform, - [[0, 1], [1, 1]], - [[0, 1], [1, 1], [2, 1]]) + with pytest.raises(ValueError): + ornt_transform([[0, 1], [1, 1]], [[0, 1], [1, 1], [2, 1]]) # Must be (N,2) in shape - assert_raises(ValueError, - ornt_transform, - [[0, 1, 1], [1, 1, 1]], - [[0, 1, 1], [1, 1, 1]]) + with pytest.raises(ValueError): + ornt_transform([[0, 1, 1], [1, 1, 1]], + [[0, 1, 1], [1, 1, 1]]) # Target axes must exist in source - assert_raises(ValueError, - ornt_transform, - [[0, 1], [1, 1], [1, 1]], - [[0, 1], [1, 1], [2, 1]]) + with pytest.raises(ValueError): + ornt_transform([[0, 1], [1, 1], [1, 1]], + [[0, 1], [1, 1], [2, 1]]) def test_ornt2axcodes(): # Recoding orientation to axis codes labels = (('left', 'right'), ('back', 'front'), ('down', 'up')) - assert_equal(ornt2axcodes([[0, 1], + assert ornt2axcodes([[0, 1], [1, 1], - [2, 1]], labels), ('right', 'front', 'up')) - assert_equal(ornt2axcodes([[0, -1], + [2, 1]], labels) == ('right', 'front', 'up') + assert ornt2axcodes([[0, -1], [1, -1], - [2, -1]], labels), ('left', 'back', 'down')) - assert_equal(ornt2axcodes([[2, -1], + [2, -1]], labels) == ('left', 'back', 'down') + assert ornt2axcodes([[2, -1], [1, -1], - [0, -1]], labels), ('down', 'back', 'left')) - assert_equal(ornt2axcodes([[1, 1], + [0, -1]], labels) == ('down', 'back', 'left') + assert ornt2axcodes([[1, 1], [2, -1], - [0, 1]], labels), ('front', 'down', 'right')) + [0, 1]], labels) == ('front', 'down', 'right') # default is RAS output directions - assert_equal(ornt2axcodes([[0, 1], + assert ornt2axcodes([[0, 1], [1, 1], - [2, 1]]), ('R', 'A', 'S')) + [2, 1]]) == ('R', 'A', 'S') # dropped axes produce None - assert_equal(ornt2axcodes([[0, 1], + assert ornt2axcodes([[0, 1], [np.nan, np.nan], - [2, 1]]), ('R', None, 'S')) + [2, 1]]) == ('R', None, 'S') # Non integer axes raises error - assert_raises(ValueError, ornt2axcodes, [[0.1, 1]]) + with pytest.raises(ValueError): + ornt2axcodes([[0.1, 1]]) # As do directions not in range - assert_raises(ValueError, ornt2axcodes, [[0, 0]]) + with pytest.raises(ValueError): + ornt2axcodes([[0, 0]]) for axcodes, ornt in zip(ALL_AXCODES, ALL_ORNTS): - assert_equal(ornt2axcodes(ornt), axcodes) + assert ornt2axcodes(ornt) == axcodes def test_axcodes2ornt(): @@ -339,44 +334,48 @@ def test_axcodes2ornt(): # Missing axcodes raise an error assert_array_equal(axcodes2ornt('RAS'), default) - assert_raises(ValueError, axcodes2ornt, 'rAS') + with pytest.raises(ValueError): + axcodes2ornt('rAS') # None is OK as axis code assert_array_equal(axcodes2ornt(('R', None, 'S')), [[0, 1], [np.nan, np.nan], [2, 1]]) # Bad axis code with None also raises error. - assert_raises(ValueError, axcodes2ornt, ('R', None, 's')) + with pytest.raises(ValueError): + axcodes2ornt(('R', None, 's')) # Axis codes checked with custom labels labels = ('SD', 'BF', 'lh') assert_array_equal(axcodes2ornt('BlD', labels), [[1, -1], [2, -1], [0, 1]]) - assert_raises(ValueError, axcodes2ornt, 'blD', labels) + with pytest.raises(ValueError): + axcodes2ornt('blD', labels) # Duplicate labels - assert_raises(ValueError, axcodes2ornt, 'blD', ('SD', 'BF', 'lD')) - assert_raises(ValueError, axcodes2ornt, 'blD', ('SD', 'SF', 'lD')) + for labels in [('SD', 'BF', 'lD'),('SD', 'SF', 'lD')]: + with pytest.raises(ValueError): + axcodes2ornt('blD', labels) for axcodes, ornt in zip(ALL_AXCODES, ALL_ORNTS): assert_array_equal(axcodes2ornt(axcodes), ornt) def test_aff2axcodes(): - assert_equal(aff2axcodes(np.eye(4)), tuple('RAS')) + assert aff2axcodes(np.eye(4)) == tuple('RAS') aff = [[0, 1, 0, 10], [-1, 0, 0, 20], [0, 0, 1, 30], [0, 0, 0, 1]] - assert_equal(aff2axcodes(aff, (('L', 'R'), ('B', 'F'), ('D', 'U'))), + assert (aff2axcodes(aff, (('L', 'R'), ('B', 'F'), ('D', 'U'))) == ('B', 'R', 'U')) - assert_equal(aff2axcodes(aff, (('L', 'R'), ('B', 'F'), ('D', 'U'))), + assert (aff2axcodes(aff, (('L', 'R'), ('B', 'F'), ('D', 'U'))) == ('B', 'R', 'U')) def test_inv_ornt_aff(): # Extra tests for inv_ornt_aff routines (also tested in # io_orientations test) - assert_raises(OrientationError, inv_ornt_aff, - [[0, 1], [1, -1], [np.nan, np.nan]], (3, 4, 5)) + with pytest.raises(OrientationError): + inv_ornt_aff([[0, 1], [1, -1], [np.nan, np.nan]], (3, 4, 5)) def test_orientation_affine_deprecation(): @@ -384,6 +383,6 @@ def test_orientation_affine_deprecation(): with warnings.catch_warnings(record=True) as warns: warnings.simplefilter('always') aff2 = orientation_affine([[0, 1], [1, -1], [2, 1]], (3, 4, 5)) - assert_equal(len(warns), 1) - assert_equal(warns[0].category, DeprecationWarning) + assert len(warns) == 1 + assert warns[0].category == DeprecationWarning assert_array_equal(aff1, aff2) diff --git a/nibabel/tests/test_parrec.py b/nibabel/tests/test_parrec.py index 940d8864e5..bb0888b0e7 100644 --- a/nibabel/tests/test_parrec.py +++ b/nibabel/tests/test_parrec.py @@ -20,10 +20,8 @@ from numpy.testing import (assert_almost_equal, assert_array_equal) -from nose.tools import (assert_true, assert_false, assert_raises, - assert_equal) - -from ..testing import (clear_and_catch_warnings, suppress_warnings, +import pytest +from ..testing_pytest import (clear_and_catch_warnings, suppress_warnings, assert_arr_dict_equal) from .test_arrayproxy import check_mmap @@ -177,15 +175,15 @@ def test_header(): v41_hdr = PARRECHeader.from_fileobj(fobj, strict_sort=strict_sort) for hdr in (v42_hdr, v41_hdr, v4_hdr): hdr = PARRECHeader(HDR_INFO, HDR_DEFS) - assert_equal(hdr.get_data_shape(), (64, 64, 9, 3)) - assert_equal(hdr.get_data_dtype(), np.dtype(' Date: Sun, 1 Dec 2019 11:24:34 -0500 Subject: [PATCH 011/223] converting more tests to pytest --- nibabel/tests/test_recoder.py | 155 +++++++++++++++----------- nibabel/tests/test_removalschedule.py | 10 +- nibabel/tests/test_round_trip.py | 4 +- nibabel/tests/test_rstutils.py | 59 +++++----- 4 files changed, 123 insertions(+), 105 deletions(-) diff --git a/nibabel/tests/test_recoder.py b/nibabel/tests/test_recoder.py index e340936ff0..28eba8860b 100644 --- a/nibabel/tests/test_recoder.py +++ b/nibabel/tests/test_recoder.py @@ -12,50 +12,75 @@ from ..volumeutils import Recoder, DtypeMapper, native_code, swapped_code -from nose.tools import assert_equal, assert_raises, assert_true, assert_false +import pytest -def test_recoder(): +def test_recoder_1(): # simplest case, no aliases codes = ((1,), (2,)) rc = Recoder(codes) - yield assert_equal, rc.code[1], 1 - yield assert_equal, rc.code[2], 2 - yield assert_raises, KeyError, rc.code.__getitem__, 3 + assert rc.code[1] == 1 + assert rc.code[2] == 2 + with pytest.raises(KeyError): + rc.code.__getitem__(3) + +def test_recoder_2(): # with explicit name for code + codes = ((1,), (2,)) rc = Recoder(codes, ['code1']) - yield assert_raises, AttributeError, rc.__getattribute__, 'code' - yield assert_equal, rc.code1[1], 1 - yield assert_equal, rc.code1[2], 2 + with pytest.raises(AttributeError): + rc.__getattribute__('code') + assert rc.code1[1] == 1 + assert rc.code1[2] == 2 + + +def test_recoder_3(): # code and label codes = ((1, 'one'), (2, 'two')) rc = Recoder(codes) # just with implicit alias - yield assert_equal, rc.code[1], 1 - yield assert_equal, rc.code[2], 2 - yield assert_raises, KeyError, rc.code.__getitem__, 3 - yield assert_equal, rc.code['one'], 1 - yield assert_equal, rc.code['two'], 2 - yield assert_raises, KeyError, rc.code.__getitem__, 'three' - yield assert_raises, AttributeError, rc.__getattribute__, 'label' - rc = Recoder(codes, ['code1', 'label']) # with explicit column names - yield assert_raises, AttributeError, rc.__getattribute__, 'code' - yield assert_equal, rc.code1[1], 1 - yield assert_equal, rc.code1['one'], 1 - yield assert_equal, rc.label[1], 'one' - yield assert_equal, rc.label['one'], 'one' + assert rc.code[1] == 1 + assert rc.code[2] == 2 + with pytest.raises(KeyError): + rc.code.__getitem__(3) + assert rc.code['one'] == 1 + assert rc.code['two'] == 2 + with pytest.raises(KeyError): + rc.code.__getitem__('three') + with pytest.raises(AttributeError): + rc.__getattribute__('label') + +def test_recoder_3(): + # with explicit column names + codes = ((1, 'one'), (2, 'two')) + rc = Recoder(codes, ['code1', 'label']) + with pytest.raises(AttributeError): + rc.__getattribute__('code') + assert rc.code1[1] == 1 + assert rc.code1['one'] == 1 + assert rc.label[1] == 'one' + assert rc.label['one'] == 'one' + + +def test_recoder_4(): # code, label, aliases codes = ((1, 'one', '1', 'first'), (2, 'two')) rc = Recoder(codes) # just with implicit alias - yield assert_equal, rc.code[1], 1 - yield assert_equal, rc.code['one'], 1 - yield assert_equal, rc.code['first'], 1 - rc = Recoder(codes, ['code1', 'label']) # with explicit column names - yield assert_equal, rc.code1[1], 1 - yield assert_equal, rc.code1['first'], 1 - yield assert_equal, rc.label[1], 'one' - yield assert_equal, rc.label['first'], 'one' + assert rc.code[1] == 1 + assert rc.code['one'] == 1 + assert rc.code['first'] == 1 + + +def test_recoder_5(): + # with explicit column names + codes = ((1, 'one', '1', 'first'), (2, 'two')) + rc = Recoder(codes, ['code1', 'label']) + assert rc.code1[1] == 1 + assert rc.code1['first'] == 1 + assert rc.label[1] == 'one' + assert rc.label['first'] == 'one' # Don't allow funny names - yield assert_raises, KeyError, Recoder, codes, ['field1'] + with pytest.raises(KeyError): + Recoder(codes, ['field1']) def test_custom_dicter(): @@ -81,22 +106,23 @@ def values(self): # code, label, aliases codes = ((1, 'one', '1', 'first'), (2, 'two')) rc = Recoder(codes, map_maker=MyDict) - yield assert_equal, rc.code[1], 'spam' - yield assert_equal, rc.code['one'], 'spam' - yield assert_equal, rc.code['first'], 'spam' - yield assert_equal, rc.code['bizarre'], 'eggs' - yield assert_equal, rc.value_set(), set(['funny', 'list']) - yield assert_equal, list(rc.keys()), ['some', 'keys'] + assert rc.code[1] == 'spam' + assert rc.code['one'] == 'spam' + assert rc.code['first'] == 'spam' + assert rc.code['bizarre'] == 'eggs' + assert rc.value_set() == set(['funny', 'list']) + assert list(rc.keys()) == ['some', 'keys'] def test_add_codes(): codes = ((1, 'one', '1', 'first'), (2, 'two')) rc = Recoder(codes) - yield assert_equal, rc.code['two'], 2 - yield assert_raises, KeyError, rc.code.__getitem__, 'three' + assert rc.code['two'] == 2 + with pytest.raises(KeyError): + rc.code.__getitem__('three') rc.add_codes(((3, 'three'), (1, 'number 1'))) - yield assert_equal, rc.code['three'], 3 - yield assert_equal, rc.code['number 1'], 1 + assert rc.code['three'] == 3 + assert rc.code['number 1'] == 1 def test_sugar(): @@ -104,31 +130,32 @@ def test_sugar(): codes = ((1, 'one', '1', 'first'), (2, 'two')) rc = Recoder(codes) # Field1 is synonym for first named dict - yield assert_equal, rc.code, rc.field1 + assert rc.code == rc.field1 rc = Recoder(codes, fields=('code1', 'label')) - yield assert_equal, rc.code1, rc.field1 + assert rc.code1 == rc.field1 # Direct key access identical to key access for first named - yield assert_equal, rc[1], rc.field1[1] - yield assert_equal, rc['two'], rc.field1['two'] + assert rc[1] == rc.field1[1] + assert rc['two'] == rc.field1['two'] # keys gets all keys - yield assert_equal, set(rc.keys()), set((1, 'one', '1', 'first', 2, 'two')) + assert set(rc.keys()) == set((1, 'one', '1', 'first', 2, 'two')) # value_set gets set of values from first column - yield assert_equal, rc.value_set(), set((1, 2)) + assert rc.value_set() == set((1, 2)) # or named column if given - yield assert_equal, rc.value_set('label'), set(('one', 'two')) + assert rc.value_set('label') == set(('one', 'two')) # "in" works for values in and outside the set - yield assert_true, 'one' in rc - yield assert_false, 'three' in rc + assert 'one' in rc + assert 'three' not in rc def test_dtmapper(): # dict-like that will lookup on dtypes, even if they don't hash properly d = DtypeMapper() - assert_raises(KeyError, d.__getitem__, 1) + with pytest.raises(KeyError): + d.__getitem__(1) d[1] = 'something' - assert_equal(d[1], 'something') - assert_equal(list(d.keys()), [1]) - assert_equal(list(d.values()), ['something']) + assert d[1] == 'something' + assert list(d.keys()) == [1] + assert list(d.values()) == ['something'] intp_dt = np.dtype('intp') if intp_dt == np.dtype('int32'): canonical_dt = np.dtype('int32') @@ -139,21 +166,23 @@ def test_dtmapper(): native_dt = canonical_dt.newbyteorder('=') explicit_dt = canonical_dt.newbyteorder(native_code) d[canonical_dt] = 'spam' - assert_equal(d[canonical_dt], 'spam') - assert_equal(d[native_dt], 'spam') - assert_equal(d[explicit_dt], 'spam') + assert d[canonical_dt] == 'spam' + assert d[native_dt] == 'spam' + assert d[explicit_dt] == 'spam' + # Test keys, values d = DtypeMapper() - assert_equal(list(d.keys()), []) - assert_equal(list(d.keys()), []) + assert list(d.keys()) == [] + assert list(d.keys()) == [] d[canonical_dt] = 'spam' - assert_equal(list(d.keys()), [canonical_dt]) - assert_equal(list(d.values()), ['spam']) + assert list(d.keys()) == [canonical_dt] + assert list(d.values()) == ['spam'] # With other byte order d = DtypeMapper() sw_dt = canonical_dt.newbyteorder(swapped_code) d[sw_dt] = 'spam' - assert_raises(KeyError, d.__getitem__, canonical_dt) - assert_equal(d[sw_dt], 'spam') + with pytest.raises(KeyError): + d.__getitem__(canonical_dt) + assert d[sw_dt] == 'spam' sw_intp_dt = intp_dt.newbyteorder(swapped_code) - assert_equal(d[sw_intp_dt], 'spam') + assert d[sw_intp_dt] == 'spam' diff --git a/nibabel/tests/test_removalschedule.py b/nibabel/tests/test_removalschedule.py index a0c3484a3a..17f40d8395 100644 --- a/nibabel/tests/test_removalschedule.py +++ b/nibabel/tests/test_removalschedule.py @@ -1,5 +1,5 @@ from ..pkg_info import cmp_pkg_version -from ..testing import assert_raises, assert_false +import pytest MODULE_SCHEDULE = [ ('5.0.0', ['nibabel.keywordonly']), @@ -26,8 +26,9 @@ def test_module_removal(): for version, to_remove in MODULE_SCHEDULE: if cmp_pkg_version(version) < 1: for module in to_remove: - with assert_raises(ImportError, msg="Time to remove " + module): + with pytest.raises(ImportError): __import__(module) + pytest.fail("Time to remove " + module) def test_object_removal(): @@ -38,7 +39,7 @@ def test_object_removal(): module = __import__(module_name) except ImportError: continue - assert_false(hasattr(module, obj), msg="Time to remove %s.%s" % (module_name, obj)) + assert not hasattr(module, obj), "Time to remove %s.%s" % (module_name, obj) def test_attribute_removal(): @@ -53,5 +54,4 @@ def test_attribute_removal(): klass = getattr(module, cls) except AttributeError: continue - assert_false(hasattr(klass, attr), - msg="Time to remove %s.%s.%s" % (module_name, cls, attr)) + assert not hasattr(klass, attr), "Time to remove %s.%s.%s" % (module_name, cls, attr) diff --git a/nibabel/tests/test_round_trip.py b/nibabel/tests/test_round_trip.py index 5c3a12b086..79d785932d 100644 --- a/nibabel/tests/test_round_trip.py +++ b/nibabel/tests/test_round_trip.py @@ -11,8 +11,6 @@ from ..arraywriters import ScalingError from ..casting import best_float, ulp, type_info -from nose.tools import assert_true - from numpy.testing import assert_array_equal DEBUG = True @@ -193,4 +191,4 @@ def check_arr(test_id, V_in, in_type, out_type, scaling_type): slope, inter) # To help debugging failures with --pdb-failure np.nonzero(all_fails) - assert_true(this_test) + assert this_test diff --git a/nibabel/tests/test_rstutils.py b/nibabel/tests/test_rstutils.py index 51103c45ca..4fb83d3170 100644 --- a/nibabel/tests/test_rstutils.py +++ b/nibabel/tests/test_rstutils.py @@ -5,49 +5,46 @@ from ..rstutils import rst_table -from nose.tools import assert_equal, assert_raises +import pytest def test_rst_table(): # Tests for printable table function R, C = 3, 4 cell_values = np.arange(R * C).reshape((R, C)) - assert_equal(rst_table(cell_values), + assert (rst_table(cell_values) == """+--------+--------+--------+--------+--------+ | | col[0] | col[1] | col[2] | col[3] | +========+========+========+========+========+ | row[0] | 0.00 | 1.00 | 2.00 | 3.00 | | row[1] | 4.00 | 5.00 | 6.00 | 7.00 | | row[2] | 8.00 | 9.00 | 10.00 | 11.00 | -+--------+--------+--------+--------+--------+""" - ) - assert_equal(rst_table(cell_values, ['a', 'b', 'c']), ++--------+--------+--------+--------+--------+""") + assert (rst_table(cell_values, ['a', 'b', 'c']) == """+---+--------+--------+--------+--------+ | | col[0] | col[1] | col[2] | col[3] | +===+========+========+========+========+ | a | 0.00 | 1.00 | 2.00 | 3.00 | | b | 4.00 | 5.00 | 6.00 | 7.00 | | c | 8.00 | 9.00 | 10.00 | 11.00 | -+---+--------+--------+--------+--------+""" - ) - assert_raises(ValueError, - rst_table, cell_values, ['a', 'b']) - assert_raises(ValueError, - rst_table, cell_values, ['a', 'b', 'c', 'd']) - assert_equal(rst_table(cell_values, None, ['1', '2', '3', '4']), ++---+--------+--------+--------+--------+""") + with pytest.raises(ValueError): + rst_table(cell_values, ['a', 'b']) + with pytest.raises(ValueError): + rst_table(cell_values, ['a', 'b', 'c', 'd']) + assert (rst_table(cell_values, None, ['1', '2', '3', '4']) == """+--------+-------+-------+-------+-------+ | | 1 | 2 | 3 | 4 | +========+=======+=======+=======+=======+ | row[0] | 0.00 | 1.00 | 2.00 | 3.00 | | row[1] | 4.00 | 5.00 | 6.00 | 7.00 | | row[2] | 8.00 | 9.00 | 10.00 | 11.00 | -+--------+-------+-------+-------+-------+""" - ) - assert_raises(ValueError, - rst_table, cell_values, None, ['1', '2', '3']) - assert_raises(ValueError, - rst_table, cell_values, None, list('12345')) - assert_equal(rst_table(cell_values, title='A title'), ++--------+-------+-------+-------+-------+""") + with pytest.raises(ValueError): + rst_table(cell_values, None, ['1', '2', '3']) + with pytest.raises(ValueError): + rst_table(cell_values, None, list('12345')) + assert (rst_table(cell_values, title='A title') == """******* A title ******* @@ -58,29 +55,26 @@ def test_rst_table(): | row[0] | 0.00 | 1.00 | 2.00 | 3.00 | | row[1] | 4.00 | 5.00 | 6.00 | 7.00 | | row[2] | 8.00 | 9.00 | 10.00 | 11.00 | -+--------+--------+--------+--------+--------+""" - ) - assert_equal(rst_table(cell_values, val_fmt='{0}'), ++--------+--------+--------+--------+--------+""") + assert (rst_table(cell_values, val_fmt='{0}') == """+--------+--------+--------+--------+--------+ | | col[0] | col[1] | col[2] | col[3] | +========+========+========+========+========+ | row[0] | 0 | 1 | 2 | 3 | | row[1] | 4 | 5 | 6 | 7 | | row[2] | 8 | 9 | 10 | 11 | -+--------+--------+--------+--------+--------+""" - ) ++--------+--------+--------+--------+--------+""") # Doing a fancy cell format cell_values_back = np.arange(R * C)[::-1].reshape((R, C)) cell_3d = np.dstack((cell_values, cell_values_back)) - assert_equal(rst_table(cell_3d, val_fmt='{0[0]}-{0[1]}'), + assert (rst_table(cell_3d, val_fmt='{0[0]}-{0[1]}') == """+--------+--------+--------+--------+--------+ | | col[0] | col[1] | col[2] | col[3] | +========+========+========+========+========+ | row[0] | 0-11 | 1-10 | 2-9 | 3-8 | | row[1] | 4-7 | 5-6 | 6-5 | 7-4 | | row[2] | 8-3 | 9-2 | 10-1 | 11-0 | -+--------+--------+--------+--------+--------+""" - ) ++--------+--------+--------+--------+--------+""") # Test formatting characters formats = dict( down='!', @@ -88,7 +82,7 @@ def test_rst_table(): thick_long='~', cross='%', title_heading='#') - assert_equal(rst_table(cell_values, title='A title', format_chars=formats), + assert (rst_table(cell_values, title='A title', format_chars=formats) == """####### A title ####### @@ -99,10 +93,7 @@ def test_rst_table(): ! row[0] ! 0.00 ! 1.00 ! 2.00 ! 3.00 ! ! row[1] ! 4.00 ! 5.00 ! 6.00 ! 7.00 ! ! row[2] ! 8.00 ! 9.00 ! 10.00 ! 11.00 ! -%________%________%________%________%________%""" - ) +%________%________%________%________%________%""") formats['funny_value'] = '!' - assert_raises(ValueError, - rst_table, - cell_values, title='A title', format_chars=formats) - return + with pytest.raises(ValueError): + rst_table(cell_values, title='A title', format_chars=formats) From 152abea74e0767c54cb5b6b38713fe4c35b07322 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Sun, 1 Dec 2019 11:25:16 -0500 Subject: [PATCH 012/223] converting test to pytest, TODO: some tests are failing on osx --- nibabel/tests/test_scaling.py | 249 ++++++++++++++++++---------------- 1 file changed, 130 insertions(+), 119 deletions(-) diff --git a/nibabel/tests/test_scaling.py b/nibabel/tests/test_scaling.py index cd66bbfe3a..443fbfd729 100644 --- a/nibabel/tests/test_scaling.py +++ b/nibabel/tests/test_scaling.py @@ -13,97 +13,99 @@ from io import BytesIO from ..volumeutils import finite_range, apply_read_scaling, array_to_file, array_from_file from ..casting import type_info -from ..testing import suppress_warnings +from ..testing_pytest import suppress_warnings from .test_volumeutils import _calculate_scale from numpy.testing import (assert_array_almost_equal, assert_array_equal) - -from nose.tools import (assert_true, assert_equal, assert_raises, - assert_not_equal) +import pytest # Debug print statements DEBUG = True -def test_finite_range(): +@pytest.mark.parametrize("in_arr, res", [ + ([[-1, 0, 1], [np.inf, np.nan, -np.inf]], (-1, 1)), + (np.array([[-1, 0, 1], [np.inf, np.nan, -np.inf]]), (-1, 1)), + ([[np.nan], [np.nan]], (np.inf, -np.inf)), # all nans slices + (np.zeros((3, 4, 5)) + np.nan, (np.inf, -np.inf)), + ([[-np.inf], [np.inf]], (np.inf, -np.inf)), # all infs slices + (np.zeros((3, 4, 5)) + np.inf, (np.inf, -np.inf)), + ([[np.nan, -1, 2], [-2, np.nan, 1]], (-2, 2)), + ([[np.nan, -np.inf, 2], [-2, np.nan, np.inf]], (-2, 2)), + ([[-np.inf, 2], [np.nan, 1]], (1, 2)), # good max case + ([[np.nan, -np.inf, 2], [-2, np.nan, np.inf]], (-2, 2)), + ([np.nan], (np.inf, -np.inf)), + ([np.inf], (np.inf, -np.inf)), + ([-np.inf], (np.inf, -np.inf)), + ([np.inf, 1], (1, 1)), # only look at finite values + ([-np.inf, 1], (1, 1)), + ([[], []], (np.inf, -np.inf)), # empty array + (np.array([[-3, 0, 1], [2, -1, 4]], dtype=np.int), (-3, 4)), + (np.array([[1, 0, 1], [2, 3, 4]], dtype=np.uint), (0, 4)), + ([0., 1, 2, 3], (0, 3)), + # Complex comparison works as if they are floats + ([[np.nan, -1 - 100j, 2], [-2, np.nan, 1 + 100j]], (-2, 2)), + ([[np.nan, -1, 2 - 100j], [-2 + 100j, np.nan, 1]], (-2 + 100j, 2 - 100j)), +]) +def test_finite_range(in_arr, res): # Finite range utility function - for in_arr, res in ( - ([[-1, 0, 1], [np.inf, np.nan, -np.inf]], (-1, 1)), - (np.array([[-1, 0, 1], [np.inf, np.nan, -np.inf]]), (-1, 1)), - ([[np.nan], [np.nan]], (np.inf, -np.inf)), # all nans slices - (np.zeros((3, 4, 5)) + np.nan, (np.inf, -np.inf)), - ([[-np.inf], [np.inf]], (np.inf, -np.inf)), # all infs slices - (np.zeros((3, 4, 5)) + np.inf, (np.inf, -np.inf)), - ([[np.nan, -1, 2], [-2, np.nan, 1]], (-2, 2)), - ([[np.nan, -np.inf, 2], [-2, np.nan, np.inf]], (-2, 2)), - ([[-np.inf, 2], [np.nan, 1]], (1, 2)), # good max case - ([[np.nan, -np.inf, 2], [-2, np.nan, np.inf]], (-2, 2)), - ([np.nan], (np.inf, -np.inf)), - ([np.inf], (np.inf, -np.inf)), - ([-np.inf], (np.inf, -np.inf)), - ([np.inf, 1], (1, 1)), # only look at finite values - ([-np.inf, 1], (1, 1)), - ([[], []], (np.inf, -np.inf)), # empty array - (np.array([[-3, 0, 1], [2, -1, 4]], dtype=np.int), (-3, 4)), - (np.array([[1, 0, 1], [2, 3, 4]], dtype=np.uint), (0, 4)), - ([0., 1, 2, 3], (0, 3)), - # Complex comparison works as if they are floats - ([[np.nan, -1 - 100j, 2], [-2, np.nan, 1 + 100j]], (-2, 2)), - ([[np.nan, -1, 2 - 100j], [-2 + 100j, np.nan, 1]], (-2 + 100j, 2 - 100j)), - ): - assert_equal(finite_range(in_arr), res) - assert_equal(finite_range(in_arr, False), res) - assert_equal(finite_range(in_arr, check_nan=False), res) - has_nan = np.any(np.isnan(in_arr)) - assert_equal(finite_range(in_arr, True), res + (has_nan,)) - assert_equal(finite_range(in_arr, check_nan=True), res + (has_nan,)) - in_arr = np.array(in_arr) - flat_arr = in_arr.ravel() - assert_equal(finite_range(flat_arr), res) - assert_equal(finite_range(flat_arr, True), res + (has_nan,)) - # Check float types work as complex - if in_arr.dtype.kind == 'f': - c_arr = in_arr.astype(np.complex) - assert_equal(finite_range(c_arr), res) - assert_equal(finite_range(c_arr, True), res + (has_nan,)) + assert finite_range(in_arr) == res + assert finite_range(in_arr, False) == res + assert finite_range(in_arr, check_nan=False) == res + has_nan = np.any(np.isnan(in_arr)) + assert finite_range(in_arr, True) == res + (has_nan,) + assert finite_range(in_arr, check_nan=True) == res + (has_nan,) + in_arr = np.array(in_arr) + flat_arr = in_arr.ravel() + assert finite_range(flat_arr) == res + assert finite_range(flat_arr, True) == res + (has_nan,) + # Check float types work as complex + if in_arr.dtype.kind == 'f': + c_arr = in_arr.astype(np.complex) + assert finite_range(c_arr) == res + assert finite_range(c_arr, True) == res + (has_nan,) + + +def test_finite_range_err(): # Test error cases a = np.array([[1., 0, 1], [2, 3, 4]]).view([('f1', 'f')]) - assert_raises(TypeError, finite_range, a) + with pytest.raises(TypeError): + finite_range(a) -def test_a2f_mn_mx(): +@pytest.mark.parametrize("out_type", [np.int16, np.float32]) +def test_a2f_mn_mx(out_type): # Test array to file mn, mx handling str_io = BytesIO() - for out_type in (np.int16, np.float32): - arr = np.arange(6, dtype=out_type) - arr_orig = arr.copy() # safe backup for testing against - # Basic round trip to warm up - array_to_file(arr, str_io) - data_back = array_from_file(arr.shape, out_type, str_io) - assert_array_equal(arr, data_back) - # Clip low - array_to_file(arr, str_io, mn=2) - data_back = array_from_file(arr.shape, out_type, str_io) - # arr unchanged - assert_array_equal(arr, arr_orig) - # returned value clipped low - assert_array_equal(data_back, [2, 2, 2, 3, 4, 5]) - # Clip high - array_to_file(arr, str_io, mx=4) - data_back = array_from_file(arr.shape, out_type, str_io) - # arr unchanged - assert_array_equal(arr, arr_orig) - # returned value clipped high - assert_array_equal(data_back, [0, 1, 2, 3, 4, 4]) - # Clip both - array_to_file(arr, str_io, mn=2, mx=4) - data_back = array_from_file(arr.shape, out_type, str_io) - # arr unchanged - assert_array_equal(arr, arr_orig) - # returned value clipped high - assert_array_equal(data_back, [2, 2, 2, 3, 4, 4]) + arr = np.arange(6, dtype=out_type) + arr_orig = arr.copy() # safe backup for testing against + # Basic round trip to warm up + array_to_file(arr, str_io) + data_back = array_from_file(arr.shape, out_type, str_io) + assert_array_equal(arr, data_back) + # Clip low + array_to_file(arr, str_io, mn=2) + data_back = array_from_file(arr.shape, out_type, str_io) + # arr unchanged + assert_array_equal(arr, arr_orig) + # returned value clipped low + assert_array_equal(data_back, [2, 2, 2, 3, 4, 5]) + # Clip high + array_to_file(arr, str_io, mx=4) + data_back = array_from_file(arr.shape, out_type, str_io) + # arr unchanged + assert_array_equal(arr, arr_orig) + # returned value clipped high + assert_array_equal(data_back, [0, 1, 2, 3, 4, 4]) + # Clip both + array_to_file(arr, str_io, mn=2, mx=4) + data_back = array_from_file(arr.shape, out_type, str_io) + # arr unchanged + assert_array_equal(arr, arr_orig) + # returned value clipped high + assert_array_equal(data_back, [2, 2, 2, 3, 4, 4]) def test_a2f_nan2zero(): @@ -129,54 +131,63 @@ def test_a2f_nan2zero(): assert_array_equal(data_back, [np.array(np.nan).astype(np.int32), 99]) -def test_array_file_scales(): +@pytest.mark.parametrize("in_type, out_type, err", [ + (np.int16, np.int16, None), + (np.int16, np.int8, None), + (np.uint16, np.uint8, None), + (np.int32, np.int8, None), + (np.float32, np.uint8, None), + (np.float32, np.int16, None) +]) +def test_array_file_scales(in_type, out_type, err): # Test scaling works for max, min when going from larger to smaller type, # and from float to integer. bio = BytesIO() - for in_type, out_type, err in ((np.int16, np.int16, None), - (np.int16, np.int8, None), - (np.uint16, np.uint8, None), - (np.int32, np.int8, None), - (np.float32, np.uint8, None), - (np.float32, np.int16, None)): - out_dtype = np.dtype(out_type) - arr = np.zeros((3,), dtype=in_type) - info = type_info(in_type) - arr[0], arr[1] = info['min'], info['max'] - if not err is None: - assert_raises(err, _calculate_scale, arr, out_dtype, True) - continue - slope, inter, mn, mx = _calculate_scale(arr, out_dtype, True) - array_to_file(arr, bio, out_type, 0, inter, slope, mn, mx) - bio.seek(0) - arr2 = array_from_file(arr.shape, out_dtype, bio) - arr3 = apply_read_scaling(arr2, slope, inter) - # Max rounding error for integer type - max_miss = slope / 2. - assert_true(np.all(np.abs(arr - arr3) <= max_miss)) - bio.truncate(0) - bio.seek(0) - - -def test_scaling_in_abstract(): + out_dtype = np.dtype(out_type) + arr = np.zeros((3,), dtype=in_type) + info = type_info(in_type) + arr[0], arr[1] = info['min'], info['max'] + if not err is None: + with pytest.raises(err): + _calculate_scale, arr, out_dtype, True) + return + slope, inter, mn, mx = _calculate_scale(arr, out_dtype, True) + array_to_file(arr, bio, out_type, 0, inter, slope, mn, mx) + bio.seek(0) + arr2 = array_from_file(arr.shape, out_dtype, bio) + arr3 = apply_read_scaling(arr2, slope, inter) + # Max rounding error for integer type + max_miss = slope / 2. + assert np.all(np.abs(arr - arr3) <= max_miss) + bio.truncate(0) + bio.seek(0) + + +@pytest.mark.parametrize("category0, category1",[ + ('int', 'int'), + ('uint', 'int'), +]) +def test_scaling_in_abstract(category0, category1): # Confirm that, for all ints and uints as input, and all possible outputs, # for any simple way of doing the calculation, the result is near enough - for category0, category1 in (('int', 'int'), - ('uint', 'int'), - ): - for in_type in np.sctypes[category0]: - for out_type in np.sctypes[category1]: - check_int_a2f(in_type, out_type) + for in_type in np.sctypes[category0]: + for out_type in np.sctypes[category1]: + check_int_a2f(in_type, out_type) + + +@pytest.mark.parametrize("category0, category1", [ + ('float', 'int'), + ('float', 'uint'), + ('complex', 'int'), + ('complex', 'uint'), +]) +def test_scaling_in_abstract_warn(category0, category1): + # Converting floats to integer - for category0, category1 in (('float', 'int'), - ('float', 'uint'), - ('complex', 'int'), - ('complex', 'uint'), - ): - for in_type in np.sctypes[category0]: - for out_type in np.sctypes[category1]: - with suppress_warnings(): # overflow - check_int_a2f(in_type, out_type) + for in_type in np.sctypes[category0]: + for out_type in np.sctypes[category1]: + with suppress_warnings(): # overflow + check_int_a2f(in_type, out_type) def check_int_a2f(in_type, out_type): @@ -205,7 +216,7 @@ def check_int_a2f(in_type, out_type): array_to_file(data, str_io, out_type, 0, inter, scale, mn, mx) data_back = array_from_file(data.shape, out_type, str_io) data_back = apply_read_scaling(data_back, scale, inter) - assert_true(np.allclose(big_floater(data), big_floater(data_back))) + assert np.allclose(big_floater(data), big_floater(data_back)) # Try with analyze-size scale and inter scale32 = np.float32(scale) inter32 = np.float32(inter) @@ -216,5 +227,5 @@ def check_int_a2f(in_type, out_type): # Clip at extremes to remove inf info = type_info(in_type) out_min, out_max = info['min'], info['max'] - assert_true(np.allclose(big_floater(data), - big_floater(np.clip(data_back, out_min, out_max)))) + assert np.allclose(big_floater(data), + big_floater(np.clip(data_back, out_min, out_max))) From 2ebef2665ec561d21fa5aae0ac673fd301b73aeb Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Sun, 1 Dec 2019 13:06:03 -0500 Subject: [PATCH 013/223] adding pytestmark to test that has not been changed to pytest --- nibabel/tests/test_scripts.py | 1 + nibabel/tests/test_spaces.py | 2 +- nibabel/tests/test_spatialimages.py | 2 +- nibabel/tests/test_spm2analyze.py | 2 +- nibabel/tests/test_spm99analyze.py | 1 + nibabel/tests/test_testing.py | 2 +- nibabel/tests/test_tmpdirs.py | 1 + nibabel/tests/test_trackvis.py | 2 +- nibabel/tests/test_tripwire.py | 2 +- nibabel/tests/test_viewers.py | 1 + nibabel/tests/test_volumeutils.py | 1 + 11 files changed, 11 insertions(+), 6 deletions(-) diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 431e606380..5e7defdaa5 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -33,6 +33,7 @@ from .test_parrec_data import BALLS, AFF_OFF from ..testing_pytest import assert_data_similar +import pytest; pytestmark = pytest.mark.skip() def _proc_stdout(stdout): stdout_str = stdout.decode('latin1').strip() diff --git a/nibabel/tests/test_spaces.py b/nibabel/tests/test_spaces.py index 2520d32225..119ecfd5c3 100644 --- a/nibabel/tests/test_spaces.py +++ b/nibabel/tests/test_spaces.py @@ -15,7 +15,7 @@ from nose.tools import (assert_true, assert_false, assert_raises, assert_equal, assert_not_equal) - +import pytest; pytestmark = pytest.mark.skip() def assert_all_in(in_shape, in_affine, out_shape, out_affine): slices = tuple(slice(N) for N in in_shape) diff --git a/nibabel/tests/test_spatialimages.py b/nibabel/tests/test_spatialimages.py index 3f9c8b4b97..5b4706bea1 100644 --- a/nibabel/tests/test_spatialimages.py +++ b/nibabel/tests/test_spatialimages.py @@ -30,7 +30,7 @@ from ..tmpdirs import InTemporaryDirectory from ..deprecator import ExpiredDeprecationError from .. import load as top_load - +import pytest; pytestmark = pytest.mark.skip() def test_header_init(): # test the basic header diff --git a/nibabel/tests/test_spm2analyze.py b/nibabel/tests/test_spm2analyze.py index e39e79b96e..ddf2956f7d 100644 --- a/nibabel/tests/test_spm2analyze.py +++ b/nibabel/tests/test_spm2analyze.py @@ -18,7 +18,7 @@ from ..testing import assert_equal, assert_raises from . import test_spm99analyze - +import pytest; pytestmark = pytest.mark.skip() class TestSpm2AnalyzeHeader(test_spm99analyze.TestSpm99AnalyzeHeader): header_class = Spm2AnalyzeHeader diff --git a/nibabel/tests/test_spm99analyze.py b/nibabel/tests/test_spm99analyze.py index 71fe41e2ec..ecc63e5935 100644 --- a/nibabel/tests/test_spm99analyze.py +++ b/nibabel/tests/test_spm99analyze.py @@ -32,6 +32,7 @@ from ..testing_pytest import bytesio_round_trip, bytesio_filemap from . import test_analyze +import pytest; pytestmark = pytest.mark.skip() FLOAT_TYPES = np.sctypes['float'] COMPLEX_TYPES = np.sctypes['complex'] diff --git a/nibabel/tests/test_testing.py b/nibabel/tests/test_testing.py index e9f2d079ea..171447560e 100644 --- a/nibabel/tests/test_testing.py +++ b/nibabel/tests/test_testing.py @@ -11,7 +11,7 @@ from ..testing import (error_warnings, suppress_warnings, clear_and_catch_warnings, assert_allclose_safely, get_fresh_mod, assert_re_in, test_data, data_path) - +import pytest; pytestmark = pytest.mark.skip() def test_assert_allclose_safely(): # Test the safe version of allclose diff --git a/nibabel/tests/test_tmpdirs.py b/nibabel/tests/test_tmpdirs.py index 1d35b59269..7914e273e1 100644 --- a/nibabel/tests/test_tmpdirs.py +++ b/nibabel/tests/test_tmpdirs.py @@ -6,6 +6,7 @@ from ..tmpdirs import InGivenDirectory from nose.tools import assert_true, assert_equal +import pytest; pytestmark = pytest.mark.skip() MY_PATH = abspath(__file__) MY_DIR = dirname(MY_PATH) diff --git a/nibabel/tests/test_trackvis.py b/nibabel/tests/test_trackvis.py index 076e22f74e..676ee52d87 100644 --- a/nibabel/tests/test_trackvis.py +++ b/nibabel/tests/test_trackvis.py @@ -12,7 +12,7 @@ from numpy.testing import assert_array_almost_equal from ..testing import (assert_true, assert_false, assert_equal, assert_raises, assert_warns, assert_array_equal, suppress_warnings) - +import pytest; pytestmark = pytest.mark.skip() def test_write(): streams = [] diff --git a/nibabel/tests/test_tripwire.py b/nibabel/tests/test_tripwire.py index 05d3b1eb3f..990f0bbf39 100644 --- a/nibabel/tests/test_tripwire.py +++ b/nibabel/tests/test_tripwire.py @@ -5,7 +5,7 @@ from nose.tools import (assert_true, assert_false, assert_raises, assert_equal, assert_not_equal) - +import pytest; pytestmark = pytest.mark.skip() def test_is_tripwire(): assert_false(is_tripwire(object())) diff --git a/nibabel/tests/test_viewers.py b/nibabel/tests/test_viewers.py index 68710b3126..0e3f076223 100644 --- a/nibabel/tests/test_viewers.py +++ b/nibabel/tests/test_viewers.py @@ -18,6 +18,7 @@ from numpy.testing import assert_array_equal, assert_equal from nose.tools import assert_raises, assert_true +import pytest; pytestmark = pytest.mark.skip() # Need at least MPL 1.3 for viewer tests. matplotlib, has_mpl, _ = optional_package('matplotlib', min_version='1.3') diff --git a/nibabel/tests/test_volumeutils.py b/nibabel/tests/test_volumeutils.py index d391abf359..711894aabc 100644 --- a/nibabel/tests/test_volumeutils.py +++ b/nibabel/tests/test_volumeutils.py @@ -61,6 +61,7 @@ from ..testing_pytest import (assert_dt_equal, assert_allclose_safely, suppress_warnings, clear_and_catch_warnings) +import pytest; pytestmark = pytest.mark.skip() #: convenience variables for numpy types FLOAT_TYPES = np.sctypes['float'] From d68ba9d675cf03993246070c8677cd9ce146a1cc Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Sun, 1 Dec 2019 15:51:34 -0500 Subject: [PATCH 014/223] fixing test_wrapstruct: removing setUpClass and adding self.header_class check to all of the test methods: couldnt find better way for suppressing tests from abstract classes and allowing for testing from all child classes --- nibabel/tests/test_wrapstruct.py | 32 ++++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/nibabel/tests/test_wrapstruct.py b/nibabel/tests/test_wrapstruct.py index b5ccdd2907..f627109fd0 100644 --- a/nibabel/tests/test_wrapstruct.py +++ b/nibabel/tests/test_wrapstruct.py @@ -118,13 +118,9 @@ def get_bad_bb(self): # means do not check return None - @classmethod - def setUpClass(cls): - if cls.header_class is None: - raise SkipTest("no testing methods from the abstract class") - - def test_general_init(self): + if not self.header_class: + pytest.skip() hdr = self.header_class() # binaryblock has length given by header data dtype binblock = hdr.binaryblock @@ -144,6 +140,8 @@ def _set_something_into_hdr(self, hdr): def test__eq__(self): # Test equal and not equal + if not self.header_class: + pytest.skip() hdr1 = self.header_class() hdr2 = self.header_class() assert hdr1 == hdr2 @@ -160,6 +158,8 @@ def test__eq__(self): def test_to_from_fileobj(self): # Successful write using write_to + if not self.header_class: + pytest.skip() hdr = self.header_class() str_io = BytesIO() hdr.write_to(str_io) @@ -169,6 +169,8 @@ def test_to_from_fileobj(self): assert hdr2.binaryblock == hdr.binaryblock def test_mappingness(self): + if not self.header_class: + pytest.skip() hdr = self.header_class() with pytest.raises(ValueError): hdr.__setitem__('nonexistent key', 0.1) @@ -205,12 +207,16 @@ def test_endianness_ro(self): endianness on initialization (or occasionally byteswapping the data) - but this is done via via the as_byteswapped method ''' + if not self.header_class: + pytest.skip() hdr = self.header_class() with pytest.raises(AttributeError): hdr.__setattr__('endianness', '<') def test_endian_guess(self): # Check guesses of endian + if not self.header_class: + pytest.skip() eh = self.header_class() assert eh.endianness == native_code hdr_data = eh.structarr.copy() @@ -225,6 +231,8 @@ def test_binblock_is_file(self): # strings following. More generally, there may be other perhaps # optional data after the binary block, in which case you will need to # override this test + if not self.header_class: + pytest.skip() hdr = self.header_class() str_io = BytesIO() hdr.write_to(str_io) @@ -232,6 +240,8 @@ def test_binblock_is_file(self): def test_structarr(self): # structarr attribute also read only + if not self.header_class: + pytest.skip() hdr = self.header_class() # Just check we can get structarr hdr.structarr @@ -250,6 +260,8 @@ def assert_no_log_err(self, hdr): def test_bytes(self): # Test get of bytes + if not self.header_class: + pytest.skip() hdr1 = self.header_class() bb = hdr1.binaryblock hdr2 = self.header_class(hdr1.binaryblock) @@ -280,6 +292,8 @@ def test_bytes(self): def test_as_byteswapped(self): # Check byte swapping + if not self.header_class: + pytest.skip() hdr = self.header_class() assert hdr.endianness == native_code # same code just returns a copy @@ -304,6 +318,8 @@ def check_fix(self, *args, **kwargs): def test_empty_check(self): # Empty header should be error free + if not self.header_class: + pytest.skip() hdr = self.header_class() hdr.check_fix(error_level=0) @@ -313,6 +329,8 @@ def _dxer(self, hdr): return self.header_class.diagnose_binaryblock(binblock) def test_str(self): + if not self.header_class: + pytest.skip() hdr = self.header_class() # Check something returns from str s1 = str(hdr) @@ -326,6 +344,8 @@ class _TestLabeledWrapStruct(_TestWrapStructBase): def test_get_value_label(self): # Test get value label method # Make a new class to avoid overwriting recoders of original + if not self.header_class: + pytest.skip() class MyHdr(self.header_class): _field_recoders = {} hdr = MyHdr() From 4f2aa9aef73edc0e44a8f601fb44f3bc9085fee4 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Sun, 1 Dec 2019 15:53:08 -0500 Subject: [PATCH 015/223] changing travis command after fixes in test_wrapstruct --- .travis.yml | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index f4fff97719..ca6b4729dc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -130,11 +130,7 @@ script: cd for_testing cp ../.coveragerc . nosetests --with-doctest --with-coverage --cover-package nibabel nibabel - pytest -v ../nibabel/tests/test_a*.py ../nibabel/tests/test_b*.py ../nibabel/tests/test_c*.py ../nibabel/tests/test_d*.py - pytest -v../nibabel/tests/test_e*.py ../nibabel/tests/test_f*.py ../nibabel/tests/test_h*.py - pytest -v../nibabel/tests/test_i*.py ../nibabel/tests/test_k*.py ../nibabel/tests/test_l*.py ../nibabel/tests/test_m*.py - pytest -v../nibabel/tests/test_n*.py ../nibabel/tests/test_o*.py ../nibabel/tests/test_p*.py ../nibabel/tests/test_q*.py - pytest -v ../nibabel/tests/test_w*.py + pytest -v ../nibabel/tests else false fi From e211a477ee94d1ea2fd1b2e447b46fe11b7d36e2 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Sat, 25 Jan 2020 14:29:08 -0500 Subject: [PATCH 016/223] MNT: Separate out pytest and nose jobs --- .azure-pipelines/windows.yml | 10 +++++++--- .travis.yml | 13 +++++++++++-- setup.cfg | 9 +++++---- 3 files changed, 23 insertions(+), 9 deletions(-) diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index f825bef612..d96b40a714 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -29,17 +29,21 @@ jobs: displayName: 'Update build tools' - script: | python -m pip install --find-links %EXTRA_WHEELS% %DEPENDS% - python -m pip install nose mock coverage codecov pytest + python -m pip install nose coverage codecov pytest displayName: 'Install dependencies' - script: | - python -m pip install . + python -m pip install '.[$(CHECK_TYPE)]' SET NIBABEL_DATA_DIR=%CD%\\nibabel-data displayName: 'Install nibabel' - script: | mkdir for_testing cd for_testing cp ../.coveragerc . - nosetests --with-doctest --with-coverage --cover-package nibabel nibabel + if %CHECK_TYPE%=="nosetests" ( + nosetests --with-doctest --with-coverage --cover-package nibabel nibabel + ) else ( + pytest --doctest-modules --cov nibabel -v --pyargs nibabel --deselect streamlines + ) displayName: 'Nose tests' - script: | cd for_testing diff --git a/.travis.yml b/.travis.yml index ca6b4729dc..aed8cf06a3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -28,6 +28,10 @@ python: matrix: include: + # Old nosetests - Remove soon + - python: 3.7 + env: + - CHECK_TYPE="nosetests" # Basic dependencies only - python: 3.5 env: @@ -124,13 +128,18 @@ script: cd doc make html; make doctest; - elif [ "${CHECK_TYPE}" == "test" ]; then + elif [ "${CHECK_TYPE}" == "nosetests" ]; then # Change into an innocuous directory and find tests from installation mkdir for_testing cd for_testing cp ../.coveragerc . nosetests --with-doctest --with-coverage --cover-package nibabel nibabel - pytest -v ../nibabel/tests + elif [ "${CHECK_TYPE}" == "test" ]; then + # Change into an innocuous directory and find tests from installation + mkdir for_testing + cd for_testing + cp ../.coveragerc . + pytest --doctest-modules --cov nibabel -v --pyargs nibabel --deselect streamlines else false fi diff --git a/setup.cfg b/setup.cfg index d425dd2371..5719650bf8 100644 --- a/setup.cfg +++ b/setup.cfg @@ -32,10 +32,6 @@ python_requires = >=3.5.1 install_requires = numpy >=1.13 packaging >=14.3 -tests_require = - nose >=0.11 - pytest -test_suite = nose.collector zip_safe = False packages = find: @@ -59,10 +55,15 @@ spm = scipy style = flake8 +nosetests = + coverage + nose >=0.11 + pytest test = coverage nose >=0.11 pytest + pytest-cov all = %(dicomfs)s %(dev)s From df6a28ec2015d00ed0fb3c0bd130aae9b8586b61 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Sat, 25 Jan 2020 14:34:40 -0500 Subject: [PATCH 017/223] TEST: Fix tests broken in the rebase --- nibabel/tests/test_minc1.py | 2 +- nibabel/tests/test_processing.py | 5 +++-- nibabel/tests/test_scaling.py | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/nibabel/tests/test_minc1.py b/nibabel/tests/test_minc1.py index 5b53d021c4..837957e566 100644 --- a/nibabel/tests/test_minc1.py +++ b/nibabel/tests/test_minc1.py @@ -112,7 +112,7 @@ def test_old_namespace(): MincImage(arr, aff) # Another old name from ..minc1 import MincFile, Minc1File - assert_false(MincFile is Minc1File) + assert MincFile is not Minc1File with pytest.raises(ExpiredDeprecationError): mf = MincFile(netcdf_file(EG_FNAME)) diff --git a/nibabel/tests/test_processing.py b/nibabel/tests/test_processing.py index 58c2573d63..dea34b85a2 100644 --- a/nibabel/tests/test_processing.py +++ b/nibabel/tests/test_processing.py @@ -172,7 +172,8 @@ def test_resample_from_to(): assert out.__class__ == Nifti1Image # From 2D to 3D, error, the fixed affine is not invertible img_2d = Nifti1Image(data[:, :, 0], affine) - assert_raises(AffineError, resample_from_to, img_2d, img) + with pytest.raises(AffineError): + resample_from_to(img_2d, img) # 3D to 2D, we don't need to invert the fixed matrix out = resample_from_to(img, img_2d) assert_array_equal(out.dataobj, data[:, :, 0]) @@ -186,7 +187,7 @@ def test_resample_from_to(): assert_almost_equal(data_4d, out.dataobj) assert_array_equal(img_4d.affine, out.affine) # Errors trying to match 3D to 4D - with pytest.rises(ValueError): + with pytest.raises(ValueError): resample_from_to(img_4d, img) with pytest.raises(ValueError): resample_from_to(img, img_4d) diff --git a/nibabel/tests/test_scaling.py b/nibabel/tests/test_scaling.py index 443fbfd729..ec335e5c24 100644 --- a/nibabel/tests/test_scaling.py +++ b/nibabel/tests/test_scaling.py @@ -149,7 +149,7 @@ def test_array_file_scales(in_type, out_type, err): arr[0], arr[1] = info['min'], info['max'] if not err is None: with pytest.raises(err): - _calculate_scale, arr, out_dtype, True) + _calculate_scale(arr, out_dtype, True) return slope, inter, mn, mx = _calculate_scale(arr, out_dtype, True) array_to_file(arr, bio, out_type, 0, inter, slope, mn, mx) From bfb63fcb37459e69bd5eb34baded1515af1d2b22 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Sat, 25 Jan 2020 14:36:29 -0500 Subject: [PATCH 018/223] CI: Add CHECK_TYPE to Azure --- .azure-pipelines/windows.yml | 3 ++- azure-pipelines.yml | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index d96b40a714..f7b316932a 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -11,6 +11,7 @@ jobs: variables: EXTRA_WHEELS: "https://5cf40426d9f06eb7461d-6fe47d9331aba7cd62fc36c7196769e4.ssl.cf2.rackcdn.com" DEPENDS: numpy scipy matplotlib h5py pydicom + CHECK_TYPE: test strategy: matrix: ${{ insert }}: ${{ parameters.matrix }} @@ -32,7 +33,7 @@ jobs: python -m pip install nose coverage codecov pytest displayName: 'Install dependencies' - script: | - python -m pip install '.[$(CHECK_TYPE)]' + python -m pip install .[$(CHECK_TYPE)] SET NIBABEL_DATA_DIR=%CD%\\nibabel-data displayName: 'Install nibabel' - script: | diff --git a/azure-pipelines.yml b/azure-pipelines.yml index d09c5b7740..2ef2539c74 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -34,3 +34,7 @@ jobs: py38-x64: PYTHON_VERSION: '3.8' PYTHON_ARCH: 'x64' + nosetests: + PYTHON_VERSION: '3.6' + PYTHON_ARCH: 'x64' + CHECK_TYPE: 'nosetests' From 75298a43a28d4e745cb70c82181a7c5254985817 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Sat, 25 Jan 2020 14:44:48 -0500 Subject: [PATCH 019/223] CI: Default to nose for Windows for now --- .azure-pipelines/windows.yml | 2 +- azure-pipelines.yml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index f7b316932a..363cd64eb4 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -11,7 +11,7 @@ jobs: variables: EXTRA_WHEELS: "https://5cf40426d9f06eb7461d-6fe47d9331aba7cd62fc36c7196769e4.ssl.cf2.rackcdn.com" DEPENDS: numpy scipy matplotlib h5py pydicom - CHECK_TYPE: test + CHECK_TYPE: nosetests strategy: matrix: ${{ insert }}: ${{ parameters.matrix }} diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 2ef2539c74..5bbd37986c 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -34,7 +34,7 @@ jobs: py38-x64: PYTHON_VERSION: '3.8' PYTHON_ARCH: 'x64' - nosetests: + pytest: PYTHON_VERSION: '3.6' PYTHON_ARCH: 'x64' - CHECK_TYPE: 'nosetests' + CHECK_TYPE: 'test' From 77402be4ba466bc2788135dad4f64e5f20f960d2 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Sat, 25 Jan 2020 14:59:15 -0500 Subject: [PATCH 020/223] RF: Avoid running data script code on doctest --- nibabel/tests/data/gen_standard.py | 65 ++++++++++++++------------- nibabel/tests/data/make_moved_anat.py | 17 +++---- 2 files changed, 42 insertions(+), 40 deletions(-) diff --git a/nibabel/tests/data/gen_standard.py b/nibabel/tests/data/gen_standard.py index b97da8ff2f..f966b5599d 100644 --- a/nibabel/tests/data/gen_standard.py +++ b/nibabel/tests/data/gen_standard.py @@ -52,35 +52,36 @@ def _gen_straight_streamline(start, end, steps=3): return streamlines -rng = np.random.RandomState(42) - -width = 4 # Coronal -height = 5 # Sagittal -depth = 7 # Axial - -voxel_size = np.array((1., 3., 2.)) - -# Generate a random mask with voxel order RAS+. -mask = rng.rand(width, height, depth) > 0.8 -mask = (255*mask).astype(np.uint8) - -# Build tractogram -streamlines = mark_the_spot(mask) -tractogram = nib.streamlines.Tractogram(streamlines) - -# Build header -affine = np.eye(4) -affine[range(3), range(3)] = voxel_size -header = {Field.DIMENSIONS: (width, height, depth), - Field.VOXEL_SIZES: voxel_size, - Field.VOXEL_TO_RASMM: affine, - Field.VOXEL_ORDER: 'RAS'} - -# Save the standard mask. -nii = nib.Nifti1Image(mask, affine=affine) -nib.save(nii, "standard.nii.gz") - -# Save the standard tractogram in every available file format. -for ext, cls in FORMATS.items(): - tfile = cls(tractogram, header) - nib.streamlines.save(tfile, "standard" + ext) +if __name__ == '__main__': + rng = np.random.RandomState(42) + + width = 4 # Coronal + height = 5 # Sagittal + depth = 7 # Axial + + voxel_size = np.array((1., 3., 2.)) + + # Generate a random mask with voxel order RAS+. + mask = rng.rand(width, height, depth) > 0.8 + mask = (255*mask).astype(np.uint8) + + # Build tractogram + streamlines = mark_the_spot(mask) + tractogram = nib.streamlines.Tractogram(streamlines) + + # Build header + affine = np.eye(4) + affine[range(3), range(3)] = voxel_size + header = {Field.DIMENSIONS: (width, height, depth), + Field.VOXEL_SIZES: voxel_size, + Field.VOXEL_TO_RASMM: affine, + Field.VOXEL_ORDER: 'RAS'} + + # Save the standard mask. + nii = nib.Nifti1Image(mask, affine=affine) + nib.save(nii, "standard.nii.gz") + + # Save the standard tractogram in every available file format. + for ext, cls in FORMATS.items(): + tfile = cls(tractogram, header) + nib.streamlines.save(tfile, "standard" + ext) diff --git a/nibabel/tests/data/make_moved_anat.py b/nibabel/tests/data/make_moved_anat.py index 6fba2d0902..ec0817885c 100644 --- a/nibabel/tests/data/make_moved_anat.py +++ b/nibabel/tests/data/make_moved_anat.py @@ -12,11 +12,12 @@ from nibabel.eulerangles import euler2mat from nibabel.affines import from_matvec -img = nib.load('anatomical.nii') -some_rotations = euler2mat(0.1, 0.2, 0.3) -extra_affine = from_matvec(some_rotations, [3, 4, 5]) -moved_anat = nib.Nifti1Image(img.dataobj, - extra_affine.dot(img.affine), - img.header) -moved_anat.set_data_dtype(np.float32) -nib.save(moved_anat, 'anat_moved.nii') +if __name__ == '__main__': + img = nib.load('anatomical.nii') + some_rotations = euler2mat(0.1, 0.2, 0.3) + extra_affine = from_matvec(some_rotations, [3, 4, 5]) + moved_anat = nib.Nifti1Image(img.dataobj, + extra_affine.dot(img.affine), + img.header) + moved_anat.set_data_dtype(np.float32) + nib.save(moved_anat, 'anat_moved.nii') From 62132ad73b751c75274c8b2051e025175745bd8e Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Sat, 25 Jan 2020 15:00:18 -0500 Subject: [PATCH 021/223] TEST: Doctests not ready --- .azure-pipelines/windows.yml | 2 +- .travis.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index 363cd64eb4..bbb6f907ad 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -43,7 +43,7 @@ jobs: if %CHECK_TYPE%=="nosetests" ( nosetests --with-doctest --with-coverage --cover-package nibabel nibabel ) else ( - pytest --doctest-modules --cov nibabel -v --pyargs nibabel --deselect streamlines + pytest --cov nibabel -v --pyargs nibabel --deselect streamlines ) displayName: 'Nose tests' - script: | diff --git a/.travis.yml b/.travis.yml index aed8cf06a3..cdcb578406 100644 --- a/.travis.yml +++ b/.travis.yml @@ -139,7 +139,7 @@ script: mkdir for_testing cd for_testing cp ../.coveragerc . - pytest --doctest-modules --cov nibabel -v --pyargs nibabel --deselect streamlines + pytest --cov nibabel -v --pyargs nibabel --deselect streamlines else false fi From 765bec8af1ceeff7afa2c44b9357118fbc81fcdf Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Sat, 25 Jan 2020 15:36:15 -0500 Subject: [PATCH 022/223] CI: Try alternative CHECK_TYPE test --- .azure-pipelines/windows.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index bbb6f907ad..469fd27c96 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -40,7 +40,7 @@ jobs: mkdir for_testing cd for_testing cp ../.coveragerc . - if %CHECK_TYPE%=="nosetests" ( + if $(CHECK_TYPE)=="nosetests" ( nosetests --with-doctest --with-coverage --cover-package nibabel nibabel ) else ( pytest --cov nibabel -v --pyargs nibabel --deselect streamlines From f908ca4b5ed690a953c89af45656df558b733514 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Sat, 25 Jan 2020 15:37:04 -0500 Subject: [PATCH 023/223] PIN: Avoid pytest 5.3.4 (pytest-dev/pytest#6517) --- setup.cfg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.cfg b/setup.cfg index 5719650bf8..fe6d91bdd3 100644 --- a/setup.cfg +++ b/setup.cfg @@ -62,7 +62,7 @@ nosetests = test = coverage nose >=0.11 - pytest + pytest !=5.3.4 pytest-cov all = %(dicomfs)s From 60479c4879cd27095303ac320ad95c0f6b54b2af Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 4 Feb 2020 09:33:59 -0500 Subject: [PATCH 024/223] TEST: Add BaseTestCase class to skip TestCases starting with ``_`` --- nibabel/testing_pytest/__init__.py | 14 ++++++++++++++ nibabel/tests/test_wrapstruct.py | 30 ++---------------------------- 2 files changed, 16 insertions(+), 28 deletions(-) diff --git a/nibabel/testing_pytest/__init__.py b/nibabel/testing_pytest/__init__.py index 38143d9c38..71217612ed 100644 --- a/nibabel/testing_pytest/__init__.py +++ b/nibabel/testing_pytest/__init__.py @@ -15,6 +15,8 @@ from pkg_resources import resource_filename from os.path import dirname, abspath, join as pjoin +import unittest + import numpy as np from numpy.testing import assert_array_equal, assert_warns from numpy.testing import dec @@ -220,3 +222,15 @@ def assert_arr_dict_equal(dict1, dict2): for key, value1 in dict1.items(): value2 = dict2[key] assert_array_equal(value1, value2) + + +class BaseTestCase(unittest.TestCase): + """ TestCase that does not attempt to run if prefixed with a ``_`` + + This restores the nose-like behavior of skipping so-named test cases + in test runners like pytest. + """ + def setUp(self): + if self.__class__.__name__.startswith('_'): + raise unittest.SkipTest("Base test case - subclass to run") + super().setUp() diff --git a/nibabel/tests/test_wrapstruct.py b/nibabel/tests/test_wrapstruct.py index f627109fd0..f052098475 100644 --- a/nibabel/tests/test_wrapstruct.py +++ b/nibabel/tests/test_wrapstruct.py @@ -34,7 +34,7 @@ from ..spatialimages import HeaderDataError from .. import imageglobals -from unittest import TestCase, SkipTest +from ..testing_pytest import BaseTestCase from numpy.testing import assert_array_equal import pytest @@ -106,7 +106,7 @@ def log_chk(hdr, level): return hdrc, message, raiser -class _TestWrapStructBase(TestCase): +class _TestWrapStructBase(BaseTestCase): ''' Class implements base tests for binary headers It serves as a base class for other binary header tests @@ -119,8 +119,6 @@ def get_bad_bb(self): return None def test_general_init(self): - if not self.header_class: - pytest.skip() hdr = self.header_class() # binaryblock has length given by header data dtype binblock = hdr.binaryblock @@ -140,8 +138,6 @@ def _set_something_into_hdr(self, hdr): def test__eq__(self): # Test equal and not equal - if not self.header_class: - pytest.skip() hdr1 = self.header_class() hdr2 = self.header_class() assert hdr1 == hdr2 @@ -158,8 +154,6 @@ def test__eq__(self): def test_to_from_fileobj(self): # Successful write using write_to - if not self.header_class: - pytest.skip() hdr = self.header_class() str_io = BytesIO() hdr.write_to(str_io) @@ -169,8 +163,6 @@ def test_to_from_fileobj(self): assert hdr2.binaryblock == hdr.binaryblock def test_mappingness(self): - if not self.header_class: - pytest.skip() hdr = self.header_class() with pytest.raises(ValueError): hdr.__setitem__('nonexistent key', 0.1) @@ -207,16 +199,12 @@ def test_endianness_ro(self): endianness on initialization (or occasionally byteswapping the data) - but this is done via via the as_byteswapped method ''' - if not self.header_class: - pytest.skip() hdr = self.header_class() with pytest.raises(AttributeError): hdr.__setattr__('endianness', '<') def test_endian_guess(self): # Check guesses of endian - if not self.header_class: - pytest.skip() eh = self.header_class() assert eh.endianness == native_code hdr_data = eh.structarr.copy() @@ -231,8 +219,6 @@ def test_binblock_is_file(self): # strings following. More generally, there may be other perhaps # optional data after the binary block, in which case you will need to # override this test - if not self.header_class: - pytest.skip() hdr = self.header_class() str_io = BytesIO() hdr.write_to(str_io) @@ -240,8 +226,6 @@ def test_binblock_is_file(self): def test_structarr(self): # structarr attribute also read only - if not self.header_class: - pytest.skip() hdr = self.header_class() # Just check we can get structarr hdr.structarr @@ -260,8 +244,6 @@ def assert_no_log_err(self, hdr): def test_bytes(self): # Test get of bytes - if not self.header_class: - pytest.skip() hdr1 = self.header_class() bb = hdr1.binaryblock hdr2 = self.header_class(hdr1.binaryblock) @@ -292,8 +274,6 @@ def test_bytes(self): def test_as_byteswapped(self): # Check byte swapping - if not self.header_class: - pytest.skip() hdr = self.header_class() assert hdr.endianness == native_code # same code just returns a copy @@ -318,8 +298,6 @@ def check_fix(self, *args, **kwargs): def test_empty_check(self): # Empty header should be error free - if not self.header_class: - pytest.skip() hdr = self.header_class() hdr.check_fix(error_level=0) @@ -329,8 +307,6 @@ def _dxer(self, hdr): return self.header_class.diagnose_binaryblock(binblock) def test_str(self): - if not self.header_class: - pytest.skip() hdr = self.header_class() # Check something returns from str s1 = str(hdr) @@ -344,8 +320,6 @@ class _TestLabeledWrapStruct(_TestWrapStructBase): def test_get_value_label(self): # Test get value label method # Make a new class to avoid overwriting recoders of original - if not self.header_class: - pytest.skip() class MyHdr(self.header_class): _field_recoders = {} hdr = MyHdr() From 9d1795a861b5108974ab09bb4ee2eadb0c94cc17 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 4 Feb 2020 09:56:30 -0500 Subject: [PATCH 025/223] TMP: Skip failing streamlines modules --- nibabel/streamlines/tests/test_array_sequence.py | 2 ++ nibabel/streamlines/tests/test_tck.py | 2 ++ nibabel/streamlines/tests/test_tractogram.py | 1 + nibabel/streamlines/tests/test_trk.py | 1 + 4 files changed, 6 insertions(+) diff --git a/nibabel/streamlines/tests/test_array_sequence.py b/nibabel/streamlines/tests/test_array_sequence.py index c92580accb..26b824e596 100644 --- a/nibabel/streamlines/tests/test_array_sequence.py +++ b/nibabel/streamlines/tests/test_array_sequence.py @@ -9,6 +9,8 @@ from nibabel.testing import assert_arrays_equal from numpy.testing import assert_array_equal +import pytest; pytestmark = pytest.mark.skip() + from ..array_sequence import ArraySequence, is_array_sequence, concatenate diff --git a/nibabel/streamlines/tests/test_tck.py b/nibabel/streamlines/tests/test_tck.py index ad16b52754..573bed02d3 100644 --- a/nibabel/streamlines/tests/test_tck.py +++ b/nibabel/streamlines/tests/test_tck.py @@ -14,6 +14,8 @@ from .. import tck as tck_module from ..tck import TckFile +import pytest; pytestmark = pytest.mark.skip() + from nose.tools import assert_equal, assert_raises, assert_true from numpy.testing import assert_array_equal from nibabel.testing import data_path, clear_and_catch_warnings diff --git a/nibabel/streamlines/tests/test_tractogram.py b/nibabel/streamlines/tests/test_tractogram.py index 407f3ef413..ba84735450 100644 --- a/nibabel/streamlines/tests/test_tractogram.py +++ b/nibabel/streamlines/tests/test_tractogram.py @@ -10,6 +10,7 @@ from nibabel.testing import clear_and_catch_warnings from nose.tools import assert_equal, assert_raises, assert_true from numpy.testing import assert_array_equal, assert_array_almost_equal +import pytest; pytestmark = pytest.mark.skip() from .. import tractogram as module_tractogram from ..tractogram import is_data_dict, is_lazy_dict diff --git a/nibabel/streamlines/tests/test_trk.py b/nibabel/streamlines/tests/test_trk.py index a0a3d8a1f3..8d4f01d766 100644 --- a/nibabel/streamlines/tests/test_trk.py +++ b/nibabel/streamlines/tests/test_trk.py @@ -11,6 +11,7 @@ from nibabel.testing import clear_and_catch_warnings, assert_arr_dict_equal from nose.tools import assert_equal, assert_raises, assert_true from numpy.testing import assert_array_equal +import pytest; pytestmark = pytest.mark.skip() from .test_tractogram import assert_tractogram_equal from ..tractogram import Tractogram From f2ff7feea8f810ce76b42aef87c268a52721316f Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 4 Feb 2020 11:00:44 -0500 Subject: [PATCH 026/223] CI: Skip converted tests in nose --- .travis.yml | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index cdcb578406..a0c19ff1f3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -133,7 +133,61 @@ script: mkdir for_testing cd for_testing cp ../.coveragerc . - nosetests --with-doctest --with-coverage --cover-package nibabel nibabel + nosetests --with-doctest --with-coverage --cover-package nibabel nibabel \ + -I test_api_validators \ + -I test_arrayproxy \ + -I test_arrayriters \ + -I test_batteryrunners \ + -I test_brikhead \ + -I test_casting \ + -I test_data \ + -I test_deprecated \ + -I test_deprecator \ + -I test_dft \ + -I test_ecat \ + -I test_ecat_data \ + -I test_endiancodes \ + -I test_environment \ + -I test_euler \ + -I test_filebasedimages \ + -I test_filehandles \ + -I test_fileholders \ + -I test_filename_parser \ + -I test_files_interface \ + -I test_fileslice \ + -I test_fileutils \ + -I test_floating \ + -I test_funcs \ + -I test_h5py_compat \ + -I test_image_api \ + -I test_image_load_save \ + -I test_image_types \ + -I test_imageclasses \ + -I test_imageglobals \ + -I test_keywordonly \ + -I test_loadsave \ + -I test_minc1 \ + -I test_minc2 \ + -I test_minc2_data \ + -I test_mriutils \ + -I test_nibabel_data \ + -I test_nifti1 \ + -I test_nifti2 \ + -I test_openers \ + -I test_optpkg \ + -I test_orientations \ + -I test_parrec \ + -I test_parrec_data \ + -I test_pkg_info \ + -I test_processing \ + -I test_proxy_api \ + -I test_quaternions \ + -I test_recoder \ + -I test_remmovalschedule \ + -I test_round_trip \ + -I test_rstutils \ + -I test_scaling \ + -I test_wrapstruct elif [ "${CHECK_TYPE}" == "test" ]; then # Change into an innocuous directory and find tests from installation mkdir for_testing From 01b1b7e0348711f01b4c43e539d94d80f71f71a0 Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 13:06:54 +0200 Subject: [PATCH 027/223] TEST: pytest conversion #864 #865 --- .../streamlines/tests/test_array_sequence.py | 150 +++++++++++------- 1 file changed, 93 insertions(+), 57 deletions(-) diff --git a/nibabel/streamlines/tests/test_array_sequence.py b/nibabel/streamlines/tests/test_array_sequence.py index 26b824e596..4fdab33d86 100644 --- a/nibabel/streamlines/tests/test_array_sequence.py +++ b/nibabel/streamlines/tests/test_array_sequence.py @@ -5,8 +5,8 @@ import itertools import numpy as np -from nose.tools import assert_equal, assert_raises, assert_true -from nibabel.testing import assert_arrays_equal +import pytest +from nibabel.testing_pytest import assert_arrays_equal from numpy.testing import assert_array_equal import pytest; pytestmark = pytest.mark.skip() @@ -17,7 +17,7 @@ SEQ_DATA = {} -def setup(): +def setup_module(): global SEQ_DATA rng = np.random.RandomState(42) SEQ_DATA['rng'] = rng @@ -32,22 +32,25 @@ def generate_data(nb_arrays, common_shape, rng): def check_empty_arr_seq(seq): - assert_equal(len(seq), 0) - assert_equal(len(seq._offsets), 0) - assert_equal(len(seq._lengths), 0) + assert len(seq) == 0 + assert len(seq._offsets) == 0 + assert len(seq._lengths) == 0 # assert_equal(seq._data.ndim, 0) - assert_equal(seq._data.ndim, 1) - assert_true(seq.common_shape == ()) + assert seq._data.ndim == 1 + + # TODO: Check assert_true + # assert_true(seq.common_shape == ()) def check_arr_seq(seq, arrays): lengths = list(map(len, arrays)) - assert_true(is_array_sequence(seq)) - assert_equal(len(seq), len(arrays)) - assert_equal(len(seq._offsets), len(arrays)) - assert_equal(len(seq._lengths), len(arrays)) - assert_equal(seq._data.shape[1:], arrays[0].shape[1:]) - assert_equal(seq.common_shape, arrays[0].shape[1:]) + assert is_array_sequence(seq) == True + assert len(seq) == len(arrays) + assert len(seq._offsets) == len(arrays) + assert len(seq._lengths) == len(arrays) + assert seq._data.shape[1:] == arrays[0].shape[1:] + assert seq.common_shape == arrays[0].shape[1:] + assert_arrays_equal(seq, arrays) # If seq is a view, then order of internal data is not guaranteed. @@ -56,18 +59,20 @@ def check_arr_seq(seq, arrays): assert_array_equal(sorted(seq._lengths), sorted(lengths)) else: seq.shrink_data() - assert_equal(seq._data.shape[0], sum(lengths)) + + assert seq._data.shape[0] == sum(lengths) + assert_array_equal(seq._data, np.concatenate(arrays, axis=0)) assert_array_equal(seq._offsets, np.r_[0, np.cumsum(lengths)[:-1]]) assert_array_equal(seq._lengths, lengths) def check_arr_seq_view(seq_view, seq): - assert_true(seq_view._is_view) - assert_true(seq_view is not seq) - assert_true(np.may_share_memory(seq_view._data, seq._data)) - assert_true(seq_view._offsets is not seq._offsets) - assert_true(seq_view._lengths is not seq._lengths) + assert seq_view._is_view is True + assert (seq_view is not seq) is True + assert (np.may_share_memory(seq_view._data, seq._data)) is True + assert seq_view._offsets is not seq._offsets + assert seq_view._lengths is not seq._lengths class TestArraySequence(unittest.TestCase): @@ -99,8 +104,8 @@ def test_creating_arraysequence_from_generator(self): seq_with_buffer = ArraySequence(gen_2, buffer_size=256) # Check buffer size effect - assert_equal(seq_with_buffer.data.shape, seq.data.shape) - assert_true(seq_with_buffer._buffer_size > seq._buffer_size) + assert seq_with_buffer.data.shape == seq.data.shape + assert seq_with_buffer._buffer_size > seq._buffer_size # Check generator result check_arr_seq(seq, SEQ_DATA['data']) @@ -123,26 +128,27 @@ def test_arraysequence_iter(self): # Try iterating through a corrupted ArraySequence object. seq = SEQ_DATA['seq'].copy() seq._lengths = seq._lengths[::2] - assert_raises(ValueError, list, seq) + with pytest.raises(ValueError): + list(seq) def test_arraysequence_copy(self): orig = SEQ_DATA['seq'] seq = orig.copy() n_rows = seq.total_nb_rows - assert_equal(n_rows, orig.total_nb_rows) + assert n_rows == orig.total_nb_rows assert_array_equal(seq._data, orig._data[:n_rows]) - assert_true(seq._data is not orig._data) + assert seq._data is not orig._data assert_array_equal(seq._offsets, orig._offsets) - assert_true(seq._offsets is not orig._offsets) + assert seq._offsets is not orig._offsets assert_array_equal(seq._lengths, orig._lengths) - assert_true(seq._lengths is not orig._lengths) - assert_equal(seq.common_shape, orig.common_shape) + assert seq._lengths is not orig._lengths + assert seq.common_shape == orig.common_shape # Taking a copy of an `ArraySequence` generated by slicing. # Only keep needed data. seq = orig[::2].copy() check_arr_seq(seq, SEQ_DATA['data'][::2]) - assert_true(seq._data is not orig._data) + assert seq._data is not orig._data def test_arraysequence_append(self): element = generate_data(nb_arrays=1, @@ -173,7 +179,9 @@ def test_arraysequence_append(self): element = generate_data(nb_arrays=1, common_shape=SEQ_DATA['seq'].common_shape*2, rng=SEQ_DATA['rng'])[0] - assert_raises(ValueError, seq.append, element) + + with pytest.raises(ValueError): + seq.append(element) def test_arraysequence_extend(self): new_data = generate_data(nb_arrays=10, @@ -219,7 +227,8 @@ def test_arraysequence_extend(self): common_shape=SEQ_DATA['seq'].common_shape*2, rng=SEQ_DATA['rng']) seq = SEQ_DATA['seq'].copy() # Copy because of in-place modification. - assert_raises(ValueError, seq.extend, data) + with pytest.raises(ValueError): + seq.extend(data) # Extend after extracting some slice working_slice = seq[:2] @@ -264,7 +273,9 @@ def test_arraysequence_getitem(self): for i, keep in enumerate(selection) if keep]) # Test invalid indexing - assert_raises(TypeError, SEQ_DATA['seq'].__getitem__, 'abc') + with pytest.raises(TypeError): + SEQ_DATA['seq'].__getitem__('abc') + #SEQ_DATA['seq'].abc # Get specific columns. seq_view = SEQ_DATA['seq'][:, 2] @@ -287,7 +298,7 @@ def test_arraysequence_setitem(self): # Setitem with a scalar. seq = SEQ_DATA['seq'].copy() seq[:] = 0 - assert_true(seq._data.sum() == 0) + assert seq._data.sum() == 0 # Setitem with a list of ndarray. seq = SEQ_DATA['seq'] * 0 @@ -297,12 +308,12 @@ def test_arraysequence_setitem(self): # Setitem using tuple indexing. seq = ArraySequence(np.arange(900).reshape((50,6,3))) seq[:, 0] = 0 - assert_true(seq._data[:, 0].sum() == 0) + assert seq._data[:, 0].sum() == 0 # Setitem using tuple indexing. seq = ArraySequence(np.arange(900).reshape((50,6,3))) seq[range(len(seq))] = 0 - assert_true(seq._data.sum() == 0) + assert seq._data.sum() == 0 # Setitem of a slice using another slice. seq = ArraySequence(np.arange(900).reshape((50,6,3))) @@ -311,20 +322,26 @@ def test_arraysequence_setitem(self): # Setitem between array sequences with different number of sequences. seq = ArraySequence(np.arange(900).reshape((50,6,3))) - assert_raises(ValueError, seq.__setitem__, slice(0, 4), seq[5:10]) + with pytest.raises(ValueError): + seq.__setitem__(slice(0, 4), seq[5:10]) + # Setitem between array sequences with different amount of points. seq1 = ArraySequence(np.arange(10).reshape(5, 2)) seq2 = ArraySequence(np.arange(15).reshape(5, 3)) - assert_raises(ValueError, seq1.__setitem__, slice(0, 5), seq2) + with pytest.raises(ValueError): + seq1.__setitem__(slice(0, 5), seq2) # Setitem between array sequences with different common shape. seq1 = ArraySequence(np.arange(12).reshape(2, 2, 3)) seq2 = ArraySequence(np.arange(8).reshape(2, 2, 2)) - assert_raises(ValueError, seq1.__setitem__, slice(0, 2), seq2) + + with pytest.raises(ValueError): + seq1.__setitem__(slice(0, 2), seq2) # Invalid index. - assert_raises(TypeError, seq.__setitem__, object(), None) + with pytest.raises(TypeError): + seq.__setitem__(object(), None) def test_arraysequence_operators(self): # Disable division per zero warnings. @@ -343,36 +360,45 @@ def test_arraysequence_operators(self): def _test_unary(op, arrseq): orig = arrseq.copy() seq = getattr(orig, op)() - assert_true(seq is not orig) + assert seq is not orig check_arr_seq(seq, [getattr(d, op)() for d in orig]) def _test_binary(op, arrseq, scalars, seqs, inplace=False): for scalar in scalars: orig = arrseq.copy() seq = getattr(orig, op)(scalar) - assert_true((seq is orig) if inplace else (seq is not orig)) + + if inplace: + assert seq is orig + else: + assert seq is not orig + check_arr_seq(seq, [getattr(e, op)(scalar) for e in arrseq]) # Test math operators with another ArraySequence. for other in seqs: orig = arrseq.copy() seq = getattr(orig, op)(other) - assert_true(seq is not SEQ_DATA['seq']) + assert seq is not SEQ_DATA['seq'] check_arr_seq(seq, [getattr(e1, op)(e2) for e1, e2 in zip(arrseq, other)]) # Operations between array sequences of different lengths. orig = arrseq.copy() - assert_raises(ValueError, getattr(orig, op), orig[::2]) + with pytest.raises(ValueError): + getattr(orig, op)(orig[::2]) # Operations between array sequences with different amount of data. seq1 = ArraySequence(np.arange(10).reshape(5, 2)) seq2 = ArraySequence(np.arange(15).reshape(5, 3)) - assert_raises(ValueError, getattr(seq1, op), seq2) + with pytest.raises(ValueError): + getattr(seq1, op)(seq2) # Operations between array sequences with different common shape. seq1 = ArraySequence(np.arange(12).reshape(2, 2, 3)) seq2 = ArraySequence(np.arange(8).reshape(2, 2, 2)) - assert_raises(ValueError, getattr(seq1, op), seq2) + with pytest.raises(ValueError): + getattr(seq1, op)(seq2) + for op in ["__add__", "__sub__", "__mul__", "__mod__", @@ -394,24 +420,33 @@ def _test_binary(op, arrseq, scalars, seqs, inplace=False): continue # Going to deal with it separately. _test_binary(op, seq_int, [42, -3, True, 0], [seq_int, seq_bool, -seq_int], inplace=True) # int <-- int - assert_raises(TypeError, _test_binary, op, seq_int, [0.5], [], inplace=True) # int <-- float - assert_raises(TypeError, _test_binary, op, seq_int, [], [seq], inplace=True) # int <-- float + + with pytest.raises(TypeError): + _test_binary(op, seq_int, [0.5], [], inplace=True) # int <-- float + _test_binary(op, seq_int, [], [seq], inplace=True) # int <-- float + # __pow__ : Integers to negative integer powers are not allowed. _test_binary("__pow__", seq, [42, -3, True, 0], [seq_int, seq_bool, -seq_int]) _test_binary("__ipow__", seq, [42, -3, True, 0], [seq_int, seq_bool, -seq_int], inplace=True) - assert_raises(ValueError, _test_binary, "__pow__", seq_int, [-3], []) - assert_raises(ValueError, _test_binary, "__ipow__", seq_int, [-3], [], inplace=True) - + + with pytest.raises(ValueError): + _test_binary("__pow__", seq_int, [-3], []) + _test_binary("__ipow__", seq_int, [-3], [], inplace=True) + # __itruediv__ is only valid with float arrseq. for scalar in SCALARS + ARRSEQS: - assert_raises(TypeError, getattr(seq_int.copy(), "__itruediv__"), scalar) + with pytest.raises(TypeError): + seq_int_cp = seq_int.copy() + seq_int_cp.__itruediv__(scalar) # Bitwise operators for op in ("__lshift__", "__rshift__", "__or__", "__and__", "__xor__"): _test_binary(op, seq_bool, [42, -3, True, 0], [seq_int, seq_bool, -seq_int]) - assert_raises(TypeError, _test_binary, op, seq_bool, [0.5], []) - assert_raises(TypeError, _test_binary, op, seq, [], [seq]) + + with pytest.raises(TypeError): + _test_binary(op, seq_bool, [0.5], []) + _test_binary(op, seq, [], [seq]) # Unary operators for op in ["__neg__", "__abs__"]: @@ -422,7 +457,8 @@ def _test_binary(op, arrseq, scalars, seqs, inplace=False): _test_unary("__abs__", seq_bool) _test_unary("__invert__", seq_bool) - assert_raises(TypeError, _test_unary, "__invert__", seq) + with pytest.raises(TypeError): + _test_unary("__invert__", seq) # Restore flags. np.seterr(**flags) @@ -442,7 +478,7 @@ def test_arraysequence_repr(self): txt1 = repr(seq) np.set_printoptions(threshold=nb_arrays//2) txt2 = repr(seq) - assert_true(len(txt2) < len(txt1)) + assert len(txt2) < len(txt1) np.set_printoptions(threshold=bkp_threshold) def test_save_and_load_arraysequence(self): @@ -485,10 +521,10 @@ def test_concatenate(): new_seq = concatenate(seqs, axis=1) seq._data += 100 # Modifying the 'seq' shouldn't change 'new_seq'. check_arr_seq(new_seq, SEQ_DATA['data']) - assert_true(not new_seq._is_view) + assert new_seq._is_view is not True seq = SEQ_DATA['seq'] seqs = [seq[:, [i]] for i in range(seq.common_shape[0])] new_seq = concatenate(seqs, axis=0) - assert_true(len(new_seq), seq.common_shape[0] * len(seq)) + assert len(new_seq) == seq.common_shape[0] * len(seq) assert_array_equal(new_seq._data, seq._data.T.reshape((-1, 1))) From ade7bdee208308bc8202ecffda0c9876b619af18 Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 14:02:06 +0200 Subject: [PATCH 028/223] TEST: test_tractogram to pytest #865 #864 --- nibabel/streamlines/tests/test_tractogram.py | 278 ++++++++++--------- 1 file changed, 149 insertions(+), 129 deletions(-) diff --git a/nibabel/streamlines/tests/test_tractogram.py b/nibabel/streamlines/tests/test_tractogram.py index ba84735450..bea0650db0 100644 --- a/nibabel/streamlines/tests/test_tractogram.py +++ b/nibabel/streamlines/tests/test_tractogram.py @@ -6,9 +6,9 @@ import operator from collections import defaultdict -from nibabel.testing import assert_arrays_equal -from nibabel.testing import clear_and_catch_warnings -from nose.tools import assert_equal, assert_raises, assert_true +import pytest +from nibabel.testing_pytest import assert_arrays_equal +from nibabel.testing_pytest import clear_and_catch_warnings from numpy.testing import assert_array_equal, assert_array_almost_equal import pytest; pytestmark = pytest.mark.skip() @@ -94,7 +94,7 @@ def make_dummy_streamline(nb_points): return streamline, data_per_point, data_for_streamline -def setup(): +def setup_module(): global DATA DATA['rng'] = np.random.RandomState(1234) @@ -150,13 +150,12 @@ def check_tractogram_item(tractogram_item, assert_array_equal(tractogram_item.streamline, streamline) - assert_equal(len(tractogram_item.data_for_streamline), - len(data_for_streamline)) + assert len(tractogram_item.data_for_streamline) == len(data_for_streamline) for key in data_for_streamline.keys(): assert_array_equal(tractogram_item.data_for_streamline[key], data_for_streamline[key]) - assert_equal(len(tractogram_item.data_for_points), len(data_for_points)) + assert len(tractogram_item.data_for_points) == len(data_for_points) for key in data_for_points.keys(): assert_arrays_equal(tractogram_item.data_for_points[key], data_for_points[key]) @@ -172,16 +171,16 @@ def check_tractogram(tractogram, data_per_streamline={}, data_per_point={}): streamlines = list(streamlines) - assert_equal(len(tractogram), len(streamlines)) + assert len(tractogram) == len(streamlines) assert_arrays_equal(tractogram.streamlines, streamlines) [t for t in tractogram] # Force iteration through tractogram. - assert_equal(len(tractogram.data_per_streamline), len(data_per_streamline)) + assert len(tractogram.data_per_streamline) == len(data_per_streamline) for key in data_per_streamline.keys(): assert_arrays_equal(tractogram.data_per_streamline[key], data_per_streamline[key]) - assert_equal(len(tractogram.data_per_point), len(data_per_point)) + assert len(tractogram.data_per_point) == len(data_per_point) for key in data_per_point.keys(): assert_arrays_equal(tractogram.data_per_point[key], data_per_point[key]) @@ -205,43 +204,44 @@ def test_per_array_dict_creation(self): nb_streamlines = len(DATA['tractogram']) data_per_streamline = DATA['tractogram'].data_per_streamline data_dict = PerArrayDict(nb_streamlines, data_per_streamline) - assert_equal(data_dict.keys(), data_per_streamline.keys()) + assert data_dict.keys() == data_per_streamline.keys() for k in data_dict.keys(): assert_array_equal(data_dict[k], data_per_streamline[k]) del data_dict['mean_curvature'] - assert_equal(len(data_dict), - len(data_per_streamline)-1) + assert len(data_dict) == len(data_per_streamline)-1 # Create a PerArrayDict object using an existing dict object. data_per_streamline = DATA['data_per_streamline'] data_dict = PerArrayDict(nb_streamlines, data_per_streamline) - assert_equal(data_dict.keys(), data_per_streamline.keys()) + assert data_dict.keys() == data_per_streamline.keys() for k in data_dict.keys(): assert_array_equal(data_dict[k], data_per_streamline[k]) del data_dict['mean_curvature'] - assert_equal(len(data_dict), len(data_per_streamline)-1) + assert len(data_dict) == len(data_per_streamline)-1 # Create a PerArrayDict object using keyword arguments. data_per_streamline = DATA['data_per_streamline'] data_dict = PerArrayDict(nb_streamlines, **data_per_streamline) - assert_equal(data_dict.keys(), data_per_streamline.keys()) + assert data_dict.keys() == data_per_streamline.keys() for k in data_dict.keys(): assert_array_equal(data_dict[k], data_per_streamline[k]) del data_dict['mean_curvature'] - assert_equal(len(data_dict), len(data_per_streamline)-1) + assert len(data_dict) == len(data_per_streamline)-1 def test_getitem(self): sdict = PerArrayDict(len(DATA['tractogram']), DATA['data_per_streamline']) - assert_raises(KeyError, sdict.__getitem__, 'invalid') + with pytest.raises(KeyError): + sdict['invalid'] + #assert_raises(KeyError, sdict.__getitem__, 'invalid') # Test slicing and advanced indexing. for k, v in DATA['tractogram'].data_per_streamline.items(): - assert_true(k in sdict) + assert k in sdict assert_arrays_equal(sdict[k], v) assert_arrays_equal(sdict[::2][k], v[::2]) assert_arrays_equal(sdict[::-1][k], v[::-1]) @@ -259,7 +259,7 @@ def test_extend(self): new_data) sdict.extend(sdict2) - assert_equal(len(sdict), len(sdict2)) + assert len(sdict) == len(sdict2) for k in DATA['tractogram'].data_per_streamline: assert_arrays_equal(sdict[k][:len(DATA['tractogram'])], DATA['tractogram'].data_per_streamline[k]) @@ -279,21 +279,24 @@ def test_extend(self): 'mean_colors': 4 * np.array(DATA['mean_colors']), 'other': 5 * np.array(DATA['mean_colors'])} sdict2 = PerArrayDict(len(DATA['tractogram']), new_data) - assert_raises(ValueError, sdict.extend, sdict2) + with pytest.raises(ValueError): + sdict.extend(sdict2) # Other dict has not the same entries (key mistmached). new_data = {'mean_curvature': 2 * np.array(DATA['mean_curvature']), 'mean_torsion': 3 * np.array(DATA['mean_torsion']), 'other': 4 * np.array(DATA['mean_colors'])} sdict2 = PerArrayDict(len(DATA['tractogram']), new_data) - assert_raises(ValueError, sdict.extend, sdict2) + with pytest.raises(ValueError): + sdict.extend(sdict2) # Other dict has the right number of entries but wrong shape. new_data = {'mean_curvature': 2 * np.array(DATA['mean_curvature']), 'mean_torsion': 3 * np.array(DATA['mean_torsion']), 'mean_colors': 4 * np.array(DATA['mean_torsion'])} sdict2 = PerArrayDict(len(DATA['tractogram']), new_data) - assert_raises(ValueError, sdict.extend, sdict2) + with pytest.raises(ValueError): + sdict.extend(sdict2) class TestPerArraySequenceDict(unittest.TestCase): @@ -304,43 +307,44 @@ def test_per_array_sequence_dict_creation(self): total_nb_rows = DATA['tractogram'].streamlines.total_nb_rows data_per_point = DATA['tractogram'].data_per_point data_dict = PerArraySequenceDict(total_nb_rows, data_per_point) - assert_equal(data_dict.keys(), data_per_point.keys()) + assert data_dict.keys() == data_per_point.keys() for k in data_dict.keys(): assert_arrays_equal(data_dict[k], data_per_point[k]) del data_dict['fa'] - assert_equal(len(data_dict), - len(data_per_point)-1) + assert len(data_dict) == len(data_per_point)-1 # Create a PerArraySequenceDict object using an existing dict object. data_per_point = DATA['data_per_point'] data_dict = PerArraySequenceDict(total_nb_rows, data_per_point) - assert_equal(data_dict.keys(), data_per_point.keys()) + assert data_dict.keys() == data_per_point.keys() for k in data_dict.keys(): assert_arrays_equal(data_dict[k], data_per_point[k]) del data_dict['fa'] - assert_equal(len(data_dict), len(data_per_point)-1) + assert len(data_dict) == len(data_per_point)-1 # Create a PerArraySequenceDict object using keyword arguments. data_per_point = DATA['data_per_point'] data_dict = PerArraySequenceDict(total_nb_rows, **data_per_point) - assert_equal(data_dict.keys(), data_per_point.keys()) + assert data_dict.keys() == data_per_point.keys() for k in data_dict.keys(): assert_arrays_equal(data_dict[k], data_per_point[k]) del data_dict['fa'] - assert_equal(len(data_dict), len(data_per_point)-1) + assert len(data_dict) == len(data_per_point)-1 def test_getitem(self): total_nb_rows = DATA['tractogram'].streamlines.total_nb_rows sdict = PerArraySequenceDict(total_nb_rows, DATA['data_per_point']) - assert_raises(KeyError, sdict.__getitem__, 'invalid') + with pytest.raises(KeyError): + sdict['invalid'] + #assert_raises(KeyError, sdict.__getitem__, 'invalid') # Test slicing and advanced indexing. for k, v in DATA['tractogram'].data_per_point.items(): - assert_true(k in sdict) + assert k in sdict assert_arrays_equal(sdict[k], v) assert_arrays_equal(sdict[::2][k], v[::2]) assert_arrays_equal(sdict[::-1][k], v[::-1]) @@ -361,7 +365,7 @@ def test_extend(self): sdict2 = PerArraySequenceDict(np.sum(list_nb_points), new_data) sdict.extend(sdict2) - assert_equal(len(sdict), len(sdict2)) + assert len(sdict) == len(sdict2) for k in DATA['tractogram'].data_per_point: assert_arrays_equal(sdict[k][:len(DATA['tractogram'])], DATA['tractogram'].data_per_point[k]) @@ -383,7 +387,8 @@ def test_extend(self): data_per_point_shapes, rng=DATA['rng']) sdict2 = PerArraySequenceDict(np.sum(list_nb_points), new_data) - assert_raises(ValueError, sdict.extend, sdict2) + with pytest.raises(ValueError): + sdict.extend(sdict2) # Other dict has not the same entries (key mistmached). data_per_point_shapes = {"colors": DATA['colors'][0].shape[1:], @@ -392,7 +397,8 @@ def test_extend(self): data_per_point_shapes, rng=DATA['rng']) sdict2 = PerArraySequenceDict(np.sum(list_nb_points), new_data) - assert_raises(ValueError, sdict.extend, sdict2) + with pytest.raises(ValueError): + sdict.extend(sdict2) # Other dict has the right number of entries but wrong shape. data_per_point_shapes = {"colors": DATA['colors'][0].shape[1:], @@ -401,7 +407,8 @@ def test_extend(self): data_per_point_shapes, rng=DATA['rng']) sdict2 = PerArraySequenceDict(np.sum(list_nb_points), new_data) - assert_raises(ValueError, sdict.extend, sdict2) + with pytest.raises(ValueError): + sdict.extend(sdict2) class TestLazyDict(unittest.TestCase): @@ -414,14 +421,13 @@ def test_lazydict_creation(self): expected_keys = DATA['data_per_streamline_func'].keys() for data_dict in lazy_dicts: - assert_true(is_lazy_dict(data_dict)) - assert_equal(data_dict.keys(), expected_keys) + assert is_lazy_dict(data_dict) is True + assert data_dict.keys() == expected_keys for k in data_dict.keys(): assert_array_equal(list(data_dict[k]), list(DATA['data_per_streamline'][k])) - assert_equal(len(data_dict), - len(DATA['data_per_streamline_func'])) + assert len(data_dict) == len(DATA['data_per_streamline_func']) class TestTractogramItem(unittest.TestCase): @@ -440,7 +446,7 @@ def test_creating_tractogram_item(self): # Create a tractogram item with a streamline, data. t = TractogramItem(streamline, data_for_streamline, data_for_points) - assert_equal(len(t), len(streamline)) + assert len(t) == len(streamline) assert_array_equal(t.streamline, streamline) assert_array_equal(list(t), streamline) assert_array_equal(t.data_for_streamline['mean_curvature'], @@ -457,7 +463,7 @@ def test_tractogram_creation(self): # Create an empty tractogram. tractogram = Tractogram() check_tractogram(tractogram) - assert_true(tractogram.affine_to_rasmm is None) + assert tractogram.affine_to_rasmm is None # Create a tractogram with only streamlines tractogram = Tractogram(streamlines=DATA['streamlines']) @@ -478,8 +484,8 @@ def test_tractogram_creation(self): DATA['data_per_streamline'], DATA['data_per_point']) - assert_true(is_data_dict(tractogram.data_per_streamline)) - assert_true(is_data_dict(tractogram.data_per_point)) + assert is_data_dict(tractogram.data_per_streamline) is True + assert is_data_dict(tractogram.data_per_point) is True # Create a tractogram from another tractogram attributes. tractogram2 = Tractogram(tractogram.streamlines, @@ -503,8 +509,9 @@ def test_tractogram_creation(self): [(0, 0, 1)]*5] data_per_point = {'wrong_data': wrong_data} - assert_raises(ValueError, Tractogram, DATA['streamlines'], - data_per_point=data_per_point) + with pytest.raises(ValueError): + Tractogram(streamlines=DATA['streamlines'], + data_per_point=data_per_point) # Inconsistent number of scalars between streamlines wrong_data = [[(1, 0, 0)]*1, @@ -512,8 +519,9 @@ def test_tractogram_creation(self): [(0, 0, 1)]*5] data_per_point = {'wrong_data': wrong_data} - assert_raises(ValueError, Tractogram, DATA['streamlines'], - data_per_point=data_per_point) + with pytest.raises(ValueError): + Tractogram(streamlines=DATA['streamlines'], + data_per_point=data_per_point) def test_setting_affine_to_rasmm(self): tractogram = DATA['tractogram'].copy() @@ -521,19 +529,20 @@ def test_setting_affine_to_rasmm(self): # Test assigning None. tractogram.affine_to_rasmm = None - assert_true(tractogram.affine_to_rasmm is None) + assert tractogram.affine_to_rasmm is None # Test assigning a valid ndarray (should make a copy). tractogram.affine_to_rasmm = affine - assert_true(tractogram.affine_to_rasmm is not affine) + assert tractogram.affine_to_rasmm is not affine # Test assigning a list of lists. tractogram.affine_to_rasmm = affine.tolist() assert_array_equal(tractogram.affine_to_rasmm, affine) # Test assigning a ndarray with wrong shape. - assert_raises(ValueError, setattr, tractogram, - "affine_to_rasmm", affine[::2]) + with pytest.raises(ValueError): + tractogram.affine_to_rasmm = affine[::2] + def test_tractogram_getitem(self): # Retrieve TractogramItem by their index. @@ -594,21 +603,21 @@ def test_tractogram_copy(self): tractogram = DATA['tractogram'].copy() # Check we copied the data and not simply created new references. - assert_true(tractogram is not DATA['tractogram']) - assert_true(tractogram.streamlines - is not DATA['tractogram'].streamlines) - assert_true(tractogram.data_per_streamline - is not DATA['tractogram'].data_per_streamline) - assert_true(tractogram.data_per_point - is not DATA['tractogram'].data_per_point) + assert tractogram is not DATA['tractogram'] + assert tractogram.streamlines is \ + not DATA['tractogram'].streamlines + assert tractogram.data_per_streamline is \ + not DATA['tractogram'].data_per_streamline + assert tractogram.data_per_point is \ + not DATA['tractogram'].data_per_point for key in tractogram.data_per_streamline: - assert_true(tractogram.data_per_streamline[key] - is not DATA['tractogram'].data_per_streamline[key]) + assert tractogram.data_per_streamline[key] is \ + not DATA['tractogram'].data_per_streamline[key] for key in tractogram.data_per_point: - assert_true(tractogram.data_per_point[key] - is not DATA['tractogram'].data_per_point[key]) + assert tractogram.data_per_point[key] is \ + not DATA['tractogram'].data_per_point[key] # Check the values of the data are the same. assert_tractogram_equal(tractogram, DATA['tractogram']) @@ -619,39 +628,44 @@ def test_creating_invalid_tractogram(self): [(0, 1, 0)]*2, [(0, 0, 1)]*3] # Last streamlines has 5 points. - assert_raises(ValueError, Tractogram, DATA['streamlines'], - data_per_point={'scalars': scalars}) + with pytest.raises(ValueError): + Tractogram(streamlines=DATA['streamlines'], + data_per_point={'scalars':scalars}) # Not enough data_per_streamline for all streamlines. properties = [np.array([1.11, 1.22], dtype="f4"), np.array([3.11, 3.22], dtype="f4")] - assert_raises(ValueError, Tractogram, DATA['streamlines'], - data_per_streamline={'properties': properties}) + with pytest.raises(ValueError): + Tractogram(streamlines=DATA['streamlines'], + data_per_streamline={'properties': properties}) # Inconsistent dimension for a data_per_point. scalars = [[(1, 0, 0)]*1, [(0, 1)]*2, [(0, 0, 1)]*5] - assert_raises(ValueError, Tractogram, DATA['streamlines'], - data_per_point={'scalars': scalars}) + with pytest.raises(ValueError): + Tractogram(streamlines=DATA['streamlines'], + data_per_point={'scalars':scalars}) # Inconsistent dimension for a data_per_streamline. properties = [[1.11, 1.22], [2.11], [3.11, 3.22]] - assert_raises(ValueError, Tractogram, DATA['streamlines'], - data_per_streamline={'properties': properties}) + with pytest.raises(ValueError): + Tractogram(streamlines=DATA['streamlines'], + data_per_streamline={'properties': properties}) # Too many dimension for a data_per_streamline. properties = [np.array([[1.11], [1.22]], dtype="f4"), np.array([[2.11], [2.22]], dtype="f4"), np.array([[3.11], [3.22]], dtype="f4")] - assert_raises(ValueError, Tractogram, DATA['streamlines'], - data_per_streamline={'properties': properties}) + with pytest.raises(ValueError): + Tractogram(streamlines=DATA['streamlines'], + data_per_streamline={'properties': properties}) def test_tractogram_apply_affine(self): tractogram = DATA['tractogram'].copy() @@ -661,7 +675,7 @@ def test_tractogram_apply_affine(self): # Apply the affine to the streamline in a lazy manner. transformed_tractogram = tractogram.apply_affine(affine, lazy=True) - assert_true(type(transformed_tractogram) is LazyTractogram) + assert type(transformed_tractogram) is LazyTractogram check_tractogram(transformed_tractogram, streamlines=[s*scaling for s in DATA['streamlines']], data_per_streamline=DATA['data_per_streamline'], @@ -674,7 +688,7 @@ def test_tractogram_apply_affine(self): # Apply the affine to the streamlines in-place. transformed_tractogram = tractogram.apply_affine(affine) - assert_true(transformed_tractogram is tractogram) + assert transformed_tractogram is tractogram check_tractogram(tractogram, streamlines=[s*scaling for s in DATA['streamlines']], data_per_streamline=DATA['data_per_streamline'], @@ -690,7 +704,7 @@ def test_tractogram_apply_affine(self): # shouldn't affect the remaining streamlines. tractogram = DATA['tractogram'].copy() transformed_tractogram = tractogram[::2].apply_affine(affine) - assert_true(transformed_tractogram is not tractogram) + assert transformed_tractogram is not tractogram check_tractogram(tractogram[::2], streamlines=[s*scaling for s in DATA['streamlines'][::2]], data_per_streamline=DATA['tractogram'].data_per_streamline[::2], @@ -724,7 +738,7 @@ def test_tractogram_apply_affine(self): tractogram = DATA['tractogram'].copy() tractogram.affine_to_rasmm = None tractogram.apply_affine(affine) - assert_true(tractogram.affine_to_rasmm is None) + assert tractogram.affine_to_rasmm is None def test_tractogram_to_world(self): tractogram = DATA['tractogram'].copy() @@ -738,7 +752,7 @@ def test_tractogram_to_world(self): np.linalg.inv(affine)) tractogram_world = transformed_tractogram.to_world(lazy=True) - assert_true(type(tractogram_world) is LazyTractogram) + assert type(tractogram_world) is LazyTractogram assert_array_almost_equal(tractogram_world.affine_to_rasmm, np.eye(4)) for s1, s2 in zip(tractogram_world.streamlines, DATA['streamlines']): @@ -746,14 +760,14 @@ def test_tractogram_to_world(self): # Bring them back streamlines to world space in a in-place manner. tractogram_world = transformed_tractogram.to_world() - assert_true(tractogram_world is tractogram) + assert tractogram_world is tractogram assert_array_almost_equal(tractogram.affine_to_rasmm, np.eye(4)) for s1, s2 in zip(tractogram.streamlines, DATA['streamlines']): assert_array_almost_equal(s1, s2) # Calling to_world twice should do nothing. tractogram_world2 = transformed_tractogram.to_world() - assert_true(tractogram_world2 is tractogram) + assert tractogram_world2 is tractogram assert_array_almost_equal(tractogram.affine_to_rasmm, np.eye(4)) for s1, s2 in zip(tractogram.streamlines, DATA['streamlines']): assert_array_almost_equal(s1, s2) @@ -761,7 +775,8 @@ def test_tractogram_to_world(self): # Calling to_world when affine_to_rasmm is None should fail. tractogram = DATA['tractogram'].copy() tractogram.affine_to_rasmm = None - assert_raises(ValueError, tractogram.to_world) + with pytest.raises(ValueError): + tractogram.to_world() def test_tractogram_extend(self): # Load tractogram that contains some metadata. @@ -771,7 +786,7 @@ def test_tractogram_extend(self): (extender, True)): first_arg = t.copy() new_t = op(first_arg, t) - assert_equal(new_t is first_arg, in_place) + assert (new_t is first_arg) is in_place assert_tractogram_equal(new_t[:len(t)], DATA['tractogram']) assert_tractogram_equal(new_t[len(t):], DATA['tractogram']) @@ -790,7 +805,8 @@ class TestLazyTractogram(unittest.TestCase): def test_lazy_tractogram_creation(self): # To create tractogram from arrays use `Tractogram`. - assert_raises(TypeError, LazyTractogram, DATA['streamlines']) + with pytest.raises(TypeError): + LazyTractogram(streamlines=DATA['streamlines']) # Streamlines and other data as generators streamlines = (x for x in DATA['streamlines']) @@ -801,29 +817,28 @@ def test_lazy_tractogram_creation(self): # Creating LazyTractogram with generators is not allowed as # generators get exhausted and are not reusable unlike generator # function. - assert_raises(TypeError, LazyTractogram, streamlines) - assert_raises(TypeError, LazyTractogram, - data_per_point={"none": None}) - assert_raises(TypeError, LazyTractogram, - data_per_streamline=data_per_streamline) - assert_raises(TypeError, LazyTractogram, DATA['streamlines'], - data_per_point=data_per_point) + with pytest.raises(TypeError): + LazyTractogram(streamlines=streamlines) + LazyTractogram(data_per_point={"none": None}) + LazyTractogram(data_per_streamline=data_per_streamline) + LazyTractogram(streamlines=DATA['streamlines'], + data_per_point=data_per_point) # Empty `LazyTractogram` tractogram = LazyTractogram() check_tractogram(tractogram) - assert_true(tractogram.affine_to_rasmm is None) + assert tractogram.affine_to_rasmm is None # Create tractogram with streamlines and other data tractogram = LazyTractogram(DATA['streamlines_func'], DATA['data_per_streamline_func'], DATA['data_per_point_func']) - assert_true(is_lazy_dict(tractogram.data_per_streamline)) - assert_true(is_lazy_dict(tractogram.data_per_point)) + assert is_lazy_dict(tractogram.data_per_streamline) is True + assert is_lazy_dict(tractogram.data_per_point) is True [t for t in tractogram] # Force iteration through tractogram. - assert_equal(len(tractogram), len(DATA['streamlines'])) + assert len(tractogram) == len(DATA['streamlines']) # Generator functions get re-called and creates new iterators. for i in range(2): @@ -855,18 +870,20 @@ def _data_gen(): assert_tractogram_equal(tractogram, DATA['tractogram']) # Creating a LazyTractogram from not a corouting should raise an error. - assert_raises(TypeError, LazyTractogram.from_data_func, _data_gen()) + with pytest.raises(TypeError): + LazyTractogram.from_data_func(_data_gen()) def test_lazy_tractogram_getitem(self): - assert_raises(NotImplementedError, - DATA['lazy_tractogram'].__getitem__, 0) + with pytest.raises(NotImplementedError): + DATA['lazy_tractogram'][0] def test_lazy_tractogram_extend(self): t = DATA['lazy_tractogram'].copy() new_t = DATA['lazy_tractogram'].copy() for op in (operator.add, operator.iadd, extender): - assert_raises(NotImplementedError, op, new_t, t) + with pytest.raises(NotImplementedError): + op(new_t, t) def test_lazy_tractogram_len(self): modules = [module_tractogram] # Modules for which to catch warnings. @@ -875,35 +892,35 @@ def test_lazy_tractogram_len(self): # Calling `len` will create new generators each time. tractogram = LazyTractogram(DATA['streamlines_func']) - assert_true(tractogram._nb_streamlines is None) + assert tractogram._nb_streamlines is None # This should produce a warning message. - assert_equal(len(tractogram), len(DATA['streamlines'])) - assert_equal(tractogram._nb_streamlines, len(DATA['streamlines'])) - assert_equal(len(w), 1) + assert len(tractogram) == len(DATA['streamlines']) + assert tractogram._nb_streamlines == len(DATA['streamlines']) + assert len(w) == 1 tractogram = LazyTractogram(DATA['streamlines_func']) # New instances should still produce a warning message. - assert_equal(len(tractogram), len(DATA['streamlines'])) - assert_equal(len(w), 2) - assert_true(issubclass(w[-1].category, Warning)) + assert len(tractogram) == len(DATA['streamlines']) + assert len(w) == 2 + assert issubclass(w[-1].category, Warning) is True # Calling again 'len' again should *not* produce a warning. - assert_equal(len(tractogram), len(DATA['streamlines'])) - assert_equal(len(w), 2) + assert len(tractogram) == len(DATA['streamlines']) + assert len(w) == 2 with clear_and_catch_warnings(record=True, modules=modules) as w: # Once we iterated through the tractogram, we know the length. tractogram = LazyTractogram(DATA['streamlines_func']) - assert_true(tractogram._nb_streamlines is None) + assert tractogram._nb_streamlines is None [t for t in tractogram] # Force iteration through tractogram. - assert_equal(tractogram._nb_streamlines, len(DATA['streamlines'])) + assert tractogram._nb_streamlines == len(DATA['streamlines']) # This should *not* produce a warning. - assert_equal(len(tractogram), len(DATA['streamlines'])) - assert_equal(len(w), 0) + assert len(tractogram) == len(DATA['streamlines']) + assert len(w) == 0 def test_lazy_tractogram_apply_affine(self): affine = np.eye(4) @@ -913,7 +930,7 @@ def test_lazy_tractogram_apply_affine(self): tractogram = DATA['lazy_tractogram'].copy() transformed_tractogram = tractogram.apply_affine(affine) - assert_true(transformed_tractogram is not tractogram) + assert transformed_tractogram is not tractogram assert_array_equal(tractogram._affine_to_apply, np.eye(4)) assert_array_equal(tractogram.affine_to_rasmm, np.eye(4)) assert_array_equal(transformed_tractogram._affine_to_apply, affine) @@ -935,14 +952,15 @@ def test_lazy_tractogram_apply_affine(self): # Calling to_world when affine_to_rasmm is None should fail. tractogram = DATA['lazy_tractogram'].copy() tractogram.affine_to_rasmm = None - assert_raises(ValueError, tractogram.to_world) + with pytest.raises(ValueError): + tractogram.to_world() # But calling apply_affine when affine_to_rasmm is None should work. tractogram = DATA['lazy_tractogram'].copy() tractogram.affine_to_rasmm = None transformed_tractogram = tractogram.apply_affine(affine) assert_array_equal(transformed_tractogram._affine_to_apply, affine) - assert_true(transformed_tractogram.affine_to_rasmm is None) + assert transformed_tractogram.affine_to_rasmm is None check_tractogram(transformed_tractogram, streamlines=[s*scaling for s in DATA['streamlines']], data_per_streamline=DATA['data_per_streamline'], @@ -950,8 +968,9 @@ def test_lazy_tractogram_apply_affine(self): # Calling apply_affine with lazy=False should fail for LazyTractogram. tractogram = DATA['lazy_tractogram'].copy() - assert_raises(ValueError, tractogram.apply_affine, - affine=np.eye(4), lazy=False) + with pytest.raises(ValueError): + tractogram.apply_affine(affine=np.eye(4), lazy=False) + def test_tractogram_to_world(self): tractogram = DATA['lazy_tractogram'].copy() @@ -965,7 +984,7 @@ def test_tractogram_to_world(self): np.linalg.inv(affine)) tractogram_world = transformed_tractogram.to_world() - assert_true(tractogram_world is not transformed_tractogram) + assert tractogram_world is not transformed_tractogram assert_array_almost_equal(tractogram_world.affine_to_rasmm, np.eye(4)) for s1, s2 in zip(tractogram_world.streamlines, DATA['streamlines']): @@ -980,40 +999,41 @@ def test_tractogram_to_world(self): # Calling to_world when affine_to_rasmm is None should fail. tractogram = DATA['lazy_tractogram'].copy() tractogram.affine_to_rasmm = None - assert_raises(ValueError, tractogram.to_world) + with pytest.raises(ValueError): + tractogram.to_world() def test_lazy_tractogram_copy(self): # Create a copy of the lazy tractogram. tractogram = DATA['lazy_tractogram'].copy() # Check we copied the data and not simply created new references. - assert_true(tractogram is not DATA['lazy_tractogram']) + assert tractogram is not DATA['lazy_tractogram'] # When copying LazyTractogram, the generator function yielding # streamlines should stay the same. - assert_true(tractogram._streamlines - is DATA['lazy_tractogram']._streamlines) + assert tractogram._streamlines \ + is DATA['lazy_tractogram']._streamlines # Copying LazyTractogram, creates new internal LazyDict objects, # but generator functions contained in it should stay the same. - assert_true(tractogram._data_per_streamline - is not DATA['lazy_tractogram']._data_per_streamline) - assert_true(tractogram._data_per_point - is not DATA['lazy_tractogram']._data_per_point) + assert tractogram._data_per_streamline \ + is not DATA['lazy_tractogram']._data_per_streamline + assert tractogram._data_per_point \ + is not DATA['lazy_tractogram']._data_per_point for key in tractogram.data_per_streamline: data = tractogram.data_per_streamline.store[key] expected = DATA['lazy_tractogram'].data_per_streamline.store[key] - assert_true(data is expected) + assert data is expected for key in tractogram.data_per_point: data = tractogram.data_per_point.store[key] expected = DATA['lazy_tractogram'].data_per_point.store[key] - assert_true(data is expected) + assert data is expected # The affine should be a copy. - assert_true(tractogram._affine_to_apply - is not DATA['lazy_tractogram']._affine_to_apply) + assert tractogram._affine_to_apply \ + is not DATA['lazy_tractogram']._affine_to_apply assert_array_equal(tractogram._affine_to_apply, DATA['lazy_tractogram']._affine_to_apply) From 083a89f94b594825b92c8351e7fa7fe008273a83 Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 16:57:39 +0200 Subject: [PATCH 029/223] Update nibabel/streamlines/tests/test_array_sequence.py Co-Authored-By: Chris Markiewicz --- nibabel/streamlines/tests/test_array_sequence.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/streamlines/tests/test_array_sequence.py b/nibabel/streamlines/tests/test_array_sequence.py index 4fdab33d86..8c0aba0069 100644 --- a/nibabel/streamlines/tests/test_array_sequence.py +++ b/nibabel/streamlines/tests/test_array_sequence.py @@ -44,7 +44,7 @@ def check_empty_arr_seq(seq): def check_arr_seq(seq, arrays): lengths = list(map(len, arrays)) - assert is_array_sequence(seq) == True + assert is_array_sequence(seq) assert len(seq) == len(arrays) assert len(seq._offsets) == len(arrays) assert len(seq._lengths) == len(arrays) From a12438cf34de270a27351dd6242f73b2b7272fd2 Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 16:58:04 +0200 Subject: [PATCH 030/223] Update nibabel/streamlines/tests/test_array_sequence.py Co-Authored-By: Chris Markiewicz --- nibabel/streamlines/tests/test_array_sequence.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/streamlines/tests/test_array_sequence.py b/nibabel/streamlines/tests/test_array_sequence.py index 8c0aba0069..73c8fae8db 100644 --- a/nibabel/streamlines/tests/test_array_sequence.py +++ b/nibabel/streamlines/tests/test_array_sequence.py @@ -6,7 +6,7 @@ import numpy as np import pytest -from nibabel.testing_pytest import assert_arrays_equal +from ...testing_pytest import assert_arrays_equal from numpy.testing import assert_array_equal import pytest; pytestmark = pytest.mark.skip() From a44ed467351231fc69398d948251cdbaa8295b8a Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 16:58:19 +0200 Subject: [PATCH 031/223] Update nibabel/streamlines/tests/test_array_sequence.py Co-Authored-By: Chris Markiewicz --- nibabel/streamlines/tests/test_array_sequence.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/streamlines/tests/test_array_sequence.py b/nibabel/streamlines/tests/test_array_sequence.py index 73c8fae8db..2078f19e6c 100644 --- a/nibabel/streamlines/tests/test_array_sequence.py +++ b/nibabel/streamlines/tests/test_array_sequence.py @@ -69,7 +69,7 @@ def check_arr_seq(seq, arrays): def check_arr_seq_view(seq_view, seq): assert seq_view._is_view is True - assert (seq_view is not seq) is True + assert seq_view is not seq assert (np.may_share_memory(seq_view._data, seq._data)) is True assert seq_view._offsets is not seq._offsets assert seq_view._lengths is not seq._lengths From 68d5f9840edc076c5c98b6a0dad3d55fd391e9a6 Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 17:03:03 +0200 Subject: [PATCH 032/223] Update nibabel/streamlines/tests/test_array_sequence.py Co-Authored-By: Chris Markiewicz --- nibabel/streamlines/tests/test_array_sequence.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/streamlines/tests/test_array_sequence.py b/nibabel/streamlines/tests/test_array_sequence.py index 2078f19e6c..e518201194 100644 --- a/nibabel/streamlines/tests/test_array_sequence.py +++ b/nibabel/streamlines/tests/test_array_sequence.py @@ -274,7 +274,7 @@ def test_arraysequence_getitem(self): # Test invalid indexing with pytest.raises(TypeError): - SEQ_DATA['seq'].__getitem__('abc') + SEQ_DATA['seq']['abc'] #SEQ_DATA['seq'].abc # Get specific columns. From 312baa2b8830b1a99bcdd359279aaee7ef51640a Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 17:03:45 +0200 Subject: [PATCH 033/223] Update nibabel/streamlines/tests/test_array_sequence.py Co-Authored-By: Chris Markiewicz --- nibabel/streamlines/tests/test_array_sequence.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/streamlines/tests/test_array_sequence.py b/nibabel/streamlines/tests/test_array_sequence.py index e518201194..fbe923cb98 100644 --- a/nibabel/streamlines/tests/test_array_sequence.py +++ b/nibabel/streamlines/tests/test_array_sequence.py @@ -330,7 +330,7 @@ def test_arraysequence_setitem(self): seq1 = ArraySequence(np.arange(10).reshape(5, 2)) seq2 = ArraySequence(np.arange(15).reshape(5, 3)) with pytest.raises(ValueError): - seq1.__setitem__(slice(0, 5), seq2) + seq1[0:5] = seq2 # Setitem between array sequences with different common shape. seq1 = ArraySequence(np.arange(12).reshape(2, 2, 3)) From d2a5878d1937b99633918bca2f25c41801400088 Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 17:04:00 +0200 Subject: [PATCH 034/223] Update nibabel/streamlines/tests/test_array_sequence.py Co-Authored-By: Chris Markiewicz --- nibabel/streamlines/tests/test_array_sequence.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/streamlines/tests/test_array_sequence.py b/nibabel/streamlines/tests/test_array_sequence.py index fbe923cb98..3fe11dc521 100644 --- a/nibabel/streamlines/tests/test_array_sequence.py +++ b/nibabel/streamlines/tests/test_array_sequence.py @@ -337,7 +337,7 @@ def test_arraysequence_setitem(self): seq2 = ArraySequence(np.arange(8).reshape(2, 2, 2)) with pytest.raises(ValueError): - seq1.__setitem__(slice(0, 2), seq2) + seq1[0:2] = seq2 # Invalid index. with pytest.raises(TypeError): From cffd3bf8aa769dd378a1fd8ba352fe2d3b11854f Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 17:08:11 +0200 Subject: [PATCH 035/223] Update nibabel/streamlines/tests/test_array_sequence.py Co-Authored-By: Chris Markiewicz --- nibabel/streamlines/tests/test_array_sequence.py | 1 + 1 file changed, 1 insertion(+) diff --git a/nibabel/streamlines/tests/test_array_sequence.py b/nibabel/streamlines/tests/test_array_sequence.py index 3fe11dc521..18cee5da80 100644 --- a/nibabel/streamlines/tests/test_array_sequence.py +++ b/nibabel/streamlines/tests/test_array_sequence.py @@ -423,6 +423,7 @@ def _test_binary(op, arrseq, scalars, seqs, inplace=False): with pytest.raises(TypeError): _test_binary(op, seq_int, [0.5], [], inplace=True) # int <-- float + with pytest.raises(TypeError): _test_binary(op, seq_int, [], [seq], inplace=True) # int <-- float From b4630790811142dac1ecd3c0a67041ec82e9f0ec Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 17:08:25 +0200 Subject: [PATCH 036/223] Update nibabel/streamlines/tests/test_array_sequence.py Co-Authored-By: Chris Markiewicz --- nibabel/streamlines/tests/test_array_sequence.py | 1 + 1 file changed, 1 insertion(+) diff --git a/nibabel/streamlines/tests/test_array_sequence.py b/nibabel/streamlines/tests/test_array_sequence.py index 18cee5da80..a87277f64b 100644 --- a/nibabel/streamlines/tests/test_array_sequence.py +++ b/nibabel/streamlines/tests/test_array_sequence.py @@ -433,6 +433,7 @@ def _test_binary(op, arrseq, scalars, seqs, inplace=False): with pytest.raises(ValueError): _test_binary("__pow__", seq_int, [-3], []) + with pytest.raises(ValueError): _test_binary("__ipow__", seq_int, [-3], [], inplace=True) # __itruediv__ is only valid with float arrseq. From b3fa3fbe71d5e5410fc677f5c309facaf95ca486 Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 17:09:37 +0200 Subject: [PATCH 037/223] Update nibabel/streamlines/tests/test_array_sequence.py Co-Authored-By: Chris Markiewicz --- nibabel/streamlines/tests/test_array_sequence.py | 1 + 1 file changed, 1 insertion(+) diff --git a/nibabel/streamlines/tests/test_array_sequence.py b/nibabel/streamlines/tests/test_array_sequence.py index a87277f64b..9c1ac74b1e 100644 --- a/nibabel/streamlines/tests/test_array_sequence.py +++ b/nibabel/streamlines/tests/test_array_sequence.py @@ -448,6 +448,7 @@ def _test_binary(op, arrseq, scalars, seqs, inplace=False): with pytest.raises(TypeError): _test_binary(op, seq_bool, [0.5], []) + with pytest.raises(TypeError): _test_binary(op, seq, [], [seq]) # Unary operators From 6e864f594399e3ae7946669a92745c3bf8f31611 Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 17:09:53 +0200 Subject: [PATCH 038/223] Update nibabel/streamlines/tests/test_tractogram.py Co-Authored-By: Chris Markiewicz --- nibabel/streamlines/tests/test_tractogram.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/streamlines/tests/test_tractogram.py b/nibabel/streamlines/tests/test_tractogram.py index bea0650db0..a43c3b0666 100644 --- a/nibabel/streamlines/tests/test_tractogram.py +++ b/nibabel/streamlines/tests/test_tractogram.py @@ -7,7 +7,7 @@ from collections import defaultdict import pytest -from nibabel.testing_pytest import assert_arrays_equal +from ....testing_pytest import assert_arrays_equal, clear_and_catch_warnings from nibabel.testing_pytest import clear_and_catch_warnings from numpy.testing import assert_array_equal, assert_array_almost_equal import pytest; pytestmark = pytest.mark.skip() From cb681cddf3a322d07d5146e8f7868f80ce9ce873 Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 17:10:06 +0200 Subject: [PATCH 039/223] Update nibabel/streamlines/tests/test_tractogram.py Co-Authored-By: Chris Markiewicz --- nibabel/streamlines/tests/test_tractogram.py | 1 - 1 file changed, 1 deletion(-) diff --git a/nibabel/streamlines/tests/test_tractogram.py b/nibabel/streamlines/tests/test_tractogram.py index a43c3b0666..61b8d8acbb 100644 --- a/nibabel/streamlines/tests/test_tractogram.py +++ b/nibabel/streamlines/tests/test_tractogram.py @@ -8,7 +8,6 @@ import pytest from ....testing_pytest import assert_arrays_equal, clear_and_catch_warnings -from nibabel.testing_pytest import clear_and_catch_warnings from numpy.testing import assert_array_equal, assert_array_almost_equal import pytest; pytestmark = pytest.mark.skip() From 8b01cd45f5d280059f409d3e9db2b4838c66ce01 Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 17:10:25 +0200 Subject: [PATCH 040/223] Update nibabel/streamlines/tests/test_tractogram.py Co-Authored-By: Chris Markiewicz --- nibabel/streamlines/tests/test_tractogram.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/streamlines/tests/test_tractogram.py b/nibabel/streamlines/tests/test_tractogram.py index 61b8d8acbb..8141005b50 100644 --- a/nibabel/streamlines/tests/test_tractogram.py +++ b/nibabel/streamlines/tests/test_tractogram.py @@ -208,7 +208,7 @@ def test_per_array_dict_creation(self): assert_array_equal(data_dict[k], data_per_streamline[k]) del data_dict['mean_curvature'] - assert len(data_dict) == len(data_per_streamline)-1 + assert len(data_dict) == len(data_per_streamline) - 1 # Create a PerArrayDict object using an existing dict object. data_per_streamline = DATA['data_per_streamline'] From c1176ecac30293707f1e226ddf9850e342eb01d0 Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 17:10:48 +0200 Subject: [PATCH 041/223] Update nibabel/streamlines/tests/test_tractogram.py Co-Authored-By: Chris Markiewicz --- nibabel/streamlines/tests/test_tractogram.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/streamlines/tests/test_tractogram.py b/nibabel/streamlines/tests/test_tractogram.py index 8141005b50..bc1eeb5094 100644 --- a/nibabel/streamlines/tests/test_tractogram.py +++ b/nibabel/streamlines/tests/test_tractogram.py @@ -218,7 +218,7 @@ def test_per_array_dict_creation(self): assert_array_equal(data_dict[k], data_per_streamline[k]) del data_dict['mean_curvature'] - assert len(data_dict) == len(data_per_streamline)-1 + assert len(data_dict) == len(data_per_streamline) - 1 # Create a PerArrayDict object using keyword arguments. data_per_streamline = DATA['data_per_streamline'] From d643c7f03777786676593615902a1f6e9e122016 Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 17:11:06 +0200 Subject: [PATCH 042/223] Update nibabel/streamlines/tests/test_tractogram.py Co-Authored-By: Chris Markiewicz --- nibabel/streamlines/tests/test_tractogram.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/streamlines/tests/test_tractogram.py b/nibabel/streamlines/tests/test_tractogram.py index bc1eeb5094..4a9ca698ae 100644 --- a/nibabel/streamlines/tests/test_tractogram.py +++ b/nibabel/streamlines/tests/test_tractogram.py @@ -228,7 +228,7 @@ def test_per_array_dict_creation(self): assert_array_equal(data_dict[k], data_per_streamline[k]) del data_dict['mean_curvature'] - assert len(data_dict) == len(data_per_streamline)-1 + assert len(data_dict) == len(data_per_streamline) - 1 def test_getitem(self): sdict = PerArrayDict(len(DATA['tractogram']), From 8326522259ac3669eefb470324151328d2963652 Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 17:11:44 +0200 Subject: [PATCH 043/223] Update nibabel/streamlines/tests/test_tractogram.py Co-Authored-By: Chris Markiewicz --- nibabel/streamlines/tests/test_tractogram.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/streamlines/tests/test_tractogram.py b/nibabel/streamlines/tests/test_tractogram.py index 4a9ca698ae..4c0f32d0b9 100644 --- a/nibabel/streamlines/tests/test_tractogram.py +++ b/nibabel/streamlines/tests/test_tractogram.py @@ -311,7 +311,7 @@ def test_per_array_sequence_dict_creation(self): assert_arrays_equal(data_dict[k], data_per_point[k]) del data_dict['fa'] - assert len(data_dict) == len(data_per_point)-1 + assert len(data_dict) == len(data_per_point) - 1 # Create a PerArraySequenceDict object using an existing dict object. data_per_point = DATA['data_per_point'] From 745108ad4e52d86cad75f0a66411f0c7ce2b19a6 Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 17:13:05 +0200 Subject: [PATCH 044/223] Update nibabel/streamlines/tests/test_tractogram.py Co-Authored-By: Chris Markiewicz --- nibabel/streamlines/tests/test_tractogram.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/streamlines/tests/test_tractogram.py b/nibabel/streamlines/tests/test_tractogram.py index 4c0f32d0b9..f8a4ad515d 100644 --- a/nibabel/streamlines/tests/test_tractogram.py +++ b/nibabel/streamlines/tests/test_tractogram.py @@ -785,7 +785,7 @@ def test_tractogram_extend(self): (extender, True)): first_arg = t.copy() new_t = op(first_arg, t) - assert (new_t is first_arg) is in_place + assert (new_t is first_arg) == in_place assert_tractogram_equal(new_t[:len(t)], DATA['tractogram']) assert_tractogram_equal(new_t[len(t):], DATA['tractogram']) From c758df74c4be3f0f07b8509420c3368ca0c920cf Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 17:14:16 +0200 Subject: [PATCH 045/223] Update nibabel/streamlines/tests/test_tractogram.py Co-Authored-By: Chris Markiewicz --- nibabel/streamlines/tests/test_tractogram.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/streamlines/tests/test_tractogram.py b/nibabel/streamlines/tests/test_tractogram.py index f8a4ad515d..b3706fe1c2 100644 --- a/nibabel/streamlines/tests/test_tractogram.py +++ b/nibabel/streamlines/tests/test_tractogram.py @@ -321,7 +321,7 @@ def test_per_array_sequence_dict_creation(self): assert_arrays_equal(data_dict[k], data_per_point[k]) del data_dict['fa'] - assert len(data_dict) == len(data_per_point)-1 + assert len(data_dict) == len(data_per_point) - 1 # Create a PerArraySequenceDict object using keyword arguments. data_per_point = DATA['data_per_point'] From d168423d7a5aaf91653e1e4167f9f50d21ab57d2 Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 17:14:48 +0200 Subject: [PATCH 046/223] Update nibabel/streamlines/tests/test_tractogram.py Co-Authored-By: Chris Markiewicz --- nibabel/streamlines/tests/test_tractogram.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/streamlines/tests/test_tractogram.py b/nibabel/streamlines/tests/test_tractogram.py index b3706fe1c2..071ef1d331 100644 --- a/nibabel/streamlines/tests/test_tractogram.py +++ b/nibabel/streamlines/tests/test_tractogram.py @@ -484,7 +484,7 @@ def test_tractogram_creation(self): DATA['data_per_point']) assert is_data_dict(tractogram.data_per_streamline) is True - assert is_data_dict(tractogram.data_per_point) is True + assert is_data_dict(tractogram.data_per_point) # Create a tractogram from another tractogram attributes. tractogram2 = Tractogram(tractogram.streamlines, From 1ad759b43081980044f80c29f7bb18f7e7172eaf Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 17:15:05 +0200 Subject: [PATCH 047/223] Update nibabel/streamlines/tests/test_tractogram.py Co-Authored-By: Chris Markiewicz --- nibabel/streamlines/tests/test_tractogram.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/streamlines/tests/test_tractogram.py b/nibabel/streamlines/tests/test_tractogram.py index 071ef1d331..9ce15a7729 100644 --- a/nibabel/streamlines/tests/test_tractogram.py +++ b/nibabel/streamlines/tests/test_tractogram.py @@ -420,7 +420,7 @@ def test_lazydict_creation(self): expected_keys = DATA['data_per_streamline_func'].keys() for data_dict in lazy_dicts: - assert is_lazy_dict(data_dict) is True + assert is_lazy_dict(data_dict) assert data_dict.keys() == expected_keys for k in data_dict.keys(): assert_array_equal(list(data_dict[k]), From 7bc83a72198270ec5df7878d5ac980d39061dd2f Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 17:15:26 +0200 Subject: [PATCH 048/223] Update nibabel/streamlines/tests/test_tractogram.py Co-Authored-By: Chris Markiewicz --- nibabel/streamlines/tests/test_tractogram.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/streamlines/tests/test_tractogram.py b/nibabel/streamlines/tests/test_tractogram.py index 9ce15a7729..72c405ed73 100644 --- a/nibabel/streamlines/tests/test_tractogram.py +++ b/nibabel/streamlines/tests/test_tractogram.py @@ -331,7 +331,7 @@ def test_per_array_sequence_dict_creation(self): assert_arrays_equal(data_dict[k], data_per_point[k]) del data_dict['fa'] - assert len(data_dict) == len(data_per_point)-1 + assert len(data_dict) == len(data_per_point) - 1 def test_getitem(self): total_nb_rows = DATA['tractogram'].streamlines.total_nb_rows From bfa7a3dc82cecdd91369cdaf25a4ef41ff6701b0 Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 17:15:42 +0200 Subject: [PATCH 049/223] Update nibabel/streamlines/tests/test_tractogram.py Co-Authored-By: Chris Markiewicz --- nibabel/streamlines/tests/test_tractogram.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/streamlines/tests/test_tractogram.py b/nibabel/streamlines/tests/test_tractogram.py index 72c405ed73..b44feae45f 100644 --- a/nibabel/streamlines/tests/test_tractogram.py +++ b/nibabel/streamlines/tests/test_tractogram.py @@ -483,7 +483,7 @@ def test_tractogram_creation(self): DATA['data_per_streamline'], DATA['data_per_point']) - assert is_data_dict(tractogram.data_per_streamline) is True + assert is_data_dict(tractogram.data_per_streamline) assert is_data_dict(tractogram.data_per_point) # Create a tractogram from another tractogram attributes. From 4fa17af5a6246ad0b5da875945c5943fe7484be3 Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 17:23:08 +0200 Subject: [PATCH 050/223] Update test_array_sequence.py --- nibabel/streamlines/tests/test_array_sequence.py | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/nibabel/streamlines/tests/test_array_sequence.py b/nibabel/streamlines/tests/test_array_sequence.py index 9c1ac74b1e..c1429f8fc4 100644 --- a/nibabel/streamlines/tests/test_array_sequence.py +++ b/nibabel/streamlines/tests/test_array_sequence.py @@ -367,11 +367,8 @@ def _test_binary(op, arrseq, scalars, seqs, inplace=False): for scalar in scalars: orig = arrseq.copy() seq = getattr(orig, op)(scalar) - - if inplace: - assert seq is orig - else: - assert seq is not orig + + assert (seq is orig) == inplace check_arr_seq(seq, [getattr(e, op)(scalar) for e in arrseq]) @@ -438,9 +435,9 @@ def _test_binary(op, arrseq, scalars, seqs, inplace=False): # __itruediv__ is only valid with float arrseq. for scalar in SCALARS + ARRSEQS: + seq_int_cp = seq_int.copy() with pytest.raises(TypeError): - seq_int_cp = seq_int.copy() - seq_int_cp.__itruediv__(scalar) + seq_int_cp /= scalar # Bitwise operators for op in ("__lshift__", "__rshift__", "__or__", "__and__", "__xor__"): From 51016a783bbb90943ecaa6ab16a22efe23ea36d4 Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 17:27:59 +0200 Subject: [PATCH 051/223] Update test_tractogram.py --- nibabel/streamlines/tests/test_tractogram.py | 37 +++++++++----------- 1 file changed, 17 insertions(+), 20 deletions(-) diff --git a/nibabel/streamlines/tests/test_tractogram.py b/nibabel/streamlines/tests/test_tractogram.py index b44feae45f..2fa72e3514 100644 --- a/nibabel/streamlines/tests/test_tractogram.py +++ b/nibabel/streamlines/tests/test_tractogram.py @@ -603,20 +603,15 @@ def test_tractogram_copy(self): # Check we copied the data and not simply created new references. assert tractogram is not DATA['tractogram'] - assert tractogram.streamlines is \ - not DATA['tractogram'].streamlines - assert tractogram.data_per_streamline is \ - not DATA['tractogram'].data_per_streamline - assert tractogram.data_per_point is \ - not DATA['tractogram'].data_per_point + assert tractogram.streamlines is not DATA['tractogram'].streamlines + assert tractogram.data_per_streamline is not DATA['tractogram'].data_per_streamline + assert tractogram.data_per_point is not DATA['tractogram'].data_per_point for key in tractogram.data_per_streamline: - assert tractogram.data_per_streamline[key] is \ - not DATA['tractogram'].data_per_streamline[key] + assert tractogram.data_per_streamline[key] is not DATA['tractogram'].data_per_streamline[key] for key in tractogram.data_per_point: - assert tractogram.data_per_point[key] is \ - not DATA['tractogram'].data_per_point[key] + assert tractogram.data_per_point[key] is not DATA['tractogram'].data_per_point[key] # Check the values of the data are the same. assert_tractogram_equal(tractogram, DATA['tractogram']) @@ -818,8 +813,14 @@ def test_lazy_tractogram_creation(self): # function. with pytest.raises(TypeError): LazyTractogram(streamlines=streamlines) + + with pytest.raises(TypeError): LazyTractogram(data_per_point={"none": None}) + + with pytest.raises(TypeError): LazyTractogram(data_per_streamline=data_per_streamline) + + with pytest.raises(TypeError): LazyTractogram(streamlines=DATA['streamlines'], data_per_point=data_per_point) @@ -833,8 +834,8 @@ def test_lazy_tractogram_creation(self): DATA['data_per_streamline_func'], DATA['data_per_point_func']) - assert is_lazy_dict(tractogram.data_per_streamline) is True - assert is_lazy_dict(tractogram.data_per_point) is True + assert is_lazy_dict(tractogram.data_per_streamline) + assert is_lazy_dict(tractogram.data_per_point) [t for t in tractogram] # Force iteration through tractogram. assert len(tractogram) == len(DATA['streamlines']) @@ -1010,15 +1011,12 @@ def test_lazy_tractogram_copy(self): # When copying LazyTractogram, the generator function yielding # streamlines should stay the same. - assert tractogram._streamlines \ - is DATA['lazy_tractogram']._streamlines + assert tractogram._streamlines is DATA['lazy_tractogram']._streamlines # Copying LazyTractogram, creates new internal LazyDict objects, # but generator functions contained in it should stay the same. - assert tractogram._data_per_streamline \ - is not DATA['lazy_tractogram']._data_per_streamline - assert tractogram._data_per_point \ - is not DATA['lazy_tractogram']._data_per_point + assert tractogram._data_per_streamline is not DATA['lazy_tractogram']._data_per_streamline + assert tractogram._data_per_point is not DATA['lazy_tractogram']._data_per_point for key in tractogram.data_per_streamline: data = tractogram.data_per_streamline.store[key] @@ -1031,8 +1029,7 @@ def test_lazy_tractogram_copy(self): assert data is expected # The affine should be a copy. - assert tractogram._affine_to_apply \ - is not DATA['lazy_tractogram']._affine_to_apply + assert tractogram._affine_to_apply is not DATA['lazy_tractogram']._affine_to_apply assert_array_equal(tractogram._affine_to_apply, DATA['lazy_tractogram']._affine_to_apply) From bc0c67bad84ebe7902d33707b7e1ce4543195b76 Mon Sep 17 00:00:00 2001 From: Anibal Solon Date: Tue, 4 Feb 2020 11:13:30 -0500 Subject: [PATCH 052/223] make sure cov is installed --- setup.cfg | 1 + 1 file changed, 1 insertion(+) diff --git a/setup.cfg b/setup.cfg index fe6d91bdd3..34c8456a04 100644 --- a/setup.cfg +++ b/setup.cfg @@ -59,6 +59,7 @@ nosetests = coverage nose >=0.11 pytest + pytest-cov test = coverage nose >=0.11 From ab2e0b89929a4a0ecb8a614359f857bb98638c8b Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 4 Feb 2020 11:30:23 -0500 Subject: [PATCH 053/223] TEST: Fix import/indentation errors --- .../streamlines/tests/test_array_sequence.py | 2 +- nibabel/streamlines/tests/test_tractogram.py | 18 +++++++----------- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/nibabel/streamlines/tests/test_array_sequence.py b/nibabel/streamlines/tests/test_array_sequence.py index c1429f8fc4..e6a3af3e62 100644 --- a/nibabel/streamlines/tests/test_array_sequence.py +++ b/nibabel/streamlines/tests/test_array_sequence.py @@ -420,7 +420,7 @@ def _test_binary(op, arrseq, scalars, seqs, inplace=False): with pytest.raises(TypeError): _test_binary(op, seq_int, [0.5], [], inplace=True) # int <-- float - with pytest.raises(TypeError): + with pytest.raises(TypeError): _test_binary(op, seq_int, [], [seq], inplace=True) # int <-- float diff --git a/nibabel/streamlines/tests/test_tractogram.py b/nibabel/streamlines/tests/test_tractogram.py index 2fa72e3514..0ab3cb3106 100644 --- a/nibabel/streamlines/tests/test_tractogram.py +++ b/nibabel/streamlines/tests/test_tractogram.py @@ -7,7 +7,7 @@ from collections import defaultdict import pytest -from ....testing_pytest import assert_arrays_equal, clear_and_catch_warnings +from ...testing_pytest import assert_arrays_equal, clear_and_catch_warnings from numpy.testing import assert_array_equal, assert_array_almost_equal import pytest; pytestmark = pytest.mark.skip() @@ -632,7 +632,7 @@ def test_creating_invalid_tractogram(self): with pytest.raises(ValueError): Tractogram(streamlines=DATA['streamlines'], - data_per_streamline={'properties': properties}) + data_per_streamline={'properties': properties}) # Inconsistent dimension for a data_per_point. scalars = [[(1, 0, 0)]*1, @@ -650,7 +650,7 @@ def test_creating_invalid_tractogram(self): with pytest.raises(ValueError): Tractogram(streamlines=DATA['streamlines'], - data_per_streamline={'properties': properties}) + data_per_streamline={'properties': properties}) # Too many dimension for a data_per_streamline. properties = [np.array([[1.11], [1.22]], dtype="f4"), @@ -659,7 +659,7 @@ def test_creating_invalid_tractogram(self): with pytest.raises(ValueError): Tractogram(streamlines=DATA['streamlines'], - data_per_streamline={'properties': properties}) + data_per_streamline={'properties': properties}) def test_tractogram_apply_affine(self): tractogram = DATA['tractogram'].copy() @@ -813,16 +813,12 @@ def test_lazy_tractogram_creation(self): # function. with pytest.raises(TypeError): LazyTractogram(streamlines=streamlines) - with pytest.raises(TypeError): LazyTractogram(data_per_point={"none": None}) - - with pytest.raises(TypeError): + with pytest.raises(TypeError): LazyTractogram(data_per_streamline=data_per_streamline) - - with pytest.raises(TypeError): - LazyTractogram(streamlines=DATA['streamlines'], - data_per_point=data_per_point) + with pytest.raises(TypeError): + LazyTractogram(streamlines=DATA['streamlines'], data_per_point=data_per_point) # Empty `LazyTractogram` tractogram = LazyTractogram() From 5ec71fb768b7469a4fd9c55e3f71cb0e361d9bcd Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 4 Feb 2020 11:41:38 -0500 Subject: [PATCH 054/223] ENH: Use generic unittest.SkipTest in missing optional_package --- nibabel/optpkg.py | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/nibabel/optpkg.py b/nibabel/optpkg.py index f87f64da9f..3590cd3c00 100644 --- a/nibabel/optpkg.py +++ b/nibabel/optpkg.py @@ -3,11 +3,6 @@ from distutils.version import LooseVersion from .tripwire import TripWire -if pkgutil.find_loader('nose'): - have_nose = True -else: - have_nose = False - def _check_pkg_version(pkg, min_version): # Default version checking function @@ -115,10 +110,8 @@ def optional_package(name, trip_msg=None, min_version=None): % (name, name, exc)) pkg = TripWire(trip_msg) - # TODO dj: no clue why is it needed... def setup_module(): - if have_nose: - import nose - raise nose.plugins.skip.SkipTest('No %s for these tests' - % name) + import unittest + raise unittest.SkipTest('No %s for these tests' % name) + return pkg, False, setup_module From f2a96be6fa76f197f237d5f0ca4480d4baed171e Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 4 Feb 2020 11:53:31 -0500 Subject: [PATCH 055/223] TEST: Cleanup test_array_sequence --- .../streamlines/tests/test_array_sequence.py | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/nibabel/streamlines/tests/test_array_sequence.py b/nibabel/streamlines/tests/test_array_sequence.py index e6a3af3e62..0802d19b19 100644 --- a/nibabel/streamlines/tests/test_array_sequence.py +++ b/nibabel/streamlines/tests/test_array_sequence.py @@ -9,8 +9,6 @@ from ...testing_pytest import assert_arrays_equal from numpy.testing import assert_array_equal -import pytest; pytestmark = pytest.mark.skip() - from ..array_sequence import ArraySequence, is_array_sequence, concatenate @@ -37,9 +35,7 @@ def check_empty_arr_seq(seq): assert len(seq._lengths) == 0 # assert_equal(seq._data.ndim, 0) assert seq._data.ndim == 1 - - # TODO: Check assert_true - # assert_true(seq.common_shape == ()) + assert seq.common_shape == () def check_arr_seq(seq, arrays): @@ -68,9 +64,9 @@ def check_arr_seq(seq, arrays): def check_arr_seq_view(seq_view, seq): - assert seq_view._is_view is True + assert seq_view._is_view assert seq_view is not seq - assert (np.may_share_memory(seq_view._data, seq._data)) is True + assert np.may_share_memory(seq_view._data, seq._data) assert seq_view._offsets is not seq._offsets assert seq_view._lengths is not seq._lengths @@ -179,7 +175,6 @@ def test_arraysequence_append(self): element = generate_data(nb_arrays=1, common_shape=SEQ_DATA['seq'].common_shape*2, rng=SEQ_DATA['rng'])[0] - with pytest.raises(ValueError): seq.append(element) @@ -275,7 +270,6 @@ def test_arraysequence_getitem(self): # Test invalid indexing with pytest.raises(TypeError): SEQ_DATA['seq']['abc'] - #SEQ_DATA['seq'].abc # Get specific columns. seq_view = SEQ_DATA['seq'][:, 2] @@ -323,8 +317,7 @@ def test_arraysequence_setitem(self): # Setitem between array sequences with different number of sequences. seq = ArraySequence(np.arange(900).reshape((50,6,3))) with pytest.raises(ValueError): - seq.__setitem__(slice(0, 4), seq[5:10]) - + seq[0:4] = seq[5:10] # Setitem between array sequences with different amount of points. seq1 = ArraySequence(np.arange(10).reshape(5, 2)) @@ -341,7 +334,7 @@ def test_arraysequence_setitem(self): # Invalid index. with pytest.raises(TypeError): - seq.__setitem__(object(), None) + seq[object()] = None def test_arraysequence_operators(self): # Disable division per zero warnings. @@ -367,7 +360,6 @@ def _test_binary(op, arrseq, scalars, seqs, inplace=False): for scalar in scalars: orig = arrseq.copy() seq = getattr(orig, op)(scalar) - assert (seq is orig) == inplace check_arr_seq(seq, [getattr(e, op)(scalar) for e in arrseq]) From 3b6f32a78be96e069ee208bfe2727a4b83a022f3 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 4 Feb 2020 11:53:51 -0500 Subject: [PATCH 056/223] CI: Skip more nose tests --- .travis.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index a0c19ff1f3..b6ef1a18a0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -134,12 +134,15 @@ script: cd for_testing cp ../.coveragerc . nosetests --with-doctest --with-coverage --cover-package nibabel nibabel \ + -I test_array_sequence \ + -I test_tractogram \ -I test_api_validators \ -I test_arrayproxy \ - -I test_arrayriters \ + -I test_arraywriters \ -I test_batteryrunners \ -I test_brikhead \ -I test_casting \ + -I test_cifti2io_header \ -I test_data \ -I test_deprecated \ -I test_deprecator \ From 49909dc35159b1974db7b9a3abb91b576155abd8 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 4 Feb 2020 11:59:13 -0500 Subject: [PATCH 057/223] TEST: Un-skip tractogram tests, style cleanups --- nibabel/streamlines/tests/test_tractogram.py | 31 +++++++------------- 1 file changed, 10 insertions(+), 21 deletions(-) diff --git a/nibabel/streamlines/tests/test_tractogram.py b/nibabel/streamlines/tests/test_tractogram.py index 0ab3cb3106..16f1df2989 100644 --- a/nibabel/streamlines/tests/test_tractogram.py +++ b/nibabel/streamlines/tests/test_tractogram.py @@ -9,7 +9,6 @@ import pytest from ...testing_pytest import assert_arrays_equal, clear_and_catch_warnings from numpy.testing import assert_array_equal, assert_array_almost_equal -import pytest; pytestmark = pytest.mark.skip() from .. import tractogram as module_tractogram from ..tractogram import is_data_dict, is_lazy_dict @@ -236,7 +235,6 @@ def test_getitem(self): with pytest.raises(KeyError): sdict['invalid'] - #assert_raises(KeyError, sdict.__getitem__, 'invalid') # Test slicing and advanced indexing. for k, v in DATA['tractogram'].data_per_streamline.items(): @@ -339,7 +337,6 @@ def test_getitem(self): with pytest.raises(KeyError): sdict['invalid'] - #assert_raises(KeyError, sdict.__getitem__, 'invalid') # Test slicing and advanced indexing. for k, v in DATA['tractogram'].data_per_point.items(): @@ -509,8 +506,7 @@ def test_tractogram_creation(self): data_per_point = {'wrong_data': wrong_data} with pytest.raises(ValueError): - Tractogram(streamlines=DATA['streamlines'], - data_per_point=data_per_point) + Tractogram(streamlines=DATA['streamlines'], data_per_point=data_per_point) # Inconsistent number of scalars between streamlines wrong_data = [[(1, 0, 0)]*1, @@ -519,8 +515,7 @@ def test_tractogram_creation(self): data_per_point = {'wrong_data': wrong_data} with pytest.raises(ValueError): - Tractogram(streamlines=DATA['streamlines'], - data_per_point=data_per_point) + Tractogram(streamlines=DATA['streamlines'], data_per_point=data_per_point) def test_setting_affine_to_rasmm(self): tractogram = DATA['tractogram'].copy() @@ -542,7 +537,6 @@ def test_setting_affine_to_rasmm(self): with pytest.raises(ValueError): tractogram.affine_to_rasmm = affine[::2] - def test_tractogram_getitem(self): # Retrieve TractogramItem by their index. for i, t in enumerate(DATA['tractogram']): @@ -623,25 +617,22 @@ def test_creating_invalid_tractogram(self): [(0, 0, 1)]*3] # Last streamlines has 5 points. with pytest.raises(ValueError): - Tractogram(streamlines=DATA['streamlines'], - data_per_point={'scalars':scalars}) + Tractogram(streamlines=DATA['streamlines'], data_per_point={'scalars': scalars}) # Not enough data_per_streamline for all streamlines. properties = [np.array([1.11, 1.22], dtype="f4"), np.array([3.11, 3.22], dtype="f4")] with pytest.raises(ValueError): - Tractogram(streamlines=DATA['streamlines'], - data_per_streamline={'properties': properties}) + Tractogram(streamlines=DATA['streamlines'], data_per_streamline={'properties': properties}) # Inconsistent dimension for a data_per_point. - scalars = [[(1, 0, 0)]*1, - [(0, 1)]*2, - [(0, 0, 1)]*5] + scalars = [[(1, 0, 0)] * 1, + [(0, 1)] * 2, + [(0, 0, 1)] * 5] with pytest.raises(ValueError): - Tractogram(streamlines=DATA['streamlines'], - data_per_point={'scalars':scalars}) + Tractogram(streamlines=DATA['streamlines'], data_per_point={'scalars':scalars}) # Inconsistent dimension for a data_per_streamline. properties = [[1.11, 1.22], @@ -649,8 +640,7 @@ def test_creating_invalid_tractogram(self): [3.11, 3.22]] with pytest.raises(ValueError): - Tractogram(streamlines=DATA['streamlines'], - data_per_streamline={'properties': properties}) + Tractogram(streamlines=DATA['streamlines'], data_per_streamline={'properties': properties}) # Too many dimension for a data_per_streamline. properties = [np.array([[1.11], [1.22]], dtype="f4"), @@ -658,8 +648,7 @@ def test_creating_invalid_tractogram(self): np.array([[3.11], [3.22]], dtype="f4")] with pytest.raises(ValueError): - Tractogram(streamlines=DATA['streamlines'], - data_per_streamline={'properties': properties}) + Tractogram(streamlines=DATA['streamlines'], data_per_streamline={'properties': properties}) def test_tractogram_apply_affine(self): tractogram = DATA['tractogram'].copy() From 8fe1c2cd9e76a6c4b3f1f3f90fe723ea05b2861c Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 4 Feb 2020 13:51:53 -0500 Subject: [PATCH 058/223] TEST: Fix optpkg test --- nibabel/tests/test_optpkg.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nibabel/tests/test_optpkg.py b/nibabel/tests/test_optpkg.py index 5603fc5127..a6b9571530 100644 --- a/nibabel/tests/test_optpkg.py +++ b/nibabel/tests/test_optpkg.py @@ -41,10 +41,10 @@ def test_basic(): # We never have package _not_a_package assert_bad('_not_a_package') - # setup_module imports nose, so make sure we don't disrupt that + # setup_module imports unittest, so make sure we don't disrupt that orig_import = builtins.__import__ def raise_Exception(*args, **kwargs): - if args[0] == 'nose': + if args[0] == 'unittest': return orig_import(*args, **kwargs) raise Exception( "non ImportError could be thrown by some malfunctioning module " From 4fbcb79fc88bc2cbc29eb0eb3fb751ce9d66f4dc Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 4 Feb 2020 13:54:15 -0500 Subject: [PATCH 059/223] TEST: Style updates to test_analyze --- nibabel/tests/test_analyze.py | 60 ++++++++++++----------------------- 1 file changed, 20 insertions(+), 40 deletions(-) diff --git a/nibabel/tests/test_analyze.py b/nibabel/tests/test_analyze.py index 9032f136c5..14bfb3b5e7 100644 --- a/nibabel/tests/test_analyze.py +++ b/nibabel/tests/test_analyze.py @@ -67,8 +67,7 @@ class TestAnalyzeHeader(_TestLabeledWrapStruct): def test_supported_types(self): hdr = self.header_class() - assert (self.supported_np_types == - supported_np_types(hdr)) + assert self.supported_np_types == supported_np_types(hdr) def get_bad_bb(self): # A value for the binary block that should raise an error @@ -117,12 +116,10 @@ def test_checks(self): hdr = hdr_t.copy() hdr['sizeof_hdr'] = 1 with suppress_warnings(): - assert (self._dxer(hdr) == 'sizeof_hdr should be ' + - str(self.sizeof_hdr)) + assert self._dxer(hdr) == 'sizeof_hdr should be ' + str(self.sizeof_hdr) hdr = hdr_t.copy() hdr['datatype'] = 0 - assert (self._dxer(hdr) == 'data code 0 not supported\n' - 'bitpix does not match datatype') + assert self._dxer(hdr) == 'data code 0 not supported\nbitpix does not match datatype' hdr = hdr_t.copy() hdr['bitpix'] = 0 assert self._dxer(hdr) == 'bitpix does not match datatype' @@ -144,11 +141,8 @@ def test_log_checks(self): fhdr, message, raiser = self.log_chk(hdr, 30) assert fhdr['sizeof_hdr'] == self.sizeof_hdr - assert (message == - 'sizeof_hdr should be {0}; set sizeof_hdr to {0}'.format( - self.sizeof_hdr)) - with pytest.raises(raiser[0]): - raiser[1](*raiser[2:]) + assert message == 'sizeof_hdr should be {0}; set sizeof_hdr to {0}'.format(self.sizeof_hdr) + pytest.raises(*raiser) # RGB datatype does not raise error hdr = HC() hdr.set_data_dtype('RGB') @@ -158,28 +152,22 @@ def test_log_checks(self): hdr['datatype'] = -1 # severity 40 with suppress_warnings(): fhdr, message, raiser = self.log_chk(hdr, 40) - assert (message == 'data code -1 not recognized; ' - 'not attempting fix') + assert message == 'data code -1 not recognized; not attempting fix' - with pytest.raises(raiser[0]): - raiser[1](*raiser[2:]) + pytest.raises(*raiser) # datatype not supported hdr['datatype'] = 255 # severity 40 fhdr, message, raiser = self.log_chk(hdr, 40) - assert (message == 'data code 255 not supported; ' - 'not attempting fix') - with pytest.raises(raiser[0]): - raiser[1](*raiser[2:]) + assert message == 'data code 255 not supported; not attempting fix' + pytest.raises(*raiser) # bitpix hdr = HC() hdr['datatype'] = 16 # float32 hdr['bitpix'] = 16 # severity 10 fhdr, message, raiser = self.log_chk(hdr, 10) assert fhdr['bitpix'] == 32 - assert (message == 'bitpix does not match datatype; ' - 'setting bitpix to match datatype') - with pytest.raises(raiser[0]): - raiser[1](*raiser[2:]) + assert message == 'bitpix does not match datatype; setting bitpix to match datatype' + pytest.raises(*raiser) def test_pixdim_log_checks(self): # pixdim positive @@ -188,17 +176,14 @@ def test_pixdim_log_checks(self): hdr['pixdim'][1] = -2 # severity 35 fhdr, message, raiser = self.log_chk(hdr, 35) assert fhdr['pixdim'][1] == 2 - assert (message == 'pixdim[1,2,3] should be positive; ' - 'setting to abs of pixdim values') - with pytest.raises(raiser[0]): - raiser[1](*raiser[2:]) + assert message == 'pixdim[1,2,3] should be positive; setting to abs of pixdim values' + pytest.raises(*raiser) hdr = HC() hdr['pixdim'][1] = 0 # severity 30 fhdr, message, raiser = self.log_chk(hdr, 30) assert fhdr['pixdim'][1] == 1 assert message == PIXDIM0_MSG - with pytest.raises(raiser[0]): - raiser[1](*raiser[2:]) + pytest.raises(*raiser) # both hdr = HC() hdr['pixdim'][1] = 0 # severity 30 @@ -206,12 +191,9 @@ def test_pixdim_log_checks(self): fhdr, message, raiser = self.log_chk(hdr, 35) assert fhdr['pixdim'][1] == 1 assert fhdr['pixdim'][2] == 2 - assert (message == 'pixdim[1,2,3] should be ' - 'non-zero and pixdim[1,2,3] should ' - 'be positive; setting 0 dims to 1 ' - 'and setting to abs of pixdim values') - with pytest.raises(raiser[0]): - raiser[1](*raiser[2:]) + assert message == ('pixdim[1,2,3] should be non-zero and pixdim[1,2,3] should be ' + 'positive; setting 0 dims to 1 and setting to abs of pixdim values') + pytest.raises(*raiser) def test_no_scaling_fixes(self): # Check we do not fix slope or intercept @@ -252,9 +234,8 @@ def test_logger_error(self): # Check log message appears in new logger imageglobals.logger = logger hdr.copy().check_fix() - assert (str_io.getvalue() == - 'bitpix does not match datatype; ' - 'setting bitpix to match datatype\n') + assert str_io.getvalue() == ('bitpix does not match datatype; ' + 'setting bitpix to match datatype\n') # Check that error_level in fact causes error to be raised imageglobals.error_level = 10 with pytest.raises(HeaderDataError): @@ -711,8 +692,7 @@ class TestAnalyzeImage(tsi.TestSpatialImage, tsi.MmapImageMixin): def test_supported_types(self): img = self.image_class(np.zeros((2, 3, 4)), np.eye(4)) - assert (self.supported_np_types == - supported_np_types(img)) + assert self.supported_np_types == supported_np_types(img) def test_default_header(self): # Check default header is as expected From 24cf57da6038cb03805a582639e154441e039af7 Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 21:55:41 +0200 Subject: [PATCH 060/223] TEST: test_trk to pytest --- nibabel/streamlines/tests/test_trk.py | 127 ++++++++++++++------------ 1 file changed, 69 insertions(+), 58 deletions(-) diff --git a/nibabel/streamlines/tests/test_trk.py b/nibabel/streamlines/tests/test_trk.py index 8d4f01d766..f88631965e 100644 --- a/nibabel/streamlines/tests/test_trk.py +++ b/nibabel/streamlines/tests/test_trk.py @@ -7,11 +7,10 @@ from io import BytesIO -from nibabel.testing import data_path -from nibabel.testing import clear_and_catch_warnings, assert_arr_dict_equal -from nose.tools import assert_equal, assert_raises, assert_true +import pytest +from ...testing_pytest import data_path +from ...testing_pytest import clear_and_catch_warnings, assert_arr_dict_equal from numpy.testing import assert_array_equal -import pytest; pytestmark = pytest.mark.skip() from .test_tractogram import assert_tractogram_equal from ..tractogram import Tractogram @@ -24,7 +23,7 @@ DATA = {} -def setup(): +def setup_module(): global DATA DATA['empty_trk_fname'] = pjoin(data_path, "empty.trk") @@ -133,45 +132,51 @@ def test_load_file_with_wrong_information(self): trk_struct[Field.VOXEL_TO_RASMM] = np.zeros((4, 4)) with clear_and_catch_warnings(record=True, modules=[trk_module]) as w: trk = TrkFile.load(BytesIO(trk_bytes)) - assert_equal(len(w), 1) - assert_true(issubclass(w[0].category, HeaderWarning)) - assert_true("identity" in str(w[0].message)) + assert len(w) == 1 + assert issubclass(w[0].category, HeaderWarning) + assert "identity" in str(w[0].message) assert_array_equal(trk.affine, np.eye(4)) # Simulate a TRK where `vox_to_ras` is invalid. trk_struct, trk_bytes = self.trk_with_bytes() trk_struct[Field.VOXEL_TO_RASMM] = np.diag([0, 0, 0, 1]) with clear_and_catch_warnings(record=True, modules=[trk_module]) as w: - assert_raises(HeaderError, TrkFile.load, BytesIO(trk_bytes)) + with pytest.raises(HeaderError): + TrkFile.load(BytesIO(trk_bytes)) # Simulate a TRK file where `voxel_order` was not provided. trk_struct, trk_bytes = self.trk_with_bytes() trk_struct[Field.VOXEL_ORDER] = b'' with clear_and_catch_warnings(record=True, modules=[trk_module]) as w: TrkFile.load(BytesIO(trk_bytes)) - assert_equal(len(w), 1) - assert_true(issubclass(w[0].category, HeaderWarning)) - assert_true("LPS" in str(w[0].message)) + assert len(w) == 1 + assert issubclass(w[0].category, HeaderWarning) + assert "LPS" in str(w[0].message) # Simulate a TRK file with an unsupported version. trk_struct, trk_bytes = self.trk_with_bytes() trk_struct['version'] = 123 - assert_raises(HeaderError, TrkFile.load, BytesIO(trk_bytes)) + with pytest.raises(HeaderError): + TrkFile.load(BytesIO(trk_bytes)) + # Simulate a TRK file with a wrong hdr_size. trk_struct, trk_bytes = self.trk_with_bytes() trk_struct['hdr_size'] = 1234 - assert_raises(HeaderError, TrkFile.load, BytesIO(trk_bytes)) + with pytest.raises(HeaderError): + TrkFile.load(BytesIO(trk_bytes)) # Simulate a TRK file with a wrong scalar_name. trk_struct, trk_bytes = self.trk_with_bytes('complex_trk_fname') trk_struct['scalar_name'][0, 0] = b'colors\x003\x004' - assert_raises(HeaderError, TrkFile.load, BytesIO(trk_bytes)) + with pytest.raises(HeaderError): + TrkFile.load(BytesIO(trk_bytes)) # Simulate a TRK file with a wrong property_name. trk_struct, trk_bytes = self.trk_with_bytes('complex_trk_fname') trk_struct['property_name'][0, 0] = b'colors\x003\x004' - assert_raises(HeaderError, TrkFile.load, BytesIO(trk_bytes)) + with pytest.raises(HeaderError): + TrkFile.load(BytesIO(trk_bytes)) def test_load_trk_version_1(self): # Simulate and test a TRK (version 1). @@ -184,9 +189,9 @@ def test_load_trk_version_1(self): trk_struct['version'] = 1 with clear_and_catch_warnings(record=True, modules=[trk_module]) as w: trk = TrkFile.load(BytesIO(trk_bytes)) - assert_equal(len(w), 1) - assert_true(issubclass(w[0].category, HeaderWarning)) - assert_true("identity" in str(w[0].message)) + assert len(w) == 1 + assert issubclass(w[0].category, HeaderWarning) + assert "identity" in str(w[0].message) assert_array_equal(trk.affine, np.eye(4)) assert_array_equal(trk.header['version'], 1) @@ -196,8 +201,8 @@ def test_load_complex_file_in_big_endian(self): # We use hdr_size as an indicator of little vs big endian. good_orders = '>' if sys.byteorder == 'little' else '>=' hdr_size = trk_struct['hdr_size'] - assert_true(hdr_size.dtype.byteorder in good_orders) - assert_equal(hdr_size, 1000) + assert hdr_size.dtype.byteorder in good_orders + assert hdr_size == 1000 for lazy_load in [False, True]: trk = TrkFile.load(DATA['complex_trk_big_endian_fname'], @@ -206,7 +211,7 @@ def test_load_complex_file_in_big_endian(self): def test_tractogram_file_properties(self): trk = TrkFile.load(DATA['simple_trk_fname']) - assert_equal(trk.streamlines, trk.tractogram.streamlines) + assert trk.streamlines == trk.tractogram.streamlines assert_array_equal(trk.affine, trk.header[Field.VOXEL_TO_RASMM]) def test_write_empty_file(self): @@ -224,8 +229,7 @@ def test_write_empty_file(self): assert_tractogram_equal(new_trk.tractogram, new_trk_orig.tractogram) trk_file.seek(0, os.SEEK_SET) - assert_equal(trk_file.read(), - open(DATA['empty_trk_fname'], 'rb').read()) + assert trk_file.read() == open(DATA['empty_trk_fname'], 'rb').read() def test_write_simple_file(self): tractogram = Tractogram(DATA['streamlines'], @@ -243,8 +247,7 @@ def test_write_simple_file(self): assert_tractogram_equal(new_trk.tractogram, new_trk_orig.tractogram) trk_file.seek(0, os.SEEK_SET) - assert_equal(trk_file.read(), - open(DATA['simple_trk_fname'], 'rb').read()) + assert trk_file.read() == open(DATA['simple_trk_fname'], 'rb').read() def test_write_complex_file(self): # With scalars @@ -293,8 +296,7 @@ def test_write_complex_file(self): assert_tractogram_equal(new_trk.tractogram, new_trk_orig.tractogram) trk_file.seek(0, os.SEEK_SET) - assert_equal(trk_file.read(), - open(DATA['complex_trk_fname'], 'rb').read()) + assert trk_file.read() == open(DATA['complex_trk_fname'], 'rb').read() def test_load_write_file(self): for fname in [DATA['empty_trk_fname'], @@ -329,8 +331,7 @@ def test_load_write_LPS_file(self): assert_tractogram_equal(new_trk.tractogram, new_trk_orig.tractogram) trk_file.seek(0, os.SEEK_SET) - assert_equal(trk_file.read(), - open(DATA['standard_LPS_trk_fname'], 'rb').read()) + assert trk_file.read() == open(DATA['standard_LPS_trk_fname'], 'rb').read() # Test writing a file where the header is missing the # Field.VOXEL_ORDER. @@ -353,8 +354,7 @@ def test_load_write_LPS_file(self): assert_tractogram_equal(new_trk.tractogram, new_trk_orig.tractogram) trk_file.seek(0, os.SEEK_SET) - assert_equal(trk_file.read(), - open(DATA['standard_LPS_trk_fname'], 'rb').read()) + assert trk_file.read() == open(DATA['standard_LPS_trk_fname'], 'rb').read() def test_write_optional_header_fields(self): # The TRK file format doesn't support additional header fields. @@ -368,7 +368,7 @@ def test_write_optional_header_fields(self): trk_file.seek(0, os.SEEK_SET) new_trk = TrkFile.load(trk_file) - assert_true("extra" not in new_trk.header) + assert "extra" not in new_trk.header def test_write_too_many_scalars_and_properties(self): # TRK supports up to 10 data_per_point. @@ -396,7 +396,8 @@ def test_write_too_many_scalars_and_properties(self): affine_to_rasmm=np.eye(4)) trk = TrkFile(tractogram) - assert_raises(ValueError, trk.save, BytesIO()) + with pytest.raises(ValueError): + trk.save(BytesIO()) # TRK supports up to 10 data_per_streamline. data_per_streamline = {} @@ -422,7 +423,8 @@ def test_write_too_many_scalars_and_properties(self): data_per_streamline=data_per_streamline) trk = TrkFile(tractogram) - assert_raises(ValueError, trk.save, BytesIO()) + with pytest.raises(ValueError): + trk.save(BytesIO()) def test_write_scalars_and_properties_name_too_long(self): # TRK supports data_per_point name up to 20 characters. @@ -438,7 +440,8 @@ def test_write_scalars_and_properties_name_too_long(self): trk = TrkFile(tractogram) if nb_chars > 18: - assert_raises(ValueError, trk.save, BytesIO()) + with pytest.raises(ValueError): + trk.save(BytesIO()) else: trk.save(BytesIO()) @@ -449,7 +452,8 @@ def test_write_scalars_and_properties_name_too_long(self): trk = TrkFile(tractogram) if nb_chars > 20: - assert_raises(ValueError, trk.save, BytesIO()) + with pytest.raises(ValueError): + trk.save(BytesIO()) else: trk.save(BytesIO()) @@ -466,7 +470,8 @@ def test_write_scalars_and_properties_name_too_long(self): trk = TrkFile(tractogram) if nb_chars > 18: - assert_raises(ValueError, trk.save, BytesIO()) + with pytest.raises(ValueError): + trk.save(BytesIO()) else: trk.save(BytesIO()) @@ -477,7 +482,8 @@ def test_write_scalars_and_properties_name_too_long(self): trk = TrkFile(tractogram) if nb_chars > 20: - assert_raises(ValueError, trk.save, BytesIO()) + with pytest.raises(ValueError): + trk.save(BytesIO()) else: trk.save(BytesIO()) @@ -499,32 +505,37 @@ def test_header_read_restore(self): hdr_from_fname['_offset_data'] += hdr_pos # Correct for start position assert_arr_dict_equal(TrkFile._read_header(bio), hdr_from_fname) # Check fileobject file position has not changed - assert_equal(bio.tell(), hdr_pos) + assert bio.tell() == hdr_pos def test_encode_names(): # Test function for encoding numbers into property names b0 = b'\x00' - assert_equal(encode_value_in_name(0, 'foo', 10), - b'foo' + b0 * 7) - assert_equal(encode_value_in_name(1, 'foo', 10), - b'foo' + b0 * 7) - assert_equal(encode_value_in_name(8, 'foo', 10), - b'foo' + b0 + b'8' + b0 * 5) - assert_equal(encode_value_in_name(40, 'foobar', 10), - b'foobar' + b0 + b'40' + b0) - assert_equal(encode_value_in_name(1, 'foobarbazz', 10), b'foobarbazz') - assert_raises(ValueError, encode_value_in_name, 1, 'foobarbazzz', 10) - assert_raises(ValueError, encode_value_in_name, 2, 'foobarbaz', 10) - assert_equal(encode_value_in_name(2, 'foobarba', 10), b'foobarba\x002') + assert encode_value_in_name(0, 'foo', 10) == b'foo' + b0 * 7 + assert encode_value_in_name(1, 'foo', 10) == b'foo' + b0 * 7 + assert encode_value_in_name(8, 'foo', 10) == b'foo' + b0 + b'8' + b0 * 5 + assert encode_value_in_name(40, 'foobar', 10) == b'foobar' + b0 + b'40' + b0 + assert encode_value_in_name(1, 'foobarbazz', 10) == b'foobarbazz' + + with pytest.raises(ValueError): + encode_value_in_name(1, 'foobarbazzz', 10) + + with pytest.raises(ValueError): + encode_value_in_name(2, 'foobarbazzz', 10) + + assert encode_value_in_name(2, 'foobarba', 10) == b'foobarba\x002' def test_decode_names(): # Test function for decoding name string into name, number b0 = b'\x00' - assert_equal(decode_value_from_name(b''), ('', 0)) - assert_equal(decode_value_from_name(b'foo' + b0 * 7), ('foo', 1)) - assert_equal(decode_value_from_name(b'foo\x008' + b0 * 5), ('foo', 8)) - assert_equal(decode_value_from_name(b'foobar\x0010\x00'), ('foobar', 10)) - assert_raises(ValueError, decode_value_from_name, b'foobar\x0010\x01') - assert_raises(HeaderError, decode_value_from_name, b'foo\x0010\x00111') + assert decode_value_from_name(b'') == ('', 0) + assert decode_value_from_name(b'foo' + b0 * 7) == ('foo', 1) + assert decode_value_from_name(b'foo\x008' + b0 * 5) == ('foo', 8) + assert decode_value_from_name(b'foobar\x0010\x00') == ('foobar', 10) + + with pytest.raises(ValueError): + decode_value_from_name(b'foobar\x0010\x01') + + with pytest.raises(HeaderError): + decode_value_from_name(b'foo\x0010\x00111') From 3a2b0d10629146fc73e1729765caf526e244dd5b Mon Sep 17 00:00:00 2001 From: robbisg Date: Tue, 4 Feb 2020 21:55:56 +0200 Subject: [PATCH 061/223] TEST: test_tck to pytest --- nibabel/streamlines/tests/test_tck.py | 58 ++++++++++++++------------- 1 file changed, 31 insertions(+), 27 deletions(-) diff --git a/nibabel/streamlines/tests/test_tck.py b/nibabel/streamlines/tests/test_tck.py index 573bed02d3..fb29776f75 100644 --- a/nibabel/streamlines/tests/test_tck.py +++ b/nibabel/streamlines/tests/test_tck.py @@ -14,17 +14,15 @@ from .. import tck as tck_module from ..tck import TckFile -import pytest; pytestmark = pytest.mark.skip() - -from nose.tools import assert_equal, assert_raises, assert_true +import pytest from numpy.testing import assert_array_equal -from nibabel.testing import data_path, clear_and_catch_warnings +from ...testing_pytest import data_path, clear_and_catch_warnings from .test_tractogram import assert_tractogram_equal DATA = {} -def setup(): +def setup_module(): global DATA DATA['empty_tck_fname'] = pjoin(data_path, "empty.tck") @@ -71,8 +69,8 @@ def test_load_matlab_nan_file(self): for lazy_load in [False, True]: tck = TckFile.load(DATA['matlab_nan_tck_fname'], lazy_load=lazy_load) streamlines = list(tck.tractogram.streamlines) - assert_equal(len(streamlines), 1) - assert_equal(streamlines[0].shape, (108, 3)) + assert len(streamlines) == 1 + assert streamlines[0].shape == (108, 3) def test_writeable_data(self): data = DATA['simple_tractogram'] @@ -82,7 +80,7 @@ def test_writeable_data(self): for actual, expected_tgi in zip(tck.streamlines, data): assert_array_equal(actual, expected_tgi.streamline) # Test we can write to arrays - assert_true(actual.flags.writeable) + assert actual.flags.writeable actual[0, 0] = 99 def test_load_simple_file_in_big_endian(self): @@ -90,7 +88,7 @@ def test_load_simple_file_in_big_endian(self): tck = TckFile.load(DATA['simple_tck_big_endian_fname'], lazy_load=lazy_load) assert_tractogram_equal(tck.tractogram, DATA['simple_tractogram']) - assert_equal(tck.header['datatype'], 'Float32BE') + assert tck.header['datatype'] == 'Float32BE' def test_load_file_with_wrong_information(self): tck_file = open(DATA['simple_tck_fname'], 'rb').read() @@ -98,12 +96,15 @@ def test_load_file_with_wrong_information(self): # Simulate a TCK file where `datatype` has not the right endianness. new_tck_file = tck_file.replace(asbytes("Float32LE"), asbytes("Float32BE")) - assert_raises(DataError, TckFile.load, BytesIO(new_tck_file)) + + with pytest.raises(DataError): + TckFile.load(BytesIO(new_tck_file)) # Simulate a TCK file with unsupported `datatype`. new_tck_file = tck_file.replace(asbytes("Float32LE"), asbytes("int32")) - assert_raises(HeaderError, TckFile.load, BytesIO(new_tck_file)) + with pytest.raises(HeaderError): + TckFile.load(BytesIO(new_tck_file)) # Simulate a TCK file with no `datatype` field. new_tck_file = tck_file.replace(b"datatype: Float32LE\n", b"") @@ -111,24 +112,25 @@ def test_load_file_with_wrong_information(self): new_tck_file = new_tck_file.replace(b"file: . 67\n", b"file: . 47\n") with clear_and_catch_warnings(record=True, modules=[tck_module]) as w: tck = TckFile.load(BytesIO(new_tck_file)) - assert_equal(len(w), 1) - assert_true(issubclass(w[0].category, HeaderWarning)) - assert_true("Missing 'datatype'" in str(w[0].message)) + assert len(w) == 1 + assert issubclass(w[0].category, HeaderWarning) + assert "Missing 'datatype'" in str(w[0].message) assert_array_equal(tck.header['datatype'], "Float32LE") # Simulate a TCK file with no `file` field. new_tck_file = tck_file.replace(b"\nfile: . 67", b"") with clear_and_catch_warnings(record=True, modules=[tck_module]) as w: tck = TckFile.load(BytesIO(new_tck_file)) - assert_equal(len(w), 1) - assert_true(issubclass(w[0].category, HeaderWarning)) - assert_true("Missing 'file'" in str(w[0].message)) + assert len(w) == 1 + assert issubclass(w[0].category, HeaderWarning) + assert "Missing 'file'" in str(w[0].message) assert_array_equal(tck.header['file'], ". 56") # Simulate a TCK file with `file` field pointing to another file. new_tck_file = tck_file.replace(b"file: . 67\n", b"file: dummy.mat 75\n") - assert_raises(HeaderError, TckFile.load, BytesIO(new_tck_file)) + with pytest.raises(HeaderError): + TckFile.load(BytesIO(new_tck_file)) # Simulate a TCK file which is missing a streamline delimiter. eos = TckFile.FIBER_DELIMITER.tostring() @@ -139,11 +141,13 @@ def test_load_file_with_wrong_information(self): buffer_size = 1. / 1024**2 # 1 bytes hdr = TckFile._read_header(BytesIO(new_tck_file)) tck_reader = TckFile._read(BytesIO(new_tck_file), hdr, buffer_size) - assert_raises(DataError, list, tck_reader) + with pytest.raises(DataError): + list(tck_reader) # Simulate a TCK file which is missing the end-of-file delimiter. new_tck_file = tck_file[:-len(eof)] - assert_raises(DataError, TckFile.load, BytesIO(new_tck_file)) + with pytest.raises(DataError): + TckFile.load(BytesIO(new_tck_file)) def test_write_empty_file(self): tractogram = Tractogram(affine_to_rasmm=np.eye(4)) @@ -160,8 +164,7 @@ def test_write_empty_file(self): assert_tractogram_equal(new_tck.tractogram, new_tck_orig.tractogram) tck_file.seek(0, os.SEEK_SET) - assert_equal(tck_file.read(), - open(DATA['empty_tck_fname'], 'rb').read()) + assert tck_file.read() == open(DATA['empty_tck_fname'], 'rb').read() def test_write_simple_file(self): tractogram = Tractogram(DATA['streamlines'], @@ -179,17 +182,18 @@ def test_write_simple_file(self): assert_tractogram_equal(new_tck.tractogram, new_tck_orig.tractogram) tck_file.seek(0, os.SEEK_SET) - assert_equal(tck_file.read(), - open(DATA['simple_tck_fname'], 'rb').read()) + assert tck_file.read() == open(DATA['simple_tck_fname'], 'rb').read() # TCK file containing not well formatted entries in its header. tck_file = BytesIO() tck = TckFile(tractogram) tck.header['new_entry'] = 'value\n' # \n not allowed - assert_raises(HeaderError, tck.save, tck_file) + with pytest.raises(HeaderError): + tck.save(tck_file) tck.header['new_entry'] = 'val:ue' # : not allowed - assert_raises(HeaderError, tck.save, tck_file) + with pytest.raises(HeaderError): + tck.save(tck_file) def test_load_write_file(self): for fname in [DATA['empty_tck_fname'], @@ -204,7 +208,7 @@ def test_load_write_file(self): # Check that the written file is the same as the one read. tck_file.seek(0, os.SEEK_SET) - assert_equal(tck_file.read(), open(fname, 'rb').read()) + assert tck_file.read() == open(fname, 'rb').read() # Save tractogram that has an affine_to_rasmm. for lazy_load in [False, True]: From d79af8b9a800204731339c6314268aa005f978ea Mon Sep 17 00:00:00 2001 From: Anibal Solon Date: Tue, 4 Feb 2020 15:26:13 -0500 Subject: [PATCH 062/223] pytest port --- nibabel/gifti/tests/test_gifti.py | 187 +++++++++++++++--------------- 1 file changed, 93 insertions(+), 94 deletions(-) diff --git a/nibabel/gifti/tests/test_gifti.py b/nibabel/gifti/tests/test_gifti.py index 167e56d6cf..8a0b3d327d 100644 --- a/nibabel/gifti/tests/test_gifti.py +++ b/nibabel/gifti/tests/test_gifti.py @@ -16,7 +16,7 @@ from numpy.testing import (assert_array_almost_equal, assert_array_equal) -from nose.tools import (assert_true, assert_false, assert_equal, assert_raises) +import pytest from nibabel.testing import clear_and_catch_warnings, test_data from .test_parse_gifti_fast import (DATA_FILE1, DATA_FILE2, DATA_FILE3, DATA_FILE4, DATA_FILE5, DATA_FILE6) @@ -35,7 +35,7 @@ def test_agg_data(): func_data = np.column_stack(tuple(da.data for da in func_da)) shape_data = shape_gii_img.get_arrays_from_intent('shape')[0].data - assert_equal(surf_gii_img.agg_data(), (point_data, triangle_data)) + assert surf_gii_img.agg_data() == (point_data, triangle_data) assert_array_equal(func_gii_img.agg_data(), func_data) assert_array_equal(shape_gii_img.agg_data(), shape_data) @@ -44,45 +44,45 @@ def test_agg_data(): assert_array_equal(func_gii_img.agg_data('time series'), func_data) assert_array_equal(shape_gii_img.agg_data('shape'), shape_data) - assert_equal(surf_gii_img.agg_data('time series'), ()) - assert_equal(func_gii_img.agg_data('triangle'), ()) - assert_equal(shape_gii_img.agg_data('pointset'), ()) + assert surf_gii_img.agg_data('time series') == () + assert func_gii_img.agg_data('triangle') == () + assert shape_gii_img.agg_data('pointset') == () - assert_equal(surf_gii_img.agg_data(('pointset', 'triangle')), (point_data, triangle_data)) - assert_equal(surf_gii_img.agg_data(('triangle', 'pointset')), (triangle_data, point_data)) + assert surf_gii_img.agg_data(('pointset', 'triangle')) == (point_data, triangle_data) + assert surf_gii_img.agg_data(('triangle', 'pointset')) == (triangle_data, point_data) def test_gifti_image(): # Check that we're not modifying the default empty list in the default # arguments. gi = GiftiImage() - assert_equal(gi.darrays, []) - assert_equal(gi.meta.metadata, {}) - assert_equal(gi.labeltable.labels, []) + assert gi.darrays == [] + assert gi.meta.metadata == {} + assert gi.labeltable.labels == [] arr = np.zeros((2, 3)) gi.darrays.append(arr) # Now check we didn't overwrite the default arg gi = GiftiImage() - assert_equal(gi.darrays, []) + assert gi.darrays == [] # Test darrays / numDA gi = GiftiImage() - assert_equal(gi.numDA, 0) + assert gi.numDA == 0 # Test from numpy numeric array data = np.random.random((5,)) da = GiftiDataArray(data) gi.add_gifti_data_array(da) - assert_equal(gi.numDA, 1) + assert gi.numDA == 1 assert_array_equal(gi.darrays[0].data, data) # Test removing gi.remove_gifti_data_array(0) - assert_equal(gi.numDA, 0) + assert gi.numDA == 0 # Remove from empty gi = GiftiImage() gi.remove_gifti_data_array_by_intent(0) - assert_equal(gi.numDA, 0) + assert gi.numDA == 0 # Remove one gi = GiftiImage() @@ -90,113 +90,112 @@ def test_gifti_image(): gi.add_gifti_data_array(da) gi.remove_gifti_data_array_by_intent(3) - assert_equal(gi.numDA, 1, "data array should exist on 'missed' remove") + assert gi.numDA == 1, "data array should exist on 'missed' remove" gi.remove_gifti_data_array_by_intent(da.intent) - assert_equal(gi.numDA, 0) + assert gi.numDA == 0 def test_gifti_image_bad_inputs(): img = GiftiImage() # Try to set a non-data-array - assert_raises(TypeError, img.add_gifti_data_array, 'not-a-data-array') + pytest.raises(TypeError, img.add_gifti_data_array, 'not-a-data-array') # Try to set to non-table def assign_labeltable(val): img.labeltable = val - assert_raises(TypeError, assign_labeltable, 'not-a-table') + pytest.raises(TypeError, assign_labeltable, 'not-a-table') # Try to set to non-table def assign_metadata(val): img.meta = val - assert_raises(TypeError, assign_metadata, 'not-a-meta') + pytest.raises(TypeError, assign_metadata, 'not-a-meta') def test_dataarray_empty(): # Test default initialization of DataArray null_da = GiftiDataArray() - assert_equal(null_da.data, None) - assert_equal(null_da.intent, 0) - assert_equal(null_da.datatype, 0) - assert_equal(null_da.encoding, 3) - assert_equal(null_da.endian, 2 if sys.byteorder == 'little' else 1) - assert_equal(null_da.coordsys.dataspace, 0) - assert_equal(null_da.coordsys.xformspace, 0) + assert null_da.data is None + assert null_da.intent == 0 + assert null_da.datatype == 0 + assert null_da.encoding == 3 + assert null_da.endian == (2 if sys.byteorder == 'little' else 1) + assert null_da.coordsys.dataspace == 0 + assert null_da.coordsys.xformspace == 0 assert_array_equal(null_da.coordsys.xform, np.eye(4)) - assert_equal(null_da.ind_ord, 1) - assert_equal(null_da.meta.metadata, {}) - assert_equal(null_da.ext_fname, '') - assert_equal(null_da.ext_offset, 0) + assert null_da.ind_ord == 1 + assert null_da.meta.metadata == {} + assert null_da.ext_fname == '' + assert null_da.ext_offset == 0 def test_dataarray_init(): # Test non-default dataarray initialization gda = GiftiDataArray # shortcut - assert_equal(gda(None).data, None) + assert gda(None).data is None arr = np.arange(12, dtype=np.float32).reshape((3, 4)) assert_array_equal(gda(arr).data, arr) # Intents - assert_raises(KeyError, gda, intent=1) # Invalid code - assert_raises(KeyError, gda, intent='not an intent') # Invalid string - assert_equal(gda(intent=2).intent, 2) - assert_equal(gda(intent='correlation').intent, 2) - assert_equal(gda(intent='NIFTI_INTENT_CORREL').intent, 2) + pytest.raises(KeyError, gda, intent=1) # Invalid code + pytest.raises(KeyError, gda, intent='not an intent') # Invalid string + assert gda(intent=2).intent == 2 + assert gda(intent='correlation').intent == 2 + assert gda(intent='NIFTI_INTENT_CORREL').intent == 2 # Datatype - assert_equal(gda(datatype=2).datatype, 2) - assert_equal(gda(datatype='uint8').datatype, 2) - assert_raises(KeyError, gda, datatype='not_datatype') + assert gda(datatype=2).datatype == 2 + assert gda(datatype='uint8').datatype == 2 + pytest.raises(KeyError, gda, datatype='not_datatype') # Float32 datatype comes from array if datatype not set - assert_equal(gda(arr).datatype, 16) + assert gda(arr).datatype == 16 # Can be overriden by init - assert_equal(gda(arr, datatype='uint8').datatype, 2) + assert gda(arr, datatype='uint8').datatype == 2 # Encoding - assert_equal(gda(encoding=1).encoding, 1) - assert_equal(gda(encoding='ASCII').encoding, 1) - assert_equal(gda(encoding='GIFTI_ENCODING_ASCII').encoding, 1) - assert_raises(KeyError, gda, encoding='not an encoding') + assert gda(encoding=1).encoding == 1 + assert gda(encoding='ASCII').encoding == 1 + assert gda(encoding='GIFTI_ENCODING_ASCII').encoding == 1 + pytest.raises(KeyError, gda, encoding='not an encoding') # Endian - assert_equal(gda(endian=1).endian, 1) - assert_equal(gda(endian='big').endian, 1) - assert_equal(gda(endian='GIFTI_ENDIAN_BIG').endian, 1) - assert_raises(KeyError, gda, endian='not endian code') + assert gda(endian=1).endian == 1 + assert gda(endian='big').endian == 1 + assert gda(endian='GIFTI_ENDIAN_BIG').endian == 1 + pytest.raises(KeyError, gda, endian='not endian code') # CoordSys aff = np.diag([2, 3, 4, 1]) cs = GiftiCoordSystem(1, 2, aff) da = gda(coordsys=cs) - assert_equal(da.coordsys.dataspace, 1) - assert_equal(da.coordsys.xformspace, 2) + assert da.coordsys.dataspace == 1 + assert da.coordsys.xformspace == 2 assert_array_equal(da.coordsys.xform, aff) # Ordering - assert_equal(gda(ordering=2).ind_ord, 2) - assert_equal(gda(ordering='F').ind_ord, 2) - assert_equal(gda(ordering='ColumnMajorOrder').ind_ord, 2) - assert_raises(KeyError, gda, ordering='not an ordering') + assert gda(ordering=2).ind_ord == 2 + assert gda(ordering='F').ind_ord == 2 + assert gda(ordering='ColumnMajorOrder').ind_ord == 2 + pytest.raises(KeyError, gda, ordering='not an ordering') # metadata meta_dict=dict(one=1, two=2) - assert_equal(gda(meta=GiftiMetaData.from_dict(meta_dict)).meta.metadata, - meta_dict) - assert_equal(gda(meta=meta_dict).meta.metadata, meta_dict) - assert_equal(gda(meta=None).meta.metadata, {}) + assert gda(meta=GiftiMetaData.from_dict(meta_dict)).meta.metadata == meta_dict + assert gda(meta=meta_dict).meta.metadata == meta_dict + assert gda(meta=None).meta.metadata == {} # ext_fname and ext_offset - assert_equal(gda(ext_fname='foo').ext_fname, 'foo') - assert_equal(gda(ext_offset=12).ext_offset, 12) + assert gda(ext_fname='foo').ext_fname == 'foo' + assert gda(ext_offset=12).ext_offset == 12 def test_dataarray_from_array(): with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) da = GiftiDataArray.from_array(np.ones((3, 4))) - assert_equal(len(w), 1) + assert len(w) == 1 for dt_code in data_type_codes.value_set(): data_type = data_type_codes.type[dt_code] if data_type is np.void: # not supported continue arr = np.zeros((10, 3), dtype=data_type) da = GiftiDataArray.from_array(arr, 'triangle') - assert_equal(da.datatype, data_type_codes[arr.dtype]) + assert da.datatype == data_type_codes[arr.dtype] bs_arr = arr.byteswap().newbyteorder() da = GiftiDataArray.from_array(bs_arr, 'triangle') - assert_equal(da.datatype, data_type_codes[arr.dtype]) + assert da.datatype == data_type_codes[arr.dtype] def test_to_xml_open_close_deprecations(): @@ -204,35 +203,35 @@ def test_to_xml_open_close_deprecations(): da = GiftiDataArray(np.ones((1,)), 'triangle') with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) - assert_true(isinstance(da.to_xml_open(), str)) - assert_equal(len(w), 1) + assert isinstance(da.to_xml_open(), str) + assert len(w) == 1 with clear_and_catch_warnings() as w: warnings.filterwarnings('once', category=DeprecationWarning) - assert_true(isinstance(da.to_xml_close(), str)) - assert_equal(len(w), 1) + assert isinstance(da.to_xml_close(), str) + assert len(w) == 1 def test_num_dim_deprecation(): da = GiftiDataArray(np.ones((2, 3, 4))) # num_dim is property, set automatically from len(da.dims) - assert_equal(da.num_dim, 3) + assert da.num_dim == 3 with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) # OK setting num_dim to correct value, but raises DeprecationWarning da.num_dim = 3 - assert_equal(len(w), 1) + assert len(w) == 1 # Any other value gives a ValueError - assert_raises(ValueError, setattr, da, 'num_dim', 4) + pytest.raises(ValueError, setattr, da, 'num_dim', 4) def test_labeltable(): img = GiftiImage() - assert_equal(len(img.labeltable.labels), 0) + assert len(img.labeltable.labels) == 0 new_table = GiftiLabelTable() new_table.labels += ['test', 'me'] img.labeltable = new_table - assert_equal(len(img.labeltable.labels), 2) + assert len(img.labeltable.labels) == 2 # Test deprecations with clear_and_catch_warnings() as w: @@ -240,23 +239,23 @@ def test_labeltable(): newer_table = GiftiLabelTable() newer_table.labels += ['test', 'me', 'again'] img.set_labeltable(newer_table) - assert_equal(len(w), 1) - assert_equal(len(img.get_labeltable().labels), 3) - assert_equal(len(w), 2) + assert len(w) == 1 + assert len(img.get_labeltable().labels) == 3 + assert len(w) == 2 def test_metadata(): nvpair = GiftiNVPairs('key', 'value') md = GiftiMetaData(nvpair=nvpair) - assert_equal(md.data[0].name, 'key') - assert_equal(md.data[0].value, 'value') + assert md.data[0].name == 'key' + assert md.data[0].value == 'value' # Test deprecation with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) - assert_equal(md.get_metadata(), dict(key='value')) - assert_equal(len(w), 1) - assert_equal(len(GiftiDataArray().get_metadata()), 0) - assert_equal(len(w), 2) + assert md.get_metadata() == dict(key='value') + assert len(w) == 1 + assert len(GiftiDataArray().get_metadata()) == 0 + assert len(w) == 2 def test_gifti_label_rgba(): @@ -267,31 +266,31 @@ def test_gifti_label_rgba(): assert_array_equal(rgba, gl1.rgba) gl1.red = 2 * gl1.red - assert_false(np.allclose(rgba, gl1.rgba)) # don't just store the list! + assert not np.allclose(rgba, gl1.rgba) # don't just store the list! gl2 = GiftiLabel() gl2.rgba = rgba assert_array_equal(rgba, gl2.rgba) gl2.blue = 2 * gl2.blue - assert_false(np.allclose(rgba, gl2.rgba)) # don't just store the list! + assert not np.allclose(rgba, gl2.rgba) # don't just store the list! def assign_rgba(gl, val): gl.rgba = val gl3 = GiftiLabel(**kwargs) - assert_raises(ValueError, assign_rgba, gl3, rgba[:2]) - assert_raises(ValueError, assign_rgba, gl3, rgba.tolist() + rgba.tolist()) + pytest.raises(ValueError, assign_rgba, gl3, rgba[:2]) + pytest.raises(ValueError, assign_rgba, gl3, rgba.tolist() + rgba.tolist()) # Test deprecation with clear_and_catch_warnings() as w: warnings.filterwarnings('once', category=DeprecationWarning) - assert_equal(kwargs['red'], gl3.get_rgba()[0]) - assert_equal(len(w), 1) + assert kwargs['red'] == gl3.get_rgba()[0] + assert len(w) == 1 # Test default value gl4 = GiftiLabel() - assert_equal(len(gl4.rgba), 4) - assert_true(np.all([elem is None for elem in gl4.rgba])) + assert len(gl4.rgba) == 4 + assert np.all([elem is None for elem in gl4.rgba]) def test_print_summary(): @@ -304,7 +303,7 @@ def test_print_summary(): def test_gifti_coord(): from ..gifti import GiftiCoordSystem gcs = GiftiCoordSystem() - assert_true(gcs.xform is not None) + assert gcs.xform is not None # Smoke test gcs.xform = None @@ -316,7 +315,7 @@ def test_data_tag_deprecated(): with clear_and_catch_warnings() as w: warnings.filterwarnings('once', category=DeprecationWarning) data_tag(np.array([]), 'ASCII', '%i', 1) - assert_equal(len(w), 1) + assert len(w) == 1 def test_gifti_round_trip(): @@ -443,5 +442,5 @@ def test_darray_dtype_coercion_failures(): gii = GiftiImage(darrays=[da]) gii_copy = GiftiImage.from_bytes(gii.to_bytes()) da_copy = gii_copy.darrays[0] - assert_equal(np.dtype(da_copy.data.dtype), np.dtype(darray_dtype)) + assert np.dtype(da_copy.data.dtype) == np.dtype(darray_dtype) assert_array_equal(da_copy.data, da.data) From 5695644074d5b754782350e844a15ff900db37e5 Mon Sep 17 00:00:00 2001 From: Anibal Solon Date: Tue, 4 Feb 2020 13:25:18 -0500 Subject: [PATCH 063/223] drop the nose --- .azure-pipelines/windows.yml | 12 ++++-------- azure-pipelines.yml | 4 ---- dev-requirements.txt | 1 + 3 files changed, 5 insertions(+), 12 deletions(-) diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index 469fd27c96..34b2aaf96f 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -11,7 +11,7 @@ jobs: variables: EXTRA_WHEELS: "https://5cf40426d9f06eb7461d-6fe47d9331aba7cd62fc36c7196769e4.ssl.cf2.rackcdn.com" DEPENDS: numpy scipy matplotlib h5py pydicom - CHECK_TYPE: nosetests + CHECK_TYPE: test strategy: matrix: ${{ insert }}: ${{ parameters.matrix }} @@ -30,7 +30,7 @@ jobs: displayName: 'Update build tools' - script: | python -m pip install --find-links %EXTRA_WHEELS% %DEPENDS% - python -m pip install nose coverage codecov pytest + python -m pip install coverage codecov pytest displayName: 'Install dependencies' - script: | python -m pip install .[$(CHECK_TYPE)] @@ -40,12 +40,8 @@ jobs: mkdir for_testing cd for_testing cp ../.coveragerc . - if $(CHECK_TYPE)=="nosetests" ( - nosetests --with-doctest --with-coverage --cover-package nibabel nibabel - ) else ( - pytest --cov nibabel -v --pyargs nibabel --deselect streamlines - ) - displayName: 'Nose tests' + pytest --cov nibabel -v --pyargs nibabel --deselect streamlines + displayName: 'Run tests' - script: | cd for_testing codecov diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 5bbd37986c..d09c5b7740 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -34,7 +34,3 @@ jobs: py38-x64: PYTHON_VERSION: '3.8' PYTHON_ARCH: 'x64' - pytest: - PYTHON_VERSION: '3.6' - PYTHON_ARCH: 'x64' - CHECK_TYPE: 'test' diff --git a/dev-requirements.txt b/dev-requirements.txt index 659ab6cada..aa0980c3b4 100644 --- a/dev-requirements.txt +++ b/dev-requirements.txt @@ -1,3 +1,4 @@ # Requirements for running tests -r requirements.txt nose +pytest From 636dc5599b40f52a27775e5b72af47b8aaf196b8 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 4 Feb 2020 15:31:52 -0500 Subject: [PATCH 064/223] CI: Give up trying to deselect streamlines --- .azure-pipelines/windows.yml | 2 +- .travis.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index 34b2aaf96f..cf9b82a1c0 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -40,7 +40,7 @@ jobs: mkdir for_testing cd for_testing cp ../.coveragerc . - pytest --cov nibabel -v --pyargs nibabel --deselect streamlines + pytest --cov nibabel -v --pyargs nibabel displayName: 'Run tests' - script: | cd for_testing diff --git a/.travis.yml b/.travis.yml index b6ef1a18a0..f8333d39a7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -196,7 +196,7 @@ script: mkdir for_testing cd for_testing cp ../.coveragerc . - pytest --cov nibabel -v --pyargs nibabel --deselect streamlines + pytest --cov nibabel -v --pyargs nibabel else false fi From 85ac45260270bd0c45c2c3bc91281e4e237990f9 Mon Sep 17 00:00:00 2001 From: orduek Date: Tue, 4 Feb 2020 15:35:14 -0500 Subject: [PATCH 065/223] changed nosetools assert_true to assert in test_io.py --- nibabel/freesurfer/tests/test_io.py | 35 +++++++++++++++-------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index fc926ee2af..41bcdd17cf 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -9,7 +9,8 @@ from ...tmpdirs import InTemporaryDirectory -from nose.tools import assert_true + +import pytest import numpy as np from numpy.testing import assert_equal, assert_raises, dec, assert_allclose, assert_array_equal @@ -92,13 +93,13 @@ def test_geometry(): with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) read_geometry(surf_path, read_metadata=True) - assert_true(any('volume information contained' in str(ww.message) + assert(any('volume information contained' in str(ww.message) for ww in w)) - assert_true(any('extension code' in str(ww.message) for ww in w)) + assert(any('extension code' in str(ww.message) for ww in w)) volume_info['head'] = [1, 2] with clear_and_catch_warnings() as w: write_geometry(surf_path, coords, faces, create_stamp, volume_info) - assert_true(any('Unknown extension' in str(ww.message) for ww in w)) + assert(any('Unknown extension' in str(ww.message) for ww in w)) volume_info['a'] = 0 assert_raises(ValueError, write_geometry, surf_path, coords, faces, create_stamp, volume_info) @@ -137,8 +138,8 @@ def test_morph_data(): """Test IO of morphometry data file (eg. curvature).""" curv_path = pjoin(data_path, "surf", "%s.%s" % ("lh", "curv")) curv = read_morph_data(curv_path) - assert_true(-1.0 < curv.min() < 0) - assert_true(0 < curv.max() < 1.0) + assert(-1.0 < curv.min() < 0) + assert(0 < curv.max() < 1.0) with InTemporaryDirectory(): new_path = 'test' write_morph_data(new_path, curv) @@ -177,8 +178,8 @@ def test_annot(): hash_ = _hash_file_content(annot_path) labels, ctab, names = read_annot(annot_path) - assert_true(labels.shape == (163842, )) - assert_true(ctab.shape == (len(names), 5)) + assert(labels.shape == (163842, )) + assert(ctab.shape == (len(names), 5)) labels_orig = None if a == 'aparc': @@ -186,9 +187,9 @@ def test_annot(): np.testing.assert_array_equal(labels == -1, labels_orig == 0) # Handle different version of fsaverage if hash_ == 'bf0b488994657435cdddac5f107d21e8': - assert_true(np.sum(labels_orig == 0) == 13887) + assert(np.sum(labels_orig == 0) == 13887) elif hash_ == 'd4f5b7cbc2ed363ac6fcf89e19353504': - assert_true(np.sum(labels_orig == 1639705) == 13327) + assert(np.sum(labels_orig == 1639705) == 13327) else: raise RuntimeError("Unknown freesurfer file. Please report " "the problem to the maintainer of nibabel.") @@ -272,7 +273,7 @@ def test_write_annot_fill_ctab(): print(labels) with clear_and_catch_warnings() as w: write_annot(annot_path, labels, rgbal, names, fill_ctab=False) - assert_true( + assert( any('Annotation values in {} will be incorrect'.format( annot_path) == str(ww.message) for ww in w)) labels2, rgbal2, names2 = read_annot(annot_path, orig_ids=True) @@ -288,7 +289,7 @@ def test_write_annot_fill_ctab(): rgbal[:, 2] * (2 ** 16)) with clear_and_catch_warnings() as w: write_annot(annot_path, labels, rgbal, names, fill_ctab=False) - assert_true( + assert( not any('Annotation values in {} will be incorrect'.format( annot_path) == str(ww.message) for ww in w)) labels2, rgbal2, names2 = read_annot(annot_path) @@ -348,13 +349,13 @@ def test_label(): label_path = pjoin(data_path, "label", "lh.cortex.label") label = read_label(label_path) # XXX : test more - assert_true(label.min() >= 0) - assert_true(label.max() <= 163841) - assert_true(label.shape[0] <= 163842) + assert(label.min() >= 0) + assert(label.max() <= 163841) + assert(label.shape[0] <= 163842) labels, scalars = read_label(label_path, True) - assert_true(np.all(labels == label)) - assert_true(len(labels) == len(scalars)) + assert(np.all(labels == label)) + assert(len(labels) == len(scalars)) def test_write_annot_maxstruct(): From 62d53c3712fe3a268849d4cc5f2feae1a02fd52c Mon Sep 17 00:00:00 2001 From: Anibal Solon Date: Tue, 4 Feb 2020 15:35:28 -0500 Subject: [PATCH 066/223] finish porting gifti module tests to pytest --- nibabel/gifti/tests/test_giftiio.py | 8 +- nibabel/gifti/tests/test_parse_gifti_fast.py | 115 +++++++++---------- 2 files changed, 60 insertions(+), 63 deletions(-) diff --git a/nibabel/gifti/tests/test_giftiio.py b/nibabel/gifti/tests/test_giftiio.py index 90fe3e4d37..87d28b00c4 100644 --- a/nibabel/gifti/tests/test_giftiio.py +++ b/nibabel/gifti/tests/test_giftiio.py @@ -9,8 +9,6 @@ import warnings -from nose.tools import (assert_true, assert_false, assert_equal, - assert_raises) from nibabel.testing import clear_and_catch_warnings from nibabel.tmpdirs import InTemporaryDirectory @@ -24,7 +22,7 @@ class TestGiftiIO(object): def setUp(self): with clear_and_catch_warnings() as w: warnings.simplefilter('always', DeprecationWarning) - assert_equal(len(w), 1) + assert len(w) == 1 def test_read_deprecated(): @@ -33,7 +31,7 @@ def test_read_deprecated(): from nibabel.gifti.giftiio import read, write img = read(DATA_FILE1) - assert_equal(len(w), 1) + assert len(w) == 1 with InTemporaryDirectory(): write(img, 'test.gii') - assert_equal(len(w), 2) + assert len(w) == 2 diff --git a/nibabel/gifti/tests/test_parse_gifti_fast.py b/nibabel/gifti/tests/test_parse_gifti_fast.py index a06180a964..15a2c69f1c 100644 --- a/nibabel/gifti/tests/test_parse_gifti_fast.py +++ b/nibabel/gifti/tests/test_parse_gifti_fast.py @@ -22,8 +22,7 @@ from numpy.testing import assert_array_almost_equal -from nose.tools import (assert_true, assert_false, assert_equal, - assert_raises) +import pytest from ...testing import clear_and_catch_warnings @@ -106,9 +105,9 @@ def assert_default_types(loaded): if defaulttype is type(None): continue loadedtype = type(getattr(loaded, attr)) - assert_equal(loadedtype, defaulttype, - "Type mismatch for attribute: {} ({!s} != {!s})".format( - attr, loadedtype, defaulttype)) + assert loadedtype == defaulttype, ( + "Type mismatch for attribute: {} ({!s} != {!s})".format( + attr, loadedtype, defaulttype)) def test_default_types(): @@ -142,18 +141,18 @@ def test_read_ordering(): # read another image first (DATA_FILE2) then the shape is wrong # Read an image img2 = load(DATA_FILE2) - assert_equal(img2.darrays[0].data.shape, (143479, 1)) + assert img2.darrays[0].data.shape == (143479, 1) # Read image for which we know output shape img = load(DATA_FILE1) - assert_equal(img.darrays[0].data.shape, (3, 3)) + assert img.darrays[0].data.shape == (3, 3) def test_load_metadata(): for i, dat in enumerate(datafiles): img = load(dat) img.meta - assert_equal(numDA[i], img.numDA) - assert_equal(img.version, '1.0') + assert numDA[i] == img.numDA + assert img.version == '1.0' def test_metadata_deprecations(): @@ -163,12 +162,12 @@ def test_metadata_deprecations(): # Test deprecation with clear_and_catch_warnings() as w: warnings.filterwarnings('once', category=DeprecationWarning) - assert_equal(me, img.get_meta()) + assert me == img.get_meta() with clear_and_catch_warnings() as w: warnings.filterwarnings('once', category=DeprecationWarning) img.set_metadata(me) - assert_equal(me, img.meta) + assert me == img.meta def test_load_dataarray1(): @@ -181,14 +180,14 @@ def test_load_dataarray1(): assert_array_almost_equal(img.darrays[0].data, DATA_FILE1_darr1) assert_array_almost_equal(img.darrays[1].data, DATA_FILE1_darr2) me = img.darrays[0].meta.metadata - assert_true('AnatomicalStructurePrimary' in me) - assert_true('AnatomicalStructureSecondary' in me) - assert_equal(me['AnatomicalStructurePrimary'], 'CortexLeft') + assert 'AnatomicalStructurePrimary' in me + assert 'AnatomicalStructureSecondary' in me + me['AnatomicalStructurePrimary'] == 'CortexLeft' assert_array_almost_equal(img.darrays[0].coordsys.xform, np.eye(4, 4)) - assert_equal(xform_codes.niistring[img.darrays[ - 0].coordsys.dataspace], 'NIFTI_XFORM_TALAIRACH') - assert_equal(xform_codes.niistring[img.darrays[ - 0].coordsys.xformspace], 'NIFTI_XFORM_TALAIRACH') + assert xform_codes.niistring[ + img.darrays[0].coordsys.dataspace] == 'NIFTI_XFORM_TALAIRACH' + assert xform_codes.niistring[img.darrays[ + 0].coordsys.xformspace] == 'NIFTI_XFORM_TALAIRACH' def test_load_dataarray2(): @@ -223,7 +222,7 @@ def test_load_dataarray4(): def test_dataarray5(): img5 = load(DATA_FILE5) for da in img5.darrays: - assert_equal(gifti_endian_codes.byteorder[da.endian], 'little') + gifti_endian_codes.byteorder[da.endian] == 'little' assert_array_almost_equal(img5.darrays[0].data, DATA_FILE5_darr1) assert_array_almost_equal(img5.darrays[1].data, DATA_FILE5_darr2) # Round trip tested below @@ -234,24 +233,24 @@ def test_base64_written(): with open(DATA_FILE5, 'rb') as fobj: contents = fobj.read() # Confirm the bad tags are still in the file - assert_true(b'GIFTI_ENCODING_B64BIN' in contents) - assert_true(b'GIFTI_ENDIAN_LITTLE' in contents) + assert b'GIFTI_ENCODING_B64BIN' in contents + assert b'GIFTI_ENDIAN_LITTLE' in contents # The good ones are missing - assert_false(b'Base64Binary' in contents) - assert_false(b'LittleEndian' in contents) + assert b'Base64Binary' not in contents + assert b'LittleEndian' not in contents # Round trip img5 = load(DATA_FILE5) save(img5, 'fixed.gii') with open('fixed.gii', 'rb') as fobj: contents = fobj.read() # The bad codes have gone, replaced by the good ones - assert_false(b'GIFTI_ENCODING_B64BIN' in contents) - assert_false(b'GIFTI_ENDIAN_LITTLE' in contents) - assert_true(b'Base64Binary' in contents) + assert b'GIFTI_ENCODING_B64BIN' not in contents + assert b'GIFTI_ENDIAN_LITTLE' not in contents + assert b'Base64Binary' in contents if sys.byteorder == 'little': - assert_true(b'LittleEndian' in contents) + assert b'LittleEndian' in contents else: - assert_true(b'BigEndian' in contents) + assert b'BigEndian' in contents img5_fixed = load('fixed.gii') darrays = img5_fixed.darrays assert_array_almost_equal(darrays[0].data, DATA_FILE5_darr1) @@ -263,7 +262,7 @@ def test_readwritedata(): with InTemporaryDirectory(): save(img, 'test.gii') img2 = load('test.gii') - assert_equal(img.numDA, img2.numDA) + assert img.numDA == img2.numDA assert_array_almost_equal(img.darrays[0].data, img2.darrays[0].data) @@ -272,7 +271,7 @@ def test_modify_darray(): img = load(fname) darray = img.darrays[0] darray.data[:] = 0 - assert_true(np.array_equiv(darray.data, 0)) + assert np.array_equiv(darray.data, 0) def test_write_newmetadata(): @@ -281,32 +280,32 @@ def test_write_newmetadata(): newmeta = gi.GiftiMetaData(attr) img.meta = newmeta myme = img.meta.metadata - assert_true('mykey' in myme) + assert 'mykey' in myme newmeta = gi.GiftiMetaData.from_dict({'mykey1': 'val2'}) img.meta = newmeta myme = img.meta.metadata - assert_true('mykey1' in myme) - assert_false('mykey' in myme) + assert 'mykey1' in myme + assert 'mykey' not in myme def test_load_getbyintent(): img = load(DATA_FILE1) da = img.get_arrays_from_intent("NIFTI_INTENT_POINTSET") - assert_equal(len(da), 1) + assert len(da) == 1 with clear_and_catch_warnings() as w: warnings.filterwarnings('once', category=DeprecationWarning) da = img.getArraysFromIntent("NIFTI_INTENT_POINTSET") - assert_equal(len(da), 1) - assert_equal(len(w), 1) - assert_equal(w[0].category, DeprecationWarning) + assert len(da) == 1 + assert len(w) == 1 + w[0].category == DeprecationWarning da = img.get_arrays_from_intent("NIFTI_INTENT_TRIANGLE") - assert_equal(len(da), 1) + assert len(da) == 1 da = img.get_arrays_from_intent("NIFTI_INTENT_CORREL") - assert_equal(len(da), 0) - assert_equal(da, []) + assert len(da) == 0 + assert da == [] def test_load_labeltable(): @@ -317,15 +316,15 @@ def test_load_labeltable(): bimg = load('test.gii') for img in (img6, bimg): assert_array_almost_equal(img.darrays[0].data[:3], DATA_FILE6_darr1) - assert_equal(len(img.labeltable.labels), 36) + assert len(img.labeltable.labels) == 36 labeldict = img.labeltable.get_labels_as_dict() - assert_true(660700 in labeldict) - assert_equal(labeldict[660700], 'entorhinal') - assert_equal(img.labeltable.labels[1].key, 2647065) - assert_equal(img.labeltable.labels[1].red, 0.0980392) - assert_equal(img.labeltable.labels[1].green, 0.392157) - assert_equal(img.labeltable.labels[1].blue, 0.156863) - assert_equal(img.labeltable.labels[1].alpha, 1) + assert 660700 in labeldict + assert labeldict[660700] == 'entorhinal' + assert img.labeltable.labels[1].key == 2647065 + assert img.labeltable.labels[1].red == 0.0980392 + assert img.labeltable.labels[1].green == 0.392157 + assert img.labeltable.labels[1].blue == 0.156863 + assert img.labeltable.labels[1].alpha == 1 def test_labeltable_deprecations(): @@ -335,14 +334,14 @@ def test_labeltable_deprecations(): # Test deprecation with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) - assert_equal(lt, img.get_labeltable()) - assert_equal(len(w), 1) + assert lt == img.get_labeltable() + assert len(w) == 1 with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) img.set_labeltable(lt) - assert_equal(len(w), 1) - assert_equal(lt, img.labeltable) + assert len(w) == 1 + assert lt == img.labeltable def test_parse_dataarrays(): @@ -361,8 +360,8 @@ def test_parse_dataarrays(): with clear_and_catch_warnings() as w: warnings.filterwarnings('once', category=UserWarning) load(fn) - assert_equal(len(w), 1) - assert_equal(img.numDA, 0) + assert len(w) == 1 + assert img.numDA == 0 def test_parse_deprecated(): @@ -371,16 +370,16 @@ def test_parse_deprecated(): with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) op = Outputter() - assert_equal(len(w), 1) + assert len(w) == 1 op.initialize() # smoke test--no error. with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) - assert_raises(ValueError, parse_gifti_file) - assert_equal(len(w), 1) + pytest.raises(ValueError, parse_gifti_file) + assert len(w) == 1 def test_parse_with_buffersize(): for buff_sz in [None, 1, 2**12]: img2 = load(DATA_FILE2, buffer_size=buff_sz) - assert_equal(img2.darrays[0].data.shape, (143479, 1)) + assert img2.darrays[0].data.shape == (143479, 1) From 325080e3f9f0edd6c892c04c17293521ddc14101 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 4 Feb 2020 14:57:23 -0500 Subject: [PATCH 067/223] TEST: Style cleanup --- nibabel/tests/test_arrayproxy.py | 8 +++---- nibabel/tests/test_arraywriters.py | 7 +++--- nibabel/tests/test_batteryrunners.py | 36 +++++----------------------- nibabel/tests/test_casting.py | 8 ++----- 4 files changed, 14 insertions(+), 45 deletions(-) diff --git a/nibabel/tests/test_arrayproxy.py b/nibabel/tests/test_arrayproxy.py index b00af7d90f..7b2fcca384 100644 --- a/nibabel/tests/test_arrayproxy.py +++ b/nibabel/tests/test_arrayproxy.py @@ -73,7 +73,7 @@ def test_init(): assert ap.shape == shape # shape should be read only with pytest.raises(AttributeError): - setattr(ap, 'shape', shape) + ap.shape = shape # Get the data assert_array_equal(np.asarray(ap), arr) # Check we can modify the original header without changing the ap version @@ -323,10 +323,8 @@ def check_mmap(hdr, offset, proxy_class, assert not unscaled_is_mmap assert not back_is_mmap else: - assert (unscaled_is_mmap == - (viral_memmap or unscaled_really_mmap)) - assert (back_is_mmap == - (viral_memmap or scaled_really_mmap)) + assert unscaled_is_mmap == (viral_memmap or unscaled_really_mmap) + assert back_is_mmap == (viral_memmap or scaled_really_mmap) if scaled_really_mmap: assert back_data.mode == expected_mode del prox, back_data diff --git a/nibabel/tests/test_arraywriters.py b/nibabel/tests/test_arraywriters.py index fa24b37102..8f30f04321 100644 --- a/nibabel/tests/test_arraywriters.py +++ b/nibabel/tests/test_arraywriters.py @@ -14,11 +14,10 @@ from ..casting import int_abs, type_info, shared_range, on_powerpc from ..volumeutils import array_from_file, apply_read_scaling, _dt_min_max -from numpy.testing import (assert_array_almost_equal, - assert_array_equal) +from numpy.testing import assert_array_almost_equal, assert_array_equal import pytest from ..testing_pytest import (assert_allclose_safely, suppress_warnings, - error_warnings) + error_warnings) FLOAT_TYPES = np.sctypes['float'] @@ -532,7 +531,7 @@ def test_nan2zero(): # Deprecation warning for nan2zero as argument to `to_fileobj` with error_warnings(): with pytest.raises(DeprecationWarning): - aw.to_fileobj(BytesIO(), 'F', False) + aw.to_fileobj(BytesIO(), 'F', False) with pytest.raises(DeprecationWarning): aw.to_fileobj(BytesIO(), 'F', nan2zero=False) # Error if nan2zero is not the value set at initialization diff --git a/nibabel/tests/test_batteryrunners.py b/nibabel/tests/test_batteryrunners.py index 883054ff96..69f18b75ac 100644 --- a/nibabel/tests/test_batteryrunners.py +++ b/nibabel/tests/test_batteryrunners.py @@ -159,43 +159,19 @@ def test_logging(): def test_checks(): battrun = BatteryRunner((chk1,)) reports = battrun.check_only({}) - assert (reports[0] == - Report(KeyError, - 20, - 'no "testkey"', - '')) + assert reports[0] == Report(KeyError, 20, 'no "testkey"', '') obj, reports = battrun.check_fix({}) - assert (reports[0] == - Report(KeyError, - 20, - 'no "testkey"', - 'added "testkey"')) + assert reports[0] == Report(KeyError, 20, 'no "testkey"', 'added "testkey"') assert obj == {'testkey': 1} battrun = BatteryRunner((chk1, chk2)) reports = battrun.check_only({}) - assert (reports[0] == - Report(KeyError, - 20, - 'no "testkey"', - '')) - assert (reports[1] == - Report(KeyError, - 20, - 'no "testkey"', - '')) + assert reports[0] == Report(KeyError, 20, 'no "testkey"', '') + assert reports[1] == Report(KeyError, 20, 'no "testkey"', '') obj, reports = battrun.check_fix({}) # In the case of fix, the previous fix exposes a different error # Note, because obj is mutable, first and second point to modified # (and final) dictionary output_obj = {'testkey': 0} - assert (reports[0] == - Report(KeyError, - 20, - 'no "testkey"', - 'added "testkey"')) - assert (reports[1] == - Report(ValueError, - 10, - '"testkey" != 0', - 'set "testkey" to 0')) + assert reports[0] == Report(KeyError, 20, 'no "testkey"', 'added "testkey"') + assert reports[1] == Report(ValueError, 10, '"testkey" != 0', 'set "testkey" to 0') assert obj == output_obj diff --git a/nibabel/tests/test_casting.py b/nibabel/tests/test_casting.py index 791cdacedb..3fe74dfb8b 100644 --- a/nibabel/tests/test_casting.py +++ b/nibabel/tests/test_casting.py @@ -43,9 +43,7 @@ def test_shared_range(): if imax_roundtrip == imax: thresh_overflow = True if thresh_overflow: - assert np.all( - (bit_bigger == casted_mx) | - (bit_bigger == imax)) + assert np.all((bit_bigger == casted_mx) | (bit_bigger == imax)) else: assert np.all((bit_bigger <= casted_mx)) if it in np.sctypes['uint']: @@ -71,9 +69,7 @@ def test_shared_range(): if imin_roundtrip == imin: thresh_overflow = True if thresh_overflow: - assert np.all( - (bit_smaller == casted_mn) | - (bit_smaller == imin)) + assert np.all((bit_smaller == casted_mn) | (bit_smaller == imin)) else: assert np.all((bit_smaller >= casted_mn)) From 5f695b8c3fc06536aebcfdc5542ce7968df5cb62 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 4 Feb 2020 15:49:36 -0500 Subject: [PATCH 068/223] TEST: Simplify data/environment fixtures --- nibabel/tests/test_data.py | 17 ++++++----------- nibabel/tests/test_environment.py | 25 ++++++++++--------------- 2 files changed, 16 insertions(+), 26 deletions(-) diff --git a/nibabel/tests/test_data.py b/nibabel/tests/test_data.py index e48356eb50..1c8812fe61 100644 --- a/nibabel/tests/test_data.py +++ b/nibabel/tests/test_data.py @@ -19,24 +19,19 @@ import pytest -from .test_environment import (with_environment, - DATA_KEY, - USER_KEY) +from .test_environment import with_environment, DATA_KEY, USER_KEY -@pytest.fixture() +@pytest.fixture def with_nimd_env(request, with_environment): DATA_FUNCS = {} DATA_FUNCS['home_dir_func'] = nibd.get_nipy_user_dir DATA_FUNCS['sys_dir_func'] = nibd.get_nipy_system_dir DATA_FUNCS['path_func'] = nibd.get_data_path - - def teardown_data_env(): - nibd.get_nipy_user_dir = DATA_FUNCS['home_dir_func'] - nibd.get_nipy_system_dir = DATA_FUNCS['sys_dir_func'] - nibd.get_data_path = DATA_FUNCS['path_func'] - - request.addfinalizer(teardown_data_env) + yield + nibd.get_nipy_user_dir = DATA_FUNCS['home_dir_func'] + nibd.get_nipy_system_dir = DATA_FUNCS['sys_dir_func'] + nibd.get_data_path = DATA_FUNCS['path_func'] def test_datasource(): diff --git a/nibabel/tests/test_environment.py b/nibabel/tests/test_environment.py index 6dc127c95f..e0514c337e 100644 --- a/nibabel/tests/test_environment.py +++ b/nibabel/tests/test_environment.py @@ -14,7 +14,7 @@ USER_KEY = 'NIPY_USER_DIR' -@pytest.fixture() +@pytest.fixture def with_environment(request): """Setup test environment for some functions that are tested in this module. In particular this functions stores attributes @@ -24,20 +24,15 @@ def with_environment(request): """ GIVEN_ENV = {} GIVEN_ENV['env'] = env.copy() - - - def teardown_environment(): - """Restore things that were remembered by the setup_environment function - """ - orig_env = GIVEN_ENV['env'] - # Pull keys out into list to avoid altering dictionary during iteration, - # causing python 3 error - for key in list(env.keys()): - if key not in orig_env: - del env[key] - env.update(orig_env) - - request.addfinalizer(teardown_environment) + yield + """Restore things that were remembered by the setup_environment function """ + orig_env = GIVEN_ENV['env'] + # Pull keys out into list to avoid altering dictionary during iteration, + # causing python 3 error + for key in list(env.keys()): + if key not in orig_env: + del env[key] + env.update(orig_env) def test_nipy_home(): From b66ec38188ce7549861f128c39a651a704dfaa1c Mon Sep 17 00:00:00 2001 From: Anibal Solon Date: Tue, 4 Feb 2020 15:56:59 -0500 Subject: [PATCH 069/223] make sure cov is installed --- .azure-pipelines/windows.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index 469fd27c96..1d660089bb 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -30,7 +30,7 @@ jobs: displayName: 'Update build tools' - script: | python -m pip install --find-links %EXTRA_WHEELS% %DEPENDS% - python -m pip install nose coverage codecov pytest + python -m pip install nose coverage codecov pytest pytest-cov displayName: 'Install dependencies' - script: | python -m pip install .[$(CHECK_TYPE)] From 2bc53088975982ab5f562727ad939ddc8eeb4d1c Mon Sep 17 00:00:00 2001 From: orduek Date: Tue, 4 Feb 2020 15:59:43 -0500 Subject: [PATCH 070/223] changed nosetools assertion to pytest in test_mghformat.py --- nibabel/freesurfer/tests/test_mghformat.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/nibabel/freesurfer/tests/test_mghformat.py b/nibabel/freesurfer/tests/test_mghformat.py index 289acbcd01..25a7254def 100644 --- a/nibabel/freesurfer/tests/test_mghformat.py +++ b/nibabel/freesurfer/tests/test_mghformat.py @@ -23,7 +23,8 @@ from ...wrapstruct import WrapStructError from ... import imageglobals -from nose.tools import assert_true, assert_false + +import pytest from numpy.testing import (assert_equal, assert_array_equal, assert_array_almost_equal, assert_almost_equal, @@ -260,7 +261,7 @@ def test_eq(): hdr2 = MGHHeader() assert_equal(hdr, hdr2) hdr.set_data_shape((2, 3, 4)) - assert_false(hdr == hdr2) + assert(hdr != hdr2) hdr2.set_data_shape((2, 3, 4)) assert_equal(hdr, hdr2) @@ -287,7 +288,7 @@ def test_mgh_load_fileobj(): bio = io.BytesIO(contents) fm = MGHImage.make_file_map(mapping=dict(image=bio)) img2 = MGHImage.from_file_map(fm) - assert_true(img2.dataobj.file_like is bio) + assert(img2.dataobj.file_like is bio) assert_array_equal(img.get_fdata(), img2.get_fdata()) @@ -477,7 +478,7 @@ def test_as_byteswapped(self): # same code just returns a copy for endianness in BIG_CODES: hdr2 = hdr.as_byteswapped(endianness) - assert_false(hdr2 is hdr) + assert(hdr2 is not hdr) assert_equal(hdr2, hdr) # Different code raises error From f3be7b238ba1e5e41eb475da7c406ac821aa2b8f Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 4 Feb 2020 16:00:29 -0500 Subject: [PATCH 071/223] TEST: Simplify, reformat test_data --- nibabel/tests/test_data.py | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/nibabel/tests/test_data.py b/nibabel/tests/test_data.py index 1c8812fe61..e5d5000438 100644 --- a/nibabel/tests/test_data.py +++ b/nibabel/tests/test_data.py @@ -157,8 +157,7 @@ def test_data_path(with_nimd_env): with open(tmpfile, 'wt') as fobj: fobj.write('[DATA]\n') fobj.write('path = %s\n' % '/path/two') - assert (get_data_path() == - tst_list + ['/path/two'] + old_pth) + assert get_data_path() == tst_list + ['/path/two'] + old_pth def test_find_data_dir(): @@ -201,10 +200,10 @@ def test_make_datasource(with_nimd_env): assert ds.version == '0.1' +@pytest.mark.xfail(raises=DataError) def test_bomber(): - with pytest.raises(DataError): - b = Bomber('bomber example', 'a message') - b.any_attribute # no error + b = Bomber('bomber example', 'a message') + b.any_attribute # no error def test_bomber_inspect(): @@ -213,13 +212,12 @@ def test_bomber_inspect(): def test_datasource_or_bomber(with_nimd_env): - pkg_def = dict( - relpath='pkg') + pkg_def = dict(relpath='pkg') with TemporaryDirectory() as tmpdir: nibd.get_data_path = lambda: [tmpdir] ds = datasource_or_bomber(pkg_def) with pytest.raises(DataError): - getattr(ds, 'get_filename') + ds.get_filename('some_file.txt') pkg_dir = pjoin(tmpdir, 'pkg') os.mkdir(pkg_dir) tmpfile = pjoin(pkg_dir, 'config.ini') @@ -235,4 +233,4 @@ def test_datasource_or_bomber(with_nimd_env): pkg_def['min version'] = '0.3' ds = datasource_or_bomber(pkg_def) # not OK with pytest.raises(DataError): - getattr(ds, 'get_filename') + ds.get_filename('some_file.txt') From 92c758aebd75b7944c351b00cf39ba733782bc86 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 4 Feb 2020 16:17:18 -0500 Subject: [PATCH 072/223] STY: Remove unused pkgutil import --- nibabel/optpkg.py | 1 - 1 file changed, 1 deletion(-) diff --git a/nibabel/optpkg.py b/nibabel/optpkg.py index 3590cd3c00..81dae3010c 100644 --- a/nibabel/optpkg.py +++ b/nibabel/optpkg.py @@ -1,5 +1,4 @@ """ Routines to support optional packages """ -import pkgutil from distutils.version import LooseVersion from .tripwire import TripWire From 1e7bdd035590d4f5235b379f6385ce2bcfc753c8 Mon Sep 17 00:00:00 2001 From: Anibal Solon Date: Tue, 4 Feb 2020 16:31:57 -0500 Subject: [PATCH 073/223] test script condition --- .azure-pipelines/windows.yml | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index 1d660089bb..008bbef248 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -40,12 +40,16 @@ jobs: mkdir for_testing cd for_testing cp ../.coveragerc . - if $(CHECK_TYPE)=="nosetests" ( - nosetests --with-doctest --with-coverage --cover-package nibabel nibabel - ) else ( - pytest --cov nibabel -v --pyargs nibabel --deselect streamlines - ) + nosetests --with-doctest --with-coverage --cover-package nibabel nibabel displayName: 'Nose tests' + condition: and(succeeded(), eq(variables['CHECK_TYPE'], 'nosetests')) + - script: | + mkdir for_testing + cd for_testing + cp ../.coveragerc . + pytest --cov nibabel -v --pyargs nibabel --deselect streamlines + displayName: 'Pytest tests' + condition: and(succeeded(), eq(variables['CHECK_TYPE'], 'test')) - script: | cd for_testing codecov From 2ef9ad4a8a998866d9f8fbadfaa44544226ff650 Mon Sep 17 00:00:00 2001 From: Anibal Solon Date: Tue, 4 Feb 2020 16:46:55 -0500 Subject: [PATCH 074/223] reintroduce nosetests into matrix --- azure-pipelines.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 5bbd37986c..0b37903121 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -38,3 +38,7 @@ jobs: PYTHON_VERSION: '3.6' PYTHON_ARCH: 'x64' CHECK_TYPE: 'test' + nosetests: + PYTHON_VERSION: '3.6' + PYTHON_ARCH: 'x64' + CHECK_TYPE: 'nosetests' \ No newline at end of file From 6817eb6b899a4a1deefa08e21437844f3f05848b Mon Sep 17 00:00:00 2001 From: Anibal Solon Date: Tue, 4 Feb 2020 16:48:28 -0500 Subject: [PATCH 075/223] remove unnecessary dependency --- setup.cfg | 1 - 1 file changed, 1 deletion(-) diff --git a/setup.cfg b/setup.cfg index 34c8456a04..fe6d91bdd3 100644 --- a/setup.cfg +++ b/setup.cfg @@ -59,7 +59,6 @@ nosetests = coverage nose >=0.11 pytest - pytest-cov test = coverage nose >=0.11 From 2d0dc89542e0be1c7c1476f1d4fdaf31f168031d Mon Sep 17 00:00:00 2001 From: Anibal Solon Date: Tue, 4 Feb 2020 16:54:03 -0500 Subject: [PATCH 076/223] pytest is already tested --- azure-pipelines.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 67d859c09b..2ef2539c74 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -34,10 +34,6 @@ jobs: py38-x64: PYTHON_VERSION: '3.8' PYTHON_ARCH: 'x64' - pytest: - PYTHON_VERSION: '3.6' - PYTHON_ARCH: 'x64' - CHECK_TYPE: 'test' nosetests: PYTHON_VERSION: '3.6' PYTHON_ARCH: 'x64' From 172598588072958887e8dbde4a1efd75252c90af Mon Sep 17 00:00:00 2001 From: Anibal Solon Date: Tue, 4 Feb 2020 17:06:04 -0500 Subject: [PATCH 077/223] nose test inclusions --- .azure-pipelines/windows.yml | 59 +++++++++++++++++++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index e0d0bdf651..8dcf0e24d8 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -40,7 +40,64 @@ jobs: mkdir for_testing cd for_testing cp ../.coveragerc . - nosetests --with-doctest --with-coverage --cover-package nibabel nibabel + nosetests --with-doctest --with-coverage --cover-package nibabel nibabel \ + -I test_array_sequence \ + -I test_tractogram \ + -I test_api_validators \ + -I test_arrayproxy \ + -I test_arraywriters \ + -I test_batteryrunners \ + -I test_brikhead \ + -I test_casting \ + -I test_cifti2io_header \ + -I test_data \ + -I test_deprecated \ + -I test_deprecator \ + -I test_dft \ + -I test_ecat \ + -I test_ecat_data \ + -I test_endiancodes \ + -I test_environment \ + -I test_euler \ + -I test_filebasedimages \ + -I test_filehandles \ + -I test_fileholders \ + -I test_filename_parser \ + -I test_files_interface \ + -I test_fileslice \ + -I test_fileutils \ + -I test_floating \ + -I test_funcs \ + -I test_h5py_compat \ + -I test_image_api \ + -I test_image_load_save \ + -I test_image_types \ + -I test_imageclasses \ + -I test_imageglobals \ + -I test_keywordonly \ + -I test_loadsave \ + -I test_minc1 \ + -I test_minc2 \ + -I test_minc2_data \ + -I test_mriutils \ + -I test_nibabel_data \ + -I test_nifti1 \ + -I test_nifti2 \ + -I test_openers \ + -I test_optpkg \ + -I test_orientations \ + -I test_parrec \ + -I test_parrec_data \ + -I test_pkg_info \ + -I test_processing \ + -I test_proxy_api \ + -I test_quaternions \ + -I test_recoder \ + -I test_remmovalschedule \ + -I test_round_trip \ + -I test_rstutils \ + -I test_scaling \ + -I test_wrapstruct displayName: 'Nose tests' condition: and(succeeded(), eq(variables['CHECK_TYPE'], 'nosetests')) - script: | From dba6f59ecf72e1ab44495b1414f68763dce43dce Mon Sep 17 00:00:00 2001 From: orduek Date: Tue, 4 Feb 2020 17:07:58 -0500 Subject: [PATCH 078/223] changed from numpy raises to pytest.raises and skipif --- nibabel/freesurfer/tests/test_io.py | 65 ++++++++++++++--------------- 1 file changed, 31 insertions(+), 34 deletions(-) diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index 41bcdd17cf..cde2edeb5f 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -12,7 +12,7 @@ import pytest import numpy as np -from numpy.testing import assert_equal, assert_raises, dec, assert_allclose, assert_array_equal +from numpy.testing import assert_allclose, assert_array_equal from .. import (read_geometry, read_morph_data, read_annot, read_label, write_geometry, write_morph_data, write_annot) @@ -20,7 +20,7 @@ from ...tests.nibabel_data import get_nibabel_data, needs_nibabel_data from ...fileslice import strided_scalar -from ...testing import clear_and_catch_warnings +from ...testing_pytest import clear_and_catch_warnings DATA_SDIR = 'fsaverage' @@ -36,10 +36,7 @@ data_path = pjoin(nib_data, 'nitest-freesurfer', DATA_SDIR) have_freesurfer = isdir(data_path) -freesurfer_test = dec.skipif( - not have_freesurfer, - 'cannot find freesurfer {0} directory'.format(DATA_SDIR)) - +freesurfer_test = pytest.mark.skipif(not have_freesurfer, reason='cannot find freesurfer {0} directory'.format(DATA_SDIR)) def _hash_file_content(fname): hasher = hashlib.md5() @@ -54,19 +51,18 @@ def test_geometry(): """Test IO of .surf""" surf_path = pjoin(data_path, "surf", "%s.%s" % ("lh", "inflated")) coords, faces = read_geometry(surf_path) - assert_equal(0, faces.min()) - assert_equal(coords.shape[0], faces.max() + 1) + assert 0==faces.min() + assert coords.shape[0]== faces.max() + 1 surf_path = pjoin(data_path, "surf", "%s.%s" % ("lh", "sphere")) coords, faces, volume_info, create_stamp = read_geometry( surf_path, read_metadata=True, read_stamp=True) - assert_equal(0, faces.min()) - assert_equal(coords.shape[0], faces.max() + 1) - assert_equal(9, len(volume_info)) - assert_equal([2, 0, 20], volume_info['head']) - assert_equal(u'created by greve on Thu Jun 8 19:17:51 2006', - create_stamp) + assert 0 == faces.min() + assert coords.shape[0] == faces.max() + 1 + assert 9 == len(volume_info) + assert [2, 0, 20] == volume_info['head'] + assert 'created by greve on Thu Jun 8 19:17:51 2006' == create_stamp # Test equivalence of freesurfer- and nibabel-generated triangular files # with respect to read_geometry() @@ -83,7 +79,7 @@ def test_geometry(): for key in ('xras', 'yras', 'zras', 'cras'): assert_allclose(volume_info2[key], volume_info[key], rtol=1e-7, atol=1e-30) - assert_equal(volume_info2['cras'], volume_info['cras']) + assert volume_info2['cras'] == volume_info['cras'] with open(surf_path, 'rb') as fobj: np.fromfile(fobj, ">u1", 3) read_create_stamp = fobj.readline().decode().rstrip('\n') @@ -101,10 +97,11 @@ def test_geometry(): write_geometry(surf_path, coords, faces, create_stamp, volume_info) assert(any('Unknown extension' in str(ww.message) for ww in w)) volume_info['a'] = 0 - assert_raises(ValueError, write_geometry, surf_path, coords, - faces, create_stamp, volume_info) + with pytest.raises(ValueError): + write_geometry(surf_path, coords, faces, create_stamp, volume_info) + - assert_equal(create_stamp, read_create_stamp) + assert create_stamp == read_create_stamp np.testing.assert_array_equal(coords, coords2) np.testing.assert_array_equal(faces, faces2) @@ -123,14 +120,14 @@ def test_quad_geometry(): new_quad = pjoin(get_nibabel_data(), 'nitest-freesurfer', 'subjects', 'bert', 'surf', 'lh.inflated.nofix') coords, faces = read_geometry(new_quad) - assert_equal(0, faces.min()) - assert_equal(coords.shape[0], faces.max() + 1) + assert 0 == faces.min() + assert coords.shape[0] == faces.max() + 1 with InTemporaryDirectory(): new_path = 'test' write_geometry(new_path, coords, faces) coords2, faces2 = read_geometry(new_path) - assert_equal(coords, coords2) - assert_equal(faces, faces2) + assert coords == coords2 + assert faces == faces2 @freesurfer_test @@ -144,7 +141,7 @@ def test_morph_data(): new_path = 'test' write_morph_data(new_path, curv) curv2 = read_morph_data(new_path) - assert_equal(curv2, curv) + assert curv2 == curv def test_write_morph_data(): @@ -157,17 +154,17 @@ def test_write_morph_data(): for shape in okay_shapes: write_morph_data('test.curv', values.reshape(shape)) # Check ordering is preserved, regardless of shape - assert_equal(values, read_morph_data('test.curv')) - assert_raises(ValueError, write_morph_data, 'test.curv', - np.zeros(shape), big_num) - # Windows 32-bit overflows Python int + assert values == read_morph_data('test.curv') + with pytest.raises(ValueError): + write_morph_data('test.curv', np.zeros(shape), big_num) + # Windows 32-bit overflows Python int if np.dtype(np.int) != np.dtype(np.int32): - assert_raises(ValueError, write_morph_data, 'test.curv', - strided_scalar((big_num,))) + with pytest.raises(ValueError): + write_morph_data('test.curv', strided_scalar((big_num,))) for shape in bad_shapes: - assert_raises(ValueError, write_morph_data, 'test.curv', - values.reshape(shape)) - + with pytest.raises(ValueError): + write_morph_data('test.curv', values.reshape(shape)) + @freesurfer_test def test_annot(): @@ -208,7 +205,7 @@ def test_annot(): if labels_orig is not None: np.testing.assert_array_equal(labels_orig, labels_orig_2) np.testing.assert_array_equal(ctab, ctab2) - assert_equal(names, names2) + assert names == names2 def test_read_write_annot(): @@ -374,4 +371,4 @@ def test_write_annot_maxstruct(): # Check round-trip assert_array_equal(labels, rt_labels) assert_array_equal(rgba, rt_ctab[:, :4]) - assert_equal(names, [n.decode('ascii') for n in rt_names]) + assert names == [n.decode('ascii') for n in rt_names] From b2676d80f7d13ca836278d221fc1743767c54bd7 Mon Sep 17 00:00:00 2001 From: Anibal Solon Date: Tue, 4 Feb 2020 17:19:55 -0500 Subject: [PATCH 079/223] windows breaklines..? --- .azure-pipelines/windows.yml | 116 +++++++++++++++++------------------ 1 file changed, 58 insertions(+), 58 deletions(-) diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index 8dcf0e24d8..e64231c447 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -40,64 +40,64 @@ jobs: mkdir for_testing cd for_testing cp ../.coveragerc . - nosetests --with-doctest --with-coverage --cover-package nibabel nibabel \ - -I test_array_sequence \ - -I test_tractogram \ - -I test_api_validators \ - -I test_arrayproxy \ - -I test_arraywriters \ - -I test_batteryrunners \ - -I test_brikhead \ - -I test_casting \ - -I test_cifti2io_header \ - -I test_data \ - -I test_deprecated \ - -I test_deprecator \ - -I test_dft \ - -I test_ecat \ - -I test_ecat_data \ - -I test_endiancodes \ - -I test_environment \ - -I test_euler \ - -I test_filebasedimages \ - -I test_filehandles \ - -I test_fileholders \ - -I test_filename_parser \ - -I test_files_interface \ - -I test_fileslice \ - -I test_fileutils \ - -I test_floating \ - -I test_funcs \ - -I test_h5py_compat \ - -I test_image_api \ - -I test_image_load_save \ - -I test_image_types \ - -I test_imageclasses \ - -I test_imageglobals \ - -I test_keywordonly \ - -I test_loadsave \ - -I test_minc1 \ - -I test_minc2 \ - -I test_minc2_data \ - -I test_mriutils \ - -I test_nibabel_data \ - -I test_nifti1 \ - -I test_nifti2 \ - -I test_openers \ - -I test_optpkg \ - -I test_orientations \ - -I test_parrec \ - -I test_parrec_data \ - -I test_pkg_info \ - -I test_processing \ - -I test_proxy_api \ - -I test_quaternions \ - -I test_recoder \ - -I test_remmovalschedule \ - -I test_round_trip \ - -I test_rstutils \ - -I test_scaling \ - -I test_wrapstruct + nosetests --with-doctest --with-coverage --cover-package nibabel nibabel ^ + -I test_array_sequence ^ + -I test_tractogram ^ + -I test_api_validators ^ + -I test_arrayproxy ^ + -I test_arraywriters ^ + -I test_batteryrunners ^ + -I test_brikhead ^ + -I test_casting ^ + -I test_cifti2io_header ^ + -I test_data ^ + -I test_deprecated ^ + -I test_deprecator ^ + -I test_dft ^ + -I test_ecat ^ + -I test_ecat_data ^ + -I test_endiancodes ^ + -I test_environment ^ + -I test_euler ^ + -I test_filebasedimages ^ + -I test_filehandles ^ + -I test_fileholders ^ + -I test_filename_parser ^ + -I test_files_interface ^ + -I test_fileslice ^ + -I test_fileutils ^ + -I test_floating ^ + -I test_funcs ^ + -I test_h5py_compat ^ + -I test_image_api ^ + -I test_image_load_save ^ + -I test_image_types ^ + -I test_imageclasses ^ + -I test_imageglobals ^ + -I test_keywordonly ^ + -I test_loadsave ^ + -I test_minc1 ^ + -I test_minc2 ^ + -I test_minc2_data ^ + -I test_mriutils ^ + -I test_nibabel_data ^ + -I test_nifti1 ^ + -I test_nifti2 ^ + -I test_openers ^ + -I test_optpkg ^ + -I test_orientations ^ + -I test_parrec ^ + -I test_parrec_data ^ + -I test_pkg_info ^ + -I test_processing ^ + -I test_proxy_api ^ + -I test_quaternions ^ + -I test_recoder ^ + -I test_remmovalschedule ^ + -I test_round_trip ^ + -I test_rstutils ^ + -I test_scaling ^ + -I test_wrapstruct displayName: 'Nose tests' condition: and(succeeded(), eq(variables['CHECK_TYPE'], 'nosetests')) - script: | From 406e6dc1adfe8f65158f425004209dcd93210225 Mon Sep 17 00:00:00 2001 From: orduek Date: Tue, 4 Feb 2020 17:28:50 -0500 Subject: [PATCH 080/223] Changed test_mghformat.py to pytest --- nibabel/freesurfer/tests/test_mghformat.py | 154 +++++++++++---------- 1 file changed, 79 insertions(+), 75 deletions(-) diff --git a/nibabel/freesurfer/tests/test_mghformat.py b/nibabel/freesurfer/tests/test_mghformat.py index 25a7254def..3d96aa60f6 100644 --- a/nibabel/freesurfer/tests/test_mghformat.py +++ b/nibabel/freesurfer/tests/test_mghformat.py @@ -26,12 +26,11 @@ import pytest -from numpy.testing import (assert_equal, assert_array_equal, - assert_array_almost_equal, assert_almost_equal, - assert_raises) -from ...testing import assert_not_equal +from numpy.testing import (assert_array_equal, + assert_array_almost_equal, assert_almost_equal) -from ...testing import data_path + +from ...testing_pytest import data_path from ...tests import test_spatialimages as tsi from ...tests.test_wrapstruct import _TestLabeledWrapStruct @@ -68,10 +67,10 @@ def test_read_mgh(): # header h = mgz.header - assert_equal(h['version'], 1) - assert_equal(h['type'], 3) - assert_equal(h['dof'], 0) - assert_equal(h['goodRASFlag'], 1) + assert h['version'] == 1 + assert h['type'] == 3 + assert h['dof'] == 0 + assert h['goodRASFlag'] == 1 assert_array_equal(h['dims'], [3, 4, 5, 2]) assert_almost_equal(h['tr'], 2.0) assert_almost_equal(h['flip_angle'], 0.0) @@ -102,10 +101,10 @@ def test_write_mgh(): # Delete loaded image to allow file deletion by windows del mgz # header - assert_equal(h['version'], 1) - assert_equal(h['type'], 3) - assert_equal(h['dof'], 0) - assert_equal(h['goodRASFlag'], 1) + assert h['version'] == 1 + assert h['type'] == 3 + assert h['dof'] == 0 + assert h['goodRASFlag'] == 1 assert_array_equal(h['dims'], [5, 4, 3, 2]) assert_almost_equal(h['tr'], 0.0) assert_almost_equal(h['flip_angle'], 0.0) @@ -132,10 +131,10 @@ def test_write_noaffine_mgh(): # Delete loaded image to allow file deletion by windows del mgz # header - assert_equal(h['version'], 1) - assert_equal(h['type'], 0) # uint8 for mgh - assert_equal(h['dof'], 0) - assert_equal(h['goodRASFlag'], 1) + assert h['version'] == 1 + assert h['type'] == 0 # uint8 for mgh + assert h['dof'] == 0 + assert h['goodRASFlag'] == 1 assert_array_equal(h['dims'], [7, 13, 3, 22]) assert_almost_equal(h['tr'], 0.0) assert_almost_equal(h['flip_angle'], 0.0) @@ -158,7 +157,7 @@ def test_set_zooms(): (1, 1, -1, 1), (1, 1, 1, -1), (1, 1, 1, 1, 5)): - with assert_raises(HeaderDataError): + with pytest.raises(HeaderDataError): h.set_zooms(zooms) # smoke test for tr=0 h.set_zooms((1, 1, 1, 0)) @@ -178,7 +177,8 @@ def bad_dtype_mgh(): def test_bad_dtype_mgh(): # Now test the above function - assert_raises(MGHError, bad_dtype_mgh) + with pytest.raises(MGHError): + bad_dtype_mgh() def test_filename_exts(): @@ -219,14 +219,14 @@ def test_header_updating(): assert_almost_equal(mgz.affine, exp_aff, 6) assert_almost_equal(hdr.get_affine(), exp_aff, 6) # Test that initial wonky header elements have not changed - assert_equal(hdr['delta'], 1) + assert hdr['delta'] == 1 assert_almost_equal(hdr['Mdc'].T, exp_aff[:3, :3]) # Save, reload, same thing img_fobj = io.BytesIO() mgz2 = _mgh_rt(mgz, img_fobj) hdr2 = mgz2.header assert_almost_equal(hdr2.get_affine(), exp_aff, 6) - assert_equal(hdr2['delta'], 1) + assert hdr2['delta'] == 1 # Change affine, change underlying header info exp_aff_d = exp_aff.copy() exp_aff_d[0, -1] = -14 @@ -259,17 +259,17 @@ def test_eq(): # Test headers compare properly hdr = MGHHeader() hdr2 = MGHHeader() - assert_equal(hdr, hdr2) + assert hdr == hdr2 hdr.set_data_shape((2, 3, 4)) assert(hdr != hdr2) hdr2.set_data_shape((2, 3, 4)) - assert_equal(hdr, hdr2) + assert hdr == hdr2 def test_header_slope_inter(): # Test placeholder slope / inter method hdr = MGHHeader() - assert_equal(hdr.get_slope_inter(), (None, None)) + assert hdr.get_slope_inter() == (None, None) def test_mgh_load_fileobj(): @@ -281,7 +281,7 @@ def test_mgh_load_fileobj(): # pass the filename to the array proxy, please feel free to change this # test. img = MGHImage.load(MGZ_FNAME) - assert_equal(img.dataobj.file_like, MGZ_FNAME) + assert img.dataobj.file_like == MGZ_FNAME # Check fileobj also passed into dataobj with ImageOpener(MGZ_FNAME) as fobj: contents = fobj.read() @@ -296,7 +296,7 @@ def test_mgh_affine_default(): hdr = MGHHeader() hdr['goodRASFlag'] = 0 hdr2 = MGHHeader(hdr.binaryblock) - assert_equal(hdr2['goodRASFlag'], 1) + assert hdr2['goodRASFlag'] == 1 assert_array_equal(hdr['Mdc'], hdr2['Mdc']) assert_array_equal(hdr['Pxyz_c'], hdr2['Pxyz_c']) @@ -311,33 +311,33 @@ def test_mgh_set_data_shape(): assert_array_equal(hdr.get_data_shape(), (5, 4, 3)) hdr.set_data_shape((5, 4, 3, 2)) assert_array_equal(hdr.get_data_shape(), (5, 4, 3, 2)) - with assert_raises(ValueError): + with pytest.raises(ValueError): hdr.set_data_shape((5, 4, 3, 2, 1)) def test_mghheader_default_structarr(): hdr = MGHHeader.default_structarr() - assert_equal(hdr['version'], 1) + assert hdr['version'] == 1 assert_array_equal(hdr['dims'], 1) - assert_equal(hdr['type'], 3) - assert_equal(hdr['dof'], 0) - assert_equal(hdr['goodRASFlag'], 1) + assert hdr['type'] == 3 + assert hdr['dof'] == 0 + assert hdr['goodRASFlag'] == 1 assert_array_equal(hdr['delta'], 1) assert_array_equal(hdr['Mdc'], [[-1, 0, 0], [0, 0, 1], [0, -1, 0]]) assert_array_equal(hdr['Pxyz_c'], 0) - assert_equal(hdr['tr'], 0) - assert_equal(hdr['flip_angle'], 0) - assert_equal(hdr['te'], 0) - assert_equal(hdr['ti'], 0) - assert_equal(hdr['fov'], 0) + assert hdr['tr'] ==0 + assert hdr['flip_angle'] == 0 + assert hdr['te'] == 0 + assert hdr['ti'] == 0 + assert hdr['fov'] == 0 for endianness in (None,) + BIG_CODES: hdr2 = MGHHeader.default_structarr(endianness=endianness) - assert_equal(hdr2, hdr) - assert_equal(hdr2.newbyteorder('>'), hdr) + assert hdr2 == hdr + assert hdr2.newbyteorder('>') == hdr for endianness in LITTLE_CODES: - with assert_raises(ValueError): + with pytest.raises(ValueError): MGHHeader.default_structarr(endianness=endianness) @@ -352,17 +352,17 @@ def test_deprecated_fields(): hdr['mrparams'] = [1, 2, 3, 4] assert_array_almost_equal(hdr['mrparams'], [1, 2, 3, 4]) - assert_equal(hdr['tr'], 1) - assert_equal(hdr['flip_angle'], 2) - assert_equal(hdr['te'], 3) - assert_equal(hdr['ti'], 4) - assert_equal(hdr['fov'], 0) + assert hdr['tr'] == 1 + assert hdr['flip_angle'] == 2 + assert hdr['te'] == 3 + assert hdr['ti'] == 4 + assert hdr['fov'] == 0 assert_array_almost_equal(hdr_data['mrparams'], [1, 2, 3, 4]) - assert_equal(hdr_data['tr'], 1) - assert_equal(hdr_data['flip_angle'], 2) - assert_equal(hdr_data['te'], 3) - assert_equal(hdr_data['ti'], 4) - assert_equal(hdr_data['fov'], 0) + assert hdr_data['tr'] == 1 + assert hdr_data['flip_angle'] == 2 + assert hdr_data['te'] == 3 + assert hdr_data['ti'] == 4 + assert hdr_data['fov'] == 0 hdr['tr'] = 5 hdr['flip_angle'] = 6 @@ -389,7 +389,7 @@ def check_dtypes(self, expected, actual): # Some images will want dtypes to be equal including endianness, # others may only require the same type # MGH requires the actual to be a big endian version of expected - assert_equal(expected.newbyteorder('>'), actual) + assert expected.newbyteorder('>') == actual class TestMGHHeader(_TestLabeledWrapStruct): @@ -406,9 +406,9 @@ def test_general_init(self): hdr = self.header_class() # binaryblock has length given by header data dtype binblock = hdr.binaryblock - assert_equal(len(binblock), hdr.structarr.dtype.itemsize) + assert len(binblock) == hdr.structarr.dtype.itemsize # Endianness will always be big, and cannot be set - assert_equal(hdr.endianness, '>') + assert hdr.endianness == '>' # You can also pass in a check flag, without data this has no # effect hdr = self.header_class(check=False) @@ -417,15 +417,15 @@ def test__eq__(self): # Test equal and not equal hdr1 = self.header_class() hdr2 = self.header_class() - assert_equal(hdr1, hdr2) + assert hdr1 == hdr2 self._set_something_into_hdr(hdr1) - assert_not_equal(hdr1, hdr2) + assert hdr1 != hdr2 self._set_something_into_hdr(hdr2) - assert_equal(hdr1, hdr2) + assert hdr1 == hdr2 # REMOVED as_byteswapped() test # Check comparing to funny thing says no - assert_not_equal(hdr1, None) - assert_not_equal(hdr1, 1) + assert hdr1 != None + assert hdr1 != 1 def test_to_from_fileobj(self): # Successful write using write_to @@ -434,56 +434,58 @@ def test_to_from_fileobj(self): hdr.write_to(str_io) str_io.seek(0) hdr2 = self.header_class.from_fileobj(str_io) - assert_equal(hdr2.endianness, '>') - assert_equal(hdr2.binaryblock, hdr.binaryblock) + assert hdr2.endianness == '>' + assert hdr2.binaryblock == hdr.binaryblock def test_endian_guess(self): # Check guesses of endian eh = self.header_class() - assert_equal(eh.endianness, '>') - assert_equal(self.header_class.guessed_endian(eh), '>') + assert eh.endianness == '>' + assert self.header_class.guessed_endian(eh) == '>' def test_bytes(self): # Test get of bytes hdr1 = self.header_class() bb = hdr1.binaryblock hdr2 = self.header_class(hdr1.binaryblock) - assert_equal(hdr1, hdr2) - assert_equal(hdr1.binaryblock, hdr2.binaryblock) + assert hdr1 == hdr2 + assert hdr1.binaryblock == hdr2.binaryblock # Do a set into the header, and try again. The specifics of 'setting # something' will depend on the nature of the bytes object self._set_something_into_hdr(hdr1) hdr2 = self.header_class(hdr1.binaryblock) - assert_equal(hdr1, hdr2) - assert_equal(hdr1.binaryblock, hdr2.binaryblock) + assert hdr1 == hdr2 + assert hdr1.binaryblock == hdr2.binaryblock # Short binaryblocks give errors (here set through init) # Long binaryblocks are truncated - assert_raises(WrapStructError, - self.header_class, - bb[:self.header_class._hdrdtype.itemsize - 1]) + with pytest.raises(WrapStructError): + self.header_class(bb[:self.header_class._hdrdtype.itemsize - 1]) + # Checking set to true by default, and prevents nonsense being # set into the header. bb_bad = self.get_bad_bb() if bb_bad is None: return with imageglobals.LoggingOutputSuppressor(): - assert_raises(HeaderDataError, self.header_class, bb_bad) + with pytest.raises(HeaderDataError): + self.header_class(bb_bad) + # now slips past without check _ = self.header_class(bb_bad, check=False) def test_as_byteswapped(self): # Check byte swapping hdr = self.header_class() - assert_equal(hdr.endianness, '>') + assert hdr.endianness == '>' # same code just returns a copy for endianness in BIG_CODES: hdr2 = hdr.as_byteswapped(endianness) assert(hdr2 is not hdr) - assert_equal(hdr2, hdr) + assert hdr2 == hdr # Different code raises error for endianness in (None,) + LITTLE_CODES: - with assert_raises(ValueError): + with pytest.raises(ValueError): hdr.as_byteswapped(endianness) # Note that contents is not rechecked on swap / copy class DC(self.header_class): @@ -491,7 +493,9 @@ def check_fix(self, *args, **kwargs): raise Exception # Assumes check=True default - assert_raises(Exception, DC, hdr.binaryblock) + with pytest.raises(Exception): + DC(hdr.binaryblock) + hdr = DC(hdr.binaryblock, check=False) hdr2 = hdr.as_byteswapped('>') @@ -500,8 +504,8 @@ def test_checks(self): hdr_t = self.header_class() # _dxer just returns the diagnostics as a string # Default hdr is OK - assert_equal(self._dxer(hdr_t), '') + assert self._dxer(hdr_t) == '' # Version should be 1 hdr = hdr_t.copy() hdr['version'] = 2 - assert_equal(self._dxer(hdr), 'Unknown MGH format version') + assert self._dxer(hdr) == 'Unknown MGH format version' From e1bb16df9aea89f587070a9dd527991f46c6c491 Mon Sep 17 00:00:00 2001 From: orduek Date: Tue, 4 Feb 2020 17:55:23 -0500 Subject: [PATCH 081/223] small fixes --- nibabel/freesurfer/tests/test_io.py | 34 +++++++++++----------- nibabel/freesurfer/tests/test_mghformat.py | 3 +- 2 files changed, 18 insertions(+), 19 deletions(-) diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index cde2edeb5f..77a8bc12a0 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -51,18 +51,18 @@ def test_geometry(): """Test IO of .surf""" surf_path = pjoin(data_path, "surf", "%s.%s" % ("lh", "inflated")) coords, faces = read_geometry(surf_path) - assert 0==faces.min() - assert coords.shape[0]== faces.max() + 1 + assert 0 == faces.min() + assert coords.shape[0] == faces.max() + 1 surf_path = pjoin(data_path, "surf", "%s.%s" % ("lh", "sphere")) coords, faces, volume_info, create_stamp = read_geometry( surf_path, read_metadata=True, read_stamp=True) assert 0 == faces.min() - assert coords.shape[0] == faces.max() + 1 + assert coords.shape[0] == (faces.max() + 1) assert 9 == len(volume_info) assert [2, 0, 20] == volume_info['head'] - assert 'created by greve on Thu Jun 8 19:17:51 2006' == create_stamp + assert ['created by greve on Thu Jun 8 19:17:51 2006'] == create_stamp # Test equivalence of freesurfer- and nibabel-generated triangular files # with respect to read_geometry() @@ -121,7 +121,7 @@ def test_quad_geometry(): 'bert', 'surf', 'lh.inflated.nofix') coords, faces = read_geometry(new_quad) assert 0 == faces.min() - assert coords.shape[0] == faces.max() + 1 + assert coords.shape[0] == (faces.max() + 1) with InTemporaryDirectory(): new_path = 'test' write_geometry(new_path, coords, faces) @@ -135,8 +135,8 @@ def test_morph_data(): """Test IO of morphometry data file (eg. curvature).""" curv_path = pjoin(data_path, "surf", "%s.%s" % ("lh", "curv")) curv = read_morph_data(curv_path) - assert(-1.0 < curv.min() < 0) - assert(0 < curv.max() < 1.0) + assert -1.0 < curv.min() < 0 + assert 0 < curv.max() < 1.0 with InTemporaryDirectory(): new_path = 'test' write_morph_data(new_path, curv) @@ -175,8 +175,8 @@ def test_annot(): hash_ = _hash_file_content(annot_path) labels, ctab, names = read_annot(annot_path) - assert(labels.shape == (163842, )) - assert(ctab.shape == (len(names), 5)) + assert labels.shape == (163842, ) + assert ctab.shape == (len(names), 5) labels_orig = None if a == 'aparc': @@ -184,9 +184,9 @@ def test_annot(): np.testing.assert_array_equal(labels == -1, labels_orig == 0) # Handle different version of fsaverage if hash_ == 'bf0b488994657435cdddac5f107d21e8': - assert(np.sum(labels_orig == 0) == 13887) + assert np.sum(labels_orig == 0) == 13887 elif hash_ == 'd4f5b7cbc2ed363ac6fcf89e19353504': - assert(np.sum(labels_orig == 1639705) == 13327) + assert np.sum(labels_orig == 1639705) == 13327 else: raise RuntimeError("Unknown freesurfer file. Please report " "the problem to the maintainer of nibabel.") @@ -270,7 +270,7 @@ def test_write_annot_fill_ctab(): print(labels) with clear_and_catch_warnings() as w: write_annot(annot_path, labels, rgbal, names, fill_ctab=False) - assert( + assert ( any('Annotation values in {} will be incorrect'.format( annot_path) == str(ww.message) for ww in w)) labels2, rgbal2, names2 = read_annot(annot_path, orig_ids=True) @@ -346,13 +346,13 @@ def test_label(): label_path = pjoin(data_path, "label", "lh.cortex.label") label = read_label(label_path) # XXX : test more - assert(label.min() >= 0) - assert(label.max() <= 163841) - assert(label.shape[0] <= 163842) + assert label.min() >= 0 + assert label.max() <= 163841 + assert label.shape[0] <= 163842 labels, scalars = read_label(label_path, True) - assert(np.all(labels == label)) - assert(len(labels) == len(scalars)) + assert (np.all(labels == label)) + assert len(labels) == len(scalars) def test_write_annot_maxstruct(): diff --git a/nibabel/freesurfer/tests/test_mghformat.py b/nibabel/freesurfer/tests/test_mghformat.py index 3d96aa60f6..37b2faa2b4 100644 --- a/nibabel/freesurfer/tests/test_mghformat.py +++ b/nibabel/freesurfer/tests/test_mghformat.py @@ -26,8 +26,7 @@ import pytest -from numpy.testing import (assert_array_equal, - assert_array_almost_equal, assert_almost_equal) +from numpy.testing import (assert_array_equal, assert_array_almost_equal, assert_almost_equal) from ...testing_pytest import data_path From e763c896f72b488e1163fb9450147d4de0de8805 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 4 Feb 2020 21:57:25 -0500 Subject: [PATCH 082/223] TEST: Refactor NetCDF tests to be more pytest friendly --- .azure-pipelines/windows.yml | 1 + .travis.yml | 1 + nibabel/externals/tests/test_netcdf.py | 125 +++++++++++-------------- 3 files changed, 55 insertions(+), 72 deletions(-) diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index e64231c447..543a672e9f 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -80,6 +80,7 @@ jobs: -I test_minc2 ^ -I test_minc2_data ^ -I test_mriutils ^ + -I test_netcdf ^ -I test_nibabel_data ^ -I test_nifti1 ^ -I test_nifti2 ^ diff --git a/.travis.yml b/.travis.yml index f8333d39a7..792e88a907 100644 --- a/.travis.yml +++ b/.travis.yml @@ -173,6 +173,7 @@ script: -I test_minc2 \ -I test_minc2_data \ -I test_mriutils \ + -I test_netcdf \ -I test_nibabel_data \ -I test_nifti1 \ -I test_nifti2 \ diff --git a/nibabel/externals/tests/test_netcdf.py b/nibabel/externals/tests/test_netcdf.py index 289e6791c1..f85393be4e 100644 --- a/nibabel/externals/tests/test_netcdf.py +++ b/nibabel/externals/tests/test_netcdf.py @@ -2,20 +2,15 @@ import os from os.path import join as pjoin, dirname -import shutil -import tempfile -import time -import sys from io import BytesIO from glob import glob from contextlib import contextmanager import numpy as np -from numpy.testing import dec, assert_ -from ..netcdf import netcdf_file +import pytest -from nose.tools import assert_true, assert_false, assert_equal, assert_raises +from ..netcdf import netcdf_file TEST_DATA_PATH = pjoin(dirname(__file__), 'data') @@ -36,54 +31,41 @@ def make_simple(*args, **kwargs): f.close() -def gen_for_simple(ncfileobj): - ''' Generator for example fileobj tests ''' - yield assert_equal, ncfileobj.history, b'Created for a test' +def assert_simple_truths(ncfileobj): + assert ncfileobj.history == b'Created for a test' time = ncfileobj.variables['time'] - yield assert_equal, time.units, b'days since 2008-01-01' - yield assert_equal, time.shape, (N_EG_ELS,) - yield assert_equal, time[-1], N_EG_ELS-1 - - -def test_read_write_files(): - # test round trip for example file - cwd = os.getcwd() - try: - tmpdir = tempfile.mkdtemp() - os.chdir(tmpdir) - with make_simple('simple.nc', 'w') as f: - pass - # To read the NetCDF file we just created:: - with netcdf_file('simple.nc') as f: - # Using mmap is the default - yield assert_true, f.use_mmap - for testargs in gen_for_simple(f): - yield testargs - - # Now without mmap - with netcdf_file('simple.nc', mmap=False) as f: - # Using mmap is the default - yield assert_false, f.use_mmap - for testargs in gen_for_simple(f): - yield testargs - - # To read the NetCDF file we just created, as file object, no - # mmap. When n * n_bytes(var_type) is not divisible by 4, this - # raised an error in pupynere 1.0.12 and scipy rev 5893, because - # calculated vsize was rounding up in units of 4 - see - # https://www.unidata.ucar.edu/software/netcdf/docs/netcdf.html - fobj = open('simple.nc', 'rb') - with netcdf_file(fobj) as f: - # by default, don't use mmap for file-like - yield assert_false, f.use_mmap - for testargs in gen_for_simple(f): - yield testargs - except: - os.chdir(cwd) - shutil.rmtree(tmpdir) - raise - os.chdir(cwd) - shutil.rmtree(tmpdir) + assert time.units == b'days since 2008-01-01' + assert time.shape == (N_EG_ELS,) + assert time[-1] == N_EG_ELS - 1 + + +def test_read_write_files(tmp_path): + fname = str(tmp_path / 'simple.nc') + + with make_simple(fname, 'w') as f: + pass + # To read the NetCDF file we just created:: + with netcdf_file(fname) as f: + # Using mmap is the default + assert f.use_mmap + assert_simple_truths(f) + + # Now without mmap + with netcdf_file(fname, mmap=False) as f: + # Using mmap is the default + assert not f.use_mmap + assert_simple_truths(f) + + # To read the NetCDF file we just created, as file object, no + # mmap. When n * n_bytes(var_type) is not divisible by 4, this + # raised an error in pupynere 1.0.12 and scipy rev 5893, because + # calculated vsize was rounding up in units of 4 - see + # https://www.unidata.ucar.edu/software/netcdf/docs/netcdf.html + fobj = open(fname, 'rb') + with netcdf_file(fobj) as f: + # by default, don't use mmap for file-like + assert not f.use_mmap + assert_simple_truths(f) def test_read_write_sio(): @@ -93,12 +75,12 @@ def test_read_write_sio(): eg_sio2 = BytesIO(str_val) with netcdf_file(eg_sio2) as f2: - for testargs in gen_for_simple(f2): - yield testargs + assert_simple_truths(f2) # Test that error is raised if attempting mmap for sio eg_sio3 = BytesIO(str_val) - yield assert_raises, ValueError, netcdf_file, eg_sio3, 'r', True + with pytest.raises(ValueError): + netcdf_file(eg_sio3, 'r', True) # Test 64-bit offset write / read eg_sio_64 = BytesIO() with make_simple(eg_sio_64, 'w', version=2) as f_64: @@ -106,15 +88,13 @@ def test_read_write_sio(): eg_sio_64 = BytesIO(str_val) with netcdf_file(eg_sio_64) as f_64: - for testargs in gen_for_simple(f_64): - yield testargs - yield assert_equal, f_64.version_byte, 2 + assert_simple_truths(f_64) + assert f_64.version_byte == 2 # also when version 2 explicitly specified eg_sio_64 = BytesIO(str_val) with netcdf_file(eg_sio_64, version=2) as f_64: - for testargs in gen_for_simple(f_64): - yield testargs - yield assert_equal, f_64.version_byte, 2 + assert_simple_truths(f_64) + assert f_64.version_byte == 2 def test_read_example_data(): @@ -134,7 +114,8 @@ def test_itemset_no_segfault_on_readonly(): time_var = f.variables['time'] # time_var.assignValue(42) should raise a RuntimeError--not seg. fault! - assert_raises(RuntimeError, time_var.assignValue, 42) + with pytest.raises(RuntimeError): + time_var.assignValue(42) def test_write_invalid_dtype(): @@ -147,14 +128,14 @@ def test_write_invalid_dtype(): with netcdf_file(BytesIO(), 'w') as f: f.createDimension('time', N_EG_ELS) for dt in dtypes: - yield assert_raises, ValueError, \ - f.createVariable, 'time', dt, ('time',) + with pytest.raises(ValueError): + f.createVariable('time', dt, ('time',)) def test_flush_rewind(): stream = BytesIO() with make_simple(stream, mode='w') as f: - x = f.createDimension('x',4) + x = f.createDimension('x', 4) v = f.createVariable('v', 'i2', ['x']) v[:] = 1 f.flush() @@ -162,7 +143,7 @@ def test_flush_rewind(): f.flush() len_double = len(stream.getvalue()) - assert_(len_single == len_double) + assert len_single == len_double def test_dtype_specifiers(): @@ -192,8 +173,8 @@ def test_ticket_1720(): io = BytesIO(contents) with netcdf_file(io, 'r') as f: - assert_equal(f.history, b'Created for a test') + assert f.history == b'Created for a test' float_var = f.variables['float_var'] - assert_equal(float_var.units, b'metres') - assert_equal(float_var.shape, (10,)) - assert_(np.allclose(float_var[:], items)) + assert float_var.units == b'metres' + assert float_var.shape == (10,) + assert np.allclose(float_var[:], items) From 61f6ecf197f9929de90e438fbbfbb2b6afafe6f1 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Wed, 5 Feb 2020 10:36:04 -0500 Subject: [PATCH 083/223] CI: Resolve Travis warnings, remove redundant job --- .travis.yml | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/.travis.yml b/.travis.yml index f8333d39a7..b2bc55eb80 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,11 +4,11 @@ # for it to be on multiple physical lines, so long as you remember: - There # can't be any leading "-"s - All newlines will be removed, so use ";"s +os: linux dist: xenial -sudo: true language: python - cache: pip + env: global: - SETUP_REQUIRES="pip setuptools>=30.3.0 wheel" @@ -26,7 +26,7 @@ python: - 3.7 - 3.8 -matrix: +jobs: include: # Old nosetests - Remove soon - python: 3.7 @@ -36,11 +36,6 @@ matrix: - python: 3.5 env: - DEPENDS="-r requirements.txt" - # Clean install - - python: 3.5 - env: - - DEPENDS="" - - CHECK_TYPE=skiptests # Absolute minimum dependencies - python: 3.5 env: @@ -110,7 +105,6 @@ install: fi # Basic import check - python -c 'import nibabel; print(nibabel.__version__)' - - if [ "$CHECK_TYPE" == "skiptests" ]; then exit 0; fi before_script: # Point to nibabel data directory From a411f338422e08b3f04efd061848a3b8bb87d084 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 4 Feb 2020 22:11:13 -0500 Subject: [PATCH 084/223] TEST: Use skipif mark instead of TestMinc2API.__init__ --- nibabel/tests/test_image_api.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/nibabel/tests/test_image_api.py b/nibabel/tests/test_image_api.py index ee8c287df2..c24afea2eb 100644 --- a/nibabel/tests/test_image_api.py +++ b/nibabel/tests/test_image_api.py @@ -712,12 +712,8 @@ class TestMinc1API(ImageHeaderAPI): example_images = MINC1_EXAMPLE_IMAGES +@pytest.mark.skipif(not have_h5py, reason="Need h5py for Minc2 tests") class TestMinc2API(TestMinc1API): - - def __init__(self): - if not have_h5py: - pytest.skip('Need h5py for these tests') - klass = image_maker = Minc2Image loader = minc2.load example_images = MINC2_EXAMPLE_IMAGES From e1da57c200577f07a085f464d3d9828ad6c1f123 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 4 Feb 2020 22:11:55 -0500 Subject: [PATCH 085/223] TEST: Use standard syntax when possible --- nibabel/tests/test_image_api.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/nibabel/tests/test_image_api.py b/nibabel/tests/test_image_api.py index c24afea2eb..738a3f1969 100644 --- a/nibabel/tests/test_image_api.py +++ b/nibabel/tests/test_image_api.py @@ -108,7 +108,7 @@ def validate_header(self, imaker, params): hdr = img.header # we can fetch it # Read only with pytest.raises(AttributeError): - setattr(img, 'header', hdr) + img.header = hdr def validate_header_deprecated(self, imaker, params): # Check deprecated header API @@ -164,9 +164,9 @@ def validate_filenames(self, imaker, params): def validate_no_slicing(self, imaker, params): img = imaker() with pytest.raises(TypeError): - img.__getitem__('string') + img['string'] with pytest.raises(TypeError): - img.__getitem__(slice(None)) + img[:] def validate_get_data_deprecated(self, imaker, params): # Check deprecated header API @@ -231,10 +231,10 @@ def validate_data_interface(self, imaker, params): # dataobj is read only fake_data = np.zeros(img.shape).astype(img.get_data_dtype()) with pytest.raises(AttributeError): - setattr(img, 'dataobj', fake_data) + img.dataobj = fake_data # So is in_memory with pytest.raises(AttributeError): - setattr(img, 'in_memory', False) + img.in_memory = False def _check_proxy_interface(self, imaker, meth_name): # Parameters assert this is an array proxy @@ -402,7 +402,7 @@ def validate_data_deprecated(self, imaker, params): # Check setting _data raises error fake_data = np.zeros(img.shape).astype(img.get_data_dtype()) with pytest.raises(AttributeError): - setattr(img, '_data', fake_data) + img._data = fake_data def validate_shape(self, imaker, params): # Validate shape @@ -414,7 +414,7 @@ def validate_shape(self, imaker, params): assert img.shape == params['data'].shape # Read only with pytest.raises(AttributeError): - setattr(img, 'shape', np.eye(4)) + img.shape = np.eye(4) def validate_ndim(self, imaker, params): # Validate shape @@ -426,7 +426,7 @@ def validate_ndim(self, imaker, params): assert img.ndim == params['data'].ndim # Read only with pytest.raises(AttributeError): - setattr(img, 'ndim', 5) + img.ndim = 5 def validate_shape_deprecated(self, imaker, params): # Check deprecated get_shape API @@ -497,7 +497,7 @@ def validate_affine(self, imaker, params): assert img.affine[0, 0] == 1.5 # Read only with pytest.raises(AttributeError): - setattr(img, 'affine', np.eye(4)) + img.affine = np.eye(4) def validate_affine_deprecated(self, imaker, params): # Check deprecated affine API From dc9d82e596239818f4fb92ad494f4ead06f08b69 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 4 Feb 2020 22:17:59 -0500 Subject: [PATCH 086/223] TEST: Use relative imports in gifti tests --- nibabel/gifti/tests/test_gifti.py | 29 ++++++++++---------- nibabel/gifti/tests/test_parse_gifti_fast.py | 14 +++++----- 2 files changed, 21 insertions(+), 22 deletions(-) diff --git a/nibabel/gifti/tests/test_gifti.py b/nibabel/gifti/tests/test_gifti.py index 8a0b3d327d..5cb70019d8 100644 --- a/nibabel/gifti/tests/test_gifti.py +++ b/nibabel/gifti/tests/test_gifti.py @@ -6,27 +6,26 @@ import numpy as np -import nibabel as nib -from nibabel.gifti import (GiftiImage, GiftiDataArray, GiftiLabel, - GiftiLabelTable, GiftiMetaData, GiftiNVPairs, - GiftiCoordSystem) -from nibabel.gifti.gifti import data_tag -from nibabel.nifti1 import data_type_codes -from nibabel.fileholders import FileHolder - -from numpy.testing import (assert_array_almost_equal, - assert_array_equal) +from ... import load +from .. import (GiftiImage, GiftiDataArray, GiftiLabel, + GiftiLabelTable, GiftiMetaData, GiftiNVPairs, + GiftiCoordSystem) +from ..gifti import data_tag +from ...nifti1 import data_type_codes +from ...fileholders import FileHolder + +from numpy.testing import assert_array_almost_equal, assert_array_equal import pytest -from nibabel.testing import clear_and_catch_warnings, test_data +from ...testing_pytest import clear_and_catch_warnings, test_data from .test_parse_gifti_fast import (DATA_FILE1, DATA_FILE2, DATA_FILE3, DATA_FILE4, DATA_FILE5, DATA_FILE6) import itertools def test_agg_data(): - surf_gii_img = nib.load(test_data('gifti', 'ascii.gii')) - func_gii_img = nib.load(test_data('gifti', 'task.func.gii')) - shape_gii_img = nib.load(test_data('gifti', 'rh.shape.curv.gii')) + surf_gii_img = load(test_data('gifti', 'ascii.gii')) + func_gii_img = load(test_data('gifti', 'task.func.gii')) + shape_gii_img = load(test_data('gifti', 'rh.shape.curv.gii')) # add timeseries data with intent code ``none`` point_data = surf_gii_img.get_arrays_from_intent('pointset')[0].data @@ -296,7 +295,7 @@ def assign_rgba(gl, val): def test_print_summary(): for fil in [DATA_FILE1, DATA_FILE2, DATA_FILE3, DATA_FILE4, DATA_FILE5, DATA_FILE6]: - gimg = nib.load(fil) + gimg = load(fil) gimg.print_summary() diff --git a/nibabel/gifti/tests/test_parse_gifti_fast.py b/nibabel/gifti/tests/test_parse_gifti_fast.py index 15a2c69f1c..5e8150ac64 100644 --- a/nibabel/gifti/tests/test_parse_gifti_fast.py +++ b/nibabel/gifti/tests/test_parse_gifti_fast.py @@ -13,17 +13,17 @@ import numpy as np -import nibabel.gifti as gi -from nibabel.gifti.util import gifti_endian_codes -from nibabel.gifti.parse_gifti_fast import Outputter, parse_gifti_file -from nibabel.loadsave import load, save -from nibabel.nifti1 import xform_codes -from nibabel.tmpdirs import InTemporaryDirectory +from .. import gifti as gi +from ..util import gifti_endian_codes +from ..parse_gifti_fast import Outputter, parse_gifti_file +from ...loadsave import load, save +from ...nifti1 import xform_codes +from ...tmpdirs import InTemporaryDirectory from numpy.testing import assert_array_almost_equal import pytest -from ...testing import clear_and_catch_warnings +from ...testing_pytest import clear_and_catch_warnings IO_DATA_PATH = pjoin(dirname(__file__), 'data') From 42beb1a02d4eaf37b61c4623351ac4b0fb0160bb Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 4 Feb 2020 22:32:59 -0500 Subject: [PATCH 087/223] TEST: Simplify giftiio deprecation tests --- nibabel/gifti/tests/test_giftiio.py | 33 ++++++++--------------------- 1 file changed, 9 insertions(+), 24 deletions(-) diff --git a/nibabel/gifti/tests/test_giftiio.py b/nibabel/gifti/tests/test_giftiio.py index 87d28b00c4..8269618b0c 100644 --- a/nibabel/gifti/tests/test_giftiio.py +++ b/nibabel/gifti/tests/test_giftiio.py @@ -7,31 +7,16 @@ # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## -import warnings +from ..giftiio import read, write +from .test_parse_gifti_fast import DATA_FILE1 -from nibabel.testing import clear_and_catch_warnings -from nibabel.tmpdirs import InTemporaryDirectory +import pytest -from .test_parse_gifti_fast import (DATA_FILE1, DATA_FILE2, DATA_FILE3, - DATA_FILE4, DATA_FILE5, DATA_FILE6) - - -class TestGiftiIO(object): - - def setUp(self): - with clear_and_catch_warnings() as w: - warnings.simplefilter('always', DeprecationWarning) - assert len(w) == 1 - - -def test_read_deprecated(): - with clear_and_catch_warnings() as w: - warnings.simplefilter('always', DeprecationWarning) - from nibabel.gifti.giftiio import read, write - +def test_read_deprecated(tmp_path): + with pytest.deprecated_call(): img = read(DATA_FILE1) - assert len(w) == 1 - with InTemporaryDirectory(): - write(img, 'test.gii') - assert len(w) == 2 + + fname = tmp_path / 'test.gii' + with pytest.deprecated_call(): + write(img, fname) From 5d0f645dbcbfbb3f185032a16cc3bb297142901b Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 4 Feb 2020 22:42:31 -0500 Subject: [PATCH 088/223] TEST: Combine imports --- nibabel/streamlines/tests/test_trk.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/nibabel/streamlines/tests/test_trk.py b/nibabel/streamlines/tests/test_trk.py index f88631965e..736f61b820 100644 --- a/nibabel/streamlines/tests/test_trk.py +++ b/nibabel/streamlines/tests/test_trk.py @@ -8,8 +8,7 @@ from io import BytesIO import pytest -from ...testing_pytest import data_path -from ...testing_pytest import clear_and_catch_warnings, assert_arr_dict_equal +from ...testing_pytest import data_path, clear_and_catch_warnings, assert_arr_dict_equal from numpy.testing import assert_array_equal from .test_tractogram import assert_tractogram_equal From 979b4396a5b67a4b40ba6800a04a09f2f8790fe1 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Wed, 5 Feb 2020 11:02:04 -0500 Subject: [PATCH 089/223] TEST: Skip giftiio tests in nose --- .azure-pipelines/windows.yml | 1 + .travis.yml | 1 + 2 files changed, 2 insertions(+) diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index 543a672e9f..89b47b8345 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -68,6 +68,7 @@ jobs: -I test_fileutils ^ -I test_floating ^ -I test_funcs ^ + -I test_giftiio ^ -I test_h5py_compat ^ -I test_image_api ^ -I test_image_load_save ^ diff --git a/.travis.yml b/.travis.yml index c1e1ecc094..b869d33947 100644 --- a/.travis.yml +++ b/.travis.yml @@ -155,6 +155,7 @@ script: -I test_fileutils \ -I test_floating \ -I test_funcs \ + -I test_giftiio \ -I test_h5py_compat \ -I test_image_api \ -I test_image_load_save \ From 5fdeed9aadf9a397b211c1139b044095c16c1f25 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 09:53:26 -0500 Subject: [PATCH 090/223] converting more tests from nibabel.tests --- nibabel/tests/test_tripwire.py | 16 ++++++---------- nibabel/tests/test_viewers.py | 28 +++++++++++++++------------- 2 files changed, 21 insertions(+), 23 deletions(-) diff --git a/nibabel/tests/test_tripwire.py b/nibabel/tests/test_tripwire.py index 990f0bbf39..b69e913d4b 100644 --- a/nibabel/tests/test_tripwire.py +++ b/nibabel/tests/test_tripwire.py @@ -3,26 +3,22 @@ from ..tripwire import TripWire, is_tripwire, TripWireError -from nose.tools import (assert_true, assert_false, assert_raises, - assert_equal, assert_not_equal) -import pytest; pytestmark = pytest.mark.skip() +import pytest def test_is_tripwire(): - assert_false(is_tripwire(object())) - assert_true(is_tripwire(TripWire('some message'))) + assert not is_tripwire(object()) + assert is_tripwire(TripWire('some message')) def test_tripwire(): # Test tripwire object silly_module_name = TripWire('We do not have silly_module_name') - assert_raises(TripWireError, - getattr, - silly_module_name, - 'do_silly_thing') + with pytest.raises(TripWireError): + getattr(silly_module_name, 'do_silly_thing') # Check AttributeError can be checked too try: silly_module_name.__wrapped__ except TripWireError as err: - assert_true(isinstance(err, AttributeError)) + assert isinstance(err, AttributeError) else: raise RuntimeError("No error raised, but expected") diff --git a/nibabel/tests/test_viewers.py b/nibabel/tests/test_viewers.py index 0e3f076223..1be6e400a2 100644 --- a/nibabel/tests/test_viewers.py +++ b/nibabel/tests/test_viewers.py @@ -14,16 +14,13 @@ from ..optpkg import optional_package from ..viewers import OrthoSlicer3D -from ..testing import skipif from numpy.testing import assert_array_equal, assert_equal -from nose.tools import assert_raises, assert_true -import pytest; pytestmark = pytest.mark.skip() +import pytest # Need at least MPL 1.3 for viewer tests. matplotlib, has_mpl, _ = optional_package('matplotlib', min_version='1.3') - -needs_mpl = skipif(not has_mpl, 'These tests need matplotlib') +needs_mpl = pytest.mark.skipif(not has_mpl, reason='These tests need matplotlib') if has_mpl: matplotlib.use('Agg') @@ -38,7 +35,7 @@ def test_viewer(): data = data * np.array([1., 2.]) # give it a # of volumes > 1 v = OrthoSlicer3D(data) assert_array_equal(v.position, (0, 0, 0)) - assert_true('OrthoSlicer3D' in repr(v)) + assert 'OrthoSlicer3D' in repr(v) # fake some events, inside and outside axes v._on_scroll(nt('event', 'button inaxes key')('up', None, None)) @@ -53,8 +50,10 @@ def test_viewer(): v.set_volume_idx(1) v.cmap = 'hot' v.clim = (0, 3) - assert_raises(ValueError, OrthoSlicer3D.clim.fset, v, (0.,)) # bad limits - assert_raises(ValueError, OrthoSlicer3D.cmap.fset, v, 'foo') # wrong cmap + with pytest.raises(ValueError): + OrthoSlicer3D.clim.fset(v, (0.,)) # bad limits + with pytest.raises(ValueError): + OrthoSlicer3D.cmap.fset(v, 'foo') # wrong cmap # decrement/increment volume numbers via keypress v.set_volume_idx(1) # should just pass @@ -76,8 +75,8 @@ def test_viewer(): v.close() # complex input should raise a TypeError prior to figure creation - assert_raises(TypeError, OrthoSlicer3D, - data[:, :, :, 0].astype(np.complex64)) + with pytest.raises(TypeError): + OrthoSlicer3D(data[:, :, :, 0].astype(np.complex64)) # other cases fig, axes = plt.subplots(1, 4) @@ -87,10 +86,13 @@ def test_viewer(): float) v2 = OrthoSlicer3D(data, affine=aff, axes=axes[:3]) # bad data (not 3+ dim) - assert_raises(ValueError, OrthoSlicer3D, data[:, :, 0, 0]) + with pytest.raises(ValueError): + OrthoSlicer3D(data[:, :, 0, 0]) # bad affine (not 4x4) - assert_raises(ValueError, OrthoSlicer3D, data, affine=np.eye(3)) - assert_raises(TypeError, v2.link_to, 1) + with pytest.raises(ValueError): + OrthoSlicer3D(data, affine=np.eye(3)) + with pytest.raises(TypeError): + v2.link_to(1) v2.link_to(v1) v2.link_to(v1) # shouldn't do anything v1.close() From 1a435fa521535e8f136fb29f99403d333bf873a0 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:45:57 -0500 Subject: [PATCH 091/223] converting nibabel/tests/test_scripts.py --- nibabel/tests/test_scripts.py | 198 +++++++++++++++++----------------- 1 file changed, 98 insertions(+), 100 deletions(-) diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 5e7defdaa5..db83a4d3f5 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -20,10 +20,8 @@ from ..loadsave import load from ..orientations import flip_axis, aff2axcodes, inv_ornt_aff -from nose.tools import assert_true, assert_false, assert_equal -from nose import SkipTest - -from numpy.testing import assert_almost_equal, assert_array_equal +import pytest +from numpy.testing import assert_almost_equal from .scriptrunner import ScriptRunner from .nibabel_data import needs_nibabel_data @@ -33,7 +31,6 @@ from .test_parrec_data import BALLS, AFF_OFF from ..testing_pytest import assert_data_similar -import pytest; pytestmark = pytest.mark.skip() def _proc_stdout(stdout): stdout_str = stdout.decode('latin1').strip() @@ -56,6 +53,14 @@ def script_test(func): DATA_PATH = abspath(pjoin(dirname(__file__), 'data')) +def load_small_file(): + try: + load(pjoin(DATA_PATH, 'small.mnc')) + return True + except: + return False + + def check_nib_ls_example4d(opts=[], hdrs_str="", other_str=""): # test nib-ls script fname = pjoin(DATA_PATH, 'example4d.nii.gz') @@ -64,7 +69,7 @@ def check_nib_ls_example4d(opts=[], hdrs_str="", other_str=""): % (hdrs_str, other_str)) cmd = ['nib-ls'] + opts + [fname] code, stdout, stderr = run_command(cmd) - assert_equal(fname, stdout[:len(fname)]) + assert fname == stdout[:len(fname)] assert_re_in(expected_re, stdout[len(fname):]) @@ -77,45 +82,45 @@ def check_nib_diff_examples(): "quatern_c", "quatern_d", "qoffset_x", "qoffset_y", "qoffset_z", "srow_x", "srow_y", "srow_z", "DATA(md5)", "DATA(diff 1:)"] for item in checked_fields: - assert_true(item in stdout) + assert item in stdout fnames2 = [pjoin(DATA_PATH, f) for f in ('example4d.nii.gz', 'example4d.nii.gz')] code, stdout, stderr = run_command(['nib-diff'] + fnames2, check_code=False) - assert_equal(stdout, "These files are identical.") + assert stdout == "These files are identical." fnames3 = [pjoin(DATA_PATH, f) for f in ('standard.nii.gz', 'example4d.nii.gz', 'example_nifti2.nii.gz')] code, stdout, stderr = run_command(['nib-diff'] + fnames3, check_code=False) for item in checked_fields: - assert_true(item in stdout) + assert item in stdout fnames4 = [pjoin(DATA_PATH, f) for f in ('standard.nii.gz', 'standard.nii.gz', 'standard.nii.gz')] code, stdout, stderr = run_command(['nib-diff'] + fnames4, check_code=False) - assert_equal(stdout, "These files are identical.") + assert stdout == "These files are identical." code, stdout, stderr = run_command(['nib-diff', '--dt', 'float64'] + fnames, check_code=False) for item in checked_fields: - assert_true(item in stdout) + assert item in stdout - -@script_test -def test_nib_ls(): - yield check_nib_ls_example4d - yield check_nib_ls_example4d, \ - ['-H', 'dim,bitpix'], " \[ 4 128 96 24 2 1 1 1\] 16" - yield check_nib_ls_example4d, ['-c'], "", " !1030 uniques. Use --all-counts" - yield check_nib_ls_example4d, ['-c', '--all-counts'], "", " 2:3 3:2 4:1 5:1.*" +@pytest.mark.parametrize("args", [ + [], + [['-H', 'dim,bitpix'], " \[ 4 128 96 24 2 1 1 1\] 16"], + [['-c'], "", " !1030 uniques. Use --all-counts"], + [['-c', '--all-counts'], "", " 2:3 3:2 4:1 5:1.*"], # both stats and counts - yield check_nib_ls_example4d, \ - ['-c', '-s', '--all-counts'], "", " \[229725\] \[2, 1.2e\+03\] 2:3 3:2 4:1 5:1.*" + [['-c', '-s', '--all-counts'], "", " \[229725\] \[2, 1.2e\+03\] 2:3 3:2 4:1 5:1.*"], # and must not error out if we allow for zeros - yield check_nib_ls_example4d, \ - ['-c', '-s', '-z', '--all-counts'], "", " \[589824\] \[0, 1.2e\+03\] 0:360099 2:3 3:2 4:1 5:1.*" + [['-c', '-s', '-z', '--all-counts'], "", " \[589824\] \[0, 1.2e\+03\] 0:360099 2:3 3:2 4:1 5:1.*"], +]) +@script_test +def test_nib_ls(args): + check_nib_ls_example4d(*args) +@pytest.mark.skipif(not load_small_file(), reason="can't load the small.mnc file") @script_test def test_nib_ls_multiple(): # verify that correctly lists/formats for multiple files @@ -126,42 +131,35 @@ def test_nib_ls_multiple(): ] code, stdout, stderr = run_command(['nib-ls'] + fnames) stdout_lines = stdout.split('\n') - assert_equal(len(stdout_lines), 4) - try: - load(pjoin(DATA_PATH, 'small.mnc')) - except: - raise SkipTest("For the other tests should be able to load MINC files") + assert len(stdout_lines) == 4 # they should be indented correctly. Since all files are int type - ln = max(len(f) for f in fnames) i_str = ' i' if sys.byteorder == 'little' else ' Date: Tue, 4 Feb 2020 11:46:26 -0500 Subject: [PATCH 092/223] adding todo --- nibabel/tests/nibabel_data.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 529e103f46..453c0af9ec 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' - +# dj-TODO def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data From 9e6cac1432fad5cd22d6412831084c93277d0d06 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 14:50:03 -0500 Subject: [PATCH 093/223] converting more tests nibabel.tests.test_s* --- nibabel/tests/test_spaces.py | 54 ++-- nibabel/tests/test_spatialimages.py | 370 ++++++++++++++-------------- nibabel/tests/test_spm2analyze.py | 12 +- nibabel/tests/test_spm99analyze.py | 57 +++-- 4 files changed, 254 insertions(+), 239 deletions(-) diff --git a/nibabel/tests/test_spaces.py b/nibabel/tests/test_spaces.py index 119ecfd5c3..5459571954 100644 --- a/nibabel/tests/test_spaces.py +++ b/nibabel/tests/test_spaces.py @@ -9,13 +9,9 @@ from ..nifti1 import Nifti1Image from ..eulerangles import euler2mat +import pytest +from numpy.testing import assert_almost_equal -from numpy.testing import (assert_almost_equal, - assert_array_equal) - -from nose.tools import (assert_true, assert_false, assert_raises, - assert_equal, assert_not_equal) -import pytest; pytestmark = pytest.mark.skip() def assert_all_in(in_shape, in_affine, out_shape, out_affine): slices = tuple(slice(N) for N in in_shape) @@ -30,8 +26,8 @@ def assert_all_in(in_shape, in_affine, out_shape, out_affine): v2v = new_v2v out_grid = apply_affine(v2v, in_grid) TINY = 1e-12 - assert_true(np.all(out_grid > -TINY)) - assert_true(np.all(out_grid < np.array(out_shape) + TINY)) + assert np.all(out_grid > -TINY) + assert np.all(out_grid < np.array(out_shape) + TINY) def get_outspace_params(): @@ -80,27 +76,32 @@ def get_outspace_params(): ) -def test_vox2out_vox(): +@pytest.mark.parametrize("arg_tuple", [ + # Enforce number of axes + ((2, 3, 4, 5), np.eye(4)), + ((2, 3, 4, 5, 6), np.eye(4)), + # Voxel sizes must be positive + ((2, 3, 4), np.eye(4), [-1, 1, 1]), + ((2, 3, 4), np.eye(4), [1, 0, 1]) +]) +def test_vox2out_vox(arg_tuple): # Test world space bounding box # Test basic case, identity, no voxel sizes passed shape, aff = vox2out_vox(((2, 3, 4), np.eye(4))) - assert_array_equal(shape, (2, 3, 4)) - assert_array_equal(aff, np.eye(4)) + assert shape == (2, 3, 4) + assert (aff == np.eye(4)).all() for in_shape, in_aff, vox, out_shape, out_aff in get_outspace_params(): img = Nifti1Image(np.ones(in_shape), in_aff) for input in ((in_shape, in_aff), img): shape, aff = vox2out_vox(input, vox) assert_all_in(in_shape, in_aff, shape, aff) - assert_equal(shape, out_shape) + assert shape == out_shape assert_almost_equal(aff, out_aff) - assert_true(isinstance(shape, tuple)) - assert_true(isinstance(shape[0], int)) + assert isinstance(shape, tuple) + assert isinstance(shape[0], int) # Enforce number of axes - assert_raises(ValueError, vox2out_vox, ((2, 3, 4, 5), np.eye(4))) - assert_raises(ValueError, vox2out_vox, ((2, 3, 4, 5, 6), np.eye(4))) - # Voxel sizes must be positive - assert_raises(ValueError, vox2out_vox, ((2, 3, 4), np.eye(4), [-1, 1, 1])) - assert_raises(ValueError, vox2out_vox, ((2, 3, 4), np.eye(4), [1, 0, 1])) + with pytest.raises(ValueError): + vox2out_vox(arg_tuple) def test_slice2volume(): @@ -112,7 +113,14 @@ def test_slice2volume(): for val in (0, 5, 10): exp_aff = np.array(def_aff) exp_aff[axis, -1] = val - assert_array_equal(slice2volume(val, axis), exp_aff) - assert_raises(ValueError, slice2volume, -1, 0) - assert_raises(ValueError, slice2volume, 0, -1) - assert_raises(ValueError, slice2volume, 0, 3) + assert (slice2volume(val, axis) == exp_aff).all() + + +@pytest.mark.parametrize("args", [ + [-1, 0], + [0, -1], + [0, 3] +]) +def test_slice2volume_exception(args): + with pytest.raises(ValueError): + slice2volume(*args) \ No newline at end of file diff --git a/nibabel/tests/test_spatialimages.py b/nibabel/tests/test_spatialimages.py index 5b4706bea1..288096638e 100644 --- a/nibabel/tests/test_spatialimages.py +++ b/nibabel/tests/test_spatialimages.py @@ -15,58 +15,59 @@ import numpy as np from io import BytesIO -from ..spatialimages import (SpatialHeader, SpatialImage, HeaderDataError, - Header, ImageDataError) +from ..spatialimages import SpatialHeader, SpatialImage, HeaderDataError, Header from ..imageclasses import spatial_axes_first +import pytest from unittest import TestCase -from nose.tools import (assert_true, assert_false, assert_equal, - assert_not_equal, assert_raises) -from numpy.testing import assert_array_equal, assert_array_almost_equal, assert_warns +from numpy.testing import assert_array_almost_equal + +from ..testing_pytest import ( + bytesio_round_trip, + clear_and_catch_warnings, + suppress_warnings, + memmap_after_ufunc +) -from ..testing import (clear_and_catch_warnings, suppress_warnings, - memmap_after_ufunc) -from ..testing_pytest import bytesio_round_trip from ..tmpdirs import InTemporaryDirectory from ..deprecator import ExpiredDeprecationError from .. import load as top_load -import pytest; pytestmark = pytest.mark.skip() def test_header_init(): # test the basic header hdr = Header() - assert_equal(hdr.get_data_dtype(), np.dtype(np.float32)) - assert_equal(hdr.get_data_shape(), (0,)) - assert_equal(hdr.get_zooms(), (1.0,)) + assert hdr.get_data_dtype() == np.dtype(np.float32) + assert hdr.get_data_shape() == (0,) + assert hdr.get_zooms() == (1.0,) hdr = Header(np.float64) - assert_equal(hdr.get_data_dtype(), np.dtype(np.float64)) - assert_equal(hdr.get_data_shape(), (0,)) - assert_equal(hdr.get_zooms(), (1.0,)) + assert hdr.get_data_dtype() == np.dtype(np.float64) + assert hdr.get_data_shape() == (0,) + assert hdr.get_zooms() == (1.0,) hdr = Header(np.float64, shape=(1, 2, 3)) - assert_equal(hdr.get_data_dtype(), np.dtype(np.float64)) - assert_equal(hdr.get_data_shape(), (1, 2, 3)) - assert_equal(hdr.get_zooms(), (1.0, 1.0, 1.0)) + assert hdr.get_data_dtype() == np.dtype(np.float64) + assert hdr.get_data_shape() == (1, 2, 3) + assert hdr.get_zooms() == (1.0, 1.0, 1.0) hdr = Header(np.float64, shape=(1, 2, 3), zooms=None) - assert_equal(hdr.get_data_dtype(), np.dtype(np.float64)) - assert_equal(hdr.get_data_shape(), (1, 2, 3)) - assert_equal(hdr.get_zooms(), (1.0, 1.0, 1.0)) + assert hdr.get_data_dtype() == np.dtype(np.float64) + assert hdr.get_data_shape() == (1, 2, 3) + assert hdr.get_zooms() == (1.0, 1.0, 1.0) hdr = Header(np.float64, shape=(1, 2, 3), zooms=(3.0, 2.0, 1.0)) - assert_equal(hdr.get_data_dtype(), np.dtype(np.float64)) - assert_equal(hdr.get_data_shape(), (1, 2, 3)) - assert_equal(hdr.get_zooms(), (3.0, 2.0, 1.0)) + assert hdr.get_data_dtype() == np.dtype(np.float64) + assert hdr.get_data_shape() == (1, 2, 3) + assert hdr.get_zooms() == (3.0, 2.0, 1.0) def test_from_header(): # check from header class method. Note equality checks below, # equality methods used here too. empty = Header.from_header() - assert_equal(Header(), empty) + assert Header() == empty empty = Header.from_header(None) - assert_equal(Header(), empty) + assert Header() == empty hdr = Header(np.float64, shape=(1, 2, 3), zooms=(3.0, 2.0, 1.0)) copy = Header.from_header(hdr) - assert_equal(hdr, copy) - assert_false(hdr is copy) + assert hdr == copy + assert not hdr is copy class C(object): @@ -76,25 +77,25 @@ def get_data_shape(self): return (5, 4, 3) def get_zooms(self): return (10.0, 9.0, 8.0) converted = Header.from_header(C()) - assert_true(isinstance(converted, Header)) - assert_equal(converted.get_data_dtype(), np.dtype('u2')) - assert_equal(converted.get_data_shape(), (5, 4, 3)) - assert_equal(converted.get_zooms(), (10.0, 9.0, 8.0)) + assert isinstance(converted, Header) + assert converted.get_data_dtype() == np.dtype('u2') + assert converted.get_data_shape() == (5, 4, 3) + assert converted.get_zooms() == (10.0, 9.0, 8.0) def test_eq(): hdr = Header() other = Header() - assert_equal(hdr, other) + assert hdr == other other = Header('u2') - assert_not_equal(hdr, other) + assert hdr != other other = Header(shape=(1, 2, 3)) - assert_not_equal(hdr, other) + assert hdr != other hdr = Header(shape=(1, 2)) other = Header(shape=(1, 2)) - assert_equal(hdr, other) + assert hdr == other other = Header(shape=(1, 2), zooms=(2.0, 3.0)) - assert_not_equal(hdr, other) + assert hdr != other def test_copy(): @@ -102,51 +103,50 @@ def test_copy(): hdr = Header(np.float64, shape=(1, 2, 3), zooms=(3.0, 2.0, 1.0)) hdr_copy = hdr.copy() hdr.set_data_shape((4, 5, 6)) - assert_equal(hdr.get_data_shape(), (4, 5, 6)) - assert_equal(hdr_copy.get_data_shape(), (1, 2, 3)) + assert hdr.get_data_shape() == (4, 5, 6) + assert hdr_copy.get_data_shape() == (1, 2, 3) hdr.set_zooms((4, 5, 6)) - assert_equal(hdr.get_zooms(), (4, 5, 6)) - assert_equal(hdr_copy.get_zooms(), (3, 2, 1)) + assert hdr.get_zooms() == (4, 5, 6) + assert hdr_copy.get_zooms() == (3, 2, 1) hdr.set_data_dtype(np.uint8) - assert_equal(hdr.get_data_dtype(), np.dtype(np.uint8)) - assert_equal(hdr_copy.get_data_dtype(), np.dtype(np.float64)) + assert hdr.get_data_dtype() == np.dtype(np.uint8) + assert hdr_copy.get_data_dtype() == np.dtype(np.float64) def test_shape_zooms(): hdr = Header() hdr.set_data_shape((1, 2, 3)) - assert_equal(hdr.get_data_shape(), (1, 2, 3)) - assert_equal(hdr.get_zooms(), (1.0, 1.0, 1.0)) + assert hdr.get_data_shape() == (1, 2, 3) + assert hdr.get_zooms() == (1.0, 1.0, 1.0) hdr.set_zooms((4, 3, 2)) - assert_equal(hdr.get_zooms(), (4.0, 3.0, 2.0)) + assert hdr.get_zooms() == (4.0, 3.0, 2.0) hdr.set_data_shape((1, 2)) - assert_equal(hdr.get_data_shape(), (1, 2)) - assert_equal(hdr.get_zooms(), (4.0, 3.0)) + assert hdr.get_data_shape() == (1, 2) + assert hdr.get_zooms() == (4.0, 3.0) hdr.set_data_shape((1, 2, 3)) - assert_equal(hdr.get_data_shape(), (1, 2, 3)) - assert_equal(hdr.get_zooms(), (4.0, 3.0, 1.0)) + assert hdr.get_data_shape() == (1, 2, 3) + assert hdr.get_zooms() == (4.0, 3.0, 1.0) # null shape is (0,) hdr.set_data_shape(()) - assert_equal(hdr.get_data_shape(), (0,)) - assert_equal(hdr.get_zooms(), (1.0,)) + assert hdr.get_data_shape() == (0,) + assert hdr.get_zooms() == (1.0,) # zooms of wrong lengths raise error - assert_raises(HeaderDataError, hdr.set_zooms, (4.0, 3.0)) - assert_raises(HeaderDataError, - hdr.set_zooms, - (4.0, 3.0, 2.0, 1.0)) + with pytest.raises(HeaderDataError): + hdr.set_zooms((4.0, 3.0)) + with pytest.raises(HeaderDataError): + hdr.set_zooms((4.0, 3.0, 2.0, 1.0)) # as do negative zooms - assert_raises(HeaderDataError, - hdr.set_zooms, - (4.0, 3.0, -2.0)) + with pytest.raises(HeaderDataError): + hdr.set_zooms((4.0, 3.0, -2.0)) def test_data_dtype(): hdr = Header() - assert_equal(hdr.get_data_dtype(), np.dtype(np.float32)) + assert hdr.get_data_dtype() == np.dtype(np.float32) hdr.set_data_dtype(np.float64) - assert_equal(hdr.get_data_dtype(), np.dtype(np.float64)) + assert hdr.get_data_dtype() == np.dtype(np.float64) hdr.set_data_dtype('u2') - assert_equal(hdr.get_data_dtype(), np.dtype(np.uint16)) + assert hdr.get_data_dtype() == np.dtype(np.uint16) def test_affine(): @@ -162,8 +162,7 @@ def test_affine(): [0, 2, 0, -1], [0, 0, 1, -1], [0, 0, 0, 1]]) - assert_array_equal(hdr.get_base_affine(), - hdr.get_best_affine()) + assert (hdr.get_base_affine() == hdr.get_best_affine()).all() def test_read_data(): @@ -174,22 +173,22 @@ class CHeader(SpatialHeader): fobj = BytesIO() data = np.arange(6).reshape((1, 2, 3)) hdr.data_to_fileobj(data, fobj) - assert_equal(fobj.getvalue(), + assert (fobj.getvalue() == data.astype(np.int32).tostring(order=order)) # data_to_fileobj accepts kwarg 'rescale', but no effect in this case fobj.seek(0) hdr.data_to_fileobj(data, fobj, rescale=True) - assert_equal(fobj.getvalue(), + assert (fobj.getvalue() == data.astype(np.int32).tostring(order=order)) # data_to_fileobj can be a list fobj.seek(0) hdr.data_to_fileobj(data.tolist(), fobj, rescale=True) - assert_equal(fobj.getvalue(), + assert (fobj.getvalue() == data.astype(np.int32).tostring(order=order)) # Read data back again fobj.seek(0) data2 = hdr.data_from_fileobj(fobj) - assert_array_equal(data, data2) + assert (data == data2).all() class DataLike(object): @@ -211,33 +210,33 @@ def test_isolation(self): arr = np.arange(24, dtype=np.int16).reshape((2, 3, 4)) aff = np.eye(4) img = img_klass(arr, aff) - assert_array_equal(img.affine, aff) + assert (img.affine == aff).all() aff[0, 0] = 99 - assert_false(np.all(img.affine == aff)) + assert not np.all(img.affine == aff) # header, created by image creation ihdr = img.header # Pass it back in img = img_klass(arr, aff, ihdr) # Check modifying header outside does not modify image ihdr.set_zooms((4, 5, 6)) - assert_not_equal(img.header, ihdr) + assert img.header != ihdr def test_float_affine(self): # Check affines get converted to float img_klass = self.image_class arr = np.arange(3, dtype=np.int16) img = img_klass(arr, np.eye(4, dtype=np.float32)) - assert_equal(img.affine.dtype, np.dtype(np.float64)) + assert img.affine.dtype == np.dtype(np.float64) img = img_klass(arr, np.eye(4, dtype=np.int16)) - assert_equal(img.affine.dtype, np.dtype(np.float64)) + assert img.affine.dtype == np.dtype(np.float64) def test_images(self): # Assumes all possible images support int16 # See https://github.com/nipy/nibabel/issues/58 arr = np.arange(24, dtype=np.int16).reshape((2, 3, 4)) img = self.image_class(arr, None) - assert_array_equal(img.get_fdata(), arr) - assert_equal(img.affine, None) + assert (img.get_fdata() == arr).all() + assert img.affine == None def test_default_header(self): # Check default header is as expected @@ -246,21 +245,21 @@ def test_default_header(self): hdr = self.image_class.header_class() hdr.set_data_shape(arr.shape) hdr.set_data_dtype(arr.dtype) - assert_equal(img.header, hdr) + assert img.header == hdr def test_data_api(self): # Test minimal api data object can initialize img = self.image_class(DataLike(), None) # Shape may be promoted to higher dimension, but may not reorder or # change size - assert_array_equal(img.get_fdata().flatten(), np.arange(3)) - assert_equal(img.shape[:1], (3,)) - assert_equal(np.prod(img.shape), 3) + assert (img.get_fdata().flatten() == np.arange(3)).all() + assert img.shape[:1] == (3,) + assert np.prod(img.shape) == 3 def check_dtypes(self, expected, actual): # Some images will want dtypes to be equal including endianness, # others may only require the same type - assert_equal(expected, actual) + assert expected == actual def test_data_default(self): # check that the default dtype comes from the data if the header @@ -285,10 +284,10 @@ def test_data_shape(self): img = img_klass(arr, np.eye(4)) # Shape may be promoted to higher dimension, but may not reorder or # change size - assert_equal(img.shape[:1], (4,)) - assert_equal(np.prod(img.shape), 4) + assert img.shape[:1] == (4,) + assert np.prod(img.shape) == 4 img = img_klass(np.zeros((2, 3, 4), dtype=np.float32), np.eye(4)) - assert_equal(img.shape, (2, 3, 4)) + assert img.shape == (2, 3, 4) def test_str(self): # Check something comes back from string representation @@ -297,13 +296,13 @@ def test_str(self): # See https://github.com/nipy/nibabel/issues/58 arr = np.arange(5, dtype=np.int16) img = img_klass(arr, np.eye(4)) - assert_true(len(str(img)) > 0) + assert len(str(img)) > 0 # Shape may be promoted to higher dimension, but may not reorder or # change size - assert_equal(img.shape[:1], (5,)) - assert_equal(np.prod(img.shape), 5) + assert img.shape[:1] == (5,) + assert np.prod(img.shape) == 5 img = img_klass(np.zeros((2, 3, 4), dtype=np.int16), np.eye(4)) - assert_true(len(str(img)) > 0) + assert len(str(img)) > 0 def test_get_shape(self): # Check that get_shape raises an ExpiredDeprecationError @@ -311,7 +310,7 @@ def test_get_shape(self): # Assumes all possible images support int16 # See https://github.com/nipy/nibabel/issues/58 img = img_klass(np.arange(1, dtype=np.int16), np.eye(4)) - with assert_raises(ExpiredDeprecationError): + with pytest.raises(ExpiredDeprecationError): img.get_shape() def test_get_fdata(self): @@ -320,55 +319,57 @@ def test_get_fdata(self): in_data_template = np.arange(24, dtype=np.int16).reshape((2, 3, 4)) in_data = in_data_template.copy() img = img_klass(in_data, None) - assert_true(in_data is img.dataobj) + assert in_data is img.dataobj # The get_fdata method changes the array to floating point type - assert_equal(img.get_fdata(dtype='f4').dtype, np.dtype(np.float32)) + assert img.get_fdata(dtype='f4').dtype == np.dtype(np.float32) fdata_32 = img.get_fdata(dtype=np.float32) - assert_equal(fdata_32.dtype, np.dtype(np.float32)) + assert fdata_32.dtype == np.dtype(np.float32) # Caching is specific to data dtype. If we reload with default data # type, the cache gets reset fdata_32[:] = 99 # Cache has been modified, we pick up the modifications, but only for # the cached data type - assert_array_equal(img.get_fdata(dtype='f4'), 99) + assert (img.get_fdata(dtype='f4') == 99).all() fdata_64 = img.get_fdata() - assert_equal(fdata_64.dtype, np.dtype(np.float64)) - assert_array_equal(fdata_64, in_data) + assert fdata_64.dtype == np.dtype(np.float64) + assert (fdata_64 == in_data).all() fdata_64[:] = 101 - assert_array_equal(img.get_fdata(dtype='f8'), 101) - assert_array_equal(img.get_fdata(), 101) + assert (img.get_fdata(dtype='f8') == 101).all() + assert (img.get_fdata() == 101).all() # Reloading with new data type blew away the float32 cache - assert_array_equal(img.get_fdata(dtype='f4'), in_data) + assert (img.get_fdata(dtype='f4') == in_data).all() img.uncache() # Now recaching, is float64 out_data = img.get_fdata() - assert_equal(out_data.dtype, np.dtype(np.float64)) + assert out_data.dtype == np.dtype(np.float64) # Input dtype needs to be floating point - assert_raises(ValueError, img.get_fdata, dtype=np.int16) - assert_raises(ValueError, img.get_fdata, dtype=np.int32) + with pytest.raises(ValueError): + img.get_fdata(dtype=np.int16) + with pytest.raises(ValueError): + img.get_fdata(dtype=np.int32) # The cache is filled out_data[:] = 42 - assert_true(img.get_fdata() is out_data) + assert img.get_fdata() is out_data img.uncache() - assert_false(img.get_fdata() is out_data) + assert not img.get_fdata() is out_data # The 42 has gone now. - assert_array_equal(img.get_fdata(), in_data_template) + assert (img.get_fdata() == in_data_template).all() # If we can save, we can create a proxy image if not self.can_save: return rt_img = bytesio_round_trip(img) - assert_false(in_data is rt_img.dataobj) - assert_array_equal(rt_img.dataobj, in_data) + assert not in_data is rt_img.dataobj + assert (rt_img.dataobj == in_data).all() out_data = rt_img.get_fdata() - assert_array_equal(out_data, in_data) - assert_false(rt_img.dataobj is out_data) - assert_equal(out_data.dtype, np.dtype(np.float64)) + assert (out_data == in_data).all() + assert not rt_img.dataobj is out_data + assert out_data.dtype == np.dtype(np.float64) # cache - assert_true(rt_img.get_fdata() is out_data) + assert rt_img.get_fdata() is out_data out_data[:] = 42 rt_img.uncache() - assert_false(rt_img.get_fdata() is out_data) - assert_array_equal(rt_img.get_fdata(), in_data) + assert not rt_img.get_fdata() is out_data + assert (rt_img.get_fdata() == in_data).all() def test_get_data(self): # Test array image and proxy image interface @@ -377,41 +378,41 @@ def test_get_data(self): in_data = in_data_template.copy() img = img_klass(in_data, None) # Can't slice into the image object: - with assert_raises(TypeError) as exception_manager: + with pytest.raises(TypeError) as exception_manager: img[0, 0, 0] # Make sure the right message gets raised: - assert_equal(str(exception_manager.exception), + assert (str(exception_manager.value) == "Cannot slice image objects; consider using " "`img.slicer[slice]` to generate a sliced image (see " "documentation for caveats) or slicing image array data " "with `img.dataobj[slice]` or `img.get_fdata()[slice]`") - assert_true(in_data is img.dataobj) - with assert_warns(DeprecationWarning): + assert in_data is img.dataobj + with pytest.warns(DeprecationWarning): out_data = img.get_data() - assert_true(in_data is out_data) + assert in_data is out_data # and that uncache has no effect img.uncache() - assert_true(in_data is out_data) - assert_array_equal(out_data, in_data_template) + assert in_data is out_data + assert (out_data == in_data_template).all() # If we can save, we can create a proxy image if not self.can_save: return rt_img = bytesio_round_trip(img) - assert_false(in_data is rt_img.dataobj) - assert_array_equal(rt_img.dataobj, in_data) - with assert_warns(DeprecationWarning): + assert not in_data is rt_img.dataobj + assert (rt_img.dataobj == in_data).all() + with pytest.warns(DeprecationWarning): out_data = rt_img.get_data() - assert_array_equal(out_data, in_data) - assert_false(rt_img.dataobj is out_data) + assert (out_data == in_data).all() + assert not rt_img.dataobj is out_data # cache - with assert_warns(DeprecationWarning): - assert_true(rt_img.get_data() is out_data) + with pytest.warns(DeprecationWarning): + assert rt_img.get_data() is out_data out_data[:] = 42 rt_img.uncache() - with assert_warns(DeprecationWarning): - assert_false(rt_img.get_data() is out_data) - with assert_warns(DeprecationWarning): - assert_array_equal(rt_img.get_data(), in_data) + with pytest.warns(DeprecationWarning): + assert not rt_img.get_data() is out_data + with pytest.warns(DeprecationWarning): + assert (rt_img.get_data() == in_data).all() def test_slicer(self): img_klass = self.image_class @@ -424,11 +425,11 @@ def test_slicer(self): img = img_klass(in_data, base_affine.copy()) if not spatial_axes_first(img): - with assert_raises(ValueError): + with pytest.raises(ValueError): img.slicer continue - assert_true(hasattr(img.slicer, '__getitem__')) + assert hasattr(img.slicer, '__getitem__') # Note spatial zooms are always first 3, even when spatial_zooms = img.header.get_zooms()[:3] @@ -437,49 +438,49 @@ def test_slicer(self): sliceobj = [slice(None, None, 2)] * 3 + \ [slice(None)] * (len(dshape) - 3) downsampled_img = img.slicer[tuple(sliceobj)] - assert_array_equal(downsampled_img.header.get_zooms()[:3], - np.array(spatial_zooms) * 2) + assert (downsampled_img.header.get_zooms()[:3] + == np.array(spatial_zooms) * 2).all() max4d = (hasattr(img.header, '_structarr') and 'dims' in img.header._structarr.dtype.fields and img.header._structarr['dims'].shape == (4,)) # Check newaxis and single-slice errors - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[None] - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[0] # Axes 1 and 2 are always spatial - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[:, None] - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[:, 0] - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[:, :, None] - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[:, :, 0] if len(img.shape) == 4: if max4d: - with assert_raises(ValueError): + with pytest.raises(ValueError): img.slicer[:, :, :, None] else: # Reorder non-spatial axes - assert_equal(img.slicer[:, :, :, None].shape, + assert (img.slicer[:, :, :, None].shape == img.shape[:3] + (1,) + img.shape[3:]) # 4D to 3D using ellipsis or slices - assert_equal(img.slicer[..., 0].shape, img.shape[:-1]) - assert_equal(img.slicer[:, :, :, 0].shape, img.shape[:-1]) + assert img.slicer[..., 0].shape == img.shape[:-1] + assert img.slicer[:, :, :, 0].shape == img.shape[:-1] else: # 3D Analyze/NIfTI/MGH to 4D - assert_equal(img.slicer[:, :, :, None].shape, img.shape + (1,)) + assert img.slicer[:, :, :, None].shape == img.shape + (1,) if len(img.shape) == 3: # Slices exceed dimensions - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[:, :, :, :, None] elif max4d: - with assert_raises(ValueError): + with pytest.raises(ValueError): img.slicer[:, :, :, :, None] else: - assert_equal(img.slicer[:, :, :, :, None].shape, + assert (img.slicer[:, :, :, :, None].shape == img.shape + (1,)) # Crop by one voxel in each dimension @@ -489,35 +490,35 @@ def test_slicer(self): sliced_ijk = img.slicer[1:, 1:, 1:] # No scaling change - assert_array_equal(sliced_i.affine[:3, :3], img.affine[:3, :3]) - assert_array_equal(sliced_j.affine[:3, :3], img.affine[:3, :3]) - assert_array_equal(sliced_k.affine[:3, :3], img.affine[:3, :3]) - assert_array_equal(sliced_ijk.affine[:3, :3], img.affine[:3, :3]) + assert (sliced_i.affine[:3, :3] == img.affine[:3, :3]).all() + assert (sliced_j.affine[:3, :3] == img.affine[:3, :3]).all() + assert (sliced_k.affine[:3, :3] == img.affine[:3, :3]).all() + assert (sliced_ijk.affine[:3, :3] == img.affine[:3, :3]).all() # Translation - assert_array_equal(sliced_i.affine[:, 3], [1, 0, 0, 1]) - assert_array_equal(sliced_j.affine[:, 3], [0, 1, 0, 1]) - assert_array_equal(sliced_k.affine[:, 3], [0, 0, 1, 1]) - assert_array_equal(sliced_ijk.affine[:, 3], [1, 1, 1, 1]) + assert (sliced_i.affine[:, 3] == [1, 0, 0, 1]).all() + assert (sliced_j.affine[:, 3] == [0, 1, 0, 1]).all() + assert (sliced_k.affine[:, 3] == [0, 0, 1, 1]).all() + assert (sliced_ijk.affine[:, 3] == [1, 1, 1, 1]).all() # No change to affines with upper-bound slices - assert_array_equal(img.slicer[:1, :1, :1].affine, img.affine) + assert (img.slicer[:1, :1, :1].affine == img.affine).all() # Yell about step = 0 - with assert_raises(ValueError): + with pytest.raises(ValueError): img.slicer[:, ::0] - with assert_raises(ValueError): + with pytest.raises(ValueError): img.slicer.slice_affine((slice(None), slice(None, None, 0))) # Don't permit zero-length slices - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[:0] # No fancy indexing - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[[0]] - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[[-1]] - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[[0], [-1]] # Check data is consistent with slicing numpy arrays @@ -534,14 +535,14 @@ def test_slicer(self): pass else: sliced_data = in_data[sliceobj] - with assert_warns(DeprecationWarning): - assert_array_equal(sliced_data, sliced_img.get_data()) - assert_array_equal(sliced_data, sliced_img.get_fdata()) - assert_array_equal(sliced_data, sliced_img.dataobj) - assert_array_equal(sliced_data, img.dataobj[sliceobj]) - with assert_warns(DeprecationWarning): - assert_array_equal(sliced_data, img.get_data()[sliceobj]) - assert_array_equal(sliced_data, img.get_fdata()[sliceobj]) + with pytest.warns(DeprecationWarning): + assert (sliced_data == sliced_img.get_data()).all() + assert (sliced_data == sliced_img.get_fdata()).all() + assert (sliced_data == sliced_img.dataobj).all() + assert (sliced_data == img.dataobj[sliceobj]).all() + with pytest.warns(DeprecationWarning): + assert (sliced_data == img.get_data()[sliceobj]).all() + assert (sliced_data == img.get_fdata()[sliceobj]).all() def test_api_deprecations(self): @@ -563,13 +564,13 @@ def from_file_map(self, file_map=None): bio = BytesIO() file_map = FakeImage.make_file_map({'image': bio}) - with assert_raises(ExpiredDeprecationError): + with pytest.raises(ExpiredDeprecationError): img.to_files(file_map) - with assert_raises(ExpiredDeprecationError): + with pytest.raises(ExpiredDeprecationError): img.to_filespec('an_image') - with assert_raises(ExpiredDeprecationError): + with pytest.raises(ExpiredDeprecationError): FakeImage.from_files(file_map) - with assert_raises(ExpiredDeprecationError): + with pytest.raises(ExpiredDeprecationError): FakeImage.filespec_to_files('an_image') @@ -634,19 +635,20 @@ def test_load_mmap(self): back_img = func(param1, **kwargs) back_data = np.asanyarray(back_img.dataobj) if expected_mode is None: - assert_false(isinstance(back_data, np.memmap), - 'Should not be a %s' % img_klass.__name__) + assert not isinstance(back_data, np.memmap), 'Should not be a %s' % img_klass.__name__ else: - assert_true(isinstance(back_data, np.memmap), - 'Not a %s' % img_klass.__name__) + assert isinstance(back_data, np.memmap), 'Not a %s' % img_klass.__name__ if self.check_mmap_mode: - assert_equal(back_data.mode, expected_mode) + assert back_data.mode == expected_mode del back_img, back_data # Check that mmap is keyword-only - assert_raises(TypeError, func, param1, True) + with pytest.raises(TypeError): + func(param1, True) # Check invalid values raise error - assert_raises(ValueError, func, param1, mmap='rw') - assert_raises(ValueError, func, param1, mmap='r+') + with pytest.raises(ValueError): + func(param1, mmap='rw') + with pytest.raises(ValueError): + func(param1, mmap='r+') def test_header_deprecated(): @@ -655,7 +657,7 @@ def test_header_deprecated(): class MyHeader(Header): pass - assert_equal(len(w), 0) + assert len(w) == 0 MyHeader() - assert_equal(len(w), 1) + assert len(w) == 1 diff --git a/nibabel/tests/test_spm2analyze.py b/nibabel/tests/test_spm2analyze.py index ddf2956f7d..a88d3cafd4 100644 --- a/nibabel/tests/test_spm2analyze.py +++ b/nibabel/tests/test_spm2analyze.py @@ -13,19 +13,18 @@ from ..spatialimages import HeaderTypeError, HeaderDataError from ..spm2analyze import Spm2AnalyzeHeader, Spm2AnalyzeImage +import pytest from numpy.testing import assert_array_equal -from ..testing import assert_equal, assert_raises from . import test_spm99analyze -import pytest; pytestmark = pytest.mark.skip() class TestSpm2AnalyzeHeader(test_spm99analyze.TestSpm99AnalyzeHeader): header_class = Spm2AnalyzeHeader def test_slope_inter(self): hdr = self.header_class() - assert_equal(hdr.get_slope_inter(), (1.0, 0.0)) + assert hdr.get_slope_inter() == (1.0, 0.0) for in_tup, exp_err, out_tup, raw_slope in ( ((2.0,), None, (2.0, 0.), 2.), ((None,), None, (None, None), np.nan), @@ -43,16 +42,17 @@ def test_slope_inter(self): ((None, 0.0), None, (None, None), np.nan)): hdr = self.header_class() if not exp_err is None: - assert_raises(exp_err, hdr.set_slope_inter, *in_tup) + with pytest.raises(exp_err): + hdr.set_slope_inter(*in_tup) # raw set if not in_tup[0] is None: hdr['scl_slope'] = in_tup[0] else: hdr.set_slope_inter(*in_tup) - assert_equal(hdr.get_slope_inter(), out_tup) + assert hdr.get_slope_inter() == out_tup # Check set survives through checking hdr = Spm2AnalyzeHeader.from_header(hdr, check=True) - assert_equal(hdr.get_slope_inter(), out_tup) + assert hdr.get_slope_inter() == out_tup assert_array_equal(hdr['scl_slope'], raw_slope) diff --git a/nibabel/tests/test_spm99analyze.py b/nibabel/tests/test_spm99analyze.py index ecc63e5935..e1d559878a 100644 --- a/nibabel/tests/test_spm99analyze.py +++ b/nibabel/tests/test_spm99analyze.py @@ -12,13 +12,15 @@ from io import BytesIO -from numpy.testing import assert_array_equal, assert_array_almost_equal, dec +from numpy.testing import assert_array_equal, assert_array_almost_equal +import pytest # Decorator to skip tests requiring save / load if scipy not available for mat # files from ..optpkg import optional_package _, have_scipy, _ = optional_package('scipy') -scipy_skip = dec.skipif(not have_scipy, 'scipy not available') + +scipy_skip = pytest.mark.skipif(not have_scipy, reason='scipy not available') from ..spm99analyze import (Spm99AnalyzeHeader, Spm99AnalyzeImage, HeaderTypeError) @@ -26,13 +28,14 @@ from ..volumeutils import apply_read_scaling, _dt_min_max from ..spatialimages import supported_np_types, HeaderDataError -from nose.tools import assert_true, assert_false, assert_equal, assert_raises - -from ..testing import assert_allclose_safely, suppress_warnings -from ..testing_pytest import bytesio_round_trip, bytesio_filemap +from ..testing_pytest import ( + bytesio_round_trip, + bytesio_filemap, + assert_allclose_safely, + suppress_warnings +) from . import test_analyze -import pytest; pytestmark = pytest.mark.skip() FLOAT_TYPES = np.sctypes['float'] COMPLEX_TYPES = np.sctypes['complex'] @@ -62,7 +65,7 @@ def test_data_scaling(self): # almost equal assert_array_almost_equal(data, data_back, 4) # But not quite - assert_false(np.all(data == data_back)) + assert not np.all(data == data_back) # This is exactly the same call, just testing it works twice data_back2 = hdr.data_from_fileobj(S3) assert_array_equal(data_back, data_back2, 4) @@ -70,12 +73,12 @@ def test_data_scaling(self): hdr.data_to_fileobj(data, S3, rescale=True) data_back = hdr.data_from_fileobj(S3) assert_array_almost_equal(data, data_back, 4) - assert_false(np.all(data == data_back)) + assert not np.all(data == data_back) # This doesn't use scaling, and so gets perfect precision with np.errstate(invalid='ignore'): hdr.data_to_fileobj(data, S3, rescale=False) data_back = hdr.data_from_fileobj(S3) - assert_true(np.all(data == data_back)) + assert np.all(data == data_back) class TestSpm99AnalyzeHeader(test_analyze.TestAnalyzeHeader, @@ -85,7 +88,7 @@ class TestSpm99AnalyzeHeader(test_analyze.TestAnalyzeHeader, def test_empty(self): super(TestSpm99AnalyzeHeader, self).test_empty() hdr = self.header_class() - assert_equal(hdr['scl_slope'], 1) + assert hdr['scl_slope'] == 1 def test_big_scaling(self): # Test that upcasting works for huge scalefactors @@ -99,11 +102,11 @@ def test_big_scaling(self): data = np.array([type_info(dtt)['max']], dtype=dtt)[:, None, None] hdr.data_to_fileobj(data, sio) data_back = hdr.data_from_fileobj(sio) - assert_true(np.allclose(data, data_back)) + assert np.allclose(data, data_back) def test_slope_inter(self): hdr = self.header_class() - assert_equal(hdr.get_slope_inter(), (1.0, None)) + assert hdr.get_slope_inter() == (1.0, None) for in_tup, exp_err, out_tup, raw_slope in ( ((2.0,), None, (2.0, None), 2.), ((None,), None, (None, None), np.nan), @@ -121,16 +124,17 @@ def test_slope_inter(self): ((None, 0.0), None, (None, None), np.nan)): hdr = self.header_class() if not exp_err is None: - assert_raises(exp_err, hdr.set_slope_inter, *in_tup) + with pytest.raises(exp_err): + hdr.set_slope_inter(*in_tup) # raw set if not in_tup[0] is None: hdr['scl_slope'] = in_tup[0] else: hdr.set_slope_inter(*in_tup) - assert_equal(hdr.get_slope_inter(), out_tup) + assert hdr.get_slope_inter() == out_tup # Check set survives through checking hdr = Spm99AnalyzeHeader.from_header(hdr, check=True) - assert_equal(hdr.get_slope_inter(), out_tup) + assert hdr.get_slope_inter() == out_tup assert_array_equal(hdr['scl_slope'], raw_slope) def test_origin_checks(self): @@ -140,14 +144,15 @@ def test_origin_checks(self): hdr.data_shape = [1, 1, 1] hdr['origin'][0] = 101 # severity 20 fhdr, message, raiser = self.log_chk(hdr, 20) - assert_equal(fhdr, hdr) - assert_equal(message, 'very large origin values ' + assert fhdr == hdr + assert (message == 'very large origin values ' 'relative to dims; leaving as set, ' 'ignoring for affine') - assert_raises(*raiser) + with pytest.raises(raiser[0]): + raiser[1](*raiser[2:]) # diagnose binary block dxer = self.header_class.diagnose_binaryblock - assert_equal(dxer(hdr.binaryblock), + assert (dxer(hdr.binaryblock) == 'very large origin values ' 'relative to dims') @@ -166,9 +171,9 @@ def assert_scale_me_scaling(self, hdr): # Assert that header `hdr` has "scale-me" scaling slope, inter = self._get_raw_scaling(hdr) if not slope is None: - assert_true(np.isnan(slope)) + assert np.isnan(slope) if not inter is None: - assert_true(np.isnan(inter)) + assert np.isnan(inter) def _get_raw_scaling(self, hdr): return hdr['scl_slope'], None @@ -399,7 +404,7 @@ def test_nan2zero_range_ok(self): img.set_data_dtype(np.uint8) with np.errstate(invalid='ignore'): rt_img = bytesio_round_trip(img) - assert_equal(rt_img.get_fdata()[0, 0, 0], 0) + assert rt_img.get_fdata()[0, 0, 0] == 0 class TestSpm99AnalyzeImage(test_analyze.TestAnalyzeImage, ImageScalingMixin): @@ -460,7 +465,7 @@ def test_mat_read(self): from scipy.io import loadmat, savemat mat_fileobj.seek(0) mats = loadmat(mat_fileobj) - assert_true('M' in mats and 'mat' in mats) + assert 'M' in mats and 'mat' in mats from_111 = np.eye(4) from_111[:3, 3] = -1 to_111 = np.eye(4) @@ -471,7 +476,7 @@ def test_mat_read(self): # should have a flip. The 'mat' matrix does include flips and so # should be unaffected by the flipping. If both are present we prefer # the the 'mat' matrix. - assert_true(img.header.default_x_flip) # check the default + assert img.header.default_x_flip # check the default flipper = np.diag([-1, 1, 1, 1]) assert_array_equal(mats['M'], np.dot(aff, np.dot(flipper, from_111))) mat_fileobj.seek(0) @@ -513,7 +518,7 @@ def test_origin_affine(): assert_array_equal(aff, hdr.get_base_affine()) hdr.set_data_shape((3, 5, 7)) hdr.set_zooms((3, 2, 1)) - assert_true(hdr.default_x_flip) + assert hdr.default_x_flip assert_array_almost_equal( hdr.get_origin_affine(), # from center of image [[-3., 0., 0., 3.], From 393f630e342710a2bd5bf44910abffd37617692c Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 15:31:41 -0500 Subject: [PATCH 094/223] converting more tests nibabel.tests.test_t* --- nibabel/tests/test_testing.py | 103 ++++++++------- nibabel/tests/test_tmpdirs.py | 12 +- nibabel/tests/test_trackvis.py | 233 +++++++++++++++++---------------- 3 files changed, 183 insertions(+), 165 deletions(-) diff --git a/nibabel/tests/test_testing.py b/nibabel/tests/test_testing.py index 171447560e..65880c2833 100644 --- a/nibabel/tests/test_testing.py +++ b/nibabel/tests/test_testing.py @@ -7,11 +7,10 @@ import numpy as np -from nose.tools import assert_equal, assert_true, assert_false, assert_raises -from ..testing import (error_warnings, suppress_warnings, +from ..testing_pytest import (error_warnings, suppress_warnings, clear_and_catch_warnings, assert_allclose_safely, get_fresh_mod, assert_re_in, test_data, data_path) -import pytest; pytestmark = pytest.mark.skip() +import pytest def test_assert_allclose_safely(): # Test the safe version of allclose @@ -19,7 +18,8 @@ def test_assert_allclose_safely(): assert_allclose_safely(1, 1) assert_allclose_safely(1, [1, 1]) assert_allclose_safely([1, 1], 1 + 1e-6) - assert_raises(AssertionError, assert_allclose_safely, [1, 1], 1 + 1e-4) + with pytest.raises(AssertionError): + assert_allclose_safely([1, 1], 1 + 1e-4) # Broadcastable matrices a = np.ones((2, 3)) b = np.ones((3, 2, 3)) @@ -27,24 +27,26 @@ def test_assert_allclose_safely(): a[0, 0] = 1 + eps assert_allclose_safely(a, b) a[0, 0] = 1 + 1.1e-5 - assert_raises(AssertionError, assert_allclose_safely, a, b) + with pytest.raises(AssertionError): + assert_allclose_safely(a, b) # Nans in same place a[0, 0] = np.nan b[:, 0, 0] = np.nan assert_allclose_safely(a, b) # Never equal with nans present, if not matching nans - assert_raises(AssertionError, - assert_allclose_safely, a, b, - match_nans=False) + with pytest.raises(AssertionError): + assert_allclose_safely(a, b, match_nans=False) b[0, 0, 0] = 1 - assert_raises(AssertionError, assert_allclose_safely, a, b) + with pytest.raises(AssertionError): + assert_allclose_safely(a, b) # Test allcloseness of inf, especially np.float128 infs for dtt in np.sctypes['float']: a = np.array([-np.inf, 1, np.inf], dtype=dtt) b = np.array([-np.inf, 1, np.inf], dtype=dtt) assert_allclose_safely(a, b) b[1] = 0 - assert_raises(AssertionError, assert_allclose_safely, a, b) + with pytest.raises(AssertionError): + assert_allclose_safely(a, b) # Empty compares equal to empty assert_allclose_safely([], []) @@ -56,19 +58,19 @@ def assert_warn_len_equal(mod, n_in_context): # warning generated by the tests within the context manager, but no # previous warnings. if 'version' in mod_warns: - assert_equal(len(mod_warns), 2) # including 'version' + assert len(mod_warns) == 2 # including 'version' else: - assert_equal(len(mod_warns), n_in_context) + assert len(mod_warns) == n_in_context def test_clear_and_catch_warnings(): # Initial state of module, no warnings my_mod = get_fresh_mod(__name__) - assert_equal(getattr(my_mod, '__warningregistry__', {}), {}) + assert getattr(my_mod, '__warningregistry__', {}) == {} with clear_and_catch_warnings(modules=[my_mod]): warnings.simplefilter('ignore') warnings.warn('Some warning') - assert_equal(my_mod.__warningregistry__, {}) + assert my_mod.__warningregistry__ == {} # Without specified modules, don't clear warnings during context with clear_and_catch_warnings(): warnings.warn('Some warning') @@ -94,23 +96,26 @@ def test_clear_and_catch_warnings_inherit(): with my_cacw(): warnings.simplefilter('ignore') warnings.warn('Some warning') - assert_equal(my_mod.__warningregistry__, {}) + assert my_mod.__warningregistry__ == {} def test_warn_error(): # Check warning error context manager n_warns = len(warnings.filters) with error_warnings(): - assert_raises(UserWarning, warnings.warn, 'A test') + with pytest.raises(UserWarning): + warnings.warn('A test') with error_warnings() as w: # w not used for anything - assert_raises(UserWarning, warnings.warn, 'A test') - assert_equal(n_warns, len(warnings.filters)) + with pytest.raises(UserWarning): + warnings.warn('A test') + assert n_warns == len(warnings.filters) # Check other errors are propagated def f(): with error_warnings(): raise ValueError('An error') - assert_raises(ValueError, f) + with pytest.raises(ValueError): + f() def test_warn_ignore(): @@ -122,54 +127,60 @@ def test_warn_ignore(): with suppress_warnings() as w: # w not used warnings.warn('Here is a warning, you will not see it') warnings.warn('Nor this one', DeprecationWarning) - assert_equal(n_warns, len(warnings.filters)) + assert n_warns == len(warnings.filters) # Check other errors are propagated def f(): with suppress_warnings(): raise ValueError('An error') - assert_raises(ValueError, f) - - -def test_assert_re_in(): - assert_re_in(".*", "") - assert_re_in(".*", ["any"]) - - # Should do match not search - assert_re_in("ab", "abc") - assert_raises(AssertionError, assert_re_in, "ab", "cab") - assert_raises(AssertionError, assert_re_in, "ab$", "abc") + with pytest.raises(ValueError): + f() +@pytest.mark.parametrize("args", [ + [".*", ""], + [".*", ["any"]], + ["ab", "abc"], # Sufficient to have one entry matching - assert_re_in("ab", ["", "abc", "laskdjf"]) - assert_raises(AssertionError, assert_re_in, "ab$", ["ddd", ""]) - + ["ab", ["", "abc", "laskdjf"]], # Tuples should be ok too - assert_re_in("ab", ("", "abc", "laskdjf")) - assert_raises(AssertionError, assert_re_in, "ab$", ("ddd", "")) + ["ab", ("", "abc", "laskdjf")] +]) +def test_assert_re_in(args): + assert_re_in(*args) - # Shouldn't "match" the empty list - assert_raises(AssertionError, assert_re_in, "", []) + +@pytest.mark.parametrize("args", [ + # Should do match not search + ["ab", "cab"], + ["ab$", "abc"], + ["ab$", ["ddd", ""]], + ["ab$", ("ddd", "")], + #Shouldn't "match" the empty list + ["", []] +]) +def test_assert_re_in_exception(args): + with pytest.raises(AssertionError): + assert_re_in(*args) def test_test_data(): - assert_equal(test_data(), data_path) - assert_equal(test_data(), + assert test_data() == data_path + assert (test_data() == os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'tests', 'data'))) for subdir in ('nicom', 'gifti', 'externals'): - assert_equal(test_data(subdir), os.path.join(data_path[:-10], subdir, 'tests', 'data')) - assert_true(os.path.exists(test_data(subdir))) - assert_false(os.path.exists(test_data(subdir, 'doesnotexist'))) + assert test_data(subdir) == os.path.join(data_path[:-10], subdir, 'tests', 'data') + assert os.path.exists(test_data(subdir)) + assert not os.path.exists(test_data(subdir, 'doesnotexist')) for subdir in ('freesurfer', 'doesnotexist'): - with assert_raises(ValueError): + with pytest.raises(ValueError): test_data(subdir) - assert_false(os.path.exists(test_data(None, 'doesnotexist'))) + assert not os.path.exists(test_data(None, 'doesnotexist')) for subdir, fname in [('gifti', 'ascii.gii'), ('nicom', '0.dcm'), ('externals', 'example_1.nc'), (None, 'empty.tck')]: - assert_true(os.path.exists(test_data(subdir, fname))) + assert os.path.exists(test_data(subdir, fname)) diff --git a/nibabel/tests/test_tmpdirs.py b/nibabel/tests/test_tmpdirs.py index 7914e273e1..c4d119b14f 100644 --- a/nibabel/tests/test_tmpdirs.py +++ b/nibabel/tests/test_tmpdirs.py @@ -5,8 +5,6 @@ from ..tmpdirs import InGivenDirectory -from nose.tools import assert_true, assert_equal -import pytest; pytestmark = pytest.mark.skip() MY_PATH = abspath(__file__) MY_DIR = dirname(MY_PATH) @@ -16,10 +14,10 @@ def test_given_directory(): # Test InGivenDirectory cwd = getcwd() with InGivenDirectory() as tmpdir: - assert_equal(tmpdir, abspath(cwd)) - assert_equal(tmpdir, abspath(getcwd())) + assert tmpdir == abspath(cwd) + assert tmpdir == abspath(getcwd()) with InGivenDirectory(MY_DIR) as tmpdir: - assert_equal(tmpdir, MY_DIR) - assert_equal(realpath(MY_DIR), realpath(abspath(getcwd()))) + assert tmpdir == MY_DIR + assert realpath(MY_DIR) == realpath(abspath(getcwd())) # We were deleting the Given directory! Check not so now. - assert_true(isfile(MY_PATH)) + assert isfile(MY_PATH) diff --git a/nibabel/tests/test_trackvis.py b/nibabel/tests/test_trackvis.py index 676ee52d87..15675882eb 100644 --- a/nibabel/tests/test_trackvis.py +++ b/nibabel/tests/test_trackvis.py @@ -9,16 +9,14 @@ from ..orientations import aff2axcodes from ..volumeutils import native_code, swapped_code -from numpy.testing import assert_array_almost_equal -from ..testing import (assert_true, assert_false, assert_equal, assert_raises, assert_warns, - assert_array_equal, suppress_warnings) -import pytest; pytestmark = pytest.mark.skip() +from numpy.testing import assert_array_almost_equal, assert_array_equal +import pytest def test_write(): streams = [] out_f = BytesIO() tv.write(out_f, [], {}) - assert_equal(out_f.getvalue(), tv.empty_header().tostring()) + assert out_f.getvalue() == tv.empty_header().tostring() out_f.truncate(0) out_f.seek(0) # Write something not-default @@ -26,7 +24,7 @@ def test_write(): # read it back out_f.seek(0) streams, hdr = tv.read(out_f) - assert_equal(hdr['id_string'], b'TRACKb') + assert hdr['id_string'] == b'TRACKb' # check that we can pass none for the header out_f.truncate(0) out_f.seek(0) @@ -37,12 +35,12 @@ def test_write(): # check that we check input values out_f.truncate(0) out_f.seek(0) - assert_raises(tv.HeaderError, - tv.write, out_f, [], {'id_string': 'not OK'}) - assert_raises(tv.HeaderError, - tv.write, out_f, [], {'version': 3}) - assert_raises(tv.HeaderError, - tv.write, out_f, [], {'hdr_size': 0}) + with pytest.raises(tv.HeaderError): + tv.write(out_f, [], {'id_string': 'not OK'}) + with pytest.raises(tv.HeaderError): + tv.write(out_f, [], {'version': 3}) + with pytest.raises(tv.HeaderError): + tv.write(out_f, [], {'hdr_size': 0}) def test_write_scalars_props(): @@ -57,26 +55,31 @@ def test_write_scalars_props(): out_f = BytesIO() streams = [(points, None, None), (points, scalars, None)] - assert_raises(tv.DataError, tv.write, out_f, streams) + with pytest.raises(tv.DataError): + tv.write(out_f, streams) out_f.seek(0) streams = [(points, np.zeros((N, M + 1)), None), (points, scalars, None)] - assert_raises(tv.DataError, tv.write, out_f, streams) + with pytest.raises(tv.DataError): + tv.write(out_f, streams) # Or if scalars different N compared to points bad_scalars = np.zeros((N + 1, M)) out_f.seek(0) streams = [(points, bad_scalars, None), (points, bad_scalars, None)] - assert_raises(tv.DataError, tv.write, out_f, streams) + with pytest.raises(tv.DataError): + tv.write(out_f, streams) # Similarly properties must have the same length for each streamline out_f.seek(0) streams = [(points, scalars, None), (points, scalars, props)] - assert_raises(tv.DataError, tv.write, out_f, streams) + with pytest.raises(tv.DataError): + tv.write(out_f, streams) out_f.seek(0) streams = [(points, scalars, np.zeros((P + 1,))), (points, scalars, props)] - assert_raises(tv.DataError, tv.write, out_f, streams) + with pytest.raises(tv.DataError): + tv.write(out_f, streams) # If all is OK, then we get back what we put in out_f.seek(0) streams = [(points, scalars, props), @@ -134,7 +137,7 @@ def test_round_trip(): tv.write(out_f, streams, {}) out_f.seek(0) streams2, hdr = tv.read(out_f) - assert_true(streamlist_equal(streams, streams2)) + assert streamlist_equal(streams, streams2) # test that we can write in different endianness and get back same result, # for versions 1, 2 and not-specified for in_dict, back_version in (({}, 2), @@ -145,15 +148,15 @@ def test_round_trip(): tv.write(out_f, streams, in_dict, endian_code) out_f.seek(0) streams2, hdr = tv.read(out_f) - assert_true(streamlist_equal(streams, streams2)) - assert_equal(hdr['version'], back_version) + assert streamlist_equal(streams, streams2) + assert hdr['version'] == back_version # test that we can get out and pass in generators out_f.seek(0) streams3, hdr = tv.read(out_f, as_generator=True) # check this is a generator rather than a list - assert_true(hasattr(streams3, 'send')) + assert hasattr(streams3, 'send') # but that it results in the same output - assert_true(streamlist_equal(streams, list(streams3))) + assert streamlist_equal(streams, list(streams3)) # write back in out_f.seek(0) streams3, hdr = tv.read(out_f, as_generator=True) @@ -164,7 +167,7 @@ def test_round_trip(): # and re-read just to check out_f_write.seek(0) streams2, hdr = tv.read(out_f_write) - assert_true(streamlist_equal(streams, streams2)) + assert streamlist_equal(streams, streams2) def test_points_processing(): @@ -192,11 +195,11 @@ def _rt(streams, hdr, points_space): # voxmm is the default. In this case we don't do anything to the # points, and we let the header pass through without further checks (raw_streams, hdr), (proc_streams, _) = _rt(vxmm_streams, {}, None) - assert_true(streamlist_equal(raw_streams, proc_streams)) - assert_true(streamlist_equal(vxmm_streams, proc_streams)) + assert streamlist_equal(raw_streams, proc_streams) + assert streamlist_equal(vxmm_streams, proc_streams) (raw_streams, hdr), (proc_streams, _) = _rt(vxmm_streams, {}, 'voxmm') - assert_true(streamlist_equal(raw_streams, proc_streams)) - assert_true(streamlist_equal(vxmm_streams, proc_streams)) + assert streamlist_equal(raw_streams, proc_streams) + assert streamlist_equal(vxmm_streams, proc_streams) # with 'voxels' as input, check for not all voxel_size == 0, warn if any # voxel_size == 0 for hdr in ( # these cause read / write errors @@ -207,21 +210,23 @@ def _rt(streams, hdr, points_space): ): # Check error on write out_f.seek(0) - assert_raises(tv.HeaderError, - tv.write, out_f, vx_streams, hdr, None, 'voxel') + with pytest.raises(tv.HeaderError): + tv.write(out_f, vx_streams, hdr, None, 'voxel') out_f.seek(0) # bypass write error and check read tv.write(out_f, vxmm_streams, hdr, None, points_space=None) out_f.seek(0) - assert_raises(tv.HeaderError, tv.read, out_f, False, 'voxel') + with pytest.raises(tv.HeaderError): + tv.read(out_f, False, 'voxel') # There's a warning for any voxel sizes == 0 hdr = {'voxel_size': [2, 3, 0]} - assert_warns(UserWarning, _rt, vx_streams, hdr, 'voxel') + with pytest.warns(UserWarning): + _rt(vx_streams, hdr, 'voxel') # This should be OK hdr = {'voxel_size': [2, 3, 4]} (raw_streams, hdr), (proc_streams, _) = _rt(vx_streams, hdr, 'voxel') - assert_true(streamlist_equal(vxmm_streams, raw_streams)) - assert_true(streamlist_equal(vx_streams, proc_streams)) + assert streamlist_equal(vxmm_streams, raw_streams) + assert streamlist_equal(vx_streams, proc_streams) # Now we try with rasmm points. In this case we need valid voxel_size, # and voxel_order, and vox_to_ras. The voxel_order has to match the # vox_to_ras, and so do the voxel sizes @@ -247,19 +252,20 @@ def _rt(streams, hdr, points_space): ): # Check error on write out_f.seek(0) - assert_raises(tv.HeaderError, - tv.write, out_f, rasmm_streams, hdr, None, 'rasmm') + with pytest.raises(tv.HeaderError): + tv.write(out_f, rasmm_streams, hdr, None, 'rasmm') out_f.seek(0) # bypass write error and check read tv.write(out_f, vxmm_streams, hdr, None, points_space=None) out_f.seek(0) - assert_raises(tv.HeaderError, tv.read, out_f, False, 'rasmm') + with pytest.raises(tv.HeaderError): + tv.read(out_f, False, 'rasmm') # This should be OK hdr = {'voxel_size': [2, 3, 4], 'voxel_order': 'RAS', 'vox_to_ras': aff} (raw_streams, hdr), (proc_streams, _) = _rt(rasmm_streams, hdr, 'rasmm') - assert_true(streamlist_equal(vxmm_streams, raw_streams)) - assert_true(streamlist_equal(rasmm_streams, proc_streams)) + assert streamlist_equal(vxmm_streams, raw_streams) + assert streamlist_equal(rasmm_streams, proc_streams) # More complex test to check matrix orientation fancy_affine = np.array([[0., -2, 0, 10], [3, 0, 0, 20], @@ -278,73 +284,73 @@ def f(pts): # from vx to mm (ijk1 * [[3, 2, 4]], scalars[1], None)] (raw_streams, hdr), (proc_streams, _) = _rt( fancy_rasmm_streams, hdr, 'rasmm') - assert_true(streamlist_equal(fancy_vxmm_streams, raw_streams)) - assert_true(streamlist_equal(fancy_rasmm_streams, proc_streams)) + assert streamlist_equal(fancy_vxmm_streams, raw_streams) + assert streamlist_equal(fancy_rasmm_streams, proc_streams) def test__check_hdr_points_space(): # Test checking routine for points_space input given header # None or voxmm -> no checks, pass through - assert_equal(tv._check_hdr_points_space({}, None), None) - assert_equal(tv._check_hdr_points_space({}, 'voxmm'), None) + assert tv._check_hdr_points_space({}, None) == None + assert tv._check_hdr_points_space({}, 'voxmm') == None # strange value for points_space -> ValueError - assert_raises(ValueError, - tv._check_hdr_points_space, {}, 'crazy') + with pytest.raises(ValueError): + tv._check_hdr_points_space({}, 'crazy') # Input not in (None, 'voxmm', 'voxels', 'rasmm') - error # voxels means check voxel sizes present and not all 0. hdr = tv.empty_header() assert_array_equal(hdr['voxel_size'], [0, 0, 0]) - assert_raises(tv.HeaderError, - tv._check_hdr_points_space, hdr, 'voxel') + with pytest.raises(tv.HeaderError): + tv._check_hdr_points_space(hdr, 'voxel') # Negative voxel size gives error - because it is not what trackvis does, # and this not what we mean by 'voxmm' hdr['voxel_size'] = [-2, 3, 4] - assert_raises(tv.HeaderError, - tv._check_hdr_points_space, hdr, 'voxel') + with pytest.raises(tv.HeaderError): + tv._check_hdr_points_space(hdr, 'voxel') # Warning here only hdr['voxel_size'] = [2, 3, 0] - assert_warns(UserWarning, - tv._check_hdr_points_space, hdr, 'voxel') + with pytest.warns(UserWarning): + tv._check_hdr_points_space(hdr, 'voxel') # This is OK hdr['voxel_size'] = [2, 3, 4] - assert_equal(tv._check_hdr_points_space(hdr, 'voxel'), None) + assert tv._check_hdr_points_space(hdr, 'voxel') == None # rasmm - check there is an affine, that it matches voxel_size and # voxel_order # no affine hdr['voxel_size'] = [2, 3, 4] - assert_raises(tv.HeaderError, - tv._check_hdr_points_space, hdr, 'rasmm') + with pytest.raises(tv.HeaderError): + tv._check_hdr_points_space(hdr, 'rasmm') # still no affine hdr['voxel_order'] = 'RAS' - assert_raises(tv.HeaderError, - tv._check_hdr_points_space, hdr, 'rasmm') + with pytest.raises(tv.HeaderError): + tv._check_hdr_points_space(hdr, 'rasmm') # nearly an affine, but 0 at position 3,3 - means not recorded in trackvis # standard hdr['vox_to_ras'] = np.diag([2, 3, 4, 0]) - assert_raises(tv.HeaderError, - tv._check_hdr_points_space, hdr, 'rasmm') + with pytest.raises(tv.HeaderError): + tv._check_hdr_points_space(hdr, 'rasmm') # This affine doesn't match RAS voxel order hdr['vox_to_ras'] = np.diag([-2, 3, 4, 1]) - assert_raises(tv.HeaderError, - tv._check_hdr_points_space, hdr, 'rasmm') + with pytest.raises(tv.HeaderError): + tv._check_hdr_points_space(hdr, 'rasmm') # This affine doesn't match the voxel size hdr['vox_to_ras'] = np.diag([3, 3, 4, 1]) - assert_raises(tv.HeaderError, - tv._check_hdr_points_space, hdr, 'rasmm') + with pytest.raises(tv.HeaderError): + tv._check_hdr_points_space(hdr, 'rasmm') # This should be OK good_aff = np.diag([2, 3, 4, 1]) hdr['vox_to_ras'] = good_aff - assert_equal(tv._check_hdr_points_space(hdr, 'rasmm'), + assert (tv._check_hdr_points_space(hdr, 'rasmm') == None) # Default voxel order of LPS assumed hdr['voxel_order'] = '' # now the RAS affine raises an error - assert_raises(tv.HeaderError, - tv._check_hdr_points_space, hdr, 'rasmm') + with pytest.raises(tv.HeaderError): + tv._check_hdr_points_space(hdr, 'rasmm') # this affine does have LPS voxel order good_lps = np.dot(np.diag([-1, -1, 1, 1]), good_aff) hdr['vox_to_ras'] = good_lps - assert_equal(tv._check_hdr_points_space(hdr, 'rasmm'), + assert (tv._check_hdr_points_space(hdr, 'rasmm') == None) @@ -352,16 +358,16 @@ def test_empty_header(): for endian in '<>': for version in (1, 2): hdr = tv.empty_header(endian, version) - assert_equal(hdr['id_string'], b'TRACK') - assert_equal(hdr['version'], version) - assert_equal(hdr['hdr_size'], 1000) + assert hdr['id_string'] == b'TRACK' + assert hdr['version'] == version + assert hdr['hdr_size'] == 1000 assert_array_equal( hdr['image_orientation_patient'], [0, 0, 0, 0, 0, 0]) hdr = tv.empty_header(version=2) assert_array_equal(hdr['vox_to_ras'], np.zeros((4, 4))) hdr_endian = tv.endian_codes[tv.empty_header().dtype.byteorder] - assert_equal(hdr_endian, tv.native_code) + assert hdr_endian == tv.native_code def test_get_affine(): @@ -391,11 +397,12 @@ def test_get_affine(): exp_aff) # check against voxel order. This one works hdr['voxel_order'] = ''.join(aff2axcodes(exp_aff)) - assert_equal(hdr['voxel_order'], b'RAS') + assert hdr['voxel_order'] == b'RAS' assert_array_equal(old_afh(hdr), exp_aff) # This one doesn't hdr['voxel_order'] = 'LAS' - assert_raises(tv.HeaderError, old_afh, hdr) + with pytest.raises(tv.HeaderError): + old_afh(hdr) # This one does work because the routine allows the final dimension to # be flipped to try and match the voxel order hdr['voxel_order'] = 'RAI' @@ -411,11 +418,12 @@ def test_get_affine(): tv.aff_to_hdr(in_aff, hdr, pos_vox=True, set_order=True) # Unset easier option hdr['vox_to_ras'] = 0 - assert_equal(hdr['voxel_order'], o_codes) + assert hdr['voxel_order'] == o_codes # Check it came back the way we wanted assert_array_equal(old_afh(hdr), in_aff) # Check that v1 header raises error - assert_raises(tv.HeaderError, tv.aff_from_hdr, hdr) + with pytest.raises(tv.HeaderError): + tv.aff_from_hdr(hdr) # now use the easier vox_to_ras field hdr = tv.empty_header() aff = np.eye(4) @@ -453,28 +461,28 @@ def test_aff_to_hdr(): for hdr in ({}, {'version': 2}, {'version': 1}): tv.aff_to_hdr(aff2, hdr, pos_vox=True, set_order=False) assert_array_equal(hdr['voxel_size'], [1, 2, 3]) - assert_false('voxel_order' in hdr) + assert not 'voxel_order' in hdr tv.aff_to_hdr(aff2, hdr, pos_vox=False, set_order=True) assert_array_equal(hdr['voxel_size'], [-1, 2, 3]) - assert_equal(hdr['voxel_order'], 'RAI') + assert hdr['voxel_order'] == 'RAI' tv.aff_to_hdr(aff2, hdr, pos_vox=True, set_order=True) assert_array_equal(hdr['voxel_size'], [1, 2, 3]) - assert_equal(hdr['voxel_order'], 'RAI') + assert hdr['voxel_order'] == 'RAI' if 'version' in hdr and hdr['version'] == 1: - assert_false('vox_to_ras' in hdr) + assert not 'vox_to_ras' in hdr else: assert_array_equal(hdr['vox_to_ras'], aff2) def test_tv_class(): tvf = tv.TrackvisFile([]) - assert_equal(tvf.streamlines, []) - assert_true(isinstance(tvf.header, np.ndarray)) - assert_equal(tvf.endianness, tv.native_code) - assert_equal(tvf.filename, None) + assert tvf.streamlines == [] + assert isinstance(tvf.header, np.ndarray) + assert tvf.endianness == tv.native_code + assert tvf.filename == None out_f = BytesIO() tvf.to_file(out_f) - assert_equal(out_f.getvalue(), tv.empty_header().tostring()) + assert out_f.getvalue() == tv.empty_header().tostring() out_f.truncate(0) out_f.seek(0) # Write something not-default @@ -483,19 +491,16 @@ def test_tv_class(): # read it back out_f.seek(0) tvf_back = tv.TrackvisFile.from_file(out_f) - assert_equal(tvf_back.header['id_string'], b'TRACKb') + assert tvf_back.header['id_string'] == b'TRACKb' # check that we check input values out_f.truncate(0) out_f.seek(0) - assert_raises(tv.HeaderError, - tv.TrackvisFile, - [], {'id_string': 'not OK'}) - assert_raises(tv.HeaderError, - tv.TrackvisFile, - [], {'version': 3}) - assert_raises(tv.HeaderError, - tv.TrackvisFile, - [], {'hdr_size': 0}) + with pytest.raises(tv.HeaderError): + tv.TrackvisFile([], {'id_string': 'not OK'}) + with pytest.raises(tv.HeaderError): + tv.TrackvisFile([], {'version': 3}) + with pytest.raises(tv.HeaderError): + tv.TrackvisFile([], {'hdr_size': 0}) affine = np.diag([1, 2, 3, 1]) affine[:3, 3] = [10, 11, 12] # affine methods will raise same warnings and errors as function @@ -503,9 +508,8 @@ def test_tv_class(): aff = tvf.get_affine(atleast_v2=True) assert_array_almost_equal(aff, affine) # Test that we raise an error with an iterator - assert_raises(tv.TrackvisFileError, - tv.TrackvisFile, - iter([])) + with pytest.raises(tv.TrackvisFileError): + tv.TrackvisFile(iter([])) def test_tvfile_io(): @@ -521,22 +525,23 @@ def test_tvfile_io(): tvf.to_file(out_f) out_f.seek(0) tvf2 = tv.TrackvisFile.from_file(out_f) - assert_equal(tvf2.filename, None) - assert_true(streamlist_equal(vxmm_streams, tvf2.streamlines)) - assert_equal(tvf2.points_space, None) + assert tvf2.filename == None + assert streamlist_equal(vxmm_streams, tvf2.streamlines) + assert tvf2.points_space == None # Voxel points_space tvf = tv.TrackvisFile(vx_streams, points_space='voxel') out_f.seek(0) # No voxel size - error - assert_raises(tv.HeaderError, tvf.to_file, out_f) + with pytest.raises(tv.HeaderError): + tvf.to_file(out_f) out_f.seek(0) # With voxel size, no error, roundtrip works tvf.header['voxel_size'] = [2, 3, 4] tvf.to_file(out_f) out_f.seek(0) tvf2 = tv.TrackvisFile.from_file(out_f, points_space='voxel') - assert_true(streamlist_equal(vx_streams, tvf2.streamlines)) - assert_equal(tvf2.points_space, 'voxel') + assert streamlist_equal(vx_streams, tvf2.streamlines) + assert tvf2.points_space == 'voxel' out_f.seek(0) # Also with affine specified tvf = tv.TrackvisFile(vx_streams, points_space='voxel', @@ -544,7 +549,7 @@ def test_tvfile_io(): tvf.to_file(out_f) out_f.seek(0) tvf2 = tv.TrackvisFile.from_file(out_f, points_space='voxel') - assert_true(streamlist_equal(vx_streams, tvf2.streamlines)) + assert streamlist_equal(vx_streams, tvf2.streamlines) # Fancy affine test fancy_affine = np.array([[0., -2, 0, 10], [3, 0, 0, 20], @@ -560,15 +565,16 @@ def f(pts): # from vx to mm tvf = tv.TrackvisFile(fancy_rasmm_streams, points_space='rasmm') out_f.seek(0) # No affine - assert_raises(tv.HeaderError, tvf.to_file, out_f) + with pytest.raises(tv.HeaderError): + tvf.to_file(out_f) out_f.seek(0) # With affine set, no error, roundtrip works tvf.set_affine(fancy_affine, pos_vox=True, set_order=True) tvf.to_file(out_f) out_f.seek(0) tvf2 = tv.TrackvisFile.from_file(out_f, points_space='rasmm') - assert_true(streamlist_equal(fancy_rasmm_streams, tvf2.streamlines)) - assert_equal(tvf2.points_space, 'rasmm') + assert streamlist_equal(fancy_rasmm_streams, tvf2.streamlines) + assert tvf2.points_space == 'rasmm' out_f.seek(0) # Also when affine given in init tvf = tv.TrackvisFile(fancy_rasmm_streams, points_space='rasmm', @@ -576,7 +582,7 @@ def f(pts): # from vx to mm tvf.to_file(out_f) out_f.seek(0) tvf2 = tv.TrackvisFile.from_file(out_f, points_space='rasmm') - assert_true(streamlist_equal(fancy_rasmm_streams, tvf2.streamlines)) + assert streamlist_equal(fancy_rasmm_streams, tvf2.streamlines) def test_read_truncated(): @@ -590,26 +596,29 @@ def test_read_truncated(): value = out_f.getvalue()[:-(3 * 4)] new_f = BytesIO(value) # By default, raises a DataError - assert_raises(tv.DataError, tv.read, new_f) + with pytest.raises(tv.DataError): + tv.read(new_f) # This corresponds to strict mode new_f.seek(0) - assert_raises(tv.DataError, tv.read, new_f, strict=True) + with pytest.raises(tv.DataError): + tv.read(new_f, strict=True) # lenient error mode lets this error pass, with truncated track short_streams = [(xyz0, None, None), (xyz1[:-1], None, None)] new_f.seek(0) streams2, hdr = tv.read(new_f, strict=False) - assert_true(streamlist_equal(streams2, short_streams)) + assert streamlist_equal(streams2, short_streams) # Check that lenient works when number of tracks is 0, where 0 signals to # the reader to read until the end of the file. again_hdr = hdr.copy() - assert_equal(again_hdr['n_count'], 2) + assert again_hdr['n_count'] == 2 again_hdr['n_count'] = 0 again_bytes = again_hdr.tostring() + value[again_hdr.itemsize:] again_f = BytesIO(again_bytes) streams2, _ = tv.read(again_f, strict=False) - assert_true(streamlist_equal(streams2, short_streams)) + assert streamlist_equal(streams2, short_streams) # Set count to one above actual number of tracks, always raise error again_hdr['n_count'] = 3 again_bytes = again_hdr.tostring() + value[again_hdr.itemsize:] again_f = BytesIO(again_bytes) - assert_raises(tv.DataError, tv.read, again_f, strict=False) + with pytest.raises(tv.DataError): + tv.read(again_f, strict=False) From 7aaa2d08a17431afd4fbc8750d5e6e4eec288642 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 15:36:11 -0500 Subject: [PATCH 095/223] converting test_volumeutils --- nibabel/tests/test_volumeutils.py | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/nibabel/tests/test_volumeutils.py b/nibabel/tests/test_volumeutils.py index 711894aabc..1591dae005 100644 --- a/nibabel/tests/test_volumeutils.py +++ b/nibabel/tests/test_volumeutils.py @@ -20,13 +20,11 @@ import bz2 import threading import time -import pytest import numpy as np from ..tmpdirs import InTemporaryDirectory from ..openers import ImageOpener -from .. import volumeutils from ..volumeutils import (array_from_file, _is_compressed_fobj, array_to_file, @@ -57,11 +55,10 @@ from numpy.testing import (assert_array_almost_equal, assert_array_equal) -from nose.tools import assert_raises +import pytest from ..testing_pytest import (assert_dt_equal, assert_allclose_safely, suppress_warnings, clear_and_catch_warnings) -import pytest; pytestmark = pytest.mark.skip() #: convenience variables for numpy types FLOAT_TYPES = np.sctypes['float'] @@ -73,11 +70,11 @@ def test_deprecated_functions(): - with assert_raises(ExpiredDeprecationError): + with pytest.raises(ExpiredDeprecationError): scale_min_max(0, 1, np.uint8, True) - with assert_raises(ExpiredDeprecationError): + with pytest.raises(ExpiredDeprecationError): calculate_scale(np.array([-2, -1], dtype=np.int8), np.uint8, True) - with assert_raises(ExpiredDeprecationError): + with pytest.raises(ExpiredDeprecationError): can_cast(np.float32, np.float32) From 4ee885592725022f0d2a434bf9aa38583fdddf87 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 15:56:41 -0500 Subject: [PATCH 096/223] converting nibabel_data --- nibabel/tests/nibabel_data.py | 10 +++++----- nibabel/tests/test_optpkg.py | 4 +--- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 453c0af9ec..0843293d10 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -4,7 +4,7 @@ from os import environ, listdir from os.path import dirname, realpath, join as pjoin, isdir, exists -from ..testing import skipif +import pytest def get_nibabel_data(): @@ -39,11 +39,11 @@ def needs_nibabel_data(subdir=None): """ nibabel_data = get_nibabel_data() if nibabel_data == '': - return skipif(True, "Need nibabel-data directory for this test") + return pytest.mark.skipif(True, reason="Need nibabel-data directory for this test") if subdir is None: - return skipif(False) + return pytest.mark.skipif(False, reason="todo") required_path = pjoin(nibabel_data, subdir) # Path should not be empty (as is the case for not-updated submodules) have_files = exists(required_path) and len(listdir(required_path)) > 0 - return skipif(not have_files, - "Need files in {0} for these tests".format(required_path)) + return pytest.mark.skipif(not have_files, + reason="Need files in {0} for these tests".format(required_path)) diff --git a/nibabel/tests/test_optpkg.py b/nibabel/tests/test_optpkg.py index a6b9571530..387cebecba 100644 --- a/nibabel/tests/test_optpkg.py +++ b/nibabel/tests/test_optpkg.py @@ -7,8 +7,7 @@ import builtins from distutils.version import LooseVersion -# TODO: remove (have to be coordinated with optpkg) -from nose import SkipTest +from unittest import SkipTest import pytest from nibabel.optpkg import optional_package @@ -28,7 +27,6 @@ def assert_bad(pkg_name, min_version=None): assert isinstance(pkg, TripWire) with pytest.raises(TripWireError): getattr(pkg, 'a_method') - # TODO: remove with pytest.raises(SkipTest): setup() From a1704970fff7d40f9846ebfc608d9476fc1c6c65 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 16:04:42 -0500 Subject: [PATCH 097/223] removing todos --- nibabel/tests/nibabel_data.py | 2 +- nibabel/tests/test_scripts.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 0843293d10..ad4ac98a16 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' -# dj-TODO + def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index db83a4d3f5..873059b510 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data +@needs_nibabel_data('nitest-balls1') def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From ff3cb80b6bc94b78b310d401ed471de49814f2e1 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 21:51:26 -0500 Subject: [PATCH 098/223] Apply suggestions from code review Co-Authored-By: Chris Markiewicz --- nibabel/tests/nibabel_data.py | 4 ++-- nibabel/tests/test_spaces.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index ad4ac98a16..4bc2957c4a 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -41,9 +41,9 @@ def needs_nibabel_data(subdir=None): if nibabel_data == '': return pytest.mark.skipif(True, reason="Need nibabel-data directory for this test") if subdir is None: - return pytest.mark.skipif(False, reason="todo") + return pytest.mark.skipif(False, reason="Don't skip") required_path = pjoin(nibabel_data, subdir) # Path should not be empty (as is the case for not-updated submodules) have_files = exists(required_path) and len(listdir(required_path)) > 0 return pytest.mark.skipif(not have_files, - reason="Need files in {0} for these tests".format(required_path)) + reason="Need files in {0} for these tests".format(required_path)) diff --git a/nibabel/tests/test_spaces.py b/nibabel/tests/test_spaces.py index 5459571954..0b301dae61 100644 --- a/nibabel/tests/test_spaces.py +++ b/nibabel/tests/test_spaces.py @@ -116,11 +116,11 @@ def test_slice2volume(): assert (slice2volume(val, axis) == exp_aff).all() -@pytest.mark.parametrize("args", [ +@pytest.mark.parametrize("index, axis", [ [-1, 0], [0, -1], [0, 3] ]) def test_slice2volume_exception(args): with pytest.raises(ValueError): - slice2volume(*args) \ No newline at end of file + slice2volume(*args) From e87d3a5c48038671cd5a0fe3ee79857052ec72d4 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Wed, 5 Feb 2020 10:03:27 -0500 Subject: [PATCH 099/223] Apply suggestions from code review Co-Authored-By: Chris Markiewicz --- nibabel/tests/test_spatialimages.py | 2 +- nibabel/tests/test_trackvis.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/nibabel/tests/test_spatialimages.py b/nibabel/tests/test_spatialimages.py index 288096638e..4e3547f1d9 100644 --- a/nibabel/tests/test_spatialimages.py +++ b/nibabel/tests/test_spatialimages.py @@ -162,7 +162,7 @@ def test_affine(): [0, 2, 0, -1], [0, 0, 1, -1], [0, 0, 0, 1]]) - assert (hdr.get_base_affine() == hdr.get_best_affine()).all() + assert np.array_equal(hdr.get_base_affine(), hdr.get_best_affine()) def test_read_data(): diff --git a/nibabel/tests/test_trackvis.py b/nibabel/tests/test_trackvis.py index 15675882eb..bcfbfe673d 100644 --- a/nibabel/tests/test_trackvis.py +++ b/nibabel/tests/test_trackvis.py @@ -525,9 +525,9 @@ def test_tvfile_io(): tvf.to_file(out_f) out_f.seek(0) tvf2 = tv.TrackvisFile.from_file(out_f) - assert tvf2.filename == None + assert tvf2.filename is None assert streamlist_equal(vxmm_streams, tvf2.streamlines) - assert tvf2.points_space == None + assert tvf2.points_space is None # Voxel points_space tvf = tv.TrackvisFile(vx_streams, points_space='voxel') out_f.seek(0) From f2931abc6e0c1b087583950b6a224fa51da02237 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:45:57 -0500 Subject: [PATCH 100/223] converting nibabel/tests/test_scripts.py --- nibabel/tests/test_scripts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 873059b510..db83a4d3f5 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') +@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From af8b38696891c8c9f1faba658a04e5fdef2d49f4 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:46:26 -0500 Subject: [PATCH 101/223] adding todo --- nibabel/tests/nibabel_data.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 4bc2957c4a..753eeb5e15 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' - +# dj-TODO def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data From 06210d57062729be7c57d651a7e435e30f3f0403 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 16:04:42 -0500 Subject: [PATCH 102/223] removing todos --- nibabel/tests/nibabel_data.py | 2 +- nibabel/tests/test_scripts.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 753eeb5e15..4bc2957c4a 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' -# dj-TODO + def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index db83a4d3f5..873059b510 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data +@needs_nibabel_data('nitest-balls1') def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From dd42dd8aa3645318f7a91fa8f594abed11429d4a Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Wed, 5 Feb 2020 10:36:20 -0500 Subject: [PATCH 103/223] small edits: suggestions from reviews --- nibabel/tests/test_spaces.py | 23 +++++++++++------------ nibabel/tests/test_spatialimages.py | 16 ++++++---------- 2 files changed, 17 insertions(+), 22 deletions(-) diff --git a/nibabel/tests/test_spaces.py b/nibabel/tests/test_spaces.py index 0b301dae61..acdd61a28e 100644 --- a/nibabel/tests/test_spaces.py +++ b/nibabel/tests/test_spaces.py @@ -76,15 +76,7 @@ def get_outspace_params(): ) -@pytest.mark.parametrize("arg_tuple", [ - # Enforce number of axes - ((2, 3, 4, 5), np.eye(4)), - ((2, 3, 4, 5, 6), np.eye(4)), - # Voxel sizes must be positive - ((2, 3, 4), np.eye(4), [-1, 1, 1]), - ((2, 3, 4), np.eye(4), [1, 0, 1]) -]) -def test_vox2out_vox(arg_tuple): +def test_vox2out_vox(): # Test world space bounding box # Test basic case, identity, no voxel sizes passed shape, aff = vox2out_vox(((2, 3, 4), np.eye(4))) @@ -101,7 +93,14 @@ def test_vox2out_vox(arg_tuple): assert isinstance(shape[0], int) # Enforce number of axes with pytest.raises(ValueError): - vox2out_vox(arg_tuple) + vox2out_vox(((2, 3, 4, 5), np.eye(4))) + with pytest.raises(ValueError): + vox2out_vox(((2, 3, 4, 5, 6), np.eye(4))) + # Voxel sizes must be positive + with pytest.raises(ValueError): + vox2out_vox(((2, 3, 4), np.eye(4), [-1, 1, 1])) + with pytest.raises(ValueError): + vox2out_vox(((2, 3, 4), np.eye(4), [1, 0, 1])) def test_slice2volume(): @@ -121,6 +120,6 @@ def test_slice2volume(): [0, -1], [0, 3] ]) -def test_slice2volume_exception(args): +def test_slice2volume_exception(index, axis): with pytest.raises(ValueError): - slice2volume(*args) + slice2volume(index, axis) diff --git a/nibabel/tests/test_spatialimages.py b/nibabel/tests/test_spatialimages.py index 4e3547f1d9..5959057fc9 100644 --- a/nibabel/tests/test_spatialimages.py +++ b/nibabel/tests/test_spatialimages.py @@ -173,18 +173,15 @@ class CHeader(SpatialHeader): fobj = BytesIO() data = np.arange(6).reshape((1, 2, 3)) hdr.data_to_fileobj(data, fobj) - assert (fobj.getvalue() == - data.astype(np.int32).tostring(order=order)) + assert fobj.getvalue() == data.astype(np.int32).tostring(order=order) # data_to_fileobj accepts kwarg 'rescale', but no effect in this case fobj.seek(0) hdr.data_to_fileobj(data, fobj, rescale=True) - assert (fobj.getvalue() == - data.astype(np.int32).tostring(order=order)) + assert fobj.getvalue() == data.astype(np.int32).tostring(order=order) # data_to_fileobj can be a list fobj.seek(0) hdr.data_to_fileobj(data.tolist(), fobj, rescale=True) - assert (fobj.getvalue() == - data.astype(np.int32).tostring(order=order)) + assert fobj.getvalue() == data.astype(np.int32).tostring(order=order) # Read data back again fobj.seek(0) data2 = hdr.data_from_fileobj(fobj) @@ -464,8 +461,8 @@ def test_slicer(self): img.slicer[:, :, :, None] else: # Reorder non-spatial axes - assert (img.slicer[:, :, :, None].shape == - img.shape[:3] + (1,) + img.shape[3:]) + assert (img.slicer[:, :, :, None].shape + == img.shape[:3] + (1,) + img.shape[3:]) # 4D to 3D using ellipsis or slices assert img.slicer[..., 0].shape == img.shape[:-1] assert img.slicer[:, :, :, 0].shape == img.shape[:-1] @@ -480,8 +477,7 @@ def test_slicer(self): with pytest.raises(ValueError): img.slicer[:, :, :, :, None] else: - assert (img.slicer[:, :, :, :, None].shape == - img.shape + (1,)) + assert img.slicer[:, :, :, :, None].shape == img.shape + (1,) # Crop by one voxel in each dimension sliced_i = img.slicer[1:] From e55940da85f795fb665b6b542ce1919607fcba1e Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Wed, 5 Feb 2020 10:45:47 -0500 Subject: [PATCH 104/223] ignoring tests with pytest.mark.parametrize --- .azure-pipelines/windows.yml | 3 +++ .travis.yml | 3 +++ 2 files changed, 6 insertions(+) diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index 89b47b8345..f63b5f48c3 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -99,6 +99,9 @@ jobs: -I test_round_trip ^ -I test_rstutils ^ -I test_scaling ^ + -I test_scripts ^ + -I test_spaces ^ + -I test_testing ^ -I test_wrapstruct displayName: 'Nose tests' condition: and(succeeded(), eq(variables['CHECK_TYPE'], 'nosetests')) diff --git a/.travis.yml b/.travis.yml index b869d33947..e8b20252f0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -186,6 +186,9 @@ script: -I test_round_trip \ -I test_rstutils \ -I test_scaling \ + -I test_scripts \ + -I test_spaces \ + -I test_testing \ -I test_wrapstruct elif [ "${CHECK_TYPE}" == "test" ]; then # Change into an innocuous directory and find tests from installation From 1e2caf4c89d7b2bfdb40b12f57e29e81f9ee8f94 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:45:57 -0500 Subject: [PATCH 105/223] converting nibabel/tests/test_scripts.py --- nibabel/tests/test_scripts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 873059b510..db83a4d3f5 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') +@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From b1fe9214b916675b914dfc284669db84c52b59c9 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:46:26 -0500 Subject: [PATCH 106/223] adding todo --- nibabel/tests/nibabel_data.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 4bc2957c4a..753eeb5e15 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' - +# dj-TODO def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data From 31c16985f4e1fe303bb42d46c80ac7bf9440891a Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 14:50:03 -0500 Subject: [PATCH 107/223] converting more tests nibabel.tests.test_s* --- nibabel/tests/test_spaces.py | 12 ++++++++++-- nibabel/tests/test_spatialimages.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/nibabel/tests/test_spaces.py b/nibabel/tests/test_spaces.py index acdd61a28e..7f8ae94c51 100644 --- a/nibabel/tests/test_spaces.py +++ b/nibabel/tests/test_spaces.py @@ -76,7 +76,15 @@ def get_outspace_params(): ) -def test_vox2out_vox(): +@pytest.mark.parametrize("arg_tuple", [ + # Enforce number of axes + ((2, 3, 4, 5), np.eye(4)), + ((2, 3, 4, 5, 6), np.eye(4)), + # Voxel sizes must be positive + ((2, 3, 4), np.eye(4), [-1, 1, 1]), + ((2, 3, 4), np.eye(4), [1, 0, 1]) +]) +def test_vox2out_vox(arg_tuple): # Test world space bounding box # Test basic case, identity, no voxel sizes passed shape, aff = vox2out_vox(((2, 3, 4), np.eye(4))) @@ -122,4 +130,4 @@ def test_slice2volume(): ]) def test_slice2volume_exception(index, axis): with pytest.raises(ValueError): - slice2volume(index, axis) + slice2volume(index, axis) \ No newline at end of file diff --git a/nibabel/tests/test_spatialimages.py b/nibabel/tests/test_spatialimages.py index 5959057fc9..d24633d283 100644 --- a/nibabel/tests/test_spatialimages.py +++ b/nibabel/tests/test_spatialimages.py @@ -162,7 +162,11 @@ def test_affine(): [0, 2, 0, -1], [0, 0, 1, -1], [0, 0, 0, 1]]) +<<<<<<< HEAD assert np.array_equal(hdr.get_base_affine(), hdr.get_best_affine()) +======= + assert (hdr.get_base_affine() == hdr.get_best_affine()).all() +>>>>>>> converting more tests nibabel.tests.test_s* def test_read_data(): @@ -173,6 +177,7 @@ class CHeader(SpatialHeader): fobj = BytesIO() data = np.arange(6).reshape((1, 2, 3)) hdr.data_to_fileobj(data, fobj) +<<<<<<< HEAD assert fobj.getvalue() == data.astype(np.int32).tostring(order=order) # data_to_fileobj accepts kwarg 'rescale', but no effect in this case fobj.seek(0) @@ -182,6 +187,20 @@ class CHeader(SpatialHeader): fobj.seek(0) hdr.data_to_fileobj(data.tolist(), fobj, rescale=True) assert fobj.getvalue() == data.astype(np.int32).tostring(order=order) +======= + assert (fobj.getvalue() == + data.astype(np.int32).tostring(order=order)) + # data_to_fileobj accepts kwarg 'rescale', but no effect in this case + fobj.seek(0) + hdr.data_to_fileobj(data, fobj, rescale=True) + assert (fobj.getvalue() == + data.astype(np.int32).tostring(order=order)) + # data_to_fileobj can be a list + fobj.seek(0) + hdr.data_to_fileobj(data.tolist(), fobj, rescale=True) + assert (fobj.getvalue() == + data.astype(np.int32).tostring(order=order)) +>>>>>>> converting more tests nibabel.tests.test_s* # Read data back again fobj.seek(0) data2 = hdr.data_from_fileobj(fobj) @@ -461,8 +480,13 @@ def test_slicer(self): img.slicer[:, :, :, None] else: # Reorder non-spatial axes +<<<<<<< HEAD assert (img.slicer[:, :, :, None].shape == img.shape[:3] + (1,) + img.shape[3:]) +======= + assert (img.slicer[:, :, :, None].shape == + img.shape[:3] + (1,) + img.shape[3:]) +>>>>>>> converting more tests nibabel.tests.test_s* # 4D to 3D using ellipsis or slices assert img.slicer[..., 0].shape == img.shape[:-1] assert img.slicer[:, :, :, 0].shape == img.shape[:-1] @@ -477,7 +501,12 @@ def test_slicer(self): with pytest.raises(ValueError): img.slicer[:, :, :, :, None] else: +<<<<<<< HEAD assert img.slicer[:, :, :, :, None].shape == img.shape + (1,) +======= + assert (img.slicer[:, :, :, :, None].shape == + img.shape + (1,)) +>>>>>>> converting more tests nibabel.tests.test_s* # Crop by one voxel in each dimension sliced_i = img.slicer[1:] From e099c290d272d5b01b9b4a2c7a4dbb2ed1a1ad55 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 16:04:42 -0500 Subject: [PATCH 108/223] removing todos --- nibabel/tests/nibabel_data.py | 2 +- nibabel/tests/test_scripts.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 753eeb5e15..4bc2957c4a 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' -# dj-TODO + def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index db83a4d3f5..873059b510 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data +@needs_nibabel_data('nitest-balls1') def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From 264d1fa93b30c94d8ab4d395d6e27defb58fa567 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Wed, 5 Feb 2020 10:03:27 -0500 Subject: [PATCH 109/223] Apply suggestions from code review Co-Authored-By: Chris Markiewicz --- nibabel/tests/test_spatialimages.py | 29 ----------------------------- 1 file changed, 29 deletions(-) diff --git a/nibabel/tests/test_spatialimages.py b/nibabel/tests/test_spatialimages.py index d24633d283..5959057fc9 100644 --- a/nibabel/tests/test_spatialimages.py +++ b/nibabel/tests/test_spatialimages.py @@ -162,11 +162,7 @@ def test_affine(): [0, 2, 0, -1], [0, 0, 1, -1], [0, 0, 0, 1]]) -<<<<<<< HEAD assert np.array_equal(hdr.get_base_affine(), hdr.get_best_affine()) -======= - assert (hdr.get_base_affine() == hdr.get_best_affine()).all() ->>>>>>> converting more tests nibabel.tests.test_s* def test_read_data(): @@ -177,7 +173,6 @@ class CHeader(SpatialHeader): fobj = BytesIO() data = np.arange(6).reshape((1, 2, 3)) hdr.data_to_fileobj(data, fobj) -<<<<<<< HEAD assert fobj.getvalue() == data.astype(np.int32).tostring(order=order) # data_to_fileobj accepts kwarg 'rescale', but no effect in this case fobj.seek(0) @@ -187,20 +182,6 @@ class CHeader(SpatialHeader): fobj.seek(0) hdr.data_to_fileobj(data.tolist(), fobj, rescale=True) assert fobj.getvalue() == data.astype(np.int32).tostring(order=order) -======= - assert (fobj.getvalue() == - data.astype(np.int32).tostring(order=order)) - # data_to_fileobj accepts kwarg 'rescale', but no effect in this case - fobj.seek(0) - hdr.data_to_fileobj(data, fobj, rescale=True) - assert (fobj.getvalue() == - data.astype(np.int32).tostring(order=order)) - # data_to_fileobj can be a list - fobj.seek(0) - hdr.data_to_fileobj(data.tolist(), fobj, rescale=True) - assert (fobj.getvalue() == - data.astype(np.int32).tostring(order=order)) ->>>>>>> converting more tests nibabel.tests.test_s* # Read data back again fobj.seek(0) data2 = hdr.data_from_fileobj(fobj) @@ -480,13 +461,8 @@ def test_slicer(self): img.slicer[:, :, :, None] else: # Reorder non-spatial axes -<<<<<<< HEAD assert (img.slicer[:, :, :, None].shape == img.shape[:3] + (1,) + img.shape[3:]) -======= - assert (img.slicer[:, :, :, None].shape == - img.shape[:3] + (1,) + img.shape[3:]) ->>>>>>> converting more tests nibabel.tests.test_s* # 4D to 3D using ellipsis or slices assert img.slicer[..., 0].shape == img.shape[:-1] assert img.slicer[:, :, :, 0].shape == img.shape[:-1] @@ -501,12 +477,7 @@ def test_slicer(self): with pytest.raises(ValueError): img.slicer[:, :, :, :, None] else: -<<<<<<< HEAD assert img.slicer[:, :, :, :, None].shape == img.shape + (1,) -======= - assert (img.slicer[:, :, :, :, None].shape == - img.shape + (1,)) ->>>>>>> converting more tests nibabel.tests.test_s* # Crop by one voxel in each dimension sliced_i = img.slicer[1:] From dd0c52195fec1f05a456e49ac9f24a399d2ed504 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:45:57 -0500 Subject: [PATCH 110/223] converting nibabel/tests/test_scripts.py --- nibabel/tests/test_scripts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 873059b510..db83a4d3f5 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') +@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From 159956e78333334ab7e7fb6ab1d4fb383b29a858 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:46:26 -0500 Subject: [PATCH 111/223] adding todo --- nibabel/tests/nibabel_data.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 4bc2957c4a..753eeb5e15 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' - +# dj-TODO def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data From e0da084b7f3e2cda539dcb00b3d6ec7128caae76 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 16:04:42 -0500 Subject: [PATCH 112/223] removing todos --- nibabel/tests/nibabel_data.py | 2 +- nibabel/tests/test_scripts.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 753eeb5e15..4bc2957c4a 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' -# dj-TODO + def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index db83a4d3f5..873059b510 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data +@needs_nibabel_data('nitest-balls1') def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From 0519f3616fb49e26cbd4b18a552be790f7007867 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Wed, 5 Feb 2020 10:36:20 -0500 Subject: [PATCH 113/223] small edits: suggestions from reviews --- nibabel/tests/test_spaces.py | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/nibabel/tests/test_spaces.py b/nibabel/tests/test_spaces.py index 7f8ae94c51..a653082f78 100644 --- a/nibabel/tests/test_spaces.py +++ b/nibabel/tests/test_spaces.py @@ -76,15 +76,7 @@ def get_outspace_params(): ) -@pytest.mark.parametrize("arg_tuple", [ - # Enforce number of axes - ((2, 3, 4, 5), np.eye(4)), - ((2, 3, 4, 5, 6), np.eye(4)), - # Voxel sizes must be positive - ((2, 3, 4), np.eye(4), [-1, 1, 1]), - ((2, 3, 4), np.eye(4), [1, 0, 1]) -]) -def test_vox2out_vox(arg_tuple): +def test_vox2out_vox(): # Test world space bounding box # Test basic case, identity, no voxel sizes passed shape, aff = vox2out_vox(((2, 3, 4), np.eye(4))) From f4f48ef88fd56676fbfe8f0683957eecf11b9503 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Wed, 5 Feb 2020 12:35:53 -0500 Subject: [PATCH 114/223] applying suggestions from 865 --- nibabel/tests/test_arraywriters.py | 8 ++++---- nibabel/tests/test_deprecator.py | 15 +++------------ nibabel/tests/test_fileslice.py | 2 +- nibabel/tests/test_funcs.py | 6 +++--- nibabel/tests/test_image_api.py | 14 ++++---------- nibabel/tests/test_orientations.py | 5 +---- nibabel/tests/test_parrec.py | 16 +++++++--------- nibabel/tests/test_parrec_data.py | 3 +-- nibabel/tests/test_recoder.py | 18 +++++++++--------- nibabel/tests/test_scaling.py | 22 ++++++++++------------ nibabel/tests/test_spatialimages.py | 23 +++++++++-------------- nibabel/tests/test_spm99analyze.py | 3 +-- 12 files changed, 53 insertions(+), 82 deletions(-) diff --git a/nibabel/tests/test_arraywriters.py b/nibabel/tests/test_arraywriters.py index 8f30f04321..1a1c4eb156 100644 --- a/nibabel/tests/test_arraywriters.py +++ b/nibabel/tests/test_arraywriters.py @@ -508,9 +508,9 @@ def test_nan2zero(): assert_array_equal(np.isnan(data_back), [True, False]) # Deprecation warning for nan2zero as argument to `to_fileobj` with error_warnings(): - with pytest.raises(DeprecationWarning): + with pytest.deprecated_call(): aw.to_fileobj(BytesIO(), 'F', True) - with pytest.raises(DeprecationWarning): + with pytest.deprecated_call(): aw.to_fileobj(BytesIO(), 'F', nan2zero=True) # Error if nan2zero is not the value set at initialization with pytest.raises(WriterError): @@ -530,9 +530,9 @@ def test_nan2zero(): assert_array_equal(data_back, [astype_res, 99]) # Deprecation warning for nan2zero as argument to `to_fileobj` with error_warnings(): - with pytest.raises(DeprecationWarning): + with pytest.deprecated_call(): aw.to_fileobj(BytesIO(), 'F', False) - with pytest.raises(DeprecationWarning): + with pytest.deprecated_call(): aw.to_fileobj(BytesIO(), 'F', nan2zero=False) # Error if nan2zero is not the value set at initialization with pytest.raises(WriterError): diff --git a/nibabel/tests/test_deprecator.py b/nibabel/tests/test_deprecator.py index 14255da4b4..eb9de3799d 100644 --- a/nibabel/tests/test_deprecator.py +++ b/nibabel/tests/test_deprecator.py @@ -69,11 +69,8 @@ def test_dep_func(self): # Test function deprecation dec = self.dep_func func = dec('foo')(func_no_doc) - with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: - warnings.simplefilter('always') + with pytest.deprecated_call(): assert func() == None - assert len(w) == 1 - assert w[0].category is DeprecationWarning assert func.__doc__ == 'foo\n' func = dec('foo')(func_doc) with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: @@ -135,11 +132,8 @@ def test_dep_func(self): assert w[0].category is UserWarning func = dec('foo', error_class=CustomError)(func_no_doc) - with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: - warnings.simplefilter('always') + with pytest.deprecated_call(): assert func() == None - assert len(w) == 1 - assert w[0].category is DeprecationWarning func = dec('foo', until='1.8', error_class=CustomError)(func_no_doc) with pytest.raises(CustomError): @@ -162,11 +156,8 @@ def test_deprecator_maker(self): dec = self.dep_maker(error_class=CustomError) func = dec('foo')(func_no_doc) - with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: - warnings.simplefilter('always') + with pytest.deprecated_call(): assert func() == None - assert len(w) == 1 - assert w[0].category is DeprecationWarning func = dec('foo', until='1.8')(func_no_doc) with pytest.raises(CustomError): diff --git a/nibabel/tests/test_fileslice.py b/nibabel/tests/test_fileslice.py index 5c80ae01b5..924da5fc9f 100644 --- a/nibabel/tests/test_fileslice.py +++ b/nibabel/tests/test_fileslice.py @@ -47,7 +47,7 @@ def test_is_fancy(): assert not is_fancy((None, 1)) assert not is_fancy((1, None)) # Chack that actual False returned (rather than falsey) - assert is_fancy(1) == False + assert is_fancy(1) is False def test_canonical_slicers(): diff --git a/nibabel/tests/test_funcs.py b/nibabel/tests/test_funcs.py index 94645f2839..db196995e0 100644 --- a/nibabel/tests/test_funcs.py +++ b/nibabel/tests/test_funcs.py @@ -138,7 +138,7 @@ def test_closest_canonical(): # And a case where the Analyze image has to be flipped img = AnalyzeImage(arr, np.diag([-1, 1, 1, 1])) xyz_img = as_closest_canonical(img) - assert not img is xyz_img + assert img is not xyz_img out_arr = xyz_img.get_fdata() assert_array_equal(out_arr, np.flipud(arr)) @@ -156,7 +156,7 @@ def test_closest_canonical(): img = Nifti1Image(arr, np.diag([-1, 1, 1, 1])) img.header.set_dim_info(0, 1, 2) xyz_img = as_closest_canonical(img) - assert not img is xyz_img + assert img is not xyz_img assert img.header.get_dim_info() == xyz_img.header.get_dim_info() out_arr = xyz_img.get_fdata() assert_array_equal(out_arr, np.flipud(arr)) @@ -181,7 +181,7 @@ def test_closest_canonical(): img.header.set_dim_info(0, 1, 2) xyz_img = as_closest_canonical(img) - assert not img is xyz_img + assert img is not xyz_img # Check both the original and new objects assert img.header.get_dim_info() == (0, 1, 2) assert xyz_img.header.get_dim_info() == (0, 2, 1) diff --git a/nibabel/tests/test_image_api.py b/nibabel/tests/test_image_api.py index 738a3f1969..34725ba186 100644 --- a/nibabel/tests/test_image_api.py +++ b/nibabel/tests/test_image_api.py @@ -113,10 +113,8 @@ def validate_header(self, imaker, params): def validate_header_deprecated(self, imaker, params): # Check deprecated header API img = imaker() - with clear_and_catch_warnings() as w: - warnings.simplefilter('always', DeprecationWarning) + with pytest.deprecated_call(): hdr = img.get_header() - assert len(w) == 1 assert hdr is img.header def validate_filenames(self, imaker, params): @@ -171,7 +169,7 @@ def validate_no_slicing(self, imaker, params): def validate_get_data_deprecated(self, imaker, params): # Check deprecated header API img = imaker() - with assert_warns(DeprecationWarning): + with pytest.deprecated_call(): data = img.get_data() assert_array_equal(np.asanyarray(img.dataobj), data) @@ -395,10 +393,8 @@ def _check_array_caching(self, imaker, meth_name, caching): def validate_data_deprecated(self, imaker, params): # Check _data property still exists, but raises warning img = imaker() - with warnings.catch_warnings(record=True) as warns: - warnings.simplefilter("always") + with pytest.deprecated_call(): assert_data_similar(img._data, params) - assert warns.pop(0).category == DeprecationWarning # Check setting _data raises error fake_data = np.zeros(img.shape).astype(img.get_data_dtype()) with pytest.raises(AttributeError): @@ -502,10 +498,8 @@ def validate_affine(self, imaker, params): def validate_affine_deprecated(self, imaker, params): # Check deprecated affine API img = imaker() - with clear_and_catch_warnings() as w: - warnings.simplefilter('always', DeprecationWarning) + with pytest.deprecated_call(): assert_almost_equal(img.get_affine(), params['affine'], 6) - assert len(w) == 1 assert img.get_affine().dtype == np.float64 aff = img.get_affine() aff[0, 0] = 1.5 diff --git a/nibabel/tests/test_orientations.py b/nibabel/tests/test_orientations.py index 5013828757..226feee526 100644 --- a/nibabel/tests/test_orientations.py +++ b/nibabel/tests/test_orientations.py @@ -380,9 +380,6 @@ def test_inv_ornt_aff(): def test_orientation_affine_deprecation(): aff1 = inv_ornt_aff([[0, 1], [1, -1], [2, 1]], (3, 4, 5)) - with warnings.catch_warnings(record=True) as warns: - warnings.simplefilter('always') + with pytest.deprecated_call(): aff2 = orientation_affine([[0, 1], [1, -1], [2, 1]], (3, 4, 5)) - assert len(warns) == 1 - assert warns[0].category == DeprecationWarning assert_array_equal(aff1, aff2) diff --git a/nibabel/tests/test_parrec.py b/nibabel/tests/test_parrec.py index bb0888b0e7..54c15fde6b 100644 --- a/nibabel/tests/test_parrec.py +++ b/nibabel/tests/test_parrec.py @@ -263,10 +263,8 @@ def test_affine_regression(): def test_get_voxel_size_deprecated(): hdr = PARRECHeader(HDR_INFO, HDR_DEFS) - with clear_and_catch_warnings(modules=[parrec], record=True) as wlist: - simplefilter('always') + with pytest.deprecated_call(): hdr.get_voxel_size() - assert wlist[0].category == DeprecationWarning def test_get_sorted_slice_indices(): @@ -304,9 +302,9 @@ def test_sorting_dual_echo_T1(): sorted_echos = t1_hdr.image_defs['echo number'][sorted_indices] n_half = len(t1_hdr.image_defs) // 2 # first half (volume 1) should all correspond to echo 1 - assert np.all(sorted_echos[:n_half] == 1) == True + assert np.all(sorted_echos[:n_half] == 1) # second half (volume 2) should all correspond to echo 2 - assert np.all(sorted_echos[n_half:] == 2) == True + assert np.all(sorted_echos[n_half:] == 2) # check volume labels vol_labels = t1_hdr.get_volume_labels() @@ -350,10 +348,10 @@ def test_sorting_multiple_echos_and_contrasts(): assert (np.all(sorted_echos[istart:iend] == current_echo) == True) # outermost sort index is image_type_mr - assert np.all(sorted_types[:ntotal//4] == 0) == True - assert np.all(sorted_types[ntotal//4:ntotal//2] == 1) == True - assert np.all(sorted_types[ntotal//2:3*ntotal//4] == 2) == True - assert np.all(sorted_types[3*ntotal//4:ntotal] == 3) == True + assert np.all(sorted_types[:ntotal//4] == 0) + assert np.all(sorted_types[ntotal//4:ntotal//2] == 1) + assert np.all(sorted_types[ntotal//2:3*ntotal//4] == 2) + assert np.all(sorted_types[3*ntotal//4:ntotal] == 3) # check volume labels vol_labels = t1_hdr.get_volume_labels() diff --git a/nibabel/tests/test_parrec_data.py b/nibabel/tests/test_parrec_data.py index 0cd92bd13f..30295a269a 100644 --- a/nibabel/tests/test_parrec_data.py +++ b/nibabel/tests/test_parrec_data.py @@ -60,8 +60,7 @@ def test_fieldmap(): fieldmap_nii = pjoin(BALLS, 'NIFTI', 'fieldmap.nii.gz') load(fieldmap_par) top_load(fieldmap_nii) - # TODO dj: i believe this shouldn't be here - #raise pytest.skip('Fieldmap remains puzzling') + raise pytest.skip('Fieldmap remains puzzling') @needs_nibabel_data('parrec_oblique') diff --git a/nibabel/tests/test_recoder.py b/nibabel/tests/test_recoder.py index 28eba8860b..8e4edd1b87 100644 --- a/nibabel/tests/test_recoder.py +++ b/nibabel/tests/test_recoder.py @@ -22,14 +22,14 @@ def test_recoder_1(): assert rc.code[1] == 1 assert rc.code[2] == 2 with pytest.raises(KeyError): - rc.code.__getitem__(3) + rc.code[3] def test_recoder_2(): # with explicit name for code codes = ((1,), (2,)) rc = Recoder(codes, ['code1']) with pytest.raises(AttributeError): - rc.__getattribute__('code') + rc.code assert rc.code1[1] == 1 assert rc.code1[2] == 2 @@ -41,20 +41,20 @@ def test_recoder_3(): assert rc.code[1] == 1 assert rc.code[2] == 2 with pytest.raises(KeyError): - rc.code.__getitem__(3) + rc.code[3] assert rc.code['one'] == 1 assert rc.code['two'] == 2 with pytest.raises(KeyError): - rc.code.__getitem__('three') + rc.code['three'] with pytest.raises(AttributeError): - rc.__getattribute__('label') + rc.label def test_recoder_3(): # with explicit column names codes = ((1, 'one'), (2, 'two')) rc = Recoder(codes, ['code1', 'label']) with pytest.raises(AttributeError): - rc.__getattribute__('code') + rc.code assert rc.code1[1] == 1 assert rc.code1['one'] == 1 assert rc.label[1] == 'one' @@ -119,7 +119,7 @@ def test_add_codes(): rc = Recoder(codes) assert rc.code['two'] == 2 with pytest.raises(KeyError): - rc.code.__getitem__('three') + rc.code['three'] rc.add_codes(((3, 'three'), (1, 'number 1'))) assert rc.code['three'] == 3 assert rc.code['number 1'] == 1 @@ -151,7 +151,7 @@ def test_dtmapper(): # dict-like that will lookup on dtypes, even if they don't hash properly d = DtypeMapper() with pytest.raises(KeyError): - d.__getitem__(1) + d[1] d[1] = 'something' assert d[1] == 'something' assert list(d.keys()) == [1] @@ -182,7 +182,7 @@ def test_dtmapper(): sw_dt = canonical_dt.newbyteorder(swapped_code) d[sw_dt] = 'spam' with pytest.raises(KeyError): - d.__getitem__(canonical_dt) + d[canonical_dt] assert d[sw_dt] == 'spam' sw_intp_dt = intp_dt.newbyteorder(swapped_code) assert d[sw_intp_dt] == 'spam' diff --git a/nibabel/tests/test_scaling.py b/nibabel/tests/test_scaling.py index ec335e5c24..db901adb61 100644 --- a/nibabel/tests/test_scaling.py +++ b/nibabel/tests/test_scaling.py @@ -159,35 +159,33 @@ def test_array_file_scales(in_type, out_type, err): # Max rounding error for integer type max_miss = slope / 2. assert np.all(np.abs(arr - arr3) <= max_miss) - bio.truncate(0) - bio.seek(0) -@pytest.mark.parametrize("category0, category1",[ +@pytest.mark.parametrize("in_type, out_type",[ ('int', 'int'), ('uint', 'int'), ]) -def test_scaling_in_abstract(category0, category1): +def test_scaling_in_abstract(in_type, out_type): # Confirm that, for all ints and uints as input, and all possible outputs, # for any simple way of doing the calculation, the result is near enough - for in_type in np.sctypes[category0]: - for out_type in np.sctypes[category1]: - check_int_a2f(in_type, out_type) + for in_tp in np.sctypes[in_type]: + for out_tp in np.sctypes[out_type]: + check_int_a2f(in_tp, out_tp) -@pytest.mark.parametrize("category0, category1", [ +@pytest.mark.parametrize("in_type, out_type", [ ('float', 'int'), ('float', 'uint'), ('complex', 'int'), ('complex', 'uint'), ]) -def test_scaling_in_abstract_warn(category0, category1): +def test_scaling_in_abstract_warn(in_type, out_type): # Converting floats to integer - for in_type in np.sctypes[category0]: - for out_type in np.sctypes[category1]: + for in_tp in np.sctypes[in_type]: + for out_tp in np.sctypes[out_type]: with suppress_warnings(): # overflow - check_int_a2f(in_type, out_type) + check_int_a2f(in_tp, out_tp) def check_int_a2f(in_type, out_type): diff --git a/nibabel/tests/test_spatialimages.py b/nibabel/tests/test_spatialimages.py index 5959057fc9..3de2af99dd 100644 --- a/nibabel/tests/test_spatialimages.py +++ b/nibabel/tests/test_spatialimages.py @@ -384,7 +384,7 @@ def test_get_data(self): "documentation for caveats) or slicing image array data " "with `img.dataobj[slice]` or `img.get_fdata()[slice]`") assert in_data is img.dataobj - with pytest.warns(DeprecationWarning): + with pytest.deprecated_call(): out_data = img.get_data() assert in_data is out_data # and that uncache has no effect @@ -397,18 +397,18 @@ def test_get_data(self): rt_img = bytesio_round_trip(img) assert not in_data is rt_img.dataobj assert (rt_img.dataobj == in_data).all() - with pytest.warns(DeprecationWarning): + with pytest.deprecated_call(): out_data = rt_img.get_data() assert (out_data == in_data).all() assert not rt_img.dataobj is out_data # cache - with pytest.warns(DeprecationWarning): + with pytest.deprecated_call(): assert rt_img.get_data() is out_data out_data[:] = 42 rt_img.uncache() - with pytest.warns(DeprecationWarning): + with pytest.deprecated_call(): assert not rt_img.get_data() is out_data - with pytest.warns(DeprecationWarning): + with pytest.deprecated_call(): assert (rt_img.get_data() == in_data).all() def test_slicer(self): @@ -531,12 +531,12 @@ def test_slicer(self): pass else: sliced_data = in_data[sliceobj] - with pytest.warns(DeprecationWarning): + with pytest.deprecated_call(): assert (sliced_data == sliced_img.get_data()).all() assert (sliced_data == sliced_img.get_fdata()).all() assert (sliced_data == sliced_img.dataobj).all() assert (sliced_data == img.dataobj[sliceobj]).all() - with pytest.warns(DeprecationWarning): + with pytest.deprecated_call(): assert (sliced_data == img.get_data()[sliceobj]).all() assert (sliced_data == img.get_fdata()[sliceobj]).all() @@ -648,12 +648,7 @@ def test_load_mmap(self): def test_header_deprecated(): - with clear_and_catch_warnings() as w: - warnings.simplefilter('always', DeprecationWarning) - + with pytest.deprecated_call(): class MyHeader(Header): pass - assert len(w) == 0 - - MyHeader() - assert len(w) == 1 + MyHeader() \ No newline at end of file diff --git a/nibabel/tests/test_spm99analyze.py b/nibabel/tests/test_spm99analyze.py index e1d559878a..331238db5c 100644 --- a/nibabel/tests/test_spm99analyze.py +++ b/nibabel/tests/test_spm99analyze.py @@ -148,8 +148,7 @@ def test_origin_checks(self): assert (message == 'very large origin values ' 'relative to dims; leaving as set, ' 'ignoring for affine') - with pytest.raises(raiser[0]): - raiser[1](*raiser[2:]) + pytest.raises(*raiser) # diagnose binary block dxer = self.header_class.diagnose_binaryblock assert (dxer(hdr.binaryblock) == From c5ccb2eb8da75ac4c5d27819320126931bf621ef Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:45:57 -0500 Subject: [PATCH 115/223] converting nibabel/tests/test_scripts.py --- nibabel/tests/test_scripts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 873059b510..db83a4d3f5 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') +@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From 5122e2d410d0b86c2bc48a15dfa06fc6d511128d Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:46:26 -0500 Subject: [PATCH 116/223] adding todo --- nibabel/tests/nibabel_data.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 4bc2957c4a..753eeb5e15 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' - +# dj-TODO def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data From a67a9c1cbd95e3aecb6ae114aae4f6b59938d2c7 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 14:50:03 -0500 Subject: [PATCH 117/223] converting more tests nibabel.tests.test_s* --- nibabel/tests/test_spaces.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/nibabel/tests/test_spaces.py b/nibabel/tests/test_spaces.py index a653082f78..7f8ae94c51 100644 --- a/nibabel/tests/test_spaces.py +++ b/nibabel/tests/test_spaces.py @@ -76,7 +76,15 @@ def get_outspace_params(): ) -def test_vox2out_vox(): +@pytest.mark.parametrize("arg_tuple", [ + # Enforce number of axes + ((2, 3, 4, 5), np.eye(4)), + ((2, 3, 4, 5, 6), np.eye(4)), + # Voxel sizes must be positive + ((2, 3, 4), np.eye(4), [-1, 1, 1]), + ((2, 3, 4), np.eye(4), [1, 0, 1]) +]) +def test_vox2out_vox(arg_tuple): # Test world space bounding box # Test basic case, identity, no voxel sizes passed shape, aff = vox2out_vox(((2, 3, 4), np.eye(4))) From 7013d72066f5e0a7c98c4ad2a4843421102c6792 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 16:04:42 -0500 Subject: [PATCH 118/223] removing todos --- nibabel/tests/nibabel_data.py | 2 +- nibabel/tests/test_scripts.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 753eeb5e15..4bc2957c4a 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' -# dj-TODO + def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index db83a4d3f5..873059b510 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data +@needs_nibabel_data('nitest-balls1') def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From 857bed6140b370d0f0f686c2ac00551e15b9caa6 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:45:57 -0500 Subject: [PATCH 119/223] converting nibabel/tests/test_scripts.py --- nibabel/tests/test_scripts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 873059b510..db83a4d3f5 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') +@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From 1a245250b6e220c575caba0e68789d425426b0cc Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:46:26 -0500 Subject: [PATCH 120/223] adding todo --- nibabel/tests/nibabel_data.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 4bc2957c4a..753eeb5e15 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' - +# dj-TODO def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data From fd2ddde0e2b5d5c883dd6ef10901f07a8ec4852d Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 16:04:42 -0500 Subject: [PATCH 121/223] removing todos --- nibabel/tests/nibabel_data.py | 2 +- nibabel/tests/test_scripts.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 753eeb5e15..4bc2957c4a 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' -# dj-TODO + def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index db83a4d3f5..873059b510 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data +@needs_nibabel_data('nitest-balls1') def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From 920b30f72ccf85c6f3794df55a0fbbbaf69bd2d5 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Wed, 5 Feb 2020 10:36:20 -0500 Subject: [PATCH 122/223] small edits: suggestions from reviews --- nibabel/tests/test_spaces.py | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/nibabel/tests/test_spaces.py b/nibabel/tests/test_spaces.py index 7f8ae94c51..a653082f78 100644 --- a/nibabel/tests/test_spaces.py +++ b/nibabel/tests/test_spaces.py @@ -76,15 +76,7 @@ def get_outspace_params(): ) -@pytest.mark.parametrize("arg_tuple", [ - # Enforce number of axes - ((2, 3, 4, 5), np.eye(4)), - ((2, 3, 4, 5, 6), np.eye(4)), - # Voxel sizes must be positive - ((2, 3, 4), np.eye(4), [-1, 1, 1]), - ((2, 3, 4), np.eye(4), [1, 0, 1]) -]) -def test_vox2out_vox(arg_tuple): +def test_vox2out_vox(): # Test world space bounding box # Test basic case, identity, no voxel sizes passed shape, aff = vox2out_vox(((2, 3, 4), np.eye(4))) From f331d20653ec820c83927194250a4fea66305cf5 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:45:57 -0500 Subject: [PATCH 123/223] converting nibabel/tests/test_scripts.py --- nibabel/tests/test_scripts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 873059b510..db83a4d3f5 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') +@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From 975178477ddb33de93a9b8ef2a2eee8066ab4f84 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:46:26 -0500 Subject: [PATCH 124/223] adding todo --- nibabel/tests/nibabel_data.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 4bc2957c4a..753eeb5e15 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' - +# dj-TODO def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data From 29da7b06d6c74f27b03599faf5fa0786edfe7862 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 14:50:03 -0500 Subject: [PATCH 125/223] converting more tests nibabel.tests.test_s* --- nibabel/tests/test_spaces.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/nibabel/tests/test_spaces.py b/nibabel/tests/test_spaces.py index a653082f78..7f8ae94c51 100644 --- a/nibabel/tests/test_spaces.py +++ b/nibabel/tests/test_spaces.py @@ -76,7 +76,15 @@ def get_outspace_params(): ) -def test_vox2out_vox(): +@pytest.mark.parametrize("arg_tuple", [ + # Enforce number of axes + ((2, 3, 4, 5), np.eye(4)), + ((2, 3, 4, 5, 6), np.eye(4)), + # Voxel sizes must be positive + ((2, 3, 4), np.eye(4), [-1, 1, 1]), + ((2, 3, 4), np.eye(4), [1, 0, 1]) +]) +def test_vox2out_vox(arg_tuple): # Test world space bounding box # Test basic case, identity, no voxel sizes passed shape, aff = vox2out_vox(((2, 3, 4), np.eye(4))) From f42da0401d093a1dee51faf9a0756406e5475c92 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 16:04:42 -0500 Subject: [PATCH 126/223] removing todos --- nibabel/tests/nibabel_data.py | 2 +- nibabel/tests/test_scripts.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 753eeb5e15..4bc2957c4a 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' -# dj-TODO + def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index db83a4d3f5..873059b510 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data +@needs_nibabel_data('nitest-balls1') def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From dff77ba68d189e3280f436acbc531f56d7d86e11 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:45:57 -0500 Subject: [PATCH 127/223] converting nibabel/tests/test_scripts.py --- nibabel/tests/test_scripts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 873059b510..db83a4d3f5 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') +@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From 61bc71498a938042f241c7f2b2c270cfac9c81d0 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:46:26 -0500 Subject: [PATCH 128/223] adding todo --- nibabel/tests/nibabel_data.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 4bc2957c4a..753eeb5e15 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' - +# dj-TODO def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data From 338b4c3734f14ec52bbd729fe4d3d9e2b66f568f Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 16:04:42 -0500 Subject: [PATCH 129/223] removing todos --- nibabel/tests/nibabel_data.py | 2 +- nibabel/tests/test_scripts.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 753eeb5e15..4bc2957c4a 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' -# dj-TODO + def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index db83a4d3f5..873059b510 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data +@needs_nibabel_data('nitest-balls1') def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From 2d799c4b7fec1caa2551b6f3a023f64e1d6ac952 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Wed, 5 Feb 2020 10:36:20 -0500 Subject: [PATCH 130/223] small edits: suggestions from reviews --- nibabel/tests/test_spaces.py | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/nibabel/tests/test_spaces.py b/nibabel/tests/test_spaces.py index 7f8ae94c51..a653082f78 100644 --- a/nibabel/tests/test_spaces.py +++ b/nibabel/tests/test_spaces.py @@ -76,15 +76,7 @@ def get_outspace_params(): ) -@pytest.mark.parametrize("arg_tuple", [ - # Enforce number of axes - ((2, 3, 4, 5), np.eye(4)), - ((2, 3, 4, 5, 6), np.eye(4)), - # Voxel sizes must be positive - ((2, 3, 4), np.eye(4), [-1, 1, 1]), - ((2, 3, 4), np.eye(4), [1, 0, 1]) -]) -def test_vox2out_vox(arg_tuple): +def test_vox2out_vox(): # Test world space bounding box # Test basic case, identity, no voxel sizes passed shape, aff = vox2out_vox(((2, 3, 4), np.eye(4))) From 436404f0dc0d06ecf7880713c4a83636f9644b1b Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:45:57 -0500 Subject: [PATCH 131/223] converting nibabel/tests/test_scripts.py --- nibabel/tests/test_scripts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 873059b510..db83a4d3f5 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') +@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From 831e553fdb630b0e457155ecfcaff11c390a8e77 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:46:26 -0500 Subject: [PATCH 132/223] adding todo --- nibabel/tests/nibabel_data.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 4bc2957c4a..753eeb5e15 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' - +# dj-TODO def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data From 099e5cf9d912f742b5776b9b7a36efc532680355 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 14:50:03 -0500 Subject: [PATCH 133/223] converting more tests nibabel.tests.test_s* --- nibabel/tests/test_spaces.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/nibabel/tests/test_spaces.py b/nibabel/tests/test_spaces.py index a653082f78..7f8ae94c51 100644 --- a/nibabel/tests/test_spaces.py +++ b/nibabel/tests/test_spaces.py @@ -76,7 +76,15 @@ def get_outspace_params(): ) -def test_vox2out_vox(): +@pytest.mark.parametrize("arg_tuple", [ + # Enforce number of axes + ((2, 3, 4, 5), np.eye(4)), + ((2, 3, 4, 5, 6), np.eye(4)), + # Voxel sizes must be positive + ((2, 3, 4), np.eye(4), [-1, 1, 1]), + ((2, 3, 4), np.eye(4), [1, 0, 1]) +]) +def test_vox2out_vox(arg_tuple): # Test world space bounding box # Test basic case, identity, no voxel sizes passed shape, aff = vox2out_vox(((2, 3, 4), np.eye(4))) From 91be3bfec2a8b724a96b81fb1d401e6793ddd332 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 15:56:41 -0500 Subject: [PATCH 134/223] converting nibabel_data --- nibabel/tests/nibabel_data.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 753eeb5e15..89a1e1c9b2 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -46,4 +46,4 @@ def needs_nibabel_data(subdir=None): # Path should not be empty (as is the case for not-updated submodules) have_files = exists(required_path) and len(listdir(required_path)) > 0 return pytest.mark.skipif(not have_files, - reason="Need files in {0} for these tests".format(required_path)) + reason="Need files in {0} for these tests".format(required_path)) \ No newline at end of file From 4becc96b8e6d43e814bf0bb79bf8855942498087 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 16:04:42 -0500 Subject: [PATCH 135/223] removing todos --- nibabel/tests/nibabel_data.py | 2 +- nibabel/tests/test_scripts.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 89a1e1c9b2..e2e5bc9ed3 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' -# dj-TODO + def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index db83a4d3f5..873059b510 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data +@needs_nibabel_data('nitest-balls1') def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From ddb21c3b83a35ca2bf7d7baea5b8d90cc707b09c Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:45:57 -0500 Subject: [PATCH 136/223] converting nibabel/tests/test_scripts.py --- nibabel/tests/test_scripts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 873059b510..db83a4d3f5 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') +@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From 5ca8a74afb126dfd2d0414badd410d2f404ec9ff Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:46:26 -0500 Subject: [PATCH 137/223] adding todo --- nibabel/tests/nibabel_data.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index e2e5bc9ed3..89a1e1c9b2 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' - +# dj-TODO def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data From 93732925c832571d0d0d496768d8c45662ecf68f Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 16:04:42 -0500 Subject: [PATCH 138/223] removing todos --- nibabel/tests/nibabel_data.py | 2 +- nibabel/tests/test_scripts.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 89a1e1c9b2..e2e5bc9ed3 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' -# dj-TODO + def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index db83a4d3f5..873059b510 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data +@needs_nibabel_data('nitest-balls1') def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From 20dcc697702b102895e029ed5fe080dbfcae2f2f Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Wed, 5 Feb 2020 10:36:20 -0500 Subject: [PATCH 139/223] small edits: suggestions from reviews --- nibabel/tests/test_spaces.py | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/nibabel/tests/test_spaces.py b/nibabel/tests/test_spaces.py index 7f8ae94c51..a653082f78 100644 --- a/nibabel/tests/test_spaces.py +++ b/nibabel/tests/test_spaces.py @@ -76,15 +76,7 @@ def get_outspace_params(): ) -@pytest.mark.parametrize("arg_tuple", [ - # Enforce number of axes - ((2, 3, 4, 5), np.eye(4)), - ((2, 3, 4, 5, 6), np.eye(4)), - # Voxel sizes must be positive - ((2, 3, 4), np.eye(4), [-1, 1, 1]), - ((2, 3, 4), np.eye(4), [1, 0, 1]) -]) -def test_vox2out_vox(arg_tuple): +def test_vox2out_vox(): # Test world space bounding box # Test basic case, identity, no voxel sizes passed shape, aff = vox2out_vox(((2, 3, 4), np.eye(4))) From f6f5e0421ccf1c9bc2ccd2e13e827c23c15a3ff5 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:45:57 -0500 Subject: [PATCH 140/223] converting nibabel/tests/test_scripts.py --- nibabel/tests/test_scripts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 873059b510..db83a4d3f5 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') +@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From 13bacafc3c5611ee92f02296216237a8931df706 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:46:26 -0500 Subject: [PATCH 141/223] adding todo --- nibabel/tests/nibabel_data.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index e2e5bc9ed3..89a1e1c9b2 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' - +# dj-TODO def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data From 525b99d68b6433a02a9dce3aca01d60812abbe05 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 14:50:03 -0500 Subject: [PATCH 142/223] converting more tests nibabel.tests.test_s* --- nibabel/tests/test_spaces.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/nibabel/tests/test_spaces.py b/nibabel/tests/test_spaces.py index a653082f78..7f8ae94c51 100644 --- a/nibabel/tests/test_spaces.py +++ b/nibabel/tests/test_spaces.py @@ -76,7 +76,15 @@ def get_outspace_params(): ) -def test_vox2out_vox(): +@pytest.mark.parametrize("arg_tuple", [ + # Enforce number of axes + ((2, 3, 4, 5), np.eye(4)), + ((2, 3, 4, 5, 6), np.eye(4)), + # Voxel sizes must be positive + ((2, 3, 4), np.eye(4), [-1, 1, 1]), + ((2, 3, 4), np.eye(4), [1, 0, 1]) +]) +def test_vox2out_vox(arg_tuple): # Test world space bounding box # Test basic case, identity, no voxel sizes passed shape, aff = vox2out_vox(((2, 3, 4), np.eye(4))) From 82c39a1bc395f091490238e28ad45772df732efb Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 16:04:42 -0500 Subject: [PATCH 143/223] removing todos --- nibabel/tests/nibabel_data.py | 2 +- nibabel/tests/test_scripts.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 89a1e1c9b2..e2e5bc9ed3 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' -# dj-TODO + def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index db83a4d3f5..873059b510 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data +@needs_nibabel_data('nitest-balls1') def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From ff899a373c6121633bb0c61bd26a2a6435cc9106 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:45:57 -0500 Subject: [PATCH 144/223] converting nibabel/tests/test_scripts.py --- nibabel/tests/test_scripts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 873059b510..db83a4d3f5 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') +@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From 9daf10f15726856ff5b9bd366cc49e5a8d2e364e Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:46:26 -0500 Subject: [PATCH 145/223] adding todo --- nibabel/tests/nibabel_data.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index e2e5bc9ed3..89a1e1c9b2 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' - +# dj-TODO def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data From b1d8cfb1c47281293788c41ff9ef28a0bbfd2767 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 16:04:42 -0500 Subject: [PATCH 146/223] removing todos --- nibabel/tests/nibabel_data.py | 2 +- nibabel/tests/test_scripts.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 89a1e1c9b2..e2e5bc9ed3 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' -# dj-TODO + def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index db83a4d3f5..873059b510 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data +@needs_nibabel_data('nitest-balls1') def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From 75f2ce667db957d7b710b9f8f510866221485b7c Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Wed, 5 Feb 2020 10:36:20 -0500 Subject: [PATCH 147/223] small edits: suggestions from reviews --- nibabel/tests/test_spaces.py | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/nibabel/tests/test_spaces.py b/nibabel/tests/test_spaces.py index 7f8ae94c51..a653082f78 100644 --- a/nibabel/tests/test_spaces.py +++ b/nibabel/tests/test_spaces.py @@ -76,15 +76,7 @@ def get_outspace_params(): ) -@pytest.mark.parametrize("arg_tuple", [ - # Enforce number of axes - ((2, 3, 4, 5), np.eye(4)), - ((2, 3, 4, 5, 6), np.eye(4)), - # Voxel sizes must be positive - ((2, 3, 4), np.eye(4), [-1, 1, 1]), - ((2, 3, 4), np.eye(4), [1, 0, 1]) -]) -def test_vox2out_vox(arg_tuple): +def test_vox2out_vox(): # Test world space bounding box # Test basic case, identity, no voxel sizes passed shape, aff = vox2out_vox(((2, 3, 4), np.eye(4))) From 683a3ee8e284ff0156c4d4dd91d262e4d25a2464 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:45:57 -0500 Subject: [PATCH 148/223] converting nibabel/tests/test_scripts.py --- nibabel/tests/test_scripts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 873059b510..db83a4d3f5 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') +@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From 39c011e5cdcfcd807d23177289f8a32feddfbf51 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:46:26 -0500 Subject: [PATCH 149/223] adding todo --- nibabel/tests/nibabel_data.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index e2e5bc9ed3..89a1e1c9b2 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' - +# dj-TODO def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data From d5e5907abd2c85bfbff8de2ebc929cb91d25f319 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 14:50:03 -0500 Subject: [PATCH 150/223] converting more tests nibabel.tests.test_s* --- nibabel/tests/test_spaces.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/nibabel/tests/test_spaces.py b/nibabel/tests/test_spaces.py index a653082f78..7f8ae94c51 100644 --- a/nibabel/tests/test_spaces.py +++ b/nibabel/tests/test_spaces.py @@ -76,7 +76,15 @@ def get_outspace_params(): ) -def test_vox2out_vox(): +@pytest.mark.parametrize("arg_tuple", [ + # Enforce number of axes + ((2, 3, 4, 5), np.eye(4)), + ((2, 3, 4, 5, 6), np.eye(4)), + # Voxel sizes must be positive + ((2, 3, 4), np.eye(4), [-1, 1, 1]), + ((2, 3, 4), np.eye(4), [1, 0, 1]) +]) +def test_vox2out_vox(arg_tuple): # Test world space bounding box # Test basic case, identity, no voxel sizes passed shape, aff = vox2out_vox(((2, 3, 4), np.eye(4))) From f7b49f38601b42276b8cc0445fd58a3130729ac4 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 16:04:42 -0500 Subject: [PATCH 151/223] removing todos --- nibabel/tests/nibabel_data.py | 2 +- nibabel/tests/test_scripts.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 89a1e1c9b2..e2e5bc9ed3 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' -# dj-TODO + def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index db83a4d3f5..873059b510 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data +@needs_nibabel_data('nitest-balls1') def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From cdf6e182a2dfca3611a63b1cdc32e1a036b64fd5 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:45:57 -0500 Subject: [PATCH 152/223] converting nibabel/tests/test_scripts.py --- nibabel/tests/test_scripts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 873059b510..db83a4d3f5 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') +@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From 8ba8134a023850d27da6f632b5a07bc138b0a0f8 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:46:26 -0500 Subject: [PATCH 153/223] adding todo --- nibabel/tests/nibabel_data.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index e2e5bc9ed3..89a1e1c9b2 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' - +# dj-TODO def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data From e86066942737afe3e1267b7da675dbb74186c86d Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 16:04:42 -0500 Subject: [PATCH 154/223] removing todos --- nibabel/tests/nibabel_data.py | 2 +- nibabel/tests/test_scripts.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 89a1e1c9b2..e2e5bc9ed3 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' -# dj-TODO + def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index db83a4d3f5..873059b510 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data +@needs_nibabel_data('nitest-balls1') def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From 32c1c1739fa6c3fa4e2655a1aa88750b0adb1626 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Wed, 5 Feb 2020 10:36:20 -0500 Subject: [PATCH 155/223] small edits: suggestions from reviews --- nibabel/tests/test_spaces.py | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/nibabel/tests/test_spaces.py b/nibabel/tests/test_spaces.py index 7f8ae94c51..a653082f78 100644 --- a/nibabel/tests/test_spaces.py +++ b/nibabel/tests/test_spaces.py @@ -76,15 +76,7 @@ def get_outspace_params(): ) -@pytest.mark.parametrize("arg_tuple", [ - # Enforce number of axes - ((2, 3, 4, 5), np.eye(4)), - ((2, 3, 4, 5, 6), np.eye(4)), - # Voxel sizes must be positive - ((2, 3, 4), np.eye(4), [-1, 1, 1]), - ((2, 3, 4), np.eye(4), [1, 0, 1]) -]) -def test_vox2out_vox(arg_tuple): +def test_vox2out_vox(): # Test world space bounding box # Test basic case, identity, no voxel sizes passed shape, aff = vox2out_vox(((2, 3, 4), np.eye(4))) From 8a9f53d2e92c58fae73ac2825520e64aef2aad9f Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:45:57 -0500 Subject: [PATCH 156/223] converting nibabel/tests/test_scripts.py --- nibabel/tests/test_scripts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 873059b510..db83a4d3f5 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') +@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From 50e7d98b0a72342b1b5a11067a2982ec61529188 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:46:26 -0500 Subject: [PATCH 157/223] adding todo --- nibabel/tests/nibabel_data.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index e2e5bc9ed3..89a1e1c9b2 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' - +# dj-TODO def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data From d4f2044bd791062501042c272812b27f28e57ff0 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 14:50:03 -0500 Subject: [PATCH 158/223] converting more tests nibabel.tests.test_s* --- nibabel/tests/test_spaces.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/nibabel/tests/test_spaces.py b/nibabel/tests/test_spaces.py index a653082f78..7f8ae94c51 100644 --- a/nibabel/tests/test_spaces.py +++ b/nibabel/tests/test_spaces.py @@ -76,7 +76,15 @@ def get_outspace_params(): ) -def test_vox2out_vox(): +@pytest.mark.parametrize("arg_tuple", [ + # Enforce number of axes + ((2, 3, 4, 5), np.eye(4)), + ((2, 3, 4, 5, 6), np.eye(4)), + # Voxel sizes must be positive + ((2, 3, 4), np.eye(4), [-1, 1, 1]), + ((2, 3, 4), np.eye(4), [1, 0, 1]) +]) +def test_vox2out_vox(arg_tuple): # Test world space bounding box # Test basic case, identity, no voxel sizes passed shape, aff = vox2out_vox(((2, 3, 4), np.eye(4))) From 547ba9265415619486ac1a770cf4714e73690d70 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 16:04:42 -0500 Subject: [PATCH 159/223] removing todos --- nibabel/tests/nibabel_data.py | 2 +- nibabel/tests/test_scripts.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 89a1e1c9b2..e2e5bc9ed3 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' -# dj-TODO + def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index db83a4d3f5..873059b510 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data +@needs_nibabel_data('nitest-balls1') def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From d8a15afcf70d7aeafed9ea558c261bf762a1731b Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:45:57 -0500 Subject: [PATCH 160/223] converting nibabel/tests/test_scripts.py --- nibabel/tests/test_scripts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 873059b510..db83a4d3f5 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') +@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From 4e32787f09c89a78f0af18aa5ab71f273ef20b3d Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 11:46:26 -0500 Subject: [PATCH 161/223] adding todo --- nibabel/tests/nibabel_data.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index e2e5bc9ed3..89a1e1c9b2 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' - +# dj-TODO def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data From 59af0aa0718c49131895aec9d8307714eaca8fae Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Tue, 4 Feb 2020 16:04:42 -0500 Subject: [PATCH 162/223] removing todos --- nibabel/tests/nibabel_data.py | 2 +- nibabel/tests/test_scripts.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 89a1e1c9b2..e2e5bc9ed3 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -22,7 +22,7 @@ def get_nibabel_data(): nibabel_data = pjoin(containing_path, 'nibabel-data') return nibabel_data if isdir(nibabel_data) else '' -# dj-TODO + def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index db83a4d3f5..873059b510 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -297,7 +297,7 @@ def test_parrec2nii(): @script_test -@needs_nibabel_data('nitest-balls1') #dj-TODO: together eith nibabel_data +@needs_nibabel_data('nitest-balls1') def test_parrec2nii_with_data(): # Use nibabel-data to test conversion # Premultiplier to relate our affines to Philips conversion From a21c0834188b9a5708f6e82cc885513a1ac46275 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Wed, 5 Feb 2020 10:36:20 -0500 Subject: [PATCH 163/223] small edits: suggestions from reviews --- nibabel/tests/test_spaces.py | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/nibabel/tests/test_spaces.py b/nibabel/tests/test_spaces.py index 7f8ae94c51..a653082f78 100644 --- a/nibabel/tests/test_spaces.py +++ b/nibabel/tests/test_spaces.py @@ -76,15 +76,7 @@ def get_outspace_params(): ) -@pytest.mark.parametrize("arg_tuple", [ - # Enforce number of axes - ((2, 3, 4, 5), np.eye(4)), - ((2, 3, 4, 5, 6), np.eye(4)), - # Voxel sizes must be positive - ((2, 3, 4), np.eye(4), [-1, 1, 1]), - ((2, 3, 4), np.eye(4), [1, 0, 1]) -]) -def test_vox2out_vox(arg_tuple): +def test_vox2out_vox(): # Test world space bounding box # Test basic case, identity, no voxel sizes passed shape, aff = vox2out_vox(((2, 3, 4), np.eye(4))) From 8d929771fa3e7d802abf3b333d9cac545971079c Mon Sep 17 00:00:00 2001 From: orduek Date: Wed, 5 Feb 2020 16:49:25 -0500 Subject: [PATCH 164/223] fixes to assert numpy --- nibabel/freesurfer/tests/test_io.py | 16 +++++++++------- nibabel/freesurfer/tests/test_mghformat.py | 6 +++--- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index 77a8bc12a0..1ca5027bf9 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -61,8 +61,9 @@ def test_geometry(): assert 0 == faces.min() assert coords.shape[0] == (faces.max() + 1) assert 9 == len(volume_info) - assert [2, 0, 20] == volume_info['head'] - assert ['created by greve on Thu Jun 8 19:17:51 2006'] == create_stamp + # assert np.array_equal([2, 0, 20],volume_info['head']) + np.testing.assert_array_equal([2, 0, 20],volume_info['head']) + assert create_stamp == ['created by greve on Thu Jun 8 19:17:51 2006'] # this creates assertion error - should we just remove it? # Test equivalence of freesurfer- and nibabel-generated triangular files # with respect to read_geometry() @@ -79,7 +80,8 @@ def test_geometry(): for key in ('xras', 'yras', 'zras', 'cras'): assert_allclose(volume_info2[key], volume_info[key], rtol=1e-7, atol=1e-30) - assert volume_info2['cras'] == volume_info['cras'] + #assert.array_equal(volume_info2['cras'], volume_info['cras']) + np.testing.assert_array_equal(volume_info2['cras'], volume_info['cras']) with open(surf_path, 'rb') as fobj: np.fromfile(fobj, ">u1", 3) read_create_stamp = fobj.readline().decode().rstrip('\n') @@ -126,8 +128,8 @@ def test_quad_geometry(): new_path = 'test' write_geometry(new_path, coords, faces) coords2, faces2 = read_geometry(new_path) - assert coords == coords2 - assert faces == faces2 + assert np.array_equal(coords,coords2) + assert np.array_equal(faces, faces2) @freesurfer_test @@ -141,7 +143,7 @@ def test_morph_data(): new_path = 'test' write_morph_data(new_path, curv) curv2 = read_morph_data(new_path) - assert curv2 == curv + assert np.array_equal (curv2, curv) def test_write_morph_data(): @@ -154,7 +156,7 @@ def test_write_morph_data(): for shape in okay_shapes: write_morph_data('test.curv', values.reshape(shape)) # Check ordering is preserved, regardless of shape - assert values == read_morph_data('test.curv') + assert np.array_equal(read_morph_data('test.curv') ,values) with pytest.raises(ValueError): write_morph_data('test.curv', np.zeros(shape), big_num) # Windows 32-bit overflows Python int diff --git a/nibabel/freesurfer/tests/test_mghformat.py b/nibabel/freesurfer/tests/test_mghformat.py index 37b2faa2b4..41bffbf6ac 100644 --- a/nibabel/freesurfer/tests/test_mghformat.py +++ b/nibabel/freesurfer/tests/test_mghformat.py @@ -26,7 +26,7 @@ import pytest -from numpy.testing import (assert_array_equal, assert_array_almost_equal, assert_almost_equal) +from numpy.testing import assert_array_equal, assert_array_almost_equal, assert_almost_equal from ...testing_pytest import data_path @@ -218,14 +218,14 @@ def test_header_updating(): assert_almost_equal(mgz.affine, exp_aff, 6) assert_almost_equal(hdr.get_affine(), exp_aff, 6) # Test that initial wonky header elements have not changed - assert hdr['delta'] == 1 + assert_array_equal(hdr['delta'], 1) assert_almost_equal(hdr['Mdc'].T, exp_aff[:3, :3]) # Save, reload, same thing img_fobj = io.BytesIO() mgz2 = _mgh_rt(mgz, img_fobj) hdr2 = mgz2.header assert_almost_equal(hdr2.get_affine(), exp_aff, 6) - assert hdr2['delta'] == 1 + assert_array_equal(hdr2['delta'],1) # Change affine, change underlying header info exp_aff_d = exp_aff.copy() exp_aff_d[0, -1] = -14 From ae39e06629dfe792745dd97b71461e85d0fad887 Mon Sep 17 00:00:00 2001 From: orduek Date: Tue, 4 Feb 2020 15:35:14 -0500 Subject: [PATCH 165/223] changed nosetools assert_true to assert in test_io.py --- nibabel/freesurfer/tests/test_io.py | 35 +++++++++++++++-------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index fc926ee2af..41bcdd17cf 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -9,7 +9,8 @@ from ...tmpdirs import InTemporaryDirectory -from nose.tools import assert_true + +import pytest import numpy as np from numpy.testing import assert_equal, assert_raises, dec, assert_allclose, assert_array_equal @@ -92,13 +93,13 @@ def test_geometry(): with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) read_geometry(surf_path, read_metadata=True) - assert_true(any('volume information contained' in str(ww.message) + assert(any('volume information contained' in str(ww.message) for ww in w)) - assert_true(any('extension code' in str(ww.message) for ww in w)) + assert(any('extension code' in str(ww.message) for ww in w)) volume_info['head'] = [1, 2] with clear_and_catch_warnings() as w: write_geometry(surf_path, coords, faces, create_stamp, volume_info) - assert_true(any('Unknown extension' in str(ww.message) for ww in w)) + assert(any('Unknown extension' in str(ww.message) for ww in w)) volume_info['a'] = 0 assert_raises(ValueError, write_geometry, surf_path, coords, faces, create_stamp, volume_info) @@ -137,8 +138,8 @@ def test_morph_data(): """Test IO of morphometry data file (eg. curvature).""" curv_path = pjoin(data_path, "surf", "%s.%s" % ("lh", "curv")) curv = read_morph_data(curv_path) - assert_true(-1.0 < curv.min() < 0) - assert_true(0 < curv.max() < 1.0) + assert(-1.0 < curv.min() < 0) + assert(0 < curv.max() < 1.0) with InTemporaryDirectory(): new_path = 'test' write_morph_data(new_path, curv) @@ -177,8 +178,8 @@ def test_annot(): hash_ = _hash_file_content(annot_path) labels, ctab, names = read_annot(annot_path) - assert_true(labels.shape == (163842, )) - assert_true(ctab.shape == (len(names), 5)) + assert(labels.shape == (163842, )) + assert(ctab.shape == (len(names), 5)) labels_orig = None if a == 'aparc': @@ -186,9 +187,9 @@ def test_annot(): np.testing.assert_array_equal(labels == -1, labels_orig == 0) # Handle different version of fsaverage if hash_ == 'bf0b488994657435cdddac5f107d21e8': - assert_true(np.sum(labels_orig == 0) == 13887) + assert(np.sum(labels_orig == 0) == 13887) elif hash_ == 'd4f5b7cbc2ed363ac6fcf89e19353504': - assert_true(np.sum(labels_orig == 1639705) == 13327) + assert(np.sum(labels_orig == 1639705) == 13327) else: raise RuntimeError("Unknown freesurfer file. Please report " "the problem to the maintainer of nibabel.") @@ -272,7 +273,7 @@ def test_write_annot_fill_ctab(): print(labels) with clear_and_catch_warnings() as w: write_annot(annot_path, labels, rgbal, names, fill_ctab=False) - assert_true( + assert( any('Annotation values in {} will be incorrect'.format( annot_path) == str(ww.message) for ww in w)) labels2, rgbal2, names2 = read_annot(annot_path, orig_ids=True) @@ -288,7 +289,7 @@ def test_write_annot_fill_ctab(): rgbal[:, 2] * (2 ** 16)) with clear_and_catch_warnings() as w: write_annot(annot_path, labels, rgbal, names, fill_ctab=False) - assert_true( + assert( not any('Annotation values in {} will be incorrect'.format( annot_path) == str(ww.message) for ww in w)) labels2, rgbal2, names2 = read_annot(annot_path) @@ -348,13 +349,13 @@ def test_label(): label_path = pjoin(data_path, "label", "lh.cortex.label") label = read_label(label_path) # XXX : test more - assert_true(label.min() >= 0) - assert_true(label.max() <= 163841) - assert_true(label.shape[0] <= 163842) + assert(label.min() >= 0) + assert(label.max() <= 163841) + assert(label.shape[0] <= 163842) labels, scalars = read_label(label_path, True) - assert_true(np.all(labels == label)) - assert_true(len(labels) == len(scalars)) + assert(np.all(labels == label)) + assert(len(labels) == len(scalars)) def test_write_annot_maxstruct(): From 665b28ae6f15a4f6698571fc1a263a500d5605f5 Mon Sep 17 00:00:00 2001 From: orduek Date: Tue, 4 Feb 2020 15:59:43 -0500 Subject: [PATCH 166/223] changed nosetools assertion to pytest in test_mghformat.py --- nibabel/freesurfer/tests/test_mghformat.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/nibabel/freesurfer/tests/test_mghformat.py b/nibabel/freesurfer/tests/test_mghformat.py index 289acbcd01..25a7254def 100644 --- a/nibabel/freesurfer/tests/test_mghformat.py +++ b/nibabel/freesurfer/tests/test_mghformat.py @@ -23,7 +23,8 @@ from ...wrapstruct import WrapStructError from ... import imageglobals -from nose.tools import assert_true, assert_false + +import pytest from numpy.testing import (assert_equal, assert_array_equal, assert_array_almost_equal, assert_almost_equal, @@ -260,7 +261,7 @@ def test_eq(): hdr2 = MGHHeader() assert_equal(hdr, hdr2) hdr.set_data_shape((2, 3, 4)) - assert_false(hdr == hdr2) + assert(hdr != hdr2) hdr2.set_data_shape((2, 3, 4)) assert_equal(hdr, hdr2) @@ -287,7 +288,7 @@ def test_mgh_load_fileobj(): bio = io.BytesIO(contents) fm = MGHImage.make_file_map(mapping=dict(image=bio)) img2 = MGHImage.from_file_map(fm) - assert_true(img2.dataobj.file_like is bio) + assert(img2.dataobj.file_like is bio) assert_array_equal(img.get_fdata(), img2.get_fdata()) @@ -477,7 +478,7 @@ def test_as_byteswapped(self): # same code just returns a copy for endianness in BIG_CODES: hdr2 = hdr.as_byteswapped(endianness) - assert_false(hdr2 is hdr) + assert(hdr2 is not hdr) assert_equal(hdr2, hdr) # Different code raises error From 441e4fe7d6b99687122a6736373ef0d30ca90da5 Mon Sep 17 00:00:00 2001 From: orduek Date: Tue, 4 Feb 2020 17:07:58 -0500 Subject: [PATCH 167/223] changed from numpy raises to pytest.raises and skipif --- nibabel/freesurfer/tests/test_io.py | 65 ++++++++++++++--------------- 1 file changed, 31 insertions(+), 34 deletions(-) diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index 41bcdd17cf..cde2edeb5f 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -12,7 +12,7 @@ import pytest import numpy as np -from numpy.testing import assert_equal, assert_raises, dec, assert_allclose, assert_array_equal +from numpy.testing import assert_allclose, assert_array_equal from .. import (read_geometry, read_morph_data, read_annot, read_label, write_geometry, write_morph_data, write_annot) @@ -20,7 +20,7 @@ from ...tests.nibabel_data import get_nibabel_data, needs_nibabel_data from ...fileslice import strided_scalar -from ...testing import clear_and_catch_warnings +from ...testing_pytest import clear_and_catch_warnings DATA_SDIR = 'fsaverage' @@ -36,10 +36,7 @@ data_path = pjoin(nib_data, 'nitest-freesurfer', DATA_SDIR) have_freesurfer = isdir(data_path) -freesurfer_test = dec.skipif( - not have_freesurfer, - 'cannot find freesurfer {0} directory'.format(DATA_SDIR)) - +freesurfer_test = pytest.mark.skipif(not have_freesurfer, reason='cannot find freesurfer {0} directory'.format(DATA_SDIR)) def _hash_file_content(fname): hasher = hashlib.md5() @@ -54,19 +51,18 @@ def test_geometry(): """Test IO of .surf""" surf_path = pjoin(data_path, "surf", "%s.%s" % ("lh", "inflated")) coords, faces = read_geometry(surf_path) - assert_equal(0, faces.min()) - assert_equal(coords.shape[0], faces.max() + 1) + assert 0==faces.min() + assert coords.shape[0]== faces.max() + 1 surf_path = pjoin(data_path, "surf", "%s.%s" % ("lh", "sphere")) coords, faces, volume_info, create_stamp = read_geometry( surf_path, read_metadata=True, read_stamp=True) - assert_equal(0, faces.min()) - assert_equal(coords.shape[0], faces.max() + 1) - assert_equal(9, len(volume_info)) - assert_equal([2, 0, 20], volume_info['head']) - assert_equal(u'created by greve on Thu Jun 8 19:17:51 2006', - create_stamp) + assert 0 == faces.min() + assert coords.shape[0] == faces.max() + 1 + assert 9 == len(volume_info) + assert [2, 0, 20] == volume_info['head'] + assert 'created by greve on Thu Jun 8 19:17:51 2006' == create_stamp # Test equivalence of freesurfer- and nibabel-generated triangular files # with respect to read_geometry() @@ -83,7 +79,7 @@ def test_geometry(): for key in ('xras', 'yras', 'zras', 'cras'): assert_allclose(volume_info2[key], volume_info[key], rtol=1e-7, atol=1e-30) - assert_equal(volume_info2['cras'], volume_info['cras']) + assert volume_info2['cras'] == volume_info['cras'] with open(surf_path, 'rb') as fobj: np.fromfile(fobj, ">u1", 3) read_create_stamp = fobj.readline().decode().rstrip('\n') @@ -101,10 +97,11 @@ def test_geometry(): write_geometry(surf_path, coords, faces, create_stamp, volume_info) assert(any('Unknown extension' in str(ww.message) for ww in w)) volume_info['a'] = 0 - assert_raises(ValueError, write_geometry, surf_path, coords, - faces, create_stamp, volume_info) + with pytest.raises(ValueError): + write_geometry(surf_path, coords, faces, create_stamp, volume_info) + - assert_equal(create_stamp, read_create_stamp) + assert create_stamp == read_create_stamp np.testing.assert_array_equal(coords, coords2) np.testing.assert_array_equal(faces, faces2) @@ -123,14 +120,14 @@ def test_quad_geometry(): new_quad = pjoin(get_nibabel_data(), 'nitest-freesurfer', 'subjects', 'bert', 'surf', 'lh.inflated.nofix') coords, faces = read_geometry(new_quad) - assert_equal(0, faces.min()) - assert_equal(coords.shape[0], faces.max() + 1) + assert 0 == faces.min() + assert coords.shape[0] == faces.max() + 1 with InTemporaryDirectory(): new_path = 'test' write_geometry(new_path, coords, faces) coords2, faces2 = read_geometry(new_path) - assert_equal(coords, coords2) - assert_equal(faces, faces2) + assert coords == coords2 + assert faces == faces2 @freesurfer_test @@ -144,7 +141,7 @@ def test_morph_data(): new_path = 'test' write_morph_data(new_path, curv) curv2 = read_morph_data(new_path) - assert_equal(curv2, curv) + assert curv2 == curv def test_write_morph_data(): @@ -157,17 +154,17 @@ def test_write_morph_data(): for shape in okay_shapes: write_morph_data('test.curv', values.reshape(shape)) # Check ordering is preserved, regardless of shape - assert_equal(values, read_morph_data('test.curv')) - assert_raises(ValueError, write_morph_data, 'test.curv', - np.zeros(shape), big_num) - # Windows 32-bit overflows Python int + assert values == read_morph_data('test.curv') + with pytest.raises(ValueError): + write_morph_data('test.curv', np.zeros(shape), big_num) + # Windows 32-bit overflows Python int if np.dtype(np.int) != np.dtype(np.int32): - assert_raises(ValueError, write_morph_data, 'test.curv', - strided_scalar((big_num,))) + with pytest.raises(ValueError): + write_morph_data('test.curv', strided_scalar((big_num,))) for shape in bad_shapes: - assert_raises(ValueError, write_morph_data, 'test.curv', - values.reshape(shape)) - + with pytest.raises(ValueError): + write_morph_data('test.curv', values.reshape(shape)) + @freesurfer_test def test_annot(): @@ -208,7 +205,7 @@ def test_annot(): if labels_orig is not None: np.testing.assert_array_equal(labels_orig, labels_orig_2) np.testing.assert_array_equal(ctab, ctab2) - assert_equal(names, names2) + assert names == names2 def test_read_write_annot(): @@ -374,4 +371,4 @@ def test_write_annot_maxstruct(): # Check round-trip assert_array_equal(labels, rt_labels) assert_array_equal(rgba, rt_ctab[:, :4]) - assert_equal(names, [n.decode('ascii') for n in rt_names]) + assert names == [n.decode('ascii') for n in rt_names] From f99d92655b2f62cbb3637a0819f73ae88f264a78 Mon Sep 17 00:00:00 2001 From: orduek Date: Tue, 4 Feb 2020 17:28:50 -0500 Subject: [PATCH 168/223] Changed test_mghformat.py to pytest --- nibabel/freesurfer/tests/test_mghformat.py | 154 +++++++++++---------- 1 file changed, 79 insertions(+), 75 deletions(-) diff --git a/nibabel/freesurfer/tests/test_mghformat.py b/nibabel/freesurfer/tests/test_mghformat.py index 25a7254def..3d96aa60f6 100644 --- a/nibabel/freesurfer/tests/test_mghformat.py +++ b/nibabel/freesurfer/tests/test_mghformat.py @@ -26,12 +26,11 @@ import pytest -from numpy.testing import (assert_equal, assert_array_equal, - assert_array_almost_equal, assert_almost_equal, - assert_raises) -from ...testing import assert_not_equal +from numpy.testing import (assert_array_equal, + assert_array_almost_equal, assert_almost_equal) -from ...testing import data_path + +from ...testing_pytest import data_path from ...tests import test_spatialimages as tsi from ...tests.test_wrapstruct import _TestLabeledWrapStruct @@ -68,10 +67,10 @@ def test_read_mgh(): # header h = mgz.header - assert_equal(h['version'], 1) - assert_equal(h['type'], 3) - assert_equal(h['dof'], 0) - assert_equal(h['goodRASFlag'], 1) + assert h['version'] == 1 + assert h['type'] == 3 + assert h['dof'] == 0 + assert h['goodRASFlag'] == 1 assert_array_equal(h['dims'], [3, 4, 5, 2]) assert_almost_equal(h['tr'], 2.0) assert_almost_equal(h['flip_angle'], 0.0) @@ -102,10 +101,10 @@ def test_write_mgh(): # Delete loaded image to allow file deletion by windows del mgz # header - assert_equal(h['version'], 1) - assert_equal(h['type'], 3) - assert_equal(h['dof'], 0) - assert_equal(h['goodRASFlag'], 1) + assert h['version'] == 1 + assert h['type'] == 3 + assert h['dof'] == 0 + assert h['goodRASFlag'] == 1 assert_array_equal(h['dims'], [5, 4, 3, 2]) assert_almost_equal(h['tr'], 0.0) assert_almost_equal(h['flip_angle'], 0.0) @@ -132,10 +131,10 @@ def test_write_noaffine_mgh(): # Delete loaded image to allow file deletion by windows del mgz # header - assert_equal(h['version'], 1) - assert_equal(h['type'], 0) # uint8 for mgh - assert_equal(h['dof'], 0) - assert_equal(h['goodRASFlag'], 1) + assert h['version'] == 1 + assert h['type'] == 0 # uint8 for mgh + assert h['dof'] == 0 + assert h['goodRASFlag'] == 1 assert_array_equal(h['dims'], [7, 13, 3, 22]) assert_almost_equal(h['tr'], 0.0) assert_almost_equal(h['flip_angle'], 0.0) @@ -158,7 +157,7 @@ def test_set_zooms(): (1, 1, -1, 1), (1, 1, 1, -1), (1, 1, 1, 1, 5)): - with assert_raises(HeaderDataError): + with pytest.raises(HeaderDataError): h.set_zooms(zooms) # smoke test for tr=0 h.set_zooms((1, 1, 1, 0)) @@ -178,7 +177,8 @@ def bad_dtype_mgh(): def test_bad_dtype_mgh(): # Now test the above function - assert_raises(MGHError, bad_dtype_mgh) + with pytest.raises(MGHError): + bad_dtype_mgh() def test_filename_exts(): @@ -219,14 +219,14 @@ def test_header_updating(): assert_almost_equal(mgz.affine, exp_aff, 6) assert_almost_equal(hdr.get_affine(), exp_aff, 6) # Test that initial wonky header elements have not changed - assert_equal(hdr['delta'], 1) + assert hdr['delta'] == 1 assert_almost_equal(hdr['Mdc'].T, exp_aff[:3, :3]) # Save, reload, same thing img_fobj = io.BytesIO() mgz2 = _mgh_rt(mgz, img_fobj) hdr2 = mgz2.header assert_almost_equal(hdr2.get_affine(), exp_aff, 6) - assert_equal(hdr2['delta'], 1) + assert hdr2['delta'] == 1 # Change affine, change underlying header info exp_aff_d = exp_aff.copy() exp_aff_d[0, -1] = -14 @@ -259,17 +259,17 @@ def test_eq(): # Test headers compare properly hdr = MGHHeader() hdr2 = MGHHeader() - assert_equal(hdr, hdr2) + assert hdr == hdr2 hdr.set_data_shape((2, 3, 4)) assert(hdr != hdr2) hdr2.set_data_shape((2, 3, 4)) - assert_equal(hdr, hdr2) + assert hdr == hdr2 def test_header_slope_inter(): # Test placeholder slope / inter method hdr = MGHHeader() - assert_equal(hdr.get_slope_inter(), (None, None)) + assert hdr.get_slope_inter() == (None, None) def test_mgh_load_fileobj(): @@ -281,7 +281,7 @@ def test_mgh_load_fileobj(): # pass the filename to the array proxy, please feel free to change this # test. img = MGHImage.load(MGZ_FNAME) - assert_equal(img.dataobj.file_like, MGZ_FNAME) + assert img.dataobj.file_like == MGZ_FNAME # Check fileobj also passed into dataobj with ImageOpener(MGZ_FNAME) as fobj: contents = fobj.read() @@ -296,7 +296,7 @@ def test_mgh_affine_default(): hdr = MGHHeader() hdr['goodRASFlag'] = 0 hdr2 = MGHHeader(hdr.binaryblock) - assert_equal(hdr2['goodRASFlag'], 1) + assert hdr2['goodRASFlag'] == 1 assert_array_equal(hdr['Mdc'], hdr2['Mdc']) assert_array_equal(hdr['Pxyz_c'], hdr2['Pxyz_c']) @@ -311,33 +311,33 @@ def test_mgh_set_data_shape(): assert_array_equal(hdr.get_data_shape(), (5, 4, 3)) hdr.set_data_shape((5, 4, 3, 2)) assert_array_equal(hdr.get_data_shape(), (5, 4, 3, 2)) - with assert_raises(ValueError): + with pytest.raises(ValueError): hdr.set_data_shape((5, 4, 3, 2, 1)) def test_mghheader_default_structarr(): hdr = MGHHeader.default_structarr() - assert_equal(hdr['version'], 1) + assert hdr['version'] == 1 assert_array_equal(hdr['dims'], 1) - assert_equal(hdr['type'], 3) - assert_equal(hdr['dof'], 0) - assert_equal(hdr['goodRASFlag'], 1) + assert hdr['type'] == 3 + assert hdr['dof'] == 0 + assert hdr['goodRASFlag'] == 1 assert_array_equal(hdr['delta'], 1) assert_array_equal(hdr['Mdc'], [[-1, 0, 0], [0, 0, 1], [0, -1, 0]]) assert_array_equal(hdr['Pxyz_c'], 0) - assert_equal(hdr['tr'], 0) - assert_equal(hdr['flip_angle'], 0) - assert_equal(hdr['te'], 0) - assert_equal(hdr['ti'], 0) - assert_equal(hdr['fov'], 0) + assert hdr['tr'] ==0 + assert hdr['flip_angle'] == 0 + assert hdr['te'] == 0 + assert hdr['ti'] == 0 + assert hdr['fov'] == 0 for endianness in (None,) + BIG_CODES: hdr2 = MGHHeader.default_structarr(endianness=endianness) - assert_equal(hdr2, hdr) - assert_equal(hdr2.newbyteorder('>'), hdr) + assert hdr2 == hdr + assert hdr2.newbyteorder('>') == hdr for endianness in LITTLE_CODES: - with assert_raises(ValueError): + with pytest.raises(ValueError): MGHHeader.default_structarr(endianness=endianness) @@ -352,17 +352,17 @@ def test_deprecated_fields(): hdr['mrparams'] = [1, 2, 3, 4] assert_array_almost_equal(hdr['mrparams'], [1, 2, 3, 4]) - assert_equal(hdr['tr'], 1) - assert_equal(hdr['flip_angle'], 2) - assert_equal(hdr['te'], 3) - assert_equal(hdr['ti'], 4) - assert_equal(hdr['fov'], 0) + assert hdr['tr'] == 1 + assert hdr['flip_angle'] == 2 + assert hdr['te'] == 3 + assert hdr['ti'] == 4 + assert hdr['fov'] == 0 assert_array_almost_equal(hdr_data['mrparams'], [1, 2, 3, 4]) - assert_equal(hdr_data['tr'], 1) - assert_equal(hdr_data['flip_angle'], 2) - assert_equal(hdr_data['te'], 3) - assert_equal(hdr_data['ti'], 4) - assert_equal(hdr_data['fov'], 0) + assert hdr_data['tr'] == 1 + assert hdr_data['flip_angle'] == 2 + assert hdr_data['te'] == 3 + assert hdr_data['ti'] == 4 + assert hdr_data['fov'] == 0 hdr['tr'] = 5 hdr['flip_angle'] = 6 @@ -389,7 +389,7 @@ def check_dtypes(self, expected, actual): # Some images will want dtypes to be equal including endianness, # others may only require the same type # MGH requires the actual to be a big endian version of expected - assert_equal(expected.newbyteorder('>'), actual) + assert expected.newbyteorder('>') == actual class TestMGHHeader(_TestLabeledWrapStruct): @@ -406,9 +406,9 @@ def test_general_init(self): hdr = self.header_class() # binaryblock has length given by header data dtype binblock = hdr.binaryblock - assert_equal(len(binblock), hdr.structarr.dtype.itemsize) + assert len(binblock) == hdr.structarr.dtype.itemsize # Endianness will always be big, and cannot be set - assert_equal(hdr.endianness, '>') + assert hdr.endianness == '>' # You can also pass in a check flag, without data this has no # effect hdr = self.header_class(check=False) @@ -417,15 +417,15 @@ def test__eq__(self): # Test equal and not equal hdr1 = self.header_class() hdr2 = self.header_class() - assert_equal(hdr1, hdr2) + assert hdr1 == hdr2 self._set_something_into_hdr(hdr1) - assert_not_equal(hdr1, hdr2) + assert hdr1 != hdr2 self._set_something_into_hdr(hdr2) - assert_equal(hdr1, hdr2) + assert hdr1 == hdr2 # REMOVED as_byteswapped() test # Check comparing to funny thing says no - assert_not_equal(hdr1, None) - assert_not_equal(hdr1, 1) + assert hdr1 != None + assert hdr1 != 1 def test_to_from_fileobj(self): # Successful write using write_to @@ -434,56 +434,58 @@ def test_to_from_fileobj(self): hdr.write_to(str_io) str_io.seek(0) hdr2 = self.header_class.from_fileobj(str_io) - assert_equal(hdr2.endianness, '>') - assert_equal(hdr2.binaryblock, hdr.binaryblock) + assert hdr2.endianness == '>' + assert hdr2.binaryblock == hdr.binaryblock def test_endian_guess(self): # Check guesses of endian eh = self.header_class() - assert_equal(eh.endianness, '>') - assert_equal(self.header_class.guessed_endian(eh), '>') + assert eh.endianness == '>' + assert self.header_class.guessed_endian(eh) == '>' def test_bytes(self): # Test get of bytes hdr1 = self.header_class() bb = hdr1.binaryblock hdr2 = self.header_class(hdr1.binaryblock) - assert_equal(hdr1, hdr2) - assert_equal(hdr1.binaryblock, hdr2.binaryblock) + assert hdr1 == hdr2 + assert hdr1.binaryblock == hdr2.binaryblock # Do a set into the header, and try again. The specifics of 'setting # something' will depend on the nature of the bytes object self._set_something_into_hdr(hdr1) hdr2 = self.header_class(hdr1.binaryblock) - assert_equal(hdr1, hdr2) - assert_equal(hdr1.binaryblock, hdr2.binaryblock) + assert hdr1 == hdr2 + assert hdr1.binaryblock == hdr2.binaryblock # Short binaryblocks give errors (here set through init) # Long binaryblocks are truncated - assert_raises(WrapStructError, - self.header_class, - bb[:self.header_class._hdrdtype.itemsize - 1]) + with pytest.raises(WrapStructError): + self.header_class(bb[:self.header_class._hdrdtype.itemsize - 1]) + # Checking set to true by default, and prevents nonsense being # set into the header. bb_bad = self.get_bad_bb() if bb_bad is None: return with imageglobals.LoggingOutputSuppressor(): - assert_raises(HeaderDataError, self.header_class, bb_bad) + with pytest.raises(HeaderDataError): + self.header_class(bb_bad) + # now slips past without check _ = self.header_class(bb_bad, check=False) def test_as_byteswapped(self): # Check byte swapping hdr = self.header_class() - assert_equal(hdr.endianness, '>') + assert hdr.endianness == '>' # same code just returns a copy for endianness in BIG_CODES: hdr2 = hdr.as_byteswapped(endianness) assert(hdr2 is not hdr) - assert_equal(hdr2, hdr) + assert hdr2 == hdr # Different code raises error for endianness in (None,) + LITTLE_CODES: - with assert_raises(ValueError): + with pytest.raises(ValueError): hdr.as_byteswapped(endianness) # Note that contents is not rechecked on swap / copy class DC(self.header_class): @@ -491,7 +493,9 @@ def check_fix(self, *args, **kwargs): raise Exception # Assumes check=True default - assert_raises(Exception, DC, hdr.binaryblock) + with pytest.raises(Exception): + DC(hdr.binaryblock) + hdr = DC(hdr.binaryblock, check=False) hdr2 = hdr.as_byteswapped('>') @@ -500,8 +504,8 @@ def test_checks(self): hdr_t = self.header_class() # _dxer just returns the diagnostics as a string # Default hdr is OK - assert_equal(self._dxer(hdr_t), '') + assert self._dxer(hdr_t) == '' # Version should be 1 hdr = hdr_t.copy() hdr['version'] = 2 - assert_equal(self._dxer(hdr), 'Unknown MGH format version') + assert self._dxer(hdr) == 'Unknown MGH format version' From 6e1e1c1a81505d671de259b4da58937ef73d6824 Mon Sep 17 00:00:00 2001 From: orduek Date: Tue, 4 Feb 2020 17:55:23 -0500 Subject: [PATCH 169/223] small fixes --- nibabel/freesurfer/tests/test_io.py | 34 +++++++++++----------- nibabel/freesurfer/tests/test_mghformat.py | 3 +- 2 files changed, 18 insertions(+), 19 deletions(-) diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index cde2edeb5f..77a8bc12a0 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -51,18 +51,18 @@ def test_geometry(): """Test IO of .surf""" surf_path = pjoin(data_path, "surf", "%s.%s" % ("lh", "inflated")) coords, faces = read_geometry(surf_path) - assert 0==faces.min() - assert coords.shape[0]== faces.max() + 1 + assert 0 == faces.min() + assert coords.shape[0] == faces.max() + 1 surf_path = pjoin(data_path, "surf", "%s.%s" % ("lh", "sphere")) coords, faces, volume_info, create_stamp = read_geometry( surf_path, read_metadata=True, read_stamp=True) assert 0 == faces.min() - assert coords.shape[0] == faces.max() + 1 + assert coords.shape[0] == (faces.max() + 1) assert 9 == len(volume_info) assert [2, 0, 20] == volume_info['head'] - assert 'created by greve on Thu Jun 8 19:17:51 2006' == create_stamp + assert ['created by greve on Thu Jun 8 19:17:51 2006'] == create_stamp # Test equivalence of freesurfer- and nibabel-generated triangular files # with respect to read_geometry() @@ -121,7 +121,7 @@ def test_quad_geometry(): 'bert', 'surf', 'lh.inflated.nofix') coords, faces = read_geometry(new_quad) assert 0 == faces.min() - assert coords.shape[0] == faces.max() + 1 + assert coords.shape[0] == (faces.max() + 1) with InTemporaryDirectory(): new_path = 'test' write_geometry(new_path, coords, faces) @@ -135,8 +135,8 @@ def test_morph_data(): """Test IO of morphometry data file (eg. curvature).""" curv_path = pjoin(data_path, "surf", "%s.%s" % ("lh", "curv")) curv = read_morph_data(curv_path) - assert(-1.0 < curv.min() < 0) - assert(0 < curv.max() < 1.0) + assert -1.0 < curv.min() < 0 + assert 0 < curv.max() < 1.0 with InTemporaryDirectory(): new_path = 'test' write_morph_data(new_path, curv) @@ -175,8 +175,8 @@ def test_annot(): hash_ = _hash_file_content(annot_path) labels, ctab, names = read_annot(annot_path) - assert(labels.shape == (163842, )) - assert(ctab.shape == (len(names), 5)) + assert labels.shape == (163842, ) + assert ctab.shape == (len(names), 5) labels_orig = None if a == 'aparc': @@ -184,9 +184,9 @@ def test_annot(): np.testing.assert_array_equal(labels == -1, labels_orig == 0) # Handle different version of fsaverage if hash_ == 'bf0b488994657435cdddac5f107d21e8': - assert(np.sum(labels_orig == 0) == 13887) + assert np.sum(labels_orig == 0) == 13887 elif hash_ == 'd4f5b7cbc2ed363ac6fcf89e19353504': - assert(np.sum(labels_orig == 1639705) == 13327) + assert np.sum(labels_orig == 1639705) == 13327 else: raise RuntimeError("Unknown freesurfer file. Please report " "the problem to the maintainer of nibabel.") @@ -270,7 +270,7 @@ def test_write_annot_fill_ctab(): print(labels) with clear_and_catch_warnings() as w: write_annot(annot_path, labels, rgbal, names, fill_ctab=False) - assert( + assert ( any('Annotation values in {} will be incorrect'.format( annot_path) == str(ww.message) for ww in w)) labels2, rgbal2, names2 = read_annot(annot_path, orig_ids=True) @@ -346,13 +346,13 @@ def test_label(): label_path = pjoin(data_path, "label", "lh.cortex.label") label = read_label(label_path) # XXX : test more - assert(label.min() >= 0) - assert(label.max() <= 163841) - assert(label.shape[0] <= 163842) + assert label.min() >= 0 + assert label.max() <= 163841 + assert label.shape[0] <= 163842 labels, scalars = read_label(label_path, True) - assert(np.all(labels == label)) - assert(len(labels) == len(scalars)) + assert (np.all(labels == label)) + assert len(labels) == len(scalars) def test_write_annot_maxstruct(): diff --git a/nibabel/freesurfer/tests/test_mghformat.py b/nibabel/freesurfer/tests/test_mghformat.py index 3d96aa60f6..37b2faa2b4 100644 --- a/nibabel/freesurfer/tests/test_mghformat.py +++ b/nibabel/freesurfer/tests/test_mghformat.py @@ -26,8 +26,7 @@ import pytest -from numpy.testing import (assert_array_equal, - assert_array_almost_equal, assert_almost_equal) +from numpy.testing import (assert_array_equal, assert_array_almost_equal, assert_almost_equal) from ...testing_pytest import data_path From d27b124a97a91534d0068024a577200d73c7aaea Mon Sep 17 00:00:00 2001 From: orduek Date: Wed, 5 Feb 2020 16:49:25 -0500 Subject: [PATCH 170/223] fixes to assert numpy --- nibabel/freesurfer/tests/test_io.py | 16 +++++++++------- nibabel/freesurfer/tests/test_mghformat.py | 6 +++--- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index 77a8bc12a0..1ca5027bf9 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -61,8 +61,9 @@ def test_geometry(): assert 0 == faces.min() assert coords.shape[0] == (faces.max() + 1) assert 9 == len(volume_info) - assert [2, 0, 20] == volume_info['head'] - assert ['created by greve on Thu Jun 8 19:17:51 2006'] == create_stamp + # assert np.array_equal([2, 0, 20],volume_info['head']) + np.testing.assert_array_equal([2, 0, 20],volume_info['head']) + assert create_stamp == ['created by greve on Thu Jun 8 19:17:51 2006'] # this creates assertion error - should we just remove it? # Test equivalence of freesurfer- and nibabel-generated triangular files # with respect to read_geometry() @@ -79,7 +80,8 @@ def test_geometry(): for key in ('xras', 'yras', 'zras', 'cras'): assert_allclose(volume_info2[key], volume_info[key], rtol=1e-7, atol=1e-30) - assert volume_info2['cras'] == volume_info['cras'] + #assert.array_equal(volume_info2['cras'], volume_info['cras']) + np.testing.assert_array_equal(volume_info2['cras'], volume_info['cras']) with open(surf_path, 'rb') as fobj: np.fromfile(fobj, ">u1", 3) read_create_stamp = fobj.readline().decode().rstrip('\n') @@ -126,8 +128,8 @@ def test_quad_geometry(): new_path = 'test' write_geometry(new_path, coords, faces) coords2, faces2 = read_geometry(new_path) - assert coords == coords2 - assert faces == faces2 + assert np.array_equal(coords,coords2) + assert np.array_equal(faces, faces2) @freesurfer_test @@ -141,7 +143,7 @@ def test_morph_data(): new_path = 'test' write_morph_data(new_path, curv) curv2 = read_morph_data(new_path) - assert curv2 == curv + assert np.array_equal (curv2, curv) def test_write_morph_data(): @@ -154,7 +156,7 @@ def test_write_morph_data(): for shape in okay_shapes: write_morph_data('test.curv', values.reshape(shape)) # Check ordering is preserved, regardless of shape - assert values == read_morph_data('test.curv') + assert np.array_equal(read_morph_data('test.curv') ,values) with pytest.raises(ValueError): write_morph_data('test.curv', np.zeros(shape), big_num) # Windows 32-bit overflows Python int diff --git a/nibabel/freesurfer/tests/test_mghformat.py b/nibabel/freesurfer/tests/test_mghformat.py index 37b2faa2b4..41bffbf6ac 100644 --- a/nibabel/freesurfer/tests/test_mghformat.py +++ b/nibabel/freesurfer/tests/test_mghformat.py @@ -26,7 +26,7 @@ import pytest -from numpy.testing import (assert_array_equal, assert_array_almost_equal, assert_almost_equal) +from numpy.testing import assert_array_equal, assert_array_almost_equal, assert_almost_equal from ...testing_pytest import data_path @@ -218,14 +218,14 @@ def test_header_updating(): assert_almost_equal(mgz.affine, exp_aff, 6) assert_almost_equal(hdr.get_affine(), exp_aff, 6) # Test that initial wonky header elements have not changed - assert hdr['delta'] == 1 + assert_array_equal(hdr['delta'], 1) assert_almost_equal(hdr['Mdc'].T, exp_aff[:3, :3]) # Save, reload, same thing img_fobj = io.BytesIO() mgz2 = _mgh_rt(mgz, img_fobj) hdr2 = mgz2.header assert_almost_equal(hdr2.get_affine(), exp_aff, 6) - assert hdr2['delta'] == 1 + assert_array_equal(hdr2['delta'],1) # Change affine, change underlying header info exp_aff_d = exp_aff.copy() exp_aff_d[0, -1] = -14 From 6890a62840db3c0e04373b839b3862982e19238b Mon Sep 17 00:00:00 2001 From: Or Duek Date: Wed, 5 Feb 2020 17:18:29 -0500 Subject: [PATCH 171/223] Update nibabel/freesurfer/tests/test_io.py Co-Authored-By: Chris Markiewicz --- nibabel/freesurfer/tests/test_io.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index 1ca5027bf9..cbd73eb14e 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -36,7 +36,8 @@ data_path = pjoin(nib_data, 'nitest-freesurfer', DATA_SDIR) have_freesurfer = isdir(data_path) -freesurfer_test = pytest.mark.skipif(not have_freesurfer, reason='cannot find freesurfer {0} directory'.format(DATA_SDIR)) +freesurfer_test = pytest.mark.skipif(not have_freesurfer, + reason='cannot find freesurfer {0} directory'.format(DATA_SDIR)) def _hash_file_content(fname): hasher = hashlib.md5() From b7e8abb7d6bbdd54251f8b705d953407a1863b89 Mon Sep 17 00:00:00 2001 From: Or Duek Date: Wed, 5 Feb 2020 17:18:40 -0500 Subject: [PATCH 172/223] Update nibabel/freesurfer/tests/test_io.py Co-Authored-By: Chris Markiewicz --- nibabel/freesurfer/tests/test_io.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index cbd73eb14e..b22ceb6e23 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -60,7 +60,7 @@ def test_geometry(): surf_path, read_metadata=True, read_stamp=True) assert 0 == faces.min() - assert coords.shape[0] == (faces.max() + 1) + assert coords.shape[0] == faces.max() + 1 assert 9 == len(volume_info) # assert np.array_equal([2, 0, 20],volume_info['head']) np.testing.assert_array_equal([2, 0, 20],volume_info['head']) From 5dbe4083cf470eef322a42a4d1835a535971d1b8 Mon Sep 17 00:00:00 2001 From: Or Duek Date: Wed, 5 Feb 2020 17:18:55 -0500 Subject: [PATCH 173/223] Update nibabel/freesurfer/tests/test_io.py Co-Authored-By: Chris Markiewicz --- nibabel/freesurfer/tests/test_io.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index b22ceb6e23..144eac6a3d 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -62,7 +62,7 @@ def test_geometry(): assert 0 == faces.min() assert coords.shape[0] == faces.max() + 1 assert 9 == len(volume_info) - # assert np.array_equal([2, 0, 20],volume_info['head']) + assert np.array_equal([2, 0, 20], volume_info['head']) np.testing.assert_array_equal([2, 0, 20],volume_info['head']) assert create_stamp == ['created by greve on Thu Jun 8 19:17:51 2006'] # this creates assertion error - should we just remove it? From 24d96e4d8c12fc0e4c39308e179a6cbfd043de7e Mon Sep 17 00:00:00 2001 From: Or Duek Date: Wed, 5 Feb 2020 17:19:09 -0500 Subject: [PATCH 174/223] Update nibabel/freesurfer/tests/test_io.py Co-Authored-By: Chris Markiewicz --- nibabel/freesurfer/tests/test_io.py | 1 - 1 file changed, 1 deletion(-) diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index 144eac6a3d..c01d079258 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -63,7 +63,6 @@ def test_geometry(): assert coords.shape[0] == faces.max() + 1 assert 9 == len(volume_info) assert np.array_equal([2, 0, 20], volume_info['head']) - np.testing.assert_array_equal([2, 0, 20],volume_info['head']) assert create_stamp == ['created by greve on Thu Jun 8 19:17:51 2006'] # this creates assertion error - should we just remove it? # Test equivalence of freesurfer- and nibabel-generated triangular files From e8965c1a1e33d070acf2b7bcd77d127b2a3219bb Mon Sep 17 00:00:00 2001 From: Or Duek Date: Wed, 5 Feb 2020 17:19:31 -0500 Subject: [PATCH 175/223] Update nibabel/freesurfer/tests/test_io.py Co-Authored-By: Chris Markiewicz --- nibabel/freesurfer/tests/test_io.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index c01d079258..27d5d352a5 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -80,7 +80,7 @@ def test_geometry(): for key in ('xras', 'yras', 'zras', 'cras'): assert_allclose(volume_info2[key], volume_info[key], rtol=1e-7, atol=1e-30) - #assert.array_equal(volume_info2['cras'], volume_info['cras']) + assert np.array_equal(volume_info2['cras'], volume_info['cras']) np.testing.assert_array_equal(volume_info2['cras'], volume_info['cras']) with open(surf_path, 'rb') as fobj: np.fromfile(fobj, ">u1", 3) From bbc36d77b7fd6c917a53f32660b481bfc8a18d54 Mon Sep 17 00:00:00 2001 From: Or Duek Date: Wed, 5 Feb 2020 17:19:40 -0500 Subject: [PATCH 176/223] Update nibabel/freesurfer/tests/test_io.py Co-Authored-By: Chris Markiewicz --- nibabel/freesurfer/tests/test_io.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index 27d5d352a5..9ebc1af138 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -156,7 +156,7 @@ def test_write_morph_data(): for shape in okay_shapes: write_morph_data('test.curv', values.reshape(shape)) # Check ordering is preserved, regardless of shape - assert np.array_equal(read_morph_data('test.curv') ,values) + assert np.array_equal(read_morph_data('test.curv'), values) with pytest.raises(ValueError): write_morph_data('test.curv', np.zeros(shape), big_num) # Windows 32-bit overflows Python int From e626a38e55a8771dafcaab65a0952c8d272b8128 Mon Sep 17 00:00:00 2001 From: Or Duek Date: Wed, 5 Feb 2020 17:19:48 -0500 Subject: [PATCH 177/223] Update nibabel/freesurfer/tests/test_io.py Co-Authored-By: Chris Markiewicz --- nibabel/freesurfer/tests/test_io.py | 1 - 1 file changed, 1 deletion(-) diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index 9ebc1af138..50805c324b 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -81,7 +81,6 @@ def test_geometry(): assert_allclose(volume_info2[key], volume_info[key], rtol=1e-7, atol=1e-30) assert np.array_equal(volume_info2['cras'], volume_info['cras']) - np.testing.assert_array_equal(volume_info2['cras'], volume_info['cras']) with open(surf_path, 'rb') as fobj: np.fromfile(fobj, ">u1", 3) read_create_stamp = fobj.readline().decode().rstrip('\n') From 2fb977b1605f5a4c4394f3b1b694e0a5e8f66de5 Mon Sep 17 00:00:00 2001 From: Or Duek Date: Wed, 5 Feb 2020 17:19:57 -0500 Subject: [PATCH 178/223] Update nibabel/freesurfer/tests/test_io.py Co-Authored-By: Chris Markiewicz --- nibabel/freesurfer/tests/test_io.py | 1 - 1 file changed, 1 deletion(-) diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index 50805c324b..b1080a87b0 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -165,7 +165,6 @@ def test_write_morph_data(): for shape in bad_shapes: with pytest.raises(ValueError): write_morph_data('test.curv', values.reshape(shape)) - @freesurfer_test def test_annot(): From 30a4639f197cebc53681cbca73b78ff98c03a609 Mon Sep 17 00:00:00 2001 From: orduek Date: Wed, 5 Feb 2020 17:23:23 -0500 Subject: [PATCH 179/223] added test_io to Ignore list in azure and travis --- .azure-pipelines/windows.yml | 3 ++- .travis.yml | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index 89b47b8345..c7411a77c7 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -99,7 +99,8 @@ jobs: -I test_round_trip ^ -I test_rstutils ^ -I test_scaling ^ - -I test_wrapstruct + -I test_wrapstruct ^ + -I test_io displayName: 'Nose tests' condition: and(succeeded(), eq(variables['CHECK_TYPE'], 'nosetests')) - script: | diff --git a/.travis.yml b/.travis.yml index b869d33947..483efe29ec 100644 --- a/.travis.yml +++ b/.travis.yml @@ -186,7 +186,8 @@ script: -I test_round_trip \ -I test_rstutils \ -I test_scaling \ - -I test_wrapstruct + -I test_wrapstruct \ + -I test_io elif [ "${CHECK_TYPE}" == "test" ]; then # Change into an innocuous directory and find tests from installation mkdir for_testing From 165da32f980af96508f5b590a8db4f7796150671 Mon Sep 17 00:00:00 2001 From: Or Duek Date: Wed, 5 Feb 2020 17:32:09 -0500 Subject: [PATCH 180/223] Update nibabel/freesurfer/tests/test_mghformat.py Co-Authored-By: Chris Markiewicz --- nibabel/freesurfer/tests/test_mghformat.py | 1 - 1 file changed, 1 deletion(-) diff --git a/nibabel/freesurfer/tests/test_mghformat.py b/nibabel/freesurfer/tests/test_mghformat.py index 41bffbf6ac..03f03b2c18 100644 --- a/nibabel/freesurfer/tests/test_mghformat.py +++ b/nibabel/freesurfer/tests/test_mghformat.py @@ -28,7 +28,6 @@ from numpy.testing import assert_array_equal, assert_array_almost_equal, assert_almost_equal - from ...testing_pytest import data_path from ...tests import test_spatialimages as tsi From 54fc107813d82abe71d763ff4a0d35f1f105e174 Mon Sep 17 00:00:00 2001 From: Or Duek Date: Wed, 5 Feb 2020 17:32:20 -0500 Subject: [PATCH 181/223] Update nibabel/freesurfer/tests/test_mghformat.py Co-Authored-By: Chris Markiewicz --- nibabel/freesurfer/tests/test_mghformat.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/freesurfer/tests/test_mghformat.py b/nibabel/freesurfer/tests/test_mghformat.py index 03f03b2c18..19c33d30bc 100644 --- a/nibabel/freesurfer/tests/test_mghformat.py +++ b/nibabel/freesurfer/tests/test_mghformat.py @@ -323,7 +323,7 @@ def test_mghheader_default_structarr(): assert_array_equal(hdr['delta'], 1) assert_array_equal(hdr['Mdc'], [[-1, 0, 0], [0, 0, 1], [0, -1, 0]]) assert_array_equal(hdr['Pxyz_c'], 0) - assert hdr['tr'] ==0 + assert hdr['tr'] == 0 assert hdr['flip_angle'] == 0 assert hdr['te'] == 0 assert hdr['ti'] == 0 From 27ef4009a5e0c7ec2e5c1b72109315af5ee559ae Mon Sep 17 00:00:00 2001 From: orduek Date: Wed, 5 Feb 2020 17:45:26 -0500 Subject: [PATCH 182/223] fixed style and convetion in test_io.py --- nibabel/freesurfer/tests/test_io.py | 57 ++++++++++------------------- 1 file changed, 19 insertions(+), 38 deletions(-) diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index b6b1e12fb1..b457a6c00d 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -36,12 +36,8 @@ data_path = pjoin(nib_data, 'nitest-freesurfer', DATA_SDIR) have_freesurfer = isdir(data_path) -<<<<<<< HEAD -freesurfer_test = pytest.mark.skipif(not have_freesurfer, reason='cannot find freesurfer {0} directory'.format(DATA_SDIR)) -======= freesurfer_test = pytest.mark.skipif(not have_freesurfer, reason='cannot find freesurfer {0} directory'.format(DATA_SDIR)) ->>>>>>> 2fb977b1605f5a4c4394f3b1b694e0a5e8f66de5 def _hash_file_content(fname): hasher = hashlib.md5() @@ -64,17 +60,10 @@ def test_geometry(): surf_path, read_metadata=True, read_stamp=True) assert 0 == faces.min() -<<<<<<< HEAD - assert coords.shape[0] == (faces.max() + 1) - assert 9 == len(volume_info) - # assert np.array_equal([2, 0, 20],volume_info['head']) - np.testing.assert_array_equal([2, 0, 20],volume_info['head']) -======= assert coords.shape[0] == faces.max() + 1 assert 9 == len(volume_info) assert np.array_equal([2, 0, 20], volume_info['head']) ->>>>>>> 2fb977b1605f5a4c4394f3b1b694e0a5e8f66de5 - assert create_stamp == ['created by greve on Thu Jun 8 19:17:51 2006'] # this creates assertion error - should we just remove it? + assert create_stamp == 'created by greve on Thu Jun 8 19:17:51 2006' # Test equivalence of freesurfer- and nibabel-generated triangular files # with respect to read_geometry() @@ -91,12 +80,8 @@ def test_geometry(): for key in ('xras', 'yras', 'zras', 'cras'): assert_allclose(volume_info2[key], volume_info[key], rtol=1e-7, atol=1e-30) -<<<<<<< HEAD - #assert.array_equal(volume_info2['cras'], volume_info['cras']) - np.testing.assert_array_equal(volume_info2['cras'], volume_info['cras']) -======= + assert np.array_equal(volume_info2['cras'], volume_info['cras']) ->>>>>>> 2fb977b1605f5a4c4394f3b1b694e0a5e8f66de5 with open(surf_path, 'rb') as fobj: np.fromfile(fobj, ">u1", 3) read_create_stamp = fobj.readline().decode().rstrip('\n') @@ -106,28 +91,31 @@ def test_geometry(): with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) read_geometry(surf_path, read_metadata=True) - assert(any('volume information contained' in str(ww.message) + + assert( + any('volume information contained' in str(ww.message) for ww in w)) - assert(any('extension code' in str(ww.message) for ww in w)) + assert( + any('extension code' in str(ww.message) for ww in w)) volume_info['head'] = [1, 2] with clear_and_catch_warnings() as w: write_geometry(surf_path, coords, faces, create_stamp, volume_info) - assert(any('Unknown extension' in str(ww.message) for ww in w)) + assert( + any('Unknown extension' in str(ww.message) for ww in w)) volume_info['a'] = 0 with pytest.raises(ValueError): write_geometry(surf_path, coords, faces, create_stamp, volume_info) - assert create_stamp == read_create_stamp - np.testing.assert_array_equal(coords, coords2) - np.testing.assert_array_equal(faces, faces2) + assert np.array_equal(coords, coords2) + assert np.array_equal(faces, faces2) # Validate byte ordering coords_swapped = coords.byteswap().newbyteorder() faces_swapped = faces.byteswap().newbyteorder() - np.testing.assert_array_equal(coords_swapped, coords) - np.testing.assert_array_equal(faces_swapped, faces) + assert np.array_equal(coords_swapped, coords) + assert np.array_equal(faces_swapped, faces) @freesurfer_test @@ -171,11 +159,8 @@ def test_write_morph_data(): for shape in okay_shapes: write_morph_data('test.curv', values.reshape(shape)) # Check ordering is preserved, regardless of shape -<<<<<<< HEAD - assert np.array_equal(read_morph_data('test.curv') ,values) -======= assert np.array_equal(read_morph_data('test.curv'), values) ->>>>>>> 2fb977b1605f5a4c4394f3b1b694e0a5e8f66de5 + with pytest.raises(ValueError): write_morph_data('test.curv', np.zeros(shape), big_num) # Windows 32-bit overflows Python int @@ -185,10 +170,6 @@ def test_write_morph_data(): for shape in bad_shapes: with pytest.raises(ValueError): write_morph_data('test.curv', values.reshape(shape)) -<<<<<<< HEAD - -======= ->>>>>>> 2fb977b1605f5a4c4394f3b1b694e0a5e8f66de5 @freesurfer_test def test_annot(): @@ -225,10 +206,10 @@ def test_annot(): if labels_orig is not None: labels_orig_2, _, _ = read_annot(annot_path, orig_ids=True) - np.testing.assert_array_equal(labels, labels2) + assert np.array_equal(labels, labels2) if labels_orig is not None: - np.testing.assert_array_equal(labels_orig, labels_orig_2) - np.testing.assert_array_equal(ctab, ctab2) + assert np.array_equal(labels_orig, labels_orig_2) + assert np.array_equal(ctab, ctab2) assert names == names2 @@ -393,6 +374,6 @@ def test_write_annot_maxstruct(): # Validate the file can be read rt_labels, rt_ctab, rt_names = read_annot(annot_path) # Check round-trip - assert_array_equal(labels, rt_labels) - assert_array_equal(rgba, rt_ctab[:, :4]) + assert np.array_equal(labels, rt_labels) + assert np.array_equal(rgba, rt_ctab[:, :4]) assert names == [n.decode('ascii') for n in rt_names] From fdd26a23810f15b05a3a8c889cc6de7c05a73826 Mon Sep 17 00:00:00 2001 From: orduek Date: Wed, 5 Feb 2020 17:59:50 -0500 Subject: [PATCH 183/223] added more changes to style --- nibabel/freesurfer/tests/test_mghformat.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/nibabel/freesurfer/tests/test_mghformat.py b/nibabel/freesurfer/tests/test_mghformat.py index 19c33d30bc..d70c4e9742 100644 --- a/nibabel/freesurfer/tests/test_mghformat.py +++ b/nibabel/freesurfer/tests/test_mghformat.py @@ -103,7 +103,7 @@ def test_write_mgh(): assert h['type'] == 3 assert h['dof'] == 0 assert h['goodRASFlag'] == 1 - assert_array_equal(h['dims'], [5, 4, 3, 2]) + assert np.array_equal(h['dims'], [5, 4, 3, 2]) assert_almost_equal(h['tr'], 0.0) assert_almost_equal(h['flip_angle'], 0.0) assert_almost_equal(h['te'], 0.0) @@ -133,7 +133,7 @@ def test_write_noaffine_mgh(): assert h['type'] == 0 # uint8 for mgh assert h['dof'] == 0 assert h['goodRASFlag'] == 1 - assert_array_equal(h['dims'], [7, 13, 3, 22]) + assert np.array_equal(h['dims'], [7, 13, 3, 22]) assert_almost_equal(h['tr'], 0.0) assert_almost_equal(h['flip_angle'], 0.0) assert_almost_equal(h['te'], 0.0) @@ -217,7 +217,7 @@ def test_header_updating(): assert_almost_equal(mgz.affine, exp_aff, 6) assert_almost_equal(hdr.get_affine(), exp_aff, 6) # Test that initial wonky header elements have not changed - assert_array_equal(hdr['delta'], 1) + assert np.array_equal(hdr['delta'], 1) assert_almost_equal(hdr['Mdc'].T, exp_aff[:3, :3]) # Save, reload, same thing img_fobj = io.BytesIO() @@ -458,7 +458,7 @@ def test_bytes(self): # Long binaryblocks are truncated with pytest.raises(WrapStructError): self.header_class(bb[:self.header_class._hdrdtype.itemsize - 1]) - + # Checking set to true by default, and prevents nonsense being # set into the header. bb_bad = self.get_bad_bb() @@ -467,7 +467,7 @@ def test_bytes(self): with imageglobals.LoggingOutputSuppressor(): with pytest.raises(HeaderDataError): self.header_class(bb_bad) - + # now slips past without check _ = self.header_class(bb_bad, check=False) @@ -493,7 +493,7 @@ def check_fix(self, *args, **kwargs): # Assumes check=True default with pytest.raises(Exception): DC(hdr.binaryblock) - + hdr = DC(hdr.binaryblock, check=False) hdr2 = hdr.as_byteswapped('>') From f79de1dc2a371053541157ab12e89cd6a09cb3a4 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Wed, 5 Feb 2020 23:51:44 -0500 Subject: [PATCH 184/223] ignoring tests that use needs_nibabel_data --- .azure-pipelines/windows.yml | 3 +++ .travis.yml | 3 +++ 2 files changed, 6 insertions(+) diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index f63b5f48c3..3eb6cececb 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -49,10 +49,12 @@ jobs: -I test_batteryrunners ^ -I test_brikhead ^ -I test_casting ^ + -I test_cifti2io_axes ^ -I test_cifti2io_header ^ -I test_data ^ -I test_deprecated ^ -I test_deprecator ^ + -I test_dicomwrappers ^ -I test_dft ^ -I test_ecat ^ -I test_ecat_data ^ @@ -75,6 +77,7 @@ jobs: -I test_image_types ^ -I test_imageclasses ^ -I test_imageglobals ^ + -I test_io ^ -I test_keywordonly ^ -I test_loadsave ^ -I test_minc1 ^ diff --git a/.travis.yml b/.travis.yml index e8b20252f0..76d2535e68 100644 --- a/.travis.yml +++ b/.travis.yml @@ -136,10 +136,12 @@ script: -I test_batteryrunners \ -I test_brikhead \ -I test_casting \ + -I test_cifti2io_axes \ -I test_cifti2io_header \ -I test_data \ -I test_deprecated \ -I test_deprecator \ + -I test_dicomwrappers \ -I test_dft \ -I test_ecat \ -I test_ecat_data \ @@ -162,6 +164,7 @@ script: -I test_image_types \ -I test_imageclasses \ -I test_imageglobals \ + -I test_io \ -I test_keywordonly \ -I test_loadsave \ -I test_minc1 \ From 2539bcd0dd1227497d0ecf6443dc56e43c3ae938 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Wed, 5 Feb 2020 23:54:54 -0500 Subject: [PATCH 185/223] some cleaning after using nose2pytest --- nibabel/tests/scriptrunner.py | 2 +- nibabel/tests/test_analyze.py | 2 +- nibabel/tests/test_arraywriters.py | 4 ++-- nibabel/tests/test_casting.py | 4 ++-- nibabel/tests/test_deprecator.py | 18 +++++++++--------- nibabel/tests/test_ecat.py | 2 +- nibabel/tests/test_environment.py | 2 +- nibabel/tests/test_files_interface.py | 8 ++++---- nibabel/tests/test_fileslice.py | 4 ++-- nibabel/tests/test_image_load_save.py | 4 ++-- nibabel/tests/test_nifti1.py | 14 +++++++------- nibabel/tests/test_openers.py | 4 ++-- nibabel/tests/test_optpkg.py | 4 ++-- nibabel/tests/test_parrec.py | 22 +++++++++++----------- nibabel/tests/test_scripts.py | 3 +-- nibabel/tests/test_spatialimages.py | 18 +++++++++--------- nibabel/tests/test_spm99analyze.py | 4 +--- nibabel/tests/test_trackvis.py | 18 ++++++++---------- nibabel/tests/test_wrapstruct.py | 2 +- 19 files changed, 67 insertions(+), 72 deletions(-) diff --git a/nibabel/tests/scriptrunner.py b/nibabel/tests/scriptrunner.py index 33b5e3dcef..0027cc36b2 100644 --- a/nibabel/tests/scriptrunner.py +++ b/nibabel/tests/scriptrunner.py @@ -135,7 +135,7 @@ def run_command(self, cmd, check_code=True): env['PYTHONPATH'] = self.local_module_dir + pathsep + pypath proc = Popen(cmd, stdout=PIPE, stderr=PIPE, env=env) stdout, stderr = proc.communicate() - if proc.poll() == None: + if proc.poll() is None: proc.terminate() if check_code and proc.returncode != 0: raise RuntimeError( diff --git a/nibabel/tests/test_analyze.py b/nibabel/tests/test_analyze.py index 14bfb3b5e7..2b2e78dd23 100644 --- a/nibabel/tests/test_analyze.py +++ b/nibabel/tests/test_analyze.py @@ -512,7 +512,7 @@ def test_from_header(self): for check in (True, False): copy = klass.from_header(hdr, check=check) assert hdr == copy - assert not hdr is copy + assert hdr is not copy class C(object): diff --git a/nibabel/tests/test_arraywriters.py b/nibabel/tests/test_arraywriters.py index 1a1c4eb156..14e9025c21 100644 --- a/nibabel/tests/test_arraywriters.py +++ b/nibabel/tests/test_arraywriters.py @@ -640,7 +640,7 @@ def test_writer_maker(): assert (aw.slope, aw.inter) == (1, 0) aw.calc_scale() slope, inter = aw.slope, aw.inter - assert not (slope, inter) == (1, 0) + assert (slope, inter) != (1, 0) # Should run by default aw = make_array_writer(arr, np.int16) assert (aw.slope, aw.inter) == (slope, inter) @@ -704,7 +704,7 @@ def test_int_int_slope(): aw = SlopeArrayWriter(arr, out_dt) except ScalingError: continue - assert not aw.slope == 0 + assert aw.slope != 0 arr_back_sc = round_trip(aw) # integer allclose adiff = int_abs(arr - arr_back_sc) diff --git a/nibabel/tests/test_casting.py b/nibabel/tests/test_casting.py index 3fe74dfb8b..9006ce321c 100644 --- a/nibabel/tests/test_casting.py +++ b/nibabel/tests/test_casting.py @@ -120,7 +120,7 @@ def test_casting(): # Confirm input array is not modified nans = np.isnan(farr) assert_array_equal(nans, np.isnan(farr_orig)) - assert_array_equal(farr[nans == False], farr_orig[nans == False]) + assert_array_equal(farr[nans is False], farr_orig[nans is False]) # Test scalars work and return scalars assert_array_equal(float_to_int(np.float32(0), np.int16), [0]) # Test scalar nan OK @@ -155,7 +155,7 @@ def test_floor_log2(): assert floor_log2(0.75) == -1 assert floor_log2(0.25) == -2 assert floor_log2(0.24) == -3 - assert floor_log2(0) == None + assert floor_log2(0) is None def test_able_int_type(): diff --git a/nibabel/tests/test_deprecator.py b/nibabel/tests/test_deprecator.py index eb9de3799d..63d2b32a70 100644 --- a/nibabel/tests/test_deprecator.py +++ b/nibabel/tests/test_deprecator.py @@ -70,18 +70,18 @@ def test_dep_func(self): dec = self.dep_func func = dec('foo')(func_no_doc) with pytest.deprecated_call(): - assert func() == None + assert func() is None assert func.__doc__ == 'foo\n' func = dec('foo')(func_doc) with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: warnings.simplefilter('always') - assert func(1) == None + assert func(1) is None assert len(w) == 1 assert func.__doc__ == 'A docstring\n\nfoo\n' func = dec('foo')(func_doc_long) with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: warnings.simplefilter('always') - assert func(1, 2) == None + assert func(1, 2) is None assert len(w) == 1 assert func.__doc__ == 'A docstring\n \n foo\n \n Some text\n' @@ -90,12 +90,12 @@ def test_dep_func(self): assert func.__doc__ == 'foo\n\n* deprecated from version: 1.1\n' with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: warnings.simplefilter('always') - assert func() == None + assert func() is None assert len(w) == 1 func = dec('foo', until='99.4')(func_no_doc) with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: warnings.simplefilter('always') - assert func() == None + assert func() is None assert len(w) == 1 assert (func.__doc__ == 'foo\n\n* Will raise {} as of version: 99.4\n' @@ -127,13 +127,13 @@ def test_dep_func(self): func = dec('foo', warn_class=UserWarning)(func_no_doc) with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: warnings.simplefilter('always') - assert func() == None + assert func() is None assert len(w) == 1 assert w[0].category is UserWarning func = dec('foo', error_class=CustomError)(func_no_doc) with pytest.deprecated_call(): - assert func() == None + assert func() is None func = dec('foo', until='1.8', error_class=CustomError)(func_no_doc) with pytest.raises(CustomError): @@ -150,14 +150,14 @@ def test_deprecator_maker(self): func = dec('foo')(func_no_doc) with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: warnings.simplefilter('always') - assert func() == None + assert func() is None assert len(w) == 1 assert w[0].category is UserWarning dec = self.dep_maker(error_class=CustomError) func = dec('foo')(func_no_doc) with pytest.deprecated_call(): - assert func() == None + assert func() is None func = dec('foo', until='1.8')(func_no_doc) with pytest.raises(CustomError): diff --git a/nibabel/tests/test_ecat.py b/nibabel/tests/test_ecat.py index b681a59b0e..0f216091f2 100644 --- a/nibabel/tests/test_ecat.py +++ b/nibabel/tests/test_ecat.py @@ -164,7 +164,7 @@ def test_subheader(self): assert self.subhdr.get_nframes() == 1 assert (self.subhdr.get_nframes() == len(self.subhdr.subheaders)) - assert self.subhdr._check_affines() == True + assert self.subhdr._check_affines() is True assert_array_almost_equal(np.diag(self.subhdr.get_frame_affine()), np.array([2.20241979, 2.20241979, 3.125, 1.])) assert self.subhdr.get_zooms()[0] == 2.20241978764534 diff --git a/nibabel/tests/test_environment.py b/nibabel/tests/test_environment.py index e0514c337e..19891a607b 100644 --- a/nibabel/tests/test_environment.py +++ b/nibabel/tests/test_environment.py @@ -60,4 +60,4 @@ def test_sys_dir(): elif os.name == 'posix': assert sys_dir == r'/etc/nipy' else: - assert sys_dir == None + assert sys_dir is None diff --git a/nibabel/tests/test_files_interface.py b/nibabel/tests/test_files_interface.py index a75484159e..da91aaf03a 100644 --- a/nibabel/tests/test_files_interface.py +++ b/nibabel/tests/test_files_interface.py @@ -29,8 +29,8 @@ def test_files_spatialimages(): for klass in klasses: file_map = klass.make_file_map() for key, value in file_map.items(): - assert value.filename == None - assert value.fileobj == None + assert value.filename is None + assert value.fileobj is None assert value.pos == 0 # If we can't create new images in memory without loading, bail here if not klass.makeable: @@ -42,8 +42,8 @@ def test_files_spatialimages(): else: img = klass(arr, aff) for key, value in img.file_map.items(): - assert value.filename == None - assert value.fileobj == None + assert value.filename is None + assert value.fileobj is None assert value.pos == 0 diff --git a/nibabel/tests/test_fileslice.py b/nibabel/tests/test_fileslice.py index 924da5fc9f..07a2627910 100644 --- a/nibabel/tests/test_fileslice.py +++ b/nibabel/tests/test_fileslice.py @@ -243,9 +243,9 @@ def test_threshold_heuristic(): # Test for default skip / read heuristic # int assert threshold_heuristic(1, 9, 1, skip_thresh=8) == 'full' - assert threshold_heuristic(1, 9, 1, skip_thresh=7) == None + assert threshold_heuristic(1, 9, 1, skip_thresh=7) is None assert threshold_heuristic(1, 9, 2, skip_thresh=16) == 'full' - assert threshold_heuristic(1, 9, 2, skip_thresh=15) == None + assert threshold_heuristic(1, 9, 2, skip_thresh=15) is None # full slice, smallest step size assert (threshold_heuristic( slice(0, 9, 1), 9, 2, skip_thresh=2) == diff --git a/nibabel/tests/test_image_load_save.py b/nibabel/tests/test_image_load_save.py index 8dd64f8185..25c5b3e1de 100644 --- a/nibabel/tests/test_image_load_save.py +++ b/nibabel/tests/test_image_load_save.py @@ -274,7 +274,7 @@ def test_analyze_detection(): def wat(hdr): return nils.which_analyze_type(hdr.binaryblock) n1_hdr = Nifti1Header(b'\0' * 348, check=False) - assert wat(n1_hdr) == None + assert wat(n1_hdr) is None n1_hdr['sizeof_hdr'] = 540 assert wat(n1_hdr) == 'nifti2' assert wat(n1_hdr.as_byteswapped()) == 'nifti2' @@ -292,7 +292,7 @@ def wat(hdr): assert wat(n1_hdr) == 'analyze' n1_hdr['sizeof_hdr'] = 0 n1_hdr['magic'] = b'' - assert wat(n1_hdr) == None + assert wat(n1_hdr) is None n1_hdr['magic'] = 'n+1' assert wat(n1_hdr) == 'nifti1' n1_hdr['magic'] = 'ni1' diff --git a/nibabel/tests/test_nifti1.py b/nibabel/tests/test_nifti1.py index ef663f6e7b..8b6a56d965 100644 --- a/nibabel/tests/test_nifti1.py +++ b/nibabel/tests/test_nifti1.py @@ -1131,9 +1131,9 @@ def test_extension_basics(): def test_ext_eq(): ext = Nifti1Extension('comment', '123') assert ext == ext - assert not ext != ext + assert ext == ext ext2 = Nifti1Extension('comment', '124') - assert not ext == ext2 + assert ext != ext2 assert ext != ext2 @@ -1148,7 +1148,7 @@ def test_extension_list(): assert ext_c0 == ext_c1 ext = Nifti1Extension('comment', '123') ext_c1.append(ext) - assert not ext_c0 == ext_c1 + assert ext_c0 != ext_c1 ext_c0.append(ext) assert ext_c0 == ext_c1 @@ -1255,8 +1255,8 @@ def test_nifti_dicom_extension(): 'NiPy'.encode('utf-8')) dcmext = Nifti1DicomExtension(2, dcmbytes_explicit) assert dcmext.__class__ == Nifti1DicomExtension - assert dcmext._guess_implicit_VR() == False - assert dcmext._is_little_endian == True + assert dcmext._guess_implicit_VR() is False + assert dcmext._is_little_endian is True assert dcmext.get_code() == 2 assert dcmext.get_content().PatientID == 'NiPy' assert len(dcmext.get_content().values()) == 1 @@ -1267,7 +1267,7 @@ def test_nifti_dicom_extension(): dcmbytes_implicit = struct.pack('') # Big Endian Nifti1Header dcmext = Nifti1DicomExtension(2, dcmbytes_explicit_be, parent_hdr=hdr_be) assert dcmext.__class__ == Nifti1DicomExtension - assert dcmext._guess_implicit_VR() == False + assert dcmext._guess_implicit_VR() is False assert dcmext.get_code() == 2 assert dcmext.get_content().PatientID == 'NiPy' assert dcmext.get_content()[0x10, 0x20].value == 'NiPy' diff --git a/nibabel/tests/test_openers.py b/nibabel/tests/test_openers.py index eac73dd92b..d9d728046e 100644 --- a/nibabel/tests/test_openers.py +++ b/nibabel/tests/test_openers.py @@ -197,7 +197,7 @@ def file_opener(fileish, mode): assert os.path.exists('test.foo') # Check this doesn't add anything to parent - assert not '.foo' in Opener.compress_ext_map + assert '.foo' not in Opener.compress_ext_map def test_file_like_wrapper(): @@ -215,7 +215,7 @@ def test_file_like_wrapper(): fobj.close() assert fobj.closed # Added the fileobj name - assert fobj.name == None + assert fobj.name is None def test_compressionlevel(): diff --git a/nibabel/tests/test_optpkg.py b/nibabel/tests/test_optpkg.py index 387cebecba..1e652a51c5 100644 --- a/nibabel/tests/test_optpkg.py +++ b/nibabel/tests/test_optpkg.py @@ -18,7 +18,7 @@ def assert_good(pkg_name, min_version=None): pkg, have_pkg, setup = optional_package(pkg_name, min_version=min_version) assert have_pkg assert sys.modules[pkg_name] == pkg - assert setup() == None + assert setup() is None def assert_bad(pkg_name, min_version=None): @@ -54,7 +54,7 @@ def raise_Exception(*args, **kwargs): def test_versions(): fake_name = '_a_fake_package' fake_pkg = types.ModuleType(fake_name) - assert not 'fake_pkg' in sys.modules + assert 'fake_pkg' not in sys.modules # Not inserted yet assert_bad(fake_name) try: diff --git a/nibabel/tests/test_parrec.py b/nibabel/tests/test_parrec.py index 54c15fde6b..fe607c1982 100644 --- a/nibabel/tests/test_parrec.py +++ b/nibabel/tests/test_parrec.py @@ -182,7 +182,7 @@ def test_header(): si = np.array( [np.unique(x) for x in hdr.get_data_scaling()]).ravel() assert_almost_equal(si, (1.2903541326522827, 0.0), 5) - assert hdr.get_q_vectors() == None + assert hdr.get_q_vectors() is None assert hdr.get_bvals_bvecs() == (None, None) @@ -525,8 +525,8 @@ def test_diffusion_parameters_v4(): bvals, bvecs = dti_v4_hdr.get_bvals_bvecs() assert_almost_equal(bvals, DTI_PAR_BVALS) # no b-vector info in V4 .PAR files - assert bvecs == None - assert dti_v4_hdr.get_q_vectors() == None + assert bvecs is None + assert dti_v4_hdr.get_q_vectors() is None def test_null_diffusion_params(): @@ -538,7 +538,7 @@ def test_null_diffusion_params(): with suppress_warnings(): hdr = PARRECHeader(gen_info, slice_info, True) assert hdr.get_bvals_bvecs() == (None, None) - assert hdr.get_q_vectors() == None + assert hdr.get_q_vectors() is None def test_epi_params(): @@ -623,11 +623,11 @@ def test__get_uniqe_image_defs(): def test_copy_on_init(): # Test that input dict / array gets copied when making header hdr = PARRECHeader(HDR_INFO, HDR_DEFS) - assert not hdr.general_info is HDR_INFO + assert hdr.general_info is not HDR_INFO hdr.general_info['max_slices'] = 10 assert hdr.general_info['max_slices'] == 10 assert HDR_INFO['max_slices'] == 9 - assert not hdr.image_defs is HDR_DEFS + assert hdr.image_defs is not HDR_DEFS hdr.image_defs['image pixel size'] = 8 assert_array_equal(hdr.image_defs['image pixel size'], 8) assert_array_equal(HDR_DEFS['image pixel size'], 16) @@ -646,11 +646,11 @@ def test_header_copy(): hdr2 = hdr.copy() def assert_copy_ok(hdr1, hdr2): - assert not hdr1 is hdr2 + assert hdr1 is not hdr2 assert hdr1.permit_truncated == hdr2.permit_truncated - assert not hdr1.general_info is hdr2.general_info + assert hdr1.general_info is not hdr2.general_info assert_arr_dict_equal(hdr1.general_info, hdr2.general_info) - assert not hdr1.image_defs is hdr2.image_defs + assert hdr1.image_defs is not hdr2.image_defs assert_structarr_equal(hdr1.image_defs, hdr2.image_defs) assert_copy_ok(hdr, hdr2) @@ -866,8 +866,8 @@ def test_ADC_map(): # general_info indicates it is a diffusion scan, but because it is # a post-processed image, the bvals and bvecs aren't available bvals, bvecs = adc_hdr.get_bvals_bvecs() - assert bvals == None - assert bvecs == None + assert bvals is None + assert bvecs is None def test_alternative_header_field_names(): diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 873059b510..19dd5f6fd0 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -335,8 +335,7 @@ def test_parrec2nii_with_data(): # The data is very close, unless it's the fieldmap if par_root != 'fieldmap': conved_data_lps = flip_axis(conved_img.dataobj, 1) - assert np.allclose(conved_data_lps, - philips_img.dataobj) + assert np.allclose(conved_data_lps, philips_img.dataobj) with InTemporaryDirectory(): # Test some options dti_par = pjoin(BALLS, 'PARREC', 'DTI.PAR') diff --git a/nibabel/tests/test_spatialimages.py b/nibabel/tests/test_spatialimages.py index 3de2af99dd..e93c358756 100644 --- a/nibabel/tests/test_spatialimages.py +++ b/nibabel/tests/test_spatialimages.py @@ -67,7 +67,7 @@ def test_from_header(): hdr = Header(np.float64, shape=(1, 2, 3), zooms=(3.0, 2.0, 1.0)) copy = Header.from_header(hdr) assert hdr == copy - assert not hdr is copy + assert hdr is not copy class C(object): @@ -233,7 +233,7 @@ def test_images(self): arr = np.arange(24, dtype=np.int16).reshape((2, 3, 4)) img = self.image_class(arr, None) assert (img.get_fdata() == arr).all() - assert img.affine == None + assert img.affine is None def test_default_header(self): # Check default header is as expected @@ -348,24 +348,24 @@ def test_get_fdata(self): out_data[:] = 42 assert img.get_fdata() is out_data img.uncache() - assert not img.get_fdata() is out_data + assert img.get_fdata() is not out_data # The 42 has gone now. assert (img.get_fdata() == in_data_template).all() # If we can save, we can create a proxy image if not self.can_save: return rt_img = bytesio_round_trip(img) - assert not in_data is rt_img.dataobj + assert in_data is not rt_img.dataobj assert (rt_img.dataobj == in_data).all() out_data = rt_img.get_fdata() assert (out_data == in_data).all() - assert not rt_img.dataobj is out_data + assert rt_img.dataobj is not out_data assert out_data.dtype == np.dtype(np.float64) # cache assert rt_img.get_fdata() is out_data out_data[:] = 42 rt_img.uncache() - assert not rt_img.get_fdata() is out_data + assert rt_img.get_fdata() is not out_data assert (rt_img.get_fdata() == in_data).all() def test_get_data(self): @@ -395,19 +395,19 @@ def test_get_data(self): if not self.can_save: return rt_img = bytesio_round_trip(img) - assert not in_data is rt_img.dataobj + assert in_data is not rt_img.dataobj assert (rt_img.dataobj == in_data).all() with pytest.deprecated_call(): out_data = rt_img.get_data() assert (out_data == in_data).all() - assert not rt_img.dataobj is out_data + assert rt_img.dataobj is not out_data # cache with pytest.deprecated_call(): assert rt_img.get_data() is out_data out_data[:] = 42 rt_img.uncache() with pytest.deprecated_call(): - assert not rt_img.get_data() is out_data + assert rt_img.get_data() is not out_data with pytest.deprecated_call(): assert (rt_img.get_data() == in_data).all() diff --git a/nibabel/tests/test_spm99analyze.py b/nibabel/tests/test_spm99analyze.py index 331238db5c..5d7cb5ce73 100644 --- a/nibabel/tests/test_spm99analyze.py +++ b/nibabel/tests/test_spm99analyze.py @@ -151,9 +151,7 @@ def test_origin_checks(self): pytest.raises(*raiser) # diagnose binary block dxer = self.header_class.diagnose_binaryblock - assert (dxer(hdr.binaryblock) == - 'very large origin values ' - 'relative to dims') + assert dxer(hdr.binaryblock) == 'very large origin values relative to dims' class ImageScalingMixin(object): diff --git a/nibabel/tests/test_trackvis.py b/nibabel/tests/test_trackvis.py index bcfbfe673d..ad4eb083a2 100644 --- a/nibabel/tests/test_trackvis.py +++ b/nibabel/tests/test_trackvis.py @@ -291,8 +291,8 @@ def f(pts): # from vx to mm def test__check_hdr_points_space(): # Test checking routine for points_space input given header # None or voxmm -> no checks, pass through - assert tv._check_hdr_points_space({}, None) == None - assert tv._check_hdr_points_space({}, 'voxmm') == None + assert tv._check_hdr_points_space({}, None) is None + assert tv._check_hdr_points_space({}, 'voxmm') is None # strange value for points_space -> ValueError with pytest.raises(ValueError): tv._check_hdr_points_space({}, 'crazy') @@ -313,7 +313,7 @@ def test__check_hdr_points_space(): tv._check_hdr_points_space(hdr, 'voxel') # This is OK hdr['voxel_size'] = [2, 3, 4] - assert tv._check_hdr_points_space(hdr, 'voxel') == None + assert tv._check_hdr_points_space(hdr, 'voxel') is None # rasmm - check there is an affine, that it matches voxel_size and # voxel_order # no affine @@ -340,8 +340,7 @@ def test__check_hdr_points_space(): # This should be OK good_aff = np.diag([2, 3, 4, 1]) hdr['vox_to_ras'] = good_aff - assert (tv._check_hdr_points_space(hdr, 'rasmm') == - None) + assert tv._check_hdr_points_space(hdr, 'rasmm') is None # Default voxel order of LPS assumed hdr['voxel_order'] = '' # now the RAS affine raises an error @@ -350,8 +349,7 @@ def test__check_hdr_points_space(): # this affine does have LPS voxel order good_lps = np.dot(np.diag([-1, -1, 1, 1]), good_aff) hdr['vox_to_ras'] = good_lps - assert (tv._check_hdr_points_space(hdr, 'rasmm') == - None) + assert tv._check_hdr_points_space(hdr, 'rasmm') is None def test_empty_header(): @@ -461,7 +459,7 @@ def test_aff_to_hdr(): for hdr in ({}, {'version': 2}, {'version': 1}): tv.aff_to_hdr(aff2, hdr, pos_vox=True, set_order=False) assert_array_equal(hdr['voxel_size'], [1, 2, 3]) - assert not 'voxel_order' in hdr + assert 'voxel_order' not in hdr tv.aff_to_hdr(aff2, hdr, pos_vox=False, set_order=True) assert_array_equal(hdr['voxel_size'], [-1, 2, 3]) assert hdr['voxel_order'] == 'RAI' @@ -469,7 +467,7 @@ def test_aff_to_hdr(): assert_array_equal(hdr['voxel_size'], [1, 2, 3]) assert hdr['voxel_order'] == 'RAI' if 'version' in hdr and hdr['version'] == 1: - assert not 'vox_to_ras' in hdr + assert 'vox_to_ras' not in hdr else: assert_array_equal(hdr['vox_to_ras'], aff2) @@ -479,7 +477,7 @@ def test_tv_class(): assert tvf.streamlines == [] assert isinstance(tvf.header, np.ndarray) assert tvf.endianness == tv.native_code - assert tvf.filename == None + assert tvf.filename is None out_f = BytesIO() tvf.to_file(out_f) assert out_f.getvalue() == tv.empty_header().tostring() diff --git a/nibabel/tests/test_wrapstruct.py b/nibabel/tests/test_wrapstruct.py index f052098475..32035db995 100644 --- a/nibabel/tests/test_wrapstruct.py +++ b/nibabel/tests/test_wrapstruct.py @@ -175,7 +175,7 @@ def test_mappingness(self): for key, val in hdr.items(): assert_array_equal(hdr[key], val) # verify that .get operates as destined - assert hdr.get('nonexistent key') == None + assert hdr.get('nonexistent key') is None assert hdr.get('nonexistent key', 'default') == 'default' assert hdr.get(keys[0]) == vals[0] assert hdr.get(keys[0], 'default') == vals[0] From e3f171bc8c557de3815927af5bbf1d9fce2d7e25 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Thu, 6 Feb 2020 11:05:22 -0500 Subject: [PATCH 186/223] MNT: CI YAML formatting, extraneous .coveragerc --- .azure-pipelines/windows.yml | 2 +- .gitignore | 1 + .travis.yml | 2 +- for_testing/.coveragerc | 9 --------- 4 files changed, 3 insertions(+), 11 deletions(-) delete mode 100644 for_testing/.coveragerc diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index c7411a77c7..a73cb7b6de 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -100,7 +100,7 @@ jobs: -I test_rstutils ^ -I test_scaling ^ -I test_wrapstruct ^ - -I test_io + -I test_io displayName: 'Nose tests' condition: and(succeeded(), eq(variables['CHECK_TYPE'], 'nosetests')) - script: | diff --git a/.gitignore b/.gitignore index fd686f2781..e876975c27 100644 --- a/.gitignore +++ b/.gitignore @@ -85,3 +85,4 @@ doc/source/reference venv/ .buildbot.patch .vscode +for_testing/ diff --git a/.travis.yml b/.travis.yml index 483efe29ec..f13b53f5a1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -187,7 +187,7 @@ script: -I test_rstutils \ -I test_scaling \ -I test_wrapstruct \ - -I test_io + -I test_io elif [ "${CHECK_TYPE}" == "test" ]; then # Change into an innocuous directory and find tests from installation mkdir for_testing diff --git a/for_testing/.coveragerc b/for_testing/.coveragerc deleted file mode 100644 index 57747ec0d8..0000000000 --- a/for_testing/.coveragerc +++ /dev/null @@ -1,9 +0,0 @@ -[run] -branch = True -source = nibabel, nisext -include = */nibabel/*, */nisext/* -omit = - */externals/* - */benchmarks/* - */tests/* - nibabel/_version.py From eaab253772078df4e62145c970b54aa965c081b2 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Thu, 6 Feb 2020 11:06:16 -0500 Subject: [PATCH 187/223] TEST: Style and formatting --- nibabel/freesurfer/tests/test_io.py | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index b457a6c00d..521923057f 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -92,16 +92,12 @@ def test_geometry(): warnings.filterwarnings('always', category=DeprecationWarning) read_geometry(surf_path, read_metadata=True) - assert( - any('volume information contained' in str(ww.message) - for ww in w)) - assert( - any('extension code' in str(ww.message) for ww in w)) + assert any('volume information contained' in str(ww.message) for ww in w) + assert any('extension code' in str(ww.message) for ww in w) volume_info['head'] = [1, 2] with clear_and_catch_warnings() as w: write_geometry(surf_path, coords, faces, create_stamp, volume_info) - assert( - any('Unknown extension' in str(ww.message) for ww in w)) + assert any('Unknown extension' in str(ww.message) for ww in w) volume_info['a'] = 0 with pytest.raises(ValueError): write_geometry(surf_path, coords, faces, create_stamp, volume_info) @@ -146,7 +142,7 @@ def test_morph_data(): new_path = 'test' write_morph_data(new_path, curv) curv2 = read_morph_data(new_path) - assert np.array_equal (curv2, curv) + assert np.array_equal(curv2, curv) def test_write_morph_data(): @@ -163,7 +159,7 @@ def test_write_morph_data(): with pytest.raises(ValueError): write_morph_data('test.curv', np.zeros(shape), big_num) - # Windows 32-bit overflows Python int + # Windows 32-bit overflows Python int if np.dtype(np.int) != np.dtype(np.int32): with pytest.raises(ValueError): write_morph_data('test.curv', strided_scalar((big_num,))) @@ -272,12 +268,10 @@ def test_write_annot_fill_ctab(): # values back. badannot = (10 * np.arange(nlabels, dtype=np.int32)).reshape(-1, 1) rgbal = np.hstack((rgba, badannot)) - print(labels) with clear_and_catch_warnings() as w: write_annot(annot_path, labels, rgbal, names, fill_ctab=False) - assert ( - any('Annotation values in {} will be incorrect'.format( - annot_path) == str(ww.message) for ww in w)) + assert any('Annotation values in {} will be incorrect'.format(annot_path) == str(ww.message) + for ww in w) labels2, rgbal2, names2 = read_annot(annot_path, orig_ids=True) names2 = [n.decode('ascii') for n in names2] assert np.all(np.isclose(rgbal2[:, :4], rgba)) @@ -291,9 +285,8 @@ def test_write_annot_fill_ctab(): rgbal[:, 2] * (2 ** 16)) with clear_and_catch_warnings() as w: write_annot(annot_path, labels, rgbal, names, fill_ctab=False) - assert( - not any('Annotation values in {} will be incorrect'.format( - annot_path) == str(ww.message) for ww in w)) + assert all('Annotation values in {} will be incorrect'.format(annot_path) != str(ww.message) + for ww in w) labels2, rgbal2, names2 = read_annot(annot_path) names2 = [n.decode('ascii') for n in names2] assert np.all(np.isclose(rgbal2[:, :4], rgba)) @@ -356,7 +349,7 @@ def test_label(): assert label.shape[0] <= 163842 labels, scalars = read_label(label_path, True) - assert (np.all(labels == label)) + assert np.all(labels == label) assert len(labels) == len(scalars) From 51f248532abb83d4c5010867d78da3d84fdaa3db Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Thu, 6 Feb 2020 11:15:02 -0500 Subject: [PATCH 188/223] CI: Restore import-only test --- .travis.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.travis.yml b/.travis.yml index b869d33947..297604e49d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -36,6 +36,11 @@ jobs: - python: 3.5 env: - DEPENDS="-r requirements.txt" + # Clean install + - python: 3.5 + env: + - DEPENDS="" + - CHECK_TYPE=skiptests # Absolute minimum dependencies - python: 3.5 env: @@ -105,6 +110,7 @@ install: fi # Basic import check - python -c 'import nibabel; print(nibabel.__version__)' + - if [ "$CHECK_TYPE" == "skiptests" ]; then exit 0; fi before_script: # Point to nibabel data directory From a9bbe82c12ef4a514978c65e82d3d062af6bd078 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Thu, 6 Feb 2020 11:41:58 -0500 Subject: [PATCH 189/223] small cleaning after review --- nibabel/tests/test_arraywriters.py | 4 ++-- nibabel/tests/test_casting.py | 2 +- nibabel/tests/test_deprecator.py | 36 +++++++++++++---------------- nibabel/tests/test_ecat.py | 5 ++-- nibabel/tests/test_nifti1.py | 6 ++--- nibabel/tests/test_spatialimages.py | 15 +++++++----- nibabel/tests/test_spm99analyze.py | 4 ++-- nibabel/tests/test_volumeutils.py | 6 ++--- 8 files changed, 37 insertions(+), 41 deletions(-) diff --git a/nibabel/tests/test_arraywriters.py b/nibabel/tests/test_arraywriters.py index 14e9025c21..1a1c4eb156 100644 --- a/nibabel/tests/test_arraywriters.py +++ b/nibabel/tests/test_arraywriters.py @@ -640,7 +640,7 @@ def test_writer_maker(): assert (aw.slope, aw.inter) == (1, 0) aw.calc_scale() slope, inter = aw.slope, aw.inter - assert (slope, inter) != (1, 0) + assert not (slope, inter) == (1, 0) # Should run by default aw = make_array_writer(arr, np.int16) assert (aw.slope, aw.inter) == (slope, inter) @@ -704,7 +704,7 @@ def test_int_int_slope(): aw = SlopeArrayWriter(arr, out_dt) except ScalingError: continue - assert aw.slope != 0 + assert not aw.slope == 0 arr_back_sc = round_trip(aw) # integer allclose adiff = int_abs(arr - arr_back_sc) diff --git a/nibabel/tests/test_casting.py b/nibabel/tests/test_casting.py index 9006ce321c..c4f9b9ba9e 100644 --- a/nibabel/tests/test_casting.py +++ b/nibabel/tests/test_casting.py @@ -120,7 +120,7 @@ def test_casting(): # Confirm input array is not modified nans = np.isnan(farr) assert_array_equal(nans, np.isnan(farr_orig)) - assert_array_equal(farr[nans is False], farr_orig[nans is False]) + assert_array_equal(farr[nans == False], farr_orig[nans == False]) # Test scalars work and return scalars assert_array_equal(float_to_int(np.float32(0), np.int16), [0]) # Test scalar nan OK diff --git a/nibabel/tests/test_deprecator.py b/nibabel/tests/test_deprecator.py index 63d2b32a70..9c15a6566e 100644 --- a/nibabel/tests/test_deprecator.py +++ b/nibabel/tests/test_deprecator.py @@ -34,9 +34,9 @@ def test__add_dep_doc(): assert _add_dep_doc('bar\n\n', 'foo') == 'bar\n\nfoo\n' assert _add_dep_doc('bar\n \n', 'foo') == 'bar\n\nfoo\n' assert (_add_dep_doc(' bar\n\nSome explanation', 'foo\nbaz') == - ' bar\n\nfoo\nbaz\n\nSome explanation\n') + ' bar\n\nfoo\nbaz\n\nSome explanation\n') assert (_add_dep_doc(' bar\n\n Some explanation', 'foo\nbaz') == - ' bar\n \n foo\n baz\n \n Some explanation\n') + ' bar\n \n foo\n baz\n \n Some explanation\n') class CustomError(Exception): @@ -73,14 +73,12 @@ def test_dep_func(self): assert func() is None assert func.__doc__ == 'foo\n' func = dec('foo')(func_doc) - with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: - warnings.simplefilter('always') + with pytest.deprecated_call() as w: assert func(1) is None assert len(w) == 1 assert func.__doc__ == 'A docstring\n\nfoo\n' func = dec('foo')(func_doc_long) - with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: - warnings.simplefilter('always') + with pytest.deprecated_call() as w: assert func(1, 2) is None assert len(w) == 1 assert func.__doc__ == 'A docstring\n \n foo\n \n Some text\n' @@ -88,13 +86,11 @@ def test_dep_func(self): # Try some since and until versions func = dec('foo', '1.1')(func_no_doc) assert func.__doc__ == 'foo\n\n* deprecated from version: 1.1\n' - with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: - warnings.simplefilter('always') + with pytest.deprecated_call() as w: assert func() is None assert len(w) == 1 func = dec('foo', until='99.4')(func_no_doc) - with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: - warnings.simplefilter('always') + with pytest.deprecated_call() as w: assert func() is None assert len(w) == 1 assert (func.__doc__ == @@ -104,22 +100,22 @@ def test_dep_func(self): with pytest.raises(ExpiredDeprecationError): func() assert (func.__doc__ == - 'foo\n\n* Raises {} as of version: 1.8\n' - .format(ExpiredDeprecationError)) + 'foo\n\n* Raises {} as of version: 1.8\n' + .format(ExpiredDeprecationError)) func = dec('foo', '1.2', '1.8')(func_no_doc) with pytest.raises(ExpiredDeprecationError): func() assert (func.__doc__ == - 'foo\n\n* deprecated from version: 1.2\n' - '* Raises {} as of version: 1.8\n' - .format(ExpiredDeprecationError)) + 'foo\n\n* deprecated from version: 1.2\n' + '* Raises {} as of version: 1.8\n' + .format(ExpiredDeprecationError)) func = dec('foo', '1.2', '1.8')(func_doc_long) assert (func.__doc__ == - 'A docstring\n \n foo\n \n' - ' * deprecated from version: 1.2\n' - ' * Raises {} as of version: 1.8\n \n' - ' Some text\n' - .format(ExpiredDeprecationError)) + 'A docstring\n \n foo\n \n' + ' * deprecated from version: 1.2\n' + ' * Raises {} as of version: 1.8\n \n' + ' Some text\n' + .format(ExpiredDeprecationError)) with pytest.raises(ExpiredDeprecationError): func() diff --git a/nibabel/tests/test_ecat.py b/nibabel/tests/test_ecat.py index 0f216091f2..918cffc52b 100644 --- a/nibabel/tests/test_ecat.py +++ b/nibabel/tests/test_ecat.py @@ -21,7 +21,7 @@ from numpy.testing import assert_array_equal, assert_array_almost_equal -from ..testing_pytest import data_path, suppress_warnings, clear_and_catch_warnings +from ..testing_pytest import data_path, suppress_warnings from ..tmpdirs import InTemporaryDirectory from .test_wrapstruct import _TestWrapStructBase @@ -271,8 +271,7 @@ def test_mlist_regression(self): def test_from_filespec_deprecation(): # Check from_filespec raises Deprecation - with clear_and_catch_warnings() as w: - warnings.simplefilter('always', DeprecationWarning) + with pytest.deprecated_call() as w: # No warning for standard load img_loaded = EcatImage.load(ecat_file) assert len(w) == 0 diff --git a/nibabel/tests/test_nifti1.py b/nibabel/tests/test_nifti1.py index 8b6a56d965..d5dff4a4e4 100644 --- a/nibabel/tests/test_nifti1.py +++ b/nibabel/tests/test_nifti1.py @@ -1131,10 +1131,10 @@ def test_extension_basics(): def test_ext_eq(): ext = Nifti1Extension('comment', '123') assert ext == ext - assert ext == ext + assert not ext != ext ext2 = Nifti1Extension('comment', '124') assert ext != ext2 - assert ext != ext2 + assert not ext == ext2 def test_extension_codes(): @@ -1148,7 +1148,7 @@ def test_extension_list(): assert ext_c0 == ext_c1 ext = Nifti1Extension('comment', '123') ext_c1.append(ext) - assert ext_c0 != ext_c1 + assert not ext_c0 == ext_c1 ext_c0.append(ext) assert ext_c0 == ext_c1 diff --git a/nibabel/tests/test_spatialimages.py b/nibabel/tests/test_spatialimages.py index e93c358756..82da89b3d7 100644 --- a/nibabel/tests/test_spatialimages.py +++ b/nibabel/tests/test_spatialimages.py @@ -379,10 +379,10 @@ def test_get_data(self): img[0, 0, 0] # Make sure the right message gets raised: assert (str(exception_manager.value) == - "Cannot slice image objects; consider using " - "`img.slicer[slice]` to generate a sliced image (see " - "documentation for caveats) or slicing image array data " - "with `img.dataobj[slice]` or `img.get_fdata()[slice]`") + "Cannot slice image objects; consider using " + "`img.slicer[slice]` to generate a sliced image (see " + "documentation for caveats) or slicing image array data " + "with `img.dataobj[slice]` or `img.get_fdata()[slice]`") assert in_data is img.dataobj with pytest.deprecated_call(): out_data = img.get_data() @@ -648,7 +648,10 @@ def test_load_mmap(self): def test_header_deprecated(): - with pytest.deprecated_call(): + with pytest.deprecated_call() as w: class MyHeader(Header): pass - MyHeader() \ No newline at end of file + + assert len(w) == 0 + MyHeader() + assert len(w) == 1 \ No newline at end of file diff --git a/nibabel/tests/test_spm99analyze.py b/nibabel/tests/test_spm99analyze.py index 5d7cb5ce73..977fef3071 100644 --- a/nibabel/tests/test_spm99analyze.py +++ b/nibabel/tests/test_spm99analyze.py @@ -146,8 +146,8 @@ def test_origin_checks(self): fhdr, message, raiser = self.log_chk(hdr, 20) assert fhdr == hdr assert (message == 'very large origin values ' - 'relative to dims; leaving as set, ' - 'ignoring for affine') + 'relative to dims; leaving as set, ' + 'ignoring for affine') pytest.raises(*raiser) # diagnose binary block dxer = self.header_class.diagnose_binaryblock diff --git a/nibabel/tests/test_volumeutils.py b/nibabel/tests/test_volumeutils.py index 1591dae005..dca5053d74 100644 --- a/nibabel/tests/test_volumeutils.py +++ b/nibabel/tests/test_volumeutils.py @@ -57,8 +57,7 @@ assert_array_equal) import pytest -from ..testing_pytest import (assert_dt_equal, assert_allclose_safely, - suppress_warnings, clear_and_catch_warnings) +from ..testing_pytest import assert_dt_equal, assert_allclose_safely, suppress_warnings #: convenience variables for numpy types FLOAT_TYPES = np.sctypes['float'] @@ -1019,8 +1018,7 @@ def test_fname_ext_ul_case(): def test_allopen(): # This import into volumeutils is for compatibility. The code is the # ``openers`` module. - with clear_and_catch_warnings() as w: - warnings.filterwarnings('once', category=DeprecationWarning) + with pytest.deprecated_call() as w: # Test default mode is 'rb' fobj = allopen(__file__) # Check we got the deprecation warning From 19b55b9319d6f0366a26323c796f64950b053cb2 Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Thu, 6 Feb 2020 11:46:44 -0500 Subject: [PATCH 190/223] small edit --- nibabel/tests/test_deprecator.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/nibabel/tests/test_deprecator.py b/nibabel/tests/test_deprecator.py index 9c15a6566e..c508795cf9 100644 --- a/nibabel/tests/test_deprecator.py +++ b/nibabel/tests/test_deprecator.py @@ -144,11 +144,10 @@ class TestDeprecatorMaker(object): def test_deprecator_maker(self): dec = self.dep_maker(warn_class=UserWarning) func = dec('foo')(func_no_doc) - with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: - warnings.simplefilter('always') + with pytest.warns(UserWarning) as w: + # warnings.simplefilter('always') assert func() is None assert len(w) == 1 - assert w[0].category is UserWarning dec = self.dep_maker(error_class=CustomError) func = dec('foo')(func_no_doc) From 6838af6273f4a01e5318ec9fd880db1ceee9988b Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Thu, 6 Feb 2020 11:49:47 -0500 Subject: [PATCH 191/223] Update nibabel/tests/test_image_api.py Co-Authored-By: Chris Markiewicz --- nibabel/tests/test_image_api.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/test_image_api.py b/nibabel/tests/test_image_api.py index 34725ba186..f5aeb53822 100644 --- a/nibabel/tests/test_image_api.py +++ b/nibabel/tests/test_image_api.py @@ -115,7 +115,7 @@ def validate_header_deprecated(self, imaker, params): img = imaker() with pytest.deprecated_call(): hdr = img.get_header() - assert hdr is img.header + assert hdr is img.header def validate_filenames(self, imaker, params): # Validate the filename, file_map interface From 5064f9a40211388c9913cd4c8cc4f7edd3c2a635 Mon Sep 17 00:00:00 2001 From: Or Duek Date: Thu, 6 Feb 2020 17:14:24 -0500 Subject: [PATCH 192/223] Update nibabel/freesurfer/tests/test_mghformat.py Co-Authored-By: Chris Markiewicz --- nibabel/freesurfer/tests/test_mghformat.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/freesurfer/tests/test_mghformat.py b/nibabel/freesurfer/tests/test_mghformat.py index d70c4e9742..e3090ca5fa 100644 --- a/nibabel/freesurfer/tests/test_mghformat.py +++ b/nibabel/freesurfer/tests/test_mghformat.py @@ -217,7 +217,7 @@ def test_header_updating(): assert_almost_equal(mgz.affine, exp_aff, 6) assert_almost_equal(hdr.get_affine(), exp_aff, 6) # Test that initial wonky header elements have not changed - assert np.array_equal(hdr['delta'], 1) + assert np.all(hdr['delta'] == 1) assert_almost_equal(hdr['Mdc'].T, exp_aff[:3, :3]) # Save, reload, same thing img_fobj = io.BytesIO() From d9c385a2ef5befbd58778f0a784d319cd09cb05b Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Thu, 6 Feb 2020 20:27:30 -0500 Subject: [PATCH 193/223] CI: Enable doctests --- .azure-pipelines/windows.yml | 2 +- .travis.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index 849d36745d..8de4ed3466 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -114,7 +114,7 @@ jobs: mkdir for_testing cd for_testing cp ../.coveragerc . - pytest --cov nibabel -v --pyargs nibabel + pytest --doctest-modules --cov nibabel -v --pyargs nibabel displayName: 'Pytest tests' condition: and(succeeded(), eq(variables['CHECK_TYPE'], 'test')) - script: | diff --git a/.travis.yml b/.travis.yml index 67131f21c8..711601764b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -206,7 +206,7 @@ script: mkdir for_testing cd for_testing cp ../.coveragerc . - pytest --cov nibabel -v --pyargs nibabel + pytest --doctest-modules --cov nibabel -v --pyargs nibabel else false fi From 0a4944976e7a16988026644ac9db4721e6111efb Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Thu, 6 Feb 2020 20:37:06 -0500 Subject: [PATCH 194/223] TEST: Use numpy 1.13 legacy print settings --- nibabel/conftest.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 nibabel/conftest.py diff --git a/nibabel/conftest.py b/nibabel/conftest.py new file mode 100644 index 0000000000..243ea957e2 --- /dev/null +++ b/nibabel/conftest.py @@ -0,0 +1,15 @@ +import pytest + + +@pytest.fixture(autouse=True, scope="session") +def set_printopts(): + import numpy as np + from distutils.version import LooseVersion + + if LooseVersion(np.__version__) >= LooseVersion("1.14"): + legacy_printopt = np.get_printoptions().get("legacy") + np.set_printoptions(legacy="1.13") + yield + np.set_printoptions(legacy=legacy_printopt) + else: + yield From 40d24719afe76d1ba8ffd6bf454b6493a6bb71c0 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Fri, 7 Feb 2020 17:46:54 -0500 Subject: [PATCH 195/223] TEST: Convert nibabel.nicom to unittest/pytest --- nibabel/nicom/tests/__init__.py | 5 +- nibabel/nicom/tests/test_csareader.py | 79 +++---- nibabel/nicom/tests/test_dicomreaders.py | 44 ++-- nibabel/nicom/tests/test_dicomwrappers.py | 270 ++++++++++++---------- nibabel/nicom/tests/test_structreader.py | 31 ++- nibabel/nicom/tests/test_utils.py | 52 ++--- nibabel/pydicom_compat.py | 15 +- nibabel/tests/test_nifti1.py | 3 +- 8 files changed, 256 insertions(+), 243 deletions(-) diff --git a/nibabel/nicom/tests/__init__.py b/nibabel/nicom/tests/__init__.py index c7c3753010..127ad5a6e0 100644 --- a/nibabel/nicom/tests/__init__.py +++ b/nibabel/nicom/tests/__init__.py @@ -1 +1,4 @@ -# init to allow relative imports in tests +from ...pydicom_compat import have_dicom +import unittest + +dicom_test = unittest.skipUnless(have_dicom, "Could not import dicom or pydicom") diff --git a/nibabel/nicom/tests/test_csareader.py b/nibabel/nicom/tests/test_csareader.py index a6bf589e90..1692aad622 100644 --- a/nibabel/nicom/tests/test_csareader.py +++ b/nibabel/nicom/tests/test_csareader.py @@ -7,15 +7,13 @@ import numpy as np +from ...pydicom_compat import pydicom from .. import csareader as csa from .. import dwiparams as dwp -from nose.tools import (assert_true, assert_false, assert_equal, assert_raises) - -from ...testing import skipif - -from nibabel.pydicom_compat import dicom_test, pydicom -from .test_dicomwrappers import (IO_DATA_PATH, DATA) +import pytest +from . import dicom_test +from .test_dicomwrappers import IO_DATA_PATH, DATA CSA2_B0 = open(pjoin(IO_DATA_PATH, 'csa2_b0.bin'), 'rb').read() CSA2_B1000 = open(pjoin(IO_DATA_PATH, 'csa2_b1000.bin'), 'rb').read() @@ -27,59 +25,61 @@ @dicom_test def test_csa_header_read(): hdr = csa.get_csa_header(DATA, 'image') - assert_equal(hdr['n_tags'], 83) - assert_equal(csa.get_csa_header(DATA, 'series')['n_tags'], 65) - assert_raises(ValueError, csa.get_csa_header, DATA, 'xxxx') - assert_true(csa.is_mosaic(hdr)) + assert hdr['n_tags'] == 83 + assert csa.get_csa_header(DATA, 'series')['n_tags'] == 65 + with pytest.raises(ValueError): + csa.get_csa_header(DATA, 'xxxx') + assert csa.is_mosaic(hdr) # Get a shallow copy of the data, lacking the CSA marker # Need to do it this way because del appears broken in pydicom 0.9.7 data2 = pydicom.dataset.Dataset() for element in DATA: if (element.tag.group, element.tag.elem) != (0x29, 0x10): data2.add(element) - assert_equal(csa.get_csa_header(data2, 'image'), None) + assert csa.get_csa_header(data2, 'image') is None # Add back the marker - CSA works again data2[(0x29, 0x10)] = DATA[(0x29, 0x10)] - assert_true(csa.is_mosaic(csa.get_csa_header(data2, 'image'))) + assert csa.is_mosaic(csa.get_csa_header(data2, 'image')) def test_csas0(): for csa_str in (CSA2_B0, CSA2_B1000): csa_info = csa.read(csa_str) - assert_equal(csa_info['type'], 2) - assert_equal(csa_info['n_tags'], 83) + assert csa_info['type'] == 2 + assert csa_info['n_tags'] == 83 tags = csa_info['tags'] - assert_equal(len(tags), 83) + assert len(tags) == 83 n_o_m = tags['NumberOfImagesInMosaic'] - assert_equal(n_o_m['items'], [48]) + assert n_o_m['items'] == [48] csa_info = csa.read(CSA2_B1000) b_matrix = csa_info['tags']['B_matrix'] - assert_equal(len(b_matrix['items']), 6) + assert len(b_matrix['items']) == 6 b_value = csa_info['tags']['B_value'] - assert_equal(b_value['items'], [1000]) + assert b_value['items'] == [1000] def test_csa_len0(): # We did get a failure for item with item_len of 0 - gh issue #92 csa_info = csa.read(CSA2_0len) - assert_equal(csa_info['type'], 2) - assert_equal(csa_info['n_tags'], 44) + assert csa_info['type'] == 2 + assert csa_info['n_tags'] == 44 tags = csa_info['tags'] - assert_equal(len(tags), 44) + assert len(tags) == 44 def test_csa_nitem(): # testing csa.read's ability to raise an error when n_items >= 200 - assert_raises(csa.CSAReadError, csa.read, CSA_STR_1001n_items) + with pytest.raises(csa.CSAReadError): + csa.read(CSA_STR_1001n_items) # OK when < 1000 csa_info = csa.read(CSA_STR_valid) - assert_equal(len(csa_info['tags']), 1) + assert len(csa_info['tags']) == 1 # OK after changing module global n_items_thresh = csa.MAX_CSA_ITEMS try: csa.MAX_CSA_ITEMS = 2000 csa_info = csa.read(CSA_STR_1001n_items) - assert_equal(len(csa_info['tags']), 1) + assert len(csa_info['tags']) == 1 finally: csa.MAX_CSA_ITEMS = n_items_thresh @@ -88,32 +88,30 @@ def test_csa_params(): for csa_str in (CSA2_B0, CSA2_B1000): csa_info = csa.read(csa_str) n_o_m = csa.get_n_mosaic(csa_info) - assert_equal(n_o_m, 48) + assert n_o_m == 48 snv = csa.get_slice_normal(csa_info) - assert_equal(snv.shape, (3,)) - assert_true(np.allclose(1, - np.sqrt((snv * snv).sum()))) + assert snv.shape == (3,) + assert np.allclose(1, np.sqrt((snv * snv).sum())) amt = csa.get_acq_mat_txt(csa_info) - assert_equal(amt, '128p*128') + assert amt == '128p*128' csa_info = csa.read(CSA2_B0) b_matrix = csa.get_b_matrix(csa_info) - assert_equal(b_matrix, None) + assert b_matrix is None b_value = csa.get_b_value(csa_info) - assert_equal(b_value, 0) + assert b_value == 0 g_vector = csa.get_g_vector(csa_info) - assert_equal(g_vector, None) + assert g_vector is None csa_info = csa.read(CSA2_B1000) b_matrix = csa.get_b_matrix(csa_info) - assert_equal(b_matrix.shape, (3, 3)) + assert b_matrix.shape == (3, 3) # check (by absence of error) that the B matrix is positive # semi-definite. dwp.B2q(b_matrix) # no error b_value = csa.get_b_value(csa_info) - assert_equal(b_value, 1000) + assert b_value == 1000 g_vector = csa.get_g_vector(csa_info) - assert_equal(g_vector.shape, (3,)) - assert_true( - np.allclose(1, np.sqrt((g_vector * g_vector).sum()))) + assert g_vector.shape == (3,) + assert np.allclose(1, np.sqrt((g_vector * g_vector).sum())) def test_ice_dims(): @@ -124,9 +122,8 @@ def test_ice_dims(): for csa_str, ex_dims in ((CSA2_B0, ex_dims0), (CSA2_B1000, ex_dims1)): csa_info = csa.read(csa_str) - assert_equal(csa.get_ice_dims(csa_info), - ex_dims) - assert_equal(csa.get_ice_dims({}), None) + assert csa.get_ice_dims(csa_info) == ex_dims + assert csa.get_ice_dims({}) is None @dicom_test @@ -138,4 +135,4 @@ def test_missing_csa_elem(): csa_tag = pydicom.dataset.Tag(0x29, 0x1010) del dcm[csa_tag] hdr = csa.get_csa_header(dcm, 'image') - assert_equal(hdr, None) + assert hdr is None diff --git a/nibabel/nicom/tests/test_dicomreaders.py b/nibabel/nicom/tests/test_dicomreaders.py index cb03aae74b..167cb26de6 100644 --- a/nibabel/nicom/tests/test_dicomreaders.py +++ b/nibabel/nicom/tests/test_dicomreaders.py @@ -2,20 +2,17 @@ """ -from os.path import join as pjoin, abspath +from os.path import join as pjoin import numpy as np from .. import dicomreaders as didr +from ...pydicom_compat import pydicom -from nibabel.pydicom_compat import dicom_test, pydicom +import pytest +from . import dicom_test -from .test_dicomwrappers import (EXPECTED_AFFINE, - EXPECTED_PARAMS, - IO_DATA_PATH, - DATA) - -from nose.tools import (assert_true, assert_false, assert_equal, assert_raises) +from .test_dicomwrappers import EXPECTED_AFFINE, EXPECTED_PARAMS, IO_DATA_PATH, DATA from numpy.testing import assert_array_equal, assert_array_almost_equal @@ -24,7 +21,7 @@ def test_read_dwi(): img = didr.mosaic_to_nii(DATA) arr = img.get_data() - assert_equal(arr.shape, (128, 128, 48)) + assert arr.shape == (128, 128, 48) assert_array_almost_equal(img.affine, EXPECTED_AFFINE) @@ -32,11 +29,12 @@ def test_read_dwi(): def test_read_dwis(): data, aff, bs, gs = didr.read_mosaic_dwi_dir(IO_DATA_PATH, 'siemens_dwi_*.dcm.gz') - assert_equal(data.ndim, 4) + assert data.ndim == 4 assert_array_almost_equal(aff, EXPECTED_AFFINE) assert_array_almost_equal(bs, (0, EXPECTED_PARAMS[0])) assert_array_almost_equal(gs, (np.zeros((3,)), EXPECTED_PARAMS[1])) - assert_raises(IOError, didr.read_mosaic_dwi_dir, 'improbable') + with pytest.raises(IOError): + didr.read_mosaic_dwi_dir('improbable') @dicom_test @@ -53,29 +51,21 @@ def test_passing_kwds(): dicom_kwargs=dict(force=True)) assert_array_equal(data, data2) # This should raise an error in pydicom.dicomio.read_file - assert_raises(TypeError, - func, - IO_DATA_PATH, - dwi_glob, - dicom_kwargs=dict(not_a_parameter=True)) + with pytest.raises(TypeError): + func(IO_DATA_PATH, dwi_glob, dicom_kwargs=dict(not_a_parameter=True)) # These are invalid dicoms, so will raise an error unless force=True - assert_raises(pydicom.filereader.InvalidDicomError, - func, - IO_DATA_PATH, - csa_glob) + with pytest.raises(pydicom.filereader.InvalidDicomError): + func(IO_DATA_PATH, csa_glob) # But here, we catch the error because the dicoms are in the wrong # format - assert_raises(didr.DicomReadError, - func, - IO_DATA_PATH, - csa_glob, - dicom_kwargs=dict(force=True)) + with pytest.raises(didr.DicomReadError): + func(IO_DATA_PATH, csa_glob, dicom_kwargs=dict(force=True)) @dicom_test def test_slices_to_series(): dicom_files = (pjoin(IO_DATA_PATH, "%d.dcm" % i) for i in range(2)) wrappers = [didr.wrapper_from_file(f) for f in dicom_files] series = didr.slices_to_series(wrappers) - assert_equal(len(series), 1) - assert_equal(len(series[0]), 2) + assert len(series) == 1 + assert len(series[0]) == 2 diff --git a/nibabel/nicom/tests/test_dicomwrappers.py b/nibabel/nicom/tests/test_dicomwrappers.py index c78249c381..0bb875002b 100755 --- a/nibabel/nicom/tests/test_dicomwrappers.py +++ b/nibabel/nicom/tests/test_dicomwrappers.py @@ -9,18 +9,17 @@ import numpy as np -from nibabel.pydicom_compat import (have_dicom, pydicom, read_file, dicom_test, - tag_for_keyword) +from nibabel.pydicom_compat import have_dicom, pydicom, read_file, tag_for_keyword from .. import dicomwrappers as didw from .. import dicomreaders as didr from ...volumeutils import endian_codes +import pytest from unittest import TestCase -from nose.tools import (assert_true, assert_false, assert_equal, - assert_not_equal, assert_raises) +from . import dicom_test -from numpy.testing import assert_array_equal, assert_array_almost_equal, assert_warns +from numpy.testing import assert_array_equal, assert_array_almost_equal from ...tests.nibabel_data import get_nibabel_data, needs_nibabel_data IO_DATA_PATH = pjoin(dirname(__file__), 'data') @@ -71,31 +70,37 @@ def test_wrappers(): (didw.MosaicWrapper, ({}, None, 10)), (didw.MultiframeWrapper, (multi_minimal,))): dw = maker(*args) - assert_equal(dw.get('InstanceNumber'), None) - assert_equal(dw.get('AcquisitionNumber'), None) - assert_raises(KeyError, dw.__getitem__, 'not an item') - assert_raises(didw.WrapperError, dw.get_data) - assert_raises(didw.WrapperError, dw.get_affine) - assert_raises(TypeError, maker) + assert dw.get('InstanceNumber') is None + assert dw.get('AcquisitionNumber') is None + with pytest.raises(KeyError): + dw['not an item'] + with pytest.raises(didw.WrapperError): + dw.get_data() + with pytest.raises(didw.WrapperError): + dw.affine + with pytest.raises(TypeError): + maker() # Check default attributes if not maker is didw.MosaicWrapper: - assert_false(dw.is_mosaic) - assert_equal(dw.b_matrix, None) - assert_equal(dw.q_vector, None) + assert not dw.is_mosaic + assert dw.b_matrix is None + assert dw.q_vector is None for maker in (didw.wrapper_from_data, didw.Wrapper, didw.SiemensWrapper, didw.MosaicWrapper ): dw = maker(DATA) - assert_equal(dw.get('InstanceNumber'), 2) - assert_equal(dw.get('AcquisitionNumber'), 2) - assert_raises(KeyError, dw.__getitem__, 'not an item') + assert dw.get('InstanceNumber') == 2 + assert dw.get('AcquisitionNumber') == 2 + with pytest.raises(KeyError): + dw['not an item'] for maker in (didw.MosaicWrapper, didw.wrapper_from_data): dw = maker(DATA) - assert_true(dw.is_mosaic) + assert dw.is_mosaic # DATA is not a Multiframe DICOM file - assert_raises(didw.WrapperError, didw.MultiframeWrapper, DATA) + with pytest.raises(didw.WrapperError): + didw.MultiframeWrapper(DATA) def test_get_from_wrapper(): @@ -103,12 +108,13 @@ def test_get_from_wrapper(): # data dcm_data = {'some_key': 'some value'} dw = didw.Wrapper(dcm_data) - assert_equal(dw.get('some_key'), 'some value') - assert_equal(dw.get('some_other_key'), None) + assert dw.get('some_key') == 'some value' + assert dw.get('some_other_key') is None # Getitem uses the same dictionary access - assert_equal(dw['some_key'], 'some value') + assert dw['some_key'] == 'some value' # And raises a WrapperError for missing keys - assert_raises(KeyError, dw.__getitem__, 'some_other_key') + with pytest.raises(KeyError): + dw['some_other_key'] # Test we don't use attributes for get class FakeData(dict): @@ -116,7 +122,7 @@ class FakeData(dict): d = FakeData() d.some_key = 'another bit of data' dw = didw.Wrapper(d) - assert_equal(dw.get('some_key'), None) + assert dw.get('some_key') is None # Check get defers to dcm_data get class FakeData2(object): @@ -126,7 +132,7 @@ def get(self, key, default): d = FakeData2() d.some_key = 'another bit of data' dw = didw.Wrapper(d) - assert_equal(dw.get('some_key'), 1) + assert dw.get('some_key') == 1 @dicom_test @@ -134,36 +140,40 @@ def test_wrapper_from_data(): # test wrapper from data, wrapper from file for dw in (didw.wrapper_from_data(DATA), didw.wrapper_from_file(DATA_FILE)): - assert_equal(dw.get('InstanceNumber'), 2) - assert_equal(dw.get('AcquisitionNumber'), 2) - assert_raises(KeyError, dw.__getitem__, 'not an item') - assert_true(dw.is_mosaic) + assert dw.get('InstanceNumber') == 2 + assert dw.get('AcquisitionNumber') == 2 + with pytest.raises(KeyError): + dw['not an item'] + assert dw.is_mosaic assert_array_almost_equal( - np.dot(didr.DPCS_TO_TAL, dw.get_affine()), + np.dot(didr.DPCS_TO_TAL, dw.affine), EXPECTED_AFFINE) for dw in (didw.wrapper_from_data(DATA_PHILIPS), didw.wrapper_from_file(DATA_FILE_PHILIPS)): - assert_equal(dw.get('InstanceNumber'), 1) - assert_equal(dw.get('AcquisitionNumber'), 3) - assert_raises(KeyError, dw.__getitem__, 'not an item') - assert_true(dw.is_multiframe) + assert dw.get('InstanceNumber') == 1 + assert dw.get('AcquisitionNumber') == 3 + with pytest.raises(KeyError): + dw['not an item'] + assert dw.is_multiframe # Another CSA file dw = didw.wrapper_from_file(DATA_FILE_SLC_NORM) - assert_true(dw.is_mosaic) + assert dw.is_mosaic # Check that multiframe requires minimal set of DICOM tags fake_data = dict() fake_data['SOPClassUID'] = '1.2.840.10008.5.1.4.1.1.4.2' dw = didw.wrapper_from_data(fake_data) - assert_false(dw.is_multiframe) + assert not dw.is_multiframe # use the correct SOPClassUID fake_data['SOPClassUID'] = '1.2.840.10008.5.1.4.1.1.4.1' - assert_raises(didw.WrapperError, didw.wrapper_from_data, fake_data) + with pytest.raises(didw.WrapperError): + didw.wrapper_from_data(fake_data) fake_data['PerFrameFunctionalGroupsSequence'] = [None] - assert_raises(didw.WrapperError, didw.wrapper_from_data, fake_data) + with pytest.raises(didw.WrapperError): + didw.wrapper_from_data(fake_data) fake_data['SharedFunctionalGroupsSequence'] = [None] # minimal set should now be met dw = didw.wrapper_from_data(fake_data) - assert_true(dw.is_multiframe) + assert dw.is_multiframe @dicom_test @@ -179,19 +189,18 @@ def test_wrapper_args_kwds(): assert_array_equal(data, dcm2.get_data()) # Trying to read non-dicom file raises pydicom error, usually csa_fname = pjoin(IO_DATA_PATH, 'csa2_b0.bin') - assert_raises(pydicom.filereader.InvalidDicomError, - didw.wrapper_from_file, - csa_fname) + with pytest.raises(pydicom.filereader.InvalidDicomError): + didw.wrapper_from_file(csa_fname) # We can force the read, in which case rubbish returns dcm_malo = didw.wrapper_from_file(csa_fname, force=True) - assert_false(dcm_malo.is_mosaic) + assert not dcm_malo.is_mosaic @dicom_test def test_dwi_params(): dw = didw.wrapper_from_data(DATA) b_matrix = dw.b_matrix - assert_equal(b_matrix.shape, (3, 3)) + assert b_matrix.shape == (3, 3) q = dw.q_vector b = np.sqrt(np.sum(q * q)) # vector norm g = q / b @@ -204,9 +213,9 @@ def test_q_vector_etc(): # Test diffusion params in wrapper classes # Default is no q_vector, b_value, b_vector dw = didw.Wrapper(DATA) - assert_equal(dw.q_vector, None) - assert_equal(dw.b_value, None) - assert_equal(dw.b_vector, None) + assert dw.q_vector is None + assert dw.b_value is None + assert dw.b_vector is None for pos in range(3): q_vec = np.zeros((3,)) q_vec[pos] = 10. @@ -214,12 +223,12 @@ def test_q_vector_etc(): dw = didw.Wrapper(DATA) dw.q_vector = q_vec assert_array_equal(dw.q_vector, q_vec) - assert_equal(dw.b_value, 10) + assert dw.b_value == 10 assert_array_equal(dw.b_vector, q_vec / 10.) # Reset wrapped dicom to refresh one_time property dw = didw.Wrapper(DATA) dw.q_vector = np.array([0, 0, 1e-6]) - assert_equal(dw.b_value, 0) + assert dw.b_value == 0 assert_array_equal(dw.b_vector, np.zeros((3,))) # Test MosaicWrapper sdw = didw.MosaicWrapper(DATA) @@ -230,7 +239,7 @@ def test_q_vector_etc(): # Reset wrapped dicom to refresh one_time property sdw = didw.MosaicWrapper(DATA) sdw.q_vector = np.array([0, 0, 1e-6]) - assert_equal(sdw.b_value, 0) + assert sdw.b_value == 0 assert_array_equal(sdw.b_vector, np.zeros((3,))) @@ -238,51 +247,51 @@ def test_q_vector_etc(): def test_vol_matching(): # make the Siemens wrapper, check it compares True against itself dw_siemens = didw.wrapper_from_data(DATA) - assert_true(dw_siemens.is_mosaic) - assert_true(dw_siemens.is_csa) - assert_true(dw_siemens.is_same_series(dw_siemens)) + assert dw_siemens.is_mosaic + assert dw_siemens.is_csa + assert dw_siemens.is_same_series(dw_siemens) # make plain wrapper, compare against itself dw_plain = didw.Wrapper(DATA) - assert_false(dw_plain.is_mosaic) - assert_false(dw_plain.is_csa) - assert_true(dw_plain.is_same_series(dw_plain)) + assert not dw_plain.is_mosaic + assert not dw_plain.is_csa + assert dw_plain.is_same_series(dw_plain) # specific vs plain wrapper compares False, because the Siemens # wrapper has more non-empty information - assert_false(dw_plain.is_same_series(dw_siemens)) + assert not dw_plain.is_same_series(dw_siemens) # and this should be symmetric - assert_false(dw_siemens.is_same_series(dw_plain)) + assert not dw_siemens.is_same_series(dw_plain) # we can even make an empty wrapper. This compares True against # itself but False against the others dw_empty = didw.Wrapper({}) - assert_true(dw_empty.is_same_series(dw_empty)) - assert_false(dw_empty.is_same_series(dw_plain)) - assert_false(dw_plain.is_same_series(dw_empty)) + assert dw_empty.is_same_series(dw_empty) + assert not dw_empty.is_same_series(dw_plain) + assert not dw_plain.is_same_series(dw_empty) # Just to check the interface, make a pretend signature-providing # object. class C(object): series_signature = {} - assert_true(dw_empty.is_same_series(C())) + assert dw_empty.is_same_series(C()) # make the Philips wrapper, check it compares True against itself dw_philips = didw.wrapper_from_data(DATA_PHILIPS) - assert_true(dw_philips.is_multiframe) - assert_true(dw_philips.is_same_series(dw_philips)) + assert dw_philips.is_multiframe + assert dw_philips.is_same_series(dw_philips) # make plain wrapper, compare against itself dw_plain_philips = didw.Wrapper(DATA) - assert_false(dw_plain_philips.is_multiframe) - assert_true(dw_plain_philips.is_same_series(dw_plain_philips)) + assert not dw_plain_philips.is_multiframe + assert dw_plain_philips.is_same_series(dw_plain_philips) # specific vs plain wrapper compares False, because the Philips # wrapper has more non-empty information - assert_false(dw_plain_philips.is_same_series(dw_philips)) + assert not dw_plain_philips.is_same_series(dw_philips) # and this should be symmetric - assert_false(dw_philips.is_same_series(dw_plain_philips)) + assert not dw_philips.is_same_series(dw_plain_philips) # we can even make an empty wrapper. This compares True against # itself but False against the others dw_empty = didw.Wrapper({}) - assert_true(dw_empty.is_same_series(dw_empty)) - assert_false(dw_empty.is_same_series(dw_plain_philips)) - assert_false(dw_plain_philips.is_same_series(dw_empty)) + assert dw_empty.is_same_series(dw_empty) + assert not dw_empty.is_same_series(dw_plain_philips) + assert not dw_plain_philips.is_same_series(dw_empty) @dicom_test @@ -290,10 +299,10 @@ def test_slice_indicator(): dw_0 = didw.wrapper_from_file(DATA_FILE_B0) dw_1000 = didw.wrapper_from_data(DATA) z = dw_0.slice_indicator - assert_false(z is None) - assert_equal(z, dw_1000.slice_indicator) + assert not z is None + assert z == dw_1000.slice_indicator dw_empty = didw.Wrapper({}) - assert_true(dw_empty.slice_indicator is None) + assert dw_empty.slice_indicator is None @dicom_test @@ -301,7 +310,7 @@ def test_orthogonal(): # Test that the slice normal is sufficiently orthogonal dw = didw.wrapper_from_file(DATA_FILE_SLC_NORM) R = dw.rotation_matrix - assert_true(np.allclose(np.eye(3), np.dot(R, R.T), atol=1e-6)) + assert np.allclose(np.eye(3), np.dot(R, R.T), atol=1e-6) # Test the threshold for rotation matrix orthogonality d = {} @@ -313,7 +322,8 @@ def test_orthogonal(): assert_array_almost_equal(dw.rotation_matrix, np.eye(3), 5) d['ImageOrientationPatient'] = [1e-4, 1, 0, 1, 0, 0] dw = didw.wrapper_from_data(d) - assert_raises(didw.WrapperPrecisionError, getattr, dw, 'rotation_matrix') + with pytest.raises(didw.WrapperPrecisionError): + dw.rotation_matrix @dicom_test @@ -338,7 +348,7 @@ def test_use_csa_sign(): iop = dw.image_orient_patient dw.image_orient_patient = np.c_[iop[:, 1], iop[:, 0]] dw2 = didw.wrapper_from_file(DATA_FILE_SLC_NORM) - assert_true(np.allclose(dw.slice_normal, dw2.slice_normal)) + assert np.allclose(dw.slice_normal, dw2.slice_normal) @dicom_test @@ -347,7 +357,8 @@ def test_assert_parallel(): # slice normal are not parallel dw = didw.wrapper_from_file(DATA_FILE_SLC_NORM) dw.image_orient_patient = np.c_[[1., 0., 0.], [0., 1., 0.]] - assert_raises(AssertionError, dw.__getattribute__, 'slice_normal') + with pytest.raises(AssertionError): + dw.slice_normal @dicom_test @@ -355,7 +366,7 @@ def test_decimal_rescale(): # Test that we don't get back a data array with dtype np.object when our # rescale slope is a decimal dw = didw.wrapper_from_file(DATA_FILE_DEC_RSCL) - assert_not_equal(dw.get_data().dtype, np.object) + assert dw.get_data().dtype != np.object def fake_frames(seq_name, field_name, value_seq): @@ -449,84 +460,95 @@ def test_shape(self): MFW = self.WRAPCLASS dw = MFW(fake_mf) # No rows, cols, raise WrapperError - assert_raises(didw.WrapperError, getattr, dw, 'image_shape') + with pytest.raises(didw.WrapperError): + dw.image_shape fake_mf['Rows'] = 64 - assert_raises(didw.WrapperError, getattr, dw, 'image_shape') + with pytest.raises(didw.WrapperError): + dw.image_shape fake_mf.pop('Rows') fake_mf['Columns'] = 64 - assert_raises(didw.WrapperError, getattr, dw, 'image_shape') + with pytest.raises(didw.WrapperError): + dw.image_shape fake_mf['Rows'] = 32 # Missing frame data, raise AssertionError - assert_raises(AssertionError, getattr, dw, 'image_shape') + with pytest.raises(AssertionError): + dw.image_shape fake_mf['NumberOfFrames'] = 4 # PerFrameFunctionalGroupsSequence does not match NumberOfFrames - assert_raises(AssertionError, getattr, dw, 'image_shape') + with pytest.raises(AssertionError): + dw.image_shape # check 3D shape when StackID index is 0 div_seq = ((1, 1), (1, 2), (1, 3), (1, 4)) fake_mf.update(fake_shape_dependents(div_seq, sid_dim=0)) - assert_equal(MFW(fake_mf).image_shape, (32, 64, 4)) + assert MFW(fake_mf).image_shape == (32, 64, 4) # Check stack number matching when StackID index is 0 div_seq = ((1, 1), (1, 2), (1, 3), (2, 4)) fake_mf.update(fake_shape_dependents(div_seq, sid_dim=0)) - assert_raises(didw.WrapperError, getattr, MFW(fake_mf), 'image_shape') + with pytest.raises(didw.WrapperError): + MFW(fake_mf).image_shape # Make some fake frame data for 4D when StackID index is 0 div_seq = ((1, 1, 1), (1, 2, 1), (1, 1, 2), (1, 2, 2), (1, 1, 3), (1, 2, 3)) fake_mf.update(fake_shape_dependents(div_seq, sid_dim=0)) - assert_equal(MFW(fake_mf).image_shape, (32, 64, 2, 3)) + assert MFW(fake_mf).image_shape == (32, 64, 2, 3) # Check stack number matching for 4D when StackID index is 0 div_seq = ((1, 1, 1), (1, 2, 1), (1, 1, 2), (1, 2, 2), (1, 1, 3), (2, 2, 3)) fake_mf.update(fake_shape_dependents(div_seq, sid_dim=0)) - assert_raises(didw.WrapperError, getattr, MFW(fake_mf), 'image_shape') + with pytest.raises(didw.WrapperError): + MFW(fake_mf).image_shape # Check indices can be non-contiguous when StackID index is 0 div_seq = ((1, 1, 1), (1, 2, 1), (1, 1, 3), (1, 2, 3)) fake_mf.update(fake_shape_dependents(div_seq, sid_dim=0)) - assert_equal(MFW(fake_mf).image_shape, (32, 64, 2, 2)) + assert MFW(fake_mf).image_shape == (32, 64, 2, 2) # Check indices can include zero when StackID index is 0 div_seq = ((1, 1, 0), (1, 2, 0), (1, 1, 3), (1, 2, 3)) fake_mf.update(fake_shape_dependents(div_seq, sid_dim=0)) - assert_equal(MFW(fake_mf).image_shape, (32, 64, 2, 2)) + assert MFW(fake_mf).image_shape == (32, 64, 2, 2) # check 3D shape when there is no StackID index div_seq = ((1,), (2,), (3,), (4,)) sid_seq = (1, 1, 1, 1) fake_mf.update(fake_shape_dependents(div_seq, sid_seq=sid_seq)) - assert_equal(MFW(fake_mf).image_shape, (32, 64, 4)) + assert MFW(fake_mf).image_shape == (32, 64, 4) # check 3D stack number matching when there is no StackID index div_seq = ((1,), (2,), (3,), (4,)) sid_seq = (1, 1, 1, 2) fake_mf.update(fake_shape_dependents(div_seq, sid_seq=sid_seq)) - assert_raises(didw.WrapperError, getattr, MFW(fake_mf), 'image_shape') + with pytest.raises(didw.WrapperError): + MFW(fake_mf).image_shape # check 4D shape when there is no StackID index div_seq = ((1, 1), (2, 1), (1, 2), (2, 2), (1, 3), (2, 3)) sid_seq = (1, 1, 1, 1, 1, 1) fake_mf.update(fake_shape_dependents(div_seq, sid_seq=sid_seq)) - assert_equal(MFW(fake_mf).image_shape, (32, 64, 2, 3)) + assert MFW(fake_mf).image_shape == (32, 64, 2, 3) # check 4D stack number matching when there is no StackID index div_seq = ((1, 1), (2, 1), (1, 2), (2, 2), (1, 3), (2, 3)) sid_seq = (1, 1, 1, 1, 1, 2) fake_mf.update(fake_shape_dependents(div_seq, sid_seq=sid_seq)) - assert_raises(didw.WrapperError, getattr, MFW(fake_mf), 'image_shape') + with pytest.raises(didw.WrapperError): + MFW(fake_mf).image_shape # check 3D shape when StackID index is 1 div_seq = ((1, 1), (2, 1), (3, 1), (4, 1)) fake_mf.update(fake_shape_dependents(div_seq, sid_dim=1)) - assert_equal(MFW(fake_mf).image_shape, (32, 64, 4)) + assert MFW(fake_mf).image_shape == (32, 64, 4) # Check stack number matching when StackID index is 1 div_seq = ((1, 1), (2, 1), (3, 2), (4, 1)) fake_mf.update(fake_shape_dependents(div_seq, sid_dim=1)) - assert_raises(didw.WrapperError, getattr, MFW(fake_mf), 'image_shape') + with pytest.raises(didw.WrapperError): + MFW(fake_mf).image_shape # Make some fake frame data for 4D when StackID index is 1 div_seq = ((1, 1, 1), (2, 1, 1), (1, 1, 2), (2, 1, 2), (1, 1, 3), (2, 1, 3)) fake_mf.update(fake_shape_dependents(div_seq, sid_dim=1)) - assert_equal(MFW(fake_mf).image_shape, (32, 64, 2, 3)) + assert MFW(fake_mf).image_shape == (32, 64, 2, 3) def test_iop(self): # Test Image orient patient for multiframe fake_mf = copy(self.MINIMAL_MF) MFW = self.WRAPCLASS dw = MFW(fake_mf) - assert_raises(didw.WrapperError, getattr, dw, 'image_orient_patient') + with pytest.raises(didw.WrapperError): + dw.image_orient_patient # Make a fake frame fake_frame = fake_frames('PlaneOrientationSequence', 'ImageOrientationPatient', @@ -535,8 +557,8 @@ def test_iop(self): assert_array_equal(MFW(fake_mf).image_orient_patient, [[0, 1], [1, 0], [0, 0]]) fake_mf['SharedFunctionalGroupsSequence'] = [None] - assert_raises(didw.WrapperError, - getattr, MFW(fake_mf), 'image_orient_patient') + with pytest.raises(didw.WrapperError): + MFW(fake_mf).image_orient_patient fake_mf['PerFrameFunctionalGroupsSequence'] = [fake_frame] assert_array_equal(MFW(fake_mf).image_orient_patient, [[0, 1], [1, 0], [0, 0]]) @@ -546,14 +568,16 @@ def test_voxel_sizes(self): fake_mf = copy(self.MINIMAL_MF) MFW = self.WRAPCLASS dw = MFW(fake_mf) - assert_raises(didw.WrapperError, getattr, dw, 'voxel_sizes') + with pytest.raises(didw.WrapperError): + dw.voxel_sizes # Make a fake frame fake_frame = fake_frames('PixelMeasuresSequence', 'PixelSpacing', [[2.1, 3.2]])[0] fake_mf['SharedFunctionalGroupsSequence'] = [fake_frame] # Still not enough, we lack information for slice distances - assert_raises(didw.WrapperError, getattr, MFW(fake_mf), 'voxel_sizes') + with pytest.raises(didw.WrapperError): + MFW(fake_mf).voxel_sizes # This can come from SpacingBetweenSlices or frame SliceThickness fake_mf['SpacingBetweenSlices'] = 4.3 assert_array_equal(MFW(fake_mf).voxel_sizes, [2.1, 3.2, 4.3]) @@ -565,7 +589,8 @@ def test_voxel_sizes(self): assert_array_equal(MFW(fake_mf).voxel_sizes, [2.1, 3.2, 5.4]) # Removing shared leads to error again fake_mf['SharedFunctionalGroupsSequence'] = [None] - assert_raises(didw.WrapperError, getattr, MFW(fake_mf), 'voxel_sizes') + with pytest.raises(didw.WrapperError): + MFW(fake_mf).voxel_sizes # Restoring to frames makes it work again fake_mf['PerFrameFunctionalGroupsSequence'] = [fake_frame] assert_array_equal(MFW(fake_mf).voxel_sizes, [2.1, 3.2, 5.4]) @@ -584,7 +609,8 @@ def test_image_position(self): fake_mf = copy(self.MINIMAL_MF) MFW = self.WRAPCLASS dw = MFW(fake_mf) - assert_raises(didw.WrapperError, getattr, dw, 'image_position') + with pytest.raises(didw.WrapperError): + dw.image_position # Make a fake frame fake_frame = fake_frames('PlanePositionSequence', 'ImagePositionPatient', @@ -592,21 +618,23 @@ def test_image_position(self): fake_mf['SharedFunctionalGroupsSequence'] = [fake_frame] assert_array_equal(MFW(fake_mf).image_position, [-2, 3, 7]) fake_mf['SharedFunctionalGroupsSequence'] = [None] - assert_raises(didw.WrapperError, - getattr, MFW(fake_mf), 'image_position') + with pytest.raises(didw.WrapperError): + MFW(fake_mf).image_position fake_mf['PerFrameFunctionalGroupsSequence'] = [fake_frame] assert_array_equal(MFW(fake_mf).image_position, [-2, 3, 7]) # Check lists of Decimals work fake_frame.PlanePositionSequence[0].ImagePositionPatient = [ Decimal(str(v)) for v in [-2, 3, 7]] assert_array_equal(MFW(fake_mf).image_position, [-2, 3, 7]) - assert_equal(MFW(fake_mf).image_position.dtype, float) + assert MFW(fake_mf).image_position.dtype == float @dicom_test def test_affine(self): # Make sure we find orientation/position/spacing info dw = didw.wrapper_from_file(DATA_FILE_4D) - dw.get_affine() + aff = dw.affine + with pytest.deprecated_call(): + assert np.array_equal(dw.get_affine(), aff) @dicom_test def test_data_real(self): @@ -619,13 +647,12 @@ def test_data_real(self): if endian_codes[data.dtype.byteorder] == '>': data = data.byteswap() dat_str = data.tostring() - assert_equal(sha1(dat_str).hexdigest(), - '149323269b0af92baa7508e19ca315240f77fa8c') + assert sha1(dat_str).hexdigest() == '149323269b0af92baa7508e19ca315240f77fa8c' @dicom_test def test_slicethickness_fallback(self): dw = didw.wrapper_from_file(DATA_FILE_EMPTY_ST) - assert_equal(dw.voxel_sizes[2], 1.0) + assert dw.voxel_sizes[2] == 1.0 @dicom_test @needs_nibabel_data('nitest-dicom') @@ -633,14 +660,15 @@ def test_data_derived_shape(self): # Test 4D diffusion data with an additional trace volume included # Excludes the trace volume and generates the correct shape dw = didw.wrapper_from_file(DATA_FILE_4D_DERIVED) - assert_equal(dw.image_shape, (96, 96, 60, 33)) + assert dw.image_shape == (96, 96, 60, 33) @dicom_test @needs_nibabel_data('nitest-dicom') def test_data_unreadable_private_headers(self): # Test CT image with unreadable CSA tags - dw = assert_warns(UserWarning, didw.wrapper_from_file, DATA_FILE_CT) - assert_equal(dw.image_shape, (512, 571)) + with pytest.warns(UserWarning): + dw = didw.wrapper_from_file(DATA_FILE_CT) + assert dw.image_shape == (512, 571) @dicom_test def test_data_fake(self): @@ -649,19 +677,22 @@ def test_data_fake(self): MFW = self.WRAPCLASS dw = MFW(fake_mf) # Fails - no shape - assert_raises(didw.WrapperError, dw.get_data) + with pytest.raises(didw.WrapperError): + dw.get_data() # Set shape by cheating dw.image_shape = (2, 3, 4) # Still fails - no data - assert_raises(didw.WrapperError, dw.get_data) + with pytest.raises(didw.WrapperError): + dw.get_data() # Make shape and indices fake_mf['Rows'] = 2 fake_mf['Columns'] = 3 dim_idxs = ((1, 1), (1, 2), (1, 3), (1, 4)) fake_mf.update(fake_shape_dependents(dim_idxs, sid_dim=0)) - assert_equal(MFW(fake_mf).image_shape, (2, 3, 4)) + assert MFW(fake_mf).image_shape == (2, 3, 4) # Still fails - no data - assert_raises(didw.WrapperError, dw.get_data) + with pytest.raises(didw.WrapperError): + dw.get_data() # Add data - 3D data = np.arange(24).reshape((2, 3, 4)) # Frames dim is first for some reason @@ -723,7 +754,8 @@ def test__scale_data(self): fake_mf['PerFrameFunctionalGroupsSequence'] = [fake_frame] # Lacking RescaleIntercept -> Error dw = MFW(fake_mf) - assert_raises(AttributeError, dw._scale_data, data) + with pytest.raises(AttributeError): + dw._scale_data(data) fake_frame.PixelValueTransformationSequence[0].RescaleIntercept = -2 assert_array_equal(data * 3 - 2, dw._scale_data(data)) # Decimals are OK diff --git a/nibabel/nicom/tests/test_structreader.py b/nibabel/nicom/tests/test_structreader.py index 05461d18a0..6e58931559 100644 --- a/nibabel/nicom/tests/test_structreader.py +++ b/nibabel/nicom/tests/test_structreader.py @@ -5,9 +5,6 @@ from ..structreader import Unpacker -from nose.tools import (assert_true, assert_false, assert_equal, assert_raises) - - def test_unpacker(): s = b'1234\x00\x01' @@ -22,30 +19,30 @@ def test_unpacker(): swapped_int = le_int swapped_code = '<' up_str = Unpacker(s, endian='<') - assert_equal(up_str.read(4), b'1234') + assert up_str.read(4) == b'1234' up_str.ptr = 0 - assert_equal(up_str.unpack('4s'), (b'1234',)) - assert_equal(up_str.unpack('h'), (le_int,)) + assert up_str.unpack('4s') == (b'1234',) + assert up_str.unpack('h') == (le_int,) up_str = Unpacker(s, endian='>') - assert_equal(up_str.unpack('4s'), (b'1234',)) - assert_equal(up_str.unpack('h'), (be_int,)) + assert up_str.unpack('4s') == (b'1234',) + assert up_str.unpack('h') == (be_int,) # now test conflict of endian up_str = Unpacker(s, ptr=4, endian='>') - assert_equal(up_str.unpack('h'), (be_int,)) + assert up_str.unpack('>h') == (be_int,) up_str.ptr = 4 - assert_equal(up_str.unpack('@h'), (native_int,)) + assert up_str.unpack('@h') == (native_int,) # test -1 for read up_str.ptr = 2 - assert_equal(up_str.read(), b'34\x00\x01') + assert up_str.read() == b'34\x00\x01' # past end - assert_equal(up_str.read(), b'') + assert up_str.read() == b'' # with n_bytes up_str.ptr = 2 - assert_equal(up_str.read(2), b'34') - assert_equal(up_str.read(2), b'\x00\x01') + assert up_str.read(2) == b'34' + assert up_str.read(2) == b'\x00\x01' diff --git a/nibabel/nicom/tests/test_utils.py b/nibabel/nicom/tests/test_utils.py index a7ab9b6bdc..142daa3d16 100644 --- a/nibabel/nicom/tests/test_utils.py +++ b/nibabel/nicom/tests/test_utils.py @@ -2,64 +2,48 @@ """ import re - -from numpy.testing import (assert_almost_equal, - assert_array_equal) - -from nose.tools import (assert_true, assert_false, assert_raises, - assert_equal, assert_not_equal) - - from ..utils import find_private_section -from nibabel.pydicom_compat import dicom_test, pydicom -from .test_dicomwrappers import (DATA, DATA_PHILIPS) +from . import dicom_test +from ...pydicom_compat import pydicom +from .test_dicomwrappers import DATA, DATA_PHILIPS @dicom_test def test_find_private_section_real(): # Find section containing named private creator information # On real data first - assert_equal(find_private_section(DATA, 0x29, 'SIEMENS CSA HEADER'), - 0x1000) - assert_equal(find_private_section(DATA, 0x29, 'SIEMENS MEDCOM HEADER2'), - 0x1100) - assert_equal(find_private_section(DATA_PHILIPS, 0x29, 'SIEMENS CSA HEADER'), - None) + assert find_private_section(DATA, 0x29, 'SIEMENS CSA HEADER') == 0x1000 + assert find_private_section(DATA, 0x29, 'SIEMENS MEDCOM HEADER2') == 0x1100 + assert find_private_section(DATA_PHILIPS, 0x29, 'SIEMENS CSA HEADER') == None # Make fake datasets ds = pydicom.dataset.Dataset({}) ds.add_new((0x11, 0x10), 'LO', b'some section') - assert_equal(find_private_section(ds, 0x11, 'some section'), 0x1000) + assert find_private_section(ds, 0x11, 'some section') == 0x1000 ds.add_new((0x11, 0x11), 'LO', b'anther section') ds.add_new((0x11, 0x12), 'LO', b'third section') - assert_equal(find_private_section(ds, 0x11, 'third section'), 0x1200) + assert find_private_section(ds, 0x11, 'third section') == 0x1200 # Wrong 'OB' is acceptable for VM (should be 'LO') ds.add_new((0x11, 0x12), 'OB', b'third section') - assert_equal(find_private_section(ds, 0x11, 'third section'), 0x1200) + assert find_private_section(ds, 0x11, 'third section') == 0x1200 # Anything else not acceptable ds.add_new((0x11, 0x12), 'PN', b'third section') - assert_equal(find_private_section(ds, 0x11, 'third section'), None) + assert find_private_section(ds, 0x11, 'third section') is None # The input (DICOM value) can be a string insteal of bytes ds.add_new((0x11, 0x12), 'LO', 'third section') - assert_equal(find_private_section(ds, 0x11, 'third section'), 0x1200) + assert find_private_section(ds, 0x11, 'third section') == 0x1200 # Search can be bytes as well as string ds.add_new((0x11, 0x12), 'LO', b'third section') - assert_equal(find_private_section(ds, 0x11, b'third section'), 0x1200) + assert find_private_section(ds, 0x11, b'third section') == 0x1200 # Search with string or bytes must be exact - assert_equal(find_private_section(ds, 0x11, b'third sectio'), None) - assert_equal(find_private_section(ds, 0x11, 'hird sectio'), None) + assert find_private_section(ds, 0x11, b'third sectio') is None + assert find_private_section(ds, 0x11, 'hird sectio') is None # The search can be a regexp - assert_equal(find_private_section(ds, - 0x11, - re.compile(r'third\Wsectio[nN]')), - 0x1200) + assert find_private_section(ds, 0x11, re.compile(r'third\Wsectio[nN]')) == 0x1200 # No match -> None - assert_equal(find_private_section(ds, - 0x11, - re.compile(r'not third\Wsectio[nN]')), - None) + assert find_private_section(ds, 0x11, re.compile(r'not third\Wsectio[nN]')) is None # If there are gaps in the sequence before the one we want, that is OK ds.add_new((0x11, 0x13), 'LO', b'near section') - assert_equal(find_private_section(ds, 0x11, 'near section'), 0x1300) + assert find_private_section(ds, 0x11, 'near section') == 0x1300 ds.add_new((0x11, 0x15), 'LO', b'far section') - assert_equal(find_private_section(ds, 0x11, 'far section'), 0x1500) + assert find_private_section(ds, 0x11, 'far section') == 0x1500 diff --git a/nibabel/pydicom_compat.py b/nibabel/pydicom_compat.py index beb787f315..9cca2a293d 100644 --- a/nibabel/pydicom_compat.py +++ b/nibabel/pydicom_compat.py @@ -12,13 +12,19 @@ else None; * tag_for_keyword : ``tag_for_keyword`` function if pydicom or dicom module is importable else None; + +A test decorator is available in nibabel.nicom.tests: + * dicom_test : test decorator that skips test if dicom not available. + +A deprecated copy is available here for backward compatibility. """ # Module has (apparently) unused imports; stop flake8 complaining # flake8: noqa import numpy as np +from .deprecated import deprecate_with_version have_dicom = True pydicom = read_file = tag_for_keyword = Sequence = None @@ -50,6 +56,9 @@ tag_for_keyword = pydicom.datadict.tag_for_name -# test decorator that skips test if dicom not available. -dicom_test = np.testing.dec.skipif(not have_dicom, - 'could not import dicom or pydicom') +@deprecate_with_version("dicom_test has been moved to nibabel.nicom.tests", + since="3.1", until="5.0") +def dicom_test(func): + # Import locally to avoid circular dependency + from .nicom.tests import dicom_test + return dicom_test(func) diff --git a/nibabel/tests/test_nifti1.py b/nibabel/tests/test_nifti1.py index d5dff4a4e4..1bb4e5ae2e 100644 --- a/nibabel/tests/test_nifti1.py +++ b/nibabel/tests/test_nifti1.py @@ -49,7 +49,8 @@ header_file = os.path.join(data_path, 'nifti1.hdr') image_file = os.path.join(data_path, 'example4d.nii.gz') -from nibabel.pydicom_compat import pydicom, dicom_test +from ..pydicom_compat import pydicom +from ..nicom.tests import dicom_test # Example transformation matrix From a23c63a24593aca804377e8837e78d9193d03724 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Fri, 7 Feb 2020 00:53:20 -0500 Subject: [PATCH 196/223] TEST: Use vanilla unittest.skip* over pytest --- nibabel/freesurfer/tests/test_io.py | 7 ++-- nibabel/tests/nibabel_data.py | 10 +++--- nibabel/tests/test_dft.py | 13 +++++--- nibabel/tests/test_image_api.py | 9 ++++-- nibabel/tests/test_parrec_data.py | 3 +- nibabel/tests/test_processing.py | 6 ++-- nibabel/tests/test_proxy_api.py | 3 +- nibabel/tests/test_scripts.py | 3 +- nibabel/tests/test_spm99analyze.py | 50 +++++++++-------------------- nibabel/tests/test_viewers.py | 3 +- 10 files changed, 49 insertions(+), 58 deletions(-) diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index 521923057f..e1ec971c65 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -6,10 +6,9 @@ import hashlib import warnings - from ...tmpdirs import InTemporaryDirectory - +import unittest import pytest import numpy as np from numpy.testing import assert_allclose, assert_array_equal @@ -36,8 +35,8 @@ data_path = pjoin(nib_data, 'nitest-freesurfer', DATA_SDIR) have_freesurfer = isdir(data_path) -freesurfer_test = pytest.mark.skipif(not have_freesurfer, - reason='cannot find freesurfer {0} directory'.format(DATA_SDIR)) +freesurfer_test = unittest.skipUnless(have_freesurfer, + 'cannot find freesurfer {0} directory'.format(DATA_SDIR)) def _hash_file_content(fname): hasher = hashlib.md5() diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index e2e5bc9ed3..3c1b58502d 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -4,7 +4,7 @@ from os import environ, listdir from os.path import dirname, realpath, join as pjoin, isdir, exists -import pytest +import unittest def get_nibabel_data(): @@ -39,11 +39,11 @@ def needs_nibabel_data(subdir=None): """ nibabel_data = get_nibabel_data() if nibabel_data == '': - return pytest.mark.skipif(True, reason="Need nibabel-data directory for this test") + return unittest.skip("Need nibabel-data directory for this test") if subdir is None: - return pytest.mark.skipif(False, reason="Don't skip") + return lambda x: x required_path = pjoin(nibabel_data, subdir) # Path should not be empty (as is the case for not-updated submodules) have_files = exists(required_path) and len(listdir(required_path)) > 0 - return pytest.mark.skipif(not have_files, - reason="Need files in {0} for these tests".format(required_path)) \ No newline at end of file + return unittest.skipUnless(have_files, + "Need files in {0} for these tests".format(required_path)) diff --git a/nibabel/tests/test_dft.py b/nibabel/tests/test_dft.py index d50ba4023e..9c3a4f5d85 100644 --- a/nibabel/tests/test_dft.py +++ b/nibabel/tests/test_dft.py @@ -10,6 +10,7 @@ from .. import dft from .. import nifti1 +import unittest import pytest # Shield optional package imports @@ -22,10 +23,12 @@ data_dir = pjoin(dirname(__file__), 'data') -pytestmark = [ - pytest.mark.skipif(os.name == 'nt', reason='FUSE not available for windows, skipping dft tests'), - pytest.mark.skipif(not have_dicom, reason='Need pydicom for dft tests, skipping') -] +def setUpModule(): + if os.name == 'nt': + raise unittest.SkipTest('FUSE not available for windows, skipping dft tests') + if not have_dicom: + raise unittest.SkipTest('Need pydicom for dft tests, skipping') + def test_init(): dft.clear_cache() @@ -76,7 +79,7 @@ def test_storage_instance(): pass -@pytest.mark.skipif(not have_pil, reason='could not import PIL.Image') +@unittest.skipUnless(have_pil, 'could not import PIL.Image') def test_png(): studies = dft.get_studies(data_dir) data = studies[0].series[0].as_png() diff --git a/nibabel/tests/test_image_api.py b/nibabel/tests/test_image_api.py index f5aeb53822..f6245aa594 100644 --- a/nibabel/tests/test_image_api.py +++ b/nibabel/tests/test_image_api.py @@ -41,6 +41,7 @@ from ..spatialimages import SpatialImage from .. import minc1, minc2, parrec, brikhead +import unittest import pytest from numpy.testing import assert_almost_equal, assert_array_equal, assert_warns, assert_allclose @@ -121,7 +122,7 @@ def validate_filenames(self, imaker, params): # Validate the filename, file_map interface if not self.can_save: - pytest.skip() + raise unittest.SkipTest img = imaker() img.set_data_dtype(np.float32) # to avoid rounding in load / save # Make sure the object does not have a file_map @@ -706,8 +707,12 @@ class TestMinc1API(ImageHeaderAPI): example_images = MINC1_EXAMPLE_IMAGES -@pytest.mark.skipif(not have_h5py, reason="Need h5py for Minc2 tests") class TestMinc2API(TestMinc1API): + + def __init__(self): + if not have_h5py: + raise unittest.SkipTest('Need h5py for these tests') + klass = image_maker = Minc2Image loader = minc2.load example_images = MINC2_EXAMPLE_IMAGES diff --git a/nibabel/tests/test_parrec_data.py b/nibabel/tests/test_parrec_data.py index 30295a269a..e626068ca1 100644 --- a/nibabel/tests/test_parrec_data.py +++ b/nibabel/tests/test_parrec_data.py @@ -12,6 +12,7 @@ from .nibabel_data import get_nibabel_data, needs_nibabel_data +import unittest import pytest from numpy.testing import assert_almost_equal @@ -60,7 +61,7 @@ def test_fieldmap(): fieldmap_nii = pjoin(BALLS, 'NIFTI', 'fieldmap.nii.gz') load(fieldmap_par) top_load(fieldmap_nii) - raise pytest.skip('Fieldmap remains puzzling') + raise unittest.SkipTest('Fieldmap remains puzzling') @needs_nibabel_data('parrec_oblique') diff --git a/nibabel/tests/test_processing.py b/nibabel/tests/test_processing.py index dea34b85a2..1dd64c6a5c 100644 --- a/nibabel/tests/test_processing.py +++ b/nibabel/tests/test_processing.py @@ -27,14 +27,14 @@ voxel_sizes) from nibabel.eulerangles import euler2mat -from numpy.testing import (assert_almost_equal, - assert_array_equal) +from numpy.testing import assert_almost_equal, assert_array_equal +import unittest import pytest from nibabel.tests.test_spaces import assert_all_in, get_outspace_params from nibabel.testing import assert_allclose_safely -needs_scipy = pytest.mark.skipif(not have_scipy, reason='These tests need scipy') +needs_scipy = unittest.skipUnless(have_scipy, 'These tests need scipy') DATA_DIR = pjoin(dirname(__file__), 'data') diff --git a/nibabel/tests/test_proxy_api.py b/nibabel/tests/test_proxy_api.py index c74d4fbdb2..f8e25c14cc 100644 --- a/nibabel/tests/test_proxy_api.py +++ b/nibabel/tests/test_proxy_api.py @@ -51,6 +51,7 @@ from ..arrayproxy import ArrayProxy, is_proxy +import unittest import pytest from numpy.testing import assert_almost_equal, assert_array_equal, assert_allclose @@ -428,7 +429,7 @@ def eg_func(): arr_out=arr_out)) def validate_header_isolated(self, pmaker, params): - raise pytest.skip('ECAT header does not support dtype get') + raise unittest.SkipTest('ECAT header does not support dtype get') class TestPARRECAPI(_TestProxyAPI): diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 19dd5f6fd0..c8c87092bf 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -20,6 +20,7 @@ from ..loadsave import load from ..orientations import flip_axis, aff2axcodes, inv_ornt_aff +import unittest import pytest from numpy.testing import assert_almost_equal @@ -120,7 +121,7 @@ def test_nib_ls(args): check_nib_ls_example4d(*args) -@pytest.mark.skipif(not load_small_file(), reason="can't load the small.mnc file") +@unittest.skipUnless(load_small_file(), "Can't load the small.mnc file") @script_test def test_nib_ls_multiple(): # verify that correctly lists/formats for multiple files diff --git a/nibabel/tests/test_spm99analyze.py b/nibabel/tests/test_spm99analyze.py index 977fef3071..3198c43ea7 100644 --- a/nibabel/tests/test_spm99analyze.py +++ b/nibabel/tests/test_spm99analyze.py @@ -13,14 +13,15 @@ from io import BytesIO from numpy.testing import assert_array_equal, assert_array_almost_equal +import unittest import pytest -# Decorator to skip tests requiring save / load if scipy not available for mat -# files from ..optpkg import optional_package _, have_scipy, _ = optional_package('scipy') -scipy_skip = pytest.mark.skipif(not have_scipy, reason='scipy not available') +# Decorator to skip tests requiring save / load if scipy not available for mat +# files +needs_scipy = unittest.skipUnless(have_scipy, 'scipy not available') from ..spm99analyze import (Spm99AnalyzeHeader, Spm99AnalyzeImage, HeaderTypeError) @@ -409,38 +410,17 @@ class TestSpm99AnalyzeImage(test_analyze.TestAnalyzeImage, ImageScalingMixin): image_class = Spm99AnalyzeImage # Decorating the old way, before the team invented @ - test_data_hdr_cache = (scipy_skip( - test_analyze.TestAnalyzeImage.test_data_hdr_cache - )) - - test_header_updating = (scipy_skip( - test_analyze.TestAnalyzeImage.test_header_updating - )) - - test_offset_to_zero = (scipy_skip( - test_analyze.TestAnalyzeImage.test_offset_to_zero - )) - - test_big_offset_exts = (scipy_skip( - test_analyze.TestAnalyzeImage.test_big_offset_exts - )) - - test_header_scaling = scipy_skip( - ImageScalingMixin.test_header_scaling) - - test_int_int_scaling = scipy_skip( - ImageScalingMixin.test_int_int_scaling) - - test_write_scaling = scipy_skip( - ImageScalingMixin.test_write_scaling) - - test_no_scaling = scipy_skip( - ImageScalingMixin.test_no_scaling) - - test_nan2zero_range_ok = scipy_skip( - ImageScalingMixin.test_nan2zero_range_ok) - - @scipy_skip + test_data_hdr_cache = needs_scipy(test_analyze.TestAnalyzeImage.test_data_hdr_cache) + test_header_updating = needs_scipy(test_analyze.TestAnalyzeImage.test_header_updating) + test_offset_to_zero = needs_scipy(test_analyze.TestAnalyzeImage.test_offset_to_zero) + test_big_offset_exts = needs_scipy(test_analyze.TestAnalyzeImage.test_big_offset_exts) + test_header_scaling = needs_scipy(ImageScalingMixin.test_header_scaling) + test_int_int_scaling = needs_scipy(ImageScalingMixin.test_int_int_scaling) + test_write_scaling = needs_scipy(ImageScalingMixin.test_write_scaling) + test_no_scaling = needs_scipy(ImageScalingMixin.test_no_scaling) + test_nan2zero_range_ok = needs_scipy(ImageScalingMixin.test_nan2zero_range_ok) + + @needs_scipy def test_mat_read(self): # Test mat file reading and writing for the SPM analyze types img_klass = self.image_class diff --git a/nibabel/tests/test_viewers.py b/nibabel/tests/test_viewers.py index 1be6e400a2..8bcb5bda06 100644 --- a/nibabel/tests/test_viewers.py +++ b/nibabel/tests/test_viewers.py @@ -16,11 +16,12 @@ from numpy.testing import assert_array_equal, assert_equal +import unittest import pytest # Need at least MPL 1.3 for viewer tests. matplotlib, has_mpl, _ = optional_package('matplotlib', min_version='1.3') -needs_mpl = pytest.mark.skipif(not has_mpl, reason='These tests need matplotlib') +needs_mpl = unittest.skipUnless(has_mpl, 'These tests need matplotlib') if has_mpl: matplotlib.use('Agg') From 2542320e7e528c91d548f42951963b400fb9c6c7 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Fri, 7 Feb 2020 15:20:14 -0500 Subject: [PATCH 197/223] RF: Remove unused pieces of testing_pytest and switch to unittest skip --- nibabel/testing_pytest/__init__.py | 19 +++---------------- 1 file changed, 3 insertions(+), 16 deletions(-) diff --git a/nibabel/testing_pytest/__init__.py b/nibabel/testing_pytest/__init__.py index 71217612ed..52055ebcc3 100644 --- a/nibabel/testing_pytest/__init__.py +++ b/nibabel/testing_pytest/__init__.py @@ -13,17 +13,12 @@ import sys import warnings from pkg_resources import resource_filename -from os.path import dirname, abspath, join as pjoin import unittest import numpy as np -from numpy.testing import assert_array_equal, assert_warns -from numpy.testing import dec -skipif = dec.skipif -slow = dec.slow +from numpy.testing import assert_array_equal -from ..deprecated import deprecate_with_version as _deprecate_with_version from .np_features import memmap_after_ufunc from .helpers import bytesio_filemap, bytesio_round_trip, assert_data_similar @@ -63,7 +58,7 @@ def assert_allclose_safely(a, b, match_nans=True, rtol=1e-5, atol=1e-8): a, b = np.broadcast_arrays(a, b) if match_nans: nans = np.isnan(a) - np.testing.assert_array_equal(nans, np.isnan(b)) + assert_array_equal(nans, np.isnan(b)) to_test = ~nans else: to_test = np.ones(a.shape, dtype=bool) @@ -199,20 +194,12 @@ class suppress_warnings(error_warnings): filter = 'ignore' -@_deprecate_with_version('catch_warn_reset is deprecated; use ' - 'nibabel.testing.clear_and_catch_warnings.', - since='2.1.0', until='3.0.0') -class catch_warn_reset(clear_and_catch_warnings): - pass - - EXTRA_SET = os.environ.get('NIPY_EXTRA_TESTS', '').split(',') def runif_extra_has(test_str): """Decorator checks to see if NIPY_EXTRA_TESTS env var contains test_str""" - return skipif(test_str not in EXTRA_SET, - "Skip {0} tests.".format(test_str)) + return unittest.skipUnless(test_str in EXTRA_SET, "Skip {0} tests.".format(test_str)) def assert_arr_dict_equal(dict1, dict2): From a223c071b59cd00dcf1cdd2044975746b9f8f74b Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Fri, 7 Feb 2020 21:20:23 -0500 Subject: [PATCH 198/223] CI: Only ignore files that use fixtures --- .azure-pipelines/windows.yml | 58 +----------------------------------- .travis.yml | 58 +----------------------------------- 2 files changed, 2 insertions(+), 114 deletions(-) diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index 8de4ed3466..fcdd542223 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -41,73 +41,17 @@ jobs: cd for_testing cp ../.coveragerc . nosetests --with-doctest --with-coverage --cover-package nibabel nibabel ^ - -I test_array_sequence ^ - -I test_tractogram ^ - -I test_api_validators ^ - -I test_arrayproxy ^ - -I test_arraywriters ^ - -I test_batteryrunners ^ - -I test_brikhead ^ - -I test_casting ^ - -I test_cifti2io_axes ^ - -I test_cifti2io_header ^ -I test_data ^ - -I test_deprecated ^ - -I test_deprecator ^ - -I test_dicomwrappers ^ - -I test_dft ^ - -I test_ecat ^ - -I test_ecat_data ^ - -I test_endiancodes ^ -I test_environment ^ -I test_euler ^ - -I test_filebasedimages ^ - -I test_filehandles ^ - -I test_fileholders ^ - -I test_filename_parser ^ - -I test_files_interface ^ - -I test_fileslice ^ - -I test_fileutils ^ - -I test_floating ^ - -I test_funcs ^ -I test_giftiio ^ - -I test_h5py_compat ^ - -I test_image_api ^ - -I test_image_load_save ^ - -I test_image_types ^ - -I test_imageclasses ^ - -I test_imageglobals ^ - -I test_io ^ - -I test_keywordonly ^ - -I test_loadsave ^ - -I test_minc1 ^ - -I test_minc2 ^ - -I test_minc2_data ^ - -I test_mriutils ^ -I test_netcdf ^ - -I test_nibabel_data ^ - -I test_nifti1 ^ - -I test_nifti2 ^ - -I test_openers ^ - -I test_optpkg ^ - -I test_orientations ^ - -I test_parrec ^ - -I test_parrec_data ^ -I test_pkg_info ^ - -I test_processing ^ - -I test_proxy_api ^ -I test_quaternions ^ - -I test_recoder ^ - -I test_remmovalschedule ^ - -I test_round_trip ^ - -I test_rstutils ^ -I test_scaling ^ - -I test_wrapstruct ^ - -I test_io ^ -I test_scripts ^ -I test_spaces ^ - -I test_testing ^ - -I test_wrapstruct + -I test_testing displayName: 'Nose tests' condition: and(succeeded(), eq(variables['CHECK_TYPE'], 'nosetests')) - script: | diff --git a/.travis.yml b/.travis.yml index 711601764b..857867c712 100644 --- a/.travis.yml +++ b/.travis.yml @@ -134,73 +134,17 @@ script: cd for_testing cp ../.coveragerc . nosetests --with-doctest --with-coverage --cover-package nibabel nibabel \ - -I test_array_sequence \ - -I test_tractogram \ - -I test_api_validators \ - -I test_arrayproxy \ - -I test_arraywriters \ - -I test_batteryrunners \ - -I test_brikhead \ - -I test_casting \ - -I test_cifti2io_axes \ - -I test_cifti2io_header \ -I test_data \ - -I test_deprecated \ - -I test_deprecator \ - -I test_dicomwrappers \ - -I test_dft \ - -I test_ecat \ - -I test_ecat_data \ - -I test_endiancodes \ -I test_environment \ -I test_euler \ - -I test_filebasedimages \ - -I test_filehandles \ - -I test_fileholders \ - -I test_filename_parser \ - -I test_files_interface \ - -I test_fileslice \ - -I test_fileutils \ - -I test_floating \ - -I test_funcs \ -I test_giftiio \ - -I test_h5py_compat \ - -I test_image_api \ - -I test_image_load_save \ - -I test_image_types \ - -I test_imageclasses \ - -I test_imageglobals \ - -I test_io \ - -I test_keywordonly \ - -I test_loadsave \ - -I test_minc1 \ - -I test_minc2 \ - -I test_minc2_data \ - -I test_mriutils \ -I test_netcdf \ - -I test_nibabel_data \ - -I test_nifti1 \ - -I test_nifti2 \ - -I test_openers \ - -I test_optpkg \ - -I test_orientations \ - -I test_parrec \ - -I test_parrec_data \ -I test_pkg_info \ - -I test_processing \ - -I test_proxy_api \ -I test_quaternions \ - -I test_recoder \ - -I test_remmovalschedule \ - -I test_round_trip \ - -I test_rstutils \ -I test_scaling \ - -I test_wrapstruct \ - -I test_io \ -I test_scripts \ -I test_spaces \ - -I test_testing \ - -I test_wrapstruct + -I test_testing elif [ "${CHECK_TYPE}" == "test" ]; then # Change into an innocuous directory and find tests from installation mkdir for_testing From b2f40bdcaf5c81e8d89142ca784e4a2f2850f577 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Sat, 8 Feb 2020 22:41:05 -0500 Subject: [PATCH 199/223] TEST: De-indent tests, cleanup style --- nibabel/tests/test_filename_parser.py | 130 +++++++++++--------------- 1 file changed, 53 insertions(+), 77 deletions(-) diff --git a/nibabel/tests/test_filename_parser.py b/nibabel/tests/test_filename_parser.py index 22178a4349..b0abc6d608 100644 --- a/nibabel/tests/test_filename_parser.py +++ b/nibabel/tests/test_filename_parser.py @@ -18,83 +18,59 @@ def test_filenames(): types_exts = (('image', '.img'), ('header', '.hdr')) for t_fname in ('test.img', 'test.hdr', 'test', 'test.'): tfns = types_filenames(t_fname, types_exts) - assert (tfns == - {'image': 'test.img', - 'header': 'test.hdr'}) - # enforcing extensions raises an error for bad extension - with pytest.raises(TypesFilenamesError): - types_filenames('test.funny', types_exts) - # If not enforcing extensions, it does the best job it can, - # assuming the passed filename is for the first type (in this case - # 'image') - tfns = types_filenames('test.funny', types_exts, - enforce_extensions=False) - assert (tfns == - {'header': 'test.hdr', - 'image': 'test.funny'}) - # .gz and .bz2 suffixes to extensions, by default, are removed - # before extension checking etc, and then put back onto every - # returned filename. - tfns = types_filenames('test.img.gz', types_exts) - assert (tfns == - {'header': 'test.hdr.gz', - 'image': 'test.img.gz'}) - tfns = types_filenames('test.img.bz2', types_exts) - assert (tfns == - {'header': 'test.hdr.bz2', - 'image': 'test.img.bz2'}) - # of course, if we don't know about e.g. gz, and enforce_extensions - # is on, we get an errror - with pytest.raises(TypesFilenamesError): - types_filenames('test.img.gz', types_exts, ()) - # if we don't know about .gz extension, and not enforcing, then we - # get something a bit odd - tfns = types_filenames('test.img.gz', types_exts, - trailing_suffixes=(), - enforce_extensions=False) - assert (tfns == - {'header': 'test.img.hdr', - 'image': 'test.img.gz'}) - # the suffixes we remove and replaces can be any suffixes. - tfns = types_filenames('test.img.bzr', types_exts, ('.bzr',)) - assert (tfns == - {'header': 'test.hdr.bzr', - 'image': 'test.img.bzr'}) - # If we specifically pass the remove / replace suffixes, then we - # don't remove / replace the .gz and .bz2, unless they are passed - # specifically. - tfns = types_filenames('test.img.bzr', types_exts, - trailing_suffixes=('.bzr',), - enforce_extensions=False) - assert (tfns == - {'header': 'test.hdr.bzr', - 'image': 'test.img.bzr'}) - # but, just .gz or .bz2 as extension gives an error, if enforcing is on - with pytest.raises(TypesFilenamesError): - types_filenames('test.gz', types_exts) - with pytest.raises(TypesFilenamesError): - types_filenames('test.bz2', types_exts) - # if enforcing is off, it tries to work out what the other files - # should be assuming the passed filename is of the first input type - tfns = types_filenames('test.gz', types_exts, - enforce_extensions=False) - assert (tfns == - {'image': 'test.gz', - 'header': 'test.hdr.gz'}) - # case (in)sensitivity, and effect of uppercase, lowercase - tfns = types_filenames('test.IMG', types_exts) - assert (tfns == - {'image': 'test.IMG', - 'header': 'test.HDR'}) - tfns = types_filenames('test.img', - (('image', '.IMG'), ('header', '.HDR'))) - assert (tfns == - {'header': 'test.hdr', - 'image': 'test.img'}) - tfns = types_filenames('test.IMG.Gz', types_exts) - assert (tfns == - {'image': 'test.IMG.Gz', - 'header': 'test.HDR.Gz'}) + assert tfns == {'image': 'test.img', 'header': 'test.hdr'} + # enforcing extensions raises an error for bad extension + with pytest.raises(TypesFilenamesError): + types_filenames('test.funny', types_exts) + # If not enforcing extensions, it does the best job it can, + # assuming the passed filename is for the first type (in this case + # 'image') + tfns = types_filenames('test.funny', types_exts, enforce_extensions=False) + assert tfns == {'header': 'test.hdr', 'image': 'test.funny'} + # .gz and .bz2 suffixes to extensions, by default, are removed + # before extension checking etc, and then put back onto every + # returned filename. + tfns = types_filenames('test.img.gz', types_exts) + assert tfns == {'header': 'test.hdr.gz', 'image': 'test.img.gz'} + tfns = types_filenames('test.img.bz2', types_exts) + assert tfns == {'header': 'test.hdr.bz2', 'image': 'test.img.bz2'} + # of course, if we don't know about e.g. gz, and enforce_extensions + # is on, we get an errror + with pytest.raises(TypesFilenamesError): + types_filenames('test.img.gz', types_exts, ()) + # if we don't know about .gz extension, and not enforcing, then we + # get something a bit odd + tfns = types_filenames('test.img.gz', types_exts, + trailing_suffixes=(), + enforce_extensions=False) + assert tfns == {'header': 'test.img.hdr', 'image': 'test.img.gz'} + # the suffixes we remove and replaces can be any suffixes. + tfns = types_filenames('test.img.bzr', types_exts, ('.bzr',)) + assert tfns == {'header': 'test.hdr.bzr', 'image': 'test.img.bzr'} + # If we specifically pass the remove / replace suffixes, then we + # don't remove / replace the .gz and .bz2, unless they are passed + # specifically. + tfns = types_filenames('test.img.bzr', types_exts, + trailing_suffixes=('.bzr',), + enforce_extensions=False) + assert tfns == {'header': 'test.hdr.bzr', 'image': 'test.img.bzr'} + # but, just .gz or .bz2 as extension gives an error, if enforcing is on + with pytest.raises(TypesFilenamesError): + types_filenames('test.gz', types_exts) + with pytest.raises(TypesFilenamesError): + types_filenames('test.bz2', types_exts) + # if enforcing is off, it tries to work out what the other files + # should be assuming the passed filename is of the first input type + tfns = types_filenames('test.gz', types_exts, + enforce_extensions=False) + assert tfns == {'image': 'test.gz', 'header': 'test.hdr.gz'} + # case (in)sensitivity, and effect of uppercase, lowercase + tfns = types_filenames('test.IMG', types_exts) + assert tfns == {'image': 'test.IMG', 'header': 'test.HDR'} + tfns = types_filenames('test.img', (('image', '.IMG'), ('header', '.HDR'))) + assert tfns == {'header': 'test.hdr', 'image': 'test.img'} + tfns = types_filenames('test.IMG.Gz', types_exts) + assert tfns == {'image': 'test.IMG.Gz', 'header': 'test.HDR.Gz'} def test_parse_filename(): From 8ed033cf1d7b9f6f63ae83bee8539571fd7dc087 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Sat, 8 Feb 2020 23:07:13 -0500 Subject: [PATCH 200/223] TEST/STY: Cleaner line breaks and alignment for test_fileslice --- nibabel/tests/test_fileslice.py | 346 ++++++++++++-------------------- 1 file changed, 123 insertions(+), 223 deletions(-) diff --git a/nibabel/tests/test_fileslice.py b/nibabel/tests/test_fileslice.py index 07a2627910..21b1224d66 100644 --- a/nibabel/tests/test_fileslice.py +++ b/nibabel/tests/test_fileslice.py @@ -64,46 +64,33 @@ def test_canonical_slicers(): for slice1 in slicers: sliceobj = (slice0, slice1) assert canonical_slicers(sliceobj, shape) == sliceobj - assert (canonical_slicers(sliceobj, shape + (2, 3, 4)) == - sliceobj + (slice(None),) * 3) - assert (canonical_slicers(sliceobj * 3, shape * 3) == - sliceobj * 3) + assert canonical_slicers(sliceobj, shape + (2, 3, 4)) == sliceobj + (slice(None),) * 3 + assert canonical_slicers(sliceobj * 3, shape * 3) == sliceobj * 3 # Check None passes through - assert (canonical_slicers(sliceobj + (None,), shape) == - sliceobj + (None,)) - assert (canonical_slicers((None,) + sliceobj, shape) == - (None,) + sliceobj) + assert canonical_slicers(sliceobj + (None,), shape) == sliceobj + (None,) + assert canonical_slicers((None,) + sliceobj, shape) == (None,) + sliceobj assert (canonical_slicers((None,) + sliceobj + (None,), shape) == - (None,) + sliceobj + (None,)) + (None,) + sliceobj + (None,)) # Check Ellipsis - assert (canonical_slicers((Ellipsis,), shape) == - (slice(None), slice(None))) - assert (canonical_slicers((Ellipsis, None), shape) == - (slice(None), slice(None), None)) - assert (canonical_slicers((Ellipsis, 1), shape) == - (slice(None), 1)) - assert (canonical_slicers((1, Ellipsis), shape) == - (1, slice(None))) + assert canonical_slicers((Ellipsis,), shape) == (slice(None), slice(None)) + assert canonical_slicers((Ellipsis, None), shape) == (slice(None), slice(None), None) + assert canonical_slicers((Ellipsis, 1), shape) == (slice(None), 1) + assert canonical_slicers((1, Ellipsis), shape) == (1, slice(None)) # Ellipsis at end does nothing - assert (canonical_slicers((1, 1, Ellipsis), shape) == - (1, 1)) + assert canonical_slicers((1, 1, Ellipsis), shape) == (1, 1) assert (canonical_slicers((1, Ellipsis, 2), (10, 1, 2, 3, 11)) == - (1, slice(None), slice(None), slice(None), 2)) + (1, slice(None), slice(None), slice(None), 2)) with pytest.raises(ValueError): canonical_slicers((Ellipsis, 1, Ellipsis), (2, 3, 4, 5)) # Check full slices get expanded for slice0 in (slice(10), slice(0, 10), slice(0, 10, 1)): - assert (canonical_slicers((slice0, 1), shape) == - (slice(None), 1)) + assert canonical_slicers((slice0, 1), shape) == (slice(None), 1) for slice0 in (slice(10), slice(0, 10), slice(0, 10, 1)): - assert (canonical_slicers((slice0, 1), shape) == - (slice(None), 1)) - assert (canonical_slicers((1, slice0), shape) == - (1, slice(None))) + assert canonical_slicers((slice0, 1), shape) == (slice(None), 1) + assert canonical_slicers((1, slice0), shape) == (1, slice(None)) # Check ints etc get parsed through to tuples assert canonical_slicers(1, shape) == (1, slice(None)) - assert (canonical_slicers(slice(None), shape) == - (slice(None), slice(None))) + assert canonical_slicers(slice(None), shape) == (slice(None), slice(None)) # Check fancy indexing raises error with pytest.raises(ValueError): canonical_slicers((np.array(1), 1), shape) @@ -205,28 +192,18 @@ def test_fill_slicer(): assert fill_slicer(slice(1, 11, 2), 10) == slice(1, 10, 2) assert fill_slicer(slice(0, 11, 3), 10) == slice(0, 10, 3) assert fill_slicer(slice(1, 11, 3), 10) == slice(1, 10, 3) - assert (fill_slicer(slice(None, None, -1), 10) == - slice(9, None, -1)) - assert (fill_slicer(slice(11, None, -1), 10) == - slice(9, None, -1)) - assert (fill_slicer(slice(None, 1, -1), 10) == - slice(9, 1, -1)) - assert (fill_slicer(slice(None, None, -2), 10) == - slice(9, None, -2)) - assert (fill_slicer(slice(None, None, -3), 10) == - slice(9, None, -3)) - assert (fill_slicer(slice(None, 0, -3), 10) == - slice(9, 0, -3)) + assert fill_slicer(slice(None, None, -1), 10) == slice(9, None, -1) + assert fill_slicer(slice(11, None, -1), 10) == slice(9, None, -1) + assert fill_slicer(slice(None, 1, -1), 10) == slice(9, 1, -1) + assert fill_slicer(slice(None, None, -2), 10) == slice(9, None, -2) + assert fill_slicer(slice(None, None, -3), 10) == slice(9, None, -3) + assert fill_slicer(slice(None, 0, -3), 10) == slice(9, 0, -3) # Start, end are always taken to be relative if negative - assert (fill_slicer(slice(None, -4, -1), 10) == - slice(9, 6, -1)) - assert (fill_slicer(slice(-4, -2, 1), 10) == - slice(6, 8, 1)) + assert fill_slicer(slice(None, -4, -1), 10) == slice(9, 6, -1) + assert fill_slicer(slice(-4, -2, 1), 10) == slice(6, 8, 1) # start after stop - assert (fill_slicer(slice(3, 2, 1), 10) == - slice(3, 2, 1)) - assert (fill_slicer(slice(2, 3, -1), 10) == - slice(2, 3, -1)) + assert fill_slicer(slice(3, 2, 1), 10) == slice(3, 2, 1) + assert fill_slicer(slice(2, 3, -1), 10) == slice(2, 3, -1) def test__positive_slice(): @@ -247,37 +224,21 @@ def test_threshold_heuristic(): assert threshold_heuristic(1, 9, 2, skip_thresh=16) == 'full' assert threshold_heuristic(1, 9, 2, skip_thresh=15) is None # full slice, smallest step size - assert (threshold_heuristic( - slice(0, 9, 1), 9, 2, skip_thresh=2) == - 'full') + assert threshold_heuristic(slice(0, 9, 1), 9, 2, skip_thresh=2) == 'full' # Dropping skip thresh below step size gives None - assert (threshold_heuristic( - slice(0, 9, 1), 9, 2, skip_thresh=1) == - None) + assert threshold_heuristic(slice(0, 9, 1), 9, 2, skip_thresh=1) == None # As does increasing step size - assert (threshold_heuristic( - slice(0, 9, 2), 9, 2, skip_thresh=3) == - None) + assert threshold_heuristic(slice(0, 9, 2), 9, 2, skip_thresh=3) == None # Negative step size same as positive - assert (threshold_heuristic( - slice(9, None, -1), 9, 2, skip_thresh=2) == - 'full') + assert threshold_heuristic(slice(9, None, -1), 9, 2, skip_thresh=2) == 'full' # Add a gap between start and end. Now contiguous because of step size - assert (threshold_heuristic( - slice(2, 9, 1), 9, 2, skip_thresh=2) == - 'contiguous') + assert threshold_heuristic(slice(2, 9, 1), 9, 2, skip_thresh=2) == 'contiguous' # To not-contiguous, even with step size 1 - assert (threshold_heuristic( - slice(2, 9, 1), 9, 2, skip_thresh=1) == - None) + assert threshold_heuristic(slice(2, 9, 1), 9, 2, skip_thresh=1) == None # Back to full when skip covers gap - assert (threshold_heuristic( - slice(2, 9, 1), 9, 2, skip_thresh=4) == - 'full') + assert threshold_heuristic(slice(2, 9, 1), 9, 2, skip_thresh=4) == 'full' # Until it doesn't cover the gap - assert (threshold_heuristic( - slice(2, 9, 1), 9, 2, skip_thresh=3) == - 'contiguous') + assert threshold_heuristic(slice(2, 9, 1), 9, 2, skip_thresh=3) == 'contiguous' # Some dummy heuristics for optimize_slicer @@ -309,233 +270,175 @@ def test_optimize_slicer(): # following tests not affected by all_full or optimization # full - always passes through assert ( - optimize_slicer(slice(None), 10, all_full, 4, heuristic) == + optimize_slicer(slice(None), 10, all_full, is_slowest, 4, heuristic) == (slice(None), slice(None))) # Even if full specified with explicit values assert ( - optimize_slicer(slice(10), 10, all_full, 4, heuristic) == + optimize_slicer(slice(10), 10, all_full, is_slowest, 4, heuristic) == (slice(None), slice(None))) assert ( - optimize_slicer(slice(0, 10), 10, all_full, 4, heuristic) == + optimize_slicer(slice(0, 10), 10, all_full, is_slowest, 4, heuristic) == (slice(None), slice(None))) assert ( - optimize_slicer(slice(0, 10, 1), 10, all_full, 4, heuristic) == + optimize_slicer(slice(0, 10, 1), 10, all_full, is_slowest, 4, heuristic) == (slice(None), slice(None))) # Reversed full is still full, but with reversed post_slice assert ( optimize_slicer( - slice(None, None, -1), 10, all_full, 4, heuristic) == + slice(None, None, -1), 10, all_full, is_slowest, 4, heuristic) == (slice(None), slice(None, None, -1))) # Contiguous is contiguous unless heuristic kicks in, in which case it may # be 'full' - assert ( - optimize_slicer(slice(9), 10, False, False, 4, _always) == - (slice(0, 9, 1), slice(None))) - assert ( - optimize_slicer(slice(9), 10, True, False, 4, _always) == - (slice(None), slice(0, 9, 1))) + assert optimize_slicer(slice(9), 10, False, False, 4, _always) == (slice(0, 9, 1), slice(None)) + assert optimize_slicer(slice(9), 10, True, False, 4, _always) == (slice(None), slice(0, 9, 1)) # Unless this is the slowest dimenion, and all_true is True, in which case # we don't update to full - assert ( - optimize_slicer(slice(9), 10, True, True, 4, _always) == - (slice(0, 9, 1), slice(None))) + assert optimize_slicer(slice(9), 10, True, True, 4, _always) == (slice(0, 9, 1), slice(None)) # Nor if the heuristic won't update - assert ( - optimize_slicer(slice(9), 10, True, False, 4, _never) == - (slice(0, 9, 1), slice(None))) - assert ( - optimize_slicer(slice(1, 10), 10, True, False, 4, _never) == - (slice(1, 10, 1), slice(None))) + assert optimize_slicer(slice(9), 10, True, False, 4, _never) == (slice(0, 9, 1), slice(None)) + assert (optimize_slicer(slice(1, 10), 10, True, False, 4, _never) == + (slice(1, 10, 1), slice(None))) # Reversed contiguous still contiguous - assert ( - optimize_slicer(slice(8, None, -1), 10, False, False, 4, _never) == - (slice(0, 9, 1), slice(None, None, -1))) - assert ( - optimize_slicer(slice(8, None, -1), 10, True, False, 4, _always) == - (slice(None), slice(8, None, -1))) - assert ( - optimize_slicer(slice(8, None, -1), 10, False, False, 4, _never) == - (slice(0, 9, 1), slice(None, None, -1))) - assert ( - optimize_slicer(slice(9, 0, -1), 10, False, False, 4, _never) == - (slice(1, 10, 1), slice(None, None, -1))) + assert (optimize_slicer(slice(8, None, -1), 10, False, False, 4, _never) == + (slice(0, 9, 1), slice(None, None, -1))) + assert (optimize_slicer(slice(8, None, -1), 10, True, False, 4, _always) == + (slice(None), slice(8, None, -1))) + assert (optimize_slicer(slice(8, None, -1), 10, False, False, 4, _never) == + (slice(0, 9, 1), slice(None, None, -1))) + assert (optimize_slicer(slice(9, 0, -1), 10, False, False, 4, _never) == + (slice(1, 10, 1), slice(None, None, -1))) # Non-contiguous - assert ( - optimize_slicer(slice(0, 10, 2), 10, False, False, 4, _never) == - (slice(0, 10, 2), slice(None))) + assert (optimize_slicer(slice(0, 10, 2), 10, False, False, 4, _never) == + (slice(0, 10, 2), slice(None))) # all_full triggers optimization, but optimization does nothing - assert ( - optimize_slicer(slice(0, 10, 2), 10, True, False, 4, _never) == - (slice(0, 10, 2), slice(None))) + assert (optimize_slicer(slice(0, 10, 2), 10, True, False, 4, _never) == + (slice(0, 10, 2), slice(None))) # all_full triggers optimization, optimization does something - assert ( - optimize_slicer(slice(0, 10, 2), 10, True, False, 4, _always) == - (slice(None), slice(0, 10, 2))) + assert (optimize_slicer(slice(0, 10, 2), 10, True, False, 4, _always) == + (slice(None), slice(0, 10, 2))) # all_full disables optimization, optimization does something - assert ( - optimize_slicer(slice(0, 10, 2), 10, False, False, 4, _always) == - (slice(0, 10, 2), slice(None))) + assert (optimize_slicer(slice(0, 10, 2), 10, False, False, 4, _always) == + (slice(0, 10, 2), slice(None))) # Non contiguous, reversed - assert ( - optimize_slicer(slice(10, None, -2), 10, False, False, 4, _never) == - (slice(1, 10, 2), slice(None, None, -1))) - assert ( - optimize_slicer(slice(10, None, -2), 10, True, False, 4, _always) == - (slice(None), slice(9, None, -2))) + assert (optimize_slicer(slice(10, None, -2), 10, False, False, 4, _never) == + (slice(1, 10, 2), slice(None, None, -1))) + assert (optimize_slicer(slice(10, None, -2), 10, True, False, 4, _always) == + (slice(None), slice(9, None, -2))) # Short non-contiguous - assert ( - optimize_slicer(slice(2, 8, 2), 10, False, False, 4, _never) == - (slice(2, 8, 2), slice(None))) + assert (optimize_slicer(slice(2, 8, 2), 10, False, False, 4, _never) == + (slice(2, 8, 2), slice(None))) # with partial read - assert ( - optimize_slicer(slice(2, 8, 2), 10, True, False, 4, _partial) == - (slice(2, 8, 1), slice(None, None, 2))) + assert (optimize_slicer(slice(2, 8, 2), 10, True, False, 4, _partial) == + (slice(2, 8, 1), slice(None, None, 2))) # If this is the slowest changing dimension, heuristic can upgrade None to # contiguous, but not (None, contiguous) to full # we've done this one already - assert optimize_slicer(slice(0, 10, 2), 10, True, False, 4, _always) \ - == (slice(None), slice(0, 10, 2)) + assert (optimize_slicer(slice(0, 10, 2), 10, True, False, 4, _always) == + (slice(None), slice(0, 10, 2))) # if slowest, just upgrade to contiguous - assert ( - optimize_slicer(slice(0, 10, 2), 10, True, True, 4, _always) == - (slice(0, 10, 1), slice(None, None, 2))) + assert (optimize_slicer(slice(0, 10, 2), 10, True, True, 4, _always) == + (slice(0, 10, 1), slice(None, None, 2))) # contiguous does not upgrade to full - assert ( - optimize_slicer(slice(9), 10, True, True, 4, _always) == - (slice(0, 9, 1), slice(None))) + assert optimize_slicer(slice(9), 10, True, True, 4, _always) == (slice(0, 9, 1), slice(None)) # integer - assert ( - optimize_slicer(0, 10, True, False, 4, _never) == - (0, 'dropped')) + assert optimize_slicer(0, 10, True, False, 4, _never) == (0, 'dropped') # can be negative - assert ( - optimize_slicer(-1, 10, True, False, 4, _never) == - (9, 'dropped')) + assert optimize_slicer(-1, 10, True, False, 4, _never) == (9, 'dropped') # or float - assert ( - optimize_slicer(0.9, 10, True, False, 4, _never) == - (0, 'dropped')) + assert optimize_slicer(0.9, 10, True, False, 4, _never) == (0, 'dropped') # should never get 'contiguous' with pytest.raises(ValueError): optimize_slicer(0, 10, True, False, 4, _partial) # full can be forced with heuristic - assert ( - optimize_slicer(0, 10, True, False, 4, _always) == - (slice(None), 0)) + assert optimize_slicer(0, 10, True, False, 4, _always) == (slice(None), 0) # but disabled for slowest changing dimension - assert ( - optimize_slicer(0, 10, True, True, 4, _always) == - (0, 'dropped')) + assert optimize_slicer(0, 10, True, True, 4, _always) == (0, 'dropped') def test_optimize_read_slicers(): # Test function to optimize read slicers - assert (optimize_read_slicers((1,), (10,), 4, _never) == - ((1,), ())) + assert optimize_read_slicers((1,), (10,), 4, _never) == ((1,), ()) assert (optimize_read_slicers((slice(None),), (10,), 4, _never) == - ((slice(None),), (slice(None),))) + ((slice(None),), (slice(None),))) assert (optimize_read_slicers((slice(9),), (10,), 4, _never) == - ((slice(0, 9, 1),), (slice(None),))) + ((slice(0, 9, 1),), (slice(None),))) # optimize cannot update a continuous to a full if last assert (optimize_read_slicers((slice(9),), (10,), 4, _always) == - ((slice(0, 9, 1),), (slice(None),))) + ((slice(0, 9, 1),), (slice(None),))) # optimize can update non-contiguous to continuous even if last # not optimizing assert (optimize_read_slicers((slice(0, 9, 2),), (10,), 4, _never) == - ((slice(0, 9, 2),), (slice(None),))) + ((slice(0, 9, 2),), (slice(None),))) # optimizing assert (optimize_read_slicers((slice(0, 9, 2),), (10,), 4, _always) == - ((slice(0, 9, 1),), (slice(None, None, 2),))) + ((slice(0, 9, 1),), (slice(None, None, 2),))) # Optimize does nothing for integer when last - assert (optimize_read_slicers((1,), (10,), 4, _always) == - ((1,), ())) + assert optimize_read_slicers((1,), (10,), 4, _always) == ((1,), ()) # 2D - assert (optimize_read_slicers( - (slice(None), slice(None)), (10, 6), 4, _never) == - ((slice(None), slice(None)), (slice(None), slice(None)))) + assert (optimize_read_slicers((slice(None), slice(None)), (10, 6), 4, _never) == + ((slice(None), slice(None)), (slice(None), slice(None)))) assert (optimize_read_slicers((slice(None), 1), (10, 6), 4, _never) == - ((slice(None), 1), (slice(None),))) + ((slice(None), 1), (slice(None),))) assert (optimize_read_slicers((1, slice(None)), (10, 6), 4, _never) == - ((1, slice(None)), (slice(None),))) + ((1, slice(None)), (slice(None),))) # Not optimizing a partial slice - assert (optimize_read_slicers( - (slice(9), slice(None)), (10, 6), 4, _never) == - ((slice(0, 9, 1), slice(None)), (slice(None), slice(None)))) + assert (optimize_read_slicers((slice(9), slice(None)), (10, 6), 4, _never) == + ((slice(0, 9, 1), slice(None)), (slice(None), slice(None)))) # Optimizing a partial slice - assert (optimize_read_slicers( - (slice(9), slice(None)), (10, 6), 4, _always) == - ((slice(None), slice(None)), (slice(0, 9, 1), slice(None)))) + assert (optimize_read_slicers((slice(9), slice(None)), (10, 6), 4, _always) == + ((slice(None), slice(None)), (slice(0, 9, 1), slice(None)))) # Optimize cannot update a continuous to a full if last - assert (optimize_read_slicers( - (slice(None), slice(5)), (10, 6), 4, _always) == - ((slice(None), slice(0, 5, 1)), (slice(None), slice(None)))) + assert (optimize_read_slicers((slice(None), slice(5)), (10, 6), 4, _always) == + ((slice(None), slice(0, 5, 1)), (slice(None), slice(None)))) # optimize can update non-contiguous to full if not last # not optimizing - assert (optimize_read_slicers( - (slice(0, 9, 3), slice(None)), (10, 6), 4, _never) == - ((slice(0, 9, 3), slice(None)), (slice(None), slice(None)))) + assert (optimize_read_slicers((slice(0, 9, 3), slice(None)), (10, 6), 4, _never) == + ((slice(0, 9, 3), slice(None)), (slice(None), slice(None)))) # optimizing full - assert (optimize_read_slicers( - (slice(0, 9, 3), slice(None)), (10, 6), 4, _always) == - ((slice(None), slice(None)), (slice(0, 9, 3), slice(None)))) + assert (optimize_read_slicers((slice(0, 9, 3), slice(None)), (10, 6), 4, _always) == + ((slice(None), slice(None)), (slice(0, 9, 3), slice(None)))) # optimizing partial - assert (optimize_read_slicers( - (slice(0, 9, 3), slice(None)), (10, 6), 4, _partial) == - ((slice(0, 9, 1), slice(None)), (slice(None, None, 3), slice(None)))) + assert (optimize_read_slicers((slice(0, 9, 3), slice(None)), (10, 6), 4, _partial) == + ((slice(0, 9, 1), slice(None)), (slice(None, None, 3), slice(None)))) # optimize can update non-contiguous to continuous even if last # not optimizing - assert (optimize_read_slicers( - (slice(None), slice(0, 5, 2)), (10, 6), 4, _never) == - ((slice(None), slice(0, 5, 2)), (slice(None), slice(None)))) + assert (optimize_read_slicers((slice(None), slice(0, 5, 2)), (10, 6), 4, _never) == + ((slice(None), slice(0, 5, 2)), (slice(None), slice(None)))) # optimizing - assert (optimize_read_slicers( - (slice(None), slice(0, 5, 2),), (10, 6), 4, _always) == - ((slice(None), slice(0, 5, 1)), (slice(None), slice(None, None, 2)))) + assert (optimize_read_slicers((slice(None), slice(0, 5, 2),), (10, 6), 4, _always) == + ((slice(None), slice(0, 5, 1)), (slice(None), slice(None, None, 2)))) # Optimize does nothing for integer when last - assert (optimize_read_slicers( - (slice(None), 1), (10, 6), 4, _always) == - ((slice(None), 1), (slice(None),))) + assert (optimize_read_slicers((slice(None), 1), (10, 6), 4, _always) == + ((slice(None), 1), (slice(None),))) # Check gap threshold with 3D _depends0 = partial(threshold_heuristic, skip_thresh=10 * 4 - 1) _depends1 = partial(threshold_heuristic, skip_thresh=10 * 4) assert (optimize_read_slicers( (slice(9), slice(None), slice(None)), (10, 6, 2), 4, _depends0) == - ((slice(None), slice(None), slice(None)), - (slice(0, 9, 1), slice(None), slice(None)))) + ((slice(None), slice(None), slice(None)), (slice(0, 9, 1), slice(None), slice(None)))) assert (optimize_read_slicers( (slice(None), slice(5), slice(None)), (10, 6, 2), 4, _depends0) == - ((slice(None), slice(0, 5, 1), slice(None)), - (slice(None), slice(None), slice(None)))) + ((slice(None), slice(0, 5, 1), slice(None)), (slice(None), slice(None), slice(None)))) assert (optimize_read_slicers( (slice(None), slice(5), slice(None)), (10, 6, 2), 4, _depends1) == - ((slice(None), slice(None), slice(None)), - (slice(None), slice(0, 5, 1), slice(None)))) + ((slice(None), slice(None), slice(None)), (slice(None), slice(0, 5, 1), slice(None)))) # Check longs as integer slices sn = slice(None) - assert (optimize_read_slicers( - (1, 2, 3), (2, 3, 4), 4, _always) == - ((sn, sn, 3), (1, 2))) + assert optimize_read_slicers((1, 2, 3), (2, 3, 4), 4, _always) == ((sn, sn, 3), (1, 2)) def test_slicers2segments(): # Test function to construct segments from slice objects - assert (slicers2segments((0,), (10,), 7, 4) == - [[7, 4]]) - assert (slicers2segments((0, 1), (10, 6), 7, 4) == - [[7 + 10 * 4, 4]]) - assert (slicers2segments((0, 1, 2), (10, 6, 4), 7, 4) == - [[7 + 10 * 4 + 10 * 6 * 2 * 4, 4]]) - assert (slicers2segments((slice(None),), (10,), 7, 4) == - [[7, 10 * 4]]) + assert slicers2segments((0,), (10,), 7, 4) == [[7, 4]] + assert slicers2segments((0, 1), (10, 6), 7, 4) == [[7 + 10 * 4, 4]] + assert slicers2segments((0, 1, 2), (10, 6, 4), 7, 4) == [[7 + 10 * 4 + 10 * 6 * 2 * 4, 4]] + assert slicers2segments((slice(None),), (10,), 7, 4) == [[7, 10 * 4]] assert (slicers2segments((0, slice(None)), (10, 6), 7, 4) == - [[7 + 10 * 4 * i, 4] for i in range(6)]) - assert (slicers2segments((slice(None), 0), (10, 6), 7, 4) == - [[7, 10 * 4]]) - assert (slicers2segments((slice(None), slice(None)), (10, 6), 7, 4) == - [[7, 10 * 6 * 4]]) - assert (slicers2segments( - (slice(None), slice(None), 2), (10, 6, 4), 7, 4) == - [[7 + 10 * 6 * 2 * 4, 10 * 6 * 4]]) + [[7 + 10 * 4 * i, 4] for i in range(6)]) + assert slicers2segments((slice(None), 0), (10, 6), 7, 4) == [[7, 10 * 4]] + assert slicers2segments((slice(None), slice(None)), (10, 6), 7, 4) == [[7, 10 * 6 * 4]] + assert (slicers2segments((slice(None), slice(None), 2), (10, 6, 4), 7, 4) == + [[7 + 10 * 6 * 2 * 4, 10 * 6 * 4]]) def test_calc_slicedefs(): @@ -623,8 +526,7 @@ def test_predict_shape(): for i in range(n_dim): slicers_list.append(_slices_for_len(shape[i])) for sliceobj in product(*slicers_list): - assert (predict_shape(sliceobj, shape) == - arr[sliceobj].shape) + assert predict_shape(sliceobj, shape) == arr[sliceobj].shape # Try some Nones and ellipses assert predict_shape((Ellipsis,), (2, 3)) == (2, 3) assert predict_shape((Ellipsis, 1), (2, 3)) == (2,) @@ -743,10 +645,8 @@ def runtest(): assert numpassed[0] == len(threads) -def _check_slicer(sliceobj, arr, fobj, offset, order, - heuristic=threshold_heuristic): - new_slice = fileslice(fobj, sliceobj, arr.shape, arr.dtype, offset, order, - heuristic) +def _check_slicer(sliceobj, arr, fobj, offset, order, heuristic=threshold_heuristic): + new_slice = fileslice(fobj, sliceobj, arr.shape, arr.dtype, offset, order, heuristic) assert_array_equal(arr[sliceobj], new_slice) From 6be3e94dc488005dc3010f0b34354a144e260fce Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Sun, 9 Feb 2020 16:17:26 -0500 Subject: [PATCH 201/223] TEST/STY: Alignment in fileutils, floating tests --- nibabel/tests/test_fileutils.py | 6 ++---- nibabel/tests/test_floating.py | 13 ++++++------- 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/nibabel/tests/test_fileutils.py b/nibabel/tests/test_fileutils.py index edc8384d4d..ffd7d91b6a 100644 --- a/nibabel/tests/test_fileutils.py +++ b/nibabel/tests/test_fileutils.py @@ -36,8 +36,7 @@ def test_read_zt_byte_strings(): # manually rewind fread.seek(0) # test readout of two strings - assert (read_zt_byte_strings(fread, 2) == - [b'test.fmr', b'test.prt']) + assert read_zt_byte_strings(fread, 2) == [b'test.fmr', b'test.prt'] assert fread.tell() == 18 # test readout of more strings than present fread.seek(0) @@ -48,6 +47,5 @@ def test_read_zt_byte_strings(): read_zt_byte_strings(fread, 2) # Try with a small bufsize fread.seek(0) - assert (read_zt_byte_strings(fread, 2, 4) == - [b'test.fmr', b'test.prt']) + assert read_zt_byte_strings(fread, 2, 4) == [b'test.fmr', b'test.prt'] fread.close() diff --git a/nibabel/tests/test_floating.py b/nibabel/tests/test_floating.py index 94d3a396b2..da5f2b6e2b 100644 --- a/nibabel/tests/test_floating.py +++ b/nibabel/tests/test_floating.py @@ -34,9 +34,9 @@ def test_type_info(): info = np.iinfo(dtt) infod = type_info(dtt) assert dict(min=info.min, max=info.max, - nexp=None, nmant=None, - minexp=None, maxexp=None, - width=np.dtype(dtt).itemsize) == infod + nexp=None, nmant=None, + minexp=None, maxexp=None, + width=np.dtype(dtt).itemsize) == infod assert infod['min'].dtype.type == dtt assert infod['max'].dtype.type == dtt for dtt in IEEE_floats + [np.complex64, np.complex64]: @@ -286,7 +286,6 @@ def test_usable_binary128(): yes = have_binary128() with np.errstate(over='ignore'): exp_test = np.longdouble(2) ** 16383 - assert (yes == - (exp_test.dtype.itemsize == 16 and - np.isfinite(exp_test) and - _check_nmant(np.longdouble, 112))) + assert yes == (exp_test.dtype.itemsize == 16 and + np.isfinite(exp_test) and + _check_nmant(np.longdouble, 112)) From 84df0426796f8d796d0f0d19d0476473d78f8cb3 Mon Sep 17 00:00:00 2001 From: Guidotti Roberto Date: Mon, 10 Feb 2020 14:43:59 +0200 Subject: [PATCH 202/223] TEST: cmdline module to pytest --- nibabel/cmdline/tests/test_parrec2nii.py | 5 +- nibabel/cmdline/tests/test_utils.py | 61 ++++++++++++------------ 2 files changed, 33 insertions(+), 33 deletions(-) diff --git a/nibabel/cmdline/tests/test_parrec2nii.py b/nibabel/cmdline/tests/test_parrec2nii.py index 9fb556e34d..c41679d84d 100644 --- a/nibabel/cmdline/tests/test_parrec2nii.py +++ b/nibabel/cmdline/tests/test_parrec2nii.py @@ -9,7 +9,6 @@ from nibabel.cmdline import parrec2nii from unittest.mock import Mock, MagicMock, patch -from nose.tools import assert_true from numpy.testing import (assert_almost_equal, assert_array_equal) from nibabel.tests.test_parrec import EG_PAR, VARY_PAR @@ -89,8 +88,8 @@ def test_parrec2nii_save_load_qform_code(*args): for fname in [EG_PAR, VARY_PAR]: parrec2nii.proc_file(fname, opts) outfname = join(pth, basename(fname)).replace('.PAR', '.nii') - assert_true(isfile(outfname)) + assert isfile(outfname) img = nibabel.load(outfname) assert_almost_equal(img.affine, PAR_AFFINE, 4) - assert_array_equal(img.header['qform_code'], 1) + assert img.header['qform_code'] == 1 assert_array_equal(img.header['sform_code'], 1) diff --git a/nibabel/cmdline/tests/test_utils.py b/nibabel/cmdline/tests/test_utils.py index 199eea5d41..eb864c62c0 100644 --- a/nibabel/cmdline/tests/test_utils.py +++ b/nibabel/cmdline/tests/test_utils.py @@ -5,9 +5,10 @@ Test running scripts """ -from nose.tools import assert_equal from numpy.testing import assert_raises +import pytest + import nibabel as nib import numpy as np from nibabel.cmdline.utils import * @@ -19,18 +20,18 @@ def test_table2string(): - assert_equal(table2string([["A", "B", "C", "D"], ["E", "F", "G", "H"]]), "A B C D\nE F G H\n") - assert_equal(table2string([["Let's", "Make", "Tests", "And"], ["Have", "Lots", "Of", "Fun"], - ["With", "Python", "Guys", "!"]]), "Let's Make Tests And\n Have Lots Of Fun"+ - "\n With Python Guys !\n") + assert table2string([["A", "B", "C", "D"], ["E", "F", "G", "H"]]) == "A B C D\nE F G H\n" + assert table2string([["Let's", "Make", "Tests", "And"], ["Have", "Lots", "Of", "Fun"], + ["With", "Python", "Guys", "!"]]) == "Let's Make Tests And\n Have Lots Of Fun"+ \ + "\n With Python Guys !\n" def test_ap(): - assert_equal(ap([1, 2], "%2d"), " 1, 2") - assert_equal(ap([1, 2], "%3d"), " 1, 2") - assert_equal(ap([1, 2], "%-2d"), "1 , 2 ") - assert_equal(ap([1, 2], "%d", "+"), "1+2") - assert_equal(ap([1, 2, 3], "%d", "-"), "1-2-3") + assert ap([1, 2], "%2d") == " 1, 2" + assert ap([1, 2], "%3d") == " 1, 2" + assert ap([1, 2], "%-2d") == "1 , 2 " + assert ap([1, 2], "%d", "+") == "1+2" + assert ap([1, 2, 3], "%d", "-") == "1-2-3" def test_safe_get(): @@ -44,8 +45,8 @@ def get_test(self): test = TestObject() test.test = 2 - assert_equal(safe_get(test, "test"), 2) - assert_equal(safe_get(test, "failtest"), "-") + assert safe_get(test, "test") == 2 + assert safe_get(test, "failtest") == "-" def test_get_headers_diff(): @@ -107,14 +108,14 @@ def test_display_diff(): " " \ "\n" - assert_equal(display_diff(bogus_names, dict_values), expected_output) + assert display_diff(bogus_names, dict_values) == expected_output def test_get_data_diff(): # testing for identical files specifically as md5 may vary by computer test_names = [pjoin(data_path, f) for f in ('standard.nii.gz', 'standard.nii.gz')] - assert_equal(get_data_hash_diff(test_names), []) + assert get_data_hash_diff(test_names) == [] # testing the maximum relative and absolute differences' different use cases test_array = np.arange(16).reshape(4, 4) @@ -124,37 +125,37 @@ def test_get_data_diff(): test_array_5 = np.arange(64).reshape(8, 8) # same shape, 2 files - assert_equal(get_data_diff([test_array, test_array_2]), - OrderedDict([('DATA(diff 1:)', [None, OrderedDict([('abs', 1), ('rel', 2.0)])])])) + assert get_data_diff([test_array, test_array_2]) == \ + OrderedDict([('DATA(diff 1:)', [None, OrderedDict([('abs', 1), ('rel', 2.0)])])]) # same shape, 3 files - assert_equal(get_data_diff([test_array, test_array_2, test_array_3]), + assert get_data_diff([test_array, test_array_2, test_array_3]) == \ OrderedDict([('DATA(diff 1:)', [None, OrderedDict([('abs', 1), ('rel', 2.0)]), OrderedDict([('abs', 2), ('rel', 2.0)])]), ('DATA(diff 2:)', [None, None, - OrderedDict([('abs', 1), ('rel', 0.66666666666666663)])])])) + OrderedDict([('abs', 1), ('rel', 0.66666666666666663)])])]) # same shape, 2 files, modified maximum abs/rel - assert_equal(get_data_diff([test_array, test_array_2], max_abs=2, max_rel=2), OrderedDict()) + assert get_data_diff([test_array, test_array_2], max_abs=2, max_rel=2) == OrderedDict() # different shape, 2 files - assert_equal(get_data_diff([test_array_2, test_array_4]), - OrderedDict([('DATA(diff 1:)', [None, {'CMP': 'incompat'}])])) + assert get_data_diff([test_array_2, test_array_4]) == \ + OrderedDict([('DATA(diff 1:)', [None, {'CMP': 'incompat'}])]) # different shape, 3 files - assert_equal(get_data_diff([test_array_4, test_array_5, test_array_2]), + assert get_data_diff([test_array_4, test_array_5, test_array_2]) == \ OrderedDict([('DATA(diff 1:)', [None, {'CMP': 'incompat'}, {'CMP': 'incompat'}]), - ('DATA(diff 2:)', [None, None, {'CMP': 'incompat'}])])) + ('DATA(diff 2:)', [None, None, {'CMP': 'incompat'}])]) test_return = get_data_diff([test_array, test_array_2], dtype=np.float32) - assert_equal(type(test_return['DATA(diff 1:)'][1]['abs']), np.float32) - assert_equal(type(test_return['DATA(diff 1:)'][1]['rel']), np.float32) + assert type(test_return['DATA(diff 1:)'][1]['abs']) is np.float32 + assert type(test_return['DATA(diff 1:)'][1]['rel']) is np.float32 test_return_2 = get_data_diff([test_array, test_array_2, test_array_3]) - assert_equal(type(test_return_2['DATA(diff 1:)'][1]['abs']), np.float64) - assert_equal(type(test_return_2['DATA(diff 1:)'][1]['rel']), np.float64) - assert_equal(type(test_return_2['DATA(diff 2:)'][2]['abs']), np.float64) - assert_equal(type(test_return_2['DATA(diff 2:)'][2]['rel']), np.float64) + assert type(test_return_2['DATA(diff 1:)'][1]['abs']) is np.float64 + assert type(test_return_2['DATA(diff 1:)'][1]['rel']) is np.float64 + assert type(test_return_2['DATA(diff 2:)'][2]['abs']) is np.float64 + assert type(test_return_2['DATA(diff 2:)'][2]['rel']) is np.float64 def test_main(): @@ -201,4 +202,4 @@ def test_main(): test_names_2 = [pjoin(data_path, f) for f in ('standard.nii.gz', 'standard.nii.gz')] with assert_raises(SystemExit): - assert_equal(main(test_names_2, StringIO()), "These files are identical.") + assert main(test_names_2, StringIO()) == "These files are identical." From 103db6ba2caeb9232d987d8974d309619e3a7fbb Mon Sep 17 00:00:00 2001 From: Guidotti Roberto Date: Mon, 10 Feb 2020 14:44:27 +0200 Subject: [PATCH 203/223] TEST: cifti2 tests to pytest --- nibabel/cifti2/tests/test_axes.py | 110 +++--- nibabel/cifti2/tests/test_cifti2.py | 371 +++++++++++-------- nibabel/cifti2/tests/test_cifti2io_header.py | 189 +++++----- nibabel/cifti2/tests/test_new_cifti2.py | 182 +++++---- 4 files changed, 454 insertions(+), 398 deletions(-) diff --git a/nibabel/cifti2/tests/test_axes.py b/nibabel/cifti2/tests/test_axes.py index 56457187a2..3f6cb3a1a4 100644 --- a/nibabel/cifti2/tests/test_axes.py +++ b/nibabel/cifti2/tests/test_axes.py @@ -1,5 +1,5 @@ import numpy as np -from nose.tools import assert_raises +import pytest from .test_cifti2io_axes import check_rewrite import nibabel.cifti2.cifti2_axes as axes from copy import deepcopy @@ -157,18 +157,18 @@ def test_brain_models(): # break brain model bmt.affine = np.eye(4) - with assert_raises(ValueError): + with pytest.raises(ValueError): bmt.affine = np.eye(3) - with assert_raises(ValueError): + with pytest.raises(ValueError): bmt.affine = np.eye(4).flatten() bmt.volume_shape = (5, 3, 1) - with assert_raises(ValueError): + with pytest.raises(ValueError): bmt.volume_shape = (5., 3, 1) - with assert_raises(ValueError): + with pytest.raises(ValueError): bmt.volume_shape = (5, 3, 1, 4) - with assert_raises(IndexError): + with pytest.raises(IndexError): bmt['thalamus_left'] # Test the constructor @@ -176,22 +176,22 @@ def test_brain_models(): assert np.all(bm_vox.name == ['CIFTI_STRUCTURE_THALAMUS_LEFT'] * 5) assert np.array_equal(bm_vox.vertex, np.full(5, -1)) assert np.array_equal(bm_vox.voxel, np.full((5, 3), 1)) - with assert_raises(ValueError): + with pytest.raises(ValueError): # no volume shape axes.BrainModelAxis('thalamus_left', voxel=np.ones((5, 3), dtype=int), affine=np.eye(4)) - with assert_raises(ValueError): + with pytest.raises(ValueError): # no affine axes.BrainModelAxis('thalamus_left', voxel=np.ones((5, 3), dtype=int), volume_shape=(2, 3, 4)) - with assert_raises(ValueError): + with pytest.raises(ValueError): # incorrect name axes.BrainModelAxis('random_name', voxel=np.ones((5, 3), dtype=int), affine=np.eye(4), volume_shape=(2, 3, 4)) - with assert_raises(ValueError): + with pytest.raises(ValueError): # negative voxel indices axes.BrainModelAxis('thalamus_left', voxel=-np.ones((5, 3), dtype=int), affine=np.eye(4), volume_shape=(2, 3, 4)) - with assert_raises(ValueError): + with pytest.raises(ValueError): # no voxels or vertices axes.BrainModelAxis('thalamus_left', affine=np.eye(4), volume_shape=(2, 3, 4)) - with assert_raises(ValueError): + with pytest.raises(ValueError): # incorrect voxel shape axes.BrainModelAxis('thalamus_left', voxel=np.ones((5, 2), dtype=int), affine=np.eye(4), volume_shape=(2, 3, 4)) @@ -199,18 +199,18 @@ def test_brain_models(): assert np.array_equal(bm_vertex.name, ['CIFTI_STRUCTURE_CORTEX_LEFT'] * 5) assert np.array_equal(bm_vertex.vertex, np.full(5, 1)) assert np.array_equal(bm_vertex.voxel, np.full((5, 3), -1)) - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.BrainModelAxis('cortex_left', vertex=np.ones(5, dtype=int)) - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.BrainModelAxis('cortex_left', vertex=np.ones(5, dtype=int), nvertices={'cortex_right': 20}) - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.BrainModelAxis('cortex_left', vertex=-np.ones(5, dtype=int), nvertices={'cortex_left': 20}) # test from_mask errors - with assert_raises(ValueError): + with pytest.raises(ValueError): # affine should be 4x4 matrix axes.BrainModelAxis.from_mask(np.arange(5) > 2, affine=np.ones(5)) - with assert_raises(ValueError): + with pytest.raises(ValueError): # only 1D or 3D masks accepted axes.BrainModelAxis.from_mask(np.ones((5, 3))) @@ -226,27 +226,27 @@ def test_brain_models(): assert bm_added.volume_shape == bm_vox.volume_shape axes.ParcelsAxis.from_brain_models([('a', bm_vox), ('b', bm_vox)]) - with assert_raises(Exception): + with pytest.raises(Exception): bm_vox + get_label() bm_other_shape = axes.BrainModelAxis('thalamus_left', voxel=np.ones((5, 3), dtype=int), affine=np.eye(4), volume_shape=(4, 3, 4)) - with assert_raises(ValueError): + with pytest.raises(ValueError): bm_vox + bm_other_shape - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.ParcelsAxis.from_brain_models([('a', bm_vox), ('b', bm_other_shape)]) bm_other_affine = axes.BrainModelAxis('thalamus_left', voxel=np.ones((5, 3), dtype=int), affine=np.eye(4) * 2, volume_shape=(2, 3, 4)) - with assert_raises(ValueError): + with pytest.raises(ValueError): bm_vox + bm_other_affine - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.ParcelsAxis.from_brain_models([('a', bm_vox), ('b', bm_other_affine)]) bm_vertex = axes.BrainModelAxis('cortex_left', vertex=np.ones(5, dtype=int), nvertices={'cortex_left': 20}) bm_other_number = axes.BrainModelAxis('cortex_left', vertex=np.ones(5, dtype=int), nvertices={'cortex_left': 30}) - with assert_raises(ValueError): + with pytest.raises(ValueError): bm_vertex + bm_other_number - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.ParcelsAxis.from_brain_models([('a', bm_vertex), ('b', bm_other_number)]) # test equalities @@ -336,29 +336,29 @@ def test_parcels(): assert len(prc2[3:]['mixed'][1]) == 1 assert prc2[3:]['mixed'][1]['CIFTI_STRUCTURE_CORTEX_LEFT'].shape == (3, ) - with assert_raises(IndexError): + with pytest.raises(IndexError): prc['non_existent'] prc['surface'] - with assert_raises(IndexError): + with pytest.raises(IndexError): # parcel exists twice prc2['surface'] # break parcels prc.affine = np.eye(4) - with assert_raises(ValueError): + with pytest.raises(ValueError): prc.affine = np.eye(3) - with assert_raises(ValueError): + with pytest.raises(ValueError): prc.affine = np.eye(4).flatten() prc.volume_shape = (5, 3, 1) - with assert_raises(ValueError): + with pytest.raises(ValueError): prc.volume_shape = (5., 3, 1) - with assert_raises(ValueError): + with pytest.raises(ValueError): prc.volume_shape = (5, 3, 1, 4) # break adding of parcels - with assert_raises(Exception): + with pytest.raises(Exception): prc + get_label() prc = get_parcels() @@ -367,12 +367,12 @@ def test_parcels(): other_prc = get_parcels() other_prc.affine = np.eye(4) * 2 - with assert_raises(ValueError): + with pytest.raises(ValueError): prc + other_prc other_prc = get_parcels() other_prc.volume_shape = (20, 3, 4) - with assert_raises(ValueError): + with pytest.raises(ValueError): prc + other_prc # test parcel equalities @@ -396,13 +396,13 @@ def test_parcels(): prc_other = deepcopy(prc) prc_other.volume_shape = (10, 3, 4) assert prc != prc_other - with assert_raises(ValueError): + with pytest.raises(ValueError): prc + prc_other prc_other = deepcopy(prc) prc_other.nvertices['CIFTI_STRUCTURE_CORTEX_LEFT'] = 80 assert prc != prc_other - with assert_raises(ValueError): + with pytest.raises(ValueError): prc + prc_other prc_other = deepcopy(prc) @@ -434,7 +434,7 @@ def test_parcels(): volume_shape=(2, 3, 4), ) - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.ParcelsAxis( voxels=[np.ones((3, 2), dtype=int)], vertices=[{}], @@ -466,7 +466,7 @@ def test_scalar(): # test equalities assert sc != get_label() - with assert_raises(Exception): + with pytest.raises(Exception): sc + get_label() sc_other = deepcopy(sc) @@ -485,10 +485,10 @@ def test_scalar(): # test constructor assert axes.ScalarAxis(['scalar_name'], [{}]) == axes.ScalarAxis(['scalar_name']) - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.ScalarAxis([['scalar_name']]) # wrong shape - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.ScalarAxis(['scalar_name'], [{}, {}]) # wrong size @@ -514,7 +514,7 @@ def test_label(): # test equalities lab = get_label() assert lab != get_scalar() - with assert_raises(Exception): + with pytest.raises(Exception): lab + get_scalar() other_lab = deepcopy(lab) @@ -540,10 +540,10 @@ def test_label(): # test constructor assert axes.LabelAxis(['scalar_name'], [{}], [{}]) == axes.LabelAxis(['scalar_name'], [{}]) - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.LabelAxis([['scalar_name']], [{}]) # wrong shape - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.LabelAxis(['scalar_name'], [{}, {}]) # wrong size @@ -558,7 +558,7 @@ def test_series(): assert sr[3].unit == 'HERTZ' sr[0].unit = 'hertz' assert sr[0].unit == 'HERTZ' - with assert_raises(ValueError): + with pytest.raises(ValueError): sr[0].unit = 'non_existent' sr = list(get_series()) @@ -570,11 +570,17 @@ def test_series(): assert ((sr[1] + sr[0] + sr[0]).time == np.arange(11) * 10 + 8).all() assert sr[1][2] == 28 assert sr[1][-2] == sr[1].time[-2] - assert_raises(ValueError, lambda: sr[0] + sr[2]) - assert_raises(ValueError, lambda: sr[2] + sr[1]) - assert_raises(ValueError, lambda: sr[0] + sr[3]) - assert_raises(ValueError, lambda: sr[3] + sr[1]) - assert_raises(ValueError, lambda: sr[3] + sr[2]) + + with pytest.raises(ValueError): + sr[0] + sr[2] + with pytest.raises(ValueError): + sr[2] + sr[1] + with pytest.raises(ValueError): + sr[0] + sr[3] + with pytest.raises(ValueError): + sr[3] + sr[1] + with pytest.raises(ValueError): + sr[3] + sr[2] # test slicing assert (sr[0][1:3].time == sr[0].time[1:3]).all() @@ -590,16 +596,16 @@ def test_series(): assert (sr[0][3:1:-1].time == sr[0].time[3:1:-1]).all() assert (sr[0][1:3:-1].time == sr[0].time[1:3:-1]).all() - with assert_raises(IndexError): + with pytest.raises(IndexError): assert sr[0][[0, 1]] - with assert_raises(IndexError): + with pytest.raises(IndexError): assert sr[0][20] - with assert_raises(IndexError): + with pytest.raises(IndexError): assert sr[0][-20] # test_equalities sr = next(get_series()) - with assert_raises(Exception): + with pytest.raises(Exception): sr + get_scalar() assert sr != sr[:2] assert sr == sr[:] diff --git a/nibabel/cifti2/tests/test_cifti2.py b/nibabel/cifti2/tests/test_cifti2.py index 8f85b62041..78eac63d1b 100644 --- a/nibabel/cifti2/tests/test_cifti2.py +++ b/nibabel/cifti2/tests/test_cifti2.py @@ -9,7 +9,7 @@ from nibabel.nifti2 import Nifti2Header from nibabel.cifti2.cifti2 import _float_01, _value_if_klass, Cifti2HeaderError -from nose.tools import assert_true, assert_equal, assert_raises, assert_is_none +import pytest from nibabel.tests.test_dataobj_images import TestDataobjAPI as _TDA @@ -27,244 +27,287 @@ def compare_xml_leaf(str1, str2): def test_value_if_klass(): - assert_equal(_value_if_klass(None, list), None) - assert_equal(_value_if_klass([1], list), [1]) - assert_raises(ValueError, _value_if_klass, 1, list) + assert _value_if_klass(None, list) is None + assert _value_if_klass([1], list) == [1] + with pytest.raises(ValueError): + _value_if_klass(1, list) def test_cifti2_metadata(): md = ci.Cifti2MetaData(metadata={'a': 'aval'}) - assert_equal(len(md), 1) - assert_equal(list(iter(md)), ['a']) - assert_equal(md['a'], 'aval') - assert_equal(md.data, dict([('a', 'aval')])) + assert len(md) == 1 + assert list(iter(md)) == ['a'] + assert md['a'] == 'aval' + assert md.data == dict([('a', 'aval')]) md = ci.Cifti2MetaData() - assert_equal(len(md), 0) - assert_equal(list(iter(md)), []) - assert_equal(md.data, {}) - assert_raises(ValueError, md.difference_update, None) + assert len(md) == 0 + assert list(iter(md)) == [] + assert md.data == {} + with pytest.raises(ValueError): + md.difference_update(None) md['a'] = 'aval' - assert_equal(md['a'], 'aval') - assert_equal(len(md), 1) - assert_equal(md.data, dict([('a', 'aval')])) + assert md['a'] == 'aval' + assert len(md) == 1 + assert md.data == dict([('a', 'aval')]) del md['a'] - assert_equal(len(md), 0) + assert len(md) == 0 metadata_test = [('a', 'aval'), ('b', 'bval')] md.update(metadata_test) - assert_equal(md.data, dict(metadata_test)) + assert md.data == dict(metadata_test) - assert_equal(list(iter(md)), list(iter(collections.OrderedDict(metadata_test)))) + assert list(iter(md)) == list(iter(collections.OrderedDict(metadata_test))) md.update({'a': 'aval', 'b': 'bval'}) - assert_equal(md.data, dict(metadata_test)) + assert md.data == dict(metadata_test) md.update({'a': 'aval', 'd': 'dval'}) - assert_equal(md.data, dict(metadata_test + [('d', 'dval')])) + assert md.data == dict(metadata_test + [('d', 'dval')]) md.difference_update({'a': 'aval', 'd': 'dval'}) - assert_equal(md.data, dict(metadata_test[1:])) + assert md.data == dict(metadata_test[1:]) - assert_raises(KeyError, md.difference_update, {'a': 'aval', 'd': 'dval'}) - assert_equal(md.to_xml().decode('utf-8'), - 'bbval') + with pytest.raises(KeyError): + md.difference_update({'a': 'aval', 'd': 'dval'}) + assert md.to_xml().decode('utf-8') == 'bbval' def test__float_01(): - assert_equal(_float_01(0), 0) - assert_equal(_float_01(1), 1) - assert_equal(_float_01('0'), 0) - assert_equal(_float_01('0.2'), 0.2) - assert_raises(ValueError, _float_01, 1.1) - assert_raises(ValueError, _float_01, -0.1) - assert_raises(ValueError, _float_01, 2) - assert_raises(ValueError, _float_01, -1) - assert_raises(ValueError, _float_01, 'foo') + assert _float_01(0) == 0 + assert _float_01(1) == 1 + assert _float_01('0') == 0 + assert _float_01('0.2') == 0.2 + with pytest.raises(ValueError): + _float_01(1.1) + with pytest.raises(ValueError): + _float_01(-0.1) + with pytest.raises(ValueError): + _float_01(2) + with pytest.raises(ValueError): + _float_01(-1) + with pytest.raises(ValueError): + _float_01('foo') def test_cifti2_labeltable(): lt = ci.Cifti2LabelTable() - assert_equal(len(lt), 0) - assert_raises(ci.Cifti2HeaderError, lt.to_xml) - assert_raises(ci.Cifti2HeaderError, lt._to_xml_element) + assert len(lt) == 0 + with pytest.raises(ci.Cifti2HeaderError): + lt.to_xml() + with pytest.raises(ci.Cifti2HeaderError): + lt._to_xml_element() + label = ci.Cifti2Label(label='Test', key=0) lt[0] = label - assert_equal(len(lt), 1) - assert_equal(dict(lt), {label.key: label}) + assert len(lt) == 1 + assert dict(lt) == {label.key: label} lt.clear() lt.append(label) - assert_equal(len(lt), 1) - assert_equal(dict(lt), {label.key: label}) + assert len(lt) == 1 + assert dict(lt) == {label.key: label} lt.clear() test_tuple = (label.label, label.red, label.green, label.blue, label.alpha) lt[label.key] = test_tuple - assert_equal(len(lt), 1) + assert len(lt) == 1 v = lt[label.key] - assert_equal( - (v.label, v.red, v.green, v.blue, v.alpha), - test_tuple - ) + assert (v.label, v.red, v.green, v.blue, v.alpha) == test_tuple + + with pytest.raises(ValueError): + lt[1] = label + + with pytest.raises(ValueError): + lt[0] = test_tuple[:-1] + + with pytest.raises(ValueError): + lt[0] = ('foo', 1.1, 0, 0, 1) + + with pytest.raises(ValueError): + lt[0] = ('foo', 1.0, -1, 0, 1) + + with pytest.raises(ValueError): + lt[0] = ('foo', 1.0, 0, -0.1, 1) - assert_raises(ValueError, lt.__setitem__, 1, label) - assert_raises(ValueError, lt.__setitem__, 0, test_tuple[:-1]) - assert_raises(ValueError, lt.__setitem__, 0, ('foo', 1.1, 0, 0, 1)) - assert_raises(ValueError, lt.__setitem__, 0, ('foo', 1.0, -1, 0, 1)) - assert_raises(ValueError, lt.__setitem__, 0, ('foo', 1.0, 0, -0.1, 1)) def test_cifti2_label(): lb = ci.Cifti2Label() lb.label = 'Test' lb.key = 0 - assert_equal(lb.rgba, (0, 0, 0, 0)) - assert_true(compare_xml_leaf( - lb.to_xml().decode('utf-8'), - "" - )) + assert lb.rgba == (0, 0, 0, 0) + assert compare_xml_leaf(lb.to_xml().decode('utf-8'), "") lb.red = 0 lb.green = 0.1 lb.blue = 0.2 lb.alpha = 0.3 - assert_equal(lb.rgba, (0, 0.1, 0.2, 0.3)) + assert lb.rgba == (0, 0.1, 0.2, 0.3) - assert_true(compare_xml_leaf( - lb.to_xml().decode('utf-8'), - "" - )) + assert compare_xml_leaf( + lb.to_xml().decode('utf-8'), + "") lb.red = 10 - assert_raises(ci.Cifti2HeaderError, lb.to_xml) + with pytest.raises(ci.Cifti2HeaderError): + lb.to_xml() lb.red = 0 lb.key = 'a' - assert_raises(ci.Cifti2HeaderError, lb.to_xml) + with pytest.raises(ci.Cifti2HeaderError): + lb.to_xml() lb.key = 0 def test_cifti2_parcel(): pl = ci.Cifti2Parcel() - assert_raises(ci.Cifti2HeaderError, pl.to_xml) - assert_raises(TypeError, pl.append_cifti_vertices, None) + with pytest.raises(ci.Cifti2HeaderError): + pl.to_xml() + + with pytest.raises(TypeError): + pl.append_cifti_vertices(None) + + with pytest.raises(ValueError): + ci.Cifti2Parcel(**{'vertices': [1, 2, 3]}) - assert_raises(ValueError, ci.Cifti2Parcel, **{'vertices': [1, 2, 3]}) pl = ci.Cifti2Parcel(name='region', voxel_indices_ijk=ci.Cifti2VoxelIndicesIJK([[1, 2, 3]]), vertices=[ci.Cifti2Vertices([0, 1, 2])]) pl.pop_cifti2_vertices(0) - assert_equal(len(pl.vertices), 0) - assert_equal( - pl.to_xml().decode('utf-8'), - '1 2 3' - ) + + assert len(pl.vertices) == 0 + assert pl.to_xml().decode('utf-8') == '1 2 3' def test_cifti2_vertices(): vs = ci.Cifti2Vertices() - assert_raises(ci.Cifti2HeaderError, vs.to_xml) + with pytest.raises(ci.Cifti2HeaderError): + vs.to_xml() + vs.brain_structure = 'CIFTI_STRUCTURE_OTHER' - assert_equal( - vs.to_xml().decode('utf-8'), - '' - ) - assert_equal(len(vs), 0) + + assert vs.to_xml().decode('utf-8') == '' + + assert len(vs) == 0 vs.extend(np.array([0, 1, 2])) - assert_equal(len(vs), 3) - assert_raises(ValueError, vs.__setitem__, 1, 'a') - assert_raises(ValueError, vs.insert, 1, 'a') - assert_equal( - vs.to_xml().decode('utf-8'), - '0 1 2' - ) + assert len(vs) == 3 + with pytest.raises(ValueError): + vs[1] = 'a' + with pytest.raises(ValueError): + vs.insert(1, 'a') + + assert vs.to_xml().decode('utf-8') == '0 1 2' vs[0] = 10 - assert_equal(vs[0], 10) - assert_equal(len(vs), 3) + assert vs[0] == 10 + assert len(vs) == 3 vs = ci.Cifti2Vertices(vertices=[0, 1, 2]) - assert_equal(len(vs), 3) + assert len(vs) == 3 def test_cifti2_transformationmatrixvoxelindicesijktoxyz(): tr = ci.Cifti2TransformationMatrixVoxelIndicesIJKtoXYZ() - assert_raises(ci.Cifti2HeaderError, tr.to_xml) + with pytest.raises(ci.Cifti2HeaderError): + tr.to_xml() def test_cifti2_surface(): s = ci.Cifti2Surface() - assert_raises(ci.Cifti2HeaderError, s.to_xml) + with pytest.raises(ci.Cifti2HeaderError): + s.to_xml() def test_cifti2_volume(): vo = ci.Cifti2Volume() - assert_raises(ci.Cifti2HeaderError, vo.to_xml) + with pytest.raises(ci.Cifti2HeaderError): + vo.to_xml() def test_cifti2_vertexindices(): vi = ci.Cifti2VertexIndices() - assert_equal(len(vi), 0) - assert_raises(ci.Cifti2HeaderError, vi.to_xml) + assert len(vi) == 0 + with pytest.raises(ci.Cifti2HeaderError): + vi.to_xml() vi.extend(np.array([0, 1, 2])) - assert_equal(len(vi), 3) - assert_equal( - vi.to_xml().decode('utf-8'), - '0 1 2' - ) - assert_raises(ValueError, vi.__setitem__, 0, 'a') + assert len(vi) == 3 + assert vi.to_xml().decode('utf-8') == '0 1 2' + + with pytest.raises(ValueError): + vi[0] = 'a' + vi[0] = 10 - assert_equal(vi[0], 10) - assert_equal(len(vi), 3) + assert vi[0] == 10 + assert len(vi) == 3 def test_cifti2_voxelindicesijk(): vi = ci.Cifti2VoxelIndicesIJK() - assert_raises(ci.Cifti2HeaderError, vi.to_xml) + with pytest.raises(ci.Cifti2HeaderError): + vi.to_xml() vi = ci.Cifti2VoxelIndicesIJK() - assert_equal(len(vi), 0) - assert_raises(ci.Cifti2HeaderError, vi.to_xml) + assert len(vi) == 0 + + with pytest.raises(ci.Cifti2HeaderError): + vi.to_xml() vi.extend(np.array([[0, 1, 2]])) - assert_equal(len(vi), 1) - assert_equal(vi[0], [0, 1, 2]) + + assert len(vi) == 1 + assert vi[0] == [0, 1, 2] vi.append([3, 4, 5]) - assert_equal(len(vi), 2) + assert len(vi) == 2 vi.append([6, 7, 8]) - assert_equal(len(vi), 3) + assert len(vi) == 3 del vi[-1] - assert_equal(len(vi), 2) + assert len(vi) == 2 - assert_equal(vi[1], [3, 4, 5]) + assert vi[1] == [3, 4, 5] vi[1] = [3, 4, 6] - assert_equal(vi[1], [3, 4, 6]) - assert_raises(ValueError, vi.__setitem__, 'a', [1, 2, 3]) - assert_raises(TypeError, vi.__setitem__, [1, 2], [1, 2, 3]) - assert_raises(ValueError, vi.__setitem__, 1, [2, 3]) - assert_equal(vi[1, 1], 4) - assert_raises(ValueError, vi.__setitem__, [1, 1], 'a') - assert_equal(vi[0, 1:], [1, 2]) + assert vi[1] == [3, 4, 6] + with pytest.raises(ValueError): + vi['a'] = [1, 2, 3] + + with pytest.raises(TypeError): + vi[[1, 2]] = [1, 2, 3] + + with pytest.raises(ValueError): + vi[1] = [2, 3] + + assert vi[1, 1] == 4 + + with pytest.raises(ValueError): + vi[[1, 1]] = 'a' + + assert vi[0, 1:] == [1, 2] vi[0, 1] = 10 - assert_equal(vi[0, 1], 10) + assert vi[0, 1] == 10 vi[0, 1] = 1 #test for vi[:, 0] and other slices - assert_raises(NotImplementedError, vi.__getitem__, (slice(None), 0)) - assert_raises(NotImplementedError, vi.__setitem__, (slice(None), 0), 0) - assert_raises(NotImplementedError, vi.__delitem__, (slice(None), 0)) - assert_raises(ValueError, vi.__getitem__, (0, 0, 0)) - assert_raises(ValueError, vi.__setitem__, (0, 0, 0), 0) - - assert_equal( - vi.to_xml().decode('utf-8'), - '0 1 2\n3 4 6' - ) - assert_raises(TypeError, ci.Cifti2VoxelIndicesIJK, [0, 1]) + with pytest.raises(NotImplementedError): + vi[(slice(None), 0)] + with pytest.raises(NotImplementedError): + vi[(slice(None), 0)] = 0 + with pytest.raises(NotImplementedError): + # Don't know how to use remove with slice + vi.__delitem__((slice(None), 0)) + with pytest.raises(ValueError): + vi[(0, 0, 0)] + + with pytest.raises(ValueError): + vi[(0, 0, 0)] = 0 + + assert vi.to_xml().decode('utf-8') == '0 1 2\n3 4 6' + + with pytest.raises(TypeError): + ci.Cifti2VoxelIndicesIJK([0, 1]) + vi = ci.Cifti2VoxelIndicesIJK([[1, 2, 3]]) - assert_equal(len(vi), 1) + assert len(vi) == 1 def test_matrixindicesmap(): @@ -273,59 +316,77 @@ def test_matrixindicesmap(): volume2 = ci.Cifti2Volume() parcel = ci.Cifti2Parcel() - assert_is_none(mim.volume) + assert mim.volume is None mim.append(volume) mim.append(parcel) - assert_equal(mim.volume, volume) - assert_raises(ci.Cifti2HeaderError, mim.insert, 0, volume) - assert_raises(ci.Cifti2HeaderError, mim.__setitem__, 1, volume) + assert mim.volume == volume + with pytest.raises(ci.Cifti2HeaderError): + mim.insert(0, volume) + + with pytest.raises(ci.Cifti2HeaderError): + mim[1] = volume mim[0] = volume2 - assert_equal(mim.volume, volume2) + assert mim.volume == volume2 del mim.volume - assert_is_none(mim.volume) - assert_raises(ValueError, delattr, mim, 'volume') + assert mim.volume is None + with pytest.raises(ValueError): + delattr(mim, 'volume') mim.volume = volume - assert_equal(mim.volume, volume) + assert mim.volume == volume mim.volume = volume2 - assert_equal(mim.volume, volume2) + assert mim.volume == volume2 - assert_raises(ValueError, setattr, mim, 'volume', parcel) + with pytest.raises(ValueError): + setattr(mim, 'volume', parcel) def test_matrix(): m = ci.Cifti2Matrix() - assert_raises(TypeError, m, setattr, 'metadata', ci.Cifti2Parcel()) - assert_raises(TypeError, m.__setitem__, 0, ci.Cifti2Parcel()) - assert_raises(TypeError, m.insert, 0, ci.Cifti2Parcel()) + + with pytest.raises(TypeError): + m(setattr, 'metadata', ci.Cifti2Parcel()) + + with pytest.raises(TypeError): + m[0] = ci.Cifti2Parcel() + + with pytest.raises(TypeError): + m.insert(0, ci.Cifti2Parcel()) mim_none = ci.Cifti2MatrixIndicesMap(None, 'CIFTI_INDEX_TYPE_LABELS') mim_0 = ci.Cifti2MatrixIndicesMap(0, 'CIFTI_INDEX_TYPE_LABELS') mim_1 = ci.Cifti2MatrixIndicesMap(1, 'CIFTI_INDEX_TYPE_LABELS') mim_01 = ci.Cifti2MatrixIndicesMap([0, 1], 'CIFTI_INDEX_TYPE_LABELS') - assert_raises(ci.Cifti2HeaderError, m.insert, 0, mim_none) - assert_equal(m.mapped_indices, []) + with pytest.raises(ci.Cifti2HeaderError): + m.insert(0, mim_none) + + assert m.mapped_indices == [] h = ci.Cifti2Header(matrix=m) - assert_equal(m.mapped_indices, []) + assert m.mapped_indices == [] m.insert(0, mim_0) - assert_equal(h.mapped_indices, [0]) - assert_equal(h.number_of_mapped_indices, 1) - assert_raises(ci.Cifti2HeaderError, m.insert, 0, mim_0) - assert_raises(ci.Cifti2HeaderError, m.insert, 0, mim_01) + assert h.mapped_indices == [0] + assert h.number_of_mapped_indices == 1 + with pytest.raises(ci.Cifti2HeaderError): + m.insert(0, mim_0) + + with pytest.raises(ci.Cifti2HeaderError): + m.insert(0, mim_01) + m[0] = mim_1 - assert_equal(list(m.mapped_indices), [1]) + assert list(m.mapped_indices) == [1] m.insert(0, mim_0) - assert_equal(list(sorted(m.mapped_indices)), [0, 1]) - assert_equal(h.number_of_mapped_indices, 2) - assert_equal(h.get_index_map(0), mim_0) - assert_equal(h.get_index_map(1), mim_1) - assert_raises(ci.Cifti2HeaderError, h.get_index_map, 2) + assert list(sorted(m.mapped_indices)) == [0, 1] + assert h.number_of_mapped_indices == 2 + assert h.get_index_map(0) == mim_0 + assert h.get_index_map(1) == mim_1 + with pytest.raises(ci.Cifti2HeaderError): + h.get_index_map(2) def test_underscoring(): @@ -342,7 +403,7 @@ def test_underscoring(): ) for camel, underscored in pairs: - assert_equal(ci.cifti2._underscore(camel), underscored) + assert ci.cifti2._underscore(camel) == underscored class TestCifti2ImageAPI(_TDA): diff --git a/nibabel/cifti2/tests/test_cifti2io_header.py b/nibabel/cifti2/tests/test_cifti2io_header.py index b8cbd05a32..9347051407 100644 --- a/nibabel/cifti2/tests/test_cifti2io_header.py +++ b/nibabel/cifti2/tests/test_cifti2io_header.py @@ -21,7 +21,7 @@ from nibabel.tests.test_nifti2 import TestNifti2SingleHeader from numpy.testing import assert_array_almost_equal -from nose.tools import (assert_true, assert_equal, assert_raises) +import pytest NIBABEL_TEST_DATA = pjoin(dirname(nib.__file__), 'tests', 'data') NIFTI2_DATA = pjoin(NIBABEL_TEST_DATA, 'example_nifti2.nii.gz') @@ -46,35 +46,36 @@ def test_read_nifti2(): filemap = ci.Cifti2Image.make_file_map() for k in filemap: filemap[k].fileobj = io.open(NIFTI2_DATA) - assert_raises(ValueError, ci.Cifti2Image.from_file_map, filemap) + with pytest.raises(ValueError): + ci.Cifti2Image.from_file_map(filemap) @needs_nibabel_data('nitest-cifti2') def test_read_internal(): img2 = ci.load(DATA_FILE6) - assert_true(isinstance(img2.header, ci.Cifti2Header)) - assert_equal(img2.shape, (1, 91282)) + assert isinstance(img2.header, ci.Cifti2Header) + assert img2.shape == (1, 91282) @needs_nibabel_data('nitest-cifti2') def test_read_and_proxies(): img2 = nib.load(DATA_FILE6) - assert_true(isinstance(img2.header, ci.Cifti2Header)) - assert_equal(img2.shape, (1, 91282)) + assert isinstance(img2.header, ci.Cifti2Header) + assert img2.shape == (1, 91282) # While we cannot reshape arrayproxies, all images are in-memory - assert_true(not img2.in_memory) + assert not img2.in_memory data = img2.get_fdata() - assert_true(data is not img2.dataobj) + assert data is not img2.dataobj # Uncaching has no effect, images are always array images img2.uncache() - assert_true(data is not img2.get_fdata()) + assert data is not img2.get_fdata() @needs_nibabel_data('nitest-cifti2') def test_version(): for i, dat in enumerate(datafiles): img = nib.load(dat) - assert_equal(LooseVersion(img.header.version), LooseVersion('2')) + assert LooseVersion(img.header.version), LooseVersion('2') @needs_nibabel_data('nitest-cifti2') @@ -84,8 +85,7 @@ def test_readwritedata(): img = ci.load(name) ci.save(img, 'test.nii') img2 = ci.load('test.nii') - assert_equal(len(img.header.matrix), - len(img2.header.matrix)) + assert len(img.header.matrix) == len(img2.header.matrix) # Order should be preserved in load/save for mim1, mim2 in zip(img.header.matrix, img2.header.matrix): @@ -93,14 +93,14 @@ def test_readwritedata(): if isinstance(m_, ci.Cifti2NamedMap)] named_maps2 = [m_ for m_ in mim2 if isinstance(m_, ci.Cifti2NamedMap)] - assert_equal(len(named_maps1), len(named_maps2)) + assert len(named_maps1) == len(named_maps2) for map1, map2 in zip(named_maps1, named_maps2): - assert_equal(map1.map_name, map2.map_name) + assert map1.map_name == map2.map_name if map1.label_table is None: - assert_true(map2.label_table is None) + assert map2.label_table is None else: - assert_equal(len(map1.label_table), - len(map2.label_table)) + assert len(map1.label_table) == len(map2.label_table) + assert_array_almost_equal(img.dataobj, img2.dataobj) @@ -111,8 +111,7 @@ def test_nibabel_readwritedata(): img = nib.load(name) nib.save(img, 'test.nii') img2 = nib.load('test.nii') - assert_equal(len(img.header.matrix), - len(img2.header.matrix)) + assert len(img.header.matrix) == len(img2.header.matrix) # Order should be preserved in load/save for mim1, mim2 in zip(img.header.matrix, img2.header.matrix): @@ -120,14 +119,13 @@ def test_nibabel_readwritedata(): if isinstance(m_, ci.Cifti2NamedMap)] named_maps2 = [m_ for m_ in mim2 if isinstance(m_, ci.Cifti2NamedMap)] - assert_equal(len(named_maps1), len(named_maps2)) + assert len(named_maps1) == len(named_maps2) for map1, map2 in zip(named_maps1, named_maps2): - assert_equal(map1.map_name, map2.map_name) + assert map1.map_name == map2.map_name if map1.label_table is None: - assert_true(map2.label_table is None) + assert map2.label_table is None else: - assert_equal(len(map1.label_table), - len(map2.label_table)) + assert len(map1.label_table) == len(map2.label_table) assert_array_almost_equal(img.dataobj, img2.dataobj) @@ -152,10 +150,10 @@ def test_cifti2types(): for name in datafiles: hdr = ci.load(name).header # Matrix and MetaData aren't conditional, so don't bother counting - assert_true(isinstance(hdr.matrix, ci.Cifti2Matrix)) - assert_true(isinstance(hdr.matrix.metadata, ci.Cifti2MetaData)) + assert isinstance(hdr.matrix, ci.Cifti2Matrix) + assert isinstance(hdr.matrix.metadata, ci.Cifti2MetaData) for mim in hdr.matrix: - assert_true(isinstance(mim, ci.Cifti2MatrixIndicesMap)) + assert isinstance(mim, ci.Cifti2MatrixIndicesMap) counter[ci.Cifti2MatrixIndicesMap] += 1 for map_ in mim: print(map_) @@ -168,21 +166,20 @@ def test_cifti2types(): counter[ci.Cifti2VoxelIndicesIJK] += 1 elif isinstance(map_, ci.Cifti2NamedMap): counter[ci.Cifti2NamedMap] += 1 - assert_true(isinstance(map_.metadata, ci.Cifti2MetaData)) + assert isinstance(map_.metadata, ci.Cifti2MetaData) if isinstance(map_.label_table, ci.Cifti2LabelTable): counter[ci.Cifti2LabelTable] += 1 for label in map_.label_table: - assert_true(isinstance(map_.label_table[label], - ci.Cifti2Label)) + assert isinstance(map_.label_table[label], ci.Cifti2Label) counter[ci.Cifti2Label] += 1 elif isinstance(map_, ci.Cifti2Parcel): counter[ci.Cifti2Parcel] += 1 if isinstance(map_.voxel_indices_ijk, ci.Cifti2VoxelIndicesIJK): counter[ci.Cifti2VoxelIndicesIJK] += 1 - assert_true(isinstance(map_.vertices, list)) + assert isinstance(map_.vertices, list) for vtcs in map_.vertices: - assert_true(isinstance(vtcs, ci.Cifti2Vertices)) + assert isinstance(vtcs, ci.Cifti2Vertices) counter[ci.Cifti2Vertices] += 1 elif isinstance(map_, ci.Cifti2Surface): counter[ci.Cifti2Surface] += 1 @@ -192,19 +189,14 @@ def test_cifti2types(): ci.Cifti2TransformationMatrixVoxelIndicesIJKtoXYZ): counter[ci.Cifti2TransformationMatrixVoxelIndicesIJKtoXYZ] += 1 - assert_equal(list(mim.named_maps), - [m_ for m_ in mim if isinstance(m_, ci.Cifti2NamedMap)]) - assert_equal(list(mim.surfaces), - [m_ for m_ in mim if isinstance(m_, ci.Cifti2Surface)]) - assert_equal(list(mim.parcels), - [m_ for m_ in mim if isinstance(m_, ci.Cifti2Parcel)]) - assert_equal(list(mim.brain_models), - [m_ for m_ in mim if isinstance(m_, ci.Cifti2BrainModel)]) - assert_equal([mim.volume] if mim.volume else [], - [m_ for m_ in mim if isinstance(m_, ci.Cifti2Volume)]) + assert list(mim.named_maps) == [m_ for m_ in mim if isinstance(m_, ci.Cifti2NamedMap)] + assert list(mim.surfaces) == [m_ for m_ in mim if isinstance(m_, ci.Cifti2Surface)] + assert list(mim.parcels) == [m_ for m_ in mim if isinstance(m_, ci.Cifti2Parcel)] + assert list(mim.brain_models) == [m_ for m_ in mim if isinstance(m_, ci.Cifti2BrainModel)] + assert [mim.volume] == [m_ for m_ in mim if isinstance(m_, ci.Cifti2Volume)] if mim.volume else [] for klass, count in counter.items(): - assert_true(count > 0, "No exercise of " + klass.__name__) + assert count > 0 # "No exercise of " + klass.__name__ @needs_nibabel_data('nitest-cifti2') @@ -237,34 +229,34 @@ def test_read_geometry(): ('CIFTI_STRUCTURE_THALAMUS_RIGHT', 1248, [32, 47, 34], [38, 55, 46])] current_index = 0 for from_file, expected in zip(geometry_mapping.brain_models, expected_geometry): - assert_true(from_file.model_type in ("CIFTI_MODEL_TYPE_SURFACE", "CIFTI_MODEL_TYPE_VOXELS")) - assert_equal(from_file.brain_structure, expected[0]) - assert_equal(from_file.index_offset, current_index) - assert_equal(from_file.index_count, expected[1]) + assert from_file.model_type in ("CIFTI_MODEL_TYPE_SURFACE", "CIFTI_MODEL_TYPE_VOXELS") + assert from_file.brain_structure == expected[0] + assert from_file.index_offset == current_index + assert from_file.index_count == expected[1] current_index += from_file.index_count if from_file.model_type == 'CIFTI_MODEL_TYPE_SURFACE': - assert_equal(from_file.voxel_indices_ijk, None) - assert_equal(len(from_file.vertex_indices), expected[1]) - assert_equal(from_file.vertex_indices[0], expected[2]) - assert_equal(from_file.vertex_indices[-1], expected[3]) - assert_equal(from_file.surface_number_of_vertices, 32492) + assert from_file.voxel_indices_ijk is None + assert len(from_file.vertex_indices) == expected[1] + assert from_file.vertex_indices[0] == expected[2] + assert from_file.vertex_indices[-1] == expected[3] + assert from_file.surface_number_of_vertices == 32492 else: - assert_equal(from_file.vertex_indices, None) - assert_equal(from_file.surface_number_of_vertices, None) - assert_equal(len(from_file.voxel_indices_ijk), expected[1]) - assert_equal(from_file.voxel_indices_ijk[0], expected[2]) - assert_equal(from_file.voxel_indices_ijk[-1], expected[3]) - assert_equal(current_index, img.shape[1]) + assert from_file.vertex_indices is None + assert from_file.surface_number_of_vertices is None + assert len(from_file.voxel_indices_ijk) == expected[1] + assert from_file.voxel_indices_ijk[0] == expected[2] + assert from_file.voxel_indices_ijk[-1], expected[3] + assert current_index == img.shape[1] expected_affine = [[-2, 0, 0, 90], [ 0, 2, 0, -126], [ 0, 0, 2, -72], [ 0, 0, 0, 1]] expected_dimensions = (91, 109, 91) - assert_true((geometry_mapping.volume.transformation_matrix_voxel_indices_ijk_to_xyz.matrix == - expected_affine).all()) - assert_equal(geometry_mapping.volume.volume_dimensions, expected_dimensions) + assert (geometry_mapping.volume.transformation_matrix_voxel_indices_ijk_to_xyz.matrix == + expected_affine).all() + assert geometry_mapping.volume.volume_dimensions == expected_dimensions @needs_nibabel_data('nitest-cifti2') @@ -327,18 +319,18 @@ def test_read_parcels(): ('ER_FRB08', ((103, 21514, 26470), (103, 21514, 26470))), ('13b_OFP03', ((60, 21042, 21194), (71, 21040, 21216)))] - assert_equal(img.shape[1], len(expected_parcels)) - assert_equal(len(list(parcel_mapping.parcels)), len(expected_parcels)) + assert img.shape[1] == len(expected_parcels) + assert len(list(parcel_mapping.parcels)) == len(expected_parcels) for (name, expected_surfaces), parcel in zip(expected_parcels, parcel_mapping.parcels): - assert_equal(parcel.name, name) - assert_equal(len(parcel.vertices), 2) + assert parcel.name == name + assert len(parcel.vertices) == 2 for vertices, orientation, (length, first_element, last_element) in zip(parcel.vertices, ('LEFT', 'RIGHT'), expected_surfaces): - assert_equal(len(vertices), length) - assert_equal(vertices[0], first_element) - assert_equal(vertices[-1], last_element) - assert_equal(vertices.brain_structure, 'CIFTI_STRUCTURE_CORTEX_%s' % orientation) + assert len(vertices) == length + assert vertices[0] == first_element + assert vertices[-1] == last_element + assert vertices.brain_structure == 'CIFTI_STRUCTURE_CORTEX_%s' % orientation @needs_nibabel_data('nitest-cifti2') @@ -347,31 +339,31 @@ def test_read_scalar(): scalar_mapping = img.header.matrix.get_index_map(0) expected_names = ('MyelinMap_BC_decurv', 'corrThickness') - assert_equal(img.shape[0], len(expected_names)) - assert_equal(len(list(scalar_mapping.named_maps)), len(expected_names)) + assert img.shape[0] == len(expected_names) + assert len(list(scalar_mapping.named_maps)) == len(expected_names) expected_meta = [('PaletteColorMapping', '\n Date: Mon, 10 Feb 2020 16:02:25 +0200 Subject: [PATCH 204/223] TEST: style fixed --- nibabel/cifti2/tests/test_cifti2.py | 6 +++--- nibabel/cifti2/tests/test_cifti2io_header.py | 6 ++---- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/nibabel/cifti2/tests/test_cifti2.py b/nibabel/cifti2/tests/test_cifti2.py index 78eac63d1b..8b31839933 100644 --- a/nibabel/cifti2/tests/test_cifti2.py +++ b/nibabel/cifti2/tests/test_cifti2.py @@ -289,12 +289,12 @@ def test_cifti2_voxelindicesijk(): #test for vi[:, 0] and other slices with pytest.raises(NotImplementedError): - vi[(slice(None), 0)] + vi[:, 0] with pytest.raises(NotImplementedError): - vi[(slice(None), 0)] = 0 + vi[:, 0] = 0 with pytest.raises(NotImplementedError): # Don't know how to use remove with slice - vi.__delitem__((slice(None), 0)) + del vi[:, 0] with pytest.raises(ValueError): vi[(0, 0, 0)] diff --git a/nibabel/cifti2/tests/test_cifti2io_header.py b/nibabel/cifti2/tests/test_cifti2io_header.py index 9347051407..4f9fab4ac4 100644 --- a/nibabel/cifti2/tests/test_cifti2io_header.py +++ b/nibabel/cifti2/tests/test_cifti2io_header.py @@ -436,10 +436,8 @@ def test_pixdim_log_checks(self): assert fhdr['pixdim'][1]== 2 assert message == self._pixdim_message + '; setting to abs of pixdim values' - - with pytest.raises(raiser[0]): - raiser[1](*raiser[2:]) - + pytest.raises(*raiser) + hdr = HC() hdr['pixdim'][1:4] = 0 # No error or warning fhdr, message, raiser = self.log_chk(hdr, 0) From 3b6896e6e26b4a3e5b381b17d65fcd33b6dde09d Mon Sep 17 00:00:00 2001 From: robbisg Date: Mon, 10 Feb 2020 22:26:38 +0200 Subject: [PATCH 205/223] TEST: fixed comments --- nibabel/cifti2/tests/test_cifti2.py | 22 ++++++++++---------- nibabel/cifti2/tests/test_cifti2io_header.py | 12 +++++------ 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/nibabel/cifti2/tests/test_cifti2.py b/nibabel/cifti2/tests/test_cifti2.py index 8b31839933..0d3d550a66 100644 --- a/nibabel/cifti2/tests/test_cifti2.py +++ b/nibabel/cifti2/tests/test_cifti2.py @@ -140,7 +140,8 @@ def test_cifti2_label(): lb.label = 'Test' lb.key = 0 assert lb.rgba == (0, 0, 0, 0) - assert compare_xml_leaf(lb.to_xml().decode('utf-8'), "") + assert compare_xml_leaf(lb.to_xml().decode('utf-8'), + "") lb.red = 0 lb.green = 0.1 @@ -148,9 +149,8 @@ def test_cifti2_label(): lb.alpha = 0.3 assert lb.rgba == (0, 0.1, 0.2, 0.3) - assert compare_xml_leaf( - lb.to_xml().decode('utf-8'), - "") + assert compare_xml_leaf(lb.to_xml().decode('utf-8'), + "") lb.red = 10 with pytest.raises(ci.Cifti2HeaderError): @@ -172,7 +172,7 @@ def test_cifti2_parcel(): pl.append_cifti_vertices(None) with pytest.raises(ValueError): - ci.Cifti2Parcel(**{'vertices': [1, 2, 3]}) + ci.Cifti2Parcel(vertices=[1, 2, 3]) pl = ci.Cifti2Parcel(name='region', voxel_indices_ijk=ci.Cifti2VoxelIndicesIJK([[1, 2, 3]]), @@ -296,10 +296,10 @@ def test_cifti2_voxelindicesijk(): # Don't know how to use remove with slice del vi[:, 0] with pytest.raises(ValueError): - vi[(0, 0, 0)] + vi[0, 0, 0] with pytest.raises(ValueError): - vi[(0, 0, 0)] = 0 + vi[0, 0, 0] = 0 assert vi.to_xml().decode('utf-8') == '0 1 2\n3 4 6' @@ -334,7 +334,7 @@ def test_matrixindicesmap(): del mim.volume assert mim.volume is None with pytest.raises(ValueError): - delattr(mim, 'volume') + del mim.volume mim.volume = volume assert mim.volume == volume @@ -342,14 +342,14 @@ def test_matrixindicesmap(): assert mim.volume == volume2 with pytest.raises(ValueError): - setattr(mim, 'volume', parcel) + mim.volume = parcel def test_matrix(): m = ci.Cifti2Matrix() - with pytest.raises(TypeError): - m(setattr, 'metadata', ci.Cifti2Parcel()) + with pytest.raises(ValueError): + m.metadata = ci.Cifti2Parcel() with pytest.raises(TypeError): m[0] = ci.Cifti2Parcel() diff --git a/nibabel/cifti2/tests/test_cifti2io_header.py b/nibabel/cifti2/tests/test_cifti2io_header.py index 4f9fab4ac4..0cbf167809 100644 --- a/nibabel/cifti2/tests/test_cifti2io_header.py +++ b/nibabel/cifti2/tests/test_cifti2io_header.py @@ -75,7 +75,7 @@ def test_read_and_proxies(): def test_version(): for i, dat in enumerate(datafiles): img = nib.load(dat) - assert LooseVersion(img.header.version), LooseVersion('2') + assert LooseVersion(img.header.version) == LooseVersion('2') @needs_nibabel_data('nitest-cifti2') @@ -193,10 +193,10 @@ def test_cifti2types(): assert list(mim.surfaces) == [m_ for m_ in mim if isinstance(m_, ci.Cifti2Surface)] assert list(mim.parcels) == [m_ for m_ in mim if isinstance(m_, ci.Cifti2Parcel)] assert list(mim.brain_models) == [m_ for m_ in mim if isinstance(m_, ci.Cifti2BrainModel)] - assert [mim.volume] == [m_ for m_ in mim if isinstance(m_, ci.Cifti2Volume)] if mim.volume else [] + assert ([mim.volume] if mim.volume else []) == [m_ for m_ in mim if isinstance(m_, ci.Cifti2Volume)] for klass, count in counter.items(): - assert count > 0 # "No exercise of " + klass.__name__ + assert count > 0, "No exercise of " + klass.__name__ @needs_nibabel_data('nitest-cifti2') @@ -246,7 +246,7 @@ def test_read_geometry(): assert from_file.surface_number_of_vertices is None assert len(from_file.voxel_indices_ijk) == expected[1] assert from_file.voxel_indices_ijk[0] == expected[2] - assert from_file.voxel_indices_ijk[-1], expected[3] + assert from_file.voxel_indices_ijk[-1] == expected[3] assert current_index == img.shape[1] expected_affine = [[-2, 0, 0, 90], @@ -352,7 +352,7 @@ def test_read_scalar(): assert key in scalar.metadata.data.keys() assert scalar.metadata[key][:len(value)] == value - assert scalar.label_table is None #".dscalar file should not define a label table" + assert scalar.label_table is None, ".dscalar file should not define a label table" @needs_nibabel_data('nitest-cifti2') @@ -433,7 +433,7 @@ def test_pixdim_log_checks(self): hdr = HC() hdr['pixdim'][1] = -2 # severity 35 fhdr, message, raiser = self.log_chk(hdr, 35) - assert fhdr['pixdim'][1]== 2 + assert fhdr['pixdim'][1] == 2 assert message == self._pixdim_message + '; setting to abs of pixdim values' pytest.raises(*raiser) From f8db80a539677dd1dea01ce7da9dbce955775131 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Mon, 10 Feb 2020 21:22:37 -0500 Subject: [PATCH 206/223] TEST/RF: Reduce redundancy in test_removalschedule, test failure case --- nibabel/tests/test_removalschedule.py | 102 ++++++++++++++++---------- 1 file changed, 65 insertions(+), 37 deletions(-) diff --git a/nibabel/tests/test_removalschedule.py b/nibabel/tests/test_removalschedule.py index 17f40d8395..28144f3af4 100644 --- a/nibabel/tests/test_removalschedule.py +++ b/nibabel/tests/test_removalschedule.py @@ -1,57 +1,85 @@ from ..pkg_info import cmp_pkg_version +import unittest +from unittest import mock import pytest MODULE_SCHEDULE = [ - ('5.0.0', ['nibabel.keywordonly']), - ('4.0.0', ['nibabel.trackvis']), - ('3.0.0', ['nibabel.minc', 'nibabel.checkwarns']), + ("5.0.0", ["nibabel.keywordonly"]), + ("4.0.0", ["nibabel.trackvis"]), + ("3.0.0", ["nibabel.minc", "nibabel.checkwarns"]), # Verify that the test will be quiet if the schedule outlives the modules - ('1.0.0', ['nibabel.neverexisted']), - ] + ("1.0.0", ["nibabel.nosuchmod"]), +] OBJECT_SCHEDULE = [ - ('3.0.0', [('nibabel.testing', 'catch_warn_reset')]), + ("5.0.0", [("nibabel.pydicom_compat", "dicom_test")]), + ("3.0.0", [("nibabel.testing", "catch_warn_reset")]), # Verify that the test will be quiet if the schedule outlives the modules - ('1.0.0', [('nibabel', 'neverexisted')]), - ] + ("1.0.0", [("nibabel.nosuchmod", "anyobj"), ("nibabel.nifti1", "nosuchobj")]), +] ATTRIBUTE_SCHEDULE = [ - ('5.0.0', [('nibabel.dataobj_images', 'DataobjImage', 'get_data')]), + ("5.0.0", [("nibabel.dataobj_images", "DataobjImage", "get_data")]), # Verify that the test will be quiet if the schedule outlives the modules - ('1.0.0', [('nibabel', 'Nifti1Image', 'neverexisted')]), - ] + ("1.0.0", [("nibabel.nosuchmod", "anyobj", "anyattr"), + ("nibabel.nifti1", "nosuchobj", "anyattr"), + ("nibabel.nifti1", "Nifti1Image", "nosuchattr")]), +] + + +def _filter(schedule): + return [entry for ver, entries in schedule if cmp_pkg_version(ver) < 1 for entry in entries] def test_module_removal(): - for version, to_remove in MODULE_SCHEDULE: - if cmp_pkg_version(version) < 1: - for module in to_remove: - with pytest.raises(ImportError): - __import__(module) - pytest.fail("Time to remove " + module) + for module in _filter(MODULE_SCHEDULE): + with pytest.raises(ImportError): + __import__(module) + assert False, "Time to remove %s" % module def test_object_removal(): - for version, to_remove in OBJECT_SCHEDULE: - if cmp_pkg_version(version) < 1: - for module_name, obj in to_remove: - try: - module = __import__(module_name) - except ImportError: - continue - assert not hasattr(module, obj), "Time to remove %s.%s" % (module_name, obj) + for module_name, obj in _filter(OBJECT_SCHEDULE): + try: + module = __import__(module_name) + except ImportError: + continue + assert not hasattr(module, obj), "Time to remove %s.%s" % (module_name, obj,) def test_attribute_removal(): - for version, to_remove in ATTRIBUTE_SCHEDULE: - if cmp_pkg_version(version) < 1: - for module_name, cls, attr in to_remove: - try: - module = __import__(module_name) - except ImportError: - continue - try: - klass = getattr(module, cls) - except AttributeError: - continue - assert not hasattr(klass, attr), "Time to remove %s.%s.%s" % (module_name, cls, attr) + for module_name, cls, attr in _filter(ATTRIBUTE_SCHEDULE): + try: + module = __import__(module_name) + except ImportError: + continue + try: + klass = getattr(module, cls) + except AttributeError: + continue + assert not hasattr(klass, attr), "Time to remove %s.%s.%s" % (module_name, cls, attr,) + + +# +# Test the tests, making sure that we will get errors when the time comes +# + +_sched = "nibabel.tests.test_removalschedule.{}_SCHEDULE".format + + +@mock.patch(_sched("MODULE"), [("3.0.0", ["nibabel.nifti1"])]) +def test_unremoved_module(): + with pytest.raises(AssertionError): + test_module_removal() + + +@mock.patch(_sched("OBJECT"), [("3.0.0", [("nibabel.nifti1", "Nifti1Image")])]) +def test_unremoved_object(): + with pytest.raises(AssertionError): + test_object_removal() + + +@mock.patch(_sched("ATTRIBUTE"), [("3.0.0", [("nibabel.nifti1", "Nifti1Image", "affine")])]) +def test_unremoved_attr(): + with pytest.raises(AssertionError): + test_attribute_removal() From 8db1cd9a6333c76d872e807d81827a21242ba76c Mon Sep 17 00:00:00 2001 From: Dorota Jarecka Date: Sun, 16 Feb 2020 19:39:14 -0500 Subject: [PATCH 207/223] changing testing_pytest back to testing --- nibabel/cifti2/tests/test_new_cifti2.py | 2 +- nibabel/freesurfer/tests/test_io.py | 2 +- nibabel/freesurfer/tests/test_mghformat.py | 2 +- nibabel/gifti/tests/test_gifti.py | 2 +- nibabel/gifti/tests/test_parse_gifti_fast.py | 2 +- .../streamlines/tests/test_array_sequence.py | 2 +- nibabel/streamlines/tests/test_tck.py | 2 +- nibabel/streamlines/tests/test_tractogram.py | 2 +- nibabel/streamlines/tests/test_trk.py | 2 +- nibabel/testing/__init__.py | 52 ++-- .../{testing_pytest => testing}/helpers.py | 0 nibabel/testing_pytest/__init__.py | 223 ------------------ nibabel/testing_pytest/np_features.py | 23 -- nibabel/tests/test_analyze.py | 4 +- nibabel/tests/test_arrayproxy.py | 2 +- nibabel/tests/test_arraywriters.py | 4 +- nibabel/tests/test_brikhead.py | 2 +- nibabel/tests/test_casting.py | 2 +- nibabel/tests/test_deprecator.py | 2 +- nibabel/tests/test_dft.py | 2 +- nibabel/tests/test_ecat.py | 2 +- nibabel/tests/test_floating.py | 2 +- nibabel/tests/test_image_api.py | 4 +- nibabel/tests/test_imageclasses.py | 2 +- nibabel/tests/test_minc1.py | 2 +- nibabel/tests/test_minc2.py | 2 +- nibabel/tests/test_nifti1.py | 5 +- nibabel/tests/test_nifti2.py | 2 +- nibabel/tests/test_openers.py | 2 +- nibabel/tests/test_parrec.py | 2 +- nibabel/tests/test_proxy_api.py | 2 +- nibabel/tests/test_scaling.py | 2 +- nibabel/tests/test_scripts.py | 2 +- nibabel/tests/test_spatialimages.py | 4 +- nibabel/tests/test_spm99analyze.py | 2 +- nibabel/tests/test_testing.py | 2 +- nibabel/tests/test_volumeutils.py | 2 +- nibabel/tests/test_wrapstruct.py | 2 +- 38 files changed, 63 insertions(+), 314 deletions(-) rename nibabel/{testing_pytest => testing}/helpers.py (100%) delete mode 100644 nibabel/testing_pytest/__init__.py delete mode 100644 nibabel/testing_pytest/np_features.py diff --git a/nibabel/cifti2/tests/test_new_cifti2.py b/nibabel/cifti2/tests/test_new_cifti2.py index a0ba390b8e..944a1c1576 100644 --- a/nibabel/cifti2/tests/test_new_cifti2.py +++ b/nibabel/cifti2/tests/test_new_cifti2.py @@ -13,7 +13,7 @@ from nibabel.tmpdirs import InTemporaryDirectory import pytest -from ...testing_pytest import ( +from ...testing import ( clear_and_catch_warnings, error_warnings, suppress_warnings, assert_array_equal) affine = [[-1.5, 0, 0, 90], diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index e1ec971c65..b2401a11ab 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -19,7 +19,7 @@ from ...tests.nibabel_data import get_nibabel_data, needs_nibabel_data from ...fileslice import strided_scalar -from ...testing_pytest import clear_and_catch_warnings +from ...testing import clear_and_catch_warnings DATA_SDIR = 'fsaverage' diff --git a/nibabel/freesurfer/tests/test_mghformat.py b/nibabel/freesurfer/tests/test_mghformat.py index e3090ca5fa..e1cfc56b18 100644 --- a/nibabel/freesurfer/tests/test_mghformat.py +++ b/nibabel/freesurfer/tests/test_mghformat.py @@ -28,7 +28,7 @@ from numpy.testing import assert_array_equal, assert_array_almost_equal, assert_almost_equal -from ...testing_pytest import data_path +from ...testing import data_path from ...tests import test_spatialimages as tsi from ...tests.test_wrapstruct import _TestLabeledWrapStruct diff --git a/nibabel/gifti/tests/test_gifti.py b/nibabel/gifti/tests/test_gifti.py index 5cb70019d8..2d60482c59 100644 --- a/nibabel/gifti/tests/test_gifti.py +++ b/nibabel/gifti/tests/test_gifti.py @@ -16,7 +16,7 @@ from numpy.testing import assert_array_almost_equal, assert_array_equal import pytest -from ...testing_pytest import clear_and_catch_warnings, test_data +from ...testing import clear_and_catch_warnings, test_data from .test_parse_gifti_fast import (DATA_FILE1, DATA_FILE2, DATA_FILE3, DATA_FILE4, DATA_FILE5, DATA_FILE6) import itertools diff --git a/nibabel/gifti/tests/test_parse_gifti_fast.py b/nibabel/gifti/tests/test_parse_gifti_fast.py index 5e8150ac64..54d8e78621 100644 --- a/nibabel/gifti/tests/test_parse_gifti_fast.py +++ b/nibabel/gifti/tests/test_parse_gifti_fast.py @@ -23,7 +23,7 @@ from numpy.testing import assert_array_almost_equal import pytest -from ...testing_pytest import clear_and_catch_warnings +from ...testing import clear_and_catch_warnings IO_DATA_PATH = pjoin(dirname(__file__), 'data') diff --git a/nibabel/streamlines/tests/test_array_sequence.py b/nibabel/streamlines/tests/test_array_sequence.py index 0802d19b19..06e19248f4 100644 --- a/nibabel/streamlines/tests/test_array_sequence.py +++ b/nibabel/streamlines/tests/test_array_sequence.py @@ -6,7 +6,7 @@ import numpy as np import pytest -from ...testing_pytest import assert_arrays_equal +from ...testing import assert_arrays_equal from numpy.testing import assert_array_equal from ..array_sequence import ArraySequence, is_array_sequence, concatenate diff --git a/nibabel/streamlines/tests/test_tck.py b/nibabel/streamlines/tests/test_tck.py index fb29776f75..0dfb043d83 100644 --- a/nibabel/streamlines/tests/test_tck.py +++ b/nibabel/streamlines/tests/test_tck.py @@ -16,7 +16,7 @@ import pytest from numpy.testing import assert_array_equal -from ...testing_pytest import data_path, clear_and_catch_warnings +from ...testing import data_path, clear_and_catch_warnings from .test_tractogram import assert_tractogram_equal DATA = {} diff --git a/nibabel/streamlines/tests/test_tractogram.py b/nibabel/streamlines/tests/test_tractogram.py index 16f1df2989..f86594d070 100644 --- a/nibabel/streamlines/tests/test_tractogram.py +++ b/nibabel/streamlines/tests/test_tractogram.py @@ -7,7 +7,7 @@ from collections import defaultdict import pytest -from ...testing_pytest import assert_arrays_equal, clear_and_catch_warnings +from ...testing import assert_arrays_equal, clear_and_catch_warnings from numpy.testing import assert_array_equal, assert_array_almost_equal from .. import tractogram as module_tractogram diff --git a/nibabel/streamlines/tests/test_trk.py b/nibabel/streamlines/tests/test_trk.py index 736f61b820..8fb35fc368 100644 --- a/nibabel/streamlines/tests/test_trk.py +++ b/nibabel/streamlines/tests/test_trk.py @@ -8,7 +8,7 @@ from io import BytesIO import pytest -from ...testing_pytest import data_path, clear_and_catch_warnings, assert_arr_dict_equal +from ...testing import data_path, clear_and_catch_warnings, assert_arr_dict_equal from numpy.testing import assert_array_equal from .test_tractogram import assert_tractogram_equal diff --git a/nibabel/testing/__init__.py b/nibabel/testing/__init__.py index fbd1128589..52055ebcc3 100644 --- a/nibabel/testing/__init__.py +++ b/nibabel/testing/__init__.py @@ -13,22 +13,14 @@ import sys import warnings from pkg_resources import resource_filename -from os.path import dirname, abspath, join as pjoin -import numpy as np -from numpy.testing import assert_array_equal, assert_warns -from numpy.testing import dec -skipif = dec.skipif -slow = dec.slow +import unittest -from ..deprecated import deprecate_with_version as _deprecate_with_version +import numpy as np +from numpy.testing import assert_array_equal -# Allow failed import of nose if not now running tests -try: - from nose.tools import (assert_equal, assert_not_equal, - assert_true, assert_false, assert_raises) -except ImportError: - pass +from .np_features import memmap_after_ufunc +from .helpers import bytesio_filemap, bytesio_round_trip, assert_data_similar from itertools import zip_longest @@ -51,14 +43,12 @@ def test_data(subdir=None, fname=None): data_path = test_data() -from .np_features import memmap_after_ufunc - def assert_dt_equal(a, b): """ Assert two numpy dtype specifiers are equal Avoids failed comparison between int32 / int64 and intp """ - assert_equal(np.dtype(a).str, np.dtype(b).str) + assert np.dtype(a).str == np.dtype(b).str def assert_allclose_safely(a, b, match_nans=True, rtol=1e-5, atol=1e-8): @@ -68,7 +58,7 @@ def assert_allclose_safely(a, b, match_nans=True, rtol=1e-5, atol=1e-8): a, b = np.broadcast_arrays(a, b) if match_nans: nans = np.isnan(a) - np.testing.assert_array_equal(nans, np.isnan(b)) + assert_array_equal(nans, np.isnan(b)) to_test = ~nans else: to_test = np.ones(a.shape, dtype=bool) @@ -81,13 +71,13 @@ def assert_allclose_safely(a, b, match_nans=True, rtol=1e-5, atol=1e-8): a = a.astype(float) if b.dtype.kind in 'ui': b = b.astype(float) - assert_true(np.allclose(a, b, rtol=rtol, atol=atol)) + assert np.allclose(a, b, rtol=rtol, atol=atol) def assert_arrays_equal(arrays1, arrays2): """ Check two iterables yield the same sequence of arrays. """ for arr1, arr2 in zip_longest(arrays1, arrays2, fillvalue=None): - assert_false(arr1 is None or arr2 is None) + assert (arr1 is not None and arr2 is not None) assert_array_equal(arr1, arr2) @@ -204,26 +194,30 @@ class suppress_warnings(error_warnings): filter = 'ignore' -@_deprecate_with_version('catch_warn_reset is deprecated; use ' - 'nibabel.testing.clear_and_catch_warnings.', - since='2.1.0', until='3.0.0') -class catch_warn_reset(clear_and_catch_warnings): - pass - - EXTRA_SET = os.environ.get('NIPY_EXTRA_TESTS', '').split(',') def runif_extra_has(test_str): """Decorator checks to see if NIPY_EXTRA_TESTS env var contains test_str""" - return skipif(test_str not in EXTRA_SET, - "Skip {0} tests.".format(test_str)) + return unittest.skipUnless(test_str in EXTRA_SET, "Skip {0} tests.".format(test_str)) def assert_arr_dict_equal(dict1, dict2): """ Assert that two dicts are equal, where dicts contain arrays """ - assert_equal(set(dict1), set(dict2)) + assert set(dict1) == set(dict2) for key, value1 in dict1.items(): value2 = dict2[key] assert_array_equal(value1, value2) + + +class BaseTestCase(unittest.TestCase): + """ TestCase that does not attempt to run if prefixed with a ``_`` + + This restores the nose-like behavior of skipping so-named test cases + in test runners like pytest. + """ + def setUp(self): + if self.__class__.__name__.startswith('_'): + raise unittest.SkipTest("Base test case - subclass to run") + super().setUp() diff --git a/nibabel/testing_pytest/helpers.py b/nibabel/testing/helpers.py similarity index 100% rename from nibabel/testing_pytest/helpers.py rename to nibabel/testing/helpers.py diff --git a/nibabel/testing_pytest/__init__.py b/nibabel/testing_pytest/__init__.py deleted file mode 100644 index 52055ebcc3..0000000000 --- a/nibabel/testing_pytest/__init__.py +++ /dev/null @@ -1,223 +0,0 @@ -# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- -# vi: set ft=python sts=4 ts=4 sw=4 et: -### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## -# -# See COPYING file distributed along with the NiBabel package for the -# copyright and license terms. -# -### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## -''' Utilities for testing ''' - -import re -import os -import sys -import warnings -from pkg_resources import resource_filename - -import unittest - -import numpy as np -from numpy.testing import assert_array_equal - -from .np_features import memmap_after_ufunc -from .helpers import bytesio_filemap, bytesio_round_trip, assert_data_similar - -from itertools import zip_longest - - -def test_data(subdir=None, fname=None): - if subdir is None: - resource = os.path.join('tests', 'data') - elif subdir in ('gifti', 'nicom', 'externals'): - resource = os.path.join(subdir, 'tests', 'data') - else: - raise ValueError("Unknown test data directory: %s" % subdir) - - if fname is not None: - resource = os.path.join(resource, fname) - - return resource_filename('nibabel', resource) - - -# set path to example data -data_path = test_data() - - -def assert_dt_equal(a, b): - """ Assert two numpy dtype specifiers are equal - - Avoids failed comparison between int32 / int64 and intp - """ - assert np.dtype(a).str == np.dtype(b).str - - -def assert_allclose_safely(a, b, match_nans=True, rtol=1e-5, atol=1e-8): - """ Allclose in integers go all wrong for large integers - """ - a = np.atleast_1d(a) # 0d arrays cannot be indexed - a, b = np.broadcast_arrays(a, b) - if match_nans: - nans = np.isnan(a) - assert_array_equal(nans, np.isnan(b)) - to_test = ~nans - else: - to_test = np.ones(a.shape, dtype=bool) - # Deal with float128 inf comparisons (bug in numpy 1.9.2) - # np.allclose(np.float128(np.inf), np.float128(np.inf)) == False - to_test = to_test & (a != b) - a = a[to_test] - b = b[to_test] - if a.dtype.kind in 'ui': - a = a.astype(float) - if b.dtype.kind in 'ui': - b = b.astype(float) - assert np.allclose(a, b, rtol=rtol, atol=atol) - - -def assert_arrays_equal(arrays1, arrays2): - """ Check two iterables yield the same sequence of arrays. """ - for arr1, arr2 in zip_longest(arrays1, arrays2, fillvalue=None): - assert (arr1 is not None and arr2 is not None) - assert_array_equal(arr1, arr2) - - -def assert_re_in(regex, c, flags=0): - """Assert that container (list, str, etc) contains entry matching the regex - """ - if not isinstance(c, (list, tuple)): - c = [c] - for e in c: - if re.match(regex, e, flags=flags): - return - raise AssertionError("Not a single entry matched %r in %r" % (regex, c)) - - -def get_fresh_mod(mod_name=__name__): - # Get this module, with warning registry empty - my_mod = sys.modules[mod_name] - try: - my_mod.__warningregistry__.clear() - except AttributeError: - pass - return my_mod - - -class clear_and_catch_warnings(warnings.catch_warnings): - """ Context manager that resets warning registry for catching warnings - - Warnings can be slippery, because, whenever a warning is triggered, Python - adds a ``__warningregistry__`` member to the *calling* module. This makes - it impossible to retrigger the warning in this module, whatever you put in - the warnings filters. This context manager accepts a sequence of `modules` - as a keyword argument to its constructor and: - - * stores and removes any ``__warningregistry__`` entries in given `modules` - on entry; - * resets ``__warningregistry__`` to its previous state on exit. - - This makes it possible to trigger any warning afresh inside the context - manager without disturbing the state of warnings outside. - - For compatibility with Python 3.0, please consider all arguments to be - keyword-only. - - Parameters - ---------- - record : bool, optional - Specifies whether warnings should be captured by a custom - implementation of ``warnings.showwarning()`` and be appended to a list - returned by the context manager. Otherwise None is returned by the - context manager. The objects appended to the list are arguments whose - attributes mirror the arguments to ``showwarning()``. - - NOTE: nibabel difference from numpy: default is True - - modules : sequence, optional - Sequence of modules for which to reset warnings registry on entry and - restore on exit - - Examples - -------- - >>> import warnings - >>> with clear_and_catch_warnings(modules=[np.core.fromnumeric]): - ... warnings.simplefilter('always') - ... # do something that raises a warning in np.core.fromnumeric - """ - class_modules = () - - def __init__(self, record=True, modules=()): - self.modules = set(modules).union(self.class_modules) - self._warnreg_copies = {} - super(clear_and_catch_warnings, self).__init__(record=record) - - def __enter__(self): - for mod in self.modules: - if hasattr(mod, '__warningregistry__'): - mod_reg = mod.__warningregistry__ - self._warnreg_copies[mod] = mod_reg.copy() - mod_reg.clear() - return super(clear_and_catch_warnings, self).__enter__() - - def __exit__(self, *exc_info): - super(clear_and_catch_warnings, self).__exit__(*exc_info) - for mod in self.modules: - if hasattr(mod, '__warningregistry__'): - mod.__warningregistry__.clear() - if mod in self._warnreg_copies: - mod.__warningregistry__.update(self._warnreg_copies[mod]) - - -class error_warnings(clear_and_catch_warnings): - """ Context manager to check for warnings as errors. Usually used with - ``assert_raises`` in the with block - - Examples - -------- - >>> with error_warnings(): - ... try: - ... warnings.warn('Message', UserWarning) - ... except UserWarning: - ... print('I consider myself warned') - I consider myself warned - """ - filter = 'error' - - def __enter__(self): - mgr = super(error_warnings, self).__enter__() - warnings.simplefilter(self.filter) - return mgr - - -class suppress_warnings(error_warnings): - """ Version of ``catch_warnings`` class that suppresses warnings - """ - filter = 'ignore' - - -EXTRA_SET = os.environ.get('NIPY_EXTRA_TESTS', '').split(',') - - -def runif_extra_has(test_str): - """Decorator checks to see if NIPY_EXTRA_TESTS env var contains test_str""" - return unittest.skipUnless(test_str in EXTRA_SET, "Skip {0} tests.".format(test_str)) - - -def assert_arr_dict_equal(dict1, dict2): - """ Assert that two dicts are equal, where dicts contain arrays - """ - assert set(dict1) == set(dict2) - for key, value1 in dict1.items(): - value2 = dict2[key] - assert_array_equal(value1, value2) - - -class BaseTestCase(unittest.TestCase): - """ TestCase that does not attempt to run if prefixed with a ``_`` - - This restores the nose-like behavior of skipping so-named test cases - in test runners like pytest. - """ - def setUp(self): - if self.__class__.__name__.startswith('_'): - raise unittest.SkipTest("Base test case - subclass to run") - super().setUp() diff --git a/nibabel/testing_pytest/np_features.py b/nibabel/testing_pytest/np_features.py deleted file mode 100644 index 8919542d1c..0000000000 --- a/nibabel/testing_pytest/np_features.py +++ /dev/null @@ -1,23 +0,0 @@ -""" Look for changes in numpy behavior over versions -""" - -import numpy as np - - -def memmap_after_ufunc(): - """ Return True if ufuncs on memmap arrays always return memmap arrays - - This should be True for numpy < 1.12, False otherwise. - - Memoize after first call. We do this to avoid having to call this when - importing nibabel.testing, because we cannot depend on the source file - being present - see gh-571. - """ - if memmap_after_ufunc.result is not None: - return memmap_after_ufunc.result - with open(__file__, 'rb') as fobj: - mm_arr = np.memmap(fobj, mode='r', shape=(10,), dtype=np.uint8) - memmap_after_ufunc.result = isinstance(mm_arr + 1, np.memmap) - return memmap_after_ufunc.result - -memmap_after_ufunc.result = None diff --git a/nibabel/tests/test_analyze.py b/nibabel/tests/test_analyze.py index 2b2e78dd23..b092a2334c 100644 --- a/nibabel/tests/test_analyze.py +++ b/nibabel/tests/test_analyze.py @@ -34,11 +34,11 @@ import pytest from numpy.testing import (assert_array_equal, assert_array_almost_equal) -from ..testing_pytest import (data_path, suppress_warnings, assert_dt_equal) +from ..testing import (data_path, suppress_warnings, assert_dt_equal, + bytesio_filemap, bytesio_round_trip) from .test_wrapstruct import _TestLabeledWrapStruct from . import test_spatialimages as tsi -from ..testing_pytest import bytesio_filemap, bytesio_round_trip header_file = os.path.join(data_path, 'analyze.hdr') diff --git a/nibabel/tests/test_arrayproxy.py b/nibabel/tests/test_arrayproxy.py index 7b2fcca384..2a509acb88 100644 --- a/nibabel/tests/test_arrayproxy.py +++ b/nibabel/tests/test_arrayproxy.py @@ -27,7 +27,7 @@ from numpy.testing import assert_array_equal, assert_array_almost_equal import pytest -from ..testing_pytest import memmap_after_ufunc +from ..testing import memmap_after_ufunc from .test_fileslice import slicer_samples from .test_openers import patch_indexed_gzip diff --git a/nibabel/tests/test_arraywriters.py b/nibabel/tests/test_arraywriters.py index 1a1c4eb156..380126d4d4 100644 --- a/nibabel/tests/test_arraywriters.py +++ b/nibabel/tests/test_arraywriters.py @@ -16,8 +16,8 @@ from numpy.testing import assert_array_almost_equal, assert_array_equal import pytest -from ..testing_pytest import (assert_allclose_safely, suppress_warnings, - error_warnings) +from ..testing import (assert_allclose_safely, suppress_warnings, + error_warnings) FLOAT_TYPES = np.sctypes['float'] diff --git a/nibabel/tests/test_brikhead.py b/nibabel/tests/test_brikhead.py index 60bd008a46..45e149b93b 100644 --- a/nibabel/tests/test_brikhead.py +++ b/nibabel/tests/test_brikhead.py @@ -16,7 +16,7 @@ import pytest from numpy.testing import assert_array_equal -from ..testing_pytest import data_path, assert_data_similar +from ..testing import data_path, assert_data_similar from .test_fileslice import slicer_samples diff --git a/nibabel/tests/test_casting.py b/nibabel/tests/test_casting.py index c4f9b9ba9e..b8f56454b5 100644 --- a/nibabel/tests/test_casting.py +++ b/nibabel/tests/test_casting.py @@ -8,7 +8,7 @@ from ..casting import (float_to_int, shared_range, CastingError, int_to_float, as_int, int_abs, floor_log2, able_int_type, best_float, ulp, longdouble_precision_improved) -from ..testing_pytest import suppress_warnings +from ..testing import suppress_warnings from numpy.testing import (assert_array_almost_equal, assert_array_equal) diff --git a/nibabel/tests/test_deprecator.py b/nibabel/tests/test_deprecator.py index c508795cf9..cf56dd598d 100644 --- a/nibabel/tests/test_deprecator.py +++ b/nibabel/tests/test_deprecator.py @@ -10,7 +10,7 @@ from nibabel.deprecator import (_ensure_cr, _add_dep_doc, ExpiredDeprecationError, Deprecator) -from ..testing_pytest import clear_and_catch_warnings +from ..testing import clear_and_catch_warnings _OWN_MODULE = sys.modules[__name__] diff --git a/nibabel/tests/test_dft.py b/nibabel/tests/test_dft.py index 9c3a4f5d85..c7c80b0dd9 100644 --- a/nibabel/tests/test_dft.py +++ b/nibabel/tests/test_dft.py @@ -4,7 +4,7 @@ import os from os.path import join as pjoin, dirname from io import BytesIO -from ..testing_pytest import suppress_warnings +from ..testing import suppress_warnings with suppress_warnings(): from .. import dft diff --git a/nibabel/tests/test_ecat.py b/nibabel/tests/test_ecat.py index 918cffc52b..a346c71569 100644 --- a/nibabel/tests/test_ecat.py +++ b/nibabel/tests/test_ecat.py @@ -21,7 +21,7 @@ from numpy.testing import assert_array_equal, assert_array_almost_equal -from ..testing_pytest import data_path, suppress_warnings +from ..testing import data_path, suppress_warnings from ..tmpdirs import InTemporaryDirectory from .test_wrapstruct import _TestWrapStructBase diff --git a/nibabel/tests/test_floating.py b/nibabel/tests/test_floating.py index da5f2b6e2b..e419eb8868 100644 --- a/nibabel/tests/test_floating.py +++ b/nibabel/tests/test_floating.py @@ -9,7 +9,7 @@ int_to_float, floor_log2, type_info, _check_nmant, _check_maxexp, ok_floats, on_powerpc, have_binary128, longdouble_precision_improved) -from ..testing_pytest import suppress_warnings +from ..testing import suppress_warnings import pytest diff --git a/nibabel/tests/test_image_api.py b/nibabel/tests/test_image_api.py index f6245aa594..8af303914b 100644 --- a/nibabel/tests/test_image_api.py +++ b/nibabel/tests/test_image_api.py @@ -45,8 +45,8 @@ import pytest from numpy.testing import assert_almost_equal, assert_array_equal, assert_warns, assert_allclose -from ..testing_pytest import (bytesio_round_trip, bytesio_filemap, - assert_data_similar, clear_and_catch_warnings) +from ..testing import (bytesio_round_trip, bytesio_filemap, + assert_data_similar, clear_and_catch_warnings) from ..tmpdirs import InTemporaryDirectory from ..deprecator import ExpiredDeprecationError diff --git a/nibabel/tests/test_imageclasses.py b/nibabel/tests/test_imageclasses.py index 8fc0da4908..193cf38cb9 100644 --- a/nibabel/tests/test_imageclasses.py +++ b/nibabel/tests/test_imageclasses.py @@ -16,7 +16,7 @@ from nibabel.imageclasses import spatial_axes_first, class_map, ext_map -from nibabel.testing_pytest import clear_and_catch_warnings +from nibabel.testing import clear_and_catch_warnings DATA_DIR = pjoin(dirname(__file__), 'data') diff --git a/nibabel/tests/test_minc1.py b/nibabel/tests/test_minc1.py index 837957e566..a908ee6ad9 100644 --- a/nibabel/tests/test_minc1.py +++ b/nibabel/tests/test_minc1.py @@ -25,7 +25,7 @@ from ..tmpdirs import InTemporaryDirectory from ..deprecator import ExpiredDeprecationError -from ..testing_pytest import assert_data_similar, data_path, clear_and_catch_warnings +from ..testing import assert_data_similar, data_path, clear_and_catch_warnings from numpy.testing import assert_array_equal import pytest diff --git a/nibabel/tests/test_minc2.py b/nibabel/tests/test_minc2.py index 5032f01480..2c2f5c6e51 100644 --- a/nibabel/tests/test_minc2.py +++ b/nibabel/tests/test_minc2.py @@ -15,7 +15,7 @@ from ..minc2 import Minc2File, Minc2Image from .._h5py_compat import h5py, have_h5py, setup_module -from ..testing_pytest import data_path +from ..testing import data_path from . import test_minc1 as tm2 diff --git a/nibabel/tests/test_nifti1.py b/nibabel/tests/test_nifti1.py index 1bb4e5ae2e..6ee1926d8d 100644 --- a/nibabel/tests/test_nifti1.py +++ b/nibabel/tests/test_nifti1.py @@ -30,16 +30,17 @@ from .test_arraywriters import rt_err_estimate, IUINT_TYPES from .test_orientations import ALL_ORNTS from .nibabel_data import get_nibabel_data, needs_nibabel_data -from ..testing_pytest import bytesio_filemap, bytesio_round_trip from numpy.testing import (assert_array_equal, assert_array_almost_equal, assert_almost_equal) -from ..testing_pytest import ( +from ..testing import ( clear_and_catch_warnings, data_path, runif_extra_has, suppress_warnings, + bytesio_filemap, + bytesio_round_trip ) import pytest diff --git a/nibabel/tests/test_nifti2.py b/nibabel/tests/test_nifti2.py index 7f9d32b6b9..d0daf9632e 100644 --- a/nibabel/tests/test_nifti2.py +++ b/nibabel/tests/test_nifti2.py @@ -21,7 +21,7 @@ from numpy.testing import assert_array_equal -from ..testing_pytest import data_path +from ..testing import data_path header_file = os.path.join(data_path, 'nifti2.hdr') image_file = os.path.join(data_path, 'example_nifti2.nii.gz') diff --git a/nibabel/tests/test_openers.py b/nibabel/tests/test_openers.py index d9d728046e..43712d11bf 100644 --- a/nibabel/tests/test_openers.py +++ b/nibabel/tests/test_openers.py @@ -20,7 +20,7 @@ from unittest import mock import pytest -from ..testing_pytest import error_warnings +from ..testing import error_warnings class Lunk(object): diff --git a/nibabel/tests/test_parrec.py b/nibabel/tests/test_parrec.py index fe607c1982..4c55179672 100644 --- a/nibabel/tests/test_parrec.py +++ b/nibabel/tests/test_parrec.py @@ -21,7 +21,7 @@ assert_array_equal) import pytest -from ..testing_pytest import (clear_and_catch_warnings, suppress_warnings, +from ..testing import (clear_and_catch_warnings, suppress_warnings, assert_arr_dict_equal) from .test_arrayproxy import check_mmap diff --git a/nibabel/tests/test_proxy_api.py b/nibabel/tests/test_proxy_api.py index f8e25c14cc..a5a9e9e051 100644 --- a/nibabel/tests/test_proxy_api.py +++ b/nibabel/tests/test_proxy_api.py @@ -55,7 +55,7 @@ import pytest from numpy.testing import assert_almost_equal, assert_array_equal, assert_allclose -from ..testing_pytest import data_path as DATA_PATH, assert_dt_equal, clear_and_catch_warnings +from ..testing import data_path as DATA_PATH, assert_dt_equal, clear_and_catch_warnings from ..deprecator import ExpiredDeprecationError from ..tmpdirs import InTemporaryDirectory diff --git a/nibabel/tests/test_scaling.py b/nibabel/tests/test_scaling.py index db901adb61..e916770dab 100644 --- a/nibabel/tests/test_scaling.py +++ b/nibabel/tests/test_scaling.py @@ -13,7 +13,7 @@ from io import BytesIO from ..volumeutils import finite_range, apply_read_scaling, array_to_file, array_from_file from ..casting import type_info -from ..testing_pytest import suppress_warnings +from ..testing import suppress_warnings from .test_volumeutils import _calculate_scale diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index c8c87092bf..1ed6870f07 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -30,7 +30,7 @@ from .test_parrec import (DTI_PAR_BVECS, DTI_PAR_BVALS, EXAMPLE_IMAGES as PARREC_EXAMPLES) from .test_parrec_data import BALLS, AFF_OFF -from ..testing_pytest import assert_data_similar +from ..testing import assert_data_similar def _proc_stdout(stdout): diff --git a/nibabel/tests/test_spatialimages.py b/nibabel/tests/test_spatialimages.py index 82da89b3d7..a2a8ddc79d 100644 --- a/nibabel/tests/test_spatialimages.py +++ b/nibabel/tests/test_spatialimages.py @@ -22,7 +22,7 @@ from unittest import TestCase from numpy.testing import assert_array_almost_equal -from ..testing_pytest import ( +from ..testing import ( bytesio_round_trip, clear_and_catch_warnings, suppress_warnings, @@ -654,4 +654,4 @@ class MyHeader(Header): assert len(w) == 0 MyHeader() - assert len(w) == 1 \ No newline at end of file + assert len(w) == 1 diff --git a/nibabel/tests/test_spm99analyze.py b/nibabel/tests/test_spm99analyze.py index 3198c43ea7..e84a18ea4f 100644 --- a/nibabel/tests/test_spm99analyze.py +++ b/nibabel/tests/test_spm99analyze.py @@ -29,7 +29,7 @@ from ..volumeutils import apply_read_scaling, _dt_min_max from ..spatialimages import supported_np_types, HeaderDataError -from ..testing_pytest import ( +from ..testing import ( bytesio_round_trip, bytesio_filemap, assert_allclose_safely, diff --git a/nibabel/tests/test_testing.py b/nibabel/tests/test_testing.py index 65880c2833..32b77fac6c 100644 --- a/nibabel/tests/test_testing.py +++ b/nibabel/tests/test_testing.py @@ -7,7 +7,7 @@ import numpy as np -from ..testing_pytest import (error_warnings, suppress_warnings, +from ..testing import (error_warnings, suppress_warnings, clear_and_catch_warnings, assert_allclose_safely, get_fresh_mod, assert_re_in, test_data, data_path) import pytest diff --git a/nibabel/tests/test_volumeutils.py b/nibabel/tests/test_volumeutils.py index dca5053d74..8b0b6a52cf 100644 --- a/nibabel/tests/test_volumeutils.py +++ b/nibabel/tests/test_volumeutils.py @@ -57,7 +57,7 @@ assert_array_equal) import pytest -from ..testing_pytest import assert_dt_equal, assert_allclose_safely, suppress_warnings +from ..testing import assert_dt_equal, assert_allclose_safely, suppress_warnings #: convenience variables for numpy types FLOAT_TYPES = np.sctypes['float'] diff --git a/nibabel/tests/test_wrapstruct.py b/nibabel/tests/test_wrapstruct.py index 32035db995..883c0ec147 100644 --- a/nibabel/tests/test_wrapstruct.py +++ b/nibabel/tests/test_wrapstruct.py @@ -34,7 +34,7 @@ from ..spatialimages import HeaderDataError from .. import imageglobals -from ..testing_pytest import BaseTestCase +from ..testing import BaseTestCase from numpy.testing import assert_array_equal import pytest From 01172127e2e85b5d3431260b426d6295a44d2441 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 18 Feb 2020 08:27:31 -0500 Subject: [PATCH 208/223] TEST: Remove last imports of nose --- nibabel/nicom/tests/test_dwiparams.py | 14 ++-- nibabel/streamlines/tests/test_streamlines.py | 76 +++++++++---------- .../streamlines/tests/test_tractogram_file.py | 21 ++--- nibabel/streamlines/tests/test_utils.py | 6 +- 4 files changed, 62 insertions(+), 55 deletions(-) diff --git a/nibabel/nicom/tests/test_dwiparams.py b/nibabel/nicom/tests/test_dwiparams.py index 3b02367951..d0d20e574a 100644 --- a/nibabel/nicom/tests/test_dwiparams.py +++ b/nibabel/nicom/tests/test_dwiparams.py @@ -6,10 +6,9 @@ from ..dwiparams import B2q, q2bg -from nose.tools import (assert_true, assert_false, assert_equal, assert_raises) +import pytest -from numpy.testing import (assert_array_equal, assert_array_almost_equal, - assert_equal as np_assert_equal) +from numpy.testing import (assert_array_almost_equal, assert_equal as np_assert_equal) def test_b2q(): @@ -27,17 +26,20 @@ def test_b2q(): assert_array_almost_equal(-q * s, B2q(B)) # Massive negative eigs B = np.eye(3) * -1 - assert_raises(ValueError, B2q, B) + with pytest.raises(ValueError): + B2q(B) # no error if we up the tolerance q = B2q(B, tol=1) # Less massive negativity, dropping tol B = np.diag([-1e-14, 10., 1]) - assert_raises(ValueError, B2q, B) + with pytest.raises(ValueError): + B2q(B) assert_array_almost_equal(B2q(B, tol=5e-13), [0, 10, 0]) # Confirm that we assume symmetric B = np.eye(3) B[0, 1] = 1e-5 - assert_raises(ValueError, B2q, B) + with pytest.raises(ValueError): + B2q(B) def test_q2bg(): diff --git a/nibabel/streamlines/tests/test_streamlines.py b/nibabel/streamlines/tests/test_streamlines.py index 2e537c63f2..9a2f803117 100644 --- a/nibabel/streamlines/tests/test_streamlines.py +++ b/nibabel/streamlines/tests/test_streamlines.py @@ -10,9 +10,7 @@ from nibabel.tmpdirs import InTemporaryDirectory from numpy.compat.py3k import asbytes -from nibabel.testing import data_path -from nibabel.testing import clear_and_catch_warnings -from nose.tools import assert_equal, assert_raises, assert_true, assert_false +from nibabel.testing import data_path, clear_and_catch_warnings from .test_tractogram import assert_tractogram_equal from ..tractogram import Tractogram, LazyTractogram @@ -82,50 +80,50 @@ def test_is_supported_detect_format(): # Test is_supported and detect_format functions # Empty file/string f = BytesIO() - assert_false(nib.streamlines.is_supported(f)) - assert_false(nib.streamlines.is_supported("")) - assert_true(nib.streamlines.detect_format(f) is None) - assert_true(nib.streamlines.detect_format("") is None) + assert not nib.streamlines.is_supported(f) + assert not nib.streamlines.is_supported("") + assert nib.streamlines.detect_format(f) is None + assert nib.streamlines.detect_format("") is None # Valid file without extension for tfile_cls in FORMATS.values(): f = BytesIO() f.write(asbytes(tfile_cls.MAGIC_NUMBER)) f.seek(0, os.SEEK_SET) - assert_true(nib.streamlines.is_supported(f)) - assert_true(nib.streamlines.detect_format(f) is tfile_cls) + assert nib.streamlines.is_supported(f) + assert nib.streamlines.detect_format(f) is tfile_cls # Wrong extension but right magic number for tfile_cls in FORMATS.values(): with tempfile.TemporaryFile(mode="w+b", suffix=".txt") as f: f.write(asbytes(tfile_cls.MAGIC_NUMBER)) f.seek(0, os.SEEK_SET) - assert_true(nib.streamlines.is_supported(f)) - assert_true(nib.streamlines.detect_format(f) is tfile_cls) + assert nib.streamlines.is_supported(f) + assert nib.streamlines.detect_format(f) is tfile_cls # Good extension but wrong magic number for ext, tfile_cls in FORMATS.items(): with tempfile.TemporaryFile(mode="w+b", suffix=ext) as f: f.write(b"pass") f.seek(0, os.SEEK_SET) - assert_false(nib.streamlines.is_supported(f)) - assert_true(nib.streamlines.detect_format(f) is None) + assert not nib.streamlines.is_supported(f) + assert nib.streamlines.detect_format(f) is None # Wrong extension, string only f = "my_tractogram.asd" - assert_false(nib.streamlines.is_supported(f)) - assert_true(nib.streamlines.detect_format(f) is None) + assert not nib.streamlines.is_supported(f) + assert nib.streamlines.detect_format(f) is None # Good extension, string only for ext, tfile_cls in FORMATS.items(): f = "my_tractogram" + ext - assert_true(nib.streamlines.is_supported(f)) - assert_equal(nib.streamlines.detect_format(f), tfile_cls) + assert nib.streamlines.is_supported(f) + assert nib.streamlines.detect_format(f) == tfile_cls # Extension should not be case-sensitive. for ext, tfile_cls in FORMATS.items(): f = "my_tractogram" + ext.upper() - assert_true(nib.streamlines.detect_format(f) is tfile_cls) + assert nib.streamlines.detect_format(f) is tfile_cls class TestLoadSave(unittest.TestCase): @@ -135,12 +133,12 @@ def test_load_empty_file(self): for empty_filename in DATA['empty_filenames']: tfile = nib.streamlines.load(empty_filename, lazy_load=lazy_load) - assert_true(isinstance(tfile, TractogramFile)) + assert isinstance(tfile, TractogramFile) if lazy_load: - assert_true(type(tfile.tractogram), Tractogram) + assert type(tfile.tractogram), Tractogram else: - assert_true(type(tfile.tractogram), LazyTractogram) + assert type(tfile.tractogram), LazyTractogram assert_tractogram_equal(tfile.tractogram, DATA['empty_tractogram']) @@ -150,12 +148,12 @@ def test_load_simple_file(self): for simple_filename in DATA['simple_filenames']: tfile = nib.streamlines.load(simple_filename, lazy_load=lazy_load) - assert_true(isinstance(tfile, TractogramFile)) + assert isinstance(tfile, TractogramFile) if lazy_load: - assert_true(type(tfile.tractogram), Tractogram) + assert type(tfile.tractogram), Tractogram else: - assert_true(type(tfile.tractogram), LazyTractogram) + assert type(tfile.tractogram), LazyTractogram assert_tractogram_equal(tfile.tractogram, DATA['simple_tractogram']) @@ -165,12 +163,12 @@ def test_load_complex_file(self): for complex_filename in DATA['complex_filenames']: tfile = nib.streamlines.load(complex_filename, lazy_load=lazy_load) - assert_true(isinstance(tfile, TractogramFile)) + assert isinstance(tfile, TractogramFile) if lazy_load: - assert_true(type(tfile.tractogram), Tractogram) + assert type(tfile.tractogram), Tractogram else: - assert_true(type(tfile.tractogram), LazyTractogram) + assert type(tfile.tractogram), LazyTractogram tractogram = Tractogram(DATA['streamlines'], affine_to_rasmm=np.eye(4)) @@ -191,19 +189,19 @@ def test_save_tractogram_file(self): trk_file = trk.TrkFile(tractogram) # No need for keyword arguments. - assert_raises(ValueError, nib.streamlines.save, - trk_file, "dummy.trk", header={}) + with self.assertRaises(ValueError): + nib.streamlines.save(trk_file, "dummy.trk", header={}) # Wrong extension. with clear_and_catch_warnings(record=True, modules=[nib.streamlines]) as w: trk_file = trk.TrkFile(tractogram) - assert_raises(ValueError, nib.streamlines.save, - trk_file, "dummy.tck", header={}) + with self.assertRaises(ValueError): + nib.streamlines.save(trk_file, "dummy.tck", header={}) - assert_equal(len(w), 1) - assert_true(issubclass(w[0].category, ExtensionWarning)) - assert_true("extension" in str(w[0].message)) + assert len(w) == 1 + assert issubclass(w[0].category, ExtensionWarning) + assert "extension" in str(w[0].message) with InTemporaryDirectory(): nib.streamlines.save(trk_file, "dummy.trk") @@ -250,9 +248,9 @@ def test_save_complex_file(self): ((not cls.SUPPORTS_DATA_PER_POINT) + (not cls.SUPPORTS_DATA_PER_STREAMLINE)) - assert_equal(len(w), nb_expected_warnings) + assert len(w) == nb_expected_warnings for i in range(nb_expected_warnings): - assert_true(issubclass(w[i].category, Warning)) + assert issubclass(w[i].category, Warning) tractogram = Tractogram(DATA['streamlines'], affine_to_rasmm=np.eye(4)) @@ -281,10 +279,12 @@ def test_save_sliced_tractogram(self): assert_tractogram_equal(tractogram, original_tractogram) def test_load_unknown_format(self): - assert_raises(ValueError, nib.streamlines.load, "") + with self.assertRaises(ValueError): + nib.streamlines.load("") def test_save_unknown_format(self): - assert_raises(ValueError, nib.streamlines.save, Tractogram(), "") + with self.assertRaises(ValueError): + nib.streamlines.save(Tractogram(), "") def test_save_from_generator(self): tractogram = Tractogram(DATA['streamlines'], diff --git a/nibabel/streamlines/tests/test_tractogram_file.py b/nibabel/streamlines/tests/test_tractogram_file.py index da5bce4b3f..2550ecf03d 100644 --- a/nibabel/streamlines/tests/test_tractogram_file.py +++ b/nibabel/streamlines/tests/test_tractogram_file.py @@ -4,7 +4,7 @@ from ..tractogram import Tractogram from ..tractogram_file import TractogramFile -from nose.tools import assert_raises, assert_equal +import pytest def test_subclassing_tractogram_file(): @@ -23,7 +23,8 @@ def load(cls, fileobj, lazy_load=True): def create_empty_header(cls): return None - assert_raises(TypeError, DummyTractogramFile, Tractogram()) + with pytest.raises(TypeError): + DummyTractogramFile(Tractogram()) # Missing 'load' method class DummyTractogramFile(TractogramFile): @@ -38,7 +39,8 @@ def save(self, fileobj): def create_empty_header(cls): return None - assert_raises(TypeError, DummyTractogramFile, Tractogram()) + with pytest.raises(TypeError): + DummyTractogramFile(Tractogram()) # Now we have everything required. class DummyTractogramFile(TractogramFile): @@ -57,12 +59,14 @@ def save(self, fileobj): dtf = DummyTractogramFile(Tractogram()) # Default create_empty_header is empty dict - assert_equal(dtf.header, {}) + assert dtf.header == {} def test_tractogram_file(): - assert_raises(NotImplementedError, TractogramFile.is_correct_format, "") - assert_raises(NotImplementedError, TractogramFile.load, "") + with pytest.raises(NotImplementedError): + TractogramFile.is_correct_format("") + with pytest.raises(NotImplementedError): + TractogramFile.load("") # Testing calling the 'save' method of `TractogramFile` object. class DummyTractogramFile(TractogramFile): @@ -78,6 +82,5 @@ def load(cls, fileobj, lazy_load=True): def save(self, fileobj): pass - assert_raises(NotImplementedError, - super(DummyTractogramFile, - DummyTractogramFile(Tractogram)).save, "") + with pytest.raises(NotImplementedError): + super(DummyTractogramFile, DummyTractogramFile(Tractogram)).save("") diff --git a/nibabel/streamlines/tests/test_utils.py b/nibabel/streamlines/tests/test_utils.py index 939ee9bb9e..bcdde6d013 100644 --- a/nibabel/streamlines/tests/test_utils.py +++ b/nibabel/streamlines/tests/test_utils.py @@ -4,7 +4,8 @@ from nibabel.testing import data_path from numpy.testing import assert_array_equal -from nose.tools import assert_raises + +import pytest from ..utils import get_affine_from_reference @@ -17,7 +18,8 @@ def test_get_affine_from_reference(): # Get affine from an numpy array. assert_array_equal(get_affine_from_reference(affine), affine) wrong_ref = np.array([[1, 2, 3], [4, 5, 6]]) - assert_raises(ValueError, get_affine_from_reference, wrong_ref) + with pytest.raises(ValueError): + get_affine_from_reference(wrong_ref) # Get affine from a `SpatialImage`. assert_array_equal(get_affine_from_reference(img), affine) From c9d9eba5ee1e51d53a3398257c9e55b6be12b2c7 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 18 Feb 2020 08:31:21 -0500 Subject: [PATCH 209/223] MNT: Purge nose from requirements, CI --- .azure-pipelines/windows.yml | 18 ------------------ .travis.yml | 21 --------------------- azure-pipelines.yml | 4 ---- dev-requirements.txt | 1 - setup.cfg | 5 ----- 5 files changed, 49 deletions(-) diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index fcdd542223..970a3b788d 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -36,24 +36,6 @@ jobs: python -m pip install .[$(CHECK_TYPE)] SET NIBABEL_DATA_DIR=%CD%\\nibabel-data displayName: 'Install nibabel' - - script: | - mkdir for_testing - cd for_testing - cp ../.coveragerc . - nosetests --with-doctest --with-coverage --cover-package nibabel nibabel ^ - -I test_data ^ - -I test_environment ^ - -I test_euler ^ - -I test_giftiio ^ - -I test_netcdf ^ - -I test_pkg_info ^ - -I test_quaternions ^ - -I test_scaling ^ - -I test_scripts ^ - -I test_spaces ^ - -I test_testing - displayName: 'Nose tests' - condition: and(succeeded(), eq(variables['CHECK_TYPE'], 'nosetests')) - script: | mkdir for_testing cd for_testing diff --git a/.travis.yml b/.travis.yml index 9ca407a757..88bd146c14 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,10 +27,6 @@ python: jobs: include: - # Old nosetests - Remove soon - - python: 3.7 - env: - - CHECK_TYPE="nosetests" # Basic dependencies only - python: 3.5 env: @@ -127,23 +123,6 @@ script: cd doc make html; make doctest; - elif [ "${CHECK_TYPE}" == "nosetests" ]; then - # Change into an innocuous directory and find tests from installation - mkdir for_testing - cd for_testing - cp ../.coveragerc . - nosetests --with-doctest --with-coverage --cover-package nibabel nibabel \ - -I test_data \ - -I test_environment \ - -I test_euler \ - -I test_giftiio \ - -I test_netcdf \ - -I test_pkg_info \ - -I test_quaternions \ - -I test_scaling \ - -I test_scripts \ - -I test_spaces \ - -I test_testing elif [ "${CHECK_TYPE}" == "test" ]; then # Change into an innocuous directory and find tests from installation mkdir for_testing diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 2ef2539c74..d09c5b7740 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -34,7 +34,3 @@ jobs: py38-x64: PYTHON_VERSION: '3.8' PYTHON_ARCH: 'x64' - nosetests: - PYTHON_VERSION: '3.6' - PYTHON_ARCH: 'x64' - CHECK_TYPE: 'nosetests' diff --git a/dev-requirements.txt b/dev-requirements.txt index aa0980c3b4..69302061bc 100644 --- a/dev-requirements.txt +++ b/dev-requirements.txt @@ -1,4 +1,3 @@ # Requirements for running tests -r requirements.txt -nose pytest diff --git a/setup.cfg b/setup.cfg index 13edca59ab..fd3e3407e1 100644 --- a/setup.cfg +++ b/setup.cfg @@ -55,13 +55,8 @@ spm = scipy style = flake8 -nosetests = - coverage - nose >=0.11 - pytest test = coverage - nose >=0.11 pytest !=5.3.4 pytest-cov all = From 1c6ea64ae34caf322b7a89f02346b781a656f454 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 18 Feb 2020 11:23:34 -0500 Subject: [PATCH 210/223] RF: Remove nose test state code --- nibabel/__init__.py | 23 ----------------------- 1 file changed, 23 deletions(-) diff --git a/nibabel/__init__.py b/nibabel/__init__.py index 2d3428289c..4cdc6018e6 100644 --- a/nibabel/__init__.py +++ b/nibabel/__init__.py @@ -36,29 +36,6 @@ For more detailed information see the :ref:`manual`. """ -# Package-wide test setup and teardown -_test_states = { - # Numpy changed print options in 1.14; we can update docstrings and remove - # these when our minimum for building docs exceeds that - 'legacy_printopt': None, - } - -def setup_package(): - """ Set numpy print style to legacy="1.13" for newer versions of numpy """ - import numpy as np - from distutils.version import LooseVersion - if LooseVersion(np.__version__) >= LooseVersion('1.14'): - if _test_states.get('legacy_printopt') is None: - _test_states['legacy_printopt'] = np.get_printoptions().get('legacy') - np.set_printoptions(legacy="1.13") - -def teardown_package(): - """ Reset print options when tests finish """ - import numpy as np - if _test_states.get('legacy_printopt') is not None: - np.set_printoptions(legacy=_test_states.pop('legacy_printopt')) - - # module imports from . import analyze as ana from . import spm99analyze as spm99 From ff922aa988f0ef446a579fc7a0f05653b51de847 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 18 Feb 2020 11:24:26 -0500 Subject: [PATCH 211/223] RF: Reimplement nibabel.test() and nibabel.bench() --- nibabel/__init__.py | 102 ++++++++++++++++++++++-- nibabel/benchmarks/pytest.benchmark.ini | 4 + setup.cfg | 1 + 3 files changed, 102 insertions(+), 5 deletions(-) create mode 100644 nibabel/benchmarks/pytest.benchmark.ini diff --git a/nibabel/__init__.py b/nibabel/__init__.py index 4cdc6018e6..7c096a0033 100644 --- a/nibabel/__init__.py +++ b/nibabel/__init__.py @@ -69,13 +69,105 @@ from . import streamlines from . import viewers -from numpy.testing import Tester -test = Tester().test -bench = Tester().bench -del Tester - from .pkg_info import get_pkg_info as _get_pkg_info def get_info(): return _get_pkg_info(os.path.dirname(__file__)) + + +def test(label=None, verbose=1, extra_argv=None, + doctests=False, coverage=False, raise_warnings=None, + timer=False): + """ + Run tests for nibabel using pytest + + The protocol mimics the ``numpy.testing.NoseTester.test()``. + Not all features are currently implemented. + + Parameters + ---------- + label : None + Unused. + verbose: int, optional + Verbosity value for test outputs. Positive values increase verbosity, and + negative values decrease it. Default is 1. + extra_argv : list, optional + List with any extra arguments to pass to pytest. + doctests: bool, optional + If True, run doctests in module. Default is False. + coverage: bool, optional + If True, report coverage of NumPy code. Default is False. + (This requires the + `coverage module `_). + raise_warnings : None + Unused. + timer : False + Unused. + + Returns + ------- + code : ExitCode + Returns the result of running the tests as a ``pytest.ExitCode`` enum + """ + import pytest + args = [] + + if label is not None: + raise NotImplementedError("Labels cannot be set at present") + + try: + verbose = int(verbose) + except ValueError: + pass + else: + if verbose > 0: + args.append("-" + "v" * verbose) + elif verbose < 0: + args.append("-" + "q" * -verbose) + + if extra_argv: + args.extend(extra_argv) + if doctests: + args.append("--doctest-modules") + if coverage: + args.extend(["--cov", "nibabel"]) + if raise_warnings: + raise NotImplementedError("Warning filters are not implemented") + if timer: + raise NotImplementedError("Timing is not implemented") + + args.extend(["--pyargs", "nibabel"]) + + pytest.main(args=args) + + +def bench(label=None, verbose=1, extra_argv=None): + """ + Run benchmarks for nibabel using pytest + + The protocol mimics the ``numpy.testing.NoseTester.bench()``. + Not all features are currently implemented. + + Parameters + ---------- + label : None + Unused. + verbose: int, optional + Verbosity value for test outputs. Positive values increase verbosity, and + negative values decrease it. Default is 1. + extra_argv : list, optional + List with any extra arguments to pass to pytest. + + Returns + ------- + code : ExitCode + Returns the result of running the tests as a ``pytest.ExitCode`` enum + """ + from pkg_resources import resource_filename + config = resource_filename("nibabel", "benchmarks/pytest.benchmark.ini") + args = [] + if extra_argv is not None: + args.extend(extra_argv) + args.extend(["-c", config]) + test(label, verbose, extra_argv=args) diff --git a/nibabel/benchmarks/pytest.benchmark.ini b/nibabel/benchmarks/pytest.benchmark.ini new file mode 100644 index 0000000000..734e6c7d4c --- /dev/null +++ b/nibabel/benchmarks/pytest.benchmark.ini @@ -0,0 +1,4 @@ +[pytest] +python_files = bench_*.py +python_functions = bench_* +addopts = --capture=no diff --git a/setup.cfg b/setup.cfg index fd3e3407e1..a180f71c8d 100644 --- a/setup.cfg +++ b/setup.cfg @@ -82,6 +82,7 @@ console_scripts = nibabel = tests/data/* */tests/data/* + benchmarks/pytest.benchmark.ini [flake8] max-line-length = 100 From 6dc8f0fecbc204f9a11cea0d2b273e77fca55a59 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 18 Feb 2020 11:27:39 -0500 Subject: [PATCH 212/223] DOC: Replace nose with pytest in the docs --- doc/source/devel/advanced_testing.rst | 2 +- doc/source/devel/make_release.rst | 2 +- doc/source/installation.rst | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/doc/source/devel/advanced_testing.rst b/doc/source/devel/advanced_testing.rst index 0dc365ea1d..77b6522cb1 100644 --- a/doc/source/devel/advanced_testing.rst +++ b/doc/source/devel/advanced_testing.rst @@ -25,7 +25,7 @@ Long-running tests Long-running tests are not enabled by default, and can be resource-intensive. To run these tests: * Set environment variable ``NIPY_EXTRA_TESTS=slow``; -* Run ``nosetests``. +* Run ``pytest nibabel``. Note that some tests may require a machine with >4GB of RAM. diff --git a/doc/source/devel/make_release.rst b/doc/source/devel/make_release.rst index 25db5210b7..6a09d280b2 100644 --- a/doc/source/devel/make_release.rst +++ b/doc/source/devel/make_release.rst @@ -79,7 +79,7 @@ Release checklist * Make sure all tests pass (from the nibabel root directory):: - nosetests --with-doctest nibabel + pytest --doctest-modules nibabel * Make sure you are set up to use the ``try_branch.py`` - see https://github.com/nipy/nibotmi/blob/master/install.rst#trying-a-set-of-changes-on-the-buildbots diff --git a/doc/source/installation.rst b/doc/source/installation.rst index ed390578ff..fe02bcdbf2 100644 --- a/doc/source/installation.rst +++ b/doc/source/installation.rst @@ -90,7 +90,7 @@ Requirements * h5py_ (optional, for MINC2 support) * PyDICOM_ 0.9.9 or greater (optional, for DICOM support) * `Python Imaging Library`_ (optional, for PNG conversion in DICOMFS) -* nose_ 0.11 or greater and pytest_ (optional, to run the tests) +* pytest_ (optional, to run the tests) * sphinx_ (optional, to build the documentation) Get the development sources @@ -128,7 +128,7 @@ module to see if everything is fine. It should look something like this:: >>> -To run the nibabel test suite, from the terminal run ``nosetests nibabel`` or +To run the nibabel test suite, from the terminal run ``pytest nibabel`` or ``python -c "import nibabel; nibabel.test()``. To run an extended test suite that validates ``nibabel`` for long-running and From 007925586224fe0fd5243ff1011725adffcc5e8d Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Tue, 18 Feb 2020 11:33:31 -0500 Subject: [PATCH 213/223] DOC: Update benchmark docstrings --- nibabel/benchmarks/bench_array_to_file.py | 8 ++------ nibabel/benchmarks/bench_arrayproxy_slicing.py | 8 ++------ nibabel/benchmarks/bench_fileslice.py | 8 ++------ nibabel/benchmarks/bench_finite_range.py | 8 ++------ nibabel/benchmarks/bench_load_save.py | 8 ++------ nibabel/benchmarks/bench_streamlines.py | 8 ++------ 6 files changed, 12 insertions(+), 36 deletions(-) diff --git a/nibabel/benchmarks/bench_array_to_file.py b/nibabel/benchmarks/bench_array_to_file.py index 4908848685..776a93000c 100644 --- a/nibabel/benchmarks/bench_array_to_file.py +++ b/nibabel/benchmarks/bench_array_to_file.py @@ -5,13 +5,9 @@ import nibabel as nib nib.bench() -If you have doctests enabled by default in nose (with a noserc file or -environment variable), and you have a numpy version <= 1.6.1, this will also -run the doctests, let's hope they pass. +Run this benchmark with:: -Run this benchmark with: - - nosetests -s --match '(?:^|[\\b_\\.//-])[Bb]ench' /path/to/bench_load_save.py + pytest -c /benchmarks/pytest.benchmark.ini /benchmarks/bench_load_save.py """ import sys diff --git a/nibabel/benchmarks/bench_arrayproxy_slicing.py b/nibabel/benchmarks/bench_arrayproxy_slicing.py index 7fe79763d0..2ed9ec9ccd 100644 --- a/nibabel/benchmarks/bench_arrayproxy_slicing.py +++ b/nibabel/benchmarks/bench_arrayproxy_slicing.py @@ -5,13 +5,9 @@ import nibabel as nib nib.bench() -If you have doctests enabled by default in nose (with a noserc file or -environment variable), and you have a numpy version <= 1.6.1, this will also -run the doctests, let's hope they pass. +Run this benchmark with:: -Run this benchmark with: - - nosetests -s --match '(?:^|[\\b_\\.//-])[Bb]ench' /path/to/bench_arrayproxy_slicing.py + pytest -c /benchmarks/pytest.benchmark.ini /benchmarks/bench_arrayproxy_slicing.py """ from timeit import timeit diff --git a/nibabel/benchmarks/bench_fileslice.py b/nibabel/benchmarks/bench_fileslice.py index 764e0390b5..8763784dc6 100644 --- a/nibabel/benchmarks/bench_fileslice.py +++ b/nibabel/benchmarks/bench_fileslice.py @@ -3,13 +3,9 @@ import nibabel as nib nib.bench() -If you have doctests enabled by default in nose (with a noserc file or -environment variable), and you have a numpy version <= 1.6.1, this will also -run the doctests, let's hope they pass. +Run this benchmark with:: -Run this benchmark with: - - nosetests -s --match '(?:^|[\\b_\\.//-])[Bb]ench' /path/to/bench_fileslice.py + pytest -c /benchmarks/pytest.benchmark.ini /benchmarks/bench_fileslice.py """ import sys diff --git a/nibabel/benchmarks/bench_finite_range.py b/nibabel/benchmarks/bench_finite_range.py index 6aa9d9d861..1ca2bf95d0 100644 --- a/nibabel/benchmarks/bench_finite_range.py +++ b/nibabel/benchmarks/bench_finite_range.py @@ -5,13 +5,9 @@ import nibabel as nib nib.bench() -If you have doctests enabled by default in nose (with a noserc file or -environment variable), and you have a numpy version <= 1.6.1, this will also -run the doctests, let's hope they pass. +Run this benchmark with:: -Run this benchmark with: - - nosetests -s --match '(?:^|[\\b_\\.//-])[Bb]ench' /path/to/bench_finite_range + pytest -c /benchmarks/pytest.benchmark.ini /benchmarks/bench_finite_range.py """ import sys diff --git a/nibabel/benchmarks/bench_load_save.py b/nibabel/benchmarks/bench_load_save.py index 59198eac1a..46118df43e 100644 --- a/nibabel/benchmarks/bench_load_save.py +++ b/nibabel/benchmarks/bench_load_save.py @@ -5,13 +5,9 @@ import nibabel as nib nib.bench() -If you have doctests enabled by default in nose (with a noserc file or -environment variable), and you have a numpy version <= 1.6.1, this will also -run the doctests, let's hope they pass. +Run this benchmark with:: -Run this benchmark with: - - nosetests -s --match '(?:^|[\\b_\\.//-])[Bb]ench' /path/to/bench_load_save.py + pytest -c /benchmarks/pytest.benchmark.ini /benchmarks/bench_load_save.py """ import sys diff --git a/nibabel/benchmarks/bench_streamlines.py b/nibabel/benchmarks/bench_streamlines.py index fc1e39f8ad..5c49c9e177 100644 --- a/nibabel/benchmarks/bench_streamlines.py +++ b/nibabel/benchmarks/bench_streamlines.py @@ -5,13 +5,9 @@ import nibabel as nib nib.bench() -If you have doctests enabled by default in nose (with a noserc file or -environment variable), and you have a numpy version <= 1.6.1, this will also run -the doctests, let's hope they pass. +Run this benchmark with:: -Run this benchmark with: - - nosetests -s --match '(?:^|[\\b_\\.//-])[Bb]ench' /path/to/bench_streamlines.py + pytest -c /benchmarks/pytest.benchmark.ini /benchmarks/bench_streamlines.py """ import numpy as np From 154b941e58337a11662d527cba79cd6cfc8eb147 Mon Sep 17 00:00:00 2001 From: "Christopher J. Markiewicz" Date: Tue, 18 Feb 2020 12:30:38 -0500 Subject: [PATCH 214/223] TEST: Final few assert_raises --- nibabel/cmdline/tests/test_utils.py | 6 ++---- nibabel/tests/test_wrapstruct.py | 4 ++-- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/nibabel/cmdline/tests/test_utils.py b/nibabel/cmdline/tests/test_utils.py index eb864c62c0..460f0d40d6 100644 --- a/nibabel/cmdline/tests/test_utils.py +++ b/nibabel/cmdline/tests/test_utils.py @@ -5,8 +5,6 @@ Test running scripts """ -from numpy.testing import assert_raises - import pytest import nibabel as nib @@ -196,10 +194,10 @@ def test_main(): -7.24879837e+00]).astype(dtype="float32")]), ('DATA(md5)', ['0a2576dd6badbb25bfb3b12076df986b', 'b0abbc492b4fd533b2c80d82570062cf'])]) - with assert_raises(SystemExit): + with pytest.raises(SystemExit): np.testing.assert_equal(main(test_names, StringIO()), expected_difference) test_names_2 = [pjoin(data_path, f) for f in ('standard.nii.gz', 'standard.nii.gz')] - with assert_raises(SystemExit): + with pytest.raises(SystemExit): assert main(test_names_2, StringIO()) == "These files are identical." diff --git a/nibabel/tests/test_wrapstruct.py b/nibabel/tests/test_wrapstruct.py index 883c0ec147..d56873d414 100644 --- a/nibabel/tests/test_wrapstruct.py +++ b/nibabel/tests/test_wrapstruct.py @@ -476,14 +476,14 @@ def test_log_checks(self): assert fhdr['an_integer'] == 1 assert (message == 'an_integer should be 1; set an_integer to 1') - assert_raises(*raiser) + pytest.raises(*raiser) # lower case string hdr = HC() hdr['a_str'] = 'Hello' # severity = 20 fhdr, message, raiser = self.log_chk(hdr, 20) assert (message == 'a_str should be lower case; ' 'set a_str to lower case') - assert_raises(*raiser) + pytest.raises(*raiser) def test_logger_error(self): # Check that we can reset the logger and error level From 22d8c65ff0b01ca7a1c398eed7915eb2968e0bef Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Wed, 19 Feb 2020 16:36:59 -0500 Subject: [PATCH 215/223] FIX: Return pytest.main results from nibabel.test/bench --- nibabel/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nibabel/__init__.py b/nibabel/__init__.py index 7c096a0033..32e2fa7009 100644 --- a/nibabel/__init__.py +++ b/nibabel/__init__.py @@ -139,7 +139,7 @@ def test(label=None, verbose=1, extra_argv=None, args.extend(["--pyargs", "nibabel"]) - pytest.main(args=args) + return pytest.main(args=args) def bench(label=None, verbose=1, extra_argv=None): @@ -170,4 +170,4 @@ def bench(label=None, verbose=1, extra_argv=None): if extra_argv is not None: args.extend(extra_argv) args.extend(["-c", config]) - test(label, verbose, extra_argv=args) + return test(label, verbose, extra_argv=args) From 49be50a6053d954caf9a599be00e418accd45426 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Wed, 19 Feb 2020 20:07:38 -0500 Subject: [PATCH 216/223] TEST: Might as well test the testers. Found a bug. --- nibabel/__init__.py | 16 ++++------- nibabel/tests/test_init.py | 59 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 10 deletions(-) create mode 100644 nibabel/tests/test_init.py diff --git a/nibabel/__init__.py b/nibabel/__init__.py index 32e2fa7009..f99e9e0b06 100644 --- a/nibabel/__init__.py +++ b/nibabel/__init__.py @@ -116,15 +116,11 @@ def test(label=None, verbose=1, extra_argv=None, if label is not None: raise NotImplementedError("Labels cannot be set at present") - try: - verbose = int(verbose) - except ValueError: - pass - else: - if verbose > 0: - args.append("-" + "v" * verbose) - elif verbose < 0: - args.append("-" + "q" * -verbose) + verbose = int(verbose) + if verbose > 0: + args.append("-" + "v" * verbose) + elif verbose < 0: + args.append("-" + "q" * -verbose) if extra_argv: args.extend(extra_argv) @@ -132,7 +128,7 @@ def test(label=None, verbose=1, extra_argv=None, args.append("--doctest-modules") if coverage: args.extend(["--cov", "nibabel"]) - if raise_warnings: + if raise_warnings is not None: raise NotImplementedError("Warning filters are not implemented") if timer: raise NotImplementedError("Timing is not implemented") diff --git a/nibabel/tests/test_init.py b/nibabel/tests/test_init.py new file mode 100644 index 0000000000..97f440497e --- /dev/null +++ b/nibabel/tests/test_init.py @@ -0,0 +1,59 @@ +import nibabel as nib +from pkg_resources import resource_filename +import pytest +from unittest import mock + +@pytest.mark.parametrize("verbose, v_args", [(-2, ["-qq"]), + (-1, ["-q"]), + (0, []), + (1, ["-v"]), + (2, ["-vv"])]) +@pytest.mark.parametrize("doctests", (True, False)) +@pytest.mark.parametrize("coverage", (True, False)) +def test_nibabel_test(verbose, v_args, doctests, coverage): + expected_args = v_args + ["--doctest-modules", "--cov", "nibabel", "--pyargs", "nibabel"] + if not doctests: + expected_args.remove("--doctest-modules") + if not coverage: + expected_args[-4:-2] = [] + + with mock.patch("pytest.main") as pytest_main: + nib.test(verbose=verbose, doctests=doctests, coverage=coverage) + + args, kwargs = pytest_main.call_args + assert args == () + assert kwargs == {"args": expected_args} + + +def test_nibabel_test_errors(): + with pytest.raises(NotImplementedError): + nib.test(label="fast") + with pytest.raises(NotImplementedError): + nib.test(raise_warnings=[]) + with pytest.raises(NotImplementedError): + nib.test(timer=True) + with pytest.raises(ValueError): + nib.test(verbose="-v") + + +def test_nibabel_bench(): + expected_args = ["-c", "--pyargs", "nibabel"] + + try: + expected_args.insert(1, resource_filename("nibabel", "benchmarks/pytest.benchmark.ini")) + except: + raise unittest.SkipTest("Not installed") + + with mock.patch("pytest.main") as pytest_main: + nib.bench(verbose=0) + + args, kwargs = pytest_main.call_args + assert args == () + assert kwargs == {"args": expected_args} + + with mock.patch("pytest.main") as pytest_main: + nib.bench(verbose=0, extra_argv=[]) + + args, kwargs = pytest_main.call_args + assert args == () + assert kwargs == {"args": expected_args} From c049a4e09ea0b3ffbb68174dc473a019bfe0360a Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Wed, 19 Feb 2020 20:11:06 -0500 Subject: [PATCH 217/223] CI: Install test requirements through extra dependencies --- .azure-pipelines/windows.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index 970a3b788d..8b7e990fe2 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -30,7 +30,6 @@ jobs: displayName: 'Update build tools' - script: | python -m pip install --find-links %EXTRA_WHEELS% %DEPENDS% - python -m pip install nose coverage codecov pytest pytest-cov displayName: 'Install dependencies' - script: | python -m pip install .[$(CHECK_TYPE)] @@ -44,6 +43,7 @@ jobs: displayName: 'Pytest tests' condition: and(succeeded(), eq(variables['CHECK_TYPE'], 'test')) - script: | + python -m pip install codecov cd for_testing codecov displayName: 'Upload To Codecov' From 592b31049b7140181dd25cb6e1f2ce22e87afac0 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Wed, 19 Feb 2020 20:12:03 -0500 Subject: [PATCH 218/223] DOC: Specify current benchmark file --- nibabel/benchmarks/bench_array_to_file.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/benchmarks/bench_array_to_file.py b/nibabel/benchmarks/bench_array_to_file.py index 776a93000c..ee0d25044d 100644 --- a/nibabel/benchmarks/bench_array_to_file.py +++ b/nibabel/benchmarks/bench_array_to_file.py @@ -7,7 +7,7 @@ Run this benchmark with:: - pytest -c /benchmarks/pytest.benchmark.ini /benchmarks/bench_load_save.py + pytest -c /benchmarks/pytest.benchmark.ini /benchmarks/bench_array_to_file.py """ import sys From 7392e8fadf57f90f92adacbe0e93c4054670016c Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Wed, 19 Feb 2020 23:30:28 -0500 Subject: [PATCH 219/223] TEST: Style and parameterization fixes for readability --- nibabel/cifti2/tests/test_cifti2io_header.py | 2 +- nibabel/tests/test_arraywriters.py | 6 +- nibabel/tests/test_files_interface.py | 2 +- nibabel/tests/test_image_load_save.py | 35 +--- nibabel/tests/test_nifti1.py | 171 ++++++++++--------- nibabel/tests/test_nifti2.py | 10 +- nibabel/tests/test_optpkg.py | 5 +- nibabel/tests/test_orientations.py | 30 ++-- nibabel/tests/test_parrec.py | 6 +- nibabel/tests/test_processing.py | 24 +-- nibabel/tests/test_proxy_api.py | 8 +- nibabel/tests/test_scaling.py | 23 +-- nibabel/tests/test_scripts.py | 3 +- nibabel/tests/test_spatialimages.py | 3 +- nibabel/tests/test_testing.py | 5 +- nibabel/tests/test_tripwire.py | 2 +- nibabel/tests/test_wrapstruct.py | 19 +-- 17 files changed, 153 insertions(+), 201 deletions(-) diff --git a/nibabel/cifti2/tests/test_cifti2io_header.py b/nibabel/cifti2/tests/test_cifti2io_header.py index 0cbf167809..0fef5ccd78 100644 --- a/nibabel/cifti2/tests/test_cifti2io_header.py +++ b/nibabel/cifti2/tests/test_cifti2io_header.py @@ -255,7 +255,7 @@ def test_read_geometry(): [ 0, 0, 0, 1]] expected_dimensions = (91, 109, 91) assert (geometry_mapping.volume.transformation_matrix_voxel_indices_ijk_to_xyz.matrix == - expected_affine).all() + expected_affine).all() assert geometry_mapping.volume.volume_dimensions == expected_dimensions diff --git a/nibabel/tests/test_arraywriters.py b/nibabel/tests/test_arraywriters.py index 380126d4d4..9268c3fe36 100644 --- a/nibabel/tests/test_arraywriters.py +++ b/nibabel/tests/test_arraywriters.py @@ -610,12 +610,12 @@ def test_dumber_writers(): aw.slope = 2.0 assert aw.slope == 2.0 with pytest.raises(AttributeError): - getattr(aw, 'inter') + aw.inter aw = ArrayWriter(arr) with pytest.raises(AttributeError): - getattr(aw, 'slope') + aw.slope with pytest.raises(AttributeError): - getattr(aw, 'inter') + aw.inter # Attempt at scaling should raise error for dumb type with pytest.raises(WriterError): ArrayWriter(arr, np.int16) diff --git a/nibabel/tests/test_files_interface.py b/nibabel/tests/test_files_interface.py index da91aaf03a..d3c895618e 100644 --- a/nibabel/tests/test_files_interface.py +++ b/nibabel/tests/test_files_interface.py @@ -57,7 +57,7 @@ def test_files_interface(): assert img.get_filename() == 'test.nii' assert img.file_map['image'].filename == 'test.nii' with pytest.raises(KeyError): - img.file_map.__getitem__('header') + img.file_map['header'] # pair - note new class img = Nifti1Pair(arr, aff) img.set_filename('test') diff --git a/nibabel/tests/test_image_load_save.py b/nibabel/tests/test_image_load_save.py index 25c5b3e1de..429144108c 100644 --- a/nibabel/tests/test_image_load_save.py +++ b/nibabel/tests/test_image_load_save.py @@ -137,8 +137,7 @@ def test_save_load(): del re_img2 spm99.save(img, sifn) re_img3 = nils.load(sifn) - assert isinstance(re_img3, - spm99.Spm99AnalyzeImage) + assert isinstance(re_img3, spm99.Spm99AnalyzeImage) assert_array_equal(re_img3.get_fdata(), data) assert_array_equal(re_img3.affine, affine) ni1.save(re_img3, nifn) @@ -301,30 +300,14 @@ def wat(hdr): def test_guessed_image_type(): # Test whether we can guess the image type from example files - assert (nils.guessed_image_type( - pjoin(DATA_PATH, 'example4d.nii.gz')) == - Nifti1Image) - assert (nils.guessed_image_type( - pjoin(DATA_PATH, 'nifti1.hdr')) == - Nifti1Pair) - assert (nils.guessed_image_type( - pjoin(DATA_PATH, 'example_nifti2.nii.gz')) == - Nifti2Image) - assert (nils.guessed_image_type( - pjoin(DATA_PATH, 'nifti2.hdr')) == - Nifti2Pair) - assert (nils.guessed_image_type( - pjoin(DATA_PATH, 'tiny.mnc')) == - Minc1Image) - assert (nils.guessed_image_type( - pjoin(DATA_PATH, 'small.mnc')) == - Minc2Image) - assert (nils.guessed_image_type( - pjoin(DATA_PATH, 'test.mgz')) == - MGHImage) - assert (nils.guessed_image_type( - pjoin(DATA_PATH, 'analyze.hdr')) == - Spm2AnalyzeImage) + assert nils.guessed_image_type(pjoin(DATA_PATH, 'example4d.nii.gz')) == Nifti1Image + assert nils.guessed_image_type(pjoin(DATA_PATH, 'nifti1.hdr')) == Nifti1Pair + assert nils.guessed_image_type(pjoin(DATA_PATH, 'example_nifti2.nii.gz')) == Nifti2Image + assert nils.guessed_image_type(pjoin(DATA_PATH, 'nifti2.hdr')) == Nifti2Pair + assert nils.guessed_image_type(pjoin(DATA_PATH, 'tiny.mnc')) == Minc1Image + assert nils.guessed_image_type(pjoin(DATA_PATH, 'small.mnc')) == Minc2Image + assert nils.guessed_image_type(pjoin(DATA_PATH, 'test.mgz')) == MGHImage + assert nils.guessed_image_type(pjoin(DATA_PATH, 'analyze.hdr')) == Spm2AnalyzeImage def test_fail_save(): diff --git a/nibabel/tests/test_nifti1.py b/nibabel/tests/test_nifti1.py index 6ee1926d8d..75f261c48e 100644 --- a/nibabel/tests/test_nifti1.py +++ b/nibabel/tests/test_nifti1.py @@ -62,43 +62,7 @@ A[:3, :3] = np.array(R) * Z # broadcasting does the job A[:3, 3] = T -HDE = HeaderDataError -header_examples_list = \ - [ - ((None, None), None, (None, None), (np.nan, np.nan)), - ((np.nan, None), None, (None, None), (np.nan, np.nan)), - ((None, np.nan), None, (None, None), (np.nan, np.nan)), - ((np.nan, np.nan), None, (None, None), (np.nan, np.nan)), - # Can only be one null - ((None, 0), HDE, (None, None), (np.nan, 0)), - ((np.nan, 0), HDE, (None, None), (np.nan, 0)), - ((1, None), HDE, (None, None), (1, np.nan)), - ((1, np.nan), HDE, (None, None), (1, np.nan)), - # Bad slope plus anything generates an error - ((0, 0), HDE, (None, None), (0, 0)), - ((0, None), HDE, (None, None), (0, np.nan)), - ((0, np.nan), HDE, (None, None), (0, np.nan)), - ((0, np.inf), HDE, (None, None), (0, np.inf)), - ((0, -np.inf), HDE, (None, None), (0, -np.inf)), - ((np.inf, 0), HDE, (None, None), (np.inf, 0)), - ((np.inf, None), HDE, (None, None), (np.inf, np.nan)), - ((np.inf, np.nan), HDE, (None, None), (np.inf, np.nan)), - ((np.inf, np.inf), HDE, (None, None), (np.inf, np.inf)), - ((np.inf, -np.inf), HDE, (None, None), (np.inf, -np.inf)), - ((-np.inf, 0), HDE, (None, None), (-np.inf, 0)), - ((-np.inf, None), HDE, (None, None), (-np.inf, np.nan)), - ((-np.inf, np.nan), HDE, (None, None), (-np.inf, np.nan)), - ((-np.inf, np.inf), HDE, (None, None), (-np.inf, np.inf)), - ((-np.inf, -np.inf), HDE, (None, None), (-np.inf, -np.inf)), - # Good slope and bad inter generates error for get_slope_inter - ((2, None), HDE, HDE, (2, np.nan)), - ((2, np.nan), HDE, HDE, (2, np.nan)), - ((2, np.inf), HDE, HDE, (2, np.inf)), - ((2, -np.inf), HDE, HDE, (2, -np.inf)), - # Good slope and inter - you guessed it - ((2, 0), None, (2, 0), (2, 0)), - ((2, 1), None, (2, 1), (2, 1)) - ] + class TestNifti1PairHeader(tana.TestAnalyzeHeader, tspm.HeaderScalingMixin): header_class = Nifti1PairHeader example_file = header_file @@ -174,9 +138,44 @@ def test_big_scaling(self): def test_slope_inter(self): hdr = self.header_class() + nan, inf, minf = np.nan, np.inf, -np.inf + HDE = HeaderDataError assert hdr.get_slope_inter() == (1.0, 0.0) - for in_tup, exp_err, out_tup, raw_values in header_examples_list: + for in_tup, exp_err, out_tup, raw_values in ( # Null scalings + ((None, None), None, (None, None), (nan, nan)), + ((nan, None), None, (None, None), (nan, nan)), + ((None, nan), None, (None, None), (nan, nan)), + ((nan, nan), None, (None, None), (nan, nan)), + # Can only be one null + ((None, 0), HDE, (None, None), (nan, 0)), + ((nan, 0), HDE, (None, None), (nan, 0)), + ((1, None), HDE, (None, None), (1, nan)), + ((1, nan), HDE, (None, None), (1, nan)), + # Bad slope plus anything generates an error + ((0, 0), HDE, (None, None), (0, 0)), + ((0, None), HDE, (None, None), (0, nan)), + ((0, nan), HDE, (None, None), (0, nan)), + ((0, inf), HDE, (None, None), (0, inf)), + ((0, minf), HDE, (None, None), (0, minf)), + ((inf, 0), HDE, (None, None), (inf, 0)), + ((inf, None), HDE, (None, None), (inf, nan)), + ((inf, nan), HDE, (None, None), (inf, nan)), + ((inf, inf), HDE, (None, None), (inf, inf)), + ((inf, minf), HDE, (None, None), (inf, minf)), + ((minf, 0), HDE, (None, None), (minf, 0)), + ((minf, None), HDE, (None, None), (minf, nan)), + ((minf, nan), HDE, (None, None), (minf, nan)), + ((minf, inf), HDE, (None, None), (minf, inf)), + ((minf, minf), HDE, (None, None), (minf, minf)), + # Good slope and bad inter generates error for get_slope_inter + ((2, None), HDE, HDE, (2, nan)), + ((2, nan), HDE, HDE, (2, nan)), + ((2, inf), HDE, HDE, (2, inf)), + ((2, minf), HDE, HDE, (2, minf)), + # Good slope and inter - you guessed it + ((2, 0), None, (2, 0), (2, 0)), + ((2, 1), None, (2, 1), (2, 1))): hdr = self.header_class() if not exp_err is None: with pytest.raises(exp_err): @@ -193,8 +192,7 @@ def test_slope_inter(self): # Check set survives through checking hdr = self.header_class.from_header(hdr, check=True) assert hdr.get_slope_inter() == out_tup - assert_array_equal([hdr['scl_slope'], hdr['scl_inter']], - raw_values) + assert_array_equal([hdr['scl_slope'], hdr['scl_inter']], raw_values) def test_nifti_qfac_checks(self): # Test qfac is 1 or -1 @@ -208,9 +206,7 @@ def test_nifti_qfac_checks(self): hdr['pixdim'][0] = 0 fhdr, message, raiser = self.log_chk(hdr, 20) assert fhdr['pixdim'][0] == 1 - assert (message == - 'pixdim[0] (qfac) should be 1 ' - '(default) or -1; setting qfac to 1') + assert message == 'pixdim[0] (qfac) should be 1 (default) or -1; setting qfac to 1' def test_nifti_qsform_checks(self): # qform, sform checks @@ -220,14 +216,12 @@ def test_nifti_qsform_checks(self): hdr['qform_code'] = -1 fhdr, message, raiser = self.log_chk(hdr, 30) assert fhdr['qform_code'] == 0 - assert (message == - 'qform_code -1 not valid; setting to 0') + assert message == 'qform_code -1 not valid; setting to 0' hdr = HC() hdr['sform_code'] = -1 fhdr, message, raiser = self.log_chk(hdr, 30) assert fhdr['sform_code'] == 0 - assert (message == - 'sform_code -1 not valid; setting to 0') + assert message == 'sform_code -1 not valid; setting to 0' def test_nifti_xform_codes(self): # Verify that all xform codes can be set in both qform and sform @@ -254,8 +248,8 @@ def test_magic_offset_checks(self): fhdr, message, raiser = self.log_chk(hdr, 45) assert fhdr['magic'] == b'ooh' assert (message == - 'magic string "ooh" is not valid; ' - 'leaving as is, but future errors are likely') + 'magic string "ooh" is not valid; ' + 'leaving as is, but future errors are likely') # For pairs, any offset is OK, but should be divisible by 16 # Singles need offset of at least 352 (nifti1) or 540 (nifti2) bytes, # with the divide by 16 rule @@ -271,18 +265,18 @@ def test_magic_offset_checks(self): fhdr, message, raiser = self.log_chk(hdr, 30) assert fhdr['vox_offset'] == bad_spm assert (message == - 'vox offset (={0:g}) not divisible by 16, ' - 'not SPM compatible; leaving at current ' - 'value'.format(bad_spm)) + 'vox offset (={0:g}) not divisible by 16, ' + 'not SPM compatible; leaving at current ' + 'value'.format(bad_spm)) # Check minimum offset (if offset set) hdr['magic'] = hdr.single_magic hdr['vox_offset'] = 10 fhdr, message, raiser = self.log_chk(hdr, 40) assert fhdr['vox_offset'] == hdr.single_vox_offset assert (message == - 'vox offset 10 too low for single ' - 'file nifti1; setting to minimum value ' - 'of ' + str(hdr.single_vox_offset)) + 'vox offset 10 too low for single ' + 'file nifti1; setting to minimum value ' + 'of ' + str(hdr.single_vox_offset)) def test_freesurfer_large_vector_hack(self): # For large vector images, Freesurfer appears to set dim[1] to -1 and @@ -315,10 +309,14 @@ def test_freesurfer_large_vector_hack(self): assert hdr.get_data_shape() == (too_big, 1, 1, 4) assert_array_equal(hdr['dim'][:5], np.array([4, -1, 1, 1, 4])) # This only works when the first 3 dimensions are -1, 1, 1 - for args in [(too_big,), (too_big, 1), (too_big, 1, 2), (too_big, 2, 1), - (1, too_big), (1, too_big, 1), (1, 1, too_big), (1, 1, 1, too_big)]: - with pytest.raises(HeaderDataError): - hdr.set_data_shape(args) + pytest.raises(HeaderDataError, hdr.set_data_shape, (too_big,)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (too_big, 1)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (too_big, 1, 2)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (too_big, 2, 1)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (1, too_big)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (1, too_big, 1)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (1, 1, too_big)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (1, 1, 1, too_big)) # Outside range of glmin raises error far_too_big = int(np.iinfo(glmin).max) + 1 with suppress_warnings(): @@ -350,14 +348,14 @@ def test_freesurfer_ico7_hack(self): assert hdr.get_data_shape() == full_shape[:dim] assert_array_equal(hdr._structarr['dim'], expected_dim) # Only works on dimensions >= 3 - for args in [ - # Only works on dimensions >= 3 - full_shape[:1], full_shape[:2], - # Bad shapes - (163842, 2, 1), (163842, 1, 2), (1, 163842, 1), - (1, 1, 163842), (1, 1, 1, 163842)]: - with pytest.raises(HeaderDataError): - hdr.set_data_shape(args) + pytest.raises(HeaderDataError, hdr.set_data_shape, full_shape[:1]) + pytest.raises(HeaderDataError, hdr.set_data_shape, full_shape[:2]) + # Bad shapes + pytest.raises(HeaderDataError, hdr.set_data_shape, (163842, 2, 1)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (163842, 1, 2)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (1, 163842, 1)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (1, 1, 163842)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (1, 1, 1, 163842)) # Test consistency of data in .mgh and mri_convert produced .nii nitest_path = os.path.join(get_nibabel_data(), 'nitest-freesurfer') mgh = mghload(os.path.join(nitest_path, 'fsaverage', 'surf', @@ -538,26 +536,26 @@ def test_slice_times(self): # The following examples are from the nifti1.h documentation. hdr['slice_code'] = slice_order_codes['sequential increasing'] assert (_print_me(hdr.get_slice_times()) == - ['0.0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6']) + ['0.0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6']) hdr['slice_start'] = 1 hdr['slice_end'] = 5 assert (_print_me(hdr.get_slice_times()) == - [None, '0.0', '0.1', '0.2', '0.3', '0.4', None]) + [None, '0.0', '0.1', '0.2', '0.3', '0.4', None]) hdr['slice_code'] = slice_order_codes['sequential decreasing'] assert (_print_me(hdr.get_slice_times()) == - [None, '0.4', '0.3', '0.2', '0.1', '0.0', None]) + [None, '0.4', '0.3', '0.2', '0.1', '0.0', None]) hdr['slice_code'] = slice_order_codes['alternating increasing'] assert (_print_me(hdr.get_slice_times()) == - [None, '0.0', '0.3', '0.1', '0.4', '0.2', None]) + [None, '0.0', '0.3', '0.1', '0.4', '0.2', None]) hdr['slice_code'] = slice_order_codes['alternating decreasing'] assert (_print_me(hdr.get_slice_times()) == - [None, '0.2', '0.4', '0.1', '0.3', '0.0', None]) + [None, '0.2', '0.4', '0.1', '0.3', '0.0', None]) hdr['slice_code'] = slice_order_codes['alternating increasing 2'] assert (_print_me(hdr.get_slice_times()) == - [None, '0.2', '0.0', '0.3', '0.1', '0.4', None]) + [None, '0.2', '0.0', '0.3', '0.1', '0.4', None]) hdr['slice_code'] = slice_order_codes['alternating decreasing 2'] assert (_print_me(hdr.get_slice_times()) == - [None, '0.4', '0.1', '0.3', '0.0', '0.2', None]) + [None, '0.4', '0.1', '0.3', '0.0', '0.2', None]) # test set hdr = self.header_class() hdr.set_dim_info(slice=2) @@ -608,8 +606,7 @@ def test_slice_times(self): def test_intents(self): ehdr = self.header_class() ehdr.set_intent('t test', (10,), name='some score') - assert (ehdr.get_intent() == - ('t test', (10.0,), 'some score')) + assert ehdr.get_intent() == ('t test', (10.0,), 'some score') # unknown intent name or code - unknown name will fail even when # allow_unknown=True with pytest.raises(KeyError): @@ -636,8 +633,7 @@ def test_intents(self): assert ehdr.get_intent() == ('unknown code 9999', (), '') assert ehdr.get_intent('code') == (9999, (), '') ehdr.set_intent(9999, name='custom intent', allow_unknown=True) - assert (ehdr.get_intent() == - ('unknown code 9999', (), 'custom intent')) + assert ehdr.get_intent() == ('unknown code 9999', (), 'custom intent') assert ehdr.get_intent('code') == (9999, (), 'custom intent') # store unknown intent with parameters. set_intent will set the # parameters, but get_intent won't return them @@ -655,10 +651,16 @@ def test_set_slice_times(self): hdr.set_dim_info(slice=2) hdr.set_data_shape([1, 1, 7]) hdr.set_slice_duration(0.1) - for times in [[0] * 6, [None] * 7, [None, 0, 1, None, 3, 4, None], - [None, 0, 1, 2.1, 3, 4, None], [None, 0, 4, 3, 2, 1, None]]: - with pytest.raises(HeaderDataError): - hdr.set_slice_times(times) + times = [0] * 6 + pytest.raises(HeaderDataError, hdr.set_slice_times, times) + times = [None] * 7 + pytest.raises(HeaderDataError, hdr.set_slice_times, times) + times = [None, 0, 1, None, 3, 4, None] + pytest.raises(HeaderDataError, hdr.set_slice_times, times) + times = [None, 0, 1, 2.1, 3, 4, None] + pytest.raises(HeaderDataError, hdr.set_slice_times, times) + times = [None, 0, 4, 3, 2, 1, None] + pytest.raises(HeaderDataError, hdr.set_slice_times, times) times = [0, 1, 2, 3, 4, 5, 6] hdr.set_slice_times(times) assert hdr['slice_code'] == 1 @@ -711,8 +713,7 @@ def test_recoded_fields(self): assert hdr.get_value_label('intent_code') == 't test' assert hdr.get_value_label('slice_code') == 'unknown' hdr['slice_code'] = 4 # alternating decreasing - assert (hdr.get_value_label('slice_code') == - 'alternating decreasing') + assert hdr.get_value_label('slice_code') == 'alternating decreasing' def unshear_44(affine): @@ -999,7 +1000,7 @@ def test_load_save(self): assert_array_equal(img3.get_fdata(), data) assert img3.header == img.header assert isinstance(np.asanyarray(img3.dataobj), - np.memmap if ext == '' else np.ndarray) + np.memmap if ext == '' else np.ndarray) # del to avoid windows errors of form 'The process cannot # access the file because it is being used' del img3 diff --git a/nibabel/tests/test_nifti2.py b/nibabel/tests/test_nifti2.py index d0daf9632e..ca6e7d8125 100644 --- a/nibabel/tests/test_nifti2.py +++ b/nibabel/tests/test_nifti2.py @@ -49,16 +49,14 @@ def test_eol_check(self): hdr['eol_check'] = 0 fhdr, message, raiser = self.log_chk(hdr, 20) assert_array_equal(fhdr['eol_check'], good_eol) - assert (message == - 'EOL check all 0; ' - 'setting EOL check to 13, 10, 26, 10') + assert message == 'EOL check all 0; setting EOL check to 13, 10, 26, 10' hdr['eol_check'] = (13, 10, 0, 10) fhdr, message, raiser = self.log_chk(hdr, 40) assert_array_equal(fhdr['eol_check'], good_eol) assert (message == - 'EOL check not 0 or 13, 10, 26, 10; ' - 'data may be corrupted by EOL conversion; ' - 'setting EOL check to 13, 10, 26, 10') + 'EOL check not 0 or 13, 10, 26, 10; ' + 'data may be corrupted by EOL conversion; ' + 'setting EOL check to 13, 10, 26, 10') class TestNifti2PairHeader(_Nifti2Mixin, TestNifti1PairHeader): diff --git a/nibabel/tests/test_optpkg.py b/nibabel/tests/test_optpkg.py index 1e652a51c5..925180ce6b 100644 --- a/nibabel/tests/test_optpkg.py +++ b/nibabel/tests/test_optpkg.py @@ -26,7 +26,7 @@ def assert_bad(pkg_name, min_version=None): assert not have_pkg assert isinstance(pkg, TripWire) with pytest.raises(TripWireError): - getattr(pkg, 'a_method') + pkg.a_method with pytest.raises(SkipTest): setup() @@ -77,7 +77,6 @@ def test_versions(): try: pkg.some_method except TripWireError as err: - assert (str(err) == - 'These functions need _a_fake_package version >= 3.0') + assert str(err) == 'These functions need _a_fake_package version >= 3.0' finally: del sys.modules[fake_name] diff --git a/nibabel/tests/test_orientations.py b/nibabel/tests/test_orientations.py index 226feee526..a3ad215488 100644 --- a/nibabel/tests/test_orientations.py +++ b/nibabel/tests/test_orientations.py @@ -267,25 +267,25 @@ def test_ornt2axcodes(): # Recoding orientation to axis codes labels = (('left', 'right'), ('back', 'front'), ('down', 'up')) assert ornt2axcodes([[0, 1], - [1, 1], - [2, 1]], labels) == ('right', 'front', 'up') + [1, 1], + [2, 1]], labels) == ('right', 'front', 'up') assert ornt2axcodes([[0, -1], - [1, -1], - [2, -1]], labels) == ('left', 'back', 'down') + [1, -1], + [2, -1]], labels) == ('left', 'back', 'down') assert ornt2axcodes([[2, -1], - [1, -1], - [0, -1]], labels) == ('down', 'back', 'left') + [1, -1], + [0, -1]], labels) == ('down', 'back', 'left') assert ornt2axcodes([[1, 1], - [2, -1], - [0, 1]], labels) == ('front', 'down', 'right') + [2, -1], + [0, 1]], labels) == ('front', 'down', 'right') # default is RAS output directions assert ornt2axcodes([[0, 1], - [1, 1], - [2, 1]]) == ('R', 'A', 'S') + [1, 1], + [2, 1]]) == ('R', 'A', 'S') # dropped axes produce None assert ornt2axcodes([[0, 1], - [np.nan, np.nan], - [2, 1]]) == ('R', None, 'S') + [np.nan, np.nan], + [2, 1]]) == ('R', None, 'S') # Non integer axes raises error with pytest.raises(ValueError): ornt2axcodes([[0.1, 1]]) @@ -365,10 +365,8 @@ def test_axcodes2ornt(): def test_aff2axcodes(): assert aff2axcodes(np.eye(4)) == tuple('RAS') aff = [[0, 1, 0, 10], [-1, 0, 0, 20], [0, 0, 1, 30], [0, 0, 0, 1]] - assert (aff2axcodes(aff, (('L', 'R'), ('B', 'F'), ('D', 'U'))) == - ('B', 'R', 'U')) - assert (aff2axcodes(aff, (('L', 'R'), ('B', 'F'), ('D', 'U'))) == - ('B', 'R', 'U')) + assert aff2axcodes(aff, (('L', 'R'), ('B', 'F'), ('D', 'U'))) == ('B', 'R', 'U') + assert aff2axcodes(aff, (('L', 'R'), ('B', 'F'), ('D', 'U'))) == ('B', 'R', 'U') def test_inv_ornt_aff(): diff --git a/nibabel/tests/test_parrec.py b/nibabel/tests/test_parrec.py index 4c55179672..d39f2a097f 100644 --- a/nibabel/tests/test_parrec.py +++ b/nibabel/tests/test_parrec.py @@ -345,8 +345,7 @@ def test_sorting_multiple_echos_and_contrasts(): np.arange(1, nslices+1)) current_echo = slice_offset % nechos + 1 # same echo for each slice in the group - assert (np.all(sorted_echos[istart:iend] == current_echo) == - True) + assert np.all(sorted_echos[istart:iend] == current_echo) # outermost sort index is image_type_mr assert np.all(sorted_types[:ntotal//4] == 0) assert np.all(sorted_types[ntotal//4:ntotal//2] == 1) @@ -403,8 +402,7 @@ def test_sorting_multiecho_ASL(): # check volume labels vol_labels = asl_hdr.get_volume_labels() - assert (list(vol_labels.keys()) == - ['echo number', 'label type', 'dynamic scan number']) + assert list(vol_labels.keys()) == ['echo number', 'label type', 'dynamic scan number'] assert_array_equal(vol_labels['dynamic scan number'], [1]*6 + [2]*6) assert_array_equal(vol_labels['label type'], [1]*3 + [2]*3 + [1]*3 + [2]*3) assert_array_equal(vol_labels['echo number'], [1, 2, 3]*4) diff --git a/nibabel/tests/test_processing.py b/nibabel/tests/test_processing.py index 1dd64c6a5c..1e9e94091e 100644 --- a/nibabel/tests/test_processing.py +++ b/nibabel/tests/test_processing.py @@ -287,17 +287,11 @@ def test_resample_to_output(): img_ni1 = Nifti2Image(data, np.eye(4)) img_ni2 = Nifti2Image(data, np.eye(4)) # Default is Nifti1Image - assert ( - resample_to_output(img_ni2).__class__ == - Nifti1Image) + assert resample_to_output(img_ni2).__class__ == Nifti1Image # Can be overriden - assert ( - resample_to_output(img_ni1, out_class=Nifti2Image).__class__ == - Nifti2Image) + assert resample_to_output(img_ni1, out_class=Nifti2Image).__class__ == Nifti2Image # None specifies out_class from input - assert ( - resample_to_output(img_ni2, out_class=None).__class__ == - Nifti2Image) + assert resample_to_output(img_ni2, out_class=None).__class__ == Nifti2Image @needs_scipy @@ -347,17 +341,11 @@ def test_smooth_image(): img_ni1 = Nifti2Image(data, np.eye(4)) img_ni2 = Nifti2Image(data, np.eye(4)) # Default is Nifti1Image - assert ( - smooth_image(img_ni2, 0).__class__ == - Nifti1Image) + assert smooth_image(img_ni2, 0).__class__ == Nifti1Image # Can be overriden - assert ( - smooth_image(img_ni1, 0, out_class=Nifti2Image).__class__ == - Nifti2Image) + assert smooth_image(img_ni1, 0, out_class=Nifti2Image).__class__ == Nifti2Image # None specifies out_class from input - assert ( - smooth_image(img_ni2, 0, out_class=None).__class__ == - Nifti2Image) + assert smooth_image(img_ni2, 0, out_class=None).__class__ == Nifti2Image @needs_scipy diff --git a/nibabel/tests/test_proxy_api.py b/nibabel/tests/test_proxy_api.py index a5a9e9e051..cccd7b729f 100644 --- a/nibabel/tests/test_proxy_api.py +++ b/nibabel/tests/test_proxy_api.py @@ -104,7 +104,7 @@ def validate_shape(self, pmaker, params): assert_array_equal(prox.shape, params['shape']) # Read only with pytest.raises(AttributeError): - setattr(prox, 'shape', params['shape']) + prox.shape = params['shape'] def validate_ndim(self, pmaker, params): # Check shape @@ -112,7 +112,7 @@ def validate_ndim(self, pmaker, params): assert prox.ndim == len(params['shape']) # Read only with pytest.raises(AttributeError): - setattr(prox, 'ndim', len(params['shape'])) + prox.ndim = len(params['shape']) def validate_is_proxy(self, pmaker, params): # Check shape @@ -122,7 +122,7 @@ def validate_is_proxy(self, pmaker, params): assert not is_proxy(np.arange(10)) # Read only with pytest.raises(AttributeError): - setattr(prox, 'is_proxy', False) + prox.is_proxy = False def validate_asarray(self, pmaker, params): # Check proxy returns expected array from asarray @@ -311,7 +311,7 @@ def validate_dtype(self, pmaker, params): prox, fio, hdr = pmaker() assert_dt_equal(prox.dtype, params['dtype']) with pytest.raises(AttributeError): - prox.__setattr__('dtype', np.dtype(prox.dtype)) + prox.dtype = np.dtype(prox.dtype) def validate_slope_inter_offset(self, pmaker, params): # Check slope, inter, offset diff --git a/nibabel/tests/test_scaling.py b/nibabel/tests/test_scaling.py index e916770dab..5855d0837a 100644 --- a/nibabel/tests/test_scaling.py +++ b/nibabel/tests/test_scaling.py @@ -131,15 +131,15 @@ def test_a2f_nan2zero(): assert_array_equal(data_back, [np.array(np.nan).astype(np.int32), 99]) -@pytest.mark.parametrize("in_type, out_type, err", [ - (np.int16, np.int16, None), - (np.int16, np.int8, None), - (np.uint16, np.uint8, None), - (np.int32, np.int8, None), - (np.float32, np.uint8, None), - (np.float32, np.int16, None) +@pytest.mark.parametrize("in_type, out_type", [ + (np.int16, np.int16), + (np.int16, np.int8), + (np.uint16, np.uint8), + (np.int32, np.int8), + (np.float32, np.uint8), + (np.float32, np.int16) ]) -def test_array_file_scales(in_type, out_type, err): +def test_array_file_scales(in_type, out_type): # Test scaling works for max, min when going from larger to smaller type, # and from float to integer. bio = BytesIO() @@ -147,10 +147,6 @@ def test_array_file_scales(in_type, out_type, err): arr = np.zeros((3,), dtype=in_type) info = type_info(in_type) arr[0], arr[1] = info['min'], info['max'] - if not err is None: - with pytest.raises(err): - _calculate_scale(arr, out_dtype, True) - return slope, inter, mn, mx = _calculate_scale(arr, out_dtype, True) array_to_file(arr, bio, out_type, 0, inter, slope, mn, mx) bio.seek(0) @@ -225,5 +221,4 @@ def check_int_a2f(in_type, out_type): # Clip at extremes to remove inf info = type_info(in_type) out_min, out_max = info['min'], info['max'] - assert np.allclose(big_floater(data), - big_floater(np.clip(data_back, out_min, out_max))) + assert np.allclose(big_floater(data), big_floater(np.clip(data_back, out_min, out_max))) diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 1ed6870f07..d15403a881 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -412,8 +412,7 @@ def test_parrec2nii_with_data(): for line in csvreader: nlines += 1 - assert sorted(csv_keys) == ['diffusion b value number', - 'gradient orientation number'] + assert sorted(csv_keys) == ['diffusion b value number', 'gradient orientation number'] assert nlines == 8 # 8 volumes present in DTI.PAR diff --git a/nibabel/tests/test_spatialimages.py b/nibabel/tests/test_spatialimages.py index a2a8ddc79d..58b41d5822 100644 --- a/nibabel/tests/test_spatialimages.py +++ b/nibabel/tests/test_spatialimages.py @@ -435,8 +435,7 @@ def test_slicer(self): sliceobj = [slice(None, None, 2)] * 3 + \ [slice(None)] * (len(dshape) - 3) downsampled_img = img.slicer[tuple(sliceobj)] - assert (downsampled_img.header.get_zooms()[:3] - == np.array(spatial_zooms) * 2).all() + assert (downsampled_img.header.get_zooms()[:3] == np.array(spatial_zooms) * 2).all() max4d = (hasattr(img.header, '_structarr') and 'dims' in img.header._structarr.dtype.fields and diff --git a/nibabel/tests/test_testing.py b/nibabel/tests/test_testing.py index 32b77fac6c..b27775a81a 100644 --- a/nibabel/tests/test_testing.py +++ b/nibabel/tests/test_testing.py @@ -165,9 +165,8 @@ def test_assert_re_in_exception(args): def test_test_data(): assert test_data() == data_path - assert (test_data() == - os.path.abspath(os.path.join(os.path.dirname(__file__), - '..', 'tests', 'data'))) + assert test_data() == os.path.abspath(os.path.join(os.path.dirname(__file__), + '..', 'tests', 'data')) for subdir in ('nicom', 'gifti', 'externals'): assert test_data(subdir) == os.path.join(data_path[:-10], subdir, 'tests', 'data') assert os.path.exists(test_data(subdir)) diff --git a/nibabel/tests/test_tripwire.py b/nibabel/tests/test_tripwire.py index b69e913d4b..2ec3e06182 100644 --- a/nibabel/tests/test_tripwire.py +++ b/nibabel/tests/test_tripwire.py @@ -14,7 +14,7 @@ def test_tripwire(): # Test tripwire object silly_module_name = TripWire('We do not have silly_module_name') with pytest.raises(TripWireError): - getattr(silly_module_name, 'do_silly_thing') + silly_module_name.do_silly_thing # Check AttributeError can be checked too try: silly_module_name.__wrapped__ diff --git a/nibabel/tests/test_wrapstruct.py b/nibabel/tests/test_wrapstruct.py index d56873d414..26e04dd8f9 100644 --- a/nibabel/tests/test_wrapstruct.py +++ b/nibabel/tests/test_wrapstruct.py @@ -165,7 +165,7 @@ def test_to_from_fileobj(self): def test_mappingness(self): hdr = self.header_class() with pytest.raises(ValueError): - hdr.__setitem__('nonexistent key', 0.1) + hdr['nonexistent key'] = 0.1 hdr_dt = hdr.structarr.dtype keys = hdr.keys() assert keys == list(hdr) @@ -201,7 +201,7 @@ def test_endianness_ro(self): ''' hdr = self.header_class() with pytest.raises(AttributeError): - hdr.__setattr__('endianness', '<') + hdr.endianness = '<' def test_endian_guess(self): # Check guesses of endian @@ -231,7 +231,7 @@ def test_structarr(self): hdr.structarr # That it's read only with pytest.raises(AttributeError): - hdr.__setattr__('structarr', 0) + hdr.structarr = 0 def log_chk(self, hdr, level): return log_chk(hdr, level) @@ -347,8 +347,7 @@ class MyHdr(self.header_class): # Speculating that we can set code value 0 or 1 new_code = 1 if code == 0 else 0 hdr[key] = new_code - assert (hdr.get_value_label(key) == - ''.format(new_code)) + assert hdr.get_value_label(key) == ''.format(new_code) class MyWrapStruct(WrapStruct): @@ -474,15 +473,13 @@ def test_log_checks(self): fhdr, message, raiser = self.log_chk(hdr, 40) return assert fhdr['an_integer'] == 1 - assert (message == - 'an_integer should be 1; set an_integer to 1') + assert message == 'an_integer should be 1; set an_integer to 1' pytest.raises(*raiser) # lower case string hdr = HC() hdr['a_str'] = 'Hello' # severity = 20 fhdr, message, raiser = self.log_chk(hdr, 20) - assert (message == 'a_str should be lower case; ' - 'set a_str to lower case') + assert message == 'a_str should be lower case; set a_str to lower case' pytest.raises(*raiser) def test_logger_error(self): @@ -502,9 +499,7 @@ def test_logger_error(self): # Check log message appears in new logger imageglobals.logger = logger hdr.copy().check_fix() - assert (str_io.getvalue() == - 'a_str should be lower case; ' - 'set a_str to lower case\n') + assert str_io.getvalue() == 'a_str should be lower case; set a_str to lower case\n' # Check that error_level in fact causes error to be raised imageglobals.error_level = 20 with pytest.raises(HeaderDataError): From a7f8e11e84d222c84afa89ebf32099f2a4ed04cb Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Wed, 19 Feb 2020 23:30:45 -0500 Subject: [PATCH 220/223] TEST: Bad test syntax --- nibabel/tests/test_nifti1.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nibabel/tests/test_nifti1.py b/nibabel/tests/test_nifti1.py index 75f261c48e..9b4747bd5d 100644 --- a/nibabel/tests/test_nifti1.py +++ b/nibabel/tests/test_nifti1.py @@ -451,7 +451,7 @@ def test_datatypes(self): if dt == np.void: continue hdr.set_data_dtype(code) - assert hdr.get_data_dtype(), data_type_codes.dtype[code] + assert hdr.get_data_dtype() == data_type_codes.dtype[code] # Check that checks also see new datatypes hdr.set_data_dtype(np.complex128) hdr.check_fix() From 60616510758961c3b03858da84b75b0ee5b94e0a Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Wed, 19 Feb 2020 23:31:30 -0500 Subject: [PATCH 221/223] TEST/RF: Mock compress_ext_map, instead of fixture --- nibabel/tests/test_openers.py | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/nibabel/tests/test_openers.py b/nibabel/tests/test_openers.py index 43712d11bf..85a8f4a0a7 100644 --- a/nibabel/tests/test_openers.py +++ b/nibabel/tests/test_openers.py @@ -18,6 +18,7 @@ from ..tmpdirs import InTemporaryDirectory from ..volumeutils import BinOpener +import unittest from unittest import mock import pytest from ..testing import error_warnings @@ -160,19 +161,8 @@ def test_Opener_gzip_type(): with patch_indexed_gzip(igzip_present): assert isinstance(Opener(fname, **kwargs).fobj, expected) -@pytest.fixture(scope="class") -def image_opener_setup(request): - compress_ext_map = ImageOpener.compress_ext_map.copy() - request.cls.compress_ext_map = compress_ext_map - - def teardown(): - ImageOpener.compress_ext_map = request.cls.compress_ext_map - request.addfinalizer(teardown) - - -@pytest.mark.usefixtures("image_opener_setup") -class TestImageOpener: +class TestImageOpener(unittest.TestCase): def test_vanilla(self): # Test that ImageOpener does add '.mgz' as gzipped file type with InTemporaryDirectory(): @@ -181,6 +171,7 @@ def test_vanilla(self): with ImageOpener('test.mgz', 'w') as fobj: assert hasattr(fobj.fobj, 'compress') + @mock.patch.dict('nibabel.openers.ImageOpener.compress_ext_map') def test_new_association(self): def file_opener(fileish, mode): return open(fileish, mode) From a98b023177bf94eaee791aa312e6cd8c57776d5f Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Wed, 19 Feb 2020 23:32:18 -0500 Subject: [PATCH 222/223] TEST: Rename tests to ensure running --- nibabel/tests/test_recoder.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nibabel/tests/test_recoder.py b/nibabel/tests/test_recoder.py index 8e4edd1b87..d6206df978 100644 --- a/nibabel/tests/test_recoder.py +++ b/nibabel/tests/test_recoder.py @@ -49,7 +49,7 @@ def test_recoder_3(): with pytest.raises(AttributeError): rc.label -def test_recoder_3(): +def test_recoder_4(): # with explicit column names codes = ((1, 'one'), (2, 'two')) rc = Recoder(codes, ['code1', 'label']) @@ -61,7 +61,7 @@ def test_recoder_3(): assert rc.label['one'] == 'one' -def test_recoder_4(): +def test_recoder_5(): # code, label, aliases codes = ((1, 'one', '1', 'first'), (2, 'two')) rc = Recoder(codes) # just with implicit alias @@ -70,7 +70,7 @@ def test_recoder_4(): assert rc.code['first'] == 1 -def test_recoder_5(): +def test_recoder_6(): # with explicit column names codes = ((1, 'one', '1', 'first'), (2, 'two')) rc = Recoder(codes, ['code1', 'label']) From 5657d01669fa3b9662dd5e51044e53ae96509cd8 Mon Sep 17 00:00:00 2001 From: Chris Markiewicz Date: Wed, 19 Feb 2020 23:33:38 -0500 Subject: [PATCH 223/223] TEST/RF: Reparametrize tests --- nibabel/tests/test_scaling.py | 38 +++++++++++++++-------------------- nibabel/tests/test_testing.py | 25 +++++++++-------------- 2 files changed, 25 insertions(+), 38 deletions(-) diff --git a/nibabel/tests/test_scaling.py b/nibabel/tests/test_scaling.py index 5855d0837a..f314e6b572 100644 --- a/nibabel/tests/test_scaling.py +++ b/nibabel/tests/test_scaling.py @@ -157,31 +157,25 @@ def test_array_file_scales(in_type, out_type): assert np.all(np.abs(arr - arr3) <= max_miss) -@pytest.mark.parametrize("in_type, out_type",[ - ('int', 'int'), - ('uint', 'int'), -]) -def test_scaling_in_abstract(in_type, out_type): +@pytest.mark.parametrize("category0, category1, overflow",[ # Confirm that, for all ints and uints as input, and all possible outputs, # for any simple way of doing the calculation, the result is near enough - for in_tp in np.sctypes[in_type]: - for out_tp in np.sctypes[out_type]: - check_int_a2f(in_tp, out_tp) - - -@pytest.mark.parametrize("in_type, out_type", [ - ('float', 'int'), - ('float', 'uint'), - ('complex', 'int'), - ('complex', 'uint'), -]) -def test_scaling_in_abstract_warn(in_type, out_type): - + ('int', 'int', False), + ('uint', 'int', False), # Converting floats to integer - for in_tp in np.sctypes[in_type]: - for out_tp in np.sctypes[out_type]: - with suppress_warnings(): # overflow - check_int_a2f(in_tp, out_tp) + ('float', 'int', True), + ('float', 'uint', True), + ('complex', 'int', True), + ('complex', 'uint', True), +]) +def test_scaling_in_abstract(category0, category1, overflow): + for in_type in np.sctypes[category0]: + for out_type in np.sctypes[category1]: + if overflow: + with suppress_warnings(): + check_int_a2f(in_type, out_type) + else: + check_int_a2f(in_type, out_type) def check_int_a2f(in_type, out_type): diff --git a/nibabel/tests/test_testing.py b/nibabel/tests/test_testing.py index b27775a81a..bbe83c6973 100644 --- a/nibabel/tests/test_testing.py +++ b/nibabel/tests/test_testing.py @@ -136,31 +136,24 @@ def f(): with pytest.raises(ValueError): f() -@pytest.mark.parametrize("args", [ +@pytest.mark.parametrize("regex, entries", [ [".*", ""], [".*", ["any"]], ["ab", "abc"], # Sufficient to have one entry matching ["ab", ["", "abc", "laskdjf"]], # Tuples should be ok too - ["ab", ("", "abc", "laskdjf")] -]) -def test_assert_re_in(args): - assert_re_in(*args) - - -@pytest.mark.parametrize("args", [ + ["ab", ("", "abc", "laskdjf")], # Should do match not search - ["ab", "cab"], - ["ab$", "abc"], - ["ab$", ["ddd", ""]], - ["ab$", ("ddd", "")], + pytest.param("ab", "cab", marks=pytest.mark.xfail), + pytest.param("ab$", "abc", marks=pytest.mark.xfail), + pytest.param("ab$", ["ddd", ""], marks=pytest.mark.xfail), + pytest.param("ab$", ("ddd", ""), marks=pytest.mark.xfail), #Shouldn't "match" the empty list - ["", []] + pytest.param("", [], marks=pytest.mark.xfail) ]) -def test_assert_re_in_exception(args): - with pytest.raises(AssertionError): - assert_re_in(*args) +def test_assert_re_in(regex, entries): + assert_re_in(regex, entries) def test_test_data():