Pytest介绍:
pytest为python的第三方单元测试库,需额外安装。它是一个非常成熟的全功能的python测试框架,主要有以下几个特点:
-
简单灵活,容易上手。
-
支持参数化。
-
能够支持简单的单元测试和复杂的功能测试。
-
pytest具有很多第三方插件,并且可以自定义扩展。
-
执行测试过程中可以将某些测试跳过(skip),或者对某些预期失败的case标记 成失败。
-
支持重复执行(rerun)失败的case。
-
方便的和持续集成工具jenkins集成。
-
可支持执行部分用例
安装:
pip install -U pytest
查看版本:
pytest --version
第一个脚本:
新建一个test_demo.py文件,写入如下代码:
def test_answer():
assert 3==5
执行脚本:
打开cmd 进入 test_demo.py 文件所在文件夹,输入 pytest 或者 pytest test_demo.py,结果如下:
===================test session starts =====================
platform win32 -- Python 3.7.7, pytest-6.2.5, py-1.10.0, pluggy-1.0.0
rootdir: E:\test1\aabb\case
collected 1 item
test_sample.py F [100%]
======================= FAILURES =======================
______________________ test_answer ______________________
def test_answer():
> assert 3==5
E assert 3 == 5
test_sample.py:3: AssertionError
================== short test summary info =================
FAILED test_sample.py::test_answer - assert 3 == 5
==================== 1 failed in 0.14s ====================
py****test运行规则:
查找当前目录及其子目录下以test_*.py或*_test.py文件,找到文件后,在文件中找到以test开头函数并执行
以类的形式编写case:
上面是一个测试函数,当case较多的情况就不太合适了,我们可以把case写在类里面。
新建一个 test_demoClass.py文件,编写如下的代码:
import pytest
class TestClass:
def test_one(self):
x = "this"
assert 'h' in x
def test_two(self):
x = "hello"
assert hasattr(x, 'check')
def test_three(self):
a = "hello"
b = "hello world"
assert a in b
if __name__ == "__main__":
pytest.main('-q test_class.py')
运行该类,结果如下:
Testing started at 18:42 ...
Launching pytest with arguments E:/test1/aabb/case/test_class.py --no-header --no-summary -q in E:\test1\aabb\case
========================= test session starts =======================
collecting ... collected 3 items
test_class.py::TestClass::test_one PASSED [ 33%]
test_class.py::TestClass::test_two FAILED [ 66%]
test_class.py:8 (TestClass.test_two)
self = <aabb.case.test_class.TestClass object at 0x0000019378686E48>
def test_two(self):
x = "hello"
> assert hasattr(x, 'check')
E AssertionError: assert False
E + where False = hasattr('hello', 'check')
test_class.py:11: AssertionError
test_class.py::TestClass::test_three PASSED [100%]
==================== 1 failed, 2 passed in 0.07s ===================
小结:
通过上面两个实例可以发现,pytest可以 通过函数形式编写case,也可以通过类的形式编写case。而且pytest的case运行规则是 查找当前目录及其子目录下以test_*.py或*_test.py文件,找到文件后,在文件中找到以test开头函数并执行。
pytest用例规则:
-
测试文件需要以 test开头,比如 test_demo.py,test_demoClass.py。
-
测试类类名要以Test 开头,比如 class TestClass: 并且不能带有init初始化方法(自己可以先尝试找到原因,后面内容会讲到)。
-
测试函数(case)要以 test开头,比如 def test_one(): def test_two(): 。
-
使用assert进行断言。
-
所有的package包都必须要有 __init__.py文件。