> 技术文档 > 基于Python+Pytest实现自动化测试(全栈实战指南)

基于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 updatesudo apt install python3.8 python3-pip
2.2 虚拟环境管理

virtualenv使用示例

pip install virtualenvvirtualenv venvsource venv/bin/activate # Linux/macOSvenv\\Scripts\\activate.bat # Windows

pipenv高级用法

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

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

3.3 Fixture的魔法

作用域控制

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

Fixture依赖

@pytest.fixturedef 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.pyimport pytestimport 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: 200 error_code: 0- name: 错误密码登录 request_body: username: \"valid_user\" password: \"wrong_password\" expected: status_code: 401 error_code: 1001

第三篇:自动化性能测试

第9章 Locust性能测试实战

9.1 基础压测脚本
# locustfile.pyfrom 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): @task def call_api(self): REQUEST_COUNTER.inc() self.client.get(\"/api\")

第四篇:企业级工程化

第12章 测试框架架构设计

12.2 配置中心实现
# config/# __init__.py# dev.yaml# prod.yamlimport yamlimport osclass Config: def __init__(self, env=\"dev\"): self.env = env self._load_config() def _load_config(self): with open(f\"config/{self.env}.yaml\") as f: self.data = yaml.safe_load(f) @property def 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