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

相关推荐
whcyhhh15 分钟前
CTF‑MISC 隐写术完整学习笔记|图片隐写全题型 + 工具 + 实战例题
python·网络安全·ctf·misc·信息隐藏
码视野31 分钟前
多宠 RFID 颈圈识别与湿粮半导体制冷保鲜分餐喂食器解决方案(软硬件一体化)
大数据·人工智能·python
未若君雅裁34 分钟前
让模型按契约返回数据,LangChain 结构化输出实战
python·langchain
学习中.........2 小时前
Transformer 训练资源估算:以 CS336 GPT-2 XL 配置为例
人工智能·python·算法·机器学习·自然语言处理
小陈的进阶之路8 小时前
Claude Code辅助测试:导入篇skills
python·自动化
whcyhhh9 小时前
头歌实践教学平台:大数据存储2023(六)
大数据·数据库·python
for_ever_love__9 小时前
python基础语法学习: 闭包
开发语言·python·学习·闭包
ly76899 小时前
Python 全面入门:从核心语法到工程实践
开发语言·python
Niuguangshuo11 小时前
DeepFilterNet 3:端侧实时全带降噪的开源标杆
python
第一程序员11 小时前
AI 辅助编程的 7 个误区:把模型当高级搜索引擎是对它的最大浪费
python·rust·github