首页 > 解决方案 > 如何在 pytest 中迭代 test_function 以获得多个值?

问题描述

我想知道如何在 pytest 中迭代 test_funtion() 以获得不同的值?例如。

list = ['ls','ps', 'df' ,'du'] #list of Linux commands
def test_method(self):
    for I in list:
       r=subprocess.check_output(I)
       if r:
          assert True
       else: 
          assert False

现在,当我运行 pytest -k test_method 时,它显示只有一个测试用例通过。但我希望所有 4 个案例都使用单个函数运行,并且需要在输出中传递 4 个测试用例。我怎样才能实现它?

标签: pythonlinuxintegration-testingpytestpython-unittest

解决方案


扩展@Nithin-Mohan 先前的回答

commands = ['ls','ps', 'df' ,'du'] #list of Linux commands
@pytest.mark.parametrize("cmds",commands)
def test_method(cmds):
   r=subprocess.check_output(cmds)
   if r:
      assert True
   else:
      assert False

这是作为 4 个单独测试运行的输出

 test_sflow.py::test_method[ls] PASSED [ 25%]                                                                                                                                                                                                          
 test_sflow.py::test_method[ps] PASSED [ 50%]                                                                                                                                                                                                         
 test_sflow.py::test_method[df] PASSED [ 75%]                                                                                                                                                                                                       
 test_sflow.py::test_method[du] PASSED [ 100%]

推荐阅读