安装
通过 pip 安装 pytest
$ pip install -U pytest
检查是否安装成功
$ pytest --version
编辑测试文件
# test_sample.py
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
执行测试文件
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 环境安装完成,正如上面你看到的,我们可以随时使用 assert 来进行测试的断言
简介
运行多个测试
pytest 默认会执行当前目录和子目录下的所有 test_*.py 或 *_test.py 测试文件
可使用 raises 断言特定 Exception
编辑测试代码
# test_sysexit.py
import pytest
def f():
raise SystemExit(1)
def test_mytest():
with pytest.raises(SystemExit):
f()
执行测试代码
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组合测试用例
该方式可用于测试一个模块或逻辑相关联的不同模块,编写实例测试代码
# 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 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 ======================
请求一个唯一的临时目录
功能测试中,我们往往需要创建一些临时文件或目录,用于程序的测试,pytest 提供一个内置的 fixtures/function 参数来请求一些随机的资源,例如一个临时目录,下面我们看一个测试用例代码
# test_tmpdir.py
def test_needsfiles(tmpdir):
print(tmpdir)
assert 0 # 报错中断
上面的代码中我们使用了参数 tmpdir,pytest 会注意到这个参数,并调用一个 fixture factory 来创建需要的这个临时目录资源
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
通过查看执行结果,pytest 为我们穿件了临时目录 test_needsfiles0
查看全部预置的 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
返回一个临时目录路径对象,这个对象在每个方法调用时都是唯一的,
该目录作为临时目录根目录下的子目录,返回的对象是 `py.path.local`_
path 对象
======================== no tests ran in 0.13 seconds =========================