1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
|
//-----------------------------------------------------------------------------
/** @file libboardgame_test/Test.cpp
@author Markus Enzenberger
@copyright GNU General Public License version 3 or later */
//-----------------------------------------------------------------------------
#include "Test.h"
#include <map>
#include "libboardgame_base/Assert.h"
#include "libboardgame_base/Log.h"
namespace libboardgame_test {
//-----------------------------------------------------------------------------
namespace {
map<string, TestFunction>& get_all_tests()
{
static map<string, TestFunction> all_tests;
return all_tests;
}
string get_fail_msg(const char* file, int line, const string& s)
{
ostringstream msg;
msg << file << ":" << line << ": " << s;
return msg.str();
}
} // namespace
//-----------------------------------------------------------------------------
TestFail::TestFail(const char* file, int line, const string& s)
: logic_error(get_fail_msg(file, line, s))
{
}
//-----------------------------------------------------------------------------
void add_test(const string& name, const TestFunction& function)
{
auto& all_tests = get_all_tests();
LIBBOARDGAME_ASSERT(all_tests.find(name) == all_tests.end());
all_tests.insert({name, function});
}
bool run_all_tests()
{
unsigned nu_fail = 0;
LIBBOARDGAME_LOG("Running ", get_all_tests().size(), " tests...");
for (auto& i : get_all_tests())
{
try
{
(i.second)();
}
catch (const TestFail& e)
{
LIBBOARDGAME_LOG(e.what());
++nu_fail;
}
}
if (nu_fail == 0)
{
LIBBOARDGAME_LOG("OK");
return true;
}
LIBBOARDGAME_LOG(nu_fail, " tests failed.\nFAIL");
return false;
}
bool run_test(const string& name)
{
for (auto& i : get_all_tests())
if (i.first == name)
{
LIBBOARDGAME_LOG("Running ", name, "...");
try
{
(i.second)();
LIBBOARDGAME_LOG("OK");
return true;
}
catch (const TestFail& e)
{
LIBBOARDGAME_LOG(e.what(), "\nFAIL");
return false;
}
}
LIBBOARDGAME_LOG("Test not found: ", name);
return false;
}
//-----------------------------------------------------------------------------
} // namespace libboardgame_test
|