pytest中⽂⽂档
官⽅⽂档
pytest documentation:
第⼀章安装和启动
pytest作为⼀个测试框架,可以⾮常简单的建⽴易⽤性好,扩展性强的测试集。这些测试因为避免了
⼤量的样板代码,所以可读性⾮常⾼。
你可以花费⼀点时间通过⼀个unittest或者略复杂的函数测试来验证你的应⽤程序或者库
1.1 安装pytest
1.在你的python环境下运⾏下⾯的命令即可安装pytest
pip install ‐U pytest
2.检查你安装的pytest的版本信息是否正确:
pip show pytest
pytest --version
1.2 创建你的第⼀个测试
创建⼀个只有4⾏代码的简单函数:
# test_sample.py 的内容
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
现在,你可以在test_sample.py的同级⽬录下直接执⾏pytest,结果如下:
(pytest_env) D:\DiluWorkspace\Code\MyTest>pytest
================================================= test session starts ================================================= platform win32 -- Python 3.7.1, pytest-5.3.2, py-1.8.1, pluggy-0.13.1
rootdir: D:\DiluWorkspace\Code\MyTest
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:7: AssertionError
================================================== 1 failed in 0.02s ================================================== (pytest_env) D:\DiluWorkspace\Code\MyTest>
这个测试的结果是失败的,因为func(3)的返回值不是5
1.3 运⾏多个测试
pytest会运⾏当前⽬录及⼦⽬录下所有以 test_*.py 和 *_test.py 命名的⽂件。⽂件匹配⽅式遵循
Standard test discovery rules
1.4 判断是否发⽣了指定的异常
使⽤raises可以判断代码是否抛出了异常:
# test_sysexit.py 的内容
import pytest
def f():
raise SystemExit(1)
def test_my_test():
with pytest.raises(SystemExit):
f()
使⽤"quiet"模式来执⾏这个测试:
(pytest_env) D:\DiluWorkspace\Code\MyTest>pytest -q test_sysexit.py
.                                                                                                                [100%]
1 passed in 0.02s
1.5 将多个测试⽤例放在⼀个class中
当你需要开发多个测试⽤例的时候,你可能需要将他们放在同⼀个class中,pytest可以很简单的创建
包含多个测试⽤例的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根据Conventions for Python test discovery查所有的测试⽤例,所以可以到所有以
**test_**开头的测试函数。我们可以通过⽂件名来直接运⾏整个模块:
(pytest_env) D:\DiluWorkspace\Code\MyTest>pytest -q test_sysexit.py
.                                                                                                                [100%]
1 passed in 0.02s
(pytest_env) D:\DiluWorkspace\Code\MyTest>
(pytest_env) D:\DiluWorkspace\Code\MyTest>pytest -q test_class.py
.F                                                                                                              [100%]
====================================================== FAILURES ======================================================= _________________________________________________ st_two __________________________________________________
self = <test_class.TestClass object at 0x000002012A089550>
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.03s
第⼀个测试⽤例passed,第⼆个测试⽤例failed。你可以很直观的观察到测试⽤例中进⾏判断的中间
值,这可以帮助理解测试⽤例失败的原因。
1.6 为测试创建唯⼀的临时⽂件夹
pytest 提供 Builtin fixtures/function arguments来创建任意的资源,⽐如⼀个具有唯⼀的临时⽂件
夹:
# test_tmpdir.py的内容
def test_needs_files(tmpdir):
print(tmpdir)
assert 0
如果函数的签名中(函数签名包括函数的参数和返回值,以及参数的封送顺序等等)包含参数tmpdir,
pytest就会在执⾏测试⽤例之前查并调⽤特定的fixture创建所需资源。在本例中,pytest会创建⼀
个unique-per-test-invocation临时⽂件夹:
pytest ‐‐fixtures
(pytest_env) D:\DiluWorkspace\Code\MyTest>pytest -q test_tmpdir.py
F                                                                                                                [100%]
====================================================== FAILURES ======================================================= __________________________________________________ test_needs_files ___________________________________________________
tmpdir = local('C:\\Users\\lcgst\\AppData\\Local\\Temp\\pytest-of-lcgst\\pytest-0\\test_needs_files0')
def test_needs_files(tmpdir):
print(tmpdir)
>      assert 0
E      assert 0
test_tmpdir.py:4: AssertionError
------------------------------------------------ Captured stdout call -------------------------------------------------
C:\Users\lcgst\AppData\Local\Temp\pytest-of-lcgst\pytest-0\test_needs_files0
1 failed in 0.03s
关于tmpdir的更多信息请参考Temporary directories and files 通过下⾯的命令可以查看所有内置
的pytest fixture:
(pytest_env) D:\DiluWorkspace\Code\MyTest>pytest --fixtures
================================================= test session starts ================================================= platform win32 -- Python 3.7.1, pytest-5.3.2, py-1.8.1, pluggy-0.13.1
rootdir: D:\DiluWorkspace\Code\MyTest
collected 5 items
cache
Return a cache object that can persist state between testing sessions.
<(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 text capturing of writes to ``sys.stdout`` and ``sys.stderr``.
The captured output is made available via ``adouterr()`` method
calls, which return a ``(out, err)`` namedtuple.
``out`` and ``err`` will be ``text`` objects.
capsysbinary
Enable bytes capturing of writes to ``sys.stdout`` and ``sys.stderr``.
The captured output is made available via ``adouterr()``
method calls, which return a ``(out, err)`` namedtuple.
``out`` and ``err`` will be ``bytes`` objects.
capfd
Enable text capturing of writes to file descriptors ``1`` and ``2``.
The captured output is made available via ``adouterr()`` method
calls, which return a ``(out, err)`` namedtuple.
``out`` and ``err`` will be ``text`` objects.
capfdbinary
Enable bytes capturing of writes to file descriptors ``1`` and ``2``.
The captured output is made available via ``adouterr()`` method
calls, which return a ``(out, err)`` namedtuple.
``out`` and ``err`` will be ``byte`` objects.
doctest_namespace [session scope]
Fixture that returns a :py:class:`dict` that will be injected into the namespace of doctests.
pytestconfig [session scope]
Session-scoped fixture that returns the :class:`_fig.Config` object.
Example::
def test_foo(pytestconfig):
ption("verbose") > 0:
...
record_property
Add an extra properties the calling test.
User properties become part of the test report and are available to the
configured reporters, like JUnit XML.
The fixture is callable with ``(name, value)``, with value being automatically
xml-encoded.
Example::
def test_function(record_property):
record_property("example_key", 1)
record_xml_attribute
Add extra xml attributes to the tag for the calling test.
The fixture is callable with ``(name, value)``, with value being
automatically xml-encoded
record_testsuite_property [session scope]
Records a new ``<property>`` tag as child of the root ``<testsuite>``. This is suitable to
writing global information regarding the entire test suite, and is compatible with ``xunit2`` JUnit family.
This is a ``session``-scoped fixture which is called with ``(name, value)``. Example:
.. code-block:: python
def test_foo(record_testsuite_property):
record_testsuite_property("ARCH", "PPC")
record_testsuite_property("STORAGE_TYPE", "CEPH")
``name`` must be a string, ``value`` will be converted to a string and properly xml-escaped.
caplog
Access and control log capturing.
Captured logs are available through the following properties/methods::
* ssages        -> list of format-interpolated log messages
*             -> string containing formatted log output
* ds        -> list of logging.LogRecord instances
* d_tuples  -> list of (logger_name, level, message) tuples
* caplog.clear()        -> clear captured records and formatted log output string
monkeypatch
The returned ``monkeypatch`` fixture provides these
helper methods to modify objects, dictionaries viron::
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, 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 :class:`WarningsRecorder` instance that records all warnings emitted by test functions.
See /library/warnings.html for information
on warning categories.
tmpdir_factory [session scope]
Return a :class:`_pdir.TempdirFactory` instance for the test session.
tmp_path_factory [session scope]
Return a :class:`_pdir.TempPathFactory` instance for the test session.
tmpdir
Return a temporary directory path object
which is unique to each test function invocation,
created as a sub directory of the base temporary
python官方文档中文版directory.  The returned object is a `py.path.local`_
path object.
.. _`py.path.local`: py.readthedocs.io/en/latest/path.html
tmp_path
Return a temporary directory path object
which is unique to each test function invocation,
created as a sub directory of the base temporary
directory.  The returned object is a :class:`pathlib.Path`
object.
.
. note::
in python < 3.6 this is a pathlib2.Path
================================================ no tests ran in 0.07s ================================================第⼆章⽤法
2.1 通过python -m pytest调⽤pytest
这是在2.0版本中新引⼊的功能。你可以通过python的解释器,利⽤命令⾏来调⽤测试:
python ‐m pytest [...]
这种调⽤⽅式⼏乎等同于直接调⽤pytest […],但需要注意的是这种通过python来调⽤的⽅式同时会
将当前⽬录添加到sys.path
2.2 退出码
pytest有以下6种退出码:
Exit code 0: 到所有测试⽤例并测试通过
Exit code 1: 到测试⽤例并运⾏但是部分测试⽤例运⾏失败
Exit code 2: ⽤户中断了测试
Exit code 3: 执⾏过程中发⽣了内部错误
Exit code 4: pytest命令⾏使⽤错误
Exit code 5: 没有到任何测试⽤例
2.3 版本信息,参数名,环境变量的帮助
pytest ‐‐version #显⽰pytest的import的路径
pytest ‐‐fixtures #显⽰内置的函数参数
pytest ‐h | ‐‐help #帮助信息
2.4 第⼀(N)次测试失败后停⽌
使⽤下⾯的参数可以让测试在第1(N)次测试失败后停⽌:
pytest ‐x # 第⼀次测试失败后停⽌测试
pytest ‐‐maxfail=2 # 第2次测试失败后停⽌测试
2.5 指定/选择测试⽤例
Pytest在命令⾏中⽀持多种⽅式来运⾏和选择测试⽤例:
对模块中进⾏测试:
pytest test_mod.py
对⽂件夹中进⾏测试:
pytest testing/
通过关键字表达式来进⾏测试:
pytest ‐k "MyClass and not method"
这种⽅式会执⾏⽂件名,类名以及函数名与给定的字符串表达式相匹配的测试⽤例。上⾯的⽤例会执
⾏st_something但是不会执⾏st_method_simple。and not 在这⾥是表达式,未经过测试
通过节点id来进⾏测试
每个被选中的测试⽤例都会被分配⼀个唯⼀的nodeid,它由模块⽂件名和以下说明符组成:参数化的类名、函数名和参数,⽤::分隔。
可以通过下⾯的⽅式运⾏模块中的指定的测试⽤例:
pytest test_mod.py::test_func
也可以通过下⾯这种⽅式:
pytest test_mod.py::TestClass::test_method
通过标记符来进⾏测试
pytest ‐m slow
这种⽅式会运⾏所有通过装饰器 @pytest.mark.slow进⾏装饰的测试⽤例。
关于标记符请参考marks
通过包来运⾏
pytest ‐‐sting
这种⽅式会导⼊sting,并且基于该包所在位置来查并运⾏测试⽤例。
2.6 修改python的traceback的打印
pytest ‐‐showlocals  #在tracebacks中显⽰本地变量
pytest ‐l            #同上
pytest ‐‐tb=auto    #(默认显⽰⽅式)该⽅式会显⽰tracebacks的第⼀条和最后⼀条的详细信息
  #其余的信息会简略显⽰
pytest ‐‐tb=long    #详细显⽰所有的tracebacks

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。