pytest.approx raises TypeError for 0-d numpy array

Created on 17 Jun 2018  路  6Comments  路  Source: pytest-dev/pytest

This works:

>>> import pytest
>>> pytest.approx(5.)
5.0 卤 5.0e-06

This doesn't work:

>>> import pytest; import numpy as np
>>> pytest.approx(np.array(5.))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/_pytest/python_api.py", line 83, in __repr__
    self._approx_scalar(x) for x in np.asarray(self.expected)))
TypeError: iteration over a 0-d array

This looks like a bug to me.

pytest 3.6.0
numpy 1.14.3

Thanks, Florian

bug

Most helpful comment

Just to point it out, that ApproxNumpy class seems to mostly use the ndindex iteration, which should correctly give () (the empty tuple) as the only, correct, index into the array? So the problem might only be in the representation itself? Not sure if that matters to you or not.

All 6 comments

GitMate.io thinks possibly related issues are https://github.com/pytest-dev/pytest/issues/1994 (Supporting arrays for approx), https://github.com/pytest-dev/pytest/issues/3312 (pytest.approx doesn't support comparison between arrays and scalars), https://github.com/pytest-dev/pytest/issues/3449 (pytest.approx gives wrong result when compared with numpy types), https://github.com/pytest-dev/pytest/issues/213 (Issue with numpy arrays and pytest.mark.parametrize), and https://github.com/pytest-dev/pytest/issues/1965 (Pytest 3.0.2 memory leak with pytest.raises).

it is, if you got an idea how to fix it please go ahead ^^

cc @tadeu which contributed the numpy support. 馃憤

Maybe it's an error with numpy, because if you do

one_element = np.array(5)
list_one_element = one_element.tolist()

it will return to you just a scalar 5, which is strange because you asked numpy to return a list. I think we have to check this if it's the expected behavior of numpy. However, I did a very simple fix for that which you can find here #3615

Just to point it out, that ApproxNumpy class seems to mostly use the ndindex iteration, which should correctly give () (the empty tuple) as the only, correct, index into the array? So the problem might only be in the representation itself? Not sure if that matters to you or not.

Was this page helpful?
0 / 5 - 0 ratings