Pytest权威教程11-模块及测试文件中集成doctest测试

[TOC]html

返回: Pytest权威教程python

模块及测试文件中集成doctest测试

编码

使用doctest选项

默认状况下,Pytest按照python doctest模块标准test*.txt模式进行匹配。你也能够经过使用如下命令更改匹配模式:linux

pytest --doctest-glob='*.rst'

在命令行上。从版本开始2.9,--doctest-glob能够在命令行中屡次使用。bash

3.1版中的新增函数:你可使用doctest_encodingini选项指定将用于这些doctest文件的编码:session

# content of pytest.ini
[pytest]
doctest_encoding = latin1

默认编码为UTF-8。函数

你还能够在全部python模块(包括常规python测试模块)中从docstrings触发doctests的运行:测试

pytest --doctest-modules

你能够将这些更改永久保存在项目中,方法是将它们放入pytest.ini文件中,以下所示:this

# content of pytest.ini
[pytest]
addopts = --doctest-modules

若是你有一个这样的文本文件:编码

# content of example.rst

hello this is a doctest
>>> x = 3
>>> x
3

和另外一个这样的:spa

# content of mymodule.py
def something():
    """ a doctest in a docstring
 >>> something()
 42
 """
    return 42

那么你能够在pytest没有命令行选项的状况下调用:

$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y,pytest-4.x.y,py-1.x.y,pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR,inifile: pytest.ini
collected 1 item

mymodule.py .                                                       [100%]

========================= 1 passed in 0.12 seconds =========================

可使用getfixture帮助器使用Fixture方法:

# content of example.rst
>>> tmp = getfixture('tmpdir')
>>> ...
>>>

此外,在执行文本doctest文件时,支持[使用类,模块或项目中的Fixture。

标准doctest模块提供了一些设置标志来配置doctest测试的严格性。在pytest中,你可使用配置文件启用这些标志。要使pytest忽略尾随空格并忽略冗长的异常堆栈跟踪,你只需编写:

[pytest]
doctest_optionflags= NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL

pytest还引入了新的选项,容许doctests在Python 2和Python 3中运行不变:

  • ALLOW_UNICODE:启用时,u前缀将从预期doctest输出中的unicode字符串中删除。
  • ALLOW_BYTES:启用时,b前缀将从预期doctest输出中的字节字符串中删除。

与任何其余选项标志同样,能够pytest.ini使用doctest_optionflagsini选项启用这些标志:

[pytest]
doctest_optionflags = ALLOW_UNICODE ALLOW_BYTES

或者,能够经过doc测试自己中的内联注释启用它:

# content of example.rst
>>> get_unicode_greeting()  # doctest: +ALLOW_UNICODE
'Hello'

默认状况下,pytest仅报告给定doctest的第一次失败。若是你想在即便遇到故障时继续测试,请执行如下操做:

pytest --doctest-modules --doctest-continue-on-failure

3.0版中的新函数。

doctest_namespace Fixture方法可用于注入到项目中,你的文档测试运行的命名空间。它旨在用于你本身的Fixture方法中,以提供将它们与上下文一块儿使用的测试。

doctest_namespace是一个标准dict对象,你能够将要放置在doctest命名空间中的对象放入其中:

# content of conftest.py
import numpy
@pytest.fixture(autouse=True)
def add_np(doctest_namespace):
    doctest_namespace['np'] = numpy

而后能够直接在你的doctests中使用它:

# content of numpy.py
def arange():
    """
>>> a = np.arange(10)
>>> len(a)
10
"""
    pass

请注意,与正常状况同样conftest.py,在conftest所在的目录树中发现了fixture。意味着若是将doctest与源代码放在一块儿,则相关的conftest.py须要位于同一目录下。在同级目录树中不会发现Fixtures!

输出格式

3.0版中的新函数。

你能够经过使用选项标准文档测试模块格式的一个更改失败你的文档测试diff的输出格式(见doctest.REPORT_UDIFF):

pytest --doctest-modules --doctest-report none
pytest --doctest-modules --doctest-report udiff
pytest --doctest-modules --doctest-report cdiff
pytest --doctest-modules --doctest-report ndiff
pytest --doctest-modules --doctest-report only_first_failure

pytest-specific 特性

相关文章
相关标签/搜索