Description
With plain python lists I can do:
a = [1, 2, 3]
b = [1, 2, 4]
assert a == b
That does not work for numpy arrays
a = np.array([1, 2, 3])
b = np.array([1, 2, 4])
> assert a == b
E ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
There are two ways out:
-
Using numpy.testing
np.testing.assert_equal(a, b)
This has the advantage of giving good context information on the error.
But it is far from the simple assertassert a == b
paradigm in pytest. -
Alternatively we can aggregate the the check to a single bool
assert np.all(a == b)
This looks much nicer, but pytest cannot tell anymore where the error is:
> assert np.all(a == b) E assert False E + where False = <function all at 0x7f57cd65eea0>(array([1, 2, 3]) == array([1, 2, 4]) E + where <function all at 0x7f57cd65eea0> = np.all
Question: Would it in principle be possible with pytest's introspection capabilities to resolve the contents of np.all()
and give a better error message? In a frist step maybe something like
assert np.all(a == b)
At index 2: False
This of course, would require an assumption on the semantics of np.all
.
Alternative idea: Could pytest be made to rewrite Possibly not a good idea because it introduces a different semantic compared to a plain assert a == b
to np.testing.assert_equal(a, b)
if either a or b is a numpy array?a == b
.