简体   繁体   中英

Python testing with parameterization from function return

I've been trying to solve a python test using pytest but have not been able to find an example configuration that works - though some are close. Here is my case study:

@pytest.fixture
def vil_check():
   code
   return [(v1,v2,v3), (...), (...)]

@pytest.mark.parameterize("v1,v2,v3", vil_check):
def test_one(v1,v2,v3):
      assert v1 < 2
      assert v2 > 5
      ....

I'm trying to follow this example:

@pytest.mark.parametrize("test_input,expected", [("3+5", 8), ("2+4", 6), ("6*9", 42)])
def test_eval(test_input, expected):
    assert eval(test_input) == expected

But using a fixture to supply the list: [("3+5", 8), ("2+4", 6), ("6*9", 42)] .

However, this configuration doesn't work:

@pytest.mark.parametrize("v1, v2, v3", vil_check)
def test_max(v1, v2, v3):
   assert abs(v1) <= 5

The error is that pytest doesn't see vil_check return as iterable. There seems to be a way to use pytest_generate_tests to accomplish this but I'm drawing a blank on how to write it.

As per OP's comment, because vil_check need not be a fixture, here's what you can do - remove the fixture decorator from vil_check and call it in mark.parametrize` below:

def vil_check():
   # code
   yield from [(v1,v2,v3), (...), (...)]

@pytest.mark.parametrize("v1,v2,v3", vil_check()):
def test_one(v1,v2,v3):
      assert v1 < 2
      assert v2 > 5
      # code

Few points:

  • you have spelled parametrized wrong, this may give you error if you have set --strict-markers .
  • the decorator should not have a :
  • for performance, i used yield from instead of return in vil_check . This will be efficient in case the list is huge

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM