我创建了一个镜像我的源代码的小程序。这里主要是在调试模式下,在运行主应用程序之前调用外部库测试器功能。想象一下,该库中的构造函数分配内存,在调试时还会测试一些静态函数。如果测试该库,它将运行静态测试程序代码。如果使用该库,则为静态测试程序代码。每次调用库函数时 静态测试程序都会运行 。
的main.c
// calls test and library
#include <stdio.h>
#include <stdlib.h>
// to test if the lib is there and the function does what it says claims
extern int testExternalLibFunctions(void);
#include "lib.h"
int main(){
testExternalLibFunctions();
printf("main function uses doTheTango\n");
doTheTango();
// do the magic stuff here and
doTheTango();
return 0;
}
test_lib.c
#include <stdio.h>
#include "lib.h"
static int Static_doTheTangoTest();
int testExternalLibFunctions(){
// define DO_THE_TANGO_TEST_SELF_TRUE
Static_doTheTangoTest();
// undefine DO_THE_TANGO_TEST_SELF_TRUE
return 0;
}
int Static_doTheTangoTest(){
printf("external function tester calls doTheTango\n");
doTheTango();
return 0;
}
lib.h
#ifndef DO_THE_TANGO_HEADER
#define DO_THE_TANGO_HEADER
extern int doTheTango();
#endif // DO_THE_TANGO_HEADER
lib.c
#include <stdio.h>
#include <assert.h>
#include "lib.h" //self
// ONLY HERE SHOULD STATIC FUNCTIONS BE TESTED
static int STATIC_TEST();
int doTheTango(){
printf("Dancing is fun - ");
// if defined DO_THE_TANGO_TEST_SELF_TRUE
STATIC_TEST();
// endif
getchar();
return 0;
}
int STATIC_TEST(){
printf("Static test 1, Yet again!");
return 0;
}
不打算拆分测试仪和主要功能,因为主要是调用更多测试人员等等......他们是相互依赖的!
如何在首次包含库时让库进行静态测试?像python中的那样,你在哪里测试
if(__name__ == __main__) -> do the static tests
答案 0 :(得分:2)
我不确定我明白你要做什么。我从源代码中看到你说'#34;静态测试1,又一次!&#34;,所以我假设你不希望在后续调用doTheTango时调用STATIC_TEST。
如果这是您想要的,请执行:
int doTheTango(){
static int isTested = 0;
printf("Dancing is fun - ");
if (!isTested) {
isTested = 1;
STATIC_TEST();
}
getchar();
return 0;
}
答案 1 :(得分:0)
这很有效!实际上也是我在寻找的东西!
// in the global doTheTangoTest you define:
extern int TEST_TANGO_SELF;
doTheTangoTest{
// to set it to 1 if the library is testing itself
TEST_TANGO_SELF = 1;
doTheTango();
// to set it to 0 if testing itself is finished
TEST_TANGO_SELF = 0;
}
和doTheTango来源
// you define again, but not as extern this time, just as int
int TEST_TANGO_SELF;
int doTheTango(){
printf("Dancing is fun - ");
// and use this global variable in a simple if statement
if(TEST_TANGO_SELF){
STATIC_TEST();
}
getchar();
return 0;
}