g3log/g2log/test_unit/testing_helpers.h

121 lines
2.4 KiB
C
Raw Normal View History

2013-07-14 01:57:26 +02:00
/*
* File: test_helper__restore_logger.h
* Author: kjell
*
* Created on July 13, 2013, 4:46 PM
*/
2013-08-19 07:17:04 +02:00
#pragma once
2013-07-14 01:57:26 +02:00
#include <memory>
#include <string>
2013-08-30 08:01:07 +02:00
#include <atomic>
#include <chrono>
#include <thread>
#include <algorithm>
2013-07-14 06:59:02 +02:00
#include "g2logworker.h"
2013-07-14 01:57:26 +02:00
2013-08-19 07:17:04 +02:00
namespace testing_helpers {
bool removeFile(std::string path_to_file);
/** After initializing ScopedCout all std::couts is redirected to the buffer
@verbatim
Example:
stringstream buffer;
ScopedCout guard(&buffer);
cout << "Hello World";
ASSERT_STREQ(buffer.str().c_str(), "Hello World"); */
class ScopedOut {
std::ostream& _out_type;
std::streambuf* _old_cout;
public:
2013-08-19 07:17:04 +02:00
explicit ScopedOut(std::ostream& out_type, std::stringstream* buffer)
: _out_type(out_type)
, _old_cout(_out_type.rdbuf()) {
_out_type.rdbuf(buffer->rdbuf());
}
virtual ~ScopedOut() {
_out_type.rdbuf(_old_cout);
}
};
2013-08-19 07:17:04 +02:00
2013-08-19 07:17:04 +02:00
/// RAII cluttering files cleanup
class LogFileCleaner
2013-07-14 01:57:26 +02:00
{
private:
std::vector<std::string> logs_to_clean_;
std::mutex g_mutex;
public:
size_t size();
LogFileCleaner() {
}
virtual ~LogFileCleaner();
void addLogToClean(std::string path_to_log);
2013-07-14 01:57:26 +02:00
};
2013-08-19 07:17:04 +02:00
/** RAII temporarily replace of logger
* and restoration of original logger at scope end*/
struct RestoreFileLogger {
explicit RestoreFileLogger(std::string directory);
~RestoreFileLogger();
2013-08-19 07:17:04 +02:00
void reset();
std::unique_ptr<g2LogWorker> logger_;
2013-07-14 06:59:02 +02:00
template<typename Call, typename ... Args >
typename std::result_of<Call(Args...)>::type callToLogger(Call call, Args&&... args) {
auto func = std::bind(call, logger_.get(), std::forward<Args>(args)...);
return func();
}
2013-07-14 06:59:02 +02:00
std::string logFile() { return log_file_; }
2013-07-14 01:57:26 +02:00
private:
std::string log_file_;
2013-07-14 01:57:26 +02:00
};
struct ScopedLogger {
ScopedLogger();
virtual ~ScopedLogger();
g2LogWorker* get();
g2LogWorker* _previousWorker;
std::unique_ptr<g2LogWorker> _currentWorker;
};
2013-08-30 08:01:07 +02:00
typedef std::shared_ptr<std::atomic<bool>> AtomicBoolPtr;
typedef std::shared_ptr<std::atomic<int>> AtomicIntPtr;
struct ScopedSetTrue {
AtomicBoolPtr _flag;
AtomicIntPtr _count;
explicit ScopedSetTrue(AtomicBoolPtr flag, AtomicIntPtr count)
: _flag(flag), _count(count) {
}
void ReceiveMsg(std::string message) {
std::chrono::milliseconds wait{100};
std::this_thread::sleep_for(wait);
++(*_count);
}
~ScopedSetTrue() {
(*_flag) = true;
}
};
2013-08-19 07:17:04 +02:00
} // testing_helpers
2013-07-14 01:57:26 +02:00
2013-07-14 01:57:26 +02:00