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

相关推荐
2501_941982059 分钟前
企业微信二次开发:如何用 Python 搭建通用的 Webhook 实时消息接收
开发语言·python·企业微信
在世修行10 分钟前
第24篇:PyInstaller打包实战 — 从Python脚本到Windows EXE
人工智能·python·pyinstaller
华研前沿标杆游学29 分钟前
2026年制造企业标杆参访实操指南:3步选对适配参访路线
python
Wang ruoxi1 小时前
Pygame 小游戏——一笔画挑战
python·pygame
萧青山1 小时前
AI阅读增强套件:用苏格拉底诘问+对抗性阅读+知识图谱构建深度阅读技能套件(Python实现)
人工智能·python·知识图谱·ai阅读增强
Java面试题总结1 小时前
Python,单引号和双引号有何区别
开发语言·python
lhxcc_fly2 小时前
LangGraph基础知识点
python·langchain·llm·langgraph
Lvan的前端笔记2 小时前
python:Mac 系统 uv 完整安装+入门实战
python·macos·uv
会飞锦鲤2 小时前
基于YOLOv10的瓜果成熟度智能检测系统
人工智能·python·深度学习·yolo·flask
AOwhisky2 小时前
Python 学习笔记(第四期)——字符串:格式化、操作与文本处理——核心知识点自测与详解
开发语言·笔记·python·学习·列表·元组·字典