Add support for pytest.approx comparisons between scalar and array (inverted order)
This commit is contained in:
parent
c34dde7a3f
commit
161d4e5fe4
|
@ -88,12 +88,14 @@ class ApproxNumpy(ApproxBase):
|
||||||
def __eq__(self, actual):
|
def __eq__(self, actual):
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
try:
|
if not np.isscalar(actual):
|
||||||
actual = np.asarray(actual)
|
try:
|
||||||
except: # noqa
|
actual = np.asarray(actual)
|
||||||
raise TypeError("cannot compare '{0}' to numpy.ndarray".format(actual))
|
except: # noqa
|
||||||
|
raise TypeError("cannot compare '{0}' to numpy.ndarray".format(actual))
|
||||||
|
|
||||||
if not np.isscalar(self.expected) and actual.shape != self.expected.shape:
|
if (not np.isscalar(self.expected) and not np.isscalar(actual)
|
||||||
|
and actual.shape != self.expected.shape):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
return ApproxBase.__eq__(self, actual)
|
return ApproxBase.__eq__(self, actual)
|
||||||
|
@ -108,6 +110,9 @@ class ApproxNumpy(ApproxBase):
|
||||||
if np.isscalar(self.expected):
|
if np.isscalar(self.expected):
|
||||||
for i in np.ndindex(actual.shape):
|
for i in np.ndindex(actual.shape):
|
||||||
yield actual[i], self.expected
|
yield actual[i], self.expected
|
||||||
|
elif np.isscalar(actual):
|
||||||
|
for i in np.ndindex(self.expected.shape):
|
||||||
|
yield actual, self.expected[i]
|
||||||
else:
|
else:
|
||||||
for i in np.ndindex(self.expected.shape):
|
for i in np.ndindex(self.expected.shape):
|
||||||
yield actual[i], self.expected[i]
|
yield actual[i], self.expected[i]
|
||||||
|
|
|
@ -402,3 +402,14 @@ class TestApprox(object):
|
||||||
assert actual != approx(expected, rel=5e-8, abs=0)
|
assert actual != approx(expected, rel=5e-8, abs=0)
|
||||||
assert approx(expected, rel=5e-7, abs=0) == actual
|
assert approx(expected, rel=5e-7, abs=0) == actual
|
||||||
assert approx(expected, rel=5e-8, abs=0) != actual
|
assert approx(expected, rel=5e-8, abs=0) != actual
|
||||||
|
|
||||||
|
def test_numpy_scalar_with_array(self):
|
||||||
|
np = pytest.importorskip('numpy')
|
||||||
|
|
||||||
|
actual = 1.0
|
||||||
|
expected = np.array([1 + 1e-7, 1 - 1e-8])
|
||||||
|
|
||||||
|
assert actual == approx(expected, rel=5e-7, abs=0)
|
||||||
|
assert actual != approx(expected, rel=5e-8, abs=0)
|
||||||
|
assert approx(expected, rel=5e-7, abs=0) == actual
|
||||||
|
assert approx(expected, rel=5e-8, abs=0) != actual
|
||||||
|
|
Loading…
Reference in New Issue