20181111-hight-property-codes
Posted deepindeed
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了20181111-hight-property-codes相关的知识,希望对你有一定的参考价值。
layout | title | categories | tags | date | description | |||
---|---|---|---|---|---|---|---|---|
post | 《高质量的C++代码笔记》 |
|
| 2018-11-11 12:59:59 -0800 | 软件质量是被大多数程序员挂在嘴上而不是放在心上的东西!有多少软件开发人员对正确性、健壮性、可靠性、效率、易用性、可读性(可理解性)、可扩展性、可复用性、兼容性、可移植性等质量属性了如指掌?并且能在实践中运用自如?。 |
引言
软件质量是被大多数程序员挂在嘴上而不是放在心上的东西! 除了完全外行和真正的编程高手外,初读本书,你最先的感受将是惊慌:“哇!我 以前捏造的 C++/C 程序怎么会有那么多的毛病?”有多少软件开发人员对正确性、健壮性、可靠性、效率、易用性、可读性(可理解性)、可扩展性、可复用性、兼容性、可移植性等质量属性了如指掌?并且能在实践中运用自如?。至少我现在还不是,我只能将平时遇到的一些值得记录的东西记录下来,以供下次翻阅。
从小程序看问题
strcpy
的实现可以看出一个人的
- 编程风格
- 出错处理
- 算法复杂度分析
char* strcpy(char* dest, const char* source)
char * destcopy = dest;
if((dest == NULL) || (source == NULL))
throw "Invalid Arguments";
while((*dest++=*source++)!= '\\0');
return destcopy;
文件结构
- 声明在头文件.h,定义在源代码文件.cpp或者.c .cc
- 为了防止头文件被重复引用,应当用 ifndef/define/endif 结构产生预 处理块。
- 用 #include <filename.h> 格式来引用标准库的头文件(编译器将 从标准库目录开始搜索)。用 #include “filename.h” 格式来引用非标准库的头文件(编译器将从用户的工作目录开始搜索)。 �4. 头文件中只存放“声明”而不存放“定义”
- 不提倡使用全局变量, 尽量不要在头文件中出现象 extern int value 这 类声明。
/*
* Copyright (c) 2001,上海贝尔有限公司网络应用事业部
* All rights reserved.
*
* 文件名称: filename.h
* 文件标识: 见配置管理计划书
* 摘 要: 简要描述本文件的内容
*
* 当前版本: 1.1
* 作 者: 输入作者(或修改者)名字
* 完成日期: 2001年7月20日
*
* 取代版本: 1.0
* 原作者 : 输入原作者(或修改者)名字
* 完成日期: 2001年5月10日
*/
为什么要声明和定义分离:
- 通过头文件来调用库功能。在很多场合,源代码不便(或不准)向用户公布,只 要向用户提供头文件和二进制的库即可。用户只需要按照头文件中的接口声明来调用库 功能,而不必关心接口怎么实现的。编译器会从库中提取相应的代码。
- 头文件能加强类型安全检查。如果某个接口被实现或被使用时,其方式与头文件 中的声明不一致,编译器就会指出错误,这一简单的规则能大大减轻程序员调试、改错 的负担。
- 便于管理。如果代码文件比较多,可以将头文件放到include目录下,源文件放到source目录下,方便分别管理
程序
- 在每个类声明之后、每个函数定义结束之后都要加空行
- 在一个函数体内,逻揖上密切相关的语句之间不加空行,其它地方应 加空行分隔。
- 一行代码只做一件事情,如只定义一个变量,或只写一条语句。
- if、 for、 while、 do 等语句自占一行,执行语句不得紧跟其后。不论 执行语句有多少都要加。这样可以防止书写失误。
- 尽可能在定义变量的同时初始化该变量。如果变量的引用处和其定义处相隔比较远,变量的初始化很容易被忘记。如果引用了未被初始化的变量,可能会导致程序错误。本建议可以减少隐患。
指针声明
修饰符 * 和 & 应该靠近数据类型还是该靠近变量名,是个有争议的活题。 若将修饰符 * 靠近数据类型,例如: int* x; 从语义上讲此写法比较直观,即 x 是 int 类型的指针。 上述写法的弊端是容易引起误解,例如: int* x, y; 此处 y 容易被误解为指针变 量。虽然将 x 和 y 分行定义可以避免误解,但并不是人人都愿意这样做。
命名规则
unix系统中常常采用小写字母+_ 的方式 g_:全局变量 k_:static 变量 m_:class成员变量
类的构造函数、析构函数和赋值函数
每个类只有一个析构函数和一个赋值函数,但可以有多个构造函数(包含一个拷贝 构造函数,其它的称为普通构造函数)。对于任意一个类 A,如果不想编写上述函数, C++编译器将自动为 A 产生四个缺省的函数,如 A(void);
// 缺省的无参数构造函数 A(const A &a);
// 缺省的拷贝构造函数 ~A(void);
// 缺省的析构函数 A & operate =(const A &a);
// 缺省的赋值函数
经验
不少难以察觉的程序错误是由于变量没有被正确初始化或清除造成的,而初始化和清除工作很容易被人遗忘。
调试经典
#define stub fprintf(stderr, "error param in %s:%s:%d\\n", __FUNCTION__, __FILE__, __LINE__);
mutable关键字用来解决常函数中不能修改对象的数据成员的问题
内存对齐
这是因为结构体内存分配有自己的对齐规则,结构体内存对齐默认的规则如下:
- 分配内存的顺序是按照声明的顺序。
- 每个变量相对于起始位置的偏移量必须是该变量类型大小的整数倍,不是整数倍空出内存,直到偏移量是整数倍为止。
- 最后整个结构体的大小必须是里面变量类型最大值的整数倍。
内存对齐https://www.cnblogs.com/suntp/p/MemAlignment.html
OpenCV中16b对齐的内存申请和释放
#define CV_MALLOC_ALIGN 16
/*!
Aligns pointer by the certain number of bytes
This small inline function aligns the pointer by the certian number of bytes by shifting
it forward by 0 or a positive offset.
*/
template <typename _Tp>
static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp))
return (_Tp*)(((size_t)ptr + n-1) & -n);
/*!
Aligns buffer size by the certain number of bytes
This small inline function aligns a buffer size by the certian number of bytes by enlarging it.
*/
static inline size_t alignSize(size_t sz, int n)
assert((n & (n - 1)) == 0); // n is a power of 2
return (sz + n-1) & -n;
void* fastMalloc( size_t size )
uchar* udata = (uchar*)malloc(size + sizeof(void*) + CV_MALLOC_ALIGN);
if(!udata)
return OutOfMemoryError(size);
uchar** adata = alignPtr((uchar**)udata + 1, CV_MALLOC_ALIGN);
adata[-1] = udata;
return adata;
void fastFree(void* ptr)
if(ptr)
uchar* udata = ((uchar**)ptr)[-1];
CV_DbgAssert(udata < (uchar*)ptr &&
((uchar*)ptr - udata) <= (ptrdiff_t)(sizeof(void*)+CV_MALLOC_ALIGN));
free(udata);
内存的作用域,不要在函数中创建临时对象返回
#include <cstdio>
#include <cstring>
///@brief 模型配置结构体
///@warning 该结构体在与did_model_set_config一起使用时,一定要先全部填充为0,再设置所需要的field。
/// set_model_config/get_model_config 是对该结构体的浅拷贝
typedef struct net_config_t
int engine;
///@brief each engine specific data can be passed to here, such as snpe_runtime, tensorrt_batch_size, ocl_context and so on.
///@note each engine implementation will cast it to the corresponding runtime type, such as snpe_context_t, ppl_context_t.
/// The lifetime of this pointer should span until create_handle finished, and the memory is managed by users.
void* engine_context;
net_config_t;
void set_net_config_t(net_config_t* config, int engine_type)
memset(config, 0, sizeof(net_config_t));
int otherc[] = 1, 0, 5;
config->engine = engine_type;
config->engine_context = (void*)&otherc;
int main(int argc, char* argv[])
net_config_t config;
// 设置模型加载配置项
set_net_config_t(&config, 3);
fprintf(stderr, "config.engine %d\\n", config.engine);
int* context = (int*)config.engine_context;
fprintf(stderr, "config.engine_context[0]=%d\\n", context[0]);
fprintf(stderr, "config.engine_context[1]=%d\\n", context[1]);
fprintf(stderr, "config.engine_context[2]=%d\\n", context[2]);
return 0;
第一次运行
config.engine 3 config.engine_context[0]=1286489600 config.engine_context[1]=32624 config.engine_context[2]=1288667592
第二次运行
config.engine 3 config.engine_context[0]=-204200448 config.engine_context[1]=32695 config.engine_context[2]=-202022456
从结果中可以看出engine_context中的内存是一块未初始化的内存空间。这是因为返回的局部数组被释放导致的结果。 这情况可能导致你的程序有不期望的执行结果。尤其是如果采用context[1]作为分支判断条件,本来应该为0或者false, 现在可能是正数,也可能是负数,为0的概率非常小。因此我们要避免这种返回局部变量的情况。
Disable COPY和ASSIGN操作的方法, 将赋值函数和拷贝构造函数显示作为private下
方案 1
// A macro to disallow copy constructor and operator=
// This should be used in the private: declarations for a class.
#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\\
type(type const &);\\
void operator=(type const &)
class TestFactoryBase
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase);
方案2
class P
public:
P(const P &) = delete;
P &operator =(const P &p) = delete;
;
以上两个delete声明禁止复制 能够通过明确的方式显式限定这些特殊方法有助于增强代码的可读性和可维护性
++i和i++的重载代码实现
ClassName& operator++()
++cur;
if(cur == last)
set_node(node + 1);
cur = first;
return *this;
ClassName operator(int)
ClassName tmp = *this;
++*this;
return tmp;
unsigned类型的默认转化造成的苦恼
u32Width是unsigned int类型的,在进行计算过程中如果u32Width=2
,执行到for (; j <= u32Width - 4; j += 4)
的时候,会出现问题: 由于j是size_t类型的, u32Width-4
会被转化为unsigned int
类型,从而造成该判断可通过,从直观上看来就发生了 j <= -2
(实际是j <= 4294967294
)是为true
的事情了。
const unsigned int blob_len = u32Num * u32Chn * u32Height;
for (size_t i = 0; i < blob_len; ++i)
size_t j = 0;
for (; j <= u32Width - 4; j += 4)
dataDstBlob[j] = (dst_type)(ps32Ptr[j] * NNIE_DATA_SCALE_INV);
dataDstBlob[j + 1] = (dst_type)(ps32Ptr[j + 1] * NNIE_DATA_SCALE_INV);
dataDstBlob[j + 2] = (dst_type)(ps32Ptr[j + 2] * NNIE_DATA_SCALE_INV);
dataDstBlob[j + 3] = (dst_type)(ps32Ptr[j + 3] * NNIE_DATA_SCALE_INV);
for (; j < u32Width; ++j)
dataDstBlob[j] = (dst_type)(ps32Ptr[j] * NNIE_DATA_SCALE_INV);
dataDstBlob += u32Width;
ps32Ptr += blob->u32Stride / getElemSize(blob->enType);
C++中容易忽略的库bitset
bitset是处理进制转换,基于bit的算法中简单算法,虽然也可以使用raw的char array替代,但是很多bitset自带的方法,可以让程序飞起来。
#include <iostream>
#include <bitset>
using namespace std;
void increment(std::bitset<5>& bset)
for (int i = 0; i < 5; ++i)
if(bset[i] == 1)
bset[i] = 0;
else
bset[i] = 1;
break;
void method_1()
for (int i = 0; i < 32; ++i)
std::bitset<5> bset(i);
std::cout << bset << std::endl;
int main(int argc, char const *argv[])
std::bitset<5> bset(0);
for (int i = 0; i < 32; ++i)
std::cout << bset << std::endl;
increment(bset);
return 0;
仿函数
仿函数(functor),就是使一个类的使用看上去象一个函数。其实现就是类中实现一个 operator(),这个类就有了类似函数的行为,就是一个仿函数类了。C语言使用函数指针和回调函数来实现仿函数,例如一个用来排序的函数可以这样使用仿函数.在C++里,我们通过在一个类中重载括号运算符的方法使用一个函数对象而不是一个普通函数。
template <typename T>
struct xxx
returnType operator()(const T& x)
return returnType;
template<typename T>
class display
public:
void operator()(const T &x)
cout<<x<<" ";
;
#include <stdio.h>
#include <stdlib.h>
//int sort_function( const void *a, const void *b);
int sort_function( const void *a, const void *b)
return *(int*)a-*(int*)b;
int main()
int list[5] = 54, 21, 11, 67, 22 ;
qsort((void *)list, 5, sizeof(list[0]), sort_function);//起始地址,个数,元素大小,回调函数
int x;
for (x = 0; x < 5; x++)
printf("%i\\n", list[x]);
return 0;
仿函数在STL中的定义
要使用STL内建的仿函数,必须包含头文件。而头文件中包含的仿函数分类包括
- 算术类仿函数 加:plus 减:minus 乘:multiplies 除:divides 模取:modulus 否定:negate
#include <iostream>
#include <numeric>
#include <vector>
#include <functional>
using namespace std;
int main()
int ia[]=1,2,3,4,5;
vector<int> iv(ia,ia+5);
cout<<accumulate(iv.begin(),iv.end(),1,multiplies<int>())<<endl;
cout<<multiplies<int>()(3,5)<<endl;
modulus<int> modulusObj;
cout<<modulusObj(3,5)<<endl; // 3
return 0;
- 关系运算类仿函数
等于:equal_to 不等于:not_equal_to 大于:greater 大于等于:greater_equal 小于:less 小于等于:less_equal
从大到小排序:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
template <class T>
class display
public:
void operator()(const T &x)
cout<<x<<" ";
;
int main()
int ia[]=1,5,4,3,2;
vector<int> iv(ia,ia+5);
sort(iv.begin(),iv.end(),greater<int>());
for_each(iv.begin(),iv.end(),display<int>());
return 0;
- 逻辑运算仿函数
逻辑与:logical_and 逻辑或:logical_or 逻辑否:logical_no
google test的一些疑问:TEST_F与TEST的区别
TEST_F与TEST的区别是,TEST_F提供了一个初始化函数(SetUp)和一个清理函数(TearDown),在TEST_F中使用的变量可以在初始化函数SetUp中初始化,在TearDown中销毁,并且所有的TEST_F是互相独立的,都是在初始化以后的状态开始运行,一个TEST_F不会影响另一个TEST_F所使用的数据。
//A.h
#ifndef A_H
#define A_H
class A
private:
int _a;
public:
A( int a );
~A( );
void add( int a );
int getA( );
;
#endif
A.cpp
#include "A.h"
A::A( int a )
this->_a = a;
A::~A( )
void A::add( int a )
this->_a += a;
int A::getA( )
return this->_a;
- A_test.cpp
// A_test.cpp
#include "A.h"
#include <gtest/gtest.h>
class A_test : public testing::Test
protected:
A* _p_a;
virtual void SetUp( ) //初始化函数
this->_p_a = new A( 1 );
virtual void TearDown( ) //清理函数
delete this->_p_a;
;
//第一个测试,参数A_test是上面的那个类,第二个参数FirstAdd是测试名称
TEST_F( A_test,FirstAdd )
EXPECT_EQ( 1,_p_a->getA( ) );
_p_a->add( 3 );
EXPECT_EQ( 4,_p_a->getA( ) );
//第二个测试
TEST_F( A_test,SecondAdd )
EXPECT_EQ( 1,_p_a->getA( ) );
_p_a->add( 5 );
EXPECT_EQ( 6,_p_a->getA( ) );
/*
上面的两个测试都是在SetUp函数执行后的状态下执行,也就是说在执行任意一个TEST_F时 _p_a->_a 的值都是初始值1
*/
- main.cpp
#include <gtest/gtest.h>
int main(int argc, char * argv[])
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
#define __TIC__() \\
struct timeval __timing_start, __timing_end; \\
gettimeofday(&__timing_start, NULL);
#define __TOC__() \\
do \\
gettimeofday(&__timing_end, NULL); \\
double __timing_gap = (__timing_end.tv_sec - \\
__timing_start.tv_sec) * \\
1000.0 + \\
(__timing_end.tv_usec - \\
__timing_start.tv_usec) / \\
1000.0; \\
fprintf(stdout, "TIME(ms): %lf\\n", __timing_gap); \\
while (0)
看看gtest的工作流程
- 入口
//第一个测试,参数A_test是上面的那个类,第二个参数FirstAdd是测试名称
TEST(A_test, FirstAdd)
EXPECT_EQ( 1,_p_a->getA( ) );
_p_a->add( 3 );
EXPECT_EQ( 4,_p_a->getA( ) );
// Define this macro to 1 to omit the definition of TEST(), which
// is a generic name and clashes with some other libraries.
#if !GTEST_DONT_DEFINE_TEST
# define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name)
#endif
#define GTEST_TEST(test_case_name, test_name)\\
GTEST_TEST_(test_case_name, test_name, \\
::testing::Test, ::testing::internal::GetTestTypeId())
- 首先看看函数中调用的一个宏的实现
// Expands to the name of the class that implements the given test.
#define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \\
test_case_name##_##test_name##_Test
// Helper macro for defining tests.
// 这个宏声明了一个继承自parent_class ::testing::Test的类,然后对这个类的属性test_info_进行赋值
#define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id)\\
class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class \\
public:\\
GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() \\
private:\\
virtual void TestBody();\\
static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;\\
GTEST_DISALLOW_COPY_AND_ASSIGN_(\\
GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\\
;\\
/*这个宏声明了一个继承自parent_class ::testing::Test的类,然后对这个类的属性test_info_进行赋值*/\\
::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)\\
::test_info_ =\\
::testing::internal::MakeAndRegisterTestInfo(\\
#test_case_name, #test_name, NULL, NULL, \\
(parent_id), \\
parent_class::SetUpTestCase, \\
parent_class::TearDownTestCase, \\
new ::testing::internal::TestFactoryImpl<\\
GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>);\\
// 实现我们的这个TestBody\\
void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody()
- 看一下MakeAndRegisterTestInfo函数
TestInfo* MakeAndRegisterTestInfo(
const char* test_case_name,
const char* name,
const char* type_param,
const char* value_param,
TypeId fixture_class_id,
SetUpTestCaseFunc set_up_tc,
TearDownTestCaseFunc tear_down_tc,
TestFactoryBase* factory)
TestInfo* const test_info =
new TestInfo(test_case_name, name, type_param, value_param,
fixture_class_id, factory);
// 添加测试用例信息到UnitTestImpl的testcase_中
GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
return test_info;
- AddTestInfo试图通过测试用例名等信息获取测试用例,然后调用测试用例对象去新增一个测试特例——test_info。 这样我们在此就将测试用例和测试特例的关系在代码中找到了关联。
// Finds and returns a TestCase with the given name. If one doesn't
// exist, creates one and returns it. It's the CALLER'S
// RESPONSIBILITY to ensure that this function is only called WHEN THE
// TESTS ARE NOT SHUFFLED.
//
// Arguments:
//
// test_case_name: name of the test case
// type_param: the name of the test case's type parameter, or NULL if
// this is not a typed or a type-parameterized test case.
// set_up_tc: pointer to the function that sets up the test case
// tear_down_tc: pointer to the function that tears down the test case
TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
const char* type_param,
Test::SetUpTestCaseFunc set_up_tc,
Test::TearDownTestCaseFunc tear_down_tc)
// Can we find a TestCase with the given name?
const std::vector<TestCase*>::const_iterator test_case =
std::find_if(test_cases_.begin(), test_cases_.end(),
TestCaseNameIs(test_case_name));
if (test_case != test_cases_.end())
return *test_case;
// No. Let's create one.
TestCase* const new_test_case =
new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
// Is this a death test case?
if (internal::UnitTestOptions::MatchesFilter(test_case_name,
kDeathTestCaseFilter))
// Yes. Inserts the test case after the last death test case
// defined so far. This only works when the test cases haven't
// been shuffled. Otherwise we may end up running a death test
// after a non-death test.
++last_death_test_case_;
test_cases_.insert(test_cases_.begin() + last_death_test_case_,
new_test_case);
else
// No. Appends to the end of the list.
test_cases_.push_back(new_test_case);
test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
return new_test_case;
Reference
- [1]. gtest测试相关: http://blog.csdn.net/breaksoftware/article/details/50948239
- [2]. Floating-Point Arithmetic 浮点数结构
来自GTEST文档中的内容,方便后续查看
Introduction: Why Google C++ Testing Framework?
Google C++ Testing Framework helps you write better C++ tests.
No matter whether you work on Linux, Windows, or a Mac, if you write C++ code, Google Test can help you.
So what makes a good test, and how does Google C++ Testing Framework fit in? We believe:
- Tests should be independent and repeatable. It's a pain to debug a test that succeeds or fails as a result of other tests. Google C++ Testing Framework isolates the tests by running each of them on a different object. When a test fails, Google C++ Testing Framework allows you to run it in isolation for quick debugging.
- Tests should be well organized and reflect the structure of the tested code. Google C++ Testing Framework groups related tests into test cases that can share data and subroutines. This common pattern is easy to recognize and makes tests easy to maintain. Such consistency is especially helpful when people switch projects and start to work on a new code base.
- Tests should be portable and reusable. The open-source community has a lot of code that is platform-neutral, its tests should also be platform-neutral. Google C++ Testing Framework works on different OSes, with different compilers (gcc, MSVC, and others), with or without exceptions, so Google C++ Testing Framework tests can easily work with a variety of configurations. (Note that the current release only contains build scripts for Linux - we are actively working on scripts for other platforms.)
- When tests fail, they should provide as much information about the problem as possible. Google C++ Testing Framework doesn't stop at the first test failure. Instead, it only stops the current test and continues with the next. You can also set up tests that report non-fatal failures after which the current test continues. Thus, you can detect and fix multiple bugs in a single run-edit-compile cycle.
- The testing framework should liberate test writers from housekeeping chores and let them focus on the test content. Google C++ Testing Framework automatically keeps track of all tests defined, and doesn't require the user to enumerate them in order to run them.
- Tests should be fast. With Google C++ Testing Framework, you can reuse shared resources across tests and pay for the set-up/tear-down only once, without making tests depend on each other.
Since Google C++ Testing Framework is based on the popular xUnit architecture, you'll feel right at home if you've used JUnit or PyUnit before. If not, it will take you about 10 minutes to learn the basics and get started. So let's go!
Note: We sometimes refer to Google C++ Testing Framework informally as Google Test.
Setting up a New Test Project
To write a test program using Google Test, you need to compile Google Test into a library and link your test with it. We provide build files for some popular build systems: msvc/
for Visual Studio, xcode/
for Mac Xcode, make/
for GNU make, codegear/
for Borland C++ Builder, and the autotools script (deprecated) and CMakeLists.txt
for CMake (recommended) in the Google Test root directory. If your build system is not on this list, you can take a look at make/Makefile
to learn how Google Test should be compiled (basically you want to compile src/gtest-all.cc
with GTEST_ROOT
and GTEST_ROOT/include
in the header search path, where GTEST_ROOT
is the Google Test root directory).
Once you are able to compile the Google Test library, you should create a project or build target for your test program. Make sure you have GTEST_ROOT/include
in the header search path so that the compiler can find "gtest/gtest.h"
when compiling your test. Set up your test project to link with the Google Test library (for example, in Visual Studio, this is done by adding a dependency on gtest.vcproj
).
If you still have questions, take a look at how Google Test's own tests are built and use them as examples.
Basic Concepts
When using Google Test, you start by writing assertions, which are statements that check whether a condition is true. An assertion's result can be success, nonfatal failure, or fatal failure. If a fatal failure occurs, it aborts the current function; otherwise the program continues normally.
Tests use assertions to verify the tested code's behavior. If a test crashes or has a failed assertion, then it fails; otherwise it succeeds.
A test case contains one or many tests. You should group your tests into test cases that reflect the structure of the tested code. When multiple tests in a test case need to share common objects and subroutines, you can put them into a test fixture class.
A test program can contain multiple test cases.
We'll now explain how to write a test program, starting at the individual assertion level and building up to tests and test cases.
Assertions
Google Test assertions are macros that resemble function calls. You test a class or function by making assertions about its behavior. When an assertion fails, Google Test prints the assertion's source file and line number location, along with a failure message. You may also supply a custom failure message which will be appended to Google Test's message.
The assertions come in pairs that test the same thing but have different effects on the current function. ASSERT_*
versions generate fatal failures when they fail, and abort the current function. EXPECT_*
versions generate nonfatal failures, which don't abort the current function. Usually EXPECT_*
are preferred, as they allow more than one failures to be reported in a test. However, you should use ASSERT_*
if it doesn't make sense to continue when the assertion in question fails.
Since a failed ASSERT_*
returns from the current function immediately, possibly skipping clean-up code that comes after it, it may cause a space leak. Depending on the nature of the leak, it may or may not be worth fixing - so keep this in mind if you get a heap checker error in addition to assertion errors.
To provide a custom failure message, simply stream it into the macro using the <<
operator, or a sequence of such operators. An example:
ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length";
for (int i = 0; i < x.size(); ++i)
EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i;
Anything that can be streamed to an ostream
can be streamed to an assertion macro--in particular, C strings and string
objects. If a wide string (wchar_t*
, TCHAR*
in UNICODE
mode on Windows, or std::wstring
) is streamed to an assertion, it will be translated to UTF-8 when printed.
Basic Assertions
These assertions do basic true/false condition testing.
Fatal assertion | Nonfatal assertion | Verifies |
---|---|---|
ASSERT_TRUE( condition) ; | EXPECT_TRUE( condition) ; | condition is true |
ASSERT_FALSE( condition) ; | EXPECT_FALSE( condition) ; | condition is false |
Remember, when they fail, ASSERT_*
yields a fatal failure and returns from the current function, while EXPECT_*
yields a nonfatal failure, allowing the function to continue running. In either case, an assertion failure means its containing test fails.
Availability: Linux, Windows, Mac.
Binary Comparison
This section describes assertions that compare two values.
Fatal assertion | Nonfatal assertion | Verifies |
---|---|---|
ASSERT_EQ( val1, val2); | EXPECT_EQ( val1, val2); | val1 == val2 |
ASSERT_NE( val1, val2); | EXPECT_NE( val1, val2); | val1 != val2 |
ASSERT_LT( val1, val2); | EXPECT_LT( val1, val2); | val1 < val2 |
ASSERT_LE( val1, val2); | EXPECT_LE( val1, val2); | val1 <= val2 |
ASSERT_GT( val1, val2); | EXPECT_GT( val1, val2); | val1 > val2 |
ASSERT_GE( val1, val2); | EXPECT_GE( val1, val2); | val1 >= val2 |
In the event of a failure, Google Test prints both val1 and val2.
Value arguments must be comparable by the assertion's comparison operator or you'll get a compiler error. We used to require the arguments to support the <<
operator for streaming to an ostream
, but it's no longer necessary since v1.6.0 (if <<
is supported, it will be called to print the arguments when the assertion fails; otherwise Google Test will attempt to print them in the best way it can. For more details and how to customize the printing of the arguments, see this Google Mock recipe.).
These assertions can work with a user-defined type, but only if you define the corresponding comparison operator (e.g. ==
, <
, etc). If the corresponding operator is defined, prefer using the ASSERT_*()
macros because they will print out not only the result of the comparison, but the two operands as well.
Arguments are always evaluated exactly once. Therefore, it's OK for the arguments to have side effects. However, as with any ordinary C/C++ function, the arguments' evaluation order is undefined (i.e. the compiler is free to choose any order) and your code should not depend on any particular argument evaluation order.
ASSERT_EQ()
does pointer equality on pointers. If used on two C strings, it tests if they are in the same memory location, not if they have the same value. Therefore, if you want to compare C strings (e.g. const char*
) by value, use ASSERT_STREQ()
, which will be described later on. In particular, to assert that a C string is NULL
, use ASSERT_STREQ(NULL, c_string)
. However, to compare two string
objects, you should use ASSERT_EQ
.
Macros in this section work with both narrow and wide string objects (string
and wstring
).
Availability: Linux, Windows, Mac.
Historical note: Before February 2016 *_EQ
had a convention of calling it as ASSERT_EQ(expected, actual)
, so lots of existing code uses this order. Now *_EQ
treats both parameters in the same way.
String Comparison
The assertions in this group compare two C strings. If you want to compare two string
objects, use EXPECT_EQ
, EXPECT_NE
, and etc instead.
Fatal assertion | Nonfatal assertion | Verifies |
---|---|---|
ASSERT_STREQ( str1, str2); | EXPECT_STREQ( str1, _str_2); | the two C strings have the same content |
ASSERT_STRNE( str1, str2); | EXPECT_STRNE( str1, str2); | the two C strings have different content |
ASSERT_STRCASEEQ( str1, str2); | EXPECT_STRCASEEQ( str1, str2); | the two C strings have the same content, ignoring case |
ASSERT_STRCASENE( str1, str2); | EXPECT_STRCASENE( str1, str2); | the two C strings have different content, ignoring case |
Note that "CASE" in an assertion name means that case is ignored.
*STREQ*
and *STRNE*
also accept wide C strings (wchar_t*
). If a comparison of two wide strings fails, their values will be printed as UTF-8 narrow strings.
A NULL
pointer and an empty string are considered different.
Availability: Linux, Windows, Mac.
See also: For more string comparison tricks (substring, prefix, suffix, and regular expression matching, for example), see the Advanced Google Test Guide.
Simple Tests
To create a test:
- Use the
TEST()
macro to define and name a test function, These are ordinary C++ functions that don't return a value. - In this function, along with any valid C++ statements you want to include, use the various Google Test assertions to check values.
- The test's result is determined by the assertions; if any assertion in the test fails (either fatally or non-fatally), or if the test crashes, the entire test fails. Otherwise, it succeeds.
TEST(test_case_name, test_name)
... test body ...
TEST()
arguments go from general to specific. The first argument is the name of the test case, and the second argument is the test's name within the test case. Both names must be valid C++ identifiers, and they should not contain underscore (_
). A test's full name consists of its containing test case and its individual name. Tests from different test cases can have the same individual name.
For example, let's take a simple integer function:
int Factorial(int n); // Returns the factorial of n
A test case for this function might look like:
// Tests factorial of 0.
TEST(FactorialTest, HandlesZeroInput)
EXPECT_EQ(1, Factorial(0));
// Tests factorial of positive numbers.
TEST(FactorialTest, HandlesPositiveInput)
EXPECT_EQ(1, Factorial(1));
EXPECT_EQ(2, Factorial(2));
EXPECT_EQ(6, Factorial(3));
EXPECT_EQ(40320, Factorial(8));
Google Test groups the test results by test cases, so logically-related tests should be in the same test case; in other words, the first argument to their TEST()
should be the same. In the above example, we have two tests, HandlesZeroInput
and HandlesPositiveInput
, that belong to the same test case FactorialTest
.
Availability: Linux, Windows, Mac.
Test Fixtures: Using the Same Data Configuration for Multiple Tests
If you find yourself writing two or more tests that operate on similar data, you can use a test fixture. It allows you to reuse the same configuration of objects for several different tests.
To create a fixture, just:
- Derive a class from
::testing::Test
. Start its body withprotected:
orpublic:
as we'll want to access fixture members from sub-classes. - Inside the class, declare any objects you plan to use.
- If necessary, write a default constructor or
SetUp()
function to prepare the objects for each test. A common mistake is to spellSetUp()
asSetup()
with a smallu
- don't let that happen to you. - If necessary, write a destructor or
TearDown()
function to release any resources you allocated inSetUp()
. To learn when you should use the constructor/destructor and when you should useSetUp()/TearDown()
, read this FAQ entry. - If needed, define subroutines for your tests to share.
When using a fixture, use TEST_F()
instead of TEST()
as it allows you to access objects and subroutines in the test fixture:
TEST_F(test_case_name, test_name)
... test body ...
Like TEST()
, the first argument is the test case name, but for TEST_F()
this must be the name of the test fixture class. You've probably guessed: _F
is for fixture.
Unfortunately, the C++ macro system does not allow us to create a single macro that can handle both types of tests. Using the wrong macro causes a compiler error.
Also, you must first define a test fixture class before using it in a TEST_F()
, or you'll get the compiler error "virtual outside class declaration
".
For each test defined with TEST_F()
, Google Test will:
- Create a fresh test fixture at runtime
- Immediately initialize it via
SetUp()
, - Run the test
- Clean up by calling
TearDown()
- Delete the test fixture. Note that different tests in the same test case have different test fixture objects, and Google Test always deletes a test fixture before it creates the next one. Google Test does not reuse the same test fixture for multiple tests. Any changes one test makes to the fixture do not affect other tests.
As an example, let's write tests for a FIFO queue class named Queue
, which has the following interface:
template <typename E> // E is the element type.
class Queue
public:
Queue();
void Enqueue(const E& element);
E* Dequeue(); // Returns NULL if the queue is empty.
size_t size() const;
...
;
First, define a fixture class. By convention, you should give it the name FooTest
where Foo
is the class being tested.
class QueueTest : public ::testing::Test
protected:
virtual void SetUp()
q1_.Enqueue(1);
q2_.Enqueue(2);
q2_.Enqueue(3);
// virtual void TearDown()
Queue<int> q0_;
Queue<int> q1_;
Queue<int> q2_;
;
In this case, TearDown()
is not needed since we don't have to clean up after each test, other than what's already done by the destructor.
Now we'll write tests using TEST_F()
and this fixture.
TEST_F(QueueTest, IsEmptyInitially)
EXPECT_EQ(0, q0_.size());
TEST_F(QueueTest, DequeueWorks)
int* n = q0_.Dequeue();
EXPECT_EQ(NULL, n);
n = q1_.Dequeue();
ASSERT_TRUE(n != NULL);
EXPECT_EQ(1, *n);
EXPECT_EQ(0, q1_.size());
delete n;
n = q2_.Dequeue();
ASSERT_TRUE(n != NULL);
EXPECT_EQ(2, *n);
EXPECT_EQ(1, q2_.size());
delete n;
The above uses both ASSERT_*
and EXPECT_*
assertions. The rule of thumb is to use EXPECT_*
when you want the test to continue to reveal more errors after the assertion failure, and use ASSERT_*
when continuing after failure doesn't make sense. For example, the second assertion in the Dequeue
test is ASSERT_TRUE(n != NULL)
, as we need to dereference the pointer n
later, which would lead to a segfault when n
is NULL
.
When these tests run, the following happens:
- Google Test constructs a
QueueTest
object (let's call itt1
). t1.SetUp()
initializest1
.- The first test (
IsEmptyInitially
) runs ont1
. t1.TearDown()
cleans up after the test finishes.t1
is destructed.- The above steps are repeated on another
QueueTest
object, this time running theDequeueWorks
test.
Availability: Linux, Windows, Mac.
Note: Google Test automatically saves all Google Test flags when a test object is constructed, and restores them when it is destructed.
Invoking the Tests
TEST()
and TEST_F()
implicitly register their tests with Google Test. So, unlike with many other C++ testing frameworks, you don't have to re-list all your defined tests in order to run them.
After defining your tests, you can run them with RUN_ALL_TESTS()
, which returns 0
if all the tests are successful, or 1
otherwise. Note that RUN_ALL_TESTS()
runs all tests in your link unit -- they can be from different test cases, or even different source files.
When invoked, the RUN_ALL_TESTS()
macro:
- Saves the state of all Google Test flags.
- Creates a test fixture object for the first test.
- Initializes it via
SetUp()
. - Runs the test on the fixture object.
- Cleans up the fixture via
TearDown()
. - Deletes the fixture.
- Restores the state of all Google Test flags.
- Repeats the above steps for the next test, until all tests have run.
In addition, if the text fixture's constructor generates a fatal failure in step 2, there is no point for step 3 - 5 and they are thus skipped. Similarly, if step 3 generates a fatal failure, step 4 will be skipped.
Important: You must not ignore the return value of RUN_ALL_TESTS()
, or gcc
will give you a compiler error. The rationale for this design is that the automated testing service determines whether a test has passed based on its exit code, not on its stdout/stderr output; thus your main()
function must return the value of RUN_ALL_TESTS()
.
Also, you should call RUN_ALL_TESTS()
only once. Calling it more than once conflicts with some advanced Google Test features (e.g. thread-safe death tests) and thus is not supported.
Availability: Linux, Windows, Mac.
Writing the main() Function
You can start from this boilerplate:
#include "this/package/foo.h"
#include "gtest/gtest.h"
namespace
// The fixture for testing class Foo.
class FooTest : public ::testing::Test
protected:
// You can remove any or all of the following functions if its body
// is empty.
FooTest()
// You can do set-up work for each test here.
virtual ~FooTest()
// You can do clean-up work that doesn't throw exceptions here.
// If the constructor and destructor are not enough for setting up
// and cleaning up each test, you can define the following methods:
virtual void SetUp()
// Code here will be called immediately after the constructor (right
// before each test).
virtual void TearDown()
// Code here will be called immediately after each test (right
// before the destructor).
// Objects declared here can be used by all tests in the test case for Foo.
;
// Tests that the Foo::Bar() method does Abc.
TEST_F(FooTest, MethodBarDoesAbc)
const string input_filepath = "this/package/testdata/myinputfile.dat";
const string output_filepath = "this/package/testdata/myoutputfile.dat";
Foo f;
EXPECT_EQ(0, f.Bar(input_filepath, output_filepath));
// Tests that Foo does Xyz.
TEST_F(FooTest, DoesXyz)
// Exercises the Xyz feature of Foo.
// namespace
int main(int argc, char **argv)
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
The ::testing::InitGoogleTest()
function parses the command line for Google Test flags, and removes all recognized flags. This allows the user to control a test program's behavior via various flags, which we'll cover in AdvancedGuide. You must call this function before calling RUN_ALL_TESTS()
, or the flags won't be properly initialized.
On Windows, InitGoogleTest()
also works with wide strings, so it can be used in programs compiled in UNICODE
mode as well.
But maybe you think that writing all those main() functions is too much work? We agree with you completely and that's why Google Test provides a basic implementation of main(). If it fits your needs, then just link your test with gtest_main library and you are good to go.
Important note for Visual C++ users
If you put your tests into a library and your main()
function is in a different library or in your .exe file, those tests will not run. The reason is a bug in Visual C++. When you define your tests, Google Test creates certain static objects to register them. These objects are not referenced from elsewhere but their constructors are still supposed to run. When Visual C++ linker sees that nothing in the library is referenced from other places it throws the library out. You have to reference your library with tests from your main program to keep the linker from discarding it. Here is how to do it. Somewhere in your library code declare a function:
__declspec(dllexport) int PullInMyLibrary() return 0;
If you put your tests in a static library (not DLL) then __declspec(dllexport)
is not required. Now, in your main program, write a code that invokes that function:
int PullInMyLibrary();
static int dummy = PullInMyLibrary();
This will keep your tests referenced and will make them register themselves at startup.
In addition, if you define your tests in a static library, add /OPT:NOREF
to your main program linker options. If you use MSVC++ IDE, go to your .exe project properties/Configuration Properties/Linker/Optimization and set References setting to Keep Unreferenced Data (/OPT:NOREF)
. This will keep Visual C++ linker from discarding individual symbols generated by your tests from the final executable.
There is one more pitfall, though. If you use Google Test as a static library (that's how it is defined in gtest.vcproj) your tests must also reside in a static library. If you have to have them in a DLL, you must change Google Test to build into a DLL as well. Otherwise your tests will not run correctly or will not run at all. The general conclusion here is: make your life easier - do not write your tests in libraries!
Where to Go from Here
Congratulations! You've learned the Google Test basics. You can start writing and running Google Test tests, read some samples, or continue with AdvancedGuide, which describes many more useful Google Test features.
Known Limitations
Google Test is designed to be thread-safe. The implementation is thread-safe on systems where the pthreads
library is available. It is currently unsafe to use Google Test assertions from two threads concurrently on other systems (e.g. Windows). In most tests this is not an issue as usually the assertions are done in the main thread. If you want to help, you can volunteer to implement the necessary synchronization primitives in gtest-port.h
for your platform.
Now that you have read Primer and learned how to write tests using Google Test, it's time to learn some new tricks. This document will show you more assertions as well as how to construct complex failure messages, propagate fatal failures, reuse and speed up your test fixtures, and use various flags with your tests.
More Assertions
This section covers some less frequently used, but still significant, assertions.
Explicit Success and Failure
These three assertions do not actually test a value or expression. Instead, they generate a success or failure directly. Like the macros that actually perform a test, you may stream a custom failure message into the them.
Generates a success. This does NOT make the overall test succeed. A test is considered successful only if none of its assertions fail during its execution.
Note: SUCCEED()
is purely documentary and currently doesn't generate any user-visible output. However, we may add SUCCEED()
messages to Google Test's output in the future.
FAIL()
generates a fatal failure, while ADD_FAILURE()
and ADD_FAILURE_AT()
generate a nonfatal failure. These are useful when control flow, rather than a Boolean expression, deteremines the test's success or failure. For example, you might want to write something like:
switch(expression)
case 1: ... some checks ...
case 2: ... some other checks
...
default: FAIL() << "We shouldn't get here.";
Note: you can only use FAIL()
in functions that return void
. See the Assertion Placement section for more information.
Availability: Linux, Windows, Mac.
Exception Assertions
These are for verifying that a piece of code throws (or does not throw) an exception of the given type:
Fatal assertion | Nonfatal assertion | Verifies |
---|---|---|
ASSERT_THROW( statement, exception_type); | EXPECT_THROW( statement, exception_type); | statement throws an exception of the given type |
ASSERT_ANY_THROW( statement); | EXPECT_ANY_THROW( statement); | statement throws an exception of any type |
ASSERT_NO_THROW( statement); | EXPECT_NO_THROW( statement); | statement doesn't throw any exception |
Examples:
ASSERT_THROW(Foo(5), bar_exception);
EXPECT_NO_THROW(
int n = 5;
Bar(&n);
);
Availability: Linux, Windows, Mac; since version 1.1.0.
Predicate Assertions for Better Error Messages
Even though Google Test has a rich set of assertions, they can never be complete, as it's impossible (nor a good idea) to anticipate all the scenarios a user might run into. Therefore, sometimes a user has to use EXPECT_TRUE()
to check a complex expression, for lack of a better macro. This has the problem of not showing you the values of the parts of the expression, making it hard to understand what went wrong. As a workaround, some users choose to construct the failure message by themselves, streaming it into EXPECT_TRUE()
. However, this is awkward especially when the expression has side-effects or is expensive to evaluate.
Google Test gives you three different options to solve this problem:
Using an Existing Boolean Function
If you already have a function or a functor that returns bool
(or a type that can be implicitly converted to bool
), you can use it in a predicate assertion to get the function arguments printed for free:
Fatal assertion | Nonfatal assertion | Verifies |
---|---|---|
ASSERT_PRED1( pred1, val1); | EXPECT_PRED1( pred1, val1); | pred1(val1) returns true |
ASSERT_PRED2( pred2, val1, val2); | EXPECT_PRED2( pred2, val1, val2); | pred2(val1, val2) returns true |
... | ... | ... |
In the above, predn is an n-ary predicate function or functor, where val1, val2, ..., and valn are its arguments. The assertion succeeds if the predicate returns true
when applied to the given arguments, and fails otherwise. When the assertion fails, it prints the value of each argument. In either case, the arguments are evaluated exactly once.
Here's an example. Given
// Returns true iff m and n have no common divisors except 1.
bool MutuallyPrime(int m, int n) ...
const int a = 3;
const int b = 4;
const int c = 10;
the
以上是关于20181111-hight-property-codes的主要内容,如果未能解决你的问题,请参考以下文章