python pytest_用 PyTest 测试 Python 代码

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

# 只收集并显示可用的测试用例,但不运行测试用例

py.test --collect-only

# 失败时调用 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.pyclass 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.pydef 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: 超时测试

参考资料

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值