本章我们介绍如何开发pytest插件,在上一篇文章中我们介绍了4个python单元测试框架。大概分两类,一类是必须有类继承的,例如 QTAF
和 unittest
, 另一类是可以没有类继承,例如nose/nose2
和 pytest
。对于没有可以没有类继承的框架,开发难度会稍大一些。
pytest扩展能力
如果我们需要给pytest增加额外的扩展能力,那么有三种方式。
1. 钩子函数
利用conftest.py
这个特殊的问题,可以创建钩子函数。
-
目录结构:
pytest_sample/
├── conftest.py
└── test_sample.py
在conftest.py
文件中实现如下功能。
import pytest
@pytest.fixture
def hello():
return "hello 虫师"
定义一个函数hello()
,并使用pytest.fixture
装饰器对其进行装饰。fixture的概念我们前面已经做介绍。这里fixture
默认的级别为function
,可以理解为被装饰的函数会在每个功能前被执行。
然后,在test_sample.py
测试文件中调动钩子函数。
# 调用钩子函数hello
def test_case(hello):
print("hello:", hello)
assert hello == "hello 虫师"
在测试用例中钩子函数hello()
作为测试用例的参数hello
被调用了。断言 hello
函数返回的结果是否为“hello 虫师”
-
执行用例:
> pytest -vs test_sample.py
================================= test session starts ===========================
collected 1 item
test_sample.py::test_case hello: hello 虫师
PASSED
================================== 1 passed in 2.61s ==