当前位置:网站首页>[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
边栏推荐
- Play with the one-stop scheme of cann target detection and recognition
- 02 - 3. Différences entre les pointeurs et les références
- LOJ 2324 - "Tsinghua training 2017" small y and binary tree
- TCP拥塞控制详解 | 7. 超越TCP
- Region 性能调优
- SQL UNION操作符
- 02-2. Default parameters, function overloading, reference, implicit type conversion, about error reporting
- Unity3d read mpu9250 example source code
- 02-3、指針和引用的區別
- A fastandrobust convolutionalneuralnetwork-based defect detection model inproductqualitycontrol-閱讀筆記
猜你喜欢

Discussion on Euler angle solution of rocket large maneuvering motion

synchronized锁升级

A fastandrobust volutionalneuralnetwork based defect detection model inproductqualitycontrol reading notes

Hot discussion: my husband is 34 years old this year and wants to read a doctoral degree. What should I do in the future to do scientific research?

Qt--优秀开源项目

热议:老公今年已经34周岁想读博,以后做科研,怎么办?

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

《MySQL DBA封神打怪之路》专栏学习大纲

LeetCode刷题——查找和最小的 K 对数字#373#Medium

LeetCode 558. Intersection of quadtree
随机推荐
Dream CMS foreground search SQL injection
Solution of connecting MySQL instance with public network
Deep learning for generic object detection: a survey
Learning outline of the column "MySQL DBA's magic road"
SPI service discovery mechanism
How to build dashboard and knowledge base in double chain note taking software? Take the embedded widget library notionpet as an example
Solve the problem that QQ mail and Thunderbird cannot log in to outlook
Docker install MySQL
A fastandrobust convolutionalneuralnetwork-based defect detection model inproductqualitycontrol-阅读笔记
夢想CMS 前臺搜索SQL注入
Total number of blocking and waiting in jconsole thread panel (RPM)
Keras deep learning practice (14) -- r-cnn target detection from scratch
[binomial tree] the power of the button cattle customers must brush questions
2022 National latest fire-fighting facility operator (intermediate fire-fighting facility operator) simulation test questions and answers
TiKV 线程池性能调优
03-2、
Automated graphical interface library pyautogui
Dynamic memory allocation problem
Will causal learning open the next generation of AI? Chapter 9 Yunji datacanvas officially released the open source project of ylarn causal learning
Wechat applet cloud development 1 - Database