Google单元测试sample分析(四)

news/2024/10/16 19:28:28/

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);


http://www.ppmy.cn/news/1188561.html

相关文章

Pytorch 猫狗识别案例

猫狗识别数据集https://download.csdn.net/download/Victor_Li_/88483483?spm1001.2014.3001.5501 训练集图片路径 测试集图片路径 训练代码如下 import torch import torchvision import matplotlib.pyplot as plt import torchvision.models as models import torch.nn as…

入门必学 | R语言for循环的常规应用

文章目录 何为判断语句在for循环中添加判断语句嵌套循环 在上一节中&#xff0c;我们介绍了迭代与for循环&#xff0c;并对for循环的结构与原理进行了深入的介绍。在这一节中&#xff0c;我们将分享for循环的常规应用&#xff0c;包括在其中加入判断语句与嵌套循环。 何为判断语…

【Azure】存储服务:Azure 的存储账户

文章目录 一、前提知识&#xff08;建议了解&#xff09;二、介绍 Azure 存储帐户三、使用 Microsoft Azure 门户创建存储帐户 一、前提知识&#xff08;建议了解&#xff09; 在每一个云厂商中&#xff0c;都有自身的云存储&#xff0c;也有根据不同功能进行区分的不同类型的…

软考 系统架构设计师系列知识点之设计模式(10)

接前一篇文章&#xff1a;软考 系统架构设计师系列知识点之设计模式&#xff08;9&#xff09; 所属章节&#xff1a; 老版&#xff08;第一版&#xff09;教材 第7章. 设计模式 第2节. 设计模式实例 相关试题 9. 某软件公司欲设计一款图像处理软件&#xff0c;帮助用户对拍…

idea的设置

1.设置搜索encoding,所有编码都给换为utf-8 安装插件 eval-reset插件 https://www.yuque.com/huanlema-pjnah/okuh3c/lvaoxt#m1pdA 设置活动模板,idea有两种方式集成tomcat,一种是右上角config配置本地tomcat,一种是插件,如果使用插件集成,则在maven,pom.xml里面加上tomcat…

rust - 理解 ToOwned trait

简介 ToOwned trait支持任意类型的转换,而Clone trait只支持&T 到 T 的转换.以下先介绍一下基本的定义,最后通过一个简单的例子详细理解一下Borrow trait和ToOwned trait的互相转换的过程. 定义 可以将任意类型T转换为U类型,其中U类型实现了Borrow<T> trait, T: …

标题:轻松转换GIF到JPG,批量处理图片,优化你的图片管理!

作为一位设计师或社交媒体工作者&#xff0c;您可能经常需要处理大量的动图或GIF文件。这些GIF文件可能需要进行格式转换&#xff0c;以便更好地满足您的需求。现在&#xff0c;我们向您介绍一款轻松转换GIF到JPG的工具&#xff0c;帮助您更高效地管理您的图片库&#xff01; …

博弈论学习笔记(2)——完全信息静态博弈

前言 这部分我们学习的是完全信息静态博弈&#xff0c;主要内容包括博弈论的基本概念、战略式博弈、Nash均衡、Nash均衡解的特性、以及Nash均衡的应用。 零、绪论 1、什么是博弈论 1&#xff09;博弈的定义 博弈论&#xff1a;研究决策主体的行为发生直接相互作用时候的决策…