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

相关推荐
川石课堂软件测试2 分钟前
零基础小白如何学习自动化测试
python·功能测试·学习·测试工具·jmeter·压力测试·harmonyos
在繁华处9 分钟前
Java从零到熟练(十二):Java与AI工具整合
java·人工智能·python
如烟花的信页12 分钟前
数美滑块逆向分析
javascript·爬虫·python·js逆向
轮子飞了34 分钟前
记一次 Spring AI Alibaba + 百炼的踩坑:结构化输出与联网搜索的冲突
人工智能·python·spring
专注VB编程开发20年40 分钟前
VB.NET是唯一能直接打击 Python 的语言
python
梦想三三1 小时前
【NLP入门到实战】TF-IDF算法详解 + 红楼梦120回关键词提取
人工智能·python·计算机视觉
弹简特1 小时前
【零基础学Python】05-Python函数完全指南:从初阶定义到进阶参数,一篇打通核心难点
开发语言·python
学地理的小胖砸1 小时前
【批量处理tiff文件生成jpg缩略图】
数据库·人工智能·python
机汇五金_1 小时前
通信设备防雨箱如何兼顾防护与散热?
网络·python
糖果店的幽灵1 小时前
LangChain 1.3 完全教程:从入门到精通-Part 7: Documents(文档处理)
java·python·langchain