Pytest
是一個比較成熟且功能完備的 Python 測試框架。其提供完善的在線文檔,并有著大量的第三方插件和內置幫助,適用于許多小型或大型項目。Pytest 靈活易學,打印調試和測試執行期間可以捕獲標準輸出,適合簡單的單元測試到復雜的功能測試。還可以執行 nose, unittest 和 doctest 風格的測試用例,甚至 Django 和 trial。支持良好的集成實踐, 支持擴展的 xUnit 風格 setup,支持非 python 測試。支持生成測試覆蓋率報告,支持 PEP8 兼容的編碼風格。
基本使用
usage: py.test [options] [file_or_dir] [file_or_dir] [...]
用例查找規則
如果不帶參數運行 pytest,那么其先從配置文件(pytest.ini,tox.ini,setup.cfg)中查找配置項 testpaths
指定的路徑中的 test case,如果沒有則從當前目錄開始查找,否者,命令行參數就用于目錄、文件查找。查找的規則如下:
- 查找指定目錄中以
test
開頭的目錄 - 遞歸遍歷目錄,除非目錄指定了不同遞歸
- 查找文件名以
test_
開頭的文件 - 查找以
Test
開頭的類(該類不能有 init 方法) - 查找以
test_
開頭的函數和方法并進行測試
如果要從默認的查找規則中忽略查找路徑,可以加上 --ingore
參數,例如:
pytest --ignore=tests/test_foobar.py
調用 pytest
- py.test:
Pytest 提供直接調用的命令行工具,即 py.test
,最新版本 pytest
和 py.test
兩個命令行工具都可用
- python -m pytest:
效果和 py.test
一樣, 這種調用方式在多 Python 版本測試的時候是有用的, 例如測試 Python3:
python3 -m pytest [...]
部分參數介紹
py.test --version 查看版本
py.test --fixtures, --funcargs 查看可用的 fixtures
pytest --markers 查看可用的 markers
py.test -h, --help 命令行和配置文件幫助
# 失敗后停止
py.test -x 首次失敗后停止執行
py.test --maxfail=2 兩次失敗之后停止執行
# 調試輸出
py.test -l, --showlocals 在 traceback 中顯示本地變量
py.test -q, --quiet 靜默模式輸出
py.test -v, --verbose 輸出更詳細的信息
py.test -s 捕獲輸出, 例如顯示 print 函數的輸出
py.test -r char 顯示指定測試類型的額外摘要信息
py.test --tb=style 錯誤信息輸出格式
- long 默認的traceback信息格式化形式
- native 標準庫格式化形式
- short 更短的格式
- line 每個錯誤一行
# 運行指定 marker 的測試
pytest -m MARKEXPR
# 運行匹配的測試
py.test -k stringexpr
# 失敗時調用 PDB
py.test --pdb
執行選擇用例
- 執行單個模塊中的全部用例:
py.test test_mod.py
- 執行指定路徑下的全部用例:
py.test somepath
- 執行字符串表達式中的用例:
py.test -k stringexpr
比如 "MyClass?and not method",選擇 TestMyClass.test_something,排除了TestMyClass.test_method_simple。
- 導入 package,使用其文件系統位置來查找和執行用例。執行 pkg 目錄下的所有用例:
py.test --pyargs pkg
- 運行指定模塊中的某個用例,如運行 test_mod.py 模塊中的 test_func 測試函數:
pytest test_mod.py::test_func
- 運行某個類下的某個用例,如運行 TestClass 類下的 test_method 測試方法:
pytest test_mod.py::TestClass::test_method
斷言
通常情況下使用 assert
語句就能對大多數測試進行斷言。對于異常斷言,可以使用上下文管理器 pytest.raises
:
def test_zero_division():
with pytest.raises(ZeroDivisionError):
1 / 0
# 還可以捕獲異常信息
def test_zero_division():
with pytest.raises(ZeroDivisionError, message='integer division or modulo by zero'):
1 / 0
對于警告斷言,可以使用上下文管理器 pytest. warns
:
with pytest.warns(RuntimeWarning):
warnings.warn("my warning", RuntimeWarning)
with warns(UserWarning, match='must be 0 or None'):
warnings.warn("value must be 0 or None", UserWarning)
with warns(UserWarning, match=r'must be \d+$'):
warnings.warn("value must be 42", UserWarning)
如果僅需斷言 DeprecationWarning
或者 PendingDeprecationWarning
警告,可以使用 pytest.deprecated_call
:
def api_call_v2():
warnings.warn('use v3 of this api', DeprecationWarning)
return 200
def test():
with pytest.deprecated_call():
assert api_call_v2() == 200
對于自定義類型的 assert 比較斷言,可以通過在 conftest.py
文件中實現pytest_assertrepr_compare
函數來實現:
# content of test_foocompare.py
class Foo:
def __init__(self, val):
self.val = val
def __eq__(self, other):
return self.val == other.val
def test():
assert 1 == 1
def test_compare():
f1 = Foo(1)
f2 = Foo(2)
f3 = Foo(1)
assert f1 == f3
assert f1 == f2
# content of conftest.py
def pytest_assertrepr_compare(op, left, right):
from test_foocompare import Foo
if isinstance(left, Foo) and isinstance(right, Foo) and op == "==":
return ['Comparing Foo instances:', 'vals: %s != %s' % (left.val, right.val)]
如果需要手動設置失敗原因,可以使用 pytest.fail
:
def test_sys_version():
if sys.version_info[0] == 2:
pytest.fail("python2 not supported")
使用 pytest.skip
和 pytest.xfail
能夠實現跳過測試的功能,skip 表示直接跳過測試,而 xfail 則表示存在預期的失敗,但兩者的效果差不多:
def test_skip_and_xfail():
if sys.version_info[0] < 3:
pytest.skip('only support python3')
print("--- start")
try:
1/0
except Exception as e:
pytest.xfail("division by zero: {}".format(e))
print("--- end")
pytest.importorskip
可以在導入失敗的時候跳過測試,還可以要求導入的包要滿足特定的版本:
docutils = pytest.importorskip("docutils")
docutils = pytest.importorskip("docutils", minversion = "0.3")
斷言近似相等可以使用 pytest.approx
:
assert 2.2 == pytest.approx(2.3)
assert 2.2 == pytest.approx(2.3, 0.1)
assert pytest.approx(2.3, 0.1) == 2.2
conftest.py
從廣義理解,conftest.py
是一個本地的 per-directory
插件,在該文件中可以定義目錄特定的 hooks 和 fixtures。py.test
框架會在它測試的項目中尋找 conftest.py 文件,然后在這個文件中尋找針對整個目錄的測試選項,比如是否檢測并運行 doctest 以及應該使用哪種模式檢測測試文件和函數。
總結起來,conftest.py
文件大致有如下幾種功能:
- Fixtures: 用于給測試用例提供靜態的測試數據,其可以被所有的測試用于訪問,除非指定了范圍
- 加載插件: 用于導入外部插件或模塊:
pytest_plugins ="myapp.testsupport.myplugin"
- 定義鉤子: 用于配置鉤子(hook),如 pytest_runtest_setup、pytest_runtest_teardown、pytest_config 等:
def pytest_runtest_setup(item):
"""called before `pytest_runtest_call(item)`"""
pass
再比如添加命令行選項的鉤子:
# content of conftest.py
import pytest
def pytest_addoption(parser):
parser.addoption("--full", action="store_ture",
help="run full test")
# content of test.py
@pytest.mark.skipif(not pytest.config.getoption("--runslow"))
def test_func_slow_1():
"""當在命令行執行 --runslow 參數時才執行該測試"""
print 'skip slow'
- 測試根路徑: 如果將 conftest.py 文件放在項目根路徑中,則 pytest 會自己搜索項目根目錄下的子模塊,并加入到 sys.path 中,這樣便可以對項目中的所有模塊進行測試,而不用設置 PYTHONPATH 來指定項目模塊的位置。
可以有多個 conftest.py
文件同時存在,其作用范圍是目錄。例如測試非常復雜時,可以為特定的一組測試創建子目錄,并在該目錄中創建 conftest.py 文件,并定義一個 futures 或 hooks。就像如下的結構:
tests
├── conftest.py
├── mod
│ └── conftest.py
├── mod2
│ └── conftest.py
└── mod3
└── conftest.py
Fixtures
fixture
是 pytest 特有的功能,它用 pytest.fixture 標識,定義在函數前面。在編寫測試函數的時候,可以將此函數名稱做為傳入參數,pytest 將會以依賴注入方式,將該函數的返回值作為測試函數的傳入參數。
pytest.fixture(scope='function', params=None, autouse=False, ids=None)
作為參數
fixture
可以作為其他測試函數的參數被使用,前提是其必須返回一個值:
@pytest.fixture()
def hello():
return "hello"
def test_string(hello):
assert hello == "hello", "fixture should return hello"
一個更加實用的例子:
@pytest.fixture
def smtp():
import smtplib
return smtplib.SMTP("smtp.gmail.com")
def test_ehlo(smtp):
response, msg = smtp.ehlo()
assert response == 250
assert 0 # for demo purposes
作為 setup
fixture
也可以不返回值,這樣可以用于在測試方法運行前運行一段代碼:
@pytest.fixture() # 默認參數,每個測試方法前調用
def before():
print('before each test')
def test_1(before):
print('test_1()')
@pytest.mark.usefixtures("before")
def test_2():
print('test_2()')
這種方式與 setup_method、setup_module 等的用法相同,其實它們也是特殊的 fixture。
在上例中,有一個測試用了 pytest.mark.usefixtures
裝飾器來標記使用哪個 fixture,這中用法表示在開始測試前應用該 fixture 函數但不需要其返回值。使用這種用法時,通過 addfinallizer
注冊釋放函數,以此來做一些“善后”工作,這類似于 teardown_function、teardown_module 等用法。示例:
@pytest.fixture()
def smtp(request):
import smtplib
smtp = smtplib.SMTP("smtp.gmail.com")
def fin():
print ("teardown smtp")
smtp.close()
request.addfinalizer(fin)
return smtp # provide the fixture value
作用范圍
fixtrue
可以通過設置 scope 參數來控制其作用域(同時也控制了調用的頻率)。如果 scope='module'
,那么 fixture 就是模塊級的,這個 fixture 函數只會在每次相同模塊加載的時候執行。這樣就可以復用一些需要時間進行創建的對象。fixture 提供三種作用域,用于指定 fixture 初始化的規則:
- function:每個測試函數之前執行一次,默認
- module:每個模塊加載之前執行一次
- session:每次 session 之前執行一次,即每次測試執行一次
反向請求
fixture
函數可以通過接受 request
對象來反向獲取請求中的測試函數、類或模塊上下文。例如:
@pytest.fixture(scope="module")
def smtp(request):
import smtplib
server = getattr(request.module, "smtpserver", "smtp.qq.com")
smtp = smtplib.SMTP(server, 587, timeout=5)
yield smtp
smtp.close()
有時需要全面測試多種不同條件下的一個對象,功能是否符合預期。可以通過設置 fixture 的 params 參數,然后通過 request 獲取設置的值:
class Foo(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def echo(self):
print self.a, self.b, self.c
return True
@pytest.fixture(params=[["1", "2", "3"], ["x", "y", "z"]])
def foo(request):
return Foo(*request.param)
def test_foo(foo):
assert foo.echo()
設置 params 參數后,運行 test 時將生成不同的測試 id,可以通過 ids 自定義 id:
@pytest.fixture(params=[1, 2, 4, 8], ids=["a", "b", "c", "d"])
def param_a(request):
return request.param
def test_param_a(param_a):
print param_a
運行以上實例會有如下結果:
test_fixture.py::test_param_a[a] 1
PASSED
test_fixture.py::test_param_a[b] 2
PASSED
test_fixture.py::test_param_a[c] 4
PASSED
test_fixture.py::test_param_a[d] 8
PASSED
自動執行
有時候需要某些 fixture 在全局自動執行,如某些全局變量的初始化工作,亦或一些全局化的清理或者初始化函數。這時可以通過設置 fixture 的 autouse 參數來讓 fixture 自動執行。設置為 autouse=True 即可使得函數默認執行。以下例子會在開始測試前清理可能殘留的文件,接著將程序目錄設置為該目錄,:
work_dir = "/tmp/app"
@pytest.fixture(scope="session", autouse=True)
def clean_workdir():
shutil.rmtree(work_dir)
os.mkdir(work_dir)
os.chrdir(work_dir)
setup/teardown
setup/teardown
是指在模塊、函數、類開始運行以及結束運行時執行一些動作。比如在一個函數中測試一個數據庫應用,測需要在函數開始前連接數據庫,在函數運行結束后斷開與數據庫的連接。setup/teardown 是特殊的 fixture,其可以有一下幾種實現方式:
# 模塊級別
def setup_module(module):
pass
def teardown_module(module):
pass
# 類級別
@classmethod
def setup_class(cls):
pass
@classmethod
def teardown_class(cls):
pass
# 方法級別
def setup_method(self, method):
pass
def teardown_method(self, method):
pass
# 函數級別
def setup_function(function):
pass
def teardown_function(function):
pass
有時候,還希望有全局的 setup 或 teardown,以便在測試開始時做一些準備工作,或者在測試結束之后做一些清理工作。這可以用 hook 來實現:
def pytest_sessionstart(session):
# setup_stuff
def pytest_sessionfinish(session, exitstatus):
# teardown_stuff
也可以用 fixture 的方式實現:
@fixture(scope='session', autouse=True)
def my_fixture():
# setup_stuff
yield
# teardown_stuff
Markers
marker
的作用是,用來標記測試,以便于選擇性的執行測試用例。Pytest 提供了一些內建的 marker:
# 跳過測試
@pytest.mark.skip(reason=None)
# 滿足某個條件時跳過該測試
@pytest.mark.skipif(condition)
# 預期該測試是失敗的
@pytest.mark.xfail(condition, reason=None, run=True, raises=None, strict=False)
# 參數化測試函數。給測試用例添加參數,供運行時填充到測試中
# 如果 parametrize 的參數名稱與 fixture 名沖突,則會覆蓋掉 fixture
@pytest.mark.parametrize(argnames, argvalues)
# 對給定測試執行給定的 fixtures
# 這種用法與直接用 fixture 效果相同
# 只不過不需要把 fixture 名稱作為參數放在方法聲明當中
@pytest.mark.usefixtures(fixturename1, fixturename2, ...)
# 讓測試盡早地被執行
@pytest.mark.tryfirst
# 讓測試盡量晚執行
@pytest.mark.trylast
例如一個使用參數化測試的例子:
@pytest.mark.parametrize(("n", "expected"), [
(1, 2),
(2, 3),
])
def test_increment(n, expected):
assert n + 1 == expected
除了內建的 markers 外,pytest 還支持沒有實現定義的 markers,如:
@pytest.mark.old_test
def test_one():
assert False
@pytest.mark.new_test
def test_two():
assert False
@pytest.mark.windows_only
def test_three():
assert False
通過使用 -m
參數可以讓 pytest 選擇性的執行部分測試:
$ pytest test.py -m 'not windows_only'
...
collected 3 items / 1 deselected
test_marker.py::test_one FAILED
更詳細的關于 marker 的說明可以參考官方文檔:
第三方插件
- pytest-randomly: 測試順序隨機
- pytest-xdist: 分布式測試
- pytest-cov: 生成測試覆蓋率報告
- pytest-pep8: 檢測代碼是否符合 PEP8 規范
- pytest-flakes: 檢測代碼風格
- pytest-html: 生成 html 報告
- pytest-rerunfailures: 失敗重試
- pytest-timeout: 超時測試
參考資料
- https://docs.pytest.org/en/latest/example/
- https://docs.pytest.org/en/latest/assert.html
- https://docs.pytest.org/en/latest/reference.html
- http://doc.pytest.org/en/latest/xunit_setup.html
- https://docs.pytest.org/en/latest/skipping.html
- https://docs.pytest.org/en/latest/fixture.html
- http://senarukana.github.io/2015/05/29/pytest-fixture/
- https://docs.pytest.org/en/latest/parametrize.html
- https://docs.pytest.org/en/latest/plugins.html