简体   繁体   中英

How to use pytest mark parametrize with functions with multiple arguments

How can I use the values from an imported CSV in pytest? The functions take multiple arguments (mix of keyword and positional). I looked at @pytest.mark.parametrize but I didn't understand how to use multiple arguments.

I am importing using np.genfromtxt, but here is an MRE with the column names:

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)

I think this is the syntax you're looking for:

@pytest.mark.parametrize("a, b, expected, _f3", mycsv)
def test_squared(a, b, expected, _f3):
    ...

This should generate 3 passing tests:

$ 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%]

Note that I needed to transpose your example array to get this working, otherwise there is a shape mismatch with the dtypes.

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