/** * index-of-utest.c - unit tests for the index_of procedure. */ #include #include #include #include "int-testing-tools.h" #include "string-testing-tools.h" // +-----------+------------------------------------------------------ // | Constants | // +-----------+ /** The size of the array we use for testing. */ #define SIZE 16 // +-----------+------------------------------------------------------ // | Variables | // +-----------+ /** * A count of errors. */ static int errors = 0; // +---------+-------------------------------------------------------- // | Helpers | // +---------+ void int_check (int values[], int size, int value, int expected) { int result = index_of (values, size, value); if (result != expected) { printf ("In searching for %d in the size %d array, " "expected %d, got %d.\n", value, size, expected, result); ++errors; } } // int_check void string_check (char *values[], int size, char *value, int expected) { int result = string_index_of (values, size, value); if (result != expected) { printf ("In searching for %s in the size %d array, " "expected %d, got %d.\n", value, size, expected, result); ++errors; } } // string_check // +-------------+---------------------------------------------------- // | Typed Tests | // +-------------+ /** * Some tests using integer arrays. * Strategy: Build the array { 0, 2, 4, 6, 8, ... } * Even numbers of the form 2*i should be at position i. * Odd numbers should not be in the array. */ void int_tests () { int i; int values[SIZE]; // Fill values with 0 2 4 6 8 .... for (i = 0; i < SIZE; i++) values[i] = 2 * i; int_check (values, SIZE, -1, -1); for (i = 0; i < SIZE; i++) { int_check (values, SIZE, 2*i, i); int_check (values, SIZE, 2*i+1, -1); } } // int_tests /** * Some tests using arrays of strings. * Strategy: Build the array { "B", "D", "F", "H", "J", ... } * The string whose one letter is 'B' + 2*i should be at position * i. * All other strings should not be in the array. */ void string_tests () { int i; char strings0[12][2]; char *strings[12]; char str[2]; str[1] = 0; // Fill in strings for (i = 0; i < 12; i++) { strings0[i][0] = 'B' + 2*i; strings0[i][1] = 0; strings[i] = strings0[i]; } // for // Systematic checks "A" ... "Y" string_check (strings, 12, "A", -1); for (i = 0; i < 12; i++) { str[0] = 'B' + 2*i; string_check (strings, 12, (char *) str, i); str[0] += 1; string_check (strings, 12, (char *) str, -1); } // Some other checks string_check (strings, 12, "", -1); string_check (strings, 12, "b", -1); string_check (strings, 12, "BB", -1); } // string_tests // +------+----------------------------------------------------------- // | Main | // +------+ int main () { // Run the tests int_tests (); string_tests (); // Check for errors. if (errors) printf ("%d errors encountered.\n", errors); return errors; } // main