首先,先介紹一下pytest
pytest是一個非常成熟的Python框架,主要用於測試,比較簡單靈活,非常容易上手,而且文檔和相關博客也有很多
學習途徑
官方文檔和技術博客
首先安裝
pip install -U pytest
創建第一個測試實例
# coding=utf-8
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
顯而易見,這樣的函數調用是錯誤的
開始測試
# 在命令行中鍵入pytest,就會得到如下的結果
========================================================== FAILURES ==========================================================
________________________________________________________ test_answer _________________________________________________________
def test_answer():
> assert func(3) == 5
E assert 4 == 5
E + where 4 = func(3)
first_test.py:7: AssertionError
================================================== 1 failed in 0.05 seconds ==================================================
如何運行多個測試
pytest將在當前目錄及其子目錄中運行test_.py或_test.py形式的所有文件.更一般地,它遵循標準測試發現規則
使用raises幫助程序斷言某些代碼引發異常
# content of test_sysexit.py
# coding=utf-8
import pytest
def f():
raise SystemExit(1)
def test_mytest():
with pytest.raises(SystemExit):
f()
使用安靜報告模式執行測試功能
(venv) ➜ pytest_zzz pytest -q second_test.py
. [100%]
1 passed in 0.01 seconds
在類中組合多個測試
一旦開發了多個測試,我們可能會希望將它們分組到一個類中,實現封裝的功能.Pytest可以很容易地創建一個包含多個測試的類
class TestClass:
def test_one(self):
x = "this"
assert "h" in x
def test_two(self):
x = "hello"
assert hasattr(x, "check")
pytest發現遵循其Python測試發現約定的所有測試,因此它找到兩個test_前綴函數.沒有必要繼承任何東西.我們可以通過傳遞文件名來運行模塊:
_____________________________________________________ TestClass.test_two _____________________________________________________
self = <third_test.TestClass instance at 0x10674d758>
def test_two(self):
x = 'hello'
> assert hasattr(x,'check')
E AssertionError: assert False
E + where False = hasattr('hello', 'check')
third_test.py:8: AssertionError
1 failed, 1 passed in 0.20 seconds
在我們封裝的類中,第一次測試通過,而第二次的測試失敗,我們可以在斷言中查看中間值,這可以用來幫助我們瞭解失敗的原因
請求功能測試的唯一臨時目錄
pytest 提供Builtin fixture/function參數來請求任意資源,比如說一個唯一的臨時目錄:
def test_needsfiles(tmpdir):
print(tmpdir)
assert 0
列出tmpdir
測試函數簽名中的名稱,並且在pytest
在執行測試函數調用之前查找並調用fixture工廠以創建資源.在測試運行之前,pytest
創建一個unique-per-test-invocation臨時目錄:
______________________________________________________ test_needsfiles _______________________________________________________
tmpdir = local('/private/var/folders/63/80c6t46d63z_8p5c78nsq38r0000gn/T/pytest-of-admin/pytest-0/test_needsfiles0')
def test_needsfiles(tmpdir):
print tmpdir
> assert 0
E assert 0
fourth_test.py:3: AssertionError
---------------------------------------------------- Captured stdout call ----------------------------------------------------
/private/var/folders/63/80c6t46d63z_8p5c78nsq38r0000gn/T/pytest-of-admin/pytest-0/test_needsfiles0
1 failed in 0.20 seconds