Simple C macros for the Test Anything Protocol

These are simple set of macros for adding TAP testing to a C program.

/* TAP format macros. */

static int tap_count;
static int tap_todo;
static int tap_fail;

#define ENDLINE {				\
	if (tap_todo) {				\
	    printf (" # TODO\n");		\
	}					\
	else {					\
	    printf ("\n");			\
	}					\
    }

#define TAP_TEST(x) {					\
	tap_count++;					\
	if (! (x)) {					\
	    if (! tap_todo) {				\
		tap_fail++;				\
	    }						\
	    printf ("not ");				\
	}						\
	printf ("ok %d - %s", tap_count, #x);		\
	ENDLINE;					\
    }

#define TAP_TEST_EQUAL(x,y) {					\
	int xval = (int) x;					\
	int yval = (int) y;					\
	tap_count++;						\
	if (! (xval == yval)) {					\
	    if (! tap_todo) {					\
		tap_fail++;					\
	    }							\
	    printf ("not ");					\
	}							\
	printf ("ok %d - %s (%d) == %s (%d)", tap_count,	\
		#x, xval, #y, yval);				\
	ENDLINE;						\
    }

#define TAP_TEST_MSG(x,msg,args...) {			\
	tap_count++;					\
	if (! (x)) {					\
	    if (! tap_todo) {				\
		tap_fail++;				\
	    }						\
	    printf ("not ");				\
	}						\
	printf ("ok %d - ", tap_count);			\
	printf (msg, ## args);				\
	ENDLINE;					\
    }

#define TODO tap_todo = 1
#define END_TODO tap_todo = 0

#define TAP_PLAN {				\
	printf ("1..%d\n", tap_count);		\
    }

(download)

This is an example C program demonstrating this simple TAP test.

#include <stdio.h>

#include "c-tap-test.h"

int main ()
{
    int x;
    TAP_TEST (1 == 1);
    TAP_TEST_MSG (1 + 1 == 2, "one plus one equals two");
    x = 4;
    TAP_TEST_MSG (x + 1 == 5, "%d plus one equals five", x);
    TODO;
    TAP_TEST (1 == 0);

    END_TODO;
    TAP_PLAN;
    return 0;
}

(download)

The output of the example looks like this:

ok 1 - 1 == 1
ok 2 - one plus one equals two
ok 3 - 4 plus one equals five
not ok 4 - 1 == 0 # TODO
1..4

You can also run it like this:

cc -o stt stt.c
prove ./stt

The header file uses static global variables, which means it is useful only if all your tests are in one file.

I've also written a manual page for the file.


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer