用Python实现自动化测试:从单元测试到API验证

文章目录

    • 前言
    • 一、自动化测试基础
      • [1.1 为什么选择Python?](#1.1 为什么选择Python?)
      • [1.2 工具准备](#1.2 工具准备)
    • 二、单元测试实战
      • [2.1 编写简单函数](#2.1 编写简单函数)
      • [2.2 使用unittest测试](#2.2 使用unittest测试)
      • [2.3 升级到pytest](#2.3 升级到pytest)
    • 三、API自动化测试
      • [3.1 测试目标](#3.1 测试目标)
      • [3.2 编写API测试](#3.2 编写API测试)
      • [3.3 用pytest优化](#3.3 用pytest优化)
    • 四、进阶优化
      • [4.1 测试报告生成](#4.1 测试报告生成)
      • [4.2 集成到CI/CD](#4.2 集成到CI/CD)
      • [4.3 性能测试初探](#4.3 性能测试初探)
    • 五、注意事项
    • 六、总结

前言

在软件开发中,自动化测试是提升代码质量和开发效率的关键。Python凭借其简洁语法和强大库(如unittestpytestrequests),成为自动化测试的热门选择。本文将从单元测试入手,逐步扩展到API自动化验证,带你打造一个高效的测试流程。无论你是测试新手还是资深开发者,这篇教程都能帮你快速上手。欢迎在评论区分享你的自动化测试经验!


一、自动化测试基础

1.1 为什么选择Python?

  • 生态丰富 :支持unittest(内置)、pytest(功能强大)、requests(API测试)。
  • 易上手:语法简单,适合快速编写测试用例。
  • 跨平台:适用于Web、后端、AI等多种场景。

1.2 工具准备

安装所需库:

bash 复制代码
pip install pytest requests

二、单元测试实战

2.1 编写简单函数

假设我们要测试一个计算器函数:

python 复制代码
# calculator.py
def add(a, b):
    return a + b

def divide(a, b):
    if b == 0:
        raise ValueError("除数不能为0")
    return a / b

2.2 使用unittest测试

创建测试文件:

python 复制代码
# test_calculator.py
import unittest
from calculator import add, divide

class TestCalculator(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)
        self.assertEqual(add(-1, 1), 0)

    def test_divide(self):
        self.assertEqual(divide(6, 2), 3.0)
        with self.assertRaises(ValueError):
            divide(5, 0)

if __name__ == "__main__":
    unittest.main()

运行测试:

bash 复制代码
python test_calculator.py

2.3 升级到pytest

pytest更灵活,支持断言和 fixture:

python 复制代码
# test_calculator_pytest.py
from calculator import add, divide

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0

def test_divide():
    assert divide(6, 2) == 3.0
    try:
        divide(5, 0)
    except ValueError:
        pass

运行:

bash 复制代码
pytest test_calculator_pytest.py -v

Tips :pytest自动发现以test_开头的文件和函数,-v显示详细输出。


三、API自动化测试

3.1 测试目标

以免费API"JSONPlaceholder"为例,测试GET请求:

地址:https://jsonplaceholder.typicode.com/posts/1

3.2 编写API测试

使用requests验证响应状态和数据:

python 复制代码
# test_api.py
import requests

def test_get_post():
    url = "https://jsonplaceholder.typicode.com/posts/1"
    response = requests.get(url)
    
    # 验证状态码
    assert response.status_code == 200, "状态码应为200"
    
    # 验证JSON数据
    data = response.json()
    assert data["id"] == 1, "ID应为1"
    assert "title" in data, "响应应包含title字段"
    
    print(f"标题: {data['title']}")

if __name__ == "__main__":
    test_get_post()

运行:

bash 复制代码
python test_api.py

3.3 用pytest优化

添加参数化和异常处理:

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

@pytest.mark.parametrize("post_id, expected_title", [
    (1, "sunt aut facere repellat provident occaecati excepturi optio reprehenderit"),
    (2, "qui est esse")
])
def test_get_post_param(post_id, expected_title):
    url = f"https://jsonplaceholder.typicode.com/posts/{post_id}"
    response = requests.get(url)
    
    assert response.status_code == 200
    data = response.json()
    assert data["title"] == expected_title

def test_invalid_post():
    url = "https://jsonplaceholder.typicode.com/posts/999"
    response = requests.get(url)
    assert response.status_code == 404, "无效ID应返回404"

运行:

bash 复制代码
pytest test_api_pytest.py -v

四、进阶优化

4.1 测试报告生成

使用pytest-html生成HTML报告:

bash 复制代码
pip install pytest-html
pytest --html=report.html

4.2 集成到CI/CD

将测试脚本加入GitHub Actions:

yaml 复制代码
# .github/workflows/test.yml
name: Run Tests
on: [push]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    - name: Set up Python
      uses: actions/setup-python@v4
      with:
        python-version: '3.9'
    - name: Install dependencies
      run: pip install pytest requests
    - name: Run tests
      run: pytest -v

4.3 性能测试初探

time模块记录API响应时间:

python 复制代码
import time

def test_api_performance():
    url = "https://jsonplaceholder.typicode.com/posts/1"
    start = time.time()
    response = requests.get(url)
    duration = time.time() - start
    assert duration < 1.0, f"响应时间 {duration}s 超过1秒"

五、注意事项

  • 测试覆盖率 :安装pytest-cov检查覆盖率(pip install pytest-cov)。
  • 异常处理 :API测试中添加超时参数(如requests.get(url, timeout=5))。
  • 合规性:避免频繁请求公共API,遵守使用规则。

六、总结

通过本文,你学会了用Python从单元测试到API验证的全流程。unittest适合基础测试,pytest提供灵活扩展,而requests让API测试更简单。下一步,你可以尝试将这些脚本集成到项目中,或探索性能测试工具如Locust

互动环节

  • 你在自动化测试中用过哪些框架?有什么优化建议吗?
  • 遇到过哪些测试难题?欢迎留言交流!
相关推荐
apcipot_rain16 分钟前
【应用密码学】实验五 公钥密码2——ECC
前端·数据库·python
小彭律师22 分钟前
门禁人脸识别系统详细技术文档
笔记·python
鸿业远图科技1 小时前
分式注记种表达方式arcgis
python·arcgis
头疼的程序员2 小时前
allure生成测试报告(搭配Pytest、allure-pytest)
测试工具·pytest
别让别人觉得你做不到2 小时前
Python(1) 做一个随机数的游戏
python
小彭律师3 小时前
人脸识别门禁系统技术文档
python
张小九995 小时前
PyTorch的dataloader制作自定义数据集
人工智能·pytorch·python
zstar-_5 小时前
FreeTex v0.2.0:功能升级/支持Mac
人工智能·python·macos·llm
苏生要努力5 小时前
第九届御网杯网络安全大赛初赛WP
linux·python·网络安全
于壮士hoho6 小时前
DeepSeek | AI需求分析
人工智能·python·ai·需求分析·dash