#include#include "myfunc.h" #include START_TEST(myfunc_test) { ck_assert(myfunc(2, 3) == 5); ck_assert(myfunc(0, 0) == 0); } END_TEST Suite *myfunc_suite(void) { Suite *s; TCase *tc_core; s = suite_create("myfunc"); tc_core = tcase_create("Core"); tcase_add_test(tc_core, myfunc_test); suite_add_tcase(s, tc_core); return s; } int main(void) { int num_failed; Suite *s; SRunner *sr; s = myfunc_suite(); sr = srunner_create(s); srunner_run_all(sr, CK_NORMAL); num_failed = srunner_ntests_failed(sr); srunner_free(sr); return (num_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; }
#includeIn this example, we define a simple C program called `myprog()` that reads two integers from the user and prints their sum to stdout. We write an integration test for this program using the `START_TEST()` and `END_TEST` macros provided by the go github.com.pingcap.check C Check package. We redirect stdout to a file using the `fmemopen()` and `stdout` techniques, to capture the program's output. We then check that the output matches our expected output using the `ck_assert_str_eq()` macro. Finally, we run our tests using the `SRunner` and `srunner_run_all()` functions.#include #include "myprog.h" #include START_TEST(myprog_test) { char *input = "2 3\n"; char *expected_output = "The sum is: 5\n"; char *output = malloc(256 * sizeof(char)); FILE *f = fmemopen(output, 256, "w"); ck_assert(f != NULL); /* Redirect stdout to our file */ stdout = f; /* Call our program with the input */ myprog(input); /* Flush stdout to our file */ fflush(stdout); /* Reset stdout */ stdout = fdopen(1, "w"); /* Check that the output matches the expected output */ ck_assert_str_eq(output, expected_output); } END_TEST Suite *myprog_suite(void) { Suite *s; TCase *tc_core; s = suite_create("myprog"); tc_core = tcase_create("Core"); tcase_add_test(tc_core, myprog_test); suite_add_tcase(s, tc_core); return s; } int main(void) { int num_failed; Suite *s; SRunner *sr; s = myprog_suite(); sr = srunner_create(s); srunner_run_all(sr, CK_NORMAL); num_failed = srunner_ntests_failed(sr); srunner_free(sr); return (num_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; }