diff options
Diffstat (limited to 'numpy/lib/tests')
-rw-r--r-- | numpy/lib/tests/__init__.py | 0 | ||||
-rw-r--r-- | numpy/lib/tests/test__datasource.py | 70 | ||||
-rw-r--r-- | numpy/lib/tests/test__iotools.py | 13 | ||||
-rw-r--r-- | numpy/lib/tests/test_arraypad.py | 48 | ||||
-rw-r--r-- | numpy/lib/tests/test_arraysetops.py | 26 | ||||
-rw-r--r-- | numpy/lib/tests/test_financial.py | 6 | ||||
-rw-r--r-- | numpy/lib/tests/test_format.py | 9 | ||||
-rw-r--r-- | numpy/lib/tests/test_function_base.py | 268 | ||||
-rw-r--r-- | numpy/lib/tests/test_index_tricks.py | 20 | ||||
-rw-r--r-- | numpy/lib/tests/test_io.py | 82 | ||||
-rw-r--r-- | numpy/lib/tests/test_mixins.py | 5 | ||||
-rw-r--r-- | numpy/lib/tests/test_nanfunctions.py | 18 | ||||
-rw-r--r-- | numpy/lib/tests/test_polynomial.py | 4 | ||||
-rw-r--r-- | numpy/lib/tests/test_recfunctions.py | 139 | ||||
-rw-r--r-- | numpy/lib/tests/test_regression.py | 71 | ||||
-rw-r--r-- | numpy/lib/tests/test_shape_base.py | 73 | ||||
-rw-r--r-- | numpy/lib/tests/test_stride_tricks.py | 8 | ||||
-rw-r--r-- | numpy/lib/tests/test_twodim_base.py | 121 | ||||
-rw-r--r-- | numpy/lib/tests/test_type_check.py | 46 | ||||
-rw-r--r-- | numpy/lib/tests/test_ufunclike.py | 5 |
20 files changed, 631 insertions, 401 deletions
diff --git a/numpy/lib/tests/__init__.py b/numpy/lib/tests/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/numpy/lib/tests/__init__.py diff --git a/numpy/lib/tests/test__datasource.py b/numpy/lib/tests/test__datasource.py index f2ad0344a..a9cb157f3 100644 --- a/numpy/lib/tests/test__datasource.py +++ b/numpy/lib/tests/test__datasource.py @@ -6,7 +6,7 @@ from tempfile import mkdtemp, mkstemp, NamedTemporaryFile 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 @@ malicious_files = ['/etc/shadow', '../../shadow', 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 @@ def invalid_httpfile(): 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 @@ class TestDataSourceOpen(TestCase): 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 @@ class TestDataSourceOpen(TestCase): 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 @@ class TestDataSourceOpen(TestCase): 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 @@ class TestDataSourceOpen(TestCase): 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 @@ class TestDataSourceOpen(TestCase): 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 @@ class TestDataSourceExists(TestCase): 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 @@ class TestDataSourceExists(TestCase): 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 @@ class TestDataSourceAbspath(TestCase): 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 @@ class TestDataSourceAbspath(TestCase): 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 @@ class TestRepositoryAbspath(TestCase): 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 @@ class TestRepositoryAbspath(TestCase): 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 @@ class TestRepositoryExists(TestCase): 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 @@ class TestRepositoryExists(TestCase): 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 6c0b2c6db..03192896c 100644 --- a/numpy/lib/tests/test__iotools.py +++ b/numpy/lib/tests/test__iotools.py @@ -6,8 +6,7 @@ from datetime import date 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 @@ from numpy.lib._iotools import ( ) -class TestLineSplitter(TestCase): +class TestLineSplitter(object): "Tests the LineSplitter class." def test_no_delimiter(self): @@ -79,7 +78,7 @@ class TestLineSplitter(TestCase): # ----------------------------------------------------------------------------- -class TestNameValidator(TestCase): +class TestNameValidator(object): def test_case_sensitivity(self): "Test case sensitivity" @@ -140,7 +139,7 @@ def _bytes_to_date(s): return date(*time.strptime(s, "%Y-%m-%d")[:3]) -class TestStringConverter(TestCase): +class TestStringConverter(object): "Test StringConverter" def test_creation(self): @@ -254,11 +253,11 @@ class TestStringConverter(TestCase): assert_(converter(val) == 9223372043271415339) -class TestMiscFunctions(TestCase): +class TestMiscFunctions(object): def test_has_nested_dtype(self): "Test has_nested_dtype" - ndtype = np.dtype(np.float) + ndtype = np.dtype(float) assert_equal(has_nested_fields(ndtype), False) ndtype = np.dtype([('A', '|S3'), ('B', float)]) assert_equal(has_nested_fields(ndtype), False) diff --git a/numpy/lib/tests/test_arraypad.py b/numpy/lib/tests/test_arraypad.py index 056aa4582..fce4c451d 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 @@ class TestConditionalShortcuts(TestCase): 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 @@ class TestStatistic(TestCase): 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 @@ class TestConstant(TestCase): 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 @@ class TestLinearRamp(TestCase): 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') @@ -640,8 +639,13 @@ class TestReflect(TestCase): b = np.array([1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3]) assert_array_equal(a, b) + def test_check_padding_an_empty_array(self): + a = pad(np.zeros((0, 3)), ((0,), (1,)), mode='reflect') + b = np.zeros((0, 5)) + 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 +779,7 @@ class TestSymmetric(TestCase): 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 +875,7 @@ class TestWrap(TestCase): 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 +898,7 @@ class TestStatLen(TestCase): 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 +937,7 @@ class TestEdge(TestCase): 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 +945,7 @@ class TestZeroPadWidth(TestCase): 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 +967,7 @@ class TestLegacyVectorFunction(TestCase): 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 +988,7 @@ class TestNdarrayPadWidth(TestCase): 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 +996,7 @@ class TestUnicodeInput(TestCase): 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)) @@ -1014,8 +1018,14 @@ class ValueError1(TestCase): assert_raises(ValueError, pad, arr, ((-2, 3), (3, 2)), **kwargs) + def test_check_empty_array(self): + assert_raises(ValueError, pad, [], 4, mode='reflect') + assert_raises(ValueError, pad, np.ndarray(0), 4, mode='reflect') + assert_raises(ValueError, pad, np.zeros((0, 3)), ((1,), (0,)), + mode='reflect') + -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 +1034,7 @@ class ValueError2(TestCase): **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 +1062,7 @@ class ValueError3(TestCase): 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 fa664ff24..b8ced41e8 100644 --- a/numpy/lib/tests/test_arraysetops.py +++ b/numpy/lib/tests/test_arraysetops.py @@ -5,14 +5,14 @@ from __future__ import division, absolute_import, print_function 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 @@ class TestSetOps(TestCase): 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 @@ class TestSetOps(TestCase): assert_array_equal(c1, c2) -class TestUnique(TestCase): +class TestUnique(object): def test_unique_1d(self): @@ -355,6 +355,16 @@ class TestUnique(TestCase): a2, a2_inv = np.unique(a, return_inverse=True) assert_array_equal(a2_inv, np.zeros(5)) + # test for ticket #9137 + a = [] + a1_idx = np.unique(a, return_index=True)[1] + a2_inv = np.unique(a, return_inverse=True)[1] + a3_idx, a3_inv = np.unique(a, return_index=True, return_inverse=True)[1:] + assert_equal(a1_idx.dtype, np.intp) + assert_equal(a2_inv.dtype, np.intp) + assert_equal(a3_idx.dtype, np.intp) + assert_equal(a3_inv.dtype, np.intp) + def test_unique_axis_errors(self): assert_raises(TypeError, self._run_axis_tests, object) assert_raises(TypeError, self._run_axis_tests, diff --git a/numpy/lib/tests/test_financial.py b/numpy/lib/tests/test_financial.py index cc8ba55e5..4db364ad5 100644 --- a/numpy/lib/tests/test_financial.py +++ b/numpy/lib/tests/test_financial.py @@ -2,12 +2,12 @@ from __future__ import division, absolute_import, print_function 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_format.py b/numpy/lib/tests/test_format.py index 93727ef0c..2d2b4cea2 100644 --- a/numpy/lib/tests/test_format.py +++ b/numpy/lib/tests/test_format.py @@ -615,6 +615,11 @@ def test_version_2_0(): format.write_array(f, d) assert_(w[0].category is UserWarning) + # check alignment of data portion + f.seek(0) + header = f.readline() + assert_(len(header) % format.ARRAY_ALIGN == 0) + f.seek(0) n = format.read_array(f) assert_array_equal(d, n) @@ -758,6 +763,7 @@ def test_read_array_header_1_0(): s.seek(format.MAGIC_LEN) shape, fortran, dtype = format.read_array_header_1_0(s) + assert_(s.tell() % format.ARRAY_ALIGN == 0) assert_((shape, fortran, dtype) == ((3, 6), False, float)) @@ -770,6 +776,7 @@ def test_read_array_header_2_0(): s.seek(format.MAGIC_LEN) shape, fortran, dtype = format.read_array_header_2_0(s) + assert_(s.tell() % format.ARRAY_ALIGN == 0) assert_((shape, fortran, dtype) == ((3, 6), False, float)) @@ -811,7 +818,7 @@ def test_large_file_support(): # avoid actually writing 5GB import subprocess as sp sp.check_call(["truncate", "-s", "5368709120", tf_name]) - except: + except Exception: raise SkipTest("Could not create 5GB large file") # write a small array to the end with open(tf_name, "wb") as f: diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py index d7d00758e..c64081088 100644 --- a/numpy/lib/tests/test_function_base.py +++ b/numpy/lib/tests/test_function_base.py @@ -6,13 +6,13 @@ import sys import decimal import numpy as np +from numpy import ma 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 + assert_allclose, assert_array_max_ulp, assert_warns, assert_raises_regex, + dec, suppress_warnings, HAS_REFCOUNT, ) -from numpy.testing.utils import HAS_REFCOUNT import numpy.lib.function_base as nfb from numpy.random import rand from numpy.lib import ( @@ -32,9 +32,9 @@ def get_mat(n): 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)) @@ -100,12 +100,12 @@ class TestRot90(TestCase): 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) @@ -173,7 +173,7 @@ class TestFlip(TestCase): np.flipud(a.swapaxes(0, i)).swapaxes(i, 0)) -class TestAny(TestCase): +class TestAny(object): def test_basic(self): y1 = [0, 0, 1, 0] @@ -190,7 +190,7 @@ class TestAny(TestCase): 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] @@ -208,7 +208,7 @@ class TestAll(TestCase): 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]]) @@ -236,7 +236,7 @@ class TestCopy(TestCase): assert_(a_fort_copy.flags.f_contiguous) -class TestAverage(TestCase): +class TestAverage(object): def test_basic(self): y1 = np.array([1, 2, 3]) @@ -346,9 +346,9 @@ class TestAverage(TestCase): 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])] @@ -420,7 +420,7 @@ class TestSelect(TestCase): select(conditions, choices) -class TestInsert(TestCase): +class TestInsert(object): def test_basic(self): a = [1, 2, 3] @@ -521,7 +521,7 @@ class TestInsert(TestCase): 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] @@ -533,7 +533,7 @@ class TestAmax(TestCase): 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] @@ -545,7 +545,7 @@ class TestAmin(TestCase): 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]) @@ -557,7 +557,7 @@ class TestPtp(TestCase): 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] @@ -580,7 +580,7 @@ class TestCumsum(TestCase): 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] @@ -590,8 +590,8 @@ class TestProd(TestCase): 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), @@ -600,7 +600,7 @@ class TestProd(TestCase): np.array([24, 1890, 600], ctype)) -class TestCumprod(TestCase): +class TestCumprod(object): def test_basic(self): ba = [1, 2, 10, 11, 6, 5, 4] @@ -610,9 +610,9 @@ class TestCumprod(TestCase): 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, @@ -627,7 +627,7 @@ class TestCumprod(TestCase): [10, 30, 120, 600]], ctype)) -class TestDiff(TestCase): +class TestDiff(object): def test_basic(self): x = [1, 4, 6, 7, 12] @@ -638,6 +638,29 @@ class TestDiff(TestCase): assert_array_equal(diff(x, n=2), out2) assert_array_equal(diff(x, n=3), out3) + x = [1.1, 2.2, 3.0, -0.2, -0.1] + out = np.array([1.1, 0.8, -3.2, 0.1]) + assert_almost_equal(diff(x), out) + + x = [True, True, False, False] + out = np.array([False, True, False]) + out2 = np.array([True, True]) + assert_array_equal(diff(x), out) + assert_array_equal(diff(x, n=2), out2) + + def test_axis(self): + x = np.zeros((10, 20, 30)) + x[:, 1::2, :] = 1 + exp = np.ones((10, 19, 30)) + exp[:, 1::2, :] = -1 + assert_array_equal(diff(x), np.zeros((10, 20, 29))) + assert_array_equal(diff(x, axis=-1), np.zeros((10, 20, 29))) + assert_array_equal(diff(x, axis=0), np.zeros((9, 20, 30))) + assert_array_equal(diff(x, axis=1), exp) + assert_array_equal(diff(x, axis=-2), exp) + assert_raises(np.AxisError, diff, x, axis=3) + assert_raises(np.AxisError, diff, x, axis=-4) + def test_nd(self): x = 20 * rand(10, 20, 30) out1 = x[:, :, 1:] - x[:, :, :-1] @@ -649,10 +672,49 @@ class TestDiff(TestCase): assert_array_equal(diff(x, axis=0), out3) assert_array_equal(diff(x, n=2, axis=0), out4) + def test_n(self): + x = list(range(3)) + assert_raises(ValueError, diff, x, n=-1) + output = [diff(x, n=n) for n in range(1, 5)] + expected = [[1, 1], [0], [], []] + assert_(diff(x, n=0) is x) + for n, (expected, out) in enumerate(zip(expected, output), start=1): + assert_(type(out) is np.ndarray) + assert_array_equal(out, expected) + assert_equal(out.dtype, np.int_) + assert_equal(len(out), max(0, len(x) - n)) + + def test_times(self): + x = np.arange('1066-10-13', '1066-10-16', dtype=np.datetime64) + expected = [ + np.array([1, 1], dtype='timedelta64[D]'), + np.array([0], dtype='timedelta64[D]'), + ] + expected.extend([np.array([], dtype='timedelta64[D]')] * 3) + for n, exp in enumerate(expected, start=1): + out = diff(x, n=n) + assert_array_equal(out, exp) + assert_equal(out.dtype, exp.dtype) -class TestDelete(TestCase): + def test_subclass(self): + x = ma.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]], + mask=[[False, False], [True, False], + [False, True], [True, True], [False, False]]) + out = diff(x) + assert_array_equal(out.data, [[1], [1], [1], [1], [1]]) + assert_array_equal(out.mask, [[False], [True], + [True], [True], [False]]) + assert_(type(out) is type(x)) - def setUp(self): + out3 = diff(x, n=3) + assert_array_equal(out3.data, [[], [], [], [], []]) + assert_array_equal(out3.mask, [[], [], [], [], []]) + assert_(type(out3) is type(x)) + + +class TestDelete(object): + + def setup(self): self.a = np.arange(5) self.nd_a = np.arange(5).repeat(2).reshape(1, 5, 2) @@ -725,7 +787,7 @@ class TestDelete(TestCase): 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]] @@ -735,7 +797,7 @@ class TestGradient(TestCase): 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) @@ -825,15 +887,15 @@ class TestGradient(TestCase): 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) @@ -843,19 +905,19 @@ class TestGradient(TestCase): 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, @@ -865,13 +927,13 @@ class TestGradient(TestCase): 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) @@ -879,14 +941,14 @@ class TestGradient(TestCase): 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]] @@ -912,7 +974,7 @@ class TestGradient(TestCase): 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( @@ -924,20 +986,26 @@ class TestGradient(TestCase): assert_array_equal(gradient(x), dx) assert_(dx.dtype == np.dtype('timedelta64[D]')) + def test_inexact_dtypes(self): + for dt in [np.float16, np.float32, np.float64]: + # dtypes should not be promoted in a different way to what diff does + x = np.array([1, 2, 3], dtype=dt) + assert_equal(gradient(x).dtype, np.diff(x).dtype) + def test_values(self): # needs at least 2 points for edge_order ==1 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) assert_raises(ValueError, gradient, np.arange(1), edge_order=2) - assert_raises(ValueError, gradient, np.arange(2), edge_order=2) + 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, @@ -953,7 +1021,7 @@ class TestAngle(TestCase): assert_array_almost_equal(z, zo, 11) -class TestTrimZeros(TestCase): +class TestTrimZeros(object): """ Only testing for integer splits. @@ -976,7 +1044,7 @@ class TestTrimZeros(TestCase): 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]) @@ -1015,7 +1083,7 @@ class TestExtins(TestCase): assert_array_equal(a, ac) -class TestVectorize(TestCase): +class TestVectorize(object): def test_simple(self): def addsubtract(a, b): @@ -1074,7 +1142,7 @@ class TestVectorize(TestCase): import random try: vectorize(random.randrange) # Should succeed - except: + except Exception: raise AssertionError() def test_keywords2_ticket_2100(self): @@ -1347,7 +1415,7 @@ class TestVectorize(TestCase): f(x) -class TestDigitize(TestCase): +class TestDigitize(object): def test_forward(self): x = np.arange(-6, 5) @@ -1420,7 +1488,7 @@ class TestDigitize(TestCase): 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 @@ -1429,7 +1497,7 @@ class TestUnwrap(TestCase): assert_(np.all(diff(unwrap(rand(10) * 100)) < np.pi)) -class TestFilterwindows(TestCase): +class TestFilterwindows(object): def test_hanning(self): # check symmetry @@ -1460,7 +1528,7 @@ class TestFilterwindows(TestCase): 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) @@ -1532,7 +1600,7 @@ class TestTrapz(TestCase): assert_almost_equal(mr, r) -class TestSinc(TestCase): +class TestSinc(object): def test_simple(self): assert_(sinc(0) == 1) @@ -1549,12 +1617,12 @@ class TestSinc(TestCase): 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): @@ -1650,16 +1718,16 @@ class TestHistogram(TestCase): # Check the type of the returned histogram a = np.arange(10) + .5 h, b = histogram(a) - assert_(np.issubdtype(h.dtype, int)) + assert_(np.issubdtype(h.dtype, np.integer)) h, b = histogram(a, normed=True) - assert_(np.issubdtype(h.dtype, float)) + assert_(np.issubdtype(h.dtype, np.floating)) h, b = histogram(a, weights=np.ones(10, int)) - assert_(np.issubdtype(h.dtype, int)) + assert_(np.issubdtype(h.dtype, np.integer)) h, b = histogram(a, weights=np.ones(10, float)) - assert_(np.issubdtype(h.dtype, float)) + assert_(np.issubdtype(h.dtype, np.floating)) def test_f32_rounding(self): # gh-4799, check that the rounding of the edges works with float32 @@ -1760,16 +1828,16 @@ class TestHistogram(TestCase): 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 @@ -1879,7 +1947,7 @@ class TestHistogramOptimBinNums(TestCase): 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, @@ -1891,7 +1959,7 @@ class TestHistogramOptimBinNums(TestCase): } 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) @@ -1909,11 +1977,11 @@ class TestHistogramOptimBinNums(TestCase): """ 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], @@ -2053,7 +2121,7 @@ class TestHistogramdd(TestCase): 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]) @@ -2065,7 +2133,7 @@ class TestUnique(TestCase): 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] @@ -2082,7 +2150,7 @@ class TestCheckFinite(TestCase): 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], @@ -2167,7 +2235,7 @@ class TestCorrCoef(TestCase): 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) @@ -2265,7 +2333,7 @@ class TestCov(TestCase): self.res1) -class Test_I0(TestCase): +class Test_I0(object): def test_simple(self): assert_almost_equal( @@ -2291,7 +2359,7 @@ class Test_I0(TestCase): [1.05884290, 1.06432317]])) -class TestKaiser(TestCase): +class TestKaiser(object): def test_simple(self): assert_(np.isfinite(kaiser(1, 1.0))) @@ -2310,7 +2378,7 @@ class TestKaiser(TestCase): kaiser(3, 4) -class TestMsort(TestCase): +class TestMsort(object): def test_simple(self): A = np.array([[0.44567325, 0.79115165, 0.54900530], @@ -2323,7 +2391,7 @@ class TestMsort(TestCase): [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]) @@ -2412,7 +2480,7 @@ class TestMeshgrid(TestCase): assert_equal(x[1, :], X) -class TestPiecewise(TestCase): +class TestPiecewise(object): def test_simple(self): # Condition is single bool list @@ -2488,7 +2556,7 @@ class TestPiecewise(TestCase): [3., 3., 1.]])) -class TestBincount(TestCase): +class TestBincount(object): def test_simple(self): y = np.bincount(np.arange(4)) @@ -2575,7 +2643,7 @@ class TestBincount(TestCase): 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, [], []) @@ -2602,28 +2670,28 @@ class TestInterp(TestCase): incres = interp(incpts, xp, yp) decres = interp(decpts, xp, yp) - inctgt = np.array([1, 1, 1, 1], dtype=np.float) + inctgt = np.array([1, 1, 1, 1], dtype=float) dectgt = inctgt[::-1] assert_equal(incres, inctgt) assert_equal(decres, dectgt) incres = interp(incpts, xp, yp, left=0) decres = interp(decpts, xp, yp, left=0) - inctgt = np.array([0, 1, 1, 1], dtype=np.float) + inctgt = np.array([0, 1, 1, 1], dtype=float) dectgt = inctgt[::-1] assert_equal(incres, inctgt) assert_equal(decres, dectgt) incres = interp(incpts, xp, yp, right=2) decres = interp(decpts, xp, yp, right=2) - inctgt = np.array([1, 1, 1, 2], dtype=np.float) + inctgt = np.array([1, 1, 1, 2], dtype=float) dectgt = inctgt[::-1] assert_equal(incres, inctgt) assert_equal(decres, dectgt) incres = interp(incpts, xp, yp, left=0, right=2) decres = interp(decpts, xp, yp, left=0, right=2) - inctgt = np.array([0, 1, 1, 2], dtype=np.float) + inctgt = np.array([0, 1, 1, 2], dtype=float) dectgt = inctgt[::-1] assert_equal(incres, inctgt) assert_equal(decres, dectgt) @@ -2693,7 +2761,7 @@ def compare_results(res, desired): assert_array_equal(res[i], desired[i]) -class TestPercentile(TestCase): +class TestPercentile(object): def test_basic(self): x = np.arange(8) * 0.5 @@ -2797,7 +2865,7 @@ class TestPercentile(TestCase): # 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) @@ -2818,7 +2886,7 @@ class TestPercentile(TestCase): # 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) @@ -2950,7 +3018,7 @@ class TestPercentile(TestCase): o = np.random.normal(size=(71, 23)) x = np.dstack([o] * 10) assert_equal(np.percentile(x, 30, axis=(0, 1)), np.percentile(o, 30)) - x = np.rollaxis(x, -1, 0) + x = np.moveaxis(x, -1, 0) assert_equal(np.percentile(x, 30, axis=(-2, -1)), np.percentile(o, 30)) x = x.swapaxes(0, 1).copy() assert_equal(np.percentile(x, 30, axis=(0, -1)), np.percentile(o, 30)) @@ -3124,7 +3192,7 @@ class TestPercentile(TestCase): a, [0.3, 0.6], (0, 2), interpolation='nearest'), b) -class TestMedian(TestCase): +class TestMedian(object): def test_basic(self): a0 = np.array(1) @@ -3331,7 +3399,7 @@ class TestMedian(TestCase): o = np.random.normal(size=(71, 23)) x = np.dstack([o] * 10) assert_equal(np.median(x, axis=(0, 1)), np.median(o)) - x = np.rollaxis(x, -1, 0) + x = np.moveaxis(x, -1, 0) assert_equal(np.median(x, axis=(-2, -1)), np.median(o)) x = x.swapaxes(0, 1).copy() assert_equal(np.median(x, axis=(0, -1)), np.median(o)) @@ -3381,7 +3449,7 @@ class TestMedian(TestCase): (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") @@ -3391,15 +3459,15 @@ class TestAdd_newdoc_ufunc(TestCase): 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 5b791026b..452b3d6a2 100644 --- a/numpy/lib/tests/test_index_tricks.py +++ b/numpy/lib/tests/test_index_tricks.py @@ -2,7 +2,7 @@ from __future__ import division, absolute_import, print_function 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 @@ from numpy.lib.index_tricks import ( ) -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 @@ class TestRavelUnravelIndex(TestCase): 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 @@ class TestGrid(TestCase): 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 @@ class TestConcatenator(TestCase): 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 @@ class TestIndexExpression(TestCase): 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 @@ -243,7 +243,7 @@ class TestIx_(TestCase): for k, (a, sz) in enumerate(zip(arrays, sizes)): assert_equal(a.shape[k], sz) assert_(all(sh == 1 for j, sh in enumerate(a.shape) if j != k)) - assert_(np.issubdtype(a.dtype, int)) + assert_(np.issubdtype(a.dtype, np.integer)) def test_bool(self): bool_a = [True, False, True, True] diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py index 868089551..6f7fcc54c 100644 --- a/numpy/lib/tests/test_io.py +++ b/numpy/lib/tests/test_io.py @@ -17,9 +17,9 @@ from numpy.lib._iotools import ConverterError, ConversionWarning 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 @@ class RoundtripTest(object): 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 @@ class TestSaveLoad(RoundtripTest, TestCase): 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 @@ class TestSavezLoad(RoundtripTest, TestCase): assert_(fp.closed) -class TestSaveTxt(TestCase): +class TestSaveTxt(object): def test_array(self): a = np.array([[1, 2], [3, 4]], float) fmt = "%.18e" @@ -329,6 +329,12 @@ class TestSaveTxt(TestCase): lines = c.readlines() assert_equal(lines, [b'1\n', b'2\n', b'3\n', b'4\n']) + def test_0D_3D(self): + c = BytesIO() + assert_raises(ValueError, np.savetxt, c, np.array(1)) + assert_raises(ValueError, np.savetxt, c, np.array([[[1], [2]]])) + + def test_record(self): a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')]) c = BytesIO() @@ -373,7 +379,7 @@ class TestSaveTxt(TestCase): # Test the functionality of the header and footer keyword argument. c = BytesIO() - a = np.array([(1, 2), (3, 4)], dtype=np.int) + a = np.array([(1, 2), (3, 4)], dtype=int) test_header_footer = 'Test header / footer' # Test the header keyword argument np.savetxt(c, a, fmt='%1d', header=test_header_footer) @@ -461,7 +467,7 @@ class TestSaveTxt(TestCase): assert_array_equal(a, b) -class TestLoadTxt(TestCase): +class TestLoadTxt(object): def test_record(self): c = TextIO() c.write('1 2\n3 4') @@ -485,7 +491,7 @@ class TestLoadTxt(TestCase): c.write('1 2\n3 4') c.seek(0) - x = np.loadtxt(c, dtype=np.int) + x = np.loadtxt(c, dtype=int) a = np.array([[1, 2], [3, 4]], int) assert_array_equal(x, a) @@ -721,7 +727,7 @@ class TestLoadTxt(TestCase): # Test using an explicit dtype with an object data = """ 1; 2001-01-01 2; 2002-01-31 """ - ndtype = [('idx', int), ('code', np.object)] + ndtype = [('idx', int), ('code', object)] func = lambda s: strptime(s.strip(), "%Y-%m-%d") converters = {1: func} test = np.loadtxt(TextIO(data), delimiter=";", dtype=ndtype, @@ -751,11 +757,11 @@ class TestLoadTxt(TestCase): # IEEE doubles and floats only, otherwise the float32 # conversion may fail. tgt = np.logspace(-10, 10, 5).astype(np.float32) - tgt = np.hstack((tgt, -tgt)).astype(np.float) + tgt = np.hstack((tgt, -tgt)).astype(float) inp = '\n'.join(map(float.hex, tgt)) c = TextIO() c.write(inp) - for dt in [np.float, np.float32]: + for dt in [float, np.float32]: c.seek(0) res = np.loadtxt(c, dtype=dt) assert_equal(res, tgt, err_msg="%s" % dt) @@ -765,7 +771,7 @@ class TestLoadTxt(TestCase): c = TextIO() c.write("%s %s" % tgt) c.seek(0) - res = np.loadtxt(c, dtype=np.complex) + res = np.loadtxt(c, dtype=complex) assert_equal(res, tgt) def test_universal_newline(self): @@ -864,7 +870,7 @@ class TestLoadTxt(TestCase): 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 +908,7 @@ class Testfromregex(TestCase): #####-------------------------------------------------------------------------- -class TestFromTxt(TestCase): +class TestFromTxt(object): # def test_record(self): # Test w/ explicit dtype @@ -1178,19 +1184,19 @@ M 33 21.99 conv = {0: int, 1: int, 2: int, 3: lambda r: dmap[r.decode()]} test = np.recfromcsv(TextIO(dstr,), dtype=dtyp, delimiter=',', names=None, converters=conv) - control = np.rec.array([[1,5,-1,0], [2,8,-1,1], [3,3,-2,3]], dtype=dtyp) + control = np.rec.array([(1,5,-1,0), (2,8,-1,1), (3,3,-2,3)], dtype=dtyp) assert_equal(test, control) dtyp = [('e1','i4'),('e2','i4'),('n', 'i1')] test = np.recfromcsv(TextIO(dstr,), dtype=dtyp, delimiter=',', usecols=(0,1,3), names=None, converters=conv) - control = np.rec.array([[1,5,0], [2,8,1], [3,3,3]], dtype=dtyp) + control = np.rec.array([(1,5,0), (2,8,1), (3,3,3)], dtype=dtyp) assert_equal(test, control) def test_dtype_with_object(self): # Test using an explicit dtype with an object data = """ 1; 2001-01-01 2; 2002-01-31 """ - ndtype = [('idx', int), ('code', np.object)] + ndtype = [('idx', int), ('code', object)] func = lambda s: strptime(s.strip(), "%Y-%m-%d") converters = {1: func} test = np.genfromtxt(TextIO(data), delimiter=";", dtype=ndtype, @@ -1200,7 +1206,7 @@ M 33 21.99 dtype=ndtype) assert_equal(test, control) - ndtype = [('nest', [('idx', int), ('code', np.object)])] + ndtype = [('nest', [('idx', int), ('code', object)])] try: test = np.genfromtxt(TextIO(data), delimiter=";", dtype=ndtype, converters=converters) @@ -1337,7 +1343,7 @@ M 33 21.99 test = np.mafromtxt(data, dtype=None, **kwargs) control = ma.array([(0, 1), (2, -1)], mask=[(False, False), (False, True)], - dtype=[('A', np.int), ('B', np.int)]) + dtype=[('A', int), ('B', int)]) assert_equal(test, control) assert_equal(test.mask, control.mask) # @@ -1345,7 +1351,7 @@ M 33 21.99 test = np.mafromtxt(data, **kwargs) control = ma.array([(0, 1), (2, -1)], mask=[(False, False), (False, True)], - dtype=[('A', np.float), ('B', np.float)]) + dtype=[('A', float), ('B', float)]) assert_equal(test, control) assert_equal(test.mask, control.mask) @@ -1414,7 +1420,7 @@ M 33 21.99 missing_values='-999.0', names=True,) control = ma.array([(0, 1.5), (2, -1.)], mask=[(False, False), (False, True)], - dtype=[('A', np.int), ('B', np.float)]) + dtype=[('A', int), ('B', float)]) assert_equal(test, control) assert_equal(test.mask, control.mask) @@ -1682,15 +1688,15 @@ M 33 21.99 kwargs = dict(delimiter=",", missing_values="N/A", names=True) 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)) + dtype=[('A', int), ('B', int)]) + assert_(isinstance(test, np.recarray)) assert_equal(test, control) # data = TextIO('A,B\n0,1\n2,N/A') test = np.recfromtxt(data, dtype=None, usemask=True, **kwargs) control = ma.array([(0, 1), (2, -1)], mask=[(False, False), (False, True)], - dtype=[('A', np.int), ('B', np.int)]) + dtype=[('A', int), ('B', int)]) assert_equal(test, control) assert_equal(test.mask, control.mask) assert_equal(test.A, [0, 2]) @@ -1701,15 +1707,15 @@ M 33 21.99 kwargs = dict(missing_values="N/A", names=True, case_sensitive=True) 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)) + dtype=[('A', int), ('B', int)]) + assert_(isinstance(test, np.recarray)) assert_equal(test, control) # data = TextIO('A,B\n0,1\n2,N/A') test = np.recfromcsv(data, dtype=None, usemask=True, **kwargs) control = ma.array([(0, 1), (2, -1)], mask=[(False, False), (False, True)], - dtype=[('A', np.int), ('B', np.int)]) + dtype=[('A', int), ('B', int)]) assert_equal(test, control) assert_equal(test.mask, control.mask) assert_equal(test.A, [0, 2]) @@ -1717,16 +1723,16 @@ M 33 21.99 data = TextIO('A,B\n0,1\n2,3') 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)) + dtype=[('a', int), ('b', int)]) + assert_(isinstance(test, np.recarray)) assert_equal(test, control) # data = TextIO('A,B\n0,1\n2,3') - dtype = [('a', np.int), ('b', np.float)] + dtype = [('a', int), ('b', float)] 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): @@ -1827,7 +1833,7 @@ M 33 21.99 assert_equal(test.dtype.names, ['f0', 'f1', 'f2']) - assert_(test.dtype['f0'] == np.float) + assert_(test.dtype['f0'] == float) assert_(test.dtype['f1'] == np.int64) assert_(test.dtype['f2'] == np.integer) @@ -1836,7 +1842,7 @@ M 33 21.99 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): @@ -1919,8 +1925,8 @@ class TestPathUsage(TestCase): kwargs = dict(delimiter=",", missing_values="N/A", names=True) 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)) + dtype=[('A', int), ('B', int)]) + assert_(isinstance(test, np.recarray)) assert_equal(test, control) @np.testing.dec.skipif(Path is None, "No pathlib.Path") @@ -1933,8 +1939,8 @@ class TestPathUsage(TestCase): kwargs = dict(missing_values="N/A", names=True, case_sensitive=True) 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)) + dtype=[('A', int), ('B', int)]) + 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 db38bdfd6..94f06c336 100644 --- a/numpy/lib/tests/test_mixins.py +++ b/numpy/lib/tests/test_mixins.py @@ -6,7 +6,8 @@ import sys 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 @@ _ALL_BINARY_OPERATORS = [ ] -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 466ceefb5..3d362fc6e 100644 --- a/numpy/lib/tests/test_nanfunctions.py +++ b/numpy/lib/tests/test_nanfunctions.py @@ -4,7 +4,7 @@ import warnings 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 @@ _ndat_zeros = np.array([[0.6244, 0.0, 0.2692, 0.0116, 0.0, 0.1170], [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 @@ class TestNanFunctions_MinMax(TestCase): assert_(issubclass(w[0].category, RuntimeWarning)) -class TestNanFunctions_ArgminArgmax(TestCase): +class TestNanFunctions_ArgminArgmax(object): nanfuncs = [np.nanargmin, np.nanargmax] @@ -224,7 +224,7 @@ class TestNanFunctions_ArgminArgmax(TestCase): 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 @@ class SharedNanFunctionsTestsMixin(object): 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 @@ class TestNanFunctions_SumProd(TestCase, SharedNanFunctionsTestsMixin): 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 @@ class TestNanFunctions_CumSumProd(TestCase, SharedNanFunctionsTestsMixin): 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 @@ class TestNanFunctions_MeanVarStd(TestCase, SharedNanFunctionsTestsMixin): 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 @@ class TestNanFunctions_Median(TestCase): ([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 0725c186d..9a4650825 100644 --- a/numpy/lib/tests/test_polynomial.py +++ b/numpy/lib/tests/test_polynomial.py @@ -80,12 +80,12 @@ poly1d([ 2.]) ''' 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 0940d37b0..bc9f8d7b6 100644 --- a/numpy/lib/tests/test_recfunctions.py +++ b/numpy/lib/tests/test_recfunctions.py @@ -4,7 +4,9 @@ import numpy as np import numpy.ma as ma from numpy.ma.mrecords import MaskedRecords from numpy.ma.testutils import assert_equal -from numpy.testing import TestCase, run_module_suite, assert_, assert_raises +from numpy.testing import ( + 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 @@ -14,10 +16,10 @@ get_names_flat = np.lib.recfunctions.get_names_flat 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.)], @@ -191,7 +193,7 @@ class TestRecFunctions(TestCase): 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 @@ -214,10 +216,10 @@ class TestRecursiveFillFields(TestCase): 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( @@ -347,10 +349,10 @@ class TestMergeArrays(TestCase): 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( @@ -401,9 +403,9 @@ class TestAppendFields(TestCase): 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( @@ -417,11 +419,11 @@ class TestStackArrays(TestCase): (_, 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 @@ -546,9 +548,38 @@ class TestStackArrays(TestCase): assert_equal(test, control) assert_equal(test.mask, control.mask) - -class TestJoinBy(TestCase): - def setUp(self): + def test_subdtype(self): + z = np.array([ + ('A', 1), ('B', 2) + ], dtype=[('A', '|S3'), ('B', float, (1,))]) + zz = np.array([ + ('a', [10.], 100.), ('b', [20.], 200.), ('c', [30.], 300.) + ], dtype=[('A', '|S3'), ('B', float, (1,)), ('C', float)]) + + res = stack_arrays((z, zz)) + expected = ma.array( + data=[ + (b'A', [1.0], 0), + (b'B', [2.0], 0), + (b'a', [10.0], 100.0), + (b'b', [20.0], 200.0), + (b'c', [30.0], 300.0)], + mask=[ + (False, [False], True), + (False, [False], True), + (False, [False], False), + (False, [False], False), + (False, [False], False) + ], + dtype=zz.dtype + ) + assert_equal(res.dtype, expected.dtype) + assert_equal(res, expected) + assert_equal(res.mask, expected.mask) + + +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)]) @@ -588,6 +619,16 @@ class TestJoinBy(TestCase): dtype=[('a', int), ('b', int), ('c', int), ('d', int)]) + def test_join_subdtype(self): + # tests the bug in https://stackoverflow.com/q/44769632/102441 + from numpy.lib import recfunctions as rfn + foo = np.array([(1,)], + dtype=[('key', int)]) + bar = np.array([(1, np.array([1,2,3]))], + dtype=[('key', int), ('value', 'uint16', 3)]) + res = join_by('key', foo, bar) + assert_equal(res, bar.view(ma.MaskedArray)) + def test_outer_join(self): a, b = self.a, self.b @@ -646,10 +687,66 @@ class TestJoinBy(TestCase): b = np.ones(3, dtype=[('c', 'u1'), ('b', 'f4'), ('a', 'i4')]) assert_raises(ValueError, join_by, ['a', 'b', 'b'], a, b) + @dec.knownfailureif(True) + def test_same_name_different_dtypes_key(self): + a_dtype = np.dtype([('key', 'S5'), ('value', '<f4')]) + b_dtype = np.dtype([('key', 'S10'), ('value', '<f4')]) + expected_dtype = np.dtype([ + ('key', 'S10'), ('value1', '<f4'), ('value2', '<f4')]) + + a = np.array([('Sarah', 8.0), ('John', 6.0)], dtype=a_dtype) + b = np.array([('Sarah', 10.0), ('John', 7.0)], dtype=b_dtype) + res = join_by('key', a, b) + + assert_equal(res.dtype, expected_dtype) + + def test_same_name_different_dtypes(self): + # gh-9338 + a_dtype = np.dtype([('key', 'S10'), ('value', '<f4')]) + b_dtype = np.dtype([('key', 'S10'), ('value', '<f8')]) + expected_dtype = np.dtype([ + ('key', '|S10'), ('value1', '<f4'), ('value2', '<f8')]) + + a = np.array([('Sarah', 8.0), ('John', 6.0)], dtype=a_dtype) + b = np.array([('Sarah', 10.0), ('John', 7.0)], dtype=b_dtype) + res = join_by('key', a, b) + + assert_equal(res.dtype, expected_dtype) + + def test_subarray_key(self): + a_dtype = np.dtype([('pos', int, 3), ('f', '<f4')]) + a = np.array([([1, 1, 1], np.pi), ([1, 2, 3], 0.0)], dtype=a_dtype) + + b_dtype = np.dtype([('pos', int, 3), ('g', '<f4')]) + b = np.array([([1, 1, 1], 3), ([3, 2, 1], 0.0)], dtype=b_dtype) + + expected_dtype = np.dtype([('pos', int, 3), ('f', '<f4'), ('g', '<f4')]) + expected = np.array([([1, 1, 1], np.pi, 3)], dtype=expected_dtype) + + res = join_by('pos', a, b) + assert_equal(res.dtype, expected_dtype) + assert_equal(res, expected) + + def test_padded_dtype(self): + dt = np.dtype('i1,f4', align=True) + dt.names = ('k', 'v') + assert_(len(dt.descr), 3) # padding field is inserted + + a = np.array([(1, 3), (3, 2)], dt) + b = np.array([(1, 1), (2, 2)], dt) + res = join_by('k', a, b) + + # no padding fields remain + expected_dtype = np.dtype([ + ('k', 'i1'), ('v1', 'f4'), ('v2', 'f4') + ]) + + 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)]) @@ -673,8 +770,8 @@ class TestJoinBy2(TestCase): 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 @@ -712,13 +809,13 @@ class TestJoinBy2(TestCase): 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 ee50dcfa4..d96d3422d 100644 --- a/numpy/lib/tests/test_regression.py +++ b/numpy/lib/tests/test_regression.py @@ -5,22 +5,19 @@ import sys import numpy as np from numpy.testing import ( - run_module_suite, TestCase, assert_, assert_equal, assert_array_equal, - assert_array_almost_equal, assert_raises + run_module_suite, assert_, assert_equal, assert_array_equal, + assert_array_almost_equal, assert_raises, _assert_valid_refcount, ) -from numpy.testing.utils import _assert_valid_refcount from numpy.compat import unicode -rlevel = 1 - -class TestRegression(TestCase): - def test_poly1d(self, level=rlevel): +class TestRegression(object): + def test_poly1d(self): # Ticket #28 assert_equal(np.poly1d([1]) - np.poly1d([1, 0]), np.poly1d([-1, 1])) - def test_cov_parameters(self, level=rlevel): + def test_cov_parameters(self): # Ticket #91 x = np.random.random((3, 3)) y = x.copy() @@ -28,57 +25,57 @@ class TestRegression(TestCase): np.cov(y, rowvar=0) assert_array_equal(x, y) - def test_mem_digitize(self, level=rlevel): + def test_mem_digitize(self): # Ticket #95 for i in range(100): np.digitize([1, 2, 3, 4], [1, 3]) np.digitize([0, 1, 2, 3, 4], [1, 3]) - def test_unique_zero_sized(self, level=rlevel): + def test_unique_zero_sized(self): # Ticket #205 assert_array_equal([], np.unique(np.array([]))) - def test_mem_vectorise(self, level=rlevel): + def test_mem_vectorise(self): # Ticket #325 vt = np.vectorize(lambda *args: args) vt(np.zeros((1, 2, 1)), np.zeros((2, 1, 1)), np.zeros((1, 1, 2))) vt(np.zeros((1, 2, 1)), np.zeros((2, 1, 1)), np.zeros((1, 1, 2)), np.zeros((2, 2))) - def test_mgrid_single_element(self, level=rlevel): + def test_mgrid_single_element(self): # Ticket #339 assert_array_equal(np.mgrid[0:0:1j], [0]) assert_array_equal(np.mgrid[0:0], []) - def test_refcount_vectorize(self, level=rlevel): + def test_refcount_vectorize(self): # Ticket #378 def p(x, y): return 123 v = np.vectorize(p) _assert_valid_refcount(v) - def test_poly1d_nan_roots(self, level=rlevel): + def test_poly1d_nan_roots(self): # 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): + def test_mem_polymul(self): # Ticket #448 np.polymul([], [1.]) - def test_mem_string_concat(self, level=rlevel): + def test_mem_string_concat(self): # Ticket #469 x = np.array([]) np.append(x, 'asdasd\tasdasd') - def test_poly_div(self, level=rlevel): + def test_poly_div(self): # Ticket #553 u = np.poly1d([1, 2, 3]) v = np.poly1d([1, 2, 3, 4, 5]) q, r = np.polydiv(u, v) assert_equal(q*v + r, u) - def test_poly_eq(self, level=rlevel): + def test_poly_eq(self): # Ticket #554 x = np.poly1d([1, 2, 3]) y = np.poly1d([3, 4]) @@ -109,13 +106,13 @@ class TestRegression(TestCase): def test_polydiv_type(self): # Make polydiv work for complex types msg = "Wrong type, should be complex" - x = np.ones(3, dtype=np.complex) + x = np.ones(3, dtype=complex) q, r = np.polydiv(x, x) - assert_(q.dtype == np.complex, msg) + assert_(q.dtype == complex, msg) msg = "Wrong type, should be float" - x = np.ones(3, dtype=np.int) + x = np.ones(3, dtype=int) q, r = np.polydiv(x, x) - assert_(q.dtype == np.float, msg) + assert_(q.dtype == float, msg) def test_histogramdd_too_many_bins(self): # Ticket 928. @@ -124,22 +121,22 @@ class TestRegression(TestCase): def test_polyint_type(self): # Ticket #944 msg = "Wrong type, should be complex" - x = np.ones(3, dtype=np.complex) - assert_(np.polyint(x).dtype == np.complex, msg) + x = np.ones(3, dtype=complex) + assert_(np.polyint(x).dtype == complex, msg) msg = "Wrong type, should be float" - x = np.ones(3, dtype=np.int) - assert_(np.polyint(x).dtype == np.float, msg) + x = np.ones(3, dtype=int) + assert_(np.polyint(x).dtype == float, msg) def test_ndenumerate_crash(self): # Ticket 1140 # Shouldn't crash: list(np.ndenumerate(np.array([[]]))) - def test_asfarray_none(self, level=rlevel): + def test_asfarray_none(self): # Test for changeset r5065 assert_array_equal(np.array([np.nan]), np.asfarray([None])) - def test_large_fancy_indexing(self, level=rlevel): + def test_large_fancy_indexing(self): # Large enough to fail on 64-bit. nbits = np.dtype(np.intp).itemsize * 8 thesize = int((2**nbits)**(1.0/5.0)+1) @@ -156,15 +153,15 @@ class TestRegression(TestCase): 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): + def test_void_coercion(self): dt = np.dtype([('a', 'f4'), ('b', 'i4')]) x = np.zeros((1,), dt) assert_(np.r_[x, x].dtype == dt) - def test_who_with_0dim_array(self, level=rlevel): + def test_who_with_0dim_array(self): # ticket #1243 import os import sys @@ -174,7 +171,7 @@ class TestRegression(TestCase): try: try: np.who({'foo': np.array(1)}) - except: + except Exception: raise AssertionError("ticket #1243") finally: sys.stdout.close() @@ -206,7 +203,7 @@ class TestRegression(TestCase): dlist = [np.float64, np.int32, np.int32] try: append_fields(base, names, data, dlist) - except: + except Exception: raise AssertionError() def test_loadtxt_fields_subarrays(self): @@ -235,10 +232,10 @@ class TestRegression(TestCase): def test_nansum_with_boolean(self): # gh-2978 - a = np.zeros(2, dtype=np.bool) + a = np.zeros(2, dtype=bool) try: np.nansum(a) - except: + except Exception: raise AssertionError() def test_py3_compat(self): diff --git a/numpy/lib/tests/test_shape_base.py b/numpy/lib/tests/test_shape_base.py index 4d06001f4..d0afeefd9 100644 --- a/numpy/lib/tests/test_shape_base.py +++ b/numpy/lib/tests/test_shape_base.py @@ -1,23 +1,25 @@ from __future__ import division, absolute_import, print_function import numpy as np +import warnings + from numpy.lib.shape_base import ( apply_along_axis, apply_over_axes, array_split, split, hsplit, dsplit, - vsplit, dstack, column_stack, kron, tile + 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( apply_along_axis(len, 0, a), len(a)*np.ones(a.shape[1])) - def test_simple101(self, level=11): + def test_simple101(self): a = np.ones((10, 101), 'd') assert_array_equal( apply_along_axis(len, 0, a), len(a)*np.ones(a.shape[1])) @@ -175,14 +177,33 @@ class TestApplyAlongAxis(TestCase): 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 TestArraySplit(TestCase): +class TestExpandDims(object): + def test_functionality(self): + s = (2, 3, 4, 5) + a = np.empty(s) + for axis in range(-5, 4): + b = expand_dims(a, axis) + assert_(b.shape[axis] == 1) + assert_(np.squeeze(b).shape == s) + + def test_deprecations(self): + # 2017-05-17, 1.13.0 + s = (2, 3, 4, 5) + a = np.empty(s) + with warnings.catch_warnings(): + warnings.simplefilter("always") + assert_warns(DeprecationWarning, expand_dims, a, -6) + assert_warns(DeprecationWarning, expand_dims, a, 5) + + +class TestArraySplit(object): def test_integer_0_split(self): a = np.arange(10) assert_raises(ValueError, array_split, a, 0) @@ -307,7 +328,7 @@ class TestArraySplit(TestCase): 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. @@ -322,12 +343,12 @@ class TestSplit(TestCase): 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) @@ -362,7 +383,7 @@ class TestDstack(TestCase): # 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. """ @@ -391,7 +412,7 @@ class TestHsplit(TestCase): compare_results(res, desired) -class TestVsplit(TestCase): +class TestVsplit(object): """Only testing for integer splits. """ @@ -418,7 +439,7 @@ class TestVsplit(TestCase): 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) @@ -451,7 +472,7 @@ class TestDsplit(TestCase): compare_results(res, desired) -class TestSqueeze(TestCase): +class TestSqueeze(object): def test_basic(self): from numpy.random import rand @@ -470,7 +491,7 @@ class TestSqueeze(TestCase): 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) @@ -489,7 +510,7 @@ class TestKron(TestCase): 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]] @@ -529,19 +550,19 @@ class TestTile(TestCase): 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])) - - 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_(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])) + + 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_stride_tricks.py b/numpy/lib/tests/test_stride_tricks.py index 7dc3c4d24..0599324d7 100644 --- a/numpy/lib/tests/test_stride_tricks.py +++ b/numpy/lib/tests/test_stride_tricks.py @@ -1,6 +1,7 @@ from __future__ import division, absolute_import, print_function import numpy as np +from numpy.core.test_rational import rational from numpy.testing import ( run_module_suite, assert_equal, assert_array_equal, assert_raises, assert_ @@ -317,6 +318,13 @@ def test_as_strided(): a_view = as_strided(a, shape=(3, 4), strides=(0, a.itemsize)) assert_equal(a.dtype, a_view.dtype) + # Custom dtypes should not be lost (gh-9161) + r = [rational(i) for i in range(4)] + a = np.array(r, dtype=rational) + a_view = as_strided(a, shape=(3, 4), strides=(0, a.itemsize)) + assert_equal(a.dtype, a_view.dtype) + assert_array_equal([r] * 3, a_view) + def as_strided_writeable(): arr = np.ones(10) view = as_strided(arr, writeable=False) diff --git a/numpy/lib/tests/test_twodim_base.py b/numpy/lib/tests/test_twodim_base.py index d57791e34..6bf668dee 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 @@ def get_mat(n): 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 @@ class TestEye(TestCase): 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 @@ class TestDiag(TestCase): 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 @@ class TestFliplr(TestCase): 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 @@ class TestFlipud(TestCase): 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 @@ class TestHistogram2d(TestCase): 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 @@ def test_mask_indices(): # 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 @@ def test_tril_indices(): 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 @@ class TestTriuIndices(object): 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 383ffa55c..8945b61ea 100644 --- a/numpy/lib/tests/test_type_check.py +++ b/numpy/lib/tests/test_type_check.py @@ -3,7 +3,7 @@ from __future__ import division, absolute_import, print_function 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, assert_raises ) from numpy.lib.type_check import ( common_type, mintypecode, isreal, iscomplex, isposinf, isneginf, @@ -15,7 +15,7 @@ def assert_all(x): 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 @@ class TestCommonType(TestCase): 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 @@ class TestMintypecode(TestCase): assert_equal(mintypecode('idD'), 'D') -class TestIsscalar(TestCase): +class TestIsscalar(object): def test_basic(self): assert_(np.isscalar(3)) @@ -92,7 +92,7 @@ class TestIsscalar(TestCase): assert_(np.isscalar(4.0)) -class TestReal(TestCase): +class TestReal(object): def test_real(self): y = np.random.rand(10,) @@ -123,7 +123,7 @@ class TestReal(TestCase): 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 @@ class TestImag(TestCase): 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 @@ class TestIscomplex(TestCase): 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 @@ class TestIsreal(TestCase): 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 @@ class TestIscomplexobj(TestCase): 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 @@ class TestIsrealobj(TestCase): assert_(not isrealobj(z)) -class TestIsnan(TestCase): +class TestIsnan(object): def test_goodvalues(self): z = np.array((-1., 0., 1.)) @@ -271,7 +271,7 @@ class TestIsnan(TestCase): 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 @@ class TestIsfinite(TestCase): 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 @@ class TestIsinf(TestCase): 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 @@ class TestIsposinf(TestCase): 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 @@ class TestIsneginf(TestCase): assert_(vals[2] == 0) -class TestNanToNum(TestCase): +class TestNanToNum(object): def test_generic(self): with np.errstate(divide='ignore', invalid='ignore'): @@ -374,7 +374,7 @@ class TestNanToNum(TestCase): vals = nan_to_num(1) assert_all(vals == 1) vals = nan_to_num([1]) - assert_array_equal(vals, np.array([1], np.int)) + assert_array_equal(vals, np.array([1], int)) def test_complex_good(self): vals = nan_to_num(1+1j) @@ -402,7 +402,7 @@ class TestNanToNum(TestCase): #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,12 +415,18 @@ class TestRealIfClose(TestCase): assert_all(isrealobj(b)) -class TestArrayConversion(TestCase): +class TestArrayConversion(object): def test_asfarray(self): a = asfarray(np.array([1, 2, 3])) assert_equal(a.__class__, np.ndarray) - assert_(np.issubdtype(a.dtype, np.float)) + assert_(np.issubdtype(a.dtype, np.floating)) + + # previously this would infer dtypes from arrays, unlike every single + # other numpy function + assert_raises(TypeError, + asfarray, np.array([1, 2, 3]), dtype=np.array(1.0)) + if __name__ == "__main__": run_module_suite() diff --git a/numpy/lib/tests/test_ufunclike.py b/numpy/lib/tests/test_ufunclike.py index 0b152540f..128ce37ab 100644 --- a/numpy/lib/tests/test_ufunclike.py +++ b/numpy/lib/tests/test_ufunclike.py @@ -4,12 +4,11 @@ import numpy as np 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]) |