test: Add an overall test runner
[platform/kernel/u-boot.git] / test / test-main.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright 2021 Google LLC
4  * Written by Simon Glass <sjg@chromium.org>
5  */
6
7 #include <common.h>
8 #include <console.h>
9 #include <test/test.h>
10
11 int ut_run_tests(struct unit_test_state *uts, const char *prefix,
12                  struct unit_test *tests, int count, const char *select_name)
13 {
14         struct unit_test *test;
15         int prefix_len = prefix ? strlen(prefix) : 0;
16         int found = 0;
17
18         for (test = tests; test < tests + count; test++) {
19                 const char *test_name = test->name;
20
21                 /* Remove the prefix */
22                 if (prefix && !strncmp(test_name, prefix, prefix_len))
23                         test_name += prefix_len;
24
25                 if (select_name && strcmp(select_name, test_name))
26                         continue;
27                 printf("Test: %s\n", test_name);
28                 found++;
29
30                 if (test->flags & UT_TESTF_CONSOLE_REC) {
31                         int ret = console_record_reset_enable();
32
33                         if (ret) {
34                                 printf("Skipping: Console recording disabled\n");
35                                 continue;
36                         }
37                 }
38
39                 uts->start = mallinfo();
40
41                 test->func(uts);
42         }
43         if (select_name && !found)
44                 return -ENOENT;
45
46         return uts->fail_count ? -EBADF : 0;
47 }
48
49 int ut_run_list(const char *category, const char *prefix,
50                 struct unit_test *tests, int count, const char *select_name)
51 {
52         struct unit_test_state uts = { .fail_count = 0 };
53         int ret;
54
55         if (!select_name)
56                 printf("Running %d %s tests\n", count, category);
57
58         ret = ut_run_tests(&uts, prefix, tests, count, select_name);
59
60         if (ret == -ENOENT)
61                 printf("Test '%s' not found\n", select_name);
62         else
63                 printf("Failures: %d\n", uts.fail_count);
64
65         return ret;
66 }