Python 使用函数的参数化进行测试 return

Python testing with parameterization from function return

我一直在尝试使用 pytest 解决 python 测试,但未能找到有效的示例配置 - 尽管有些很接近。这是我的案例研究:

@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
      ....

我正在尝试效仿这个例子:

@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

但使用 fixture 提供列表:[("3+5", 8), ("2+4", 6), ("6*9", 42)].

但是,此配置不起作用:

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

错误是 pytest 没有将 vil_check return 视为可迭代的。 似乎有一种方法可以使用 pytest_generate_tests 来完成此操作,但我对如何编写它一无所知。

根据 OP 的评论,因为 vil_check 不需要固定装置,所以您可以这样做 - 从 vil_checkcall 中删除 fixture 装饰器mark.parametrize 下面:

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

几点:

  • 你拼错了parametrized,如果你设置了--strict-markers.
  • ,这可能会给你带来错误
  • 装饰器不应该有 :
  • 为了性能,我在 vil_check 中使用 yield from 而不是 return。如果列表很大
  • ,这将是有效的