diff --git a/numpy/testing/utils.py b/numpy/testing/utils.py index 133330a12edd..3667e67e007b 100644 --- a/numpy/testing/utils.py +++ b/numpy/testing/utils.py @@ -13,6 +13,7 @@ import shutil import contextlib from tempfile import mkdtemp, mkstemp +from unittest.case import SkipTest from .nosetester import import_nose from numpy.core import float32, empty, arange, array_repr, ndarray @@ -38,20 +39,11 @@ class KnownFailureException(Exception): '''Raise this exception to mark a test as a known failing test.''' pass -KnownFailureTest = KnownFailureException # backwards compat - - -# nose.SkipTest is unittest.case.SkipTest -# import it into the namespace, so that it's available as np.testing.SkipTest -try: - from unittest.case import SkipTest -except ImportError: - # on py2.6 unittest.case is not available. Ask nose for a replacement. - SkipTest = import_nose().SkipTest - +KnownFailureTest = KnownFailureException # backwards compat verbose = 0 + def assert_(val, msg=''): """ Assert that works in release mode. @@ -70,6 +62,7 @@ def assert_(val, msg=''): smsg = msg raise AssertionError(smsg) + def gisnan(x): """like isnan, but always raise an error if type not supported instead of returning a TypeError object. @@ -87,6 +80,7 @@ def gisnan(x): raise TypeError("isnan not supported for this type") return st + def gisfinite(x): """like isfinite, but always raise an error if type not supported instead of returning a TypeError object. @@ -105,6 +99,7 @@ def gisfinite(x): raise TypeError("isfinite not supported for this type") return st + def gisinf(x): """like isinf, but always raise an error if type not supported instead of returning a TypeError object. @@ -123,6 +118,7 @@ def gisinf(x): raise TypeError("isinf not supported for this type") return st + @deprecate(message="numpy.testing.rand is deprecated in numpy 1.11. " "Use numpy.random.rand instead.") def rand(*args): @@ -138,6 +134,7 @@ def rand(*args): f[i] = random.random() return results + if os.name == 'nt': # Code "stolen" from enthought/debug/memusage.py def GetPerformanceAttributes(object, counter, instance=None, @@ -260,6 +257,7 @@ def build_err_msg(arrays, err_msg, header='Items are not equal:', msg.append(' %s: %s' % (names[i], r)) return '\n'.join(msg) + def assert_equal(actual,desired,err_msg='',verbose=True): """ Raises an AssertionError if two objects are not equal. @@ -374,6 +372,7 @@ def assert_equal(actual,desired,err_msg='',verbose=True): if not (desired == actual): raise AssertionError(msg) + def print_assert_equal(test_string, actual, desired): """ Test if two objects are equal, and print an error message if test fails. @@ -414,6 +413,7 @@ def print_assert_equal(test_string, actual, desired): pprint.pprint(desired, msg) raise AssertionError(msg.getvalue()) + def assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=True): """ Raises an AssertionError if two items are not equal up to desired @@ -630,6 +630,7 @@ def assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=True): if np.abs(sc_desired - sc_actual) >= np.power(10., -(significant-1)): raise AssertionError(msg) + def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='', precision=6): __tracebackhide__ = True # Hide traceback for py.test @@ -740,6 +741,7 @@ def chk_same_position(x_id, y_id, hasval='nan'): names=('x', 'y'), precision=precision) raise ValueError(msg) + def assert_array_equal(x, y, err_msg='', verbose=True): """ Raises an AssertionError if two array_like objects are not equal. @@ -806,6 +808,7 @@ def assert_array_equal(x, y, err_msg='', verbose=True): assert_array_compare(operator.__eq__, x, y, err_msg=err_msg, verbose=verbose, header='Arrays are not equal') + def assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True): """ Raises an AssertionError if two objects are not equal up to desired @@ -983,9 +986,11 @@ def assert_array_less(x, y, err_msg='', verbose=True): verbose=verbose, header='Arrays are not less-ordered') + def runstring(astr, dict): exec(astr, dict) + def assert_string_equal(actual, desired): """ Test if two strings are equal. @@ -1390,6 +1395,7 @@ def compare(x, y): assert_array_compare(compare, actual, desired, err_msg=str(err_msg), verbose=verbose, header=header) + def assert_array_almost_equal_nulp(x, y, nulp=1): """ Compare two arrays relatively to their spacing. @@ -1452,6 +1458,7 @@ def assert_array_almost_equal_nulp(x, y, nulp=1): msg = "X and Y are not equal to %d ULP (max is %g)" % (nulp, max_nulp) raise AssertionError(msg) + def assert_array_max_ulp(a, b, maxulp=1, dtype=None): """ Check that all items of arrays differ in at most N Units in the Last Place. @@ -1496,6 +1503,7 @@ def assert_array_max_ulp(a, b, maxulp=1, dtype=None): maxulp) return ret + def nulp_diff(x, y, dtype=None): """For each item in x and y, return the number of representable floating points between them. @@ -1549,6 +1557,7 @@ def _diff(rx, ry, vdt): ry = integer_repr(y) return _diff(rx, ry, t) + def _integer_repr(x, vdt, comp): # Reinterpret binary representation of the float as sign-magnitude: # take into account two-complement representation @@ -1563,6 +1572,7 @@ def _integer_repr(x, vdt, comp): return rx + def integer_repr(x): """Return the signed-magnitude interpretation of the binary representation of x.""" @@ -1574,6 +1584,7 @@ def integer_repr(x): else: raise ValueError("Unsupported dtype %s" % x.dtype) + # The following two classes are copied from python 2.6 warnings module (context # manager) class WarningMessage(object): @@ -1608,6 +1619,7 @@ def __str__(self): "line : %r}" % (self.message, self._category_name, self.filename, self.lineno, self.line)) + class WarningManager(object): """ A context manager that copies and restores the warnings filter upon @@ -1855,6 +1867,7 @@ def tempdir(*args, **kwargs): finally: shutil.rmtree(tmpdir) + @contextlib.contextmanager def temppath(*args, **kwargs): """Context manager for temporary files. @@ -1863,7 +1876,7 @@ def temppath(*args, **kwargs): parameters are the same as for tempfile.mkstemp and are passed directly to that function. The underlying file is removed when the context is exited, so it should be closed at that time. - + Windows does not allow a temporary file to be opened if it is already open, so the underlying file must be closed after opening before it can be opened again.