diff --git a/.azure-pipelines/windows.yml b/.azure-pipelines/windows.yml index f825bef612..8b7e990fe2 100644 --- a/.azure-pipelines/windows.yml +++ b/.azure-pipelines/windows.yml @@ -11,6 +11,7 @@ jobs: variables: EXTRA_WHEELS: "https://5cf40426d9f06eb7461d-6fe47d9331aba7cd62fc36c7196769e4.ssl.cf2.rackcdn.com" DEPENDS: numpy scipy matplotlib h5py pydicom + CHECK_TYPE: test strategy: matrix: ${{ insert }}: ${{ parameters.matrix }} @@ -29,19 +30,20 @@ jobs: displayName: 'Update build tools' - script: | python -m pip install --find-links %EXTRA_WHEELS% %DEPENDS% - python -m pip install nose mock coverage codecov pytest displayName: 'Install dependencies' - script: | - python -m pip install . + python -m pip install .[$(CHECK_TYPE)] SET NIBABEL_DATA_DIR=%CD%\\nibabel-data displayName: 'Install nibabel' - script: | mkdir for_testing cd for_testing cp ../.coveragerc . - nosetests --with-doctest --with-coverage --cover-package nibabel nibabel - displayName: 'Nose tests' + pytest --doctest-modules --cov nibabel -v --pyargs nibabel + displayName: 'Pytest tests' + condition: and(succeeded(), eq(variables['CHECK_TYPE'], 'test')) - script: | + python -m pip install codecov cd for_testing codecov displayName: 'Upload To Codecov' diff --git a/.gitignore b/.gitignore index fd686f2781..e876975c27 100644 --- a/.gitignore +++ b/.gitignore @@ -85,3 +85,4 @@ doc/source/reference venv/ .buildbot.patch .vscode +for_testing/ diff --git a/.travis.yml b/.travis.yml index 4e8e1051f1..fcf2085c63 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,11 +4,11 @@ # for it to be on multiple physical lines, so long as you remember: - There # can't be any leading "-"s - All newlines will be removed, so use ";"s +os: linux dist: xenial -sudo: true language: python - cache: pip + env: global: - SETUP_REQUIRES="pip setuptools>=30.3.0 wheel" @@ -25,7 +25,7 @@ python: - 3.7 - 3.8 -matrix: +jobs: include: # Basic dependencies only - python: 3.5 @@ -143,7 +143,7 @@ script: mkdir for_testing cd for_testing cp ../.coveragerc . - nosetests --with-doctest --with-coverage --cover-package nibabel nibabel + pytest --doctest-modules --cov nibabel -v --pyargs nibabel else false fi diff --git a/dev-requirements.txt b/dev-requirements.txt index 659ab6cada..69302061bc 100644 --- a/dev-requirements.txt +++ b/dev-requirements.txt @@ -1,3 +1,3 @@ # Requirements for running tests -r requirements.txt -nose +pytest diff --git a/doc/source/devel/advanced_testing.rst b/doc/source/devel/advanced_testing.rst index 0dc365ea1d..77b6522cb1 100644 --- a/doc/source/devel/advanced_testing.rst +++ b/doc/source/devel/advanced_testing.rst @@ -25,7 +25,7 @@ Long-running tests Long-running tests are not enabled by default, and can be resource-intensive. To run these tests: * Set environment variable ``NIPY_EXTRA_TESTS=slow``; -* Run ``nosetests``. +* Run ``pytest nibabel``. Note that some tests may require a machine with >4GB of RAM. diff --git a/doc/source/devel/make_release.rst b/doc/source/devel/make_release.rst index 25db5210b7..6a09d280b2 100644 --- a/doc/source/devel/make_release.rst +++ b/doc/source/devel/make_release.rst @@ -79,7 +79,7 @@ Release checklist * Make sure all tests pass (from the nibabel root directory):: - nosetests --with-doctest nibabel + pytest --doctest-modules nibabel * Make sure you are set up to use the ``try_branch.py`` - see https://github.com/nipy/nibotmi/blob/master/install.rst#trying-a-set-of-changes-on-the-buildbots diff --git a/doc/source/installation.rst b/doc/source/installation.rst index ed390578ff..fe02bcdbf2 100644 --- a/doc/source/installation.rst +++ b/doc/source/installation.rst @@ -90,7 +90,7 @@ Requirements * h5py_ (optional, for MINC2 support) * PyDICOM_ 0.9.9 or greater (optional, for DICOM support) * `Python Imaging Library`_ (optional, for PNG conversion in DICOMFS) -* nose_ 0.11 or greater and pytest_ (optional, to run the tests) +* pytest_ (optional, to run the tests) * sphinx_ (optional, to build the documentation) Get the development sources @@ -128,7 +128,7 @@ module to see if everything is fine. It should look something like this:: >>> -To run the nibabel test suite, from the terminal run ``nosetests nibabel`` or +To run the nibabel test suite, from the terminal run ``pytest nibabel`` or ``python -c "import nibabel; nibabel.test()``. To run an extended test suite that validates ``nibabel`` for long-running and diff --git a/nibabel/__init__.py b/nibabel/__init__.py index 2d3428289c..f99e9e0b06 100644 --- a/nibabel/__init__.py +++ b/nibabel/__init__.py @@ -36,29 +36,6 @@ For more detailed information see the :ref:`manual`. """ -# Package-wide test setup and teardown -_test_states = { - # Numpy changed print options in 1.14; we can update docstrings and remove - # these when our minimum for building docs exceeds that - 'legacy_printopt': None, - } - -def setup_package(): - """ Set numpy print style to legacy="1.13" for newer versions of numpy """ - import numpy as np - from distutils.version import LooseVersion - if LooseVersion(np.__version__) >= LooseVersion('1.14'): - if _test_states.get('legacy_printopt') is None: - _test_states['legacy_printopt'] = np.get_printoptions().get('legacy') - np.set_printoptions(legacy="1.13") - -def teardown_package(): - """ Reset print options when tests finish """ - import numpy as np - if _test_states.get('legacy_printopt') is not None: - np.set_printoptions(legacy=_test_states.pop('legacy_printopt')) - - # module imports from . import analyze as ana from . import spm99analyze as spm99 @@ -92,13 +69,101 @@ def teardown_package(): from . import streamlines from . import viewers -from numpy.testing import Tester -test = Tester().test -bench = Tester().bench -del Tester - from .pkg_info import get_pkg_info as _get_pkg_info def get_info(): return _get_pkg_info(os.path.dirname(__file__)) + + +def test(label=None, verbose=1, extra_argv=None, + doctests=False, coverage=False, raise_warnings=None, + timer=False): + """ + Run tests for nibabel using pytest + + The protocol mimics the ``numpy.testing.NoseTester.test()``. + Not all features are currently implemented. + + Parameters + ---------- + label : None + Unused. + verbose: int, optional + Verbosity value for test outputs. Positive values increase verbosity, and + negative values decrease it. Default is 1. + extra_argv : list, optional + List with any extra arguments to pass to pytest. + doctests: bool, optional + If True, run doctests in module. Default is False. + coverage: bool, optional + If True, report coverage of NumPy code. Default is False. + (This requires the + `coverage module `_). + raise_warnings : None + Unused. + timer : False + Unused. + + Returns + ------- + code : ExitCode + Returns the result of running the tests as a ``pytest.ExitCode`` enum + """ + import pytest + args = [] + + if label is not None: + raise NotImplementedError("Labels cannot be set at present") + + verbose = int(verbose) + if verbose > 0: + args.append("-" + "v" * verbose) + elif verbose < 0: + args.append("-" + "q" * -verbose) + + if extra_argv: + args.extend(extra_argv) + if doctests: + args.append("--doctest-modules") + if coverage: + args.extend(["--cov", "nibabel"]) + if raise_warnings is not None: + raise NotImplementedError("Warning filters are not implemented") + if timer: + raise NotImplementedError("Timing is not implemented") + + args.extend(["--pyargs", "nibabel"]) + + return pytest.main(args=args) + + +def bench(label=None, verbose=1, extra_argv=None): + """ + Run benchmarks for nibabel using pytest + + The protocol mimics the ``numpy.testing.NoseTester.bench()``. + Not all features are currently implemented. + + Parameters + ---------- + label : None + Unused. + verbose: int, optional + Verbosity value for test outputs. Positive values increase verbosity, and + negative values decrease it. Default is 1. + extra_argv : list, optional + List with any extra arguments to pass to pytest. + + Returns + ------- + code : ExitCode + Returns the result of running the tests as a ``pytest.ExitCode`` enum + """ + from pkg_resources import resource_filename + config = resource_filename("nibabel", "benchmarks/pytest.benchmark.ini") + args = [] + if extra_argv is not None: + args.extend(extra_argv) + args.extend(["-c", config]) + return test(label, verbose, extra_argv=args) diff --git a/nibabel/benchmarks/bench_array_to_file.py b/nibabel/benchmarks/bench_array_to_file.py index 4908848685..ee0d25044d 100644 --- a/nibabel/benchmarks/bench_array_to_file.py +++ b/nibabel/benchmarks/bench_array_to_file.py @@ -5,13 +5,9 @@ import nibabel as nib nib.bench() -If you have doctests enabled by default in nose (with a noserc file or -environment variable), and you have a numpy version <= 1.6.1, this will also -run the doctests, let's hope they pass. +Run this benchmark with:: -Run this benchmark with: - - nosetests -s --match '(?:^|[\\b_\\.//-])[Bb]ench' /path/to/bench_load_save.py + pytest -c /benchmarks/pytest.benchmark.ini /benchmarks/bench_array_to_file.py """ import sys diff --git a/nibabel/benchmarks/bench_arrayproxy_slicing.py b/nibabel/benchmarks/bench_arrayproxy_slicing.py index 7fe79763d0..2ed9ec9ccd 100644 --- a/nibabel/benchmarks/bench_arrayproxy_slicing.py +++ b/nibabel/benchmarks/bench_arrayproxy_slicing.py @@ -5,13 +5,9 @@ import nibabel as nib nib.bench() -If you have doctests enabled by default in nose (with a noserc file or -environment variable), and you have a numpy version <= 1.6.1, this will also -run the doctests, let's hope they pass. +Run this benchmark with:: -Run this benchmark with: - - nosetests -s --match '(?:^|[\\b_\\.//-])[Bb]ench' /path/to/bench_arrayproxy_slicing.py + pytest -c /benchmarks/pytest.benchmark.ini /benchmarks/bench_arrayproxy_slicing.py """ from timeit import timeit diff --git a/nibabel/benchmarks/bench_fileslice.py b/nibabel/benchmarks/bench_fileslice.py index 764e0390b5..8763784dc6 100644 --- a/nibabel/benchmarks/bench_fileslice.py +++ b/nibabel/benchmarks/bench_fileslice.py @@ -3,13 +3,9 @@ import nibabel as nib nib.bench() -If you have doctests enabled by default in nose (with a noserc file or -environment variable), and you have a numpy version <= 1.6.1, this will also -run the doctests, let's hope they pass. +Run this benchmark with:: -Run this benchmark with: - - nosetests -s --match '(?:^|[\\b_\\.//-])[Bb]ench' /path/to/bench_fileslice.py + pytest -c /benchmarks/pytest.benchmark.ini /benchmarks/bench_fileslice.py """ import sys diff --git a/nibabel/benchmarks/bench_finite_range.py b/nibabel/benchmarks/bench_finite_range.py index 6aa9d9d861..1ca2bf95d0 100644 --- a/nibabel/benchmarks/bench_finite_range.py +++ b/nibabel/benchmarks/bench_finite_range.py @@ -5,13 +5,9 @@ import nibabel as nib nib.bench() -If you have doctests enabled by default in nose (with a noserc file or -environment variable), and you have a numpy version <= 1.6.1, this will also -run the doctests, let's hope they pass. +Run this benchmark with:: -Run this benchmark with: - - nosetests -s --match '(?:^|[\\b_\\.//-])[Bb]ench' /path/to/bench_finite_range + pytest -c /benchmarks/pytest.benchmark.ini /benchmarks/bench_finite_range.py """ import sys diff --git a/nibabel/benchmarks/bench_load_save.py b/nibabel/benchmarks/bench_load_save.py index 59198eac1a..46118df43e 100644 --- a/nibabel/benchmarks/bench_load_save.py +++ b/nibabel/benchmarks/bench_load_save.py @@ -5,13 +5,9 @@ import nibabel as nib nib.bench() -If you have doctests enabled by default in nose (with a noserc file or -environment variable), and you have a numpy version <= 1.6.1, this will also -run the doctests, let's hope they pass. +Run this benchmark with:: -Run this benchmark with: - - nosetests -s --match '(?:^|[\\b_\\.//-])[Bb]ench' /path/to/bench_load_save.py + pytest -c /benchmarks/pytest.benchmark.ini /benchmarks/bench_load_save.py """ import sys diff --git a/nibabel/benchmarks/bench_streamlines.py b/nibabel/benchmarks/bench_streamlines.py index fc1e39f8ad..5c49c9e177 100644 --- a/nibabel/benchmarks/bench_streamlines.py +++ b/nibabel/benchmarks/bench_streamlines.py @@ -5,13 +5,9 @@ import nibabel as nib nib.bench() -If you have doctests enabled by default in nose (with a noserc file or -environment variable), and you have a numpy version <= 1.6.1, this will also run -the doctests, let's hope they pass. +Run this benchmark with:: -Run this benchmark with: - - nosetests -s --match '(?:^|[\\b_\\.//-])[Bb]ench' /path/to/bench_streamlines.py + pytest -c /benchmarks/pytest.benchmark.ini /benchmarks/bench_streamlines.py """ import numpy as np diff --git a/nibabel/benchmarks/pytest.benchmark.ini b/nibabel/benchmarks/pytest.benchmark.ini new file mode 100644 index 0000000000..734e6c7d4c --- /dev/null +++ b/nibabel/benchmarks/pytest.benchmark.ini @@ -0,0 +1,4 @@ +[pytest] +python_files = bench_*.py +python_functions = bench_* +addopts = --capture=no diff --git a/nibabel/cifti2/tests/test_axes.py b/nibabel/cifti2/tests/test_axes.py index 56457187a2..3f6cb3a1a4 100644 --- a/nibabel/cifti2/tests/test_axes.py +++ b/nibabel/cifti2/tests/test_axes.py @@ -1,5 +1,5 @@ import numpy as np -from nose.tools import assert_raises +import pytest from .test_cifti2io_axes import check_rewrite import nibabel.cifti2.cifti2_axes as axes from copy import deepcopy @@ -157,18 +157,18 @@ def test_brain_models(): # break brain model bmt.affine = np.eye(4) - with assert_raises(ValueError): + with pytest.raises(ValueError): bmt.affine = np.eye(3) - with assert_raises(ValueError): + with pytest.raises(ValueError): bmt.affine = np.eye(4).flatten() bmt.volume_shape = (5, 3, 1) - with assert_raises(ValueError): + with pytest.raises(ValueError): bmt.volume_shape = (5., 3, 1) - with assert_raises(ValueError): + with pytest.raises(ValueError): bmt.volume_shape = (5, 3, 1, 4) - with assert_raises(IndexError): + with pytest.raises(IndexError): bmt['thalamus_left'] # Test the constructor @@ -176,22 +176,22 @@ def test_brain_models(): assert np.all(bm_vox.name == ['CIFTI_STRUCTURE_THALAMUS_LEFT'] * 5) assert np.array_equal(bm_vox.vertex, np.full(5, -1)) assert np.array_equal(bm_vox.voxel, np.full((5, 3), 1)) - with assert_raises(ValueError): + with pytest.raises(ValueError): # no volume shape axes.BrainModelAxis('thalamus_left', voxel=np.ones((5, 3), dtype=int), affine=np.eye(4)) - with assert_raises(ValueError): + with pytest.raises(ValueError): # no affine axes.BrainModelAxis('thalamus_left', voxel=np.ones((5, 3), dtype=int), volume_shape=(2, 3, 4)) - with assert_raises(ValueError): + with pytest.raises(ValueError): # incorrect name axes.BrainModelAxis('random_name', voxel=np.ones((5, 3), dtype=int), affine=np.eye(4), volume_shape=(2, 3, 4)) - with assert_raises(ValueError): + with pytest.raises(ValueError): # negative voxel indices axes.BrainModelAxis('thalamus_left', voxel=-np.ones((5, 3), dtype=int), affine=np.eye(4), volume_shape=(2, 3, 4)) - with assert_raises(ValueError): + with pytest.raises(ValueError): # no voxels or vertices axes.BrainModelAxis('thalamus_left', affine=np.eye(4), volume_shape=(2, 3, 4)) - with assert_raises(ValueError): + with pytest.raises(ValueError): # incorrect voxel shape axes.BrainModelAxis('thalamus_left', voxel=np.ones((5, 2), dtype=int), affine=np.eye(4), volume_shape=(2, 3, 4)) @@ -199,18 +199,18 @@ def test_brain_models(): assert np.array_equal(bm_vertex.name, ['CIFTI_STRUCTURE_CORTEX_LEFT'] * 5) assert np.array_equal(bm_vertex.vertex, np.full(5, 1)) assert np.array_equal(bm_vertex.voxel, np.full((5, 3), -1)) - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.BrainModelAxis('cortex_left', vertex=np.ones(5, dtype=int)) - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.BrainModelAxis('cortex_left', vertex=np.ones(5, dtype=int), nvertices={'cortex_right': 20}) - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.BrainModelAxis('cortex_left', vertex=-np.ones(5, dtype=int), nvertices={'cortex_left': 20}) # test from_mask errors - with assert_raises(ValueError): + with pytest.raises(ValueError): # affine should be 4x4 matrix axes.BrainModelAxis.from_mask(np.arange(5) > 2, affine=np.ones(5)) - with assert_raises(ValueError): + with pytest.raises(ValueError): # only 1D or 3D masks accepted axes.BrainModelAxis.from_mask(np.ones((5, 3))) @@ -226,27 +226,27 @@ def test_brain_models(): assert bm_added.volume_shape == bm_vox.volume_shape axes.ParcelsAxis.from_brain_models([('a', bm_vox), ('b', bm_vox)]) - with assert_raises(Exception): + with pytest.raises(Exception): bm_vox + get_label() bm_other_shape = axes.BrainModelAxis('thalamus_left', voxel=np.ones((5, 3), dtype=int), affine=np.eye(4), volume_shape=(4, 3, 4)) - with assert_raises(ValueError): + with pytest.raises(ValueError): bm_vox + bm_other_shape - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.ParcelsAxis.from_brain_models([('a', bm_vox), ('b', bm_other_shape)]) bm_other_affine = axes.BrainModelAxis('thalamus_left', voxel=np.ones((5, 3), dtype=int), affine=np.eye(4) * 2, volume_shape=(2, 3, 4)) - with assert_raises(ValueError): + with pytest.raises(ValueError): bm_vox + bm_other_affine - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.ParcelsAxis.from_brain_models([('a', bm_vox), ('b', bm_other_affine)]) bm_vertex = axes.BrainModelAxis('cortex_left', vertex=np.ones(5, dtype=int), nvertices={'cortex_left': 20}) bm_other_number = axes.BrainModelAxis('cortex_left', vertex=np.ones(5, dtype=int), nvertices={'cortex_left': 30}) - with assert_raises(ValueError): + with pytest.raises(ValueError): bm_vertex + bm_other_number - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.ParcelsAxis.from_brain_models([('a', bm_vertex), ('b', bm_other_number)]) # test equalities @@ -336,29 +336,29 @@ def test_parcels(): assert len(prc2[3:]['mixed'][1]) == 1 assert prc2[3:]['mixed'][1]['CIFTI_STRUCTURE_CORTEX_LEFT'].shape == (3, ) - with assert_raises(IndexError): + with pytest.raises(IndexError): prc['non_existent'] prc['surface'] - with assert_raises(IndexError): + with pytest.raises(IndexError): # parcel exists twice prc2['surface'] # break parcels prc.affine = np.eye(4) - with assert_raises(ValueError): + with pytest.raises(ValueError): prc.affine = np.eye(3) - with assert_raises(ValueError): + with pytest.raises(ValueError): prc.affine = np.eye(4).flatten() prc.volume_shape = (5, 3, 1) - with assert_raises(ValueError): + with pytest.raises(ValueError): prc.volume_shape = (5., 3, 1) - with assert_raises(ValueError): + with pytest.raises(ValueError): prc.volume_shape = (5, 3, 1, 4) # break adding of parcels - with assert_raises(Exception): + with pytest.raises(Exception): prc + get_label() prc = get_parcels() @@ -367,12 +367,12 @@ def test_parcels(): other_prc = get_parcels() other_prc.affine = np.eye(4) * 2 - with assert_raises(ValueError): + with pytest.raises(ValueError): prc + other_prc other_prc = get_parcels() other_prc.volume_shape = (20, 3, 4) - with assert_raises(ValueError): + with pytest.raises(ValueError): prc + other_prc # test parcel equalities @@ -396,13 +396,13 @@ def test_parcels(): prc_other = deepcopy(prc) prc_other.volume_shape = (10, 3, 4) assert prc != prc_other - with assert_raises(ValueError): + with pytest.raises(ValueError): prc + prc_other prc_other = deepcopy(prc) prc_other.nvertices['CIFTI_STRUCTURE_CORTEX_LEFT'] = 80 assert prc != prc_other - with assert_raises(ValueError): + with pytest.raises(ValueError): prc + prc_other prc_other = deepcopy(prc) @@ -434,7 +434,7 @@ def test_parcels(): volume_shape=(2, 3, 4), ) - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.ParcelsAxis( voxels=[np.ones((3, 2), dtype=int)], vertices=[{}], @@ -466,7 +466,7 @@ def test_scalar(): # test equalities assert sc != get_label() - with assert_raises(Exception): + with pytest.raises(Exception): sc + get_label() sc_other = deepcopy(sc) @@ -485,10 +485,10 @@ def test_scalar(): # test constructor assert axes.ScalarAxis(['scalar_name'], [{}]) == axes.ScalarAxis(['scalar_name']) - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.ScalarAxis([['scalar_name']]) # wrong shape - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.ScalarAxis(['scalar_name'], [{}, {}]) # wrong size @@ -514,7 +514,7 @@ def test_label(): # test equalities lab = get_label() assert lab != get_scalar() - with assert_raises(Exception): + with pytest.raises(Exception): lab + get_scalar() other_lab = deepcopy(lab) @@ -540,10 +540,10 @@ def test_label(): # test constructor assert axes.LabelAxis(['scalar_name'], [{}], [{}]) == axes.LabelAxis(['scalar_name'], [{}]) - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.LabelAxis([['scalar_name']], [{}]) # wrong shape - with assert_raises(ValueError): + with pytest.raises(ValueError): axes.LabelAxis(['scalar_name'], [{}, {}]) # wrong size @@ -558,7 +558,7 @@ def test_series(): assert sr[3].unit == 'HERTZ' sr[0].unit = 'hertz' assert sr[0].unit == 'HERTZ' - with assert_raises(ValueError): + with pytest.raises(ValueError): sr[0].unit = 'non_existent' sr = list(get_series()) @@ -570,11 +570,17 @@ def test_series(): assert ((sr[1] + sr[0] + sr[0]).time == np.arange(11) * 10 + 8).all() assert sr[1][2] == 28 assert sr[1][-2] == sr[1].time[-2] - assert_raises(ValueError, lambda: sr[0] + sr[2]) - assert_raises(ValueError, lambda: sr[2] + sr[1]) - assert_raises(ValueError, lambda: sr[0] + sr[3]) - assert_raises(ValueError, lambda: sr[3] + sr[1]) - assert_raises(ValueError, lambda: sr[3] + sr[2]) + + with pytest.raises(ValueError): + sr[0] + sr[2] + with pytest.raises(ValueError): + sr[2] + sr[1] + with pytest.raises(ValueError): + sr[0] + sr[3] + with pytest.raises(ValueError): + sr[3] + sr[1] + with pytest.raises(ValueError): + sr[3] + sr[2] # test slicing assert (sr[0][1:3].time == sr[0].time[1:3]).all() @@ -590,16 +596,16 @@ def test_series(): assert (sr[0][3:1:-1].time == sr[0].time[3:1:-1]).all() assert (sr[0][1:3:-1].time == sr[0].time[1:3:-1]).all() - with assert_raises(IndexError): + with pytest.raises(IndexError): assert sr[0][[0, 1]] - with assert_raises(IndexError): + with pytest.raises(IndexError): assert sr[0][20] - with assert_raises(IndexError): + with pytest.raises(IndexError): assert sr[0][-20] # test_equalities sr = next(get_series()) - with assert_raises(Exception): + with pytest.raises(Exception): sr + get_scalar() assert sr != sr[:2] assert sr == sr[:] diff --git a/nibabel/cifti2/tests/test_cifti2.py b/nibabel/cifti2/tests/test_cifti2.py index 8f85b62041..0d3d550a66 100644 --- a/nibabel/cifti2/tests/test_cifti2.py +++ b/nibabel/cifti2/tests/test_cifti2.py @@ -9,7 +9,7 @@ from nibabel.nifti2 import Nifti2Header from nibabel.cifti2.cifti2 import _float_01, _value_if_klass, Cifti2HeaderError -from nose.tools import assert_true, assert_equal, assert_raises, assert_is_none +import pytest from nibabel.tests.test_dataobj_images import TestDataobjAPI as _TDA @@ -27,244 +27,287 @@ def compare_xml_leaf(str1, str2): def test_value_if_klass(): - assert_equal(_value_if_klass(None, list), None) - assert_equal(_value_if_klass([1], list), [1]) - assert_raises(ValueError, _value_if_klass, 1, list) + assert _value_if_klass(None, list) is None + assert _value_if_klass([1], list) == [1] + with pytest.raises(ValueError): + _value_if_klass(1, list) def test_cifti2_metadata(): md = ci.Cifti2MetaData(metadata={'a': 'aval'}) - assert_equal(len(md), 1) - assert_equal(list(iter(md)), ['a']) - assert_equal(md['a'], 'aval') - assert_equal(md.data, dict([('a', 'aval')])) + assert len(md) == 1 + assert list(iter(md)) == ['a'] + assert md['a'] == 'aval' + assert md.data == dict([('a', 'aval')]) md = ci.Cifti2MetaData() - assert_equal(len(md), 0) - assert_equal(list(iter(md)), []) - assert_equal(md.data, {}) - assert_raises(ValueError, md.difference_update, None) + assert len(md) == 0 + assert list(iter(md)) == [] + assert md.data == {} + with pytest.raises(ValueError): + md.difference_update(None) md['a'] = 'aval' - assert_equal(md['a'], 'aval') - assert_equal(len(md), 1) - assert_equal(md.data, dict([('a', 'aval')])) + assert md['a'] == 'aval' + assert len(md) == 1 + assert md.data == dict([('a', 'aval')]) del md['a'] - assert_equal(len(md), 0) + assert len(md) == 0 metadata_test = [('a', 'aval'), ('b', 'bval')] md.update(metadata_test) - assert_equal(md.data, dict(metadata_test)) + assert md.data == dict(metadata_test) - assert_equal(list(iter(md)), list(iter(collections.OrderedDict(metadata_test)))) + assert list(iter(md)) == list(iter(collections.OrderedDict(metadata_test))) md.update({'a': 'aval', 'b': 'bval'}) - assert_equal(md.data, dict(metadata_test)) + assert md.data == dict(metadata_test) md.update({'a': 'aval', 'd': 'dval'}) - assert_equal(md.data, dict(metadata_test + [('d', 'dval')])) + assert md.data == dict(metadata_test + [('d', 'dval')]) md.difference_update({'a': 'aval', 'd': 'dval'}) - assert_equal(md.data, dict(metadata_test[1:])) + assert md.data == dict(metadata_test[1:]) - assert_raises(KeyError, md.difference_update, {'a': 'aval', 'd': 'dval'}) - assert_equal(md.to_xml().decode('utf-8'), - 'bbval') + with pytest.raises(KeyError): + md.difference_update({'a': 'aval', 'd': 'dval'}) + assert md.to_xml().decode('utf-8') == 'bbval' def test__float_01(): - assert_equal(_float_01(0), 0) - assert_equal(_float_01(1), 1) - assert_equal(_float_01('0'), 0) - assert_equal(_float_01('0.2'), 0.2) - assert_raises(ValueError, _float_01, 1.1) - assert_raises(ValueError, _float_01, -0.1) - assert_raises(ValueError, _float_01, 2) - assert_raises(ValueError, _float_01, -1) - assert_raises(ValueError, _float_01, 'foo') + assert _float_01(0) == 0 + assert _float_01(1) == 1 + assert _float_01('0') == 0 + assert _float_01('0.2') == 0.2 + with pytest.raises(ValueError): + _float_01(1.1) + with pytest.raises(ValueError): + _float_01(-0.1) + with pytest.raises(ValueError): + _float_01(2) + with pytest.raises(ValueError): + _float_01(-1) + with pytest.raises(ValueError): + _float_01('foo') def test_cifti2_labeltable(): lt = ci.Cifti2LabelTable() - assert_equal(len(lt), 0) - assert_raises(ci.Cifti2HeaderError, lt.to_xml) - assert_raises(ci.Cifti2HeaderError, lt._to_xml_element) + assert len(lt) == 0 + with pytest.raises(ci.Cifti2HeaderError): + lt.to_xml() + with pytest.raises(ci.Cifti2HeaderError): + lt._to_xml_element() + label = ci.Cifti2Label(label='Test', key=0) lt[0] = label - assert_equal(len(lt), 1) - assert_equal(dict(lt), {label.key: label}) + assert len(lt) == 1 + assert dict(lt) == {label.key: label} lt.clear() lt.append(label) - assert_equal(len(lt), 1) - assert_equal(dict(lt), {label.key: label}) + assert len(lt) == 1 + assert dict(lt) == {label.key: label} lt.clear() test_tuple = (label.label, label.red, label.green, label.blue, label.alpha) lt[label.key] = test_tuple - assert_equal(len(lt), 1) + assert len(lt) == 1 v = lt[label.key] - assert_equal( - (v.label, v.red, v.green, v.blue, v.alpha), - test_tuple - ) + assert (v.label, v.red, v.green, v.blue, v.alpha) == test_tuple + + with pytest.raises(ValueError): + lt[1] = label + + with pytest.raises(ValueError): + lt[0] = test_tuple[:-1] + + with pytest.raises(ValueError): + lt[0] = ('foo', 1.1, 0, 0, 1) + + with pytest.raises(ValueError): + lt[0] = ('foo', 1.0, -1, 0, 1) + + with pytest.raises(ValueError): + lt[0] = ('foo', 1.0, 0, -0.1, 1) - assert_raises(ValueError, lt.__setitem__, 1, label) - assert_raises(ValueError, lt.__setitem__, 0, test_tuple[:-1]) - assert_raises(ValueError, lt.__setitem__, 0, ('foo', 1.1, 0, 0, 1)) - assert_raises(ValueError, lt.__setitem__, 0, ('foo', 1.0, -1, 0, 1)) - assert_raises(ValueError, lt.__setitem__, 0, ('foo', 1.0, 0, -0.1, 1)) def test_cifti2_label(): lb = ci.Cifti2Label() lb.label = 'Test' lb.key = 0 - assert_equal(lb.rgba, (0, 0, 0, 0)) - assert_true(compare_xml_leaf( - lb.to_xml().decode('utf-8'), - "" - )) + assert lb.rgba == (0, 0, 0, 0) + assert compare_xml_leaf(lb.to_xml().decode('utf-8'), + "") lb.red = 0 lb.green = 0.1 lb.blue = 0.2 lb.alpha = 0.3 - assert_equal(lb.rgba, (0, 0.1, 0.2, 0.3)) + assert lb.rgba == (0, 0.1, 0.2, 0.3) - assert_true(compare_xml_leaf( - lb.to_xml().decode('utf-8'), - "" - )) + assert compare_xml_leaf(lb.to_xml().decode('utf-8'), + "") lb.red = 10 - assert_raises(ci.Cifti2HeaderError, lb.to_xml) + with pytest.raises(ci.Cifti2HeaderError): + lb.to_xml() lb.red = 0 lb.key = 'a' - assert_raises(ci.Cifti2HeaderError, lb.to_xml) + with pytest.raises(ci.Cifti2HeaderError): + lb.to_xml() lb.key = 0 def test_cifti2_parcel(): pl = ci.Cifti2Parcel() - assert_raises(ci.Cifti2HeaderError, pl.to_xml) - assert_raises(TypeError, pl.append_cifti_vertices, None) + with pytest.raises(ci.Cifti2HeaderError): + pl.to_xml() + + with pytest.raises(TypeError): + pl.append_cifti_vertices(None) + + with pytest.raises(ValueError): + ci.Cifti2Parcel(vertices=[1, 2, 3]) - assert_raises(ValueError, ci.Cifti2Parcel, **{'vertices': [1, 2, 3]}) pl = ci.Cifti2Parcel(name='region', voxel_indices_ijk=ci.Cifti2VoxelIndicesIJK([[1, 2, 3]]), vertices=[ci.Cifti2Vertices([0, 1, 2])]) pl.pop_cifti2_vertices(0) - assert_equal(len(pl.vertices), 0) - assert_equal( - pl.to_xml().decode('utf-8'), - '1 2 3' - ) + + assert len(pl.vertices) == 0 + assert pl.to_xml().decode('utf-8') == '1 2 3' def test_cifti2_vertices(): vs = ci.Cifti2Vertices() - assert_raises(ci.Cifti2HeaderError, vs.to_xml) + with pytest.raises(ci.Cifti2HeaderError): + vs.to_xml() + vs.brain_structure = 'CIFTI_STRUCTURE_OTHER' - assert_equal( - vs.to_xml().decode('utf-8'), - '' - ) - assert_equal(len(vs), 0) + + assert vs.to_xml().decode('utf-8') == '' + + assert len(vs) == 0 vs.extend(np.array([0, 1, 2])) - assert_equal(len(vs), 3) - assert_raises(ValueError, vs.__setitem__, 1, 'a') - assert_raises(ValueError, vs.insert, 1, 'a') - assert_equal( - vs.to_xml().decode('utf-8'), - '0 1 2' - ) + assert len(vs) == 3 + with pytest.raises(ValueError): + vs[1] = 'a' + with pytest.raises(ValueError): + vs.insert(1, 'a') + + assert vs.to_xml().decode('utf-8') == '0 1 2' vs[0] = 10 - assert_equal(vs[0], 10) - assert_equal(len(vs), 3) + assert vs[0] == 10 + assert len(vs) == 3 vs = ci.Cifti2Vertices(vertices=[0, 1, 2]) - assert_equal(len(vs), 3) + assert len(vs) == 3 def test_cifti2_transformationmatrixvoxelindicesijktoxyz(): tr = ci.Cifti2TransformationMatrixVoxelIndicesIJKtoXYZ() - assert_raises(ci.Cifti2HeaderError, tr.to_xml) + with pytest.raises(ci.Cifti2HeaderError): + tr.to_xml() def test_cifti2_surface(): s = ci.Cifti2Surface() - assert_raises(ci.Cifti2HeaderError, s.to_xml) + with pytest.raises(ci.Cifti2HeaderError): + s.to_xml() def test_cifti2_volume(): vo = ci.Cifti2Volume() - assert_raises(ci.Cifti2HeaderError, vo.to_xml) + with pytest.raises(ci.Cifti2HeaderError): + vo.to_xml() def test_cifti2_vertexindices(): vi = ci.Cifti2VertexIndices() - assert_equal(len(vi), 0) - assert_raises(ci.Cifti2HeaderError, vi.to_xml) + assert len(vi) == 0 + with pytest.raises(ci.Cifti2HeaderError): + vi.to_xml() vi.extend(np.array([0, 1, 2])) - assert_equal(len(vi), 3) - assert_equal( - vi.to_xml().decode('utf-8'), - '0 1 2' - ) - assert_raises(ValueError, vi.__setitem__, 0, 'a') + assert len(vi) == 3 + assert vi.to_xml().decode('utf-8') == '0 1 2' + + with pytest.raises(ValueError): + vi[0] = 'a' + vi[0] = 10 - assert_equal(vi[0], 10) - assert_equal(len(vi), 3) + assert vi[0] == 10 + assert len(vi) == 3 def test_cifti2_voxelindicesijk(): vi = ci.Cifti2VoxelIndicesIJK() - assert_raises(ci.Cifti2HeaderError, vi.to_xml) + with pytest.raises(ci.Cifti2HeaderError): + vi.to_xml() vi = ci.Cifti2VoxelIndicesIJK() - assert_equal(len(vi), 0) - assert_raises(ci.Cifti2HeaderError, vi.to_xml) + assert len(vi) == 0 + + with pytest.raises(ci.Cifti2HeaderError): + vi.to_xml() vi.extend(np.array([[0, 1, 2]])) - assert_equal(len(vi), 1) - assert_equal(vi[0], [0, 1, 2]) + + assert len(vi) == 1 + assert vi[0] == [0, 1, 2] vi.append([3, 4, 5]) - assert_equal(len(vi), 2) + assert len(vi) == 2 vi.append([6, 7, 8]) - assert_equal(len(vi), 3) + assert len(vi) == 3 del vi[-1] - assert_equal(len(vi), 2) + assert len(vi) == 2 - assert_equal(vi[1], [3, 4, 5]) + assert vi[1] == [3, 4, 5] vi[1] = [3, 4, 6] - assert_equal(vi[1], [3, 4, 6]) - assert_raises(ValueError, vi.__setitem__, 'a', [1, 2, 3]) - assert_raises(TypeError, vi.__setitem__, [1, 2], [1, 2, 3]) - assert_raises(ValueError, vi.__setitem__, 1, [2, 3]) - assert_equal(vi[1, 1], 4) - assert_raises(ValueError, vi.__setitem__, [1, 1], 'a') - assert_equal(vi[0, 1:], [1, 2]) + assert vi[1] == [3, 4, 6] + with pytest.raises(ValueError): + vi['a'] = [1, 2, 3] + + with pytest.raises(TypeError): + vi[[1, 2]] = [1, 2, 3] + + with pytest.raises(ValueError): + vi[1] = [2, 3] + + assert vi[1, 1] == 4 + + with pytest.raises(ValueError): + vi[[1, 1]] = 'a' + + assert vi[0, 1:] == [1, 2] vi[0, 1] = 10 - assert_equal(vi[0, 1], 10) + assert vi[0, 1] == 10 vi[0, 1] = 1 #test for vi[:, 0] and other slices - assert_raises(NotImplementedError, vi.__getitem__, (slice(None), 0)) - assert_raises(NotImplementedError, vi.__setitem__, (slice(None), 0), 0) - assert_raises(NotImplementedError, vi.__delitem__, (slice(None), 0)) - assert_raises(ValueError, vi.__getitem__, (0, 0, 0)) - assert_raises(ValueError, vi.__setitem__, (0, 0, 0), 0) - - assert_equal( - vi.to_xml().decode('utf-8'), - '0 1 2\n3 4 6' - ) - assert_raises(TypeError, ci.Cifti2VoxelIndicesIJK, [0, 1]) + with pytest.raises(NotImplementedError): + vi[:, 0] + with pytest.raises(NotImplementedError): + vi[:, 0] = 0 + with pytest.raises(NotImplementedError): + # Don't know how to use remove with slice + del vi[:, 0] + with pytest.raises(ValueError): + vi[0, 0, 0] + + with pytest.raises(ValueError): + vi[0, 0, 0] = 0 + + assert vi.to_xml().decode('utf-8') == '0 1 2\n3 4 6' + + with pytest.raises(TypeError): + ci.Cifti2VoxelIndicesIJK([0, 1]) + vi = ci.Cifti2VoxelIndicesIJK([[1, 2, 3]]) - assert_equal(len(vi), 1) + assert len(vi) == 1 def test_matrixindicesmap(): @@ -273,59 +316,77 @@ def test_matrixindicesmap(): volume2 = ci.Cifti2Volume() parcel = ci.Cifti2Parcel() - assert_is_none(mim.volume) + assert mim.volume is None mim.append(volume) mim.append(parcel) - assert_equal(mim.volume, volume) - assert_raises(ci.Cifti2HeaderError, mim.insert, 0, volume) - assert_raises(ci.Cifti2HeaderError, mim.__setitem__, 1, volume) + assert mim.volume == volume + with pytest.raises(ci.Cifti2HeaderError): + mim.insert(0, volume) + + with pytest.raises(ci.Cifti2HeaderError): + mim[1] = volume mim[0] = volume2 - assert_equal(mim.volume, volume2) + assert mim.volume == volume2 del mim.volume - assert_is_none(mim.volume) - assert_raises(ValueError, delattr, mim, 'volume') + assert mim.volume is None + with pytest.raises(ValueError): + del mim.volume mim.volume = volume - assert_equal(mim.volume, volume) + assert mim.volume == volume mim.volume = volume2 - assert_equal(mim.volume, volume2) + assert mim.volume == volume2 - assert_raises(ValueError, setattr, mim, 'volume', parcel) + with pytest.raises(ValueError): + mim.volume = parcel def test_matrix(): m = ci.Cifti2Matrix() - assert_raises(TypeError, m, setattr, 'metadata', ci.Cifti2Parcel()) - assert_raises(TypeError, m.__setitem__, 0, ci.Cifti2Parcel()) - assert_raises(TypeError, m.insert, 0, ci.Cifti2Parcel()) + + with pytest.raises(ValueError): + m.metadata = ci.Cifti2Parcel() + + with pytest.raises(TypeError): + m[0] = ci.Cifti2Parcel() + + with pytest.raises(TypeError): + m.insert(0, ci.Cifti2Parcel()) mim_none = ci.Cifti2MatrixIndicesMap(None, 'CIFTI_INDEX_TYPE_LABELS') mim_0 = ci.Cifti2MatrixIndicesMap(0, 'CIFTI_INDEX_TYPE_LABELS') mim_1 = ci.Cifti2MatrixIndicesMap(1, 'CIFTI_INDEX_TYPE_LABELS') mim_01 = ci.Cifti2MatrixIndicesMap([0, 1], 'CIFTI_INDEX_TYPE_LABELS') - assert_raises(ci.Cifti2HeaderError, m.insert, 0, mim_none) - assert_equal(m.mapped_indices, []) + with pytest.raises(ci.Cifti2HeaderError): + m.insert(0, mim_none) + + assert m.mapped_indices == [] h = ci.Cifti2Header(matrix=m) - assert_equal(m.mapped_indices, []) + assert m.mapped_indices == [] m.insert(0, mim_0) - assert_equal(h.mapped_indices, [0]) - assert_equal(h.number_of_mapped_indices, 1) - assert_raises(ci.Cifti2HeaderError, m.insert, 0, mim_0) - assert_raises(ci.Cifti2HeaderError, m.insert, 0, mim_01) + assert h.mapped_indices == [0] + assert h.number_of_mapped_indices == 1 + with pytest.raises(ci.Cifti2HeaderError): + m.insert(0, mim_0) + + with pytest.raises(ci.Cifti2HeaderError): + m.insert(0, mim_01) + m[0] = mim_1 - assert_equal(list(m.mapped_indices), [1]) + assert list(m.mapped_indices) == [1] m.insert(0, mim_0) - assert_equal(list(sorted(m.mapped_indices)), [0, 1]) - assert_equal(h.number_of_mapped_indices, 2) - assert_equal(h.get_index_map(0), mim_0) - assert_equal(h.get_index_map(1), mim_1) - assert_raises(ci.Cifti2HeaderError, h.get_index_map, 2) + assert list(sorted(m.mapped_indices)) == [0, 1] + assert h.number_of_mapped_indices == 2 + assert h.get_index_map(0) == mim_0 + assert h.get_index_map(1) == mim_1 + with pytest.raises(ci.Cifti2HeaderError): + h.get_index_map(2) def test_underscoring(): @@ -342,7 +403,7 @@ def test_underscoring(): ) for camel, underscored in pairs: - assert_equal(ci.cifti2._underscore(camel), underscored) + assert ci.cifti2._underscore(camel) == underscored class TestCifti2ImageAPI(_TDA): diff --git a/nibabel/cifti2/tests/test_cifti2io_header.py b/nibabel/cifti2/tests/test_cifti2io_header.py index b8cbd05a32..0fef5ccd78 100644 --- a/nibabel/cifti2/tests/test_cifti2io_header.py +++ b/nibabel/cifti2/tests/test_cifti2io_header.py @@ -21,7 +21,7 @@ from nibabel.tests.test_nifti2 import TestNifti2SingleHeader from numpy.testing import assert_array_almost_equal -from nose.tools import (assert_true, assert_equal, assert_raises) +import pytest NIBABEL_TEST_DATA = pjoin(dirname(nib.__file__), 'tests', 'data') NIFTI2_DATA = pjoin(NIBABEL_TEST_DATA, 'example_nifti2.nii.gz') @@ -46,35 +46,36 @@ def test_read_nifti2(): filemap = ci.Cifti2Image.make_file_map() for k in filemap: filemap[k].fileobj = io.open(NIFTI2_DATA) - assert_raises(ValueError, ci.Cifti2Image.from_file_map, filemap) + with pytest.raises(ValueError): + ci.Cifti2Image.from_file_map(filemap) @needs_nibabel_data('nitest-cifti2') def test_read_internal(): img2 = ci.load(DATA_FILE6) - assert_true(isinstance(img2.header, ci.Cifti2Header)) - assert_equal(img2.shape, (1, 91282)) + assert isinstance(img2.header, ci.Cifti2Header) + assert img2.shape == (1, 91282) @needs_nibabel_data('nitest-cifti2') def test_read_and_proxies(): img2 = nib.load(DATA_FILE6) - assert_true(isinstance(img2.header, ci.Cifti2Header)) - assert_equal(img2.shape, (1, 91282)) + assert isinstance(img2.header, ci.Cifti2Header) + assert img2.shape == (1, 91282) # While we cannot reshape arrayproxies, all images are in-memory - assert_true(not img2.in_memory) + assert not img2.in_memory data = img2.get_fdata() - assert_true(data is not img2.dataobj) + assert data is not img2.dataobj # Uncaching has no effect, images are always array images img2.uncache() - assert_true(data is not img2.get_fdata()) + assert data is not img2.get_fdata() @needs_nibabel_data('nitest-cifti2') def test_version(): for i, dat in enumerate(datafiles): img = nib.load(dat) - assert_equal(LooseVersion(img.header.version), LooseVersion('2')) + assert LooseVersion(img.header.version) == LooseVersion('2') @needs_nibabel_data('nitest-cifti2') @@ -84,8 +85,7 @@ def test_readwritedata(): img = ci.load(name) ci.save(img, 'test.nii') img2 = ci.load('test.nii') - assert_equal(len(img.header.matrix), - len(img2.header.matrix)) + assert len(img.header.matrix) == len(img2.header.matrix) # Order should be preserved in load/save for mim1, mim2 in zip(img.header.matrix, img2.header.matrix): @@ -93,14 +93,14 @@ def test_readwritedata(): if isinstance(m_, ci.Cifti2NamedMap)] named_maps2 = [m_ for m_ in mim2 if isinstance(m_, ci.Cifti2NamedMap)] - assert_equal(len(named_maps1), len(named_maps2)) + assert len(named_maps1) == len(named_maps2) for map1, map2 in zip(named_maps1, named_maps2): - assert_equal(map1.map_name, map2.map_name) + assert map1.map_name == map2.map_name if map1.label_table is None: - assert_true(map2.label_table is None) + assert map2.label_table is None else: - assert_equal(len(map1.label_table), - len(map2.label_table)) + assert len(map1.label_table) == len(map2.label_table) + assert_array_almost_equal(img.dataobj, img2.dataobj) @@ -111,8 +111,7 @@ def test_nibabel_readwritedata(): img = nib.load(name) nib.save(img, 'test.nii') img2 = nib.load('test.nii') - assert_equal(len(img.header.matrix), - len(img2.header.matrix)) + assert len(img.header.matrix) == len(img2.header.matrix) # Order should be preserved in load/save for mim1, mim2 in zip(img.header.matrix, img2.header.matrix): @@ -120,14 +119,13 @@ def test_nibabel_readwritedata(): if isinstance(m_, ci.Cifti2NamedMap)] named_maps2 = [m_ for m_ in mim2 if isinstance(m_, ci.Cifti2NamedMap)] - assert_equal(len(named_maps1), len(named_maps2)) + assert len(named_maps1) == len(named_maps2) for map1, map2 in zip(named_maps1, named_maps2): - assert_equal(map1.map_name, map2.map_name) + assert map1.map_name == map2.map_name if map1.label_table is None: - assert_true(map2.label_table is None) + assert map2.label_table is None else: - assert_equal(len(map1.label_table), - len(map2.label_table)) + assert len(map1.label_table) == len(map2.label_table) assert_array_almost_equal(img.dataobj, img2.dataobj) @@ -152,10 +150,10 @@ def test_cifti2types(): for name in datafiles: hdr = ci.load(name).header # Matrix and MetaData aren't conditional, so don't bother counting - assert_true(isinstance(hdr.matrix, ci.Cifti2Matrix)) - assert_true(isinstance(hdr.matrix.metadata, ci.Cifti2MetaData)) + assert isinstance(hdr.matrix, ci.Cifti2Matrix) + assert isinstance(hdr.matrix.metadata, ci.Cifti2MetaData) for mim in hdr.matrix: - assert_true(isinstance(mim, ci.Cifti2MatrixIndicesMap)) + assert isinstance(mim, ci.Cifti2MatrixIndicesMap) counter[ci.Cifti2MatrixIndicesMap] += 1 for map_ in mim: print(map_) @@ -168,21 +166,20 @@ def test_cifti2types(): counter[ci.Cifti2VoxelIndicesIJK] += 1 elif isinstance(map_, ci.Cifti2NamedMap): counter[ci.Cifti2NamedMap] += 1 - assert_true(isinstance(map_.metadata, ci.Cifti2MetaData)) + assert isinstance(map_.metadata, ci.Cifti2MetaData) if isinstance(map_.label_table, ci.Cifti2LabelTable): counter[ci.Cifti2LabelTable] += 1 for label in map_.label_table: - assert_true(isinstance(map_.label_table[label], - ci.Cifti2Label)) + assert isinstance(map_.label_table[label], ci.Cifti2Label) counter[ci.Cifti2Label] += 1 elif isinstance(map_, ci.Cifti2Parcel): counter[ci.Cifti2Parcel] += 1 if isinstance(map_.voxel_indices_ijk, ci.Cifti2VoxelIndicesIJK): counter[ci.Cifti2VoxelIndicesIJK] += 1 - assert_true(isinstance(map_.vertices, list)) + assert isinstance(map_.vertices, list) for vtcs in map_.vertices: - assert_true(isinstance(vtcs, ci.Cifti2Vertices)) + assert isinstance(vtcs, ci.Cifti2Vertices) counter[ci.Cifti2Vertices] += 1 elif isinstance(map_, ci.Cifti2Surface): counter[ci.Cifti2Surface] += 1 @@ -192,19 +189,14 @@ def test_cifti2types(): ci.Cifti2TransformationMatrixVoxelIndicesIJKtoXYZ): counter[ci.Cifti2TransformationMatrixVoxelIndicesIJKtoXYZ] += 1 - assert_equal(list(mim.named_maps), - [m_ for m_ in mim if isinstance(m_, ci.Cifti2NamedMap)]) - assert_equal(list(mim.surfaces), - [m_ for m_ in mim if isinstance(m_, ci.Cifti2Surface)]) - assert_equal(list(mim.parcels), - [m_ for m_ in mim if isinstance(m_, ci.Cifti2Parcel)]) - assert_equal(list(mim.brain_models), - [m_ for m_ in mim if isinstance(m_, ci.Cifti2BrainModel)]) - assert_equal([mim.volume] if mim.volume else [], - [m_ for m_ in mim if isinstance(m_, ci.Cifti2Volume)]) + assert list(mim.named_maps) == [m_ for m_ in mim if isinstance(m_, ci.Cifti2NamedMap)] + assert list(mim.surfaces) == [m_ for m_ in mim if isinstance(m_, ci.Cifti2Surface)] + assert list(mim.parcels) == [m_ for m_ in mim if isinstance(m_, ci.Cifti2Parcel)] + assert list(mim.brain_models) == [m_ for m_ in mim if isinstance(m_, ci.Cifti2BrainModel)] + assert ([mim.volume] if mim.volume else []) == [m_ for m_ in mim if isinstance(m_, ci.Cifti2Volume)] for klass, count in counter.items(): - assert_true(count > 0, "No exercise of " + klass.__name__) + assert count > 0, "No exercise of " + klass.__name__ @needs_nibabel_data('nitest-cifti2') @@ -237,34 +229,34 @@ def test_read_geometry(): ('CIFTI_STRUCTURE_THALAMUS_RIGHT', 1248, [32, 47, 34], [38, 55, 46])] current_index = 0 for from_file, expected in zip(geometry_mapping.brain_models, expected_geometry): - assert_true(from_file.model_type in ("CIFTI_MODEL_TYPE_SURFACE", "CIFTI_MODEL_TYPE_VOXELS")) - assert_equal(from_file.brain_structure, expected[0]) - assert_equal(from_file.index_offset, current_index) - assert_equal(from_file.index_count, expected[1]) + assert from_file.model_type in ("CIFTI_MODEL_TYPE_SURFACE", "CIFTI_MODEL_TYPE_VOXELS") + assert from_file.brain_structure == expected[0] + assert from_file.index_offset == current_index + assert from_file.index_count == expected[1] current_index += from_file.index_count if from_file.model_type == 'CIFTI_MODEL_TYPE_SURFACE': - assert_equal(from_file.voxel_indices_ijk, None) - assert_equal(len(from_file.vertex_indices), expected[1]) - assert_equal(from_file.vertex_indices[0], expected[2]) - assert_equal(from_file.vertex_indices[-1], expected[3]) - assert_equal(from_file.surface_number_of_vertices, 32492) + assert from_file.voxel_indices_ijk is None + assert len(from_file.vertex_indices) == expected[1] + assert from_file.vertex_indices[0] == expected[2] + assert from_file.vertex_indices[-1] == expected[3] + assert from_file.surface_number_of_vertices == 32492 else: - assert_equal(from_file.vertex_indices, None) - assert_equal(from_file.surface_number_of_vertices, None) - assert_equal(len(from_file.voxel_indices_ijk), expected[1]) - assert_equal(from_file.voxel_indices_ijk[0], expected[2]) - assert_equal(from_file.voxel_indices_ijk[-1], expected[3]) - assert_equal(current_index, img.shape[1]) + assert from_file.vertex_indices is None + assert from_file.surface_number_of_vertices is None + assert len(from_file.voxel_indices_ijk) == expected[1] + assert from_file.voxel_indices_ijk[0] == expected[2] + assert from_file.voxel_indices_ijk[-1] == expected[3] + assert current_index == img.shape[1] expected_affine = [[-2, 0, 0, 90], [ 0, 2, 0, -126], [ 0, 0, 2, -72], [ 0, 0, 0, 1]] expected_dimensions = (91, 109, 91) - assert_true((geometry_mapping.volume.transformation_matrix_voxel_indices_ijk_to_xyz.matrix == - expected_affine).all()) - assert_equal(geometry_mapping.volume.volume_dimensions, expected_dimensions) + assert (geometry_mapping.volume.transformation_matrix_voxel_indices_ijk_to_xyz.matrix == + expected_affine).all() + assert geometry_mapping.volume.volume_dimensions == expected_dimensions @needs_nibabel_data('nitest-cifti2') @@ -327,18 +319,18 @@ def test_read_parcels(): ('ER_FRB08', ((103, 21514, 26470), (103, 21514, 26470))), ('13b_OFP03', ((60, 21042, 21194), (71, 21040, 21216)))] - assert_equal(img.shape[1], len(expected_parcels)) - assert_equal(len(list(parcel_mapping.parcels)), len(expected_parcels)) + assert img.shape[1] == len(expected_parcels) + assert len(list(parcel_mapping.parcels)) == len(expected_parcels) for (name, expected_surfaces), parcel in zip(expected_parcels, parcel_mapping.parcels): - assert_equal(parcel.name, name) - assert_equal(len(parcel.vertices), 2) + assert parcel.name == name + assert len(parcel.vertices) == 2 for vertices, orientation, (length, first_element, last_element) in zip(parcel.vertices, ('LEFT', 'RIGHT'), expected_surfaces): - assert_equal(len(vertices), length) - assert_equal(vertices[0], first_element) - assert_equal(vertices[-1], last_element) - assert_equal(vertices.brain_structure, 'CIFTI_STRUCTURE_CORTEX_%s' % orientation) + assert len(vertices) == length + assert vertices[0] == first_element + assert vertices[-1] == last_element + assert vertices.brain_structure == 'CIFTI_STRUCTURE_CORTEX_%s' % orientation @needs_nibabel_data('nitest-cifti2') @@ -347,31 +339,31 @@ def test_read_scalar(): scalar_mapping = img.header.matrix.get_index_map(0) expected_names = ('MyelinMap_BC_decurv', 'corrThickness') - assert_equal(img.shape[0], len(expected_names)) - assert_equal(len(list(scalar_mapping.named_maps)), len(expected_names)) + assert img.shape[0] == len(expected_names) + assert len(list(scalar_mapping.named_maps)) == len(expected_names) expected_meta = [('PaletteColorMapping', '\n = LooseVersion("1.14"): + legacy_printopt = np.get_printoptions().get("legacy") + np.set_printoptions(legacy="1.13") + yield + np.set_printoptions(legacy=legacy_printopt) + else: + yield diff --git a/nibabel/externals/tests/test_netcdf.py b/nibabel/externals/tests/test_netcdf.py index 289e6791c1..f85393be4e 100644 --- a/nibabel/externals/tests/test_netcdf.py +++ b/nibabel/externals/tests/test_netcdf.py @@ -2,20 +2,15 @@ import os from os.path import join as pjoin, dirname -import shutil -import tempfile -import time -import sys from io import BytesIO from glob import glob from contextlib import contextmanager import numpy as np -from numpy.testing import dec, assert_ -from ..netcdf import netcdf_file +import pytest -from nose.tools import assert_true, assert_false, assert_equal, assert_raises +from ..netcdf import netcdf_file TEST_DATA_PATH = pjoin(dirname(__file__), 'data') @@ -36,54 +31,41 @@ def make_simple(*args, **kwargs): f.close() -def gen_for_simple(ncfileobj): - ''' Generator for example fileobj tests ''' - yield assert_equal, ncfileobj.history, b'Created for a test' +def assert_simple_truths(ncfileobj): + assert ncfileobj.history == b'Created for a test' time = ncfileobj.variables['time'] - yield assert_equal, time.units, b'days since 2008-01-01' - yield assert_equal, time.shape, (N_EG_ELS,) - yield assert_equal, time[-1], N_EG_ELS-1 - - -def test_read_write_files(): - # test round trip for example file - cwd = os.getcwd() - try: - tmpdir = tempfile.mkdtemp() - os.chdir(tmpdir) - with make_simple('simple.nc', 'w') as f: - pass - # To read the NetCDF file we just created:: - with netcdf_file('simple.nc') as f: - # Using mmap is the default - yield assert_true, f.use_mmap - for testargs in gen_for_simple(f): - yield testargs - - # Now without mmap - with netcdf_file('simple.nc', mmap=False) as f: - # Using mmap is the default - yield assert_false, f.use_mmap - for testargs in gen_for_simple(f): - yield testargs - - # To read the NetCDF file we just created, as file object, no - # mmap. When n * n_bytes(var_type) is not divisible by 4, this - # raised an error in pupynere 1.0.12 and scipy rev 5893, because - # calculated vsize was rounding up in units of 4 - see - # https://www.unidata.ucar.edu/software/netcdf/docs/netcdf.html - fobj = open('simple.nc', 'rb') - with netcdf_file(fobj) as f: - # by default, don't use mmap for file-like - yield assert_false, f.use_mmap - for testargs in gen_for_simple(f): - yield testargs - except: - os.chdir(cwd) - shutil.rmtree(tmpdir) - raise - os.chdir(cwd) - shutil.rmtree(tmpdir) + assert time.units == b'days since 2008-01-01' + assert time.shape == (N_EG_ELS,) + assert time[-1] == N_EG_ELS - 1 + + +def test_read_write_files(tmp_path): + fname = str(tmp_path / 'simple.nc') + + with make_simple(fname, 'w') as f: + pass + # To read the NetCDF file we just created:: + with netcdf_file(fname) as f: + # Using mmap is the default + assert f.use_mmap + assert_simple_truths(f) + + # Now without mmap + with netcdf_file(fname, mmap=False) as f: + # Using mmap is the default + assert not f.use_mmap + assert_simple_truths(f) + + # To read the NetCDF file we just created, as file object, no + # mmap. When n * n_bytes(var_type) is not divisible by 4, this + # raised an error in pupynere 1.0.12 and scipy rev 5893, because + # calculated vsize was rounding up in units of 4 - see + # https://www.unidata.ucar.edu/software/netcdf/docs/netcdf.html + fobj = open(fname, 'rb') + with netcdf_file(fobj) as f: + # by default, don't use mmap for file-like + assert not f.use_mmap + assert_simple_truths(f) def test_read_write_sio(): @@ -93,12 +75,12 @@ def test_read_write_sio(): eg_sio2 = BytesIO(str_val) with netcdf_file(eg_sio2) as f2: - for testargs in gen_for_simple(f2): - yield testargs + assert_simple_truths(f2) # Test that error is raised if attempting mmap for sio eg_sio3 = BytesIO(str_val) - yield assert_raises, ValueError, netcdf_file, eg_sio3, 'r', True + with pytest.raises(ValueError): + netcdf_file(eg_sio3, 'r', True) # Test 64-bit offset write / read eg_sio_64 = BytesIO() with make_simple(eg_sio_64, 'w', version=2) as f_64: @@ -106,15 +88,13 @@ def test_read_write_sio(): eg_sio_64 = BytesIO(str_val) with netcdf_file(eg_sio_64) as f_64: - for testargs in gen_for_simple(f_64): - yield testargs - yield assert_equal, f_64.version_byte, 2 + assert_simple_truths(f_64) + assert f_64.version_byte == 2 # also when version 2 explicitly specified eg_sio_64 = BytesIO(str_val) with netcdf_file(eg_sio_64, version=2) as f_64: - for testargs in gen_for_simple(f_64): - yield testargs - yield assert_equal, f_64.version_byte, 2 + assert_simple_truths(f_64) + assert f_64.version_byte == 2 def test_read_example_data(): @@ -134,7 +114,8 @@ def test_itemset_no_segfault_on_readonly(): time_var = f.variables['time'] # time_var.assignValue(42) should raise a RuntimeError--not seg. fault! - assert_raises(RuntimeError, time_var.assignValue, 42) + with pytest.raises(RuntimeError): + time_var.assignValue(42) def test_write_invalid_dtype(): @@ -147,14 +128,14 @@ def test_write_invalid_dtype(): with netcdf_file(BytesIO(), 'w') as f: f.createDimension('time', N_EG_ELS) for dt in dtypes: - yield assert_raises, ValueError, \ - f.createVariable, 'time', dt, ('time',) + with pytest.raises(ValueError): + f.createVariable('time', dt, ('time',)) def test_flush_rewind(): stream = BytesIO() with make_simple(stream, mode='w') as f: - x = f.createDimension('x',4) + x = f.createDimension('x', 4) v = f.createVariable('v', 'i2', ['x']) v[:] = 1 f.flush() @@ -162,7 +143,7 @@ def test_flush_rewind(): f.flush() len_double = len(stream.getvalue()) - assert_(len_single == len_double) + assert len_single == len_double def test_dtype_specifiers(): @@ -192,8 +173,8 @@ def test_ticket_1720(): io = BytesIO(contents) with netcdf_file(io, 'r') as f: - assert_equal(f.history, b'Created for a test') + assert f.history == b'Created for a test' float_var = f.variables['float_var'] - assert_equal(float_var.units, b'metres') - assert_equal(float_var.shape, (10,)) - assert_(np.allclose(float_var[:], items)) + assert float_var.units == b'metres' + assert float_var.shape == (10,) + assert np.allclose(float_var[:], items) diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index fc926ee2af..b2401a11ab 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -6,12 +6,12 @@ import hashlib import warnings - from ...tmpdirs import InTemporaryDirectory -from nose.tools import assert_true +import unittest +import pytest import numpy as np -from numpy.testing import assert_equal, assert_raises, dec, assert_allclose, assert_array_equal +from numpy.testing import assert_allclose, assert_array_equal from .. import (read_geometry, read_morph_data, read_annot, read_label, write_geometry, write_morph_data, write_annot) @@ -35,10 +35,8 @@ data_path = pjoin(nib_data, 'nitest-freesurfer', DATA_SDIR) have_freesurfer = isdir(data_path) -freesurfer_test = dec.skipif( - not have_freesurfer, - 'cannot find freesurfer {0} directory'.format(DATA_SDIR)) - +freesurfer_test = unittest.skipUnless(have_freesurfer, + 'cannot find freesurfer {0} directory'.format(DATA_SDIR)) def _hash_file_content(fname): hasher = hashlib.md5() @@ -53,19 +51,18 @@ def test_geometry(): """Test IO of .surf""" surf_path = pjoin(data_path, "surf", "%s.%s" % ("lh", "inflated")) coords, faces = read_geometry(surf_path) - assert_equal(0, faces.min()) - assert_equal(coords.shape[0], faces.max() + 1) + assert 0 == faces.min() + assert coords.shape[0] == faces.max() + 1 surf_path = pjoin(data_path, "surf", "%s.%s" % ("lh", "sphere")) coords, faces, volume_info, create_stamp = read_geometry( surf_path, read_metadata=True, read_stamp=True) - assert_equal(0, faces.min()) - assert_equal(coords.shape[0], faces.max() + 1) - assert_equal(9, len(volume_info)) - assert_equal([2, 0, 20], volume_info['head']) - assert_equal(u'created by greve on Thu Jun 8 19:17:51 2006', - create_stamp) + assert 0 == faces.min() + assert coords.shape[0] == faces.max() + 1 + assert 9 == len(volume_info) + assert np.array_equal([2, 0, 20], volume_info['head']) + assert create_stamp == 'created by greve on Thu Jun 8 19:17:51 2006' # Test equivalence of freesurfer- and nibabel-generated triangular files # with respect to read_geometry() @@ -82,7 +79,8 @@ def test_geometry(): for key in ('xras', 'yras', 'zras', 'cras'): assert_allclose(volume_info2[key], volume_info[key], rtol=1e-7, atol=1e-30) - assert_equal(volume_info2['cras'], volume_info['cras']) + + assert np.array_equal(volume_info2['cras'], volume_info['cras']) with open(surf_path, 'rb') as fobj: np.fromfile(fobj, ">u1", 3) read_create_stamp = fobj.readline().decode().rstrip('\n') @@ -92,27 +90,27 @@ def test_geometry(): with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) read_geometry(surf_path, read_metadata=True) - assert_true(any('volume information contained' in str(ww.message) - for ww in w)) - assert_true(any('extension code' in str(ww.message) for ww in w)) + + assert any('volume information contained' in str(ww.message) for ww in w) + assert any('extension code' in str(ww.message) for ww in w) volume_info['head'] = [1, 2] with clear_and_catch_warnings() as w: write_geometry(surf_path, coords, faces, create_stamp, volume_info) - assert_true(any('Unknown extension' in str(ww.message) for ww in w)) + assert any('Unknown extension' in str(ww.message) for ww in w) volume_info['a'] = 0 - assert_raises(ValueError, write_geometry, surf_path, coords, - faces, create_stamp, volume_info) + with pytest.raises(ValueError): + write_geometry(surf_path, coords, faces, create_stamp, volume_info) - assert_equal(create_stamp, read_create_stamp) + assert create_stamp == read_create_stamp - np.testing.assert_array_equal(coords, coords2) - np.testing.assert_array_equal(faces, faces2) + assert np.array_equal(coords, coords2) + assert np.array_equal(faces, faces2) # Validate byte ordering coords_swapped = coords.byteswap().newbyteorder() faces_swapped = faces.byteswap().newbyteorder() - np.testing.assert_array_equal(coords_swapped, coords) - np.testing.assert_array_equal(faces_swapped, faces) + assert np.array_equal(coords_swapped, coords) + assert np.array_equal(faces_swapped, faces) @freesurfer_test @@ -122,14 +120,14 @@ def test_quad_geometry(): new_quad = pjoin(get_nibabel_data(), 'nitest-freesurfer', 'subjects', 'bert', 'surf', 'lh.inflated.nofix') coords, faces = read_geometry(new_quad) - assert_equal(0, faces.min()) - assert_equal(coords.shape[0], faces.max() + 1) + assert 0 == faces.min() + assert coords.shape[0] == (faces.max() + 1) with InTemporaryDirectory(): new_path = 'test' write_geometry(new_path, coords, faces) coords2, faces2 = read_geometry(new_path) - assert_equal(coords, coords2) - assert_equal(faces, faces2) + assert np.array_equal(coords,coords2) + assert np.array_equal(faces, faces2) @freesurfer_test @@ -137,13 +135,13 @@ def test_morph_data(): """Test IO of morphometry data file (eg. curvature).""" curv_path = pjoin(data_path, "surf", "%s.%s" % ("lh", "curv")) curv = read_morph_data(curv_path) - assert_true(-1.0 < curv.min() < 0) - assert_true(0 < curv.max() < 1.0) + assert -1.0 < curv.min() < 0 + assert 0 < curv.max() < 1.0 with InTemporaryDirectory(): new_path = 'test' write_morph_data(new_path, curv) curv2 = read_morph_data(new_path) - assert_equal(curv2, curv) + assert np.array_equal(curv2, curv) def test_write_morph_data(): @@ -156,17 +154,17 @@ def test_write_morph_data(): for shape in okay_shapes: write_morph_data('test.curv', values.reshape(shape)) # Check ordering is preserved, regardless of shape - assert_equal(values, read_morph_data('test.curv')) - assert_raises(ValueError, write_morph_data, 'test.curv', - np.zeros(shape), big_num) + assert np.array_equal(read_morph_data('test.curv'), values) + + with pytest.raises(ValueError): + write_morph_data('test.curv', np.zeros(shape), big_num) # Windows 32-bit overflows Python int if np.dtype(np.int) != np.dtype(np.int32): - assert_raises(ValueError, write_morph_data, 'test.curv', - strided_scalar((big_num,))) + with pytest.raises(ValueError): + write_morph_data('test.curv', strided_scalar((big_num,))) for shape in bad_shapes: - assert_raises(ValueError, write_morph_data, 'test.curv', - values.reshape(shape)) - + with pytest.raises(ValueError): + write_morph_data('test.curv', values.reshape(shape)) @freesurfer_test def test_annot(): @@ -177,8 +175,8 @@ def test_annot(): hash_ = _hash_file_content(annot_path) labels, ctab, names = read_annot(annot_path) - assert_true(labels.shape == (163842, )) - assert_true(ctab.shape == (len(names), 5)) + assert labels.shape == (163842, ) + assert ctab.shape == (len(names), 5) labels_orig = None if a == 'aparc': @@ -186,9 +184,9 @@ def test_annot(): np.testing.assert_array_equal(labels == -1, labels_orig == 0) # Handle different version of fsaverage if hash_ == 'bf0b488994657435cdddac5f107d21e8': - assert_true(np.sum(labels_orig == 0) == 13887) + assert np.sum(labels_orig == 0) == 13887 elif hash_ == 'd4f5b7cbc2ed363ac6fcf89e19353504': - assert_true(np.sum(labels_orig == 1639705) == 13327) + assert np.sum(labels_orig == 1639705) == 13327 else: raise RuntimeError("Unknown freesurfer file. Please report " "the problem to the maintainer of nibabel.") @@ -203,11 +201,11 @@ def test_annot(): if labels_orig is not None: labels_orig_2, _, _ = read_annot(annot_path, orig_ids=True) - np.testing.assert_array_equal(labels, labels2) + assert np.array_equal(labels, labels2) if labels_orig is not None: - np.testing.assert_array_equal(labels_orig, labels_orig_2) - np.testing.assert_array_equal(ctab, ctab2) - assert_equal(names, names2) + assert np.array_equal(labels_orig, labels_orig_2) + assert np.array_equal(ctab, ctab2) + assert names == names2 def test_read_write_annot(): @@ -269,12 +267,10 @@ def test_write_annot_fill_ctab(): # values back. badannot = (10 * np.arange(nlabels, dtype=np.int32)).reshape(-1, 1) rgbal = np.hstack((rgba, badannot)) - print(labels) with clear_and_catch_warnings() as w: write_annot(annot_path, labels, rgbal, names, fill_ctab=False) - assert_true( - any('Annotation values in {} will be incorrect'.format( - annot_path) == str(ww.message) for ww in w)) + assert any('Annotation values in {} will be incorrect'.format(annot_path) == str(ww.message) + for ww in w) labels2, rgbal2, names2 = read_annot(annot_path, orig_ids=True) names2 = [n.decode('ascii') for n in names2] assert np.all(np.isclose(rgbal2[:, :4], rgba)) @@ -288,9 +284,8 @@ def test_write_annot_fill_ctab(): rgbal[:, 2] * (2 ** 16)) with clear_and_catch_warnings() as w: write_annot(annot_path, labels, rgbal, names, fill_ctab=False) - assert_true( - not any('Annotation values in {} will be incorrect'.format( - annot_path) == str(ww.message) for ww in w)) + assert all('Annotation values in {} will be incorrect'.format(annot_path) != str(ww.message) + for ww in w) labels2, rgbal2, names2 = read_annot(annot_path) names2 = [n.decode('ascii') for n in names2] assert np.all(np.isclose(rgbal2[:, :4], rgba)) @@ -348,13 +343,13 @@ def test_label(): label_path = pjoin(data_path, "label", "lh.cortex.label") label = read_label(label_path) # XXX : test more - assert_true(label.min() >= 0) - assert_true(label.max() <= 163841) - assert_true(label.shape[0] <= 163842) + assert label.min() >= 0 + assert label.max() <= 163841 + assert label.shape[0] <= 163842 labels, scalars = read_label(label_path, True) - assert_true(np.all(labels == label)) - assert_true(len(labels) == len(scalars)) + assert np.all(labels == label) + assert len(labels) == len(scalars) def test_write_annot_maxstruct(): @@ -371,6 +366,6 @@ def test_write_annot_maxstruct(): # Validate the file can be read rt_labels, rt_ctab, rt_names = read_annot(annot_path) # Check round-trip - assert_array_equal(labels, rt_labels) - assert_array_equal(rgba, rt_ctab[:, :4]) - assert_equal(names, [n.decode('ascii') for n in rt_names]) + assert np.array_equal(labels, rt_labels) + assert np.array_equal(rgba, rt_ctab[:, :4]) + assert names == [n.decode('ascii') for n in rt_names] diff --git a/nibabel/freesurfer/tests/test_mghformat.py b/nibabel/freesurfer/tests/test_mghformat.py index 289acbcd01..e1cfc56b18 100644 --- a/nibabel/freesurfer/tests/test_mghformat.py +++ b/nibabel/freesurfer/tests/test_mghformat.py @@ -23,12 +23,10 @@ from ...wrapstruct import WrapStructError from ... import imageglobals -from nose.tools import assert_true, assert_false -from numpy.testing import (assert_equal, assert_array_equal, - assert_array_almost_equal, assert_almost_equal, - assert_raises) -from ...testing import assert_not_equal +import pytest + +from numpy.testing import assert_array_equal, assert_array_almost_equal, assert_almost_equal from ...testing import data_path @@ -67,10 +65,10 @@ def test_read_mgh(): # header h = mgz.header - assert_equal(h['version'], 1) - assert_equal(h['type'], 3) - assert_equal(h['dof'], 0) - assert_equal(h['goodRASFlag'], 1) + assert h['version'] == 1 + assert h['type'] == 3 + assert h['dof'] == 0 + assert h['goodRASFlag'] == 1 assert_array_equal(h['dims'], [3, 4, 5, 2]) assert_almost_equal(h['tr'], 2.0) assert_almost_equal(h['flip_angle'], 0.0) @@ -101,11 +99,11 @@ def test_write_mgh(): # Delete loaded image to allow file deletion by windows del mgz # header - assert_equal(h['version'], 1) - assert_equal(h['type'], 3) - assert_equal(h['dof'], 0) - assert_equal(h['goodRASFlag'], 1) - assert_array_equal(h['dims'], [5, 4, 3, 2]) + assert h['version'] == 1 + assert h['type'] == 3 + assert h['dof'] == 0 + assert h['goodRASFlag'] == 1 + assert np.array_equal(h['dims'], [5, 4, 3, 2]) assert_almost_equal(h['tr'], 0.0) assert_almost_equal(h['flip_angle'], 0.0) assert_almost_equal(h['te'], 0.0) @@ -131,11 +129,11 @@ def test_write_noaffine_mgh(): # Delete loaded image to allow file deletion by windows del mgz # header - assert_equal(h['version'], 1) - assert_equal(h['type'], 0) # uint8 for mgh - assert_equal(h['dof'], 0) - assert_equal(h['goodRASFlag'], 1) - assert_array_equal(h['dims'], [7, 13, 3, 22]) + assert h['version'] == 1 + assert h['type'] == 0 # uint8 for mgh + assert h['dof'] == 0 + assert h['goodRASFlag'] == 1 + assert np.array_equal(h['dims'], [7, 13, 3, 22]) assert_almost_equal(h['tr'], 0.0) assert_almost_equal(h['flip_angle'], 0.0) assert_almost_equal(h['te'], 0.0) @@ -157,7 +155,7 @@ def test_set_zooms(): (1, 1, -1, 1), (1, 1, 1, -1), (1, 1, 1, 1, 5)): - with assert_raises(HeaderDataError): + with pytest.raises(HeaderDataError): h.set_zooms(zooms) # smoke test for tr=0 h.set_zooms((1, 1, 1, 0)) @@ -177,7 +175,8 @@ def bad_dtype_mgh(): def test_bad_dtype_mgh(): # Now test the above function - assert_raises(MGHError, bad_dtype_mgh) + with pytest.raises(MGHError): + bad_dtype_mgh() def test_filename_exts(): @@ -218,14 +217,14 @@ def test_header_updating(): assert_almost_equal(mgz.affine, exp_aff, 6) assert_almost_equal(hdr.get_affine(), exp_aff, 6) # Test that initial wonky header elements have not changed - assert_equal(hdr['delta'], 1) + assert np.all(hdr['delta'] == 1) assert_almost_equal(hdr['Mdc'].T, exp_aff[:3, :3]) # Save, reload, same thing img_fobj = io.BytesIO() mgz2 = _mgh_rt(mgz, img_fobj) hdr2 = mgz2.header assert_almost_equal(hdr2.get_affine(), exp_aff, 6) - assert_equal(hdr2['delta'], 1) + assert_array_equal(hdr2['delta'],1) # Change affine, change underlying header info exp_aff_d = exp_aff.copy() exp_aff_d[0, -1] = -14 @@ -258,17 +257,17 @@ def test_eq(): # Test headers compare properly hdr = MGHHeader() hdr2 = MGHHeader() - assert_equal(hdr, hdr2) + assert hdr == hdr2 hdr.set_data_shape((2, 3, 4)) - assert_false(hdr == hdr2) + assert(hdr != hdr2) hdr2.set_data_shape((2, 3, 4)) - assert_equal(hdr, hdr2) + assert hdr == hdr2 def test_header_slope_inter(): # Test placeholder slope / inter method hdr = MGHHeader() - assert_equal(hdr.get_slope_inter(), (None, None)) + assert hdr.get_slope_inter() == (None, None) def test_mgh_load_fileobj(): @@ -280,14 +279,14 @@ def test_mgh_load_fileobj(): # pass the filename to the array proxy, please feel free to change this # test. img = MGHImage.load(MGZ_FNAME) - assert_equal(img.dataobj.file_like, MGZ_FNAME) + assert img.dataobj.file_like == MGZ_FNAME # Check fileobj also passed into dataobj with ImageOpener(MGZ_FNAME) as fobj: contents = fobj.read() bio = io.BytesIO(contents) fm = MGHImage.make_file_map(mapping=dict(image=bio)) img2 = MGHImage.from_file_map(fm) - assert_true(img2.dataobj.file_like is bio) + assert(img2.dataobj.file_like is bio) assert_array_equal(img.get_fdata(), img2.get_fdata()) @@ -295,7 +294,7 @@ def test_mgh_affine_default(): hdr = MGHHeader() hdr['goodRASFlag'] = 0 hdr2 = MGHHeader(hdr.binaryblock) - assert_equal(hdr2['goodRASFlag'], 1) + assert hdr2['goodRASFlag'] == 1 assert_array_equal(hdr['Mdc'], hdr2['Mdc']) assert_array_equal(hdr['Pxyz_c'], hdr2['Pxyz_c']) @@ -310,33 +309,33 @@ def test_mgh_set_data_shape(): assert_array_equal(hdr.get_data_shape(), (5, 4, 3)) hdr.set_data_shape((5, 4, 3, 2)) assert_array_equal(hdr.get_data_shape(), (5, 4, 3, 2)) - with assert_raises(ValueError): + with pytest.raises(ValueError): hdr.set_data_shape((5, 4, 3, 2, 1)) def test_mghheader_default_structarr(): hdr = MGHHeader.default_structarr() - assert_equal(hdr['version'], 1) + assert hdr['version'] == 1 assert_array_equal(hdr['dims'], 1) - assert_equal(hdr['type'], 3) - assert_equal(hdr['dof'], 0) - assert_equal(hdr['goodRASFlag'], 1) + assert hdr['type'] == 3 + assert hdr['dof'] == 0 + assert hdr['goodRASFlag'] == 1 assert_array_equal(hdr['delta'], 1) assert_array_equal(hdr['Mdc'], [[-1, 0, 0], [0, 0, 1], [0, -1, 0]]) assert_array_equal(hdr['Pxyz_c'], 0) - assert_equal(hdr['tr'], 0) - assert_equal(hdr['flip_angle'], 0) - assert_equal(hdr['te'], 0) - assert_equal(hdr['ti'], 0) - assert_equal(hdr['fov'], 0) + assert hdr['tr'] == 0 + assert hdr['flip_angle'] == 0 + assert hdr['te'] == 0 + assert hdr['ti'] == 0 + assert hdr['fov'] == 0 for endianness in (None,) + BIG_CODES: hdr2 = MGHHeader.default_structarr(endianness=endianness) - assert_equal(hdr2, hdr) - assert_equal(hdr2.newbyteorder('>'), hdr) + assert hdr2 == hdr + assert hdr2.newbyteorder('>') == hdr for endianness in LITTLE_CODES: - with assert_raises(ValueError): + with pytest.raises(ValueError): MGHHeader.default_structarr(endianness=endianness) @@ -351,17 +350,17 @@ def test_deprecated_fields(): hdr['mrparams'] = [1, 2, 3, 4] assert_array_almost_equal(hdr['mrparams'], [1, 2, 3, 4]) - assert_equal(hdr['tr'], 1) - assert_equal(hdr['flip_angle'], 2) - assert_equal(hdr['te'], 3) - assert_equal(hdr['ti'], 4) - assert_equal(hdr['fov'], 0) + assert hdr['tr'] == 1 + assert hdr['flip_angle'] == 2 + assert hdr['te'] == 3 + assert hdr['ti'] == 4 + assert hdr['fov'] == 0 assert_array_almost_equal(hdr_data['mrparams'], [1, 2, 3, 4]) - assert_equal(hdr_data['tr'], 1) - assert_equal(hdr_data['flip_angle'], 2) - assert_equal(hdr_data['te'], 3) - assert_equal(hdr_data['ti'], 4) - assert_equal(hdr_data['fov'], 0) + assert hdr_data['tr'] == 1 + assert hdr_data['flip_angle'] == 2 + assert hdr_data['te'] == 3 + assert hdr_data['ti'] == 4 + assert hdr_data['fov'] == 0 hdr['tr'] = 5 hdr['flip_angle'] = 6 @@ -388,7 +387,7 @@ def check_dtypes(self, expected, actual): # Some images will want dtypes to be equal including endianness, # others may only require the same type # MGH requires the actual to be a big endian version of expected - assert_equal(expected.newbyteorder('>'), actual) + assert expected.newbyteorder('>') == actual class TestMGHHeader(_TestLabeledWrapStruct): @@ -405,9 +404,9 @@ def test_general_init(self): hdr = self.header_class() # binaryblock has length given by header data dtype binblock = hdr.binaryblock - assert_equal(len(binblock), hdr.structarr.dtype.itemsize) + assert len(binblock) == hdr.structarr.dtype.itemsize # Endianness will always be big, and cannot be set - assert_equal(hdr.endianness, '>') + assert hdr.endianness == '>' # You can also pass in a check flag, without data this has no # effect hdr = self.header_class(check=False) @@ -416,15 +415,15 @@ def test__eq__(self): # Test equal and not equal hdr1 = self.header_class() hdr2 = self.header_class() - assert_equal(hdr1, hdr2) + assert hdr1 == hdr2 self._set_something_into_hdr(hdr1) - assert_not_equal(hdr1, hdr2) + assert hdr1 != hdr2 self._set_something_into_hdr(hdr2) - assert_equal(hdr1, hdr2) + assert hdr1 == hdr2 # REMOVED as_byteswapped() test # Check comparing to funny thing says no - assert_not_equal(hdr1, None) - assert_not_equal(hdr1, 1) + assert hdr1 != None + assert hdr1 != 1 def test_to_from_fileobj(self): # Successful write using write_to @@ -433,56 +432,58 @@ def test_to_from_fileobj(self): hdr.write_to(str_io) str_io.seek(0) hdr2 = self.header_class.from_fileobj(str_io) - assert_equal(hdr2.endianness, '>') - assert_equal(hdr2.binaryblock, hdr.binaryblock) + assert hdr2.endianness == '>' + assert hdr2.binaryblock == hdr.binaryblock def test_endian_guess(self): # Check guesses of endian eh = self.header_class() - assert_equal(eh.endianness, '>') - assert_equal(self.header_class.guessed_endian(eh), '>') + assert eh.endianness == '>' + assert self.header_class.guessed_endian(eh) == '>' def test_bytes(self): # Test get of bytes hdr1 = self.header_class() bb = hdr1.binaryblock hdr2 = self.header_class(hdr1.binaryblock) - assert_equal(hdr1, hdr2) - assert_equal(hdr1.binaryblock, hdr2.binaryblock) + assert hdr1 == hdr2 + assert hdr1.binaryblock == hdr2.binaryblock # Do a set into the header, and try again. The specifics of 'setting # something' will depend on the nature of the bytes object self._set_something_into_hdr(hdr1) hdr2 = self.header_class(hdr1.binaryblock) - assert_equal(hdr1, hdr2) - assert_equal(hdr1.binaryblock, hdr2.binaryblock) + assert hdr1 == hdr2 + assert hdr1.binaryblock == hdr2.binaryblock # Short binaryblocks give errors (here set through init) # Long binaryblocks are truncated - assert_raises(WrapStructError, - self.header_class, - bb[:self.header_class._hdrdtype.itemsize - 1]) + with pytest.raises(WrapStructError): + self.header_class(bb[:self.header_class._hdrdtype.itemsize - 1]) + # Checking set to true by default, and prevents nonsense being # set into the header. bb_bad = self.get_bad_bb() if bb_bad is None: return with imageglobals.LoggingOutputSuppressor(): - assert_raises(HeaderDataError, self.header_class, bb_bad) + with pytest.raises(HeaderDataError): + self.header_class(bb_bad) + # now slips past without check _ = self.header_class(bb_bad, check=False) def test_as_byteswapped(self): # Check byte swapping hdr = self.header_class() - assert_equal(hdr.endianness, '>') + assert hdr.endianness == '>' # same code just returns a copy for endianness in BIG_CODES: hdr2 = hdr.as_byteswapped(endianness) - assert_false(hdr2 is hdr) - assert_equal(hdr2, hdr) + assert(hdr2 is not hdr) + assert hdr2 == hdr # Different code raises error for endianness in (None,) + LITTLE_CODES: - with assert_raises(ValueError): + with pytest.raises(ValueError): hdr.as_byteswapped(endianness) # Note that contents is not rechecked on swap / copy class DC(self.header_class): @@ -490,7 +491,9 @@ def check_fix(self, *args, **kwargs): raise Exception # Assumes check=True default - assert_raises(Exception, DC, hdr.binaryblock) + with pytest.raises(Exception): + DC(hdr.binaryblock) + hdr = DC(hdr.binaryblock, check=False) hdr2 = hdr.as_byteswapped('>') @@ -499,8 +502,8 @@ def test_checks(self): hdr_t = self.header_class() # _dxer just returns the diagnostics as a string # Default hdr is OK - assert_equal(self._dxer(hdr_t), '') + assert self._dxer(hdr_t) == '' # Version should be 1 hdr = hdr_t.copy() hdr['version'] = 2 - assert_equal(self._dxer(hdr), 'Unknown MGH format version') + assert self._dxer(hdr) == 'Unknown MGH format version' diff --git a/nibabel/gifti/tests/test_gifti.py b/nibabel/gifti/tests/test_gifti.py index 167e56d6cf..2d60482c59 100644 --- a/nibabel/gifti/tests/test_gifti.py +++ b/nibabel/gifti/tests/test_gifti.py @@ -6,27 +6,26 @@ import numpy as np -import nibabel as nib -from nibabel.gifti import (GiftiImage, GiftiDataArray, GiftiLabel, - GiftiLabelTable, GiftiMetaData, GiftiNVPairs, - GiftiCoordSystem) -from nibabel.gifti.gifti import data_tag -from nibabel.nifti1 import data_type_codes -from nibabel.fileholders import FileHolder - -from numpy.testing import (assert_array_almost_equal, - assert_array_equal) -from nose.tools import (assert_true, assert_false, assert_equal, assert_raises) -from nibabel.testing import clear_and_catch_warnings, test_data +from ... import load +from .. import (GiftiImage, GiftiDataArray, GiftiLabel, + GiftiLabelTable, GiftiMetaData, GiftiNVPairs, + GiftiCoordSystem) +from ..gifti import data_tag +from ...nifti1 import data_type_codes +from ...fileholders import FileHolder + +from numpy.testing import assert_array_almost_equal, assert_array_equal +import pytest +from ...testing import clear_and_catch_warnings, test_data from .test_parse_gifti_fast import (DATA_FILE1, DATA_FILE2, DATA_FILE3, DATA_FILE4, DATA_FILE5, DATA_FILE6) import itertools def test_agg_data(): - surf_gii_img = nib.load(test_data('gifti', 'ascii.gii')) - func_gii_img = nib.load(test_data('gifti', 'task.func.gii')) - shape_gii_img = nib.load(test_data('gifti', 'rh.shape.curv.gii')) + surf_gii_img = load(test_data('gifti', 'ascii.gii')) + func_gii_img = load(test_data('gifti', 'task.func.gii')) + shape_gii_img = load(test_data('gifti', 'rh.shape.curv.gii')) # add timeseries data with intent code ``none`` point_data = surf_gii_img.get_arrays_from_intent('pointset')[0].data @@ -35,7 +34,7 @@ def test_agg_data(): func_data = np.column_stack(tuple(da.data for da in func_da)) shape_data = shape_gii_img.get_arrays_from_intent('shape')[0].data - assert_equal(surf_gii_img.agg_data(), (point_data, triangle_data)) + assert surf_gii_img.agg_data() == (point_data, triangle_data) assert_array_equal(func_gii_img.agg_data(), func_data) assert_array_equal(shape_gii_img.agg_data(), shape_data) @@ -44,45 +43,45 @@ def test_agg_data(): assert_array_equal(func_gii_img.agg_data('time series'), func_data) assert_array_equal(shape_gii_img.agg_data('shape'), shape_data) - assert_equal(surf_gii_img.agg_data('time series'), ()) - assert_equal(func_gii_img.agg_data('triangle'), ()) - assert_equal(shape_gii_img.agg_data('pointset'), ()) + assert surf_gii_img.agg_data('time series') == () + assert func_gii_img.agg_data('triangle') == () + assert shape_gii_img.agg_data('pointset') == () - assert_equal(surf_gii_img.agg_data(('pointset', 'triangle')), (point_data, triangle_data)) - assert_equal(surf_gii_img.agg_data(('triangle', 'pointset')), (triangle_data, point_data)) + assert surf_gii_img.agg_data(('pointset', 'triangle')) == (point_data, triangle_data) + assert surf_gii_img.agg_data(('triangle', 'pointset')) == (triangle_data, point_data) def test_gifti_image(): # Check that we're not modifying the default empty list in the default # arguments. gi = GiftiImage() - assert_equal(gi.darrays, []) - assert_equal(gi.meta.metadata, {}) - assert_equal(gi.labeltable.labels, []) + assert gi.darrays == [] + assert gi.meta.metadata == {} + assert gi.labeltable.labels == [] arr = np.zeros((2, 3)) gi.darrays.append(arr) # Now check we didn't overwrite the default arg gi = GiftiImage() - assert_equal(gi.darrays, []) + assert gi.darrays == [] # Test darrays / numDA gi = GiftiImage() - assert_equal(gi.numDA, 0) + assert gi.numDA == 0 # Test from numpy numeric array data = np.random.random((5,)) da = GiftiDataArray(data) gi.add_gifti_data_array(da) - assert_equal(gi.numDA, 1) + assert gi.numDA == 1 assert_array_equal(gi.darrays[0].data, data) # Test removing gi.remove_gifti_data_array(0) - assert_equal(gi.numDA, 0) + assert gi.numDA == 0 # Remove from empty gi = GiftiImage() gi.remove_gifti_data_array_by_intent(0) - assert_equal(gi.numDA, 0) + assert gi.numDA == 0 # Remove one gi = GiftiImage() @@ -90,113 +89,112 @@ def test_gifti_image(): gi.add_gifti_data_array(da) gi.remove_gifti_data_array_by_intent(3) - assert_equal(gi.numDA, 1, "data array should exist on 'missed' remove") + assert gi.numDA == 1, "data array should exist on 'missed' remove" gi.remove_gifti_data_array_by_intent(da.intent) - assert_equal(gi.numDA, 0) + assert gi.numDA == 0 def test_gifti_image_bad_inputs(): img = GiftiImage() # Try to set a non-data-array - assert_raises(TypeError, img.add_gifti_data_array, 'not-a-data-array') + pytest.raises(TypeError, img.add_gifti_data_array, 'not-a-data-array') # Try to set to non-table def assign_labeltable(val): img.labeltable = val - assert_raises(TypeError, assign_labeltable, 'not-a-table') + pytest.raises(TypeError, assign_labeltable, 'not-a-table') # Try to set to non-table def assign_metadata(val): img.meta = val - assert_raises(TypeError, assign_metadata, 'not-a-meta') + pytest.raises(TypeError, assign_metadata, 'not-a-meta') def test_dataarray_empty(): # Test default initialization of DataArray null_da = GiftiDataArray() - assert_equal(null_da.data, None) - assert_equal(null_da.intent, 0) - assert_equal(null_da.datatype, 0) - assert_equal(null_da.encoding, 3) - assert_equal(null_da.endian, 2 if sys.byteorder == 'little' else 1) - assert_equal(null_da.coordsys.dataspace, 0) - assert_equal(null_da.coordsys.xformspace, 0) + assert null_da.data is None + assert null_da.intent == 0 + assert null_da.datatype == 0 + assert null_da.encoding == 3 + assert null_da.endian == (2 if sys.byteorder == 'little' else 1) + assert null_da.coordsys.dataspace == 0 + assert null_da.coordsys.xformspace == 0 assert_array_equal(null_da.coordsys.xform, np.eye(4)) - assert_equal(null_da.ind_ord, 1) - assert_equal(null_da.meta.metadata, {}) - assert_equal(null_da.ext_fname, '') - assert_equal(null_da.ext_offset, 0) + assert null_da.ind_ord == 1 + assert null_da.meta.metadata == {} + assert null_da.ext_fname == '' + assert null_da.ext_offset == 0 def test_dataarray_init(): # Test non-default dataarray initialization gda = GiftiDataArray # shortcut - assert_equal(gda(None).data, None) + assert gda(None).data is None arr = np.arange(12, dtype=np.float32).reshape((3, 4)) assert_array_equal(gda(arr).data, arr) # Intents - assert_raises(KeyError, gda, intent=1) # Invalid code - assert_raises(KeyError, gda, intent='not an intent') # Invalid string - assert_equal(gda(intent=2).intent, 2) - assert_equal(gda(intent='correlation').intent, 2) - assert_equal(gda(intent='NIFTI_INTENT_CORREL').intent, 2) + pytest.raises(KeyError, gda, intent=1) # Invalid code + pytest.raises(KeyError, gda, intent='not an intent') # Invalid string + assert gda(intent=2).intent == 2 + assert gda(intent='correlation').intent == 2 + assert gda(intent='NIFTI_INTENT_CORREL').intent == 2 # Datatype - assert_equal(gda(datatype=2).datatype, 2) - assert_equal(gda(datatype='uint8').datatype, 2) - assert_raises(KeyError, gda, datatype='not_datatype') + assert gda(datatype=2).datatype == 2 + assert gda(datatype='uint8').datatype == 2 + pytest.raises(KeyError, gda, datatype='not_datatype') # Float32 datatype comes from array if datatype not set - assert_equal(gda(arr).datatype, 16) + assert gda(arr).datatype == 16 # Can be overriden by init - assert_equal(gda(arr, datatype='uint8').datatype, 2) + assert gda(arr, datatype='uint8').datatype == 2 # Encoding - assert_equal(gda(encoding=1).encoding, 1) - assert_equal(gda(encoding='ASCII').encoding, 1) - assert_equal(gda(encoding='GIFTI_ENCODING_ASCII').encoding, 1) - assert_raises(KeyError, gda, encoding='not an encoding') + assert gda(encoding=1).encoding == 1 + assert gda(encoding='ASCII').encoding == 1 + assert gda(encoding='GIFTI_ENCODING_ASCII').encoding == 1 + pytest.raises(KeyError, gda, encoding='not an encoding') # Endian - assert_equal(gda(endian=1).endian, 1) - assert_equal(gda(endian='big').endian, 1) - assert_equal(gda(endian='GIFTI_ENDIAN_BIG').endian, 1) - assert_raises(KeyError, gda, endian='not endian code') + assert gda(endian=1).endian == 1 + assert gda(endian='big').endian == 1 + assert gda(endian='GIFTI_ENDIAN_BIG').endian == 1 + pytest.raises(KeyError, gda, endian='not endian code') # CoordSys aff = np.diag([2, 3, 4, 1]) cs = GiftiCoordSystem(1, 2, aff) da = gda(coordsys=cs) - assert_equal(da.coordsys.dataspace, 1) - assert_equal(da.coordsys.xformspace, 2) + assert da.coordsys.dataspace == 1 + assert da.coordsys.xformspace == 2 assert_array_equal(da.coordsys.xform, aff) # Ordering - assert_equal(gda(ordering=2).ind_ord, 2) - assert_equal(gda(ordering='F').ind_ord, 2) - assert_equal(gda(ordering='ColumnMajorOrder').ind_ord, 2) - assert_raises(KeyError, gda, ordering='not an ordering') + assert gda(ordering=2).ind_ord == 2 + assert gda(ordering='F').ind_ord == 2 + assert gda(ordering='ColumnMajorOrder').ind_ord == 2 + pytest.raises(KeyError, gda, ordering='not an ordering') # metadata meta_dict=dict(one=1, two=2) - assert_equal(gda(meta=GiftiMetaData.from_dict(meta_dict)).meta.metadata, - meta_dict) - assert_equal(gda(meta=meta_dict).meta.metadata, meta_dict) - assert_equal(gda(meta=None).meta.metadata, {}) + assert gda(meta=GiftiMetaData.from_dict(meta_dict)).meta.metadata == meta_dict + assert gda(meta=meta_dict).meta.metadata == meta_dict + assert gda(meta=None).meta.metadata == {} # ext_fname and ext_offset - assert_equal(gda(ext_fname='foo').ext_fname, 'foo') - assert_equal(gda(ext_offset=12).ext_offset, 12) + assert gda(ext_fname='foo').ext_fname == 'foo' + assert gda(ext_offset=12).ext_offset == 12 def test_dataarray_from_array(): with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) da = GiftiDataArray.from_array(np.ones((3, 4))) - assert_equal(len(w), 1) + assert len(w) == 1 for dt_code in data_type_codes.value_set(): data_type = data_type_codes.type[dt_code] if data_type is np.void: # not supported continue arr = np.zeros((10, 3), dtype=data_type) da = GiftiDataArray.from_array(arr, 'triangle') - assert_equal(da.datatype, data_type_codes[arr.dtype]) + assert da.datatype == data_type_codes[arr.dtype] bs_arr = arr.byteswap().newbyteorder() da = GiftiDataArray.from_array(bs_arr, 'triangle') - assert_equal(da.datatype, data_type_codes[arr.dtype]) + assert da.datatype == data_type_codes[arr.dtype] def test_to_xml_open_close_deprecations(): @@ -204,35 +202,35 @@ def test_to_xml_open_close_deprecations(): da = GiftiDataArray(np.ones((1,)), 'triangle') with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) - assert_true(isinstance(da.to_xml_open(), str)) - assert_equal(len(w), 1) + assert isinstance(da.to_xml_open(), str) + assert len(w) == 1 with clear_and_catch_warnings() as w: warnings.filterwarnings('once', category=DeprecationWarning) - assert_true(isinstance(da.to_xml_close(), str)) - assert_equal(len(w), 1) + assert isinstance(da.to_xml_close(), str) + assert len(w) == 1 def test_num_dim_deprecation(): da = GiftiDataArray(np.ones((2, 3, 4))) # num_dim is property, set automatically from len(da.dims) - assert_equal(da.num_dim, 3) + assert da.num_dim == 3 with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) # OK setting num_dim to correct value, but raises DeprecationWarning da.num_dim = 3 - assert_equal(len(w), 1) + assert len(w) == 1 # Any other value gives a ValueError - assert_raises(ValueError, setattr, da, 'num_dim', 4) + pytest.raises(ValueError, setattr, da, 'num_dim', 4) def test_labeltable(): img = GiftiImage() - assert_equal(len(img.labeltable.labels), 0) + assert len(img.labeltable.labels) == 0 new_table = GiftiLabelTable() new_table.labels += ['test', 'me'] img.labeltable = new_table - assert_equal(len(img.labeltable.labels), 2) + assert len(img.labeltable.labels) == 2 # Test deprecations with clear_and_catch_warnings() as w: @@ -240,23 +238,23 @@ def test_labeltable(): newer_table = GiftiLabelTable() newer_table.labels += ['test', 'me', 'again'] img.set_labeltable(newer_table) - assert_equal(len(w), 1) - assert_equal(len(img.get_labeltable().labels), 3) - assert_equal(len(w), 2) + assert len(w) == 1 + assert len(img.get_labeltable().labels) == 3 + assert len(w) == 2 def test_metadata(): nvpair = GiftiNVPairs('key', 'value') md = GiftiMetaData(nvpair=nvpair) - assert_equal(md.data[0].name, 'key') - assert_equal(md.data[0].value, 'value') + assert md.data[0].name == 'key' + assert md.data[0].value == 'value' # Test deprecation with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) - assert_equal(md.get_metadata(), dict(key='value')) - assert_equal(len(w), 1) - assert_equal(len(GiftiDataArray().get_metadata()), 0) - assert_equal(len(w), 2) + assert md.get_metadata() == dict(key='value') + assert len(w) == 1 + assert len(GiftiDataArray().get_metadata()) == 0 + assert len(w) == 2 def test_gifti_label_rgba(): @@ -267,44 +265,44 @@ def test_gifti_label_rgba(): assert_array_equal(rgba, gl1.rgba) gl1.red = 2 * gl1.red - assert_false(np.allclose(rgba, gl1.rgba)) # don't just store the list! + assert not np.allclose(rgba, gl1.rgba) # don't just store the list! gl2 = GiftiLabel() gl2.rgba = rgba assert_array_equal(rgba, gl2.rgba) gl2.blue = 2 * gl2.blue - assert_false(np.allclose(rgba, gl2.rgba)) # don't just store the list! + assert not np.allclose(rgba, gl2.rgba) # don't just store the list! def assign_rgba(gl, val): gl.rgba = val gl3 = GiftiLabel(**kwargs) - assert_raises(ValueError, assign_rgba, gl3, rgba[:2]) - assert_raises(ValueError, assign_rgba, gl3, rgba.tolist() + rgba.tolist()) + pytest.raises(ValueError, assign_rgba, gl3, rgba[:2]) + pytest.raises(ValueError, assign_rgba, gl3, rgba.tolist() + rgba.tolist()) # Test deprecation with clear_and_catch_warnings() as w: warnings.filterwarnings('once', category=DeprecationWarning) - assert_equal(kwargs['red'], gl3.get_rgba()[0]) - assert_equal(len(w), 1) + assert kwargs['red'] == gl3.get_rgba()[0] + assert len(w) == 1 # Test default value gl4 = GiftiLabel() - assert_equal(len(gl4.rgba), 4) - assert_true(np.all([elem is None for elem in gl4.rgba])) + assert len(gl4.rgba) == 4 + assert np.all([elem is None for elem in gl4.rgba]) def test_print_summary(): for fil in [DATA_FILE1, DATA_FILE2, DATA_FILE3, DATA_FILE4, DATA_FILE5, DATA_FILE6]: - gimg = nib.load(fil) + gimg = load(fil) gimg.print_summary() def test_gifti_coord(): from ..gifti import GiftiCoordSystem gcs = GiftiCoordSystem() - assert_true(gcs.xform is not None) + assert gcs.xform is not None # Smoke test gcs.xform = None @@ -316,7 +314,7 @@ def test_data_tag_deprecated(): with clear_and_catch_warnings() as w: warnings.filterwarnings('once', category=DeprecationWarning) data_tag(np.array([]), 'ASCII', '%i', 1) - assert_equal(len(w), 1) + assert len(w) == 1 def test_gifti_round_trip(): @@ -443,5 +441,5 @@ def test_darray_dtype_coercion_failures(): gii = GiftiImage(darrays=[da]) gii_copy = GiftiImage.from_bytes(gii.to_bytes()) da_copy = gii_copy.darrays[0] - assert_equal(np.dtype(da_copy.data.dtype), np.dtype(darray_dtype)) + assert np.dtype(da_copy.data.dtype) == np.dtype(darray_dtype) assert_array_equal(da_copy.data, da.data) diff --git a/nibabel/gifti/tests/test_giftiio.py b/nibabel/gifti/tests/test_giftiio.py index 90fe3e4d37..8269618b0c 100644 --- a/nibabel/gifti/tests/test_giftiio.py +++ b/nibabel/gifti/tests/test_giftiio.py @@ -7,33 +7,16 @@ # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## -import warnings +from ..giftiio import read, write +from .test_parse_gifti_fast import DATA_FILE1 -from nose.tools import (assert_true, assert_false, assert_equal, - assert_raises) -from nibabel.testing import clear_and_catch_warnings -from nibabel.tmpdirs import InTemporaryDirectory +import pytest -from .test_parse_gifti_fast import (DATA_FILE1, DATA_FILE2, DATA_FILE3, - DATA_FILE4, DATA_FILE5, DATA_FILE6) - - -class TestGiftiIO(object): - - def setUp(self): - with clear_and_catch_warnings() as w: - warnings.simplefilter('always', DeprecationWarning) - assert_equal(len(w), 1) - - -def test_read_deprecated(): - with clear_and_catch_warnings() as w: - warnings.simplefilter('always', DeprecationWarning) - from nibabel.gifti.giftiio import read, write - +def test_read_deprecated(tmp_path): + with pytest.deprecated_call(): img = read(DATA_FILE1) - assert_equal(len(w), 1) - with InTemporaryDirectory(): - write(img, 'test.gii') - assert_equal(len(w), 2) + + fname = tmp_path / 'test.gii' + with pytest.deprecated_call(): + write(img, fname) diff --git a/nibabel/gifti/tests/test_parse_gifti_fast.py b/nibabel/gifti/tests/test_parse_gifti_fast.py index a06180a964..54d8e78621 100644 --- a/nibabel/gifti/tests/test_parse_gifti_fast.py +++ b/nibabel/gifti/tests/test_parse_gifti_fast.py @@ -13,17 +13,16 @@ import numpy as np -import nibabel.gifti as gi -from nibabel.gifti.util import gifti_endian_codes -from nibabel.gifti.parse_gifti_fast import Outputter, parse_gifti_file -from nibabel.loadsave import load, save -from nibabel.nifti1 import xform_codes -from nibabel.tmpdirs import InTemporaryDirectory +from .. import gifti as gi +from ..util import gifti_endian_codes +from ..parse_gifti_fast import Outputter, parse_gifti_file +from ...loadsave import load, save +from ...nifti1 import xform_codes +from ...tmpdirs import InTemporaryDirectory from numpy.testing import assert_array_almost_equal -from nose.tools import (assert_true, assert_false, assert_equal, - assert_raises) +import pytest from ...testing import clear_and_catch_warnings @@ -106,9 +105,9 @@ def assert_default_types(loaded): if defaulttype is type(None): continue loadedtype = type(getattr(loaded, attr)) - assert_equal(loadedtype, defaulttype, - "Type mismatch for attribute: {} ({!s} != {!s})".format( - attr, loadedtype, defaulttype)) + assert loadedtype == defaulttype, ( + "Type mismatch for attribute: {} ({!s} != {!s})".format( + attr, loadedtype, defaulttype)) def test_default_types(): @@ -142,18 +141,18 @@ def test_read_ordering(): # read another image first (DATA_FILE2) then the shape is wrong # Read an image img2 = load(DATA_FILE2) - assert_equal(img2.darrays[0].data.shape, (143479, 1)) + assert img2.darrays[0].data.shape == (143479, 1) # Read image for which we know output shape img = load(DATA_FILE1) - assert_equal(img.darrays[0].data.shape, (3, 3)) + assert img.darrays[0].data.shape == (3, 3) def test_load_metadata(): for i, dat in enumerate(datafiles): img = load(dat) img.meta - assert_equal(numDA[i], img.numDA) - assert_equal(img.version, '1.0') + assert numDA[i] == img.numDA + assert img.version == '1.0' def test_metadata_deprecations(): @@ -163,12 +162,12 @@ def test_metadata_deprecations(): # Test deprecation with clear_and_catch_warnings() as w: warnings.filterwarnings('once', category=DeprecationWarning) - assert_equal(me, img.get_meta()) + assert me == img.get_meta() with clear_and_catch_warnings() as w: warnings.filterwarnings('once', category=DeprecationWarning) img.set_metadata(me) - assert_equal(me, img.meta) + assert me == img.meta def test_load_dataarray1(): @@ -181,14 +180,14 @@ def test_load_dataarray1(): assert_array_almost_equal(img.darrays[0].data, DATA_FILE1_darr1) assert_array_almost_equal(img.darrays[1].data, DATA_FILE1_darr2) me = img.darrays[0].meta.metadata - assert_true('AnatomicalStructurePrimary' in me) - assert_true('AnatomicalStructureSecondary' in me) - assert_equal(me['AnatomicalStructurePrimary'], 'CortexLeft') + assert 'AnatomicalStructurePrimary' in me + assert 'AnatomicalStructureSecondary' in me + me['AnatomicalStructurePrimary'] == 'CortexLeft' assert_array_almost_equal(img.darrays[0].coordsys.xform, np.eye(4, 4)) - assert_equal(xform_codes.niistring[img.darrays[ - 0].coordsys.dataspace], 'NIFTI_XFORM_TALAIRACH') - assert_equal(xform_codes.niistring[img.darrays[ - 0].coordsys.xformspace], 'NIFTI_XFORM_TALAIRACH') + assert xform_codes.niistring[ + img.darrays[0].coordsys.dataspace] == 'NIFTI_XFORM_TALAIRACH' + assert xform_codes.niistring[img.darrays[ + 0].coordsys.xformspace] == 'NIFTI_XFORM_TALAIRACH' def test_load_dataarray2(): @@ -223,7 +222,7 @@ def test_load_dataarray4(): def test_dataarray5(): img5 = load(DATA_FILE5) for da in img5.darrays: - assert_equal(gifti_endian_codes.byteorder[da.endian], 'little') + gifti_endian_codes.byteorder[da.endian] == 'little' assert_array_almost_equal(img5.darrays[0].data, DATA_FILE5_darr1) assert_array_almost_equal(img5.darrays[1].data, DATA_FILE5_darr2) # Round trip tested below @@ -234,24 +233,24 @@ def test_base64_written(): with open(DATA_FILE5, 'rb') as fobj: contents = fobj.read() # Confirm the bad tags are still in the file - assert_true(b'GIFTI_ENCODING_B64BIN' in contents) - assert_true(b'GIFTI_ENDIAN_LITTLE' in contents) + assert b'GIFTI_ENCODING_B64BIN' in contents + assert b'GIFTI_ENDIAN_LITTLE' in contents # The good ones are missing - assert_false(b'Base64Binary' in contents) - assert_false(b'LittleEndian' in contents) + assert b'Base64Binary' not in contents + assert b'LittleEndian' not in contents # Round trip img5 = load(DATA_FILE5) save(img5, 'fixed.gii') with open('fixed.gii', 'rb') as fobj: contents = fobj.read() # The bad codes have gone, replaced by the good ones - assert_false(b'GIFTI_ENCODING_B64BIN' in contents) - assert_false(b'GIFTI_ENDIAN_LITTLE' in contents) - assert_true(b'Base64Binary' in contents) + assert b'GIFTI_ENCODING_B64BIN' not in contents + assert b'GIFTI_ENDIAN_LITTLE' not in contents + assert b'Base64Binary' in contents if sys.byteorder == 'little': - assert_true(b'LittleEndian' in contents) + assert b'LittleEndian' in contents else: - assert_true(b'BigEndian' in contents) + assert b'BigEndian' in contents img5_fixed = load('fixed.gii') darrays = img5_fixed.darrays assert_array_almost_equal(darrays[0].data, DATA_FILE5_darr1) @@ -263,7 +262,7 @@ def test_readwritedata(): with InTemporaryDirectory(): save(img, 'test.gii') img2 = load('test.gii') - assert_equal(img.numDA, img2.numDA) + assert img.numDA == img2.numDA assert_array_almost_equal(img.darrays[0].data, img2.darrays[0].data) @@ -272,7 +271,7 @@ def test_modify_darray(): img = load(fname) darray = img.darrays[0] darray.data[:] = 0 - assert_true(np.array_equiv(darray.data, 0)) + assert np.array_equiv(darray.data, 0) def test_write_newmetadata(): @@ -281,32 +280,32 @@ def test_write_newmetadata(): newmeta = gi.GiftiMetaData(attr) img.meta = newmeta myme = img.meta.metadata - assert_true('mykey' in myme) + assert 'mykey' in myme newmeta = gi.GiftiMetaData.from_dict({'mykey1': 'val2'}) img.meta = newmeta myme = img.meta.metadata - assert_true('mykey1' in myme) - assert_false('mykey' in myme) + assert 'mykey1' in myme + assert 'mykey' not in myme def test_load_getbyintent(): img = load(DATA_FILE1) da = img.get_arrays_from_intent("NIFTI_INTENT_POINTSET") - assert_equal(len(da), 1) + assert len(da) == 1 with clear_and_catch_warnings() as w: warnings.filterwarnings('once', category=DeprecationWarning) da = img.getArraysFromIntent("NIFTI_INTENT_POINTSET") - assert_equal(len(da), 1) - assert_equal(len(w), 1) - assert_equal(w[0].category, DeprecationWarning) + assert len(da) == 1 + assert len(w) == 1 + w[0].category == DeprecationWarning da = img.get_arrays_from_intent("NIFTI_INTENT_TRIANGLE") - assert_equal(len(da), 1) + assert len(da) == 1 da = img.get_arrays_from_intent("NIFTI_INTENT_CORREL") - assert_equal(len(da), 0) - assert_equal(da, []) + assert len(da) == 0 + assert da == [] def test_load_labeltable(): @@ -317,15 +316,15 @@ def test_load_labeltable(): bimg = load('test.gii') for img in (img6, bimg): assert_array_almost_equal(img.darrays[0].data[:3], DATA_FILE6_darr1) - assert_equal(len(img.labeltable.labels), 36) + assert len(img.labeltable.labels) == 36 labeldict = img.labeltable.get_labels_as_dict() - assert_true(660700 in labeldict) - assert_equal(labeldict[660700], 'entorhinal') - assert_equal(img.labeltable.labels[1].key, 2647065) - assert_equal(img.labeltable.labels[1].red, 0.0980392) - assert_equal(img.labeltable.labels[1].green, 0.392157) - assert_equal(img.labeltable.labels[1].blue, 0.156863) - assert_equal(img.labeltable.labels[1].alpha, 1) + assert 660700 in labeldict + assert labeldict[660700] == 'entorhinal' + assert img.labeltable.labels[1].key == 2647065 + assert img.labeltable.labels[1].red == 0.0980392 + assert img.labeltable.labels[1].green == 0.392157 + assert img.labeltable.labels[1].blue == 0.156863 + assert img.labeltable.labels[1].alpha == 1 def test_labeltable_deprecations(): @@ -335,14 +334,14 @@ def test_labeltable_deprecations(): # Test deprecation with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) - assert_equal(lt, img.get_labeltable()) - assert_equal(len(w), 1) + assert lt == img.get_labeltable() + assert len(w) == 1 with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) img.set_labeltable(lt) - assert_equal(len(w), 1) - assert_equal(lt, img.labeltable) + assert len(w) == 1 + assert lt == img.labeltable def test_parse_dataarrays(): @@ -361,8 +360,8 @@ def test_parse_dataarrays(): with clear_and_catch_warnings() as w: warnings.filterwarnings('once', category=UserWarning) load(fn) - assert_equal(len(w), 1) - assert_equal(img.numDA, 0) + assert len(w) == 1 + assert img.numDA == 0 def test_parse_deprecated(): @@ -371,16 +370,16 @@ def test_parse_deprecated(): with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) op = Outputter() - assert_equal(len(w), 1) + assert len(w) == 1 op.initialize() # smoke test--no error. with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) - assert_raises(ValueError, parse_gifti_file) - assert_equal(len(w), 1) + pytest.raises(ValueError, parse_gifti_file) + assert len(w) == 1 def test_parse_with_buffersize(): for buff_sz in [None, 1, 2**12]: img2 = load(DATA_FILE2, buffer_size=buff_sz) - assert_equal(img2.darrays[0].data.shape, (143479, 1)) + assert img2.darrays[0].data.shape == (143479, 1) diff --git a/nibabel/nicom/tests/__init__.py b/nibabel/nicom/tests/__init__.py index c7c3753010..127ad5a6e0 100644 --- a/nibabel/nicom/tests/__init__.py +++ b/nibabel/nicom/tests/__init__.py @@ -1 +1,4 @@ -# init to allow relative imports in tests +from ...pydicom_compat import have_dicom +import unittest + +dicom_test = unittest.skipUnless(have_dicom, "Could not import dicom or pydicom") diff --git a/nibabel/nicom/tests/test_csareader.py b/nibabel/nicom/tests/test_csareader.py index a6bf589e90..1692aad622 100644 --- a/nibabel/nicom/tests/test_csareader.py +++ b/nibabel/nicom/tests/test_csareader.py @@ -7,15 +7,13 @@ import numpy as np +from ...pydicom_compat import pydicom from .. import csareader as csa from .. import dwiparams as dwp -from nose.tools import (assert_true, assert_false, assert_equal, assert_raises) - -from ...testing import skipif - -from nibabel.pydicom_compat import dicom_test, pydicom -from .test_dicomwrappers import (IO_DATA_PATH, DATA) +import pytest +from . import dicom_test +from .test_dicomwrappers import IO_DATA_PATH, DATA CSA2_B0 = open(pjoin(IO_DATA_PATH, 'csa2_b0.bin'), 'rb').read() CSA2_B1000 = open(pjoin(IO_DATA_PATH, 'csa2_b1000.bin'), 'rb').read() @@ -27,59 +25,61 @@ @dicom_test def test_csa_header_read(): hdr = csa.get_csa_header(DATA, 'image') - assert_equal(hdr['n_tags'], 83) - assert_equal(csa.get_csa_header(DATA, 'series')['n_tags'], 65) - assert_raises(ValueError, csa.get_csa_header, DATA, 'xxxx') - assert_true(csa.is_mosaic(hdr)) + assert hdr['n_tags'] == 83 + assert csa.get_csa_header(DATA, 'series')['n_tags'] == 65 + with pytest.raises(ValueError): + csa.get_csa_header(DATA, 'xxxx') + assert csa.is_mosaic(hdr) # Get a shallow copy of the data, lacking the CSA marker # Need to do it this way because del appears broken in pydicom 0.9.7 data2 = pydicom.dataset.Dataset() for element in DATA: if (element.tag.group, element.tag.elem) != (0x29, 0x10): data2.add(element) - assert_equal(csa.get_csa_header(data2, 'image'), None) + assert csa.get_csa_header(data2, 'image') is None # Add back the marker - CSA works again data2[(0x29, 0x10)] = DATA[(0x29, 0x10)] - assert_true(csa.is_mosaic(csa.get_csa_header(data2, 'image'))) + assert csa.is_mosaic(csa.get_csa_header(data2, 'image')) def test_csas0(): for csa_str in (CSA2_B0, CSA2_B1000): csa_info = csa.read(csa_str) - assert_equal(csa_info['type'], 2) - assert_equal(csa_info['n_tags'], 83) + assert csa_info['type'] == 2 + assert csa_info['n_tags'] == 83 tags = csa_info['tags'] - assert_equal(len(tags), 83) + assert len(tags) == 83 n_o_m = tags['NumberOfImagesInMosaic'] - assert_equal(n_o_m['items'], [48]) + assert n_o_m['items'] == [48] csa_info = csa.read(CSA2_B1000) b_matrix = csa_info['tags']['B_matrix'] - assert_equal(len(b_matrix['items']), 6) + assert len(b_matrix['items']) == 6 b_value = csa_info['tags']['B_value'] - assert_equal(b_value['items'], [1000]) + assert b_value['items'] == [1000] def test_csa_len0(): # We did get a failure for item with item_len of 0 - gh issue #92 csa_info = csa.read(CSA2_0len) - assert_equal(csa_info['type'], 2) - assert_equal(csa_info['n_tags'], 44) + assert csa_info['type'] == 2 + assert csa_info['n_tags'] == 44 tags = csa_info['tags'] - assert_equal(len(tags), 44) + assert len(tags) == 44 def test_csa_nitem(): # testing csa.read's ability to raise an error when n_items >= 200 - assert_raises(csa.CSAReadError, csa.read, CSA_STR_1001n_items) + with pytest.raises(csa.CSAReadError): + csa.read(CSA_STR_1001n_items) # OK when < 1000 csa_info = csa.read(CSA_STR_valid) - assert_equal(len(csa_info['tags']), 1) + assert len(csa_info['tags']) == 1 # OK after changing module global n_items_thresh = csa.MAX_CSA_ITEMS try: csa.MAX_CSA_ITEMS = 2000 csa_info = csa.read(CSA_STR_1001n_items) - assert_equal(len(csa_info['tags']), 1) + assert len(csa_info['tags']) == 1 finally: csa.MAX_CSA_ITEMS = n_items_thresh @@ -88,32 +88,30 @@ def test_csa_params(): for csa_str in (CSA2_B0, CSA2_B1000): csa_info = csa.read(csa_str) n_o_m = csa.get_n_mosaic(csa_info) - assert_equal(n_o_m, 48) + assert n_o_m == 48 snv = csa.get_slice_normal(csa_info) - assert_equal(snv.shape, (3,)) - assert_true(np.allclose(1, - np.sqrt((snv * snv).sum()))) + assert snv.shape == (3,) + assert np.allclose(1, np.sqrt((snv * snv).sum())) amt = csa.get_acq_mat_txt(csa_info) - assert_equal(amt, '128p*128') + assert amt == '128p*128' csa_info = csa.read(CSA2_B0) b_matrix = csa.get_b_matrix(csa_info) - assert_equal(b_matrix, None) + assert b_matrix is None b_value = csa.get_b_value(csa_info) - assert_equal(b_value, 0) + assert b_value == 0 g_vector = csa.get_g_vector(csa_info) - assert_equal(g_vector, None) + assert g_vector is None csa_info = csa.read(CSA2_B1000) b_matrix = csa.get_b_matrix(csa_info) - assert_equal(b_matrix.shape, (3, 3)) + assert b_matrix.shape == (3, 3) # check (by absence of error) that the B matrix is positive # semi-definite. dwp.B2q(b_matrix) # no error b_value = csa.get_b_value(csa_info) - assert_equal(b_value, 1000) + assert b_value == 1000 g_vector = csa.get_g_vector(csa_info) - assert_equal(g_vector.shape, (3,)) - assert_true( - np.allclose(1, np.sqrt((g_vector * g_vector).sum()))) + assert g_vector.shape == (3,) + assert np.allclose(1, np.sqrt((g_vector * g_vector).sum())) def test_ice_dims(): @@ -124,9 +122,8 @@ def test_ice_dims(): for csa_str, ex_dims in ((CSA2_B0, ex_dims0), (CSA2_B1000, ex_dims1)): csa_info = csa.read(csa_str) - assert_equal(csa.get_ice_dims(csa_info), - ex_dims) - assert_equal(csa.get_ice_dims({}), None) + assert csa.get_ice_dims(csa_info) == ex_dims + assert csa.get_ice_dims({}) is None @dicom_test @@ -138,4 +135,4 @@ def test_missing_csa_elem(): csa_tag = pydicom.dataset.Tag(0x29, 0x1010) del dcm[csa_tag] hdr = csa.get_csa_header(dcm, 'image') - assert_equal(hdr, None) + assert hdr is None diff --git a/nibabel/nicom/tests/test_dicomreaders.py b/nibabel/nicom/tests/test_dicomreaders.py index cb03aae74b..167cb26de6 100644 --- a/nibabel/nicom/tests/test_dicomreaders.py +++ b/nibabel/nicom/tests/test_dicomreaders.py @@ -2,20 +2,17 @@ """ -from os.path import join as pjoin, abspath +from os.path import join as pjoin import numpy as np from .. import dicomreaders as didr +from ...pydicom_compat import pydicom -from nibabel.pydicom_compat import dicom_test, pydicom +import pytest +from . import dicom_test -from .test_dicomwrappers import (EXPECTED_AFFINE, - EXPECTED_PARAMS, - IO_DATA_PATH, - DATA) - -from nose.tools import (assert_true, assert_false, assert_equal, assert_raises) +from .test_dicomwrappers import EXPECTED_AFFINE, EXPECTED_PARAMS, IO_DATA_PATH, DATA from numpy.testing import assert_array_equal, assert_array_almost_equal @@ -24,7 +21,7 @@ def test_read_dwi(): img = didr.mosaic_to_nii(DATA) arr = img.get_data() - assert_equal(arr.shape, (128, 128, 48)) + assert arr.shape == (128, 128, 48) assert_array_almost_equal(img.affine, EXPECTED_AFFINE) @@ -32,11 +29,12 @@ def test_read_dwi(): def test_read_dwis(): data, aff, bs, gs = didr.read_mosaic_dwi_dir(IO_DATA_PATH, 'siemens_dwi_*.dcm.gz') - assert_equal(data.ndim, 4) + assert data.ndim == 4 assert_array_almost_equal(aff, EXPECTED_AFFINE) assert_array_almost_equal(bs, (0, EXPECTED_PARAMS[0])) assert_array_almost_equal(gs, (np.zeros((3,)), EXPECTED_PARAMS[1])) - assert_raises(IOError, didr.read_mosaic_dwi_dir, 'improbable') + with pytest.raises(IOError): + didr.read_mosaic_dwi_dir('improbable') @dicom_test @@ -53,29 +51,21 @@ def test_passing_kwds(): dicom_kwargs=dict(force=True)) assert_array_equal(data, data2) # This should raise an error in pydicom.dicomio.read_file - assert_raises(TypeError, - func, - IO_DATA_PATH, - dwi_glob, - dicom_kwargs=dict(not_a_parameter=True)) + with pytest.raises(TypeError): + func(IO_DATA_PATH, dwi_glob, dicom_kwargs=dict(not_a_parameter=True)) # These are invalid dicoms, so will raise an error unless force=True - assert_raises(pydicom.filereader.InvalidDicomError, - func, - IO_DATA_PATH, - csa_glob) + with pytest.raises(pydicom.filereader.InvalidDicomError): + func(IO_DATA_PATH, csa_glob) # But here, we catch the error because the dicoms are in the wrong # format - assert_raises(didr.DicomReadError, - func, - IO_DATA_PATH, - csa_glob, - dicom_kwargs=dict(force=True)) + with pytest.raises(didr.DicomReadError): + func(IO_DATA_PATH, csa_glob, dicom_kwargs=dict(force=True)) @dicom_test def test_slices_to_series(): dicom_files = (pjoin(IO_DATA_PATH, "%d.dcm" % i) for i in range(2)) wrappers = [didr.wrapper_from_file(f) for f in dicom_files] series = didr.slices_to_series(wrappers) - assert_equal(len(series), 1) - assert_equal(len(series[0]), 2) + assert len(series) == 1 + assert len(series[0]) == 2 diff --git a/nibabel/nicom/tests/test_dicomwrappers.py b/nibabel/nicom/tests/test_dicomwrappers.py index c78249c381..0bb875002b 100755 --- a/nibabel/nicom/tests/test_dicomwrappers.py +++ b/nibabel/nicom/tests/test_dicomwrappers.py @@ -9,18 +9,17 @@ import numpy as np -from nibabel.pydicom_compat import (have_dicom, pydicom, read_file, dicom_test, - tag_for_keyword) +from nibabel.pydicom_compat import have_dicom, pydicom, read_file, tag_for_keyword from .. import dicomwrappers as didw from .. import dicomreaders as didr from ...volumeutils import endian_codes +import pytest from unittest import TestCase -from nose.tools import (assert_true, assert_false, assert_equal, - assert_not_equal, assert_raises) +from . import dicom_test -from numpy.testing import assert_array_equal, assert_array_almost_equal, assert_warns +from numpy.testing import assert_array_equal, assert_array_almost_equal from ...tests.nibabel_data import get_nibabel_data, needs_nibabel_data IO_DATA_PATH = pjoin(dirname(__file__), 'data') @@ -71,31 +70,37 @@ def test_wrappers(): (didw.MosaicWrapper, ({}, None, 10)), (didw.MultiframeWrapper, (multi_minimal,))): dw = maker(*args) - assert_equal(dw.get('InstanceNumber'), None) - assert_equal(dw.get('AcquisitionNumber'), None) - assert_raises(KeyError, dw.__getitem__, 'not an item') - assert_raises(didw.WrapperError, dw.get_data) - assert_raises(didw.WrapperError, dw.get_affine) - assert_raises(TypeError, maker) + assert dw.get('InstanceNumber') is None + assert dw.get('AcquisitionNumber') is None + with pytest.raises(KeyError): + dw['not an item'] + with pytest.raises(didw.WrapperError): + dw.get_data() + with pytest.raises(didw.WrapperError): + dw.affine + with pytest.raises(TypeError): + maker() # Check default attributes if not maker is didw.MosaicWrapper: - assert_false(dw.is_mosaic) - assert_equal(dw.b_matrix, None) - assert_equal(dw.q_vector, None) + assert not dw.is_mosaic + assert dw.b_matrix is None + assert dw.q_vector is None for maker in (didw.wrapper_from_data, didw.Wrapper, didw.SiemensWrapper, didw.MosaicWrapper ): dw = maker(DATA) - assert_equal(dw.get('InstanceNumber'), 2) - assert_equal(dw.get('AcquisitionNumber'), 2) - assert_raises(KeyError, dw.__getitem__, 'not an item') + assert dw.get('InstanceNumber') == 2 + assert dw.get('AcquisitionNumber') == 2 + with pytest.raises(KeyError): + dw['not an item'] for maker in (didw.MosaicWrapper, didw.wrapper_from_data): dw = maker(DATA) - assert_true(dw.is_mosaic) + assert dw.is_mosaic # DATA is not a Multiframe DICOM file - assert_raises(didw.WrapperError, didw.MultiframeWrapper, DATA) + with pytest.raises(didw.WrapperError): + didw.MultiframeWrapper(DATA) def test_get_from_wrapper(): @@ -103,12 +108,13 @@ def test_get_from_wrapper(): # data dcm_data = {'some_key': 'some value'} dw = didw.Wrapper(dcm_data) - assert_equal(dw.get('some_key'), 'some value') - assert_equal(dw.get('some_other_key'), None) + assert dw.get('some_key') == 'some value' + assert dw.get('some_other_key') is None # Getitem uses the same dictionary access - assert_equal(dw['some_key'], 'some value') + assert dw['some_key'] == 'some value' # And raises a WrapperError for missing keys - assert_raises(KeyError, dw.__getitem__, 'some_other_key') + with pytest.raises(KeyError): + dw['some_other_key'] # Test we don't use attributes for get class FakeData(dict): @@ -116,7 +122,7 @@ class FakeData(dict): d = FakeData() d.some_key = 'another bit of data' dw = didw.Wrapper(d) - assert_equal(dw.get('some_key'), None) + assert dw.get('some_key') is None # Check get defers to dcm_data get class FakeData2(object): @@ -126,7 +132,7 @@ def get(self, key, default): d = FakeData2() d.some_key = 'another bit of data' dw = didw.Wrapper(d) - assert_equal(dw.get('some_key'), 1) + assert dw.get('some_key') == 1 @dicom_test @@ -134,36 +140,40 @@ def test_wrapper_from_data(): # test wrapper from data, wrapper from file for dw in (didw.wrapper_from_data(DATA), didw.wrapper_from_file(DATA_FILE)): - assert_equal(dw.get('InstanceNumber'), 2) - assert_equal(dw.get('AcquisitionNumber'), 2) - assert_raises(KeyError, dw.__getitem__, 'not an item') - assert_true(dw.is_mosaic) + assert dw.get('InstanceNumber') == 2 + assert dw.get('AcquisitionNumber') == 2 + with pytest.raises(KeyError): + dw['not an item'] + assert dw.is_mosaic assert_array_almost_equal( - np.dot(didr.DPCS_TO_TAL, dw.get_affine()), + np.dot(didr.DPCS_TO_TAL, dw.affine), EXPECTED_AFFINE) for dw in (didw.wrapper_from_data(DATA_PHILIPS), didw.wrapper_from_file(DATA_FILE_PHILIPS)): - assert_equal(dw.get('InstanceNumber'), 1) - assert_equal(dw.get('AcquisitionNumber'), 3) - assert_raises(KeyError, dw.__getitem__, 'not an item') - assert_true(dw.is_multiframe) + assert dw.get('InstanceNumber') == 1 + assert dw.get('AcquisitionNumber') == 3 + with pytest.raises(KeyError): + dw['not an item'] + assert dw.is_multiframe # Another CSA file dw = didw.wrapper_from_file(DATA_FILE_SLC_NORM) - assert_true(dw.is_mosaic) + assert dw.is_mosaic # Check that multiframe requires minimal set of DICOM tags fake_data = dict() fake_data['SOPClassUID'] = '1.2.840.10008.5.1.4.1.1.4.2' dw = didw.wrapper_from_data(fake_data) - assert_false(dw.is_multiframe) + assert not dw.is_multiframe # use the correct SOPClassUID fake_data['SOPClassUID'] = '1.2.840.10008.5.1.4.1.1.4.1' - assert_raises(didw.WrapperError, didw.wrapper_from_data, fake_data) + with pytest.raises(didw.WrapperError): + didw.wrapper_from_data(fake_data) fake_data['PerFrameFunctionalGroupsSequence'] = [None] - assert_raises(didw.WrapperError, didw.wrapper_from_data, fake_data) + with pytest.raises(didw.WrapperError): + didw.wrapper_from_data(fake_data) fake_data['SharedFunctionalGroupsSequence'] = [None] # minimal set should now be met dw = didw.wrapper_from_data(fake_data) - assert_true(dw.is_multiframe) + assert dw.is_multiframe @dicom_test @@ -179,19 +189,18 @@ def test_wrapper_args_kwds(): assert_array_equal(data, dcm2.get_data()) # Trying to read non-dicom file raises pydicom error, usually csa_fname = pjoin(IO_DATA_PATH, 'csa2_b0.bin') - assert_raises(pydicom.filereader.InvalidDicomError, - didw.wrapper_from_file, - csa_fname) + with pytest.raises(pydicom.filereader.InvalidDicomError): + didw.wrapper_from_file(csa_fname) # We can force the read, in which case rubbish returns dcm_malo = didw.wrapper_from_file(csa_fname, force=True) - assert_false(dcm_malo.is_mosaic) + assert not dcm_malo.is_mosaic @dicom_test def test_dwi_params(): dw = didw.wrapper_from_data(DATA) b_matrix = dw.b_matrix - assert_equal(b_matrix.shape, (3, 3)) + assert b_matrix.shape == (3, 3) q = dw.q_vector b = np.sqrt(np.sum(q * q)) # vector norm g = q / b @@ -204,9 +213,9 @@ def test_q_vector_etc(): # Test diffusion params in wrapper classes # Default is no q_vector, b_value, b_vector dw = didw.Wrapper(DATA) - assert_equal(dw.q_vector, None) - assert_equal(dw.b_value, None) - assert_equal(dw.b_vector, None) + assert dw.q_vector is None + assert dw.b_value is None + assert dw.b_vector is None for pos in range(3): q_vec = np.zeros((3,)) q_vec[pos] = 10. @@ -214,12 +223,12 @@ def test_q_vector_etc(): dw = didw.Wrapper(DATA) dw.q_vector = q_vec assert_array_equal(dw.q_vector, q_vec) - assert_equal(dw.b_value, 10) + assert dw.b_value == 10 assert_array_equal(dw.b_vector, q_vec / 10.) # Reset wrapped dicom to refresh one_time property dw = didw.Wrapper(DATA) dw.q_vector = np.array([0, 0, 1e-6]) - assert_equal(dw.b_value, 0) + assert dw.b_value == 0 assert_array_equal(dw.b_vector, np.zeros((3,))) # Test MosaicWrapper sdw = didw.MosaicWrapper(DATA) @@ -230,7 +239,7 @@ def test_q_vector_etc(): # Reset wrapped dicom to refresh one_time property sdw = didw.MosaicWrapper(DATA) sdw.q_vector = np.array([0, 0, 1e-6]) - assert_equal(sdw.b_value, 0) + assert sdw.b_value == 0 assert_array_equal(sdw.b_vector, np.zeros((3,))) @@ -238,51 +247,51 @@ def test_q_vector_etc(): def test_vol_matching(): # make the Siemens wrapper, check it compares True against itself dw_siemens = didw.wrapper_from_data(DATA) - assert_true(dw_siemens.is_mosaic) - assert_true(dw_siemens.is_csa) - assert_true(dw_siemens.is_same_series(dw_siemens)) + assert dw_siemens.is_mosaic + assert dw_siemens.is_csa + assert dw_siemens.is_same_series(dw_siemens) # make plain wrapper, compare against itself dw_plain = didw.Wrapper(DATA) - assert_false(dw_plain.is_mosaic) - assert_false(dw_plain.is_csa) - assert_true(dw_plain.is_same_series(dw_plain)) + assert not dw_plain.is_mosaic + assert not dw_plain.is_csa + assert dw_plain.is_same_series(dw_plain) # specific vs plain wrapper compares False, because the Siemens # wrapper has more non-empty information - assert_false(dw_plain.is_same_series(dw_siemens)) + assert not dw_plain.is_same_series(dw_siemens) # and this should be symmetric - assert_false(dw_siemens.is_same_series(dw_plain)) + assert not dw_siemens.is_same_series(dw_plain) # we can even make an empty wrapper. This compares True against # itself but False against the others dw_empty = didw.Wrapper({}) - assert_true(dw_empty.is_same_series(dw_empty)) - assert_false(dw_empty.is_same_series(dw_plain)) - assert_false(dw_plain.is_same_series(dw_empty)) + assert dw_empty.is_same_series(dw_empty) + assert not dw_empty.is_same_series(dw_plain) + assert not dw_plain.is_same_series(dw_empty) # Just to check the interface, make a pretend signature-providing # object. class C(object): series_signature = {} - assert_true(dw_empty.is_same_series(C())) + assert dw_empty.is_same_series(C()) # make the Philips wrapper, check it compares True against itself dw_philips = didw.wrapper_from_data(DATA_PHILIPS) - assert_true(dw_philips.is_multiframe) - assert_true(dw_philips.is_same_series(dw_philips)) + assert dw_philips.is_multiframe + assert dw_philips.is_same_series(dw_philips) # make plain wrapper, compare against itself dw_plain_philips = didw.Wrapper(DATA) - assert_false(dw_plain_philips.is_multiframe) - assert_true(dw_plain_philips.is_same_series(dw_plain_philips)) + assert not dw_plain_philips.is_multiframe + assert dw_plain_philips.is_same_series(dw_plain_philips) # specific vs plain wrapper compares False, because the Philips # wrapper has more non-empty information - assert_false(dw_plain_philips.is_same_series(dw_philips)) + assert not dw_plain_philips.is_same_series(dw_philips) # and this should be symmetric - assert_false(dw_philips.is_same_series(dw_plain_philips)) + assert not dw_philips.is_same_series(dw_plain_philips) # we can even make an empty wrapper. This compares True against # itself but False against the others dw_empty = didw.Wrapper({}) - assert_true(dw_empty.is_same_series(dw_empty)) - assert_false(dw_empty.is_same_series(dw_plain_philips)) - assert_false(dw_plain_philips.is_same_series(dw_empty)) + assert dw_empty.is_same_series(dw_empty) + assert not dw_empty.is_same_series(dw_plain_philips) + assert not dw_plain_philips.is_same_series(dw_empty) @dicom_test @@ -290,10 +299,10 @@ def test_slice_indicator(): dw_0 = didw.wrapper_from_file(DATA_FILE_B0) dw_1000 = didw.wrapper_from_data(DATA) z = dw_0.slice_indicator - assert_false(z is None) - assert_equal(z, dw_1000.slice_indicator) + assert not z is None + assert z == dw_1000.slice_indicator dw_empty = didw.Wrapper({}) - assert_true(dw_empty.slice_indicator is None) + assert dw_empty.slice_indicator is None @dicom_test @@ -301,7 +310,7 @@ def test_orthogonal(): # Test that the slice normal is sufficiently orthogonal dw = didw.wrapper_from_file(DATA_FILE_SLC_NORM) R = dw.rotation_matrix - assert_true(np.allclose(np.eye(3), np.dot(R, R.T), atol=1e-6)) + assert np.allclose(np.eye(3), np.dot(R, R.T), atol=1e-6) # Test the threshold for rotation matrix orthogonality d = {} @@ -313,7 +322,8 @@ def test_orthogonal(): assert_array_almost_equal(dw.rotation_matrix, np.eye(3), 5) d['ImageOrientationPatient'] = [1e-4, 1, 0, 1, 0, 0] dw = didw.wrapper_from_data(d) - assert_raises(didw.WrapperPrecisionError, getattr, dw, 'rotation_matrix') + with pytest.raises(didw.WrapperPrecisionError): + dw.rotation_matrix @dicom_test @@ -338,7 +348,7 @@ def test_use_csa_sign(): iop = dw.image_orient_patient dw.image_orient_patient = np.c_[iop[:, 1], iop[:, 0]] dw2 = didw.wrapper_from_file(DATA_FILE_SLC_NORM) - assert_true(np.allclose(dw.slice_normal, dw2.slice_normal)) + assert np.allclose(dw.slice_normal, dw2.slice_normal) @dicom_test @@ -347,7 +357,8 @@ def test_assert_parallel(): # slice normal are not parallel dw = didw.wrapper_from_file(DATA_FILE_SLC_NORM) dw.image_orient_patient = np.c_[[1., 0., 0.], [0., 1., 0.]] - assert_raises(AssertionError, dw.__getattribute__, 'slice_normal') + with pytest.raises(AssertionError): + dw.slice_normal @dicom_test @@ -355,7 +366,7 @@ def test_decimal_rescale(): # Test that we don't get back a data array with dtype np.object when our # rescale slope is a decimal dw = didw.wrapper_from_file(DATA_FILE_DEC_RSCL) - assert_not_equal(dw.get_data().dtype, np.object) + assert dw.get_data().dtype != np.object def fake_frames(seq_name, field_name, value_seq): @@ -449,84 +460,95 @@ def test_shape(self): MFW = self.WRAPCLASS dw = MFW(fake_mf) # No rows, cols, raise WrapperError - assert_raises(didw.WrapperError, getattr, dw, 'image_shape') + with pytest.raises(didw.WrapperError): + dw.image_shape fake_mf['Rows'] = 64 - assert_raises(didw.WrapperError, getattr, dw, 'image_shape') + with pytest.raises(didw.WrapperError): + dw.image_shape fake_mf.pop('Rows') fake_mf['Columns'] = 64 - assert_raises(didw.WrapperError, getattr, dw, 'image_shape') + with pytest.raises(didw.WrapperError): + dw.image_shape fake_mf['Rows'] = 32 # Missing frame data, raise AssertionError - assert_raises(AssertionError, getattr, dw, 'image_shape') + with pytest.raises(AssertionError): + dw.image_shape fake_mf['NumberOfFrames'] = 4 # PerFrameFunctionalGroupsSequence does not match NumberOfFrames - assert_raises(AssertionError, getattr, dw, 'image_shape') + with pytest.raises(AssertionError): + dw.image_shape # check 3D shape when StackID index is 0 div_seq = ((1, 1), (1, 2), (1, 3), (1, 4)) fake_mf.update(fake_shape_dependents(div_seq, sid_dim=0)) - assert_equal(MFW(fake_mf).image_shape, (32, 64, 4)) + assert MFW(fake_mf).image_shape == (32, 64, 4) # Check stack number matching when StackID index is 0 div_seq = ((1, 1), (1, 2), (1, 3), (2, 4)) fake_mf.update(fake_shape_dependents(div_seq, sid_dim=0)) - assert_raises(didw.WrapperError, getattr, MFW(fake_mf), 'image_shape') + with pytest.raises(didw.WrapperError): + MFW(fake_mf).image_shape # Make some fake frame data for 4D when StackID index is 0 div_seq = ((1, 1, 1), (1, 2, 1), (1, 1, 2), (1, 2, 2), (1, 1, 3), (1, 2, 3)) fake_mf.update(fake_shape_dependents(div_seq, sid_dim=0)) - assert_equal(MFW(fake_mf).image_shape, (32, 64, 2, 3)) + assert MFW(fake_mf).image_shape == (32, 64, 2, 3) # Check stack number matching for 4D when StackID index is 0 div_seq = ((1, 1, 1), (1, 2, 1), (1, 1, 2), (1, 2, 2), (1, 1, 3), (2, 2, 3)) fake_mf.update(fake_shape_dependents(div_seq, sid_dim=0)) - assert_raises(didw.WrapperError, getattr, MFW(fake_mf), 'image_shape') + with pytest.raises(didw.WrapperError): + MFW(fake_mf).image_shape # Check indices can be non-contiguous when StackID index is 0 div_seq = ((1, 1, 1), (1, 2, 1), (1, 1, 3), (1, 2, 3)) fake_mf.update(fake_shape_dependents(div_seq, sid_dim=0)) - assert_equal(MFW(fake_mf).image_shape, (32, 64, 2, 2)) + assert MFW(fake_mf).image_shape == (32, 64, 2, 2) # Check indices can include zero when StackID index is 0 div_seq = ((1, 1, 0), (1, 2, 0), (1, 1, 3), (1, 2, 3)) fake_mf.update(fake_shape_dependents(div_seq, sid_dim=0)) - assert_equal(MFW(fake_mf).image_shape, (32, 64, 2, 2)) + assert MFW(fake_mf).image_shape == (32, 64, 2, 2) # check 3D shape when there is no StackID index div_seq = ((1,), (2,), (3,), (4,)) sid_seq = (1, 1, 1, 1) fake_mf.update(fake_shape_dependents(div_seq, sid_seq=sid_seq)) - assert_equal(MFW(fake_mf).image_shape, (32, 64, 4)) + assert MFW(fake_mf).image_shape == (32, 64, 4) # check 3D stack number matching when there is no StackID index div_seq = ((1,), (2,), (3,), (4,)) sid_seq = (1, 1, 1, 2) fake_mf.update(fake_shape_dependents(div_seq, sid_seq=sid_seq)) - assert_raises(didw.WrapperError, getattr, MFW(fake_mf), 'image_shape') + with pytest.raises(didw.WrapperError): + MFW(fake_mf).image_shape # check 4D shape when there is no StackID index div_seq = ((1, 1), (2, 1), (1, 2), (2, 2), (1, 3), (2, 3)) sid_seq = (1, 1, 1, 1, 1, 1) fake_mf.update(fake_shape_dependents(div_seq, sid_seq=sid_seq)) - assert_equal(MFW(fake_mf).image_shape, (32, 64, 2, 3)) + assert MFW(fake_mf).image_shape == (32, 64, 2, 3) # check 4D stack number matching when there is no StackID index div_seq = ((1, 1), (2, 1), (1, 2), (2, 2), (1, 3), (2, 3)) sid_seq = (1, 1, 1, 1, 1, 2) fake_mf.update(fake_shape_dependents(div_seq, sid_seq=sid_seq)) - assert_raises(didw.WrapperError, getattr, MFW(fake_mf), 'image_shape') + with pytest.raises(didw.WrapperError): + MFW(fake_mf).image_shape # check 3D shape when StackID index is 1 div_seq = ((1, 1), (2, 1), (3, 1), (4, 1)) fake_mf.update(fake_shape_dependents(div_seq, sid_dim=1)) - assert_equal(MFW(fake_mf).image_shape, (32, 64, 4)) + assert MFW(fake_mf).image_shape == (32, 64, 4) # Check stack number matching when StackID index is 1 div_seq = ((1, 1), (2, 1), (3, 2), (4, 1)) fake_mf.update(fake_shape_dependents(div_seq, sid_dim=1)) - assert_raises(didw.WrapperError, getattr, MFW(fake_mf), 'image_shape') + with pytest.raises(didw.WrapperError): + MFW(fake_mf).image_shape # Make some fake frame data for 4D when StackID index is 1 div_seq = ((1, 1, 1), (2, 1, 1), (1, 1, 2), (2, 1, 2), (1, 1, 3), (2, 1, 3)) fake_mf.update(fake_shape_dependents(div_seq, sid_dim=1)) - assert_equal(MFW(fake_mf).image_shape, (32, 64, 2, 3)) + assert MFW(fake_mf).image_shape == (32, 64, 2, 3) def test_iop(self): # Test Image orient patient for multiframe fake_mf = copy(self.MINIMAL_MF) MFW = self.WRAPCLASS dw = MFW(fake_mf) - assert_raises(didw.WrapperError, getattr, dw, 'image_orient_patient') + with pytest.raises(didw.WrapperError): + dw.image_orient_patient # Make a fake frame fake_frame = fake_frames('PlaneOrientationSequence', 'ImageOrientationPatient', @@ -535,8 +557,8 @@ def test_iop(self): assert_array_equal(MFW(fake_mf).image_orient_patient, [[0, 1], [1, 0], [0, 0]]) fake_mf['SharedFunctionalGroupsSequence'] = [None] - assert_raises(didw.WrapperError, - getattr, MFW(fake_mf), 'image_orient_patient') + with pytest.raises(didw.WrapperError): + MFW(fake_mf).image_orient_patient fake_mf['PerFrameFunctionalGroupsSequence'] = [fake_frame] assert_array_equal(MFW(fake_mf).image_orient_patient, [[0, 1], [1, 0], [0, 0]]) @@ -546,14 +568,16 @@ def test_voxel_sizes(self): fake_mf = copy(self.MINIMAL_MF) MFW = self.WRAPCLASS dw = MFW(fake_mf) - assert_raises(didw.WrapperError, getattr, dw, 'voxel_sizes') + with pytest.raises(didw.WrapperError): + dw.voxel_sizes # Make a fake frame fake_frame = fake_frames('PixelMeasuresSequence', 'PixelSpacing', [[2.1, 3.2]])[0] fake_mf['SharedFunctionalGroupsSequence'] = [fake_frame] # Still not enough, we lack information for slice distances - assert_raises(didw.WrapperError, getattr, MFW(fake_mf), 'voxel_sizes') + with pytest.raises(didw.WrapperError): + MFW(fake_mf).voxel_sizes # This can come from SpacingBetweenSlices or frame SliceThickness fake_mf['SpacingBetweenSlices'] = 4.3 assert_array_equal(MFW(fake_mf).voxel_sizes, [2.1, 3.2, 4.3]) @@ -565,7 +589,8 @@ def test_voxel_sizes(self): assert_array_equal(MFW(fake_mf).voxel_sizes, [2.1, 3.2, 5.4]) # Removing shared leads to error again fake_mf['SharedFunctionalGroupsSequence'] = [None] - assert_raises(didw.WrapperError, getattr, MFW(fake_mf), 'voxel_sizes') + with pytest.raises(didw.WrapperError): + MFW(fake_mf).voxel_sizes # Restoring to frames makes it work again fake_mf['PerFrameFunctionalGroupsSequence'] = [fake_frame] assert_array_equal(MFW(fake_mf).voxel_sizes, [2.1, 3.2, 5.4]) @@ -584,7 +609,8 @@ def test_image_position(self): fake_mf = copy(self.MINIMAL_MF) MFW = self.WRAPCLASS dw = MFW(fake_mf) - assert_raises(didw.WrapperError, getattr, dw, 'image_position') + with pytest.raises(didw.WrapperError): + dw.image_position # Make a fake frame fake_frame = fake_frames('PlanePositionSequence', 'ImagePositionPatient', @@ -592,21 +618,23 @@ def test_image_position(self): fake_mf['SharedFunctionalGroupsSequence'] = [fake_frame] assert_array_equal(MFW(fake_mf).image_position, [-2, 3, 7]) fake_mf['SharedFunctionalGroupsSequence'] = [None] - assert_raises(didw.WrapperError, - getattr, MFW(fake_mf), 'image_position') + with pytest.raises(didw.WrapperError): + MFW(fake_mf).image_position fake_mf['PerFrameFunctionalGroupsSequence'] = [fake_frame] assert_array_equal(MFW(fake_mf).image_position, [-2, 3, 7]) # Check lists of Decimals work fake_frame.PlanePositionSequence[0].ImagePositionPatient = [ Decimal(str(v)) for v in [-2, 3, 7]] assert_array_equal(MFW(fake_mf).image_position, [-2, 3, 7]) - assert_equal(MFW(fake_mf).image_position.dtype, float) + assert MFW(fake_mf).image_position.dtype == float @dicom_test def test_affine(self): # Make sure we find orientation/position/spacing info dw = didw.wrapper_from_file(DATA_FILE_4D) - dw.get_affine() + aff = dw.affine + with pytest.deprecated_call(): + assert np.array_equal(dw.get_affine(), aff) @dicom_test def test_data_real(self): @@ -619,13 +647,12 @@ def test_data_real(self): if endian_codes[data.dtype.byteorder] == '>': data = data.byteswap() dat_str = data.tostring() - assert_equal(sha1(dat_str).hexdigest(), - '149323269b0af92baa7508e19ca315240f77fa8c') + assert sha1(dat_str).hexdigest() == '149323269b0af92baa7508e19ca315240f77fa8c' @dicom_test def test_slicethickness_fallback(self): dw = didw.wrapper_from_file(DATA_FILE_EMPTY_ST) - assert_equal(dw.voxel_sizes[2], 1.0) + assert dw.voxel_sizes[2] == 1.0 @dicom_test @needs_nibabel_data('nitest-dicom') @@ -633,14 +660,15 @@ def test_data_derived_shape(self): # Test 4D diffusion data with an additional trace volume included # Excludes the trace volume and generates the correct shape dw = didw.wrapper_from_file(DATA_FILE_4D_DERIVED) - assert_equal(dw.image_shape, (96, 96, 60, 33)) + assert dw.image_shape == (96, 96, 60, 33) @dicom_test @needs_nibabel_data('nitest-dicom') def test_data_unreadable_private_headers(self): # Test CT image with unreadable CSA tags - dw = assert_warns(UserWarning, didw.wrapper_from_file, DATA_FILE_CT) - assert_equal(dw.image_shape, (512, 571)) + with pytest.warns(UserWarning): + dw = didw.wrapper_from_file(DATA_FILE_CT) + assert dw.image_shape == (512, 571) @dicom_test def test_data_fake(self): @@ -649,19 +677,22 @@ def test_data_fake(self): MFW = self.WRAPCLASS dw = MFW(fake_mf) # Fails - no shape - assert_raises(didw.WrapperError, dw.get_data) + with pytest.raises(didw.WrapperError): + dw.get_data() # Set shape by cheating dw.image_shape = (2, 3, 4) # Still fails - no data - assert_raises(didw.WrapperError, dw.get_data) + with pytest.raises(didw.WrapperError): + dw.get_data() # Make shape and indices fake_mf['Rows'] = 2 fake_mf['Columns'] = 3 dim_idxs = ((1, 1), (1, 2), (1, 3), (1, 4)) fake_mf.update(fake_shape_dependents(dim_idxs, sid_dim=0)) - assert_equal(MFW(fake_mf).image_shape, (2, 3, 4)) + assert MFW(fake_mf).image_shape == (2, 3, 4) # Still fails - no data - assert_raises(didw.WrapperError, dw.get_data) + with pytest.raises(didw.WrapperError): + dw.get_data() # Add data - 3D data = np.arange(24).reshape((2, 3, 4)) # Frames dim is first for some reason @@ -723,7 +754,8 @@ def test__scale_data(self): fake_mf['PerFrameFunctionalGroupsSequence'] = [fake_frame] # Lacking RescaleIntercept -> Error dw = MFW(fake_mf) - assert_raises(AttributeError, dw._scale_data, data) + with pytest.raises(AttributeError): + dw._scale_data(data) fake_frame.PixelValueTransformationSequence[0].RescaleIntercept = -2 assert_array_equal(data * 3 - 2, dw._scale_data(data)) # Decimals are OK diff --git a/nibabel/nicom/tests/test_dwiparams.py b/nibabel/nicom/tests/test_dwiparams.py index 3b02367951..d0d20e574a 100644 --- a/nibabel/nicom/tests/test_dwiparams.py +++ b/nibabel/nicom/tests/test_dwiparams.py @@ -6,10 +6,9 @@ from ..dwiparams import B2q, q2bg -from nose.tools import (assert_true, assert_false, assert_equal, assert_raises) +import pytest -from numpy.testing import (assert_array_equal, assert_array_almost_equal, - assert_equal as np_assert_equal) +from numpy.testing import (assert_array_almost_equal, assert_equal as np_assert_equal) def test_b2q(): @@ -27,17 +26,20 @@ def test_b2q(): assert_array_almost_equal(-q * s, B2q(B)) # Massive negative eigs B = np.eye(3) * -1 - assert_raises(ValueError, B2q, B) + with pytest.raises(ValueError): + B2q(B) # no error if we up the tolerance q = B2q(B, tol=1) # Less massive negativity, dropping tol B = np.diag([-1e-14, 10., 1]) - assert_raises(ValueError, B2q, B) + with pytest.raises(ValueError): + B2q(B) assert_array_almost_equal(B2q(B, tol=5e-13), [0, 10, 0]) # Confirm that we assume symmetric B = np.eye(3) B[0, 1] = 1e-5 - assert_raises(ValueError, B2q, B) + with pytest.raises(ValueError): + B2q(B) def test_q2bg(): diff --git a/nibabel/nicom/tests/test_structreader.py b/nibabel/nicom/tests/test_structreader.py index 05461d18a0..6e58931559 100644 --- a/nibabel/nicom/tests/test_structreader.py +++ b/nibabel/nicom/tests/test_structreader.py @@ -5,9 +5,6 @@ from ..structreader import Unpacker -from nose.tools import (assert_true, assert_false, assert_equal, assert_raises) - - def test_unpacker(): s = b'1234\x00\x01' @@ -22,30 +19,30 @@ def test_unpacker(): swapped_int = le_int swapped_code = '<' up_str = Unpacker(s, endian='<') - assert_equal(up_str.read(4), b'1234') + assert up_str.read(4) == b'1234' up_str.ptr = 0 - assert_equal(up_str.unpack('4s'), (b'1234',)) - assert_equal(up_str.unpack('h'), (le_int,)) + assert up_str.unpack('4s') == (b'1234',) + assert up_str.unpack('h') == (le_int,) up_str = Unpacker(s, endian='>') - assert_equal(up_str.unpack('4s'), (b'1234',)) - assert_equal(up_str.unpack('h'), (be_int,)) + assert up_str.unpack('4s') == (b'1234',) + assert up_str.unpack('h') == (be_int,) # now test conflict of endian up_str = Unpacker(s, ptr=4, endian='>') - assert_equal(up_str.unpack('h'), (be_int,)) + assert up_str.unpack('>h') == (be_int,) up_str.ptr = 4 - assert_equal(up_str.unpack('@h'), (native_int,)) + assert up_str.unpack('@h') == (native_int,) # test -1 for read up_str.ptr = 2 - assert_equal(up_str.read(), b'34\x00\x01') + assert up_str.read() == b'34\x00\x01' # past end - assert_equal(up_str.read(), b'') + assert up_str.read() == b'' # with n_bytes up_str.ptr = 2 - assert_equal(up_str.read(2), b'34') - assert_equal(up_str.read(2), b'\x00\x01') + assert up_str.read(2) == b'34' + assert up_str.read(2) == b'\x00\x01' diff --git a/nibabel/nicom/tests/test_utils.py b/nibabel/nicom/tests/test_utils.py index a7ab9b6bdc..142daa3d16 100644 --- a/nibabel/nicom/tests/test_utils.py +++ b/nibabel/nicom/tests/test_utils.py @@ -2,64 +2,48 @@ """ import re - -from numpy.testing import (assert_almost_equal, - assert_array_equal) - -from nose.tools import (assert_true, assert_false, assert_raises, - assert_equal, assert_not_equal) - - from ..utils import find_private_section -from nibabel.pydicom_compat import dicom_test, pydicom -from .test_dicomwrappers import (DATA, DATA_PHILIPS) +from . import dicom_test +from ...pydicom_compat import pydicom +from .test_dicomwrappers import DATA, DATA_PHILIPS @dicom_test def test_find_private_section_real(): # Find section containing named private creator information # On real data first - assert_equal(find_private_section(DATA, 0x29, 'SIEMENS CSA HEADER'), - 0x1000) - assert_equal(find_private_section(DATA, 0x29, 'SIEMENS MEDCOM HEADER2'), - 0x1100) - assert_equal(find_private_section(DATA_PHILIPS, 0x29, 'SIEMENS CSA HEADER'), - None) + assert find_private_section(DATA, 0x29, 'SIEMENS CSA HEADER') == 0x1000 + assert find_private_section(DATA, 0x29, 'SIEMENS MEDCOM HEADER2') == 0x1100 + assert find_private_section(DATA_PHILIPS, 0x29, 'SIEMENS CSA HEADER') == None # Make fake datasets ds = pydicom.dataset.Dataset({}) ds.add_new((0x11, 0x10), 'LO', b'some section') - assert_equal(find_private_section(ds, 0x11, 'some section'), 0x1000) + assert find_private_section(ds, 0x11, 'some section') == 0x1000 ds.add_new((0x11, 0x11), 'LO', b'anther section') ds.add_new((0x11, 0x12), 'LO', b'third section') - assert_equal(find_private_section(ds, 0x11, 'third section'), 0x1200) + assert find_private_section(ds, 0x11, 'third section') == 0x1200 # Wrong 'OB' is acceptable for VM (should be 'LO') ds.add_new((0x11, 0x12), 'OB', b'third section') - assert_equal(find_private_section(ds, 0x11, 'third section'), 0x1200) + assert find_private_section(ds, 0x11, 'third section') == 0x1200 # Anything else not acceptable ds.add_new((0x11, 0x12), 'PN', b'third section') - assert_equal(find_private_section(ds, 0x11, 'third section'), None) + assert find_private_section(ds, 0x11, 'third section') is None # The input (DICOM value) can be a string insteal of bytes ds.add_new((0x11, 0x12), 'LO', 'third section') - assert_equal(find_private_section(ds, 0x11, 'third section'), 0x1200) + assert find_private_section(ds, 0x11, 'third section') == 0x1200 # Search can be bytes as well as string ds.add_new((0x11, 0x12), 'LO', b'third section') - assert_equal(find_private_section(ds, 0x11, b'third section'), 0x1200) + assert find_private_section(ds, 0x11, b'third section') == 0x1200 # Search with string or bytes must be exact - assert_equal(find_private_section(ds, 0x11, b'third sectio'), None) - assert_equal(find_private_section(ds, 0x11, 'hird sectio'), None) + assert find_private_section(ds, 0x11, b'third sectio') is None + assert find_private_section(ds, 0x11, 'hird sectio') is None # The search can be a regexp - assert_equal(find_private_section(ds, - 0x11, - re.compile(r'third\Wsectio[nN]')), - 0x1200) + assert find_private_section(ds, 0x11, re.compile(r'third\Wsectio[nN]')) == 0x1200 # No match -> None - assert_equal(find_private_section(ds, - 0x11, - re.compile(r'not third\Wsectio[nN]')), - None) + assert find_private_section(ds, 0x11, re.compile(r'not third\Wsectio[nN]')) is None # If there are gaps in the sequence before the one we want, that is OK ds.add_new((0x11, 0x13), 'LO', b'near section') - assert_equal(find_private_section(ds, 0x11, 'near section'), 0x1300) + assert find_private_section(ds, 0x11, 'near section') == 0x1300 ds.add_new((0x11, 0x15), 'LO', b'far section') - assert_equal(find_private_section(ds, 0x11, 'far section'), 0x1500) + assert find_private_section(ds, 0x11, 'far section') == 0x1500 diff --git a/nibabel/optpkg.py b/nibabel/optpkg.py index d52329f186..81dae3010c 100644 --- a/nibabel/optpkg.py +++ b/nibabel/optpkg.py @@ -1,13 +1,7 @@ """ Routines to support optional packages """ -import pkgutil from distutils.version import LooseVersion from .tripwire import TripWire -if pkgutil.find_loader('nose'): - have_nose = True -else: - have_nose = False - def _check_pkg_version(pkg, min_version): # Default version checking function @@ -116,8 +110,7 @@ def optional_package(name, trip_msg=None, min_version=None): pkg = TripWire(trip_msg) def setup_module(): - if have_nose: - import nose - raise nose.plugins.skip.SkipTest('No %s for these tests' - % name) + import unittest + raise unittest.SkipTest('No %s for these tests' % name) + return pkg, False, setup_module diff --git a/nibabel/pydicom_compat.py b/nibabel/pydicom_compat.py index beb787f315..9cca2a293d 100644 --- a/nibabel/pydicom_compat.py +++ b/nibabel/pydicom_compat.py @@ -12,13 +12,19 @@ else None; * tag_for_keyword : ``tag_for_keyword`` function if pydicom or dicom module is importable else None; + +A test decorator is available in nibabel.nicom.tests: + * dicom_test : test decorator that skips test if dicom not available. + +A deprecated copy is available here for backward compatibility. """ # Module has (apparently) unused imports; stop flake8 complaining # flake8: noqa import numpy as np +from .deprecated import deprecate_with_version have_dicom = True pydicom = read_file = tag_for_keyword = Sequence = None @@ -50,6 +56,9 @@ tag_for_keyword = pydicom.datadict.tag_for_name -# test decorator that skips test if dicom not available. -dicom_test = np.testing.dec.skipif(not have_dicom, - 'could not import dicom or pydicom') +@deprecate_with_version("dicom_test has been moved to nibabel.nicom.tests", + since="3.1", until="5.0") +def dicom_test(func): + # Import locally to avoid circular dependency + from .nicom.tests import dicom_test + return dicom_test(func) diff --git a/nibabel/streamlines/tests/test_array_sequence.py b/nibabel/streamlines/tests/test_array_sequence.py index c92580accb..06e19248f4 100644 --- a/nibabel/streamlines/tests/test_array_sequence.py +++ b/nibabel/streamlines/tests/test_array_sequence.py @@ -5,8 +5,8 @@ import itertools import numpy as np -from nose.tools import assert_equal, assert_raises, assert_true -from nibabel.testing import assert_arrays_equal +import pytest +from ...testing import assert_arrays_equal from numpy.testing import assert_array_equal from ..array_sequence import ArraySequence, is_array_sequence, concatenate @@ -15,7 +15,7 @@ SEQ_DATA = {} -def setup(): +def setup_module(): global SEQ_DATA rng = np.random.RandomState(42) SEQ_DATA['rng'] = rng @@ -30,22 +30,23 @@ def generate_data(nb_arrays, common_shape, rng): def check_empty_arr_seq(seq): - assert_equal(len(seq), 0) - assert_equal(len(seq._offsets), 0) - assert_equal(len(seq._lengths), 0) + assert len(seq) == 0 + assert len(seq._offsets) == 0 + assert len(seq._lengths) == 0 # assert_equal(seq._data.ndim, 0) - assert_equal(seq._data.ndim, 1) - assert_true(seq.common_shape == ()) + assert seq._data.ndim == 1 + assert seq.common_shape == () def check_arr_seq(seq, arrays): lengths = list(map(len, arrays)) - assert_true(is_array_sequence(seq)) - assert_equal(len(seq), len(arrays)) - assert_equal(len(seq._offsets), len(arrays)) - assert_equal(len(seq._lengths), len(arrays)) - assert_equal(seq._data.shape[1:], arrays[0].shape[1:]) - assert_equal(seq.common_shape, arrays[0].shape[1:]) + assert is_array_sequence(seq) + assert len(seq) == len(arrays) + assert len(seq._offsets) == len(arrays) + assert len(seq._lengths) == len(arrays) + assert seq._data.shape[1:] == arrays[0].shape[1:] + assert seq.common_shape == arrays[0].shape[1:] + assert_arrays_equal(seq, arrays) # If seq is a view, then order of internal data is not guaranteed. @@ -54,18 +55,20 @@ def check_arr_seq(seq, arrays): assert_array_equal(sorted(seq._lengths), sorted(lengths)) else: seq.shrink_data() - assert_equal(seq._data.shape[0], sum(lengths)) + + assert seq._data.shape[0] == sum(lengths) + assert_array_equal(seq._data, np.concatenate(arrays, axis=0)) assert_array_equal(seq._offsets, np.r_[0, np.cumsum(lengths)[:-1]]) assert_array_equal(seq._lengths, lengths) def check_arr_seq_view(seq_view, seq): - assert_true(seq_view._is_view) - assert_true(seq_view is not seq) - assert_true(np.may_share_memory(seq_view._data, seq._data)) - assert_true(seq_view._offsets is not seq._offsets) - assert_true(seq_view._lengths is not seq._lengths) + assert seq_view._is_view + assert seq_view is not seq + assert np.may_share_memory(seq_view._data, seq._data) + assert seq_view._offsets is not seq._offsets + assert seq_view._lengths is not seq._lengths class TestArraySequence(unittest.TestCase): @@ -97,8 +100,8 @@ def test_creating_arraysequence_from_generator(self): seq_with_buffer = ArraySequence(gen_2, buffer_size=256) # Check buffer size effect - assert_equal(seq_with_buffer.data.shape, seq.data.shape) - assert_true(seq_with_buffer._buffer_size > seq._buffer_size) + assert seq_with_buffer.data.shape == seq.data.shape + assert seq_with_buffer._buffer_size > seq._buffer_size # Check generator result check_arr_seq(seq, SEQ_DATA['data']) @@ -121,26 +124,27 @@ def test_arraysequence_iter(self): # Try iterating through a corrupted ArraySequence object. seq = SEQ_DATA['seq'].copy() seq._lengths = seq._lengths[::2] - assert_raises(ValueError, list, seq) + with pytest.raises(ValueError): + list(seq) def test_arraysequence_copy(self): orig = SEQ_DATA['seq'] seq = orig.copy() n_rows = seq.total_nb_rows - assert_equal(n_rows, orig.total_nb_rows) + assert n_rows == orig.total_nb_rows assert_array_equal(seq._data, orig._data[:n_rows]) - assert_true(seq._data is not orig._data) + assert seq._data is not orig._data assert_array_equal(seq._offsets, orig._offsets) - assert_true(seq._offsets is not orig._offsets) + assert seq._offsets is not orig._offsets assert_array_equal(seq._lengths, orig._lengths) - assert_true(seq._lengths is not orig._lengths) - assert_equal(seq.common_shape, orig.common_shape) + assert seq._lengths is not orig._lengths + assert seq.common_shape == orig.common_shape # Taking a copy of an `ArraySequence` generated by slicing. # Only keep needed data. seq = orig[::2].copy() check_arr_seq(seq, SEQ_DATA['data'][::2]) - assert_true(seq._data is not orig._data) + assert seq._data is not orig._data def test_arraysequence_append(self): element = generate_data(nb_arrays=1, @@ -171,7 +175,8 @@ def test_arraysequence_append(self): element = generate_data(nb_arrays=1, common_shape=SEQ_DATA['seq'].common_shape*2, rng=SEQ_DATA['rng'])[0] - assert_raises(ValueError, seq.append, element) + with pytest.raises(ValueError): + seq.append(element) def test_arraysequence_extend(self): new_data = generate_data(nb_arrays=10, @@ -217,7 +222,8 @@ def test_arraysequence_extend(self): common_shape=SEQ_DATA['seq'].common_shape*2, rng=SEQ_DATA['rng']) seq = SEQ_DATA['seq'].copy() # Copy because of in-place modification. - assert_raises(ValueError, seq.extend, data) + with pytest.raises(ValueError): + seq.extend(data) # Extend after extracting some slice working_slice = seq[:2] @@ -262,7 +268,8 @@ def test_arraysequence_getitem(self): for i, keep in enumerate(selection) if keep]) # Test invalid indexing - assert_raises(TypeError, SEQ_DATA['seq'].__getitem__, 'abc') + with pytest.raises(TypeError): + SEQ_DATA['seq']['abc'] # Get specific columns. seq_view = SEQ_DATA['seq'][:, 2] @@ -285,7 +292,7 @@ def test_arraysequence_setitem(self): # Setitem with a scalar. seq = SEQ_DATA['seq'].copy() seq[:] = 0 - assert_true(seq._data.sum() == 0) + assert seq._data.sum() == 0 # Setitem with a list of ndarray. seq = SEQ_DATA['seq'] * 0 @@ -295,12 +302,12 @@ def test_arraysequence_setitem(self): # Setitem using tuple indexing. seq = ArraySequence(np.arange(900).reshape((50,6,3))) seq[:, 0] = 0 - assert_true(seq._data[:, 0].sum() == 0) + assert seq._data[:, 0].sum() == 0 # Setitem using tuple indexing. seq = ArraySequence(np.arange(900).reshape((50,6,3))) seq[range(len(seq))] = 0 - assert_true(seq._data.sum() == 0) + assert seq._data.sum() == 0 # Setitem of a slice using another slice. seq = ArraySequence(np.arange(900).reshape((50,6,3))) @@ -309,20 +316,25 @@ def test_arraysequence_setitem(self): # Setitem between array sequences with different number of sequences. seq = ArraySequence(np.arange(900).reshape((50,6,3))) - assert_raises(ValueError, seq.__setitem__, slice(0, 4), seq[5:10]) + with pytest.raises(ValueError): + seq[0:4] = seq[5:10] # Setitem between array sequences with different amount of points. seq1 = ArraySequence(np.arange(10).reshape(5, 2)) seq2 = ArraySequence(np.arange(15).reshape(5, 3)) - assert_raises(ValueError, seq1.__setitem__, slice(0, 5), seq2) + with pytest.raises(ValueError): + seq1[0:5] = seq2 # Setitem between array sequences with different common shape. seq1 = ArraySequence(np.arange(12).reshape(2, 2, 3)) seq2 = ArraySequence(np.arange(8).reshape(2, 2, 2)) - assert_raises(ValueError, seq1.__setitem__, slice(0, 2), seq2) + + with pytest.raises(ValueError): + seq1[0:2] = seq2 # Invalid index. - assert_raises(TypeError, seq.__setitem__, object(), None) + with pytest.raises(TypeError): + seq[object()] = None def test_arraysequence_operators(self): # Disable division per zero warnings. @@ -341,36 +353,41 @@ def test_arraysequence_operators(self): def _test_unary(op, arrseq): orig = arrseq.copy() seq = getattr(orig, op)() - assert_true(seq is not orig) + assert seq is not orig check_arr_seq(seq, [getattr(d, op)() for d in orig]) def _test_binary(op, arrseq, scalars, seqs, inplace=False): for scalar in scalars: orig = arrseq.copy() seq = getattr(orig, op)(scalar) - assert_true((seq is orig) if inplace else (seq is not orig)) + assert (seq is orig) == inplace + check_arr_seq(seq, [getattr(e, op)(scalar) for e in arrseq]) # Test math operators with another ArraySequence. for other in seqs: orig = arrseq.copy() seq = getattr(orig, op)(other) - assert_true(seq is not SEQ_DATA['seq']) + assert seq is not SEQ_DATA['seq'] check_arr_seq(seq, [getattr(e1, op)(e2) for e1, e2 in zip(arrseq, other)]) # Operations between array sequences of different lengths. orig = arrseq.copy() - assert_raises(ValueError, getattr(orig, op), orig[::2]) + with pytest.raises(ValueError): + getattr(orig, op)(orig[::2]) # Operations between array sequences with different amount of data. seq1 = ArraySequence(np.arange(10).reshape(5, 2)) seq2 = ArraySequence(np.arange(15).reshape(5, 3)) - assert_raises(ValueError, getattr(seq1, op), seq2) + with pytest.raises(ValueError): + getattr(seq1, op)(seq2) # Operations between array sequences with different common shape. seq1 = ArraySequence(np.arange(12).reshape(2, 2, 3)) seq2 = ArraySequence(np.arange(8).reshape(2, 2, 2)) - assert_raises(ValueError, getattr(seq1, op), seq2) + with pytest.raises(ValueError): + getattr(seq1, op)(seq2) + for op in ["__add__", "__sub__", "__mul__", "__mod__", @@ -392,24 +409,36 @@ def _test_binary(op, arrseq, scalars, seqs, inplace=False): continue # Going to deal with it separately. _test_binary(op, seq_int, [42, -3, True, 0], [seq_int, seq_bool, -seq_int], inplace=True) # int <-- int - assert_raises(TypeError, _test_binary, op, seq_int, [0.5], [], inplace=True) # int <-- float - assert_raises(TypeError, _test_binary, op, seq_int, [], [seq], inplace=True) # int <-- float + + with pytest.raises(TypeError): + _test_binary(op, seq_int, [0.5], [], inplace=True) # int <-- float + with pytest.raises(TypeError): + _test_binary(op, seq_int, [], [seq], inplace=True) # int <-- float + # __pow__ : Integers to negative integer powers are not allowed. _test_binary("__pow__", seq, [42, -3, True, 0], [seq_int, seq_bool, -seq_int]) _test_binary("__ipow__", seq, [42, -3, True, 0], [seq_int, seq_bool, -seq_int], inplace=True) - assert_raises(ValueError, _test_binary, "__pow__", seq_int, [-3], []) - assert_raises(ValueError, _test_binary, "__ipow__", seq_int, [-3], [], inplace=True) - + + with pytest.raises(ValueError): + _test_binary("__pow__", seq_int, [-3], []) + with pytest.raises(ValueError): + _test_binary("__ipow__", seq_int, [-3], [], inplace=True) + # __itruediv__ is only valid with float arrseq. for scalar in SCALARS + ARRSEQS: - assert_raises(TypeError, getattr(seq_int.copy(), "__itruediv__"), scalar) + seq_int_cp = seq_int.copy() + with pytest.raises(TypeError): + seq_int_cp /= scalar # Bitwise operators for op in ("__lshift__", "__rshift__", "__or__", "__and__", "__xor__"): _test_binary(op, seq_bool, [42, -3, True, 0], [seq_int, seq_bool, -seq_int]) - assert_raises(TypeError, _test_binary, op, seq_bool, [0.5], []) - assert_raises(TypeError, _test_binary, op, seq, [], [seq]) + + with pytest.raises(TypeError): + _test_binary(op, seq_bool, [0.5], []) + with pytest.raises(TypeError): + _test_binary(op, seq, [], [seq]) # Unary operators for op in ["__neg__", "__abs__"]: @@ -420,7 +449,8 @@ def _test_binary(op, arrseq, scalars, seqs, inplace=False): _test_unary("__abs__", seq_bool) _test_unary("__invert__", seq_bool) - assert_raises(TypeError, _test_unary, "__invert__", seq) + with pytest.raises(TypeError): + _test_unary("__invert__", seq) # Restore flags. np.seterr(**flags) @@ -440,7 +470,7 @@ def test_arraysequence_repr(self): txt1 = repr(seq) np.set_printoptions(threshold=nb_arrays//2) txt2 = repr(seq) - assert_true(len(txt2) < len(txt1)) + assert len(txt2) < len(txt1) np.set_printoptions(threshold=bkp_threshold) def test_save_and_load_arraysequence(self): @@ -483,10 +513,10 @@ def test_concatenate(): new_seq = concatenate(seqs, axis=1) seq._data += 100 # Modifying the 'seq' shouldn't change 'new_seq'. check_arr_seq(new_seq, SEQ_DATA['data']) - assert_true(not new_seq._is_view) + assert new_seq._is_view is not True seq = SEQ_DATA['seq'] seqs = [seq[:, [i]] for i in range(seq.common_shape[0])] new_seq = concatenate(seqs, axis=0) - assert_true(len(new_seq), seq.common_shape[0] * len(seq)) + assert len(new_seq) == seq.common_shape[0] * len(seq) assert_array_equal(new_seq._data, seq._data.T.reshape((-1, 1))) diff --git a/nibabel/streamlines/tests/test_streamlines.py b/nibabel/streamlines/tests/test_streamlines.py index 2e537c63f2..9a2f803117 100644 --- a/nibabel/streamlines/tests/test_streamlines.py +++ b/nibabel/streamlines/tests/test_streamlines.py @@ -10,9 +10,7 @@ from nibabel.tmpdirs import InTemporaryDirectory from numpy.compat.py3k import asbytes -from nibabel.testing import data_path -from nibabel.testing import clear_and_catch_warnings -from nose.tools import assert_equal, assert_raises, assert_true, assert_false +from nibabel.testing import data_path, clear_and_catch_warnings from .test_tractogram import assert_tractogram_equal from ..tractogram import Tractogram, LazyTractogram @@ -82,50 +80,50 @@ def test_is_supported_detect_format(): # Test is_supported and detect_format functions # Empty file/string f = BytesIO() - assert_false(nib.streamlines.is_supported(f)) - assert_false(nib.streamlines.is_supported("")) - assert_true(nib.streamlines.detect_format(f) is None) - assert_true(nib.streamlines.detect_format("") is None) + assert not nib.streamlines.is_supported(f) + assert not nib.streamlines.is_supported("") + assert nib.streamlines.detect_format(f) is None + assert nib.streamlines.detect_format("") is None # Valid file without extension for tfile_cls in FORMATS.values(): f = BytesIO() f.write(asbytes(tfile_cls.MAGIC_NUMBER)) f.seek(0, os.SEEK_SET) - assert_true(nib.streamlines.is_supported(f)) - assert_true(nib.streamlines.detect_format(f) is tfile_cls) + assert nib.streamlines.is_supported(f) + assert nib.streamlines.detect_format(f) is tfile_cls # Wrong extension but right magic number for tfile_cls in FORMATS.values(): with tempfile.TemporaryFile(mode="w+b", suffix=".txt") as f: f.write(asbytes(tfile_cls.MAGIC_NUMBER)) f.seek(0, os.SEEK_SET) - assert_true(nib.streamlines.is_supported(f)) - assert_true(nib.streamlines.detect_format(f) is tfile_cls) + assert nib.streamlines.is_supported(f) + assert nib.streamlines.detect_format(f) is tfile_cls # Good extension but wrong magic number for ext, tfile_cls in FORMATS.items(): with tempfile.TemporaryFile(mode="w+b", suffix=ext) as f: f.write(b"pass") f.seek(0, os.SEEK_SET) - assert_false(nib.streamlines.is_supported(f)) - assert_true(nib.streamlines.detect_format(f) is None) + assert not nib.streamlines.is_supported(f) + assert nib.streamlines.detect_format(f) is None # Wrong extension, string only f = "my_tractogram.asd" - assert_false(nib.streamlines.is_supported(f)) - assert_true(nib.streamlines.detect_format(f) is None) + assert not nib.streamlines.is_supported(f) + assert nib.streamlines.detect_format(f) is None # Good extension, string only for ext, tfile_cls in FORMATS.items(): f = "my_tractogram" + ext - assert_true(nib.streamlines.is_supported(f)) - assert_equal(nib.streamlines.detect_format(f), tfile_cls) + assert nib.streamlines.is_supported(f) + assert nib.streamlines.detect_format(f) == tfile_cls # Extension should not be case-sensitive. for ext, tfile_cls in FORMATS.items(): f = "my_tractogram" + ext.upper() - assert_true(nib.streamlines.detect_format(f) is tfile_cls) + assert nib.streamlines.detect_format(f) is tfile_cls class TestLoadSave(unittest.TestCase): @@ -135,12 +133,12 @@ def test_load_empty_file(self): for empty_filename in DATA['empty_filenames']: tfile = nib.streamlines.load(empty_filename, lazy_load=lazy_load) - assert_true(isinstance(tfile, TractogramFile)) + assert isinstance(tfile, TractogramFile) if lazy_load: - assert_true(type(tfile.tractogram), Tractogram) + assert type(tfile.tractogram), Tractogram else: - assert_true(type(tfile.tractogram), LazyTractogram) + assert type(tfile.tractogram), LazyTractogram assert_tractogram_equal(tfile.tractogram, DATA['empty_tractogram']) @@ -150,12 +148,12 @@ def test_load_simple_file(self): for simple_filename in DATA['simple_filenames']: tfile = nib.streamlines.load(simple_filename, lazy_load=lazy_load) - assert_true(isinstance(tfile, TractogramFile)) + assert isinstance(tfile, TractogramFile) if lazy_load: - assert_true(type(tfile.tractogram), Tractogram) + assert type(tfile.tractogram), Tractogram else: - assert_true(type(tfile.tractogram), LazyTractogram) + assert type(tfile.tractogram), LazyTractogram assert_tractogram_equal(tfile.tractogram, DATA['simple_tractogram']) @@ -165,12 +163,12 @@ def test_load_complex_file(self): for complex_filename in DATA['complex_filenames']: tfile = nib.streamlines.load(complex_filename, lazy_load=lazy_load) - assert_true(isinstance(tfile, TractogramFile)) + assert isinstance(tfile, TractogramFile) if lazy_load: - assert_true(type(tfile.tractogram), Tractogram) + assert type(tfile.tractogram), Tractogram else: - assert_true(type(tfile.tractogram), LazyTractogram) + assert type(tfile.tractogram), LazyTractogram tractogram = Tractogram(DATA['streamlines'], affine_to_rasmm=np.eye(4)) @@ -191,19 +189,19 @@ def test_save_tractogram_file(self): trk_file = trk.TrkFile(tractogram) # No need for keyword arguments. - assert_raises(ValueError, nib.streamlines.save, - trk_file, "dummy.trk", header={}) + with self.assertRaises(ValueError): + nib.streamlines.save(trk_file, "dummy.trk", header={}) # Wrong extension. with clear_and_catch_warnings(record=True, modules=[nib.streamlines]) as w: trk_file = trk.TrkFile(tractogram) - assert_raises(ValueError, nib.streamlines.save, - trk_file, "dummy.tck", header={}) + with self.assertRaises(ValueError): + nib.streamlines.save(trk_file, "dummy.tck", header={}) - assert_equal(len(w), 1) - assert_true(issubclass(w[0].category, ExtensionWarning)) - assert_true("extension" in str(w[0].message)) + assert len(w) == 1 + assert issubclass(w[0].category, ExtensionWarning) + assert "extension" in str(w[0].message) with InTemporaryDirectory(): nib.streamlines.save(trk_file, "dummy.trk") @@ -250,9 +248,9 @@ def test_save_complex_file(self): ((not cls.SUPPORTS_DATA_PER_POINT) + (not cls.SUPPORTS_DATA_PER_STREAMLINE)) - assert_equal(len(w), nb_expected_warnings) + assert len(w) == nb_expected_warnings for i in range(nb_expected_warnings): - assert_true(issubclass(w[i].category, Warning)) + assert issubclass(w[i].category, Warning) tractogram = Tractogram(DATA['streamlines'], affine_to_rasmm=np.eye(4)) @@ -281,10 +279,12 @@ def test_save_sliced_tractogram(self): assert_tractogram_equal(tractogram, original_tractogram) def test_load_unknown_format(self): - assert_raises(ValueError, nib.streamlines.load, "") + with self.assertRaises(ValueError): + nib.streamlines.load("") def test_save_unknown_format(self): - assert_raises(ValueError, nib.streamlines.save, Tractogram(), "") + with self.assertRaises(ValueError): + nib.streamlines.save(Tractogram(), "") def test_save_from_generator(self): tractogram = Tractogram(DATA['streamlines'], diff --git a/nibabel/streamlines/tests/test_tck.py b/nibabel/streamlines/tests/test_tck.py index ad16b52754..0dfb043d83 100644 --- a/nibabel/streamlines/tests/test_tck.py +++ b/nibabel/streamlines/tests/test_tck.py @@ -14,15 +14,15 @@ from .. import tck as tck_module from ..tck import TckFile -from nose.tools import assert_equal, assert_raises, assert_true +import pytest from numpy.testing import assert_array_equal -from nibabel.testing import data_path, clear_and_catch_warnings +from ...testing import data_path, clear_and_catch_warnings from .test_tractogram import assert_tractogram_equal DATA = {} -def setup(): +def setup_module(): global DATA DATA['empty_tck_fname'] = pjoin(data_path, "empty.tck") @@ -69,8 +69,8 @@ def test_load_matlab_nan_file(self): for lazy_load in [False, True]: tck = TckFile.load(DATA['matlab_nan_tck_fname'], lazy_load=lazy_load) streamlines = list(tck.tractogram.streamlines) - assert_equal(len(streamlines), 1) - assert_equal(streamlines[0].shape, (108, 3)) + assert len(streamlines) == 1 + assert streamlines[0].shape == (108, 3) def test_writeable_data(self): data = DATA['simple_tractogram'] @@ -80,7 +80,7 @@ def test_writeable_data(self): for actual, expected_tgi in zip(tck.streamlines, data): assert_array_equal(actual, expected_tgi.streamline) # Test we can write to arrays - assert_true(actual.flags.writeable) + assert actual.flags.writeable actual[0, 0] = 99 def test_load_simple_file_in_big_endian(self): @@ -88,7 +88,7 @@ def test_load_simple_file_in_big_endian(self): tck = TckFile.load(DATA['simple_tck_big_endian_fname'], lazy_load=lazy_load) assert_tractogram_equal(tck.tractogram, DATA['simple_tractogram']) - assert_equal(tck.header['datatype'], 'Float32BE') + assert tck.header['datatype'] == 'Float32BE' def test_load_file_with_wrong_information(self): tck_file = open(DATA['simple_tck_fname'], 'rb').read() @@ -96,12 +96,15 @@ def test_load_file_with_wrong_information(self): # Simulate a TCK file where `datatype` has not the right endianness. new_tck_file = tck_file.replace(asbytes("Float32LE"), asbytes("Float32BE")) - assert_raises(DataError, TckFile.load, BytesIO(new_tck_file)) + + with pytest.raises(DataError): + TckFile.load(BytesIO(new_tck_file)) # Simulate a TCK file with unsupported `datatype`. new_tck_file = tck_file.replace(asbytes("Float32LE"), asbytes("int32")) - assert_raises(HeaderError, TckFile.load, BytesIO(new_tck_file)) + with pytest.raises(HeaderError): + TckFile.load(BytesIO(new_tck_file)) # Simulate a TCK file with no `datatype` field. new_tck_file = tck_file.replace(b"datatype: Float32LE\n", b"") @@ -109,24 +112,25 @@ def test_load_file_with_wrong_information(self): new_tck_file = new_tck_file.replace(b"file: . 67\n", b"file: . 47\n") with clear_and_catch_warnings(record=True, modules=[tck_module]) as w: tck = TckFile.load(BytesIO(new_tck_file)) - assert_equal(len(w), 1) - assert_true(issubclass(w[0].category, HeaderWarning)) - assert_true("Missing 'datatype'" in str(w[0].message)) + assert len(w) == 1 + assert issubclass(w[0].category, HeaderWarning) + assert "Missing 'datatype'" in str(w[0].message) assert_array_equal(tck.header['datatype'], "Float32LE") # Simulate a TCK file with no `file` field. new_tck_file = tck_file.replace(b"\nfile: . 67", b"") with clear_and_catch_warnings(record=True, modules=[tck_module]) as w: tck = TckFile.load(BytesIO(new_tck_file)) - assert_equal(len(w), 1) - assert_true(issubclass(w[0].category, HeaderWarning)) - assert_true("Missing 'file'" in str(w[0].message)) + assert len(w) == 1 + assert issubclass(w[0].category, HeaderWarning) + assert "Missing 'file'" in str(w[0].message) assert_array_equal(tck.header['file'], ". 56") # Simulate a TCK file with `file` field pointing to another file. new_tck_file = tck_file.replace(b"file: . 67\n", b"file: dummy.mat 75\n") - assert_raises(HeaderError, TckFile.load, BytesIO(new_tck_file)) + with pytest.raises(HeaderError): + TckFile.load(BytesIO(new_tck_file)) # Simulate a TCK file which is missing a streamline delimiter. eos = TckFile.FIBER_DELIMITER.tostring() @@ -137,11 +141,13 @@ def test_load_file_with_wrong_information(self): buffer_size = 1. / 1024**2 # 1 bytes hdr = TckFile._read_header(BytesIO(new_tck_file)) tck_reader = TckFile._read(BytesIO(new_tck_file), hdr, buffer_size) - assert_raises(DataError, list, tck_reader) + with pytest.raises(DataError): + list(tck_reader) # Simulate a TCK file which is missing the end-of-file delimiter. new_tck_file = tck_file[:-len(eof)] - assert_raises(DataError, TckFile.load, BytesIO(new_tck_file)) + with pytest.raises(DataError): + TckFile.load(BytesIO(new_tck_file)) def test_write_empty_file(self): tractogram = Tractogram(affine_to_rasmm=np.eye(4)) @@ -158,8 +164,7 @@ def test_write_empty_file(self): assert_tractogram_equal(new_tck.tractogram, new_tck_orig.tractogram) tck_file.seek(0, os.SEEK_SET) - assert_equal(tck_file.read(), - open(DATA['empty_tck_fname'], 'rb').read()) + assert tck_file.read() == open(DATA['empty_tck_fname'], 'rb').read() def test_write_simple_file(self): tractogram = Tractogram(DATA['streamlines'], @@ -177,17 +182,18 @@ def test_write_simple_file(self): assert_tractogram_equal(new_tck.tractogram, new_tck_orig.tractogram) tck_file.seek(0, os.SEEK_SET) - assert_equal(tck_file.read(), - open(DATA['simple_tck_fname'], 'rb').read()) + assert tck_file.read() == open(DATA['simple_tck_fname'], 'rb').read() # TCK file containing not well formatted entries in its header. tck_file = BytesIO() tck = TckFile(tractogram) tck.header['new_entry'] = 'value\n' # \n not allowed - assert_raises(HeaderError, tck.save, tck_file) + with pytest.raises(HeaderError): + tck.save(tck_file) tck.header['new_entry'] = 'val:ue' # : not allowed - assert_raises(HeaderError, tck.save, tck_file) + with pytest.raises(HeaderError): + tck.save(tck_file) def test_load_write_file(self): for fname in [DATA['empty_tck_fname'], @@ -202,7 +208,7 @@ def test_load_write_file(self): # Check that the written file is the same as the one read. tck_file.seek(0, os.SEEK_SET) - assert_equal(tck_file.read(), open(fname, 'rb').read()) + assert tck_file.read() == open(fname, 'rb').read() # Save tractogram that has an affine_to_rasmm. for lazy_load in [False, True]: diff --git a/nibabel/streamlines/tests/test_tractogram.py b/nibabel/streamlines/tests/test_tractogram.py index 407f3ef413..f86594d070 100644 --- a/nibabel/streamlines/tests/test_tractogram.py +++ b/nibabel/streamlines/tests/test_tractogram.py @@ -6,9 +6,8 @@ import operator from collections import defaultdict -from nibabel.testing import assert_arrays_equal -from nibabel.testing import clear_and_catch_warnings -from nose.tools import assert_equal, assert_raises, assert_true +import pytest +from ...testing import assert_arrays_equal, clear_and_catch_warnings from numpy.testing import assert_array_equal, assert_array_almost_equal from .. import tractogram as module_tractogram @@ -93,7 +92,7 @@ def make_dummy_streamline(nb_points): return streamline, data_per_point, data_for_streamline -def setup(): +def setup_module(): global DATA DATA['rng'] = np.random.RandomState(1234) @@ -149,13 +148,12 @@ def check_tractogram_item(tractogram_item, assert_array_equal(tractogram_item.streamline, streamline) - assert_equal(len(tractogram_item.data_for_streamline), - len(data_for_streamline)) + assert len(tractogram_item.data_for_streamline) == len(data_for_streamline) for key in data_for_streamline.keys(): assert_array_equal(tractogram_item.data_for_streamline[key], data_for_streamline[key]) - assert_equal(len(tractogram_item.data_for_points), len(data_for_points)) + assert len(tractogram_item.data_for_points) == len(data_for_points) for key in data_for_points.keys(): assert_arrays_equal(tractogram_item.data_for_points[key], data_for_points[key]) @@ -171,16 +169,16 @@ def check_tractogram(tractogram, data_per_streamline={}, data_per_point={}): streamlines = list(streamlines) - assert_equal(len(tractogram), len(streamlines)) + assert len(tractogram) == len(streamlines) assert_arrays_equal(tractogram.streamlines, streamlines) [t for t in tractogram] # Force iteration through tractogram. - assert_equal(len(tractogram.data_per_streamline), len(data_per_streamline)) + assert len(tractogram.data_per_streamline) == len(data_per_streamline) for key in data_per_streamline.keys(): assert_arrays_equal(tractogram.data_per_streamline[key], data_per_streamline[key]) - assert_equal(len(tractogram.data_per_point), len(data_per_point)) + assert len(tractogram.data_per_point) == len(data_per_point) for key in data_per_point.keys(): assert_arrays_equal(tractogram.data_per_point[key], data_per_point[key]) @@ -204,43 +202,43 @@ def test_per_array_dict_creation(self): nb_streamlines = len(DATA['tractogram']) data_per_streamline = DATA['tractogram'].data_per_streamline data_dict = PerArrayDict(nb_streamlines, data_per_streamline) - assert_equal(data_dict.keys(), data_per_streamline.keys()) + assert data_dict.keys() == data_per_streamline.keys() for k in data_dict.keys(): assert_array_equal(data_dict[k], data_per_streamline[k]) del data_dict['mean_curvature'] - assert_equal(len(data_dict), - len(data_per_streamline)-1) + assert len(data_dict) == len(data_per_streamline) - 1 # Create a PerArrayDict object using an existing dict object. data_per_streamline = DATA['data_per_streamline'] data_dict = PerArrayDict(nb_streamlines, data_per_streamline) - assert_equal(data_dict.keys(), data_per_streamline.keys()) + assert data_dict.keys() == data_per_streamline.keys() for k in data_dict.keys(): assert_array_equal(data_dict[k], data_per_streamline[k]) del data_dict['mean_curvature'] - assert_equal(len(data_dict), len(data_per_streamline)-1) + assert len(data_dict) == len(data_per_streamline) - 1 # Create a PerArrayDict object using keyword arguments. data_per_streamline = DATA['data_per_streamline'] data_dict = PerArrayDict(nb_streamlines, **data_per_streamline) - assert_equal(data_dict.keys(), data_per_streamline.keys()) + assert data_dict.keys() == data_per_streamline.keys() for k in data_dict.keys(): assert_array_equal(data_dict[k], data_per_streamline[k]) del data_dict['mean_curvature'] - assert_equal(len(data_dict), len(data_per_streamline)-1) + assert len(data_dict) == len(data_per_streamline) - 1 def test_getitem(self): sdict = PerArrayDict(len(DATA['tractogram']), DATA['data_per_streamline']) - assert_raises(KeyError, sdict.__getitem__, 'invalid') + with pytest.raises(KeyError): + sdict['invalid'] # Test slicing and advanced indexing. for k, v in DATA['tractogram'].data_per_streamline.items(): - assert_true(k in sdict) + assert k in sdict assert_arrays_equal(sdict[k], v) assert_arrays_equal(sdict[::2][k], v[::2]) assert_arrays_equal(sdict[::-1][k], v[::-1]) @@ -258,7 +256,7 @@ def test_extend(self): new_data) sdict.extend(sdict2) - assert_equal(len(sdict), len(sdict2)) + assert len(sdict) == len(sdict2) for k in DATA['tractogram'].data_per_streamline: assert_arrays_equal(sdict[k][:len(DATA['tractogram'])], DATA['tractogram'].data_per_streamline[k]) @@ -278,21 +276,24 @@ def test_extend(self): 'mean_colors': 4 * np.array(DATA['mean_colors']), 'other': 5 * np.array(DATA['mean_colors'])} sdict2 = PerArrayDict(len(DATA['tractogram']), new_data) - assert_raises(ValueError, sdict.extend, sdict2) + with pytest.raises(ValueError): + sdict.extend(sdict2) # Other dict has not the same entries (key mistmached). new_data = {'mean_curvature': 2 * np.array(DATA['mean_curvature']), 'mean_torsion': 3 * np.array(DATA['mean_torsion']), 'other': 4 * np.array(DATA['mean_colors'])} sdict2 = PerArrayDict(len(DATA['tractogram']), new_data) - assert_raises(ValueError, sdict.extend, sdict2) + with pytest.raises(ValueError): + sdict.extend(sdict2) # Other dict has the right number of entries but wrong shape. new_data = {'mean_curvature': 2 * np.array(DATA['mean_curvature']), 'mean_torsion': 3 * np.array(DATA['mean_torsion']), 'mean_colors': 4 * np.array(DATA['mean_torsion'])} sdict2 = PerArrayDict(len(DATA['tractogram']), new_data) - assert_raises(ValueError, sdict.extend, sdict2) + with pytest.raises(ValueError): + sdict.extend(sdict2) class TestPerArraySequenceDict(unittest.TestCase): @@ -303,43 +304,43 @@ def test_per_array_sequence_dict_creation(self): total_nb_rows = DATA['tractogram'].streamlines.total_nb_rows data_per_point = DATA['tractogram'].data_per_point data_dict = PerArraySequenceDict(total_nb_rows, data_per_point) - assert_equal(data_dict.keys(), data_per_point.keys()) + assert data_dict.keys() == data_per_point.keys() for k in data_dict.keys(): assert_arrays_equal(data_dict[k], data_per_point[k]) del data_dict['fa'] - assert_equal(len(data_dict), - len(data_per_point)-1) + assert len(data_dict) == len(data_per_point) - 1 # Create a PerArraySequenceDict object using an existing dict object. data_per_point = DATA['data_per_point'] data_dict = PerArraySequenceDict(total_nb_rows, data_per_point) - assert_equal(data_dict.keys(), data_per_point.keys()) + assert data_dict.keys() == data_per_point.keys() for k in data_dict.keys(): assert_arrays_equal(data_dict[k], data_per_point[k]) del data_dict['fa'] - assert_equal(len(data_dict), len(data_per_point)-1) + assert len(data_dict) == len(data_per_point) - 1 # Create a PerArraySequenceDict object using keyword arguments. data_per_point = DATA['data_per_point'] data_dict = PerArraySequenceDict(total_nb_rows, **data_per_point) - assert_equal(data_dict.keys(), data_per_point.keys()) + assert data_dict.keys() == data_per_point.keys() for k in data_dict.keys(): assert_arrays_equal(data_dict[k], data_per_point[k]) del data_dict['fa'] - assert_equal(len(data_dict), len(data_per_point)-1) + assert len(data_dict) == len(data_per_point) - 1 def test_getitem(self): total_nb_rows = DATA['tractogram'].streamlines.total_nb_rows sdict = PerArraySequenceDict(total_nb_rows, DATA['data_per_point']) - assert_raises(KeyError, sdict.__getitem__, 'invalid') + with pytest.raises(KeyError): + sdict['invalid'] # Test slicing and advanced indexing. for k, v in DATA['tractogram'].data_per_point.items(): - assert_true(k in sdict) + assert k in sdict assert_arrays_equal(sdict[k], v) assert_arrays_equal(sdict[::2][k], v[::2]) assert_arrays_equal(sdict[::-1][k], v[::-1]) @@ -360,7 +361,7 @@ def test_extend(self): sdict2 = PerArraySequenceDict(np.sum(list_nb_points), new_data) sdict.extend(sdict2) - assert_equal(len(sdict), len(sdict2)) + assert len(sdict) == len(sdict2) for k in DATA['tractogram'].data_per_point: assert_arrays_equal(sdict[k][:len(DATA['tractogram'])], DATA['tractogram'].data_per_point[k]) @@ -382,7 +383,8 @@ def test_extend(self): data_per_point_shapes, rng=DATA['rng']) sdict2 = PerArraySequenceDict(np.sum(list_nb_points), new_data) - assert_raises(ValueError, sdict.extend, sdict2) + with pytest.raises(ValueError): + sdict.extend(sdict2) # Other dict has not the same entries (key mistmached). data_per_point_shapes = {"colors": DATA['colors'][0].shape[1:], @@ -391,7 +393,8 @@ def test_extend(self): data_per_point_shapes, rng=DATA['rng']) sdict2 = PerArraySequenceDict(np.sum(list_nb_points), new_data) - assert_raises(ValueError, sdict.extend, sdict2) + with pytest.raises(ValueError): + sdict.extend(sdict2) # Other dict has the right number of entries but wrong shape. data_per_point_shapes = {"colors": DATA['colors'][0].shape[1:], @@ -400,7 +403,8 @@ def test_extend(self): data_per_point_shapes, rng=DATA['rng']) sdict2 = PerArraySequenceDict(np.sum(list_nb_points), new_data) - assert_raises(ValueError, sdict.extend, sdict2) + with pytest.raises(ValueError): + sdict.extend(sdict2) class TestLazyDict(unittest.TestCase): @@ -413,14 +417,13 @@ def test_lazydict_creation(self): expected_keys = DATA['data_per_streamline_func'].keys() for data_dict in lazy_dicts: - assert_true(is_lazy_dict(data_dict)) - assert_equal(data_dict.keys(), expected_keys) + assert is_lazy_dict(data_dict) + assert data_dict.keys() == expected_keys for k in data_dict.keys(): assert_array_equal(list(data_dict[k]), list(DATA['data_per_streamline'][k])) - assert_equal(len(data_dict), - len(DATA['data_per_streamline_func'])) + assert len(data_dict) == len(DATA['data_per_streamline_func']) class TestTractogramItem(unittest.TestCase): @@ -439,7 +442,7 @@ def test_creating_tractogram_item(self): # Create a tractogram item with a streamline, data. t = TractogramItem(streamline, data_for_streamline, data_for_points) - assert_equal(len(t), len(streamline)) + assert len(t) == len(streamline) assert_array_equal(t.streamline, streamline) assert_array_equal(list(t), streamline) assert_array_equal(t.data_for_streamline['mean_curvature'], @@ -456,7 +459,7 @@ def test_tractogram_creation(self): # Create an empty tractogram. tractogram = Tractogram() check_tractogram(tractogram) - assert_true(tractogram.affine_to_rasmm is None) + assert tractogram.affine_to_rasmm is None # Create a tractogram with only streamlines tractogram = Tractogram(streamlines=DATA['streamlines']) @@ -477,8 +480,8 @@ def test_tractogram_creation(self): DATA['data_per_streamline'], DATA['data_per_point']) - assert_true(is_data_dict(tractogram.data_per_streamline)) - assert_true(is_data_dict(tractogram.data_per_point)) + assert is_data_dict(tractogram.data_per_streamline) + assert is_data_dict(tractogram.data_per_point) # Create a tractogram from another tractogram attributes. tractogram2 = Tractogram(tractogram.streamlines, @@ -502,8 +505,8 @@ def test_tractogram_creation(self): [(0, 0, 1)]*5] data_per_point = {'wrong_data': wrong_data} - assert_raises(ValueError, Tractogram, DATA['streamlines'], - data_per_point=data_per_point) + with pytest.raises(ValueError): + Tractogram(streamlines=DATA['streamlines'], data_per_point=data_per_point) # Inconsistent number of scalars between streamlines wrong_data = [[(1, 0, 0)]*1, @@ -511,8 +514,8 @@ def test_tractogram_creation(self): [(0, 0, 1)]*5] data_per_point = {'wrong_data': wrong_data} - assert_raises(ValueError, Tractogram, DATA['streamlines'], - data_per_point=data_per_point) + with pytest.raises(ValueError): + Tractogram(streamlines=DATA['streamlines'], data_per_point=data_per_point) def test_setting_affine_to_rasmm(self): tractogram = DATA['tractogram'].copy() @@ -520,19 +523,19 @@ def test_setting_affine_to_rasmm(self): # Test assigning None. tractogram.affine_to_rasmm = None - assert_true(tractogram.affine_to_rasmm is None) + assert tractogram.affine_to_rasmm is None # Test assigning a valid ndarray (should make a copy). tractogram.affine_to_rasmm = affine - assert_true(tractogram.affine_to_rasmm is not affine) + assert tractogram.affine_to_rasmm is not affine # Test assigning a list of lists. tractogram.affine_to_rasmm = affine.tolist() assert_array_equal(tractogram.affine_to_rasmm, affine) # Test assigning a ndarray with wrong shape. - assert_raises(ValueError, setattr, tractogram, - "affine_to_rasmm", affine[::2]) + with pytest.raises(ValueError): + tractogram.affine_to_rasmm = affine[::2] def test_tractogram_getitem(self): # Retrieve TractogramItem by their index. @@ -593,21 +596,16 @@ def test_tractogram_copy(self): tractogram = DATA['tractogram'].copy() # Check we copied the data and not simply created new references. - assert_true(tractogram is not DATA['tractogram']) - assert_true(tractogram.streamlines - is not DATA['tractogram'].streamlines) - assert_true(tractogram.data_per_streamline - is not DATA['tractogram'].data_per_streamline) - assert_true(tractogram.data_per_point - is not DATA['tractogram'].data_per_point) + assert tractogram is not DATA['tractogram'] + assert tractogram.streamlines is not DATA['tractogram'].streamlines + assert tractogram.data_per_streamline is not DATA['tractogram'].data_per_streamline + assert tractogram.data_per_point is not DATA['tractogram'].data_per_point for key in tractogram.data_per_streamline: - assert_true(tractogram.data_per_streamline[key] - is not DATA['tractogram'].data_per_streamline[key]) + assert tractogram.data_per_streamline[key] is not DATA['tractogram'].data_per_streamline[key] for key in tractogram.data_per_point: - assert_true(tractogram.data_per_point[key] - is not DATA['tractogram'].data_per_point[key]) + assert tractogram.data_per_point[key] is not DATA['tractogram'].data_per_point[key] # Check the values of the data are the same. assert_tractogram_equal(tractogram, DATA['tractogram']) @@ -618,39 +616,39 @@ def test_creating_invalid_tractogram(self): [(0, 1, 0)]*2, [(0, 0, 1)]*3] # Last streamlines has 5 points. - assert_raises(ValueError, Tractogram, DATA['streamlines'], - data_per_point={'scalars': scalars}) + with pytest.raises(ValueError): + Tractogram(streamlines=DATA['streamlines'], data_per_point={'scalars': scalars}) # Not enough data_per_streamline for all streamlines. properties = [np.array([1.11, 1.22], dtype="f4"), np.array([3.11, 3.22], dtype="f4")] - assert_raises(ValueError, Tractogram, DATA['streamlines'], - data_per_streamline={'properties': properties}) + with pytest.raises(ValueError): + Tractogram(streamlines=DATA['streamlines'], data_per_streamline={'properties': properties}) # Inconsistent dimension for a data_per_point. - scalars = [[(1, 0, 0)]*1, - [(0, 1)]*2, - [(0, 0, 1)]*5] + scalars = [[(1, 0, 0)] * 1, + [(0, 1)] * 2, + [(0, 0, 1)] * 5] - assert_raises(ValueError, Tractogram, DATA['streamlines'], - data_per_point={'scalars': scalars}) + with pytest.raises(ValueError): + Tractogram(streamlines=DATA['streamlines'], data_per_point={'scalars':scalars}) # Inconsistent dimension for a data_per_streamline. properties = [[1.11, 1.22], [2.11], [3.11, 3.22]] - assert_raises(ValueError, Tractogram, DATA['streamlines'], - data_per_streamline={'properties': properties}) + with pytest.raises(ValueError): + Tractogram(streamlines=DATA['streamlines'], data_per_streamline={'properties': properties}) # Too many dimension for a data_per_streamline. properties = [np.array([[1.11], [1.22]], dtype="f4"), np.array([[2.11], [2.22]], dtype="f4"), np.array([[3.11], [3.22]], dtype="f4")] - assert_raises(ValueError, Tractogram, DATA['streamlines'], - data_per_streamline={'properties': properties}) + with pytest.raises(ValueError): + Tractogram(streamlines=DATA['streamlines'], data_per_streamline={'properties': properties}) def test_tractogram_apply_affine(self): tractogram = DATA['tractogram'].copy() @@ -660,7 +658,7 @@ def test_tractogram_apply_affine(self): # Apply the affine to the streamline in a lazy manner. transformed_tractogram = tractogram.apply_affine(affine, lazy=True) - assert_true(type(transformed_tractogram) is LazyTractogram) + assert type(transformed_tractogram) is LazyTractogram check_tractogram(transformed_tractogram, streamlines=[s*scaling for s in DATA['streamlines']], data_per_streamline=DATA['data_per_streamline'], @@ -673,7 +671,7 @@ def test_tractogram_apply_affine(self): # Apply the affine to the streamlines in-place. transformed_tractogram = tractogram.apply_affine(affine) - assert_true(transformed_tractogram is tractogram) + assert transformed_tractogram is tractogram check_tractogram(tractogram, streamlines=[s*scaling for s in DATA['streamlines']], data_per_streamline=DATA['data_per_streamline'], @@ -689,7 +687,7 @@ def test_tractogram_apply_affine(self): # shouldn't affect the remaining streamlines. tractogram = DATA['tractogram'].copy() transformed_tractogram = tractogram[::2].apply_affine(affine) - assert_true(transformed_tractogram is not tractogram) + assert transformed_tractogram is not tractogram check_tractogram(tractogram[::2], streamlines=[s*scaling for s in DATA['streamlines'][::2]], data_per_streamline=DATA['tractogram'].data_per_streamline[::2], @@ -723,7 +721,7 @@ def test_tractogram_apply_affine(self): tractogram = DATA['tractogram'].copy() tractogram.affine_to_rasmm = None tractogram.apply_affine(affine) - assert_true(tractogram.affine_to_rasmm is None) + assert tractogram.affine_to_rasmm is None def test_tractogram_to_world(self): tractogram = DATA['tractogram'].copy() @@ -737,7 +735,7 @@ def test_tractogram_to_world(self): np.linalg.inv(affine)) tractogram_world = transformed_tractogram.to_world(lazy=True) - assert_true(type(tractogram_world) is LazyTractogram) + assert type(tractogram_world) is LazyTractogram assert_array_almost_equal(tractogram_world.affine_to_rasmm, np.eye(4)) for s1, s2 in zip(tractogram_world.streamlines, DATA['streamlines']): @@ -745,14 +743,14 @@ def test_tractogram_to_world(self): # Bring them back streamlines to world space in a in-place manner. tractogram_world = transformed_tractogram.to_world() - assert_true(tractogram_world is tractogram) + assert tractogram_world is tractogram assert_array_almost_equal(tractogram.affine_to_rasmm, np.eye(4)) for s1, s2 in zip(tractogram.streamlines, DATA['streamlines']): assert_array_almost_equal(s1, s2) # Calling to_world twice should do nothing. tractogram_world2 = transformed_tractogram.to_world() - assert_true(tractogram_world2 is tractogram) + assert tractogram_world2 is tractogram assert_array_almost_equal(tractogram.affine_to_rasmm, np.eye(4)) for s1, s2 in zip(tractogram.streamlines, DATA['streamlines']): assert_array_almost_equal(s1, s2) @@ -760,7 +758,8 @@ def test_tractogram_to_world(self): # Calling to_world when affine_to_rasmm is None should fail. tractogram = DATA['tractogram'].copy() tractogram.affine_to_rasmm = None - assert_raises(ValueError, tractogram.to_world) + with pytest.raises(ValueError): + tractogram.to_world() def test_tractogram_extend(self): # Load tractogram that contains some metadata. @@ -770,7 +769,7 @@ def test_tractogram_extend(self): (extender, True)): first_arg = t.copy() new_t = op(first_arg, t) - assert_equal(new_t is first_arg, in_place) + assert (new_t is first_arg) == in_place assert_tractogram_equal(new_t[:len(t)], DATA['tractogram']) assert_tractogram_equal(new_t[len(t):], DATA['tractogram']) @@ -789,7 +788,8 @@ class TestLazyTractogram(unittest.TestCase): def test_lazy_tractogram_creation(self): # To create tractogram from arrays use `Tractogram`. - assert_raises(TypeError, LazyTractogram, DATA['streamlines']) + with pytest.raises(TypeError): + LazyTractogram(streamlines=DATA['streamlines']) # Streamlines and other data as generators streamlines = (x for x in DATA['streamlines']) @@ -800,29 +800,30 @@ def test_lazy_tractogram_creation(self): # Creating LazyTractogram with generators is not allowed as # generators get exhausted and are not reusable unlike generator # function. - assert_raises(TypeError, LazyTractogram, streamlines) - assert_raises(TypeError, LazyTractogram, - data_per_point={"none": None}) - assert_raises(TypeError, LazyTractogram, - data_per_streamline=data_per_streamline) - assert_raises(TypeError, LazyTractogram, DATA['streamlines'], - data_per_point=data_per_point) + with pytest.raises(TypeError): + LazyTractogram(streamlines=streamlines) + with pytest.raises(TypeError): + LazyTractogram(data_per_point={"none": None}) + with pytest.raises(TypeError): + LazyTractogram(data_per_streamline=data_per_streamline) + with pytest.raises(TypeError): + LazyTractogram(streamlines=DATA['streamlines'], data_per_point=data_per_point) # Empty `LazyTractogram` tractogram = LazyTractogram() check_tractogram(tractogram) - assert_true(tractogram.affine_to_rasmm is None) + assert tractogram.affine_to_rasmm is None # Create tractogram with streamlines and other data tractogram = LazyTractogram(DATA['streamlines_func'], DATA['data_per_streamline_func'], DATA['data_per_point_func']) - assert_true(is_lazy_dict(tractogram.data_per_streamline)) - assert_true(is_lazy_dict(tractogram.data_per_point)) + assert is_lazy_dict(tractogram.data_per_streamline) + assert is_lazy_dict(tractogram.data_per_point) [t for t in tractogram] # Force iteration through tractogram. - assert_equal(len(tractogram), len(DATA['streamlines'])) + assert len(tractogram) == len(DATA['streamlines']) # Generator functions get re-called and creates new iterators. for i in range(2): @@ -854,18 +855,20 @@ def _data_gen(): assert_tractogram_equal(tractogram, DATA['tractogram']) # Creating a LazyTractogram from not a corouting should raise an error. - assert_raises(TypeError, LazyTractogram.from_data_func, _data_gen()) + with pytest.raises(TypeError): + LazyTractogram.from_data_func(_data_gen()) def test_lazy_tractogram_getitem(self): - assert_raises(NotImplementedError, - DATA['lazy_tractogram'].__getitem__, 0) + with pytest.raises(NotImplementedError): + DATA['lazy_tractogram'][0] def test_lazy_tractogram_extend(self): t = DATA['lazy_tractogram'].copy() new_t = DATA['lazy_tractogram'].copy() for op in (operator.add, operator.iadd, extender): - assert_raises(NotImplementedError, op, new_t, t) + with pytest.raises(NotImplementedError): + op(new_t, t) def test_lazy_tractogram_len(self): modules = [module_tractogram] # Modules for which to catch warnings. @@ -874,35 +877,35 @@ def test_lazy_tractogram_len(self): # Calling `len` will create new generators each time. tractogram = LazyTractogram(DATA['streamlines_func']) - assert_true(tractogram._nb_streamlines is None) + assert tractogram._nb_streamlines is None # This should produce a warning message. - assert_equal(len(tractogram), len(DATA['streamlines'])) - assert_equal(tractogram._nb_streamlines, len(DATA['streamlines'])) - assert_equal(len(w), 1) + assert len(tractogram) == len(DATA['streamlines']) + assert tractogram._nb_streamlines == len(DATA['streamlines']) + assert len(w) == 1 tractogram = LazyTractogram(DATA['streamlines_func']) # New instances should still produce a warning message. - assert_equal(len(tractogram), len(DATA['streamlines'])) - assert_equal(len(w), 2) - assert_true(issubclass(w[-1].category, Warning)) + assert len(tractogram) == len(DATA['streamlines']) + assert len(w) == 2 + assert issubclass(w[-1].category, Warning) is True # Calling again 'len' again should *not* produce a warning. - assert_equal(len(tractogram), len(DATA['streamlines'])) - assert_equal(len(w), 2) + assert len(tractogram) == len(DATA['streamlines']) + assert len(w) == 2 with clear_and_catch_warnings(record=True, modules=modules) as w: # Once we iterated through the tractogram, we know the length. tractogram = LazyTractogram(DATA['streamlines_func']) - assert_true(tractogram._nb_streamlines is None) + assert tractogram._nb_streamlines is None [t for t in tractogram] # Force iteration through tractogram. - assert_equal(tractogram._nb_streamlines, len(DATA['streamlines'])) + assert tractogram._nb_streamlines == len(DATA['streamlines']) # This should *not* produce a warning. - assert_equal(len(tractogram), len(DATA['streamlines'])) - assert_equal(len(w), 0) + assert len(tractogram) == len(DATA['streamlines']) + assert len(w) == 0 def test_lazy_tractogram_apply_affine(self): affine = np.eye(4) @@ -912,7 +915,7 @@ def test_lazy_tractogram_apply_affine(self): tractogram = DATA['lazy_tractogram'].copy() transformed_tractogram = tractogram.apply_affine(affine) - assert_true(transformed_tractogram is not tractogram) + assert transformed_tractogram is not tractogram assert_array_equal(tractogram._affine_to_apply, np.eye(4)) assert_array_equal(tractogram.affine_to_rasmm, np.eye(4)) assert_array_equal(transformed_tractogram._affine_to_apply, affine) @@ -934,14 +937,15 @@ def test_lazy_tractogram_apply_affine(self): # Calling to_world when affine_to_rasmm is None should fail. tractogram = DATA['lazy_tractogram'].copy() tractogram.affine_to_rasmm = None - assert_raises(ValueError, tractogram.to_world) + with pytest.raises(ValueError): + tractogram.to_world() # But calling apply_affine when affine_to_rasmm is None should work. tractogram = DATA['lazy_tractogram'].copy() tractogram.affine_to_rasmm = None transformed_tractogram = tractogram.apply_affine(affine) assert_array_equal(transformed_tractogram._affine_to_apply, affine) - assert_true(transformed_tractogram.affine_to_rasmm is None) + assert transformed_tractogram.affine_to_rasmm is None check_tractogram(transformed_tractogram, streamlines=[s*scaling for s in DATA['streamlines']], data_per_streamline=DATA['data_per_streamline'], @@ -949,8 +953,9 @@ def test_lazy_tractogram_apply_affine(self): # Calling apply_affine with lazy=False should fail for LazyTractogram. tractogram = DATA['lazy_tractogram'].copy() - assert_raises(ValueError, tractogram.apply_affine, - affine=np.eye(4), lazy=False) + with pytest.raises(ValueError): + tractogram.apply_affine(affine=np.eye(4), lazy=False) + def test_tractogram_to_world(self): tractogram = DATA['lazy_tractogram'].copy() @@ -964,7 +969,7 @@ def test_tractogram_to_world(self): np.linalg.inv(affine)) tractogram_world = transformed_tractogram.to_world() - assert_true(tractogram_world is not transformed_tractogram) + assert tractogram_world is not transformed_tractogram assert_array_almost_equal(tractogram_world.affine_to_rasmm, np.eye(4)) for s1, s2 in zip(tractogram_world.streamlines, DATA['streamlines']): @@ -979,40 +984,37 @@ def test_tractogram_to_world(self): # Calling to_world when affine_to_rasmm is None should fail. tractogram = DATA['lazy_tractogram'].copy() tractogram.affine_to_rasmm = None - assert_raises(ValueError, tractogram.to_world) + with pytest.raises(ValueError): + tractogram.to_world() def test_lazy_tractogram_copy(self): # Create a copy of the lazy tractogram. tractogram = DATA['lazy_tractogram'].copy() # Check we copied the data and not simply created new references. - assert_true(tractogram is not DATA['lazy_tractogram']) + assert tractogram is not DATA['lazy_tractogram'] # When copying LazyTractogram, the generator function yielding # streamlines should stay the same. - assert_true(tractogram._streamlines - is DATA['lazy_tractogram']._streamlines) + assert tractogram._streamlines is DATA['lazy_tractogram']._streamlines # Copying LazyTractogram, creates new internal LazyDict objects, # but generator functions contained in it should stay the same. - assert_true(tractogram._data_per_streamline - is not DATA['lazy_tractogram']._data_per_streamline) - assert_true(tractogram._data_per_point - is not DATA['lazy_tractogram']._data_per_point) + assert tractogram._data_per_streamline is not DATA['lazy_tractogram']._data_per_streamline + assert tractogram._data_per_point is not DATA['lazy_tractogram']._data_per_point for key in tractogram.data_per_streamline: data = tractogram.data_per_streamline.store[key] expected = DATA['lazy_tractogram'].data_per_streamline.store[key] - assert_true(data is expected) + assert data is expected for key in tractogram.data_per_point: data = tractogram.data_per_point.store[key] expected = DATA['lazy_tractogram'].data_per_point.store[key] - assert_true(data is expected) + assert data is expected # The affine should be a copy. - assert_true(tractogram._affine_to_apply - is not DATA['lazy_tractogram']._affine_to_apply) + assert tractogram._affine_to_apply is not DATA['lazy_tractogram']._affine_to_apply assert_array_equal(tractogram._affine_to_apply, DATA['lazy_tractogram']._affine_to_apply) diff --git a/nibabel/streamlines/tests/test_tractogram_file.py b/nibabel/streamlines/tests/test_tractogram_file.py index da5bce4b3f..2550ecf03d 100644 --- a/nibabel/streamlines/tests/test_tractogram_file.py +++ b/nibabel/streamlines/tests/test_tractogram_file.py @@ -4,7 +4,7 @@ from ..tractogram import Tractogram from ..tractogram_file import TractogramFile -from nose.tools import assert_raises, assert_equal +import pytest def test_subclassing_tractogram_file(): @@ -23,7 +23,8 @@ def load(cls, fileobj, lazy_load=True): def create_empty_header(cls): return None - assert_raises(TypeError, DummyTractogramFile, Tractogram()) + with pytest.raises(TypeError): + DummyTractogramFile(Tractogram()) # Missing 'load' method class DummyTractogramFile(TractogramFile): @@ -38,7 +39,8 @@ def save(self, fileobj): def create_empty_header(cls): return None - assert_raises(TypeError, DummyTractogramFile, Tractogram()) + with pytest.raises(TypeError): + DummyTractogramFile(Tractogram()) # Now we have everything required. class DummyTractogramFile(TractogramFile): @@ -57,12 +59,14 @@ def save(self, fileobj): dtf = DummyTractogramFile(Tractogram()) # Default create_empty_header is empty dict - assert_equal(dtf.header, {}) + assert dtf.header == {} def test_tractogram_file(): - assert_raises(NotImplementedError, TractogramFile.is_correct_format, "") - assert_raises(NotImplementedError, TractogramFile.load, "") + with pytest.raises(NotImplementedError): + TractogramFile.is_correct_format("") + with pytest.raises(NotImplementedError): + TractogramFile.load("") # Testing calling the 'save' method of `TractogramFile` object. class DummyTractogramFile(TractogramFile): @@ -78,6 +82,5 @@ def load(cls, fileobj, lazy_load=True): def save(self, fileobj): pass - assert_raises(NotImplementedError, - super(DummyTractogramFile, - DummyTractogramFile(Tractogram)).save, "") + with pytest.raises(NotImplementedError): + super(DummyTractogramFile, DummyTractogramFile(Tractogram)).save("") diff --git a/nibabel/streamlines/tests/test_trk.py b/nibabel/streamlines/tests/test_trk.py index a0a3d8a1f3..8fb35fc368 100644 --- a/nibabel/streamlines/tests/test_trk.py +++ b/nibabel/streamlines/tests/test_trk.py @@ -7,9 +7,8 @@ from io import BytesIO -from nibabel.testing import data_path -from nibabel.testing import clear_and_catch_warnings, assert_arr_dict_equal -from nose.tools import assert_equal, assert_raises, assert_true +import pytest +from ...testing import data_path, clear_and_catch_warnings, assert_arr_dict_equal from numpy.testing import assert_array_equal from .test_tractogram import assert_tractogram_equal @@ -23,7 +22,7 @@ DATA = {} -def setup(): +def setup_module(): global DATA DATA['empty_trk_fname'] = pjoin(data_path, "empty.trk") @@ -132,45 +131,51 @@ def test_load_file_with_wrong_information(self): trk_struct[Field.VOXEL_TO_RASMM] = np.zeros((4, 4)) with clear_and_catch_warnings(record=True, modules=[trk_module]) as w: trk = TrkFile.load(BytesIO(trk_bytes)) - assert_equal(len(w), 1) - assert_true(issubclass(w[0].category, HeaderWarning)) - assert_true("identity" in str(w[0].message)) + assert len(w) == 1 + assert issubclass(w[0].category, HeaderWarning) + assert "identity" in str(w[0].message) assert_array_equal(trk.affine, np.eye(4)) # Simulate a TRK where `vox_to_ras` is invalid. trk_struct, trk_bytes = self.trk_with_bytes() trk_struct[Field.VOXEL_TO_RASMM] = np.diag([0, 0, 0, 1]) with clear_and_catch_warnings(record=True, modules=[trk_module]) as w: - assert_raises(HeaderError, TrkFile.load, BytesIO(trk_bytes)) + with pytest.raises(HeaderError): + TrkFile.load(BytesIO(trk_bytes)) # Simulate a TRK file where `voxel_order` was not provided. trk_struct, trk_bytes = self.trk_with_bytes() trk_struct[Field.VOXEL_ORDER] = b'' with clear_and_catch_warnings(record=True, modules=[trk_module]) as w: TrkFile.load(BytesIO(trk_bytes)) - assert_equal(len(w), 1) - assert_true(issubclass(w[0].category, HeaderWarning)) - assert_true("LPS" in str(w[0].message)) + assert len(w) == 1 + assert issubclass(w[0].category, HeaderWarning) + assert "LPS" in str(w[0].message) # Simulate a TRK file with an unsupported version. trk_struct, trk_bytes = self.trk_with_bytes() trk_struct['version'] = 123 - assert_raises(HeaderError, TrkFile.load, BytesIO(trk_bytes)) + with pytest.raises(HeaderError): + TrkFile.load(BytesIO(trk_bytes)) + # Simulate a TRK file with a wrong hdr_size. trk_struct, trk_bytes = self.trk_with_bytes() trk_struct['hdr_size'] = 1234 - assert_raises(HeaderError, TrkFile.load, BytesIO(trk_bytes)) + with pytest.raises(HeaderError): + TrkFile.load(BytesIO(trk_bytes)) # Simulate a TRK file with a wrong scalar_name. trk_struct, trk_bytes = self.trk_with_bytes('complex_trk_fname') trk_struct['scalar_name'][0, 0] = b'colors\x003\x004' - assert_raises(HeaderError, TrkFile.load, BytesIO(trk_bytes)) + with pytest.raises(HeaderError): + TrkFile.load(BytesIO(trk_bytes)) # Simulate a TRK file with a wrong property_name. trk_struct, trk_bytes = self.trk_with_bytes('complex_trk_fname') trk_struct['property_name'][0, 0] = b'colors\x003\x004' - assert_raises(HeaderError, TrkFile.load, BytesIO(trk_bytes)) + with pytest.raises(HeaderError): + TrkFile.load(BytesIO(trk_bytes)) def test_load_trk_version_1(self): # Simulate and test a TRK (version 1). @@ -183,9 +188,9 @@ def test_load_trk_version_1(self): trk_struct['version'] = 1 with clear_and_catch_warnings(record=True, modules=[trk_module]) as w: trk = TrkFile.load(BytesIO(trk_bytes)) - assert_equal(len(w), 1) - assert_true(issubclass(w[0].category, HeaderWarning)) - assert_true("identity" in str(w[0].message)) + assert len(w) == 1 + assert issubclass(w[0].category, HeaderWarning) + assert "identity" in str(w[0].message) assert_array_equal(trk.affine, np.eye(4)) assert_array_equal(trk.header['version'], 1) @@ -195,8 +200,8 @@ def test_load_complex_file_in_big_endian(self): # We use hdr_size as an indicator of little vs big endian. good_orders = '>' if sys.byteorder == 'little' else '>=' hdr_size = trk_struct['hdr_size'] - assert_true(hdr_size.dtype.byteorder in good_orders) - assert_equal(hdr_size, 1000) + assert hdr_size.dtype.byteorder in good_orders + assert hdr_size == 1000 for lazy_load in [False, True]: trk = TrkFile.load(DATA['complex_trk_big_endian_fname'], @@ -205,7 +210,7 @@ def test_load_complex_file_in_big_endian(self): def test_tractogram_file_properties(self): trk = TrkFile.load(DATA['simple_trk_fname']) - assert_equal(trk.streamlines, trk.tractogram.streamlines) + assert trk.streamlines == trk.tractogram.streamlines assert_array_equal(trk.affine, trk.header[Field.VOXEL_TO_RASMM]) def test_write_empty_file(self): @@ -223,8 +228,7 @@ def test_write_empty_file(self): assert_tractogram_equal(new_trk.tractogram, new_trk_orig.tractogram) trk_file.seek(0, os.SEEK_SET) - assert_equal(trk_file.read(), - open(DATA['empty_trk_fname'], 'rb').read()) + assert trk_file.read() == open(DATA['empty_trk_fname'], 'rb').read() def test_write_simple_file(self): tractogram = Tractogram(DATA['streamlines'], @@ -242,8 +246,7 @@ def test_write_simple_file(self): assert_tractogram_equal(new_trk.tractogram, new_trk_orig.tractogram) trk_file.seek(0, os.SEEK_SET) - assert_equal(trk_file.read(), - open(DATA['simple_trk_fname'], 'rb').read()) + assert trk_file.read() == open(DATA['simple_trk_fname'], 'rb').read() def test_write_complex_file(self): # With scalars @@ -292,8 +295,7 @@ def test_write_complex_file(self): assert_tractogram_equal(new_trk.tractogram, new_trk_orig.tractogram) trk_file.seek(0, os.SEEK_SET) - assert_equal(trk_file.read(), - open(DATA['complex_trk_fname'], 'rb').read()) + assert trk_file.read() == open(DATA['complex_trk_fname'], 'rb').read() def test_load_write_file(self): for fname in [DATA['empty_trk_fname'], @@ -328,8 +330,7 @@ def test_load_write_LPS_file(self): assert_tractogram_equal(new_trk.tractogram, new_trk_orig.tractogram) trk_file.seek(0, os.SEEK_SET) - assert_equal(trk_file.read(), - open(DATA['standard_LPS_trk_fname'], 'rb').read()) + assert trk_file.read() == open(DATA['standard_LPS_trk_fname'], 'rb').read() # Test writing a file where the header is missing the # Field.VOXEL_ORDER. @@ -352,8 +353,7 @@ def test_load_write_LPS_file(self): assert_tractogram_equal(new_trk.tractogram, new_trk_orig.tractogram) trk_file.seek(0, os.SEEK_SET) - assert_equal(trk_file.read(), - open(DATA['standard_LPS_trk_fname'], 'rb').read()) + assert trk_file.read() == open(DATA['standard_LPS_trk_fname'], 'rb').read() def test_write_optional_header_fields(self): # The TRK file format doesn't support additional header fields. @@ -367,7 +367,7 @@ def test_write_optional_header_fields(self): trk_file.seek(0, os.SEEK_SET) new_trk = TrkFile.load(trk_file) - assert_true("extra" not in new_trk.header) + assert "extra" not in new_trk.header def test_write_too_many_scalars_and_properties(self): # TRK supports up to 10 data_per_point. @@ -395,7 +395,8 @@ def test_write_too_many_scalars_and_properties(self): affine_to_rasmm=np.eye(4)) trk = TrkFile(tractogram) - assert_raises(ValueError, trk.save, BytesIO()) + with pytest.raises(ValueError): + trk.save(BytesIO()) # TRK supports up to 10 data_per_streamline. data_per_streamline = {} @@ -421,7 +422,8 @@ def test_write_too_many_scalars_and_properties(self): data_per_streamline=data_per_streamline) trk = TrkFile(tractogram) - assert_raises(ValueError, trk.save, BytesIO()) + with pytest.raises(ValueError): + trk.save(BytesIO()) def test_write_scalars_and_properties_name_too_long(self): # TRK supports data_per_point name up to 20 characters. @@ -437,7 +439,8 @@ def test_write_scalars_and_properties_name_too_long(self): trk = TrkFile(tractogram) if nb_chars > 18: - assert_raises(ValueError, trk.save, BytesIO()) + with pytest.raises(ValueError): + trk.save(BytesIO()) else: trk.save(BytesIO()) @@ -448,7 +451,8 @@ def test_write_scalars_and_properties_name_too_long(self): trk = TrkFile(tractogram) if nb_chars > 20: - assert_raises(ValueError, trk.save, BytesIO()) + with pytest.raises(ValueError): + trk.save(BytesIO()) else: trk.save(BytesIO()) @@ -465,7 +469,8 @@ def test_write_scalars_and_properties_name_too_long(self): trk = TrkFile(tractogram) if nb_chars > 18: - assert_raises(ValueError, trk.save, BytesIO()) + with pytest.raises(ValueError): + trk.save(BytesIO()) else: trk.save(BytesIO()) @@ -476,7 +481,8 @@ def test_write_scalars_and_properties_name_too_long(self): trk = TrkFile(tractogram) if nb_chars > 20: - assert_raises(ValueError, trk.save, BytesIO()) + with pytest.raises(ValueError): + trk.save(BytesIO()) else: trk.save(BytesIO()) @@ -498,32 +504,37 @@ def test_header_read_restore(self): hdr_from_fname['_offset_data'] += hdr_pos # Correct for start position assert_arr_dict_equal(TrkFile._read_header(bio), hdr_from_fname) # Check fileobject file position has not changed - assert_equal(bio.tell(), hdr_pos) + assert bio.tell() == hdr_pos def test_encode_names(): # Test function for encoding numbers into property names b0 = b'\x00' - assert_equal(encode_value_in_name(0, 'foo', 10), - b'foo' + b0 * 7) - assert_equal(encode_value_in_name(1, 'foo', 10), - b'foo' + b0 * 7) - assert_equal(encode_value_in_name(8, 'foo', 10), - b'foo' + b0 + b'8' + b0 * 5) - assert_equal(encode_value_in_name(40, 'foobar', 10), - b'foobar' + b0 + b'40' + b0) - assert_equal(encode_value_in_name(1, 'foobarbazz', 10), b'foobarbazz') - assert_raises(ValueError, encode_value_in_name, 1, 'foobarbazzz', 10) - assert_raises(ValueError, encode_value_in_name, 2, 'foobarbaz', 10) - assert_equal(encode_value_in_name(2, 'foobarba', 10), b'foobarba\x002') + assert encode_value_in_name(0, 'foo', 10) == b'foo' + b0 * 7 + assert encode_value_in_name(1, 'foo', 10) == b'foo' + b0 * 7 + assert encode_value_in_name(8, 'foo', 10) == b'foo' + b0 + b'8' + b0 * 5 + assert encode_value_in_name(40, 'foobar', 10) == b'foobar' + b0 + b'40' + b0 + assert encode_value_in_name(1, 'foobarbazz', 10) == b'foobarbazz' + + with pytest.raises(ValueError): + encode_value_in_name(1, 'foobarbazzz', 10) + + with pytest.raises(ValueError): + encode_value_in_name(2, 'foobarbazzz', 10) + + assert encode_value_in_name(2, 'foobarba', 10) == b'foobarba\x002' def test_decode_names(): # Test function for decoding name string into name, number b0 = b'\x00' - assert_equal(decode_value_from_name(b''), ('', 0)) - assert_equal(decode_value_from_name(b'foo' + b0 * 7), ('foo', 1)) - assert_equal(decode_value_from_name(b'foo\x008' + b0 * 5), ('foo', 8)) - assert_equal(decode_value_from_name(b'foobar\x0010\x00'), ('foobar', 10)) - assert_raises(ValueError, decode_value_from_name, b'foobar\x0010\x01') - assert_raises(HeaderError, decode_value_from_name, b'foo\x0010\x00111') + assert decode_value_from_name(b'') == ('', 0) + assert decode_value_from_name(b'foo' + b0 * 7) == ('foo', 1) + assert decode_value_from_name(b'foo\x008' + b0 * 5) == ('foo', 8) + assert decode_value_from_name(b'foobar\x0010\x00') == ('foobar', 10) + + with pytest.raises(ValueError): + decode_value_from_name(b'foobar\x0010\x01') + + with pytest.raises(HeaderError): + decode_value_from_name(b'foo\x0010\x00111') diff --git a/nibabel/streamlines/tests/test_utils.py b/nibabel/streamlines/tests/test_utils.py index 939ee9bb9e..bcdde6d013 100644 --- a/nibabel/streamlines/tests/test_utils.py +++ b/nibabel/streamlines/tests/test_utils.py @@ -4,7 +4,8 @@ from nibabel.testing import data_path from numpy.testing import assert_array_equal -from nose.tools import assert_raises + +import pytest from ..utils import get_affine_from_reference @@ -17,7 +18,8 @@ def test_get_affine_from_reference(): # Get affine from an numpy array. assert_array_equal(get_affine_from_reference(affine), affine) wrong_ref = np.array([[1, 2, 3], [4, 5, 6]]) - assert_raises(ValueError, get_affine_from_reference, wrong_ref) + with pytest.raises(ValueError): + get_affine_from_reference(wrong_ref) # Get affine from a `SpatialImage`. assert_array_equal(get_affine_from_reference(img), affine) diff --git a/nibabel/testing/__init__.py b/nibabel/testing/__init__.py index fbd1128589..52055ebcc3 100644 --- a/nibabel/testing/__init__.py +++ b/nibabel/testing/__init__.py @@ -13,22 +13,14 @@ import sys import warnings from pkg_resources import resource_filename -from os.path import dirname, abspath, join as pjoin -import numpy as np -from numpy.testing import assert_array_equal, assert_warns -from numpy.testing import dec -skipif = dec.skipif -slow = dec.slow +import unittest -from ..deprecated import deprecate_with_version as _deprecate_with_version +import numpy as np +from numpy.testing import assert_array_equal -# Allow failed import of nose if not now running tests -try: - from nose.tools import (assert_equal, assert_not_equal, - assert_true, assert_false, assert_raises) -except ImportError: - pass +from .np_features import memmap_after_ufunc +from .helpers import bytesio_filemap, bytesio_round_trip, assert_data_similar from itertools import zip_longest @@ -51,14 +43,12 @@ def test_data(subdir=None, fname=None): data_path = test_data() -from .np_features import memmap_after_ufunc - def assert_dt_equal(a, b): """ Assert two numpy dtype specifiers are equal Avoids failed comparison between int32 / int64 and intp """ - assert_equal(np.dtype(a).str, np.dtype(b).str) + assert np.dtype(a).str == np.dtype(b).str def assert_allclose_safely(a, b, match_nans=True, rtol=1e-5, atol=1e-8): @@ -68,7 +58,7 @@ def assert_allclose_safely(a, b, match_nans=True, rtol=1e-5, atol=1e-8): a, b = np.broadcast_arrays(a, b) if match_nans: nans = np.isnan(a) - np.testing.assert_array_equal(nans, np.isnan(b)) + assert_array_equal(nans, np.isnan(b)) to_test = ~nans else: to_test = np.ones(a.shape, dtype=bool) @@ -81,13 +71,13 @@ def assert_allclose_safely(a, b, match_nans=True, rtol=1e-5, atol=1e-8): a = a.astype(float) if b.dtype.kind in 'ui': b = b.astype(float) - assert_true(np.allclose(a, b, rtol=rtol, atol=atol)) + assert np.allclose(a, b, rtol=rtol, atol=atol) def assert_arrays_equal(arrays1, arrays2): """ Check two iterables yield the same sequence of arrays. """ for arr1, arr2 in zip_longest(arrays1, arrays2, fillvalue=None): - assert_false(arr1 is None or arr2 is None) + assert (arr1 is not None and arr2 is not None) assert_array_equal(arr1, arr2) @@ -204,26 +194,30 @@ class suppress_warnings(error_warnings): filter = 'ignore' -@_deprecate_with_version('catch_warn_reset is deprecated; use ' - 'nibabel.testing.clear_and_catch_warnings.', - since='2.1.0', until='3.0.0') -class catch_warn_reset(clear_and_catch_warnings): - pass - - EXTRA_SET = os.environ.get('NIPY_EXTRA_TESTS', '').split(',') def runif_extra_has(test_str): """Decorator checks to see if NIPY_EXTRA_TESTS env var contains test_str""" - return skipif(test_str not in EXTRA_SET, - "Skip {0} tests.".format(test_str)) + return unittest.skipUnless(test_str in EXTRA_SET, "Skip {0} tests.".format(test_str)) def assert_arr_dict_equal(dict1, dict2): """ Assert that two dicts are equal, where dicts contain arrays """ - assert_equal(set(dict1), set(dict2)) + assert set(dict1) == set(dict2) for key, value1 in dict1.items(): value2 = dict2[key] assert_array_equal(value1, value2) + + +class BaseTestCase(unittest.TestCase): + """ TestCase that does not attempt to run if prefixed with a ``_`` + + This restores the nose-like behavior of skipping so-named test cases + in test runners like pytest. + """ + def setUp(self): + if self.__class__.__name__.startswith('_'): + raise unittest.SkipTest("Base test case - subclass to run") + super().setUp() diff --git a/nibabel/tests/test_helpers.py b/nibabel/testing/helpers.py similarity index 88% rename from nibabel/tests/test_helpers.py rename to nibabel/testing/helpers.py index 928b4bd1a3..49112fddfb 100644 --- a/nibabel/tests/test_helpers.py +++ b/nibabel/testing/helpers.py @@ -4,12 +4,9 @@ import numpy as np -from ..openers import ImageOpener -from ..tmpdirs import InTemporaryDirectory from ..optpkg import optional_package _, have_scipy, _ = optional_package('scipy.io') -from nose.tools import assert_true from numpy.testing import assert_array_equal @@ -51,6 +48,6 @@ def assert_data_similar(arr, params): return summary = params['data_summary'] real_arr = np.asarray(arr) - assert_true(np.allclose( + assert np.allclose( (real_arr.min(), real_arr.max(), real_arr.mean()), - (summary['min'], summary['max'], summary['mean']))) + (summary['min'], summary['max'], summary['mean'])) diff --git a/nibabel/testing_pytest/__init__.py b/nibabel/testing_pytest/__init__.py deleted file mode 100644 index 675c506e3b..0000000000 --- a/nibabel/testing_pytest/__init__.py +++ /dev/null @@ -1,223 +0,0 @@ -# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- -# vi: set ft=python sts=4 ts=4 sw=4 et: -### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## -# -# See COPYING file distributed along with the NiBabel package for the -# copyright and license terms. -# -### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## -''' Utilities for testing ''' - -import re -import os -import sys -import warnings -from pkg_resources import resource_filename -from os.path import dirname, abspath, join as pjoin - -import numpy as np -from numpy.testing import assert_array_equal, assert_warns -from numpy.testing import dec -skipif = dec.skipif -slow = dec.slow - -from ..deprecated import deprecate_with_version as _deprecate_with_version - - -from itertools import zip_longest - - -def test_data(subdir=None, fname=None): - if subdir is None: - resource = os.path.join('tests', 'data') - elif subdir in ('gifti', 'nicom', 'externals'): - resource = os.path.join(subdir, 'tests', 'data') - else: - raise ValueError("Unknown test data directory: %s" % subdir) - - if fname is not None: - resource = os.path.join(resource, fname) - - return resource_filename('nibabel', resource) - - -# set path to example data -data_path = test_data() - - -from .np_features import memmap_after_ufunc - -def assert_dt_equal(a, b): - """ Assert two numpy dtype specifiers are equal - - Avoids failed comparison between int32 / int64 and intp - """ - assert np.dtype(a).str == np.dtype(b).str - - -def assert_allclose_safely(a, b, match_nans=True, rtol=1e-5, atol=1e-8): - """ Allclose in integers go all wrong for large integers - """ - a = np.atleast_1d(a) # 0d arrays cannot be indexed - a, b = np.broadcast_arrays(a, b) - if match_nans: - nans = np.isnan(a) - np.testing.assert_array_equal(nans, np.isnan(b)) - to_test = ~nans - else: - to_test = np.ones(a.shape, dtype=bool) - # Deal with float128 inf comparisons (bug in numpy 1.9.2) - # np.allclose(np.float128(np.inf), np.float128(np.inf)) == False - to_test = to_test & (a != b) - a = a[to_test] - b = b[to_test] - if a.dtype.kind in 'ui': - a = a.astype(float) - if b.dtype.kind in 'ui': - b = b.astype(float) - assert np.allclose(a, b, rtol=rtol, atol=atol) - - -def assert_arrays_equal(arrays1, arrays2): - """ Check two iterables yield the same sequence of arrays. """ - for arr1, arr2 in zip_longest(arrays1, arrays2, fillvalue=None): - assert (arr1 is not None and arr2 is not None) - assert_array_equal(arr1, arr2) - - -def assert_re_in(regex, c, flags=0): - """Assert that container (list, str, etc) contains entry matching the regex - """ - if not isinstance(c, (list, tuple)): - c = [c] - for e in c: - if re.match(regex, e, flags=flags): - return - raise AssertionError("Not a single entry matched %r in %r" % (regex, c)) - - -def get_fresh_mod(mod_name=__name__): - # Get this module, with warning registry empty - my_mod = sys.modules[mod_name] - try: - my_mod.__warningregistry__.clear() - except AttributeError: - pass - return my_mod - - -class clear_and_catch_warnings(warnings.catch_warnings): - """ Context manager that resets warning registry for catching warnings - - Warnings can be slippery, because, whenever a warning is triggered, Python - adds a ``__warningregistry__`` member to the *calling* module. This makes - it impossible to retrigger the warning in this module, whatever you put in - the warnings filters. This context manager accepts a sequence of `modules` - as a keyword argument to its constructor and: - - * stores and removes any ``__warningregistry__`` entries in given `modules` - on entry; - * resets ``__warningregistry__`` to its previous state on exit. - - This makes it possible to trigger any warning afresh inside the context - manager without disturbing the state of warnings outside. - - For compatibility with Python 3.0, please consider all arguments to be - keyword-only. - - Parameters - ---------- - record : bool, optional - Specifies whether warnings should be captured by a custom - implementation of ``warnings.showwarning()`` and be appended to a list - returned by the context manager. Otherwise None is returned by the - context manager. The objects appended to the list are arguments whose - attributes mirror the arguments to ``showwarning()``. - - NOTE: nibabel difference from numpy: default is True - - modules : sequence, optional - Sequence of modules for which to reset warnings registry on entry and - restore on exit - - Examples - -------- - >>> import warnings - >>> with clear_and_catch_warnings(modules=[np.core.fromnumeric]): - ... warnings.simplefilter('always') - ... # do something that raises a warning in np.core.fromnumeric - """ - class_modules = () - - def __init__(self, record=True, modules=()): - self.modules = set(modules).union(self.class_modules) - self._warnreg_copies = {} - super(clear_and_catch_warnings, self).__init__(record=record) - - def __enter__(self): - for mod in self.modules: - if hasattr(mod, '__warningregistry__'): - mod_reg = mod.__warningregistry__ - self._warnreg_copies[mod] = mod_reg.copy() - mod_reg.clear() - return super(clear_and_catch_warnings, self).__enter__() - - def __exit__(self, *exc_info): - super(clear_and_catch_warnings, self).__exit__(*exc_info) - for mod in self.modules: - if hasattr(mod, '__warningregistry__'): - mod.__warningregistry__.clear() - if mod in self._warnreg_copies: - mod.__warningregistry__.update(self._warnreg_copies[mod]) - - -class error_warnings(clear_and_catch_warnings): - """ Context manager to check for warnings as errors. Usually used with - ``assert_raises`` in the with block - - Examples - -------- - >>> with error_warnings(): - ... try: - ... warnings.warn('Message', UserWarning) - ... except UserWarning: - ... print('I consider myself warned') - I consider myself warned - """ - filter = 'error' - - def __enter__(self): - mgr = super(error_warnings, self).__enter__() - warnings.simplefilter(self.filter) - return mgr - - -class suppress_warnings(error_warnings): - """ Version of ``catch_warnings`` class that suppresses warnings - """ - filter = 'ignore' - - -@_deprecate_with_version('catch_warn_reset is deprecated; use ' - 'nibabel.testing.clear_and_catch_warnings.', - since='2.1.0', until='3.0.0') -class catch_warn_reset(clear_and_catch_warnings): - pass - - -EXTRA_SET = os.environ.get('NIPY_EXTRA_TESTS', '').split(',') - - -def runif_extra_has(test_str): - """Decorator checks to see if NIPY_EXTRA_TESTS env var contains test_str""" - return skipif(test_str not in EXTRA_SET, - "Skip {0} tests.".format(test_str)) - - -def assert_arr_dict_equal(dict1, dict2): - """ Assert that two dicts are equal, where dicts contain arrays - """ - assert set(dict1) == set(dict2) - for key, value1 in dict1.items(): - value2 = dict2[key] - assert_array_equal(value1, value2) diff --git a/nibabel/testing_pytest/np_features.py b/nibabel/testing_pytest/np_features.py deleted file mode 100644 index 8919542d1c..0000000000 --- a/nibabel/testing_pytest/np_features.py +++ /dev/null @@ -1,23 +0,0 @@ -""" Look for changes in numpy behavior over versions -""" - -import numpy as np - - -def memmap_after_ufunc(): - """ Return True if ufuncs on memmap arrays always return memmap arrays - - This should be True for numpy < 1.12, False otherwise. - - Memoize after first call. We do this to avoid having to call this when - importing nibabel.testing, because we cannot depend on the source file - being present - see gh-571. - """ - if memmap_after_ufunc.result is not None: - return memmap_after_ufunc.result - with open(__file__, 'rb') as fobj: - mm_arr = np.memmap(fobj, mode='r', shape=(10,), dtype=np.uint8) - memmap_after_ufunc.result = isinstance(mm_arr + 1, np.memmap) - return memmap_after_ufunc.result - -memmap_after_ufunc.result = None diff --git a/nibabel/tests/data/gen_standard.py b/nibabel/tests/data/gen_standard.py index b97da8ff2f..f966b5599d 100644 --- a/nibabel/tests/data/gen_standard.py +++ b/nibabel/tests/data/gen_standard.py @@ -52,35 +52,36 @@ def _gen_straight_streamline(start, end, steps=3): return streamlines -rng = np.random.RandomState(42) - -width = 4 # Coronal -height = 5 # Sagittal -depth = 7 # Axial - -voxel_size = np.array((1., 3., 2.)) - -# Generate a random mask with voxel order RAS+. -mask = rng.rand(width, height, depth) > 0.8 -mask = (255*mask).astype(np.uint8) - -# Build tractogram -streamlines = mark_the_spot(mask) -tractogram = nib.streamlines.Tractogram(streamlines) - -# Build header -affine = np.eye(4) -affine[range(3), range(3)] = voxel_size -header = {Field.DIMENSIONS: (width, height, depth), - Field.VOXEL_SIZES: voxel_size, - Field.VOXEL_TO_RASMM: affine, - Field.VOXEL_ORDER: 'RAS'} - -# Save the standard mask. -nii = nib.Nifti1Image(mask, affine=affine) -nib.save(nii, "standard.nii.gz") - -# Save the standard tractogram in every available file format. -for ext, cls in FORMATS.items(): - tfile = cls(tractogram, header) - nib.streamlines.save(tfile, "standard" + ext) +if __name__ == '__main__': + rng = np.random.RandomState(42) + + width = 4 # Coronal + height = 5 # Sagittal + depth = 7 # Axial + + voxel_size = np.array((1., 3., 2.)) + + # Generate a random mask with voxel order RAS+. + mask = rng.rand(width, height, depth) > 0.8 + mask = (255*mask).astype(np.uint8) + + # Build tractogram + streamlines = mark_the_spot(mask) + tractogram = nib.streamlines.Tractogram(streamlines) + + # Build header + affine = np.eye(4) + affine[range(3), range(3)] = voxel_size + header = {Field.DIMENSIONS: (width, height, depth), + Field.VOXEL_SIZES: voxel_size, + Field.VOXEL_TO_RASMM: affine, + Field.VOXEL_ORDER: 'RAS'} + + # Save the standard mask. + nii = nib.Nifti1Image(mask, affine=affine) + nib.save(nii, "standard.nii.gz") + + # Save the standard tractogram in every available file format. + for ext, cls in FORMATS.items(): + tfile = cls(tractogram, header) + nib.streamlines.save(tfile, "standard" + ext) diff --git a/nibabel/tests/data/make_moved_anat.py b/nibabel/tests/data/make_moved_anat.py index 6fba2d0902..ec0817885c 100644 --- a/nibabel/tests/data/make_moved_anat.py +++ b/nibabel/tests/data/make_moved_anat.py @@ -12,11 +12,12 @@ from nibabel.eulerangles import euler2mat from nibabel.affines import from_matvec -img = nib.load('anatomical.nii') -some_rotations = euler2mat(0.1, 0.2, 0.3) -extra_affine = from_matvec(some_rotations, [3, 4, 5]) -moved_anat = nib.Nifti1Image(img.dataobj, - extra_affine.dot(img.affine), - img.header) -moved_anat.set_data_dtype(np.float32) -nib.save(moved_anat, 'anat_moved.nii') +if __name__ == '__main__': + img = nib.load('anatomical.nii') + some_rotations = euler2mat(0.1, 0.2, 0.3) + extra_affine = from_matvec(some_rotations, [3, 4, 5]) + moved_anat = nib.Nifti1Image(img.dataobj, + extra_affine.dot(img.affine), + img.header) + moved_anat.set_data_dtype(np.float32) + nib.save(moved_anat, 'anat_moved.nii') diff --git a/nibabel/tests/nibabel_data.py b/nibabel/tests/nibabel_data.py index 529e103f46..3c1b58502d 100644 --- a/nibabel/tests/nibabel_data.py +++ b/nibabel/tests/nibabel_data.py @@ -4,7 +4,7 @@ from os import environ, listdir from os.path import dirname, realpath, join as pjoin, isdir, exists -from ..testing import skipif +import unittest def get_nibabel_data(): @@ -39,11 +39,11 @@ def needs_nibabel_data(subdir=None): """ nibabel_data = get_nibabel_data() if nibabel_data == '': - return skipif(True, "Need nibabel-data directory for this test") + return unittest.skip("Need nibabel-data directory for this test") if subdir is None: - return skipif(False) + return lambda x: x required_path = pjoin(nibabel_data, subdir) # Path should not be empty (as is the case for not-updated submodules) have_files = exists(required_path) and len(listdir(required_path)) > 0 - return skipif(not have_files, - "Need files in {0} for these tests".format(required_path)) + return unittest.skipUnless(have_files, + "Need files in {0} for these tests".format(required_path)) 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 6b05df83e3..b092a2334c 100644 --- a/nibabel/tests/test_analyze.py +++ b/nibabel/tests/test_analyze.py @@ -31,18 +31,14 @@ from ..tmpdirs import InTemporaryDirectory from ..arraywriters import WriterError -from nose.tools import (assert_equal, assert_not_equal, assert_true, - assert_false, assert_raises) - +import pytest from numpy.testing import (assert_array_equal, assert_array_almost_equal) -from ..testing import (assert_equal, assert_not_equal, assert_true, - assert_false, assert_raises, data_path, - suppress_warnings, assert_dt_equal) +from ..testing import (data_path, suppress_warnings, assert_dt_equal, + bytesio_filemap, bytesio_round_trip) from .test_wrapstruct import _TestLabeledWrapStruct from . import test_spatialimages as tsi -from .test_helpers import bytesio_filemap, bytesio_round_trip header_file = os.path.join(data_path, 'analyze.hdr') @@ -71,8 +67,7 @@ class TestAnalyzeHeader(_TestLabeledWrapStruct): def test_supported_types(self): hdr = self.header_class() - assert_equal(self.supported_np_types, - supported_np_types(hdr)) + assert self.supported_np_types == supported_np_types(hdr) def get_bad_bb(self): # A value for the binary block that should raise an error @@ -84,7 +79,7 @@ def test_general_init(self): hdr = self.header_class() # an empty header has shape (0,) - like an empty array # (np.array([])) - assert_equal(hdr.get_data_shape(), (0,)) + assert hdr.get_data_shape() == (0,) # The affine is always homogenous 3D regardless of shape. The # default affine will have -1 as the X zoom iff default_x_flip # is True (which it is by default). We have to be careful of the @@ -93,20 +88,20 @@ def test_general_init(self): assert_array_equal(np.diag(hdr.get_base_affine()), [-1, 1, 1, 1]) # But zooms only go with number of dimensions - assert_equal(hdr.get_zooms(), (1.0,)) + assert hdr.get_zooms() == (1.0,) def test_header_size(self): - assert_equal(self.header_class.template_dtype.itemsize, self.sizeof_hdr) + assert self.header_class.template_dtype.itemsize == self.sizeof_hdr def test_empty(self): hdr = self.header_class() - assert_true(len(hdr.binaryblock) == self.sizeof_hdr) - assert_true(hdr['sizeof_hdr'] == self.sizeof_hdr) - assert_true(np.all(hdr['dim'][1:] == 1)) - assert_true(hdr['dim'][0] == 0) - assert_true(np.all(hdr['pixdim'] == 1)) - assert_true(hdr['datatype'] == 16) # float32 - assert_true(hdr['bitpix'] == 32) + assert len(hdr.binaryblock) == self.sizeof_hdr + assert hdr['sizeof_hdr'] == self.sizeof_hdr + assert np.all(hdr['dim'][1:] == 1) + assert hdr['dim'][0] == 0 + assert np.all(hdr['pixdim'] == 1) + assert hdr['datatype'] == 16 # float32 + assert hdr['bitpix'] == 32 def _set_something_into_hdr(self, hdr): # Called from test_bytes test method. Specific to the header data type @@ -117,26 +112,24 @@ def test_checks(self): # Test header checks hdr_t = self.header_class() # _dxer just returns the diagnostics as a string - assert_equal(self._dxer(hdr_t), '') + assert self._dxer(hdr_t) == '' hdr = hdr_t.copy() hdr['sizeof_hdr'] = 1 with suppress_warnings(): - assert_equal(self._dxer(hdr), 'sizeof_hdr should be ' + - str(self.sizeof_hdr)) + assert self._dxer(hdr) == 'sizeof_hdr should be ' + str(self.sizeof_hdr) hdr = hdr_t.copy() hdr['datatype'] = 0 - assert_equal(self._dxer(hdr), 'data code 0 not supported\n' - 'bitpix does not match datatype') + assert self._dxer(hdr) == 'data code 0 not supported\nbitpix does not match datatype' hdr = hdr_t.copy() hdr['bitpix'] = 0 - assert_equal(self._dxer(hdr), 'bitpix does not match datatype') + assert self._dxer(hdr) == 'bitpix does not match datatype' def test_pixdim_checks(self): hdr_t = self.header_class() for i in (1, 2, 3): hdr = hdr_t.copy() hdr['pixdim'][i] = -1 - assert_equal(self._dxer(hdr), 'pixdim[1,2,3] should be positive') + assert self._dxer(hdr) == 'pixdim[1,2,3] should be positive' def test_log_checks(self): # Test logging, fixing, errors for header checking @@ -146,11 +139,10 @@ def test_log_checks(self): with suppress_warnings(): hdr['sizeof_hdr'] = 350 # severity 30 fhdr, message, raiser = self.log_chk(hdr, 30) - assert_equal(fhdr['sizeof_hdr'], self.sizeof_hdr) - assert_equal(message, - 'sizeof_hdr should be {0}; set sizeof_hdr to {0}'.format( - self.sizeof_hdr)) - assert_raises(*raiser) + + assert fhdr['sizeof_hdr'] == self.sizeof_hdr + assert message == 'sizeof_hdr should be {0}; set sizeof_hdr to {0}'.format(self.sizeof_hdr) + pytest.raises(*raiser) # RGB datatype does not raise error hdr = HC() hdr.set_data_dtype('RGB') @@ -160,25 +152,22 @@ def test_log_checks(self): hdr['datatype'] = -1 # severity 40 with suppress_warnings(): fhdr, message, raiser = self.log_chk(hdr, 40) - assert_equal(message, 'data code -1 not recognized; ' - 'not attempting fix') + assert message == 'data code -1 not recognized; not attempting fix' - assert_raises(*raiser) + pytest.raises(*raiser) # datatype not supported hdr['datatype'] = 255 # severity 40 fhdr, message, raiser = self.log_chk(hdr, 40) - assert_equal(message, 'data code 255 not supported; ' - 'not attempting fix') - assert_raises(*raiser) + assert message == 'data code 255 not supported; not attempting fix' + pytest.raises(*raiser) # bitpix hdr = HC() hdr['datatype'] = 16 # float32 hdr['bitpix'] = 16 # severity 10 fhdr, message, raiser = self.log_chk(hdr, 10) - assert_equal(fhdr['bitpix'], 32) - assert_equal(message, 'bitpix does not match datatype; ' - 'setting bitpix to match datatype') - assert_raises(*raiser) + assert fhdr['bitpix'] == 32 + assert message == 'bitpix does not match datatype; setting bitpix to match datatype' + pytest.raises(*raiser) def test_pixdim_log_checks(self): # pixdim positive @@ -186,28 +175,25 @@ def test_pixdim_log_checks(self): hdr = HC() hdr['pixdim'][1] = -2 # severity 35 fhdr, message, raiser = self.log_chk(hdr, 35) - assert_equal(fhdr['pixdim'][1], 2) - assert_equal(message, 'pixdim[1,2,3] should be positive; ' - 'setting to abs of pixdim values') - assert_raises(*raiser) + assert fhdr['pixdim'][1] == 2 + assert message == 'pixdim[1,2,3] should be positive; setting to abs of pixdim values' + pytest.raises(*raiser) hdr = HC() hdr['pixdim'][1] = 0 # severity 30 fhdr, message, raiser = self.log_chk(hdr, 30) - assert_equal(fhdr['pixdim'][1], 1) - assert_equal(message, PIXDIM0_MSG) - assert_raises(*raiser) + assert fhdr['pixdim'][1] == 1 + assert message == PIXDIM0_MSG + pytest.raises(*raiser) # both hdr = HC() hdr['pixdim'][1] = 0 # severity 30 hdr['pixdim'][2] = -2 # severity 35 fhdr, message, raiser = self.log_chk(hdr, 35) - assert_equal(fhdr['pixdim'][1], 1) - assert_equal(fhdr['pixdim'][2], 2) - assert_equal(message, 'pixdim[1,2,3] should be ' - 'non-zero and pixdim[1,2,3] should ' - 'be positive; setting 0 dims to 1 ' - 'and setting to abs of pixdim values') - assert_raises(*raiser) + assert fhdr['pixdim'][1] == 1 + assert fhdr['pixdim'][2] == 2 + assert message == ('pixdim[1,2,3] should be non-zero and pixdim[1,2,3] should be ' + 'positive; setting 0 dims to 1 and setting to abs of pixdim values') + pytest.raises(*raiser) def test_no_scaling_fixes(self): # Check we do not fix slope or intercept @@ -248,12 +234,12 @@ def test_logger_error(self): # Check log message appears in new logger imageglobals.logger = logger hdr.copy().check_fix() - assert_equal(str_io.getvalue(), - 'bitpix does not match datatype; ' - 'setting bitpix to match datatype\n') + assert str_io.getvalue() == ('bitpix does not match datatype; ' + 'setting bitpix to match datatype\n') # Check that error_level in fact causes error to be raised imageglobals.error_level = 10 - assert_raises(HeaderDataError, hdr.copy().check_fix) + with pytest.raises(HeaderDataError): + hdr.copy().check_fix() finally: imageglobals.logger, imageglobals.error_level = log_cache @@ -304,55 +290,58 @@ def assert_set_dtype(dt_spec, np_dtype): assert_set_dtype(int, np_sys_int) hdr = self.header_class() for inp in all_unsupported_types: - assert_raises(HeaderDataError, hdr.set_data_dtype, inp) + with pytest.raises(HeaderDataError): + hdr.set_data_dtype(inp) def test_shapes(self): # Test that shape checks work hdr = self.header_class() for shape in ((2, 3, 4), (2, 3, 4, 5), (2, 3), (2,)): hdr.set_data_shape(shape) - assert_equal(hdr.get_data_shape(), shape) + assert hdr.get_data_shape() == shape # Check max works, but max+1 raises error dim_dtype = hdr.structarr['dim'].dtype # as_int for safety to deal with numpy 1.4.1 int conversion errors mx = as_int(np.iinfo(dim_dtype).max) shape = (mx,) hdr.set_data_shape(shape) - assert_equal(hdr.get_data_shape(), shape) + assert hdr.get_data_shape() == shape shape = (mx + 1,) - assert_raises(HeaderDataError, hdr.set_data_shape, shape) + with pytest.raises(HeaderDataError): + hdr.set_data_shape(shape) # Lists or tuples or arrays will work for setting shape shape = (2, 3, 4) for constructor in (list, tuple, np.array): hdr.set_data_shape(constructor(shape)) - assert_equal(hdr.get_data_shape(), shape) + assert hdr.get_data_shape() == shape def test_read_write_data(self): # Check reading and writing of data hdr = self.header_class() # Trying to read data from an empty header gives no data bytes = hdr.data_from_fileobj(BytesIO()) - assert_equal(len(bytes), 0) + assert len(bytes) == 0 # Setting no data into an empty header results in - no data str_io = BytesIO() hdr.data_to_fileobj([], str_io) - assert_equal(str_io.getvalue(), b'') + assert str_io.getvalue() == b'' # Setting more data then there should be gives an error - assert_raises(HeaderDataError, - hdr.data_to_fileobj, - np.zeros(3), - str_io) + with pytest.raises(HeaderDataError): + hdr.data_to_fileobj(np.zeros(3), str_io) # Test valid write hdr.set_data_shape((1, 2, 3)) hdr.set_data_dtype(np.float32) S = BytesIO() data = np.arange(6, dtype=np.float64) # data have to be the right shape - assert_raises(HeaderDataError, hdr.data_to_fileobj, data, S) + with pytest.raises(HeaderDataError): + hdr.data_to_fileobj(data, S) data = data.reshape((1, 2, 3)) # and size - assert_raises(HeaderDataError, hdr.data_to_fileobj, data[:, :, :-1], S) - assert_raises(HeaderDataError, hdr.data_to_fileobj, data[:, :-1, :], S) + with pytest.raises(HeaderDataError): + hdr.data_to_fileobj(data[:, :, :-1], S) + with pytest.raises(HeaderDataError): + hdr.data_to_fileobj(data[:, :-1, :], S) # OK if so hdr.data_to_fileobj(data, S) # Read it back @@ -360,7 +349,7 @@ def test_read_write_data(self): # Should be about the same assert_array_almost_equal(data, data_back) # but with the header dtype, not the data dtype - assert_equal(hdr.get_data_dtype(), data_back.dtype) + assert hdr.get_data_dtype() == data_back.dtype # this is with native endian, not so for swapped S2 = BytesIO() hdr2 = hdr.as_byteswapped() @@ -371,9 +360,9 @@ def test_read_write_data(self): # Compares the same assert_array_almost_equal(data_back, data_back2) # Same dtype names - assert_equal(data_back.dtype.name, data_back2.dtype.name) + assert data_back.dtype.name == data_back2.dtype.name # But not the same endianness - assert_not_equal(data.dtype.byteorder, data_back2.dtype.byteorder) + assert data.dtype.byteorder != data_back2.dtype.byteorder # Try scaling down to integer hdr.set_data_dtype(np.uint8) S3 = BytesIO() @@ -385,15 +374,16 @@ def test_read_write_data(self): assert_array_almost_equal(data, data_back) # If the header can't do scaling, rescale raises an error if not hdr.has_data_slope: - assert_raises(HeaderTypeError, hdr.data_to_fileobj, data, S3) - assert_raises(HeaderTypeError, hdr.data_to_fileobj, data, S3, - rescale=True) + with pytest.raises(HeaderTypeError): + hdr.data_to_fileobj(data, S3) + with pytest.raises(HeaderTypeError): + hdr.data_to_fileobj(data, S3, rescale=True) # If not scaling we lose precision from rounding data = np.arange(6, dtype=np.float64).reshape((1, 2, 3)) + 0.5 with np.errstate(invalid='ignore'): hdr.data_to_fileobj(data, S3, rescale=False) data_back = hdr.data_from_fileobj(S3) - assert_false(np.allclose(data, data_back)) + assert not np.allclose(data, data_back) # Test RGB image dtype = np.dtype([('R', 'uint8'), ('G', 'uint8'), ('B', 'uint8')]) data = np.ones((1, 2, 3), dtype) @@ -409,26 +399,24 @@ def test_datatype(self): for code in codes.value_set(): npt = codes.type[code] if npt is np.void: - assert_raises( - HeaderDataError, - ehdr.set_data_dtype, - code) + with pytest.raises(HeaderDataError): + ehdr.set_data_dtype(code) continue dt = codes.dtype[code] ehdr.set_data_dtype(npt) - assert_true(ehdr['datatype'] == code) - assert_true(ehdr['bitpix'] == dt.itemsize * 8) + assert ehdr['datatype'] == code + assert ehdr['bitpix'] == dt.itemsize * 8 ehdr.set_data_dtype(code) - assert_true(ehdr['datatype'] == code) + assert ehdr['datatype'] == code ehdr.set_data_dtype(dt) - assert_true(ehdr['datatype'] == code) + assert ehdr['datatype'] == code def test_offset(self): # Test get / set offset hdr = self.header_class() offset = hdr.get_data_offset() hdr.set_data_offset(offset + 16) - assert_equal(hdr.get_data_offset(), offset + 16) + assert hdr.get_data_offset() == offset + 16 def test_data_shape_zooms_affine(self): hdr = self.header_class() @@ -436,27 +424,23 @@ def test_data_shape_zooms_affine(self): L = len(shape) hdr.set_data_shape(shape) if L: - assert_equal(hdr.get_data_shape(), shape) + assert hdr.get_data_shape() == shape else: - assert_equal(hdr.get_data_shape(), (0,)) + assert hdr.get_data_shape() == (0,) # Default zoom - for 3D - is 1(()) - assert_equal(hdr.get_zooms(), (1,) * L) + assert hdr.get_zooms() == (1,) * L # errors if zooms do not match shape if len(shape): - assert_raises(HeaderDataError, - hdr.set_zooms, - (1,) * (L - 1)) + with pytest.raises(HeaderDataError): + hdr.set_zooms((1,) * (L - 1)) # Errors for negative zooms - assert_raises(HeaderDataError, - hdr.set_zooms, - (-1,) + (1,) * (L - 1)) - assert_raises(HeaderDataError, - hdr.set_zooms, - (1,) * (L + 1)) + with pytest.raises(HeaderDataError): + hdr.set_zooms((-1,) + (1,) * (L - 1)) + with pytest.raises(HeaderDataError): + hdr.set_zooms((1,) * (L + 1)) # Errors for negative zooms - assert_raises(HeaderDataError, - hdr.set_zooms, - (-1,) * L) + with pytest.raises(HeaderDataError): + hdr.set_zooms((-1,) * L) # reducing the dimensionality of the array and then increasing # it again reverts the previously set zoom values to 1.0 hdr = self.header_class() @@ -489,20 +473,20 @@ def test_default_x_flip(self): def test_from_eg_file(self): fileobj = open(self.example_file, 'rb') hdr = self.header_class.from_fileobj(fileobj, check=False) - assert_equal(hdr.endianness, '>') - assert_equal(hdr['sizeof_hdr'], self.sizeof_hdr) + assert hdr.endianness == '>' + assert hdr['sizeof_hdr'] == self.sizeof_hdr def test_orientation(self): # Test flips hdr = self.header_class() - assert_true(hdr.default_x_flip) + assert hdr.default_x_flip hdr.set_data_shape((3, 5, 7)) hdr.set_zooms((4, 5, 6)) aff = np.diag((-4, 5, 6, 1)) aff[:3, 3] = np.array([1, 2, 3]) * np.array([-4, 5, 6]) * -1 assert_array_equal(hdr.get_base_affine(), aff) hdr.default_x_flip = False - assert_false(hdr.default_x_flip) + assert not hdr.default_x_flip aff[0] *= -1 assert_array_equal(hdr.get_base_affine(), aff) @@ -512,23 +496,23 @@ def test_str(self): s1 = str(hdr) # check the datacode recoding rexp = re.compile('^datatype +: float32', re.MULTILINE) - assert_true(rexp.search(s1) is not None) + assert rexp.search(s1) is not None def test_from_header(self): # check from header class method. klass = self.header_class empty = klass.from_header() - assert_equal(klass(), empty) + assert klass() == empty empty = klass.from_header(None) - assert_equal(klass(), empty) + assert klass() == empty hdr = klass() hdr.set_data_dtype(np.float64) hdr.set_data_shape((1, 2, 3)) hdr.set_zooms((3.0, 2.0, 1.0)) for check in (True, False): copy = klass.from_header(hdr, check=check) - assert_equal(hdr, copy) - assert_false(hdr is copy) + assert hdr == copy + assert hdr is not copy class C(object): @@ -538,17 +522,17 @@ def get_data_shape(self): return (5, 4, 3) def get_zooms(self): return (10.0, 9.0, 8.0) converted = klass.from_header(C()) - assert_true(isinstance(converted, klass)) - assert_equal(converted.get_data_dtype(), np.dtype('i2')) - assert_equal(converted.get_data_shape(), (5, 4, 3)) - assert_equal(converted.get_zooms(), (10.0, 9.0, 8.0)) + assert isinstance(converted, klass) + assert converted.get_data_dtype() == np.dtype('i2') + assert converted.get_data_shape() == (5, 4, 3) + assert converted.get_zooms() == (10.0, 9.0, 8.0) def test_base_affine(self): klass = self.header_class hdr = klass() hdr.set_data_shape((3, 5, 7)) hdr.set_zooms((3, 2, 1)) - assert_true(hdr.default_x_flip) + assert hdr.default_x_flip assert_array_almost_equal( hdr.get_base_affine(), [[-3., 0., 0., 3.], @@ -574,7 +558,7 @@ def test_scaling(self): # Test integer scaling from float # Analyze headers cannot do float-integer scaling hdr = self.header_class() - assert_true(hdr.default_x_flip) + assert hdr.default_x_flip shape = (1, 2, 3) hdr.set_data_shape(shape) hdr.set_data_dtype(np.float32) @@ -588,22 +572,23 @@ def test_scaling(self): hdr.set_data_dtype(np.int32) # Writing to int needs scaling, and raises an error if we can't scale if not hdr.has_data_slope: - assert_raises(HeaderTypeError, hdr.data_to_fileobj, data, BytesIO()) + with pytest.raises(HeaderTypeError): + hdr.data_to_fileobj(data, BytesIO()) # But if we aren't scaling, convert the floats to integers and write with np.errstate(invalid='ignore'): hdr.data_to_fileobj(data, S, rescale=False) rdata = hdr.data_from_fileobj(S) - assert_true(np.allclose(data, rdata)) + assert np.allclose(data, rdata) # This won't work for floats that aren't close to integers data_p5 = data + 0.5 with np.errstate(invalid='ignore'): hdr.data_to_fileobj(data_p5, S, rescale=False) rdata = hdr.data_from_fileobj(S) - assert_false(np.allclose(data_p5, rdata)) + assert not np.allclose(data_p5, rdata) def test_slope_inter(self): hdr = self.header_class() - assert_equal(hdr.get_slope_inter(), (None, None)) + assert hdr.get_slope_inter() == (None, None) for slinter in ((None,), (None, None), (np.nan, np.nan), @@ -614,9 +599,11 @@ def test_slope_inter(self): (None, 0), (1.0, 0)): hdr.set_slope_inter(*slinter) - assert_equal(hdr.get_slope_inter(), (None, None)) - assert_raises(HeaderTypeError, hdr.set_slope_inter, 1.1) - assert_raises(HeaderTypeError, hdr.set_slope_inter, 1.0, 0.1) + assert hdr.get_slope_inter() == (None, None) + with pytest.raises(HeaderTypeError): + hdr.set_slope_inter(1.1) + with pytest.raises(HeaderTypeError): + hdr.set_slope_inter(1.0, 0.1) def test_from_analyze_map(self): # Test that any header can pass values from a mapping @@ -625,19 +612,22 @@ def test_from_analyze_map(self): class H1(object): pass - assert_raises(AttributeError, klass.from_header, H1()) + with pytest.raises(AttributeError): + klass.from_header(H1()) class H2(object): def get_data_dtype(self): return np.dtype('u1') - assert_raises(AttributeError, klass.from_header, H2()) + with pytest.raises(AttributeError): + klass.from_header(H2()) class H3(H2): def get_data_shape(self): return (2, 3, 4) - assert_raises(AttributeError, klass.from_header, H3()) + with pytest.raises(AttributeError): + klass.from_header(H3()) class H4(H3): @@ -647,7 +637,7 @@ def get_zooms(self): exp_hdr.set_data_dtype(np.dtype('u1')) exp_hdr.set_data_shape((2, 3, 4)) exp_hdr.set_zooms((4, 5, 6)) - assert_equal(klass.from_header(H4()), exp_hdr) + assert klass.from_header(H4()) == exp_hdr # cal_max, cal_min get properly set from ``as_analyze_map`` class H5(H4): @@ -656,7 +646,7 @@ def as_analyze_map(self): return dict(cal_min=-100, cal_max=100) exp_hdr['cal_min'] = -100 exp_hdr['cal_max'] = 100 - assert_equal(klass.from_header(H5()), exp_hdr) + assert klass.from_header(H5()) == exp_hdr # set_* methods override fields fron header class H6(H5): @@ -664,7 +654,7 @@ class H6(H5): def as_analyze_map(self): return dict(datatype=4, bitpix=32, cal_min=-100, cal_max=100) - assert_equal(klass.from_header(H6()), exp_hdr) + assert klass.from_header(H6()) == exp_hdr # Any mapping will do, including a Nifti header class H7(H5): @@ -677,7 +667,7 @@ def as_analyze_map(self): return n_hdr # Values from methods still override values from header (shape, dtype, # zooms still at defaults from n_hdr header fields above) - assert_equal(klass.from_header(H7()), exp_hdr) + assert klass.from_header(H7()) == exp_hdr def test_best_affine(): @@ -691,7 +681,8 @@ def test_data_code_error(): # test analyze raising error for unsupported codes hdr = Nifti1Header() hdr['datatype'] = 256 - assert_raises(HeaderDataError, AnalyzeHeader.from_header, hdr) + with pytest.raises(HeaderDataError): + AnalyzeHeader.from_header(hdr) class TestAnalyzeImage(tsi.TestSpatialImage, tsi.MmapImageMixin): @@ -701,8 +692,7 @@ class TestAnalyzeImage(tsi.TestSpatialImage, tsi.MmapImageMixin): def test_supported_types(self): img = self.image_class(np.zeros((2, 3, 4)), np.eye(4)) - assert_equal(self.supported_np_types, - supported_np_types(img)) + assert self.supported_np_types == supported_np_types(img) def test_default_header(self): # Check default header is as expected @@ -713,7 +703,7 @@ def test_default_header(self): hdr.set_data_dtype(arr.dtype) hdr.set_data_offset(0) hdr.set_slope_inter(np.nan, np.nan) - assert_equal(img.header, hdr) + assert img.header == hdr def test_data_hdr_cache(self): # test the API for loaded images, such that the data returned @@ -732,21 +722,21 @@ def test_data_hdr_cache(self): img = IC(data, affine, hdr) img.to_file_map(fm) img2 = IC.from_file_map(fm) - assert_equal(img2.shape, shape) - assert_equal(img2.get_data_dtype().type, np.int16) + assert img2.shape == shape + assert img2.get_data_dtype().type == np.int16 hdr = img2.header hdr.set_data_shape((3, 2, 2)) - assert_equal(hdr.get_data_shape(), (3, 2, 2)) + assert hdr.get_data_shape() == (3, 2, 2) hdr.set_data_dtype(np.uint8) - assert_equal(hdr.get_data_dtype(), np.dtype(np.uint8)) + assert hdr.get_data_dtype() == np.dtype(np.uint8) assert_array_equal(img2.get_fdata(), data) assert_array_equal(np.asanyarray(img2.dataobj), data) # now check read_img_data function - here we do see the changed # header sc_data = read_img_data(img2) - assert_equal(sc_data.shape, (3, 2, 2)) + assert sc_data.shape == (3, 2, 2) us_data = read_img_data(img2, prefer='unscaled') - assert_equal(us_data.shape, (3, 2, 2)) + assert us_data.shape == (3, 2, 2) def test_affine_44(self): IC = self.image_class @@ -760,7 +750,8 @@ def test_affine_44(self): img = IC(data, affine.tolist()) assert_array_equal(affine, img.affine) # Not OK - affine wrong shape - assert_raises(ValueError, IC, data, np.diag([2, 3, 4])) + with pytest.raises(ValueError): + IC(data, np.diag([2, 3, 4])) def test_offset_to_zero(self): # Check offset is always set to zero when creating images @@ -768,24 +759,24 @@ def test_offset_to_zero(self): arr = np.arange(24, dtype=np.int16).reshape((2, 3, 4)) aff = np.eye(4) img = img_klass(arr, aff) - assert_equal(img.header.get_data_offset(), 0) + assert img.header.get_data_offset() == 0 # Save to BytesIO object(s), make sure offset still zero bytes_map = bytesio_filemap(img_klass) img.to_file_map(bytes_map) - assert_equal(img.header.get_data_offset(), 0) + assert img.header.get_data_offset() == 0 # Set offset in in-memory image big_off = 1024 img.header.set_data_offset(big_off) - assert_equal(img.header.get_data_offset(), big_off) + assert img.header.get_data_offset() == big_off # Offset is in proxy but not in image after saving to fileobj img_rt = bytesio_round_trip(img) - assert_equal(img_rt.dataobj.offset, big_off) - assert_equal(img_rt.header.get_data_offset(), 0) + assert img_rt.dataobj.offset == big_off + assert img_rt.header.get_data_offset() == 0 # The original header still has the big_off value img.header.set_data_offset(big_off) # Making a new image with this header resets to zero img_again = img_klass(arr, aff, img.header) - assert_equal(img_again.header.get_data_offset(), 0) + assert img_again.header.get_data_offset() == 0 def test_big_offset_exts(self): # Check writing offset beyond data works for different file extensions @@ -845,7 +836,7 @@ def test_pickle(self): img_str = pickle.dumps(img) img2 = pickle.loads(img_str) assert_array_equal(img.get_fdata(), img2.get_fdata()) - assert_equal(img.header, img2.header) + assert img.header == img2.header # Save / reload using bytes IO objects for key, value in img.file_map.items(): value.fileobj = BytesIO() @@ -864,10 +855,11 @@ def test_no_finite_values(self): data[:, 2] = -np.inf img = self.image_class(data, None) img.set_data_dtype(np.int16) - assert_equal(img.get_data_dtype(), np.dtype(np.int16)) + assert img.get_data_dtype() == np.dtype(np.int16) fm = bytesio_filemap(img) if not img.header.has_data_slope: - assert_raises(WriterError, img.to_file_map, fm) + with pytest.raises(WriterError): + img.to_file_map(fm) return img.to_file_map(fm) img_back = self.image_class.from_file_map(fm) @@ -879,4 +871,5 @@ def test_unsupported(): data = np.arange(24, dtype=np.int32).reshape((2, 3, 4)) affine = np.eye(4) data = np.arange(24, dtype=np.uint32).reshape((2, 3, 4)) - assert_raises(HeaderDataError, AnalyzeImage, data, affine) + with pytest.raises(HeaderDataError): + AnalyzeImage(data, affine) diff --git a/nibabel/tests/test_api_validators.py b/nibabel/tests/test_api_validators.py index 41d3f41110..a4d23aaefd 100644 --- a/nibabel/tests/test_api_validators.py +++ b/nibabel/tests/test_api_validators.py @@ -1,7 +1,6 @@ """ Metaclass and class for validating instance APIs """ -from nose.tools import assert_equal class validator2test(type): @@ -79,8 +78,8 @@ def validate_something(self, obj, params): The metaclass sets up a ``test_something`` function that runs these checks on each ( """ - assert_equal(obj.var, params['var']) - assert_equal(obj.get_var(), params['var']) + assert obj.var == params['var'] + assert obj.get_var() == params['var'] class TestRunAllTests(ValidateAPI): @@ -102,4 +101,4 @@ def validate_second(self, obj, param): def teardown(): # Check that both validate_xxx tests got run - assert_equal(TestRunAllTests.run_tests, ['first', 'second']) + assert TestRunAllTests.run_tests == ['first', 'second'] diff --git a/nibabel/tests/test_arrayproxy.py b/nibabel/tests/test_arrayproxy.py index 527f9b8f91..2a509acb88 100644 --- a/nibabel/tests/test_arrayproxy.py +++ b/nibabel/tests/test_arrayproxy.py @@ -26,9 +26,8 @@ from unittest import mock from numpy.testing import assert_array_equal, assert_array_almost_equal -from nose.tools import (assert_true, assert_false, assert_equal, - assert_not_equal, assert_raises) -from nibabel.testing import memmap_after_ufunc +import pytest +from ..testing import memmap_after_ufunc from .test_fileslice import slicer_samples from .test_openers import patch_indexed_gzip @@ -70,15 +69,16 @@ def test_init(): bio.write(arr.tostring(order='F')) hdr = FunkyHeader(shape) ap = ArrayProxy(bio, hdr) - assert_true(ap.file_like is bio) - assert_equal(ap.shape, shape) + assert ap.file_like is bio + assert ap.shape == shape # shape should be read only - assert_raises(AttributeError, setattr, ap, 'shape', shape) + with pytest.raises(AttributeError): + ap.shape = shape # Get the data assert_array_equal(np.asarray(ap), arr) # Check we can modify the original header without changing the ap version hdr.shape[0] = 6 - assert_not_equal(ap.shape, shape) + assert ap.shape != shape # Data stays the same, also assert_array_equal(np.asarray(ap), arr) # C order also possible @@ -88,7 +88,8 @@ def test_init(): ap = CArrayProxy(bio, FunkyHeader((2, 3, 4))) assert_array_equal(np.asarray(ap), arr) # Illegal init - assert_raises(TypeError, ArrayProxy, bio, object()) + with pytest.raises(TypeError): + ArrayProxy(bio, object()) def test_tuplespec(): @@ -106,7 +107,7 @@ def test_tuplespec(): ap_tuple = ArrayProxy(bio, tuple_spec) # Header and tuple specs produce identical behavior for prop in ('shape', 'dtype', 'offset', 'slope', 'inter', 'is_proxy'): - assert_equal(getattr(ap_header, prop), getattr(ap_tuple, prop)) + assert getattr(ap_header, prop) == getattr(ap_tuple, prop) for method, args in (('get_unscaled', ()), ('__array__', ()), ('__getitem__', ((0, 2, 1), )) ): @@ -116,9 +117,12 @@ def test_tuplespec(): for n in range(2, 5): ArrayProxy(bio, tuple_spec[:n]) # Bad tuple lengths - assert_raises(TypeError, ArrayProxy, bio, ()) - assert_raises(TypeError, ArrayProxy, bio, tuple_spec[:1]) - assert_raises(TypeError, ArrayProxy, bio, tuple_spec + ('error',)) + with pytest.raises(TypeError): + ArrayProxy(bio, ()) + with pytest.raises(TypeError): + ArrayProxy(bio, tuple_spec[:1]) + with pytest.raises(TypeError): + ArrayProxy(bio, tuple_spec + ('error',)) def write_raw_data(arr, hdr, fileobj): @@ -136,8 +140,8 @@ def test_nifti1_init(): write_raw_data(arr, hdr, bio) hdr.set_slope_inter(2, 10) ap = ArrayProxy(bio, hdr) - assert_true(ap.file_like == bio) - assert_equal(ap.shape, shape) + assert ap.file_like == bio + assert ap.shape == shape # Get the data assert_array_equal(np.asarray(ap), arr * 2.0 + 10) with InTemporaryDirectory(): @@ -145,8 +149,8 @@ def test_nifti1_init(): write_raw_data(arr, hdr, f) f.close() ap = ArrayProxy('test.nii', hdr) - assert_true(ap.file_like == 'test.nii') - assert_equal(ap.shape, shape) + assert ap.file_like == 'test.nii' + assert ap.shape == shape assert_array_equal(np.asarray(ap), arr * 2.0 + 10) @@ -182,14 +186,14 @@ def test_is_proxy(): hdr = FunkyHeader((2, 3, 4)) bio = BytesIO() prox = ArrayProxy(bio, hdr) - assert_true(is_proxy(prox)) - assert_false(is_proxy(bio)) - assert_false(is_proxy(hdr)) - assert_false(is_proxy(np.zeros((2, 3, 4)))) + assert is_proxy(prox) + assert not is_proxy(bio) + assert not is_proxy(hdr) + assert not is_proxy(np.zeros((2, 3, 4))) class NP(object): is_proxy = False - assert_false(is_proxy(NP())) + assert not is_proxy(NP()) def test_reshape_dataobj(): @@ -203,11 +207,11 @@ def test_reshape_dataobj(): assert_array_equal(prox, arr) assert_array_equal(reshape_dataobj(prox, (2, 3, 4)), np.reshape(arr, (2, 3, 4))) - assert_equal(prox.shape, shape) - assert_equal(arr.shape, shape) + assert prox.shape == shape + assert arr.shape == shape assert_array_equal(reshape_dataobj(arr, (2, 3, 4)), np.reshape(arr, (2, 3, 4))) - assert_equal(arr.shape, shape) + assert arr.shape == shape class ArrGiver(object): @@ -216,7 +220,7 @@ def __array__(self): assert_array_equal(reshape_dataobj(ArrGiver(), (2, 3, 4)), np.reshape(arr, (2, 3, 4))) - assert_equal(arr.shape, shape) + assert arr.shape == shape def test_reshaped_is_proxy(): @@ -224,13 +228,16 @@ def test_reshaped_is_proxy(): hdr = FunkyHeader(shape) bio = BytesIO() prox = ArrayProxy(bio, hdr) - assert_true(isinstance(prox.reshape((2, 3, 4)), ArrayProxy)) + assert isinstance(prox.reshape((2, 3, 4)), ArrayProxy) minus1 = prox.reshape((2, -1, 4)) - assert_true(isinstance(minus1, ArrayProxy)) - assert_equal(minus1.shape, (2, 3, 4)) - assert_raises(ValueError, prox.reshape, (-1, -1, 4)) - assert_raises(ValueError, prox.reshape, (2, 3, 5)) - assert_raises(ValueError, prox.reshape, (2, -1, 5)) + assert isinstance(minus1, ArrayProxy) + assert minus1.shape == (2, 3, 4) + with pytest.raises(ValueError): + prox.reshape((-1, -1, 4)) + with pytest.raises(ValueError): + prox.reshape((2, 3, 5)) + with pytest.raises(ValueError): + prox.reshape((2, -1, 5)) def test_get_unscaled(): @@ -313,21 +320,22 @@ def check_mmap(hdr, offset, proxy_class, unscaled_is_mmap = isinstance(unscaled, np.memmap) back_is_mmap = isinstance(back_data, np.memmap) if expected_mode is None: - assert_false(unscaled_is_mmap) - assert_false(back_is_mmap) + assert not unscaled_is_mmap + assert not back_is_mmap else: - assert_equal(unscaled_is_mmap, - viral_memmap or unscaled_really_mmap) - assert_equal(back_is_mmap, - viral_memmap or scaled_really_mmap) + assert unscaled_is_mmap == (viral_memmap or unscaled_really_mmap) + assert back_is_mmap == (viral_memmap or scaled_really_mmap) if scaled_really_mmap: - assert_equal(back_data.mode, expected_mode) + assert back_data.mode == expected_mode del prox, back_data # Check that mmap is keyword-only - assert_raises(TypeError, proxy_class, fname, hdr, True) + with pytest.raises(TypeError): + proxy_class(fname, hdr, True) # Check invalid values raise error - assert_raises(ValueError, proxy_class, fname, hdr, mmap='rw') - assert_raises(ValueError, proxy_class, fname, hdr, mmap='r+') + with pytest.raises(ValueError): + proxy_class(fname, hdr, mmap='rw') + with pytest.raises(ValueError): + proxy_class(fname, hdr, mmap='r+') # An image opener class which counts how many instances of itself have been @@ -462,11 +470,11 @@ def test_keep_file_open_true_false_invalid(): fobj.write(data.tostring(order='F')) for invalid_kfo in (55, 'auto', 'cauto'): - with assert_raises(ValueError): + with pytest.raises(ValueError): ArrayProxy(fname, ((10, 10, 10), dtype), keep_file_open=invalid_kfo) with patch_keep_file_open_default(invalid_kfo): - with assert_raises(ValueError): + with pytest.raises(ValueError): ArrayProxy(fname, ((10, 10, 10), dtype)) diff --git a/nibabel/tests/test_arraywriters.py b/nibabel/tests/test_arraywriters.py index d5547e875f..9268c3fe36 100644 --- a/nibabel/tests/test_arraywriters.py +++ b/nibabel/tests/test_arraywriters.py @@ -14,11 +14,8 @@ from ..casting import int_abs, type_info, shared_range, on_powerpc from ..volumeutils import array_from_file, apply_read_scaling, _dt_min_max -from numpy.testing import (assert_array_almost_equal, - assert_array_equal) -from nose.tools import (assert_true, assert_false, - assert_equal, assert_not_equal, - assert_raises) +from numpy.testing import assert_array_almost_equal, assert_array_equal +import pytest from ..testing import (assert_allclose_safely, suppress_warnings, error_warnings) @@ -56,8 +53,8 @@ def test_arraywriters(): for type in test_types: arr = np.arange(10, dtype=type) aw = klass(arr) - assert_true(aw.array is arr) - assert_equal(aw.out_dtype, arr.dtype) + assert aw.array is arr + assert aw.out_dtype == arr.dtype assert_array_equal(arr, round_trip(aw)) # Byteswapped should be OK bs_arr = arr.byteswap().newbyteorder('S') @@ -80,7 +77,7 @@ def test_arraywriters(): # C order works as well arr_back = round_trip(a2w, 'C') assert_array_equal(arr2, arr_back) - assert_true(arr_back.flags.c_contiguous) + assert arr_back.flags.c_contiguous def test_arraywriter_check_scaling(): @@ -89,14 +86,17 @@ def test_arraywriter_check_scaling(): arr = np.array([0, 1, 128, 255], np.uint8) aw = ArrayWriter(arr) # Out of range, scaling needed, default is error - assert_raises(WriterError, ArrayWriter, arr, np.int8) + with pytest.raises(WriterError): + ArrayWriter(arr, np.int8) # Make default explicit - assert_raises(WriterError, ArrayWriter, arr, np.int8, check_scaling=True) + with pytest.raises(WriterError): + ArrayWriter(arr, np.int8, check_scaling=True) # Turn off scaling check aw = ArrayWriter(arr, np.int8, check_scaling=False) assert_array_equal(round_trip(aw), np.clip(arr, 0, 127)) # Has to be keyword - assert_raises(TypeError, ArrayWriter, arr, np.int8, False) + with pytest.raises(TypeError): + ArrayWriter(arr, np.int8, False) def test_no_scaling(): @@ -154,39 +154,42 @@ def test_scaling_needed(): dt_def = [('f', 'i4')] arr = np.ones(10, dt_def) for t in NUMERIC_TYPES: - assert_raises(WriterError, ArrayWriter, arr, t) + with pytest.raises(WriterError): + ArrayWriter(arr, t) narr = np.ones(10, t) - assert_raises(WriterError, ArrayWriter, narr, dt_def) - assert_false(ArrayWriter(arr).scaling_needed()) - assert_false(ArrayWriter(arr, dt_def).scaling_needed()) + with pytest.raises(WriterError): + ArrayWriter(narr, dt_def) + assert not ArrayWriter(arr).scaling_needed() + assert not ArrayWriter(arr, dt_def).scaling_needed() # Any numeric type that can cast, needs no scaling for in_t in NUMERIC_TYPES: for out_t in NUMERIC_TYPES: if np.can_cast(in_t, out_t): aw = ArrayWriter(np.ones(10, in_t), out_t) - assert_false(aw.scaling_needed()) + assert not aw.scaling_needed() for in_t in NUMERIC_TYPES: # Numeric types to complex never need scaling arr = np.ones(10, in_t) for out_t in COMPLEX_TYPES: - assert_false(ArrayWriter(arr, out_t).scaling_needed()) + assert not ArrayWriter(arr, out_t).scaling_needed() # Attempts to scale from complex to anything else fails for in_t in COMPLEX_TYPES: for out_t in FLOAT_TYPES + IUINT_TYPES: arr = np.ones(10, in_t) - assert_raises(WriterError, ArrayWriter, arr, out_t) + with pytest.raises(WriterError): + ArrayWriter(arr, out_t) # Scaling from anything but complex to floats is OK for in_t in FLOAT_TYPES + IUINT_TYPES: arr = np.ones(10, in_t) for out_t in FLOAT_TYPES: - assert_false(ArrayWriter(arr, out_t).scaling_needed()) + assert not ArrayWriter(arr, out_t).scaling_needed() # For any other output type, arrays with no data don't need scaling for in_t in FLOAT_TYPES + IUINT_TYPES: arr_0 = np.zeros(10, in_t) arr_e = [] for out_t in IUINT_TYPES: - assert_false(ArrayWriter(arr_0, out_t).scaling_needed()) - assert_false(ArrayWriter(arr_e, out_t).scaling_needed()) + assert not ArrayWriter(arr_0, out_t).scaling_needed() + assert not ArrayWriter(arr_e, out_t).scaling_needed() # Going to (u)ints, non-finite arrays don't need scaling for writers that # can do scaling because these use finite_range to threshold the input data, # but ArrayWriter does not do this. so scaling_needed is True @@ -197,17 +200,16 @@ def test_scaling_needed(): arr_mix = np.array([np.nan, np.inf, -np.inf], dtype=in_t) for out_t in IUINT_TYPES: for arr in (arr_nan, arr_inf, arr_minf, arr_mix): - assert_true( - ArrayWriter(arr, out_t, check_scaling=False).scaling_needed()) - assert_false(SlopeArrayWriter(arr, out_t).scaling_needed()) - assert_false(SlopeInterArrayWriter(arr, out_t).scaling_needed()) + assert ArrayWriter(arr, out_t, check_scaling=False).scaling_needed() + assert not SlopeArrayWriter(arr, out_t).scaling_needed() + assert not SlopeInterArrayWriter(arr, out_t).scaling_needed() # Floats as input always need scaling for in_t in FLOAT_TYPES: arr = np.ones(10, in_t) for out_t in IUINT_TYPES: # We need an arraywriter that will tolerate construction when # scaling is needed - assert_true(SlopeArrayWriter(arr, out_t).scaling_needed()) + assert SlopeArrayWriter(arr, out_t).scaling_needed() # in-range (u)ints don't need scaling for in_t in IUINT_TYPES: in_info = np.iinfo(in_t) @@ -217,18 +219,18 @@ def test_scaling_needed(): out_min, out_max = out_info.min, out_info.max if in_min >= out_min and in_max <= out_max: arr = np.array([in_min, in_max], in_t) - assert_true(np.can_cast(arr.dtype, out_t)) + assert np.can_cast(arr.dtype, out_t) # We've already tested this with can_cast above, but... - assert_false(ArrayWriter(arr, out_t).scaling_needed()) + assert not ArrayWriter(arr, out_t).scaling_needed() continue # The output data type does not include the input data range max_min = max(in_min, out_min) # 0 for input or output uint min_max = min(in_max, out_max) arr = np.array([max_min, min_max], in_t) - assert_false(ArrayWriter(arr, out_t).scaling_needed()) - assert_true(SlopeInterArrayWriter(arr + 1, out_t).scaling_needed()) + assert not ArrayWriter(arr, out_t).scaling_needed() + assert SlopeInterArrayWriter(arr + 1, out_t).scaling_needed() if in_t in INT_TYPES: - assert_true(SlopeInterArrayWriter(arr - 1, out_t).scaling_needed()) + assert SlopeInterArrayWriter(arr - 1, out_t).scaling_needed() def test_special_rt(): @@ -239,14 +241,15 @@ def test_special_rt(): for in_dtt in FLOAT_TYPES: for out_dtt in IUINT_TYPES: in_arr = arr.astype(in_dtt) - assert_raises(WriterError, ArrayWriter, in_arr, out_dtt) + with pytest.raises(WriterError): + ArrayWriter(in_arr, out_dtt) aw = ArrayWriter(in_arr, out_dtt, check_scaling=False) mn, mx = shared_range(float, out_dtt) - assert_true(np.allclose(round_trip(aw).astype(float), - [mx, 0, mn])) + assert np.allclose(round_trip(aw).astype(float), + [mx, 0, mn]) for klass in (SlopeArrayWriter, SlopeInterArrayWriter): aw = klass(in_arr, out_dtt) - assert_equal(get_slope_inter(aw), (1, 0)) + assert get_slope_inter(aw) == (1, 0) assert_array_equal(round_trip(aw), 0) for in_dtt, out_dtt, awt in itertools.product( FLOAT_TYPES, @@ -254,7 +257,7 @@ def test_special_rt(): (ArrayWriter, SlopeArrayWriter, SlopeInterArrayWriter)): arr = np.zeros((3,), dtype=in_dtt) aw = awt(arr, out_dtt) - assert_equal(get_slope_inter(aw), (1, 0)) + assert get_slope_inter(aw) == (1, 0) assert_array_equal(round_trip(aw), 0) @@ -265,7 +268,7 @@ def test_high_int2uint(): arr = np.array([2**63], dtype=np.uint64) out_type = np.int64 aw = SlopeInterArrayWriter(arr, out_type) - assert_equal(aw.inter, 2**63) + assert aw.inter == 2**63 def test_slope_inter_castable(): @@ -282,7 +285,8 @@ def test_slope_inter_castable(): for in_dtt in FLOAT_TYPES: for out_dtt in IUINT_TYPES: in_arr = arr.astype(in_dtt) - assert_raises(WriterError, ArrayWriter, in_arr, out_dtt) + with pytest.raises(WriterError): + ArrayWriter(in_arr, out_dtt) aw = SlopeArrayWriter(arr.astype(in_dtt), out_dtt) # no error aw = SlopeInterArrayWriter(arr.astype(in_dtt), out_dtt) # no error for in_dtt, out_dtt, arr, slope_only, slope_inter, neither in ( @@ -313,17 +317,20 @@ def test_slope_inter_castable(): if slope_only: SlopeArrayWriter(data, out_dtt) else: - assert_raises(WriterError, SlopeArrayWriter, data, out_dtt) + with pytest.raises(WriterError): + SlopeArrayWriter(data, out_dtt) # With scaling and intercept if slope_inter: SlopeInterArrayWriter(data, out_dtt) else: - assert_raises(WriterError, SlopeInterArrayWriter, data, out_dtt) + with pytest.raises(WriterError): + SlopeInterArrayWriter(data, out_dtt) # With neither if neither: ArrayWriter(data, out_dtt) else: - assert_raises(WriterError, ArrayWriter, data, out_dtt) + with pytest.raises(WriterError): + ArrayWriter(data, out_dtt) def test_calculate_scale(): @@ -333,27 +340,28 @@ def test_calculate_scale(): SAW = SlopeArrayWriter # Offset handles scaling when it can aw = SIAW(npa([-2, -1], dtype=np.int8), np.uint8) - assert_equal(get_slope_inter(aw), (1.0, -2.0)) + assert get_slope_inter(aw) == (1.0, -2.0) # Sign flip handles these cases aw = SAW(npa([-2, -1], dtype=np.int8), np.uint8) - assert_equal(get_slope_inter(aw), (-1.0, 0.0)) + assert get_slope_inter(aw) == (-1.0, 0.0) aw = SAW(npa([-2, 0], dtype=np.int8), np.uint8) - assert_equal(get_slope_inter(aw), (-1.0, 0.0)) + assert get_slope_inter(aw) == (-1.0, 0.0) # But not when min magnitude is too large (scaling mechanism kicks in) aw = SAW(npa([-510, 0], dtype=np.int16), np.uint8) - assert_equal(get_slope_inter(aw), (-2.0, 0.0)) + assert get_slope_inter(aw) == (-2.0, 0.0) # Or for floats (attempts to expand across range) aw = SAW(npa([-2, 0], dtype=np.float32), np.uint8) - assert_not_equal(get_slope_inter(aw), (-1.0, 0.0)) + assert get_slope_inter(aw) != (-1.0, 0.0) # Case where offset handles scaling aw = SIAW(npa([-1, 1], dtype=np.int8), np.uint8) - assert_equal(get_slope_inter(aw), (1.0, -1.0)) + assert get_slope_inter(aw) == (1.0, -1.0) # Can't work for no offset case - assert_raises(WriterError, SAW, npa([-1, 1], dtype=np.int8), np.uint8) + with pytest.raises(WriterError): + SAW(npa([-1, 1], dtype=np.int8), np.uint8) # Offset trick can't work when max is out of range aw = SIAW(npa([-1, 255], dtype=np.int16), np.uint8) slope_inter = get_slope_inter(aw) - assert_not_equal(slope_inter, (1.0, -1.0)) + assert slope_inter != (1.0, -1.0) def test_resets(): @@ -391,11 +399,11 @@ def test_no_offset_scale(): (126, 127), (-127, 127)): aw = SAW(np.array(data, dtype=np.float32), np.int8) - assert_equal(aw.slope, 1.0) + assert aw.slope == 1.0 aw = SAW(np.array([-126, 127 * 2.0], dtype=np.float32), np.int8) - assert_equal(aw.slope, 2) + assert aw.slope == 2 aw = SAW(np.array([-128 * 2.0, 127], dtype=np.float32), np.int8) - assert_equal(aw.slope, 2) + assert aw.slope == 2 # Test that nasty abs behavior does not upset us n = -2**15 aw = SAW(np.array([n, n], dtype=np.int16), np.uint8) @@ -406,17 +414,17 @@ def test_with_offset_scale(): # Tests of specific cases in slope, inter SIAW = SlopeInterArrayWriter aw = SIAW(np.array([0, 127], dtype=np.int8), np.uint8) - assert_equal((aw.slope, aw.inter), (1, 0)) # in range + assert (aw.slope, aw.inter) == (1, 0) # in range aw = SIAW(np.array([-1, 126], dtype=np.int8), np.uint8) - assert_equal((aw.slope, aw.inter), (1, -1)) # offset only + assert (aw.slope, aw.inter) == (1, -1) # offset only aw = SIAW(np.array([-1, 254], dtype=np.int16), np.uint8) - assert_equal((aw.slope, aw.inter), (1, -1)) # offset only + assert (aw.slope, aw.inter) == (1, -1) # offset only aw = SIAW(np.array([-1, 255], dtype=np.int16), np.uint8) - assert_not_equal((aw.slope, aw.inter), (1, -1)) # Too big for offset only + assert (aw.slope, aw.inter) != (1, -1) # Too big for offset only aw = SIAW(np.array([-256, -2], dtype=np.int16), np.uint8) - assert_equal((aw.slope, aw.inter), (1, -256)) # offset only + assert (aw.slope, aw.inter) == (1, -256) # offset only aw = SIAW(np.array([-256, -2], dtype=np.int16), np.int8) - assert_equal((aw.slope, aw.inter), (1, -129)) # offset only + assert (aw.slope, aw.inter) == (1, -129) # offset only def test_io_scaling(): @@ -450,10 +458,10 @@ def test_io_scaling(): # Slope might be negative max_miss = np.abs(aw.slope) / 2. abs_err = np.abs(arr - arr3) - assert_true(np.all(abs_err <= max_miss)) + assert np.all(abs_err <= max_miss) if out_type in UINT_TYPES and 0 in (min(arr), max(arr)): # Check that error is minimized for 0 as min or max - assert_true(min(abs_err) == abs_err[arr == 0]) + assert min(abs_err) == abs_err[arr == 0] bio.truncate(0) bio.seek(0) @@ -476,10 +484,10 @@ def test_input_ranges(): max_miss = np.abs(aw.slope) / working_type(2.) + work_eps * 10 abs_err = np.abs(arr - arr3) max_err = np.abs(arr) * work_eps + max_miss - assert_true(np.all(abs_err <= max_err)) + assert np.all(abs_err <= max_err) if out_type in UINT_TYPES and 0 in (min(arr), max(arr)): # Check that error is minimized for 0 as min or max - assert_true(min(abs_err) == abs_err[arr == 0]) + assert min(abs_err) == abs_err[arr == 0] bio.truncate(0) bio.seek(0) @@ -500,12 +508,13 @@ def test_nan2zero(): assert_array_equal(np.isnan(data_back), [True, False]) # Deprecation warning for nan2zero as argument to `to_fileobj` with error_warnings(): - assert_raises(DeprecationWarning, - aw.to_fileobj, BytesIO(), 'F', True) - assert_raises(DeprecationWarning, - aw.to_fileobj, BytesIO(), 'F', nan2zero=True) + with pytest.deprecated_call(): + aw.to_fileobj(BytesIO(), 'F', True) + with pytest.deprecated_call(): + aw.to_fileobj(BytesIO(), 'F', nan2zero=True) # Error if nan2zero is not the value set at initialization - assert_raises(WriterError, aw.to_fileobj, BytesIO(), 'F', False) + with pytest.raises(WriterError): + aw.to_fileobj(BytesIO(), 'F', False) # set explicitly aw = awt(arr, np.float32, nan2zero=True, **kwargs) data_back = round_trip(aw) @@ -521,12 +530,13 @@ def test_nan2zero(): assert_array_equal(data_back, [astype_res, 99]) # Deprecation warning for nan2zero as argument to `to_fileobj` with error_warnings(): - assert_raises(DeprecationWarning, - aw.to_fileobj, BytesIO(), 'F', False) - assert_raises(DeprecationWarning, - aw.to_fileobj, BytesIO(), 'F', nan2zero=False) + with pytest.deprecated_call(): + aw.to_fileobj(BytesIO(), 'F', False) + with pytest.deprecated_call(): + aw.to_fileobj(BytesIO(), 'F', nan2zero=False) # Error if nan2zero is not the value set at initialization - assert_raises(WriterError, aw.to_fileobj, BytesIO(), 'F', True) + with pytest.raises(WriterError): + aw.to_fileobj(BytesIO(), 'F', True) def test_byte_orders(): @@ -580,55 +590,62 @@ def test_to_float(): for klass in (SlopeInterArrayWriter, SlopeArrayWriter, ArrayWriter): if in_type in COMPLEX_TYPES and out_type in FLOAT_TYPES: - assert_raises(WriterError, klass, arr, out_type) + with pytest.raises(WriterError): + klass(arr, out_type) continue aw = klass(arr, out_type) - assert_true(aw.array is arr) - assert_equal(aw.out_dtype, out_type) + assert aw.array is arr + assert aw.out_dtype == out_type arr_back = round_trip(aw) assert_array_equal(arr.astype(out_type), arr_back) # Check too-big values overflowed correctly out_min, out_max = out_info['min'], out_info['max'] - assert_true(np.all(arr_back[arr > out_max] == np.inf)) - assert_true(np.all(arr_back[arr < out_min] == -np.inf)) + assert np.all(arr_back[arr > out_max] == np.inf) + assert np.all(arr_back[arr < out_min] == -np.inf) def test_dumber_writers(): arr = np.arange(10, dtype=np.float64) aw = SlopeArrayWriter(arr) aw.slope = 2.0 - assert_equal(aw.slope, 2.0) - assert_raises(AttributeError, getattr, aw, 'inter') + assert aw.slope == 2.0 + with pytest.raises(AttributeError): + aw.inter aw = ArrayWriter(arr) - assert_raises(AttributeError, getattr, aw, 'slope') - assert_raises(AttributeError, getattr, aw, 'inter') + with pytest.raises(AttributeError): + aw.slope + with pytest.raises(AttributeError): + aw.inter # Attempt at scaling should raise error for dumb type - assert_raises(WriterError, ArrayWriter, arr, np.int16) + with pytest.raises(WriterError): + ArrayWriter(arr, np.int16) def test_writer_maker(): arr = np.arange(10, dtype=np.float64) aw = make_array_writer(arr, np.float64) - assert_true(isinstance(aw, SlopeInterArrayWriter)) + assert isinstance(aw, SlopeInterArrayWriter) aw = make_array_writer(arr, np.float64, True, True) - assert_true(isinstance(aw, SlopeInterArrayWriter)) + assert isinstance(aw, SlopeInterArrayWriter) aw = make_array_writer(arr, np.float64, True, False) - assert_true(isinstance(aw, SlopeArrayWriter)) + assert isinstance(aw, SlopeArrayWriter) aw = make_array_writer(arr, np.float64, False, False) - assert_true(isinstance(aw, ArrayWriter)) - assert_raises(ValueError, make_array_writer, arr, np.float64, False) - assert_raises(ValueError, make_array_writer, arr, np.float64, False, True) + assert isinstance(aw, ArrayWriter) + with pytest.raises(ValueError): + make_array_writer(arr, np.float64, False) + with pytest.raises(ValueError): + make_array_writer(arr, np.float64, False, True) # Does calc_scale get run by default? aw = make_array_writer(arr, np.int16, calc_scale=False) - assert_equal((aw.slope, aw.inter), (1, 0)) + assert (aw.slope, aw.inter) == (1, 0) aw.calc_scale() slope, inter = aw.slope, aw.inter - assert_false((slope, inter) == (1, 0)) + assert not (slope, inter) == (1, 0) # Should run by default aw = make_array_writer(arr, np.int16) - assert_equal((aw.slope, aw.inter), (slope, inter)) + assert (aw.slope, aw.inter) == (slope, inter) aw = make_array_writer(arr, np.int16, calc_scale=True) - assert_equal((aw.slope, aw.inter), (slope, inter)) + assert (aw.slope, aw.inter) == (slope, inter) def test_float_int_min_max(): @@ -647,7 +664,7 @@ def test_float_int_min_max(): except ScalingError: continue arr_back_sc = round_trip(aw) - assert_true(np.allclose(arr, arr_back_sc)) + assert np.allclose(arr, arr_back_sc) def test_int_int_min_max(): @@ -666,7 +683,7 @@ def test_int_int_min_max(): # integer allclose adiff = int_abs(arr - arr_back_sc) rdiff = adiff / (arr + eps) - assert_true(np.all(rdiff < rtol)) + assert np.all(rdiff < rtol) def test_int_int_slope(): @@ -687,12 +704,12 @@ def test_int_int_slope(): aw = SlopeArrayWriter(arr, out_dt) except ScalingError: continue - assert_false(aw.slope == 0) + assert not aw.slope == 0 arr_back_sc = round_trip(aw) # integer allclose adiff = int_abs(arr - arr_back_sc) rdiff = adiff / (arr + eps) - assert_true(np.all(rdiff < rtol)) + assert np.all(rdiff < rtol) def test_float_int_spread(): @@ -712,7 +729,7 @@ def test_float_int_spread(): # Simulate allclose test with large atol diff = np.abs(arr_t - arr_back_sc) rdiff = diff / np.abs(arr_t) - assert_true(np.all((diff <= max_miss) | (rdiff <= 1e-5))) + assert np.all((diff <= max_miss) | (rdiff <= 1e-5)) def rt_err_estimate(arr_t, out_dtype, slope, inter): @@ -749,7 +766,7 @@ def test_rt_bias(): aw.inter) # Hokey use of max_miss as a std estimate bias_thresh = np.max([max_miss / np.sqrt(count), eps]) - assert_true(np.abs(bias) < bias_thresh) + assert np.abs(bias) < bias_thresh def test_nan2zero_scaling(): @@ -789,10 +806,10 @@ def test_nan2zero_scaling(): back_nan_0 = round_trip(nan_0_aw) * float(sign) zero_aw = awt(zero_arr, out_dt, nan2zero=True) back_zero = round_trip(zero_aw) * float(sign) - assert_true(np.allclose(back_nan[1:], back_zero[1:])) + assert np.allclose(back_nan[1:], back_zero[1:]) assert_array_equal(back_nan[1:], back_nan_0[2:]) - assert_true(np.abs(back_nan[0] - back_zero[0]) < 1e-2) - assert_equal(*back_nan_0[:2]) + assert np.abs(back_nan[0] - back_zero[0]) < 1e-2 + assert back_nan_0[0] == back_nan_0[1] def test_finite_range_nan(): @@ -834,11 +851,11 @@ def test_finite_range_nan(): continue # Should not matter about the order of finite range method call # and has_nan property - test this is true - assert_equal(aw.has_nan, has_nan) - assert_equal(aw.finite_range(), res) + assert aw.has_nan == has_nan + assert aw.finite_range() == res aw = awt(in_arr, out_type, **kwargs) - assert_equal(aw.finite_range(), res) - assert_equal(aw.has_nan, has_nan) + assert aw.finite_range() == res + assert aw.has_nan == has_nan # Check float types work as complex in_arr = np.array(in_arr) if in_arr.dtype.kind == 'f': @@ -848,10 +865,11 @@ def test_finite_range_nan(): except WriterError: continue aw = awt(c_arr, out_type, **kwargs) - assert_equal(aw.has_nan, has_nan) - assert_equal(aw.finite_range(), res) + assert aw.has_nan == has_nan + assert aw.finite_range() == res # Structured type cannot be nan and we can test this a = np.array([[1., 0, 1], [2, 3, 4]]).view([('f1', 'f')]) aw = awt(a, a.dtype, **kwargs) - assert_raises(TypeError, aw.finite_range) - assert_false(aw.has_nan) + with pytest.raises(TypeError): + aw.finite_range() + assert not aw.has_nan diff --git a/nibabel/tests/test_batteryrunners.py b/nibabel/tests/test_batteryrunners.py index 1130c2f4cb..69f18b75ac 100644 --- a/nibabel/tests/test_batteryrunners.py +++ b/nibabel/tests/test_batteryrunners.py @@ -15,9 +15,7 @@ from ..batteryrunners import BatteryRunner, Report -from ..testing import (assert_true, assert_false, assert_equal, - assert_not_equal, assert_raises) - +import pytest # define some trivial functions as checks def chk1(obj, fix=False): @@ -80,64 +78,67 @@ def chk_error(obj, fix=False): def test_init_basic(): # With no args, raise - assert_raises(TypeError, BatteryRunner) + with pytest.raises(TypeError): + BatteryRunner() # Len returns number of checks battrun = BatteryRunner((chk1,)) - assert_equal(len(battrun), 1) + assert len(battrun) == 1 battrun = BatteryRunner((chk1, chk2)) - assert_equal(len(battrun), 2) + assert len(battrun) == 2 def test_init_report(): rep = Report() - assert_equal(rep, Report(Exception, 0, '', '')) + assert rep == Report(Exception, 0, '', '') def test_report_strings(): rep = Report() - assert_not_equal(rep.__str__(), '') - assert_equal(rep.message, '') + assert rep.__str__() != '' + assert rep.message == '' str_io = StringIO() rep.write_raise(str_io) - assert_equal(str_io.getvalue(), '') + assert str_io.getvalue() == '' rep = Report(ValueError, 20, 'msg', 'fix') rep.write_raise(str_io) - assert_equal(str_io.getvalue(), '') + assert str_io.getvalue() == '' rep.problem_level = 30 rep.write_raise(str_io) - assert_equal(str_io.getvalue(), 'Level 30: msg; fix\n') + assert str_io.getvalue() == 'Level 30: msg; fix\n' str_io.truncate(0) str_io.seek(0) # No fix string, no fix message rep.fix_msg = '' rep.write_raise(str_io) - assert_equal(str_io.getvalue(), 'Level 30: msg\n') + assert str_io.getvalue() == 'Level 30: msg\n' rep.fix_msg = 'fix' str_io.truncate(0) str_io.seek(0) # If we drop the level, nothing goes to the log rep.problem_level = 20 rep.write_raise(str_io) - assert_equal(str_io.getvalue(), '') + assert str_io.getvalue() == '' # Unless we set the default log level in the call rep.write_raise(str_io, log_level=20) - assert_equal(str_io.getvalue(), 'Level 20: msg; fix\n') + assert str_io.getvalue() == 'Level 20: msg; fix\n' str_io.truncate(0) str_io.seek(0) # If we set the error level down this low, we raise an error - assert_raises(ValueError, rep.write_raise, str_io, 20) + with pytest.raises(ValueError): + rep.write_raise(str_io, 20) # But the log level wasn't low enough to do a log entry - assert_equal(str_io.getvalue(), '') + assert str_io.getvalue() == '' # Error still raised with lower log threshold, but now we do get a # log entry - assert_raises(ValueError, rep.write_raise, str_io, 20, 20) - assert_equal(str_io.getvalue(), 'Level 20: msg; fix\n') + with pytest.raises(ValueError): + rep.write_raise(str_io, 20, 20) + assert str_io.getvalue() == 'Level 20: msg; fix\n' # If there's no error, we can't raise str_io.truncate(0) str_io.seek(0) rep.error = None rep.write_raise(str_io, 20) - assert_equal(str_io.getvalue(), '') + assert str_io.getvalue() == '' def test_logging(): @@ -147,10 +148,10 @@ def test_logging(): logger.setLevel(30) # defaultish level logger.addHandler(logging.StreamHandler(str_io)) rep.log_raise(logger) - assert_equal(str_io.getvalue(), '') + assert str_io.getvalue() == '' rep.problem_level = 30 rep.log_raise(logger) - assert_equal(str_io.getvalue(), 'msg; fix\n') + assert str_io.getvalue() == 'msg; fix\n' str_io.truncate(0) str_io.seek(0) @@ -158,43 +159,19 @@ def test_logging(): def test_checks(): battrun = BatteryRunner((chk1,)) reports = battrun.check_only({}) - assert_equal(reports[0], - Report(KeyError, - 20, - 'no "testkey"', - '')) + assert reports[0] == Report(KeyError, 20, 'no "testkey"', '') obj, reports = battrun.check_fix({}) - assert_equal(reports[0], - Report(KeyError, - 20, - 'no "testkey"', - 'added "testkey"')) - assert_equal(obj, {'testkey': 1}) + assert reports[0] == Report(KeyError, 20, 'no "testkey"', 'added "testkey"') + assert obj == {'testkey': 1} battrun = BatteryRunner((chk1, chk2)) reports = battrun.check_only({}) - assert_equal(reports[0], - Report(KeyError, - 20, - 'no "testkey"', - '')) - assert_equal(reports[1], - Report(KeyError, - 20, - 'no "testkey"', - '')) + assert reports[0] == Report(KeyError, 20, 'no "testkey"', '') + assert reports[1] == Report(KeyError, 20, 'no "testkey"', '') obj, reports = battrun.check_fix({}) # In the case of fix, the previous fix exposes a different error # Note, because obj is mutable, first and second point to modified # (and final) dictionary output_obj = {'testkey': 0} - assert_equal(reports[0], - Report(KeyError, - 20, - 'no "testkey"', - 'added "testkey"')) - assert_equal(reports[1], - Report(ValueError, - 10, - '"testkey" != 0', - 'set "testkey" to 0')) - assert_equal(obj, output_obj) + assert reports[0] == Report(KeyError, 20, 'no "testkey"', 'added "testkey"') + assert reports[1] == Report(ValueError, 10, '"testkey" != 0', 'set "testkey" to 0') + assert obj == output_obj diff --git a/nibabel/tests/test_brikhead.py b/nibabel/tests/test_brikhead.py index d09023d248..45e149b93b 100644 --- a/nibabel/tests/test_brikhead.py +++ b/nibabel/tests/test_brikhead.py @@ -14,12 +14,11 @@ from .. import load, Nifti1Image from .. import brikhead -from nose.tools import (assert_true, assert_equal, assert_raises) +import pytest from numpy.testing import assert_array_equal -from ..testing import data_path +from ..testing import data_path, assert_data_similar from .test_fileslice import slicer_samples -from .test_helpers import assert_data_similar EXAMPLE_IMAGES = [ dict( @@ -80,10 +79,10 @@ def test_makehead(self): for tp in self.test_files: head1 = self.module.AFNIHeader.from_fileobj(tp['head']) head2 = self.module.AFNIHeader.from_header(head1) - assert_equal(head1, head2) - with assert_raises(self.module.AFNIHeaderError): + assert head1 == head2 + with pytest.raises(self.module.AFNIHeaderError): self.module.AFNIHeader.from_header(header=None) - with assert_raises(self.module.AFNIHeaderError): + with pytest.raises(self.module.AFNIHeaderError): self.module.AFNIHeader.from_header(tp['fname']) @@ -94,22 +93,22 @@ class TestAFNIImage(object): def test_brikheadfile(self): for tp in self.test_files: brik = self.module.load(tp['fname']) - assert_equal(brik.get_data_dtype().type, tp['dtype']) - assert_equal(brik.shape, tp['shape']) - assert_equal(brik.header.get_zooms(), tp['zooms']) + assert brik.get_data_dtype().type == tp['dtype'] + assert brik.shape == tp['shape'] + assert brik.header.get_zooms() == tp['zooms'] assert_array_equal(brik.affine, tp['affine']) - assert_equal(brik.header.get_space(), tp['space']) + assert brik.header.get_space() == tp['space'] data = brik.get_fdata() - assert_equal(data.shape, tp['shape']) + assert data.shape == tp['shape'] assert_array_equal(brik.dataobj.scaling, tp['scaling']) - assert_equal(brik.header.get_volume_labels(), tp['labels']) + assert brik.header.get_volume_labels() == tp['labels'] def test_load(self): # Check highest level load of brikhead works for tp in self.test_files: img = self.module.load(tp['head']) data = img.get_fdata() - assert_equal(data.shape, tp['shape']) + assert data.shape == tp['shape'] # min, max, mean values assert_data_similar(data, tp) # check if file can be converted to nifti @@ -123,7 +122,7 @@ def test_array_proxy_slicing(self): img = self.module.load(tp['fname']) arr = img.get_fdata() prox = img.dataobj - assert_true(prox.is_proxy) + assert prox.is_proxy for sliceobj in slicer_samples(img.shape): assert_array_equal(arr[sliceobj], prox[sliceobj]) @@ -134,7 +133,7 @@ class TestBadFiles(object): def test_brikheadfile(self): for tp in self.test_files: - with assert_raises(tp['err']): + with pytest.raises(tp['err']): self.module.load(tp['head']) @@ -145,5 +144,5 @@ class TestBadVars(object): def test_unpack_var(self): for var in self.vars: - with assert_raises(self.module.AFNIHeaderError): + with pytest.raises(self.module.AFNIHeaderError): self.module._unpack_var(var) diff --git a/nibabel/tests/test_casting.py b/nibabel/tests/test_casting.py index c9d3645ad1..b8f56454b5 100644 --- a/nibabel/tests/test_casting.py +++ b/nibabel/tests/test_casting.py @@ -12,7 +12,7 @@ from numpy.testing import (assert_array_almost_equal, assert_array_equal) -from nose.tools import (assert_true, assert_false, assert_equal, assert_raises) +import pytest def test_shared_range(): @@ -35,7 +35,7 @@ def test_shared_range(): # not have an exact representation. fimax = int_to_float(imax, ft) if np.isfinite(fimax): - assert_true(int(fimax) != imax) + assert int(fimax) != imax # Therefore the imax, cast back to float, and to integer, will # overflow. If it overflows to the imax, we need to allow for # that possibility in the testing of our overflowed values @@ -43,13 +43,11 @@ def test_shared_range(): if imax_roundtrip == imax: thresh_overflow = True if thresh_overflow: - assert_true(np.all( - (bit_bigger == casted_mx) | - (bit_bigger == imax))) + assert np.all((bit_bigger == casted_mx) | (bit_bigger == imax)) else: - assert_true(np.all((bit_bigger <= casted_mx))) + assert np.all((bit_bigger <= casted_mx)) if it in np.sctypes['uint']: - assert_equal(mn, 0) + assert mn == 0 continue # And something larger for the minimum with suppress_warnings(): # overflow @@ -63,7 +61,7 @@ def test_shared_range(): # not have an exact representation. fimin = int_to_float(imin, ft) if np.isfinite(fimin): - assert_true(int(fimin) != imin) + assert int(fimin) != imin # Therefore the imin, cast back to float, and to integer, will # overflow. If it overflows to the imin, we need to allow for # that possibility in the testing of our overflowed values @@ -71,11 +69,9 @@ def test_shared_range(): if imin_roundtrip == imin: thresh_overflow = True if thresh_overflow: - assert_true(np.all( - (bit_smaller == casted_mn) | - (bit_smaller == imin))) + assert np.all((bit_smaller == casted_mn) | (bit_smaller == imin)) else: - assert_true(np.all((bit_smaller >= casted_mn))) + assert np.all((bit_smaller >= casted_mn)) def test_shared_range_inputs(): @@ -114,7 +110,8 @@ def test_casting(): im_exp[1] = ii.max assert_array_equal(iarr, im_exp) # NaNs, with nan2zero False, gives error - assert_raises(CastingError, float_to_int, farr, it, False) + with pytest.raises(CastingError): + float_to_int(farr, it, False) # We can pass through NaNs if we really want exp_arr[arr.index(np.nan)] = ft(np.nan).astype(it) with np.errstate(invalid='ignore'): @@ -130,7 +127,8 @@ def test_casting(): with np.errstate(invalid='ignore'): assert_array_equal(float_to_int(np.nan, np.int16), [0]) # Test nans give error if not nan2zero - assert_raises(CastingError, float_to_int, np.nan, np.int16, False) + with pytest.raises(CastingError): + float_to_int(np.nan, np.int16, False) def test_int_abs(): @@ -139,25 +137,25 @@ def test_int_abs(): in_arr = np.array([info.min, info.max], dtype=itype) idtype = np.dtype(itype) udtype = np.dtype(idtype.str.replace('i', 'u')) - assert_equal(udtype.kind, 'u') - assert_equal(idtype.itemsize, udtype.itemsize) + assert udtype.kind == 'u' + assert idtype.itemsize == udtype.itemsize mn, mx = in_arr e_mn = as_int(mx) + 1 # as_int needed for numpy 1.4.1 casting - assert_equal(int_abs(mx), mx) - assert_equal(int_abs(mn), e_mn) + assert int_abs(mx) == mx + assert int_abs(mn) == e_mn assert_array_equal(int_abs(in_arr), [e_mn, mx]) def test_floor_log2(): - assert_equal(floor_log2(2**9 + 1), 9) - assert_equal(floor_log2(-2**9 + 1), 8) - assert_equal(floor_log2(2), 1) - assert_equal(floor_log2(1), 0) - assert_equal(floor_log2(0.5), -1) - assert_equal(floor_log2(0.75), -1) - assert_equal(floor_log2(0.25), -2) - assert_equal(floor_log2(0.24), -3) - assert_equal(floor_log2(0), None) + assert floor_log2(2**9 + 1) == 9 + assert floor_log2(-2**9 + 1) == 8 + assert floor_log2(2) == 1 + assert floor_log2(1) == 0 + assert floor_log2(0.5) == -1 + assert floor_log2(0.75) == -1 + assert floor_log2(0.25) == -2 + assert floor_log2(0.24) == -3 + assert floor_log2(0) is None def test_able_int_type(): @@ -176,7 +174,7 @@ def test_able_int_type(): ([-1, 2**64 - 1], None), ([0, 2**64 - 1], np.uint64), ([0, 2**64], None)): - assert_equal(able_int_type(vals), exp_out) + assert able_int_type(vals) == exp_out def test_able_casting(): @@ -193,11 +191,11 @@ def test_able_casting(): ApBt = (A + B).dtype.type able_type = able_int_type([in_mn, in_mx, out_mn, out_mx]) if able_type is None: - assert_equal(ApBt, np.float64) + assert ApBt == np.float64 continue # Use str for comparison to avoid int32/64 vs intp comparison # failures - assert_equal(np.dtype(ApBt).str, np.dtype(able_type).str) + assert np.dtype(ApBt).str == np.dtype(able_type).str def test_best_float(): @@ -212,51 +210,51 @@ def test_best_float(): best = best_float() end_of_ints = np.float64(2**53) # float64 has continuous integers up to 2**53 - assert_equal(end_of_ints, end_of_ints + 1) + assert end_of_ints == end_of_ints + 1 # longdouble may have more, but not on 32 bit windows, at least end_of_ints = np.longdouble(2**53) if (end_of_ints == (end_of_ints + 1) or # off continuous integers machine() == 'sparc64' or # crippling slow longdouble on sparc longdouble_precision_improved()): # Windows precisions can change - assert_equal(best, np.float64) + assert best == np.float64 else: - assert_equal(best, np.longdouble) + assert best == np.longdouble def test_longdouble_precision_improved(): # Just check that this can only be True on windows, msvc from numpy.distutils.ccompiler import get_default_compiler if not (os.name == 'nt' and get_default_compiler() == 'msvc'): - assert_false(longdouble_precision_improved()) + assert not longdouble_precision_improved() def test_ulp(): - assert_equal(ulp(), np.finfo(np.float64).eps) - assert_equal(ulp(1.0), np.finfo(np.float64).eps) - assert_equal(ulp(np.float32(1.0)), np.finfo(np.float32).eps) - assert_equal(ulp(np.float32(1.999)), np.finfo(np.float32).eps) + assert ulp() == np.finfo(np.float64).eps + assert ulp(1.0) == np.finfo(np.float64).eps + assert ulp(np.float32(1.0)) == np.finfo(np.float32).eps + assert ulp(np.float32(1.999)) == np.finfo(np.float32).eps # Integers always return 1 - assert_equal(ulp(1), 1) - assert_equal(ulp(2**63 - 1), 1) + assert ulp(1) == 1 + assert ulp(2**63 - 1) == 1 # negative / positive same - assert_equal(ulp(-1), 1) - assert_equal(ulp(7.999), ulp(4.0)) - assert_equal(ulp(-7.999), ulp(4.0)) - assert_equal(ulp(np.float64(2**54 - 2)), 2) - assert_equal(ulp(np.float64(2**54)), 4) - assert_equal(ulp(np.float64(2**54)), 4) + assert ulp(-1) == 1 + assert ulp(7.999) == ulp(4.0) + assert ulp(-7.999) == ulp(4.0) + assert ulp(np.float64(2**54 - 2)) == 2 + assert ulp(np.float64(2**54)) == 4 + assert ulp(np.float64(2**54)) == 4 # Infs, NaNs return nan - assert_true(np.isnan(ulp(np.inf))) - assert_true(np.isnan(ulp(-np.inf))) - assert_true(np.isnan(ulp(np.nan))) + assert np.isnan(ulp(np.inf)) + assert np.isnan(ulp(-np.inf)) + assert np.isnan(ulp(np.nan)) # 0 gives subnormal smallest subn64 = np.float64(2**(-1022 - 52)) subn32 = np.float32(2**(-126 - 23)) - assert_equal(ulp(0.0), subn64) - assert_equal(ulp(np.float64(0)), subn64) - assert_equal(ulp(np.float32(0)), subn32) + assert ulp(0.0) == subn64 + assert ulp(np.float64(0)) == subn64 + assert ulp(np.float32(0)) == subn32 # as do multiples of subnormal smallest - assert_equal(ulp(subn64 * np.float64(2**52)), subn64) - assert_equal(ulp(subn64 * np.float64(2**53)), subn64 * 2) - assert_equal(ulp(subn32 * np.float32(2**23)), subn32) - assert_equal(ulp(subn32 * np.float32(2**24)), subn32 * 2) + assert ulp(subn64 * np.float64(2**52)) == subn64 + assert ulp(subn64 * np.float64(2**53)) == subn64 * 2 + assert ulp(subn32 * np.float32(2**23)) == subn32 + assert ulp(subn32 * np.float32(2**24)) == subn32 * 2 diff --git a/nibabel/tests/test_data.py b/nibabel/tests/test_data.py index 641d6e55cd..e5d5000438 100644 --- a/nibabel/tests/test_data.py +++ b/nibabel/tests/test_data.py @@ -16,93 +16,73 @@ from .. import data as nibd -from nose import with_setup -from nose.tools import (assert_equal, assert_raises, raises, assert_false) +import pytest -from .test_environment import (setup_environment, - teardown_environment, - DATA_KEY, - USER_KEY) +from .test_environment import with_environment, DATA_KEY, USER_KEY -DATA_FUNCS = {} - -def setup_data_env(): - setup_environment() - global DATA_FUNCS +@pytest.fixture +def with_nimd_env(request, with_environment): + DATA_FUNCS = {} DATA_FUNCS['home_dir_func'] = nibd.get_nipy_user_dir DATA_FUNCS['sys_dir_func'] = nibd.get_nipy_system_dir DATA_FUNCS['path_func'] = nibd.get_data_path - - -def teardown_data_env(): - teardown_environment() + yield nibd.get_nipy_user_dir = DATA_FUNCS['home_dir_func'] nibd.get_nipy_system_dir = DATA_FUNCS['sys_dir_func'] nibd.get_data_path = DATA_FUNCS['path_func'] -# decorator to use setup, teardown environment -with_environment = with_setup(setup_data_env, teardown_data_env) - - def test_datasource(): # Tests for DataSource pth = pjoin('some', 'path') ds = Datasource(pth) - yield assert_equal, ds.get_filename('unlikeley'), pjoin(pth, 'unlikeley') - yield (assert_equal, ds.get_filename('un', 'like', 'ley'), - pjoin(pth, 'un', 'like', 'ley')) + assert ds.get_filename('unlikeley') == pjoin(pth, 'unlikeley') + assert ds.get_filename('un', 'like', 'ley') == pjoin(pth, 'un', 'like', 'ley') def test_versioned(): with TemporaryDirectory() as tmpdir: - yield (assert_raises, - DataError, - VersionedDatasource, - tmpdir) + with pytest.raises(DataError): + VersionedDatasource(tmpdir) tmpfile = pjoin(tmpdir, 'config.ini') # ini file, but wrong section with open(tmpfile, 'wt') as fobj: fobj.write('[SOMESECTION]\n') fobj.write('version = 0.1\n') - yield (assert_raises, - DataError, - VersionedDatasource, - tmpdir) + with pytest.raises(DataError): + VersionedDatasource(tmpdir) # ini file, but right section, wrong key with open(tmpfile, 'wt') as fobj: fobj.write('[DEFAULT]\n') fobj.write('somekey = 0.1\n') - yield (assert_raises, - DataError, - VersionedDatasource, - tmpdir) + with pytest.raises(DataError): + VersionedDatasource(tmpdir) # ini file, right section and key with open(tmpfile, 'wt') as fobj: fobj.write('[DEFAULT]\n') fobj.write('version = 0.1\n') vds = VersionedDatasource(tmpdir) - yield assert_equal, vds.version, '0.1' - yield assert_equal, vds.version_no, 0.1 - yield assert_equal, vds.major_version, 0 - yield assert_equal, vds.minor_version, 1 - yield assert_equal, vds.get_filename('config.ini'), tmpfile + assert vds.version == '0.1' + assert vds.version_no == 0.1 + assert vds.major_version == 0 + assert vds.minor_version == 1 + assert vds.get_filename('config.ini') == tmpfile # ini file, right section and key, funny value with open(tmpfile, 'wt') as fobj: fobj.write('[DEFAULT]\n') fobj.write('version = 0.1.2.dev\n') vds = VersionedDatasource(tmpdir) - yield assert_equal, vds.version, '0.1.2.dev' - yield assert_equal, vds.version_no, 0.1 - yield assert_equal, vds.major_version, 0 - yield assert_equal, vds.minor_version, 1 + assert vds.version == '0.1.2.dev' + assert vds.version_no == 0.1 + assert vds.major_version == 0 + assert vds.minor_version == 1 def test__cfg_value(): # no file, return '' - yield assert_equal, _cfg_value('/implausible_file'), '' + assert _cfg_value('/implausible_file') == '' # try files try: fd, tmpfile = tempfile.mkstemp() @@ -111,16 +91,16 @@ def test__cfg_value(): fobj.write('[strange section]\n') fobj.write('path = /some/path\n') fobj.flush() - yield assert_equal, _cfg_value(tmpfile), '' + assert _cfg_value(tmpfile) == '' # right section, wrong key fobj.write('[DATA]\n') fobj.write('funnykey = /some/path\n') fobj.flush() - yield assert_equal, _cfg_value(tmpfile), '' + assert _cfg_value(tmpfile) == '' # right section, right key fobj.write('path = /some/path\n') fobj.flush() - yield assert_equal, _cfg_value(tmpfile), '/some/path' + assert _cfg_value(tmpfile) == '/some/path' fobj.close() finally: try: @@ -129,8 +109,7 @@ def test__cfg_value(): pass -@with_environment -def test_data_path(): +def test_data_path(with_nimd_env): # wipe out any sources of data paths if DATA_KEY in env: del env[DATA_KEY] @@ -147,15 +126,15 @@ def test_data_path(): def_dirs = [pjoin(sys.prefix, 'share', 'nipy')] if sys.prefix == '/usr': def_dirs.append(pjoin('/usr/local', 'share', 'nipy')) - assert_equal(old_pth, def_dirs + ['/user/path']) + assert old_pth == def_dirs + ['/user/path'] # then we'll try adding some of our own tst_pth = '/a/path' + os.path.pathsep + '/b/ path' tst_list = ['/a/path', '/b/ path'] # First, an environment variable os.environ[DATA_KEY] = tst_list[0] - assert_equal(get_data_path(), tst_list[:1] + old_pth) + assert get_data_path() == tst_list[:1] + old_pth os.environ[DATA_KEY] = tst_pth - assert_equal(get_data_path(), tst_list + old_pth) + assert get_data_path() == tst_list + old_pth del os.environ[DATA_KEY] # Next, make a fake user directory, and put a file in there with TemporaryDirectory() as tmpdir: @@ -164,9 +143,9 @@ def test_data_path(): fobj.write('[DATA]\n') fobj.write('path = %s' % tst_pth) nibd.get_nipy_user_dir = lambda: tmpdir - assert_equal(get_data_path(), tst_list + def_dirs + [tmpdir]) + assert get_data_path() == tst_list + def_dirs + [tmpdir] nibd.get_nipy_user_dir = lambda: fake_user_dir - assert_equal(get_data_path(), old_pth) + assert get_data_path() == old_pth # with some trepidation, the system config files with TemporaryDirectory() as tmpdir: nibd.get_nipy_system_dir = lambda: tmpdir @@ -178,8 +157,7 @@ def test_data_path(): with open(tmpfile, 'wt') as fobj: fobj.write('[DATA]\n') fobj.write('path = %s\n' % '/path/two') - assert_equal(get_data_path(), - tst_list + ['/path/two'] + old_pth) + assert get_data_path() == tst_list + ['/path/two'] + old_pth def test_find_data_dir(): @@ -189,52 +167,40 @@ def test_find_data_dir(): # under_here == '/nipy/utils' # subhere = 'tests' # fails with non-existant path - yield (assert_raises, - DataError, - find_data_dir, - [here], - 'implausible', - 'directory') + with pytest.raises(DataError): + find_data_dir([here], 'implausible', 'directory') # fails with file, when directory expected - yield (assert_raises, - DataError, - find_data_dir, - [here], - fname) + with pytest.raises(DataError): + find_data_dir([here], fname) # passes with directory that exists dd = find_data_dir([under_here], subhere) - yield assert_equal, dd, here + assert dd == here # and when one path in path list does not work dud_dir = pjoin(under_here, 'implausible') dd = find_data_dir([dud_dir, under_here], subhere) - yield assert_equal, dd, here + assert dd == here -@with_environment -def test_make_datasource(): +def test_make_datasource(with_nimd_env): pkg_def = dict( relpath='pkg') with TemporaryDirectory() as tmpdir: nibd.get_data_path = lambda: [tmpdir] - yield (assert_raises, - DataError, - make_datasource, - pkg_def) + with pytest.raises(DataError): + make_datasource(pkg_def) pkg_dir = pjoin(tmpdir, 'pkg') os.mkdir(pkg_dir) - yield (assert_raises, - DataError, - make_datasource, - pkg_def) + with pytest.raises(DataError): + make_datasource(pkg_def) tmpfile = pjoin(pkg_dir, 'config.ini') with open(tmpfile, 'wt') as fobj: fobj.write('[DEFAULT]\n') fobj.write('version = 0.1\n') ds = make_datasource(pkg_def, data_path=[tmpdir]) - yield assert_equal, ds.version, '0.1' + assert ds.version == '0.1' -@raises(DataError) +@pytest.mark.xfail(raises=DataError) def test_bomber(): b = Bomber('bomber example', 'a message') b.any_attribute # no error @@ -242,21 +208,16 @@ def test_bomber(): def test_bomber_inspect(): b = Bomber('bomber example', 'a message') - assert_false(hasattr(b, 'any_attribute')) + assert not hasattr(b, 'any_attribute') -@with_environment -def test_datasource_or_bomber(): - pkg_def = dict( - relpath='pkg') +def test_datasource_or_bomber(with_nimd_env): + pkg_def = dict(relpath='pkg') with TemporaryDirectory() as tmpdir: nibd.get_data_path = lambda: [tmpdir] ds = datasource_or_bomber(pkg_def) - yield (assert_raises, - DataError, - getattr, - ds, - 'get_filename') + with pytest.raises(DataError): + ds.get_filename('some_file.txt') pkg_dir = pjoin(tmpdir, 'pkg') os.mkdir(pkg_dir) tmpfile = pjoin(pkg_dir, 'config.ini') @@ -271,8 +232,5 @@ def test_datasource_or_bomber(): ds.get_filename('some_file.txt') pkg_def['min version'] = '0.3' ds = datasource_or_bomber(pkg_def) # not OK - yield (assert_raises, - DataError, - getattr, - ds, - 'get_filename') + with pytest.raises(DataError): + ds.get_filename('some_file.txt') diff --git a/nibabel/tests/test_deprecated.py b/nibabel/tests/test_deprecated.py index 2964707717..c031a0c60d 100644 --- a/nibabel/tests/test_deprecated.py +++ b/nibabel/tests/test_deprecated.py @@ -7,7 +7,6 @@ from nibabel.deprecated import (ModuleProxy, FutureWarningMixin, deprecate_with_version) -from nose.tools import (assert_true, assert_equal) from nibabel.tests.test_deprecator import TestDeprecatorFunc as _TestDF @@ -25,9 +24,9 @@ def teardown(): def test_module_proxy(): # Test proxy for module mp = ModuleProxy('nibabel.deprecated') - assert_true(hasattr(mp, 'ModuleProxy')) - assert_true(mp.ModuleProxy is ModuleProxy) - assert_equal(repr(mp), '') + assert hasattr(mp, 'ModuleProxy') + assert mp.ModuleProxy is ModuleProxy + assert repr(mp) == '' def test_futurewarning_mixin(): @@ -47,19 +46,19 @@ class E(FutureWarningMixin, C): warn_message = "Oh no, not this one" with warnings.catch_warnings(record=True) as warns: c = C(42) - assert_equal(c.meth(), 42) - assert_equal(warns, []) + assert c.meth() == 42 + assert warns == [] d = D(42) - assert_equal(d.meth(), 42) + assert d.meth() == 42 warn = warns.pop(0) - assert_equal(warn.category, FutureWarning) - assert_equal(str(warn.message), + assert warn.category == FutureWarning + assert (str(warn.message) == 'This class will be removed in future versions') e = E(42) - assert_equal(e.meth(), 42) + assert e.meth() == 42 warn = warns.pop(0) - assert_equal(warn.category, FutureWarning) - assert_equal(str(warn.message), 'Oh no, not this one') + assert warn.category == FutureWarning + assert str(warn.message) == 'Oh no, not this one' class TestNibabelDeprecator(_TestDF): @@ -78,6 +77,6 @@ def func(): try: pkg_info.cmp_pkg_version.__defaults__ = ('2.0dev',) # No error, even though version is dev version of current - assert_equal(func(), 99) + assert func() == 99 finally: pkg_info.cmp_pkg_version.__defaults__ = ('2.0',) diff --git a/nibabel/tests/test_deprecator.py b/nibabel/tests/test_deprecator.py index c4dc2437a4..cf56dd598d 100644 --- a/nibabel/tests/test_deprecator.py +++ b/nibabel/tests/test_deprecator.py @@ -5,7 +5,7 @@ import warnings from functools import partial -from nose.tools import (assert_true, assert_raises, assert_equal) +import pytest from nibabel.deprecator import (_ensure_cr, _add_dep_doc, ExpiredDeprecationError, Deprecator) @@ -17,26 +17,26 @@ def test__ensure_cr(): # Make sure text ends with carriage return - assert_equal(_ensure_cr(' foo'), ' foo\n') - assert_equal(_ensure_cr(' foo\n'), ' foo\n') - assert_equal(_ensure_cr(' foo '), ' foo\n') - assert_equal(_ensure_cr('foo '), 'foo\n') - assert_equal(_ensure_cr('foo \n bar'), 'foo \n bar\n') - assert_equal(_ensure_cr('foo \n\n'), 'foo\n') + assert _ensure_cr(' foo') == ' foo\n' + assert _ensure_cr(' foo\n') == ' foo\n' + assert _ensure_cr(' foo ') == ' foo\n' + assert _ensure_cr('foo ') == 'foo\n' + assert _ensure_cr('foo \n bar') == 'foo \n bar\n' + assert _ensure_cr('foo \n\n') == 'foo\n' def test__add_dep_doc(): # Test utility function to add deprecation message to docstring - assert_equal(_add_dep_doc('', 'foo'), 'foo\n') - assert_equal(_add_dep_doc('bar', 'foo'), 'bar\n\nfoo\n') - assert_equal(_add_dep_doc(' bar', 'foo'), ' bar\n\nfoo\n') - assert_equal(_add_dep_doc(' bar', 'foo\n'), ' bar\n\nfoo\n') - assert_equal(_add_dep_doc('bar\n\n', 'foo'), 'bar\n\nfoo\n') - assert_equal(_add_dep_doc('bar\n \n', 'foo'), 'bar\n\nfoo\n') - assert_equal(_add_dep_doc(' bar\n\nSome explanation', 'foo\nbaz'), - ' bar\n\nfoo\nbaz\n\nSome explanation\n') - assert_equal(_add_dep_doc(' bar\n\n Some explanation', 'foo\nbaz'), - ' bar\n \n foo\n baz\n \n Some explanation\n') + assert _add_dep_doc('', 'foo') == 'foo\n' + assert _add_dep_doc('bar', 'foo') == 'bar\n\nfoo\n' + assert _add_dep_doc(' bar', 'foo') == ' bar\n\nfoo\n' + assert _add_dep_doc(' bar', 'foo\n') == ' bar\n\nfoo\n' + assert _add_dep_doc('bar\n\n', 'foo') == 'bar\n\nfoo\n' + assert _add_dep_doc('bar\n \n', 'foo') == 'bar\n\nfoo\n' + assert (_add_dep_doc(' bar\n\nSome explanation', 'foo\nbaz') == + ' bar\n\nfoo\nbaz\n\nSome explanation\n') + assert (_add_dep_doc(' bar\n\n Some explanation', 'foo\nbaz') == + ' bar\n \n foo\n baz\n \n Some explanation\n') class CustomError(Exception): @@ -69,77 +69,71 @@ 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_equal(func(), None) - assert_equal(len(w), 1) - assert_true(w[0].category is DeprecationWarning) - assert_equal(func.__doc__, 'foo\n') + 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_equal(func(1), None) - assert_equal(len(w), 1) - assert_equal(func.__doc__, 'A docstring\n\nfoo\n') + 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_equal(func(1, 2), None) - assert_equal(len(w), 1) - assert_equal(func.__doc__, 'A docstring\n \n foo\n \n Some text\n') + 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_equal(func.__doc__, 'foo\n\n* deprecated from version: 1.1\n') - with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: - warnings.simplefilter('always') - assert_equal(func(), None) - assert_equal(len(w), 1) - func = dec('foo', until='2.4')(func_no_doc) - with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: - warnings.simplefilter('always') - assert_equal(func(), None) - assert_equal(len(w), 1) - assert_equal(func.__doc__, - 'foo\n\n* Will raise {} as of version: 2.4\n' + assert func.__doc__ == 'foo\n\n* deprecated from version: 1.1\n' + with pytest.deprecated_call() as w: + assert func() is None + assert len(w) == 1 + func = dec('foo', until='99.4')(func_no_doc) + 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' .format(ExpiredDeprecationError)) func = dec('foo', until='1.8')(func_no_doc) - assert_raises(ExpiredDeprecationError, func) - assert_equal(func.__doc__, - 'foo\n\n* Raises {} as of version: 1.8\n' - .format(ExpiredDeprecationError)) + with pytest.raises(ExpiredDeprecationError): + func() + assert (func.__doc__ == + 'foo\n\n* Raises {} as of version: 1.8\n' + .format(ExpiredDeprecationError)) func = dec('foo', '1.2', '1.8')(func_no_doc) - assert_raises(ExpiredDeprecationError, func) - assert_equal(func.__doc__, - 'foo\n\n* deprecated from version: 1.2\n' - '* Raises {} as of version: 1.8\n' - .format(ExpiredDeprecationError)) + with pytest.raises(ExpiredDeprecationError): + func() + assert (func.__doc__ == + 'foo\n\n* deprecated from version: 1.2\n' + '* Raises {} as of version: 1.8\n' + .format(ExpiredDeprecationError)) func = dec('foo', '1.2', '1.8')(func_doc_long) - assert_equal(func.__doc__, - 'A docstring\n \n foo\n \n' - ' * deprecated from version: 1.2\n' - ' * Raises {} as of version: 1.8\n \n' - ' Some text\n' - .format(ExpiredDeprecationError)) - assert_raises(ExpiredDeprecationError, func) + 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)) + with pytest.raises(ExpiredDeprecationError): + func() # Check different warnings and errors func = dec('foo', warn_class=UserWarning)(func_no_doc) with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: warnings.simplefilter('always') - assert_equal(func(), None) - assert_equal(len(w), 1) - assert_true(w[0].category is UserWarning) + assert func() 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_equal(func(), None) - assert_equal(len(w), 1) - assert_true(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) - assert_raises(CustomError, func) + with pytest.raises(CustomError): + func() class TestDeprecatorMaker(object): @@ -150,19 +144,16 @@ 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_equal(func(), None) - assert_equal(len(w), 1) - assert_true(w[0].category is UserWarning) + with pytest.warns(UserWarning) as w: + # warnings.simplefilter('always') + assert func() is None + assert len(w) == 1 dec = self.dep_maker(error_class=CustomError) func = dec('foo')(func_no_doc) - with clear_and_catch_warnings(modules=[_OWN_MODULE]) as w: - warnings.simplefilter('always') - assert_equal(func(), None) - assert_equal(len(w), 1) - assert_true(w[0].category is DeprecationWarning) + with pytest.deprecated_call(): + assert func() is None func = dec('foo', until='1.8')(func_no_doc) - assert_raises(CustomError, func) + with pytest.raises(CustomError): + func() diff --git a/nibabel/tests/test_dft.py b/nibabel/tests/test_dft.py index 0285b01575..c7c80b0dd9 100644 --- a/nibabel/tests/test_dft.py +++ b/nibabel/tests/test_dft.py @@ -6,32 +6,28 @@ from io import BytesIO from ..testing import suppress_warnings -import numpy as np - with suppress_warnings(): from .. import dft from .. import nifti1 -from nose import SkipTest -from nose.tools import (assert_true, assert_false, assert_equal, assert_raises) +import unittest +import pytest # Shield optional package imports from ..optpkg import optional_package -# setup_module will raise SkipTest if no dicom to import from nibabel.pydicom_compat import have_dicom PImage, have_pil, _ = optional_package('PIL.Image') -pil_test = np.testing.dec.skipif(not have_pil, 'could not import PIL.Image') data_dir = pjoin(dirname(__file__), 'data') -def setup_module(): +def setUpModule(): if os.name == 'nt': - raise SkipTest('FUSE not available for windows, skipping dft tests') + raise unittest.SkipTest('FUSE not available for windows, skipping dft tests') if not have_dicom: - raise SkipTest('Need pydicom for dft tests, skipping') + raise unittest.SkipTest('Need pydicom for dft tests, skipping') def test_init(): @@ -41,41 +37,41 @@ def test_init(): def test_study(): studies = dft.get_studies(data_dir) - assert_equal(len(studies), 1) - assert_equal(studies[0].uid, + assert len(studies) == 1 + assert (studies[0].uid == '1.3.12.2.1107.5.2.32.35119.30000010011408520750000000022') - assert_equal(studies[0].date, '20100114') - assert_equal(studies[0].time, '121314.000000') - assert_equal(studies[0].comments, 'dft study comments') - assert_equal(studies[0].patient_name, 'dft patient name') - assert_equal(studies[0].patient_id, '1234') - assert_equal(studies[0].patient_birth_date, '19800102') - assert_equal(studies[0].patient_sex, 'F') + assert studies[0].date == '20100114' + assert studies[0].time == '121314.000000' + assert studies[0].comments == 'dft study comments' + assert studies[0].patient_name == 'dft patient name' + assert studies[0].patient_id == '1234' + assert studies[0].patient_birth_date == '19800102' + assert studies[0].patient_sex == 'F' def test_series(): studies = dft.get_studies(data_dir) - assert_equal(len(studies[0].series), 1) + assert len(studies[0].series) == 1 ser = studies[0].series[0] - assert_equal(ser.uid, + assert (ser.uid == '1.3.12.2.1107.5.2.32.35119.2010011420292594820699190.0.0.0') - assert_equal(ser.number, '12') - assert_equal(ser.description, 'CBU_DTI_64D_1A') - assert_equal(ser.rows, 256) - assert_equal(ser.columns, 256) - assert_equal(ser.bits_allocated, 16) - assert_equal(ser.bits_stored, 12) + assert ser.number == '12' + assert ser.description == 'CBU_DTI_64D_1A' + assert ser.rows == 256 + assert ser.columns == 256 + assert ser.bits_allocated == 16 + assert ser.bits_stored == 12 def test_storage_instances(): studies = dft.get_studies(data_dir) sis = studies[0].series[0].storage_instances - assert_equal(len(sis), 2) - assert_equal(sis[0].instance_number, 1) - assert_equal(sis[1].instance_number, 2) - assert_equal(sis[0].uid, + assert len(sis) == 2 + assert sis[0].instance_number == 1 + assert sis[1].instance_number == 2 + assert (sis[0].uid == '1.3.12.2.1107.5.2.32.35119.2010011420300180088599504.0') - assert_equal(sis[1].uid, + assert (sis[1].uid == '1.3.12.2.1107.5.2.32.35119.2010011420300180088599504.1') @@ -83,17 +79,17 @@ def test_storage_instance(): pass -@pil_test +@unittest.skipUnless(have_pil, 'could not import PIL.Image') def test_png(): studies = dft.get_studies(data_dir) data = studies[0].series[0].as_png() im = PImage.open(BytesIO(data)) - assert_equal(im.size, (256, 256)) + assert im.size == (256, 256) def test_nifti(): studies = dft.get_studies(data_dir) data = studies[0].series[0].as_nifti() - assert_equal(len(data), 352 + 2 * 256 * 256 * 2) + assert len(data) == 352 + 2 * 256 * 256 * 2 h = nifti1.Nifti1Header(data[:348]) - assert_equal(h.get_data_shape(), (256, 256, 2)) + assert h.get_data_shape() == (256, 256, 2) diff --git a/nibabel/tests/test_ecat.py b/nibabel/tests/test_ecat.py index a3a40b2904..a346c71569 100644 --- a/nibabel/tests/test_ecat.py +++ b/nibabel/tests/test_ecat.py @@ -17,11 +17,11 @@ get_frame_order, get_series_framenumbers) from unittest import TestCase -from nose.tools import (assert_true, assert_false, assert_equal, assert_raises) +import pytest from numpy.testing import assert_array_equal, assert_array_almost_equal -from ..testing import data_path, suppress_warnings, clear_and_catch_warnings +from ..testing import data_path, suppress_warnings from ..tmpdirs import InTemporaryDirectory from .test_wrapstruct import _TestWrapStructBase @@ -35,16 +35,16 @@ class TestEcatHeader(_TestWrapStructBase): example_file = ecat_file def test_header_size(self): - assert_equal(self.header_class.template_dtype.itemsize, 512) + assert self.header_class.template_dtype.itemsize == 512 def test_empty(self): hdr = self.header_class() - assert_true(len(hdr.binaryblock) == 512) - assert_true(hdr['magic_number'] == b'MATRIX72') - assert_true(hdr['sw_version'] == 74) - assert_true(hdr['num_frames'] == 0) - assert_true(hdr['file_type'] == 0) - assert_true(hdr['ecat_calibration_factor'] == 1.0) + assert len(hdr.binaryblock) == 512 + assert hdr['magic_number'] == b'MATRIX72' + assert hdr['sw_version'] == 74 + assert hdr['num_frames'] == 0 + assert hdr['file_type'] == 0 + assert hdr['ecat_calibration_factor'] == 1.0 def _set_something_into_hdr(self, hdr): # Called from test_bytes test method. Specific to the header data type @@ -53,28 +53,29 @@ def _set_something_into_hdr(self, hdr): def test_dtype(self): # dtype not specified in header, only in subheaders hdr = self.header_class() - assert_raises(NotImplementedError, hdr.get_data_dtype) + with pytest.raises(NotImplementedError): + hdr.get_data_dtype() def test_header_codes(self): fid = open(ecat_file, 'rb') hdr = self.header_class() newhdr = hdr.from_fileobj(fid) fid.close() - assert_true(newhdr.get_filetype() == 'ECAT7_VOLUME16') - assert_equal(newhdr.get_patient_orient(), + assert newhdr.get_filetype() == 'ECAT7_VOLUME16' + assert (newhdr.get_patient_orient() == 'ECAT7_Unknown_Orientation') def test_update(self): hdr = self.header_class() - assert_true(hdr['num_frames'] == 0) + assert hdr['num_frames'] == 0 hdr['num_frames'] = 2 - assert_true(hdr['num_frames'] == 2) + assert hdr['num_frames'] == 2 def test_from_eg_file(self): # Example header is big-endian with Opener(self.example_file) as fileobj: hdr = self.header_class.from_fileobj(fileobj, check=False) - assert_equal(hdr.endianness, '>') + assert hdr.endianness == '>' class TestEcatMlist(TestCase): @@ -93,9 +94,9 @@ def test_mlist(self): mats = np.recarray(shape=(32, 4), dtype=dt, buf=dat) fid.close() # tests - assert_true(mats['matlist'][0, 0] + mats['matlist'][0, 3] == 31) - assert_true(get_frame_order(mlist)[0][0] == 0) - assert_true(get_frame_order(mlist)[0][1] == 16842758.0) + assert mats['matlist'][0, 0] + mats['matlist'][0, 3] == 31 + assert get_frame_order(mlist)[0][0] == 0 + assert get_frame_order(mlist)[0][1] == 16842758.0 # test badly ordered mlist badordermlist = np.array([[1.68427540e+07, 3.00000000e+00, 1.20350000e+04, 1.00000000e+00], @@ -110,7 +111,7 @@ def test_mlist(self): [1.68427580e+07, 6.01680000e+04, 7.22000000e+04, 1.00000000e+00]]) with suppress_warnings(): # STORED order - assert_true(get_frame_order(badordermlist)[0][0] == 1) + assert get_frame_order(badordermlist)[0][0] == 1 def test_mlist_errors(self): fid = open(self.example_file, 'rb') @@ -132,17 +133,18 @@ def test_mlist_errors(self): with suppress_warnings(): # STORED order series_framenumbers = get_series_framenumbers(mlist) # first frame stored was actually 2nd frame acquired - assert_true(series_framenumbers[0] == 2) + assert series_framenumbers[0] == 2 order = [series_framenumbers[x] for x in sorted(series_framenumbers)] # true series order is [2,1,3,4,5,6], note counting starts at 1 - assert_true(order == [2, 1, 3, 4, 5, 6]) + assert order == [2, 1, 3, 4, 5, 6] mlist[0, 0] = 0 with suppress_warnings(): frames_order = get_frame_order(mlist) neworder = [frames_order[x][0] for x in sorted(frames_order)] - assert_true(neworder == [1, 2, 3, 4, 5]) + assert neworder == [1, 2, 3, 4, 5] with suppress_warnings(): - assert_raises(IOError, get_series_framenumbers, mlist) + with pytest.raises(IOError): + get_series_framenumbers(mlist) class TestEcatSubHeader(TestCase): @@ -155,26 +157,26 @@ class TestEcatSubHeader(TestCase): subhdr = subhdr_class(hdr, mlist, fid) def test_subheader_size(self): - assert_equal(self.subhdr_class._subhdrdtype.itemsize, 510) + assert self.subhdr_class._subhdrdtype.itemsize == 510 def test_subheader(self): - assert_equal(self.subhdr.get_shape(), (10, 10, 3)) - assert_equal(self.subhdr.get_nframes(), 1) - assert_equal(self.subhdr.get_nframes(), + assert self.subhdr.get_shape() == (10, 10, 3) + assert self.subhdr.get_nframes() == 1 + assert (self.subhdr.get_nframes() == len(self.subhdr.subheaders)) - assert_equal(self.subhdr._check_affines(), True) + assert self.subhdr._check_affines() is True assert_array_almost_equal(np.diag(self.subhdr.get_frame_affine()), np.array([2.20241979, 2.20241979, 3.125, 1.])) - assert_equal(self.subhdr.get_zooms()[0], 2.20241978764534) - assert_equal(self.subhdr.get_zooms()[2], 3.125) - assert_equal(self.subhdr._get_data_dtype(0), np.int16) + assert self.subhdr.get_zooms()[0] == 2.20241978764534 + assert self.subhdr.get_zooms()[2] == 3.125 + assert self.subhdr._get_data_dtype(0) == np.int16 #assert_equal(self.subhdr._get_frame_offset(), 1024) - assert_equal(self.subhdr._get_frame_offset(), 1536) + assert self.subhdr._get_frame_offset() == 1536 dat = self.subhdr.raw_data_from_fileobj() - assert_equal(dat.shape, self.subhdr.get_shape()) - assert_equal(self.subhdr.subheaders[0]['scale_factor'].item(), 1.0) + assert dat.shape == self.subhdr.get_shape() + assert self.subhdr.subheaders[0]['scale_factor'].item() == 1.0 ecat_calib_factor = self.hdr['ecat_calibration_factor'] - assert_equal(ecat_calib_factor, 25007614.0) + assert ecat_calib_factor == 25007614.0 class TestEcatImage(TestCase): @@ -183,9 +185,9 @@ class TestEcatImage(TestCase): img = image_class.load(example_file) def test_file(self): - assert_equal(self.img.file_map['header'].filename, + assert (self.img.file_map['header'].filename == self.example_file) - assert_equal(self.img.file_map['image'].filename, + assert (self.img.file_map['image'].filename == self.example_file) def test_save(self): @@ -200,7 +202,7 @@ def test_save(self): def test_data(self): dat = self.img.get_fdata() - assert_equal(dat.shape, self.img.shape) + assert dat.shape == self.img.shape frame = self.img.get_frame(0) assert_array_equal(frame, dat[:, :, :, 0]) @@ -220,7 +222,7 @@ def test_array_proxy_slicing(self): # Test slicing of array proxy arr = self.img.get_fdata() prox = self.img.dataobj - assert_true(prox.is_proxy) + assert prox.is_proxy for sliceobj in slicer_samples(self.img.shape): assert_array_equal(arr[sliceobj], prox[sliceobj]) @@ -235,7 +237,7 @@ def test_isolation(self): img = img_klass(arr, aff, hdr, sub_hdr, mlist) assert_array_equal(img.affine, aff) aff[0, 0] = 99 - assert_false(np.all(img.affine == aff)) + assert not np.all(img.affine == aff) def test_float_affine(self): # Check affines get converted to float @@ -246,9 +248,9 @@ def test_float_affine(self): self.img.get_subheaders(), self.img.get_mlist()) img = img_klass(arr, aff.astype(np.float32), hdr, sub_hdr, mlist) - assert_equal(img.get_affine().dtype, np.dtype(np.float64)) + assert img.get_affine().dtype == np.dtype(np.float64) img = img_klass(arr, aff.astype(np.int16), hdr, sub_hdr, mlist) - assert_equal(img.get_affine().dtype, np.dtype(np.float64)) + assert img.get_affine().dtype == np.dtype(np.float64) def test_data_regression(self): # Test whether data read has changed since 1.3.0 @@ -257,8 +259,8 @@ def test_data_regression(self): min=1125342630.0, mean=117907565661.46666) data = self.img.get_fdata() - assert_equal(data.max(), vals['max']) - assert_equal(data.min(), vals['min']) + assert data.max() == vals['max'] + assert data.min() == vals['min'] assert_array_almost_equal(data.mean(), vals['mean']) def test_mlist_regression(self): @@ -269,12 +271,11 @@ 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_equal(len(w), 0) + assert len(w) == 0 # Warning for from_filespec img_speced = EcatImage.from_filespec(ecat_file) - assert_equal(len(w), 1) + assert len(w) == 1 assert_array_equal(img_loaded.get_fdata(), img_speced.get_fdata()) diff --git a/nibabel/tests/test_ecat_data.py b/nibabel/tests/test_ecat_data.py index 4b187bf855..1accd01a14 100644 --- a/nibabel/tests/test_ecat_data.py +++ b/nibabel/tests/test_ecat_data.py @@ -17,7 +17,6 @@ from .nibabel_data import get_nibabel_data, needs_nibabel_data from ..ecat import load -from nose.tools import assert_equal from numpy.testing import (assert_array_equal, assert_almost_equal) ECAT_TEST_PATH = pjoin(get_nibabel_data(), 'nipy-ecattest') @@ -40,11 +39,11 @@ class TestNegatives(object): def test_load(self): # Check highest level load of minc works img = self.opener(self.example_params['fname']) - assert_equal(img.shape, self.example_params['shape']) - assert_equal(img.get_data_dtype(0).type, self.example_params['type']) + assert img.shape == self.example_params['shape'] + assert img.get_data_dtype(0).type == self.example_params['type'] # Check correspondence of data and recorded shape data = img.get_fdata() - assert_equal(data.shape, self.example_params['shape']) + assert data.shape == self.example_params['shape'] # min, max, mean values from given parameters assert_almost_equal(data.min(), self.example_params['min'], 4) assert_almost_equal(data.max(), self.example_params['max'], 4) diff --git a/nibabel/tests/test_endiancodes.py b/nibabel/tests/test_endiancodes.py index 805de0d572..94c9ea0344 100644 --- a/nibabel/tests/test_endiancodes.py +++ b/nibabel/tests/test_endiancodes.py @@ -10,31 +10,27 @@ import sys - -from nose.tools import assert_equal -from nose.tools import assert_true - from ..volumeutils import (endian_codes, native_code, swapped_code) def test_native_swapped(): native_is_le = sys.byteorder == 'little' if native_is_le: - assert_equal((native_code, swapped_code), ('<', '>')) + assert (native_code, swapped_code) == ('<', '>') else: - assert_equal((native_code, swapped_code), ('>', '<')) + assert (native_code, swapped_code) == ('>', '<') def test_to_numpy(): if sys.byteorder == 'little': - yield assert_true, endian_codes['native'] == '<' - yield assert_true, endian_codes['swapped'] == '>' + assert endian_codes['native'] == '<' + assert endian_codes['swapped'] == '>' else: - yield assert_true, endian_codes['native'] == '>' - yield assert_true, endian_codes['swapped'] == '<' - yield assert_true, endian_codes['native'] == endian_codes['='] - yield assert_true, endian_codes['big'] == '>' + assert endian_codes['native'] == '>' + assert endian_codes['swapped'] == '<' + assert endian_codes['native'] == endian_codes['='] + assert endian_codes['big'] == '>' for code in ('little', '<', 'l', 'L', 'le'): - yield assert_true, endian_codes[code] == '<' + assert endian_codes[code] == '<' for code in ('big', '>', 'b', 'B', 'be'): - yield assert_true, endian_codes[code] == '>' + assert endian_codes[code] == '>' diff --git a/nibabel/tests/test_environment.py b/nibabel/tests/test_environment.py index 7b02ea866f..19891a607b 100644 --- a/nibabel/tests/test_environment.py +++ b/nibabel/tests/test_environment.py @@ -8,32 +8,24 @@ from .. import environment as nibe -from numpy.testing import (assert_array_almost_equal, - assert_array_equal) +import pytest -from nose.tools import assert_equal - -from nose import with_setup - -GIVEN_ENV = {} DATA_KEY = 'NIPY_DATA_PATH' USER_KEY = 'NIPY_USER_DIR' -def setup_environment(): +@pytest.fixture +def with_environment(request): """Setup test environment for some functions that are tested in this module. In particular this functions stores attributes and other things that we need to stub in some test functions. This needs to be done on a function level and not module level because each testfunction needs a pristine environment. """ - global GIVEN_ENV + GIVEN_ENV = {} GIVEN_ENV['env'] = env.copy() - - -def teardown_environment(): - """Restore things that were remembered by the setup_environment function - """ + yield + """Restore things that were remembered by the setup_environment function """ orig_env = GIVEN_ENV['env'] # Pull keys out into list to avoid altering dictionary during iteration, # causing python 3 error @@ -43,17 +35,12 @@ def teardown_environment(): env.update(orig_env) -# decorator to use setup, teardown environment -with_environment = with_setup(setup_environment, teardown_environment) - - def test_nipy_home(): # Test logic for nipy home directory - assert_equal(nibe.get_home_dir(), os.path.expanduser('~')) + assert nibe.get_home_dir() == os.path.expanduser('~') -@with_environment -def test_user_dir(): +def test_user_dir(with_environment): if USER_KEY in env: del env[USER_KEY] home_dir = nibe.get_home_dir() @@ -61,16 +48,16 @@ def test_user_dir(): exp = pjoin(home_dir, '.nipy') else: exp = pjoin(home_dir, '_nipy') - assert_equal(exp, nibe.get_nipy_user_dir()) + assert exp == nibe.get_nipy_user_dir() env[USER_KEY] = '/a/path' - assert_equal(abspath('/a/path'), nibe.get_nipy_user_dir()) + assert abspath('/a/path') == nibe.get_nipy_user_dir() def test_sys_dir(): sys_dir = nibe.get_nipy_system_dir() if os.name == 'nt': - assert_equal(sys_dir, r'C:\etc\nipy') + assert sys_dir == r'C:\etc\nipy' elif os.name == 'posix': - assert_equal(sys_dir, r'/etc/nipy') + assert sys_dir == r'/etc/nipy' else: - assert_equal(sys_dir, None) + assert sys_dir is None diff --git a/nibabel/tests/test_euler.py b/nibabel/tests/test_euler.py index 0d7027222f..915e65e552 100644 --- a/nibabel/tests/test_euler.py +++ b/nibabel/tests/test_euler.py @@ -15,9 +15,7 @@ from .. import eulerangles as nea from .. import quaternions as nq -from nose.tools import assert_false -from nose.tools import assert_true - +import pytest from numpy.testing import assert_array_equal, assert_array_almost_equal FLOAT_EPS = np.finfo(np.float).eps @@ -90,36 +88,38 @@ def test_basic_euler(): M2 = nea.euler2mat(0, yr) M3 = nea.euler2mat(0, 0, xr) # which are all valid rotation matrices - yield assert_true, is_valid_rotation(M) - yield assert_true, is_valid_rotation(M1) - yield assert_true, is_valid_rotation(M2) - yield assert_true, is_valid_rotation(M3) + assert is_valid_rotation(M) + assert is_valid_rotation(M1) + assert is_valid_rotation(M2) + assert is_valid_rotation(M3) # Full matrix is composition of three individual matrices - yield assert_true, np.allclose(M, np.dot(M3, np.dot(M2, M1))) + assert np.allclose(M, np.dot(M3, np.dot(M2, M1))) # Rotations can be specified with named args, default 0 - yield assert_true, np.all(nea.euler2mat(zr) == nea.euler2mat(z=zr)) - yield assert_true, np.all(nea.euler2mat(0, yr) == nea.euler2mat(y=yr)) - yield assert_true, np.all(nea.euler2mat(0, 0, xr) == nea.euler2mat(x=xr)) + assert np.all(nea.euler2mat(zr) == nea.euler2mat(z=zr)) + assert np.all(nea.euler2mat(0, yr) == nea.euler2mat(y=yr)) + assert np.all(nea.euler2mat(0, 0, xr) == nea.euler2mat(x=xr)) # Applying an opposite rotation same as inverse (the inverse is # the same as the transpose, but just for clarity) - yield assert_true, np.allclose(nea.euler2mat(x=-xr), + assert np.allclose(nea.euler2mat(x=-xr), np.linalg.inv(nea.euler2mat(x=xr))) -def test_euler_mat(): +def test_euler_mat_1(): M = nea.euler2mat() - yield assert_array_equal, M, np.eye(3) - for x, y, z in eg_rots: - M1 = nea.euler2mat(z, y, x) - M2 = sympy_euler(z, y, x) - yield assert_array_almost_equal, M1, M2 - M3 = np.dot(x_only(x), np.dot(y_only(y), z_only(z))) - yield assert_array_almost_equal, M1, M3 - zp, yp, xp = nea.mat2euler(M1) - # The parameters may not be the same as input, but they give the - # same rotation matrix - M4 = nea.euler2mat(zp, yp, xp) - yield assert_array_almost_equal, M1, M4 + assert_array_equal(M, np.eye(3)) + +@pytest.mark.parametrize("x, y, z", eg_rots) +def test_euler_mat_2(x, y, z): + M1 = nea.euler2mat(z, y, x) + M2 = sympy_euler(z, y, x) + assert_array_almost_equal(M1, M2) + M3 = np.dot(x_only(x), np.dot(y_only(y), z_only(z))) + assert_array_almost_equal(M1, M3) + zp, yp, xp = nea.mat2euler(M1) + # The parameters may not be the same as input, but they give the + # same rotation matrix + M4 = nea.euler2mat(zp, yp, xp) + assert_array_almost_equal(M1, M4) def sympy_euler2quat(z=0, y=0, x=0): @@ -148,27 +148,27 @@ def test_euler_instability(): M = nea.euler2mat(*zyx) # Round trip M_back = nea.euler2mat(*nea.mat2euler(M)) - yield assert_true, np.allclose(M, M_back) + assert np.allclose(M, M_back) # disturb matrix slightly M_e = M - FLOAT_EPS # round trip to test - OK M_e_back = nea.euler2mat(*nea.mat2euler(M_e)) - yield assert_true, np.allclose(M_e, M_e_back) + assert np.allclose(M_e, M_e_back) # not so with crude routine M_e_back = nea.euler2mat(*crude_mat2euler(M_e)) - yield assert_false, np.allclose(M_e, M_e_back) - - -def test_quats(): - for x, y, z in eg_rots: - M1 = nea.euler2mat(z, y, x) - quatM = nq.mat2quat(M1) - quat = nea.euler2quat(z, y, x) - yield nq.nearly_equivalent, quatM, quat - quatS = sympy_euler2quat(z, y, x) - yield nq.nearly_equivalent, quat, quatS - zp, yp, xp = nea.quat2euler(quat) - # The parameters may not be the same as input, but they give the - # same rotation matrix - M2 = nea.euler2mat(zp, yp, xp) - yield assert_array_almost_equal, M1, M2 + assert not np.allclose(M_e, M_e_back) + + +@pytest.mark.parametrize("x, y, z", eg_rots) +def test_quats(x, y, z): + M1 = nea.euler2mat(z, y, x) + quatM = nq.mat2quat(M1) + quat = nea.euler2quat(z, y, x) + assert nq.nearly_equivalent(quatM, quat) + quatS = sympy_euler2quat(z, y, x) + assert nq.nearly_equivalent(quat, quatS) + zp, yp, xp = nea.quat2euler(quat) + # The parameters may not be the same as input, but they give the + # same rotation matrix + M2 = nea.euler2mat(zp, yp, xp) + assert_array_almost_equal(M1, M2) diff --git a/nibabel/tests/test_filebasedimages.py b/nibabel/tests/test_filebasedimages.py index a9c5668508..efac76a65a 100644 --- a/nibabel/tests/test_filebasedimages.py +++ b/nibabel/tests/test_filebasedimages.py @@ -10,9 +10,6 @@ from .test_image_api import GenericImageAPI, SerializeMixin -from nose.tools import (assert_true, assert_false, assert_equal, - assert_not_equal) - class FBNumpyImage(FileBasedImage): header_class = FileBasedHeader @@ -113,20 +110,20 @@ def __init__(self, seq=None): in_list = [1, 3, 2] hdr = H(in_list) hdr_c = hdr.copy() - assert_equal(hdr_c.a_list, hdr.a_list) + assert hdr_c.a_list == hdr.a_list # Copy is independent of original hdr_c.a_list[0] = 99 - assert_not_equal(hdr_c.a_list, hdr.a_list) + assert hdr_c.a_list != hdr.a_list # From header does a copy hdr2 = H.from_header(hdr) - assert_true(isinstance(hdr2, H)) - assert_equal(hdr2.a_list, hdr.a_list) + assert isinstance(hdr2, H) + assert hdr2.a_list == hdr.a_list hdr2.a_list[0] = 42 - assert_not_equal(hdr2.a_list, hdr.a_list) + assert hdr2.a_list != hdr.a_list # Default header input to from_heder gives new empty header hdr3 = H.from_header() - assert_true(isinstance(hdr3, H)) - assert_equal(hdr3.a_list, []) + assert isinstance(hdr3, H) + assert hdr3.a_list == [] hdr4 = H.from_header(None) - assert_true(isinstance(hdr4, H)) - assert_equal(hdr4.a_list, []) + assert isinstance(hdr4, H) + assert hdr4.a_list == [] diff --git a/nibabel/tests/test_filehandles.py b/nibabel/tests/test_filehandles.py index 1533b7c4f8..23ae573a70 100644 --- a/nibabel/tests/test_filehandles.py +++ b/nibabel/tests/test_filehandles.py @@ -20,10 +20,6 @@ from ..loadsave import load, save from ..nifti1 import Nifti1Image -from numpy.testing import (assert_array_almost_equal, - assert_array_equal) - - def test_multiload(): # Make a tiny image, save, load many times. If we are leaking filehandles, diff --git a/nibabel/tests/test_fileholders.py b/nibabel/tests/test_fileholders.py index b28727a47e..e31a6efcbc 100644 --- a/nibabel/tests/test_fileholders.py +++ b/nibabel/tests/test_fileholders.py @@ -6,56 +6,49 @@ from ..fileholders import FileHolder -from numpy.testing import (assert_array_almost_equal, - assert_array_equal) - -from nose.tools import assert_equal -from nose.tools import assert_false -from nose.tools import assert_true - def test_init(): fh = FileHolder('a_fname') - assert_equal(fh.filename, 'a_fname') - assert_true(fh.fileobj is None) - assert_equal(fh.pos, 0) + assert fh.filename == 'a_fname' + assert fh.fileobj is None + assert fh.pos == 0 sio0 = BytesIO() fh = FileHolder('a_test', sio0) - assert_equal(fh.filename, 'a_test') - assert_true(fh.fileobj is sio0) - assert_equal(fh.pos, 0) + assert fh.filename == 'a_test' + assert fh.fileobj is sio0 + assert fh.pos == 0 fh = FileHolder('a_test_2', sio0, 3) - assert_equal(fh.filename, 'a_test_2') - assert_true(fh.fileobj is sio0) - assert_equal(fh.pos, 3) + assert fh.filename == 'a_test_2' + assert fh.fileobj is sio0 + assert fh.pos == 3 def test_same_file_as(): fh = FileHolder('a_fname') - assert_true(fh.same_file_as(fh)) + assert fh.same_file_as(fh) fh2 = FileHolder('a_test') - assert_false(fh.same_file_as(fh2)) + assert not fh.same_file_as(fh2) sio0 = BytesIO() fh3 = FileHolder('a_fname', sio0) fh4 = FileHolder('a_fname', sio0) - assert_true(fh3.same_file_as(fh4)) - assert_false(fh3.same_file_as(fh)) + assert fh3.same_file_as(fh4) + assert not fh3.same_file_as(fh) fh5 = FileHolder(fileobj=sio0) fh6 = FileHolder(fileobj=sio0) - assert_true(fh5.same_file_as(fh6)) + assert fh5.same_file_as(fh6) # Not if the filename is the same - assert_false(fh5.same_file_as(fh3)) + assert not fh5.same_file_as(fh3) # pos doesn't matter fh4_again = FileHolder('a_fname', sio0, pos=4) - assert_true(fh3.same_file_as(fh4_again)) + assert fh3.same_file_as(fh4_again) def test_file_like(): # Test returning file object or filename fh = FileHolder('a_fname') - assert_equal(fh.file_like, 'a_fname') + assert fh.file_like == 'a_fname' bio = BytesIO() fh = FileHolder(fileobj=bio) - assert_true(fh.file_like is bio) + assert fh.file_like is bio fh = FileHolder('a_fname', fileobj=bio) - assert_true(fh.file_like is bio) + assert fh.file_like is bio diff --git a/nibabel/tests/test_filename_parser.py b/nibabel/tests/test_filename_parser.py index f7317ac183..b0abc6d608 100644 --- a/nibabel/tests/test_filename_parser.py +++ b/nibabel/tests/test_filename_parser.py @@ -11,99 +11,66 @@ from ..filename_parser import (types_filenames, TypesFilenamesError, parse_filename, splitext_addext) -from nose.tools import (assert_equal, assert_true, assert_false, - assert_raises) +import pytest def test_filenames(): types_exts = (('image', '.img'), ('header', '.hdr')) for t_fname in ('test.img', 'test.hdr', 'test', 'test.'): tfns = types_filenames(t_fname, types_exts) - assert_equal(tfns, - {'image': 'test.img', - 'header': 'test.hdr'}) - # enforcing extensions raises an error for bad extension - assert_raises(TypesFilenamesError, - types_filenames, - 'test.funny', - types_exts) - # If not enforcing extensions, it does the best job it can, - # assuming the passed filename is for the first type (in this case - # 'image') - tfns = types_filenames('test.funny', types_exts, - enforce_extensions=False) - assert_equal(tfns, - {'header': 'test.hdr', - 'image': 'test.funny'}) - # .gz and .bz2 suffixes to extensions, by default, are removed - # before extension checking etc, and then put back onto every - # returned filename. - tfns = types_filenames('test.img.gz', types_exts) - assert_equal(tfns, - {'header': 'test.hdr.gz', - 'image': 'test.img.gz'}) - tfns = types_filenames('test.img.bz2', types_exts) - assert_equal(tfns, - {'header': 'test.hdr.bz2', - 'image': 'test.img.bz2'}) - # of course, if we don't know about e.g. gz, and enforce_extensions - # is on, we get an errror - assert_raises(TypesFilenamesError, - types_filenames, - 'test.img.gz', - types_exts, ()) - # if we don't know about .gz extension, and not enforcing, then we - # get something a bit odd - tfns = types_filenames('test.img.gz', types_exts, - trailing_suffixes=(), - enforce_extensions=False) - assert_equal(tfns, - {'header': 'test.img.hdr', - 'image': 'test.img.gz'}) - # the suffixes we remove and replaces can be any suffixes. - tfns = types_filenames('test.img.bzr', types_exts, ('.bzr',)) - assert_equal(tfns, - {'header': 'test.hdr.bzr', - 'image': 'test.img.bzr'}) - # If we specifically pass the remove / replace suffixes, then we - # don't remove / replace the .gz and .bz2, unless they are passed - # specifically. - tfns = types_filenames('test.img.bzr', types_exts, - trailing_suffixes=('.bzr',), - enforce_extensions=False) - assert_equal(tfns, - {'header': 'test.hdr.bzr', - 'image': 'test.img.bzr'}) - # but, just .gz or .bz2 as extension gives an error, if enforcing is on - assert_raises(TypesFilenamesError, - types_filenames, - 'test.gz', - types_exts) - assert_raises(TypesFilenamesError, - types_filenames, - 'test.bz2', - types_exts) - # if enforcing is off, it tries to work out what the other files - # should be assuming the passed filename is of the first input type - tfns = types_filenames('test.gz', types_exts, - enforce_extensions=False) - assert_equal(tfns, - {'image': 'test.gz', - 'header': 'test.hdr.gz'}) - # case (in)sensitivity, and effect of uppercase, lowercase - tfns = types_filenames('test.IMG', types_exts) - assert_equal(tfns, - {'image': 'test.IMG', - 'header': 'test.HDR'}) - tfns = types_filenames('test.img', - (('image', '.IMG'), ('header', '.HDR'))) - assert_equal(tfns, - {'header': 'test.hdr', - 'image': 'test.img'}) - tfns = types_filenames('test.IMG.Gz', types_exts) - assert_equal(tfns, - {'image': 'test.IMG.Gz', - 'header': 'test.HDR.Gz'}) + assert tfns == {'image': 'test.img', 'header': 'test.hdr'} + # enforcing extensions raises an error for bad extension + with pytest.raises(TypesFilenamesError): + types_filenames('test.funny', types_exts) + # If not enforcing extensions, it does the best job it can, + # assuming the passed filename is for the first type (in this case + # 'image') + tfns = types_filenames('test.funny', types_exts, enforce_extensions=False) + assert tfns == {'header': 'test.hdr', 'image': 'test.funny'} + # .gz and .bz2 suffixes to extensions, by default, are removed + # before extension checking etc, and then put back onto every + # returned filename. + tfns = types_filenames('test.img.gz', types_exts) + assert tfns == {'header': 'test.hdr.gz', 'image': 'test.img.gz'} + tfns = types_filenames('test.img.bz2', types_exts) + assert tfns == {'header': 'test.hdr.bz2', 'image': 'test.img.bz2'} + # of course, if we don't know about e.g. gz, and enforce_extensions + # is on, we get an errror + with pytest.raises(TypesFilenamesError): + types_filenames('test.img.gz', types_exts, ()) + # if we don't know about .gz extension, and not enforcing, then we + # get something a bit odd + tfns = types_filenames('test.img.gz', types_exts, + trailing_suffixes=(), + enforce_extensions=False) + assert tfns == {'header': 'test.img.hdr', 'image': 'test.img.gz'} + # the suffixes we remove and replaces can be any suffixes. + tfns = types_filenames('test.img.bzr', types_exts, ('.bzr',)) + assert tfns == {'header': 'test.hdr.bzr', 'image': 'test.img.bzr'} + # If we specifically pass the remove / replace suffixes, then we + # don't remove / replace the .gz and .bz2, unless they are passed + # specifically. + tfns = types_filenames('test.img.bzr', types_exts, + trailing_suffixes=('.bzr',), + enforce_extensions=False) + assert tfns == {'header': 'test.hdr.bzr', 'image': 'test.img.bzr'} + # but, just .gz or .bz2 as extension gives an error, if enforcing is on + with pytest.raises(TypesFilenamesError): + types_filenames('test.gz', types_exts) + with pytest.raises(TypesFilenamesError): + types_filenames('test.bz2', types_exts) + # if enforcing is off, it tries to work out what the other files + # should be assuming the passed filename is of the first input type + tfns = types_filenames('test.gz', types_exts, + enforce_extensions=False) + assert tfns == {'image': 'test.gz', 'header': 'test.hdr.gz'} + # case (in)sensitivity, and effect of uppercase, lowercase + tfns = types_filenames('test.IMG', types_exts) + assert tfns == {'image': 'test.IMG', 'header': 'test.HDR'} + tfns = types_filenames('test.img', (('image', '.IMG'), ('header', '.HDR'))) + assert tfns == {'header': 'test.hdr', 'image': 'test.img'} + tfns = types_filenames('test.IMG.Gz', types_exts) + assert tfns == {'image': 'test.IMG.Gz', 'header': 'test.HDR.Gz'} def test_parse_filename(): @@ -121,52 +88,52 @@ def test_parse_filename(): for inps, exps in exp_in_outs: pth, sufs = inps res = parse_filename(pth, types_exts, sufs) - assert_equal(res, exps) + assert res == exps upth = pth.upper() uexps = (exps[0].upper(), exps[1].upper(), exps[2].upper() if exps[2] else None, exps[3]) res = parse_filename(upth, types_exts, sufs) - assert_equal(res, uexps) + assert res == uexps # test case sensitivity res = parse_filename('/path/fnameext2.GZ', types_exts, ('.gz',), False) # case insensitive again - assert_equal(res, ('/path/fname', 'ext2', '.GZ', 't2')) + assert res == ('/path/fname', 'ext2', '.GZ', 't2') res = parse_filename('/path/fnameext2.GZ', types_exts, ('.gz',), True) # case sensitive - assert_equal(res, ('/path/fnameext2', '.GZ', None, None)) + assert res == ('/path/fnameext2', '.GZ', None, None) res = parse_filename('/path/fnameEXT2.gz', types_exts, ('.gz',), False) # case insensitive - assert_equal(res, ('/path/fname', 'EXT2', '.gz', 't2')) + assert res == ('/path/fname', 'EXT2', '.gz', 't2') res = parse_filename('/path/fnameEXT2.gz', types_exts, ('.gz',), True) # case sensitive - assert_equal(res, ('/path/fnameEXT2', '', '.gz', None)) + assert res == ('/path/fnameEXT2', '', '.gz', None) def test_splitext_addext(): res = splitext_addext('fname.ext.gz') - assert_equal(res, ('fname', '.ext', '.gz')) + assert res == ('fname', '.ext', '.gz') res = splitext_addext('fname.ext') - assert_equal(res, ('fname', '.ext', '')) + assert res == ('fname', '.ext', '') res = splitext_addext('fname.ext.foo', ('.foo', '.bar')) - assert_equal(res, ('fname', '.ext', '.foo')) + assert res == ('fname', '.ext', '.foo') res = splitext_addext('fname.ext.FOO', ('.foo', '.bar')) - assert_equal(res, ('fname', '.ext', '.FOO')) + assert res == ('fname', '.ext', '.FOO') # case sensitive res = splitext_addext('fname.ext.FOO', ('.foo', '.bar'), True) - assert_equal(res, ('fname.ext', '.FOO', '')) + assert res == ('fname.ext', '.FOO', '') # edge cases res = splitext_addext('.nii') - assert_equal(res, ('', '.nii', '')) + assert res == ('', '.nii', '') res = splitext_addext('...nii') - assert_equal(res, ('..', '.nii', '')) + assert res == ('..', '.nii', '') res = splitext_addext('.') - assert_equal(res, ('.', '', '')) + assert res == ('.', '', '') res = splitext_addext('..') - assert_equal(res, ('..', '', '')) + assert res == ('..', '', '') res = splitext_addext('...') - assert_equal(res, ('...', '', '')) + assert res == ('...', '', '') diff --git a/nibabel/tests/test_files_interface.py b/nibabel/tests/test_files_interface.py index 1994741a1a..d3c895618e 100644 --- a/nibabel/tests/test_files_interface.py +++ b/nibabel/tests/test_files_interface.py @@ -17,10 +17,8 @@ from ..fileholders import FileHolderError from ..spatialimages import SpatialImage -from nose.tools import (assert_true, assert_false, assert_equal, assert_raises) - from numpy.testing import assert_array_equal - +import pytest def test_files_spatialimages(): # test files creation in image classes @@ -31,9 +29,9 @@ def test_files_spatialimages(): for klass in klasses: file_map = klass.make_file_map() for key, value in file_map.items(): - assert_equal(value.filename, None) - assert_equal(value.fileobj, None) - assert_equal(value.pos, 0) + assert value.filename 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: continue @@ -44,9 +42,9 @@ def test_files_spatialimages(): else: img = klass(arr, aff) for key, value in img.file_map.items(): - assert_equal(value.filename, None) - assert_equal(value.fileobj, None) - assert_equal(value.pos, 0) + assert value.filename is None + assert value.fileobj is None + assert value.pos == 0 def test_files_interface(): @@ -56,15 +54,16 @@ def test_files_interface(): img = Nifti1Image(arr, aff) # single image img.set_filename('test') - assert_equal(img.get_filename(), 'test.nii') - assert_equal(img.file_map['image'].filename, 'test.nii') - assert_raises(KeyError, img.file_map.__getitem__, 'header') + assert img.get_filename() == 'test.nii' + assert img.file_map['image'].filename == 'test.nii' + with pytest.raises(KeyError): + img.file_map['header'] # pair - note new class img = Nifti1Pair(arr, aff) img.set_filename('test') - assert_equal(img.get_filename(), 'test.img') - assert_equal(img.file_map['image'].filename, 'test.img') - assert_equal(img.file_map['header'].filename, 'test.hdr') + assert img.get_filename() == 'test.img' + assert img.file_map['image'].filename == 'test.img' + assert img.file_map['header'].filename == 'test.hdr' # fileobjs - single image img = Nifti1Image(arr, aff) img.file_map['image'].fileobj = BytesIO() @@ -76,7 +75,8 @@ def test_files_interface(): img = Nifti1Pair(arr, aff) img.file_map['image'].fileobj = BytesIO() # no header yet - assert_raises(FileHolderError, img.to_file_map) + with pytest.raises(FileHolderError): + img.to_file_map() img.file_map['header'].fileobj = BytesIO() img.to_file_map() # saves to files img2 = Nifti1Pair.from_file_map(img.file_map) diff --git a/nibabel/tests/test_fileslice.py b/nibabel/tests/test_fileslice.py index 19735200eb..21b1224d66 100644 --- a/nibabel/tests/test_fileslice.py +++ b/nibabel/tests/test_fileslice.py @@ -1,11 +1,9 @@ """ Test slicing of file-like objects """ -import sys from io import BytesIO from itertools import product from functools import partial -from distutils.version import LooseVersion from threading import Thread, Lock import time @@ -18,10 +16,7 @@ calc_slicedefs, _simple_fileslice, slice2outax, strided_scalar) -from nose.tools import assert_equal -from nose.tools import assert_false -from nose.tools import assert_raises - +import pytest from numpy.testing import assert_array_equal @@ -34,7 +29,7 @@ def _check_slice(sliceobj): # Check if this is a view a[:] = 99 b_is_view = np.all(b == 99) - assert_equal(not is_fancy(sliceobj), b_is_view) + assert (not is_fancy(sliceobj)) == b_is_view def test_is_fancy(): @@ -48,11 +43,11 @@ def test_is_fancy(): if maybe_bad and slice1 is Ellipsis: continue _check_slice((slice0, slice1)) - assert_false(is_fancy((None,))) - assert_false(is_fancy((None, 1))) - assert_false(is_fancy((1, None))) + assert not is_fancy((None,)) + assert not is_fancy((None, 1)) + assert not is_fancy((1, None)) # Chack that actual False returned (rather than falsey) - assert_equal(is_fancy(1), False) + assert is_fancy(1) is False def test_canonical_slicers(): @@ -65,90 +60,83 @@ def test_canonical_slicers(): 2) shape = (10, 10) for slice0 in slicers: - assert_equal(canonical_slicers((slice0,), shape), (slice0, slice(None))) + assert canonical_slicers((slice0,), shape) == (slice0, slice(None)) for slice1 in slicers: sliceobj = (slice0, slice1) - assert_equal(canonical_slicers(sliceobj, shape), sliceobj) - assert_equal(canonical_slicers(sliceobj, shape + (2, 3, 4)), - sliceobj + (slice(None),) * 3) - assert_equal(canonical_slicers(sliceobj * 3, shape * 3), - sliceobj * 3) + assert canonical_slicers(sliceobj, shape) == sliceobj + assert canonical_slicers(sliceobj, shape + (2, 3, 4)) == sliceobj + (slice(None),) * 3 + assert canonical_slicers(sliceobj * 3, shape * 3) == sliceobj * 3 # Check None passes through - assert_equal(canonical_slicers(sliceobj + (None,), shape), - sliceobj + (None,)) - assert_equal(canonical_slicers((None,) + sliceobj, shape), - (None,) + sliceobj) - assert_equal(canonical_slicers((None,) + sliceobj + (None,), shape), - (None,) + sliceobj + (None,)) + assert canonical_slicers(sliceobj + (None,), shape) == sliceobj + (None,) + assert canonical_slicers((None,) + sliceobj, shape) == (None,) + sliceobj + assert (canonical_slicers((None,) + sliceobj + (None,), shape) == + (None,) + sliceobj + (None,)) # Check Ellipsis - assert_equal(canonical_slicers((Ellipsis,), shape), - (slice(None), slice(None))) - assert_equal(canonical_slicers((Ellipsis, None), shape), - (slice(None), slice(None), None)) - assert_equal(canonical_slicers((Ellipsis, 1), shape), - (slice(None), 1)) - assert_equal(canonical_slicers((1, Ellipsis), shape), - (1, slice(None))) + assert canonical_slicers((Ellipsis,), shape) == (slice(None), slice(None)) + assert canonical_slicers((Ellipsis, None), shape) == (slice(None), slice(None), None) + assert canonical_slicers((Ellipsis, 1), shape) == (slice(None), 1) + assert canonical_slicers((1, Ellipsis), shape) == (1, slice(None)) # Ellipsis at end does nothing - assert_equal(canonical_slicers((1, 1, Ellipsis), shape), - (1, 1)) - assert_equal(canonical_slicers((1, Ellipsis, 2), (10, 1, 2, 3, 11)), - (1, slice(None), slice(None), slice(None), 2)) - assert_raises(ValueError, - canonical_slicers, (Ellipsis, 1, Ellipsis), (2, 3, 4, 5)) + assert canonical_slicers((1, 1, Ellipsis), shape) == (1, 1) + assert (canonical_slicers((1, Ellipsis, 2), (10, 1, 2, 3, 11)) == + (1, slice(None), slice(None), slice(None), 2)) + with pytest.raises(ValueError): + canonical_slicers((Ellipsis, 1, Ellipsis), (2, 3, 4, 5)) # Check full slices get expanded for slice0 in (slice(10), slice(0, 10), slice(0, 10, 1)): - assert_equal(canonical_slicers((slice0, 1), shape), - (slice(None), 1)) + assert canonical_slicers((slice0, 1), shape) == (slice(None), 1) for slice0 in (slice(10), slice(0, 10), slice(0, 10, 1)): - assert_equal(canonical_slicers((slice0, 1), shape), - (slice(None), 1)) - assert_equal(canonical_slicers((1, slice0), shape), - (1, slice(None))) + assert canonical_slicers((slice0, 1), shape) == (slice(None), 1) + assert canonical_slicers((1, slice0), shape) == (1, slice(None)) # Check ints etc get parsed through to tuples - assert_equal(canonical_slicers(1, shape), (1, slice(None))) - assert_equal(canonical_slicers(slice(None), shape), - (slice(None), slice(None))) + assert canonical_slicers(1, shape) == (1, slice(None)) + assert canonical_slicers(slice(None), shape) == (slice(None), slice(None)) # Check fancy indexing raises error - assert_raises(ValueError, canonical_slicers, (np.array(1), 1), shape) - assert_raises(ValueError, canonical_slicers, (1, np.array(1)), shape) + with pytest.raises(ValueError): + canonical_slicers((np.array(1), 1), shape) + with pytest.raises(ValueError): + canonical_slicers((1, np.array(1)), shape) # Check out of range integer raises error - assert_raises(ValueError, canonical_slicers, (10,), shape) - assert_raises(ValueError, canonical_slicers, (1, 10), shape) - assert_raises(ValueError, canonical_slicers, (10,), shape, True) - assert_raises(ValueError, canonical_slicers, (1, 10), shape, True) + with pytest.raises(ValueError): + canonical_slicers((10,), shape) + with pytest.raises(ValueError): + canonical_slicers((1, 10), shape) + with pytest.raises(ValueError): + canonical_slicers((10,), shape, True) + with pytest.raises(ValueError): + canonical_slicers((1, 10), shape, True) # Unless check_inds is False - assert_equal(canonical_slicers((10,), shape, False), (10, slice(None))) - assert_equal(canonical_slicers((1, 10,), shape, False), (1, 10)) + assert canonical_slicers((10,), shape, False) == (10, slice(None)) + assert canonical_slicers((1, 10,), shape, False) == (1, 10) # Check negative -> positive - assert_equal(canonical_slicers(-1, shape), (9, slice(None))) - assert_equal(canonical_slicers((slice(None), -1), shape), (slice(None), 9)) + assert canonical_slicers(-1, shape) == (9, slice(None)) + assert canonical_slicers((slice(None), -1), shape) == (slice(None), 9) def test_slice2outax(): # Test function giving output axes from input ndims and slice sn = slice(None) - assert_equal(slice2outax(1, (sn,)), (0,)) - assert_equal(slice2outax(1, (1,)), (None,)) - assert_equal(slice2outax(1, (None,)), (1,)) - assert_equal(slice2outax(1, (None, 1)), (None,)) - assert_equal(slice2outax(1, (None, 1, None)), (None,)) - assert_equal(slice2outax(1, (None, sn)), (1,)) - assert_equal(slice2outax(2, (sn,)), (0, 1)) - assert_equal(slice2outax(2, (sn, sn)), (0, 1)) - assert_equal(slice2outax(2, (1,)), (None, 0)) - assert_equal(slice2outax(2, (sn, 1)), (0, None)) - assert_equal(slice2outax(2, (None,)), (1, 2)) - assert_equal(slice2outax(2, (None, 1)), (None, 1)) - assert_equal(slice2outax(2, (None, 1, None)), (None, 2)) - assert_equal(slice2outax(2, (None, 1, None, 2)), (None, None)) - assert_equal(slice2outax(2, (None, sn, None, 1)), (1, None)) - assert_equal(slice2outax(3, (sn,)), (0, 1, 2)) - assert_equal(slice2outax(3, (sn, sn)), (0, 1, 2)) - assert_equal(slice2outax(3, (sn, None, sn)), (0, 2, 3)) - assert_equal(slice2outax(3, (sn, None, sn, None, sn)), (0, 2, 4)) - assert_equal(slice2outax(3, (1,)), (None, 0, 1)) - assert_equal(slice2outax(3, (None, sn, None, 1)), (1, None, 3)) + assert slice2outax(1, (sn,)) == (0,) + assert slice2outax(1, (1,)) == (None,) + assert slice2outax(1, (None,)) == (1,) + assert slice2outax(1, (None, 1)) == (None,) + assert slice2outax(1, (None, 1, None)) == (None,) + assert slice2outax(1, (None, sn)) == (1,) + assert slice2outax(2, (sn,)) == (0, 1) + assert slice2outax(2, (sn, sn)) == (0, 1) + assert slice2outax(2, (1,)) == (None, 0) + assert slice2outax(2, (sn, 1)) == (0, None) + assert slice2outax(2, (None,)) == (1, 2) + assert slice2outax(2, (None, 1)) == (None, 1) + assert slice2outax(2, (None, 1, None)) == (None, 2) + assert slice2outax(2, (None, 1, None, 2)) == (None, None) + assert slice2outax(2, (None, sn, None, 1)) == (1, None) + assert slice2outax(3, (sn,)) == (0, 1, 2) + assert slice2outax(3, (sn, sn)) == (0, 1, 2) + assert slice2outax(3, (sn, None, sn)) == (0, 2, 3) + assert slice2outax(3, (sn, None, sn, None, sn)) == (0, 2, 4) + assert slice2outax(3, (1,)) == (None, 0, 1) + assert slice2outax(3, (None, sn, None, 1)) == (1, None, 3) def _slices_for_len(L): @@ -174,109 +162,83 @@ def _slices_for_len(L): def test_slice2len(): # Test slice length calculation - assert_equal(slice2len(slice(None), 10), 10) - assert_equal(slice2len(slice(11), 10), 10) - assert_equal(slice2len(slice(1, 11), 10), 9) - assert_equal(slice2len(slice(1, 1), 10), 0) - assert_equal(slice2len(slice(1, 11, 2), 10), 5) - assert_equal(slice2len(slice(0, 11, 3), 10), 4) - assert_equal(slice2len(slice(1, 11, 3), 10), 3) - assert_equal(slice2len(slice(None, None, -1), 10), 10) - assert_equal(slice2len(slice(11, None, -1), 10), 10) - assert_equal(slice2len(slice(None, 1, -1), 10), 8) - assert_equal(slice2len(slice(None, None, -2), 10), 5) - assert_equal(slice2len(slice(None, None, -3), 10), 4) - assert_equal(slice2len(slice(None, 0, -3), 10), 3) + assert slice2len(slice(None), 10) == 10 + assert slice2len(slice(11), 10) == 10 + assert slice2len(slice(1, 11), 10) == 9 + assert slice2len(slice(1, 1), 10) == 0 + assert slice2len(slice(1, 11, 2), 10) == 5 + assert slice2len(slice(0, 11, 3), 10) == 4 + assert slice2len(slice(1, 11, 3), 10) == 3 + assert slice2len(slice(None, None, -1), 10) == 10 + assert slice2len(slice(11, None, -1), 10) == 10 + assert slice2len(slice(None, 1, -1), 10) == 8 + assert slice2len(slice(None, None, -2), 10) == 5 + assert slice2len(slice(None, None, -3), 10) == 4 + assert slice2len(slice(None, 0, -3), 10) == 3 # Start, end are always taken to be relative if negative - assert_equal(slice2len(slice(None, -4, -1), 10), 3) - assert_equal(slice2len(slice(-4, -2, 1), 10), 2) + assert slice2len(slice(None, -4, -1), 10) == 3 + assert slice2len(slice(-4, -2, 1), 10) == 2 # start after stop - assert_equal(slice2len(slice(3, 2, 1), 10), 0) - assert_equal(slice2len(slice(2, 3, -1), 10), 0) + assert slice2len(slice(3, 2, 1), 10) == 0 + assert slice2len(slice(2, 3, -1), 10) == 0 def test_fill_slicer(): # Test slice length calculation - assert_equal(fill_slicer(slice(None), 10), slice(0, 10, 1)) - assert_equal(fill_slicer(slice(11), 10), slice(0, 10, 1)) - assert_equal(fill_slicer(slice(1, 11), 10), slice(1, 10, 1)) - assert_equal(fill_slicer(slice(1, 1), 10), slice(1, 1, 1)) - assert_equal(fill_slicer(slice(1, 11, 2), 10), slice(1, 10, 2)) - assert_equal(fill_slicer(slice(0, 11, 3), 10), slice(0, 10, 3)) - assert_equal(fill_slicer(slice(1, 11, 3), 10), slice(1, 10, 3)) - assert_equal(fill_slicer(slice(None, None, -1), 10), - slice(9, None, -1)) - assert_equal(fill_slicer(slice(11, None, -1), 10), - slice(9, None, -1)) - assert_equal(fill_slicer(slice(None, 1, -1), 10), - slice(9, 1, -1)) - assert_equal(fill_slicer(slice(None, None, -2), 10), - slice(9, None, -2)) - assert_equal(fill_slicer(slice(None, None, -3), 10), - slice(9, None, -3)) - assert_equal(fill_slicer(slice(None, 0, -3), 10), - slice(9, 0, -3)) + assert fill_slicer(slice(None), 10) == slice(0, 10, 1) + assert fill_slicer(slice(11), 10) == slice(0, 10, 1) + assert fill_slicer(slice(1, 11), 10) == slice(1, 10, 1) + assert fill_slicer(slice(1, 1), 10) == slice(1, 1, 1) + assert fill_slicer(slice(1, 11, 2), 10) == slice(1, 10, 2) + assert fill_slicer(slice(0, 11, 3), 10) == slice(0, 10, 3) + assert fill_slicer(slice(1, 11, 3), 10) == slice(1, 10, 3) + assert fill_slicer(slice(None, None, -1), 10) == slice(9, None, -1) + assert fill_slicer(slice(11, None, -1), 10) == slice(9, None, -1) + assert fill_slicer(slice(None, 1, -1), 10) == slice(9, 1, -1) + assert fill_slicer(slice(None, None, -2), 10) == slice(9, None, -2) + assert fill_slicer(slice(None, None, -3), 10) == slice(9, None, -3) + assert fill_slicer(slice(None, 0, -3), 10) == slice(9, 0, -3) # Start, end are always taken to be relative if negative - assert_equal(fill_slicer(slice(None, -4, -1), 10), - slice(9, 6, -1)) - assert_equal(fill_slicer(slice(-4, -2, 1), 10), - slice(6, 8, 1)) + assert fill_slicer(slice(None, -4, -1), 10) == slice(9, 6, -1) + assert fill_slicer(slice(-4, -2, 1), 10) == slice(6, 8, 1) # start after stop - assert_equal(fill_slicer(slice(3, 2, 1), 10), - slice(3, 2, 1)) - assert_equal(fill_slicer(slice(2, 3, -1), 10), - slice(2, 3, -1)) + assert fill_slicer(slice(3, 2, 1), 10) == slice(3, 2, 1) + assert fill_slicer(slice(2, 3, -1), 10) == slice(2, 3, -1) def test__positive_slice(): # Reverse slice direction to be positive - assert_equal(_positive_slice(slice(0, 5, 1)), slice(0, 5, 1)) - assert_equal(_positive_slice(slice(1, 5, 3)), slice(1, 5, 3)) - assert_equal(_positive_slice(slice(4, None, -2)), slice(0, 5, 2)) - assert_equal(_positive_slice(slice(4, None, -1)), slice(0, 5, 1)) - assert_equal(_positive_slice(slice(4, 1, -1)), slice(2, 5, 1)) - assert_equal(_positive_slice(slice(4, 1, -2)), slice(2, 5, 2)) + assert _positive_slice(slice(0, 5, 1)) == slice(0, 5, 1) + assert _positive_slice(slice(1, 5, 3)) == slice(1, 5, 3) + assert _positive_slice(slice(4, None, -2)) == slice(0, 5, 2) + assert _positive_slice(slice(4, None, -1)) == slice(0, 5, 1) + assert _positive_slice(slice(4, 1, -1)) == slice(2, 5, 1) + assert _positive_slice(slice(4, 1, -2)) == slice(2, 5, 2) def test_threshold_heuristic(): # Test for default skip / read heuristic # int - assert_equal(threshold_heuristic(1, 9, 1, skip_thresh=8), 'full') - assert_equal(threshold_heuristic(1, 9, 1, skip_thresh=7), None) - assert_equal(threshold_heuristic(1, 9, 2, skip_thresh=16), 'full') - assert_equal(threshold_heuristic(1, 9, 2, skip_thresh=15), None) + assert threshold_heuristic(1, 9, 1, skip_thresh=8) == 'full' + assert threshold_heuristic(1, 9, 1, skip_thresh=7) is None + assert threshold_heuristic(1, 9, 2, skip_thresh=16) == 'full' + assert threshold_heuristic(1, 9, 2, skip_thresh=15) is None # full slice, smallest step size - assert_equal(threshold_heuristic( - slice(0, 9, 1), 9, 2, skip_thresh=2), - 'full') + assert threshold_heuristic(slice(0, 9, 1), 9, 2, skip_thresh=2) == 'full' # Dropping skip thresh below step size gives None - assert_equal(threshold_heuristic( - slice(0, 9, 1), 9, 2, skip_thresh=1), - None) + assert threshold_heuristic(slice(0, 9, 1), 9, 2, skip_thresh=1) == None # As does increasing step size - assert_equal(threshold_heuristic( - slice(0, 9, 2), 9, 2, skip_thresh=3), - None) + assert threshold_heuristic(slice(0, 9, 2), 9, 2, skip_thresh=3) == None # Negative step size same as positive - assert_equal(threshold_heuristic( - slice(9, None, -1), 9, 2, skip_thresh=2), - 'full') + assert threshold_heuristic(slice(9, None, -1), 9, 2, skip_thresh=2) == 'full' # Add a gap between start and end. Now contiguous because of step size - assert_equal(threshold_heuristic( - slice(2, 9, 1), 9, 2, skip_thresh=2), - 'contiguous') + assert threshold_heuristic(slice(2, 9, 1), 9, 2, skip_thresh=2) == 'contiguous' # To not-contiguous, even with step size 1 - assert_equal(threshold_heuristic( - slice(2, 9, 1), 9, 2, skip_thresh=1), - None) + assert threshold_heuristic(slice(2, 9, 1), 9, 2, skip_thresh=1) == None # Back to full when skip covers gap - assert_equal(threshold_heuristic( - slice(2, 9, 1), 9, 2, skip_thresh=4), - 'full') + assert threshold_heuristic(slice(2, 9, 1), 9, 2, skip_thresh=4) == 'full' # Until it doesn't cover the gap - assert_equal(threshold_heuristic( - slice(2, 9, 1), 9, 2, skip_thresh=3), - 'contiguous') + assert threshold_heuristic(slice(2, 9, 1), 9, 2, skip_thresh=3) == 'contiguous' # Some dummy heuristics for optimize_slicer @@ -307,227 +269,176 @@ def test_optimize_slicer(): for is_slowest in (True, False): # following tests not affected by all_full or optimization # full - always passes through - assert_equal( - optimize_slicer(slice(None), 10, all_full, 4, heuristic), + assert ( + optimize_slicer(slice(None), 10, all_full, is_slowest, 4, heuristic) == (slice(None), slice(None))) # Even if full specified with explicit values - assert_equal( - optimize_slicer(slice(10), 10, all_full, 4, heuristic), + assert ( + optimize_slicer(slice(10), 10, all_full, is_slowest, 4, heuristic) == (slice(None), slice(None))) - assert_equal( - optimize_slicer(slice(0, 10), 10, all_full, 4, heuristic), + assert ( + optimize_slicer(slice(0, 10), 10, all_full, is_slowest, 4, heuristic) == (slice(None), slice(None))) - assert_equal( - optimize_slicer(slice(0, 10, 1), 10, all_full, 4, heuristic), + assert ( + optimize_slicer(slice(0, 10, 1), 10, all_full, is_slowest, 4, heuristic) == (slice(None), slice(None))) # Reversed full is still full, but with reversed post_slice - assert_equal( + assert ( optimize_slicer( - slice(None, None, -1), 10, all_full, 4, heuristic), + slice(None, None, -1), 10, all_full, is_slowest, 4, heuristic) == (slice(None), slice(None, None, -1))) # Contiguous is contiguous unless heuristic kicks in, in which case it may # be 'full' - assert_equal( - optimize_slicer(slice(9), 10, False, False, 4, _always), - (slice(0, 9, 1), slice(None))) - assert_equal( - optimize_slicer(slice(9), 10, True, False, 4, _always), - (slice(None), slice(0, 9, 1))) + assert optimize_slicer(slice(9), 10, False, False, 4, _always) == (slice(0, 9, 1), slice(None)) + assert optimize_slicer(slice(9), 10, True, False, 4, _always) == (slice(None), slice(0, 9, 1)) # Unless this is the slowest dimenion, and all_true is True, in which case # we don't update to full - assert_equal( - optimize_slicer(slice(9), 10, True, True, 4, _always), - (slice(0, 9, 1), slice(None))) + assert optimize_slicer(slice(9), 10, True, True, 4, _always) == (slice(0, 9, 1), slice(None)) # Nor if the heuristic won't update - assert_equal( - optimize_slicer(slice(9), 10, True, False, 4, _never), - (slice(0, 9, 1), slice(None))) - assert_equal( - optimize_slicer(slice(1, 10), 10, True, False, 4, _never), - (slice(1, 10, 1), slice(None))) + assert optimize_slicer(slice(9), 10, True, False, 4, _never) == (slice(0, 9, 1), slice(None)) + assert (optimize_slicer(slice(1, 10), 10, True, False, 4, _never) == + (slice(1, 10, 1), slice(None))) # Reversed contiguous still contiguous - assert_equal( - optimize_slicer(slice(8, None, -1), 10, False, False, 4, _never), - (slice(0, 9, 1), slice(None, None, -1))) - assert_equal( - optimize_slicer(slice(8, None, -1), 10, True, False, 4, _always), - (slice(None), slice(8, None, -1))) - assert_equal( - optimize_slicer(slice(8, None, -1), 10, False, False, 4, _never), - (slice(0, 9, 1), slice(None, None, -1))) - assert_equal( - optimize_slicer(slice(9, 0, -1), 10, False, False, 4, _never), - (slice(1, 10, 1), slice(None, None, -1))) + assert (optimize_slicer(slice(8, None, -1), 10, False, False, 4, _never) == + (slice(0, 9, 1), slice(None, None, -1))) + assert (optimize_slicer(slice(8, None, -1), 10, True, False, 4, _always) == + (slice(None), slice(8, None, -1))) + assert (optimize_slicer(slice(8, None, -1), 10, False, False, 4, _never) == + (slice(0, 9, 1), slice(None, None, -1))) + assert (optimize_slicer(slice(9, 0, -1), 10, False, False, 4, _never) == + (slice(1, 10, 1), slice(None, None, -1))) # Non-contiguous - assert_equal( - optimize_slicer(slice(0, 10, 2), 10, False, False, 4, _never), - (slice(0, 10, 2), slice(None))) + assert (optimize_slicer(slice(0, 10, 2), 10, False, False, 4, _never) == + (slice(0, 10, 2), slice(None))) # all_full triggers optimization, but optimization does nothing - assert_equal( - optimize_slicer(slice(0, 10, 2), 10, True, False, 4, _never), - (slice(0, 10, 2), slice(None))) + assert (optimize_slicer(slice(0, 10, 2), 10, True, False, 4, _never) == + (slice(0, 10, 2), slice(None))) # all_full triggers optimization, optimization does something - assert_equal( - optimize_slicer(slice(0, 10, 2), 10, True, False, 4, _always), - (slice(None), slice(0, 10, 2))) + assert (optimize_slicer(slice(0, 10, 2), 10, True, False, 4, _always) == + (slice(None), slice(0, 10, 2))) # all_full disables optimization, optimization does something - assert_equal( - optimize_slicer(slice(0, 10, 2), 10, False, False, 4, _always), - (slice(0, 10, 2), slice(None))) + assert (optimize_slicer(slice(0, 10, 2), 10, False, False, 4, _always) == + (slice(0, 10, 2), slice(None))) # Non contiguous, reversed - assert_equal( - optimize_slicer(slice(10, None, -2), 10, False, False, 4, _never), - (slice(1, 10, 2), slice(None, None, -1))) - assert_equal( - optimize_slicer(slice(10, None, -2), 10, True, False, 4, _always), - (slice(None), slice(9, None, -2))) + assert (optimize_slicer(slice(10, None, -2), 10, False, False, 4, _never) == + (slice(1, 10, 2), slice(None, None, -1))) + assert (optimize_slicer(slice(10, None, -2), 10, True, False, 4, _always) == + (slice(None), slice(9, None, -2))) # Short non-contiguous - assert_equal( - optimize_slicer(slice(2, 8, 2), 10, False, False, 4, _never), - (slice(2, 8, 2), slice(None))) + assert (optimize_slicer(slice(2, 8, 2), 10, False, False, 4, _never) == + (slice(2, 8, 2), slice(None))) # with partial read - assert_equal( - optimize_slicer(slice(2, 8, 2), 10, True, False, 4, _partial), - (slice(2, 8, 1), slice(None, None, 2))) + assert (optimize_slicer(slice(2, 8, 2), 10, True, False, 4, _partial) == + (slice(2, 8, 1), slice(None, None, 2))) # If this is the slowest changing dimension, heuristic can upgrade None to # contiguous, but not (None, contiguous) to full - assert_equal( # we've done this one already - optimize_slicer(slice(0, 10, 2), 10, True, False, 4, _always), - (slice(None), slice(0, 10, 2))) - assert_equal( # if slowest, just upgrade to contiguous - optimize_slicer(slice(0, 10, 2), 10, True, True, 4, _always), - (slice(0, 10, 1), slice(None, None, 2))) - assert_equal( # contiguous does not upgrade to full - optimize_slicer(slice(9), 10, True, True, 4, _always), - (slice(0, 9, 1), slice(None))) + # we've done this one already + assert (optimize_slicer(slice(0, 10, 2), 10, True, False, 4, _always) == + (slice(None), slice(0, 10, 2))) + # if slowest, just upgrade to contiguous + assert (optimize_slicer(slice(0, 10, 2), 10, True, True, 4, _always) == + (slice(0, 10, 1), slice(None, None, 2))) + # contiguous does not upgrade to full + assert optimize_slicer(slice(9), 10, True, True, 4, _always) == (slice(0, 9, 1), slice(None)) # integer - assert_equal( - optimize_slicer(0, 10, True, False, 4, _never), - (0, 'dropped')) - assert_equal( # can be negative - optimize_slicer(-1, 10, True, False, 4, _never), - (9, 'dropped')) - assert_equal( # or float - optimize_slicer(0.9, 10, True, False, 4, _never), - (0, 'dropped')) - assert_raises(ValueError, # should never get 'contiguous' - optimize_slicer, 0, 10, True, False, 4, _partial) - assert_equal( # full can be forced with heuristic - optimize_slicer(0, 10, True, False, 4, _always), - (slice(None), 0)) - assert_equal( # but disabled for slowest changing dimension - optimize_slicer(0, 10, True, True, 4, _always), - (0, 'dropped')) + assert optimize_slicer(0, 10, True, False, 4, _never) == (0, 'dropped') + # can be negative + assert optimize_slicer(-1, 10, True, False, 4, _never) == (9, 'dropped') + # or float + assert optimize_slicer(0.9, 10, True, False, 4, _never) == (0, 'dropped') + # should never get 'contiguous' + with pytest.raises(ValueError): + optimize_slicer(0, 10, True, False, 4, _partial) + # full can be forced with heuristic + assert optimize_slicer(0, 10, True, False, 4, _always) == (slice(None), 0) + # but disabled for slowest changing dimension + assert optimize_slicer(0, 10, True, True, 4, _always) == (0, 'dropped') def test_optimize_read_slicers(): # Test function to optimize read slicers - assert_equal(optimize_read_slicers((1,), (10,), 4, _never), - ((1,), ())) - assert_equal(optimize_read_slicers((slice(None),), (10,), 4, _never), - ((slice(None),), (slice(None),))) - assert_equal(optimize_read_slicers((slice(9),), (10,), 4, _never), - ((slice(0, 9, 1),), (slice(None),))) + assert optimize_read_slicers((1,), (10,), 4, _never) == ((1,), ()) + assert (optimize_read_slicers((slice(None),), (10,), 4, _never) == + ((slice(None),), (slice(None),))) + assert (optimize_read_slicers((slice(9),), (10,), 4, _never) == + ((slice(0, 9, 1),), (slice(None),))) # optimize cannot update a continuous to a full if last - assert_equal(optimize_read_slicers((slice(9),), (10,), 4, _always), - ((slice(0, 9, 1),), (slice(None),))) + assert (optimize_read_slicers((slice(9),), (10,), 4, _always) == + ((slice(0, 9, 1),), (slice(None),))) # optimize can update non-contiguous to continuous even if last # not optimizing - assert_equal(optimize_read_slicers((slice(0, 9, 2),), (10,), 4, _never), - ((slice(0, 9, 2),), (slice(None),))) + assert (optimize_read_slicers((slice(0, 9, 2),), (10,), 4, _never) == + ((slice(0, 9, 2),), (slice(None),))) # optimizing - assert_equal(optimize_read_slicers((slice(0, 9, 2),), (10,), 4, _always), - ((slice(0, 9, 1),), (slice(None, None, 2),))) + assert (optimize_read_slicers((slice(0, 9, 2),), (10,), 4, _always) == + ((slice(0, 9, 1),), (slice(None, None, 2),))) # Optimize does nothing for integer when last - assert_equal(optimize_read_slicers((1,), (10,), 4, _always), - ((1,), ())) + assert optimize_read_slicers((1,), (10,), 4, _always) == ((1,), ()) # 2D - assert_equal(optimize_read_slicers( - (slice(None), slice(None)), (10, 6), 4, _never), - ((slice(None), slice(None)), (slice(None), slice(None)))) - assert_equal(optimize_read_slicers((slice(None), 1), (10, 6), 4, _never), - ((slice(None), 1), (slice(None),))) - assert_equal(optimize_read_slicers((1, slice(None)), (10, 6), 4, _never), - ((1, slice(None)), (slice(None),))) + assert (optimize_read_slicers((slice(None), slice(None)), (10, 6), 4, _never) == + ((slice(None), slice(None)), (slice(None), slice(None)))) + assert (optimize_read_slicers((slice(None), 1), (10, 6), 4, _never) == + ((slice(None), 1), (slice(None),))) + assert (optimize_read_slicers((1, slice(None)), (10, 6), 4, _never) == + ((1, slice(None)), (slice(None),))) # Not optimizing a partial slice - assert_equal(optimize_read_slicers( - (slice(9), slice(None)), (10, 6), 4, _never), - ((slice(0, 9, 1), slice(None)), (slice(None), slice(None)))) + assert (optimize_read_slicers((slice(9), slice(None)), (10, 6), 4, _never) == + ((slice(0, 9, 1), slice(None)), (slice(None), slice(None)))) # Optimizing a partial slice - assert_equal(optimize_read_slicers( - (slice(9), slice(None)), (10, 6), 4, _always), - ((slice(None), slice(None)), (slice(0, 9, 1), slice(None)))) + assert (optimize_read_slicers((slice(9), slice(None)), (10, 6), 4, _always) == + ((slice(None), slice(None)), (slice(0, 9, 1), slice(None)))) # Optimize cannot update a continuous to a full if last - assert_equal(optimize_read_slicers( - (slice(None), slice(5)), (10, 6), 4, _always), - ((slice(None), slice(0, 5, 1)), (slice(None), slice(None)))) + assert (optimize_read_slicers((slice(None), slice(5)), (10, 6), 4, _always) == + ((slice(None), slice(0, 5, 1)), (slice(None), slice(None)))) # optimize can update non-contiguous to full if not last # not optimizing - assert_equal(optimize_read_slicers( - (slice(0, 9, 3), slice(None)), (10, 6), 4, _never), - ((slice(0, 9, 3), slice(None)), (slice(None), slice(None)))) + assert (optimize_read_slicers((slice(0, 9, 3), slice(None)), (10, 6), 4, _never) == + ((slice(0, 9, 3), slice(None)), (slice(None), slice(None)))) # optimizing full - assert_equal(optimize_read_slicers( - (slice(0, 9, 3), slice(None)), (10, 6), 4, _always), - ((slice(None), slice(None)), (slice(0, 9, 3), slice(None)))) + assert (optimize_read_slicers((slice(0, 9, 3), slice(None)), (10, 6), 4, _always) == + ((slice(None), slice(None)), (slice(0, 9, 3), slice(None)))) # optimizing partial - assert_equal(optimize_read_slicers( - (slice(0, 9, 3), slice(None)), (10, 6), 4, _partial), - ((slice(0, 9, 1), slice(None)), (slice(None, None, 3), slice(None)))) + assert (optimize_read_slicers((slice(0, 9, 3), slice(None)), (10, 6), 4, _partial) == + ((slice(0, 9, 1), slice(None)), (slice(None, None, 3), slice(None)))) # optimize can update non-contiguous to continuous even if last # not optimizing - assert_equal(optimize_read_slicers( - (slice(None), slice(0, 5, 2)), (10, 6), 4, _never), - ((slice(None), slice(0, 5, 2)), (slice(None), slice(None)))) + assert (optimize_read_slicers((slice(None), slice(0, 5, 2)), (10, 6), 4, _never) == + ((slice(None), slice(0, 5, 2)), (slice(None), slice(None)))) # optimizing - assert_equal(optimize_read_slicers( - (slice(None), slice(0, 5, 2),), (10, 6), 4, _always), - ((slice(None), slice(0, 5, 1)), (slice(None), slice(None, None, 2)))) + assert (optimize_read_slicers((slice(None), slice(0, 5, 2),), (10, 6), 4, _always) == + ((slice(None), slice(0, 5, 1)), (slice(None), slice(None, None, 2)))) # Optimize does nothing for integer when last - assert_equal(optimize_read_slicers( - (slice(None), 1), (10, 6), 4, _always), - ((slice(None), 1), (slice(None),))) + assert (optimize_read_slicers((slice(None), 1), (10, 6), 4, _always) == + ((slice(None), 1), (slice(None),))) # Check gap threshold with 3D _depends0 = partial(threshold_heuristic, skip_thresh=10 * 4 - 1) _depends1 = partial(threshold_heuristic, skip_thresh=10 * 4) - assert_equal(optimize_read_slicers( - (slice(9), slice(None), slice(None)), (10, 6, 2), 4, _depends0), - ((slice(None), slice(None), slice(None)), - (slice(0, 9, 1), slice(None), slice(None)))) - assert_equal(optimize_read_slicers( - (slice(None), slice(5), slice(None)), (10, 6, 2), 4, _depends0), - ((slice(None), slice(0, 5, 1), slice(None)), - (slice(None), slice(None), slice(None)))) - assert_equal(optimize_read_slicers( - (slice(None), slice(5), slice(None)), (10, 6, 2), 4, _depends1), - ((slice(None), slice(None), slice(None)), - (slice(None), slice(0, 5, 1), slice(None)))) + assert (optimize_read_slicers( + (slice(9), slice(None), slice(None)), (10, 6, 2), 4, _depends0) == + ((slice(None), slice(None), slice(None)), (slice(0, 9, 1), slice(None), slice(None)))) + assert (optimize_read_slicers( + (slice(None), slice(5), slice(None)), (10, 6, 2), 4, _depends0) == + ((slice(None), slice(0, 5, 1), slice(None)), (slice(None), slice(None), slice(None)))) + assert (optimize_read_slicers( + (slice(None), slice(5), slice(None)), (10, 6, 2), 4, _depends1) == + ((slice(None), slice(None), slice(None)), (slice(None), slice(0, 5, 1), slice(None)))) # Check longs as integer slices sn = slice(None) - assert_equal(optimize_read_slicers( - (1, 2, 3), (2, 3, 4), 4, _always), - ((sn, sn, 3), (1, 2))) + assert optimize_read_slicers((1, 2, 3), (2, 3, 4), 4, _always) == ((sn, sn, 3), (1, 2)) def test_slicers2segments(): # Test function to construct segments from slice objects - assert_equal(slicers2segments((0,), (10,), 7, 4), - [[7, 4]]) - assert_equal(slicers2segments((0, 1), (10, 6), 7, 4), - [[7 + 10 * 4, 4]]) - assert_equal(slicers2segments((0, 1, 2), (10, 6, 4), 7, 4), - [[7 + 10 * 4 + 10 * 6 * 2 * 4, 4]]) - assert_equal(slicers2segments((slice(None),), (10,), 7, 4), - [[7, 10 * 4]]) - assert_equal(slicers2segments((0, slice(None)), (10, 6), 7, 4), - [[7 + 10 * 4 * i, 4] for i in range(6)]) - assert_equal(slicers2segments((slice(None), 0), (10, 6), 7, 4), - [[7, 10 * 4]]) - assert_equal(slicers2segments((slice(None), slice(None)), (10, 6), 7, 4), - [[7, 10 * 6 * 4]]) - assert_equal(slicers2segments( - (slice(None), slice(None), 2), (10, 6, 4), 7, 4), - [[7 + 10 * 6 * 2 * 4, 10 * 6 * 4]]) + assert slicers2segments((0,), (10,), 7, 4) == [[7, 4]] + assert slicers2segments((0, 1), (10, 6), 7, 4) == [[7 + 10 * 4, 4]] + assert slicers2segments((0, 1, 2), (10, 6, 4), 7, 4) == [[7 + 10 * 4 + 10 * 6 * 2 * 4, 4]] + assert slicers2segments((slice(None),), (10,), 7, 4) == [[7, 10 * 4]] + assert (slicers2segments((0, slice(None)), (10, 6), 7, 4) == + [[7 + 10 * 4 * i, 4] for i in range(6)]) + assert slicers2segments((slice(None), 0), (10, 6), 7, 4) == [[7, 10 * 4]] + assert slicers2segments((slice(None), slice(None)), (10, 6), 7, 4) == [[7, 10 * 6 * 4]] + assert (slicers2segments((slice(None), slice(None), 2), (10, 6, 4), 7, 4) == + [[7 + 10 * 6 * 2 * 4, 10 * 6 * 4]]) def test_calc_slicedefs(): @@ -535,71 +446,71 @@ def test_calc_slicedefs(): # wrote them after the code. We live and (fail to) learn segments, out_shape, new_slicing = calc_slicedefs( (1,), (10,), 4, 7, 'F', _never) - assert_equal(segments, [[11, 4]]) - assert_equal(new_slicing, ()) - assert_equal(out_shape, ()) - assert_equal( - calc_slicedefs((slice(None),), (10,), 4, 7, 'F', _never), + assert segments == [[11, 4]] + assert new_slicing == () + assert out_shape == () + assert ( + calc_slicedefs((slice(None),), (10,), 4, 7, 'F', _never) == ([[7, 40]], (10,), (), )) - assert_equal( - calc_slicedefs((slice(9),), (10,), 4, 7, 'F', _never), + assert ( + calc_slicedefs((slice(9),), (10,), 4, 7, 'F', _never) == ([[7, 36]], (9,), (), )) - assert_equal( - calc_slicedefs((slice(1, 9),), (10,), 4, 7, 'F', _never), + assert ( + calc_slicedefs((slice(1, 9),), (10,), 4, 7, 'F', _never) == ([[11, 32]], (8,), (), )) # Two dimensions, single slice - assert_equal( - calc_slicedefs((0,), (10, 6), 4, 7, 'F', _never), + assert ( + calc_slicedefs((0,), (10, 6), 4, 7, 'F', _never) == ([[7, 4], [47, 4], [87, 4], [127, 4], [167, 4], [207, 4]], (6,), (), )) - assert_equal( - calc_slicedefs((0,), (10, 6), 4, 7, 'C', _never), + assert ( + calc_slicedefs((0,), (10, 6), 4, 7, 'C', _never) == ([[7, 6 * 4]], (6,), (), )) # Two dimensions, contiguous not full - assert_equal( - calc_slicedefs((1, slice(1, 5)), (10, 6), 4, 7, 'F', _never), + assert ( + calc_slicedefs((1, slice(1, 5)), (10, 6), 4, 7, 'F', _never) == ([[51, 4], [91, 4], [131, 4], [171, 4]], (4,), (), )) - assert_equal( - calc_slicedefs((1, slice(1, 5)), (10, 6), 4, 7, 'C', _never), + assert ( + calc_slicedefs((1, slice(1, 5)), (10, 6), 4, 7, 'C', _never) == ([[7 + 7 * 4, 16]], (4,), (), )) # With full slice first - assert_equal( - calc_slicedefs((slice(None), slice(1, 5)), (10, 6), 4, 7, 'F', _never), + assert ( + calc_slicedefs((slice(None), slice(1, 5)), (10, 6), 4, 7, 'F', _never) == ([[47, 160]], (10, 4), (), )) # Check effect of heuristic on calc_slicedefs # Even integer slices can generate full when heuristic says so - assert_equal( - calc_slicedefs((1, slice(None)), (10, 6), 4, 7, 'F', _always), + assert ( + calc_slicedefs((1, slice(None)), (10, 6), 4, 7, 'F', _always) == ([[7, 10 * 6 * 4]], (10, 6), (1, slice(None)), )) # Except when last - assert_equal( - calc_slicedefs((slice(None), 1), (10, 6), 4, 7, 'F', _always), + assert ( + calc_slicedefs((slice(None), 1), (10, 6), 4, 7, 'F', _always) == ([[7 + 10 * 4, 10 * 4]], (10,), (), @@ -615,17 +526,16 @@ def test_predict_shape(): for i in range(n_dim): slicers_list.append(_slices_for_len(shape[i])) for sliceobj in product(*slicers_list): - assert_equal(predict_shape(sliceobj, shape), - arr[sliceobj].shape) + assert predict_shape(sliceobj, shape) == arr[sliceobj].shape # Try some Nones and ellipses - assert_equal(predict_shape((Ellipsis,), (2, 3)), (2, 3)) - assert_equal(predict_shape((Ellipsis, 1), (2, 3)), (2,)) - assert_equal(predict_shape((1, Ellipsis), (2, 3)), (3,)) - assert_equal(predict_shape((1, slice(None), Ellipsis), (2, 3)), (3,)) - assert_equal(predict_shape((None,), (2, 3)), (1, 2, 3)) - assert_equal(predict_shape((None, 1), (2, 3)), (1, 3)) - assert_equal(predict_shape((1, None, slice(None)), (2, 3)), (1, 3)) - assert_equal(predict_shape((1, slice(None), None), (2, 3)), (3, 1)) + assert predict_shape((Ellipsis,), (2, 3)) == (2, 3) + assert predict_shape((Ellipsis, 1), (2, 3)) == (2,) + assert predict_shape((1, Ellipsis), (2, 3)) == (3,) + assert predict_shape((1, slice(None), Ellipsis), (2, 3)) == (3,) + assert predict_shape((None,), (2, 3)) == (1, 2, 3) + assert predict_shape((None, 1), (2, 3)) == (1, 3) + assert predict_shape((1, None, slice(None)), (2, 3)) == (1, 3) + assert predict_shape((1, slice(None), None), (2, 3)) == (3, 1) def test_strided_scalar(): @@ -636,18 +546,19 @@ def test_strided_scalar(): expected = np.zeros(shape, dtype=np.array(scalar).dtype) + scalar observed = strided_scalar(shape, scalar) assert_array_equal(observed, expected) - assert_equal(observed.shape, shape) - assert_equal(observed.dtype, expected.dtype) + assert observed.shape == shape + assert observed.dtype == expected.dtype assert_array_equal(observed.strides, 0) # Strided scalars are set as not writeable # This addresses a numpy 1.10 breakage of broadcasting a strided # array without resizing (see GitHub PR #358) - assert_false(observed.flags.writeable) + assert not observed.flags.writeable def setval(x): x[..., 0] = 99 # RuntimeError for numpy < 1.10 - assert_raises((RuntimeError, ValueError), setval, observed) + with pytest.raises((RuntimeError, ValueError)): + setval(observed) # Default scalar value is 0 assert_array_equal(strided_scalar((2, 3, 4)), np.zeros((2, 3, 4))) @@ -670,9 +581,12 @@ def test_read_segments(): np.r_[arr[5:25], arr[50:75]]) _check_bytes(read_segments(fobj, [], 0), arr[0:0]) # Error conditions - assert_raises(ValueError, read_segments, fobj, [], 1) - assert_raises(ValueError, read_segments, fobj, [(0, 200)], 199) - assert_raises(Exception, read_segments, fobj, [(0, 100), (100, 200)], 199) + with pytest.raises(ValueError): + read_segments(fobj, [], 1) + with pytest.raises(ValueError): + read_segments(fobj, [(0, 200)], 199) + with pytest.raises(Exception): + read_segments(fobj, [(0, 100), (100, 200)], 199) def test_read_segments_lock(): @@ -731,10 +645,8 @@ def runtest(): assert numpassed[0] == len(threads) -def _check_slicer(sliceobj, arr, fobj, offset, order, - heuristic=threshold_heuristic): - new_slice = fileslice(fobj, sliceobj, arr.shape, arr.dtype, offset, order, - heuristic) +def _check_slicer(sliceobj, arr, fobj, offset, order, heuristic=threshold_heuristic): + new_slice = fileslice(fobj, sliceobj, arr.shape, arr.dtype, offset, order, heuristic) assert_array_equal(arr[sliceobj], new_slice) @@ -798,8 +710,8 @@ def test_fileslice_errors(): fobj = BytesIO(arr.tostring()) _check_slicer((1,), arr, fobj, 0, 'C') # Fancy indexing raises error - assert_raises(ValueError, - fileslice, fobj, (np.array(1),), (2, 3, 4), arr.dtype) + with pytest.raises(ValueError): + fileslice(fobj, (np.array(1),), (2, 3, 4), arr.dtype) def test_fileslice_heuristic(): diff --git a/nibabel/tests/test_fileutils.py b/nibabel/tests/test_fileutils.py index 63ecc8ee34..ffd7d91b6a 100644 --- a/nibabel/tests/test_fileutils.py +++ b/nibabel/tests/test_fileutils.py @@ -12,12 +12,7 @@ from ..fileutils import read_zt_byte_strings -from numpy.testing import (assert_almost_equal, - assert_array_equal) - -from nose.tools import (assert_true, assert_false, assert_raises, - assert_equal, assert_not_equal) - +import pytest from ..tmpdirs import InTemporaryDirectory @@ -35,22 +30,22 @@ def test_read_zt_byte_strings(): # open it again fread = open(path, 'rb') # test readout of one string - assert_equal(read_zt_byte_strings(fread), [b'test.fmr']) + assert read_zt_byte_strings(fread) == [b'test.fmr'] # test new file position - assert_equal(fread.tell(), 9) + assert fread.tell() == 9 # manually rewind fread.seek(0) # test readout of two strings - assert_equal(read_zt_byte_strings(fread, 2), - [b'test.fmr', b'test.prt']) - assert_equal(fread.tell(), 18) + assert read_zt_byte_strings(fread, 2) == [b'test.fmr', b'test.prt'] + assert fread.tell() == 18 # test readout of more strings than present fread.seek(0) - assert_raises(ValueError, read_zt_byte_strings, fread, 3) + with pytest.raises(ValueError): + read_zt_byte_strings(fread, 3) fread.seek(9) - assert_raises(ValueError, read_zt_byte_strings, fread, 2) + with pytest.raises(ValueError): + read_zt_byte_strings(fread, 2) # Try with a small bufsize fread.seek(0) - assert_equal(read_zt_byte_strings(fread, 2, 4), - [b'test.fmr', b'test.prt']) + assert read_zt_byte_strings(fread, 2, 4) == [b'test.fmr', b'test.prt'] fread.close() diff --git a/nibabel/tests/test_floating.py b/nibabel/tests/test_floating.py index 0c4b5a8cb3..e419eb8868 100644 --- a/nibabel/tests/test_floating.py +++ b/nibabel/tests/test_floating.py @@ -2,7 +2,6 @@ """ import sys -from distutils.version import LooseVersion import numpy as np @@ -12,8 +11,7 @@ longdouble_precision_improved) from ..testing import suppress_warnings -from nose import SkipTest -from nose.tools import assert_equal, assert_raises, assert_true, assert_false +import pytest IEEE_floats = [np.float16, np.float32, np.float64] @@ -35,17 +33,17 @@ def test_type_info(): for dtt in np.sctypes['int'] + np.sctypes['uint']: info = np.iinfo(dtt) infod = type_info(dtt) - assert_equal(dict(min=info.min, max=info.max, - nexp=None, nmant=None, - minexp=None, maxexp=None, - width=np.dtype(dtt).itemsize), infod) - assert_equal(infod['min'].dtype.type, dtt) - assert_equal(infod['max'].dtype.type, dtt) + assert dict(min=info.min, max=info.max, + nexp=None, nmant=None, + minexp=None, maxexp=None, + width=np.dtype(dtt).itemsize) == infod + assert infod['min'].dtype.type == dtt + assert infod['max'].dtype.type == dtt for dtt in IEEE_floats + [np.complex64, np.complex64]: infod = type_info(dtt) - assert_equal(dtt2dict(dtt), infod) - assert_equal(infod['min'].dtype.type, dtt) - assert_equal(infod['max'].dtype.type, dtt) + assert dtt2dict(dtt) == infod + assert infod['min'].dtype.type == dtt + assert infod['max'].dtype.type == dtt # What is longdouble? ld_dict = dtt2dict(np.longdouble) dbl_dict = dtt2dict(np.float64) @@ -70,14 +68,14 @@ def test_type_info(): ld_dict['width'] = width else: raise ValueError("Unexpected float type {} to test".format(np.longdouble)) - assert_equal(ld_dict, infod) + assert ld_dict == infod def test_nmant(): for t in IEEE_floats: - assert_equal(type_info(t)['nmant'], np.finfo(t).nmant) + assert type_info(t)['nmant'] == np.finfo(t).nmant if (LD_INFO['nmant'], LD_INFO['nexp']) == (63, 15): - assert_equal(type_info(np.longdouble)['nmant'], 63) + assert type_info(np.longdouble)['nmant'] == 63 def test_check_nmant_nexp(): @@ -85,35 +83,37 @@ def test_check_nmant_nexp(): for t in IEEE_floats: nmant = np.finfo(t).nmant maxexp = np.finfo(t).maxexp - assert_true(_check_nmant(t, nmant)) - assert_false(_check_nmant(t, nmant - 1)) - assert_false(_check_nmant(t, nmant + 1)) + assert _check_nmant(t, nmant) + assert not _check_nmant(t, nmant - 1) + assert not _check_nmant(t, nmant + 1) with suppress_warnings(): # overflow - assert_true(_check_maxexp(t, maxexp)) - assert_false(_check_maxexp(t, maxexp - 1)) + assert _check_maxexp(t, maxexp) + assert not _check_maxexp(t, maxexp - 1) with suppress_warnings(): - assert_false(_check_maxexp(t, maxexp + 1)) + assert not _check_maxexp(t, maxexp + 1) # Check against type_info for t in ok_floats(): ti = type_info(t) if ti['nmant'] not in (105, 106): # This check does not work for PPC double pair - assert_true(_check_nmant(t, ti['nmant'])) + assert _check_nmant(t, ti['nmant']) # Test fails for longdouble after blacklisting of OSX powl as of numpy # 1.12 - see https://github.com/numpy/numpy/issues/8307 if t != np.longdouble or sys.platform != 'darwin': - assert_true(_check_maxexp(t, ti['maxexp'])) + assert _check_maxexp(t, ti['maxexp']) def test_as_int(): # Integer representation of number - assert_equal(as_int(2.0), 2) - assert_equal(as_int(-2.0), -2) - assert_raises(FloatingError, as_int, 2.1) - assert_raises(FloatingError, as_int, -2.1) - assert_equal(as_int(2.1, False), 2) - assert_equal(as_int(-2.1, False), -2) + assert as_int(2.0) == 2 + assert as_int(-2.0) == -2 + with pytest.raises(FloatingError): + as_int(2.1) + with pytest.raises(FloatingError): + as_int(-2.1) + assert as_int(2.1, False) == 2 + assert as_int(-2.1, False) == -2 v = np.longdouble(2**64) - assert_equal(as_int(v), 2**64) + assert as_int(v) == 2**64 # Have all long doubles got 63+1 binary bits of precision? Windows 32-bit # longdouble appears to have 52 bit precision, but we avoid that by checking # for known precisions that are less than that required @@ -122,13 +122,15 @@ def test_as_int(): except FloatingError: nmant = 63 # Unknown precision, let's hope it's at least 63 v = np.longdouble(2) ** (nmant + 1) - 1 - assert_equal(as_int(v), 2**(nmant + 1) - 1) + assert as_int(v) == 2**(nmant + 1) - 1 # Check for predictable overflow nexp64 = floor_log2(type_info(np.float64)['max']) with np.errstate(over='ignore'): val = np.longdouble(2**nexp64) * 2 # outside float64 range - assert_raises(OverflowError, as_int, val) - assert_raises(OverflowError, as_int, -val) + with pytest.raises(OverflowError): + as_int(val) + with pytest.raises(OverflowError): + as_int(-val) def test_int_to_float(): @@ -138,18 +140,20 @@ def test_int_to_float(): nmant = type_info(ie3)['nmant'] for p in range(nmant + 3): i = 2**p + 1 - assert_equal(int_to_float(i, ie3), ie3(i)) - assert_equal(int_to_float(-i, ie3), ie3(-i)) + assert int_to_float(i, ie3) == ie3(i) + assert int_to_float(-i, ie3) == ie3(-i) # IEEEs in this case are binary formats only nexp = floor_log2(type_info(ie3)['max']) # Values too large for the format smn, smx = -2**(nexp + 1), 2**(nexp + 1) if ie3 is np.float64: - assert_raises(OverflowError, int_to_float, smn, ie3) - assert_raises(OverflowError, int_to_float, smx, ie3) + with pytest.raises(OverflowError): + int_to_float(smn, ie3) + with pytest.raises(OverflowError): + int_to_float(smx, ie3) else: - assert_equal(int_to_float(smn, ie3), ie3(smn)) - assert_equal(int_to_float(smx, ie3), ie3(smx)) + assert int_to_float(smn, ie3) == ie3(smn) + assert int_to_float(smx, ie3) == ie3(smx) # Longdoubles do better than int, we hope LD = np.longdouble # up to integer precision of float64 nmant, we get the same result as for @@ -157,29 +161,31 @@ def test_int_to_float(): nmant = type_info(np.float64)['nmant'] for p in range(nmant + 2): # implicit i = 2**p - 1 - assert_equal(int_to_float(i, LD), LD(i)) - assert_equal(int_to_float(-i, LD), LD(-i)) + assert int_to_float(i, LD) == LD(i) + assert int_to_float(-i, LD) == LD(-i) # Above max of float64, we're hosed nexp64 = floor_log2(type_info(np.float64)['max']) smn64, smx64 = -2**(nexp64 + 1), 2**(nexp64 + 1) # The algorithm here implemented goes through float64, so supermax and # supermin will cause overflow errors - assert_raises(OverflowError, int_to_float, smn64, LD) - assert_raises(OverflowError, int_to_float, smx64, LD) + with pytest.raises(OverflowError): + int_to_float(smn64, LD) + with pytest.raises(OverflowError): + int_to_float(smx64, LD) try: nmant = type_info(np.longdouble)['nmant'] except FloatingError: # don't know where to test return # test we recover precision just above nmant i = 2**(nmant + 1) - 1 - assert_equal(as_int(int_to_float(i, LD)), i) - assert_equal(as_int(int_to_float(-i, LD)), -i) + assert as_int(int_to_float(i, LD)) == i + assert as_int(int_to_float(-i, LD)) == -i # If longdouble can cope with 2**64, test if nmant >= 63: # Check conversion to int; the line below causes an error subtracting # ints / uint64 values, at least for Python 3.3 and numpy dev 1.8 big_int = np.uint64(2**64 - 1) - assert_equal(as_int(int_to_float(big_int, LD)), big_int) + assert as_int(int_to_float(big_int, LD)) == big_int def test_as_int_np_fix(): @@ -188,13 +194,13 @@ def test_as_int_np_fix(): for t in np.sctypes['int'] + np.sctypes['uint']: info = np.iinfo(t) mn, mx = np.array([info.min, info.max], dtype=t) - assert_equal((mn, mx), (as_int(mn), as_int(mx))) + assert (mn, mx) == (as_int(mn), as_int(mx)) def test_floor_exact_16(): # A normal integer can generate an inf in float16 - assert_equal(floor_exact(2**31, np.float16), np.inf) - assert_equal(floor_exact(-2**31, np.float16), -np.inf) + assert floor_exact(2**31, np.float16) == np.inf + assert floor_exact(-2**31, np.float16) == -np.inf def test_floor_exact_64(): @@ -203,11 +209,11 @@ def test_floor_exact_64(): start = np.float64(2**e) across = start + np.arange(2048, dtype=np.float64) gaps = set(np.diff(across)).difference([0]) - assert_equal(len(gaps), 1) + assert len(gaps) == 1 gap = gaps.pop() - assert_equal(gap, int(gap)) + assert gap == int(gap) test_val = 2**(e + 1) - 1 - assert_equal(floor_exact(test_val, np.float64), 2**(e + 1) - int(gap)) + assert floor_exact(test_val, np.float64) == 2**(e + 1) - int(gap) def test_floor_exact(): @@ -226,21 +232,21 @@ def test_floor_exact(): for t in to_test: # A number bigger than the range returns the max info = type_info(t) - assert_equal(floor_exact(2**5000, t), np.inf) - assert_equal(ceil_exact(2**5000, t), np.inf) + assert floor_exact(2**5000, t) == np.inf + assert ceil_exact(2**5000, t) == np.inf # A number more negative returns -inf - assert_equal(floor_exact(-2**5000, t), -np.inf) - assert_equal(ceil_exact(-2**5000, t), -np.inf) + assert floor_exact(-2**5000, t) == -np.inf + assert ceil_exact(-2**5000, t) == -np.inf # Check around end of integer precision nmant = info['nmant'] for i in range(nmant + 1): iv = 2**i # up to 2**nmant should be exactly representable for func in (int_flex, int_ceex): - assert_equal(func(iv, t), iv) - assert_equal(func(-iv, t), -iv) - assert_equal(func(iv - 1, t), iv - 1) - assert_equal(func(-iv + 1, t), -iv + 1) + assert func(iv, t) == iv + assert func(-iv, t) == -iv + assert func(iv - 1, t) == iv - 1 + assert func(-iv + 1, t) == -iv + 1 if t is np.longdouble and ( on_powerpc() or longdouble_precision_improved()): @@ -251,28 +257,28 @@ def test_floor_exact(): continue # Confirm to ourselves that 2**(nmant+1) can't be exactly represented iv = 2**(nmant + 1) - assert_equal(int_flex(iv + 1, t), iv) - assert_equal(int_ceex(iv + 1, t), iv + 2) + assert int_flex(iv + 1, t) == iv + assert int_ceex(iv + 1, t) == iv + 2 # negatives - assert_equal(int_flex(-iv - 1, t), -iv - 2) - assert_equal(int_ceex(-iv - 1, t), -iv) + assert int_flex(-iv - 1, t) == -iv - 2 + assert int_ceex(-iv - 1, t) == -iv # The gap in representable numbers is 2 above 2**(nmant+1), 4 above # 2**(nmant+2), and so on. for i in range(5): iv = 2**(nmant + 1 + i) gap = 2**(i + 1) - assert_equal(as_int(t(iv) + t(gap)), iv + gap) + assert as_int(t(iv) + t(gap)) == iv + gap for j in range(1, gap): - assert_equal(int_flex(iv + j, t), iv) - assert_equal(int_flex(iv + gap + j, t), iv + gap) - assert_equal(int_ceex(iv + j, t), iv + gap) - assert_equal(int_ceex(iv + gap + j, t), iv + 2 * gap) + assert int_flex(iv + j, t) == iv + assert int_flex(iv + gap + j, t) == iv + gap + assert int_ceex(iv + j, t) == iv + gap + assert int_ceex(iv + gap + j, t) == iv + 2 * gap # negatives for j in range(1, gap): - assert_equal(int_flex(-iv - j, t), -iv - gap) - assert_equal(int_flex(-iv - gap - j, t), -iv - 2 * gap) - assert_equal(int_ceex(-iv - j, t), -iv) - assert_equal(int_ceex(-iv - gap - j, t), -iv - gap) + assert int_flex(-iv - j, t) == -iv - gap + assert int_flex(-iv - gap - j, t) == -iv - 2 * gap + assert int_ceex(-iv - j, t) == -iv + assert int_ceex(-iv - gap - j, t) == -iv - gap def test_usable_binary128(): @@ -280,7 +286,6 @@ def test_usable_binary128(): yes = have_binary128() with np.errstate(over='ignore'): exp_test = np.longdouble(2) ** 16383 - assert_equal(yes, - exp_test.dtype.itemsize == 16 and - np.isfinite(exp_test) and - _check_nmant(np.longdouble, 112)) + assert yes == (exp_test.dtype.itemsize == 16 and + np.isfinite(exp_test) and + _check_nmant(np.longdouble, 112)) diff --git a/nibabel/tests/test_funcs.py b/nibabel/tests/test_funcs.py index 447555d6d0..db196995e0 100644 --- a/nibabel/tests/test_funcs.py +++ b/nibabel/tests/test_funcs.py @@ -18,7 +18,7 @@ from ..tmpdirs import InTemporaryDirectory from numpy.testing import assert_array_equal -from nose.tools import (assert_true, assert_false, assert_equal, assert_raises) +import pytest _counter = 0 @@ -33,7 +33,8 @@ def _as_fname(img): def test_concat(): # Smoke test: concat empty list. - assert_raises(ValueError, concat_images, []) + with pytest.raises(ValueError): + concat_images([]) # Build combinations of 3D, 4D w/size[3] == 1, and 4D w/size[3] == 3 all_shapes_5D = ((1, 4, 5, 3, 3), @@ -104,25 +105,23 @@ def test_concat(): all_imgs = concat_images([img0, img1], **concat_imgs_kwargs) except ValueError as ve: - assert_true(expect_error, str(ve)) + assert expect_error, str(ve) else: - assert_false( - expect_error, "Expected a concatenation error, but got none.") + assert not expect_error, "Expected a concatenation error, but got none." assert_array_equal(all_imgs.get_fdata(), all_data) assert_array_equal(all_imgs.affine, affine) # check that not-matching affines raise error - assert_raises(ValueError, concat_images, [ - img0, img2], **concat_imgs_kwargs) + with pytest.raises(ValueError): + concat_images([img0, img2], **concat_imgs_kwargs) # except if check_affines is False try: all_imgs = concat_images([img0, img1], **concat_imgs_kwargs) except ValueError as ve: - assert_true(expect_error, str(ve)) + assert expect_error, str(ve) else: - assert_false( - expect_error, "Expected a concatenation error, but got none.") + assert not expect_error, "Expected a concatenation error, but got none." assert_array_equal(all_imgs.get_fdata(), all_data) assert_array_equal(all_imgs.affine, affine) @@ -134,12 +133,12 @@ def test_closest_canonical(): # Test with an AnalyzeImage first img = AnalyzeImage(arr, np.eye(4)) xyz_img = as_closest_canonical(img) - assert_true(img is xyz_img) + assert img is xyz_img # And a case where the Analyze image has to be flipped img = AnalyzeImage(arr, np.diag([-1, 1, 1, 1])) xyz_img = as_closest_canonical(img) - assert_false(img is xyz_img) + assert img is not xyz_img out_arr = xyz_img.get_fdata() assert_array_equal(out_arr, np.flipud(arr)) @@ -151,14 +150,14 @@ def test_closest_canonical(): # re-order them properly img.header.set_dim_info(0, 1, 2) xyz_img = as_closest_canonical(img) - assert_true(img is xyz_img) + assert img is xyz_img # a axis flip img = Nifti1Image(arr, np.diag([-1, 1, 1, 1])) img.header.set_dim_info(0, 1, 2) xyz_img = as_closest_canonical(img) - assert_false(img is xyz_img) - assert_true(img.header.get_dim_info() == xyz_img.header.get_dim_info()) + assert 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)) @@ -170,9 +169,10 @@ def test_closest_canonical(): # although it's more or less canonical already img = Nifti1Image(arr, aff) xyz_img = as_closest_canonical(img) - assert_true(img is xyz_img) + assert img is xyz_img # it's still not diagnonal - assert_raises(OrientationError, as_closest_canonical, img, True) + with pytest.raises(OrientationError): + as_closest_canonical(img, True) # an axis swap aff = np.diag([1, 0, 0, 1]) @@ -181,14 +181,14 @@ def test_closest_canonical(): img.header.set_dim_info(0, 1, 2) xyz_img = as_closest_canonical(img) - assert_false(img is xyz_img) + assert img is not xyz_img # Check both the original and new objects - assert_true(img.header.get_dim_info() == (0, 1, 2)) - assert_true(xyz_img.header.get_dim_info() == (0, 2, 1)) + assert img.header.get_dim_info() == (0, 1, 2) + assert xyz_img.header.get_dim_info() == (0, 2, 1) out_arr = xyz_img.get_fdata() assert_array_equal(out_arr, np.transpose(arr, (0, 2, 1, 3))) # same axis swap but with None dim info (except for slice dim) img.header.set_dim_info(None, None, 2) xyz_img = as_closest_canonical(img) - assert_true(xyz_img.header.get_dim_info() == (None, None, 1)) + assert xyz_img.header.get_dim_info() == (None, None, 1) diff --git a/nibabel/tests/test_h5py_compat.py b/nibabel/tests/test_h5py_compat.py index af5c50989c..325645a18c 100644 --- a/nibabel/tests/test_h5py_compat.py +++ b/nibabel/tests/test_h5py_compat.py @@ -10,7 +10,6 @@ from ..optpkg import optional_package from .. import _h5py_compat as compat -from ..testing import assert_equal, assert_true, assert_false, assert_not_equal h5py, have_h5py, _ = optional_package('h5py') @@ -18,30 +17,30 @@ def test_optpkg_equivalence(): # No effect on Linux/OSX if os.name == 'posix': - assert_equal(have_h5py, compat.have_h5py) + assert have_h5py == compat.have_h5py # No effect on Python 2.7 or 3.6+ if sys.version_info >= (3, 6) or sys.version_info < (3,): - assert_equal(have_h5py, compat.have_h5py) + assert have_h5py == compat.have_h5py # Available in a strict subset of cases if not have_h5py: - assert_false(compat.have_h5py) + assert not compat.have_h5py # Available when version is high enough elif LooseVersion(h5py.__version__) >= '2.10': - assert_true(compat.have_h5py) + assert compat.have_h5py def test_disabled_h5py_cases(): # On mismatch if have_h5py and not compat.have_h5py: # Recapitulate min_h5py conditions from _h5py_compat - assert_equal(os.name, 'nt') - assert_true((3,) <= sys.version_info < (3, 6)) - assert_true(LooseVersion(h5py.__version__) < '2.10') + assert os.name == 'nt' + assert (3,) <= sys.version_info < (3, 6) + assert LooseVersion(h5py.__version__) < '2.10' # Verify that the root cause is present # If any tests fail, they will likely be these, so they may be # ill-advised... if LooseVersion(np.__version__) < '1.18': - assert_equal(str(np.longdouble), str(np.float64)) + assert str(np.longdouble) == str(np.float64) else: - assert_not_equal(str(np.longdouble), str(np.float64)) - assert_not_equal(np.longdouble, np.float64) + assert str(np.longdouble) != str(np.float64) + assert np.longdouble != np.float64 diff --git a/nibabel/tests/test_image_api.py b/nibabel/tests/test_image_api.py index f91b61af9e..8af303914b 100644 --- a/nibabel/tests/test_image_api.py +++ b/nibabel/tests/test_image_api.py @@ -41,17 +41,16 @@ from ..spatialimages import SpatialImage from .. import minc1, minc2, parrec, brikhead -from nose import SkipTest -from nose.tools import (assert_true, assert_false, assert_raises, assert_equal) +import unittest +import pytest from numpy.testing import assert_almost_equal, assert_array_equal, assert_warns, assert_allclose -from ..testing import clear_and_catch_warnings +from ..testing import (bytesio_round_trip, bytesio_filemap, + assert_data_similar, clear_and_catch_warnings) from ..tmpdirs import InTemporaryDirectory from ..deprecator import ExpiredDeprecationError from .test_api_validators import ValidateAPI -from .test_helpers import (bytesio_round_trip, bytesio_filemap, - assert_data_similar) from .test_minc1 import EXAMPLE_IMAGES as MINC1_EXAMPLE_IMAGES from .test_minc2 import EXAMPLE_IMAGES as MINC2_EXAMPLE_IMAGES from .test_parrec import EXAMPLE_IMAGES as PARREC_EXAMPLE_IMAGES @@ -109,21 +108,21 @@ def validate_header(self, imaker, params): img = imaker() hdr = img.header # we can fetch it # Read only - assert_raises(AttributeError, setattr, img, 'header', hdr) + with pytest.raises(AttributeError): + img.header = hdr 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_equal(len(w), 1) - assert_true(hdr is img.header) + assert hdr is img.header def validate_filenames(self, imaker, params): # Validate the filename, file_map interface + if not self.can_save: - raise SkipTest + raise unittest.SkipTest img = imaker() img.set_data_dtype(np.float32) # to avoid rounding in load / save # Make sure the object does not have a file_map @@ -145,8 +144,8 @@ def validate_filenames(self, imaker, params): fname = 'an_image' + self.standard_extension for path in (fname, pathlib.Path(fname)): img.set_filename(path) - assert_equal(img.get_filename(), str(path)) - assert_equal(img.file_map['image'].filename, str(path)) + assert img.get_filename() == str(path) + assert img.file_map['image'].filename == str(path) # to_ / from_ filename fname = 'another_image' + self.standard_extension for path in (fname, pathlib.Path(fname)): @@ -163,13 +162,15 @@ def validate_filenames(self, imaker, params): def validate_no_slicing(self, imaker, params): img = imaker() - assert_raises(TypeError, img.__getitem__, 'string') - assert_raises(TypeError, img.__getitem__, slice(None)) + with pytest.raises(TypeError): + img['string'] + with pytest.raises(TypeError): + img[:] 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) @@ -184,19 +185,19 @@ def validate_dtype(self, imaker, params): # data / storage dtype img = imaker() # Need to rename this one - assert_equal(img.get_data_dtype().type, params['dtype']) + assert img.get_data_dtype().type == params['dtype'] # dtype survives round trip if self.has_scaling and self.can_save: with np.errstate(invalid='ignore'): rt_img = bytesio_round_trip(img) - assert_equal(rt_img.get_data_dtype().type, params['dtype']) + assert rt_img.get_data_dtype().type == params['dtype'] # Setting to a different dtype img.set_data_dtype(np.float32) # assumed supported for all formats - assert_equal(img.get_data_dtype().type, np.float32) + assert img.get_data_dtype().type == np.float32 # dtype survives round trip if self.can_save: rt_img = bytesio_round_trip(img) - assert_equal(rt_img.get_data_dtype().type, np.float32) + assert rt_img.get_data_dtype().type == np.float32 class DataInterfaceMixin(GetSetDtypeMixin): @@ -210,8 +211,8 @@ class DataInterfaceMixin(GetSetDtypeMixin): def validate_data_interface(self, imaker, params): # Check get data returns array, and caches img = imaker() - assert_equal(img.shape, img.dataobj.shape) - assert_equal(img.ndim, len(img.shape)) + assert img.shape == img.dataobj.shape + assert img.ndim == len(img.shape) assert_data_similar(img.dataobj, params) for meth_name in self.meth_names: if params['is_proxy']: @@ -219,53 +220,56 @@ def validate_data_interface(self, imaker, params): else: # Array image self._check_array_interface(imaker, meth_name) # Data shape is same as image shape - assert_equal(img.shape, getattr(img, meth_name)().shape) + assert img.shape == getattr(img, meth_name)().shape # Data ndim is same as image ndim - assert_equal(img.ndim, getattr(img, meth_name)().ndim) + assert img.ndim == getattr(img, meth_name)().ndim # Values to get_data caching parameter must be 'fill' or # 'unchanged' - assert_raises(ValueError, img.get_data, caching='something') + with pytest.raises(ValueError): + img.get_data(caching='something') # dataobj is read only fake_data = np.zeros(img.shape).astype(img.get_data_dtype()) - assert_raises(AttributeError, setattr, img, 'dataobj', fake_data) + with pytest.raises(AttributeError): + img.dataobj = fake_data # So is in_memory - assert_raises(AttributeError, setattr, img, 'in_memory', False) + with pytest.raises(AttributeError): + img.in_memory = False def _check_proxy_interface(self, imaker, meth_name): # Parameters assert this is an array proxy img = imaker() # Does is_proxy agree? - assert_true(is_proxy(img.dataobj)) + assert is_proxy(img.dataobj) # Confirm it is not a numpy array - assert_false(isinstance(img.dataobj, np.ndarray)) + assert not isinstance(img.dataobj, np.ndarray) # Confirm it can be converted to a numpy array with asarray proxy_data = np.asarray(img.dataobj) proxy_copy = proxy_data.copy() # Not yet cached, proxy image: in_memory is False - assert_false(img.in_memory) + assert not img.in_memory # Load with caching='unchanged' method = getattr(img, meth_name) data = method(caching='unchanged') # Still not cached - assert_false(img.in_memory) + assert not img.in_memory # Default load, does caching data = method() # Data now cached. in_memory is True if either of the get_data # or get_fdata caches are not-None - assert_true(img.in_memory) + assert img.in_memory # We previously got proxy_data from disk, but data, which we # have just fetched, is a fresh copy. - assert_false(proxy_data is data) + assert not proxy_data is data # asarray on dataobj, applied above, returns same numerical # values. This might not be true get_fdata operating on huge # integers, but lets assume that's not true here. assert_array_equal(proxy_data, data) # Now caching='unchanged' does nothing, returns cached version data_again = method(caching='unchanged') - assert_true(data is data_again) + assert data is data_again # caching='fill' does nothing because the cache is already full data_yet_again = method(caching='fill') - assert_true(data is data_yet_again) + assert data is data_yet_again # changing array data does not change proxy data, or reloaded # data data[:] = 42 @@ -276,16 +280,16 @@ def _check_proxy_interface(self, imaker, meth_name): # until we uncache img.uncache() # Which unsets in_memory - assert_false(img.in_memory) + assert not img.in_memory assert_array_equal(method(), proxy_copy) # Check caching='fill' does cache data img = imaker() method = getattr(img, meth_name) - assert_false(img.in_memory) + assert not img.in_memory data = method(caching='fill') - assert_true(img.in_memory) + assert img.in_memory data_again = method() - assert_true(data is data_again) + assert data is data_again # Check the interaction of caching with get_data, get_fdata. # Caching for `get_data` should have no effect on caching for # get_fdata, and vice versa. @@ -297,21 +301,21 @@ def _check_proxy_interface(self, imaker, meth_name): other_data = other_method() # We get the original data, not the modified cache assert_array_equal(proxy_data, other_data) - assert_false(np.all(data == other_data)) + assert not np.all(data == other_data) # We can modify the other cache, without affecting the first other_data[:] = 44 assert_array_equal(other_method(), 44) - assert_false(np.all(method() == other_method())) + assert not np.all(method() == other_method()) if meth_name != 'get_fdata': return # Check that caching refreshes for new floating point type. img.uncache() fdata = img.get_fdata() - assert_equal(fdata.dtype, np.float64) + assert fdata.dtype == np.float64 fdata[:] = 42 fdata_back = img.get_fdata() assert_array_equal(fdata_back, 42) - assert_equal(fdata_back.dtype, np.float64) + assert fdata_back.dtype == np.float64 # New data dtype, no caching, doesn't use or alter cache fdata_new_dt = img.get_fdata(caching='unchanged', dtype='f4') # We get back the original read, not the modified cache @@ -319,7 +323,7 @@ def _check_proxy_interface(self, imaker, meth_name): # factors, rather than 64-bit factors and then cast to float-32 # Use rtol/atol from numpy.allclose assert_allclose(fdata_new_dt, proxy_data.astype('f4'), rtol=1e-05, atol=1e-08) - assert_equal(fdata_new_dt.dtype, np.float32) + assert fdata_new_dt.dtype == np.float32 # The original cache stays in place, for default float64 assert_array_equal(img.get_fdata(), 42) # And for not-default float32, because we haven't cached @@ -345,8 +349,8 @@ def _check_array_caching(self, imaker, meth_name, caching): method = getattr(img, meth_name) get_data_func = (method if caching is None else partial(method, caching=caching)) - assert_true(isinstance(img.dataobj, np.ndarray)) - assert_true(img.in_memory) + assert isinstance(img.dataobj, np.ndarray) + assert img.in_memory data = get_data_func() # Returned data same object as underlying dataobj if using # old ``get_data`` method, or using newer ``get_fdata`` @@ -356,10 +360,10 @@ def _check_array_caching(self, imaker, meth_name, caching): # Set something to the output array. data[:] = 42 get_result_changed = np.all(get_data_func() == 42) - assert_equal(get_result_changed, - dataobj_is_data or caching != 'unchanged') + assert (get_result_changed == + (dataobj_is_data or caching != 'unchanged')) if dataobj_is_data: - assert_true(data is img.dataobj) + assert data is img.dataobj # Changing array data changes # data assert_array_equal(np.asarray(img.dataobj), 42) @@ -367,15 +371,15 @@ def _check_array_caching(self, imaker, meth_name, caching): img.uncache() assert_array_equal(get_data_func(), 42) else: - assert_false(data is img.dataobj) - assert_false(np.all(np.asarray(img.dataobj) == 42)) + assert not data is img.dataobj + assert not np.all(np.asarray(img.dataobj) == 42) # Uncache does have an effect img.uncache() - assert_false(np.all(get_data_func() == 42)) + assert not np.all(get_data_func() == 42) # in_memory is always true for array images, regardless of # cache state. img.uncache() - assert_true(img.in_memory) + assert img.in_memory if meth_name != 'get_fdata': return # Return original array from get_fdata only if the input array is the @@ -385,45 +389,46 @@ def _check_array_caching(self, imaker, meth_name, caching): return for float_type in float_types: data = get_data_func(dtype=float_type) - assert_equal(data is img.dataobj, arr_dtype == float_type) + assert (data is img.dataobj) == (arr_dtype == float_type) def validate_data_deprecated(self, imaker, params): # Check _data property still exists, but raises warning img = imaker() - with warnings.catch_warnings(record=True) as warns: - warnings.simplefilter("always") + with pytest.deprecated_call(): assert_data_similar(img._data, params) - assert_equal(warns.pop(0).category, DeprecationWarning) # Check setting _data raises error fake_data = np.zeros(img.shape).astype(img.get_data_dtype()) - assert_raises(AttributeError, setattr, img, '_data', fake_data) + with pytest.raises(AttributeError): + img._data = fake_data def validate_shape(self, imaker, params): # Validate shape img = imaker() # Same as expected shape - assert_equal(img.shape, params['shape']) + assert img.shape == params['shape'] # Same as array shape if passed if 'data' in params: - assert_equal(img.shape, params['data'].shape) + assert img.shape == params['data'].shape # Read only - assert_raises(AttributeError, setattr, img, 'shape', np.eye(4)) + with pytest.raises(AttributeError): + img.shape = np.eye(4) def validate_ndim(self, imaker, params): # Validate shape img = imaker() # Same as expected ndim - assert_equal(img.ndim, len(params['shape'])) + assert img.ndim == len(params['shape']) # Same as array ndim if passed if 'data' in params: - assert_equal(img.ndim, params['data'].ndim) + assert img.ndim == params['data'].ndim # Read only - assert_raises(AttributeError, setattr, img, 'ndim', 5) + with pytest.raises(AttributeError): + img.ndim = 5 def validate_shape_deprecated(self, imaker, params): # Check deprecated get_shape API img = imaker() - with assert_raises(ExpiredDeprecationError): + with pytest.raises(ExpiredDeprecationError): img.get_shape() def validate_mmap_parameter(self, imaker, params): @@ -448,10 +453,10 @@ def validate_mmap_parameter(self, imaker, params): rt_img = img.__class__.from_filename(fname, mmap='r') assert_almost_equal(img.get_fdata(), rt_img.get_fdata()) # r+ is specifically not valid for images - assert_raises(ValueError, - img.__class__.from_filename, fname, mmap='r+') - assert_raises(ValueError, - img.__class__.from_filename, fname, mmap='invalid') + with pytest.raises(ValueError): + img.__class__.from_filename(fname, mmap='r+') + with pytest.raises(ValueError): + img.__class__.from_filename(fname, mmap='invalid') del rt_img # to allow windows to delete the directory @@ -469,8 +474,8 @@ def validate_header_shape(self, imaker, params): shape = hdr.get_data_shape() new_shape = (shape[0] + 1,) + shape[1:] hdr.set_data_shape(new_shape) - assert_true(img.header is hdr) - assert_equal(img.header.get_data_shape(), new_shape) + assert img.header is hdr + assert img.header.get_data_shape() == new_shape class AffineMixin(object): @@ -484,23 +489,22 @@ def validate_affine(self, imaker, params): # Check affine API img = imaker() assert_almost_equal(img.affine, params['affine'], 6) - assert_equal(img.affine.dtype, np.float64) + assert img.affine.dtype == np.float64 img.affine[0, 0] = 1.5 - assert_equal(img.affine[0, 0], 1.5) + assert img.affine[0, 0] == 1.5 # Read only - assert_raises(AttributeError, setattr, img, 'affine', np.eye(4)) + with pytest.raises(AttributeError): + img.affine = np.eye(4) 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_equal(len(w), 1) - assert_equal(img.get_affine().dtype, np.float64) + assert img.get_affine().dtype == np.float64 aff = img.get_affine() aff[0, 0] = 1.5 - assert_true(aff is img.get_affine()) + assert aff is img.get_affine() class SerializeMixin(object): @@ -584,7 +588,7 @@ def obj_params(self): def validate_path_maybe_image(self, imaker, params): for img_params in self.example_images: test, sniff = self.klass.path_maybe_image(img_params['fname']) - assert_true(isinstance(test, bool)) + assert isinstance(test, bool) if sniff is not None: assert isinstance(sniff[0], bytes) assert isinstance(sniff[1], str) @@ -707,7 +711,7 @@ class TestMinc2API(TestMinc1API): def __init__(self): if not have_h5py: - raise SkipTest('Need h5py for these tests') + raise unittest.SkipTest('Need h5py for these tests') klass = image_maker = Minc2Image loader = minc2.load diff --git a/nibabel/tests/test_image_load_save.py b/nibabel/tests/test_image_load_save.py index 9d58a3ed60..429144108c 100644 --- a/nibabel/tests/test_image_load_save.py +++ b/nibabel/tests/test_image_load_save.py @@ -30,7 +30,7 @@ from ..spatialimages import SpatialImage from numpy.testing import assert_array_equal, assert_array_almost_equal -from nose.tools import assert_true, assert_equal, assert_not_equal, assert_raises +import pytest _, have_scipy, _ = optional_package('scipy') # No scipy=>no SPM-format writing DATA_PATH = pjoin(dirname(__file__), 'data') @@ -68,15 +68,15 @@ def test_save_load_endian(): data = np.arange(np.prod(shape), dtype='f4').reshape(shape) # Native endian image img = Nifti1Image(data, affine) - assert_equal(img.header.endianness, native_code) + assert img.header.endianness == native_code img2 = round_trip(img) - assert_equal(img2.header.endianness, native_code) + assert img2.header.endianness == native_code assert_array_equal(img2.get_fdata(), data) assert_array_equal(np.asanyarray(img2.dataobj), data) # byte swapped endian image bs_hdr = img.header.as_byteswapped() bs_img = Nifti1Image(data, affine, bs_hdr) - assert_equal(bs_img.header.endianness, swapped_code) + assert bs_img.header.endianness == swapped_code # of course the data is the same because it's not written to disk assert_array_equal(bs_img.get_fdata(), data) assert_array_equal(np.asanyarray(bs_img.dataobj), data) @@ -84,27 +84,27 @@ def test_save_load_endian(): cbs_img = AnalyzeImage.from_image(bs_img) # this will make the header native by doing the header conversion cbs_hdr = cbs_img.header - assert_equal(cbs_hdr.endianness, native_code) + assert cbs_hdr.endianness == native_code # and the byte order follows it back into another image cbs_img2 = Nifti1Image.from_image(cbs_img) cbs_hdr2 = cbs_img2.header - assert_equal(cbs_hdr2.endianness, native_code) + assert cbs_hdr2.endianness == native_code # Try byteswapped round trip bs_img2 = round_trip(bs_img) bs_data2 = np.asanyarray(bs_img2.dataobj) bs_fdata2 = bs_img2.get_fdata() # now the data dtype was swapped endian, so the read data is too - assert_equal(bs_data2.dtype.byteorder, swapped_code) - assert_equal(bs_img2.header.endianness, swapped_code) + assert bs_data2.dtype.byteorder == swapped_code + assert bs_img2.header.endianness == swapped_code assert_array_equal(bs_data2, data) # but get_fdata uses native endian - assert_not_equal(bs_fdata2.dtype.byteorder, swapped_code) + assert bs_fdata2.dtype.byteorder != swapped_code assert_array_equal(bs_fdata2, data) # Now mix up byteswapped data and non-byteswapped header mixed_img = Nifti1Image(bs_data2, affine) - assert_equal(mixed_img.header.endianness, native_code) + assert mixed_img.header.endianness == native_code m_img2 = round_trip(mixed_img) - assert_equal(m_img2.header.endianness, native_code) + assert m_img2.header.endianness == native_code assert_array_equal(m_img2.get_fdata(), data) @@ -121,7 +121,7 @@ def test_save_load(): sifn = 'another_image.img' ni1.save(img, nifn) re_img = nils.load(nifn) - assert_true(isinstance(re_img, ni1.Nifti1Image)) + assert isinstance(re_img, ni1.Nifti1Image) assert_array_equal(re_img.get_fdata(), data) assert_array_equal(re_img.affine, affine) # These and subsequent del statements are to prevent confusing @@ -131,20 +131,19 @@ def test_save_load(): if have_scipy: # skip we we cannot read .mat files spm2.save(img, sifn) re_img2 = nils.load(sifn) - assert_true(isinstance(re_img2, spm2.Spm2AnalyzeImage)) + assert isinstance(re_img2, spm2.Spm2AnalyzeImage) assert_array_equal(re_img2.get_fdata(), data) assert_array_equal(re_img2.affine, affine) del re_img2 spm99.save(img, sifn) re_img3 = nils.load(sifn) - assert_true(isinstance(re_img3, - spm99.Spm99AnalyzeImage)) + assert isinstance(re_img3, spm99.Spm99AnalyzeImage) assert_array_equal(re_img3.get_fdata(), data) assert_array_equal(re_img3.affine, affine) ni1.save(re_img3, nifn) del re_img3 re_img = nils.load(nifn) - assert_true(isinstance(re_img, ni1.Nifti1Image)) + assert isinstance(re_img, ni1.Nifti1Image) assert_array_equal(re_img.get_fdata(), data) assert_array_equal(re_img.affine, affine) del re_img @@ -159,13 +158,13 @@ def test_two_to_one(): affine[:3, 3] = [3, 2, 1] # single file format img = ni1.Nifti1Image(data, affine) - assert_equal(img.header['magic'], b'n+1') + assert img.header['magic'] == b'n+1' str_io = BytesIO() img.file_map['image'].fileobj = str_io # check that the single format vox offset stays at zero img.to_file_map() - assert_equal(img.header['magic'], b'n+1') - assert_equal(img.header['vox_offset'], 0) + assert img.header['magic'] == b'n+1' + assert img.header['vox_offset'] == 0 # make a new pair image, with the single image header pimg = ni1.Nifti1Pair(data, affine, img.header) isio = BytesIO() @@ -174,32 +173,32 @@ def test_two_to_one(): pimg.file_map['header'].fileobj = hsio pimg.to_file_map() # the offset stays at zero (but is 352 on disk) - assert_equal(pimg.header['magic'], b'ni1') - assert_equal(pimg.header['vox_offset'], 0) + assert pimg.header['magic'] == b'ni1' + assert pimg.header['vox_offset'] == 0 assert_array_equal(pimg.get_fdata(), data) # same for from_image, going from single image to pair format ana_img = ana.AnalyzeImage.from_image(img) - assert_equal(ana_img.header['vox_offset'], 0) + assert ana_img.header['vox_offset'] == 0 # back to the single image, save it again to a stringio str_io = BytesIO() img.file_map['image'].fileobj = str_io img.to_file_map() - assert_equal(img.header['vox_offset'], 0) + assert img.header['vox_offset'] == 0 aimg = ana.AnalyzeImage.from_image(img) - assert_equal(aimg.header['vox_offset'], 0) + assert aimg.header['vox_offset'] == 0 aimg = spm99.Spm99AnalyzeImage.from_image(img) - assert_equal(aimg.header['vox_offset'], 0) + assert aimg.header['vox_offset'] == 0 aimg = spm2.Spm2AnalyzeImage.from_image(img) - assert_equal(aimg.header['vox_offset'], 0) + assert aimg.header['vox_offset'] == 0 nfimg = ni1.Nifti1Pair.from_image(img) - assert_equal(nfimg.header['vox_offset'], 0) + assert nfimg.header['vox_offset'] == 0 # now set the vox offset directly hdr = nfimg.header hdr['vox_offset'] = 16 - assert_equal(nfimg.header['vox_offset'], 16) + assert nfimg.header['vox_offset'] == 16 # check it gets properly set by the nifti single image nfimg = ni1.Nifti1Image.from_image(img) - assert_equal(nfimg.header['vox_offset'], 0) + assert nfimg.header['vox_offset'] == 0 def test_negative_load_save(): @@ -260,7 +259,7 @@ def test_filename_save(): nils.save(img, path) rt_img = nils.load(path) assert_array_almost_equal(rt_img.get_fdata(), data) - assert_true(type(rt_img) is loadklass) + assert type(rt_img) is loadklass # delete image to allow file close. Otherwise windows # raises an error when trying to delete the directory del rt_img @@ -274,57 +273,41 @@ def test_analyze_detection(): def wat(hdr): return nils.which_analyze_type(hdr.binaryblock) n1_hdr = Nifti1Header(b'\0' * 348, check=False) - assert_equal(wat(n1_hdr), None) + assert wat(n1_hdr) is None n1_hdr['sizeof_hdr'] = 540 - assert_equal(wat(n1_hdr), 'nifti2') - assert_equal(wat(n1_hdr.as_byteswapped()), 'nifti2') + assert wat(n1_hdr) == 'nifti2' + assert wat(n1_hdr.as_byteswapped()) == 'nifti2' n1_hdr['sizeof_hdr'] = 348 - assert_equal(wat(n1_hdr), 'analyze') - assert_equal(wat(n1_hdr.as_byteswapped()), 'analyze') + assert wat(n1_hdr) == 'analyze' + assert wat(n1_hdr.as_byteswapped()) == 'analyze' n1_hdr['magic'] = b'n+1' - assert_equal(wat(n1_hdr), 'nifti1') - assert_equal(wat(n1_hdr.as_byteswapped()), 'nifti1') + assert wat(n1_hdr) == 'nifti1' + assert wat(n1_hdr.as_byteswapped()) == 'nifti1' n1_hdr['magic'] = b'ni1' - assert_equal(wat(n1_hdr), 'nifti1') - assert_equal(wat(n1_hdr.as_byteswapped()), 'nifti1') + assert wat(n1_hdr) == 'nifti1' + assert wat(n1_hdr.as_byteswapped()) == 'nifti1' # Doesn't matter what magic is if it's not a nifti1 magic n1_hdr['magic'] = b'ni2' - assert_equal(wat(n1_hdr), 'analyze') + assert wat(n1_hdr) == 'analyze' n1_hdr['sizeof_hdr'] = 0 n1_hdr['magic'] = b'' - assert_equal(wat(n1_hdr), None) + assert wat(n1_hdr) is None n1_hdr['magic'] = 'n+1' - assert_equal(wat(n1_hdr), 'nifti1') + assert wat(n1_hdr) == 'nifti1' n1_hdr['magic'] = 'ni1' - assert_equal(wat(n1_hdr), 'nifti1') + assert wat(n1_hdr) == 'nifti1' def test_guessed_image_type(): # Test whether we can guess the image type from example files - assert_equal(nils.guessed_image_type( - pjoin(DATA_PATH, 'example4d.nii.gz')), - Nifti1Image) - assert_equal(nils.guessed_image_type( - pjoin(DATA_PATH, 'nifti1.hdr')), - Nifti1Pair) - assert_equal(nils.guessed_image_type( - pjoin(DATA_PATH, 'example_nifti2.nii.gz')), - Nifti2Image) - assert_equal(nils.guessed_image_type( - pjoin(DATA_PATH, 'nifti2.hdr')), - Nifti2Pair) - assert_equal(nils.guessed_image_type( - pjoin(DATA_PATH, 'tiny.mnc')), - Minc1Image) - assert_equal(nils.guessed_image_type( - pjoin(DATA_PATH, 'small.mnc')), - Minc2Image) - assert_equal(nils.guessed_image_type( - pjoin(DATA_PATH, 'test.mgz')), - MGHImage) - assert_equal(nils.guessed_image_type( - pjoin(DATA_PATH, 'analyze.hdr')), - Spm2AnalyzeImage) + assert nils.guessed_image_type(pjoin(DATA_PATH, 'example4d.nii.gz')) == Nifti1Image + assert nils.guessed_image_type(pjoin(DATA_PATH, 'nifti1.hdr')) == Nifti1Pair + assert nils.guessed_image_type(pjoin(DATA_PATH, 'example_nifti2.nii.gz')) == Nifti2Image + assert nils.guessed_image_type(pjoin(DATA_PATH, 'nifti2.hdr')) == Nifti2Pair + assert nils.guessed_image_type(pjoin(DATA_PATH, 'tiny.mnc')) == Minc1Image + assert nils.guessed_image_type(pjoin(DATA_PATH, 'small.mnc')) == Minc2Image + assert nils.guessed_image_type(pjoin(DATA_PATH, 'test.mgz')) == MGHImage + assert nils.guessed_image_type(pjoin(DATA_PATH, 'analyze.hdr')) == Spm2AnalyzeImage def test_fail_save(): @@ -333,6 +316,6 @@ def test_fail_save(): affine = np.eye(4, dtype=np.float32) img = SpatialImage(dataobj, affine) # Fails because float16 is not supported. - with assert_raises(AttributeError): + with pytest.raises(AttributeError): nils.save(img, 'foo.nii.gz') del img diff --git a/nibabel/tests/test_image_types.py b/nibabel/tests/test_image_types.py index 3ffc65eead..632e23224d 100644 --- a/nibabel/tests/test_image_types.py +++ b/nibabel/tests/test_image_types.py @@ -20,7 +20,6 @@ Spm2AnalyzeImage, Spm99AnalyzeImage, MGHImage, all_image_classes) -from nose.tools import assert_true DATA_PATH = pjoin(dirname(__file__), 'data') @@ -64,7 +63,7 @@ def check_img(img_path, img_klass, sniff_mode, sniff, expect_success, 'sizeof_hdr', 0) current_sizeof_hdr = 0 if new_sniff is None else \ len(new_sniff[0]) - assert_true(current_sizeof_hdr >= expected_sizeof_hdr, new_msg) + assert current_sizeof_hdr >= expected_sizeof_hdr, new_msg # Check that the image type was recognized. new_msg = '%s (%s) image is%s a %s image.' % ( @@ -72,7 +71,7 @@ def check_img(img_path, img_klass, sniff_mode, sniff, expect_success, msg, '' if is_img else ' not', img_klass.__name__) - assert_true(is_img, new_msg) + assert is_img, new_msg if sniff_mode == 'vanilla': return new_sniff diff --git a/nibabel/tests/test_imageclasses.py b/nibabel/tests/test_imageclasses.py index 12232c42e4..193cf38cb9 100644 --- a/nibabel/tests/test_imageclasses.py +++ b/nibabel/tests/test_imageclasses.py @@ -15,7 +15,6 @@ from nibabel import imageclasses from nibabel.imageclasses import spatial_axes_first, class_map, ext_map -from nose.tools import (assert_true, assert_false, assert_equal) from nibabel.testing import clear_and_catch_warnings @@ -37,26 +36,26 @@ def test_spatial_axes_first(): for img_class in (AnalyzeImage, Nifti1Image, Nifti2Image): data = np.zeros(shape) img = img_class(data, affine) - assert_true(spatial_axes_first(img)) + assert spatial_axes_first(img) # True for MINC images < 4D for fname in MINC_3DS: img = nib.load(pjoin(DATA_DIR, fname)) - assert_true(len(img.shape) == 3) - assert_true(spatial_axes_first(img)) + assert len(img.shape) == 3 + assert spatial_axes_first(img) # False for MINC images < 4D for fname in MINC_4DS: img = nib.load(pjoin(DATA_DIR, fname)) - assert_true(len(img.shape) == 4) - assert_false(spatial_axes_first(img)) + assert len(img.shape) == 4 + assert not spatial_axes_first(img) def test_deprecations(): with clear_and_catch_warnings(modules=[imageclasses]) as w: warnings.filterwarnings('always', category=DeprecationWarning) nifti_single = class_map['nifti_single'] - assert_equal(nifti_single['class'], Nifti1Image) - assert_equal(len(w), 1) + assert nifti_single['class'] == Nifti1Image + assert len(w) == 1 nifti_ext = ext_map['.nii'] - assert_equal(nifti_ext, 'nifti_single') - assert_equal(len(w), 2) + assert nifti_ext == 'nifti_single' + assert len(w) == 2 diff --git a/nibabel/tests/test_imageglobals.py b/nibabel/tests/test_imageglobals.py index f730a4db01..42cbe6fdce 100644 --- a/nibabel/tests/test_imageglobals.py +++ b/nibabel/tests/test_imageglobals.py @@ -8,10 +8,6 @@ ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## """ Tests for imageglobals module """ - -from nose.tools import (assert_true, assert_false, assert_raises, - assert_equal, assert_not_equal) - from .. import imageglobals as igs @@ -19,5 +15,5 @@ def test_errorlevel(): orig_level = igs.error_level for level in (10, 20, 30): with igs.ErrorLevel(level): - assert_equal(igs.error_level, level) - assert_equal(igs.error_level, orig_level) + assert igs.error_level == level + assert igs.error_level == orig_level diff --git a/nibabel/tests/test_init.py b/nibabel/tests/test_init.py new file mode 100644 index 0000000000..97f440497e --- /dev/null +++ b/nibabel/tests/test_init.py @@ -0,0 +1,59 @@ +import nibabel as nib +from pkg_resources import resource_filename +import pytest +from unittest import mock + +@pytest.mark.parametrize("verbose, v_args", [(-2, ["-qq"]), + (-1, ["-q"]), + (0, []), + (1, ["-v"]), + (2, ["-vv"])]) +@pytest.mark.parametrize("doctests", (True, False)) +@pytest.mark.parametrize("coverage", (True, False)) +def test_nibabel_test(verbose, v_args, doctests, coverage): + expected_args = v_args + ["--doctest-modules", "--cov", "nibabel", "--pyargs", "nibabel"] + if not doctests: + expected_args.remove("--doctest-modules") + if not coverage: + expected_args[-4:-2] = [] + + with mock.patch("pytest.main") as pytest_main: + nib.test(verbose=verbose, doctests=doctests, coverage=coverage) + + args, kwargs = pytest_main.call_args + assert args == () + assert kwargs == {"args": expected_args} + + +def test_nibabel_test_errors(): + with pytest.raises(NotImplementedError): + nib.test(label="fast") + with pytest.raises(NotImplementedError): + nib.test(raise_warnings=[]) + with pytest.raises(NotImplementedError): + nib.test(timer=True) + with pytest.raises(ValueError): + nib.test(verbose="-v") + + +def test_nibabel_bench(): + expected_args = ["-c", "--pyargs", "nibabel"] + + try: + expected_args.insert(1, resource_filename("nibabel", "benchmarks/pytest.benchmark.ini")) + except: + raise unittest.SkipTest("Not installed") + + with mock.patch("pytest.main") as pytest_main: + nib.bench(verbose=0) + + args, kwargs = pytest_main.call_args + assert args == () + assert kwargs == {"args": expected_args} + + with mock.patch("pytest.main") as pytest_main: + nib.bench(verbose=0, extra_argv=[]) + + args, kwargs = pytest_main.call_args + assert args == () + assert kwargs == {"args": expected_args} diff --git a/nibabel/tests/test_keywordonly.py b/nibabel/tests/test_keywordonly.py index 0ef63d9b13..26e21ce02d 100644 --- a/nibabel/tests/test_keywordonly.py +++ b/nibabel/tests/test_keywordonly.py @@ -2,8 +2,7 @@ from ..keywordonly import kw_only_func, kw_only_meth -from nose.tools import assert_equal -from nose.tools import assert_raises +import pytest def test_kw_only_func(): @@ -11,23 +10,28 @@ def test_kw_only_func(): def func(an_arg): "My docstring" return an_arg - assert_equal(func(1), 1) - assert_raises(TypeError, func, 1, 2) + assert func(1) == 1 + with pytest.raises(TypeError): + func(1, 2) dec_func = kw_only_func(1)(func) - assert_equal(dec_func(1), 1) - assert_raises(TypeError, dec_func, 1, 2) - assert_raises(TypeError, dec_func, 1, akeyarg=3) - assert_equal(dec_func.__doc__, 'My docstring') + assert dec_func(1) == 1 + with pytest.raises(TypeError): + dec_func(1, 2) + with pytest.raises(TypeError): + dec_func(1, akeyarg=3) + assert dec_func.__doc__ == 'My docstring' @kw_only_func(1) def kw_func(an_arg, a_kwarg='thing'): "Another docstring" return an_arg, a_kwarg - assert_equal(kw_func(1), (1, 'thing')) - assert_raises(TypeError, kw_func, 1, 2) - assert_equal(kw_func(1, a_kwarg=2), (1, 2)) - assert_raises(TypeError, kw_func, 1, akeyarg=3) - assert_equal(kw_func.__doc__, 'Another docstring') + assert kw_func(1) == (1, 'thing') + with pytest.raises(TypeError): + kw_func(1, 2) + assert kw_func(1, a_kwarg=2) == (1, 2) + with pytest.raises(TypeError): + kw_func(1, akeyarg=3) + assert kw_func.__doc__ == 'Another docstring' class C(object): @@ -36,8 +40,10 @@ def kw_meth(self, an_arg, a_kwarg='thing'): "Method docstring" return an_arg, a_kwarg c = C() - assert_equal(c.kw_meth(1), (1, 'thing')) - assert_raises(TypeError, c.kw_meth, 1, 2) - assert_equal(c.kw_meth(1, a_kwarg=2), (1, 2)) - assert_raises(TypeError, c.kw_meth, 1, akeyarg=3) - assert_equal(c.kw_meth.__doc__, 'Method docstring') + assert c.kw_meth(1) == (1, 'thing') + with pytest.raises(TypeError): + c.kw_meth(1, 2) + assert c.kw_meth(1, a_kwarg=2) == (1, 2) + with pytest.raises(TypeError): + c.kw_meth(1, akeyarg=3) + assert c.kw_meth.__doc__ == 'Method docstring' diff --git a/nibabel/tests/test_loadsave.py b/nibabel/tests/test_loadsave.py index 3d7101b6d3..71f0435f1a 100644 --- a/nibabel/tests/test_loadsave.py +++ b/nibabel/tests/test_loadsave.py @@ -20,8 +20,7 @@ from numpy.testing import (assert_almost_equal, assert_array_equal) -from nose.tools import (assert_true, assert_false, assert_raises, - assert_equal, assert_not_equal) +import pytest data_path = pjoin(dirname(__file__), 'data') @@ -48,7 +47,7 @@ def test_read_img_data(): # These examples have null scaling - assert prefer=unscaled is the same dao = img.dataobj if hasattr(dao, 'slope') and hasattr(img.header, 'raw_data_from_fileobj'): - assert_equal((dao.slope, dao.inter), (1, 0)) + assert (dao.slope, dao.inter) == (1, 0) assert_array_equal(read_img_data(img, prefer='unscaled'), data) # Assert all caps filename works as well with TemporaryDirectory() as tmpdir: @@ -63,15 +62,16 @@ def test_read_img_data(): def test_file_not_found(): - assert_raises(FileNotFoundError, load, 'does_not_exist.nii.gz') + with pytest.raises(FileNotFoundError): + load('does_not_exist.nii.gz') def test_load_empty_image(): with InTemporaryDirectory(): open('empty.nii', 'w').close() - with assert_raises(ImageFileError) as err: + with pytest.raises(ImageFileError) as err: load('empty.nii') - assert_true(err.exception.args[0].startswith('Empty file: ')) + assert str(err.value).startswith('Empty file: ') def test_read_img_data_nifti(): @@ -86,13 +86,15 @@ def test_read_img_data_nifti(): img = img_class(data, np.eye(4)) img.set_data_dtype(out_dtype) # No filemap => error - assert_raises(ImageFileError, read_img_data, img) + with pytest.raises(ImageFileError): + read_img_data(img) # Make a filemap froot = 'an_image_{0}'.format(i) img.file_map = img.filespec_to_file_map(froot) # Trying to read from this filemap will generate an error because # we are going to read from files that do not exist - assert_raises(IOError, read_img_data, img) + with pytest.raises(IOError): + read_img_data(img) img.to_file_map() # Load - now the scaling and offset correctly applied img_fname = img.file_map['image'].filename @@ -127,8 +129,8 @@ def test_read_img_data_nifti(): else: new_inter = 0 # scaled scaling comes from new parameters in header - assert_true(np.allclose(actual_unscaled * 2.1 + new_inter, - read_img_data(img_back))) + assert np.allclose(actual_unscaled * 2.1 + new_inter, + read_img_data(img_back)) # Unscaled array didn't change assert_array_equal(actual_unscaled, read_img_data(img_back, prefer='unscaled')) diff --git a/nibabel/tests/test_minc1.py b/nibabel/tests/test_minc1.py index eb9ff15cab..a908ee6ad9 100644 --- a/nibabel/tests/test_minc1.py +++ b/nibabel/tests/test_minc1.py @@ -24,13 +24,13 @@ from ..minc1 import Minc1File, Minc1Image, MincHeader from ..tmpdirs import InTemporaryDirectory -from ..testing import (assert_true, assert_equal, assert_false, assert_raises, assert_warns, - assert_array_equal, data_path, clear_and_catch_warnings) from ..deprecator import ExpiredDeprecationError +from ..testing import assert_data_similar, data_path, clear_and_catch_warnings +from numpy.testing import assert_array_equal +import pytest from . import test_spatialimages as tsi from .test_fileslice import slicer_samples -from .test_helpers import assert_data_similar EG_FNAME = pjoin(data_path, 'tiny.mnc') @@ -107,14 +107,13 @@ def test_old_namespace(): aff = np.diag([2, 3, 4, 1]) from .. import Minc1Image, MincImage - assert_false(Minc1Image is MincImage) - with assert_raises(ExpiredDeprecationError): + assert Minc1Image is not MincImage + with pytest.raises(ExpiredDeprecationError): MincImage(arr, aff) - assert_equal(warns, []) # Another old name from ..minc1 import MincFile, Minc1File - assert_false(MincFile is Minc1File) - with assert_raises(ExpiredDeprecationError): + assert MincFile is not Minc1File + with pytest.raises(ExpiredDeprecationError): mf = MincFile(netcdf_file(EG_FNAME)) @@ -129,12 +128,12 @@ def test_mincfile(self): for tp in self.test_files: mnc_obj = self.opener(tp['fname'], 'r') mnc = self.file_class(mnc_obj) - assert_equal(mnc.get_data_dtype().type, tp['dtype']) - assert_equal(mnc.get_data_shape(), tp['shape']) - assert_equal(mnc.get_zooms(), tp['zooms']) + assert mnc.get_data_dtype().type == tp['dtype'] + assert mnc.get_data_shape() == tp['shape'] + assert mnc.get_zooms() == tp['zooms'] assert_array_equal(mnc.get_affine(), tp['affine']) data = mnc.get_scaled_data() - assert_equal(data.shape, tp['shape']) + assert data.shape == tp['shape'] def test_mincfile_slicing(self): # Test slicing and scaling of mincfile data @@ -158,7 +157,7 @@ def test_load(self): for tp in self.test_files: img = load(tp['fname']) data = img.get_fdata() - assert_equal(data.shape, tp['shape']) + assert data.shape == tp['shape'] # min, max, mean values from read in SPM2 / minctools assert_data_similar(data, tp) # check if mnc can be converted to nifti @@ -172,7 +171,7 @@ def test_array_proxy_slicing(self): img = load(tp['fname']) arr = img.get_fdata() prox = img.dataobj - assert_true(prox.is_proxy) + assert prox.is_proxy for sliceobj in slicer_samples(img.shape): assert_array_equal(arr[sliceobj], prox[sliceobj]) @@ -202,8 +201,10 @@ def test_header_data_io(): bio = BytesIO() hdr = MincHeader() arr = np.arange(24).reshape((2, 3, 4)) - assert_raises(NotImplementedError, hdr.data_to_fileobj, arr, bio) - assert_raises(NotImplementedError, hdr.data_from_fileobj, bio) + with pytest.raises(NotImplementedError): + hdr.data_to_fileobj(arr, bio) + with pytest.raises(NotImplementedError): + hdr.data_from_fileobj(bio) class TestMinc1Image(tsi.TestSpatialImage): @@ -217,7 +218,7 @@ def test_data_to_from_fileobj(self): img = self.module.load(fpath) bio = BytesIO() arr = np.arange(24).reshape((2, 3, 4)) - assert_raises(NotImplementedError, - img.header.data_to_fileobj, arr, bio) - assert_raises(NotImplementedError, - img.header.data_from_fileobj, bio) + with pytest.raises(NotImplementedError): + img.header.data_to_fileobj(arr, bio) + with pytest.raises(NotImplementedError): + img.header.data_from_fileobj(bio) diff --git a/nibabel/tests/test_minc2.py b/nibabel/tests/test_minc2.py index f4367cbc11..2c2f5c6e51 100644 --- a/nibabel/tests/test_minc2.py +++ b/nibabel/tests/test_minc2.py @@ -15,8 +15,6 @@ from ..minc2 import Minc2File, Minc2Image from .._h5py_compat import h5py, have_h5py, setup_module -from nose.tools import (assert_true, assert_equal, assert_false, assert_raises) - from ..testing import data_path from . import test_minc1 as tm2 diff --git a/nibabel/tests/test_minc2_data.py b/nibabel/tests/test_minc2_data.py index ebfafa938f..6d5a4b0e35 100644 --- a/nibabel/tests/test_minc2_data.py +++ b/nibabel/tests/test_minc2_data.py @@ -19,7 +19,6 @@ from .nibabel_data import get_nibabel_data, needs_nibabel_data from .. import load as top_load, Nifti1Image -from nose.tools import assert_equal from numpy.testing import (assert_array_equal, assert_almost_equal) MINC2_PATH = pjoin(get_nibabel_data(), 'nitest-minc2') @@ -58,14 +57,14 @@ class TestEPIFrame(object): def test_load(self): # Check highest level load of minc works img = self.opener(self.example_params['fname']) - assert_equal(img.shape, self.example_params['shape']) + assert img.shape == self.example_params['shape'] assert_almost_equal(img.header.get_zooms(), self.example_params['zooms'], 5) assert_almost_equal(img.affine, self.example_params['affine'], 4) - assert_equal(img.get_data_dtype().type, self.example_params['type']) + assert img.get_data_dtype().type == self.example_params['type'] # Check correspondence of data and recorded shape data = img.get_fdata() - assert_equal(data.shape, self.example_params['shape']) + assert data.shape == self.example_params['shape'] # min, max, mean values from read in SPM2 assert_almost_equal(data.min(), self.example_params['min'], 4) assert_almost_equal(data.max(), self.example_params['max'], 4) diff --git a/nibabel/tests/test_mriutils.py b/nibabel/tests/test_mriutils.py index 527afc61ba..8c6b198c95 100644 --- a/nibabel/tests/test_mriutils.py +++ b/nibabel/tests/test_mriutils.py @@ -10,12 +10,8 @@ """ -from numpy.testing import (assert_almost_equal, - assert_array_equal) - -from nose.tools import (assert_true, assert_false, assert_raises, - assert_equal, assert_not_equal) - +from numpy.testing import assert_almost_equal +import pytest from ..mriutils import calculate_dwell_time, MRIError @@ -28,5 +24,7 @@ def test_calculate_dwell_time(): 3.3 / (42.576 * 3.4 * 3 * 3)) # Echo train length of 1 is valid, but returns 0 dwell time assert_almost_equal(calculate_dwell_time(3.3, 1, 3), 0) - assert_raises(MRIError, calculate_dwell_time, 3.3, 0, 3.0) - assert_raises(MRIError, calculate_dwell_time, 3.3, 2, -0.1) + with pytest.raises(MRIError): + calculate_dwell_time(3.3, 0, 3.0) + with pytest.raises(MRIError): + calculate_dwell_time(3.3, 2, -0.1) diff --git a/nibabel/tests/test_nibabel_data.py b/nibabel/tests/test_nibabel_data.py index f804f7499f..86e94f5c34 100644 --- a/nibabel/tests/test_nibabel_data.py +++ b/nibabel/tests/test_nibabel_data.py @@ -6,7 +6,6 @@ from . import nibabel_data as nibd -from nose.tools import assert_equal MY_DIR = dirname(__file__) @@ -23,10 +22,10 @@ def test_get_nibabel_data(): # Test getting directory local_data = realpath(pjoin(MY_DIR, '..', '..', 'nibabel-data')) if isdir(local_data): - assert_equal(nibd.get_nibabel_data(), local_data) + assert nibd.get_nibabel_data() == local_data else: - assert_equal(nibd.get_nibabel_data(), '') + assert nibd.get_nibabel_data() == '' nibd.environ['NIBABEL_DATA_DIR'] = 'not_a_path' - assert_equal(nibd.get_nibabel_data(), '') + assert nibd.get_nibabel_data() == '' nibd.environ['NIBABEL_DATA_DIR'] = MY_DIR - assert_equal(nibd.get_nibabel_data(), MY_DIR) + assert nibd.get_nibabel_data() == MY_DIR diff --git a/nibabel/tests/test_nifti1.py b/nibabel/tests/test_nifti1.py index 0213b615f1..9b4747bd5d 100644 --- a/nibabel/tests/test_nifti1.py +++ b/nibabel/tests/test_nifti1.py @@ -29,20 +29,20 @@ from .test_arraywriters import rt_err_estimate, IUINT_TYPES from .test_orientations import ALL_ORNTS -from .test_helpers import bytesio_filemap, bytesio_round_trip from .nibabel_data import get_nibabel_data, needs_nibabel_data from numpy.testing import (assert_array_equal, assert_array_almost_equal, assert_almost_equal) -from nose.tools import (assert_true, assert_false, assert_equal, - assert_raises) from ..testing import ( clear_and_catch_warnings, data_path, runif_extra_has, suppress_warnings, + bytesio_filemap, + bytesio_round_trip ) +import pytest from . import test_analyze as tana from . import test_spm99analyze as tspm @@ -50,7 +50,8 @@ header_file = os.path.join(data_path, 'nifti1.hdr') image_file = os.path.join(data_path, 'example4d.nii.gz') -from nibabel.pydicom_compat import pydicom, dicom_test +from ..pydicom_compat import pydicom +from ..nicom.tests import dicom_test # Example transformation matrix @@ -82,15 +83,15 @@ class TestNifti1PairHeader(tana.TestAnalyzeHeader, tspm.HeaderScalingMixin): def test_empty(self): tana.TestAnalyzeHeader.test_empty(self) hdr = self.header_class() - assert_equal(hdr['magic'], hdr.pair_magic) - assert_equal(hdr['scl_slope'], 1) - assert_equal(hdr['vox_offset'], 0) + assert hdr['magic'] == hdr.pair_magic + assert hdr['scl_slope'] == 1 + assert hdr['vox_offset'] == 0 def test_from_eg_file(self): hdr = self.header_class.from_fileobj(open(self.example_file, 'rb')) - assert_equal(hdr.endianness, '<') - assert_equal(hdr['magic'], hdr.pair_magic) - assert_equal(hdr['sizeof_hdr'], self.sizeof_hdr) + assert hdr.endianness == '<' + assert hdr['magic'] == hdr.pair_magic + assert hdr['sizeof_hdr'] == self.sizeof_hdr def test_data_scaling(self): # Test scaling in header @@ -109,7 +110,7 @@ def test_data_scaling(self): hdr.set_data_dtype(np.int8) hdr.set_slope_inter(1, 0) hdr.data_to_fileobj(data, S, rescale=True) - assert_false(np.allclose(hdr.get_slope_inter(), (1, 0))) + assert not np.allclose(hdr.get_slope_inter(), (1, 0)) rdata = hdr.data_from_fileobj(S) assert_array_almost_equal(data, rdata) # Without scaling does rounding, doesn't alter scaling @@ -133,13 +134,13 @@ def test_big_scaling(self): data = np.array([finf['min'], finf['max']], dtype=dtt)[:, None, None] hdr.data_to_fileobj(data, sio) data_back = hdr.data_from_fileobj(sio) - assert_true(np.allclose(data, data_back)) + assert np.allclose(data, data_back) def test_slope_inter(self): hdr = self.header_class() nan, inf, minf = np.nan, np.inf, -np.inf HDE = HeaderDataError - assert_equal(hdr.get_slope_inter(), (1.0, 0.0)) + assert hdr.get_slope_inter() == (1.0, 0.0) for in_tup, exp_err, out_tup, raw_values in ( # Null scalings ((None, None), None, (None, None), (nan, nan)), @@ -177,20 +178,21 @@ def test_slope_inter(self): ((2, 1), None, (2, 1), (2, 1))): hdr = self.header_class() if not exp_err is None: - assert_raises(exp_err, hdr.set_slope_inter, *in_tup) + with pytest.raises(exp_err): + hdr.set_slope_inter(*in_tup) in_list = [v if not v is None else np.nan for v in in_tup] hdr['scl_slope'], hdr['scl_inter'] = in_list else: hdr.set_slope_inter(*in_tup) if isinstance(out_tup, Exception): - assert_raises(out_tup, hdr.get_slope_inter) + with pytest.raises(out_tup): + hdr.get_slope_inter() else: - assert_equal(hdr.get_slope_inter(), out_tup) + assert hdr.get_slope_inter() == out_tup # Check set survives through checking hdr = self.header_class.from_header(hdr, check=True) - assert_equal(hdr.get_slope_inter(), out_tup) - assert_array_equal([hdr['scl_slope'], hdr['scl_inter']], - raw_values) + assert hdr.get_slope_inter() == out_tup + assert_array_equal([hdr['scl_slope'], hdr['scl_inter']], raw_values) def test_nifti_qfac_checks(self): # Test qfac is 1 or -1 @@ -203,10 +205,8 @@ def test_nifti_qfac_checks(self): # 0 is not hdr['pixdim'][0] = 0 fhdr, message, raiser = self.log_chk(hdr, 20) - assert_equal(fhdr['pixdim'][0], 1) - assert_equal(message, - 'pixdim[0] (qfac) should be 1 ' - '(default) or -1; setting qfac to 1') + assert fhdr['pixdim'][0] == 1 + assert message == 'pixdim[0] (qfac) should be 1 (default) or -1; setting qfac to 1' def test_nifti_qsform_checks(self): # qform, sform checks @@ -215,15 +215,13 @@ def test_nifti_qsform_checks(self): hdr = HC() hdr['qform_code'] = -1 fhdr, message, raiser = self.log_chk(hdr, 30) - assert_equal(fhdr['qform_code'], 0) - assert_equal(message, - 'qform_code -1 not valid; setting to 0') + assert fhdr['qform_code'] == 0 + assert message == 'qform_code -1 not valid; setting to 0' hdr = HC() hdr['sform_code'] = -1 fhdr, message, raiser = self.log_chk(hdr, 30) - assert_equal(fhdr['sform_code'], 0) - assert_equal(message, - 'sform_code -1 not valid; setting to 0') + assert fhdr['sform_code'] == 0 + assert message == 'sform_code -1 not valid; setting to 0' def test_nifti_xform_codes(self): # Verify that all xform codes can be set in both qform and sform @@ -231,14 +229,16 @@ def test_nifti_xform_codes(self): affine = np.eye(4) for code in nifti1.xform_codes.keys(): hdr.set_qform(affine, code) - assert_equal(hdr['qform_code'], nifti1.xform_codes[code]) + assert hdr['qform_code'] == nifti1.xform_codes[code] hdr.set_sform(affine, code) - assert_equal(hdr['sform_code'], nifti1.xform_codes[code]) + assert hdr['sform_code'] == nifti1.xform_codes[code] # Raise KeyError on unknown code for bad_code in (-1, 6, 10): - assert_raises(KeyError, hdr.set_qform, affine, bad_code) - assert_raises(KeyError, hdr.set_sform, affine, bad_code) + with pytest.raises(KeyError): + hdr.set_qform(affine, bad_code) + with pytest.raises(KeyError): + hdr.set_sform(affine, bad_code) def test_magic_offset_checks(self): # magic and offset @@ -246,10 +246,10 @@ def test_magic_offset_checks(self): hdr = HC() hdr['magic'] = 'ooh' fhdr, message, raiser = self.log_chk(hdr, 45) - assert_equal(fhdr['magic'], b'ooh') - assert_equal(message, - 'magic string "ooh" is not valid; ' - 'leaving as is, but future errors are likely') + assert fhdr['magic'] == b'ooh' + assert (message == + 'magic string "ooh" is not valid; ' + 'leaving as is, but future errors are likely') # For pairs, any offset is OK, but should be divisible by 16 # Singles need offset of at least 352 (nifti1) or 540 (nifti2) bytes, # with the divide by 16 rule @@ -263,20 +263,20 @@ def test_magic_offset_checks(self): self.assert_no_log_err(hdr) hdr['vox_offset'] = bad_spm fhdr, message, raiser = self.log_chk(hdr, 30) - assert_equal(fhdr['vox_offset'], bad_spm) - assert_equal(message, - 'vox offset (={0:g}) not divisible by 16, ' - 'not SPM compatible; leaving at current ' - 'value'.format(bad_spm)) + assert fhdr['vox_offset'] == bad_spm + assert (message == + 'vox offset (={0:g}) not divisible by 16, ' + 'not SPM compatible; leaving at current ' + 'value'.format(bad_spm)) # Check minimum offset (if offset set) hdr['magic'] = hdr.single_magic hdr['vox_offset'] = 10 fhdr, message, raiser = self.log_chk(hdr, 40) - assert_equal(fhdr['vox_offset'], hdr.single_vox_offset) - assert_equal(message, - 'vox offset 10 too low for single ' - 'file nifti1; setting to minimum value ' - 'of ' + str(hdr.single_vox_offset)) + assert fhdr['vox_offset'] == hdr.single_vox_offset + assert (message == + 'vox offset 10 too low for single ' + 'file nifti1; setting to minimum value ' + 'of ' + str(hdr.single_vox_offset)) def test_freesurfer_large_vector_hack(self): # For large vector images, Freesurfer appears to set dim[1] to -1 and @@ -285,14 +285,14 @@ def test_freesurfer_large_vector_hack(self): # The standard case hdr = HC() hdr.set_data_shape((2, 3, 4)) - assert_equal(hdr.get_data_shape(), (2, 3, 4)) - assert_equal(hdr['glmin'], 0) + assert hdr.get_data_shape() == (2, 3, 4) + assert hdr['glmin'] == 0 # Just left of the freesurfer case dim_type = hdr.template_dtype['dim'].base glmin = hdr.template_dtype['glmin'].base too_big = int(np.iinfo(dim_type).max) + 1 hdr.set_data_shape((too_big - 1, 1, 1)) - assert_equal(hdr.get_data_shape(), (too_big - 1, 1, 1)) + assert hdr.get_data_shape() == (too_big - 1, 1, 1) # The freesurfer case full_shape = (too_big, 1, 1, 1, 1, 1, 1) for dim in range(3, 8): @@ -300,39 +300,41 @@ def test_freesurfer_large_vector_hack(self): expected_dim = np.array([dim, -1, 1, 1, 1, 1, 1, 1]) with suppress_warnings(): hdr.set_data_shape(full_shape[:dim]) - assert_equal(hdr.get_data_shape(), full_shape[:dim]) + assert hdr.get_data_shape() == full_shape[:dim] assert_array_equal(hdr['dim'], expected_dim) - assert_equal(hdr['glmin'], too_big) + assert hdr['glmin'] == too_big # Allow the fourth dimension to vary with suppress_warnings(): hdr.set_data_shape((too_big, 1, 1, 4)) - assert_equal(hdr.get_data_shape(), (too_big, 1, 1, 4)) + assert hdr.get_data_shape() == (too_big, 1, 1, 4) assert_array_equal(hdr['dim'][:5], np.array([4, -1, 1, 1, 4])) # This only works when the first 3 dimensions are -1, 1, 1 - assert_raises(HeaderDataError, hdr.set_data_shape, (too_big,)) - assert_raises(HeaderDataError, hdr.set_data_shape, (too_big, 1)) - assert_raises(HeaderDataError, hdr.set_data_shape, (too_big, 1, 2)) - assert_raises(HeaderDataError, hdr.set_data_shape, (too_big, 2, 1)) - assert_raises(HeaderDataError, hdr.set_data_shape, (1, too_big)) - assert_raises(HeaderDataError, hdr.set_data_shape, (1, too_big, 1)) - assert_raises(HeaderDataError, hdr.set_data_shape, (1, 1, too_big)) - assert_raises(HeaderDataError, hdr.set_data_shape, (1, 1, 1, too_big)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (too_big,)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (too_big, 1)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (too_big, 1, 2)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (too_big, 2, 1)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (1, too_big)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (1, too_big, 1)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (1, 1, too_big)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (1, 1, 1, too_big)) # Outside range of glmin raises error far_too_big = int(np.iinfo(glmin).max) + 1 with suppress_warnings(): hdr.set_data_shape((far_too_big - 1, 1, 1)) - assert_equal(hdr.get_data_shape(), (far_too_big - 1, 1, 1)) - assert_raises(HeaderDataError, hdr.set_data_shape, (far_too_big, 1, 1)) + assert hdr.get_data_shape() == (far_too_big - 1, 1, 1) + with pytest.raises(HeaderDataError): + hdr.set_data_shape((far_too_big, 1, 1)) # glmin of zero raises error (implausible vector length) hdr.set_data_shape((-1, 1, 1)) hdr['glmin'] = 0 - assert_raises(HeaderDataError, hdr.get_data_shape) + with pytest.raises(HeaderDataError): + hdr.get_data_shape() # Lists or tuples or arrays will work for setting shape for shape in ((too_big - 1, 1, 1), (too_big, 1, 1)): for constructor in (list, tuple, np.array): with suppress_warnings(): hdr.set_data_shape(constructor(shape)) - assert_equal(hdr.get_data_shape(), shape) + assert hdr.get_data_shape() == shape @needs_nibabel_data('nitest-freesurfer') def test_freesurfer_ico7_hack(self): @@ -343,24 +345,24 @@ def test_freesurfer_ico7_hack(self): for dim in range(3, 8): expected_dim = np.array([dim, 27307, 1, 6, 1, 1, 1, 1]) hdr.set_data_shape(full_shape[:dim]) - assert_equal(hdr.get_data_shape(), full_shape[:dim]) + assert hdr.get_data_shape() == full_shape[:dim] assert_array_equal(hdr._structarr['dim'], expected_dim) # Only works on dimensions >= 3 - assert_raises(HeaderDataError, hdr.set_data_shape, full_shape[:1]) - assert_raises(HeaderDataError, hdr.set_data_shape, full_shape[:2]) + pytest.raises(HeaderDataError, hdr.set_data_shape, full_shape[:1]) + pytest.raises(HeaderDataError, hdr.set_data_shape, full_shape[:2]) # Bad shapes - assert_raises(HeaderDataError, hdr.set_data_shape, (163842, 2, 1)) - assert_raises(HeaderDataError, hdr.set_data_shape, (163842, 1, 2)) - assert_raises(HeaderDataError, hdr.set_data_shape, (1, 163842, 1)) - assert_raises(HeaderDataError, hdr.set_data_shape, (1, 1, 163842)) - assert_raises(HeaderDataError, hdr.set_data_shape, (1, 1, 1, 163842)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (163842, 2, 1)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (163842, 1, 2)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (1, 163842, 1)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (1, 1, 163842)) + pytest.raises(HeaderDataError, hdr.set_data_shape, (1, 1, 1, 163842)) # Test consistency of data in .mgh and mri_convert produced .nii nitest_path = os.path.join(get_nibabel_data(), 'nitest-freesurfer') mgh = mghload(os.path.join(nitest_path, 'fsaverage', 'surf', 'lh.orig.avg.area.mgh')) nii = load(os.path.join(nitest_path, 'derivative', 'fsaverage', 'surf', 'lh.orig.avg.area.nii')) - assert_equal(mgh.shape, nii.shape) + assert mgh.shape == nii.shape assert_array_equal(mgh.get_fdata(), nii.get_fdata()) assert_array_equal(nii.header._structarr['dim'][1:4], np.array([27307, 1, 6])) @@ -368,7 +370,7 @@ def test_freesurfer_ico7_hack(self): with InTemporaryDirectory(): nii.to_filename('test.nii') nii2 = load('test.nii') - assert_equal(nii.shape, nii2.shape) + assert nii.shape == nii2.shape assert_array_equal(nii.get_fdata(), nii2.get_fdata()) assert_array_equal(nii.affine, nii2.affine) @@ -379,8 +381,8 @@ def test_qform_sform(self): empty_sform = np.zeros((4, 4)) empty_sform[-1, -1] = 1 assert_array_equal(hdr.get_sform(), empty_sform) - assert_equal(hdr.get_qform(coded=True), (None, 0)) - assert_equal(hdr.get_sform(coded=True), (None, 0)) + assert hdr.get_qform(coded=True) == (None, 0) + assert hdr.get_sform(coded=True) == (None, 0) # Affines with no shears nice_aff = np.diag([2, 3, 4, 1]) another_aff = np.diag([3, 4, 5, 1]) @@ -388,39 +390,39 @@ def test_qform_sform(self): nasty_aff = from_matvec(np.arange(9).reshape((3, 3)), [9, 10, 11]) nasty_aff[0, 0] = 1 # Make full rank fixed_aff = unshear_44(nasty_aff) - assert_false(np.allclose(fixed_aff, nasty_aff)) + assert not np.allclose(fixed_aff, nasty_aff) for in_meth, out_meth in ((hdr.set_qform, hdr.get_qform), (hdr.set_sform, hdr.get_sform)): in_meth(nice_aff, 2) aff, code = out_meth(coded=True) assert_array_equal(aff, nice_aff) - assert_equal(code, 2) + assert code == 2 assert_array_equal(out_meth(), nice_aff) # non coded # Affine may be passed if code == 0, and will get set into header, # but the returned affine with 'coded=True' will be None. in_meth(another_aff, 0) - assert_equal(out_meth(coded=True), (None, 0)) # coded -> None + assert out_meth(coded=True) == (None, 0) # coded -> None assert_array_almost_equal(out_meth(), another_aff) # else -> input # Default qform code when previous == 0 is 2 in_meth(nice_aff) aff, code = out_meth(coded=True) - assert_equal(code, 2) + assert code == 2 # Unless code was non-zero before in_meth(nice_aff, 1) in_meth(nice_aff) aff, code = out_meth(coded=True) - assert_equal(code, 1) + assert code == 1 # Can set code without modifying affine, by passing affine=None assert_array_equal(aff, nice_aff) # affine same as before in_meth(None, 3) aff, code = out_meth(coded=True) assert_array_equal(aff, nice_aff) # affine same as before - assert_equal(code, 3) + assert code == 3 # affine is None on its own, or with code==0, resets code to 0 in_meth(None, 0) - assert_equal(out_meth(coded=True), (None, 0)) + assert out_meth(coded=True) == (None, 0) in_meth(None) - assert_equal(out_meth(coded=True), (None, 0)) + assert out_meth(coded=True) == (None, 0) # List works as input in_meth(nice_aff.tolist()) assert_array_equal(out_meth(), nice_aff) @@ -429,17 +431,18 @@ def test_qform_sform(self): hdr.set_qform(nasty_aff, 1) assert_array_almost_equal(hdr.get_qform(), fixed_aff) # Unless allow_shears is False - assert_raises(HeaderDataError, hdr.set_qform, nasty_aff, 1, False) + with pytest.raises(HeaderDataError): + hdr.set_qform(nasty_aff, 1, False) # Reset sform, give qform a code, to test sform hdr.set_sform(None) hdr.set_qform(nice_aff, 1) # Check sform unchanged by setting qform - assert_equal(hdr.get_sform(coded=True), (None, 0)) + assert hdr.get_sform(coded=True) == (None, 0) # Setting does change the sform ouput hdr.set_sform(nasty_aff, 1) aff, code = hdr.get_sform(coded=True) assert_array_equal(aff, nasty_aff) - assert_equal(code, 1) + assert code == 1 def test_datatypes(self): hdr = self.header_class() @@ -448,9 +451,7 @@ def test_datatypes(self): if dt == np.void: continue hdr.set_data_dtype(code) - (assert_equal, - hdr.get_data_dtype(), - data_type_codes.dtype[code]) + assert hdr.get_data_dtype() == data_type_codes.dtype[code] # Check that checks also see new datatypes hdr.set_data_dtype(np.complex128) hdr.check_fix() @@ -460,11 +461,11 @@ def test_quaternion(self): hdr['quatern_b'] = 0 hdr['quatern_c'] = 0 hdr['quatern_d'] = 0 - assert_true(np.allclose(hdr.get_qform_quaternion(), [1.0, 0, 0, 0])) + assert np.allclose(hdr.get_qform_quaternion(), [1.0, 0, 0, 0]) hdr['quatern_b'] = 1 hdr['quatern_c'] = 0 hdr['quatern_d'] = 0 - assert_true(np.allclose(hdr.get_qform_quaternion(), [0, 1, 0, 0])) + assert np.allclose(hdr.get_qform_quaternion(), [0, 1, 0, 0]) # Check threshold set correctly for float32 hdr['quatern_b'] = 1 + np.finfo(self.quat_dtype).eps assert_array_almost_equal(hdr.get_qform_quaternion(), [0, 1, 0, 0]) @@ -474,35 +475,36 @@ def test_qform(self): ehdr = self.header_class() ehdr.set_qform(A) qA = ehdr.get_qform() - assert_true, np.allclose(A, qA, atol=1e-5) - assert_true, np.allclose(Z, ehdr['pixdim'][1:4]) + assert np.allclose(A, qA, atol=1e-5) + assert np.allclose(Z, ehdr['pixdim'][1:4]) xfas = nifti1.xform_codes - assert_true, ehdr['qform_code'] == xfas['aligned'] + assert ehdr['qform_code'] == xfas['aligned'] ehdr.set_qform(A, 'scanner') - assert_true, ehdr['qform_code'] == xfas['scanner'] + assert ehdr['qform_code'] == xfas['scanner'] ehdr.set_qform(A, xfas['aligned']) - assert_true, ehdr['qform_code'] == xfas['aligned'] + assert ehdr['qform_code'] == xfas['aligned'] # Test pixdims[1,2,3] are checked for negatives for dims in ((-1, 1, 1), (1, -1, 1), (1, 1, -1)): ehdr['pixdim'][1:4] = dims - assert_raises(HeaderDataError, ehdr.get_qform) + with pytest.raises(HeaderDataError): + ehdr.get_qform() def test_sform(self): # Test roundtrip case ehdr = self.header_class() ehdr.set_sform(A) sA = ehdr.get_sform() - assert_true, np.allclose(A, sA, atol=1e-5) + assert np.allclose(A, sA, atol=1e-5) xfas = nifti1.xform_codes - assert_true, ehdr['sform_code'] == xfas['aligned'] + assert ehdr['sform_code'] == xfas['aligned'] ehdr.set_sform(A, 'scanner') - assert_true, ehdr['sform_code'] == xfas['scanner'] + assert ehdr['sform_code'] == xfas['scanner'] ehdr.set_sform(A, xfas['aligned']) - assert_true, ehdr['sform_code'] == xfas['aligned'] + assert ehdr['sform_code'] == xfas['aligned'] def test_dim_info(self): ehdr = self.header_class() - assert_true(ehdr.get_dim_info() == (None, None, None)) + assert ehdr.get_dim_info() == (None, None, None) for info in ((0, 2, 1), (None, None, None), (0, 2, None), @@ -511,18 +513,21 @@ def test_dim_info(self): (None, None, 1), ): ehdr.set_dim_info(*info) - assert_true(ehdr.get_dim_info() == info) + assert ehdr.get_dim_info() == info def test_slice_times(self): hdr = self.header_class() # error if slice dimension not specified - assert_raises(HeaderDataError, hdr.get_slice_times) + with pytest.raises(HeaderDataError): + hdr.get_slice_times() hdr.set_dim_info(slice=2) # error if slice dimension outside shape - assert_raises(HeaderDataError, hdr.get_slice_times) + with pytest.raises(HeaderDataError): + hdr.get_slice_times() hdr.set_data_shape((1, 1, 7)) # error if slice duration not set - assert_raises(HeaderDataError, hdr.get_slice_times) + with pytest.raises(HeaderDataError): + hdr.get_slice_times() hdr.set_slice_duration(0.1) # We need a function to print out the Nones and floating point # values in a predictable way, for the tests below. @@ -530,51 +535,56 @@ def test_slice_times(self): _print_me = lambda s: list(map(_stringer, s)) # The following examples are from the nifti1.h documentation. hdr['slice_code'] = slice_order_codes['sequential increasing'] - assert_equal(_print_me(hdr.get_slice_times()), - ['0.0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6']) + assert (_print_me(hdr.get_slice_times()) == + ['0.0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6']) hdr['slice_start'] = 1 hdr['slice_end'] = 5 - assert_equal(_print_me(hdr.get_slice_times()), - [None, '0.0', '0.1', '0.2', '0.3', '0.4', None]) + assert (_print_me(hdr.get_slice_times()) == + [None, '0.0', '0.1', '0.2', '0.3', '0.4', None]) hdr['slice_code'] = slice_order_codes['sequential decreasing'] - assert_equal(_print_me(hdr.get_slice_times()), - [None, '0.4', '0.3', '0.2', '0.1', '0.0', None]) + assert (_print_me(hdr.get_slice_times()) == + [None, '0.4', '0.3', '0.2', '0.1', '0.0', None]) hdr['slice_code'] = slice_order_codes['alternating increasing'] - assert_equal(_print_me(hdr.get_slice_times()), - [None, '0.0', '0.3', '0.1', '0.4', '0.2', None]) + assert (_print_me(hdr.get_slice_times()) == + [None, '0.0', '0.3', '0.1', '0.4', '0.2', None]) hdr['slice_code'] = slice_order_codes['alternating decreasing'] - assert_equal(_print_me(hdr.get_slice_times()), - [None, '0.2', '0.4', '0.1', '0.3', '0.0', None]) + assert (_print_me(hdr.get_slice_times()) == + [None, '0.2', '0.4', '0.1', '0.3', '0.0', None]) hdr['slice_code'] = slice_order_codes['alternating increasing 2'] - assert_equal(_print_me(hdr.get_slice_times()), - [None, '0.2', '0.0', '0.3', '0.1', '0.4', None]) + assert (_print_me(hdr.get_slice_times()) == + [None, '0.2', '0.0', '0.3', '0.1', '0.4', None]) hdr['slice_code'] = slice_order_codes['alternating decreasing 2'] - assert_equal(_print_me(hdr.get_slice_times()), - [None, '0.4', '0.1', '0.3', '0.0', '0.2', None]) + assert (_print_me(hdr.get_slice_times()) == + [None, '0.4', '0.1', '0.3', '0.0', '0.2', None]) # test set hdr = self.header_class() hdr.set_dim_info(slice=2) # need slice dim to correspond with shape times = [None, 0.2, 0.4, 0.1, 0.3, 0.0, None] - assert_raises(HeaderDataError, hdr.set_slice_times, times) + with pytest.raises(HeaderDataError): + hdr.set_slice_times(times) hdr.set_data_shape([1, 1, 7]) - assert_raises(HeaderDataError, hdr.set_slice_times, - times[:-1]) # wrong length - assert_raises(HeaderDataError, hdr.set_slice_times, - (None,) * len(times)) # all None + with pytest.raises(HeaderDataError): + # wrong length + hdr.set_slice_times(times[:-1]) + with pytest.raises(HeaderDataError): + # all None + hdr.set_slice_times((None,) * len(times)) n_mid_times = times[:] n_mid_times[3] = None - assert_raises(HeaderDataError, hdr.set_slice_times, - n_mid_times) # None in middle + with pytest.raises(HeaderDataError): + # None in middle + hdr.set_slice_times(n_mid_times) funny_times = times[:] funny_times[3] = 0.05 - assert_raises(HeaderDataError, hdr.set_slice_times, - funny_times) # can't get single slice duration + with pytest.raises(HeaderDataError): + # can't get single slice duration + hdr.set_slice_times(funny_times) hdr.set_slice_times(times) - assert_equal(hdr.get_value_label('slice_code'), + assert (hdr.get_value_label('slice_code') == 'alternating decreasing') - assert_equal(hdr['slice_start'], 1) - assert_equal(hdr['slice_end'], 5) + assert hdr['slice_start'] == 1 + assert hdr['slice_end'] == 5 assert_array_almost_equal(hdr['slice_duration'], 0.1) # Ambiguous case @@ -587,52 +597,54 @@ def test_slice_times(self): hdr2.set_slice_times([0.1, 0]) assert len(w) == 1 # but always must be choosing sequential one first - assert_equal(hdr2.get_value_label('slice_code'), 'sequential decreasing') + assert hdr2.get_value_label('slice_code') == 'sequential decreasing' # and the other direction hdr2.set_slice_times([0, 0.1]) - assert_equal(hdr2.get_value_label('slice_code'), 'sequential increasing') + assert hdr2.get_value_label('slice_code') == 'sequential increasing' def test_intents(self): ehdr = self.header_class() ehdr.set_intent('t test', (10,), name='some score') - assert_equal(ehdr.get_intent(), - ('t test', (10.0,), 'some score')) + assert ehdr.get_intent() == ('t test', (10.0,), 'some score') # unknown intent name or code - unknown name will fail even when # allow_unknown=True - assert_raises(KeyError, ehdr.set_intent, 'no intention') - assert_raises(KeyError, ehdr.set_intent, 'no intention', - allow_unknown=True) - assert_raises(KeyError, ehdr.set_intent, 32767) + with pytest.raises(KeyError): + ehdr.set_intent('no intention') + with pytest.raises(KeyError): + ehdr.set_intent('no intention', allow_unknown=True) + with pytest.raises(KeyError): + ehdr.set_intent(32767) # too many parameters - assert_raises(HeaderDataError, ehdr.set_intent, 't test', (10, 10)) + with pytest.raises(HeaderDataError): + ehdr.set_intent('t test', (10, 10)) # too few parameters - assert_raises(HeaderDataError, ehdr.set_intent, 'f test', (10,)) + with pytest.raises(HeaderDataError): + ehdr.set_intent('f test', (10,)) # check unset parameters are set to 0, and name to '' ehdr.set_intent('t test') - assert_equal((ehdr['intent_p1'], ehdr['intent_p2'], ehdr['intent_p3']), + assert ((ehdr['intent_p1'], ehdr['intent_p2'], ehdr['intent_p3']) == (0, 0, 0)) - assert_equal(ehdr['intent_name'], b'') + assert ehdr['intent_name'] == b'' ehdr.set_intent('t test', (10,)) - assert_equal((ehdr['intent_p2'], ehdr['intent_p3']), (0, 0)) + assert (ehdr['intent_p2'], ehdr['intent_p3']) == (0, 0) # store intent that is not in nifti1.intent_codes recoder ehdr.set_intent(9999, allow_unknown=True) - assert_equal(ehdr.get_intent(), ('unknown code 9999', (), '')) - assert_equal(ehdr.get_intent('code'), (9999, (), '')) + assert ehdr.get_intent() == ('unknown code 9999', (), '') + assert ehdr.get_intent('code') == (9999, (), '') ehdr.set_intent(9999, name='custom intent', allow_unknown=True) - assert_equal(ehdr.get_intent(), - ('unknown code 9999', (), 'custom intent')) - assert_equal(ehdr.get_intent('code'), (9999, (), 'custom intent')) + assert ehdr.get_intent() == ('unknown code 9999', (), 'custom intent') + assert ehdr.get_intent('code') == (9999, (), 'custom intent') # store unknown intent with parameters. set_intent will set the # parameters, but get_intent won't return them ehdr.set_intent(code=9999, params=(1, 2, 3), allow_unknown=True) - assert_equal(ehdr.get_intent(), ('unknown code 9999', (), '')) - assert_equal(ehdr.get_intent('code'), (9999, (), '')) + assert ehdr.get_intent() == ('unknown code 9999', (), '') + assert ehdr.get_intent('code') == (9999, (), '') # unknown intent requires either zero, or three, parameters - assert_raises(HeaderDataError, ehdr.set_intent, 999, (1,), - allow_unknown=True) - assert_raises(HeaderDataError, ehdr.set_intent, 999, (1,2), - allow_unknown=True) + with pytest.raises(HeaderDataError): + ehdr.set_intent(999, (1,), allow_unknown=True) + with pytest.raises(HeaderDataError): + ehdr.set_intent(999, (1,2), allow_unknown=True) def test_set_slice_times(self): hdr = self.header_class() @@ -640,69 +652,68 @@ def test_set_slice_times(self): hdr.set_data_shape([1, 1, 7]) hdr.set_slice_duration(0.1) times = [0] * 6 - assert_raises(HeaderDataError, hdr.set_slice_times, times) + pytest.raises(HeaderDataError, hdr.set_slice_times, times) times = [None] * 7 - assert_raises(HeaderDataError, hdr.set_slice_times, times) + pytest.raises(HeaderDataError, hdr.set_slice_times, times) times = [None, 0, 1, None, 3, 4, None] - assert_raises(HeaderDataError, hdr.set_slice_times, times) + pytest.raises(HeaderDataError, hdr.set_slice_times, times) times = [None, 0, 1, 2.1, 3, 4, None] - assert_raises(HeaderDataError, hdr.set_slice_times, times) + pytest.raises(HeaderDataError, hdr.set_slice_times, times) times = [None, 0, 4, 3, 2, 1, None] - assert_raises(HeaderDataError, hdr.set_slice_times, times) + pytest.raises(HeaderDataError, hdr.set_slice_times, times) times = [0, 1, 2, 3, 4, 5, 6] hdr.set_slice_times(times) - assert_equal(hdr['slice_code'], 1) - assert_equal(hdr['slice_start'], 0) - assert_equal(hdr['slice_end'], 6) - assert_equal(hdr['slice_duration'], 1.0) + assert hdr['slice_code'] == 1 + assert hdr['slice_start'] == 0 + assert hdr['slice_end'] == 6 + assert hdr['slice_duration'] == 1.0 times = [None, 0, 1, 2, 3, 4, None] hdr.set_slice_times(times) - assert_equal(hdr['slice_code'], 1) - assert_equal(hdr['slice_start'], 1) - assert_equal(hdr['slice_end'], 5) - assert_equal(hdr['slice_duration'], 1.0) + assert hdr['slice_code'] == 1 + assert hdr['slice_start'] == 1 + assert hdr['slice_end'] == 5 + assert hdr['slice_duration'] == 1.0 times = [None, 0.4, 0.3, 0.2, 0.1, 0, None] hdr.set_slice_times(times) - assert_true(np.allclose(hdr['slice_duration'], 0.1)) + assert np.allclose(hdr['slice_duration'], 0.1) times = [None, 4, 3, 2, 1, 0, None] hdr.set_slice_times(times) - assert_equal(hdr['slice_code'], 2) + assert hdr['slice_code'] == 2 times = [None, 0, 3, 1, 4, 2, None] hdr.set_slice_times(times) - assert_equal(hdr['slice_code'], 3) + assert hdr['slice_code'] == 3 times = [None, 2, 4, 1, 3, 0, None] hdr.set_slice_times(times) - assert_equal(hdr['slice_code'], 4) + assert hdr['slice_code'] == 4 times = [None, 2, 0, 3, 1, 4, None] hdr.set_slice_times(times) - assert_equal(hdr['slice_code'], 5) + assert hdr['slice_code'] == 5 times = [None, 4, 1, 3, 0, 2, None] hdr.set_slice_times(times) - assert_equal(hdr['slice_code'], 6) + assert hdr['slice_code'] == 6 def test_xyzt_units(self): hdr = self.header_class() - assert_equal(hdr.get_xyzt_units(), ('unknown', 'unknown')) + assert hdr.get_xyzt_units() == ('unknown', 'unknown') hdr.set_xyzt_units('mm', 'sec') - assert_equal(hdr.get_xyzt_units(), ('mm', 'sec')) + assert hdr.get_xyzt_units() == ('mm', 'sec') hdr.set_xyzt_units() - assert_equal(hdr.get_xyzt_units(), ('unknown', 'unknown')) + assert hdr.get_xyzt_units() == ('unknown', 'unknown') def test_recoded_fields(self): hdr = self.header_class() - assert_equal(hdr.get_value_label('qform_code'), 'unknown') + assert hdr.get_value_label('qform_code') == 'unknown' hdr['qform_code'] = 3 - assert_equal(hdr.get_value_label('qform_code'), 'talairach') - assert_equal(hdr.get_value_label('sform_code'), 'unknown') + assert hdr.get_value_label('qform_code') == 'talairach' + assert hdr.get_value_label('sform_code') == 'unknown' hdr['sform_code'] = 3 - assert_equal(hdr.get_value_label('sform_code'), 'talairach') - assert_equal(hdr.get_value_label('intent_code'), 'none') + assert hdr.get_value_label('sform_code') == 'talairach' + assert hdr.get_value_label('intent_code') == 'none' hdr.set_intent('t test', (10,), name='some score') - assert_equal(hdr.get_value_label('intent_code'), 't test') - assert_equal(hdr.get_value_label('slice_code'), 'unknown') + assert hdr.get_value_label('intent_code') == 't test' + assert hdr.get_value_label('slice_code') == 'unknown' hdr['slice_code'] = 4 # alternating decreasing - assert_equal(hdr.get_value_label('slice_code'), - 'alternating decreasing') + assert hdr.get_value_label('slice_code') == 'alternating decreasing' def unshear_44(affine): @@ -721,9 +732,9 @@ class TestNifti1SingleHeader(TestNifti1PairHeader): def test_empty(self): tana.TestAnalyzeHeader.test_empty(self) hdr = self.header_class() - assert_equal(hdr['magic'], hdr.single_magic) - assert_equal(hdr['scl_slope'], 1) - assert_equal(hdr['vox_offset'], 0) + assert hdr['magic'] == hdr.single_magic + assert hdr['scl_slope'] == 1 + assert hdr['vox_offset'] == 0 def test_binblock_is_file(self): # Override test that binary string is the same as the file on disk; in @@ -732,7 +743,7 @@ def test_binblock_is_file(self): hdr = self.header_class() str_io = BytesIO() hdr.write_to(str_io) - assert_equal(str_io.getvalue(), hdr.binaryblock + b'\x00' * 4) + assert str_io.getvalue() == hdr.binaryblock + b'\x00' * 4 def test_float128(self): hdr = self.header_class() @@ -740,9 +751,10 @@ def test_float128(self): ld_dt = np.dtype(np.longdouble) if have_binary128() or ld_dt == np.dtype(np.float64): hdr.set_data_dtype(np.longdouble) - assert_equal(hdr.get_data_dtype(), ld_dt) + assert hdr.get_data_dtype() == ld_dt else: - assert_raises(HeaderDataError, hdr.set_data_dtype, np.longdouble) + with pytest.raises(HeaderDataError): + hdr.set_data_dtype(np.longdouble) class TestNifti1Pair(tana.TestAnalyzeImage, tspm.ImageScalingMixin): @@ -792,13 +804,13 @@ def test_qform_cycle(self): # None affine img = img_klass(np.zeros((2, 3, 4)), None) hdr_back = self._qform_rt(img).header - assert_equal(hdr_back['qform_code'], 3) - assert_equal(hdr_back['sform_code'], 4) + assert hdr_back['qform_code'] == 3 + assert hdr_back['sform_code'] == 4 # Try non-None affine img = img_klass(np.zeros((2, 3, 4)), np.eye(4)) hdr_back = self._qform_rt(img).header - assert_equal(hdr_back['qform_code'], 3) - assert_equal(hdr_back['sform_code'], 4) + assert hdr_back['qform_code'] == 3 + assert hdr_back['sform_code'] == 4 # Modify affine in-place - does it hold? img.affine[0, 0] = 9 img.to_file_map() @@ -818,8 +830,8 @@ def test_header_update_affine(self): hdr.set_qform(aff, 2) hdr.set_sform(aff, 2) img.update_header() - assert_equal(hdr['sform_code'], 2) - assert_equal(hdr['qform_code'], 2) + assert hdr['sform_code'] == 2 + assert hdr['qform_code'] == 2 def test_set_qform(self): img = self.image_class(np.zeros((2, 3, 4)), @@ -835,12 +847,12 @@ def test_set_qform(self): # Set qform using new_affine img.set_qform(new_affine, 1) assert_array_almost_equal(img.get_qform(), new_affine) - assert_equal(hdr['qform_code'], 1) + assert hdr['qform_code'] == 1 # Image get is same as header get assert_array_almost_equal(img.get_qform(), new_affine) # Coded version of get gets same information qaff, code = img.get_qform(coded=True) - assert_equal(code, 1) + assert code == 1 assert_array_almost_equal(qaff, new_affine) # Image affine now reset to best affine (which is sform) assert_array_almost_equal(img.affine, hdr.get_best_affine()) @@ -852,7 +864,7 @@ def test_set_qform(self): assert_array_almost_equal(hdr.get_zooms(), [1.1, 1.1, 1.1]) img.set_qform(None) qaff, code = img.get_qform(coded=True) - assert_equal((qaff, code), (None, 0)) + assert (qaff, code) == (None, 0) assert_array_almost_equal(hdr.get_zooms(), [1.1, 1.1, 1.1]) # Best affine similarly assert_array_almost_equal(img.affine, hdr.get_best_affine()) @@ -860,14 +872,16 @@ def test_set_qform(self): img.set_sform(None) img.set_qform(new_affine, 1) qaff, code = img.get_qform(coded=True) - assert_equal(code, 1) + assert code == 1 assert_array_almost_equal(img.affine, new_affine) new_affine[0, 1] = 2 # If affine has has shear, should raise Error if strip_shears=False img.set_qform(new_affine, 2) - assert_raises(HeaderDataError, img.set_qform, new_affine, 2, False) + with pytest.raises(HeaderDataError): + img.set_qform(new_affine, 2, False) # Unexpected keyword raises error - assert_raises(TypeError, img.get_qform, strange=True) + with pytest.raises(TypeError): + img.get_qform(strange=True) # updating None affine, None header does not work, because None header # results in setting the sform to default img = self.image_class(np.zeros((2, 3, 4)), None) @@ -889,16 +903,16 @@ def test_set_sform(self): img.affine[:] = aff_affine assert_array_almost_equal(img.affine, aff_affine) # Sform, Qform codes are 'aligned', 'unknown' by default - assert_equal((hdr['sform_code'], hdr['qform_code']), (2, 0)) + assert (hdr['sform_code'], hdr['qform_code']) == (2, 0) # Set sform using new_affine when qform is 0 img.set_sform(new_affine, 1) - assert_equal(hdr['sform_code'], 1) + assert hdr['sform_code'] == 1 assert_array_almost_equal(hdr.get_sform(), new_affine) # Image get is same as header get assert_array_almost_equal(img.get_sform(), new_affine) # Coded version gives same result saff, code = img.get_sform(coded=True) - assert_equal(code, 1) + assert code == 1 assert_array_almost_equal(saff, new_affine) # Because we've reset the sform with update_affine, the affine changes assert_array_almost_equal(img.affine, hdr.get_best_affine()) @@ -915,22 +929,23 @@ def test_set_sform(self): img.set_qform(qform_affine, 1) img.set_sform(new_affine, 1) saff, code = img.get_sform(coded=True) - assert_equal(code, 1) + assert code == 1 assert_array_almost_equal(saff, new_affine) assert_array_almost_equal(img.affine, new_affine) # zooms follow qform assert_array_almost_equal(hdr.get_zooms(), [1.2, 1.2, 1.2]) # Clear sform using None, best_affine should fall back on qform img.set_sform(None) - assert_equal(hdr['sform_code'], 0) - assert_equal(hdr['qform_code'], 1) + assert hdr['sform_code'] == 0 + assert hdr['qform_code'] == 1 # Sform holds previous affine from last set assert_array_almost_equal(hdr.get_sform(), saff) # Image affine follows qform assert_array_almost_equal(img.affine, qform_affine) assert_array_almost_equal(hdr.get_best_affine(), img.affine) # Unexpected keyword raises error - assert_raises(TypeError, img.get_sform, strange=True) + with pytest.raises(TypeError): + img.get_sform(strange=True) # updating None affine should also work img = self.image_class(np.zeros((2, 3, 4)), None) new_affine = np.eye(4) @@ -971,8 +986,8 @@ def test_load_save(self): data = np.arange(np.prod(shape), dtype=npt).reshape(shape) affine = np.diag([1, 2, 3, 1]) img = IC(data, affine) - assert_equal(img.header.get_data_offset(), 0) - assert_equal(img.shape, shape) + assert img.header.get_data_offset() == 0 + assert img.shape == shape img.set_data_dtype(npt) img2 = bytesio_round_trip(img) assert_array_equal(img2.get_fdata(), data) @@ -981,11 +996,11 @@ def test_load_save(self): fname = os.path.join(tmpdir, 'test' + img_ext + ext) img.to_filename(fname) img3 = IC.load(fname) - assert_true(isinstance(img3, img.__class__)) + assert isinstance(img3, img.__class__) assert_array_equal(img3.get_fdata(), data) - assert_equal(img3.header, img.header) - assert_true(isinstance(np.asanyarray(img3.dataobj), - np.memmap if ext == '' else np.ndarray)) + assert img3.header == img.header + assert isinstance(np.asanyarray(img3.dataobj), + np.memmap if ext == '' else np.ndarray) # del to avoid windows errors of form 'The process cannot # access the file because it is being used' del img3 @@ -1027,8 +1042,8 @@ def test_affines_init(self): # Default is sform set, qform not set img = IC(arr, aff) hdr = img.header - assert_equal(hdr['qform_code'], 0) - assert_equal(hdr['sform_code'], 2) + assert hdr['qform_code'] == 0 + assert hdr['sform_code'] == 2 assert_array_equal(hdr.get_zooms(), [2, 3, 4]) # This is also true for affines with header passed qaff = np.diag([3, 4, 5, 1]) @@ -1039,16 +1054,16 @@ def test_affines_init(self): img = IC(arr, aff, hdr) new_hdr = img.header # Again affine is sort of anonymous space - assert_equal(new_hdr['qform_code'], 0) - assert_equal(new_hdr['sform_code'], 2) + assert new_hdr['qform_code'] == 0 + assert new_hdr['sform_code'] == 2 assert_array_equal(new_hdr.get_sform(), aff) assert_array_equal(new_hdr.get_zooms(), [2, 3, 4]) # But if no affine passed, codes and matrices stay the same img = IC(arr, None, hdr) new_hdr = img.header - assert_equal(new_hdr['qform_code'], 1) # scanner + assert new_hdr['qform_code'] == 1 # scanner assert_array_equal(new_hdr.get_qform(), qaff) - assert_equal(new_hdr['sform_code'], 3) # Still talairach + assert new_hdr['sform_code'] == 3 # Still talairach assert_array_equal(new_hdr.get_sform(), saff) # Pixdims as in the original header assert_array_equal(new_hdr.get_zooms(), [3, 4, 5]) @@ -1057,13 +1072,13 @@ def test_read_no_extensions(self): IC = self.image_class arr = np.arange(24).reshape((2, 3, 4)) img = IC(arr, np.eye(4)) - assert_equal(len(img.header.extensions), 0) + assert len(img.header.extensions) == 0 img_rt = bytesio_round_trip(img) - assert_equal(len(img_rt.header.extensions), 0) + assert len(img_rt.header.extensions) == 0 # Check simple round trip with large offset img.header.set_data_offset(1024) img_rt = bytesio_round_trip(img) - assert_equal(len(img_rt.header.extensions), 0) + assert len(img_rt.header.extensions) == 0 def _get_raw_scaling(self, hdr): return hdr['scl_slope'], hdr['scl_inter'] @@ -1094,34 +1109,35 @@ def test_offset_errors(self): IC = self.image_class arr = np.arange(24).reshape((2, 3, 4)) img = IC(arr, np.eye(4)) - assert_equal(img.header.get_data_offset(), 0) + assert img.header.get_data_offset() == 0 # Saving with zero offset is OK img_rt = bytesio_round_trip(img) - assert_equal(img_rt.header.get_data_offset(), 0) + assert img_rt.header.get_data_offset() == 0 # Saving with too low offset explicitly set gives error fm = bytesio_filemap(IC) img.header.set_data_offset(16) - assert_raises(HeaderDataError, img.to_file_map, fm) + with pytest.raises(HeaderDataError): + img.to_file_map(fm) def test_extension_basics(): raw = '123' ext = Nifti1Extension('comment', raw) - assert_true(ext.get_sizeondisk() == 16) - assert_true(ext.get_content() == raw) - assert_true(ext.get_code() == 6) + assert ext.get_sizeondisk() == 16 + assert ext.get_content() == raw + assert ext.get_code() == 6 # Test that extensions already aligned to 16 bytes are not padded ext = Nifti1Extension('comment', b'x' * 24) - assert_true(ext.get_sizeondisk() == 32) + assert ext.get_sizeondisk() == 32 def test_ext_eq(): ext = Nifti1Extension('comment', '123') - assert_true(ext == ext) - assert_false(ext != ext) + assert ext == ext + assert not ext != ext ext2 = Nifti1Extension('comment', '124') - assert_false(ext == ext2) - assert_true(ext != ext2) + assert ext != ext2 + assert not ext == ext2 def test_extension_codes(): @@ -1132,12 +1148,12 @@ def test_extension_codes(): def test_extension_list(): ext_c0 = Nifti1Extensions() ext_c1 = Nifti1Extensions() - assert_equal(ext_c0, ext_c1) + assert ext_c0 == ext_c1 ext = Nifti1Extension('comment', '123') ext_c1.append(ext) - assert_false(ext_c0 == ext_c1) + assert not ext_c0 == ext_c1 ext_c0.append(ext) - assert_true(ext_c0 == ext_c1) + assert ext_c0 == ext_c1 def test_extension_io(): @@ -1146,23 +1162,23 @@ def test_extension_io(): ext1.write_to(bio, False) bio.seek(0) ebacks = Nifti1Extensions.from_fileobj(bio, -1, False) - assert_equal(len(ebacks), 1) - assert_equal(ext1, ebacks[0]) + assert len(ebacks) == 1 + assert ext1 == ebacks[0] # Check the start is what we expect exp_dtype = np.dtype([('esize', 'i4'), ('ecode', 'i4')]) bio.seek(0) buff = np.ndarray(shape=(), dtype=exp_dtype, buffer=bio.read(16)) - assert_equal(buff['esize'], 32) - assert_equal(buff['ecode'], 6) + assert buff['esize'] == 32 + assert buff['ecode'] == 6 # Try another extension on top bio.seek(32) ext2 = Nifti1Extension(6, b'Comment') ext2.write_to(bio, False) bio.seek(0) ebacks = Nifti1Extensions.from_fileobj(bio, -1, False) - assert_equal(len(ebacks), 2) - assert_equal(ext1, ebacks[0]) - assert_equal(ext2, ebacks[1]) + assert len(ebacks) == 2 + assert ext1 == ebacks[0] + assert ext2 == ebacks[1] # Rewrite but deliberately setting esize wrongly bio.truncate(0) bio.seek(0) @@ -1178,11 +1194,11 @@ def test_extension_io(): bio.seek(0) with warnings.catch_warnings(record=True) as warns: ebacks = Nifti1Extensions.from_fileobj(bio, -1, False) - assert_equal(len(warns), 1) - assert_equal(warns[0].category, UserWarning) - assert_equal(len(ebacks), 2) - assert_equal(ext1, ebacks[0]) - assert_equal(ext2, ebacks[1]) + assert len(warns) == 1 + assert warns[0].category == UserWarning + assert len(ebacks) == 2 + assert ext1 == ebacks[0] + assert ext2 == ebacks[1] def test_nifti_extensions(): @@ -1190,25 +1206,25 @@ def test_nifti_extensions(): # basic checks of the available extensions hdr = nim.header exts_container = hdr.extensions - assert_equal(len(exts_container), 2) - assert_equal(exts_container.count('comment'), 2) - assert_equal(exts_container.count('afni'), 0) - assert_equal(exts_container.get_codes(), [6, 6]) - assert_equal((exts_container.get_sizeondisk()) % 16, 0) + assert len(exts_container) == 2 + assert exts_container.count('comment') == 2 + assert exts_container.count('afni') == 0 + assert exts_container.get_codes() == [6, 6] + assert (exts_container.get_sizeondisk()) % 16 == 0 # first extension should be short one - assert_equal(exts_container[0].get_content(), b'extcomment1') + assert exts_container[0].get_content() == b'extcomment1' # add one afniext = Nifti1Extension('afni', '') exts_container.append(afniext) - assert_true(exts_container.get_codes() == [6, 6, 4]) - assert_true(exts_container.count('comment') == 2) - assert_true(exts_container.count('afni') == 1) - assert_true((exts_container.get_sizeondisk()) % 16 == 0) + assert exts_container.get_codes() == [6, 6, 4] + assert exts_container.count('comment') == 2 + assert exts_container.count('afni') == 1 + assert (exts_container.get_sizeondisk()) % 16 == 0 # delete one del exts_container[1] - assert_true(exts_container.get_codes() == [6, 4]) - assert_true(exts_container.count('comment') == 1) - assert_true(exts_container.count('afni') == 1) + assert exts_container.get_codes() == [6, 4] + assert exts_container.count('comment') == 1 + assert exts_container.count('afni') == 1 @dicom_test @@ -1219,47 +1235,47 @@ def test_nifti_dicom_extension(): # create an empty dataset if no content provided (to write a new header) dcmext = Nifti1DicomExtension(2, b'') - assert_equal(dcmext.get_content().__class__, pydicom.dataset.Dataset) - assert_equal(len(dcmext.get_content().values()), 0) + assert dcmext.get_content().__class__ == pydicom.dataset.Dataset + assert len(dcmext.get_content().values()) == 0 # create an empty dataset if no content provided (to write a new header) dcmext = Nifti1DicomExtension(2, None) - assert_equal(dcmext.get_content().__class__, pydicom.dataset.Dataset) - assert_equal(len(dcmext.get_content().values()), 0) + assert dcmext.get_content().__class__ == pydicom.dataset.Dataset + assert len(dcmext.get_content().values()) == 0 # use a dataset if provided ds = pydicom.dataset.Dataset() ds.add_new((0x10, 0x20), 'LO', 'NiPy') dcmext = Nifti1DicomExtension(2, ds) - assert_equal(dcmext.get_content().__class__, pydicom.dataset.Dataset) - assert_equal(len(dcmext.get_content().values()), 1) - assert_equal(dcmext.get_content().PatientID, 'NiPy') + assert dcmext.get_content().__class__ == pydicom.dataset.Dataset + assert len(dcmext.get_content().values()) == 1 + assert dcmext.get_content().PatientID == 'NiPy' # create a single dicom tag (Patient ID, [0010,0020]) with Explicit VR / LE dcmbytes_explicit = struct.pack('2H2sH4s', 0x10, 0x20, @@ -1267,30 +1283,31 @@ def test_nifti_dicom_extension(): 'NiPy'.encode('utf-8')) hdr_be = Nifti1Header(endianness='>') # Big Endian Nifti1Header dcmext = Nifti1DicomExtension(2, dcmbytes_explicit_be, parent_hdr=hdr_be) - assert_equal(dcmext.__class__, Nifti1DicomExtension) - assert_equal(dcmext._guess_implicit_VR(), False) - assert_equal(dcmext.get_code(), 2) - assert_equal(dcmext.get_content().PatientID, 'NiPy') - assert_equal(dcmext.get_content()[0x10, 0x20].value, 'NiPy') - assert_equal(len(dcmext.get_content().values()), 1) - assert_equal(dcmext._mangle(dcmext.get_content()), dcmbytes_explicit_be) - assert_equal(dcmext.get_sizeondisk() % 16, 0) + assert dcmext.__class__ == Nifti1DicomExtension + assert dcmext._guess_implicit_VR() is False + assert dcmext.get_code() == 2 + assert dcmext.get_content().PatientID == 'NiPy' + assert dcmext.get_content()[0x10, 0x20].value == 'NiPy' + assert len(dcmext.get_content().values()) == 1 + assert dcmext._mangle(dcmext.get_content()) == dcmbytes_explicit_be + assert dcmext.get_sizeondisk() % 16 == 0 # Check that a dicom dataset is written w/ BE encoding when not created # using BE bytestring when given a BE nifti header dcmext = Nifti1DicomExtension(2, ds, parent_hdr=hdr_be) - assert_equal(dcmext._mangle(dcmext.get_content()), dcmbytes_explicit_be) + assert dcmext._mangle(dcmext.get_content()) == dcmbytes_explicit_be # dicom extension access from nifti extensions - assert_equal(exts_container.count('dicom'), 0) + assert exts_container.count('dicom') == 0 exts_container.append(dcmext) - assert_equal(exts_container.count('dicom'), 1) - assert_equal(exts_container.get_codes(), [6, 6, 2]) - assert_equal(dcmext._mangle(dcmext.get_content()), dcmbytes_explicit_be) - assert_equal(dcmext.get_sizeondisk() % 16, 0) + assert exts_container.count('dicom') == 1 + assert exts_container.get_codes() == [6, 6, 2] + assert dcmext._mangle(dcmext.get_content()) == dcmbytes_explicit_be + assert dcmext.get_sizeondisk() % 16 == 0 # creating an extension with bad content should raise - assert_raises(TypeError, Nifti1DicomExtension, 2, 0) + with pytest.raises(TypeError): + Nifti1DicomExtension(2, 0) class TestNifti1General(object): @@ -1309,38 +1326,38 @@ def test_loadsave_cycle(self): # ensure we have extensions hdr = nim.header exts_container = hdr.extensions - assert_true(len(exts_container) > 0) + assert len(exts_container) > 0 # write into the air ;-) lnim = bytesio_round_trip(nim) hdr = lnim.header lexts_container = hdr.extensions - assert_equal(exts_container, lexts_container) + assert exts_container == lexts_container # build int16 image data = np.ones((2, 3, 4, 5), dtype='int16') img = self.single_class(data, np.eye(4)) hdr = img.header - assert_equal(hdr.get_data_dtype(), np.int16) + assert hdr.get_data_dtype() == np.int16 # default should have no scaling assert_array_equal(hdr.get_slope_inter(), (None, None)) # set scaling hdr.set_slope_inter(2, 8) - assert_equal(hdr.get_slope_inter(), (2, 8)) + assert hdr.get_slope_inter() == (2, 8) # now build new image with updated header wnim = self.single_class(data, np.eye(4), header=hdr) - assert_equal(wnim.get_data_dtype(), np.int16) + assert wnim.get_data_dtype() == np.int16 # Header scaling reset to default by image creation - assert_equal(wnim.header.get_slope_inter(), (None, None)) + assert wnim.header.get_slope_inter() == (None, None) # But we can reset it again after image creation wnim.header.set_slope_inter(2, 8) - assert_equal(wnim.header.get_slope_inter(), (2, 8)) + assert wnim.header.get_slope_inter() == (2, 8) # write into the air again ;-) lnim = bytesio_round_trip(wnim) - assert_equal(lnim.get_data_dtype(), np.int16) + assert lnim.get_data_dtype() == np.int16 # Scaling applied assert_array_equal(lnim.get_fdata(), data * 2. + 8.) # slope, inter reset by image creation, but saved in proxy - assert_equal(lnim.header.get_slope_inter(), (None, None)) - assert_equal((lnim.dataobj.slope, lnim.dataobj.inter), (2, 8)) + assert lnim.header.get_slope_inter() == (None, None) + assert (lnim.dataobj.slope, lnim.dataobj.inter) == (2, 8) def test_load(self): # test module level load. We try to load a nii and an .img and a .hdr @@ -1371,7 +1388,7 @@ def test_float_int_min_max(self): img = self.single_class(arr, aff) img_back = bytesio_round_trip(img) arr_back_sc = img_back.get_fdata() - assert_true(np.allclose(arr, arr_back_sc)) + assert np.allclose(arr, arr_back_sc) def test_float_int_spread(self): # Test rounding error for spread of values @@ -1392,7 +1409,7 @@ def test_float_int_spread(self): # Simulate allclose test with large atol diff = np.abs(arr_t - arr_back_sc) rdiff = diff / np.abs(arr_t) - assert_true(np.all((diff <= max_miss) | (rdiff <= 1e-5))) + assert np.all((diff <= max_miss) | (rdiff <= 1e-5)) def test_rt_bias(self): # Check for bias in round trip @@ -1415,7 +1432,7 @@ def test_rt_bias(self): inter) # Hokey use of max_miss as a std estimate bias_thresh = np.max([max_miss / np.sqrt(count), eps]) - assert_true(np.abs(bias) < bias_thresh) + assert np.abs(bias) < bias_thresh def test_reoriented_dim_info(self): # Check that dim_info is reoriented correctly @@ -1445,7 +1462,7 @@ def test_reoriented_dim_info(self): new_fdir = dirs[new_freq] if new_freq is not None else None new_pdir = dirs[new_phas] if new_phas is not None else None new_sdir = dirs[new_slic] if new_slic is not None else None - assert_equal((new_fdir, new_pdir, new_sdir), (fdir, pdir, sdir)) + assert (new_fdir, new_pdir, new_sdir) == (fdir, pdir, sdir) @runif_extra_has('slow') @@ -1459,6 +1476,6 @@ def test_large_nifti1(): del img data = load('test.nii.gz').get_fdata() # Check that the data are all ones - assert_equal(image_shape, data.shape) + assert image_shape == data.shape n_ones = np.sum((data == 1.)) - assert_equal(np.prod(image_shape), n_ones) + assert np.prod(image_shape) == n_ones diff --git a/nibabel/tests/test_nifti2.py b/nibabel/tests/test_nifti2.py index 730e30a689..ca6e7d8125 100644 --- a/nibabel/tests/test_nifti2.py +++ b/nibabel/tests/test_nifti2.py @@ -19,7 +19,6 @@ from .test_nifti1 import (TestNifti1PairHeader, TestNifti1SingleHeader, TestNifti1Pair, TestNifti1Image, TestNifti1General) -from nose.tools import assert_equal from numpy.testing import assert_array_equal from ..testing import data_path @@ -50,16 +49,14 @@ def test_eol_check(self): hdr['eol_check'] = 0 fhdr, message, raiser = self.log_chk(hdr, 20) assert_array_equal(fhdr['eol_check'], good_eol) - assert_equal(message, - 'EOL check all 0; ' - 'setting EOL check to 13, 10, 26, 10') + assert message == 'EOL check all 0; setting EOL check to 13, 10, 26, 10' hdr['eol_check'] = (13, 10, 0, 10) fhdr, message, raiser = self.log_chk(hdr, 40) assert_array_equal(fhdr['eol_check'], good_eol) - assert_equal(message, - 'EOL check not 0 or 13, 10, 26, 10; ' - 'data may be corrupted by EOL conversion; ' - 'setting EOL check to 13, 10, 26, 10') + assert (message == + 'EOL check not 0 or 13, 10, 26, 10; ' + 'data may be corrupted by EOL conversion; ' + 'setting EOL check to 13, 10, 26, 10') class TestNifti2PairHeader(_Nifti2Mixin, TestNifti1PairHeader): @@ -110,6 +107,6 @@ def test_nifti12_conversion(): in_hdr.set_data_dtype(dtype_type) in_hdr.extensions[:] = [ext1, ext2] out_hdr = out_type.from_header(in_hdr) - assert_equal(out_hdr.get_data_shape(), shape) - assert_equal(out_hdr.get_data_dtype(), dtype_type) - assert_equal(in_hdr.extensions, out_hdr.extensions) + assert out_hdr.get_data_shape() == shape + assert out_hdr.get_data_dtype() == dtype_type + assert in_hdr.extensions == out_hdr.extensions diff --git a/nibabel/tests/test_openers.py b/nibabel/tests/test_openers.py index 6d1baab734..85a8f4a0a7 100644 --- a/nibabel/tests/test_openers.py +++ b/nibabel/tests/test_openers.py @@ -18,9 +18,9 @@ from ..tmpdirs import InTemporaryDirectory from ..volumeutils import BinOpener +import unittest from unittest import mock -from nose.tools import (assert_true, assert_false, assert_equal, - assert_not_equal, assert_raises) +import pytest from ..testing import error_warnings @@ -41,24 +41,24 @@ def read(self): def test_Opener(): # Test default mode is 'rb' fobj = Opener(__file__) - assert_equal(fobj.mode, 'rb') + assert fobj.mode == 'rb' fobj.close() # That it's a context manager with Opener(__file__) as fobj: - assert_equal(fobj.mode, 'rb') + assert fobj.mode == 'rb' # That we can set the mode with Opener(__file__, 'r') as fobj: - assert_equal(fobj.mode, 'r') + assert fobj.mode == 'r' # with keyword arguments with Opener(__file__, mode='r') as fobj: - assert_equal(fobj.mode, 'r') + assert fobj.mode == 'r' # fileobj returns fileobj passed through message = b"Wine? Wouldn't you?" for obj in (BytesIO(message), Lunk(message)): with Opener(obj) as fobj: - assert_equal(fobj.read(), message) + assert fobj.read() == message # Which does not close the object - assert_false(obj.closed) + assert not obj.closed # mode is gently ignored fobj = Opener(obj, mode='r') @@ -77,31 +77,34 @@ def test_Opener_various(): sobj): with Opener(input, 'wb') as fobj: fobj.write(message) - assert_equal(fobj.tell(), len(message)) + assert fobj.tell() == len(message) if input == sobj: input.seek(0) with Opener(input, 'rb') as fobj: message_back = fobj.read() - assert_equal(message, message_back) + assert message == message_back if input == sobj: # Fileno is unsupported for BytesIO - assert_raises(UnsupportedOperation, fobj.fileno) + with pytest.raises(UnsupportedOperation): + fobj.fileno() elif input.endswith('.bz2') and not bz2_fileno: - assert_raises(AttributeError, fobj.fileno) + with pytest.raises(AttributeError): + fobj.fileno() # indexed gzip is used by default, and drops file # handles by default, so we don't have a fileno. elif input.endswith('gz') and HAVE_INDEXED_GZIP and \ StrictVersion(igzip.__version__) >= StrictVersion('0.7.0'): - assert_raises(igzip.NoHandleError, fobj.fileno) + with pytest.raises(igzip.NoHandleError): + fobj.fileno() else: # Just check there is a fileno - assert_not_equal(fobj.fileno(), 0) + assert fobj.fileno() != 0 def test_BinOpener(): with error_warnings(): - assert_raises(DeprecationWarning, - BinOpener, 'test.txt', 'r') + with pytest.raises(DeprecationWarning): + BinOpener('test.txt', 'r') class MockIndexedGzipFile(GzipFile): @@ -159,22 +162,16 @@ def test_Opener_gzip_type(): assert isinstance(Opener(fname, **kwargs).fobj, expected) -class TestImageOpener: - - def setUp(self): - self.compress_ext_map = ImageOpener.compress_ext_map.copy() - - def teardown(self): - ImageOpener.compress_ext_map = self.compress_ext_map - +class TestImageOpener(unittest.TestCase): def test_vanilla(self): # Test that ImageOpener does add '.mgz' as gzipped file type with InTemporaryDirectory(): with ImageOpener('test.gz', 'w') as fobj: - assert_true(hasattr(fobj.fobj, 'compress')) + assert hasattr(fobj.fobj, 'compress') with ImageOpener('test.mgz', 'w') as fobj: - assert_true(hasattr(fobj.fobj, 'compress')) + assert hasattr(fobj.fobj, 'compress') + @mock.patch.dict('nibabel.openers.ImageOpener.compress_ext_map') def test_new_association(self): def file_opener(fileish, mode): return open(fileish, mode) @@ -182,16 +179,16 @@ def file_opener(fileish, mode): # Add the association n_associations = len(ImageOpener.compress_ext_map) ImageOpener.compress_ext_map['.foo'] = (file_opener, ('mode',)) - assert_equal(n_associations + 1, len(ImageOpener.compress_ext_map)) - assert_true('.foo' in ImageOpener.compress_ext_map) + assert n_associations + 1 == len(ImageOpener.compress_ext_map) + assert '.foo' in ImageOpener.compress_ext_map with InTemporaryDirectory(): with ImageOpener('test.foo', 'w'): pass - assert_true(os.path.exists('test.foo')) + assert os.path.exists('test.foo') # Check this doesn't add anything to parent - assert_false('.foo' in Opener.compress_ext_map) + assert '.foo' not in Opener.compress_ext_map def test_file_like_wrapper(): @@ -199,17 +196,17 @@ def test_file_like_wrapper(): message = b"History of the nude in" sobj = BytesIO() fobj = Opener(sobj) - assert_equal(fobj.tell(), 0) + assert fobj.tell() == 0 fobj.write(message) - assert_equal(fobj.tell(), len(message)) + assert fobj.tell() == len(message) fobj.seek(0) - assert_equal(fobj.tell(), 0) - assert_equal(fobj.read(6), message[:6]) - assert_false(fobj.closed) + assert fobj.tell() == 0 + assert fobj.read(6) == message[:6] + assert not fobj.closed fobj.close() - assert_true(fobj.closed) + assert fobj.closed # Added the fileobj name - assert_equal(fobj.name, None) + assert fobj.name is None def test_compressionlevel(): @@ -236,8 +233,8 @@ class MyOpener(Opener): with open(fname, 'rb') as fobj: my_selves_smaller = fobj.read() sizes[compresslevel] = len(my_selves_smaller) - assert_equal(sizes['default'], sizes[default_val]) - assert_true(sizes[1] > sizes[5]) + assert sizes['default'] == sizes[default_val] + assert sizes[1] > sizes[5] def test_compressed_ext_case(): @@ -256,23 +253,23 @@ class StrictOpener(Opener): with Opener(fname, 'wb') as fobj: fobj.write(contents) with Opener(fname, 'rb') as fobj: - assert_equal(fobj.read(), contents) + assert fobj.read() == contents os.unlink(fname) with StrictOpener(fname, 'wb') as fobj: fobj.write(contents) with StrictOpener(fname, 'rb') as fobj: - assert_equal(fobj.read(), contents) + assert fobj.read() == contents lext = ext.lower() if lext != ext: # extension should not be recognized -> file - assert_true(isinstance(fobj.fobj, file_class)) + assert isinstance(fobj.fobj, file_class) elif lext == 'gz': try: from ..openers import IndexedGzipFile except ImportError: IndexedGzipFile = GzipFile - assert_true(isinstance(fobj.fobj, (GzipFile, IndexedGzipFile))) + assert isinstance(fobj.fobj, (GzipFile, IndexedGzipFile)) else: - assert_true(isinstance(fobj.fobj, BZ2File)) + assert isinstance(fobj.fobj, BZ2File) def test_name(): @@ -287,22 +284,22 @@ def test_name(): lunk): exp_name = input if type(input) == type('') else None with Opener(input, 'wb') as fobj: - assert_equal(fobj.name, exp_name) + assert fobj.name == exp_name def test_set_extensions(): # Test that we can add extensions that are compressed with InTemporaryDirectory(): with Opener('test.gz', 'w') as fobj: - assert_true(hasattr(fobj.fobj, 'compress')) + assert hasattr(fobj.fobj, 'compress') with Opener('test.glrph', 'w') as fobj: - assert_false(hasattr(fobj.fobj, 'compress')) + assert not hasattr(fobj.fobj, 'compress') class MyOpener(Opener): compress_ext_map = Opener.compress_ext_map.copy() compress_ext_map['.glrph'] = Opener.gz_def with MyOpener('test.glrph', 'w') as fobj: - assert_true(hasattr(fobj.fobj, 'compress')) + assert hasattr(fobj.fobj, 'compress') def test_close_if_mine(): @@ -319,11 +316,11 @@ def test_close_if_mine(): # gzip objects have no 'closed' attribute has_closed = hasattr(fobj.fobj, 'closed') if has_closed: - assert_false(fobj.closed) + assert not fobj.closed fobj.close_if_mine() is_str = type(input) is type('') if has_closed: - assert_equal(fobj.closed, is_str) + assert fobj.closed == is_str def test_iter(): @@ -345,11 +342,12 @@ def test_iter(): fobj.write(asbytes(line + os.linesep)) with Opener(input, 'rb') as fobj: for back_line, line in zip(fobj, lines): - assert_equal(asstr(back_line).rstrip(), line) + assert asstr(back_line).rstrip() == line if not does_t: continue with Opener(input, 'rt') as fobj: for back_line, line in zip(fobj, lines): - assert_equal(back_line.rstrip(), line) + assert back_line.rstrip() == line lobj = Opener(Lunk('')) - assert_raises(TypeError, list, lobj) + with pytest.raises(TypeError): + list(lobj) diff --git a/nibabel/tests/test_optpkg.py b/nibabel/tests/test_optpkg.py index 17c0816e70..925180ce6b 100644 --- a/nibabel/tests/test_optpkg.py +++ b/nibabel/tests/test_optpkg.py @@ -7,10 +7,8 @@ import builtins from distutils.version import LooseVersion -from nose import SkipTest -from nose.tools import (assert_true, assert_false, assert_raises, - assert_equal) - +from unittest import SkipTest +import pytest from nibabel.optpkg import optional_package from nibabel.tripwire import TripWire, TripWireError @@ -18,17 +16,19 @@ def assert_good(pkg_name, min_version=None): pkg, have_pkg, setup = optional_package(pkg_name, min_version=min_version) - assert_true(have_pkg) - assert_equal(sys.modules[pkg_name], pkg) - assert_equal(setup(), None) + assert have_pkg + assert sys.modules[pkg_name] == pkg + assert setup() is None def assert_bad(pkg_name, min_version=None): pkg, have_pkg, setup = optional_package(pkg_name, min_version=min_version) - assert_false(have_pkg) - assert_true(isinstance(pkg, TripWire)) - assert_raises(TripWireError, getattr, pkg, 'a_method') - assert_raises(SkipTest, setup) + assert not have_pkg + assert isinstance(pkg, TripWire) + with pytest.raises(TripWireError): + pkg.a_method + with pytest.raises(SkipTest): + setup() def test_basic(): @@ -39,10 +39,10 @@ def test_basic(): # We never have package _not_a_package assert_bad('_not_a_package') - # setup_module imports nose, so make sure we don't disrupt that + # setup_module imports unittest, so make sure we don't disrupt that orig_import = builtins.__import__ def raise_Exception(*args, **kwargs): - if args[0] == 'nose': + if args[0] == 'unittest': return orig_import(*args, **kwargs) raise Exception( "non ImportError could be thrown by some malfunctioning module " @@ -54,7 +54,7 @@ def raise_Exception(*args, **kwargs): def test_versions(): fake_name = '_a_fake_package' fake_pkg = types.ModuleType(fake_name) - assert_false('fake_pkg' in sys.modules) + assert 'fake_pkg' not in sys.modules # Not inserted yet assert_bad(fake_name) try: @@ -77,7 +77,6 @@ def test_versions(): try: pkg.some_method except TripWireError as err: - assert_equal(str(err), - 'These functions need _a_fake_package version >= 3.0') + assert str(err) == 'These functions need _a_fake_package version >= 3.0' finally: del sys.modules[fake_name] diff --git a/nibabel/tests/test_orientations.py b/nibabel/tests/test_orientations.py index 798f595fc7..a3ad215488 100644 --- a/nibabel/tests/test_orientations.py +++ b/nibabel/tests/test_orientations.py @@ -11,7 +11,7 @@ import numpy as np import warnings -from nose.tools import assert_true, assert_equal, assert_raises +import pytest from numpy.testing import assert_array_equal @@ -128,15 +128,12 @@ def test_apply(): # Test 4D with an example orientation ornt = OUT_ORNTS[-1] t_arr = apply_orientation(a[:, :, :, None], ornt) - assert_equal(t_arr.ndim, 4) + assert t_arr.ndim == 4 # Orientation errors - assert_raises(OrientationError, - apply_orientation, - a[:, :, 1], ornt) - assert_raises(OrientationError, - apply_orientation, - a, - [[0, 1], [np.nan, np.nan], [2, 1]]) + with pytest.raises(OrientationError): + apply_orientation(a[:, :, 1], ornt) + with pytest.raises(OrientationError): + apply_orientation(a, [[0, 1], [np.nan, np.nan], [2, 1]]) shape = np.array(a.shape) for ornt in ALL_ORNTS: t_arr = apply_orientation(a, ornt) @@ -171,7 +168,7 @@ def test_io_orientation(): ornt = io_orientation(in_arr) assert_array_equal(ornt, out_ornt) taff = inv_ornt_aff(ornt, shape) - assert_true(same_transform(taff, ornt, shape)) + assert same_transform(taff, ornt, shape) for axno in range(3): arr = in_arr.copy() ex_ornt = out_ornt.copy() @@ -182,7 +179,7 @@ def test_io_orientation(): ornt = io_orientation(arr) assert_array_equal(ornt, ex_ornt) taff = inv_ornt_aff(ornt, shape) - assert_true(same_transform(taff, ornt, shape)) + assert same_transform(taff, ornt, shape) # Test nasty hang for zero columns rzs = np.c_[np.diag([2, 3, 4, 5]), np.zeros((4, 3))] arr = from_matvec(rzs, [15, 16, 17, 18]) @@ -252,54 +249,52 @@ def test_ornt_transform(): [[1, -1], [2, 1], [0, 1]] ) # Must have same shape - assert_raises(ValueError, - ornt_transform, - [[0, 1], [1, 1]], - [[0, 1], [1, 1], [2, 1]]) + with pytest.raises(ValueError): + ornt_transform([[0, 1], [1, 1]], [[0, 1], [1, 1], [2, 1]]) # Must be (N,2) in shape - assert_raises(ValueError, - ornt_transform, - [[0, 1, 1], [1, 1, 1]], - [[0, 1, 1], [1, 1, 1]]) + with pytest.raises(ValueError): + ornt_transform([[0, 1, 1], [1, 1, 1]], + [[0, 1, 1], [1, 1, 1]]) # Target axes must exist in source - assert_raises(ValueError, - ornt_transform, - [[0, 1], [1, 1], [1, 1]], - [[0, 1], [1, 1], [2, 1]]) + with pytest.raises(ValueError): + ornt_transform([[0, 1], [1, 1], [1, 1]], + [[0, 1], [1, 1], [2, 1]]) def test_ornt2axcodes(): # Recoding orientation to axis codes labels = (('left', 'right'), ('back', 'front'), ('down', 'up')) - assert_equal(ornt2axcodes([[0, 1], - [1, 1], - [2, 1]], labels), ('right', 'front', 'up')) - assert_equal(ornt2axcodes([[0, -1], - [1, -1], - [2, -1]], labels), ('left', 'back', 'down')) - assert_equal(ornt2axcodes([[2, -1], - [1, -1], - [0, -1]], labels), ('down', 'back', 'left')) - assert_equal(ornt2axcodes([[1, 1], - [2, -1], - [0, 1]], labels), ('front', 'down', 'right')) + assert ornt2axcodes([[0, 1], + [1, 1], + [2, 1]], labels) == ('right', 'front', 'up') + assert ornt2axcodes([[0, -1], + [1, -1], + [2, -1]], labels) == ('left', 'back', 'down') + assert ornt2axcodes([[2, -1], + [1, -1], + [0, -1]], labels) == ('down', 'back', 'left') + assert ornt2axcodes([[1, 1], + [2, -1], + [0, 1]], labels) == ('front', 'down', 'right') # default is RAS output directions - assert_equal(ornt2axcodes([[0, 1], - [1, 1], - [2, 1]]), ('R', 'A', 'S')) + assert ornt2axcodes([[0, 1], + [1, 1], + [2, 1]]) == ('R', 'A', 'S') # dropped axes produce None - assert_equal(ornt2axcodes([[0, 1], - [np.nan, np.nan], - [2, 1]]), ('R', None, 'S')) + assert ornt2axcodes([[0, 1], + [np.nan, np.nan], + [2, 1]]) == ('R', None, 'S') # Non integer axes raises error - assert_raises(ValueError, ornt2axcodes, [[0.1, 1]]) + with pytest.raises(ValueError): + ornt2axcodes([[0.1, 1]]) # As do directions not in range - assert_raises(ValueError, ornt2axcodes, [[0, 0]]) + with pytest.raises(ValueError): + ornt2axcodes([[0, 0]]) for axcodes, ornt in zip(ALL_AXCODES, ALL_ORNTS): - assert_equal(ornt2axcodes(ornt), axcodes) + assert ornt2axcodes(ornt) == axcodes def test_axcodes2ornt(): @@ -339,51 +334,50 @@ def test_axcodes2ornt(): # Missing axcodes raise an error assert_array_equal(axcodes2ornt('RAS'), default) - assert_raises(ValueError, axcodes2ornt, 'rAS') + with pytest.raises(ValueError): + axcodes2ornt('rAS') # None is OK as axis code assert_array_equal(axcodes2ornt(('R', None, 'S')), [[0, 1], [np.nan, np.nan], [2, 1]]) # Bad axis code with None also raises error. - assert_raises(ValueError, axcodes2ornt, ('R', None, 's')) + with pytest.raises(ValueError): + axcodes2ornt(('R', None, 's')) # Axis codes checked with custom labels labels = ('SD', 'BF', 'lh') assert_array_equal(axcodes2ornt('BlD', labels), [[1, -1], [2, -1], [0, 1]]) - assert_raises(ValueError, axcodes2ornt, 'blD', labels) + with pytest.raises(ValueError): + axcodes2ornt('blD', labels) # Duplicate labels - assert_raises(ValueError, axcodes2ornt, 'blD', ('SD', 'BF', 'lD')) - assert_raises(ValueError, axcodes2ornt, 'blD', ('SD', 'SF', 'lD')) + for labels in [('SD', 'BF', 'lD'),('SD', 'SF', 'lD')]: + with pytest.raises(ValueError): + axcodes2ornt('blD', labels) for axcodes, ornt in zip(ALL_AXCODES, ALL_ORNTS): assert_array_equal(axcodes2ornt(axcodes), ornt) def test_aff2axcodes(): - assert_equal(aff2axcodes(np.eye(4)), tuple('RAS')) + assert aff2axcodes(np.eye(4)) == tuple('RAS') aff = [[0, 1, 0, 10], [-1, 0, 0, 20], [0, 0, 1, 30], [0, 0, 0, 1]] - assert_equal(aff2axcodes(aff, (('L', 'R'), ('B', 'F'), ('D', 'U'))), - ('B', 'R', 'U')) - assert_equal(aff2axcodes(aff, (('L', 'R'), ('B', 'F'), ('D', 'U'))), - ('B', 'R', 'U')) + assert aff2axcodes(aff, (('L', 'R'), ('B', 'F'), ('D', 'U'))) == ('B', 'R', 'U') + assert aff2axcodes(aff, (('L', 'R'), ('B', 'F'), ('D', 'U'))) == ('B', 'R', 'U') def test_inv_ornt_aff(): # Extra tests for inv_ornt_aff routines (also tested in # io_orientations test) - assert_raises(OrientationError, inv_ornt_aff, - [[0, 1], [1, -1], [np.nan, np.nan]], (3, 4, 5)) + with pytest.raises(OrientationError): + inv_ornt_aff([[0, 1], [1, -1], [np.nan, np.nan]], (3, 4, 5)) def test_orientation_affine_deprecation(): 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_equal(len(warns), 1) - assert_equal(warns[0].category, DeprecationWarning) assert_array_equal(aff1, aff2) diff --git a/nibabel/tests/test_parrec.py b/nibabel/tests/test_parrec.py index 940d8864e5..d39f2a097f 100644 --- a/nibabel/tests/test_parrec.py +++ b/nibabel/tests/test_parrec.py @@ -20,9 +20,7 @@ from numpy.testing import (assert_almost_equal, assert_array_equal) -from nose.tools import (assert_true, assert_false, assert_raises, - assert_equal) - +import pytest from ..testing import (clear_and_catch_warnings, suppress_warnings, assert_arr_dict_equal) @@ -177,15 +175,15 @@ def test_header(): v41_hdr = PARRECHeader.from_fileobj(fobj, strict_sort=strict_sort) for hdr in (v42_hdr, v41_hdr, v4_hdr): hdr = PARRECHeader(HDR_INFO, HDR_DEFS) - assert_equal(hdr.get_data_shape(), (64, 64, 9, 3)) - assert_equal(hdr.get_data_dtype(), np.dtype(' -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 8b11e5cc51..58b41d5822 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 import ( + bytesio_round_trip, + clear_and_catch_warnings, + suppress_warnings, + memmap_after_ufunc +) -from .test_helpers import bytesio_round_trip -from ..testing import (clear_and_catch_warnings, suppress_warnings, - memmap_after_ufunc) from ..tmpdirs import InTemporaryDirectory from ..deprecator import ExpiredDeprecationError from .. import load as top_load - 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,48 @@ 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 +485,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 +530,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 +559,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 +630,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 diff --git a/nibabel/tests/test_spm2analyze.py b/nibabel/tests/test_spm2analyze.py index e39e79b96e..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 - 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 86143f35ab..e84a18ea4f 100644 --- a/nibabel/tests/test_spm99analyze.py +++ b/nibabel/tests/test_spm99analyze.py @@ -12,13 +12,16 @@ 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 unittest +import pytest -# Decorator to skip tests requiring save / load if scipy not available for mat -# files from ..optpkg import optional_package _, have_scipy, _ = optional_package('scipy') -scipy_skip = dec.skipif(not have_scipy, 'scipy not available') + +# Decorator to skip tests requiring save / load if scipy not available for mat +# files +needs_scipy = unittest.skipUnless(have_scipy, 'scipy not available') from ..spm99analyze import (Spm99AnalyzeHeader, Spm99AnalyzeImage, HeaderTypeError) @@ -26,12 +29,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 import ( + bytesio_round_trip, + bytesio_filemap, + assert_allclose_safely, + suppress_warnings +) from . import test_analyze -from .test_helpers import bytesio_round_trip, bytesio_filemap FLOAT_TYPES = np.sctypes['float'] COMPLEX_TYPES = np.sctypes['complex'] @@ -61,7 +66,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) @@ -69,12 +74,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, @@ -84,7 +89,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 @@ -98,11 +103,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), @@ -120,16 +125,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): @@ -139,16 +145,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): @@ -165,9 +169,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 @@ -398,7 +402,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): @@ -406,38 +410,17 @@ class TestSpm99AnalyzeImage(test_analyze.TestAnalyzeImage, ImageScalingMixin): image_class = Spm99AnalyzeImage # Decorating the old way, before the team invented @ - test_data_hdr_cache = (scipy_skip( - test_analyze.TestAnalyzeImage.test_data_hdr_cache - )) - - test_header_updating = (scipy_skip( - test_analyze.TestAnalyzeImage.test_header_updating - )) - - test_offset_to_zero = (scipy_skip( - test_analyze.TestAnalyzeImage.test_offset_to_zero - )) - - test_big_offset_exts = (scipy_skip( - test_analyze.TestAnalyzeImage.test_big_offset_exts - )) - - test_header_scaling = scipy_skip( - ImageScalingMixin.test_header_scaling) - - test_int_int_scaling = scipy_skip( - ImageScalingMixin.test_int_int_scaling) - - test_write_scaling = scipy_skip( - ImageScalingMixin.test_write_scaling) - - test_no_scaling = scipy_skip( - ImageScalingMixin.test_no_scaling) - - test_nan2zero_range_ok = scipy_skip( - ImageScalingMixin.test_nan2zero_range_ok) - - @scipy_skip + test_data_hdr_cache = needs_scipy(test_analyze.TestAnalyzeImage.test_data_hdr_cache) + test_header_updating = needs_scipy(test_analyze.TestAnalyzeImage.test_header_updating) + test_offset_to_zero = needs_scipy(test_analyze.TestAnalyzeImage.test_offset_to_zero) + test_big_offset_exts = needs_scipy(test_analyze.TestAnalyzeImage.test_big_offset_exts) + test_header_scaling = needs_scipy(ImageScalingMixin.test_header_scaling) + test_int_int_scaling = needs_scipy(ImageScalingMixin.test_int_int_scaling) + test_write_scaling = needs_scipy(ImageScalingMixin.test_write_scaling) + test_no_scaling = needs_scipy(ImageScalingMixin.test_no_scaling) + test_nan2zero_range_ok = needs_scipy(ImageScalingMixin.test_nan2zero_range_ok) + + @needs_scipy def test_mat_read(self): # Test mat file reading and writing for the SPM analyze types img_klass = self.image_class @@ -459,7 +442,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) @@ -470,7 +453,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) @@ -512,7 +495,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 e9f2d079ea..bbe83c6973 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, clear_and_catch_warnings, assert_allclose_safely, get_fresh_mod, assert_re_in, test_data, data_path) - +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,52 @@ 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("regex, entries", [ + [".*", ""], + [".*", ["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", "")) - - # Shouldn't "match" the empty list - assert_raises(AssertionError, assert_re_in, "", []) + ["ab", ("", "abc", "laskdjf")], + # Should do match not search + pytest.param("ab", "cab", marks=pytest.mark.xfail), + pytest.param("ab$", "abc", marks=pytest.mark.xfail), + pytest.param("ab$", ["ddd", ""], marks=pytest.mark.xfail), + pytest.param("ab$", ("ddd", ""), marks=pytest.mark.xfail), + #Shouldn't "match" the empty list + pytest.param("", [], marks=pytest.mark.xfail) +]) +def test_assert_re_in(regex, entries): + assert_re_in(regex, entries) def test_test_data(): - assert_equal(test_data(), data_path) - assert_equal(test_data(), - os.path.abspath(os.path.join(os.path.dirname(__file__), - '..', 'tests', '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 1d35b59269..c4d119b14f 100644 --- a/nibabel/tests/test_tmpdirs.py +++ b/nibabel/tests/test_tmpdirs.py @@ -5,7 +5,6 @@ from ..tmpdirs import InGivenDirectory -from nose.tools import assert_true, assert_equal MY_PATH = abspath(__file__) MY_DIR = dirname(MY_PATH) @@ -15,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 076e22f74e..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) - +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 05d3b1eb3f..2ec3e06182 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 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): + 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 d4879b46a8..907a3bbb1e 100644 --- a/nibabel/tests/test_viewers.py +++ b/nibabel/tests/test_viewers.py @@ -14,16 +14,16 @@ 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 unittest +import pytest # Need at least MPL 1.3 for viewer tests. # 2020.02.11 - 1.3 wheels are no longer distributed, so the minimum we test with is 1.5 matplotlib, has_mpl, _ = optional_package('matplotlib', min_version='1.5') -needs_mpl = skipif(not has_mpl, 'These tests need matplotlib') +needs_mpl = unittest.skipUnless(has_mpl, 'These tests need matplotlib') if has_mpl: matplotlib.use('Agg') @@ -38,7 +38,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 +53,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 +78,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 +89,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 d391abf359..8b0b6a52cf 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,10 +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) +from ..testing import assert_dt_equal, assert_allclose_safely, suppress_warnings #: convenience variables for numpy types FLOAT_TYPES = np.sctypes['float'] @@ -72,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) @@ -1021,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 45e8c28a52..26e04dd8f9 100644 --- a/nibabel/tests/test_wrapstruct.py +++ b/nibabel/tests/test_wrapstruct.py @@ -34,12 +34,11 @@ from ..spatialimages import HeaderDataError from .. import imageglobals -from unittest import TestCase +from ..testing import BaseTestCase from numpy.testing import assert_array_equal +import pytest -from ..testing import (assert_equal, assert_true, assert_false, - assert_raises, assert_not_equal) INTEGER_TYPES = np.sctypes['int'] + np.sctypes['uint'] @@ -80,7 +79,7 @@ def log_chk(hdr, level): if level == 0: # Should never log or raise error logger.setLevel(0) hdrc.check_fix(logger=logger, error_level=0) - assert_equal(str_io.getvalue(), '') + assert str_io.getvalue() == '' logger.removeHandler(handler) return hdrc, '', () # Non zero defect level, test above and below threshold. @@ -90,12 +89,12 @@ def log_chk(hdr, level): # Logging level above threshold, no log. logger.setLevel(level + 1) hdrc.check_fix(logger=logger, error_level=e_lev) - assert_equal(str_io.getvalue(), '') + assert str_io.getvalue() == '' # Logging level below threshold, log appears, store logged message logger.setLevel(level - 1) hdrc = hdr.copy() hdrc.check_fix(logger=logger, error_level=e_lev) - assert_true(str_io.getvalue() != '') + assert str_io.getvalue() != '' message = str_io.getvalue().strip() logger.removeHandler(handler) # When error level == level, check_fix should raise an error @@ -107,7 +106,7 @@ def log_chk(hdr, level): return hdrc, message, raiser -class _TestWrapStructBase(TestCase): +class _TestWrapStructBase(BaseTestCase): ''' Class implements base tests for binary headers It serves as a base class for other binary header tests @@ -123,12 +122,12 @@ def test_general_init(self): hdr = self.header_class() # binaryblock has length given by header data dtype binblock = hdr.binaryblock - assert_equal(len(binblock), hdr.structarr.dtype.itemsize) + assert len(binblock) == hdr.structarr.dtype.itemsize # Endianness will be native by default for empty header - assert_equal(hdr.endianness, native_code) + assert hdr.endianness == native_code # But you can change this if you want hdr = self.header_class(endianness='swapped') - assert_equal(hdr.endianness, swapped_code) + assert hdr.endianness == swapped_code # You can also pass in a check flag, without data this has no # effect hdr = self.header_class(check=False) @@ -141,17 +140,17 @@ def test__eq__(self): # Test equal and not equal hdr1 = self.header_class() hdr2 = self.header_class() - assert_equal(hdr1, hdr2) + assert hdr1 == hdr2 self._set_something_into_hdr(hdr1) - assert_not_equal(hdr1, hdr2) + assert hdr1 != hdr2 self._set_something_into_hdr(hdr2) - assert_equal(hdr1, hdr2) + assert hdr1 == hdr2 # Check byteswapping maintains equality hdr3 = hdr2.as_byteswapped() - assert_equal(hdr2, hdr3) + assert hdr2 == hdr3 # Check comparing to funny thing says no - assert_not_equal(hdr1, None) - assert_not_equal(hdr1, 1) + assert hdr1 != None + assert hdr1 != 1 def test_to_from_fileobj(self): # Successful write using write_to @@ -160,28 +159,26 @@ def test_to_from_fileobj(self): hdr.write_to(str_io) str_io.seek(0) hdr2 = self.header_class.from_fileobj(str_io) - assert_equal(hdr2.endianness, native_code) - assert_equal(hdr2.binaryblock, hdr.binaryblock) + assert hdr2.endianness == native_code + assert hdr2.binaryblock == hdr.binaryblock def test_mappingness(self): hdr = self.header_class() - assert_raises(ValueError, - hdr.__setitem__, - 'nonexistent key', - 0.1) + with pytest.raises(ValueError): + hdr['nonexistent key'] = 0.1 hdr_dt = hdr.structarr.dtype keys = hdr.keys() - assert_equal(keys, list(hdr)) + assert keys == list(hdr) vals = hdr.values() - assert_equal(len(vals), len(keys)) - assert_equal(keys, list(hdr_dt.names)) + assert len(vals) == len(keys) + assert keys == list(hdr_dt.names) for key, val in hdr.items(): assert_array_equal(hdr[key], val) # verify that .get operates as destined - assert_equal(hdr.get('nonexistent key'), None) - assert_equal(hdr.get('nonexistent key', 'default'), 'default') - assert_equal(hdr.get(keys[0]), vals[0]) - assert_equal(hdr.get(keys[0], 'default'), vals[0]) + assert hdr.get('nonexistent key') is None + assert hdr.get('nonexistent key', 'default') == 'default' + assert hdr.get(keys[0]) == vals[0] + assert hdr.get(keys[0], 'default') == vals[0] # make sure .get returns values which evaluate to False. We have to # use a different falsy value depending on the data type of the first @@ -189,9 +186,9 @@ def test_mappingness(self): falsyval = 0 if np.issubdtype(hdr_dt[0], np.number) else b'' hdr[keys[0]] = falsyval - assert_equal(hdr[keys[0]], falsyval) - assert_equal(hdr.get(keys[0]), falsyval) - assert_equal(hdr.get(keys[0], -1), falsyval) + assert hdr[keys[0]] == falsyval + assert hdr.get(keys[0]) == falsyval + assert hdr.get(keys[0], -1) == falsyval def test_endianness_ro(self): @@ -203,16 +200,17 @@ def test_endianness_ro(self): data) - but this is done via via the as_byteswapped method ''' hdr = self.header_class() - assert_raises(AttributeError, hdr.__setattr__, 'endianness', '<') + with pytest.raises(AttributeError): + hdr.endianness = '<' def test_endian_guess(self): # Check guesses of endian eh = self.header_class() - assert_equal(eh.endianness, native_code) + assert eh.endianness == native_code hdr_data = eh.structarr.copy() hdr_data = hdr_data.byteswap(swapped_code) eh_swapped = self.header_class(hdr_data.tostring()) - assert_equal(eh_swapped.endianness, swapped_code) + assert eh_swapped.endianness == swapped_code def test_binblock_is_file(self): # Checks that the binary string respresentation is the whole of the @@ -224,7 +222,7 @@ def test_binblock_is_file(self): hdr = self.header_class() str_io = BytesIO() hdr.write_to(str_io) - assert_equal(str_io.getvalue(), hdr.binaryblock) + assert str_io.getvalue() == hdr.binaryblock def test_structarr(self): # structarr attribute also read only @@ -232,7 +230,8 @@ def test_structarr(self): # Just check we can get structarr hdr.structarr # That it's read only - assert_raises(AttributeError, hdr.__setattr__, 'structarr', 0) + with pytest.raises(AttributeError): + hdr.structarr = 0 def log_chk(self, hdr, level): return log_chk(hdr, level) @@ -241,50 +240,49 @@ def assert_no_log_err(self, hdr): """ Assert that no logging or errors result from this `hdr` """ fhdr, message, raiser = self.log_chk(hdr, 0) - assert_equal((fhdr, message), (hdr, '')) + assert (fhdr, message) == (hdr, '') def test_bytes(self): # Test get of bytes hdr1 = self.header_class() bb = hdr1.binaryblock hdr2 = self.header_class(hdr1.binaryblock) - assert_equal(hdr1, hdr2) - assert_equal(hdr1.binaryblock, hdr2.binaryblock) + assert hdr1 == hdr2 + assert hdr1.binaryblock == hdr2.binaryblock # Do a set into the header, and try again. The specifics of 'setting # something' will depend on the nature of the bytes object self._set_something_into_hdr(hdr1) hdr2 = self.header_class(hdr1.binaryblock) - assert_equal(hdr1, hdr2) - assert_equal(hdr1.binaryblock, hdr2.binaryblock) + assert hdr1 == hdr2 + assert hdr1.binaryblock == hdr2.binaryblock # Short and long binaryblocks give errors # (here set through init) - assert_raises(WrapStructError, - self.header_class, - bb[:-1]) - assert_raises(WrapStructError, - self.header_class, - bb + b'\x00') + with pytest.raises(WrapStructError): + self.header_class(bb[:-1]) + with pytest.raises(WrapStructError): + self.header_class(bb + b'\x00') # Checking set to true by default, and prevents nonsense being # set into the header. bb_bad = self.get_bad_bb() if bb_bad is None: return with imageglobals.LoggingOutputSuppressor(): - assert_raises(HeaderDataError, self.header_class, bb_bad) + with pytest.raises(HeaderDataError): + self.header_class(bb_bad) # now slips past without check _ = self.header_class(bb_bad, check=False) def test_as_byteswapped(self): # Check byte swapping hdr = self.header_class() - assert_equal(hdr.endianness, native_code) + assert hdr.endianness == native_code # same code just returns a copy hdr2 = hdr.as_byteswapped(native_code) - assert_false(hdr is hdr2) + assert not hdr is hdr2 # Different code gives byteswapped copy hdr_bs = hdr.as_byteswapped(swapped_code) - assert_equal(hdr_bs.endianness, swapped_code) - assert_not_equal(hdr.binaryblock, hdr_bs.binaryblock) + assert hdr_bs.endianness == swapped_code + assert hdr.binaryblock != hdr_bs.binaryblock # Note that contents is not rechecked on swap / copy class DC(self.header_class): @@ -292,7 +290,8 @@ class DC(self.header_class): def check_fix(self, *args, **kwargs): raise Exception # Assumes check=True default - assert_raises(Exception, DC, hdr.binaryblock) + with pytest.raises(Exception): + DC(hdr.binaryblock) hdr = DC(hdr.binaryblock, check=False) hdr2 = hdr.as_byteswapped(native_code) hdr_bs = hdr.as_byteswapped(swapped_code) @@ -311,7 +310,8 @@ def test_str(self): hdr = self.header_class() # Check something returns from str s1 = str(hdr) - assert_true(len(s1) > 0) + assert len(s1) > 0 + class _TestLabeledWrapStruct(_TestWrapStructBase): @@ -324,28 +324,30 @@ class MyHdr(self.header_class): _field_recoders = {} hdr = MyHdr() # Key not existing raises error - assert_raises(ValueError, hdr.get_value_label, 'improbable') + with pytest.raises(ValueError): + hdr.get_value_label('improbable') # Even if there is a recoder - assert_true('improbable' not in hdr.keys()) + assert 'improbable' not in hdr.keys() rec = Recoder([[0, 'fullness of heart']], ('code', 'label')) hdr._field_recoders['improbable'] = rec - assert_raises(ValueError, hdr.get_value_label, 'improbable') + with pytest.raises(ValueError): + hdr.get_value_label('improbable') # If the key exists in the structure, and is intable, then we can recode for key, value in hdr.items(): # No recoder at first - assert_raises(ValueError, hdr.get_value_label, 0) + with pytest.raises(ValueError): + hdr.get_value_label(0) if not value.dtype.type in INTEGER_TYPES or not np.isscalar(value): continue code = int(value) rec = Recoder([[code, 'fullness of heart']], ('code', 'label')) hdr._field_recoders[key] = rec - assert_equal(hdr.get_value_label(key), 'fullness of heart') + assert hdr.get_value_label(key) == 'fullness of heart' # If key exists, but value is missing, we get 'unknown code' # Speculating that we can set code value 0 or 1 new_code = 1 if code == 0 else 0 hdr[key] = new_code - assert_equal(hdr.get_value_label(key), - ''.format(new_code)) + assert hdr.get_value_label(key) == ''.format(new_code) class MyWrapStruct(WrapStruct): @@ -418,48 +420,48 @@ def _set_something_into_hdr(self, hdr): def test_empty(self): # Test contents of default header hdr = self.header_class() - assert_equal(hdr['an_integer'], 1) - assert_equal(hdr['a_str'], b'a string') + assert hdr['an_integer'] == 1 + assert hdr['a_str'] == b'a string' def test_str(self): hdr = self.header_class() s1 = str(hdr) - assert_true(len(s1) > 0) - assert_true('an_integer' in s1) - assert_true('a_str' in s1) + assert len(s1) > 0 + assert 'an_integer' in s1 + assert 'a_str' in s1 def test_copy(self): hdr = self.header_class() hdr2 = hdr.copy() - assert_equal(hdr, hdr2) + assert hdr == hdr2 self._set_something_into_hdr(hdr) - assert_not_equal(hdr, hdr2) + assert hdr != hdr2 self._set_something_into_hdr(hdr2) - assert_equal(hdr, hdr2) + assert hdr == hdr2 def test_copy(self): hdr = self.header_class() hdr2 = hdr.copy() - assert_equal(hdr, hdr2) + assert hdr == hdr2 self._set_something_into_hdr(hdr) - assert_not_equal(hdr, hdr2) + assert hdr != hdr2 self._set_something_into_hdr(hdr2) - assert_equal(hdr, hdr2) + assert hdr == hdr2 def test_checks(self): # Test header checks hdr_t = self.header_class() # _dxer just returns the diagnostics as a string # Default hdr is OK - assert_equal(self._dxer(hdr_t), '') + assert self._dxer(hdr_t) == '' # An integer should be 1 hdr = hdr_t.copy() hdr['an_integer'] = 2 - assert_equal(self._dxer(hdr), 'an_integer should be 1') + assert self._dxer(hdr) == 'an_integer should be 1' # String should be lower case hdr = hdr_t.copy() hdr['a_str'] = 'My Name' - assert_equal(self._dxer(hdr), 'a_str should be lower case') + assert self._dxer(hdr) == 'a_str should be lower case' def test_log_checks(self): # Test logging, fixing, errors for header checking @@ -470,17 +472,15 @@ def test_log_checks(self): hdr['an_integer'] = 2 # severity 40 fhdr, message, raiser = self.log_chk(hdr, 40) return - assert_equal(fhdr['an_integer'], 1) - assert_equal(message, - 'an_integer should be 1; set an_integer to 1') - assert_raises(*raiser) + assert fhdr['an_integer'] == 1 + assert message == 'an_integer should be 1; set an_integer to 1' + pytest.raises(*raiser) # lower case string hdr = HC() hdr['a_str'] = 'Hello' # severity = 20 fhdr, message, raiser = self.log_chk(hdr, 20) - assert_equal(message, 'a_str should be lower case; ' - 'set a_str to lower case') - assert_raises(*raiser) + assert message == 'a_str should be lower case; set a_str to lower case' + pytest.raises(*raiser) def test_logger_error(self): # Check that we can reset the logger and error level @@ -499,12 +499,11 @@ def test_logger_error(self): # Check log message appears in new logger imageglobals.logger = logger hdr.copy().check_fix() - assert_equal(str_io.getvalue(), - 'a_str should be lower case; ' - 'set a_str to lower case\n') + assert str_io.getvalue() == 'a_str should be lower case; set a_str to lower case\n' # Check that error_level in fact causes error to be raised imageglobals.error_level = 20 - assert_raises(HeaderDataError, hdr.copy().check_fix) + with pytest.raises(HeaderDataError): + hdr.copy().check_fix() finally: imageglobals.logger, imageglobals.error_level = log_cache @@ -518,13 +517,13 @@ class MyHdr(self.header_class): _field_recoders = {} hdr = MyHdr() s1 = str(hdr) - assert_true(len(s1) > 0) - assert_true('an_integer : 1' in s1) - assert_true('fullness of heart' not in s1) + assert len(s1) > 0 + assert 'an_integer : 1' in s1 + assert 'fullness of heart' not in s1 rec = Recoder([[1, 'fullness of heart']], ('code', 'label')) hdr._field_recoders['an_integer'] = rec s2 = str(hdr) - assert_true('fullness of heart' in s2) + assert 'fullness of heart' in s2 hdr['an_integer'] = 10 s1 = str(hdr) - assert_true('' in s1) + assert '' in s1 diff --git a/setup.cfg b/setup.cfg index 9bf595fe99..a180f71c8d 100644 --- a/setup.cfg +++ b/setup.cfg @@ -32,10 +32,6 @@ python_requires = >=3.5.1 install_requires = numpy >=1.13 packaging >=14.3 -tests_require = - nose >=0.11 - pytest -test_suite = nose.collector zip_safe = False packages = find: @@ -61,8 +57,8 @@ style = flake8 test = coverage - nose >=0.11 - pytest + pytest !=5.3.4 + pytest-cov all = %(dicomfs)s %(dev)s @@ -86,6 +82,7 @@ console_scripts = nibabel = tests/data/* */tests/data/* + benchmarks/pytest.benchmark.ini [flake8] max-line-length = 100