diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index 89b47b8345..3eb6cececb 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -49,10 +49,12 @@ jobs: -I test_batteryrunners ^ -I test_brikhead ^ -I test_casting ^ + -I test_cifti2io_axes ^ -I test_cifti2io_header ^ -I test_data ^ -I test_deprecated ^ -I test_deprecator ^ + -I test_dicomwrappers ^ -I test_dft ^ -I test_ecat ^ -I test_ecat_data ^ @@ -75,6 +77,7 @@ jobs: -I test_image_types ^ -I test_imageclasses ^ -I test_imageglobals ^ + -I test_io ^ -I test_keywordonly ^ -I test_loadsave ^ -I test_minc1 ^ @@ -99,6 +102,9 @@ jobs: -I test_round_trip ^ -I test_rstutils ^ -I test_scaling ^ + -I test_scripts ^ + -I test_spaces ^ + -I test_testing ^ -I test_wrapstruct displayName: 'Nose tests' condition: and(succeeded(), eq(variables['CHECK_TYPE'], 'nosetests')) diff --git a/.travis.yml b/.travis.yml index b869d33947..76d2535e68 100644 --- a/.travis.yml +++ b/.travis.yml @@ -136,10 +136,12 @@ script: -I test_batteryrunners \ -I test_brikhead \ -I test_casting \ + -I test_cifti2io_axes \ -I test_cifti2io_header \ -I test_data \ -I test_deprecated \ -I test_deprecator \ + -I test_dicomwrappers \ -I test_dft \ -I test_ecat \ -I test_ecat_data \ @@ -162,6 +164,7 @@ script: -I test_image_types \ -I test_imageclasses \ -I test_imageglobals \ + -I test_io \ -I test_keywordonly \ -I test_loadsave \ -I test_minc1 \ @@ -186,6 +189,9 @@ script: -I test_round_trip \ -I test_rstutils \ -I test_scaling \ + -I test_scripts \ + -I test_spaces \ + -I test_testing \ -I test_wrapstruct elif [ "${CHECK_TYPE}" == "test" ]; then # Change into an innocuous directory and find tests from installation diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 529e103f46..e2e5bc9ed3 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -4,7 +4,7 @@ from os import environ, listdir from os.path import dirname, realpath, join as pjoin, isdir, exists -from ..testing import skipif +import pytest def get_nibabel_data(): @@ -39,11 +39,11 @@ def needs_nibabel_data(subdir=None): """ nibabel_data = get_nibabel_data() if nibabel_data == '': - return skipif(True, "Need nibabel-data directory for this test") + return pytest.mark.skipif(True, reason="Need nibabel-data directory for this test") if subdir is None: - return skipif(False) + return pytest.mark.skipif(False, reason="Don't skip") required_path = pjoin(nibabel_data, subdir) # Path should not be empty (as is the case for not-updated submodules) have_files = exists(required_path) and len(listdir(required_path)) > 0 - return skipif(not have_files, - "Need files in {0} for these tests".format(required_path)) + return pytest.mark.skipif(not have_files, + reason="Need files in {0} for these tests".format(required_path)) \ No newline at end of file diff --git a/nibabel/tests/scriptrunner.py b/nibabel/tests/scriptrunner.py index 33b5e3dcef..0027cc36b2 100644 --- a/nibabel/tests/scriptrunner.py +++ b/nibabel/tests/scriptrunner.py @@ -135,7 +135,7 @@ def run_command(self, cmd, check_code=True): env['PYTHONPATH'] = self.local_module_dir + pathsep + pypath proc = Popen(cmd, stdout=PIPE, stderr=PIPE, env=env) stdout, stderr = proc.communicate() - if proc.poll() == None: + if proc.poll() is None: proc.terminate() if check_code and proc.returncode != 0: raise RuntimeError( diff --git a/nibabel/tests/test_analyze.py b/nibabel/tests/test_analyze.py index 14bfb3b5e7..2b2e78dd23 100644 --- a/nibabel/tests/test_analyze.py +++ b/nibabel/tests/test_analyze.py @@ -512,7 +512,7 @@ def test_from_header(self): for check in (True, False): copy = klass.from_header(hdr, check=check) assert hdr == copy - assert not hdr is copy + assert hdr is not copy class C(object): diff --git a/nibabel/tests/test_arraywriters.py b/nibabel/tests/test_arraywriters.py index 8f30f04321..1a1c4eb156 100644 --- a/nibabel/tests/test_arraywriters.py +++ b/nibabel/tests/test_arraywriters.py @@ -508,9 +508,9 @@ def test_nan2zero(): assert_array_equal(np.isnan(data_back), [True, False]) # Deprecation warning for nan2zero as argument to `to_fileobj` with error_warnings(): - with pytest.raises(DeprecationWarning): + with pytest.deprecated_call(): aw.to_fileobj(BytesIO(), 'F', True) - with pytest.raises(DeprecationWarning): + with pytest.deprecated_call(): aw.to_fileobj(BytesIO(), 'F', nan2zero=True) # Error if nan2zero is not the value set at initialization with pytest.raises(WriterError): @@ -530,9 +530,9 @@ def test_nan2zero(): assert_array_equal(data_back, [astype_res, 99]) # Deprecation warning for nan2zero as argument to `to_fileobj` with error_warnings(): - with pytest.raises(DeprecationWarning): + with pytest.deprecated_call(): aw.to_fileobj(BytesIO(), 'F', False) - with pytest.raises(DeprecationWarning): + with pytest.deprecated_call(): aw.to_fileobj(BytesIO(), 'F', nan2zero=False) # Error if nan2zero is not the value set at initialization with pytest.raises(WriterError): diff --git a/nibabel/tests/test_casting.py b/nibabel/tests/test_casting.py index 3fe74dfb8b..c4f9b9ba9e 100644 --- a/nibabel/tests/test_casting.py +++ b/nibabel/tests/test_casting.py @@ -155,7 +155,7 @@ def test_floor_log2(): assert floor_log2(0.75) == -1 assert floor_log2(0.25) == -2 assert floor_log2(0.24) == -3 - assert floor_log2(0) == None + assert floor_log2(0) is None def test_able_int_type(): diff --git a/nibabel/tests/test_deprecator.py b/nibabel/tests/test_deprecator.py index 14255da4b4..c508795cf9 100644 --- a/nibabel/tests/test_deprecator.py +++ b/nibabel/tests/test_deprecator.py @@ -34,9 +34,9 @@ def test__add_dep_doc(): assert _add_dep_doc('bar\n\n', 'foo') == 'bar\n\nfoo\n' assert _add_dep_doc('bar\n \n', 'foo') == 'bar\n\nfoo\n' assert (_add_dep_doc(' bar\n\nSome explanation', 'foo\nbaz') == - ' bar\n\nfoo\nbaz\n\nSome explanation\n') + ' bar\n\nfoo\nbaz\n\nSome explanation\n') assert (_add_dep_doc(' bar\n\n Some explanation', 'foo\nbaz') == - ' bar\n \n foo\n baz\n \n Some explanation\n') + ' bar\n \n foo\n baz\n \n Some explanation\n') class CustomError(Exception): @@ -69,36 +69,29 @@ def test_dep_func(self): # Test function deprecation dec = self.dep_func func = dec('foo')(func_no_doc) - with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: - warnings.simplefilter('always') - assert func() == None - assert len(w) == 1 - assert w[0].category is DeprecationWarning + with pytest.deprecated_call(): + assert func() is None assert func.__doc__ == 'foo\n' func = dec('foo')(func_doc) - with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: - warnings.simplefilter('always') - assert func(1) == None + with pytest.deprecated_call() as w: + assert func(1) is None assert len(w) == 1 assert func.__doc__ == 'A docstring\n\nfoo\n' func = dec('foo')(func_doc_long) - with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: - warnings.simplefilter('always') - assert func(1, 2) == None + with pytest.deprecated_call() as w: + assert func(1, 2) is None assert len(w) == 1 assert func.__doc__ == 'A docstring\n \n foo\n \n Some text\n' # Try some since and until versions func = dec('foo', '1.1')(func_no_doc) assert func.__doc__ == 'foo\n\n* deprecated from version: 1.1\n' - with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: - warnings.simplefilter('always') - assert func() == None + with pytest.deprecated_call() as w: + assert func() is None assert len(w) == 1 func = dec('foo', until='99.4')(func_no_doc) - with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: - warnings.simplefilter('always') - assert func() == None + with pytest.deprecated_call() as w: + assert func() is None assert len(w) == 1 assert (func.__doc__ == 'foo\n\n* Will raise {} as of version: 99.4\n' @@ -107,22 +100,22 @@ def test_dep_func(self): with pytest.raises(ExpiredDeprecationError): func() assert (func.__doc__ == - 'foo\n\n* Raises {} as of version: 1.8\n' - .format(ExpiredDeprecationError)) + 'foo\n\n* Raises {} as of version: 1.8\n' + .format(ExpiredDeprecationError)) func = dec('foo', '1.2', '1.8')(func_no_doc) with pytest.raises(ExpiredDeprecationError): func() assert (func.__doc__ == - 'foo\n\n* deprecated from version: 1.2\n' - '* Raises {} as of version: 1.8\n' - .format(ExpiredDeprecationError)) + 'foo\n\n* deprecated from version: 1.2\n' + '* Raises {} as of version: 1.8\n' + .format(ExpiredDeprecationError)) func = dec('foo', '1.2', '1.8')(func_doc_long) assert (func.__doc__ == - 'A docstring\n \n foo\n \n' - ' * deprecated from version: 1.2\n' - ' * Raises {} as of version: 1.8\n \n' - ' Some text\n' - .format(ExpiredDeprecationError)) + 'A docstring\n \n foo\n \n' + ' * deprecated from version: 1.2\n' + ' * Raises {} as of version: 1.8\n \n' + ' Some text\n' + .format(ExpiredDeprecationError)) with pytest.raises(ExpiredDeprecationError): func() @@ -130,16 +123,13 @@ def test_dep_func(self): func = dec('foo', warn_class=UserWarning)(func_no_doc) with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: warnings.simplefilter('always') - assert func() == None + assert func() is None assert len(w) == 1 assert w[0].category is UserWarning func = dec('foo', error_class=CustomError)(func_no_doc) - with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: - warnings.simplefilter('always') - assert func() == None - assert len(w) == 1 - assert w[0].category is DeprecationWarning + with pytest.deprecated_call(): + assert func() is None func = dec('foo', until='1.8', error_class=CustomError)(func_no_doc) with pytest.raises(CustomError): @@ -154,19 +144,15 @@ class TestDeprecatorMaker(object): def test_deprecator_maker(self): dec = self.dep_maker(warn_class=UserWarning) func = dec('foo')(func_no_doc) - with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: - warnings.simplefilter('always') - assert func() == None + with pytest.warns(UserWarning) as w: + # warnings.simplefilter('always') + assert func() is None assert len(w) == 1 - assert w[0].category is UserWarning dec = self.dep_maker(error_class=CustomError) func = dec('foo')(func_no_doc) - with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: - warnings.simplefilter('always') - assert func() == None - assert len(w) == 1 - assert w[0].category is DeprecationWarning + with pytest.deprecated_call(): + assert func() is None func = dec('foo', until='1.8')(func_no_doc) with pytest.raises(CustomError): diff --git a/nibabel/tests/test_ecat.py b/nibabel/tests/test_ecat.py index b681a59b0e..918cffc52b 100644 --- a/nibabel/tests/test_ecat.py +++ b/nibabel/tests/test_ecat.py @@ -21,7 +21,7 @@ from numpy.testing import assert_array_equal, assert_array_almost_equal -from ..testing_pytest import data_path, suppress_warnings, clear_and_catch_warnings +from ..testing_pytest import data_path, suppress_warnings from ..tmpdirs import InTemporaryDirectory from .test_wrapstruct import _TestWrapStructBase @@ -164,7 +164,7 @@ def test_subheader(self): assert self.subhdr.get_nframes() == 1 assert (self.subhdr.get_nframes() == len(self.subhdr.subheaders)) - assert self.subhdr._check_affines() == True + assert self.subhdr._check_affines() is True assert_array_almost_equal(np.diag(self.subhdr.get_frame_affine()), np.array([2.20241979, 2.20241979, 3.125, 1.])) assert self.subhdr.get_zooms()[0] == 2.20241978764534 @@ -271,8 +271,7 @@ def test_mlist_regression(self): def test_from_filespec_deprecation(): # Check from_filespec raises Deprecation - with clear_and_catch_warnings() as w: - warnings.simplefilter('always', DeprecationWarning) + with pytest.deprecated_call() as w: # No warning for standard load img_loaded = EcatImage.load(ecat_file) assert len(w) == 0 diff --git a/nibabel/tests/test_environment.py b/nibabel/tests/test_environment.py index e0514c337e..19891a607b 100644 --- a/nibabel/tests/test_environment.py +++ b/nibabel/tests/test_environment.py @@ -60,4 +60,4 @@ def test_sys_dir(): elif os.name == 'posix': assert sys_dir == r'/etc/nipy' else: - assert sys_dir == None + assert sys_dir is None diff --git a/nibabel/tests/test_files_interface.py b/nibabel/tests/test_files_interface.py index a75484159e..da91aaf03a 100644 --- a/nibabel/tests/test_files_interface.py +++ b/nibabel/tests/test_files_interface.py @@ -29,8 +29,8 @@ def test_files_spatialimages(): for klass in klasses: file_map = klass.make_file_map() for key, value in file_map.items(): - assert value.filename == None - assert value.fileobj == None + assert value.filename is None + assert value.fileobj is None assert value.pos == 0 # If we can't create new images in memory without loading, bail here if not klass.makeable: @@ -42,8 +42,8 @@ def test_files_spatialimages(): else: img = klass(arr, aff) for key, value in img.file_map.items(): - assert value.filename == None - assert value.fileobj == None + assert value.filename is None + assert value.fileobj is None assert value.pos == 0 diff --git a/nibabel/tests/test_fileslice.py b/nibabel/tests/test_fileslice.py index 5c80ae01b5..07a2627910 100644 --- a/nibabel/tests/test_fileslice.py +++ b/nibabel/tests/test_fileslice.py @@ -47,7 +47,7 @@ def test_is_fancy(): assert not is_fancy((None, 1)) assert not is_fancy((1, None)) # Chack that actual False returned (rather than falsey) - assert is_fancy(1) == False + assert is_fancy(1) is False def test_canonical_slicers(): @@ -243,9 +243,9 @@ def test_threshold_heuristic(): # Test for default skip / read heuristic # int assert threshold_heuristic(1, 9, 1, skip_thresh=8) == 'full' - assert threshold_heuristic(1, 9, 1, skip_thresh=7) == None + assert threshold_heuristic(1, 9, 1, skip_thresh=7) is None assert threshold_heuristic(1, 9, 2, skip_thresh=16) == 'full' - assert threshold_heuristic(1, 9, 2, skip_thresh=15) == None + assert threshold_heuristic(1, 9, 2, skip_thresh=15) is None # full slice, smallest step size assert (threshold_heuristic( slice(0, 9, 1), 9, 2, skip_thresh=2) == diff --git a/nibabel/tests/test_funcs.py b/nibabel/tests/test_funcs.py index 94645f2839..db196995e0 100644 --- a/nibabel/tests/test_funcs.py +++ b/nibabel/tests/test_funcs.py @@ -138,7 +138,7 @@ def test_closest_canonical(): # And a case where the Analyze image has to be flipped img = AnalyzeImage(arr, np.diag([-1, 1, 1, 1])) xyz_img = as_closest_canonical(img) - assert not img is xyz_img + assert img is not xyz_img out_arr = xyz_img.get_fdata() assert_array_equal(out_arr, np.flipud(arr)) @@ -156,7 +156,7 @@ def test_closest_canonical(): img = Nifti1Image(arr, np.diag([-1, 1, 1, 1])) img.header.set_dim_info(0, 1, 2) xyz_img = as_closest_canonical(img) - assert not img is xyz_img + assert img is not xyz_img assert img.header.get_dim_info() == xyz_img.header.get_dim_info() out_arr = xyz_img.get_fdata() assert_array_equal(out_arr, np.flipud(arr)) @@ -181,7 +181,7 @@ def test_closest_canonical(): img.header.set_dim_info(0, 1, 2) xyz_img = as_closest_canonical(img) - assert not img is xyz_img + assert img is not xyz_img # Check both the original and new objects assert img.header.get_dim_info() == (0, 1, 2) assert xyz_img.header.get_dim_info() == (0, 2, 1) diff --git a/nibabel/tests/test_image_api.py b/nibabel/tests/test_image_api.py index 738a3f1969..f5aeb53822 100644 --- a/nibabel/tests/test_image_api.py +++ b/nibabel/tests/test_image_api.py @@ -113,11 +113,9 @@ def validate_header(self, imaker, params): def validate_header_deprecated(self, imaker, params): # Check deprecated header API img = imaker() - with clear_and_catch_warnings() as w: - warnings.simplefilter('always', DeprecationWarning) + with pytest.deprecated_call(): hdr = img.get_header() - assert len(w) == 1 - assert hdr is img.header + assert hdr is img.header def validate_filenames(self, imaker, params): # Validate the filename, file_map interface @@ -171,7 +169,7 @@ def validate_no_slicing(self, imaker, params): def validate_get_data_deprecated(self, imaker, params): # Check deprecated header API img = imaker() - with assert_warns(DeprecationWarning): + with pytest.deprecated_call(): data = img.get_data() assert_array_equal(np.asanyarray(img.dataobj), data) @@ -395,10 +393,8 @@ def _check_array_caching(self, imaker, meth_name, caching): def validate_data_deprecated(self, imaker, params): # Check _data property still exists, but raises warning img = imaker() - with warnings.catch_warnings(record=True) as warns: - warnings.simplefilter("always") + with pytest.deprecated_call(): assert_data_similar(img._data, params) - assert warns.pop(0).category == DeprecationWarning # Check setting _data raises error fake_data = np.zeros(img.shape).astype(img.get_data_dtype()) with pytest.raises(AttributeError): @@ -502,10 +498,8 @@ def validate_affine(self, imaker, params): def validate_affine_deprecated(self, imaker, params): # Check deprecated affine API img = imaker() - with clear_and_catch_warnings() as w: - warnings.simplefilter('always', DeprecationWarning) + with pytest.deprecated_call(): assert_almost_equal(img.get_affine(), params['affine'], 6) - assert len(w) == 1 assert img.get_affine().dtype == np.float64 aff = img.get_affine() aff[0, 0] = 1.5 diff --git a/nibabel/tests/test_image_load_save.py b/nibabel/tests/test_image_load_save.py index 8dd64f8185..25c5b3e1de 100644 --- a/nibabel/tests/test_image_load_save.py +++ b/nibabel/tests/test_image_load_save.py @@ -274,7 +274,7 @@ def test_analyze_detection(): def wat(hdr): return nils.which_analyze_type(hdr.binaryblock) n1_hdr = Nifti1Header(b'\0' * 348, check=False) - assert wat(n1_hdr) == None + assert wat(n1_hdr) is None n1_hdr['sizeof_hdr'] = 540 assert wat(n1_hdr) == 'nifti2' assert wat(n1_hdr.as_byteswapped()) == 'nifti2' @@ -292,7 +292,7 @@ def wat(hdr): assert wat(n1_hdr) == 'analyze' n1_hdr['sizeof_hdr'] = 0 n1_hdr['magic'] = b'' - assert wat(n1_hdr) == None + assert wat(n1_hdr) is None n1_hdr['magic'] = 'n+1' assert wat(n1_hdr) == 'nifti1' n1_hdr['magic'] = 'ni1' diff --git a/nibabel/tests/test_nifti1.py b/nibabel/tests/test_nifti1.py index ef663f6e7b..d5dff4a4e4 100644 --- a/nibabel/tests/test_nifti1.py +++ b/nibabel/tests/test_nifti1.py @@ -1133,8 +1133,8 @@ def test_ext_eq(): assert ext == ext assert not ext != ext ext2 = Nifti1Extension('comment', '124') - assert not ext == ext2 assert ext != ext2 + assert not ext == ext2 def test_extension_codes(): @@ -1255,8 +1255,8 @@ def test_nifti_dicom_extension(): 'NiPy'.encode('utf-8')) dcmext = Nifti1DicomExtension(2, dcmbytes_explicit) assert dcmext.__class__ == Nifti1DicomExtension - assert dcmext._guess_implicit_VR() == False - assert dcmext._is_little_endian == True + assert dcmext._guess_implicit_VR() is False + assert dcmext._is_little_endian is True assert dcmext.get_code() == 2 assert dcmext.get_content().PatientID == 'NiPy' assert len(dcmext.get_content().values()) == 1 @@ -1267,7 +1267,7 @@ def test_nifti_dicom_extension(): dcmbytes_implicit = struct.pack('') # Big Endian Nifti1Header dcmext = Nifti1DicomExtension(2, dcmbytes_explicit_be, parent_hdr=hdr_be) assert dcmext.__class__ == Nifti1DicomExtension - assert dcmext._guess_implicit_VR() == False + assert dcmext._guess_implicit_VR() is False assert dcmext.get_code() == 2 assert dcmext.get_content().PatientID == 'NiPy' assert dcmext.get_content()[0x10, 0x20].value == 'NiPy' diff --git a/nibabel/tests/test_openers.py b/nibabel/tests/test_openers.py index eac73dd92b..d9d728046e 100644 --- a/nibabel/tests/test_openers.py +++ b/nibabel/tests/test_openers.py @@ -197,7 +197,7 @@ def file_opener(fileish, mode): assert os.path.exists('test.foo') # Check this doesn't add anything to parent - assert not '.foo' in Opener.compress_ext_map + assert '.foo' not in Opener.compress_ext_map def test_file_like_wrapper(): @@ -215,7 +215,7 @@ def test_file_like_wrapper(): fobj.close() assert fobj.closed # Added the fileobj name - assert fobj.name == None + assert fobj.name is None def test_compressionlevel(): diff --git a/nibabel/tests/test_optpkg.py b/nibabel/tests/test_optpkg.py index a6b9571530..1e652a51c5 100644 --- a/nibabel/tests/test_optpkg.py +++ b/nibabel/tests/test_optpkg.py @@ -7,8 +7,7 @@ import builtins from distutils.version import LooseVersion -# TODO: remove (have to be coordinated with optpkg) -from nose import SkipTest +from unittest import SkipTest import pytest from nibabel.optpkg import optional_package @@ -19,7 +18,7 @@ def assert_good(pkg_name, min_version=None): pkg, have_pkg, setup = optional_package(pkg_name, min_version=min_version) assert have_pkg assert sys.modules[pkg_name] == pkg - assert setup() == None + assert setup() is None def assert_bad(pkg_name, min_version=None): @@ -28,7 +27,6 @@ def assert_bad(pkg_name, min_version=None): assert isinstance(pkg, TripWire) with pytest.raises(TripWireError): getattr(pkg, 'a_method') - # TODO: remove with pytest.raises(SkipTest): setup() @@ -56,7 +54,7 @@ def raise_Exception(*args, **kwargs): def test_versions(): fake_name = '_a_fake_package' fake_pkg = types.ModuleType(fake_name) - assert not 'fake_pkg' in sys.modules + assert 'fake_pkg' not in sys.modules # Not inserted yet assert_bad(fake_name) try: diff --git a/nibabel/tests/test_orientations.py b/nibabel/tests/test_orientations.py index 5013828757..226feee526 100644 --- a/nibabel/tests/test_orientations.py +++ b/nibabel/tests/test_orientations.py @@ -380,9 +380,6 @@ def test_inv_ornt_aff(): def test_orientation_affine_deprecation(): aff1 = inv_ornt_aff([[0, 1], [1, -1], [2, 1]], (3, 4, 5)) - with warnings.catch_warnings(record=True) as warns: - warnings.simplefilter('always') + with pytest.deprecated_call(): aff2 = orientation_affine([[0, 1], [1, -1], [2, 1]], (3, 4, 5)) - assert len(warns) == 1 - assert warns[0].category == DeprecationWarning assert_array_equal(aff1, aff2) diff --git a/nibabel/tests/test_parrec.py b/nibabel/tests/test_parrec.py index bb0888b0e7..fe607c1982 100644 --- a/nibabel/tests/test_parrec.py +++ b/nibabel/tests/test_parrec.py @@ -182,7 +182,7 @@ def test_header(): si = np.array( [np.unique(x) for x in hdr.get_data_scaling()]).ravel() assert_almost_equal(si, (1.2903541326522827, 0.0), 5) - assert hdr.get_q_vectors() == None + assert hdr.get_q_vectors() is None assert hdr.get_bvals_bvecs() == (None, None) @@ -263,10 +263,8 @@ def test_affine_regression(): def test_get_voxel_size_deprecated(): hdr = PARRECHeader(HDR_INFO, HDR_DEFS) - with clear_and_catch_warnings(modules=[parrec], record=True) as wlist: - simplefilter('always') + with pytest.deprecated_call(): hdr.get_voxel_size() - assert wlist[0].category == DeprecationWarning def test_get_sorted_slice_indices(): @@ -304,9 +302,9 @@ def test_sorting_dual_echo_T1(): sorted_echos = t1_hdr.image_defs['echo number'][sorted_indices] n_half = len(t1_hdr.image_defs) // 2 # first half (volume 1) should all correspond to echo 1 - assert np.all(sorted_echos[:n_half] == 1) == True + assert np.all(sorted_echos[:n_half] == 1) # second half (volume 2) should all correspond to echo 2 - assert np.all(sorted_echos[n_half:] == 2) == True + assert np.all(sorted_echos[n_half:] == 2) # check volume labels vol_labels = t1_hdr.get_volume_labels() @@ -350,10 +348,10 @@ def test_sorting_multiple_echos_and_contrasts(): assert (np.all(sorted_echos[istart:iend] == current_echo) == True) # outermost sort index is image_type_mr - assert np.all(sorted_types[:ntotal//4] == 0) == True - assert np.all(sorted_types[ntotal//4:ntotal//2] == 1) == True - assert np.all(sorted_types[ntotal//2:3*ntotal//4] == 2) == True - assert np.all(sorted_types[3*ntotal//4:ntotal] == 3) == True + assert np.all(sorted_types[:ntotal//4] == 0) + assert np.all(sorted_types[ntotal//4:ntotal//2] == 1) + assert np.all(sorted_types[ntotal//2:3*ntotal//4] == 2) + assert np.all(sorted_types[3*ntotal//4:ntotal] == 3) # check volume labels vol_labels = t1_hdr.get_volume_labels() @@ -527,8 +525,8 @@ def test_diffusion_parameters_v4(): bvals, bvecs = dti_v4_hdr.get_bvals_bvecs() assert_almost_equal(bvals, DTI_PAR_BVALS) # no b-vector info in V4 .PAR files - assert bvecs == None - assert dti_v4_hdr.get_q_vectors() == None + assert bvecs is None + assert dti_v4_hdr.get_q_vectors() is None def test_null_diffusion_params(): @@ -540,7 +538,7 @@ def test_null_diffusion_params(): with suppress_warnings(): hdr = PARRECHeader(gen_info, slice_info, True) assert hdr.get_bvals_bvecs() == (None, None) - assert hdr.get_q_vectors() == None + assert hdr.get_q_vectors() is None def test_epi_params(): @@ -625,11 +623,11 @@ def test__get_uniqe_image_defs(): def test_copy_on_init(): # Test that input dict / array gets copied when making header hdr = PARRECHeader(HDR_INFO, HDR_DEFS) - assert not hdr.general_info is HDR_INFO + assert hdr.general_info is not HDR_INFO hdr.general_info['max_slices'] = 10 assert hdr.general_info['max_slices'] == 10 assert HDR_INFO['max_slices'] == 9 - assert not hdr.image_defs is HDR_DEFS + assert hdr.image_defs is not HDR_DEFS hdr.image_defs['image pixel size'] = 8 assert_array_equal(hdr.image_defs['image pixel size'], 8) assert_array_equal(HDR_DEFS['image pixel size'], 16) @@ -648,11 +646,11 @@ def test_header_copy(): hdr2 = hdr.copy() def assert_copy_ok(hdr1, hdr2): - assert not hdr1 is hdr2 + assert hdr1 is not hdr2 assert hdr1.permit_truncated == hdr2.permit_truncated - assert not hdr1.general_info is hdr2.general_info + assert hdr1.general_info is not hdr2.general_info assert_arr_dict_equal(hdr1.general_info, hdr2.general_info) - assert not hdr1.image_defs is hdr2.image_defs + assert hdr1.image_defs is not hdr2.image_defs assert_structarr_equal(hdr1.image_defs, hdr2.image_defs) assert_copy_ok(hdr, hdr2) @@ -868,8 +866,8 @@ def test_ADC_map(): # general_info indicates it is a diffusion scan, but because it is # a post-processed image, the bvals and bvecs aren't available bvals, bvecs = adc_hdr.get_bvals_bvecs() - assert bvals == None - assert bvecs == None + assert bvals is None + assert bvecs is None def test_alternative_header_field_names(): diff --git a/nibabel/tests/test_parrec_data.py b/nibabel/tests/test_parrec_data.py index 0cd92bd13f..30295a269a 100644 --- a/nibabel/tests/test_parrec_data.py +++ b/nibabel/tests/test_parrec_data.py @@ -60,8 +60,7 @@ def test_fieldmap(): fieldmap_nii = pjoin(BALLS, 'NIFTI', 'fieldmap.nii.gz') load(fieldmap_par) top_load(fieldmap_nii) - # TODO dj: i believe this shouldn't be here - #raise pytest.skip('Fieldmap remains puzzling') + raise pytest.skip('Fieldmap remains puzzling') @needs_nibabel_data('parrec_oblique') diff --git a/nibabel/tests/test_recoder.py b/nibabel/tests/test_recoder.py index 28eba8860b..8e4edd1b87 100644 --- a/nibabel/tests/test_recoder.py +++ b/nibabel/tests/test_recoder.py @@ -22,14 +22,14 @@ def test_recoder_1(): assert rc.code[1] == 1 assert rc.code[2] == 2 with pytest.raises(KeyError): - rc.code.__getitem__(3) + rc.code[3] def test_recoder_2(): # with explicit name for code codes = ((1,), (2,)) rc = Recoder(codes, ['code1']) with pytest.raises(AttributeError): - rc.__getattribute__('code') + rc.code assert rc.code1[1] == 1 assert rc.code1[2] == 2 @@ -41,20 +41,20 @@ def test_recoder_3(): assert rc.code[1] == 1 assert rc.code[2] == 2 with pytest.raises(KeyError): - rc.code.__getitem__(3) + rc.code[3] assert rc.code['one'] == 1 assert rc.code['two'] == 2 with pytest.raises(KeyError): - rc.code.__getitem__('three') + rc.code['three'] with pytest.raises(AttributeError): - rc.__getattribute__('label') + rc.label def test_recoder_3(): # with explicit column names codes = ((1, 'one'), (2, 'two')) rc = Recoder(codes, ['code1', 'label']) with pytest.raises(AttributeError): - rc.__getattribute__('code') + rc.code assert rc.code1[1] == 1 assert rc.code1['one'] == 1 assert rc.label[1] == 'one' @@ -119,7 +119,7 @@ def test_add_codes(): rc = Recoder(codes) assert rc.code['two'] == 2 with pytest.raises(KeyError): - rc.code.__getitem__('three') + rc.code['three'] rc.add_codes(((3, 'three'), (1, 'number 1'))) assert rc.code['three'] == 3 assert rc.code['number 1'] == 1 @@ -151,7 +151,7 @@ def test_dtmapper(): # dict-like that will lookup on dtypes, even if they don't hash properly d = DtypeMapper() with pytest.raises(KeyError): - d.__getitem__(1) + d[1] d[1] = 'something' assert d[1] == 'something' assert list(d.keys()) == [1] @@ -182,7 +182,7 @@ def test_dtmapper(): sw_dt = canonical_dt.newbyteorder(swapped_code) d[sw_dt] = 'spam' with pytest.raises(KeyError): - d.__getitem__(canonical_dt) + d[canonical_dt] assert d[sw_dt] == 'spam' sw_intp_dt = intp_dt.newbyteorder(swapped_code) assert d[sw_intp_dt] == 'spam' diff --git a/nibabel/tests/test_scaling.py b/nibabel/tests/test_scaling.py index ec335e5c24..db901adb61 100644 --- a/nibabel/tests/test_scaling.py +++ b/nibabel/tests/test_scaling.py @@ -159,35 +159,33 @@ def test_array_file_scales(in_type, out_type, err): # Max rounding error for integer type max_miss = slope / 2. assert np.all(np.abs(arr - arr3) <= max_miss) - bio.truncate(0) - bio.seek(0) -@pytest.mark.parametrize("category0, category1",[ +@pytest.mark.parametrize("in_type, out_type",[ ('int', 'int'), ('uint', 'int'), ]) -def test_scaling_in_abstract(category0, category1): +def test_scaling_in_abstract(in_type, out_type): # Confirm that, for all ints and uints as input, and all possible outputs, # for any simple way of doing the calculation, the result is near enough - for in_type in np.sctypes[category0]: - for out_type in np.sctypes[category1]: - check_int_a2f(in_type, out_type) + for in_tp in np.sctypes[in_type]: + for out_tp in np.sctypes[out_type]: + check_int_a2f(in_tp, out_tp) -@pytest.mark.parametrize("category0, category1", [ +@pytest.mark.parametrize("in_type, out_type", [ ('float', 'int'), ('float', 'uint'), ('complex', 'int'), ('complex', 'uint'), ]) -def test_scaling_in_abstract_warn(category0, category1): +def test_scaling_in_abstract_warn(in_type, out_type): # Converting floats to integer - for in_type in np.sctypes[category0]: - for out_type in np.sctypes[category1]: + for in_tp in np.sctypes[in_type]: + for out_tp in np.sctypes[out_type]: with suppress_warnings(): # overflow - check_int_a2f(in_type, out_type) + check_int_a2f(in_tp, out_tp) def check_int_a2f(in_type, out_type): diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 5e7defdaa5..19dd5f6fd0 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -20,10 +20,8 @@ from ..loadsave import load from ..orientations import flip_axis, aff2axcodes, inv_ornt_aff -from nose.tools import assert_true, assert_false, assert_equal -from nose import SkipTest - -from numpy.testing import assert_almost_equal, assert_array_equal +import pytest +from numpy.testing import assert_almost_equal from .scriptrunner import ScriptRunner from .nibabel_data import needs_nibabel_data @@ -33,7 +31,6 @@ from .test_parrec_data import BALLS, AFF_OFF from ..testing_pytest import assert_data_similar -import pytest; pytestmark = pytest.mark.skip() def _proc_stdout(stdout): stdout_str = stdout.decode('latin1').strip() @@ -56,6 +53,14 @@ def script_test(func): DATA_PATH = abspath(pjoin(dirname(__file__), 'data')) +def load_small_file(): + try: + load(pjoin(DATA_PATH, 'small.mnc')) + return True + except: + return False + + def check_nib_ls_example4d(opts=[], hdrs_str="", other_str=""): # test nib-ls script fname = pjoin(DATA_PATH, 'example4d.nii.gz') @@ -64,7 +69,7 @@ def check_nib_ls_example4d(opts=[], hdrs_str="", other_str=""): % (hdrs_str, other_str)) cmd = ['nib-ls'] + opts + [fname] code, stdout, stderr = run_command(cmd) - assert_equal(fname, stdout[:len(fname)]) + assert fname == stdout[:len(fname)] assert_re_in(expected_re, stdout[len(fname):]) @@ -77,45 +82,45 @@ def check_nib_diff_examples(): "quatern_c", "quatern_d", "qoffset_x", "qoffset_y", "qoffset_z", "srow_x", "srow_y", "srow_z", "DATA(md5)", "DATA(diff 1:)"] for item in checked_fields: - assert_true(item in stdout) + assert item in stdout fnames2 = [pjoin(DATA_PATH, f) for f in ('example4d.nii.gz', 'example4d.nii.gz')] code, stdout, stderr = run_command(['nib-diff'] + fnames2, check_code=False) - assert_equal(stdout, "These files are identical.") + assert stdout == "These files are identical." fnames3 = [pjoin(DATA_PATH, f) for f in ('standard.nii.gz', 'example4d.nii.gz', 'example_nifti2.nii.gz')] code, stdout, stderr = run_command(['nib-diff'] + fnames3, check_code=False) for item in checked_fields: - assert_true(item in stdout) + assert item in stdout fnames4 = [pjoin(DATA_PATH, f) for f in ('standard.nii.gz', 'standard.nii.gz', 'standard.nii.gz')] code, stdout, stderr = run_command(['nib-diff'] + fnames4, check_code=False) - assert_equal(stdout, "These files are identical.") + assert stdout == "These files are identical." code, stdout, stderr = run_command(['nib-diff', '--dt', 'float64'] + fnames, check_code=False) for item in checked_fields: - assert_true(item in stdout) + assert item in stdout - -@script_test -def test_nib_ls(): - yield check_nib_ls_example4d - yield check_nib_ls_example4d, \ - ['-H', 'dim,bitpix'], " \[ 4 128 96 24 2 1 1 1\] 16" - yield check_nib_ls_example4d, ['-c'], "", " !1030 uniques. Use --all-counts" - yield check_nib_ls_example4d, ['-c', '--all-counts'], "", " 2:3 3:2 4:1 5:1.*" +@pytest.mark.parametrize("args", [ + [], + [['-H', 'dim,bitpix'], " \[ 4 128 96 24 2 1 1 1\] 16"], + [['-c'], "", " !1030 uniques. Use --all-counts"], + [['-c', '--all-counts'], "", " 2:3 3:2 4:1 5:1.*"], # both stats and counts - yield check_nib_ls_example4d, \ - ['-c', '-s', '--all-counts'], "", " \[229725\] \[2, 1.2e\+03\] 2:3 3:2 4:1 5:1.*" + [['-c', '-s', '--all-counts'], "", " \[229725\] \[2, 1.2e\+03\] 2:3 3:2 4:1 5:1.*"], # and must not error out if we allow for zeros - yield check_nib_ls_example4d, \ - ['-c', '-s', '-z', '--all-counts'], "", " \[589824\] \[0, 1.2e\+03\] 0:360099 2:3 3:2 4:1 5:1.*" + [['-c', '-s', '-z', '--all-counts'], "", " \[589824\] \[0, 1.2e\+03\] 0:360099 2:3 3:2 4:1 5:1.*"], +]) +@script_test +def test_nib_ls(args): + check_nib_ls_example4d(*args) +@pytest.mark.skipif(not load_small_file(), reason="can't load the small.mnc file") @script_test def test_nib_ls_multiple(): # verify that correctly lists/formats for multiple files @@ -126,42 +131,35 @@ def test_nib_ls_multiple(): ] code, stdout, stderr = run_command(['nib-ls'] + fnames) stdout_lines = stdout.split('\n') - assert_equal(len(stdout_lines), 4) - try: - load(pjoin(DATA_PATH, 'small.mnc')) - except: - raise SkipTest("For the other tests should be able to load MINC files") + assert len(stdout_lines) == 4 # they should be indented correctly. Since all files are int type - ln = max(len(f) for f in fnames) i_str = ' i' if sys.byteorder == 'little' else ' -TINY)) - assert_true(np.all(out_grid < np.array(out_shape) + TINY)) + assert np.all(out_grid > -TINY) + assert np.all(out_grid < np.array(out_shape) + TINY) def get_outspace_params(): @@ -84,23 +80,27 @@ def test_vox2out_vox(): # Test world space bounding box # Test basic case, identity, no voxel sizes passed shape, aff = vox2out_vox(((2, 3, 4), np.eye(4))) - assert_array_equal(shape, (2, 3, 4)) - assert_array_equal(aff, np.eye(4)) + assert shape == (2, 3, 4) + assert (aff == np.eye(4)).all() for in_shape, in_aff, vox, out_shape, out_aff in get_outspace_params(): img = Nifti1Image(np.ones(in_shape), in_aff) for input in ((in_shape, in_aff), img): shape, aff = vox2out_vox(input, vox) assert_all_in(in_shape, in_aff, shape, aff) - assert_equal(shape, out_shape) + assert shape == out_shape assert_almost_equal(aff, out_aff) - assert_true(isinstance(shape, tuple)) - assert_true(isinstance(shape[0], int)) + assert isinstance(shape, tuple) + assert isinstance(shape[0], int) # Enforce number of axes - assert_raises(ValueError, vox2out_vox, ((2, 3, 4, 5), np.eye(4))) - assert_raises(ValueError, vox2out_vox, ((2, 3, 4, 5, 6), np.eye(4))) + with pytest.raises(ValueError): + vox2out_vox(((2, 3, 4, 5), np.eye(4))) + with pytest.raises(ValueError): + vox2out_vox(((2, 3, 4, 5, 6), np.eye(4))) # Voxel sizes must be positive - assert_raises(ValueError, vox2out_vox, ((2, 3, 4), np.eye(4), [-1, 1, 1])) - assert_raises(ValueError, vox2out_vox, ((2, 3, 4), np.eye(4), [1, 0, 1])) + with pytest.raises(ValueError): + vox2out_vox(((2, 3, 4), np.eye(4), [-1, 1, 1])) + with pytest.raises(ValueError): + vox2out_vox(((2, 3, 4), np.eye(4), [1, 0, 1])) def test_slice2volume(): @@ -112,7 +112,14 @@ def test_slice2volume(): for val in (0, 5, 10): exp_aff = np.array(def_aff) exp_aff[axis, -1] = val - assert_array_equal(slice2volume(val, axis), exp_aff) - assert_raises(ValueError, slice2volume, -1, 0) - assert_raises(ValueError, slice2volume, 0, -1) - assert_raises(ValueError, slice2volume, 0, 3) + assert (slice2volume(val, axis) == exp_aff).all() + + +@pytest.mark.parametrize("index, axis", [ + [-1, 0], + [0, -1], + [0, 3] +]) +def test_slice2volume_exception(index, axis): + with pytest.raises(ValueError): + slice2volume(index, axis) \ No newline at end of file diff --git a/nibabel/tests/test_spatialimages.py b/nibabel/tests/test_spatialimages.py index 5b4706bea1..82da89b3d7 100644 --- a/nibabel/tests/test_spatialimages.py +++ b/nibabel/tests/test_spatialimages.py @@ -15,58 +15,59 @@ import numpy as np from io import BytesIO -from ..spatialimages import (SpatialHeader, SpatialImage, HeaderDataError, - Header, ImageDataError) +from ..spatialimages import SpatialHeader, SpatialImage, HeaderDataError, Header from ..imageclasses import spatial_axes_first +import pytest from unittest import TestCase -from nose.tools import (assert_true, assert_false, assert_equal, - assert_not_equal, assert_raises) -from numpy.testing import assert_array_equal, assert_array_almost_equal, assert_warns +from numpy.testing import assert_array_almost_equal + +from ..testing_pytest import ( + bytesio_round_trip, + clear_and_catch_warnings, + suppress_warnings, + memmap_after_ufunc +) -from ..testing import (clear_and_catch_warnings, suppress_warnings, - memmap_after_ufunc) -from ..testing_pytest import bytesio_round_trip from ..tmpdirs import InTemporaryDirectory from ..deprecator import ExpiredDeprecationError from .. import load as top_load -import pytest; pytestmark = pytest.mark.skip() def test_header_init(): # test the basic header hdr = Header() - assert_equal(hdr.get_data_dtype(), np.dtype(np.float32)) - assert_equal(hdr.get_data_shape(), (0,)) - assert_equal(hdr.get_zooms(), (1.0,)) + assert hdr.get_data_dtype() == np.dtype(np.float32) + assert hdr.get_data_shape() == (0,) + assert hdr.get_zooms() == (1.0,) hdr = Header(np.float64) - assert_equal(hdr.get_data_dtype(), np.dtype(np.float64)) - assert_equal(hdr.get_data_shape(), (0,)) - assert_equal(hdr.get_zooms(), (1.0,)) + assert hdr.get_data_dtype() == np.dtype(np.float64) + assert hdr.get_data_shape() == (0,) + assert hdr.get_zooms() == (1.0,) hdr = Header(np.float64, shape=(1, 2, 3)) - assert_equal(hdr.get_data_dtype(), np.dtype(np.float64)) - assert_equal(hdr.get_data_shape(), (1, 2, 3)) - assert_equal(hdr.get_zooms(), (1.0, 1.0, 1.0)) + assert hdr.get_data_dtype() == np.dtype(np.float64) + assert hdr.get_data_shape() == (1, 2, 3) + assert hdr.get_zooms() == (1.0, 1.0, 1.0) hdr = Header(np.float64, shape=(1, 2, 3), zooms=None) - assert_equal(hdr.get_data_dtype(), np.dtype(np.float64)) - assert_equal(hdr.get_data_shape(), (1, 2, 3)) - assert_equal(hdr.get_zooms(), (1.0, 1.0, 1.0)) + assert hdr.get_data_dtype() == np.dtype(np.float64) + assert hdr.get_data_shape() == (1, 2, 3) + assert hdr.get_zooms() == (1.0, 1.0, 1.0) hdr = Header(np.float64, shape=(1, 2, 3), zooms=(3.0, 2.0, 1.0)) - assert_equal(hdr.get_data_dtype(), np.dtype(np.float64)) - assert_equal(hdr.get_data_shape(), (1, 2, 3)) - assert_equal(hdr.get_zooms(), (3.0, 2.0, 1.0)) + assert hdr.get_data_dtype() == np.dtype(np.float64) + assert hdr.get_data_shape() == (1, 2, 3) + assert hdr.get_zooms() == (3.0, 2.0, 1.0) def test_from_header(): # check from header class method. Note equality checks below, # equality methods used here too. empty = Header.from_header() - assert_equal(Header(), empty) + assert Header() == empty empty = Header.from_header(None) - assert_equal(Header(), empty) + assert Header() == empty hdr = Header(np.float64, shape=(1, 2, 3), zooms=(3.0, 2.0, 1.0)) copy = Header.from_header(hdr) - assert_equal(hdr, copy) - assert_false(hdr is copy) + assert hdr == copy + assert hdr is not copy class C(object): @@ -76,25 +77,25 @@ def get_data_shape(self): return (5, 4, 3) def get_zooms(self): return (10.0, 9.0, 8.0) converted = Header.from_header(C()) - assert_true(isinstance(converted, Header)) - assert_equal(converted.get_data_dtype(), np.dtype('u2')) - assert_equal(converted.get_data_shape(), (5, 4, 3)) - assert_equal(converted.get_zooms(), (10.0, 9.0, 8.0)) + assert isinstance(converted, Header) + assert converted.get_data_dtype() == np.dtype('u2') + assert converted.get_data_shape() == (5, 4, 3) + assert converted.get_zooms() == (10.0, 9.0, 8.0) def test_eq(): hdr = Header() other = Header() - assert_equal(hdr, other) + assert hdr == other other = Header('u2') - assert_not_equal(hdr, other) + assert hdr != other other = Header(shape=(1, 2, 3)) - assert_not_equal(hdr, other) + assert hdr != other hdr = Header(shape=(1, 2)) other = Header(shape=(1, 2)) - assert_equal(hdr, other) + assert hdr == other other = Header(shape=(1, 2), zooms=(2.0, 3.0)) - assert_not_equal(hdr, other) + assert hdr != other def test_copy(): @@ -102,51 +103,50 @@ def test_copy(): hdr = Header(np.float64, shape=(1, 2, 3), zooms=(3.0, 2.0, 1.0)) hdr_copy = hdr.copy() hdr.set_data_shape((4, 5, 6)) - assert_equal(hdr.get_data_shape(), (4, 5, 6)) - assert_equal(hdr_copy.get_data_shape(), (1, 2, 3)) + assert hdr.get_data_shape() == (4, 5, 6) + assert hdr_copy.get_data_shape() == (1, 2, 3) hdr.set_zooms((4, 5, 6)) - assert_equal(hdr.get_zooms(), (4, 5, 6)) - assert_equal(hdr_copy.get_zooms(), (3, 2, 1)) + assert hdr.get_zooms() == (4, 5, 6) + assert hdr_copy.get_zooms() == (3, 2, 1) hdr.set_data_dtype(np.uint8) - assert_equal(hdr.get_data_dtype(), np.dtype(np.uint8)) - assert_equal(hdr_copy.get_data_dtype(), np.dtype(np.float64)) + assert hdr.get_data_dtype() == np.dtype(np.uint8) + assert hdr_copy.get_data_dtype() == np.dtype(np.float64) def test_shape_zooms(): hdr = Header() hdr.set_data_shape((1, 2, 3)) - assert_equal(hdr.get_data_shape(), (1, 2, 3)) - assert_equal(hdr.get_zooms(), (1.0, 1.0, 1.0)) + assert hdr.get_data_shape() == (1, 2, 3) + assert hdr.get_zooms() == (1.0, 1.0, 1.0) hdr.set_zooms((4, 3, 2)) - assert_equal(hdr.get_zooms(), (4.0, 3.0, 2.0)) + assert hdr.get_zooms() == (4.0, 3.0, 2.0) hdr.set_data_shape((1, 2)) - assert_equal(hdr.get_data_shape(), (1, 2)) - assert_equal(hdr.get_zooms(), (4.0, 3.0)) + assert hdr.get_data_shape() == (1, 2) + assert hdr.get_zooms() == (4.0, 3.0) hdr.set_data_shape((1, 2, 3)) - assert_equal(hdr.get_data_shape(), (1, 2, 3)) - assert_equal(hdr.get_zooms(), (4.0, 3.0, 1.0)) + assert hdr.get_data_shape() == (1, 2, 3) + assert hdr.get_zooms() == (4.0, 3.0, 1.0) # null shape is (0,) hdr.set_data_shape(()) - assert_equal(hdr.get_data_shape(), (0,)) - assert_equal(hdr.get_zooms(), (1.0,)) + assert hdr.get_data_shape() == (0,) + assert hdr.get_zooms() == (1.0,) # zooms of wrong lengths raise error - assert_raises(HeaderDataError, hdr.set_zooms, (4.0, 3.0)) - assert_raises(HeaderDataError, - hdr.set_zooms, - (4.0, 3.0, 2.0, 1.0)) + with pytest.raises(HeaderDataError): + hdr.set_zooms((4.0, 3.0)) + with pytest.raises(HeaderDataError): + hdr.set_zooms((4.0, 3.0, 2.0, 1.0)) # as do negative zooms - assert_raises(HeaderDataError, - hdr.set_zooms, - (4.0, 3.0, -2.0)) + with pytest.raises(HeaderDataError): + hdr.set_zooms((4.0, 3.0, -2.0)) def test_data_dtype(): hdr = Header() - assert_equal(hdr.get_data_dtype(), np.dtype(np.float32)) + assert hdr.get_data_dtype() == np.dtype(np.float32) hdr.set_data_dtype(np.float64) - assert_equal(hdr.get_data_dtype(), np.dtype(np.float64)) + assert hdr.get_data_dtype() == np.dtype(np.float64) hdr.set_data_dtype('u2') - assert_equal(hdr.get_data_dtype(), np.dtype(np.uint16)) + assert hdr.get_data_dtype() == np.dtype(np.uint16) def test_affine(): @@ -162,8 +162,7 @@ def test_affine(): [0, 2, 0, -1], [0, 0, 1, -1], [0, 0, 0, 1]]) - assert_array_equal(hdr.get_base_affine(), - hdr.get_best_affine()) + assert np.array_equal(hdr.get_base_affine(), hdr.get_best_affine()) def test_read_data(): @@ -174,22 +173,19 @@ class CHeader(SpatialHeader): fobj = BytesIO() data = np.arange(6).reshape((1, 2, 3)) hdr.data_to_fileobj(data, fobj) - assert_equal(fobj.getvalue(), - data.astype(np.int32).tostring(order=order)) + assert fobj.getvalue() == data.astype(np.int32).tostring(order=order) # data_to_fileobj accepts kwarg 'rescale', but no effect in this case fobj.seek(0) hdr.data_to_fileobj(data, fobj, rescale=True) - assert_equal(fobj.getvalue(), - data.astype(np.int32).tostring(order=order)) + assert fobj.getvalue() == data.astype(np.int32).tostring(order=order) # data_to_fileobj can be a list fobj.seek(0) hdr.data_to_fileobj(data.tolist(), fobj, rescale=True) - assert_equal(fobj.getvalue(), - data.astype(np.int32).tostring(order=order)) + assert fobj.getvalue() == data.astype(np.int32).tostring(order=order) # Read data back again fobj.seek(0) data2 = hdr.data_from_fileobj(fobj) - assert_array_equal(data, data2) + assert (data == data2).all() class DataLike(object): @@ -211,33 +207,33 @@ def test_isolation(self): arr = np.arange(24, dtype=np.int16).reshape((2, 3, 4)) aff = np.eye(4) img = img_klass(arr, aff) - assert_array_equal(img.affine, aff) + assert (img.affine == aff).all() aff[0, 0] = 99 - assert_false(np.all(img.affine == aff)) + assert not np.all(img.affine == aff) # header, created by image creation ihdr = img.header # Pass it back in img = img_klass(arr, aff, ihdr) # Check modifying header outside does not modify image ihdr.set_zooms((4, 5, 6)) - assert_not_equal(img.header, ihdr) + assert img.header != ihdr def test_float_affine(self): # Check affines get converted to float img_klass = self.image_class arr = np.arange(3, dtype=np.int16) img = img_klass(arr, np.eye(4, dtype=np.float32)) - assert_equal(img.affine.dtype, np.dtype(np.float64)) + assert img.affine.dtype == np.dtype(np.float64) img = img_klass(arr, np.eye(4, dtype=np.int16)) - assert_equal(img.affine.dtype, np.dtype(np.float64)) + assert img.affine.dtype == np.dtype(np.float64) def test_images(self): # Assumes all possible images support int16 # See https://github.com/nipy/nibabel/issues/58 arr = np.arange(24, dtype=np.int16).reshape((2, 3, 4)) img = self.image_class(arr, None) - assert_array_equal(img.get_fdata(), arr) - assert_equal(img.affine, None) + assert (img.get_fdata() == arr).all() + assert img.affine is None def test_default_header(self): # Check default header is as expected @@ -246,21 +242,21 @@ def test_default_header(self): hdr = self.image_class.header_class() hdr.set_data_shape(arr.shape) hdr.set_data_dtype(arr.dtype) - assert_equal(img.header, hdr) + assert img.header == hdr def test_data_api(self): # Test minimal api data object can initialize img = self.image_class(DataLike(), None) # Shape may be promoted to higher dimension, but may not reorder or # change size - assert_array_equal(img.get_fdata().flatten(), np.arange(3)) - assert_equal(img.shape[:1], (3,)) - assert_equal(np.prod(img.shape), 3) + assert (img.get_fdata().flatten() == np.arange(3)).all() + assert img.shape[:1] == (3,) + assert np.prod(img.shape) == 3 def check_dtypes(self, expected, actual): # Some images will want dtypes to be equal including endianness, # others may only require the same type - assert_equal(expected, actual) + assert expected == actual def test_data_default(self): # check that the default dtype comes from the data if the header @@ -285,10 +281,10 @@ def test_data_shape(self): img = img_klass(arr, np.eye(4)) # Shape may be promoted to higher dimension, but may not reorder or # change size - assert_equal(img.shape[:1], (4,)) - assert_equal(np.prod(img.shape), 4) + assert img.shape[:1] == (4,) + assert np.prod(img.shape) == 4 img = img_klass(np.zeros((2, 3, 4), dtype=np.float32), np.eye(4)) - assert_equal(img.shape, (2, 3, 4)) + assert img.shape == (2, 3, 4) def test_str(self): # Check something comes back from string representation @@ -297,13 +293,13 @@ def test_str(self): # See https://github.com/nipy/nibabel/issues/58 arr = np.arange(5, dtype=np.int16) img = img_klass(arr, np.eye(4)) - assert_true(len(str(img)) > 0) + assert len(str(img)) > 0 # Shape may be promoted to higher dimension, but may not reorder or # change size - assert_equal(img.shape[:1], (5,)) - assert_equal(np.prod(img.shape), 5) + assert img.shape[:1] == (5,) + assert np.prod(img.shape) == 5 img = img_klass(np.zeros((2, 3, 4), dtype=np.int16), np.eye(4)) - assert_true(len(str(img)) > 0) + assert len(str(img)) > 0 def test_get_shape(self): # Check that get_shape raises an ExpiredDeprecationError @@ -311,7 +307,7 @@ def test_get_shape(self): # Assumes all possible images support int16 # See https://github.com/nipy/nibabel/issues/58 img = img_klass(np.arange(1, dtype=np.int16), np.eye(4)) - with assert_raises(ExpiredDeprecationError): + with pytest.raises(ExpiredDeprecationError): img.get_shape() def test_get_fdata(self): @@ -320,55 +316,57 @@ def test_get_fdata(self): in_data_template = np.arange(24, dtype=np.int16).reshape((2, 3, 4)) in_data = in_data_template.copy() img = img_klass(in_data, None) - assert_true(in_data is img.dataobj) + assert in_data is img.dataobj # The get_fdata method changes the array to floating point type - assert_equal(img.get_fdata(dtype='f4').dtype, np.dtype(np.float32)) + assert img.get_fdata(dtype='f4').dtype == np.dtype(np.float32) fdata_32 = img.get_fdata(dtype=np.float32) - assert_equal(fdata_32.dtype, np.dtype(np.float32)) + assert fdata_32.dtype == np.dtype(np.float32) # Caching is specific to data dtype. If we reload with default data # type, the cache gets reset fdata_32[:] = 99 # Cache has been modified, we pick up the modifications, but only for # the cached data type - assert_array_equal(img.get_fdata(dtype='f4'), 99) + assert (img.get_fdata(dtype='f4') == 99).all() fdata_64 = img.get_fdata() - assert_equal(fdata_64.dtype, np.dtype(np.float64)) - assert_array_equal(fdata_64, in_data) + assert fdata_64.dtype == np.dtype(np.float64) + assert (fdata_64 == in_data).all() fdata_64[:] = 101 - assert_array_equal(img.get_fdata(dtype='f8'), 101) - assert_array_equal(img.get_fdata(), 101) + assert (img.get_fdata(dtype='f8') == 101).all() + assert (img.get_fdata() == 101).all() # Reloading with new data type blew away the float32 cache - assert_array_equal(img.get_fdata(dtype='f4'), in_data) + assert (img.get_fdata(dtype='f4') == in_data).all() img.uncache() # Now recaching, is float64 out_data = img.get_fdata() - assert_equal(out_data.dtype, np.dtype(np.float64)) + assert out_data.dtype == np.dtype(np.float64) # Input dtype needs to be floating point - assert_raises(ValueError, img.get_fdata, dtype=np.int16) - assert_raises(ValueError, img.get_fdata, dtype=np.int32) + with pytest.raises(ValueError): + img.get_fdata(dtype=np.int16) + with pytest.raises(ValueError): + img.get_fdata(dtype=np.int32) # The cache is filled out_data[:] = 42 - assert_true(img.get_fdata() is out_data) + assert img.get_fdata() is out_data img.uncache() - assert_false(img.get_fdata() is out_data) + assert img.get_fdata() is not out_data # The 42 has gone now. - assert_array_equal(img.get_fdata(), in_data_template) + assert (img.get_fdata() == in_data_template).all() # If we can save, we can create a proxy image if not self.can_save: return rt_img = bytesio_round_trip(img) - assert_false(in_data is rt_img.dataobj) - assert_array_equal(rt_img.dataobj, in_data) + assert in_data is not rt_img.dataobj + assert (rt_img.dataobj == in_data).all() out_data = rt_img.get_fdata() - assert_array_equal(out_data, in_data) - assert_false(rt_img.dataobj is out_data) - assert_equal(out_data.dtype, np.dtype(np.float64)) + assert (out_data == in_data).all() + assert rt_img.dataobj is not out_data + assert out_data.dtype == np.dtype(np.float64) # cache - assert_true(rt_img.get_fdata() is out_data) + assert rt_img.get_fdata() is out_data out_data[:] = 42 rt_img.uncache() - assert_false(rt_img.get_fdata() is out_data) - assert_array_equal(rt_img.get_fdata(), in_data) + assert rt_img.get_fdata() is not out_data + assert (rt_img.get_fdata() == in_data).all() def test_get_data(self): # Test array image and proxy image interface @@ -377,41 +375,41 @@ def test_get_data(self): in_data = in_data_template.copy() img = img_klass(in_data, None) # Can't slice into the image object: - with assert_raises(TypeError) as exception_manager: + with pytest.raises(TypeError) as exception_manager: img[0, 0, 0] # Make sure the right message gets raised: - assert_equal(str(exception_manager.exception), - "Cannot slice image objects; consider using " - "`img.slicer[slice]` to generate a sliced image (see " - "documentation for caveats) or slicing image array data " - "with `img.dataobj[slice]` or `img.get_fdata()[slice]`") - assert_true(in_data is img.dataobj) - with assert_warns(DeprecationWarning): + assert (str(exception_manager.value) == + "Cannot slice image objects; consider using " + "`img.slicer[slice]` to generate a sliced image (see " + "documentation for caveats) or slicing image array data " + "with `img.dataobj[slice]` or `img.get_fdata()[slice]`") + assert in_data is img.dataobj + with pytest.deprecated_call(): out_data = img.get_data() - assert_true(in_data is out_data) + assert in_data is out_data # and that uncache has no effect img.uncache() - assert_true(in_data is out_data) - assert_array_equal(out_data, in_data_template) + assert in_data is out_data + assert (out_data == in_data_template).all() # If we can save, we can create a proxy image if not self.can_save: return rt_img = bytesio_round_trip(img) - assert_false(in_data is rt_img.dataobj) - assert_array_equal(rt_img.dataobj, in_data) - with assert_warns(DeprecationWarning): + assert in_data is not rt_img.dataobj + assert (rt_img.dataobj == in_data).all() + with pytest.deprecated_call(): out_data = rt_img.get_data() - assert_array_equal(out_data, in_data) - assert_false(rt_img.dataobj is out_data) + assert (out_data == in_data).all() + assert rt_img.dataobj is not out_data # cache - with assert_warns(DeprecationWarning): - assert_true(rt_img.get_data() is out_data) + with pytest.deprecated_call(): + assert rt_img.get_data() is out_data out_data[:] = 42 rt_img.uncache() - with assert_warns(DeprecationWarning): - assert_false(rt_img.get_data() is out_data) - with assert_warns(DeprecationWarning): - assert_array_equal(rt_img.get_data(), in_data) + with pytest.deprecated_call(): + assert rt_img.get_data() is not out_data + with pytest.deprecated_call(): + assert (rt_img.get_data() == in_data).all() def test_slicer(self): img_klass = self.image_class @@ -424,11 +422,11 @@ def test_slicer(self): img = img_klass(in_data, base_affine.copy()) if not spatial_axes_first(img): - with assert_raises(ValueError): + with pytest.raises(ValueError): img.slicer continue - assert_true(hasattr(img.slicer, '__getitem__')) + assert hasattr(img.slicer, '__getitem__') # Note spatial zooms are always first 3, even when spatial_zooms = img.header.get_zooms()[:3] @@ -437,50 +435,49 @@ def test_slicer(self): sliceobj = [slice(None, None, 2)] * 3 + \ [slice(None)] * (len(dshape) - 3) downsampled_img = img.slicer[tuple(sliceobj)] - assert_array_equal(downsampled_img.header.get_zooms()[:3], - np.array(spatial_zooms) * 2) + assert (downsampled_img.header.get_zooms()[:3] + == np.array(spatial_zooms) * 2).all() max4d = (hasattr(img.header, '_structarr') and 'dims' in img.header._structarr.dtype.fields and img.header._structarr['dims'].shape == (4,)) # Check newaxis and single-slice errors - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[None] - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[0] # Axes 1 and 2 are always spatial - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[:, None] - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[:, 0] - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[:, :, None] - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[:, :, 0] if len(img.shape) == 4: if max4d: - with assert_raises(ValueError): + with pytest.raises(ValueError): img.slicer[:, :, :, None] else: # Reorder non-spatial axes - assert_equal(img.slicer[:, :, :, None].shape, - img.shape[:3] + (1,) + img.shape[3:]) + assert (img.slicer[:, :, :, None].shape + == img.shape[:3] + (1,) + img.shape[3:]) # 4D to 3D using ellipsis or slices - assert_equal(img.slicer[..., 0].shape, img.shape[:-1]) - assert_equal(img.slicer[:, :, :, 0].shape, img.shape[:-1]) + assert img.slicer[..., 0].shape == img.shape[:-1] + assert img.slicer[:, :, :, 0].shape == img.shape[:-1] else: # 3D Analyze/NIfTI/MGH to 4D - assert_equal(img.slicer[:, :, :, None].shape, img.shape + (1,)) + assert img.slicer[:, :, :, None].shape == img.shape + (1,) if len(img.shape) == 3: # Slices exceed dimensions - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[:, :, :, :, None] elif max4d: - with assert_raises(ValueError): + with pytest.raises(ValueError): img.slicer[:, :, :, :, None] else: - assert_equal(img.slicer[:, :, :, :, None].shape, - img.shape + (1,)) + assert img.slicer[:, :, :, :, None].shape == img.shape + (1,) # Crop by one voxel in each dimension sliced_i = img.slicer[1:] @@ -489,35 +486,35 @@ def test_slicer(self): sliced_ijk = img.slicer[1:, 1:, 1:] # No scaling change - assert_array_equal(sliced_i.affine[:3, :3], img.affine[:3, :3]) - assert_array_equal(sliced_j.affine[:3, :3], img.affine[:3, :3]) - assert_array_equal(sliced_k.affine[:3, :3], img.affine[:3, :3]) - assert_array_equal(sliced_ijk.affine[:3, :3], img.affine[:3, :3]) + assert (sliced_i.affine[:3, :3] == img.affine[:3, :3]).all() + assert (sliced_j.affine[:3, :3] == img.affine[:3, :3]).all() + assert (sliced_k.affine[:3, :3] == img.affine[:3, :3]).all() + assert (sliced_ijk.affine[:3, :3] == img.affine[:3, :3]).all() # Translation - assert_array_equal(sliced_i.affine[:, 3], [1, 0, 0, 1]) - assert_array_equal(sliced_j.affine[:, 3], [0, 1, 0, 1]) - assert_array_equal(sliced_k.affine[:, 3], [0, 0, 1, 1]) - assert_array_equal(sliced_ijk.affine[:, 3], [1, 1, 1, 1]) + assert (sliced_i.affine[:, 3] == [1, 0, 0, 1]).all() + assert (sliced_j.affine[:, 3] == [0, 1, 0, 1]).all() + assert (sliced_k.affine[:, 3] == [0, 0, 1, 1]).all() + assert (sliced_ijk.affine[:, 3] == [1, 1, 1, 1]).all() # No change to affines with upper-bound slices - assert_array_equal(img.slicer[:1, :1, :1].affine, img.affine) + assert (img.slicer[:1, :1, :1].affine == img.affine).all() # Yell about step = 0 - with assert_raises(ValueError): + with pytest.raises(ValueError): img.slicer[:, ::0] - with assert_raises(ValueError): + with pytest.raises(ValueError): img.slicer.slice_affine((slice(None), slice(None, None, 0))) # Don't permit zero-length slices - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[:0] # No fancy indexing - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[[0]] - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[[-1]] - with assert_raises(IndexError): + with pytest.raises(IndexError): img.slicer[[0], [-1]] # Check data is consistent with slicing numpy arrays @@ -534,14 +531,14 @@ def test_slicer(self): pass else: sliced_data = in_data[sliceobj] - with assert_warns(DeprecationWarning): - assert_array_equal(sliced_data, sliced_img.get_data()) - assert_array_equal(sliced_data, sliced_img.get_fdata()) - assert_array_equal(sliced_data, sliced_img.dataobj) - assert_array_equal(sliced_data, img.dataobj[sliceobj]) - with assert_warns(DeprecationWarning): - assert_array_equal(sliced_data, img.get_data()[sliceobj]) - assert_array_equal(sliced_data, img.get_fdata()[sliceobj]) + with pytest.deprecated_call(): + assert (sliced_data == sliced_img.get_data()).all() + assert (sliced_data == sliced_img.get_fdata()).all() + assert (sliced_data == sliced_img.dataobj).all() + assert (sliced_data == img.dataobj[sliceobj]).all() + with pytest.deprecated_call(): + assert (sliced_data == img.get_data()[sliceobj]).all() + assert (sliced_data == img.get_fdata()[sliceobj]).all() def test_api_deprecations(self): @@ -563,13 +560,13 @@ def from_file_map(self, file_map=None): bio = BytesIO() file_map = FakeImage.make_file_map({'image': bio}) - with assert_raises(ExpiredDeprecationError): + with pytest.raises(ExpiredDeprecationError): img.to_files(file_map) - with assert_raises(ExpiredDeprecationError): + with pytest.raises(ExpiredDeprecationError): img.to_filespec('an_image') - with assert_raises(ExpiredDeprecationError): + with pytest.raises(ExpiredDeprecationError): FakeImage.from_files(file_map) - with assert_raises(ExpiredDeprecationError): + with pytest.raises(ExpiredDeprecationError): FakeImage.filespec_to_files('an_image') @@ -634,28 +631,27 @@ def test_load_mmap(self): back_img = func(param1, **kwargs) back_data = np.asanyarray(back_img.dataobj) if expected_mode is None: - assert_false(isinstance(back_data, np.memmap), - 'Should not be a %s' % img_klass.__name__) + assert not isinstance(back_data, np.memmap), 'Should not be a %s' % img_klass.__name__ else: - assert_true(isinstance(back_data, np.memmap), - 'Not a %s' % img_klass.__name__) + assert isinstance(back_data, np.memmap), 'Not a %s' % img_klass.__name__ if self.check_mmap_mode: - assert_equal(back_data.mode, expected_mode) + assert back_data.mode == expected_mode del back_img, back_data # Check that mmap is keyword-only - assert_raises(TypeError, func, param1, True) + with pytest.raises(TypeError): + func(param1, True) # Check invalid values raise error - assert_raises(ValueError, func, param1, mmap='rw') - assert_raises(ValueError, func, param1, mmap='r+') + with pytest.raises(ValueError): + func(param1, mmap='rw') + with pytest.raises(ValueError): + func(param1, mmap='r+') def test_header_deprecated(): - with clear_and_catch_warnings() as w: - warnings.simplefilter('always', DeprecationWarning) - + with pytest.deprecated_call() as w: class MyHeader(Header): pass - assert_equal(len(w), 0) + assert len(w) == 0 MyHeader() - assert_equal(len(w), 1) + assert len(w) == 1 \ No newline at end of file diff --git a/nibabel/tests/test_spm2analyze.py b/nibabel/tests/test_spm2analyze.py index ddf2956f7d..a88d3cafd4 100644 --- a/nibabel/tests/test_spm2analyze.py +++ b/nibabel/tests/test_spm2analyze.py @@ -13,19 +13,18 @@ from ..spatialimages import HeaderTypeError, HeaderDataError from ..spm2analyze import Spm2AnalyzeHeader, Spm2AnalyzeImage +import pytest from numpy.testing import assert_array_equal -from ..testing import assert_equal, assert_raises from . import test_spm99analyze -import pytest; pytestmark = pytest.mark.skip() class TestSpm2AnalyzeHeader(test_spm99analyze.TestSpm99AnalyzeHeader): header_class = Spm2AnalyzeHeader def test_slope_inter(self): hdr = self.header_class() - assert_equal(hdr.get_slope_inter(), (1.0, 0.0)) + assert hdr.get_slope_inter() == (1.0, 0.0) for in_tup, exp_err, out_tup, raw_slope in ( ((2.0,), None, (2.0, 0.), 2.), ((None,), None, (None, None), np.nan), @@ -43,16 +42,17 @@ def test_slope_inter(self): ((None, 0.0), None, (None, None), np.nan)): hdr = self.header_class() if not exp_err is None: - assert_raises(exp_err, hdr.set_slope_inter, *in_tup) + with pytest.raises(exp_err): + hdr.set_slope_inter(*in_tup) # raw set if not in_tup[0] is None: hdr['scl_slope'] = in_tup[0] else: hdr.set_slope_inter(*in_tup) - assert_equal(hdr.get_slope_inter(), out_tup) + assert hdr.get_slope_inter() == out_tup # Check set survives through checking hdr = Spm2AnalyzeHeader.from_header(hdr, check=True) - assert_equal(hdr.get_slope_inter(), out_tup) + assert hdr.get_slope_inter() == out_tup assert_array_equal(hdr['scl_slope'], raw_slope) diff --git a/nibabel/tests/test_spm99analyze.py b/nibabel/tests/test_spm99analyze.py index ecc63e5935..977fef3071 100644 --- a/nibabel/tests/test_spm99analyze.py +++ b/nibabel/tests/test_spm99analyze.py @@ -12,13 +12,15 @@ from io import BytesIO -from numpy.testing import assert_array_equal, assert_array_almost_equal, dec +from numpy.testing import assert_array_equal, assert_array_almost_equal +import pytest # Decorator to skip tests requiring save / load if scipy not available for mat # files from ..optpkg import optional_package _, have_scipy, _ = optional_package('scipy') -scipy_skip = dec.skipif(not have_scipy, 'scipy not available') + +scipy_skip = pytest.mark.skipif(not have_scipy, reason='scipy not available') from ..spm99analyze import (Spm99AnalyzeHeader, Spm99AnalyzeImage, HeaderTypeError) @@ -26,13 +28,14 @@ from ..volumeutils import apply_read_scaling, _dt_min_max from ..spatialimages import supported_np_types, HeaderDataError -from nose.tools import assert_true, assert_false, assert_equal, assert_raises - -from ..testing import assert_allclose_safely, suppress_warnings -from ..testing_pytest import bytesio_round_trip, bytesio_filemap +from ..testing_pytest import ( + bytesio_round_trip, + bytesio_filemap, + assert_allclose_safely, + suppress_warnings +) from . import test_analyze -import pytest; pytestmark = pytest.mark.skip() FLOAT_TYPES = np.sctypes['float'] COMPLEX_TYPES = np.sctypes['complex'] @@ -62,7 +65,7 @@ def test_data_scaling(self): # almost equal assert_array_almost_equal(data, data_back, 4) # But not quite - assert_false(np.all(data == data_back)) + assert not np.all(data == data_back) # This is exactly the same call, just testing it works twice data_back2 = hdr.data_from_fileobj(S3) assert_array_equal(data_back, data_back2, 4) @@ -70,12 +73,12 @@ def test_data_scaling(self): hdr.data_to_fileobj(data, S3, rescale=True) data_back = hdr.data_from_fileobj(S3) assert_array_almost_equal(data, data_back, 4) - assert_false(np.all(data == data_back)) + assert not np.all(data == data_back) # This doesn't use scaling, and so gets perfect precision with np.errstate(invalid='ignore'): hdr.data_to_fileobj(data, S3, rescale=False) data_back = hdr.data_from_fileobj(S3) - assert_true(np.all(data == data_back)) + assert np.all(data == data_back) class TestSpm99AnalyzeHeader(test_analyze.TestAnalyzeHeader, @@ -85,7 +88,7 @@ class TestSpm99AnalyzeHeader(test_analyze.TestAnalyzeHeader, def test_empty(self): super(TestSpm99AnalyzeHeader, self).test_empty() hdr = self.header_class() - assert_equal(hdr['scl_slope'], 1) + assert hdr['scl_slope'] == 1 def test_big_scaling(self): # Test that upcasting works for huge scalefactors @@ -99,11 +102,11 @@ def test_big_scaling(self): data = np.array([type_info(dtt)['max']], dtype=dtt)[:, None, None] hdr.data_to_fileobj(data, sio) data_back = hdr.data_from_fileobj(sio) - assert_true(np.allclose(data, data_back)) + assert np.allclose(data, data_back) def test_slope_inter(self): hdr = self.header_class() - assert_equal(hdr.get_slope_inter(), (1.0, None)) + assert hdr.get_slope_inter() == (1.0, None) for in_tup, exp_err, out_tup, raw_slope in ( ((2.0,), None, (2.0, None), 2.), ((None,), None, (None, None), np.nan), @@ -121,16 +124,17 @@ def test_slope_inter(self): ((None, 0.0), None, (None, None), np.nan)): hdr = self.header_class() if not exp_err is None: - assert_raises(exp_err, hdr.set_slope_inter, *in_tup) + with pytest.raises(exp_err): + hdr.set_slope_inter(*in_tup) # raw set if not in_tup[0] is None: hdr['scl_slope'] = in_tup[0] else: hdr.set_slope_inter(*in_tup) - assert_equal(hdr.get_slope_inter(), out_tup) + assert hdr.get_slope_inter() == out_tup # Check set survives through checking hdr = Spm99AnalyzeHeader.from_header(hdr, check=True) - assert_equal(hdr.get_slope_inter(), out_tup) + assert hdr.get_slope_inter() == out_tup assert_array_equal(hdr['scl_slope'], raw_slope) def test_origin_checks(self): @@ -140,16 +144,14 @@ def test_origin_checks(self): hdr.data_shape = [1, 1, 1] hdr['origin'][0] = 101 # severity 20 fhdr, message, raiser = self.log_chk(hdr, 20) - assert_equal(fhdr, hdr) - assert_equal(message, 'very large origin values ' - 'relative to dims; leaving as set, ' - 'ignoring for affine') - assert_raises(*raiser) + assert fhdr == hdr + assert (message == 'very large origin values ' + 'relative to dims; leaving as set, ' + 'ignoring for affine') + pytest.raises(*raiser) # diagnose binary block dxer = self.header_class.diagnose_binaryblock - assert_equal(dxer(hdr.binaryblock), - 'very large origin values ' - 'relative to dims') + assert dxer(hdr.binaryblock) == 'very large origin values relative to dims' class ImageScalingMixin(object): @@ -166,9 +168,9 @@ def assert_scale_me_scaling(self, hdr): # Assert that header `hdr` has "scale-me" scaling slope, inter = self._get_raw_scaling(hdr) if not slope is None: - assert_true(np.isnan(slope)) + assert np.isnan(slope) if not inter is None: - assert_true(np.isnan(inter)) + assert np.isnan(inter) def _get_raw_scaling(self, hdr): return hdr['scl_slope'], None @@ -399,7 +401,7 @@ def test_nan2zero_range_ok(self): img.set_data_dtype(np.uint8) with np.errstate(invalid='ignore'): rt_img = bytesio_round_trip(img) - assert_equal(rt_img.get_fdata()[0, 0, 0], 0) + assert rt_img.get_fdata()[0, 0, 0] == 0 class TestSpm99AnalyzeImage(test_analyze.TestAnalyzeImage, ImageScalingMixin): @@ -460,7 +462,7 @@ def test_mat_read(self): from scipy.io import loadmat, savemat mat_fileobj.seek(0) mats = loadmat(mat_fileobj) - assert_true('M' in mats and 'mat' in mats) + assert 'M' in mats and 'mat' in mats from_111 = np.eye(4) from_111[:3, 3] = -1 to_111 = np.eye(4) @@ -471,7 +473,7 @@ def test_mat_read(self): # should have a flip. The 'mat' matrix does include flips and so # should be unaffected by the flipping. If both are present we prefer # the the 'mat' matrix. - assert_true(img.header.default_x_flip) # check the default + assert img.header.default_x_flip # check the default flipper = np.diag([-1, 1, 1, 1]) assert_array_equal(mats['M'], np.dot(aff, np.dot(flipper, from_111))) mat_fileobj.seek(0) @@ -513,7 +515,7 @@ def test_origin_affine(): assert_array_equal(aff, hdr.get_base_affine()) hdr.set_data_shape((3, 5, 7)) hdr.set_zooms((3, 2, 1)) - assert_true(hdr.default_x_flip) + assert hdr.default_x_flip assert_array_almost_equal( hdr.get_origin_affine(), # from center of image [[-3., 0., 0., 3.], diff --git a/nibabel/tests/test_testing.py b/nibabel/tests/test_testing.py index 171447560e..65880c2833 100644 --- a/nibabel/tests/test_testing.py +++ b/nibabel/tests/test_testing.py @@ -7,11 +7,10 @@ import numpy as np -from nose.tools import assert_equal, assert_true, assert_false, assert_raises -from ..testing import (error_warnings, suppress_warnings, +from ..testing_pytest import (error_warnings, suppress_warnings, clear_and_catch_warnings, assert_allclose_safely, get_fresh_mod, assert_re_in, test_data, data_path) -import pytest; pytestmark = pytest.mark.skip() +import pytest def test_assert_allclose_safely(): # Test the safe version of allclose @@ -19,7 +18,8 @@ def test_assert_allclose_safely(): assert_allclose_safely(1, 1) assert_allclose_safely(1, [1, 1]) assert_allclose_safely([1, 1], 1 + 1e-6) - assert_raises(AssertionError, assert_allclose_safely, [1, 1], 1 + 1e-4) + with pytest.raises(AssertionError): + assert_allclose_safely([1, 1], 1 + 1e-4) # Broadcastable matrices a = np.ones((2, 3)) b = np.ones((3, 2, 3)) @@ -27,24 +27,26 @@ def test_assert_allclose_safely(): a[0, 0] = 1 + eps assert_allclose_safely(a, b) a[0, 0] = 1 + 1.1e-5 - assert_raises(AssertionError, assert_allclose_safely, a, b) + with pytest.raises(AssertionError): + assert_allclose_safely(a, b) # Nans in same place a[0, 0] = np.nan b[:, 0, 0] = np.nan assert_allclose_safely(a, b) # Never equal with nans present, if not matching nans - assert_raises(AssertionError, - assert_allclose_safely, a, b, - match_nans=False) + with pytest.raises(AssertionError): + assert_allclose_safely(a, b, match_nans=False) b[0, 0, 0] = 1 - assert_raises(AssertionError, assert_allclose_safely, a, b) + with pytest.raises(AssertionError): + assert_allclose_safely(a, b) # Test allcloseness of inf, especially np.float128 infs for dtt in np.sctypes['float']: a = np.array([-np.inf, 1, np.inf], dtype=dtt) b = np.array([-np.inf, 1, np.inf], dtype=dtt) assert_allclose_safely(a, b) b[1] = 0 - assert_raises(AssertionError, assert_allclose_safely, a, b) + with pytest.raises(AssertionError): + assert_allclose_safely(a, b) # Empty compares equal to empty assert_allclose_safely([], []) @@ -56,19 +58,19 @@ def assert_warn_len_equal(mod, n_in_context): # warning generated by the tests within the context manager, but no # previous warnings. if 'version' in mod_warns: - assert_equal(len(mod_warns), 2) # including 'version' + assert len(mod_warns) == 2 # including 'version' else: - assert_equal(len(mod_warns), n_in_context) + assert len(mod_warns) == n_in_context def test_clear_and_catch_warnings(): # Initial state of module, no warnings my_mod = get_fresh_mod(__name__) - assert_equal(getattr(my_mod, '__warningregistry__', {}), {}) + assert getattr(my_mod, '__warningregistry__', {}) == {} with clear_and_catch_warnings(modules=[my_mod]): warnings.simplefilter('ignore') warnings.warn('Some warning') - assert_equal(my_mod.__warningregistry__, {}) + assert my_mod.__warningregistry__ == {} # Without specified modules, don't clear warnings during context with clear_and_catch_warnings(): warnings.warn('Some warning') @@ -94,23 +96,26 @@ def test_clear_and_catch_warnings_inherit(): with my_cacw(): warnings.simplefilter('ignore') warnings.warn('Some warning') - assert_equal(my_mod.__warningregistry__, {}) + assert my_mod.__warningregistry__ == {} def test_warn_error(): # Check warning error context manager n_warns = len(warnings.filters) with error_warnings(): - assert_raises(UserWarning, warnings.warn, 'A test') + with pytest.raises(UserWarning): + warnings.warn('A test') with error_warnings() as w: # w not used for anything - assert_raises(UserWarning, warnings.warn, 'A test') - assert_equal(n_warns, len(warnings.filters)) + with pytest.raises(UserWarning): + warnings.warn('A test') + assert n_warns == len(warnings.filters) # Check other errors are propagated def f(): with error_warnings(): raise ValueError('An error') - assert_raises(ValueError, f) + with pytest.raises(ValueError): + f() def test_warn_ignore(): @@ -122,54 +127,60 @@ def test_warn_ignore(): with suppress_warnings() as w: # w not used warnings.warn('Here is a warning, you will not see it') warnings.warn('Nor this one', DeprecationWarning) - assert_equal(n_warns, len(warnings.filters)) + assert n_warns == len(warnings.filters) # Check other errors are propagated def f(): with suppress_warnings(): raise ValueError('An error') - assert_raises(ValueError, f) - - -def test_assert_re_in(): - assert_re_in(".*", "") - assert_re_in(".*", ["any"]) - - # Should do match not search - assert_re_in("ab", "abc") - assert_raises(AssertionError, assert_re_in, "ab", "cab") - assert_raises(AssertionError, assert_re_in, "ab$", "abc") + with pytest.raises(ValueError): + f() +@pytest.mark.parametrize("args", [ + [".*", ""], + [".*", ["any"]], + ["ab", "abc"], # Sufficient to have one entry matching - assert_re_in("ab", ["", "abc", "laskdjf"]) - assert_raises(AssertionError, assert_re_in, "ab$", ["ddd", ""]) - + ["ab", ["", "abc", "laskdjf"]], # Tuples should be ok too - assert_re_in("ab", ("", "abc", "laskdjf")) - assert_raises(AssertionError, assert_re_in, "ab$", ("ddd", "")) + ["ab", ("", "abc", "laskdjf")] +]) +def test_assert_re_in(args): + assert_re_in(*args) - # Shouldn't "match" the empty list - assert_raises(AssertionError, assert_re_in, "", []) + +@pytest.mark.parametrize("args", [ + # Should do match not search + ["ab", "cab"], + ["ab$", "abc"], + ["ab$", ["ddd", ""]], + ["ab$", ("ddd", "")], + #Shouldn't "match" the empty list + ["", []] +]) +def test_assert_re_in_exception(args): + with pytest.raises(AssertionError): + assert_re_in(*args) def test_test_data(): - assert_equal(test_data(), data_path) - assert_equal(test_data(), + assert test_data() == data_path + assert (test_data() == os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'tests', 'data'))) for subdir in ('nicom', 'gifti', 'externals'): - assert_equal(test_data(subdir), os.path.join(data_path[:-10], subdir, 'tests', 'data')) - assert_true(os.path.exists(test_data(subdir))) - assert_false(os.path.exists(test_data(subdir, 'doesnotexist'))) + assert test_data(subdir) == os.path.join(data_path[:-10], subdir, 'tests', 'data') + assert os.path.exists(test_data(subdir)) + assert not os.path.exists(test_data(subdir, 'doesnotexist')) for subdir in ('freesurfer', 'doesnotexist'): - with assert_raises(ValueError): + with pytest.raises(ValueError): test_data(subdir) - assert_false(os.path.exists(test_data(None, 'doesnotexist'))) + assert not os.path.exists(test_data(None, 'doesnotexist')) for subdir, fname in [('gifti', 'ascii.gii'), ('nicom', '0.dcm'), ('externals', 'example_1.nc'), (None, 'empty.tck')]: - assert_true(os.path.exists(test_data(subdir, fname))) + assert os.path.exists(test_data(subdir, fname)) diff --git a/nibabel/tests/test_tmpdirs.py b/nibabel/tests/test_tmpdirs.py index 7914e273e1..c4d119b14f 100644 --- a/nibabel/tests/test_tmpdirs.py +++ b/nibabel/tests/test_tmpdirs.py @@ -5,8 +5,6 @@ from ..tmpdirs import InGivenDirectory -from nose.tools import assert_true, assert_equal -import pytest; pytestmark = pytest.mark.skip() MY_PATH = abspath(__file__) MY_DIR = dirname(MY_PATH) @@ -16,10 +14,10 @@ def test_given_directory(): # Test InGivenDirectory cwd = getcwd() with InGivenDirectory() as tmpdir: - assert_equal(tmpdir, abspath(cwd)) - assert_equal(tmpdir, abspath(getcwd())) + assert tmpdir == abspath(cwd) + assert tmpdir == abspath(getcwd()) with InGivenDirectory(MY_DIR) as tmpdir: - assert_equal(tmpdir, MY_DIR) - assert_equal(realpath(MY_DIR), realpath(abspath(getcwd()))) + assert tmpdir == MY_DIR + assert realpath(MY_DIR) == realpath(abspath(getcwd())) # We were deleting the Given directory! Check not so now. - assert_true(isfile(MY_PATH)) + assert isfile(MY_PATH) diff --git a/nibabel/tests/test_trackvis.py b/nibabel/tests/test_trackvis.py index 676ee52d87..ad4eb083a2 100644 --- a/nibabel/tests/test_trackvis.py +++ b/nibabel/tests/test_trackvis.py @@ -9,16 +9,14 @@ from ..orientations import aff2axcodes from ..volumeutils import native_code, swapped_code -from numpy.testing import assert_array_almost_equal -from ..testing import (assert_true, assert_false, assert_equal, assert_raises, assert_warns, - assert_array_equal, suppress_warnings) -import pytest; pytestmark = pytest.mark.skip() +from numpy.testing import assert_array_almost_equal, assert_array_equal +import pytest def test_write(): streams = [] out_f = BytesIO() tv.write(out_f, [], {}) - assert_equal(out_f.getvalue(), tv.empty_header().tostring()) + assert out_f.getvalue() == tv.empty_header().tostring() out_f.truncate(0) out_f.seek(0) # Write something not-default @@ -26,7 +24,7 @@ def test_write(): # read it back out_f.seek(0) streams, hdr = tv.read(out_f) - assert_equal(hdr['id_string'], b'TRACKb') + assert hdr['id_string'] == b'TRACKb' # check that we can pass none for the header out_f.truncate(0) out_f.seek(0) @@ -37,12 +35,12 @@ def test_write(): # check that we check input values out_f.truncate(0) out_f.seek(0) - assert_raises(tv.HeaderError, - tv.write, out_f, [], {'id_string': 'not OK'}) - assert_raises(tv.HeaderError, - tv.write, out_f, [], {'version': 3}) - assert_raises(tv.HeaderError, - tv.write, out_f, [], {'hdr_size': 0}) + with pytest.raises(tv.HeaderError): + tv.write(out_f, [], {'id_string': 'not OK'}) + with pytest.raises(tv.HeaderError): + tv.write(out_f, [], {'version': 3}) + with pytest.raises(tv.HeaderError): + tv.write(out_f, [], {'hdr_size': 0}) def test_write_scalars_props(): @@ -57,26 +55,31 @@ def test_write_scalars_props(): out_f = BytesIO() streams = [(points, None, None), (points, scalars, None)] - assert_raises(tv.DataError, tv.write, out_f, streams) + with pytest.raises(tv.DataError): + tv.write(out_f, streams) out_f.seek(0) streams = [(points, np.zeros((N, M + 1)), None), (points, scalars, None)] - assert_raises(tv.DataError, tv.write, out_f, streams) + with pytest.raises(tv.DataError): + tv.write(out_f, streams) # Or if scalars different N compared to points bad_scalars = np.zeros((N + 1, M)) out_f.seek(0) streams = [(points, bad_scalars, None), (points, bad_scalars, None)] - assert_raises(tv.DataError, tv.write, out_f, streams) + with pytest.raises(tv.DataError): + tv.write(out_f, streams) # Similarly properties must have the same length for each streamline out_f.seek(0) streams = [(points, scalars, None), (points, scalars, props)] - assert_raises(tv.DataError, tv.write, out_f, streams) + with pytest.raises(tv.DataError): + tv.write(out_f, streams) out_f.seek(0) streams = [(points, scalars, np.zeros((P + 1,))), (points, scalars, props)] - assert_raises(tv.DataError, tv.write, out_f, streams) + with pytest.raises(tv.DataError): + tv.write(out_f, streams) # If all is OK, then we get back what we put in out_f.seek(0) streams = [(points, scalars, props), @@ -134,7 +137,7 @@ def test_round_trip(): tv.write(out_f, streams, {}) out_f.seek(0) streams2, hdr = tv.read(out_f) - assert_true(streamlist_equal(streams, streams2)) + assert streamlist_equal(streams, streams2) # test that we can write in different endianness and get back same result, # for versions 1, 2 and not-specified for in_dict, back_version in (({}, 2), @@ -145,15 +148,15 @@ def test_round_trip(): tv.write(out_f, streams, in_dict, endian_code) out_f.seek(0) streams2, hdr = tv.read(out_f) - assert_true(streamlist_equal(streams, streams2)) - assert_equal(hdr['version'], back_version) + assert streamlist_equal(streams, streams2) + assert hdr['version'] == back_version # test that we can get out and pass in generators out_f.seek(0) streams3, hdr = tv.read(out_f, as_generator=True) # check this is a generator rather than a list - assert_true(hasattr(streams3, 'send')) + assert hasattr(streams3, 'send') # but that it results in the same output - assert_true(streamlist_equal(streams, list(streams3))) + assert streamlist_equal(streams, list(streams3)) # write back in out_f.seek(0) streams3, hdr = tv.read(out_f, as_generator=True) @@ -164,7 +167,7 @@ def test_round_trip(): # and re-read just to check out_f_write.seek(0) streams2, hdr = tv.read(out_f_write) - assert_true(streamlist_equal(streams, streams2)) + assert streamlist_equal(streams, streams2) def test_points_processing(): @@ -192,11 +195,11 @@ def _rt(streams, hdr, points_space): # voxmm is the default. In this case we don't do anything to the # points, and we let the header pass through without further checks (raw_streams, hdr), (proc_streams, _) = _rt(vxmm_streams, {}, None) - assert_true(streamlist_equal(raw_streams, proc_streams)) - assert_true(streamlist_equal(vxmm_streams, proc_streams)) + assert streamlist_equal(raw_streams, proc_streams) + assert streamlist_equal(vxmm_streams, proc_streams) (raw_streams, hdr), (proc_streams, _) = _rt(vxmm_streams, {}, 'voxmm') - assert_true(streamlist_equal(raw_streams, proc_streams)) - assert_true(streamlist_equal(vxmm_streams, proc_streams)) + assert streamlist_equal(raw_streams, proc_streams) + assert streamlist_equal(vxmm_streams, proc_streams) # with 'voxels' as input, check for not all voxel_size == 0, warn if any # voxel_size == 0 for hdr in ( # these cause read / write errors @@ -207,21 +210,23 @@ def _rt(streams, hdr, points_space): ): # Check error on write out_f.seek(0) - assert_raises(tv.HeaderError, - tv.write, out_f, vx_streams, hdr, None, 'voxel') + with pytest.raises(tv.HeaderError): + tv.write(out_f, vx_streams, hdr, None, 'voxel') out_f.seek(0) # bypass write error and check read tv.write(out_f, vxmm_streams, hdr, None, points_space=None) out_f.seek(0) - assert_raises(tv.HeaderError, tv.read, out_f, False, 'voxel') + with pytest.raises(tv.HeaderError): + tv.read(out_f, False, 'voxel') # There's a warning for any voxel sizes == 0 hdr = {'voxel_size': [2, 3, 0]} - assert_warns(UserWarning, _rt, vx_streams, hdr, 'voxel') + with pytest.warns(UserWarning): + _rt(vx_streams, hdr, 'voxel') # This should be OK hdr = {'voxel_size': [2, 3, 4]} (raw_streams, hdr), (proc_streams, _) = _rt(vx_streams, hdr, 'voxel') - assert_true(streamlist_equal(vxmm_streams, raw_streams)) - assert_true(streamlist_equal(vx_streams, proc_streams)) + assert streamlist_equal(vxmm_streams, raw_streams) + assert streamlist_equal(vx_streams, proc_streams) # Now we try with rasmm points. In this case we need valid voxel_size, # and voxel_order, and vox_to_ras. The voxel_order has to match the # vox_to_ras, and so do the voxel sizes @@ -247,19 +252,20 @@ def _rt(streams, hdr, points_space): ): # Check error on write out_f.seek(0) - assert_raises(tv.HeaderError, - tv.write, out_f, rasmm_streams, hdr, None, 'rasmm') + with pytest.raises(tv.HeaderError): + tv.write(out_f, rasmm_streams, hdr, None, 'rasmm') out_f.seek(0) # bypass write error and check read tv.write(out_f, vxmm_streams, hdr, None, points_space=None) out_f.seek(0) - assert_raises(tv.HeaderError, tv.read, out_f, False, 'rasmm') + with pytest.raises(tv.HeaderError): + tv.read(out_f, False, 'rasmm') # This should be OK hdr = {'voxel_size': [2, 3, 4], 'voxel_order': 'RAS', 'vox_to_ras': aff} (raw_streams, hdr), (proc_streams, _) = _rt(rasmm_streams, hdr, 'rasmm') - assert_true(streamlist_equal(vxmm_streams, raw_streams)) - assert_true(streamlist_equal(rasmm_streams, proc_streams)) + assert streamlist_equal(vxmm_streams, raw_streams) + assert streamlist_equal(rasmm_streams, proc_streams) # More complex test to check matrix orientation fancy_affine = np.array([[0., -2, 0, 10], [3, 0, 0, 20], @@ -278,90 +284,88 @@ def f(pts): # from vx to mm (ijk1 * [[3, 2, 4]], scalars[1], None)] (raw_streams, hdr), (proc_streams, _) = _rt( fancy_rasmm_streams, hdr, 'rasmm') - assert_true(streamlist_equal(fancy_vxmm_streams, raw_streams)) - assert_true(streamlist_equal(fancy_rasmm_streams, proc_streams)) + assert streamlist_equal(fancy_vxmm_streams, raw_streams) + assert streamlist_equal(fancy_rasmm_streams, proc_streams) def test__check_hdr_points_space(): # Test checking routine for points_space input given header # None or voxmm -> no checks, pass through - assert_equal(tv._check_hdr_points_space({}, None), None) - assert_equal(tv._check_hdr_points_space({}, 'voxmm'), None) + assert tv._check_hdr_points_space({}, None) is None + assert tv._check_hdr_points_space({}, 'voxmm') is None # strange value for points_space -> ValueError - assert_raises(ValueError, - tv._check_hdr_points_space, {}, 'crazy') + with pytest.raises(ValueError): + tv._check_hdr_points_space({}, 'crazy') # Input not in (None, 'voxmm', 'voxels', 'rasmm') - error # voxels means check voxel sizes present and not all 0. hdr = tv.empty_header() assert_array_equal(hdr['voxel_size'], [0, 0, 0]) - assert_raises(tv.HeaderError, - tv._check_hdr_points_space, hdr, 'voxel') + with pytest.raises(tv.HeaderError): + tv._check_hdr_points_space(hdr, 'voxel') # Negative voxel size gives error - because it is not what trackvis does, # and this not what we mean by 'voxmm' hdr['voxel_size'] = [-2, 3, 4] - assert_raises(tv.HeaderError, - tv._check_hdr_points_space, hdr, 'voxel') + with pytest.raises(tv.HeaderError): + tv._check_hdr_points_space(hdr, 'voxel') # Warning here only hdr['voxel_size'] = [2, 3, 0] - assert_warns(UserWarning, - tv._check_hdr_points_space, hdr, 'voxel') + with pytest.warns(UserWarning): + tv._check_hdr_points_space(hdr, 'voxel') # This is OK hdr['voxel_size'] = [2, 3, 4] - assert_equal(tv._check_hdr_points_space(hdr, 'voxel'), None) + assert tv._check_hdr_points_space(hdr, 'voxel') is None # rasmm - check there is an affine, that it matches voxel_size and # voxel_order # no affine hdr['voxel_size'] = [2, 3, 4] - assert_raises(tv.HeaderError, - tv._check_hdr_points_space, hdr, 'rasmm') + with pytest.raises(tv.HeaderError): + tv._check_hdr_points_space(hdr, 'rasmm') # still no affine hdr['voxel_order'] = 'RAS' - assert_raises(tv.HeaderError, - tv._check_hdr_points_space, hdr, 'rasmm') + with pytest.raises(tv.HeaderError): + tv._check_hdr_points_space(hdr, 'rasmm') # nearly an affine, but 0 at position 3,3 - means not recorded in trackvis # standard hdr['vox_to_ras'] = np.diag([2, 3, 4, 0]) - assert_raises(tv.HeaderError, - tv._check_hdr_points_space, hdr, 'rasmm') + with pytest.raises(tv.HeaderError): + tv._check_hdr_points_space(hdr, 'rasmm') # This affine doesn't match RAS voxel order hdr['vox_to_ras'] = np.diag([-2, 3, 4, 1]) - assert_raises(tv.HeaderError, - tv._check_hdr_points_space, hdr, 'rasmm') + with pytest.raises(tv.HeaderError): + tv._check_hdr_points_space(hdr, 'rasmm') # This affine doesn't match the voxel size hdr['vox_to_ras'] = np.diag([3, 3, 4, 1]) - assert_raises(tv.HeaderError, - tv._check_hdr_points_space, hdr, 'rasmm') + with pytest.raises(tv.HeaderError): + tv._check_hdr_points_space(hdr, 'rasmm') # This should be OK good_aff = np.diag([2, 3, 4, 1]) hdr['vox_to_ras'] = good_aff - assert_equal(tv._check_hdr_points_space(hdr, 'rasmm'), - None) + assert tv._check_hdr_points_space(hdr, 'rasmm') is None # Default voxel order of LPS assumed hdr['voxel_order'] = '' # now the RAS affine raises an error - assert_raises(tv.HeaderError, - tv._check_hdr_points_space, hdr, 'rasmm') + with pytest.raises(tv.HeaderError): + tv._check_hdr_points_space(hdr, 'rasmm') # this affine does have LPS voxel order good_lps = np.dot(np.diag([-1, -1, 1, 1]), good_aff) hdr['vox_to_ras'] = good_lps - assert_equal(tv._check_hdr_points_space(hdr, 'rasmm'), - None) + assert tv._check_hdr_points_space(hdr, 'rasmm') is None def test_empty_header(): for endian in '<>': for version in (1, 2): hdr = tv.empty_header(endian, version) - assert_equal(hdr['id_string'], b'TRACK') - assert_equal(hdr['version'], version) - assert_equal(hdr['hdr_size'], 1000) + assert hdr['id_string'] == b'TRACK' + assert hdr['version'] == version + assert hdr['hdr_size'] == 1000 assert_array_equal( hdr['image_orientation_patient'], [0, 0, 0, 0, 0, 0]) hdr = tv.empty_header(version=2) assert_array_equal(hdr['vox_to_ras'], np.zeros((4, 4))) hdr_endian = tv.endian_codes[tv.empty_header().dtype.byteorder] - assert_equal(hdr_endian, tv.native_code) + assert hdr_endian == tv.native_code def test_get_affine(): @@ -391,11 +395,12 @@ def test_get_affine(): exp_aff) # check against voxel order. This one works hdr['voxel_order'] = ''.join(aff2axcodes(exp_aff)) - assert_equal(hdr['voxel_order'], b'RAS') + assert hdr['voxel_order'] == b'RAS' assert_array_equal(old_afh(hdr), exp_aff) # This one doesn't hdr['voxel_order'] = 'LAS' - assert_raises(tv.HeaderError, old_afh, hdr) + with pytest.raises(tv.HeaderError): + old_afh(hdr) # This one does work because the routine allows the final dimension to # be flipped to try and match the voxel order hdr['voxel_order'] = 'RAI' @@ -411,11 +416,12 @@ def test_get_affine(): tv.aff_to_hdr(in_aff, hdr, pos_vox=True, set_order=True) # Unset easier option hdr['vox_to_ras'] = 0 - assert_equal(hdr['voxel_order'], o_codes) + assert hdr['voxel_order'] == o_codes # Check it came back the way we wanted assert_array_equal(old_afh(hdr), in_aff) # Check that v1 header raises error - assert_raises(tv.HeaderError, tv.aff_from_hdr, hdr) + with pytest.raises(tv.HeaderError): + tv.aff_from_hdr(hdr) # now use the easier vox_to_ras field hdr = tv.empty_header() aff = np.eye(4) @@ -453,28 +459,28 @@ def test_aff_to_hdr(): for hdr in ({}, {'version': 2}, {'version': 1}): tv.aff_to_hdr(aff2, hdr, pos_vox=True, set_order=False) assert_array_equal(hdr['voxel_size'], [1, 2, 3]) - assert_false('voxel_order' in hdr) + assert 'voxel_order' not in hdr tv.aff_to_hdr(aff2, hdr, pos_vox=False, set_order=True) assert_array_equal(hdr['voxel_size'], [-1, 2, 3]) - assert_equal(hdr['voxel_order'], 'RAI') + assert hdr['voxel_order'] == 'RAI' tv.aff_to_hdr(aff2, hdr, pos_vox=True, set_order=True) assert_array_equal(hdr['voxel_size'], [1, 2, 3]) - assert_equal(hdr['voxel_order'], 'RAI') + assert hdr['voxel_order'] == 'RAI' if 'version' in hdr and hdr['version'] == 1: - assert_false('vox_to_ras' in hdr) + assert 'vox_to_ras' not in hdr else: assert_array_equal(hdr['vox_to_ras'], aff2) def test_tv_class(): tvf = tv.TrackvisFile([]) - assert_equal(tvf.streamlines, []) - assert_true(isinstance(tvf.header, np.ndarray)) - assert_equal(tvf.endianness, tv.native_code) - assert_equal(tvf.filename, None) + assert tvf.streamlines == [] + assert isinstance(tvf.header, np.ndarray) + assert tvf.endianness == tv.native_code + assert tvf.filename is None out_f = BytesIO() tvf.to_file(out_f) - assert_equal(out_f.getvalue(), tv.empty_header().tostring()) + assert out_f.getvalue() == tv.empty_header().tostring() out_f.truncate(0) out_f.seek(0) # Write something not-default @@ -483,19 +489,16 @@ def test_tv_class(): # read it back out_f.seek(0) tvf_back = tv.TrackvisFile.from_file(out_f) - assert_equal(tvf_back.header['id_string'], b'TRACKb') + assert tvf_back.header['id_string'] == b'TRACKb' # check that we check input values out_f.truncate(0) out_f.seek(0) - assert_raises(tv.HeaderError, - tv.TrackvisFile, - [], {'id_string': 'not OK'}) - assert_raises(tv.HeaderError, - tv.TrackvisFile, - [], {'version': 3}) - assert_raises(tv.HeaderError, - tv.TrackvisFile, - [], {'hdr_size': 0}) + with pytest.raises(tv.HeaderError): + tv.TrackvisFile([], {'id_string': 'not OK'}) + with pytest.raises(tv.HeaderError): + tv.TrackvisFile([], {'version': 3}) + with pytest.raises(tv.HeaderError): + tv.TrackvisFile([], {'hdr_size': 0}) affine = np.diag([1, 2, 3, 1]) affine[:3, 3] = [10, 11, 12] # affine methods will raise same warnings and errors as function @@ -503,9 +506,8 @@ def test_tv_class(): aff = tvf.get_affine(atleast_v2=True) assert_array_almost_equal(aff, affine) # Test that we raise an error with an iterator - assert_raises(tv.TrackvisFileError, - tv.TrackvisFile, - iter([])) + with pytest.raises(tv.TrackvisFileError): + tv.TrackvisFile(iter([])) def test_tvfile_io(): @@ -521,22 +523,23 @@ def test_tvfile_io(): tvf.to_file(out_f) out_f.seek(0) tvf2 = tv.TrackvisFile.from_file(out_f) - assert_equal(tvf2.filename, None) - assert_true(streamlist_equal(vxmm_streams, tvf2.streamlines)) - assert_equal(tvf2.points_space, None) + assert tvf2.filename is None + assert streamlist_equal(vxmm_streams, tvf2.streamlines) + assert tvf2.points_space is None # Voxel points_space tvf = tv.TrackvisFile(vx_streams, points_space='voxel') out_f.seek(0) # No voxel size - error - assert_raises(tv.HeaderError, tvf.to_file, out_f) + with pytest.raises(tv.HeaderError): + tvf.to_file(out_f) out_f.seek(0) # With voxel size, no error, roundtrip works tvf.header['voxel_size'] = [2, 3, 4] tvf.to_file(out_f) out_f.seek(0) tvf2 = tv.TrackvisFile.from_file(out_f, points_space='voxel') - assert_true(streamlist_equal(vx_streams, tvf2.streamlines)) - assert_equal(tvf2.points_space, 'voxel') + assert streamlist_equal(vx_streams, tvf2.streamlines) + assert tvf2.points_space == 'voxel' out_f.seek(0) # Also with affine specified tvf = tv.TrackvisFile(vx_streams, points_space='voxel', @@ -544,7 +547,7 @@ def test_tvfile_io(): tvf.to_file(out_f) out_f.seek(0) tvf2 = tv.TrackvisFile.from_file(out_f, points_space='voxel') - assert_true(streamlist_equal(vx_streams, tvf2.streamlines)) + assert streamlist_equal(vx_streams, tvf2.streamlines) # Fancy affine test fancy_affine = np.array([[0., -2, 0, 10], [3, 0, 0, 20], @@ -560,15 +563,16 @@ def f(pts): # from vx to mm tvf = tv.TrackvisFile(fancy_rasmm_streams, points_space='rasmm') out_f.seek(0) # No affine - assert_raises(tv.HeaderError, tvf.to_file, out_f) + with pytest.raises(tv.HeaderError): + tvf.to_file(out_f) out_f.seek(0) # With affine set, no error, roundtrip works tvf.set_affine(fancy_affine, pos_vox=True, set_order=True) tvf.to_file(out_f) out_f.seek(0) tvf2 = tv.TrackvisFile.from_file(out_f, points_space='rasmm') - assert_true(streamlist_equal(fancy_rasmm_streams, tvf2.streamlines)) - assert_equal(tvf2.points_space, 'rasmm') + assert streamlist_equal(fancy_rasmm_streams, tvf2.streamlines) + assert tvf2.points_space == 'rasmm' out_f.seek(0) # Also when affine given in init tvf = tv.TrackvisFile(fancy_rasmm_streams, points_space='rasmm', @@ -576,7 +580,7 @@ def f(pts): # from vx to mm tvf.to_file(out_f) out_f.seek(0) tvf2 = tv.TrackvisFile.from_file(out_f, points_space='rasmm') - assert_true(streamlist_equal(fancy_rasmm_streams, tvf2.streamlines)) + assert streamlist_equal(fancy_rasmm_streams, tvf2.streamlines) def test_read_truncated(): @@ -590,26 +594,29 @@ def test_read_truncated(): value = out_f.getvalue()[:-(3 * 4)] new_f = BytesIO(value) # By default, raises a DataError - assert_raises(tv.DataError, tv.read, new_f) + with pytest.raises(tv.DataError): + tv.read(new_f) # This corresponds to strict mode new_f.seek(0) - assert_raises(tv.DataError, tv.read, new_f, strict=True) + with pytest.raises(tv.DataError): + tv.read(new_f, strict=True) # lenient error mode lets this error pass, with truncated track short_streams = [(xyz0, None, None), (xyz1[:-1], None, None)] new_f.seek(0) streams2, hdr = tv.read(new_f, strict=False) - assert_true(streamlist_equal(streams2, short_streams)) + assert streamlist_equal(streams2, short_streams) # Check that lenient works when number of tracks is 0, where 0 signals to # the reader to read until the end of the file. again_hdr = hdr.copy() - assert_equal(again_hdr['n_count'], 2) + assert again_hdr['n_count'] == 2 again_hdr['n_count'] = 0 again_bytes = again_hdr.tostring() + value[again_hdr.itemsize:] again_f = BytesIO(again_bytes) streams2, _ = tv.read(again_f, strict=False) - assert_true(streamlist_equal(streams2, short_streams)) + assert streamlist_equal(streams2, short_streams) # Set count to one above actual number of tracks, always raise error again_hdr['n_count'] = 3 again_bytes = again_hdr.tostring() + value[again_hdr.itemsize:] again_f = BytesIO(again_bytes) - assert_raises(tv.DataError, tv.read, again_f, strict=False) + with pytest.raises(tv.DataError): + tv.read(again_f, strict=False) diff --git a/nibabel/tests/test_tripwire.py b/nibabel/tests/test_tripwire.py index 990f0bbf39..b69e913d4b 100644 --- a/nibabel/tests/test_tripwire.py +++ b/nibabel/tests/test_tripwire.py @@ -3,26 +3,22 @@ from ..tripwire import TripWire, is_tripwire, TripWireError -from nose.tools import (assert_true, assert_false, assert_raises, - assert_equal, assert_not_equal) -import pytest; pytestmark = pytest.mark.skip() +import pytest def test_is_tripwire(): - assert_false(is_tripwire(object())) - assert_true(is_tripwire(TripWire('some message'))) + assert not is_tripwire(object()) + assert is_tripwire(TripWire('some message')) def test_tripwire(): # Test tripwire object silly_module_name = TripWire('We do not have silly_module_name') - assert_raises(TripWireError, - getattr, - silly_module_name, - 'do_silly_thing') + with pytest.raises(TripWireError): + getattr(silly_module_name, 'do_silly_thing') # Check AttributeError can be checked too try: silly_module_name.__wrapped__ except TripWireError as err: - assert_true(isinstance(err, AttributeError)) + assert isinstance(err, AttributeError) else: raise RuntimeError("No error raised, but expected") diff --git a/nibabel/tests/test_viewers.py b/nibabel/tests/test_viewers.py index 0e3f076223..1be6e400a2 100644 --- a/nibabel/tests/test_viewers.py +++ b/nibabel/tests/test_viewers.py @@ -14,16 +14,13 @@ from ..optpkg import optional_package from ..viewers import OrthoSlicer3D -from ..testing import skipif from numpy.testing import assert_array_equal, assert_equal -from nose.tools import assert_raises, assert_true -import pytest; pytestmark = pytest.mark.skip() +import pytest # Need at least MPL 1.3 for viewer tests. matplotlib, has_mpl, _ = optional_package('matplotlib', min_version='1.3') - -needs_mpl = skipif(not has_mpl, 'These tests need matplotlib') +needs_mpl = pytest.mark.skipif(not has_mpl, reason='These tests need matplotlib') if has_mpl: matplotlib.use('Agg') @@ -38,7 +35,7 @@ def test_viewer(): data = data * np.array([1., 2.]) # give it a # of volumes > 1 v = OrthoSlicer3D(data) assert_array_equal(v.position, (0, 0, 0)) - assert_true('OrthoSlicer3D' in repr(v)) + assert 'OrthoSlicer3D' in repr(v) # fake some events, inside and outside axes v._on_scroll(nt('event', 'button inaxes key')('up', None, None)) @@ -53,8 +50,10 @@ def test_viewer(): v.set_volume_idx(1) v.cmap = 'hot' v.clim = (0, 3) - assert_raises(ValueError, OrthoSlicer3D.clim.fset, v, (0.,)) # bad limits - assert_raises(ValueError, OrthoSlicer3D.cmap.fset, v, 'foo') # wrong cmap + with pytest.raises(ValueError): + OrthoSlicer3D.clim.fset(v, (0.,)) # bad limits + with pytest.raises(ValueError): + OrthoSlicer3D.cmap.fset(v, 'foo') # wrong cmap # decrement/increment volume numbers via keypress v.set_volume_idx(1) # should just pass @@ -76,8 +75,8 @@ def test_viewer(): v.close() # complex input should raise a TypeError prior to figure creation - assert_raises(TypeError, OrthoSlicer3D, - data[:, :, :, 0].astype(np.complex64)) + with pytest.raises(TypeError): + OrthoSlicer3D(data[:, :, :, 0].astype(np.complex64)) # other cases fig, axes = plt.subplots(1, 4) @@ -87,10 +86,13 @@ def test_viewer(): float) v2 = OrthoSlicer3D(data, affine=aff, axes=axes[:3]) # bad data (not 3+ dim) - assert_raises(ValueError, OrthoSlicer3D, data[:, :, 0, 0]) + with pytest.raises(ValueError): + OrthoSlicer3D(data[:, :, 0, 0]) # bad affine (not 4x4) - assert_raises(ValueError, OrthoSlicer3D, data, affine=np.eye(3)) - assert_raises(TypeError, v2.link_to, 1) + with pytest.raises(ValueError): + OrthoSlicer3D(data, affine=np.eye(3)) + with pytest.raises(TypeError): + v2.link_to(1) v2.link_to(v1) v2.link_to(v1) # shouldn't do anything v1.close() diff --git a/nibabel/tests/test_volumeutils.py b/nibabel/tests/test_volumeutils.py index 711894aabc..dca5053d74 100644 --- a/nibabel/tests/test_volumeutils.py +++ b/nibabel/tests/test_volumeutils.py @@ -20,13 +20,11 @@ import bz2 import threading import time -import pytest import numpy as np from ..tmpdirs import InTemporaryDirectory from ..openers import ImageOpener -from .. import volumeutils from ..volumeutils import (array_from_file, _is_compressed_fobj, array_to_file, @@ -57,11 +55,9 @@ from numpy.testing import (assert_array_almost_equal, assert_array_equal) -from nose.tools import assert_raises +import pytest -from ..testing_pytest import (assert_dt_equal, assert_allclose_safely, - suppress_warnings, clear_and_catch_warnings) -import pytest; pytestmark = pytest.mark.skip() +from ..testing_pytest import assert_dt_equal, assert_allclose_safely, suppress_warnings #: convenience variables for numpy types FLOAT_TYPES = np.sctypes['float'] @@ -73,11 +69,11 @@ def test_deprecated_functions(): - with assert_raises(ExpiredDeprecationError): + with pytest.raises(ExpiredDeprecationError): scale_min_max(0, 1, np.uint8, True) - with assert_raises(ExpiredDeprecationError): + with pytest.raises(ExpiredDeprecationError): calculate_scale(np.array([-2, -1], dtype=np.int8), np.uint8, True) - with assert_raises(ExpiredDeprecationError): + with pytest.raises(ExpiredDeprecationError): can_cast(np.float32, np.float32) @@ -1022,8 +1018,7 @@ def test_fname_ext_ul_case(): def test_allopen(): # This import into volumeutils is for compatibility. The code is the # ``openers`` module. - with clear_and_catch_warnings() as w: - warnings.filterwarnings('once', category=DeprecationWarning) + with pytest.deprecated_call() as w: # Test default mode is 'rb' fobj = allopen(__file__) # Check we got the deprecation warning diff --git a/nibabel/tests/test_wrapstruct.py b/nibabel/tests/test_wrapstruct.py index f052098475..32035db995 100644 --- a/nibabel/tests/test_wrapstruct.py +++ b/nibabel/tests/test_wrapstruct.py @@ -175,7 +175,7 @@ def test_mappingness(self): for key, val in hdr.items(): assert_array_equal(hdr[key], val) # verify that .get operates as destined - assert hdr.get('nonexistent key') == None + assert hdr.get('nonexistent key') is None assert hdr.get('nonexistent key', 'default') == 'default' assert hdr.get(keys[0]) == vals[0] assert hdr.get(keys[0], 'default') == vals[0]