国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python 測(cè)試框架 pytest

2019-11-11 07:05:54
字體:
供稿:網(wǎng)友

pytest 有時(shí)也被稱為 py.test,是因?yàn)樗褂玫膱?zhí)行命令是 $ py.test。本文中我們使用 pytest 指代這個(gè)測(cè)試框架,py.test 特指運(yùn)行命令。

    較于 nose


這里沒有使用像前三篇一樣(簡介-舉例-discovery-環(huán)境)式的分段展開,是因?yàn)?pytest 與 nose 的基本用法極其相似。因此只做一個(gè)比較就好了。他倆的區(qū)別僅在于

調(diào)用測(cè)試的命令不同,pytest 用的是 $ py.test創(chuàng)建測(cè)試環(huán)境(setup/teardown)的 api 不同   

下面使用一個(gè)例子說明 pytest 的 setup/teardown 使用方式。

some_test.py:

import pytest@pytest.fixture(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)的方式如上例所示,通過顯式指定 scope='' 參數(shù)來選擇需要使用的 pytest.fixture 裝飾器。即一個(gè) fixture 函數(shù)的類型從你定義它的時(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 二選一


    首先,單是從不需要使用特定類模板的角度上,nose 和 pytest 就較于 unittest 好出太多了。doctest 比較奇葩我們?cè)谶@里不比。因此對(duì)于 “選一個(gè)自己喜歡的測(cè)試框架來用” 的問題,就變成了 nose 和 pytest 二選一的問題。

pythontesting.net 的作者非常喜歡 pytest,并表示

pytest 賽高,不服 solo

好吧,其實(shí)他說的是 “如果你挑不出 pytest 的毛病,就用這個(gè)吧”。

于是下面我們就來挑挑 pytest 的毛病:

它的 setup/teardown 語法與 unittest 的兼容性不如 nose 高,實(shí)現(xiàn)方式也不如 nose 直觀    第一條足矣   

畢竟 unittest 還是 Python 自帶的單元測(cè)試框架,肯定有很多怕麻煩的人在用,所以與其語法保持一定兼容性能避免很多麻煩。即使 pytest 在命令行中有彩色輸出讓我很喜歡,但這還是不如第一條重要。

實(shí)際上,PyPI 中 nose 的下載量也是 pytest 的 8 倍多。

所以假如再繼續(xù)寫某一個(gè)框架的詳解的話,大概我會(huì)選 nose 吧。


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 泰安市| 保德县| 沾化县| 开封县| 泾川县| 十堰市| 亚东县| 夏津县| 历史| 通城县| 泰和县| 大港区| 长垣县| 黄陵县| 肇源县| 惠州市| 瑞丽市| 卢龙县| 望江县| 汉寿县| 贺州市| 望谟县| 盈江县| 益阳市| 新昌县| 黔西县| 天柱县| 松滋市| 新巴尔虎右旗| 舟山市| 无极县| 泽普县| 兴宁市| 万荣县| 雅江县| 东阳市| 广昌县| 罗江县| 大埔区| 库伦旗| 建瓯市|