安装
hello world
test_hellp.py
def test_hello():
assert 1 != 1除了使用 pytest 命令行执行,也可以通过代码启动
main.py
import pytest
if __name__ == '__main__':
pytest.main()基本概念
报告
报告结论的缩写有
| 缩写 | 单词 | 含义 |
|---|---|---|
| - | passed | 通过 |
| F | failed | 失败 |
| E | error | 出错 |
| S | skiped | 跳过 |
| X | xpassed | 不符合预期,用例未失败 |
| x | xFailed | 符合预期,用例失败 |
import
脚本
test/test_add.py
import pytest
# 由于使用的是 pytset.main() 方式
# 将 test 当作了项目程序中的模型,因此能正确导入 add
from add import add
def test_add():
assert add(1,2) == 3命令行
上述项目结构用 pytest 启动则无法正确导入 add 包,需要在测试用例脚本中添加额外设置
test/__init__.py
import sys
import os
# 将嵌套文件夹路径添加到 sys.path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))用例规则
用例发现
在 pytest 中检索用例的规则为
- 遍历项目下的所有目录,除
venv、.xxx文件夹 - 测试用例的脚本文件必须以
test_开头或以_test结尾 - 遍历测试脚本中所有
test_开头的函数或方法
内容规则
pytest 对测试用例的要求
- 可调用的方法、函数、变量对象
- 命名必须以
test_开头 - 测试用例函数不能有形参,除方法的
self参数 - 测试用例函数不能有返回
类
pytest 不能用类充当测试用例,但是会使用类进行测试用例分组
def add(a,b):
return a + b
class TestAdd:
def test_int(self):
assert add(1,2) == 3
def test_str(self):
assert add('a','b') == 'ab'命令行
配置
pytest.ini
conftest.py
在 conftest.py 中定义的内容可以实现 pytest 全局共享,例如 fixture
标记
用户标记
- 在
pytest.ini中注册
[pytest]
markers =
api: 接口测试
ut: 单元测试
web: UI 测试- 给用例添加标记
import pytest
@pytest.mark.api
def test_case():
assert 1 == 1- 标记筛选
内置标记
内置标记除了具有筛选功能,还具备其他特殊功能
import pytest
# 标记可叠加
@pytest.mark.xfail
@pytest.mark.api
def test_case():
assert 1 != 1参数化测试
test/test_add.py
import pytest
# 由于使用的是 pytset.main() 方式,因此能正确的找到包
from add import add
# NOTE - 数据可以定义为本地文件,然后读取
datas = [
(1, 2, 3),
(0, 0, 0),
(-1, -1, -2),
(1.5, 2.5, 4.0),
(1000000, 2000000, 3000000),
]
@pytest.mark.parametrize(
"a,b,res", # 定义数据参数名,在 test_add 中使用
datas
)
def test_add(a,b,res):
assert add(a,b) == resfixture
函数 hook
import pytest
from add import add
@pytest.fixture
def add_fixture():
# 用例执行前运行
print("setup")
yield
# 用例执行后执行
print("teardown")
def test_add_int(add_fixture):
print('add_int')
assert add(1,2) == 3
# 给测试用例添加标记,与上面写法等价
@pytest.mark.usefixtures('add_fixture')
def test_add_str():
print('add_str')
assert add('a','b') == 'ab'全局 hook
import pytest
from add import add
# 指定 autouse 参数可以为当前测试用例脚本中的所有测试用例自动添加 fixture
@pytest.fixture(autouse=True)
def add_fixture():
print("setup")
yield
print("teardown")
def test_add_int():
print('add_int')
assert add(1,2) == 3
def test_add_str():
print('add_str')
assert add('1','2') == '12'嵌套
import pytest
from add import add
@pytest.fixture
def f():
print("f() setup")
yield
print("f() teardown")
@pytest.fixture(autouse=True)
def add_fixture(f):
print("setup")
yield
print("teardown")
def test_add_int():
print('add_int')
assert add(1,2) == 3参数传递
import pytest
from add import add
@pytest.fixture()
def add_fixture():
print("setup")
# 前置处理完成后,将参数传递给测试用例
yield 12,12
print("teardown")
def test_add_int(add_fixture):
# 在测试用例中通过 add_fixture 接收 yield 传入的参数
print(f"test_add_int, {add_fixture}")
assert add(1,2) == 3作用范围
fixture 可通过 scope 指定其作用范围
session;pytest执行的前后module: 在每个 module 前后执行class: 测试用例类集合的前后执行function: 在每个用例的前后执行
@pytest.fixture(autouse=True,scope="session")
def add_fixture():
print("setup")
yield
print("teardown")Note
虽然 fixture 可以指定范围,但是也只有那些指定了该 fixture 的测试用例,才能使用 fixture,未指定 fixture 的测试用例同样无法访问。想要实现真正全局共享,则需要结合 conftest.py 与 autouse=true 实现
异步测试
import pytest
@pytest.mark.asyncio
async def test_async_test():
""" 异步测试 """Note
测试 async 接口时,@pytest.mark.asyncio 与 @pytest.mark.repeat 可能存在兼容问题
插件
概念
在 pytest 主要有两类插件
- 内置插件
- 第三方插件
这些插件的启用方式有
pytest执行参数- 配置文件
fixturemark
管理
常用插件
pytest-html
作用: 生成网页报告
通过 pytest.ini 配置启动参数
[pytest]
; 直接配置文件中写死参数
addopts = --html=report.html --self-contained-htmlpytest-xdist
作用:多进程执行测试用例
pytest-rerunfailures
作用 : 用例失败后重新执行,主要用于网络接口测试
pytest-result-log
作用 : 将测试结果存放到日志文件
需要配置 pytest.ini 配置文件
[pytest]
; 日志保存目录
log_file = ./pytest.log
; 记录日志等级:1. CRITICAL:严重错误,表示系统无法继续运行。
;2. ERROR:错误,但不影响系统运行。
;3. WARNING:警告,表示存在可能会导致错误的情况。
;4. INFO:信息,用于记录系统运行过程中的重要信息。
;5. DEBUG:调试信息,用于记录详细的系统执行过程。
;6. NOTSET:没有设置日志等级,表示输出所有日志信息。
log_file_level = info
# 记录日志时间
log_file_format = %(levelname)-8s %(asctime)s [%(name)s:%(lineno)s] : %(message)s
log_file_date_format = %Y-%m-%d %H:%M:%S
# 控制是否记录结果,1记录,0不记录
result_log = 1
# 控制是否记录分割线,1记录,0不记录
result_log_separator = 1