前言
TestSuite一直是unittest的靈活與精髓之處,在繁多的測試用例中,可以任意挑選和組合各種用例集,比如smoke用例集、
level1用例集、
webtest用例集、
bug回歸用例集
等等,當(dāng)然這些TestSuite需要我們提前定義好,并把用例加載進去。Pytest采取的是完全不同的用例組織和運行方式。用例的運行主要基于名稱匹配;組織則基于用例目錄,用例命名格式及用例mark標(biāo)簽, 這種方式省去了麻煩的提前定義TestSuite及加載用例的過程,執(zhí)行時通過路徑/用例名格式/不同的標(biāo)簽組合來動態(tài)匹配出要執(zhí)行的用例,使用更加靈活。然而,從原有的unittest框架轉(zhuǎn)向pytest懷抱時仍不得不面臨這樣一個問題:我原先定義好的TestSuite怎么執(zhí)行?
實現(xiàn)方法
主要思路:
①迭代遍歷TestSuite中的所有case得到每個case的路徑test_demo.TestDemo.test_a
②將case路徑轉(zhuǎn)化為Pytest支持的運行格式test_demo.py::TestDemo::test_a并組成一個case名稱列表供Pytest調(diào)用。
示例用例: test_demo.py:
1
2
3
4
5
6
7
8
|
import unittest class TestDemo(unittest.TestCase): def test_a( self ): print ( "a" ) def test_b( self ): print ( "b" ) |
示例測試套件:demo.py:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
import unittest import pytest from test_demo import TestDemo suite = unittest.TestSuite() suite.addTests([TestDemo( 'test_a' ), TestDemo( 'test_b' )]) # 因為suite中可能會存在嵌套, 所以我們要迭代取出其中所有的用例: def collect(suite): cases = [] # 用于存放Pytest支持的用例路徑字符串 def _collect(tests): # 遞歸,如果下級元素還是TestSuite則繼續(xù)往下找 if isinstance (tests, unittest.TestSuite): [_collect(i) for i in tests if tests.countTestCases() ! = 0 ] else : _path = tests. id ().split( "." ) # case.id()可以獲取用例路徑(字符串) _path[ 0 ] + = ".py" cases.append( "::" .join(_path)) # 如果下級元素是TestCase,則添加到TestSuite中 _collect(suite) return cases if __name__ = = '__main__' : cases = collect(suite) pytest.main([ * cases, "-v" ]) # pytest.main(cases) # 不加額外參數(shù)的化可直接執(zhí)行cases |
到此這篇關(guān)于Pytest執(zhí)行unittest TestSuite(測試套件)的實現(xiàn)方法的文章就介紹到這了,更多相關(guān)Pytest unittest TestSuite測試套件內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://www.jianshu.com/p/6a05ccd3ca94