testing in Unison with googletest

内核开发者
• 阅读 1478

Suppose we've written an application library in Unison, We could do some test to make sure that it works as expected.

In this article, we'll walk through writing a simple testcase in Unison with googletest.

What is googletest?

Build googletest as a shared library

First of all, to work in Unison, we need to build googletest into a shared library.

Choose the right version of googletest

Starting from version v1.10.0, googletest requires the compiler support C++11 standard, while version 1.8.x is the last releases that works with pre-C++11 compilers.

  • For CentOS 7, the gcc (version 4.8.x) fully supports C++11, so the latest version would be prefered.
  • For CentOS 6, the gcc (version 4.4.x) support only part of C++11, so only v1.8.x is available. Still, with the experimental C++0x, part of C++11 features is provided.

Get source code of googletest

You can clone the git repository, or download the source tarball.
In this example, release-v1.10.0 will be used. we'll build it under ~/build-googletest

  • Clone git repository

    mkdir ~/build-googletest
    cd ~/build-googletest
    git clone https://github.com/google/googletest.git
    cd googletest
    # list all released version
    git tag
    # possible output:
        release-1.0.0
        release-1.0.1
        release-1.1.0
        release-1.10.0
        release-1.2.0
        release-1.2.1
        release-1.3.0
        release-1.4.0
        release-1.5.0
        release-1.6.0
        release-1.7.0
        release-1.8.0
        release-1.8.1
        v1.10.x # unreleased
    # we'll check out the latest release
    git checkout release-1.10.0
  • Download source tarball

    mkdir ~/build-googletest
    cd ~/build-googletest
    wget https://github.com/google/googletest/archive/release-1.10.0.tar.gz
    tar xzf googletest-release-1.10.0.tar.gz

Build shared library

I've created a github repository alancprc/google-test-build-as-shared-lib, containing the Makefile to build googletest as a shared library, you should get the Makefile before going on.

  • Put the Makefile under ~/build-googletest
  • The default option in Makefile is -m64, which tells the compiler to generate code for a 64-bit environment. -m64 is for U1709+, you'll need to replace -m64 with -m32 for Unison 4.x
  • Run make to build
  • If everything goes well, you'll get following .so files

    libgtest.so
    libgtest_main.so
    libgmock.so
    libgmock_main.so

    and the following output

    Running main() from gmock_main.cc
    [==========] Running 6 tests from 2 test cases.
    [----------] Global test environment set-up.
    [----------] 3 tests from FactorialTest
    [ RUN      ] FactorialTest.Negative
    [       OK ] FactorialTest.Negative (0 ms)
    [ RUN      ] FactorialTest.Zero
    [       OK ] FactorialTest.Zero (0 ms)
    [ RUN      ] FactorialTest.Positive
    [       OK ] FactorialTest.Positive (0 ms)
    [----------] 3 tests from FactorialTest (0 ms total)
    
    [----------] 3 tests from IsPrimeTest
    [ RUN      ] IsPrimeTest.Negative
    [       OK ] IsPrimeTest.Negative (0 ms)
    [ RUN      ] IsPrimeTest.Trivial
    [       OK ] IsPrimeTest.Trivial (0 ms)
    [ RUN      ] IsPrimeTest.Positive
    [       OK ] IsPrimeTest.Positive (0 ms)
    [----------] 3 tests from IsPrimeTest (0 ms total)
    
    [----------] Global test environment tear-down
    [==========] 6 tests from 2 test cases ran. (0 ms total)
    [  PASSED  ] 6 tests.

Install googletest to system directories

  • Put the generated shared libraries into /usr/lib64, or /usr/lib if -m32 option is set. root permission is required.

    cp -at /usr/lib64/ libgtest*.so libgmock*.so
  • put the header files to /usr/local/include

    cp -at /usr/local/include ./googletest/googletest/include/gtest ./googletest/googletest/include/gmock

Use googletest in Unison application library

Library to test

In this example, we create a Unison application library called UnisonUtil, containing files unison-util.h and unison-util.cpp, providing a simple function void removeTrailNewLine(StringS &str). The source code is as follows:

  • unison-util.h

    #pragma once
    #include <Unison.h>
    
    namespace util {
    
    /** @brief remove trailing new line '\n' in string.*/
    void removeTrailNewLine(StringS &str);
    
    }  // namespace util
  • unison-util.cpp

    #include "unison-util.h"
    
    namespace util {
    
    void removeTrailNewLine(StringS &str)
    {
      int len = str.Length();
      if (len and str[len - 1] == '\n') {
        str.Erase(len - 1, 1);
      }
    }
    
    }  // namespace util

Create UnitTest application library

  1. Create an application library UnitTest in Unison TestTool.
  2. Add a source file unittest.cpp, with following code

    #include <gmock/gmock.h>
    #include "unison-util.h"
    
    using namespace std;
    
    TMResultM StartGTest()
    {
     int argc = 1;
     const char* argv[] = {"a.out"};
    
     std::cout << "\n\n\nRunning main() from unittest.cpp\n";
     testing::InitGoogleMock(&argc, const_cast<char**>(argv));
     int result = RUN_ALL_TESTS();
     return result == 0 ? TM_PASS : TM_FAIL;
    }
    
    TEST(UtilFuncTest, removeTrailNewLineTest)
    {
     StringS str = "hello world\n";
     util::removeTrailNewLine(str);
     util::removeTrailNewLine(str);
     EXPECT_STREQ(str, "hello world");
    }

Set up the UnitTest library

  • Add following to Compiler Flags

    -pthread
    -DGTEST_LINKED_AS_SHARED_LIBRARY=1
    -fno-gnu-unique
  • Add following to Linker Flags

    -lpthread
    -lgmock -lgtest
  • Add include path for UnisonUtil and googletest

    ./                      # include path for UnisonUtil
    /usr/local/include      # include path for googletest
  • Add library UnisonUtil as dependency

Build and start test

  • build UnitTest library
  • Create a TestGroup tgStartGTest, which calls StartGTest() function
  • Execute the TestGroup
    you should see the following output in dataviewer

    Running main() from unittest.cpp
    [==========] Running 1 test from 1 test suite.
    [----------] Global test environment set-up.
    [----------] 1 test from UtilFuncTest
    [ RUN      ] UtilFuncTest.removeTrailNewLineTest
    [       OK ] UtilFuncTest.removeTrailNewLineTest (0 ms)
    [----------] 1 test from UtilFuncTest (0 ms total)
    
    [----------] Global test environment tear-down
    [==========] 1 test from 1 test suite ran. (0 ms total)
    [ PASSED ] 1 test.

Known issue

  • Unable to close the dynamic-linked library file

    << __WARNING 1:___________________________________
    
    In utlrt-aliang_sim (DynamicLink_Method), 4gl/class/dll_method/DLL_Installation.cxx, line 897, at Sun May 31 12:06:55 2020
    
    Warning: Uninstalling Dynamic-Link Method:
    
    File: /home/aliang/working/unison-util/x86_64_linux_3.10.0/libUnitTest.un.so
    
    Unable to close the dynamic-linked library file
        Please check for any static variables in inlined functions and move them out so they are not inlined. The test program has to be unloaded and loaded back after changing it. Running 'readelf -Ws libUnitTest.un.so | grep UNIQUE | c++filt' will help to find what is causing the error.
    User file: 4gl/class/dll_method/DLL_Installation.cxx, Line: 897, Statement: DynamicLink_Method
    • This error may occur on CentOS 7 or CentOS 6 with an updated gcc version. To solve this error, add compiler flag -fno-gnu-unique to the application library.

Why not build googletest into a Unison application library?

Though installing googletest into system directory is disencouraged by googletest document, I found it necessary to use it in Unison.
I've tried to build googletest into a Unison application library, but when the library gets re-compiled, the tests get duplicated, which is really annoying.
For example, if the above test uses a googletest as a Unison application library, it'll become something like following after re-compiling UnisonUtil library.

Running main() from unittest.cpp
[==========] Running 2 tests from 1 test suites.
[----------] Global test environment set-up.
[----------] 2 tests from UtilFuncTest
[ RUN      ] UtilFuncTest.removeTrailNewLineTest
[       OK ] UtilFuncTest.removeTrailNewLineTest (0 ms)
[ RUN      ] UtilFuncTest.removeTrailNewLineTest
[       OK ] UtilFuncTest.removeTrailNewLineTest (0 ms)
[----------] 2 tests from UtilFuncTest (0 ms total)

[----------] Global test environment tear-down
[==========] 2 tests from 1 test suites ran. (0 ms total)
[  PASSED  ] 2 tests.

if the UnisonUtil library gets another re-compiling, the output becomes as follows.

Running main() from unittest.cpp
[==========] Running 3 tests from 1 test suites.
[----------] Global test environment set-up.
[----------] 3 tests from UtilFuncTest
[ RUN      ] UtilFuncTest.removeTrailNewLineTest
[       OK ] UtilFuncTest.removeTrailNewLineTest (0 ms)
[ RUN      ] UtilFuncTest.removeTrailNewLineTest
[       OK ] UtilFuncTest.removeTrailNewLineTest (0 ms)
[ RUN      ] UtilFuncTest.removeTrailNewLineTest
[       OK ] UtilFuncTest.removeTrailNewLineTest (0 ms)
[----------] 3 tests from UtilFuncTest (0 ms total)

[----------] Global test environment tear-down
[==========] 3 tests from 1 test suites ran. (0 ms total)
[  PASSED  ] 3 tests.

原创文章,始发于https://alancprc.github.io/c++/2020/05/31/testing-in-unison-with-googletest.html
本文链接https://segmentfault.com/a/1190000022796424
转载请注明出处

点赞
收藏
评论区
推荐文章
blmius blmius
4年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
Wesley13 Wesley13
4年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
4年前
FLV文件格式
1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  
Wesley13 Wesley13
4年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
4年前
PHP创建多级树型结构
<!lang:php<?php$areaarray(array('id'1,'pid'0,'name''中国'),array('id'5,'pid'0,'name''美国'),array('id'2,'pid'1,'name''吉林'),array('id'4,'pid'2,'n
Wesley13 Wesley13
4年前
Java日期时间API系列36
  十二时辰,古代劳动人民把一昼夜划分成十二个时段,每一个时段叫一个时辰。二十四小时和十二时辰对照表:时辰时间24时制子时深夜11:00凌晨01:0023:0001:00丑时上午01:00上午03:0001:0003:00寅时上午03:00上午0
Wesley13 Wesley13
4年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
4年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Python进阶者 Python进阶者
2年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
内核开发者
内核开发者
Lv1
与其做个无途的归人不如去做个有梦的乘客.
文章
4
粉丝
0
获赞
0