当前位置: 首页 > 开发者资讯

python自动化测试怎么用?

  Python 自动化测试可以通过多种框架和工具实现,覆盖单元测试、接口测试、UI 测试等场景。使用Python进行自动化测试的方法有很多,unittest是Python的内置模块,不需要额外安装,提供了一些工具,可以帮助我们编写和运行测试,确保代码按预期工作。以下是具体方法和示例,帮助你快速上手。

  一、Python 自动化测试的核心框架

  1. 单元测试:unittest(Python 内置)

  适用场景:测试函数、类等最小单元。

  示例:

  pythonimport unittestdef add(a, b):return a + bclass TestAdd(unittest.TestCase):def test_add_positive(self):self.assertEqual(add(2, 3), 5)def test_add_negative(self):self.assertEqual(add(-1, 1), 0)if __name__ == '__main__':unittest.main()

  运行方式:直接执行脚本,或通过命令行 python -m unittest test_module.py。

  2. 接口测试:requests + pytest

  适用场景:测试 RESTful API 的请求与响应。

  示例:

  pythonimport requestsimport pytest@pytest.fixturedef api_url():return "https://jsonplaceholder.typicode.com/posts/1"def test_get_request(api_url):response = requests.get(api_url)assert response.status_code == 200assert response.json()["id"] == 1def test_post_request(api_url):data = {"title": "foo", "body": "bar", "userId": 1}response = requests.post(api_url, json=data) # 实际API可能不支持POST到此端点assert response.status_code == 201 # 根据实际API调整

  运行方式:安装 pytest 后执行 pytest test_api.py -v。

  3. UI 测试:Selenium + pytest

  适用场景:自动化操作浏览器。

  示例:

  pythonfrom selenium import webdriverfrom selenium.webdriver.common.by import Byimport pytest@pytest.fixturedef browser():driver = webdriver.Chrome() # 需提前下载ChromeDriveryield driverdriver.quit()def test_search_google(browser):browser.get("https://www.google.com")search_box = browser.find_element(By.NAME, "q")search_box.send_keys("Python自动化测试")search_box.submit()assert "Python自动化测试" in browser.title

  运行方式:安装 selenium 和浏览器驱动后执行 pytest test_ui.py -v。

python自动化测试怎么用.jpg

  二、自动化测试进阶技巧

  1. 参数化测试

  作用:用同一测试逻辑测试多组数据。

  示例:

  pythonimport 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

  2. 测试夹具

  作用:共享测试前的初始化代码。

  示例:

  pythonimport pytest@pytest.fixturedef setup_db():# 模拟连接数据库print("连接数据库...")yield # 测试执行点print("关闭数据库连接...")def test_db_query(setup_db):assert True # 实际测试数据库查询

  3. 生成测试报告(pytest-html)

  安装:pip install pytest-html

  运行:

  bashpytest test_module.py --html=report.html

  结果:生成 HTML 格式的测试报告,包含通过/失败用例详情。

  4. 持续集成(CI)集成

  工具:GitHub Actions、Jenkins。

  示例(GitHub Actions 配置):

  yamlname: Python CIon: [push]jobs:test:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v2- name: Set up Pythonuses: actions/setup-python@v2with:python-version: '3.9'- name: Install dependenciesrun: pip install pytest selenium- name: Run testsrun: pytest test_ui.py -v

  三、自动化测试最佳实践

  测试分层:

  单元测试(快速反馈)→ 接口测试(核心逻辑)→ UI 测试(全流程)。

  测试数据管理:

  使用外部文件或数据库存储测试数据,避免硬编码。

  日志与截图:

  UI 测试失败时自动截图,日志记录关键步骤。

  并行测试:

  使用 pytest-xdist 加速测试执行:

  bashpytest -n 4 # 启用4个进程并行测试

  四、常见问题解决

  Selenium 报错 WebDriverException:

  检查浏览器驱动版本是否与浏览器匹配。

  接口测试返回 404:

  确认 API 地址是否正确,或使用 requests.get跳过 SSL 验证。

  测试速度慢:

  减少 UI 测试数量,优先用单元/接口测试覆盖核心逻辑。

  通过以上方法,你可以快速搭建 Python 自动化测试体系,覆盖从简单函数到复杂 Web 应用的测试需求。根据项目规模选择合适的工具组合,并逐步完善测试覆盖率。


猜你喜欢