【问题标题】:pytest parameterize - row from CSV as a testcasepytest 参数化 - 来自 CSV 的行作为测试用例
【发布时间】:2014-02-21 09:52:34
【问题描述】:

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

这是伪代码:

class test_mytest:
  def test_rows:
    for row in csvreader:
       run_method(row)
       for onecol in row:
          run_method2(onecol)

我已尝试阅读 pytest 文档,但我不清楚。

这是我使用 generate_tests hook for row 作为参数所做的事情。我想知道如何对内部 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)

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

感谢您的帮助。谢谢

【问题讨论】:

    标签: python rows pytest parameterized-tests


    【解决方案1】:

    您可能希望使用pytest_generate_tests() 挂钩,如下所述:https://docs.pytest.org/en/stable/parametrize.html#pytest-generate-tests 这允许您读取 csv 文件并根据其内容对所需的测试进行参数化。

    更新

    更新后的问题似乎并不完全清楚,但我假设您需要在一行和一列上测试某些内容。这只是要求进行两个测试:

    def test_row(row):
        assert row  # or whatever
    
    def test_column(col):
        assert col  # or whatever
    

    现在剩下的就是使用pytest_generate_tests() 钩子为rowcol 创建参数化的fixture。所以在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)))
    

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

    【讨论】:

    • 嘿,感谢您的回复。我之前阅读了该链接并尝试了 pytest_generate_tests() 挂钩。有一些问题,但现在已解决。这个链接最能帮助我理解holgerkrekel.net/2009/05/13/…
    • 现在为了生成报告,我需要让内部 for 循环也看起来像一个测试用例。有什么想法吗?
    • 你能用实际的pytest_generate_tests() 代码更新问题,并可能显示一两个参数化的测试函数吗?否则很难猜出你的意思。
    • 嗨,flub,我更新了这个问题。你能帮我解决这个要求吗?我试过参数化标记,也试过@params。另一个快速信息是,对于我在 python greenlets 中使用的第二个函数
    猜你喜欢
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    相关资源
    最近更新 更多