Python提高:pytest的简单案例-由Deepseek产生

以下是 4 个简单但典型的 pytest 案例,覆盖常用场景:

案例1:基本断言(测试一个简单的加法函数)

python 复制代码
# test_basic.py
def add(a, b):
    return a + b

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
    assert add(0, 0) == 0

案例2:参数化测试(一组输入输出)

python 复制代码
# test_parametrize.py
import pytest

def is_even(n):
    return n % 2 == 0

@pytest.mark.parametrize("num, expected", [
    (2, True),
    (3, False),
    (0, True),
    (-4, True),
])
def test_is_even(num, expected):
    assert is_even(num) == expected

案例3:异常测试(断言抛出特定异常)

python 复制代码
# test_exception.py
import pytest

def divide(a, b):
    if b == 0:
        raise ValueError("除数不能为0")
    return a / b

def test_divide_by_zero():
    with pytest.raises(ValueError, match="除数不能为0"):
        divide(10, 0)

案例4:使用 fixture(临时文件与清理)

python 复制代码
# test_fixture.py
import pytest
import tempfile
import os

@pytest.fixture
def temp_file():
    """创建一个临时文件,测试结束后自动删除"""
    f = tempfile.NamedTemporaryFile(delete=False)
    f.write(b"hello pytest")
    f.close()
    yield f.name          # 提供文件路径给测试函数
    os.unlink(f.name)     # 清理

def test_file_content(temp_file):
    with open(temp_file, 'rb') as f:
        content = f.read()
    assert content == b"hello pytest"

运行方式 :保存为 .py 文件,在终端执行 pytest 文件名.py -v 即可看到结果。

相关推荐
Ulyanov6 分钟前
《从质点到位姿:基于Python与PyVista的导弹制导控制全栈仿真》: 驯服猛兽——自动驾驶仪(Autopilot)设计与舵机动力学
python·自动驾驶·雷达电子对抗
暗影八度21 分钟前
OpenMetadata Python ingestion 开发环境搭建与运行文档
开发语言·python
清水白石00826 分钟前
从“能装上”到“可复现”:Python 团队如何正确使用 requirements.txt、锁定文件与依赖分组
开发语言·人工智能·python
jiayong2327 分钟前
Python面试题集 - 基础语法与核心概念
开发语言·windows·python
05候补工程师29 分钟前
ROS 2 入门:从零实现小海龟 (Turtlesim) 的手动控制与自动化绘圆
运维·经验分享·python·ubuntu·机器人·自动化
凯瑟琳.奥古斯特31 分钟前
Django Flask FastAPI 三者对比
开发语言·python·django·flask·fastapi
godspeed_lucip31 分钟前
LLM和Agent——专题2: LLM as Judge 入门(2)
人工智能·python
jiayong2341 分钟前
Python面试题集 - 数据结构与算法
开发语言·python
十年之少1 小时前
使用VSCode 对PyQt5 say Hello—— Python + Qt 开发
vscode·python·qt
70asunflower1 小时前
6.1 图表选择指南
python·信息可视化·数据挖掘·数据分析