当前位置:网站首页>[embedded unit test] construction of C language unit test framework
[embedded unit test] construction of C language unit test framework
2022-07-19 11:41:00 【Ruler.】
cmocka
The unit test framework is a software package , It allows developers to easily express what kind of behavior the product code needs to show . The unit testing framework provides a solution to automate unit testing , Let developers pay more attention to the design and writing of test cases , Instead of thinking about how to organize test cases .
cmocka It's an elegant C Language unit testing framework , Support simulation objects . It just needs standard C library , It is suitable for all kinds of computing platforms (Linux、windows, And embedded ).
In theory ,cmocka It can support any standard C Cross compiler of Library .
This article will introduce how to use the embedded environment ( Cross compilation ) build cmocka Unit test environment , as well as cmocka Simple example of use .
cmocka Cross compilation
Source download
Up to date 1.1.5 edition , For embedded environments , We need to download the source code for cross compilation
cmocka1.1 Source code download address
Here we use cmocka-1.1.5.tar.xz For example .
Compilation preparation
Put the above source code in linux Decompression in the environment , And create a new compilation directory in the same level directory of the source code build_dir

cmocka-1.1.5 The contents are as follows :

Source code modification
Get into cmocka-1.1.5 Source directory , Modify the top level CMakeLists.txt, Note out the following line .doc Components require specific library support , Embedded environments generally do not have this library , And this is just generating code comments , No effect on function , So annotate it .
# add_subdirectory(doc)
Specify compiler
The next in build_dir Create a new configuration file at the same level of directory arm64_setup.cmake( The file name is optional )
The contents of the document are as follows :
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm64)
set(tools /mnt/opt/compile_tools/bin/)
set(CMAKE_C_COMPILER ${tools}/aarch64-openwrt-linux-gcc)
set(CMAKE_CXX_COMPILER ${tools}/aarch64-openwrt-linux-g++)
CMAKE_SYSTEM_NAMESpecify the embedded system typeCMAKE_SYSTEM_PROCESSORSpecify the embedded platformtoolsCross compiler path ( Subject to the actual path )CMAKE_C_COMPILERC Cross compilerCMAKE_CXX_COMPILERC++ Cross compiler
compile
Compilation needs to enter build_dir Catalog , First execute the following command to generate the necessary configuration and makefile file
$ cd build_dir
$ cmake -DCMAKE_TOOLCHAIN_FILE=../arm64_setup.cmake -DBUILD_STATIC_LIB=ON ../cmocka-1.1.5/
-DCMAKE_TOOLCHAIN_FILEIs to specify the compiler configuration file just created-DBUILD_STATIC_LIB=ONIs to compile and generate static libraries , Removing this sentence will only generate dynamic libraries../cmocka-1.1.5/Appoint cmocka Source directory
If the above steps are correct , So in build_dir Several directories and files should be generated , Among them is makefile, Next make Recompile, .
$ make
The following prompt indicates that the compilation is successful :
Scanning dependencies of target cmocka
[ 4%] Building C object src/CMakeFiles/cmocka.dir/cmocka.c.o
......
[100%] Linking C executable test_uptime
[100%] Built target test_uptime
if necessary
clean, Directly inbuild_dirDirectory executionmake cleanYou can't , becauseCmakeI won't support it . The simplest way is tobuild_dirThe directory can be emptied manually .
Check... After compilation build_dir/src, It will generate the dynamic library or static library we need .
Use file Instructions can see that this dynamic library is ARM aarch64 Platform , It shows that our cross compilation is successful .
$ build_dir/src$ ls
CMakeFiles libcmocka.so libcmocka.so.0.7.0 Makefile
cmake_install.cmake libcmocka.so.0 libcmocka-static.a
$ file libcmocka.so.0.7.0
libcmocka.so.0.7.0: ELF 64-bit LSB shared object, ARM aarch64, version 1 (SYSV), dynamically linked, with debug_info, not stripped
in addition ,build_dir/example Some examples will also be generated under the directory demo, It can run directly on the development board .
$ build_dir/example$ ls
allocate_module_test CMakeFiles Makefile
assert_macro_test cmake_install.cmake mock
assert_module_test CTestTestfile.cmake simple_test
$ file simple_test
simple_test: ELF 64-bit LSB executable, ARM aarch64, version 1 (SYSV), dynamically linked, interpreter /lib/ld-musl-aarch64.so.1, with debug_info, not stripped
With libcmocka, Add... In the source code cmocka.h, I can use cmocka Provided API Compile our own unit test code .
cmocka.hbe locatedcmockaSource codeincludeCatalog
cmocka Examples of use
The test code is as follows :
$ tree hello/
hello/
├── inc
│ └── cmocka.h
├── libs
│ ├── libcmocka.so
│ └── libcmocka-static.a
├── makefile
└── src
└── hello_cmocka.c
libsFolder main repository file , RecommendedlibcmockaStatic library , The advantage of using static libraries is that the compiled binary files can be run directly on the development board , If it is a dynamic library, it also needs to be installed on the development board , The disadvantage of static library is the large volume of compiled products .
Example makefile The documents are as follows :
#source file
SOURCE += $(wildcard ./src/*.c)
OBJS := $(patsubst %.c,%.o,$(patsubst %.cpp,%.o,$(SOURCE)))
TARGET := hello_cmocka
#compile and lib parameter
CC := aarch64-openwrt-linux-gcc
LIBS := -lcmocka-static
LDFLAGS := -L./libs
DEFINES :=
INCLUDE := -I./inc/
CFLAGS := -g -Wno-unused-variable -O3 $(DEFINES) $(INCLUDE)
CXXFLAGS:= $(CFLAGS)
.PHONY:
all : $(TARGET)
objs : $(OBJS)
clean :
rm -fr ./src/*.o
rm -fr $(TARGET)
$(TARGET) : $(OBJS)
$(CC) $(CXXFLAGS) -o [email protected] $(OBJS) $(LDFLAGS) $(LIBS)
Example hello_cmocka.c as follows :
#include <stdarg.h>
#include <stdio.h>
#include <setjmp.h>
#include <stddef.h>
#include <stdint.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <cmocka.h>
static int add(int a ,int b)
{
return a+b;
}
static char* print_string(int num)
{
switch(num)
{
case 1: return "CASE1";
case 2: return "CASE2";
default: return "NOT SUPPORT";
}
return "NOT SUPPORT";
}
static void test_demo1(void **state)
{
int ret = add(3,2);
assert_int_equal(ret, 5);
(void) state;
}
static void test_demo2(void **state)
{
int ret = add(3,2);
assert_int_equal(ret, 0);
(void) state;
}
static void test_demo3(void **state)
{
char *p = print_string(1);
assert_string_equal(p, "CASE1");
(void) state;
}
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_demo1),
cmocka_unit_test(test_demo2),
cmocka_unit_test(test_demo3),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
The operation results are as follows :
# ./hello_cmocka
[==========] Running 3 test(s).
[ RUN ] test_demo1
[ OK ] test_demo1
[ RUN ] test_demo2
[ ERROR ] --- 0x5 != 0
[ LINE ] --- src/hello_cmocka.c:46: error: Failure!
[ FAILED ] test_demo2
[ RUN ] test_demo3
[ OK ] test_demo3
[==========] 3 test(s) run.
[ PASSED ] 2 test(s).
[ FAILED ] 1 test(s), listed below:
[ FAILED ] test_demo2
1 FAILED TEST(S)
Tips test_demo2 Test to fail , as a result of 0x5 != 0,test_demo2 The expected result is 0, Actual return 5, Fall short of expectations , So the test failed .assert_int_equal() Is a judgment int Type the results ,assert_string_equal() Is a judgment const char * Result of type . besides ,cmocka More other tests are also provided API, Please refer to cmocka.h.
common problem
- Compile error
/cmocka-1.1.5/include/cmocka.h:132:28: error: conflicting types for 'uintptr_t'
typedef unsigned int uintptr_t;
/mnt/opt/include/bits/alltypes.h:109:24: note: previous declaration of 'uintptr_t' was here
typedef unsigned _Addr uintptr_t;
cmocka Source code uintptr_t The definition conflicts with the definition in our cross compiler , Here, you only need to comment out the definitions in the compiler for the time being , Finished compiling cmocka Just change it back .
- Other compilation problems
cmocka Only standards are used C library , Its cross platform compatibility is very good . therefore , Most cross compilers should be supported ( Unless your compiler version is very low , Yes C The library is not fully supported ).
therefore , Cross compilation cmocka The compilation problems encountered in the source code are basically C Code problem , It's not about the platform .
Reference resources
边栏推荐
- Introduction of database lock, shared with InnoDB, exclusive lock
- Dynamic memory allocation problem
- synchronized锁升级
- JVM钩子hooks函数
- Learning outline of the column "MySQL DBA's magic road"
- Leetcode 1328. 破坏回文串(可以,已解决)
- 下推计算结果缓存
- STM32F407 NVIC
- function/symbol ‘pango_context_set_round_glyph_positions‘ not found in library ‘libpango-1.0.so.0‘x
- function/symbol ‘pango_ context_ set_ round_ glyph_ positions‘ not found in library ‘libpango-1.0. so. 0‘x
猜你喜欢

JVM hook hooks function

QT -- excellent open source project

Developing those things: how to solve the problem of long-time encoding and decoding of RK chip video processing?

A fastandrobust convolutionalneuralnetwork-based defect detection model inproductqualitycontrol-閱讀筆記

466-82(3、146、215)

Keras deep learning practice (14) -- r-cnn target detection from scratch

Tier defect detection using full revolutionary network

Deep learning for generic object detection: a survey

SPI service discovery mechanism

A fastandrobust volutionalneuralnetwork based defect detection model inproductqualitycontrol reading notes
随机推荐
03-1、内联函数、auto关键字、typeid、nullptr
TiFlash 性能调优
TiDB 内存控制文档
03-2、
TCP拥塞控制详解 | 7. 超越TCP
What happened to cinder in openstack-m
Un modèle de détection par défaut basé sur le réseau neuronal évolutif rapide dans le contrôle de la qualité des produits - lire les notes
TCP拥塞控制详解 | 7. 超越TCP
[PostgreSQL] PostgreSQL 15 optimizes distinct
Play with the one-stop scheme of cann target detection and recognition
Mpu9250 ky9250 attitude, angle module and mpu9250 MPL DMA comparison
Configure spectrum navigation for Huawei wireless devices
02-2. Default parameters, function overloading, reference, implicit type conversion, about error reporting
Kernel mode and user mode
Antd form setting array fields
How to build dashboard and knowledge base in double chain note taking software? Take the embedded widget library notionpet as an example
02-3、指針和引用的區別
An error, uncaught typeerror: modalfactory is not a constructor
【无标题】cv 学习1转换
What do you look at after climbing the wall? The most popular foreign website - website navigation over the wall