首页 > 其他 > 详细

Pytest - 使用介绍1

时间:2019-02-27 15:32:23      阅读:179      评论:0      收藏:0      [点我收藏+]

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\tracy.tan\workspace\TracyTest\src\PY\tests\my, inifile:
collected 2 items

test_myPyTest.py .. [100%]

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

5. 执行pytest不同的参数:

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    # 只运行满足需要的函数 (需要测试证明)

 

6. pytest常用插件:

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

 

Pytest - 使用介绍1

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!