分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请轻击人工智能教程​​https://www.captainai.net/troubleshooter

这是一份最实用、最精简、可直接落地项目的 PyTest 核心教程,覆盖 90% 日常测试需求,适合自动化测试、单元测试、接口测试使用。

一、安装与基础运行

1. 安装

pip install pytest

2. 命名规则(必须遵守)

PyTest 自动识别

  • 测试文件:test_*.py*_test.py
  • 测试函数 / 方法:test_*
  • 测试类:Test*(类内不能有 __init__

3. 运行命令(最常用)

pytest                          # 运行所有测试
pytest -v                       # 详细输出(推荐)
pytest -s                       # 显示 print 内容
pytest test_demo.py             # 运行单个文件
pytest test_demo.py::test_func  # 运行单个用例

二、最简单的测试用例

示例:test_demo.py

# 最简单的测试:函数形式
def test_add():
    assert 1 + 2 == 3

# 测试类形式
class TestDemo:
    def test_sub(self):
        assert 5 - 2 == 3

运行:

pytest test_demo.py -v

PyTest 最大优势:只用原生 assert,不用任何复杂语法!

三、断言(核心)

PyTest 断言超级简单,全部用 Python 自带 assert

1. 常用断言

assert 1 == 1           # 相等
assert 2 > 1            # 大小
assert "a" in "abc"     # 包含
assert True             # 布尔判断
assert [1,2] == [1,2]   # 列表相等

2. 异常断言(必学)

验证代码是否抛出预期异常

import pytest

def test_zero_division():
    with pytest.raises(ZeroDivisionError):
        1 / 0

3. 浮点数断言(必学)

assert 0.1 + 0.2 == pytest.approx(0.3)

四、Fixture(测试神器)

Fixture = 前置 + 后置 + 共享数据替代传统 setup/teardown,是 PyTest 最核心功能。

1. 基础 Fixture

import pytest

# 定义 fixture
@pytest.fixture
def user():
    print("\n前置:准备用户数据")
    yield {"name": "test", "age": 18}  # 返回数据给测试用例
    print("\n后置:清理数据")

# 测试用例直接使用(传参即可)
def test_user(user):
    assert user["age"] == 18

2. Fixture 作用域(重点)

@pytest.fixture(scope="function")  # 默认:每个函数执行一次
@pytest.fixture(scope="class")     # 每个类一次
@pytest.fixture(scope="module")    # 每个文件一次
@pytest.fixture(scope="session")   # 整个测试会话一次(全局)

3. 自动执行 Fixture

@pytest.fixture(autouse=True)  # 自动运行,不用传参
def setup():
    print("每个用例自动执行前置")

4. conftest.py(全局共享)

项目根目录创建 conftest.py所有测试文件都能使用里面的 fixture,无需导入。

五、参数化测试(数据驱动)

一组测试逻辑 + 多组测试数据 = 批量运行大幅减少重复代码。

1. 基础参数化

import pytest

@pytest.mark.parametrize("a, b, expected", [
    (1, 2, 3),
    (4, 5, 9),
    (0, 0, 0),
])
def test_add(a, b, expected):
    assert a + b == expected

2. 给用例起名字(清晰)

@pytest.mark.parametrize("a, b, expected", [
    (1, 2, 3),
    (4, 5, 9),
], ids=["正常1", "正常2"])

六、标记用例(skip/xfail/ 自定义)

1. 跳过用例

@pytest.mark.skip("暂时不执行")
def test_skip():
    assert 1 == 2

2. 条件跳过

import sys
@pytest.mark.skipif(sys.platform == "win32", reason="Windows不支持")
def test_linux_only():
    pass

3. 预期失败(已知 Bug)

@pytest.mark.xfail(reason="Bug未修复")
def test_known_fail():
    assert False

4. 自定义标记(冒烟 / 回归)

@pytest.mark.smoke  # 冒烟用例
def test_login():
    assert True

运行:

pytest -m smoke

七、常用插件(必装)

1. 生成美观 HTML 报告

pip install pytest-html
pytest --html=report.html

2. 测试覆盖率

pip install pytest-cov
pytest --cov

3. 多进程并行运行(加速)

pip install pytest-xdist
pytest -n auto

八、标准项目结构(企业级)

项目/
├── conftest.py       # 全局 fixture
├── pytest.ini        # 配置文件
├── src/              # 业务代码
└── tests/            # 测试目录
    ├── test_api.py
    ├── test_db.py
    └── test_user.py

pytest.ini 示例

[pytest]
testpaths = tests
python_files = test_*.py
python_classes = Test*
python_functions = test_*
markers =
    smoke: 冒烟测试
    api: 接口测试

九、完整实战示例(可直接复制)

import pytest

# Fixture
@pytest.fixture
def calc():
    class Calc:
        def add(self, a, b): return a + b
        def div(self, a, b): return a / b
    return Calc()

# 参数化
@pytest.mark.parametrize("a,b,expected", [(1,2,3), (4,5,9)])
def test_add(calc, a, b, expected):
    assert calc.add(a, b) == expected

# 异常测试
def test_div_zero(calc):
    with pytest.raises(ZeroDivisionError):
        calc.div(1, 0)

# 跳过用例
@pytest.mark.skip
def test_skip():
    assert 1 == 1

核心总结(记住这 6 点就够了)

  1. 文件 / 函数以 test_ 开头,自动识别
  2. 只用 assert 断言,简单强大
  3. Fixture 做前置 / 后置 / 数据共享
  4. @parametrize 实现数据驱动
  5. mark 标记:skip/xfail/smoke
  6. 插件:报告、覆盖率、并行执行

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐