blob: c234b4f45efcd6ae41f98532d34b5fc08842d542 [file] [log] [blame]
Matt Spinler635de8c2020-09-24 13:51:40 -05001#include "logger.hpp"
2
3#include <gtest/gtest.h>
4
5using namespace phosphor::fan;
6using namespace std::literals::string_literals;
7
8TEST(LoggerTest, Test)
9{
10 const auto logSize = 5;
11
12 Logger logger{logSize};
13
14 for (int i = 0; i < logSize; i++)
15 {
16 logger.log("Test Message "s + std::to_string(i));
17 }
18
19 auto messages = logger.getLogs();
20
21 ASSERT_EQ(messages.size(), logSize);
22
23 EXPECT_EQ((messages[0][1].get<std::string>()), "Test Message 0");
24 EXPECT_EQ((messages[1][1].get<std::string>()), "Test Message 1");
25 EXPECT_EQ((messages[2][1].get<std::string>()), "Test Message 2");
26 EXPECT_EQ((messages[3][1].get<std::string>()), "Test Message 3");
27 EXPECT_EQ((messages[4][1].get<std::string>()), "Test Message 4");
28
29 // There isn't really a way to verify the timestamp, but
30 // it can at least be printed.
31 for (const auto& msg : messages)
32 {
33 std::cout << "Timestamp: " << msg[0] << "\n";
34 }
35
36 // Add another message, it should purge the first one
37 logger.log("New Message");
38
39 messages = logger.getLogs();
40 ASSERT_EQ(messages.size(), logSize);
41
42 // Check the first and last
43 EXPECT_EQ((messages[0][1].get<std::string>()), "Test Message 1");
44 EXPECT_EQ((messages[4][1].get<std::string>()), "New Message");
45
46 auto path = logger.saveToTempFile();
47 ASSERT_TRUE(std::filesystem::exists(path));
48
49 std::ifstream file{path};
50
51 // check that valid JSON was written
52 auto newJSON = nlohmann::json::parse(file);
53 EXPECT_EQ(newJSON["Logs"].size(), logSize);
54 std::filesystem::remove(path);
55
56 logger.clear();
57 messages = logger.getLogs();
58 EXPECT_TRUE(messages.empty());
59}