Merge pull request #9452 from eric-wieser/new-style-classes
MAINT: Use new-style classes on 2.7
diff --git a/numpy/core/tests/test_abc.py b/numpy/core/tests/test_abc.py
index 2430866..515a76a 100644
--- a/numpy/core/tests/test_abc.py
+++ b/numpy/core/tests/test_abc.py
@@ -1,43 +1,43 @@
from __future__ import division, absolute_import, print_function
-from numpy.testing import TestCase, assert_, run_module_suite
+from numpy.testing import assert_, run_module_suite
import numbers
from numpy.core.numerictypes import sctypes
-class ABC(TestCase):
+class TestABC(object):
def test_floats(self):
for t in sctypes['float']:
- assert_(isinstance(t(), numbers.Real),
+ assert_(isinstance(t(), numbers.Real),
"{0} is not instance of Real".format(t.__name__))
assert_(issubclass(t, numbers.Real),
"{0} is not subclass of Real".format(t.__name__))
- assert_(not isinstance(t(), numbers.Rational),
+ assert_(not isinstance(t(), numbers.Rational),
"{0} is instance of Rational".format(t.__name__))
assert_(not issubclass(t, numbers.Rational),
"{0} is subclass of Rational".format(t.__name__))
def test_complex(self):
for t in sctypes['complex']:
- assert_(isinstance(t(), numbers.Complex),
+ assert_(isinstance(t(), numbers.Complex),
"{0} is not instance of Complex".format(t.__name__))
assert_(issubclass(t, numbers.Complex),
"{0} is not subclass of Complex".format(t.__name__))
- assert_(not isinstance(t(), numbers.Real),
+ assert_(not isinstance(t(), numbers.Real),
"{0} is instance of Real".format(t.__name__))
assert_(not issubclass(t, numbers.Real),
"{0} is subclass of Real".format(t.__name__))
def test_int(self):
for t in sctypes['int']:
- assert_(isinstance(t(), numbers.Integral),
+ assert_(isinstance(t(), numbers.Integral),
"{0} is not instance of Integral".format(t.__name__))
assert_(issubclass(t, numbers.Integral),
"{0} is not subclass of Integral".format(t.__name__))
def test_uint(self):
for t in sctypes['uint']:
- assert_(isinstance(t(), numbers.Integral),
+ assert_(isinstance(t(), numbers.Integral),
"{0} is not instance of Integral".format(t.__name__))
assert_(issubclass(t, numbers.Integral),
"{0} is not subclass of Integral".format(t.__name__))
diff --git a/numpy/core/tests/test_arrayprint.py b/numpy/core/tests/test_arrayprint.py
index b80c5d1..7d4acd3 100644
--- a/numpy/core/tests/test_arrayprint.py
+++ b/numpy/core/tests/test_arrayprint.py
@@ -5,7 +5,7 @@
import numpy as np
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_equal
+ run_module_suite, assert_, assert_equal
)
class TestArrayRepr(object):
@@ -61,7 +61,7 @@
'array([list([1, 2]), list([3])], dtype=object)')
-class TestComplexArray(TestCase):
+class TestComplexArray(object):
def test_str(self):
rvals = [0, 1, -1, np.inf, -np.inf, np.nan]
cvals = [complex(rp, ip) for rp in rvals for ip in rvals]
@@ -108,7 +108,7 @@
for res, val in zip(actual, wanted):
assert_(res == val)
-class TestArray2String(TestCase):
+class TestArray2String(object):
def test_basic(self):
"""Basic test of array2string."""
a = np.arange(3)
@@ -183,13 +183,13 @@
assert_equal(np.array2string(array_scalar), "( 1., 2.12345679, 3.)")
-class TestPrintOptions:
+class TestPrintOptions(object):
"""Test getting and setting global print options."""
- def setUp(self):
+ def setup(self):
self.oldopts = np.get_printoptions()
- def tearDown(self):
+ def teardown(self):
np.set_printoptions(**self.oldopts)
def test_basic(self):
diff --git a/numpy/core/tests/test_datetime.py b/numpy/core/tests/test_datetime.py
index 48afa72..58f2b9c 100644
--- a/numpy/core/tests/test_datetime.py
+++ b/numpy/core/tests/test_datetime.py
@@ -6,7 +6,7 @@
import numpy as np
import datetime
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_equal, assert_raises,
+ run_module_suite, assert_, assert_equal, assert_raises,
assert_warns, dec, suppress_warnings
)
@@ -18,7 +18,7 @@
_has_pytz = False
-class TestDateTime(TestCase):
+class TestDateTime(object):
def test_datetime_dtype_creation(self):
for unit in ['Y', 'M', 'W', 'D',
'h', 'm', 's', 'ms', 'us',
@@ -1131,7 +1131,7 @@
assert_(np.not_equal(dt_other, dt_nat))
assert_(np.not_equal(td_nat, td_other))
assert_(np.not_equal(td_other, td_nat))
- self.assertEqual(len(sup.log), 0)
+ assert_equal(len(sup.log), 0)
def test_datetime_minmax(self):
# The metadata of the result should become the GCD
@@ -1227,10 +1227,10 @@
def test_divisor_conversion_fs(self):
assert_(np.dtype('M8[fs/100]') == np.dtype('M8[10as]'))
- self.assertRaises(ValueError, lambda: np.dtype('M8[3fs/10000]'))
+ assert_raises(ValueError, lambda: np.dtype('M8[3fs/10000]'))
def test_divisor_conversion_as(self):
- self.assertRaises(ValueError, lambda: np.dtype('M8[as/10]'))
+ assert_raises(ValueError, lambda: np.dtype('M8[as/10]'))
def test_string_parser_variants(self):
# Allow space instead of 'T' between date and time
@@ -1947,7 +1947,7 @@
assert_raises(ValueError, np.isnat, np.zeros(10, t))
-class TestDateTimeData(TestCase):
+class TestDateTimeData(object):
def test_basic(self):
a = np.array(['1980-03-23'], dtype=np.datetime64)
diff --git a/numpy/core/tests/test_defchararray.py b/numpy/core/tests/test_defchararray.py
index 11d7c3b..fade693 100644
--- a/numpy/core/tests/test_defchararray.py
+++ b/numpy/core/tests/test_defchararray.py
@@ -5,13 +5,13 @@
import numpy as np
from numpy.core.multiarray import _vec_string
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_equal, assert_array_equal
+ run_module_suite, assert_, assert_equal, assert_array_equal, assert_raises,
)
kw_unicode_true = {'unicode': True} # make 2to3 work properly
kw_unicode_false = {'unicode': False}
-class TestBasic(TestCase):
+class TestBasic(object):
def test_from_object_array(self):
A = np.array([['abc', 2],
['long ', '0123456789']], dtype='O')
@@ -23,7 +23,7 @@
def test_from_object_array_unicode(self):
A = np.array([['abc', u'Sigma \u03a3'],
['long ', '0123456789']], dtype='O')
- self.assertRaises(ValueError, np.char.array, (A,))
+ assert_raises(ValueError, np.char.array, (A,))
B = np.char.array(A, **kw_unicode_true)
assert_equal(B.dtype.itemsize, 10 * np.array('a', 'U').dtype.itemsize)
assert_array_equal(B, [['abc', u'Sigma \u03a3'],
@@ -62,7 +62,7 @@
def fail():
np.char.array(A, **kw_unicode_false)
- self.assertRaises(UnicodeEncodeError, fail)
+ assert_raises(UnicodeEncodeError, fail)
def test_unicode_upconvert(self):
A = np.char.array(['abc'])
@@ -82,59 +82,59 @@
assert_equal(A.itemsize, 4)
assert_(issubclass(A.dtype.type, np.unicode_))
-class TestVecString(TestCase):
+class TestVecString(object):
def test_non_existent_method(self):
def fail():
_vec_string('a', np.string_, 'bogus')
- self.assertRaises(AttributeError, fail)
+ assert_raises(AttributeError, fail)
def test_non_string_array(self):
def fail():
_vec_string(1, np.string_, 'strip')
- self.assertRaises(TypeError, fail)
+ assert_raises(TypeError, fail)
def test_invalid_args_tuple(self):
def fail():
_vec_string(['a'], np.string_, 'strip', 1)
- self.assertRaises(TypeError, fail)
+ assert_raises(TypeError, fail)
def test_invalid_type_descr(self):
def fail():
_vec_string(['a'], 'BOGUS', 'strip')
- self.assertRaises(TypeError, fail)
+ assert_raises(TypeError, fail)
def test_invalid_function_args(self):
def fail():
_vec_string(['a'], np.string_, 'strip', (1,))
- self.assertRaises(TypeError, fail)
+ assert_raises(TypeError, fail)
def test_invalid_result_type(self):
def fail():
_vec_string(['a'], np.integer, 'strip')
- self.assertRaises(TypeError, fail)
+ assert_raises(TypeError, fail)
def test_broadcast_error(self):
def fail():
_vec_string([['abc', 'def']], np.integer, 'find', (['a', 'd', 'j'],))
- self.assertRaises(ValueError, fail)
+ assert_raises(ValueError, fail)
-class TestWhitespace(TestCase):
- def setUp(self):
+class TestWhitespace(object):
+ def setup(self):
self.A = np.array([['abc ', '123 '],
['789 ', 'xyz ']]).view(np.chararray)
self.B = np.array([['abc', '123'],
@@ -148,16 +148,16 @@
assert_(not np.any(self.A < self.B))
assert_(not np.any(self.A != self.B))
-class TestChar(TestCase):
- def setUp(self):
+class TestChar(object):
+ def setup(self):
self.A = np.array('abc1', dtype='c').view(np.chararray)
def test_it(self):
assert_equal(self.A.shape, (4,))
assert_equal(self.A.upper()[:2].tobytes(), b'AB')
-class TestComparisons(TestCase):
- def setUp(self):
+class TestComparisons(object):
+ def setup(self):
self.A = np.array([['abc', '123'],
['789', 'xyz']]).view(np.chararray)
self.B = np.array([['efg', '123 '],
@@ -184,21 +184,21 @@
class TestComparisonsMixed1(TestComparisons):
"""Ticket #1276"""
- def setUp(self):
- TestComparisons.setUp(self)
+ def setup(self):
+ TestComparisons.setup(self)
self.B = np.array([['efg', '123 '],
['051', 'tuv']], np.unicode_).view(np.chararray)
class TestComparisonsMixed2(TestComparisons):
"""Ticket #1276"""
- def setUp(self):
- TestComparisons.setUp(self)
+ def setup(self):
+ TestComparisons.setup(self)
self.A = np.array([['abc', '123'],
['789', 'xyz']], np.unicode_).view(np.chararray)
-class TestInformation(TestCase):
- def setUp(self):
+class TestInformation(object):
+ def setup(self):
self.A = np.array([[' abc ', ''],
['12345', 'MixedCase'],
['123 \t 345 \0 ', 'UPPER']]).view(np.chararray)
@@ -230,7 +230,7 @@
def fail():
self.A.endswith('3', 'fdjk')
- self.assertRaises(TypeError, fail)
+ assert_raises(TypeError, fail)
def test_find(self):
assert_(issubclass(self.A.find('a').dtype.type, np.integer))
@@ -244,7 +244,7 @@
def fail():
self.A.index('a')
- self.assertRaises(ValueError, fail)
+ assert_raises(ValueError, fail)
assert_(np.char.index('abcba', 'b') == 1)
assert_(issubclass(np.char.index('abcba', 'b').dtype.type, np.integer))
@@ -288,7 +288,7 @@
def fail():
self.A.rindex('a')
- self.assertRaises(ValueError, fail)
+ assert_raises(ValueError, fail)
assert_(np.char.rindex('abcba', 'b') == 3)
assert_(issubclass(np.char.rindex('abcba', 'b').dtype.type, np.integer))
@@ -300,11 +300,11 @@
def fail():
self.A.startswith('3', 'fdjk')
- self.assertRaises(TypeError, fail)
+ assert_raises(TypeError, fail)
-class TestMethods(TestCase):
- def setUp(self):
+class TestMethods(object):
+ def setup(self):
self.A = np.array([[' abc ', ''],
['12345', 'MixedCase'],
['123 \t 345 \0 ', 'UPPER']],
@@ -579,7 +579,7 @@
def fail():
self.A.isnumeric()
- self.assertRaises(TypeError, fail)
+ assert_raises(TypeError, fail)
assert_(issubclass(self.B.isnumeric().dtype.type, np.bool_))
assert_array_equal(self.B.isnumeric(), [
[False, False], [True, False], [False, False]])
@@ -589,14 +589,14 @@
def fail():
self.A.isdecimal()
- self.assertRaises(TypeError, fail)
+ assert_raises(TypeError, fail)
assert_(issubclass(self.B.isdecimal().dtype.type, np.bool_))
assert_array_equal(self.B.isdecimal(), [
[False, False], [True, False], [False, False]])
-class TestOperations(TestCase):
- def setUp(self):
+class TestOperations(object):
+ def setup(self):
self.A = np.array([['abc', '123'],
['789', 'xyz']]).view(np.chararray)
self.B = np.array([['efg', '456'],
diff --git a/numpy/core/tests/test_deprecations.py b/numpy/core/tests/test_deprecations.py
index 500f78c..3df34a7 100644
--- a/numpy/core/tests/test_deprecations.py
+++ b/numpy/core/tests/test_deprecations.py
@@ -28,7 +28,7 @@
message = ''
warning_cls = DeprecationWarning
- def setUp(self):
+ def setup(self):
self.warn_ctx = warnings.catch_warnings(record=True)
self.log = self.warn_ctx.__enter__()
@@ -42,7 +42,7 @@
warnings.filterwarnings("always", message=self.message,
category=self.warning_cls)
- def tearDown(self):
+ def teardown(self):
self.warn_ctx.__exit__()
def assert_deprecated(self, function, num=1, ignore_others=False,
@@ -379,7 +379,7 @@
class TestTestDeprecated(object):
def test_assert_deprecated(self):
test_case_instance = _DeprecationTestCase()
- test_case_instance.setUp()
+ test_case_instance.setup()
assert_raises(AssertionError,
test_case_instance.assert_deprecated,
lambda: None)
@@ -388,7 +388,7 @@
warnings.warn("foo", category=DeprecationWarning, stacklevel=2)
test_case_instance.assert_deprecated(foo)
- test_case_instance.tearDown()
+ test_case_instance.teardown()
class TestClassicIntDivision(_DeprecationTestCase):
diff --git a/numpy/core/tests/test_dtype.py b/numpy/core/tests/test_dtype.py
index 7829cb6..06dd585 100644
--- a/numpy/core/tests/test_dtype.py
+++ b/numpy/core/tests/test_dtype.py
@@ -6,7 +6,7 @@
import numpy as np
from numpy.core.test_rational import rational
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_equal, assert_raises,
+ run_module_suite, assert_, assert_equal, assert_raises,
dec
)
@@ -20,7 +20,7 @@
assert_(hash(a) != hash(b),
"two different types hash to the same value !")
-class TestBuiltin(TestCase):
+class TestBuiltin(object):
def test_run(self):
"""Only test hash runs at all."""
for t in [np.int, np.float, np.complex, np.int32, np.str, np.object,
@@ -36,7 +36,7 @@
dt2 = dt.newbyteorder("<")
dt3 = dt.newbyteorder(">")
if dt == dt2:
- self.assertTrue(dt.byteorder != dt2.byteorder, "bogus test")
+ assert_(dt.byteorder != dt2.byteorder, "bogus test")
assert_dtype_equal(dt, dt2)
else:
self.assertTrue(dt.byteorder != dt3.byteorder, "bogus test")
@@ -51,8 +51,8 @@
else:
left = uintp
right = np.dtype(np.ulonglong)
- self.assertTrue(left == right)
- self.assertTrue(hash(left) == hash(right))
+ assert_(left == right)
+ assert_(hash(left) == hash(right))
def test_invalid_types(self):
# Make sure invalid type strings raise an error
@@ -104,7 +104,7 @@
'formats':['i1', 'f4'],
'offsets':[0, 2]}, align=True)
-class TestRecord(TestCase):
+class TestRecord(object):
def test_equivalent_record(self):
"""Test whether equivalent record dtypes hash the same."""
a = np.dtype([('yo', np.int)])
@@ -146,10 +146,10 @@
"""Test if an appropriate exception is raised when passing bad values to
the dtype constructor.
"""
- self.assertRaises(TypeError, np.dtype,
- dict(names=set(['A', 'B']), formats=['f8', 'i4']))
- self.assertRaises(TypeError, np.dtype,
- dict(names=['A', 'B'], formats=set(['f8', 'i4'])))
+ assert_raises(TypeError, np.dtype,
+ dict(names=set(['A', 'B']), formats=['f8', 'i4']))
+ assert_raises(TypeError, np.dtype,
+ dict(names=['A', 'B'], formats=set(['f8', 'i4'])))
def test_aligned_size(self):
# Check that structured dtypes get padded to an aligned size
@@ -276,9 +276,9 @@
def test_nonint_offsets(self):
# gh-8059
def make_dtype(off):
- return np.dtype({'names': ['A'], 'formats': ['i4'],
+ return np.dtype({'names': ['A'], 'formats': ['i4'],
'offsets': [off]})
-
+
assert_raises(TypeError, make_dtype, 'ASD')
assert_raises(OverflowError, make_dtype, 2**70)
assert_raises(TypeError, make_dtype, 2.3)
@@ -289,7 +289,7 @@
np.zeros(1, dtype=dt)[0].item()
-class TestSubarray(TestCase):
+class TestSubarray(object):
def test_single_subarray(self):
a = np.dtype((np.int, (2)))
b = np.dtype((np.int, (2,)))
@@ -415,7 +415,7 @@
assert_equal(t1.alignment, t2.alignment)
-class TestMonsterType(TestCase):
+class TestMonsterType(object):
"""Test deeply nested subtypes."""
def test1(self):
@@ -433,29 +433,29 @@
('yi', np.dtype((a, (3, 2))))])
assert_dtype_equal(c, d)
-class TestMetadata(TestCase):
+class TestMetadata(object):
def test_no_metadata(self):
d = np.dtype(int)
- self.assertEqual(d.metadata, None)
+ assert_(d.metadata is None)
def test_metadata_takes_dict(self):
d = np.dtype(int, metadata={'datum': 1})
- self.assertEqual(d.metadata, {'datum': 1})
+ assert_(d.metadata == {'datum': 1})
def test_metadata_rejects_nondict(self):
- self.assertRaises(TypeError, np.dtype, int, metadata='datum')
- self.assertRaises(TypeError, np.dtype, int, metadata=1)
- self.assertRaises(TypeError, np.dtype, int, metadata=None)
+ assert_raises(TypeError, np.dtype, int, metadata='datum')
+ assert_raises(TypeError, np.dtype, int, metadata=1)
+ assert_raises(TypeError, np.dtype, int, metadata=None)
def test_nested_metadata(self):
d = np.dtype([('a', np.dtype(int, metadata={'datum': 1}))])
- self.assertEqual(d['a'].metadata, {'datum': 1})
+ assert_(d['a'].metadata == {'datum': 1})
- def base_metadata_copied(self):
+ def test_base_metadata_copied(self):
d = np.dtype((np.void, np.dtype('i4,i4', metadata={'datum': 1})))
- assert_equal(d.metadata, {'datum': 1})
+ assert_(d.metadata == {'datum': 1})
-class TestString(TestCase):
+class TestString(object):
def test_complex_dtype_str(self):
dt = np.dtype([('top', [('tiles', ('>f4', (64, 64)), (1,)),
('rtile', '>f4', (64, 36))], (3,)),
@@ -582,7 +582,7 @@
# Pull request #4722
np.array(["", ""]).astype(object)
-class TestDtypeAttributeDeletion(TestCase):
+class TestDtypeAttributeDeletion(object):
def test_dtype_non_writable_attributes_deletion(self):
dt = np.dtype(np.double)
@@ -600,7 +600,7 @@
assert_raises(AttributeError, delattr, dt, s)
-class TestDtypeAttributes(TestCase):
+class TestDtypeAttributes(object):
def test_descr_has_trailing_void(self):
# see gh-6359
dtype = np.dtype({
@@ -625,17 +625,15 @@
assert_equal(np.dtype(user_def_subcls).name, 'user_def_subcls')
-class TestPickling(TestCase):
+class TestPickling(object):
def check_pickling(self, dtype):
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
pickled = pickle.loads(pickle.dumps(dtype, proto))
assert_equal(pickled, dtype)
assert_equal(pickled.descr, dtype.descr)
- if dtype.metadata:
+ if dtype.metadata is not None:
assert_equal(pickled.metadata, dtype.metadata)
- else:
- self.assertFalse(pickled.metadata) # may be None
# Check the reconstructed dtype is functional
x = np.zeros(3, dtype=dtype)
y = np.zeros(3, dtype=pickled)
diff --git a/numpy/core/tests/test_einsum.py b/numpy/core/tests/test_einsum.py
index 1175833..7cc9f67 100644
--- a/numpy/core/tests/test_einsum.py
+++ b/numpy/core/tests/test_einsum.py
@@ -2,7 +2,7 @@
import numpy as np
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_equal, assert_array_equal,
+ run_module_suite, assert_, assert_equal, assert_array_equal,
assert_almost_equal, assert_raises, suppress_warnings
)
@@ -14,7 +14,7 @@
global_size_dict[char] = size
-class TestEinSum(TestCase):
+class TestEinSum(object):
def test_einsum_errors(self):
for do_opt in [True, False]:
# Need enough arguments
@@ -766,7 +766,7 @@
self.optimize_compare('aef,fbc,dca->bde')
-class TestEinSumPath(TestCase):
+class TestEinSumPath(object):
def build_operands(self, string):
# Builds views based off initial operands
diff --git a/numpy/core/tests/test_errstate.py b/numpy/core/tests/test_errstate.py
index 7fc749a..ae06af7 100644
--- a/numpy/core/tests/test_errstate.py
+++ b/numpy/core/tests/test_errstate.py
@@ -3,10 +3,10 @@
import platform
import numpy as np
-from numpy.testing import TestCase, assert_, run_module_suite, dec
+from numpy.testing import assert_, run_module_suite, dec
-class TestErrstate(TestCase):
+class TestErrstate(object):
@dec.skipif(platform.machine() == "armv5tel", "See gh-413.")
def test_invalid(self):
with np.errstate(all='raise', under='ignore'):
diff --git a/numpy/core/tests/test_function_base.py b/numpy/core/tests/test_function_base.py
index 94c55bd..bffe523 100644
--- a/numpy/core/tests/test_function_base.py
+++ b/numpy/core/tests/test_function_base.py
@@ -3,7 +3,7 @@
from numpy import (logspace, linspace, geomspace, dtype, array, sctypes,
arange, isnan, ndarray, sqrt, nextafter)
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_equal, assert_raises,
+ run_module_suite, assert_, assert_equal, assert_raises,
assert_array_equal, assert_allclose, suppress_warnings
)
@@ -40,7 +40,7 @@
__array_priority__ = 10
-class TestLogspace(TestCase):
+class TestLogspace(object):
def test_basic(self):
y = logspace(0, 6)
@@ -76,7 +76,7 @@
assert_equal(ls, logspace(1.0, 7.0, 1))
-class TestGeomspace(TestCase):
+class TestGeomspace(object):
def test_basic(self):
y = geomspace(1, 1e6)
@@ -191,7 +191,7 @@
assert_raises(ValueError, geomspace, 0, 0)
-class TestLinspace(TestCase):
+class TestLinspace(object):
def test_basic(self):
y = linspace(0, 10)
diff --git a/numpy/core/tests/test_getlimits.py b/numpy/core/tests/test_getlimits.py
index 4adb80f..64900b2 100644
--- a/numpy/core/tests/test_getlimits.py
+++ b/numpy/core/tests/test_getlimits.py
@@ -7,44 +7,44 @@
from numpy.core import finfo, iinfo
from numpy import half, single, double, longdouble
from numpy.testing import (
- TestCase, run_module_suite, assert_equal, assert_
+ run_module_suite, assert_equal, assert_, assert_raises
)
from numpy.core.getlimits import (_discovered_machar, _float16_ma, _float32_ma,
_float64_ma, _float128_ma, _float80_ma)
##################################################
-class TestPythonFloat(TestCase):
+class TestPythonFloat(object):
def test_singleton(self):
ftype = finfo(float)
ftype2 = finfo(float)
assert_equal(id(ftype), id(ftype2))
-class TestHalf(TestCase):
+class TestHalf(object):
def test_singleton(self):
ftype = finfo(half)
ftype2 = finfo(half)
assert_equal(id(ftype), id(ftype2))
-class TestSingle(TestCase):
+class TestSingle(object):
def test_singleton(self):
ftype = finfo(single)
ftype2 = finfo(single)
assert_equal(id(ftype), id(ftype2))
-class TestDouble(TestCase):
+class TestDouble(object):
def test_singleton(self):
ftype = finfo(double)
ftype2 = finfo(double)
assert_equal(id(ftype), id(ftype2))
-class TestLongdouble(TestCase):
+class TestLongdouble(object):
def test_singleton(self,level=2):
ftype = finfo(longdouble)
ftype2 = finfo(longdouble)
assert_equal(id(ftype), id(ftype2))
-class TestFinfo(TestCase):
+class TestFinfo(object):
def test_basic(self):
dts = list(zip(['f2', 'f4', 'f8', 'c8', 'c16'],
[np.float16, np.float32, np.float64, np.complex64,
@@ -55,9 +55,9 @@
'nmant', 'precision', 'resolution', 'tiny'):
assert_equal(getattr(finfo(dt1), attr),
getattr(finfo(dt2), attr), attr)
- self.assertRaises(ValueError, finfo, 'i4')
+ assert_raises(ValueError, finfo, 'i4')
-class TestIinfo(TestCase):
+class TestIinfo(object):
def test_basic(self):
dts = list(zip(['i1', 'i2', 'i4', 'i8',
'u1', 'u2', 'u4', 'u8'],
@@ -67,14 +67,14 @@
for attr in ('bits', 'min', 'max'):
assert_equal(getattr(iinfo(dt1), attr),
getattr(iinfo(dt2), attr), attr)
- self.assertRaises(ValueError, iinfo, 'f4')
+ assert_raises(ValueError, iinfo, 'f4')
def test_unsigned_max(self):
types = np.sctypes['uint']
for T in types:
assert_equal(iinfo(T).max, T(-1))
-class TestRepr(TestCase):
+class TestRepr(object):
def test_iinfo_repr(self):
expected = "iinfo(min=-32768, max=32767, dtype=int16)"
assert_equal(repr(np.iinfo(np.int16)), expected)
diff --git a/numpy/core/tests/test_half.py b/numpy/core/tests/test_half.py
index 7a4d363..9678f03 100644
--- a/numpy/core/tests/test_half.py
+++ b/numpy/core/tests/test_half.py
@@ -4,8 +4,7 @@
import numpy as np
from numpy import uint16, float16, float32, float64
-from numpy.testing import TestCase, run_module_suite, assert_, assert_equal, \
- dec
+from numpy.testing import run_module_suite, assert_, assert_equal, dec
def assert_raises_fpe(strmatch, callable, *args, **kwargs):
@@ -18,8 +17,8 @@
assert_(False,
"Did not raise floating point %s error" % strmatch)
-class TestHalf(TestCase):
- def setUp(self):
+class TestHalf(object):
+ def setup(self):
# An array of all possible float16 values
self.all_f16 = np.arange(0x10000, dtype=uint16)
self.all_f16.dtype = float16
diff --git a/numpy/core/tests/test_indexerrors.py b/numpy/core/tests/test_indexerrors.py
index e6b6be3..50919ff 100644
--- a/numpy/core/tests/test_indexerrors.py
+++ b/numpy/core/tests/test_indexerrors.py
@@ -1,9 +1,9 @@
from __future__ import division, absolute_import, print_function
import numpy as np
-from numpy.testing import TestCase, run_module_suite, assert_raises
+from numpy.testing import run_module_suite, assert_raises
-class TestIndexErrors(TestCase):
+class TestIndexErrors(object):
'''Tests to exercise indexerrors not covered by other tests.'''
def test_arraytypes_fasttake(self):
diff --git a/numpy/core/tests/test_indexing.py b/numpy/core/tests/test_indexing.py
index 1f8efe3..43965d9 100644
--- a/numpy/core/tests/test_indexing.py
+++ b/numpy/core/tests/test_indexing.py
@@ -9,7 +9,7 @@
from numpy.core.multiarray_tests import array_indexing
from itertools import product
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_equal, assert_raises,
+ run_module_suite, assert_, assert_equal, assert_raises,
assert_array_equal, assert_warns, HAS_REFCOUNT
)
@@ -28,7 +28,7 @@
_HAS_CTYPE = False
-class TestIndexing(TestCase):
+class TestIndexing(object):
def test_index_no_floats(self):
a = np.array([[[5]]])
@@ -511,7 +511,7 @@
arr[slices] = 10
assert_array_equal(arr, 10.)
-class TestFieldIndexing(TestCase):
+class TestFieldIndexing(object):
def test_scalar_return_type(self):
# Field access on an array should return an array, even if it
# is 0-d.
@@ -520,7 +520,7 @@
assert_(isinstance(a[['a']], np.ndarray))
-class TestBroadcastedAssignments(TestCase):
+class TestBroadcastedAssignments(object):
def assign(self, a, ind, val):
a[ind] = val
return a
@@ -571,7 +571,7 @@
assert_((a[::-1] == v).all())
-class TestSubclasses(TestCase):
+class TestSubclasses(object):
def test_basic(self):
class SubClass(np.ndarray):
pass
@@ -616,7 +616,7 @@
assert_array_equal(new_s.finalize_status, new_s)
assert_array_equal(new_s.old, s)
-class TestFancyIndexingCast(TestCase):
+class TestFancyIndexingCast(object):
def test_boolean_index_cast_assign(self):
# Setup the boolean index and float arrays.
shape = (8, 63)
@@ -638,7 +638,7 @@
zero_array.__setitem__, bool_index, np.array([1j]))
assert_equal(zero_array[0, 1], 0)
-class TestFancyIndexingEquivalence(TestCase):
+class TestFancyIndexingEquivalence(object):
def test_object_assign(self):
# Check that the field and object special case using copyto is active.
# The right hand side cannot be converted to an array here.
@@ -686,7 +686,7 @@
assert_array_equal(a, b[0])
-class TestMultiIndexingAutomated(TestCase):
+class TestMultiIndexingAutomated(object):
"""
These tests use code to mimic the C-Code indexing for selection.
@@ -708,7 +708,7 @@
"""
- def setUp(self):
+ def setup(self):
self.a = np.arange(np.prod([3, 1, 5, 6])).reshape(3, 1, 5, 6)
self.b = np.empty((3, 0, 5, 6))
self.complex_indices = ['skip', Ellipsis,
@@ -1103,7 +1103,7 @@
for index in self.complex_indices:
self._check_single_index(a, index)
-class TestFloatNonIntegerArgument(TestCase):
+class TestFloatNonIntegerArgument(object):
"""
These test that ``TypeError`` is raised when you try to use
non-integers as arguments to for indexing and slicing e.g. ``a[0.0:5]``
@@ -1158,7 +1158,7 @@
assert_raises(TypeError, np.min, d, (.2, 1.2))
-class TestBooleanIndexing(TestCase):
+class TestBooleanIndexing(object):
# Using a boolean as integer argument/indexing is an error.
def test_bool_as_int_argument_errors(self):
a = np.array([[[1]]])
@@ -1178,7 +1178,7 @@
assert_raises(IndexError, lambda: a[False, [0, 1], ...])
-class TestArrayToIndexDeprecation(TestCase):
+class TestArrayToIndexDeprecation(object):
"""Creating an an index from array not 0-D is an error.
"""
@@ -1191,7 +1191,7 @@
assert_raises(TypeError, np.take, a, [0], a)
-class TestNonIntegerArrayLike(TestCase):
+class TestNonIntegerArrayLike(object):
"""Tests that array_likes only valid if can safely cast to integer.
For instance, lists give IndexError when they cannot be safely cast to
@@ -1208,7 +1208,7 @@
a.__getitem__([])
-class TestMultipleEllipsisError(TestCase):
+class TestMultipleEllipsisError(object):
"""An index can only have a single ellipsis.
"""
@@ -1219,7 +1219,7 @@
assert_raises(IndexError, a.__getitem__, ((Ellipsis,) * 3,))
-class TestCApiAccess(TestCase):
+class TestCApiAccess(object):
def test_getitem(self):
subscript = functools.partial(array_indexing, 0)
diff --git a/numpy/core/tests/test_item_selection.py b/numpy/core/tests/test_item_selection.py
index 1eb09f1..2808897 100644
--- a/numpy/core/tests/test_item_selection.py
+++ b/numpy/core/tests/test_item_selection.py
@@ -4,12 +4,12 @@
import numpy as np
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_raises,
+ run_module_suite, assert_, assert_raises,
assert_array_equal, HAS_REFCOUNT
)
-class TestTake(TestCase):
+class TestTake(object):
def test_simple(self):
a = [[1, 2], [3, 4]]
a_str = [[b'1', b'2'], [b'3', b'4']]
diff --git a/numpy/core/tests/test_longdouble.py b/numpy/core/tests/test_longdouble.py
index eda52c9..ffdf518 100644
--- a/numpy/core/tests/test_longdouble.py
+++ b/numpy/core/tests/test_longdouble.py
@@ -5,7 +5,7 @@
import numpy as np
from numpy.testing import (
run_module_suite, assert_, assert_equal, dec, assert_raises,
- assert_array_equal, TestCase, temppath,
+ assert_array_equal, temppath,
)
from test_print import in_foreign_locale
@@ -110,7 +110,7 @@
np.array([1]))
-class FileBased(TestCase):
+class TestFileBased(object):
ldbl = 1 + LD_INFO.eps
tgt = np.array([ldbl]*5)
diff --git a/numpy/core/tests/test_machar.py b/numpy/core/tests/test_machar.py
index 765b38a..7acb02e 100644
--- a/numpy/core/tests/test_machar.py
+++ b/numpy/core/tests/test_machar.py
@@ -1,11 +1,16 @@
+"""
+Test machar. Given recent changes to hardcode type data, we might want to get
+rid of both MachAr and this test at some point.
+
+"""
from __future__ import division, absolute_import, print_function
from numpy.core.machar import MachAr
import numpy.core.numerictypes as ntypes
from numpy import errstate, array
-from numpy.testing import TestCase, run_module_suite
+from numpy.testing import run_module_suite
-class TestMachAr(TestCase):
+class TestMachAr(object):
def _run_machar_highprec(self):
# Instantiate MachAr instance with high enough precision to cause
# underflow
@@ -13,6 +18,7 @@
hiprec = ntypes.float96
MachAr(lambda v:array([v], hiprec))
except AttributeError:
+ # Fixme, this needs to raise a 'skip' exception.
"Skipping test: no ntypes.float96 available on this platform."
def test_underlow(self):
@@ -22,7 +28,8 @@
try:
self._run_machar_highprec()
except FloatingPointError as e:
- self.fail("Caught %s exception, should not have been raised." % e)
+ msg = "Caught %s exception, should not have been raised." % e
+ raise AssertionError(msg)
if __name__ == "__main__":
diff --git a/numpy/core/tests/test_memmap.py b/numpy/core/tests/test_memmap.py
index c0c3522..1cd09ab 100644
--- a/numpy/core/tests/test_memmap.py
+++ b/numpy/core/tests/test_memmap.py
@@ -12,12 +12,12 @@
from numpy import arange, allclose, asarray
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_equal, assert_array_equal,
+ run_module_suite, assert_, assert_equal, assert_array_equal,
dec, suppress_warnings
)
-class TestMemmap(TestCase):
- def setUp(self):
+class TestMemmap(object):
+ def setup(self):
self.tmpfp = NamedTemporaryFile(prefix='mmap')
self.tempdir = mkdtemp()
self.shape = (3, 4)
@@ -25,7 +25,7 @@
self.data = arange(12, dtype=self.dtype)
self.data.resize(self.shape)
- def tearDown(self):
+ def teardown(self):
self.tmpfp.close()
shutil.rmtree(self.tempdir)
@@ -41,7 +41,7 @@
shape=self.shape)
assert_(allclose(self.data, newfp))
assert_array_equal(self.data, newfp)
- self.assertEqual(newfp.flags.writeable, False)
+ assert_equal(newfp.flags.writeable, False)
def test_open_with_filename(self):
tmpname = mktemp('', 'mmap', dir=self.tempdir)
@@ -60,8 +60,8 @@
mode = "w+"
fp = memmap(self.tmpfp, dtype=self.dtype, mode=mode,
shape=self.shape, offset=offset)
- self.assertEqual(offset, fp.offset)
- self.assertEqual(mode, fp.mode)
+ assert_equal(offset, fp.offset)
+ assert_equal(mode, fp.mode)
del fp
def test_filename(self):
@@ -70,9 +70,9 @@
shape=self.shape)
abspath = os.path.abspath(tmpname)
fp[:] = self.data[:]
- self.assertEqual(abspath, fp.filename)
+ assert_equal(abspath, fp.filename)
b = fp[:1]
- self.assertEqual(abspath, b.filename)
+ assert_equal(abspath, b.filename)
del b
del fp
@@ -83,16 +83,16 @@
shape=self.shape)
abspath = os.path.realpath(os.path.abspath(tmpname))
fp[:] = self.data[:]
- self.assertEqual(abspath, str(fp.filename.resolve()))
+ assert_equal(abspath, str(fp.filename.resolve()))
b = fp[:1]
- self.assertEqual(abspath, str(b.filename.resolve()))
+ assert_equal(abspath, str(b.filename.resolve()))
del b
del fp
def test_filename_fileobj(self):
fp = memmap(self.tmpfp, dtype=self.dtype, mode="w+",
shape=self.shape)
- self.assertEqual(fp.filename, self.tmpfp.name)
+ assert_equal(fp.filename, self.tmpfp.name)
@dec.knownfailureif(sys.platform == 'gnu0', "This test is known to fail on hurd")
def test_flush(self):
diff --git a/numpy/core/tests/test_multiarray.py b/numpy/core/tests/test_multiarray.py
index c182a4d..21f4056 100644
--- a/numpy/core/tests/test_multiarray.py
+++ b/numpy/core/tests/test_multiarray.py
@@ -29,7 +29,7 @@
test_inplace_increment, get_buffer_info, test_as_c_array,
)
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_raises, assert_warns,
+ run_module_suite, assert_, assert_raises, assert_warns,
assert_equal, assert_almost_equal, assert_array_equal, assert_raises_regex,
assert_array_almost_equal, assert_allclose, IS_PYPY, HAS_REFCOUNT,
assert_array_less, runstring, dec, SkipTest, temppath, suppress_warnings
@@ -74,15 +74,15 @@
return data
-class TestFlags(TestCase):
- def setUp(self):
+class TestFlags(object):
+ def setup(self):
self.a = np.arange(10)
def test_writeable(self):
mydict = locals()
self.a.flags.writeable = False
- self.assertRaises(ValueError, runstring, 'self.a[0] = 3', mydict)
- self.assertRaises(ValueError, runstring, 'self.a[0:1].itemset(3)', mydict)
+ assert_raises(ValueError, runstring, 'self.a[0] = 3', mydict)
+ assert_raises(ValueError, runstring, 'self.a[0:1].itemset(3)', mydict)
self.a.flags.writeable = True
self.a[0] = 5
self.a[0] = 0
@@ -110,7 +110,7 @@
assert_(a.flags.aligned)
-class TestHash(TestCase):
+class TestHash(object):
# see #3793
def test_int(self):
for st, ut, s in [(np.int8, np.uint8, 8),
@@ -132,8 +132,8 @@
err_msg="%r: 2**%d - 1" % (ut, i))
-class TestAttributes(TestCase):
- def setUp(self):
+class TestAttributes(object):
+ def setup(self):
self.one = np.arange(10)
self.two = np.arange(20).reshape(4, 5)
self.three = np.arange(60, dtype=np.float64).reshape(2, 5, 6)
@@ -164,7 +164,7 @@
assert_equal(self.three.dtype, np.dtype(np.float_))
assert_equal(self.one.dtype.char, 'l')
assert_equal(self.three.dtype.char, 'd')
- self.assertTrue(self.three.dtype.str[0] in '<>')
+ assert_(self.three.dtype.str[0] in '<>')
assert_equal(self.one.dtype.str[1], 'i')
assert_equal(self.three.dtype.str[1], 'f')
@@ -194,12 +194,12 @@
strides=strides*x.itemsize)
assert_equal(make_array(4, 4, -1), np.array([4, 3, 2, 1]))
- self.assertRaises(ValueError, make_array, 4, 4, -2)
- self.assertRaises(ValueError, make_array, 4, 2, -1)
- self.assertRaises(ValueError, make_array, 8, 3, 1)
+ assert_raises(ValueError, make_array, 4, 4, -2)
+ assert_raises(ValueError, make_array, 4, 2, -1)
+ assert_raises(ValueError, make_array, 8, 3, 1)
assert_equal(make_array(8, 3, 0), np.array([3]*8))
# Check behavior reported in gh-2503:
- self.assertRaises(ValueError, make_array, (2, 3), 5, np.array([-2, -3]))
+ assert_raises(ValueError, make_array, (2, 3), 5, np.array([-2, -3]))
make_array(0, 0, 10)
def test_set_stridesattr(self):
@@ -216,9 +216,9 @@
assert_equal(make_array(4, 4, -1), np.array([4, 3, 2, 1]))
assert_equal(make_array(7, 3, 1), np.array([3, 4, 5, 6, 7, 8, 9]))
- self.assertRaises(ValueError, make_array, 4, 4, -2)
- self.assertRaises(ValueError, make_array, 4, 2, -1)
- self.assertRaises(RuntimeError, make_array, 8, 3, 1)
+ assert_raises(ValueError, make_array, 4, 4, -2)
+ assert_raises(ValueError, make_array, 4, 2, -1)
+ assert_raises(RuntimeError, make_array, 8, 3, 1)
# Check that the true extent of the array is used.
# Test relies on as_strided base not exposing a buffer.
x = np.lib.stride_tricks.as_strided(np.arange(1), (10, 10), (0, 0))
@@ -226,12 +226,12 @@
def set_strides(arr, strides):
arr.strides = strides
- self.assertRaises(ValueError, set_strides, x, (10*x.itemsize, x.itemsize))
+ assert_raises(ValueError, set_strides, x, (10*x.itemsize, x.itemsize))
# Test for offset calculations:
x = np.lib.stride_tricks.as_strided(np.arange(10, dtype=np.int8)[-1],
shape=(10,), strides=(-1,))
- self.assertRaises(ValueError, set_strides, x[::-1], -1)
+ assert_raises(ValueError, set_strides, x[::-1], -1)
a = x[::-1]
a.strides = 1
a[::2].strides = 2
@@ -265,7 +265,7 @@
assert_array_equal(x['b'], [-2, -2])
-class TestArrayConstruction(TestCase):
+class TestArrayConstruction(object):
def test_array(self):
d = np.ones(6)
r = np.array([d, d])
@@ -343,7 +343,7 @@
assert_(np.asfortranarray(d).flags.f_contiguous)
-class TestAssignment(TestCase):
+class TestAssignment(object):
def test_assignment_broadcasting(self):
a = np.arange(6).reshape(2, 3)
@@ -449,7 +449,7 @@
assert_equal(arr[0], tinya)
-class TestDtypedescr(TestCase):
+class TestDtypedescr(object):
def test_construction(self):
d1 = np.dtype('i4')
assert_equal(d1, np.dtype(np.int32))
@@ -457,48 +457,48 @@
assert_equal(d2, np.dtype(np.float64))
def test_byteorders(self):
- self.assertNotEqual(np.dtype('<i4'), np.dtype('>i4'))
- self.assertNotEqual(np.dtype([('a', '<i4')]), np.dtype([('a', '>i4')]))
+ assert_(np.dtype('<i4') != np.dtype('>i4'))
+ assert_(np.dtype([('a', '<i4')]) != np.dtype([('a', '>i4')]))
-class TestZeroRank(TestCase):
- def setUp(self):
+class TestZeroRank(object):
+ def setup(self):
self.d = np.array(0), np.array('x', object)
def test_ellipsis_subscript(self):
a, b = self.d
- self.assertEqual(a[...], 0)
- self.assertEqual(b[...], 'x')
- self.assertTrue(a[...].base is a) # `a[...] is a` in numpy <1.9.
- self.assertTrue(b[...].base is b) # `b[...] is b` in numpy <1.9.
+ assert_equal(a[...], 0)
+ assert_equal(b[...], 'x')
+ assert_(a[...].base is a) # `a[...] is a` in numpy <1.9.
+ assert_(b[...].base is b) # `b[...] is b` in numpy <1.9.
def test_empty_subscript(self):
a, b = self.d
- self.assertEqual(a[()], 0)
- self.assertEqual(b[()], 'x')
- self.assertTrue(type(a[()]) is a.dtype.type)
- self.assertTrue(type(b[()]) is str)
+ assert_equal(a[()], 0)
+ assert_equal(b[()], 'x')
+ assert_(type(a[()]) is a.dtype.type)
+ assert_(type(b[()]) is str)
def test_invalid_subscript(self):
a, b = self.d
- self.assertRaises(IndexError, lambda x: x[0], a)
- self.assertRaises(IndexError, lambda x: x[0], b)
- self.assertRaises(IndexError, lambda x: x[np.array([], int)], a)
- self.assertRaises(IndexError, lambda x: x[np.array([], int)], b)
+ assert_raises(IndexError, lambda x: x[0], a)
+ assert_raises(IndexError, lambda x: x[0], b)
+ assert_raises(IndexError, lambda x: x[np.array([], int)], a)
+ assert_raises(IndexError, lambda x: x[np.array([], int)], b)
def test_ellipsis_subscript_assignment(self):
a, b = self.d
a[...] = 42
- self.assertEqual(a, 42)
+ assert_equal(a, 42)
b[...] = ''
- self.assertEqual(b.item(), '')
+ assert_equal(b.item(), '')
def test_empty_subscript_assignment(self):
a, b = self.d
a[()] = 42
- self.assertEqual(a, 42)
+ assert_equal(a, 42)
b[()] = ''
- self.assertEqual(b.item(), '')
+ assert_equal(b.item(), '')
def test_invalid_subscript_assignment(self):
a, b = self.d
@@ -506,20 +506,20 @@
def assign(x, i, v):
x[i] = v
- self.assertRaises(IndexError, assign, a, 0, 42)
- self.assertRaises(IndexError, assign, b, 0, '')
- self.assertRaises(ValueError, assign, a, (), '')
+ assert_raises(IndexError, assign, a, 0, 42)
+ assert_raises(IndexError, assign, b, 0, '')
+ assert_raises(ValueError, assign, a, (), '')
def test_newaxis(self):
a, b = self.d
- self.assertEqual(a[np.newaxis].shape, (1,))
- self.assertEqual(a[..., np.newaxis].shape, (1,))
- self.assertEqual(a[np.newaxis, ...].shape, (1,))
- self.assertEqual(a[..., np.newaxis].shape, (1,))
- self.assertEqual(a[np.newaxis, ..., np.newaxis].shape, (1, 1))
- self.assertEqual(a[..., np.newaxis, np.newaxis].shape, (1, 1))
- self.assertEqual(a[np.newaxis, np.newaxis, ...].shape, (1, 1))
- self.assertEqual(a[(np.newaxis,)*10].shape, (1,)*10)
+ assert_equal(a[np.newaxis].shape, (1,))
+ assert_equal(a[..., np.newaxis].shape, (1,))
+ assert_equal(a[np.newaxis, ...].shape, (1,))
+ assert_equal(a[..., np.newaxis].shape, (1,))
+ assert_equal(a[np.newaxis, ..., np.newaxis].shape, (1, 1))
+ assert_equal(a[..., np.newaxis, np.newaxis].shape, (1, 1))
+ assert_equal(a[np.newaxis, np.newaxis, ...].shape, (1, 1))
+ assert_equal(a[(np.newaxis,)*10].shape, (1,)*10)
def test_invalid_newaxis(self):
a, b = self.d
@@ -527,40 +527,40 @@
def subscript(x, i):
x[i]
- self.assertRaises(IndexError, subscript, a, (np.newaxis, 0))
- self.assertRaises(IndexError, subscript, a, (np.newaxis,)*50)
+ assert_raises(IndexError, subscript, a, (np.newaxis, 0))
+ assert_raises(IndexError, subscript, a, (np.newaxis,)*50)
def test_constructor(self):
x = np.ndarray(())
x[()] = 5
- self.assertEqual(x[()], 5)
+ assert_equal(x[()], 5)
y = np.ndarray((), buffer=x)
y[()] = 6
- self.assertEqual(x[()], 6)
+ assert_equal(x[()], 6)
def test_output(self):
x = np.array(2)
- self.assertRaises(ValueError, np.add, x, [1], x)
+ assert_raises(ValueError, np.add, x, [1], x)
-class TestScalarIndexing(TestCase):
- def setUp(self):
+class TestScalarIndexing(object):
+ def setup(self):
self.d = np.array([0, 1])[0]
def test_ellipsis_subscript(self):
a = self.d
- self.assertEqual(a[...], 0)
- self.assertEqual(a[...].shape, ())
+ assert_equal(a[...], 0)
+ assert_equal(a[...].shape, ())
def test_empty_subscript(self):
a = self.d
- self.assertEqual(a[()], 0)
- self.assertEqual(a[()].shape, ())
+ assert_equal(a[()], 0)
+ assert_equal(a[()].shape, ())
def test_invalid_subscript(self):
a = self.d
- self.assertRaises(IndexError, lambda x: x[0], a)
- self.assertRaises(IndexError, lambda x: x[np.array([], int)], a)
+ assert_raises(IndexError, lambda x: x[0], a)
+ assert_raises(IndexError, lambda x: x[np.array([], int)], a)
def test_invalid_subscript_assignment(self):
a = self.d
@@ -568,18 +568,18 @@
def assign(x, i, v):
x[i] = v
- self.assertRaises(TypeError, assign, a, 0, 42)
+ assert_raises(TypeError, assign, a, 0, 42)
def test_newaxis(self):
a = self.d
- self.assertEqual(a[np.newaxis].shape, (1,))
- self.assertEqual(a[..., np.newaxis].shape, (1,))
- self.assertEqual(a[np.newaxis, ...].shape, (1,))
- self.assertEqual(a[..., np.newaxis].shape, (1,))
- self.assertEqual(a[np.newaxis, ..., np.newaxis].shape, (1, 1))
- self.assertEqual(a[..., np.newaxis, np.newaxis].shape, (1, 1))
- self.assertEqual(a[np.newaxis, np.newaxis, ...].shape, (1, 1))
- self.assertEqual(a[(np.newaxis,)*10].shape, (1,)*10)
+ assert_equal(a[np.newaxis].shape, (1,))
+ assert_equal(a[..., np.newaxis].shape, (1,))
+ assert_equal(a[np.newaxis, ...].shape, (1,))
+ assert_equal(a[..., np.newaxis].shape, (1,))
+ assert_equal(a[np.newaxis, ..., np.newaxis].shape, (1, 1))
+ assert_equal(a[..., np.newaxis, np.newaxis].shape, (1, 1))
+ assert_equal(a[np.newaxis, np.newaxis, ...].shape, (1, 1))
+ assert_equal(a[(np.newaxis,)*10].shape, (1,)*10)
def test_invalid_newaxis(self):
a = self.d
@@ -587,8 +587,8 @@
def subscript(x, i):
x[i]
- self.assertRaises(IndexError, subscript, a, (np.newaxis, 0))
- self.assertRaises(IndexError, subscript, a, (np.newaxis,)*50)
+ assert_raises(IndexError, subscript, a, (np.newaxis, 0))
+ assert_raises(IndexError, subscript, a, (np.newaxis,)*50)
def test_overlapping_assignment(self):
# With positive strides
@@ -639,13 +639,13 @@
assert_equal(a, [0, 1, 0, 1, 2])
-class TestCreation(TestCase):
+class TestCreation(object):
def test_from_attribute(self):
class x(object):
def __array__(self, dtype=None):
pass
- self.assertRaises(ValueError, np.array, x())
+ assert_raises(ValueError, np.array, x())
def test_from_string(self):
types = np.typecodes['AllInteger'] + np.typecodes['Float']
@@ -856,7 +856,7 @@
shape=(max_bytes//itemsize + 1,), dtype=dtype)
-class TestStructured(TestCase):
+class TestStructured(object):
def test_subarray_field_access(self):
a = np.zeros((3, 5), dtype=[('a', ('i4', (2, 2)))])
a['a'] = np.arange(60).reshape(3, 5, 2, 2)
@@ -1097,16 +1097,16 @@
assert_(b.base is a)
-class TestBool(TestCase):
+class TestBool(object):
def test_test_interning(self):
a0 = np.bool_(0)
b0 = np.bool_(False)
- self.assertTrue(a0 is b0)
+ assert_(a0 is b0)
a1 = np.bool_(1)
b1 = np.bool_(True)
- self.assertTrue(a1 is b1)
- self.assertTrue(np.array([True])[0] is a1)
- self.assertTrue(np.array(True)[()] is a1)
+ assert_(a1 is b1)
+ assert_(np.array([True])[0] is a1)
+ assert_(np.array(True)[()] is a1)
def test_sum(self):
d = np.ones(101, dtype=np.bool)
@@ -1125,14 +1125,14 @@
l = [(i & x) != 0 for x in powers]
a = np.array(l, dtype=np.bool)
c = builtins.sum(l)
- self.assertEqual(np.count_nonzero(a), c)
+ assert_equal(np.count_nonzero(a), c)
av = a.view(np.uint8)
av *= 3
- self.assertEqual(np.count_nonzero(a), c)
+ assert_equal(np.count_nonzero(a), c)
av *= 4
- self.assertEqual(np.count_nonzero(a), c)
+ assert_equal(np.count_nonzero(a), c)
av[av != 0] = 0xFF
- self.assertEqual(np.count_nonzero(a), c)
+ assert_equal(np.count_nonzero(a), c)
def test_count_nonzero(self):
# check all 12 bit combinations in a length 17 array
@@ -1150,13 +1150,13 @@
for o in range(7):
a = np.zeros((18,), dtype=np.bool)[o+1:]
a[:o] = True
- self.assertEqual(np.count_nonzero(a), builtins.sum(a.tolist()))
+ assert_equal(np.count_nonzero(a), builtins.sum(a.tolist()))
a = np.ones((18,), dtype=np.bool)[o+1:]
a[:o] = False
- self.assertEqual(np.count_nonzero(a), builtins.sum(a.tolist()))
+ assert_equal(np.count_nonzero(a), builtins.sum(a.tolist()))
-class TestMethods(TestCase):
+class TestMethods(object):
def test_compress(self):
tgt = [[5, 6, 7, 8, 9]]
arr = np.arange(10).reshape(2, 5)
@@ -1201,8 +1201,8 @@
a = np.array(ba, ctype)
a2 = np.array(ba2, ctype)
if ctype in ['1', 'b']:
- self.assertRaises(ArithmeticError, a.prod)
- self.assertRaises(ArithmeticError, a2.prod, axis=1)
+ assert_raises(ArithmeticError, a.prod)
+ assert_raises(ArithmeticError, a2.prod, axis=1)
else:
assert_equal(a.prod(axis=0), 26400)
assert_array_equal(a2.prod(axis=0),
@@ -1283,9 +1283,9 @@
def test_transpose(self):
a = np.array([[1, 2], [3, 4]])
assert_equal(a.transpose(), [[1, 3], [2, 4]])
- self.assertRaises(ValueError, lambda: a.transpose(0))
- self.assertRaises(ValueError, lambda: a.transpose(0, 0))
- self.assertRaises(ValueError, lambda: a.transpose(0, 1, 2))
+ assert_raises(ValueError, lambda: a.transpose(0))
+ assert_raises(ValueError, lambda: a.transpose(0, 0))
+ assert_raises(ValueError, lambda: a.transpose(0, 1, 2))
def test_sort(self):
# test ordering for floats and complex containing nans. It is only
@@ -2044,8 +2044,8 @@
# sorted
d = np.arange(49)
- self.assertEqual(np.partition(d, 5, kind=k)[5], 5)
- self.assertEqual(np.partition(d, 15, kind=k)[15], 15)
+ assert_equal(np.partition(d, 5, kind=k)[5], 5)
+ assert_equal(np.partition(d, 15, kind=k)[15], 15)
assert_array_equal(d[np.argpartition(d, 5, kind=k)],
np.partition(d, 5, kind=k))
assert_array_equal(d[np.argpartition(d, 15, kind=k)],
@@ -2053,8 +2053,8 @@
# rsorted
d = np.arange(47)[::-1]
- self.assertEqual(np.partition(d, 6, kind=k)[6], 6)
- self.assertEqual(np.partition(d, 16, kind=k)[16], 16)
+ assert_equal(np.partition(d, 6, kind=k)[6], 6)
+ assert_equal(np.partition(d, 16, kind=k)[16], 16)
assert_array_equal(d[np.argpartition(d, 6, kind=k)],
np.partition(d, 6, kind=k))
assert_array_equal(d[np.argpartition(d, 16, kind=k)],
@@ -2094,7 +2094,7 @@
tgt = np.sort(np.arange(47) % 7)
np.random.shuffle(d)
for i in range(d.size):
- self.assertEqual(np.partition(d, i, kind=k)[i], tgt[i])
+ assert_equal(np.partition(d, i, kind=k)[i], tgt[i])
assert_array_equal(d[np.argpartition(d, 6, kind=k)],
np.partition(d, 6, kind=k))
assert_array_equal(d[np.argpartition(d, 16, kind=k)],
@@ -2146,7 +2146,7 @@
for s in (9, 16)]
for dt, s in td:
aae = assert_array_equal
- at = self.assertTrue
+ at = assert_
d = np.arange(s, dtype=dt)
np.random.shuffle(d)
@@ -2155,7 +2155,7 @@
d0 = np.transpose(d1)
for i in range(d.size):
p = np.partition(d, i, kind=k)
- self.assertEqual(p[i], i)
+ assert_equal(p[i], i)
# all before are smaller
assert_array_less(p[:i], p[i])
# all after are larger
@@ -2522,7 +2522,7 @@
b = np.arange(8).reshape((2, 2, 2)).view(MyArray)
t = b.trace()
- assert isinstance(t, MyArray)
+ assert_(isinstance(t, MyArray))
def test_put(self):
icodes = np.typecodes['AllInteger']
@@ -3109,7 +3109,7 @@
a ** 2
-class TestTemporaryElide(TestCase):
+class TestTemporaryElide(object):
# elision is only triggered on relatively large arrays
def test_extension_incref_elide(self):
@@ -3202,7 +3202,7 @@
assert_equal(a, 1)
-class TestCAPI(TestCase):
+class TestCAPI(object):
def test_IsPythonScalar(self):
from numpy.core.multiarray_tests import IsPythonScalar
assert_(IsPythonScalar(b'foobar'))
@@ -3212,16 +3212,16 @@
assert_(IsPythonScalar("a"))
-class TestSubscripting(TestCase):
+class TestSubscripting(object):
def test_test_zero_rank(self):
x = np.array([1, 2, 3])
- self.assertTrue(isinstance(x[0], np.int_))
+ assert_(isinstance(x[0], np.int_))
if sys.version_info[0] < 3:
- self.assertTrue(isinstance(x[0], int))
- self.assertTrue(type(x[0, ...]) is np.ndarray)
+ assert_(isinstance(x[0], int))
+ assert_(type(x[0, ...]) is np.ndarray)
-class TestPickling(TestCase):
+class TestPickling(object):
def test_roundtrip(self):
import pickle
carray = np.array([[2, 9], [7, 0], [3, 8]])
@@ -3287,7 +3287,7 @@
assert_equal(a, p)
-class TestFancyIndexing(TestCase):
+class TestFancyIndexing(object):
def test_list(self):
x = np.ones((1, 1))
x[:, [0]] = 2.0
@@ -3341,7 +3341,7 @@
assert_array_equal(x, np.array([[1, 10, 3, 4], [5, 6, 7, 8]]))
-class TestStringCompare(TestCase):
+class TestStringCompare(object):
def test_string(self):
g1 = np.array(["This", "is", "example"])
g2 = np.array(["This", "was", "example"])
@@ -3373,7 +3373,7 @@
assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0, 1, 2]])
-class TestArgmax(TestCase):
+class TestArgmax(object):
nan_arr = [
([0, 1, 2, 3, np.nan], 4),
@@ -3507,7 +3507,7 @@
assert_equal(a.argmax(), 1)
-class TestArgmin(TestCase):
+class TestArgmin(object):
nan_arr = [
([0, 1, 2, 3, np.nan], 4),
@@ -3655,7 +3655,7 @@
assert_equal(a.argmin(), 1)
-class TestMinMax(TestCase):
+class TestMinMax(object):
def test_scalar(self):
assert_raises(np.AxisError, np.amax, 1, 1)
@@ -3685,14 +3685,14 @@
assert_equal(np.amax(a), a[0])
-class TestNewaxis(TestCase):
+class TestNewaxis(object):
def test_basic(self):
sk = np.array([0, -0.1, 0.1])
res = 250*sk[:, np.newaxis]
assert_almost_equal(res.ravel(), 250*sk)
-class TestClip(TestCase):
+class TestClip(object):
def _check_range(self, x, cmin, cmax):
assert_(np.all(x >= cmin))
assert_(np.all(x <= cmax))
@@ -3766,7 +3766,7 @@
assert_array_equal(result, expected)
-class TestCompress(TestCase):
+class TestCompress(object):
def test_axis(self):
tgt = [[5, 6, 7, 8, 9]]
arr = np.arange(10).reshape(2, 5)
@@ -3884,7 +3884,7 @@
assert_(rec1['x'] == 5.0 and rec1['y'] == 4.0)
-class TestLexsort(TestCase):
+class TestLexsort(object):
def test_basic(self):
a = [1, 2, 1, 3, 1, 5]
b = [0, 4, 5, 6, 2, 3]
@@ -3931,10 +3931,10 @@
x = np.linspace(0., 1., 42*3).reshape(42, 3)
assert_raises(np.AxisError, np.lexsort, x, axis=2)
-class TestIO(TestCase):
+class TestIO(object):
"""Test tofile, fromfile, tobytes, and fromstring"""
- def setUp(self):
+ def setup(self):
shape = (2, 4, 3)
rand = np.random.random
self.x = rand(shape) + rand(shape).astype(np.complex)*1j
@@ -3943,7 +3943,7 @@
self.tempdir = tempfile.mkdtemp()
self.filename = tempfile.mktemp(dir=self.tempdir)
- def tearDown(self):
+ def teardown(self):
shutil.rmtree(self.tempdir)
def test_nofile(self):
@@ -4032,7 +4032,7 @@
with io.open(self.filename, 'rb', buffering=0) as f:
f.seek = fail
f.tell = fail
- self.assertRaises(IOError, np.fromfile, f, dtype=self.dtype)
+ assert_raises(IOError, np.fromfile, f, dtype=self.dtype)
def test_io_open_unbuffered_fromfile(self):
# gh-6632
@@ -4263,8 +4263,8 @@
yield self.tst_basic, b'', np.array([]), {}
-class TestFlat(TestCase):
- def setUp(self):
+class TestFlat(object):
+ def setup(self):
a0 = np.arange(20.0)
a = a0.reshape(4, 5)
a0.shape = (4, 5)
@@ -4310,7 +4310,7 @@
assert_(f.base is self.b0)
-class TestResize(TestCase):
+class TestResize(object):
def test_basic(self):
x = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
if IS_PYPY:
@@ -4324,7 +4324,7 @@
def test_check_reference(self):
x = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
y = x
- self.assertRaises(ValueError, x.resize, (5, 1))
+ assert_raises(ValueError, x.resize, (5, 1))
del y # avoid pyflakes unused variable warning.
def test_int_shape(self):
@@ -4355,10 +4355,10 @@
assert_equal(x.size, 1)
def test_invalid_arguments(self):
- self.assertRaises(TypeError, np.eye(3).resize, 'hi')
- self.assertRaises(ValueError, np.eye(3).resize, -1)
- self.assertRaises(TypeError, np.eye(3).resize, order=1)
- self.assertRaises(TypeError, np.eye(3).resize, refcheck='hi')
+ assert_raises(TypeError, np.eye(3).resize, 'hi')
+ assert_raises(ValueError, np.eye(3).resize, -1)
+ assert_raises(TypeError, np.eye(3).resize, order=1)
+ assert_raises(TypeError, np.eye(3).resize, refcheck='hi')
def test_freeform_shape(self):
x = np.eye(3)
@@ -4389,7 +4389,7 @@
assert_array_equal(a['k'][:-5], 1)
-class TestRecord(TestCase):
+class TestRecord(object):
def test_field_rename(self):
dt = np.dtype([('f', float), ('i', int)])
dt.names = ['p', 'q']
@@ -4565,14 +4565,14 @@
b.flags.writeable = False
c = np.array([(1, 2), (3, 4)], dtype='i1,i2')
c.flags.writeable = False
- self.assertTrue(hash(a[0]) == hash(a[1]))
- self.assertTrue(hash(a[0]) == hash(b[0]))
- self.assertTrue(hash(a[0]) != hash(b[1]))
- self.assertTrue(hash(c[0]) == hash(a[0]) and c[0] == a[0])
+ assert_(hash(a[0]) == hash(a[1]))
+ assert_(hash(a[0]) == hash(b[0]))
+ assert_(hash(a[0]) != hash(b[1]))
+ assert_(hash(c[0]) == hash(a[0]) and c[0] == a[0])
def test_record_no_hash(self):
a = np.array([(1, 2), (1, 2)], dtype='i1,i2')
- self.assertRaises(TypeError, hash, a[0])
+ assert_raises(TypeError, hash, a[0])
def test_empty_structure_creation(self):
# make sure these do not raise errors (gh-5631)
@@ -4581,7 +4581,7 @@
np.array([(), (), (), (), ()], dtype={'names': [], 'formats': [],
'offsets': [], 'itemsize': 12})
-class TestView(TestCase):
+class TestView(object):
def test_basic(self):
x = np.array([(1, 2, 3, 4), (5, 6, 7, 8)],
dtype=[('r', np.int8), ('g', np.int8),
@@ -4606,11 +4606,11 @@
return a.std(**args)
-class TestStats(TestCase):
+class TestStats(object):
funcs = [_mean, _var, _std]
- def setUp(self):
+ def setup(self):
np.random.seed(range(3))
self.rmat = np.random.random((4, 5))
self.cmat = self.rmat + 1j * self.rmat
@@ -4776,7 +4776,7 @@
def test_mean_float16(self):
# This fail if the sum inside mean is done in float16 instead
# of float32.
- assert _mean(np.ones(100000, dtype='float16')) == 1
+ assert_(_mean(np.ones(100000, dtype='float16')) == 1)
def test_var_values(self):
for mat in [self.rmat, self.cmat, self.omat]:
@@ -4813,7 +4813,7 @@
res = dat.var(1)
assert_(res.info == dat.info)
-class TestVdot(TestCase):
+class TestVdot(object):
def test_basic(self):
dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger']
dt_complex = np.typecodes['Complex']
@@ -4873,8 +4873,8 @@
np.vdot(a.flatten(), b.flatten()))
-class TestDot(TestCase):
- def setUp(self):
+class TestDot(object):
+ def setup(self):
np.random.seed(128)
self.A = np.random.rand(4, 2)
self.b1 = np.random.rand(2, 1)
@@ -5151,7 +5151,7 @@
assert_dot_close(A_f_12, X_f_2, desired)
-class MatmulCommon():
+class MatmulCommon(object):
"""Common tests for '@' operator and numpy.matmul.
Do not derive from TestCase to avoid nose running it.
@@ -5346,7 +5346,7 @@
assert_equal(res, tgt12_21)
-class TestMatmul(MatmulCommon, TestCase):
+class TestMatmul(MatmulCommon):
matmul = np.matmul
def test_out_arg(self):
@@ -5391,7 +5391,7 @@
if sys.version_info[:2] >= (3, 5):
- class TestMatmulOperator(MatmulCommon, TestCase):
+ class TestMatmulOperator(MatmulCommon):
import operator
matmul = operator.matmul
@@ -5426,7 +5426,7 @@
assert_raises(TypeError, exec_, "a @= b", globals(), locals())
-class TestInner(TestCase):
+class TestInner(object):
def test_inner_type_mismatch(self):
c = 1.
@@ -5519,7 +5519,7 @@
assert_equal(np.inner(b, a).transpose(2,3,0,1), desired)
-class TestSummarization(TestCase):
+class TestSummarization(object):
def test_1d(self):
A = np.arange(1001)
strA = '[ 0 1 2 ..., 998 999 1000]'
@@ -5539,26 +5539,26 @@
assert_(repr(A) == reprA)
-class TestAlen(TestCase):
+class TestAlen(object):
def test_basic(self):
m = np.array([1, 2, 3])
- self.assertEqual(np.alen(m), 3)
+ assert_equal(np.alen(m), 3)
m = np.array([[1, 2, 3], [4, 5, 7]])
- self.assertEqual(np.alen(m), 2)
+ assert_equal(np.alen(m), 2)
m = [1, 2, 3]
- self.assertEqual(np.alen(m), 3)
+ assert_equal(np.alen(m), 3)
m = [[1, 2, 3], [4, 5, 7]]
- self.assertEqual(np.alen(m), 2)
+ assert_equal(np.alen(m), 2)
def test_singleton(self):
- self.assertEqual(np.alen(5), 1)
+ assert_equal(np.alen(5), 1)
-class TestChoose(TestCase):
- def setUp(self):
+class TestChoose(object):
+ def setup(self):
self.x = 2*np.ones((3,), dtype=int)
self.y = 3*np.ones((3,), dtype=int)
self.x2 = 2*np.ones((2, 3), dtype=int)
@@ -5578,8 +5578,8 @@
assert_equal(A, [[2, 2, 3], [2, 2, 3]])
-class TestRepeat(TestCase):
- def setUp(self):
+class TestRepeat(object):
+ def setup(self):
self.m = np.array([1, 2, 3, 4, 5, 6])
self.m_rect = self.m.reshape((2, 3))
@@ -5619,7 +5619,7 @@
NEIGH_MODE = {'zero': 0, 'one': 1, 'constant': 2, 'circular': 3, 'mirror': 4}
-class TestNeighborhoodIter(TestCase):
+class TestNeighborhoodIter(object):
# Simple, 2d tests
def _test_simple2d(self, dt):
# Test zero and one padding for simple data type
@@ -5698,7 +5698,7 @@
r = np.array([[2, 1, 1, 2, 3], [1, 1, 2, 3, 4], [1, 2, 3, 4, 5],
[2, 3, 4, 5, 5], [3, 4, 5, 5, 4]], dtype=dt)
l = test_neighborhood_iterator(x, [-2, 2], x[1], NEIGH_MODE['mirror'])
- self.assertTrue([i.dtype == dt for i in l])
+ assert_([i.dtype == dt for i in l])
assert_array_equal(l, r)
def test_mirror(self):
@@ -5722,7 +5722,7 @@
self._test_circular(Decimal)
# Test stacking neighborhood iterators
-class TestStackedNeighborhoodIter(TestCase):
+class TestStackedNeighborhoodIter(object):
# Simple, 1d test: stacking 2 constant-padded neigh iterators
def test_simple_const(self):
dt = np.float64
@@ -6412,7 +6412,7 @@
assert_raises(ValueError, a[0].__delitem__, 'x')
-class TestMemEventHook(TestCase):
+class TestMemEventHook(object):
def test_mem_seteventhook(self):
# The actual tests are within the C code in
# multiarray/multiarray_tests.c.src
@@ -6424,7 +6424,7 @@
gc.collect()
test_pydatamem_seteventhook_end()
-class TestMapIter(TestCase):
+class TestMapIter(object):
def test_mapiter(self):
# The actual tests are within the C code in
# multiarray/multiarray_tests.c.src
@@ -6446,7 +6446,7 @@
assert_equal(b, [100.1, 51., 6., 3., 4., 5.])
-class TestAsCArray(TestCase):
+class TestAsCArray(object):
def test_1darray(self):
array = np.arange(24, dtype=np.double)
from_c = test_as_c_array(array, 3)
@@ -6463,7 +6463,7 @@
assert_equal(array[1, 2, 3], from_c)
-class TestConversion(TestCase):
+class TestConversion(object):
def test_array_scalar_relational_operation(self):
# All integer
for dt1 in np.typecodes['AllInteger']:
@@ -6528,7 +6528,7 @@
assert_raises(Error, bool, self_containing) # previously stack overflow
-class TestWhere(TestCase):
+class TestWhere(object):
def test_basic(self):
dts = [np.bool, np.int16, np.int32, np.int64, np.double, np.complex128,
np.longdouble, np.clongdouble]
@@ -6695,7 +6695,7 @@
if not IS_PYPY:
# sys.getsizeof() is not valid on PyPy
- class TestSizeOf(TestCase):
+ class TestSizeOf(object):
def test_empty_array(self):
x = np.array([])
@@ -6741,7 +6741,7 @@
assert_raises(TypeError, d.__sizeof__, "a")
-class TestHashing(TestCase):
+class TestHashing(object):
def test_arrays_not_hashable(self):
x = np.ones(3)
@@ -6749,10 +6749,10 @@
def test_collections_hashable(self):
x = np.array([])
- self.assertFalse(isinstance(x, collections.Hashable))
+ assert_(not isinstance(x, collections.Hashable))
-class TestArrayPriority(TestCase):
+class TestArrayPriority(object):
# This will go away when __array_priority__ is settled, meanwhile
# it serves to check unintended changes.
op = operator
@@ -6838,54 +6838,54 @@
assert_(isinstance(f(b, a), self.Other), msg)
-class TestBytestringArrayNonzero(TestCase):
+class TestBytestringArrayNonzero(object):
def test_empty_bstring_array_is_falsey(self):
- self.assertFalse(np.array([''], dtype=np.str))
+ assert_(not np.array([''], dtype=np.str))
def test_whitespace_bstring_array_is_falsey(self):
a = np.array(['spam'], dtype=np.str)
a[0] = ' \0\0'
- self.assertFalse(a)
+ assert_(not a)
def test_all_null_bstring_array_is_falsey(self):
a = np.array(['spam'], dtype=np.str)
a[0] = '\0\0\0\0'
- self.assertFalse(a)
+ assert_(not a)
def test_null_inside_bstring_array_is_truthy(self):
a = np.array(['spam'], dtype=np.str)
a[0] = ' \0 \0'
- self.assertTrue(a)
+ assert_(a)
-class TestUnicodeArrayNonzero(TestCase):
+class TestUnicodeArrayNonzero(object):
def test_empty_ustring_array_is_falsey(self):
- self.assertFalse(np.array([''], dtype=np.unicode))
+ assert_(not np.array([''], dtype=np.unicode))
def test_whitespace_ustring_array_is_falsey(self):
a = np.array(['eggs'], dtype=np.unicode)
a[0] = ' \0\0'
- self.assertFalse(a)
+ assert_(not a)
def test_all_null_ustring_array_is_falsey(self):
a = np.array(['eggs'], dtype=np.unicode)
a[0] = '\0\0\0\0'
- self.assertFalse(a)
+ assert_(not a)
def test_null_inside_ustring_array_is_truthy(self):
a = np.array(['eggs'], dtype=np.unicode)
a[0] = ' \0 \0'
- self.assertTrue(a)
+ assert_(a)
-class TestCTypes(TestCase):
+class TestCTypes(object):
def test_ctypes_is_available(self):
test_arr = np.array([[1, 2, 3], [4, 5, 6]])
- self.assertEqual(ctypes, test_arr.ctypes._ctypes)
+ assert_equal(ctypes, test_arr.ctypes._ctypes)
assert_equal(tuple(test_arr.ctypes.shape), (2, 3))
def test_ctypes_is_not_available(self):
@@ -6894,8 +6894,8 @@
try:
test_arr = np.array([[1, 2, 3], [4, 5, 6]])
- self.assertIsInstance(
- test_arr.ctypes._ctypes, _internal._missing_ctypes)
+ assert_(isinstance(test_arr.ctypes._ctypes,
+ _internal._missing_ctypes))
assert_equal(tuple(test_arr.ctypes.shape), (2, 3))
finally:
_internal.ctypes = ctypes
diff --git a/numpy/core/tests/test_numeric.py b/numpy/core/tests/test_numeric.py
index 1e51c4a..d597c92 100644
--- a/numpy/core/tests/test_numeric.py
+++ b/numpy/core/tests/test_numeric.py
@@ -10,13 +10,13 @@
from numpy.core import umath
from numpy.random import rand, randint, randn
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_equal, assert_raises,
+ run_module_suite, assert_, assert_equal, assert_raises,
assert_raises_regex, assert_array_equal, assert_almost_equal,
assert_array_almost_equal, dec, HAS_REFCOUNT, suppress_warnings
)
-class TestResize(TestCase):
+class TestResize(object):
def test_copies(self):
A = np.array([[1, 2], [3, 4]])
Ar1 = np.array([[1, 2, 3, 4], [1, 2, 3, 4]])
@@ -48,7 +48,7 @@
assert_equal(A.dtype, Ar.dtype)
-class TestNonarrayArgs(TestCase):
+class TestNonarrayArgs(object):
# check that non-array arguments to functions wrap them in arrays
def test_choose(self):
choices = [[0, 1, 2],
@@ -208,41 +208,41 @@
assert_(w[0].category is RuntimeWarning)
-class TestBoolScalar(TestCase):
+class TestBoolScalar(object):
def test_logical(self):
f = np.False_
t = np.True_
s = "xyz"
- self.assertTrue((t and s) is s)
- self.assertTrue((f and s) is f)
+ assert_((t and s) is s)
+ assert_((f and s) is f)
def test_bitwise_or(self):
f = np.False_
t = np.True_
- self.assertTrue((t | t) is t)
- self.assertTrue((f | t) is t)
- self.assertTrue((t | f) is t)
- self.assertTrue((f | f) is f)
+ assert_((t | t) is t)
+ assert_((f | t) is t)
+ assert_((t | f) is t)
+ assert_((f | f) is f)
def test_bitwise_and(self):
f = np.False_
t = np.True_
- self.assertTrue((t & t) is t)
- self.assertTrue((f & t) is f)
- self.assertTrue((t & f) is f)
- self.assertTrue((f & f) is f)
+ assert_((t & t) is t)
+ assert_((f & t) is f)
+ assert_((t & f) is f)
+ assert_((f & f) is f)
def test_bitwise_xor(self):
f = np.False_
t = np.True_
- self.assertTrue((t ^ t) is f)
- self.assertTrue((f ^ t) is t)
- self.assertTrue((t ^ f) is t)
- self.assertTrue((f ^ f) is f)
+ assert_((t ^ t) is f)
+ assert_((f ^ t) is t)
+ assert_((t ^ f) is t)
+ assert_((f ^ f) is f)
-class TestBoolArray(TestCase):
- def setUp(self):
+class TestBoolArray(object):
+ def setup(self):
# offset for simd tests
self.t = np.array([True] * 41, dtype=np.bool)[1::]
self.f = np.array([False] * 41, dtype=np.bool)[1::]
@@ -255,31 +255,31 @@
self.im[-2] = False
def test_all_any(self):
- self.assertTrue(self.t.all())
- self.assertTrue(self.t.any())
- self.assertFalse(self.f.all())
- self.assertFalse(self.f.any())
- self.assertTrue(self.nm.any())
- self.assertTrue(self.im.any())
- self.assertFalse(self.nm.all())
- self.assertFalse(self.im.all())
+ assert_(self.t.all())
+ assert_(self.t.any())
+ assert_(not self.f.all())
+ assert_(not self.f.any())
+ assert_(self.nm.any())
+ assert_(self.im.any())
+ assert_(not self.nm.all())
+ assert_(not self.im.all())
# check bad element in all positions
for i in range(256 - 7):
d = np.array([False] * 256, dtype=np.bool)[7::]
d[i] = True
- self.assertTrue(np.any(d))
+ assert_(np.any(d))
e = np.array([True] * 256, dtype=np.bool)[7::]
e[i] = False
- self.assertFalse(np.all(e))
+ assert_(not np.all(e))
assert_array_equal(e, ~d)
# big array test for blocked libc loops
for i in list(range(9, 6000, 507)) + [7764, 90021, -10]:
d = np.array([False] * 100043, dtype=np.bool)
d[i] = True
- self.assertTrue(np.any(d), msg="%r" % i)
+ assert_(np.any(d), msg="%r" % i)
e = np.array([True] * 100043, dtype=np.bool)
e[i] = False
- self.assertFalse(np.all(e), msg="%r" % i)
+ assert_(not np.all(e), msg="%r" % i)
def test_logical_not_abs(self):
assert_array_equal(~self.t, self.f)
@@ -328,8 +328,8 @@
assert_array_equal(self.im ^ False, self.im)
-class TestBoolCmp(TestCase):
- def setUp(self):
+class TestBoolCmp(object):
+ def setup(self):
self.f = np.ones(256, dtype=np.float32)
self.ef = np.ones(self.f.size, dtype=np.bool)
self.d = np.ones(128, dtype=np.float64)
@@ -428,28 +428,28 @@
assert_array_equal(np.signbit(self.signd[i:]), self.ed[i:])
-class TestSeterr(TestCase):
+class TestSeterr(object):
def test_default(self):
err = np.geterr()
- self.assertEqual(err, dict(
- divide='warn',
- invalid='warn',
- over='warn',
- under='ignore',
- ))
+ assert_equal(err,
+ dict(divide='warn',
+ invalid='warn',
+ over='warn',
+ under='ignore')
+ )
def test_set(self):
with np.errstate():
err = np.seterr()
old = np.seterr(divide='print')
- self.assertTrue(err == old)
+ assert_(err == old)
new = np.seterr()
- self.assertTrue(new['divide'] == 'print')
+ assert_(new['divide'] == 'print')
np.seterr(over='raise')
- self.assertTrue(np.geterr()['over'] == 'raise')
- self.assertTrue(new['divide'] == 'print')
+ assert_(np.geterr()['over'] == 'raise')
+ assert_(new['divide'] == 'print')
np.seterr(**old)
- self.assertTrue(np.geterr() == old)
+ assert_(np.geterr() == old)
@dec.skipif(platform.machine() == "armv5tel", "See gh-413.")
def test_divide_err(self):
@@ -472,7 +472,7 @@
with np.errstate(divide='warn'):
np.seterrobj([20000, 1, None])
np.array([1.]) / np.array([0.])
- self.assertEqual(len(w), 1)
+ assert_equal(len(w), 1)
def log_err(*args):
self.called += 1
@@ -483,12 +483,12 @@
with np.errstate(divide='ignore'):
np.seterrobj([20000, 3, log_err])
np.array([1.]) / np.array([0.])
- self.assertEqual(self.called, 1)
+ assert_equal(self.called, 1)
np.seterrobj(olderrobj)
with np.errstate(divide='ignore'):
np.divide(1., 0., extobj=[20000, 3, log_err])
- self.assertEqual(self.called, 2)
+ assert_equal(self.called, 2)
finally:
np.seterrobj(olderrobj)
del self.called
@@ -512,7 +512,7 @@
np.seterrobj(olderrobj)
-class TestFloatExceptions(TestCase):
+class TestFloatExceptions(object):
def assert_raises_fpe(self, fpeerr, flop, x, y):
ftype = type(x)
try:
@@ -596,20 +596,20 @@
warnings.simplefilter("always")
with np.errstate(all="warn"):
np.divide(1, 0.)
- self.assertEqual(len(w), 1)
- self.assertTrue("divide by zero" in str(w[0].message))
+ assert_equal(len(w), 1)
+ assert_("divide by zero" in str(w[0].message))
np.array(1e300) * np.array(1e300)
- self.assertEqual(len(w), 2)
- self.assertTrue("overflow" in str(w[-1].message))
+ assert_equal(len(w), 2)
+ assert_("overflow" in str(w[-1].message))
np.array(np.inf) - np.array(np.inf)
- self.assertEqual(len(w), 3)
- self.assertTrue("invalid value" in str(w[-1].message))
+ assert_equal(len(w), 3)
+ assert_("invalid value" in str(w[-1].message))
np.array(1e-300) * np.array(1e-300)
- self.assertEqual(len(w), 4)
- self.assertTrue("underflow" in str(w[-1].message))
+ assert_equal(len(w), 4)
+ assert_("underflow" in str(w[-1].message))
-class TestTypes(TestCase):
+class TestTypes(object):
def check_promotion_cases(self, promote_func):
# tests that the scalars get coerced correctly.
b = np.bool_(0)
@@ -878,7 +878,7 @@
pass
-class TestFromiter(TestCase):
+class TestFromiter(object):
def makegen(self):
for x in range(24):
yield x**2
@@ -887,25 +887,25 @@
ai32 = np.fromiter(self.makegen(), np.int32)
ai64 = np.fromiter(self.makegen(), np.int64)
af = np.fromiter(self.makegen(), float)
- self.assertTrue(ai32.dtype == np.dtype(np.int32))
- self.assertTrue(ai64.dtype == np.dtype(np.int64))
- self.assertTrue(af.dtype == np.dtype(float))
+ assert_(ai32.dtype == np.dtype(np.int32))
+ assert_(ai64.dtype == np.dtype(np.int64))
+ assert_(af.dtype == np.dtype(float))
def test_lengths(self):
expected = np.array(list(self.makegen()))
a = np.fromiter(self.makegen(), int)
a20 = np.fromiter(self.makegen(), int, 20)
- self.assertTrue(len(a) == len(expected))
- self.assertTrue(len(a20) == 20)
- self.assertRaises(ValueError, np.fromiter,
+ assert_(len(a) == len(expected))
+ assert_(len(a20) == 20)
+ assert_raises(ValueError, np.fromiter,
self.makegen(), int, len(expected) + 10)
def test_values(self):
expected = np.array(list(self.makegen()))
a = np.fromiter(self.makegen(), int)
a20 = np.fromiter(self.makegen(), int, 20)
- self.assertTrue(np.alltrue(a == expected, axis=0))
- self.assertTrue(np.alltrue(a20 == expected[:20], axis=0))
+ assert_(np.alltrue(a == expected, axis=0))
+ assert_(np.alltrue(a20 == expected[:20], axis=0))
def load_data(self, n, eindex):
# Utility method for the issue 2592 tests.
@@ -918,18 +918,18 @@
def test_2592(self):
# Test iteration exceptions are correctly raised.
count, eindex = 10, 5
- self.assertRaises(NIterError, np.fromiter,
+ assert_raises(NIterError, np.fromiter,
self.load_data(count, eindex), dtype=int, count=count)
def test_2592_edge(self):
# Test iter. exceptions, edge case (exception at end of iterator).
count = 10
eindex = count-1
- self.assertRaises(NIterError, np.fromiter,
+ assert_raises(NIterError, np.fromiter,
self.load_data(count, eindex), dtype=int, count=count)
-class TestNonzero(TestCase):
+class TestNonzero(object):
def test_nonzero_trivial(self):
assert_equal(np.count_nonzero(np.array([])), 0)
assert_equal(np.count_nonzero(np.array([], dtype='?')), 0)
@@ -1114,7 +1114,7 @@
assert_equal(m.nonzero(), tgt)
-class TestIndex(TestCase):
+class TestIndex(object):
def test_boolean(self):
a = rand(3, 5, 8)
V = rand(5, 8)
@@ -1131,7 +1131,7 @@
assert_equal(c.dtype, np.dtype('int32'))
-class TestBinaryRepr(TestCase):
+class TestBinaryRepr(object):
def test_zero(self):
assert_equal(np.binary_repr(0), '0')
@@ -1168,7 +1168,7 @@
assert_equal(np.binary_repr(num, width=width), exp)
-class TestBaseRepr(TestCase):
+class TestBaseRepr(object):
def test_base3(self):
assert_equal(np.base_repr(3**5, 3), '100000')
@@ -1184,13 +1184,13 @@
assert_equal(np.base_repr(-12, 4), '-30')
def test_base_range(self):
- with self.assertRaises(ValueError):
+ with assert_raises(ValueError):
np.base_repr(1, 1)
- with self.assertRaises(ValueError):
+ with assert_raises(ValueError):
np.base_repr(1, 37)
-class TestArrayComparisons(TestCase):
+class TestArrayComparisons(object):
def test_array_equal(self):
res = np.array_equal(np.array([1, 2]), np.array([1, 2]))
assert_(res)
@@ -1270,8 +1270,8 @@
assert_(x.dtype.isnative == y.dtype.isnative)
-class TestClip(TestCase):
- def setUp(self):
+class TestClip(object):
+ def setup(self):
self.nr = 5
self.nc = 3
@@ -1697,7 +1697,7 @@
a2 = np.clip(a, m, M, out=a)
self.clip(a, m, M, ac)
assert_array_strict_equal(a2, ac)
- self.assertTrue(a2 is a)
+ assert_(a2 is a)
def test_clip_nan(self):
d = np.arange(7.)
@@ -1712,10 +1712,10 @@
rtol = 1e-5
atol = 1e-8
- def setUp(self):
+ def setup(self):
self.olderr = np.seterr(invalid='ignore')
- def tearDown(self):
+ def teardown(self):
np.seterr(**self.olderr)
def tst_allclose(self, x, y):
@@ -1931,8 +1931,8 @@
assert_(type(np.isclose(0, np.inf)) is bool)
-class TestStdVar(TestCase):
- def setUp(self):
+class TestStdVar(object):
+ def setup(self):
self.A = np.array([1, -1, 1, -1])
self.real_var = 1
@@ -1970,7 +1970,7 @@
assert_array_equal(r, out)
-class TestStdVarComplex(TestCase):
+class TestStdVarComplex(object):
def test_basic(self):
A = np.array([1, 1.j, -1, -1.j])
real_var = 1
@@ -1982,10 +1982,10 @@
assert_equal(np.std(1j), 0)
-class TestCreationFuncs(TestCase):
+class TestCreationFuncs(object):
# Test ones, zeros, empty and full.
- def setUp(self):
+ def setup(self):
dtypes = {np.dtype(tp) for tp in itertools.chain(*np.sctypes.values())}
# void, bytes, str
variable_sized = {tp for tp in dtypes if tp.str.endswith('0')}
@@ -2053,10 +2053,10 @@
assert_(sys.getrefcount(dim) == beg)
-class TestLikeFuncs(TestCase):
+class TestLikeFuncs(object):
'''Test ones_like, zeros_like, empty_like and full_like'''
- def setUp(self):
+ def setup(self):
self.data = [
# Array scalars
(np.array(3.), None),
@@ -2171,7 +2171,7 @@
self.check_like_function(np.full_like, np.inf, True)
-class TestCorrelate(TestCase):
+class TestCorrelate(object):
def _setup(self, dt):
self.x = np.array([1, 2, 3, 4, 5], dtype=dt)
self.xs = np.arange(1, 20)[::3]
@@ -2222,7 +2222,7 @@
assert_array_almost_equal(z, r_z)
-class TestConvolve(TestCase):
+class TestConvolve(object):
def test_object(self):
d = [1.] * 100
k = [1.] * 3
@@ -2264,7 +2264,7 @@
assert_equal(str(a), "[1]")
-class TestRoll(TestCase):
+class TestRoll(object):
def test_roll1d(self):
x = np.arange(10)
xr = np.roll(x, 2)
@@ -2322,7 +2322,7 @@
assert_equal(np.roll(x, 1), np.array([]))
-class TestRollaxis(TestCase):
+class TestRollaxis(object):
# expected shape indexed by (axis, start) for array of
# shape (1, 2, 3, 4)
@@ -2384,7 +2384,7 @@
assert_(not res.flags['OWNDATA'])
-class TestMoveaxis(TestCase):
+class TestMoveaxis(object):
def test_move_to_end(self):
x = np.random.randn(5, 6, 7)
for source, expected in [(0, (6, 7, 5)),
@@ -2458,7 +2458,7 @@
assert_(isinstance(result, np.ndarray))
-class TestCross(TestCase):
+class TestCross(object):
def test_2x2(self):
u = [1, 2]
v = [3, 4]
@@ -2621,7 +2621,7 @@
yield self.set_and_check_flag, flag, None, a
-class TestBroadcast(TestCase):
+class TestBroadcast(object):
def test_broadcast_in_args(self):
# gh-5881
arrs = [np.empty((6, 7)), np.empty((5, 6, 1)), np.empty((7,)),
@@ -2658,7 +2658,7 @@
assert_equal(mit.numiter, j)
-class TestKeepdims(TestCase):
+class TestKeepdims(object):
class sub_array(np.ndarray):
def sum(self, axis=None, dtype=None, out=None):
@@ -2670,7 +2670,7 @@
assert_raises(TypeError, np.sum, x, keepdims=True)
-class TestTensordot(TestCase):
+class TestTensordot(object):
def test_zero_dimension(self):
# Test resolution to issue #5663
diff --git a/numpy/core/tests/test_numerictypes.py b/numpy/core/tests/test_numerictypes.py
index 293031c..f912e39 100644
--- a/numpy/core/tests/test_numerictypes.py
+++ b/numpy/core/tests/test_numerictypes.py
@@ -4,7 +4,7 @@
import numpy as np
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_equal
+ run_module_suite, assert_, assert_equal, assert_raises
)
# This is the structure of the table used for plain objects:
@@ -102,99 +102,99 @@
# Creation tests
############################################################
-class create_zeros(object):
+class CreateZeros(object):
"""Check the creation of heterogeneous arrays zero-valued"""
def test_zeros0D(self):
"""Check creation of 0-dimensional objects"""
h = np.zeros((), dtype=self._descr)
- self.assertTrue(normalize_descr(self._descr) == h.dtype.descr)
- self.assertTrue(h.dtype.fields['x'][0].name[:4] == 'void')
- self.assertTrue(h.dtype.fields['x'][0].char == 'V')
- self.assertTrue(h.dtype.fields['x'][0].type == np.void)
+ assert_(normalize_descr(self._descr) == h.dtype.descr)
+ assert_(h.dtype.fields['x'][0].name[:4] == 'void')
+ assert_(h.dtype.fields['x'][0].char == 'V')
+ assert_(h.dtype.fields['x'][0].type == np.void)
# A small check that data is ok
assert_equal(h['z'], np.zeros((), dtype='u1'))
def test_zerosSD(self):
"""Check creation of single-dimensional objects"""
h = np.zeros((2,), dtype=self._descr)
- self.assertTrue(normalize_descr(self._descr) == h.dtype.descr)
- self.assertTrue(h.dtype['y'].name[:4] == 'void')
- self.assertTrue(h.dtype['y'].char == 'V')
- self.assertTrue(h.dtype['y'].type == np.void)
+ assert_(normalize_descr(self._descr) == h.dtype.descr)
+ assert_(h.dtype['y'].name[:4] == 'void')
+ assert_(h.dtype['y'].char == 'V')
+ assert_(h.dtype['y'].type == np.void)
# A small check that data is ok
assert_equal(h['z'], np.zeros((2,), dtype='u1'))
def test_zerosMD(self):
"""Check creation of multi-dimensional objects"""
h = np.zeros((2, 3), dtype=self._descr)
- self.assertTrue(normalize_descr(self._descr) == h.dtype.descr)
- self.assertTrue(h.dtype['z'].name == 'uint8')
- self.assertTrue(h.dtype['z'].char == 'B')
- self.assertTrue(h.dtype['z'].type == np.uint8)
+ assert_(normalize_descr(self._descr) == h.dtype.descr)
+ assert_(h.dtype['z'].name == 'uint8')
+ assert_(h.dtype['z'].char == 'B')
+ assert_(h.dtype['z'].type == np.uint8)
# A small check that data is ok
assert_equal(h['z'], np.zeros((2, 3), dtype='u1'))
-class test_create_zeros_plain(create_zeros, TestCase):
+class TestCreateZerosPlain(CreateZeros):
"""Check the creation of heterogeneous arrays zero-valued (plain)"""
_descr = Pdescr
-class test_create_zeros_nested(create_zeros, TestCase):
+class TestCreateZerosNested(CreateZeros):
"""Check the creation of heterogeneous arrays zero-valued (nested)"""
_descr = Ndescr
-class create_values(object):
+class CreateValues(object):
"""Check the creation of heterogeneous arrays with values"""
def test_tuple(self):
"""Check creation from tuples"""
h = np.array(self._buffer, dtype=self._descr)
- self.assertTrue(normalize_descr(self._descr) == h.dtype.descr)
+ assert_(normalize_descr(self._descr) == h.dtype.descr)
if self.multiple_rows:
- self.assertTrue(h.shape == (2,))
+ assert_(h.shape == (2,))
else:
- self.assertTrue(h.shape == ())
+ assert_(h.shape == ())
def test_list_of_tuple(self):
"""Check creation from list of tuples"""
h = np.array([self._buffer], dtype=self._descr)
- self.assertTrue(normalize_descr(self._descr) == h.dtype.descr)
+ assert_(normalize_descr(self._descr) == h.dtype.descr)
if self.multiple_rows:
- self.assertTrue(h.shape == (1, 2))
+ assert_(h.shape == (1, 2))
else:
- self.assertTrue(h.shape == (1,))
+ assert_(h.shape == (1,))
def test_list_of_list_of_tuple(self):
"""Check creation from list of list of tuples"""
h = np.array([[self._buffer]], dtype=self._descr)
- self.assertTrue(normalize_descr(self._descr) == h.dtype.descr)
+ assert_(normalize_descr(self._descr) == h.dtype.descr)
if self.multiple_rows:
- self.assertTrue(h.shape == (1, 1, 2))
+ assert_(h.shape == (1, 1, 2))
else:
- self.assertTrue(h.shape == (1, 1))
+ assert_(h.shape == (1, 1))
-class test_create_values_plain_single(create_values, TestCase):
+class TestCreateValuesPlainSingle(CreateValues):
"""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, TestCase):
+class TestCreateValuesPlainMultiple(CreateValues):
"""Check the creation of heterogeneous arrays (plain, multiple rows)"""
_descr = Pdescr
multiple_rows = 1
_buffer = PbufferT
-class test_create_values_nested_single(create_values, TestCase):
+class TestCreateValuesNestedSingle(CreateValues):
"""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, TestCase):
+class TestCreateValuesNestedMultiple(CreateValues):
"""Check the creation of heterogeneous arrays (nested, multiple rows)"""
_descr = Ndescr
multiple_rows = 1
@@ -205,18 +205,18 @@
# Reading tests
############################################################
-class read_values_plain(object):
+class ReadValuesPlain(object):
"""Check the reading of values in heterogeneous arrays (plain)"""
def test_access_fields(self):
h = np.array(self._buffer, dtype=self._descr)
if not self.multiple_rows:
- self.assertTrue(h.shape == ())
+ assert_(h.shape == ())
assert_equal(h['x'], np.array(self._buffer[0], dtype='i4'))
assert_equal(h['y'], np.array(self._buffer[1], dtype='f8'))
assert_equal(h['z'], np.array(self._buffer[2], dtype='u1'))
else:
- self.assertTrue(len(h) == 2)
+ assert_(len(h) == 2)
assert_equal(h['x'], np.array([self._buffer[0][0],
self._buffer[1][0]], dtype='i4'))
assert_equal(h['y'], np.array([self._buffer[0][1],
@@ -225,31 +225,31 @@
self._buffer[1][2]], dtype='u1'))
-class test_read_values_plain_single(read_values_plain, TestCase):
+class TestReadValuesPlainSingle(ReadValuesPlain):
"""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, TestCase):
+class TestReadValuesPlainMultiple(ReadValuesPlain):
"""Check the values of heterogeneous arrays (plain, multiple rows)"""
_descr = Pdescr
multiple_rows = 1
_buffer = PbufferT
-class read_values_nested(object):
+class ReadValuesNested(object):
"""Check the reading of values in heterogeneous arrays (nested)"""
def test_access_top_fields(self):
"""Check reading the top fields of a nested array"""
h = np.array(self._buffer, dtype=self._descr)
if not self.multiple_rows:
- self.assertTrue(h.shape == ())
+ assert_(h.shape == ())
assert_equal(h['x'], np.array(self._buffer[0], dtype='i4'))
assert_equal(h['y'], np.array(self._buffer[4], dtype='f8'))
assert_equal(h['z'], np.array(self._buffer[5], dtype='u1'))
else:
- self.assertTrue(len(h) == 2)
+ assert_(len(h) == 2)
assert_equal(h['x'], np.array([self._buffer[0][0],
self._buffer[1][0]], dtype='i4'))
assert_equal(h['y'], np.array([self._buffer[0][4],
@@ -308,41 +308,41 @@
def test_nested1_descriptor(self):
"""Check access nested descriptors of a nested array (1st level)"""
h = np.array(self._buffer, dtype=self._descr)
- self.assertTrue(h.dtype['Info']['value'].name == 'complex128')
- self.assertTrue(h.dtype['Info']['y2'].name == 'float64')
+ assert_(h.dtype['Info']['value'].name == 'complex128')
+ assert_(h.dtype['Info']['y2'].name == 'float64')
if sys.version_info[0] >= 3:
- self.assertTrue(h.dtype['info']['Name'].name == 'str256')
+ assert_(h.dtype['info']['Name'].name == 'str256')
else:
- self.assertTrue(h.dtype['info']['Name'].name == 'unicode256')
- self.assertTrue(h.dtype['info']['Value'].name == 'complex128')
+ assert_(h.dtype['info']['Name'].name == 'unicode256')
+ assert_(h.dtype['info']['Value'].name == 'complex128')
def test_nested2_descriptor(self):
"""Check access nested descriptors of a nested array (2nd level)"""
h = np.array(self._buffer, dtype=self._descr)
- self.assertTrue(h.dtype['Info']['Info2']['value'].name == 'void256')
- self.assertTrue(h.dtype['Info']['Info2']['z3'].name == 'void64')
+ assert_(h.dtype['Info']['Info2']['value'].name == 'void256')
+ assert_(h.dtype['Info']['Info2']['z3'].name == 'void64')
-class test_read_values_nested_single(read_values_nested, TestCase):
+class TestReadValuesNestedSingle(ReadValuesNested):
"""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, TestCase):
+class TestReadValuesNestedMultiple(ReadValuesNested):
"""Check the values of heterogeneous arrays (nested, multiple rows)"""
_descr = Ndescr
multiple_rows = True
_buffer = NbufferT
-class TestEmptyField(TestCase):
+class TestEmptyField(object):
def test_assign(self):
a = np.arange(10, dtype=np.float32)
a.dtype = [("int", "<0i4"), ("float", "<2f4")]
assert_(a['int'].shape == (5, 0))
assert_(a['float'].shape == (5, 2))
-class TestCommonType(TestCase):
+class TestCommonType(object):
def test_scalar_loses1(self):
res = np.find_common_type(['f4', 'f4', 'i2'], ['f8'])
assert_(res == 'f4')
@@ -363,15 +363,15 @@
res = np.find_common_type(['u8', 'i8', 'i8'], ['f8'])
assert_(res == 'f8')
-class TestMultipleFields(TestCase):
- def setUp(self):
+class TestMultipleFields(object):
+ def setup(self):
self.ary = np.array([(1, 2, 3, 4), (5, 6, 7, 8)], dtype='i4,f4,i2,c8')
def _bad_call(self):
return self.ary['f0', 'f1']
def test_no_tuple(self):
- self.assertRaises(IndexError, self._bad_call)
+ assert_raises(IndexError, self._bad_call)
def test_return(self):
res = self.ary[['f0', 'f2']].tolist()
diff --git a/numpy/core/tests/test_records.py b/numpy/core/tests/test_records.py
index 6f1ed37..f9f1432 100644
--- a/numpy/core/tests/test_records.py
+++ b/numpy/core/tests/test_records.py
@@ -8,12 +8,12 @@
import numpy as np
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_equal, assert_array_equal,
+ run_module_suite, assert_, assert_equal, assert_array_equal,
assert_array_almost_equal, assert_raises, assert_warns
)
-class TestFromrecords(TestCase):
+class TestFromrecords(object):
def test_fromrecords(self):
r = np.rec.fromrecords([[456, 'dbe', 1.2], [2, 'de', 1.3]],
names='col1,col2,col3')
@@ -298,8 +298,8 @@
assert_equal(rec['f1'], [b'', b'', b''])
-class TestRecord(TestCase):
- def setUp(self):
+class TestRecord(object):
+ def setup(self):
self.data = np.rec.fromrecords([(1, 2, 3), (4, 5, 6)],
dtype=[("col1", "<i4"),
("col2", "<i4"),
@@ -323,7 +323,7 @@
def assign_invalid_column(x):
x[0].col5 = 1
- self.assertRaises(AttributeError, assign_invalid_column, a)
+ assert_raises(AttributeError, assign_invalid_column, a)
def test_nonwriteable_setfield(self):
# gh-8171
diff --git a/numpy/core/tests/test_regression.py b/numpy/core/tests/test_regression.py
index c873852..a802e6a 100644
--- a/numpy/core/tests/test_regression.py
+++ b/numpy/core/tests/test_regression.py
@@ -13,7 +13,7 @@
import numpy as np
from numpy.testing import (
- run_module_suite, TestCase, assert_, assert_equal, IS_PYPY,
+ run_module_suite, assert_, assert_equal, IS_PYPY,
assert_almost_equal, assert_array_equal, assert_array_almost_equal,
assert_raises, assert_warns, dec, suppress_warnings,
_assert_valid_refcount, HAS_REFCOUNT,
@@ -22,7 +22,7 @@
rlevel = 1
-class TestRegression(TestCase):
+class TestRegression(object):
def test_invalid_round(self, level=rlevel):
# Ticket #3
v = 4.7599999999999998
@@ -104,7 +104,7 @@
def rs():
b.shape = (10,)
- self.assertRaises(AttributeError, rs)
+ assert_raises(AttributeError, rs)
def test_bool(self, level=rlevel):
# Ticket #60
@@ -134,14 +134,14 @@
# https://github.com/numpy/numpy/issues/565
a = np.array(['test', 'auto'])
assert_array_equal(a == 'auto', np.array([False, True]))
- self.assertTrue(a[1] == 'auto')
- self.assertTrue(a[0] != 'auto')
+ assert_(a[1] == 'auto')
+ assert_(a[0] != 'auto')
b = np.linspace(0, 10, 11)
# This should return true for now, but will eventually raise an error:
with suppress_warnings() as sup:
sup.filter(FutureWarning)
- self.assertTrue(b != 'auto')
- self.assertTrue(b[0] != 'auto')
+ assert_(b != 'auto')
+ assert_(b[0] != 'auto')
def test_unicode_swapping(self, level=rlevel):
# Ticket #79
@@ -157,7 +157,7 @@
def test_mem_dtype_align(self, level=rlevel):
# Ticket #93
- self.assertRaises(TypeError, np.dtype,
+ assert_raises(TypeError, np.dtype,
{'names':['a'], 'formats':['foo']}, align=1)
@dec.knownfailureif((sys.version_info[0] >= 3) or
@@ -169,8 +169,8 @@
# Ticket #99
i_width = np.int_(0).nbytes*2 - 1
np.intp('0x' + 'f'*i_width, 16)
- self.assertRaises(OverflowError, np.intp, '0x' + 'f'*(i_width+1), 16)
- self.assertRaises(ValueError, np.intp, '0x1', 32)
+ assert_raises(OverflowError, np.intp, '0x' + 'f'*(i_width+1), 16)
+ assert_raises(ValueError, np.intp, '0x1', 32)
assert_equal(255, np.intp('0xFF', 16))
assert_equal(1024, np.intp(1024))
@@ -250,7 +250,7 @@
# Ticket #128
x = np.arange(9).reshape((3, 3))
y = np.array([0, 0, 0])
- self.assertRaises(ValueError, np.hstack, (x, y))
+ assert_raises(ValueError, np.hstack, (x, y))
def test_squeeze_type(self, level=rlevel):
# Ticket #133
@@ -310,8 +310,8 @@
def bfb():
x[:] = np.arange(3, dtype=float)
- self.assertRaises(ValueError, bfa)
- self.assertRaises(ValueError, bfb)
+ assert_raises(ValueError, bfa)
+ assert_raises(ValueError, bfb)
def test_nonarray_assignment(self):
# See also Issue gh-2870, test for non-array assignment
@@ -342,7 +342,7 @@
# Ticket #196
dt = np.dtype([('x', int), ('y', np.object_)])
# Wrong way
- self.assertRaises(ValueError, np.array, [1, 'object'], dt)
+ assert_raises(ValueError, np.array, [1, 'object'], dt)
# Correct way
np.array([(1, 'object')], dt)
@@ -361,7 +361,7 @@
def index_tmp():
tmp[np.array(10)]
- self.assertRaises(IndexError, index_tmp)
+ assert_raises(IndexError, index_tmp)
def test_chararray_rstrip(self, level=rlevel):
# Ticket #222
@@ -457,7 +457,7 @@
def test_object_array_from_list(self, level=rlevel):
# Ticket #270
- self.assertEqual(np.array([1, 'A', None]).shape, (3,))
+ assert_(np.array([1, 'A', None]).shape == (3,))
def test_multiple_assign(self, level=rlevel):
# Ticket #273
@@ -581,7 +581,7 @@
def test_string_array_size(self, level=rlevel):
# Ticket #342
- self.assertRaises(ValueError,
+ assert_raises(ValueError,
np.array, [['X'], ['X', 'X', 'X']], '|S1')
def test_dtype_repr(self, level=rlevel):
@@ -675,8 +675,8 @@
def test_convolve_empty(self, level=rlevel):
# Convolve should raise an error for empty input array.
- self.assertRaises(ValueError, np.convolve, [], [1])
- self.assertRaises(ValueError, np.convolve, [1], [])
+ assert_raises(ValueError, np.convolve, [], [1])
+ assert_raises(ValueError, np.convolve, [1], [])
def test_multidim_byteswap(self, level=rlevel):
# Ticket #449
@@ -764,7 +764,7 @@
def test_mem_on_invalid_dtype(self):
"Ticket #583"
- self.assertRaises(ValueError, np.fromiter, [['12', ''], ['13', '']], str)
+ assert_raises(ValueError, np.fromiter, [['12', ''], ['13', '']], str)
def test_dot_negative_stride(self, level=rlevel):
# Ticket #588
@@ -783,7 +783,7 @@
y = np.zeros([484, 286])
x |= y
- self.assertRaises(TypeError, rs)
+ assert_raises(TypeError, rs)
def test_unicode_scalar(self, level=rlevel):
# Ticket #600
@@ -807,12 +807,12 @@
def ia(x, s, v):
x[(s > 0)] = v
- self.assertRaises(IndexError, ia, x, s, np.zeros(9, dtype=float))
- self.assertRaises(IndexError, ia, x, s, np.zeros(11, dtype=float))
+ assert_raises(IndexError, ia, x, s, np.zeros(9, dtype=float))
+ assert_raises(IndexError, ia, x, s, np.zeros(11, dtype=float))
# Old special case (different code path):
- self.assertRaises(ValueError, ia, x.flat, s, np.zeros(9, dtype=float))
- self.assertRaises(ValueError, ia, x.flat, s, np.zeros(11, dtype=float))
+ assert_raises(ValueError, ia, x.flat, s, np.zeros(9, dtype=float))
+ assert_raises(ValueError, ia, x.flat, s, np.zeros(11, dtype=float))
def test_mem_scalar_indexing(self, level=rlevel):
# Ticket #603
@@ -1011,7 +1011,7 @@
def test_mem_fromiter_invalid_dtype_string(self, level=rlevel):
x = [1, 2, 3]
- self.assertRaises(ValueError,
+ assert_raises(ValueError,
np.fromiter, [xi for xi in x], dtype='S')
def test_reduce_big_object_array(self, level=rlevel):
@@ -1224,16 +1224,16 @@
def test_array_resize_method_system_error(self):
# Ticket #840 - order should be an invalid keyword.
x = np.array([[0, 1], [2, 3]])
- self.assertRaises(TypeError, x.resize, (2, 2), order='C')
+ assert_raises(TypeError, x.resize, (2, 2), order='C')
def test_for_zero_length_in_choose(self, level=rlevel):
"Ticket #882"
a = np.array(1)
- self.assertRaises(ValueError, lambda x: x.choose([]), a)
+ assert_raises(ValueError, lambda x: x.choose([]), a)
def test_array_ndmin_overflow(self):
"Ticket #947."
- self.assertRaises(ValueError, lambda: np.array([1], ndmin=33))
+ assert_raises(ValueError, lambda: np.array([1], ndmin=33))
def test_void_scalar_with_titles(self, level=rlevel):
# No ticket
@@ -1308,7 +1308,7 @@
good = 'Maximum allowed size exceeded'
try:
np.arange(sz)
- self.assertTrue(np.size == sz)
+ assert_(np.size == sz)
except ValueError as e:
if not str(e) == good:
self.fail("Got msg '%s', expected '%s'" % (e, good))
@@ -1380,7 +1380,7 @@
a = np.array([[u'abc', u'\u03a3'],
[u'asdf', u'erw']],
dtype='U')
- self.assertRaises(UnicodeEncodeError, np.array, a, 'S4')
+ assert_raises(UnicodeEncodeError, np.array, a, 'S4')
def test_mixed_string_unicode_array_creation(self):
a = np.array(['1234', u'123'])
@@ -1462,7 +1462,7 @@
def test_duplicate_title_and_name(self):
# Ticket #1254
dtspec = [(('a', 'a'), 'i'), ('b', 'i')]
- self.assertRaises(ValueError, np.dtype, dtspec)
+ assert_raises(ValueError, np.dtype, dtspec)
def test_signed_integer_division_overflow(self):
# Ticket #1317.
@@ -2068,8 +2068,8 @@
assert_equal(arr, arr_cp)
assert_equal(arr.shape, arr_cp.shape)
assert_equal(int(arr), int(arr_cp))
- self.assertTrue(arr is not arr_cp)
- self.assertTrue(isinstance(arr_cp, type(arr)))
+ assert_(arr is not arr_cp)
+ assert_(isinstance(arr_cp, type(arr)))
def test_deepcopy_F_order_object_array(self):
# Ticket #6456.
@@ -2079,13 +2079,13 @@
arr_cp = copy.deepcopy(arr)
assert_equal(arr, arr_cp)
- self.assertTrue(arr is not arr_cp)
+ assert_(arr is not arr_cp)
# Ensure that we have actually copied the item.
- self.assertTrue(arr[0, 1] is not arr_cp[1, 1])
+ assert_(arr[0, 1] is not arr_cp[1, 1])
# Ensure we are allowed to have references to the same object.
- self.assertTrue(arr[0, 1] is arr[1, 1])
+ assert_(arr[0, 1] is arr[1, 1])
# Check the references hold for the copied objects.
- self.assertTrue(arr_cp[0, 1] is arr_cp[1, 1])
+ assert_(arr_cp[0, 1] is arr_cp[1, 1])
def test_deepcopy_empty_object_array(self):
# Ticket #8536.
diff --git a/numpy/core/tests/test_scalarinherit.py b/numpy/core/tests/test_scalarinherit.py
index e8cf7fd..8e0910d 100644
--- a/numpy/core/tests/test_scalarinherit.py
+++ b/numpy/core/tests/test_scalarinherit.py
@@ -5,7 +5,7 @@
from __future__ import division, absolute_import, print_function
import numpy as np
-from numpy.testing import TestCase, run_module_suite, assert_
+from numpy.testing import run_module_suite, assert_
class A(object):
@@ -23,7 +23,7 @@
class C0(B0):
pass
-class TestInherit(TestCase):
+class TestInherit(object):
def test_init(self):
x = B(1.0)
assert_(str(x) == '1.0')
diff --git a/numpy/core/tests/test_scalarmath.py b/numpy/core/tests/test_scalarmath.py
index 264efd8..d1cc9ee 100644
--- a/numpy/core/tests/test_scalarmath.py
+++ b/numpy/core/tests/test_scalarmath.py
@@ -7,7 +7,7 @@
import numpy as np
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_equal, assert_raises,
+ run_module_suite, assert_, assert_equal, assert_raises,
assert_almost_equal, assert_allclose, assert_array_equal, IS_PYPY,
suppress_warnings, dec, _gen_alignment_data,
)
@@ -22,7 +22,7 @@
# This compares scalarmath against ufuncs.
-class TestTypes(TestCase):
+class TestTypes(object):
def test_types(self, level=1):
for atype in types:
a = atype(1)
@@ -61,7 +61,7 @@
np.add(1, 1)
-class TestBaseMath(TestCase):
+class TestBaseMath(object):
def test_blocked(self):
# test alignments offsets for simd instructions
# alignments for vz + 2 * (vs - 1) + 1
@@ -107,7 +107,7 @@
np.add(d, np.ones_like(d))
-class TestPower(TestCase):
+class TestPower(object):
def test_small_types(self):
for t in [np.int8, np.int16, np.float16]:
a = t(3)
@@ -199,7 +199,7 @@
return (+1, -1)
-class TestModulus(TestCase):
+class TestModulus(object):
def test_modulus_basic(self):
dt = np.typecodes['AllInteger'] + np.typecodes['Float']
@@ -291,7 +291,7 @@
assert_(np.isnan(rem), 'dt: %s' % dt)
-class TestComplexDivision(TestCase):
+class TestComplexDivision(object):
def test_zero_division(self):
with np.errstate(all="ignore"):
for t in [np.complex64, np.complex128]:
@@ -363,7 +363,7 @@
assert_equal(result.imag, ex[1])
-class TestConversion(TestCase):
+class TestConversion(object):
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]
@@ -405,7 +405,7 @@
sup.record(np.ComplexWarning)
x = np.clongdouble(np.inf)
assert_raises(OverflowError, int, x)
- self.assertEqual(len(sup.log), 1)
+ assert_equal(len(sup.log), 1)
@dec.knownfailureif(not IS_PYPY)
def test_clongdouble___int__(self):
@@ -480,7 +480,7 @@
assert_(np.equal(np.datetime64('NaT'), None))
-#class TestRepr(TestCase):
+#class TestRepr(object):
# def test_repr(self):
# for t in types:
# val = t(1197346475.0137341)
@@ -524,7 +524,7 @@
if not IS_PYPY:
# sys.getsizeof() is not valid on PyPy
- class TestSizeOf(TestCase):
+ class TestSizeOf(object):
def test_equal_nbytes(self):
for type in types:
@@ -536,7 +536,7 @@
assert_raises(TypeError, d.__sizeof__, "a")
-class TestMultiply(TestCase):
+class TestMultiply(object):
def test_seq_repeat(self):
# Test that basic sequences get repeated when multiplied with
# numpy integers. And errors are raised when multiplied with others.
@@ -574,7 +574,7 @@
assert_array_equal(np.int_(3) * arr_like, np.full(3, 3))
-class TestNegative(TestCase):
+class TestNegative(object):
def test_exceptions(self):
a = np.ones((), dtype=np.bool_)[()]
assert_raises(TypeError, operator.neg, a)
@@ -588,7 +588,7 @@
assert_equal(operator.neg(a) + a, 0)
-class TestSubtract(TestCase):
+class TestSubtract(object):
def test_exceptions(self):
a = np.ones((), dtype=np.bool_)[()]
assert_raises(TypeError, operator.sub, a, a)
@@ -602,7 +602,7 @@
assert_equal(operator.sub(a, a), 0)
-class TestAbs(TestCase):
+class TestAbs(object):
def _test_abs_func(self, absfunc):
for tp in floating_types:
diff --git a/numpy/core/tests/test_scalarprint.py b/numpy/core/tests/test_scalarprint.py
index 8d0f271..7e17e04 100644
--- a/numpy/core/tests/test_scalarprint.py
+++ b/numpy/core/tests/test_scalarprint.py
@@ -5,10 +5,10 @@
from __future__ import division, absolute_import, print_function
import numpy as np
-from numpy.testing import TestCase, assert_, run_module_suite
+from numpy.testing import assert_, run_module_suite
-class TestRealScalars(TestCase):
+class TestRealScalars(object):
def test_str(self):
svals = [0.0, -0.0, 1, -1, np.inf, -np.inf, np.nan]
styps = [np.float16, np.float32, np.float64, np.longdouble]
diff --git a/numpy/core/tests/test_shape_base.py b/numpy/core/tests/test_shape_base.py
index c1680d1..9913af6 100644
--- a/numpy/core/tests/test_shape_base.py
+++ b/numpy/core/tests/test_shape_base.py
@@ -4,13 +4,13 @@
import numpy as np
from numpy.core import (array, arange, atleast_1d, atleast_2d, atleast_3d,
block, vstack, hstack, newaxis, concatenate, stack)
-from numpy.testing import (TestCase, assert_, assert_raises,
+from numpy.testing import (assert_, assert_raises,
assert_array_equal, assert_equal, run_module_suite,
assert_raises_regex, assert_almost_equal)
from numpy.compat import long
-class TestAtleast1d(TestCase):
+class TestAtleast1d(object):
def test_0D_array(self):
a = array(1)
b = array(2)
@@ -51,7 +51,7 @@
assert_(atleast_1d([[2, 3], [4, 5]]).shape == (2, 2))
-class TestAtleast2d(TestCase):
+class TestAtleast2d(object):
def test_0D_array(self):
a = array(1)
b = array(2)
@@ -90,7 +90,7 @@
assert_(atleast_2d([[[3, 1], [4, 5]], [[3, 5], [1, 2]]]).shape == (2, 2, 2))
-class TestAtleast3d(TestCase):
+class TestAtleast3d(object):
def test_0D_array(self):
a = array(1)
b = array(2)
@@ -122,7 +122,7 @@
assert_array_equal(res, desired)
-class TestHstack(TestCase):
+class TestHstack(object):
def test_non_iterable(self):
assert_raises(TypeError, hstack, 1)
@@ -151,7 +151,7 @@
assert_array_equal(res, desired)
-class TestVstack(TestCase):
+class TestVstack(object):
def test_non_iterable(self):
assert_raises(TypeError, vstack, 1)
@@ -187,7 +187,7 @@
assert_array_equal(res, desired)
-class TestConcatenate(TestCase):
+class TestConcatenate(object):
def test_exceptions(self):
# test axis must be in bounds
for ndim in [1, 2, 3]:
@@ -333,7 +333,7 @@
stack, [m, m])
-class TestBlock(TestCase):
+class TestBlock(object):
def test_block_simple_row_wise(self):
a_2d = np.ones((2, 2))
b_2d = 2 * a_2d
diff --git a/numpy/core/tests/test_ufunc.py b/numpy/core/tests/test_ufunc.py
index 7879f9c..fd33f12 100644
--- a/numpy/core/tests/test_ufunc.py
+++ b/numpy/core/tests/test_ufunc.py
@@ -5,14 +5,14 @@
import numpy.core.operand_flag_tests as opflag_tests
from numpy.core.test_rational import rational, test_add, test_add_rationals
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_equal, assert_raises,
+ run_module_suite, assert_, assert_equal, assert_raises,
assert_array_equal, assert_almost_equal, assert_array_almost_equal,
assert_no_warnings
)
import warnings
-class TestUfuncKwargs(TestCase):
+class TestUfuncKwargs(object):
def test_kwarg_exact(self):
assert_raises(TypeError, np.add, 1, 2, castingx='safe')
assert_raises(TypeError, np.add, 1, 2, dtypex=np.int)
@@ -34,7 +34,7 @@
dtype=np.int)
-class TestUfunc(TestCase):
+class TestUfunc(object):
def test_pickle(self):
import pickle
assert_(pickle.loads(pickle.dumps(np.sin)) is np.sin)
@@ -1189,7 +1189,7 @@
# Test exception thrown
values = np.array(['a', 1], dtype=np.object)
- self.assertRaises(TypeError, np.add.at, values, [0, 1], 1)
+ assert_raises(TypeError, np.add.at, values, [0, 1], 1)
assert_array_equal(values, np.array(['a', 1], dtype=np.object))
# Test multiple output ufuncs raise error, gh-5665
diff --git a/numpy/core/tests/test_umath.py b/numpy/core/tests/test_umath.py
index a7dbde9..714af5b 100644
--- a/numpy/core/tests/test_umath.py
+++ b/numpy/core/tests/test_umath.py
@@ -10,7 +10,7 @@
from numpy.core import umath_tests as ncu_tests
import numpy as np
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_equal, assert_raises,
+ run_module_suite, assert_, assert_equal, assert_raises,
assert_raises_regex, assert_array_equal, assert_almost_equal,
assert_array_almost_equal, dec, assert_allclose, assert_no_warnings,
suppress_warnings, _gen_alignment_data,
@@ -31,7 +31,7 @@
np.seterr(**self.olderr)
-class TestConstants(TestCase):
+class TestConstants(object):
def test_pi(self):
assert_allclose(ncu.pi, 3.141592653589793, 1e-15)
@@ -42,7 +42,7 @@
assert_allclose(ncu.euler_gamma, 0.5772156649015329, 1e-15)
-class TestOut(TestCase):
+class TestOut(object):
def test_out_subok(self):
for subok in (True, False):
a = np.array(0.5)
@@ -175,7 +175,7 @@
assert_(w[0].category is DeprecationWarning)
-class TestComparisons(TestCase):
+class TestComparisons(object):
def test_ignore_object_identity_in_equal(self):
# Check error raised when comparing identical objects whose comparison
# is not a simple boolean, e.g., arrays that are compared elementwise.
@@ -213,7 +213,7 @@
assert_equal(np.not_equal(a, a), [True])
-class TestDivision(TestCase):
+class TestDivision(object):
def test_division_int(self):
# int division should follow Python
x = np.array([5, 10, 90, 100, -5, -10, -90, -100, -120])
@@ -274,7 +274,7 @@
return (+1, -1)
-class TestRemainder(TestCase):
+class TestRemainder(object):
def test_remainder_basic(self):
dt = np.typecodes['AllInteger'] + np.typecodes['Float']
@@ -365,7 +365,7 @@
assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
-class TestCbrt(TestCase):
+class TestCbrt(object):
def test_cbrt_scalar(self):
assert_almost_equal((np.cbrt(np.float32(-2.5)**3)), -2.5)
@@ -378,7 +378,7 @@
assert_equal(np.cbrt(-np.inf), -np.inf)
-class TestPower(TestCase):
+class TestPower(object):
def test_power_float(self):
x = np.array([1., 2., 3.])
assert_equal(x**0, [1., 1., 1.])
@@ -517,7 +517,7 @@
assert_raises(ValueError, np.power, one, minusone)
-class TestFloat_power(TestCase):
+class TestFloat_power(object):
def test_type_conversion(self):
arg_type = '?bhilBHILefdgFDG'
res_type = 'ddddddddddddgDDG'
@@ -528,7 +528,7 @@
assert_(res.dtype.name == np.dtype(dtout).name, msg)
-class TestLog2(TestCase):
+class TestLog2(object):
def test_log2_values(self):
x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
@@ -559,7 +559,7 @@
assert_(w[2].category is RuntimeWarning)
-class TestExp2(TestCase):
+class TestExp2(object):
def test_exp2_values(self):
x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
@@ -611,7 +611,7 @@
assert_(np.isnan(np.logaddexp2(np.nan, np.nan)))
-class TestLog(TestCase):
+class TestLog(object):
def test_log_values(self):
x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
@@ -622,7 +622,7 @@
assert_almost_equal(np.log(xf), yf)
-class TestExp(TestCase):
+class TestExp(object):
def test_exp_values(self):
x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
@@ -674,7 +674,7 @@
assert_(np.isnan(np.logaddexp(np.nan, np.nan)))
-class TestLog1p(TestCase):
+class TestLog1p(object):
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))
@@ -688,7 +688,7 @@
assert_equal(ncu.log1p(-np.inf), np.nan)
-class TestExpm1(TestCase):
+class TestExpm1(object):
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)
@@ -701,7 +701,7 @@
assert_equal(ncu.expm1(-np.inf), -1.)
-class TestHypot(TestCase, object):
+class TestHypot(object):
def test_simple(self):
assert_almost_equal(ncu.hypot(1, 1), ncu.sqrt(2))
assert_almost_equal(ncu.hypot(0, 0), 0)
@@ -725,7 +725,7 @@
"hypot(%s, %s) is %s, not inf" % (x, y, ncu.hypot(x, y)))
-class TestHypotSpecialValues(TestCase):
+class TestHypotSpecialValues(object):
def test_nan_outputs(self):
assert_hypot_isnan(np.nan, np.nan)
assert_hypot_isnan(np.nan, 1)
@@ -762,7 +762,7 @@
assert_((ncu.arctan2(x, y) == 0 and np.signbit(ncu.arctan2(x, y))), "arctan(%s, %s) is %s, not -0" % (x, y, ncu.arctan2(x, y)))
-class TestArctan2SpecialValues(TestCase):
+class TestArctan2SpecialValues(object):
def test_one_one(self):
# atan2(1, 1) returns pi/4.
assert_almost_equal(ncu.arctan2(1, 1), 0.25 * np.pi)
@@ -831,7 +831,7 @@
assert_arctan2_isnan(np.nan, np.nan)
-class TestLdexp(TestCase):
+class TestLdexp(object):
def _check_ldexp(self, tp):
assert_almost_equal(ncu.ldexp(np.array(2., np.float32),
np.array(3, tp)), 16.)
@@ -1059,7 +1059,7 @@
assert_equal(np.fmin(arg1, arg2), out)
-class TestBool(TestCase):
+class TestBool(object):
def test_exceptions(self):
a = np.ones(1, dtype=np.bool_)
assert_raises(TypeError, np.negative, a)
@@ -1122,7 +1122,7 @@
assert_equal(np.logical_xor.reduce(arr), arr.sum() % 2 == 1)
-class TestBitwiseUFuncs(TestCase):
+class TestBitwiseUFuncs(object):
bitwise_types = [np.dtype(c) for c in '?' + 'bBhHiIlLqQ' + 'O']
@@ -1207,7 +1207,7 @@
assert_(type(f.reduce(btype)) is bool, msg)
-class TestInt(TestCase):
+class TestInt(object):
def test_logical_not(self):
x = np.ones(10, dtype=np.int16)
o = np.ones(10 * 2, dtype=np.bool)
@@ -1218,24 +1218,24 @@
assert_array_equal(o, tgt)
-class TestFloatingPoint(TestCase):
+class TestFloatingPoint(object):
def test_floating_point(self):
assert_equal(ncu.FLOATING_POINT_SUPPORT, 1)
-class TestDegrees(TestCase):
+class TestDegrees(object):
def test_degrees(self):
assert_almost_equal(ncu.degrees(np.pi), 180.0)
assert_almost_equal(ncu.degrees(-0.5*np.pi), -90.0)
-class TestRadians(TestCase):
+class TestRadians(object):
def test_radians(self):
assert_almost_equal(ncu.radians(180.0), np.pi)
assert_almost_equal(ncu.radians(-90.0), -0.5*np.pi)
-class TestHeavside(TestCase):
+class TestHeavside(object):
def test_heaviside(self):
x = np.array([[-30.0, -0.1, 0.0, 0.2], [7.5, np.nan, np.inf, -np.inf]])
expectedhalf = np.array([[0.0, 0.0, 0.5, 1.0], [1.0, np.nan, 1.0, 0.0]])
@@ -1257,7 +1257,7 @@
assert_equal(h, expected1.astype(np.float32))
-class TestSign(TestCase):
+class TestSign(object):
def test_sign(self):
a = np.array([np.inf, -np.inf, np.nan, 0.0, 3.0, -3.0])
out = np.zeros(a.shape)
@@ -1287,7 +1287,7 @@
assert_raises(TypeError, test_nan)
-class TestMinMax(TestCase):
+class TestMinMax(object):
def test_minmax_blocked(self):
# simd tests on max/min, test all alignments, slow but important
# for 2 * vz + 2 * (vs - 1) + 1 (unrolled once)
@@ -1317,7 +1317,7 @@
assert_equal(d.min(), d[0])
-class TestAbsoluteNegative(TestCase):
+class TestAbsoluteNegative(object):
def test_abs_neg_blocked(self):
# simd tests on abs, test all alignments for vz + 2 * (vs - 1) + 1
for dt, sz in [(np.float32, 11), (np.float64, 5)]:
@@ -1326,7 +1326,7 @@
tgt = [ncu.absolute(i) for i in inp]
np.absolute(inp, out=out)
assert_equal(out, tgt, err_msg=msg)
- self.assertTrue((out >= 0).all())
+ assert_((out >= 0).all())
tgt = [-1*(i) for i in inp]
np.negative(inp, out=out)
@@ -1359,7 +1359,7 @@
np.abs(np.ones_like(d), out=d)
-class TestPositive(TestCase):
+class TestPositive(object):
def test_valid(self):
valid_dtypes = [int, float, complex, object]
for dtype in valid_dtypes:
@@ -1378,7 +1378,7 @@
np.positive(np.array(['bar'], dtype=object))
-class TestSpecialMethods(TestCase):
+class TestSpecialMethods(object):
def test_wrap(self):
class with_wrap(object):
@@ -1395,11 +1395,11 @@
x = ncu.minimum(a, a)
assert_equal(x.arr, np.zeros(1))
func, args, i = x.context
- self.assertTrue(func is ncu.minimum)
- self.assertEqual(len(args), 2)
+ assert_(func is ncu.minimum)
+ assert_equal(len(args), 2)
assert_equal(args[0], a)
assert_equal(args[1], a)
- self.assertEqual(i, 0)
+ assert_equal(i, 0)
def test_wrap_with_iterable(self):
# test fix for bug #1026:
@@ -1415,7 +1415,7 @@
a = with_wrap()
x = ncu.multiply(a, (1, 2, 3))
- self.assertTrue(isinstance(x, with_wrap))
+ assert_(isinstance(x, with_wrap))
assert_array_equal(x, np.array((1, 2, 3)))
def test_priority_with_scalar(self):
@@ -1429,7 +1429,7 @@
a = A()
x = np.float64(1)*a
- self.assertTrue(isinstance(x, A))
+ assert_(isinstance(x, A))
assert_array_equal(x, np.array(1))
def test_old_wrap(self):
@@ -1470,25 +1470,25 @@
b = B()
c = C()
f = ncu.minimum
- self.assertTrue(type(f(x, x)) is np.ndarray)
- self.assertTrue(type(f(x, a)) is A)
- self.assertTrue(type(f(x, b)) is B)
- self.assertTrue(type(f(x, c)) is C)
- self.assertTrue(type(f(a, x)) is A)
- self.assertTrue(type(f(b, x)) is B)
- self.assertTrue(type(f(c, x)) is C)
+ assert_(type(f(x, x)) is np.ndarray)
+ assert_(type(f(x, a)) is A)
+ assert_(type(f(x, b)) is B)
+ assert_(type(f(x, c)) is C)
+ assert_(type(f(a, x)) is A)
+ assert_(type(f(b, x)) is B)
+ assert_(type(f(c, x)) is C)
- self.assertTrue(type(f(a, a)) is A)
- self.assertTrue(type(f(a, b)) is B)
- self.assertTrue(type(f(b, a)) is B)
- self.assertTrue(type(f(b, b)) is B)
- self.assertTrue(type(f(b, c)) is C)
- self.assertTrue(type(f(c, b)) is C)
- self.assertTrue(type(f(c, c)) is C)
+ assert_(type(f(a, a)) is A)
+ assert_(type(f(a, b)) is B)
+ assert_(type(f(b, a)) is B)
+ assert_(type(f(b, b)) is B)
+ assert_(type(f(b, c)) is C)
+ assert_(type(f(c, b)) is C)
+ assert_(type(f(c, c)) is C)
- self.assertTrue(type(ncu.exp(a) is A))
- self.assertTrue(type(ncu.exp(b) is B))
- self.assertTrue(type(ncu.exp(c) is C))
+ assert_(type(ncu.exp(a) is A))
+ assert_(type(ncu.exp(b) is B))
+ assert_(type(ncu.exp(c) is C))
def test_failing_wrap(self):
@@ -1500,7 +1500,7 @@
raise RuntimeError
a = A()
- self.assertRaises(RuntimeError, ncu.maximum, a, a)
+ assert_raises(RuntimeError, ncu.maximum, a, a)
def test_none_wrap(self):
# Tests that issue #8507 is resolved. Previously, this would segfault
@@ -1571,7 +1571,7 @@
raise RuntimeError
a = A()
- self.assertRaises(RuntimeError, ncu.maximum, a, a)
+ assert_raises(RuntimeError, ncu.maximum, a, a)
def test_array_with_context(self):
@@ -1593,10 +1593,10 @@
a = A()
ncu.maximum(np.zeros(1), a)
- self.assertTrue(a.func is ncu.maximum)
+ assert_(a.func is ncu.maximum)
assert_equal(a.args[0], 0)
- self.assertTrue(a.args[1] is a)
- self.assertTrue(a.i == 1)
+ assert_(a.args[1] is a)
+ assert_(a.i == 1)
assert_equal(ncu.maximum(a, B()), 0)
assert_equal(ncu.maximum(a, C()), 0)
@@ -2185,7 +2185,7 @@
assert_(a.info, {'inputs': [0, 2]})
-class TestChoose(TestCase):
+class TestChoose(object):
def test_mixed(self):
c = np.array([True, True])
a = np.array([True, True])
@@ -2386,12 +2386,12 @@
self.check_loss_of_precision(np.longcomplex)
-class TestAttributes(TestCase):
+class TestAttributes(object):
def test_attributes(self):
add = ncu.add
assert_equal(add.__name__, 'add')
- self.assertTrue(add.ntypes >= 18) # don't fail if types added
- self.assertTrue('ii->i' in add.types)
+ assert_(add.ntypes >= 18) # don't fail if types added
+ assert_('ii->i' in add.types)
assert_equal(add.nin, 2)
assert_equal(add.nout, 1)
assert_equal(add.identity, 0)
@@ -2405,7 +2405,7 @@
"frexp(x[, out1, out2], / [, out=(None, None)], *, where=True"))
-class TestSubclass(TestCase):
+class TestSubclass(object):
def test_subclass_op(self):
diff --git a/numpy/core/tests/test_umath_complex.py b/numpy/core/tests/test_umath_complex.py
index 536ad39..eac22b8 100644
--- a/numpy/core/tests/test_umath_complex.py
+++ b/numpy/core/tests/test_umath_complex.py
@@ -6,7 +6,7 @@
import numpy as np
import numpy.core.umath as ncu
from numpy.testing import (
- TestCase, run_module_suite, assert_equal, assert_array_equal,
+ run_module_suite, assert_raises, assert_equal, assert_array_equal,
assert_almost_equal, dec
)
@@ -129,7 +129,7 @@
yield check, f, np.nan, 0, np.nan, 0
-class TestClog(TestCase):
+class TestClog(object):
def test_simple(self):
x = np.array([1+0j, 1+2j])
y_r = np.log(np.abs(x)) + 1j * np.angle(x)
@@ -152,7 +152,7 @@
with np.errstate(divide='raise'):
x = np.array([np.NZERO], dtype=np.complex)
y = np.complex(-np.inf, np.pi)
- self.assertRaises(FloatingPointError, np.log, x)
+ assert_raises(FloatingPointError, np.log, x)
with np.errstate(divide='ignore'):
assert_almost_equal(np.log(x), y)
@@ -164,7 +164,7 @@
with np.errstate(divide='raise'):
x = np.array([0], dtype=np.complex)
y = np.complex(-np.inf, 0)
- self.assertRaises(FloatingPointError, np.log, x)
+ assert_raises(FloatingPointError, np.log, x)
with np.errstate(divide='ignore'):
assert_almost_equal(np.log(x), y)
@@ -188,7 +188,7 @@
with np.errstate(invalid='raise'):
x = np.array([complex(1., np.nan)], dtype=np.complex)
y = np.complex(np.nan, np.nan)
- #self.assertRaises(FloatingPointError, np.log, x)
+ #assert_raises(FloatingPointError, np.log, x)
with np.errstate(invalid='ignore'):
assert_almost_equal(np.log(x), y)
@@ -197,7 +197,7 @@
with np.errstate(invalid='raise'):
x = np.array([np.inf + 1j * np.nan], dtype=np.complex)
- #self.assertRaises(FloatingPointError, np.log, x)
+ #assert_raises(FloatingPointError, np.log, x)
with np.errstate(invalid='ignore'):
assert_almost_equal(np.log(x), y)
@@ -350,7 +350,7 @@
# XXX: check for conj(csqrt(z)) == csqrt(conj(z)) (need to fix branch
# cuts first)
-class TestCpow(TestCase):
+class TestCpow(object):
def setUp(self):
self.olderr = np.seterr(invalid='ignore')
diff --git a/numpy/core/tests/test_unicode.py b/numpy/core/tests/test_unicode.py
index ae2beb2..8c502ca 100644
--- a/numpy/core/tests/test_unicode.py
+++ b/numpy/core/tests/test_unicode.py
@@ -5,7 +5,7 @@
import numpy as np
from numpy.compat import unicode
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_equal, assert_array_equal)
+ run_module_suite, assert_, assert_equal, assert_array_equal)
# Guess the UCS length for this python interpreter
if sys.version_info[:2] >= (3, 3):
@@ -68,24 +68,24 @@
# Creation tests
############################################################
-class create_zeros(object):
+class CreateZeros(object):
"""Check the creation of zero-valued arrays"""
def content_check(self, ua, ua_scalar, nbytes):
# Check the length of the unicode base type
- self.assertTrue(int(ua.dtype.str[2:]) == self.ulen)
+ assert_(int(ua.dtype.str[2:]) == self.ulen)
# Check the length of the data buffer
- self.assertTrue(buffer_length(ua) == nbytes)
+ assert_(buffer_length(ua) == nbytes)
# Small check that data in array element is ok
- self.assertTrue(ua_scalar == u'')
+ assert_(ua_scalar == u'')
# Encode to ascii and double check
- self.assertTrue(ua_scalar.encode('ascii') == b'')
+ assert_(ua_scalar.encode('ascii') == b'')
# Check buffer lengths for scalars
if ucs4:
- self.assertTrue(buffer_length(ua_scalar) == 0)
+ assert_(buffer_length(ua_scalar) == 0)
else:
- self.assertTrue(buffer_length(ua_scalar) == 0)
+ assert_(buffer_length(ua_scalar) == 0)
def test_zeros0D(self):
# Check creation of 0-dimensional objects
@@ -105,47 +105,47 @@
self.content_check(ua, ua[-1, -1, -1], 4*self.ulen*2*3*4)
-class test_create_zeros_1(create_zeros, TestCase):
+class TestCreateZeros_1(CreateZeros):
"""Check the creation of zero-valued arrays (size 1)"""
ulen = 1
-class test_create_zeros_2(create_zeros, TestCase):
+class TestCreateZeros_2(CreateZeros):
"""Check the creation of zero-valued arrays (size 2)"""
ulen = 2
-class test_create_zeros_1009(create_zeros, TestCase):
+class TestCreateZeros_1009(CreateZeros):
"""Check the creation of zero-valued arrays (size 1009)"""
ulen = 1009
-class create_values(object):
+class CreateValues(object):
"""Check the creation of unicode arrays with values"""
def content_check(self, ua, ua_scalar, nbytes):
# Check the length of the unicode base type
- self.assertTrue(int(ua.dtype.str[2:]) == self.ulen)
+ assert_(int(ua.dtype.str[2:]) == self.ulen)
# Check the length of the data buffer
- self.assertTrue(buffer_length(ua) == nbytes)
+ assert_(buffer_length(ua) == nbytes)
# Small check that data in array element is ok
- self.assertTrue(ua_scalar == self.ucs_value*self.ulen)
+ assert_(ua_scalar == self.ucs_value*self.ulen)
# Encode to UTF-8 and double check
- self.assertTrue(ua_scalar.encode('utf-8') ==
+ assert_(ua_scalar.encode('utf-8') ==
(self.ucs_value*self.ulen).encode('utf-8'))
# Check buffer lengths for scalars
if ucs4:
- self.assertTrue(buffer_length(ua_scalar) == 4*self.ulen)
+ assert_(buffer_length(ua_scalar) == 4*self.ulen)
else:
if self.ucs_value == ucs4_value:
# In UCS2, the \U0010FFFF will be represented using a
# surrogate *pair*
- self.assertTrue(buffer_length(ua_scalar) == 2*2*self.ulen)
+ assert_(buffer_length(ua_scalar) == 2*2*self.ulen)
else:
# In UCS2, the \uFFFF will be represented using a
# regular 2-byte word
- self.assertTrue(buffer_length(ua_scalar) == 2*self.ulen)
+ assert_(buffer_length(ua_scalar) == 2*self.ulen)
def test_values0D(self):
# Check creation of 0-dimensional objects with values
@@ -165,37 +165,37 @@
self.content_check(ua, ua[-1, -1, -1], 4*self.ulen*2*3*4)
-class test_create_values_1_ucs2(create_values, TestCase):
+class TestCreateValues_1_UCS2(CreateValues):
"""Check the creation of valued arrays (size 1, UCS2 values)"""
ulen = 1
ucs_value = ucs2_value
-class test_create_values_1_ucs4(create_values, TestCase):
+class TestCreateValues_1_UCS4(CreateValues):
"""Check the creation of valued arrays (size 1, UCS4 values)"""
ulen = 1
ucs_value = ucs4_value
-class test_create_values_2_ucs2(create_values, TestCase):
+class TestCreateValues_2_UCS2(CreateValues):
"""Check the creation of valued arrays (size 2, UCS2 values)"""
ulen = 2
ucs_value = ucs2_value
-class test_create_values_2_ucs4(create_values, TestCase):
+class TestCreateValues_2_UCS4(CreateValues):
"""Check the creation of valued arrays (size 2, UCS4 values)"""
ulen = 2
ucs_value = ucs4_value
-class test_create_values_1009_ucs2(create_values, TestCase):
+class TestCreateValues_1009_UCS2(CreateValues):
"""Check the creation of valued arrays (size 1009, UCS2 values)"""
ulen = 1009
ucs_value = ucs2_value
-class test_create_values_1009_ucs4(create_values, TestCase):
+class TestCreateValues_1009_UCS4(CreateValues):
"""Check the creation of valued arrays (size 1009, UCS4 values)"""
ulen = 1009
ucs_value = ucs4_value
@@ -205,32 +205,32 @@
# Assignment tests
############################################################
-class assign_values(object):
+class AssignValues(object):
"""Check the assignment of unicode arrays with values"""
def content_check(self, ua, ua_scalar, nbytes):
# Check the length of the unicode base type
- self.assertTrue(int(ua.dtype.str[2:]) == self.ulen)
+ assert_(int(ua.dtype.str[2:]) == self.ulen)
# Check the length of the data buffer
- self.assertTrue(buffer_length(ua) == nbytes)
+ assert_(buffer_length(ua) == nbytes)
# Small check that data in array element is ok
- self.assertTrue(ua_scalar == self.ucs_value*self.ulen)
+ assert_(ua_scalar == self.ucs_value*self.ulen)
# Encode to UTF-8 and double check
- self.assertTrue(ua_scalar.encode('utf-8') ==
+ assert_(ua_scalar.encode('utf-8') ==
(self.ucs_value*self.ulen).encode('utf-8'))
# Check buffer lengths for scalars
if ucs4:
- self.assertTrue(buffer_length(ua_scalar) == 4*self.ulen)
+ assert_(buffer_length(ua_scalar) == 4*self.ulen)
else:
if self.ucs_value == ucs4_value:
# In UCS2, the \U0010FFFF will be represented using a
# surrogate *pair*
- self.assertTrue(buffer_length(ua_scalar) == 2*2*self.ulen)
+ assert_(buffer_length(ua_scalar) == 2*2*self.ulen)
else:
# In UCS2, the \uFFFF will be represented using a
# regular 2-byte word
- self.assertTrue(buffer_length(ua_scalar) == 2*self.ulen)
+ assert_(buffer_length(ua_scalar) == 2*self.ulen)
def test_values0D(self):
# Check assignment of 0-dimensional objects with values
@@ -255,37 +255,37 @@
self.content_check(ua, ua[-1, -1, -1], 4*self.ulen*2*3*4)
-class test_assign_values_1_ucs2(assign_values, TestCase):
+class TestAssignValues_1_UCS2(AssignValues):
"""Check the assignment of valued arrays (size 1, UCS2 values)"""
ulen = 1
ucs_value = ucs2_value
-class test_assign_values_1_ucs4(assign_values, TestCase):
+class TestAssignValues_1_UCS4(AssignValues):
"""Check the assignment of valued arrays (size 1, UCS4 values)"""
ulen = 1
ucs_value = ucs4_value
-class test_assign_values_2_ucs2(assign_values, TestCase):
+class TestAssignValues_2_UCS2(AssignValues):
"""Check the assignment of valued arrays (size 2, UCS2 values)"""
ulen = 2
ucs_value = ucs2_value
-class test_assign_values_2_ucs4(assign_values, TestCase):
+class TestAssignValues_2_UCS4(AssignValues):
"""Check the assignment of valued arrays (size 2, UCS4 values)"""
ulen = 2
ucs_value = ucs4_value
-class test_assign_values_1009_ucs2(assign_values, TestCase):
+class TestAssignValues_1009_UCS2(AssignValues):
"""Check the assignment of valued arrays (size 1009, UCS2 values)"""
ulen = 1009
ucs_value = ucs2_value
-class test_assign_values_1009_ucs4(assign_values, TestCase):
+class TestAssignValues_1009_UCS4(AssignValues):
"""Check the assignment of valued arrays (size 1009, UCS4 values)"""
ulen = 1009
ucs_value = ucs4_value
@@ -295,7 +295,7 @@
# Byteorder tests
############################################################
-class byteorder_values:
+class ByteorderValues(object):
"""Check the byteorder of unicode arrays in round-trip conversions"""
def test_values0D(self):
@@ -305,7 +305,7 @@
# This changes the interpretation of the data region (but not the
# actual data), therefore the returned scalars are not
# the same (they are byte-swapped versions of each other).
- self.assertTrue(ua[()] != ua2[()])
+ assert_(ua[()] != ua2[()])
ua3 = ua2.newbyteorder()
# Arrays must be equal after the round-trip
assert_equal(ua, ua3)
@@ -314,8 +314,8 @@
# Check byteorder of single-dimensional objects
ua = np.array([self.ucs_value*self.ulen]*2, dtype='U%s' % self.ulen)
ua2 = ua.newbyteorder()
- self.assertTrue((ua != ua2).all())
- self.assertTrue(ua[-1] != ua2[-1])
+ assert_((ua != ua2).all())
+ assert_(ua[-1] != ua2[-1])
ua3 = ua2.newbyteorder()
# Arrays must be equal after the round-trip
assert_equal(ua, ua3)
@@ -325,8 +325,8 @@
ua = np.array([[[self.ucs_value*self.ulen]*2]*3]*4,
dtype='U%s' % self.ulen)
ua2 = ua.newbyteorder()
- self.assertTrue((ua != ua2).all())
- self.assertTrue(ua[-1, -1, -1] != ua2[-1, -1, -1])
+ assert_((ua != ua2).all())
+ assert_(ua[-1, -1, -1] != ua2[-1, -1, -1])
ua3 = ua2.newbyteorder()
# Arrays must be equal after the round-trip
assert_equal(ua, ua3)
@@ -338,8 +338,8 @@
test2 = np.repeat(test1, 2)[::2]
for ua in (test1, test2):
ua2 = ua.astype(dtype=ua.dtype.newbyteorder())
- self.assertTrue((ua == ua2).all())
- self.assertTrue(ua[-1] == ua2[-1])
+ assert_((ua == ua2).all())
+ assert_(ua[-1] == ua2[-1])
ua3 = ua2.astype(dtype=ua.dtype)
# Arrays must be equal after the round-trip
assert_equal(ua, ua3)
@@ -353,45 +353,45 @@
# Cast to a longer type with zero padding
longer_type = np.dtype('U%s' % (self.ulen+1)).newbyteorder()
ua2 = ua.astype(dtype=longer_type)
- self.assertTrue((ua == ua2).all())
- self.assertTrue(ua[-1] == ua2[-1])
+ assert_((ua == ua2).all())
+ assert_(ua[-1] == ua2[-1])
# Cast back again with truncating:
ua3 = ua2.astype(dtype=ua.dtype)
# Arrays must be equal after the round-trip
assert_equal(ua, ua3)
-class test_byteorder_1_ucs2(byteorder_values, TestCase):
+class TestByteorder_1_UCS2(ByteorderValues):
"""Check the byteorder in unicode (size 1, UCS2 values)"""
ulen = 1
ucs_value = ucs2_value
-class test_byteorder_1_ucs4(byteorder_values, TestCase):
+class TestByteorder_1_UCS4(ByteorderValues):
"""Check the byteorder in unicode (size 1, UCS4 values)"""
ulen = 1
ucs_value = ucs4_value
-class test_byteorder_2_ucs2(byteorder_values, TestCase):
+class TestByteorder_2_UCS2(ByteorderValues):
"""Check the byteorder in unicode (size 2, UCS2 values)"""
ulen = 2
ucs_value = ucs2_value
-class test_byteorder_2_ucs4(byteorder_values, TestCase):
+class TestByteorder_2_UCS4(ByteorderValues):
"""Check the byteorder in unicode (size 2, UCS4 values)"""
ulen = 2
ucs_value = ucs4_value
-class test_byteorder_1009_ucs2(byteorder_values, TestCase):
+class TestByteorder_1009_UCS2(ByteorderValues):
"""Check the byteorder in unicode (size 1009, UCS2 values)"""
ulen = 1009
ucs_value = ucs2_value
-class test_byteorder_1009_ucs4(byteorder_values, TestCase):
+class TestByteorder_1009_UCS4(ByteorderValues):
"""Check the byteorder in unicode (size 1009, UCS4 values)"""
ulen = 1009
ucs_value = ucs4_value
diff --git a/numpy/distutils/tests/test_exec_command.py b/numpy/distutils/tests/test_exec_command.py
index d5a0c5a..5e7b3f3 100644
--- a/numpy/distutils/tests/test_exec_command.py
+++ b/numpy/distutils/tests/test_exec_command.py
@@ -6,7 +6,7 @@
from numpy.distutils import exec_command
from numpy.distutils.exec_command import get_pythonexe
-from numpy.testing import TestCase, run_module_suite, tempdir
+from numpy.testing import run_module_suite, tempdir, assert_
# In python 3 stdout, stderr are text (unicode compliant) devices, so to
# emulate them import StringIO from the io module.
@@ -94,94 +94,94 @@
exec_command.exec_command("cd '.'")
-class TestExecCommand(TestCase):
- def setUp(self):
+class TestExecCommand(object):
+ def setup(self):
self.pyexe = get_pythonexe()
def check_nt(self, **kws):
s, o = exec_command.exec_command('cmd /C echo path=%path%')
- self.assertEqual(s, 0)
- self.assertNotEqual(o, '')
+ assert_(s == 0)
+ assert_(o != '')
s, o = exec_command.exec_command(
'"%s" -c "import sys;sys.stderr.write(sys.platform)"' % self.pyexe)
- self.assertEqual(s, 0)
- self.assertEqual(o, 'win32')
+ assert_(s == 0)
+ assert_(o == 'win32')
def check_posix(self, **kws):
s, o = exec_command.exec_command("echo Hello", **kws)
- self.assertEqual(s, 0)
- self.assertEqual(o, 'Hello')
+ assert_(s == 0)
+ assert_(o == 'Hello')
s, o = exec_command.exec_command('echo $AAA', **kws)
- self.assertEqual(s, 0)
- self.assertEqual(o, '')
+ assert_(s == 0)
+ assert_(o == '')
s, o = exec_command.exec_command('echo "$AAA"', AAA='Tere', **kws)
- self.assertEqual(s, 0)
- self.assertEqual(o, 'Tere')
+ assert_(s == 0)
+ assert_(o == 'Tere')
s, o = exec_command.exec_command('echo "$AAA"', **kws)
- self.assertEqual(s, 0)
- self.assertEqual(o, '')
+ assert_(s == 0)
+ assert_(o == '')
if 'BBB' not in os.environ:
os.environ['BBB'] = 'Hi'
s, o = exec_command.exec_command('echo "$BBB"', **kws)
- self.assertEqual(s, 0)
- self.assertEqual(o, 'Hi')
+ assert_(s == 0)
+ assert_(o == 'Hi')
s, o = exec_command.exec_command('echo "$BBB"', BBB='Hey', **kws)
- self.assertEqual(s, 0)
- self.assertEqual(o, 'Hey')
+ assert_(s == 0)
+ assert_(o == 'Hey')
s, o = exec_command.exec_command('echo "$BBB"', **kws)
- self.assertEqual(s, 0)
- self.assertEqual(o, 'Hi')
+ assert_(s == 0)
+ assert_(o == 'Hi')
del os.environ['BBB']
s, o = exec_command.exec_command('echo "$BBB"', **kws)
- self.assertEqual(s, 0)
- self.assertEqual(o, '')
+ assert_(s == 0)
+ assert_(o == '')
s, o = exec_command.exec_command('this_is_not_a_command', **kws)
- self.assertNotEqual(s, 0)
- self.assertNotEqual(o, '')
+ assert_(s != 0)
+ assert_(o != '')
s, o = exec_command.exec_command('echo path=$PATH', **kws)
- self.assertEqual(s, 0)
- self.assertNotEqual(o, '')
+ assert_(s == 0)
+ assert_(o != '')
s, o = exec_command.exec_command(
'"%s" -c "import sys,os;sys.stderr.write(os.name)"' %
self.pyexe, **kws)
- self.assertEqual(s, 0)
- self.assertEqual(o, 'posix')
+ assert_(s == 0)
+ assert_(o == 'posix')
def check_basic(self, *kws):
s, o = exec_command.exec_command(
'"%s" -c "raise \'Ignore me.\'"' % self.pyexe, **kws)
- self.assertNotEqual(s, 0)
- self.assertNotEqual(o, '')
+ assert_(s != 0)
+ assert_(o != '')
s, o = exec_command.exec_command(
'"%s" -c "import sys;sys.stderr.write(\'0\');'
'sys.stderr.write(\'1\');sys.stderr.write(\'2\')"' %
self.pyexe, **kws)
- self.assertEqual(s, 0)
- self.assertEqual(o, '012')
+ assert_(s == 0)
+ assert_(o == '012')
s, o = exec_command.exec_command(
'"%s" -c "import sys;sys.exit(15)"' % self.pyexe, **kws)
- self.assertEqual(s, 15)
- self.assertEqual(o, '')
+ assert_(s == 15)
+ assert_(o == '')
s, o = exec_command.exec_command(
'"%s" -c "print(\'Heipa\'")' % self.pyexe, **kws)
- self.assertEqual(s, 0)
- self.assertEqual(o, 'Heipa')
+ assert_(s == 0)
+ assert_(o == 'Heipa')
def check_execute_in(self, **kws):
with tempdir() as tmpdir:
@@ -194,13 +194,13 @@
s, o = exec_command.exec_command(
'"%s" -c "f = open(\'%s\', \'r\'); f.close()"' %
(self.pyexe, fn), **kws)
- self.assertNotEqual(s, 0)
- self.assertNotEqual(o, '')
+ assert_(s != 0)
+ assert_(o != '')
s, o = exec_command.exec_command(
'"%s" -c "f = open(\'%s\', \'r\'); print(f.read()); '
'f.close()"' % (self.pyexe, fn), execute_in=tmpdir, **kws)
- self.assertEqual(s, 0)
- self.assertEqual(o, 'Hello')
+ assert_(s == 0)
+ assert_(o == 'Hello')
def test_basic(self):
with redirect_stdout(StringIO()):
diff --git a/numpy/distutils/tests/test_fcompiler_gnu.py b/numpy/distutils/tests/test_fcompiler_gnu.py
index 7ca99db..9ad63cf 100644
--- a/numpy/distutils/tests/test_fcompiler_gnu.py
+++ b/numpy/distutils/tests/test_fcompiler_gnu.py
@@ -1,6 +1,6 @@
from __future__ import division, absolute_import, print_function
-from numpy.testing import TestCase, assert_, run_module_suite
+from numpy.testing import assert_, run_module_suite
import numpy.distutils.fcompiler
@@ -29,7 +29,7 @@
'4.9.1')
]
-class TestG77Versions(TestCase):
+class TestG77Versions(object):
def test_g77_version(self):
fc = numpy.distutils.fcompiler.new_fcompiler(compiler='gnu')
for vs, version in g77_version_strings:
@@ -42,7 +42,7 @@
v = fc.version_match(vs)
assert_(v is None, (vs, v))
-class TestGFortranVersions(TestCase):
+class TestGFortranVersions(object):
def test_gfortran_version(self):
fc = numpy.distutils.fcompiler.new_fcompiler(compiler='gnu95')
for vs, version in gfortran_version_strings:
diff --git a/numpy/distutils/tests/test_fcompiler_intel.py b/numpy/distutils/tests/test_fcompiler_intel.py
index 8e371b9..b13a017 100644
--- a/numpy/distutils/tests/test_fcompiler_intel.py
+++ b/numpy/distutils/tests/test_fcompiler_intel.py
@@ -1,7 +1,7 @@
from __future__ import division, absolute_import, print_function
import numpy.distutils.fcompiler
-from numpy.testing import TestCase, run_module_suite, assert_
+from numpy.testing import run_module_suite, assert_
intel_32bit_version_strings = [
@@ -16,7 +16,7 @@
"running on Intel(R) 64, Version 11.1", '11.1')
]
-class TestIntelFCompilerVersions(TestCase):
+class TestIntelFCompilerVersions(object):
def test_32bit_version(self):
fc = numpy.distutils.fcompiler.new_fcompiler(compiler='intel')
for vs, version in intel_32bit_version_strings:
@@ -24,7 +24,7 @@
assert_(v == version)
-class TestIntelEM64TFCompilerVersions(TestCase):
+class TestIntelEM64TFCompilerVersions(object):
def test_64bit_version(self):
fc = numpy.distutils.fcompiler.new_fcompiler(compiler='intelem')
for vs, version in intel_64bit_version_strings:
diff --git a/numpy/distutils/tests/test_misc_util.py b/numpy/distutils/tests/test_misc_util.py
index f7fcbe2..dd4dbc8 100644
--- a/numpy/distutils/tests/test_misc_util.py
+++ b/numpy/distutils/tests/test_misc_util.py
@@ -6,12 +6,12 @@
appendpath, minrelpath, gpaths, get_shared_lib_extension, get_info
)
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_equal
+ run_module_suite, assert_, assert_equal
)
ajoin = lambda *paths: join(*((sep,)+paths))
-class TestAppendpath(TestCase):
+class TestAppendpath(object):
def test_1(self):
assert_equal(appendpath('prefix', 'name'), join('prefix', 'name'))
@@ -35,7 +35,7 @@
assert_equal(appendpath('/prefix/sub/sub2', '/prefix/sub/sup/name'),
ajoin('prefix', 'sub', 'sub2', 'sup', 'name'))
-class TestMinrelpath(TestCase):
+class TestMinrelpath(object):
def test_1(self):
n = lambda path: path.replace('/', sep)
@@ -49,7 +49,7 @@
assert_equal(minrelpath(n('.././..')), n('../..'))
assert_equal(minrelpath(n('aa/bb/.././../dd')), n('dd'))
-class TestGpaths(TestCase):
+class TestGpaths(object):
def test_gpaths(self):
local_path = minrelpath(join(dirname(__file__), '..'))
@@ -58,7 +58,7 @@
f = gpaths('system_info.py', local_path)
assert_(join(local_path, 'system_info.py') == f[0], repr(f))
-class TestSharedExtension(TestCase):
+class TestSharedExtension(object):
def test_get_shared_lib_extension(self):
import sys
diff --git a/numpy/distutils/tests/test_npy_pkg_config.py b/numpy/distutils/tests/test_npy_pkg_config.py
index bdef471..29891b6 100644
--- a/numpy/distutils/tests/test_npy_pkg_config.py
+++ b/numpy/distutils/tests/test_npy_pkg_config.py
@@ -3,7 +3,7 @@
import os
from numpy.distutils.npy_pkg_config import read_config, parse_flags
-from numpy.testing import TestCase, run_module_suite, temppath
+from numpy.testing import run_module_suite, temppath, assert_
simple = """\
[meta]
@@ -36,7 +36,7 @@
simple_variable_d = {'cflags': '-I/foo/bar/include', 'libflags': '-L/foo/bar/lib',
'version': '0.1', 'name': 'foo'}
-class TestLibraryInfo(TestCase):
+class TestLibraryInfo(object):
def test_simple(self):
with temppath('foo.ini') as path:
with open(path, 'w') as f:
@@ -44,10 +44,10 @@
pkg = os.path.splitext(path)[0]
out = read_config(pkg)
- self.assertTrue(out.cflags() == simple_d['cflags'])
- self.assertTrue(out.libs() == simple_d['libflags'])
- self.assertTrue(out.name == simple_d['name'])
- self.assertTrue(out.version == simple_d['version'])
+ assert_(out.cflags() == simple_d['cflags'])
+ assert_(out.libs() == simple_d['libflags'])
+ assert_(out.name == simple_d['name'])
+ assert_(out.version == simple_d['version'])
def test_simple_variable(self):
with temppath('foo.ini') as path:
@@ -56,34 +56,34 @@
pkg = os.path.splitext(path)[0]
out = read_config(pkg)
- self.assertTrue(out.cflags() == simple_variable_d['cflags'])
- self.assertTrue(out.libs() == simple_variable_d['libflags'])
- self.assertTrue(out.name == simple_variable_d['name'])
- self.assertTrue(out.version == simple_variable_d['version'])
+ assert_(out.cflags() == simple_variable_d['cflags'])
+ assert_(out.libs() == simple_variable_d['libflags'])
+ assert_(out.name == simple_variable_d['name'])
+ assert_(out.version == simple_variable_d['version'])
out.vars['prefix'] = '/Users/david'
- self.assertTrue(out.cflags() == '-I/Users/david/include')
+ assert_(out.cflags() == '-I/Users/david/include')
-class TestParseFlags(TestCase):
+class TestParseFlags(object):
def test_simple_cflags(self):
d = parse_flags("-I/usr/include")
- self.assertTrue(d['include_dirs'] == ['/usr/include'])
+ assert_(d['include_dirs'] == ['/usr/include'])
d = parse_flags("-I/usr/include -DFOO")
- self.assertTrue(d['include_dirs'] == ['/usr/include'])
- self.assertTrue(d['macros'] == ['FOO'])
+ assert_(d['include_dirs'] == ['/usr/include'])
+ assert_(d['macros'] == ['FOO'])
d = parse_flags("-I /usr/include -DFOO")
- self.assertTrue(d['include_dirs'] == ['/usr/include'])
- self.assertTrue(d['macros'] == ['FOO'])
+ assert_(d['include_dirs'] == ['/usr/include'])
+ assert_(d['macros'] == ['FOO'])
def test_simple_lflags(self):
d = parse_flags("-L/usr/lib -lfoo -L/usr/lib -lbar")
- self.assertTrue(d['library_dirs'] == ['/usr/lib', '/usr/lib'])
- self.assertTrue(d['libraries'] == ['foo', 'bar'])
+ assert_(d['library_dirs'] == ['/usr/lib', '/usr/lib'])
+ assert_(d['libraries'] == ['foo', 'bar'])
d = parse_flags("-L /usr/lib -lfoo -L/usr/lib -lbar")
- self.assertTrue(d['library_dirs'] == ['/usr/lib', '/usr/lib'])
- self.assertTrue(d['libraries'] == ['foo', 'bar'])
+ assert_(d['library_dirs'] == ['/usr/lib', '/usr/lib'])
+ assert_(d['libraries'] == ['foo', 'bar'])
if __name__ == '__main__':
diff --git a/numpy/distutils/tests/test_system_info.py b/numpy/distutils/tests/test_system_info.py
index 59b4cc1..026179d 100644
--- a/numpy/distutils/tests/test_system_info.py
+++ b/numpy/distutils/tests/test_system_info.py
@@ -8,7 +8,7 @@
from numpy.distutils import ccompiler
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_equal, dec
+ run_module_suite, assert_, assert_equal, dec
)
from numpy.distutils.system_info import system_info, ConfigParser
from numpy.distutils.system_info import default_lib_dirs, default_include_dirs
@@ -21,9 +21,9 @@
1 - display warning message
2 - raise error
"""
- cl = {'temp1': TestTemp1,
- 'temp2': TestTemp2
- }.get(name.lower(), test_system_info)
+ cl = {'temp1': Temp1Info,
+ 'temp2': Temp2Info
+ }.get(name.lower(), _system_info)
return cl()
simple_site = """
@@ -84,7 +84,7 @@
HAVE_COMPILER = have_compiler()
-class test_system_info(system_info):
+class _system_info(system_info):
def __init__(self,
default_lib_dirs=default_lib_dirs,
@@ -111,17 +111,19 @@
return info
-class TestTemp1(test_system_info):
+class Temp1Info(_system_info):
+ """For testing purposes"""
section = 'temp1'
-class TestTemp2(test_system_info):
+class Temp2Info(_system_info):
+ """For testing purposes"""
section = 'temp2'
-class TestSystemInfoReading(TestCase):
+class TestSystemInfoReading(object):
- def setUp(self):
+ def setup(self):
""" Create the libraries """
# Create 2 sources and 2 libraries
self._dir1 = mkdtemp()
diff --git a/numpy/f2py/tests/test_array_from_pyobj.py b/numpy/f2py/tests/test_array_from_pyobj.py
index 48bb7c0..1f6b594 100644
--- a/numpy/f2py/tests/test_array_from_pyobj.py
+++ b/numpy/f2py/tests/test_array_from_pyobj.py
@@ -17,7 +17,7 @@
wrap = None
-def setup():
+def setup_module():
"""
Build the required testing extension module
@@ -294,7 +294,7 @@
return obj_attr[0] == self.arr_attr[0]
-class test_intent(unittest.TestCase):
+class TestIntent(object):
def test_in_out(self):
assert_equal(str(intent.in_.out), 'intent(in,out)')
@@ -305,7 +305,7 @@
assert_(not intent.in_.is_intent('c'))
-class _test_shared_memory:
+class _test_shared_memory(object):
num2seq = [1, 2]
num23seq = [[1, 2, 3], [4, 5, 6]]
@@ -578,14 +578,12 @@
for t in _type_names:
exec('''\
-class test_%s_gen(unittest.TestCase,
- _test_shared_memory
- ):
- def setUp(self):
+class TestGen_%s(_test_shared_memory):
+ def setup(self):
self.type = Type(%r)
array = lambda self,dims,intent,obj: Array(Type(%r),dims,intent,obj)
''' % (t, t, t))
if __name__ == "__main__":
- setup()
+ setup_module()
run_module_suite()
diff --git a/numpy/f2py/tests/util.py b/numpy/f2py/tests/util.py
index fe608d8..55716a2 100644
--- a/numpy/f2py/tests/util.py
+++ b/numpy/f2py/tests/util.py
@@ -319,7 +319,7 @@
module = None
module_name = None
- def setUp(self):
+ def setup(self):
if self.module is not None:
return
diff --git a/numpy/fft/tests/test_fftpack.py b/numpy/fft/tests/test_fftpack.py
index a2cbc0f..7ac0488 100644
--- a/numpy/fft/tests/test_fftpack.py
+++ b/numpy/fft/tests/test_fftpack.py
@@ -2,8 +2,10 @@
import numpy as np
from numpy.random import random
-from numpy.testing import TestCase, run_module_suite, assert_array_almost_equal
-from numpy.testing import assert_array_equal
+from numpy.testing import (
+ run_module_suite, assert_array_almost_equal, assert_array_equal,
+ assert_raises,
+ )
import threading
import sys
if sys.version_info[0] >= 3:
@@ -19,13 +21,13 @@
return np.sum(x*np.exp(phase), axis=1)
-class TestFFTShift(TestCase):
+class TestFFTShift(object):
def test_fft_n(self):
- self.assertRaises(ValueError, np.fft.fft, [1, 2, 3], 0)
+ assert_raises(ValueError, np.fft.fft, [1, 2, 3], 0)
-class TestFFT1D(TestCase):
+class TestFFT1D(object):
def test_fft(self):
x = random(30) + 1j*random(30)
@@ -145,7 +147,7 @@
assert_array_almost_equal(x_norm,
np.linalg.norm(tmp))
-class TestFFTThreadSafe(TestCase):
+class TestFFTThreadSafe(object):
threads = 16
input_shape = (800, 200)
diff --git a/numpy/fft/tests/test_helper.py b/numpy/fft/tests/test_helper.py
index ff56ff6..f02edf7 100644
--- a/numpy/fft/tests/test_helper.py
+++ b/numpy/fft/tests/test_helper.py
@@ -6,13 +6,15 @@
from __future__ import division, absolute_import, print_function
import numpy as np
-from numpy.testing import TestCase, run_module_suite, assert_array_almost_equal
+from numpy.testing import (
+ run_module_suite, assert_array_almost_equal, assert_equal,
+ )
from numpy import fft
from numpy import pi
from numpy.fft.helper import _FFTCache
-class TestFFTShift(TestCase):
+class TestFFTShift(object):
def test_definition(self):
x = [0, 1, 2, 3, 4, -4, -3, -2, -1]
@@ -40,7 +42,7 @@
fft.ifftshift(shifted, axes=(0,)))
-class TestFFTFreq(TestCase):
+class TestFFTFreq(object):
def test_definition(self):
x = [0, 1, 2, 3, 4, -4, -3, -2, -1]
@@ -51,7 +53,7 @@
assert_array_almost_equal(10*pi*fft.fftfreq(10, pi), x)
-class TestRFFTFreq(TestCase):
+class TestRFFTFreq(object):
def test_definition(self):
x = [0, 1, 2, 3, 4]
@@ -62,7 +64,7 @@
assert_array_almost_equal(10*pi*fft.rfftfreq(10, pi), x)
-class TestIRFFTN(TestCase):
+class TestIRFFTN(object):
def test_not_last_axis_success(self):
ar, ai = np.random.random((2, 16, 8, 32))
@@ -74,7 +76,7 @@
fft.irfftn(a, axes=axes)
-class TestFFTCache(TestCase):
+class TestFFTCache(object):
def test_basic_behaviour(self):
c = _FFTCache(max_size_in_mb=1, max_item_count=4)
@@ -90,7 +92,7 @@
np.zeros(2, dtype=np.float32))
# Nothing should be left.
- self.assertEqual(len(c._dict), 0)
+ assert_equal(len(c._dict), 0)
# Now put everything in twice so it can be retrieved once and each will
# still have one item left.
@@ -101,7 +103,7 @@
np.ones(2, dtype=np.float32))
assert_array_almost_equal(c.pop_twiddle_factors(2),
np.zeros(2, dtype=np.float32))
- self.assertEqual(len(c._dict), 2)
+ assert_equal(len(c._dict), 2)
def test_automatic_pruning(self):
# That's around 2600 single precision samples.
@@ -109,27 +111,27 @@
c.put_twiddle_factors(1, np.ones(200, dtype=np.float32))
c.put_twiddle_factors(2, np.ones(200, dtype=np.float32))
- self.assertEqual(list(c._dict.keys()), [1, 2])
+ assert_equal(list(c._dict.keys()), [1, 2])
# This is larger than the limit but should still be kept.
c.put_twiddle_factors(3, np.ones(3000, dtype=np.float32))
- self.assertEqual(list(c._dict.keys()), [1, 2, 3])
+ assert_equal(list(c._dict.keys()), [1, 2, 3])
# Add one more.
c.put_twiddle_factors(4, np.ones(3000, dtype=np.float32))
# The other three should no longer exist.
- self.assertEqual(list(c._dict.keys()), [4])
+ assert_equal(list(c._dict.keys()), [4])
# Now test the max item count pruning.
c = _FFTCache(max_size_in_mb=0.01, max_item_count=2)
c.put_twiddle_factors(2, np.empty(2))
c.put_twiddle_factors(1, np.empty(2))
# Can still be accessed.
- self.assertEqual(list(c._dict.keys()), [2, 1])
+ assert_equal(list(c._dict.keys()), [2, 1])
c.put_twiddle_factors(3, np.empty(2))
# 1 and 3 can still be accessed - c[2] has been touched least recently
# and is thus evicted.
- self.assertEqual(list(c._dict.keys()), [1, 3])
+ assert_equal(list(c._dict.keys()), [1, 3])
# One last test. We will add a single large item that is slightly
# bigger then the cache size. Some small items can still be added.
@@ -138,18 +140,18 @@
c.put_twiddle_factors(2, np.ones(2, dtype=np.float32))
c.put_twiddle_factors(3, np.ones(2, dtype=np.float32))
c.put_twiddle_factors(4, np.ones(2, dtype=np.float32))
- self.assertEqual(list(c._dict.keys()), [1, 2, 3, 4])
+ assert_equal(list(c._dict.keys()), [1, 2, 3, 4])
# One more big item. This time it is 6 smaller ones but they are
# counted as one big item.
for _ in range(6):
c.put_twiddle_factors(5, np.ones(500, dtype=np.float32))
# '1' no longer in the cache. Rest still in the cache.
- self.assertEqual(list(c._dict.keys()), [2, 3, 4, 5])
+ assert_equal(list(c._dict.keys()), [2, 3, 4, 5])
# Another big item - should now be the only item in the cache.
c.put_twiddle_factors(6, np.ones(4000, dtype=np.float32))
- self.assertEqual(list(c._dict.keys()), [6])
+ assert_equal(list(c._dict.keys()), [6])
if __name__ == "__main__":
diff --git a/numpy/lib/tests/test__datasource.py b/numpy/lib/tests/test__datasource.py
index f2ad034..a9cb157 100644
--- a/numpy/lib/tests/test__datasource.py
+++ b/numpy/lib/tests/test__datasource.py
@@ -6,7 +6,7 @@
from shutil import rmtree
from numpy.testing import (
- run_module_suite, TestCase, assert_, SkipTest
+ run_module_suite, assert_, assert_equal, assert_raises, SkipTest,
)
import numpy.lib._datasource as datasource
@@ -55,7 +55,7 @@
magic_line = b'three is the magic number'
-# Utility functions used by many TestCases
+# Utility functions used by many tests
def valid_textfile(filedir):
# Generate and return a valid temporary file.
fd, path = mkstemp(suffix='.txt', prefix='dstmp_', dir=filedir, text=True)
@@ -95,12 +95,12 @@
return http_fakefile
-class TestDataSourceOpen(TestCase):
- def setUp(self):
+class TestDataSourceOpen(object):
+ def setup(self):
self.tmpdir = mkdtemp()
self.ds = datasource.DataSource(self.tmpdir)
- def tearDown(self):
+ def teardown(self):
rmtree(self.tmpdir)
del self.ds
@@ -111,7 +111,7 @@
def test_InvalidHTTP(self):
url = invalid_httpurl()
- self.assertRaises(IOError, self.ds.open, url)
+ assert_raises(IOError, self.ds.open, url)
try:
self.ds.open(url)
except IOError as e:
@@ -119,7 +119,7 @@
assert_(e.errno is None)
def test_InvalidHTTPCacheURLError(self):
- self.assertRaises(URLError, self.ds._cache, invalid_httpurl())
+ assert_raises(URLError, self.ds._cache, invalid_httpurl())
def test_ValidFile(self):
local_file = valid_textfile(self.tmpdir)
@@ -129,7 +129,7 @@
def test_InvalidFile(self):
invalid_file = invalid_textfile(self.tmpdir)
- self.assertRaises(IOError, self.ds.open, invalid_file)
+ assert_raises(IOError, self.ds.open, invalid_file)
def test_ValidGzipFile(self):
try:
@@ -145,7 +145,7 @@
fp = self.ds.open(filepath)
result = fp.readline()
fp.close()
- self.assertEqual(magic_line, result)
+ assert_equal(magic_line, result)
def test_ValidBz2File(self):
try:
@@ -161,15 +161,15 @@
fp = self.ds.open(filepath)
result = fp.readline()
fp.close()
- self.assertEqual(magic_line, result)
+ assert_equal(magic_line, result)
-class TestDataSourceExists(TestCase):
- def setUp(self):
+class TestDataSourceExists(object):
+ def setup(self):
self.tmpdir = mkdtemp()
self.ds = datasource.DataSource(self.tmpdir)
- def tearDown(self):
+ def teardown(self):
rmtree(self.tmpdir)
del self.ds
@@ -177,7 +177,7 @@
assert_(self.ds.exists(valid_httpurl()))
def test_InvalidHTTP(self):
- self.assertEqual(self.ds.exists(invalid_httpurl()), False)
+ assert_equal(self.ds.exists(invalid_httpurl()), False)
def test_ValidFile(self):
# Test valid file in destpath
@@ -191,15 +191,15 @@
def test_InvalidFile(self):
tmpfile = invalid_textfile(self.tmpdir)
- self.assertEqual(self.ds.exists(tmpfile), False)
+ assert_equal(self.ds.exists(tmpfile), False)
-class TestDataSourceAbspath(TestCase):
- def setUp(self):
+class TestDataSourceAbspath(object):
+ def setup(self):
self.tmpdir = os.path.abspath(mkdtemp())
self.ds = datasource.DataSource(self.tmpdir)
- def tearDown(self):
+ def teardown(self):
rmtree(self.tmpdir)
del self.ds
@@ -207,30 +207,30 @@
scheme, netloc, upath, pms, qry, frg = urlparse(valid_httpurl())
local_path = os.path.join(self.tmpdir, netloc,
upath.strip(os.sep).strip('/'))
- self.assertEqual(local_path, self.ds.abspath(valid_httpurl()))
+ assert_equal(local_path, self.ds.abspath(valid_httpurl()))
def test_ValidFile(self):
tmpfile = valid_textfile(self.tmpdir)
tmpfilename = os.path.split(tmpfile)[-1]
# Test with filename only
- self.assertEqual(tmpfile, self.ds.abspath(tmpfilename))
+ assert_equal(tmpfile, self.ds.abspath(tmpfilename))
# Test filename with complete path
- self.assertEqual(tmpfile, self.ds.abspath(tmpfile))
+ assert_equal(tmpfile, self.ds.abspath(tmpfile))
def test_InvalidHTTP(self):
scheme, netloc, upath, pms, qry, frg = urlparse(invalid_httpurl())
invalidhttp = os.path.join(self.tmpdir, netloc,
upath.strip(os.sep).strip('/'))
- self.assertNotEqual(invalidhttp, self.ds.abspath(valid_httpurl()))
+ assert_(invalidhttp != self.ds.abspath(valid_httpurl()))
def test_InvalidFile(self):
invalidfile = valid_textfile(self.tmpdir)
tmpfile = valid_textfile(self.tmpdir)
tmpfilename = os.path.split(tmpfile)[-1]
# Test with filename only
- self.assertNotEqual(invalidfile, self.ds.abspath(tmpfilename))
+ assert_(invalidfile != self.ds.abspath(tmpfilename))
# Test filename with complete path
- self.assertNotEqual(invalidfile, self.ds.abspath(tmpfile))
+ assert_(invalidfile != self.ds.abspath(tmpfile))
def test_sandboxing(self):
tmpfile = valid_textfile(self.tmpdir)
@@ -259,12 +259,12 @@
os.sep = orig_os_sep
-class TestRepositoryAbspath(TestCase):
- def setUp(self):
+class TestRepositoryAbspath(object):
+ def setup(self):
self.tmpdir = os.path.abspath(mkdtemp())
self.repos = datasource.Repository(valid_baseurl(), self.tmpdir)
- def tearDown(self):
+ def teardown(self):
rmtree(self.tmpdir)
del self.repos
@@ -273,7 +273,7 @@
local_path = os.path.join(self.repos._destpath, netloc,
upath.strip(os.sep).strip('/'))
filepath = self.repos.abspath(valid_httpfile())
- self.assertEqual(local_path, filepath)
+ assert_equal(local_path, filepath)
def test_sandboxing(self):
tmp_path = lambda x: os.path.abspath(self.repos.abspath(x))
@@ -292,12 +292,12 @@
os.sep = orig_os_sep
-class TestRepositoryExists(TestCase):
- def setUp(self):
+class TestRepositoryExists(object):
+ def setup(self):
self.tmpdir = mkdtemp()
self.repos = datasource.Repository(valid_baseurl(), self.tmpdir)
- def tearDown(self):
+ def teardown(self):
rmtree(self.tmpdir)
del self.repos
@@ -308,7 +308,7 @@
def test_InvalidFile(self):
tmpfile = invalid_textfile(self.tmpdir)
- self.assertEqual(self.repos.exists(tmpfile), False)
+ assert_equal(self.repos.exists(tmpfile), False)
def test_RemoveHTTPFile(self):
assert_(self.repos.exists(valid_httpurl()))
@@ -325,11 +325,11 @@
assert_(self.repos.exists(tmpfile))
-class TestOpenFunc(TestCase):
- def setUp(self):
+class TestOpenFunc(object):
+ def setup(self):
self.tmpdir = mkdtemp()
- def tearDown(self):
+ def teardown(self):
rmtree(self.tmpdir)
def test_DataSourceOpen(self):
diff --git a/numpy/lib/tests/test__iotools.py b/numpy/lib/tests/test__iotools.py
index 6c0b2c6..a7ee9cb 100644
--- a/numpy/lib/tests/test__iotools.py
+++ b/numpy/lib/tests/test__iotools.py
@@ -6,8 +6,7 @@
import numpy as np
from numpy.testing import (
- run_module_suite, TestCase, assert_, assert_equal, assert_allclose,
- assert_raises
+ run_module_suite, assert_, assert_equal, assert_allclose, assert_raises,
)
from numpy.lib._iotools import (
LineSplitter, NameValidator, StringConverter,
@@ -15,7 +14,7 @@
)
-class TestLineSplitter(TestCase):
+class TestLineSplitter(object):
"Tests the LineSplitter class."
def test_no_delimiter(self):
@@ -79,7 +78,7 @@
# -----------------------------------------------------------------------------
-class TestNameValidator(TestCase):
+class TestNameValidator(object):
def test_case_sensitivity(self):
"Test case sensitivity"
@@ -140,7 +139,7 @@
return date(*time.strptime(s, "%Y-%m-%d")[:3])
-class TestStringConverter(TestCase):
+class TestStringConverter(object):
"Test StringConverter"
def test_creation(self):
@@ -254,7 +253,7 @@
assert_(converter(val) == 9223372043271415339)
-class TestMiscFunctions(TestCase):
+class TestMiscFunctions(object):
def test_has_nested_dtype(self):
"Test has_nested_dtype"
diff --git a/numpy/lib/tests/test_arraypad.py b/numpy/lib/tests/test_arraypad.py
index 056aa45..55cd24a 100644
--- a/numpy/lib/tests/test_arraypad.py
+++ b/numpy/lib/tests/test_arraypad.py
@@ -4,12 +4,11 @@
from __future__ import division, absolute_import, print_function
import numpy as np
-from numpy.testing import (assert_array_equal, assert_raises, assert_allclose,
- TestCase)
+from numpy.testing import (assert_array_equal, assert_raises, assert_allclose,)
from numpy.lib import pad
-class TestConditionalShortcuts(TestCase):
+class TestConditionalShortcuts(object):
def test_zero_padding_shortcuts(self):
test = np.arange(120).reshape(4, 5, 6)
pad_amt = [(0, 0) for axis in test.shape]
@@ -52,7 +51,7 @@
pad(test, pad_amt, mode=mode, stat_length=30))
-class TestStatistic(TestCase):
+class TestStatistic(object):
def test_check_mean_stat_length(self):
a = np.arange(100).astype('f')
a = pad(a, ((25, 20), ), 'mean', stat_length=((2, 3), ))
@@ -346,7 +345,7 @@
assert_array_equal(a, b)
-class TestConstant(TestCase):
+class TestConstant(object):
def test_check_constant(self):
a = np.arange(100)
a = pad(a, (25, 20), 'constant', constant_values=(10, 20))
@@ -491,7 +490,7 @@
assert_allclose(test, expected)
-class TestLinearRamp(TestCase):
+class TestLinearRamp(object):
def test_check_simple(self):
a = np.arange(100).astype('f')
a = pad(a, (25, 20), 'linear_ramp', end_values=(4, 5))
@@ -531,7 +530,7 @@
assert_allclose(test, expected)
-class TestReflect(TestCase):
+class TestReflect(object):
def test_check_simple(self):
a = np.arange(100)
a = pad(a, (25, 20), 'reflect')
@@ -641,7 +640,7 @@
assert_array_equal(a, b)
-class TestSymmetric(TestCase):
+class TestSymmetric(object):
def test_check_simple(self):
a = np.arange(100)
a = pad(a, (25, 20), 'symmetric')
@@ -775,7 +774,7 @@
assert_array_equal(a, b)
-class TestWrap(TestCase):
+class TestWrap(object):
def test_check_simple(self):
a = np.arange(100)
a = pad(a, (25, 20), 'wrap')
@@ -871,7 +870,7 @@
assert_array_equal(a, b)
-class TestStatLen(TestCase):
+class TestStatLen(object):
def test_check_simple(self):
a = np.arange(30)
a = np.reshape(a, (6, 5))
@@ -894,7 +893,7 @@
assert_array_equal(a, b)
-class TestEdge(TestCase):
+class TestEdge(object):
def test_check_simple(self):
a = np.arange(12)
a = np.reshape(a, (4, 3))
@@ -933,7 +932,7 @@
assert_array_equal(padded, expected)
-class TestZeroPadWidth(TestCase):
+class TestZeroPadWidth(object):
def test_zero_pad_width(self):
arr = np.arange(30)
arr = np.reshape(arr, (6, 5))
@@ -941,7 +940,7 @@
assert_array_equal(arr, pad(arr, pad_width, mode='constant'))
-class TestLegacyVectorFunction(TestCase):
+class TestLegacyVectorFunction(object):
def test_legacy_vector_functionality(self):
def _padwithtens(vector, pad_width, iaxis, kwargs):
vector[:pad_width[0]] = 10
@@ -963,7 +962,7 @@
assert_array_equal(a, b)
-class TestNdarrayPadWidth(TestCase):
+class TestNdarrayPadWidth(object):
def test_check_simple(self):
a = np.arange(12)
a = np.reshape(a, (4, 3))
@@ -984,7 +983,7 @@
assert_array_equal(a, b)
-class TestUnicodeInput(TestCase):
+class TestUnicodeInput(object):
def test_unicode_mode(self):
constant_mode = u'constant'
a = np.pad([1], 2, mode=constant_mode)
@@ -992,7 +991,7 @@
assert_array_equal(a, b)
-class ValueError1(TestCase):
+class TestValueError1(object):
def test_check_simple(self):
arr = np.arange(30)
arr = np.reshape(arr, (6, 5))
@@ -1015,7 +1014,7 @@
**kwargs)
-class ValueError2(TestCase):
+class TestValueError2(object):
def test_check_negative_pad_amount(self):
arr = np.arange(30)
arr = np.reshape(arr, (6, 5))
@@ -1024,7 +1023,7 @@
**kwargs)
-class ValueError3(TestCase):
+class TestValueError3(object):
def test_check_kwarg_not_allowed(self):
arr = np.arange(30).reshape(5, 6)
assert_raises(ValueError, pad, arr, 4, mode='mean',
@@ -1052,7 +1051,7 @@
mode='constant')
-class TypeError1(TestCase):
+class TestTypeError1(object):
def test_float(self):
arr = np.arange(30)
assert_raises(TypeError, pad, arr, ((-2.1, 3), (3, 2)))
diff --git a/numpy/lib/tests/test_arraysetops.py b/numpy/lib/tests/test_arraysetops.py
index d47534f..b8ced41 100644
--- a/numpy/lib/tests/test_arraysetops.py
+++ b/numpy/lib/tests/test_arraysetops.py
@@ -5,14 +5,14 @@
import numpy as np
from numpy.testing import (
- run_module_suite, TestCase, assert_array_equal, assert_equal, assert_raises
+ run_module_suite, assert_array_equal, assert_equal, assert_raises,
)
from numpy.lib.arraysetops import (
ediff1d, intersect1d, setxor1d, union1d, setdiff1d, unique, in1d, isin
)
-class TestSetOps(TestCase):
+class TestSetOps(object):
def test_intersect1d(self):
# unique inputs
@@ -89,28 +89,28 @@
x = isin(a, b)
y = isin_slow(a, b)
assert_array_equal(x, y)
-
+
#multidimensional arrays in both arguments
a = np.arange(24).reshape([2, 3, 4])
b = np.array([[10, 20, 30], [0, 1, 3], [11, 22, 33]])
assert_isin_equal(a, b)
-
+
#array-likes as both arguments
c = [(9, 8), (7, 6)]
d = (9, 7)
assert_isin_equal(c, d)
-
+
#zero-d array:
f = np.array(3)
assert_isin_equal(f, b)
assert_isin_equal(a, f)
assert_isin_equal(f, f)
-
+
#scalar:
assert_isin_equal(5, b)
assert_isin_equal(a, 6)
assert_isin_equal(5, 6)
-
+
#empty array-like:
x = []
assert_isin_equal(x, b)
@@ -252,7 +252,7 @@
assert_array_equal(c1, c2)
-class TestUnique(TestCase):
+class TestUnique(object):
def test_unique_1d(self):
diff --git a/numpy/lib/tests/test_financial.py b/numpy/lib/tests/test_financial.py
index cc8ba55..4db364a 100644
--- a/numpy/lib/tests/test_financial.py
+++ b/numpy/lib/tests/test_financial.py
@@ -2,12 +2,12 @@
import numpy as np
from numpy.testing import (
- run_module_suite, TestCase, assert_, assert_almost_equal,
- assert_allclose, assert_equal
+ run_module_suite, assert_, assert_almost_equal, assert_allclose,
+ assert_equal
)
-class TestFinancial(TestCase):
+class TestFinancial(object):
def test_rate(self):
assert_almost_equal(np.rate(10, 0, -3500, 10000),
0.1107, 4)
diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py
index 2f76647..099a2d4 100644
--- a/numpy/lib/tests/test_function_base.py
+++ b/numpy/lib/tests/test_function_base.py
@@ -7,10 +7,10 @@
import numpy as np
from numpy.testing import (
- run_module_suite, TestCase, assert_, assert_equal, assert_array_equal,
+ run_module_suite, assert_, assert_equal, assert_array_equal,
assert_almost_equal, assert_array_almost_equal, assert_raises,
- assert_allclose, assert_array_max_ulp, assert_warns,
- assert_raises_regex, dec, suppress_warnings, HAS_REFCOUNT,
+ assert_allclose, assert_array_max_ulp, assert_warns, assert_raises_regex,
+ dec, suppress_warnings, HAS_REFCOUNT,
)
import numpy.lib.function_base as nfb
from numpy.random import rand
@@ -31,9 +31,9 @@
return data
-class TestRot90(TestCase):
+class TestRot90(object):
def test_basic(self):
- self.assertRaises(ValueError, rot90, np.ones(4))
+ assert_raises(ValueError, rot90, np.ones(4))
assert_raises(ValueError, rot90, np.ones((2,2,2)), axes=(0,1,2))
assert_raises(ValueError, rot90, np.ones((2,2)), axes=(0,2))
assert_raises(ValueError, rot90, np.ones((2,2)), axes=(1,1))
@@ -99,12 +99,12 @@
rot90(a_rot90_20, k=k-1, axes=(2, 0)))
-class TestFlip(TestCase):
+class TestFlip(object):
def test_axes(self):
- self.assertRaises(ValueError, np.flip, np.ones(4), axis=1)
- self.assertRaises(ValueError, np.flip, np.ones((4, 4)), axis=2)
- self.assertRaises(ValueError, np.flip, np.ones((4, 4)), axis=-3)
+ assert_raises(ValueError, np.flip, np.ones(4), axis=1)
+ assert_raises(ValueError, np.flip, np.ones((4, 4)), axis=2)
+ assert_raises(ValueError, np.flip, np.ones((4, 4)), axis=-3)
def test_basic_lr(self):
a = get_mat(4)
@@ -172,7 +172,7 @@
np.flipud(a.swapaxes(0, i)).swapaxes(i, 0))
-class TestAny(TestCase):
+class TestAny(object):
def test_basic(self):
y1 = [0, 0, 1, 0]
@@ -189,7 +189,7 @@
assert_array_equal(np.sometrue(y1, axis=1), [0, 1, 1])
-class TestAll(TestCase):
+class TestAll(object):
def test_basic(self):
y1 = [0, 1, 1, 0]
@@ -207,7 +207,7 @@
assert_array_equal(np.alltrue(y1, axis=1), [0, 0, 1])
-class TestCopy(TestCase):
+class TestCopy(object):
def test_basic(self):
a = np.array([[1, 2], [3, 4]])
@@ -235,7 +235,7 @@
assert_(a_fort_copy.flags.f_contiguous)
-class TestAverage(TestCase):
+class TestAverage(object):
def test_basic(self):
y1 = np.array([1, 2, 3])
@@ -345,9 +345,9 @@
a = np.array([decimal.Decimal(x) for x in range(10)])
w = np.array([decimal.Decimal(1) for _ in range(10)])
w /= w.sum()
- assert_almost_equal(a.mean(0), average(a, weights=w))
+ assert_almost_equal(a.mean(0), average(a, weights=w))
-class TestSelect(TestCase):
+class TestSelect(object):
choices = [np.array([1, 2, 3]),
np.array([4, 5, 6]),
np.array([7, 8, 9])]
@@ -419,7 +419,7 @@
select(conditions, choices)
-class TestInsert(TestCase):
+class TestInsert(object):
def test_basic(self):
a = [1, 2, 3]
@@ -520,7 +520,7 @@
assert_array_equal(b[[0, 3]], np.array(val, dtype=b.dtype))
-class TestAmax(TestCase):
+class TestAmax(object):
def test_basic(self):
a = [3, 4, 5, 10, -3, -5, 6.0]
@@ -532,7 +532,7 @@
assert_equal(np.amax(b, axis=1), [9.0, 10.0, 8.0])
-class TestAmin(TestCase):
+class TestAmin(object):
def test_basic(self):
a = [3, 4, 5, 10, -3, -5, 6.0]
@@ -544,7 +544,7 @@
assert_equal(np.amin(b, axis=1), [3.0, 4.0, 2.0])
-class TestPtp(TestCase):
+class TestPtp(object):
def test_basic(self):
a = np.array([3, 4, 5, 10, -3, -5, 6.0])
@@ -556,7 +556,7 @@
assert_equal(b.ptp(axis=-1), [6.0, 6.0, 6.0])
-class TestCumsum(TestCase):
+class TestCumsum(object):
def test_basic(self):
ba = [1, 2, 10, 11, 6, 5, 4]
@@ -579,7 +579,7 @@
assert_array_equal(np.cumsum(a2, axis=1), tgt)
-class TestProd(TestCase):
+class TestProd(object):
def test_basic(self):
ba = [1, 2, 10, 11, 6, 5, 4]
@@ -589,8 +589,8 @@
a = np.array(ba, ctype)
a2 = np.array(ba2, ctype)
if ctype in ['1', 'b']:
- self.assertRaises(ArithmeticError, np.prod, a)
- self.assertRaises(ArithmeticError, np.prod, a2, 1)
+ assert_raises(ArithmeticError, np.prod, a)
+ assert_raises(ArithmeticError, np.prod, a2, 1)
else:
assert_equal(a.prod(axis=0), 26400)
assert_array_equal(a2.prod(axis=0),
@@ -599,7 +599,7 @@
np.array([24, 1890, 600], ctype))
-class TestCumprod(TestCase):
+class TestCumprod(object):
def test_basic(self):
ba = [1, 2, 10, 11, 6, 5, 4]
@@ -609,9 +609,9 @@
a = np.array(ba, ctype)
a2 = np.array(ba2, ctype)
if ctype in ['1', 'b']:
- self.assertRaises(ArithmeticError, np.cumprod, a)
- self.assertRaises(ArithmeticError, np.cumprod, a2, 1)
- self.assertRaises(ArithmeticError, np.cumprod, a)
+ assert_raises(ArithmeticError, np.cumprod, a)
+ assert_raises(ArithmeticError, np.cumprod, a2, 1)
+ assert_raises(ArithmeticError, np.cumprod, a)
else:
assert_array_equal(np.cumprod(a, axis=-1),
np.array([1, 2, 20, 220,
@@ -626,7 +626,7 @@
[10, 30, 120, 600]], ctype))
-class TestDiff(TestCase):
+class TestDiff(object):
def test_basic(self):
x = [1, 4, 6, 7, 12]
@@ -659,9 +659,9 @@
assert_array_equal(diff(x, n=2, axis=0), out4)
-class TestDelete(TestCase):
+class TestDelete(object):
- def setUp(self):
+ def setup(self):
self.a = np.arange(5)
self.nd_a = np.arange(5).repeat(2).reshape(1, 5, 2)
@@ -734,7 +734,7 @@
assert_equal(m.flags.f_contiguous, k.flags.f_contiguous)
-class TestGradient(TestCase):
+class TestGradient(object):
def test_basic(self):
v = [[1, 1], [3, 4]]
@@ -744,7 +744,7 @@
assert_array_equal(gradient(x), dx)
assert_array_equal(gradient(v), dx)
- def test_args(self):
+ def test_args(self):
dx = np.cumsum(np.ones(5))
dx_uneven = [1., 2., 5., 9., 11.]
f_2d = np.arange(25).reshape(5, 5)
@@ -827,15 +827,15 @@
def test_spacing(self):
f = np.array([0, 2., 3., 4., 5., 5.])
- f = np.tile(f, (6,1)) + f.reshape(-1, 1)
+ f = np.tile(f, (6,1)) + f.reshape(-1, 1)
x_uneven = np.array([0., 0.5, 1., 3., 5., 7.])
x_even = np.arange(6.)
-
+
fdx_even_ord1 = np.tile([2., 1.5, 1., 1., 0.5, 0.], (6,1))
fdx_even_ord2 = np.tile([2.5, 1.5, 1., 1., 0.5, -0.5], (6,1))
fdx_uneven_ord1 = np.tile([4., 3., 1.7, 0.5, 0.25, 0.], (6,1))
fdx_uneven_ord2 = np.tile([5., 3., 1.7, 0.5, 0.25, -0.25], (6,1))
-
+
# evenly spaced
for edge_order, exp_res in [(1, fdx_even_ord1), (2, fdx_even_ord2)]:
res1 = gradient(f, 1., axis=(0,1), edge_order=edge_order)
@@ -845,19 +845,19 @@
axis=None, edge_order=edge_order)
assert_array_equal(res1, res2)
assert_array_equal(res2, res3)
- assert_almost_equal(res1[0], exp_res.T)
- assert_almost_equal(res1[1], exp_res)
-
+ assert_almost_equal(res1[0], exp_res.T)
+ assert_almost_equal(res1[1], exp_res)
+
res1 = gradient(f, 1., axis=0, edge_order=edge_order)
res2 = gradient(f, x_even, axis=0, edge_order=edge_order)
assert_(res1.shape == res2.shape)
assert_almost_equal(res2, exp_res.T)
-
+
res1 = gradient(f, 1., axis=1, edge_order=edge_order)
res2 = gradient(f, x_even, axis=1, edge_order=edge_order)
assert_(res1.shape == res2.shape)
assert_array_equal(res2, exp_res)
-
+
# unevenly spaced
for edge_order, exp_res in [(1, fdx_uneven_ord1), (2, fdx_uneven_ord2)]:
res1 = gradient(f, x_uneven, x_uneven,
@@ -867,13 +867,13 @@
assert_array_equal(res1, res2)
assert_almost_equal(res1[0], exp_res.T)
assert_almost_equal(res1[1], exp_res)
-
+
res1 = gradient(f, x_uneven, axis=0, edge_order=edge_order)
assert_almost_equal(res1, exp_res.T)
-
+
res1 = gradient(f, x_uneven, axis=1, edge_order=edge_order)
assert_almost_equal(res1, exp_res)
-
+
# mixed
res1 = gradient(f, x_even, x_uneven, axis=(0,1), edge_order=1)
res2 = gradient(f, x_uneven, x_even, axis=(1,0), edge_order=1)
@@ -881,14 +881,14 @@
assert_array_equal(res1[1], res2[0])
assert_almost_equal(res1[0], fdx_even_ord1.T)
assert_almost_equal(res1[1], fdx_uneven_ord1)
-
+
res1 = gradient(f, x_even, x_uneven, axis=(0,1), edge_order=2)
res2 = gradient(f, x_uneven, x_even, axis=(1,0), edge_order=2)
assert_array_equal(res1[0], res2[1])
assert_array_equal(res1[1], res2[0])
assert_almost_equal(res1[0], fdx_even_ord2.T)
assert_almost_equal(res1[1], fdx_uneven_ord2)
-
+
def test_specific_axes(self):
# Testing that gradient can work on a given axis only
v = [[1, 1], [3, 4]]
@@ -914,7 +914,7 @@
assert_raises(np.AxisError, gradient, x, axis=3)
assert_raises(np.AxisError, gradient, x, axis=-3)
# assert_raises(TypeError, gradient, x, axis=[1,])
-
+
def test_timedelta64(self):
# Make sure gradient() can handle special types like timedelta64
x = np.array(
@@ -937,7 +937,7 @@
gradient(np.arange(2), edge_order=1)
# needs at least 3 points for edge_order ==1
gradient(np.arange(3), edge_order=2)
-
+
assert_raises(ValueError, gradient, np.arange(0), edge_order=1)
assert_raises(ValueError, gradient, np.arange(0), edge_order=2)
assert_raises(ValueError, gradient, np.arange(1), edge_order=1)
@@ -945,7 +945,7 @@
assert_raises(ValueError, gradient, np.arange(2), edge_order=2)
-class TestAngle(TestCase):
+class TestAngle(object):
def test_basic(self):
x = [1 + 3j, np.sqrt(2) / 2.0 + 1j * np.sqrt(2) / 2,
@@ -961,7 +961,7 @@
assert_array_almost_equal(z, zo, 11)
-class TestTrimZeros(TestCase):
+class TestTrimZeros(object):
"""
Only testing for integer splits.
@@ -984,7 +984,7 @@
assert_array_equal(res, np.array([1, 0, 2, 3, 0, 4]))
-class TestExtins(TestCase):
+class TestExtins(object):
def test_basic(self):
a = np.array([1, 3, 2, 1, 2, 3, 3])
@@ -1023,7 +1023,7 @@
assert_array_equal(a, ac)
-class TestVectorize(TestCase):
+class TestVectorize(object):
def test_simple(self):
def addsubtract(a, b):
@@ -1355,7 +1355,7 @@
f(x)
-class TestDigitize(TestCase):
+class TestDigitize(object):
def test_forward(self):
x = np.arange(-6, 5)
@@ -1428,7 +1428,7 @@
assert_(not isinstance(digitize(b, a, True), A))
-class TestUnwrap(TestCase):
+class TestUnwrap(object):
def test_simple(self):
# check that unwrap removes jumps greather that 2*pi
@@ -1437,7 +1437,7 @@
assert_(np.all(diff(unwrap(rand(10) * 100)) < np.pi))
-class TestFilterwindows(TestCase):
+class TestFilterwindows(object):
def test_hanning(self):
# check symmetry
@@ -1468,7 +1468,7 @@
assert_almost_equal(np.sum(w, axis=0), 3.7800, 4)
-class TestTrapz(TestCase):
+class TestTrapz(object):
def test_simple(self):
x = np.arange(-10, 10, .1)
@@ -1540,7 +1540,7 @@
assert_almost_equal(mr, r)
-class TestSinc(TestCase):
+class TestSinc(object):
def test_simple(self):
assert_(sinc(0) == 1)
@@ -1557,12 +1557,12 @@
assert_array_equal(y1, y3)
-class TestHistogram(TestCase):
+class TestHistogram(object):
- def setUp(self):
+ def setup(self):
pass
- def tearDown(self):
+ def teardown(self):
pass
def test_simple(self):
@@ -1768,16 +1768,16 @@
left_edges = edges[:-1][mask]
right_edges = edges[1:][mask]
for x, left, right in zip(arr, left_edges, right_edges):
- self.assertGreaterEqual(x, left)
- self.assertLess(x, right)
+ assert_(x >= left)
+ assert_(x < right)
def test_last_bin_inclusive_range(self):
arr = np.array([0., 0., 0., 1., 2., 3., 3., 4., 5.])
hist, edges = np.histogram(arr, bins=30, range=(-0.5, 5))
- self.assertEqual(hist[-1], 1)
+ assert_equal(hist[-1], 1)
-class TestHistogramOptimBinNums(TestCase):
+class TestHistogramOptimBinNums(object):
"""
Provide test coverage when using provided estimators for optimal number of
bins
@@ -1887,7 +1887,7 @@
completely ignored. All test values have been precomputed and
the shouldn't change.
"""
- # some basic sanity checking, with some fixed data.
+ # some basic sanity checking, with some fixed data.
# Checking for the correct number of bins
basic_test = {
50: {'fd': 8, 'scott': 8, 'rice': 15,
@@ -1899,7 +1899,7 @@
}
for testlen, expectedResults in basic_test.items():
- # create some sort of non uniform data to test with
+ # create some sort of non uniform data to test with
# (3 peak uniform mixture)
x1 = np.linspace(-10, -1, testlen // 5 * 2)
x2 = np.linspace(1, 10, testlen // 5 * 3)
@@ -1917,11 +1917,11 @@
"""
estimator_list = ['fd', 'scott', 'rice', 'sturges', 'auto']
for estimator in estimator_list:
- assert_raises(TypeError, histogram, [1, 2, 3],
+ assert_raises(TypeError, histogram, [1, 2, 3],
estimator, weights=[1, 2, 3])
-class TestHistogramdd(TestCase):
+class TestHistogramdd(object):
def test_simple(self):
x = np.array([[-.5, .5, 1.5], [-.5, 1.5, 2.5], [-.5, 2.5, .5],
@@ -2061,7 +2061,7 @@
range=[[0.0, 1.0], [np.nan, 0.75], [0.25, 0.5]])
-class TestUnique(TestCase):
+class TestUnique(object):
def test_simple(self):
x = np.array([4, 3, 2, 1, 1, 2, 3, 4, 0])
@@ -2073,7 +2073,7 @@
assert_(np.all(unique(x) == [1 + 1j, 1 + 10j, 5 + 6j, 10]))
-class TestCheckFinite(TestCase):
+class TestCheckFinite(object):
def test_simple(self):
a = [1, 2, 3]
@@ -2090,7 +2090,7 @@
assert_(a.dtype == np.float64)
-class TestCorrCoef(TestCase):
+class TestCorrCoef(object):
A = np.array(
[[0.15391142, 0.18045767, 0.14197213],
[0.70461506, 0.96474128, 0.27906989],
@@ -2175,7 +2175,7 @@
assert_(np.all(np.abs(c) <= 1.0))
-class TestCov(TestCase):
+class TestCov(object):
x1 = np.array([[0, 2], [1, 1], [2, 0]]).T
res1 = np.array([[1., -1.], [-1., 1.]])
x2 = np.array([0.0, 1.0, 2.0], ndmin=2)
@@ -2273,7 +2273,7 @@
self.res1)
-class Test_I0(TestCase):
+class Test_I0(object):
def test_simple(self):
assert_almost_equal(
@@ -2299,7 +2299,7 @@
[1.05884290, 1.06432317]]))
-class TestKaiser(TestCase):
+class TestKaiser(object):
def test_simple(self):
assert_(np.isfinite(kaiser(1, 1.0)))
@@ -2318,7 +2318,7 @@
kaiser(3, 4)
-class TestMsort(TestCase):
+class TestMsort(object):
def test_simple(self):
A = np.array([[0.44567325, 0.79115165, 0.54900530],
@@ -2331,7 +2331,7 @@
[0.64864341, 0.79115165, 0.96098397]]))
-class TestMeshgrid(TestCase):
+class TestMeshgrid(object):
def test_simple(self):
[X, Y] = meshgrid([1, 2, 3], [4, 5, 6, 7])
@@ -2420,7 +2420,7 @@
assert_equal(x[1, :], X)
-class TestPiecewise(TestCase):
+class TestPiecewise(object):
def test_simple(self):
# Condition is single bool list
@@ -2496,7 +2496,7 @@
[3., 3., 1.]]))
-class TestBincount(TestCase):
+class TestBincount(object):
def test_simple(self):
y = np.bincount(np.arange(4))
@@ -2583,7 +2583,7 @@
assert_equal(sys.getrefcount(np.dtype(np.double)), double_refcount)
-class TestInterp(TestCase):
+class TestInterp(object):
def test_exceptions(self):
assert_raises(ValueError, interp, 0, [], [])
@@ -2701,7 +2701,7 @@
assert_array_equal(res[i], desired[i])
-class TestPercentile(TestCase):
+class TestPercentile(object):
def test_basic(self):
x = np.arange(8) * 0.5
@@ -2805,7 +2805,7 @@
# test for no empty dimensions for compatibility with old percentile
x = np.arange(12).reshape(3, 4)
assert_equal(np.percentile(x, 50), 5.5)
- self.assertTrue(np.isscalar(np.percentile(x, 50)))
+ assert_(np.isscalar(np.percentile(x, 50)))
r0 = np.array([4., 5., 6., 7.])
assert_equal(np.percentile(x, 50, axis=0), r0)
assert_equal(np.percentile(x, 50, axis=0).shape, r0.shape)
@@ -2826,7 +2826,7 @@
# test for no empty dimensions for compatibility with old percentile
x = np.arange(12).reshape(3, 4)
assert_equal(np.percentile(x, 50, interpolation='lower'), 5.)
- self.assertTrue(np.isscalar(np.percentile(x, 50)))
+ assert_(np.isscalar(np.percentile(x, 50)))
r0 = np.array([4., 5., 6., 7.])
c0 = np.percentile(x, 50, interpolation='lower', axis=0)
assert_equal(c0, r0)
@@ -3132,7 +3132,7 @@
a, [0.3, 0.6], (0, 2), interpolation='nearest'), b)
-class TestMedian(TestCase):
+class TestMedian(object):
def test_basic(self):
a0 = np.array(1)
@@ -3389,7 +3389,7 @@
(1, 1, 7, 1))
-class TestAdd_newdoc_ufunc(TestCase):
+class TestAdd_newdoc_ufunc(object):
def test_ufunc_arg(self):
assert_raises(TypeError, add_newdoc_ufunc, 2, "blah")
@@ -3399,15 +3399,15 @@
assert_raises(TypeError, add_newdoc_ufunc, np.add, 3)
-class TestAdd_newdoc(TestCase):
+class TestAdd_newdoc(object):
@dec.skipif(sys.flags.optimize == 2)
def test_add_doc(self):
# test np.add_newdoc
tgt = "Current flat index into the array."
- self.assertEqual(np.core.flatiter.index.__doc__[:len(tgt)], tgt)
- self.assertTrue(len(np.core.ufunc.identity.__doc__) > 300)
- self.assertTrue(len(np.lib.index_tricks.mgrid.__doc__) > 300)
+ assert_equal(np.core.flatiter.index.__doc__[:len(tgt)], tgt)
+ assert_(len(np.core.ufunc.identity.__doc__) > 300)
+ assert_(len(np.lib.index_tricks.mgrid.__doc__) > 300)
if __name__ == "__main__":
diff --git a/numpy/lib/tests/test_index_tricks.py b/numpy/lib/tests/test_index_tricks.py
index 5b79102..f06406c 100644
--- a/numpy/lib/tests/test_index_tricks.py
+++ b/numpy/lib/tests/test_index_tricks.py
@@ -2,7 +2,7 @@
import numpy as np
from numpy.testing import (
- run_module_suite, TestCase, assert_, assert_equal, assert_array_equal,
+ run_module_suite, assert_, assert_equal, assert_array_equal,
assert_almost_equal, assert_array_almost_equal, assert_raises
)
from numpy.lib.index_tricks import (
@@ -11,7 +11,7 @@
)
-class TestRavelUnravelIndex(TestCase):
+class TestRavelUnravelIndex(object):
def test_basic(self):
assert_equal(np.unravel_index(2, (2, 2)), (1, 0))
assert_equal(np.ravel_multi_index((1, 0), (2, 2)), 2)
@@ -110,11 +110,11 @@
def test_writeability(self):
# See gh-7269
x, y = np.unravel_index([1, 2, 3], (4, 5))
- self.assertTrue(x.flags.writeable)
- self.assertTrue(y.flags.writeable)
+ assert_(x.flags.writeable)
+ assert_(y.flags.writeable)
-class TestGrid(TestCase):
+class TestGrid(object):
def test_basic(self):
a = mgrid[-1:1:10j]
b = mgrid[-1:1:0.1]
@@ -147,7 +147,7 @@
0.2*np.ones(20, 'd'), 11)
-class TestConcatenator(TestCase):
+class TestConcatenator(object):
def test_1d(self):
assert_array_equal(r_[1, 2, 3, 4, 5, 6], np.array([1, 2, 3, 4, 5, 6]))
b = np.ones(5)
@@ -206,14 +206,14 @@
assert_equal(type(actual), type(expected))
-class TestNdenumerate(TestCase):
+class TestNdenumerate(object):
def test_basic(self):
a = np.array([[1, 2], [3, 4]])
assert_equal(list(ndenumerate(a)),
[((0, 0), 1), ((0, 1), 2), ((1, 0), 3), ((1, 1), 4)])
-class TestIndexExpression(TestCase):
+class TestIndexExpression(object):
def test_regression_1(self):
# ticket #1196
a = np.arange(2)
@@ -227,7 +227,7 @@
assert_equal(a[:, :3, [1, 2]], a[s_[:, :3, [1, 2]]])
-class TestIx_(TestCase):
+class TestIx_(object):
def test_regression_1(self):
# Test empty inputs create ouputs of indexing type, gh-5804
# Test both lists and arrays
diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py
index 8680895..4bc2a1b 100644
--- a/numpy/lib/tests/test_io.py
+++ b/numpy/lib/tests/test_io.py
@@ -17,9 +17,9 @@
from numpy.compat import asbytes, bytes, unicode, Path
from numpy.ma.testutils import assert_equal
from numpy.testing import (
- TestCase, run_module_suite, assert_warns, assert_,
- assert_raises_regex, assert_raises, assert_allclose,
- assert_array_equal, temppath, dec, IS_PYPY, suppress_warnings
+ run_module_suite, assert_warns, assert_, assert_raises_regex,
+ assert_raises, assert_allclose, assert_array_equal, temppath, dec, IS_PYPY,
+ suppress_warnings
)
@@ -165,7 +165,7 @@
self.check_roundtrips(a)
-class TestSaveLoad(RoundtripTest, TestCase):
+class TestSaveLoad(RoundtripTest):
def roundtrip(self, *args, **kwargs):
RoundtripTest.roundtrip(self, np.save, *args, **kwargs)
assert_equal(self.arr[0], self.arr_reloaded)
@@ -173,7 +173,7 @@
assert_equal(self.arr[0].flags.fnc, self.arr_reloaded.flags.fnc)
-class TestSavezLoad(RoundtripTest, TestCase):
+class TestSavezLoad(RoundtripTest):
def roundtrip(self, *args, **kwargs):
RoundtripTest.roundtrip(self, np.savez, *args, **kwargs)
try:
@@ -304,7 +304,7 @@
assert_(fp.closed)
-class TestSaveTxt(TestCase):
+class TestSaveTxt(object):
def test_array(self):
a = np.array([[1, 2], [3, 4]], float)
fmt = "%.18e"
@@ -461,7 +461,7 @@
assert_array_equal(a, b)
-class TestLoadTxt(TestCase):
+class TestLoadTxt(object):
def test_record(self):
c = TextIO()
c.write('1 2\n3 4')
@@ -864,7 +864,7 @@
np.loadtxt(c, delimiter=',', dtype=dt, comments=None) # Should succeed
-class Testfromregex(TestCase):
+class Testfromregex(object):
# np.fromregex expects files opened in binary mode.
def test_record(self):
c = TextIO()
@@ -902,7 +902,7 @@
#####--------------------------------------------------------------------------
-class TestFromTxt(TestCase):
+class TestFromTxt(object):
#
def test_record(self):
# Test w/ explicit dtype
@@ -1683,7 +1683,7 @@
test = np.recfromtxt(data, **kwargs)
control = np.array([(0, 1), (2, 3)],
dtype=[('A', np.int), ('B', np.int)])
- self.assertTrue(isinstance(test, np.recarray))
+ assert_(isinstance(test, np.recarray))
assert_equal(test, control)
#
data = TextIO('A,B\n0,1\n2,N/A')
@@ -1702,7 +1702,7 @@
test = np.recfromcsv(data, dtype=None, **kwargs)
control = np.array([(0, 1), (2, 3)],
dtype=[('A', np.int), ('B', np.int)])
- self.assertTrue(isinstance(test, np.recarray))
+ assert_(isinstance(test, np.recarray))
assert_equal(test, control)
#
data = TextIO('A,B\n0,1\n2,N/A')
@@ -1718,7 +1718,7 @@
test = np.recfromcsv(data, missing_values='N/A',)
control = np.array([(0, 1), (2, 3)],
dtype=[('a', np.int), ('b', np.int)])
- self.assertTrue(isinstance(test, np.recarray))
+ assert_(isinstance(test, np.recarray))
assert_equal(test, control)
#
data = TextIO('A,B\n0,1\n2,3')
@@ -1726,7 +1726,7 @@
test = np.recfromcsv(data, missing_values='N/A', dtype=dtype)
control = np.array([(0, 1), (2, 3)],
dtype=dtype)
- self.assertTrue(isinstance(test, np.recarray))
+ assert_(isinstance(test, np.recarray))
assert_equal(test, control)
def test_max_rows(self):
@@ -1836,7 +1836,7 @@
assert_equal(test['f2'], 1024)
-class TestPathUsage(TestCase):
+class TestPathUsage(object):
# Test that pathlib.Path can be used
@np.testing.dec.skipif(Path is None, "No pathlib.Path")
def test_loadtxt(self):
@@ -1920,7 +1920,7 @@
test = np.recfromtxt(path, **kwargs)
control = np.array([(0, 1), (2, 3)],
dtype=[('A', np.int), ('B', np.int)])
- self.assertTrue(isinstance(test, np.recarray))
+ assert_(isinstance(test, np.recarray))
assert_equal(test, control)
@np.testing.dec.skipif(Path is None, "No pathlib.Path")
@@ -1934,7 +1934,7 @@
test = np.recfromcsv(path, dtype=None, **kwargs)
control = np.array([(0, 1), (2, 3)],
dtype=[('A', np.int), ('B', np.int)])
- self.assertTrue(isinstance(test, np.recarray))
+ assert_(isinstance(test, np.recarray))
assert_equal(test, control)
diff --git a/numpy/lib/tests/test_mixins.py b/numpy/lib/tests/test_mixins.py
index db38bdf..94f06c3 100644
--- a/numpy/lib/tests/test_mixins.py
+++ b/numpy/lib/tests/test_mixins.py
@@ -6,7 +6,8 @@
import numpy as np
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_equal, assert_raises)
+ run_module_suite, assert_, assert_equal, assert_raises
+ )
PY2 = sys.version_info.major < 3
@@ -99,7 +100,7 @@
]
-class TestNDArrayOperatorsMixin(TestCase):
+class TestNDArrayOperatorsMixin(object):
def test_array_like_add(self):
diff --git a/numpy/lib/tests/test_nanfunctions.py b/numpy/lib/tests/test_nanfunctions.py
index 466ceef..3d362fc 100644
--- a/numpy/lib/tests/test_nanfunctions.py
+++ b/numpy/lib/tests/test_nanfunctions.py
@@ -4,7 +4,7 @@
import numpy as np
from numpy.testing import (
- run_module_suite, TestCase, assert_, assert_equal, assert_almost_equal,
+ run_module_suite, assert_, assert_equal, assert_almost_equal,
assert_no_warnings, assert_raises, assert_array_equal, suppress_warnings
)
@@ -35,7 +35,7 @@
[0.1610, 0.0, 0.0, 0.1859, 0.3146, 0.0]])
-class TestNanFunctions_MinMax(TestCase):
+class TestNanFunctions_MinMax(object):
nanfuncs = [np.nanmin, np.nanmax]
stdfuncs = [np.min, np.max]
@@ -165,7 +165,7 @@
assert_(issubclass(w[0].category, RuntimeWarning))
-class TestNanFunctions_ArgminArgmax(TestCase):
+class TestNanFunctions_ArgminArgmax(object):
nanfuncs = [np.nanargmin, np.nanargmax]
@@ -224,7 +224,7 @@
assert_(np.isscalar(res))
-class TestNanFunctions_IntTypes(TestCase):
+class TestNanFunctions_IntTypes(object):
int_types = (np.int8, np.int16, np.int32, np.int64, np.uint8,
np.uint16, np.uint32, np.uint64)
@@ -396,7 +396,7 @@
assert_(np.isscalar(res))
-class TestNanFunctions_SumProd(TestCase, SharedNanFunctionsTestsMixin):
+class TestNanFunctions_SumProd(SharedNanFunctionsTestsMixin):
nanfuncs = [np.nansum, np.nanprod]
stdfuncs = [np.sum, np.prod]
@@ -430,7 +430,7 @@
assert_equal(res, tgt)
-class TestNanFunctions_CumSumProd(TestCase, SharedNanFunctionsTestsMixin):
+class TestNanFunctions_CumSumProd(SharedNanFunctionsTestsMixin):
nanfuncs = [np.nancumsum, np.nancumprod]
stdfuncs = [np.cumsum, np.cumprod]
@@ -513,7 +513,7 @@
assert_almost_equal(res, tgt)
-class TestNanFunctions_MeanVarStd(TestCase, SharedNanFunctionsTestsMixin):
+class TestNanFunctions_MeanVarStd(SharedNanFunctionsTestsMixin):
nanfuncs = [np.nanmean, np.nanvar, np.nanstd]
stdfuncs = [np.mean, np.var, np.std]
@@ -585,7 +585,7 @@
assert_(len(w) == 0)
-class TestNanFunctions_Median(TestCase):
+class TestNanFunctions_Median(object):
def test_mutation(self):
# Check that passed array is not modified.
@@ -749,7 +749,7 @@
([np.nan] * i) + [-inf] * j)
-class TestNanFunctions_Percentile(TestCase):
+class TestNanFunctions_Percentile(object):
def test_mutation(self):
# Check that passed array is not modified.
diff --git a/numpy/lib/tests/test_polynomial.py b/numpy/lib/tests/test_polynomial.py
index 0725c18..9a46508 100644
--- a/numpy/lib/tests/test_polynomial.py
+++ b/numpy/lib/tests/test_polynomial.py
@@ -80,12 +80,12 @@
'''
import numpy as np
from numpy.testing import (
- run_module_suite, TestCase, assert_, assert_equal, assert_array_equal,
+ run_module_suite, assert_, assert_equal, assert_array_equal,
assert_almost_equal, assert_array_almost_equal, assert_raises, rundocs
)
-class TestDocs(TestCase):
+class TestDocs(object):
def test_doctests(self):
return rundocs()
diff --git a/numpy/lib/tests/test_recfunctions.py b/numpy/lib/tests/test_recfunctions.py
index 7cf93d6..bc9f8d7 100644
--- a/numpy/lib/tests/test_recfunctions.py
+++ b/numpy/lib/tests/test_recfunctions.py
@@ -5,8 +5,8 @@
from numpy.ma.mrecords import MaskedRecords
from numpy.ma.testutils import assert_equal
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_raises, dec
-)
+ run_module_suite, assert_, assert_raises, dec
+ )
from numpy.lib.recfunctions import (
drop_fields, rename_fields, get_fieldstructure, recursive_fill_fields,
find_duplicates, merge_arrays, append_fields, stack_arrays, join_by
@@ -16,10 +16,10 @@
zip_descr = np.lib.recfunctions.zip_descr
-class TestRecFunctions(TestCase):
+class TestRecFunctions(object):
# Misc tests
- def setUp(self):
+ def setup(self):
x = np.array([1, 2, ])
y = np.array([10, 20, 30])
z = np.array([('A', 1.), ('B', 2.)],
@@ -193,7 +193,7 @@
assert_equal(test[0], a[test[-1]])
-class TestRecursiveFillFields(TestCase):
+class TestRecursiveFillFields(object):
# Test recursive_fill_fields.
def test_simple_flexible(self):
# Test recursive_fill_fields on flexible-array
@@ -216,10 +216,10 @@
assert_equal(test, control)
-class TestMergeArrays(TestCase):
+class TestMergeArrays(object):
# Test merge_arrays
- def setUp(self):
+ def setup(self):
x = np.array([1, 2, ])
y = np.array([10, 20, 30])
z = np.array(
@@ -349,10 +349,10 @@
assert_equal(test, control)
-class TestAppendFields(TestCase):
+class TestAppendFields(object):
# Test append_fields
- def setUp(self):
+ def setup(self):
x = np.array([1, 2, ])
y = np.array([10, 20, 30])
z = np.array(
@@ -403,9 +403,9 @@
assert_equal(test, control)
-class TestStackArrays(TestCase):
+class TestStackArrays(object):
# Test stack_arrays
- def setUp(self):
+ def setup(self):
x = np.array([1, 2, ])
y = np.array([10, 20, 30])
z = np.array(
@@ -419,11 +419,11 @@
(_, x, _, _) = self.data
test = stack_arrays((x,))
assert_equal(test, x)
- self.assertTrue(test is x)
+ assert_(test is x)
test = stack_arrays(x)
assert_equal(test, x)
- self.assertTrue(test is x)
+ assert_(test is x)
def test_unnamed_fields(self):
# Tests combinations of arrays w/o named fields
@@ -578,8 +578,8 @@
assert_equal(res.mask, expected.mask)
-class TestJoinBy(TestCase):
- def setUp(self):
+class TestJoinBy(object):
+ def setup(self):
self.a = np.array(list(zip(np.arange(10), np.arange(50, 60),
np.arange(100, 110))),
dtype=[('a', int), ('b', int), ('c', int)])
@@ -744,9 +744,9 @@
assert_equal(res.dtype, expected_dtype)
-class TestJoinBy2(TestCase):
+class TestJoinBy2(object):
@classmethod
- def setUp(cls):
+ def setup(cls):
cls.a = np.array(list(zip(np.arange(10), np.arange(50, 60),
np.arange(100, 110))),
dtype=[('a', int), ('b', int), ('c', int)])
@@ -770,8 +770,8 @@
assert_equal(test, control)
def test_no_postfix(self):
- self.assertRaises(ValueError, join_by, 'a', self.a, self.b,
- r1postfix='', r2postfix='')
+ assert_raises(ValueError, join_by, 'a', self.a, self.b,
+ r1postfix='', r2postfix='')
def test_no_r2postfix(self):
# Basic test of join_by no_r2postfix
@@ -809,13 +809,13 @@
assert_equal(test.dtype, control.dtype)
assert_equal(test, control)
-class TestAppendFieldsObj(TestCase):
+class TestAppendFieldsObj(object):
"""
Test append_fields with arrays containing objects
"""
# https://github.com/numpy/numpy/issues/2346
- def setUp(self):
+ def setup(self):
from datetime import date
self.data = dict(obj=date(2000, 1, 1))
diff --git a/numpy/lib/tests/test_regression.py b/numpy/lib/tests/test_regression.py
index 6095ac4..1567219 100644
--- a/numpy/lib/tests/test_regression.py
+++ b/numpy/lib/tests/test_regression.py
@@ -5,7 +5,7 @@
import numpy as np
from numpy.testing import (
- run_module_suite, TestCase, assert_, assert_equal, assert_array_equal,
+ run_module_suite, assert_, assert_equal, assert_array_equal,
assert_array_almost_equal, assert_raises, _assert_valid_refcount,
)
from numpy.compat import unicode
@@ -13,7 +13,7 @@
rlevel = 1
-class TestRegression(TestCase):
+class TestRegression(object):
def test_poly1d(self, level=rlevel):
# Ticket #28
assert_equal(np.poly1d([1]) - np.poly1d([1, 0]),
@@ -59,7 +59,7 @@
def test_poly1d_nan_roots(self, level=rlevel):
# Ticket #396
p = np.poly1d([np.nan, np.nan, 1], r=0)
- self.assertRaises(np.linalg.LinAlgError, getattr, p, "r")
+ assert_raises(np.linalg.LinAlgError, getattr, p, "r")
def test_mem_polymul(self, level=rlevel):
# Ticket #448
@@ -155,8 +155,8 @@
i = np.random.randint(0, n, size=thesize)
a[np.ix_(i, i, i, i, i)]
- self.assertRaises(ValueError, dp)
- self.assertRaises(ValueError, dp2)
+ assert_raises(ValueError, dp)
+ assert_raises(ValueError, dp2)
def test_void_coercion(self, level=rlevel):
dt = np.dtype([('a', 'f4'), ('b', 'i4')])
diff --git a/numpy/lib/tests/test_shape_base.py b/numpy/lib/tests/test_shape_base.py
index 14406fe..9e739ea 100644
--- a/numpy/lib/tests/test_shape_base.py
+++ b/numpy/lib/tests/test_shape_base.py
@@ -8,12 +8,12 @@
vsplit, dstack, column_stack, kron, tile, expand_dims,
)
from numpy.testing import (
- run_module_suite, TestCase, assert_, assert_equal, assert_array_equal,
- assert_raises, assert_warns
+ run_module_suite, assert_, assert_equal, assert_array_equal, assert_raises,
+ assert_warns
)
-class TestApplyAlongAxis(TestCase):
+class TestApplyAlongAxis(object):
def test_simple(self):
a = np.ones((20, 10), 'd')
assert_array_equal(
@@ -177,14 +177,14 @@
assert_equal(type(actual[i]), type(expected[i]))
-class TestApplyOverAxes(TestCase):
+class TestApplyOverAxes(object):
def test_simple(self):
a = np.arange(24).reshape(2, 3, 4)
aoa_a = apply_over_axes(np.sum, a, [0, 2])
assert_array_equal(aoa_a, np.array([[[60], [92], [124]]]))
-class TestExpandDims(TestCase):
+class TestExpandDims(object):
def test_functionality(self):
s = (2, 3, 4, 5)
a = np.empty(s)
@@ -203,7 +203,7 @@
assert_warns(DeprecationWarning, expand_dims, a, 5)
-class TestArraySplit(TestCase):
+class TestArraySplit(object):
def test_integer_0_split(self):
a = np.arange(10)
assert_raises(ValueError, array_split, a, 0)
@@ -328,7 +328,7 @@
compare_results(res, desired)
-class TestSplit(TestCase):
+class TestSplit(object):
# The split 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.
@@ -343,12 +343,12 @@
a = np.arange(10)
assert_raises(ValueError, split, a, 3)
-class TestColumnStack(TestCase):
+class TestColumnStack(object):
def test_non_iterable(self):
assert_raises(TypeError, column_stack, 1)
-class TestDstack(TestCase):
+class TestDstack(object):
def test_non_iterable(self):
assert_raises(TypeError, dstack, 1)
@@ -383,7 +383,7 @@
# array_split has more comprehensive test of splitting.
# only do simple test on hsplit, vsplit, and dsplit
-class TestHsplit(TestCase):
+class TestHsplit(object):
"""Only testing for integer splits.
"""
@@ -412,7 +412,7 @@
compare_results(res, desired)
-class TestVsplit(TestCase):
+class TestVsplit(object):
"""Only testing for integer splits.
"""
@@ -439,7 +439,7 @@
compare_results(res, desired)
-class TestDsplit(TestCase):
+class TestDsplit(object):
# Only testing for integer splits.
def test_non_iterable(self):
assert_raises(ValueError, dsplit, 1, 1)
@@ -472,7 +472,7 @@
compare_results(res, desired)
-class TestSqueeze(TestCase):
+class TestSqueeze(object):
def test_basic(self):
from numpy.random import rand
@@ -491,7 +491,7 @@
assert_equal(type(res), np.ndarray)
-class TestKron(TestCase):
+class TestKron(object):
def test_return_type(self):
a = np.ones([2, 2])
m = np.asmatrix(a)
@@ -510,7 +510,7 @@
assert_equal(type(kron(ma, a)), myarray)
-class TestTile(TestCase):
+class TestTile(object):
def test_basic(self):
a = np.array([0, 1, 2])
b = [[1, 2], [3, 4]]
@@ -550,19 +550,19 @@
assert_equal(large, klarge)
-class TestMayShareMemory(TestCase):
+class TestMayShareMemory(object):
def test_basic(self):
d = np.ones((50, 60))
d2 = np.ones((30, 60, 6))
- self.assertTrue(np.may_share_memory(d, d))
- self.assertTrue(np.may_share_memory(d, d[::-1]))
- self.assertTrue(np.may_share_memory(d, d[::2]))
- self.assertTrue(np.may_share_memory(d, d[1:, ::-1]))
+ assert_(np.may_share_memory(d, d))
+ assert_(np.may_share_memory(d, d[::-1]))
+ assert_(np.may_share_memory(d, d[::2]))
+ assert_(np.may_share_memory(d, d[1:, ::-1]))
- self.assertFalse(np.may_share_memory(d[::-1], d2))
- self.assertFalse(np.may_share_memory(d[::2], d2))
- self.assertFalse(np.may_share_memory(d[1:, ::-1], d2))
- self.assertTrue(np.may_share_memory(d2[1:, ::-1], d2))
+ assert_(not np.may_share_memory(d[::-1], d2))
+ assert_(not np.may_share_memory(d[::2], d2))
+ assert_(not np.may_share_memory(d[1:, ::-1], d2))
+ assert_(np.may_share_memory(d2[1:, ::-1], d2))
# Utility
diff --git a/numpy/lib/tests/test_twodim_base.py b/numpy/lib/tests/test_twodim_base.py
index d57791e..6bf668d 100644
--- a/numpy/lib/tests/test_twodim_base.py
+++ b/numpy/lib/tests/test_twodim_base.py
@@ -4,8 +4,8 @@
from __future__ import division, absolute_import, print_function
from numpy.testing import (
- TestCase, run_module_suite, assert_equal, assert_array_equal,
- assert_array_max_ulp, assert_array_almost_equal, assert_raises,
+ run_module_suite, assert_equal, assert_array_equal, assert_array_max_ulp,
+ assert_array_almost_equal, assert_raises,
)
from numpy import (
@@ -23,7 +23,7 @@
return data
-class TestEye(TestCase):
+class TestEye(object):
def test_basic(self):
assert_equal(eye(4),
array([[1, 0, 0, 0],
@@ -96,7 +96,7 @@
assert_equal(eye(2, 2, dtype=bool), [[True, False], [False, True]])
-class TestDiag(TestCase):
+class TestDiag(object):
def test_vector(self):
vals = (100 * arange(5)).astype('l')
b = zeros((5, 5))
@@ -140,12 +140,12 @@
assert_equal(diag(A, k=-3), [])
def test_failure(self):
- self.assertRaises(ValueError, diag, [[[1]]])
+ assert_raises(ValueError, diag, [[[1]]])
-class TestFliplr(TestCase):
+class TestFliplr(object):
def test_basic(self):
- self.assertRaises(ValueError, fliplr, ones(4))
+ assert_raises(ValueError, fliplr, ones(4))
a = get_mat(4)
b = a[:, ::-1]
assert_equal(fliplr(a), b)
@@ -156,7 +156,7 @@
assert_equal(fliplr(a), b)
-class TestFlipud(TestCase):
+class TestFlipud(object):
def test_basic(self):
a = get_mat(4)
b = a[::-1, :]
@@ -168,7 +168,7 @@
assert_equal(flipud(a), b)
-class TestHistogram2d(TestCase):
+class TestHistogram2d(object):
def test_simple(self):
x = array(
[0.41702200, 0.72032449, 1.1437481e-4, 0.302332573, 0.146755891])
@@ -265,7 +265,7 @@
assert_array_equal(xe, array([0., 0.25, 0.5, 0.75, 1]))
-class TestTri(TestCase):
+class TestTri(object):
def test_dtype(self):
out = array([[1, 0, 0],
[1, 1, 0],
@@ -349,10 +349,10 @@
# simple test without offset
iu = mask_indices(3, np.triu)
a = np.arange(9).reshape(3, 3)
- yield (assert_array_equal, a[iu], array([0, 1, 2, 4, 5, 8]))
+ assert_array_equal(a[iu], array([0, 1, 2, 4, 5, 8]))
# Now with an offset
iu1 = mask_indices(3, np.triu, 1)
- yield (assert_array_equal, a[iu1], array([1, 2, 5]))
+ assert_array_equal(a[iu1], array([1, 2, 5]))
def test_tril_indices():
@@ -369,37 +369,37 @@
b = np.arange(1, 21).reshape(4, 5)
# indexing:
- yield (assert_array_equal, a[il1],
- array([1, 5, 6, 9, 10, 11, 13, 14, 15, 16]))
- yield (assert_array_equal, b[il3],
- array([1, 6, 7, 11, 12, 13, 16, 17, 18, 19]))
+ assert_array_equal(a[il1],
+ array([1, 5, 6, 9, 10, 11, 13, 14, 15, 16]))
+ assert_array_equal(b[il3],
+ array([1, 6, 7, 11, 12, 13, 16, 17, 18, 19]))
# And for assigning values:
a[il1] = -1
- yield (assert_array_equal, a,
- array([[-1, 2, 3, 4],
- [-1, -1, 7, 8],
- [-1, -1, -1, 12],
- [-1, -1, -1, -1]]))
+ assert_array_equal(a,
+ array([[-1, 2, 3, 4],
+ [-1, -1, 7, 8],
+ [-1, -1, -1, 12],
+ [-1, -1, -1, -1]]))
b[il3] = -1
- yield (assert_array_equal, b,
- array([[-1, 2, 3, 4, 5],
- [-1, -1, 8, 9, 10],
- [-1, -1, -1, 14, 15],
- [-1, -1, -1, -1, 20]]))
+ assert_array_equal(b,
+ array([[-1, 2, 3, 4, 5],
+ [-1, -1, 8, 9, 10],
+ [-1, -1, -1, 14, 15],
+ [-1, -1, -1, -1, 20]]))
# These cover almost the whole array (two diagonals right of the main one):
a[il2] = -10
- yield (assert_array_equal, a,
- array([[-10, -10, -10, 4],
- [-10, -10, -10, -10],
- [-10, -10, -10, -10],
- [-10, -10, -10, -10]]))
+ assert_array_equal(a,
+ array([[-10, -10, -10, 4],
+ [-10, -10, -10, -10],
+ [-10, -10, -10, -10],
+ [-10, -10, -10, -10]]))
b[il4] = -10
- yield (assert_array_equal, b,
- array([[-10, -10, -10, 4, 5],
- [-10, -10, -10, -10, 10],
- [-10, -10, -10, -10, -10],
- [-10, -10, -10, -10, -10]]))
+ assert_array_equal(b,
+ array([[-10, -10, -10, 4, 5],
+ [-10, -10, -10, -10, 10],
+ [-10, -10, -10, -10, -10],
+ [-10, -10, -10, -10, -10]]))
class TestTriuIndices(object):
@@ -416,39 +416,40 @@
b = np.arange(1, 21).reshape(4, 5)
# Both for indexing:
- yield (assert_array_equal, a[iu1],
- array([1, 2, 3, 4, 6, 7, 8, 11, 12, 16]))
- yield (assert_array_equal, b[iu3],
- array([1, 2, 3, 4, 5, 7, 8, 9, 10, 13, 14, 15, 19, 20]))
+ assert_array_equal(a[iu1],
+ array([1, 2, 3, 4, 6, 7, 8, 11, 12, 16]))
+ assert_array_equal(b[iu3],
+ array([1, 2, 3, 4, 5, 7, 8, 9,
+ 10, 13, 14, 15, 19, 20]))
# And for assigning values:
a[iu1] = -1
- yield (assert_array_equal, a,
- array([[-1, -1, -1, -1],
- [5, -1, -1, -1],
- [9, 10, -1, -1],
- [13, 14, 15, -1]]))
+ assert_array_equal(a,
+ array([[-1, -1, -1, -1],
+ [5, -1, -1, -1],
+ [9, 10, -1, -1],
+ [13, 14, 15, -1]]))
b[iu3] = -1
- yield (assert_array_equal, b,
- array([[-1, -1, -1, -1, -1],
- [6, -1, -1, -1, -1],
- [11, 12, -1, -1, -1],
- [16, 17, 18, -1, -1]]))
+ assert_array_equal(b,
+ array([[-1, -1, -1, -1, -1],
+ [6, -1, -1, -1, -1],
+ [11, 12, -1, -1, -1],
+ [16, 17, 18, -1, -1]]))
# These cover almost the whole array (two diagonals right of the
# main one):
a[iu2] = -10
- yield (assert_array_equal, a,
- array([[-1, -1, -10, -10],
- [5, -1, -1, -10],
- [9, 10, -1, -1],
- [13, 14, 15, -1]]))
+ assert_array_equal(a,
+ array([[-1, -1, -10, -10],
+ [5, -1, -1, -10],
+ [9, 10, -1, -1],
+ [13, 14, 15, -1]]))
b[iu4] = -10
- yield (assert_array_equal, b,
- array([[-1, -1, -10, -10, -10],
- [6, -1, -1, -10, -10],
- [11, 12, -1, -1, -10],
- [16, 17, 18, -1, -1]]))
+ assert_array_equal(b,
+ array([[-1, -1, -10, -10, -10],
+ [6, -1, -1, -10, -10],
+ [11, 12, -1, -1, -10],
+ [16, 17, 18, -1, -1]]))
class TestTrilIndicesFrom(object):
diff --git a/numpy/lib/tests/test_type_check.py b/numpy/lib/tests/test_type_check.py
index 383ffa5..259fcd4 100644
--- a/numpy/lib/tests/test_type_check.py
+++ b/numpy/lib/tests/test_type_check.py
@@ -3,7 +3,7 @@
import numpy as np
from numpy.compat import long
from numpy.testing import (
- TestCase, assert_, assert_equal, assert_array_equal, run_module_suite
+ assert_, assert_equal, assert_array_equal, run_module_suite
)
from numpy.lib.type_check import (
common_type, mintypecode, isreal, iscomplex, isposinf, isneginf,
@@ -15,7 +15,7 @@
assert_(np.all(x), x)
-class TestCommonType(TestCase):
+class TestCommonType(object):
def test_basic(self):
ai32 = np.array([[1, 2], [3, 4]], dtype=np.int32)
af16 = np.array([[1, 2], [3, 4]], dtype=np.float16)
@@ -31,7 +31,7 @@
assert_(common_type(acd) == np.cdouble)
-class TestMintypecode(TestCase):
+class TestMintypecode(object):
def test_default_1(self):
for itype in '1bcsuwil':
@@ -81,7 +81,7 @@
assert_equal(mintypecode('idD'), 'D')
-class TestIsscalar(TestCase):
+class TestIsscalar(object):
def test_basic(self):
assert_(np.isscalar(3))
@@ -92,7 +92,7 @@
assert_(np.isscalar(4.0))
-class TestReal(TestCase):
+class TestReal(object):
def test_real(self):
y = np.random.rand(10,)
@@ -123,7 +123,7 @@
assert_(not isinstance(out, np.ndarray))
-class TestImag(TestCase):
+class TestImag(object):
def test_real(self):
y = np.random.rand(10,)
@@ -154,7 +154,7 @@
assert_(not isinstance(out, np.ndarray))
-class TestIscomplex(TestCase):
+class TestIscomplex(object):
def test_fail(self):
z = np.array([-1, 0, 1])
@@ -167,7 +167,7 @@
assert_array_equal(res, [1, 0, 0])
-class TestIsreal(TestCase):
+class TestIsreal(object):
def test_pass(self):
z = np.array([-1, 0, 1j])
@@ -180,7 +180,7 @@
assert_array_equal(res, [0, 1, 1])
-class TestIscomplexobj(TestCase):
+class TestIscomplexobj(object):
def test_basic(self):
z = np.array([-1, 0, 1])
@@ -233,7 +233,7 @@
assert_(iscomplexobj(a))
-class TestIsrealobj(TestCase):
+class TestIsrealobj(object):
def test_basic(self):
z = np.array([-1, 0, 1])
assert_(isrealobj(z))
@@ -241,7 +241,7 @@
assert_(not isrealobj(z))
-class TestIsnan(TestCase):
+class TestIsnan(object):
def test_goodvalues(self):
z = np.array((-1., 0., 1.))
@@ -271,7 +271,7 @@
assert_all(np.isnan(np.array(0+0j)/0.) == 1)
-class TestIsfinite(TestCase):
+class TestIsfinite(object):
# Fixme, wrong place, isfinite now ufunc
def test_goodvalues(self):
@@ -302,7 +302,7 @@
assert_all(np.isfinite(np.array(1+1j)/0.) == 0)
-class TestIsinf(TestCase):
+class TestIsinf(object):
# Fixme, wrong place, isinf now ufunc
def test_goodvalues(self):
@@ -331,7 +331,7 @@
assert_all(np.isinf(np.array((0.,))/0.) == 0)
-class TestIsposinf(TestCase):
+class TestIsposinf(object):
def test_generic(self):
with np.errstate(divide='ignore', invalid='ignore'):
@@ -341,7 +341,7 @@
assert_(vals[2] == 1)
-class TestIsneginf(TestCase):
+class TestIsneginf(object):
def test_generic(self):
with np.errstate(divide='ignore', invalid='ignore'):
@@ -351,7 +351,7 @@
assert_(vals[2] == 0)
-class TestNanToNum(TestCase):
+class TestNanToNum(object):
def test_generic(self):
with np.errstate(divide='ignore', invalid='ignore'):
@@ -402,7 +402,7 @@
#assert_all(vals.real < -1e10) and assert_all(np.isfinite(vals))
-class TestRealIfClose(TestCase):
+class TestRealIfClose(object):
def test_basic(self):
a = np.random.rand(10)
@@ -415,7 +415,7 @@
assert_all(isrealobj(b))
-class TestArrayConversion(TestCase):
+class TestArrayConversion(object):
def test_asfarray(self):
a = asfarray(np.array([1, 2, 3]))
diff --git a/numpy/lib/tests/test_ufunclike.py b/numpy/lib/tests/test_ufunclike.py
index 0b15254..128ce37 100644
--- a/numpy/lib/tests/test_ufunclike.py
+++ b/numpy/lib/tests/test_ufunclike.py
@@ -4,12 +4,11 @@
import numpy.core as nx
import numpy.lib.ufunclike as ufl
from numpy.testing import (
- run_module_suite, TestCase, assert_, assert_equal, assert_array_equal,
- assert_warns
+ run_module_suite, assert_, assert_equal, assert_array_equal, assert_warns
)
-class TestUfunclike(TestCase):
+class TestUfunclike(object):
def test_isposinf(self):
a = nx.array([nx.inf, -nx.inf, nx.nan, 0.0, 3.0, -3.0])
diff --git a/numpy/linalg/tests/test_build.py b/numpy/linalg/tests/test_build.py
index a91f976..b46a72c 100644
--- a/numpy/linalg/tests/test_build.py
+++ b/numpy/linalg/tests/test_build.py
@@ -5,7 +5,7 @@
import re
from numpy.linalg import lapack_lite
-from numpy.testing import TestCase, dec, run_module_suite
+from numpy.testing import run_module_suite, assert_, dec
class FindDependenciesLdd(object):
@@ -40,7 +40,7 @@
return founds
-class TestF77Mismatch(TestCase):
+class TestF77Mismatch(object):
@dec.skipif(not(sys.platform[:5] == 'linux'),
"Skipping fortran compiler mismatch on non Linux platform")
@@ -48,7 +48,7 @@
f = FindDependenciesLdd()
deps = f.grep_dependencies(lapack_lite.__file__,
[b'libg2c', b'libgfortran'])
- self.assertFalse(len(deps) > 1,
+ assert_(len(deps) <= 1,
"""Both g77 and gfortran runtimes linked in lapack_lite ! This is likely to
cause random crashes and wrong results. See numpy INSTALL.txt for more
information.""")
diff --git a/numpy/linalg/tests/test_regression.py b/numpy/linalg/tests/test_regression.py
index d2080b7..558abca 100644
--- a/numpy/linalg/tests/test_regression.py
+++ b/numpy/linalg/tests/test_regression.py
@@ -7,7 +7,7 @@
import numpy as np
from numpy import linalg, arange, float64, array, dot, transpose
from numpy.testing import (
- TestCase, run_module_suite, assert_equal, assert_array_equal,
+ run_module_suite, assert_, assert_raises, assert_equal, assert_array_equal,
assert_array_almost_equal, assert_array_less
)
@@ -15,7 +15,7 @@
rlevel = 1
-class TestRegression(TestCase):
+class TestRegression(object):
def test_eig_build(self, level=rlevel):
# Ticket #652
@@ -64,7 +64,7 @@
def test_norm_vector_badarg(self):
# Regression for #786: Froebenius norm for vectors raises
# TypeError.
- self.assertRaises(ValueError, linalg.norm, array([1., 2., 3.]), 'fro')
+ assert_raises(ValueError, linalg.norm, array([1., 2., 3.]), 'fro')
def test_lapack_endian(self):
# For bug #1482
@@ -98,47 +98,47 @@
norm = linalg.norm(testvector)
assert_array_equal(norm, [0, 1])
- self.assertEqual(norm.dtype, np.dtype('float64'))
+ assert_(norm.dtype == np.dtype('float64'))
norm = linalg.norm(testvector, ord=1)
assert_array_equal(norm, [0, 1])
- self.assertNotEqual(norm.dtype, np.dtype('float64'))
+ assert_(norm.dtype != np.dtype('float64'))
norm = linalg.norm(testvector, ord=2)
assert_array_equal(norm, [0, 1])
- self.assertEqual(norm.dtype, np.dtype('float64'))
+ assert_(norm.dtype == np.dtype('float64'))
- self.assertRaises(ValueError, linalg.norm, testvector, ord='fro')
- self.assertRaises(ValueError, linalg.norm, testvector, ord='nuc')
- self.assertRaises(ValueError, linalg.norm, testvector, ord=np.inf)
- self.assertRaises(ValueError, linalg.norm, testvector, ord=-np.inf)
+ assert_raises(ValueError, linalg.norm, testvector, ord='fro')
+ assert_raises(ValueError, linalg.norm, testvector, ord='nuc')
+ assert_raises(ValueError, linalg.norm, testvector, ord=np.inf)
+ assert_raises(ValueError, linalg.norm, testvector, ord=-np.inf)
with warnings.catch_warnings():
warnings.simplefilter("error", DeprecationWarning)
- self.assertRaises((AttributeError, DeprecationWarning),
+ assert_raises((AttributeError, DeprecationWarning),
linalg.norm, testvector, ord=0)
- self.assertRaises(ValueError, linalg.norm, testvector, ord=-1)
- self.assertRaises(ValueError, linalg.norm, testvector, ord=-2)
+ assert_raises(ValueError, linalg.norm, testvector, ord=-1)
+ assert_raises(ValueError, linalg.norm, testvector, ord=-2)
testmatrix = np.array([[np.array([0, 1]), 0, 0],
[0, 0, 0]], dtype=object)
norm = linalg.norm(testmatrix)
assert_array_equal(norm, [0, 1])
- self.assertEqual(norm.dtype, np.dtype('float64'))
+ assert_(norm.dtype == np.dtype('float64'))
norm = linalg.norm(testmatrix, ord='fro')
assert_array_equal(norm, [0, 1])
- self.assertEqual(norm.dtype, np.dtype('float64'))
+ assert_(norm.dtype == np.dtype('float64'))
- self.assertRaises(TypeError, linalg.norm, testmatrix, ord='nuc')
- self.assertRaises(ValueError, linalg.norm, testmatrix, ord=np.inf)
- self.assertRaises(ValueError, linalg.norm, testmatrix, ord=-np.inf)
- self.assertRaises(ValueError, linalg.norm, testmatrix, ord=0)
- self.assertRaises(ValueError, linalg.norm, testmatrix, ord=1)
- self.assertRaises(ValueError, linalg.norm, testmatrix, ord=-1)
- self.assertRaises(TypeError, linalg.norm, testmatrix, ord=2)
- self.assertRaises(TypeError, linalg.norm, testmatrix, ord=-2)
- self.assertRaises(ValueError, linalg.norm, testmatrix, ord=3)
+ assert_raises(TypeError, linalg.norm, testmatrix, ord='nuc')
+ assert_raises(ValueError, linalg.norm, testmatrix, ord=np.inf)
+ assert_raises(ValueError, linalg.norm, testmatrix, ord=-np.inf)
+ assert_raises(ValueError, linalg.norm, testmatrix, ord=0)
+ assert_raises(ValueError, linalg.norm, testmatrix, ord=1)
+ assert_raises(ValueError, linalg.norm, testmatrix, ord=-1)
+ assert_raises(TypeError, linalg.norm, testmatrix, ord=2)
+ assert_raises(TypeError, linalg.norm, testmatrix, ord=-2)
+ assert_raises(ValueError, linalg.norm, testmatrix, ord=3)
if __name__ == '__main__':
diff --git a/numpy/ma/tests/test_core.py b/numpy/ma/tests/test_core.py
index c8bcb75..06f4df0 100644
--- a/numpy/ma/tests/test_core.py
+++ b/numpy/ma/tests/test_core.py
@@ -20,7 +20,7 @@
import numpy.core.fromnumeric as fromnumeric
import numpy.core.umath as umath
from numpy.testing import (
- TestCase, run_module_suite, assert_raises, assert_warns, suppress_warnings
+ run_module_suite, assert_raises, assert_warns, suppress_warnings
)
from numpy import ndarray
from numpy.compat import asbytes, asbytes_nested
@@ -56,10 +56,10 @@
"setting an item on a masked array which has a shared mask will not copy")
-class TestMaskedArray(TestCase):
+class TestMaskedArray(object):
# Base test class for MaskedArrays.
- def setUp(self):
+ def setup(self):
# Base data definition.
x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
@@ -94,14 +94,14 @@
x = masked_array(0, mask=False)
assert_equal(str(x), '0')
x = array(0, mask=1)
- self.assertTrue(x.filled().dtype is x._data.dtype)
+ assert_(x.filled().dtype is x._data.dtype)
def test_basic1d(self):
# Test of basic array creation and properties in 1 dimension.
(x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
- self.assertTrue(not isMaskedArray(x))
- self.assertTrue(isMaskedArray(xm))
- self.assertTrue((xm - ym).filled(0).any())
+ assert_(not isMaskedArray(x))
+ assert_(isMaskedArray(xm))
+ assert_((xm - ym).filled(0).any())
fail_if_equal(xm.mask.astype(int), ym.mask.astype(int))
s = x.shape
assert_equal(np.shape(xm), s)
@@ -124,8 +124,8 @@
ym.shape = s
xf.shape = s
- self.assertTrue(not isMaskedArray(x))
- self.assertTrue(isMaskedArray(xm))
+ assert_(not isMaskedArray(x))
+ assert_(isMaskedArray(xm))
assert_equal(shape(xm), s)
assert_equal(xm.shape, s)
assert_equal(xm.size, reduce(lambda x, y:x * y, s))
@@ -218,7 +218,7 @@
x.mask = nomask
data = array((x, x[::-1]))
assert_equal(data, [[0, 1, 2, 3, 4], [4, 3, 2, 1, 0]])
- self.assertTrue(data.mask is nomask)
+ assert_(data.mask is nomask)
def test_creation_from_ndarray_with_padding(self):
x = np.array([('A', 0)], dtype={'names':['f0','f1'],
@@ -239,18 +239,18 @@
def test_asarray_default_order(self):
# See Issue #6646
m = np.eye(3).T
- self.assertFalse(m.flags.c_contiguous)
+ assert_(not m.flags.c_contiguous)
new_m = asarray(m)
- self.assertTrue(new_m.flags.c_contiguous)
+ assert_(new_m.flags.c_contiguous)
def test_asarray_enforce_order(self):
# See Issue #6646
m = np.eye(3).T
- self.assertFalse(m.flags.c_contiguous)
+ assert_(not m.flags.c_contiguous)
new_m = asarray(m, order='C')
- self.assertTrue(new_m.flags.c_contiguous)
+ assert_(new_m.flags.c_contiguous)
def test_fix_invalid(self):
# Checks fix_invalid.
@@ -264,8 +264,8 @@
# Test of masked element
x = arange(6)
x[1] = masked
- self.assertTrue(str(masked) == '--')
- self.assertTrue(x[1] is masked)
+ assert_(str(masked) == '--')
+ assert_(x[1] is masked)
assert_equal(filled(x[1], 0), 0)
def test_set_element_as_object(self):
@@ -274,12 +274,12 @@
x = (1, 2, 3, 4, 5)
a[0] = x
assert_equal(a[0], x)
- self.assertTrue(a[0] is x)
+ assert_(a[0] is x)
import datetime
dt = datetime.datetime.now()
a[0] = dt
- self.assertTrue(a[0] is dt)
+ assert_(a[0] is dt)
def test_indexing(self):
# Tests conversions and indexing
@@ -380,43 +380,43 @@
n = [0, 0, 1, 0, 0]
m = make_mask(n)
m2 = make_mask(m)
- self.assertTrue(m is m2)
+ assert_(m is m2)
m3 = make_mask(m, copy=1)
- self.assertTrue(m is not m3)
+ assert_(m is not m3)
x1 = np.arange(5)
y1 = array(x1, mask=m)
assert_equal(y1._data.__array_interface__, x1.__array_interface__)
- self.assertTrue(allequal(x1, y1.data))
+ assert_(allequal(x1, y1.data))
assert_equal(y1._mask.__array_interface__, m.__array_interface__)
y1a = array(y1)
- self.assertTrue(y1a._data.__array_interface__ ==
+ assert_(y1a._data.__array_interface__ ==
y1._data.__array_interface__)
- self.assertTrue(y1a.mask is y1.mask)
+ assert_(y1a.mask is y1.mask)
y2 = array(x1, mask=m3)
- self.assertTrue(y2._data.__array_interface__ == x1.__array_interface__)
- self.assertTrue(y2._mask.__array_interface__ == m3.__array_interface__)
- self.assertTrue(y2[2] is masked)
+ assert_(y2._data.__array_interface__ == x1.__array_interface__)
+ assert_(y2._mask.__array_interface__ == m3.__array_interface__)
+ assert_(y2[2] is masked)
y2[2] = 9
- self.assertTrue(y2[2] is not masked)
- self.assertTrue(y2._mask.__array_interface__ == m3.__array_interface__)
- self.assertTrue(allequal(y2.mask, 0))
+ assert_(y2[2] is not masked)
+ assert_(y2._mask.__array_interface__ == m3.__array_interface__)
+ assert_(allequal(y2.mask, 0))
y2a = array(x1, mask=m, copy=1)
- self.assertTrue(y2a._data.__array_interface__ != x1.__array_interface__)
- #self.assertTrue( y2a.mask is not m)
- self.assertTrue(y2a._mask.__array_interface__ != m.__array_interface__)
- self.assertTrue(y2a[2] is masked)
+ assert_(y2a._data.__array_interface__ != x1.__array_interface__)
+ #assert_( y2a.mask is not m)
+ assert_(y2a._mask.__array_interface__ != m.__array_interface__)
+ assert_(y2a[2] is masked)
y2a[2] = 9
- self.assertTrue(y2a[2] is not masked)
- #self.assertTrue( y2a.mask is not m)
- self.assertTrue(y2a._mask.__array_interface__ != m.__array_interface__)
- self.assertTrue(allequal(y2a.mask, 0))
+ assert_(y2a[2] is not masked)
+ #assert_( y2a.mask is not m)
+ assert_(y2a._mask.__array_interface__ != m.__array_interface__)
+ assert_(allequal(y2a.mask, 0))
y3 = array(x1 * 1.0, mask=m)
- self.assertTrue(filled(y3).dtype is (x1 * 1.0).dtype)
+ assert_(filled(y3).dtype is (x1 * 1.0).dtype)
x4 = arange(4)
x4[2] = masked
@@ -447,8 +447,8 @@
def test_copy_on_python_builtins(self):
# Tests copy works on python builtins (issue#8019)
- self.assertTrue(isMaskedArray(np.ma.copy([1,2,3])))
- self.assertTrue(isMaskedArray(np.ma.copy((1,2,3))))
+ assert_(isMaskedArray(np.ma.copy([1,2,3])))
+ assert_(isMaskedArray(np.ma.copy((1,2,3))))
def test_copy_immutable(self):
# Tests that the copy method is immutable, GitHub issue #5247
@@ -518,7 +518,7 @@
a_pickled = pickle.loads(a.dumps())
assert_equal(a_pickled._mask, a._mask)
assert_equal(a_pickled, a)
- self.assertTrue(isinstance(a_pickled._data, np.matrix))
+ assert_(isinstance(a_pickled._data, np.matrix))
def test_pickling_maskedconstant(self):
# Test pickling MaskedConstant
@@ -558,19 +558,19 @@
assert_equal(1.0, float(array(1)))
assert_equal(1, int(array([[[1]]])))
assert_equal(1.0, float(array([[1]])))
- self.assertRaises(TypeError, float, array([1, 1]))
+ assert_raises(TypeError, float, array([1, 1]))
with suppress_warnings() as sup:
sup.filter(UserWarning, 'Warning: converting a masked element')
assert_(np.isnan(float(array([1], mask=[1]))))
a = array([1, 2, 3], mask=[1, 0, 0])
- self.assertRaises(TypeError, lambda: float(a))
+ assert_raises(TypeError, lambda: float(a))
assert_equal(float(a[-1]), 3.)
- self.assertTrue(np.isnan(float(a[0])))
- self.assertRaises(TypeError, int, a)
+ assert_(np.isnan(float(a[0])))
+ assert_raises(TypeError, int, a)
assert_equal(int(a[-1]), 3)
- self.assertRaises(MAError, lambda:int(a[0]))
+ assert_raises(MAError, lambda:int(a[0]))
def test_oddfeatures_1(self):
# Test of other odd features
@@ -679,8 +679,8 @@
a = array(np.array([(0, 1, 2), (4, 5, 6)], order='F'),
mask=np.array([(0, 0, 1), (1, 0, 0)], order='F'),
order='F') # this is currently ignored
- self.assertTrue(a.flags['F_CONTIGUOUS'])
- self.assertTrue(a.filled(0).flags['F_CONTIGUOUS'])
+ assert_(a.flags['F_CONTIGUOUS'])
+ assert_(a.filled(0).flags['F_CONTIGUOUS'])
def test_optinfo_propagation(self):
# Checks that _optinfo dictionary isn't back-propagated
@@ -768,14 +768,14 @@
dtype=ndtype)
# w/o mask
f = a[0]
- self.assertTrue(isinstance(f, mvoid))
+ assert_(isinstance(f, mvoid))
assert_equal((f[0], f['a']), (1, 1))
assert_equal(f['b'], 2)
# w/ mask
f = a[1]
- self.assertTrue(isinstance(f, mvoid))
- self.assertTrue(f[0] is masked)
- self.assertTrue(f['a'] is masked)
+ assert_(isinstance(f, mvoid))
+ assert_(f[0] is masked)
+ assert_(f['a'] is masked)
assert_equal(f[1], 4)
# exotic dtype
@@ -862,10 +862,10 @@
assert_(mx2[0] == 0.)
-class TestMaskedArrayArithmetic(TestCase):
+class TestMaskedArrayArithmetic(object):
# Base test class for MaskedArrays.
- def setUp(self):
+ def setup(self):
# Base data definition.
x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
@@ -882,7 +882,7 @@
self.err_status = np.geterr()
np.seterr(divide='ignore', invalid='ignore')
- def tearDown(self):
+ def teardown(self):
np.seterr(**self.err_status)
def test_basic_arithmetic(self):
@@ -942,8 +942,8 @@
# Tests mixed arithmetics.
na = np.array([1])
ma = array([1])
- self.assertTrue(isinstance(na + ma, MaskedArray))
- self.assertTrue(isinstance(ma + na, MaskedArray))
+ assert_(isinstance(na + ma, MaskedArray))
+ assert_(isinstance(ma + na, MaskedArray))
def test_limits_arithmetic(self):
tiny = np.finfo(float).tiny
@@ -955,11 +955,11 @@
# Tests some scalar arithmetics on MaskedArrays.
# Masked singleton should remain masked no matter what
xm = array(0, mask=1)
- self.assertTrue((1 / array(0)).mask)
- self.assertTrue((1 + xm).mask)
- self.assertTrue((-xm).mask)
- self.assertTrue(maximum(xm, xm).mask)
- self.assertTrue(minimum(xm, xm).mask)
+ assert_((1 / array(0)).mask)
+ assert_((1 + xm).mask)
+ assert_((-xm).mask)
+ assert_(maximum(xm, xm).mask)
+ assert_(minimum(xm, xm).mask)
def test_masked_singleton_equality(self):
# Tests (in)equality on masked singleton
@@ -1031,7 +1031,7 @@
ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0])
res = count(ott)
- self.assertTrue(res.dtype.type is np.intp)
+ assert_(res.dtype.type is np.intp)
assert_equal(3, res)
ott = ott.reshape((2, 2))
@@ -1082,19 +1082,19 @@
def test_minimummaximum_func(self):
a = np.ones((2, 2))
aminimum = minimum(a, a)
- self.assertTrue(isinstance(aminimum, MaskedArray))
+ assert_(isinstance(aminimum, MaskedArray))
assert_equal(aminimum, np.minimum(a, a))
aminimum = minimum.outer(a, a)
- self.assertTrue(isinstance(aminimum, MaskedArray))
+ assert_(isinstance(aminimum, MaskedArray))
assert_equal(aminimum, np.minimum.outer(a, a))
amaximum = maximum(a, a)
- self.assertTrue(isinstance(amaximum, MaskedArray))
+ assert_(isinstance(amaximum, MaskedArray))
assert_equal(amaximum, np.maximum(a, a))
amaximum = maximum.outer(a, a)
- self.assertTrue(isinstance(amaximum, MaskedArray))
+ assert_(isinstance(amaximum, MaskedArray))
assert_equal(amaximum, np.maximum.outer(a, a))
def test_minmax_reduce(self):
@@ -1120,33 +1120,33 @@
pass
nout = np.empty((4,), dtype=float)
result = npfunc(xm, axis=0, out=nout)
- self.assertTrue(result is nout)
+ assert_(result is nout)
# Use the ma version
nout.fill(-999)
result = mafunc(xm, axis=0, out=nout)
- self.assertTrue(result is nout)
+ assert_(result is nout)
def test_minmax_methods(self):
# Additional tests on max/min
(_, _, _, _, _, xm, _, _, _, _) = self.d
xm.shape = (xm.size,)
assert_equal(xm.max(), 10)
- self.assertTrue(xm[0].max() is masked)
- self.assertTrue(xm[0].max(0) is masked)
- self.assertTrue(xm[0].max(-1) is masked)
+ assert_(xm[0].max() is masked)
+ assert_(xm[0].max(0) is masked)
+ assert_(xm[0].max(-1) is masked)
assert_equal(xm.min(), -10.)
- self.assertTrue(xm[0].min() is masked)
- self.assertTrue(xm[0].min(0) is masked)
- self.assertTrue(xm[0].min(-1) is masked)
+ assert_(xm[0].min() is masked)
+ assert_(xm[0].min(0) is masked)
+ assert_(xm[0].min(-1) is masked)
assert_equal(xm.ptp(), 20.)
- self.assertTrue(xm[0].ptp() is masked)
- self.assertTrue(xm[0].ptp(0) is masked)
- self.assertTrue(xm[0].ptp(-1) is masked)
+ assert_(xm[0].ptp() is masked)
+ assert_(xm[0].ptp(0) is masked)
+ assert_(xm[0].ptp(-1) is masked)
x = array([1, 2, 3], mask=True)
- self.assertTrue(x.min() is masked)
- self.assertTrue(x.max() is masked)
- self.assertTrue(x.ptp() is masked)
+ assert_(x.min() is masked)
+ assert_(x.max() is masked)
+ assert_(x.ptp() is masked)
def test_addsumprod(self):
# Tests add, sum, product.
@@ -1503,7 +1503,7 @@
assert_equal(a.mask, [0, 0, 0, 0, 1])
-class TestMaskedArrayAttributes(TestCase):
+class TestMaskedArrayAttributes(object):
def test_keepmask(self):
# Tests the keep mask flag
@@ -1531,8 +1531,8 @@
assert_equal(xh._data, [0, 10, 2, 3, 4])
assert_equal(xs._data, [0, 10, 2, 3, 40])
assert_equal(xs.mask, [0, 0, 0, 1, 0])
- self.assertTrue(xh._hardmask)
- self.assertTrue(not xs._hardmask)
+ assert_(xh._hardmask)
+ assert_(not xs._hardmask)
xh[1:4] = [10, 20, 30]
xs[1:4] = [10, 20, 30]
assert_equal(xh._data, [0, 10, 20, 3, 4])
@@ -1622,7 +1622,7 @@
test = masked_array(np.matrix([[1, 2, 3]]), mask=[0, 0, 1])
assert_equal(test.flat[1], 2)
assert_equal(test.flat[2], masked)
- self.assertTrue(np.all(test.flat[0:2] == test[0, 0:2]))
+ assert_(np.all(test.flat[0:2] == test[0, 0:2]))
# Test flat on masked_matrices
test = masked_array(np.matrix([[1, 2, 3]]), mask=[0, 0, 1])
test.flat = masked_array([3, 2, 1], mask=[1, 0, 0])
@@ -1696,7 +1696,7 @@
assert_equal(m._mask, np.ma.nomask)
-class TestFillingValues(TestCase):
+class TestFillingValues(object):
def test_check_on_scalar(self):
# Test _check_fill_value set to valid and invalid values
@@ -1711,8 +1711,8 @@
assert_equal(fval, b"0")
fval = _check_fill_value(None, "|S3")
assert_equal(fval, default_fill_value(b"camelot!"))
- self.assertRaises(TypeError, _check_fill_value, 1e+20, int)
- self.assertRaises(TypeError, _check_fill_value, 'stuff', int)
+ assert_raises(TypeError, _check_fill_value, 1e+20, int)
+ assert_raises(TypeError, _check_fill_value, 'stuff', int)
def test_check_on_fields(self):
# Tests _check_fill_value with records
@@ -1720,18 +1720,18 @@
ndtype = [('a', int), ('b', float), ('c', "|S3")]
# A check on a list should return a single record
fval = _check_fill_value([-999, -12345678.9, "???"], ndtype)
- self.assertTrue(isinstance(fval, ndarray))
+ assert_(isinstance(fval, ndarray))
assert_equal(fval.item(), [-999, -12345678.9, b"???"])
# A check on None should output the defaults
fval = _check_fill_value(None, ndtype)
- self.assertTrue(isinstance(fval, ndarray))
+ assert_(isinstance(fval, ndarray))
assert_equal(fval.item(), [default_fill_value(0),
default_fill_value(0.),
asbytes(default_fill_value("0"))])
#.....Using a structured type as fill_value should work
fill_val = np.array((-999, -12345678.9, "???"), dtype=ndtype)
fval = _check_fill_value(fill_val, ndtype)
- self.assertTrue(isinstance(fval, ndarray))
+ assert_(isinstance(fval, ndarray))
assert_equal(fval.item(), [-999, -12345678.9, b"???"])
#.....Using a flexible type w/ a different type shouldn't matter
@@ -1744,25 +1744,25 @@
# suppress deprecation warning in 1.12 (remove in 1.13)
with assert_warns(FutureWarning):
fval = _check_fill_value(fill_val, ndtype)
- self.assertTrue(isinstance(fval, ndarray))
+ assert_(isinstance(fval, ndarray))
assert_equal(fval.item(), [-999, -12345678.9, b"???"])
#.....Using an object-array shouldn't matter either
fill_val = np.ndarray(shape=(1,), dtype=object)
fill_val[0] = (-999, -12345678.9, b"???")
fval = _check_fill_value(fill_val, object)
- self.assertTrue(isinstance(fval, ndarray))
+ assert_(isinstance(fval, ndarray))
assert_equal(fval.item(), [-999, -12345678.9, b"???"])
# NOTE: This test was never run properly as "fill_value" rather than
# "fill_val" was assigned. Written properly, it fails.
#fill_val = np.array((-999, -12345678.9, "???"))
#fval = _check_fill_value(fill_val, ndtype)
- #self.assertTrue(isinstance(fval, ndarray))
+ #assert_(isinstance(fval, ndarray))
#assert_equal(fval.item(), [-999, -12345678.9, b"???"])
#.....One-field-only flexible type should work as well
ndtype = [("a", int)]
fval = _check_fill_value(-999999999, ndtype)
- self.assertTrue(isinstance(fval, ndarray))
+ assert_(isinstance(fval, ndarray))
assert_equal(fval.item(), (-999999999,))
def test_fillvalue_conversion(self):
@@ -2027,17 +2027,17 @@
assert_equal(a["f1"].fill_value, default_fill_value("eggs"))
-class TestUfuncs(TestCase):
+class TestUfuncs(object):
# Test class for the application of ufuncs on MaskedArrays.
- def setUp(self):
+ def setup(self):
# Base data definition.
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),)
self.err_status = np.geterr()
np.seterr(divide='ignore', invalid='ignore')
- def tearDown(self):
+ def teardown(self):
np.seterr(**self.err_status)
def test_testUfuncRegression(self):
@@ -2073,8 +2073,8 @@
def test_reduce(self):
# Tests reduce on MaskedArrays.
a = self.d[0]
- self.assertTrue(not alltrue(a, axis=0))
- self.assertTrue(sometrue(a, axis=0))
+ assert_(not alltrue(a, axis=0))
+ assert_(sometrue(a, axis=0))
assert_equal(sum(a[:3], axis=0), 0)
assert_equal(product(a, axis=0), 0)
assert_equal(add.reduce(a), pi)
@@ -2087,8 +2087,8 @@
assert_equal(amask.min(), 5)
assert_equal(amask.max(0), a.max(0))
assert_equal(amask.min(0), [5, 6, 7, 8])
- self.assertTrue(amask.max(1)[0].mask)
- self.assertTrue(amask.min(1)[0].mask)
+ assert_(amask.max(1)[0].mask)
+ assert_(amask.min(1)[0].mask)
def test_ndarray_mask(self):
# Check that the mask of the result is a ndarray (not a MaskedArray...)
@@ -2098,14 +2098,14 @@
mask=[1, 0, 0, 0, 1])
assert_equal(test, control)
assert_equal(test.mask, control.mask)
- self.assertTrue(not isinstance(test.mask, MaskedArray))
+ assert_(not isinstance(test.mask, MaskedArray))
def test_treatment_of_NotImplemented(self):
# Check that NotImplemented is returned at appropriate places
a = masked_array([1., 2.], mask=[1, 0])
- self.assertRaises(TypeError, operator.mul, a, "abc")
- self.assertRaises(TypeError, operator.truediv, a, "abc")
+ assert_raises(TypeError, operator.mul, a, "abc")
+ assert_raises(TypeError, operator.truediv, a, "abc")
class MyClass(object):
__array_priority__ = a.__array_priority__ + 1
@@ -2171,10 +2171,10 @@
# also check that allclose uses ma ufuncs, to avoid warning
allclose(m, 0.5)
-class TestMaskedArrayInPlaceArithmetics(TestCase):
+class TestMaskedArrayInPlaceArithmetics(object):
# Test MaskedArray Arithmetics
- def setUp(self):
+ def setup(self):
x = arange(10)
y = arange(10)
xm = arange(10)
@@ -2673,9 +2673,9 @@
assert_equal(len(w), 0, "Failed on type=%s." % t)
-class TestMaskedArrayMethods(TestCase):
+class TestMaskedArrayMethods(object):
# Test class for miscellaneous MaskedArrays methods.
- def setUp(self):
+ def setup(self):
# Base data definition.
x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,
8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
@@ -2729,25 +2729,25 @@
# Tests allclose on arrays
a = np.random.rand(10)
b = a + np.random.rand(10) * 1e-8
- self.assertTrue(allclose(a, b))
+ assert_(allclose(a, b))
# Test allclose w/ infs
a[0] = np.inf
- self.assertTrue(not allclose(a, b))
+ assert_(not allclose(a, b))
b[0] = np.inf
- self.assertTrue(allclose(a, b))
+ assert_(allclose(a, b))
# Test allclose w/ masked
a = masked_array(a)
a[-1] = masked
- self.assertTrue(allclose(a, b, masked_equal=True))
- self.assertTrue(not allclose(a, b, masked_equal=False))
+ assert_(allclose(a, b, masked_equal=True))
+ assert_(not allclose(a, b, masked_equal=False))
# Test comparison w/ scalar
a *= 1e-8
a[0] = 0
- self.assertTrue(allclose(a, 0, masked_equal=True))
+ assert_(allclose(a, 0, masked_equal=True))
# Test that the function works for MIN_INT integer typed arrays
a = masked_array([np.iinfo(np.int_).min], dtype=np.int_)
- self.assertTrue(allclose(a, a))
+ assert_(allclose(a, a))
def test_allany(self):
# Checks the any/all methods/functions.
@@ -2761,15 +2761,15 @@
mxbig = (mx > 0.5)
mxsmall = (mx < 0.5)
- self.assertFalse(mxbig.all())
- self.assertTrue(mxbig.any())
+ assert_(not mxbig.all())
+ assert_(mxbig.any())
assert_equal(mxbig.all(0), [False, False, True])
assert_equal(mxbig.all(1), [False, False, True])
assert_equal(mxbig.any(0), [False, False, True])
assert_equal(mxbig.any(1), [True, True, True])
- self.assertFalse(mxsmall.all())
- self.assertTrue(mxsmall.any())
+ assert_(not mxsmall.all())
+ assert_(mxsmall.any())
assert_equal(mxsmall.all(0), [True, True, False])
assert_equal(mxsmall.all(1), [False, False, False])
assert_equal(mxsmall.any(0), [True, True, False])
@@ -2787,15 +2787,15 @@
mXbig = (mX > 0.5)
mXsmall = (mX < 0.5)
- self.assertFalse(mXbig.all())
- self.assertTrue(mXbig.any())
+ assert_(not mXbig.all())
+ assert_(mXbig.any())
assert_equal(mXbig.all(0), np.matrix([False, False, True]))
assert_equal(mXbig.all(1), np.matrix([False, False, True]).T)
assert_equal(mXbig.any(0), np.matrix([False, False, True]))
assert_equal(mXbig.any(1), np.matrix([True, True, True]).T)
- self.assertFalse(mXsmall.all())
- self.assertTrue(mXsmall.any())
+ assert_(not mXsmall.all())
+ assert_(mXsmall.any())
assert_equal(mXsmall.all(0), np.matrix([True, True, False]))
assert_equal(mXsmall.all(1), np.matrix([False, False, False]).T)
assert_equal(mXsmall.any(0), np.matrix([True, True, False]))
@@ -2806,18 +2806,18 @@
store = empty((), dtype=bool)
full = array([1, 2, 3], mask=True)
- self.assertTrue(full.all() is masked)
+ assert_(full.all() is masked)
full.all(out=store)
- self.assertTrue(store)
- self.assertTrue(store._mask, True)
- self.assertTrue(store is not masked)
+ assert_(store)
+ assert_(store._mask, True)
+ assert_(store is not masked)
store = empty((), dtype=bool)
- self.assertTrue(full.any() is masked)
+ assert_(full.any() is masked)
full.any(out=store)
- self.assertTrue(not store)
- self.assertTrue(store._mask, True)
- self.assertTrue(store is not masked)
+ assert_(not store)
+ assert_(store._mask, True)
+ assert_(store is not masked)
def test_argmax_argmin(self):
# Tests argmin & argmax on MaskedArrays.
@@ -2902,7 +2902,7 @@
a = array(np.matrix([1, 2, 3, 4]), mask=[0, 0, 0, 0])
b = a.compressed()
assert_equal(b, a)
- self.assertTrue(isinstance(b, np.matrix))
+ assert_(isinstance(b, np.matrix))
a[0, 0] = masked
b = a.compressed()
assert_equal(b, [[2, 3, 4]])
@@ -2936,11 +2936,11 @@
n = [0, 0, 0, 1, 1]
m = make_mask(n)
x = array(d, mask=m)
- self.assertTrue(x[3] is masked)
- self.assertTrue(x[4] is masked)
+ assert_(x[3] is masked)
+ assert_(x[4] is masked)
x[[1, 4]] = [10, 40]
- self.assertTrue(x[3] is masked)
- self.assertTrue(x[4] is not masked)
+ assert_(x[3] is masked)
+ assert_(x[4] is not masked)
assert_equal(x, [0, 10, 2, -1, 40])
x = masked_array(arange(10), mask=[1, 0, 0, 0, 0] * 2)
@@ -2966,12 +2966,12 @@
z = array([3., -1.], mask=[False, True])
x.put([1, 2], z)
- self.assertTrue(x[0] is not masked)
+ assert_(x[0] is not masked)
assert_equal(x[0], 0)
- self.assertTrue(x[1] is not masked)
+ assert_(x[1] is not masked)
assert_equal(x[1], 3)
- self.assertTrue(x[2] is masked)
- self.assertTrue(x[3] is not masked)
+ assert_(x[2] is masked)
+ assert_(x[3] is not masked)
assert_equal(x[3], 0)
def test_put_hardmask(self):
@@ -3072,7 +3072,7 @@
x = [1, 4, 2, 3]
sortedx = sort(x)
- self.assertTrue(not isinstance(sorted, MaskedArray))
+ assert_(not isinstance(sorted, MaskedArray))
x = array([0, 1, -1, -2, 2], mask=nomask, dtype=np.int8)
sortedx = sort(x, endwith=False)
@@ -3186,7 +3186,7 @@
assert_equal(data.squeeze(), [1, 2, 3])
assert_equal(data.squeeze()._mask, [1, 1, 1])
data = masked_array([[1]], mask=True)
- self.assertTrue(data.squeeze() is masked)
+ assert_(data.squeeze() is masked)
def test_swapaxes(self):
# Tests swapaxes on MaskedArrays.
@@ -3220,8 +3220,8 @@
masked_array([[10, 20], [10, 20]], [[0, 1], [0, 1]]))
# assert_equal crashes when passed np.ma.mask
- self.assertIs(x[1], np.ma.masked)
- self.assertIs(x.take(1), np.ma.masked)
+ assert_(x[1] is np.ma.masked)
+ assert_(x.take(1) is np.ma.masked)
x = array([[10, 20, 30], [40, 50, 60]], mask=[[0, 0, 1], [1, 0, 0, ]])
assert_equal(x.take([0, 2], axis=1),
@@ -3265,8 +3265,8 @@
x = array(np.arange(12))
x[[1, -2]] = masked
xlist = x.tolist()
- self.assertTrue(xlist[1] is None)
- self.assertTrue(xlist[-2] is None)
+ assert_(xlist[1] is None)
+ assert_(xlist[-2] is None)
# ... on 2D
x.shape = (3, 4)
xlist = x.tolist()
@@ -3370,9 +3370,9 @@
assert_equal(MaskedArray.cumsum(marray.T, 0), control.cumsum(0))
-class TestMaskedArrayMathMethods(TestCase):
+class TestMaskedArrayMathMethods(object):
- def setUp(self):
+ def setup(self):
# Base data definition.
x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,
8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
@@ -3431,12 +3431,12 @@
output.fill(-9999)
result = npfunc(xm, axis=0, out=output)
# ... the result should be the given output
- self.assertTrue(result is output)
+ assert_(result is output)
assert_equal(result, xmmeth(axis=0, out=output))
output = empty((3, 4), dtype=int)
result = xmmeth(axis=0, out=output)
- self.assertTrue(result is output)
+ assert_(result is output)
def test_ptp(self):
# Tests ptp on MaskedArrays.
@@ -3568,31 +3568,31 @@
x = array(arange(10), mask=True)
for methodname in ('var', 'std'):
method = getattr(x, methodname)
- self.assertTrue(method() is masked)
- self.assertTrue(method(0) is masked)
- self.assertTrue(method(-1) is masked)
+ assert_(method() is masked)
+ assert_(method(0) is masked)
+ assert_(method(-1) is masked)
# Using a masked array as explicit output
method(out=mout)
- self.assertTrue(mout is not masked)
+ assert_(mout is not masked)
assert_equal(mout.mask, True)
# Using a ndarray as explicit output
method(out=nout)
- self.assertTrue(np.isnan(nout))
+ assert_(np.isnan(nout))
x = array(arange(10), mask=True)
x[-1] = 9
for methodname in ('var', 'std'):
method = getattr(x, methodname)
- self.assertTrue(method(ddof=1) is masked)
- self.assertTrue(method(0, ddof=1) is masked)
- self.assertTrue(method(-1, ddof=1) is masked)
+ assert_(method(ddof=1) is masked)
+ assert_(method(0, ddof=1) is masked)
+ assert_(method(-1, ddof=1) is masked)
# Using a masked array as explicit output
method(out=mout, ddof=1)
- self.assertTrue(mout is not masked)
+ assert_(mout is not masked)
assert_equal(mout.mask, True)
# Using a ndarray as explicit output
method(out=nout, ddof=1)
- self.assertTrue(np.isnan(nout))
+ assert_(np.isnan(nout))
def test_varstd_ddof(self):
a = array([[1, 1, 0], [1, 1, 0]], mask=[[0, 0, 1], [0, 0, 1]])
@@ -3641,9 +3641,9 @@
assert_equal(a.max(1), [3, 6])
-class TestMaskedArrayMathMethodsComplex(TestCase):
+class TestMaskedArrayMathMethodsComplex(object):
# Test class for miscellaneous MaskedArrays methods.
- def setUp(self):
+ def setup(self):
# Base data definition.
x = np.array([8.375j, 7.545j, 8.828j, 8.5j, 1.757j, 5.928,
8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
@@ -3694,10 +3694,10 @@
mX[:, k].compressed().std())
-class TestMaskedArrayFunctions(TestCase):
+class TestMaskedArrayFunctions(object):
# Test class for miscellaneous functions.
- def setUp(self):
+ def setup(self):
x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
@@ -3821,12 +3821,12 @@
output.fill(-9999)
result = np.round(xm, decimals=2, out=output)
# ... the result should be the given output
- self.assertTrue(result is output)
+ assert_(result is output)
assert_equal(result, xm.round(decimals=2, out=output))
output = empty((3, 4), dtype=float)
result = xm.round(decimals=2, out=output)
- self.assertTrue(result is output)
+ assert_(result is output)
def test_round_with_scalar(self):
# Testing round with scalar/zero dimension input
@@ -3855,13 +3855,13 @@
def test_identity(self):
a = identity(5)
- self.assertTrue(isinstance(a, MaskedArray))
+ assert_(isinstance(a, MaskedArray))
assert_equal(a, np.identity(5))
def test_power(self):
x = -1.1
assert_almost_equal(power(x, 2.), 1.21)
- self.assertTrue(power(x, masked) is masked)
+ assert_(power(x, masked) is masked)
x = array([-1.1, -1.1, 1.1, 1.1, 0.])
b = array([0.5, 2., 0.5, 2., -1.], mask=[0, 0, 0, 0, 1])
y = power(x, b)
@@ -4069,7 +4069,7 @@
store = empty(4, dtype=int)
chosen = choose([2, 3, 1, 0], choices, out=store)
assert_equal(store, array([20, 31, 12, 3]))
- self.assertTrue(store is chosen)
+ assert_(store is chosen)
# Check with some masked indices + out
store = empty(4, dtype=int)
indices_ = array([2, 3, 1, 0], mask=[1, 0, 0, 1])
@@ -4090,25 +4090,25 @@
# Try the default
b = a.reshape((5, 2))
assert_equal(b.shape, (5, 2))
- self.assertTrue(b.flags['C'])
+ assert_(b.flags['C'])
# Try w/ arguments as list instead of tuple
b = a.reshape(5, 2)
assert_equal(b.shape, (5, 2))
- self.assertTrue(b.flags['C'])
+ assert_(b.flags['C'])
# Try w/ order
b = a.reshape((5, 2), order='F')
assert_equal(b.shape, (5, 2))
- self.assertTrue(b.flags['F'])
+ assert_(b.flags['F'])
# Try w/ order
b = a.reshape(5, 2, order='F')
assert_equal(b.shape, (5, 2))
- self.assertTrue(b.flags['F'])
+ assert_(b.flags['F'])
c = np.reshape(a, (2, 5))
- self.assertTrue(isinstance(c, MaskedArray))
+ assert_(isinstance(c, MaskedArray))
assert_equal(c.shape, (2, 5))
- self.assertTrue(c[0, 0] is masked)
- self.assertTrue(c.flags['C'])
+ assert_(c[0, 0] is masked)
+ assert_(c.flags['C'])
def test_make_mask_descr(self):
# Flexible
@@ -4331,9 +4331,9 @@
assert_equal(test, masked_equal([-1, -1, -1, -1, -1], -1))
-class TestMaskedFields(TestCase):
+class TestMaskedFields(object):
- def setUp(self):
+ def setup(self):
ilist = [1, 2, 3, 4, 5]
flist = [1.1, 2.2, 3.3, 4.4, 5.5]
slist = ['one', 'two', 'three', 'four', 'five']
@@ -4432,7 +4432,7 @@
test = a.view((float, 2), np.matrix)
assert_equal(test, data)
- self.assertTrue(isinstance(test, np.matrix))
+ assert_(isinstance(test, np.matrix))
def test_getitem(self):
ndtype = [('a', float), ('b', float)]
@@ -4497,7 +4497,7 @@
assert_equal(len(rec), len(self.data['ddtype']))
-class TestMaskedObjectArray(TestCase):
+class TestMaskedObjectArray(object):
def test_getitem(self):
arr = np.ma.array([None, None])
@@ -4545,9 +4545,9 @@
assert_(arr[0] is np.ma.masked)
-class TestMaskedView(TestCase):
+class TestMaskedView(object):
- def setUp(self):
+ def setup(self):
iterator = list(zip(np.arange(10), np.random.rand(10)))
data = np.array(iterator)
a = array(iterator, dtype=[('a', float), ('b', float)])
@@ -4558,14 +4558,14 @@
def test_view_to_nothing(self):
(data, a, controlmask) = self.data
test = a.view()
- self.assertTrue(isinstance(test, MaskedArray))
+ assert_(isinstance(test, MaskedArray))
assert_equal(test._data, a._data)
assert_equal(test._mask, a._mask)
def test_view_to_type(self):
(data, a, controlmask) = self.data
test = a.view(np.ndarray)
- self.assertTrue(not isinstance(test, MaskedArray))
+ assert_(not isinstance(test, MaskedArray))
assert_equal(test, a._data)
assert_equal_records(test, data.view(a.dtype).squeeze())
@@ -4573,7 +4573,7 @@
(data, a, controlmask) = self.data
# View globally
test = a.view(float)
- self.assertTrue(isinstance(test, MaskedArray))
+ assert_(isinstance(test, MaskedArray))
assert_equal(test, data.ravel())
assert_equal(test.mask, controlmask)
@@ -4586,13 +4586,13 @@
assert_equal(test['B'], a['b'])
test = a[0].view([('A', float), ('B', float)])
- self.assertTrue(isinstance(test, MaskedArray))
+ assert_(isinstance(test, MaskedArray))
assert_equal(test.mask.dtype.names, ('A', 'B'))
assert_equal(test['A'], a['a'][0])
assert_equal(test['B'], a['b'][0])
test = a[-1].view([('A', float), ('B', float)])
- self.assertTrue(isinstance(test, MaskedArray))
+ assert_(isinstance(test, MaskedArray))
assert_equal(test.dtype.names, ('A', 'B'))
assert_equal(test['A'], a['a'][-1])
assert_equal(test['B'], a['b'][-1])
@@ -4601,17 +4601,17 @@
(data, a, controlmask) = self.data
# View globally
test = a.view((float, 2))
- self.assertTrue(isinstance(test, MaskedArray))
+ assert_(isinstance(test, MaskedArray))
assert_equal(test, data)
assert_equal(test.mask, controlmask.reshape(-1, 2))
# View on 1 masked element
test = a[0].view((float, 2))
- self.assertTrue(isinstance(test, MaskedArray))
+ assert_(isinstance(test, MaskedArray))
assert_equal(test, data[0])
assert_equal(test.mask, (1, 0))
# View on 1 unmasked element
test = a[-1].view((float, 2))
- self.assertTrue(isinstance(test, MaskedArray))
+ assert_(isinstance(test, MaskedArray))
assert_equal(test, data[-1])
def test_view_to_dtype_and_type(self):
@@ -4619,10 +4619,10 @@
test = a.view((float, 2), np.matrix)
assert_equal(test, data)
- self.assertTrue(isinstance(test, np.matrix))
- self.assertTrue(not isinstance(test, MaskedArray))
+ assert_(isinstance(test, np.matrix))
+ assert_(not isinstance(test, MaskedArray))
-class TestOptionalArgs(TestCase):
+class TestOptionalArgs(object):
def test_ndarrayfuncs(self):
# test axis arg behaves the same as ndarray (including multiple axes)
@@ -4709,10 +4709,10 @@
assert_raises(np.AxisError, count, np.ma.array(1), axis=1)
-class TestMaskedConstant(TestCase):
+class TestMaskedConstant(object):
def _do_add_test(self, add):
# sanity check
- self.assertIs(add(np.ma.masked, 1), np.ma.masked)
+ assert_(add(np.ma.masked, 1) is np.ma.masked)
# now try with a vector
vector = np.array([1, 2, 3])
diff --git a/numpy/ma/tests/test_deprecations.py b/numpy/ma/tests/test_deprecations.py
index 24dd7cb..23c0954 100644
--- a/numpy/ma/tests/test_deprecations.py
+++ b/numpy/ma/tests/test_deprecations.py
@@ -4,11 +4,11 @@
from __future__ import division, absolute_import, print_function
import numpy as np
-from numpy.testing import TestCase, run_module_suite, assert_warns
+from numpy.testing import run_module_suite, assert_warns
from numpy.ma.testutils import assert_equal
from numpy.ma.core import MaskedArrayFutureWarning
-class TestArgsort(TestCase):
+class TestArgsort(object):
""" gh-8701 """
def _test_base(self, argsort, cls):
arr_0d = np.array(1).view(cls)
@@ -37,7 +37,7 @@
return self._test_base(np.ma.MaskedArray.argsort, np.ma.MaskedArray)
-class TestMinimumMaximum(TestCase):
+class TestMinimumMaximum(object):
def test_minimum(self):
assert_warns(DeprecationWarning, np.ma.minimum, np.ma.array([1, 2]))
diff --git a/numpy/ma/tests/test_extras.py b/numpy/ma/tests/test_extras.py
index 18198d4..897a0fd 100644
--- a/numpy/ma/tests/test_extras.py
+++ b/numpy/ma/tests/test_extras.py
@@ -14,8 +14,7 @@
import numpy as np
from numpy.testing import (
- TestCase, run_module_suite, assert_warns, suppress_warnings,
- assert_raises
+ run_module_suite, assert_warns, suppress_warnings, assert_raises,
)
from numpy.ma.testutils import (
assert_, assert_array_equal, assert_equal, assert_almost_equal
@@ -35,7 +34,7 @@
import numpy.ma.extras as mae
-class TestGeneric(TestCase):
+class TestGeneric(object):
#
def test_masked_all(self):
# Tests masked_all
@@ -140,7 +139,7 @@
assert_equal(test, None)
-class TestAverage(TestCase):
+class TestAverage(object):
# Several tests of average. Why so many ? Good point...
def test_testAverage1(self):
# Test of average.
@@ -149,7 +148,7 @@
assert_equal(2.0, average(ott, weights=[1., 1., 2., 1.]))
result, wts = average(ott, weights=[1., 1., 2., 1.], returned=1)
assert_equal(2.0, result)
- self.assertTrue(wts == 4.0)
+ assert_(wts == 4.0)
ott[:] = masked
assert_equal(average(ott, axis=0).mask, [True])
ott = array([0., 1., 2., 3.], mask=[True, False, False, False])
@@ -271,7 +270,7 @@
assert_almost_equal(wav1.imag, expected1.imag)
-class TestConcatenator(TestCase):
+class TestConcatenator(object):
# Tests for mr_, the equivalent of r_ for masked arrays.
def test_1d(self):
@@ -281,7 +280,7 @@
m = [1, 0, 0, 0, 0]
d = masked_array(b, mask=m)
c = mr_[d, 0, 0, d]
- self.assertTrue(isinstance(c, MaskedArray))
+ assert_(isinstance(c, MaskedArray))
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])
@@ -295,12 +294,12 @@
b_2 = masked_array(a_2, mask=m_2)
# append columns
d = mr_['1', b_1, b_2]
- self.assertTrue(d.shape == (5, 10))
+ assert_(d.shape == (5, 10))
assert_array_equal(d[:, :5], b_1)
assert_array_equal(d[:, 5:], b_2)
assert_array_equal(d.mask, np.r_['1', m_1, m_2])
d = mr_[b_1, b_2]
- self.assertTrue(d.shape == (10, 5))
+ assert_(d.shape == (10, 5))
assert_array_equal(d[:5,:], b_1)
assert_array_equal(d[5:,:], b_2)
assert_array_equal(d.mask, np.r_[m_1, m_2])
@@ -318,7 +317,7 @@
assert_equal(type(actual.data), type(expected.data))
-class TestNotMasked(TestCase):
+class TestNotMasked(object):
# Tests notmasked_edges and notmasked_contiguous.
def test_edges(self):
@@ -367,19 +366,19 @@
assert_equal(tmp[-3], slice(0, 4, None))
#
tmp = notmasked_contiguous(a, 0)
- self.assertTrue(len(tmp[-1]) == 1)
- self.assertTrue(tmp[-2] is None)
+ assert_(len(tmp[-1]) == 1)
+ assert_(tmp[-2] is None)
assert_equal(tmp[-3], tmp[-1])
- self.assertTrue(len(tmp[0]) == 2)
+ assert_(len(tmp[0]) == 2)
#
tmp = notmasked_contiguous(a, 1)
assert_equal(tmp[0][-1], slice(0, 4, None))
- self.assertTrue(tmp[1] is None)
+ assert_(tmp[1] is None)
assert_equal(tmp[2][-1], slice(7, 8, None))
assert_equal(tmp[2][-2], slice(0, 6, None))
-class TestCompressFunctions(TestCase):
+class TestCompressFunctions(object):
def test_compress_nd(self):
# Tests compress_nd
@@ -538,12 +537,12 @@
assert_equal(mask_rowcols(x, 1,).mask,
[[1, 1, 0], [1, 1, 0], [1, 1, 0]])
x = array(x._data, mask=[[1, 0, 0], [0, 1, 0], [0, 0, 1]])
- self.assertTrue(mask_rowcols(x).all() is masked)
- self.assertTrue(mask_rowcols(x, 0).all() is masked)
- self.assertTrue(mask_rowcols(x, 1).all() is masked)
- self.assertTrue(mask_rowcols(x).mask.all())
- self.assertTrue(mask_rowcols(x, 0).mask.all())
- self.assertTrue(mask_rowcols(x, 1).mask.all())
+ assert_(mask_rowcols(x).all() is masked)
+ assert_(mask_rowcols(x, 0).all() is masked)
+ assert_(mask_rowcols(x, 1).all() is masked)
+ assert_(mask_rowcols(x).mask.all())
+ assert_(mask_rowcols(x, 0).mask.all())
+ assert_(mask_rowcols(x, 1).mask.all())
def test_dot(self):
# Tests dot product
@@ -632,7 +631,7 @@
assert_equal(a, res)
-class TestApplyAlongAxis(TestCase):
+class TestApplyAlongAxis(object):
# Tests 2D functions
def test_3d(self):
a = arange(12.).reshape(2, 2, 3)
@@ -654,7 +653,7 @@
assert_equal(xa, [[2, 5], [8, 11]])
-class TestApplyOverAxes(TestCase):
+class TestApplyOverAxes(object):
# Tests apply_over_axes
def test_basic(self):
a = arange(24).reshape(2, 3, 4)
@@ -667,7 +666,7 @@
assert_equal(test, ctrl)
-class TestMedian(TestCase):
+class TestMedian(object):
def test_pytype(self):
r = np.ma.median([[np.inf, np.inf], [np.inf, np.inf]], axis=-1)
assert_equal(r, np.inf)
@@ -1069,9 +1068,9 @@
assert_(type(np.ma.median(o.astype(object))), float)
-class TestCov(TestCase):
+class TestCov(object):
- def setUp(self):
+ def setup(self):
self.data = array(np.random.rand(12))
def test_1d_without_missing(self):
@@ -1136,9 +1135,9 @@
x.shape[0] / frac))
-class TestCorrcoef(TestCase):
+class TestCorrcoef(object):
- def setUp(self):
+ def setup(self):
self.data = array(np.random.rand(12))
self.data2 = array(np.random.rand(12))
@@ -1243,7 +1242,7 @@
control[:-1, :-1])
-class TestPolynomial(TestCase):
+class TestPolynomial(object):
#
def test_polyfit(self):
# Tests polyfit
@@ -1301,13 +1300,13 @@
assert_almost_equal(a, a_)
-class TestArraySetOps(TestCase):
+class TestArraySetOps(object):
def test_unique_onlist(self):
# Test unique on list
data = [1, 1, 1, 2, 2, 3]
test = unique(data, return_index=True, return_inverse=True)
- self.assertTrue(isinstance(test[0], MaskedArray))
+ assert_(isinstance(test[0], MaskedArray))
assert_equal(test[0], masked_array([1, 2, 3], mask=[0, 0, 0]))
assert_equal(test[1], [0, 3, 5])
assert_equal(test[2], [0, 0, 0, 1, 1, 2])
@@ -1404,13 +1403,13 @@
test = ediff1d(x)
control = array([1, 1, 1, 1], mask=[0, 0, 0, 0])
assert_equal(test, control)
- self.assertTrue(isinstance(test, MaskedArray))
+ assert_(isinstance(test, MaskedArray))
assert_equal(test.filled(0), control.filled(0))
assert_equal(test.mask, control.mask)
#
test = ediff1d(x, to_end=masked, to_begin=masked)
control = array([0, 1, 1, 1, 1, 0], mask=[1, 0, 0, 0, 0, 1])
- self.assertTrue(isinstance(test, MaskedArray))
+ assert_(isinstance(test, MaskedArray))
assert_equal(test.filled(0), control.filled(0))
assert_equal(test.mask, control.mask)
@@ -1525,7 +1524,7 @@
assert_array_equal(setdiff1d(a, b), np.array(['c']))
-class TestShapeBase(TestCase):
+class TestShapeBase(object):
def test_atleast_2d(self):
# Test atleast_2d
diff --git a/numpy/ma/tests/test_mrecords.py b/numpy/ma/tests/test_mrecords.py
index 7857334..da22f8d 100644
--- a/numpy/ma/tests/test_mrecords.py
+++ b/numpy/ma/tests/test_mrecords.py
@@ -14,7 +14,7 @@
import numpy.ma as ma
from numpy import recarray
from numpy.ma import masked, nomask
-from numpy.testing import TestCase, run_module_suite, temppath
+from numpy.testing import run_module_suite, temppath
from numpy.core.records import (
fromrecords as recfromrecords, fromarrays as recfromarrays
)
@@ -28,21 +28,14 @@
)
-class TestMRecords(TestCase):
- # Base test class for MaskedArrays.
- def __init__(self, *args, **kwds):
- TestCase.__init__(self, *args, **kwds)
- self.setup()
+class TestMRecords(object):
- def setup(self):
- # Generic setup
- ilist = [1, 2, 3, 4, 5]
- flist = [1.1, 2.2, 3.3, 4.4, 5.5]
- slist = [b'one', b'two', b'three', b'four', b'five']
- ddtype = [('a', int), ('b', float), ('c', '|S8')]
- mask = [0, 1, 0, 0, 1]
- self.base = ma.array(list(zip(ilist, flist, slist)),
- mask=mask, dtype=ddtype)
+ ilist = [1, 2, 3, 4, 5]
+ flist = [1.1, 2.2, 3.3, 4.4, 5.5]
+ slist = [b'one', b'two', b'three', b'four', b'five']
+ ddtype = [('a', int), ('b', float), ('c', '|S8')]
+ mask = [0, 1, 0, 0, 1]
+ base = ma.array(list(zip(ilist, flist, slist)), mask=mask, dtype=ddtype)
def test_byview(self):
# Test creation by view
@@ -279,16 +272,16 @@
base = self.base.copy()
mbase = base.view(mrecarray)
mbase.harden_mask()
- self.assertTrue(mbase._hardmask)
+ assert_(mbase._hardmask)
mbase.mask = nomask
assert_equal_records(mbase._mask, base._mask)
mbase.soften_mask()
- self.assertTrue(not mbase._hardmask)
+ assert_(not mbase._hardmask)
mbase.mask = nomask
# So, the mask of a field is no longer set to nomask...
assert_equal_records(mbase._mask,
ma.make_mask_none(base.shape, base.dtype))
- self.assertTrue(ma.make_mask(mbase['b']._mask) is nomask)
+ assert_(ma.make_mask(mbase['b']._mask) is nomask)
assert_equal(mbase['a']._mask, mbase['b']._mask)
def test_pickling(self):
@@ -356,9 +349,9 @@
dtype=mult.dtype))
-class TestView(TestCase):
+class TestView(object):
- def setUp(self):
+ def setup(self):
(a, b) = (np.arange(10), np.random.rand(10))
ndtype = [('a', np.float), ('b', np.float)]
arr = np.array(list(zip(a, b)), dtype=ndtype)
@@ -370,7 +363,7 @@
def test_view_by_itself(self):
(mrec, a, b, arr) = self.data
test = mrec.view()
- self.assertTrue(isinstance(test, MaskedRecords))
+ assert_(isinstance(test, MaskedRecords))
assert_equal_records(test, mrec)
assert_equal_records(test._mask, mrec._mask)
@@ -378,40 +371,34 @@
(mrec, a, b, arr) = self.data
ntype = (np.float, 2)
test = mrec.view(ntype)
- self.assertTrue(isinstance(test, ma.MaskedArray))
+ assert_(isinstance(test, ma.MaskedArray))
assert_equal(test, np.array(list(zip(a, b)), dtype=np.float))
- self.assertTrue(test[3, 1] is ma.masked)
+ assert_(test[3, 1] is ma.masked)
def test_view_flexible_type(self):
(mrec, a, b, arr) = self.data
alttype = [('A', np.float), ('B', np.float)]
test = mrec.view(alttype)
- self.assertTrue(isinstance(test, MaskedRecords))
+ assert_(isinstance(test, MaskedRecords))
assert_equal_records(test, arr.view(alttype))
- self.assertTrue(test['B'][3] is masked)
+ assert_(test['B'][3] is masked)
assert_equal(test.dtype, np.dtype(alttype))
- self.assertTrue(test._fill_value is None)
+ assert_(test._fill_value is None)
##############################################################################
-class TestMRecordsImport(TestCase):
- # Base test class for MaskedArrays.
- def __init__(self, *args, **kwds):
- TestCase.__init__(self, *args, **kwds)
- self.setup()
+class TestMRecordsImport(object):
- def setup(self):
- # Generic setup
- _a = ma.array([1, 2, 3], mask=[0, 0, 1], dtype=int)
- _b = ma.array([1.1, 2.2, 3.3], mask=[0, 0, 1], dtype=float)
- _c = ma.array([b'one', b'two', b'three'],
- mask=[0, 0, 1], dtype='|S8')
- ddtype = [('a', int), ('b', float), ('c', '|S8')]
- mrec = fromarrays([_a, _b, _c], dtype=ddtype,
- fill_value=(b'99999', b'99999.',
- b'N/A'))
- nrec = recfromarrays((_a._data, _b._data, _c._data), dtype=ddtype)
- self.data = (mrec, nrec, ddtype)
+ _a = ma.array([1, 2, 3], mask=[0, 0, 1], dtype=int)
+ _b = ma.array([1.1, 2.2, 3.3], mask=[0, 0, 1], dtype=float)
+ _c = ma.array([b'one', b'two', b'three'],
+ mask=[0, 0, 1], dtype='|S8')
+ ddtype = [('a', int), ('b', float), ('c', '|S8')]
+ mrec = fromarrays([_a, _b, _c], dtype=ddtype,
+ fill_value=(b'99999', b'99999.',
+ b'N/A'))
+ nrec = recfromarrays((_a._data, _b._data, _c._data), dtype=ddtype)
+ data = (mrec, nrec, ddtype)
def test_fromarrays(self):
_a = ma.array([1, 2, 3], mask=[0, 0, 1], dtype=int)
@@ -485,7 +472,7 @@
with open(path, 'w') as f:
f.write(fcontent)
mrectxt = fromtextfile(path, delimitor=',', varnames='ABCDEFG')
- self.assertTrue(isinstance(mrectxt, MaskedRecords))
+ assert_(isinstance(mrectxt, MaskedRecords))
assert_equal(mrectxt.F, [1, 1, 1, 1])
assert_equal(mrectxt.E._mask, [1, 1, 1, 1])
assert_equal(mrectxt.C, [1, 2, 3.e+5, -1e-10])
diff --git a/numpy/ma/tests/test_old_ma.py b/numpy/ma/tests/test_old_ma.py
index 769e281..9152e8d 100644
--- a/numpy/ma/tests/test_old_ma.py
+++ b/numpy/ma/tests/test_old_ma.py
@@ -5,7 +5,9 @@
import numpy as np
import numpy.core.umath as umath
import numpy.core.fromnumeric as fromnumeric
-from numpy.testing import TestCase, run_module_suite, assert_
+from numpy.testing import (
+ run_module_suite, assert_, assert_raises, assert_equal,
+ )
from numpy.ma.testutils import assert_array_equal
from numpy.ma import (
MaskType, MaskedArray, absolute, add, all, allclose, allequal, alltrue,
@@ -31,9 +33,9 @@
return result
-class TestMa(TestCase):
+class TestMa(object):
- def setUp(self):
+ def setup(self):
x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
a10 = 10.
@@ -51,16 +53,16 @@
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.assertFalse(isMaskedArray(x))
- self.assertTrue(isMaskedArray(xm))
- self.assertEqual(shape(xm), s)
- self.assertEqual(xm.shape, s)
- self.assertEqual(xm.dtype, x.dtype)
- self.assertEqual(xm.size, reduce(lambda x, y:x * y, s))
- self.assertEqual(count(xm), len(m1) - reduce(lambda x, y:x + y, m1))
- self.assertTrue(eq(xm, xf))
- self.assertTrue(eq(filled(xm, 1.e20), xf))
- self.assertTrue(eq(x, xm))
+ assert_(not isMaskedArray(x))
+ assert_(isMaskedArray(xm))
+ assert_equal(shape(xm), s)
+ assert_equal(xm.shape, s)
+ assert_equal(xm.dtype, x.dtype)
+ assert_equal(xm.size, reduce(lambda x, y:x * y, s))
+ assert_equal(count(xm), len(m1) - reduce(lambda x, y:x + y, m1))
+ assert_(eq(xm, xf))
+ assert_(eq(filled(xm, 1.e20), xf))
+ assert_(eq(x, xm))
def test_testBasic2d(self):
# Test of basic array creation and properties in 2 dimensions.
@@ -72,107 +74,107 @@
ym.shape = s
xf.shape = s
- self.assertFalse(isMaskedArray(x))
- self.assertTrue(isMaskedArray(xm))
- self.assertEqual(shape(xm), s)
- self.assertEqual(xm.shape, s)
- self.assertEqual(xm.size, reduce(lambda x, y:x * y, s))
- self.assertEqual(count(xm),
+ assert_(not isMaskedArray(x))
+ assert_(isMaskedArray(xm))
+ assert_equal(shape(xm), s)
+ assert_equal(xm.shape, s)
+ assert_equal(xm.size, reduce(lambda x, y:x * y, s))
+ assert_equal(count(xm),
len(m1) - reduce(lambda x, y:x + y, m1))
- self.assertTrue(eq(xm, xf))
- self.assertTrue(eq(filled(xm, 1.e20), xf))
- self.assertTrue(eq(x, xm))
- self.setUp()
+ assert_(eq(xm, xf))
+ assert_(eq(filled(xm, 1.e20), xf))
+ assert_(eq(x, xm))
+ self.setup()
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]])
a2dm = masked_array(a2d, [[0, 0], [1, 0]])
- self.assertTrue(eq(a2d * a2d, a2d * a2dm))
- self.assertTrue(eq(a2d + a2d, a2d + a2dm))
- self.assertTrue(eq(a2d - a2d, a2d - a2dm))
+ assert_(eq(a2d * a2d, a2d * a2dm))
+ assert_(eq(a2d + a2d, a2d + a2dm))
+ assert_(eq(a2d - a2d, a2d - a2dm))
for s in [(12,), (4, 3), (2, 6)]:
x = x.reshape(s)
y = y.reshape(s)
xm = xm.reshape(s)
ym = ym.reshape(s)
xf = xf.reshape(s)
- self.assertTrue(eq(-x, -xm))
- self.assertTrue(eq(x + y, xm + ym))
- self.assertTrue(eq(x - y, xm - ym))
- self.assertTrue(eq(x * y, xm * ym))
+ assert_(eq(-x, -xm))
+ assert_(eq(x + y, xm + ym))
+ assert_(eq(x - y, xm - ym))
+ assert_(eq(x * y, xm * ym))
with np.errstate(divide='ignore', invalid='ignore'):
- self.assertTrue(eq(x / y, xm / ym))
- self.assertTrue(eq(a10 + y, a10 + ym))
- self.assertTrue(eq(a10 - y, a10 - ym))
- self.assertTrue(eq(a10 * y, a10 * ym))
+ assert_(eq(x / y, xm / ym))
+ assert_(eq(a10 + y, a10 + ym))
+ assert_(eq(a10 - y, a10 - ym))
+ assert_(eq(a10 * y, a10 * ym))
with np.errstate(divide='ignore', invalid='ignore'):
- self.assertTrue(eq(a10 / y, a10 / ym))
- self.assertTrue(eq(x + a10, xm + a10))
- self.assertTrue(eq(x - a10, xm - a10))
- self.assertTrue(eq(x * a10, xm * a10))
- self.assertTrue(eq(x / a10, xm / a10))
- self.assertTrue(eq(x ** 2, xm ** 2))
- self.assertTrue(eq(abs(x) ** 2.5, abs(xm) ** 2.5))
- self.assertTrue(eq(x ** y, xm ** ym))
- self.assertTrue(eq(np.add(x, y), add(xm, ym)))
- self.assertTrue(eq(np.subtract(x, y), subtract(xm, ym)))
- self.assertTrue(eq(np.multiply(x, y), multiply(xm, ym)))
+ assert_(eq(a10 / y, a10 / ym))
+ assert_(eq(x + a10, xm + a10))
+ assert_(eq(x - a10, xm - a10))
+ assert_(eq(x * a10, xm * a10))
+ assert_(eq(x / a10, xm / a10))
+ assert_(eq(x ** 2, xm ** 2))
+ assert_(eq(abs(x) ** 2.5, abs(xm) ** 2.5))
+ assert_(eq(x ** y, xm ** ym))
+ assert_(eq(np.add(x, y), add(xm, ym)))
+ assert_(eq(np.subtract(x, y), subtract(xm, ym)))
+ assert_(eq(np.multiply(x, y), multiply(xm, ym)))
with np.errstate(divide='ignore', invalid='ignore'):
- self.assertTrue(eq(np.divide(x, y), divide(xm, ym)))
+ assert_(eq(np.divide(x, y), divide(xm, ym)))
def test_testMixedArithmetic(self):
na = np.array([1])
ma = array([1])
- self.assertTrue(isinstance(na + ma, MaskedArray))
- self.assertTrue(isinstance(ma + na, MaskedArray))
+ assert_(isinstance(na + ma, MaskedArray))
+ assert_(isinstance(ma + na, MaskedArray))
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.assertTrue(eq(np.cos(x), cos(xm)))
- self.assertTrue(eq(np.cosh(x), cosh(xm)))
- self.assertTrue(eq(np.sin(x), sin(xm)))
- self.assertTrue(eq(np.sinh(x), sinh(xm)))
- self.assertTrue(eq(np.tan(x), tan(xm)))
- self.assertTrue(eq(np.tanh(x), tanh(xm)))
+ assert_(eq(np.cos(x), cos(xm)))
+ assert_(eq(np.cosh(x), cosh(xm)))
+ assert_(eq(np.sin(x), sin(xm)))
+ assert_(eq(np.sinh(x), sinh(xm)))
+ assert_(eq(np.tan(x), tan(xm)))
+ assert_(eq(np.tanh(x), tanh(xm)))
with np.errstate(divide='ignore', invalid='ignore'):
- self.assertTrue(eq(np.sqrt(abs(x)), sqrt(xm)))
- self.assertTrue(eq(np.log(abs(x)), log(xm)))
- self.assertTrue(eq(np.log10(abs(x)), log10(xm)))
- self.assertTrue(eq(np.exp(x), exp(xm)))
- self.assertTrue(eq(np.arcsin(z), arcsin(zm)))
- self.assertTrue(eq(np.arccos(z), arccos(zm)))
- self.assertTrue(eq(np.arctan(z), arctan(zm)))
- self.assertTrue(eq(np.arctan2(x, y), arctan2(xm, ym)))
- self.assertTrue(eq(np.absolute(x), absolute(xm)))
- self.assertTrue(eq(np.equal(x, y), equal(xm, ym)))
- self.assertTrue(eq(np.not_equal(x, y), not_equal(xm, ym)))
- self.assertTrue(eq(np.less(x, y), less(xm, ym)))
- self.assertTrue(eq(np.greater(x, y), greater(xm, ym)))
- self.assertTrue(eq(np.less_equal(x, y), less_equal(xm, ym)))
- self.assertTrue(eq(np.greater_equal(x, y), greater_equal(xm, ym)))
- self.assertTrue(eq(np.conjugate(x), conjugate(xm)))
- self.assertTrue(eq(np.concatenate((x, y)), concatenate((xm, ym))))
- self.assertTrue(eq(np.concatenate((x, y)), concatenate((x, y))))
- self.assertTrue(eq(np.concatenate((x, y)), concatenate((xm, y))))
- self.assertTrue(eq(np.concatenate((x, y, x)), concatenate((x, ym, x))))
+ assert_(eq(np.sqrt(abs(x)), sqrt(xm)))
+ assert_(eq(np.log(abs(x)), log(xm)))
+ assert_(eq(np.log10(abs(x)), log10(xm)))
+ assert_(eq(np.exp(x), exp(xm)))
+ assert_(eq(np.arcsin(z), arcsin(zm)))
+ assert_(eq(np.arccos(z), arccos(zm)))
+ assert_(eq(np.arctan(z), arctan(zm)))
+ assert_(eq(np.arctan2(x, y), arctan2(xm, ym)))
+ assert_(eq(np.absolute(x), absolute(xm)))
+ assert_(eq(np.equal(x, y), equal(xm, ym)))
+ assert_(eq(np.not_equal(x, y), not_equal(xm, ym)))
+ assert_(eq(np.less(x, y), less(xm, ym)))
+ assert_(eq(np.greater(x, y), greater(xm, ym)))
+ assert_(eq(np.less_equal(x, y), less_equal(xm, ym)))
+ assert_(eq(np.greater_equal(x, y), greater_equal(xm, ym)))
+ assert_(eq(np.conjugate(x), conjugate(xm)))
+ assert_(eq(np.concatenate((x, y)), concatenate((xm, ym))))
+ assert_(eq(np.concatenate((x, y)), concatenate((x, y))))
+ assert_(eq(np.concatenate((x, y)), concatenate((xm, y))))
+ assert_(eq(np.concatenate((x, y, x)), concatenate((x, ym, x))))
def test_xtestCount(self):
# Test count
ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0])
- self.assertTrue(count(ott).dtype.type is np.intp)
- self.assertEqual(3, count(ott))
- self.assertEqual(1, count(1))
- self.assertTrue(eq(0, array(1, mask=[1])))
+ assert_(count(ott).dtype.type is np.intp)
+ assert_equal(3, count(ott))
+ assert_equal(1, count(1))
+ assert_(eq(0, array(1, mask=[1])))
ott = ott.reshape((2, 2))
- self.assertTrue(count(ott).dtype.type is np.intp)
+ assert_(count(ott).dtype.type is np.intp)
assert_(isinstance(count(ott, 0), np.ndarray))
- self.assertTrue(count(ott).dtype.type is np.intp)
- self.assertTrue(eq(3, count(ott)))
+ assert_(count(ott).dtype.type is np.intp)
+ assert_(eq(3, count(ott)))
assert_(getmask(count(ott, 0)) is nomask)
- self.assertTrue(eq([1, 2], count(ott, 0)))
+ assert_(eq([1, 2], count(ott, 0)))
def test_testMinMax(self):
# Test minimum and maximum.
@@ -181,29 +183,29 @@
xmr = ravel(xm)
# true because of careful selection of data
- self.assertTrue(eq(max(xr), maximum.reduce(xmr)))
- self.assertTrue(eq(min(xr), minimum.reduce(xmr)))
+ assert_(eq(max(xr), maximum.reduce(xmr)))
+ assert_(eq(min(xr), minimum.reduce(xmr)))
def test_testAddSumProd(self):
# Test add, sum, product.
(x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
- self.assertTrue(eq(np.add.reduce(x), add.reduce(x)))
- self.assertTrue(eq(np.add.accumulate(x), add.accumulate(x)))
- self.assertTrue(eq(4, sum(array(4), axis=0)))
- self.assertTrue(eq(4, sum(array(4), axis=0)))
- self.assertTrue(eq(np.sum(x, axis=0), sum(x, axis=0)))
- self.assertTrue(eq(np.sum(filled(xm, 0), axis=0), sum(xm, axis=0)))
- self.assertTrue(eq(np.sum(x, 0), sum(x, 0)))
- self.assertTrue(eq(np.product(x, axis=0), product(x, axis=0)))
- self.assertTrue(eq(np.product(x, 0), product(x, 0)))
- self.assertTrue(eq(np.product(filled(xm, 1), axis=0),
+ assert_(eq(np.add.reduce(x), add.reduce(x)))
+ assert_(eq(np.add.accumulate(x), add.accumulate(x)))
+ assert_(eq(4, sum(array(4), axis=0)))
+ assert_(eq(4, sum(array(4), axis=0)))
+ assert_(eq(np.sum(x, axis=0), sum(x, axis=0)))
+ assert_(eq(np.sum(filled(xm, 0), axis=0), sum(xm, axis=0)))
+ assert_(eq(np.sum(x, 0), sum(x, 0)))
+ assert_(eq(np.product(x, axis=0), product(x, axis=0)))
+ assert_(eq(np.product(x, 0), product(x, 0)))
+ assert_(eq(np.product(filled(xm, 1), axis=0),
product(xm, axis=0)))
if len(s) > 1:
- self.assertTrue(eq(np.concatenate((x, y), 1),
+ assert_(eq(np.concatenate((x, y), 1),
concatenate((xm, ym), 1)))
- self.assertTrue(eq(np.add.reduce(x, 1), add.reduce(x, 1)))
- self.assertTrue(eq(np.sum(x, 1), sum(x, 1)))
- self.assertTrue(eq(np.product(x, 1), product(x, 1)))
+ assert_(eq(np.add.reduce(x, 1), add.reduce(x, 1)))
+ assert_(eq(np.sum(x, 1), sum(x, 1)))
+ assert_(eq(np.product(x, 1), product(x, 1)))
def test_testCI(self):
# Test of conversions and indexing
@@ -250,9 +252,9 @@
x2 = np.array([1, 'hello', 2, 3], object)
s1 = x1[1]
s2 = x2[1]
- self.assertEqual(type(s2), str)
- self.assertEqual(type(s1), str)
- self.assertEqual(s1, s2)
+ assert_equal(type(s2), str)
+ assert_equal(type(s1), str)
+ assert_equal(s1, s2)
assert_(x1[1:1].shape == (0,))
def test_testCopySize(self):
@@ -260,47 +262,47 @@
n = [0, 0, 1, 0, 0]
m = make_mask(n)
m2 = make_mask(m)
- self.assertTrue(m is m2)
+ assert_(m is m2)
m3 = make_mask(m, copy=1)
- self.assertTrue(m is not m3)
+ assert_(m is not m3)
x1 = np.arange(5)
y1 = array(x1, mask=m)
- self.assertTrue(y1._data is not x1)
- self.assertTrue(allequal(x1, y1._data))
- self.assertTrue(y1.mask is m)
+ assert_(y1._data is not x1)
+ assert_(allequal(x1, y1._data))
+ assert_(y1.mask is m)
y1a = array(y1, copy=0)
- self.assertTrue(y1a.mask is y1.mask)
+ assert_(y1a.mask is y1.mask)
y2 = array(x1, mask=m3, copy=0)
- self.assertTrue(y2.mask is m3)
- self.assertTrue(y2[2] is masked)
+ assert_(y2.mask is m3)
+ assert_(y2[2] is masked)
y2[2] = 9
- self.assertTrue(y2[2] is not masked)
- self.assertTrue(y2.mask is m3)
- self.assertTrue(allequal(y2.mask, 0))
+ assert_(y2[2] is not masked)
+ assert_(y2.mask is m3)
+ assert_(allequal(y2.mask, 0))
y2a = array(x1, mask=m, copy=1)
- self.assertTrue(y2a.mask is not m)
- self.assertTrue(y2a[2] is masked)
+ assert_(y2a.mask is not m)
+ assert_(y2a[2] is masked)
y2a[2] = 9
- self.assertTrue(y2a[2] is not masked)
- self.assertTrue(y2a.mask is not m)
- self.assertTrue(allequal(y2a.mask, 0))
+ assert_(y2a[2] is not masked)
+ assert_(y2a.mask is not m)
+ assert_(allequal(y2a.mask, 0))
y3 = array(x1 * 1.0, mask=m)
- self.assertTrue(filled(y3).dtype is (x1 * 1.0).dtype)
+ assert_(filled(y3).dtype is (x1 * 1.0).dtype)
x4 = arange(4)
x4[2] = masked
y4 = resize(x4, (8,))
- self.assertTrue(eq(concatenate([x4, x4]), y4))
- self.assertTrue(eq(getmask(y4), [0, 0, 1, 0, 0, 0, 1, 0]))
+ assert_(eq(concatenate([x4, x4]), y4))
+ assert_(eq(getmask(y4), [0, 0, 1, 0, 0, 0, 1, 0]))
y5 = repeat(x4, (2, 2, 2, 2), axis=0)
- self.assertTrue(eq(y5, [0, 0, 1, 1, 2, 2, 3, 3]))
+ assert_(eq(y5, [0, 0, 1, 1, 2, 2, 3, 3]))
y6 = repeat(x4, 2, axis=0)
- self.assertTrue(eq(y5, y6))
+ assert_(eq(y5, y6))
def test_testPut(self):
# Test of put
@@ -309,46 +311,46 @@
m = make_mask(n)
m2 = m.copy()
x = array(d, mask=m)
- self.assertTrue(x[3] is masked)
- self.assertTrue(x[4] is masked)
+ assert_(x[3] is masked)
+ assert_(x[4] is masked)
x[[1, 4]] = [10, 40]
- self.assertTrue(x.mask is m)
- self.assertTrue(x[3] is masked)
- self.assertTrue(x[4] is not masked)
- self.assertTrue(eq(x, [0, 10, 2, -1, 40]))
+ assert_(x.mask is m)
+ assert_(x[3] is masked)
+ assert_(x[4] is not masked)
+ assert_(eq(x, [0, 10, 2, -1, 40]))
x = array(d, mask=m2, copy=True)
x.put([0, 1, 2], [-1, 100, 200])
- self.assertTrue(x.mask is not m2)
- self.assertTrue(x[3] is masked)
- self.assertTrue(x[4] is masked)
- self.assertTrue(eq(x, [-1, 100, 200, 0, 0]))
+ assert_(x.mask is not m2)
+ assert_(x[3] is masked)
+ assert_(x[4] is masked)
+ assert_(eq(x, [-1, 100, 200, 0, 0]))
def test_testPut2(self):
# Test of put
d = arange(5)
x = array(d, mask=[0, 0, 0, 0, 0])
z = array([10, 40], mask=[1, 0])
- self.assertTrue(x[2] is not masked)
- self.assertTrue(x[3] is not masked)
+ assert_(x[2] is not masked)
+ assert_(x[3] is not masked)
x[2:4] = z
- self.assertTrue(x[2] is masked)
- self.assertTrue(x[3] is not masked)
- self.assertTrue(eq(x, [0, 1, 10, 40, 4]))
+ assert_(x[2] is masked)
+ assert_(x[3] is not masked)
+ assert_(eq(x, [0, 1, 10, 40, 4]))
d = arange(5)
x = array(d, mask=[0, 0, 0, 0, 0])
y = x[2:4]
z = array([10, 40], mask=[1, 0])
- self.assertTrue(x[2] is not masked)
- self.assertTrue(x[3] is not masked)
+ assert_(x[2] is not masked)
+ assert_(x[3] is not masked)
y[:] = z
- self.assertTrue(y[0] is masked)
- self.assertTrue(y[1] is not masked)
- self.assertTrue(eq(y, [10, 40]))
- self.assertTrue(x[2] is masked)
- self.assertTrue(x[3] is not masked)
- self.assertTrue(eq(x, [0, 1, 10, 40, 4]))
+ assert_(y[0] is masked)
+ assert_(y[1] is not masked)
+ assert_(eq(y, [10, 40]))
+ assert_(x[2] is masked)
+ assert_(x[3] is not masked)
+ assert_(eq(x, [0, 1, 10, 40, 4]))
def test_testMaPut(self):
(x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
@@ -555,147 +557,147 @@
# Test of masked element
xx = arange(6)
xx[1] = masked
- self.assertTrue(str(masked) == '--')
- self.assertTrue(xx[1] is masked)
- self.assertEqual(filled(xx[1], 0), 0)
+ assert_(str(masked) == '--')
+ assert_(xx[1] is masked)
+ assert_equal(filled(xx[1], 0), 0)
def test_testAverage1(self):
# Test of average.
ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0])
- self.assertTrue(eq(2.0, average(ott, axis=0)))
- self.assertTrue(eq(2.0, average(ott, weights=[1., 1., 2., 1.])))
+ assert_(eq(2.0, average(ott, axis=0)))
+ assert_(eq(2.0, average(ott, weights=[1., 1., 2., 1.])))
result, wts = average(ott, weights=[1., 1., 2., 1.], returned=1)
- self.assertTrue(eq(2.0, result))
- self.assertTrue(wts == 4.0)
+ assert_(eq(2.0, result))
+ assert_(wts == 4.0)
ott[:] = masked
- self.assertTrue(average(ott, axis=0) is masked)
+ assert_(average(ott, axis=0) is masked)
ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0])
ott = ott.reshape(2, 2)
ott[:, 1] = masked
- self.assertTrue(eq(average(ott, axis=0), [2.0, 0.0]))
- self.assertTrue(average(ott, axis=1)[0] is masked)
- self.assertTrue(eq([2., 0.], average(ott, axis=0)))
+ assert_(eq(average(ott, axis=0), [2.0, 0.0]))
+ assert_(average(ott, axis=1)[0] is masked)
+ assert_(eq([2., 0.], average(ott, axis=0)))
result, wts = average(ott, axis=0, returned=1)
- self.assertTrue(eq(wts, [1., 0.]))
+ assert_(eq(wts, [1., 0.]))
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]]
x = arange(6)
- self.assertTrue(allclose(average(x, axis=0), 2.5))
- self.assertTrue(allclose(average(x, axis=0, weights=w1), 2.5))
+ assert_(allclose(average(x, axis=0), 2.5))
+ assert_(allclose(average(x, axis=0, weights=w1), 2.5))
y = array([arange(6), 2.0 * arange(6)])
- self.assertTrue(allclose(average(y, None),
+ assert_(allclose(average(y, None),
np.add.reduce(np.arange(6)) * 3. / 12.))
- self.assertTrue(allclose(average(y, axis=0), np.arange(6) * 3. / 2.))
- self.assertTrue(allclose(average(y, axis=1),
+ assert_(allclose(average(y, axis=0), np.arange(6) * 3. / 2.))
+ assert_(allclose(average(y, axis=1),
[average(x, axis=0), average(x, axis=0)*2.0]))
- self.assertTrue(allclose(average(y, None, weights=w2), 20. / 6.))
- self.assertTrue(allclose(average(y, axis=0, weights=w2),
+ assert_(allclose(average(y, None, weights=w2), 20. / 6.))
+ assert_(allclose(average(y, axis=0, weights=w2),
[0., 1., 2., 3., 4., 10.]))
- self.assertTrue(allclose(average(y, axis=1),
+ assert_(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]]
m4 = ones(6)
m5 = [0, 1, 1, 1, 1, 1]
- self.assertTrue(allclose(average(masked_array(x, m1), axis=0), 2.5))
- self.assertTrue(allclose(average(masked_array(x, m2), axis=0), 2.5))
- self.assertTrue(average(masked_array(x, m4), axis=0) is masked)
- self.assertEqual(average(masked_array(x, m5), axis=0), 0.0)
- self.assertEqual(count(average(masked_array(x, m4), axis=0)), 0)
+ assert_(allclose(average(masked_array(x, m1), axis=0), 2.5))
+ assert_(allclose(average(masked_array(x, m2), axis=0), 2.5))
+ assert_(average(masked_array(x, m4), axis=0) is masked)
+ assert_equal(average(masked_array(x, m5), axis=0), 0.0)
+ assert_equal(count(average(masked_array(x, m4), axis=0)), 0)
z = masked_array(y, m3)
- self.assertTrue(allclose(average(z, None), 20. / 6.))
- self.assertTrue(allclose(average(z, axis=0),
+ assert_(allclose(average(z, None), 20. / 6.))
+ assert_(allclose(average(z, axis=0),
[0., 1., 99., 99., 4.0, 7.5]))
- self.assertTrue(allclose(average(z, axis=1), [2.5, 5.0]))
- self.assertTrue(allclose(average(z, axis=0, weights=w2),
+ assert_(allclose(average(z, axis=1), [2.5, 5.0]))
+ assert_(allclose(average(z, axis=0, weights=w2),
[0., 1., 99., 99., 4.0, 10.0]))
a = arange(6)
b = arange(6) * 3
r1, w1 = average([[a, b], [b, a]], axis=1, returned=1)
- self.assertEqual(shape(r1), shape(w1))
- self.assertEqual(r1.shape, w1.shape)
+ assert_equal(shape(r1), shape(w1))
+ assert_equal(r1.shape, w1.shape)
r2, w2 = average(ones((2, 2, 3)), axis=0, weights=[3, 1], returned=1)
- self.assertEqual(shape(w2), shape(r2))
+ assert_equal(shape(w2), shape(r2))
r2, w2 = average(ones((2, 2, 3)), returned=1)
- self.assertEqual(shape(w2), shape(r2))
+ assert_equal(shape(w2), shape(r2))
r2, w2 = average(ones((2, 2, 3)), weights=ones((2, 2, 3)), returned=1)
- self.assertTrue(shape(w2) == shape(r2))
+ assert_(shape(w2) == shape(r2))
a2d = array([[1, 2], [0, 4]], float)
a2dm = masked_array(a2d, [[0, 0], [1, 0]])
a2da = average(a2d, axis=0)
- self.assertTrue(eq(a2da, [0.5, 3.0]))
+ assert_(eq(a2da, [0.5, 3.0]))
a2dma = average(a2dm, axis=0)
- self.assertTrue(eq(a2dma, [1.0, 3.0]))
+ assert_(eq(a2dma, [1.0, 3.0]))
a2dma = average(a2dm, axis=None)
- self.assertTrue(eq(a2dma, 7. / 3.))
+ assert_(eq(a2dma, 7. / 3.))
a2dma = average(a2dm, axis=1)
- self.assertTrue(eq(a2dma, [1.5, 4.0]))
+ assert_(eq(a2dma, [1.5, 4.0]))
def test_testToPython(self):
- self.assertEqual(1, int(array(1)))
- self.assertEqual(1.0, float(array(1)))
- self.assertEqual(1, int(array([[[1]]])))
- self.assertEqual(1.0, float(array([[1]])))
- self.assertRaises(TypeError, float, array([1, 1]))
- self.assertRaises(ValueError, bool, array([0, 1]))
- self.assertRaises(ValueError, bool, array([0, 0], mask=[0, 1]))
+ assert_equal(1, int(array(1)))
+ assert_equal(1.0, float(array(1)))
+ assert_equal(1, int(array([[[1]]])))
+ assert_equal(1.0, float(array([[1]])))
+ assert_raises(TypeError, float, array([1, 1]))
+ assert_raises(ValueError, bool, array([0, 1]))
+ assert_raises(ValueError, bool, array([0, 0], mask=[0, 1]))
def test_testScalarArithmetic(self):
xm = array(0, mask=1)
#TODO FIXME: Find out what the following raises a warning in r8247
with np.errstate(divide='ignore'):
- self.assertTrue((1 / array(0)).mask)
- self.assertTrue((1 + xm).mask)
- self.assertTrue((-xm).mask)
- self.assertTrue((-xm).mask)
- self.assertTrue(maximum(xm, xm).mask)
- self.assertTrue(minimum(xm, xm).mask)
- self.assertTrue(xm.filled().dtype is xm._data.dtype)
+ assert_((1 / array(0)).mask)
+ assert_((1 + xm).mask)
+ assert_((-xm).mask)
+ assert_((-xm).mask)
+ assert_(maximum(xm, xm).mask)
+ assert_(minimum(xm, xm).mask)
+ assert_(xm.filled().dtype is xm._data.dtype)
x = array(0, mask=0)
- self.assertTrue(x.filled() == x._data)
- self.assertEqual(str(xm), str(masked_print_option))
+ assert_(x.filled() == x._data)
+ assert_equal(str(xm), str(masked_print_option))
def test_testArrayMethods(self):
a = array([1, 3, 2])
- self.assertTrue(eq(a.any(), a._data.any()))
- self.assertTrue(eq(a.all(), a._data.all()))
- self.assertTrue(eq(a.argmax(), a._data.argmax()))
- self.assertTrue(eq(a.argmin(), a._data.argmin()))
- self.assertTrue(eq(a.choose(0, 1, 2, 3, 4),
+ assert_(eq(a.any(), a._data.any()))
+ assert_(eq(a.all(), a._data.all()))
+ assert_(eq(a.argmax(), a._data.argmax()))
+ assert_(eq(a.argmin(), a._data.argmin()))
+ assert_(eq(a.choose(0, 1, 2, 3, 4),
a._data.choose(0, 1, 2, 3, 4)))
- self.assertTrue(eq(a.compress([1, 0, 1]), a._data.compress([1, 0, 1])))
- self.assertTrue(eq(a.conj(), a._data.conj()))
- self.assertTrue(eq(a.conjugate(), a._data.conjugate()))
+ assert_(eq(a.compress([1, 0, 1]), a._data.compress([1, 0, 1])))
+ assert_(eq(a.conj(), a._data.conj()))
+ assert_(eq(a.conjugate(), a._data.conjugate()))
m = array([[1, 2], [3, 4]])
- self.assertTrue(eq(m.diagonal(), m._data.diagonal()))
- self.assertTrue(eq(a.sum(), a._data.sum()))
- self.assertTrue(eq(a.take([1, 2]), a._data.take([1, 2])))
- self.assertTrue(eq(m.transpose(), m._data.transpose()))
+ assert_(eq(m.diagonal(), m._data.diagonal()))
+ assert_(eq(a.sum(), a._data.sum()))
+ assert_(eq(a.take([1, 2]), a._data.take([1, 2])))
+ assert_(eq(m.transpose(), m._data.transpose()))
def test_testArrayAttributes(self):
a = array([1, 3, 2])
- self.assertEqual(a.ndim, 1)
+ assert_equal(a.ndim, 1)
def test_testAPI(self):
- self.assertFalse([m for m in dir(np.ndarray)
- if m not in dir(MaskedArray) and
- not m.startswith('_')])
+ assert_(not [m for m in dir(np.ndarray)
+ if m not in dir(MaskedArray) and
+ not m.startswith('_')])
def test_testSingleElementSubscript(self):
a = array([1, 3, 2])
b = array([1, 3, 2], mask=[1, 0, 1])
- self.assertEqual(a[0].shape, ())
- self.assertEqual(b[0].shape, ())
- self.assertEqual(b[1].shape, ())
+ assert_equal(a[0].shape, ())
+ assert_equal(b[0].shape, ())
+ assert_equal(b[1].shape, ())
-class TestUfuncs(TestCase):
- def setUp(self):
+class TestUfuncs(object):
+ 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),)
@@ -733,35 +735,35 @@
np.seterr(divide='ignore')
ur = uf(*args)
mr = mf(*args)
- self.assertTrue(eq(ur.filled(0), mr.filled(0), f))
- self.assertTrue(eqmask(ur.mask, mr.mask))
+ assert_(eq(ur.filled(0), mr.filled(0), f))
+ assert_(eqmask(ur.mask, mr.mask))
def test_reduce(self):
a = self.d[0]
- self.assertFalse(alltrue(a, axis=0))
- self.assertTrue(sometrue(a, axis=0))
- self.assertEqual(sum(a[:3], axis=0), 0)
- self.assertEqual(product(a, axis=0), 0)
+ assert_(not alltrue(a, axis=0))
+ assert_(sometrue(a, axis=0))
+ assert_equal(sum(a[:3], axis=0), 0)
+ assert_equal(product(a, axis=0), 0)
def test_minmax(self):
a = arange(1, 13).reshape(3, 4)
amask = masked_where(a < 5, a)
- self.assertEqual(amask.max(), a.max())
- self.assertEqual(amask.min(), 5)
- self.assertTrue((amask.max(0) == a.max(0)).all())
- self.assertTrue((amask.min(0) == [5, 6, 7, 8]).all())
- self.assertTrue(amask.max(1)[0].mask)
- self.assertTrue(amask.min(1)[0].mask)
+ assert_equal(amask.max(), a.max())
+ assert_equal(amask.min(), 5)
+ assert_((amask.max(0) == a.max(0)).all())
+ assert_((amask.min(0) == [5, 6, 7, 8]).all())
+ assert_(amask.max(1)[0].mask)
+ assert_(amask.min(1)[0].mask)
def test_nonzero(self):
for t in "?bhilqpBHILQPfdgFDGO":
x = array([1, 0, 2, 0], mask=[0, 0, 1, 1])
- self.assertTrue(eq(nonzero(x), [0]))
+ assert_(eq(nonzero(x), [0]))
-class TestArrayMethods(TestCase):
+class TestArrayMethods(object):
- def setUp(self):
+ def setup(self):
x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,
8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
3.012, 6.022, 5.095, 3.116, 5.238, 3.957,
@@ -786,63 +788,63 @@
def test_trace(self):
(x, X, XX, m, mx, mX, mXX,) = self.d
mXdiag = mX.diagonal()
- self.assertEqual(mX.trace(), mX.diagonal().compressed().sum())
- self.assertTrue(eq(mX.trace(),
+ assert_equal(mX.trace(), mX.diagonal().compressed().sum())
+ assert_(eq(mX.trace(),
X.trace() - sum(mXdiag.mask * X.diagonal(),
axis=0)))
def test_clip(self):
(x, X, XX, m, mx, mX, mXX,) = self.d
clipped = mx.clip(2, 8)
- self.assertTrue(eq(clipped.mask, mx.mask))
- self.assertTrue(eq(clipped._data, x.clip(2, 8)))
- self.assertTrue(eq(clipped._data, mx._data.clip(2, 8)))
+ assert_(eq(clipped.mask, mx.mask))
+ assert_(eq(clipped._data, x.clip(2, 8)))
+ assert_(eq(clipped._data, mx._data.clip(2, 8)))
def test_ptp(self):
(x, X, XX, m, mx, mX, mXX,) = self.d
(n, m) = X.shape
- self.assertEqual(mx.ptp(), mx.compressed().ptp())
+ assert_equal(mx.ptp(), mx.compressed().ptp())
rows = np.zeros(n, np.float_)
cols = np.zeros(m, np.float_)
for k in range(m):
cols[k] = mX[:, k].compressed().ptp()
for k in range(n):
rows[k] = mX[k].compressed().ptp()
- self.assertTrue(eq(mX.ptp(0), cols))
- self.assertTrue(eq(mX.ptp(1), rows))
+ assert_(eq(mX.ptp(0), cols))
+ assert_(eq(mX.ptp(1), rows))
def test_swapaxes(self):
(x, X, XX, m, mx, mX, mXX,) = self.d
mXswapped = mX.swapaxes(0, 1)
- self.assertTrue(eq(mXswapped[-1], mX[:, -1]))
+ assert_(eq(mXswapped[-1], mX[:, -1]))
mXXswapped = mXX.swapaxes(0, 2)
- self.assertEqual(mXXswapped.shape, (2, 2, 3, 3))
+ assert_equal(mXXswapped.shape, (2, 2, 3, 3))
def test_cumprod(self):
(x, X, XX, m, mx, mX, mXX,) = self.d
mXcp = mX.cumprod(0)
- self.assertTrue(eq(mXcp._data, mX.filled(1).cumprod(0)))
+ assert_(eq(mXcp._data, mX.filled(1).cumprod(0)))
mXcp = mX.cumprod(1)
- self.assertTrue(eq(mXcp._data, mX.filled(1).cumprod(1)))
+ assert_(eq(mXcp._data, mX.filled(1).cumprod(1)))
def test_cumsum(self):
(x, X, XX, m, mx, mX, mXX,) = self.d
mXcp = mX.cumsum(0)
- self.assertTrue(eq(mXcp._data, mX.filled(0).cumsum(0)))
+ assert_(eq(mXcp._data, mX.filled(0).cumsum(0)))
mXcp = mX.cumsum(1)
- self.assertTrue(eq(mXcp._data, mX.filled(0).cumsum(1)))
+ assert_(eq(mXcp._data, mX.filled(0).cumsum(1)))
def test_varstd(self):
(x, X, XX, m, mx, mX, mXX,) = self.d
- self.assertTrue(eq(mX.var(axis=None), mX.compressed().var()))
- self.assertTrue(eq(mX.std(axis=None), mX.compressed().std()))
- self.assertTrue(eq(mXX.var(axis=3).shape, XX.var(axis=3).shape))
- self.assertTrue(eq(mX.var().shape, X.var().shape))
+ assert_(eq(mX.var(axis=None), mX.compressed().var()))
+ assert_(eq(mX.std(axis=None), mX.compressed().std()))
+ assert_(eq(mXX.var(axis=3).shape, XX.var(axis=3).shape))
+ assert_(eq(mX.var().shape, X.var().shape))
(mXvar0, mXvar1) = (mX.var(axis=0), mX.var(axis=1))
for k in range(6):
- self.assertTrue(eq(mXvar1[k], mX[k].compressed().var()))
- self.assertTrue(eq(mXvar0[k], mX[:, k].compressed().var()))
- self.assertTrue(eq(np.sqrt(mXvar0[k]),
+ assert_(eq(mXvar1[k], mX[k].compressed().var()))
+ assert_(eq(mXvar0[k], mX[:, k].compressed().var()))
+ assert_(eq(np.sqrt(mXvar0[k]),
mX[:, k].compressed().std()))
diff --git a/numpy/ma/tests/test_regression.py b/numpy/ma/tests/test_regression.py
index d1fb2bb..34dd29d 100644
--- a/numpy/ma/tests/test_regression.py
+++ b/numpy/ma/tests/test_regression.py
@@ -3,14 +3,15 @@
import warnings
import numpy as np
-from numpy.testing import (assert_, TestCase, assert_array_equal,
- assert_allclose, run_module_suite,
- suppress_warnings)
+from numpy.testing import (
+ assert_, assert_array_equal, assert_allclose, run_module_suite,
+ suppress_warnings
+ )
rlevel = 1
-class TestRegression(TestCase):
+class TestRegression(object):
def test_masked_array_create(self,level=rlevel):
# Ticket #17
x = np.ma.masked_array([0, 1, 2, 3, 0, 4, 5, 6],
diff --git a/numpy/ma/tests/test_subclassing.py b/numpy/ma/tests/test_subclassing.py
index b2995fd..e59dd46 100644
--- a/numpy/ma/tests/test_subclassing.py
+++ b/numpy/ma/tests/test_subclassing.py
@@ -9,7 +9,7 @@
from __future__ import division, absolute_import, print_function
import numpy as np
-from numpy.testing import TestCase, run_module_suite, assert_raises, dec
+from numpy.testing import run_module_suite, assert_, assert_raises, dec
from numpy.ma.testutils import assert_equal
from numpy.ma.core import (
array, arange, masked, MaskedArray, masked_array, log, add, hypot,
@@ -172,10 +172,10 @@
return obj
-class TestSubclassing(TestCase):
+class TestSubclassing(object):
# Test suite for masked subclasses of ndarray.
- def setUp(self):
+ def setup(self):
x = np.arange(5, dtype='float')
mx = mmatrix(x, mask=[0, 1, 0, 0, 0])
self.data = (x, mx)
@@ -186,41 +186,41 @@
m = [0, 0, 1, 0, 0]
xsub = SubArray(x)
xmsub = masked_array(xsub, mask=m)
- self.assertTrue(isinstance(xmsub, MaskedArray))
+ assert_(isinstance(xmsub, MaskedArray))
assert_equal(xmsub._data, xsub)
- self.assertTrue(isinstance(xmsub._data, SubArray))
+ assert_(isinstance(xmsub._data, SubArray))
def test_maskedarray_subclassing(self):
# Tests subclassing MaskedArray
(x, mx) = self.data
- self.assertTrue(isinstance(mx._data, np.matrix))
+ assert_(isinstance(mx._data, np.matrix))
def test_masked_unary_operations(self):
# Tests masked_unary_operation
(x, mx) = self.data
with np.errstate(divide='ignore'):
- self.assertTrue(isinstance(log(mx), mmatrix))
+ assert_(isinstance(log(mx), mmatrix))
assert_equal(log(x), np.log(x))
def test_masked_binary_operations(self):
# Tests masked_binary_operation
(x, mx) = self.data
# Result should be a mmatrix
- self.assertTrue(isinstance(add(mx, mx), mmatrix))
- self.assertTrue(isinstance(add(mx, x), mmatrix))
+ assert_(isinstance(add(mx, mx), mmatrix))
+ assert_(isinstance(add(mx, x), mmatrix))
# Result should work
assert_equal(add(mx, x), mx+x)
- self.assertTrue(isinstance(add(mx, mx)._data, np.matrix))
- self.assertTrue(isinstance(add.outer(mx, mx), mmatrix))
- self.assertTrue(isinstance(hypot(mx, mx), mmatrix))
- self.assertTrue(isinstance(hypot(mx, x), mmatrix))
+ assert_(isinstance(add(mx, mx)._data, np.matrix))
+ assert_(isinstance(add.outer(mx, mx), mmatrix))
+ assert_(isinstance(hypot(mx, mx), mmatrix))
+ assert_(isinstance(hypot(mx, x), mmatrix))
def test_masked_binary_operations2(self):
# Tests domained_masked_binary_operation
(x, mx) = self.data
xmx = masked_array(mx.data.__array__(), mask=mx.mask)
- self.assertTrue(isinstance(divide(mx, mx), mmatrix))
- self.assertTrue(isinstance(divide(mx, x), mmatrix))
+ assert_(isinstance(divide(mx, mx), mmatrix))
+ assert_(isinstance(divide(mx, x), mmatrix))
assert_equal(divide(mx, mx), divide(xmx, xmx))
def test_attributepropagation(self):
@@ -229,22 +229,22 @@
ym = msubarray(x)
#
z = (my+1)
- self.assertTrue(isinstance(z, MaskedArray))
- self.assertTrue(not isinstance(z, MSubArray))
- self.assertTrue(isinstance(z._data, SubArray))
+ assert_(isinstance(z, MaskedArray))
+ assert_(not isinstance(z, MSubArray))
+ assert_(isinstance(z._data, SubArray))
assert_equal(z._data.info, {})
#
z = (ym+1)
- self.assertTrue(isinstance(z, MaskedArray))
- self.assertTrue(isinstance(z, MSubArray))
- self.assertTrue(isinstance(z._data, SubArray))
- self.assertTrue(z._data.info['added'] > 0)
+ assert_(isinstance(z, MaskedArray))
+ assert_(isinstance(z, MSubArray))
+ assert_(isinstance(z._data, SubArray))
+ assert_(z._data.info['added'] > 0)
# Test that inplace methods from data get used (gh-4617)
ym += 1
- self.assertTrue(isinstance(ym, MaskedArray))
- self.assertTrue(isinstance(ym, MSubArray))
- self.assertTrue(isinstance(ym._data, SubArray))
- self.assertTrue(ym._data.info['iadded'] > 0)
+ assert_(isinstance(ym, MaskedArray))
+ assert_(isinstance(ym, MSubArray))
+ assert_(isinstance(ym._data, SubArray))
+ assert_(ym._data.info['iadded'] > 0)
#
ym._set_mask([1, 0, 0, 0, 1])
assert_equal(ym._mask, [1, 0, 0, 0, 1])
@@ -253,7 +253,7 @@
#
xsub = subarray(x, info={'name':'x'})
mxsub = masked_array(xsub)
- self.assertTrue(hasattr(mxsub, 'info'))
+ assert_(hasattr(mxsub, 'info'))
assert_equal(mxsub.info, xsub.info)
def test_subclasspreservation(self):
@@ -264,22 +264,22 @@
xsub = MSubArray(x, mask=m, info={'xsub':xinfo})
#
mxsub = masked_array(xsub, subok=False)
- self.assertTrue(not isinstance(mxsub, MSubArray))
- self.assertTrue(isinstance(mxsub, MaskedArray))
+ assert_(not isinstance(mxsub, MSubArray))
+ assert_(isinstance(mxsub, MaskedArray))
assert_equal(mxsub._mask, m)
#
mxsub = asarray(xsub)
- self.assertTrue(not isinstance(mxsub, MSubArray))
- self.assertTrue(isinstance(mxsub, MaskedArray))
+ assert_(not isinstance(mxsub, MSubArray))
+ assert_(isinstance(mxsub, MaskedArray))
assert_equal(mxsub._mask, m)
#
mxsub = masked_array(xsub, subok=True)
- self.assertTrue(isinstance(mxsub, MSubArray))
+ assert_(isinstance(mxsub, MSubArray))
assert_equal(mxsub.info, xsub.info)
assert_equal(mxsub._mask, xsub._mask)
#
mxsub = asanyarray(xsub)
- self.assertTrue(isinstance(mxsub, MSubArray))
+ assert_(isinstance(mxsub, MSubArray))
assert_equal(mxsub.info, xsub.info)
assert_equal(mxsub._mask, m)
@@ -290,21 +290,21 @@
mxcsub = masked_array(xcsub, mask=[True, False, True, False, False])
# getter should return a ComplicatedSubArray, even for single item
# first check we wrote ComplicatedSubArray correctly
- self.assertTrue(isinstance(xcsub[1], ComplicatedSubArray))
- self.assertTrue(isinstance(xcsub[1,...], ComplicatedSubArray))
- self.assertTrue(isinstance(xcsub[1:4], ComplicatedSubArray))
+ assert_(isinstance(xcsub[1], ComplicatedSubArray))
+ assert_(isinstance(xcsub[1,...], ComplicatedSubArray))
+ assert_(isinstance(xcsub[1:4], ComplicatedSubArray))
# now that it propagates inside the MaskedArray
- self.assertTrue(isinstance(mxcsub[1], ComplicatedSubArray))
- self.assertTrue(isinstance(mxcsub[1,...].data, ComplicatedSubArray))
- self.assertTrue(mxcsub[0] is masked)
- self.assertTrue(isinstance(mxcsub[0,...].data, ComplicatedSubArray))
- self.assertTrue(isinstance(mxcsub[1:4].data, ComplicatedSubArray))
+ assert_(isinstance(mxcsub[1], ComplicatedSubArray))
+ assert_(isinstance(mxcsub[1,...].data, ComplicatedSubArray))
+ assert_(mxcsub[0] is masked)
+ assert_(isinstance(mxcsub[0,...].data, ComplicatedSubArray))
+ assert_(isinstance(mxcsub[1:4].data, ComplicatedSubArray))
# also for flattened version (which goes via MaskedIterator)
- self.assertTrue(isinstance(mxcsub.flat[1].data, ComplicatedSubArray))
- self.assertTrue(mxcsub.flat[0] is masked)
- self.assertTrue(isinstance(mxcsub.flat[1:4].base, ComplicatedSubArray))
+ assert_(isinstance(mxcsub.flat[1].data, ComplicatedSubArray))
+ assert_(mxcsub.flat[0] is masked)
+ assert_(isinstance(mxcsub.flat[1:4].base, ComplicatedSubArray))
# setter should only work with ComplicatedSubArray input
# first check we wrote ComplicatedSubArray correctly
@@ -325,21 +325,21 @@
xcsub = ComplicatedSubArray(x)
mxcsub_nomask = masked_array(xcsub)
- self.assertTrue(isinstance(mxcsub_nomask[1,...].data, ComplicatedSubArray))
- self.assertTrue(isinstance(mxcsub_nomask[0,...].data, ComplicatedSubArray))
+ assert_(isinstance(mxcsub_nomask[1,...].data, ComplicatedSubArray))
+ assert_(isinstance(mxcsub_nomask[0,...].data, ComplicatedSubArray))
- self.assertTrue(isinstance(mxcsub_nomask[1], ComplicatedSubArray))
- self.assertTrue(isinstance(mxcsub_nomask[0], ComplicatedSubArray))
+ assert_(isinstance(mxcsub_nomask[1], ComplicatedSubArray))
+ assert_(isinstance(mxcsub_nomask[0], ComplicatedSubArray))
def test_subclass_repr(self):
"""test that repr uses the name of the subclass
and 'array' for np.ndarray"""
x = np.arange(5)
mx = masked_array(x, mask=[True, False, True, False, False])
- self.assertTrue(repr(mx).startswith('masked_array'))
+ assert_(repr(mx).startswith('masked_array'))
xsub = SubArray(x)
mxsub = masked_array(xsub, mask=[True, False, True, False, False])
- self.assertTrue(repr(mxsub).startswith(
+ assert_(repr(mxsub).startswith(
'masked_{0}(data = [-- 1 -- 3 4]'.format(SubArray.__name__)))
def test_subclass_str(self):
@@ -348,13 +348,13 @@
x = np.arange(5)
xsub = SubArray(x)
mxsub = masked_array(xsub, mask=[True, False, True, False, False])
- self.assertTrue(str(mxsub) == '[-- 1 -- 3 4]')
+ assert_(str(mxsub) == '[-- 1 -- 3 4]')
xcsub = ComplicatedSubArray(x)
assert_raises(ValueError, xcsub.__setitem__, 0,
np.ma.core.masked_print_option)
mxcsub = masked_array(xcsub, mask=[True, False, True, False, False])
- self.assertTrue(str(mxcsub) == 'myprefix [-- 1 -- 3 4] mypostfix')
+ assert_(str(mxcsub) == 'myprefix [-- 1 -- 3 4] mypostfix')
def test_pure_subclass_info_preservation(self):
# Test that ufuncs and methods conserve extra information consistently;
@@ -362,11 +362,11 @@
arr1 = SubMaskedArray('test', data=[1,2,3,4,5,6])
arr2 = SubMaskedArray(data=[0,1,2,3,4,5])
diff1 = np.subtract(arr1, arr2)
- self.assertTrue('info' in diff1._optinfo)
- self.assertTrue(diff1._optinfo['info'] == 'test')
+ assert_('info' in diff1._optinfo)
+ assert_(diff1._optinfo['info'] == 'test')
diff2 = arr1 - arr2
- self.assertTrue('info' in diff2._optinfo)
- self.assertTrue(diff2._optinfo['info'] == 'test')
+ assert_('info' in diff2._optinfo)
+ assert_(diff2._optinfo['info'] == 'test')
###############################################################################
diff --git a/numpy/matrixlib/tests/test_defmatrix.py b/numpy/matrixlib/tests/test_defmatrix.py
index fd36d77..e4c3c49 100644
--- a/numpy/matrixlib/tests/test_defmatrix.py
+++ b/numpy/matrixlib/tests/test_defmatrix.py
@@ -5,13 +5,13 @@
import numpy as np
from numpy import matrix, asmatrix, bmat
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_equal, assert_almost_equal,
+ run_module_suite, assert_, assert_equal, assert_almost_equal,
assert_array_equal, assert_array_almost_equal, assert_raises
)
from numpy.matrixlib.defmatrix import matrix_power
from numpy.matrixlib import mat
-class TestCtor(TestCase):
+class TestCtor(object):
def test_basic(self):
A = np.array([[1, 2], [3, 4]])
mA = matrix(A)
@@ -58,7 +58,7 @@
assert_(np.all(b2 == mixresult))
-class TestProperties(TestCase):
+class TestProperties(object):
def test_sum(self):
"""Test whether matrix.sum(axis=1) preserves orientation.
Fails in NumPy <= 0.9.6.2127.
@@ -191,7 +191,7 @@
B = matrix([[True], [True], [False]])
assert_array_equal(A, B)
-class TestCasting(TestCase):
+class TestCasting(object):
def test_basic(self):
A = np.arange(100).reshape(10, 10)
mA = matrix(A)
@@ -210,7 +210,7 @@
assert_(np.all(mA != mB))
-class TestAlgebra(TestCase):
+class TestAlgebra(object):
def test_basic(self):
import numpy.linalg as linalg
@@ -271,7 +271,7 @@
self.fail("matrix.__mul__ with non-numeric object doesn't raise"
"a TypeError")
-class TestMatrixReturn(TestCase):
+class TestMatrixReturn(object):
def test_instance_methods(self):
a = matrix([1.0], dtype='f8')
methodargs = {
@@ -313,7 +313,7 @@
assert_(type(d) is np.ndarray)
-class TestIndexing(TestCase):
+class TestIndexing(object):
def test_basic(self):
x = asmatrix(np.zeros((3, 2), float))
y = np.zeros((3, 1), float)
@@ -322,9 +322,8 @@
assert_equal(x, [[0, 1], [0, 0], [0, 0]])
-class TestNewScalarIndexing(TestCase):
- def setUp(self):
- self.a = matrix([[1, 2], [3, 4]])
+class TestNewScalarIndexing(object):
+ a = matrix([[1, 2], [3, 4]])
def test_dimesions(self):
a = self.a
@@ -390,7 +389,7 @@
assert_array_equal(x[[2, 1, 0],:], x[::-1,:])
-class TestPower(TestCase):
+class TestPower(object):
def test_returntype(self):
a = np.array([[0, 1], [0, 0]])
assert_(type(matrix_power(a, 2)) is np.ndarray)
@@ -401,10 +400,10 @@
assert_array_equal(matrix_power([[0, 1], [0, 0]], 2), [[0, 0], [0, 0]])
-class TestShape(TestCase):
- def setUp(self):
- self.a = np.array([[1], [2]])
- self.m = matrix([[1], [2]])
+class TestShape(object):
+
+ a = np.array([[1], [2]])
+ m = matrix([[1], [2]])
def test_shape(self):
assert_equal(self.a.shape, (2, 1))
diff --git a/numpy/matrixlib/tests/test_multiarray.py b/numpy/matrixlib/tests/test_multiarray.py
index d27e24e..bf891a1 100644
--- a/numpy/matrixlib/tests/test_multiarray.py
+++ b/numpy/matrixlib/tests/test_multiarray.py
@@ -2,10 +2,10 @@
import numpy as np
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_equal, assert_array_equal
+ run_module_suite, assert_, assert_equal, assert_array_equal
)
-class TestView(TestCase):
+class TestView(object):
def test_type(self):
x = np.array([1, 2, 3])
assert_(isinstance(x.view(np.matrix), np.matrix))
diff --git a/numpy/matrixlib/tests/test_numeric.py b/numpy/matrixlib/tests/test_numeric.py
index 28329da..b826b8e 100644
--- a/numpy/matrixlib/tests/test_numeric.py
+++ b/numpy/matrixlib/tests/test_numeric.py
@@ -1,9 +1,9 @@
from __future__ import division, absolute_import, print_function
import numpy as np
-from numpy.testing import assert_equal, TestCase, run_module_suite
+from numpy.testing import assert_equal, run_module_suite
-class TestDot(TestCase):
+class TestDot(object):
def test_matscalar(self):
b1 = np.matrix(np.ones((3, 3), dtype=complex))
assert_equal(b1*1.0, b1)
diff --git a/numpy/matrixlib/tests/test_regression.py b/numpy/matrixlib/tests/test_regression.py
index 0839fbf..b681374 100644
--- a/numpy/matrixlib/tests/test_regression.py
+++ b/numpy/matrixlib/tests/test_regression.py
@@ -1,11 +1,13 @@
from __future__ import division, absolute_import, print_function
import numpy as np
-from numpy.testing import TestCase, run_module_suite, assert_, assert_equal
+from numpy.testing import (
+ run_module_suite, assert_, assert_equal, assert_raises
+ )
rlevel = 1
-class TestRegression(TestCase):
+class TestRegression(object):
def test_kron_matrix(self, level=rlevel):
# Ticket #71
x = np.matrix('[1 0; 1 0]')
@@ -25,13 +27,13 @@
def mul():
np.mat(np.eye(2))*np.ones(2)
- self.assertRaises(ValueError, mul)
+ assert_raises(ValueError, mul)
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, ())
+ assert_equal(x.std().shape, ())
+ assert_equal(x.argmax().shape, ())
if __name__ == "__main__":
run_module_suite()
diff --git a/numpy/polynomial/tests/test_chebyshev.py b/numpy/polynomial/tests/test_chebyshev.py
index dc0cd14..2e43447 100644
--- a/numpy/polynomial/tests/test_chebyshev.py
+++ b/numpy/polynomial/tests/test_chebyshev.py
@@ -7,8 +7,9 @@
import numpy.polynomial.chebyshev as cheb
from numpy.polynomial.polynomial import polyval
from numpy.testing import (
- TestCase, assert_almost_equal, assert_raises,
- assert_equal, assert_, run_module_suite)
+ assert_almost_equal, assert_raises, assert_equal, assert_,
+ run_module_suite
+ )
def trim(x):
@@ -28,7 +29,7 @@
Tlist = [T0, T1, T2, T3, T4, T5, T6, T7, T8, T9]
-class TestPrivate(TestCase):
+class TestPrivate(object):
def test__cseries_to_zseries(self):
for i in range(5):
@@ -45,7 +46,7 @@
assert_equal(res, tgt)
-class TestConstants(TestCase):
+class TestConstants(object):
def test_chebdomain(self):
assert_equal(cheb.chebdomain, [-1, 1])
@@ -60,7 +61,7 @@
assert_equal(cheb.chebx, [0, 1])
-class TestArithmetic(TestCase):
+class TestArithmetic(object):
def test_chebadd(self):
for i in range(5):
@@ -112,7 +113,7 @@
assert_equal(trim(res), trim(tgt), err_msg=msg)
-class TestEvaluation(TestCase):
+class TestEvaluation(object):
# coefficients of 1 + 2*x + 3*x**2
c1d = np.array([2.5, 2., 1.5])
c2d = np.einsum('i,j->ij', c1d, c1d)
@@ -206,7 +207,7 @@
assert_(res.shape == (2, 3)*3)
-class TestIntegral(TestCase):
+class TestIntegral(object):
def test_chebint(self):
# check exceptions
@@ -305,7 +306,7 @@
assert_almost_equal(res, tgt)
-class TestDerivative(TestCase):
+class TestDerivative(object):
def test_chebder(self):
# check exceptions
@@ -345,7 +346,7 @@
assert_almost_equal(res, tgt)
-class TestVander(TestCase):
+class TestVander(object):
# some random values in [-1, 1)
x = np.random.random((3, 5))*2 - 1
@@ -393,7 +394,7 @@
assert_(van.shape == (1, 5, 24))
-class TestFitting(TestCase):
+class TestFitting(object):
def test_chebfit(self):
def f(x):
@@ -470,7 +471,7 @@
assert_almost_equal(coef1, coef2)
-class TestCompanion(TestCase):
+class TestCompanion(object):
def test_raises(self):
assert_raises(ValueError, cheb.chebcompanion, [])
@@ -485,7 +486,7 @@
assert_(cheb.chebcompanion([1, 2])[0, 0] == -.5)
-class TestGauss(TestCase):
+class TestGauss(object):
def test_100(self):
x, w = cheb.chebgauss(100)
@@ -504,7 +505,7 @@
assert_almost_equal(w.sum(), tgt)
-class TestMisc(TestCase):
+class TestMisc(object):
def test_chebfromroots(self):
res = cheb.chebfromroots([])
diff --git a/numpy/polynomial/tests/test_hermite.py b/numpy/polynomial/tests/test_hermite.py
index 06ce46a..2e39d85 100644
--- a/numpy/polynomial/tests/test_hermite.py
+++ b/numpy/polynomial/tests/test_hermite.py
@@ -7,8 +7,9 @@
import numpy.polynomial.hermite as herm
from numpy.polynomial.polynomial import polyval
from numpy.testing import (
- TestCase, assert_almost_equal, assert_raises,
- assert_equal, assert_, run_module_suite)
+ assert_almost_equal, assert_raises, assert_equal, assert_,
+ run_module_suite
+ )
H0 = np.array([1])
H1 = np.array([0, 2])
@@ -28,7 +29,7 @@
return herm.hermtrim(x, tol=1e-6)
-class TestConstants(TestCase):
+class TestConstants(object):
def test_hermdomain(self):
assert_equal(herm.hermdomain, [-1, 1])
@@ -43,7 +44,7 @@
assert_equal(herm.hermx, [0, .5])
-class TestArithmetic(TestCase):
+class TestArithmetic(object):
x = np.linspace(-3, 3, 100)
def test_hermadd(self):
@@ -100,7 +101,7 @@
assert_equal(trim(res), trim(tgt), err_msg=msg)
-class TestEvaluation(TestCase):
+class TestEvaluation(object):
# coefficients of 1 + 2*x + 3*x**2
c1d = np.array([2.5, 1., .75])
c2d = np.einsum('i,j->ij', c1d, c1d)
@@ -194,7 +195,7 @@
assert_(res.shape == (2, 3)*3)
-class TestIntegral(TestCase):
+class TestIntegral(object):
def test_hermint(self):
# check exceptions
@@ -293,7 +294,7 @@
assert_almost_equal(res, tgt)
-class TestDerivative(TestCase):
+class TestDerivative(object):
def test_hermder(self):
# check exceptions
@@ -333,7 +334,7 @@
assert_almost_equal(res, tgt)
-class TestVander(TestCase):
+class TestVander(object):
# some random values in [-1, 1)
x = np.random.random((3, 5))*2 - 1
@@ -381,7 +382,7 @@
assert_(van.shape == (1, 5, 24))
-class TestFitting(TestCase):
+class TestFitting(object):
def test_hermfit(self):
def f(x):
@@ -458,7 +459,7 @@
assert_almost_equal(coef1, coef2)
-class TestCompanion(TestCase):
+class TestCompanion(object):
def test_raises(self):
assert_raises(ValueError, herm.hermcompanion, [])
@@ -473,7 +474,7 @@
assert_(herm.hermcompanion([1, 2])[0, 0] == -.25)
-class TestGauss(TestCase):
+class TestGauss(object):
def test_100(self):
x, w = herm.hermgauss(100)
@@ -492,7 +493,7 @@
assert_almost_equal(w.sum(), tgt)
-class TestMisc(TestCase):
+class TestMisc(object):
def test_hermfromroots(self):
res = herm.hermfromroots([])
diff --git a/numpy/polynomial/tests/test_hermite_e.py b/numpy/polynomial/tests/test_hermite_e.py
index 38da325..a819107 100644
--- a/numpy/polynomial/tests/test_hermite_e.py
+++ b/numpy/polynomial/tests/test_hermite_e.py
@@ -7,8 +7,9 @@
import numpy.polynomial.hermite_e as herme
from numpy.polynomial.polynomial import polyval
from numpy.testing import (
- TestCase, assert_almost_equal, assert_raises,
- assert_equal, assert_, run_module_suite)
+ assert_almost_equal, assert_raises, assert_equal, assert_,
+ run_module_suite
+ )
He0 = np.array([1])
He1 = np.array([0, 1])
@@ -28,7 +29,7 @@
return herme.hermetrim(x, tol=1e-6)
-class TestConstants(TestCase):
+class TestConstants(object):
def test_hermedomain(self):
assert_equal(herme.hermedomain, [-1, 1])
@@ -43,7 +44,7 @@
assert_equal(herme.hermex, [0, 1])
-class TestArithmetic(TestCase):
+class TestArithmetic(object):
x = np.linspace(-3, 3, 100)
def test_hermeadd(self):
@@ -100,7 +101,7 @@
assert_equal(trim(res), trim(tgt), err_msg=msg)
-class TestEvaluation(TestCase):
+class TestEvaluation(object):
# coefficients of 1 + 2*x + 3*x**2
c1d = np.array([4., 2., 3.])
c2d = np.einsum('i,j->ij', c1d, c1d)
@@ -194,7 +195,7 @@
assert_(res.shape == (2, 3)*3)
-class TestIntegral(TestCase):
+class TestIntegral(object):
def test_hermeint(self):
# check exceptions
@@ -293,7 +294,7 @@
assert_almost_equal(res, tgt)
-class TestDerivative(TestCase):
+class TestDerivative(object):
def test_hermeder(self):
# check exceptions
@@ -334,7 +335,7 @@
assert_almost_equal(res, tgt)
-class TestVander(TestCase):
+class TestVander(object):
# some random values in [-1, 1)
x = np.random.random((3, 5))*2 - 1
@@ -382,7 +383,7 @@
assert_(van.shape == (1, 5, 24))
-class TestFitting(TestCase):
+class TestFitting(object):
def test_hermefit(self):
def f(x):
@@ -459,7 +460,7 @@
assert_almost_equal(coef1, coef2)
-class TestCompanion(TestCase):
+class TestCompanion(object):
def test_raises(self):
assert_raises(ValueError, herme.hermecompanion, [])
@@ -474,7 +475,7 @@
assert_(herme.hermecompanion([1, 2])[0, 0] == -.5)
-class TestGauss(TestCase):
+class TestGauss(object):
def test_100(self):
x, w = herme.hermegauss(100)
@@ -493,7 +494,7 @@
assert_almost_equal(w.sum(), tgt)
-class TestMisc(TestCase):
+class TestMisc(object):
def test_hermefromroots(self):
res = herme.hermefromroots([])
diff --git a/numpy/polynomial/tests/test_laguerre.py b/numpy/polynomial/tests/test_laguerre.py
index 0fa76b4..17a3f75 100644
--- a/numpy/polynomial/tests/test_laguerre.py
+++ b/numpy/polynomial/tests/test_laguerre.py
@@ -7,8 +7,9 @@
import numpy.polynomial.laguerre as lag
from numpy.polynomial.polynomial import polyval
from numpy.testing import (
- TestCase, assert_almost_equal, assert_raises,
- assert_equal, assert_, run_module_suite)
+ assert_almost_equal, assert_raises, assert_equal, assert_,
+ run_module_suite
+ )
L0 = np.array([1])/1
L1 = np.array([1, -1])/1
@@ -25,7 +26,7 @@
return lag.lagtrim(x, tol=1e-6)
-class TestConstants(TestCase):
+class TestConstants(object):
def test_lagdomain(self):
assert_equal(lag.lagdomain, [0, 1])
@@ -40,7 +41,7 @@
assert_equal(lag.lagx, [1, -1])
-class TestArithmetic(TestCase):
+class TestArithmetic(object):
x = np.linspace(-3, 3, 100)
def test_lagadd(self):
@@ -97,7 +98,7 @@
assert_almost_equal(trim(res), trim(tgt), err_msg=msg)
-class TestEvaluation(TestCase):
+class TestEvaluation(object):
# coefficients of 1 + 2*x + 3*x**2
c1d = np.array([9., -14., 6.])
c2d = np.einsum('i,j->ij', c1d, c1d)
@@ -191,7 +192,7 @@
assert_(res.shape == (2, 3)*3)
-class TestIntegral(TestCase):
+class TestIntegral(object):
def test_lagint(self):
# check exceptions
@@ -290,7 +291,7 @@
assert_almost_equal(res, tgt)
-class TestDerivative(TestCase):
+class TestDerivative(object):
def test_lagder(self):
# check exceptions
@@ -330,7 +331,7 @@
assert_almost_equal(res, tgt)
-class TestVander(TestCase):
+class TestVander(object):
# some random values in [-1, 1)
x = np.random.random((3, 5))*2 - 1
@@ -378,7 +379,7 @@
assert_(van.shape == (1, 5, 24))
-class TestFitting(TestCase):
+class TestFitting(object):
def test_lagfit(self):
def f(x):
@@ -440,7 +441,7 @@
assert_almost_equal(lag.lagfit(x, x, [0, 1]), [1, -1])
-class TestCompanion(TestCase):
+class TestCompanion(object):
def test_raises(self):
assert_raises(ValueError, lag.lagcompanion, [])
@@ -455,7 +456,7 @@
assert_(lag.lagcompanion([1, 2])[0, 0] == 1.5)
-class TestGauss(TestCase):
+class TestGauss(object):
def test_100(self):
x, w = lag.laggauss(100)
@@ -474,7 +475,7 @@
assert_almost_equal(w.sum(), tgt)
-class TestMisc(TestCase):
+class TestMisc(object):
def test_lagfromroots(self):
res = lag.lagfromroots([])
diff --git a/numpy/polynomial/tests/test_legendre.py b/numpy/polynomial/tests/test_legendre.py
index 485bc96..375f41d 100644
--- a/numpy/polynomial/tests/test_legendre.py
+++ b/numpy/polynomial/tests/test_legendre.py
@@ -7,8 +7,9 @@
import numpy.polynomial.legendre as leg
from numpy.polynomial.polynomial import polyval
from numpy.testing import (
- TestCase, assert_almost_equal, assert_raises,
- assert_equal, assert_, run_module_suite)
+ assert_almost_equal, assert_raises, assert_equal, assert_,
+ run_module_suite
+ )
L0 = np.array([1])
L1 = np.array([0, 1])
@@ -28,7 +29,7 @@
return leg.legtrim(x, tol=1e-6)
-class TestConstants(TestCase):
+class TestConstants(object):
def test_legdomain(self):
assert_equal(leg.legdomain, [-1, 1])
@@ -43,7 +44,7 @@
assert_equal(leg.legx, [0, 1])
-class TestArithmetic(TestCase):
+class TestArithmetic(object):
x = np.linspace(-1, 1, 100)
def test_legadd(self):
@@ -101,7 +102,7 @@
assert_equal(trim(res), trim(tgt), err_msg=msg)
-class TestEvaluation(TestCase):
+class TestEvaluation(object):
# coefficients of 1 + 2*x + 3*x**2
c1d = np.array([2., 2., 2.])
c2d = np.einsum('i,j->ij', c1d, c1d)
@@ -195,7 +196,7 @@
assert_(res.shape == (2, 3)*3)
-class TestIntegral(TestCase):
+class TestIntegral(object):
def test_legint(self):
# check exceptions
@@ -294,7 +295,7 @@
assert_almost_equal(res, tgt)
-class TestDerivative(TestCase):
+class TestDerivative(object):
def test_legder(self):
# check exceptions
@@ -334,7 +335,7 @@
assert_almost_equal(res, tgt)
-class TestVander(TestCase):
+class TestVander(object):
# some random values in [-1, 1)
x = np.random.random((3, 5))*2 - 1
@@ -382,7 +383,7 @@
assert_(van.shape == (1, 5, 24))
-class TestFitting(TestCase):
+class TestFitting(object):
def test_legfit(self):
def f(x):
@@ -459,7 +460,7 @@
assert_almost_equal(coef1, coef2)
-class TestCompanion(TestCase):
+class TestCompanion(object):
def test_raises(self):
assert_raises(ValueError, leg.legcompanion, [])
@@ -474,7 +475,7 @@
assert_(leg.legcompanion([1, 2])[0, 0] == -.5)
-class TestGauss(TestCase):
+class TestGauss(object):
def test_100(self):
x, w = leg.leggauss(100)
@@ -493,7 +494,7 @@
assert_almost_equal(w.sum(), tgt)
-class TestMisc(TestCase):
+class TestMisc(object):
def test_legfromroots(self):
res = leg.legfromroots([])
diff --git a/numpy/polynomial/tests/test_polynomial.py b/numpy/polynomial/tests/test_polynomial.py
index 037be59..bf6c5e8 100644
--- a/numpy/polynomial/tests/test_polynomial.py
+++ b/numpy/polynomial/tests/test_polynomial.py
@@ -6,8 +6,9 @@
import numpy as np
import numpy.polynomial.polynomial as poly
from numpy.testing import (
- TestCase, assert_almost_equal, assert_raises,
- assert_equal, assert_, run_module_suite)
+ assert_almost_equal, assert_raises, assert_equal, assert_,
+ run_module_suite
+ )
def trim(x):
@@ -27,7 +28,7 @@
Tlist = [T0, T1, T2, T3, T4, T5, T6, T7, T8, T9]
-class TestConstants(TestCase):
+class TestConstants(object):
def test_polydomain(self):
assert_equal(poly.polydomain, [-1, 1])
@@ -42,7 +43,7 @@
assert_equal(poly.polyx, [0, 1])
-class TestArithmetic(TestCase):
+class TestArithmetic(object):
def test_polyadd(self):
for i in range(5):
@@ -103,7 +104,7 @@
assert_equal(res, tgt, err_msg=msg)
-class TestEvaluation(TestCase):
+class TestEvaluation(object):
# coefficients of 1 + 2*x + 3*x**2
c1d = np.array([1., 2., 3.])
c2d = np.einsum('i,j->ij', c1d, c1d)
@@ -263,7 +264,7 @@
assert_(res.shape == (2, 3)*3)
-class TestIntegral(TestCase):
+class TestIntegral(object):
def test_polyint(self):
# check exceptions
@@ -357,7 +358,7 @@
assert_almost_equal(res, tgt)
-class TestDerivative(TestCase):
+class TestDerivative(object):
def test_polyder(self):
# check exceptions
@@ -397,7 +398,7 @@
assert_almost_equal(res, tgt)
-class TestVander(TestCase):
+class TestVander(object):
# some random values in [-1, 1)
x = np.random.random((3, 5))*2 - 1
@@ -445,7 +446,7 @@
assert_(van.shape == (1, 5, 24))
-class TestCompanion(TestCase):
+class TestCompanion(object):
def test_raises(self):
assert_raises(ValueError, poly.polycompanion, [])
@@ -460,7 +461,7 @@
assert_(poly.polycompanion([1, 2])[0, 0] == -.5)
-class TestMisc(TestCase):
+class TestMisc(object):
def test_polyfromroots(self):
res = poly.polyfromroots([])
diff --git a/numpy/polynomial/tests/test_polyutils.py b/numpy/polynomial/tests/test_polyutils.py
index 974e2e0..bd1cb20 100644
--- a/numpy/polynomial/tests/test_polyutils.py
+++ b/numpy/polynomial/tests/test_polyutils.py
@@ -6,11 +6,12 @@
import numpy as np
import numpy.polynomial.polyutils as pu
from numpy.testing import (
- TestCase, assert_almost_equal, assert_raises,
- assert_equal, assert_, run_module_suite)
+ assert_almost_equal, assert_raises, assert_equal, assert_,
+ run_module_suite
+ )
-class TestMisc(TestCase):
+class TestMisc(object):
def test_trimseq(self):
for i in range(5):
@@ -43,7 +44,7 @@
assert_equal(pu.trimcoef(coef, 2), [0])
-class TestDomain(TestCase):
+class TestDomain(object):
def test_getdomain(self):
# test for real values
diff --git a/numpy/polynomial/tests/test_printing.py b/numpy/polynomial/tests/test_printing.py
index 86cd257..52604c0 100644
--- a/numpy/polynomial/tests/test_printing.py
+++ b/numpy/polynomial/tests/test_printing.py
@@ -1,10 +1,10 @@
from __future__ import division, absolute_import, print_function
import numpy.polynomial as poly
-from numpy.testing import TestCase, run_module_suite, assert_
+from numpy.testing import run_module_suite, assert_
-class test_str(TestCase):
+class TestStr(object):
def test_polynomial_str(self):
res = str(poly.Polynomial([0, 1]))
tgt = 'poly([0., 1.])'
@@ -36,7 +36,7 @@
assert_(res, tgt)
-class test_repr(TestCase):
+class TestRepr(object):
def test_polynomial_str(self):
res = repr(poly.Polynomial([0, 1]))
tgt = 'Polynomial([0., 1.])'
diff --git a/numpy/random/tests/test_random.py b/numpy/random/tests/test_random.py
index 0e73964..9b41f6f 100644
--- a/numpy/random/tests/test_random.py
+++ b/numpy/random/tests/test_random.py
@@ -3,15 +3,16 @@
import numpy as np
from numpy.testing import (
- TestCase, run_module_suite, assert_, assert_raises, assert_equal,
- assert_warns, assert_no_warnings, assert_array_equal,
- assert_array_almost_equal, suppress_warnings)
+ run_module_suite, assert_, assert_raises, assert_equal, assert_warns,
+ assert_no_warnings, assert_array_equal, assert_array_almost_equal,
+ suppress_warnings
+ )
from numpy import random
import sys
import warnings
-class TestSeed(TestCase):
+class TestSeed(object):
def test_scalar(self):
s = np.random.RandomState(0)
assert_equal(s.randint(1000), 684)
@@ -42,7 +43,7 @@
assert_raises(ValueError, np.random.RandomState, [1, -2, 4294967296])
-class TestBinomial(TestCase):
+class TestBinomial(object):
def test_n_zero(self):
# Tests the corner case of n == 0 for the binomial distribution.
# binomial(0, p) should be zero for any p in [0, 1].
@@ -57,7 +58,7 @@
assert_raises(ValueError, random.binomial, 1, np.nan)
-class TestMultinomial(TestCase):
+class TestMultinomial(object):
def test_basic(self):
random.multinomial(100, [0.2, 0.8])
@@ -85,8 +86,8 @@
np.float(1))
-class TestSetState(TestCase):
- def setUp(self):
+class TestSetState(object):
+ def setup(self):
self.seed = 1234567890
self.prng = random.RandomState(self.seed)
self.state = self.prng.get_state()
@@ -133,7 +134,7 @@
self.prng.negative_binomial(0.5, 0.5)
-class TestRandint(TestCase):
+class TestRandint(object):
rfunc = np.random.randint
@@ -259,7 +260,7 @@
ubnd = 2 if dt is np.bool_ else np.iinfo(dt).max + 1
sample = self.rfunc(lbnd, ubnd, dtype=dt)
- self.assertEqual(sample.dtype, np.dtype(dt))
+ assert_equal(sample.dtype, np.dtype(dt))
for dt in (np.bool, np.int, np.long):
lbnd = 0 if dt is np.bool else np.iinfo(dt).min
@@ -267,15 +268,15 @@
# gh-7284: Ensure that we get Python data types
sample = self.rfunc(lbnd, ubnd, dtype=dt)
- self.assertFalse(hasattr(sample, 'dtype'))
- self.assertEqual(type(sample), dt)
+ assert_(not hasattr(sample, 'dtype'))
+ assert_equal(type(sample), dt)
-class TestRandomDist(TestCase):
+class TestRandomDist(object):
# Make sure the random distribution returns the correct value for a
# given seed
- def setUp(self):
+ def setup(self):
self.seed = 1234567890
def test_rand(self):
@@ -929,10 +930,10 @@
assert_array_equal(actual, desired)
-class TestBroadcast(TestCase):
+class TestBroadcast(object):
# tests that functions that broadcast behave
# correctly when presented with non-scalar arguments
- def setUp(self):
+ def setup(self):
self.seed = 123456789
def setSeed(self):
@@ -1484,9 +1485,9 @@
assert_raises(ValueError, logseries, bad_p_one * 3)
assert_raises(ValueError, logseries, bad_p_two * 3)
-class TestThread(TestCase):
+class TestThread(object):
# make sure each state produces the same sequence even in threads
- def setUp(self):
+ def setup(self):
self.seeds = range(4)
def check_function(self, function, sz):
@@ -1527,8 +1528,8 @@
self.check_function(gen_random, sz=(10000, 6))
# See Issue #4263
-class TestSingleEltArrayInput(TestCase):
- def setUp(self):
+class TestSingleEltArrayInput(object):
+ def setup(self):
self.argOne = np.array([2])
self.argTwo = np.array([3])
self.argThree = np.array([4])
@@ -1551,7 +1552,7 @@
else:
out = func(self.argOne)
- self.assertEqual(out.shape, self.tgtShape)
+ assert_equal(out.shape, self.tgtShape)
def test_two_arg_funcs(self):
funcs = (np.random.uniform, np.random.normal,
@@ -1572,13 +1573,13 @@
argTwo = self.argTwo
out = func(self.argOne, argTwo)
- self.assertEqual(out.shape, self.tgtShape)
+ assert_equal(out.shape, self.tgtShape)
out = func(self.argOne[0], argTwo)
- self.assertEqual(out.shape, self.tgtShape)
+ assert_equal(out.shape, self.tgtShape)
out = func(self.argOne, argTwo[0])
- self.assertEqual(out.shape, self.tgtShape)
+ assert_equal(out.shape, self.tgtShape)
# TODO: Uncomment once randint can broadcast arguments
# def test_randint(self):
@@ -1604,13 +1605,13 @@
for func in funcs:
out = func(self.argOne, self.argTwo, self.argThree)
- self.assertEqual(out.shape, self.tgtShape)
+ assert_equal(out.shape, self.tgtShape)
out = func(self.argOne[0], self.argTwo, self.argThree)
- self.assertEqual(out.shape, self.tgtShape)
+ assert_equal(out.shape, self.tgtShape)
out = func(self.argOne, self.argTwo[0], self.argThree)
- self.assertEqual(out.shape, self.tgtShape)
+ assert_equal(out.shape, self.tgtShape)
if __name__ == "__main__":
run_module_suite()
diff --git a/numpy/random/tests/test_regression.py b/numpy/random/tests/test_regression.py
index ce435b3..572f4c0 100644
--- a/numpy/random/tests/test_regression.py
+++ b/numpy/random/tests/test_regression.py
@@ -1,14 +1,15 @@
from __future__ import division, absolute_import, print_function
import sys
-from numpy.testing import (TestCase, run_module_suite, assert_,
- assert_array_equal, assert_raises)
+from numpy.testing import (
+ run_module_suite, assert_, assert_array_equal, assert_raises,
+ )
from numpy import random
from numpy.compat import long
import numpy as np
-class TestRegression(TestCase):
+class TestRegression(object):
def test_VonMises_range(self):
# Make sure generated random variables are in [-pi, pi].
diff --git a/numpy/tests/test_ctypeslib.py b/numpy/tests/test_ctypeslib.py
index 2c58f11..e8043d0 100644
--- a/numpy/tests/test_ctypeslib.py
+++ b/numpy/tests/test_ctypeslib.py
@@ -5,7 +5,7 @@
import numpy as np
from numpy.ctypeslib import ndpointer, load_library
from numpy.distutils.misc_util import get_shared_lib_extension
-from numpy.testing import TestCase, run_module_suite, dec
+from numpy.testing import run_module_suite, assert_, assert_raises, dec
try:
cdll = None
@@ -20,7 +20,7 @@
except ImportError:
_HAS_CTYPE = False
-class TestLoadLibrary(TestCase):
+class TestLoadLibrary(object):
@dec.skipif(not _HAS_CTYPE,
"ctypes not available on this python installation")
@dec.knownfailureif(sys.platform ==
@@ -53,65 +53,65 @@
" (import error was: %s)" % str(e))
print(msg)
-class TestNdpointer(TestCase):
+class TestNdpointer(object):
def test_dtype(self):
dt = np.intc
p = ndpointer(dtype=dt)
- self.assertTrue(p.from_param(np.array([1], dt)))
+ assert_(p.from_param(np.array([1], dt)))
dt = '<i4'
p = ndpointer(dtype=dt)
- self.assertTrue(p.from_param(np.array([1], dt)))
+ assert_(p.from_param(np.array([1], dt)))
dt = np.dtype('>i4')
p = ndpointer(dtype=dt)
p.from_param(np.array([1], dt))
- self.assertRaises(TypeError, p.from_param,
+ assert_raises(TypeError, p.from_param,
np.array([1], dt.newbyteorder('swap')))
dtnames = ['x', 'y']
dtformats = [np.intc, np.float64]
dtdescr = {'names': dtnames, 'formats': dtformats}
dt = np.dtype(dtdescr)
p = ndpointer(dtype=dt)
- self.assertTrue(p.from_param(np.zeros((10,), dt)))
+ assert_(p.from_param(np.zeros((10,), dt)))
samedt = np.dtype(dtdescr)
p = ndpointer(dtype=samedt)
- self.assertTrue(p.from_param(np.zeros((10,), dt)))
+ assert_(p.from_param(np.zeros((10,), dt)))
dt2 = np.dtype(dtdescr, align=True)
if dt.itemsize != dt2.itemsize:
- self.assertRaises(TypeError, p.from_param, np.zeros((10,), dt2))
+ assert_raises(TypeError, p.from_param, np.zeros((10,), dt2))
else:
- self.assertTrue(p.from_param(np.zeros((10,), dt2)))
+ assert_(p.from_param(np.zeros((10,), dt2)))
def test_ndim(self):
p = ndpointer(ndim=0)
- self.assertTrue(p.from_param(np.array(1)))
- self.assertRaises(TypeError, p.from_param, np.array([1]))
+ assert_(p.from_param(np.array(1)))
+ assert_raises(TypeError, p.from_param, np.array([1]))
p = ndpointer(ndim=1)
- self.assertRaises(TypeError, p.from_param, np.array(1))
- self.assertTrue(p.from_param(np.array([1])))
+ assert_raises(TypeError, p.from_param, np.array(1))
+ assert_(p.from_param(np.array([1])))
p = ndpointer(ndim=2)
- self.assertTrue(p.from_param(np.array([[1]])))
+ assert_(p.from_param(np.array([[1]])))
def test_shape(self):
p = ndpointer(shape=(1, 2))
- self.assertTrue(p.from_param(np.array([[1, 2]])))
- self.assertRaises(TypeError, p.from_param, np.array([[1], [2]]))
+ assert_(p.from_param(np.array([[1, 2]])))
+ assert_raises(TypeError, p.from_param, np.array([[1], [2]]))
p = ndpointer(shape=())
- self.assertTrue(p.from_param(np.array(1)))
+ assert_(p.from_param(np.array(1)))
def test_flags(self):
x = np.array([[1, 2], [3, 4]], order='F')
p = ndpointer(flags='FORTRAN')
- self.assertTrue(p.from_param(x))
+ assert_(p.from_param(x))
p = ndpointer(flags='CONTIGUOUS')
- self.assertRaises(TypeError, p.from_param, x)
+ assert_raises(TypeError, p.from_param, x)
p = ndpointer(flags=x.flags.num)
- self.assertTrue(p.from_param(x))
- self.assertRaises(TypeError, p.from_param, np.array([[1, 2], [3, 4]]))
+ assert_(p.from_param(x))
+ assert_raises(TypeError, p.from_param, np.array([[1, 2], [3, 4]]))
def test_cache(self):
a1 = ndpointer(dtype=np.float64)
a2 = ndpointer(dtype=np.float64)
- self.assertEqual(a1, a2)
+ assert_(a1 == a2)
if __name__ == "__main__":