pytest 有時(shí)也被稱(chēng)為 py.test,是因?yàn)樗褂玫膱?zhí)行命令是 $ py.test
。本文中我們使用 pytest 指代這個(gè)測(cè)試框架,py.test 特指運(yùn)行命令。
$ py.test
創(chuàng)建測(cè)試環(huán)境(setup/teardown)的 api 不同 下面使用一個(gè)例子說(shuō)明 pytest 的 setup/teardown 使用方式。
some_test.py:
import [email protected](scope='function')def setup_function(request): def teardown_function(): PRint("teardown_function called.") request.addfinalizer(teardown_function) print('setup_function called.')@pytest.fixture(scope='module')def setup_module(request): def teardown_module(): print("teardown_module called.") request.addfinalizer(teardown_module) print('setup_module called.')def test_1(setup_function): print('Test_1 called.')def test_2(setup_module): print('Test_2 called.')def test_3(setup_module): print('Test_3 called.')
pytest 創(chuàng)建測(cè)試環(huán)境(fixture)的方式如上例所示,通過(guò)顯式指定
scope=''
參數(shù)來(lái)選擇需要使用的 pytest.fixture 裝飾器。即一個(gè) fixture 函數(shù)的類(lèi)型從你定義它的時(shí)候就確定了,這與使用@nose.with_setup()
十分不同。對(duì)于scope='function'
的 fixture 函數(shù),它就是會(huì)在測(cè)試用例的前后分別調(diào)用 setup/teardown。測(cè)試用例的參數(shù)如def test_1(setup_function)
只負(fù)責(zé)引用具體的對(duì)象,它并不關(guān)心對(duì)方的作用域是函數(shù)級(jí)的還是模塊級(jí)的。有效的 scope 參數(shù)限于:
'function','module','class','session'
,默認(rèn)為function
。運(yùn)行上例:
$ py.test some_test.py -s
。-s
用于顯示 print() 函數(shù)============================= test session starts =============================platform win32 -- Python 3.3.2 -- py-1.4.20 -- pytest-2.5.2collected 3 itemstest.py setup_function called.Test_1 called..teardown_function called.setup_module called.Test_2 called..Test_3 called..teardown_module called.========================== 3 passed in 0.02 seconds ===========================
這里需要注意的地方是:setup_module 被調(diào)用的位置。
pytest 與 nose 二選一
首先,單是從不需要使用特定類(lèi)模板的角度上,nose 和 pytest 就較于 unittest 好出太多了。doctest 比較奇葩我們?cè)谶@里不比。因此對(duì)于 “選一個(gè)自己喜歡的測(cè)試框架來(lái)用” 的問(wèn)題,就變成了 nose 和 pytest 二選一的問(wèn)題。pythontesting.net 的作者非常喜歡 pytest,并表示
pytest 賽高,不服 solo
好吧,其實(shí)他說(shuō)的是 “如果你挑不出 pytest 的毛病,就用這個(gè)吧”。
于是下面我們就來(lái)挑挑 pytest 的毛病:
它的 setup/teardown 語(yǔ)法與 unittest 的兼容性不如 nose 高,實(shí)現(xiàn)方式也不如 nose 直觀 第一條足矣畢竟 unittest 還是 Python 自帶的單元測(cè)試框架,肯定有很多怕麻煩的人在用,所以與其語(yǔ)法保持一定兼容性能避免很多麻煩。即使 pytest 在命令行中有彩色輸出讓我很喜歡,但這還是不如第一條重要。
實(shí)際上,PyPI 中 nose 的下載量也是 pytest 的 8 倍多。
所以假如再繼續(xù)寫(xiě)某一個(gè)框架的詳解的話(huà),大概我會(huì)選 nose 吧。
新聞熱點(diǎn)
疑難解答
網(wǎng)友關(guān)注