Improve harness
[ctestharness.git] / src / harness.c
blob5e07ea0a00b20fb910f2d896c92d169fb2860fbe
1 #include <stdio.h>
2 #include "harness.h"
4 #define MAX_TESTS 1024
6 struct harness_cfg *cfg = NULL;
7 struct harness_test tests[MAX_TESTS] = {0};
9 int
10 harness_init(struct harness_cfg *harness_cfg)
12 if (harness_cfg == NULL) {
13 (void)fprintf(stderr, "harness: harness_cfg cannot be NULL\n");
14 return (1);
16 if (harness_cfg->setup == NULL || harness_cfg->teardown == NULL) {
17 (void)fprintf(stderr, "harness: setup or teardown functions "
18 "cannot be NULL\n");
19 return (1);
22 cfg = harness_cfg;
23 return (0);
26 int
27 harness_add_test(char *test_name, test_function *test, void *user_data)
29 if (cfg->ntests >= MAX_TESTS) {
30 (void)fprintf(stderr, "harness: Unable to add more tests\n");
31 return (1);
33 tests[cfg->ntests].test_functions = test;
34 tests[cfg->ntests].test_name = test_name;
35 tests[cfg->ntests].user_data = user_data;
36 cfg->ntests++;
38 return (0);
41 void
42 harness_run(void *user_data)
44 int res, npass, nfail;
46 cfg->setup(user_data);
47 (void)fprintf(stdout, "[----------] Test environment set-up.\n");
49 res = npass = nfail = 0;
50 (void)fprintf(stdout, "[==========] Running %d test cases.\n",
51 cfg->ntests);
52 for (int i = 0; i < cfg->ntests; i++) {
53 res = tests[i].test_functions(tests[i].user_data);
54 if (res == 0) {
55 (void)fprintf(stdout, "[ %8s ] %s\n", "OK",
56 tests[i].test_name);
57 npass++;
58 } else {
59 (void)fprintf(stdout, "[ %8s ] %s\n", "NOK",
60 tests[i].test_name);
61 nfail++;
65 (void)fprintf(stdout, "[==========] %d test cases ran.\n", cfg->ntests);
66 (void)fprintf(stdout, "[ PASSED ] %d tests.\n", npass);
67 (void)fprintf(stdout, "[ FAILED ] %d tests.\n", nfail);
69 cfg->teardown(user_data);
70 (void)fprintf(stdout, "[----------] Test environment teardown.\n");