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 小时前
力扣刷题——509. 斐波那契数
python·算法·leetcode·动态规划
科雷软件测试2 小时前
使用python+Midscene.js AI驱动打造企业级WEB自动化解决方案
前端·javascript·python
星越华夏2 小时前
python——三角函数用法
开发语言·python
gmaajt3 小时前
mysql如何检查数据库表是否存在损坏_使用CHECK TABLE命令修复
jvm·数据库·python
heRs BART3 小时前
【Flask】四、flask连接并操作数据库
数据库·python·flask
PyHaVolask4 小时前
Python 爬虫进阶:直接请求 JSON 接口与开发者工具使用
爬虫·python·请求头·反爬·json接口·chrome开发者工具
larance4 小时前
安装dify的几个问题
python
2301_773553624 小时前
CSS如何对用户访问过的链接进行降级颜色处理_使用-visited伪类改变颜色
jvm·数据库·python
2301_815279524 小时前
Golang怎么理解Go的sync.Pool底层_Golang如何理解Pool的本地缓存和GC清理机制【详解】
jvm·数据库·python