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

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

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



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

相关推荐

JavaScript做个贪吃蛇小游戏(过关-加速),无需网络直接玩。

JavaScript做个贪吃蛇小游戏(过关-则加速)在浏览器打开文件,无需网络直接玩。<!DOCTYPEhtml><htmllang="en"><...

大模型部署加速方法简单总结(大模型 ai)

以下对大模型部署、压缩、加速的方法做一个简单总结,为后续需要备查。llama.cppGithub:https://github.com/ggerganov/llama.cppLLaMA.cpp项...

安徽医大第一医院应用VitaFlow Liberty(R)Flex为患者焕然一“心”

近日,在安徽医科大学第一附属医院心血管内科负责人暨北京安贞医院安徽医院业务副院长喻荣辉教授的鼎力支持和卓越带领下,凭借着先进的VitaFlowLiberty(R)Flex经导管主动脉瓣可回收可...

300 多行代码搞定微信 8.0 的「炸」「裂」特效!

微信8.0更新的一大特色就是支持动画表情,如果发送的消息只有一个内置的表情图标,这个表情会有一段简单的动画,一些特殊的表情还有全屏特效,例如烟花表情有全屏放烟花的特效,炸弹表情有爆炸动画并且消息和...

让div填充屏幕剩余高度的方法(div填充20px)

技术背景在前端开发中,经常会遇到需要让某个div元素填充屏幕剩余高度的需求,比如创建具有固定头部和底部,中间内容区域自适应填充剩余空间的布局。随着CSS技术的发展,有多种方法可以实现这一需求。实现步骤...

css之div内容居中(css中div怎么居中)

div中的内容居中显示,包括水平和垂直2个方向。<html><head><styletype="text/css">...

使用uniapp开发小程序遇到的一些问题及解决方法

1、swiper组件自定义知识点swiper组件的指示点默认是圆圈,想要自己设置指示点,需要获得当前索引,然后赋给当前索引不同的样式,然后在做个动画就可以了。*关键点用change方法,然后通过e.d...

微信小程序主页面排版(怎样设置小程序的排版)

开发小程序的话首先要了解里面的每个文件的作用小程序没有DOM对象,一切基于组件化小程序的四个重要的文件*.js*.wxml--->view结构---->html*.wxss--...

Vue动态组件的实践与原理探究(vue动态组件component原理)

我司有一个工作台搭建产品,允许通过拖拽小部件的方式来搭建一个工作台页面,平台内置了一些常用小部件,另外也允许自行开发小部件上传使用,本文会从实践的角度来介绍其实现原理。ps.本文项目使用VueCLI...

【HarmonyOS Next之旅】兼容JS的类Web开发(四) -> tabs

目录1->创建Tabs2->设置Tabs方向3->设置样式4->显示页签索引5->场景示例编辑1->创建Tabs在pages/index目录...

CSS:前端必会的flex布局,我把布局代码全部展示出来了

进入我的主页,查看更多CSS的分享!首先呢,先去看文档,了解flex是什么,这里不做赘述。当然,可以看下面的代码示例,辅助你理解。一、row将子元素在水平方向进行布局:1.垂直方向靠顶部,水平方向靠...

【HarmonyOS Next之旅】兼容JS的类Web开发(四) -> swiper

目录1->创建Swiper组件2->添加属性3->设置样式4->绑定事件5->场景示例编辑1->创建Swiper组件在pages/index...

CSS:Flex布局,网页排版神器!(css3 flex布局)

还在为网页排版抓狂?别担心,CSS的flex布局来了,让你轻松玩转各种页面布局,实现网页设计自由!什么是Flex布局?Flex布局,也称为弹性布局,是CSS中的一种强大布局方式,它能够让你...

移动WEB开发之flex布局,附携程网首页案例制作

一、flex布局体验传统布局兼容性好布局繁琐局限性,不能再移动端很好的布局1.1flex弹性布局:操作方便,布局极为简单,移动端应用很广泛PC端浏览器支持情况较差IE11或更低版本,不支持或仅部...

2024最新升级–前端内功修炼 5大主流布局系统进阶(mk分享)

2024最新升级–前端内功修炼5大主流布局系统进阶(mk分享)获课》789it.top/14658/前端布局是网页设计中至关重要的一环,它决定了网页的结构和元素的排列方式。随着前端技术的不断发展,现...