用Python实现自动化测试:从单元测试到API验证_pytest api自动化
文章目录
前言
在软件开发中,自动化测试是提升代码质量和开发效率的关键。Python凭借其简洁语法和强大库(如unittest
、pytest
、requests
),成为自动化测试的热门选择。本文将从单元测试入手,逐步扩展到API自动化验证,带你打造一个高效的测试流程。无论你是测试新手还是资深开发者,这篇教程都能帮你快速上手。欢迎在评论区分享你的自动化测试经验!
一、自动化测试基础
1.1 为什么选择Python?
- 生态丰富:支持
unittest
(内置)、pytest
(功能强大)、requests
(API测试)。 - 易上手:语法简单,适合快速编写测试用例。
- 跨平台:适用于Web、后端、AI等多种场景。
1.2 工具准备
安装所需库:
pip install pytest requests
二、单元测试实战
2.1 编写简单函数
假设我们要测试一个计算器函数:
# calculator.pydef add(a, b): return a + bdef divide(a, b): if b == 0: raise ValueError(\"除数不能为0\") return a / b
2.2 使用unittest测试
创建测试文件:
# test_calculator.pyimport unittestfrom calculator import add, divideclass 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()
运行测试:
python test_calculator.py
2.3 升级到pytest
pytest更灵活,支持断言和 fixture:
# test_calculator_pytest.pyfrom calculator import add, dividedef test_add(): assert add(2, 3) == 5 assert add(-1, 1) == 0def test_divide(): assert divide(6, 2) == 3.0 try: divide(5, 0) except ValueError: pass
运行:
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
验证响应状态和数据:
# test_api.pyimport requestsdef 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()
运行:
python test_api.py
3.3 用pytest优化
添加参数化和异常处理:
# test_api_pytest.pyimport pytestimport 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_titledef test_invalid_post(): url = \"https://jsonplaceholder.typicode.com/posts/999\" response = requests.get(url) assert response.status_code == 404, \"无效ID应返回404\"
运行:
pytest test_api_pytest.py -v
四、进阶优化
4.1 测试报告生成
使用pytest-html
生成HTML报告:
pip install pytest-htmlpytest --html=report.html
4.2 集成到CI/CD
将测试脚本加入GitHub Actions:
# .github/workflows/test.ymlname: Run Testson: [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响应时间:
import timedef 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
。
互动环节:
- 你在自动化测试中用过哪些框架?有什么优化建议吗?
- 遇到过哪些测试难题?欢迎留言交流!