From 44301c070e7574fc0cb11fabdbdb4c2a88fa273e Mon Sep 17 00:00:00 2001 From: Hwankyu Jhun Date: Wed, 30 Mar 2022 10:15:12 +0900 Subject: [PATCH] Fix unit tests - Use GMainLoop Change-Id: Ia9761524cbe785dca5defa48764448158f306285 Signed-off-by: Hwankyu Jhun --- unittests/service_app_test.cc | 64 +++++++++++++++++++++++++++++++++++-------- 1 file changed, 53 insertions(+), 11 deletions(-) diff --git a/unittests/service_app_test.cc b/unittests/service_app_test.cc index 87cdab9..5785ed8 100644 --- a/unittests/service_app_test.cc +++ b/unittests/service_app_test.cc @@ -16,10 +16,13 @@ #include #include +#include #include #include +#include #include +#include #include #include @@ -43,9 +46,36 @@ class ServiceAppTest : public TestFixture { ServiceAppTest() : TestFixture(std::make_unique()) {} virtual ~ServiceAppTest() {} - virtual void SetUp() {} + virtual void SetUp() { + context_ = g_main_context_new(); + loop_ = g_main_loop_new(context_, false); + } + + virtual void TearDown() { + if (loop_) { + g_main_loop_unref(loop_); + loop_ = nullptr; + } + + if (context_) { + g_main_context_unref(context_); + context_ = nullptr; + } + } + + void LoopRun() { + g_main_loop_run(loop_); + } - virtual void TearDown() {} + void LoopQuit() { + g_main_loop_quit(loop_); + } + + GMainContext* context_ = nullptr; + GMainLoop* loop_ = nullptr; + std::mutex mutex_; + std::condition_variable cond_; + bool started_ = false; }; extern "C" int __dlog_print(log_id_t log_id, int prio, const char* tag, @@ -98,29 +128,41 @@ TEST_F(ServiceAppTest, Basic) { EXPECT_THAT(ret, testing::Eq(APP_ERROR_INVALID_PARAMETER)); EXPECT_CALL(GetMock(), Run(_, _)).Times(1); - bool loop = true; + + std::unique_lock lock(mutex_); EXPECT_CALL(GetMock(), OnLoopRun()) .WillOnce(testing::Invoke([&]() { - while (loop) { - std::cout << "wait..." << std::endl; - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - } + LoopRun(); })); std::thread t([&]() { + { + std::unique_lock t_lock(mutex_); + GSource* source = g_timeout_source_new(100); + g_source_set_callback(source, [](gpointer user_data) { + auto* h = static_cast(user_data); + std::unique_lock l(h->mutex_); + h->started_ = true; + h->cond_.notify_one(); + return G_SOURCE_REMOVE; + }, this, nullptr); + g_source_attach(source, context_); + g_source_unref(source); + } + callback.create = __service_app_create_cb; - service_app_main(argc, argv, &callback, reinterpret_cast(&loop)); + service_app_main(argc, argv, &callback, this); }); - std::this_thread::sleep_for(std::chrono::milliseconds(50)); - ret = service_app_main(argc, argv, &callback, &loop); + cond_.wait(lock, [&] { return started_; }); + ret = service_app_main(argc, argv, &callback, this); EXPECT_THAT(ret, testing::Eq(APP_ERROR_ALREADY_RUNNING)); // test service_app_exit EXPECT_CALL(GetMock(), Exit()).Times(1); EXPECT_CALL(GetMock(), OnLoopExit()) .WillOnce(testing::Invoke([&]() { - loop = false; + LoopQuit(); t.join(); })); service_app_exit(); -- 2.7.4