当前位置: 首页 > news >正文

ai+实现pytest框架讲解(2)

一、推荐项目结构
plaintext
your_project/
├── conftest.py # 全局 fixture、钩子、插件配置
├── requirements.txt # 依赖
├── src/ # 业务代码
│ └── calculator.py
└── tests/ # 测试用例
├── test_calculator.py
└── test_api_demo.py
二、requirements.txt(直接复制)
txt
pytest>=7.0
pytest-cov
pytest-html
pytest-xdist
pytest-rerunfailures
requests
安装:
bash
运行
pip install -r requirements.txt
三、conftest.py(全局 fixture)
python
运行
import pytest
import requests

# ------------------------------
# 1. 会话级 fixture(整个测试只执行一次)
# ------------------------------
@pytest.fixture(scope="session", name="session_fixture")
def global_session_fixture():
print("\n[Session] 开始全局前置")
base_url = "https://httpbin.org"
yield base_url
print("\n[Session] 结束全局后置")

# ------------------------------
# 2. 模块级 fixture
# ------------------------------
@pytest.fixture(scope="module", name="module_fixture")
def module_level_fixture():
print("\n[Module] 模块前置")
yield
print("\n[Module] 模块后置")

# ------------------------------
# 3. 函数级 fixture(默认)
# ------------------------------
@pytest.fixture(scope="function", name="func_fixture")
def function_level_fixture():
print("\n[Function] 用例前置")
test_data = {"username": "test", "password": "123456"}
yield test_data
print("\n[Function] 用例后置")

# ------------------------------
# 4. 接口请求 fixture(示例)
# ------------------------------
@pytest.fixture(scope="function")
def api_client(session_fixture):
s = requests.Session()
s.base_url = session_fixture
yield s
s.close()

# ------------------------------
# 5. pytest 配置(可选)
# ------------------------------
def pytest_configure(config):
# 注册标记,避免警告
config.addinivalue_line("markers", "smoke: 冒烟测试")
config.addinivalue_line("markers", "api: 接口测试")
config.addinivalue_line("markers", "slow: 慢用例")
四、src/calculator.py(被测代码)
python
运行
def add(a: int | float, b: int | float) -> int | float:
return a + b

def divide(a: int | float, b: int | float) -> int | float:
if b == 0:
raise ValueError("除数不能为0")
return a / b
五、tests/test_calculator.py(单元测试模板)
python
运行
import pytest
from src.calculator import add, divide

# ------------------------------
# 1. 普通测试
# ------------------------------
def test_add_normal():
assert add(1, 2) == 3
assert add(-1, 1) == 0

# ------------------------------
# 2. 参数化测试(最常用)
# ------------------------------
@pytest.mark.parametrize("a, b, expected", [
(1, 2, 3),
(0, 0, 0),
(-5, 3, -2),
(2.5, 2.5, 5.0),
])
def test_add_param(a, b, expected):
assert add(a, b) == expected

# ------------------------------
# 3. 异常断言(推荐写法)
# ------------------------------
def test_divide_by_zero():
with pytest.raises(ValueError) as excinfo:
divide(10, 0)
assert "除数不能为0" in str(excinfo.value)

# ------------------------------
# 4. 使用 fixture
# ------------------------------
@pytest.mark.smoke
def test_with_fixture(func_fixture, module_fixture):
data = func_fixture
assert data["username"] == "test"

# ------------------------------
# 5. 跳过用例 / 预期失败
# ------------------------------
@pytest.mark.skip(reason="暂不执行")
def test_skip_demo():
assert True

@pytest.mark.xfail(reason="已知bug,待修复")
def test_xfail_demo():
assert 1 == 2
六、tests/test_api_demo.py(接口测试模板)
python
运行
import pytest

@pytest.mark.api
def test_get_request(api_client):
resp = api_client.get(f"{api_client.base_url}/get")
assert resp.status_code == 200
assert "url" in resp.json()

@pytest.mark.api
def test_post_request(api_client):
data = {"key": "value"}
resp = api_client.post(f"{api_client.base_url}/post", json=data)
assert resp.status_code == 200
assert resp.json()["json"]["key"] == "value"
七、常用运行命令(直接复制到终端)
bash
运行
# 1. 基础运行
pytest

# 2. 详细输出
pytest -v

# 3. 只运行冒烟用例
pytest -m smoke -v

# 4. 只运行接口测试
pytest -m api -v

# 5. 运行指定文件/函数
pytest tests/test_calculator.py::test_add_param -v

# 6. 失败停止
pytest -x

# 7. 多进程并行(快很多)
pytest -n auto

# 8. 失败重跑2次
pytest --reruns=2

# 9. 生成HTML报告
pytest --html=report.html --self-contained-html

# 10. 覆盖率报告(html)
pytest --cov=src --cov-report=html
八、PyCharm 一键配置
File → Settings → Tools → Python Integrated Tools
Testing → Default test runner → pytest
右键 tests/ → Run pytest in tests
如果你告诉我你是做接口自动化还是UI 自动化 (Selenium/Playwright),我可以再给你对应场景的专用 pytest 框架模板(含日志、用例依赖、Allure 报告、Excel/JSON 参数化)。
如何使用pytest进行接口测试?
pytest 接口测试实战教程(最清晰、最实用)
我直接给你一套可直接运行、企业级的接口测试模板,不用你自己搭环境,复制就能用。
你会学到:
用 pytest + requests 做接口测试
统一管理域名、请求头、token
接口用例写法(GET/POST)
断言、参数化、异常处理
生成测试报告
完全工程化结构
一、先安装依赖(必须)
bash
运行
pip install pytest requests pytest-html pytest-cov
二、推荐项目结构(标准接口测试框架)
plaintext
api_test_project/
├── conftest.py # 全局 fixture:域名、token、会话
├── test_api.py # 接口测试用例
└── pytest.ini # pytest 配置
三、核心文件 1:conftest.py(全局配置)
这个文件不用导入,pytest 会自动识别。
作用:统一域名、请求头、登录 token、公共会话。
python
运行
import pytest
import requests

# --------------------------
# 全局基础配置(整个测试项目只用这1次)
# --------------------------
@pytest.fixture(scope="session")
def base_url():
return "https://httpbin.org" # 测试接口地址

# --------------------------
# 公共请求会话(自动带请求头)
# --------------------------
@pytest.fixture(scope="session")
def api_session(base_url):
session = requests.Session()

# 公共请求头(所有接口自动带上)
session.headers.update({
"Content-Type": "application/json",
"User-Agent": "pytest-api-test"
})

# 如果需要登录token,在这里写
# login_resp = session.post(f"{base_url}/login", json={"user":"test"})
# token = login_resp.json()["token"]
# session.headers["Authorization"] = f"Bearer {token}"

yield session # 提供给测试用例使用
session.close() # 测试结束关闭会话
四、核心文件 2:test_api.py(接口用例)
直接写 GET / POST / 表单 / JSON 接口用例。
python
运行
import pytest

# --------------------------
# 1. GET 接口测试
# --------------------------
def test_get_api(api_session, base_url):
# 发送请求
resp = api_session.get(f"{base_url}/get", params={"id": 100})

# 断言
assert resp.status_code == 200 # 状态码
assert resp.json()["args"]["id"] == "100" # 业务断言

# --------------------------
# 2. POST JSON 接口测试
# --------------------------
def test_post_json_api(api_session, base_url):
json_data = {
"username": "test",
"password": "123456"
}

resp = api_session.post(f"{base_url}/post", json=json_data)

assert resp.status_code == 200
assert resp.json()["json"]["username"] == "test"

# --------------------------
# 3. 参数化接口(批量测试)
# --------------------------
@pytest.mark.parametrize("num, expected", [(1, "1"), (2, "2"), (10, "10")])
def test_get_param(api_session, base_url, num, expected):
resp = api_session.get(f"{base_url}/get", params={"id": num})
assert resp.json()["args"]["id"] == expected
五、运行命令(直接复制)
1. 基础运行
bash
运行
pytest -v
2. 生成 HTML 报告
bash
运行
pytest --html=report.html --self-contained-html
3. 只运行某个接口用例
bash
运行
pytest test_api.py::test_get_api -v
4. 多线程跑(加速)
bash
运行
pytest -n auto
六、接口测试常用断言(必背)
python
运行
# 状态码断言
assert resp.status_code == 200

# 响应不为空
assert resp.text != ""

# JSON 字段断言
assert resp.json()["code"] == 0
assert "success" in resp.json()["msg"]

# 响应时间断言
assert resp.elapsed.total_seconds() < 1
七、企业级接口测试必备功能(我帮你写好)
1. 带 Token 的请求(登录后调用)
在 conftest.py 里加登录:
python
运行
# 登录获取 token
login_resp = session.post(f"{base_url}/login", json={"username":"admin"})
token = login_resp.json()["data"]["token"]
session.headers["Authorization"] = f"Bearer {token}"
2. 接口数据依赖(A 接口结果给 B 接口用)
python
运行
def test_a(api_session, base_url):
resp = api_session.post(f"{base_url}/post", json={"id": 1})
return resp.json()["json"]["id"] # 返回给其他用例

def test_b(api_session, base_url, test_a):
user_id = test_a
resp = api_session.get(f"{base_url}/get", params={"id": user_id})
assert resp.status_code == 200
3. 接口用例分类(冒烟 / 回归 / 模块)
python
运行
@pytest.mark.smoke
def test_login():
...
运行:
bash
运行
pytest -m smoke -v
八、总结(最简单记忆)
pytest 接口测试 =
conftest.py(公共配置) + api_session(请求) + 用例(发送 + 断言)
你只需要写:
请求地址
请求参数
断言
就完成了接口自动化。

http://www.jsqmd.com/news/554612/

相关文章:

  • 总结全国好用的多元素分析仪品牌,哪家值得推荐? - mypinpai
  • 3.29
  • Win11+VS2022下Ceres库安装全攻略:从源码编译到避坑指南
  • Fun-ASR语音识别新手入门:环境配置+Web服务启动,10分钟搞定
  • 资源下载器:突破平台限制的全场景网络资源获取解决方案
  • # 发散创新:用 Rust构建高性能 Web3.0 智能合约验证器
  • 组合式API如何重塑Vue管理系统开发?探索3大架构升级与实践路径
  • 2026年广西云南等地防潮通信设备工厂排名,这些品牌值得关注 - myqiye
  • oii一键生成动漫,oiioii一键生成动漫,oii邀请码,oiioii邀请码2026年3月29日最新
  • 告别对账烦恼:用SAP COPA深度拆解生产成本9大差异与销售成本
  • # 发散创新:用 Locust 实现高并发压力测试的实战进阶指南在现代分布式系统中,**性能瓶颈往往隐藏在看似稳定的接口背后**。
  • Nunchaku-flux-1-devWebUI国产化适配:麒麟V10+统信UOS操作系统兼容性验证
  • 环视摄像头系统避坑指南:常见标定问题与动态辅助线精度优化
  • Web技术栈全解析:构建Qwen3智能字幕对齐系统管理后台
  • 建设项目筹备:2026年专业可行性研究报告服务参考,大健康产业规划/景观规划与设计,可行性研究报告代写公司有哪些 - 品牌推荐师
  • 2026年上海地区口碑好的纹理美观的进口岩板品牌推荐,专业定制企业全解析 - 工业设备
  • 如何高效配置RedisInsight:Redis可视化管理的完整专业指南
  • 2026年木百叶供货商家推荐,性价比高的是哪些 - 工业品网
  • 圣女司幼幽-造相Z-Turbo环境部署详解:Anaconda虚拟环境管理
  • Hunyuan-MT-7B效果展示:蒙古语牧区政策文件→中文政务公文风格转换
  • api设计风格: 命令式/可链式/配置式
  • Qlib量化投资平台:如何用AI技术提升你的投资策略效率?
  • 飞书H5应用免登实战:用tt.requestAccess搞定SSO,避开redirect_uri的坑
  • Hugo-PaperMod终极指南:快速解决导航菜单渲染异常的3个实战方案
  • 新手小白学习web第5弹
  • 2026年罗马帘制造商家哪家售后好,靠谱品牌排名揭晓 - 工业品牌热点
  • 运算放大器实战指南:从核心原理到精准选型
  • 2026年干法制粒机口碑排行榜,济南干法制粒机生产厂怎么选择 - 工业推荐榜
  • 为什么选择skrollr?5个步骤打造专业级滚动视差效果
  • 基于JavaScript插件架构的Android TTS语音引擎自定义开发指南