3 ms·
A minimal C unit testing framework (only 3 LOC)
- Locke1689 17y agohttp://en.wikipedia.org/wiki/Assert.h http://en.wikipedia.org/wiki/Assert.h For those of you working in embedded environments where even that is too heavy: cross-compile or write that stupid macro yourself (it's 3 lines for pity's sake!).
- wheaties 17y agoUm 3 lines? That's not 3 lines. Sure it FITS into 3 lines but every time you see a ";" you also see a new line. So #define mu_run_test(test) do { char message = test(); tests_run++; if (message) return message; } while (0) Isn't one line but #define mu_run_test(test) do { char *message = test(); tests_run++; if (message) return message; } while (0
- steveklabnik 17y agoI don't think this is some grand conspiracy where this guy is going to slip a macro past us to make us think he's some super 1337 coder becauase I can count LOC on one hand. It's just that most people would see a #define as 1LOC. The semantics are a bit iffy becuase it's a macro, yes, but even then, okay, it's 12 LOC if you put in those extra lines. It's still tiny. His point about the simplicity of tests still stands.
- dkersten 17y agoWell, then, I'm going to start a blog series about "X in 1 LOC" and just mash everything into one line. If that doesn't work, I'll rename it to "X in 2 LOC" and put the code into a define, then use the define. Obviously I will be posting each and every port to HN. You downvote me now, but you'll be upvoting me when I make infinite amounts of money on my 2 LOC implementations of.. everything :-D
- steveklabnik 17y agoYou're still missing the point. It has nothing to do with the value of X, except that it's small.
- audidude 17y agoNeat hack, but I far more enjoy glib's g_test_*() infrastructure. It also integrates well with `make' and can print out reports or store them for future comparisons.
- steveklabnik 17y agoThe point is not that this is a super robust awesome framework, it's that testing is so simple that everyone should do it.
- nkurz 17y agoI've never liked having to type my test twice, once for the actual test and once for the 'message'. So I do something more like this instead: #include <stdio.h> #define test(expr) do { \ if (!(expr)) printf("FAILED: %s\n", #expr); \ else printf(" ok: %s\n", #expr); \ } while (0) int main(void) { int a = 1; test(a == 1); test(a == 0); return 0; } I don't actually use the direct printf() approach, but this shows the idea. Is there a reason more people don't 'stringify' macro arguments? I'm pretty tied to GCC, and am not always aware of what works on other compilers.
- nova 17y agoYou could also concatenate the strings, as they are know at compile time, and use puts or something simpler than printf. puts("FAILED: " #expr ) (Or you could keep the printf, as it looks like GCC optimizes it to puts when just used to print a string, without variable interpolation)