pytest--使用前提

 
python 鄙视链:pytest 鄙视 > unittest 鄙视 >  robotframework 。
pytest 是 python 的第三方单元测试框架,比自带 unittest 更简洁和高效,支持315种以上的插件,同时兼容 unittest 框架。这就使得我们在 unittest 框架迁移到 pytest 框架的时候不需要重写代码。
 
一、安装
首先使用 pip 安装 pytest 
pip3 install pytest
 查看 pytest 是否安装成功
pytest --version
 
二、简单使用
1.创建 test_sample.py 文件,代码如下:
#!/usr/bin/env python
# coding=utf-8
import pytest

def inc(x):
    return x + 1

def test_answer():
    assert inc(3) == 5

if __name__ =="__main__":
    pytest.main()
执行结果:
test_sample.py F                                                         [100%]
================================== FAILURES ===================================
_________________________________ test_answer _________________________________
    def test_answer():
>       assert inc(3) == 5
E       assert 4 == 5
E        +  where 4 = inc(3)

test_sample.py:19: AssertionError
============================== 1 failed in 0.41s ==============================
从上面的例子可以看出,pytest 中断言的用法直接使用 assert ,和 unittest 中断言 self.assert 用法有所区别。
 
2.总结一下:使用 pytest 执行测试需要遵行的规则:
  • .py 测试文件必须以test_开头(或者以_test结尾) 
  • 测试类必须以Test开头,并且不能有 init 方法
  • 测试方法必须以test_开头
  • 断言必须使用 assert
 
三、文件结构
project root folder
      |——…
      |——src
      |    |——…
      |——tests
      |    |——conftest.py
      |    |——pytest.ini
      |——func
      |    |——__init__.py
      |    |——test_xx.py
      |    |—— …
      |——unit
      |    |——__init__.py
      |    |——test_xx.py
      |    |——…

 

 

posted @ 2020-11-16 12:22  盲仔不瞎忙  阅读(72)  评论(0编辑  收藏  举报