/** * tally-utest.c * A very simple unit test of the tally function. */ // +---------+-------------------------------------------------------- // | Headers | // +---------+ #include #include #include "tally.h" // +---------+-------------------------------------------------------- // | Globals | // +---------+ static int errors = 0; // A count of errors static int tests = 0; // A count of tests conducted // +--------+--------------------------------------------------------- // | Macros | // +--------+ /** * BLOCK(CODE) * Wrap a block of code for cleanliness. */ #define BLOCK(CODE) do { CODE } while (0) /** * CHECK(EXPRESSION, EXPECTED) * Check the value of an expression and, if it's not what is * expected, print an error message. */ #define CHECK(EXPRESSION, EXPECTED) \ BLOCK ( \ ++tests; \ int result = EXPRESSION; \ if (result != EXPECTED) \ { \ ++errors; \ fprintf (stderr, "ERROR\n"); \ fprintf (stderr, " Expression: %s\n", #EXPRESSION); \ fprintf (stderr, " Expected: %d\n", EXPECTED); \ fprintf (stderr, " Result: %d\n", result); \ } \ ) // +-------------------+---------------------------------------------- // | String Predicates | // +-------------------+ /** * a1 - check for an a in position 1. */ int a1 (char *str) { return ( (str != NULL) && (str[0] != '\0') && (str[1] == 'a') ); } // a1 /** * lope - check for the substring of "lope" */ int lope (char *str) { return (str != NULL) && (strstr (str, "lope") != NULL); } // lope /** * length1 * Determine if the string has a length of 1 */ int length1 (char *str) { return ( (str != NULL) && (str[0] != '\0') && (str[1] == '\0') ); } // length1 /** * length2 * Determine if the string has a length of 2 */ int length2 (char *str) { return ( (str != NULL) && (str[0] != '\0') && (str[1] != '\0') && (str[2] == '\0') ); } // +------+----------------------------------------------------------- // | Main | // +------+ int main () { char *strings1[] = { "aardvark", "antelope", "jack rabbit", "jackelope" }; char *strings2[] = { "a", "aa", "b", "bbb", "c", "cccc", "d", "dd" }; CHECK (tally_strings (strings1, 4, a1), 3); CHECK (tally_strings (strings2, 8, a1), 1); CHECK (tally_strings (strings1, 4, lope), 2); CHECK (tally_strings (strings2, 8, lope), 0); CHECK (tally_strings (strings1, 4, length1), 0); CHECK (tally_strings (strings2, 8, length1), 4); CHECK (tally_strings (strings1, 4, length1), 0); CHECK (tally_strings (strings2, 8, length2), 2); fprintf (stderr, "%d tests conducted.\n", tests); fprintf (stderr, "%d errors encountered.\n", errors); if (errors) fprintf (stderr, "FAILED!\n"); else fprintf (stderr, "PASSED.\n"); return errors; } // main