summaryrefslogtreecommitdiff
path: root/numpy/lib/tests
diff options
context:
space:
mode:
Diffstat (limited to 'numpy/lib/tests')
-rw-r--r--numpy/lib/tests/test__version.py2
-rw-r--r--numpy/lib/tests/test_arraysetops.py79
-rw-r--r--numpy/lib/tests/test_format.py2
-rw-r--r--numpy/lib/tests/test_function_base.py69
-rw-r--r--numpy/lib/tests/test_index_tricks.py15
-rw-r--r--numpy/lib/tests/test_io.py5
-rw-r--r--numpy/lib/tests/test_nanfunctions.py50
-rw-r--r--numpy/lib/tests/test_polynomial.py31
-rw-r--r--numpy/lib/tests/test_regression.py2
-rw-r--r--numpy/lib/tests/test_utils.py11
10 files changed, 230 insertions, 36 deletions
diff --git a/numpy/lib/tests/test__version.py b/numpy/lib/tests/test__version.py
index 182504631..e6d41ad93 100644
--- a/numpy/lib/tests/test__version.py
+++ b/numpy/lib/tests/test__version.py
@@ -7,7 +7,7 @@ from numpy.lib import NumpyVersion
def test_main_versions():
assert_(NumpyVersion('1.8.0') == '1.8.0')
- for ver in ['1.9.0', '2.0.0', '1.8.1']:
+ for ver in ['1.9.0', '2.0.0', '1.8.1', '10.0.1']:
assert_(NumpyVersion('1.8.0') < ver)
for ver in ['1.7.0', '1.7.1', '0.9.9']:
diff --git a/numpy/lib/tests/test_arraysetops.py b/numpy/lib/tests/test_arraysetops.py
index 847e6cb8a..d62da9efb 100644
--- a/numpy/lib/tests/test_arraysetops.py
+++ b/numpy/lib/tests/test_arraysetops.py
@@ -358,6 +358,39 @@ class TestSetOps:
result = np.in1d(ar1, ar2)
assert_array_equal(result, expected)
+ def test_in1d_with_arrays_containing_tuples(self):
+ ar1 = np.array([(1,), 2], dtype=object)
+ ar2 = np.array([(1,), 2], dtype=object)
+ expected = np.array([True, True])
+ result = np.in1d(ar1, ar2)
+ assert_array_equal(result, expected)
+ result = np.in1d(ar1, ar2, invert=True)
+ assert_array_equal(result, np.invert(expected))
+
+ # An integer is added at the end of the array to make sure
+ # that the array builder will create the array with tuples
+ # and after it's created the integer is removed.
+ # There's a bug in the array constructor that doesn't handle
+ # tuples properly and adding the integer fixes that.
+ ar1 = np.array([(1,), (2, 1), 1], dtype=object)
+ ar1 = ar1[:-1]
+ ar2 = np.array([(1,), (2, 1), 1], dtype=object)
+ ar2 = ar2[:-1]
+ expected = np.array([True, True])
+ result = np.in1d(ar1, ar2)
+ assert_array_equal(result, expected)
+ result = np.in1d(ar1, ar2, invert=True)
+ assert_array_equal(result, np.invert(expected))
+
+ ar1 = np.array([(1,), (2, 3), 1], dtype=object)
+ ar1 = ar1[:-1]
+ ar2 = np.array([(1,), 2], dtype=object)
+ expected = np.array([True, False])
+ result = np.in1d(ar1, ar2)
+ assert_array_equal(result, expected)
+ result = np.in1d(ar1, ar2, invert=True)
+ assert_array_equal(result, np.invert(expected))
+
def test_union1d(self):
a = np.array([5, 4, 7, 1, 2])
b = np.array([2, 4, 3, 3, 2, 1, 5])
@@ -531,6 +564,52 @@ class TestUnique:
assert_equal(a3_idx.dtype, np.intp)
assert_equal(a3_inv.dtype, np.intp)
+ # test for ticket 2111 - float
+ a = [2.0, np.nan, 1.0, np.nan]
+ ua = [1.0, 2.0, np.nan]
+ ua_idx = [2, 0, 1]
+ ua_inv = [1, 2, 0, 2]
+ ua_cnt = [1, 1, 2]
+ assert_equal(np.unique(a), ua)
+ assert_equal(np.unique(a, return_index=True), (ua, ua_idx))
+ assert_equal(np.unique(a, return_inverse=True), (ua, ua_inv))
+ assert_equal(np.unique(a, return_counts=True), (ua, ua_cnt))
+
+ # test for ticket 2111 - complex
+ a = [2.0-1j, np.nan, 1.0+1j, complex(0.0, np.nan), complex(1.0, np.nan)]
+ ua = [1.0+1j, 2.0-1j, complex(0.0, np.nan)]
+ ua_idx = [2, 0, 3]
+ ua_inv = [1, 2, 0, 2, 2]
+ ua_cnt = [1, 1, 3]
+ assert_equal(np.unique(a), ua)
+ assert_equal(np.unique(a, return_index=True), (ua, ua_idx))
+ assert_equal(np.unique(a, return_inverse=True), (ua, ua_inv))
+ assert_equal(np.unique(a, return_counts=True), (ua, ua_cnt))
+
+ # test for ticket 2111 - datetime64
+ nat = np.datetime64('nat')
+ a = [np.datetime64('2020-12-26'), nat, np.datetime64('2020-12-24'), nat]
+ ua = [np.datetime64('2020-12-24'), np.datetime64('2020-12-26'), nat]
+ ua_idx = [2, 0, 1]
+ ua_inv = [1, 2, 0, 2]
+ ua_cnt = [1, 1, 2]
+ assert_equal(np.unique(a), ua)
+ assert_equal(np.unique(a, return_index=True), (ua, ua_idx))
+ assert_equal(np.unique(a, return_inverse=True), (ua, ua_inv))
+ assert_equal(np.unique(a, return_counts=True), (ua, ua_cnt))
+
+ # test for ticket 2111 - timedelta
+ nat = np.timedelta64('nat')
+ a = [np.timedelta64(1, 'D'), nat, np.timedelta64(1, 'h'), nat]
+ ua = [np.timedelta64(1, 'h'), np.timedelta64(1, 'D'), nat]
+ ua_idx = [2, 0, 1]
+ ua_inv = [1, 2, 0, 2]
+ ua_cnt = [1, 1, 2]
+ assert_equal(np.unique(a), ua)
+ assert_equal(np.unique(a, return_index=True), (ua, ua_idx))
+ assert_equal(np.unique(a, return_inverse=True), (ua, ua_inv))
+ assert_equal(np.unique(a, return_counts=True), (ua, ua_cnt))
+
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_format.py b/numpy/lib/tests/test_format.py
index bac42fad3..10656a233 100644
--- a/numpy/lib/tests/test_format.py
+++ b/numpy/lib/tests/test_format.py
@@ -402,7 +402,7 @@ class BytesIOSRandomSize(BytesIO):
def read(self, size=None):
import random
size = random.randint(1, size)
- return super(BytesIOSRandomSize, self).read(size)
+ return super().read(size)
def roundtrip(arr):
diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py
index 4c7c0480c..a4f49a78b 100644
--- a/numpy/lib/tests/test_function_base.py
+++ b/numpy/lib/tests/test_function_base.py
@@ -1798,6 +1798,24 @@ class TestUnwrap:
assert_array_equal(unwrap([1, 1 + 2 * np.pi]), [1, 1])
# check that unwrap maintains continuity
assert_(np.all(diff(unwrap(rand(10) * 100)) < np.pi))
+
+ def test_period(self):
+ # check that unwrap removes jumps greater that 255
+ assert_array_equal(unwrap([1, 1 + 256], period=255), [1, 2])
+ # check that unwrap maintains continuity
+ assert_(np.all(diff(unwrap(rand(10) * 1000, period=255)) < 255))
+ # check simple case
+ simple_seq = np.array([0, 75, 150, 225, 300])
+ wrap_seq = np.mod(simple_seq, 255)
+ assert_array_equal(unwrap(wrap_seq, period=255), simple_seq)
+ # check custom discont value
+ uneven_seq = np.array([0, 75, 150, 225, 300, 430])
+ wrap_uneven = np.mod(uneven_seq, 250)
+ no_discont = unwrap(wrap_uneven, period=250)
+ assert_array_equal(no_discont, [0, 75, 150, 225, 300, 180])
+ sm_discont = unwrap(wrap_uneven, period=250, discont=140)
+ assert_array_equal(sm_discont, [0, 75, 150, 225, 300, 430])
+ assert sm_discont.dtype == wrap_uneven.dtype
class TestFilterwindows:
@@ -2307,6 +2325,27 @@ class TestMeshgrid:
assert_equal(x[0, :], 0)
assert_equal(x[1, :], X)
+ def test_nd_shape(self):
+ a, b, c, d, e = np.meshgrid(*([0] * i for i in range(1, 6)))
+ expected_shape = (2, 1, 3, 4, 5)
+ assert_equal(a.shape, expected_shape)
+ assert_equal(b.shape, expected_shape)
+ assert_equal(c.shape, expected_shape)
+ assert_equal(d.shape, expected_shape)
+ assert_equal(e.shape, expected_shape)
+
+ def test_nd_values(self):
+ a, b, c = np.meshgrid([0], [1, 2], [3, 4, 5])
+ assert_equal(a, [[[0, 0, 0]], [[0, 0, 0]]])
+ assert_equal(b, [[[1, 1, 1]], [[2, 2, 2]]])
+ assert_equal(c, [[[3, 4, 5]], [[3, 4, 5]]])
+
+ def test_nd_indexing(self):
+ a, b, c = np.meshgrid([0], [1, 2], [3, 4, 5], indexing='ij')
+ assert_equal(a, [[[0, 0, 0], [0, 0, 0]]])
+ assert_equal(b, [[[1, 1, 1], [2, 2, 2]]])
+ assert_equal(c, [[[3, 4, 5], [3, 4, 5]]])
+
class TestPiecewise:
@@ -2399,6 +2438,14 @@ class TestPiecewise:
assert_array_equal(y, np.array([[-1., -1., -1.],
[3., 3., 1.]]))
+ def test_subclasses(self):
+ class subclass(np.ndarray):
+ pass
+ x = np.arange(5.).view(subclass)
+ r = piecewise(x, [x<2., x>=4], [-1., 1., 0.])
+ assert_equal(type(r), subclass)
+ assert_equal(r, [-1., -1., 0., 0., 1.])
+
class TestBincount:
@@ -2721,6 +2768,10 @@ class TestPercentile:
assert_equal(p, Fraction(7, 4))
assert_equal(type(p), Fraction)
+ p = np.percentile(x, [Fraction(50)])
+ assert_equal(p, np.array([Fraction(7, 4)]))
+ assert_equal(type(p), np.ndarray)
+
def test_api(self):
d = np.ones(5)
np.percentile(d, 5, None, None, False)
@@ -3115,6 +3166,16 @@ class TestPercentile:
assert_equal(np.percentile(
a, [0.3, 0.6], (0, 2), interpolation='nearest'), b)
+ def test_nan_q(self):
+ # GH18830
+ with pytest.raises(ValueError, match="Percentiles must be in"):
+ np.percentile([1, 2, 3, 4.0], np.nan)
+ with pytest.raises(ValueError, match="Percentiles must be in"):
+ np.percentile([1, 2, 3, 4.0], [np.nan])
+ q = np.linspace(1.0, 99.0, 16)
+ q[0] = np.nan
+ with pytest.raises(ValueError, match="Percentiles must be in"):
+ np.percentile([1, 2, 3, 4.0], q)
class TestQuantile:
# most of this is already tested by TestPercentile
@@ -3151,6 +3212,14 @@ class TestQuantile:
assert_equal(q, Fraction(7, 4))
assert_equal(type(q), Fraction)
+ q = np.quantile(x, [Fraction(1, 2)])
+ assert_equal(q, np.array([Fraction(7, 4)]))
+ assert_equal(type(q), np.ndarray)
+
+ q = np.quantile(x, [[Fraction(1, 2)]])
+ assert_equal(q, np.array([[Fraction(7, 4)]]))
+ assert_equal(type(q), np.ndarray)
+
# repeat with integral input but fractional quantile
x = np.arange(8)
assert_equal(np.quantile(x, Fraction(1, 2)), Fraction(7, 2))
diff --git a/numpy/lib/tests/test_index_tricks.py b/numpy/lib/tests/test_index_tricks.py
index 843e27cef..c21aefd1a 100644
--- a/numpy/lib/tests/test_index_tricks.py
+++ b/numpy/lib/tests/test_index_tricks.py
@@ -16,23 +16,13 @@ class TestRavelUnravelIndex:
def test_basic(self):
assert_equal(np.unravel_index(2, (2, 2)), (1, 0))
- # test backwards compatibility with older dims
- # keyword argument; see Issue #10586
- with assert_warns(DeprecationWarning):
- # we should achieve the correct result
- # AND raise the appropriate warning
- # when using older "dims" kw argument
- assert_equal(np.unravel_index(indices=2,
- dims=(2, 2)),
- (1, 0))
-
# test that new shape argument works properly
assert_equal(np.unravel_index(indices=2,
shape=(2, 2)),
(1, 0))
# test that an invalid second keyword argument
- # is properly handled
+ # is properly handled, including the old name `dims`.
with assert_raises(TypeError):
np.unravel_index(indices=2, hape=(2, 2))
@@ -42,6 +32,9 @@ class TestRavelUnravelIndex:
with assert_raises(TypeError):
np.unravel_index(254, ims=(17, 94))
+ with assert_raises(TypeError):
+ np.unravel_index(254, dims=(17, 94))
+
assert_equal(np.ravel_multi_index((1, 0), (2, 2)), 2)
assert_equal(np.unravel_index(254, (17, 94)), (2, 66))
assert_equal(np.ravel_multi_index((2, 66), (17, 94)), 254)
diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py
index aa4499764..534ab683c 100644
--- a/numpy/lib/tests/test_io.py
+++ b/numpy/lib/tests/test_io.py
@@ -580,7 +580,7 @@ class TestSaveTxt:
memoryerror_raised.value = False
try:
# The test takes at least 6GB of memory, writes a file larger
- # than 4GB
+ # than 4GB. This tests the ``allowZip64`` kwarg to ``zipfile``
test_data = np.asarray([np.random.rand(
np.random.randint(50,100),4)
for i in range(800000)], dtype=object)
@@ -599,6 +599,9 @@ class TestSaveTxt:
p.join()
if memoryerror_raised.value:
raise MemoryError("Child process raised a MemoryError exception")
+ # -9 indicates a SIGKILL, probably an OOM.
+ if p.exitcode == -9:
+ pytest.xfail("subprocess got a SIGKILL, apparently free memory was not sufficient")
assert p.exitcode == 0
class LoadTxtBase:
diff --git a/numpy/lib/tests/test_nanfunctions.py b/numpy/lib/tests/test_nanfunctions.py
index e0f723a3c..1f1f5601b 100644
--- a/numpy/lib/tests/test_nanfunctions.py
+++ b/numpy/lib/tests/test_nanfunctions.py
@@ -588,6 +588,15 @@ class TestNanFunctions_MeanVarStd(SharedNanFunctionsTestsMixin):
assert_(len(w) == 0)
+_TIME_UNITS = (
+ "Y", "M", "W", "D", "h", "m", "s", "ms", "us", "ns", "ps", "fs", "as"
+)
+
+# All `inexact` + `timdelta64` type codes
+_TYPE_CODES = list(np.typecodes["AllFloat"])
+_TYPE_CODES += [f"m8[{unit}]" for unit in _TIME_UNITS]
+
+
class TestNanFunctions_Median:
def test_mutation(self):
@@ -662,23 +671,32 @@ class TestNanFunctions_Median:
res = np.nanmedian(_ndat, axis=1)
assert_almost_equal(res, tgt)
- def test_allnans(self):
- mat = np.array([np.nan]*9).reshape(3, 3)
- for axis in [None, 0, 1]:
- with suppress_warnings() as sup:
- sup.record(RuntimeWarning)
+ @pytest.mark.parametrize("axis", [None, 0, 1])
+ @pytest.mark.parametrize("dtype", _TYPE_CODES)
+ def test_allnans(self, dtype, axis):
+ mat = np.full((3, 3), np.nan).astype(dtype)
+ with suppress_warnings() as sup:
+ sup.record(RuntimeWarning)
- assert_(np.isnan(np.nanmedian(mat, axis=axis)).all())
- if axis is None:
- assert_(len(sup.log) == 1)
- else:
- assert_(len(sup.log) == 3)
- # Check scalar
- assert_(np.isnan(np.nanmedian(np.nan)))
- if axis is None:
- assert_(len(sup.log) == 2)
- else:
- assert_(len(sup.log) == 4)
+ output = np.nanmedian(mat, axis=axis)
+ assert output.dtype == mat.dtype
+ assert np.isnan(output).all()
+
+ if axis is None:
+ assert_(len(sup.log) == 1)
+ else:
+ assert_(len(sup.log) == 3)
+
+ # Check scalar
+ scalar = np.array(np.nan).astype(dtype)[()]
+ output_scalar = np.nanmedian(scalar)
+ assert output_scalar.dtype == scalar.dtype
+ assert np.isnan(output_scalar)
+
+ if axis is None:
+ assert_(len(sup.log) == 2)
+ else:
+ assert_(len(sup.log) == 4)
def test_empty(self):
mat = np.zeros((0, 3))
diff --git a/numpy/lib/tests/test_polynomial.py b/numpy/lib/tests/test_polynomial.py
index 6c3e4fa02..3734344d2 100644
--- a/numpy/lib/tests/test_polynomial.py
+++ b/numpy/lib/tests/test_polynomial.py
@@ -4,6 +4,12 @@ from numpy.testing import (
assert_array_almost_equal, assert_raises, assert_allclose
)
+import pytest
+
+# `poly1d` has some support for `bool_` and `timedelta64`,
+# but it is limited and they are therefore excluded here
+TYPE_CODES = np.typecodes["AllInteger"] + np.typecodes["AllFloat"] + "O"
+
class TestPolynomial:
def test_poly1d_str_and_repr(self):
@@ -57,11 +63,26 @@ class TestPolynomial:
assert_equal(np.polydiv(np.poly1d([1, 0, -1]), np.poly1d([1, 1])),
(np.poly1d([1., -1.]), np.poly1d([0.])))
- def test_poly1d_misc(self):
- p = np.poly1d([1., 2, 3])
- assert_equal(np.asarray(p), np.array([1., 2., 3.]))
+ @pytest.mark.parametrize("type_code", TYPE_CODES)
+ def test_poly1d_misc(self, type_code: str) -> None:
+ dtype = np.dtype(type_code)
+ ar = np.array([1, 2, 3], dtype=dtype)
+ p = np.poly1d(ar)
+
+ # `__eq__`
+ assert_equal(np.asarray(p), ar)
+ assert_equal(np.asarray(p).dtype, dtype)
assert_equal(len(p), 2)
- assert_equal((p[0], p[1], p[2], p[3]), (3.0, 2.0, 1.0, 0))
+
+ # `__getitem__`
+ comparison_dct = {-1: 0, 0: 3, 1: 2, 2: 1, 3: 0}
+ for index, ref in comparison_dct.items():
+ scalar = p[index]
+ assert_equal(scalar, ref)
+ if dtype == np.object_:
+ assert isinstance(scalar, int)
+ else:
+ assert_equal(scalar.dtype, dtype)
def test_poly1d_variable_arg(self):
q = np.poly1d([1., 2, 3], variable='y')
@@ -257,7 +278,7 @@ class TestPolynomial:
assert_equal(q.coeffs.dtype, np.complex128)
assert_equal(r.coeffs.dtype, np.complex128)
assert_equal(q*a + r, b)
-
+
c = [1, 2, 3]
d = np.poly1d([1, 2, 3])
s, t = np.polydiv(c, d)
diff --git a/numpy/lib/tests/test_regression.py b/numpy/lib/tests/test_regression.py
index 55df2a675..373226277 100644
--- a/numpy/lib/tests/test_regression.py
+++ b/numpy/lib/tests/test_regression.py
@@ -1,3 +1,5 @@
+import pytest
+
import os
import numpy as np
diff --git a/numpy/lib/tests/test_utils.py b/numpy/lib/tests/test_utils.py
index 33951b92a..8a877ae69 100644
--- a/numpy/lib/tests/test_utils.py
+++ b/numpy/lib/tests/test_utils.py
@@ -4,7 +4,7 @@ import pytest
from numpy.core import arange
from numpy.testing import assert_, assert_equal, assert_raises_regex
-from numpy.lib import deprecate
+from numpy.lib import deprecate, deprecate_with_doc
import numpy.lib.utils as utils
from io import StringIO
@@ -60,6 +60,11 @@ def old_func6(self, x):
new_func6 = deprecate(old_func6)
+@deprecate_with_doc(msg="Rather use new_func7")
+def old_func7(self,x):
+ return x
+
+
def test_deprecate_decorator():
assert_('deprecated' in old_func.__doc__)
@@ -73,6 +78,10 @@ def test_deprecate_fn():
assert_('new_func3' in new_func3.__doc__)
+def test_deprecate_with_doc_decorator_message():
+ assert_('Rather use new_func7' in old_func7.__doc__)
+
+
@pytest.mark.skipif(sys.flags.optimize == 2, reason="-OO discards docstrings")
@pytest.mark.parametrize('old_func, new_func', [
(old_func4, new_func4),