09-21-08 - 4

I just had this idea for embedded unit tests. My big problem with unit tests has always been that they're off in seperate code that's hard to maintain and gets out of date and is too much of a pain to create and people don't do it. Also it's not as valuable as an assert that's right there in the code as documentation when you read it.

Now, I have a COMPILER_ASSERT thing and love that, but it can't call functions, you can only check constant conditions. What if you could do a compiler assert that was right there, something like :

REQUIRE( ilog2ceil(256) == 8 );
REQUIRE( ilog2ceil(11) == 4 );

Now, in the actual compile there would just be a

#define REQUIRE(exp)

that makes those expressions do nothing, but you would run your own custom build step that scans the file for "REQUIRE" and grabs all those expressions and puts them in their own little .cpp file, compiles it and runs it with

#define REQUIRE(exp)	if ( ! (exp) ) { make bad error report, send people email, whatever }

The stuff in REQUIRE might use things in the file, so the easiest thing would be for the autogen to make the test function at the bottom of each .cpp Then call them all from main. The autogen would also have to disable the original main somehow to run its own main. In VC you would make the autogen thing a custom build step as part of your project build, so that a unit test failure would result in a failure to build.

Actually I can do something without autogen that's not bad. With cblib right now I can do :


That executes at startup so it can't make the build fail, but hey I can do it right now without any autogen code madness.

For longer unit tests you can just put them in a function, like :

static bool CheckLotsOfStuff()
	.. blah blah ... do unit testy stuff here ...
	return true;

REQUIRE( CheckLotsOfStuff() );

No comments:

old rants