Skip to content

MRG: Cleaner tests #254

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 3 commits into from
Oct 13, 2014
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
4 changes: 2 additions & 2 deletions doc/source/coordinate_systems.rst
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ the array.
>>> slice_1 = epi_img_data[:, 30, :]
>>> slice_2 = epi_img_data[:, :, 16]
>>> show_slices([slice_0, slice_1, slice_2])
>>> plt.suptitle("Center slices for EPI image")
>>> plt.suptitle("Center slices for EPI image") # doctest: +SKIP
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These skips were necessary on my system or tests would fail.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What happens on your system for these? Presumably you are running make doctests on the docs?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, let me test again on current master...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

e.g.:

larsoner@bunk:~/custombuilds/nibabel$ make testmanual
F..F
======================================================================
FAIL: Doctest: coordinate_systems.rst
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python2.7/doctest.py", line 2226, in runTest
    raise self.failureException(self.format_failure(new.getvalue()))
AssertionError: Failed doctest test for coordinate_systems.rst
  File "/home/larsoner/custombuilds/nibabel/doc/source/coordinate_systems.rst", line 0

----------------------------------------------------------------------
File "/home/larsoner/custombuilds/nibabel/doc/source/coordinate_systems.rst", line 58, in coordinate_systems.rst
Failed example:
    plt.suptitle("Center slices for EPI image")
Expected nothing
Got:
    <matplotlib.text.Text object at 0x2b0f27e16790>

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Try adding a semicolon at the end of the line instead?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That should indeed suppress it, I'll add it

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

...actually it does not suppress it. Back to the SKIP?


We collected an anatomical image in the same session. We can load that image
and look at slices in the three axes:
Expand All @@ -77,7 +77,7 @@ and look at slices in the three axes:
>>> show_slices([anat_img_data[28, :, :],
... anat_img_data[:, 33, :],
... anat_img_data[:, :, 28]])
>>> plt.suptitle("Center slices for anatomical image")
>>> plt.suptitle("Center slices for anatomical image") # doctest: +SKIP

As is usually the case, we had a different field of view for the anatomical
scan, and so the anatomical image has a different shape, size, and orientation
Expand Down
2 changes: 1 addition & 1 deletion doc/source/neuro_radio_conventions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ Here we are showing the middle slice of :download:`an image
>>> img_data = img.get_data()
>>> a_slice = img_data[:, :, 28]
>>> # Need transpose to put first axis left-right, second bottom-top
>>> plt.imshow(a_slice.T, cmap="gray", origin="lower")
>>> plt.imshow(a_slice.T, cmap="gray", origin="lower") # doctest: +SKIP

This slice does have the voxels from the right of isocenter towards the right
of the screen, neurology style.
Expand Down
13 changes: 13 additions & 0 deletions nibabel/imageglobals.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
logger = logging.getLogger('nibabel.global')
logger.addHandler(logging.StreamHandler())


class ErrorLevel(object):
""" Context manager to set log error level
"""
Expand All @@ -45,3 +46,15 @@ def __exit__(self, exc, value, tb):
global error_level
error_level = self._original_level
return False


class LoggingOutputSuppressor(object):
"""Context manager to prevent global logger from printing"""
def __enter__(self):
self.orig_handlers = logger.handlers
for handler in self.orig_handlers:
logger.removeHandler(handler)

def __exit__(self, exc, value, tb):
for handler in self.orig_handlers:
logger.addHandler(handler)
12 changes: 6 additions & 6 deletions nibabel/nicom/dicomwrappers.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ def rotation_matrix(self):
"""
iop = self.image_orient_patient
s_norm = self.slice_normal
if None in (iop, s_norm):
if iop is None or s_norm is None:
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These show up a lot. Without these changes to how None are handled, there are DeprecationWarnings, and presumably eventually problems will be caused.

return None
R = np.eye(3)
# np.fliplr(iop) gives matrix F in
Expand Down Expand Up @@ -235,7 +235,7 @@ def slice_indicator(self):
"""
ipp = self.image_position
s_norm = self.slice_normal
if None in (ipp, s_norm):
if ipp is None or s_norm is None:
return None
return np.inner(ipp, s_norm)

Expand Down Expand Up @@ -304,7 +304,7 @@ def get_affine(self):
# column, slice)
vox = self.voxel_sizes
ipp = self.image_position
if None in (orient, vox, ipp):
if any(p is None for p in (orient, vox, ipp)):
raise WrapperError('Not enough information for affine')
aff = np.eye(4)
aff[:3, :3] = orient * np.array(vox)
Expand Down Expand Up @@ -786,7 +786,7 @@ def image_position(self):
md_rows, md_cols = (self.get('Rows'), self.get('Columns'))
iop = self.image_orient_patient
pix_spacing = self.get('PixelSpacing')
if None in (ipp, md_rows, md_cols, iop, pix_spacing):
if any(x is None for x in (ipp, md_rows, md_cols, iop, pix_spacing)):
return None
# PixelSpacing values are python Decimal in pydicom 0.9.7
pix_spacing = np.array(list(map(float, pix_spacing)))
Expand Down Expand Up @@ -881,8 +881,8 @@ def none_or_close(val1, val2, rtol=1e-5, atol=1e-6):
>>> none_or_close([0,1], [0,2])
False
"""
if (val1, val2) == (None, None):
if val1 is None and val2 is None:
return True
if None in (val1, val2):
if val1 is None or val2 is None:
return False
return np.allclose(val1, val2, rtol, atol)
2 changes: 1 addition & 1 deletion nibabel/nifti1.py
Original file line number Diff line number Diff line change
Expand Up @@ -1061,7 +1061,7 @@ def set_slope_inter(self, slope, inter=None):
raise HeaderDataError('Slope cannot be 0 or infinite')
if inter in (np.inf, -np.inf):
raise HeaderDataError('Intercept cannot be infinite')
if np.diff(np.isnan([slope, inter])):
if np.isnan(slope) ^ np.isnan(inter):
raise HeaderDataError('None or both of slope, inter should be nan')
self._structarr['scl_slope'] = slope
self._structarr['scl_inter'] = inter
Expand Down
10 changes: 10 additions & 0 deletions nibabel/testing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from os.path import dirname, abspath, join as pjoin

import numpy as np
from warnings import catch_warnings, simplefilter

# set path to example data
data_path = abspath(pjoin(dirname(__file__), '..', 'tests', 'data'))
Expand Down Expand Up @@ -49,3 +50,12 @@ def assert_allclose_safely(a, b, match_nans=True):
if b.dtype.kind in 'ui':
b = b.astype(float)
assert_true(np.allclose(a, b))


class suppress_warnings(catch_warnings):
""" Version of ``catch_warnings`` class that suppresses warnings
"""
def __enter__(self):
res = super(suppress_warnings, self).__enter__()
simplefilter('ignore')
return res
22 changes: 14 additions & 8 deletions nibabel/tests/test_analyze.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@
assert_array_almost_equal)

from ..testing import (assert_equal, assert_not_equal, assert_true,
assert_false, assert_raises, data_path)
assert_false, assert_raises, data_path,
suppress_warnings)

from .test_wrapstruct import _TestLabeledWrapStruct
from . import test_spatialimages as tsi
Expand All @@ -45,6 +46,7 @@

PIXDIM0_MSG = 'pixdim[1,2,3] should be non-zero; setting 0 dims to 1'


class TestAnalyzeHeader(_TestLabeledWrapStruct):
header_class = AnalyzeHeader
example_file = header_file
Expand Down Expand Up @@ -97,7 +99,8 @@ def test_empty(self):

def _set_something_into_hdr(self, hdr):
# Called from test_bytes test method. Specific to the header data type
hdr.set_data_shape((1, 2, 3))
with suppress_warnings():
hdr.set_data_shape((1, 2, 3))

def test_checks(self):
# Test header checks
Expand All @@ -106,8 +109,9 @@ def test_checks(self):
assert_equal(self._dxer(hdr_t), '')
hdr = hdr_t.copy()
hdr['sizeof_hdr'] = 1
assert_equal(self._dxer(hdr), 'sizeof_hdr should be ' +
str(self.sizeof_hdr))
with suppress_warnings():
assert_equal(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'
Expand All @@ -125,8 +129,9 @@ def test_log_checks(self):
HC = self.header_class
# magic
hdr = HC()
hdr['sizeof_hdr'] = 350 # severity 30
fhdr, message, raiser = self.log_chk(hdr, 30)
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(
Expand All @@ -139,15 +144,16 @@ def test_log_checks(self):
# datatype not recognized
hdr = HC()
hdr['datatype'] = -1 # severity 40
fhdr, message, raiser = self.log_chk(hdr, 40)
with suppress_warnings():
fhdr, message, raiser = self.log_chk(hdr, 40)
assert_equal(message, 'data code -1 not recognized; '
'not attempting fix')
assert_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')
'not attempting fix')
assert_raises(*raiser)
# bitpix
hdr = HC()
Expand Down
11 changes: 6 additions & 5 deletions nibabel/tests/test_arraywriters.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from platform import python_compiler, machine
from distutils.version import LooseVersion
import itertools

import numpy as np

from ..externals.six import BytesIO
Expand All @@ -28,7 +27,7 @@
assert_equal, assert_not_equal,
assert_raises)

from ..testing import assert_allclose_safely
from ..testing import assert_allclose_safely, suppress_warnings
from ..checkwarns import ErrorWarnings


Expand Down Expand Up @@ -135,8 +134,9 @@ def test_no_scaling():
kwargs = (dict(check_scaling=False) if awt == ArrayWriter
else dict(calc_scale=False))
aw = awt(arr, out_dtype, **kwargs)
back_arr = round_trip(aw)
exp_back = arr.astype(float)
with suppress_warnings(): # cast to real from cplx
back_arr = round_trip(aw)
exp_back = arr.astype(float)
if out_dtype in IUINT_TYPES:
exp_back = np.round(exp_back)
if hasattr(aw, 'slope') and in_dtype in FLOAT_TYPES:
Expand Down Expand Up @@ -642,7 +642,8 @@ def test_float_int_min_max():
continue
for out_dt in IUINT_TYPES:
try:
aw = SlopeInterArrayWriter(arr, out_dt)
with suppress_warnings(): # overflow
aw = SlopeInterArrayWriter(arr, out_dt)
except ScalingError:
continue
arr_back_sc = round_trip(aw)
Expand Down
8 changes: 5 additions & 3 deletions nibabel/tests/test_casting.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@
import os

from platform import machine

import numpy as np

from ..casting import (float_to_int, shared_range, CastingError, int_to_float,
as_int, int_abs, floor_log2, able_int_type, best_float,
ulp, longdouble_precision_improved)
from ..testing import suppress_warnings

from numpy.testing import (assert_array_almost_equal, assert_array_equal)

Expand All @@ -23,7 +23,8 @@ def test_shared_range():
# (if this system generates that) or something smaller (because of
# overflow)
mn, mx = shared_range(ft, it)
ovs = ft(mx) + np.arange(2048, dtype=ft)
with suppress_warnings():
ovs = ft(mx) + np.arange(2048, dtype=ft)
# Float16 can overflow to inf
bit_bigger = ovs[np.isfinite(ovs)].astype(it)
casted_mx = ft(mx).astype(it)
Expand Down Expand Up @@ -51,7 +52,8 @@ def test_shared_range():
assert_equal(mn, 0)
continue
# And something larger for the minimum
ovs = ft(mn) - np.arange(2048, dtype=ft)
with suppress_warnings(): # overflow
ovs = ft(mn) - np.arange(2048, dtype=ft)
# Float16 can overflow to inf
bit_smaller = ovs[np.isfinite(ovs)].astype(it)
casted_mn = ft(mn).astype(it)
Expand Down
19 changes: 12 additions & 7 deletions nibabel/tests/test_ecat.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,20 @@
from ..ecat import EcatHeader, EcatMlist, EcatSubHeader, EcatImage

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

from ..testing import data_path
from ..testing import data_path, suppress_warnings
from ..tmpdirs import InTemporaryDirectory

from .test_wrapstruct import _TestWrapStructBase
from .test_fileslice import slicer_samples

ecat_file = os.path.join(data_path, 'tinypet.v')


class TestEcatHeader(_TestWrapStructBase):
header_class = EcatHeader
example_file = ecat_file
Expand Down Expand Up @@ -111,7 +111,8 @@ def test_mlist(self):
6.01670000e+04, 1.00000000e+00],
[ 1.68427580e+07, 6.01680000e+04,
7.22000000e+04, 1.00000000e+00]])
assert_true(badordermlist.get_frame_order()[0][0] == 1)
with suppress_warnings(): # STORED order
assert_true(badordermlist.get_frame_order()[0][0] == 1)

def test_mlist_errors(self):
fid = open(self.example_file, 'rb')
Expand All @@ -130,18 +131,21 @@ def test_mlist_errors(self):
6.01670000e+04, 1.00000000e+00],
[ 1.68427580e+07, 6.01680000e+04,
7.22000000e+04, 1.00000000e+00]])
series_framenumbers = mlist.get_series_framenumbers()
with suppress_warnings(): # STORED order
series_framenumbers = mlist.get_series_framenumbers()
# first frame stored was actually 2nd frame acquired
assert_true(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])
mlist._mlist[0,0] = 0
frames_order = mlist.get_frame_order()
with suppress_warnings():
frames_order = mlist.get_frame_order()
neworder =[frames_order[x][0] for x in sorted(frames_order)]
assert_true(neworder == [1, 2, 3, 4, 5])
assert_raises(IOError,
mlist.get_series_framenumbers)
with suppress_warnings():
assert_raises(IOError,
mlist.get_series_framenumbers)



Expand Down Expand Up @@ -178,6 +182,7 @@ def test_subheader(self):
ecat_calib_factor = self.hdr['ecat_calibration_factor']
assert_equal(ecat_calib_factor, 25007614.0)


class TestEcatImage(TestCase):
image_class = EcatImage
example_file = ecat_file
Expand Down
7 changes: 5 additions & 2 deletions nibabel/tests/test_floating.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
int_to_float, floor_log2, type_info, _check_nmant,
_check_maxexp, ok_floats, on_powerpc, have_binary128,
longdouble_precision_improved)
from ..testing import suppress_warnings

from nose import SkipTest
from nose.tools import assert_equal, assert_raises, assert_true, assert_false
Expand Down Expand Up @@ -92,9 +93,11 @@ def test_check_nmant_nexp():
assert_true(_check_nmant(t, nmant))
assert_false(_check_nmant(t, nmant - 1))
assert_false(_check_nmant(t, nmant + 1))
assert_true(_check_maxexp(t, maxexp))
with suppress_warnings(): # overflow
assert_true(_check_maxexp(t, maxexp))
assert_false(_check_maxexp(t, maxexp - 1))
assert_false(_check_maxexp(t, maxexp + 1))
with suppress_warnings():
assert_false(_check_maxexp(t, maxexp + 1))
# Check against type_info
for t in ok_floats():
ti = type_info(t)
Expand Down
2 changes: 2 additions & 0 deletions nibabel/tests/test_minc1.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from __future__ import division, print_function, absolute_import

from os.path import join as pjoin

import gzip
import bz2
import warnings
Expand All @@ -33,6 +34,7 @@

EG_FNAME = pjoin(data_path, 'tiny.mnc')


def test_old_namespace():
# Check old names are defined in minc1 module and top level
# Check warnings raised
Expand Down
Loading