Google单元测试sample分析(四)
GoogleTest单元测试可用实现在每个测试用例结束后监控其内存使用情况,
可以通过GoogleTest提供的事件侦听器EmptyTestEventListener 来实现,下面通过官方提供的sample例子,路径在samples文件夹下的sample10_unittest.cpp
// Copyright 2009 Google Inc. All Rights Reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.// This sample shows how to use Google Test listener API to implement
// a primitive leak checker.#include <stdio.h>
#include <stdlib.h>#include "gtest/gtest.h"
using ::testing::EmptyTestEventListener;
using ::testing::InitGoogleTest;
using ::testing::Test;
using ::testing::TestEventListeners;
using ::testing::TestInfo;
using ::testing::TestPartResult;
using ::testing::UnitTest;namespace {
// We will track memory used by this class.
class Water {public:// Normal Water declarations go here.// operator new and operator delete help us control water allocation.void* operator new(size_t allocation_size) {allocated_++;return malloc(allocation_size);}void operator delete(void* block, size_t /* allocation_size */) {allocated_--;free(block);}static int allocated() { return allocated_; }private:static int allocated_;
};int Water::allocated_ = 0;// This event listener monitors how many Water objects are created and
// destroyed by each test, and reports a failure if a test leaks some Water
// objects. It does this by comparing the number of live Water objects at
// the beginning of a test and at the end of a test.
class LeakChecker : public EmptyTestEventListener {private:// Called before a test starts.void OnTestStart(const TestInfo& /* test_info */) override {initially_allocated_ = Water::allocated();}// Called after a test ends.void OnTestEnd(const TestInfo& /* test_info */) override {int difference = Water::allocated() - initially_allocated_;// You can generate a failure in any event handler except// OnTestPartResult. Just use an appropriate Google Test assertion to do// it.EXPECT_LE(difference, 0) << "Leaked " << difference << " unit(s) of Water!";}int initially_allocated_;
};TEST(ListenersTest, DoesNotLeak) {Water* water = new Water;delete water;
}// This should fail when the --check_for_leaks command line flag is
// specified.
TEST(ListenersTest, LeaksWater) {Water* water = new Water;EXPECT_TRUE(water != nullptr);
}
} // namespaceint main(int argc, char **argv) {InitGoogleTest(&argc, argv);bool check_for_leaks = false;if (argc > 1 && strcmp(argv[1], "--check_for_leaks") == 0 )check_for_leaks = true;elseprintf("%s\n", "Run this program with --check_for_leaks to enable ""custom leak checking in the tests.");// If we are given the --check_for_leaks command line flag, installs the// leak checker.if (check_for_leaks) {TestEventListeners& listeners = UnitTest::GetInstance()->listeners();// Adds the leak checker to the end of the test event listener list,// after the default text output printer and the default XML report// generator.//// The order is important - it ensures that failures generated in the// leak checker's OnTestEnd() method are processed by the text and XML// printers *before* their OnTestEnd() methods are called, such that// they are attributed to the right test. Remember that a listener// receives an OnXyzStart event *after* listeners preceding it in the// list received that event, and receives an OnXyzEnd event *before*// listeners preceding it.//// We don't need to worry about deleting the new listener later, as// Google Test will do it.listeners.Append(new LeakChecker);}return RUN_ALL_TESTS();
}
通过Water类来重写new和delete方法来实现记录内存分配/释放的情况,另外通过LeakChecker 继承自EmptyTestEventListener 并实现OnTestStart(测试用例开始前运行)和OnTestEnd方法(测试用例结束后运行)
关于LeakChecker的使用是先获取系统提供的listeners ,然后把自定义事件加入到系统中去即可。
TestEventListeners& listeners = UnitTest::GetInstance()->listeners();
listeners.Append(new LeakChecker);
相关文章:
Google单元测试sample分析(四)
GoogleTest单元测试可用实现在每个测试用例结束后监控其内存使用情况, 可以通过GoogleTest提供的事件侦听器EmptyTestEventListener 来实现,下面通过官方提供的sample例子,路径在samples文件夹下的sample10_unittest.cpp // Copyright 2009…...
网络套接字编程(二)
网络套接字编程(二) 文章目录 网络套接字编程(二)简易TCP网络程序服务端创建套接字服务端绑定IP地址和端口号服务端监听服务端运行服务端网络服务服务端启动客户端创建套接字客户端的绑定和监听问题客户端建立连接并通信客户端启动程序测试单执行流服务器的弊端 多进程版TCP网络…...
LLaMA-Adapter源码解析
LLaMA-Adapter源码解析 伪代码 def transformer_block_with_llama_adapter(x, gating_factor, soft_prompt):residual xy zero_init_attention(soft_prompt, x) # llama-adapter: prepend prefixx self_attention(x)x x gating_factor * y # llama-adapter: apply zero_init…...
JavaScript设计模式之发布-订阅模式
发布者和订阅者完全解耦(通过消息队列进行通信) 适用场景:功能模块间进行通信,如Vue的事件总线。 ES6实现方式: class eventManager {constructor() {this.eventList {};}on(eventName, callback) {if (this.eventL…...
mysql---索引
概要 索引:排序的列表,列表当中存储的是索引的值和包含这个值的数据所在的行的物理地址 作用:加快查找速度 注:索引要在创建表时尽量创建完全,后期添加影响变动大。 索引也需要占用磁盘空间,innodb表数据…...
微信小程序——简易复制文本
在微信小程序中,可以使用wx.setClipboardData()方法来实现复制文本内容的功能。以下是一个示例代码: // 点击按钮触发复制事件 copyText: function() {var that this;wx.setClipboardData({data: 要复制的文本内容,success: function(res) {wx.showToa…...
【51单片机】矩阵键盘与定时器(学习笔记)
一、矩阵键盘 1、矩阵键盘概述 在键盘中按键数量较多时,为了减少I/O口的占用,通常将按键排列成矩阵形式 采用逐行或逐列的“扫描”,就可以读出任何位置按键的状态 2、扫描的概念 数码管扫描(输出扫描):…...
vue 中使用async await
在程序中使用同步的方式来加载异步的数据的方式: async function() {let promise new Promise((resolve, reject) > {resolve(res);}).then(re > {return re; });await promise; }...
C语言学习之内存区域的划分
内存区域的划分:32位OS可以访问的虚拟内存空间为0~4G;一、内核空间:3~4G;二、用户空间0~3G;栈区:局部变量在栈区分配、由OS负责分配和回收堆区:由程序员手动分配(malloc函数)和回收(free函数);静…...
Unity Animator cpu性能测试
测试案例: 场景中共有4000个物体,挂在40个animtor 上,每个Animator控制100个物体的动画。 使用工具: Unity Profiler. Unity 版本: unity 2019.4.40f1 测试环境: 手机 测试过程: 没有挂…...
数据结构 - 顺序表ArrayList
目录 实现一个通用的顺序表 总结 包装类 装箱 / 装包 和 拆箱 / 拆包 ArrayList 与 顺序表 ArrayList基础功能演示 add 和 addAll ,添加元素功能 ArrayList的扩容机制 来看一下,下面的代码是否存在缺陷 模拟实现 ArrayList add 功能 add ind…...
【Echarts】玫瑰饼图数据交互
在学习echarts玫瑰饼图的过程中,了解到三种数据交互的方法,如果对您也有帮助,不胜欣喜。 一、官网教程 https://echarts.apache.org/examples/zh/editor.html?cpie-roseType-simple (该教程数据在代码中) import *…...
k8s、pod
Pod k8s中的port【端口:30000-32767】 port :为Service 在 cluster IP 上暴露的端口 targetPort:对应容器映射在 pod 端口上 nodePort:可以通过k8s 集群外部使用 node IP node port 访问Service containerPort:容…...
一天掌握python爬虫【基础篇】 涵盖 requests、beautifulsoup、selenium
大家好,我是python222小锋老师。前段时间卷了一套 Python3零基础7天入门实战 以及1小时掌握Python操作Mysql数据库之pymysql模块技术 近日锋哥又卷了一波课程,python爬虫【基础篇】 涵盖 requests、beautifulsoup、selenium,文字版视频版。1…...
睿趣科技:想知道开抖音小店的成本
随着互联网的发展,越来越多的人开始尝试通过开设网店来创业。抖音作为目前最受欢迎的短视频平台之一,也提供了开店的功能。那么,开一家抖音小店需要多少成本呢? 首先,我们需要了解的是,抖音小店的开店费用是…...
python项目部署代码汇总:目标检测类、人体姿态类
一、AI健身计数 1、图片视频检测 (cpu运行): 注:左上角为fps,左下角为次数统计。 1.哑铃弯举:12,14,16 详细环境安装教程:pyqt5AI健身CPU实时检测mediapipe 可视化界面…...
力扣每日一题92:反转链表||
题目描述: 给你单链表的头指针 head 和两个整数 left 和 right ,其中 left < right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。 示例 1: 输入:head [1,2,3,4,5], left 2, right 4 输…...
Vue+OpenLayers从入门到实战进阶案例汇总目录,兼容OpenLayers7和OpenLayers8
本篇作为《VueOpenLayers入门教程》和《VueOpenLayers实战进阶案例》所有文章的二合一汇总目录,方便查找。 本专栏源码是由OpenLayers结合Vue框架编写。 本专栏从Vue搭建脚手架到如何引入OpenLayers依赖的每一步详细新手教程,再到通过各种入门案例和综合…...
C#中使用LINQtoSQL管理SQL数据库之添加、修改和删除
目录 一、添加数据 二、修改数据 三、删除数据 四、添加、修改和删除的源码 五、生成效果 1.VS和SSMS原始记录 2.删除ID2和5的记录 3.添加记录ID2、5和8 4.修改ID3和ID4的记录 用LINQtoSQL管理SQL Server数据库时,主要有添加、修改和删除3种操作。 项目中创…...
飞致云及其旗下1Panel项目进入2023年第三季度最具成长性开源初创榜单
2023年10月26日,知名风险投资机构Runa Capital发布2023年第三季度ROSS指数(Runa Open Source Startup Index)。ROSS指数按季度汇总并公布在代码托管平台GitHub上年化增长率(AGR)排名前二十位的开源初创公司和开源项目。…...
(LeetCode 每日一题) 3442. 奇偶频次间的最大差值 I (哈希、字符串)
题目:3442. 奇偶频次间的最大差值 I 思路 :哈希,时间复杂度0(n)。 用哈希表来记录每个字符串中字符的分布情况,哈希表这里用数组即可实现。 C版本: class Solution { public:int maxDifference(string s) {int a[26]…...
Java如何权衡是使用无序的数组还是有序的数组
在 Java 中,选择有序数组还是无序数组取决于具体场景的性能需求与操作特点。以下是关键权衡因素及决策指南: ⚖️ 核心权衡维度 维度有序数组无序数组查询性能二分查找 O(log n) ✅线性扫描 O(n) ❌插入/删除需移位维护顺序 O(n) ❌直接操作尾部 O(1) ✅内存开销与无序数组相…...
在rocky linux 9.5上在线安装 docker
前面是指南,后面是日志 sudo dnf config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo sudo dnf install docker-ce docker-ce-cli containerd.io -y docker version sudo systemctl start docker sudo systemctl status docker …...
Spring AI与Spring Modulith核心技术解析
Spring AI核心架构解析 Spring AI(https://spring.io/projects/spring-ai)作为Spring生态中的AI集成框架,其核心设计理念是通过模块化架构降低AI应用的开发复杂度。与Python生态中的LangChain/LlamaIndex等工具类似,但特别为多语…...
云原生玩法三问:构建自定义开发环境
云原生玩法三问:构建自定义开发环境 引言 临时运维一个古董项目,无文档,无环境,无交接人,俗称三无。 运行设备的环境老,本地环境版本高,ssh不过去。正好最近对 腾讯出品的云原生 cnb 感兴趣&…...
return this;返回的是谁
一个审批系统的示例来演示责任链模式的实现。假设公司需要处理不同金额的采购申请,不同级别的经理有不同的审批权限: // 抽象处理者:审批者 abstract class Approver {protected Approver successor; // 下一个处理者// 设置下一个处理者pub…...
安宝特案例丨Vuzix AR智能眼镜集成专业软件,助力卢森堡医院药房转型,赢得辉瑞创新奖
在Vuzix M400 AR智能眼镜的助力下,卢森堡罗伯特舒曼医院(the Robert Schuman Hospitals, HRS)凭借在无菌制剂生产流程中引入增强现实技术(AR)创新项目,荣获了2024年6月7日由卢森堡医院药剂师协会࿰…...
纯 Java 项目(非 SpringBoot)集成 Mybatis-Plus 和 Mybatis-Plus-Join
纯 Java 项目(非 SpringBoot)集成 Mybatis-Plus 和 Mybatis-Plus-Join 1、依赖1.1、依赖版本1.2、pom.xml 2、代码2.1、SqlSession 构造器2.2、MybatisPlus代码生成器2.3、获取 config.yml 配置2.3.1、config.yml2.3.2、项目配置类 2.4、ftl 模板2.4.1、…...
第7篇:中间件全链路监控与 SQL 性能分析实践
7.1 章节导读 在构建数据库中间件的过程中,可观测性 和 性能分析 是保障系统稳定性与可维护性的核心能力。 特别是在复杂分布式场景中,必须做到: 🔍 追踪每一条 SQL 的生命周期(从入口到数据库执行)&#…...
深入理解Optional:处理空指针异常
1. 使用Optional处理可能为空的集合 在Java开发中,集合判空是一个常见但容易出错的场景。传统方式虽然可行,但存在一些潜在问题: // 传统判空方式 if (!CollectionUtils.isEmpty(userInfoList)) {for (UserInfo userInfo : userInfoList) {…...
