Skip to content

Instantly share code, notes, and snippets.

@tksmiura
Last active May 7, 2017 03:45
Show Gist options
  • Save tksmiura/b95aefdafa29abbcef967471bf6e523b to your computer and use it in GitHub Desktop.
Save tksmiura/b95aefdafa29abbcef967471bf6e523b to your computer and use it in GitHub Desktop.
SimpleUnitTestC

Simple unit test for C langage

Aim

  • easy to test, such as 'make test'
  • easy make test code

Usage

  • Add test function named 'test0nn' to 'ut_main.c'.
  • Test functions check code using UT_ASSERT.
  • Do 'make test'.

Sample

% make test
cc -Wall -O2 -c ut_main.c
cc -o ut_main ut_main.o
./ut_main
ut_main.c:24: 'func1(0) == 1' is NG
test NG test002
result 2/3 
#include <stdio.h>
static int func1(int parm)
{
if (parm > 0)
return 1;
return 0;
}
int main(int argc, char *argv[])
{
printf("Hello World!\n");
printf("arg test %d\n", func1(argc));
return 0;
}
all: main
# TARGETS
PROGRAM = main
OBJS = main.o
TEST = ut_main
TEST_OBJS = ut_main.o
# ENVIRONMENT
CC ?= gcc
CFLAGS ?= -Wall -O2
# suffixes
.SUFFIXES: .c .o
# target
$(PROGRAM): $(OBJS)
$(CC) -o $(PROGRAM) $^
# suffix rules
.c.o:
$(CC) $(CFLAGS) -c $<
# clean target
.PHONY: clean
clean:
$(RM) $(PROGRAM) $(OBJS) $(TEST) $(TEST_OBJS)
# test target
.PHONY: test
test: $(TEST)
./$(TEST)
$(TEST): $(TEST_OBJS)
$(CC) -o $(TEST) $^
# header (not using now)
# main.o: str.h
#include <stdio.h>
#include <dlfcn.h>
#include <stdbool.h>
/* test function prototype */
typedef bool (*Test)(void);
#define main __original_main
/* test target source */
#include "main.c"
#undef main
/* test assert */
#define UT_ASSERT(f) {if (!(f)) {printf("%s:%u: '%s' is NG\n", __FILE__,__LINE__,#f);return false;}}
/*
* test codes
*/
bool test001(void)
{
UT_ASSERT(func1(1) == 1);
return true;
}
bool test002(void)
{
UT_ASSERT(func1(0) == 1);
return true;
}
bool test003(void)
{
UT_ASSERT(func1(-1) == 0);
return true;
}
/* add more test code ... */
int main(int argc, char *argv[])
{
Test t;
bool ret;
int i;
char func_name[100];
unsigned int count_ok = 0, count = 0;
for (i = 0; i < 100; i++) {
sprintf(func_name, "test%03d", i);
t = (Test) dlsym(RTLD_DEFAULT, func_name);
if (t != NULL) {
count++;
ret = (*t)();
if (ret)
count_ok++;
else
printf("test NG %s\n", func_name);
}
}
printf("result %u/%u \n", count_ok, count);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment