summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAlan McIntyre <alan.mcintyre@local>2008-06-17 00:23:20 +0000
committerAlan McIntyre <alan.mcintyre@local>2008-06-17 00:23:20 +0000
commitc331857d8663ecf54bbe88c834755da749e8ab52 (patch)
treef4cc69ec328a5ff4d3b108f3610acb119a196493
parent22ba7886a84dc6a16ca75871f7cd2f10ef8de1f9 (diff)
downloadnumpy-c331857d8663ecf54bbe88c834755da749e8ab52.tar.gz
Switched to use nose to run tests. Added test and bench functions to all modules.
-rw-r--r--README.txt9
-rw-r--r--numpy/__init__.py16
-rw-r--r--numpy/core/__init__.py7
-rw-r--r--numpy/core/tests/test_defmatrix.py75
-rw-r--r--numpy/core/tests/test_errstate.py11
-rw-r--r--numpy/core/tests/test_memmap.py10
-rw-r--r--numpy/core/tests/test_multiarray.py228
-rw-r--r--numpy/core/tests/test_numeric.py105
-rw-r--r--numpy/core/tests/test_numerictypes.py67
-rw-r--r--numpy/core/tests/test_records.py41
-rw-r--r--numpy/core/tests/test_regression.py302
-rw-r--r--numpy/core/tests/test_scalarmath.py30
-rw-r--r--numpy/core/tests/test_ufunc.py9
-rw-r--r--numpy/core/tests/test_umath.py71
-rw-r--r--numpy/core/tests/test_unicode.py132
-rw-r--r--numpy/distutils/__init__.py6
-rw-r--r--numpy/distutils/tests/f2py_ext/tests/test_fib2.py6
-rw-r--r--numpy/distutils/tests/f2py_f90_ext/tests/test_foo.py6
-rw-r--r--numpy/distutils/tests/gen_ext/tests/test_fib3.py6
-rw-r--r--numpy/distutils/tests/pyrex_ext/tests/test_primes.py6
-rw-r--r--numpy/distutils/tests/swig_ext/tests/test_example.py8
-rw-r--r--numpy/distutils/tests/swig_ext/tests/test_example2.py6
-rw-r--r--numpy/distutils/tests/test_fcompiler_gnu.py6
-rw-r--r--numpy/distutils/tests/test_misc_util.py19
-rw-r--r--numpy/doc/DISTUTILS.txt38
-rw-r--r--numpy/f2py/lib/parser/test_Fortran2003.py474
-rw-r--r--numpy/f2py/lib/parser/test_parser.py143
-rw-r--r--numpy/f2py/lib/tests/test_derived_scalar.py8
-rw-r--r--numpy/f2py/lib/tests/test_module_module.py6
-rw-r--r--numpy/f2py/lib/tests/test_module_scalar.py8
-rw-r--r--numpy/f2py/lib/tests/test_scalar_function_in.py33
-rw-r--r--numpy/f2py/lib/tests/test_scalar_in_out.py35
-rw-r--r--numpy/f2py/tests/array_from_pyobj/tests/test_array_from_pyobj.py49
-rw-r--r--numpy/fft/__init__.py6
-rw-r--r--numpy/fft/tests/test_fftpack.py12
-rw-r--r--numpy/fft/tests/test_helper.py16
-rw-r--r--numpy/lib/__init__.py7
-rw-r--r--numpy/lib/tests/test__datasource.py14
-rw-r--r--numpy/lib/tests/test_arraysetops.py26
-rw-r--r--numpy/lib/tests/test_financial.py7
-rw-r--r--numpy/lib/tests/test_format.py4
-rw-r--r--numpy/lib/tests/test_function_base.py163
-rw-r--r--numpy/lib/tests/test_getlimits.py28
-rw-r--r--numpy/lib/tests/test_index_tricks.py19
-rw-r--r--numpy/lib/tests/test_io.py9
-rw-r--r--numpy/lib/tests/test_machar.py7
-rw-r--r--numpy/lib/tests/test_polynomial.py14
-rw-r--r--numpy/lib/tests/test_regression.py4
-rw-r--r--numpy/lib/tests/test_shape_base.py175
-rw-r--r--numpy/lib/tests/test_twodim_base.py46
-rw-r--r--numpy/lib/tests/test_type_check.py127
-rw-r--r--numpy/lib/tests/test_ufunclike.py8
-rw-r--r--numpy/linalg/__init__.py6
-rw-r--r--numpy/linalg/tests/test_linalg.py52
-rw-r--r--numpy/linalg/tests/test_regression.py5
-rw-r--r--numpy/ma/__init__.py4
-rw-r--r--numpy/ma/tests/test_core.py60
-rw-r--r--numpy/ma/tests/test_extras.py49
-rw-r--r--numpy/ma/tests/test_mrecords.py10
-rw-r--r--numpy/ma/tests/test_old_ma.py219
-rw-r--r--numpy/ma/tests/test_subclassing.py26
-rw-r--r--numpy/ma/testutils.py10
-rw-r--r--numpy/numarray/__init__.py4
-rw-r--r--numpy/oldnumeric/__init__.py4
-rw-r--r--numpy/oldnumeric/tests/test_oldnumeric.py4
-rw-r--r--numpy/random/__init__.py6
-rw-r--r--numpy/random/tests/test_random.py6
-rw-r--r--numpy/testing/__init__.py24
-rw-r--r--numpy/testing/decorators.py92
-rw-r--r--numpy/testing/info.py30
-rw-r--r--numpy/testing/nosetester.py140
-rw-r--r--numpy/testing/nulltester.py15
-rw-r--r--numpy/testing/numpytest.py548
-rw-r--r--numpy/testing/parametric.py300
-rw-r--r--numpy/testing/pkgtester.py27
-rw-r--r--numpy/testing/tests/test_utils.py7
-rw-r--r--numpy/testing/utils.py53
-rw-r--r--numpy/tests/test_ctypeslib.py19
78 files changed, 1947 insertions, 2441 deletions
diff --git a/README.txt b/README.txt
index a1fa2f6d2..97856eb5c 100644
--- a/README.txt
+++ b/README.txt
@@ -9,11 +9,16 @@ find it. You can guide the process using a site.cfg file.
If fast BLAS and LAPACK cannot be found, then a slower default version is used.
After installation, tests can be run (from outside the source
-directory) with
+directory) with:
python -c 'import numpy; numpy.test()'
-The most current development version is always available from our
+Please note that you must have the 'nose' test framework installed in order to
+run the tests. More information about nose is available here:
+
+http://somethingaboutorange.com/mrl/projects/nose/
+
+The most current development version of NumPy is always available from our
subversion repository:
http://svn.scipy.org/svn/numpy/trunk
diff --git a/numpy/__init__.py b/numpy/__init__.py
index e4c58e3dd..87c350ad5 100644
--- a/numpy/__init__.py
+++ b/numpy/__init__.py
@@ -94,8 +94,11 @@ else:
__all__ = ['add_newdocs']
pkgload.__doc__ = PackageLoader.__call__.__doc__
- import testing
- from testing import ScipyTest, NumpyTest
+
+ from testing.pkgtester import Tester
+ test = Tester().test
+ bench = Tester().bench
+
import core
from core import *
import lib
@@ -113,15 +116,8 @@ else:
from core import round, abs, max, min
__all__.extend(['__version__', 'pkgload', 'PackageLoader',
- 'ScipyTest', 'NumpyTest', 'show_config'])
+ 'show_config'])
__all__.extend(core.__all__)
__all__.extend(lib.__all__)
__all__.extend(['linalg', 'fft', 'random', 'ctypeslib'])
- def test(*args, **kw):
- import os, sys
- print 'Numpy is installed in %s' % (os.path.split(__file__)[0],)
- print 'Numpy version %s' % (__version__,)
- print 'Python version %s' % (sys.version.replace('\n', '',),)
- return NumpyTest().test(*args, **kw)
- test.__doc__ = NumpyTest.test.__doc__
diff --git a/numpy/core/__init__.py b/numpy/core/__init__.py
index 37ed7213e..e2beb3fb3 100644
--- a/numpy/core/__init__.py
+++ b/numpy/core/__init__.py
@@ -31,7 +31,6 @@ __all__ += rec.__all__
__all__ += char.__all__
-
-def test(level=1, verbosity=1):
- from numpy.testing import NumpyTest
- return NumpyTest().test(level, verbosity)
+from numpy.testing.pkgtester import Tester
+test = Tester().test
+bench = Tester().bench
diff --git a/numpy/core/tests/test_defmatrix.py b/numpy/core/tests/test_defmatrix.py
index da711014c..d5f4ebfaa 100644
--- a/numpy/core/tests/test_defmatrix.py
+++ b/numpy/core/tests/test_defmatrix.py
@@ -1,12 +1,12 @@
+import sys
from numpy.testing import *
set_package_path()
-import numpy.core;reload(numpy.core)
from numpy.core import *
import numpy as np
restore_path()
-class TestCtor(NumpyTestCase):
- def check_basic(self):
+class TestCtor(TestCase):
+ def test_basic(self):
A = array([[1,2],[3,4]])
mA = matrix(A)
assert all(mA.A == A)
@@ -24,8 +24,9 @@ class TestCtor(NumpyTestCase):
mvec = matrix(vec)
assert mvec.shape == (1,5)
-class TestProperties(NumpyTestCase):
- def check_sum(self):
+
+class TestProperties(TestCase):
+ def test_sum(self):
"""Test whether matrix.sum(axis=1) preserves orientation.
Fails in NumPy <= 0.9.6.2127.
"""
@@ -40,7 +41,7 @@ class TestProperties(NumpyTestCase):
assert_array_equal(sum1, M.sum(axis=1))
assert sumall == M.sum()
- def check_basic(self):
+ def test_basic(self):
import numpy.linalg as linalg
A = array([[1., 2.],
@@ -57,7 +58,7 @@ class TestProperties(NumpyTestCase):
assert all(array(transpose(B) == mB.T))
assert all(array(conjugate(transpose(B)) == mB.H))
- def check_comparisons(self):
+ def test_comparisons(self):
A = arange(100).reshape(10,10)
mA = matrix(A)
mB = matrix(A) + 0.1
@@ -81,19 +82,20 @@ class TestProperties(NumpyTestCase):
assert not all(abs(mA) > 0)
assert all(abs(mB > 0))
- def check_asmatrix(self):
+ def test_asmatrix(self):
A = arange(100).reshape(10,10)
mA = asmatrix(A)
A[0,0] = -10
assert A[0,0] == mA[0,0]
- def check_noaxis(self):
+ def test_noaxis(self):
A = matrix([[1,0],[0,1]])
assert A.sum() == matrix(2)
assert A.mean() == matrix(0.5)
-class TestCasting(NumpyTestCase):
- def check_basic(self):
+
+class TestCasting(TestCase):
+ def test_basic(self):
A = arange(100).reshape(10,10)
mA = matrix(A)
@@ -110,8 +112,9 @@ class TestCasting(NumpyTestCase):
assert mC.dtype.type == complex128
assert all(mA != mB)
-class TestAlgebra(NumpyTestCase):
- def check_basic(self):
+
+class TestAlgebra(TestCase):
+ def test_basic(self):
import numpy.linalg as linalg
A = array([[1., 2.],
@@ -133,8 +136,9 @@ class TestAlgebra(NumpyTestCase):
assert allclose((mA + mA).A, (A + A))
assert allclose((3*mA).A, (3*A))
-class TestMatrixReturn(NumpyTestCase):
- def check_instance_methods(self):
+
+class TestMatrixReturn(TestCase):
+ def test_instance_methods(self):
a = matrix([1.0], dtype='f8')
methodargs = {
'astype' : ('intc',),
@@ -172,33 +176,35 @@ class TestMatrixReturn(NumpyTestCase):
assert type(c) is matrix
assert type(d) is matrix
-class TestIndexing(NumpyTestCase):
- def check_basic(self):
+
+class TestIndexing(TestCase):
+ def test_basic(self):
x = asmatrix(zeros((3,2),float))
y = zeros((3,1),float)
y[:,0] = [0.8,0.2,0.3]
x[:,1] = y>0.5
assert_equal(x, [[0,1],[0,0],[0,0]])
-class TestNewScalarIndexing(NumpyTestCase):
+
+class TestNewScalarIndexing(TestCase):
def setUp(self):
self.a = matrix([[1, 2],[3,4]])
- def check_dimesions(self):
+ def test_dimesions(self):
a = self.a
x = a[0]
assert_equal(x.ndim, 2)
- def check_array_from_matrix_list(self):
+ def test_array_from_matrix_list(self):
a = self.a
x = array([a, a])
assert_equal(x.shape, [2,2,2])
- def check_array_to_list(self):
+ def test_array_to_list(self):
a = self.a
assert_equal(a.tolist(),[[1, 2], [3, 4]])
- def check_fancy_indexing(self):
+ def test_fancy_indexing(self):
a = self.a
x = a[1, [0,1,0]]
assert isinstance(x, matrix)
@@ -216,30 +222,36 @@ class TestNewScalarIndexing(NumpyTestCase):
## assert_equal(x[0].shape,(1,3))
## assert_equal(x[:,0].shape,(2,1))
-## x = matrix(0)
-## assert_equal(x[0,0],0)
-## assert_equal(x[0],0)
-## assert_equal(x[:,0].shape,x.shape)
+ def test_matrix_element(self):
+ x = matrix([[1,2,3],[4,5,6]])
+ assert_equal(x[0][0].shape,(1,3))
+ assert_equal(x[0].shape,(1,3))
+ assert_equal(x[:,0].shape,(2,1))
- def check_scalar_indexing(self):
+ x = matrix(0)
+ assert_equal(x[0,0],0)
+ assert_equal(x[0],0)
+ assert_equal(x[:,0].shape,x.shape)
+
+ def test_scalar_indexing(self):
x = asmatrix(zeros((3,2),float))
assert_equal(x[0,0],x[0][0])
- def check_row_column_indexing(self):
+ def test_row_column_indexing(self):
x = asmatrix(np.eye(2))
assert_array_equal(x[0,:],[[1,0]])
assert_array_equal(x[1,:],[[0,1]])
assert_array_equal(x[:,0],[[1],[0]])
assert_array_equal(x[:,1],[[0],[1]])
- def check_boolean_indexing(self):
+ def test_boolean_indexing(self):
A = arange(6)
A.shape = (3,2)
x = asmatrix(A)
assert_array_equal(x[:,array([True,False])],x[:,0])
assert_array_equal(x[array([True,False,False]),:],x[0,:])
- def check_list_indexing(self):
+ def test_list_indexing(self):
A = arange(6)
A.shape = (3,2)
x = asmatrix(A)
@@ -247,6 +259,5 @@ class TestNewScalarIndexing(NumpyTestCase):
assert_array_equal(x[[2,1,0],:],x[::-1,:])
-
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/core/tests/test_errstate.py b/numpy/core/tests/test_errstate.py
index 1e1082559..b8b98d138 100644
--- a/numpy/core/tests/test_errstate.py
+++ b/numpy/core/tests/test_errstate.py
@@ -12,11 +12,7 @@ from numpy.core import *
from numpy.random import rand, randint
from numpy.testing import *
-
-
-class TestErrstate(NumpyTestCase):
-
-
+class TestErrstate(TestCase):
def test_invalid(self):
with errstate(all='raise', under='ignore'):
a = -arange(3)
@@ -57,6 +53,5 @@ class TestErrstate(NumpyTestCase):
"""
-if __name__ == '__main__':
- from numpy.testing import *
- NumpyTest().run()
+if __name__ == "__main__":
+ nose.run(argv=['', __file__])
diff --git a/numpy/core/tests/test_memmap.py b/numpy/core/tests/test_memmap.py
index bc0001f79..ce51514d4 100644
--- a/numpy/core/tests/test_memmap.py
+++ b/numpy/core/tests/test_memmap.py
@@ -1,13 +1,12 @@
from tempfile import NamedTemporaryFile, mktemp
import os
+import warnings
from numpy.core import memmap
from numpy import arange, allclose
from numpy.testing import *
-import warnings
-
-class TestMemmap(NumpyTestCase):
+class TestMemmap(TestCase):
def setUp(self):
self.tmpfp = NamedTemporaryFile(prefix='mmap')
self.shape = (3,4)
@@ -46,5 +45,6 @@ class TestMemmap(NumpyTestCase):
fp.sync()
warnings.simplefilter('default', DeprecationWarning)
-if __name__ == '__main__':
- NumpyTest().run()
+
+if __name__ == "__main__":
+ nose.run(argv=['', __file__])
diff --git a/numpy/core/tests/test_multiarray.py b/numpy/core/tests/test_multiarray.py
index 163ec7f90..723536908 100644
--- a/numpy/core/tests/test_multiarray.py
+++ b/numpy/core/tests/test_multiarray.py
@@ -1,15 +1,14 @@
import tempfile
-
+import sys
import numpy as np
from numpy.testing import *
from numpy.core import *
-
-class TestFlags(NumpyTestCase):
+class TestFlags(TestCase):
def setUp(self):
self.a = arange(10)
- def check_writeable(self):
+ def test_writeable(self):
mydict = locals()
self.a.flags.writeable = False
self.assertRaises(RuntimeError, runstring, 'self.a[0] = 3', mydict)
@@ -17,7 +16,7 @@ class TestFlags(NumpyTestCase):
self.a[0] = 5
self.a[0] = 0
- def check_otherflags(self):
+ def test_otherflags(self):
assert_equal(self.a.flags.carray, True)
assert_equal(self.a.flags.farray, False)
assert_equal(self.a.flags.behaved, True)
@@ -29,13 +28,13 @@ class TestFlags(NumpyTestCase):
assert_equal(self.a.flags.updateifcopy, False)
-class TestAttributes(NumpyTestCase):
+class TestAttributes(TestCase):
def setUp(self):
self.one = arange(10)
self.two = arange(20).reshape(4,5)
self.three = arange(60,dtype=float64).reshape(2,5,6)
- def check_attributes(self):
+ def test_attributes(self):
assert_equal(self.one.shape, (10,))
assert_equal(self.two.shape, (4,5))
assert_equal(self.three.shape, (2,5,6))
@@ -56,7 +55,7 @@ class TestAttributes(NumpyTestCase):
assert_equal(self.two.itemsize, self.two.dtype.itemsize)
assert_equal(self.two.base, arange(20))
- def check_dtypeattr(self):
+ def test_dtypeattr(self):
assert_equal(self.one.dtype, dtype(int_))
assert_equal(self.three.dtype, dtype(float_))
assert_equal(self.one.dtype.char, 'l')
@@ -65,7 +64,7 @@ class TestAttributes(NumpyTestCase):
assert_equal(self.one.dtype.str[1], 'i')
assert_equal(self.three.dtype.str[1], 'f')
- def check_stridesattr(self):
+ def test_stridesattr(self):
x = self.one
def make_array(size, offset, strides):
return ndarray([size], buffer=x, dtype=int,
@@ -79,7 +78,7 @@ class TestAttributes(NumpyTestCase):
#self.failUnlessRaises(ValueError, lambda: ndarray([1], strides=4))
- def check_set_stridesattr(self):
+ def test_set_stridesattr(self):
x = self.one
def make_array(size, offset, strides):
try:
@@ -94,7 +93,7 @@ class TestAttributes(NumpyTestCase):
self.failUnlessRaises(ValueError, make_array, 8, 3, 1)
#self.failUnlessRaises(ValueError, make_array, 8, 3, 0)
- def check_fill(self):
+ def test_fill(self):
for t in "?bhilqpBHILQPfdgFDGO":
x = empty((3,2,1), t)
y = empty((3,2,1), t)
@@ -106,82 +105,85 @@ class TestAttributes(NumpyTestCase):
x.fill(x[0])
assert_equal(x['f1'][1], x['f1'][0])
-class TestDtypedescr(NumpyTestCase):
- def check_construction(self):
+
+class TestDtypedescr(TestCase):
+ def test_construction(self):
d1 = dtype('i4')
assert_equal(d1, dtype(int32))
d2 = dtype('f8')
assert_equal(d2, dtype(float64))
-class TestFromstring(NumpyTestCase):
- def check_binary(self):
+
+class TestFromstring(TestCase):
+ def test_binary(self):
a = fromstring('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@',dtype='<f4')
assert_array_equal(a, array([1,2,3,4]))
- def check_string(self):
+ def test_string(self):
a = fromstring('1,2,3,4', sep=',')
assert_array_equal(a, [1., 2., 3., 4.])
- def check_counted_string(self):
+ def test_counted_string(self):
a = fromstring('1,2,3,4', count=4, sep=',')
assert_array_equal(a, [1., 2., 3., 4.])
a = fromstring('1,2,3,4', count=3, sep=',')
assert_array_equal(a, [1., 2., 3.])
- def check_string_with_ws(self):
+ def test_string_with_ws(self):
a = fromstring('1 2 3 4 ', dtype=int, sep=' ')
assert_array_equal(a, [1, 2, 3, 4])
- def check_counted_string_with_ws(self):
+ def test_counted_string_with_ws(self):
a = fromstring('1 2 3 4 ', count=3, dtype=int, sep=' ')
assert_array_equal(a, [1, 2, 3])
- def check_ascii(self):
+ def test_ascii(self):
a = fromstring('1 , 2 , 3 , 4', sep=',')
b = fromstring('1,2,3,4', dtype=float, sep=',')
assert_array_equal(a, [1.,2.,3.,4.])
assert_array_equal(a,b)
-class TestZeroRank(NumpyTestCase):
+
+class TestZeroRank(TestCase):
def setUp(self):
self.d = array(0), array('x', object)
- def check_ellipsis_subscript(self):
+ def test_ellipsis_subscript(self):
a,b = self.d
self.failUnlessEqual(a[...], 0)
self.failUnlessEqual(b[...], 'x')
self.failUnless(a[...] is a)
self.failUnless(b[...] is b)
- def check_empty_subscript(self):
+ def test_empty_subscript(self):
a,b = self.d
self.failUnlessEqual(a[()], 0)
self.failUnlessEqual(b[()], 'x')
self.failUnless(type(a[()]) is a.dtype.type)
self.failUnless(type(b[()]) is str)
- def check_invalid_subscript(self):
+ def test_invalid_subscript(self):
a,b = self.d
self.failUnlessRaises(IndexError, lambda x: x[0], a)
self.failUnlessRaises(IndexError, lambda x: x[0], b)
self.failUnlessRaises(IndexError, lambda x: x[array([], int)], a)
self.failUnlessRaises(IndexError, lambda x: x[array([], int)], b)
- def check_ellipsis_subscript_assignment(self):
+ def test_ellipsis_subscript_assignment(self):
a,b = self.d
a[...] = 42
self.failUnlessEqual(a, 42)
b[...] = ''
self.failUnlessEqual(b.item(), '')
- def check_empty_subscript_assignment(self):
+ def test_empty_subscript_assignment(self):
a,b = self.d
a[()] = 42
self.failUnlessEqual(a, 42)
b[()] = ''
self.failUnlessEqual(b.item(), '')
- def check_invalid_subscript_assignment(self):
+ def test_invalid_subscript_assignment(self):
a,b = self.d
def assign(x, i, v):
x[i] = v
@@ -189,7 +191,7 @@ class TestZeroRank(NumpyTestCase):
self.failUnlessRaises(IndexError, assign, b, 0, '')
self.failUnlessRaises(ValueError, assign, a, (), '')
- def check_newaxis(self):
+ def test_newaxis(self):
a,b = self.d
self.failUnlessEqual(a[newaxis].shape, (1,))
self.failUnlessEqual(a[..., newaxis].shape, (1,))
@@ -200,13 +202,13 @@ class TestZeroRank(NumpyTestCase):
self.failUnlessEqual(a[newaxis, newaxis, ...].shape, (1,1))
self.failUnlessEqual(a[(newaxis,)*10].shape, (1,)*10)
- def check_invalid_newaxis(self):
+ def test_invalid_newaxis(self):
a,b = self.d
def subscript(x, i): x[i]
self.failUnlessRaises(IndexError, subscript, a, (newaxis, 0))
self.failUnlessRaises(IndexError, subscript, a, (newaxis,)*50)
- def check_constructor(self):
+ def test_constructor(self):
x = ndarray(())
x[()] = 5
self.failUnlessEqual(x[()], 5)
@@ -214,36 +216,37 @@ class TestZeroRank(NumpyTestCase):
y[()] = 6
self.failUnlessEqual(x[()], 6)
- def check_output(self):
+ def test_output(self):
x = array(2)
self.failUnlessRaises(ValueError, add, x, [1], x)
-class TestScalarIndexing(NumpyTestCase):
+
+class TestScalarIndexing(TestCase):
def setUp(self):
self.d = array([0,1])[0]
- def check_ellipsis_subscript(self):
+ def test_ellipsis_subscript(self):
a = self.d
self.failUnlessEqual(a[...], 0)
self.failUnlessEqual(a[...].shape,())
- def check_empty_subscript(self):
+ def test_empty_subscript(self):
a = self.d
self.failUnlessEqual(a[()], 0)
self.failUnlessEqual(a[()].shape,())
- def check_invalid_subscript(self):
+ def test_invalid_subscript(self):
a = self.d
self.failUnlessRaises(IndexError, lambda x: x[0], a)
self.failUnlessRaises(IndexError, lambda x: x[array([], int)], a)
- def check_invalid_subscript_assignment(self):
+ def test_invalid_subscript_assignment(self):
a = self.d
def assign(x, i, v):
x[i] = v
self.failUnlessRaises(TypeError, assign, a, 0, 42)
- def check_newaxis(self):
+ def test_newaxis(self):
a = self.d
self.failUnlessEqual(a[newaxis].shape, (1,))
self.failUnlessEqual(a[..., newaxis].shape, (1,))
@@ -254,22 +257,21 @@ class TestScalarIndexing(NumpyTestCase):
self.failUnlessEqual(a[newaxis, newaxis, ...].shape, (1,1))
self.failUnlessEqual(a[(newaxis,)*10].shape, (1,)*10)
- def check_invalid_newaxis(self):
+ def test_invalid_newaxis(self):
a = self.d
def subscript(x, i): x[i]
self.failUnlessRaises(IndexError, subscript, a, (newaxis, 0))
self.failUnlessRaises(IndexError, subscript, a, (newaxis,)*50)
-
-class TestCreation(NumpyTestCase):
- def check_from_attribute(self):
+class TestCreation(TestCase):
+ def test_from_attribute(self):
class x(object):
def __array__(self, dtype=None):
pass
self.failUnlessRaises(ValueError, array, x())
- def check_from_string(self) :
+ def test_from_string(self) :
types = np.typecodes['AllInteger'] + np.typecodes['Float']
nstr = ['123','123']
result = array([123, 123], dtype=int)
@@ -277,8 +279,9 @@ class TestCreation(NumpyTestCase):
msg = 'String conversion for %s' % type
assert_equal(array(nstr, dtype=type), result, err_msg=msg)
-class TestBool(NumpyTestCase):
- def check_test_interning(self):
+
+class TestBool(TestCase):
+ def test_test_interning(self):
a0 = bool_(0)
b0 = bool_(False)
self.failUnless(a0 is b0)
@@ -289,21 +292,21 @@ class TestBool(NumpyTestCase):
self.failUnless(array(True)[()] is a1)
-class TestMethods(NumpyTestCase):
- def check_test_round(self):
+class TestMethods(TestCase):
+ def test_test_round(self):
assert_equal(array([1.2,1.5]).round(), [1,2])
assert_equal(array(1.5).round(), 2)
assert_equal(array([12.2,15.5]).round(-1), [10,20])
assert_equal(array([12.15,15.51]).round(1), [12.2,15.5])
- def check_transpose(self):
+ def test_transpose(self):
a = array([[1,2],[3,4]])
assert_equal(a.transpose(), [[1,3],[2,4]])
self.failUnlessRaises(ValueError, lambda: a.transpose(0))
self.failUnlessRaises(ValueError, lambda: a.transpose(0,0))
self.failUnlessRaises(ValueError, lambda: a.transpose(0,1,2))
- def check_sort(self):
+ def test_sort(self):
# all c scalar sorts use the same code with different types
# so it suffices to run a quick check with one type. The number
# of sorted items must be greater than ~50 to check the actual
@@ -390,7 +393,7 @@ class TestMethods(NumpyTestCase):
# d.sort(axis=None)
#assert_equal(d, c, "test sort with axis=None")
- def check_argsort(self):
+ def test_argsort(self):
# all c scalar argsorts use the same code with different types
# so it suffices to run a quick check with one type. The number
# of sorted items must be greater than ~50 to check the actual
@@ -468,7 +471,7 @@ class TestMethods(NumpyTestCase):
a = np.array(['aaaaaaaaa' for i in range(100)], dtype=np.unicode)
assert_equal(a.argsort(kind='m'), r)
- def check_flatten(self):
+ def test_flatten(self):
x0 = np.array([[1,2,3],[4,5,6]], np.int32)
x1 = np.array([[[1,2],[3,4]],[[5,6],[7,8]]], np.int32)
y0 = np.array([1,2,3,4,5,6], np.int32)
@@ -482,14 +485,16 @@ class TestMethods(NumpyTestCase):
assert_equal(x1.flatten('F'), y1f)
assert_equal(x1.flatten('F'), x1.T.flatten())
-class TestSubscripting(NumpyTestCase):
- def check_test_zero_rank(self):
+
+class TestSubscripting(TestCase):
+ def test_test_zero_rank(self):
x = array([1,2,3])
self.failUnless(isinstance(x[0], int))
self.failUnless(type(x[0, ...]) is ndarray)
-class TestPickling(NumpyTestCase):
- def check_both(self):
+
+class TestPickling(TestCase):
+ def test_both(self):
import pickle
carray = array([[2,9],[7,0],[3,8]])
tarray = transpose(carray)
@@ -498,45 +503,46 @@ class TestPickling(NumpyTestCase):
# version 0 pickles, using protocol=2 to pickle
# version 0 doesn't have a version field
- def check_version0_int8(self):
+ def test_version0_int8(self):
s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x04\x85cnumpy\ndtype\nq\x04U\x02i1K\x00K\x01\x87Rq\x05(U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x04\x01\x02\x03\x04tb.'
a = array([1,2,3,4], dtype=int8)
p = loads(s)
assert_equal(a, p)
- def check_version0_float32(self):
+ def test_version0_float32(self):
s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x04\x85cnumpy\ndtype\nq\x04U\x02f4K\x00K\x01\x87Rq\x05(U\x01<NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x10\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@tb.'
a = array([1.0, 2.0, 3.0, 4.0], dtype=float32)
p = loads(s)
assert_equal(a, p)
- def check_version0_object(self):
+ def test_version0_object(self):
s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x02\x85cnumpy\ndtype\nq\x04U\x02O8K\x00K\x01\x87Rq\x05(U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89]q\x06(}q\x07U\x01aK\x01s}q\x08U\x01bK\x02setb.'
a = array([{'a':1}, {'b':2}])
p = loads(s)
assert_equal(a, p)
# version 1 pickles, using protocol=2 to pickle
- def check_version1_int8(self):
+ def test_version1_int8(self):
s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x01K\x04\x85cnumpy\ndtype\nq\x04U\x02i1K\x00K\x01\x87Rq\x05(K\x01U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x04\x01\x02\x03\x04tb.'
a = array([1,2,3,4], dtype=int8)
p = loads(s)
assert_equal(a, p)
- def check_version1_float32(self):
+ def test_version1_float32(self):
s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x01K\x04\x85cnumpy\ndtype\nq\x04U\x02f4K\x00K\x01\x87Rq\x05(K\x01U\x01<NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x10\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@tb.'
a = array([1.0, 2.0, 3.0, 4.0], dtype=float32)
p = loads(s)
assert_equal(a, p)
- def check_version1_object(self):
+ def test_version1_object(self):
s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x01K\x02\x85cnumpy\ndtype\nq\x04U\x02O8K\x00K\x01\x87Rq\x05(K\x01U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89]q\x06(}q\x07U\x01aK\x01s}q\x08U\x01bK\x02setb.'
a = array([{'a':1}, {'b':2}])
p = loads(s)
assert_equal(a, p)
-class TestFancyIndexing(NumpyTestCase):
- def check_list(self):
+
+class TestFancyIndexing(TestCase):
+ def test_list(self):
x = ones((1,1))
x[:,[0]] = 2.0
assert_array_equal(x, array([[2.0]]))
@@ -545,7 +551,7 @@ class TestFancyIndexing(NumpyTestCase):
x[:,:,[0]] = 2.0
assert_array_equal(x, array([[[2.0]]]))
- def check_tuple(self):
+ def test_tuple(self):
x = ones((1,1))
x[:,(0,)] = 2.0
assert_array_equal(x, array([[2.0]]))
@@ -553,8 +559,9 @@ class TestFancyIndexing(NumpyTestCase):
x[:,:,(0,)] = 2.0
assert_array_equal(x, array([[[2.0]]]))
-class TestStringCompare(NumpyTestCase):
- def check_string(self):
+
+class TestStringCompare(TestCase):
+ def test_string(self):
g1 = array(["This","is","example"])
g2 = array(["This","was","example"])
assert_array_equal(g1 == g2, [g1[i] == g2[i] for i in [0,1,2]])
@@ -564,7 +571,7 @@ class TestStringCompare(NumpyTestCase):
assert_array_equal(g1 < g2, [g1[i] < g2[i] for i in [0,1,2]])
assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0,1,2]])
- def check_mixed(self):
+ def test_mixed(self):
g1 = array(["spam","spa","spammer","and eggs"])
g2 = "spam"
assert_array_equal(g1 == g2, [x == g2 for x in g1])
@@ -575,7 +582,7 @@ class TestStringCompare(NumpyTestCase):
assert_array_equal(g1 >= g2, [x >= g2 for x in g1])
- def check_unicode(self):
+ def test_unicode(self):
g1 = array([u"This",u"is",u"example"])
g2 = array([u"This",u"was",u"example"])
assert_array_equal(g1 == g2, [g1[i] == g2[i] for i in [0,1,2]])
@@ -586,8 +593,8 @@ class TestStringCompare(NumpyTestCase):
assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0,1,2]])
-class TestArgmax(NumpyTestCase):
- def check_all(self):
+class TestArgmax(TestCase):
+ def test_all(self):
a = np.random.normal(0,1,(4,5,6,7,8))
for i in xrange(a.ndim):
amax = a.max(i)
@@ -596,13 +603,15 @@ class TestArgmax(NumpyTestCase):
axes.remove(i)
assert all(amax == aargmax.choose(*a.transpose(i,*axes)))
-class TestNewaxis(NumpyTestCase):
- def check_basic(self):
+
+class TestNewaxis(TestCase):
+ def test_basic(self):
sk = array([0,-0.1,0.1])
res = 250*sk[:,newaxis]
assert_almost_equal(res.ravel(),250*sk)
-class TestClip(NumpyTestCase):
+
+class TestClip(TestCase):
def _check_range(self,x,cmin,cmax):
assert np.all(x >= cmin)
assert np.all(x <= cmax)
@@ -636,7 +645,7 @@ class TestClip(NumpyTestCase):
self._check_range(x,expected_min,expected_max)
return x
- def check_basic(self):
+ def test_basic(self):
for inplace in [False, True]:
self._clip_type('float',1024,-12.8,100.2, inplace=inplace)
self._clip_type('float',1024,0,0, inplace=inplace)
@@ -647,13 +656,13 @@ class TestClip(NumpyTestCase):
x = self._clip_type('uint',1024,-120,100,expected_min=0, inplace=inplace)
x = self._clip_type('uint',1024,0,0, inplace=inplace)
- def check_record_array(self):
+ def test_record_array(self):
rec = np.array([(-5, 2.0, 3.0), (5.0, 4.0, 3.0)],
dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8')])
y = rec['x'].clip(-0.3,0.5)
self._check_range(y,-0.3,0.5)
- def check_max_or_min(self):
+ def test_max_or_min(self):
val = np.array([0,1,2,3,4,5,6,7])
x = val.clip(3)
assert np.all(x >= 3)
@@ -662,24 +671,24 @@ class TestClip(NumpyTestCase):
x = val.clip(max=4)
assert np.all(x <= 4)
-class TestPutmask(ParametricTestCase):
+
+class TestPutmask(TestCase):
def tst_basic(self,x,T,mask,val):
np.putmask(x,mask,val)
assert np.all(x[mask] == T(val))
assert x.dtype == T
- def testip_types(self):
+ def test_ip_types(self):
unchecked_types = [str, unicode, np.void, object]
x = np.random.random(1000)*100
mask = x < 40
- tests = []
for val in [-100,0,15]:
for types in np.sctypes.itervalues():
- tests.extend([(self.tst_basic,x.copy().astype(T),T,mask,val)
- for T in types if T not in unchecked_types])
- return tests
+ for T in types:
+ if T not in unchecked_types:
+ yield self.tst_basic,x.copy().astype(T),T,mask,val
def test_mask_size(self):
self.failUnlessRaises(ValueError, np.putmask,
@@ -690,8 +699,9 @@ class TestPutmask(ParametricTestCase):
np.putmask(x,[True,False,True],-1)
assert_array_equal(x,[-1,2,-1])
- def testip_byteorder(self):
- return [(self.tst_byteorder,dtype) for dtype in ('>i4','<i4')]
+ def test_ip_byteorder(self):
+ for dtype in ('>i4','<i4'):
+ yield self.tst_byteorder,dtype
def test_record_array(self):
# Note mixed byteorder.
@@ -708,21 +718,21 @@ class TestPutmask(ParametricTestCase):
## np.putmask(z,[True,True,True],3)
pass
-class TestTake(ParametricTestCase):
+
+class TestTake(TestCase):
def tst_basic(self,x):
ind = range(x.shape[0])
assert_array_equal(x.take(ind, axis=0), x)
- def testip_types(self):
+ def test_ip_types(self):
unchecked_types = [str, unicode, np.void, object]
x = np.random.random(24)*100
x.shape = 2,3,4
- tests = []
for types in np.sctypes.itervalues():
- tests.extend([(self.tst_basic,x.copy().astype(T))
- for T in types if T not in unchecked_types])
- return tests
+ for T in types:
+ if T not in unchecked_types:
+ yield self.tst_basic,x.copy().astype(T)
def test_raise(self):
x = np.random.random(24)*100
@@ -748,8 +758,9 @@ class TestTake(ParametricTestCase):
x = np.array([1,2,3],dtype)
assert_array_equal(x.take([0,2,1]),[1,3,2])
- def testip_byteorder(self):
- return [(self.tst_byteorder,dtype) for dtype in ('>i4','<i4')]
+ def test_ip_byteorder(self):
+ for dtype in ('>i4','<i4'):
+ yield self.tst_byteorder,dtype
def test_record_array(self):
# Note mixed byteorder.
@@ -758,7 +769,8 @@ class TestTake(ParametricTestCase):
rec1 = rec.take([1])
assert rec1['x'] == 5.0 and rec1['y'] == 4.0
-class TestLexsort(NumpyTestCase):
+
+class TestLexsort(TestCase):
def test_basic(self):
a = [1,2,1,3,1,5]
b = [0,4,5,6,2,3]
@@ -772,7 +784,8 @@ class TestLexsort(NumpyTestCase):
assert_array_equal(x[1][idx],np.sort(x[1]))
-class TestFromToFile(NumpyTestCase):
+
+class TestFromToFile(TestCase):
def setUp(self):
shape = (4,7)
rand = np.random.random
@@ -801,21 +814,21 @@ class TestFromToFile(NumpyTestCase):
y = np.fromfile(filename,dtype=self.dtype)
assert_array_equal(y,self.x.flat)
-class TestFromBuffer(ParametricTestCase):
+
+class TestFromBuffer(TestCase):
def tst_basic(self,buffer,expected,kwargs):
assert_array_equal(np.frombuffer(buffer,**kwargs),expected)
- def testip_basic(self):
- tests = []
+ def test_ip_basic(self):
for byteorder in ['<','>']:
for dtype in [float,int,np.complex]:
dt = np.dtype(dtype).newbyteorder(byteorder)
x = (np.random.random((4,7))*5).astype(dt)
buf = x.tostring()
- tests.append((self.tst_basic,buf,x.flat,{'dtype':dt}))
- return tests
+ yield self.tst_basic,buf,x.flat,{'dtype':dt}
+
-class TestResize(NumpyTestCase):
+class TestResize(TestCase):
def test_basic(self):
x = np.eye(3)
x.resize((5,5))
@@ -827,13 +840,15 @@ class TestResize(NumpyTestCase):
y = x
self.failUnlessRaises(ValueError,x.resize,(5,1))
-class TestRecord(NumpyTestCase):
+
+class TestRecord(TestCase):
def test_field_rename(self):
dt = np.dtype([('f',float),('i',int)])
dt.names = ['p','q']
assert_equal(dt.names,['p','q'])
-class TestView(NumpyTestCase):
+
+class TestView(TestCase):
def test_basic(self):
x = np.array([(1,2,3,4),(5,6,7,8)],dtype=[('r',np.int8),('g',np.int8),
('b',np.int8),('a',np.int8)])
@@ -857,7 +872,8 @@ class TestView(NumpyTestCase):
assert(isinstance(y,np.matrix))
assert_equal(y.dtype, np.dtype('<i2'))
-class TestStats(NumpyTestCase):
+
+class TestStats(TestCase):
def test_subclass(self):
class TestArray(np.ndarray):
def __new__(cls, data, info):
@@ -875,12 +891,6 @@ class TestStats(NumpyTestCase):
res = dat.var(1)
assert res.info == dat.info
-# Import tests without matching module names
-set_local_path()
-from test_unicode import *
-from test_regression import *
-from test_ufunc import *
-restore_path()
if __name__ == "__main__":
- NumpyTest('numpy.core.multiarray').run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/core/tests/test_numeric.py b/numpy/core/tests/test_numeric.py
index 0b186e147..4cae58f31 100644
--- a/numpy/core/tests/test_numeric.py
+++ b/numpy/core/tests/test_numeric.py
@@ -1,8 +1,8 @@
+import sys
from numpy.core import *
from numpy.random import rand, randint, randn
from numpy.testing import *
from numpy.core.multiarray import dot as dot_
-import sys
class Vec:
def __init__(self,sequence=None):
@@ -31,7 +31,8 @@ class Vec:
return "Vec("+repr(self.array.tolist())+")"
__str__=__repr__
-class TestDot(NumpyTestCase):
+
+class TestDot(TestCase):
def setUp(self):
self.A = rand(10,8)
self.b1 = rand(8,1)
@@ -40,87 +41,87 @@ class TestDot(NumpyTestCase):
self.b4 = rand(10)
self.N = 14
- def check_matmat(self):
+ def test_matmat(self):
A = self.A
c1 = dot(A.transpose(), A)
c2 = dot_(A.transpose(), A)
assert_almost_equal(c1, c2, decimal=self.N)
- def check_matvec(self):
+ def test_matvec(self):
A, b1 = self.A, self.b1
c1 = dot(A, b1)
c2 = dot_(A, b1)
assert_almost_equal(c1, c2, decimal=self.N)
- def check_matvec2(self):
+ def test_matvec2(self):
A, b2 = self.A, self.b2
c1 = dot(A, b2)
c2 = dot_(A, b2)
assert_almost_equal(c1, c2, decimal=self.N)
- def check_vecmat(self):
+ def test_vecmat(self):
A, b4 = self.A, self.b4
c1 = dot(b4, A)
c2 = dot_(b4, A)
assert_almost_equal(c1, c2, decimal=self.N)
- def check_vecmat2(self):
+ def test_vecmat2(self):
b3, A = self.b3, self.A
c1 = dot(b3, A.transpose())
c2 = dot_(b3, A.transpose())
assert_almost_equal(c1, c2, decimal=self.N)
- def check_vecmat3(self):
+ def test_vecmat3(self):
A, b4 = self.A, self.b4
c1 = dot(A.transpose(),b4)
c2 = dot_(A.transpose(),b4)
assert_almost_equal(c1, c2, decimal=self.N)
- def check_vecvecouter(self):
+ def test_vecvecouter(self):
b1, b3 = self.b1, self.b3
c1 = dot(b1, b3)
c2 = dot_(b1, b3)
assert_almost_equal(c1, c2, decimal=self.N)
- def check_vecvecinner(self):
+ def test_vecvecinner(self):
b1, b3 = self.b1, self.b3
c1 = dot(b3, b1)
c2 = dot_(b3, b1)
assert_almost_equal(c1, c2, decimal=self.N)
- def check_matscalar(self):
+ def test_matscalar(self):
b1 = matrix(ones((3,3),dtype=complex))
assert_equal(b1*1.0, b1)
- def check_columnvect(self):
+ def test_columnvect1(self):
b1 = ones((3,1))
b2 = [5.3]
c1 = dot(b1,b2)
c2 = dot_(b1,b2)
assert_almost_equal(c1, c2, decimal=self.N)
- def check_columnvect(self):
+ def test_columnvect2(self):
b1 = ones((3,1)).transpose()
b2 = [6.2]
c1 = dot(b2,b1)
c2 = dot_(b2,b1)
assert_almost_equal(c1, c2, decimal=self.N)
- def check_vecscalar(self):
+ def test_vecscalar(self):
b1 = rand(1,1)
b2 = rand(1,8)
c1 = dot(b1,b2)
c2 = dot_(b1,b2)
assert_almost_equal(c1, c2, decimal=self.N)
- def check_vecscalar2(self):
+ def test_vecscalar2(self):
b1 = rand(8,1)
b2 = rand(1,1)
c1 = dot(b1,b2)
c2 = dot_(b1,b2)
assert_almost_equal(c1, c2, decimal=self.N)
- def check_all(self):
+ def test_all(self):
dims = [(),(1,),(1,1)]
for dim1 in dims:
for dim2 in dims:
@@ -131,7 +132,7 @@ class TestDot(NumpyTestCase):
assert (c1.shape == c2.shape)
assert_almost_equal(c1, c2, decimal=self.N)
- def check_vecobject(self):
+ def test_vecobject(self):
U_non_cont = transpose([[1.,1.],[1.,2.]])
U_cont = ascontiguousarray(U_non_cont)
x = array([Vec([1.,0.]),Vec([0.,1.])])
@@ -141,7 +142,7 @@ class TestDot(NumpyTestCase):
assert_equal(zeros[1].array, zeros_test[1].array)
-class TestBoolScalar(NumpyTestCase):
+class TestBoolScalar(TestCase):
def test_logical(self):
f = False_
t = True_
@@ -174,7 +175,7 @@ class TestBoolScalar(NumpyTestCase):
self.failUnless((f ^ f) is f)
-class TestSeterr(NumpyTestCase):
+class TestSeterr(TestCase):
def test_set(self):
err = seterr()
old = seterr(divide='warn')
@@ -186,7 +187,8 @@ class TestSeterr(NumpyTestCase):
self.failUnless(new['divide'] == 'warn')
seterr(**old)
self.failUnless(geterr() == old)
- def test_divideerr(self):
+
+ def test_divide_err(self):
seterr(divide='raise')
try:
array([1.]) / array([0.])
@@ -198,8 +200,7 @@ class TestSeterr(NumpyTestCase):
array([1.]) / array([0.])
-class TestFromiter(NumpyTestCase):
-
+class TestFromiter(TestCase):
def makegen(self):
for x in xrange(24):
yield x**2
@@ -232,7 +233,8 @@ class TestFromiter(NumpyTestCase):
self.failUnless(alltrue(a == expected,axis=0))
self.failUnless(alltrue(a20 == expected[:20],axis=0))
-class TestIndex(NumpyTestCase):
+
+class TestIndex(TestCase):
def test_boolean(self):
a = rand(3,5,8)
V = rand(5,8)
@@ -241,7 +243,8 @@ class TestIndex(NumpyTestCase):
V[g1,g2] = -V[g1,g2]
assert (array([a[0][V>0],a[1][V>0],a[2][V>0]]) == a[:,V>0]).all()
-class TestBinaryRepr(NumpyTestCase):
+
+class TestBinaryRepr(TestCase):
def test_zero(self):
assert_equal(binary_repr(0),'0')
@@ -252,6 +255,7 @@ class TestBinaryRepr(NumpyTestCase):
assert_equal(binary_repr(-1), '-1')
assert_equal(binary_repr(-1, width=8), '11111111')
+
def assert_array_strict_equal(x, y):
assert_array_equal(x, y)
# Check flags
@@ -260,7 +264,7 @@ def assert_array_strict_equal(x, y):
assert x.dtype.isnative == y.dtype.isnative
-class TestClip(NumpyTestCase):
+class TestClip(TestCase):
def setUp(self):
self.nr = 5
self.nc = 3
@@ -509,7 +513,7 @@ class TestClip(NumpyTestCase):
ac = self.clip(a,m,M)
assert_array_strict_equal(ac, act)
- def test_type_cast_04(self):
+ def test_type_cast_05(self):
"Test native int32 with double arrays min/max."
a = self._generate_int_data(self.nr, self.nc)
m = -0.5
@@ -518,7 +522,7 @@ class TestClip(NumpyTestCase):
act = self.clip(a, m * zeros(a.shape), M)
assert_array_strict_equal(ac, act)
- def test_type_cast_05(self):
+ def test_type_cast_06(self):
"Test native with NON native scalar min/max."
a = self._generate_data(self.nr, self.nc)
m = 0.5
@@ -528,7 +532,7 @@ class TestClip(NumpyTestCase):
ac = self.fastclip(a, m_s, M)
assert_array_strict_equal(ac, act)
- def test_type_cast_06(self):
+ def test_type_cast_07(self):
"Test NON native with native array min/max."
a = self._generate_data(self.nr, self.nc)
m = -0.5 * ones(a.shape)
@@ -539,7 +543,7 @@ class TestClip(NumpyTestCase):
ac = self.fastclip(a_s, m, M)
assert_array_strict_equal(ac, act)
- def test_type_cast_07(self):
+ def test_type_cast_08(self):
"Test NON native with native scalar min/max."
a = self._generate_data(self.nr, self.nc)
m = -0.5
@@ -550,7 +554,7 @@ class TestClip(NumpyTestCase):
act = a_s.clip(m, M)
assert_array_strict_equal(ac, act)
- def test_type_cast_08(self):
+ def test_type_cast_09(self):
"Test native with NON native array min/max."
a = self._generate_data(self.nr, self.nc)
m = -0.5 * ones(a.shape)
@@ -561,7 +565,7 @@ class TestClip(NumpyTestCase):
act = self.clip(a, m_s, M)
assert_array_strict_equal(ac, act)
- def test_type_cast_09(self):
+ def test_type_cast_10(self):
"""Test native int32 with float min/max and float out for output argument."""
a = self._generate_int_data(self.nr, self.nc)
b = zeros(a.shape, dtype = float32)
@@ -571,7 +575,7 @@ class TestClip(NumpyTestCase):
ac = self.fastclip(a, m , M, out = b)
assert_array_strict_equal(ac, act)
- def test_type_cast_10(self):
+ def test_type_cast_11(self):
"Test non native with native scalar, min/max, out non native"
a = self._generate_non_native_data(self.nr, self.nc)
b = a.copy()
@@ -583,7 +587,7 @@ class TestClip(NumpyTestCase):
self.clip(a, m, M, out = bt)
assert_array_strict_equal(b, bt)
- def test_type_cast_11(self):
+ def test_type_cast_12(self):
"Test native int32 input and min/max and float out"
a = self._generate_int_data(self.nr, self.nc)
b = zeros(a.shape, dtype = float32)
@@ -681,7 +685,7 @@ class TestClip(NumpyTestCase):
self.assert_(a2 is a)
-class test_allclose_inf(ParametricTestCase):
+class test_allclose_inf(TestCase):
rtol = 1e-5
atol = 1e-8
@@ -691,7 +695,7 @@ class test_allclose_inf(ParametricTestCase):
def tst_not_allclose(self,x,y):
assert not allclose(x,y), "%s and %s shouldn't be close" % (x,y)
- def testip_allclose(self):
+ def test_ip_allclose(self):
"""Parametric test factory."""
arr = array([100,1000])
aran = arange(125).reshape((5,5,5))
@@ -709,7 +713,7 @@ class test_allclose_inf(ParametricTestCase):
for (x,y) in data:
yield (self.tst_allclose,x,y)
- def testip_not_allclose(self):
+ def test_ip_not_allclose(self):
"""Parametric test factory."""
aran = arange(125).reshape((5,5,5))
@@ -737,7 +741,8 @@ class test_allclose_inf(ParametricTestCase):
assert_array_equal(x,array([inf,1]))
assert_array_equal(y,array([0,inf]))
-class TestStdVar(NumpyTestCase):
+
+class TestStdVar(TestCase):
def setUp(self):
self.A = array([1,-1,1,-1])
self.real_var = 1
@@ -745,25 +750,27 @@ class TestStdVar(NumpyTestCase):
def test_basic(self):
assert_almost_equal(var(self.A),self.real_var)
assert_almost_equal(std(self.A)**2,self.real_var)
+
def test_ddof1(self):
- assert_almost_equal(var(self.A,ddof=1),self.real_var*len(self.A)/float(len(self.A)-1))
- assert_almost_equal(std(self.A,ddof=1)**2,self.real_var*len(self.A)/float(len(self.A)-1))
+ assert_almost_equal(var(self.A,ddof=1),
+ self.real_var*len(self.A)/float(len(self.A)-1))
+ assert_almost_equal(std(self.A,ddof=1)**2,
+ self.real_var*len(self.A)/float(len(self.A)-1))
+
def test_ddof2(self):
- assert_almost_equal(var(self.A,ddof=2),self.real_var*len(self.A)/float(len(self.A)-2))
- assert_almost_equal(std(self.A,ddof=2)**2,self.real_var*len(self.A)/float(len(self.A)-2))
+ assert_almost_equal(var(self.A,ddof=2),
+ self.real_var*len(self.A)/float(len(self.A)-2))
+ assert_almost_equal(std(self.A,ddof=2)**2,
+ self.real_var*len(self.A)/float(len(self.A)-2))
+
-class TestStdVarComplex(NumpyTestCase):
+class TestStdVarComplex(TestCase):
def test_basic(self):
A = array([1,1.j,-1,-1.j])
real_var = 1
assert_almost_equal(var(A),real_var)
assert_almost_equal(std(A)**2,real_var)
-import sys
-if sys.version_info[:2] >= (2, 5):
- set_local_path()
- from test_errstate import *
- restore_path()
-if __name__ == '__main__':
- NumpyTest().run()
+if __name__ == "__main__":
+ nose.run(argv=['', __file__])
diff --git a/numpy/core/tests/test_numerictypes.py b/numpy/core/tests/test_numerictypes.py
index bfbd91fec..0384cf88a 100644
--- a/numpy/core/tests/test_numerictypes.py
+++ b/numpy/core/tests/test_numerictypes.py
@@ -3,7 +3,6 @@ from numpy.testing import *
import numpy
from numpy import zeros, ones, array
-
# This is the structure of the table used for plain objects:
#
# +-+-+-+
@@ -102,7 +101,7 @@ def normalize_descr(descr):
class create_zeros:
"""Check the creation of heterogeneous arrays zero-valued"""
- def check_zeros0D(self):
+ def test_zeros0D(self):
"""Check creation of 0-dimensional objects"""
h = zeros((), dtype=self._descr)
self.assert_(normalize_descr(self._descr) == h.dtype.descr)
@@ -112,7 +111,7 @@ class create_zeros:
# A small check that data is ok
assert_equal(h['z'], zeros((), dtype='u1'))
- def check_zerosSD(self):
+ def test_zerosSD(self):
"""Check creation of single-dimensional objects"""
h = zeros((2,), dtype=self._descr)
self.assert_(normalize_descr(self._descr) == h.dtype.descr)
@@ -122,7 +121,7 @@ class create_zeros:
# A small check that data is ok
assert_equal(h['z'], zeros((2,), dtype='u1'))
- def check_zerosMD(self):
+ def test_zerosMD(self):
"""Check creation of multi-dimensional objects"""
h = zeros((2,3), dtype=self._descr)
self.assert_(normalize_descr(self._descr) == h.dtype.descr)
@@ -133,11 +132,11 @@ class create_zeros:
assert_equal(h['z'], zeros((2,3), dtype='u1'))
-class test_create_zeros_plain(create_zeros, NumpyTestCase):
+class test_create_zeros_plain(create_zeros, TestCase):
"""Check the creation of heterogeneous arrays zero-valued (plain)"""
_descr = Pdescr
-class test_create_zeros_nested(create_zeros, NumpyTestCase):
+class test_create_zeros_nested(create_zeros, TestCase):
"""Check the creation of heterogeneous arrays zero-valued (nested)"""
_descr = Ndescr
@@ -145,7 +144,7 @@ class test_create_zeros_nested(create_zeros, NumpyTestCase):
class create_values:
"""Check the creation of heterogeneous arrays with values"""
- def check_tuple(self):
+ def test_tuple(self):
"""Check creation from tuples"""
h = array(self._buffer, dtype=self._descr)
self.assert_(normalize_descr(self._descr) == h.dtype.descr)
@@ -154,7 +153,7 @@ class create_values:
else:
self.assert_(h.shape == ())
- def check_list_of_tuple(self):
+ def test_list_of_tuple(self):
"""Check creation from list of tuples"""
h = array([self._buffer], dtype=self._descr)
self.assert_(normalize_descr(self._descr) == h.dtype.descr)
@@ -163,7 +162,7 @@ class create_values:
else:
self.assert_(h.shape == (1,))
- def check_list_of_list_of_tuple(self):
+ def test_list_of_list_of_tuple(self):
"""Check creation from list of list of tuples"""
h = array([[self._buffer]], dtype=self._descr)
self.assert_(normalize_descr(self._descr) == h.dtype.descr)
@@ -173,25 +172,25 @@ class create_values:
self.assert_(h.shape == (1,1))
-class test_create_values_plain_single(create_values, NumpyTestCase):
+class test_create_values_plain_single(create_values, TestCase):
"""Check the creation of heterogeneous arrays (plain, single row)"""
_descr = Pdescr
multiple_rows = 0
_buffer = PbufferT[0]
-class test_create_values_plain_multiple(create_values, NumpyTestCase):
+class test_create_values_plain_multiple(create_values, TestCase):
"""Check the creation of heterogeneous arrays (plain, multiple rows)"""
_descr = Pdescr
multiple_rows = 1
_buffer = PbufferT
-class test_create_values_nested_single(create_values, NumpyTestCase):
+class test_create_values_nested_single(create_values, TestCase):
"""Check the creation of heterogeneous arrays (nested, single row)"""
_descr = Ndescr
multiple_rows = 0
_buffer = NbufferT[0]
-class test_create_values_nested_multiple(create_values, NumpyTestCase):
+class test_create_values_nested_multiple(create_values, TestCase):
"""Check the creation of heterogeneous arrays (nested, multiple rows)"""
_descr = Ndescr
multiple_rows = 1
@@ -205,7 +204,7 @@ class test_create_values_nested_multiple(create_values, NumpyTestCase):
class read_values_plain:
"""Check the reading of values in heterogeneous arrays (plain)"""
- def check_access_fields(self):
+ def test_access_fields(self):
h = array(self._buffer, dtype=self._descr)
if not self.multiple_rows:
self.assert_(h.shape == ())
@@ -222,13 +221,13 @@ class read_values_plain:
self._buffer[1][2]], dtype='u1'))
-class test_read_values_plain_single(read_values_plain, NumpyTestCase):
+class test_read_values_plain_single(read_values_plain, TestCase):
"""Check the creation of heterogeneous arrays (plain, single row)"""
_descr = Pdescr
multiple_rows = 0
_buffer = PbufferT[0]
-class test_read_values_plain_multiple(read_values_plain, NumpyTestCase):
+class test_read_values_plain_multiple(read_values_plain, TestCase):
"""Check the values of heterogeneous arrays (plain, multiple rows)"""
_descr = Pdescr
multiple_rows = 1
@@ -238,7 +237,7 @@ class read_values_nested:
"""Check the reading of values in heterogeneous arrays (nested)"""
- def check_access_top_fields(self):
+ def test_access_top_fields(self):
"""Check reading the top fields of a nested array"""
h = array(self._buffer, dtype=self._descr)
if not self.multiple_rows:
@@ -256,7 +255,7 @@ class read_values_nested:
self._buffer[1][5]], dtype='u1'))
- def check_nested1_acessors(self):
+ def test_nested1_acessors(self):
"""Check reading the nested fields of a nested array (1st level)"""
h = array(self._buffer, dtype=self._descr)
if not self.multiple_rows:
@@ -286,7 +285,7 @@ class read_values_nested:
self._buffer[1][3][1]],
dtype='c16'))
- def check_nested2_acessors(self):
+ def test_nested2_acessors(self):
"""Check reading the nested fields of a nested array (2nd level)"""
h = array(self._buffer, dtype=self._descr)
if not self.multiple_rows:
@@ -304,7 +303,7 @@ class read_values_nested:
self._buffer[1][1][2][3]],
dtype='u4'))
- def check_nested1_descriptor(self):
+ def test_nested1_descriptor(self):
"""Check access nested descriptors of a nested array (1st level)"""
h = array(self._buffer, dtype=self._descr)
self.assert_(h.dtype['Info']['value'].name == 'complex128')
@@ -312,53 +311,49 @@ class read_values_nested:
self.assert_(h.dtype['info']['Name'].name == 'unicode256')
self.assert_(h.dtype['info']['Value'].name == 'complex128')
- def check_nested2_descriptor(self):
+ def test_nested2_descriptor(self):
"""Check access nested descriptors of a nested array (2nd level)"""
h = array(self._buffer, dtype=self._descr)
self.assert_(h.dtype['Info']['Info2']['value'].name == 'void256')
self.assert_(h.dtype['Info']['Info2']['z3'].name == 'void64')
-class test_read_values_nested_single(read_values_nested, NumpyTestCase):
+class test_read_values_nested_single(read_values_nested, TestCase):
"""Check the values of heterogeneous arrays (nested, single row)"""
_descr = Ndescr
multiple_rows = False
_buffer = NbufferT[0]
-class test_read_values_nested_multiple(read_values_nested, NumpyTestCase):
+class test_read_values_nested_multiple(read_values_nested, TestCase):
"""Check the values of heterogeneous arrays (nested, multiple rows)"""
_descr = Ndescr
multiple_rows = True
_buffer = NbufferT
-class TestEmptyField(NumpyTestCase):
- def check_assign(self):
+class TestEmptyField(TestCase):
+ def test_assign(self):
a = numpy.arange(10, dtype=numpy.float32)
a.dtype = [("int", "<0i4"),("float", "<2f4")]
assert(a['int'].shape == (5,0))
assert(a['float'].shape == (5,2))
-class TestCommonType(NumpyTestCase):
- def check_scalar_loses1(self):
+class TestCommonType(TestCase):
+ def test_scalar_loses1(self):
res = numpy.find_common_type(['f4','f4','i4'],['f8'])
assert(res == 'f4')
- def check_scalar_loses2(self):
+ def test_scalar_loses2(self):
res = numpy.find_common_type(['f4','f4'],['i8'])
assert(res == 'f4')
- def check_scalar_wins(self):
+ def test_scalar_wins(self):
res = numpy.find_common_type(['f4','f4','i4'],['c8'])
assert(res == 'c8')
- def check_scalar_wins2(self):
+ def test_scalar_wins2(self):
res = numpy.find_common_type(['u4','i4','i4'],['f4'])
assert(res == 'f8')
- def check_scalar_wins3(self): # doesn't go up to 'f16' on purpose
+ def test_scalar_wins3(self): # doesn't go up to 'f16' on purpose
res = numpy.find_common_type(['u8','i8','i8'],['f8'])
assert(res == 'f8')
-
-
-
-
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/core/tests/test_records.py b/numpy/core/tests/test_records.py
index 7f8aeb70c..450aa77ef 100644
--- a/numpy/core/tests/test_records.py
+++ b/numpy/core/tests/test_records.py
@@ -1,29 +1,33 @@
-
+from os import path
from numpy.testing import *
set_package_path()
-from os import path
-import numpy.core;reload(numpy.core)
+import numpy.core
+reload(numpy.core)
+import numpy
from numpy.core import *
restore_path()
-class TestFromrecords(NumpyTestCase):
- def check_fromrecords(self):
- r = rec.fromrecords([[456,'dbe',1.2],[2,'de',1.3]],names='col1,col2,col3')
+class TestFromrecords(TestCase):
+ def test_fromrecords(self):
+ r = rec.fromrecords([[456,'dbe',1.2],[2,'de',1.3]],
+ names='col1,col2,col3')
assert_equal(r[0].item(),(456, 'dbe', 1.2))
- def check_method_array(self):
+ def test_method_array(self):
r = rec.array('abcdefg'*100,formats='i2,a3,i4',shape=3,byteorder='big')
assert_equal(r[1].item(),(25444, 'efg', 1633837924))
- def check_method_array2(self):
- r=rec.array([(1,11,'a'),(2,22,'b'),(3,33,'c'),(4,44,'d'),(5,55,'ex'),(6,66,'f'),(7,77,'g')],formats='u1,f4,a1')
+ def test_method_array2(self):
+ r=rec.array([(1,11,'a'),(2,22,'b'),(3,33,'c'),(4,44,'d'),(5,55,'ex'),
+ (6,66,'f'),(7,77,'g')],formats='u1,f4,a1')
assert_equal(r[1].item(),(2, 22.0, 'b'))
- def check_recarray_slices(self):
- r=rec.array([(1,11,'a'),(2,22,'b'),(3,33,'c'),(4,44,'d'),(5,55,'ex'),(6,66,'f'),(7,77,'g')],formats='u1,f4,a1')
+ def test_recarray_slices(self):
+ r=rec.array([(1,11,'a'),(2,22,'b'),(3,33,'c'),(4,44,'d'),(5,55,'ex'),
+ (6,66,'f'),(7,77,'g')],formats='u1,f4,a1')
assert_equal(r[1::2][1].item(),(4, 44.0, 'd'))
- def check_recarray_fromarrays(self):
+ def test_recarray_fromarrays(self):
x1 = array([1,2,3,4])
x2 = array(['a','dd','xyz','12'])
x3 = array([1.1,2,3,4])
@@ -32,14 +36,14 @@ class TestFromrecords(NumpyTestCase):
x1[1] = 34
assert_equal(r.a,array([1,2,3,4]))
- def check_recarray_fromfile(self):
+ def test_recarray_fromfile(self):
data_dir = path.join(path.dirname(__file__),'data')
filename = path.join(data_dir,'recarray_from_file.fits')
fd = open(filename)
fd.seek(2880*2)
r = rec.fromfile(fd, formats='f8,i4,a5', shape=3, byteorder='big')
- def check_recarray_from_obj(self):
+ def test_recarray_from_obj(self):
count = 10
a = zeros(count, dtype='O')
b = zeros(count, dtype='f8')
@@ -54,7 +58,7 @@ class TestFromrecords(NumpyTestCase):
assert(mine.data1[i]==0.0)
assert(mine.data2[i]==0.0)
- def check_recarray_from_names(self):
+ def test_recarray_from_names(self):
ra = rec.array([
(1, 'abc', 3.7000002861022949, 0),
(2, 'xy', 6.6999998092651367, 1),
@@ -70,7 +74,7 @@ class TestFromrecords(NumpyTestCase):
for k in xrange(len(ra)):
assert ra[k].item() == pa[k].item()
- def check_recarray_conflict_fields(self):
+ def test_recarray_conflict_fields(self):
ra = rec.array([(1,'abc',2.3),(2,'xyz',4.2),
(3,'wrs',1.3)],
names='field, shape, mean')
@@ -85,7 +89,7 @@ class TestFromrecords(NumpyTestCase):
assert_array_equal(ra['field'], [[5,5,5]])
assert callable(ra.field)
-class TestRecord(NumpyTestCase):
+class TestRecord(TestCase):
def setUp(self):
self.data = rec.fromrecords([(1,2,3),(4,5,6)],
dtype=[("col1", "<i4"),
@@ -110,5 +114,6 @@ class TestRecord(NumpyTestCase):
x[0].col5 = 1
self.failUnlessRaises(AttributeError,assign_invalid_column,a)
+
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/core/tests/test_regression.py b/numpy/core/tests/test_regression.py
index 3bbd56757..353d76d04 100644
--- a/numpy/core/tests/test_regression.py
+++ b/numpy/core/tests/test_regression.py
@@ -1,10 +1,8 @@
-from numpy.testing import *
-
from StringIO import StringIO
import pickle
import sys
from os import path
-
+from numpy.testing import *
set_local_path()
import numpy as np
restore_path()
@@ -24,17 +22,17 @@ def assert_valid_refcount(op):
assert(sys.getrefcount(i) >= rc)
-class TestRegression(NumpyTestCase):
- def check_invalid_round(self,level=rlevel):
+class TestRegression(TestCase):
+ def test_invalid_round(self,level=rlevel):
"""Ticket #3"""
v = 4.7599999999999998
assert_array_equal(np.array([v]),np.array(v))
- def check_mem_empty(self,level=rlevel):
+ def test_mem_empty(self,level=rlevel):
"""Ticket #7"""
np.empty((1,),dtype=[('x',np.int64)])
- def check_pickle_transposed(self,level=rlevel):
+ def test_pickle_transposed(self,level=rlevel):
"""Ticket #16"""
a = np.transpose(np.array([[2,9],[7,0],[3,8]]))
f = StringIO()
@@ -44,43 +42,43 @@ class TestRegression(NumpyTestCase):
f.close()
assert_array_equal(a,b)
- def check_masked_array_create(self,level=rlevel):
+ def test_masked_array_create(self,level=rlevel):
"""Ticket #17"""
x = np.ma.masked_array([0,1,2,3,0,4,5,6],mask=[0,0,0,1,1,1,0,0])
assert_array_equal(np.ma.nonzero(x),[[1,2,6,7]])
- def check_poly1d(self,level=rlevel):
+ def test_poly1d(self,level=rlevel):
"""Ticket #28"""
assert_equal(np.poly1d([1]) - np.poly1d([1,0]),
np.poly1d([-1,1]))
- def check_typeNA(self,level=rlevel):
+ def test_typeNA(self,level=rlevel):
"""Ticket #31"""
assert_equal(np.typeNA[np.int64],'Int64')
assert_equal(np.typeNA[np.uint64],'UInt64')
- def check_dtype_names(self,level=rlevel):
+ def test_dtype_names(self,level=rlevel):
"""Ticket #35"""
dt = np.dtype([(('name','label'),np.int32,3)])
- def check_reduce(self,level=rlevel):
+ def test_reduce(self,level=rlevel):
"""Ticket #40"""
assert_almost_equal(np.add.reduce([1.,.5],dtype=None), 1.5)
- def check_zeros_order(self,level=rlevel):
+ def test_zeros_order(self,level=rlevel):
"""Ticket #43"""
np.zeros([3], int, 'C')
np.zeros([3], order='C')
np.zeros([3], int, order='C')
- def check_sort_bigendian(self,level=rlevel):
+ def test_sort_bigendian(self,level=rlevel):
"""Ticket #47"""
a = np.linspace(0, 10, 11)
c = a.astype(np.dtype('<f8'))
c.sort()
assert_array_almost_equal(c, a)
- def check_negative_nd_indexing(self,level=rlevel):
+ def test_negative_nd_indexing(self,level=rlevel):
"""Ticket #49"""
c = np.arange(125).reshape((5,5,5))
origidx = np.array([-1, 0, 1])
@@ -88,7 +86,7 @@ class TestRegression(NumpyTestCase):
c[idx]
assert_array_equal(idx, origidx)
- def check_char_dump(self,level=rlevel):
+ def test_char_dump(self,level=rlevel):
"""Ticket #50"""
import tempfile
f = StringIO()
@@ -98,7 +96,7 @@ class TestRegression(NumpyTestCase):
ca = np.load(f)
f.close()
- def check_noncontiguous_fill(self,level=rlevel):
+ def test_noncontiguous_fill(self,level=rlevel):
"""Ticket #58."""
a = np.zeros((5,3))
b = a[:,:2,]
@@ -106,15 +104,15 @@ class TestRegression(NumpyTestCase):
b.shape = (10,)
self.failUnlessRaises(AttributeError,rs)
- def check_bool(self,level=rlevel):
+ def test_bool(self,level=rlevel):
"""Ticket #60"""
x = np.bool_(1)
- def check_masked_array(self,level=rlevel):
+ def test_masked_array(self,level=rlevel):
"""Ticket #61"""
x = np.ma.array(1,mask=[1])
- def check_mem_masked_where(self,level=rlevel):
+ def test_mem_masked_where(self,level=rlevel):
"""Ticket #62"""
from numpy.ma import masked_where, MaskType
a = np.zeros((1,1))
@@ -122,31 +120,31 @@ class TestRegression(NumpyTestCase):
c = masked_where(b,a)
a-c
- def check_indexing1(self,level=rlevel):
+ def test_indexing1(self,level=rlevel):
"""Ticket #64"""
descr = [('x', [('y', [('z', 'c16', (2,)),]),]),]
buffer = ((([6j,4j],),),)
h = np.array(buffer, dtype=descr)
h['x']['y']['z']
- def check_indexing2(self,level=rlevel):
+ def test_indexing2(self,level=rlevel):
"""Ticket #65"""
descr = [('x', 'i4', (2,))]
buffer = ([3,2],)
h = np.array(buffer, dtype=descr)
h['x']
- def check_round(self,level=rlevel):
+ def test_round(self,level=rlevel):
"""Ticket #67"""
x = np.array([1+2j])
assert_almost_equal(x**(-1), [1/(1+2j)])
- def check_kron_matrix(self,level=rlevel):
+ def test_kron_matrix(self,level=rlevel):
"""Ticket #71"""
x = np.matrix('[1 0; 1 0]')
assert_equal(type(np.kron(x,x)),type(x))
- def check_scalar_compare(self,level=rlevel):
+ def test_scalar_compare(self,level=rlevel):
"""Ticket #72"""
a = np.array(['test', 'auto'])
assert_array_equal(a == 'auto', np.array([False,True]))
@@ -156,25 +154,25 @@ class TestRegression(NumpyTestCase):
self.assert_(b != 'auto')
self.assert_(b[0] != 'auto')
- def check_unicode_swapping(self,level=rlevel):
+ def test_unicode_swapping(self,level=rlevel):
"""Ticket #79"""
ulen = 1
ucs_value = u'\U0010FFFF'
ua = np.array([[[ucs_value*ulen]*2]*3]*4, dtype='U%s' % ulen)
ua2 = ua.newbyteorder()
- def check_matrix_std_argmax(self,level=rlevel):
+ def test_matrix_std_argmax(self,level=rlevel):
"""Ticket #83"""
x = np.asmatrix(np.random.uniform(0,1,(3,3)))
self.assertEqual(x.std().shape, ())
self.assertEqual(x.argmax().shape, ())
- def check_object_array_fill(self,level=rlevel):
+ def test_object_array_fill(self,level=rlevel):
"""Ticket #86"""
x = np.zeros(1, 'O')
x.fill([])
- def check_cov_parameters(self,level=rlevel):
+ def test_cov_parameters(self,level=rlevel):
"""Ticket #91"""
x = np.random.random((3,3))
y = x.copy()
@@ -182,18 +180,18 @@ class TestRegression(NumpyTestCase):
np.cov(y,rowvar=0)
assert_array_equal(x,y)
- def check_mem_dtype_align(self,level=rlevel):
+ def test_mem_dtype_align(self,level=rlevel):
"""Ticket #93"""
self.failUnlessRaises(TypeError,np.dtype,
{'names':['a'],'formats':['foo']},align=1)
- def check_mem_digitize(self,level=rlevel):
+ def test_mem_digitize(self,level=rlevel):
"""Ticket #95"""
for i in range(100):
np.digitize([1,2,3,4],[1,3])
np.digitize([0,1,2,3,4],[1,3])
- def check_intp(self,level=rlevel):
+ def test_intp(self,level=rlevel):
"""Ticket #99"""
i_width = np.int_(0).nbytes*2 - 1
long('0x' + 'f'*i_width,16)
@@ -202,7 +200,7 @@ class TestRegression(NumpyTestCase):
assert_equal(255,np.long('0xFF',16))
assert_equal(1024,np.long(1024))
- def check_endian_bool_indexing(self,level=rlevel):
+ def test_endian_bool_indexing(self,level=rlevel):
"""Ticket #105"""
a = np.arange(10.,dtype='>f8')
b = np.arange(10.,dtype='<f8')
@@ -215,13 +213,13 @@ class TestRegression(NumpyTestCase):
assert(np.all(a[ya] > 0.5))
assert(np.all(b[yb] > 0.5))
- def check_mem_dot(self,level=rlevel):
+ def test_mem_dot(self,level=rlevel):
"""Ticket #106"""
x = np.random.randn(0,1)
y = np.random.randn(10,1)
z = np.dot(x, np.transpose(y))
- def check_arange_endian(self,level=rlevel):
+ def test_arange_endian(self,level=rlevel):
"""Ticket #111"""
ref = np.arange(10)
x = np.arange(10,dtype='<f8')
@@ -231,19 +229,19 @@ class TestRegression(NumpyTestCase):
# Longfloat support is not consistent enough across
# platforms for this test to be meaningful.
-# def check_longfloat_repr(self,level=rlevel):
+# def test_longfloat_repr(self,level=rlevel):
# """Ticket #112"""
# if np.longfloat(0).itemsize > 8:
# a = np.exp(np.array([1000],dtype=np.longfloat))
# assert(str(a)[1:9] == str(a[0])[:8])
- def check_argmax(self,level=rlevel):
+ def test_argmax(self,level=rlevel):
"""Ticket #119"""
a = np.random.normal(0,1,(4,5,6,7,8))
for i in xrange(a.ndim):
aargmax = a.argmax(i)
- def check_matrix_properties(self,level=rlevel):
+ def test_matrix_properties(self,level=rlevel):
"""Ticket #125"""
a = np.matrix([1.0],dtype=float)
assert(type(a.real) is np.matrix)
@@ -252,34 +250,34 @@ class TestRegression(NumpyTestCase):
assert(type(c) is np.matrix)
assert(type(d) is np.matrix)
- def check_mem_divmod(self,level=rlevel):
+ def test_mem_divmod(self,level=rlevel):
"""Ticket #126"""
for i in range(10):
divmod(np.array([i])[0],10)
- def check_hstack_invalid_dims(self,level=rlevel):
+ def test_hstack_invalid_dims(self,level=rlevel):
"""Ticket #128"""
x = np.arange(9).reshape((3,3))
y = np.array([0,0,0])
self.failUnlessRaises(ValueError,np.hstack,(x,y))
- def check_squeeze_type(self,level=rlevel):
+ def test_squeeze_type(self,level=rlevel):
"""Ticket #133"""
a = np.array([3])
b = np.array(3)
assert(type(a.squeeze()) is np.ndarray)
assert(type(b.squeeze()) is np.ndarray)
- def check_add_identity(self,level=rlevel):
+ def test_add_identity(self,level=rlevel):
"""Ticket #143"""
assert_equal(0,np.add.identity)
- def check_binary_repr_0(self,level=rlevel):
+ def test_binary_repr_0(self,level=rlevel):
"""Ticket #151"""
assert_equal('0',np.binary_repr(0))
- def check_rec_iterate(self,level=rlevel):
+ def test_rec_iterate(self,level=rlevel):
"""Ticket #160"""
descr = np.dtype([('i',int),('f',float),('s','|S3')])
x = np.rec.array([(1,1.1,'1.0'),
@@ -287,19 +285,19 @@ class TestRegression(NumpyTestCase):
x[0].tolist()
[i for i in x[0]]
- def check_unicode_string_comparison(self,level=rlevel):
+ def test_unicode_string_comparison(self,level=rlevel):
"""Ticket #190"""
a = np.array('hello',np.unicode_)
b = np.array('world')
a == b
- def check_tostring_FORTRANORDER_discontiguous(self,level=rlevel):
+ def test_tostring_FORTRANORDER_discontiguous(self,level=rlevel):
"""Fix in r2836"""
# Create discontiguous Fortran-ordered array
x = np.array(np.random.rand(3,3),order='F')[:,:2]
assert_array_almost_equal(x.ravel(),np.fromstring(x.tostring()))
- def check_flat_assignment(self,level=rlevel):
+ def test_flat_assignment(self,level=rlevel):
"""Correct behaviour of ticket #194"""
x = np.empty((3,1))
x.flat = np.arange(3)
@@ -307,7 +305,7 @@ class TestRegression(NumpyTestCase):
x.flat = np.arange(3,dtype=float)
assert_array_almost_equal(x,[[0],[1],[2]])
- def check_broadcast_flat_assignment(self,level=rlevel):
+ def test_broadcast_flat_assignment(self,level=rlevel):
"""Ticket #194"""
x = np.empty((3,1))
def bfa(): x[:] = np.arange(3)
@@ -315,7 +313,7 @@ class TestRegression(NumpyTestCase):
self.failUnlessRaises(ValueError, bfa)
self.failUnlessRaises(ValueError, bfb)
- def check_unpickle_dtype_with_object(self,level=rlevel):
+ def test_unpickle_dtype_with_object(self,level=rlevel):
"""Implemented in r2840"""
dt = np.dtype([('x',int),('y',np.object_),('z','O')])
f = StringIO()
@@ -325,7 +323,7 @@ class TestRegression(NumpyTestCase):
f.close()
assert_equal(dt,dt_)
- def check_mem_array_creation_invalid_specification(self,level=rlevel):
+ def test_mem_array_creation_invalid_specification(self,level=rlevel):
"""Ticket #196"""
dt = np.dtype([('x',int),('y',np.object_)])
# Wrong way
@@ -333,7 +331,7 @@ class TestRegression(NumpyTestCase):
# Correct way
np.array([(1,'object')],dt)
- def check_recarray_single_element(self,level=rlevel):
+ def test_recarray_single_element(self,level=rlevel):
"""Ticket #202"""
a = np.array([1,2,3],dtype=np.int32)
b = a.copy()
@@ -341,24 +339,24 @@ class TestRegression(NumpyTestCase):
assert_array_equal(a,b)
assert_equal(a,r[0][0])
- def check_zero_sized_array_indexing(self,level=rlevel):
+ def test_zero_sized_array_indexing(self,level=rlevel):
"""Ticket #205"""
tmp = np.array([])
def index_tmp(): tmp[np.array(10)]
self.failUnlessRaises(IndexError, index_tmp)
- def check_unique_zero_sized(self,level=rlevel):
+ def test_unique_zero_sized(self,level=rlevel):
"""Ticket #205"""
assert_array_equal([], np.unique(np.array([])))
- def check_chararray_rstrip(self,level=rlevel):
+ def test_chararray_rstrip(self,level=rlevel):
"""Ticket #222"""
x = np.chararray((1,),5)
x[0] = 'a '
x = x.rstrip()
assert_equal(x[0], 'a')
- def check_object_array_shape(self,level=rlevel):
+ def test_object_array_shape(self,level=rlevel):
"""Ticket #239"""
assert_equal(np.array([[1,2],3,4],dtype=object).shape, (3,))
assert_equal(np.array([[1,2],[3,4]],dtype=object).shape, (2,2))
@@ -367,29 +365,29 @@ class TestRegression(NumpyTestCase):
assert_equal(np.array([[],[],[]],dtype=object).shape, (3,0))
assert_equal(np.array([[3,4],[5,6],None],dtype=object).shape, (3,))
- def check_mem_around(self,level=rlevel):
+ def test_mem_around(self,level=rlevel):
"""Ticket #243"""
x = np.zeros((1,))
y = [0]
decimal = 6
np.around(abs(x-y),decimal) <= 10.0**(-decimal)
- def check_character_array_strip(self,level=rlevel):
+ def test_character_array_strip(self,level=rlevel):
"""Ticket #246"""
x = np.char.array(("x","x ","x "))
for c in x: assert_equal(c,"x")
- def check_lexsort(self,level=rlevel):
+ def test_lexsort(self,level=rlevel):
"""Lexsort memory error"""
v = np.array([1,2,3,4,5,6,7,8,9,10])
assert_equal(np.lexsort(v),0)
- def check_pickle_dtype(self,level=rlevel):
+ def test_pickle_dtype(self,level=rlevel):
"""Ticket #251"""
import pickle
pickle.dumps(np.float)
- def check_masked_array_multiply(self,level=rlevel):
+ def test_masked_array_multiply(self,level=rlevel):
"""Ticket #254"""
a = np.ma.zeros((4,1))
a[2,0] = np.ma.masked
@@ -397,41 +395,41 @@ class TestRegression(NumpyTestCase):
a*b
b*a
- def check_swap_real(self, level=rlevel):
+ def test_swap_real(self, level=rlevel):
"""Ticket #265"""
assert_equal(np.arange(4,dtype='>c8').imag.max(),0.0)
assert_equal(np.arange(4,dtype='<c8').imag.max(),0.0)
assert_equal(np.arange(4,dtype='>c8').real.max(),3.0)
assert_equal(np.arange(4,dtype='<c8').real.max(),3.0)
- def check_object_array_from_list(self, level=rlevel):
+ def test_object_array_from_list(self, level=rlevel):
"""Ticket #270"""
a = np.array([1,'A',None])
- def check_masked_array_repeat(self, level=rlevel):
+ def test_masked_array_repeat(self, level=rlevel):
"""Ticket #271"""
np.ma.array([1],mask=False).repeat(10)
- def check_multiple_assign(self, level=rlevel):
+ def test_multiple_assign(self, level=rlevel):
"""Ticket #273"""
a = np.zeros((3,1),int)
a[[1,2]] = 1
- def check_empty_array_type(self, level=rlevel):
+ def test_empty_array_type(self, level=rlevel):
assert_equal(np.array([]).dtype, np.zeros(0).dtype)
- def check_void_coercion(self, level=rlevel):
+ def test_void_coercion(self, level=rlevel):
dt = np.dtype([('a','f4'),('b','i4')])
x = np.zeros((1,),dt)
assert(np.r_[x,x].dtype == dt)
- def check_void_copyswap(self, level=rlevel):
+ def test_void_copyswap(self, level=rlevel):
dt = np.dtype([('one', '<i4'),('two', '<i4')])
x = np.array((1,2), dtype=dt)
x = x.byteswap()
assert(x['one'] > 1 and x['two'] > 2)
- def check_method_args(self, level=rlevel):
+ def test_method_args(self, level=rlevel):
# Make sure methods and functions have same default axis
# keyword and arguments
funcs1= ['argmax', 'argmin', 'sum', ('product', 'prod'),
@@ -470,17 +468,17 @@ class TestRegression(NumpyTestCase):
res2 = getattr(np, func)(arr1, arr2)
assert abs(res1-res2).max() < 1e-8, func
- def check_mem_lexsort_strings(self, level=rlevel):
+ def test_mem_lexsort_strings(self, level=rlevel):
"""Ticket #298"""
lst = ['abc','cde','fgh']
np.lexsort((lst,))
- def check_fancy_index(self, level=rlevel):
+ def test_fancy_index(self, level=rlevel):
"""Ticket #302"""
x = np.array([1,2])[np.array([0])]
assert_equal(x.shape,(1,))
- def check_recarray_copy(self, level=rlevel):
+ def test_recarray_copy(self, level=rlevel):
"""Ticket #312"""
dt = [('x',np.int16),('y',np.float64)]
ra = np.array([(1,2.3)], dtype=dt)
@@ -488,68 +486,68 @@ class TestRegression(NumpyTestCase):
rb['x'] = 2.
assert ra['x'] != rb['x']
- def check_rec_fromarray(self, level=rlevel):
+ def test_rec_fromarray(self, level=rlevel):
"""Ticket #322"""
x1 = np.array([[1,2],[3,4],[5,6]])
x2 = np.array(['a','dd','xyz'])
x3 = np.array([1.1,2,3])
np.rec.fromarrays([x1,x2,x3], formats="(2,)i4,a3,f8")
- def check_object_array_assign(self, level=rlevel):
+ def test_object_array_assign(self, level=rlevel):
x = np.empty((2,2),object)
x.flat[2] = (1,2,3)
assert_equal(x.flat[2],(1,2,3))
- def check_ndmin_float64(self, level=rlevel):
+ def test_ndmin_float64(self, level=rlevel):
"""Ticket #324"""
x = np.array([1,2,3],dtype=np.float64)
assert_equal(np.array(x,dtype=np.float32,ndmin=2).ndim,2)
assert_equal(np.array(x,dtype=np.float64,ndmin=2).ndim,2)
- def check_mem_vectorise(self, level=rlevel):
+ def test_mem_vectorise(self, level=rlevel):
"""Ticket #325"""
vt = np.vectorize(lambda *args: args)
vt(np.zeros((1,2,1)), np.zeros((2,1,1)), np.zeros((1,1,2)))
vt(np.zeros((1,2,1)), np.zeros((2,1,1)), np.zeros((1,1,2)), np.zeros((2,2)))
- def check_mem_axis_minimization(self, level=rlevel):
+ def test_mem_axis_minimization(self, level=rlevel):
"""Ticket #327"""
data = np.arange(5)
data = np.add.outer(data,data)
- def check_mem_float_imag(self, level=rlevel):
+ def test_mem_float_imag(self, level=rlevel):
"""Ticket #330"""
np.float64(1.0).imag
- def check_dtype_tuple(self, level=rlevel):
+ def test_dtype_tuple(self, level=rlevel):
"""Ticket #334"""
assert np.dtype('i4') == np.dtype(('i4',()))
- def check_dtype_posttuple(self, level=rlevel):
+ def test_dtype_posttuple(self, level=rlevel):
"""Ticket #335"""
np.dtype([('col1', '()i4')])
- def check_mgrid_single_element(self, level=rlevel):
+ def test_mgrid_single_element(self, level=rlevel):
"""Ticket #339"""
assert_array_equal(np.mgrid[0:0:1j],[0])
assert_array_equal(np.mgrid[0:0],[])
- def check_numeric_carray_compare(self, level=rlevel):
+ def test_numeric_carray_compare(self, level=rlevel):
"""Ticket #341"""
assert_equal(np.array([ 'X' ], 'c'),'X')
- def check_string_array_size(self, level=rlevel):
+ def test_string_array_size(self, level=rlevel):
"""Ticket #342"""
self.failUnlessRaises(ValueError,
np.array,[['X'],['X','X','X']],'|S1')
- def check_dtype_repr(self, level=rlevel):
+ def test_dtype_repr(self, level=rlevel):
"""Ticket #344"""
dt1=np.dtype(('uint32', 2))
dt2=np.dtype(('uint32', (2,)))
assert_equal(dt1.__repr__(), dt2.__repr__())
- def check_reshape_order(self, level=rlevel):
+ def test_reshape_order(self, level=rlevel):
"""Make sure reshape order works."""
a = np.arange(6).reshape(2,3,order='F')
assert_equal(a,[[0,2,4],[1,3,5]])
@@ -557,22 +555,22 @@ class TestRegression(NumpyTestCase):
b = a[:,1]
assert_equal(b.reshape(2,2,order='F'), [[2,6],[4,8]])
- def check_repeat_discont(self, level=rlevel):
+ def test_repeat_discont(self, level=rlevel):
"""Ticket #352"""
a = np.arange(12).reshape(4,3)[:,2]
assert_equal(a.repeat(3), [2,2,2,5,5,5,8,8,8,11,11,11])
- def check_array_index(self, level=rlevel):
+ def test_array_index(self, level=rlevel):
"""Make sure optimization is not called in this case."""
a = np.array([1,2,3])
a2 = np.array([[1,2,3]])
assert_equal(a[np.where(a==3)], a2[np.where(a2==3)])
- def check_object_argmax(self, level=rlevel):
+ def test_object_argmax(self, level=rlevel):
a = np.array([1,2,3],dtype=object)
assert a.argmax() == 2
- def check_recarray_fields(self, level=rlevel):
+ def test_recarray_fields(self, level=rlevel):
"""Ticket #372"""
dt0 = np.dtype([('f0','i4'),('f1','i4')])
dt1 = np.dtype([('f0','i8'),('f1','i8')])
@@ -583,33 +581,33 @@ class TestRegression(NumpyTestCase):
np.rec.fromarrays([(1,2),(3,4)])]:
assert(a.dtype in [dt0,dt1])
- def check_random_shuffle(self, level=rlevel):
+ def test_random_shuffle(self, level=rlevel):
"""Ticket #374"""
a = np.arange(5).reshape((5,1))
b = a.copy()
np.random.shuffle(b)
assert_equal(np.sort(b, axis=0),a)
- def check_refcount_vectorize(self, level=rlevel):
+ def test_refcount_vectorize(self, level=rlevel):
"""Ticket #378"""
def p(x,y): return 123
v = np.vectorize(p)
assert_valid_refcount(v)
- def check_poly1d_nan_roots(self, level=rlevel):
+ def test_poly1d_nan_roots(self, level=rlevel):
"""Ticket #396"""
p = np.poly1d([np.nan,np.nan,1], r=0)
self.failUnlessRaises(np.linalg.LinAlgError,getattr,p,"r")
- def check_refcount_vdot(self, level=rlevel):
+ def test_refcount_vdot(self, level=rlevel):
"""Changeset #3443"""
assert_valid_refcount(np.vdot)
- def check_startswith(self, level=rlevel):
+ def test_startswith(self, level=rlevel):
ca = np.char.array(['Hi','There'])
assert_equal(ca.startswith('H'),[True,False])
- def check_noncommutative_reduce_accumulate(self, level=rlevel):
+ def test_noncommutative_reduce_accumulate(self, level=rlevel):
"""Ticket #413"""
tosubtract = np.arange(5)
todivide = np.array([2.0, 0.5, 0.25])
@@ -620,44 +618,44 @@ class TestRegression(NumpyTestCase):
assert_array_equal(np.divide.accumulate(todivide),
np.array([2., 4., 16.]))
- def check_mem_polymul(self, level=rlevel):
+ def test_mem_polymul(self, level=rlevel):
"""Ticket #448"""
np.polymul([],[1.])
- def check_convolve_empty(self, level=rlevel):
+ def test_convolve_empty(self, level=rlevel):
"""Convolve should raise an error for empty input array."""
self.failUnlessRaises(AssertionError,np.convolve,[],[1])
self.failUnlessRaises(AssertionError,np.convolve,[1],[])
- def check_multidim_byteswap(self, level=rlevel):
+ def test_multidim_byteswap(self, level=rlevel):
"""Ticket #449"""
r=np.array([(1,(0,1,2))], dtype="i2,3i2")
assert_array_equal(r.byteswap(),
np.array([(256,(0,256,512))],r.dtype))
- def check_string_NULL(self, level=rlevel):
+ def test_string_NULL(self, level=rlevel):
"""Changeset 3557"""
assert_equal(np.array("a\x00\x0b\x0c\x00").item(),
'a\x00\x0b\x0c')
- def check_mem_string_concat(self, level=rlevel):
+ def test_mem_string_concat(self, level=rlevel):
"""Ticket #469"""
x = np.array([])
np.append(x,'asdasd\tasdasd')
- def check_matrix_multiply_by_1d_vector(self, level=rlevel) :
+ def test_matrix_multiply_by_1d_vector(self, level=rlevel) :
"""Ticket #473"""
def mul() :
np.mat(np.eye(2))*np.ones(2)
self.failUnlessRaises(ValueError,mul)
- def check_junk_in_string_fields_of_recarray(self, level=rlevel):
+ def test_junk_in_string_fields_of_recarray(self, level=rlevel):
"""Ticket #483"""
r = np.array([['abc']], dtype=[('var1', '|S20')])
assert str(r['var1'][0][0]) == 'abc'
- def check_take_output(self, level=rlevel):
+ def test_take_output(self, level=rlevel):
"""Ensure that 'take' honours output parameter."""
x = np.arange(12).reshape((3,4))
a = np.take(x,[0,2],axis=1)
@@ -665,7 +663,7 @@ class TestRegression(NumpyTestCase):
np.take(x,[0,2],axis=1,out=b)
assert_array_equal(a,b)
- def check_array_str_64bit(self, level=rlevel):
+ def test_array_str_64bit(self, level=rlevel):
"""Ticket #501"""
s = np.array([1, np.nan],dtype=np.float64)
errstate = np.seterr(all='raise')
@@ -674,7 +672,7 @@ class TestRegression(NumpyTestCase):
finally:
np.seterr(**errstate)
- def check_frompyfunc_endian(self, level=rlevel):
+ def test_frompyfunc_endian(self, level=rlevel):
"""Ticket #503"""
from math import radians
uradians = np.frompyfunc(radians, 1, 1)
@@ -683,66 +681,66 @@ class TestRegression(NumpyTestCase):
assert_almost_equal(uradians(big_endian).astype(float),
uradians(little_endian).astype(float))
- def check_mem_string_arr(self, level=rlevel):
+ def test_mem_string_arr(self, level=rlevel):
"""Ticket #514"""
s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
t = []
np.hstack((t, s ))
- def check_arr_transpose(self, level=rlevel):
+ def test_arr_transpose(self, level=rlevel):
"""Ticket #516"""
x = np.random.rand(*(2,)*16)
y = x.transpose(range(16))
- def check_string_mergesort(self, level=rlevel):
+ def test_string_mergesort(self, level=rlevel):
"""Ticket #540"""
x = np.array(['a']*32)
assert_array_equal(x.argsort(kind='m'), np.arange(32))
- def check_argmax_byteorder(self, level=rlevel):
+ def test_argmax_byteorder(self, level=rlevel):
"""Ticket #546"""
a = np.arange(3, dtype='>f')
assert a[a.argmax()] == a.max()
- def check_numeric_random(self, level=rlevel):
+ def test_numeric_random(self, level=rlevel):
"""Ticket #552"""
from numpy.oldnumeric.random_array import randint
randint(0,50,[2,3])
- def check_poly_div(self, level=rlevel):
+ def test_poly_div(self, level=rlevel):
"""Ticket #553"""
u = np.poly1d([1,2,3])
v = np.poly1d([1,2,3,4,5])
q,r = np.polydiv(u,v)
assert_equal(q*v + r, u)
- def check_poly_eq(self, level=rlevel):
+ def test_poly_eq(self, level=rlevel):
"""Ticket #554"""
x = np.poly1d([1,2,3])
y = np.poly1d([3,4])
assert x != y
assert x == x
- def check_rand_seed(self, level=rlevel):
+ def test_rand_seed(self, level=rlevel):
"""Ticket #555"""
for l in np.arange(4):
np.random.seed(l)
- def check_mem_deallocation_leak(self, level=rlevel):
+ def test_mem_deallocation_leak(self, level=rlevel):
"""Ticket #562"""
a = np.zeros(5,dtype=float)
b = np.array(a,dtype=float)
del a, b
- def check_mem_insert(self, level=rlevel):
+ def test_mem_insert(self, level=rlevel):
"""Ticket #572"""
np.lib.place(1,1,1)
- def check_mem_on_invalid_dtype(self):
+ def test_mem_on_invalid_dtype(self):
"Ticket #583"
self.failUnlessRaises(ValueError, np.fromiter, [['12',''],['13','']], str)
- def check_dot_negative_stride(self, level=rlevel):
+ def test_dot_negative_stride(self, level=rlevel):
"""Ticket #588"""
x = np.array([[1,5,25,125.,625]])
y = np.array([[20.],[160.],[640.],[1280.],[1024.]])
@@ -750,14 +748,14 @@ class TestRegression(NumpyTestCase):
y2 = y[::-1]
assert_equal(np.dot(x,z),np.dot(x,y2))
- def check_object_casting(self, level=rlevel):
+ def test_object_casting(self, level=rlevel):
def rs():
x = np.ones([484,286])
y = np.zeros([484,286])
x |= y
self.failUnlessRaises(TypeError,rs)
- def check_unicode_scalar(self, level=rlevel):
+ def test_unicode_scalar(self, level=rlevel):
"""Ticket #600"""
import cPickle
x = np.array(["DROND", "DROND1"], dtype="U6")
@@ -765,7 +763,7 @@ class TestRegression(NumpyTestCase):
new = cPickle.loads(cPickle.dumps(el))
assert_equal(new, el)
- def check_arange_non_native_dtype(self, level=rlevel):
+ def test_arange_non_native_dtype(self, level=rlevel):
"""Ticket #616"""
for T in ('>f4','<f4'):
dt = np.dtype(T)
@@ -773,75 +771,75 @@ class TestRegression(NumpyTestCase):
assert_equal(np.arange(0.5,dtype=dt).dtype,dt)
assert_equal(np.arange(5,dtype=dt).dtype,dt)
- def check_bool_indexing_invalid_nr_elements(self, level=rlevel):
+ def test_bool_indexing_invalid_nr_elements(self, level=rlevel):
s = np.ones(10,dtype=float)
x = np.array((15,),dtype=float)
def ia(x,s): x[(s>0)]=1.0
self.failUnlessRaises(ValueError,ia,x,s)
- def check_mem_scalar_indexing(self, level=rlevel):
+ def test_mem_scalar_indexing(self, level=rlevel):
"""Ticket #603"""
x = np.array([0],dtype=float)
index = np.array(0,dtype=np.int32)
x[index]
- def check_binary_repr_0_width(self, level=rlevel):
+ def test_binary_repr_0_width(self, level=rlevel):
assert_equal(np.binary_repr(0,width=3),'000')
- def check_fromstring(self, level=rlevel):
+ def test_fromstring(self, level=rlevel):
assert_equal(np.fromstring("12:09:09", dtype=int, sep=":"),
[12,9,9])
- def check_searchsorted_variable_length(self, level=rlevel):
+ def test_searchsorted_variable_length(self, level=rlevel):
x = np.array(['a','aa','b'])
y = np.array(['d','e'])
assert_equal(x.searchsorted(y), [3,3])
- def check_string_argsort_with_zeros(self, level=rlevel):
+ def test_string_argsort_with_zeros(self, level=rlevel):
"""Check argsort for strings containing zeros."""
x = np.fromstring("\x00\x02\x00\x01", dtype="|S2")
assert_array_equal(x.argsort(kind='m'), np.array([1,0]))
assert_array_equal(x.argsort(kind='q'), np.array([1,0]))
- def check_string_sort_with_zeros(self, level=rlevel):
+ def test_string_sort_with_zeros(self, level=rlevel):
"""Check sort for strings containing zeros."""
x = np.fromstring("\x00\x02\x00\x01", dtype="|S2")
y = np.fromstring("\x00\x01\x00\x02", dtype="|S2")
assert_array_equal(np.sort(x, kind="q"), y)
- def check_hist_bins_as_list(self, level=rlevel):
+ def test_hist_bins_as_list(self, level=rlevel):
"""Ticket #632"""
hist,edges = np.histogram([1,2,3,4],[1,2])
assert_array_equal(hist,[1,3])
assert_array_equal(edges,[1,2])
- def check_copy_detection_zero_dim(self, level=rlevel):
+ def test_copy_detection_zero_dim(self, level=rlevel):
"""Ticket #658"""
np.indices((0,3,4)).T.reshape(-1,3)
- def check_flat_byteorder(self, level=rlevel):
+ def test_flat_byteorder(self, level=rlevel):
"""Ticket #657"""
x = np.arange(10)
assert_array_equal(x.astype('>i4'),x.astype('<i4').flat[:])
assert_array_equal(x.astype('>i4').flat[:],x.astype('<i4'))
- def check_uint64_from_negative(self, level=rlevel) :
+ def test_uint64_from_negative(self, level=rlevel) :
assert_equal(np.uint64(-2), np.uint64(18446744073709551614))
- def check_sign_bit(self, level=rlevel):
+ def test_sign_bit(self, level=rlevel):
x = np.array([0,-0.0,0])
assert_equal(str(np.abs(x)),'[ 0. 0. 0.]')
- def check_flat_index_byteswap(self, level=rlevel):
+ def test_flat_index_byteswap(self, level=rlevel):
for dt in (np.dtype('<i4'),np.dtype('>i4')):
x = np.array([-1,0,1],dtype=dt)
assert_equal(x.flat[0].dtype, x[0].dtype)
- def check_copy_detection_corner_case(self, level=rlevel):
+ def test_copy_detection_corner_case(self, level=rlevel):
"""Ticket #658"""
np.indices((0,3,4)).T.reshape(-1,3)
- def check_object_array_refcounting(self, level=rlevel):
+ def test_object_array_refcounting(self, level=rlevel):
"""Ticket #633"""
if not hasattr(sys, 'getrefcount'):
return
@@ -942,7 +940,7 @@ class TestRegression(NumpyTestCase):
assert cnt(a) == cnt0_a + 5 + 2
assert cnt(b) == cnt0_b + 5 + 3
- def check_mem_custom_float_to_array(self, level=rlevel):
+ def test_mem_custom_float_to_array(self, level=rlevel):
"""Ticket 702"""
class MyFloat:
def __float__(self):
@@ -951,7 +949,7 @@ class TestRegression(NumpyTestCase):
tmp = np.atleast_1d([MyFloat()])
tmp2 = tmp.astype(float)
- def check_object_array_refcount_self_assign(self, level=rlevel):
+ def test_object_array_refcount_self_assign(self, level=rlevel):
"""Ticket #711"""
class VictimObject(object):
deleted = False
@@ -966,23 +964,23 @@ class TestRegression(NumpyTestCase):
arr[:] = arr # trying to induce a segfault by doing it again...
assert not arr[0].deleted
- def check_mem_fromiter_invalid_dtype_string(self, level=rlevel):
+ def test_mem_fromiter_invalid_dtype_string(self, level=rlevel):
x = [1,2,3]
self.failUnlessRaises(ValueError,
np.fromiter, [xi for xi in x], dtype='S')
- def check_reduce_big_object_array(self, level=rlevel):
+ def test_reduce_big_object_array(self, level=rlevel):
"""Ticket #713"""
oldsize = np.setbufsize(10*16)
a = np.array([None]*161, object)
assert not np.any(a)
np.setbufsize(oldsize)
- def check_mem_0d_array_index(self, level=rlevel):
+ def test_mem_0d_array_index(self, level=rlevel):
"""Ticket #714"""
np.zeros(10)[np.array(0)]
- def check_floats_from_string(self, level=rlevel):
+ def test_floats_from_string(self, level=rlevel):
"""Ticket #640, floats from string"""
fsingle = np.single('1.234')
fdouble = np.double('1.234')
@@ -991,7 +989,7 @@ class TestRegression(NumpyTestCase):
assert_almost_equal(fdouble, 1.234)
assert_almost_equal(flongdouble, 1.234)
- def check_complex_dtype_printing(self, level=rlevel):
+ def test_complex_dtype_printing(self, level=rlevel):
dt = np.dtype([('top', [('tiles', ('>f4', (64, 64)), (1,)),
('rtile', '>f4', (64, 36))], (3,)),
('bottom', [('bleft', ('>f4', (8, 64)), (1,)),
@@ -1002,7 +1000,7 @@ class TestRegression(NumpyTestCase):
"('bottom', [('bleft', ('>f4', (8, 64)), (1,)), "
"('bright', '>f4', (8, 36))])]")
- def check_nonnative_endian_fill(self, level=rlevel):
+ def test_nonnative_endian_fill(self, level=rlevel):
""" Non-native endian arrays were incorrectly filled with scalars before
r5034.
"""
@@ -1014,11 +1012,11 @@ class TestRegression(NumpyTestCase):
x.fill(1)
assert_equal(x, np.array([1], dtype=dtype))
- def check_asfarray_none(self, level=rlevel):
+ def test_asfarray_none(self, level=rlevel):
"""Test for changeset r5065"""
assert_array_equal(np.array([np.nan]), np.asfarray([None]))
- def check_dot_alignment_sse2(self, level=rlevel):
+ def test_dot_alignment_sse2(self, level=rlevel):
"""Test for ticket #551, changeset r5140"""
x = np.zeros((30,40))
y = pickle.loads(pickle.dumps(x))
@@ -1027,7 +1025,7 @@ class TestRegression(NumpyTestCase):
# This shouldn't cause a segmentation fault:
np.dot(z, y)
- def check_astype_copy(self, level=rlevel):
+ def test_astype_copy(self, level=rlevel):
"""Ticket #788, changeset r5155"""
# The test data file was generated by scipy.io.savemat.
# The dtype is float64, but the isbuiltin attribute is 0.
@@ -1038,7 +1036,7 @@ class TestRegression(NumpyTestCase):
assert (xp.__array_interface__['data'][0] !=
xpd.__array_interface__['data'][0])
- def check_compress_small_type(self, level=rlevel):
+ def test_compress_small_type(self, level=rlevel):
"""Ticket #789, changeset 5217.
"""
# compress with out argument segfaulted if cannot cast safely
@@ -1053,7 +1051,7 @@ class TestRegression(NumpyTestCase):
except TypeError:
pass
- def check_attributes(self, level=rlevel):
+ def test_attributes(self, level=rlevel):
"""Ticket #791
"""
import numpy as np
@@ -1124,8 +1122,7 @@ class TestRegression(NumpyTestCase):
assert dat.var(1).info == 'jubba'
assert dat.view(TestArray).info == 'jubba'
-
- def check_recarray_tolist(self, level=rlevel):
+ def test_recarray_tolist(self, level=rlevel):
"""Ticket #793, changeset r5215
"""
a = np.recarray(2, formats="i4,f8,f8", names="id,x,y")
@@ -1133,7 +1130,7 @@ class TestRegression(NumpyTestCase):
assert( a[0].tolist() == b[0])
assert( a[1].tolist() == b[1])
- def check_large_fancy_indexing(self, level=rlevel):
+ def test_large_fancy_indexing(self, level=rlevel):
# Large enough to fail on 64-bit.
nbits = np.dtype(np.intp).itemsize * 8
thesize = int((2**nbits)**(1.0/5.0)+1)
@@ -1150,10 +1147,11 @@ class TestRegression(NumpyTestCase):
self.failUnlessRaises(ValueError, dp)
self.failUnlessRaises(ValueError, dp2)
- def check_char_array_creation(self, level=rlevel):
+ def test_char_array_creation(self, level=rlevel):
a = np.array('123', dtype='c')
b = np.array(['1','2','3'])
assert_equal(a,b)
+
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/core/tests/test_scalarmath.py b/numpy/core/tests/test_scalarmath.py
index d07460516..4a884607a 100644
--- a/numpy/core/tests/test_scalarmath.py
+++ b/numpy/core/tests/test_scalarmath.py
@@ -10,13 +10,13 @@ types = [np.bool_, np.byte, np.ubyte, np.short, np.ushort, np.intc, np.uintc,
# This compares scalarmath against ufuncs.
-class TestTypes(NumpyTestCase):
- def check_types(self, level=1):
+class TestTypes(TestCase):
+ def test_types(self, level=1):
for atype in types:
a = atype(1)
assert a == 1, "error with %r: got %r" % (atype,a)
- def check_type_add(self, level=1):
+ def test_type_add(self, level=1):
# list of types
for k, atype in enumerate(types):
vala = atype(3)
@@ -30,20 +30,21 @@ class TestTypes(NumpyTestCase):
val.dtype.char == valo.dtype.char, \
"error with (%d,%d)" % (k,l)
- def check_type_create(self, level=1):
+ def test_type_create(self, level=1):
for k, atype in enumerate(types):
a = array([1,2,3],atype)
b = atype([1,2,3])
assert_equal(a,b)
-class TestPower(NumpyTestCase):
- def check_small_types(self):
+
+class TestPower(TestCase):
+ def test_small_types(self):
for t in [np.int8, np.int16]:
a = t(3)
b = a ** 4
assert b == 81, "error with %r: got %r" % (t,b)
- def check_large_types(self):
+ def test_large_types(self):
for t in [np.int32, np.int64, np.float32, np.float64, np.longdouble]:
a = t(51)
b = a ** 4
@@ -53,7 +54,8 @@ class TestPower(NumpyTestCase):
else:
assert_almost_equal(b, 6765201, err_msg=msg)
-class TestConversion(NumpyTestCase):
+
+class TestConversion(TestCase):
def test_int_from_long(self):
l = [1e6, 1e12, 1e18, -1e6, -1e12, -1e18]
li = [10**6, 10**12, 10**18, -10**6, -10**12, -10**18]
@@ -64,6 +66,7 @@ class TestConversion(NumpyTestCase):
a = np.array(l[:3], dtype=np.uint64)
assert_equal(map(int,a), li[:3])
+
#class TestRepr(NumpyTestCase):
# def check_repr(self):
# for t in types:
@@ -72,8 +75,9 @@ class TestConversion(NumpyTestCase):
# val2 = eval(val_repr)
# assert_equal( val, val2 )
-class TestRepr(NumpyTestCase):
- def check_float_repr(self):
+
+class TestRepr(TestCase):
+ def test_float_repr(self):
from numpy import nan, inf
for t in [np.float32, np.float64, np.longdouble]:
if t is np.longdouble: # skip it for now.
@@ -82,7 +86,8 @@ class TestRepr(NumpyTestCase):
last_fraction_bit_idx = finfo.nexp + finfo.nmant
last_exponent_bit_idx = finfo.nexp
storage_bytes = np.dtype(t).itemsize*8
- for which in ['small denorm','small norm']: # could add some more types here
+ # could add some more types to the list below
+ for which in ['small denorm','small norm']:
# Values from http://en.wikipedia.org/wiki/IEEE_754
constr = array([0x00]*storage_bytes,dtype=np.uint8)
if which == 'small denorm':
@@ -106,5 +111,6 @@ class TestRepr(NumpyTestCase):
if not (val2 == 0 and val < 1e-100):
assert_equal(val, val2)
+
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/core/tests/test_ufunc.py b/numpy/core/tests/test_ufunc.py
index b99c938d8..a958d67e0 100644
--- a/numpy/core/tests/test_ufunc.py
+++ b/numpy/core/tests/test_ufunc.py
@@ -1,14 +1,14 @@
import numpy as np
from numpy.testing import *
-class TestUfunc(NumpyTestCase):
+class TestUfunc(TestCase):
def test_reduceat_shifting_sum(self) :
L = 6
x = np.arange(L)
idx = np.array(zip(np.arange(L-2), np.arange(L-2)+2)).ravel()
assert_array_equal(np.add.reduceat(x,idx)[::2],
[1,3,5,7])
- def check_generic_loops(self) :
+ def test_generic_loops(self) :
"""Test generic loops.
The loops to be tested are:
@@ -147,7 +147,7 @@ class TestUfunc(NumpyTestCase):
# check PyUFunc_On_Om
# fixme -- I don't know how to do this yet
- def check_all_ufunc(self) :
+ def test_all_ufunc(self) :
"""Try to check presence and results of all ufuncs.
The list of ufuncs comes from generate_umath.py and is as follows:
@@ -232,5 +232,6 @@ class TestUfunc(NumpyTestCase):
"""
pass
+
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/core/tests/test_umath.py b/numpy/core/tests/test_umath.py
index 0d0e8840e..a57692f5f 100644
--- a/numpy/core/tests/test_umath.py
+++ b/numpy/core/tests/test_umath.py
@@ -6,16 +6,16 @@ from numpy import zeros, ndarray, array, choose, pi
import numpy as np
restore_path()
-class TestDivision(NumpyTestCase):
- def check_division_int(self):
+class TestDivision(TestCase):
+ def test_division_int(self):
# int division should return the floor of the result, a la Python
x = array([5, 10, 90, 100, -5, -10, -90, -100, -120])
assert_equal(x / 100, [0, 0, 0, 1, -1, -1, -1, -1, -2])
assert_equal(x // 100, [0, 0, 0, 1, -1, -1, -1, -1, -2])
assert_equal(x % 100, [5, 10, 90, 0, 95, 90, 10, 0, 80])
-class TestPower(NumpyTestCase):
- def check_power_float(self):
+class TestPower(TestCase):
+ def test_power_float(self):
x = array([1., 2., 3.])
assert_equal(x**0, [1., 1., 1.])
assert_equal(x**1, x)
@@ -26,7 +26,7 @@ class TestPower(NumpyTestCase):
assert_almost_equal(x**(-1), [1., 0.5, 1./3])
assert_almost_equal(x**(0.5), [1., ncu.sqrt(2), ncu.sqrt(3)])
- def check_power_complex(self):
+ def test_power_complex(self):
x = array([1+2j, 2+3j, 3+4j])
assert_equal(x**0, [1., 1., 1.])
assert_equal(x**1, x)
@@ -39,41 +39,42 @@ class TestPower(NumpyTestCase):
assert_almost_equal(x**14, [-76443+16124j, 23161315+58317492j,
5583548873 + 2465133864j])
-class TestLog1p(NumpyTestCase):
- def check_log1p(self):
+
+class TestLog1p(TestCase):
+ def test_log1p(self):
assert_almost_equal(ncu.log1p(0.2), ncu.log(1.2))
assert_almost_equal(ncu.log1p(1e-6), ncu.log(1+1e-6))
-class TestExpm1(NumpyTestCase):
- def check_expm1(self):
+class TestExpm1(TestCase):
+ def test_expm1(self):
assert_almost_equal(ncu.expm1(0.2), ncu.exp(0.2)-1)
assert_almost_equal(ncu.expm1(1e-6), ncu.exp(1e-6)-1)
-class TestMaximum(NumpyTestCase):
- def check_reduce_complex(self):
+class TestMaximum(TestCase):
+ def test_reduce_complex(self):
assert_equal(maximum.reduce([1,2j]),1)
assert_equal(maximum.reduce([1+3j,2j]),1+3j)
-class TestMinimum(NumpyTestCase):
- def check_reduce_complex(self):
+class TestMinimum(TestCase):
+ def test_reduce_complex(self):
assert_equal(minimum.reduce([1,2j]),2j)
-class TestFloatingPoint(NumpyTestCase):
- def check_floating_point(self):
+class TestFloatingPoint(TestCase):
+ def test_floating_point(self):
assert_equal(ncu.FLOATING_POINT_SUPPORT, 1)
-def TestDegrees(NumpyTestCase):
- def check_degrees(self):
+class TestDegrees(TestCase):
+ def test_degrees(self):
assert_almost_equal(ncu.degrees(pi), 180.0)
assert_almost_equal(ncu.degrees(-0.5*pi), -90.0)
-def TestRadians(NumpyTestCase):
- def check_radians(self):
+class TestRadians(TestCase):
+ def test_radians(self):
assert_almost_equal(ncu.radians(180.0), pi)
- assert_almost_equal(ncu.degrees(-90.0), -0.5*pi)
+ assert_almost_equal(ncu.radians(-90.0), -0.5*pi)
-class TestSpecialMethods(NumpyTestCase):
- def check_wrap(self):
+class TestSpecialMethods(TestCase):
+ def test_wrap(self):
class with_wrap(object):
def __array__(self):
return zeros(1)
@@ -92,7 +93,7 @@ class TestSpecialMethods(NumpyTestCase):
assert_equal(args[1], a)
self.failUnlessEqual(i, 0)
- def check_old_wrap(self):
+ def test_old_wrap(self):
class with_wrap(object):
def __array__(self):
return zeros(1)
@@ -104,7 +105,7 @@ class TestSpecialMethods(NumpyTestCase):
x = minimum(a, a)
assert_equal(x.arr, zeros(1))
- def check_priority(self):
+ def test_priority(self):
class A(object):
def __array__(self):
return zeros(1)
@@ -142,7 +143,7 @@ class TestSpecialMethods(NumpyTestCase):
self.failUnless(type(exp(b) is B))
self.failUnless(type(exp(c) is C))
- def check_failing_wrap(self):
+ def test_failing_wrap(self):
class A(object):
def __array__(self):
return zeros(1)
@@ -151,7 +152,7 @@ class TestSpecialMethods(NumpyTestCase):
a = A()
self.failUnlessRaises(RuntimeError, maximum, a, a)
- def check_array_with_context(self):
+ def test_array_with_context(self):
class A(object):
def __array__(self, dtype=None, context=None):
func, args, i = context
@@ -174,19 +175,20 @@ class TestSpecialMethods(NumpyTestCase):
assert_equal(maximum(a, B()), 0)
assert_equal(maximum(a, C()), 0)
-class TestChoose(NumpyTestCase):
- def check_mixed(self):
+
+class TestChoose(TestCase):
+ def test_mixed(self):
c = array([True,True])
a = array([True,True])
assert_equal(choose(c, (a, 1)), array([1,1]))
-class TestComplexFunctions(NumpyTestCase):
+class TestComplexFunctions(TestCase):
funcs = [np.arcsin , np.arccos , np.arctan, np.arcsinh, np.arccosh,
np.arctanh, np.sin , np.cos , np.tan , np.exp,
np.log , np.sqrt , np.log10]
- def check_it(self):
+ def test_it(self):
for f in self.funcs:
if f is np.arccosh :
x = 1.5
@@ -197,7 +199,7 @@ class TestComplexFunctions(NumpyTestCase):
assert_almost_equal(fz.real, fr, err_msg='real part %s'%f)
assert_almost_equal(fz.imag, 0., err_msg='imag part %s'%f)
- def check_precisions_consistent(self) :
+ def test_precisions_consistent(self) :
z = 1 + 1j
for f in self.funcs :
fcf = f(np.csingle(z))
@@ -207,8 +209,8 @@ class TestComplexFunctions(NumpyTestCase):
assert_almost_equal(fcl, fcd, decimal=15, err_msg='fch-fcl %s'%f)
-class TestChoose(NumpyTestCase):
- def check_attributes(self):
+class TestAttributes(TestCase):
+ def test_attributes(self):
add = ncu.add
assert_equal(add.__name__, 'add')
assert add.__doc__.startswith('y = add(x1,x2)\n\n')
@@ -218,5 +220,6 @@ class TestChoose(NumpyTestCase):
assert_equal(add.nout, 1)
assert_equal(add.identity, 0)
+
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/core/tests/test_unicode.py b/numpy/core/tests/test_unicode.py
index 7d7c06f30..40ddd584e 100644
--- a/numpy/core/tests/test_unicode.py
+++ b/numpy/core/tests/test_unicode.py
@@ -18,10 +18,10 @@ ucs4_value = u'\U0010FFFF'
# Creation tests
############################################################
-class create_zeros(NumpyTestCase):
+class create_zeros:
"""Check the creation of zero-valued arrays"""
- def content_test(self, ua, ua_scalar, nbytes):
+ def content_check(self, ua, ua_scalar, nbytes):
# Check the length of the unicode base type
self.assert_(int(ua.dtype.str[2:]) == self.ulen)
@@ -37,41 +37,43 @@ class create_zeros(NumpyTestCase):
else:
self.assert_(len(buffer(ua_scalar)) == 0)
- def check_zeros0D(self):
+ def test_zeros0D(self):
"""Check creation of 0-dimensional objects"""
ua = zeros((), dtype='U%s' % self.ulen)
- self.content_test(ua, ua[()], 4*self.ulen)
+ self.content_check(ua, ua[()], 4*self.ulen)
- def check_zerosSD(self):
+ def test_zerosSD(self):
"""Check creation of single-dimensional objects"""
ua = zeros((2,), dtype='U%s' % self.ulen)
- self.content_test(ua, ua[0], 4*self.ulen*2)
- self.content_test(ua, ua[1], 4*self.ulen*2)
+ self.content_check(ua, ua[0], 4*self.ulen*2)
+ self.content_check(ua, ua[1], 4*self.ulen*2)
- def check_zerosMD(self):
+ def test_zerosMD(self):
"""Check creation of multi-dimensional objects"""
ua = zeros((2,3,4), dtype='U%s' % self.ulen)
- self.content_test(ua, ua[0,0,0], 4*self.ulen*2*3*4)
- self.content_test(ua, ua[-1,-1,-1], 4*self.ulen*2*3*4)
+ self.content_check(ua, ua[0,0,0], 4*self.ulen*2*3*4)
+ self.content_check(ua, ua[-1,-1,-1], 4*self.ulen*2*3*4)
-class test_create_zeros_1(create_zeros):
+class test_create_zeros_1(create_zeros, TestCase):
"""Check the creation of zero-valued arrays (size 1)"""
ulen = 1
-class test_create_zeros_2(create_zeros):
+
+class test_create_zeros_2(create_zeros, TestCase):
"""Check the creation of zero-valued arrays (size 2)"""
ulen = 2
-class test_create_zeros_1009(create_zeros):
+
+class test_create_zeros_1009(create_zeros, TestCase):
"""Check the creation of zero-valued arrays (size 1009)"""
ulen = 1009
-class create_values(NumpyTestCase):
+class create_values:
"""Check the creation of unicode arrays with values"""
- def content_test(self, ua, ua_scalar, nbytes):
+ def content_check(self, ua, ua_scalar, nbytes):
# Check the length of the unicode base type
self.assert_(int(ua.dtype.str[2:]) == self.ulen)
@@ -95,50 +97,55 @@ class create_values(NumpyTestCase):
# regular 2-byte word
self.assert_(len(buffer(ua_scalar)) == 2*self.ulen)
- def check_values0D(self):
+ def test_values0D(self):
"""Check creation of 0-dimensional objects with values"""
ua = array(self.ucs_value*self.ulen, dtype='U%s' % self.ulen)
- self.content_test(ua, ua[()], 4*self.ulen)
+ self.content_check(ua, ua[()], 4*self.ulen)
- def check_valuesSD(self):
+ def test_valuesSD(self):
"""Check creation of single-dimensional objects with values"""
ua = array([self.ucs_value*self.ulen]*2, dtype='U%s' % self.ulen)
- self.content_test(ua, ua[0], 4*self.ulen*2)
- self.content_test(ua, ua[1], 4*self.ulen*2)
+ self.content_check(ua, ua[0], 4*self.ulen*2)
+ self.content_check(ua, ua[1], 4*self.ulen*2)
- def check_valuesMD(self):
+ def test_valuesMD(self):
"""Check creation of multi-dimensional objects with values"""
ua = array([[[self.ucs_value*self.ulen]*2]*3]*4, dtype='U%s' % self.ulen)
- self.content_test(ua, ua[0,0,0], 4*self.ulen*2*3*4)
- self.content_test(ua, ua[-1,-1,-1], 4*self.ulen*2*3*4)
+ self.content_check(ua, ua[0,0,0], 4*self.ulen*2*3*4)
+ self.content_check(ua, ua[-1,-1,-1], 4*self.ulen*2*3*4)
-class test_create_values_1_ucs2(create_values):
+class test_create_values_1_ucs2(create_values, TestCase):
"""Check the creation of valued arrays (size 1, UCS2 values)"""
ulen = 1
ucs_value = ucs2_value
-class test_create_values_1_ucs4(create_values):
+
+class test_create_values_1_ucs4(create_values, TestCase):
"""Check the creation of valued arrays (size 1, UCS4 values)"""
ulen = 1
ucs_value = ucs4_value
-class test_create_values_2_ucs2(create_values):
+
+class test_create_values_2_ucs2(create_values, TestCase):
"""Check the creation of valued arrays (size 2, UCS2 values)"""
ulen = 2
ucs_value = ucs2_value
-class test_create_values_2_ucs4(create_values):
+
+class test_create_values_2_ucs4(create_values, TestCase):
"""Check the creation of valued arrays (size 2, UCS4 values)"""
ulen = 2
ucs_value = ucs4_value
-class test_create_values_1009_ucs2(create_values):
+
+class test_create_values_1009_ucs2(create_values, TestCase):
"""Check the creation of valued arrays (size 1009, UCS2 values)"""
ulen = 1009
ucs_value = ucs2_value
-class test_create_values_1009_ucs4(create_values):
+
+class test_create_values_1009_ucs4(create_values, TestCase):
"""Check the creation of valued arrays (size 1009, UCS4 values)"""
ulen = 1009
ucs_value = ucs4_value
@@ -148,10 +155,10 @@ class test_create_values_1009_ucs4(create_values):
# Assignment tests
############################################################
-class assign_values(NumpyTestCase):
+class assign_values:
"""Check the assignment of unicode arrays with values"""
- def content_test(self, ua, ua_scalar, nbytes):
+ def content_check(self, ua, ua_scalar, nbytes):
# Check the length of the unicode base type
self.assert_(int(ua.dtype.str[2:]) == self.ulen)
@@ -175,68 +182,74 @@ class assign_values(NumpyTestCase):
# regular 2-byte word
self.assert_(len(buffer(ua_scalar)) == 2*self.ulen)
- def check_values0D(self):
+ def test_values0D(self):
"""Check assignment of 0-dimensional objects with values"""
ua = zeros((), dtype='U%s' % self.ulen)
ua[()] = self.ucs_value*self.ulen
- self.content_test(ua, ua[()], 4*self.ulen)
+ self.content_check(ua, ua[()], 4*self.ulen)
- def check_valuesSD(self):
+ def test_valuesSD(self):
"""Check assignment of single-dimensional objects with values"""
ua = zeros((2,), dtype='U%s' % self.ulen)
ua[0] = self.ucs_value*self.ulen
- self.content_test(ua, ua[0], 4*self.ulen*2)
+ self.content_check(ua, ua[0], 4*self.ulen*2)
ua[1] = self.ucs_value*self.ulen
- self.content_test(ua, ua[1], 4*self.ulen*2)
+ self.content_check(ua, ua[1], 4*self.ulen*2)
- def check_valuesMD(self):
+ def test_valuesMD(self):
"""Check assignment of multi-dimensional objects with values"""
ua = zeros((2,3,4), dtype='U%s' % self.ulen)
ua[0,0,0] = self.ucs_value*self.ulen
- self.content_test(ua, ua[0,0,0], 4*self.ulen*2*3*4)
+ self.content_check(ua, ua[0,0,0], 4*self.ulen*2*3*4)
ua[-1,-1,-1] = self.ucs_value*self.ulen
- self.content_test(ua, ua[-1,-1,-1], 4*self.ulen*2*3*4)
+ self.content_check(ua, ua[-1,-1,-1], 4*self.ulen*2*3*4)
-class test_assign_values_1_ucs2(assign_values):
+class test_assign_values_1_ucs2(assign_values, TestCase):
"""Check the assignment of valued arrays (size 1, UCS2 values)"""
ulen = 1
ucs_value = ucs2_value
-class test_assign_values_1_ucs4(assign_values):
+
+class test_assign_values_1_ucs4(assign_values, TestCase):
"""Check the assignment of valued arrays (size 1, UCS4 values)"""
ulen = 1
ucs_value = ucs4_value
+
-class test_assign_values_2_ucs2(assign_values):
+class test_assign_values_2_ucs2(assign_values, TestCase):
"""Check the assignment of valued arrays (size 2, UCS2 values)"""
ulen = 2
ucs_value = ucs2_value
+
-class test_assign_values_2_ucs4(assign_values):
+class test_assign_values_2_ucs4(assign_values, TestCase):
"""Check the assignment of valued arrays (size 2, UCS4 values)"""
ulen = 2
ucs_value = ucs4_value
+
-class test_assign_values_1009_ucs2(assign_values):
+class test_assign_values_1009_ucs2(assign_values, TestCase):
"""Check the assignment of valued arrays (size 1009, UCS2 values)"""
ulen = 1009
ucs_value = ucs2_value
+
-class test_assign_values_1009_ucs4(assign_values):
+class test_assign_values_1009_ucs4(assign_values, TestCase):
"""Check the assignment of valued arrays (size 1009, UCS4 values)"""
ulen = 1009
ucs_value = ucs4_value
+
############################################################
# Byteorder tests
############################################################
-class byteorder_values(NumpyTestCase):
+class byteorder_values:
"""Check the byteorder of unicode arrays in round-trip conversions"""
- def check_values0D(self):
+ def test_values0D(self):
"""Check byteorder of 0-dimensional objects"""
ua = array(self.ucs_value*self.ulen, dtype='U%s' % self.ulen)
ua2 = ua.newbyteorder()
@@ -248,7 +261,7 @@ class byteorder_values(NumpyTestCase):
# Arrays must be equal after the round-trip
assert_equal(ua, ua3)
- def check_valuesSD(self):
+ def test_valuesSD(self):
"""Check byteorder of single-dimensional objects"""
ua = array([self.ucs_value*self.ulen]*2, dtype='U%s' % self.ulen)
ua2 = ua.newbyteorder()
@@ -258,7 +271,7 @@ class byteorder_values(NumpyTestCase):
# Arrays must be equal after the round-trip
assert_equal(ua, ua3)
- def check_valuesMD(self):
+ def test_valuesMD(self):
"""Check byteorder of multi-dimensional objects"""
ua = array([[[self.ucs_value*self.ulen]*2]*3]*4,
dtype='U%s' % self.ulen)
@@ -269,36 +282,43 @@ class byteorder_values(NumpyTestCase):
# Arrays must be equal after the round-trip
assert_equal(ua, ua3)
-class test_byteorder_1_ucs2(byteorder_values):
+
+class test_byteorder_1_ucs2(byteorder_values, TestCase):
"""Check the byteorder in unicode (size 1, UCS2 values)"""
ulen = 1
ucs_value = ucs2_value
+
-class test_byteorder_1_ucs4(byteorder_values):
+class test_byteorder_1_ucs4(byteorder_values, TestCase):
"""Check the byteorder in unicode (size 1, UCS4 values)"""
ulen = 1
ucs_value = ucs4_value
+
-class test_byteorder_2_ucs2(byteorder_values):
+class test_byteorder_2_ucs2(byteorder_values, TestCase):
"""Check the byteorder in unicode (size 2, UCS2 values)"""
ulen = 2
ucs_value = ucs2_value
+
-class test_byteorder_2_ucs4(byteorder_values):
+class test_byteorder_2_ucs4(byteorder_values, TestCase):
"""Check the byteorder in unicode (size 2, UCS4 values)"""
ulen = 2
ucs_value = ucs4_value
+
-class test_byteorder_1009_ucs2(byteorder_values):
+class test_byteorder_1009_ucs2(byteorder_values, TestCase):
"""Check the byteorder in unicode (size 1009, UCS2 values)"""
ulen = 1009
ucs_value = ucs2_value
+
-class test_byteorder_1009_ucs4(byteorder_values):
+class test_byteorder_1009_ucs4(byteorder_values, TestCase):
"""Check the byteorder in unicode (size 1009, UCS4 values)"""
ulen = 1009
ucs_value = ucs4_value
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
+
diff --git a/numpy/distutils/__init__.py b/numpy/distutils/__init__.py
index 72f10ba25..893ab4411 100644
--- a/numpy/distutils/__init__.py
+++ b/numpy/distutils/__init__.py
@@ -15,6 +15,6 @@ except ImportError:
_INSTALLED = False
if _INSTALLED:
- def test(level=1, verbosity=1):
- from numpy.testing import NumpyTest
- return NumpyTest().test(level, verbosity)
+ from numpy.testing.pkgtester import Tester
+ test = Tester().test
+ bench = Tester().bench
diff --git a/numpy/distutils/tests/f2py_ext/tests/test_fib2.py b/numpy/distutils/tests/f2py_ext/tests/test_fib2.py
index 9a52ab17a..295397aad 100644
--- a/numpy/distutils/tests/f2py_ext/tests/test_fib2.py
+++ b/numpy/distutils/tests/f2py_ext/tests/test_fib2.py
@@ -4,10 +4,10 @@ set_package_path()
from f2py_ext import fib2
del sys.path[0]
-class TestFib2(NumpyTestCase):
+class TestFib2(TestCase):
- def check_fib(self):
+ def test_fib(self):
assert_array_equal(fib2.fib(6),[0,1,1,2,3,5])
if __name__ == "__main__":
- NumpyTest(fib2).run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/distutils/tests/f2py_f90_ext/tests/test_foo.py b/numpy/distutils/tests/f2py_f90_ext/tests/test_foo.py
index 3d48f6ca9..40402e949 100644
--- a/numpy/distutils/tests/f2py_f90_ext/tests/test_foo.py
+++ b/numpy/distutils/tests/f2py_f90_ext/tests/test_foo.py
@@ -4,10 +4,10 @@ set_package_path()
from f2py_f90_ext import foo
del sys.path[0]
-class TestFoo(NumpyTestCase):
+class TestFoo(TestCase):
- def check_foo_free(self):
+ def test_foo_free(self):
assert_equal(foo.foo_free.bar13(),13)
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/distutils/tests/gen_ext/tests/test_fib3.py b/numpy/distutils/tests/gen_ext/tests/test_fib3.py
index b962a12aa..0c1e2d60d 100644
--- a/numpy/distutils/tests/gen_ext/tests/test_fib3.py
+++ b/numpy/distutils/tests/gen_ext/tests/test_fib3.py
@@ -4,10 +4,10 @@ set_package_path()
from gen_ext import fib3
del sys.path[0]
-class TestFib3(NumpyTestCase):
+class TestFib3(TestCase):
- def check_fib(self):
+ def test_fib(self):
assert_array_equal(fib3.fib(6),[0,1,1,2,3,5])
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/distutils/tests/pyrex_ext/tests/test_primes.py b/numpy/distutils/tests/pyrex_ext/tests/test_primes.py
index 1ca5ed8e7..c08da8651 100644
--- a/numpy/distutils/tests/pyrex_ext/tests/test_primes.py
+++ b/numpy/distutils/tests/pyrex_ext/tests/test_primes.py
@@ -5,9 +5,9 @@ set_package_path()
from pyrex_ext.primes import primes
restore_path()
-class TestPrimes(NumpyTestCase):
- def check_simple(self, level=1):
+class TestPrimes(TestCase):
+ def test_simple(self, level=1):
l = primes(10)
assert_equal(l, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29])
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/distutils/tests/swig_ext/tests/test_example.py b/numpy/distutils/tests/swig_ext/tests/test_example.py
index f24162077..6a3895295 100644
--- a/numpy/distutils/tests/swig_ext/tests/test_example.py
+++ b/numpy/distutils/tests/swig_ext/tests/test_example.py
@@ -4,15 +4,15 @@ set_package_path()
from swig_ext import example
restore_path()
-class TestExample(NumpyTestCase):
+class TestExample(TestCase):
- def check_fact(self):
+ def test_fact(self):
assert_equal(example.fact(10),3628800)
- def check_cvar(self):
+ def test_cvar(self):
assert_equal(example.cvar.My_variable,3.0)
example.cvar.My_variable = 5
assert_equal(example.cvar.My_variable,5.0)
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/distutils/tests/swig_ext/tests/test_example2.py b/numpy/distutils/tests/swig_ext/tests/test_example2.py
index 3150e1a16..3cb1db201 100644
--- a/numpy/distutils/tests/swig_ext/tests/test_example2.py
+++ b/numpy/distutils/tests/swig_ext/tests/test_example2.py
@@ -4,9 +4,9 @@ set_package_path()
from swig_ext import example2
restore_path()
-class TestExample2(NumpyTestCase):
+class TestExample2(TestCase):
- def check_zoo(self):
+ def test_zoo(self):
z = example2.Zoo()
z.shut_up('Tiger')
z.shut_up('Lion')
@@ -14,4 +14,4 @@ class TestExample2(NumpyTestCase):
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/distutils/tests/test_fcompiler_gnu.py b/numpy/distutils/tests/test_fcompiler_gnu.py
index 002d360b9..99384bc8f 100644
--- a/numpy/distutils/tests/test_fcompiler_gnu.py
+++ b/numpy/distutils/tests/test_fcompiler_gnu.py
@@ -21,7 +21,7 @@ gfortran_version_strings = [
('GNU Fortran (GCC) 4.3.0 20070316 (experimental)', '4.3.0'),
]
-class TestG77Versions(NumpyTestCase):
+class TestG77Versions(TestCase):
def test_g77_version(self):
fc = numpy.distutils.fcompiler.new_fcompiler(compiler='gnu')
for vs, version in g77_version_strings:
@@ -34,7 +34,7 @@ class TestG77Versions(NumpyTestCase):
v = fc.version_match(vs)
assert v is None, (vs, v)
-class TestGortranVersions(NumpyTestCase):
+class TestGortranVersions(TestCase):
def test_gfortran_version(self):
fc = numpy.distutils.fcompiler.new_fcompiler(compiler='gnu95')
for vs, version in gfortran_version_strings:
@@ -49,4 +49,4 @@ class TestGortranVersions(NumpyTestCase):
if __name__ == '__main__':
- NumpyTest.run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/distutils/tests/test_misc_util.py b/numpy/distutils/tests/test_misc_util.py
index 4d2404092..fed1567b7 100644
--- a/numpy/distutils/tests/test_misc_util.py
+++ b/numpy/distutils/tests/test_misc_util.py
@@ -8,15 +8,15 @@ from os.path import join, sep
ajoin = lambda *paths: join(*((sep,)+paths))
-class TestAppendpath(NumpyTestCase):
+class TestAppendpath(TestCase):
- def check_1(self):
+ def test_1(self):
assert_equal(appendpath('prefix','name'),join('prefix','name'))
assert_equal(appendpath('/prefix','name'),ajoin('prefix','name'))
assert_equal(appendpath('/prefix','/name'),ajoin('prefix','name'))
assert_equal(appendpath('prefix','/name'),join('prefix','name'))
- def check_2(self):
+ def test_2(self):
assert_equal(appendpath('prefix/sub','name'),
join('prefix','sub','name'))
assert_equal(appendpath('prefix/sub','sup/name'),
@@ -24,7 +24,7 @@ class TestAppendpath(NumpyTestCase):
assert_equal(appendpath('/prefix/sub','/prefix/name'),
ajoin('prefix','sub','name'))
- def check_3(self):
+ def test_3(self):
assert_equal(appendpath('/prefix/sub','/prefix/sup/name'),
ajoin('prefix','sub','sup','name'))
assert_equal(appendpath('/prefix/sub/sub2','/prefix/sup/sup2/name'),
@@ -32,9 +32,9 @@ class TestAppendpath(NumpyTestCase):
assert_equal(appendpath('/prefix/sub/sub2','/prefix/sub/sup/name'),
ajoin('prefix','sub','sub2','sup','name'))
-class TestMinrelpath(NumpyTestCase):
+class TestMinrelpath(TestCase):
- def check_1(self):
+ def test_1(self):
import os
n = lambda path: path.replace('/',os.path.sep)
assert_equal(minrelpath(n('aa/bb')),n('aa/bb'))
@@ -47,14 +47,15 @@ class TestMinrelpath(NumpyTestCase):
assert_equal(minrelpath(n('.././..')),n('../..'))
assert_equal(minrelpath(n('aa/bb/.././../dd')),n('dd'))
-class TestGpaths(NumpyTestCase):
+class TestGpaths(TestCase):
- def check_gpaths(self):
+ def test_gpaths(self):
local_path = minrelpath(os.path.join(os.path.dirname(__file__),'..'))
ls = gpaths('command/*.py', local_path)
assert os.path.join(local_path,'command','build_src.py') in ls,`ls`
f = gpaths('system_info.py', local_path)
assert os.path.join(local_path,'system_info.py')==f[0],`f`
+
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/doc/DISTUTILS.txt b/numpy/doc/DISTUTILS.txt
index c5b21da3d..9a7672d0e 100644
--- a/numpy/doc/DISTUTILS.txt
+++ b/numpy/doc/DISTUTILS.txt
@@ -465,12 +465,10 @@ The ``tests/`` directory
Ideally, every Python code, extension module, or subpackage in Scipy
package directory should have the corresponding ``test_<name>.py``
file in ``tests/`` directory. This file should define classes
-derived from ``NumpyTestCase`` (or from ``unittest.TestCase``) class
-and have names starting with ``test``. The methods of these classes
-which names start with ``bench``, ``check``, or ``test``, are passed
-on to unittest machinery. In addition, the value of the first optional
-argument of these methods determine the level of the corresponding
-test. Default level is 1.
+derived from the ``numpy.testing.TestCase`` class (or from
+``unittest.TestCase``) and have names starting with ``test``. The methods
+of these classes whose names contain ``test`` or start with ``bench`` are
+automatically picked up by the test machinery.
A minimal example of a ``test_yyy.py`` file that implements tests for
a Scipy package module ``numpy.xxx.yyy`` containing a function
@@ -489,20 +487,16 @@ a Scipy package module ``numpy.xxx.yyy`` containing a function
# import modules that are located in the same directory as this file.
restore_path()
- class test_zzz(NumpyTestCase):
- def check_simple(self, level=1):
+ class test_zzz(TestCase):
+ def test_simple(self, level=1):
assert zzz()=='Hello from zzz'
#...
if __name__ == "__main__":
- NumpyTest().run()
-
-``NumpyTestCase`` is derived from ``unittest.TestCase`` and it
-basically only implements an additional method ``measure(self,
-code_str, times=1)``.
+ nose.run(argv=['', __file__])
Note that all classes that are inherited from ``TestCase`` class, are
-picked up by the test runner when using ``testoob``.
+automatically picked up by the test runner.
``numpy.testing`` module provides also the following convenience
functions::
@@ -514,25 +508,15 @@ functions::
assert_array_almost_equal(x,y,decimal=6,err_msg='')
rand(*shape) # returns random array with a given shape
-``NumpyTest`` can be used for running ``tests/test_*.py`` scripts.
-For instance, to run all test scripts of the module ``xxx``, execute
-in Python:
-
- >>> NumpyTest('xxx').test(level=1,verbosity=1)
+To run all test scripts of the module ``xxx``, execute in Python:
-or equivalently,
-
- >>> import xxx
- >>> NumpyTest(xxx).test(level=1,verbosity=1)
+ >>> import numpy
+ >>> numpy.xxx.test()
To run only tests for ``xxx.yyy`` module, execute:
>>> NumpyTest('xxx.yyy').test(level=1,verbosity=1)
-To take the level and verbosity parameters for tests from
-``sys.argv``, use ``NumpyTest.run()`` method (this is supported only
-when ``optparse`` is installed).
-
Extra features in NumPy Distutils
'''''''''''''''''''''''''''''''''
diff --git a/numpy/f2py/lib/parser/test_Fortran2003.py b/numpy/f2py/lib/parser/test_Fortran2003.py
index 525061db4..b8e8fd998 100644
--- a/numpy/f2py/lib/parser/test_Fortran2003.py
+++ b/numpy/f2py/lib/parser/test_Fortran2003.py
@@ -7,9 +7,9 @@ from api import get_reader
############################### SECTION 2 ####################################
###############################################################################
-class TestProgram(NumpyTestCase): # R201
+class TestProgram(TestCase): # R201
- def check_simple(self):
+ def test_simple(self):
reader = get_reader('''\
subroutine foo
end subroutine foo
@@ -21,9 +21,9 @@ class TestProgram(NumpyTestCase): # R201
assert isinstance(a, cls),`a`
assert_equal(str(a), 'SUBROUTINE foo\nEND SUBROUTINE foo\nSUBROUTINE bar\nEND SUBROUTINE bar')
-class TestSpecificationPart(NumpyTestCase): # R204
+class TestSpecificationPart(TestCase): # R204
- def check_simple(self):
+ def test_simple(self):
from api import get_reader
reader = get_reader('''\
integer a''')
@@ -37,9 +37,9 @@ class TestSpecificationPart(NumpyTestCase): # R204
############################### SECTION 3 ####################################
###############################################################################
-class TestName(NumpyTestCase): # R304
+class TestName(TestCase): # R304
- def check_name(self):
+ def test_name(self):
a = Name('a')
assert isinstance(a,Name),`a`
a = Name('a2')
@@ -55,9 +55,9 @@ class TestName(NumpyTestCase): # R304
############################### SECTION 4 ####################################
###############################################################################
-class TestTypeParamValue(NumpyTestCase): # 402
+class TestTypeParamValue(TestCase): # 402
- def check_type_param_value(self):
+ def test_type_param_value(self):
cls = Type_Param_Value
a = cls('*')
assert isinstance(a,cls),`a`
@@ -72,9 +72,9 @@ class TestTypeParamValue(NumpyTestCase): # 402
assert isinstance(a,Level_2_Expr),`a`
assert_equal(str(a),'1 + 2')
-class TestIntrinsicTypeSpec(NumpyTestCase): # R403
+class TestIntrinsicTypeSpec(TestCase): # R403
- def check_intrinsic_type_spec(self):
+ def test_intrinsic_type_spec(self):
cls = Intrinsic_Type_Spec
a = cls('INTEGER')
assert isinstance(a,cls),`a`
@@ -109,9 +109,9 @@ class TestIntrinsicTypeSpec(NumpyTestCase): # R403
assert isinstance(a,cls),`a`
assert_equal(str(a),'DOUBLE PRECISION')
-class TestKindSelector(NumpyTestCase): # R404
+class TestKindSelector(TestCase): # R404
- def check_kind_selector(self):
+ def test_kind_selector(self):
cls = Kind_Selector
a = cls('(1)')
assert isinstance(a,cls),`a`
@@ -126,9 +126,9 @@ class TestKindSelector(NumpyTestCase): # R404
assert isinstance(a,cls),`a`
assert_equal(str(a),'*1')
-class TestSignedIntLiteralConstant(NumpyTestCase): # R405
+class TestSignedIntLiteralConstant(TestCase): # R405
- def check_int_literal_constant(self):
+ def test_int_literal_constant(self):
cls = Signed_Int_Literal_Constant
a = cls('1')
assert isinstance(a,cls),`a`
@@ -152,9 +152,9 @@ class TestSignedIntLiteralConstant(NumpyTestCase): # R405
assert isinstance(a,cls),`a`
assert_equal(str(a),'+1976354279568241_8')
-class TestIntLiteralConstant(NumpyTestCase): # R406
+class TestIntLiteralConstant(TestCase): # R406
- def check_int_literal_constant(self):
+ def test_int_literal_constant(self):
cls = Int_Literal_Constant
a = cls('1')
assert isinstance(a,cls),`a`
@@ -178,9 +178,9 @@ class TestIntLiteralConstant(NumpyTestCase): # R406
assert isinstance(a,cls),`a`
assert_equal(str(a),'1976354279568241_8')
-class TestBinaryConstant(NumpyTestCase): # R412
+class TestBinaryConstant(TestCase): # R412
- def check_boz_literal_constant(self):
+ def test_boz_literal_constant(self):
cls = Boz_Literal_Constant
bcls = Binary_Constant
a = cls('B"01"')
@@ -188,9 +188,9 @@ class TestBinaryConstant(NumpyTestCase): # R412
assert_equal(str(a),'B"01"')
assert_equal(repr(a),"%s('B\"01\"')" % (bcls.__name__))
-class TestOctalConstant(NumpyTestCase): # R413
+class TestOctalConstant(TestCase): # R413
- def check_boz_literal_constant(self):
+ def test_boz_literal_constant(self):
cls = Boz_Literal_Constant
ocls = Octal_Constant
a = cls('O"017"')
@@ -198,9 +198,9 @@ class TestOctalConstant(NumpyTestCase): # R413
assert_equal(str(a),'O"017"')
assert_equal(repr(a),"%s('O\"017\"')" % (ocls.__name__))
-class TestHexConstant(NumpyTestCase): # R414
+class TestHexConstant(TestCase): # R414
- def check_boz_literal_constant(self):
+ def test_boz_literal_constant(self):
cls = Boz_Literal_Constant
zcls = Hex_Constant
a = cls('Z"01A"')
@@ -208,9 +208,9 @@ class TestHexConstant(NumpyTestCase): # R414
assert_equal(str(a),'Z"01A"')
assert_equal(repr(a),"%s('Z\"01A\"')" % (zcls.__name__))
-class TestSignedRealLiteralConstant(NumpyTestCase): # R416
+class TestSignedRealLiteralConstant(TestCase): # R416
- def check_signed_real_literal_constant(self):
+ def test_signed_real_literal_constant(self):
cls = Signed_Real_Literal_Constant
a = cls('12.78')
assert isinstance(a,cls),`a`
@@ -265,9 +265,9 @@ class TestSignedRealLiteralConstant(NumpyTestCase): # R416
assert isinstance(a,cls),`a`
assert_equal(str(a),'-10.9E-17_quad')
-class TestRealLiteralConstant(NumpyTestCase): # R417
+class TestRealLiteralConstant(TestCase): # R417
- def check_real_literal_constant(self):
+ def test_real_literal_constant(self):
cls = Real_Literal_Constant
a = cls('12.78')
assert isinstance(a,cls),`a`
@@ -326,9 +326,9 @@ class TestRealLiteralConstant(NumpyTestCase): # R417
assert isinstance(a,cls),`a`
assert_equal(str(a),'0.0D+0')
-class TestCharSelector(NumpyTestCase): # R424
+class TestCharSelector(TestCase): # R424
- def check_char_selector(self):
+ def test_char_selector(self):
cls = Char_Selector
a = cls('(len=2, kind=8)')
assert isinstance(a,cls),`a`
@@ -352,9 +352,9 @@ class TestCharSelector(NumpyTestCase): # R424
assert isinstance(a,cls),`a`
assert_equal(str(a),'(LEN = 2, KIND = 8)')
-class TestComplexLiteralConstant(NumpyTestCase): # R421
+class TestComplexLiteralConstant(TestCase): # R421
- def check_complex_literal_constant(self):
+ def test_complex_literal_constant(self):
cls = Complex_Literal_Constant
a = cls('(1.0, -1.0)')
assert isinstance(a,cls),`a`
@@ -374,9 +374,9 @@ class TestComplexLiteralConstant(NumpyTestCase): # R421
assert_equal(str(a),'(0., PI)')
-class TestTypeName(NumpyTestCase): # C424
+class TestTypeName(TestCase): # C424
- def check_simple(self):
+ def test_simple(self):
cls = Type_Name
a = cls('a')
assert isinstance(a,cls),`a`
@@ -386,9 +386,9 @@ class TestTypeName(NumpyTestCase): # C424
self.assertRaises(NoMatchError,cls,'integer')
self.assertRaises(NoMatchError,cls,'doubleprecision')
-class TestLengthSelector(NumpyTestCase): # R425
+class TestLengthSelector(TestCase): # R425
- def check_length_selector(self):
+ def test_length_selector(self):
cls = Length_Selector
a = cls('( len = *)')
assert isinstance(a,cls),`a`
@@ -399,9 +399,9 @@ class TestLengthSelector(NumpyTestCase): # R425
assert isinstance(a,cls),`a`
assert_equal(str(a),'*2')
-class TestCharLength(NumpyTestCase): # R426
+class TestCharLength(TestCase): # R426
- def check_char_length(self):
+ def test_char_length(self):
cls = Char_Length
a = cls('(1)')
assert isinstance(a,cls),`a`
@@ -420,9 +420,9 @@ class TestCharLength(NumpyTestCase): # R426
assert isinstance(a,cls),`a`
assert_equal(str(a),'(:)')
-class TestCharLiteralConstant(NumpyTestCase): # R427
+class TestCharLiteralConstant(TestCase): # R427
- def check_char_literal_constant(self):
+ def test_char_literal_constant(self):
cls = Char_Literal_Constant
a = cls('NIH_"DO"')
assert isinstance(a,cls),`a`
@@ -454,9 +454,9 @@ class TestCharLiteralConstant(NumpyTestCase): # R427
assert isinstance(a,cls),`a`
assert_equal(str(a),'"hey ha(ada)\t"')
-class TestLogicalLiteralConstant(NumpyTestCase): # R428
+class TestLogicalLiteralConstant(TestCase): # R428
- def check_logical_literal_constant(self):
+ def test_logical_literal_constant(self):
cls = Logical_Literal_Constant
a = cls('.TRUE.')
assert isinstance(a,cls),`a`
@@ -475,9 +475,9 @@ class TestLogicalLiteralConstant(NumpyTestCase): # R428
assert isinstance(a,cls),`a`
assert_equal(str(a),'.TRUE._HA')
-class TestDerivedTypeStmt(NumpyTestCase): # R430
+class TestDerivedTypeStmt(TestCase): # R430
- def check_simple(self):
+ def test_simple(self):
cls = Derived_Type_Stmt
a = cls('type a')
assert isinstance(a, cls),`a`
@@ -492,18 +492,18 @@ class TestDerivedTypeStmt(NumpyTestCase): # R430
assert isinstance(a, cls),`a`
assert_equal(str(a),'TYPE, PRIVATE, ABSTRACT :: a(b, c)')
-class TestTypeName(NumpyTestCase): # C423
+class TestTypeName(TestCase): # C423
- def check_simple(self):
+ def test_simple(self):
cls = Type_Name
a = cls('a')
assert isinstance(a, cls),`a`
assert_equal(str(a),'a')
assert_equal(repr(a),"Type_Name('a')")
-class TestTypeAttrSpec(NumpyTestCase): # R431
+class TestTypeAttrSpec(TestCase): # R431
- def check_simple(self):
+ def test_simple(self):
cls = Type_Attr_Spec
a = cls('abstract')
assert isinstance(a, cls),`a`
@@ -523,9 +523,9 @@ class TestTypeAttrSpec(NumpyTestCase): # R431
assert_equal(str(a),'PRIVATE')
-class TestEndTypeStmt(NumpyTestCase): # R433
+class TestEndTypeStmt(TestCase): # R433
- def check_simple(self):
+ def test_simple(self):
cls = End_Type_Stmt
a = cls('end type')
assert isinstance(a, cls),`a`
@@ -536,18 +536,18 @@ class TestEndTypeStmt(NumpyTestCase): # R433
assert isinstance(a, cls),`a`
assert_equal(str(a),'END TYPE a')
-class TestSequenceStmt(NumpyTestCase): # R434
+class TestSequenceStmt(TestCase): # R434
- def check_simple(self):
+ def test_simple(self):
cls = Sequence_Stmt
a = cls('sequence')
assert isinstance(a, cls),`a`
assert_equal(str(a),'SEQUENCE')
assert_equal(repr(a),"Sequence_Stmt('SEQUENCE')")
-class TestTypeParamDefStmt(NumpyTestCase): # R435
+class TestTypeParamDefStmt(TestCase): # R435
- def check_simple(self):
+ def test_simple(self):
cls = Type_Param_Def_Stmt
a = cls('integer ,kind :: a')
assert isinstance(a, cls),`a`
@@ -558,9 +558,9 @@ class TestTypeParamDefStmt(NumpyTestCase): # R435
assert isinstance(a, cls),`a`
assert_equal(str(a),'INTEGER*2, LEN :: a = 3, b = 2 + c')
-class TestTypeParamDecl(NumpyTestCase): # R436
+class TestTypeParamDecl(TestCase): # R436
- def check_simple(self):
+ def test_simple(self):
cls = Type_Param_Decl
a = cls('a=2')
assert isinstance(a, cls),`a`
@@ -571,9 +571,9 @@ class TestTypeParamDecl(NumpyTestCase): # R436
assert isinstance(a, Name),`a`
assert_equal(str(a),'a')
-class TestTypeParamAttrSpec(NumpyTestCase): # R437
+class TestTypeParamAttrSpec(TestCase): # R437
- def check_simple(self):
+ def test_simple(self):
cls = Type_Param_Attr_Spec
a = cls('kind')
assert isinstance(a, cls),`a`
@@ -584,9 +584,9 @@ class TestTypeParamAttrSpec(NumpyTestCase): # R437
assert isinstance(a, cls),`a`
assert_equal(str(a),'LEN')
-class TestComponentAttrSpec(NumpyTestCase): # R441
+class TestComponentAttrSpec(TestCase): # R441
- def check_simple(self):
+ def test_simple(self):
cls = Component_Attr_Spec
a = cls('pointer')
assert isinstance(a, cls),`a`
@@ -605,9 +605,9 @@ class TestComponentAttrSpec(NumpyTestCase): # R441
assert isinstance(a, Access_Spec),`a`
assert_equal(str(a),'PRIVATE')
-class TestComponentDecl(NumpyTestCase): # R442
+class TestComponentDecl(TestCase): # R442
- def check_simple(self):
+ def test_simple(self):
cls = Component_Decl
a = cls('a(1)')
assert isinstance(a, cls),`a`
@@ -626,9 +626,9 @@ class TestComponentDecl(NumpyTestCase): # R442
assert isinstance(a, cls),`a`
assert_equal(str(a),'a(1) => NULL')
-class TestFinalBinding(NumpyTestCase): # R454
+class TestFinalBinding(TestCase): # R454
- def check_simple(self):
+ def test_simple(self):
cls = Final_Binding
a = cls('final a, b')
assert isinstance(a,cls),`a`
@@ -639,9 +639,9 @@ class TestFinalBinding(NumpyTestCase): # R454
assert isinstance(a,cls),`a`
assert_equal(str(a),'FINAL :: a')
-class TestDerivedTypeSpec(NumpyTestCase): # R455
+class TestDerivedTypeSpec(TestCase): # R455
- def check_simple(self):
+ def test_simple(self):
cls = Derived_Type_Spec
a = cls('a(b)')
assert isinstance(a,cls),`a`
@@ -660,9 +660,9 @@ class TestDerivedTypeSpec(NumpyTestCase): # R455
assert isinstance(a,cls),`a`
assert_equal(str(a),'a()')
-class TestTypeParamSpec(NumpyTestCase): # R456
+class TestTypeParamSpec(TestCase): # R456
- def check_type_param_spec(self):
+ def test_type_param_spec(self):
cls = Type_Param_Spec
a = cls('a=1')
assert isinstance(a,cls),`a`
@@ -677,9 +677,9 @@ class TestTypeParamSpec(NumpyTestCase): # R456
assert isinstance(a,cls),`a`
assert_equal(str(a),'k = :')
-class TestTypeParamSpecList(NumpyTestCase): # R456-list
+class TestTypeParamSpecList(TestCase): # R456-list
- def check_type_param_spec_list(self):
+ def test_type_param_spec_list(self):
cls = Type_Param_Spec_List
a = cls('a,b')
@@ -694,9 +694,9 @@ class TestTypeParamSpecList(NumpyTestCase): # R456-list
assert isinstance(a,cls),`a`
assert_equal(str(a),'k = a, c, g = 1')
-class TestStructureConstructor2(NumpyTestCase): # R457.b
+class TestStructureConstructor2(TestCase): # R457.b
- def check_simple(self):
+ def test_simple(self):
cls = Structure_Constructor_2
a = cls('k=a')
assert isinstance(a,cls),`a`
@@ -707,9 +707,9 @@ class TestStructureConstructor2(NumpyTestCase): # R457.b
assert isinstance(a,Name),`a`
assert_equal(str(a),'a')
-class TestStructureConstructor(NumpyTestCase): # R457
+class TestStructureConstructor(TestCase): # R457
- def check_structure_constructor(self):
+ def test_structure_constructor(self):
cls = Structure_Constructor
a = cls('t()')
assert isinstance(a,cls),`a`
@@ -729,9 +729,9 @@ class TestStructureConstructor(NumpyTestCase): # R457
assert isinstance(a,Name),`a`
assert_equal(str(a),'a')
-class TestComponentSpec(NumpyTestCase): # R458
+class TestComponentSpec(TestCase): # R458
- def check_simple(self):
+ def test_simple(self):
cls = Component_Spec
a = cls('k=a')
assert isinstance(a,cls),`a`
@@ -750,9 +750,9 @@ class TestComponentSpec(NumpyTestCase): # R458
assert isinstance(a, Component_Spec),`a`
assert_equal(str(a),'s = a % b')
-class TestComponentSpecList(NumpyTestCase): # R458-list
+class TestComponentSpecList(TestCase): # R458-list
- def check_simple(self):
+ def test_simple(self):
cls = Component_Spec_List
a = cls('k=a, b')
assert isinstance(a,cls),`a`
@@ -763,9 +763,9 @@ class TestComponentSpecList(NumpyTestCase): # R458-list
assert isinstance(a,cls),`a`
assert_equal(str(a),'k = a, c')
-class TestArrayConstructor(NumpyTestCase): # R465
+class TestArrayConstructor(TestCase): # R465
- def check_simple(self):
+ def test_simple(self):
cls = Array_Constructor
a = cls('(/a/)')
assert isinstance(a,cls),`a`
@@ -785,9 +785,9 @@ class TestArrayConstructor(NumpyTestCase): # R465
assert isinstance(a,cls),`a`
assert_equal(str(a),'[INTEGER :: a, b]')
-class TestAcSpec(NumpyTestCase): # R466
+class TestAcSpec(TestCase): # R466
- def check_ac_spec(self):
+ def test_ac_spec(self):
cls = Ac_Spec
a = cls('integer ::')
assert isinstance(a,cls),`a`
@@ -806,9 +806,9 @@ class TestAcSpec(NumpyTestCase): # R466
assert isinstance(a,cls),`a`
assert_equal(str(a),'INTEGER :: a, (a, b, n = 1, 5)')
-class TestAcValueList(NumpyTestCase): # R469-list
+class TestAcValueList(TestCase): # R469-list
- def check_ac_value_list(self):
+ def test_ac_value_list(self):
cls = Ac_Value_List
a = cls('a, b')
assert isinstance(a,cls),`a`
@@ -819,18 +819,18 @@ class TestAcValueList(NumpyTestCase): # R469-list
assert isinstance(a,Name),`a`
assert_equal(str(a),'a')
-class TestAcImpliedDo(NumpyTestCase): # R470
+class TestAcImpliedDo(TestCase): # R470
- def check_ac_implied_do(self):
+ def test_ac_implied_do(self):
cls = Ac_Implied_Do
a = cls('( a, b, n = 1, 5 )')
assert isinstance(a,cls),`a`
assert_equal(str(a),'(a, b, n = 1, 5)')
assert_equal(repr(a),"Ac_Implied_Do(Ac_Value_List(',', (Name('a'), Name('b'))), Ac_Implied_Do_Control(Name('n'), [Int_Literal_Constant('1', None), Int_Literal_Constant('5', None)]))")
-class TestAcImpliedDoControl(NumpyTestCase): # R471
+class TestAcImpliedDoControl(TestCase): # R471
- def check_ac_implied_do_control(self):
+ def test_ac_implied_do_control(self):
cls = Ac_Implied_Do_Control
a = cls('n = 3, 5')
assert isinstance(a,cls),`a`
@@ -845,9 +845,9 @@ class TestAcImpliedDoControl(NumpyTestCase): # R471
############################### SECTION 5 ####################################
###############################################################################
-class TestTypeDeclarationStmt(NumpyTestCase): # R501
+class TestTypeDeclarationStmt(TestCase): # R501
- def check_simple(self):
+ def test_simple(self):
cls = Type_Declaration_Stmt
a = cls('integer a')
assert isinstance(a, cls),`a`
@@ -869,9 +869,9 @@ class TestTypeDeclarationStmt(NumpyTestCase): # R501
a = cls('DOUBLE PRECISION ALPHA, BETA')
assert isinstance(a, cls),`a`
-class TestDeclarationTypeSpec(NumpyTestCase): # R502
+class TestDeclarationTypeSpec(TestCase): # R502
- def check_simple(self):
+ def test_simple(self):
cls = Declaration_Type_Spec
a = cls('Integer*2')
assert isinstance(a, Intrinsic_Type_Spec),`a`
@@ -882,9 +882,9 @@ class TestDeclarationTypeSpec(NumpyTestCase): # R502
assert_equal(str(a), 'TYPE(foo)')
assert_equal(repr(a), "Declaration_Type_Spec('TYPE', Type_Name('foo'))")
-class TestAttrSpec(NumpyTestCase): # R503
+class TestAttrSpec(TestCase): # R503
- def check_simple(self):
+ def test_simple(self):
cls = Attr_Spec
a = cls('allocatable')
assert isinstance(a, cls),`a`
@@ -894,27 +894,27 @@ class TestAttrSpec(NumpyTestCase): # R503
assert isinstance(a, Dimension_Attr_Spec),`a`
assert_equal(str(a),'DIMENSION(a)')
-class TestDimensionAttrSpec(NumpyTestCase): # R503.d
+class TestDimensionAttrSpec(TestCase): # R503.d
- def check_simple(self):
+ def test_simple(self):
cls = Dimension_Attr_Spec
a = cls('dimension(a)')
assert isinstance(a, cls),`a`
assert_equal(str(a),'DIMENSION(a)')
assert_equal(repr(a),"Dimension_Attr_Spec('DIMENSION', Explicit_Shape_Spec(None, Name('a')))")
-class TestIntentAttrSpec(NumpyTestCase): # R503.f
+class TestIntentAttrSpec(TestCase): # R503.f
- def check_simple(self):
+ def test_simple(self):
cls = Intent_Attr_Spec
a = cls('intent(in)')
assert isinstance(a, cls),`a`
assert_equal(str(a),'INTENT(IN)')
assert_equal(repr(a),"Intent_Attr_Spec('INTENT', Intent_Spec('IN'))")
-class TestEntityDecl(NumpyTestCase): # 504
+class TestEntityDecl(TestCase): # 504
- def check_simple(self):
+ def test_simple(self):
cls = Entity_Decl
a = cls('a(1)')
assert isinstance(a, cls),`a`
@@ -929,9 +929,9 @@ class TestEntityDecl(NumpyTestCase): # 504
assert isinstance(a, cls),`a`
assert_equal(str(a),'a(1)*(3) = 2')
-class TestAccessSpec(NumpyTestCase): # R508
+class TestAccessSpec(TestCase): # R508
- def check_simple(self):
+ def test_simple(self):
cls = Access_Spec
a = cls('private')
assert isinstance(a, cls),`a`
@@ -942,9 +942,9 @@ class TestAccessSpec(NumpyTestCase): # R508
assert isinstance(a, cls),`a`
assert_equal(str(a),'PUBLIC')
-class TestLanguageBindingSpec(NumpyTestCase): # R509
+class TestLanguageBindingSpec(TestCase): # R509
- def check_simple(self):
+ def test_simple(self):
cls = Language_Binding_Spec
a = cls('bind(c)')
assert isinstance(a, cls),`a`
@@ -955,9 +955,9 @@ class TestLanguageBindingSpec(NumpyTestCase): # R509
assert isinstance(a, cls),`a`
assert_equal(str(a),'BIND(C, NAME = "hey")')
-class TestExplicitShapeSpec(NumpyTestCase): # R511
+class TestExplicitShapeSpec(TestCase): # R511
- def check_simple(self):
+ def test_simple(self):
cls = Explicit_Shape_Spec
a = cls('a:b')
assert isinstance(a, cls),`a`
@@ -968,9 +968,9 @@ class TestExplicitShapeSpec(NumpyTestCase): # R511
assert isinstance(a, cls),`a`
assert_equal(str(a),'a')
-class TestUpperBound(NumpyTestCase): # R513
+class TestUpperBound(TestCase): # R513
- def check_simple(self):
+ def test_simple(self):
cls = Upper_Bound
a = cls('a')
assert isinstance(a, Name),`a`
@@ -978,9 +978,9 @@ class TestUpperBound(NumpyTestCase): # R513
self.assertRaises(NoMatchError,cls,'*')
-class TestAssumedShapeSpec(NumpyTestCase): # R514
+class TestAssumedShapeSpec(TestCase): # R514
- def check_simple(self):
+ def test_simple(self):
cls = Assumed_Shape_Spec
a = cls(':')
assert isinstance(a, cls),`a`
@@ -991,9 +991,9 @@ class TestAssumedShapeSpec(NumpyTestCase): # R514
assert isinstance(a, cls),`a`
assert_equal(str(a),'a :')
-class TestDeferredShapeSpec(NumpyTestCase): # R515
+class TestDeferredShapeSpec(TestCase): # R515
- def check_simple(self):
+ def test_simple(self):
cls = Deferred_Shape_Spec
a = cls(':')
assert isinstance(a, cls),`a`
@@ -1001,9 +1001,9 @@ class TestDeferredShapeSpec(NumpyTestCase): # R515
assert_equal(repr(a),'Deferred_Shape_Spec(None, None)')
-class TestAssumedSizeSpec(NumpyTestCase): # R516
+class TestAssumedSizeSpec(TestCase): # R516
- def check_simple(self):
+ def test_simple(self):
cls = Assumed_Size_Spec
a = cls('*')
assert isinstance(a, cls),`a`
@@ -1022,9 +1022,9 @@ class TestAssumedSizeSpec(NumpyTestCase): # R516
assert isinstance(a, cls),`a`
assert_equal(str(a),'a : b, 1 : *')
-class TestAccessStmt(NumpyTestCase): # R518
+class TestAccessStmt(TestCase): # R518
- def check_simple(self):
+ def test_simple(self):
cls = Access_Stmt
a = cls('private')
assert isinstance(a, cls),`a`
@@ -1039,9 +1039,9 @@ class TestAccessStmt(NumpyTestCase): # R518
assert isinstance(a, cls),`a`
assert_equal(str(a),'PUBLIC :: a')
-class TestParameterStmt(NumpyTestCase): # R538
+class TestParameterStmt(TestCase): # R538
- def check_simple(self):
+ def test_simple(self):
cls = Parameter_Stmt
a = cls('parameter(a=1)')
assert isinstance(a, cls),`a`
@@ -1056,18 +1056,18 @@ class TestParameterStmt(NumpyTestCase): # R538
assert isinstance(a, cls),`a`
assert_equal(str(a),'PARAMETER(ONE = 1.0D+0, ZERO = 0.0D+0)')
-class TestNamedConstantDef(NumpyTestCase): # R539
+class TestNamedConstantDef(TestCase): # R539
- def check_simple(self):
+ def test_simple(self):
cls = Named_Constant_Def
a = cls('a=1')
assert isinstance(a, cls),`a`
assert_equal(str(a),'a = 1')
assert_equal(repr(a),"Named_Constant_Def(Name('a'), Int_Literal_Constant('1', None))")
-class TestPointerDecl(NumpyTestCase): # R541
+class TestPointerDecl(TestCase): # R541
- def check_simple(self):
+ def test_simple(self):
cls = Pointer_Decl
a = cls('a(:)')
assert isinstance(a, cls),`a`
@@ -1078,9 +1078,9 @@ class TestPointerDecl(NumpyTestCase): # R541
assert isinstance(a, cls),`a`
assert_equal(str(a),'a(:, :)')
-class TestImplicitStmt(NumpyTestCase): # R549
+class TestImplicitStmt(TestCase): # R549
- def check_simple(self):
+ def test_simple(self):
cls = Implicit_Stmt
a = cls('implicitnone')
assert isinstance(a, cls),`a`
@@ -1091,9 +1091,9 @@ class TestImplicitStmt(NumpyTestCase): # R549
assert isinstance(a, cls),`a`
assert_equal(str(a),'IMPLICIT REAL(A - D), DOUBLE PRECISION(R - T, X), TYPE(a)(Y - Z)')
-class TestImplicitSpec(NumpyTestCase): # R550
+class TestImplicitSpec(TestCase): # R550
- def check_simple(self):
+ def test_simple(self):
cls = Implicit_Spec
a = cls('integer (a-z)')
assert isinstance(a, cls),`a`
@@ -1104,9 +1104,9 @@ class TestImplicitSpec(NumpyTestCase): # R550
assert isinstance(a, cls),`a`
assert_equal(str(a),'DOUBLE COMPLEX(R, D - G)')
-class TestLetterSpec(NumpyTestCase): # R551
+class TestLetterSpec(TestCase): # R551
- def check_simple(self):
+ def test_simple(self):
cls = Letter_Spec
a = cls('a-z')
assert isinstance(a, cls),`a`
@@ -1117,9 +1117,9 @@ class TestLetterSpec(NumpyTestCase): # R551
assert isinstance(a, cls),`a`
assert_equal(str(a),'D')
-class TestEquivalenceStmt(NumpyTestCase): # R554
+class TestEquivalenceStmt(TestCase): # R554
- def check_simple(self):
+ def test_simple(self):
cls = Equivalence_Stmt
a = cls('equivalence (a, b ,z)')
assert isinstance(a, cls),`a`
@@ -1130,9 +1130,9 @@ class TestEquivalenceStmt(NumpyTestCase): # R554
assert isinstance(a, cls),`a`
assert_equal(str(a),'EQUIVALENCE(a, b, z), (b, l)')
-class TestCommonStmt(NumpyTestCase): # R557
+class TestCommonStmt(TestCase): # R557
- def check_simple(self):
+ def test_simple(self):
cls = Common_Stmt
a = cls('common a')
assert isinstance(a, cls),`a`
@@ -1151,9 +1151,9 @@ class TestCommonStmt(NumpyTestCase): # R557
assert isinstance(a, cls),`a`
assert_equal(str(a),'COMMON /name/ a, b(4, 5) // c /ljuks/ g(2)')
-class TestCommonBlockObject(NumpyTestCase): # R558
+class TestCommonBlockObject(TestCase): # R558
- def check_simple(self):
+ def test_simple(self):
cls = Common_Block_Object
a = cls('a(2)')
assert isinstance(a, cls),`a`
@@ -1169,9 +1169,9 @@ class TestCommonBlockObject(NumpyTestCase): # R558
############################### SECTION 6 ####################################
###############################################################################
-class TestSubstring(NumpyTestCase): # R609
+class TestSubstring(TestCase): # R609
- def check_simple(self):
+ def test_simple(self):
cls = Substring
a = cls('a(:)')
assert isinstance(a, cls),`a`
@@ -1184,9 +1184,9 @@ class TestSubstring(NumpyTestCase): # R609
assert_equal(repr(a),"Substring(Name('a'), Substring_Range(Int_Literal_Constant('1', None), Int_Literal_Constant('2', None)))")
-class TestSubstringRange(NumpyTestCase): # R611
+class TestSubstringRange(TestCase): # R611
- def check_simple(self):
+ def test_simple(self):
cls = Substring_Range
a = cls(':')
assert isinstance(a, cls),`a`
@@ -1215,9 +1215,9 @@ class TestSubstringRange(NumpyTestCase): # R611
assert_equal(str(a),': b')
-class TestDataRef(NumpyTestCase): # R612
+class TestDataRef(TestCase): # R612
- def check_data_ref(self):
+ def test_data_ref(self):
cls = Data_Ref
a = cls('a%b')
assert isinstance(a,cls),`a`
@@ -1228,17 +1228,17 @@ class TestDataRef(NumpyTestCase): # R612
assert isinstance(a,Name),`a`
assert_equal(str(a),'a')
-class TestPartRef(NumpyTestCase): # R613
+class TestPartRef(TestCase): # R613
- def check_part_ref(self):
+ def test_part_ref(self):
cls = Part_Ref
a = cls('a')
assert isinstance(a, Name),`a`
assert_equal(str(a),'a')
-class TestTypeParamInquiry(NumpyTestCase): # R615
+class TestTypeParamInquiry(TestCase): # R615
- def check_simple(self):
+ def test_simple(self):
cls = Type_Param_Inquiry
a = cls('a % b')
assert isinstance(a,cls),`a`
@@ -1246,9 +1246,9 @@ class TestTypeParamInquiry(NumpyTestCase): # R615
assert_equal(repr(a),"Type_Param_Inquiry(Name('a'), '%', Name('b'))")
-class TestArraySection(NumpyTestCase): # R617
+class TestArraySection(TestCase): # R617
- def check_array_section(self):
+ def test_array_section(self):
cls = Array_Section
a = cls('a(:)')
assert isinstance(a,cls),`a`
@@ -1260,9 +1260,9 @@ class TestArraySection(NumpyTestCase): # R617
assert_equal(str(a),'a(2 :)')
-class TestSectionSubscript(NumpyTestCase): # R619
+class TestSectionSubscript(TestCase): # R619
- def check_simple(self):
+ def test_simple(self):
cls = Section_Subscript
a = cls('1:2')
@@ -1273,9 +1273,9 @@ class TestSectionSubscript(NumpyTestCase): # R619
assert isinstance(a, Name),`a`
assert_equal(str(a),'zzz')
-class TestSectionSubscriptList(NumpyTestCase): # R619-list
+class TestSectionSubscriptList(TestCase): # R619-list
- def check_simple(self):
+ def test_simple(self):
cls = Section_Subscript_List
a = cls('a,2')
assert isinstance(a,cls),`a`
@@ -1290,9 +1290,9 @@ class TestSectionSubscriptList(NumpyTestCase): # R619-list
assert isinstance(a,cls),`a`
assert_equal(str(a),': : 1, 3')
-class TestSubscriptTriplet(NumpyTestCase): # R620
+class TestSubscriptTriplet(TestCase): # R620
- def check_simple(self):
+ def test_simple(self):
cls = Subscript_Triplet
a = cls('a:b')
assert isinstance(a,cls),`a`
@@ -1319,18 +1319,18 @@ class TestSubscriptTriplet(NumpyTestCase): # R620
assert isinstance(a,cls),`a`
assert_equal(str(a),'a + 1 :')
-class TestAllocOpt(NumpyTestCase): # R624
+class TestAllocOpt(TestCase): # R624
- def check_simple(self):
+ def test_simple(self):
cls = Alloc_Opt
a = cls('stat=a')
assert isinstance(a, cls),`a`
assert_equal(str(a),'STAT = a')
assert_equal(repr(a),"Alloc_Opt('STAT', Name('a'))")
-class TestNullifyStmt(NumpyTestCase): # R633
+class TestNullifyStmt(TestCase): # R633
- def check_simple(self):
+ def test_simple(self):
cls = Nullify_Stmt
a = cls('nullify (a)')
assert isinstance(a, cls),`a`
@@ -1345,9 +1345,9 @@ class TestNullifyStmt(NumpyTestCase): # R633
############################### SECTION 7 ####################################
###############################################################################
-class TestPrimary(NumpyTestCase): # R701
+class TestPrimary(TestCase): # R701
- def check_simple(self):
+ def test_simple(self):
cls = Primary
a = cls('a')
assert isinstance(a,Name),`a`
@@ -1401,9 +1401,9 @@ class TestPrimary(NumpyTestCase): # R701
assert isinstance(a,Real_Literal_Constant),`a`
assert_equal(str(a),'0.0E-1')
-class TestParenthesis(NumpyTestCase): # R701.h
+class TestParenthesis(TestCase): # R701.h
- def check_simple(self):
+ def test_simple(self):
cls = Parenthesis
a = cls('(a)')
assert isinstance(a,cls),`a`
@@ -1422,9 +1422,9 @@ class TestParenthesis(NumpyTestCase): # R701.h
assert isinstance(a,cls),`a`
assert_equal(str(a),'(a + (a + c))')
-class TestLevel1Expr(NumpyTestCase): # R702
+class TestLevel1Expr(TestCase): # R702
- def check_simple(self):
+ def test_simple(self):
cls = Level_1_Expr
a = cls('.hey. a')
assert isinstance(a,cls),`a`
@@ -1433,9 +1433,9 @@ class TestLevel1Expr(NumpyTestCase): # R702
self.assertRaises(NoMatchError,cls,'.not. a')
-class TestMultOperand(NumpyTestCase): # R704
+class TestMultOperand(TestCase): # R704
- def check_simple(self):
+ def test_simple(self):
cls = Mult_Operand
a = cls('a**b')
assert isinstance(a,cls),`a`
@@ -1454,9 +1454,9 @@ class TestMultOperand(NumpyTestCase): # R704
assert isinstance(a,Real_Literal_Constant),`a`
assert_equal(str(a),'0.0E-1')
-class TestAddOperand(NumpyTestCase): # R705
+class TestAddOperand(TestCase): # R705
- def check_simple(self):
+ def test_simple(self):
cls = Add_Operand
a = cls('a*b')
assert isinstance(a,cls),`a`
@@ -1475,9 +1475,9 @@ class TestAddOperand(NumpyTestCase): # R705
assert isinstance(a,Real_Literal_Constant),`a`
assert_equal(str(a),'0.0E-1')
-class TestLevel2Expr(NumpyTestCase): # R706
+class TestLevel2Expr(TestCase): # R706
- def check_simple(self):
+ def test_simple(self):
cls = Level_2_Expr
a = cls('a+b')
assert isinstance(a,cls),`a`
@@ -1509,9 +1509,9 @@ class TestLevel2Expr(NumpyTestCase): # R706
assert_equal(str(a),'0.0E-1')
-class TestLevel2UnaryExpr(NumpyTestCase):
+class TestLevel2UnaryExpr(TestCase):
- def check_simple(self):
+ def test_simple(self):
cls = Level_2_Unary_Expr
a = cls('+a')
assert isinstance(a,cls),`a`
@@ -1531,9 +1531,9 @@ class TestLevel2UnaryExpr(NumpyTestCase):
assert_equal(str(a),'0.0E-1')
-class TestLevel3Expr(NumpyTestCase): # R710
+class TestLevel3Expr(TestCase): # R710
- def check_simple(self):
+ def test_simple(self):
cls = Level_3_Expr
a = cls('a//b')
assert isinstance(a,cls),`a`
@@ -1544,9 +1544,9 @@ class TestLevel3Expr(NumpyTestCase): # R710
assert isinstance(a,cls),`a`
assert_equal(str(a),'"a" // "b"')
-class TestLevel4Expr(NumpyTestCase): # R712
+class TestLevel4Expr(TestCase): # R712
- def check_simple(self):
+ def test_simple(self):
cls = Level_4_Expr
a = cls('a.eq.b')
assert isinstance(a,cls),`a`
@@ -1593,18 +1593,18 @@ class TestLevel4Expr(NumpyTestCase): # R712
assert isinstance(a,cls),`a`
assert_equal(str(a),'a > b')
-class TestAndOperand(NumpyTestCase): # R714
+class TestAndOperand(TestCase): # R714
- def check_simple(self):
+ def test_simple(self):
cls = And_Operand
a = cls('.not.a')
assert isinstance(a,cls),`a`
assert_equal(str(a),'.NOT. a')
assert_equal(repr(a),"And_Operand('.NOT.', Name('a'))")
-class TestOrOperand(NumpyTestCase): # R715
+class TestOrOperand(TestCase): # R715
- def check_simple(self):
+ def test_simple(self):
cls = Or_Operand
a = cls('a.and.b')
assert isinstance(a,cls),`a`
@@ -1612,9 +1612,9 @@ class TestOrOperand(NumpyTestCase): # R715
assert_equal(repr(a),"Or_Operand(Name('a'), '.AND.', Name('b'))")
-class TestEquivOperand(NumpyTestCase): # R716
+class TestEquivOperand(TestCase): # R716
- def check_simple(self):
+ def test_simple(self):
cls = Equiv_Operand
a = cls('a.or.b')
assert isinstance(a,cls),`a`
@@ -1622,9 +1622,9 @@ class TestEquivOperand(NumpyTestCase): # R716
assert_equal(repr(a),"Equiv_Operand(Name('a'), '.OR.', Name('b'))")
-class TestLevel5Expr(NumpyTestCase): # R717
+class TestLevel5Expr(TestCase): # R717
- def check_simple(self):
+ def test_simple(self):
cls = Level_5_Expr
a = cls('a.eqv.b')
assert isinstance(a,cls),`a`
@@ -1639,9 +1639,9 @@ class TestLevel5Expr(NumpyTestCase): # R717
assert isinstance(a,Level_4_Expr),`a`
assert_equal(str(a),'a .EQ. b')
-class TestExpr(NumpyTestCase): # R722
+class TestExpr(TestCase): # R722
- def check_simple(self):
+ def test_simple(self):
cls = Expr
a = cls('a .op. b')
assert isinstance(a,cls),`a`
@@ -1661,9 +1661,9 @@ class TestExpr(NumpyTestCase): # R722
self.assertRaises(NoMatchError,Scalar_Int_Expr,'a,b')
-class TestAssignmentStmt(NumpyTestCase): # R734
+class TestAssignmentStmt(TestCase): # R734
- def check_simple(self):
+ def test_simple(self):
cls = Assignment_Stmt
a = cls('a = b')
assert isinstance(a, cls),`a`
@@ -1678,27 +1678,27 @@ class TestAssignmentStmt(NumpyTestCase): # R734
assert isinstance(a, cls),`a`
assert_equal(str(a),'a % c = b + c')
-class TestProcComponentRef(NumpyTestCase): # R741
+class TestProcComponentRef(TestCase): # R741
- def check_proc_component_ref(self):
+ def test_proc_component_ref(self):
cls = Proc_Component_Ref
a = cls('a % b')
assert isinstance(a,cls),`a`
assert_equal(str(a),'a % b')
assert_equal(repr(a),"Proc_Component_Ref(Name('a'), '%', Name('b'))")
-class TestWhereStmt(NumpyTestCase): # R743
+class TestWhereStmt(TestCase): # R743
- def check_simple(self):
+ def test_simple(self):
cls = Where_Stmt
a = cls('where (a) c=2')
assert isinstance(a,cls),`a`
assert_equal(str(a),'WHERE (a) c = 2')
assert_equal(repr(a),"Where_Stmt(Name('a'), Assignment_Stmt(Name('c'), '=', Int_Literal_Constant('2', None)))")
-class TestWhereConstructStmt(NumpyTestCase): # R745
+class TestWhereConstructStmt(TestCase): # R745
- def check_simple(self):
+ def test_simple(self):
cls = Where_Construct_Stmt
a = cls('where (a)')
assert isinstance(a,cls),`a`
@@ -1710,9 +1710,9 @@ class TestWhereConstructStmt(NumpyTestCase): # R745
############################### SECTION 8 ####################################
###############################################################################
-class TestContinueStmt(NumpyTestCase): # R848
+class TestContinueStmt(TestCase): # R848
- def check_simple(self):
+ def test_simple(self):
cls = Continue_Stmt
a = cls('continue')
assert isinstance(a, cls),`a`
@@ -1723,9 +1723,9 @@ class TestContinueStmt(NumpyTestCase): # R848
############################### SECTION 9 ####################################
###############################################################################
-class TestIoUnit(NumpyTestCase): # R901
+class TestIoUnit(TestCase): # R901
- def check_simple(self):
+ def test_simple(self):
cls = Io_Unit
a = cls('*')
assert isinstance(a, cls),`a`
@@ -1735,18 +1735,18 @@ class TestIoUnit(NumpyTestCase): # R901
assert isinstance(a, Name),`a`
assert_equal(str(a),'a')
-class TestWriteStmt(NumpyTestCase): # R911
+class TestWriteStmt(TestCase): # R911
- def check_simple(self):
+ def test_simple(self):
cls = Write_Stmt
a = cls('write (123)"hey"')
assert isinstance(a, cls),`a`
assert_equal(str(a),'WRITE(UNIT = 123) "hey"')
assert_equal(repr(a),'Write_Stmt(Io_Control_Spec_List(\',\', (Io_Control_Spec(\'UNIT\', Int_Literal_Constant(\'123\', None)),)), Char_Literal_Constant(\'"hey"\', None))')
-class TestPrintStmt(NumpyTestCase): # R912
+class TestPrintStmt(TestCase): # R912
- def check_simple(self):
+ def test_simple(self):
cls = Print_Stmt
a = cls('print 123')
assert isinstance(a, cls),`a`
@@ -1757,18 +1757,18 @@ class TestPrintStmt(NumpyTestCase): # R912
assert isinstance(a, cls),`a`
assert_equal(str(a),'PRINT *, "a=", a')
-class TestIoControlSpec(NumpyTestCase): # R913
+class TestIoControlSpec(TestCase): # R913
- def check_simple(self):
+ def test_simple(self):
cls = Io_Control_Spec
a = cls('end=123')
assert isinstance(a, cls),`a`
assert_equal(str(a),'END = 123')
assert_equal(repr(a),"Io_Control_Spec('END', Label('123'))")
-class TestIoControlSpecList(NumpyTestCase): # R913-list
+class TestIoControlSpecList(TestCase): # R913-list
- def check_simple(self):
+ def test_simple(self):
cls = Io_Control_Spec_List
a = cls('end=123')
assert isinstance(a, cls),`a`
@@ -1793,9 +1793,9 @@ class TestIoControlSpecList(NumpyTestCase): # R913-list
assert isinstance(a, cls),`a`
assert_equal(str(a),'UNIT = 123, NML = a')
-class TestFormat(NumpyTestCase): # R914
+class TestFormat(TestCase): # R914
- def check_simple(self):
+ def test_simple(self):
cls = Format
a = cls('*')
assert isinstance(a, cls),`a`
@@ -1810,17 +1810,17 @@ class TestFormat(NumpyTestCase): # R914
assert isinstance(a, Label),`a`
assert_equal(str(a),'123')
-class TestWaitStmt(NumpyTestCase): # R921
+class TestWaitStmt(TestCase): # R921
- def check_simple(self):
+ def test_simple(self):
cls = Wait_Stmt
a = cls('wait (123)')
assert isinstance(a, cls),`a`
assert_equal(str(a),'WAIT(UNIT = 123)')
-class TestWaitSpec(NumpyTestCase): # R922
+class TestWaitSpec(TestCase): # R922
- def check_simple(self):
+ def test_simple(self):
cls = Wait_Spec
a = cls('123')
assert isinstance(a, cls),`a`
@@ -1840,9 +1840,9 @@ class TestWaitSpec(NumpyTestCase): # R922
############################### SECTION 11 ####################################
###############################################################################
-class TestUseStmt(NumpyTestCase): # R1109
+class TestUseStmt(TestCase): # R1109
- def check_simple(self):
+ def test_simple(self):
cls = Use_Stmt
a = cls('use a')
assert isinstance(a, cls),`a`
@@ -1861,9 +1861,9 @@ class TestUseStmt(NumpyTestCase): # R1109
assert isinstance(a, cls),`a`
assert_equal(str(a),'USE, INTRINSIC :: a, OPERATOR(.HEY.) => OPERATOR(.HOO.), c => g')
-class TestModuleNature(NumpyTestCase): # R1110
+class TestModuleNature(TestCase): # R1110
- def check_simple(self):
+ def test_simple(self):
cls = Module_Nature
a = cls('intrinsic')
assert isinstance(a, cls),`a`
@@ -1878,9 +1878,9 @@ class TestModuleNature(NumpyTestCase): # R1110
############################### SECTION 12 ####################################
###############################################################################
-class TestFunctionReference(NumpyTestCase): # R1217
+class TestFunctionReference(TestCase): # R1217
- def check_simple(self):
+ def test_simple(self):
cls = Function_Reference
a = cls('f()')
assert isinstance(a,cls),`a`
@@ -1892,18 +1892,18 @@ class TestFunctionReference(NumpyTestCase): # R1217
assert_equal(str(a),'f(2, k = 1, a)')
-class TestProcedureDesignator(NumpyTestCase): # R1219
+class TestProcedureDesignator(TestCase): # R1219
- def check_procedure_designator(self):
+ def test_procedure_designator(self):
cls = Procedure_Designator
a = cls('a%b')
assert isinstance(a,cls),`a`
assert_equal(str(a),'a % b')
assert_equal(repr(a),"Procedure_Designator(Name('a'), '%', Name('b'))")
-class TestActualArgSpec(NumpyTestCase): # R1220
+class TestActualArgSpec(TestCase): # R1220
- def check_simple(self):
+ def test_simple(self):
cls = Actual_Arg_Spec
a = cls('k=a')
assert isinstance(a,cls),`a`
@@ -1914,9 +1914,9 @@ class TestActualArgSpec(NumpyTestCase): # R1220
assert isinstance(a,Name),`a`
assert_equal(str(a),'a')
-class TestActualArgSpecList(NumpyTestCase):
+class TestActualArgSpecList(TestCase):
- def check_simple(self):
+ def test_simple(self):
cls = Actual_Arg_Spec_List
a = cls('a,b')
assert isinstance(a,cls),`a`
@@ -1935,18 +1935,18 @@ class TestActualArgSpecList(NumpyTestCase):
assert isinstance(a,Name),`a`
assert_equal(str(a),'a')
-class TestAltReturnSpec(NumpyTestCase): # R1222
+class TestAltReturnSpec(TestCase): # R1222
- def check_alt_return_spec(self):
+ def test_alt_return_spec(self):
cls = Alt_Return_Spec
a = cls('* 123')
assert isinstance(a,cls),`a`
assert_equal(str(a),'*123')
assert_equal(repr(a),"Alt_Return_Spec(Label('123'))")
-class TestPrefix(NumpyTestCase): # R1227
+class TestPrefix(TestCase): # R1227
- def check_simple(self):
+ def test_simple(self):
cls = Prefix
a = cls('pure recursive')
assert isinstance(a, cls),`a`
@@ -1957,9 +1957,9 @@ class TestPrefix(NumpyTestCase): # R1227
assert isinstance(a, cls),`a`
assert_equal(str(a),'INTEGER*2 PURE')
-class TestPrefixSpec(NumpyTestCase): # R1228
+class TestPrefixSpec(TestCase): # R1228
- def check_simple(self):
+ def test_simple(self):
cls = Prefix_Spec
a = cls('pure')
assert isinstance(a, cls),`a`
@@ -1978,9 +1978,9 @@ class TestPrefixSpec(NumpyTestCase): # R1228
assert isinstance(a, Intrinsic_Type_Spec),`a`
assert_equal(str(a),'INTEGER*2')
-class TestSubroutineSubprogram(NumpyTestCase): # R1231
+class TestSubroutineSubprogram(TestCase): # R1231
- def check_simple(self):
+ def test_simple(self):
from api import get_reader
reader = get_reader('''\
subroutine foo
@@ -2000,9 +2000,9 @@ class TestSubroutineSubprogram(NumpyTestCase): # R1231
assert isinstance(a, cls),`a`
assert_equal(str(a),'SUBROUTINE foo\n INTEGER :: a\nEND SUBROUTINE foo')
-class TestSubroutineStmt(NumpyTestCase): # R1232
+class TestSubroutineStmt(TestCase): # R1232
- def check_simple(self):
+ def test_simple(self):
cls = Subroutine_Stmt
a = cls('subroutine foo')
assert isinstance(a, cls),`a`
@@ -2021,9 +2021,9 @@ class TestSubroutineStmt(NumpyTestCase): # R1232
assert isinstance(a, cls),`a`
assert_equal(str(a),'SUBROUTINE foo BIND(C)')
-class TestEndSubroutineStmt(NumpyTestCase): # R1234
+class TestEndSubroutineStmt(TestCase): # R1234
- def check_simple(self):
+ def test_simple(self):
cls = End_Subroutine_Stmt
a = cls('end subroutine foo')
assert isinstance(a, cls),`a`
@@ -2038,18 +2038,18 @@ class TestEndSubroutineStmt(NumpyTestCase): # R1234
assert isinstance(a, cls),`a`
assert_equal(str(a),'END SUBROUTINE')
-class TestReturnStmt(NumpyTestCase): # R1236
+class TestReturnStmt(TestCase): # R1236
- def check_simple(self):
+ def test_simple(self):
cls = Return_Stmt
a = cls('return')
assert isinstance(a, cls),`a`
assert_equal(str(a), 'RETURN')
assert_equal(repr(a), 'Return_Stmt(None)')
-class TestContains(NumpyTestCase): # R1237
+class TestContains(TestCase): # R1237
- def check_simple(self):
+ def test_simple(self):
cls = Contains_Stmt
a = cls('Contains')
assert isinstance(a, cls),`a`
@@ -2098,4 +2098,4 @@ if 1:
print '-----'
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/f2py/lib/parser/test_parser.py b/numpy/f2py/lib/parser/test_parser.py
index e7dd4f971..6770ac4a5 100644
--- a/numpy/f2py/lib/parser/test_parser.py
+++ b/numpy/f2py/lib/parser/test_parser.py
@@ -34,25 +34,25 @@ def parse(cls, line, label='',
return r
raise ValueError, 'parsing %r with %s pattern failed' % (line, cls.__name__)
-class TestStatements(NumpyTestCase):
+class TestStatements(TestCase):
- def check_assignment(self):
+ def test_assignment(self):
assert_equal(parse(Assignment,'a=b'), 'a = b')
assert_equal(parse(PointerAssignment,'a=>b'), 'a => b')
assert_equal(parse(Assignment,'a (2)=b(n,m)'), 'a(2) = b(n,m)')
assert_equal(parse(Assignment,'a % 2(2,4)=b(a(i))'), 'a%2(2,4) = b(a(i))')
- def check_assign(self):
+ def test_assign(self):
assert_equal(parse(Assign,'assign 10 to a'),'ASSIGN 10 TO a')
- def check_call(self):
+ def test_call(self):
assert_equal(parse(Call,'call a'),'CALL a')
assert_equal(parse(Call,'call a()'),'CALL a')
assert_equal(parse(Call,'call a(1)'),'CALL a(1)')
assert_equal(parse(Call,'call a(1,2)'),'CALL a(1, 2)')
assert_equal(parse(Call,'call a % 2 ( n , a+1 )'),'CALL a % 2(n, a+1)')
- def check_goto(self):
+ def test_goto(self):
assert_equal(parse(Goto,'go to 19'),'GO TO 19')
assert_equal(parse(Goto,'goto 19'),'GO TO 19')
assert_equal(parse(ComputedGoto,'goto (1, 2 ,3) a+b(2)'),
@@ -63,29 +63,29 @@ class TestStatements(NumpyTestCase):
assert_equal(parse(AssignedGoto,'goto a ( 1 )'),'GO TO a (1)')
assert_equal(parse(AssignedGoto,'goto a ( 1 ,2)'),'GO TO a (1, 2)')
- def check_continue(self):
+ def test_continue(self):
assert_equal(parse(Continue,'continue'),'CONTINUE')
- def check_return(self):
+ def test_return(self):
assert_equal(parse(Return,'return'),'RETURN')
assert_equal(parse(Return,'return a'),'RETURN a')
assert_equal(parse(Return,'return a+1'),'RETURN a+1')
assert_equal(parse(Return,'return a(c, a)'),'RETURN a(c, a)')
- def check_stop(self):
+ def test_stop(self):
assert_equal(parse(Stop,'stop'),'STOP')
assert_equal(parse(Stop,'stop 1'),'STOP 1')
assert_equal(parse(Stop,'stop "a"'),'STOP "a"')
assert_equal(parse(Stop,'stop "a b"'),'STOP "a b"')
- def check_print(self):
+ def test_print(self):
assert_equal(parse(Print, 'print*'),'PRINT *')
assert_equal(parse(Print, 'print "a b( c )"'),'PRINT "a b( c )"')
assert_equal(parse(Print, 'print 12, a'),'PRINT 12, a')
assert_equal(parse(Print, 'print 12, a , b'),'PRINT 12, a, b')
assert_equal(parse(Print, 'print 12, a(c,1) , b'),'PRINT 12, a(c,1), b')
- def check_read(self):
+ def test_read(self):
assert_equal(parse(Read, 'read ( 10 )'),'READ (10)')
assert_equal(parse(Read, 'read ( 10 ) a '),'READ (10) a')
assert_equal(parse(Read, 'read ( 10 ) a , b'),'READ (10) a, b')
@@ -98,44 +98,44 @@ class TestStatements(NumpyTestCase):
assert_equal(parse(Read, 'read * , a , b'),'READ *, a, b')
assert_equal(parse(Read, 'read ( unit =10 )'),'READ (UNIT = 10)')
- def check_write(self):
+ def test_write(self):
assert_equal(parse(Write, 'write ( 10 )'),'WRITE (10)')
assert_equal(parse(Write, 'write ( 10 , a )'),'WRITE (10, a)')
assert_equal(parse(Write, 'write ( 10 ) b'),'WRITE (10) b')
assert_equal(parse(Write, 'write ( 10 ) a(1) , b+2'),'WRITE (10) a(1), b+2')
assert_equal(parse(Write, 'write ( unit=10 )'),'WRITE (UNIT = 10)')
- def check_flush(self):
+ def test_flush(self):
assert_equal(parse(Flush, 'flush 10'),'FLUSH (10)')
assert_equal(parse(Flush, 'flush (10)'),'FLUSH (10)')
assert_equal(parse(Flush, 'flush (UNIT = 10)'),'FLUSH (UNIT = 10)')
assert_equal(parse(Flush, 'flush (10, err= 23)'),'FLUSH (10, ERR = 23)')
- def check_wait(self):
+ def test_wait(self):
assert_equal(parse(Wait, 'wait(10)'),'WAIT (10)')
assert_equal(parse(Wait, 'wait(10,err=129)'),'WAIT (10, ERR = 129)')
- def check_contains(self):
+ def test_contains(self):
assert_equal(parse(Contains, 'contains'),'CONTAINS')
- def check_allocate(self):
+ def test_allocate(self):
assert_equal(parse(Allocate, 'allocate (a)'), 'ALLOCATE (a)')
assert_equal(parse(Allocate, \
'allocate (a, stat=b)'), 'ALLOCATE (a, STAT = b)')
assert_equal(parse(Allocate, 'allocate (a,b(:1))'), 'ALLOCATE (a, b(:1))')
assert_equal(parse(Allocate, \
'allocate (real(8)::a)'), 'ALLOCATE (REAL(KIND=8) :: a)')
- def check_deallocate(self):
+ def test_deallocate(self):
assert_equal(parse(Deallocate, 'deallocate (a)'), 'DEALLOCATE (a)')
assert_equal(parse(Deallocate, 'deallocate (a, stat=b)'), 'DEALLOCATE (a, STAT = b)')
- def check_moduleprocedure(self):
+ def test_moduleprocedure(self):
assert_equal(parse(ModuleProcedure,\
'ModuleProcedure a'), 'MODULE PROCEDURE a')
assert_equal(parse(ModuleProcedure,\
'module procedure a , b'), 'MODULE PROCEDURE a, b')
- def check_access(self):
+ def test_access(self):
assert_equal(parse(Public,'Public'),'PUBLIC')
assert_equal(parse(Public,'public a'),'PUBLIC a')
assert_equal(parse(Public,'public :: a'),'PUBLIC a')
@@ -144,45 +144,45 @@ class TestStatements(NumpyTestCase):
assert_equal(parse(Private,'private'),'PRIVATE')
assert_equal(parse(Private,'private :: a'),'PRIVATE a')
- def check_close(self):
+ def test_close(self):
assert_equal(parse(Close,'close (12)'),'CLOSE (12)')
assert_equal(parse(Close,'close (12, err=99)'),'CLOSE (12, ERR = 99)')
assert_equal(parse(Close,'close (12, status = a(1,2))'),'CLOSE (12, STATUS = a(1,2))')
- def check_cycle(self):
+ def test_cycle(self):
assert_equal(parse(Cycle,'cycle'),'CYCLE')
assert_equal(parse(Cycle,'cycle ab'),'CYCLE ab')
- def check_rewind(self):
+ def test_rewind(self):
assert_equal(parse(Rewind,'rewind 1'),'REWIND (1)')
assert_equal(parse(Rewind,'rewind (1)'),'REWIND (1)')
assert_equal(parse(Rewind,'rewind (1, err = 123)'),'REWIND (1, ERR = 123)')
- def check_backspace(self):
+ def test_backspace(self):
assert_equal(parse(Backspace,'backspace 1'),'BACKSPACE (1)')
assert_equal(parse(Backspace,'backspace (1)'),'BACKSPACE (1)')
assert_equal(parse(Backspace,'backspace (1, err = 123)'),'BACKSPACE (1, ERR = 123)')
- def check_endfile(self):
+ def test_endfile(self):
assert_equal(parse(Endfile,'endfile 1'),'ENDFILE (1)')
assert_equal(parse(Endfile,'endfile (1)'),'ENDFILE (1)')
assert_equal(parse(Endfile,'endfile (1, err = 123)'),'ENDFILE (1, ERR = 123)')
- def check_open(self):
+ def test_open(self):
assert_equal(parse(Open,'open (1)'),'OPEN (1)')
assert_equal(parse(Open,'open (1, err = 123)'),'OPEN (1, ERR = 123)')
- def check_format(self):
+ def test_format(self):
assert_equal(parse(Format,'1: format ()'),'1: FORMAT ()')
assert_equal(parse(Format,'199 format (1)'),'199: FORMAT (1)')
assert_equal(parse(Format,'2 format (1 , SS)'),'2: FORMAT (1, ss)')
- def check_save(self):
+ def test_save(self):
assert_equal(parse(Save,'save'), 'SAVE')
assert_equal(parse(Save,'save :: a'), 'SAVE a')
assert_equal(parse(Save,'save a,b'), 'SAVE a, b')
- def check_data(self):
+ def test_data(self):
assert_equal(parse(Data,'data a /b/'), 'DATA a / b /')
assert_equal(parse(Data,'data a , c /b/'), 'DATA a, c / b /')
assert_equal(parse(Data,'data a /b ,c/'), 'DATA a / b, c /')
@@ -190,11 +190,11 @@ class TestStatements(NumpyTestCase):
assert_equal(parse(Data,'data a(1,2) /b/'), 'DATA a(1,2) / b /')
assert_equal(parse(Data,'data a /b, c(1)/'), 'DATA a / b, c(1) /')
- def check_nullify(self):
+ def test_nullify(self):
assert_equal(parse(Nullify,'nullify(a)'),'NULLIFY (a)')
assert_equal(parse(Nullify,'nullify(a ,b)'),'NULLIFY (a, b)')
- def check_use(self):
+ def test_use(self):
assert_equal(parse(Use, 'use a'), 'USE a')
assert_equal(parse(Use, 'use :: a'), 'USE a')
assert_equal(parse(Use, 'use, intrinsic:: a'), 'USE INTRINSIC :: a')
@@ -205,79 +205,79 @@ class TestStatements(NumpyTestCase):
'use :: a , only: operator(+) , b'),\
'USE a, ONLY: operator(+), b')
- def check_exit(self):
+ def test_exit(self):
assert_equal(parse(Exit,'exit'),'EXIT')
assert_equal(parse(Exit,'exit ab'),'EXIT ab')
- def check_parameter(self):
+ def test_parameter(self):
assert_equal(parse(Parameter,'parameter (a = b(1,2))'),
'PARAMETER (a = b(1,2))')
assert_equal(parse(Parameter,'parameter (a = b(1,2) , b=1)'),
'PARAMETER (a = b(1,2), b=1)')
- def check_equivalence(self):
+ def test_equivalence(self):
assert_equal(parse(Equivalence,'equivalence (a , b)'),'EQUIVALENCE (a, b)')
assert_equal(parse(Equivalence,'equivalence (a , b) , ( c, d(1) , g )'),
'EQUIVALENCE (a, b), (c, d(1), g)')
- def check_dimension(self):
+ def test_dimension(self):
assert_equal(parse(Dimension,'dimension a(b)'),'DIMENSION a(b)')
assert_equal(parse(Dimension,'dimension::a(b)'),'DIMENSION a(b)')
assert_equal(parse(Dimension,'dimension a(b) , c(d)'),'DIMENSION a(b), c(d)')
assert_equal(parse(Dimension,'dimension a(b,c)'),'DIMENSION a(b,c)')
- def check_target(self):
+ def test_target(self):
assert_equal(parse(Target,'target a(b)'),'TARGET a(b)')
assert_equal(parse(Target,'target::a(b)'),'TARGET a(b)')
assert_equal(parse(Target,'target a(b) , c(d)'),'TARGET a(b), c(d)')
assert_equal(parse(Target,'target a(b,c)'),'TARGET a(b,c)')
- def check_pointer(self):
+ def test_pointer(self):
assert_equal(parse(Pointer,'pointer a=b'),'POINTER a=b')
assert_equal(parse(Pointer,'pointer :: a=b'),'POINTER a=b')
assert_equal(parse(Pointer,'pointer a=b, c=d(1,2)'),'POINTER a=b, c=d(1,2)')
- def check_protected(self):
+ def test_protected(self):
assert_equal(parse(Protected,'protected a'),'PROTECTED a')
assert_equal(parse(Protected,'protected::a'),'PROTECTED a')
assert_equal(parse(Protected,'protected a , b'),'PROTECTED a, b')
- def check_volatile(self):
+ def test_volatile(self):
assert_equal(parse(Volatile,'volatile a'),'VOLATILE a')
assert_equal(parse(Volatile,'volatile::a'),'VOLATILE a')
assert_equal(parse(Volatile,'volatile a , b'),'VOLATILE a, b')
- def check_value(self):
+ def test_value(self):
assert_equal(parse(Value,'value a'),'VALUE a')
assert_equal(parse(Value,'value::a'),'VALUE a')
assert_equal(parse(Value,'value a , b'),'VALUE a, b')
- def check_arithmeticif(self):
+ def test_arithmeticif(self):
assert_equal(parse(ArithmeticIf,'if (a) 1,2,3'),'IF (a) 1, 2, 3')
assert_equal(parse(ArithmeticIf,'if (a(1)) 1,2,3'),'IF (a(1)) 1, 2, 3')
assert_equal(parse(ArithmeticIf,'if (a(1,2)) 1,2,3'),'IF (a(1,2)) 1, 2, 3')
- def check_intrinsic(self):
+ def test_intrinsic(self):
assert_equal(parse(Intrinsic,'intrinsic a'),'INTRINSIC a')
assert_equal(parse(Intrinsic,'intrinsic::a'),'INTRINSIC a')
assert_equal(parse(Intrinsic,'intrinsic a , b'),'INTRINSIC a, b')
- def check_inquire(self):
+ def test_inquire(self):
assert_equal(parse(Inquire, 'inquire (1)'),'INQUIRE (1)')
assert_equal(parse(Inquire, 'inquire (1, err=123)'),'INQUIRE (1, ERR = 123)')
assert_equal(parse(Inquire, 'inquire (iolength=a) b'),'INQUIRE (IOLENGTH = a) b')
assert_equal(parse(Inquire, 'inquire (iolength=a) b ,c(1,2)'),
'INQUIRE (IOLENGTH = a) b, c(1,2)')
- def check_sequence(self):
+ def test_sequence(self):
assert_equal(parse(Sequence, 'sequence'),'SEQUENCE')
- def check_external(self):
+ def test_external(self):
assert_equal(parse(External,'external a'),'EXTERNAL a')
assert_equal(parse(External,'external::a'),'EXTERNAL a')
assert_equal(parse(External,'external a , b'),'EXTERNAL a, b')
- def check_common(self):
+ def test_common(self):
assert_equal(parse(Common, 'common a'),'COMMON a')
assert_equal(parse(Common, 'common a , b'),'COMMON a, b')
assert_equal(parse(Common, 'common a , b(1,2)'),'COMMON a, b(1,2)')
@@ -289,18 +289,18 @@ class TestStatements(NumpyTestCase):
assert_equal(parse(Common, 'common / name/ a, /foo/ c(1) ,d'),
'COMMON / name / a / foo / c(1), d')
- def check_optional(self):
+ def test_optional(self):
assert_equal(parse(Optional,'optional a'),'OPTIONAL a')
assert_equal(parse(Optional,'optional::a'),'OPTIONAL a')
assert_equal(parse(Optional,'optional a , b'),'OPTIONAL a, b')
- def check_intent(self):
+ def test_intent(self):
assert_equal(parse(Intent,'intent (in) a'),'INTENT (IN) a')
assert_equal(parse(Intent,'intent(in)::a'),'INTENT (IN) a')
assert_equal(parse(Intent,'intent(in) a , b'),'INTENT (IN) a, b')
assert_equal(parse(Intent,'intent (in, out) a'),'INTENT (IN, OUT) a')
- def check_entry(self):
+ def test_entry(self):
assert_equal(parse(Entry,'entry a'), 'ENTRY a')
assert_equal(parse(Entry,'entry a()'), 'ENTRY a')
assert_equal(parse(Entry,'entry a(b)'), 'ENTRY a (b)')
@@ -315,13 +315,13 @@ class TestStatements(NumpyTestCase):
assert_equal(parse(Entry,'entry a(b,*) result (g)'),
'ENTRY a (b, *) RESULT (g)')
- def check_import(self):
+ def test_import(self):
assert_equal(parse(Import,'import'),'IMPORT')
assert_equal(parse(Import,'import a'),'IMPORT a')
assert_equal(parse(Import,'import::a'),'IMPORT a')
assert_equal(parse(Import,'import a , b'),'IMPORT a, b')
- def check_forall(self):
+ def test_forall(self):
assert_equal(parse(ForallStmt,'forall (i = 1:n(k,:) : 2) a(i) = i*i*b(i)'),
'FORALL (i = 1 : n(k,:) : 2) a(i) = i*i*b(i)')
assert_equal(parse(ForallStmt,'forall (i=1:n,j=2:3) a(i) = b(i,i)'),
@@ -329,7 +329,7 @@ class TestStatements(NumpyTestCase):
assert_equal(parse(ForallStmt,'forall (i=1:n,j=2:3, 1+a(1,2)) a(i) = b(i,i)'),
'FORALL (i = 1 : n, j = 2 : 3, 1+a(1,2)) a(i) = b(i,i)')
- def check_specificbinding(self):
+ def test_specificbinding(self):
assert_equal(parse(SpecificBinding,'procedure a'),'PROCEDURE a')
assert_equal(parse(SpecificBinding,'procedure :: a'),'PROCEDURE a')
assert_equal(parse(SpecificBinding,'procedure , NOPASS :: a'),'PROCEDURE , NOPASS :: a')
@@ -343,29 +343,29 @@ class TestStatements(NumpyTestCase):
assert_equal(parse(SpecificBinding,'procedure(n),pass :: a =>c'),
'PROCEDURE (n) , PASS :: a => c')
- def check_genericbinding(self):
+ def test_genericbinding(self):
assert_equal(parse(GenericBinding,'generic :: a=>b'),'GENERIC :: a => b')
assert_equal(parse(GenericBinding,'generic, public :: a=>b'),'GENERIC, PUBLIC :: a => b')
assert_equal(parse(GenericBinding,'generic, public :: a(1,2)=>b ,c'),
'GENERIC, PUBLIC :: a(1,2) => b, c')
- def check_finalbinding(self):
+ def test_finalbinding(self):
assert_equal(parse(FinalBinding,'final a'),'FINAL a')
assert_equal(parse(FinalBinding,'final::a'),'FINAL a')
assert_equal(parse(FinalBinding,'final a , b'),'FINAL a, b')
- def check_allocatable(self):
+ def test_allocatable(self):
assert_equal(parse(Allocatable,'allocatable a'),'ALLOCATABLE a')
assert_equal(parse(Allocatable,'allocatable :: a'),'ALLOCATABLE a')
assert_equal(parse(Allocatable,'allocatable a (1,2)'),'ALLOCATABLE a (1,2)')
assert_equal(parse(Allocatable,'allocatable a (1,2) ,b'),'ALLOCATABLE a (1,2), b')
- def check_asynchronous(self):
+ def test_asynchronous(self):
assert_equal(parse(Asynchronous,'asynchronous a'),'ASYNCHRONOUS a')
assert_equal(parse(Asynchronous,'asynchronous::a'),'ASYNCHRONOUS a')
assert_equal(parse(Asynchronous,'asynchronous a , b'),'ASYNCHRONOUS a, b')
- def check_bind(self):
+ def test_bind(self):
assert_equal(parse(Bind,'bind(c) a'),'BIND (C) a')
assert_equal(parse(Bind,'bind(c) :: a'),'BIND (C) a')
assert_equal(parse(Bind,'bind(c) a ,b'),'BIND (C) a, b')
@@ -373,13 +373,13 @@ class TestStatements(NumpyTestCase):
assert_equal(parse(Bind,'bind(c) /a/ ,b'),'BIND (C) / a /, b')
assert_equal(parse(Bind,'bind(c,name="hey") a'),'BIND (C, NAME = "hey") a')
- def check_else(self):
+ def test_else(self):
assert_equal(parse(Else,'else'),'ELSE')
assert_equal(parse(ElseIf,'else if (a) then'),'ELSE IF (a) THEN')
assert_equal(parse(ElseIf,'else if (a.eq.b(1,2)) then'),
'ELSE IF (a.eq.b(1,2)) THEN')
- def check_case(self):
+ def test_case(self):
assert_equal(parse(Case,'case (1)'),'CASE ( 1 )')
assert_equal(parse(Case,'case (1:)'),'CASE ( 1 : )')
assert_equal(parse(Case,'case (:1)'),'CASE ( : 1 )')
@@ -391,56 +391,56 @@ class TestStatements(NumpyTestCase):
assert_equal(parse(Case,'case (a(1,:):)'),'CASE ( a(1,:) : )')
assert_equal(parse(Case,'case default'),'CASE DEFAULT')
- def check_where(self):
+ def test_where(self):
assert_equal(parse(WhereStmt,'where (1) a=1'),'WHERE ( 1 ) a = 1')
assert_equal(parse(WhereStmt,'where (a(1,2)) a=1'),'WHERE ( a(1,2) ) a = 1')
- def check_elsewhere(self):
+ def test_elsewhere(self):
assert_equal(parse(ElseWhere,'else where'),'ELSE WHERE')
assert_equal(parse(ElseWhere,'elsewhere (1)'),'ELSE WHERE ( 1 )')
assert_equal(parse(ElseWhere,'elsewhere(a(1,2))'),'ELSE WHERE ( a(1,2) )')
- def check_enumerator(self):
+ def test_enumerator(self):
assert_equal(parse(Enumerator,'enumerator a'), 'ENUMERATOR a')
assert_equal(parse(Enumerator,'enumerator:: a'), 'ENUMERATOR a')
assert_equal(parse(Enumerator,'enumerator a,b'), 'ENUMERATOR a, b')
assert_equal(parse(Enumerator,'enumerator a=1'), 'ENUMERATOR a=1')
assert_equal(parse(Enumerator,'enumerator a=1 , b=c(1,2)'), 'ENUMERATOR a=1, b=c(1,2)')
- def check_fortranname(self):
+ def test_fortranname(self):
assert_equal(parse(FortranName,'fortranname a'),'FORTRANNAME a')
- def check_threadsafe(self):
+ def test_threadsafe(self):
assert_equal(parse(Threadsafe,'threadsafe'),'THREADSAFE')
- def check_depend(self):
+ def test_depend(self):
assert_equal(parse(Depend,'depend( a) b'), 'DEPEND ( a ) b')
assert_equal(parse(Depend,'depend( a) ::b'), 'DEPEND ( a ) b')
assert_equal(parse(Depend,'depend( a,c) b,e'), 'DEPEND ( a, c ) b, e')
- def check_check(self):
+ def test_check(self):
assert_equal(parse(Check,'check(1) a'), 'CHECK ( 1 ) a')
assert_equal(parse(Check,'check(1) :: a'), 'CHECK ( 1 ) a')
assert_equal(parse(Check,'check(b(1,2)) a'), 'CHECK ( b(1,2) ) a')
assert_equal(parse(Check,'check(a>1) :: a'), 'CHECK ( a>1 ) a')
- def check_callstatement(self):
+ def test_callstatement(self):
assert_equal(parse(CallStatement,'callstatement (*func)()',isstrict=1),
'CALLSTATEMENT (*func)()')
assert_equal(parse(CallStatement,'callstatement i=1;(*func)()',isstrict=1),
'CALLSTATEMENT i=1;(*func)()')
- def check_callprotoargument(self):
+ def test_callprotoargument(self):
assert_equal(parse(CallProtoArgument,'callprotoargument int(*), double'),
'CALLPROTOARGUMENT int(*), double')
- def check_pause(self):
+ def test_pause(self):
assert_equal(parse(Pause,'pause'),'PAUSE')
assert_equal(parse(Pause,'pause 1'),'PAUSE 1')
assert_equal(parse(Pause,'pause "hey"'),'PAUSE "hey"')
assert_equal(parse(Pause,'pause "hey pa"'),'PAUSE "hey pa"')
- def check_integer(self):
+ def test_integer(self):
assert_equal(parse(Integer,'integer'),'INTEGER')
assert_equal(parse(Integer,'integer*4'),'INTEGER*4')
assert_equal(parse(Integer,'integer*4 a'),'INTEGER*4 a')
@@ -460,7 +460,7 @@ class TestStatements(NumpyTestCase):
assert_equal(parse(Integer,'integer(kind=2+2)'),'INTEGER(KIND=2+2)')
assert_equal(parse(Integer,'integer(kind=f(4,5))'),'INTEGER(KIND=f(4,5))')
- def check_character(self):
+ def test_character(self):
assert_equal(parse(Character,'character'),'CHARACTER')
assert_equal(parse(Character,'character*2'),'CHARACTER(LEN=2)')
assert_equal(parse(Character,'character**'),'CHARACTER(LEN=*)')
@@ -482,7 +482,7 @@ class TestStatements(NumpyTestCase):
assert_equal(parse(Character,'character(len=3,kind=fA(1,2))'),
'CHARACTER(LEN=3, KIND=fa(1,2))')
- def check_implicit(self):
+ def test_implicit(self):
assert_equal(parse(Implicit,'implicit none'),'IMPLICIT NONE')
assert_equal(parse(Implicit,'implicit'),'IMPLICIT NONE')
assert_equal(parse(Implicit,'implicit integer (i-m)'),
@@ -492,5 +492,6 @@ class TestStatements(NumpyTestCase):
assert_equal(parse(Implicit,'implicit integer (i-m), real (z)'),
'IMPLICIT INTEGER ( i-m ), REAL ( z )')
+
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/f2py/lib/tests/test_derived_scalar.py b/numpy/f2py/lib/tests/test_derived_scalar.py
index b5f24dea5..76b54ae51 100644
--- a/numpy/f2py/lib/tests/test_derived_scalar.py
+++ b/numpy/f2py/lib/tests/test_derived_scalar.py
@@ -42,9 +42,9 @@ m, = compile(fortran_code, 'test_derived_scalar_ext')
from numpy import *
-class TestM(NumpyTestCase):
+class TestM(TestCase):
- def check_foo_simple(self, level=1):
+ def test_foo_simple(self, level=1):
a = m.myt(2)
assert_equal(a.flag,2)
assert isinstance(a,m.myt),`a`
@@ -59,7 +59,7 @@ class TestM(NumpyTestCase):
#s = m.foo((5,))
- def check_foo2_simple(self, level=1):
+ def test_foo2_simple(self, level=1):
a = m.myt(2)
assert_equal(a.flag,2)
assert isinstance(a,m.myt),`a`
@@ -71,4 +71,4 @@ class TestM(NumpyTestCase):
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/f2py/lib/tests/test_module_module.py b/numpy/f2py/lib/tests/test_module_module.py
index d56cb45a6..53348b5d8 100644
--- a/numpy/f2py/lib/tests/test_module_module.py
+++ b/numpy/f2py/lib/tests/test_module_module.py
@@ -51,11 +51,11 @@ m,m2 = compile(fortran_code, modulenames=['test_module_module_ext',
from numpy import *
-class TestM(NumpyTestCase):
+class TestM(TestCase):
- def check_foo_simple(self, level=1):
+ def test_foo_simple(self, level=1):
foo = m.foo
foo()
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/f2py/lib/tests/test_module_scalar.py b/numpy/f2py/lib/tests/test_module_scalar.py
index 1ac4455be..684fab1b2 100644
--- a/numpy/f2py/lib/tests/test_module_scalar.py
+++ b/numpy/f2py/lib/tests/test_module_scalar.py
@@ -40,19 +40,19 @@ m, = compile(fortran_code, modulenames = ['test_module_scalar_ext'])
from numpy import *
-class TestM(NumpyTestCase):
+class TestM(TestCase):
- def check_foo_simple(self, level=1):
+ def test_foo_simple(self, level=1):
foo = m.foo
r = foo(2)
assert isinstance(r,int32),`type(r)`
assert_equal(r,3)
- def check_foo2_simple(self, level=1):
+ def test_foo2_simple(self, level=1):
foo2 = m.foo2
r = foo2(2)
assert isinstance(r,int32),`type(r)`
assert_equal(r,4)
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/f2py/lib/tests/test_scalar_function_in.py b/numpy/f2py/lib/tests/test_scalar_function_in.py
index 24387def5..f2497d065 100644
--- a/numpy/f2py/lib/tests/test_scalar_function_in.py
+++ b/numpy/f2py/lib/tests/test_scalar_function_in.py
@@ -107,9 +107,9 @@ m, = compile(fortran_code, 'test_scalar_function_in_ext')
from numpy import *
-class TestM(NumpyTestCase):
+class TestM(TestCase):
- def check_foo_integer1(self, level=1):
+ def test_foo_integer1(self, level=1):
i = int8(2)
e = int8(3)
func = m.fooint1
@@ -144,7 +144,7 @@ class TestM(NumpyTestCase):
self.assertRaises(TypeError,lambda :func([2,1]))
self.assertRaises(TypeError,lambda :func({}))
- def check_foo_integer2(self, level=1):
+ def test_foo_integer2(self, level=1):
i = int16(2)
e = int16(3)
func = m.fooint2
@@ -179,7 +179,7 @@ class TestM(NumpyTestCase):
self.assertRaises(TypeError,lambda :func([2,1]))
self.assertRaises(TypeError,lambda :func({}))
- def check_foo_integer4(self, level=1):
+ def test_foo_integer4(self, level=1):
i = int32(2)
e = int32(3)
func = m.fooint4
@@ -214,7 +214,7 @@ class TestM(NumpyTestCase):
self.assertRaises(TypeError,lambda :func([2,1]))
self.assertRaises(TypeError,lambda :func({}))
- def check_foo_integer8(self, level=1):
+ def test_foo_integer8(self, level=1):
i = int64(2)
e = int64(3)
func = m.fooint8
@@ -249,7 +249,7 @@ class TestM(NumpyTestCase):
self.assertRaises(TypeError,lambda :func([2,1]))
self.assertRaises(TypeError,lambda :func({}))
- def check_foo_real4(self, level=1):
+ def test_foo_real4(self, level=1):
i = float32(2)
e = float32(3)
func = m.foofloat4
@@ -283,7 +283,7 @@ class TestM(NumpyTestCase):
self.assertRaises(TypeError,lambda :func([2,1]))
self.assertRaises(TypeError,lambda :func({}))
- def check_foo_real8(self, level=1):
+ def test_foo_real8(self, level=1):
i = float64(2)
e = float64(3)
func = m.foofloat8
@@ -317,7 +317,7 @@ class TestM(NumpyTestCase):
self.assertRaises(TypeError,lambda :func([2,1]))
self.assertRaises(TypeError,lambda :func({}))
- def check_foo_complex8(self, level=1):
+ def test_foo_complex8(self, level=1):
i = complex64(2)
e = complex64(3)
func = m.foocomplex8
@@ -358,7 +358,7 @@ class TestM(NumpyTestCase):
self.assertRaises(TypeError,lambda :func([2,1,3]))
self.assertRaises(TypeError,lambda :func({}))
- def check_foo_complex16(self, level=1):
+ def test_foo_complex16(self, level=1):
i = complex128(2)
e = complex128(3)
func = m.foocomplex16
@@ -399,7 +399,7 @@ class TestM(NumpyTestCase):
self.assertRaises(TypeError,lambda :func([2,1,3]))
self.assertRaises(TypeError,lambda :func({}))
- def check_foo_bool1(self, level=1):
+ def test_foo_bool1(self, level=1):
i = bool8(True)
e = bool8(False)
func = m.foobool1
@@ -419,7 +419,7 @@ class TestM(NumpyTestCase):
assert isinstance(r,bool8),`type(r)`
assert_equal(r,not e)
- def check_foo_bool2(self, level=1):
+ def test_foo_bool2(self, level=1):
i = bool8(True)
e = bool8(False)
func = m.foobool2
@@ -439,7 +439,7 @@ class TestM(NumpyTestCase):
assert isinstance(r,bool8),`type(r)`
assert_equal(r,not e)
- def check_foo_bool4(self, level=1):
+ def test_foo_bool4(self, level=1):
i = bool8(True)
e = bool8(False)
func = m.foobool4
@@ -459,7 +459,7 @@ class TestM(NumpyTestCase):
assert isinstance(r,bool8),`type(r)`
assert_equal(r,not e)
- def check_foo_bool8(self, level=1):
+ def test_foo_bool8(self, level=1):
i = bool8(True)
e = bool8(False)
func = m.foobool8
@@ -479,7 +479,7 @@ class TestM(NumpyTestCase):
assert isinstance(r,bool8),`type(r)`
assert_equal(r,not e)
- def check_foo_string1(self, level=1):
+ def test_foo_string1(self, level=1):
i = string0('a')
e = string0('1')
func = m.foostring1
@@ -497,7 +497,7 @@ class TestM(NumpyTestCase):
assert isinstance(r,string0),`type(r)`
assert_equal(r,e)
- def check_foo_string5(self, level=1):
+ def test_foo_string5(self, level=1):
i = string0('abcde')
e = string0('12cde')
func = m.foostring5
@@ -528,5 +528,6 @@ class TestM(NumpyTestCase):
r = func('')
assert_equal(r,'')
+
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/f2py/lib/tests/test_scalar_in_out.py b/numpy/f2py/lib/tests/test_scalar_in_out.py
index dc6007b8e..2f8ccceab 100644
--- a/numpy/f2py/lib/tests/test_scalar_in_out.py
+++ b/numpy/f2py/lib/tests/test_scalar_in_out.py
@@ -104,9 +104,9 @@ m, = compile(fortran_code, 'test_scalar_in_out_ext', source_ext = '.f')
from numpy import *
-class TestM(NumpyTestCase):
+class TestM(TestCase):
- def check_foo_integer1(self, level=1):
+ def test_foo_integer1(self, level=1):
i = int8(2)
e = int8(3)
func = m.fooint1
@@ -141,7 +141,7 @@ class TestM(NumpyTestCase):
self.assertRaises(TypeError,lambda :func([2,1]))
self.assertRaises(TypeError,lambda :func({}))
- def check_foo_integer2(self, level=1):
+ def test_foo_integer2(self, level=1):
i = int16(2)
e = int16(3)
func = m.fooint2
@@ -176,7 +176,7 @@ class TestM(NumpyTestCase):
self.assertRaises(TypeError,lambda :func([2,1]))
self.assertRaises(TypeError,lambda :func({}))
- def check_foo_integer4(self, level=1):
+ def test_foo_integer4(self, level=1):
i = int32(2)
e = int32(3)
func = m.fooint4
@@ -211,7 +211,7 @@ class TestM(NumpyTestCase):
self.assertRaises(TypeError,lambda :func([2,1]))
self.assertRaises(TypeError,lambda :func({}))
- def check_foo_integer8(self, level=1):
+ def test_foo_integer8(self, level=1):
i = int64(2)
e = int64(3)
func = m.fooint8
@@ -246,7 +246,7 @@ class TestM(NumpyTestCase):
self.assertRaises(TypeError,lambda :func([2,1]))
self.assertRaises(TypeError,lambda :func({}))
- def check_foo_real4(self, level=1):
+ def test_foo_real4(self, level=1):
i = float32(2)
e = float32(3)
func = m.foofloat4
@@ -280,7 +280,7 @@ class TestM(NumpyTestCase):
self.assertRaises(TypeError,lambda :func([2,1]))
self.assertRaises(TypeError,lambda :func({}))
- def check_foo_real8(self, level=1):
+ def test_foo_real8(self, level=1):
i = float64(2)
e = float64(3)
func = m.foofloat8
@@ -314,7 +314,7 @@ class TestM(NumpyTestCase):
self.assertRaises(TypeError,lambda :func([2,1]))
self.assertRaises(TypeError,lambda :func({}))
- def check_foo_complex8(self, level=1):
+ def test_foo_complex8(self, level=1):
i = complex64(2)
e = complex64(3)
func = m.foocomplex8
@@ -355,7 +355,7 @@ class TestM(NumpyTestCase):
self.assertRaises(TypeError,lambda :func([2,1,3]))
self.assertRaises(TypeError,lambda :func({}))
- def check_foo_complex16(self, level=1):
+ def test_foo_complex16(self, level=1):
i = complex128(2)
e = complex128(3)
func = m.foocomplex16
@@ -396,7 +396,7 @@ class TestM(NumpyTestCase):
self.assertRaises(TypeError,lambda :func([2,1,3]))
self.assertRaises(TypeError,lambda :func({}))
- def check_foo_bool1(self, level=1):
+ def test_foo_bool1(self, level=1):
i = bool8(True)
e = bool8(False)
func = m.foobool1
@@ -416,7 +416,7 @@ class TestM(NumpyTestCase):
assert isinstance(r,bool8),`type(r)`
assert_equal(r,not e)
- def check_foo_bool2(self, level=1):
+ def test_foo_bool2(self, level=1):
i = bool8(True)
e = bool8(False)
func = m.foobool2
@@ -436,7 +436,7 @@ class TestM(NumpyTestCase):
assert isinstance(r,bool8),`type(r)`
assert_equal(r,not e)
- def check_foo_bool4(self, level=1):
+ def test_foo_bool4(self, level=1):
i = bool8(True)
e = bool8(False)
func = m.foobool4
@@ -456,7 +456,7 @@ class TestM(NumpyTestCase):
assert isinstance(r,bool8),`type(r)`
assert_equal(r,not e)
- def check_foo_bool8(self, level=1):
+ def test_foo_bool8(self, level=1):
i = bool8(True)
e = bool8(False)
func = m.foobool8
@@ -476,7 +476,7 @@ class TestM(NumpyTestCase):
assert isinstance(r,bool8),`type(r)`
assert_equal(r,not e)
- def check_foo_string1(self, level=1):
+ def test_foo_string1(self, level=1):
i = string0('a')
e = string0('1')
func = m.foostring1
@@ -494,7 +494,7 @@ class TestM(NumpyTestCase):
assert isinstance(r,string0),`type(r)`
assert_equal(r,e)
- def check_foo_string5(self, level=1):
+ def test_foo_string5(self, level=1):
i = string0('abcde')
e = string0('12cde')
func = m.foostring5
@@ -516,7 +516,7 @@ class TestM(NumpyTestCase):
assert isinstance(r,string0),`type(r)`
assert_equal(r,'12] ')
- def check_foo_string0(self, level=1):
+ def test_foo_string0(self, level=1):
i = string0('abcde')
e = string0('12cde')
func = m.foostringstar
@@ -525,5 +525,6 @@ class TestM(NumpyTestCase):
r = func('')
assert_equal(r,'')
+
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/f2py/tests/array_from_pyobj/tests/test_array_from_pyobj.py b/numpy/f2py/tests/array_from_pyobj/tests/test_array_from_pyobj.py
index e1d4a47a6..67df2f09c 100644
--- a/numpy/f2py/tests/array_from_pyobj/tests/test_array_from_pyobj.py
+++ b/numpy/f2py/tests/array_from_pyobj/tests/test_array_from_pyobj.py
@@ -8,7 +8,7 @@ from numpy.core.multiarray import typeinfo
set_package_path()
from array_from_pyobj import wrap
-del sys.path[0]
+restore_path()
def flags_info(arr):
flags = wrap.array_attrs(arr)[6]
@@ -240,7 +240,7 @@ class Array:
##################################################
class test_intent(unittest.TestCase):
- def check_in_out(self):
+ def test_in_out(self):
assert_equal(str(intent.in_.out),'intent(in,out)')
assert intent.in_.c.is_intent('c')
assert not intent.in_.c.is_intent_exact('c')
@@ -251,11 +251,11 @@ class test_intent(unittest.TestCase):
class _test_shared_memory:
num2seq = [1,2]
num23seq = [[1,2,3],[4,5,6]]
- def check_in_from_2seq(self):
+ def test_in_from_2seq(self):
a = self.array([2],intent.in_,self.num2seq)
assert not a.has_shared_memory()
- def check_in_from_2casttype(self):
+ def test_in_from_2casttype(self):
for t in self.type.cast_types():
obj = array(self.num2seq,dtype=t.dtype)
a = self.array([len(self.num2seq)],intent.in_,obj)
@@ -264,7 +264,7 @@ class _test_shared_memory:
else:
assert not a.has_shared_memory(),`t.dtype`
- def check_inout_2seq(self):
+ def test_inout_2seq(self):
obj = array(self.num2seq,dtype=self.type.dtype)
a = self.array([len(self.num2seq)],intent.inout,obj)
assert a.has_shared_memory()
@@ -277,7 +277,7 @@ class _test_shared_memory:
else:
raise SystemError,'intent(inout) should have failed on sequence'
- def check_f_inout_23seq(self):
+ def test_f_inout_23seq(self):
obj = array(self.num23seq,dtype=self.type.dtype,fortran=1)
shape = (len(self.num23seq),len(self.num23seq[0]))
a = self.array(shape,intent.in_.inout,obj)
@@ -293,31 +293,31 @@ class _test_shared_memory:
else:
raise SystemError,'intent(inout) should have failed on improper array'
- def check_c_inout_23seq(self):
+ def test_c_inout_23seq(self):
obj = array(self.num23seq,dtype=self.type.dtype)
shape = (len(self.num23seq),len(self.num23seq[0]))
a = self.array(shape,intent.in_.c.inout,obj)
assert a.has_shared_memory()
- def check_in_copy_from_2casttype(self):
+ def test_in_copy_from_2casttype(self):
for t in self.type.cast_types():
obj = array(self.num2seq,dtype=t.dtype)
a = self.array([len(self.num2seq)],intent.in_.copy,obj)
assert not a.has_shared_memory(),`t.dtype`
- def check_c_in_from_23seq(self):
+ def test_c_in_from_23seq(self):
a = self.array([len(self.num23seq),len(self.num23seq[0])],
intent.in_,self.num23seq)
assert not a.has_shared_memory()
- def check_in_from_23casttype(self):
+ def test_in_from_23casttype(self):
for t in self.type.cast_types():
obj = array(self.num23seq,dtype=t.dtype)
a = self.array([len(self.num23seq),len(self.num23seq[0])],
intent.in_,obj)
assert not a.has_shared_memory(),`t.dtype`
- def check_f_in_from_23casttype(self):
+ def test_f_in_from_23casttype(self):
for t in self.type.cast_types():
obj = array(self.num23seq,dtype=t.dtype,fortran=1)
a = self.array([len(self.num23seq),len(self.num23seq[0])],
@@ -327,7 +327,7 @@ class _test_shared_memory:
else:
assert not a.has_shared_memory(),`t.dtype`
- def check_c_in_from_23casttype(self):
+ def test_c_in_from_23casttype(self):
for t in self.type.cast_types():
obj = array(self.num23seq,dtype=t.dtype)
a = self.array([len(self.num23seq),len(self.num23seq[0])],
@@ -337,21 +337,21 @@ class _test_shared_memory:
else:
assert not a.has_shared_memory(),`t.dtype`
- def check_f_copy_in_from_23casttype(self):
+ def test_f_copy_in_from_23casttype(self):
for t in self.type.cast_types():
obj = array(self.num23seq,dtype=t.dtype,fortran=1)
a = self.array([len(self.num23seq),len(self.num23seq[0])],
intent.in_.copy,obj)
assert not a.has_shared_memory(),`t.dtype`
- def check_c_copy_in_from_23casttype(self):
+ def test_c_copy_in_from_23casttype(self):
for t in self.type.cast_types():
obj = array(self.num23seq,dtype=t.dtype)
a = self.array([len(self.num23seq),len(self.num23seq[0])],
intent.in_.c.copy,obj)
assert not a.has_shared_memory(),`t.dtype`
- def check_in_cache_from_2casttype(self):
+ def test_in_cache_from_2casttype(self):
for t in self.type.all_types():
if t.elsize != self.type.elsize:
continue
@@ -377,7 +377,7 @@ class _test_shared_memory:
raise
else:
raise SystemError,'intent(cache) should have failed on multisegmented array'
- def check_in_cache_from_2casttype_failure(self):
+ def test_in_cache_from_2casttype_failure(self):
for t in self.type.all_types():
if t.elsize >= self.type.elsize:
continue
@@ -391,7 +391,7 @@ class _test_shared_memory:
else:
raise SystemError,'intent(cache) should have failed on smaller array'
- def check_cache_hidden(self):
+ def test_cache_hidden(self):
shape = (2,)
a = self.array(shape,intent.cache.hide,None)
assert a.arr.shape==shape
@@ -409,7 +409,7 @@ class _test_shared_memory:
else:
raise SystemError,'intent(cache) should have failed on undefined dimensions'
- def check_hidden(self):
+ def test_hidden(self):
shape = (2,)
a = self.array(shape,intent.hide,None)
assert a.arr.shape==shape
@@ -436,7 +436,7 @@ class _test_shared_memory:
else:
raise SystemError,'intent(hide) should have failed on undefined dimensions'
- def check_optional_none(self):
+ def test_optional_none(self):
shape = (2,)
a = self.array(shape,intent.optional,None)
assert a.arr.shape==shape
@@ -454,14 +454,14 @@ class _test_shared_memory:
assert a.arr_equal(a.arr,zeros(shape,dtype=self.type.dtype))
assert not a.arr.flags['FORTRAN'] and a.arr.flags['CONTIGUOUS']
- def check_optional_from_2seq(self):
+ def test_optional_from_2seq(self):
obj = self.num2seq
shape = (len(obj),)
a = self.array(shape,intent.optional,obj)
assert a.arr.shape==shape
assert not a.has_shared_memory()
- def check_optional_from_23seq(self):
+ def test_optional_from_23seq(self):
obj = self.num23seq
shape = (len(obj),len(obj[0]))
a = self.array(shape,intent.optional,obj)
@@ -472,7 +472,7 @@ class _test_shared_memory:
assert a.arr.shape==shape
assert not a.has_shared_memory()
- def check_inplace(self):
+ def test_inplace(self):
obj = array(self.num23seq,dtype=self.type.dtype)
assert not obj.flags['FORTRAN'] and obj.flags['CONTIGUOUS']
shape = obj.shape
@@ -484,7 +484,7 @@ class _test_shared_memory:
assert obj.flags['FORTRAN'] # obj attributes are changed inplace!
assert not obj.flags['CONTIGUOUS']
- def check_inplace_from_casttype(self):
+ def test_inplace_from_casttype(self):
for t in self.type.cast_types():
if t is self.type:
continue
@@ -502,6 +502,7 @@ class _test_shared_memory:
assert not obj.flags['CONTIGUOUS']
assert obj.dtype.type is self.type.dtype # obj type is changed inplace!
+
for t in Type._type_names:
exec '''\
class test_%s_gen(unittest.TestCase,
@@ -512,4 +513,4 @@ class test_%s_gen(unittest.TestCase,
''' % (t,t,t)
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/fft/__init__.py b/numpy/fft/__init__.py
index 0c5a7f2ed..d7f6c3d87 100644
--- a/numpy/fft/__init__.py
+++ b/numpy/fft/__init__.py
@@ -4,6 +4,6 @@ from info import __doc__
from fftpack import *
from helper import *
-def test(level=1, verbosity=1):
- from numpy.testing import NumpyTest
- return NumpyTest().test(level, verbosity)
+from numpy.testing.pkgtester import Tester
+test = Tester().test
+bench = Tester().bench
diff --git a/numpy/fft/tests/test_fftpack.py b/numpy/fft/tests/test_fftpack.py
index d1409bd69..149611e6a 100644
--- a/numpy/fft/tests/test_fftpack.py
+++ b/numpy/fft/tests/test_fftpack.py
@@ -10,15 +10,17 @@ def fft1(x):
phase = np.arange(L).reshape(-1,1) * phase
return np.sum(x*np.exp(phase),axis=1)
-class TestFFTShift(NumpyTestCase):
- def check_fft_n(self):
+class TestFFTShift(TestCase):
+ def test_fft_n(self):
self.failUnlessRaises(ValueError,np.fft.fft,[1,2,3],0)
-class TestFFT1D(NumpyTestCase):
- def check_basic(self):
+
+class TestFFT1D(TestCase):
+ def test_basic(self):
rand = np.random.random
x = rand(30) + 1j*rand(30)
assert_array_almost_equal(fft1(x), np.fft.fft(x))
+
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/fft/tests/test_helper.py b/numpy/fft/tests/test_helper.py
index aaec6530a..42678fb79 100644
--- a/numpy/fft/tests/test_helper.py
+++ b/numpy/fft/tests/test_helper.py
@@ -7,16 +7,15 @@ import sys
from numpy.testing import *
set_package_path()
from numpy.fft import fftshift,ifftshift,fftfreq
-del sys.path[0]
+restore_path()
from numpy import pi
def random(size):
return rand(*size)
-class TestFFTShift(NumpyTestCase):
-
- def check_definition(self):
+class TestFFTShift(TestCase):
+ def test_definition(self):
x = [0,1,2,3,4,-4,-3,-2,-1]
y = [-4,-3,-2,-1,0,1,2,3,4]
assert_array_almost_equal(fftshift(x),y)
@@ -26,14 +25,14 @@ class TestFFTShift(NumpyTestCase):
assert_array_almost_equal(fftshift(x),y)
assert_array_almost_equal(ifftshift(y),x)
- def check_inverse(self):
+ def test_inverse(self):
for n in [1,4,9,100,211]:
x = random((n,))
assert_array_almost_equal(ifftshift(fftshift(x)),x)
-class TestFFTFreq(NumpyTestCase):
- def check_definition(self):
+class TestFFTFreq(TestCase):
+ def test_definition(self):
x = [0,1,2,3,4,-4,-3,-2,-1]
assert_array_almost_equal(9*fftfreq(9),x)
assert_array_almost_equal(9*pi*fftfreq(9,pi),x)
@@ -41,5 +40,6 @@ class TestFFTFreq(NumpyTestCase):
assert_array_almost_equal(10*fftfreq(10),x)
assert_array_almost_equal(10*pi*fftfreq(10,pi),x)
+
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/lib/__init__.py b/numpy/lib/__init__.py
index b011095f3..643320bc0 100644
--- a/numpy/lib/__init__.py
+++ b/numpy/lib/__init__.py
@@ -34,6 +34,7 @@ __all__ += arraysetops.__all__
__all__ += io.__all__
__all__ += financial.__all__
-def test(level=1, verbosity=1):
- from numpy.testing import NumpyTest
- return NumpyTest().test(level, verbosity)
+from numpy.testing.pkgtester import Tester
+test = Tester().test
+bench = Tester().bench
+
diff --git a/numpy/lib/tests/test__datasource.py b/numpy/lib/tests/test__datasource.py
index 93e77d28c..695da0470 100644
--- a/numpy/lib/tests/test__datasource.py
+++ b/numpy/lib/tests/test__datasource.py
@@ -67,7 +67,7 @@ def valid_httpfile():
def invalid_httpfile():
return http_fakefile
-class TestDataSourceOpen(NumpyTestCase):
+class TestDataSourceOpen(TestCase):
def setUp(self):
self.tmpdir = mkdtemp()
self.ds = datasource.DataSource(self.tmpdir)
@@ -127,7 +127,7 @@ class TestDataSourceOpen(NumpyTestCase):
self.assertEqual(magic_line, result)
-class TestDataSourceExists(NumpyTestCase):
+class TestDataSourceExists(TestCase):
def setUp(self):
self.tmpdir = mkdtemp()
self.ds = datasource.DataSource(self.tmpdir)
@@ -157,7 +157,7 @@ class TestDataSourceExists(NumpyTestCase):
self.assertEqual(self.ds.exists(tmpfile), False)
-class TestDataSourceAbspath(NumpyTestCase):
+class TestDataSourceAbspath(TestCase):
def setUp(self):
self.tmpdir = os.path.abspath(mkdtemp())
self.ds = datasource.DataSource(self.tmpdir)
@@ -222,7 +222,7 @@ class TestDataSourceAbspath(NumpyTestCase):
os.sep = orig_os_sep
-class TestRepositoryAbspath(NumpyTestCase):
+class TestRepositoryAbspath(TestCase):
def setUp(self):
self.tmpdir = os.path.abspath(mkdtemp())
self.repos = datasource.Repository(valid_baseurl(), self.tmpdir)
@@ -255,7 +255,7 @@ class TestRepositoryAbspath(NumpyTestCase):
os.sep = orig_os_sep
-class TestRepositoryExists(NumpyTestCase):
+class TestRepositoryExists(TestCase):
def setUp(self):
self.tmpdir = mkdtemp()
self.repos = datasource.Repository(valid_baseurl(), self.tmpdir)
@@ -288,7 +288,7 @@ class TestRepositoryExists(NumpyTestCase):
assert self.repos.exists(tmpfile)
-class TestOpenFunc(NumpyTestCase):
+class TestOpenFunc(TestCase):
def setUp(self):
self.tmpdir = mkdtemp()
@@ -304,4 +304,4 @@ class TestOpenFunc(NumpyTestCase):
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/lib/tests/test_arraysetops.py b/numpy/lib/tests/test_arraysetops.py
index 5a5a8fbd8..ca505e9c5 100644
--- a/numpy/lib/tests/test_arraysetops.py
+++ b/numpy/lib/tests/test_arraysetops.py
@@ -6,15 +6,14 @@ from numpy.testing import *
set_package_path()
import numpy
from numpy.lib.arraysetops import *
-from numpy.lib.arraysetops import ediff1d
restore_path()
##################################################
-class TestAso(NumpyTestCase):
+class TestAso(TestCase):
##
# 03.11.2005, c
- def check_unique1d( self ):
+ def test_unique1d( self ):
a = numpy.array( [5, 7, 1, 2, 1, 5, 7] )
@@ -26,7 +25,7 @@ class TestAso(NumpyTestCase):
##
# 03.11.2005, c
- def check_intersect1d( self ):
+ def test_intersect1d( self ):
a = numpy.array( [5, 7, 1, 2] )
b = numpy.array( [2, 4, 3, 1, 5] )
@@ -39,7 +38,7 @@ class TestAso(NumpyTestCase):
##
# 03.11.2005, c
- def check_intersect1d_nu( self ):
+ def test_intersect1d_nu( self ):
a = numpy.array( [5, 5, 7, 1, 2] )
b = numpy.array( [2, 1, 4, 3, 3, 1, 5] )
@@ -52,7 +51,7 @@ class TestAso(NumpyTestCase):
##
# 03.11.2005, c
- def check_setxor1d( self ):
+ def test_setxor1d( self ):
a = numpy.array( [5, 7, 1, 2] )
b = numpy.array( [2, 4, 3, 1, 5] )
@@ -77,7 +76,7 @@ class TestAso(NumpyTestCase):
assert_array_equal([], setxor1d([],[]))
- def check_ediff1d(self):
+ def test_ediff1d(self):
zero_elem = numpy.array([])
one_elem = numpy.array([1])
two_elem = numpy.array([1,2])
@@ -91,7 +90,7 @@ class TestAso(NumpyTestCase):
##
# 03.11.2005, c
- def check_setmember1d( self ):
+ def test_setmember1d( self ):
a = numpy.array( [5, 7, 1, 2] )
b = numpy.array( [2, 4, 3, 1, 5] )
@@ -114,7 +113,7 @@ class TestAso(NumpyTestCase):
##
# 03.11.2005, c
- def check_union1d( self ):
+ def test_union1d( self ):
a = numpy.array( [5, 4, 7, 1, 2] )
b = numpy.array( [2, 4, 3, 3, 2, 1, 5] )
@@ -128,7 +127,7 @@ class TestAso(NumpyTestCase):
##
# 03.11.2005, c
# 09.01.2006
- def check_setdiff1d( self ):
+ def test_setdiff1d( self ):
a = numpy.array( [6, 5, 4, 7, 1, 2] )
b = numpy.array( [2, 4, 3, 3, 2, 1, 5] )
@@ -145,14 +144,14 @@ class TestAso(NumpyTestCase):
assert_array_equal([], setdiff1d([],[]))
- def check_setdiff1d_char_array(self):
+ def test_setdiff1d_char_array(self):
a = numpy.array(['a','b','c'])
b = numpy.array(['a','b','s'])
assert_array_equal(setdiff1d(a,b),numpy.array(['c']))
##
# 03.11.2005, c
- def check_manyways( self ):
+ def test_manyways( self ):
nItem = 100
a = numpy.fix( nItem / 10 * numpy.random.random( nItem ) )
@@ -171,5 +170,6 @@ class TestAso(NumpyTestCase):
c2 = setdiff1d( aux2, aux1 )
assert_array_equal( c1, c2 )
+
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/lib/tests/test_financial.py b/numpy/lib/tests/test_financial.py
index ee38c10dc..df5a0fbde 100644
--- a/numpy/lib/tests/test_financial.py
+++ b/numpy/lib/tests/test_financial.py
@@ -32,8 +32,9 @@ True
from numpy.testing import *
import numpy as np
-class TestDocs(NumpyTestCase):
- def check_doctests(self): return self.rundocs()
+def test():
+ import doctest
+ doctest.testmod()
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/lib/tests/test_format.py b/numpy/lib/tests/test_format.py
index e7b27ce94..4a473c55e 100644
--- a/numpy/lib/tests/test_format.py
+++ b/numpy/lib/tests/test_format.py
@@ -506,3 +506,7 @@ def test_read_version_1_0_bad_magic():
for magic in bad_version_magic + malformed_magic:
f = StringIO(magic)
yield raises(ValueError)(format.read_array), f
+
+
+if __name__ == "__main__":
+ nose.run(argv=['', __file__])
diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py
index e1a7ae67a..3cd7cd6bb 100644
--- a/numpy/lib/tests/test_function_base.py
+++ b/numpy/lib/tests/test_function_base.py
@@ -5,11 +5,10 @@ set_package_path()
import numpy.lib;reload(numpy.lib)
from numpy.lib import *
from numpy.core import *
+restore_path()
-del sys.path[0]
-
-class TestAny(NumpyTestCase):
- def check_basic(self):
+class TestAny(TestCase):
+ def test_basic(self):
y1 = [0,0,1,0]
y2 = [0,0,0,0]
y3 = [1,0,1,0]
@@ -17,14 +16,14 @@ class TestAny(NumpyTestCase):
assert(any(y3))
assert(not any(y2))
- def check_nd(self):
+ def test_nd(self):
y1 = [[0,0,0],[0,1,0],[1,1,0]]
assert(any(y1))
assert_array_equal(sometrue(y1,axis=0),[1,1,0])
assert_array_equal(sometrue(y1,axis=1),[0,1,1])
-class TestAll(NumpyTestCase):
- def check_basic(self):
+class TestAll(TestCase):
+ def test_basic(self):
y1 = [0,1,1,0]
y2 = [0,0,0,0]
y3 = [1,1,1,1]
@@ -33,14 +32,14 @@ class TestAll(NumpyTestCase):
assert(not all(y2))
assert(all(~array(y2)))
- def check_nd(self):
+ def test_nd(self):
y1 = [[0,0,1],[0,1,1],[1,1,1]]
assert(not all(y1))
assert_array_equal(alltrue(y1,axis=0),[0,0,1])
assert_array_equal(alltrue(y1,axis=1),[0,0,1])
-class TestAverage(NumpyTestCase):
- def check_basic(self):
+class TestAverage(TestCase):
+ def test_basic(self):
y1 = array([1,2,3])
assert(average(y1,axis=0) == 2.)
y2 = array([1.,2.,3.])
@@ -61,7 +60,7 @@ class TestAverage(NumpyTestCase):
y6 = matrix(rand(5,5))
assert_array_equal(y6.mean(0), average(y6,0))
- def check_weights(self):
+ def test_weights(self):
y = arange(10)
w = arange(10)
assert_almost_equal(average(y, weights=w), (arange(10)**2).sum()*1./arange(10).sum())
@@ -89,7 +88,7 @@ class TestAverage(NumpyTestCase):
assert_equal(average(y1, weights=w2), 5.)
- def check_returned(self):
+ def test_returned(self):
y = array([[1,2,3],[4,5,6]])
# No weights
@@ -116,14 +115,14 @@ class TestAverage(NumpyTestCase):
assert_array_equal(scl, array([1.,6.]))
-class TestSelect(NumpyTestCase):
+class TestSelect(TestCase):
def _select(self,cond,values,default=0):
output = []
for m in range(len(cond)):
output += [V[m] for V,C in zip(values,cond) if C[m]] or [default]
return output
- def check_basic(self):
+ def test_basic(self):
choices = [array([1,2,3]),
array([4,5,6]),
array([7,8,9])]
@@ -136,8 +135,8 @@ class TestSelect(NumpyTestCase):
assert_equal(len(choices),3)
assert_equal(len(conditions),3)
-class TestLogspace(NumpyTestCase):
- def check_basic(self):
+class TestLogspace(TestCase):
+ def test_basic(self):
y = logspace(0,6)
assert(len(y)==50)
y = logspace(0,6,num=100)
@@ -147,8 +146,8 @@ class TestLogspace(NumpyTestCase):
y = logspace(0,6,num=7)
assert_array_equal(y,[1,10,100,1e3,1e4,1e5,1e6])
-class TestLinspace(NumpyTestCase):
- def check_basic(self):
+class TestLinspace(TestCase):
+ def test_basic(self):
y = linspace(0,10)
assert(len(y)==50)
y = linspace(2,10,num=100)
@@ -159,28 +158,28 @@ class TestLinspace(NumpyTestCase):
assert_almost_equal(st,8/49.0)
assert_array_almost_equal(y,mgrid[2:10:50j],13)
- def check_corner(self):
+ def test_corner(self):
y = list(linspace(0,1,1))
assert y == [0.0], y
y = list(linspace(0,1,2.5))
assert y == [0.0, 1.0]
- def check_type(self):
+ def test_type(self):
t1 = linspace(0,1,0).dtype
t2 = linspace(0,1,1).dtype
t3 = linspace(0,1,2).dtype
assert_equal(t1, t2)
assert_equal(t2, t3)
-class TestInsert(NumpyTestCase):
- def check_basic(self):
+class TestInsert(TestCase):
+ def test_basic(self):
a = [1,2,3]
assert_equal(insert(a,0,1), [1,1,2,3])
assert_equal(insert(a,3,1), [1,2,3,1])
assert_equal(insert(a,[1,1,1],[1,2,3]), [1,1,2,3,2,3])
-class TestAmax(NumpyTestCase):
- def check_basic(self):
+class TestAmax(TestCase):
+ def test_basic(self):
a = [3,4,5,10,-3,-5,6.0]
assert_equal(amax(a),10.0)
b = [[3,6.0, 9.0],
@@ -189,8 +188,8 @@ class TestAmax(NumpyTestCase):
assert_equal(amax(b,axis=0),[8.0,10.0,9.0])
assert_equal(amax(b,axis=1),[9.0,10.0,8.0])
-class TestAmin(NumpyTestCase):
- def check_basic(self):
+class TestAmin(TestCase):
+ def test_basic(self):
a = [3,4,5,10,-3,-5,6.0]
assert_equal(amin(a),-5.0)
b = [[3,6.0, 9.0],
@@ -199,8 +198,8 @@ class TestAmin(NumpyTestCase):
assert_equal(amin(b,axis=0),[3.0,3.0,2.0])
assert_equal(amin(b,axis=1),[3.0,4.0,2.0])
-class TestPtp(NumpyTestCase):
- def check_basic(self):
+class TestPtp(TestCase):
+ def test_basic(self):
a = [3,4,5,10,-3,-5,6.0]
assert_equal(ptp(a,axis=0),15.0)
b = [[3,6.0, 9.0],
@@ -209,8 +208,8 @@ class TestPtp(NumpyTestCase):
assert_equal(ptp(b,axis=0),[5.0,7.0,7.0])
assert_equal(ptp(b,axis=-1),[6.0,6.0,6.0])
-class TestCumsum(NumpyTestCase):
- def check_basic(self):
+class TestCumsum(TestCase):
+ def test_basic(self):
ba = [1,2,10,11,6,5,4]
ba2 = [[1,2,3,4],[5,6,7,9],[10,3,4,5]]
for ctype in [int8,uint8,int16,uint16,int32,uint32,
@@ -225,8 +224,8 @@ class TestCumsum(NumpyTestCase):
[5,11,18,27],
[10,13,17,22]],ctype))
-class TestProd(NumpyTestCase):
- def check_basic(self):
+class TestProd(TestCase):
+ def test_basic(self):
ba = [1,2,10,11,6,5,4]
ba2 = [[1,2,3,4],[5,6,7,9],[10,3,4,5]]
for ctype in [int16,uint16,int32,uint32,
@@ -243,8 +242,8 @@ class TestProd(NumpyTestCase):
array([50,36,84,180],ctype))
assert_array_equal(prod(a2,axis=-1),array([24, 1890, 600],ctype))
-class TestCumprod(NumpyTestCase):
- def check_basic(self):
+class TestCumprod(TestCase):
+ def test_basic(self):
ba = [1,2,10,11,6,5,4]
ba2 = [[1,2,3,4],[5,6,7,9],[10,3,4,5]]
for ctype in [int16,uint16,int32,uint32,
@@ -268,8 +267,8 @@ class TestCumprod(NumpyTestCase):
[ 5, 30, 210, 1890],
[10, 30, 120, 600]],ctype))
-class TestDiff(NumpyTestCase):
- def check_basic(self):
+class TestDiff(TestCase):
+ def test_basic(self):
x = [1,4,6,7,12]
out = array([3,2,1,5])
out2 = array([-1,-1,4])
@@ -278,7 +277,7 @@ class TestDiff(NumpyTestCase):
assert_array_equal(diff(x,n=2),out2)
assert_array_equal(diff(x,n=3),out3)
- def check_nd(self):
+ def test_nd(self):
x = 20*rand(10,20,30)
out1 = x[:,:,1:] - x[:,:,:-1]
out2 = out1[:,:,1:] - out1[:,:,:-1]
@@ -289,8 +288,8 @@ class TestDiff(NumpyTestCase):
assert_array_equal(diff(x,axis=0),out3)
assert_array_equal(diff(x,n=2,axis=0),out4)
-class TestAngle(NumpyTestCase):
- def check_basic(self):
+class TestAngle(TestCase):
+ def test_basic(self):
x = [1+3j,sqrt(2)/2.0+1j*sqrt(2)/2,1,1j,-1,-1j,1-3j,-1+3j]
y = angle(x)
yo = [arctan(3.0/1.0),arctan(1.0),0,pi/2,pi,-pi/2.0,
@@ -300,33 +299,33 @@ class TestAngle(NumpyTestCase):
assert_array_almost_equal(y,yo,11)
assert_array_almost_equal(z,zo,11)
-class TestTrimZeros(NumpyTestCase):
+class TestTrimZeros(TestCase):
""" only testing for integer splits.
"""
- def check_basic(self):
+ def test_basic(self):
a= array([0,0,1,2,3,4,0])
res = trim_zeros(a)
assert_array_equal(res,array([1,2,3,4]))
- def check_leading_skip(self):
+ def test_leading_skip(self):
a= array([0,0,1,0,2,3,4,0])
res = trim_zeros(a)
assert_array_equal(res,array([1,0,2,3,4]))
- def check_trailing_skip(self):
+ def test_trailing_skip(self):
a= array([0,0,1,0,2,3,0,4,0])
res = trim_zeros(a)
assert_array_equal(res,array([1,0,2,3,0,4]))
-class TestExtins(NumpyTestCase):
- def check_basic(self):
+class TestExtins(TestCase):
+ def test_basic(self):
a = array([1,3,2,1,2,3,3])
b = extract(a>1,a)
assert_array_equal(b,[3,2,2,3,3])
- def check_place(self):
+ def test_place(self):
a = array([1,4,3,2,5,8,7])
place(a,[0,1,0,1,0,1,0],[2,4,6])
assert_array_equal(a,[1,2,3,4,5,6,7])
- def check_both(self):
+ def test_both(self):
a = rand(10)
mask = a > 0.5
ac = a.copy()
@@ -335,8 +334,8 @@ class TestExtins(NumpyTestCase):
place(a,mask,c)
assert_array_equal(a,ac)
-class TestVectorize(NumpyTestCase):
- def check_simple(self):
+class TestVectorize(TestCase):
+ def test_simple(self):
def addsubtract(a,b):
if a > b:
return a - b
@@ -345,7 +344,7 @@ class TestVectorize(NumpyTestCase):
f = vectorize(addsubtract)
r = f([0,3,6,9],[1,3,5,7])
assert_array_equal(r,[1,6,1,2])
- def check_scalar(self):
+ def test_scalar(self):
def addsubtract(a,b):
if a > b:
return a - b
@@ -354,59 +353,59 @@ class TestVectorize(NumpyTestCase):
f = vectorize(addsubtract)
r = f([0,3,6,9],5)
assert_array_equal(r,[5,8,1,4])
- def check_large(self):
+ def test_large(self):
x = linspace(-3,2,10000)
f = vectorize(lambda x: x)
y = f(x)
assert_array_equal(y, x)
-class TestDigitize(NumpyTestCase):
- def check_forward(self):
+class TestDigitize(TestCase):
+ def test_forward(self):
x = arange(-6,5)
bins = arange(-5,5)
assert_array_equal(digitize(x,bins),arange(11))
- def check_reverse(self):
+ def test_reverse(self):
x = arange(5,-6,-1)
bins = arange(5,-5,-1)
assert_array_equal(digitize(x,bins),arange(11))
- def check_random(self):
+ def test_random(self):
x = rand(10)
bin = linspace(x.min(), x.max(), 10)
assert all(digitize(x,bin) != 0)
-class TestUnwrap(NumpyTestCase):
- def check_simple(self):
+class TestUnwrap(TestCase):
+ def test_simple(self):
#check that unwrap removes jumps greather that 2*pi
assert_array_equal(unwrap([1,1+2*pi]),[1,1])
#check that unwrap maintans continuity
assert(all(diff(unwrap(rand(10)*100))<pi))
-class TestFilterwindows(NumpyTestCase):
- def check_hanning(self):
+class TestFilterwindows(TestCase):
+ def test_hanning(self):
#check symmetry
w=hanning(10)
assert_array_almost_equal(w,flipud(w),7)
#check known value
assert_almost_equal(sum(w,axis=0),4.500,4)
- def check_hamming(self):
+ def test_hamming(self):
#check symmetry
w=hamming(10)
assert_array_almost_equal(w,flipud(w),7)
#check known value
assert_almost_equal(sum(w,axis=0),4.9400,4)
- def check_bartlett(self):
+ def test_bartlett(self):
#check symmetry
w=bartlett(10)
assert_array_almost_equal(w,flipud(w),7)
#check known value
assert_almost_equal(sum(w,axis=0),4.4444,4)
- def check_blackman(self):
+ def test_blackman(self):
#check symmetry
w=blackman(10)
assert_array_almost_equal(w,flipud(w),7)
@@ -414,23 +413,23 @@ class TestFilterwindows(NumpyTestCase):
assert_almost_equal(sum(w,axis=0),3.7800,4)
-class TestTrapz(NumpyTestCase):
- def check_simple(self):
+class TestTrapz(TestCase):
+ def test_simple(self):
r=trapz(exp(-1.0/2*(arange(-10,10,.1))**2)/sqrt(2*pi),dx=0.1)
#check integral of normal equals 1
assert_almost_equal(sum(r,axis=0),1,7)
-class TestSinc(NumpyTestCase):
- def check_simple(self):
+class TestSinc(TestCase):
+ def test_simple(self):
assert(sinc(0)==1)
w=sinc(linspace(-1,1,100))
#check symmetry
assert_array_almost_equal(w,flipud(w),7)
-class TestHistogram(NumpyTestCase):
+class TestHistogram(TestCase):
import warnings
warnings.simplefilter('ignore', FutureWarning)
- def check_simple(self):
+ def test_simple(self):
n=100
v=rand(n)
(a,b)=histogram(v)
@@ -441,7 +440,7 @@ class TestHistogram(NumpyTestCase):
(a,b)=histogram(linspace(0,10,100))
assert_array_equal(a, 10)
- def check_simple_new(self):
+ def test_simple_new(self):
n=100
v=rand(n)
(a,b)=histogram(v, new=True)
@@ -452,7 +451,7 @@ class TestHistogram(NumpyTestCase):
(a,b)=histogram(linspace(0,10,100), new=True)
assert_array_equal(a, 10)
- def check_normed_new(self):
+ def test_normed_new(self):
# Check that the integral of the density equals 1.
n = 100
v = rand(n)
@@ -468,7 +467,7 @@ class TestHistogram(NumpyTestCase):
assert_almost_equal(area, 1)
- def check_outliers_new(self):
+ def test_outliers_new(self):
# Check that outliers are not tallied
a = arange(10)+.5
@@ -493,7 +492,7 @@ class TestHistogram(NumpyTestCase):
assert_equal(h, w[1:-1])
- def check_type_new(self):
+ def test_type_new(self):
# Check the type of the returned histogram
a = arange(10)+.5
h,b = histogram(a, new=True)
@@ -509,7 +508,7 @@ class TestHistogram(NumpyTestCase):
assert(issubdtype(h.dtype, float))
- def check_weights_new(self):
+ def test_weights_new(self):
v = rand(100)
w = ones(100)*5
a,b = histogram(v,new=True)
@@ -531,8 +530,8 @@ class TestHistogram(NumpyTestCase):
wa, wb = histogram([1,2,2,4], bins=4, weights=[4,3,2,1], normed=True, new=True)
assert_array_equal(wa, array([4,5,0,1])/10./3.*4)
-class TestHistogramdd(NumpyTestCase):
- def check_simple(self):
+class TestHistogramdd(TestCase):
+ def test_simple(self):
x = array([[-.5, .5, 1.5], [-.5, 1.5, 2.5], [-.5, 2.5, .5], \
[.5, .5, 1.5], [.5, 1.5, 2.5], [.5, 2.5, 2.5]])
H, edges = histogramdd(x, (2,3,3), range = [[-1,1], [0,3], [0,3]])
@@ -564,7 +563,7 @@ class TestHistogramdd(NumpyTestCase):
H,edges = histogramdd([arange(5), arange(5), arange(5)], 5)
assert_array_equal(H, Z)
- def check_shape_3d(self):
+ def test_shape_3d(self):
# All possible permutations for bins of different lengths in 3D.
bins = ((5, 4, 6), (6, 4, 5), (5, 6, 4), (4, 6, 5), (6, 5, 4),
(4, 5, 6))
@@ -573,7 +572,7 @@ class TestHistogramdd(NumpyTestCase):
H, edges = histogramdd(r, b)
assert(H.shape == b)
- def check_shape_4d(self):
+ def test_shape_4d(self):
# All possible permutations for bins of different lengths in 4D.
bins = ((7, 4, 5, 6), (4, 5, 7, 6), (5, 6, 4, 7), (7, 6, 5, 4),
(5, 7, 6, 4), (4, 6, 7, 5), (6, 5, 7, 4), (7, 5, 4, 6),
@@ -587,7 +586,7 @@ class TestHistogramdd(NumpyTestCase):
H, edges = histogramdd(r, b)
assert(H.shape == b)
- def check_weights(self):
+ def test_weights(self):
v = rand(100,2)
hist, edges = histogramdd(v)
n_hist, edges = histogramdd(v, normed=True)
@@ -598,13 +597,13 @@ class TestHistogramdd(NumpyTestCase):
w_hist, edges = histogramdd(v, weights=ones(100, int)*2)
assert_array_equal(w_hist, 2*hist)
- def check_identical_samples(self):
+ def test_identical_samples(self):
x = zeros((10,2),int)
hist, edges = histogramdd(x, bins=2)
assert_array_equal(edges[0],array([-0.5, 0. , 0.5]))
-class TestUnique(NumpyTestCase):
- def check_simple(self):
+class TestUnique(TestCase):
+ def test_simple(self):
x = array([4,3,2,1,1,2,3,4, 0])
assert(all(unique(x) == [0,1,2,3,4]))
assert(unique(array([1,1,1,1,1])) == array([1]))
@@ -618,4 +617,4 @@ def compare_results(res,desired):
assert_array_equal(res[i],desired[i])
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/lib/tests/test_getlimits.py b/numpy/lib/tests/test_getlimits.py
index a85228689..a6be8abd2 100644
--- a/numpy/lib/tests/test_getlimits.py
+++ b/numpy/lib/tests/test_getlimits.py
@@ -2,39 +2,40 @@
"""
from numpy.testing import *
-import numpy.lib;reload(numpy.lib)
+import numpy.lib
+reload(numpy.lib)
from numpy.lib.getlimits import finfo, iinfo
from numpy import single,double,longdouble
import numpy as np
##################################################
-class TestPythonFloat(NumpyTestCase):
- def check_singleton(self):
+class TestPythonFloat(TestCase):
+ def test_singleton(self):
ftype = finfo(float)
ftype2 = finfo(float)
assert_equal(id(ftype),id(ftype2))
-class TestSingle(NumpyTestCase):
- def check_singleton(self):
+class TestSingle(TestCase):
+ def test_singleton(self):
ftype = finfo(single)
ftype2 = finfo(single)
assert_equal(id(ftype),id(ftype2))
-class TestDouble(NumpyTestCase):
- def check_singleton(self):
+class TestDouble(TestCase):
+ def test_singleton(self):
ftype = finfo(double)
ftype2 = finfo(double)
assert_equal(id(ftype),id(ftype2))
-class TestLongdouble(NumpyTestCase):
- def check_singleton(self,level=2):
+class TestLongdouble(TestCase):
+ def test_singleton(self,level=2):
ftype = finfo(longdouble)
ftype2 = finfo(longdouble)
assert_equal(id(ftype),id(ftype2))
-class TestIinfo(NumpyTestCase):
- def check_basic(self):
+class TestIinfo(TestCase):
+ def test_basic(self):
dts = zip(['i1', 'i2', 'i4', 'i8',
'u1', 'u2', 'u4', 'u8'],
[np.int8, np.int16, np.int32, np.int64,
@@ -44,10 +45,11 @@ class TestIinfo(NumpyTestCase):
assert_equal(iinfo(dt1).max, iinfo(dt2).max)
self.assertRaises(ValueError, iinfo, 'f4')
- def check_unsigned_max(self):
+ def test_unsigned_max(self):
types = np.sctypes['uint']
for T in types:
assert_equal(iinfo(T).max, T(-1))
+
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/lib/tests/test_index_tricks.py b/numpy/lib/tests/test_index_tricks.py
index a0105656b..51d8e59db 100644
--- a/numpy/lib/tests/test_index_tricks.py
+++ b/numpy/lib/tests/test_index_tricks.py
@@ -3,8 +3,8 @@ set_package_path()
from numpy import array, ones, r_, mgrid
restore_path()
-class TestGrid(NumpyTestCase):
- def check_basic(self):
+class TestGrid(TestCase):
+ def test_basic(self):
a = mgrid[-1:1:10j]
b = mgrid[-1:1:0.1]
assert(a.shape == (10,))
@@ -16,7 +16,7 @@ class TestGrid(NumpyTestCase):
assert_almost_equal(b[-1],b[0]+19*0.1,11)
assert_almost_equal(a[1]-a[0],2.0/9.0,11)
- def check_nd(self):
+ def test_nd(self):
c = mgrid[-1:1:10j,-2:2:10j]
d = mgrid[-1:1:0.1,-2:2:0.2]
assert(c.shape == (2,10,10))
@@ -28,22 +28,22 @@ class TestGrid(NumpyTestCase):
assert_array_almost_equal(d[0,1,:]-d[0,0,:], 0.1*ones(20,'d'),11)
assert_array_almost_equal(d[1,:,1]-d[1,:,0], 0.2*ones(20,'d'),11)
-class TestConcatenator(NumpyTestCase):
- def check_1d(self):
+class TestConcatenator(TestCase):
+ def test_1d(self):
assert_array_equal(r_[1,2,3,4,5,6],array([1,2,3,4,5,6]))
b = ones(5)
c = r_[b,0,0,b]
assert_array_equal(c,[1,1,1,1,1,0,0,1,1,1,1,1])
- def check_mixed_type(self):
+ def test_mixed_type(self):
g = r_[10.1, 1:10]
assert(g.dtype == 'f8')
- def check_more_mixed_type(self):
+ def test_more_mixed_type(self):
g = r_[-10.1, array([1]), array([2,3,4]), 10.0]
assert(g.dtype == 'f8')
- def check_2d(self):
+ def test_2d(self):
b = rand(5,5)
c = rand(5,5)
d = r_['1',b,c] # append columns
@@ -55,5 +55,6 @@ class TestConcatenator(NumpyTestCase):
assert_array_equal(d[:5,:],b)
assert_array_equal(d[5:,:],c)
+
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py
index 8e7ffc425..7cc595d4f 100644
--- a/numpy/lib/tests/test_io.py
+++ b/numpy/lib/tests/test_io.py
@@ -2,7 +2,7 @@ from numpy.testing import *
import numpy as np
import StringIO
-class TestSaveTxt(NumpyTestCase):
+class TestSaveTxt(TestCase):
def test_array(self):
a =np.array( [[1,2],[3,4]], float)
c = StringIO.StringIO()
@@ -62,7 +62,7 @@ class TestSaveTxt(NumpyTestCase):
assert_equal(lines, ['01 : 2.0\n', '03 : 4.0\n'])
-class TestLoadTxt(NumpyTestCase):
+class TestLoadTxt(TestCase):
def test_record(self):
c = StringIO.StringIO()
c.write('1 2\n3 4')
@@ -164,7 +164,7 @@ class TestLoadTxt(NumpyTestCase):
assert_array_equal(x, a[:,1:])
-class Testfromregex(NumpyTestCase):
+class Testfromregex(TestCase):
def test_record(self):
c = StringIO.StringIO()
c.write('1.312 foo\n1.534 bar\n4.444 qux')
@@ -196,5 +196,6 @@ class Testfromregex(NumpyTestCase):
a = np.array([(1312,), (1534,), (4444,)], dtype=dt)
assert_array_equal(x, a)
+
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/lib/tests/test_machar.py b/numpy/lib/tests/test_machar.py
index 584cd1164..7485fc6c2 100644
--- a/numpy/lib/tests/test_machar.py
+++ b/numpy/lib/tests/test_machar.py
@@ -1,10 +1,10 @@
-from numpy.testing import NumpyTestCase, NumpyTest
+from numpy.testing import *
from numpy.lib.machar import MachAr
import numpy.core.numerictypes as ntypes
from numpy import seterr, array
-class TestMachAr(NumpyTestCase):
+class TestMachAr(TestCase):
def _run_machar_highprec(self):
# Instanciate MachAr instance with high enough precision to cause
# underflow
@@ -26,5 +26,6 @@ class TestMachAr(NumpyTestCase):
finally:
seterr(**serrstate)
+
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/lib/tests/test_polynomial.py b/numpy/lib/tests/test_polynomial.py
index 012f49d77..3bd002cc0 100644
--- a/numpy/lib/tests/test_polynomial.py
+++ b/numpy/lib/tests/test_polynomial.py
@@ -76,13 +76,14 @@ poly1d([ 2.])
from numpy.testing import *
import numpy as np
-class TestDocs(NumpyTestCase):
- def check_doctests(self): return self.rundocs()
+class TestDocs(TestCase):
+ def test_doctests(self):
+ return rundocs()
- def check_roots(self):
+ def test_roots(self):
assert_array_equal(np.roots([1,0,0]), [0,0])
- def check_str_leading_zeros(self):
+ def test_str_leading_zeros(self):
p = np.poly1d([4,3,2,1])
p[3] = 0
assert_equal(str(p),
@@ -94,7 +95,7 @@ class TestDocs(NumpyTestCase):
p[1] = 0
assert_equal(str(p), " \n0")
- def check_polyfit(self) :
+ def test_polyfit(self) :
c = np.array([3., 2., 1.])
x = np.linspace(0,2,5)
y = np.polyval(c,x)
@@ -109,5 +110,6 @@ class TestDocs(NumpyTestCase):
cc = np.concatenate((c,c), axis=1)
assert_almost_equal(cc, np.polyfit(x,yy,2))
+
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/lib/tests/test_regression.py b/numpy/lib/tests/test_regression.py
index 868184b81..a5ba55928 100644
--- a/numpy/lib/tests/test_regression.py
+++ b/numpy/lib/tests/test_regression.py
@@ -6,7 +6,7 @@ restore_path()
rlevel = 1
-class TestRegression(NumpyTestCase):
+class TestRegression(TestCase):
def test_polyfit_build(self,level=rlevel):
"""Ticket #628"""
ref = [-1.06123820e-06, 5.70886914e-04, -1.13822012e-01,
@@ -30,4 +30,4 @@ class TestRegression(NumpyTestCase):
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/lib/tests/test_shape_base.py b/numpy/lib/tests/test_shape_base.py
index 320871a95..60265cd80 100644
--- a/numpy/lib/tests/test_shape_base.py
+++ b/numpy/lib/tests/test_shape_base.py
@@ -1,31 +1,34 @@
from numpy.testing import *
set_package_path()
-import numpy.lib;
from numpy.lib import *
from numpy.core import *
restore_path()
-class TestApplyAlongAxis(NumpyTestCase):
- def check_simple(self):
+class TestApplyAlongAxis(TestCase):
+ def test_simple(self):
a = ones((20,10),'d')
assert_array_equal(apply_along_axis(len,0,a),len(a)*ones(shape(a)[1]))
- def check_simple101(self,level=11):
+
+ def test_simple101(self,level=11):
a = ones((10,101),'d')
assert_array_equal(apply_along_axis(len,0,a),len(a)*ones(shape(a)[1]))
- def check_3d(self):
+ def test_3d(self):
a = arange(27).reshape((3,3,3))
- assert_array_equal(apply_along_axis(sum,0,a), [[27,30,33],[36,39,42],[45,48,51]])
+ assert_array_equal(apply_along_axis(sum,0,a),
+ [[27,30,33],[36,39,42],[45,48,51]])
+
-class TestArraySplit(NumpyTestCase):
- def check_integer_0_split(self):
+class TestArraySplit(TestCase):
+ def test_integer_0_split(self):
a = arange(10)
try:
res = array_split(a,0)
assert(0) # it should have thrown a value error
except ValueError:
pass
- def check_integer_split(self):
+
+ def test_integer_split(self):
a = arange(10)
res = array_split(a,1)
desired = [arange(10)]
@@ -78,19 +81,22 @@ class TestArraySplit(NumpyTestCase):
arange(4,5),arange(5,6), arange(6,7), arange(7,8),
arange(8,9), arange(9,10),array([])]
compare_results(res,desired)
- def check_integer_split_2D_rows(self):
+
+ def test_integer_split_2D_rows(self):
a = array([arange(10),arange(10)])
res = array_split(a,3,axis=0)
desired = [array([arange(10)]),array([arange(10)]),array([])]
compare_results(res,desired)
- def check_integer_split_2D_cols(self):
+
+ def test_integer_split_2D_cols(self):
a = array([arange(10),arange(10)])
res = array_split(a,3,axis=-1)
desired = [array([arange(4),arange(4)]),
array([arange(4,7),arange(4,7)]),
array([arange(7,10),arange(7,10)])]
compare_results(res,desired)
- def check_integer_split_2D_default(self):
+
+ def test_integer_split_2D_default(self):
""" This will fail if we change default axis
"""
a = array([arange(10),arange(10)])
@@ -99,20 +105,21 @@ class TestArraySplit(NumpyTestCase):
compare_results(res,desired)
#perhaps should check higher dimensions
- def check_index_split_simple(self):
+ def test_index_split_simple(self):
a = arange(10)
indices = [1,5,7]
res = array_split(a,indices,axis=-1)
desired = [arange(0,1),arange(1,5),arange(5,7),arange(7,10)]
compare_results(res,desired)
- def check_index_split_low_bound(self):
+ def test_index_split_low_bound(self):
a = arange(10)
indices = [0,5,7]
res = array_split(a,indices,axis=-1)
desired = [array([]),arange(0,5),arange(5,7),arange(7,10)]
compare_results(res,desired)
- def check_index_split_high_bound(self):
+
+ def test_index_split_high_bound(self):
a = arange(10)
indices = [0,5,7,10,12]
res = array_split(a,indices,axis=-1)
@@ -120,18 +127,19 @@ class TestArraySplit(NumpyTestCase):
array([]),array([])]
compare_results(res,desired)
-class TestSplit(NumpyTestCase):
+
+class TestSplit(TestCase):
"""* This function is essentially the same as array_split,
except that it test if splitting will result in an
equal split. Only test for this case.
*"""
- def check_equal_split(self):
+ def test_equal_split(self):
a = arange(10)
res = split(a,2)
desired = [arange(5),arange(5,10)]
compare_results(res,desired)
- def check_unequal_split(self):
+ def test_unequal_split(self):
a = arange(10)
try:
res = split(a,3)
@@ -139,29 +147,34 @@ class TestSplit(NumpyTestCase):
except ValueError:
pass
-class TestAtleast1d(NumpyTestCase):
- def check_0D_array(self):
+
+class TestAtleast1d(TestCase):
+ def test_0D_array(self):
a = array(1); b = array(2);
res=map(atleast_1d,[a,b])
desired = [array([1]),array([2])]
assert_array_equal(res,desired)
- def check_1D_array(self):
+
+ def test_1D_array(self):
a = array([1,2]); b = array([2,3]);
res=map(atleast_1d,[a,b])
desired = [array([1,2]),array([2,3])]
assert_array_equal(res,desired)
- def check_2D_array(self):
+
+ def test_2D_array(self):
a = array([[1,2],[1,2]]); b = array([[2,3],[2,3]]);
res=map(atleast_1d,[a,b])
desired = [a,b]
assert_array_equal(res,desired)
- def check_3D_array(self):
+
+ def test_3D_array(self):
a = array([[1,2],[1,2]]); b = array([[2,3],[2,3]]);
a = array([a,a]);b = array([b,b]);
res=map(atleast_1d,[a,b])
desired = [a,b]
assert_array_equal(res,desired)
- def check_r1array(self):
+
+ def test_r1array(self):
""" Test to make sure equivalent Travis O's r1array function
"""
assert(atleast_1d(3).shape == (1,))
@@ -170,114 +183,130 @@ class TestAtleast1d(NumpyTestCase):
assert(atleast_1d(3.0).shape == (1,))
assert(atleast_1d([[2,3],[4,5]]).shape == (2,2))
-class TestAtleast2d(NumpyTestCase):
- def check_0D_array(self):
+class TestAtleast2d(TestCase):
+ def test_0D_array(self):
a = array(1); b = array(2);
res=map(atleast_2d,[a,b])
desired = [array([[1]]),array([[2]])]
assert_array_equal(res,desired)
- def check_1D_array(self):
+
+ def test_1D_array(self):
a = array([1,2]); b = array([2,3]);
res=map(atleast_2d,[a,b])
desired = [array([[1,2]]),array([[2,3]])]
assert_array_equal(res,desired)
- def check_2D_array(self):
+
+ def test_2D_array(self):
a = array([[1,2],[1,2]]); b = array([[2,3],[2,3]]);
res=map(atleast_2d,[a,b])
desired = [a,b]
assert_array_equal(res,desired)
- def check_3D_array(self):
+
+ def test_3D_array(self):
a = array([[1,2],[1,2]]); b = array([[2,3],[2,3]]);
a = array([a,a]);b = array([b,b]);
res=map(atleast_2d,[a,b])
desired = [a,b]
assert_array_equal(res,desired)
- def check_r2array(self):
+
+ def test_r2array(self):
""" Test to make sure equivalent Travis O's r2array function
"""
assert(atleast_2d(3).shape == (1,1))
assert(atleast_2d([3j,1]).shape == (1,2))
assert(atleast_2d([[[3,1],[4,5]],[[3,5],[1,2]]]).shape == (2,2,2))
-class TestAtleast3d(NumpyTestCase):
- def check_0D_array(self):
+
+class TestAtleast3d(TestCase):
+ def test_0D_array(self):
a = array(1); b = array(2);
res=map(atleast_3d,[a,b])
desired = [array([[[1]]]),array([[[2]]])]
assert_array_equal(res,desired)
- def check_1D_array(self):
+
+ def test_1D_array(self):
a = array([1,2]); b = array([2,3]);
res=map(atleast_3d,[a,b])
desired = [array([[[1],[2]]]),array([[[2],[3]]])]
assert_array_equal(res,desired)
- def check_2D_array(self):
+
+ def test_2D_array(self):
a = array([[1,2],[1,2]]); b = array([[2,3],[2,3]]);
res=map(atleast_3d,[a,b])
desired = [a[:,:,newaxis],b[:,:,newaxis]]
assert_array_equal(res,desired)
- def check_3D_array(self):
+
+ def test_3D_array(self):
a = array([[1,2],[1,2]]); b = array([[2,3],[2,3]]);
a = array([a,a]);b = array([b,b]);
res=map(atleast_3d,[a,b])
desired = [a,b]
assert_array_equal(res,desired)
-class TestHstack(NumpyTestCase):
- def check_0D_array(self):
+class TestHstack(TestCase):
+ def test_0D_array(self):
a = array(1); b = array(2);
res=hstack([a,b])
desired = array([1,2])
assert_array_equal(res,desired)
- def check_1D_array(self):
+
+ def test_1D_array(self):
a = array([1]); b = array([2]);
res=hstack([a,b])
desired = array([1,2])
assert_array_equal(res,desired)
- def check_2D_array(self):
+
+ def test_2D_array(self):
a = array([[1],[2]]); b = array([[1],[2]]);
res=hstack([a,b])
desired = array([[1,1],[2,2]])
assert_array_equal(res,desired)
-class TestVstack(NumpyTestCase):
- def check_0D_array(self):
+class TestVstack(TestCase):
+ def test_0D_array(self):
a = array(1); b = array(2);
res=vstack([a,b])
desired = array([[1],[2]])
assert_array_equal(res,desired)
- def check_1D_array(self):
+
+ def test_1D_array(self):
a = array([1]); b = array([2]);
res=vstack([a,b])
desired = array([[1],[2]])
assert_array_equal(res,desired)
- def check_2D_array(self):
+
+ def test_2D_array(self):
a = array([[1],[2]]); b = array([[1],[2]]);
res=vstack([a,b])
desired = array([[1],[2],[1],[2]])
assert_array_equal(res,desired)
- def check_2D_array2(self):
+
+ def test_2D_array2(self):
a = array([1,2]); b = array([1,2]);
res=vstack([a,b])
desired = array([[1,2],[1,2]])
assert_array_equal(res,desired)
-class TestDstack(NumpyTestCase):
- def check_0D_array(self):
+class TestDstack(TestCase):
+ def test_0D_array(self):
a = array(1); b = array(2);
res=dstack([a,b])
desired = array([[[1,2]]])
assert_array_equal(res,desired)
- def check_1D_array(self):
+
+ def test_1D_array(self):
a = array([1]); b = array([2]);
res=dstack([a,b])
desired = array([[[1,2]]])
assert_array_equal(res,desired)
- def check_2D_array(self):
+
+ def test_2D_array(self):
a = array([[1],[2]]); b = array([[1],[2]]);
res=dstack([a,b])
desired = array([[[1,1]],[[2,2,]]])
assert_array_equal(res,desired)
- def check_2D_array2(self):
+
+ def test_2D_array2(self):
a = array([1,2]); b = array([1,2]);
res=dstack([a,b])
desired = array([[[1,1],[2,2]]])
@@ -286,49 +315,54 @@ class TestDstack(NumpyTestCase):
""" array_split has more comprehensive test of splitting.
only do simple test on hsplit, vsplit, and dsplit
"""
-class TestHsplit(NumpyTestCase):
+class TestHsplit(TestCase):
""" only testing for integer splits.
"""
- def check_0D_array(self):
+ def test_0D_array(self):
a= array(1)
try:
hsplit(a,2)
assert(0)
except ValueError:
pass
- def check_1D_array(self):
+
+ def test_1D_array(self):
a= array([1,2,3,4])
res = hsplit(a,2)
desired = [array([1,2]),array([3,4])]
compare_results(res,desired)
- def check_2D_array(self):
+
+ def test_2D_array(self):
a= array([[1,2,3,4],
[1,2,3,4]])
res = hsplit(a,2)
desired = [array([[1,2],[1,2]]),array([[3,4],[3,4]])]
compare_results(res,desired)
-class TestVsplit(NumpyTestCase):
+
+class TestVsplit(TestCase):
""" only testing for integer splits.
"""
- def check_1D_array(self):
+ def test_1D_array(self):
a= array([1,2,3,4])
try:
vsplit(a,2)
assert(0)
except ValueError:
pass
- def check_2D_array(self):
+
+ def test_2D_array(self):
a= array([[1,2,3,4],
[1,2,3,4]])
res = vsplit(a,2)
desired = [array([[1,2,3,4]]),array([[1,2,3,4]])]
compare_results(res,desired)
-class TestDsplit(NumpyTestCase):
+
+class TestDsplit(TestCase):
""" only testing for integer splits.
"""
- def check_2D_array(self):
+ def test_2D_array(self):
a= array([[1,2,3,4],
[1,2,3,4]])
try:
@@ -336,7 +370,8 @@ class TestDsplit(NumpyTestCase):
assert(0)
except ValueError:
pass
- def check_3D_array(self):
+
+ def test_3D_array(self):
a= array([[[1,2,3,4],
[1,2,3,4]],
[[1,2,3,4],
@@ -346,8 +381,9 @@ class TestDsplit(NumpyTestCase):
array([[[3,4],[3,4]],[[3,4],[3,4]]])]
compare_results(res,desired)
-class TestSqueeze(NumpyTestCase):
- def check_basic(self):
+
+class TestSqueeze(TestCase):
+ def test_basic(self):
a = rand(20,10,10,1,1)
b = rand(20,1,10,1,20)
c = rand(1,1,20,10)
@@ -355,8 +391,9 @@ class TestSqueeze(NumpyTestCase):
assert_array_equal(squeeze(b),reshape(b,(20,10,20)))
assert_array_equal(squeeze(c),reshape(c,(20,10)))
-class TestKron(NumpyTestCase):
- def check_return_type(self):
+
+class TestKron(TestCase):
+ def test_return_type(self):
a = ones([2,2])
m = asmatrix(a)
assert_equal(type(kron(a,a)), ndarray)
@@ -372,8 +409,8 @@ class TestKron(NumpyTestCase):
assert_equal(type(kron(ma,a)), myarray)
-class TestTile(NumpyTestCase):
- def check_basic(self):
+class TestTile(TestCase):
+ def test_basic(self):
a = array([0,1,2])
b = [[1,2],[3,4]]
assert_equal(tile(a,2), [0,1,2,0,1,2])
@@ -384,12 +421,12 @@ class TestTile(NumpyTestCase):
assert_equal(tile(b,(2,2)),[[1,2,1,2],[3,4,3,4],
[1,2,1,2],[3,4,3,4]])
- def check_empty(self):
+ def test_empty(self):
a = array([[[]]])
d = tile(a,(3,2,5)).shape
assert_equal(d,(3,2,0))
- def check_kroncompare(self):
+ def test_kroncompare(self):
import numpy.random as nr
reps=[(2,),(1,2),(2,1),(2,2),(2,3,2),(3,2)]
shape=[(3,),(2,3),(3,4,3),(3,2,3),(4,3,2,4),(2,2)]
@@ -401,12 +438,12 @@ class TestTile(NumpyTestCase):
klarge = kron(a, b)
assert_equal(large, klarge)
-# Utility
+# Utility
def compare_results(res,desired):
for i in range(len(desired)):
assert_array_equal(res[i],desired[i])
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/lib/tests/test_twodim_base.py b/numpy/lib/tests/test_twodim_base.py
index 3a9e8df80..33a685bcf 100644
--- a/numpy/lib/tests/test_twodim_base.py
+++ b/numpy/lib/tests/test_twodim_base.py
@@ -17,8 +17,8 @@ def get_mat(n):
data = add.outer(data,data)
return data
-class TestEye(NumpyTestCase):
- def check_basic(self):
+class TestEye(TestCase):
+ def test_basic(self):
assert_equal(eye(4),array([[1,0,0,0],
[0,1,0,0],
[0,0,1,0],
@@ -29,7 +29,7 @@ class TestEye(NumpyTestCase):
[0,0,0,1]],'f'))
assert_equal(eye(3) == 1, eye(3,dtype=bool))
- def check_diag(self):
+ def test_diag(self):
assert_equal(eye(4,k=1),array([[0,1,0,0],
[0,0,1,0],
[0,0,0,1],
@@ -38,7 +38,7 @@ class TestEye(NumpyTestCase):
[1,0,0,0],
[0,1,0,0],
[0,0,1,0]]))
- def check_2d(self):
+ def test_2d(self):
assert_equal(eye(4,3),array([[1,0,0],
[0,1,0],
[0,0,1],
@@ -46,7 +46,7 @@ class TestEye(NumpyTestCase):
assert_equal(eye(3,4),array([[1,0,0,0],
[0,1,0,0],
[0,0,1,0]]))
- def check_diag2d(self):
+ def test_diag2d(self):
assert_equal(eye(3,4,k=2),array([[0,0,1,0],
[0,0,0,1],
[0,0,0,0]]))
@@ -55,8 +55,8 @@ class TestEye(NumpyTestCase):
[1,0,0],
[0,1,0]]))
-class TestDiag(NumpyTestCase):
- def check_vector(self):
+class TestDiag(TestCase):
+ def test_vector(self):
vals = (100*arange(5)).astype('l')
b = zeros((5,5))
for k in range(5):
@@ -70,7 +70,7 @@ class TestDiag(NumpyTestCase):
assert_equal(diag(vals,k=2), b)
assert_equal(diag(vals,k=-2), c)
- def check_matrix(self):
+ def test_matrix(self):
vals = (100*get_mat(5)+1).astype('l')
b = zeros((5,))
for k in range(5):
@@ -84,8 +84,8 @@ class TestDiag(NumpyTestCase):
b[k] = vals[k+2,k]
assert_equal(diag(vals,-2),b[:3])
-class TestFliplr(NumpyTestCase):
- def check_basic(self):
+class TestFliplr(TestCase):
+ def test_basic(self):
self.failUnlessRaises(ValueError, fliplr, ones(4))
a = get_mat(4)
b = a[:,::-1]
@@ -96,8 +96,8 @@ class TestFliplr(NumpyTestCase):
[5,4,3]]
assert_equal(fliplr(a),b)
-class TestFlipud(NumpyTestCase):
- def check_basic(self):
+class TestFlipud(TestCase):
+ def test_basic(self):
a = get_mat(4)
b = a[::-1,:]
assert_equal(flipud(a),b)
@@ -107,8 +107,8 @@ class TestFlipud(NumpyTestCase):
[0,1,2]]
assert_equal(flipud(a),b)
-class TestRot90(NumpyTestCase):
- def check_basic(self):
+class TestRot90(TestCase):
+ def test_basic(self):
self.failUnlessRaises(ValueError, rot90, ones(4))
a = [[0,1,2],
@@ -133,12 +133,12 @@ class TestRot90(NumpyTestCase):
for k in range(0,13,4):
assert_equal(rot90(a,k=k),b4)
- def check_axes(self):
+ def test_axes(self):
a = ones((50,40,3))
assert_equal(rot90(a).shape,(40,50,3))
-class TestHistogram2d(NumpyTestCase):
- def check_simple(self):
+class TestHistogram2d(TestCase):
+ def test_simple(self):
x = array([ 0.41702200, 0.72032449, 0.00011437481, 0.302332573, 0.146755891])
y = array([ 0.09233859, 0.18626021, 0.34556073, 0.39676747, 0.53881673])
xedges = np.linspace(0,1,10)
@@ -161,7 +161,7 @@ class TestHistogram2d(NumpyTestCase):
assert_array_equal(xedges, np.linspace(0,9,11))
assert_array_equal(yedges, np.linspace(0,9,11))
- def check_asym(self):
+ def test_asym(self):
x = array([1, 1, 2, 3, 4, 4, 4, 5])
y = array([1, 3, 2, 0, 1, 2, 3, 4])
H, xed, yed = histogram2d(x,y, (6, 5), range = [[0,6],[0,5]], normed=True)
@@ -174,7 +174,7 @@ class TestHistogram2d(NumpyTestCase):
assert_array_almost_equal(H, answer/8., 3)
assert_array_equal(xed, np.linspace(0,6,7))
assert_array_equal(yed, np.linspace(0,5,6))
- def check_norm(self):
+ def test_norm(self):
x = array([1,2,3,1,2,3,1,2,3])
y = array([1,1,1,2,2,2,3,3,3])
H, xed, yed = histogram2d(x,y,[[1,2,3,5], [1,2,3,5]], normed=True)
@@ -183,12 +183,13 @@ class TestHistogram2d(NumpyTestCase):
[.5,.5,.25]])/9.
assert_array_almost_equal(H, answer, 3)
- def check_all_outliers(self):
+ def test_all_outliers(self):
r = rand(100)+1.
H, xed, yed = histogram2d(r, r, (4, 5), range=([0,1], [0,1]))
assert_array_equal(H, 0)
-class TestTri(NumpyTestCase):
+
+class TestTri(TestCase):
def test_dtype(self):
out = array([[1,0,0],
[1,1,0],
@@ -196,5 +197,6 @@ class TestTri(NumpyTestCase):
assert_array_equal(tri(3),out)
assert_array_equal(tri(3,dtype=bool),out.astype(bool))
+
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/lib/tests/test_type_check.py b/numpy/lib/tests/test_type_check.py
index 633c34dc8..80f112427 100644
--- a/numpy/lib/tests/test_type_check.py
+++ b/numpy/lib/tests/test_type_check.py
@@ -10,9 +10,9 @@ restore_path()
def assert_all(x):
assert(all(x)), x
-class TestMintypecode(NumpyTestCase):
+class TestMintypecode(TestCase):
- def check_default_1(self):
+ def test_default_1(self):
for itype in '1bcsuwil':
assert_equal(mintypecode(itype),'d')
assert_equal(mintypecode('f'),'f')
@@ -20,7 +20,7 @@ class TestMintypecode(NumpyTestCase):
assert_equal(mintypecode('F'),'F')
assert_equal(mintypecode('D'),'D')
- def check_default_2(self):
+ def test_default_2(self):
for itype in '1bcsuwil':
assert_equal(mintypecode(itype+'f'),'f')
assert_equal(mintypecode(itype+'d'),'d')
@@ -45,7 +45,7 @@ class TestMintypecode(NumpyTestCase):
assert_equal(mintypecode('DF'),'D')
assert_equal(mintypecode('DD'),'D')
- def check_default_3(self):
+ def test_default_3(self):
assert_equal(mintypecode('fdF'),'D')
#assert_equal(mintypecode('fdF',savespace=1),'F')
assert_equal(mintypecode('fdD'),'D')
@@ -59,8 +59,8 @@ class TestMintypecode(NumpyTestCase):
#assert_equal(mintypecode('idF',savespace=1),'F')
assert_equal(mintypecode('idD'),'D')
-class TestIsscalar(NumpyTestCase):
- def check_basic(self):
+class TestIsscalar(TestCase):
+ def test_basic(self):
assert(isscalar(3))
assert(not isscalar([3]))
assert(not isscalar((3,)))
@@ -68,145 +68,145 @@ class TestIsscalar(NumpyTestCase):
assert(isscalar(10L))
assert(isscalar(4.0))
-class TestReal(NumpyTestCase):
- def check_real(self):
+class TestReal(TestCase):
+ def test_real(self):
y = rand(10,)
assert_array_equal(y,real(y))
- def check_cmplx(self):
+ def test_cmplx(self):
y = rand(10,)+1j*rand(10,)
assert_array_equal(y.real,real(y))
-class TestImag(NumpyTestCase):
- def check_real(self):
+class TestImag(TestCase):
+ def test_real(self):
y = rand(10,)
assert_array_equal(0,imag(y))
- def check_cmplx(self):
+ def test_cmplx(self):
y = rand(10,)+1j*rand(10,)
assert_array_equal(y.imag,imag(y))
-class TestIscomplex(NumpyTestCase):
- def check_fail(self):
+class TestIscomplex(TestCase):
+ def test_fail(self):
z = array([-1,0,1])
res = iscomplex(z)
assert(not sometrue(res,axis=0))
- def check_pass(self):
+ def test_pass(self):
z = array([-1j,1,0])
res = iscomplex(z)
assert_array_equal(res,[1,0,0])
-class TestIsreal(NumpyTestCase):
- def check_pass(self):
+class TestIsreal(TestCase):
+ def test_pass(self):
z = array([-1,0,1j])
res = isreal(z)
assert_array_equal(res,[1,1,0])
- def check_fail(self):
+ def test_fail(self):
z = array([-1j,1,0])
res = isreal(z)
assert_array_equal(res,[0,1,1])
-class TestIscomplexobj(NumpyTestCase):
- def check_basic(self):
+class TestIscomplexobj(TestCase):
+ def test_basic(self):
z = array([-1,0,1])
assert(not iscomplexobj(z))
z = array([-1j,0,-1])
assert(iscomplexobj(z))
-class TestIsrealobj(NumpyTestCase):
- def check_basic(self):
+class TestIsrealobj(TestCase):
+ def test_basic(self):
z = array([-1,0,1])
assert(isrealobj(z))
z = array([-1j,0,-1])
assert(not isrealobj(z))
-class TestIsnan(NumpyTestCase):
- def check_goodvalues(self):
+class TestIsnan(TestCase):
+ def test_goodvalues(self):
z = array((-1.,0.,1.))
res = isnan(z) == 0
assert_all(alltrue(res,axis=0))
- def check_posinf(self):
+ def test_posinf(self):
olderr = seterr(divide='ignore')
assert_all(isnan(array((1.,))/0.) == 0)
seterr(**olderr)
- def check_neginf(self):
+ def test_neginf(self):
olderr = seterr(divide='ignore')
assert_all(isnan(array((-1.,))/0.) == 0)
seterr(**olderr)
- def check_ind(self):
+ def test_ind(self):
olderr = seterr(divide='ignore', invalid='ignore')
assert_all(isnan(array((0.,))/0.) == 1)
seterr(**olderr)
- #def check_qnan(self): log(-1) return pi*j now
+ #def test_qnan(self): log(-1) return pi*j now
# assert_all(isnan(log(-1.)) == 1)
- def check_integer(self):
+ def test_integer(self):
assert_all(isnan(1) == 0)
- def check_complex(self):
+ def test_complex(self):
assert_all(isnan(1+1j) == 0)
- def check_complex1(self):
+ def test_complex1(self):
olderr = seterr(divide='ignore', invalid='ignore')
assert_all(isnan(array(0+0j)/0.) == 1)
seterr(**olderr)
-class TestIsfinite(NumpyTestCase):
- def check_goodvalues(self):
+class TestIsfinite(TestCase):
+ def test_goodvalues(self):
z = array((-1.,0.,1.))
res = isfinite(z) == 1
assert_all(alltrue(res,axis=0))
- def check_posinf(self):
+ def test_posinf(self):
olderr = seterr(divide='ignore')
assert_all(isfinite(array((1.,))/0.) == 0)
seterr(**olderr)
- def check_neginf(self):
+ def test_neginf(self):
olderr = seterr(divide='ignore')
assert_all(isfinite(array((-1.,))/0.) == 0)
seterr(**olderr)
- def check_ind(self):
+ def test_ind(self):
olderr = seterr(divide='ignore', invalid='ignore')
assert_all(isfinite(array((0.,))/0.) == 0)
seterr(**olderr)
- #def check_qnan(self):
+ #def test_qnan(self):
# assert_all(isfinite(log(-1.)) == 0)
- def check_integer(self):
+ def test_integer(self):
assert_all(isfinite(1) == 1)
- def check_complex(self):
+ def test_complex(self):
assert_all(isfinite(1+1j) == 1)
- def check_complex1(self):
+ def test_complex1(self):
olderr = seterr(divide='ignore', invalid='ignore')
assert_all(isfinite(array(1+1j)/0.) == 0)
seterr(**olderr)
-class TestIsinf(NumpyTestCase):
- def check_goodvalues(self):
+class TestIsinf(TestCase):
+ def test_goodvalues(self):
z = array((-1.,0.,1.))
res = isinf(z) == 0
assert_all(alltrue(res,axis=0))
- def check_posinf(self):
+ def test_posinf(self):
olderr = seterr(divide='ignore')
assert_all(isinf(array((1.,))/0.) == 1)
seterr(**olderr)
- def check_posinf_scalar(self):
+ def test_posinf_scalar(self):
olderr = seterr(divide='ignore')
assert_all(isinf(array(1.,)/0.) == 1)
seterr(**olderr)
- def check_neginf(self):
+ def test_neginf(self):
olderr = seterr(divide='ignore')
assert_all(isinf(array((-1.,))/0.) == 1)
seterr(**olderr)
- def check_neginf_scalar(self):
+ def test_neginf_scalar(self):
olderr = seterr(divide='ignore')
assert_all(isinf(array(-1.)/0.) == 1)
seterr(**olderr)
- def check_ind(self):
+ def test_ind(self):
olderr = seterr(divide='ignore', invalid='ignore')
assert_all(isinf(array((0.,))/0.) == 0)
seterr(**olderr)
- #def check_qnan(self):
+ #def test_qnan(self):
# assert_all(isinf(log(-1.)) == 0)
# assert_all(isnan(log(-1.)) == 1)
-class TestIsposinf(NumpyTestCase):
- def check_generic(self):
+class TestIsposinf(TestCase):
+ def test_generic(self):
olderr = seterr(divide='ignore', invalid='ignore')
vals = isposinf(array((-1.,0,1))/0.)
seterr(**olderr)
@@ -214,8 +214,8 @@ class TestIsposinf(NumpyTestCase):
assert(vals[1] == 0)
assert(vals[2] == 1)
-class TestIsneginf(NumpyTestCase):
- def check_generic(self):
+class TestIsneginf(TestCase):
+ def test_generic(self):
olderr = seterr(divide='ignore', invalid='ignore')
vals = isneginf(array((-1.,0,1))/0.)
seterr(**olderr)
@@ -223,21 +223,21 @@ class TestIsneginf(NumpyTestCase):
assert(vals[1] == 0)
assert(vals[2] == 0)
-class TestNanToNum(NumpyTestCase):
- def check_generic(self):
+class TestNanToNum(TestCase):
+ def test_generic(self):
olderr = seterr(divide='ignore', invalid='ignore')
vals = nan_to_num(array((-1.,0,1))/0.)
seterr(**olderr)
assert_all(vals[0] < -1e10) and assert_all(isfinite(vals[0]))
assert(vals[1] == 0)
assert_all(vals[2] > 1e10) and assert_all(isfinite(vals[2]))
- def check_integer(self):
+ def test_integer(self):
vals = nan_to_num(1)
assert_all(vals == 1)
- def check_complex_good(self):
+ def test_complex_good(self):
vals = nan_to_num(1+1j)
assert_all(vals == 1+1j)
- def check_complex_bad(self):
+ def test_complex_bad(self):
v = 1+1j
olderr = seterr(divide='ignore', invalid='ignore')
v += array(0+1.j)/0.
@@ -245,7 +245,7 @@ class TestNanToNum(NumpyTestCase):
vals = nan_to_num(v)
# !! This is actually (unexpectedly) zero
assert_all(isfinite(vals))
- def check_complex_bad2(self):
+ def test_complex_bad2(self):
v = 1+1j
olderr = seterr(divide='ignore', invalid='ignore')
v += array(-1+1.j)/0.
@@ -259,8 +259,8 @@ class TestNanToNum(NumpyTestCase):
#assert_all(vals.real < -1e10) and assert_all(isfinite(vals))
-class TestRealIfClose(NumpyTestCase):
- def check_basic(self):
+class TestRealIfClose(TestCase):
+ def test_basic(self):
a = rand(10)
b = real_if_close(a+1e-15j)
assert_all(isrealobj(b))
@@ -270,11 +270,12 @@ class TestRealIfClose(NumpyTestCase):
b = real_if_close(a+1e-7j,tol=1e-6)
assert_all(isrealobj(b))
-class TestArrayConversion(NumpyTestCase):
- def check_asfarray(self):
+class TestArrayConversion(TestCase):
+ def test_asfarray(self):
a = asfarray(array([1,2,3]))
assert_equal(a.__class__,ndarray)
assert issubdtype(a.dtype,float)
+
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/lib/tests/test_ufunclike.py b/numpy/lib/tests/test_ufunclike.py
index 926439fb4..f734355bd 100644
--- a/numpy/lib/tests/test_ufunclike.py
+++ b/numpy/lib/tests/test_ufunclike.py
@@ -59,8 +59,10 @@ array([ 2.169925 , 1.20163386, 2.70043972])
from numpy.testing import *
-class TestDocs(NumpyTestCase):
- def check_doctests(self): return self.rundocs()
+class TestDocs(TestCase):
+ def test_doctests(self):
+ return rundocs()
+
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/linalg/__init__.py b/numpy/linalg/__init__.py
index 85d81d0a8..842c791d2 100644
--- a/numpy/linalg/__init__.py
+++ b/numpy/linalg/__init__.py
@@ -3,6 +3,6 @@ from info import __doc__
from linalg import *
-def test(level=1, verbosity=1):
- from numpy.testing import NumpyTest
- return NumpyTest().test(level, verbosity)
+from numpy.testing.pkgtester import Tester
+test = Tester().test
+bench = Tester().test
diff --git a/numpy/linalg/tests/test_linalg.py b/numpy/linalg/tests/test_linalg.py
index d7c3a63ca..58c5cd456 100644
--- a/numpy/linalg/tests/test_linalg.py
+++ b/numpy/linalg/tests/test_linalg.py
@@ -23,28 +23,28 @@ def assert_almost_equal(a, b, **kw):
decimal = 12
old_assert_almost_equal(a, b, decimal=decimal, **kw)
-class LinalgTestCase(NumpyTestCase):
- def check_single(self):
+class LinalgTestCase:
+ def test_single(self):
a = array([[1.,2.], [3.,4.]], dtype=single)
b = array([2., 1.], dtype=single)
self.do(a, b)
- def check_double(self):
+ def test_double(self):
a = array([[1.,2.], [3.,4.]], dtype=double)
b = array([2., 1.], dtype=double)
self.do(a, b)
- def check_csingle(self):
+ def test_csingle(self):
a = array([[1.+2j,2+3j], [3+4j,4+5j]], dtype=csingle)
b = array([2.+1j, 1.+2j], dtype=csingle)
self.do(a, b)
- def check_cdouble(self):
+ def test_cdouble(self):
a = array([[1.+2j,2+3j], [3+4j,4+5j]], dtype=cdouble)
b = array([2.+1j, 1.+2j], dtype=cdouble)
self.do(a, b)
- def check_empty(self):
+ def test_empty(self):
a = atleast_2d(array([], dtype = double))
b = atleast_2d(array([], dtype = double))
try:
@@ -53,79 +53,79 @@ class LinalgTestCase(NumpyTestCase):
except linalg.LinAlgError, e:
pass
- def check_nonarray(self):
+ def test_nonarray(self):
a = [[1,2], [3,4]]
b = [2, 1]
self.do(a,b)
- def check_matrix_b_only(self):
+ def test_matrix_b_only(self):
"""Check that matrix type is preserved."""
a = array([[1.,2.], [3.,4.]])
b = matrix([2., 1.]).T
self.do(a, b)
- def check_matrix_a_and_b(self):
+ def test_matrix_a_and_b(self):
"""Check that matrix type is preserved."""
a = matrix([[1.,2.], [3.,4.]])
b = matrix([2., 1.]).T
self.do(a, b)
-class TestSolve(LinalgTestCase):
+class TestSolve(LinalgTestCase, TestCase):
def do(self, a, b):
x = linalg.solve(a, b)
assert_almost_equal(b, dot(a, x))
assert imply(isinstance(b, matrix), isinstance(x, matrix))
-class TestInv(LinalgTestCase):
+class TestInv(LinalgTestCase, TestCase):
def do(self, a, b):
a_inv = linalg.inv(a)
assert_almost_equal(dot(a, a_inv), identity(asarray(a).shape[0]))
assert imply(isinstance(a, matrix), isinstance(a_inv, matrix))
-class TestEigvals(LinalgTestCase):
+class TestEigvals(LinalgTestCase, TestCase):
def do(self, a, b):
ev = linalg.eigvals(a)
evalues, evectors = linalg.eig(a)
assert_almost_equal(ev, evalues)
-class TestEig(LinalgTestCase):
+class TestEig(LinalgTestCase, TestCase):
def do(self, a, b):
evalues, evectors = linalg.eig(a)
assert_almost_equal(dot(a, evectors), multiply(evectors, evalues))
assert imply(isinstance(a, matrix), isinstance(evectors, matrix))
-class TestSVD(LinalgTestCase):
+class TestSVD(LinalgTestCase, TestCase):
def do(self, a, b):
u, s, vt = linalg.svd(a, 0)
assert_almost_equal(a, dot(multiply(u, s), vt))
assert imply(isinstance(a, matrix), isinstance(u, matrix))
assert imply(isinstance(a, matrix), isinstance(vt, matrix))
-class TestCondSVD(LinalgTestCase):
+class TestCondSVD(LinalgTestCase, TestCase):
def do(self, a, b):
c = asarray(a) # a might be a matrix
s = linalg.svd(c, compute_uv=False)
old_assert_almost_equal(s[0]/s[-1], linalg.cond(a), decimal=5)
-class TestCond2(LinalgTestCase):
+class TestCond2(LinalgTestCase, TestCase):
def do(self, a, b):
c = asarray(a) # a might be a matrix
s = linalg.svd(c, compute_uv=False)
old_assert_almost_equal(s[0]/s[-1], linalg.cond(a,2), decimal=5)
-class TestCondInf(NumpyTestCase):
+class TestCondInf(TestCase):
def test(self):
A = array([[1.,0,0],[0,-2.,0],[0,0,3.]])
assert_almost_equal(linalg.cond(A,inf),3.)
-class TestPinv(LinalgTestCase):
+class TestPinv(LinalgTestCase, TestCase):
def do(self, a, b):
a_ginv = linalg.pinv(a)
assert_almost_equal(dot(a, a_ginv), identity(asarray(a).shape[0]))
assert imply(isinstance(a, matrix), isinstance(a_ginv, matrix))
-class TestDet(LinalgTestCase):
+class TestDet(LinalgTestCase, TestCase):
def do(self, a, b):
d = linalg.det(a)
if asarray(a).dtype.type in (single, double):
@@ -135,7 +135,7 @@ class TestDet(LinalgTestCase):
ev = linalg.eigvals(ad)
assert_almost_equal(d, multiply.reduce(ev))
-class TestLstsq(LinalgTestCase):
+class TestLstsq(LinalgTestCase, TestCase):
def do(self, a, b):
u, s, vt = linalg.svd(a, 0)
x, residuals, rank, sv = linalg.lstsq(a, b)
@@ -145,7 +145,7 @@ class TestLstsq(LinalgTestCase):
assert imply(isinstance(b, matrix), isinstance(x, matrix))
assert imply(isinstance(b, matrix), isinstance(residuals, matrix))
-class TestMatrixPower(ParametricTestCase):
+class TestMatrixPower(TestCase):
R90 = array([[0,1],[-1,0]])
Arb22 = array([[4,-7],[-2,10]])
noninv = array([[1,0],[0,0]])
@@ -158,6 +158,7 @@ class TestMatrixPower(ParametricTestCase):
def test_large_power(self):
assert_equal(matrix_power(self.R90,2L**100+2**10+2**5+1),self.R90)
+
def test_large_power_trailing_zero(self):
assert_equal(matrix_power(self.R90,2L**100+2**10+2**5),identity(2))
@@ -197,10 +198,11 @@ class TestMatrixPower(ParametricTestCase):
self.assertRaises(numpy.linalg.linalg.LinAlgError,
lambda: matrix_power(self.noninv,-1))
-class TestBoolPower(NumpyTestCase):
- def check_square(self):
+class TestBoolPower(TestCase):
+ def test_square(self):
A = array([[True,False],[True,True]])
assert_equal(matrix_power(A,2),A)
-if __name__ == '__main__':
- NumpyTest().run()
+
+if __name__ == "__main__":
+ nose.run(argv=['', __file__])
diff --git a/numpy/linalg/tests/test_regression.py b/numpy/linalg/tests/test_regression.py
index 7a2588000..ec9bc695f 100644
--- a/numpy/linalg/tests/test_regression.py
+++ b/numpy/linalg/tests/test_regression.py
@@ -9,7 +9,7 @@ restore_path()
rlevel = 1
-class TestRegression(NumpyTestCase):
+class TestRegression(TestCase):
def test_eig_build(self, level = rlevel):
"""Ticket #652"""
rva = array([1.03221168e+02 +0.j,
@@ -54,5 +54,6 @@ class TestRegression(NumpyTestCase):
assert_array_almost_equal(b, np.zeros((2, 2)))
+
if __name__ == '__main__':
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/ma/__init__.py b/numpy/ma/__init__.py
index ccbb6d3c6..bdf7f6f7a 100644
--- a/numpy/ma/__init__.py
+++ b/numpy/ma/__init__.py
@@ -20,3 +20,7 @@ from extras import *
__all__ = ['core', 'extras']
__all__ += core.__all__
__all__ += extras.__all__
+
+from numpy.testing.pkgtester import Tester
+test = Tester().test
+bench = Tester().bench
diff --git a/numpy/ma/tests/test_core.py b/numpy/ma/tests/test_core.py
index 4558777dd..bc9168082 100644
--- a/numpy/ma/tests/test_core.py
+++ b/numpy/ma/tests/test_core.py
@@ -12,34 +12,17 @@ import warnings
import numpy as np
import numpy.core.fromnumeric as fromnumeric
from numpy import ndarray
+from numpy.ma.testutils import *
-
-from numpy.testing import NumpyTest, NumpyTestCase
-from numpy.testing import set_local_path, restore_path
-from numpy.testing.utils import build_err_msg
-
-import numpy.ma.testutils
-from numpy.ma.testutils import NumpyTestCase, \
- assert_equal, assert_array_equal, fail_if_equal, assert_not_equal, \
- assert_almost_equal, assert_mask_equal, assert_equal_records
-
-import numpy.ma.core as coremodule
+import numpy.ma.core
from numpy.ma.core import *
pi = np.pi
-set_local_path()
-from test_old_ma import *
-restore_path()
-
#..............................................................................
-class TestMaskedArray(NumpyTestCase):
+class TestMaskedArray(TestCase):
"Base test class for MaskedArrays."
- def __init__(self, *args, **kwds):
- NumpyTestCase.__init__(self, *args, **kwds)
- self.setUp()
-
def setUp (self):
"Base data definition."
x = np.array([1.,1.,1.,-2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
@@ -443,7 +426,7 @@ class TestMaskedArray(NumpyTestCase):
#------------------------------------------------------------------------------
-class TestMaskedArrayArithmetic(NumpyTestCase):
+class TestMaskedArrayArithmetic(TestCase):
"Base test class for MaskedArrays."
def setUp (self):
@@ -616,7 +599,7 @@ class TestMaskedArrayArithmetic(NumpyTestCase):
for funcname in ('min', 'max'):
# Initialize
npfunc = getattr(np, funcname)
- mafunc = getattr(coremodule, funcname)
+ mafunc = getattr(numpy.ma.core, funcname)
# Use the np version
nout = np.empty((4,), dtype=int)
result = npfunc(xm,axis=0,out=nout)
@@ -730,7 +713,7 @@ class TestMaskedArrayArithmetic(NumpyTestCase):
#------------------------------------------------------------------------------
-class TestMaskedArrayAttributes(NumpyTestCase):
+class TestMaskedArrayAttributes(TestCase):
def test_keepmask(self):
@@ -828,7 +811,7 @@ class TestMaskedArrayAttributes(NumpyTestCase):
#------------------------------------------------------------------------------
-class TestFillingValues(NumpyTestCase):
+class TestFillingValues(TestCase):
#
def test_check_on_scalar(self):
"Test _check_fill_value"
@@ -922,7 +905,7 @@ class TestFillingValues(NumpyTestCase):
assert_equal(series._fill_value, data._fill_value)
#
mtype = [('f',float_),('s','|S3')]
- x = array([(1,'a'),(2,'b'),(np.pi,'pi')], dtype=mtype)
+ x = array([(1,'a'),(2,'b'),(pi,'pi')], dtype=mtype)
x.fill_value=999
assert_equal(x.fill_value.item(),[999.,'999'])
assert_equal(x['f'].fill_value, 999)
@@ -938,9 +921,10 @@ class TestFillingValues(NumpyTestCase):
assert_equal(np.asarray(x.fill_value).dtype, float_)
assert_equal(x.fill_value, 999.)
+
#------------------------------------------------------------------------------
-class TestUfuncs(NumpyTestCase):
+class TestUfuncs(TestCase):
"Test class for the application of ufuncs on MaskedArrays."
def setUp(self):
"Base data definition."
@@ -972,7 +956,7 @@ class TestUfuncs(NumpyTestCase):
uf = getattr(umath, f)
except AttributeError:
uf = getattr(fromnumeric, f)
- mf = getattr(coremodule, f)
+ mf = getattr(numpy.ma.core, f)
args = self.d[:uf.nin]
ur = uf(*args)
mr = mf(*args)
@@ -1002,7 +986,7 @@ class TestUfuncs(NumpyTestCase):
#------------------------------------------------------------------------------
-class TestMaskedArrayInPlaceArithmetics(NumpyTestCase):
+class TestMaskedArrayInPlaceArithmetics(TestCase):
"Test MaskedArray Arithmetics"
def setUp(self):
@@ -1134,7 +1118,7 @@ class TestMaskedArrayInPlaceArithmetics(NumpyTestCase):
#------------------------------------------------------------------------------
-class TestMaskedArrayMethods(NumpyTestCase):
+class TestMaskedArrayMethods(TestCase):
"Test class for miscellaneous MaskedArrays methods."
def setUp(self):
"Base data definition."
@@ -1630,7 +1614,7 @@ class TestMaskedArrayMethods(NumpyTestCase):
#------------------------------------------------------------------------------
-class TestMaskArrayMathMethod(NumpyTestCase):
+class TestMaskArrayMathMethod(TestCase):
def setUp(self):
"Base data definition."
@@ -1781,7 +1765,7 @@ class TestMaskArrayMathMethod(NumpyTestCase):
#------------------------------------------------------------------------------
-class TestMaskedArrayMathMethodsComplex(NumpyTestCase):
+class TestMaskedArrayMathMethodsComplex(TestCase):
"Test class for miscellaneous MaskedArrays methods."
def setUp(self):
"Base data definition."
@@ -1834,7 +1818,7 @@ class TestMaskedArrayMathMethodsComplex(NumpyTestCase):
#------------------------------------------------------------------------------
-class TestMaskedArrayFunctions(NumpyTestCase):
+class TestMaskedArrayFunctions(TestCase):
"Test class for miscellaneous functions."
#
def setUp(self):
@@ -2090,7 +2074,7 @@ class TestMaskedArrayFunctions(NumpyTestCase):
#------------------------------------------------------------------------------
-class TestMaskedFields(NumpyTestCase):
+class TestMaskedFields(TestCase):
#
def setUp(self):
ilist = [1,2,3,4,5]
@@ -2125,13 +2109,13 @@ class TestMaskedFields(NumpyTestCase):
"Check setting an element of a record)"
base = self.data['base']
(base_a, base_b, base_c) = (base['a'], base['b'], base['c'])
- base[0] = (np.pi, np.pi, 'pi')
+ base[0] = (pi, pi, 'pi')
assert_equal(base_a.dtype, int)
assert_equal(base_a.data, [3,2,3,4,5])
assert_equal(base_b.dtype, float)
- assert_equal(base_b.data, [np.pi, 2.2, 3.3, 4.4, 5.5])
+ assert_equal(base_b.data, [pi, 2.2, 3.3, 4.4, 5.5])
assert_equal(base_c.dtype, '|S8')
assert_equal(base_c.data, ['pi','two','three','four','five'])
@@ -2139,13 +2123,13 @@ class TestMaskedFields(NumpyTestCase):
def test_set_record_slice(self):
base = self.data['base']
(base_a, base_b, base_c) = (base['a'], base['b'], base['c'])
- base[:3] = (np.pi, np.pi, 'pi')
+ base[:3] = (pi, pi, 'pi')
assert_equal(base_a.dtype, int)
assert_equal(base_a.data, [3,3,3,4,5])
assert_equal(base_b.dtype, float)
- assert_equal(base_b.data, [np.pi, np.pi, np.pi, 4.4, 5.5])
+ assert_equal(base_b.data, [pi, pi, pi, 4.4, 5.5])
assert_equal(base_c.dtype, '|S8')
assert_equal(base_c.data, ['pi','pi','pi','four','five'])
@@ -2163,4 +2147,4 @@ class TestMaskedFields(NumpyTestCase):
###############################################################################
#------------------------------------------------------------------------------
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/ma/tests/test_extras.py b/numpy/ma/tests/test_extras.py
index 805800c53..722b88cb0 100644
--- a/numpy/ma/tests/test_extras.py
+++ b/numpy/ma/tests/test_extras.py
@@ -11,21 +11,15 @@ __version__ = '1.0'
__revision__ = "$Revision: 3473 $"
__date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $'
-import numpy as np
-from numpy.testing import NumpyTest, NumpyTestCase
-from numpy.testing.utils import build_err_msg
-
-import numpy.ma.testutils
+import numpy
+from numpy.testing import *
from numpy.ma.testutils import *
-
-import numpy.ma.core
from numpy.ma.core import *
-import numpy.ma.extras
from numpy.ma.extras import *
-class TestAverage(NumpyTestCase):
+class TestAverage(TestCase):
"Several tests of average. Why so many ? Good point..."
- def check_testAverage1(self):
+ def test_testAverage1(self):
"Test of average."
ott = array([0.,1.,2.,3.], mask=[1,0,0,0])
assert_equal(2.0, average(ott,axis=0))
@@ -44,7 +38,7 @@ class TestAverage(NumpyTestCase):
result, wts = average(ott, axis=0, returned=1)
assert_equal(wts, [1., 0.])
- def check_testAverage2(self):
+ def test_testAverage2(self):
"More tests of average."
w1 = [0,1,1,1,1,0]
w2 = [[0,1,1,1,1,0],[1,0,0,0,0,1]]
@@ -77,7 +71,7 @@ class TestAverage(NumpyTestCase):
assert_equal(average(z, axis=1), [2.5, 5.0])
assert_equal(average(z,axis=0, weights=w2), [0.,1., 99., 99., 4.0, 10.0])
- def check_testAverage3(self):
+ def test_testAverage3(self):
"Yet more tests of average!"
a = arange(6)
b = arange(6) * 3
@@ -101,9 +95,9 @@ class TestAverage(NumpyTestCase):
a2dma = average(a2dm, axis=1)
assert_equal(a2dma, [1.5, 4.0])
-class TestConcatenator(NumpyTestCase):
+class TestConcatenator(TestCase):
"Tests for mr_, the equivalent of r_ for masked arrays."
- def check_1d(self):
+ def test_1d(self):
"Tests mr_ on 1D arrays."
assert_array_equal(mr_[1,2,3,4,5,6],array([1,2,3,4,5,6]))
b = ones(5)
@@ -114,7 +108,7 @@ class TestConcatenator(NumpyTestCase):
assert_array_equal(c,[1,1,1,1,1,0,0,1,1,1,1,1])
assert_array_equal(c.mask, mr_[m,0,0,m])
- def check_2d(self):
+ def test_2d(self):
"Tests mr_ on 2D arrays."
a_1 = rand(5,5)
a_2 = rand(5,5)
@@ -133,9 +127,9 @@ class TestConcatenator(NumpyTestCase):
assert_array_equal(d[5:,:],b_2)
assert_array_equal(d.mask, np.r_[m_1,m_2])
-class TestNotMasked(NumpyTestCase):
+class TestNotMasked(TestCase):
"Tests notmasked_edges and notmasked_contiguous."
- def check_edges(self):
+ def test_edges(self):
"Tests unmasked_edges"
a = masked_array(np.arange(24).reshape(3,8),
mask=[[0,0,0,0,1,1,1,0],
@@ -152,7 +146,7 @@ class TestNotMasked(NumpyTestCase):
assert_equal(tmp[0], (array([0,2,]), array([0,0])))
assert_equal(tmp[1], (array([0,2,]), array([7,7])))
- def check_contiguous(self):
+ def test_contiguous(self):
"Tests notmasked_contiguous"
a = masked_array(np.arange(24).reshape(3,8),
mask=[[0,0,0,0,1,1,1,1],
@@ -175,9 +169,9 @@ class TestNotMasked(NumpyTestCase):
assert_equal(tmp[2][-1], slice(7,7,None))
assert_equal(tmp[2][-2], slice(0,5,None))
-class Test2DFunctions(NumpyTestCase):
+class Test2DFunctions(TestCase):
"Tests 2D functions"
- def check_compress2d(self):
+ def test_compress2d(self):
"Tests compress2d"
x = array(np.arange(9).reshape(3,3), mask=[[1,0,0],[0,0,0],[0,0,0]])
assert_equal(compress_rowcols(x), [[4,5],[7,8]] )
@@ -196,7 +190,7 @@ class Test2DFunctions(NumpyTestCase):
assert_equal(compress_rowcols(x,0).size, 0 )
assert_equal(compress_rowcols(x,1).size, 0 )
#
- def check_mask_rowcols(self):
+ def test_mask_rowcols(self):
"Tests mask_rowcols."
x = array(np.arange(9).reshape(3,3), mask=[[1,0,0],[0,0,0],[0,0,0]])
assert_equal(mask_rowcols(x).mask, [[1,1,1],[1,0,0],[1,0,0]] )
@@ -322,19 +316,16 @@ class Test2DFunctions(NumpyTestCase):
assert_equal(dx._data, np.r_[0,difx_d,0])
assert_equal(dx._mask, np.r_[1,0,0,0,0,1])
-class TestApplyAlongAxis(NumpyTestCase):
+class TestApplyAlongAxis(TestCase):
"Tests 2D functions"
- def check_3d(self):
+ def test_3d(self):
a = arange(12.).reshape(2,2,3)
def myfunc(b):
return b[1]
xa = apply_along_axis(myfunc,2,a)
assert_equal(xa,[[1,4],[7,10]])
-class TestMedian(NumpyTestCase):
- def __init__(self, *args, **kwds):
- NumpyTestCase.__init__(self, *args, **kwds)
- #
+class TestMedian(TestCase):
def test_2d(self):
"Tests median w/ 2D"
(n,p) = (101,30)
@@ -361,7 +352,7 @@ class TestMedian(NumpyTestCase):
assert_equal(median(x,0), [[12,10],[8,9],[16,17]])
-class TestPolynomial(NumpyTestCase):
+class TestPolynomial(TestCase):
#
def test_polyfit(self):
"Tests polyfit"
@@ -394,4 +385,4 @@ class TestPolynomial(NumpyTestCase):
###############################################################################
#------------------------------------------------------------------------------
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/ma/tests/test_mrecords.py b/numpy/ma/tests/test_mrecords.py
index f9a246410..9083d227c 100644
--- a/numpy/ma/tests/test_mrecords.py
+++ b/numpy/ma/tests/test_mrecords.py
@@ -27,10 +27,10 @@ from numpy.ma.mrecords import MaskedRecords, mrecarray,\
fromarrays, fromtextfile, fromrecords, addfield
#..............................................................................
-class TestMRecords(NumpyTestCase):
+class TestMRecords(TestCase):
"Base test class for MaskedArrays."
def __init__(self, *args, **kwds):
- NumpyTestCase.__init__(self, *args, **kwds)
+ TestCase.__init__(self, *args, **kwds)
self.setup()
def setup(self):
@@ -318,10 +318,10 @@ class TestMRecords(NumpyTestCase):
[(1,1.1,None),(2,2.2,'two'),(None,None,'three')])
################################################################################
-class TestMRecordsImport(NumpyTestCase):
+class TestMRecordsImport(TestCase):
"Base test class for MaskedArrays."
def __init__(self, *args, **kwds):
- NumpyTestCase.__init__(self, *args, **kwds)
+ TestCase.__init__(self, *args, **kwds)
self.setup()
def setup(self):
@@ -429,4 +429,4 @@ class TestMRecordsImport(NumpyTestCase):
###############################################################################
#------------------------------------------------------------------------------
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/ma/tests/test_old_ma.py b/numpy/ma/tests/test_old_ma.py
index 02afabdc4..81d68df5a 100644
--- a/numpy/ma/tests/test_old_ma.py
+++ b/numpy/ma/tests/test_old_ma.py
@@ -3,7 +3,8 @@ import types, time
from numpy.ma import *
from numpy.core.numerictypes import float32
from numpy.ma.core import umath
-from numpy.testing import NumpyTestCase, NumpyTest
+from numpy.testing import *
+
pi = numpy.pi
def eq(v,w, msg=''):
result = allclose(v,w)
@@ -14,11 +15,7 @@ def eq(v,w, msg=''):
%s"""% (msg, str(v), str(w))
return result
-class TestMa(NumpyTestCase):
- def __init__(self, *args, **kwds):
- NumpyTestCase.__init__(self, *args, **kwds)
- self.setUp()
-
+class TestMa(TestCase):
def setUp (self):
x=numpy.array([1.,1.,1.,-2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
y=numpy.array([5.,0.,3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
@@ -34,7 +31,7 @@ class TestMa(NumpyTestCase):
xm.set_fill_value(1.e+20)
self.d = (x, y, a10, m1, m2, xm, ym, z, zm, xf, s)
- def check_testBasic1d(self):
+ def test_testBasic1d(self):
"Test of basic array creation and properties in 1 dimension."
(x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
self.failIf(isMaskedArray(x))
@@ -48,7 +45,7 @@ class TestMa(NumpyTestCase):
self.failUnless(eq(filled(xm, 1.e20), xf))
self.failUnless(eq(x, xm))
- def check_testBasic2d(self):
+ def test_testBasic2d(self):
"Test of basic array creation and properties in 2 dimensions."
for s in [(4,3), (6,2)]:
(x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
@@ -69,7 +66,7 @@ class TestMa(NumpyTestCase):
self.failUnless(eq(x, xm))
self.setUp()
- def check_testArithmetic (self):
+ def test_testArithmetic (self):
"Test of basic arithmetic."
(x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
a2d = array([[1,2],[0,4]])
@@ -111,13 +108,13 @@ class TestMa(NumpyTestCase):
numpy.seterr(**olderr)
- def check_testMixedArithmetic(self):
+ def test_testMixedArithmetic(self):
na = numpy.array([1])
ma = array([1])
self.failUnless(isinstance(na + ma, MaskedArray))
self.failUnless(isinstance(ma + na, MaskedArray))
- def check_testUfuncs1 (self):
+ def test_testUfuncs1 (self):
"Test various functions such as sin, cos."
(x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
self.failUnless (eq(numpy.cos(x), cos(xm)))
@@ -149,7 +146,7 @@ class TestMa(NumpyTestCase):
self.failUnless (eq(numpy.concatenate((x,y)), concatenate((xm,y))))
self.failUnless (eq(numpy.concatenate((x,y,x)), concatenate((x,ym,x))))
- def check_xtestCount (self):
+ def test_xtestCount (self):
"Test count"
ott = array([0.,1.,2.,3.], mask=[1,0,0,0])
self.failUnless( isinstance(count(ott), types.IntType))
@@ -163,15 +160,19 @@ class TestMa(NumpyTestCase):
assert getmask(count(ott,0)) is nomask
self.failUnless (eq([1,2],count(ott,0)))
- def check_testMinMax (self):
+ def test_testMinMax (self):
"Test minimum and maximum."
(x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
xr = numpy.ravel(x) #max doesn't work if shaped
xmr = ravel(xm)
- self.failUnless (eq(max(xr), maximum(xmr))) #true because of careful selection of data
- self.failUnless (eq(min(xr), minimum(xmr))) #true because of careful selection of data
- def check_testAddSumProd (self):
+ #true because of careful selection of data
+ self.failUnless(eq(max(xr), maximum(xmr)))
+
+ #true because of careful selection of data
+ self.failUnless(eq(min(xr), minimum(xmr)))
+
+ def test_testAddSumProd (self):
"Test add, sum, product."
(x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
self.failUnless (eq(numpy.add.reduce(x), add.reduce(x)))
@@ -183,15 +184,17 @@ class TestMa(NumpyTestCase):
self.failUnless (eq(numpy.sum(x,0), sum(x,0)))
self.failUnless (eq(numpy.product(x,axis=0), product(x,axis=0)))
self.failUnless (eq(numpy.product(x,0), product(x,0)))
- self.failUnless (eq(numpy.product(filled(xm,1),axis=0), product(xm,axis=0)))
+ self.failUnless (eq(numpy.product(filled(xm,1),axis=0),
+ product(xm,axis=0)))
if len(s) > 1:
- self.failUnless (eq(numpy.concatenate((x,y),1), concatenate((xm,ym),1)))
+ self.failUnless (eq(numpy.concatenate((x,y),1),
+ concatenate((xm,ym),1)))
self.failUnless (eq(numpy.add.reduce(x,1), add.reduce(x,1)))
self.failUnless (eq(numpy.sum(x,1), sum(x,1)))
self.failUnless (eq(numpy.product(x,1), product(x,1)))
- def check_testCI(self):
+ def test_testCI(self):
"Test of conversions and indexing"
x1 = numpy.array([1,2,4,3])
x2 = array(x1, mask = [1,0,0,0])
@@ -240,7 +243,7 @@ class TestMa(NumpyTestCase):
self.assertEqual(s1, s2)
assert x1[1:1].shape == (0,)
- def check_testCopySize(self):
+ def test_testCopySize(self):
"Tests of some subtle points of copying and sizing."
n = [0,0,1,0,0]
m = make_mask(n)
@@ -279,7 +282,7 @@ class TestMa(NumpyTestCase):
y6 = repeat(x4, 2, axis=0)
self.failUnless( eq(y5, y6))
- def check_testPut(self):
+ def test_testPut(self):
"Test of put"
d = arange(5)
n = [0,0,0,1,1]
@@ -299,14 +302,14 @@ class TestMa(NumpyTestCase):
self.failUnless( x[3] is masked)
self.failUnless( x[4] is masked)
- def check_testMaPut(self):
+ def test_testMaPut(self):
(x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1]
i = numpy.nonzero(m)[0]
put(ym, i, zm)
assert all(take(ym, i, axis=0) == zm)
- def check_testOddFeatures(self):
+ def test_testOddFeatures(self):
"Test of other odd features"
x = arange(20); x=x.reshape(4,5)
x.flat[5] = 12
@@ -358,7 +361,8 @@ class TestMa(NumpyTestCase):
assert z[1] is not masked
assert z[2] is masked
assert eq(masked_where(greater(x, 2), x), masked_greater(x,2))
- assert eq(masked_where(greater_equal(x, 2), x), masked_greater_equal(x,2))
+ assert eq(masked_where(greater_equal(x, 2), x),
+ masked_greater_equal(x,2))
assert eq(masked_where(less(x, 2), x), masked_less(x,2))
assert eq(masked_where(less_equal(x, 2), x), masked_less_equal(x,2))
assert eq(masked_where(not_equal(x, 2), x), masked_not_equal(x,2))
@@ -366,10 +370,14 @@ class TestMa(NumpyTestCase):
assert eq(masked_where(not_equal(x,2), x), masked_not_equal(x,2))
assert eq(masked_inside(range(5), 1, 3), [0, 199, 199, 199, 4])
assert eq(masked_outside(range(5), 1, 3),[199,1,2,3,199])
- assert eq(masked_inside(array(range(5), mask=[1,0,0,0,0]), 1, 3).mask, [1,1,1,1,0])
- assert eq(masked_outside(array(range(5), mask=[0,1,0,0,0]), 1, 3).mask, [1,1,0,0,1])
- assert eq(masked_equal(array(range(5), mask=[1,0,0,0,0]), 2).mask, [1,0,1,0,0])
- assert eq(masked_not_equal(array([2,2,1,2,1], mask=[1,0,0,0,0]), 2).mask, [1,0,1,0,1])
+ assert eq(masked_inside(array(range(5), mask=[1,0,0,0,0]), 1, 3).mask,
+ [1,1,1,1,0])
+ assert eq(masked_outside(array(range(5), mask=[0,1,0,0,0]), 1, 3).mask,
+ [1,1,0,0,1])
+ assert eq(masked_equal(array(range(5), mask=[1,0,0,0,0]), 2).mask,
+ [1,0,1,0,0])
+ assert eq(masked_not_equal(array([2,2,1,2,1], mask=[1,0,0,0,0]), 2).mask,
+ [1,0,1,0,1])
assert eq(masked_where([1,1,0,0,0], [1,2,3,4,5]), [99,99,3,4,5])
atest = ones((10,10,10), dtype=float32)
btest = zeros(atest.shape, MaskType)
@@ -396,7 +404,7 @@ class TestMa(NumpyTestCase):
z = where(c, 1, masked)
assert eq(z, [99, 1, 1, 99, 99, 99])
- def check_testMinMax(self):
+ def test_testMinMax(self):
"Test of minumum, maximum."
assert eq(minimum([1,2,3],[4,0,9]), [1,0,3])
assert eq(maximum([1,2,3],[4,0,9]), [4,2,9])
@@ -409,7 +417,7 @@ class TestMa(NumpyTestCase):
assert minimum(x) == 0
assert maximum(x) == 4
- def check_testTakeTransposeInnerOuter(self):
+ def test_testTakeTransposeInnerOuter(self):
"Test of take, transpose, inner, outer products"
x = arange(24)
y = numpy.arange(24)
@@ -429,7 +437,7 @@ class TestMa(NumpyTestCase):
assert t[1] == 2
assert t[2] == 3
- def check_testInplace(self):
+ def test_testInplace(self):
"""Test of inplace operations and rich comparisons"""
y = arange(10)
@@ -479,7 +487,7 @@ class TestMa(NumpyTestCase):
x += 1.
assert eq(x, y+1.)
- def check_testPickle(self):
+ def test_testPickle(self):
"Test of pickling"
import pickle
x = arange(12)
@@ -489,7 +497,7 @@ class TestMa(NumpyTestCase):
y = pickle.loads(s)
assert eq(x,y)
- def check_testMasked(self):
+ def test_testMasked(self):
"Test of masked element"
xx=arange(6)
xx[1] = masked
@@ -502,7 +510,7 @@ class TestMa(NumpyTestCase):
#self.failUnlessRaises(Exception, lambda x,y: x+y, masked, xx)
#self.failUnlessRaises(Exception, lambda x,y: x+y, xx, masked)
- def check_testAverage1(self):
+ def test_testAverage1(self):
"Test of average."
ott = array([0.,1.,2.,3.], mask=[1,0,0,0])
self.failUnless(eq(2.0, average(ott,axis=0)))
@@ -521,7 +529,7 @@ class TestMa(NumpyTestCase):
result, wts = average(ott, axis=0, returned=1)
self.failUnless(eq(wts, [1., 0.]))
- def check_testAverage2(self):
+ def test_testAverage2(self):
"More tests of average."
w1 = [0,1,1,1,1,0]
w2 = [[0,1,1,1,1,0],[1,0,0,0,0,1]]
@@ -529,12 +537,16 @@ class TestMa(NumpyTestCase):
self.failUnless(allclose(average(x, axis=0), 2.5))
self.failUnless(allclose(average(x, axis=0, weights=w1), 2.5))
y=array([arange(6), 2.0*arange(6)])
- self.failUnless(allclose(average(y, None), numpy.add.reduce(numpy.arange(6))*3./12.))
+ self.failUnless(allclose(average(y, None),
+ numpy.add.reduce(numpy.arange(6))*3./12.))
self.failUnless(allclose(average(y, axis=0), numpy.arange(6) * 3./2.))
- self.failUnless(allclose(average(y, axis=1), [average(x,axis=0), average(x,axis=0) * 2.0]))
+ self.failUnless(allclose(average(y, axis=1),
+ [average(x,axis=0), average(x,axis=0) * 2.0]))
self.failUnless(allclose(average(y, None, weights=w2), 20./6.))
- self.failUnless(allclose(average(y, axis=0, weights=w2), [0.,1.,2.,3.,4.,10.]))
- self.failUnless(allclose(average(y, axis=1), [average(x,axis=0), average(x,axis=0) * 2.0]))
+ self.failUnless(allclose(average(y, axis=0, weights=w2),
+ [0.,1.,2.,3.,4.,10.]))
+ self.failUnless(allclose(average(y, axis=1),
+ [average(x,axis=0), average(x,axis=0) * 2.0]))
m1 = zeros(6)
m2 = [0,0,1,1,0,0]
m3 = [[0,0,1,1,0,0],[0,1,1,1,1,0]]
@@ -549,7 +561,8 @@ class TestMa(NumpyTestCase):
self.failUnless(allclose(average(z, None), 20./6.))
self.failUnless(allclose(average(z, axis=0), [0.,1.,99.,99.,4.0, 7.5]))
self.failUnless(allclose(average(z, axis=1), [2.5, 5.0]))
- self.failUnless(allclose( average(z,axis=0, weights=w2), [0.,1., 99., 99., 4.0, 10.0]))
+ self.failUnless(allclose( average(z,axis=0, weights=w2),
+ [0.,1., 99., 99., 4.0, 10.0]))
a = arange(6)
b = arange(6) * 3
@@ -573,7 +586,7 @@ class TestMa(NumpyTestCase):
a2dma = average(a2dm, axis=1)
self.failUnless(eq(a2dma, [1.5, 4.0]))
- def check_testToPython(self):
+ def test_testToPython(self):
self.assertEqual(1, int(array(1)))
self.assertEqual(1.0, float(array(1)))
self.assertEqual(1, int(array([[[1]]])))
@@ -582,7 +595,7 @@ class TestMa(NumpyTestCase):
self.failUnlessRaises(ValueError, bool, array([0,1]))
self.failUnlessRaises(ValueError, bool, array([0,0],mask=[0,1]))
- def check_testScalarArithmetic(self):
+ def test_testScalarArithmetic(self):
xm = array(0, mask=1)
self.failUnless((1/array(0)).mask)
self.failUnless((1 + xm).mask)
@@ -595,7 +608,7 @@ class TestMa(NumpyTestCase):
self.failUnless(x.filled() == x.data)
self.failUnlessEqual(str(xm), str(masked_print_option))
- def check_testArrayMethods(self):
+ def test_testArrayMethods(self):
a = array([1,3,2])
b = array([1,3,2], mask=[1,0,1])
self.failUnless(eq(a.any(), a.data.any()))
@@ -612,29 +625,29 @@ class TestMa(NumpyTestCase):
self.failUnless(eq(a.take([1,2]), a.data.take([1,2])))
self.failUnless(eq(m.transpose(), m.data.transpose()))
- def check_testArrayAttributes(self):
+ def test_testArrayAttributes(self):
a = array([1,3,2])
b = array([1,3,2], mask=[1,0,1])
self.failUnlessEqual(a.ndim, 1)
- def check_testAPI(self):
+ def test_testAPI(self):
self.failIf([m for m in dir(numpy.ndarray)
if m not in dir(MaskedArray) and not m.startswith('_')])
- def check_testSingleElementSubscript(self):
+ def test_testSingleElementSubscript(self):
a = array([1,3,2])
b = array([1,3,2], mask=[1,0,1])
self.failUnlessEqual(a[0].shape, ())
self.failUnlessEqual(b[0].shape, ())
self.failUnlessEqual(b[1].shape, ())
-class TestUfuncs(NumpyTestCase):
+class TestUfuncs(TestCase):
def setUp(self):
self.d = (array([1.0, 0, -1, pi/2]*2, mask=[0,1]+[0]*6),
array([1.0, 0, -1, pi/2]*2, mask=[1,0]+[0]*6),)
- def check_testUfuncRegression(self):
+ def test_testUfuncRegression(self):
for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate',
'sin', 'cos', 'tan',
'arcsin', 'arccos', 'arctan',
@@ -661,8 +674,11 @@ class TestUfuncs(NumpyTestCase):
mf = getattr(numpy.ma, f)
args = self.d[:uf.nin]
olderr = numpy.geterr()
- if f in ['sqrt', 'arctanh', 'arcsin', 'arccos', 'arccosh', 'arctanh', 'log',
- 'log10','divide','true_divide', 'floor_divide', 'remainder', 'fmod']:
+ f_invalid_ignore = ['sqrt', 'arctanh', 'arcsin', 'arccos',
+ 'arccosh', 'arctanh', 'log', 'log10','divide',
+ 'true_divide', 'floor_divide', 'remainder',
+ 'fmod']
+ if f in f_invalid_ignore:
numpy.seterr(invalid='ignore')
if f in ['arctanh', 'log', 'log10']:
numpy.seterr(divide='ignore')
@@ -695,7 +711,7 @@ class TestUfuncs(NumpyTestCase):
self.failUnless(eq(nonzero(x), [0]))
-class TestArrayMethods(NumpyTestCase):
+class TestArrayMethods(TestCase):
def setUp(self):
x = numpy.array([ 8.375, 7.545, 8.828, 8.5 , 1.757, 5.928,
@@ -799,56 +815,55 @@ def eqmask(m1, m2):
return m1 is nomask
return (m1 == m2).all()
-def timingTest():
- for f in [testf, testinplace]:
- for n in [1000,10000,50000]:
- t = testta(n, f)
- t1 = testtb(n, f)
- t2 = testtc(n, f)
- print f.test_name
- print """\
-n = %7d
-numpy time (ms) %6.1f
-MA maskless ratio %6.1f
-MA masked ratio %6.1f
-""" % (n, t*1000.0, t1/t, t2/t)
-
-def testta(n, f):
- x=numpy.arange(n) + 1.0
- tn0 = time.time()
- z = f(x)
- return time.time() - tn0
-
-def testtb(n, f):
- x=arange(n) + 1.0
- tn0 = time.time()
- z = f(x)
- return time.time() - tn0
-
-def testtc(n, f):
- x=arange(n) + 1.0
- x[0] = masked
- tn0 = time.time()
- z = f(x)
- return time.time() - tn0
-
-def testf(x):
- for i in range(25):
- y = x **2 + 2.0 * x - 1.0
- w = x **2 + 1.0
- z = (y / w) ** 2
- return z
-testf.test_name = 'Simple arithmetic'
-
-def testinplace(x):
- for i in range(25):
- y = x**2
- y += 2.0*x
- y -= 1.0
- y /= x
- return y
-testinplace.test_name = 'Inplace operations'
+#def timingTest():
+# for f in [testf, testinplace]:
+# for n in [1000,10000,50000]:
+# t = testta(n, f)
+# t1 = testtb(n, f)
+# t2 = testtc(n, f)
+# print f.test_name
+# print """\
+#n = %7d
+#numpy time (ms) %6.1f
+#MA maskless ratio %6.1f
+#MA masked ratio %6.1f
+#""" % (n, t*1000.0, t1/t, t2/t)
+
+#def testta(n, f):
+# x=numpy.arange(n) + 1.0
+# tn0 = time.time()
+# z = f(x)
+# return time.time() - tn0
+
+#def testtb(n, f):
+# x=arange(n) + 1.0
+# tn0 = time.time()
+# z = f(x)
+# return time.time() - tn0
+
+#def testtc(n, f):
+# x=arange(n) + 1.0
+# x[0] = masked
+# tn0 = time.time()
+# z = f(x)
+# return time.time() - tn0
+
+#def testf(x):
+# for i in range(25):
+# y = x **2 + 2.0 * x - 1.0
+# w = x **2 + 1.0
+# z = (y / w) ** 2
+# return z
+#testf.test_name = 'Simple arithmetic'
+
+#def testinplace(x):
+# for i in range(25):
+# y = x**2
+# y += 2.0*x
+# y -= 1.0
+# y /= x
+# return y
+#testinplace.test_name = 'Inplace operations'
if __name__ == "__main__":
- NumpyTest('numpy.ma').run()
- #timingTest()
+ nose.run(argv=['', __file__])
diff --git a/numpy/ma/tests/test_subclassing.py b/numpy/ma/tests/test_subclassing.py
index d3d95763c..d61087f01 100644
--- a/numpy/ma/tests/test_subclassing.py
+++ b/numpy/ma/tests/test_subclassing.py
@@ -13,15 +13,10 @@ __date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $'
import numpy as N
import numpy.core.numeric as numeric
-from numpy.testing import NumpyTest, NumpyTestCase
-
-import numpy.ma.testutils
+from numpy.testing import *
from numpy.ma.testutils import *
-
-import numpy.ma.core as coremodule
from numpy.ma.core import *
-
class SubArray(N.ndarray):
"""Defines a generic N.ndarray subclass, that stores some metadata
in the dictionary `info`."""
@@ -36,6 +31,7 @@ class SubArray(N.ndarray):
result = N.ndarray.__add__(self, other)
result.info.update({'added':result.info.pop('added',0)+1})
return result
+
subarray = SubArray
class MSubArray(SubArray,MaskedArray):
@@ -53,6 +49,7 @@ class MSubArray(SubArray,MaskedArray):
_view._sharedmask = False
return _view
_series = property(fget=_get_series)
+
msubarray = MSubArray
class MMatrix(MaskedArray, N.matrix,):
@@ -69,14 +66,13 @@ class MMatrix(MaskedArray, N.matrix,):
_view._sharedmask = False
return _view
_series = property(fget=_get_series)
-mmatrix = MMatrix
-
+mmatrix = MMatrix
-class TestSubclassing(NumpyTestCase):
+class TestSubclassing(TestCase):
"""Test suite for masked subclasses of ndarray."""
- def check_data_subclassing(self):
+ def test_data_subclassing(self):
"Tests whether the subclass is kept."
x = N.arange(5)
m = [0,0,1,0,0]
@@ -86,7 +82,7 @@ class TestSubclassing(NumpyTestCase):
assert_equal(xmsub._data, xsub)
assert isinstance(xmsub._data, SubArray)
- def check_maskedarray_subclassing(self):
+ def test_maskedarray_subclassing(self):
"Tests subclassing MaskedArray"
x = N.arange(5)
mx = mmatrix(x,mask=[0,1,0,0,0])
@@ -101,7 +97,7 @@ class TestSubclassing(NumpyTestCase):
assert isinstance(hypot(mx,mx), mmatrix)
assert isinstance(hypot(mx,x), mmatrix)
- def check_attributepropagation(self):
+ def test_attributepropagation(self):
x = array(arange(5), mask=[0]+[1]*4)
my = masked_array(subarray(x))
ym = msubarray(x)
@@ -128,7 +124,7 @@ class TestSubclassing(NumpyTestCase):
assert hasattr(mxsub, 'info')
assert_equal(mxsub.info, xsub.info)
- def check_subclasspreservation(self):
+ def test_subclasspreservation(self):
"Checks that masked_array(...,subok=True) preserves the class."
x = N.arange(5)
m = [0,0,1,0,0]
@@ -158,8 +154,8 @@ class TestSubclassing(NumpyTestCase):
################################################################################
if __name__ == '__main__':
- NumpyTest().run()
- #
+ nose.run(argv=['', __file__])
+
if 0:
x = array(arange(5), mask=[0]+[1]*4)
my = masked_array(subarray(x))
diff --git a/numpy/ma/testutils.py b/numpy/ma/testutils.py
index 83aec7ea2..f1749619d 100644
--- a/numpy/ma/testutils.py
+++ b/numpy/ma/testutils.py
@@ -15,9 +15,9 @@ import operator
import numpy as np
from numpy import ndarray, float_
import numpy.core.umath as umath
-from numpy.testing import NumpyTest, NumpyTestCase
-import numpy.testing.utils as utils
+from numpy.testing import *
from numpy.testing.utils import build_err_msg, rand
+import numpy.testing.utils as utils
import core
from core import mask_or, getmask, getmaskarray, masked_array, nomask, masked
@@ -166,9 +166,9 @@ def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='',
raise ValueError(msg)
# OK, now run the basic tests on filled versions
return utils.assert_array_compare(comparison,
- x.filled(fill_value), y.filled(fill_value),
- err_msg=err_msg,
- verbose=verbose, header=header)
+ x.filled(fill_value), y.filled(fill_value),
+ err_msg=err_msg,
+ verbose=verbose, header=header)
def assert_array_equal(x, y, err_msg='', verbose=True):
diff --git a/numpy/numarray/__init__.py b/numpy/numarray/__init__.py
index b0819d127..b7736db3c 100644
--- a/numpy/numarray/__init__.py
+++ b/numpy/numarray/__init__.py
@@ -24,3 +24,7 @@ del util
del functions
del ufuncs
del compat
+
+from numpy.testing.pkgtester import Tester
+test = Tester().test
+bench = Tester().bench
diff --git a/numpy/oldnumeric/__init__.py b/numpy/oldnumeric/__init__.py
index 83819ad04..ad30ba68e 100644
--- a/numpy/oldnumeric/__init__.py
+++ b/numpy/oldnumeric/__init__.py
@@ -39,3 +39,7 @@ del functions
del precision
del ufuncs
del misc
+
+from numpy.testing.pkgtester import Tester
+test = Tester().test
+bench = Tester().bench
diff --git a/numpy/oldnumeric/tests/test_oldnumeric.py b/numpy/oldnumeric/tests/test_oldnumeric.py
index 628ec231f..6e641c756 100644
--- a/numpy/oldnumeric/tests/test_oldnumeric.py
+++ b/numpy/oldnumeric/tests/test_oldnumeric.py
@@ -6,7 +6,7 @@ from numpy.core.numeric import float32, float64, complex64, complex128, int8, \
int16, int32, int64, uint, uint8, uint16, uint32, uint64
class test_oldtypes(NumPyTestCase):
- def check_oldtypes(self, level=1):
+ def test_oldtypes(self, level=1):
a1 = array([0,1,0], Float)
a2 = array([0,1,0], float)
assert_array_equal(a1, a2)
@@ -83,4 +83,4 @@ class test_oldtypes(NumPyTestCase):
if __name__ == "__main__":
- NumPyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/random/__init__.py b/numpy/random/__init__.py
index 5a7423208..723285874 100644
--- a/numpy/random/__init__.py
+++ b/numpy/random/__init__.py
@@ -13,6 +13,6 @@ def __RandomState_ctor():
"""
return RandomState()
-def test(level=1, verbosity=1):
- from numpy.testing import NumpyTest
- return NumpyTest().test(level, verbosity)
+from numpy.testing.pkgtester import Tester
+test = Tester().test
+bench = Tester().bench
diff --git a/numpy/random/tests/test_random.py b/numpy/random/tests/test_random.py
index 793803252..c42b02442 100644
--- a/numpy/random/tests/test_random.py
+++ b/numpy/random/tests/test_random.py
@@ -2,7 +2,7 @@ from numpy.testing import *
from numpy import random
import numpy as np
-class TestMultinomial(NumpyTestCase):
+class TestMultinomial(TestCase):
def test_basic(self):
random.multinomial(100, [0.2, 0.8])
@@ -16,7 +16,7 @@ class TestMultinomial(NumpyTestCase):
assert np.all(x < -1)
-class TestSetState(NumpyTestCase):
+class TestSetState(TestCase):
def setUp(self):
self.seed = 1234567890
self.prng = random.RandomState(self.seed)
@@ -62,4 +62,4 @@ class TestSetState(NumpyTestCase):
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])
diff --git a/numpy/testing/__init__.py b/numpy/testing/__init__.py
index 87578fca0..fa448f298 100644
--- a/numpy/testing/__init__.py
+++ b/numpy/testing/__init__.py
@@ -1,5 +1,23 @@
+"""Common test support for all numpy test scripts.
-from info import __doc__
-from numpytest import *
+This single module should provide all the common functionality for numpy tests
+in a single location, so that test scripts can just import it and work right
+away.
+"""
+
+#import unittest
+from unittest import TestCase
+
+import decorators as dec
from utils import *
-from parametric import ParametricTestCase
+
+try:
+ import nose
+ from nose.tools import raises
+except ImportError:
+ pass
+
+from numpytest import *
+
+from pkgtester import Tester
+test = Tester().test
diff --git a/numpy/testing/decorators.py b/numpy/testing/decorators.py
new file mode 100644
index 000000000..6573c2a43
--- /dev/null
+++ b/numpy/testing/decorators.py
@@ -0,0 +1,92 @@
+"""Decorators for labeling test objects
+
+Decorators that merely return a modified version of the original
+function object are straightforward. Decorators that return a new
+function object need to use
+nose.tools.make_decorator(original_function)(decorator) in returning
+the decorator, in order to preserve metadata such as function name,
+setup and teardown functions and so on - see nose.tools for more
+information.
+
+"""
+
+try:
+ import nose
+except ImportError:
+ pass
+
+def slow(t):
+ """Labels a test as 'slow'.
+
+ The exact definition of a slow test is obviously both subjective and
+ hardware-dependent, but in general any individual test that requires more
+ than a second or two should be labeled as slow (the whole suite consits of
+ thousands of tests, so even a second is significant)."""
+
+ t.slow = True
+ return t
+
+def setastest(tf=True):
+ ''' Signals to nose that this function is or is not a test
+
+ Parameters
+ ----------
+ tf : bool
+ If True specifies this is a test, not a test otherwise
+
+ e.g
+ >>> @setastest(False)
+ >>> def func_with_test_in_name(arg1, arg2): pass
+ ...
+ >>>
+
+ This decorator cannot use the nose namespace, because it can be
+ called from a non-test module. See also istest and nottest in
+ nose.tools
+
+ '''
+ def set_test(t):
+ t.__test__ = tf
+ return t
+ return set_test
+
+def skipif(skip_condition, msg=None):
+ ''' Make function raise SkipTest exception if skip_condition is true
+
+ Parameters
+ ---------
+ skip_condition : bool
+ Flag to determine whether to skip test (True) or not (False)
+ msg : string
+ Message to give on raising a SkipTest exception
+
+ Returns
+ -------
+ decorator : function
+ Decorator, which, when applied to a function, causes SkipTest
+ to be raised when the skip_condition was True, and the function
+ to be called normally otherwise.
+
+ Notes
+ -----
+ You will see from the code that we had to further decorate the
+ decorator with the nose.tools.make_decorator function in order to
+ transmit function name, and various other metadata.
+ '''
+ if msg is None:
+ msg = 'Test skipped due to test condition'
+ def skip_decorator(f):
+ def skipper(*args, **kwargs):
+ if skip_condition:
+ raise nose.SkipTest, msg
+ else:
+ return f(*args, **kwargs)
+ return nose.tools.make_decorator(f)(skipper)
+ return skip_decorator
+
+def skipknownfailure(f):
+ ''' Decorator to raise SkipTest for test known to fail
+ '''
+ def skipper(*args, **kwargs):
+ raise nose.SkipTest, 'This test is known to fail'
+ return nose.tools.make_decorator(f)(skipper)
diff --git a/numpy/testing/info.py b/numpy/testing/info.py
deleted file mode 100644
index 8b09d8ed3..000000000
--- a/numpy/testing/info.py
+++ /dev/null
@@ -1,30 +0,0 @@
-"""
-Numpy testing tools
-===================
-
-Numpy-style unit-testing
-------------------------
-
- NumpyTest -- Numpy tests site manager
- NumpyTestCase -- unittest.TestCase with measure method
- IgnoreException -- raise when checking disabled feature, it'll be ignored
- set_package_path -- prepend package build directory to path
- set_local_path -- prepend local directory (to tests files) to path
- restore_path -- restore path after set_package_path
-
-Utility functions
------------------
-
- jiffies -- return 1/100ths of a second that the current process has used
- memusage -- virtual memory size in bytes of the running python [linux]
- rand -- array of random numbers from given shape
- assert_equal -- assert equality
- assert_almost_equal -- assert equality with decimal tolerance
- assert_approx_equal -- assert equality with significant digits tolerance
- assert_array_equal -- assert arrays equality
- assert_array_almost_equal -- assert arrays equality with decimal tolerance
- assert_array_less -- assert arrays less-ordering
-
-"""
-
-global_symbols = ['ScipyTest','NumpyTest']
diff --git a/numpy/testing/nosetester.py b/numpy/testing/nosetester.py
new file mode 100644
index 000000000..e0a0aad3f
--- /dev/null
+++ b/numpy/testing/nosetester.py
@@ -0,0 +1,140 @@
+''' Nose test running
+
+Implements test and bench functions for modules.
+
+'''
+import os
+import sys
+import re
+
+import nose
+
+class NoseTester(object):
+ """ Nose test runner.
+
+ Usage: NoseTester(<package>).test()
+
+ <package> is package path or module Default for package is None. A
+ value of None finds calling module path.
+
+ Typical call is from module __init__, and corresponds to this:
+
+ >>> test = NoseTester().test
+
+ In practice, because nose may not be importable, the __init__
+ files actually have:
+
+ >>> from scipy.testing.pkgtester import Tester
+ >>> test = Tester().test
+
+ The pkgtester module checks for the presence of nose on the path,
+ returning this class if nose is present, and a null class
+ otherwise.
+ """
+
+ def __init__(self, package=None):
+ ''' Test class init
+
+ Parameters
+ ----------
+ package : string or module
+ If string, gives full path to package
+ If None, extract calling module path
+ Default is None
+ '''
+ if package is None:
+ f = sys._getframe(1)
+ package = f.f_locals.get('__file__', None)
+ assert package is not None
+ package = os.path.dirname(package)
+ elif isinstance(package, type(os)):
+ package = os.path.dirname(package.__file__)
+ self.package_path = package
+
+ def _add_doc(testtype):
+ ''' Decorator to add docstring to functions using test labels
+
+ Parameters
+ ----------
+ testtype : string
+ Type of test for function docstring
+ '''
+ def docit(func):
+ test_header = \
+ '''Parameters
+ ----------
+ label : {'fast', 'full', '', attribute identifer}
+ Identifies %(testtype)s to run. This can be a string to pass to
+ the nosetests executable with the'-A' option, or one of
+ several special values.
+ Special values are:
+ 'fast' - the default - which corresponds to
+ nosetests -A option of
+ 'not slow'.
+ 'full' - fast (as above) and slow %(testtype)s as in
+ no -A option to nosetests - same as ''
+ None or '' - run all %(testtype)ss
+ attribute_identifier - string passed directly to
+ nosetests as '-A'
+ verbose : integer
+ verbosity value for test outputs, 1-10
+ extra_argv : list
+ List with any extra args to pass to nosetests''' \
+ % {'testtype': testtype}
+ func.__doc__ = func.__doc__ % {
+ 'test_header': test_header}
+ return func
+ return docit
+
+ @_add_doc('(testtype)')
+ def _test_argv(self, label, verbose, extra_argv):
+ ''' Generate argv for nosetest command
+
+ %(test_header)s
+ '''
+ argv = [__file__, self.package_path, '-s']
+ if label and label != 'full':
+ if not isinstance(label, basestring):
+ raise TypeError, 'Selection label should be a string'
+ if label == 'fast':
+ label = 'not slow'
+ argv += ['-A', label]
+ argv += ['--verbosity', str(verbose)]
+ if extra_argv:
+ argv += extra_argv
+ return argv
+
+ @_add_doc('test')
+ def test(self, label='fast', verbose=1, extra_argv=None, doctests=False,
+ coverage=False):
+ ''' Run tests for module using nose
+
+ %(test_header)s
+ doctests : boolean
+ If True, run doctests in module, default False
+ '''
+ argv = self._test_argv(label, verbose, extra_argv)
+ if doctests:
+ argv+=['--with-doctest','--doctest-tests']
+
+ if coverage:
+ argv+=['--cover-package=numpy','--with-coverage',
+ '--cover-tests','--cover-inclusive','--cover-erase']
+
+ # bypass these samples under distutils
+ argv += ['--exclude','f2py_ext']
+ argv += ['--exclude','f2py_f90_ext']
+ argv += ['--exclude','gen_ext']
+ argv += ['--exclude','pyrex_ext']
+ argv += ['--exclude','swig_ext']
+
+ nose.run(argv=argv)
+
+ @_add_doc('benchmark')
+ def bench(self, label='fast', verbose=1, extra_argv=None):
+ ''' Run benchmarks for module using nose
+
+ %(test_header)s'''
+ argv = self._test_argv(label, verbose, extra_argv)
+ argv += ['--match', r'(?:^|[\\b_\\.%s-])[Bb]ench' % os.sep]
+ nose.run(argv=argv)
diff --git a/numpy/testing/nulltester.py b/numpy/testing/nulltester.py
new file mode 100644
index 000000000..50d5484f6
--- /dev/null
+++ b/numpy/testing/nulltester.py
@@ -0,0 +1,15 @@
+''' Null tester to signal nose tests disabled
+
+Merely returns error reporting lack of nose package or version number
+below requirements.
+
+See pkgtester, nosetester modules
+
+'''
+
+class NullTester(object):
+ def test(self, labels=None, *args, **kwargs):
+ raise ImportError, \
+ 'Need nose >=0.10 for tests - see %s' % \
+ 'http://somethingaboutorange.com/mrl/projects/nose'
+ bench = test
diff --git a/numpy/testing/numpytest.py b/numpy/testing/numpytest.py
index 4792f035b..73002f92f 100644
--- a/numpy/testing/numpytest.py
+++ b/numpy/testing/numpytest.py
@@ -10,10 +10,7 @@ import traceback
import warnings
__all__ = ['set_package_path', 'set_local_path', 'restore_path',
- 'IgnoreException', 'NumpyTestCase', 'NumpyTest',
- 'ScipyTestCase', 'ScipyTest', # for backward compatibility
- 'importall',
- ]
+ 'IgnoreException', 'importall',]
DEBUG=0
from numpy.testing.utils import jiffies
@@ -113,95 +110,6 @@ class _dummy_stream:
self.stream.flush()
-class NumpyTestCase (unittest.TestCase):
-
- def measure(self,code_str,times=1):
- """ Return elapsed time for executing code_str in the
- namespace of the caller for given times.
- """
- frame = get_frame(1)
- locs,globs = frame.f_locals,frame.f_globals
- code = compile(code_str,
- 'NumpyTestCase runner for '+self.__class__.__name__,
- 'exec')
- i = 0
- elapsed = jiffies()
- while i<times:
- i += 1
- exec code in globs,locs
- elapsed = jiffies() - elapsed
- return 0.01*elapsed
-
- def __call__(self, result=None):
- if result is None or not hasattr(result, 'errors') \
- or not hasattr(result, 'stream'):
- return unittest.TestCase.__call__(self, result)
-
- nof_errors = len(result.errors)
- save_stream = result.stream
- result.stream = _dummy_stream(save_stream)
- unittest.TestCase.__call__(self, result)
- if nof_errors != len(result.errors):
- test, errstr = result.errors[-1][:2]
- if isinstance(errstr, tuple):
- errstr = str(errstr[0])
- elif isinstance(errstr, str):
- errstr = errstr.split('\n')[-2]
- else:
- # allow for proxy classes
- errstr = str(errstr).split('\n')[-2]
- l = len(result.stream.data)
- if errstr.startswith('IgnoreException:'):
- if l==1:
- assert result.stream.data[-1]=='E', \
- repr(result.stream.data)
- result.stream.data[-1] = 'i'
- else:
- assert result.stream.data[-1]=='ERROR\n', \
- repr(result.stream.data)
- result.stream.data[-1] = 'ignoring\n'
- del result.errors[-1]
- map(save_stream.write, result.stream.data)
- save_stream.flush()
- result.stream = save_stream
-
- def warn(self, message):
- from numpy.distutils.misc_util import yellow_text
- print>>sys.stderr,yellow_text('Warning: %s' % (message))
- sys.stderr.flush()
- def info(self, message):
- print>>sys.stdout, message
- sys.stdout.flush()
-
- def rundocs(self, filename=None):
- """ Run doc string tests found in filename.
- """
- import doctest
- if filename is None:
- f = get_frame(1)
- filename = f.f_globals['__file__']
- name = os.path.splitext(os.path.basename(filename))[0]
- path = [os.path.dirname(filename)]
- file, pathname, description = imp.find_module(name, path)
- try:
- m = imp.load_module(name, file, pathname, description)
- finally:
- file.close()
- if sys.version[:3]<'2.4':
- doctest.testmod(m, verbose=False)
- else:
- tests = doctest.DocTestFinder().find(m)
- runner = doctest.DocTestRunner(verbose=False)
- for test in tests:
- runner.run(test)
- return
-
-class ScipyTestCase(NumpyTestCase):
- def __init__(self, package=None):
- warnings.warn("ScipyTestCase is now called NumpyTestCase; please update your code",
- DeprecationWarning, stacklevel=2)
- NumpyTestCase.__init__(self, package)
-
def _get_all_method_names(cls):
names = dir(cls)
@@ -214,460 +122,6 @@ def _get_all_method_names(cls):
# for debug build--check for memory leaks during the test.
-class _NumPyTextTestResult(unittest._TextTestResult):
- def startTest(self, test):
- unittest._TextTestResult.startTest(self, test)
- if self.showAll:
- N = len(sys.getobjects(0))
- self._totnumobj = N
- self._totrefcnt = sys.gettotalrefcount()
- return
-
- def stopTest(self, test):
- if self.showAll:
- N = len(sys.getobjects(0))
- self.stream.write("objects: %d ===> %d; " % (self._totnumobj, N))
- self.stream.write("refcnts: %d ===> %d\n" % (self._totrefcnt,
- sys.gettotalrefcount()))
- return
-
-class NumPyTextTestRunner(unittest.TextTestRunner):
- def _makeResult(self):
- return _NumPyTextTestResult(self.stream, self.descriptions, self.verbosity)
-
-
-class NumpyTest:
- """ Numpy tests site manager.
-
- Usage: NumpyTest(<package>).test(level=1,verbosity=1)
-
- <package> is package name or its module object.
-
- Package is supposed to contain a directory tests/ with test_*.py
- files where * refers to the names of submodules. See .rename()
- method to redefine name mapping between test_*.py files and names of
- submodules. Pattern test_*.py can be overwritten by redefining
- .get_testfile() method.
-
- test_*.py files are supposed to define a classes, derived from
- NumpyTestCase or unittest.TestCase, with methods having names
- starting with test or bench or check. The names of TestCase classes
- must have a prefix test. This can be overwritten by redefining
- .check_testcase_name() method.
-
- And that is it! No need to implement test or test_suite functions
- in each .py file.
-
- Old-style test_suite(level=1) hooks are also supported.
- """
- _check_testcase_name = re.compile(r'test.*|Test.*').match
- def check_testcase_name(self, name):
- """ Return True if name matches TestCase class.
- """
- return not not self._check_testcase_name(name)
-
- testfile_patterns = ['test_%(modulename)s.py']
- def get_testfile(self, module, verbosity = 0):
- """ Return path to module test file.
- """
- mstr = self._module_str
- short_module_name = self._get_short_module_name(module)
- d = os.path.split(module.__file__)[0]
- test_dir = os.path.join(d,'tests')
- local_test_dir = os.path.join(os.getcwd(),'tests')
- if os.path.basename(os.path.dirname(local_test_dir)) \
- == os.path.basename(os.path.dirname(test_dir)):
- test_dir = local_test_dir
- for pat in self.testfile_patterns:
- fn = os.path.join(test_dir, pat % {'modulename':short_module_name})
- if os.path.isfile(fn):
- return fn
- if verbosity>1:
- self.warn('No test file found in %s for module %s' \
- % (test_dir, mstr(module)))
- return
-
- def __init__(self, package=None):
- if package is None:
- from numpy.distutils.misc_util import get_frame
- f = get_frame(1)
- package = f.f_locals.get('__name__',f.f_globals.get('__name__',None))
- assert package is not None
- self.package = package
- self._rename_map = {}
-
- def rename(self, **kws):
- """Apply renaming submodule test file test_<name>.py to
- test_<newname>.py.
-
- Usage: self.rename(name='newname') before calling the
- self.test() method.
-
- If 'newname' is None, then no tests will be executed for a given
- module.
- """
- for k,v in kws.items():
- self._rename_map[k] = v
- return
-
- def _module_str(self, module):
- filename = module.__file__[-30:]
- if filename!=module.__file__:
- filename = '...'+filename
- return '<module %r from %r>' % (module.__name__, filename)
-
- def _get_method_names(self,clsobj,level):
- names = []
- for mthname in _get_all_method_names(clsobj):
- if mthname[:5] not in ['bench','check'] \
- and mthname[:4] not in ['test']:
- continue
- mth = getattr(clsobj, mthname)
- if type(mth) is not types.MethodType:
- continue
- d = mth.im_func.func_defaults
- if d is not None:
- mthlevel = d[0]
- else:
- mthlevel = 1
- if level>=mthlevel:
- if mthname not in names:
- names.append(mthname)
- for base in clsobj.__bases__:
- for n in self._get_method_names(base,level):
- if n not in names:
- names.append(n)
- return names
-
- def _get_short_module_name(self, module):
- d,f = os.path.split(module.__file__)
- short_module_name = os.path.splitext(os.path.basename(f))[0]
- if short_module_name=='__init__':
- short_module_name = module.__name__.split('.')[-1]
- short_module_name = self._rename_map.get(short_module_name,short_module_name)
- return short_module_name
-
- def _get_module_tests(self, module, level, verbosity):
- mstr = self._module_str
-
- short_module_name = self._get_short_module_name(module)
- if short_module_name is None:
- return []
-
- test_file = self.get_testfile(module, verbosity)
-
- if test_file is None:
- return []
-
- if not os.path.isfile(test_file):
- if short_module_name[:5]=='info_' \
- and short_module_name[5:]==module.__name__.split('.')[-2]:
- return []
- if short_module_name in ['__cvs_version__','__svn_version__']:
- return []
- if short_module_name[-8:]=='_version' \
- and short_module_name[:-8]==module.__name__.split('.')[-2]:
- return []
- if verbosity>1:
- self.warn(test_file)
- self.warn(' !! No test file %r found for %s' \
- % (os.path.basename(test_file), mstr(module)))
- return []
-
- if test_file in self.test_files:
- return []
-
- parent_module_name = '.'.join(module.__name__.split('.')[:-1])
- test_module_name,ext = os.path.splitext(os.path.basename(test_file))
- test_dir_module = parent_module_name+'.tests'
- test_module_name = test_dir_module+'.'+test_module_name
-
- if test_dir_module not in sys.modules:
- sys.modules[test_dir_module] = imp.new_module(test_dir_module)
-
- old_sys_path = sys.path[:]
- try:
- f = open(test_file,'r')
- test_module = imp.load_module(test_module_name, f,
- test_file, ('.py', 'r', 1))
- f.close()
- except:
- sys.path[:] = old_sys_path
- self.warn('FAILURE importing tests for %s' % (mstr(module)))
- output_exception(sys.stderr)
- return []
- sys.path[:] = old_sys_path
-
- self.test_files.append(test_file)
-
- return self._get_suite_list(test_module, level, module.__name__)
-
- def _get_suite_list(self, test_module, level, module_name='__main__',
- verbosity=1):
- suite_list = []
- if hasattr(test_module, 'test_suite'):
- suite_list.extend(test_module.test_suite(level)._tests)
- for name in dir(test_module):
- obj = getattr(test_module, name)
- if type(obj) is not type(unittest.TestCase) \
- or not issubclass(obj, unittest.TestCase) \
- or not self.check_testcase_name(obj.__name__):
- continue
- for mthname in self._get_method_names(obj,level):
- suite = obj(mthname)
- if getattr(suite,'isrunnable',lambda mthname:1)(mthname):
- suite_list.append(suite)
- matched_suite_list = [suite for suite in suite_list \
- if self.testcase_match(suite.id()\
- .replace('__main__.',''))]
- if verbosity>=0:
- self.info(' Found %s/%s tests for %s' \
- % (len(matched_suite_list), len(suite_list), module_name))
- return matched_suite_list
-
- def _test_suite_from_modules(self, this_package, level, verbosity):
- package_name = this_package.__name__
- modules = []
- for name, module in sys.modules.items():
- if not name.startswith(package_name) or module is None:
- continue
- if not hasattr(module,'__file__'):
- continue
- if os.path.basename(os.path.dirname(module.__file__))=='tests':
- continue
- modules.append((name, module))
-
- modules.sort()
- modules = [m[1] for m in modules]
-
- self.test_files = []
- suites = []
- for module in modules:
- suites.extend(self._get_module_tests(module, abs(level), verbosity))
-
- suites.extend(self._get_suite_list(sys.modules[package_name],
- abs(level), verbosity=verbosity))
- return unittest.TestSuite(suites)
-
- def _test_suite_from_all_tests(self, this_package, level, verbosity):
- importall(this_package)
- package_name = this_package.__name__
-
- # Find all tests/ directories under the package
- test_dirs_names = {}
- for name, module in sys.modules.items():
- if not name.startswith(package_name) or module is None:
- continue
- if not hasattr(module, '__file__'):
- continue
- d = os.path.dirname(module.__file__)
- if os.path.basename(d)=='tests':
- continue
- d = os.path.join(d, 'tests')
- if not os.path.isdir(d):
- continue
- if d in test_dirs_names:
- continue
- test_dir_module = '.'.join(name.split('.')[:-1]+['tests'])
- test_dirs_names[d] = test_dir_module
-
- test_dirs = test_dirs_names.keys()
- test_dirs.sort()
-
- # For each file in each tests/ directory with a test case in it,
- # import the file, and add the test cases to our list
- suite_list = []
- testcase_match = re.compile(r'\s*class\s+\w+\s*\(.*TestCase').match
- for test_dir in test_dirs:
- test_dir_module = test_dirs_names[test_dir]
-
- if test_dir_module not in sys.modules:
- sys.modules[test_dir_module] = imp.new_module(test_dir_module)
-
- for fn in os.listdir(test_dir):
- base, ext = os.path.splitext(fn)
- if ext != '.py':
- continue
- f = os.path.join(test_dir, fn)
-
- # check that file contains TestCase class definitions:
- fid = open(f, 'r')
- skip = True
- for line in fid:
- if testcase_match(line):
- skip = False
- break
- fid.close()
- if skip:
- continue
-
- # import the test file
- n = test_dir_module + '.' + base
- # in case test files import local modules
- sys.path.insert(0, test_dir)
- fo = None
- try:
- try:
- fo = open(f)
- test_module = imp.load_module(n, fo, f,
- ('.py', 'U', 1))
- except Exception, msg:
- print 'Failed importing %s: %s' % (f,msg)
- continue
- finally:
- if fo:
- fo.close()
- del sys.path[0]
-
- suites = self._get_suite_list(test_module, level,
- module_name=n,
- verbosity=verbosity)
- suite_list.extend(suites)
-
- all_tests = unittest.TestSuite(suite_list)
- return all_tests
-
- def test(self, level=1, verbosity=1, all=True, sys_argv=[],
- testcase_pattern='.*'):
- """Run Numpy module test suite with level and verbosity.
-
- level:
- None --- do nothing, return None
- < 0 --- scan for tests of level=abs(level),
- don't run them, return TestSuite-list
- > 0 --- scan for tests of level, run them,
- return TestRunner
- > 10 --- run all tests (same as specifying all=True).
- (backward compatibility).
-
- verbosity:
- >= 0 --- show information messages
- > 1 --- show warnings on missing tests
-
- all:
- True --- run all test files (like self.testall())
- False (default) --- only run test files associated with a module
-
- sys_argv --- replacement of sys.argv[1:] during running
- tests.
-
- testcase_pattern --- run only tests that match given pattern.
-
- It is assumed (when all=False) that package tests suite follows
- the following convention: for each package module, there exists
- file <packagepath>/tests/test_<modulename>.py that defines
- TestCase classes (with names having prefix 'test_') with methods
- (with names having prefixes 'check_' or 'bench_'); each of these
- methods are called when running unit tests.
- """
- if level is None: # Do nothing.
- return
-
- if isinstance(self.package, str):
- exec 'import %s as this_package' % (self.package)
- else:
- this_package = self.package
-
- self.testcase_match = re.compile(testcase_pattern).match
-
- if all:
- all_tests = self._test_suite_from_all_tests(this_package,
- level, verbosity)
- else:
- all_tests = self._test_suite_from_modules(this_package,
- level, verbosity)
-
- if level < 0:
- return all_tests
-
- runner = unittest.TextTestRunner(verbosity=verbosity)
- old_sys_argv = sys.argv[1:]
- sys.argv[1:] = sys_argv
- # Use the builtin displayhook. If the tests are being run
- # under IPython (for instance), any doctest test suites will
- # fail otherwise.
- old_displayhook = sys.displayhook
- sys.displayhook = sys.__displayhook__
- try:
- r = runner.run(all_tests)
- finally:
- sys.displayhook = old_displayhook
- sys.argv[1:] = old_sys_argv
- return r
-
- def testall(self, level=1,verbosity=1):
- """ Run Numpy module test suite with level and verbosity.
-
- level:
- None --- do nothing, return None
- < 0 --- scan for tests of level=abs(level),
- don't run them, return TestSuite-list
- > 0 --- scan for tests of level, run them,
- return TestRunner
-
- verbosity:
- >= 0 --- show information messages
- > 1 --- show warnings on missing tests
-
- Different from .test(..) method, this method looks for
- TestCase classes from all files in <packagedir>/tests/
- directory and no assumptions are made for naming the
- TestCase classes or their methods.
- """
- return self.test(level=level, verbosity=verbosity, all=True)
-
- def run(self):
- """ Run Numpy module test suite with level and verbosity
- taken from sys.argv. Requires optparse module.
- """
- try:
- from optparse import OptionParser
- except ImportError:
- self.warn('Failed to import optparse module, ignoring.')
- return self.test()
- usage = r'usage: %prog [-v <verbosity>] [-l <level>]'\
- r' [-s "<replacement of sys.argv[1:]>"]'\
- r' [-t "<testcase pattern>"]'
- parser = OptionParser(usage)
- parser.add_option("-v", "--verbosity",
- action="store",
- dest="verbosity",
- default=1,
- type='int')
- parser.add_option("-l", "--level",
- action="store",
- dest="level",
- default=1,
- type='int')
- parser.add_option("-s", "--sys-argv",
- action="store",
- dest="sys_argv",
- default='',
- type='string')
- parser.add_option("-t", "--testcase-pattern",
- action="store",
- dest="testcase_pattern",
- default=r'.*',
- type='string')
- (options, args) = parser.parse_args()
- return self.test(options.level,options.verbosity,
- sys_argv=shlex.split(options.sys_argv or ''),
- testcase_pattern=options.testcase_pattern)
-
- def warn(self, message):
- from numpy.distutils.misc_util import yellow_text
- print>>sys.stderr,yellow_text('Warning: %s' % (message))
- sys.stderr.flush()
- def info(self, message):
- print>>sys.stdout, message
- sys.stdout.flush()
-
-class ScipyTest(NumpyTest):
- def __init__(self, package=None):
- warnings.warn("ScipyTest is now called NumpyTest; please update your code",
- DeprecationWarning, stacklevel=2)
- NumpyTest.__init__(self, package)
-
def importall(package):
"""
diff --git a/numpy/testing/parametric.py b/numpy/testing/parametric.py
deleted file mode 100644
index 43577d7d4..000000000
--- a/numpy/testing/parametric.py
+++ /dev/null
@@ -1,300 +0,0 @@
-"""Support for parametric tests in unittest.
-
-:Author: Fernando Perez
-
-Purpose
-=======
-
-Briefly, the main class in this module allows you to easily and cleanly
-(without the gross name-mangling hacks that are normally needed) to write
-unittest TestCase classes that have parametrized tests. That is, tests which
-consist of multiple sub-tests that scan for example a parameter range, but
-where you want each sub-test to:
-
-* count as a separate test in the statistics.
-
-* be run even if others in the group error out or fail.
-
-
-The class offers a simple name-based convention to create such tests (see
-simple example at the end), in one of two ways:
-
-* Each sub-test in a group can be run fully independently, with the
- setUp/tearDown methods being called each time.
-
-* The whole group can be run with setUp/tearDown being called only once for the
- group. This lets you conveniently reuse state that may be very expensive to
- compute for multiple tests. Be careful not to corrupt it!!!
-
-
-Caveats
-=======
-
-This code relies on implementation details of the unittest module (some key
-methods are heavily modified versions of those, after copying them in). So it
-may well break either if you make sophisticated use of the unittest APIs, or if
-unittest itself changes in the future. I have only tested this with Python
-2.5.
-
-"""
-__docformat__ = "restructuredtext en"
-
-import unittest
-
-class ParametricTestCase(unittest.TestCase):
- """TestCase subclass with support for parametric tests.
-
- Subclasses of this class can implement test methods that return a list of
- tests and arguments to call those with, to do parametric testing (often
- also called 'data driven' testing."""
-
- #: Prefix for tests with independent state. These methods will be run with
- #: a separate setUp/tearDown call for each test in the group.
- _indepParTestPrefix = 'testip'
-
- #: Prefix for tests with shared state. These methods will be run with
- #: a single setUp/tearDown call for the whole group. This is useful when
- #: writing a group of tests for which the setup is expensive and one wants
- #: to actually share that state. Use with care (especially be careful not
- #: to mutate the state you are using, which will alter later tests).
- _shareParTestPrefix = 'testsp'
-
- def exec_test(self,test,args,result):
- """Execute a single test. Returns a success boolean"""
-
- ok = False
- try:
- test(*args)
- ok = True
- except self.failureException:
- result.addFailure(self, self._exc_info())
- except KeyboardInterrupt:
- raise
- except:
- result.addError(self, self._exc_info())
-
- return ok
-
- def set_testMethodDoc(self,doc):
- self._testMethodDoc = doc
- self._TestCase__testMethodDoc = doc
-
- def get_testMethodDoc(self):
- return self._testMethodDoc
-
- testMethodDoc = property(fset=set_testMethodDoc, fget=get_testMethodDoc)
-
- def get_testMethodName(self):
- try:
- return getattr(self,"_testMethodName")
- except:
- return getattr(self,"_TestCase__testMethodName")
-
- testMethodName = property(fget=get_testMethodName)
-
- def run_test(self, testInfo,result):
- """Run one test with arguments"""
-
- test,args = testInfo[0],testInfo[1:]
-
- # Reset the doc attribute to be the docstring of this particular test,
- # so that in error messages it prints the actual test's docstring and
- # not that of the test factory.
- self.testMethodDoc = test.__doc__
- result.startTest(self)
- try:
- try:
- self.setUp()
- except KeyboardInterrupt:
- raise
- except:
- result.addError(self, self._exc_info())
- return
-
- ok = self.exec_test(test,args,result)
-
- try:
- self.tearDown()
- except KeyboardInterrupt:
- raise
- except:
- result.addError(self, self._exc_info())
- ok = False
- if ok: result.addSuccess(self)
- finally:
- result.stopTest(self)
-
- def run_tests(self, tests,result):
- """Run many tests with a common setUp/tearDown.
-
- The entire set of tests is run with a single setUp/tearDown call."""
-
- try:
- self.setUp()
- except KeyboardInterrupt:
- raise
- except:
- result.testsRun += 1
- result.addError(self, self._exc_info())
- return
-
- saved_doc = self.testMethodDoc
-
- try:
- # Run all the tests specified
- for testInfo in tests:
- test,args = testInfo[0],testInfo[1:]
-
- # Set the doc argument for this test. Note that even if we do
- # this, the fail/error tracebacks still print the docstring for
- # the parent factory, because they only generate the message at
- # the end of the run, AFTER we've restored it. There is no way
- # to tell the unittest system (without overriding a lot of
- # stuff) to extract this information right away, the logic is
- # hardcoded to pull it later, since unittest assumes it doesn't
- # change.
- self.testMethodDoc = test.__doc__
- result.startTest(self)
- ok = self.exec_test(test,args,result)
- if ok: result.addSuccess(self)
-
- finally:
- # Restore docstring info and run tearDown once only.
- self.testMethodDoc = saved_doc
- try:
- self.tearDown()
- except KeyboardInterrupt:
- raise
- except:
- result.addError(self, self._exc_info())
-
- def run(self, result=None):
- """Test runner."""
-
- #print
- #print '*** run for method:',self._testMethodName # dbg
- #print '*** doc:',self._testMethodDoc # dbg
-
- if result is None: result = self.defaultTestResult()
-
- # Independent tests: each gets its own setup/teardown
- if self.testMethodName.startswith(self._indepParTestPrefix):
- for t in getattr(self,self.testMethodName)():
- self.run_test(t,result)
- # Shared-state test: single setup/teardown for all
- elif self.testMethodName.startswith(self._shareParTestPrefix):
- tests = getattr(self,self.testMethodName,'runTest')()
- self.run_tests(tests,result)
- # Normal unittest Test methods
- else:
- unittest.TestCase.run(self,result)
-
-#############################################################################
-# Quick and dirty interactive example/test
-if __name__ == '__main__':
-
- class ExampleTestCase(ParametricTestCase):
-
- #-------------------------------------------------------------------
- # An instrumented setUp method so we can see when it gets called and
- # how many times per instance
- counter = 0
-
- def setUp(self):
- self.counter += 1
- print 'setUp count: %2s for: %s' % (self.counter,
- self.testMethodDoc)
-
- #-------------------------------------------------------------------
- # A standard test method, just like in the unittest docs.
- def test_foo(self):
- """Normal test for feature foo."""
- pass
-
- #-------------------------------------------------------------------
- # Testing methods that need parameters. These can NOT be named test*,
- # since they would be picked up by unittest and called without
- # arguments. Instead, call them anything else (I use tst*) and then
- # load them via the factories below.
- def tstX(self,i):
- "Test feature X with parameters."
- print 'tstX, i=',i
- if i==1 or i==3:
- # Test fails
- self.fail('i is bad, bad: %s' % i)
-
- def tstY(self,i):
- "Test feature Y with parameters."
- print 'tstY, i=',i
- if i==1:
- # Force an error
- 1/0
-
- def tstXX(self,i,j):
- "Test feature XX with parameters."
- print 'tstXX, i=',i,'j=',j
- if i==1:
- # Test fails
- self.fail('i is bad, bad: %s' % i)
-
- def tstYY(self,i):
- "Test feature YY with parameters."
- print 'tstYY, i=',i
- if i==2:
- # Force an error
- 1/0
-
- def tstZZ(self):
- """Test feature ZZ without parameters, needs multiple runs.
-
- This could be a random test that you want to run multiple times."""
- pass
-
- #-------------------------------------------------------------------
- # Parametric test factories that create the test groups to call the
- # above tst* methods with their required arguments.
- def testip(self):
- """Independent parametric test factory.
-
- A separate setUp() call is made for each test returned by this
- method.
-
- You must return an iterable (list or generator is fine) containing
- tuples with the actual method to be called as the first argument,
- and the arguments for that call later."""
- return [(self.tstX,i) for i in range(5)]
-
- def testip2(self):
- """Another independent parametric test factory"""
- return [(self.tstY,i) for i in range(5)]
-
- def testip3(self):
- """Test factory combining different subtests.
-
- This one shows how to assemble calls to different tests."""
- return [(self.tstX,3),(self.tstX,9),(self.tstXX,4,10),
- (self.tstZZ,),(self.tstZZ,)]
-
- def testsp(self):
- """Shared parametric test factory
-
- A single setUp() call is made for all the tests returned by this
- method.
- """
- return [(self.tstXX,i,i+1) for i in range(5)]
-
- def testsp2(self):
- """Another shared parametric test factory"""
- return [(self.tstYY,i) for i in range(5)]
-
- def testsp3(self):
- """Another shared parametric test factory.
-
- This one simply calls the same test multiple times, without any
- arguments. Note that you must still return tuples, even if there
- are no arguments."""
- return [(self.tstZZ,) for i in range(10)]
-
-
- # This test class runs normally under unittest's default runner
- unittest.main()
diff --git a/numpy/testing/pkgtester.py b/numpy/testing/pkgtester.py
new file mode 100644
index 000000000..8b22955fa
--- /dev/null
+++ b/numpy/testing/pkgtester.py
@@ -0,0 +1,27 @@
+''' Define test function for scipy package
+
+Module tests for presence of useful version of nose. If present
+returns NoseTester, otherwise returns a placeholder test routine
+reporting lack of nose and inability to run tests. Typical use is in
+module __init__:
+
+from scipy.testing.pkgtester import Tester
+test = Tester().test
+
+See nosetester module for test implementation
+
+'''
+fine_nose = True
+try:
+ import nose
+except ImportError:
+ fine_nose = False
+else:
+ nose_version = nose.__versioninfo__
+ if nose_version[0] < 1 and nose_version[1] < 10:
+ fine_nose = False
+
+if fine_nose:
+ from numpy.testing.nosetester import NoseTester as Tester
+else:
+ from numpy.testing.nulltester import NullTester as Tester
diff --git a/numpy/testing/tests/test_utils.py b/numpy/testing/tests/test_utils.py
index 6f40c778b..27cc4a809 100644
--- a/numpy/testing/tests/test_utils.py
+++ b/numpy/testing/tests/test_utils.py
@@ -1,9 +1,7 @@
import numpy as N
-from numpy.testing.utils import *
-
+from numpy.testing import *
import unittest
-
class _GenericTest(object):
def _test_equal(self, a, b):
self._assert_func(a, b)
@@ -163,5 +161,6 @@ class TestRaises(unittest.TestCase):
else:
raise AssertionError("should have raised an AssertionError")
+
if __name__ == '__main__':
- unittest.main()
+ nose.run(argv=['', __file__])
diff --git a/numpy/testing/utils.py b/numpy/testing/utils.py
index 680b4f168..538014f33 100644
--- a/numpy/testing/utils.py
+++ b/numpy/testing/utils.py
@@ -10,8 +10,8 @@ import operator
__all__ = ['assert_equal', 'assert_almost_equal','assert_approx_equal',
'assert_array_equal', 'assert_array_less', 'assert_string_equal',
- 'assert_array_almost_equal', 'jiffies', 'memusage', 'rand',
- 'runstring', 'raises']
+ 'assert_array_almost_equal', 'build_err_msg', 'jiffies', 'memusage',
+ 'rand', 'rundocs', 'runstring']
def rand(*args):
"""Returns an array of random numbers with the given shape.
@@ -295,32 +295,25 @@ def assert_string_equal(actual, desired):
assert actual==desired, msg
-def raises(*exceptions):
- """ Assert that a test function raises one of the specified exceptions to
- pass.
+def rundocs(filename=None):
+ """ Run doc string tests found in filename.
"""
- # FIXME: when we transition to nose, just use its implementation. It's
- # better.
- def deco(function):
- def f2(*args, **kwds):
- try:
- function(*args, **kwds)
- except exceptions:
- pass
- except:
- # Anything else.
- raise
- else:
- raise AssertionError('%s() did not raise one of (%s)' %
- (function.__name__, ', '.join([e.__name__ for e in exceptions])))
- try:
- f2.__name__ = function.__name__
- except TypeError:
- # Python 2.3 does not permit this.
- pass
- f2.__dict__ = function.__dict__
- f2.__doc__ = function.__doc__
- f2.__module__ = function.__module__
- return f2
-
- return deco
+ import doctest, imp
+ if filename is None:
+ f = sys._getframe(1)
+ filename = f.f_globals['__file__']
+ name = os.path.splitext(os.path.basename(filename))[0]
+ path = [os.path.dirname(filename)]
+ file, pathname, description = imp.find_module(name, path)
+ try:
+ m = imp.load_module(name, file, pathname, description)
+ finally:
+ file.close()
+ if sys.version[:3]<'2.4':
+ doctest.testmod(m, verbose=False)
+ else:
+ tests = doctest.DocTestFinder().find(m)
+ runner = doctest.DocTestRunner(verbose=False)
+ for test in tests:
+ runner.run(test)
+ return
diff --git a/numpy/tests/test_ctypeslib.py b/numpy/tests/test_ctypeslib.py
index 5d21a09ea..12e4dce01 100644
--- a/numpy/tests/test_ctypeslib.py
+++ b/numpy/tests/test_ctypeslib.py
@@ -2,8 +2,8 @@ import numpy as np
from numpy.ctypeslib import ndpointer, load_library
from numpy.testing import *
-class TestLoadLibrary(NumpyTestCase):
- def check_basic(self):
+class TestLoadLibrary(TestCase):
+ def test_basic(self):
try:
cdll = load_library('multiarray',
np.core.multiarray.__file__)
@@ -12,7 +12,7 @@ class TestLoadLibrary(NumpyTestCase):
" (import error was: %s)" % str(e)
print msg
- def check_basic2(self):
+ def test_basic2(self):
"""Regression for #801: load_library with a full library name
(including extension) does not work."""
try:
@@ -28,8 +28,8 @@ class TestLoadLibrary(NumpyTestCase):
" (import error was: %s)" % str(e)
print msg
-class TestNdpointer(NumpyTestCase):
- def check_dtype(self):
+class TestNdpointer(TestCase):
+ def test_dtype(self):
dt = np.intc
p = ndpointer(dtype=dt)
self.assert_(p.from_param(np.array([1], dt)))
@@ -56,7 +56,7 @@ class TestNdpointer(NumpyTestCase):
else:
self.assert_(p.from_param(np.zeros((10,), dt2)))
- def check_ndim(self):
+ def test_ndim(self):
p = ndpointer(ndim=0)
self.assert_(p.from_param(np.array(1)))
self.assertRaises(TypeError, p.from_param, np.array([1]))
@@ -66,14 +66,14 @@ class TestNdpointer(NumpyTestCase):
p = ndpointer(ndim=2)
self.assert_(p.from_param(np.array([[1]])))
- def check_shape(self):
+ def test_shape(self):
p = ndpointer(shape=(1,2))
self.assert_(p.from_param(np.array([[1,2]])))
self.assertRaises(TypeError, p.from_param, np.array([[1],[2]]))
p = ndpointer(shape=())
self.assert_(p.from_param(np.array(1)))
- def check_flags(self):
+ def test_flags(self):
x = np.array([[1,2,3]], order='F')
p = ndpointer(flags='FORTRAN')
self.assert_(p.from_param(x))
@@ -83,5 +83,6 @@ class TestNdpointer(NumpyTestCase):
self.assert_(p.from_param(x))
self.assertRaises(TypeError, p.from_param, np.array([[1,2,3]]))
+
if __name__ == "__main__":
- NumpyTest().run()
+ nose.run(argv=['', __file__])