安裝
通過 pip 安裝 pytest
$ pip install -U pytest
檢查是否安裝成功
$ pytest --version
編輯測試文件
# test_sample.py
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
執(zhí)行測試文件
pytest test_sample.py
============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-3.2.1, py-1.4.34, pluggy-0.4.0
rootdir: E:\test, inifile:
collected 1 item
test_sample.py F
================================== FAILURES ===================================
_________________________________ test_answer _________________________________
def test_answer():
> assert func(3) == 5
E assert 4 == 5
E + where 4 = func(3)
test_sample.py:7: AssertionError
========================== 1 failed in 0.18 seconds ===========================
到這里 pytest 環(huán)境安裝完成,正如上面你看到的,我們可以隨時(shí)使用 assert 來進(jìn)行測試的斷言
簡介
運(yùn)行多個測試
pytest 默認(rèn)會執(zhí)行當(dāng)前目錄和子目錄下的所有 test_*.py 或 *_test.py 測試文件
可使用 raises 斷言特定 Exception
編輯測試代碼
# test_sysexit.py
import pytest
def f():
raise SystemExit(1)
def test_mytest():
with pytest.raises(SystemExit):
f()
執(zhí)行測試代碼
pytest test_sysexit.py
============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-3.2.1, py-1.4.34, pluggy-0.4.0
rootdir: E:\test, inifile:
collected 1 item
test_sysexit.py .
========================== 1 passed in 0.03 seconds ===========================
通過Class組合測試用例
該方式可用于測試一個模塊或邏輯相關(guān)聯(lián)的不同模塊,編寫實(shí)例測試代碼
# 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')
執(zhí)行測試
pytest test_class.py
============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-3.2.1, py-1.4.34, pluggy-0.4.0
rootdir: E:\test, inifile:
collected 2 items
test_class.py .F
================================== FAILURES ===================================
_____________________________ TestClass.test_two ______________________________
self = <test_class.TestClass object at 0x03DFA6D0>
def test_two(self):
x = "hello"
> assert hasattr(x, 'check')
E AssertionError: assert False
E + where False = hasattr('hello', 'check')
test_class.py:9: AssertionError
===================== 1 failed, 1 passed in 0.18 seconds ======================
請求一個唯一的臨時(shí)目錄
功能測試中,我們往往需要創(chuàng)建一些臨時(shí)文件或目錄,用于程序的測試,pytest 提供一個內(nèi)置的 fixtures/function 參數(shù)來請求一些隨機(jī)的資源,例如一個臨時(shí)目錄,下面我們看一個測試用例代碼
# test_tmpdir.py
def test_needsfiles(tmpdir):
print(tmpdir)
assert 0 # 報(bào)錯中斷
上面的代碼中我們使用了參數(shù) tmpdir,pytest 會注意到這個參數(shù),并調(diào)用一個 fixture factory 來創(chuàng)建需要的這個臨時(shí)目錄資源
pytest -q test_tmpdir.py
F
================================== FAILURES ===================================
_______________________________ test_needsfiles _______________________________
tmpdir = local('C:\\Users\\test\\AppData\\Local\\Temp\\pytest-of-test\\pytest-0\\test_needsfiles0')
def test_needsfiles(tmpdir):
print(tmpdir)
> assert 0
E assert 0
test_tmpdir.py:4: AssertionError
---------------------------- Captured stdout call -----------------------------
C:\Users\test\AppData\Local\Temp\pytest-of-test\pytest-0\test_needsfiles0
1 failed in 0.12 seconds
通過查看執(zhí)行結(jié)果,pytest 為我們穿件了臨時(shí)目錄 test_needsfiles0
查看全部預(yù)置的 pytest fixtures: explicit, modular, scalable
pytest --fixtures
============================= test session starts =============================
cache
Return 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 the
name of your plugin or application to avoid clashes with other cache users.
Values can be any object handled by the json stdlib module.
capsys
Enable capturing of writes to sys.stdout/sys.stderr and make
captured output available via ``capsys.readouterr()`` method calls
which return a ``(out, err)`` tuple.
capfd
Enable capturing of writes to file descriptors 1 and 2 and make
captured output available via ``capfd.readouterr()`` method calls
which return a ``(out, err)`` tuple.
doctest_namespace
Inject names into the doctest namespace.
pytestconfig
the pytest config object with access to command line opts.
record_xml_property
Add extra xml properties to the tag for the calling test.
The fixture is callable with ``(name, value)``, with value being automatically
xml-encoded.
monkeypatch
The returned ``monkeypatch`` fixture provides these
helper 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 requesting
test function or fixture has finished. The ``raising``
parameter determines if a KeyError or AttributeError
will be raised if the set/deletion operation has no target.
recwarn
Return a WarningsRecorder instance that provides these methods:
* ``pop(category=None)``: return last warning matching the category.
* ``clear()``: clear list of warnings
See http://docs.python.org/library/warnings.html for information
on warning categories.
tmpdir_factory
Return a TempdirFactory instance for the test session.
tmpdir
返回一個臨時(shí)目錄路徑對象,這個對象在每個方法調(diào)用時(shí)都是唯一的,
該目錄作為臨時(shí)目錄根目錄下的子目錄,返回的對象是 `py.path.local`_
path 對象
======================== no tests ran in 0.13 seconds =========================