Skip to content

Commit 7d8688d

Browse files
committed
Reflect dimension in approx repr for numpy arrays.
1 parent 2534193 commit 7d8688d

File tree

2 files changed

+21
-15
lines changed

2 files changed

+21
-15
lines changed

src/_pytest/python_api.py

+9-5
Original file line numberDiff line numberDiff line change
@@ -82,14 +82,18 @@ class ApproxNumpy(ApproxBase):
8282
"""
8383

8484
def __repr__(self):
85-
# It might be nice to rewrite this function to account for the
86-
# shape of the array...
8785
import numpy as np
8886

89-
list_scalars = []
90-
for x in np.ndindex(self.expected.shape):
91-
list_scalars.append(self._approx_scalar(np.asscalar(self.expected[x])))
87+
def recursive_map(f, x):
88+
if isinstance(x, list):
89+
return list(recursive_map(f, xi) for xi in x)
90+
else:
91+
return f(x)
9292

93+
list_scalars = recursive_map(
94+
self._approx_scalar,
95+
self.expected.tolist())
96+
9397
return "approx({!r})".format(list_scalars)
9498

9599
if sys.version_info[0] == 2:

testing/python/approx.py

+12-10
Original file line numberDiff line numberDiff line change
@@ -59,17 +59,19 @@ def test_repr_string(self, plus_minus):
5959
),
6060
)
6161

62-
def test_repr_0d_array(self, plus_minus):
62+
def test_repr_nd_array(self, plus_minus):
63+
# Make sure that arrays of all different dimensions are repr'd
64+
# correctly.
6365
np = pytest.importorskip("numpy")
64-
np_array = np.array(5.)
65-
assert approx(np_array) == 5.0
66-
string_expected = "approx([5.0 {} 5.0e-06])".format(plus_minus)
67-
68-
assert repr(approx(np_array)) == string_expected
69-
70-
np_array = np.array([5.])
71-
assert approx(np_array) == 5.0
72-
assert repr(approx(np_array)) == string_expected
66+
examples = [
67+
(np.array(5.), 'approx(5.0 {pm} 5.0e-06)'),
68+
(np.array([5.]), 'approx([5.0 {pm} 5.0e-06])'),
69+
(np.array([[5.]]), 'approx([[5.0 {pm} 5.0e-06]])'),
70+
(np.array([[5., 6.]]), 'approx([[5.0 {pm} 5.0e-06, 6.0 {pm} 6.0e-06]])'),
71+
(np.array([[5.], [6.]]), 'approx([[5.0 {pm} 5.0e-06], [6.0 {pm} 6.0e-06]])'),
72+
]
73+
for np_array, repr_string in examples:
74+
assert repr(approx(np_array)) == repr_string.format(pm=plus_minus)
7375

7476
def test_operator_overloading(self):
7577
assert 1 == approx(1, rel=1e-6, abs=1e-12)

0 commit comments

Comments
 (0)