/** * iv-utest.c * A simple unit test for int vectors. Warning! Since there is * no iv_free operation, this program will leak memory like a sieve. * Since it's hard to see memory corruption, this program does not * quite test for it. Okay, it's a sucky test, but it will suffice * for now. */ // +---------+-------------------------------------------------------- // | Headers | // +---------+ #include #include "int-vector.h" // +---------+-------------------------------------------------------- // | Globals | // +---------+ static int errors = 0; // A count of errors static int tests = 0; // A count of tests conducted // +---------+-------------------------------------------------------- // | Helpers | // +---------+ /** * BLOCK(CODE) * Wrap a block of code for cleanliness. */ #define BLOCK(CODE) do { CODE } while (0) /** * FUN(X,Y) * A function of X and Y useful for putting "interesting" values * in our arrays. */ #define FUN(X,Y) (X-3)*(Y+2) /** * 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); \ } \ ) // +------+----------------------------------------------------------- // | Main | // +------+ int main () { int size; // The size of the vector int i; // A fun counter variable struct int_vector *vec; // The vector we're using // Try a variety of sizes of vectors for (size = 1; size < 10; size++) { // Build the vector vec = iv_new (size); CHECK (iv_size (vec), size); // Set some values, at both valid and invalid positions for (i = -2; i < size+2; i++) iv_set (vec, i, FUN (i, size)); // Get some values, for (i = 0; i < size; i++) { ++tests; int result = iv_get (vec, i); if (result != FUN (i, size)) { ++errors; fprintf (stderr, "ERROR\n"); fprintf (stderr, " Expression: iv_get (vec, %d)\n", i); fprintf (stderr, " Result: %d\n", result); fprintf (stderr, " Expected: %d\n", FUN (i, size)); } // if } // for i } // for size // Report 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