Pytest: Fixture parametrization breaks if parameter is a numpy array

Created on 11 Oct 2019  路  2Comments  路  Source: pytest-dev/pytest


Description

On latest release and also on master branch, windows 10

The following test:

from numpy import linspace
from pytest import fixture

@fixture(params=linspace(1, 10, 10))
def value(request):
    return request.param

def test_bug(value):
    assert value == value

breaks with:

Traceback (most recent call last):
  File "D:/WORK/pytest-nparray-params-bug/test_bug.py", line 4, in <module>
    @fixture(params=linspace(1, 10, 10))
  File "D:\WORK\pytest-nparray-params-bug\venv\lib\site-packages\_pytest\fixtures.py", line 1123, in fixture
    name=name
  File "D:\WORK\pytest-nparray-params-bug\venv\lib\site-packages\_pytest\fixtures.py", line 1032, in _parse_fixture_args
    key: value for key, value in kwargs.items() if arguments.get(key) != value
  File "D:\WORK\pytest-nparray-params-bug\venv\lib\site-packages\_pytest\fixtures.py", line 1032, in <dictcomp>
    key: value for key, value in kwargs.items() if arguments.get(key) != value
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Cause

It seems that this line:

https://github.com/pytest-dev/pytest/blob/b162ab6a45d5432744b193bb2efbd80a6fe2cc6c/src/_pytest/fixtures.py#L1031-L1033

Tries to get a boolean result from comparing None != <array> which is ambiguous.

Possible solution

This might be solved by moving the cast to list (line 1137) at the very beginning (1116) of this function:

https://github.com/pytest-dev/pytest/blob/b162ab6a45d5432744b193bb2efbd80a6fe2cc6c/src/_pytest/fixtures.py#L1116-L1139

I am actually running tests with this change but not 100% certain about side-effects, although it seems to be that casting to list that soon should not cause problems (equivalent of casting to list in user test code).

If you think this is okay I can create the PR.

  • [x] a detailed description of the bug or suggestion
  • [ ] output of pip list from the virtual environment you are using
  • [x] pytest and operating system versions
  • [x] minimal example if possible
fixtures parametrize bug

All 2 comments

Hi @Sup3rGeo,

Thanks a lot for the report and detailed proposed solution.

I don't think this will have any side-effects, please open a PR! Thanks!

FYI @Sup3rGeo you can get syntax highlighting for code blocks on GitHub, relevantly for python and python-traceback (and pycon for a REPL session) :smile:

Thanks for reporting this, and for suggesting a fix!

Was this page helpful?
0 / 5 - 0 ratings