pytest parameterize - 从CSV行作为测试用例

use*_*988 1 python rows pytest parameterized-tests

我必须读取一个CSV文件,并且每行中的每个组合都需要运行一些方法.我希望将每一行视为测试用例.是否可以将行作为参数发送 - pytest参数化我的测试用例?你能告诉我一些关于如何做到这一点的想法吗?

这是伪代码:

class test_mytest:
  def test_rows:
    for row in csvreader:
       run_method(row)
       for onecol in row:
          run_method2(onecol)
Run Code Online (Sandbox Code Playgroud)

我试过阅读pytest文档,但对我来说并不清楚.

这是我正在做的使用generate_tests hook for row作为param.我想知道如何为内部for循环函数做同样的事情 - 这个内部循环也应该作为测试用例收集

def pytest_generate_tests(metafunc):
    read_csvrows()
    for funcargs in metafunc.cls.params[metafunc.function.__name__]:
        # schedule a new test function run with applied **funcargs
        metafunc.addcall(funcargs=funcargs)

class TestClass:

    params = {
       'test_rows': rows,   
    }
    def test_rows:
        run_method(row)
        for onecol in row:
             test_method2(onecol)
Run Code Online (Sandbox Code Playgroud)

现在,我需要为-for循环调用test_method2生成报告(它是csv文件每行中列中元素列表的参数化方法).Pytest也需要收集那些作为测试用例.

感谢你的帮助.谢谢

flu*_*lub 5

你可能想要使用pytest_generate_tests()这里描述的钩子:https://docs.pytest.org/en/latest/parametrize.html#pytest-generate-tests 这允许你阅读csv文件并参数化你想要的测试关于它的内容.

更新:

更新后的问题似乎并不完全清楚,但我假设你需要在一行和一列上测试一些东西.这只需要两个测试:

def test_row(row):
    assert row  # or whatever

def test_column(col):
    assert col  # or whatever
Run Code Online (Sandbox Code Playgroud)

现在剩下的工作就是创建参数化的固定装置rowcol使用pytest_generate_tests()挂钩.所以在conftest.py文件中:

def test_generate_tests(metafunc):
    rows = read_csvrows()
    if 'row' in metafunc.fixturenames:
        metafunc.parametrize('row', rows)
    if 'col' in metafunc.fixturenames:
        metafunc.parametrize('col', list(itertools.chain(*rows)))
Run Code Online (Sandbox Code Playgroud)

请注意使用推荐的metafunc.parametrize()函数而不是已弃用的函数metafunc.addcall()