python自动化测试
Python自动化测试指南
Python是自动化测试领域的首选语言之一,凭借其简洁的语法、丰富的库和强大的生态系统,能够高效地实现各种测试需求。本文将详细介绍Python在自动化测试中的应用,涵盖Web测试、API测试、单元测试、GUI测试等多个方面。
1. 自动化测试基础
测试金字塔
E2E测试 (少量)▲│集成测试 (适量)▲│单元测试 (大量)
测试类型
- 单元测试:测试最小功能单元
- 集成测试:测试模块间交互
- 系统测试:测试完整系统
- 验收测试:验证是否满足需求
- 回归测试:确保变更未引入新缺陷
2. 单元测试(unittest/pytest)
2.1 使用unittest
import unittestclass Calculator:def add(self, a, b):return a + bdef subtract(self, a, b):return a - bclass TestCalculator(unittest.TestCase):def setUp(self):self.calc = Calculator()def test_add(self):self.assertEqual(self.calc.add(2, 3), 5)self.assertEqual(self.calc.add(-1, 1), 0)def test_subtract(self):self.assertEqual(self.calc.subtract(5, 3), 2)self.assertEqual(self.calc.subtract(1, 1), 0)if __name__ == '__main__':unittest.main()
2.2 使用pytest(推荐)
# 安装: pip install pytest
def test_add():assert 1 + 1 == 2def test_subtract():assert 5 - 3 == 2# 参数化测试
import pytest@pytest.mark.parametrize("a, b, expected", [(1, 2, 3),(0, 0, 0),(-1, 1, 0)
])
def test_add_parametrized(a, b, expected):assert a + b == expected
pytest优势:
- 简洁的语法(无需继承TestCase)
- 自动发现测试
- 丰富的插件系统
- 更好的断言(无需assertEqual,直接使用assert)
3. Web自动化测试(Selenium)
3.1 安装Selenium
pip install selenium
# 下载对应浏览器的WebDriver
# Chrome: https://sites.google.com/chromium.org/driver/
# Firefox: https://github.com/mozilla/geckodriver/releases