diff --git a/.travis.yml b/.travis.yml index 804e198b90..ca6b4729dc 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_affines.py ../nibabel/tests/test_volumeutils.py + pytest -v ../nibabel/tests else false fi 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/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 88% rename from nibabel/tests/test_helpers.py rename to nibabel/testing_pytest/helpers.py index 928b4bd1a3..49112fddfb 100644 --- a/nibabel/tests/test_helpers.py +++ b/nibabel/testing_pytest/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'])) diff --git a/nibabel/tests/test_analyze.py b/nibabel/tests/test_analyze.py index 6b05df83e3..9032f136c5 100644 --- a/nibabel/tests/test_analyze.py +++ b/nibabel/tests/test_analyze.py @@ -31,18 +31,14 @@ 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 -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') @@ -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 a7cbb8b555..f4c2710a60 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 b1cc081b6d..28c26913a7 100644 --- a/nibabel/tests/test_arrayproxy.py +++ b/nibabel/tests/test_arrayproxy.py @@ -26,9 +26,8 @@ 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), )) ): @@ -114,14 +115,17 @@ def test_tuplespec(): getattr(ap_tuple, method)(*args)) # Tuple-defined ArrayProxies have no header to store with warnings.catch_warnings(): - assert_true(ap_tuple.header is None) + assert ap_tuple.header is None # Partial tuples of length 2-4 are also valid 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): @@ -139,12 +143,12 @@ 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 # Check there has been a copy of the header with warnings.catch_warnings(): warnings.simplefilter("ignore") - assert_false(ap.header is hdr) + assert not ap.header is hdr # Get the data assert_array_equal(np.asarray(ap), arr * 2.0 + 10) with InTemporaryDirectory(): @@ -152,8 +156,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) @@ -189,14 +193,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(): @@ -210,11 +214,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): @@ -223,7 +227,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(): @@ -231,13 +235,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(): @@ -320,21 +327,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 @@ -477,11 +487,11 @@ def test_keep_file_open_true_false_invalid(): fname = 'testdata' with open(fname, 'wb') as fobj: fobj.write(data.tostring(order='F')) - with assert_raises(ValueError): + with pytest.raises(ValueError): ArrayProxy(fname, ((10, 10, 10), dtype), keep_file_open=55) - with assert_raises(ValueError): + with pytest.raises(ValueError): ArrayProxy(fname, ((10, 10, 10), dtype), keep_file_open='autob') - with assert_raises(ValueError): + with pytest.raises(ValueError): ArrayProxy(fname, ((10, 10, 10), dtype), keep_file_open='cauto') 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_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..60bd008a46 100644 --- a/nibabel/tests/test_brikhead.py +++ b/nibabel/tests/test_brikhead.py @@ -14,12 +14,11 @@ 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, assert_data_similar from .test_fileslice import slicer_samples -from .test_helpers import assert_data_similar EXAMPLE_IMAGES = [ dict( @@ -80,10 +79,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 +93,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 +122,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 +133,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 +144,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 diff --git a/nibabel/tests/test_checkwarns.py b/nibabel/tests/test_checkwarns.py index b1e6483273..993b030b78 100644 --- a/nibabel/tests/test_checkwarns.py +++ b/nibabel/tests/test_checkwarns.py @@ -1,6 +1,6 @@ """ Tests for warnings context managers """ -from ..testing import assert_equal, assert_warns, suppress_warnings +from ..testing_pytest import assert_warns, suppress_warnings def test_ignore_and_error_warnings(): diff --git a/nibabel/tests/test_data.py b/nibabel/tests/test_data.py index 641d6e55cd..e48356eb50 100644 --- a/nibabel/tests/test_data.py +++ b/nibabel/tests/test_data.py @@ -16,93 +16,78 @@ 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, +from .test_environment import (with_environment, DATA_KEY, USER_KEY) -DATA_FUNCS = {} - -def setup_data_env(): - setup_environment() - global DATA_FUNCS +@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'] -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 +96,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 +114,7 @@ def test__cfg_value(): pass -@with_environment -def test_data_path(): +def test_data_path(with_nimd_env): # wipe out any sources of data paths if DATA_KEY in env: del env[DATA_KEY] @@ -147,15 +131,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 +148,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 +162,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 +173,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_nimd_env): 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_nimd_env): 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 +239,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) 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 d9401db156..72dcc65a1a 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.float32, np.float64] try: @@ -43,17 +41,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) @@ -78,14 +76,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(): @@ -93,35 +91,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 @@ -130,13 +130,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(): @@ -146,18 +148,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 @@ -165,29 +169,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(): @@ -196,15 +202,14 @@ 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)) +@pytest.mark.skipif(not have_float16, reason='No float16') def test_floor_exact_16(): # A normal integer can generate an inf in float16 - if not have_float16: - raise SkipTest('No 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(): @@ -213,11 +218,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(): @@ -236,21 +241,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()): @@ -261,28 +266,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(): @@ -290,7 +295,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 26d70b6e55..78193f4307 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,27 +17,27 @@ 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... - assert_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_image_api.py b/nibabel/tests/test_image_api.py index 10b61628c7..916f1d030f 100644 --- a/nibabel/tests/test_image_api.py +++ b/nibabel/tests/test_image_api.py @@ -41,16 +41,14 @@ 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, clear_and_catch_warnings) from ..tmpdirs import InTemporaryDirectory 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 @@ -108,7 +106,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 @@ -116,13 +115,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 @@ -144,8 +144,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)): @@ -162,8 +162,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 @@ -183,19 +185,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): @@ -209,8 +211,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']: @@ -218,53 +220,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 @@ -275,16 +280,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. @@ -296,21 +301,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 @@ -318,7 +323,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 @@ -344,8 +349,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`` @@ -355,10 +360,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) @@ -366,15 +371,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 @@ -384,7 +389,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 @@ -392,40 +397,43 @@ 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 clear_and_catch_warnings() as w: warnings.simplefilter('always', DeprecationWarning) - assert_equal(img.get_shape(), params['shape']) - assert_equal(len(w), 1) + assert img.get_shape() == params['shape'] + assert len(w) == 1 def validate_mmap_parameter(self, imaker, params): img = imaker() @@ -449,10 +457,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 @@ -470,8 +478,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): @@ -485,11 +493,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 @@ -497,11 +506,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): @@ -585,7 +594,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) @@ -708,7 +717,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 a4d42fdc36..33afd4ea60 100644 --- a/nibabel/tests/test_minc1.py +++ b/nibabel/tests/test_minc1.py @@ -24,12 +24,12 @@ 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 ..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 -from .test_helpers import assert_data_similar EG_FNAME = pjoin(data_path, 'tiny.mnc') @@ -110,40 +110,40 @@ def test_old_namespace(): # This import does not trigger an import of the minc.py module, because # it's the proxy object. from .. import minc - assert_equal(warns, []) + assert warns == [] # If there was a previous import it will be module, otherwise it will be # a proxy previous_import = isinstance(minc, types.ModuleType) if not previous_import: - assert_true(isinstance(minc, ModuleProxy)) + assert isinstance(minc, ModuleProxy) old_minc1image = minc.Minc1Image # just to check it works # There may or may not be a warning raised on accessing the proxy, # depending on whether the minc.py module is already imported in this # test run. if not previous_import: - assert_equal(warns.pop(0).category, DeprecationWarning) + assert warns.pop(0).category == DeprecationWarning with clear_and_catch_warnings() as warns: from .. import Minc1Image, MincImage - assert_equal(warns, []) + assert warns == [] # The import from old module is the same as that from new - assert_true(old_minc1image is Minc1Image) + assert old_minc1image is Minc1Image # But the old named import, imported from new, is not the same - assert_false(Minc1Image is MincImage) - assert_equal(warns, []) + assert not Minc1Image is MincImage + assert warns == [] # Create object using old name mimg = MincImage(arr, aff) # Call to create object created warning - assert_equal(warns.pop(0).category, FutureWarning) + assert warns.pop(0).category == FutureWarning assert_array_equal(mimg.get_fdata(), arr) # Another old name from ..minc1 import MincFile, Minc1File - assert_false(MincFile is Minc1File) - assert_equal(warns, []) + assert not MincFile is Minc1File + assert warns == [] mf = MincFile(netcdf_file(EG_FNAME)) # Call to create object created warning - assert_equal(warns.pop(0).category, FutureWarning) - assert_equal(mf.get_data_shape(), (10, 20, 20)) + assert warns.pop(0).category == FutureWarning + assert mf.get_data_shape() == (10, 20, 20) class _TestMincFile(object): @@ -157,12 +157,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 @@ -186,7 +186,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 @@ -200,7 +200,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]) @@ -230,8 +230,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): @@ -245,7 +247,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) \ No newline at end of file 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) 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 0213b615f1..ef663f6e7b 100644 --- a/nibabel/tests/test_nifti1.py +++ b/nibabel/tests/test_nifti1.py @@ -29,20 +29,19 @@ 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) -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 69704eaeb1..2ac62f383c 100644 --- a/nibabel/tests/test_openers.py +++ b/nibabel/tests/test_openers.py @@ -19,9 +19,8 @@ from ..volumeutils import BinOpener 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 99f90b5de6..33000530a4 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('= np.dtype(dtype) # Shape matches expected shape - assert_equal(out.shape, params['shape']) + assert out.shape == params['shape'] def validate_header_isolated(self, pmaker, params): # Confirm altering input header has no effect @@ -289,8 +288,8 @@ def validate_dtype(self, pmaker, params): # Read-only dtype attribute prox, fio, hdr = pmaker() assert_dt_equal(prox.dtype, params['dtype']) - assert_raises(AttributeError, - prox.__setattr__, 'dtype', np.dtype(prox.dtype)) + with pytest.raises(AttributeError): + prox.__setattr__('dtype', np.dtype(prox.dtype)) def validate_slope_inter_offset(self, pmaker, params): # Check slope, inter, offset @@ -299,17 +298,17 @@ def validate_slope_inter_offset(self, pmaker, params): expected = params[attr_name] assert_array_equal(getattr(prox, attr_name), expected) # Read only - assert_raises(AttributeError, - setattr, prox, attr_name, expected) + with pytest.raises(AttributeError): + setattr(prox, attr_name, expected) def validate_deprecated_header(self, pmaker, params): prox, fio, hdr = pmaker() with warnings.catch_warnings(record=True) as warns: warnings.simplefilter("always") # Header is a copy of original - assert_false(prox.header is hdr) - assert_equal(prox.header, hdr) - assert_equal(warns.pop(0).category, DeprecationWarning) + assert not prox.header is hdr + assert prox.header == hdr + assert warns.pop(0).category == DeprecationWarning class TestSpm99AnalyzeProxyAPI(TestAnalyzeProxyAPI): @@ -407,7 +406,7 @@ def eg_func(): arr_out=arr_out)) def validate_header_isolated(self, pmaker, params): - raise SkipTest('ECAT header does not support dtype get') + raise pytest.skip('ECAT header does not support dtype get') class TestPARRECAPI(_TestProxyAPI): diff --git a/nibabel/tests/test_quaternions.py b/nibabel/tests/test_quaternions.py index a3f2ba9546..cb24c7d0ce 100644 --- a/nibabel/tests/test_quaternions.py +++ b/nibabel/tests/test_quaternions.py @@ -11,11 +11,9 @@ import numpy as np from numpy import pi -from ..testing import slow -from nose.tools import assert_raises, assert_true, assert_false, \ - assert_equal +import pytest -from numpy.testing import assert_array_almost_equal, assert_array_equal +from numpy.testing import assert_array_almost_equal, assert_array_equal, dec from .. import quaternions as nq from .. import eulerangles as nea @@ -55,129 +53,135 @@ def test_fillpos(): # Takes np array xyz = np.zeros((3,)) w, x, y, z = nq.fillpositive(xyz) - yield assert_true, w == 1 + assert w == 1 # Or lists xyz = [0] * 3 w, x, y, z = nq.fillpositive(xyz) - yield assert_true, w == 1 + assert w == 1 # Errors with wrong number of values - yield assert_raises, ValueError, nq.fillpositive, [0, 0] - yield assert_raises, ValueError, nq.fillpositive, [0] * 4 + with pytest.raises(ValueError): + nq.fillpositive([0, 0]) + with pytest.raises(ValueError): + nq.fillpositive([0] * 4) # Errors with negative w2 - yield assert_raises, ValueError, nq.fillpositive, [1.0] * 3 + with pytest.raises(ValueError): + nq.fillpositive([1.0] * 3) # Test corner case where w is near zero wxyz = nq.fillpositive([1, 0, 0]) - yield assert_true, wxyz[0] == 0.0 + assert wxyz[0] == 0.0 def test_conjugate(): # Takes sequence cq = nq.conjugate((1, 0, 0, 0)) # Returns float type - yield assert_true, cq.dtype.kind == 'f' + assert cq.dtype.kind == 'f' def test_quat2mat(): # also tested in roundtrip case below M = nq.quat2mat([1, 0, 0, 0]) - yield assert_array_almost_equal, M, np.eye(3) + assert_array_almost_equal, M, np.eye(3) M = nq.quat2mat([3, 0, 0, 0]) - yield assert_array_almost_equal, M, np.eye(3) + assert_array_almost_equal, M, np.eye(3) M = nq.quat2mat([0, 1, 0, 0]) - yield assert_array_almost_equal, M, np.diag([1, -1, -1]) + assert_array_almost_equal, M, np.diag([1, -1, -1]) M = nq.quat2mat([0, 2, 0, 0]) - yield assert_array_almost_equal, M, np.diag([1, -1, -1]) + assert_array_almost_equal, M, np.diag([1, -1, -1]) M = nq.quat2mat([0, 0, 0, 0]) - yield assert_array_almost_equal, M, np.eye(3) + assert_array_almost_equal, M, np.eye(3) -def test_inverse(): +def test_inverse_0(): # Takes sequence iq = nq.inverse((1, 0, 0, 0)) # Returns float type - yield assert_true, iq.dtype.kind == 'f' - for M, q in eg_pairs: - iq = nq.inverse(q) - iqM = nq.quat2mat(iq) - iM = np.linalg.inv(M) - yield assert_true, np.allclose(iM, iqM) + assert iq.dtype.kind == 'f' + + +@pytest.mark.parametrize("M, q", eg_pairs) +def test_inverse_1(M, q): + iq = nq.inverse(q) + iqM = nq.quat2mat(iq) + iM = np.linalg.inv(M) + assert np.allclose(iM, iqM) def test_eye(): qi = nq.eye() - yield assert_true, qi.dtype.kind == 'f' - yield assert_true, np.all([1, 0, 0, 0] == qi) - yield assert_true, np.allclose(nq.quat2mat(qi), np.eye(3)) + assert qi.dtype.kind == 'f' + assert np.all([1, 0, 0, 0] == qi) + assert np.allclose(nq.quat2mat(qi), np.eye(3)) def test_norm(): qi = nq.eye() - yield assert_true, nq.norm(qi) == 1 - yield assert_true, nq.isunit(qi) + assert nq.norm(qi) == 1 + assert nq.isunit(qi) qi[1] = 0.2 - yield assert_true, not nq.isunit(qi) + assert not nq.isunit(qi) -@slow -def test_mult(): +@dec.slow +@pytest.mark.parametrize("M1, q1", eg_pairs[0::4]) +@pytest.mark.parametrize("M2, q2", eg_pairs[1::4]) +def test_mult(M1, q1, M2, q2): # Test that quaternion * same as matrix * - for M1, q1 in eg_pairs[0::4]: - for M2, q2 in eg_pairs[1::4]: - q21 = nq.mult(q2, q1) - yield assert_array_almost_equal, np.dot(M2, M1), nq.quat2mat(q21) + q21 = nq.mult(q2, q1) + assert_array_almost_equal, np.dot(M2, M1), nq.quat2mat(q21) -def test_inverse(): - for M, q in eg_pairs: - iq = nq.inverse(q) - iqM = nq.quat2mat(iq) - iM = np.linalg.inv(M) - yield assert_true, np.allclose(iM, iqM) +@pytest.mark.parametrize("M, q", eg_pairs) +def test_inverse(M, q): + iq = nq.inverse(q) + iqM = nq.quat2mat(iq) + iM = np.linalg.inv(M) + assert np.allclose(iM, iqM) def test_eye(): qi = nq.eye() - yield assert_true, np.all([1, 0, 0, 0] == qi) - yield assert_true, np.allclose(nq.quat2mat(qi), np.eye(3)) + assert np.all([1, 0, 0, 0] == qi) + assert np.allclose(nq.quat2mat(qi), np.eye(3)) -def test_qrotate(): - for vec in np.eye(3): - for M, q in eg_pairs: - vdash = nq.rotate_vector(vec, q) - vM = np.dot(M, vec) - yield assert_array_almost_equal, vdash, vM +@pytest.mark.parametrize("vec", np.eye(3)) +@pytest.mark.parametrize("M, q", eg_pairs) +def test_qrotate(vec, M, q): + vdash = nq.rotate_vector(vec, q) + vM = np.dot(M, vec) + assert_array_almost_equal(vdash, vM) -def test_quaternion_reconstruction(): +@pytest.mark.parametrize("q", unit_quats) +def test_quaternion_reconstruction(q): # Test reconstruction of arbitrary unit quaternions - for q in unit_quats: - M = nq.quat2mat(q) - qt = nq.mat2quat(M) - # Accept positive or negative match - posm = np.allclose(q, qt) - negm = np.allclose(q, -qt) - yield assert_true, posm or negm + M = nq.quat2mat(q) + qt = nq.mat2quat(M) + # Accept positive or negative match + posm = np.allclose(q, qt) + negm = np.allclose(q, -qt) + assert (posm or negm) def test_angle_axis2quat(): q = nq.angle_axis2quat(0, [1, 0, 0]) - yield assert_array_equal, q, [1, 0, 0, 0] + assert_array_equal(q, [1, 0, 0, 0]) q = nq.angle_axis2quat(np.pi, [1, 0, 0]) - yield assert_array_almost_equal, q, [0, 1, 0, 0] + assert_array_almost_equal(q, [0, 1, 0, 0]) q = nq.angle_axis2quat(np.pi, [1, 0, 0], True) - yield assert_array_almost_equal, q, [0, 1, 0, 0] + assert_array_almost_equal(q, [0, 1, 0, 0]) q = nq.angle_axis2quat(np.pi, [2, 0, 0], False) - yield assert_array_almost_equal, q, [0, 1, 0, 0] + assert_array_almost_equal(q, [0, 1, 0, 0]) def test_angle_axis(): for M, q in eg_pairs: theta, vec = nq.quat2angle_axis(q) q2 = nq.angle_axis2quat(theta, vec) - yield nq.nearly_equivalent, q, q2 + nq.nearly_equivalent(q, q2) aa_mat = nq.angle_axis2mat(theta, vec) - yield assert_array_almost_equal, aa_mat, M + assert_array_almost_equal(aa_mat, M) unit_vec = vec / np.sqrt(vec.dot(vec)) aa_mat2 = nq.angle_axis2mat(theta, unit_vec, is_normalized=True) - yield assert_array_almost_equal, aa_mat2, M + assert_array_almost_equal(aa_mat2, M) 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 ce1ba668b2..9cfb6ca13c 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 = [ ('4.0.0', ['nibabel.trackvis']), @@ -25,8 +25,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(): @@ -37,7 +38,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(): @@ -52,5 +53,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) diff --git a/nibabel/tests/test_scaling.py b/nibabel/tests/test_scaling.py index 019cc58d1c..456a295532 100644 --- a/nibabel/tests/test_scaling.py +++ b/nibabel/tests/test_scaling.py @@ -14,112 +14,121 @@ from ..volumeutils import (calculate_scale, scale_min_max, 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 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_scale_min_max(): +# TODO: this test fails on my mac for uint64 +@pytest.mark.parametrize("tp", np.sctypes['uint'] + np.sctypes['int']) +@pytest.mark.parametrize("mn, mx", [ + (0, "imax"), + ("imin", 0), + ("imin", "imax"), + (1, 10), + (-1, -1), + (1, 1), + (-10, -1), + (-100, 10) +]) +def test_scale_min_max(tp, mn, mx): mx_dt = np.maximum_sctype(np.float) - for tp in np.sctypes['uint'] + np.sctypes['int']: - info = np.iinfo(tp) - # Need to pump up to max fp type to contain python longs - imin = np.array(info.min, dtype=mx_dt) - imax = np.array(info.max, dtype=mx_dt) - value_pairs = ( - (0, imax), - (imin, 0), - (imin, imax), - (1, 10), - (-1, -1), - (1, 1), - (-10, -1), - (-100, 10)) - for mn, mx in value_pairs: - # with intercept - scale, inter = scale_min_max(mn, mx, tp, True) - if mx - mn: - assert_array_almost_equal, (mx - inter) / scale, imax - assert_array_almost_equal, (mn - inter) / scale, imin - else: - assert_equal, (scale, inter), (1.0, mn) - # without intercept - if imin == 0 and mn < 0 and mx > 0: - (assert_raises, ValueError, - scale_min_max, mn, mx, tp, False) - continue - scale, inter = scale_min_max(mn, mx, tp, False) - assert_equal, inter, 0.0 - if mn == 0 and mx == 0: - assert_equal, scale, 1.0 - continue - sc_mn = mn / scale - sc_mx = mx / scale - assert_true, sc_mn >= imin - assert_true, sc_mx <= imax - if imin == 0: - if mx > 0: # numbers all +ve - assert_array_almost_equal, mx / scale, imax - else: # numbers all -ve - assert_array_almost_equal, mn / scale, imax - continue - if abs(mx) >= abs(mn): - assert_array_almost_equal, mx / scale, imax - else: - assert_array_almost_equal, mn / scale, imin + info = np.iinfo(tp) + # Need to pump up to max fp type to contain python longs + imin = np.array(info.min, dtype=mx_dt) + imax = np.array(info.max, dtype=mx_dt) + if mn == "imin": + mn = imin + if mx == "imax": + mx = imax + + # with intercept + scale, inter = scale_min_max(mn, mx, tp, True) + if mx - mn: + assert_array_almost_equal, (mx - inter) / scale, imax + assert_array_almost_equal, (mn - inter) / scale, imin + else: + assert (scale, inter) == (1.0, mn) + # without intercept + if imin == 0 and mn < 0 and mx > 0: + with pytest.raises(ValueError): + scale_min_max(mn, mx, tp, False) + return + scale, inter = scale_min_max(mn, mx, tp, False) + assert inter == 0.0 + if mn == 0 and mx == 0: + assert scale == 1.0 + return + sc_mn = mn / scale + sc_mx = mx / scale + assert sc_mn >= imin + assert sc_mx <= imax + + if imin == 0: + if mx > 0: # numbers all +ve + assert_array_almost_equal, mx / scale, imax + else: # numbers all -ve + assert_array_almost_equal, mn / scale, imax + return + if abs(mx) >= abs(mn): + assert_array_almost_equal, mx / scale, imax + else: + assert_array_almost_equal, mn / scale, imin -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_calculate_scale(): @@ -127,52 +136,52 @@ def test_calculate_scale(): npa = np.array # Here the offset handles it res = calculate_scale(npa([-2, -1], dtype=np.int8), np.uint8, True) - assert_equal(res, (1.0, -2.0, None, None)) + assert res == (1.0, -2.0, None, None) # Not having offset not a problem obviously res = calculate_scale(npa([-2, -1], dtype=np.int8), np.uint8, 0) - assert_equal(res, (-1.0, 0.0, None, None)) + assert res == (-1.0, 0.0, None, None) # Case where offset handles scaling res = calculate_scale(npa([-1, 1], dtype=np.int8), np.uint8, 1) - assert_equal(res, (1.0, -1.0, None, None)) + assert res == (1.0, -1.0, None, None) # Can't work for no offset case - assert_raises(ValueError, - calculate_scale, npa([-1, 1], dtype=np.int8), np.uint8, 0) + with pytest.raises(ValueError): + calculate_scale(npa([-1, 1], dtype=np.int8), np.uint8, 0) # Offset trick can't work when max is out of range res = calculate_scale(npa([-1, 255], dtype=np.int16), np.uint8, 1) - assert_not_equal(res, (1.0, -1.0, None, None)) + assert res != (1.0, -1.0, None, None) -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(): @@ -198,54 +207,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) + 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) -def test_scaling_in_abstract(): +@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): @@ -274,7 +292,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) @@ -285,5 +303,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))) diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 6d46e57c5c..5e7defdaa5 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -31,8 +31,9 @@ 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 +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 7d275e3366..11e00d26f2 100644 --- a/nibabel/tests/test_spatialimages.py +++ b/nibabel/tests/test_spatialimages.py @@ -24,12 +24,12 @@ 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 .. 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 86143f35ab..ecc63e5935 100644 --- a/nibabel/tests/test_spm99analyze.py +++ b/nibabel/tests/test_spm99analyze.py @@ -29,9 +29,10 @@ 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 +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 4072f85131..d71d9f1cd7 100644 --- a/nibabel/tests/test_volumeutils.py +++ b/nibabel/tests/test_volumeutils.py @@ -57,6 +57,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'] diff --git a/nibabel/tests/test_wrapstruct.py b/nibabel/tests/test_wrapstruct.py index 45e8c28a52..f627109fd0 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 @@ -120,15 +119,17 @@ 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 - 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) @@ -139,49 +140,53 @@ 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_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 + if not self.header_class: + pytest.skip() hdr = self.header_class() str_io = BytesIO() 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): + if not self.header_class: + pytest.skip() 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 +194,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): @@ -202,17 +207,22 @@ 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() - assert_raises(AttributeError, hdr.__setattr__, 'endianness', '<') + 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_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 @@ -221,18 +231,23 @@ 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) - assert_equal(str_io.getvalue(), hdr.binaryblock) + assert str_io.getvalue() == hdr.binaryblock 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 # 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 +256,53 @@ 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 + if not self.header_class: + pytest.skip() 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 + if not self.header_class: + pytest.skip() 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,13 +310,16 @@ 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) 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) @@ -308,10 +329,13 @@ 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) - assert_true(len(s1) > 0) + assert len(s1) > 0 + class _TestLabeledWrapStruct(_TestWrapStructBase): @@ -320,31 +344,36 @@ 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() # 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 +447,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 +499,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 +528,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 +548,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