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

目录

第一篇:基础篇

[第1章 自动化测试概述](#第1章 自动化测试概述)

[1.1 什么是自动化测试](#1.1 什么是自动化测试)

[第2章 环境搭建与工具链配置](#第2章 环境搭建与工具链配置)

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

[2.2 虚拟环境管理](#2.2 虚拟环境管理)

[2.3 Pytest基础配置(pytest.ini)](#2.3 Pytest基础配置(pytest.ini))

[第3章 Pytest核心语法与测试框架](#第3章 Pytest核心语法与测试框架)

[3.3 Fixture的魔法](#3.3 Fixture的魔法)

第二篇:自动化接口测试

[第5章 Pytest接口测试实战](#第5章 Pytest接口测试实战)

[5.3 数据驱动测试完整实现](#5.3 数据驱动测试完整实现)

第三篇:自动化性能测试

[第9章 Locust性能测试实战](#第9章 Locust性能测试实战)

[9.1 基础压测脚本](#9.1 基础压测脚本)

[9.3 Prometheus监控集成](#9.3 Prometheus监控集成)

第四篇:企业级工程化

[第12章 测试框架架构设计](#第12章 测试框架架构设计)

[12.2 配置中心实现](#12.2 配置中心实现)

附录:常见错误解决方案

问题1:Fixture循环依赖

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

完整项目结构示例


第一篇:基础篇

第1章 自动化测试概述

1.1 什么是自动化测试

核心定义

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

典型应用场景

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

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

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

Python+Pytest优势

python 复制代码
# 示例:一个简单的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快速安装

bash 复制代码
sudo apt update
sudo apt install python3.8 python3-pip
2.2 虚拟环境管理

virtualenv使用示例

bash 复制代码
pip install virtualenv
virtualenv venv
source venv/bin/activate  # Linux/macOS
venv\Scripts\activate.bat # Windows

pipenv高级用法

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

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

3.3 Fixture的魔法

作用域控制

python 复制代码
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 == 1

def test_query2(database_connection):
    # 复用同一个数据库连接

Fixture依赖

python 复制代码
@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 数据驱动测试完整实现

测试数据分离

python 复制代码
# test_api.py
import pytest
import requests

def 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数据文件

python 复制代码
# 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 基础压测脚本
python 复制代码
# locustfile.py
from locust import HttpUser, task, between

class 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})

启动命令

bash 复制代码
locust -f locustfile.py --headless -u 1000 -r 100 --run-time 10m
9.3 Prometheus监控集成
python 复制代码
from prometheus_client import start_http_server, Counter

REQUEST_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 配置中心实现
python 复制代码
# config/
#   __init__.py
#   dev.yaml
#   prod.yaml

import yaml
import os

class 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'

修正方案

确保参数化数据为可序列化格式:

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

完整项目结构示例

python 复制代码
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
相关推荐
旺旺大力包9 分钟前
【 React 】重点知识总结 && 快速上手指南
开发语言·前端·react.js
慕容青峰15 分钟前
【第十六届 蓝桥杯 省 C/Python A/Java C 登山】题解
c语言·c++·python·算法·蓝桥杯·sublime text
enyp8015 分钟前
C++抽象基类定义与使用
开发语言·c++
向来痴_21 分钟前
PyTorch 多 GPU 入门:深入解析 nn.DataParallel 的工作原理与局限
人工智能·pytorch·python
眠修1 小时前
Python 简介与入门
开发语言·python
Ai 编码助手1 小时前
用Go语言&&正则,如何爬取数据
开发语言·后端·golang
C137的本贾尼1 小时前
Java多线程编程初阶指南
java·开发语言
PythonicCC1 小时前
基于Python Socket的多线程聊天程序案例分析
python
Dxy12393102162 小时前
NLTK 语料库与词典资源
python
Bunury2 小时前
element-plus添加暗黑模式
开发语言·前端·javascript