当前位置: 首页 > news >正文

Python 面试:单元测试unit testing 使用pytest

1. 对于函数进行单元测试

calc.py

def add(x, y):"""Add Function"""return x + ydef subtract(x, y):"""Subtract Function"""return x - ydef multiply(x, y):"""Multiply Function"""return x * ydef divide(x, y):"""Divide Function"""if y == 0: raise ValueError('Can not divide by zero!')return x / y

test_calc.py

import unittest
import calcclass TestCalc(unittest.TestCase):def test_add(self):self.assertEqual(calc.add(10, 5), 15)self.assertEqual(calc.add(-1, 1), 0)self.assertEqual(calc.add(-1, -1), -2)def test_subtract(self):self.assertEqual(calc.subtract(10, 5), 5)self.assertEqual(calc.subtract(-1, 1), -2)self.assertEqual(calc.subtract(-1, -1), 0)def test_multiply(self):self.assertEqual(calc.multiply(10, 5), 50)self.assertEqual(calc.multiply(-1, 1), -1)self.assertEqual(calc.multiply(-1, -1), 1)def test_divide(self):self.assertEqual(calc.divide(10, 5), 2)self.assertEqual(calc.divide(-1, 1), -1)self.assertEqual(calc.divide(-1, -1), 1)self.assertRaises(ValueError, calc.divide, 10, 0)if __name__ == '__main__':unittest.main()

2. 对于对象(object)进行单元测试

employee.py

class Employee:"""A sample Employee class"""raise_amt = 1.05def __init__(self, first, last, pay):self.first = firstself.last = lastself.pay = pay@propertydef email(self):return '{}.{}@email.com'.format(self.first, self.last)@propertydef fullname(self):return '{} {}'.format(self.first, self.last)def apply_raise(self):self.pay = int(self.pay * self.raise_amt)

test_employee.py

import unittest
from employee import Employeeclass TestEmployee(unittest.TestCase):@classmethoddef setUpClass(cls):print('setupClass')@classmethoddef tearDownClass(cls):print('teardownClass')def setUp(self):print('setUp')self.emp_1 = Employee('Elon', 'Musk', 50000)self.emp_2 = Employee('Sue', 'Smith', 60000)def tearDown(self):print('tearDown\n')def test_email(self):print('test_email')self.assertEqual(self.emp_1.email, 'Elon.Musk@email.com')self.assertEqual(self.emp_2.email, 'Sue.Smith@email.com')self.emp_1.first = 'John'self.emp_2.first = 'Jane'self.assertEqual(self.emp_1.email, 'John.Musk@email.com')self.assertEqual(self.emp_2.email, 'Jane.Smith@email.com')def test_fullname(self):print('test_fullname')self.assertEqual(self.emp_1.fullname, 'Elon Musk')self.assertEqual(self.emp_2.fullname, 'Sue Smith')self.emp_1.first = 'John'self.emp_2.first = 'Jane'self.assertEqual(self.emp_1.fullname, 'John Musk')self.assertEqual(self.emp_2.fullname, 'Jane Smith')def test_apply_raise(self):print('test_apply_raise')self.emp_1.apply_raise()self.emp_2.apply_raise()self.assertEqual(self.emp_1.pay, 52500)self.assertEqual(self.emp_2.pay, 63000)if __name__ == '__main__':unittest.main()

输出为:
setupClass
setUp
test_apply_raise
tearDown

.setUp
test_email
tearDown

.setUp
test_fullname
tearDown

.teardownClass


Ran 3 tests in 0.001s

OK

3. 使用mock模拟对象库

employee.py

import requestsclass Employee:"""A sample Employee class"""raise_amt = 1.05def __init__(self, first, last, pay):self.first = firstself.last = lastself.pay = pay@propertydef email(self):return '{}.{}@email.com'.format(self.first, self.last)@propertydef fullname(self):return '{} {}'.format(self.first, self.last)def apply_raise(self):self.pay = int(self.pay * self.raise_amt)def monthly_schedule(self, month):response = requests.get(f'http://company.com/{self.last}/{month}')if response.ok:return response.textelse:return 'Bad Response!'

test_employee.py

import unittest
from unittest.mock import patch
from employee import Employeeclass TestEmployee(unittest.TestCase):@classmethoddef setUpClass(cls):print('setupClass')@classmethoddef tearDownClass(cls):print('teardownClass')def setUp(self):print('setUp')self.emp_1 = Employee('Elon', 'Musk', 50000)self.emp_2 = Employee('Sue', 'Smith', 60000)def tearDown(self):print('tearDown\n')# Test 1def test_email(self):print('test_email')self.assertEqual(self.emp_1.email, 'Elon.Musk@email.com')self.assertEqual(self.emp_2.email, 'Sue.Smith@email.com')self.emp_1.first = 'John'self.emp_2.first = 'Jane'self.assertEqual(self.emp_1.email, 'John.Musk@email.com')self.assertEqual(self.emp_2.email, 'Jane.Smith@email.com')# Test 2def test_fullname(self):print('test_fullname')self.assertEqual(self.emp_1.fullname, 'Elon Musk')self.assertEqual(self.emp_2.fullname, 'Sue Smith')self.emp_1.first = 'John'self.emp_2.first = 'Jane'self.assertEqual(self.emp_1.fullname, 'John Musk')self.assertEqual(self.emp_2.fullname, 'Jane Smith')# Test 3def test_apply_raise(self):print('test_apply_raise')self.emp_1.apply_raise()self.emp_2.apply_raise()self.assertEqual(self.emp_1.pay, 52500)self.assertEqual(self.emp_2.pay, 63000)# Test 4def test_monthly_schedule(self):# 模拟替换网络请求with patch('employee.requests.get') as mocked_get:mocked_get.return_value.ok = Truemocked_get.return_value.text = 'Success'schedule = self.emp_1.monthly_schedule('May')mocked_get.assert_called_with('http://company.com/Musk/May')self.assertEqual(schedule, 'Success')mocked_get.return_value.ok = Falseschedule = self.emp_2.monthly_schedule('June')mocked_get.assert_called_with('http://company.com/Smith/June')self.assertEqual(schedule, 'Bad Response!')if __name__ == '__main__':unittest.main()

输出为:
setupClass
setUp
test_apply_raise
tearDown

.setUp
test_email
tearDown

.setUp
test_fullname
tearDown

.setUp
tearDown

.teardownClass


Ran 4 tests in 0.001s

OK

4. 使用pytest进行测试

binarysearch.py,主要使用assert。

def binary_search(array, target):if not array:return -1begin, end = 0, len(array)while begin < end:mid = begin + (end - begin) // 2if array[mid] == target:return midelif array[mid] > target:end = midelse:begin = mid + 1return -1def test():assert binary_search([0, 1, 2, 3, 4, 5], 1) == 1assert binary_search([0, 1, 2, 3, 4, 5], 6) == -1assert binary_search([0, 1, 2, 3, 4, 5], -1) == -1assert binary_search([0, 1, 2, 3, 4, 5], 0) == 0assert binary_search([0, 1, 2, 3, 4, 5], 5) == 5assert binary_search([0], 0) == 0assert binary_search([], 1) == -1

在CMD中输入指令:pytest binarysearch.py

输出为:
================================================= test session starts =================================================
platform win32 – Python 3.10.9, pytest-7.1.2, pluggy-1.0.0
rootdir: C:\Users\h13je\Working_Log\01092023\python_learning
plugins: anyio-3.5.0
collected 1 item

binarysearch.py . [100%]

================================================== 1 passed in 0.02s ==================================================

相关文章:

Python 面试:单元测试unit testing 使用pytest

1. 对于函数进行单元测试 calc.py def add(x, y):"""Add Function"""return x ydef subtract(x, y):"""Subtract Function"""return x - ydef multiply(x, y):"""Multiply Function""…...

螺旋矩阵、旋转矩阵、矩阵Z字打印

螺旋矩阵 #include <iostream> #include <vector> void display(std::vector<std::vector<int>>&nums){for(int i 0; i < nums.size(); i){for(int j 0; j < nums[0].size(); j){std::cout<<nums[i][j]<< ;}std::cout<<…...

Seaborn绘制热力图的子图

Seaborn绘制热力图的子图 提示&#xff1a;如何绘制三张子图 绘制的时候&#xff0c;会出现如下问题 &#xff08;1&#xff09;如何绘制1*3的子图 &#xff08;2&#xff09;三个显示条&#xff0c;如何只显示最后一个 提示&#xff1a;下面就展示详细步骤 Seaborn绘制热力…...

C++二级题目4

小白鼠再排队 不会 多余的数 #include<iostream> #include<string.h> #include<stdio.h> #include<iomanip> #include<cmath> #include<bits/stdc.h> int a[2000][2000]; int b[2000]; char c[2000]; long long n; using namespace std; i…...

Tomcat 部署时 war 和 war exploded区别

在 Tomcat 调试部署的时候&#xff0c;我们通常会看到有下面 2 个选项。 是选择war还是war exploded 这里首先看一下他们两个的区别&#xff1a; war 模式&#xff1a;将WEB工程以包的形式上传到服务器 &#xff1b;war exploded 模式&#xff1a;将WEB工程以当前文件夹的位置…...

Delphi IdTcpServer IdTcpClient 传输简单文本

Delphi IdTcpServer IdTcpClient 传输简单文本 已经很久敲代码了&#xff0c;想找一段直接Delphi11 TCP简单文本传输&#xff0c;费劲&#xff01;FStringStream 、FStrStream &#xff1a; FStringStream:TStringStream.Create(,TEncoding.UTF8); 已经很久敲代码了&#xff0c…...

界面控件Telerik UI for WPF——Windows 11主题精简模式提升应用体验

Telerik UI for WPF拥有超过100个控件来创建美观、高性能的桌面应用程序&#xff0c;同时还能快速构建企业级办公WPF应用程序。Telerik UI for WPF支持MVVM、触摸等&#xff0c;创建的应用程序可靠且结构良好&#xff0c;非常容易维护&#xff0c;其直观的API将无缝地集成Visua…...

PoseC3D 基于人体姿态的动作识别新范式

摘要1. Introduction2. Related Work动作识别 3D-CNN基于骨架的动作识别 GCN基于骨骼的动作识别 2D-CNN3. Framework3.1. Good Practice for Pose Extraction3.2. From 2D Poses to 3D Heatmap Volumes3.3 基于骨骼的动作识别 3D-CNNPose-SlowOnlyRGBPose-SlowFast4. Experimen…...

html2canvas 截图空白 或出现toDataURL‘ on ‘HTMLCanvasElement或img标签没截下来 的所有解决办法

1.如果截图空白&#xff1a; 1.1以下的参数是必须要有的。 width: shareContent.offsetWidth, //设置canvas尺寸与所截图尺寸相同&#xff0c;防止白边height: shareContent.offsetHeight, //防止白边logging: true,useCORS: true,x:0,y:0,2&#xff0c;如果出现了报错 toData…...

Eclipse错误提示: Symbol ‘xxxx‘ could not be resolved

问题现象&#xff1a; 调试FPGA时&#xff0c;如果在qsys中增加新的内容&#xff0c;到nios中编译的时候就会提示找不到宏定义。 而这些宏定义都是在system.h这个头文件中的&#xff0c;原来的宏定义都能找到&#xff0c;就是新增的找不到&#xff0c;这个应该和头文件路径没有…...

基于Java的OA办公管理系统,Spring Boot框架,vue技术,mysql数据库,前台+后台,完美运行,有一万一千字论文。

基于Java的OA办公管理系统&#xff0c;Spring Boot框架&#xff0c;vue技术&#xff0c;mysql数据库&#xff0c;前台后台&#xff0c;完美运行&#xff0c;有一万一千字论文。 系统中的功能模块主要是实现管理员和员工的管理&#xff1b; 管理员&#xff1a;个人中心、普通员工…...

正则表达式(JAVA)

正则表达式(JAVA) 文章目录 正则表达式(JAVA)用法字符类(只匹配一个字符)预定义字符(只匹配一个字符)数量词贪婪爬取符号捕获分组规则捕获分组符号 非捕获分组案例忽略大小写 用法 正则表达式在用于校验信息是否满足某些规则的时候,非常的好用 在文本中查找满足要求的内容 字…...

264_BOOST中的Json库解析_BOOST_AUTO(itrpromodel, doc.FindMember(“productmodel“));

BOOST_AUTO(itrpromodel, doc.FindMember("productmodel"));if(itrpromodel != doc.MemberEnd()){BOOST_AUTO(iterd_url...

linux rpm 离线安装 nginx 自用,仅供参考

检查是否安装nginx ps -ef|grep nginx 检查rpm是否安装nginx rpm -qa|grep nginx 查看linux centos 发行版本 cat /etc/centos-release (查看其它发现版本 就把centos替换为别的 比如 红旗的 redflag ) 查看cpu信息 x86_64 lscpu 检查nginx所需依赖 …...

第十二章 YOLO的部署实战篇(上篇)

cuda教程目录 第一章 指针篇 第二章 CUDA原理篇 第三章 CUDA编译器环境配置篇 第四章 kernel函数基础篇 第五章 kernel索引(index)篇 第六章 kenel矩阵计算实战篇 第七章 kenel实战强化篇 第八章 CUDA内存应用与性能优化篇 第九章 CUDA原子(atomic)实战篇 第十章 CUDA流(strea…...

无涯教程-Android - List View函数

Android ListView 是垂直滚动列表中显示的视图&#xff0c;使用 Adapter 从列表(如数组或数据库)中获取内容的列表项会自动插入列表中。 适配器(Adapter)实际上是UI组件和将数据填充到UI组件中的数据源之间的桥梁&#xff0c;适配器保存数据并将数据发送到适配器视图&#xff0…...

stable diffusion实践操作-重绘

系列文章目录 本文专门开一节写局部重绘相关的内容&#xff0c;在看之前&#xff0c;可以同步关注&#xff1a; stable diffusion实践操作 提示&#xff1a;写完文章后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 系列文章目录前言一、局…...

C# 静态构造函数未执行 .net core框架

代码如下&#xff0c;在执行Encoding.GetEncoding(“gb2312”);方法后报错&#xff0c;说没有找到对应编码&#xff0c;经测试&#xff0c;发现是静态构造函数未执行。 public static class Encodings {/// <summary>/// 注册相关编码/// </summary>static Encodi…...

Java 复习笔记 - 学生管理系统篇

文章目录 学生管理系统一&#xff0c;需求部分需求分析初始菜单学生类添加功能删除功能修改功能查询功能 二&#xff0c;实现部分&#xff08;一&#xff09;初始化主界面&#xff08;二&#xff09;编写学生类&#xff08;三&#xff09;编写添加学生方法&#xff08;四&#…...

【UIPickerView-UIDatePicker-应用程序对象 Objective-C语言】

一、今天我们来学习三个东西 1.UIPickerView-UIDatePicker-应用程序对象 1.首先,来看数据选择控件 数据选择控件, 大家对这个数据选择控件,是怎么理解的, 1)数据选择控件,首先,是不是得有数据, 2)然后呢,你还得让用户能够选择, 3)最后,你还得是一个控件儿 那…...

仿京东 项目笔记1

目录 项目代码1. 项目配置2. 前端Vue核心3. 组件的显示与隐藏用v-if和v-show4. 路由传参4.1 路由跳转有几种方式&#xff1f;4.2 路由传参&#xff0c;参数有几种写法&#xff1f;4.3 路由传参相关面试题4.3.1 路由传递参数&#xff08;对象写法&#xff09;path是否可以结合pa…...

huggingface transformers库中LlamaForCausalLM

新手入门笔记。 LlamaForCausalLM 的使用示例&#xff0c;这应该是一段推理代码。 from transformers import AutoTokenizer, LlamaForCausalLMmodel LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS) tokenizer AutoTokenizer.from_pretrained(PATH_TO_CONVE…...

04-过滤器和拦截器有什么区别?【Java面试题总结】

过滤器和拦截器有什么区别&#xff1f; 运行顺序不同&#xff1a;过滤器是在 Servlet 容器接收到请求之后&#xff0c;但在 Servlet被调用之前运行的&#xff1b;而拦截器则是在Servlet 被调用之后&#xff0c;但在响应被发送到客户端之前运行的。 过滤器Filter 依赖于 Servle…...

如何用selenium或pyppeteer来启动多个AdsPower窗口

前言 本文是该专栏的第57篇,后面会持续分享python爬虫干货知识,记得关注。 关于selenium或pyppeteer来启动打开adspower浏览器的方法,笔者在本专栏前面有详细介绍过,感兴趣的同学可往前翻阅《如何用selenium或pyppeteer来链接并打开指纹浏览器AdsPower》,文章内容包含完整…...

京东店铺所有商品API接口数据

​​京东平台店铺所有商品数据接口是开放平台提供的一种API接口&#xff0c;通过调用API接口&#xff0c;开发者可以获取京东整店的商品的标题、价格、库存、月销量、总销量、库存、详情描述、图片、价格信息等详细信息 。 获取店铺所有商品接口API是一种用于获取电商平台上商…...

stm32之27.iic协议oled显示

屏幕如果无法点亮&#xff0c;需要用GPIO_OType_PP推挽输出&#xff0c;加并上拉电阻 1.显示字符串代码 2.显示图片代码&#xff08;unsigned强制转换&#xff08;char*&#xff09;&#xff09; 汉字显示...

paddle 1-高级

目录 为什么要精通深度学习的高级内容 高级内容包含哪些武器 1. 模型资源 2. 设计思想与二次研发 3. 工业部署 4. 飞桨全流程研发工具 5. 行业应用与项目案例 飞桨开源组件使用场景概览 框架和全流程工具 1. 模型训练组件 2. 模型部署组件 3. 其他全研发流程的辅助…...

ChatGPT帮助高职院校学生实现个性化自适应学习与对话式学习

一、学习层面&#xff1a;ChatGPT帮助高职院校学生实现个性化自适应学习与对话式学习 1.帮助高职院校学生实现个性化自适应学习 数字技术的飞速发展引起了教育界和学术界对高职院校学生个性化自适应学习的更多关注和支持&#xff0c;其运作机制依赖于人工智能等技术&#xff0…...

如何通过python写接口自动化脚本对一个需要调用第三方支付的报名流程进行测试?

对于需要调用第三方支付的报名流程进行接口自动化测试&#xff0c;可以通过以下步骤来编写Python代码&#xff1a; 1. 确认API需求 首先&#xff0c;需要确认报名流程的API需求和预期功能。这涉及到对业务需求的理解和API设计的分析。 2. 安装依赖库 在Python程序中&#x…...

将OSGB格式数据转换为3d tiles的格式

现有需求需要将已有的一些OSGB数据加载到CesiumJS中展示,但是CesiumJS本身不支持osbg格式的数据渲染所以我们需要将其转换一下,有两种格式可以转换一种是glTF格式,另一种是我们今天要介绍的3D Tiles格式 下载开源工具 在github上其实有好多这种工具,每个工具的用法大同小异,这…...