Add support for pytest.approx comparisons between scalar and array (inverted order)

This commit is contained in:
Tadeu Manoel 2018-03-14 16:29:04 -03:00
parent c34dde7a3f
commit 161d4e5fe4
2 changed files with 21 additions and 5 deletions

View File

@ -88,12 +88,14 @@ class ApproxNumpy(ApproxBase):
def __eq__(self, actual):
import numpy as np
try:
actual = np.asarray(actual)
except: # noqa
raise TypeError("cannot compare '{0}' to numpy.ndarray".format(actual))
if not np.isscalar(actual):
try:
actual = np.asarray(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 ApproxBase.__eq__(self, actual)
@ -108,6 +110,9 @@ class ApproxNumpy(ApproxBase):
if np.isscalar(self.expected):
for i in np.ndindex(actual.shape):
yield actual[i], self.expected
elif np.isscalar(actual):
for i in np.ndindex(self.expected.shape):
yield actual, self.expected[i]
else:
for i in np.ndindex(self.expected.shape):
yield actual[i], self.expected[i]

View File

@ -402,3 +402,14 @@ class TestApprox(object):
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
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