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 即可看到结果。

相关推荐
云和数据.ChenGuang7 小时前
Python 常见特殊方法详解:__new__、__init__、__del__、__str__、__repr__ 与 __getattribute__
开发语言·人工智能·python·1024程序员节
xyouyuweizhu8 小时前
字节流与字符流:Java IO 的两条主线该怎么选
java·开发语言·python
迪菲赫尔曼8 小时前
【基础篇 04】第一次使用终端:命令在哪里输入,电脑现在又“站”在哪里?
python·yolo·目标检测
qianbo_insist8 小时前
# 在 Qwen3.5-2B 上把 GDN-1 无损换成 GDN-2:一次完整的架构手术实验(负结果)
人工智能·pytorch·python·架构
专注仿真10 小时前
Agentic RAG算法详解
人工智能·python·大模型训练·控制算法
学习论之费曼学习法10 小时前
无人值守AI内容矩阵实战(8):标题 A/B 实验的 6 个工程实现细节,隔日对比与自动判胜
人工智能·python·算法·矩阵·自动化·a/b测试·内容矩阵
东哥168810 小时前
我用 DeepSeek 做了 4 个零依赖的赚钱小工具,全部开源
python·开源·deepseek
Carl_奕然10 小时前
【机器视觉】最强算法之:3D高斯泼溅(3D Gaussian Splatting)
人工智能·python·算法·目标检测·计算机视觉·3d
小亮_money11 小时前
Agent开发工程师-Python环境搭建
人工智能·python
isfox11 小时前
Python3 线程:多任务并发编程详解
python