test: Call test_pre/post_run() from driver model tests
[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 DECLARE_GLOBAL_DATA_PTR;
12
13 int test_pre_run(struct unit_test_state *uts, struct unit_test *test)
14 {
15         /* DM tests have already done this */
16         if (!(test->flags & UT_TESTF_DM))
17                 uts->start = mallinfo();
18
19         if (test->flags & UT_TESTF_CONSOLE_REC) {
20                 int ret = console_record_reset_enable();
21
22                 if (ret) {
23                         printf("Skipping: Console recording disabled\n");
24                         return -EAGAIN;
25                 }
26         }
27
28         return 0;
29 }
30
31 int test_post_run(struct unit_test_state *uts, struct unit_test *test)
32 {
33         gd->flags &= ~GD_FLG_RECORD;
34
35         return 0;
36 }
37
38 int ut_run_tests(struct unit_test_state *uts, const char *prefix,
39                  struct unit_test *tests, int count, const char *select_name)
40 {
41         struct unit_test *test;
42         int prefix_len = prefix ? strlen(prefix) : 0;
43         int found = 0;
44
45         for (test = tests; test < tests + count; test++) {
46                 const char *test_name = test->name;
47                 int ret;
48
49                 /* Remove the prefix */
50                 if (prefix && !strncmp(test_name, prefix, prefix_len))
51                         test_name += prefix_len;
52
53                 if (select_name && strcmp(select_name, test_name))
54                         continue;
55                 printf("Test: %s\n", test_name);
56                 found++;
57
58                 ret = test_pre_run(uts, test);
59                 if (ret == -EAGAIN)
60                         continue;
61                 if (ret)
62                         return ret;
63
64                 test->func(uts);
65
66                 ret = test_post_run(uts, test);
67                 if (ret)
68                         return ret;
69         }
70         if (select_name && !found)
71                 return -ENOENT;
72
73         return uts->fail_count ? -EBADF : 0;
74 }
75
76 int ut_run_list(const char *category, const char *prefix,
77                 struct unit_test *tests, int count, const char *select_name)
78 {
79         struct unit_test_state uts = { .fail_count = 0 };
80         int ret;
81
82         if (!select_name)
83                 printf("Running %d %s tests\n", count, category);
84
85         ret = ut_run_tests(&uts, prefix, tests, count, select_name);
86
87         if (ret == -ENOENT)
88                 printf("Test '%s' not found\n", select_name);
89         else
90                 printf("Failures: %d\n", uts.fail_count);
91
92         return ret;
93 }