C header-only unit testing with FCTX
Just a quick hat tip to FCTX, a library I've found invaluable these past few months. FCTX provides header-only unit testing for C. Sure, if you're in C++ land there's a ton of xUnit-like frameworks available (with Boost.Test being my favorite), but for vanilla C projects FCTX wins hands down.
As an example, here's something I put together for a Stack Overflow response:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ctype.h> | |
void trim(char * const a) | |
{ | |
char *p = a, *q = a; | |
while (isspace(*q)) ++q; | |
while (*q) *p++ = *q++; | |
*p = '\0'; | |
while (p > a && isspace(*--p)) *p = '\0'; | |
} | |
/* See http://fctx.wildbearsoftware.com/ */ | |
#include "fct.h" | |
FCT_BGN() | |
{ | |
FCT_QTEST_BGN(trim) | |
{ | |
{ char s[] = ""; trim(s); fct_chk_eq_str("", s); } // Trivial | |
{ char s[] = " "; trim(s); fct_chk_eq_str("", s); } // Trivial | |
{ char s[] = "\t"; trim(s); fct_chk_eq_str("", s); } // Trivial | |
{ char s[] = "a"; trim(s); fct_chk_eq_str("a", s); } // NOP | |
{ char s[] = "abc"; trim(s); fct_chk_eq_str("abc", s); } // NOP | |
{ char s[] = " a"; trim(s); fct_chk_eq_str("a", s); } // Leading | |
{ char s[] = " a c"; trim(s); fct_chk_eq_str("a c", s); } // Leading | |
{ char s[] = "a "; trim(s); fct_chk_eq_str("a", s); } // Trailing | |
{ char s[] = "a c "; trim(s); fct_chk_eq_str("a c", s); } // Trailing | |
{ char s[] = " a "; trim(s); fct_chk_eq_str("a", s); } // Both | |
{ char s[] = " a c "; trim(s); fct_chk_eq_str("a c", s); } // Both | |
// Villemoes pointed out an edge case that corrupted memory. Thank you. | |
// http://stackoverflow.com/questions/122616/#comment23332594_4505533 | |
{ | |
char s[] = "a "; // Buffer with whitespace before s + 2 | |
trim(s + 2); // Trim " " containing only whitespace | |
fct_chk_eq_str("", s + 2); // Ensure correct result from the trim | |
fct_chk_eq_str("a ", s); // Ensure preceding buffer not mutated | |
} | |
} | |
FCT_QTEST_END(); | |
} | |
FCT_END(); |
No comments:
Post a Comment