python测试4_Python 各种测试框架简介(四):pytest
pytest 有時也被稱為 py.test,是因為它使用的執(zhí)行命令是 $ py.test。本文中我們使用 pytest 指代這個測試框架,py.test 特指運行命令。
##較于 nose
這里沒有使用像前三篇一樣(簡介-舉例-discovery-環(huán)境)式的分段展開,是因為 pytest 與 nose 的基本用法極其相似。因此只做一個比較就好了。他倆的區(qū)別僅在于
調(diào)用測試的命令不同,pytest 用的是 $ py.test
創(chuàng)建測試環(huán)境(setup/teardown)的 api 不同
下面使用一個例子說明 pytest 的 setup/teardown 使用方式。
some_test.py:
lang:python
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)建測試環(huán)境(fixture)的方式如上例所示,通過顯式指定 scope='' 參數(shù)來選擇需要使用的 pytest.fixture 裝飾器。即一個 fixture 函數(shù)的類型從你定義它的時候就確定了,這與使用 @nose.with_setup() 十分不同。對于 scope='function' 的 fixture 函數(shù),它就是會在測試用例的前后分別調(diào)用 setup/teardown。測試用例的參數(shù)如 def test_1(setup_function) 只負(fù)責(zé)引用具體的對象,它并不關(guān)心對方的作用域是函數(shù)級的還是模塊級的。
有效的 scope 參數(shù)限于:'function','module','class','session',默認(rèn)為 function。
運行上例:$ 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.2
collected 3 items
test.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 比較奇葩我們在這里不比。因此對于 “選一個自己喜歡的測試框架來用” 的問題,就變成了 nose 和 pytest 二選一的問題。
pythontesting.net 的作者非常喜歡 pytest,并表示
pytest 賽高,不服 solo
好吧,其實他說的是 “如果你挑不出 pytest 的毛病,就用這個吧”。
于是下面我們就來挑挑 pytest 的毛病:
它的 setup/teardown 語法與 unittest 的兼容性不如 nose 高,實現(xiàn)方式也不如 nose 直觀
第一條足矣
畢竟 unittest 還是 Python 自帶的單元測試框架,肯定有很多怕麻煩的人在用,所以與其語法保持一定兼容性能避免很多麻煩。即使 pytest 在命令行中有彩色輸出讓我很喜歡,但這還是不如第一條重要。
實際上,PyPI 中 nose 的下載量也是 pytest 的 8 倍多。
所以假如再繼續(xù)寫某一個框架的詳解的話,大概我會選 nose 吧。
總結(jié)
以上是生活随笔為你收集整理的python测试4_Python 各种测试框架简介(四):pytest的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。