Skip to main content
 首页 » 编程设计

python之pytest在类中以正确的顺序运行场景

2025年05月04日19lyj

所以我有以下结构:

class Test(object): 
 
   def test_1(self): 
      pass 
 
   def test_2(self): 
      pass 
 
   def test_3(self): 
      pass 

它运行得很好,现在我正在添加“场景”(在 pytest - A quick port of “testscenarios” 中推荐):

def pytest_generate_tests(metafunc): 
    idlist = [] 
    argvalues = [] 
    for scenario in metafunc.cls.scenarios: 
        idlist.append(scenario[0]) 
        items = scenario[1].items() 
        argnames = [x[0] for x in items] 
        argvalues.append(([x[1] for x in items])) 
    metafunc.parametrize(argnames, argvalues, ids=idlist) 
 
class Test(object): 
       scenarios = ['1' {'arg':'value1'}, 
                    '2' {'arg':'value2'}] 
 
       def test_1(self, arg): 
          pass 
 
       def test_2(self, arg): 
          pass 
 
       def test_3(self, arg): 
          pass 

当我运行它时,测试顺序错误,我得到:

test_1[1]   
test_1[2]   
test_2[1]    
test_2[2]   
test_3[1]   
test_3[2] 

看起来真的不像是测试类的场景。

问题:是否有任何解决方案可以以正确的顺序运行它?喜欢:

test_1[1] 
test_2[1] 
test_3[1] 
test_1[2] 
test_2[2] 
test_3[2] 

请您参考如下方法:

即将推出的 pytest-2.3 支持更好的(基于资源的)排序,我刚刚更新了文档中的场景示例:https://docs.pytest.org/en/latest/example/parametrize.html#a-quick-port-of-testscenarios

您可以使用

初步安装当前的开发版本
pip install -i http://pypi.testrun.org -U pytest 

并且应该使用“py.test --version”获取 pytest-2.3.0.dev15 并能够使用它。