/* * Simple example of a CUnit unit test. * * This program (crudely) demonstrates a very simple "black box" * test of the standard library functions fprintf() and fread(). * It uses suite initialization and cleanup functions to open * and close a common temporary file used by the test functions. * The test functions then write to and read from the temporary * file in the course of testing the library functions. * * The 2 test functions are added to a single CUnit suite, and * then run using the CUnit Basic interface. The output of the * program (on CUnit version 2.0-2) is: * * CUnit : A Unit testing framework for C. * http://cunit.sourceforge.net/ * * Suite: Suite_1 * Test: test of fprintf() ... passed * Test: test of fread() ... passed * * --Run Summary: Type Total Ran Passed Failed * suites 1 1 n/a 0 * tests 2 2 2 0 * asserts 5 5 5 0 */ #include #include #include "CUnit/Basic.h" #include /* Pointer to the file used by the tests. */ static FILE* temp_file = NULL; /* The suite initialization function. * Opens the temporary file used by the tests. * Returns zero on success, non-zero otherwise. */ int init_suite_expr(void) { fo_libfo_init (); if (NULL == (temp_file = fopen("temp.txt", "w+"))) { return -1; } else { return 0; } } /* The suite cleanup function. * Closes the temporary file used by the tests. * Returns zero on success, non-zero otherwise. */ int clean_suite_expr(void) { fo_libfo_shutdown (); if (0 != fclose(temp_file)) { return -1; } else { temp_file = NULL; return 0; } } /* Simple test of fprintf(). * Writes test data to the temporary file and checks * whether the expected number of bytes were written. */ static void testFPRINTF(void) { int i1 = 10; if (NULL != temp_file) { CU_ASSERT(0 == fprintf(temp_file, "")); CU_ASSERT(2 == fprintf(temp_file, "Q\n")); CU_ASSERT(7 == fprintf(temp_file, "i1 = %d", i1)); } } /* Simple test of fread(). * Reads the data previously written by testFPRINTF() * and checks whether the expected characters are present. * Must be run after testFPRINTF(). */ static void testFREAD(void) { unsigned char buffer[20]; if (NULL != temp_file) { rewind(temp_file); CU_ASSERT(9 == fread(buffer, sizeof(unsigned char), 20, temp_file)); CU_ASSERT(0 == strncmp(buffer, "Q\ni1 = 10", 9)); } } static void test_fo_expr_eval(void) { CU_ASSERT_PTR_NULL (fo_expr_eval ("test", "test", NULL, NULL, NULL, NULL, NULL, NULL, NULL)); } CU_TestInfo test_array1[] = { { "test of fprintf()1", testFPRINTF }, { "test of fread()1", testFREAD }, { "test of fo_expr_eval()", test_fo_expr_eval }, CU_TEST_INFO_NULL, }; CU_SuiteInfo suites[] = { { "fo-expr-eval", init_suite_expr, clean_suite_expr, test_array1 }, CU_SUITE_INFO_NULL, }; CU_SuiteInfo * test_fo_expr_eval_get_suites() { return suites; } /* The main() function for setting up and running the tests. * Returns a CUE_SUCCESS on successful running, another * CUnit error code on failure. */