[英]How to use pytest mark parametrize with functions with multiple arguments
如何在 pytest 中使用导入的 CSV 中的值? 这些函数采用多个参数(关键字和位置的混合)。 我查看了@pytest.mark.parametrize,但我不明白如何使用多个参数。
我正在使用 np.genfromtxt 导入,但这是一个包含列名的 MRE:
import pytest
import numpy.lib.recfunctions as rf
def squared(x, *, y):
return (x + y) ** 2
def cubed(x, *, y):
return (x + y) ** 3
mycsv = np.array(([1, 2, 3], [5, 5, 5], [36, 49, 64], [216, 343, 512]))
dtypes = [("a", "f8"), ("b", "f8"), ("f_squared", "f8"), ("f_cubed", "f8")]
mycsv = rf.unstructured_to_structured(mycsv, dtype=np.dtype(dtypes))
## do this for all rows in mycsv
def test_squared():
# how do extract 'a' and 'b' from mycsv["a"] and mycsv["b"]
# expected is in 'f_squared' how to get this from mycsv["f_squared"]
computed = squared(x=a, y=b)
msg = f"""Failed for x {a} at y {b},
Expected {expected}, computed {computed}."""
np.testing.assert_allclose(expected, computed, rtol=2e-2, err_msg=msg)
我认为这是您正在寻找的语法:
@pytest.mark.parametrize("a, b, expected, _f3", mycsv)
def test_squared(a, b, expected, _f3):
...
这应该生成 3 个通过测试:
$ python -m pytest
...
test_x.py::test_squared[1.0-5.0-36.0-216.0] PASSED [ 33%]
test_x.py::test_squared[2.0-5.0-49.0-343.0] PASSED [ 66%]
test_x.py::test_squared[3.0-5.0-64.0-512.0] PASSED [100%]
请注意,我需要转置您的示例数组才能使其正常工作,否则形状与数据类型不匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.