python-测试代码

news2024/9/22 12:21:00

1. 测试函数

get_name.py

def combination(first, last):
    '''将姓名组合在一起'''
    name = first + ' ' + last
    return name.title()

hello_world.py

from get_name import combination

print("Enter 'q' to quit!")
while True:
    first = input('Please input your first name: ')
    if first == 'q':
        break
    last = input('Please input your last name: ')
    if last == 'q':
        break
    name = combination(first, last)
    print(name)

# Enter 'q' to quit!
# Please input your first name: tom
# Please input your last name: riddle
# Tom Riddle
# Please input your first name: q

1.1. 单元测试和测试用例

  • 单元测试:用于核实函数的某个方面没有问题。

  • 测试用例:是一组单元测试,这些单元测试一起核实函数在各种情形下的行为都符号要求。

  • 全覆盖式侧式用例:包含一整套单元测试,涵盖了各种可能的函数使用方式。

1.1.1 可通过的测试

注意:

  • 导入模块unittest以及要测试的函数

  • 创建一个继承unittest.TestCase的类,编写一系列方法对函数行为的不同方面进行测试

  • 方法名使用test_或test,会在我们运行.py时自动运行这个方法

  • 断言方法,即调用unittest的方法assertEqual(测试的结果,期望的结果)

  • 在最后加上 if __name__=='__main__' : unittest.main()

get_name.py

def combination(first, last):
    '''将姓名组合在一起'''
    name = first + ' ' + last
    return name.title()

hello_world.py

from get_name import combination

print("Enter 'q' to quit!")
while True:
    first = input('Please input your first name: ')
    if first == 'q':
        break
    last = input('Please input your last name: ')
    if last == 'q':
        break
    name = combination(first, last)
    print(name)

# Enter 'q' to quit!
# Please input your first name: tom
# Please input your last name: riddle
# Tom Riddle
# Please input your first name: q

test_name.py

import unittest
from get_name import combination

class TestName(unittest.TestCase):
    def test_name(self):
        result_name = combination('harry', 'potter')
        self.assertEqual(result_name, 'Harry Potter')

if __name__ == '__main__':
    unittest.main()

# Ran 1 test in 0.008s
# OK

1.1.2 不能通过的测试

get_name.py

def combination(first, middle, last):
    '''将姓名组合在一起'''
    name = first + ' ' + middle + ' ' + last
    return name.title()

再次运行test_name.py,运行结果如下:

1.1.3 测试未通过时进行处理

修改get_name.py

def combination(first, last, middle=''):
    '''将姓名组合在一起'''
    if middle:
        name = first + ' ' + middle + ' ' + last
    else:
        name = first + ' ' + last
    return name.title()

test_name.py运行结果:

1.1.4 添加新测试

注意:测试类中的函数名要带有描述性,这样才能明白测试未通过时的输出

test_name.py

import unittest
from get_name import combination

class TestName(unittest.TestCase):
    def test_name(self):
        result_name = combination('harry', 'potter')
        self.assertEqual(result_name, 'Harry Potter')

    def test_middle_name(self):
        result_name = combination('li', 'xiao', 'ming')
        self.assertEqual(result_name, 'Li Ming Xiao')

if __name__ == '__main__':
    unittest.main()

# Ran 2 tests in 0.002s
# OK

2. 测试类

2.1. 各种断言方法

unittest.TestCase类中提供了很多断言的方法:

方法

用途

assertEqual(a,b)

核实 a==b

assertNotEqual(a,b)

核实 a!=b

assertTrue(x)

核实x为True

assertFalse(x)

核实x为False

assertIn(item,list)

核实item在list中

assertNotIn(item,list)

核实item不在list中

2.2. 一个要测试的类

investigate.py

class Investigation():
    '''调查问卷'''

    def __init__(self, question):
        self.question = question
        self.responses = []

    def show_question(self):
        print(self.question)

    def store_new_response(self, new_response):
        self.responses.append(new_response)

    def show_results(self):
        for response in self.responses:
            print(response)

language_investigate.py

from investigate import Investigation

question = '你喜欢哪种编程语言?'
my_investigate = Investigation(question)
my_investigate.show_question()
print("Enter 'q' to quit!")
while True:
    response = input('Language: ')
    if response == 'q':
        break
    my_investigate.store_new_response(response)
my_investigate.show_results()
# 你喜欢哪种编程语言?
# Enter 'q' to quit!
# Language: Python
# Language: C
# Language: q
# Python
# C

2.3. 测试Investigation类

investigate_test.py

import unittest
from investigate import Investigation

class TestInvestigate(unittest.TestCase):
    def test_store_single_response(self):
        question = '你喜欢哪种编程语言?'
        my_investigate = Investigation(question)
        my_investigate.store_new_response('Python')
        self.assertIn('Python', my_investigate.responses)

if __name__ == '__main__':
    unittest.main()
# Ran 1 test in 0.002s
# OK

investigate_test.py(针对多个回答做测试)

import unittest
from investigate import Investigation

class TestInvestigate(unittest.TestCase):
    def test_store_single_response(self):
        question = '你喜欢那种编程语言?'
        my_investigate = Investigation(question)
        my_investigate.store_new_response('Python')
        self.assertIn('Python', my_investigate.responses)

    def test_store_three_responses(self):
        question = '你喜欢哪些编程语言?'
        my_investigate = Investigation(question)
        responses = ['C', 'Java', 'Python']
        for response in responses:
            my_investigate.store_new_response(response)
        for response in responses:
            self.assertIn(response, my_investigate.responses)

if __name__ == '__main__':
    unittest.main()
# Ran 2 tests in 0.002s
# OK

2.4. setUp方法

注意:

  • unittest.TestCase类包含setUp方法,这样我们只需创建一次对象,并在各个测试方法中使用它。

  • Python会先运行setUp方法,再运行以test_打头的方法,因此我们编写的每个测试方法就都可以使用在setUp中创建的对象了。

import unittest
from investigate import Investigation

class TestInvestigate(unittest.TestCase):
    def setUp(self):
        question = '你喜欢什么编程语言?'
        self.investigate = Investigation(question)
        self.responses = ['C', 'Python', 'Java']

    def test_store_single_response(self):
        self.investigate.store_new_response(self.responses[1])
        self.assertIn(self.responses[1], self.investigate.responses)

    def test_store_three_responses(self):
        for response in self.responses:
            self.investigate.store_new_response(response)
        for response in self.responses:
            self.assertIn(response, self.investigate.responses)

if __name__ == '__main__':
    unittest.main()

# Ran 2 tests in 0.002s
# OK

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/177096.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

理光Aficio MP C2500扫描到文件夹设置方法

首先在需要接收扫描文件的电脑上设置共享文件夹。 注: (1)文件夹的名字最好简单一点,比如:scan、123等等; (2)文件夹的共享权限最好能设置为最大(WindowsXP、Windows200…

Future、CompletableFuture概述

1.同步和异步 (1)同步:需要等待结果返回,才能继续运行 (2)异步:不需要等待结果返回,就能继续运行 (3)异步设计:多线程可以让方法执行变为异步(比…

第四章必备前端基础知识-第二节3:CSS盒模型和浮动

文章目录一:盒模型(1)border(2)padding(3)margin二:flex布局一:盒模型 盒模型:在HTML中,每个标签(或元素)相当于是一个盒…

Mybatis和Jpa

这里写目录标题1.Mybatis1.1 JDBC的缺点1.2 Mybatis的整体架构1.3 入门案例1.3.1 问题:无法连接到数据库服务器1.4 动态代理实现Mapper1.5 mybatis-config.xml配置1.5.1 properties属性读取外部资源1.5.2 settings设置1.5.3 typeAliases1.5.4 typeHandlers(类型处理…

【Substance Designer】基础操作和节点学习记录

写在前面 这个记录稍微有点杂,大概是庄懂的技术美术入门课(美术向)-直播录屏-第20课和一些基础操作的记录合集吧! 补充 学习发现,基础的节点是需要学习和记录的,但是真正用起来还是要多用多练!所以这种简单的记录节点…

YOLOv5/v7 引入 RepVGG 重参数化模块

本篇博文代码出自YOLOv5-lite ,YOLOv5-lite的作者在CSDN的账号是 pogg_ ,大家可以关注一下,这也是一位在开源项目上做了很多工作的博主。 RepVGG的原理和融合推导过程可以看我的这篇博文:RepVGG:让VGG风格的ConvNets再…

机制设计原理与应用(三)Screening

文章目录3 Screening3.1 为单个不可分割的项目定价3.1.1 对θ\thetaθ的假设3.1.2 问题描述3.1.3 特性3.2 为无限可分的项目定价3.2.1 对θ\thetaθ的假设3.2.3 特性3.2.4 收益最大化3.2.5 最优解决方案3 Screening Screening theory:机制设计理论可以被看作是其多…

Cadence PCB仿真使用Allegro PCB SI生成振铃ringing仿真报告及报告导读图文教程

🏡《Cadence 开发合集目录》   🏡《Cadence PCB 仿真宝典目录》 目录 1,概述2,生成报告3,报告导读4,总结1,概述 本文简单介绍使用Allegro PCB SI生成网络的振铃性能评估的报告的方法,及振铃ringing报告要点导读。 2,生成报告 第1步,选择需要生成报告的网络,然后…

第二章 ArcGIS数据和地理数据库

文章目录第一节 ArcGIS和4D数据基本知识1 4D数据介绍1.1 DLG1.2 DEM1.3 DOM1.4 DRG1.5 4D表现2 ArcGIS的数据和4D数据对应3 栅格数据3.1 查看帮助3.2 空间分辨率3.3 分辨率与比例尺换算3.4 栅格数据介绍——cellsize3.5 栅格数据波段3.6 栅格格式4 栅格数据改变分辨率5 转换栅格…

【 uniapp - 黑马优购 | 登录与支付(2)】如何实现三秒后跳转和微信支付

个人名片: 🐼作者简介:一名大二在校生,讨厌编程🎋 🐻‍❄️个人主页🥇:小新爱学习. 🐼个人WeChat:见文末 🕊️系列专栏:🖼…

Ubuntu20.04+MAVROS+PX4+Gazebo安装教程

Ubuntu20.04MAVROSPX4Gazebo安装PX4步骤安装MAVROS安装QGCPX4仿真安装PX4步骤 从github上clone源码 git clone https://github.com/PX4/PX4-Autopilot.git --recursive进入PX4-Autopilot文件夹,继续下载未下载完的组件 cd PX4-Autopilot/ git submodule update -…

flowable使用 act_hi_xxx

HistoryService 流程历史信息 act_hi_procinst : 历史流程信息&#xff0c;&#xff0c;如果流程执行完了&#xff0c;end_time_ 和 duration不为null // 没有执行完的List<HistoricProcessInstance> list historyService.createHistoricProcessInstanceQuery().unfi…

uniapp封装并全局挂载request请求

前言 日常开发中,前端项目中需要调用服务端api完成页面渲染,uniapp提供的请求api:uni.request相对繁琐;另外服务端提供的不同api仅子路径不同,api域名以及根路径都是相同的,一旦接口api变更,需要更改地方就会很多.鉴于以上可以将uni.request进行封装,简化开发. 目前uniapp项…

MySQL(四):B+树索引、聚簇索引、二级索引、联合索引

目录一、B树索引1.1 在没有索引时进行查找记录1.2 索引方案1.3 InnoDB中的索引方案二、聚簇索引三、二级索引四、联合索引五、InnoDB中B树索引的注意事项5.1 根页面的位置不会改变5.2 内节点中目录项记录的唯一性5.3 一个页面至少容纳两条记录一、B树索引 数据库中的用来存储数…

MySQL进阶篇之索引1

02、索引 2.1、索引概述 1、介绍 索引&#xff08;index&#xff09;是帮助MySQL高效获取数据的数据结构&#xff08;有序&#xff09;。在数据之外&#xff0c;数据库系统还维护着满足特定查找算法的数据结构&#xff0c;这些数据结构以某种方式引用&#xff08;指向&#…

Cepstral Analysis 倒谱分析

源过滤器分离 倒谱分析是另一种将声道滤波器响应与激励分开的方法&#xff08;如线性预测&#xff09; 它基于以下观察&#xff1a;语音信号的频谱是激励频谱和声道频率响应的乘积 可以使用log将乘法转换为加法&#xff0c;因此&#xff0c;“对数频谱”可以看作是对数激励频…

十七、Gtk4-Menu and action

Menu 用户经常使用菜单向计算机发出命令。它是这样的: 现在让我们分析一下上面的菜单。对象有两种类型。 “File”, “Edit”, “View”, “Cut”, “Copy”, “Paste” and “Select All”. 它们被称为“菜单项&#xff08;menu item&#xff09;”或简单地称为“item”。当…

字节青训前端笔记 | 前端调试

在程序员的世界中&#xff0c;BUG 一词相信同学们再熟悉不过了&#xff0c;本节课将围绕前端开发中所遇见的 BUG 出发&#xff0c;讲解作为一名合格的前端开发人员&#xff0c;你应该掌握哪些开发调试知识 Chorme DevTools Chorme DevTools 是 chorme内核为大家提供的高效的前…

gdb使用

gdb是一款UNIX及UNIX-like下的调试工具 gdb可用于调试用gcc编译的可执行文件&#xff0c;用gdb调试时gcc编译需要使用参数-g 本文是对于gdb在Linux下使用的基本命令的总结gdb调试视频演示&#xff0c;gdb调试基础指令&#xff0c;gdb调试其他命令&#xff0c;gdb常见错误说明 目…

23种设计模式(二十一)——命令模式【行为变化】

文章目录 意图什么时候使用命令真实世界类比命令模式的实现命令模式的优缺点亦称:动作、事务、Action、Transaction、Command 意图 将一个请求封装为一个对象,使发出请求的责任和执行请求的责任分割开。这样两者之间通过命令对象进行沟通,这样方便将命令对象进行储存、传递…