[翻译]pytest测试框架(一)
此文已由作者吳琪惠授權(quán)網(wǎng)易云社區(qū)發(fā)布。
歡迎訪問網(wǎng)易云社區(qū),了解更多網(wǎng)易技術(shù)產(chǎn)品運(yùn)營(yíng)經(jīng)驗(yàn)。
純官網(wǎng)譯文而已。。。
pytest是一個(gè)成熟的、全功能的python測(cè)試工具。
pytest框架編寫測(cè)試用例時(shí),小的用例會(huì)變得更容易編寫,但對(duì)于復(fù)雜的應(yīng)用或者庫(kù)應(yīng)該更謹(jǐn)慎選擇。
特征:
1.斷言失敗之后具備詳細(xì)的失敗信息(不無(wú)需記住self.asseer*的名字)
2.自動(dòng)失敗測(cè)試模塊和方法
3.模塊化組件,可用于管理小的或者參數(shù)化長(zhǎng)時(shí)間存活的測(cè)試資源
4.可以在box外運(yùn)行uniitest和nose測(cè)試組件
5.支持Python2.6+, Python3.3+, PyPy-2.3, Jython-2.5 (未測(cè)試)
6.豐富的插件架構(gòu),擁有超過150+個(gè)外部插件和人氣活動(dòng)的論壇社區(qū)
安裝:
支持的python版本:Python 2.6,2.7,3.3,3.4,3.5, Jython, PyPy-2.3
支持的平臺(tái):Unix/Posix ,Windows
Pypi連接:pytest
安裝命令:
pip?install?-U?pytest檢查安裝結(jié)果:
$?pytest?--version This?is?pytest?version?3.0.6,?imported?from?$PYTHON_PREFIX/lib/python3.5/site-packages/pytest.py第一次運(yùn)行一個(gè)簡(jiǎn)單的例子:
#?content?of?test_sample.pydef?inc(x):return?x?+?1def?test_answer():assert?inc(3)?==?5運(yùn)行結(jié)果:
$?pytest =======?test?session?starts?======== platform?linux?--?Python?3.5.2,?pytest-3.0.6,?py-1.4.33,?pluggy-0.4.0rootdir:?$REGENDOC_TMPDIR,?inifile: collected?1?itemstest_sample.py?F=======?FAILURES?======== _______?test_answer?________????def?test_answer():>???????assert?inc(3)?==?5E???????assert?4?==?5E????????+??where?4?=?inc(3)test_sample.py:5:?AssertionError =======?1?failed?in?0.12?seconds?========上面的例子失敗是因?yàn)閒unc(3)不應(yīng)該返回5,而是4
提示:你可以簡(jiǎn)單的使用 assert 語(yǔ)句來(lái)進(jìn)行測(cè)試是否異常,pytest內(nèi)置了詳盡的斷言,可只能的識(shí)別 assert表達(dá)式的中間項(xiàng),你無(wú)需記住JUint那么多的傳統(tǒng)方法
運(yùn)行多個(gè)測(cè)試用例:
pytest會(huì)運(yùn)行當(dāng)前路徑以及其子路徑下的所有格式如 test_*.py 或者 *_test.py文件,通常遵循標(biāo)準(zhǔn)試驗(yàn)發(fā)現(xiàn)規(guī)則。
異常斷言:
如果你想要assert一些拋出異常的代碼,你可以使用raises,運(yùn)行腳本,使用“quiet”靜默模式(-q):
#?content?of?test_sysexit.pyimport?pytestdef?f():raise?SystemExit(1)def?test_mytest():with?pytest.raises(SystemExit):f()運(yùn)行結(jié)果:
$?pytest?-q?test_sysexit.py .1?passed?in?0.12?seconds在一個(gè)類中分組用例:
實(shí)際場(chǎng)景中,會(huì)遇到一個(gè)類中或者一個(gè)模塊下有一些邏輯上有關(guān)聯(lián)的用例組,舉個(gè)例子:
#?content?of?test_class.pyclass?TestClass:def?test_one(self):x?=?"this"assert?'h'?in?xdef?test_two(self):x?=?"hello"assert?hasattr(x,?'check')上面兩個(gè)用例,沒有子類,因此我們可以直接使用文件名來(lái)運(yùn)行:
$?pytest?-q?test_class.py .F =======?FAILURES?======== _______?TestClass.test_two?________self?=?<test_class.TestClass?object?at?0xdeadbeef>????def?test_two(self):x?=?"hello">???????assert?hasattr(x,?'check') E???????assert?FalseE????????+??where?False?=?hasattr('hello',?'check')test_class.py:8:?AssertionError1?failed,?1?passed?in?0.12?seconds第一個(gè)用例passed,第二個(gè)failed,并且我們可以情況的看著斷言中的一些中間值,幫助我們理解錯(cuò)誤原因。
功能測(cè)試用例:生成唯一的臨時(shí)目錄
功能測(cè)試經(jīng)常需要?jiǎng)?chuàng)建一些文件,并將其傳遞給應(yīng)用程序?qū)ο蟆ytest提供 Builtin fixtures/function 參數(shù)允許請(qǐng)求任意資源,例如唯一的臨時(shí)目錄:
#?content?of?test_tmpdir.pydef?test_needsfiles(tmpdir):print?(tmpdir)assert?0在函數(shù)中打印了參數(shù) tmpdir,pytest會(huì)在執(zhí)行測(cè)試方法之前,查找和調(diào)用一個(gè)fixture factory來(lái)創(chuàng)建資源。運(yùn)行例子:
$?pytest?-q?test_tmpdir.py F =======?FAILURES?======== _______?test_needsfiles?________tmpdir?=?local('PYTEST_TMPDIR/test_needsfiles0')????def?test_needsfiles(tmpdir):print?(tmpdir) >???????assert?0E???????assert?0test_tmpdir.py:3:?AssertionError ---------------------------?Captured?stdout?call?--------------------------- PYTEST_TMPDIR/test_needsfiles01?failed?in?0.12?seconds在測(cè)試執(zhí)行之前,一個(gè) 唯一的-單獨(dú)的-測(cè)試-執(zhí)行 臨時(shí)路徑被創(chuàng)建。
斷言的前面的print內(nèi)容也會(huì)打印出來(lái),測(cè)試時(shí)可以多加print語(yǔ)句,保證異常時(shí)輸出一些有用的信息。
以下命令可以看到更多的內(nèi)置函數(shù):
pytest?--fixtures???#?shows?builtin?and?custom?fixturesE:\0WORKS\MyPytest>py.test?--fixtures =============================?test?session?starts?============================= platform?win32?--?Python?2.7.10,?pytest-3.0.4,?py-1.4.31,?pluggy-0.4.0rootdir:?E:\0WORKS\MyPytest,?inifile:plugins:?html-1.11.0,?rerunfailures-2.1.0collected?1?items cacheReturn?a?cache?object?that?can?persist?state?between?testing?sessions.cache.get(key,?default)cache.set(key,?value)Keys?must?be?a?``/``?separated?value,?where?the?first?part?is?usually?thename?of?your?plugin?or?application?to?avoid?clashes?with?other?cache?users.Values?can?be?any?object?handled?by?the?json?stdlib?module. capsysEnable?capturing?of?writes?to?sys.stdout/sys.stderr?and?makecaptured?output?available?via?``capsys.readouterr()``?method?callswhich?return?a?``(out,?err)``?tuple. capfdEnable?capturing?of?writes?to?file?descriptors?1?and?2?and?makecaptured?output?available?via?``capfd.readouterr()``?method?callswhich?return?a?``(out,?err)``?tuple. doctest_namespaceInject?names?into?the?doctest?namespace. pytestconfigthe?pytest?config?object?with?access?to?command?line?opts. record_xml_propertyAdd?extra?xml?properties?to?the?tag?for?the?calling?test.The?fixture?is?callable?with?``(name,?value)``,?with?value?being?automatical lyxml-encoded. monkeypatchThe?returned?``monkeypatch``?fixture?provides?thesehelper?methods?to?modify?objects,?dictionaries?or?os.environ::monkeypatch.setattr(obj,?name,?value,?raising=True)monkeypatch.delattr(obj,?name,?raising=True)monkeypatch.setitem(mapping,?name,?value)monkeypatch.delitem(obj,?name,?raising=True)monkeypatch.setenv(name,?value,?prepend=False)monkeypatch.delenv(name,?value,?raising=True)monkeypatch.syspath_prepend(path)monkeypatch.chdir(path)All?modifications?will?be?undone?after?the?requestingtest?function?or?fixture?has?finished.?The?``raising``parameter?determines?if?a?KeyError?or?AttributeErrorwill?be?raised?if?the?set/deletion?operation?has?no?target. recwarnReturn?a?WarningsRecorder?instance?that?provides?these?methods:*?``pop(category=None)``:?return?last?warning?matching?the?category.*?``clear()``:?clear?list?of?warningsSee?http://docs.python.org/library/warnings.html?for?information????on?warning?categories. tmpdir_factoryReturn?a?TempdirFactory?instance?for?the?test?session. tmpdirReturn?a?temporary?directory?path?objectwhich?is?unique?to?each?test?function?invocation,created?as?a?sub?directory?of?the?base?temporarydirectory.??The?returned?object?is?a?`py.path.local`_path?object.------------------?fixtures?defined?from?pytest_html.plugin?------------------- environmentProvide?environment?details?for?HTML?report========================?no?tests?ran?in?0.21?seconds?=========================?
網(wǎng)易云免費(fèi)體驗(yàn)館,0成本體驗(yàn)20+款云產(chǎn)品!?
更多網(wǎng)易技術(shù)、產(chǎn)品、運(yùn)營(yíng)經(jīng)驗(yàn)分享請(qǐng)點(diǎn)擊。
相關(guān)文章:
【推薦】?iOS 安裝包瘦身 (上篇)
【推薦】?爬蟲開發(fā)python工具包介紹 (2)
【推薦】?使用Phaser開發(fā)你的第一個(gè)H5游戲(一)
總結(jié)
以上是生活随笔為你收集整理的[翻译]pytest测试框架(一)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python3.6入门到高阶(全栈) d
- 下一篇: 【收藏】一篇快速帮企业转型区块链的锦囊