安裝 pytest
- 在命令行中運行以下命令:
pip install -U pytest - 檢查當(dāng)前安裝的版本:
pytest --version
創(chuàng)建你的第一個測試
創(chuàng)建一個簡單的只有四行的測試方法
# content of test_sample.py
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
就是這樣. 現(xiàn)在你可以執(zhí)行這個測試方法了.
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
rootdir: $REGENDOC_TMPDIR, inifile:
collected 1 item
test_sample.py F [100%]
================================= FAILURES =================================
_______________________________ test_answer ________________________________
def test_answer():
> assert func(3) == 5
E assert 4 == 5
E + where 4 = func(3)
test_sample.py:5: AssertionError
========================= 1 failed in 0.12 seconds =========================
這里測試返回了一個錯誤報告, 因為func(3) 不能返回 5.
Note: 你可以使用`assert`聲明驗證測試預(yù)期. pytest的高級斷言內(nèi)省將會
智能地報告assert表達(dá)式的中間值,這樣您就可以避免JUnit遺留的許多名稱
方法
運行多個測試
pytest將會運行當(dāng)前文件夾及其子文件夾中所有 test_.py* 及*_test.py格式的測試. 更普遍的, 請參閱 standard test discovery rules.
斷言引發(fā)了某個異常
斷言一些代碼引發(fā)異常通過使用raise這一助手
# content of test_sysexit.py
import pytest
def f():
raise SystemExit(1)
def test_mytest():
with pytest.raises(SystemExit):
f()
通過安靜報告模式執(zhí)行測試功能
$ pytest -q test_sysexit.py
. [100%]
1 passed in 0.12 seconds
在一個類中運行多個測試用例
你也許想要將一次開發(fā)的多個測試用例放到一個類里. pytest使創(chuàng)建一個類來控制超過一個測試用例變得很簡單:
# content of test_class.py
class TestClass(object):
def test_one(self):
x = 'this'
assert 'h' in x
def test_two(self):
x = 'hello'
assert hasattr(x, 'check')
pytest 遵循Python測試發(fā)現(xiàn)約定來發(fā)現(xiàn)所有測試用例, 因此它會找到所有test_開頭的方法. 這里不需要子類化任何東西. 我們能夠簡單的通過傳遞模塊文件名來運行模塊:
$ pytest -q test_class.py
.F [100%]
================================= FAILURES =================================
____________________________ TestClass.test_two ____________________________
self = <test_class.TestClass object at 0xdeadbeef>
def test_two(self):
x = "hello"
> assert hasattr(x, 'check')
E AssertionError: assert False
E + where False = hasattr('hello', 'check')
test_class.py:8: AssertionError
1 failed, 1 passed in 0.12 seconds
第一個用例是'Passed', 第二個是'Failed'. 你能夠很容易的看到斷言中的中間值來幫助你理解失敗的原因.
為功能測試請求一個唯一的臨時目錄
# content of test_tmpdir.py
def test_needsfiles(tmpdir):
print(tmpdir)
assert 0
在測試函數(shù)簽名中列出名稱tmpdir, pytest將查找并調(diào)用一個fixture工廠來創(chuàng)建
執(zhí)行測試函數(shù)調(diào)用之前的資源.Pytest 創(chuàng)建一個唯一的每個測試調(diào)用的臨時目錄:
$ pytest -q test_tmpdir.py
F [100%]
================================= FAILURES =================================
_____________________________ test_needsfiles ______________________________
tmpdir = local('PYTEST_TMPDIR/test_needsfiles0')
def test_needsfiles(tmpdir):
print (tmpdir)
> assert 0
E assert 0
test_tmpdir.py:3: AssertionError
--------------------------- Captured stdout call ---------------------------
PYTEST_TMPDIR/test_needsfiles0
1 failed in 0.12 seconds
更多關(guān)于臨時文件的處理請參閱Temporary directories and files
pytest --fixtures # 顯示內(nèi)置和自定義裝置