#include #include #include #include #include TEST(SingleThread, Configuration) { vptyp::Logger l; EXPECT_NO_THROW(l.configure({"apprx", "size", "time"})); EXPECT_NO_THROW(l.add("apprx", 123)); EXPECT_ANY_THROW(l.add("not in configuration", 123)); } TEST(SingleThread, Add) { vptyp::Logger l; std::ostringstream s; std::queue> prev; l.configure({"apprx", "size", "time"}, s); auto decorator = [&l, &prev](std::string field, int value) { l.add(field, value); prev.push({field, value}); }; decorator("size", 1); decorator("time", 1); sleep(1); decorator("apprx", 12); decorator("size", 2); sleep(1); // results auto d = s.rdbuf()->view(); std::string_view view; while (view = d.substr(0, d.find('\n')), view.size() > 0) { if (prev.empty()) break; size_t res{0}; while (res != view.npos) { auto nextAwaiting = prev.front(); res = view.find(nextAwaiting.first); if (res != view.npos) prev.pop(); } } EXPECT_EQ(prev.empty(), true); } TEST(MultiThread, Configure) { vptyp::Logger l; std::atomic howManyConfigured; auto fConfig = [&l, &howManyConfigured] { bool res{false}; EXPECT_NO_THROW(res = l.configure({"apprx", "size", "time"})); howManyConfigured.fetch_add(static_cast(res)); }; // simulate race condition configure std::vector threads(10); for (auto& thread : threads) { thread = std::jthread(fConfig); } threads.clear(); EXPECT_EQ(howManyConfigured.load(), 1); } TEST(MultiThread, Add) { vptyp::Logger l; std::ostringstream s; std::mutex mtx; std::queue> prev; l.configure({"apprx", "size", "time"}, s); auto decorator = [&l, &prev, &mtx](std::string field, int value) { for (auto i = 0; i < 100; ++i) { l.add(field, value); { std::lock_guard g(mtx); prev.push({field, value}); } } }; std::vector threads(10); for (auto& thread : threads) { thread = std::jthread(decorator, "apprx", rand() % 100); } threads.clear(); sleep(1); // results auto d = s.rdbuf()->view(); std::string_view view; while (view = d.substr(0, d.find('\n')), view.size() > 0) { if (prev.empty()) break; size_t res{0}; while (res != view.npos) { auto nextAwaiting = prev.front(); res = view.find(nextAwaiting.first); if (res != view.npos) prev.pop(); } } EXPECT_EQ(prev.empty(), true); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }