/** * ibs-utest.c * Sam's quick and dirty unit test for binary search. */ #include #include #include "ibs.h" int tests = 0; int errors = 0; void test (int size) { int A[size]; int i; int result; for (i = 0; i < size; i++) A[i] = 2*i; for (i = 0; i < size; i++) { // Even value should be there. ++tests; result = ibs (A, size, 2*i); if (result != i) { fprintf (stderr, "Searching for %d in size %d, expected %d, got %d\n", 2*i, size, i, result); ++errors; } // Odd value should not be there ++tests; result = ibs (A, size, 2*i - 1); if (result != -1) { fprintf (stderr, "Searching for %d in size %d, expected -1, got %d\n", 2*i-1, size, result); ++errors; } } // for ++tests; result = ibs (A, size, 2*size - 1); if (result != -1) { fprintf (stderr, "Searching for %d in size %d, expected -1, got %d\n", 2*size-1, size, result); ++errors; } } // test /** * empty_test does some funky things with the bounds of the array. */ void empty_test () { int vals[] = { 1, 2 }; ++tests; if (ibs (vals, 0, 1) != -1) { fprintf (stderr, "Found value in empty array (case 1).\n"); ++errors; } if (ibs (vals, 0, 0) != -1) { fprintf (stderr, "Found value in empty array (case 2).\n"); } if (ibs (vals, 0, 2) != -1) { fprintf (stderr, "Found value in empty array (case 3).\n"); } } // empty_test int main (void) { // Primary tests int j; for (j = 0; j < 33; j++) test (j); // A few additional tests empty_test (); // Report results fprintf (stderr, "%d tests conducted.\n", tests); fprintf (stderr, "%d errors encountered.\n", errors); return errors; } // main