Skip to content

Commit

Permalink
Add support for pytest.approx comparisons between scalar and array (i…
Browse files Browse the repository at this point in the history
…nverted order)
  • Loading branch information
tadeu committed Mar 14, 2018
1 parent c34dde7 commit 161d4e5
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
15 changes: 10 additions & 5 deletions _pytest/python_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,12 +88,14 @@ def __repr__(self):
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)
Expand All @@ -108,6 +110,9 @@ def _yield_comparisons(self, actual):
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]
Expand Down
11 changes: 11 additions & 0 deletions testing/python/approx.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,3 +402,14 @@ def test_numpy_array_with_scalar(self):
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

0 comments on commit 161d4e5

Please sign in to comment.