pytest

是什么

python的一种单元测试框架,与python自带的unittest测试框架类似,但是比unittest框架使用起来更简洁,效率更高

安装

pip install -U pytest

举例

测试文件

# content of test_sample.py

def func(x):
    return x+1

def test_func():
    assert func(3) == 3

运行测试

$ py.test
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1
rootdir: /tmp/doc-exec-101, inifile:
collected 1 items
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:5: AssertionError
========================= 1 failed in 0.01 seconds =========================

使用

编写规则

编写pytest测试样例非常简单,只需要按照下面的规则:

  • 测试文件以test_开头(以_test结尾也可以)
  • 测试类以Test开头,并且不能带有 init 方法
  • 测试函数以test_开头
  • 断言使用基本的assert即可

执行测试

py.test               # run all tests below current dir
py.test test_mod.py   # run tests in module
py.test somepath      # run all tests below somepath
py.test -k stringexpr # only run tests with names that match the
                      # the "string expression", e.g. "MyClass and not method"
                      # will select TestMyClass.test_something
                      # but not TestMyClass.test_method_simple
py.test test_mod.py::test_func # only run tests that match the "node ID",
                   # e.g "test_mod.py::test_func" will select
                               # only test_func in test_mod.py

测试报告

安装pytest-html插件

pip install pytest-html

执行生成

py.test --html=path

生成xml报告(无需插件)

py.test --junitxml=path

覆盖率
安装插件pytest-cov

pip install pytest-cov

执行

pytest --cov-report=html --cov=./ test_code_target_dir

注:这里的覆盖率值被测试函数的覆盖率,未被显式测试函数不参与覆盖率计算

参数说明

—cov=[path], measure coverage for filesystem path (multi-allowed), 指定被测试对象,用于计算测试覆盖率

—cov-report=type, type of report to generate: term, term-missing, annotate, html, xml (multi-allowed), 测试报告的类型

—cov-config=path, config file for coverage, default: .coveragerc, coverage配置文件

—no-cov-on-fail, do not report coverage if test run fails, default: False,如果测试失败,不生成测试报告

—cov-fail-under=MIN, Fail if the total coverage is less than MIN. 如果测试覆盖率低于MIN,则认为失败

获取帮助

py.test --version # shows where pytest was imported from
py.test --fixtures # show available builtin function arguments
py.test -h | --help # show help on command line and config file options
  • -v 用于显示每个测试函数的执行结果
  • -q 只显示整体测试结果
  • -s 用于显示测试函数中print()函数输出
  • -x, —exitfirst, exit instantly on first error or failed test
  • -h 帮助

其他功能

  • 测试顺序随机
    pip install pytest-randomly
  • 分布式测试
    pip install pytest-xdist
  • 出错立即返回
    pip install pytest-instafail
原文地址:https://www.cnblogs.com/meiguhuaxian/p/14167028.html