1 /*
2  * Copyright (c) 2013, Google, Inc. All rights reserved
3  *
4  * Use of this source code is governed by a MIT-style
5  * license that can be found in the LICENSE file or at
6  * https://opensource.org/licenses/MIT
7  */
8 /*
9  * All unit tests get registered here.  A call to run_all_tests() will run
10  * them and provide results.
11  */
12 #include <lib/unittest.h>
13 
14 #include <assert.h>
15 #include <lk/console_cmd.h>
16 #include <lk/err.h>
17 
18 static struct test_case_element *test_case_list = NULL;
19 static struct test_case_element *failed_test_case_list = NULL;
20 
21 /*
22  * Registers a test case with the unit test framework.
23  */
unittest_register_test_case(struct test_case_element * elem)24 void unittest_register_test_case(struct test_case_element *elem) {
25     DEBUG_ASSERT(elem);
26     DEBUG_ASSERT(elem->next == NULL);
27     elem->next = test_case_list;
28     test_case_list = elem;
29 }
30 
31 /*
32  * Runs all registered test cases.
33  */
run_all_tests(void)34 bool run_all_tests(void) {
35     unsigned int n_tests   = 0;
36     unsigned int n_success = 0;
37     unsigned int n_failed  = 0;
38 
39     bool all_success = true;
40     struct test_case_element *current = test_case_list;
41     while (current) {
42         if (!current->test_case()) {
43             current->failed_next = failed_test_case_list;
44             failed_test_case_list = current;
45             all_success = false;
46         }
47         current = current->next;
48         n_tests++;
49     }
50 
51     if (all_success) {
52         n_success = n_tests;
53         unittest_printf("SUCCESS!  All test cases passed!\n");
54     } else {
55         struct test_case_element *failed = failed_test_case_list;
56         while (failed) {
57             struct test_case_element *failed_next =
58                     failed->failed_next;
59             failed->failed_next = NULL;
60             failed = failed_next;
61             n_failed++;
62         }
63         n_success = n_tests - n_failed;
64         failed_test_case_list = NULL;
65     }
66 
67     unittest_printf("\n====================================================\n");
68     unittest_printf  ("    CASES:  %d     SUCCESS:  %d     FAILED:  %d   ",
69                       n_tests, n_success, n_failed);
70     unittest_printf("\n====================================================\n");
71 
72     return all_success;
73 }
74 
do_unittests(int argc,const console_cmd_args * argv)75 static int do_unittests(int argc, const console_cmd_args *argv) {
76     bool result = run_all_tests();
77 
78     printf("run_all_tests returned %d\n", result);
79     return NO_ERROR;
80 }
81 
82 STATIC_COMMAND_START
83 STATIC_COMMAND("unittests", "run all unit tests", do_unittests)
84 STATIC_COMMAND("ut", "run all unit tests", do_unittests)
85 STATIC_COMMAND_END(name);
86 
87