test: don't throw from the destructor of DebugLogHelper

Throwing an exception from the destructor of a class is a bad practice,
avoid that and instead print the message to the standard error output
and call `std::abort()`.
This commit is contained in:
Vasil Dimov
2022-12-23 10:03:26 +01:00
parent d20f10affb
commit d6aa266d43
2 changed files with 14 additions and 12 deletions

View File

@@ -8,7 +8,8 @@
#include <noui.h>
#include <tinyformat.h>
#include <stdexcept>
#include <cstdlib>
#include <iostream>
DebugLogHelper::DebugLogHelper(std::string message, MatchFn match)
: m_message{std::move(message)}, m_match(std::move(match))
@@ -21,11 +22,12 @@ DebugLogHelper::DebugLogHelper(std::string message, MatchFn match)
noui_test_redirect();
}
void DebugLogHelper::check_found()
DebugLogHelper::~DebugLogHelper()
{
noui_reconnect();
LogInstance().DeleteCallback(m_print_connection);
if (!m_found && m_match(nullptr)) {
throw std::runtime_error(strprintf("'%s' not found in debug log\n", m_message));
tfm::format(std::cerr, "Fatal error: expected message not found in the debug log: '%s'\n", m_message);
std::abort();
}
}

View File

@@ -13,10 +13,7 @@
class DebugLogHelper
{
const std::string m_message;
bool m_found{false};
std::list<std::function<void(const std::string&)>>::iterator m_print_connection;
public:
//! Custom match checking function.
//!
//! Invoked with pointers to lines containing matching strings, and with
@@ -27,13 +24,16 @@ class DebugLogHelper
//! (2) raising an error in check_found if no match was found
//! Can return false to do the opposite in either case.
using MatchFn = std::function<bool(const std::string* line)>;
MatchFn m_match;
void check_found();
public:
explicit DebugLogHelper(std::string message, MatchFn match = [](const std::string*){ return true; });
~DebugLogHelper() noexcept(false) { check_found(); }
~DebugLogHelper();
private:
const std::string m_message;
bool m_found{false};
std::list<std::function<void(const std::string&)>>::iterator m_print_connection;
MatchFn m_match;
};
#define ASSERT_DEBUG_LOG(message) DebugLogHelper UNIQUE_NAME(debugloghelper)(message)