百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

使用Pytest进行单元测试 pytest教程

zhezhongyun 2024-12-16 17:34 42 浏览



PyTest简介



`pytest` 是一个非常流行的 Python 测试框架,提供了简单易用的测试功能。以下是 `pytest` 的基本使用方法:

  1. 安装 `pytest`
pip install pytest
  1. 创建测试文件

`pytest` 会自动发现以 `test_` 开头或 `_test` 结尾的文件。你可以创建一个名为 `test_example.py` 的文件。

# test_example.py
def add(a, b):
return a + b
def test_add():
assert add(1, 2) == 3
assert add(-1, 1) == 0
assert add(0, 0) == 0
  1. 运行测试

在命令行中,导航到包含测试文件的目录,然后运行以下命令:

pytest

`pytest` 会自动查找以 `test_` 开头的测试文件,并执行其中的测试函数。

  1. 查看测试结果

运行 `pytest` 后,你会看到测试的结果,包括通过的测试和失败的测试。如果测试失败,`pytest` 会提供详细的错误信息,帮助你调试。

  1. 测试夹具(Fixtures)

`pytest` 还支持测试夹具,用于设置测试环境。可以使用 `@pytest.fixture` 装饰器定义夹具。例如:

import pytest

@pytest.fixture
def sample_data():
	return [1, 2, 3]

def test_sum(sample_data):
	assert sum(sample_data) == 6


  1. 参数化测试

你可以使用 `@pytest.mark.parametrize` 来参数化测试函数。例如:

import pytest
@pytest.mark.parametrize("a, b, expected", [
  (1, 2, 3),
  (-1, 1, 0),
  (0, 0, 0)
  ])
def test_add(a, b, expected):
	assert add(a, b) == expected
  1. 运行特定测试

如果你只想运行特定的测试,可以使用以下命令:

pytest -k "test_add"
  1. 生成测试报告

你还可以生成测试报告,比如 HTML 格式的报告。首先安装 `pytest-html`:

pip install pytest-html

然后运行测试并生成报告:

pytest --html=report.html

`pytest` 是一个功能强大且灵活的测试框架,适合用于单元测试和集成测试。通过上述方法,你可以快速上手并编写测试用例。

实践

这里有一个基于Alchemy 访问MySQL的类,要对其中的方法进行测试,使用pytest输出测试报告。写了三个单元测试文件,应用了夹具和参数进行测试,最终的结果如下:




测试代码如下:


# hanzi_test.py
import os
import sys

# 添加当前文件所在目录到Python路径中
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(current_dir)

# 添加包的父目录到Python路径中
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)

from interface.mysql.db_dictation.service.HanziService import HanziService
from interface.mysql.db_dictation.entity.Hanzi import Hanzi
def test_hanzi():

    obj = HanziService()

    res = obj.getByHanzi('好')

    for itm in res:
        assert itm.f_hanzi == '好'
        print(f"{itm.f_hanzi} {itm.f_pinyin} {itm.f_meaning} {itm.f_sound_url} {itm.f_writing_url}")

def test_hanzi_pinyin():
    obj = HanziService()

    res = obj.getByHanziAndPinyin('好', 'hào')

    assert res.f_hanzi == '好' 
    assert res.f_pinyin == 'hào'

    itm = res
    print(f"{itm.f_hanzi} {itm.f_pinyin} {itm.f_meaning} {itm.f_sound_url} {itm.f_writing_url}")

def test_pinyin():

    obj = HanziService()

    res = obj.getByPinyin('hào')

    for itm in res:
        assert itm.f_pinyin == 'hào'
        print(f"{itm.f_hanzi} {itm.f_pinyin} {itm.f_meaning} {itm.f_sound_url} {itm.f_writing_url}")
# fixture_test.py
import os
import sys

# 添加当前文件所在目录到Python路径中
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(current_dir)

# 添加包的父目录到Python路径中
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)


import pytest
@pytest.fixture
def getObj():
    from interface.mysql.db_dictation.service.HanziService import HanziService
    from interface.mysql.db_dictation.entity.Hanzi import Hanzi
    return HanziService()
def test_fixture_hanzi(getObj):

    res = getObj.getByHanzi('好')

    for itm in res:
        assert itm.f_hanzi == '好'
        print(f"{itm.f_hanzi} {itm.f_pinyin} {itm.f_meaning} {itm.f_sound_url} {itm.f_writing_url}")

def test_fixture_hanzi_pinyin(getObj):

    res = getObj.getByHanziAndPinyin('好', 'hào')

    assert res.f_hanzi == '好' 
    assert res.f_pinyin == 'hào'
    itm = res
    print(f"{itm.f_hanzi} {itm.f_pinyin} {itm.f_meaning} {itm.f_sound_url} {itm.f_writing_url}")

def test_fixture_pinyin(getObj):

    res = getObj.getByPinyin('hào')

    for itm in res:
        assert itm.f_pinyin == 'hào'
        print(f"{itm.f_hanzi} {itm.f_pinyin} {itm.f_meaning} {itm.f_sound_url} {itm.f_writing_url}")
# parametrize_test.py
import os
import sys

# 添加当前文件所在目录到Python路径中
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(current_dir)

# 添加包的父目录到Python路径中
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)

from interface.mysql.db_dictation.service.HanziService import HanziService
from interface.mysql.db_dictation.entity.Hanzi import Hanzi

import pytest

@pytest.mark.parametrize("hanzi, pinyin, expected", [
    ('好', 'hào','好'),
    ('耗', 'hào','耗'),
    ('浩', 'hào','浩'),
    ('颢', 'hào','颢'),
])
def test_parametrize_hanzi(hanzi,pinyin,expected):

    obj = HanziService()

    res = obj.getByHanzi(hanzi)

    for itm in res:
        assert itm.f_hanzi == expected
        print(f"{itm.f_hanzi} {itm.f_pinyin} {itm.f_meaning} {itm.f_sound_url} {itm.f_writing_url}")

@pytest.mark.parametrize("hanzi, pinyin, expected", [
    ('好', 'hào','好'),
    ('耗', 'hào','耗'),
    ('浩', 'hào','浩'),
    ('颢', 'hào','颢'),
])
def test_parametrize_hanzi_pinyin(hanzi,pinyin,expected):
    obj = HanziService()

    res = obj.getByHanziAndPinyin(hanzi, pinyin)

    assert res.f_hanzi == hanzi
    assert res.f_pinyin == pinyin

    itm = res
    print(f"{itm.f_hanzi} {itm.f_pinyin} {itm.f_meaning} {itm.f_sound_url} {itm.f_writing_url}")

@pytest.mark.parametrize("hanzi, pinyin, expected", [
    ('好', 'hào','好'),
    ('耗', 'hào','耗'),
    ('浩', 'hào','浩'),
    ('颢', 'hào','颢'),
])
def test_parametrize_pinyin(hanzi,pinyin,expected):

    obj = HanziService()

    res = obj.getByPinyin(pinyin)

    for itm in res:
        assert itm.f_pinyin == pinyin
        print(f"{itm.f_hanzi} {itm.f_pinyin} {itm.f_meaning} {itm.f_sound_url} {itm.f_writing_url}")

参考文章:

  1. Python技术架构 https://www.toutiao.com/article/7422119050685334054/
  2. PyTest : https://docs.pytest.org/en/stable/index.html

相关推荐

JPA实体类注解,看这篇就全会了

基本注解@Entity标注于实体类声明语句之前,指出该Java类为实体类,将映射到指定的数据库表。name(可选):实体名称。缺省为实体类的非限定名称。该名称用于引用查询中的实体。不与@Tab...

Dify教程02 - Dify+Deepseek零代码赋能,普通人也能开发AI应用

开始今天的教程之前,先解决昨天遇到的一个问题,docker安装Dify的时候有个报错,进入Dify面板的时候会出现“InternalServerError”的提示,log日志报错:S3_USE_A...

用离散标记重塑人体姿态:VQ-VAE实现关键点组合关系编码

在人体姿态估计领域,传统方法通常将关键点作为基本处理单元,这些关键点在人体骨架结构上代表关节位置(如肘部、膝盖和头部)的空间坐标。现有模型对这些关键点的预测主要采用两种范式:直接通过坐标回归或间接通过...

B 客户端流RPC (clientstream Client Stream)

客户端编写一系列消息并将其发送到服务器,同样使用提供的流。一旦客户端写完消息,它就等待服务器读取消息并返回响应gRPC再次保证了单个RPC调用中的消息排序在客户端流RPC模式中,客户端会发送多个请...

我的模型我做主02——训练自己的大模型:简易入门指南

模型训练往往需要较高的配置,为了满足友友们的好奇心,这里我们不要内存,不要gpu,用最简单的方式,让大家感受一下什么是模型训练。基于你的硬件配置,我们可以设计一个完全在CPU上运行的简易模型训练方案。...

开源项目MessageNest打造个性化消息推送平台多种通知方式

今天介绍一个开源项目,MessageNest-可以打造个性化消息推送平台,整合邮件、钉钉、企业微信等多种通知方式。定制你的消息,让通知方式更灵活多样。开源地址:https://github.c...

使用投机规则API加快页面加载速度

当今的网络用户要求快速导航,从一个页面移动到另一个页面时应尽量减少延迟。投机规则应用程序接口(SpeculationRulesAPI)的出现改变了网络应用程序接口(WebAPI)领域的游戏规则。...

JSONP安全攻防技术

关于JSONPJSONP全称是JSONwithPadding,是基于JSON格式的为解决跨域请求资源而产生的解决方案。它的基本原理是利用HTML的元素标签,远程调用JSON文件来实现数据传递。如果...

大数据Doris(六):编译 Doris遇到的问题

编译Doris遇到的问题一、js_generator.cc:(.text+0xfc3c):undefinedreferenceto`well_known_types_js’查找Doris...

网页内嵌PDF获取的办法

最近女王大人为了通过某认证考试,交了2000RMB,官方居然没有给线下教材资料,直接给的是在线教材,教材是PDF的但是是内嵌在网页内,可惜却没有给具体的PDF地址,无法下载,看到女王大人一点点的截图保...

印度女孩被邻居家客人性骚扰,父亲上门警告,反被围殴致死

微信的规则进行了调整希望大家看完故事多点“在看”,喜欢的话也点个分享和赞这样事儿君的推送才能继续出现在你的订阅列表里才能继续跟大家分享每个开怀大笑或拍案惊奇的好故事啦~话说只要稍微关注新闻的人,应该...

下周重要财经数据日程一览 (1229-0103)

下周焦点全球制造业PMI美国消费者信心指数美国首申失业救济人数值得注意的是,下周一希腊还将举行第三轮总统选举需要谷歌日历同步及部分智能手机(安卓,iPhone)同步日历功能的朋友请点击此链接,数据公布...

PyTorch 深度学习实战(38):注意力机制全面解析

在上一篇文章中,我们探讨了分布式训练实战。本文将深入解析注意力机制的完整发展历程,从最初的Seq2Seq模型到革命性的Transformer架构。我们将使用PyTorch实现2个关键阶段的注意力机制变...

聊聊Spring AI的EmbeddingModel

序本文主要研究一下SpringAI的EmbeddingModelEmbeddingModelspring-ai-core/src/main/java/org/springframework/ai/e...

前端分享-少年了解过iframe么

iframe就像是HTML的「内嵌画布」,允许在页面中加载独立网页,如同在画布上叠加另一幅动态画卷。核心特性包括:独立上下文:每个iframe都拥有独立的DOM/CSS/JS环境(类似浏...