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

基于Python+Pytest实现自动化测试(全栈实战指南)

目录

第一篇:基础篇

第1章 自动化测试概述

1.1 什么是自动化测试

第2章 环境搭建与工具链配置

2.1 Python环境安装(Windows/macOS/Linux)

2.2 虚拟环境管理

2.3 Pytest基础配置(pytest.ini)

第3章 Pytest核心语法与测试框架

3.3 Fixture的魔法

第二篇:自动化接口测试

第5章 Pytest接口测试实战

5.3 数据驱动测试完整实现

第三篇:自动化性能测试

第9章 Locust性能测试实战

9.1 基础压测脚本

9.3 Prometheus监控集成

第四篇:企业级工程化

第12章 测试框架架构设计

12.2 配置中心实现

附录:常见错误解决方案

问题1:Fixture循环依赖

问题2:参数化数据格式错误

完整项目结构示例


第一篇:基础篇

第1章 自动化测试概述

1.1 什么是自动化测试

核心定义
自动化测试是通过编写脚本或使用工具替代人工执行测试用例的过程,其核心目标是通过可重复执行的测试流程提升测试效率和覆盖率。

典型应用场景

  • 回归测试:每次代码变更后快速验证核心功能

  • 大数据量测试:如批量数据上传/下载的验证

  • 多环境验证:同时测试Windows/Linux/macOS平台兼容性

Python+Pytest优势

# 示例:一个简单的Pytest测试用例
def test_addition():assert 1 + 1 == 2
  • 语法简洁:无需复杂类继承,函数即用例

  • 插件生态:超过800个官方插件支持各类扩展需求

  • 报告友好:支持HTML/Allure可视化报告生成


第2章 环境搭建与工具链配置

2.1 Python环境安装(Windows/macOS/Linux)

Windows安装步骤

  1. 访问Python官网下载3.8+版本安装包

  2. 勾选"Add Python to PATH"选项

  3. 验证安装:python --version

Linux快速安装

sudo apt update
sudo apt install python3.8 python3-pip
2.2 虚拟环境管理

virtualenv使用示例

pip install virtualenv
virtualenv venv
source venv/bin/activate  # Linux/macOS
venv\Scripts\activate.bat # Windows

pipenv高级用法

pip install pipenv
pipenv install pytest
pipenv run pytest tests/
2.3 Pytest基础配置(pytest.ini)
# pytest.ini 示例配置
[pytest]
addopts = -v --html=report.html
testpaths = tests
python_files = test_*.py

第3章 Pytest核心语法与测试框架

3.3 Fixture的魔法

作用域控制

import pytest@pytest.fixture(scope="module")
def database_connection():conn = create_db_conn()yield connconn.close()def test_query1(database_connection):result = database_connection.execute("SELECT 1")assert result == 1def test_query2(database_connection):# 复用同一个数据库连接

Fixture依赖

@pytest.fixture
def user_token(api_client):return api_client.login("admin", "password123")def test_create_post(user_token):headers = {"Authorization": f"Bearer {user_token}"}# 使用token调用接口

第二篇:自动化接口测试

第5章 Pytest接口测试实战

5.3 数据驱动测试完整实现

测试数据分离

# test_api.py
import pytest
import requestsdef load_yaml_cases(file_name):with open(f"data/{file_name}", 'r') as f:return yaml.safe_load(f)@pytest.mark.parametrize("case", load_yaml_cases("login_cases.yaml"))
def test_user_login(case):url = "https://api.example.com/login"response = requests.post(url,json=case["request_body"],headers=case.get("headers", {}))assert response.status_code == case["expected"]["status_code"]assert response.json()["error_code"] == case["expected"]["error_code"]

YAML数据文件

# data/login_cases.yaml
- name: 正确用户名密码登录request_body:username: "valid_user"password: "correct_password"expected:status_code: 200error_code: 0- name: 错误密码登录request_body:username: "valid_user"password: "wrong_password"expected:status_code: 401error_code: 1001

第三篇:自动化性能测试

第9章 Locust性能测试实战

9.1 基础压测脚本
# locustfile.py
from locust import HttpUser, task, betweenclass WebsiteUser(HttpUser):wait_time = between(1, 5)@task(3)def view_items(self):self.client.get("/items")@task(1)def add_to_cart(self):self.client.post("/cart", json={"item_id": 42})

启动命令

locust -f locustfile.py --headless -u 1000 -r 100 --run-time 10m
9.3 Prometheus监控集成
from prometheus_client import start_http_server, CounterREQUEST_COUNTER = Counter('api_requests_total', 'Total API requests')class ApiUser(HttpUser):@taskdef call_api(self):REQUEST_COUNTER.inc()self.client.get("/api")

第四篇:企业级工程化

第12章 测试框架架构设计

12.2 配置中心实现
# config/
#   __init__.py
#   dev.yaml
#   prod.yamlimport yaml
import osclass Config:def __init__(self, env="dev"):self.env = envself._load_config()def _load_config(self):with open(f"config/{self.env}.yaml") as f:self.data = yaml.safe_load(f)@propertydef base_url(self):return self.data["base_url"]# 使用示例
config = Config(os.getenv("ENV", "dev"))
requests.get(f"{config.base_url}/api")

附录:常见错误解决方案

问题1:Fixture循环依赖

错误现象
ValueError: Circular dependency detected

解决方案
重构Fixture结构,使用@pytest.fixture(autouse=True)或合并相关Fixture

问题2:参数化数据格式错误

典型错误
TypeError: unhashable type: 'dict'

修正方案
确保参数化数据为可序列化格式:

@pytest.mark.parametrize("a,b,expected", [(1, 2, 3),(4, 5, 9)
])

完整项目结构示例

automation_framework/
├── conftest.py
├── pytest.ini
├── requirements.txt
├── tests/
│   ├── unit/
│   ├── api/
│   │   ├── test_login.py
│   │   └── data/
│   │       └── login_cases.yaml
│   └── performance/
│       └── locustfile.py
└── utils/├── config_loader.py└── report_generator.py

相关文章:

  • 从单点突破到链式攻击:XSS 的渗透全路径解析
  • Linux-信号
  • 【产品经理从0到1】用户研究和需求分析
  • Python 设计模式:桥接模式
  • 23种设计模式-结构型模式之桥接模式(Java版本)
  • LangChain4j 搭配 Kotlin:以协程、流式交互赋能语言模型开发
  • 联易融助力乡村振兴,仙湖茶产业焕新机
  • 智能指针之设计模式4
  • 网络安全·第五天·TCP协议安全分析
  • leetcode0207. 课程表-medium
  • WordPress 只能访问html文件,不能访问php
  • (最新)华为 2026 届校招实习-硬件技术工程师-硬件通用/单板开发—机试题—(共14套)(每套四十题)
  • flutter 插件收集
  • 联易融出席深圳链主企业供应链金融座谈会,加速对接票交所系统
  • AI 模型在前端应用中的典型使用场景和限制
  • Activity使用优化
  • Elasticsearch性能优化实践
  • Nacos 2.0.2 在 CentOS 7 上开启权限认证(含 Docker Compose 配置与接口示例)
  • linux 手动触发崩溃
  • 马浩棋:产通链CT-Chain 破局不动产 RWA,引领数智金融新变革
  • 神二十具备执行发射任务的各项条件
  • 00后为购演唱会门票转账近16万元“解封”银行卡,民警及时追回
  • ESG领跑者|每一步都向前,李宁要让可持续发展成为可持续之事
  • 荣膺劳伦斯大奖实至名归,杜普兰蒂斯的传奇没有极限
  • 九江市人大常委会原党组成员、副主任戴晓慧主动交代问题,正接受审查调查
  • 隽逸不凡——北京画院藏近代篆刻家金城花鸟画赏析