-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLoggerTests.cpp
More file actions
84 lines (69 loc) · 2.03 KB
/
Copy pathLoggerTests.cpp
File metadata and controls
84 lines (69 loc) · 2.03 KB
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
/// @file
/// @brief Unit tests for the shared console logger (shared/Logger.h), covering file mirroring.
// Unit tests for the shared console logger (shared/Logger.h). The console/color side needs a
// real console, so these cover the file-mirroring behavior: level tagging and the timestamp
// prefix. The logger is scoped so its destructor closes the file before it is read back.
#include <gtest/gtest.h>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <string>
#include "Logger.h"
namespace
{
namespace fs = std::filesystem;
/// Reads and returns the entire contents of the file at `path` as a string.
std::string ReadAll(const fs::path& path)
{
std::ifstream in(path);
std::stringstream ss;
ss << in.rdbuf();
return ss.str();
}
/// Fixture providing a fresh temp log path, removed before and after each test.
class LoggerTest : public ::testing::Test
{
protected:
fs::path logPath;
void SetUp() override
{
logPath = fs::temp_directory_path() / "sg_logger_test.log";
std::error_code ec;
fs::remove(logPath, ec);
}
void TearDown() override
{
std::error_code ec;
fs::remove(logPath, ec);
}
};
TEST_F(LoggerTest, MirrorsLinesToFileWithLevel)
{
{
Shared::Logger logger;
logger.attachConsole(logPath.string());
logger.info("hello world");
logger.error("boom");
}
const std::string contents = ReadAll(logPath);
EXPECT_NE(contents.find("[INFO] hello world"), std::string::npos);
EXPECT_NE(contents.find("[ERROR] boom"), std::string::npos);
}
TEST_F(LoggerTest, PrefixesEachLineWithATimestamp)
{
{
Shared::Logger logger;
logger.attachConsole(logPath.string());
logger.info("x");
}
const std::string contents = ReadAll(logPath);
ASSERT_FALSE(contents.empty());
EXPECT_EQ(contents.front(), '['); // [HH:MM:SS] ...
EXPECT_NE(contents.find("] [INFO] x"), std::string::npos);
}
TEST(LoggerNoFileTest, LoggingWithoutAFileIsSafe)
{
Shared::Logger logger; // no attachConsole → no log file
EXPECT_NO_THROW(logger.info("no file"));
}
} // namespace