ai+实现pytest框架讲解(1)
ai+实现pytest框架讲解
pytest测试框架讲解:
(1)什么事测试框架
讲解1:抽象的工具集合:用例发现,用例管理,环境管理,用例执行,其他
讲解2:验证过的方法论:用例之间隔离,使用断言宣告结果,为每个用例单读收集i/o和日志,数据驱子动测试,行为驱动测试,关键字驱动测试,
冒烟测试,回归测试,增量测试
讲解3:常见的测试框架:
a、java: junit 、
b、python :unittest、pytest、po框架
(2)pytest 基础入门
a、环境准备:python、pycharm、pytest(框架)
b、安装pytest
下载:pip install pytest 安装
升级: pip install pytest -U 版本在3.9以后
c、创建用例
注意点:
1、不要创建在venv的环境中
2、py文件中test 开头
3、函数也要test开头
4、测试用例要:断言 违反了框架的基本原理 :
5、内容需要断言
6、返回值是null reture 就报错

7、执行用例
a、pytest 命令执行
b、pytest的启动函数

c、ide按钮【不推荐】运行 ;比如vscode、pycharm、方法不同

8、用例执行情况

用例执行情况:
成功:passed (.)
失败: failed (F)
跳过:skiped (s)
出错:error (E)
预期外:(了解,在白盒测试中)
预期外成功 (X大写)
预期内失败(x小写)


9、用例发现规则:
a、遍历所有目录;venv (python的虚拟环境)和.开始 无法识别
b、遍历所有的py文件 (test开头或者 _test 结尾)
c、遍历所有的test开头的类(不能拥有__init __初始化 文件)
d、收集符合要求的函数,方法(test开头吗,没有参数,没有返回值)
(3)pytest 进阶管理
a、配置(配置的目的是改变现状:改变现在pytest)

(一)命令参数
1、常用的参数:h (配置一个翻译工具,都去翻译,看下,我们就讲一些常用,必用的)

pytest -h 执行
2、作用:只运行 函数名 / 类名 包含这个关键词的用例
pytest -k "Testxiaosir"

3、 只重新运行上一次失败的测试用例
--lf = --last-failed
中文意思:只重新运行上一次执行失败的测试用
--lf = 只跑上次失败的用例(快速验证修复
--ff = 先跑失败的,再跑全部

4、-x 快速失败(当有用例失败就停止测试)
pytest -x

5、-v 增加输出详细的程度(-v 更详细 -vv -vvv 上不封顶)
pytest -v
(二)配置文件
b、标记
(4)pytest 核心利器
(5)pytest 插件生态
(6)pytest 实战应用
==========================================
一、pytest 核心介绍
定义:pytest 是 Python 生态最主流、简洁强大的单元 / 自动化测试框架,完全兼容 unittest,语法极简、插件丰富、自动发现用例,是 Web 自动化、接口测试、TDD/BDD 的首选工具。
1. 核心优势
语法零,通用模版:不用继承类、不用复杂断言,直接用 assert pytest
自动发现用例:按命名规则自动扫描测试文件 / 函数pytest
丰富断言:原生支持 == , != , in , is / 异常断言
Fixture 机制:全局 / 模块 / 类 / 函数级前置 / 后置、依赖注入(替代 setup/teardown)
参数化测试:@pytest.mark.parametrize( 一键多组数据)
插件生态:覆盖率、HTML 报告、并行、异步、Allure、接口 / UI 自动化
兼容 unittest /nose:老用例可无缝迁移
2. 版本要求
Python ≥ 3.8(pytest 8.x+)
二、安装(含常用插件)
1. 基础安装
# 安装最新版
pip install -U pytest

# 验证安装
pytest --version

2. 实战必备插件(推荐)
(1) 代码覆盖率
pip install pytest-cov

(2)HTML测试报告
pip install pytest-html

(3)多进程并行执行
pip install pytest-xdist

(4)异步代码测试支持
pip install pytest-asyncio

三、pytest 基本规则(用例发现)
pytest 自动识别测试:
(1)测试文件:test_*.py 或 *_test.py
(2)测试函数:以 test_ 开头pytest
(3)测试类:以 Test 开头(无 __init__)
(4)类中测试方法:以 test_ 开头
四、运用案例
1. 编写被测代码

代码:

2. 编写测试文件
新建 test_py1.py

代码:

3. 执行测试方法
(1)执行当前目录所有测试
pytest

(2) 详细输出
pytest -v

(3) 只运行指定文件
pytest test_calculator.py -v


# 只运行指定函数
pytest test_py1.py::test_add -v

执行结果示例:

查看用例执行结果
五、进阶用法
@pytest.mark.parametrize
作用
(1)一个测试函数,自动跑多组测试数据!
(2)不用写 N 个重复的 assert,超级省事
1. 测试类(批量组织用例)
python
运行
class TestCalculator:
def test_add(self):
assert add(2,3) ==5
def test_divide_normal(self):
assert divide(6,2) ==3
def test_divide_zero(self):
pytest.raises(ValueError, divide, 5, 0)
2. 参数化测试(多组数据)
python
运行
import pytest
# 一次定义多组输入+预期
@pytest.mark.parametrize("a, b, expected", [
(1, 2, 3),
(-1, 1, 0),
(0, 0, 0),
(10, -5, 5),
])
def test_add_param(a, b, expected):
assert add(a, b) == expected
```{insert\_element\_4\_}
### 3. Fixture(前置/后置/共享数据)
Fixture 是 pytest 最核心特性,替代 `setup/teardown`。
#### (1)基础 Fixture
```python
import pytest
# 定义 Fixture:每个测试函数执行前自动运行
@pytest.fixture
def setup_data():
print("\n=== 测试前置准备 ===")
data = {"user": "test", "pwd": "123456"}
# yield 之前:前置
yield data
# yield 之后:后置清理
print("\n=== 测试后置清理 ===")
# 测试函数直接注入 Fixture
def test_login(setup_data):
user = setup_data["user"]
assert user == "test"
```{insert\_element\_5\_}
#### (2)Fixture 作用域(scope)
```python
# function(默认)/ class / module / package / session
@pytest.fixture(scope="module")
def module_fixture():
print("模块开始前执行")



(3)conftest.py(全局共享 Fixture)
项目根目录新建 conftest.py,所有测试文件自动可见,无需 import。
python运行
# conftest.py
# conftest.py
# 1. 导入 pytest 库(必须写,否则用不了 fixture)
import pytest
## 2. 定义一个 全局 fixture(作用域:整个测试会话)
@pytest.fixture(scope="session") #session = 整个测试过程只执行 1 次
def global_data():
# 3. 返回一个字典,里面存放 全局通用数据
return {"base_url": "http://49.233.201.254:8080/cms/manage/login.do"}

4. 常用命令行参数
pytest # 运行所有
pytest -v # 详细输出
pytest -q # 极简输出
pytest -x # 失败即停止
pytest -k "add or login" # 运行名称含 add/login 的用例
pytest --tb=short # 简化报错堆栈
pytest --html=report.html # 生成HTML报告
pytest --cov=./ --cov-report=html # 覆盖率报告
pytest -n auto # 多进程并行(需pytest-xdist)
5. 标记(Mark):分组执行
python
运行
@pytest.mark.smoke
def test_add_smoke():
assert add(1,1)==2
@pytest.mark.functional
def test_divide_func():
assert divide(4,2)==2
执行:
bash
运行
pytest -m smoke # 只跑冒烟用例
pytest -m "not slow" # 排除慢用例
六、常见断言写法
python
运行
# 相等
assert a == b
# 不相等
assert a != b
# 包含
assert x in lst
# 为真/假
assert condition is True
assert not condition
# 异常
with pytest.raises(ValueError) as excinfo:
divide(1, 0)
assert "除数不能为0" in str(excinfo.value)
七、IDE 集成(PyCharm/VS Code)
PyCharm
File → Settings → Tools → Python Integrated Tools
Testing → Default test runner → 选 pytest
右键测试文件 / 函数 → Run 'pytest in ...'
VS Code
安装 Python 扩展
测试面板 → 配置测试 → 选择 pytest
直接在测试面板运行 / 调试
八、总结
pytest = 简洁语法 + 强大 Fixture + 参数化 + 插件生态
入门:test_.py + test_() + assert 即可写用例
进阶:Fixture + parametrize + Mark 实现工程化测试
适合:单元测试、接口自动化、UI 自动化、性能测试、TDD

浙公网安备 33010602011771号