Skip to content

TEST: Style cleanups, simpler fixtures #878

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 5, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion nibabel/optpkg.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
""" Routines to support optional packages """
import pkgutil
from distutils.version import LooseVersion
from .tripwire import TripWire

Expand Down
8 changes: 3 additions & 5 deletions nibabel/tests/test_arrayproxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def test_init():
assert ap.shape == shape
# shape should be read only
with pytest.raises(AttributeError):
setattr(ap, 'shape', shape)
ap.shape = shape
# Get the data
assert_array_equal(np.asarray(ap), arr)
# Check we can modify the original header without changing the ap version
Expand Down Expand Up @@ -323,10 +323,8 @@ def check_mmap(hdr, offset, proxy_class,
assert not unscaled_is_mmap
assert not back_is_mmap
else:
assert (unscaled_is_mmap ==
(viral_memmap or unscaled_really_mmap))
assert (back_is_mmap ==
(viral_memmap or scaled_really_mmap))
assert unscaled_is_mmap == (viral_memmap or unscaled_really_mmap)
assert back_is_mmap == (viral_memmap or scaled_really_mmap)
if scaled_really_mmap:
assert back_data.mode == expected_mode
del prox, back_data
Expand Down
7 changes: 3 additions & 4 deletions nibabel/tests/test_arraywriters.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,10 @@
from ..casting import int_abs, type_info, shared_range, on_powerpc
from ..volumeutils import array_from_file, apply_read_scaling, _dt_min_max

from numpy.testing import (assert_array_almost_equal,
assert_array_equal)
from numpy.testing import assert_array_almost_equal, assert_array_equal
import pytest
from ..testing_pytest import (assert_allclose_safely, suppress_warnings,
error_warnings)
error_warnings)


FLOAT_TYPES = np.sctypes['float']
Expand Down Expand Up @@ -532,7 +531,7 @@ def test_nan2zero():
# Deprecation warning for nan2zero as argument to `to_fileobj`
with error_warnings():
with pytest.raises(DeprecationWarning):
aw.to_fileobj(BytesIO(), 'F', False)
aw.to_fileobj(BytesIO(), 'F', False)
with pytest.raises(DeprecationWarning):
aw.to_fileobj(BytesIO(), 'F', nan2zero=False)
# Error if nan2zero is not the value set at initialization
Expand Down
36 changes: 6 additions & 30 deletions nibabel/tests/test_batteryrunners.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,43 +159,19 @@ def test_logging():
def test_checks():
battrun = BatteryRunner((chk1,))
reports = battrun.check_only({})
assert (reports[0] ==
Report(KeyError,
20,
'no "testkey"',
''))
assert reports[0] == Report(KeyError, 20, 'no "testkey"', '')
obj, reports = battrun.check_fix({})
assert (reports[0] ==
Report(KeyError,
20,
'no "testkey"',
'added "testkey"'))
assert reports[0] == Report(KeyError, 20, 'no "testkey"', 'added "testkey"')
assert obj == {'testkey': 1}
battrun = BatteryRunner((chk1, chk2))
reports = battrun.check_only({})
assert (reports[0] ==
Report(KeyError,
20,
'no "testkey"',
''))
assert (reports[1] ==
Report(KeyError,
20,
'no "testkey"',
''))
assert reports[0] == Report(KeyError, 20, 'no "testkey"', '')
assert reports[1] == Report(KeyError, 20, 'no "testkey"', '')
obj, reports = battrun.check_fix({})
# In the case of fix, the previous fix exposes a different error
# Note, because obj is mutable, first and second point to modified
# (and final) dictionary
output_obj = {'testkey': 0}
assert (reports[0] ==
Report(KeyError,
20,
'no "testkey"',
'added "testkey"'))
assert (reports[1] ==
Report(ValueError,
10,
'"testkey" != 0',
'set "testkey" to 0'))
assert reports[0] == Report(KeyError, 20, 'no "testkey"', 'added "testkey"')
assert reports[1] == Report(ValueError, 10, '"testkey" != 0', 'set "testkey" to 0')
assert obj == output_obj
8 changes: 2 additions & 6 deletions nibabel/tests/test_casting.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,7 @@ def test_shared_range():
if imax_roundtrip == imax:
thresh_overflow = True
if thresh_overflow:
assert np.all(
(bit_bigger == casted_mx) |
(bit_bigger == imax))
assert np.all((bit_bigger == casted_mx) | (bit_bigger == imax))
else:
assert np.all((bit_bigger <= casted_mx))
if it in np.sctypes['uint']:
Expand All @@ -71,9 +69,7 @@ def test_shared_range():
if imin_roundtrip == imin:
thresh_overflow = True
if thresh_overflow:
assert np.all(
(bit_smaller == casted_mn) |
(bit_smaller == imin))
assert np.all((bit_smaller == casted_mn) | (bit_smaller == imin))
else:
assert np.all((bit_smaller >= casted_mn))

Expand Down
33 changes: 13 additions & 20 deletions nibabel/tests/test_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,24 +19,19 @@

import pytest

from .test_environment import (with_environment,
DATA_KEY,
USER_KEY)
from .test_environment import with_environment, DATA_KEY, USER_KEY


@pytest.fixture()
@pytest.fixture
def with_nimd_env(request, with_environment):
DATA_FUNCS = {}
DATA_FUNCS['home_dir_func'] = nibd.get_nipy_user_dir
DATA_FUNCS['sys_dir_func'] = nibd.get_nipy_system_dir
DATA_FUNCS['path_func'] = nibd.get_data_path

def teardown_data_env():
nibd.get_nipy_user_dir = DATA_FUNCS['home_dir_func']
nibd.get_nipy_system_dir = DATA_FUNCS['sys_dir_func']
nibd.get_data_path = DATA_FUNCS['path_func']

request.addfinalizer(teardown_data_env)
yield
nibd.get_nipy_user_dir = DATA_FUNCS['home_dir_func']
nibd.get_nipy_system_dir = DATA_FUNCS['sys_dir_func']
nibd.get_data_path = DATA_FUNCS['path_func']


def test_datasource():
Expand Down Expand Up @@ -162,8 +157,7 @@ def test_data_path(with_nimd_env):
with open(tmpfile, 'wt') as fobj:
fobj.write('[DATA]\n')
fobj.write('path = %s\n' % '/path/two')
assert (get_data_path() ==
tst_list + ['/path/two'] + old_pth)
assert get_data_path() == tst_list + ['/path/two'] + old_pth


def test_find_data_dir():
Expand Down Expand Up @@ -206,10 +200,10 @@ def test_make_datasource(with_nimd_env):
assert ds.version == '0.1'


@pytest.mark.xfail(raises=DataError)
def test_bomber():
with pytest.raises(DataError):
b = Bomber('bomber example', 'a message')
b.any_attribute # no error
b = Bomber('bomber example', 'a message')
b.any_attribute # no error


def test_bomber_inspect():
Expand All @@ -218,13 +212,12 @@ def test_bomber_inspect():


def test_datasource_or_bomber(with_nimd_env):
pkg_def = dict(
relpath='pkg')
pkg_def = dict(relpath='pkg')
with TemporaryDirectory() as tmpdir:
nibd.get_data_path = lambda: [tmpdir]
ds = datasource_or_bomber(pkg_def)
with pytest.raises(DataError):
getattr(ds, 'get_filename')
ds.get_filename('some_file.txt')
pkg_dir = pjoin(tmpdir, 'pkg')
os.mkdir(pkg_dir)
tmpfile = pjoin(pkg_dir, 'config.ini')
Expand All @@ -240,4 +233,4 @@ def test_datasource_or_bomber(with_nimd_env):
pkg_def['min version'] = '0.3'
ds = datasource_or_bomber(pkg_def) # not OK
with pytest.raises(DataError):
getattr(ds, 'get_filename')
ds.get_filename('some_file.txt')
25 changes: 10 additions & 15 deletions nibabel/tests/test_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
USER_KEY = 'NIPY_USER_DIR'


@pytest.fixture()
@pytest.fixture
def with_environment(request):
"""Setup test environment for some functions that are tested
in this module. In particular this functions stores attributes
Expand All @@ -24,20 +24,15 @@ def with_environment(request):
"""
GIVEN_ENV = {}
GIVEN_ENV['env'] = env.copy()


def teardown_environment():
"""Restore things that were remembered by the setup_environment function
"""
orig_env = GIVEN_ENV['env']
# Pull keys out into list to avoid altering dictionary during iteration,
# causing python 3 error
for key in list(env.keys()):
if key not in orig_env:
del env[key]
env.update(orig_env)

request.addfinalizer(teardown_environment)
yield
"""Restore things that were remembered by the setup_environment function """
orig_env = GIVEN_ENV['env']
# Pull keys out into list to avoid altering dictionary during iteration,
# causing python 3 error
for key in list(env.keys()):
if key not in orig_env:
del env[key]
env.update(orig_env)


def test_nipy_home():
Expand Down