Pytest

References:  https://www.jianshu.com/p/a754e3d47671

1. ***** Why Pytest ***** 

  1)  简单灵活,方便使用;能够支持简单的单元测试和复杂的功能测试,还可以用来做selenium/appnium等自动化测试、接口自动化测试(pytest+requests);
  2) pytest具有很多第三方插件,并且可以自定义扩展,比较好用的如pytest-selenium(集成selenium)、pytest-html(完美html测试报告生成)、pytest-rerunfailures(失败case重复执行)、pytest-xdist(多CPU分发)等;
  3) 测试用例的skip和xfail处理;
  4) 可以很好的和CI工具结合,例如jenkins;

  5) 兼容unitest和nose。

2. 安装:
 pip install pytest

3. 编写规则:
编写pytest测试样例非常简单,只需要按照下面的规则:
    1) 测试文件名以test_开头(或以_test结尾), 即测试文件名为:test_*.py或*_test.py;
    2) 测试文件中可以包括测试函数和测试类:
        a. 测试类以Test开头,并且不能带有 init 方法;
        b. 测试函数以test_开头;
        c.一个测试类中可以有多个test_开头的测试函数;
    3) 测试函数以test_开头, 一个测试文件中可以包含多个
    4) 断言使用基本的assert即可

4. 编写和执行pytest

      在执行pytest命令时,会自动从当前目录及子目录中寻找符合上述约束的测试函数来执行。

示例:
1) 编写代码:test_myPyTest.py如下:
class TestClass(object):
def test_one(self):
x = "this"
assert 'h' in x
def test_two(self):
x = "hello"
assert not hasattr(x, 'check')

2) 命令行,cd到test_myPyTest.py路径,执行:pytest,则上面两个test_函数都被执行,且输出结果如下:
>pytest
============================= test session starts =============================
platform win32 -- Python 2.7.11, pytest-4.3.0, py-1.8.0, pluggy-0.9.0
rootdir: C:Users racy.tanworkspaceTracyTestsrcPY estsmy, inifile:
collected 2 items

test_myPyTest.py .. [100%]

========================== 2 passed in 0.06 seconds ===========================

5. 执行pytest不同的参数:

1) 文件/路径相关参数
pytest # 运行当前文件夹下所有test_开头的函数
pytest test_mod.py # 运行module 文件test_mod.py中test_开头的函数 run tests in module file test_mod.py
pytest somepath # 运行指定路径(somepath,如:./tests/)中test_开头的函数
pytest -k stringexpr # 只运行函数命中匹配stringexpr的test_开头的函数(需要测试证明)
pytest test_mod.py::test_func # 只运行满足需要的函数 (需要测试证明)

2) Console参数介绍
-v 用于显示每个测试函数的执行结果
-q 只显示整体测试结果
-s 用于显示测试函数中print()函数输出
-x, --exitfirst, exit instantly on first error or failed test
-h 帮助

6. pytest常用插件:

pytest-django: 针对Django框架的单测框架
pytest-twisted: 针对twisted框架的单测框架
pytest-cov: 产生覆盖率报告
pytest-instafail: 发送错误时报告错误信息
pytest-bdd 测试驱动开发工具
pytest-konira 测试驱动开发工具
pytest-timeout: 支持超时功能
pytest-pep8: 支持PEP8检查
pytest-flakes: 结合pyflakes进行代码检查

7. 测试报告

  pytest可以方便的生成测试报告,即可以生成HTML的测试报告,也可以生成XML格式的测试报告用来与持续集成工具集成。

1) 生成HTML格式报告:
    pytest --resultlog=path
2) 生成XML格式的报告:
    py.test --junitxml=path

8、如何获取帮助信息

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

 

原文地址:https://www.cnblogs.com/tanql/p/10443942.html