2 Copyright (C) 2016-2020 Free Software Foundation, Inc.
4 This file is part of GDB.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19 #include "common-defs.h"
20 #include "common-exceptions.h"
21 #include "common-debug.h"
27 /* All the tests that have been registered. Using an std::map allows keeping
28 the order of tests stable and easily looking up whether a test name
31 static std::map<std::string, std::unique_ptr<selftest>> tests;
33 /* A selftest that calls the test function without arguments. */
35 struct simple_selftest : public selftest
37 simple_selftest (self_test_function *function_)
38 : function (function_)
41 void operator() () const override
46 self_test_function *function;
52 register_test (const std::string &name, selftest *test)
54 /* Check that no test with this name already exist. */
55 gdb_assert (tests.find (name) == tests.end ());
57 tests[name] = std::unique_ptr<selftest> (test);
63 register_test (const std::string &name, self_test_function *function)
65 register_test (name, new simple_selftest (function));
71 run_tests (const char *filter)
73 int ran = 0, failed = 0;
75 for (const auto &pair : tests)
77 const std::string &name = pair.first;
78 const std::unique_ptr<selftest> &test = pair.second;
80 if (filter != NULL && *filter != '\0'
81 && name.find (filter) == std::string::npos)
86 debug_printf (_("Running selftest %s.\n"), name.c_str ());
90 catch (const gdb_exception_error &ex)
93 debug_printf ("Self test failed: %s\n", ex.what ());
99 debug_printf (_("Ran %d unit tests, %d failed\n"),
103 /* See selftest.h. */
105 void for_each_selftest (for_each_selftest_ftype func)
107 for (const auto &pair : tests)
111 } // namespace selftests