亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

PyTest 教程:安装、编写与运行 Python 测试的完整指南

什么是 PyTest?

PyTest 是一款强大的开源测试框架,让开发者能为 Python 项目编写简洁、可扩展的测试用例——无论是单元测试、集成测试还是端到端 API 测试。支持并行执行、固件注入、参数化、开箱即用的丰富报告。

为什么选择 PyTest?

安装 PyTest

使用 pip 安装最新稳定版:

pip install pytest

验证安装:

pytest --version

如需指定版本,可固定版本号,如 pip install pytest==7.4.0。

入门:基础测试

创建项目目录,添加测试文件 test_sample1.py:

import pytest
def test_file1_method1():
    x = 5
    y = 6
    assert x + 1 == y, "Addition failed"
    assert x == y, "Values should match"
def test_file1_method2():
    x = 5
    y = 6
    assert x + 1 == y, "Addition failed"

运行测试套件:

pytest

输出示例:

==================== test session starts ====================
collected 2 items
test_sample1.py F. [100%]
=================================== FAILURES ===================================
...

理解断言

PyTest 断言表现如标准 Python assert 语句。失败时测试停止,PyTest 报告确切位置和信息:

assert "hello" == "Hai", "Mismatched greeting"

测试发现规则

运行特定测试

执行目录下所有测试:

pytest

运行单个文件:

pytest test_sample1.py

按子串过滤:

pytest -k method1 -v

按标记运行:

pytest -m set1

并行执行

安装 xdist 插件并启动 4 进程并行:

pip install pytest-xdist
pytest -n 4

使用固件

定义一次可复用的设置逻辑并注入测试:

import pytest
@pytest.fixture
def supply_data():
    return [25, 35, 45]
def test_compare_with_first(supply_data):
    assert supply_data[0] == 25

将固件代码放入 conftest.py 可跨多测试模块共享。

参数化测试

单测试运行多组输入:

import pytest
@pytest.mark.parametrize("a, b, expected", [(5, 5, 10), (3, 5, 8)])
def test_add(a, b, expected):
    assert a + b == expected

跳过与预期失败

使用标记跳过或标记预期失败,不污染结果:

import pytest
@pytest.mark.skip(reason="Feature not yet available")
def test_future_feature():
    pass
@pytest.mark.xfail(reason="Known bug")
def test_known_issue():
    assert 1 == 2

生成 XML 报告

生成兼容 JUnit 的 XML 文件供 CI 流水线使用:

pytest -v --junitxml=result.xml

实战示例:测试公开 API

下面最小框架演练 https://reqres.in/:

# conftest.py
import pytest
@pytest.fixture
def base_url():
    return "https://reqres.in/api"
# test_list_user.py
import requests, json
import pytest
@pytest.mark.parametrize("user_id, first_name", [(1, "George"), (2, "Janet")])
def test_valid_user(base_url, user_id, first_name):
    resp = requests.get(f"{base_url}/users/{user_id}")
    data = json.loads(resp.text)
    assert resp.status_code == 200
    assert data["data"]["id"] == user_id
    assert data["data"]["first_name"] == first_name
def test_invalid_user(base_url):
    resp = requests.get(f"{base_url}/users/50")
    assert resp.status_code == 404
# test_login_user.py
import requests, json
import pytest
def test_login_success(base_url):
    payload = {"email": "test@test.com", "password": "something"}
    resp = requests.post(f"{base_url}/login/", data=payload)
    data = json.loads(resp.text)
    assert resp.status_code == 200
    assert data["token"] == "QpwL5tke4Pnpja7X"
def test_login_missing_password(base_url):
    payload = {"email": "test@test.com"}
    resp = requests.post(f"{base_url}/login/", data=payload)
    data = json.loads(resp.text)
    assert resp.status_code == 400
    assert data["error"] == "Missing password"

结语

本教程涵盖 PyTest 安装、编写清晰测试、使用固件与标记、并行运行、生成 XML 报告、构建简单 API 测试套件。掌握这些基础,你能自信地扩展 Python 测试实践。

Python

  1. 维护积压详解:化解策略与最佳实践
  2. 电子管测试仪全攻略:选型、操作与避坑指南
  3. 轻松找回并保护Wi-Fi网络安全密钥:完整指南
  4. WiFi通话全解析:原理、优势与运营商支持现状
  5. 6G技术前瞻:超高速连接的未来图景与关键突破
  6. 局部放电测试解析:守护高压设备安全
  7. 预防泵汽蚀:成因、症状与避免措施全解析
  8. 铜钎焊完全指南:工艺对比、操作步骤与实战技巧
  9. 装卸平台安装实战指南:Koke专业团队的标准化交付流程
  10. 液压泵性能测试全流程:从出厂验收到现场状态监测
  11. Google Cloud部署WordPress全流程实战:从实例创建到域名SSL配置
  12. Coded UI 测试自动化框架:从入门到实战的完整指南