日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

[翻译]pytest测试框架(一)

發布時間:2025/3/20 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [翻译]pytest测试框架(一) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.


此文已由作者吳琪惠授權網易云社區發布。

歡迎訪問網易云社區,了解更多網易技術產品運營經驗。


純官網譯文而已。。。

pytest是一個成熟的、全功能的python測試工具。

pytest框架編寫測試用例時,小的用例會變得更容易編寫,但對于復雜的應用或者庫應該更謹慎選擇。


特征:

1.斷言失敗之后具備詳細的失敗信息(不無需記住self.asseer*的名字)

2.自動失敗測試模塊和方法

3.模塊化組件,可用于管理小的或者參數化長時間存活的測試資源

4.可以在box外運行uniitest和nose測試組件

5.支持Python2.6+, Python3.3+, PyPy-2.3, Jython-2.5 (未測試)

6.豐富的插件架構,擁有超過150+個外部插件和人氣活動的論壇社區


安裝:

支持的python版本:Python 2.6,2.7,3.3,3.4,3.5, Jython, PyPy-2.3

支持的平臺:Unix/Posix ,Windows

Pypi連接:pytest

安裝命令:

pip?install?-U?pytest

檢查安裝結果:

$?pytest?--version This?is?pytest?version?3.0.6,?imported?from?$PYTHON_PREFIX/lib/python3.5/site-packages/pytest.py


第一次運行一個簡單的例子:

#?content?of?test_sample.pydef?inc(x):return?x?+?1def?test_answer():assert?inc(3)?==?5

運行結果:

$?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?========

上面的例子失敗是因為func(3)不應該返回5,而是4

提示:你可以簡單的使用 assert 語句來進行測試是否異常,pytest內置了詳盡的斷言,可只能的識別 assert表達式的中間項,你無需記住JUint那么多的傳統方法


運行多個測試用例:

pytest會運行當前路徑以及其子路徑下的所有格式如 test_*.py 或者 *_test.py文件,通常遵循標準試驗發現規則。


異常斷言:

如果你想要assert一些拋出異常的代碼,你可以使用raises,運行腳本,使用“quiet”靜默模式(-q):

#?content?of?test_sysexit.pyimport?pytestdef?f():raise?SystemExit(1)def?test_mytest():with?pytest.raises(SystemExit):f()

運行結果:

$?pytest?-q?test_sysexit.py .1?passed?in?0.12?seconds


在一個類中分組用例:

實際場景中,會遇到一個類中或者一個模塊下有一些邏輯上有關聯的用例組,舉個例子:

#?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')

上面兩個用例,沒有子類,因此我們可以直接使用文件名來運行:

$?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

第一個用例passed,第二個failed,并且我們可以情況的看著斷言中的一些中間值,幫助我們理解錯誤原因。


功能測試用例:生成唯一的臨時目錄

功能測試經常需要創建一些文件,并將其傳遞給應用程序對象。pytest提供 Builtin fixtures/function 參數允許請求任意資源,例如唯一的臨時目錄:

#?content?of?test_tmpdir.pydef?test_needsfiles(tmpdir):print?(tmpdir)assert?0

在函數中打印了參數 tmpdir,pytest會在執行測試方法之前,查找和調用一個fixture factory來創建資源。運行例子:

$?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

在測試執行之前,一個 唯一的-單獨的-測試-執行 臨時路徑被創建。


斷言的前面的print內容也會打印出來,測試時可以多加print語句,保證異常時輸出一些有用的信息。

以下命令可以看到更多的內置函數:

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?=========================

?


網易云免費體驗館,0成本體驗20+款云產品!?

更多網易技術、產品、運營經驗分享請點擊。




相關文章:
【推薦】?iOS 安裝包瘦身 (上篇)
【推薦】?爬蟲開發python工具包介紹 (2)
【推薦】?使用Phaser開發你的第一個H5游戲(一)

總結

以上是生活随笔為你收集整理的[翻译]pytest测试框架(一)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。