From cb226b33ef7221fc26faf3221eb2553298c3dc77 Mon Sep 17 00:00:00 2001 From: msieben <4319079+msieben@users.noreply.github.com> Date: Wed, 26 Jun 2024 10:41:25 +0200 Subject: [PATCH] Development/namespaces (#1652) * [Tests/init/core] : Separate 'tests' from 'core' namespaces. Initial changes by mostly search and replace. * [Tests/unit/core] : partially revert '8a3fe02b8a9f3ff7c3672942d2ee906115420956' to include 'test_messageException' * [Tests/unit / Tests/unit/core] : Do not depend on 'IPTestAdministrator' if it not used * [Tests/unit/core] : Make explicit global namespace lookup * [DOC] Singletons section (#1540) * singleton section added * singletons documentation section added * singletons.md added to mkdocs.yml * warning fixed * formating fix * singletons description addded * [doc] description of singletons added * Update singletons.md --------- Co-authored-by: MFransen69 <39826971+MFransen69@users.noreply.github.com> * [Actions] Adding process containers with runC backend to be built in the Linux workflow (#1655) * Fixing warnings in RunC process containers * Adding containers to Actions * Removing PROCESSCONTAINERS_CLIB option as it was the same as RunC * Temporarily using a template from development to test the changes * Using sizeof to get the size of a buffer instead of a fixed value which did not match the buffer size on top of that * Changing back to use template from master * [Tests/unit/core] : more use of full nested namespaces * [Tests/unit/core] : remove 'using' in 'test_hash' * Revert "[Tests/unit / Tests/unit/core] : Do not depend on 'IPTestAdministrator' if it not used" This reverts commit 7ac03350fc14b77f7ab4596d56893551b8d86797. --------- Co-authored-by: Piotr Czekaj Co-authored-by: MFransen69 <39826971+MFransen69@users.noreply.github.com> Co-authored-by: Mateusz Daniluk <121170681+VeithMetro@users.noreply.github.com> --- Tests/unit/core/test_cyclicbuffer.cpp | 411 +- Tests/unit/core/test_databuffer.cpp | 18 +- Tests/unit/core/test_dataelement.cpp | 189 +- Tests/unit/core/test_dataelementfile.cpp | 111 +- Tests/unit/core/test_doorbell.cpp | 33 +- Tests/unit/core/test_enumerate.cpp | 47 +- Tests/unit/core/test_event.cpp | 171 +- Tests/unit/core/test_filesystem.cpp | 165 +- Tests/unit/core/test_frametype.cpp | 79 +- Tests/unit/core/test_hash.cpp | 166 +- Tests/unit/core/test_hex2strserialization.cpp | 17 +- Tests/unit/core/test_ipc.cpp | 327 +- Tests/unit/core/test_ipcclient.cpp | 25 +- Tests/unit/core/test_iso639.cpp | 38 +- Tests/unit/core/test_iterator.cpp | 11 +- Tests/unit/core/test_jsonparser.cpp | 568 +-- Tests/unit/core/test_keyvalue.cpp | 75 +- Tests/unit/core/test_library.cpp | 51 +- Tests/unit/core/test_library_helloworld.cpp | 35 +- Tests/unit/core/test_lockablecontainer.cpp | 71 +- Tests/unit/core/test_measurementtype.cpp | 5 +- Tests/unit/core/test_memberavailability.cpp | 111 +- Tests/unit/core/test_messageException.cpp | 31 +- Tests/unit/core/test_message_dispatcher.cpp | 80 +- Tests/unit/core/test_message_unit.cpp | 924 ++-- Tests/unit/core/test_networkinfo.cpp | 185 +- Tests/unit/core/test_nodeid.cpp | 44 +- Tests/unit/core/test_numbertype.cpp | 175 +- Tests/unit/core/test_optional.cpp | 57 +- Tests/unit/core/test_parser.cpp | 111 +- Tests/unit/core/test_portability.cpp | 167 +- Tests/unit/core/test_processinfo.cpp | 76 +- Tests/unit/core/test_queue.cpp | 11 +- Tests/unit/core/test_rangetype.cpp | 15 +- Tests/unit/core/test_readwritelock.cpp | 26 +- Tests/unit/core/test_rectangle.cpp | 61 +- Tests/unit/core/test_rpc.cpp | 110 +- Tests/unit/core/test_semaphore.cpp | 203 +- Tests/unit/core/test_sharedbuffer.cpp | 59 +- Tests/unit/core/test_singleton.cpp | 89 +- Tests/unit/core/test_socketstreamjson.cpp | 84 +- Tests/unit/core/test_socketstreamtext.cpp | 25 +- Tests/unit/core/test_statetrigger.cpp | 56 +- Tests/unit/core/test_stopwatch.cpp | 121 +- Tests/unit/core/test_synchronize.cpp | 89 +- Tests/unit/core/test_synchronous.cpp | 276 +- Tests/unit/core/test_systeminfo.cpp | 939 ++-- Tests/unit/core/test_textfragment.cpp | 97 +- Tests/unit/core/test_textreader.cpp | 33 +- Tests/unit/core/test_thread.cpp | 25 +- Tests/unit/core/test_threadpool.cpp | 2391 +++++----- Tests/unit/core/test_time.cpp | 4154 +++++++++-------- Tests/unit/core/test_timer.cpp | 29 +- Tests/unit/core/test_tracing.cpp | 545 +-- Tests/unit/core/test_tristate.cpp | 41 +- Tests/unit/core/test_valuerecorder.cpp | 229 +- Tests/unit/core/test_weblinkjson.cpp | 98 +- Tests/unit/core/test_weblinktext.cpp | 60 +- Tests/unit/core/test_websocketjson.cpp | 64 +- Tests/unit/core/test_websockettext.cpp | 28 +- Tests/unit/core/test_workerpool.cpp | 2587 +++++----- Tests/unit/core/test_xgetopt.cpp | 79 +- 62 files changed, 8742 insertions(+), 8456 deletions(-) diff --git a/Tests/unit/core/test_cyclicbuffer.cpp b/Tests/unit/core/test_cyclicbuffer.cpp index 91f16ca5f1..bda7fb48d7 100644 --- a/Tests/unit/core/test_cyclicbuffer.cpp +++ b/Tests/unit/core/test_cyclicbuffer.cpp @@ -28,8 +28,8 @@ #include "../IPTestAdministrator.h" namespace Thunder { -namespace Core { namespace Tests { +namespace Core { struct Data { bool shareable; @@ -57,31 +57,31 @@ namespace Tests { struct stat st; if (lstat(fileName, &st) == 0) { - if ((mode & Core::File::USER_READ) != (st.st_mode & S_IRUSR)) { + if ((mode & ::Thunder::Core::File::Mode::USER_READ) != (st.st_mode & S_IRUSR)) { valid = false; } - else if ((mode & Core::File::USER_WRITE) != (st.st_mode & S_IWUSR)) { + else if ((mode & ::Thunder::Core::File::Mode::USER_WRITE) != (st.st_mode & S_IWUSR)) { valid = false; } - else if ((mode & Core::File::USER_EXECUTE) != (st.st_mode & S_IXUSR)) { + else if ((mode & ::Thunder::Core::File::Mode::USER_EXECUTE) != (st.st_mode & S_IXUSR)) { valid = false; } - else if ((mode & Core::File::GROUP_READ) != (st.st_mode & S_IRGRP)) { + else if ((mode & ::Thunder::Core::File::Mode::GROUP_READ) != (st.st_mode & S_IRGRP)) { valid = false; } - else if((mode & Core::File::GROUP_WRITE) != (st.st_mode & S_IWGRP)) { + else if((mode & ::Thunder::Core::File::Mode::GROUP_WRITE) != (st.st_mode & S_IWGRP)) { valid = false; } - else if ((mode & Core::File::GROUP_EXECUTE) != (st.st_mode & S_IXGRP)) { + else if ((mode & ::Thunder::Core::File::GROUP_EXECUTE) != (st.st_mode & S_IXGRP)) { valid = false; } - else if ((mode & Core::File::OTHERS_READ) != (st.st_mode & S_IROTH)) { + else if ((mode & ::Thunder::Core::File::OTHERS_READ) != (st.st_mode & S_IROTH)) { valid = false; } - else if((mode & Core::File::OTHERS_WRITE) != (st.st_mode & S_IWOTH)) { + else if((mode & ::Thunder::Core::File::OTHERS_WRITE) != (st.st_mode & S_IWOTH)) { valid = false; } - else if ((mode & Core::File::OTHERS_EXECUTE) != (st.st_mode & S_IXOTH)) { + else if ((mode & ::Thunder::Core::File::OTHERS_EXECUTE) != (st.st_mode & S_IXOTH)) { valid = false; } else { valid = true; @@ -134,13 +134,13 @@ namespace Tests { const uint32_t MaxSignalWaitTime = 1000; // In milliseconds static void* ThreadToCheckBufferIsSharable(void* data) { - CyclicBuffer* buffer = static_cast(data); + ::Thunder::Core::CyclicBuffer* buffer = static_cast<::Thunder::Core::CyclicBuffer*>(data); uint32_t written = buffer->Write(reinterpret_cast(SampleData), sizeof(SampleData)); static bool shareable = (written == sizeof(SampleData)); pthread_exit(&shareable); } - bool CheckBufferIsSharable(CyclicBuffer* buffer) + bool CheckBufferIsSharable(::Thunder::Core::CyclicBuffer* buffer) { void *status = nullptr; pthread_t threadID; @@ -149,14 +149,14 @@ namespace Tests { return ((status != nullptr) ? *(static_cast(status)) : false); } - class ThreadLock : public Thread { + class ThreadLock : public ::Thunder::Core::Thread { public: ThreadLock() = delete; ThreadLock(const ThreadLock&) = delete; ThreadLock& operator=(const ThreadLock&) = delete; - ThreadLock(CyclicBuffer& cyclicBuffer, uint32_t waitTime, Event& event) - : Thread(Thread::DefaultStackSize(), _T("Test2")) + ThreadLock(::Thunder::Core::CyclicBuffer& cyclicBuffer, uint32_t waitTime, ::Thunder::Core::Event& event) + : ::Thunder::Core::Thread(::Thunder::Core::Thread::DefaultStackSize(), _T("Test2")) , _event(event) , _waitTime(waitTime) , _cyclicBuffer(cyclicBuffer) @@ -174,32 +174,32 @@ namespace Tests { _event.SetEvent(); Block(); } - return (infinite); + return (::Thunder::Core::infinite); } private: - Event& _event; + ::Thunder::Core::Event& _event; uint32_t _waitTime; - CyclicBuffer& _cyclicBuffer; + ::Thunder::Core::CyclicBuffer& _cyclicBuffer; }; - class CyclicBufferTest : public CyclicBuffer { + class CyclicBufferTest : public ::Thunder::Core::CyclicBuffer { public: - CyclicBufferTest() = delete; - CyclicBufferTest(const CyclicBufferTest&) = delete; + CyclicBufferTest() = delete; + CyclicBufferTest(const CyclicBufferTest&) = delete; CyclicBufferTest& operator=(const CyclicBufferTest&) = delete; - CyclicBufferTest(const string& fileName, const uint32_t mode, const uint32_t bufferSize, const bool overwrite) - : CyclicBuffer(fileName, mode, bufferSize, overwrite) + CyclicBufferTest(const string& fileName, const uint32_t mode, const uint32_t bufferSize, const bool overwrite) + : ::Thunder::Core::CyclicBuffer(fileName, mode, bufferSize, overwrite) { } - CyclicBufferTest(DataElementFile& dataElementFile, const bool initiator, const uint32_t offset, const uint32_t bufferSize, const bool overwrite) - : CyclicBuffer(dataElementFile, initiator, offset, bufferSize, overwrite) + CyclicBufferTest(::Thunder::Core::DataElementFile& dataElementFile, const bool initiator, const uint32_t offset, const uint32_t bufferSize, const bool overwrite) + : ::Thunder::Core::CyclicBuffer(dataElementFile, initiator, offset, bufferSize, overwrite) { } ~CyclicBufferTest() = default; - /* virtual */ uint32_t GetOverwriteSize(Cursor& cursor) override + /* virtual */ uint32_t GetOverwriteSize(::Thunder::Core::CyclicBuffer::Cursor& cursor) override { while (cursor.Offset() < cursor.Size()) { uint16_t chunkSize = 0; @@ -214,15 +214,15 @@ namespace Tests { TEST(Core_CyclicBuffer, Create) { const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::CREATE | Core::File::SHAREABLE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::Mode::CREATE | ::Thunder::Core::File::Mode::SHAREABLE; { std::string bufferName {"cyclicbuffer01"}; uint8_t cyclicBufferSize = 50; - // Create CyclicBuffer with Size 50 - CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); + // Create::Thunder::Core::CyclicBuffer with Size 50 + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); EXPECT_STREQ(buffer.Name().c_str(), bufferName.c_str()); EXPECT_EQ(buffer.Size(), cyclicBufferSize); @@ -230,7 +230,7 @@ namespace Tests { EXPECT_EQ(buffer.Open(), true); // Check File Size - EXPECT_EQ(FileSize(bufferName.c_str()), (cyclicBufferSize + sizeof(CyclicBuffer::control))); + EXPECT_EQ(FileSize(bufferName.c_str()), (cyclicBufferSize + sizeof(::Thunder::Core::CyclicBuffer::control))); // Remove after usage before destruction buffer.Close(); @@ -242,7 +242,7 @@ namespace Tests { // Overwrite Buffer with Create uint8_t cyclicBufferSize = 100; std::string bufferName {"cyclicbuffer02"}; - CyclicBuffer buffer1(bufferName.c_str(), mode, cyclicBufferSize, false); + ::Thunder::Core::CyclicBuffer buffer1(bufferName.c_str(), mode, cyclicBufferSize, false); EXPECT_STREQ(buffer1.Name().c_str(), bufferName.c_str()); EXPECT_EQ(buffer1.Size(), cyclicBufferSize); @@ -254,7 +254,7 @@ namespace Tests { // Create cyclic buffer with same name to check overwritting or not cyclicBufferSize = 20; - CyclicBuffer buffer2(bufferName.c_str(), mode, cyclicBufferSize, false); + ::Thunder::Core::CyclicBuffer buffer2(bufferName.c_str(), mode, cyclicBufferSize, false); EXPECT_STREQ(buffer2.Name().c_str(), bufferName.c_str()); EXPECT_EQ(buffer2.Size(), cyclicBufferSize); @@ -269,14 +269,14 @@ namespace Tests { TEST(Core_CyclicBuffer, CheckAccessOnStorageFile) { const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::CREATE | Core::File::SHAREABLE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::Mode::CREATE | ::Thunder::Core::File::Mode::SHAREABLE; std::string bufferName {"cyclicbuffer01"}; uint8_t cyclicBufferSize = 50; - // Create CyclicBuffer with Size 50 - CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); + // Create::Thunder::Core::CyclicBuffer with Size 50 + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); EXPECT_STREQ(buffer.Name().c_str(), bufferName.c_str()); EXPECT_STREQ(buffer.Storage().Name().c_str(), bufferName.c_str()); @@ -295,11 +295,11 @@ namespace Tests { std::string bufferName {"cyclicbuffer01"}; const uint8_t cyclicBufferSize = 50; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::OTHERS_READ | Core::File::OTHERS_WRITE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::Mode::OTHERS_READ | ::Thunder::Core::File::Mode::OTHERS_WRITE; - CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); EXPECT_STREQ(buffer.Name().c_str(), bufferName.c_str()); EXPECT_EQ(buffer.Size(), cyclicBufferSize); @@ -315,10 +315,10 @@ namespace Tests { std::string bufferName {"cyclicbuffer01"}; const uint8_t cyclicBufferSize = 50; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::SHAREABLE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::SHAREABLE; - CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); EXPECT_STREQ(buffer.Name().c_str(), bufferName.c_str()); EXPECT_EQ(buffer.Size(), cyclicBufferSize); @@ -336,10 +336,10 @@ namespace Tests { std::string bufferName {"cyclicbuffer01"}; const uint8_t cyclicBufferSize = 50; const uint32_t mode = - Core::File::USER_WRITE | - Core::File::OTHERS_READ | Core::File::OTHERS_WRITE; + ::Thunder::Core::File::Mode::USER_WRITE | + ::Thunder::Core::File::Mode::OTHERS_READ | ::Thunder::Core::File::Mode::OTHERS_WRITE; - CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); EXPECT_STREQ(buffer.Name().c_str(), bufferName.c_str()); EXPECT_EQ(buffer.Size(), cyclicBufferSize); @@ -356,10 +356,10 @@ namespace Tests { std::string bufferName {"cyclicbuffer01"}; const uint8_t cyclicBufferSize = 50; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE; - CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); EXPECT_STREQ(buffer.Name().c_str(), bufferName.c_str()); EXPECT_EQ(buffer.Size(), cyclicBufferSize); @@ -379,9 +379,9 @@ namespace Tests { std::string bufferName {"cyclicbuffer01"}; const uint8_t cyclicBufferSize = 50; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE ; - CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE ; + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); EXPECT_STREQ(buffer.Name().c_str(), bufferName.c_str()); EXPECT_EQ(buffer.Size(), cyclicBufferSize); EXPECT_EQ(buffer.IsValid(), true); @@ -402,9 +402,9 @@ namespace Tests { std::string bufferName {"cyclicbuffer01"}; const uint8_t cyclicBufferSize = 20; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::SHAREABLE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::Mode::SHAREABLE; CyclicBufferTest buffer(bufferName.c_str(), mode, cyclicBufferSize, true); EXPECT_STREQ(buffer.Name().c_str(), bufferName.c_str()); @@ -444,9 +444,9 @@ namespace Tests { std::string bufferName {"cyclicbuffer01"}; const uint8_t cyclicBufferSize = 50; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE ; - CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE ; + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); EXPECT_STREQ(buffer.Name().c_str(), bufferName.c_str()); EXPECT_EQ(buffer.Size(), cyclicBufferSize); EXPECT_EQ(buffer.IsValid(), true); @@ -489,9 +489,9 @@ namespace Tests { std::string bufferName {"cyclicbuffer01"}; const uint8_t cyclicBufferSize = 50; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE ; - CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE ; + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); EXPECT_STREQ(buffer.Name().c_str(), bufferName.c_str()); EXPECT_EQ(buffer.Size(), cyclicBufferSize); EXPECT_EQ(buffer.IsValid(), true); @@ -541,9 +541,9 @@ namespace Tests { std::string bufferName {"cyclicbuffer01"}; const uint8_t cyclicBufferSize = 10; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE ; - CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE ; + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); EXPECT_STREQ(buffer.Name().c_str(), bufferName.c_str()); EXPECT_EQ(buffer.Size(), cyclicBufferSize); EXPECT_EQ(buffer.IsValid(), true); @@ -573,9 +573,9 @@ namespace Tests { std::string bufferName {"cyclicbuffer01"}; const uint8_t cyclicBufferSize = 50; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE ; - CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE ; + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); EXPECT_STREQ(buffer.Name().c_str(), bufferName.c_str()); EXPECT_EQ(buffer.Size(), cyclicBufferSize); EXPECT_EQ(buffer.IsValid(), true); @@ -586,24 +586,24 @@ namespace Tests { EXPECT_EQ(buffer.Free(), cyclicBufferSize - (sizeof(SampleData))); EXPECT_EQ(buffer.Reserve(0), 0u); - EXPECT_EQ(buffer.Reserve(51), Core::ERROR_INVALID_INPUT_LENGTH); + EXPECT_EQ(buffer.Reserve(51), ::Thunder::Core::ERROR_INVALID_INPUT_LENGTH); // Remove after usage before destruction buffer.Close(); } TEST(Core_CyclicBuffer, Using_DataElementFile) { const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::CREATE | Core::File::SHAREABLE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::CREATE | ::Thunder::Core::File::Mode::SHAREABLE; { std::string fileName {"cyclicbuffer01"}; uint8_t cyclicBufferSize = 50; - uint8_t cyclicBufferWithControlDataSize = cyclicBufferSize + sizeof(CyclicBuffer::control); - DataElementFile dataElementFile(fileName, mode, cyclicBufferWithControlDataSize); - // Create CyclicBuffer with Size 50 - CyclicBuffer buffer(dataElementFile, true, 0, cyclicBufferWithControlDataSize, false); + uint8_t cyclicBufferWithControlDataSize = cyclicBufferSize + sizeof(::Thunder::Core::CyclicBuffer::control); + ::Thunder::Core::DataElementFile dataElementFile(fileName, mode, cyclicBufferWithControlDataSize); + // Create::Thunder::Core::CyclicBuffer with Size 50 + ::Thunder::Core::CyclicBuffer buffer(dataElementFile, true, 0, cyclicBufferWithControlDataSize, false); EXPECT_STREQ(buffer.Name().c_str(), fileName.c_str()); EXPECT_EQ(buffer.Size(), cyclicBufferSize); @@ -623,18 +623,18 @@ namespace Tests { TEST(Core_CyclicBuffer, Using_DataElementFile_WithOffset) { const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::CREATE | Core::File::SHAREABLE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::CREATE | ::Thunder::Core::File::Mode::SHAREABLE; { std::string fileName {"cyclicbuffer01"}; uint8_t cyclicBufferSize = 50; uint32_t offset = 56; - uint8_t cyclicBufferWithControlDataSize = cyclicBufferSize + sizeof(CyclicBuffer::control); - DataElementFile dataElementFile(fileName, mode, cyclicBufferWithControlDataSize + offset); - // Create CyclicBuffer with Size 50 - CyclicBuffer buffer(dataElementFile, true, offset, cyclicBufferWithControlDataSize, false); + uint8_t cyclicBufferWithControlDataSize = cyclicBufferSize + sizeof(::Thunder::Core::CyclicBuffer::control); + ::Thunder::Core::DataElementFile dataElementFile(fileName, mode, cyclicBufferWithControlDataSize + offset); + // Create::Thunder::Core::CyclicBuffer with Size 50 + ::Thunder::Core::CyclicBuffer buffer(dataElementFile, true, offset, cyclicBufferWithControlDataSize, false); EXPECT_STREQ(buffer.Name().c_str(), fileName.c_str()); EXPECT_EQ(buffer.Size(), cyclicBufferSize); @@ -654,18 +654,18 @@ namespace Tests { TEST(Core_CyclicBuffer, Using_DataElementFile_WithInvalidOffset) { const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::CREATE | Core::File::SHAREABLE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::CREATE | ::Thunder::Core::File::Mode::SHAREABLE; { std::string fileName {"cyclicbuffer01"}; uint8_t cyclicBufferSize = 50; uint32_t offset = 50; - uint8_t cyclicBufferWithControlDataSize = cyclicBufferSize + sizeof(CyclicBuffer::control); - DataElementFile dataElementFile(fileName, mode, cyclicBufferWithControlDataSize + offset); - // Create CyclicBuffer with Size 50 - CyclicBuffer buffer(dataElementFile, true, offset, cyclicBufferWithControlDataSize, false); + uint8_t cyclicBufferWithControlDataSize = cyclicBufferSize + sizeof(::Thunder::Core::CyclicBuffer::control); + ::Thunder::Core::DataElementFile dataElementFile(fileName, mode, cyclicBufferWithControlDataSize + offset); + // Create::Thunder::Core::CyclicBuffer with Size 50 + ::Thunder::Core::CyclicBuffer buffer(dataElementFile, true, offset, cyclicBufferWithControlDataSize, false); EXPECT_STREQ(buffer.Name().c_str(), fileName.c_str()); EXPECT_EQ(buffer.IsValid(), false); @@ -686,10 +686,10 @@ namespace Tests { std::string bufferName {"cyclicbuffer01"}; const uint8_t cyclicBufferSize = 10; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE ; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE ; - CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); EXPECT_EQ(buffer.IsOverwrite(), false); EXPECT_EQ(buffer.Size(), cyclicBufferSize); @@ -728,11 +728,11 @@ namespace Tests { std::string bufferName {"cyclicbuffer01"}; const uint8_t cyclicBufferSize = 100; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::SHAREABLE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::Mode::SHAREABLE; - CyclicBufferTest buffer(bufferName.c_str(), mode, cyclicBufferSize, true); + CyclicBufferTest buffer(bufferName.c_str(), mode, cyclicBufferSize, true); EXPECT_STREQ(buffer.Name().c_str(), bufferName.c_str()); EXPECT_EQ(buffer.Size(), cyclicBufferSize); EXPECT_EQ(buffer.IsValid(), true); @@ -828,11 +828,11 @@ namespace Tests { static int ClonedProcessFunc(void* arg) { Data* data = static_cast(arg); uint32_t cyclicBufferSize = 10; - uint32_t shareableFlag = (data->shareable == true) ? Core::File::SHAREABLE : 0; + uint32_t shareableFlag = (data->shareable == true) ? ::Thunder::Core::File::Mode::SHAREABLE : 0; - CyclicBuffer buffer(data->bufferName.c_str(), - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | shareableFlag, + ::Thunder::Core::CyclicBuffer buffer(data->bufferName.c_str(), + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | shareableFlag, cyclicBufferSize, false); buffer.Write(reinterpret_cast(SampleData), sizeof(SampleData)); @@ -870,11 +870,11 @@ namespace Tests { SetSharePermissionsFromClonedProcess(bufferName, shareable); uint32_t cyclicBufferSize = 0; - uint32_t shareableFlag = (shareable == true) ? Core::File::SHAREABLE : 0; + uint32_t shareableFlag = (shareable == true) ? ::Thunder::Core::File::Mode::SHAREABLE : 0; - CyclicBuffer buffer(bufferName.c_str(), - Core::File::USER_READ | Core::File::USER_WRITE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | shareableFlag, cyclicBufferSize, false); EXPECT_EQ(buffer.Used(), ((shareable == true) ? sizeof(SampleData) : 0)); @@ -906,10 +906,10 @@ namespace Tests { std::string bufferName {"cyclicbuffer01"}; const uint32_t CyclicBufferSize = 10; - uint32_t shareableFlag = (shareable == true) ? Core::File::SHAREABLE : 0; + uint32_t shareableFlag = (shareable == true) ? ::Thunder::Core::File::Mode::SHAREABLE : 0; const uint32_t mode = - (Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | + (::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | shareableFlag); struct Data data; @@ -925,11 +925,11 @@ namespace Tests { uint32_t cyclicBufferSize = CyclicBufferSize; uint8_t loadBuffer[cyclicBufferSize + 1]; - CyclicBufferTest* buffer = nullptr; - DataElementFile* dataElementFile = nullptr; + CyclicBufferTest* buffer = nullptr; + ::Thunder::Core::DataElementFile* dataElementFile = nullptr; if (data->usingDataElementFile == true) { - uint8_t cyclicBufferWithControlDataSize = cyclicBufferSize + sizeof(CyclicBuffer::control); - dataElementFile = new DataElementFile(bufferName, data->mode | Core::File::CREATE, cyclicBufferWithControlDataSize + data->offset); + uint8_t cyclicBufferWithControlDataSize = cyclicBufferSize + sizeof(::Thunder::Core::CyclicBuffer::control); + dataElementFile = new ::Thunder::Core::DataElementFile(bufferName, data->mode | ::Thunder::Core::File::CREATE, cyclicBufferWithControlDataSize + data->offset); buffer = new CyclicBufferTest(*dataElementFile, true, data->offset, cyclicBufferWithControlDataSize, false); } else { buffer = new CyclicBufferTest(bufferName, data->mode, cyclicBufferSize, false); @@ -992,16 +992,16 @@ namespace Tests { uint32_t cyclicBufferSize = CyclicBufferSize; uint8_t loadBuffer[cyclicBufferSize]; - CyclicBufferTest* buffer; - DataElementFile* dataElementFile = nullptr; + CyclicBufferTest* buffer; + ::Thunder::Core::DataElementFile* dataElementFile = nullptr; if (usingDataElementFile == true) { - dataElementFile = new DataElementFile(bufferName, mode, 0); + dataElementFile = new ::Thunder::Core::DataElementFile(bufferName, mode, 0); buffer = new CyclicBufferTest(*dataElementFile, false, offset, 0, false); } else { buffer = new CyclicBufferTest(bufferName, mode, 0, false); } - EXPECT_EQ(buffer->Size(), static_cast(((shareable == true) ? CyclicBufferSize : 0))); + EXPECT_EQ(buffer->Size(), static_cast(((shareable == true) ?CyclicBufferSize : 0))); testAdmin.Sync("setup client"); if (shareable == true) { @@ -1038,7 +1038,7 @@ namespace Tests { } } - Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } TEST(Core_CyclicBuffer, CheckSharePermissionsFromForkedProcessWithoutOverwrite) { @@ -1063,11 +1063,11 @@ namespace Tests { uint32_t cyclicBufferSize = 0; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::SHAREABLE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::Mode::SHAREABLE; - CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); testAdmin.Sync("setup server"); testAdmin.Sync("client wrote"); @@ -1080,7 +1080,7 @@ namespace Tests { testAdmin.Sync("server read"); string data = "klmnopq"; result = buffer.Reserve(data.size()); - EXPECT_EQ(result, ERROR_INVALID_INPUT_LENGTH); + EXPECT_EQ(result, ::Thunder::Core::ERROR_INVALID_INPUT_LENGTH); result = buffer.Write(reinterpret_cast(data.c_str()), data.size()); EXPECT_EQ(result, 0u); @@ -1111,11 +1111,11 @@ namespace Tests { uint32_t cyclicBufferSize = 10; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::SHAREABLE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::Mode::SHAREABLE; - CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); testAdmin.Sync("setup client"); testAdmin.Sync("setup server"); @@ -1147,7 +1147,7 @@ namespace Tests { buffer.Close(); } - Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } TEST(Core_CyclicBuffer, WithOverWriteUsingFork) { @@ -1157,11 +1157,11 @@ namespace Tests { uint32_t cyclicBufferSize = 10; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::SHAREABLE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::Mode::SHAREABLE; - CyclicBufferTest buffer(bufferName.c_str(), mode, cyclicBufferSize, true); + CyclicBufferTest buffer(bufferName.c_str(), mode, cyclicBufferSize, true); testAdmin.Sync("setup server"); testAdmin.Sync("setup client"); @@ -1202,11 +1202,11 @@ namespace Tests { uint32_t cyclicBufferSize = 0; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::SHAREABLE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::Mode::SHAREABLE; - CyclicBufferTest buffer(bufferName.c_str(), mode, cyclicBufferSize, true); + CyclicBufferTest buffer(bufferName.c_str(), mode, cyclicBufferSize, true); testAdmin.Sync("setup client"); testAdmin.Sync("server wrote"); @@ -1230,7 +1230,7 @@ namespace Tests { testAdmin.Sync("server read"); buffer.Close(); } - Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } TEST(Core_CyclicBuffer, WithOverwriteUsingForksReversed) { @@ -1241,11 +1241,11 @@ namespace Tests { testAdmin.Sync("setup server"); const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::SHAREABLE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::Mode::SHAREABLE; - CyclicBufferTest buffer(bufferName.c_str(), mode, cyclicBufferSize, true); + CyclicBufferTest buffer(bufferName.c_str(), mode, cyclicBufferSize, true); EXPECT_TRUE(buffer.IsOverwrite()); testAdmin.Sync("setup client"); @@ -1293,11 +1293,11 @@ namespace Tests { { uint32_t cyclicBufferSize = 10; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::SHAREABLE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::Mode::SHAREABLE; - CyclicBufferTest buffer(bufferName.c_str(), mode, cyclicBufferSize, true); + CyclicBufferTest buffer(bufferName.c_str(), mode, cyclicBufferSize, true); EXPECT_TRUE(buffer.IsOverwrite()); EXPECT_TRUE(buffer.IsValid()); @@ -1344,17 +1344,17 @@ namespace Tests { buffer.Close(); } - Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } TEST(Core_CyclicBuffer, LockUnlock_WithoutDataPresent) { string bufferName = "cyclicbuffer01"; uint32_t cyclicBufferSize = 10; - CyclicBuffer buffer(bufferName.c_str(), - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::SHAREABLE, cyclicBufferSize, false); + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::Mode::SHAREABLE, cyclicBufferSize, false); buffer.Lock(); EXPECT_EQ(buffer.IsLocked(), true); @@ -1367,10 +1367,10 @@ namespace Tests { string bufferName = "cyclicbuffer01"; uint32_t cyclicBufferSize = 10; - CyclicBuffer buffer(bufferName.c_str(), - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::SHAREABLE, cyclicBufferSize, false); + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::Mode::SHAREABLE, cyclicBufferSize, false); buffer.Lock(); EXPECT_EQ(buffer.IsLocked(), true); @@ -1389,11 +1389,11 @@ namespace Tests { uint32_t cyclicBufferSize = 20; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::SHAREABLE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::Mode::SHAREABLE; - CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); testAdmin.Sync("setup server"); testAdmin.Sync("setup client"); @@ -1441,11 +1441,11 @@ namespace Tests { uint32_t cyclicBufferSize = 0; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::SHAREABLE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::Mode::SHAREABLE; - CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, true); + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, true); EXPECT_EQ(buffer.LockPid(), 0u); testAdmin.Sync("setup client"); @@ -1484,7 +1484,7 @@ namespace Tests { buffer.Close(); } - Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } //TODO: revisit these test cases after fixing the issues with cyclicbuffer lock/unlock sequence TEST(Core_CyclicBuffer, DISABLED_LockUnlock_FromParentAndForks_WithDataPresent) @@ -1495,11 +1495,11 @@ namespace Tests { uint32_t cyclicBufferSize = 20; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::SHAREABLE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::Mode::SHAREABLE; - CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); testAdmin.Sync("setup server"); testAdmin.Sync("setup client"); @@ -1517,12 +1517,12 @@ namespace Tests { EXPECT_EQ(buffer.IsLocked(), false); EXPECT_NE(buffer.Used(), 0u); - Event event(false, false); - ThreadLock threadLock(buffer, Core::infinite, event); + ::Thunder::Core::Event event(false, false); + ThreadLock threadLock(buffer, ::Thunder::Core::infinite, event); threadLock.Run(); // Lock before requesting cyclic buffer lock - if (event.Lock(MaxSignalWaitTime * 2) == Core::ERROR_NONE) { + if (event.Lock(MaxSignalWaitTime * 2) == ::Thunder::Core::ERROR_NONE) { // Seems thread is not active so re-request lock event.ResetEvent(); event.Lock(MaxSignalWaitTime); @@ -1541,13 +1541,13 @@ namespace Tests { EXPECT_EQ(buffer.Used(), 0u); EXPECT_EQ(buffer.IsLocked(), false); - Event event(false, false); - ThreadLock threadLock(buffer, Core::infinite, event); + ::Thunder::Core::Event event(false, false); + ThreadLock threadLock(buffer, ::Thunder::Core::infinite, event); threadLock.Run(); EXPECT_EQ(buffer.IsLocked(), false); // Lock before requesting cyclic buffer lock - if (event.Lock(MaxSignalWaitTime * 2) == Core::ERROR_NONE) { + if (event.Lock(MaxSignalWaitTime * 2) == ::Thunder::Core::ERROR_NONE) { // Seems thread is not active so re-request lock event.ResetEvent(); event.Lock(MaxSignalWaitTime); @@ -1591,11 +1591,11 @@ namespace Tests { uint32_t cyclicBufferSize = 0; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::SHAREABLE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::Mode::SHAREABLE; - CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, true); + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, true); testAdmin.Sync("setup client"); testAdmin.Sync("server timedLock"); @@ -1617,12 +1617,12 @@ namespace Tests { EXPECT_EQ(CheckTimeOutIsExpired(timeOutTime, waitTime), true); EXPECT_EQ(buffer.IsLocked(), false); - Event event(false, false); - ThreadLock threadLock(buffer, Core::infinite, event); + ::Thunder::Core::Event event(false, false); + ThreadLock threadLock(buffer, ::Thunder::Core::infinite, event); threadLock.Run(); // Lock before requesting cyclic buffer lock - if (event.Lock(MaxSignalWaitTime * 2) == Core::ERROR_NONE) { + if (event.Lock(MaxSignalWaitTime * 2) == ::Thunder::Core::ERROR_NONE) { // Seems thread is not active so re-request lock event.ResetEvent(); event.Lock(MaxSignalWaitTime); @@ -1645,24 +1645,24 @@ namespace Tests { testAdmin.Sync("client exit"); buffer.Close(); } - Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } TEST(Core_CyclicBuffer, DISABLED_LockUnlock_UsingAlert) { string bufferName = "cyclicbuffer01"; uint32_t cyclicBufferSize = 10; - CyclicBuffer buffer(bufferName.c_str(), - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::SHAREABLE, cyclicBufferSize, false); + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::Mode::SHAREABLE, cyclicBufferSize, false); - Event event(false, false); - ThreadLock threadLock(buffer, Core::infinite, event); + ::Thunder::Core::Event event(false, false); + ThreadLock threadLock(buffer, ::Thunder::Core::infinite, event); threadLock.Run(); // Lock before requesting cyclic buffer lock - if (event.Lock(MaxSignalWaitTime * 2) == Core::ERROR_NONE) { + if (event.Lock(MaxSignalWaitTime * 2) == ::Thunder::Core::ERROR_NONE) { // Seems thread is not active so re-request lock event.ResetEvent(); event.Lock(MaxSignalWaitTime); @@ -1687,24 +1687,24 @@ namespace Tests { uint32_t cyclicBufferSize = 20; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::SHAREABLE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::Mode::SHAREABLE; - CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, false); testAdmin.Sync("setup server"); testAdmin.Sync("setup client"); EXPECT_EQ(buffer.LockPid(), 0u); - Event event(false, false); - ThreadLock threadLock(buffer, Core::infinite, event); + ::Thunder::Core::Event event(false, false); + ThreadLock threadLock(buffer, ::Thunder::Core::infinite, event); threadLock.Run(); EXPECT_EQ(buffer.LockPid(), 0u); testAdmin.Sync("server locked"); // Lock before requesting cyclic buffer lock - if (event.Lock(MaxSignalWaitTime * 2) == Core::ERROR_NONE) { + if (event.Lock(MaxSignalWaitTime * 2) == ::Thunder::Core::ERROR_NONE) { // Seems thread is not active so re-request lock event.ResetEvent(); event.Lock(MaxSignalWaitTime); @@ -1735,11 +1735,11 @@ namespace Tests { uint32_t cyclicBufferSize = 0; const uint32_t mode = - Core::File::USER_READ | Core::File::USER_WRITE | Core::File::USER_EXECUTE | - Core::File::GROUP_READ | Core::File::GROUP_WRITE | - Core::File::SHAREABLE; + ::Thunder::Core::File::Mode::USER_READ | ::Thunder::Core::File::Mode::USER_WRITE | ::Thunder::Core::File::Mode::USER_EXECUTE | + ::Thunder::Core::File::Mode::GROUP_READ | ::Thunder::Core::File::Mode::GROUP_WRITE | + ::Thunder::Core::File::Mode::SHAREABLE; - CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, true); + ::Thunder::Core::CyclicBuffer buffer(bufferName.c_str(), mode, cyclicBufferSize, true); testAdmin.Sync("setup client"); testAdmin.Sync("server locked"); @@ -1749,14 +1749,14 @@ namespace Tests { testAdmin.Sync("server alerted"); EXPECT_EQ(buffer.LockPid(), 0u); - Event event(false, false); - ThreadLock threadLock(buffer, Core::infinite, event); + ::Thunder::Core::Event event(false, false); + ThreadLock threadLock(buffer, ::Thunder::Core::infinite, event); threadLock.Run(); EXPECT_EQ(buffer.LockPid(), 0u); testAdmin.Sync("client locked"); // Lock before requesting cyclic buffer lock - if (event.Lock(MaxSignalWaitTime * 2) == Core::ERROR_NONE) { + if (event.Lock(MaxSignalWaitTime * 2) == ::Thunder::Core::ERROR_NONE) { // Seems thread is not active so re-request lock event.ResetEvent(); event.Lock(MaxSignalWaitTime); @@ -1774,8 +1774,9 @@ namespace Tests { buffer.Close(); } - Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } -} // Tests + } // Core +} // Tests } // Thunder diff --git a/Tests/unit/core/test_databuffer.cpp b/Tests/unit/core/test_databuffer.cpp index cf8daf9990..f0ecddf2ef 100644 --- a/Tests/unit/core/test_databuffer.cpp +++ b/Tests/unit/core/test_databuffer.cpp @@ -26,20 +26,20 @@ #include namespace Thunder { -namespace Core { namespace Tests { +namespace Core { -TEST(Core_DataBuffer, simple) -{ - constexpr uint32_t blocksize = 10; + TEST(Core_DataBuffer, simple) + { + constexpr uint32_t blocksize = 10; - Thunder::Core::ScopedStorage storage; + ::Thunder::Core::ScopedStorage storage; - EXPECT_EQ(storage.Size(), blocksize); + EXPECT_EQ(storage.Size(), blocksize); - EXPECT_NE(storage.Buffer(), nullptr); -} + EXPECT_NE(storage.Buffer(), nullptr); + } -} // Tests } // Core +} // Tests } // Thunder diff --git a/Tests/unit/core/test_dataelement.cpp b/Tests/unit/core/test_dataelement.cpp index 3585277391..c9f63f979d 100644 --- a/Tests/unit/core/test_dataelement.cpp +++ b/Tests/unit/core/test_dataelement.cpp @@ -25,95 +25,100 @@ #include -using namespace Thunder; -using namespace Thunder::Core; - -TEST(test_data, simple_data) -{ - const uint8_t arr[] = {10,20,30,40,50,60,70,80,90,100}; - const uint16_t len = 5; - const uint16_t off = 0; - DataStore obj1; - obj1.Copy(arr,len,off); - uint32_t size = 1024; - EXPECT_EQ(obj1.Size(),size); - obj1.Size(1025); - EXPECT_EQ(*obj1.Buffer(),10); - - uint8_t arr1[] = {10,20,30,40,50,60,70,80,90,100}; - const uint64_t s = 10; - DataElement obj_sample; - DataElement obj2(s,arr1); - DataElement obj_operator = obj2; - uint32_t crc = 4134036294; - EXPECT_EQ(obj2.CRC32(0,10),crc); - EXPECT_TRUE(obj2.Copy(obj2,0)); - - uint64_t alloc_size = 10; - EXPECT_EQ(obj2.AllocatedSize(), alloc_size); - EXPECT_TRUE(obj2.Size(sizeof(arr))); - EXPECT_TRUE(obj2.IsValid()); - EXPECT_EQ(*obj2.Buffer(),10); - - uint8_t arr2[] = {10,20,30,40,50}; - const uint8_t infom = 10; - uint64_t SearchNumber = 10; - EXPECT_EQ((obj2.SearchNumber(2,infom)),SearchNumber); - obj2.SetNumber(2,10); - uint64_t GetNumber = 10; - EXPECT_EQ((obj2.GetNumber(2)),GetNumber); - - obj2.Search(2,arr2,5); - obj2.SetBitNumber(2,5,8,10); - uint64_t GetBitNumber = 10; - EXPECT_EQ(obj2.GetBitNumber(2,5,8),GetBitNumber); - - const uint8_t val= 32; - const uint64_t offset= 0; - obj2.Set(val,offset); - obj2.Align(); - - DataElement obj(obj2); - DataElement obj3 = obj; - DataElement obj4(obj2,0,0); - - uint32_t ob_size = 10; - EXPECT_EQ(obj3.Size(),ob_size); - EXPECT_FALSE(obj3.Expand(0,0)); - EXPECT_TRUE(obj3.Shrink(0,0)); - EXPECT_FALSE(obj3.Copy(obj2)); -} - -TEST(test_linkeddata, simple_linkeddata) -{ - uint8_t arr[] = {10,20,30,40,50,60,70,80,90,100}; - uint8_t arr1[] ={}; - const uint64_t offset= 0; - DataElement objt1(10,arr); - LinkedDataElement ob1; - LinkedDataElement ob2(objt1); - LinkedDataElement ob3(ob2); - ob3.Enclosed(&ob2); - EXPECT_EQ(ob3.Enclosed(), &ob2); - ob3.SetBuffer(2,9,arr); - ob3.GetBuffer(2,9,arr1); - LinkedDataElement ob4; - ob4 = ob2; - EXPECT_EQ(ob4.Copy(offset,ob2), unsigned(10)); - EXPECT_EQ(ob2.Copy(offset,ob3), unsigned(10)); - - ob1.Enclosed(); - EXPECT_EQ(ob2.LinkedSize(), unsigned(10)); - EXPECT_EQ(ob2.LinkedElements(),unsigned(1)); -} - -TEST(test_dataParser, simple_dataParser) -{ - uint8_t arr[] = {10,20,30,40,50}; - DataElement object1(10,arr); - DataElementParser parser1(object1,0); - uint64_t size = -10; - EXPECT_TRUE(parser1.IsValid()); - EXPECT_EQ(parser1.Size(),size); - parser1.SkipBytes(2); -} +namespace Thunder { +namespace Tests { +namespace Core { + + TEST(test_data, simple_data) + { + const uint8_t arr[] = {10,20,30,40,50,60,70,80,90,100}; + const uint16_t len = 5; + const uint16_t off = 0; + ::Thunder::Core::DataStore obj1; + obj1.Copy(arr,len,off); + uint32_t size = 1024; + EXPECT_EQ(obj1.Size(),size); + obj1.Size(1025); + EXPECT_EQ(*obj1.Buffer(),10); + + uint8_t arr1[] = {10,20,30,40,50,60,70,80,90,100}; + const uint64_t s = 10; + ::Thunder::Core::DataElement obj_sample; + ::Thunder::Core::DataElement obj2(s,arr1); + ::Thunder::Core::DataElement obj_operator = obj2; + uint32_t crc = 4134036294; + EXPECT_EQ(obj2.CRC32(0,10),crc); + EXPECT_TRUE(obj2.Copy(obj2,0)); + + uint64_t alloc_size = 10; + EXPECT_EQ(obj2.AllocatedSize(), alloc_size); + EXPECT_TRUE(obj2.Size(sizeof(arr))); + EXPECT_TRUE(obj2.IsValid()); + EXPECT_EQ(*obj2.Buffer(),10); + + uint8_t arr2[] = {10,20,30,40,50}; + const uint8_t infom = 10; + uint64_t SearchNumber = 10; + EXPECT_EQ((obj2.SearchNumber(2,infom)),SearchNumber); + obj2.SetNumber(2,10); + uint64_t GetNumber = 10; + EXPECT_EQ((obj2.GetNumber(2)),GetNumber); + + obj2.Search(2,arr2,5); + obj2.SetBitNumber(2,5,8,10); + uint64_t GetBitNumber = 10; + EXPECT_EQ(obj2.GetBitNumber(2,5,8),GetBitNumber); + + const uint8_t val= 32; + const uint64_t offset= 0; + obj2.Set(val,offset); + obj2.Align(); + + ::Thunder::Core::DataElement obj(obj2); + ::Thunder::Core::DataElement obj3 = obj; + ::Thunder::Core::DataElement obj4(obj2,0,0); + + uint32_t ob_size = 10; + EXPECT_EQ(obj3.Size(),ob_size); + EXPECT_FALSE(obj3.Expand(0,0)); + EXPECT_TRUE(obj3.Shrink(0,0)); + EXPECT_FALSE(obj3.Copy(obj2)); + } + + TEST(test_linkeddata, simple_linkeddata) + { + uint8_t arr[] = {10,20,30,40,50,60,70,80,90,100}; + uint8_t arr1[] ={}; + const uint64_t offset= 0; + ::Thunder::Core::DataElement objt1(10,arr); + ::Thunder::Core::LinkedDataElement ob1; + ::Thunder::Core::LinkedDataElement ob2(objt1); + ::Thunder::Core::LinkedDataElement ob3(ob2); + ob3.Enclosed(&ob2); + EXPECT_EQ(ob3.Enclosed(), &ob2); + ob3.SetBuffer(2,9,arr); + ob3.GetBuffer(2,9,arr1); + ::Thunder::Core::LinkedDataElement ob4; + ob4 = ob2; + EXPECT_EQ(ob4.Copy(offset,ob2), unsigned(10)); + EXPECT_EQ(ob2.Copy(offset,ob3), unsigned(10)); + + ob1.Enclosed(); + EXPECT_EQ(ob2.LinkedSize(), unsigned(10)); + EXPECT_EQ(ob2.LinkedElements(),unsigned(1)); + } + + TEST(test_dataParser, simple_dataParser) + { + uint8_t arr[] = {10,20,30,40,50}; + ::Thunder::Core::DataElement object1(10,arr); + ::Thunder::Core::DataElementParser parser1(object1,0); + uint64_t size = -10; + EXPECT_TRUE(parser1.IsValid()); + EXPECT_EQ(parser1.Size(),size); + parser1.SkipBytes(2); + } + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_dataelementfile.cpp b/Tests/unit/core/test_dataelementfile.cpp index 1dffb9607c..472ee898f1 100644 --- a/Tests/unit/core/test_dataelementfile.cpp +++ b/Tests/unit/core/test_dataelementfile.cpp @@ -25,85 +25,90 @@ #include -using namespace Thunder; -using namespace Thunder::Core; +namespace Thunder { +namespace Tests { +namespace Core { -class DataFile: public Core::DataElementFile -{ -public: - DataFile() = delete; - - DataFile(File& file) - : DataElementFile(file, File::USER_READ) + class DataFile: public ::Thunder::Core::DataElementFile { - } - - DataFile(string fileName, uint32_t type, uint32_t size) - :DataElementFile(fileName, type, size) - { - } - - void MemoryMap() + public: + DataFile() = delete; + + DataFile(::Thunder::Core::File& file) + : ::Thunder::Core::DataElementFile(file, ::Thunder::Core::File::USER_READ) + { + } + + DataFile(string fileName, uint32_t type, uint32_t size) + : ::Thunder::Core::DataElementFile(fileName, type, size) + { + } + + void MemoryMap() + { + Reallocation(54); + ReopenMemoryMappedFile(); + } + }; + + TEST(test_datafile, simple_test) { - Reallocation(54); - ReopenMemoryMappedFile(); - } -}; - -TEST(test_datafile, simple_test) -{ - const string fileName = "dataFile.txt"; - const string message = ">echo 'DataElement file checking......'"; - string buffer = message + fileName; + const string fileName = "dataFile.txt"; + const string message = ">echo 'DataElement file checking......'"; + string buffer = message + fileName; #ifdef __POSIX__ - errno = 0; + errno = 0; #endif - File file(fileName); + ::Thunder::Core::File file(fileName); - ASSERT_FALSE(file.Exists()); + ASSERT_FALSE(file.Exists()); - // Always for a non-existing file + // Always for a non-existing file #ifdef __WINDOWS__ - EXPECT_EQ(file.ErrorCode(), static_cast(ERROR_FILE_NOT_FOUND)); + EXPECT_EQ(file.ErrorCode(), static_cast(ERROR_FILE_NOT_FOUND)); #endif #ifdef __POSIX__ - EXPECT_EQ(file.ErrorCode(), static_cast(ENOENT)); + EXPECT_EQ(file.ErrorCode(), static_cast(ENOENT)); #endif - ASSERT_TRUE(file.Create(true)); - EXPECT_EQ(file.IsOpen(), true); - EXPECT_EQ(file.Name(), fileName); + ASSERT_TRUE(file.Create(true)); + EXPECT_EQ(file.IsOpen(), true); + EXPECT_EQ(file.Name(), fileName); #ifdef __POSIX__ - errno = 0; + errno = 0; #endif - DataFile obj1(file); + DataFile obj1(file); #ifdef __WINDOWS__ - EXPECT_EQ(obj1.ErrorCode(), static_cast(ERROR_SUCCESS)); + EXPECT_EQ(obj1.ErrorCode(), static_cast(ERROR_SUCCESS)); #endif #ifdef __POSIX__ - EXPECT_EQ(obj1.ErrorCode(), static_cast(0)); + EXPECT_EQ(obj1.ErrorCode(), static_cast(0)); #endif - DataFile object(fileName, 1, 10); - DataFile obj2(fileName, 1, 50); + DataFile object(fileName, 1, 10); + DataFile obj2(fileName, 1, 50); - obj1.Sync(); - obj2.MemoryMap(); + obj1.Sync(); + obj2.MemoryMap(); - const string& name = obj1.Name(); + const string& name = obj1.Name(); - EXPECT_EQ(name.c_str(), fileName); - EXPECT_EQ(obj2.IsValid(), true); + EXPECT_EQ(name.c_str(), fileName); + EXPECT_EQ(obj2.IsValid(), true); - const File& obj1File = obj1.Storage(); - EXPECT_STREQ(obj1File.FileName().c_str(), file.FileName().c_str()); + const ::Thunder::Core::File& obj1File = obj1.Storage(); + EXPECT_STREQ(obj1File.FileName().c_str(), file.FileName().c_str()); - obj1.ReloadFileInfo(); - obj1.MemoryMap(); + obj1.ReloadFileInfo(); + obj1.MemoryMap(); + + EXPECT_TRUE(file.Destroy()); + } - EXPECT_TRUE(file.Destroy()); -} +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_doorbell.cpp b/Tests/unit/core/test_doorbell.cpp index ecc6cca21a..4b8aed5de1 100644 --- a/Tests/unit/core/test_doorbell.cpp +++ b/Tests/unit/core/test_doorbell.cpp @@ -29,21 +29,22 @@ namespace Thunder { namespace Tests { +namespace Core { TEST(Core_DoorBell, simpleSet) { std::string fileName {"/tmp/doorbell01"}; auto lambdaFunc = [fileName] (IPTestAdministrator & testAdmin) { - Core::DoorBell doorBell(fileName.c_str()); + ::Thunder::Core::DoorBell doorBell(fileName.c_str()); - EXPECT_EQ(doorBell.Wait(Core::infinite), Core::ERROR_NONE); - if (doorBell.Wait(Core::infinite) == Core::ERROR_NONE) { + EXPECT_EQ(doorBell.Wait(::Thunder::Core::infinite), ::Thunder::Core::ERROR_NONE); + if (doorBell.Wait(::Thunder::Core::infinite) == ::Thunder::Core::ERROR_NONE) { doorBell.Acknowledge(); testAdmin.Sync("First ring"); } - EXPECT_EQ(doorBell.Wait(Core::infinite), Core::ERROR_NONE); - if (doorBell.Wait(Core::infinite) == Core::ERROR_NONE) { + EXPECT_EQ(doorBell.Wait(::Thunder::Core::infinite), ::Thunder::Core::ERROR_NONE); + if (doorBell.Wait(::Thunder::Core::infinite) == ::Thunder::Core::ERROR_NONE) { doorBell.Acknowledge(); testAdmin.Sync("Second ring"); } @@ -56,22 +57,23 @@ namespace Tests { IPTestAdministrator testAdmin(otherSide); { - Core::DoorBell doorBell(fileName.c_str()); + ::Thunder::Core::DoorBell doorBell(fileName.c_str()); ::SleepMs(10); doorBell.Ring(); testAdmin.Sync("First ring"); doorBell.Ring(); testAdmin.Sync("Second ring"); } - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } TEST(Core_DoorBell, simpleSetReversed) { + + std::string fileName {"/tmp/doorbell02"}; auto lambdaFunc = [fileName] (IPTestAdministrator & testAdmin) { - - Core::DoorBell doorBell(fileName.c_str()); + ::Thunder::Core::DoorBell doorBell(fileName.c_str()); ::SleepMs(10); doorBell.Ring(); testAdmin.Sync("First ring"); @@ -85,22 +87,23 @@ namespace Tests { IPTestAdministrator testAdmin(otherSide); { - Core::DoorBell doorBell(fileName.c_str()); - EXPECT_EQ(doorBell.Wait(Core::infinite), Core::ERROR_NONE); - if (doorBell.Wait(Core::infinite) == Core::ERROR_NONE) { + ::Thunder::Core::DoorBell doorBell(fileName.c_str()); + EXPECT_EQ(doorBell.Wait(::Thunder::Core::infinite), ::Thunder::Core::ERROR_NONE); + if (doorBell.Wait(::Thunder::Core::infinite) == ::Thunder::Core::ERROR_NONE) { doorBell.Acknowledge(); testAdmin.Sync("First ring"); } - EXPECT_EQ(doorBell.Wait(Core::infinite), Core::ERROR_NONE); - if (doorBell.Wait(Core::infinite) == Core::ERROR_NONE) { + EXPECT_EQ(doorBell.Wait(::Thunder::Core::infinite), ::Thunder::Core::ERROR_NONE); + if (doorBell.Wait(::Thunder::Core::infinite) == ::Thunder::Core::ERROR_NONE) { doorBell.Acknowledge(); testAdmin.Sync("Second ring"); } doorBell.Relinquish(); } - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } +} // Core } // Tests } // Thunder diff --git a/Tests/unit/core/test_enumerate.cpp b/Tests/unit/core/test_enumerate.cpp index 8b53bd78fa..55ebf10dbe 100644 --- a/Tests/unit/core/test_enumerate.cpp +++ b/Tests/unit/core/test_enumerate.cpp @@ -28,6 +28,7 @@ namespace Thunder { namespace Tests { +namespace Core { enum class TestEnum { ONE, @@ -37,7 +38,7 @@ namespace Tests { TEST(Core_Enumerate, CheckEntries) { - Core::EnumerateType testEnum; + ::Thunder::Core::EnumerateType testEnum; EXPECT_FALSE(testEnum.IsSet()); for (int i = 0; i < 3; i++) { EXPECT_EQ(testEnum.Entry(i)->value, (i == 0 ? TestEnum::ONE : (i == 1 ? TestEnum::TWO : TestEnum::THREE))); @@ -47,7 +48,7 @@ namespace Tests { TEST(Core_Enumerate, Assignment) { - Core::EnumerateType testEnum; + ::Thunder::Core::EnumerateType testEnum; testEnum.Assignment(true, "three"); EXPECT_FALSE(testEnum.IsSet()); @@ -66,14 +67,14 @@ namespace Tests { testEnum.Clear(); EXPECT_FALSE(testEnum.IsSet()); - Core::EnumerateType testEnum1; + ::Thunder::Core::EnumerateType testEnum1; testEnum.Assignment(true, "three"); EXPECT_FALSE(testEnum != testEnum1); EXPECT_TRUE(testEnum != testEnum1.Value()); - Core::EnumerateType testEnum2(testEnum1); - Core::EnumerateType testEnum3; + ::Thunder::Core::EnumerateType testEnum2(testEnum1); + ::Thunder::Core::EnumerateType testEnum3; testEnum3 = testEnum1; EXPECT_TRUE(testEnum3 == testEnum1); testEnum3 = testEnum1.Value(); @@ -82,7 +83,7 @@ namespace Tests { TEST(Core_Enumerate, FromEnumType) { TestEnum e = TestEnum::TWO; - Core::EnumerateType testEnum(e); + ::Thunder::Core::EnumerateType testEnum(e); EXPECT_EQ(testEnum, e); EXPECT_TRUE(testEnum.IsSet()); EXPECT_EQ(testEnum.Value(), TestEnum::TWO); @@ -91,7 +92,7 @@ namespace Tests { TEST(Core_Enumerate, FromValue) { - Core::EnumerateType testEnum(1); + ::Thunder::Core::EnumerateType testEnum(1); EXPECT_TRUE(testEnum.IsSet()); EXPECT_EQ(testEnum.Value(), TestEnum::TWO); EXPECT_STREQ(testEnum.Data(), "TWO"); @@ -102,7 +103,7 @@ namespace Tests { TEST(Core_Enumerate, FromStringCaseSensitiveTrue) { - Core::EnumerateType testEnum("THREE"); + ::Thunder::Core::EnumerateType testEnum("THREE"); EXPECT_TRUE(testEnum.IsSet()); EXPECT_EQ(testEnum.Value(), TestEnum::THREE); EXPECT_STREQ(testEnum.Data(), "THREE"); @@ -110,13 +111,13 @@ namespace Tests { TEST(Core_Enumerate, FromStringCaseSensitiveFalse) { - Core::EnumerateType testEnum("three"); + ::Thunder::Core::EnumerateType testEnum("three"); EXPECT_FALSE(testEnum.IsSet()); } TEST(Core_Enumerate, FromStringCaseInsensitive) { - Core::EnumerateType testEnum("three", false); + ::Thunder::Core::EnumerateType testEnum("three", false); EXPECT_TRUE(testEnum.IsSet()); EXPECT_EQ(testEnum.Value(), TestEnum::THREE); EXPECT_STREQ(testEnum.Data(), "THREE"); @@ -124,8 +125,8 @@ namespace Tests { TEST(Core_Enumerate, FromTextFragmentCaseSensitiveTrue) { - Core::TextFragment testFragment("THREE"); - Core::EnumerateType testEnum(testFragment); + ::Thunder::Core::TextFragment testFragment("THREE"); + ::Thunder::Core::EnumerateType testEnum(testFragment); EXPECT_TRUE(testEnum.IsSet()); EXPECT_EQ(testEnum.Value(), TestEnum::THREE); EXPECT_STREQ(testEnum.Data(), "THREE"); @@ -133,23 +134,27 @@ namespace Tests { TEST(Core_Enumerate, FromTextFragmentCaseSensitiveFalse) { - Core::TextFragment testFragment("three"); - Core::EnumerateType testEnum(testFragment); + ::Thunder::Core::TextFragment testFragment("three"); + ::Thunder::Core::EnumerateType testEnum(testFragment); EXPECT_FALSE(testEnum.IsSet()); } TEST(Core_Enumerate, FromTextFragmentCaseInsensitive) { - Core::TextFragment testFragment("three"); - Core::EnumerateType testEnum(testFragment, false); + ::Thunder::Core::TextFragment testFragment("three"); + ::Thunder::Core::EnumerateType testEnum(testFragment, false); EXPECT_TRUE(testEnum.IsSet()); EXPECT_EQ(testEnum.Value(), TestEnum::THREE); EXPECT_STREQ(testEnum.Data(), "THREE"); } + +} // Core } // Tests -ENUM_CONVERSION_BEGIN(Tests::TestEnum) - { Tests::TestEnum::ONE, _TXT("ONE") }, - { Tests::TestEnum::TWO, _TXT("TWO") }, - { Tests::TestEnum::THREE, _TXT("THREE") }, -ENUM_CONVERSION_END(Tests::TestEnum) + +ENUM_CONVERSION_BEGIN(Tests::Core::TestEnum) + { Tests::Core::TestEnum::ONE, _TXT("ONE") }, + { Tests::Core::TestEnum::TWO, _TXT("TWO") }, + { Tests::Core::TestEnum::THREE, _TXT("THREE") }, +ENUM_CONVERSION_END(Tests::Core::TestEnum) + } // Thunder diff --git a/Tests/unit/core/test_event.cpp b/Tests/unit/core/test_event.cpp index 26c75096d8..468a1891ad 100644 --- a/Tests/unit/core/test_event.cpp +++ b/Tests/unit/core/test_event.cpp @@ -27,93 +27,98 @@ #include -using namespace Thunder; -using namespace Thunder::Core; - -class ThreadClass : public Core::Thread { -public: - ThreadClass() = delete; - ThreadClass(const ThreadClass&) = delete; - ThreadClass& operator=(const ThreadClass&) = delete; - - ThreadClass(Event& event, std::thread::id parentTid, bool& threadDone, volatile bool& lock, volatile bool& setEvent) - : Core::Thread(Core::Thread::DefaultStackSize(), _T("Test")) - , _threadDone(threadDone) - , _lock(lock) - , _setEvent(setEvent) - , _event(event) - , _parentTid(parentTid) +namespace Thunder { +namespace Tests { +namespace Core { + + class ThreadClass : public ::Thunder::Core::Thread { + public: + ThreadClass() = delete; + ThreadClass(const ThreadClass&) = delete; + ThreadClass& operator=(const ThreadClass&) = delete; + + ThreadClass(::Thunder::Core::Event& event, std::thread::id parentTid, bool& threadDone, volatile bool& lock, volatile bool& setEvent) + : ::Thunder::Core::Thread(::Thunder::Core::Thread::DefaultStackSize(), _T("Test")) + , _threadDone(threadDone) + , _lock(lock) + , _setEvent(setEvent) + , _event(event) + , _parentTid(parentTid) + { + } + + virtual ~ThreadClass() + { + } + + virtual uint32_t Worker() override + { + while (IsRunning() && (!_threadDone)) { + EXPECT_TRUE(_parentTid != std::this_thread::get_id()); + ::SleepMs(50); + if (_lock) { + _threadDone = true; + _lock = false; + _event.Unlock(); + }else if (_setEvent) { + _threadDone = true; + _setEvent = false; + _event.SetEvent(); + } + } + return (::Thunder::Core::infinite); + } + private: + volatile bool& _threadDone; + volatile bool& _lock; + volatile bool& _setEvent; + ::Thunder::Core::Event& _event; + std::thread::id _parentTid; + }; + + TEST(test_event, simple_event) { + ::Thunder::Core::Event event(false,true); + uint64_t timeOut(::Thunder::Core::Time::Now().Add(3).Ticks()); + uint64_t now(::Thunder::Core::Time::Now().Ticks()); + + if (now < timeOut) { + event.Lock(static_cast((timeOut - now) / ::Thunder::Core::Time::TicksPerMillisecond)); + EXPECT_FALSE(event.IsSet()); + } } - virtual ~ThreadClass() - { + TEST(test_event, unlock_event) + { + ::Thunder::Core::Event event(false,true); + std::thread::id parentTid; + bool threadDone = false; + volatile bool lock = true; + volatile bool setEvent = false; + + ThreadClass object(event, parentTid, threadDone, lock, setEvent); + object.Run(); + event.Lock(); + EXPECT_FALSE(lock); + object.Stop(); } - virtual uint32_t Worker() override + TEST(DISABLED_test_event, set_event) { - while (IsRunning() && (!_threadDone)) { - EXPECT_TRUE(_parentTid != std::this_thread::get_id()); - ::SleepMs(50); - if (_lock) { - _threadDone = true; - _lock = false; - _event.Unlock(); - }else if (_setEvent) { - _threadDone = true; - _setEvent = false; - _event.SetEvent(); - } - } - return (Core::infinite); - } -private: - volatile bool& _threadDone; - volatile bool& _lock; - volatile bool& _setEvent; - Event& _event; - std::thread::id _parentTid; -}; - -TEST(test_event, simple_event) -{ - Event event(false,true); - uint64_t timeOut(Core::Time::Now().Add(3).Ticks()); - uint64_t now(Core::Time::Now().Ticks()); - - if (now < timeOut) { - event.Lock(static_cast((timeOut - now) / Core::Time::TicksPerMillisecond)); - EXPECT_FALSE(event.IsSet()); + ::Thunder::Core::Event event(false,true); + std::thread::id parentTid; + bool threadDone = false; + volatile bool lock = false; + volatile bool setEvent = true; + + event.ResetEvent(); + ThreadClass object(event, parentTid, threadDone, lock, setEvent); + object.Run(); + event.Lock(); + EXPECT_FALSE(setEvent); + object.Stop(); } -} - -TEST(test_event, unlock_event) -{ - Event event(false,true); - std::thread::id parentTid; - bool threadDone = false; - volatile bool lock = true; - volatile bool setEvent = false; - - ThreadClass object(event, parentTid, threadDone, lock, setEvent); - object.Run(); - event.Lock(); - EXPECT_FALSE(lock); - object.Stop(); -} - -TEST(DISABLED_test_event, set_event) -{ - Event event(false,true); - std::thread::id parentTid; - bool threadDone = false; - volatile bool lock = false; - volatile bool setEvent = true; - - event.ResetEvent(); - ThreadClass object(event, parentTid, threadDone, lock, setEvent); - object.Run(); - event.Lock(); - EXPECT_FALSE(setEvent); - object.Stop(); -} + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_filesystem.cpp b/Tests/unit/core/test_filesystem.cpp index b51eb51d1c..ce68d8f0ed 100644 --- a/Tests/unit/core/test_filesystem.cpp +++ b/Tests/unit/core/test_filesystem.cpp @@ -25,96 +25,101 @@ #include -using namespace Thunder; -using namespace Thunder::Core; +namespace Thunder { +namespace Tests { +namespace Core { -TEST (test_file, file) -{ - File file; - File fileObj1("Sample.txt"); - fileObj1.Create(true); - File fileObj2(fileObj1); - fileObj2.SetSize(150); + TEST (test_file, file) + { + ::Thunder::Core::File file; + ::Thunder::Core::File fileObj1("Sample.txt"); + fileObj1.Create(true); + ::Thunder::Core::File fileObj2(fileObj1); + fileObj2.SetSize(150); - EXPECT_TRUE(fileObj1.Open()); - EXPECT_TRUE(fileObj1.Append()); - EXPECT_TRUE(fileObj1.Create()); - EXPECT_TRUE(fileObj1.Create(Core::File::USER_WRITE)); - EXPECT_TRUE(fileObj1.Open(true)); + EXPECT_TRUE(fileObj1.Open()); + EXPECT_TRUE(fileObj1.Append()); + EXPECT_TRUE(fileObj1.Create()); + EXPECT_TRUE(fileObj1.Create(::Thunder::Core::File::USER_WRITE)); + EXPECT_TRUE(fileObj1.Open(true)); - char buffer[] = "New Line is added to the File."; - if (fileObj1.IsOpen()) { - fileObj1.Write(reinterpret_cast(buffer), sizeof(buffer)); - } - if (fileObj1.IsOpen()) { - fileObj1.Read(reinterpret_cast(buffer), sizeof(buffer)); - } + char buffer[] = "New Line is added to the File."; + if (fileObj1.IsOpen()) { + fileObj1.Write(reinterpret_cast(buffer), sizeof(buffer)); + } + if (fileObj1.IsOpen()) { + fileObj1.Read(reinterpret_cast(buffer), sizeof(buffer)); + } - static string fileName = file.FileName("/home/file/datafile.txt"); - EXPECT_EQ(fileName, "datafile"); - static string filenameExt = file.FileNameExtended("/home/file/datafile.txt"); - EXPECT_EQ(filenameExt, "datafile.txt"); - static string pathName = file.PathName("/home/file/datafile.txt"); - EXPECT_EQ(pathName, "/home/file/"); - static string extension = file.Extension("/home/file/datafile.txt"); - EXPECT_EQ(extension, "txt"); - fileObj1.Destroy(); -} + static string fileName = file.FileName("/home/file/datafile.txt"); + EXPECT_EQ(fileName, "datafile"); + static string filenameExt = file.FileNameExtended("/home/file/datafile.txt"); + EXPECT_EQ(filenameExt, "datafile.txt"); + static string pathName = file.PathName("/home/file/datafile.txt"); + EXPECT_EQ(pathName, "/home/file/"); + static string extension = file.Extension("/home/file/datafile.txt"); + EXPECT_EQ(extension, "txt"); + fileObj1.Destroy(); + } -TEST (test_file, file_functions) -{ - File fileObj1("Sample2.txt"); - fileObj1.Create(true); - char buffer[] = "Sample2.txt is moved to newFile.txt"; - fileObj1.Write(reinterpret_cast(buffer), sizeof(buffer)); - EXPECT_TRUE(fileObj1.IsOpen()); - EXPECT_TRUE(fileObj1.Exists()); - EXPECT_FALSE(fileObj1.IsReadOnly()); - EXPECT_FALSE(fileObj1.IsHidden()); - EXPECT_FALSE(fileObj1.IsSystem()); - EXPECT_FALSE(fileObj1.IsArchive()); - EXPECT_FALSE(fileObj1.IsDirectory()); - EXPECT_FALSE(fileObj1.IsLink()); - EXPECT_FALSE(fileObj1.IsCompressed()); - EXPECT_FALSE(fileObj1.IsEncrypted()); - uint64_t size = 0; - EXPECT_EQ(fileObj1.Size(), size); - //EXPECT_EQ(fileObj1.DuplicateHandle(), 11); TODO - EXPECT_TRUE(fileObj1.Move("newFile.txt")); - fileObj1.Destroy(); -} + TEST (test_file, file_functions) + { + ::Thunder::Core::File fileObj1("Sample2.txt"); + fileObj1.Create(true); + char buffer[] = "Sample2.txt is moved to newFile.txt"; + fileObj1.Write(reinterpret_cast(buffer), sizeof(buffer)); + EXPECT_TRUE(fileObj1.IsOpen()); + EXPECT_TRUE(fileObj1.Exists()); + EXPECT_FALSE(fileObj1.IsReadOnly()); + EXPECT_FALSE(fileObj1.IsHidden()); + EXPECT_FALSE(fileObj1.IsSystem()); + EXPECT_FALSE(fileObj1.IsArchive()); + EXPECT_FALSE(fileObj1.IsDirectory()); + EXPECT_FALSE(fileObj1.IsLink()); + EXPECT_FALSE(fileObj1.IsCompressed()); + EXPECT_FALSE(fileObj1.IsEncrypted()); + uint64_t size = 0; + EXPECT_EQ(fileObj1.Size(), size); + //EXPECT_EQ(fileObj1.DuplicateHandle(), 11); TODO + EXPECT_TRUE(fileObj1.Move("newFile.txt")); + fileObj1.Destroy(); + } -TEST (test_file, directory) -{ - string path = "home/file"; - Directory dirOne(path.c_str()); - Directory dirTwo(path.c_str(), _T("*")); - Directory dirThree = dirOne ; + TEST (test_file, directory) + { + string path = "home/file"; + ::Thunder::Core::Directory dirOne(path.c_str()); + ::Thunder::Core::Directory dirTwo(path.c_str(), _T("*")); + ::Thunder::Core::Directory dirThree = dirOne ; - EXPECT_TRUE(dirOne.CreatePath()); - EXPECT_FALSE(dirOne.Create()); - EXPECT_FALSE(dirThree.IsValid()); - EXPECT_TRUE(dirOne.Next()); + EXPECT_TRUE(dirOne.CreatePath()); + EXPECT_FALSE(dirOne.Create()); + EXPECT_FALSE(dirThree.IsValid()); + EXPECT_TRUE(dirOne.Next()); - char buffer[15]; - string currenPath = ".."; - snprintf(buffer,(path.size() + currenPath.size() + 2), "%s/%s",path.c_str(), currenPath.c_str()); + char buffer[15]; + string currenPath = ".."; + snprintf(buffer,(path.size() + currenPath.size() + 2), "%s/%s",path.c_str(), currenPath.c_str()); #ifdef BUILD_ARM - if ((dirOne.Current(), buffer) == 0) { + if ((dirOne.Current(), buffer) == 0) { #else - if (strcmp(dirOne.Current().c_str(), buffer) == 0) { + if (strcmp(dirOne.Current().c_str(), buffer) == 0) { #endif - EXPECT_EQ(dirOne.Current(), buffer); - EXPECT_EQ(dirOne.Name(), currenPath.c_str()); - } else { - currenPath = "."; - snprintf(buffer,(path.size() + currenPath.size() + 2), "%s/%s",path.c_str(), currenPath.c_str()); - EXPECT_EQ(dirOne.Current(), buffer); - EXPECT_EQ(dirOne.Name(), currenPath.c_str()); + EXPECT_EQ(dirOne.Current(), buffer); + EXPECT_EQ(dirOne.Name(), currenPath.c_str()); + } else { + currenPath = "."; + snprintf(buffer,(path.size() + currenPath.size() + 2), "%s/%s",path.c_str(), currenPath.c_str()); + EXPECT_EQ(dirOne.Current(), buffer); + EXPECT_EQ(dirOne.Name(), currenPath.c_str()); + } + + EXPECT_TRUE(dirOne.IsDirectory()); + dirOne.Reset(); + EXPECT_TRUE(dirOne.Next()); + system("rm -rf home"); } - EXPECT_TRUE(dirOne.IsDirectory()); - dirOne.Reset(); - EXPECT_TRUE(dirOne.Next()); - system("rm -rf home"); -} +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_frametype.cpp b/Tests/unit/core/test_frametype.cpp index d79c8a3580..b8b9efd2f4 100644 --- a/Tests/unit/core/test_frametype.cpp +++ b/Tests/unit/core/test_frametype.cpp @@ -25,43 +25,48 @@ #include -using namespace Thunder; -using namespace Thunder::Core; +namespace Thunder { +namespace Tests { +namespace Core { -TEST(test_frame, simple_set) -{ - uint8_t arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; - uint8_t arr1[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; - const uint16_t BLOCKSIZE = 20; - FrameType obj1; - FrameType obj_copy(obj1); - FrameType<0> obj2(arr, 15); - uint16_t len = 15; - uint16_t len1 = 13; - uint16_t offset = 0; - EXPECT_EQ(obj1.SetBuffer(offset, len, arr), 17u); - EXPECT_EQ(obj1.GetBuffer(offset, len1, arr1), 17u); + TEST(test_frame, simple_set) + { + uint8_t arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; + uint8_t arr1[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; + const uint16_t BLOCKSIZE = 20; + ::Thunder::Core::FrameType obj1; + ::Thunder::Core::FrameType obj_copy(obj1); + ::Thunder::Core::FrameType<0> obj2(arr, 15); + uint16_t len = 15; + uint16_t len1 = 13; + uint16_t offset = 0; + EXPECT_EQ(obj1.SetBuffer(offset, len, arr), 17u); + EXPECT_EQ(obj1.GetBuffer(offset, len1, arr1), 17u); - FrameType::Writer obj3(obj1, offset); - obj3.Buffer(15, arr); - obj3.Copy(13, arr1); - obj3.Number(4); - obj3.Boolean(TRUE); - obj3.Text("Frametype"); - obj3.NullTerminatedText("Frametype"); + ::Thunder::Core::FrameType::Writer obj3(obj1, offset); + obj3.Buffer(15, arr); + obj3.Copy(13, arr1); + obj3.Number(4); + obj3.Boolean(TRUE); + obj3.Text("Frametype"); + obj3.NullTerminatedText("Frametype"); - obj1.Size(5000); - FrameType::Reader obj4(obj1, offset); - obj4.Buffer(15, arr); - obj4.Copy(13, arr1); - obj4.Number(); - obj4.Boolean(); - obj4.Text(); - obj4.NullTerminatedText(); - obj4.UnlockBuffer(15); - // TODO: why doesn't this work when inlining is disabled? - //obj4.Dump(); - uint32_t Size = 5000; - EXPECT_EQ(obj1.Size(), Size); - obj1.Clear(); -} + obj1.Size(5000); + ::Thunder::Core::FrameType::Reader obj4(obj1, offset); + obj4.Buffer(15, arr); + obj4.Copy(13, arr1); + obj4.Number(); + obj4.Boolean(); + obj4.Text(); + obj4.NullTerminatedText(); + obj4.UnlockBuffer(15); + // TODO: why doesn't this work when inlining is disabled? + //obj4.Dump(); + uint32_t Size = 5000; + EXPECT_EQ(obj1.Size(), Size); + obj1.Clear(); + } + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_hash.cpp b/Tests/unit/core/test_hash.cpp index 0ff9d7db82..fd87cfb7dd 100644 --- a/Tests/unit/core/test_hash.cpp +++ b/Tests/unit/core/test_hash.cpp @@ -30,6 +30,7 @@ namespace Thunder { namespace Tests { +namespace Core { std::string GetSystemHash(std::string result) { @@ -94,24 +95,23 @@ namespace Tests { return hash; } template - class SignedFileType : public Core::File { + class SignedFileType : public ::Thunder::Core::File { private: static int16_t constexpr BlockSize = 1024; public: - using HashType = HASHALGORITHM; SignedFileType(const SignedFileType&) = delete; SignedFileType& operator=(const SignedFileType&) = delete; SignedFileType() - : Core::File() + : ::Thunder::Core::File() , _hash() , _startPosition(0) { _hash.Reset(); } SignedFileType(const string& path) - : Core::File(path) + : ::Thunder::Core::File(path) , _hash() , _startPosition(0) { @@ -126,95 +126,95 @@ namespace Tests { void Open() { // Are we opening the file ? - if (Core::File::IsOpen() == false) { - if (Core::File::Open() == true) { + if (::Thunder::Core::File::IsOpen() == false) { + if (::Thunder::Core::File::Open() == true) { _startPosition = 0; - Core::File::LoadFileInfo(); - Core::File::Position(false, _startPosition); + ::Thunder::Core::File::LoadFileInfo(); + ::Thunder::Core::File::Position(false, _startPosition); } } } void Close() { - if (Core::File::IsOpen() == true) { - Core::File::Close(); + if (::Thunder::Core::File::IsOpen() == true) { + ::Thunder::Core::File::Close(); } } - inline HashType& Hash() + inline HASHALGORITHM& Hash() { return (_hash); } - inline const HashType& Hash() const + inline const HASHALGORITHM& Hash() const { return (_hash); } void CreateFileData(const uint8_t data, const uint32_t length) { - if (Core::File::Create() == true) { + if (::Thunder::Core::File::Create() == true) { Write(data, length); } } void AppendFileData(const uint8_t data, const uint32_t length) { - Core::File::Append(); + ::Thunder::Core::File::Append(); Write(data, length); } void AppendFileData(const uint8_t data[], const uint32_t length) { - Core::File::Append(); + ::Thunder::Core::File::Append(); Write(data, length); } void ReadFileData(const int64_t position, uint8_t data[], uint32_t& length) { - if (Core::File::IsOpen() != true) { + if (::Thunder::Core::File::IsOpen() != true) { Open(); } - if (Core::File::IsOpen() == true) { - int64_t currentPosition = Core::File::Position(); - Core::File::Position(false, position); - length = Core::File::Read(data, length); - Core::File::Position(false, currentPosition); + if (::Thunder::Core::File::IsOpen() == true) { + int64_t currentPosition = ::Thunder::Core::File::Position(); + ::Thunder::Core::File::Position(false, position); + length = ::Thunder::Core::File::Read(data, length); + ::Thunder::Core::File::Position(false, currentPosition); } } void DestroyFile() { - if (Core::File::IsOpen() == true) { + if (::Thunder::Core::File::IsOpen() == true) { Close(); } - Core::File::Destroy(); + ::Thunder::Core::File::Destroy(); } int64_t FileSize() { - Core::File::LoadFileInfo(); - return Core::File::Size(); + ::Thunder::Core::File::LoadFileInfo(); + return ::Thunder::Core::File::Size(); } uint32_t CalculateHash(const uint32_t start, const uint32_t end) { - uint32_t status = Core::ERROR_NONE; - HashType& hash = _hash; + uint32_t status = ::Thunder::Core::ERROR_NONE; + HASHALGORITHM& hash = _hash; uint8_t buffer[64]; - if (Core::File::IsOpen() != true) { + if (::Thunder::Core::File::IsOpen() != true) { Open(); } - if (Core::File::IsOpen() == true) { - if ((start < Core::File::Size()) && (end <= Core::File::Size())) { - uint32_t pos = Core::File::Position(); + if (::Thunder::Core::File::IsOpen() == true) { + if ((start < ::Thunder::Core::File::Size()) && (end <= ::Thunder::Core::File::Size())) { + uint32_t pos = ::Thunder::Core::File::Position(); uint32_t size = end; - Core::File::Position(false, start); + ::Thunder::Core::File::Position(false, start); // Read all Data to calculate the HASH/HMAC while (size > 0) { uint16_t chunk = std::min(static_cast(sizeof(buffer)), static_cast(size)); - Core::File::Read(buffer, chunk); + ::Thunder::Core::File::Read(buffer, chunk); hash.Input(buffer, chunk); size -= chunk; } - Core::File::Position(false, pos); + ::Thunder::Core::File::Position(false, pos); } else { - status = Core::ERROR_GENERAL; + status = ::Thunder::Core::ERROR_GENERAL; printf("Wrong file position given start = %u end = %u, cross check\n", start, end); } } @@ -258,16 +258,16 @@ namespace Tests { uint32_t position = 0; while (size > 0) { uint16_t chunk = std::min(static_cast(64), static_cast(size)); - Core::File::Write(buffer + position, chunk); + ::Thunder::Core::File::Write(buffer + position, chunk); size -= chunk; position += chunk; } } private: - HashType _hash; + HASHALGORITHM _hash; int64_t _startPosition; - Core::File _hashFileStorage; + ::Thunder::Core::File _hashFileStorage; }; // MD5 Tests @@ -275,7 +275,7 @@ namespace Tests { { SignedFileType signedFile("test.txt"); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); Crypto::MD5& md5 = signedFile.Hash(); uint8_t thunderHMAC[Crypto::HASH_MD5]; @@ -292,7 +292,7 @@ namespace Tests { signedFile.CreateFileData('B', 25); signedFile.AppendFileData('C', 30); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); uint8_t thunderHMAC[Crypto::HASH_MD5]; memcpy(thunderHMAC, md5.Result(), Crypto::HASH_MD5); @@ -307,7 +307,7 @@ namespace Tests { Crypto::MD5& md5 = signedFile.Hash(); md5.Reset(); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); // Read current context from MD5 handle Crypto::MD5::Context context = md5.CurrentContext(); @@ -328,7 +328,7 @@ namespace Tests { Crypto::MD5& md5 = signedFile.Hash(); md5.Reset(); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); // Read current context from MD5 handle Crypto::MD5::Context context = md5.CurrentContext(); @@ -340,7 +340,7 @@ namespace Tests { // Append some more data to file int64_t start = signedFile.FileSize(); signedFile.AppendFileData('C', 30); - EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), ::Thunder::Core::ERROR_NONE); uint8_t thunderHMAC[Crypto::HASH_MD5]; memcpy(thunderHMAC, md5.Result(), Crypto::HASH_MD5); @@ -355,7 +355,7 @@ namespace Tests { Crypto::MD5& md5 = signedFile.Hash(); md5.Reset(); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); // Read current context from MD5 handle Crypto::MD5::Context context = md5.CurrentContext(); @@ -380,7 +380,7 @@ namespace Tests { signedFile.AppendFileData(data, sizeof(data)); // Calculate final hash - EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), ::Thunder::Core::ERROR_NONE); uint8_t thunderHMAC[Crypto::HASH_MD5]; memcpy(thunderHMAC, md5.Result(), Crypto::HASH_MD5); @@ -395,7 +395,7 @@ namespace Tests { { SignedFileType signedFile("test.txt"); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); Crypto::SHA1& sha1 = signedFile.Hash(); uint8_t thunderHMAC[Crypto::HASH_SHA1]; @@ -412,7 +412,7 @@ namespace Tests { signedFile.CreateFileData('B', 25); signedFile.AppendFileData('C', 30); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); uint8_t thunderHMAC[Crypto::HASH_SHA1]; memcpy(thunderHMAC, sha1.Result(), Crypto::HASH_SHA1); @@ -427,7 +427,7 @@ namespace Tests { Crypto::SHA1& sha1 = signedFile.Hash(); sha1.Reset(); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); // Read current context from SHA1 handle Crypto::SHA1::Context context = sha1.CurrentContext(); @@ -448,7 +448,7 @@ namespace Tests { Crypto::SHA1& sha1 = signedFile.Hash(); sha1.Reset(); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); // Read current context from SHA1 handle Crypto::SHA1::Context context = sha1.CurrentContext(); @@ -460,7 +460,7 @@ namespace Tests { // Append some more data to file int64_t start = signedFile.FileSize(); signedFile.AppendFileData('C', 30); - EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), ::Thunder::Core::ERROR_NONE); uint8_t thunderHMAC[Crypto::HASH_SHA1]; memcpy(thunderHMAC, sha1.Result(), Crypto::HASH_SHA1); @@ -475,7 +475,7 @@ namespace Tests { Crypto::SHA1& sha1 = signedFile.Hash(); sha1.Reset(); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); // Read current context from SHA1 handle Crypto::SHA1::Context context = sha1.CurrentContext(); @@ -500,7 +500,7 @@ namespace Tests { signedFile.AppendFileData(data, sizeof(data)); // Calculate final hash - EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), ::Thunder::Core::ERROR_NONE); uint8_t thunderHMAC[Crypto::HASH_SHA1]; memcpy(thunderHMAC, sha1.Result(), Crypto::HASH_SHA1); @@ -515,7 +515,7 @@ namespace Tests { { SignedFileType signedFile("test.txt"); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); Crypto::SHA224& sha224 = signedFile.Hash(); uint8_t thunderHMAC[Crypto::HASH_SHA224]; @@ -532,7 +532,7 @@ namespace Tests { signedFile.CreateFileData('B', 25); signedFile.AppendFileData('C', 30); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); uint8_t thunderHMAC[Crypto::HASH_SHA224]; memcpy(thunderHMAC, sha224.Result(), Crypto::HASH_SHA224); @@ -547,7 +547,7 @@ namespace Tests { Crypto::SHA224& sha224 = signedFile.Hash(); sha224.Reset(); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); // Read current context from SHA224 handle Crypto::SHA1::Context context = sha224.CurrentContext(); @@ -568,7 +568,7 @@ namespace Tests { Crypto::SHA224& sha224 = signedFile.Hash(); sha224.Reset(); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); // Read current context from SHA224 handle Crypto::SHA224::Context context = sha224.CurrentContext(); @@ -580,7 +580,7 @@ namespace Tests { // Append some more data to file int64_t start = signedFile.FileSize(); signedFile.AppendFileData('C', 30); - EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), ::Thunder::Core::ERROR_NONE); uint8_t thunderHMAC[Crypto::HASH_SHA224]; memcpy(thunderHMAC, sha224.Result(), Crypto::HASH_SHA224); @@ -595,7 +595,7 @@ namespace Tests { Crypto::SHA224& sha224 = signedFile.Hash(); sha224.Reset(); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); // Read current context from SHA224 handle Crypto::SHA224::Context context = sha224.CurrentContext(); @@ -620,7 +620,7 @@ namespace Tests { signedFile.AppendFileData(data, sizeof(data)); // Calculate final hash - EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), ::Thunder::Core::ERROR_NONE); uint8_t thunderHMAC[Crypto::HASH_SHA224]; memcpy(thunderHMAC, sha224.Result(), Crypto::HASH_SHA224); @@ -635,7 +635,7 @@ namespace Tests { { SignedFileType signedFile("test.txt"); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); Crypto::SHA256& sha256 = signedFile.Hash(); uint8_t thunderHMAC[Crypto::HASH_SHA256]; @@ -651,7 +651,7 @@ namespace Tests { signedFile.CreateFileData('B', 25); signedFile.AppendFileData('C', 30); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); uint8_t thunderHMAC[Crypto::HASH_SHA256]; memcpy(thunderHMAC, sha256.Result(), Crypto::HASH_SHA256); @@ -666,7 +666,7 @@ namespace Tests { Crypto::SHA256& sha256 = signedFile.Hash(); sha256.Reset(); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); // Read current context from SHA256 handle Crypto::SHA256::Context context = sha256.CurrentContext(); @@ -687,7 +687,7 @@ namespace Tests { Crypto::SHA256& sha256 = signedFile.Hash(); sha256.Reset(); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); // Read current context from SHA256 handle Crypto::SHA256::Context context = sha256.CurrentContext(); @@ -699,7 +699,7 @@ namespace Tests { // Append some more data to file int64_t start = signedFile.FileSize(); signedFile.AppendFileData('C', 30); - EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), ::Thunder::Core::ERROR_NONE); uint8_t thunderHMAC[Crypto::HASH_SHA256]; memcpy(thunderHMAC, sha256.Result(), Crypto::HASH_SHA256); @@ -715,7 +715,7 @@ namespace Tests { Crypto::SHA256& sha256 = signedFile.Hash(); sha256.Reset(); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); // Read current context from SHA256 handle Crypto::SHA256::Context context = sha256.CurrentContext(); @@ -740,7 +740,7 @@ namespace Tests { signedFile.AppendFileData(data, sizeof(data)); // Calculate final hash - EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), ::Thunder::Core::ERROR_NONE); uint8_t thunderHMAC[Crypto::HASH_SHA256]; memcpy(thunderHMAC, sha256.Result(), Crypto::HASH_SHA256); @@ -755,7 +755,7 @@ namespace Tests { { SignedFileType signedFile("test.txt"); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); Crypto::SHA384& sha384 = signedFile.Hash(); uint8_t thunderHMAC[Crypto::HASH_SHA384]; @@ -772,7 +772,7 @@ namespace Tests { signedFile.CreateFileData('B', 25); signedFile.AppendFileData('C', 30); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); uint8_t thunderHMAC[Crypto::HASH_SHA384]; memcpy(thunderHMAC, sha384.Result(), Crypto::HASH_SHA384); @@ -787,7 +787,7 @@ namespace Tests { Crypto::SHA384& sha384 = signedFile.Hash(); sha384.Reset(); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); // Read current context from SHA384 handle Crypto::SHA384::Context context = sha384.CurrentContext(); @@ -808,7 +808,7 @@ namespace Tests { Crypto::SHA384& sha384 = signedFile.Hash(); sha384.Reset(); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); // Read current context from SHA384 handle Crypto::SHA384::Context context = sha384.CurrentContext(); @@ -820,7 +820,7 @@ namespace Tests { // Append some more data to file int64_t start = signedFile.FileSize(); signedFile.AppendFileData('C', 30); - EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), ::Thunder::Core::ERROR_NONE); uint8_t thunderHMAC[Crypto::HASH_SHA384]; memcpy(thunderHMAC, sha384.Result(), Crypto::HASH_SHA384); @@ -835,7 +835,7 @@ namespace Tests { Crypto::SHA384& sha384 = signedFile.Hash(); sha384.Reset(); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); // Read current context from SHA384 handle Crypto::SHA384::Context context = sha384.CurrentContext(); @@ -860,7 +860,7 @@ namespace Tests { signedFile.AppendFileData(data, sizeof(data)); // Calculate final hash - EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), ::Thunder::Core::ERROR_NONE); uint8_t thunderHMAC[Crypto::HASH_SHA384]; memcpy(thunderHMAC, sha384.Result(), Crypto::HASH_SHA384); @@ -875,7 +875,7 @@ namespace Tests { { SignedFileType signedFile("test.txt"); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); Crypto::SHA512& sha512 = signedFile.Hash(); uint8_t thunderHMAC[Crypto::HASH_SHA512]; @@ -892,7 +892,7 @@ namespace Tests { signedFile.CreateFileData('B', 25); signedFile.AppendFileData('C', 30); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); uint8_t thunderHMAC[Crypto::HASH_SHA512]; memcpy(thunderHMAC, sha512.Result(), Crypto::HASH_SHA512); @@ -907,7 +907,7 @@ namespace Tests { Crypto::SHA512& sha512 = signedFile.Hash(); sha512.Reset(); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); Crypto::SHA512::Context context = sha512.CurrentContext(); @@ -927,7 +927,7 @@ namespace Tests { Crypto::SHA512& sha512 = signedFile.Hash(); sha512.Reset(); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); // Read current context from SHA512 handle Crypto::SHA512::Context context = sha512.CurrentContext(); @@ -939,7 +939,7 @@ namespace Tests { // Append some more data to file int64_t start = signedFile.FileSize(); signedFile.AppendFileData('C', 30); - EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), ::Thunder::Core::ERROR_NONE); uint8_t thunderHMAC[Crypto::HASH_SHA512]; memcpy(thunderHMAC, sha512.Result(), Crypto::HASH_SHA512); @@ -954,7 +954,7 @@ namespace Tests { Crypto::SHA512& sha512 = signedFile.Hash(); sha512.Reset(); signedFile.CreateFileData('B', 25); - EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(0, signedFile.FileSize()), ::Thunder::Core::ERROR_NONE); // Read current context from SHA512 handle Crypto::SHA512::Context context = sha512.CurrentContext(); @@ -979,7 +979,7 @@ namespace Tests { signedFile.AppendFileData(data, sizeof(data)); // Calculate final hash - EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), Core::ERROR_NONE); + EXPECT_EQ(signedFile.CalculateHash(start, signedFile.FileSize() - start), ::Thunder::Core::ERROR_NONE); uint8_t thunderHMAC[Crypto::HASH_SHA512]; memcpy(thunderHMAC, sha512.Result(), Crypto::HASH_SHA512); @@ -988,5 +988,7 @@ namespace Tests { ExecuteCmd("sha512sum test.txt").c_str()); signedFile.DestroyFile(); } -} -} + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_hex2strserialization.cpp b/Tests/unit/core/test_hex2strserialization.cpp index 6b9075a01b..6e666744c3 100644 --- a/Tests/unit/core/test_hex2strserialization.cpp +++ b/Tests/unit/core/test_hex2strserialization.cpp @@ -30,13 +30,14 @@ namespace Thunder { namespace Tests { +namespace Core { TEST(HEX2StrSerialization, serialiation_working) { uint8_t object[] = {0xB1, 0x32, 0x01}; const uint16_t lenght = sizeof(object); string output; - Core::ToHexString(object, lenght, output); + ::Thunder::Core::ToHexString(object, lenght, output); EXPECT_EQ(output, "b13201"); } @@ -47,7 +48,7 @@ namespace Tests { uint8_t buffer[8] = {0}; string output; - uint16_t length = Core::FromHexString(str, buffer, 8); + uint16_t length = ::Thunder::Core::FromHexString(str, buffer, 8); EXPECT_EQ(length, 3); EXPECT_EQ(memcmp(expected, buffer, sizeof(expected)), 0); @@ -59,7 +60,7 @@ namespace Tests { uint8_t buffer[8] = {0}; string output; - uint16_t length = Core::FromHexString(str, buffer, 8); + uint16_t length = ::Thunder::Core::FromHexString(str, buffer, 8); EXPECT_EQ(length, 3); EXPECT_EQ(memcmp(expected, buffer, sizeof(expected)), 0); @@ -71,7 +72,7 @@ namespace Tests { uint8_t buffer[8] = {0}; string output; - uint16_t length = Core::FromHexString(str, buffer, 8); + uint16_t length = ::Thunder::Core::FromHexString(str, buffer, 8); EXPECT_EQ(length, 3); EXPECT_EQ(memcmp(expected, buffer, sizeof(expected)), 0); @@ -83,10 +84,12 @@ namespace Tests { uint8_t buffer[8] = {0x00, 0x00, 0xDE, 0xAD, 0xBE, 0xEF}; string output; - uint16_t length = Core::FromHexString(str, buffer, 2); + uint16_t length = ::Thunder::Core::FromHexString(str, buffer, 2); EXPECT_EQ(length, 2); EXPECT_EQ(memcmp(expected, buffer, sizeof(expected)), 0); } -} -} + +} // Core +} // Tests +} // Thunder \ No newline at end of file diff --git a/Tests/unit/core/test_ipc.cpp b/Tests/unit/core/test_ipc.cpp index 4bfea2226a..52299d5919 100644 --- a/Tests/unit/core/test_ipc.cpp +++ b/Tests/unit/core/test_ipc.cpp @@ -29,6 +29,7 @@ namespace Thunder { namespace Tests { +namespace Core { class Response { public: @@ -126,11 +127,11 @@ namespace Tests { uint64_t _context; }; - typedef Core::IPCMessageType<1, Triplet, Response> TripletResponse; - typedef Core::IPCMessageType<2, Core::Void, Triplet> VoidTriplet; - typedef Core::IPCMessageType<3, Core::IPC::Text<2048>, Core::IPC::Text<2048>> TextText; + typedef ::Thunder::Core::IPCMessageType<1, Triplet, Response> TripletResponse; + typedef ::Thunder::Core::IPCMessageType<2, ::Thunder::Core::Void, Triplet> VoidTriplet; + typedef ::Thunder::Core::IPCMessageType<3, ::Thunder::Core::IPC::Text<2048>, ::Thunder::Core::IPC::Text<2048>> TextText; - class HandleTripletResponse : public Core::IIPCServer { + class HandleTripletResponse : public ::Thunder::Core::IIPCServer { public: HandleTripletResponse(const HandleTripletResponse&) = delete; HandleTripletResponse& operator=(const HandleTripletResponse&) = delete; @@ -145,9 +146,9 @@ namespace Tests { public: // Here comes the actual implementation of the RPC... - virtual void Procedure(Core::IPCChannel& source, Core::ProxyType& data) + virtual void Procedure(::Thunder::Core::IPCChannel& source, ::Thunder::Core::ProxyType<::Thunder::Core::IIPC>& data) { - Core::ProxyType message(data); + ::Thunder::Core::ProxyType message(data); uint32_t result = message->Parameters().Display() + message->Parameters().Surface() + static_cast(message->Parameters().Context()); message->Response() = Response(result); @@ -155,7 +156,7 @@ namespace Tests { } }; - class HandleVoidTriplet : public Core::IIPCServer { + class HandleVoidTriplet : public ::Thunder::Core::IIPCServer { public: HandleVoidTriplet(const HandleVoidTriplet&) = delete; HandleVoidTriplet& operator=(const HandleVoidTriplet&) = delete; @@ -169,9 +170,9 @@ namespace Tests { public: // Here comes the actual implementation of the RPC... - virtual void Procedure(Core::IPCChannel& source, Core::ProxyType& data) + virtual void Procedure(::Thunder::Core::IPCChannel& source, ::Thunder::Core::ProxyType<::Thunder::Core::IIPC>& data) { - Core::ProxyType message(data); + ::Thunder::Core::ProxyType message(data); Triplet newValue(1, 2, 3); message->Response() = newValue; @@ -179,7 +180,7 @@ namespace Tests { } }; - class HandleTextText : public Core::IIPCServer { + class HandleTextText : public ::Thunder::Core::IIPCServer { public: HandleTextText(const HandleTextText&) = delete; HandleTextText& operator=(const HandleTextText&) = delete; @@ -194,12 +195,12 @@ namespace Tests { public: // Here comes the actual implementation of the RPC... - virtual void Procedure(Core::IPCChannel& source, Core::ProxyType& data) + virtual void Procedure(::Thunder::Core::IPCChannel& source, ::Thunder::Core::ProxyType<::Thunder::Core::IIPC>& data) { - Core::ProxyType message(data); + ::Thunder::Core::ProxyType message(data); string text = message->Parameters().Value(); - message->Response() = Core::IPC::Text<2048>(text); + message->Response() = ::Thunder::Core::IPC::Text<2048>(text); source.ReportResponse(data); } }; @@ -208,34 +209,34 @@ namespace Tests { { std::string connector = _T("/tmp/testserver0"); auto lambdaFunc = [connector](IPTestAdministrator & testAdmin) { - Core::NodeId continousNode(connector.c_str()); + ::Thunder::Core::NodeId continousNode(connector.c_str()); uint32_t error; - Core::ProxyType > factory(Core::ProxyType >::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> > factory(::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> >::Create()); factory->CreateFactory(2); factory->CreateFactory(2); factory->CreateFactory(2); - Core::IPCChannelClientType continousChannel(continousNode, 32, factory); + ::Thunder::Core::IPCChannelClientType<::Thunder::Core::Void, true, false> continousChannel(continousNode, 32, factory); - Core::ProxyType handler1(Core::ProxyType::Create()); - Core::ProxyType handler2(Core::ProxyType::Create()); - Core::ProxyType handler3(Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler1(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler2(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler3(::Thunder::Core::ProxyType::Create()); continousChannel.Register(TripletResponse::Id(), handler1); continousChannel.Register(VoidTriplet::Id(), handler2); continousChannel.Register(TextText::Id(), handler3); error = continousChannel.Source().Open(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); testAdmin.Sync("setup server"); testAdmin.Sync("setup client"); testAdmin.Sync("done testing"); error = continousChannel.Source().Close(1000); // Wait for 1 second - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); continousChannel.Unregister(TripletResponse::Id()); continousChannel.Unregister(VoidTriplet::Id()); continousChannel.Unregister(TextText::Id()); @@ -249,32 +250,32 @@ namespace Tests { IPTestAdministrator testAdmin(otherSide); { - Core::NodeId continousNode(connector.c_str()); + ::Thunder::Core::NodeId continousNode(connector.c_str()); uint32_t error; testAdmin.Sync("setup server"); - Core::ProxyType > factory(Core::ProxyType >::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> > factory(::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> >::Create()); factory->CreateFactory(2); factory->CreateFactory(2); factory->CreateFactory(2); - Core::IPCChannelClientType continousChannel(continousNode, 32, factory); + ::Thunder::Core::IPCChannelClientType<::Thunder::Core::Void, false, false> continousChannel(continousNode, 32, factory); - Core::ProxyType handler1(Core::ProxyType::Create()); - Core::ProxyType handler2(Core::ProxyType::Create()); - Core::ProxyType handler3(Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler1(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler2(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler3(::Thunder::Core::ProxyType::Create()); error = continousChannel.Source().Open(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); testAdmin.Sync("setup client"); - Core::ProxyType tripletResponseData(Core::ProxyType::Create(Triplet(1, 2, 3))); - Core::ProxyType voidTripletData(Core::ProxyType::Create()); + ::Thunder::Core::ProxyType tripletResponseData(::Thunder::Core::ProxyType::Create(Triplet(1, 2, 3))); + ::Thunder::Core::ProxyType voidTripletData(::Thunder::Core::ProxyType::Create()); string text = "test text"; - Core::ProxyType textTextData(Core::ProxyType::Create(Core::IPC::Text<2048>(text))); + ::Thunder::Core::ProxyType textTextData(::Thunder::Core::ProxyType::Create(::Thunder::Core::IPC::Text<2048>(text))); uint16_t display = 1;; uint32_t surface = 2; @@ -282,25 +283,25 @@ namespace Tests { uint32_t result = 6; error = continousChannel.Invoke(tripletResponseData, 2000); - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); EXPECT_EQ(tripletResponseData->Response().Result(), result); error = continousChannel.Invoke(voidTripletData, 2000); - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); EXPECT_EQ(voidTripletData->Response().Display(), display); EXPECT_EQ(voidTripletData->Response().Surface(), surface); EXPECT_EQ(voidTripletData->Response().Context(), context); error = continousChannel.Invoke(textTextData, 2000); - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); EXPECT_STREQ(textTextData->Response().Value(), text.c_str()); error = continousChannel.Source().Close(1000); // Wait for 1 second - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); factory->DestroyFactories(); - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } testAdmin.Sync("done testing"); } @@ -309,33 +310,33 @@ namespace Tests { { std::string connector = _T("/tmp/testserver1"); auto lambdaFunc = [connector](IPTestAdministrator & testAdmin) { - Core::NodeId continousNode(connector.c_str()); + ::Thunder::Core::NodeId continousNode(connector.c_str()); uint32_t error; testAdmin.Sync("setup client"); - Core::ProxyType > factory(Core::ProxyType >::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> > factory(::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> >::Create()); factory->CreateFactory(2); factory->CreateFactory(2); factory->CreateFactory(2); - Core::IPCChannelClientType continousChannel(continousNode, 32, factory); + ::Thunder::Core::IPCChannelClientType<::Thunder::Core::Void, false, false> continousChannel(continousNode, 32, factory); - Core::ProxyType handler1(Core::ProxyType::Create()); - Core::ProxyType handler2(Core::ProxyType::Create()); - Core::ProxyType handler3(Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler1(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler2(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler3(::Thunder::Core::ProxyType::Create()); error = continousChannel.Source().Open(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); testAdmin.Sync("setup server"); - Core::ProxyType tripletResponseData(Core::ProxyType::Create(Triplet(1, 2, 3))); - Core::ProxyType voidTripletData(Core::ProxyType::Create()); + ::Thunder::Core::ProxyType tripletResponseData(::Thunder::Core::ProxyType::Create(Triplet(1, 2, 3))); + ::Thunder::Core::ProxyType voidTripletData(::Thunder::Core::ProxyType::Create()); string text = "test text"; - Core::ProxyType textTextData(Core::ProxyType::Create(Core::IPC::Text<2048>(text))); + ::Thunder::Core::ProxyType textTextData(::Thunder::Core::ProxyType::Create(::Thunder::Core::IPC::Text<2048>(text))); uint16_t display = 1;; uint32_t surface = 2; @@ -343,25 +344,25 @@ namespace Tests { uint32_t result = 6; error = continousChannel.Invoke(tripletResponseData, 5000); - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); EXPECT_EQ(tripletResponseData->Response().Result(), result); error = continousChannel.Invoke(voidTripletData, 2000); - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); EXPECT_EQ(voidTripletData->Response().Display(), display); EXPECT_EQ(voidTripletData->Response().Surface(), surface); EXPECT_EQ(voidTripletData->Response().Context(), context); error = continousChannel.Invoke(textTextData, 2000); - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); EXPECT_STREQ(textTextData->Response().Value(), text.c_str()); error = continousChannel.Source().Close(1000); // Wait for 1 second - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); factory->DestroyFactories(); - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); testAdmin.Sync("done testing"); }; @@ -372,34 +373,34 @@ namespace Tests { IPTestAdministrator testAdmin(otherSide); { - Core::NodeId continousNode(connector.c_str()); + ::Thunder::Core::NodeId continousNode(connector.c_str()); uint32_t error; - Core::ProxyType > factory(Core::ProxyType >::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> > factory(::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> >::Create()); factory->CreateFactory(2); factory->CreateFactory(2); factory->CreateFactory(2); - Core::IPCChannelClientType continousChannel(continousNode, 32, factory); + ::Thunder::Core::IPCChannelClientType<::Thunder::Core::Void, true, false> continousChannel(continousNode, 32, factory); - Core::ProxyType handler1(Core::ProxyType::Create()); - Core::ProxyType handler2(Core::ProxyType::Create()); - Core::ProxyType handler3(Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler1(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler2(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler3(::Thunder::Core::ProxyType::Create()); continousChannel.Register(TripletResponse::Id(), handler1); continousChannel.Register(VoidTriplet::Id(), handler2); continousChannel.Register(TextText::Id(), handler3); error = continousChannel.Source().Open(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); testAdmin.Sync("setup client"); testAdmin.Sync("setup server"); testAdmin.Sync("done testing"); error = continousChannel.Source().Close(1000); // Wait for 1 second - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); continousChannel.Unregister(TripletResponse::Id()); continousChannel.Unregister(VoidTriplet::Id()); @@ -407,7 +408,7 @@ namespace Tests { factory->DestroyFactories(); - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } } @@ -415,34 +416,34 @@ namespace Tests { { std::string connector = _T("/tmp/testserver2"); auto lambdaFunc = [connector](IPTestAdministrator & testAdmin) { - Core::NodeId flashNode(connector.c_str()); + ::Thunder::Core::NodeId flashNode(connector.c_str()); uint32_t error; - Core::ProxyType > factory(Core::ProxyType >::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> > factory(::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> >::Create()); factory->CreateFactory(2); factory->CreateFactory(2); factory->CreateFactory(2); - Core::IPCChannelClientType flashChannel(flashNode, 512, factory); + ::Thunder::Core::IPCChannelClientType<::Thunder::Core::Void, true, false> flashChannel(flashNode, 512, factory); - Core::ProxyType handler1(Core::ProxyType::Create()); - Core::ProxyType handler2(Core::ProxyType::Create()); - Core::ProxyType handler3(Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler1(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler2(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler3(::Thunder::Core::ProxyType::Create()); flashChannel.Register(TripletResponse::Id(), handler1); flashChannel.Register(VoidTriplet::Id(), handler2); flashChannel.Register(TextText::Id(), handler3); error = flashChannel.Source().Open(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); testAdmin.Sync("setup server"); testAdmin.Sync("setup client"); testAdmin.Sync("done testing"); error = flashChannel.Source().Close(1000); // Wait for 1 Second - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); flashChannel.Unregister(TripletResponse::Id()); flashChannel.Unregister(VoidTriplet::Id()); flashChannel.Unregister(TextText::Id()); @@ -456,29 +457,29 @@ namespace Tests { IPTestAdministrator testAdmin(otherSide); { - Core::NodeId flashNode(connector.c_str()); + ::Thunder::Core::NodeId flashNode(connector.c_str()); uint32_t error; testAdmin.Sync("setup server"); - Core::ProxyType > factory(Core::ProxyType >::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> > factory(::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> >::Create()); factory->CreateFactory(2); factory->CreateFactory(2); factory->CreateFactory(2); - Core::IPCChannelClientType flashChannel(flashNode, 512, factory); + ::Thunder::Core::IPCChannelClientType<::Thunder::Core::Void, false, false> flashChannel(flashNode, 512, factory); - Core::ProxyType handler1(Core::ProxyType::Create()); - Core::ProxyType handler2(Core::ProxyType::Create()); - Core::ProxyType handler3(Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler1(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler2(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler3(::Thunder::Core::ProxyType::Create()); testAdmin.Sync("setup client"); - Core::ProxyType tripletResponseData(Core::ProxyType::Create(Triplet(1, 2, 3))); - Core::ProxyType voidTripletData(Core::ProxyType::Create()); + ::Thunder::Core::ProxyType tripletResponseData(::Thunder::Core::ProxyType::Create(Triplet(1, 2, 3))); + ::Thunder::Core::ProxyType voidTripletData(::Thunder::Core::ProxyType::Create()); string text = "test text"; - Core::ProxyType textTextData(Core::ProxyType::Create(Core::IPC::Text<2048>(text))); + ::Thunder::Core::ProxyType textTextData(::Thunder::Core::ProxyType::Create(::Thunder::Core::IPC::Text<2048>(text))); uint16_t display = 1;; uint32_t surface = 2; @@ -486,33 +487,33 @@ namespace Tests { uint32_t result = 6; error = flashChannel.Source().Open(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); error = flashChannel.Invoke(tripletResponseData, 2000); - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); EXPECT_EQ(tripletResponseData->Response().Result(), result); error = flashChannel.Source().Close(1000); // Wait for 1 Second - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); error = flashChannel.Source().Open(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); error = flashChannel.Invoke(voidTripletData, 2000); - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); EXPECT_EQ(voidTripletData->Response().Display(), display); EXPECT_EQ(voidTripletData->Response().Surface(), surface); EXPECT_EQ(voidTripletData->Response().Context(), context); error = flashChannel.Source().Close(1000); // Wait for 1 Second - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); error = flashChannel.Source().Open(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); error = flashChannel.Invoke(textTextData, 2000); - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); EXPECT_STREQ(textTextData->Response().Value(), text.c_str()); error = flashChannel.Source().Close(1000); // Wait for 1 Second - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); factory->DestroyFactories(); - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } testAdmin.Sync("done testing"); @@ -522,34 +523,34 @@ namespace Tests { { std::string connector = _T("/tmp/testserver3"); auto lambdaFunc = [connector](IPTestAdministrator & testAdmin) { - Core::NodeId flashNode(connector.c_str()); + ::Thunder::Core::NodeId flashNode(connector.c_str()); uint32_t error; - Core::ProxyType > factory(Core::ProxyType >::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> > factory(::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> >::Create()); factory->CreateFactory(2); factory->CreateFactory(2); factory->CreateFactory(2); - Core::IPCChannelClientType flashChannel(flashNode, 512, factory); + ::Thunder::Core::IPCChannelClientType<::Thunder::Core::Void, true, false> flashChannel(flashNode, 512, factory); - Core::ProxyType handler1(Core::ProxyType::Create()); - Core::ProxyType handler2(Core::ProxyType::Create()); - Core::ProxyType handler3(Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler1(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler2(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler3(::Thunder::Core::ProxyType::Create()); flashChannel.Register(TripletResponse::Id(), handler1); flashChannel.Register(VoidTriplet::Id(), handler2); flashChannel.Register(TextText::Id(), handler3); error = flashChannel.Source().Open(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); testAdmin.Sync("setup server"); testAdmin.Sync("setup client"); testAdmin.Sync("done testing"); error = flashChannel.Source().Close(1000); // Wait for 1 Second - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); flashChannel.Unregister(TripletResponse::Id()); flashChannel.Unregister(VoidTriplet::Id()); flashChannel.Unregister(TextText::Id()); @@ -563,29 +564,29 @@ namespace Tests { IPTestAdministrator testAdmin(otherSide); { - Core::NodeId flashNode(connector.c_str()); + ::Thunder::Core::NodeId flashNode(connector.c_str()); uint32_t error; testAdmin.Sync("setup server"); - Core::ProxyType > factory(Core::ProxyType >::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> > factory(::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> >::Create()); factory->CreateFactory(2); factory->CreateFactory(2); factory->CreateFactory(2); - Core::IPCChannelClientType flashChannel(flashNode, 512, factory); + ::Thunder::Core::IPCChannelClientType<::Thunder::Core::Void, false, false> flashChannel(flashNode, 512, factory); - Core::ProxyType handler1(Core::ProxyType::Create()); - Core::ProxyType handler2(Core::ProxyType::Create()); - Core::ProxyType handler3(Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler1(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler2(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler3(::Thunder::Core::ProxyType::Create()); testAdmin.Sync("setup client"); - Core::ProxyType tripletResponseData(Core::ProxyType::Create(Triplet(1, 2, 3))); - Core::ProxyType voidTripletData(Core::ProxyType::Create()); + ::Thunder::Core::ProxyType tripletResponseData(::Thunder::Core::ProxyType::Create(Triplet(1, 2, 3))); + ::Thunder::Core::ProxyType voidTripletData(::Thunder::Core::ProxyType::Create()); string text = "test text"; - Core::ProxyType textTextData(Core::ProxyType::Create(Core::IPC::Text<2048>(text))); + ::Thunder::Core::ProxyType textTextData(::Thunder::Core::ProxyType::Create(::Thunder::Core::IPC::Text<2048>(text))); uint16_t display = 1;; uint32_t surface = 2; @@ -593,33 +594,33 @@ namespace Tests { uint32_t result = 6; error = flashChannel.Source().Open(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); error = flashChannel.Invoke(tripletResponseData, 2000); - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); EXPECT_EQ(tripletResponseData->Response().Result(), result); error = flashChannel.Source().Close(1000); // Wait for 1 Second - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); error = flashChannel.Source().Open(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); error = flashChannel.Invoke(voidTripletData, 2000); - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); EXPECT_EQ(voidTripletData->Response().Display(), display); EXPECT_EQ(voidTripletData->Response().Surface(), surface); EXPECT_EQ(voidTripletData->Response().Context(), context); error = flashChannel.Source().Close(1000); // Wait for 1 Second - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); error = flashChannel.Source().Open(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); error = flashChannel.Invoke(textTextData, 2000); - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); EXPECT_STREQ(textTextData->Response().Value(), text.c_str()); error = flashChannel.Source().Close(1000); // Wait for 1 Second - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); factory->DestroyFactories(); - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } testAdmin.Sync("done testing"); } @@ -628,38 +629,38 @@ namespace Tests { { std::string connector = _T("/tmp/testserver4"); auto lambdaFunc = [connector](IPTestAdministrator & testAdmin) { - Core::NodeId multiNode(connector.c_str()); + ::Thunder::Core::NodeId multiNode(connector.c_str()); uint32_t error; - Core::ProxyType > factory(Core::ProxyType >::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> > factory(::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> >::Create()); factory->CreateFactory(2); factory->CreateFactory(2); factory->CreateFactory(2); - Core::IPCChannelServerType multiChannel(multiNode, 512, factory); + ::Thunder::Core::IPCChannelServerType<::Thunder::Core::Void, false> multiChannel(multiNode, 512, factory); - Core::ProxyType handler1(Core::ProxyType::Create()); - Core::ProxyType handler2(Core::ProxyType::Create()); - Core::ProxyType handler3(Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler1(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler2(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler3(::Thunder::Core::ProxyType::Create()); multiChannel.Register(TripletResponse::Id(), handler1); multiChannel.Register(VoidTriplet::Id(), handler2); multiChannel.Register(TextText::Id(), handler3); error = multiChannel.Open(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); testAdmin.Sync("setup server"); testAdmin.Sync("setup client"); testAdmin.Sync("done testing"); error = multiChannel.Close(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); factory->DestroyFactories(); - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); }; static std::function lambdaVar = lambdaFunc; @@ -668,32 +669,32 @@ namespace Tests { IPTestAdministrator testAdmin(otherSide); { - Core::NodeId multiNode(connector.c_str()); + ::Thunder::Core::NodeId multiNode(connector.c_str()); uint32_t error; testAdmin.Sync("setup server"); - Core::ProxyType > factory(Core::ProxyType >::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> > factory(::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> >::Create()); factory->CreateFactory(2); factory->CreateFactory(2); factory->CreateFactory(2); - Core::IPCChannelClientType multiChannel(multiNode, 512, factory); + ::Thunder::Core::IPCChannelClientType<::Thunder::Core::Void, false, false> multiChannel(multiNode, 512, factory); - Core::ProxyType handler1(Core::ProxyType::Create()); - Core::ProxyType handler2(Core::ProxyType::Create()); - Core::ProxyType handler3(Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler1(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler2(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler3(::Thunder::Core::ProxyType::Create()); error = multiChannel.Source().Open(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); testAdmin.Sync("setup client"); - Core::ProxyType tripletResponseData(Core::ProxyType::Create(Triplet(1, 2, 3))); - Core::ProxyType voidTripletData(Core::ProxyType::Create()); + ::Thunder::Core::ProxyType tripletResponseData(::Thunder::Core::ProxyType::Create(Triplet(1, 2, 3))); + ::Thunder::Core::ProxyType voidTripletData(::Thunder::Core::ProxyType::Create()); string text = "test text"; - Core::ProxyType textTextData(Core::ProxyType::Create(Core::IPC::Text<2048>(text))); + ::Thunder::Core::ProxyType textTextData(::Thunder::Core::ProxyType::Create(::Thunder::Core::IPC::Text<2048>(text))); uint16_t display = 1;; uint32_t surface = 2; @@ -701,25 +702,25 @@ namespace Tests { uint32_t result = 6; error = multiChannel.Invoke(tripletResponseData, 2000); - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); EXPECT_EQ(tripletResponseData->Response().Result(), result); error = multiChannel.Invoke(voidTripletData, 2000); - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); EXPECT_EQ(voidTripletData->Response().Display(), display); EXPECT_EQ(voidTripletData->Response().Surface(), surface); EXPECT_EQ(voidTripletData->Response().Context(), context); error = multiChannel.Invoke(textTextData, 2000); - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); EXPECT_STREQ(textTextData->Response().Value(), text.c_str()); error = multiChannel.Source().Close(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); factory->DestroyFactories(); - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } // testAdmin.Sync("done testing"); } @@ -728,48 +729,48 @@ namespace Tests { { std::string connector = _T("/tmp/testserver5"); auto lambdaFunc = [connector](IPTestAdministrator & testAdmin) { - Core::NodeId multiNode(connector.c_str()); + ::Thunder::Core::NodeId multiNode(connector.c_str()); uint32_t error; testAdmin.Sync("setup client"); - Core::ProxyType > factory(Core::ProxyType >::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> > factory(::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> >::Create()); factory->CreateFactory(2); factory->CreateFactory(2); factory->CreateFactory(2); - Core::IPCChannelClientType multiChannel(multiNode, 512, factory); + ::Thunder::Core::IPCChannelClientType<::Thunder::Core::Void, false, false> multiChannel(multiNode, 512, factory); - Core::ProxyType handler1(Core::ProxyType::Create()); - Core::ProxyType handler2(Core::ProxyType::Create()); - Core::ProxyType handler3(Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler1(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler2(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler3(::Thunder::Core::ProxyType::Create()); error = multiChannel.Source().Open(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); testAdmin.Sync("setup server"); - Core::ProxyType tripletResponseData(Core::ProxyType::Create(Triplet(1, 2, 3))); - Core::ProxyType voidTripletData(Core::ProxyType::Create()); + ::Thunder::Core::ProxyType tripletResponseData(::Thunder::Core::ProxyType::Create(Triplet(1, 2, 3))); + ::Thunder::Core::ProxyType voidTripletData(::Thunder::Core::ProxyType::Create()); string text = "test text"; - Core::ProxyType textTextData(Core::ProxyType::Create(Core::IPC::Text<2048>(text))); + ::Thunder::Core::ProxyType textTextData(::Thunder::Core::ProxyType::Create(::Thunder::Core::IPC::Text<2048>(text))); uint16_t display = 1;; uint32_t surface = 2; uint64_t context = 3; uint32_t result = 6; error = multiChannel.Invoke(tripletResponseData, 5000); - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); EXPECT_EQ(tripletResponseData->Response().Result(), result); error = multiChannel.Invoke(voidTripletData, 2000); - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); EXPECT_EQ(voidTripletData->Response().Display(), display); EXPECT_EQ(voidTripletData->Response().Surface(), surface); EXPECT_EQ(voidTripletData->Response().Context(), context); error = multiChannel.Invoke(textTextData, 2000); - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); EXPECT_STREQ(textTextData->Response().Value(), text.c_str()); tripletResponseData.Release(); @@ -777,7 +778,7 @@ namespace Tests { textTextData.Release(); error = multiChannel.Source().Close(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); handler1.Release(); handler2.Release(); @@ -789,7 +790,7 @@ namespace Tests { factory->DestroyFactories(); - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); testAdmin.Sync("done testing"); }; @@ -800,33 +801,33 @@ namespace Tests { IPTestAdministrator testAdmin(otherSide); { - Core::NodeId multiNode(connector.c_str()); + ::Thunder::Core::NodeId multiNode(connector.c_str()); uint32_t error; - Core::ProxyType > factory(Core::ProxyType >::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> > factory(::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> >::Create()); factory->CreateFactory(2); factory->CreateFactory(2); factory->CreateFactory(2); - Core::IPCChannelServerType multiChannel(multiNode, 512, factory); + ::Thunder::Core::IPCChannelServerType<::Thunder::Core::Void, false> multiChannel(multiNode, 512, factory); - Core::ProxyType handler1(Core::ProxyType::Create()); - Core::ProxyType handler2(Core::ProxyType::Create()); - Core::ProxyType handler3(Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler1(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler2(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer> handler3(::Thunder::Core::ProxyType::Create()); multiChannel.Register(TripletResponse::Id(), handler1); multiChannel.Register(VoidTriplet::Id(), handler2); multiChannel.Register(TextText::Id(), handler3); error = multiChannel.Open(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); testAdmin.Sync("setup client"); testAdmin.Sync("setup server"); testAdmin.Sync("done testing"); error = multiChannel.Close(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); handler1.Release(); handler2.Release(); @@ -840,10 +841,12 @@ namespace Tests { factory->DestroyFactories(); - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); // testAdmin.Sync("done testing"); } } + +} // Core } // Tests } // Thunder diff --git a/Tests/unit/core/test_ipcclient.cpp b/Tests/unit/core/test_ipcclient.cpp index 9edd7ae49c..66298e6958 100644 --- a/Tests/unit/core/test_ipcclient.cpp +++ b/Tests/unit/core/test_ipcclient.cpp @@ -29,27 +29,28 @@ namespace Thunder { namespace Tests { +namespace Core { TEST(Core_IPC, IPCClientConnection) { std::string connector = _T("/tmp/testserver"); auto lambdaFunc = [connector](IPTestAdministrator & testAdmin) { - Core::NodeId serverNode(connector.c_str()); + ::Thunder::Core::NodeId serverNode(connector.c_str()); uint32_t error; - Core::ProxyType > factory(Core::ProxyType >::Create()); - Core::IPCChannelServerType serverChannel(serverNode, 512, factory); + ::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> > factory(::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> >::Create()); + ::Thunder::Core::IPCChannelServerType<::Thunder::Core::Void, false> serverChannel(serverNode, 512, factory); error = serverChannel.Open(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); testAdmin.Sync("setup server"); testAdmin.Sync("setup client"); testAdmin.Sync("done testing"); error = serverChannel.Close(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); serverChannel.Cleanup(); @@ -62,23 +63,25 @@ namespace Tests { IPTestAdministrator testAdmin(otherSide); { - Core::NodeId clientNode(connector.c_str()); + ::Thunder::Core::NodeId clientNode(connector.c_str()); uint32_t error; testAdmin.Sync("setup server"); - Core::ProxyType > factory(Core::ProxyType >::Create()); - Core::IPCChannelClientType clientChannel(clientNode, 512, factory); + ::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> > factory(::Thunder::Core::ProxyType<::Thunder::Core::FactoryType<::Thunder::Core::IIPC, uint32_t> >::Create()); + ::Thunder::Core::IPCChannelClientType<::Thunder::Core::Void, false, false> clientChannel(clientNode, 512, factory); error = clientChannel.Source().Open(1000); // Wait for 1 Second. - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); testAdmin.Sync("setup client"); error = clientChannel.Close(1000); - EXPECT_EQ(error, Core::ERROR_NONE); + EXPECT_EQ(error, ::Thunder::Core::ERROR_NONE); factory->DestroyFactories(); - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } testAdmin.Sync("done testing"); } + +} // Core } // Tests } // Thunder diff --git a/Tests/unit/core/test_iso639.cpp b/Tests/unit/core/test_iso639.cpp index 71f1446a1a..a79cdc8459 100644 --- a/Tests/unit/core/test_iso639.cpp +++ b/Tests/unit/core/test_iso639.cpp @@ -25,22 +25,26 @@ #include -using namespace Thunder; -using namespace Thunder::Core; +namespace Thunder { +namespace Tests { +namespace Core { -TEST(test_ISO639, simple_ISO639) -{ - Language(); - Language lang("eng"); - Language(12); - Language lang1(" "); - Language lang2("en"); - Language lang3("aaaaaa"); - - EXPECT_TRUE(lang.IsValid()); - EXPECT_STREQ(lang.LetterCode3(),"eng"); - EXPECT_STREQ(lang.LetterCode2(),"en"); - EXPECT_STREQ(lang.Description(),"Engels"); - EXPECT_EQ(lang.Id(),127); -} + TEST(test_ISO639, simple_ISO639) + { + ::Thunder::Core::Language(); + ::Thunder::Core::Language lang("eng"); + ::Thunder::Core::Language(12); + ::Thunder::Core::Language lang1(" "); + ::Thunder::Core::Language lang2("en"); + ::Thunder::Core::Language lang3("aaaaaa"); + + EXPECT_TRUE(lang.IsValid()); + EXPECT_STREQ(lang.LetterCode3(),"eng"); + EXPECT_STREQ(lang.LetterCode2(),"en"); + EXPECT_STREQ(lang.Description(),"Engels"); + EXPECT_EQ(lang.Id(),127); + } +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_iterator.cpp b/Tests/unit/core/test_iterator.cpp index 8d656ecd78..07dc54d3f5 100644 --- a/Tests/unit/core/test_iterator.cpp +++ b/Tests/unit/core/test_iterator.cpp @@ -27,6 +27,7 @@ namespace Thunder { namespace Tests { +namespace Core { class DataClass { public: @@ -50,10 +51,10 @@ namespace Tests { }; template - class IteratorClass : public Core::IteratorType + class IteratorClass : public ::Thunder::Core::IteratorType { private: - typedef Core::IteratorType BaseClass; + typedef ::Thunder::Core::IteratorType BaseClass; public: IteratorClass() =delete; @@ -69,10 +70,10 @@ namespace Tests { }; template - class IteratorMapClass : public Core::IteratorMapType + class IteratorMapClass : public ::Thunder::Core::IteratorMapType { private: - typedef Core::IteratorMapType BaseClass; + typedef ::Thunder::Core::IteratorMapType BaseClass; public: IteratorMapClass() = delete; @@ -155,5 +156,7 @@ namespace Tests { for (uint8_t i = 1; iterator.Next(); i++) ValidateMap(iterator, i); } + +} // Core } // Tests } // Thunder diff --git a/Tests/unit/core/test_jsonparser.cpp b/Tests/unit/core/test_jsonparser.cpp index 8cccbf459b..678ee6bdc3 100644 --- a/Tests/unit/core/test_jsonparser.cpp +++ b/Tests/unit/core/test_jsonparser.cpp @@ -30,6 +30,9 @@ #include namespace Thunder { +namespace Tests { +namespace Core { + enum class JSONTestEnum { ENUM_1, ENUM_2, @@ -37,14 +40,19 @@ namespace Thunder { ENUM_4 }; - ENUM_CONVERSION_BEGIN(JSONTestEnum) - { JSONTestEnum::ENUM_1, _TXT("enum_1") }, - { JSONTestEnum::ENUM_2, _TXT("enum_2") }, - { JSONTestEnum::ENUM_3, _TXT("enum_3") }, - { JSONTestEnum::ENUM_4, _TXT("enum_4") }, - ENUM_CONVERSION_END(JSONTestEnum) +} // Core +} // Tests + + ENUM_CONVERSION_BEGIN(Tests::Core::JSONTestEnum) + { Tests::Core::JSONTestEnum::ENUM_1, _TXT("enum_1") }, + { Tests::Core::JSONTestEnum::ENUM_2, _TXT("enum_2") }, + { Tests::Core::JSONTestEnum::ENUM_3, _TXT("enum_3") }, + { Tests::Core::JSONTestEnum::ENUM_4, _TXT("enum_4") }, + ENUM_CONVERSION_END(Tests::Core::JSONTestEnum) namespace Tests { +namespace Core { + struct TestCaseBase { virtual ~TestCaseBase() = 0; @@ -53,12 +61,12 @@ namespace Tests { TestCaseBase::~TestCaseBase() {} template - class PrimitiveJson : public TestCaseBase, public Core::JSON::Container { + class PrimitiveJson : public TestCaseBase, public ::Thunder::Core::JSON::Container { public: - static_assert(std::is_base_of::value, "You have to derive from Core::JSON::IElement"); + static_assert(std::is_base_of<::Thunder::Core::JSON::IElement, T>::value, "You have to derive from ::Thunder::Core::JSON::IElement"); explicit PrimitiveJson() - : Core::JSON::Container() + : ::Thunder::Core::JSON::Container() { } @@ -102,7 +110,7 @@ namespace Tests { void Execute(T& test, const std::string& testJSON, bool valid) { static_assert(std::is_base_of::value, "This is to be run against TCs"); - Core::OptionalType error; + ::Thunder::Core::OptionalType<::Thunder::Core::JSON::Error> error; const bool result = test.FromString(testJSON, error); EXPECT_EQ(valid, result); EXPECT_NE(valid, error.IsSet()); @@ -135,7 +143,7 @@ namespace Tests { TestData data; data.key = "key"; data.keyToPutInJson = "\"" + data.key + "\""; - ExecutePrimitiveJsonTest(data, false, [](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, false, [](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(string{}, v.Value()); }); } @@ -146,7 +154,7 @@ namespace Tests { data.key = "key"; data.keyToPutInJson = "\"" + data.key + "\""; data.keyValueSeparator.clear(); - ExecutePrimitiveJsonTest(data, false, [](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, false, [](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(string{}, v.Value()); }); } @@ -157,7 +165,7 @@ namespace Tests { data.key = "[\"key\"]"; data.keyToPutInJson = data.key; data.keyValueSeparator.clear(); - ExecutePrimitiveJsonTest(data, false, [](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, false, [](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(string{}, v.Value()); }); } @@ -168,7 +176,7 @@ namespace Tests { data.key = "\"key\","; data.keyToPutInJson = data.key; data.keyValueSeparator.clear(); - ExecutePrimitiveJsonTest(data, false, [](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, false, [](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(string{}, v.Value()); }); } @@ -180,7 +188,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "value"; data.valueToPutInJson = "\"" + data.value + "\","; - ExecutePrimitiveJsonTest(data, false, [](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, false, [](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(string{}, v.Value()); }); } @@ -192,7 +200,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "value"; data.valueToPutInJson = "\"" + data.value + "\":"; - ExecutePrimitiveJsonTest(data, false, [](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, false, [](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(string{}, v.Value()); }); } @@ -204,7 +212,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\" :"; data.value = "value"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, false, [](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, false, [](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(string{}, v.Value()); }); } @@ -216,7 +224,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "value"; data.valueToPutInJson = "\"" + data.value + "\",,"; - ExecutePrimitiveJsonTest(data, false, [](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, false, [](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(string{}, v.Value()); }); } @@ -228,8 +236,8 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "[\"foo\", \"bar\"]"; data.valueToPutInJson = data.value; - ExecutePrimitiveJsonTest>( - data, true, [](const Core::JSON::ArrayType& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::String>>( + data, true, [](const ::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::String>& v) { EXPECT_EQ(2u, v.Length()); EXPECT_NE(string{}, v[0].Value()); EXPECT_NE(string{}, v[1].Value()); @@ -243,8 +251,8 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "null"; data.valueToPutInJson = data.value; - ExecutePrimitiveJsonTest>( - data, true, [](const Core::JSON::ArrayType& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::String>>( + data, true, [](const ::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::String>& v) { EXPECT_TRUE(v.IsNull()); }); } @@ -256,8 +264,8 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "nulk"; data.valueToPutInJson = data.value; - ExecutePrimitiveJsonTest>( - data, false, [](const Core::JSON::ArrayType& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::String>>( + data, false, [](const ::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::String>& v) { EXPECT_EQ(0u, v.Length()); }); } @@ -269,8 +277,8 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "[,]"; data.valueToPutInJson = "[,]"; - ExecutePrimitiveJsonTest>( - data, false, [](const Core::JSON::ArrayType& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::String>>( + data, false, [](const ::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::String>& v) { EXPECT_EQ(0u, v.Length()); }); } @@ -281,8 +289,8 @@ namespace Tests { data.key = "key"; data.keyToPutInJson = "\"" + data.key + "\""; data.valueToPutInJson = "(\"Foo\"]"; - ExecutePrimitiveJsonTest>( - data, false, [](const Core::JSON::ArrayType& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::String>>( + data, false, [](const ::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::String>& v) { EXPECT_EQ(0u, v.Length()); }); } @@ -293,8 +301,8 @@ namespace Tests { data.key = "key"; data.keyToPutInJson = "\"" + data.key + "\""; data.valueToPutInJson = "[\"Foo\"}"; - ExecutePrimitiveJsonTest>( - data, false, [](const Core::JSON::ArrayType& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::String>>( + data, false, [](const ::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::String>& v) { EXPECT_EQ(0u, v.Length()); }); } @@ -305,8 +313,8 @@ namespace Tests { data.key = "key"; data.keyToPutInJson = "\"" + data.key + "\""; data.valueToPutInJson = "[\"Foo\")"; - ExecutePrimitiveJsonTest>( - data, false, [](const Core::JSON::ArrayType& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::String>>( + data, false, [](const ::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::String>& v) { EXPECT_EQ(0u, v.Length()); }); } @@ -318,7 +326,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "value"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(data.value, v.Value()); }); } @@ -330,7 +338,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "null"; data.valueToPutInJson = data.value; - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { EXPECT_TRUE(v.IsNull()); }); } @@ -342,7 +350,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "value"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(data.value, v.Value()); }); } @@ -354,7 +362,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "value}"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(data.value, v.Value()); }); } @@ -366,7 +374,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = ":]"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(data.value, v.Value()); }); } @@ -378,7 +386,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "value"; data.valueToPutInJson = data.value; - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(data.value, v.Value()); }); } @@ -392,7 +400,7 @@ namespace Tests { data.value = "Φίλιππον ὁρῶ"; printf(" input value : %zd --- = %s \n", data.value.length(), data.value.c_str()); data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { printf(" output value : %zd --- = %s \n", v.Value().length(), v.Value().c_str()); EXPECT_EQ(data.value, v.Value()); }); @@ -408,7 +416,7 @@ namespace Tests { data.value = "კონფერენცია შეჰკრებს"; printf(" input value : %zd --- = %s \n", data.value.length(), data.value.c_str()); data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { printf(" output value : %zd --- = %s \n", v.Value().length(), v.Value().c_str()); EXPECT_EQ(data.value, v.Value()); }); @@ -423,7 +431,7 @@ namespace Tests { data.value = "Десятую Международную"; printf(" input value : %zd --- = %s \n", data.value.length(), data.value.c_str()); data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { printf(" output value : %zd --- = %s \n", v.Value().length(), v.Value().c_str()); EXPECT_EQ(data.value, v.Value()); }); @@ -438,7 +446,7 @@ namespace Tests { data.value = "suis heureuse"; printf(" input value : %zd --- = %s \n", data.value.length(), data.value.c_str()); data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { printf(" output value : %zd --- = %s \n", v.Value().length(), v.Value().c_str()); EXPECT_EQ(data.value, v.Value()); }); @@ -453,7 +461,7 @@ namespace Tests { data.value = "ใช้สาวนั้นเป็นชนวนชื่นชวนใจ"; printf(" input value : %zd --- = %s \n", data.value.length(), data.value.c_str()); data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { printf(" output value : %zd --- = %s \n", v.Value().length(), v.Value().c_str()); EXPECT_EQ(data.value, v.Value()); }); @@ -466,7 +474,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "value"; data.valueToPutInJson = "\"" + data.value; - ExecutePrimitiveJsonTest(data, false, [](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, false, [](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(string{}, v.Value()); }); } @@ -479,7 +487,7 @@ namespace Tests { data.value = "value"; data.valueToPutInJson = data.value + "\""; - ExecutePrimitiveJsonTest(data, false, [](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, false, [](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(string{}, v.Value()); }); } @@ -491,7 +499,7 @@ namespace Tests { data.keyToPutInJson = data.key; data.value = "value"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, false, [](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, false, [](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(string{}, v.Value()); }); } @@ -503,7 +511,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key; data.value = "value"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, false, [](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, false, [](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(string{}, v.Value()); }); } @@ -515,7 +523,7 @@ namespace Tests { data.keyToPutInJson = data.key + "\""; data.value = "value"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, false, [](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, false, [](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(string{}, v.Value()); }); } @@ -527,7 +535,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "123"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [](const Core::JSON::DecUInt8& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::DecUInt8>(data, true, [](const ::Thunder::Core::JSON::DecUInt8& v) { EXPECT_EQ(123u, v.Value()); }); } @@ -539,7 +547,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "null"; data.valueToPutInJson = data.value; - ExecutePrimitiveJsonTest(data, true, [](const Core::JSON::DecUInt8& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::DecUInt8>(data, true, [](const ::Thunder::Core::JSON::DecUInt8& v) { EXPECT_TRUE(v.IsNull()); }); } @@ -551,7 +559,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "-123"; data.valueToPutInJson = data.value; - ExecutePrimitiveJsonTest(data, true, [](const Core::JSON::DecSInt8& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::DecSInt8>(data, true, [](const ::Thunder::Core::JSON::DecSInt8& v) { EXPECT_EQ(-123, v.Value()); }); } @@ -563,7 +571,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "+123"; data.valueToPutInJson = data.value; - ExecutePrimitiveJsonTest(data, false, [](const Core::JSON::DecSInt8& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::DecSInt8>(data, false, [](const ::Thunder::Core::JSON::DecSInt8& v) { EXPECT_NE(123, v.Value()); }); } @@ -575,7 +583,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "123g"; data.valueToPutInJson = data.value; - ExecutePrimitiveJsonTest(data, false, [](const Core::JSON::DecUInt8& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::DecUInt8>(data, false, [](const ::Thunder::Core::JSON::DecUInt8& v) { EXPECT_EQ(0u, v.Value()); }); } @@ -587,7 +595,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "0X7B"; data.valueToPutInJson = "\"" + data.value + "\"";; - ExecutePrimitiveJsonTest(data, true, [](const Core::JSON::HexUInt8& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::HexUInt8>(data, true, [](const ::Thunder::Core::JSON::HexUInt8& v) { EXPECT_EQ(123u, v.Value()); }); } @@ -599,7 +607,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "-0X7B"; data.valueToPutInJson = "\"" + data.value + "\"";; - ExecutePrimitiveJsonTest(data, true, [](const Core::JSON::HexSInt8& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::HexSInt8>(data, true, [](const ::Thunder::Core::JSON::HexSInt8& v) { EXPECT_EQ(-123, v.Value()); }); } @@ -611,7 +619,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "0173"; data.valueToPutInJson = "\"" + data.value + "\"";; - ExecutePrimitiveJsonTest(data, true, [](const Core::JSON::OctUInt8& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::OctUInt8>(data, true, [](const ::Thunder::Core::JSON::OctUInt8& v) { EXPECT_EQ(123u, v.Value()); }); } @@ -623,7 +631,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "-0173"; data.valueToPutInJson = "\"" + data.value + "\"";; - ExecutePrimitiveJsonTest(data, true, [](const Core::JSON::OctSInt8& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::OctSInt8>(data, true, [](const ::Thunder::Core::JSON::OctSInt8& v) { EXPECT_EQ(-123, v.Value()); }); } @@ -635,7 +643,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "1e2"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, false, [](const Core::JSON::DecUInt8& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::DecUInt8>(data, false, [](const ::Thunder::Core::JSON::DecUInt8& v) { EXPECT_EQ(100u, v.Value()); }); } @@ -647,7 +655,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "1.34f"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [data](const Core::JSON::Float& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::Float>(data, true, [data](const ::Thunder::Core::JSON::Float& v) { std::ostringstream value; value << v.Value(); std::string res = value.str(); @@ -672,7 +680,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "1.3"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [data](const Core::JSON::Float& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::Float>(data, true, [data](const ::Thunder::Core::JSON::Float& v) { std::ostringstream value; value << v.Value(); @@ -692,7 +700,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "1.35"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [data](const Core::JSON::Float& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::Float>(data, true, [data](const ::Thunder::Core::JSON::Float& v) { std::ostringstream value; value << v.Value(); @@ -712,7 +720,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "2.349"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [data](const Core::JSON::Float& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::Float>(data, true, [data](const ::Thunder::Core::JSON::Float& v) { std::ostringstream value; value << v.Value(); @@ -732,7 +740,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "48.3"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [data](const Core::JSON::Float& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::Float>(data, true, [data](const ::Thunder::Core::JSON::Float& v) { std::ostringstream value; value << v.Value(); @@ -752,7 +760,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "48.39"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [data](const Core::JSON::Float& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::Float>(data, true, [data](const ::Thunder::Core::JSON::Float& v) { std::ostringstream value; value << v.Value(); @@ -772,7 +780,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "48.398"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [data](const Core::JSON::Float& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::Float>(data, true, [data](const ::Thunder::Core::JSON::Float& v) { std::ostringstream value; value << v.Value(); @@ -792,7 +800,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "489.3"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [data](const Core::JSON::Float& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::Float>(data, true, [data](const ::Thunder::Core::JSON::Float& v) { std::ostringstream value; value << v.Value(); @@ -812,7 +820,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "489.38"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [data](const Core::JSON::Float& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::Float>(data, true, [data](const ::Thunder::Core::JSON::Float& v) { std::ostringstream value; value << v.Value(); @@ -832,7 +840,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "489.389"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [data](const Core::JSON::Float& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::Float>(data, true, [data](const ::Thunder::Core::JSON::Float& v) { std::ostringstream value; value << v.Value(); @@ -852,7 +860,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "6.61914e+6"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [data](const Core::JSON::Double& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::Double>(data, true, [data](const ::Thunder::Core::JSON::Double& v) { std::ostringstream value; value << v.Value(); @@ -872,7 +880,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "3.5"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [data](const Core::JSON::Double& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::Double>(data, true, [data](const ::Thunder::Core::JSON::Double& v) { std::ostringstream value; value << v.Value(); @@ -892,7 +900,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "3.56"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [data](const Core::JSON::Double& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::Double>(data, true, [data](const ::Thunder::Core::JSON::Double& v) { std::ostringstream value; value << v.Value(); @@ -912,7 +920,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "3.567"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [data](const Core::JSON::Double& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::Double>(data, true, [data](const ::Thunder::Core::JSON::Double& v) { std::ostringstream value; value << v.Value(); @@ -932,7 +940,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "32.5"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [data](const Core::JSON::Double& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::Double>(data, true, [data](const ::Thunder::Core::JSON::Double& v) { std::ostringstream value; value << v.Value(); @@ -952,7 +960,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "32.59"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [data](const Core::JSON::Double& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::Double>(data, true, [data](const ::Thunder::Core::JSON::Double& v) { std::ostringstream value; value << v.Value(); @@ -972,7 +980,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "32.598"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [data](const Core::JSON::Double& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::Double>(data, true, [data](const ::Thunder::Core::JSON::Double& v) { std::ostringstream value; value << v.Value(); @@ -992,7 +1000,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "326.5"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [data](const Core::JSON::Double& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::Double>(data, true, [data](const ::Thunder::Core::JSON::Double& v) { std::ostringstream value; value << v.Value(); @@ -1012,7 +1020,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "326.56"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [data](const Core::JSON::Double& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::Double>(data, true, [data](const ::Thunder::Core::JSON::Double& v) { std::ostringstream value; value << v.Value(); @@ -1032,7 +1040,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "326.545"; data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest(data, true, [data](const Core::JSON::Double& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::Double>(data, true, [data](const ::Thunder::Core::JSON::Double& v) { std::ostringstream value; value << v.Value(); @@ -1058,7 +1066,7 @@ namespace Tests { data.valueToPutInJson = "\"" + valueJSONFormatted + "\""; // Key and value in container are both JSON strings - ExecutePrimitiveJsonTest(data, true, [&data, &valueJSONFormatted](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data, &valueJSONFormatted](const ::Thunder::Core::JSON::String& v) { ASSERT_TRUE(v.IsQuoted()); string value; @@ -1084,7 +1092,7 @@ namespace Tests { data.valueToPutInJson = "\"" + valueJSONFormatted + "\""; // Key and value in container are both JSON strings - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { ASSERT_TRUE(v.IsQuoted()); string value; @@ -1110,7 +1118,7 @@ namespace Tests { data.valueToPutInJson = "\"" + valueJSONFormatted + "\""; // Key and value in container are both JSON strings - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { ASSERT_TRUE(v.IsQuoted()); string value; @@ -1137,7 +1145,7 @@ namespace Tests { data.valueToPutInJson = "\"" + valueJSONFormatted + "\""; // Key and value in container are both JSON strings - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { ASSERT_TRUE(v.IsQuoted()); string value; @@ -1163,7 +1171,7 @@ namespace Tests { data.valueToPutInJson = "\"" + valueJSONFormatted + "\""; // Key and value in container are both JSON strings - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { ASSERT_TRUE(v.IsQuoted()); string value; @@ -1191,7 +1199,7 @@ namespace Tests { data.valueToPutInJson = "\"" + valueJSONFormatted + "\""; // Key and value in container are both JSON strings - ExecutePrimitiveJsonTest(data, true, [&data, &valueExpected](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data, &valueExpected](const ::Thunder::Core::JSON::String& v) { ASSERT_TRUE(v.IsQuoted()); string value; @@ -1218,7 +1226,7 @@ namespace Tests { data.valueToPutInJson = "\"" + valueJSONFormatted + "\""; // Key and value in container are both JSON strings - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { ASSERT_TRUE(v.IsQuoted()); string value; @@ -1245,7 +1253,7 @@ namespace Tests { data.valueToPutInJson = "\"" + valueJSONFormatted + "\""; // Key and value in container are both JSON strings - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { ASSERT_TRUE(v.IsQuoted()); string value; @@ -1272,7 +1280,7 @@ namespace Tests { data.valueToPutInJson = "\"" + valueJSONFormatted + "\""; // Key and value in container are both JSON strings - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { ASSERT_TRUE(v.IsQuoted()); string value; @@ -1299,7 +1307,7 @@ namespace Tests { data.valueToPutInJson = "\"" + valueJSONFormatted + "\""; // Key and value in container are both JSON strings - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { ASSERT_TRUE(v.IsQuoted()); string value; @@ -1326,7 +1334,7 @@ namespace Tests { data.valueToPutInJson = "\"" + valueJSONFormatted + "\""; // Key and value in container are both JSON strings - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { ASSERT_TRUE(v.IsQuoted()); string value; @@ -1354,7 +1362,7 @@ namespace Tests { data.valueToPutInJson = "\"" + valueJSONFormatted + "\""; // Key and value in container are both JSON strings - ExecutePrimitiveJsonTest(data, true, [&data, &valueExpected](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data, &valueExpected](const ::Thunder::Core::JSON::String& v) { ASSERT_TRUE(v.IsQuoted()); string value; @@ -1380,7 +1388,7 @@ namespace Tests { data.valueToPutInJson = "\"" + valueJSONFormatted + "\""; // Key and value in container are both JSON strings - ExecutePrimitiveJsonTest(data, false, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, false, [&data](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(string{}, v.Value()); }); } @@ -1400,7 +1408,7 @@ namespace Tests { data.valueToPutInJson = "\"" + valueJSONFormatted + "\""; // Key and value in container are both JSON strings - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { ASSERT_TRUE(v.IsQuoted()); string value; @@ -1426,7 +1434,7 @@ namespace Tests { data.valueToPutInJson = "\"" + valueJSONFormatted + "\""; // Key and value in container are both JSON strings - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { ASSERT_TRUE(v.IsQuoted()); string value; @@ -1454,7 +1462,7 @@ namespace Tests { data.valueToPutInJson = "\"" + valueJSONFormatted + "\""; - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { ASSERT_TRUE(v.IsQuoted()); string value; @@ -1481,7 +1489,7 @@ namespace Tests { data.valueToPutInJson = "\"" + valueJSONFormatted + "\""; // Key and value in container are both JSON strings - ExecutePrimitiveJsonTest(data, false, [](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, false, [](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(string{}, v.Value()); }); } @@ -1501,7 +1509,7 @@ namespace Tests { data.valueToPutInJson = "\"" + valueJSONFormatted + "\""; // Key and value in container are both JSON strings - ExecutePrimitiveJsonTest(data, false, [] (const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, false, [] (const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(string{}, v.Value()); }); } @@ -1516,7 +1524,7 @@ namespace Tests { data.valueToPutInJson = "{\"" + data.key + "\":\"" + data.value + "\"}"; - ExecutePrimitiveJsonTest>(data, true, [&data](const PrimitiveJson& v) { + ExecutePrimitiveJsonTest>(data, true, [&data](const PrimitiveJson<::Thunder::Core::JSON::String>& v) { EXPECT_TRUE(v.HasLabel(data.key)); EXPECT_EQ(data.value, v.Value().Value()); }); @@ -1530,7 +1538,7 @@ namespace Tests { data.valueToPutInJson = "{\"" + data.key + "\":\"" + data.value + "\"}"; - ExecutePrimitiveJsonTest>(data, true, [&data](const PrimitiveJson& v) { + ExecutePrimitiveJsonTest>(data, true, [&data](const PrimitiveJson<::Thunder::Core::JSON::String>& v) { EXPECT_TRUE(v.HasLabel(data.key)); EXPECT_EQ(string{}, v.Value().Value()); }); @@ -1546,7 +1554,7 @@ namespace Tests { data.valueToPutInJson = data.value; - ExecutePrimitiveJsonTest>(data, true, [](const PrimitiveJson& v) { + ExecutePrimitiveJsonTest>(data, true, [](const PrimitiveJson<::Thunder::Core::JSON::String>& v) { EXPECT_TRUE(v.IsNull()); }); } @@ -1561,7 +1569,7 @@ namespace Tests { data.valueToPutInJson = data.value; - ExecutePrimitiveJsonTest>(data, false, nullptr); + ExecutePrimitiveJsonTest>(data, false, nullptr); } TEST(JSONParser, Unmatched1) @@ -1574,7 +1582,7 @@ namespace Tests { data.valueToPutInJson = "[" + data.value + "}"; - ExecutePrimitiveJsonTest>(data, false, nullptr); + ExecutePrimitiveJsonTest>(data, false, nullptr); } TEST(JSONParser, Unmatched2) @@ -1584,7 +1592,7 @@ namespace Tests { data.keyToPutInJson = "\"" + data.key + "\""; data.value = "\"" + data.key + "\":\"value\""; data.valueToPutInJson = "{" + data.value + "]"; - ExecutePrimitiveJsonTest>(data, false, nullptr); + ExecutePrimitiveJsonTest>(data, false, nullptr); } // Extensions: @@ -1598,7 +1606,7 @@ namespace Tests { data.valueToPutInJson = data.value; - ExecutePrimitiveJsonTest(data, false, nullptr); + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::Buffer>(data, false, nullptr); } TEST(JSONParser, OpaqueObject) @@ -1611,7 +1619,7 @@ namespace Tests { data.valueToPutInJson = data.value; - ExecutePrimitiveJsonTest(data, true, [&data](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, [&data](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(data.value, v.Value()); }); } @@ -1629,7 +1637,7 @@ namespace Tests { data.valueToPutInJson = data.value; - ExecutePrimitiveJsonTest(data, true, nullptr); + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, true, nullptr); } TEST(JSONParser, MalformedOpaqueObject1) @@ -1642,7 +1650,7 @@ namespace Tests { data.valueToPutInJson = data.value; - ExecutePrimitiveJsonTest(data, false, [](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, false, [](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(string{}, v.Value()); }); } @@ -1657,7 +1665,7 @@ namespace Tests { data.valueToPutInJson = data.value; - ExecutePrimitiveJsonTest(data, false, [](const Core::JSON::String& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::String>(data, false, [](const ::Thunder::Core::JSON::String& v) { EXPECT_EQ(string{}, v.Value()); }); } @@ -1672,7 +1680,7 @@ namespace Tests { data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest>(data, true, [&data](const Core::JSON::EnumType& v) { + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::EnumType>(data, true, [&data](const ::Thunder::Core::JSON::EnumType& v) { EXPECT_EQ(JSONTestEnum::ENUM_2, v.Value()); }); } @@ -1687,18 +1695,18 @@ namespace Tests { data.valueToPutInJson = "\"" + data.value + "\""; - ExecutePrimitiveJsonTest>(data, false, nullptr); + ExecutePrimitiveJsonTest<::Thunder::Core::JSON::EnumType>(data, false, nullptr); } #ifdef _0 TEST(JSONParser, Variant) { - Thunder::Core::JSON::Variant variant; - Thunder::Core::JSON::Variant variant1(std::numeric_limits::min()); + ::Thunder::Core::JSON::Variant variant; + ::Thunder::Core::JSON::Variant variant1(std::numeric_limits::min()); - Thunder::Core::JSON::Variant variant2(std::numeric_limits::min()); - Thunder::Core::JSON::Variant variant3(std::numeric_limits::min()); - Thunder::Core::JSON::Variant variant4(std::numeric_limits::min()); - Thunder::Core::JSON::Variant variant5(true); + ::Thunder::Core::JSON::Variant variant2(std::numeric_limits::min()); + ::Thunder::Core::JSON::Variant variant3(std::numeric_limits::min()); + ::Thunder::Core::JSON::Variant variant4(std::numeric_limits::min()); + ::Thunder::Core::JSON::Variant variant5(true); //EXPECT_EQ(variant1.Number(), 0); //TODO EXPECT_EQ(variant2.Number(), 0); @@ -1706,31 +1714,31 @@ namespace Tests { EXPECT_EQ(variant4.Number(), 0); const TCHAR text[] = "varient"; - Thunder::Core::JSON::Variant variant6(text); + ::Thunder::Core::JSON::Variant variant6(text); EXPECT_STREQ(variant6.String().c_str(), text); - Thunder::Core::JSON::Variant variant6_new = text; + ::Thunder::Core::JSON::Variant variant6_new = text; EXPECT_STREQ(variant6_new.String().c_str(), text); std::string msg = "varient"; - Thunder::Core::JSON::Variant variant7(msg); + ::Thunder::Core::JSON::Variant variant7(msg); EXPECT_STREQ(variant7.String().c_str(), msg.c_str()); - Thunder::Core::JSON::Variant variant8(variant4); + ::Thunder::Core::JSON::Variant variant8(variant4); - Thunder::Core::JSON::VariantContainer container; - Thunder::Core::JSON::Variant val1(10); - Thunder::Core::JSON::Variant val2(20); - Thunder::Core::JSON::Variant val3(30); + ::Thunder::Core::JSON::VariantContainer container; + ::Thunder::Core::JSON::Variant val1(10); + ::Thunder::Core::JSON::Variant val2(20); + ::Thunder::Core::JSON::Variant val3(30); container.Set("key1", val1); container.Set("key2", val2); container.Set("key3", val3); - Thunder::Core::JSON::Variant variant9(container); + ::Thunder::Core::JSON::Variant variant9(container); msg = "name=key1 type=Object value={\n name=key1 type=Number value=10\n name=key2 type=Number value=20\n name=key3 type=Number value=30\n}\n"; EXPECT_STREQ(variant9.GetDebugString("key1").c_str(), msg.c_str()); variant2.Boolean(true); - Thunder::Core::JSON::Variant variant10 = variant4; + ::Thunder::Core::JSON::Variant variant10 = variant4; variant5.Content(); EXPECT_TRUE(variant5.Boolean()); @@ -1744,25 +1752,25 @@ namespace Tests { variant6.Boolean(true); - Thunder::Core::JSON::Variant variant11; + ::Thunder::Core::JSON::Variant variant11; variant11.Object(container); msg = "name=key1 type=Object value={\n name=key1 type=Number value=10\n name=key2 type=Number value=20\n name=key3 type=Number value=30\n}\n"; EXPECT_STREQ(variant11.GetDebugString("key1").c_str(), msg.c_str()); - Thunder::Core::JSON::VariantContainer variantContainer = variant11.Object(); + ::Thunder::Core::JSON::VariantContainer variantContainer = variant11.Object(); EXPECT_EQ(variantContainer.Get("key1").String(), "10"); } TEST(JSONParser, VariantContainer) { - Thunder::Core::JSON::VariantContainer container; + ::Thunder::Core::JSON::VariantContainer container; - Thunder::Core::JSON::Variant val1(10); - Thunder::Core::JSON::Variant val2(20); - Thunder::Core::JSON::Variant val3(30); - Thunder::Core::JSON::Variant val4(40); - Thunder::Core::JSON::Variant val5(50); - Thunder::Core::JSON::Variant val6(60); + ::Thunder::Core::JSON::Variant val1(10); + ::Thunder::Core::JSON::Variant val2(20); + ::Thunder::Core::JSON::Variant val3(30); + ::Thunder::Core::JSON::Variant val4(40); + ::Thunder::Core::JSON::Variant val5(50); + ::Thunder::Core::JSON::Variant val6(60); container.Set("key1", val1); container.Set("key2", val2); @@ -1775,29 +1783,29 @@ namespace Tests { EXPECT_EQ((container.Get("key1")).String(), "10"); EXPECT_EQ((container["key5"]).String(), "50"); - Thunder::Core::JSON::Variant variant1 = container["key5"]; - const Thunder::Core::JSON::Variant variant2 = container["key5"]; + ::Thunder::Core::JSON::Variant variant1 = container["key5"]; + const ::Thunder::Core::JSON::Variant variant2 = container["key5"]; EXPECT_EQ(variant1.String(), "50"); EXPECT_EQ(variant2.String(), "50"); std::string serialize = "{\"key1\":\"hello\"}"; - Thunder::Core::JSON::VariantContainer container1(serialize); + ::Thunder::Core::JSON::VariantContainer container1(serialize); std::string text; container1.ToString(text); EXPECT_STREQ(text.c_str(),serialize.c_str()); serialize = "\"key1\":\"hello\""; //Trigger a call to ErrorDisplayMessage() with purposefully created error condition. - Thunder::Core::JSON::VariantContainer errorContainer(serialize); + ::Thunder::Core::JSON::VariantContainer errorContainer(serialize); errorContainer.ToString(text); const TCHAR serialized[] = "{\"key2\":\"checking\"}"; - Thunder::Core::JSON::VariantContainer container2(serialized); + ::Thunder::Core::JSON::VariantContainer container2(serialized); container2.ToString(text); EXPECT_STREQ(text.c_str(), serialized); - Thunder::Core::JSON::VariantContainer container_new(container2); - Thunder::Core::JSON::VariantContainer container_copy = container_new; + ::Thunder::Core::JSON::VariantContainer container_new(container2); + ::Thunder::Core::JSON::VariantContainer container_copy = container_new; std::string debugString = " name=key1 type=Number value=10\n name=key2 type=Number value=20\n name=key3 type=Number value=30\n name=key4 type=Number value=40\n name=key5 type=Number value=50\n name=key6 type=Number value=60\n"; EXPECT_STREQ(container.GetDebugString(3).c_str(), debugString.c_str()); @@ -1805,20 +1813,20 @@ namespace Tests { TEST(JSONParser, VariantDebugStringNumber) { - Thunder::Core::JSON::Variant variant(10); + ::Thunder::Core::JSON::Variant variant(10); std::string debugString = " [0] name=hello type=Number value=10\n"; EXPECT_STREQ(variant.GetDebugString("hello",3,0).c_str(), debugString.c_str()); - Thunder::Core::JSON::Variant variant1 = std::numeric_limits::min(); + ::Thunder::Core::JSON::Variant variant1 = std::numeric_limits::min(); EXPECT_EQ(variant1.Number(), 0); - Thunder::Core::JSON::Variant variant2 = 10; + ::Thunder::Core::JSON::Variant variant2 = 10; EXPECT_EQ(variant2.Number(), 10); } TEST(JSONParser, VariantDebugStringEmpty) { - Thunder::Core::JSON::Variant variant; + ::Thunder::Core::JSON::Variant variant; std::string debugString = " [0] name=hello type=Empty value=null\n"; EXPECT_STREQ(variant.GetDebugString("hello", 1, 0).c_str(), debugString.c_str()); @@ -1826,81 +1834,81 @@ namespace Tests { TEST(JSONParser, VariantDebugStringBoolean) { - Thunder::Core::JSON::Variant variant(true); + ::Thunder::Core::JSON::Variant variant(true); std::string debugString = " [0] name=hello type=Boolean value=true\n"; EXPECT_STREQ(variant.GetDebugString("hello", 1, 0).c_str(), debugString.c_str()); - Thunder::Core::JSON::Variant variant1 = true; + ::Thunder::Core::JSON::Variant variant1 = true; EXPECT_STREQ(variant1.GetDebugString("hello", 1, 0).c_str(), debugString.c_str()); } TEST(JSONParser, VariantDebugStringString) { - Thunder::Core::JSON::Variant variant("Variant"); + ::Thunder::Core::JSON::Variant variant("Variant"); std::string debugString = " [0] name=hello type=String value=Variant\n"; EXPECT_STREQ(variant.GetDebugString("hello", 1, 0).c_str(), debugString.c_str()); - Thunder::Core::JSON::Variant variant1 = "Variant"; + ::Thunder::Core::JSON::Variant variant1 = "Variant"; EXPECT_STREQ(variant1.GetDebugString("hello", 1, 0).c_str(), debugString.c_str()); } TEST(JSONParser, VariantDebugStringArray) { - Thunder::Core::JSON::ArrayType array; - array.Add(Thunder::Core::JSON::Variant(10)); - Thunder::Core::JSON::Variant variant(array); + ::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::Variant> array; + array.Add(::Thunder::Core::JSON::Variant(10)); + ::Thunder::Core::JSON::Variant variant(array); std::string debugString = " [0] name=hello type=String value=[10]\n"; EXPECT_STREQ(variant.GetDebugString("hello", 1, 0).c_str(), debugString.c_str()); - Thunder::Core::JSON::Variant variant1 = Thunder::Core::JSON::Variant(array); + ::Thunder::Core::JSON::Variant variant1 = ::Thunder::Core::JSON::Variant(array); EXPECT_STREQ(variant1.GetDebugString("hello", 1, 0).c_str(), debugString.c_str()); - Thunder::Core::JSON::Variant variant2; + ::Thunder::Core::JSON::Variant variant2; variant2.Array(array); - Thunder::Core::JSON::ArrayType result; + ::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::Variant> result; result = variant2.Array(); - Thunder::Core::JSON::Variant variant3(result); + ::Thunder::Core::JSON::Variant variant3(result); EXPECT_STREQ(variant3.GetDebugString("hello", 1, 0).c_str(), debugString.c_str());; } TEST(JSONParser, VariantDebugStringObject) { - Thunder::Core::JSON::VariantContainer container; - Thunder::Core::JSON::Variant val1(10); - Thunder::Core::JSON::Variant val2(20); - Thunder::Core::JSON::Variant val3(30); + ::Thunder::Core::JSON::VariantContainer container; + ::Thunder::Core::JSON::Variant val1(10); + ::Thunder::Core::JSON::Variant val2(20); + ::Thunder::Core::JSON::Variant val3(30); container.Set("key1", val1); container.Set("key2", val2); container.Set("key3", val3); - Thunder::Core::JSON::Variant variant(container); + ::Thunder::Core::JSON::Variant variant(container); std::string debugString = " [0] name=hello type=Object value={\n name=key1 type=Number value=10\n name=key2 type=Number value=20\n name=key3 type=Number value=30\n }\n"; EXPECT_STREQ(variant.GetDebugString("hello", 1, 0).c_str(), debugString.c_str()); - Thunder::Core::JSON::Variant variant1 = container; + ::Thunder::Core::JSON::Variant variant1 = container; EXPECT_STREQ(variant1.GetDebugString("hello", 1, 0).c_str(), debugString.c_str()); } TEST(JSONParser, VariantContainerWithElements) { - std::list> elements; + std::list> elements; - Thunder::Core::JSON::Variant val1(10); - Thunder::Core::JSON::Variant val2(20); - Thunder::Core::JSON::Variant val3(30); + ::Thunder::Core::JSON::Variant val1(10); + ::Thunder::Core::JSON::Variant val2(20); + ::Thunder::Core::JSON::Variant val3(30); - elements.push_back(std::pair("Key1", val1)); - elements.push_back(std::pair("Key2", val2)); - elements.push_back(std::pair("Key3", val3)); + elements.push_back(std::pair("Key1", val1)); + elements.push_back(std::pair("Key2", val2)); + elements.push_back(std::pair("Key3", val3)); - Thunder::Core::JSON::VariantContainer container(elements); + ::Thunder::Core::JSON::VariantContainer container(elements); - Thunder::Core::JSON::VariantContainer::Iterator it = container.Variants(); + ::Thunder::Core::JSON::VariantContainer::Iterator it = container.Variants(); EXPECT_TRUE(it.Next()); EXPECT_TRUE(container.HasLabel("Key1")); EXPECT_TRUE(it.IsValid()); @@ -1908,20 +1916,20 @@ namespace Tests { TEST(JSONParser, VariantContainerIterator) { - std::list> elements; + std::list> elements; - Thunder::Core::JSON::Variant val1(10); - Thunder::Core::JSON::Variant val2(20); - Thunder::Core::JSON::Variant val3(30); + ::Thunder::Core::JSON::Variant val1(10); + ::Thunder::Core::JSON::Variant val2(20); + ::Thunder::Core::JSON::Variant val3(30); - elements.push_back(std::pair("Key1", val1)); - elements.push_back(std::pair("Key2", val2)); - elements.push_back(std::pair("Key3", val3)); + elements.push_back(std::pair("Key1", val1)); + elements.push_back(std::pair("Key2", val2)); + elements.push_back(std::pair("Key3", val3)); - Thunder::Core::JSON::VariantContainer::Iterator iterator; - Thunder::Core::JSON::VariantContainer::Iterator it(elements); - Thunder::Core::JSON::VariantContainer::Iterator itCopy(iterator); - Thunder::Core::JSON::VariantContainer::Iterator iteratorCopy = itCopy; + ::Thunder::Core::JSON::VariantContainer::Iterator iterator; + ::Thunder::Core::JSON::VariantContainer::Iterator it(elements); + ::Thunder::Core::JSON::VariantContainer::Iterator itCopy(iterator); + ::Thunder::Core::JSON::VariantContainer::Iterator iteratorCopy = itCopy; EXPECT_TRUE(it.Next()); EXPECT_TRUE(it.IsValid()); @@ -1937,7 +1945,7 @@ namespace Tests { { // UTF8 for the violin music key: (byte array) f0 9d 84 9e => CodePoint 0x1D11E => UTF16 0xD834 0xDD1E string input = R"("Violin key sending: \uD834\uDD1E")"; - Core::JSON::String json; + ::Thunder::Core::JSON::String json; string received; json.FromString(input); @@ -1946,7 +1954,7 @@ namespace Tests { } { string input = R"("Control: [25][\u0019] Character: [28][\u001C]")"; - Core::JSON::String json; + ::Thunder::Core::JSON::String json; string received; json.FromString(input); @@ -1954,7 +1962,7 @@ namespace Tests { EXPECT_STREQ(input.c_str(), received.c_str()); } { - Core::JSONRPC::Message message; + ::Thunder::Core::JSONRPC::Message message; string input = R"({"jsonrpc":"2.0","id":1234567890,"method":"WifiControl.1.connect","params":{"ssid":"iPhone\\"}})"; string received; @@ -1973,7 +1981,7 @@ namespace Tests { // It should show it as an UTF8 string show : "aλόγουςb" but the string, // should have the hex bytes as shown above. string input = R"("a\u03BB\u1F79\u03B3\u03BF\u03C5\u03C2b")"; - Core::JSON::String json; + ::Thunder::Core::JSON::String json; string received; json.FromString(input); @@ -1982,7 +1990,7 @@ namespace Tests { } { string input = R"("Wrong code: \uD4\u1E")"; - Core::JSON::String json; + ::Thunder::Core::JSON::String json; string received; json.FromString(input); @@ -1991,13 +1999,13 @@ namespace Tests { } } - class SmallTest : public Thunder::Core::JSON::Container { + class SmallTest : public ::Thunder::Core::JSON::Container { public: SmallTest(const SmallTest&) = delete; SmallTest& operator=(const SmallTest&) = delete; SmallTest() - : Core::JSON::Container() + : ::Thunder::Core::JSON::Container() , A(0) , B(0) , C() @@ -2014,23 +2022,23 @@ namespace Tests { public: void Clear() { - Core::JSON::Container::Clear(); + ::Thunder::Core::JSON::Container::Clear(); } - Core::JSON::DecUInt32 A; - Core::JSON::Float B; - Core::JSON::String C; - Core::JSON::Boolean D; - Core::JSON::EnumType E; + ::Thunder::Core::JSON::DecUInt32 A; + ::Thunder::Core::JSON::Float B; + ::Thunder::Core::JSON::String C; + ::Thunder::Core::JSON::Boolean D; + ::Thunder::Core::JSON::EnumType E; }; - class SmallTest2 : public Thunder::Core::JSON::Container { + class SmallTest2 : public ::Thunder::Core::JSON::Container { public: SmallTest2(const SmallTest2&) = delete; SmallTest2& operator=(const SmallTest2&) = delete; SmallTest2() - : Core::JSON::Container() + : ::Thunder::Core::JSON::Container() , A() , B(0.0) , C(0.0) { @@ -2043,15 +2051,15 @@ namespace Tests { public: void Clear() { - Core::JSON::Container::Clear(); + ::Thunder::Core::JSON::Container::Clear(); } - Core::JSON::ArrayType A; - Core::JSON::Float B; - Core::JSON::Double C; + ::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::String> A; + ::Thunder::Core::JSON::Float B; + ::Thunder::Core::JSON::Double C; }; - class StringContainer : public Core::JSON::Container { + class StringContainer : public ::Thunder::Core::JSON::Container { public: StringContainer(const StringContainer&) = delete; StringContainer& operator=(const StringContainer&) = delete; @@ -2063,13 +2071,13 @@ namespace Tests { ~StringContainer() override = default; public: - Core::JSON::String Name; + ::Thunder::Core::JSON::String Name; }; - class ParamsInfo : public Core::JSON::Container { + class ParamsInfo : public ::Thunder::Core::JSON::Container { public: ParamsInfo() - : Core::JSON::Container() { + : ::Thunder::Core::JSON::Container() { Add(_T("ssid"), &Ssid); } ~ParamsInfo() override = default; @@ -2078,16 +2086,16 @@ namespace Tests { ParamsInfo& operator=(const ParamsInfo&) = delete; public: - Core::JSON::String Ssid; // Identifier of a network + ::Thunder::Core::JSON::String Ssid; // Identifier of a network }; - class CommandParameters : public Thunder::Core::JSON::Container { + class CommandParameters : public ::Thunder::Core::JSON::Container { public: CommandParameters(const CommandParameters&) = delete; CommandParameters& operator=(const CommandParameters&) = delete; CommandParameters() - : Core::JSON::Container() + : ::Thunder::Core::JSON::Container() , G(00) , H(0) , I() @@ -2105,22 +2113,22 @@ namespace Tests { ~CommandParameters() override = default; public: - Thunder::Core::JSON::OctSInt16 G; - Thunder::Core::JSON::DecSInt16 H; - Thunder::Core::JSON::EnumType I; - Thunder::Core::JSON::ArrayType J; - Thunder::Core::JSON::Float K; - Thunder::Core::JSON::Double L; + ::Thunder::Core::JSON::OctSInt16 G; + ::Thunder::Core::JSON::DecSInt16 H; + ::Thunder::Core::JSON::EnumType I; + ::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::DecUInt16> J; + ::Thunder::Core::JSON::Float K; + ::Thunder::Core::JSON::Double L; }; - class CommandRequest : public Thunder::Core::JSON::Container { + class CommandRequest : public ::Thunder::Core::JSON::Container { public: CommandRequest(const CommandRequest&) = delete; CommandRequest& operator=(const CommandRequest&) = delete; public: CommandRequest() - : Core::JSON::Container() + : ::Thunder::Core::JSON::Container() , A(0x0) , B() , C(0x0) @@ -2146,19 +2154,19 @@ namespace Tests { void Clear() { - Thunder::Core::JSON::Container::Clear(); + ::Thunder::Core::JSON::Container::Clear(); } public: - Thunder::Core::JSON::HexSInt32 A; - Thunder::Core::JSON::String B; - Thunder::Core::JSON::HexUInt32 C; - Thunder::Core::JSON::Boolean D; - Thunder::Core::JSON::OctUInt16 E; + ::Thunder::Core::JSON::HexSInt32 A; + ::Thunder::Core::JSON::String B; + ::Thunder::Core::JSON::HexUInt32 C; + ::Thunder::Core::JSON::Boolean D; + ::Thunder::Core::JSON::OctUInt16 E; CommandParameters F; - Thunder::Core::JSON::ArrayType M; - Thunder::Core::JSON::Float N; - Thunder::Core::JSON::Double O; + ::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::String> M; + ::Thunder::Core::JSON::Float N; + ::Thunder::Core::JSON::Double O; }; TEST(JSONParser, smallParser) @@ -2168,8 +2176,8 @@ namespace Tests { string input = R"({"D":true})"; string translated = R"({"D":true})"; - Core::JSON::Tester<1, SmallTest> parser; - Core::ProxyType output = Core::ProxyType::Create(); + ::Thunder::Core::JSON::Tester<1, SmallTest> parser; + ::Thunder::Core::ProxyType output = ::Thunder::Core::ProxyType::Create(); string received; parser.FromString(input, output); @@ -2181,8 +2189,8 @@ namespace Tests { string input = R"({"D":false})"; string translated = R"({"D":false})"; - Core::JSON::Tester<1, SmallTest> parser; - Core::ProxyType output = Core::ProxyType::Create(); + ::Thunder::Core::JSON::Tester<1, SmallTest> parser; + ::Thunder::Core::ProxyType output = ::Thunder::Core::ProxyType::Create(); string received; parser.FromString(input, output); @@ -2194,8 +2202,8 @@ namespace Tests { string input = R"({"A":null,"B":null,"C":null,"D":null,"E":null})"; string translated = R"({"A":null,"B":null,"C":null,"D":null,"E":null})"; - Core::JSON::Tester<1, SmallTest> parser; - Core::ProxyType output = Core::ProxyType::Create(); + ::Thunder::Core::JSON::Tester<1, SmallTest> parser; + ::Thunder::Core::ProxyType output = ::Thunder::Core::ProxyType::Create(); string received; parser.FromString(input, output); @@ -2207,8 +2215,8 @@ namespace Tests { string input = R"({"A":"1","B":"3.2","C":"Text"})"; string translated = R"({"A":1,"B":3.2,"C":"Text"})"; - Core::JSON::Tester<1, SmallTest> parser; - Core::ProxyType output = Core::ProxyType::Create(); + ::Thunder::Core::JSON::Tester<1, SmallTest> parser; + ::Thunder::Core::ProxyType output = ::Thunder::Core::ProxyType::Create(); string received; parser.FromString(input, output); @@ -2220,8 +2228,8 @@ namespace Tests { string input = R"({"A":["test"],"B":"3.2","C":"-65.22"})"; string translated = R"({"A":["test"],"B":3.2,"C":-65.22})"; - Core::JSON::Tester<1, SmallTest2> parser; - Core::ProxyType output = Core::ProxyType::Create(); + ::Thunder::Core::JSON::Tester<1, SmallTest2> parser; + ::Thunder::Core::ProxyType output = ::Thunder::Core::ProxyType::Create(); string received; parser.FromString(input, output); @@ -2232,8 +2240,8 @@ namespace Tests { string input = R"({"a":"-0x5A","b":"TestIdentifier","c":"0x5A","d":true,"e":"014","f":{"g":"-014","h":"-44","i":"enum_4","j":["6","14","22"],"k":"1.1","l":"2.11"},"m":["Test"],"n":"3.2","o":"-65.22"})"; string translated = R"({"a":"-0x5A","b":"TestIdentifier","c":"0x5A","d":true,"e":"014","f":{"g":"-014","h":-44,"i":"enum_4","j":[6,14,22],"k":1.1,"l":2.11},"m":["Test"],"n":3.2,"o":-65.22})"; - Core::JSON::Tester<1, CommandRequest> parser; - Core::ProxyType output = Core::ProxyType::Create(); + ::Thunder::Core::JSON::Tester<1, CommandRequest> parser; + ::Thunder::Core::ProxyType output = ::Thunder::Core::ProxyType::Create(); string received; parser.FromString(input, output); @@ -2245,7 +2253,7 @@ namespace Tests { string input = R"({"a":"-0x5A","b":"TestIdentifier","c":"0x5A","d":true,"e":"014","f":{"g":"-014","h":"-44","i":"enum_4","j":["6","14","22"],"k":"1.1","l":"2.11"},"m":["Test"],"n":"3.2","o":"-65.22"})"; string inputRequired = R"({"a":"-0x5A","b":"TestIdentifier","c":"0x5A","d":true,"e":"014","f":{"g":"-014","h":-44,"i":"enum_4","j":[6,14,22],"k":1.1,"l":2.11},"m":["Test"],"n":3.2,"o":-65.22})"; string output; - Thunder::Core::ProxyType command = Thunder::Core::ProxyType::Create(); + ::Thunder::Core::ProxyType command = ::Thunder::Core::ProxyType::Create(); command->A = -90; command->B = _T("TestIdentifier"); command->C = 90; @@ -2254,24 +2262,24 @@ namespace Tests { command->F.G = -12; command->F.H = -44; command->F.I = JSONTestEnum::ENUM_4; - command->F.J.Add(Thunder::Core::JSON::DecUInt16(6, true)); - command->F.J.Add(Thunder::Core::JSON::DecUInt16(14, true)); - command->F.J.Add(Thunder::Core::JSON::DecUInt16(22, true)); + command->F.J.Add(::Thunder::Core::JSON::DecUInt16(6, true)); + command->F.J.Add(::Thunder::Core::JSON::DecUInt16(14, true)); + command->F.J.Add(::Thunder::Core::JSON::DecUInt16(22, true)); command->F.K = static_cast(1.1); command->F.L = 2.11; command->N = static_cast(3.2); command->O = -65.22; - Thunder::Core::JSON::String str; + ::Thunder::Core::JSON::String str; str = string("Test"); command->M.Add(str); - Thunder::Core::JSON::Tester<1, CommandRequest> parser; + ::Thunder::Core::JSON::Tester<1, CommandRequest> parser; //ToString parser.ToString(command, output); EXPECT_STREQ(inputRequired.c_str(), output.c_str()); //FromString - Thunder::Core::ProxyType received = Thunder::Core::ProxyType::Create(); + ::Thunder::Core::ProxyType received = ::Thunder::Core::ProxyType::Create(); parser.FromString(input, received); output.clear(); parser.ToString(received, output); @@ -2283,7 +2291,7 @@ namespace Tests { EXPECT_STREQ(inputRequired.c_str(), output.c_str()); //ArrayType Iterator - Thunder::Core::JSON::ArrayType::Iterator settings(command->F.J.Elements()); + ::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::DecUInt16>::Iterator settings(command->F.J.Elements()); for(int i = 0; settings.Next(); i++) EXPECT_EQ(settings.Current().Value(), command->F.J[i]); //null test @@ -2367,7 +2375,7 @@ namespace Tests { EXPECT_STREQ(input.c_str(), output.c_str()); input = R"("hPh\\one")"; - Core::JSON::String str; + ::Thunder::Core::JSON::String str; str.FromString(input); str.ToString(output); printf("\n\n Case 5: \n"); @@ -2501,17 +2509,17 @@ namespace Tests { escapeSequence = 10; input = escapeSequence; printf("\n\n Case 17 \n"); - Thunder::Core::ProxyType commandInput = Thunder::Core::ProxyType::Create(); - Thunder::Core::JSON::Tester<1, CommandRequest> parserInput; + ::Thunder::Core::ProxyType commandInput = ::Thunder::Core::ProxyType::Create(); + ::Thunder::Core::JSON::Tester<1, CommandRequest> parserInput; commandInput->B = input; output.clear(); parserInput.ToString(commandInput, output); - Thunder::Core::ProxyType commandOutput = Thunder::Core::ProxyType::Create(); - Thunder::Core::JSON::Tester<1, CommandRequest> parserOutput; + ::Thunder::Core::ProxyType commandOutput = ::Thunder::Core::ProxyType::Create(); + ::Thunder::Core::JSON::Tester<1, CommandRequest> parserOutput; parserOutput.FromString(output, commandOutput); EXPECT_STREQ(commandInput->B.Value().c_str(), commandOutput->B.Value().c_str()); - Core::JSONRPC::Message message; + ::Thunder::Core::JSONRPC::Message message; input = R"({"jsonrpc":"2.0","id":1234567890,"method":"WifiControl.1.connect","params":{"ssid":"iPhone\\"}})"; message.FromString(input); message.ToString(output); @@ -2539,8 +2547,8 @@ namespace Tests { string input = R"({"D":true})"; string translated = R"({"D":true})"; - Core::JSON::Tester<512, SmallTest> parser; - Core::ProxyType output = Core::ProxyType::Create(); + ::Thunder::Core::JSON::Tester<512, SmallTest> parser; + ::Thunder::Core::ProxyType output = ::Thunder::Core::ProxyType::Create(); string received; parser.FromString(input, output); @@ -2552,8 +2560,8 @@ namespace Tests { string input = R"({"D":false})"; string translated = R"({"D":false})"; - Core::JSON::Tester<512, SmallTest> parser; - Core::ProxyType output = Core::ProxyType::Create(); + ::Thunder::Core::JSON::Tester<512, SmallTest> parser; + ::Thunder::Core::ProxyType output = ::Thunder::Core::ProxyType::Create(); string received; parser.FromString(input, output); @@ -2565,8 +2573,8 @@ namespace Tests { string input = R"({"A":null,"B":null,"C":null,"D":null,"E":null})"; string translated = R"({"A":null,"B":null,"C":null,"D":null,"E":null})"; - Core::JSON::Tester<512, SmallTest> parser; - Core::ProxyType output = Core::ProxyType::Create(); + ::Thunder::Core::JSON::Tester<512, SmallTest> parser; + ::Thunder::Core::ProxyType output = ::Thunder::Core::ProxyType::Create(); string received; parser.FromString(input, output); @@ -2578,8 +2586,8 @@ namespace Tests { string input = R"({"A":"1","B":"3.2","C":"Text"})"; string translated = R"({"A":1,"B":3.2,"C":"Text"})"; - Core::JSON::Tester<512, SmallTest> parser; - Core::ProxyType output = Core::ProxyType::Create(); + ::Thunder::Core::JSON::Tester<512, SmallTest> parser; + ::Thunder::Core::ProxyType output = ::Thunder::Core::ProxyType::Create(); string received; parser.FromString(input, output); @@ -2591,8 +2599,8 @@ namespace Tests { string input = R"({"A":["test"],"B":"3.2","C":"-65.22"})"; string translated = R"({"A":["test"],"B":3.2,"C":-65.22})"; - Core::JSON::Tester<512, SmallTest2> parser; - Core::ProxyType output = Core::ProxyType::Create(); + ::Thunder::Core::JSON::Tester<512, SmallTest2> parser; + ::Thunder::Core::ProxyType output = ::Thunder::Core::ProxyType::Create(); string received; parser.FromString(input, output); @@ -2603,8 +2611,8 @@ namespace Tests { string input = R"({"a":"-0x5A","b":"TestIdentifier","c":"0x5A","d":true,"e":"014","f":{"g":"-014","h":"-44","i":"enum_4","j":["6","14","22"],"k":"1.1","l":"2.11"},"m":["Test"],"n":"3.2","o":"-65.22"})"; string translated = R"({"a":"-0x5A","b":"TestIdentifier","c":"0x5A","d":true,"e":"014","f":{"g":"-014","h":-44,"i":"enum_4","j":[6,14,22],"k":1.1,"l":2.11},"m":["Test"],"n":3.2,"o":-65.22})"; - Core::JSON::Tester<512, CommandRequest> parser; - Core::ProxyType output = Core::ProxyType::Create(); + ::Thunder::Core::JSON::Tester<512, CommandRequest> parser; + ::Thunder::Core::ProxyType output = ::Thunder::Core::ProxyType::Create(); string received; parser.FromString(input, output); @@ -2616,7 +2624,7 @@ namespace Tests { string input = R"({"a":"-0x5A","b":"TestIdentifier","c":"0x5A","d":true,"e":"014","f":{"g":"-014","h":"-44","i":"enum_4","j":["6","14","22"],"k":"1.1","l":"2.11"},"m":["Test"],"n":"3.2","o":"-65.22"})"; string inputRequired = R"({"a":"-0x5A","b":"TestIdentifier","c":"0x5A","d":true,"e":"014","f":{"g":"-014","h":-44,"i":"enum_4","j":[6,14,22],"k":1.1,"l":2.11},"m":["Test"],"n":3.2,"o":-65.22})"; string output; - Thunder::Core::ProxyType command = Thunder::Core::ProxyType::Create(); + ::Thunder::Core::ProxyType command = ::Thunder::Core::ProxyType::Create(); command->A = -90; command->B = _T("TestIdentifier"); command->C = 90; @@ -2625,23 +2633,23 @@ namespace Tests { command->F.G = -12; command->F.H = -44; command->F.I = JSONTestEnum::ENUM_4; - command->F.J.Add(Thunder::Core::JSON::DecUInt16(6, true)); - command->F.J.Add(Thunder::Core::JSON::DecUInt16(14, true)); - command->F.J.Add(Thunder::Core::JSON::DecUInt16(22, true)); + command->F.J.Add(::Thunder::Core::JSON::DecUInt16(6, true)); + command->F.J.Add(::Thunder::Core::JSON::DecUInt16(14, true)); + command->F.J.Add(::Thunder::Core::JSON::DecUInt16(22, true)); command->F.K = static_cast(1.1); command->F.L = 2.11; command->N = static_cast(3.2); command->O = -65.22; - Thunder::Core::JSON::String str; + ::Thunder::Core::JSON::String str; str = string("Test"); command->M.Add(str); - Thunder::Core::JSON::Tester<512, CommandRequest> parser; + ::Thunder::Core::JSON::Tester<512, CommandRequest> parser; //ToString parser.ToString(command, output); EXPECT_STREQ(inputRequired.c_str(), output.c_str()); //FromString - Thunder::Core::ProxyType received = Thunder::Core::ProxyType::Create(); + ::Thunder::Core::ProxyType received = ::Thunder::Core::ProxyType::Create(); parser.FromString(input, received); output.clear(); parser.ToString(received, output); @@ -2653,7 +2661,7 @@ namespace Tests { EXPECT_STREQ(inputRequired.c_str(), output.c_str()); //ArrayType Iterator - Thunder::Core::JSON::ArrayType::Iterator settings(command->F.J.Elements()); + ::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::DecUInt16>::Iterator settings(command->F.J.Elements()); for (int i = 0; settings.Next(); i++) EXPECT_EQ(settings.Current().Value(), command->F.J[i]); //null test @@ -2739,7 +2747,7 @@ namespace Tests { EXPECT_STREQ(input.c_str(), output.c_str()); input = R"("hPh\\one")"; - Core::JSON::String str; + ::Thunder::Core::JSON::String str; str.FromString(input); str.ToString(output); printf("\n\n Case 5: \n"); @@ -2873,17 +2881,17 @@ namespace Tests { escapeSequence = 10; input = escapeSequence; printf("\n\n Case 17 \n"); - Thunder::Core::ProxyType commandInput = Thunder::Core::ProxyType::Create(); - Thunder::Core::JSON::Tester<512, CommandRequest> parserInput; + ::Thunder::Core::ProxyType commandInput = ::Thunder::Core::ProxyType::Create(); + ::Thunder::Core::JSON::Tester<512, CommandRequest> parserInput; commandInput->B = input; output.clear(); parserInput.ToString(commandInput, output); - Thunder::Core::ProxyType commandOutput = Thunder::Core::ProxyType::Create(); - Thunder::Core::JSON::Tester<512, CommandRequest> parserOutput; + ::Thunder::Core::ProxyType commandOutput = ::Thunder::Core::ProxyType::Create(); + ::Thunder::Core::JSON::Tester<512, CommandRequest> parserOutput; parserOutput.FromString(output, commandOutput); EXPECT_STREQ(commandInput->B.Value().c_str(), commandOutput->B.Value().c_str()); - Core::JSONRPC::Message message; + ::Thunder::Core::JSONRPC::Message message; input = R"({"jsonrpc":"2.0","id":1234567890,"method":"WifiControl.1.connect","params":{"ssid":"iPhone\\"}})"; message.FromString(input); message.ToString(output); @@ -2903,5 +2911,7 @@ namespace Tests { EXPECT_STREQ(input.c_str(), output.c_str()); } } -} -} + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_keyvalue.cpp b/Tests/unit/core/test_keyvalue.cpp index e60b8ac6b0..a590d81300 100644 --- a/Tests/unit/core/test_keyvalue.cpp +++ b/Tests/unit/core/test_keyvalue.cpp @@ -25,38 +25,43 @@ #include -using namespace Thunder; -using namespace Thunder::Core; - -TEST(test_keyvaluetype, simple_keyvaluetype) -{ - string key = "Name"; - string value = "Adam"; - string key1 = "Age"; - - KeyValueType keyvalue(key); - KeyValueType keyvalue1(key,value); - KeyValueType keyvalue2(keyvalue1); - KeyValueType keyvalue3(key); - keyvalue3 = keyvalue1; - KeyValueType keyvalue4(key1); - - EXPECT_TRUE(keyvalue3 == keyvalue1); - EXPECT_TRUE(keyvalue3 != keyvalue4); - - EXPECT_STREQ(keyvalue3.Key().c_str(),key.c_str()); - EXPECT_STREQ(keyvalue3.Value().c_str(),value.c_str()); - EXPECT_TRUE(keyvalue3.IsKey(key)); -} - -TEST(test_textkeyvaluetype, simple_textkeyvaluetype) -{ - string buffer = "/Service/testing/test"; - TextFragment key; - key = TextFragment(string(buffer)); - OptionalType value = TextFragment(string(buffer)); - const bool CASESENSITIVE = true; - - TextKeyValueType textkeyvaluetype; - TextKeyValueType textkeyvaluetype1(key, value); -} +namespace Thunder { +namespace Tests { +namespace Core { + + TEST(test_keyvaluetype, simple_keyvaluetype) + { + string key = "Name"; + string value = "Adam"; + string key1 = "Age"; + + ::Thunder::Core::KeyValueType keyvalue(key); + ::Thunder::Core::KeyValueType keyvalue1(key,value); + ::Thunder::Core::KeyValueType keyvalue2(keyvalue1); + ::Thunder::Core::KeyValueType keyvalue3(key); + keyvalue3 = keyvalue1; + ::Thunder::Core::KeyValueType keyvalue4(key1); + + EXPECT_TRUE(keyvalue3 == keyvalue1); + EXPECT_TRUE(keyvalue3 != keyvalue4); + + EXPECT_STREQ(keyvalue3.Key().c_str(),key.c_str()); + EXPECT_STREQ(keyvalue3.Value().c_str(),value.c_str()); + EXPECT_TRUE(keyvalue3.IsKey(key)); + } + + TEST(test_textkeyvaluetype, simple_textkeyvaluetype) + { + string buffer = "/Service/testing/test"; + ::Thunder::Core::TextFragment key; + key = ::Thunder::Core::TextFragment(string(buffer)); + ::Thunder::Core::OptionalType<::Thunder::Core::TextFragment> value = ::Thunder::Core::TextFragment(string(buffer)); + const bool CASESENSITIVE = true; + + ::Thunder::Core::TextKeyValueType textkeyvaluetype; + ::Thunder::Core::TextKeyValueType textkeyvaluetype1(key, value); + } + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_library.cpp b/Tests/unit/core/test_library.cpp index b6aa99ae57..f556b25220 100644 --- a/Tests/unit/core/test_library.cpp +++ b/Tests/unit/core/test_library.cpp @@ -25,35 +25,40 @@ #include -using namespace Thunder; -using namespace Thunder::Core; +namespace Thunder { +namespace Tests { +namespace Core { -TEST(Core_Library, simpleSet) -{ + TEST(Core_Library, simpleSet) + { + ::Thunder::Core::Library libObj; #ifdef BUILD_ARM - const string file = _T("/usr/lib/testdata/libhelloworld.so"); // For QEMU + const string file = _T("/usr/lib/testdata/libhelloworld.so"); // For QEMU #else - const string file = string(BUILD_DIR) + _T("/libhelloworld.so"); // For PC - //const string file = _T("/usr/lib/libwpe-0.2.so"); //For box. + const string file = string(BUILD_DIR) + _T("/libhelloworld.so"); // For PC + //const string file = _T("/usr/lib/libwpe-0.2.so"); //For box. #endif - const TCHAR* function = _T("HelloWorld"); - const string file1 = _T("libThunder.so"); + const TCHAR* function = _T("HelloWorld"); + const string file1 = _T("libThunder.so"); - Library LibObj1(file.c_str()); - EXPECT_TRUE(LibObj1.Error().empty()); + ::Thunder::Core::Library LibObj1(file.c_str()); + EXPECT_TRUE(LibObj1.Error().empty()); - LibObj1.LoadFunction(function); - EXPECT_TRUE(LibObj1.IsLoaded()); - EXPECT_TRUE(LibObj1.Error().empty()); + LibObj1.LoadFunction(function); + EXPECT_TRUE(LibObj1.IsLoaded()); + EXPECT_TRUE(LibObj1.Error().empty()); - Library LibObj2(LibObj1); // Copy constructor - EXPECT_TRUE(LibObj1.Error().empty()); - EXPECT_TRUE(LibObj2.Error().empty()); + ::Thunder::Core::Library LibObj2(LibObj1); // Copy constructor + EXPECT_TRUE(LibObj1.Error().empty()); + EXPECT_TRUE(LibObj2.Error().empty()); - Library LibObj3; - LibObj3 = LibObj2; // Copy assignment + ::Thunder::Core::Library LibObj3; + LibObj3 = LibObj2; // Copy assignment - EXPECT_TRUE(LibObj2.Error().empty()); - EXPECT_TRUE(LibObj3.Error().empty()); // Same as LibObj2 - EXPECT_EQ(LibObj3.Name(), file); -} + EXPECT_TRUE(LibObj2.Error().empty()); + EXPECT_TRUE(LibObj3.Error().empty()); // Same as LibObj2 + EXPECT_EQ(LibObj3.Name(), file); + } +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_library_helloworld.cpp b/Tests/unit/core/test_library_helloworld.cpp index aa1f6f3ea5..78662bfc14 100644 --- a/Tests/unit/core/test_library_helloworld.cpp +++ b/Tests/unit/core/test_library_helloworld.cpp @@ -1,9 +1,32 @@ +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + #include -namespace Thunder{ - namespace Test{ - extern "C" std::string HelloWorld(){ - return "Hello World!"; - } +namespace Thunder { +namespace Tests { +namespace Core { + + extern "C" std::string HelloWorld(){ + return "Hello World!"; } -} + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_lockablecontainer.cpp b/Tests/unit/core/test_lockablecontainer.cpp index 634d197578..e86fb0d644 100644 --- a/Tests/unit/core/test_lockablecontainer.cpp +++ b/Tests/unit/core/test_lockablecontainer.cpp @@ -25,36 +25,41 @@ #include -using namespace Thunder; -using namespace Thunder::Core; - -class Container -{ - public: - Container() - : _length(0) - , _data(nullptr) - { - } - - ~Container() - { - } - - private: - int _length; - int* _data; -}; - -TEST(test_lockableContainer, lockContainer_test) -{ - LockableContainerType containerObj1; - LockableContainerType containerObj2(containerObj1); - LockableContainerType containerObj3; - containerObj3 = containerObj2; - - EXPECT_TRUE(containerObj1.ReadLock()); - containerObj1.ReadUnlock(); - EXPECT_TRUE(containerObj2.WriteLock()); - containerObj2.WriteUnlock(); -} +namespace Thunder { +namespace Tests { +namespace Core { + + class Container + { + public: + Container() + : _length(0) + , _data(nullptr) + { + } + + ~Container() + { + } + + private: + int _length; + int* _data; + }; + + TEST(test_lockableContainer, lockContainer_test) + { + ::Thunder::Core::LockableContainerType containerObj1; + ::Thunder::Core::LockableContainerType containerObj2(containerObj1); + ::Thunder::Core::LockableContainerType containerObj3; + containerObj3 = containerObj2; + + EXPECT_TRUE(containerObj1.ReadLock()); + containerObj1.ReadUnlock(); + EXPECT_TRUE(containerObj2.WriteLock()); + containerObj2.WriteUnlock(); + } + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_measurementtype.cpp b/Tests/unit/core/test_measurementtype.cpp index fed7764b6a..bef2296f84 100644 --- a/Tests/unit/core/test_measurementtype.cpp +++ b/Tests/unit/core/test_measurementtype.cpp @@ -27,10 +27,11 @@ namespace Thunder { namespace Tests { +namespace Core { TEST(Core_MeasurementType, simpleSet) { - Core::MeasurementType data; + ::Thunder::Core::MeasurementType data; data.Set(100); data.Set(200); data.Set(120); @@ -47,5 +48,7 @@ namespace Tests { EXPECT_EQ(data.Average(), 0u); EXPECT_EQ(data.Measurements(), 0u); } + +} // Core } // Tests } // Thunder diff --git a/Tests/unit/core/test_memberavailability.cpp b/Tests/unit/core/test_memberavailability.cpp index 0b437afd88..4fb9762691 100644 --- a/Tests/unit/core/test_memberavailability.cpp +++ b/Tests/unit/core/test_memberavailability.cpp @@ -29,6 +29,7 @@ namespace Thunder { namespace Tests { +namespace Core { struct TestWithMember { @@ -79,13 +80,13 @@ namespace Tests { IS_MEMBER_AVAILABLE(Test1, hasTest1); template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __TestWithMember(TYPE& t) { return t.Test1(); } template < typename TYPE> - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __TestWithMember(TYPE&) { return "method not available"; @@ -93,13 +94,13 @@ namespace Tests { IS_MEMBER_AVAILABLE(Test1, hasTest1Args); template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test1WithMemberHasArg(TYPE& t, int value) { return t.Test1(value); } template < typename TYPE> - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test1WithMemberHasArg(TYPE&, int) { return "method not available"; @@ -107,26 +108,26 @@ namespace Tests { IS_STATIC_MEMBER_AVAILABLE(Test1, hasStaticTest1); template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test1WithStaticMember() { return TYPE::Test1(); } template < typename TYPE> - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test1WithStaticMember() { return "method not available"; } IS_STATIC_MEMBER_AVAILABLE(Test1, hasStaticTest1Args); template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test1WithStaticMemberHasArg(int value) { return TYPE::Test1(value); } template < typename TYPE> - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test1WithStaticMemberHasArg(int) { return "method not available"; @@ -179,38 +180,38 @@ namespace Tests { IS_MEMBER_AVAILABLE(Test2, hasTest2ArgBool); template - inline typename Core::TypeTraits::enable_if::value, void>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, void>::type __Test2WithMemberHasArgBool(TYPE& t, bool& value) { t.Test2(value); } template < typename TYPE> - inline typename Core::TypeTraits::enable_if::value, void>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, void>::type __Test2WithMemberHasArgBool(TYPE&, bool&) { } IS_MEMBER_AVAILABLE(Test2, hasTest2ArgString); template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test2WithMemberHasArgString(TYPE& t, string& str) { return t.Test2(str); } template < typename TYPE> - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test2WithMemberHasArgString(TYPE&, string&) { } IS_STATIC_MEMBER_AVAILABLE(Test2, hasTest2NoArg); template - inline typename Core::TypeTraits::enable_if::value, bool>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, bool>::type __Test2WithStaticMember() { return TYPE::Test2(); } template < typename TYPE> - inline typename Core::TypeTraits::enable_if::value, bool>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, bool>::type __Test2WithStaticMember() { return false; @@ -218,26 +219,26 @@ namespace Tests { IS_STATIC_MEMBER_AVAILABLE(Test2, hasTest2StaticArgBool); template - inline typename Core::TypeTraits::enable_if::value, void>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, void>::type __Test2WithStaticMemberArgBool(bool value) { TYPE::Test2(value); } template < typename TYPE> - inline typename Core::TypeTraits::enable_if::value, void>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, void>::type __Test2WithStaticMemberArgBool(bool) { } IS_STATIC_MEMBER_AVAILABLE(Test2, hasTest2ArgInt); template - inline typename Core::TypeTraits::enable_if::value, int>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, int>::type __Test2WithStaticMemberArgInt(int value) { return TYPE::Test2(value); } template < typename TYPE> - inline typename Core::TypeTraits::enable_if::value, int>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, int>::type __Test2WithStaticMemberArgInt(int) { return 0; @@ -277,13 +278,13 @@ namespace Tests { IS_MEMBER_AVAILABLE(Test3, hasTest3ConstNoArg); template - inline typename Core::TypeTraits::enable_if::value, bool>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, bool>::type __Test3WithConstMemberNonConstType(TYPE& t) { return t.Test3(); } template < typename TYPE> - inline typename Core::TypeTraits::enable_if::value, bool>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, bool>::type __Test3WithConstMemberNonConstType(TYPE&) { return false; @@ -291,26 +292,26 @@ namespace Tests { IS_MEMBER_AVAILABLE(Test3, hasTest3ConstTypeNoArg); template - inline typename Core::TypeTraits::enable_if::value, bool>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, bool>::type __Test3WithConstMember(const TYPE& t) { return t.Test3(); } template < typename TYPE> - inline typename Core::TypeTraits::enable_if::value, bool>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, bool>::type __Test3WithConstMember(const TYPE&) { return false; } IS_MEMBER_AVAILABLE(Test3, hasTest3NonConstArgString); template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test3WithNonConstMember(TYPE& t, string str) { return t.Test3(str); } template < typename TYPE> - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test3WithNonConstMember(TYPE&, string) { return "method not available"; @@ -318,13 +319,13 @@ namespace Tests { IS_MEMBER_AVAILABLE(Test3, hasTest3ConstArgString); template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test3WithNonConstMember(const TYPE& t, string str) { return t.Test3(str); } template < typename TYPE> - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test3WithNonConstMember(const TYPE&, string) { return "method not available"; @@ -332,39 +333,39 @@ namespace Tests { IS_MEMBER_AVAILABLE(Test3, hasTest3ConstArg); template - inline typename Core::TypeTraits::enable_if::value, int>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, int>::type __Test3WithConstMember(const TYPE& t, const int value) { return t.Test3(value); } template < typename TYPE> - inline typename Core::TypeTraits::enable_if::value, int>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, int>::type __Test3WithConstMember(const TYPE&, const int) { return 0; } IS_MEMBER_AVAILABLE(Test3, hasTest3NoArg); template - inline typename Core::TypeTraits::enable_if::value, bool>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, bool>::type __Test3WithConstType(const TYPE& t) { return t.Test3(); } template < typename TYPE> - inline typename Core::TypeTraits::enable_if::value, bool>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, bool>::type __Test3WithConstType(const TYPE&) { return false; } IS_MEMBER_AVAILABLE(Test3, hasTest3Arg); template - inline typename Core::TypeTraits::enable_if::value, int>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, int>::type __Test3WithConstTypeArgInt(const TYPE& t, int value) { return t.Test3(value); } template < typename TYPE> - inline typename Core::TypeTraits::enable_if::value, int>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, int>::type __Test3WithConstTypeArgInt(const TYPE&, int) { return 0; @@ -421,104 +422,104 @@ namespace Tests { IS_MEMBER_AVAILABLE_INHERITANCE_TREE(Test4, hasTest4TypeArgDouble); template - inline typename Core::TypeTraits::enable_if::value, bool>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, bool>::type __Test4WithMemberArgDouble(double d) { return TYPE::Test4(d); } template - inline typename Core::TypeTraits::enable_if::value, bool>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, bool>::type __Test4WithMemberArgDouble(double) { return false; } IS_MEMBER_AVAILABLE_INHERITANCE_TREE(Test4, hasTest4ConstTypeArgString); template - inline typename Core::TypeTraits::enable_if::value, bool>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, bool>::type __Test4WithConstMemberArgString(string str) const { return TYPE::Test4(str); } template - inline typename Core::TypeTraits::enable_if::value, bool>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, bool>::type __Test4WithConstMemberArgString(string) const { return false; } IS_MEMBER_AVAILABLE_INHERITANCE_TREE(Test4, hasTest4ArgInt); template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test4WithMemberArgInt(int value) { return TYPE::Test4(value); } template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test4WithMemberArgInt(int) { return 0; } IS_MEMBER_AVAILABLE_INHERITANCE_TREE(Test4, hasTest4ConstArgInt); template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test4WithMemberArgInt(int value) const { return TYPE::Test4(value); } template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test4WithMemberArgInt(int) const { return 0; } IS_MEMBER_AVAILABLE_INHERITANCE_TREE(Test4, hasTest4ConstArgString); template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test4WithConstMemberArgStringAndBool(string str, bool b) const { return TYPE::Test4(str, b); } template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test4WithConstMemberArgStringAndBool(string, bool) const { return "method not available"; } IS_MEMBER_AVAILABLE(Test5, hasTest5ConstArgString); template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test5WithConstMemberArgString(string str) { return TYPE::Test5(str); } template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test5WithConstMemberArgString(string) { return "method not available"; } IS_MEMBER_AVAILABLE_INHERITANCE_TREE(Test5, hasTest5ConstArgStringOnBase); template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test5WithConstMemberArgStringOnBase(string str) { return TYPE::Test5(str); } template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test5WithConstMemberArgStringOnBase(string) { return "method not available"; } IS_MEMBER_AVAILABLE_INHERITANCE_TREE(Test6, hasTest6ConstArgStringOnBoth); template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test6WithConstMemberArgStringOnBoth(string str) { return TYPE::Test6(str); } template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test6WithConstMemberArgStringOnBoth(string) { return "method not available"; @@ -544,13 +545,13 @@ namespace Tests { IS_TEMPLATE_MEMBER_AVAILABLE(Test7, hasTest7Template); template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test7Template(TYPE& t) { return t.template Test7(); } template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test7Template(TYPE&) { return "method not available"; @@ -567,13 +568,13 @@ namespace Tests { IS_TEMPLATE_MEMBER_AVAILABLE(Test8, hasTest8WithoutTemplate); template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test8WithoutTemplate(TYPE& t) { return t.Test8(); } template - inline typename Core::TypeTraits::enable_if::value, string>::type + inline typename ::Thunder::Core::TypeTraits::enable_if::value, string>::type __Test8WithoutTemplate(TYPE&) { return "method not available"; @@ -784,5 +785,7 @@ namespace Tests { TestNonTemplateMember nonTemplateMember; EXPECT_STREQ((__Test8WithoutTemplate(nonTemplateMember)).c_str(), "method not available"); } -} -} + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_messageException.cpp b/Tests/unit/core/test_messageException.cpp index 86180ddbdf..2633ce3dda 100644 --- a/Tests/unit/core/test_messageException.cpp +++ b/Tests/unit/core/test_messageException.cpp @@ -25,22 +25,27 @@ #include -using namespace Thunder; -using namespace Thunder::Core; +namespace Thunder { +namespace Tests { +namespace Core { -TEST(test_messageException, simple_messageException) -{ - const std::string msg = "Testing the message exception."; + TEST(test_messageException, simple_messageException) + { + const std::string msg = "Testing the message exception."; - // No 'error' concatenated - MessageException exception(msg, false); + // No 'error' concatenated + ::Thunder::Core::MessageException exception(msg, false); - EXPECT_STREQ(exception.Message(), msg.c_str()); + EXPECT_STREQ(exception.Message(), msg.c_str()); - // 'error' concatenated - MessageException exception1(msg, true); + // 'error' concatenated + ::Thunder::Core::MessageException exception1(msg, true); - const string result = msg + ": No such file or directory"; + const string result = msg + ": No such file or directory"; - EXPECT_STREQ(exception1.Message(), result.c_str()); -} + EXPECT_STREQ(exception1.Message(), result.c_str()); + } + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_message_dispatcher.cpp b/Tests/unit/core/test_message_dispatcher.cpp index c741e48445..0446042f64 100644 --- a/Tests/unit/core/test_message_dispatcher.cpp +++ b/Tests/unit/core/test_message_dispatcher.cpp @@ -31,6 +31,7 @@ namespace Thunder { namespace Tests { +namespace Core { class Core_MessageDispatcher : public testing::Test { protected: @@ -43,25 +44,25 @@ namespace Tests { , _basePath(_T("/tmp/TestMessageDispatcher")) { //if directory exists remove it to clear data (eg. sockets) that can remain after previous run - if (Core::File(_basePath).IsDirectory()) { - Core::Directory(_basePath.c_str()).Destroy(); + if (::Thunder::Core::File(_basePath).IsDirectory()) { + ::Thunder::Core::Directory(_basePath.c_str()).Destroy(); } //create directory - if (!Core::Directory(_basePath.c_str()).CreatePath()) { + if (!::Thunder::Core::Directory(_basePath.c_str()).CreatePath()) { std::cerr << "Unable to create MessageDispatcher directory" << std::endl; } } ~Core_MessageDispatcher() { - if (Core::File(_basePath).IsDirectory()) { - Core::Directory(_basePath.c_str()).Destroy(); + if (::Thunder::Core::File(_basePath).IsDirectory()) { + ::Thunder::Core::Directory(_basePath.c_str()).Destroy(); } } void SetUp() override { - _dispatcher.reset(new Core::MessageDispatcherType(_identifier, _instanceId, true, _basePath)); + _dispatcher.reset(new ::Thunder::Core::MessageDispatcherType(_identifier, _instanceId, true, _basePath)); } void TearDown() override { @@ -69,10 +70,10 @@ namespace Tests { ++_instanceId; - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } - std::unique_ptr> _dispatcher; + std::unique_ptr<::Thunder::Core::MessageDispatcherType> _dispatcher; string _identifier; string _basePath; @@ -90,8 +91,8 @@ namespace Tests { uint16_t readLength = sizeof(readData); //act - ASSERT_EQ(_dispatcher->PushData(sizeof(testData), testData), Core::ERROR_NONE); - ASSERT_EQ(_dispatcher->PopData(readLength, readData), Core::ERROR_NONE); + ASSERT_EQ(_dispatcher->PushData(sizeof(testData), testData), ::Thunder::Core::ERROR_NONE); + ASSERT_EQ(_dispatcher->PopData(readLength, readData), ::Thunder::Core::ERROR_NONE); //assert ASSERT_EQ(readLength, sizeof(testData)); @@ -108,8 +109,8 @@ namespace Tests { uint16_t readLength = sizeof(readData); //act - ASSERT_EQ(_dispatcher->PushData(sizeof(testData), testData), Core::ERROR_NONE); - ASSERT_EQ(_dispatcher->PopData(readLength, readData), Core::ERROR_GENERAL); + ASSERT_EQ(_dispatcher->PushData(sizeof(testData), testData), ::Thunder::Core::ERROR_NONE); + ASSERT_EQ(_dispatcher->PopData(readLength, readData), ::Thunder::Core::ERROR_GENERAL); //assert ASSERT_EQ(readLength, 2); @@ -118,16 +119,16 @@ namespace Tests { TEST_F(Core_MessageDispatcher, CreateAndOpenOperatesOnSameValidFile) { - Core::MessageDispatcherType writerDispatcher(_T("test_md"), 0, true, this->_basePath); - Core::MessageDispatcherType readerDispatcher(_T("test_md"), 0, false, this->_basePath); + ::Thunder::Core::MessageDispatcherType writerDispatcher(_T("test_md"), 0, true, this->_basePath); + ::Thunder::Core::MessageDispatcherType readerDispatcher(_T("test_md"), 0, false, this->_basePath); uint8_t testData[2] = { 13, 37 }; uint8_t readData[4]; uint16_t readLength = sizeof(readData); - ASSERT_EQ(_dispatcher->PushData(sizeof(testData), testData), Core::ERROR_NONE); - ASSERT_EQ(_dispatcher->PopData(readLength, readData), Core::ERROR_NONE); + ASSERT_EQ(_dispatcher->PushData(sizeof(testData), testData), ::Thunder::Core::ERROR_NONE); + ASSERT_EQ(_dispatcher->PopData(readLength, readData), ::Thunder::Core::ERROR_NONE); ASSERT_EQ(readLength, sizeof(testData)); ASSERT_EQ(readData[0], 13); @@ -136,24 +137,24 @@ namespace Tests { TEST_F(Core_MessageDispatcher, MessageDispatcherCanBeOpenedAndClosed) { - Core::MessageDispatcherType writerDispatcher(_T("test_md"), 0, true, this->_basePath); + ::Thunder::Core::MessageDispatcherType writerDispatcher(_T("test_md"), 0, true, this->_basePath); { - Core::MessageDispatcherType readerDispatcher(_T("test_md"), 0, false, this->_basePath); + ::Thunder::Core::MessageDispatcherType readerDispatcher(_T("test_md"), 0, false, this->_basePath); //destructor is called } //reopen - Core::MessageDispatcherType readerDispatcher(_T("test_md"), 0, true, this->_basePath); + ::Thunder::Core::MessageDispatcherType readerDispatcher(_T("test_md"), 0, true, this->_basePath); uint8_t testData[2] = { 13, 37 }; uint8_t readData[4]; uint16_t readLength = sizeof(readData); - ASSERT_EQ(_dispatcher->PushData(sizeof(testData), testData), Core::ERROR_NONE); - ASSERT_EQ(_dispatcher->PopData(readLength, readData), Core::ERROR_NONE); + ASSERT_EQ(_dispatcher->PushData(sizeof(testData), testData), ::Thunder::Core::ERROR_NONE); + ASSERT_EQ(_dispatcher->PopData(readLength, readData), ::Thunder::Core::ERROR_NONE); ASSERT_EQ(readLength, sizeof(testData)); ASSERT_EQ(readData[0], 13); @@ -168,8 +169,8 @@ namespace Tests { uint16_t readLength = sizeof(readData); //first read, write, assert - ASSERT_EQ(_dispatcher->PushData(sizeof(testData), testData), Core::ERROR_NONE); - ASSERT_EQ(_dispatcher->PopData(readLength, readData), Core::ERROR_NONE); + ASSERT_EQ(_dispatcher->PushData(sizeof(testData), testData), ::Thunder::Core::ERROR_NONE); + ASSERT_EQ(_dispatcher->PopData(readLength, readData), ::Thunder::Core::ERROR_NONE); ASSERT_EQ(readLength, sizeof(testData)); ASSERT_EQ(readData[0], 13); @@ -178,8 +179,8 @@ namespace Tests { //second read, write, assert testData[0] = 40; readLength = sizeof(readData); - ASSERT_EQ(_dispatcher->PushData(1, testData), Core::ERROR_NONE); - ASSERT_EQ(_dispatcher->PopData(readLength, readData), Core::ERROR_NONE); + ASSERT_EQ(_dispatcher->PushData(1, testData), ::Thunder::Core::ERROR_NONE); + ASSERT_EQ(_dispatcher->PopData(readLength, readData), ::Thunder::Core::ERROR_NONE); ASSERT_EQ(readLength, 1); ASSERT_EQ(readData[0], 40); } @@ -187,7 +188,7 @@ namespace Tests { TEST_F(Core_MessageDispatcher, WriteAndReadDataAreEqualInDiffrentProcesses) { auto lambdaFunc = [this](IPTestAdministrator& testAdmin) { - Core::MessageDispatcherType dispatcher(this->_identifier, this->_instanceId, false, this->_basePath); + ::Thunder::Core::MessageDispatcherType dispatcher(this->_identifier, this->_instanceId, false, this->_basePath); uint8_t readData[4]; uint16_t readLength = sizeof(readData); @@ -195,7 +196,7 @@ namespace Tests { testAdmin.Sync("setup reader"); testAdmin.Sync("writer wrote"); - ASSERT_EQ(dispatcher.PopData(readLength, readData), Core::ERROR_NONE); + ASSERT_EQ(dispatcher.PopData(readLength, readData), ::Thunder::Core::ERROR_NONE); ASSERT_EQ(readLength, 2); ASSERT_EQ(readData[0], 13); @@ -214,7 +215,7 @@ namespace Tests { testAdmin.Sync("setup reader"); uint8_t testData[2] = { 13, 37 }; - ASSERT_EQ(_dispatcher->PushData(sizeof(testData), testData), Core::ERROR_NONE); + ASSERT_EQ(_dispatcher->PushData(sizeof(testData), testData), ::Thunder::Core::ERROR_NONE); testAdmin.Sync("writer wrote"); testAdmin.Sync("reader read"); @@ -225,14 +226,14 @@ namespace Tests { TEST_F(Core_MessageDispatcher, PushDataShouldNotFitWhenExcedingDataBufferSize) { uint8_t fullBufferSimulation[DATA_SIZE + 1 - + sizeof(Core::CyclicBuffer::control)]; + + sizeof(::Thunder::Core::CyclicBuffer::control)]; - ASSERT_EQ(_dispatcher->PushData(sizeof(fullBufferSimulation), fullBufferSimulation), Core::ERROR_WRITE_ERROR); + ASSERT_EQ(_dispatcher->PushData(sizeof(fullBufferSimulation), fullBufferSimulation), ::Thunder::Core::ERROR_WRITE_ERROR); } TEST_F(Core_MessageDispatcher, PushDataShouldFlushOldDataIfDoesNotFit) { - uint8_t fullBufferSimulation[DATA_SIZE - 1 + sizeof(Core::CyclicBuffer::control) //almost full buffer + uint8_t fullBufferSimulation[DATA_SIZE - 1 + sizeof(::Thunder::Core::CyclicBuffer::control) //almost full buffer - sizeof(uint8_t) //size of type (part of message header) - sizeof(uint16_t)]; //size of length (part of message header) @@ -241,14 +242,14 @@ namespace Tests { uint8_t readData[4]; uint16_t readLength = sizeof(readData); - ASSERT_EQ(_dispatcher->PushData(sizeof(fullBufferSimulation), fullBufferSimulation), Core::ERROR_NONE); + ASSERT_EQ(_dispatcher->PushData(sizeof(fullBufferSimulation), fullBufferSimulation), ::Thunder::Core::ERROR_NONE); //buffer is full, but trying to write new data - ASSERT_EQ(_dispatcher->PushData(sizeof(testData), testData), Core::ERROR_NONE); + ASSERT_EQ(_dispatcher->PushData(sizeof(testData), testData), ::Thunder::Core::ERROR_NONE); //new data written, so the oldest data should be replaced //this is first entry and should be first popped (FIFO) - ASSERT_EQ(_dispatcher->PopData(readLength, readData), Core::ERROR_NONE); + ASSERT_EQ(_dispatcher->PopData(readLength, readData), ::Thunder::Core::ERROR_NONE); ASSERT_EQ(readLength, sizeof(testData)); ASSERT_EQ(readData[0], 12); ASSERT_EQ(readData[1], 21); @@ -258,7 +259,7 @@ namespace Tests { TEST_F(Core_MessageDispatcher, DISABLED_ReaderShouldWaitUntillRingBells) { auto lambdaFunc = [this](IPTestAdministrator& testAdmin) { - Core::MessageDispatcherType dispatcher(this->_identifier, this->_instanceId, false, this->_basePath); + ::Thunder::Core::MessageDispatcherType dispatcher(this->_identifier, this->_instanceId, false, this->_basePath); uint8_t readData[4]; uint16_t readLength = sizeof(readData); @@ -267,8 +268,8 @@ namespace Tests { dispatcher.Wait(0); //initialize socket testAdmin.Sync("init"); - if (dispatcher.Wait(Core::infinite) == Core::ERROR_NONE) { - ASSERT_EQ(dispatcher.PopData(readLength, readData), Core::ERROR_NONE); + if (dispatcher.Wait(::Thunder::Core::infinite) == ::Thunder::Core::ERROR_NONE) { + ASSERT_EQ(dispatcher.PopData(readLength, readData), ::Thunder::Core::ERROR_NONE); ASSERT_EQ(readLength, 2); ASSERT_EQ(readData[0], 13); @@ -289,7 +290,7 @@ namespace Tests { uint8_t testData[2] = { 13, 37 }; testAdmin.Sync("init"); - ASSERT_EQ(_dispatcher->PushData(sizeof(testData), testData), Core::ERROR_NONE); + ASSERT_EQ(_dispatcher->PushData(sizeof(testData), testData), ::Thunder::Core::ERROR_NONE); } testAdmin.Sync("done"); } @@ -361,7 +362,7 @@ namespace Tests { TEST_F(Core_MessageDispatcher, DISABLED_WriteAndReadMetaDataAreEqualInDiffrentProcesses) { auto lambdaFunc = [this](IPTestAdministrator& testAdmin) { - Core::MessageDispatcherType dispatcher(this->_identifier, this->_instanceId, false, this->_basePath); + ::Thunder::Core::MessageDispatcherType dispatcher(this->_identifier, this->_instanceId, false, this->_basePath); uint8_t testData[2] = { 13, 37 }; //testAdmin.Sync("setup"); @@ -399,5 +400,6 @@ namespace Tests { ASSERT_EQ(result, 0); } +} // Core } // Tests } // Thunder diff --git a/Tests/unit/core/test_message_unit.cpp b/Tests/unit/core/test_message_unit.cpp index ff3e3bfda6..b2c180c922 100644 --- a/Tests/unit/core/test_message_unit.cpp +++ b/Tests/unit/core/test_message_unit.cpp @@ -26,531 +26,499 @@ #include #include "../IPTestAdministrator.h" - -using namespace Thunder; -class Control : public Core::Messaging::IControl { -public: - Control(const Core::Messaging::MetaData& metaData) - : _metaData(metaData) - { - } - ~Control() override - { - Destroy(); - } - void Enable(bool enable) override - { - _isEnabled = enable; - } - bool Enable() const override - { - return _isEnabled; - } - void Destroy() override - { - _isEnabled = false; - } - const Core::Messaging::MetaData& MessageMetaData() const override - { - return _metaData; - } +namespace Thunder { +namespace Tests { +namespace Core { -private: - bool _isEnabled; - Core::Messaging::MetaData _metaData; -}; + class Control : public ::Thunder::Core::Messaging::IControl { + public: + Control(const ::Thunder::Core::Messaging::MetaData& metaData) + : _metaData(metaData) + { + } + ~Control() override + { + Destroy(); + } + void Enable(bool enable) override + { + _isEnabled = enable; + } + bool Enable() const override + { + return _isEnabled; + } + void Destroy() override + { + _isEnabled = false; + } + const ::Thunder::Core::Messaging::MetaData& MessageMetaData() const override + { + return _metaData; + } -class Core_Messaging_MessageUnit : public testing::Test { -protected: - Core_Messaging_MessageUnit() - { - _controls.emplace_back(new Control({ Core::Messaging::MetaData::MessageType::TRACING, _T("Test_Category_1"), EXPAND_AND_QUOTE(MODULE_NAME) })); - _controls.emplace_back(new Control({ Core::Messaging::MetaData::MessageType::TRACING, _T("Test_Category_2"), EXPAND_AND_QUOTE(MODULE_NAME) })); - _controls.emplace_back(new Control({ Core::Messaging::MetaData::MessageType::TRACING, _T("Test_Category_3"), EXPAND_AND_QUOTE(MODULE_NAME) })); - _controls.emplace_back(new Control({ Core::Messaging::MetaData::MessageType::TRACING, _T("Test_Category_4"), EXPAND_AND_QUOTE(MODULE_NAME) })); - _controls.emplace_back(new Control({ Core::Messaging::MetaData::MessageType::TRACING, _T("Test_Category_1"), _T("Test_Module2") })); - _controls.emplace_back(new Control({ Core::Messaging::MetaData::MessageType::LOGGING, _T("Test_Category_5"), _T("SysLog") })); - } - ~Core_Messaging_MessageUnit() = default; + private: + bool _isEnabled; + ::Thunder::Core::Messaging::MetaData _metaData; + }; - static void SetUpTestSuite() - { - Core::Messaging::MessageUnit::Instance().IsBackground(_background); - Core::Messaging::MessageUnit::Instance().Open(_basePath); - } + class Core_Messaging_MessageUnit : public testing::Test { + protected: + Core_Messaging_MessageUnit() + { + _controls.emplace_back(new Control({ ::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T("Test_Category_1"), EXPAND_AND_QUOTE(MODULE_NAME) })); + _controls.emplace_back(new Control({ ::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T("Test_Category_2"), EXPAND_AND_QUOTE(MODULE_NAME) })); + _controls.emplace_back(new Control({ ::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T("Test_Category_3"), EXPAND_AND_QUOTE(MODULE_NAME) })); + _controls.emplace_back(new Control({ ::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T("Test_Category_4"), EXPAND_AND_QUOTE(MODULE_NAME) })); + _controls.emplace_back(new Control({ ::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T("Test_Category_1"), _T("Test_Module2") })); + _controls.emplace_back(new Control({ ::Thunder::Core::Messaging::MetaData::MessageType::LOGGING, _T("Test_Category_5"), _T("SysLog") })); + } + ~Core_Messaging_MessageUnit() = default; - static void TearDownTestSuite() - { - Core::Messaging::MessageUnit::Instance().Close(); - Core::Singleton::Dispose(); - } - void SetUp() override - { - for (const auto& control : _controls) { - Core::Messaging::MessageUnit::Instance().Announce(control.get()); + static void SetUpTestSuite() + { + ::Thunder::Core::Messaging::MessageUnit::Instance().IsBackground(_background); + ::Thunder::Core::Messaging::MessageUnit::Instance().Open(_basePath); } - } - void TearDown() override - { - Core::Messaging::MessageUnit::Instance().Defaults(_T("")); - for (const auto& control : _controls) { - Core::Messaging::MessageUnit::Instance().Revoke(control.get()); + static void TearDownTestSuite() + { + ::Thunder::Core::Messaging::MessageUnit::Instance().Close(); + ::Thunder::Core::Singleton::Dispose(); } - } + void SetUp() override + { + for (const auto& control : _controls) { + ::Thunder::Core::Messaging::MessageUnit::Instance().Announce(control.get()); + } + } + + void TearDown() override + { + ::Thunder::Core::Messaging::MessageUnit::Instance().Defaults(_T("")); + for (const auto& control : _controls) { + ::Thunder::Core::Messaging::MessageUnit::Instance().Revoke(control.get()); + } + } + + string DispatcherIdentifier() + { + string result; + ::Thunder::Core::SystemInfo::GetEnvironment(::Thunder::Core::Messaging::MessageUnit::MESSAGE_DISPACTHER_IDENTIFIER_ENV, result); + return result; + } + + string DispatcherBasePath() + { + string result; + ::Thunder::Core::SystemInfo::GetEnvironment(::Thunder::Core::Messaging::MessageUnit::MESSAGE_DISPATCHER_PATH_ENV, result); + return result; + } + + static bool _background; + static string _basePath; + std::list> _controls; + }; + + bool Core_Messaging_MessageUnit::_background = false; + string Core_Messaging_MessageUnit::_basePath = _T("/tmp/"); - string DispatcherIdentifier() + TEST_F(Core_Messaging_MessageUnit, TraceMessageIsEnabledByDefaultWhenConfigFullySpecified) { - string result; - Core::SystemInfo::GetEnvironment(Core::Messaging::MessageUnit::MESSAGE_DISPACTHER_IDENTIFIER_ENV, result); - return result; + const string config = R"({"tracing":{"messages":[{"category":"Information","module":"Plugin_DeviceInfo","enabled":true}]}})"; + + ::Thunder::Core::Messaging::MessageUnit::Instance().Defaults(config); + ASSERT_TRUE(::Thunder::Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ ::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T("Information"), _T("Plugin_DeviceInfo") })); + ASSERT_FALSE(::Thunder::Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ ::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T("Information"), _T("Some_Module") })); + ASSERT_FALSE(::Thunder::Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ ::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T("SomeCategory"), _T("Plugin_DeviceInfo") })); } - string DispatcherBasePath() + TEST_F(Core_Messaging_MessageUnit, TraceMessageIsDisabledByDefaultWhenConfigFullySpecified) { - string result; - Core::SystemInfo::GetEnvironment(Core::Messaging::MessageUnit::MESSAGE_DISPATCHER_PATH_ENV, result); - return result; - } + const string config = R"({"tracing":{"messages":[{"category":"Information","module":"Plugin_DeviceInfo","enabled":false}]}})"; - static bool _background; - static string _basePath; - std::list> _controls; -}; - -bool Core_Messaging_MessageUnit::_background = false; -string Core_Messaging_MessageUnit::_basePath = _T("/tmp/"); - -TEST_F(Core_Messaging_MessageUnit, TraceMessageIsEnabledByDefaultWhenConfigFullySpecified) -{ - const string config = R"({"tracing":{"messages":[{"category":"Information","module":"Plugin_DeviceInfo","enabled":true}]}})"; - - Core::Messaging::MessageUnit::Instance().Defaults(config); - ASSERT_TRUE(Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ Core::Messaging::MetaData::MessageType::TRACING, _T("Information"), _T("Plugin_DeviceInfo") })); - ASSERT_FALSE(Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ Core::Messaging::MetaData::MessageType::TRACING, _T("Information"), _T("Some_Module") })); - ASSERT_FALSE(Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ Core::Messaging::MetaData::MessageType::TRACING, _T("SomeCategory"), _T("Plugin_DeviceInfo") })); -} - -TEST_F(Core_Messaging_MessageUnit, TraceMessageIsDisabledByDefaultWhenConfigFullySpecified) -{ - const string config = R"({"tracing":{"messages":[{"category":"Information","module":"Plugin_DeviceInfo","enabled":false}]}})"; - - Core::Messaging::MessageUnit::Instance().Defaults(config); - ASSERT_FALSE(Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ Core::Messaging::MetaData::MessageType::TRACING, _T("Information"), _T("Plugin_DeviceInfo") })); - ASSERT_FALSE(Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ Core::Messaging::MetaData::MessageType::TRACING, _T("Information"), _T("Some_Module") })); - ASSERT_FALSE(Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ Core::Messaging::MetaData::MessageType::TRACING, _T("SomeCategory"), _T("Plugin_DeviceInfo") })); -} - -TEST_F(Core_Messaging_MessageUnit, TraceMessagesAreEnabledWhenModuleNotSpecified) -{ - const string config = R"({"tracing":{"messages":[{"category":"Information","enabled":true}]}})"; - - Core::Messaging::MessageUnit::Instance().Defaults(config); - ASSERT_TRUE(Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ Core::Messaging::MetaData::MessageType::TRACING, _T("Information"), _T("Plugin_DeviceInfo") })); - ASSERT_TRUE(Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ Core::Messaging::MetaData::MessageType::TRACING, _T("Information"), _T("Some_Module") })); - ASSERT_FALSE(Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ Core::Messaging::MetaData::MessageType::TRACING, _T("SomeCategory"), _T("Plugin_DeviceInfo") })); -} - -TEST_F(Core_Messaging_MessageUnit, TraceMessagesAreDisabledWhenModuleNotSpecified) -{ - const string config = R"({"tracing":{"messages":[{"category":"Information","enabled":false}]}})"; - - Core::Messaging::MessageUnit::Instance().Defaults(config); - ASSERT_FALSE(Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ Core::Messaging::MetaData::MessageType::TRACING, _T("Information"), _T("Plugin_DeviceInfo") })); - ASSERT_FALSE(Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ Core::Messaging::MetaData::MessageType::TRACING, _T("Information"), _T("Some_Module") })); - ASSERT_FALSE(Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ Core::Messaging::MetaData::MessageType::TRACING, _T("SomeCategory"), _T("Plugin_DeviceInfo") })); -} - -TEST_F(Core_Messaging_MessageUnit, LoggingMessageIsEnabledIfNotConfigured) -{ - //logging messages are enabled by default (if not specified otherwise in the config) - const string config = R"({"logging":{"messages":[{"category":"Startup","module":"SysLog","enabled":false}]}})"; - Core::Messaging::MessageUnit::Instance().Defaults(config); - ASSERT_FALSE(Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ Core::Messaging::MetaData::MessageType::LOGGING, _T("Startup"), _T("SysLog") })); - ASSERT_TRUE(Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ Core::Messaging::MetaData::MessageType::LOGGING, _T("Notification"), _T("SysLog") })); -} - -TEST_F(Core_Messaging_MessageUnit, MessageClientWillReturnListOfControls) -{ - //this test is using metadata (IPC) passing, so no other proces tests for now - Messaging::MessageClient client(DispatcherIdentifier(), DispatcherBasePath()); - client.AddInstance(0); //we are in framework - auto it = client.Enabled(); - - int matches = 0; - int count = 0; - while (it.Next()) { - auto info = it.Current(); - if (info.first.Module() == EXPAND_AND_QUOTE(MODULE_NAME)) { - ++matches; - } - ++count; + ::Thunder::Core::Messaging::MessageUnit::Instance().Defaults(config); + ASSERT_FALSE(::Thunder::Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ ::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T("Information"), _T("Plugin_DeviceInfo") })); + ASSERT_FALSE(::Thunder::Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ ::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T("Information"), _T("Some_Module") })); + ASSERT_FALSE(::Thunder::Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ ::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T("SomeCategory"), _T("Plugin_DeviceInfo") })); } - ASSERT_GE(count, 4); - ASSERT_EQ(matches, 4); -} + TEST_F(Core_Messaging_MessageUnit, TraceMessagesAreEnabledWhenModuleNotSpecified) + { + const string config = R"({"tracing":{"messages":[{"category":"Information","enabled":true}]}})"; + + ::Thunder::Core::Messaging::MessageUnit::Instance().Defaults(config); + ASSERT_TRUE(::Thunder::Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ ::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T("Information"), _T("Plugin_DeviceInfo") })); + ASSERT_TRUE(::Thunder::Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ ::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T("Information"), _T("Some_Module") })); + ASSERT_FALSE(::Thunder::Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ ::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T("SomeCategory"), _T("Plugin_DeviceInfo") })); + } -TEST_F(Core_Messaging_MessageUnit, EnablingMessagesShouldUpdateExistingDefaultConfig) -{ - const string config = R"({"tracing":{"messages":[{"category":"ExampleCategory","module":"ExampleModule","enabled":false}]}})"; - Core::Messaging::MessageUnit::Instance().Defaults(config); - const Core::Messaging::MetaData toBeUpdated(Core::Messaging::MetaData::MessageType::TRACING, _T("ExampleCategory"), _T("ExampleModule")); - ASSERT_FALSE(Core::Messaging::MessageUnit::Instance().IsEnabledByDefault(toBeUpdated)); + TEST_F(Core_Messaging_MessageUnit, TraceMessagesAreDisabledWhenModuleNotSpecified) + { + const string config = R"({"tracing":{"messages":[{"category":"Information","enabled":false}]}})"; - Messaging::MessageClient client(DispatcherIdentifier(), DispatcherBasePath()); - client.AddInstance(0); //we are in framework - client.Enable(toBeUpdated, true); + ::Thunder::Core::Messaging::MessageUnit::Instance().Defaults(config); + ASSERT_FALSE(::Thunder::Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ ::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T("Information"), _T("Plugin_DeviceInfo") })); + ASSERT_FALSE(::Thunder::Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ ::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T("Information"), _T("Some_Module") })); + ASSERT_FALSE(::Thunder::Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ ::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T("SomeCategory"), _T("Plugin_DeviceInfo") })); + } - ASSERT_TRUE(Core::Messaging::MessageUnit::Instance().IsEnabledByDefault(toBeUpdated)); -} + TEST_F(Core_Messaging_MessageUnit, LoggingMessageIsEnabledIfNotConfigured) + { + //logging messages are enabled by default (if not specified otherwise in the config) + const string config = R"({"logging":{"messages":[{"category":"Startup","module":"SysLog","enabled":false}]}})"; + ::Thunder::Core::Messaging::MessageUnit::Instance().Defaults(config); + ASSERT_FALSE(::Thunder::Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ ::Thunder::Core::Messaging::MetaData::MessageType::LOGGING, _T("Startup"), _T("SysLog") })); + ASSERT_TRUE(::Thunder::Core::Messaging::MessageUnit::Instance().IsEnabledByDefault({ ::Thunder::Core::Messaging::MetaData::MessageType::LOGGING, _T("Notification"), _T("SysLog") })); + } -TEST_F(Core_Messaging_MessageUnit, EnablingMessagesShouldAddToDefaultConfigListIfNotPresent) -{ - const Core::Messaging::MetaData toBeAdded(Core::Messaging::MetaData::MessageType::TRACING, _T("ExampleCategory"), _T("ExampleModule")); + TEST_F(Core_Messaging_MessageUnit, MessageClientWillReturnListOfControls) + { + //this test is using metadata (IPC) passing, so no other proces tests for now + Messaging::MessageClient client(DispatcherIdentifier(), DispatcherBasePath()); + client.AddInstance(0); //we are in framework + auto it = client.Enabled(); + + int matches = 0; + int count = 0; + while (it.Next()) { + auto info = it.Current(); + if (info.first.Module() == EXPAND_AND_QUOTE(MODULE_NAME)) { + ++matches; + } + ++count; + } - ASSERT_FALSE(Core::Messaging::MessageUnit::Instance().IsEnabledByDefault(toBeAdded)); + ASSERT_GE(count, 4); + ASSERT_EQ(matches, 4); + } - Messaging::MessageClient client(DispatcherIdentifier(), DispatcherBasePath()); - client.AddInstance(0); //we are in framework - client.Enable(toBeAdded, true); + TEST_F(Core_Messaging_MessageUnit, EnablingMessagesShouldUpdateExistingDefaultConfig) + { + const string config = R"({"tracing":{"messages":[{"category":"ExampleCategory","module":"ExampleModule","enabled":false}]}})"; + ::Thunder::Core::Messaging::MessageUnit::Instance().Defaults(config); + const ::Thunder::Core::Messaging::MetaData toBeUpdated(::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T("ExampleCategory"), _T("ExampleModule")); + ASSERT_FALSE(::Thunder::Core::Messaging::MessageUnit::Instance().IsEnabledByDefault(toBeUpdated)); - ASSERT_TRUE(Core::Messaging::MessageUnit::Instance().IsEnabledByDefault(toBeAdded)); - auto defaultsString = Core::Messaging::MessageUnit::Instance().Defaults(); - Core::Messaging::Settings settings; - settings.FromString(defaultsString); + Messaging::MessageClient client(DispatcherIdentifier(), DispatcherBasePath()); + client.AddInstance(0); //we are in framework + client.Enable(toBeUpdated, true); - ASSERT_EQ(settings.Tracing.Entries.Length(), 1); - auto entriesIt = settings.Tracing.Entries.Elements(); - while (entriesIt.Next()) { - ASSERT_STREQ(entriesIt.Current().Category.Value().c_str(), toBeAdded.Category().c_str()); - ASSERT_STREQ(entriesIt.Current().Module.Value().c_str(), toBeAdded.Module().c_str()); + ASSERT_TRUE(::Thunder::Core::Messaging::MessageUnit::Instance().IsEnabledByDefault(toBeUpdated)); } -} -TEST_F(Core_Messaging_MessageUnit, EnablingMessagesByTypeShouldEnableEverything) -{ - Messaging::MessageClient client(DispatcherIdentifier(), DispatcherBasePath()); - client.AddInstance(0); //we are in framework - auto itBeforeUpdate = client.Enabled(); + TEST_F(Core_Messaging_MessageUnit, EnablingMessagesShouldAddToDefaultConfigListIfNotPresent) + { + const ::Thunder::Core::Messaging::MetaData toBeAdded(::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T("ExampleCategory"), _T("ExampleModule")); + + ASSERT_FALSE(::Thunder::Core::Messaging::MessageUnit::Instance().IsEnabledByDefault(toBeAdded)); - int matches = 0; - while (itBeforeUpdate.Next()) { - auto info = itBeforeUpdate.Current(); - if (info.first.Type() == Core::Messaging::MetaData::MessageType::TRACING && info.second == true) { - ++matches; + Messaging::MessageClient client(DispatcherIdentifier(), DispatcherBasePath()); + client.AddInstance(0); //we are in framework + client.Enable(toBeAdded, true); + + ASSERT_TRUE(::Thunder::Core::Messaging::MessageUnit::Instance().IsEnabledByDefault(toBeAdded)); + auto defaultsString = ::Thunder::Core::Messaging::MessageUnit::Instance().Defaults(); + ::Thunder::Core::Messaging::Settings settings; + settings.FromString(defaultsString); + + ASSERT_EQ(settings.Tracing.Entries.Length(), 1); + auto entriesIt = settings.Tracing.Entries.Elements(); + while (entriesIt.Next()) { + ASSERT_STREQ(entriesIt.Current().Category.Value().c_str(), toBeAdded.Category().c_str()); + ASSERT_STREQ(entriesIt.Current().Module.Value().c_str(), toBeAdded.Module().c_str()); } } - ASSERT_EQ(matches, 0); - matches = 0; - client.Enable({ Core::Messaging::MetaData::MessageType::TRACING, _T(""), _T("") }, true); - auto itAfterUpdate = client.Enabled(); - while (itAfterUpdate.Next()) { - auto info = itAfterUpdate.Current(); - if (info.first.Type() == Core::Messaging::MetaData::MessageType::TRACING && info.second == true) { - ++matches; + TEST_F(Core_Messaging_MessageUnit, EnablingMessagesByTypeShouldEnableEverything) + { + Messaging::MessageClient client(DispatcherIdentifier(), DispatcherBasePath()); + client.AddInstance(0); //we are in framework + auto itBeforeUpdate = client.Enabled(); + + int matches = 0; + while (itBeforeUpdate.Next()) { + auto info = itBeforeUpdate.Current(); + if (info.first.Type() == ::Thunder::Core::Messaging::MetaData::MessageType::TRACING && info.second == true) { + ++matches; + } } - } - ASSERT_GE(matches, 5); -} - -TEST_F(Core_Messaging_MessageUnit, LogMessagesCanToggledWhenLogModuleSpecified) -{ - Messaging::MessageClient client(DispatcherIdentifier(), DispatcherBasePath()); - client.AddInstance(0); //we are in framework - auto itBeforeUpdate = client.Enabled(); - Core::Messaging::MetaData messageToToggle(Core::Messaging::MetaData::MessageType::LOGGING, _T("Test_Category_5"), _T("SysLog")); - - int matches = 0; - while (itBeforeUpdate.Next()) { - auto info = itBeforeUpdate.Current(); - if (info.first == messageToToggle && info.second == true) { - ++matches; + ASSERT_EQ(matches, 0); + + matches = 0; + client.Enable({ ::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T(""), _T("") }, true); + auto itAfterUpdate = client.Enabled(); + while (itAfterUpdate.Next()) { + auto info = itAfterUpdate.Current(); + if (info.first.Type() == ::Thunder::Core::Messaging::MetaData::MessageType::TRACING && info.second == true) { + ++matches; + } } + ASSERT_GE(matches, 5); } - ASSERT_EQ(matches, 1); - matches = 0; - client.Enable(messageToToggle, false); - auto itAfterUpdate = client.Enabled(); - while (itAfterUpdate.Next()) { - auto info = itAfterUpdate.Current(); - if (info.first == messageToToggle && info.second == false) { - ++matches; + TEST_F(Core_Messaging_MessageUnit, LogMessagesCanToggledWhenLogModuleSpecified) + { + Messaging::MessageClient client(DispatcherIdentifier(), DispatcherBasePath()); + client.AddInstance(0); //we are in framework + auto itBeforeUpdate = client.Enabled(); + ::Thunder::Core::Messaging::MetaData messageToToggle(::Thunder::Core::Messaging::MetaData::MessageType::LOGGING, _T("Test_Category_5"), _T("SysLog")); + + int matches = 0; + while (itBeforeUpdate.Next()) { + auto info = itBeforeUpdate.Current(); + if (info.first == messageToToggle && info.second == true) { + ++matches; + } } + ASSERT_EQ(matches, 1); + + matches = 0; + client.Enable(messageToToggle, false); + auto itAfterUpdate = client.Enabled(); + while (itAfterUpdate.Next()) { + auto info = itAfterUpdate.Current(); + if (info.first == messageToToggle && info.second == false) { + ++matches; + } + } + ASSERT_EQ(matches, 1); } - ASSERT_EQ(matches, 1); -} - -TEST_F(Core_Messaging_MessageUnit, LogEnablingMessagesShouldAddToDefaultConfigListIfNotPresent) -{ - const Core::Messaging::MetaData tobeAdded(Core::Messaging::MetaData::MessageType::LOGGING, _T("Test_Category_5"), _T("SysLog")); - ASSERT_TRUE(Core::Messaging::MessageUnit::Instance().IsEnabledByDefault(tobeAdded)); - - Messaging::MessageClient client(DispatcherIdentifier(), DispatcherBasePath()); - client.AddInstance(0); //we are in framework - client.Enable(tobeAdded, false); - - ASSERT_FALSE(Core::Messaging::MessageUnit::Instance().IsEnabledByDefault(tobeAdded)); - auto defaultsString = Core::Messaging::MessageUnit::Instance().Defaults(); - Core::Messaging::Settings settings; - settings.FromString(defaultsString); - - ASSERT_EQ(settings.Logging.Entries.Length(), 1); - auto entriesIt = settings.Logging.Entries.Elements(); - while (entriesIt.Next()) { - ASSERT_STREQ(entriesIt.Current().Category.Value().c_str(), tobeAdded.Category().c_str()); - ASSERT_STREQ(entriesIt.Current().Module.Value().c_str(), tobeAdded.Module().c_str()); - } -} -TEST_F(Core_Messaging_MessageUnit, EnablingFullySpecifiedMessageUpdateOnlyThisOne) -{ - Messaging::MessageClient client(DispatcherIdentifier(), DispatcherBasePath()); - client.AddInstance(0); //we are in framework - auto itBeforeUpdate = client.Enabled(); - Core::Messaging::MetaData message(Core::Messaging::MetaData::MessageType::TRACING, _T("Test_Category_1"), EXPAND_AND_QUOTE(MODULE_NAME)); + TEST_F(Core_Messaging_MessageUnit, LogEnablingMessagesShouldAddToDefaultConfigListIfNotPresent) + { + const ::Thunder::Core::Messaging::MetaData tobeAdded(::Thunder::Core::Messaging::MetaData::MessageType::LOGGING, _T("Test_Category_5"), _T("SysLog")); + ASSERT_TRUE(::Thunder::Core::Messaging::MessageUnit::Instance().IsEnabledByDefault(tobeAdded)); - int matches = 0; - while (itBeforeUpdate.Next()) { - auto info = itBeforeUpdate.Current(); - if (info.first == message && info.second == false) { - ++matches; + Messaging::MessageClient client(DispatcherIdentifier(), DispatcherBasePath()); + client.AddInstance(0); //we are in framework + client.Enable(tobeAdded, false); + + ASSERT_FALSE(::Thunder::Core::Messaging::MessageUnit::Instance().IsEnabledByDefault(tobeAdded)); + auto defaultsString = ::Thunder::Core::Messaging::MessageUnit::Instance().Defaults(); + ::Thunder::Core::Messaging::Settings settings; + settings.FromString(defaultsString); + + ASSERT_EQ(settings.Logging.Entries.Length(), 1); + auto entriesIt = settings.Logging.Entries.Elements(); + while (entriesIt.Next()) { + ASSERT_STREQ(entriesIt.Current().Category.Value().c_str(), tobeAdded.Category().c_str()); + ASSERT_STREQ(entriesIt.Current().Module.Value().c_str(), tobeAdded.Module().c_str()); } } - ASSERT_EQ(matches, 1); - matches = 0; - client.Enable(message, true); - auto itAfterUpdate = client.Enabled(); - while (itAfterUpdate.Next()) { - auto info = itAfterUpdate.Current(); - if (info.first == message && info.second == true) { - ++matches; + TEST_F(Core_Messaging_MessageUnit, EnablingFullySpecifiedMessageUpdateOnlyThisOne) + { + Messaging::MessageClient client(DispatcherIdentifier(), DispatcherBasePath()); + client.AddInstance(0); //we are in framework + auto itBeforeUpdate = client.Enabled(); + ::Thunder::Core::Messaging::MetaData message(::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T("Test_Category_1"), EXPAND_AND_QUOTE(MODULE_NAME)); + + int matches = 0; + while (itBeforeUpdate.Next()) { + auto info = itBeforeUpdate.Current(); + if (info.first == message && info.second == false) { + ++matches; + } } - } - ASSERT_EQ(matches, 1); -} - -TEST_F(Core_Messaging_MessageUnit, EnablingMessageSpecifiedByModuleShouldEnableAllCategoriesInsideIt) -{ - Messaging::MessageClient client(DispatcherIdentifier(), DispatcherBasePath()); - client.AddInstance(0); //we are in framework - auto itBeforeUpdate = client.Enabled(); - - int enabled = 0; - while (itBeforeUpdate.Next()) { - auto info = itBeforeUpdate.Current(); - if (info.first.Type() == Core::Messaging::MetaData::MessageType::TRACING && info.first.Module() == EXPAND_AND_QUOTE(MODULE_NAME)) { - if (info.second == true) { - ++enabled; + ASSERT_EQ(matches, 1); + + matches = 0; + client.Enable(message, true); + auto itAfterUpdate = client.Enabled(); + while (itAfterUpdate.Next()) { + auto info = itAfterUpdate.Current(); + if (info.first == message && info.second == true) { + ++matches; } } + ASSERT_EQ(matches, 1); } - ASSERT_EQ(enabled, 0); - - enabled = 0; - client.Enable({ Core::Messaging::MetaData::MessageType::TRACING, _T(""), EXPAND_AND_QUOTE(MODULE_NAME) }, true); - auto itAfterUpdate = client.Enabled(); - while (itAfterUpdate.Next()) { - auto info = itAfterUpdate.Current(); - if (info.first.Type() == Core::Messaging::MetaData::MessageType::TRACING && info.first.Module() == EXPAND_AND_QUOTE(MODULE_NAME)) { - if (info.second == true) { - ++enabled; + + TEST_F(Core_Messaging_MessageUnit, EnablingMessageSpecifiedByModuleShouldEnableAllCategoriesInsideIt) + { + Messaging::MessageClient client(DispatcherIdentifier(), DispatcherBasePath()); + client.AddInstance(0); //we are in framework + auto itBeforeUpdate = client.Enabled(); + + int enabled = 0; + while (itBeforeUpdate.Next()) { + auto info = itBeforeUpdate.Current(); + if (info.first.Type() == ::Thunder::Core::Messaging::MetaData::MessageType::TRACING && info.first.Module() == EXPAND_AND_QUOTE(MODULE_NAME)) { + if (info.second == true) { + ++enabled; + } + } + } + ASSERT_EQ(enabled, 0); + + enabled = 0; + client.Enable({ ::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T(""), EXPAND_AND_QUOTE(MODULE_NAME) }, true); + auto itAfterUpdate = client.Enabled(); + while (itAfterUpdate.Next()) { + auto info = itAfterUpdate.Current(); + if (info.first.Type() == ::Thunder::Core::Messaging::MetaData::MessageType::TRACING && info.first.Module() == EXPAND_AND_QUOTE(MODULE_NAME)) { + if (info.second == true) { + ++enabled; + } } } + + ASSERT_EQ(enabled, 4); } - ASSERT_EQ(enabled, 4); -} - -TEST_F(Core_Messaging_MessageUnit, EnablingMessageSpecifiedByCategoryShouldEnableItInAllModules) -{ - Messaging::MessageClient client(DispatcherIdentifier(), DispatcherBasePath()); - client.AddInstance(0); //we are in framework - auto itBeforeUpdate = client.Enabled(); - - int enabled = 0; - while (itBeforeUpdate.Next()) { - auto info = itBeforeUpdate.Current(); - if (info.first.Type() == Core::Messaging::MetaData::MessageType::TRACING && info.first.Category() == _T("Test_Category_1")) { - if (info.second == true) { - ++enabled; + TEST_F(Core_Messaging_MessageUnit, EnablingMessageSpecifiedByCategoryShouldEnableItInAllModules) + { + Messaging::MessageClient client(DispatcherIdentifier(), DispatcherBasePath()); + client.AddInstance(0); //we are in framework + auto itBeforeUpdate = client.Enabled(); + + int enabled = 0; + while (itBeforeUpdate.Next()) { + auto info = itBeforeUpdate.Current(); + if (info.first.Type() == ::Thunder::Core::Messaging::MetaData::MessageType::TRACING && info.first.Category() == _T("Test_Category_1")) { + if (info.second == true) { + ++enabled; + } } } - } - ASSERT_EQ(enabled, 0); - - enabled = 0; - client.Enable({ Core::Messaging::MetaData::MessageType::TRACING, _T("Test_Category_1"), _T("") }, true); - auto itAfterUpdate = client.Enabled(); - while (itAfterUpdate.Next()) { - auto info = itAfterUpdate.Current(); - if (info.first.Type() == Core::Messaging::MetaData::MessageType::TRACING && info.first.Category() == _T("Test_Category_1")) { - if (info.second == true) { - ++enabled; + ASSERT_EQ(enabled, 0); + + enabled = 0; + client.Enable({ ::Thunder::Core::Messaging::MetaData::MessageType::TRACING, _T("Test_Category_1"), _T("") }, true); + auto itAfterUpdate = client.Enabled(); + while (itAfterUpdate.Next()) { + auto info = itAfterUpdate.Current(); + if (info.first.Type() == ::Thunder::Core::Messaging::MetaData::MessageType::TRACING && info.first.Category() == _T("Test_Category_1")) { + if (info.second == true) { + ++enabled; + } } } - } - ASSERT_EQ(enabled, 2); -} + ASSERT_EQ(enabled, 2); + } -TEST_F(Core_Messaging_MessageUnit, TextMessageEventIsProperlySerializedIfBufferBigEnough) -{ - uint8_t buffer[1 * 1024]; - const string testTextMessage = _T("TEST MESSAGE"); + TEST_F(Core_Messaging_MessageUnit, TextMessageEventIsProperlySerializedIfBufferBigEnough) + { + uint8_t buffer[1 * 1024]; + const string testTextMessage = _T("TEST MESSAGE"); - Messaging::TextMessage tm(testTextMessage); - auto serialized = tm.Serialize(buffer, sizeof(buffer)); - ASSERT_GT(serialized, 0); + Messaging::TextMessage tm(testTextMessage); + auto serialized = tm.Serialize(buffer, sizeof(buffer)); + ASSERT_GT(serialized, 0); - auto deserialized = tm.Deserialize(buffer, sizeof(buffer)); - ASSERT_EQ(serialized, deserialized); + auto deserialized = tm.Deserialize(buffer, sizeof(buffer)); + ASSERT_EQ(serialized, deserialized); - string result; - tm.ToString(result); - ASSERT_STREQ(result.c_str(), testTextMessage.c_str()); -} + string result; + tm.ToString(result); + ASSERT_STREQ(result.c_str(), testTextMessage.c_str()); + } -TEST_F(Core_Messaging_MessageUnit, TextMessageEventIsProperlySerializedAndCutIfBufferNotBigEnough) -{ - uint8_t buffer[5]; - const string testTextMessage = _T("abcdefghi"); + TEST_F(Core_Messaging_MessageUnit, TextMessageEventIsProperlySerializedAndCutIfBufferNotBigEnough) + { + uint8_t buffer[5]; + const string testTextMessage = _T("abcdefghi"); - Messaging::TextMessage tm(testTextMessage); - auto serialized = tm.Serialize(buffer, sizeof(buffer)); - ASSERT_GT(serialized, 0); + Messaging::TextMessage tm(testTextMessage); + auto serialized = tm.Serialize(buffer, sizeof(buffer)); + ASSERT_GT(serialized, 0); - auto deserialized = tm.Deserialize(buffer, serialized); - ASSERT_EQ(serialized, deserialized); + auto deserialized = tm.Deserialize(buffer, serialized); + ASSERT_EQ(serialized, deserialized); - string result; - tm.ToString(result); - //last byte reserved for null termination - ASSERT_STREQ(result.c_str(), _T("abcd")); -} + string result; + tm.ToString(result); + //last byte reserved for null termination + ASSERT_STREQ(result.c_str(), _T("abcd")); + } -TEST_F(Core_Messaging_MessageUnit, ControlListIsProperlySerializedIfBufferBigEnough) -{ - uint8_t buffer[1 * 1024]; + TEST_F(Core_Messaging_MessageUnit, ControlListIsProperlySerializedIfBufferBigEnough) + { + uint8_t buffer[1 * 1024]; - Core::Messaging::ControlList cl; - for (const auto& control : _controls) { - cl.Announce(control.get()); - } + ::Thunder::Core::Messaging::ControlList cl; + for (const auto& control : _controls) { + cl.Announce(control.get()); + } - auto serialized = cl.Serialize(buffer, sizeof(buffer)); - ASSERT_GT(serialized, 0); - ASSERT_EQ(buffer[0], _controls.size()); + auto serialized = cl.Serialize(buffer, sizeof(buffer)); + ASSERT_GT(serialized, 0); + ASSERT_EQ(buffer[0], _controls.size()); - auto deserialized = cl.Deserialize(buffer, serialized); - ASSERT_EQ(serialized, deserialized); + auto deserialized = cl.Deserialize(buffer, serialized); + ASSERT_EQ(serialized, deserialized); - auto informationIt = cl.Information(); - auto controlsIt = _controls.cbegin(); - while (informationIt.Next()) { - ASSERT_EQ(informationIt.Current().first, controlsIt->get()->MessageMetaData()); - ++controlsIt; - } -} - -TEST_F(Core_Messaging_MessageUnit, ControlListIsProperlySerializedIfBufferNotBigEnough) -{ - const int controlsThatShouldFit = 2; - uint16_t maxBufferSize = 0; - auto it = _controls.cbegin(); - for (int i = 0; i < controlsThatShouldFit; ++i, ++it) { - maxBufferSize += sizeof(it->get()->MessageMetaData().Type()); - maxBufferSize += it->get()->MessageMetaData().Category().size() + 1; - maxBufferSize += it->get()->MessageMetaData().Module().size() + 1; - maxBufferSize += sizeof(bool); + auto informationIt = cl.Information(); + auto controlsIt = _controls.cbegin(); + while (informationIt.Next()) { + ASSERT_EQ(informationIt.Current().first, controlsIt->get()->MessageMetaData()); + ++controlsIt; + } } - std::vector buffer; - buffer.resize(maxBufferSize + 1); + TEST_F(Core_Messaging_MessageUnit, ControlListIsProperlySerializedIfBufferNotBigEnough) + { + const int controlsThatShouldFit = 2; + uint16_t maxBufferSize = 0; + auto it = _controls.cbegin(); + for (int i = 0; i < controlsThatShouldFit; ++i, ++it) { + maxBufferSize += sizeof(it->get()->MessageMetaData().Type()); + maxBufferSize += it->get()->MessageMetaData().Category().size() + 1; + maxBufferSize += it->get()->MessageMetaData().Module().size() + 1; + maxBufferSize += sizeof(bool); + } - Core::Messaging::ControlList cl; - for (const auto& control : _controls) { - cl.Announce(control.get()); - } + std::vector buffer; + buffer.resize(maxBufferSize + 1); - auto serialized = cl.Serialize(buffer.data(), buffer.size()); - ASSERT_GT(serialized, 0); - ASSERT_EQ(buffer[0], controlsThatShouldFit); + ::Thunder::Core::Messaging::ControlList cl; + for (const auto& control : _controls) { + cl.Announce(control.get()); + } - auto deserialized = cl.Deserialize(buffer.data(), serialized); - ASSERT_EQ(serialized, deserialized); + auto serialized = cl.Serialize(buffer.data(), buffer.size()); + ASSERT_GT(serialized, 0); + ASSERT_EQ(buffer[0], controlsThatShouldFit); - auto informationIt = cl.Information(); - auto controlsIt = _controls.cbegin(); - while (informationIt.Next()) { - ASSERT_EQ(informationIt.Current().first, controlsIt->get()->MessageMetaData()); - ++controlsIt; + auto deserialized = cl.Deserialize(buffer.data(), serialized); + ASSERT_EQ(serialized, deserialized); + + auto informationIt = cl.Information(); + auto controlsIt = _controls.cbegin(); + while (informationIt.Next()) { + ASSERT_EQ(informationIt.Current().first, controlsIt->get()->MessageMetaData()); + ++controlsIt; + } } -} - -TEST_F(Core_Messaging_MessageUnit, PopMessageShouldReturnLastPushedMessage) -{ - const string traceMessage = _T("some trace"); - Messaging::MessageClient client(DispatcherIdentifier(), DispatcherBasePath()); - client.AddInstance(0); //we are in framework - - //factory should be added before attempting to pop data - Messaging::TraceFactory factory; - client.AddFactory(Core::Messaging::MetaData::MessageType::TRACING, &factory); - - Messaging::TextMessage tm(traceMessage); - Core::Messaging::Information info(Core::Messaging::MetaData::MessageType::TRACING, - _T("some_category"), - EXPAND_AND_QUOTE(MODULE_NAME), - _T("some_file.cpp"), - 1337, - Core::Time::Now().Ticks()); - - Core::Messaging::MessageUnit::Instance().Push(info, &tm); - - auto messages = client.PopMessagesAsList(); - ASSERT_EQ(messages.size(), 1); - auto message = messages.front(); - - ASSERT_NE(message.first.MessageMetaData().Type(), Core::Messaging::MetaData::MessageType::INVALID); - ASSERT_EQ(message.first.MessageMetaData(), info.MessageMetaData()); - - string result; - message.second->ToString(result); - ASSERT_STREQ(message.first.FileName().c_str(), info.FileName().c_str()); - ASSERT_EQ(message.first.LineNumber(), info.LineNumber()); - ASSERT_EQ(message.first.TimeStamp(), info.TimeStamp()); - ASSERT_STREQ(traceMessage.c_str(), result.c_str()); -} - -TEST_F(Core_Messaging_MessageUnit, PopMessageShouldReturnLastPushedMessageInOtherProcess) -{ - const string traceMessage = _T("some trace"); - Messaging::TextMessage tm(traceMessage); - Core::Messaging::Information info(Core::Messaging::MetaData::MessageType::TRACING, - _T("some_category"), - EXPAND_AND_QUOTE(MODULE_NAME), - _T("some_file.cpp"), - 1337, - Core::Time::Now().Ticks()); - - auto lambdaFunc = [&](IPTestAdministrator& testAdmin) { + + TEST_F(Core_Messaging_MessageUnit, PopMessageShouldReturnLastPushedMessage) + { + const string traceMessage = _T("some trace"); Messaging::MessageClient client(DispatcherIdentifier(), DispatcherBasePath()); - client.AddInstance(0); + client.AddInstance(0); //we are in framework + + //factory should be added before attempting to pop data Messaging::TraceFactory factory; - client.AddFactory(Core::Messaging::MetaData::MessageType::TRACING, &factory); - testAdmin.Sync("setup"); - testAdmin.Sync("writer wrote"); - auto messages = client.PopMessagesAsList(); + client.AddFactory(::Thunder::Core::Messaging::MetaData::MessageType::TRACING, &factory); + Messaging::TextMessage tm(traceMessage); + ::Thunder::Core::Messaging::Information info(::Thunder::Core::Messaging::MetaData::MessageType::TRACING, + _T("some_category"), + EXPAND_AND_QUOTE(MODULE_NAME), + _T("some_file.cpp"), + 1337, + ::Thunder::Core::Time::Now().Ticks()); + + ::Thunder::Core::Messaging::MessageUnit::Instance().Push(info, &tm); + + auto messages = client.PopMessagesAsList(); ASSERT_EQ(messages.size(), 1); auto message = messages.front(); - ASSERT_NE(message.first.MessageMetaData().Type(), Core::Messaging::MetaData::MessageType::INVALID); + ASSERT_NE(message.first.MessageMetaData().Type(), ::Thunder::Core::Messaging::MetaData::MessageType::INVALID); ASSERT_EQ(message.first.MessageMetaData(), info.MessageMetaData()); string result; @@ -559,20 +527,58 @@ TEST_F(Core_Messaging_MessageUnit, PopMessageShouldReturnLastPushedMessageInOthe ASSERT_EQ(message.first.LineNumber(), info.LineNumber()); ASSERT_EQ(message.first.TimeStamp(), info.TimeStamp()); ASSERT_STREQ(traceMessage.c_str(), result.c_str()); + } - testAdmin.Sync("reader read"); - testAdmin.Sync("done"); - }; - - static std::function lambdaVar = lambdaFunc; - IPTestAdministrator::OtherSideMain otherSide = [](IPTestAdministrator& testAdmin) { lambdaVar(testAdmin); }; - IPTestAdministrator testAdmin(otherSide); - + TEST_F(Core_Messaging_MessageUnit, PopMessageShouldReturnLastPushedMessageInOtherProcess) { - testAdmin.Sync("setup"); - testAdmin.Sync("writer wrote"); - Core::Messaging::MessageUnit::Instance().Push(info, &tm); - testAdmin.Sync("reader read"); + const string traceMessage = _T("some trace"); + Messaging::TextMessage tm(traceMessage); + ::Thunder::Core::Messaging::Information info(::Thunder::Core::Messaging::MetaData::MessageType::TRACING, + _T("some_category"), + EXPAND_AND_QUOTE(MODULE_NAME), + _T("some_file.cpp"), + 1337, + ::Thunder::Core::Time::Now().Ticks()); + + auto lambdaFunc = [&](IPTestAdministrator& testAdmin) { + Messaging::MessageClient client(DispatcherIdentifier(), DispatcherBasePath()); + client.AddInstance(0); + Messaging::TraceFactory factory; + client.AddFactory(::Thunder::Core::Messaging::MetaData::MessageType::TRACING, &factory); + testAdmin.Sync("setup"); + testAdmin.Sync("writer wrote"); + auto messages = client.PopMessagesAsList(); + + ASSERT_EQ(messages.size(), 1); + auto message = messages.front(); + + ASSERT_NE(message.first.MessageMetaData().Type(), ::Thunder::Core::Messaging::MetaData::MessageType::INVALID); + ASSERT_EQ(message.first.MessageMetaData(), info.MessageMetaData()); + + string result; + message.second->ToString(result); + ASSERT_STREQ(message.first.FileName().c_str(), info.FileName().c_str()); + ASSERT_EQ(message.first.LineNumber(), info.LineNumber()); + ASSERT_EQ(message.first.TimeStamp(), info.TimeStamp()); + ASSERT_STREQ(traceMessage.c_str(), result.c_str()); + + testAdmin.Sync("reader read"); + testAdmin.Sync("done"); + }; + + static std::function lambdaVar = lambdaFunc; + IPTestAdministrator::OtherSideMain otherSide = [](IPTestAdministrator& testAdmin) { lambdaVar(testAdmin); }; + IPTestAdministrator testAdmin(otherSide); + + { + testAdmin.Sync("setup"); + testAdmin.Sync("writer wrote"); + ::Thunder::Core::Messaging::MessageUnit::Instance().Push(info, &tm); + testAdmin.Sync("reader read"); + } + testAdmin.Sync("done"); } - testAdmin.Sync("done"); -} + +} // Core +} // Tests +} // Thunder \ No newline at end of file diff --git a/Tests/unit/core/test_networkinfo.cpp b/Tests/unit/core/test_networkinfo.cpp index b09b5d70cc..3439054849 100644 --- a/Tests/unit/core/test_networkinfo.cpp +++ b/Tests/unit/core/test_networkinfo.cpp @@ -25,100 +25,105 @@ #include -using namespace Thunder; -using namespace Thunder::Core; - -TEST(test_ipv4addressiterator, simple_ipv4addressiterator) -{ - AdapterIterator adapters; - AdapterIterator adapters2; - - AdapterIterator adapter("eth0"); - IPV4AddressIterator result; - - result.Next(); - //EXPECT_EQ(adapters.Index(),adapters.Index()); TODO - while (adapters.Next() == true) { - if (adapters.IsValid() == true) { - IPV4AddressIterator index(adapters.IPV4Addresses()); - EXPECT_EQ(index.Count(),index.Count()); - EXPECT_STREQ(adapters.Name().c_str(),adapters.Name().c_str()); - while (index.Next() == true) { - NodeId current(index.Address()); - IPNode currentNode(index.Address()); - EXPECT_EQ(adapter.Add(currentNode),ERROR_NONE); - EXPECT_EQ(adapter.Gateway(currentNode,current),ERROR_NONE); - EXPECT_EQ(adapter.Delete(currentNode),ERROR_NONE); - EXPECT_EQ(adapter.Broadcast(current),ERROR_NONE); - if ((current.IsMulticast() == false) && (current.IsLocalInterface() == false)) { - result = index; - EXPECT_STREQ(current.HostName().c_str(),current.HostName().c_str()); - EXPECT_STREQ(current.HostAddress().c_str(),current.HostAddress().c_str()); +namespace Thunder { +namespace Tests { +namespace Core { + + TEST(test_ipv4addressiterator, simple_ipv4addressiterator) + { + ::Thunder::Core::AdapterIterator adapters; + ::Thunder::Core::AdapterIterator adapters2; + + ::Thunder::Core::AdapterIterator adapter("eth0"); + ::Thunder::Core::IPV4AddressIterator result; + + result.Next(); + //EXPECT_EQ(adapters.Index(),adapters.Index()); TODO + while (adapters.Next() == true) { + if (adapters.IsValid() == true) { + ::Thunder::Core::IPV4AddressIterator index(adapters.IPV4Addresses()); + EXPECT_EQ(index.Count(),index.Count()); + EXPECT_STREQ(adapters.Name().c_str(),adapters.Name().c_str()); + while (index.Next() == true) { + ::Thunder::Core::NodeId current(index.Address()); + ::Thunder::Core::IPNode currentNode(index.Address()); + EXPECT_EQ(adapter.Add(currentNode),::Thunder::Core::ERROR_NONE); + EXPECT_EQ(adapter.Gateway(currentNode,current),::Thunder::Core::ERROR_NONE); + EXPECT_EQ(adapter.Delete(currentNode),::Thunder::Core::ERROR_NONE); + EXPECT_EQ(adapter.Broadcast(current),::Thunder::Core::ERROR_NONE); + if ((current.IsMulticast() == false) && (current.IsLocalInterface() == false)) { + result = index; + EXPECT_STREQ(current.HostName().c_str(),current.HostName().c_str()); + EXPECT_STREQ(current.HostAddress().c_str(),current.HostAddress().c_str()); + } } } - } + } + + ::Thunder::Core::IPV4AddressIterator ipv4addressiterator1; + ipv4addressiterator1 = result; + ::Thunder::Core::IPV4AddressIterator ipv4addressiterator2(result); + ipv4addressiterator1.Reset(); + + ::Thunder::Core::Singleton::Dispose(); } - IPV4AddressIterator ipv4addressiterator1; - ipv4addressiterator1 = result; - IPV4AddressIterator ipv4addressiterator2(result); - ipv4addressiterator1.Reset(); - - Core::Singleton::Dispose(); -} - -TEST(test_ipv6addressiterator, simple_ipv6addressiterator) -{ - AdapterIterator adapters; - IPV6AddressIterator result; - result.Next(); - while (adapters.Next() == true) { - IPV6AddressIterator index(adapters.IPV6Addresses()); - EXPECT_EQ(index.Count(),index.Count()); - EXPECT_STREQ(adapters.Name().c_str(),adapters.Name().c_str()); - while (index.Next() == true) { - NodeId current(index.Address()); - if ((current.IsMulticast() == false) && (current.IsLocalInterface() == false)) { - result = index; - EXPECT_STREQ(current.HostName().c_str(),current.HostName().c_str()); - EXPECT_STREQ(current.HostAddress().c_str(),current.HostAddress().c_str()); + TEST(test_ipv6addressiterator, simple_ipv6addressiterator) + { + ::Thunder::Core::AdapterIterator adapters; + ::Thunder::Core::IPV6AddressIterator result; + result.Next(); + while (adapters.Next() == true) { + ::Thunder::Core::IPV6AddressIterator index(adapters.IPV6Addresses()); + EXPECT_EQ(index.Count(),index.Count()); + EXPECT_STREQ(adapters.Name().c_str(),adapters.Name().c_str()); + while (index.Next() == true) { + ::Thunder::Core::NodeId current(index.Address()); + if ((current.IsMulticast() == false) && (current.IsLocalInterface() == false)) { + result = index; + EXPECT_STREQ(current.HostName().c_str(),current.HostName().c_str()); + EXPECT_STREQ(current.HostAddress().c_str(),current.HostAddress().c_str()); + } } } + ::Thunder::Core::IPV6AddressIterator ipv6addressiterator1; + ipv6addressiterator1 = result; + ::Thunder::Core::IPV6AddressIterator ipv6addressiterator2(result); + ipv6addressiterator1.Reset(); + + ::Thunder::Core::Singleton::Dispose(); + } + + TEST(DISABLED_test_adapteriterator, simple_adapteriterator) + { + ::Thunder::Core::AdapterIterator adapter("eth0"); + ::Thunder::Core::AdapterIterator adapter1 = adapter; + ::Thunder::Core::AdapterIterator adapter2(adapter); + ::Thunder::Core::AdapterIterator adapter3("test0"); + + EXPECT_TRUE(adapter.IsUp()); + EXPECT_TRUE(adapter.IsRunning()); + adapter.Up(true); + adapter.Up(false); + + EXPECT_EQ(adapter.Count(),adapter.Count()); + EXPECT_STREQ(adapter.Name().c_str(),adapter.Name().c_str()); + + EXPECT_STREQ(adapter.MACAddress(':').c_str(),adapter.MACAddress(':').c_str()); + uint8_t buffer[32]; + adapter.MACAddress(buffer,32); + + ::Thunder::Core::Singleton::Dispose(); } - IPV6AddressIterator ipv6addressiterator1; - ipv6addressiterator1 = result; - IPV6AddressIterator ipv6addressiterator2(result); - ipv6addressiterator1.Reset(); - - Core::Singleton::Dispose(); -} - -TEST(DISABLED_test_adapteriterator, simple_adapteriterator) -{ - AdapterIterator adapter("eth0"); - AdapterIterator adapter1 = adapter; - AdapterIterator adapter2(adapter); - AdapterIterator adapter3("test0"); - - EXPECT_TRUE(adapter.IsUp()); - EXPECT_TRUE(adapter.IsRunning()); - adapter.Up(true); - adapter.Up(false); - - EXPECT_EQ(adapter.Count(),adapter.Count()); - EXPECT_STREQ(adapter.Name().c_str(),adapter.Name().c_str()); - - EXPECT_STREQ(adapter.MACAddress(':').c_str(),adapter.MACAddress(':').c_str()); - uint8_t buffer[32]; - adapter.MACAddress(buffer,32); - - Core::Singleton::Dispose(); -} - -TEST(DISABLED_test_adapterobserver, simple_adapterobserver) -{ - AdapterObserver::INotification* callback; - AdapterObserver observer(callback); - - Core::Singleton::Dispose(); -} + + TEST(DISABLED_test_adapterobserver, simple_adapterobserver) + { + ::Thunder::Core::AdapterObserver::INotification* callback; + ::Thunder::Core::AdapterObserver observer(callback); + + ::Thunder::Core::Singleton::Dispose(); + } + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_nodeid.cpp b/Tests/unit/core/test_nodeid.cpp index 7ff22fcccf..b583814836 100644 --- a/Tests/unit/core/test_nodeid.cpp +++ b/Tests/unit/core/test_nodeid.cpp @@ -25,21 +25,29 @@ #include -using namespace Thunder; - -TEST(Core_NodeId, simpleSet) -{ - Core::NodeId nodeId("localhost:80"); - - std::cout << "Hostname: " << nodeId.HostName() << std::endl; - std::cout << "Type: " << nodeId.Type() << std::endl; - std::cout << "PortNumber: " << nodeId.PortNumber() << std::endl; - std::cout << "IsValid: " << nodeId.IsValid() << std::endl; - std::cout << "Size: " << nodeId.Size() << std::endl; - std::cout << "HostAddress: " << nodeId.HostAddress() << std::endl; - std::cout << "QualifiedName: " << nodeId.QualifiedName() << std::endl; - std::cout << "IsLocalInterface: " << nodeId.IsLocalInterface() << std::endl; - std::cout << "IsAnyInterface: " << nodeId.IsAnyInterface() << std::endl; - std::cout << "IsMulticast: " << nodeId.IsMulticast() << std::endl; - std::cout << "DefaultMask: " << static_cast(nodeId.DefaultMask()) << std::endl; -} +namespace Thunder { +namespace Tests { +namespace Core { + + + + TEST(Core_NodeId, simpleSet) + { + ::Thunder::Core::NodeId nodeId("localhost:80"); + + std::cout << "Hostname: " << nodeId.HostName() << std::endl; + std::cout << "Type: " << nodeId.Type() << std::endl; + std::cout << "PortNumber: " << nodeId.PortNumber() << std::endl; + std::cout << "IsValid: " << nodeId.IsValid() << std::endl; + std::cout << "Size: " << nodeId.Size() << std::endl; + std::cout << "HostAddress: " << nodeId.HostAddress() << std::endl; + std::cout << "QualifiedName: " << nodeId.QualifiedName() << std::endl; + std::cout << "IsLocalInterface: " << nodeId.IsLocalInterface() << std::endl; + std::cout << "IsAnyInterface: " << nodeId.IsAnyInterface() << std::endl; + std::cout << "IsMulticast: " << nodeId.IsMulticast() << std::endl; + std::cout << "DefaultMask: " << static_cast(nodeId.DefaultMask()) << std::endl; + } + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_numbertype.cpp b/Tests/unit/core/test_numbertype.cpp index 5bc5a658bb..27fe4e61c6 100644 --- a/Tests/unit/core/test_numbertype.cpp +++ b/Tests/unit/core/test_numbertype.cpp @@ -27,6 +27,7 @@ namespace Thunder { namespace Tests { +namespace Core { template T Tester(string& text) @@ -39,46 +40,46 @@ namespace Tests { TEST(Core_NumberType, generic) { - Core::NumberType numbertype; + ::Thunder::Core::NumberType numbertype; string buffer = "/Service/testing/numbertype"; - Core::NumberType typetextfragment(Core::TextFragment(string(buffer))); + ::Thunder::Core::NumberType<::Thunder::Core::TextFragment> typetextfragment(::Thunder::Core::TextFragment(string(buffer))); string valdata = "90"; - Core::NumberType val1 = Tester>(valdata); - Core::NumberType val2 = Tester>(valdata); - EXPECT_EQ(Core::NumberType::ToNetwork(val1),'Z'); - EXPECT_EQ(Core::NumberType::FromNetwork(val1),'Z'); - EXPECT_EQ(Core::NumberType::ToNetwork(val2),'Z'); - EXPECT_EQ(Core::NumberType::FromNetwork(val2),'Z'); - - Core::NumberType val3 = Tester>(valdata); - Core::NumberType val4 = Tester>(valdata); - EXPECT_EQ(Core::NumberType::ToNetwork(val3),23040); - EXPECT_EQ(Core::NumberType::FromNetwork(val3),23040); - EXPECT_EQ(Core::NumberType::ToNetwork(val4),23040); - EXPECT_EQ(Core::NumberType::FromNetwork(val4),23040); - - Core::NumberType val5 = Tester>(valdata); - Core::NumberType val6 = (unsigned)Tester>(valdata); - EXPECT_EQ(Core::NumberType::ToNetwork(val5),1509949440); - EXPECT_EQ(Core::NumberType::FromNetwork(val5),1509949440); - EXPECT_EQ(Core::NumberType::ToNetwork(val6),1509949440u); - EXPECT_EQ(Core::NumberType::FromNetwork(val6),1509949440u); - - Core::NumberType val7 = Tester>(valdata); - Core::NumberType val8 = (unsigned)Tester>(valdata); - EXPECT_EQ(Core::NumberType::ToNetwork(val7),90); - EXPECT_EQ(Core::NumberType::FromNetwork(val7),90); - EXPECT_EQ(Core::NumberType::ToNetwork(val8),90u); - EXPECT_EQ(Core::NumberType::FromNetwork(val8),90u); + ::Thunder::Core::NumberType val1 = Tester<::Thunder::Core::NumberType>(valdata); + ::Thunder::Core::NumberType val2 = Tester<::Thunder::Core::NumberType>(valdata); + EXPECT_EQ(::Thunder::Core::NumberType::ToNetwork(val1),'Z'); + EXPECT_EQ(::Thunder::Core::NumberType::FromNetwork(val1),'Z'); + EXPECT_EQ(::Thunder::Core::NumberType::ToNetwork(val2),'Z'); + EXPECT_EQ(::Thunder::Core::NumberType::FromNetwork(val2),'Z'); + + ::Thunder::Core::NumberType val3 = Tester<::Thunder::Core::NumberType>(valdata); + ::Thunder::Core::NumberType val4 = Tester<::Thunder::Core::NumberType>(valdata); + EXPECT_EQ(::Thunder::Core::NumberType::ToNetwork(val3),23040); + EXPECT_EQ(::Thunder::Core::NumberType::FromNetwork(val3),23040); + EXPECT_EQ(::Thunder::Core::NumberType::ToNetwork(val4),23040); + EXPECT_EQ(::Thunder::Core::NumberType::FromNetwork(val4),23040); + + ::Thunder::Core::NumberType val5 = Tester<::Thunder::Core::NumberType>(valdata); + ::Thunder::Core::NumberType val6 = (unsigned)Tester<::Thunder::Core::NumberType>(valdata); + EXPECT_EQ(::Thunder::Core::NumberType::ToNetwork(val5),1509949440); + EXPECT_EQ(::Thunder::Core::NumberType::FromNetwork(val5),1509949440); + EXPECT_EQ(::Thunder::Core::NumberType::ToNetwork(val6),1509949440u); + EXPECT_EQ(::Thunder::Core::NumberType::FromNetwork(val6),1509949440u); + + ::Thunder::Core::NumberType val7 = Tester<::Thunder::Core::NumberType>(valdata); + ::Thunder::Core::NumberType val8 = (unsigned)Tester<::Thunder::Core::NumberType>(valdata); + EXPECT_EQ(::Thunder::Core::NumberType::ToNetwork(val7),90); + EXPECT_EQ(::Thunder::Core::NumberType::FromNetwork(val7),90); + EXPECT_EQ(::Thunder::Core::NumberType::ToNetwork(val8),90u); + EXPECT_EQ(::Thunder::Core::NumberType::FromNetwork(val8),90u); val8.MaxSize(); EXPECT_EQ(val8.Serialize(valdata),2); EXPECT_EQ(val8.Deserialize(valdata),2); string valdata1 = "90"; - Core::NumberType num1 = Tester, false>(valdata); - Core::NumberType num2 = Tester, false>(valdata1); + ::Thunder::Core::NumberType num1 = Tester<::Thunder::Core::NumberType, false>(valdata); + ::Thunder::Core::NumberType num2 = Tester<::Thunder::Core::NumberType, false>(valdata1); EXPECT_TRUE(num1==num2); EXPECT_FALSE(num1!=num2); @@ -104,144 +105,144 @@ namespace Tests { TEST(Core_NumberType, PositiveNumber) { string data = "90"; - Core::NumberType num1 = Tester>(data); + ::Thunder::Core::NumberType num1 = Tester<::Thunder::Core::NumberType>(data); EXPECT_STREQ(num1.Text().c_str(), "90"); - Core::NumberType num2 = Tester>(data); + ::Thunder::Core::NumberType num2 = Tester<::Thunder::Core::NumberType>(data); EXPECT_STREQ(num2.Text().c_str(), "90"); } TEST(Core_NumberType, NegativeNumber) { string data = "-90"; - Core::NumberType num = Tester, true>(data); + ::Thunder::Core::NumberType num = Tester<::Thunder::Core::NumberType, true>(data); EXPECT_STREQ(num.Text().c_str(), "-90"); } TEST(Core_NumberType, NumberOutOfLimit) { string data = "256"; - Core::NumberType num1(data.c_str(), data.size()); + ::Thunder::Core::NumberType num1(data.c_str(), data.size()); EXPECT_NE(256, num1.Value()); data = "128"; - Core::NumberType num2(data.c_str(), data.size()); + ::Thunder::Core::NumberType num2(data.c_str(), data.size()); EXPECT_NE(128, num2.Value()); data = "-129"; - Core::NumberType num3(data.c_str(), data.size()); + ::Thunder::Core::NumberType num3(data.c_str(), data.size()); EXPECT_NE(-129, num3.Value()); } TEST(Core_NumberType, PositiveHexNumber) { string data = "5A"; - Core::NumberType num1 = Tester>(data); + ::Thunder::Core::NumberType num1 = Tester<::Thunder::Core::NumberType>(data); EXPECT_STREQ(num1.Text().c_str(), "0x5A"); - Core::NumberType num2 = Tester>(data); + ::Thunder::Core::NumberType num2 = Tester<::Thunder::Core::NumberType>(data); EXPECT_STREQ(num2.Text().c_str(), "0x5A"); data = "0x5A"; - Core::NumberType num3 = Tester>(data); + ::Thunder::Core::NumberType num3 = Tester<::Thunder::Core::NumberType>(data); EXPECT_STREQ(num3.Text().c_str(), "0x5A"); - Core::NumberType num4 = Tester>(data); + ::Thunder::Core::NumberType num4 = Tester<::Thunder::Core::NumberType>(data); EXPECT_STREQ(num4.Text().c_str(), "0x5A"); - Core::NumberType num5 = Tester>(data); + ::Thunder::Core::NumberType num5 = Tester<::Thunder::Core::NumberType>(data); EXPECT_STREQ(num5.Text().c_str(), "90"); - Core::NumberType num6 = Tester>(data); + ::Thunder::Core::NumberType num6 = Tester<::Thunder::Core::NumberType>(data); EXPECT_STREQ(num6.Text().c_str(), "90"); - Core::NumberType num7(num4); - Core::NumberType num8 = num4; + ::Thunder::Core::NumberType num7(num4); + ::Thunder::Core::NumberType num8 = num4; } TEST(Core_NumberType, NegativeHexNumber) { string data = "-5A"; - Core::NumberType num1 = Tester, true>(data); + ::Thunder::Core::NumberType num1 = Tester<::Thunder::Core::NumberType, true>(data); EXPECT_STREQ(num1.Text().c_str(), "-0x5A"); data = "-0x5A"; - Core::NumberType num2 = Tester, true>(data); + ::Thunder::Core::NumberType num2 = Tester<::Thunder::Core::NumberType, true>(data); EXPECT_STREQ(num2.Text().c_str(), "-0x5A"); - Core::NumberType num3 = Tester, true>(data); + ::Thunder::Core::NumberType num3 = Tester<::Thunder::Core::NumberType, true>(data); EXPECT_STREQ(num3.Text().c_str(), "-90"); } TEST(Core_NumberType, PositiveOctNumber) { string data = "132"; - Core::NumberType num1 = Tester>(data); + ::Thunder::Core::NumberType num1 = Tester<::Thunder::Core::NumberType>(data); EXPECT_STREQ(num1.Text().c_str(), "0132"); - Core::NumberType num2 = Tester>(data); + ::Thunder::Core::NumberType num2 = Tester<::Thunder::Core::NumberType>(data); EXPECT_STREQ(num2.Text().c_str(), "0132"); data = "0132"; - Core::NumberType num3 = Tester>(data); + ::Thunder::Core::NumberType num3 = Tester<::Thunder::Core::NumberType>(data); EXPECT_STREQ(num3.Text().c_str(), "0132"); - Core::NumberType num4 = Tester>(data); + ::Thunder::Core::NumberType num4 = Tester<::Thunder::Core::NumberType>(data); EXPECT_STREQ(num4.Text().c_str(), "0132"); - Core::NumberType num5 = Tester>(data); + ::Thunder::Core::NumberType num5 = Tester<::Thunder::Core::NumberType>(data); EXPECT_STREQ(num5.Text().c_str(), "90"); - Core::NumberType num6 = Tester>(data); + ::Thunder::Core::NumberType num6 = Tester<::Thunder::Core::NumberType>(data); EXPECT_STREQ(num6.Text().c_str(), "90"); } TEST(Core_NumberType, NegativeOctNumber) { string data = "-132"; - Core::NumberType num1 = Tester, true>(data); + ::Thunder::Core::NumberType num1 = Tester<::Thunder::Core::NumberType, true>(data); EXPECT_STREQ(num1.Text().c_str(), "-0132"); data = "-0132"; - Core::NumberType num2 = Tester, true>(data); + ::Thunder::Core::NumberType num2 = Tester<::Thunder::Core::NumberType, true>(data); EXPECT_STREQ(num2.Text().c_str(), "-0132"); - Core::NumberType num3 = Tester, true>(data); + ::Thunder::Core::NumberType num3 = Tester<::Thunder::Core::NumberType, true>(data); EXPECT_STREQ(num3.Text().c_str(), "-90"); } TEST(Core_NumberType, ConversionFunctions) { - EXPECT_EQ(Core::FromDigits('a'), 0); - EXPECT_EQ(Core::FromDigits('1'), 1); - - EXPECT_EQ(Core::FromHexDigits('1'), 1); - EXPECT_EQ(Core::FromHexDigits('a'), 10); - EXPECT_EQ(Core::FromHexDigits('A'), 10); - EXPECT_EQ(Core::FromHexDigits('z'), 0); - - EXPECT_EQ(Core::FromBase64('1'), 53); - EXPECT_EQ(Core::FromBase64('a'), 26); - EXPECT_EQ(Core::FromBase64('A'), 0); - EXPECT_EQ(Core::FromBase64('+'), 62); - EXPECT_EQ(Core::FromBase64('/'), 63); - EXPECT_EQ(Core::FromBase64('-'), 0); - - EXPECT_EQ(Core::FromDirect('a'), 97); - EXPECT_EQ(Core::ToDigits(9), '9'); - - EXPECT_EQ(Core::ToHexDigits(1), '1'); - EXPECT_EQ(Core::ToHexDigits(10), 'A'); - EXPECT_EQ(Core::ToHexDigits(30), '0'); - - EXPECT_EQ(Core::ToBase64(26), 'a'); - EXPECT_EQ(Core::ToDirect(97), 'a'); + EXPECT_EQ(::Thunder::Core::FromDigits('a'), 0); + EXPECT_EQ(::Thunder::Core::FromDigits('1'), 1); + + EXPECT_EQ(::Thunder::Core::FromHexDigits('1'), 1); + EXPECT_EQ(::Thunder::Core::FromHexDigits('a'), 10); + EXPECT_EQ(::Thunder::Core::FromHexDigits('A'), 10); + EXPECT_EQ(::Thunder::Core::FromHexDigits('z'), 0); + + EXPECT_EQ(::Thunder::Core::FromBase64('1'), 53); + EXPECT_EQ(::Thunder::Core::FromBase64('a'), 26); + EXPECT_EQ(::Thunder::Core::FromBase64('A'), 0); + EXPECT_EQ(::Thunder::Core::FromBase64('+'), 62); + EXPECT_EQ(::Thunder::Core::FromBase64('/'), 63); + EXPECT_EQ(::Thunder::Core::FromBase64('-'), 0); + + EXPECT_EQ(::Thunder::Core::FromDirect('a'), 97); + EXPECT_EQ(::Thunder::Core::ToDigits(9), '9'); + + EXPECT_EQ(::Thunder::Core::ToHexDigits(1), '1'); + EXPECT_EQ(::Thunder::Core::ToHexDigits(10), 'A'); + EXPECT_EQ(::Thunder::Core::ToHexDigits(30), '0'); + + EXPECT_EQ(::Thunder::Core::ToBase64(26), 'a'); + EXPECT_EQ(::Thunder::Core::ToDirect(97), 'a'); } TEST(Core_NumberType, Fractional_test) { - Core::Fractional fractional; - Core::Fractional fractional1(3,2); - Core::Fractional fractional2(fractional1); - Core::Fractional fractional3; + ::Thunder::Core::Fractional fractional; + ::Thunder::Core::Fractional fractional1(3,2); + ::Thunder::Core::Fractional fractional2(fractional1); + ::Thunder::Core::Fractional fractional3; fractional3 = fractional1; EXPECT_EQ(fractional1.Integer(),3); EXPECT_EQ(fractional1.Remainder(),2u); - Core::NumberType num1; + ::Thunder::Core::NumberType<::Thunder::Core::Fractional, true> num1; fractional3 = num1.Max(); EXPECT_EQ(fractional3.Integer(),2147483647); @@ -250,5 +251,7 @@ namespace Tests { EXPECT_EQ(fractional3.Integer(),-2147483648); EXPECT_EQ(fractional3.Remainder(),4294967295); } + +} // Core } // Tests } // Thunder diff --git a/Tests/unit/core/test_optional.cpp b/Tests/unit/core/test_optional.cpp index c802dbeeab..0efa4f0498 100644 --- a/Tests/unit/core/test_optional.cpp +++ b/Tests/unit/core/test_optional.cpp @@ -25,30 +25,35 @@ #include -using namespace Thunder; -using namespace Thunder::Core; +namespace Thunder { +namespace Tests { +namespace Core { -TEST(test_optional, simple_test) -{ - OptionalType obj; - int type = obj; - EXPECT_EQ(type, 0); - obj.Clear(); - EXPECT_FALSE(obj.IsSet()); - OptionalType obj1("request"); - OptionalType obj2(obj1); - EXPECT_TRUE(obj2 == obj1); - EXPECT_TRUE(obj2.Value() == obj1.Value()); - EXPECT_TRUE(obj1.IsSet()); - const OptionalType obj3; - OptionalType obj4; - obj4 = obj3; - const OptionalType obj5; - const OptionalType objSample = 40; - OptionalType object; - object = 20; - EXPECT_TRUE(objSample != object.Value()); - EXPECT_TRUE(objSample != obj5); - int type1 = objSample; - EXPECT_EQ(type1, 40); -} + TEST(test_optional, simple_test) + { + ::Thunder::Core::OptionalType obj; + int type = obj; + EXPECT_EQ(type, 0); + obj.Clear(); + EXPECT_FALSE(obj.IsSet()); + ::Thunder::Core::OptionalType obj1("request"); + ::Thunder::Core::OptionalType obj2(obj1); + EXPECT_TRUE(obj2 == obj1); + EXPECT_TRUE(obj2.Value() == obj1.Value()); + EXPECT_TRUE(obj1.IsSet()); + const ::Thunder::Core::OptionalType obj3; + ::Thunder::Core::OptionalType obj4; + obj4 = obj3; + const ::Thunder::Core::OptionalType obj5; + const ::Thunder::Core::OptionalType objSample = 40; + ::Thunder::Core::OptionalType object; + object = 20; + EXPECT_TRUE(objSample != object.Value()); + EXPECT_TRUE(objSample != obj5); + int type1 = objSample; + EXPECT_EQ(type1, 40); + } + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_parser.cpp b/Tests/unit/core/test_parser.cpp index 9ba7053626..1141b19520 100644 --- a/Tests/unit/core/test_parser.cpp +++ b/Tests/unit/core/test_parser.cpp @@ -25,67 +25,72 @@ #include -using namespace Thunder; -using namespace Thunder::Core; +namespace Thunder { +namespace Tests { +namespace Core { -class Deserializer { -private: - typedef ParserType Parser; + class Deserializer { + private: + typedef ::Thunder::Core::ParserType<::Thunder::Core::TerminatorCarriageReturnLineFeed, Deserializer> Parser; -public : - Deserializer() - : _parser(*this) + public : + Deserializer() + : _parser(*this) + { + } + + void operations() + { + _parser.Reset(); + _parser.CollectWord(); + _parser.CollectWord('/'); + _parser.CollectWord(::Thunder::Core::ParserType<::Thunder::Core::TerminatorCarriageReturnLineFeed, Deserializer>::ParseState::UPPERCASE); + _parser.CollectWord('/',::Thunder::Core::ParserType<::Thunder::Core::TerminatorCarriageReturnLineFeed, Deserializer>::ParseState::UPPERCASE); + _parser.CollectLine(); + _parser.CollectLine(::Thunder::Core::ParserType<::Thunder::Core::TerminatorCarriageReturnLineFeed, Deserializer>::ParseState::UPPERCASE); + _parser.FlushLine(); + _parser.PassThrough(5); + } + + ~Deserializer() + { + } + + private: + Parser _parser; + }; + + TEST(test_parser_type, simple_parser_type) { + Deserializer deserializer; + deserializer.operations(); } - void operations() + TEST(test_text_parser, simple_text_parser) { - _parser.Reset(); - _parser.CollectWord(); - _parser.CollectWord('/'); - _parser.CollectWord(Core::ParserType::ParseState::UPPERCASE); - _parser.CollectWord('/',Core::ParserType::ParseState::UPPERCASE); - _parser.CollectLine(); - _parser.CollectLine(Core::ParserType::ParseState::UPPERCASE); - _parser.FlushLine(); - _parser.PassThrough(5); + ::Thunder::Core::TextFragment inputLine("/Service/testing/parsertest"); + ::Thunder::Core::TextParser textparser(inputLine); + textparser.Skip(2); + textparser.Skip('S'); + textparser.Find(_T("e")); + textparser.SkipWhiteSpace(); + textparser.SkipLine(); + ::Thunder::Core::OptionalType<::Thunder::Core::TextFragment> token; + textparser.ReadText(token, _T("/")); } - ~Deserializer() + TEST(test_path_parser, simple_path_parser) { + ::Thunder::Core::TextFragment inputFile("C://Service/testing/pathparsertest.txt"); + ::Thunder::Core::PathParser pathparser(inputFile); + + EXPECT_EQ(pathparser.Drive().Value(),'C'); + EXPECT_STREQ(pathparser.Path().Value().Text().c_str(),_T("//Service/testing")); + EXPECT_STREQ(pathparser.FileName().Value().Text().c_str(),_T("pathparsertest.txt")); + EXPECT_STREQ(pathparser.BaseFileName().Value().Text().c_str(),_T("pathparsertest")); + EXPECT_STREQ(pathparser.Extension().Value().Text().c_str(),_T("txt"));; } -private: - Parser _parser; -}; - -TEST(test_parser_type, simple_parser_type) -{ - Deserializer deserializer; - deserializer.operations(); -} - -TEST(test_text_parser, simple_text_parser) -{ - TextFragment inputLine("/Service/testing/parsertest"); - TextParser textparser(inputLine); - textparser.Skip(2); - textparser.Skip('S'); - textparser.Find(_T("e")); - textparser.SkipWhiteSpace(); - textparser.SkipLine(); - OptionalType token; - textparser.ReadText(token, _T("/")); -} - -TEST(test_path_parser, simple_path_parser) -{ - TextFragment inputFile("C://Service/testing/pathparsertest.txt"); - PathParser pathparser(inputFile); - - EXPECT_EQ(pathparser.Drive().Value(),'C'); - EXPECT_STREQ(pathparser.Path().Value().Text().c_str(),_T("//Service/testing")); - EXPECT_STREQ(pathparser.FileName().Value().Text().c_str(),_T("pathparsertest.txt")); - EXPECT_STREQ(pathparser.BaseFileName().Value().Text().c_str(),_T("pathparsertest")); - EXPECT_STREQ(pathparser.Extension().Value().Text().c_str(),_T("txt"));; -} +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_portability.cpp b/Tests/unit/core/test_portability.cpp index 24e448615b..737a3f9b42 100644 --- a/Tests/unit/core/test_portability.cpp +++ b/Tests/unit/core/test_portability.cpp @@ -27,93 +27,98 @@ #include -using namespace Thunder; -using namespace Thunder::Core; - -class ThreadClass : public Core::Thread { -public: - ThreadClass() = delete; - ThreadClass(const ThreadClass&) = delete; - ThreadClass& operator=(const ThreadClass&) = delete; - - ThreadClass(std::thread::id parentId) - : Core::Thread(Core::Thread::DefaultStackSize(), _T("Test")) - , _threadDone(false) - , _parentId(parentId) +namespace Thunder { +namespace Tests { +namespace Core { + + class ThreadClass : public ::Thunder::Core::Thread { + public: + ThreadClass() = delete; + ThreadClass(const ThreadClass&) = delete; + ThreadClass& operator=(const ThreadClass&) = delete; + + ThreadClass(std::thread::id parentId) + : ::Thunder::Core::Thread(::Thunder::Core::Thread::DefaultStackSize(), _T("Test")) + , _threadDone(false) + , _parentId(parentId) + { + } + + virtual ~ThreadClass() + { + } + + virtual uint32_t Worker() override + { + while (IsRunning() && (!_threadDone)) { + EXPECT_TRUE(_parentId != std::this_thread::get_id()); + _threadDone = true; + ::SleepMs(50); + } + return (::Thunder::Core::infinite); + } + + private: + volatile bool _threadDone; + std::thread::id _parentId; + }; + + TEST(test_portability, simple_upper) { + std::string input = "hello"; + std::string output; + ::Thunder::Core::ToUpper(input,output); + EXPECT_STREQ(output.c_str(),_T("HELLO")); + + ::Thunder::Core::ToUpper(input); + EXPECT_STREQ(input.c_str(),_T("HELLO")); } - virtual ~ThreadClass() + TEST(test_portability, simple_lower) { + std::string input = "HELLO"; + std::string output; + ::Thunder::Core::ToLower(input,output); + EXPECT_STREQ(output.c_str(),_T("hello")); + + ::Thunder::Core::ToLower(input); + EXPECT_STREQ(input.c_str(),_T("hello")); } - virtual uint32_t Worker() override + TEST(test_portability, simple_generic) { - while (IsRunning() && (!_threadDone)) { - EXPECT_TRUE(_parentId != std::this_thread::get_id()); - _threadDone = true; - ::SleepMs(50); - } - return (Core::infinite); + SleepS(1); + SleepMs(1); + EXPECT_EQ(htonl(12345),ntohl(12345)); + + std::thread::id parentId; + ThreadClass object(parentId); + object.Run(); + + //#ifdef __DEBUG__ + // DumpCallStack(object.Id(), nullptr); + //#endif + + object.Stop(); + + std::string s1 = "Hello"; + uint8_t dest_buffer[6]; + ::memmove((void*)dest_buffer,(void*)s1.c_str(), static_cast(5)); + dest_buffer[5] = '\0'; + EXPECT_STREQ((const char*)(dest_buffer),s1.c_str()); + } + + TEST(test_error, simple_error) + { + EXPECT_STREQ(ErrorToString(::Thunder::Core::ERROR_NONE),"ERROR_NONE"); + } + + TEST(test_void, simple_void) + { + ::Thunder::Core::Void v; + ::Thunder::Core::Void v2 = v; } -private: - volatile bool _threadDone; - std::thread::id _parentId; -}; - -TEST(test_portability, simple_upper) -{ - std::string input = "hello"; - std::string output; - ToUpper(input,output); - EXPECT_STREQ(output.c_str(),_T("HELLO")); - - ToUpper(input); - EXPECT_STREQ(input.c_str(),_T("HELLO")); -} - -TEST(test_portability, simple_lower) -{ - std::string input = "HELLO"; - std::string output; - ToLower(input,output); - EXPECT_STREQ(output.c_str(),_T("hello")); - - ToLower(input); - EXPECT_STREQ(input.c_str(),_T("hello")); -} - -TEST(test_portability, simple_generic) -{ - SleepS(1); - SleepMs(1); - EXPECT_EQ(htonl(12345),ntohl(12345)); - - std::thread::id parentId; - ThreadClass object(parentId); - object.Run(); - -//#ifdef __DEBUG__ -// DumpCallStack(object.Id(), nullptr); -//#endif - - object.Stop(); - - std::string s1 = "Hello"; - uint8_t dest_buffer[6]; - ::memmove((void*)dest_buffer,(void*)s1.c_str(), static_cast(5)); - dest_buffer[5] = '\0'; - EXPECT_STREQ((const char*)(dest_buffer),s1.c_str()); -} - -TEST(test_error, simple_error) -{ - EXPECT_STREQ(ErrorToString(ERROR_NONE),"ERROR_NONE"); -} - -TEST(test_void, simple_void) -{ - Void v; - Void v2 = v; -} +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_processinfo.cpp b/Tests/unit/core/test_processinfo.cpp index 5ab22f4a9c..ef9152d4ab 100644 --- a/Tests/unit/core/test_processinfo.cpp +++ b/Tests/unit/core/test_processinfo.cpp @@ -25,39 +25,47 @@ #include -using namespace Thunder; - -TEST(Core_ProcessInfo, simpleSet) -{ - pid_t pid = getpid(); - Core::ProcessInfo processInfo(pid); - std::cout << "Name :" << processInfo.Name() << std::endl; - std::cout << "Id :" << processInfo.Id() << std::endl; - std::cout << "Priority :" << static_cast(processInfo.Priority()) << std::endl; - std::cout << "IsActive :" << (processInfo.IsActive() ? "Yes" : "No") << std::endl; - std::cout << "Executable :" << processInfo.Executable() << std::endl; - //std::cout << "Group :" << processInfo.Group() << std::endl; - //std::cout << "User :" << processInfo.User() << std::endl; - std::cout << "Size Allocated :" << (processInfo.Allocated() >> 10) << " KB" << std::endl; - std::cout << "Size Resident :" << (processInfo.Resident() >> 10) << " KB" << std::endl; - std::cout << "Size Shared :" << (processInfo.Shared() >> 10) << " KB" << std::endl; - - Core::ProcessInfo::Iterator childIterator = Core::ProcessInfo(0).Children(); - - childIterator.Reset(false); - std::list pids; - std::cout << "Children of PID 0 (" << childIterator.Count() << ") in revers order" << std::endl; - while (childIterator.Previous()) { - Core::ProcessInfo childProcessInfo = childIterator.Current(); - std::cout << "\tName : " << childProcessInfo.Name() << " (" << childProcessInfo.Id() << "): " << childProcessInfo.Resident() << std::endl; - pids.push_front(childProcessInfo.Id()); - } +namespace Thunder { +namespace Tests { +namespace Core { + + + + TEST(Core_ProcessInfo, simpleSet) + { + pid_t pid = getpid(); + ::Thunder::Core::ProcessInfo processInfo(pid); + std::cout << "Name :" << processInfo.Name() << std::endl; + std::cout << "Id :" << processInfo.Id() << std::endl; + std::cout << "Priority :" << static_cast(processInfo.Priority()) << std::endl; + std::cout << "IsActive :" << (processInfo.IsActive() ? "Yes" : "No") << std::endl; + std::cout << "Executable :" << processInfo.Executable() << std::endl; + //std::cout << "Group :" << processInfo.Group() << std::endl; + //std::cout << "User :" << processInfo.User() << std::endl; + std::cout << "Size Allocated :" << (processInfo.Allocated() >> 10) << " KB" << std::endl; + std::cout << "Size Resident :" << (processInfo.Resident() >> 10) << " KB" << std::endl; + std::cout << "Size Shared :" << (processInfo.Shared() >> 10) << " KB" << std::endl; - std::cout << "Children of PID 0 (" << childIterator.Count() << ") " << std::endl; - while (childIterator.Next()) { - Core::ProcessInfo childProcessInfo = childIterator.Current(); - std::cout << "\tName : " << childProcessInfo.Name() << " (" << childProcessInfo.Id() << "): " << childProcessInfo.Resident() << std::endl; - EXPECT_EQ(childProcessInfo.Id(),pids.front()); - pids.pop_front(); + ::Thunder::Core::ProcessInfo::Iterator childIterator = ::Thunder::Core::ProcessInfo(0).Children(); + + childIterator.Reset(false); + std::list pids; + std::cout << "Children of PID 0 (" << childIterator.Count() << ") in revers order" << std::endl; + while (childIterator.Previous()) { + ::Thunder::Core::ProcessInfo childProcessInfo = childIterator.Current(); + std::cout << "\tName : " << childProcessInfo.Name() << " (" << childProcessInfo.Id() << "): " << childProcessInfo.Resident() << std::endl; + pids.push_front(childProcessInfo.Id()); + } + + std::cout << "Children of PID 0 (" << childIterator.Count() << ") " << std::endl; + while (childIterator.Next()) { + ::Thunder::Core::ProcessInfo childProcessInfo = childIterator.Current(); + std::cout << "\tName : " << childProcessInfo.Name() << " (" << childProcessInfo.Id() << "): " << childProcessInfo.Resident() << std::endl; + EXPECT_EQ(childProcessInfo.Id(),pids.front()); + pids.pop_front(); + } } -} + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_queue.cpp b/Tests/unit/core/test_queue.cpp index 80c5e237ac..005ed2c742 100644 --- a/Tests/unit/core/test_queue.cpp +++ b/Tests/unit/core/test_queue.cpp @@ -25,12 +25,13 @@ #include -using namespace Thunder; -using namespace Thunder::Core; +namespace Thunder { +namespace Tests { +namespace Core { TEST(test_queue, simple_queue) { - QueueType obj1(20); + ::Thunder::Core::QueueType obj1(20); EXPECT_TRUE(obj1.Insert(20,300)); EXPECT_TRUE(obj1.Insert(30,300)); EXPECT_TRUE(obj1.Post(20)); @@ -42,3 +43,7 @@ TEST(test_queue, simple_queue) obj1.Disable(); obj1.Flush(); } + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_rangetype.cpp b/Tests/unit/core/test_rangetype.cpp index d5aa747099..1a2cb2cf07 100644 --- a/Tests/unit/core/test_rangetype.cpp +++ b/Tests/unit/core/test_rangetype.cpp @@ -27,6 +27,7 @@ namespace Thunder { namespace Tests { +namespace Core { template void RangeTest(T data) @@ -47,23 +48,25 @@ namespace Tests { TEST(Core_RangeType, BoundaryExclusive) { - Core::RangeType data(1u, 100u); - RangeTest, false>(data); + ::Thunder::Core::RangeType data(1u, 100u); + RangeTest<::Thunder::Core::RangeType, false>(data); } TEST(Core_RangeType, BoundaryInclusive) { - Core::RangeType data(1u, 100u); - RangeTest>(data); + ::Thunder::Core::RangeType data(1u, 100u); + RangeTest<::Thunder::Core::RangeType>(data); } TEST(Core_RangeType, EqualBoundary) { - Core::RangeType withBoundary(2u, 2u); + ::Thunder::Core::RangeType withBoundary(2u, 2u); EXPECT_EQ(withBoundary.Range(), 1u); - Core::RangeType withoutBoundary(2u, 2u); + ::Thunder::Core::RangeType withoutBoundary(2u, 2u); EXPECT_EQ(withoutBoundary.Range(), 0u); } + +} // Core } // Tests } // Thunder diff --git a/Tests/unit/core/test_readwritelock.cpp b/Tests/unit/core/test_readwritelock.cpp index 18c72583b5..6aa3a79448 100644 --- a/Tests/unit/core/test_readwritelock.cpp +++ b/Tests/unit/core/test_readwritelock.cpp @@ -25,18 +25,22 @@ #include -using namespace Thunder; -using namespace Thunder::Core; +namespace Thunder { +namespace Tests { +namespace Core { -TEST(test_ReadWritelock, simpleSet) -{ - ReadWriteLock readObj; - EXPECT_TRUE(readObj.ReadLock()); + TEST(test_ReadWritelock, simpleSet) + { + ::Thunder::Core::ReadWriteLock readObj; + EXPECT_TRUE(readObj.ReadLock()); - readObj.ReadUnlock(); - ReadWriteLock writeObj; - EXPECT_TRUE(writeObj.WriteLock()); + readObj.ReadUnlock(); + ::Thunder::Core::ReadWriteLock writeObj; + EXPECT_TRUE(writeObj.WriteLock()); - writeObj.WriteUnlock(); -} + writeObj.WriteUnlock(); + } +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_rectangle.cpp b/Tests/unit/core/test_rectangle.cpp index 2900036b8c..0f6e8a586b 100644 --- a/Tests/unit/core/test_rectangle.cpp +++ b/Tests/unit/core/test_rectangle.cpp @@ -25,32 +25,37 @@ #include -using namespace Thunder; -using namespace Thunder::Core; - -TEST(test_rectangle, simple_rectangle) -{ - Rectangle(); - Rectangle r1(2,3,2,3); - Rectangle r2(2,4,2,4); - EXPECT_FALSE(r1 == r2); - EXPECT_TRUE(r1 != r2); - - Rectangle r3(2,3,2,3); - EXPECT_TRUE(r1 == r3); - EXPECT_FALSE(r1 != r3); +namespace Thunder { +namespace Tests { +namespace Core { + + TEST(test_rectangle, simple_rectangle) + { + ::Thunder::Core::Rectangle(); + ::Thunder::Core::Rectangle r1(2,3,2,3); + ::Thunder::Core::Rectangle r2(2,4,2,4); + EXPECT_FALSE(r1 == r2); + EXPECT_TRUE(r1 != r2); - Rectangle r4 = r1 & r2; - Rectangle r5(2,4,2,2); - EXPECT_TRUE(r4 == r5); - - Rectangle r6 = r1 | r2; - Rectangle r7(2,3,2,5); - EXPECT_TRUE(r6 == r7); - - Rectangle r8 = r1.combine(r2); - EXPECT_TRUE(r8 == r7); - - EXPECT_TRUE(r1.Contains(2,3)); - EXPECT_TRUE(r1.Overlaps(r2)); -} + ::Thunder::Core::Rectangle r3(2,3,2,3); + EXPECT_TRUE(r1 == r3); + EXPECT_FALSE(r1 != r3); + + ::Thunder::Core::Rectangle r4 = r1 & r2; + ::Thunder::Core::Rectangle r5(2,4,2,2); + EXPECT_TRUE(r4 == r5); + + ::Thunder::Core::Rectangle r6 = r1 | r2; + ::Thunder::Core::Rectangle r7(2,3,2,5); + EXPECT_TRUE(r6 == r7); + + ::Thunder::Core::Rectangle r8 = r1.combine(r2); + EXPECT_TRUE(r8 == r7); + + EXPECT_TRUE(r1.Contains(2,3)); + EXPECT_TRUE(r1.Overlaps(r2)); + } + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_rpc.cpp b/Tests/unit/core/test_rpc.cpp index bac4cd4d6d..ffe3c028fb 100644 --- a/Tests/unit/core/test_rpc.cpp +++ b/Tests/unit/core/test_rpc.cpp @@ -29,8 +29,11 @@ #include "../IPTestAdministrator.h" namespace Thunder { +namespace Tests { +namespace Core { + namespace Exchange { - struct IAdder : virtual public Core::IUnknown { + struct IAdder : virtual public ::Thunder::Core::IUnknown { enum { ID = 0x80000001 }; virtual uint32_t GetValue() = 0; virtual void Add(uint32_t value) = 0; @@ -38,9 +41,7 @@ namespace Exchange { }; } // Exchange -namespace Tests { - - class Adder : public Exchange::IAdder + class Adder : public Thunder::Tests::Core::Exchange::IAdder { public: Adder() @@ -64,22 +65,19 @@ namespace Tests { } BEGIN_INTERFACE_MAP(Adder) - INTERFACE_ENTRY(Exchange::IAdder) + INTERFACE_ENTRY(Thunder::Tests::Core::Exchange::IAdder) END_INTERFACE_MAP private: uint32_t m_value; }; - // Proxystubs. - using namespace Exchange; - // ----------------------------------------------------------------- // STUB // ----------------------------------------------------------------- // - // IAdder interface stub definitions + // Thunder::Tests::Core::Exchange::IAdder interface stub definitions // // Methods: // (0) virtual uint32_t GetValue() = 0 @@ -87,49 +85,49 @@ namespace Tests { // (2) virtual uint32_t GetPid() = 0 // - ProxyStub::MethodHandler AdderStubMethods[] = { + ::Thunder::ProxyStub::MethodHandler AdderStubMethods[] = { // virtual uint32_t GetValue() = 0 // - [](Core::ProxyType& channel VARIABLE_IS_NOT_USED, Core::ProxyType& message) { - RPC::Data::Input& input(message->Parameters()); + [](::Thunder::Core::ProxyType<::Thunder::Core::IPCChannel>& channel VARIABLE_IS_NOT_USED, ::Thunder::Core::ProxyType& message) { + ::Thunder::RPC::Data::Input& input(message->Parameters()); // call implementation - IAdder* implementation = reinterpret_cast(input.Implementation()); - EXPECT_TRUE((implementation != nullptr) && "Null IAdder implementation pointer"); + Thunder::Tests::Core::Exchange::IAdder* implementation = reinterpret_cast(input.Implementation()); + EXPECT_TRUE((implementation != nullptr) && "Null Thunder::Tests::Core::Exchange::IAdder implementation pointer"); const uint32_t output = implementation->GetValue(); // write return value - RPC::Data::Frame::Writer writer(message->Response().Writer()); + ::Thunder::RPC::Data::Frame::Writer writer(message->Response().Writer()); writer.Number(output); }, // virtual void Add(uint32_t) = 0 // - [](Core::ProxyType& channel VARIABLE_IS_NOT_USED, Core::ProxyType& message) { - RPC::Data::Input& input(message->Parameters()); + [](::Thunder::Core::ProxyType<::Thunder::Core::IPCChannel>& channel VARIABLE_IS_NOT_USED, ::Thunder::Core::ProxyType& message) { + ::Thunder::RPC::Data::Input& input(message->Parameters()); // read parameters - RPC::Data::Frame::Reader reader(input.Reader()); + ::Thunder::RPC::Data::Frame::Reader reader(input.Reader()); const uint32_t param0 = reader.Number(); // call implementation - IAdder* implementation = reinterpret_cast(input.Implementation()); - EXPECT_TRUE((implementation != nullptr) && "Null IAdder implementation pointer"); + Thunder::Tests::Core::Exchange::IAdder* implementation = reinterpret_cast(input.Implementation()); + EXPECT_TRUE((implementation != nullptr) && "Null Thunder::Tests::Core::Exchange::IAdder implementation pointer"); implementation->Add(param0); }, // virtual uint32_t GetPid() = 0 // - [](Core::ProxyType& channel VARIABLE_IS_NOT_USED, Core::ProxyType& message) { - RPC::Data::Input& input(message->Parameters()); + [](::Thunder::Core::ProxyType<::Thunder::Core::IPCChannel>& channel VARIABLE_IS_NOT_USED, ::Thunder::Core::ProxyType& message) { + ::Thunder::RPC::Data::Input& input(message->Parameters()); // call implementation - IAdder* implementation = reinterpret_cast(input.Implementation()); - EXPECT_TRUE((implementation != nullptr) && "Null IAdder implementation pointer"); + Thunder::Tests::Core::Exchange::IAdder* implementation = reinterpret_cast(input.Implementation()); + EXPECT_TRUE((implementation != nullptr) && "Null Thunder::Tests::Core::Exchange::IAdder implementation pointer"); const uint32_t output = implementation->GetPid(); // write return value - RPC::Data::Frame::Writer writer(message->Response().Writer()); + ::Thunder::RPC::Data::Frame::Writer writer(message->Response().Writer()); writer.Number(output); }, @@ -141,7 +139,7 @@ namespace Tests { // ----------------------------------------------------------------- // - // IAdder interface proxy definitions + // Thunder::Tests::Core::Exchange::IAdder interface proxy definitions // // Methods: // (0) virtual uint32_t GetValue() = 0 @@ -149,22 +147,22 @@ namespace Tests { // (2) virtual uint32_t GetPid() = 0 // - class AdderProxy final : public ProxyStub::UnknownProxyType { + class AdderProxy final : public ::Thunder::ProxyStub::UnknownProxyType { public: - AdderProxy(const Core::ProxyType& channel, Core::instance_id implementation, const bool otherSideInformed) - : BaseClass(channel, implementation, otherSideInformed) + AdderProxy(const ::Thunder::Core::ProxyType<::Thunder::Core::IPCChannel>& channel, ::Thunder::Core::instance_id implementation, const bool otherSideInformed) + : ::Thunder::ProxyStub::UnknownProxyType::BaseClass(channel, implementation, otherSideInformed) { } uint32_t GetValue() override { - IPCMessage newMessage(BaseClass::Message(0)); + ::Thunder::ProxyStub::UnknownProxyType::IPCMessage newMessage(::Thunder::ProxyStub::UnknownProxyType::BaseClass::Message(0)); // invoke the method handler uint32_t output{}; - if ((output = Invoke(newMessage)) == Core::ERROR_NONE) { + if ((output = Invoke(newMessage)) == ::Thunder::Core::ERROR_NONE) { // read return value - RPC::Data::Frame::Reader reader(newMessage->Response().Reader()); + ::Thunder::RPC::Data::Frame::Reader reader(newMessage->Response().Reader()); output = reader.Number(); } @@ -173,10 +171,10 @@ namespace Tests { void Add(uint32_t param0) override { - IPCMessage newMessage(BaseClass::Message(1)); + ::Thunder::ProxyStub::UnknownProxyType::IPCMessage newMessage(::Thunder::ProxyStub::UnknownProxyType::BaseClass::Message(1)); // write parameters - RPC::Data::Frame::Writer writer(newMessage->Parameters().Writer()); + ::Thunder::RPC::Data::Frame::Writer writer(newMessage->Parameters().Writer()); writer.Number(param0); // invoke the method handler @@ -185,13 +183,13 @@ namespace Tests { uint32_t GetPid() override { - IPCMessage newMessage(BaseClass::Message(2)); + ::Thunder::ProxyStub::UnknownProxyType::IPCMessage newMessage(::Thunder::ProxyStub::UnknownProxyType::BaseClass::Message(2)); // invoke the method handler uint32_t output{}; - if ((output = Invoke(newMessage)) == Core::ERROR_NONE) { + if ((output = Invoke(newMessage)) == ::Thunder::Core::ERROR_NONE) { // read return value - RPC::Data::Frame::Reader reader(newMessage->Response().Reader()); + ::Thunder::RPC::Data::Frame::Reader reader(newMessage->Response().Reader()); output = reader.Number(); } @@ -205,35 +203,35 @@ namespace Tests { namespace { - typedef ProxyStub::UnknownStubType AdderStub; + typedef ::Thunder::ProxyStub::UnknownStubType AdderStub; static class Instantiation { public: Instantiation() { - RPC::Administrator::Instance().Announce(); + ::Thunder::RPC::Administrator::Instance().Announce(); } } ProxyStubRegistration; } // namespace namespace { - class ExternalAccess : public RPC::Communicator + class ExternalAccess : public ::Thunder::RPC::Communicator { public: ExternalAccess() = delete; ExternalAccess(const ExternalAccess &) = delete; ExternalAccess & operator=(const ExternalAccess &) = delete; - ExternalAccess(const Core::NodeId & source) - : RPC::Communicator(source, _T("")) + ExternalAccess(const ::Thunder::Core::NodeId & source) + : ::Thunder::RPC::Communicator(source, _T("")) { - Open(Core::infinite); + Open(::Thunder::Core::infinite); } ~ExternalAccess() { - Close(Core::infinite); + Close(::Thunder::Core::infinite); } private: @@ -241,8 +239,8 @@ namespace Tests { { void* result = nullptr; - if (interfaceId == Exchange::IAdder::ID) { - Exchange::IAdder * newAdder = Core::Service::Create(); + if (interfaceId == Thunder::Tests::Core::Exchange::IAdder::ID) { + Thunder::Tests::Core::Exchange::IAdder * newAdder = ::Thunder::Core::Service::Create(); result = newAdder; } @@ -255,7 +253,7 @@ namespace Tests { { std::string connector{"/tmp/wperpc01"}; auto lambdaFunc = [connector](IPTestAdministrator & testAdmin) { - Core::NodeId remoteNode(connector.c_str()); + ::Thunder::Core::NodeId remoteNode(connector.c_str()); ExternalAccess communicator(remoteNode); @@ -263,7 +261,7 @@ namespace Tests { testAdmin.Sync("done testing"); - communicator.Close(Core::infinite); + communicator.Close(::Thunder::Core::infinite); }; static std::function lambdaVar = lambdaFunc; @@ -275,15 +273,15 @@ namespace Tests { testAdmin.Sync("setup server"); { - Core::NodeId remoteNode(connector.c_str()); + ::Thunder::Core::NodeId remoteNode(connector.c_str()); - Core::ProxyType> engine = Core::ProxyType>::Create(); + ::Thunder::Core::ProxyType<::Thunder::RPC::InvokeServerType<4, 0, 1>> engine = ::Thunder::Core::ProxyType<::Thunder::RPC::InvokeServerType<4, 0, 1>>::Create(); EXPECT_TRUE(engine.IsValid()); - Core::ProxyType client = Core::ProxyType::Create(remoteNode, Core::ProxyType(engine)); + ::Thunder::Core::ProxyType<::Thunder::RPC::CommunicatorClient> client = ::Thunder::Core::ProxyType<::Thunder::RPC::CommunicatorClient>::Create(remoteNode, ::Thunder::Core::ProxyType<::Thunder::Core::IIPCServer>(engine)); EXPECT_TRUE(client.IsValid()); - // Create remote instance of "IAdder". - Exchange::IAdder * adder = client->Open(_T("Adder")); + // Create remote instance of "Thunder::Tests::Core::Exchange::IAdder". + Thunder::Tests::Core::Exchange::IAdder * adder = client->Open(_T("Adder")); ASSERT_TRUE(adder != nullptr); @@ -299,11 +297,13 @@ namespace Tests { adder->Release(); - client->Close(Core::infinite); + client->Close(::Thunder::Core::infinite); } testAdmin.Sync("done testing"); - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } + +} // Core } // Tests } // Thunder diff --git a/Tests/unit/core/test_semaphore.cpp b/Tests/unit/core/test_semaphore.cpp index 356aaf7104..f5dec185c8 100644 --- a/Tests/unit/core/test_semaphore.cpp +++ b/Tests/unit/core/test_semaphore.cpp @@ -27,115 +27,120 @@ #include -using namespace Thunder; -using namespace Thunder::Core; - -static int g_shared = 2; // Change it back to 1 after fixing and enabling simple_criticalsection test - -class ThreadClass : public Core::Thread { -public: - ThreadClass() = delete; - ThreadClass(const ThreadClass&) = delete; - ThreadClass& operator=(const ThreadClass&) = delete; - - ThreadClass(Core::CriticalSection& lock,std::thread::id parentId) - : Core::Thread(Core::Thread::DefaultStackSize(), _T("Test")) - , _lock(lock) - , _parentId(parentId) - , _done(false) - { - } +namespace Thunder { +namespace Tests { +namespace Core { + + static int g_shared = 2; // Change it back to 1 after fixing and enabling simple_criticalsection test + + class ThreadClass : public ::Thunder::Core::Thread { + public: + ThreadClass() = delete; + ThreadClass(const ThreadClass&) = delete; + ThreadClass& operator=(const ThreadClass&) = delete; + + ThreadClass(::Thunder::Core::CriticalSection& lock,std::thread::id parentId) + : ::Thunder::Core::Thread(::Thunder::Core::Thread::DefaultStackSize(), _T("Test")) + , _lock(lock) + , _parentId(parentId) + , _done(false) + { + } + + virtual ~ThreadClass() + { + } + + virtual uint32_t Worker() override + { + while (IsRunning() && (!_done)) { + EXPECT_TRUE(_parentId != std::this_thread::get_id()); + _done = true; + _lock.Lock(); + g_shared++; + _lock.Unlock(); + ::SleepMs(50); + } + return (::Thunder::Core::infinite); + } - virtual ~ThreadClass() + private: + ::Thunder::Core::CriticalSection& _lock; + std::thread::id _parentId; + volatile bool _done; + }; + + TEST(test_criticalsection, DISABLED_simple_criticalsection) { + ::Thunder::Core::CriticalSection lock; + + ThreadClass object(lock, std::this_thread::get_id()); + object.Run(); + lock.Lock(); + g_shared++; + lock.Unlock(); + object.Stop(); + object.Wait(::Thunder::Core::Thread::STOPPED, ::Thunder::Core::infinite); + EXPECT_EQ(g_shared,2); } - virtual uint32_t Worker() override + TEST(test_binairysemaphore, simple_binairysemaphore_timeout) { - while (IsRunning() && (!_done)) { - EXPECT_TRUE(_parentId != std::this_thread::get_id()); - _done = true; - _lock.Lock(); + ::Thunder::Core::BinairySemaphore bsem(true); + uint64_t timeOut(::Thunder::Core::Time::Now().Add(3).Ticks()); + uint64_t now(::Thunder::Core::Time::Now().Ticks()); + + if (now < timeOut) { + bsem.Lock(static_cast((timeOut - now) / ::Thunder::Core::Time::TicksPerMillisecond)); g_shared++; - _lock.Unlock(); - ::SleepMs(50); } - return (Core::infinite); + EXPECT_EQ(g_shared,3); } -private: - Core::CriticalSection& _lock; - std::thread::id _parentId; - volatile bool _done; -}; - -TEST(test_criticalsection, DISABLED_simple_criticalsection) -{ - Core::CriticalSection lock; - - ThreadClass object(lock, std::this_thread::get_id()); - object.Run(); - lock.Lock(); - g_shared++; - lock.Unlock(); - object.Stop(); - object.Wait(Core::Thread::STOPPED, Core::infinite); - EXPECT_EQ(g_shared,2); -} - -TEST(test_binairysemaphore, simple_binairysemaphore_timeout) -{ - BinairySemaphore bsem(true); - uint64_t timeOut(Core::Time::Now().Add(3).Ticks()); - uint64_t now(Core::Time::Now().Ticks()); - - if (now < timeOut) { - bsem.Lock(static_cast((timeOut - now) / Core::Time::TicksPerMillisecond)); + TEST(test_binairysemaphore, simple_binairysemaphore) + { + ::Thunder::Core::BinairySemaphore bsem(1,5); + bsem.Lock(); g_shared++; + bsem.Unlock(); + EXPECT_EQ(g_shared,4); } - EXPECT_EQ(g_shared,3); -} - -TEST(test_binairysemaphore, simple_binairysemaphore) -{ - BinairySemaphore bsem(1,5); - bsem.Lock(); - g_shared++; - bsem.Unlock(); - EXPECT_EQ(g_shared,4); -} - -TEST(test_countingsemaphore, simple_countingsemaphore_timeout) -{ - CountingSemaphore csem(1,5); - uint64_t timeOut(Core::Time::Now().Add(3).Ticks()); - uint64_t now(Core::Time::Now().Ticks()); - do + + TEST(test_countingsemaphore, simple_countingsemaphore_timeout) { - if (now < timeOut) { - csem.Lock(static_cast((timeOut - now) / Core::Time::TicksPerMillisecond)); - g_shared++; - } - } while (timeOut < Core::Time::Now().Ticks()); - EXPECT_EQ(g_shared,5); - - timeOut = Core::Time::Now().Add(3).Ticks(); - now = Core::Time::Now().Ticks(); - do + ::Thunder::Core::CountingSemaphore csem(1,5); + uint64_t timeOut(::Thunder::Core::Time::Now().Add(3).Ticks()); + uint64_t now(::Thunder::Core::Time::Now().Ticks()); + do + { + if (now < timeOut) { + csem.Lock(static_cast((timeOut - now) / ::Thunder::Core::Time::TicksPerMillisecond)); + g_shared++; + } + } while (timeOut < ::Thunder::Core::Time::Now().Ticks()); + EXPECT_EQ(g_shared,5); + + timeOut = ::Thunder::Core::Time::Now().Add(3).Ticks(); + now = ::Thunder::Core::Time::Now().Ticks(); + do + { + if (now < timeOut) { + csem.TryUnlock(static_cast((timeOut - now) / ::Thunder::Core::Time::TicksPerMillisecond)); + g_shared++; + } + } while (timeOut < ::Thunder::Core::Time::Now().Ticks()); + EXPECT_EQ(g_shared,6); + } + + TEST(test_countingsemaphore, simple_countingsemaphore) { - if (now < timeOut) { - csem.TryUnlock(static_cast((timeOut - now) / Core::Time::TicksPerMillisecond)); - g_shared++; - } - } while (timeOut < Core::Time::Now().Ticks()); - EXPECT_EQ(g_shared,6); -} - -TEST(test_countingsemaphore, simple_countingsemaphore) -{ - CountingSemaphore csem(1,5); - csem.Lock(); - g_shared++; - csem.Unlock(1); - EXPECT_EQ(g_shared,7); -} + ::Thunder::Core::CountingSemaphore csem(1,5); + csem.Lock(); + g_shared++; + csem.Unlock(1); + EXPECT_EQ(g_shared,7); + } + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_sharedbuffer.cpp b/Tests/unit/core/test_sharedbuffer.cpp index c3577700f7..0dd41eecc7 100644 --- a/Tests/unit/core/test_sharedbuffer.cpp +++ b/Tests/unit/core/test_sharedbuffer.cpp @@ -29,6 +29,7 @@ namespace Thunder { namespace Tests { +namespace Core { void CleanUpBuffer(string bufferName) { @@ -53,16 +54,16 @@ namespace Tests { uint32_t bufferSize = 8 * 1024; uint32_t result; - Core::SharedBuffer buff01(bufferName.c_str(), - Core::File::USER_READ | - Core::File::USER_WRITE | - Core::File::USER_EXECUTE | - Core::File::GROUP_READ | - Core::File::GROUP_WRITE , + ::Thunder::Core::SharedBuffer buff01(bufferName.c_str(), + ::Thunder::Core::File::USER_READ | + ::Thunder::Core::File::USER_WRITE | + ::Thunder::Core::File::USER_EXECUTE | + ::Thunder::Core::File::GROUP_READ | + ::Thunder::Core::File::GROUP_WRITE , bufferSize, administrationSize); - result = buff01.RequestProduce(Core::infinite); - EXPECT_EQ(result, Core::ERROR_NONE); + result = buff01.RequestProduce(::Thunder::Core::infinite); + EXPECT_EQ(result, ::Thunder::Core::ERROR_NONE); testAdmin.Sync("setup producer"); @@ -76,7 +77,7 @@ namespace Tests { buffer[2] = 44; result = buff01.Produced(); - EXPECT_EQ(result, Core::ERROR_NONE); + EXPECT_EQ(result, ::Thunder::Core::ERROR_NONE); testAdmin.Sync("consumer done"); }; @@ -93,12 +94,12 @@ namespace Tests { uint32_t bufferSize = 8 * 1024; uint32_t result; - Core::SharedBuffer buff01(bufferName.c_str()); + ::Thunder::Core::SharedBuffer buff01(bufferName.c_str()); testAdmin.Sync("setup consumer"); - result = buff01.RequestConsume(Core::infinite); - EXPECT_EQ(result, Core::ERROR_NONE); + result = buff01.RequestConsume(::Thunder::Core::infinite); + EXPECT_EQ(result, ::Thunder::Core::ERROR_NONE); uint8_t * buffer = buff01.Buffer(); EXPECT_EQ(buff01.Size(), bufferSize); @@ -108,12 +109,12 @@ namespace Tests { EXPECT_EQ(buffer[2], 44); buff01.Consumed(); - EXPECT_EQ(result, Core::ERROR_NONE); + EXPECT_EQ(result, ::Thunder::Core::ERROR_NONE); } testAdmin.Sync("consumer done"); - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } TEST(Core_SharedBuffer, simpleSetReversed) @@ -126,12 +127,12 @@ namespace Tests { uint32_t bufferSize = 8 * 1024; uint32_t result; - Core::SharedBuffer buff01(bufferName.c_str()); + ::Thunder::Core::SharedBuffer buff01(bufferName.c_str()); testAdmin.Sync("setup producer"); - result = buff01.RequestConsume(Core::infinite); - EXPECT_EQ(result, Core::ERROR_NONE); + result = buff01.RequestConsume(::Thunder::Core::infinite); + EXPECT_EQ(result, ::Thunder::Core::ERROR_NONE); uint8_t * buffer = buff01.Buffer(); EXPECT_EQ(buff01.Size(), bufferSize); @@ -141,7 +142,7 @@ namespace Tests { EXPECT_EQ(buffer[2], 44); buff01.Consumed(); - EXPECT_EQ(result, Core::ERROR_NONE); + EXPECT_EQ(result, ::Thunder::Core::ERROR_NONE); testAdmin.Sync("producer done"); }; @@ -159,16 +160,16 @@ namespace Tests { uint32_t bufferSize = 8 * 1024; uint32_t result; - Core::SharedBuffer buff01(bufferName.c_str(), - Core::File::USER_READ | - Core::File::USER_WRITE | - Core::File::USER_EXECUTE | - Core::File::GROUP_READ | - Core::File::GROUP_WRITE , + ::Thunder::Core::SharedBuffer buff01(bufferName.c_str(), + ::Thunder::Core::File::USER_READ | + ::Thunder::Core::File::USER_WRITE | + ::Thunder::Core::File::USER_EXECUTE | + ::Thunder::Core::File::GROUP_READ | + ::Thunder::Core::File::GROUP_WRITE , bufferSize, administrationSize); - result = buff01.RequestProduce(Core::infinite); - EXPECT_EQ(result, Core::ERROR_NONE); + result = buff01.RequestProduce(::Thunder::Core::infinite); + EXPECT_EQ(result, ::Thunder::Core::ERROR_NONE); testAdmin.Sync("setup consumer"); @@ -182,13 +183,15 @@ namespace Tests { buffer[2] = 44; result = buff01.Produced(); - EXPECT_EQ(result, Core::ERROR_NONE); + EXPECT_EQ(result, ::Thunder::Core::ERROR_NONE); } testAdmin.Sync("producer done"); CleanUpBuffer(bufferName); - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } + +} // Core } // Tests } // Thunder diff --git a/Tests/unit/core/test_singleton.cpp b/Tests/unit/core/test_singleton.cpp index 26a1acf184..cf65be489c 100644 --- a/Tests/unit/core/test_singleton.cpp +++ b/Tests/unit/core/test_singleton.cpp @@ -25,48 +25,53 @@ #include -using namespace Thunder; -using namespace Thunder::Core; +namespace Thunder { +namespace Tests { +namespace Core { -class SingletonTypeOne { - public: - SingletonTypeOne() - { - } - virtual ~SingletonTypeOne() - { - } -}; + class SingletonTypeOne { + public: + SingletonTypeOne() + { + } + virtual ~SingletonTypeOne() + { + } + }; -class SingletonTypeTwo { - public: - SingletonTypeTwo(string) - { - } - virtual ~SingletonTypeTwo() - { - } -}; -class SingletonTypeThree { - public: - SingletonTypeThree (string, string) - { - } - virtual ~SingletonTypeThree() - { - } -}; + class SingletonTypeTwo { + public: + SingletonTypeTwo(string) + { + } + virtual ~SingletonTypeTwo() + { + } + }; + class SingletonTypeThree { + public: + SingletonTypeThree (string, string) + { + } + virtual ~SingletonTypeThree() + { + } + }; -TEST(test_singleton, simple_singleton) -{ - static SingletonTypeOne& object1 = SingletonType::Instance(); - static SingletonTypeOne& object_sample = SingletonType::Instance(); - EXPECT_EQ(&object1,&object_sample); - static SingletonTypeTwo& object2 = SingletonType::Instance("SingletonTypeTwo"); - static SingletonTypeThree& object3 = SingletonType::Instance("SingletonTypeThree","SingletonTypeThree"); - SingletonType* x = (SingletonType*)&object2; - EXPECT_STREQ(x->ImplementationName().c_str(),"SingletonTypeTwo"); - SingletonType* y = (SingletonType*)&object3; - EXPECT_STREQ(y->ImplementationName().c_str(),"SingletonTypeThree"); - Singleton::Dispose(); -} + TEST(test_singleton, simple_singleton) + { + static SingletonTypeOne& object1 = ::Thunder::Core::SingletonType::Instance(); + static SingletonTypeOne& object_sample = ::Thunder::Core::SingletonType::Instance(); + EXPECT_EQ(&object1,&object_sample); + static SingletonTypeTwo& object2 = ::Thunder::Core::SingletonType::Instance("SingletonTypeTwo"); + static SingletonTypeThree& object3 = ::Thunder::Core::SingletonType::Instance("SingletonTypeThree","SingletonTypeThree"); + ::Thunder::Core::SingletonType* x = (::Thunder::Core::SingletonType*)&object2; + EXPECT_STREQ(x->ImplementationName().c_str(),"SingletonTypeTwo"); + ::Thunder::Core::SingletonType* y = (::Thunder::Core::SingletonType*)&object3; + EXPECT_STREQ(y->ImplementationName().c_str(),"SingletonTypeThree"); + ::Thunder::Core::Singleton::Dispose(); + } + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_socketstreamjson.cpp b/Tests/unit/core/test_socketstreamjson.cpp index 337491e46d..6441a30547 100644 --- a/Tests/unit/core/test_socketstreamjson.cpp +++ b/Tests/unit/core/test_socketstreamjson.cpp @@ -32,21 +32,22 @@ namespace Thunder { namespace Tests { +namespace Core { - enum class CommandType { + enum class CommandTypeSocketStreamJSON { EXECUTESHELL, WIFISETTINGS, FANCONTROL, PLAYERCONTROL }; - class Parameters : public Core::JSON::Container { + class Parameters : public ::Thunder::Core::JSON::Container { public: Parameters(const Parameters&) = delete; Parameters& operator=(const Parameters&) = delete; Parameters() - : Core::JSON::Container() + : ::Thunder::Core::JSON::Container() , Speed(0) , Duration(0) , Command() @@ -63,19 +64,19 @@ namespace Tests { } public: - Core::JSON::OctSInt16 Speed; - Core::JSON::DecUInt16 Duration; - Core::JSON::EnumType Command; - Core::JSON::ArrayType Settings; + ::Thunder::Core::JSON::OctSInt16 Speed; + ::Thunder::Core::JSON::DecUInt16 Duration; + ::Thunder::Core::JSON::EnumType Command; + ::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::DecUInt16> Settings; }; - class Command : public Core::JSON::Container { + class Command : public ::Thunder::Core::JSON::Container { public: Command(const Command&) = delete; Command& operator=(const Command&) = delete; Command() - : Core::JSON::Container() + : ::Thunder::Core::JSON::Container() , Identifier(0) , Name() , BaseAddress(0) @@ -94,20 +95,20 @@ namespace Tests { } public: - Core::JSON::DecUInt32 Identifier; - Core::JSON::String Name; - Core::JSON::HexUInt32 BaseAddress; - Core::JSON::Boolean TrickFlag; + ::Thunder::Core::JSON::DecUInt32 Identifier; + ::Thunder::Core::JSON::String Name; + ::Thunder::Core::JSON::HexUInt32 BaseAddress; + ::Thunder::Core::JSON::Boolean TrickFlag; Parameters Params; }; - class JSONObjectFactory : public Core::ProxyPoolType { + class JSONObjectFactory : public ::Thunder::Core::ProxyPoolType { public: JSONObjectFactory() = delete; JSONObjectFactory(const JSONObjectFactory&) = delete; JSONObjectFactory& operator= (const JSONObjectFactory&) = delete; - JSONObjectFactory(const uint32_t number) : Core::ProxyPoolType(number) + JSONObjectFactory(const uint32_t number) : ::Thunder::Core::ProxyPoolType(number) { } @@ -116,23 +117,23 @@ namespace Tests { } public: - Core::ProxyType Element(const string&) + ::Thunder::Core::ProxyType<::Thunder::Core::JSON::IElement> Element(const string&) { - return (Core::ProxyType(Core::ProxyPoolType::Element())); + return (::Thunder::Core::ProxyType<::Thunder::Core::JSON::IElement>(::Thunder::Core::ProxyPoolType::Element())); } }; template - class JSONConnector : public Core::StreamJSONType { + class JSONConnector : public ::Thunder::Core::StreamJSONType<::Thunder::Core::SocketStream, JSONObjectFactory&, INTERFACE> { private: - typedef Core::StreamJSONType BaseClass; + typedef ::Thunder::Core::StreamJSONType<::Thunder::Core::SocketStream, JSONObjectFactory&, INTERFACE> BaseClass; public: JSONConnector() = delete; JSONConnector(const JSONConnector& copy) = delete; JSONConnector& operator=(const JSONConnector&) = delete; - JSONConnector(const Core::NodeId& remoteNode) + JSONConnector(const ::Thunder::Core::NodeId& remoteNode) : BaseClass(5, _objectFactory, false, remoteNode.AnyInterface(), remoteNode, 1024, 1024) , _serverSocket(false) , _dataPending(false, false) @@ -140,7 +141,7 @@ namespace Tests { { } - JSONConnector(const SOCKET& connector, const Core::NodeId& remoteId, Core::SocketServerType>*) + JSONConnector(const SOCKET& connector, const ::Thunder::Core::NodeId& remoteId, ::Thunder::Core::SocketServerType>*) : BaseClass(5, _objectFactory, false, connector, remoteId, 1024, 1024) , _serverSocket(true) , _dataPending(false, false) @@ -153,7 +154,7 @@ namespace Tests { } public: - virtual void Received(Core::ProxyType& newElement) + virtual void Received(::Thunder::Core::ProxyType<::Thunder::Core::JSON::IElement>& newElement) { string textElement; newElement->ToString(textElement); @@ -166,7 +167,7 @@ namespace Tests { } } - virtual void Send(Core::ProxyType& newElement) + virtual void Send(::Thunder::Core::ProxyType<::Thunder::Core::JSON::IElement>& newElement) { } @@ -205,7 +206,7 @@ namespace Tests { private: bool _serverSocket; string _dataReceived; - mutable Core::Event _dataPending; + mutable ::Thunder::Core::Event _dataPending; JSONObjectFactory _objectFactory; static bool _done; @@ -225,12 +226,12 @@ namespace Tests { { std::string connector = "/tmp/wpestreamjson0"; auto lambdaFunc = [connector](IPTestAdministrator & testAdmin) { - Core::SocketServerType> jsonSocketServer(Core::NodeId(connector.c_str())); - jsonSocketServer.Open(Core::infinite); + ::Thunder::Core::SocketServerType> jsonSocketServer(::Thunder::Core::NodeId(connector.c_str())); + jsonSocketServer.Open(::Thunder::Core::infinite); testAdmin.Sync("setup server"); - std::unique_lock lk(JSONConnector::_mutex); - while (!JSONConnector::GetState()) { - JSONConnector::_cv.wait(lk); + std::unique_lock lk(JSONConnector<::Thunder::Core::JSON::IElement>::_mutex); + while (!JSONConnector<::Thunder::Core::JSON::IElement>::GetState()) { + JSONConnector<::Thunder::Core::JSON::IElement>::_cv.wait(lk); } testAdmin.Sync("client open"); @@ -244,34 +245,35 @@ namespace Tests { IPTestAdministrator testAdmin(otherSide); testAdmin.Sync("setup server"); { - Core::ProxyType sendObject = Core::ProxyType::Create(); + ::Thunder::Core::ProxyType sendObject = ::Thunder::Core::ProxyType::Create(); sendObject->Identifier = 1; sendObject->Name = _T("TestCase"); sendObject->Params.Duration = 100; std::string sendString; sendObject->ToString(sendString); - JSONConnector jsonSocketClient(Core::NodeId(connector.c_str())); - jsonSocketClient.Open(Core::infinite); + JSONConnector<::Thunder::Core::JSON::IElement> jsonSocketClient(::Thunder::Core::NodeId(connector.c_str())); + jsonSocketClient.Open(::Thunder::Core::infinite); testAdmin.Sync("client open"); - jsonSocketClient.Submit(Core::ProxyType(sendObject)); + jsonSocketClient.Submit(::Thunder::Core::ProxyType<::Thunder::Core::JSON::IElement>(sendObject)); jsonSocketClient.Wait(); string received; jsonSocketClient.Retrieve(received); EXPECT_STREQ(sendString.c_str(), received.c_str()); - jsonSocketClient.Close(Core::infinite); + jsonSocketClient.Close(::Thunder::Core::infinite); testAdmin.Sync("client done"); } - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } +} // Core } // Tests -ENUM_CONVERSION_BEGIN(Tests::CommandType) - { Tests::CommandType::EXECUTESHELL, _TXT("ExecuteShell") }, - { Tests::CommandType::WIFISETTINGS, _TXT("WiFiSettings") }, - { Tests::CommandType::FANCONTROL, _TXT("FanControl") }, - { Tests::CommandType::PLAYERCONTROL, _TXT("PlayerControl") }, -ENUM_CONVERSION_END(Tests::CommandType) +ENUM_CONVERSION_BEGIN(Tests::Core::CommandTypeSocketStreamJSON) + { Tests::Core::CommandTypeSocketStreamJSON::EXECUTESHELL, _TXT("ExecuteShell") }, + { Tests::Core::CommandTypeSocketStreamJSON::WIFISETTINGS, _TXT("WiFiSettings") }, + { Tests::Core::CommandTypeSocketStreamJSON::FANCONTROL, _TXT("FanControl") }, + { Tests::Core::CommandTypeSocketStreamJSON::PLAYERCONTROL, _TXT("PlayerControl") }, +ENUM_CONVERSION_END(Tests::Core::CommandTypeSocketStreamJSON) } // Thunder diff --git a/Tests/unit/core/test_socketstreamtext.cpp b/Tests/unit/core/test_socketstreamtext.cpp index 6a613e8768..59fe3ed647 100644 --- a/Tests/unit/core/test_socketstreamtext.cpp +++ b/Tests/unit/core/test_socketstreamtext.cpp @@ -32,24 +32,25 @@ namespace Thunder { namespace Tests { +namespace Core { - class TextConnector : public Core::StreamTextType { + class TextConnector : public ::Thunder::Core::StreamTextType<::Thunder::Core::SocketStream, ::Thunder::Core::TerminatorCarriageReturn> { private: - typedef Core::StreamTextType BaseClass; + typedef ::Thunder::Core::StreamTextType<::Thunder::Core::SocketStream, ::Thunder::Core::TerminatorCarriageReturn> BaseClass; public: TextConnector() = delete; TextConnector(const TextConnector& copy) = delete; TextConnector& operator=(const TextConnector&) = delete; - TextConnector(const Thunder::Core::NodeId& remoteNode) + TextConnector(const ::Thunder::Core::NodeId& remoteNode) : BaseClass(false, remoteNode.AnyInterface(), remoteNode, 1024, 1024) , _serverSocket(false) , _dataPending(false, false) { } - TextConnector(const SOCKET& connector, const Core::NodeId& remoteId, Core::SocketServerType*) + TextConnector(const SOCKET& connector, const ::Thunder::Core::NodeId& remoteId, ::Thunder::Core::SocketServerType*) : BaseClass(false, connector, remoteId, 1024, 1024) , _serverSocket(true) , _dataPending(false, false) @@ -105,7 +106,7 @@ namespace Tests { private: bool _serverSocket; string _dataReceived; - mutable Thunder::Core::Event _dataPending; + mutable ::Thunder::Core::Event _dataPending; static bool _done; public: @@ -122,8 +123,8 @@ namespace Tests { std::string connector {"/tmp/wpestreamtext0"}; auto lambdaFunc = [connector](IPTestAdministrator & testAdmin) { - Core::SocketServerType textSocketServer(Core::NodeId(connector.c_str())); - textSocketServer.Open(Core::infinite); + ::Thunder::Core::SocketServerType textSocketServer(::Thunder::Core::NodeId(connector.c_str())); + textSocketServer.Open(::Thunder::Core::infinite); testAdmin.Sync("setup server"); std::unique_lock lk(TextConnector::_mutex); while (!TextConnector::GetState()) { @@ -140,8 +141,8 @@ namespace Tests { IPTestAdministrator testAdmin(otherSide); testAdmin.Sync("setup server"); { - TextConnector textSocketClient(Core::NodeId(connector.c_str())); - textSocketClient.Open(Core::infinite); + TextConnector textSocketClient(::Thunder::Core::NodeId(connector.c_str())); + textSocketClient.Open(::Thunder::Core::infinite); testAdmin.Sync("server open"); string message = "hello"; textSocketClient.Submit(message); @@ -149,10 +150,12 @@ namespace Tests { string received; textSocketClient.Retrieve(received); EXPECT_STREQ(message.c_str(), received.c_str()); - textSocketClient.Close(Core::infinite); + textSocketClient.Close(::Thunder::Core::infinite); testAdmin.Sync("client done"); } - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } + +} // Core } // Tests } // Thunder diff --git a/Tests/unit/core/test_statetrigger.cpp b/Tests/unit/core/test_statetrigger.cpp index 48d514df3e..4af677decf 100644 --- a/Tests/unit/core/test_statetrigger.cpp +++ b/Tests/unit/core/test_statetrigger.cpp @@ -25,34 +25,42 @@ #include -using namespace Thunder; -using namespace Thunder::Core; +namespace Thunder { +namespace Tests { +namespace Core { -enum class TestState { - TEST_INIT = 0x00, - TEST_MESSAGE = 0x01, - TEST_READY = 0x02, - TEST_ERROR = 0x03 -}; + + -TEST(test_statetrigger, simple_statetrigger) -{ - Thunder::Core::StateTrigger state(TestState::TEST_READY); + enum class TestState { + TEST_INIT = 0x00, + TEST_MESSAGE = 0x01, + TEST_READY = 0x02, + TEST_ERROR = 0x03 + }; - EXPECT_EQ(state.GetState(),TestState::TEST_READY) << "State not equal to TEST_READY."; - state.SetState(TestState::TEST_MESSAGE); - EXPECT_NE(state.GetState(),TestState::TEST_READY) << "State is TEST_MESSAGE."; - EXPECT_TRUE(state.GetState() == TestState::TEST_MESSAGE) << "State is not TEST_MESSAGE"; - EXPECT_FALSE(state.GetState() != TestState::TEST_MESSAGE) << "State is TEST_MESSAGE"; - state = TestState::TEST_READY; + TEST(test_statetrigger, simple_statetrigger) + { + ::Thunder::Core::StateTrigger state(TestState::TEST_READY); - uint64_t timeOut(Core::Time::Now().Add(5).Ticks()); - uint64_t now(Core::Time::Now().Ticks()); + EXPECT_EQ(state.GetState(),TestState::TEST_READY) << "State not equal to TEST_READY."; + state.SetState(TestState::TEST_MESSAGE); + EXPECT_NE(state.GetState(),TestState::TEST_READY) << "State is TEST_MESSAGE."; + EXPECT_TRUE(state.GetState() == TestState::TEST_MESSAGE) << "State is not TEST_MESSAGE"; + EXPECT_FALSE(state.GetState() != TestState::TEST_MESSAGE) << "State is TEST_MESSAGE"; + state = TestState::TEST_READY; - state.WaitState(static_cast(TestState::TEST_INIT),static_cast((timeOut - now) / Core::Time::TicksPerMillisecond)); + uint64_t timeOut(::Thunder::Core::Time::Now().Add(5).Ticks()); + uint64_t now(::Thunder::Core::Time::Now().Ticks()); - timeOut = Core::Time::Now().Add(3).Ticks(); - now = Core::Time::Now().Ticks(); + state.WaitState(static_cast(TestState::TEST_INIT),static_cast((timeOut - now) / ::Thunder::Core::Time::TicksPerMillisecond)); - state.WaitStateClear(static_cast(TestState::TEST_READY),static_cast((timeOut - now) / Core::Time::TicksPerMillisecond)); -} + timeOut = ::Thunder::Core::Time::Now().Add(3).Ticks(); + now = ::Thunder::Core::Time::Now().Ticks(); + + state.WaitStateClear(static_cast(TestState::TEST_READY),static_cast((timeOut - now) / ::Thunder::Core::Time::TicksPerMillisecond)); + } + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_stopwatch.cpp b/Tests/unit/core/test_stopwatch.cpp index 97b11a5081..a8d5d0467f 100644 --- a/Tests/unit/core/test_stopwatch.cpp +++ b/Tests/unit/core/test_stopwatch.cpp @@ -25,68 +25,73 @@ #include -using namespace Thunder; -using namespace Thunder::Core; +namespace Thunder { +namespace Tests { +namespace Core { -TEST(test_stopWatch, Elapsed_WithoutDelay) -{ - StopWatch stopWatch1, stopWatch2; - uint64_t elapsed1 = stopWatch1.Elapsed(); - uint64_t elapsed2 = stopWatch2.Elapsed(); - EXPECT_EQ(elapsed1 /Time::MilliSecondsPerSecond, elapsed2 / Time::MilliSecondsPerSecond); -} -TEST(test_stopWatch, Elapsed_WithDelay) -{ - int8_t wait = 1; - StopWatch stopWatch1, stopWatch2; - uint64_t elapsed1 = stopWatch1.Elapsed(); - EXPECT_EQ(stopWatch1.Elapsed() / Time::MicroSecondsPerSecond, (stopWatch1.Elapsed() / Time::MicroSecondsPerSecond)); - sleep(wait); - uint64_t elapsed2 = stopWatch2.Elapsed(); - uint64_t elapsed3 = stopWatch1.Elapsed(); - EXPECT_EQ(elapsed2 / Time::MicroSecondsPerSecond, (elapsed1 / Time::MicroSecondsPerSecond) + wait); - EXPECT_EQ(elapsed3 / Time::MicroSecondsPerSecond, (elapsed1 / Time::MicroSecondsPerSecond) + wait); - EXPECT_EQ(elapsed3 / Time::MicroSecondsPerSecond, (elapsed2 / Time::MicroSecondsPerSecond)); -} -TEST(test_stopWatch, Reset_WithoutDelay) -{ - StopWatch stopWatch1, stopWatch2; - uint64_t elapsed1 = stopWatch1.Elapsed(); - uint64_t reset1 = stopWatch1.Reset(); - uint64_t elapsed2 = stopWatch2.Elapsed(); - uint64_t reset2 = stopWatch2.Reset(); + TEST(test_stopWatch, Elapsed_WithoutDelay) + { + ::Thunder::Core::StopWatch stopWatch1, stopWatch2; + uint64_t elapsed1 = stopWatch1.Elapsed(); + uint64_t elapsed2 = stopWatch2.Elapsed(); + EXPECT_EQ(elapsed1 / ::Thunder::Core::Time::MilliSecondsPerSecond, elapsed2 / ::Thunder::Core::Time::MilliSecondsPerSecond); + } + TEST(test_stopWatch, Elapsed_WithDelay) + { + int8_t wait = 1; + ::Thunder::Core::StopWatch stopWatch1, stopWatch2; + uint64_t elapsed1 = stopWatch1.Elapsed(); + EXPECT_EQ(stopWatch1.Elapsed() / ::Thunder::Core::Time::MicroSecondsPerSecond, (stopWatch1.Elapsed() / ::Thunder::Core::Time::MicroSecondsPerSecond)); + sleep(wait); + uint64_t elapsed2 = stopWatch2.Elapsed(); + uint64_t elapsed3 = stopWatch1.Elapsed(); + EXPECT_EQ(elapsed2 / ::Thunder::Core::Time::MicroSecondsPerSecond, (elapsed1 / ::Thunder::Core::Time::MicroSecondsPerSecond) + wait); + EXPECT_EQ(elapsed3 / ::Thunder::Core::Time::MicroSecondsPerSecond, (elapsed1 / ::Thunder::Core::Time::MicroSecondsPerSecond) + wait); + EXPECT_EQ(elapsed3 / ::Thunder::Core::Time::MicroSecondsPerSecond, (elapsed2 / ::Thunder::Core::Time::MicroSecondsPerSecond)); + } + TEST(test_stopWatch, Reset_WithoutDelay) + { + ::Thunder::Core::StopWatch stopWatch1, stopWatch2; + uint64_t elapsed1 = stopWatch1.Elapsed(); + uint64_t reset1 = stopWatch1.Reset(); + uint64_t elapsed2 = stopWatch2.Elapsed(); + uint64_t reset2 = stopWatch2.Reset(); - // Microsecond comparison is not doing - // instead simply checking reset is a value after elapsed one - EXPECT_LE(elapsed1, reset1); - EXPECT_LE(elapsed2, reset2); + // Microsecond comparison is not doing + // instead simply checking reset is a value after elapsed one + EXPECT_LE(elapsed1, reset1); + EXPECT_LE(elapsed2, reset2); - elapsed1 = stopWatch1.Elapsed(); - elapsed2 = stopWatch2.Elapsed(); + elapsed1 = stopWatch1.Elapsed(); + elapsed2 = stopWatch2.Elapsed(); - // Microsecond comparison is not doing - // instead simply checking converting to millisecond - EXPECT_EQ(elapsed1 / Time::MilliSecondsPerSecond, reset1 / Time::MilliSecondsPerSecond); - EXPECT_EQ(elapsed2 / Time::MilliSecondsPerSecond, reset2 / Time::MilliSecondsPerSecond); -} -TEST(test_stopWatch, Reset_WithDelay) -{ - int8_t wait = 1; - StopWatch stopWatch1, stopWatch2; - uint64_t elapsed1 = stopWatch1.Elapsed(); - uint64_t elapsed2 = stopWatch2.Elapsed(); - sleep(wait); - uint64_t reset1 = stopWatch1.Reset(); - uint64_t reset2 = stopWatch2.Reset(); + // Microsecond comparison is not doing + // instead simply checking converting to millisecond + EXPECT_EQ(elapsed1 / ::Thunder::Core::Time::MilliSecondsPerSecond, reset1 / ::Thunder::Core::Time::MilliSecondsPerSecond); + EXPECT_EQ(elapsed2 / ::Thunder::Core::Time::MilliSecondsPerSecond, reset2 / ::Thunder::Core::Time::MilliSecondsPerSecond); + } + TEST(test_stopWatch, Reset_WithDelay) + { + int8_t wait = 1; + ::Thunder::Core::StopWatch stopWatch1, stopWatch2; + uint64_t elapsed1 = stopWatch1.Elapsed(); + uint64_t elapsed2 = stopWatch2.Elapsed(); + sleep(wait); + uint64_t reset1 = stopWatch1.Reset(); + uint64_t reset2 = stopWatch2.Reset(); - EXPECT_EQ(reset1 / Time::MicroSecondsPerSecond, (elapsed1 / Time::MicroSecondsPerSecond) + wait); - EXPECT_EQ(reset2 / Time::MicroSecondsPerSecond, (elapsed2 / Time::MicroSecondsPerSecond) + wait); + EXPECT_EQ(reset1 / ::Thunder::Core::Time::MicroSecondsPerSecond, (elapsed1 / ::Thunder::Core::Time::MicroSecondsPerSecond) + wait); + EXPECT_EQ(reset2 / ::Thunder::Core::Time::MicroSecondsPerSecond, (elapsed2 / ::Thunder::Core::Time::MicroSecondsPerSecond) + wait); - sleep(wait); - elapsed1 = stopWatch1.Elapsed(); - sleep(wait); - elapsed2 = stopWatch2.Elapsed(); + sleep(wait); + elapsed1 = stopWatch1.Elapsed(); + sleep(wait); + elapsed2 = stopWatch2.Elapsed(); - EXPECT_EQ(elapsed1 / Time::MicroSecondsPerSecond, (reset1 / Time::MicroSecondsPerSecond)); - EXPECT_EQ(elapsed2 / Time::MicroSecondsPerSecond, (reset2 / Time::MicroSecondsPerSecond) + wait); -} + EXPECT_EQ(elapsed1 / ::Thunder::Core::Time::MicroSecondsPerSecond, (reset1 / ::Thunder::Core::Time::MicroSecondsPerSecond)); + EXPECT_EQ(elapsed2 / ::Thunder::Core::Time::MicroSecondsPerSecond, (reset2 / ::Thunder::Core::Time::MicroSecondsPerSecond) + wait); + } + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_synchronize.cpp b/Tests/unit/core/test_synchronize.cpp index 8fcec033f6..05ef2c9785 100644 --- a/Tests/unit/core/test_synchronize.cpp +++ b/Tests/unit/core/test_synchronize.cpp @@ -25,54 +25,59 @@ #include -using namespace Thunder; -using namespace Thunder::Core; +namespace Thunder { +namespace Tests { +namespace Core { -class SynchronizeClass { -public: - SynchronizeClass() - : _msg("") - { - } + class SynchronizeClass { + public: + SynchronizeClass() + : _msg("") + { + } - ~SynchronizeClass() - { - } + ~SynchronizeClass() + { + } -public: - bool Copy(const string message) - { - bool result = false; - _msg = message; - if (!_msg.empty()) - result = true; - return result; - } + public: + bool Copy(const string message) + { + bool result = false; + _msg = message; + if (!_msg.empty()) + result = true; + return result; + } + + private: + string _msg; + }; -private: - string _msg; -}; + TEST(test_synchronize, synchronize_test) + { + string MESSAGE = "SynchronizeType request"; + SynchronizeClass syncObject1; + ::Thunder::Core::SynchronizeType syncObject2; + ::Thunder::Core::SynchronizeType syncObject3; -TEST(test_synchronize, synchronize_test) -{ - string MESSAGE = "SynchronizeType request"; - SynchronizeClass syncObject1; - SynchronizeType syncObject2; - SynchronizeType syncObject3; + syncObject2.Load(); + syncObject2.Evaluate(); - syncObject2.Load(); - syncObject2.Evaluate(); + syncObject3.Load(syncObject1); + EXPECT_EQ(syncObject3.Acquire(unsigned(5)), unsigned(11)); + syncObject3.Load(syncObject1); + EXPECT_TRUE(syncObject3.Evaluate(MESSAGE)); - syncObject3.Load(syncObject1); - EXPECT_EQ(syncObject3.Acquire(unsigned(5)), unsigned(11)); - syncObject3.Load(syncObject1); - EXPECT_TRUE(syncObject3.Evaluate(MESSAGE)); + syncObject2.Lock(); + syncObject2.Flush(); + syncObject2.Unlock(); - syncObject2.Lock(); - syncObject2.Flush(); - syncObject2.Unlock(); + syncObject3.Lock(); + syncObject3.Flush(); + syncObject3.Unlock(); + } - syncObject3.Lock(); - syncObject3.Flush(); - syncObject3.Unlock(); -} +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_synchronous.cpp b/Tests/unit/core/test_synchronous.cpp index 700aab9aa7..608afd198f 100644 --- a/Tests/unit/core/test_synchronous.cpp +++ b/Tests/unit/core/test_synchronous.cpp @@ -27,158 +27,172 @@ #include "../IPTestAdministrator.h" -using namespace Thunder; -using namespace Thunder::Core; - -namespace { - const string localhost = "127.0.0.1"; - const uint16_t portNumber = 9749; - const uint16_t bufferSize = 1024; -} - -class Message : public Core::IOutbound { -protected: - Message(uint8_t buffer[]) - : _buffer(buffer) - { +namespace Thunder { +namespace Tests { +namespace Core { + + namespace { + const string localhost = "127.0.0.1"; + const uint16_t portNumber = 9749; + const uint16_t bufferSize = 1024; } -public: - Message() = delete; - Message(const Message&) = delete; - Message& operator=(const Message&) = delete; + class Message : public ::Thunder::Core::IOutbound { + protected: + Message(uint8_t buffer[]) + : _buffer(buffer) + { + } - Message(const uint16_t size, uint8_t buffer[]) - : _size(size) - , _buffer(buffer) - , _offset(0) - { - } + public: + Message() = delete; + Message(const Message&) = delete; + Message& operator=(const Message&) = delete; - virtual ~Message() - { - } - -private: - virtual void Reload() const override - { - _offset = 0; - } + Message(const uint16_t size, uint8_t buffer[]) + : _size(size) + , _buffer(buffer) + , _offset(0) + { + } - virtual uint16_t Serialize(uint8_t stream[], const uint16_t length) const override - { - uint16_t result = std::min(static_cast(sizeof(_buffer) - _offset), length); - if (result > 0) { + virtual ~Message() + { + } - ::memcpy(stream, &(_buffer[_offset]), result); - _offset += result; + private: + virtual void Reload() const override + { + _offset = 0; } - return (result); - } -private: - uint16_t _size; - uint8_t* _buffer; - mutable uint16_t _offset; -}; + virtual uint16_t Serialize(uint8_t stream[], const uint16_t length) const override + { + uint16_t result = std::min(static_cast(sizeof(_buffer) - _offset), length); + if (result > 0) { -class InMessage : public Core::IInbound { -protected: - InMessage(uint8_t buffer[]) - : _buffer(buffer) - { - } + ::memcpy(stream, &(_buffer[_offset]), result); + _offset += result; + } + return (result); + } -public: - InMessage(const InMessage&) = delete; - InMessage& operator=(const InMessage&) = delete; + private: + uint16_t _size; + uint8_t* _buffer; + mutable uint16_t _offset; + }; - InMessage() - : _buffer() - , _error(~0) - , _offset(0) - { - } + class InMessage : public ::Thunder::Core::IInbound { + protected: + InMessage(uint8_t buffer[]) + : _buffer(buffer) + { + } - virtual ~InMessage() - { - } + public: + InMessage(const InMessage&) = delete; + InMessage& operator=(const InMessage&) = delete; -private: - virtual uint16_t Deserialize(const uint8_t stream[], const uint16_t length) override - { - uint16_t result = 0; - uint16_t toCopy = std::min(static_cast(sizeof(_buffer)-_offset), length); - ::memcpy(reinterpret_cast(&stream), &(_buffer[_offset]), toCopy); + InMessage() + : _buffer() + , _error(~0) + , _offset(0) + { + } - _error = Core::ERROR_NONE; - result = length; - return (result); - } + virtual ~InMessage() + { + } - virtual state IsCompleted() const override - { - return (_error != static_cast(~0) ? state::COMPLETED : state::INPROGRESS); - } + private: + virtual uint16_t Deserialize(const uint8_t stream[], const uint16_t length) override + { + uint16_t result = 0; + uint16_t toCopy = std::min(static_cast(sizeof(_buffer)-_offset), length); + ::memcpy(reinterpret_cast(&stream), &(_buffer[_offset]), toCopy); -private: - uint8_t* _buffer; - mutable uint16_t _error; - mutable uint16_t _offset; -}; + _error = ::Thunder::Core::ERROR_NONE; + result = length; + return (result); + } -class SynchronousSocket : public Core::SynchronousChannelType { -public: - SynchronousSocket(const SynchronousSocket&) = delete; - SynchronousSocket& operator=(const SynchronousSocket&) = delete; - SynchronousSocket() = delete; + virtual state IsCompleted() const override + { + return (_error != static_cast(~0) ? state::COMPLETED : state::INPROGRESS); + } - SynchronousSocket(bool listening) - :SynchronousChannelType((listening ? SocketPort::LISTEN : SocketPort::STREAM),listening ?Core::NodeId(_T(localhost.c_str()),(portNumber),Core::NodeId::TYPE_IPV4):Core::NodeId(_T(localhost.c_str()),(portNumber),Core::NodeId::TYPE_DOMAIN),listening ?Core::NodeId(_T(localhost.c_str()),(portNumber),Core::NodeId::TYPE_DOMAIN):Core::NodeId(_T(localhost.c_str()),(portNumber),Core::NodeId::TYPE_IPV4), bufferSize, bufferSize) - { - EXPECT_FALSE(Core::SynchronousChannelType::Open(Core::infinite) != Core::ERROR_NONE); - } + private: + uint8_t* _buffer; + mutable uint16_t _error; + mutable uint16_t _offset; + }; - virtual ~SynchronousSocket() - { - Core::SynchronousChannelType::Close(Core::infinite); - } + class SynchronousSocket : public ::Thunder::Core::SynchronousChannelType<::Thunder::Core::SocketPort> { + public: + SynchronousSocket(const SynchronousSocket&) = delete; + SynchronousSocket& operator=(const SynchronousSocket&) = delete; + SynchronousSocket() = delete; + + SynchronousSocket(bool listening) + : SynchronousChannelType<::Thunder::Core::SocketPort>( + (listening ? ::Thunder::Core::SocketPort::LISTEN : ::Thunder::Core::SocketPort::STREAM) + , (listening ? ::Thunder::Core::NodeId(_T(localhost.c_str()), (portNumber), ::Thunder::Core::NodeId::TYPE_IPV4) + : ::Thunder::Core::NodeId(_T(localhost.c_str()), (portNumber), ::Thunder::Core::NodeId::TYPE_DOMAIN) + ) + , (listening ? ::Thunder::Core::NodeId(_T(localhost.c_str()), (portNumber), ::Thunder::Core::NodeId::TYPE_DOMAIN) + : ::Thunder::Core::NodeId(_T(localhost.c_str()), (portNumber), ::Thunder::Core::NodeId::TYPE_IPV4) + ) + , bufferSize, bufferSize + ) + { + EXPECT_FALSE(::Thunder::Core::SynchronousChannelType<::Thunder::Core::SocketPort>::Open(::Thunder::Core::infinite) != ::Thunder::Core::ERROR_NONE); + } - virtual uint16_t Deserialize(const uint8_t* dataFrame, const uint16_t availableData) - { - return 1; - } -}; - -TEST(test_synchronous, simple_synchronous) -{ - IPTestAdministrator::OtherSideMain otherSide = [](IPTestAdministrator& testAdmin) { - SynchronousSocket synchronousServerSocket(true); - testAdmin.Sync("setup server"); - - testAdmin.Sync("connect client"); - testAdmin.Sync("client msg"); - testAdmin.Sync("client newmsg"); - testAdmin.Sync("client revokemsg"); + virtual ~SynchronousSocket() + { + ::Thunder::Core::SynchronousChannelType<::Thunder::Core::SocketPort>::Close(::Thunder::Core::infinite); + } + + virtual uint16_t Deserialize(const uint8_t* dataFrame, const uint16_t availableData) + { + return 1; + } }; - IPTestAdministrator testAdmin(otherSide); + TEST(test_synchronous, simple_synchronous) { - testAdmin.Sync("setup server"); - SynchronousSocket synchronousClientSocket(false); - - testAdmin.Sync("connect client"); - uint8_t buffer[] = "Hello"; - Message message(5,buffer); - EXPECT_EQ(synchronousClientSocket.Exchange(500, message),0u); - testAdmin.Sync("client msg"); - - InMessage response; - Message newmessage(5,buffer); - synchronousClientSocket.Exchange(500, newmessage, response);//TODO Output verification is pending. - testAdmin.Sync("client newmsg"); - synchronousClientSocket.Revoke(message); - testAdmin.Sync("client revokemsg"); + IPTestAdministrator::OtherSideMain otherSide = [](IPTestAdministrator& testAdmin) { + SynchronousSocket synchronousServerSocket(true); + testAdmin.Sync("setup server"); + + testAdmin.Sync("connect client"); + testAdmin.Sync("client msg"); + testAdmin.Sync("client newmsg"); + testAdmin.Sync("client revokemsg"); + }; + + IPTestAdministrator testAdmin(otherSide); + { + testAdmin.Sync("setup server"); + SynchronousSocket synchronousClientSocket(false); + + testAdmin.Sync("connect client"); + uint8_t buffer[] = "Hello"; + Message message(5,buffer); + EXPECT_EQ(synchronousClientSocket.Exchange(500, message),0u); + testAdmin.Sync("client msg"); + + InMessage response; + Message newmessage(5,buffer); + synchronousClientSocket.Exchange(500, newmessage, response);//TODO Output verification is pending. + testAdmin.Sync("client newmsg"); + synchronousClientSocket.Revoke(message); + testAdmin.Sync("client revokemsg"); + } + ::Thunder::Core::Singleton::Dispose(); } - Core::Singleton::Dispose(); -} + +} // Core +} // Tests +} // Thunder \ No newline at end of file diff --git a/Tests/unit/core/test_systeminfo.cpp b/Tests/unit/core/test_systeminfo.cpp index b1784f72db..4904549076 100644 --- a/Tests/unit/core/test_systeminfo.cpp +++ b/Tests/unit/core/test_systeminfo.cpp @@ -33,548 +33,549 @@ namespace Thunder { namespace Tests { - -enum class Purpose { - MEM, - SWAP, - HOST, - CHIPSET, - CPULOAD, -}; - -enum class Function { - TOTAL, - FREE, - AVAILABLE, - CACHED, - NONE -}; - -inline uint32_t PlaceValue(uint8_t places) { - uint32_t placeValue = 1; - for (uint8_t i = 0; i < places; ++i) { - placeValue *= 10; +namespace Core { + + enum class Purpose { + MEM, + SWAP, + HOST, + CHIPSET, + CPULOAD, + }; + + enum class Function { + TOTAL, + FREE, + AVAILABLE, + CACHED, + NONE + }; + + inline uint32_t PlaceValue(uint8_t places) { + uint32_t placeValue = 1; + for (uint8_t i = 0; i < places; ++i) { + placeValue *= 10; + } + return placeValue; } - return placeValue; -} -double Round(double value, uint8_t places) { - uint32_t placeValue = PlaceValue(places); - value = (value + 0.005) * placeValue; - value = (double)((int) value); - value = value / placeValue; - return value; -} + double Round(double value, uint8_t places) { + uint32_t placeValue = PlaceValue(places); + value = (value + 0.005) * placeValue; + value = (double)((int) value); + value = value / placeValue; + return value; + } #ifdef __POSIX__ -std::string Architecture() -{ - std::string architecture; - struct utsname buf; - if (uname(&buf) == 0) { - architecture = buf.machine; - } - return architecture; -} - -std::string FirmwareVersion() -{ - std::string release; - struct utsname buf; - if (uname(&buf) == 0) { - release = buf.release; + std::string Architecture() + { + std::string architecture; + struct utsname buf; + if (uname(&buf) == 0) { + architecture = buf.machine; + } + return architecture; } - return release; -} - -std::string GetChipset(std::string result) -{ - std::string chipset; - std::stringstream iss(result); - while (getline(iss, result, '\n')) + std::string FirmwareVersion() { - if (result.find("model name") != std::string::npos) { - std::size_t position = result.find(':'); - if (position != std::string::npos) { - chipset.assign(result.substr(result.find_first_not_of(" ", position + 1))); - break; - } + std::string release; + struct utsname buf; + if (uname(&buf) == 0) { + release = buf.release; } + return release; } - return chipset; -} -std::string GetCPUJiffies(std::string result) -{ - int i = 0; - std::stringstream iss(result); - - uint64_t jiffies = 0; - size_t* endPtr = nullptr; - iss >> result; // Skip first word - while (iss >> result) + + std::string GetChipset(std::string result) { - if (result.empty() != true) { - uint64_t value = stol(result, endPtr); - if (endPtr == nullptr) { - jiffies += value; // FIXME: cross check do we need to use all fields to get jiffies or not - // https://titanwolf.org/Network/Articles/Article?AID=3d8450d1-470b-4533-bb5a-c46ded0215bb + std::string chipset; + std::stringstream iss(result); + + while (getline(iss, result, '\n')) + { + if (result.find("model name") != std::string::npos) { + std::size_t position = result.find(':'); + if (position != std::string::npos) { + chipset.assign(result.substr(result.find_first_not_of(" ", position + 1))); + break; + } } } - i++; + return chipset; } + std::string GetCPUJiffies(std::string result) + { + int i = 0; + std::stringstream iss(result); + + uint64_t jiffies = 0; + size_t* endPtr = nullptr; + iss >> result; // Skip first word + while (iss >> result) + { + if (result.empty() != true) { + uint64_t value = stol(result, endPtr); + if (endPtr == nullptr) { + jiffies += value; // FIXME: cross check do we need to use all fields to get jiffies or not + // https://titanwolf.org/Network/Articles/Article?AID=3d8450d1-470b-4533-bb5a-c46ded0215bb + } + } + i++; + } - return std::to_string(jiffies); - -} -std::string GetCPULoad(std::string result) -{ - int i = 0; - std::stringstream iss(result); - - std::vector usageData; - size_t* endPtr = nullptr; + return std::to_string(jiffies); - while (iss >> result) + } + std::string GetCPULoad(std::string result) { - if ((i % 2) == 1) { - float value = stof(result, endPtr); - if (endPtr == nullptr) { - usageData.push_back(value); + int i = 0; + std::stringstream iss(result); + + std::vector usageData; + size_t* endPtr = nullptr; + + while (iss >> result) + { + if ((i % 2) == 1) { + float value = stof(result, endPtr); + if (endPtr == nullptr) { + usageData.push_back(value); + } } + i++; } - i++; - } - float nonIdle = 0, idle = 0; - for (uint8_t index = 0; index < usageData.size(); ++index) { - if ((index == 3) || (index == 4)) { - idle += usageData[index]; - } else { - nonIdle += usageData[index]; + float nonIdle = 0, idle = 0; + for (uint8_t index = 0; index < usageData.size(); ++index) { + if ((index == 3) || (index == 4)) { + idle += usageData[index]; + } else { + nonIdle += usageData[index]; + } } + // Send non decimal part + return std::to_string(static_cast(nonIdle)); } - // Send non decimal part - return std::to_string(static_cast(nonIdle)); -} -inline std::string GetMemoryValue(std::string buffer, bool found) { + inline std::string GetMemoryValue(std::string buffer, bool found) { - int i = 0; - string result; - if (found == true) { - std::stringstream iss(buffer); + int i = 0; + string result; + if (found == true) { + std::stringstream iss(buffer); - while (iss >> result) { - if (i == 1) { - break; - } + while (iss >> result) { + if (i == 1) { + break; + } - i++; + i++; + } } + return result; } - return result; -} - -std::string GetMemory(std::string result, Function func) -{ - std::string word; - - bool found = false; - if ((func == Function::TOTAL) && (result.find("MemTotal:") != std::string::npos)) { - found = true; - } else if ((func == Function::FREE) && (result.find("MemFree:") != std::string::npos)) { - found = true; - } else if ((func == Function::CACHED) && (result.find("Cached:") != std::string::npos)) { - found = true; - } else if ((func == Function::AVAILABLE) && (result.find("MemAvailable") != std::string::npos)) { - found = true; - } - - return GetMemoryValue(result, found); -} -std::string GetSwapMemory(std::string result, Function func) -{ - std::string word; + std::string GetMemory(std::string result, Function func) + { + std::string word; + + bool found = false; + if ((func == Function::TOTAL) && (result.find("MemTotal:") != std::string::npos)) { + found = true; + } else if ((func == Function::FREE) && (result.find("MemFree:") != std::string::npos)) { + found = true; + } else if ((func == Function::CACHED) && (result.find("Cached:") != std::string::npos)) { + found = true; + } else if ((func == Function::AVAILABLE) && (result.find("MemAvailable") != std::string::npos)) { + found = true; + } - bool found = false; - if ((func == Function::TOTAL) && (result.find("SwapTotal:") != std::string::npos)) { - found = true; - } else if ((func == Function::FREE) && (result.find("SwapFree:") != std::string::npos)) { - found = true; - } else if ((func == Function::CACHED) && (result.find("SwapCached:") != std::string::npos)) { - found = true; + return GetMemoryValue(result, found); } - return GetMemoryValue(result, found); -} + std::string GetSwapMemory(std::string result, Function func) + { + std::string word; + + bool found = false; + if ((func == Function::TOTAL) && (result.find("SwapTotal:") != std::string::npos)) { + found = true; + } else if ((func == Function::FREE) && (result.find("SwapFree:") != std::string::npos)) { + found = true; + } else if ((func == Function::CACHED) && (result.find("SwapCached:") != std::string::npos)) { + found = true; + } -std::string ExecuteCmd(const char* cmd, Purpose purpose, Function func) { - char buffer[128]; - std::string result = ""; - std::string word = ""; - FILE* pipe = popen(cmd, "r"); + return GetMemoryValue(result, found); + } + + std::string ExecuteCmd(const char* cmd, Purpose purpose, Function func) { + char buffer[128]; + std::string result = ""; + std::string word = ""; + FILE* pipe = popen(cmd, "r"); - EXPECT_TRUE(pipe != nullptr); + EXPECT_TRUE(pipe != nullptr); #ifdef __CORE_EXCEPTION_CATCHING__ - try { + try { #endif - while (fgets(buffer, sizeof buffer, pipe) != NULL) { - result = buffer; - if (purpose == Purpose::MEM) { - word = GetMemory(result, func); - break; - } else if (purpose == Purpose::SWAP) { - word = GetSwapMemory(result, func); - break; - } else if (purpose == Purpose::HOST) { - word.assign(result); - break; - } else if (purpose == Purpose::CHIPSET) { - if (result.find("model name") != std::string::npos) { - word = GetChipset(result); - } - break; - } else if (purpose == Purpose::CPULOAD) { - if (result.find("%Cpu(s):") != std::string::npos) { - word = GetCPULoad(result); + while (fgets(buffer, sizeof buffer, pipe) != NULL) { + result = buffer; + if (purpose == Purpose::MEM) { + word = GetMemory(result, func); + break; + } else if (purpose == Purpose::SWAP) { + word = GetSwapMemory(result, func); + break; + } else if (purpose == Purpose::HOST) { + word.assign(result); + break; + } else if (purpose == Purpose::CHIPSET) { + if (result.find("model name") != std::string::npos) { + word = GetChipset(result); + } + break; + } else if (purpose == Purpose::CPULOAD) { + if (result.find("%Cpu(s):") != std::string::npos) { + word = GetCPULoad(result); + } + break; } - break; } - } #ifdef __CORE_EXCEPTION_CATCHING__ - } catch (...) { + } catch (...) { + pclose(pipe); + throw; + } +#endif pclose(pipe); - throw; + + return word; + } + + float GetUpTime() { + std::string uptime; + std::ifstream file("/proc/uptime"); + if (file >> uptime) + return (ceil(stof(uptime))); + return 0; } #endif - pclose(pipe); - - return word; -} - -float GetUpTime() { - std::string uptime; - std::ifstream file("/proc/uptime"); - if (file >> uptime) - return (ceil(stof(uptime))); - return 0; -} -#endif -const uint8_t* RawDeviceId() -{ - static uint8_t* MACAddress = nullptr; - static uint8_t MACAddressBuffer[Core::AdapterIterator::MacSize + 1]; - - if (MACAddress == nullptr) { - memset(MACAddressBuffer, 0, Core::AdapterIterator::MacSize + 1); - - Core::AdapterIterator adapters; - while ((adapters.Next() == true)) { - if (adapters.HasMAC() == true) { - adapters.MACAddress(&MACAddressBuffer[1], Core::AdapterIterator::MacSize); - break; + const uint8_t* RawDeviceId() + { + static uint8_t* MACAddress = nullptr; + static uint8_t MACAddressBuffer[::Thunder::Core::AdapterIterator::MacSize + 1]; + + if (MACAddress == nullptr) { + memset(MACAddressBuffer, 0, ::Thunder::Core::AdapterIterator::MacSize + 1); + + ::Thunder::Core::AdapterIterator adapters; + while ((adapters.Next() == true)) { + if (adapters.HasMAC() == true) { + adapters.MACAddress(&MACAddressBuffer[1], ::Thunder::Core::AdapterIterator::MacSize); + break; + } } + MACAddressBuffer[0] = ::Thunder::Core::AdapterIterator::MacSize; + MACAddress = &MACAddressBuffer[0]; } - MACAddressBuffer[0] = Core::AdapterIterator::MacSize; - MACAddress = &MACAddressBuffer[0]; + + return MACAddress; } - return MACAddress; -} - -TEST(Core_SystemInfo, RawDeviceId) -{ - const uint8_t* rawDeviceId = RawDeviceId(); - // Simple check added, since the rawId is currently based on MAC address of first active interface - EXPECT_EQ((rawDeviceId != nullptr), true); - - // Call to dispose Network adapter instance created with RawDeviceId sequence - Core::Singleton::Dispose(); -} -TEST(Core_SystemInfo, RawDeviceId_To_ID) -{ - const uint8_t* rawDeviceId = RawDeviceId(); - string id1 (Core::SystemInfo::Instance().Id(rawDeviceId, 0xFF)); - uint8_t readPaddedSize = 0x11; - string id2 (Core::SystemInfo::Instance().Id(rawDeviceId, readPaddedSize)); - uint8_t readSize = 0xc; - string id3 (Core::SystemInfo::Instance().Id(rawDeviceId, readSize)); - - EXPECT_GE(id1.size(), static_cast(0)); - EXPECT_EQ(id2.size(), readPaddedSize); - size_t paddingStartPosition = id2.find_first_of('0', 0); - size_t paddingEndPosition = id2.find_first_not_of('0', paddingStartPosition); - EXPECT_EQ((id1.size() + (paddingEndPosition - paddingStartPosition)), id2.size()); - - EXPECT_EQ((id3.size() == readSize), true); - - // Call to dispose Network adapter instance created with RawDeviceId sequence - Core::Singleton::Dispose(); -} + TEST(Core_SystemInfo, RawDeviceId) + { + const uint8_t* rawDeviceId = RawDeviceId(); + // Simple check added, since the rawId is currently based on MAC address of first active interface + EXPECT_EQ((rawDeviceId != nullptr), true); + + // Call to dispose Network adapter instance created with RawDeviceId sequence + ::Thunder::Core::Singleton::Dispose(); + } + TEST(Core_SystemInfo, RawDeviceId_To_ID) + { + const uint8_t* rawDeviceId = RawDeviceId(); + string id1 (::Thunder::Core::SystemInfo::Instance().Id(rawDeviceId, 0xFF)); + uint8_t readPaddedSize = 0x11; + string id2 (::Thunder::Core::SystemInfo::Instance().Id(rawDeviceId, readPaddedSize)); + uint8_t readSize = 0xc; + string id3 (::Thunder::Core::SystemInfo::Instance().Id(rawDeviceId, readSize)); + + EXPECT_GE(id1.size(), static_cast(0)); + EXPECT_EQ(id2.size(), readPaddedSize); + size_t paddingStartPosition = id2.find_first_of('0', 0); + size_t paddingEndPosition = id2.find_first_not_of('0', paddingStartPosition); + EXPECT_EQ((id1.size() + (paddingEndPosition - paddingStartPosition)), id2.size()); + + EXPECT_EQ((id3.size() == readSize), true); + + // Call to dispose Network adapter instance created with RawDeviceId sequence + ::Thunder::Core::Singleton::Dispose(); + } #ifdef __POSIX__ -TEST(Core_SystemInfo, GetEnvironment_SetUsing_setenv) -{ - string env = "TEST_GETENVIRONMENT_WITH_SETENV"; - string valueSet = "HelloTest"; - ::setenv(env.c_str(), valueSet.c_str(), 1); - string valueGet; - Core::SystemInfo::GetEnvironment(env, valueGet); - EXPECT_STREQ(valueGet.c_str(), valueSet.c_str()); - ::unsetenv(env.c_str()); -} + TEST(Core_SystemInfo, GetEnvironment_SetUsing_setenv) + { + string env = "TEST_GETENVIRONMENT_WITH_SETENV"; + string valueSet = "HelloTest"; + ::setenv(env.c_str(), valueSet.c_str(), 1); + string valueGet; + ::Thunder::Core::SystemInfo::GetEnvironment(env, valueGet); + EXPECT_STREQ(valueGet.c_str(), valueSet.c_str()); + ::unsetenv(env.c_str()); + } #endif -TEST(Core_SystemInfo, GetEnvironment_SetUsing_SetEnvironment_With_ValueTypeAsString) -{ - string env = "TEST_GETENVIRONMENT_WITH_SETENVIRONMENT"; - string valueSet = "HaiTest"; - // Call forced with default value - Core::SystemInfo::SetEnvironment(env, valueSet); - string valueGet; - Core::SystemInfo::GetEnvironment(env, valueGet); - EXPECT_STREQ(valueGet.c_str(), valueSet.c_str()); - - valueSet = "ForcedTest"; - // Call forced with true - Core::SystemInfo::SetEnvironment(env, valueSet, true); - Core::SystemInfo::GetEnvironment(env, valueGet); - EXPECT_STREQ(valueGet.c_str(), valueSet.c_str()); - - valueSet = "NotForcedTest"; - // Call forced with false - Core::SystemInfo::SetEnvironment(env, valueSet, false); - Core::SystemInfo::GetEnvironment(env, valueGet); - EXPECT_STREQ(valueGet.c_str(), "ForcedTest"); + TEST(Core_SystemInfo, GetEnvironment_SetUsing_SetEnvironment_With_ValueTypeAsString) + { + string env = "TEST_GETENVIRONMENT_WITH_SETENVIRONMENT"; + string valueSet = "HaiTest"; + // Call forced with default value + ::Thunder::Core::SystemInfo::SetEnvironment(env, valueSet); + string valueGet; + ::Thunder::Core::SystemInfo::GetEnvironment(env, valueGet); + EXPECT_STREQ(valueGet.c_str(), valueSet.c_str()); + + valueSet = "ForcedTest"; + // Call forced with true + ::Thunder::Core::SystemInfo::SetEnvironment(env, valueSet, true); + ::Thunder::Core::SystemInfo::GetEnvironment(env, valueGet); + EXPECT_STREQ(valueGet.c_str(), valueSet.c_str()); + + valueSet = "NotForcedTest"; + // Call forced with false + ::Thunder::Core::SystemInfo::SetEnvironment(env, valueSet, false); + ::Thunder::Core::SystemInfo::GetEnvironment(env, valueGet); + EXPECT_STREQ(valueGet.c_str(), "ForcedTest"); #ifdef __POSIX__ - ::unsetenv(env.c_str()); - // Call forced with false after unset/clear environement variable - Core::SystemInfo::SetEnvironment(env, valueSet, false); - Core::SystemInfo::GetEnvironment(env, valueGet); - EXPECT_STREQ(valueGet.c_str(), valueSet.c_str()); - ::unsetenv(env.c_str()); + ::unsetenv(env.c_str()); + // Call forced with false after unset/clear environement variable + ::Thunder::Core::SystemInfo::SetEnvironment(env, valueSet, false); + ::Thunder::Core::SystemInfo::GetEnvironment(env, valueGet); + EXPECT_STREQ(valueGet.c_str(), valueSet.c_str()); + ::unsetenv(env.c_str()); #endif -} -TEST(Core_SystemInfo, GetEnvironment_SetUsing_SetEnvironment_WithValueTypeAsTCharPointer) -{ - string env = "TEST_GETENVIRONMENT_WITH_SETENVIRONMENT"; - TCHAR valueSet[25] = "HaiTest"; - // Call forced with default value - Core::SystemInfo::SetEnvironment(env, valueSet); - string valueGet; - Core::SystemInfo::GetEnvironment(env, valueGet); - EXPECT_STREQ(valueGet.c_str(), valueSet); - - strcpy(valueSet, "ForcedTest"); - // Call forced with true - Core::SystemInfo::SetEnvironment(env, valueSet, true); - Core::SystemInfo::GetEnvironment(env, valueGet); - EXPECT_STREQ(valueGet.c_str(), valueSet); - - strcpy(valueSet, "NotForcedTest"); - // Call forced with false - Core::SystemInfo::SetEnvironment(env, valueSet, false); - Core::SystemInfo::GetEnvironment(env, valueGet); - EXPECT_STREQ(valueGet.c_str(), "ForcedTest"); + } + TEST(Core_SystemInfo, GetEnvironment_SetUsing_SetEnvironment_WithValueTypeAsTCharPointer) + { + string env = "TEST_GETENVIRONMENT_WITH_SETENVIRONMENT"; + TCHAR valueSet[25] = "HaiTest"; + // Call forced with default value + ::Thunder::Core::SystemInfo::SetEnvironment(env, valueSet); + string valueGet; + ::Thunder::Core::SystemInfo::GetEnvironment(env, valueGet); + EXPECT_STREQ(valueGet.c_str(), valueSet); + + strcpy(valueSet, "ForcedTest"); + // Call forced with true + ::Thunder::Core::SystemInfo::SetEnvironment(env, valueSet, true); + ::Thunder::Core::SystemInfo::GetEnvironment(env, valueGet); + EXPECT_STREQ(valueGet.c_str(), valueSet); + + strcpy(valueSet, "NotForcedTest"); + // Call forced with false + ::Thunder::Core::SystemInfo::SetEnvironment(env, valueSet, false); + ::Thunder::Core::SystemInfo::GetEnvironment(env, valueGet); + EXPECT_STREQ(valueGet.c_str(), "ForcedTest"); #ifdef __POSIX__ - ::unsetenv(env.c_str()); + ::unsetenv(env.c_str()); - // Call forced with false after unset/clear environement variable - Core::SystemInfo::SetEnvironment(env, valueSet, false); - Core::SystemInfo::GetEnvironment(env, valueGet); - EXPECT_STREQ(valueGet.c_str(), valueSet); - ::unsetenv(env.c_str()); + // Call forced with false after unset/clear environement variable + ::Thunder::Core::SystemInfo::SetEnvironment(env, valueSet, false); + ::Thunder::Core::SystemInfo::GetEnvironment(env, valueGet); + EXPECT_STREQ(valueGet.c_str(), valueSet); + ::unsetenv(env.c_str()); #endif -} + } #ifdef __POSIX__ -TEST(Core_SystemInfo, HostName) -{ - std::string cmd = "hostname"; - string hostname = ExecuteCmd(cmd.c_str(), Purpose::HOST, Function::NONE).c_str(); - hostname.erase(std::remove(hostname.begin(), hostname.end(), '\n'), hostname.end()); - EXPECT_STREQ(Core::SystemInfo::Instance().GetHostName().c_str(), hostname.c_str()); -} -TEST(Core_SystemInfo, HardwareInfo) -{ - EXPECT_STREQ(Core::SystemInfo::Instance().Architecture().c_str(), Architecture().c_str()); - std::string cmd = "cat /proc/cpuinfo | grep model | grep name"; - EXPECT_STREQ(Core::SystemInfo::Instance().Chipset().c_str(), ExecuteCmd(cmd.c_str(), Purpose::CHIPSET, Function::NONE).c_str()); -} -TEST(Core_SystemInfo, FirmwareInfo) -{ - EXPECT_STREQ(Core::SystemInfo::Instance().FirmwareVersion().c_str(), FirmwareVersion().c_str()); -} - -static constexpr uint32_t MegaBytesPerBytes = 1024 * 1024; -static constexpr uint32_t MegaBytesPerKBytes = 1024; - -TEST(Core_SystemInfo, MemoryInfo) -{ - long pageSize= sysconf(_SC_PAGESIZE); - - EXPECT_NE(pageSize, -1); - EXPECT_EQ(Core::SystemInfo::Instance().GetPageSize(), static_cast(pageSize)); - - std::string cmd = "cat /proc/meminfo | grep MemTotal"; - string result = ExecuteCmd(cmd.c_str(), Purpose::MEM, Function::TOTAL); - if (result.empty() != true) { - uint64_t totalRam = std::stoul(result) * 1024; - EXPECT_EQ(Core::SystemInfo::Instance().GetTotalRam(), totalRam); - EXPECT_EQ(Core::SystemInfo::Instance().GetPhysicalPageCount(), static_cast(totalRam / pageSize)); + TEST(Core_SystemInfo, HostName) + { + std::string cmd = "hostname"; + string hostname = ExecuteCmd(cmd.c_str(), Purpose::HOST, Function::NONE).c_str(); + hostname.erase(std::remove(hostname.begin(), hostname.end(), '\n'), hostname.end()); + EXPECT_STREQ(::Thunder::Core::SystemInfo::Instance().GetHostName().c_str(), hostname.c_str()); } - cmd = "cat /proc/meminfo | grep SwapTotal:"; - result = ExecuteCmd(cmd.c_str(), Purpose::SWAP, Function::TOTAL); - if (result.empty() != true) { - uint64_t totalSwap = std::stoul(result) * 1024; - EXPECT_EQ(Core::SystemInfo::Instance().GetTotalSwap(), static_cast(totalSwap)); + TEST(Core_SystemInfo, HardwareInfo) + { + EXPECT_STREQ(::Thunder::Core::SystemInfo::Instance().Architecture().c_str(), Architecture().c_str()); + std::string cmd = "cat /proc/cpuinfo | grep model | grep name"; + EXPECT_STREQ(::Thunder::Core::SystemInfo::Instance().Chipset().c_str(), ExecuteCmd(cmd.c_str(), Purpose::CHIPSET, Function::NONE).c_str()); + } + TEST(Core_SystemInfo, FirmwareInfo) + { + EXPECT_STREQ(::Thunder::Core::SystemInfo::Instance().FirmwareVersion().c_str(), FirmwareVersion().c_str()); } + static constexpr uint32_t MegaBytesPerBytes = 1024 * 1024; + static constexpr uint32_t MegaBytesPerKBytes = 1024; + + TEST(Core_SystemInfo, MemoryInfo) + { + long pageSize= sysconf(_SC_PAGESIZE); + + EXPECT_NE(pageSize, -1); + EXPECT_EQ(::Thunder::Core::SystemInfo::Instance().GetPageSize(), static_cast(pageSize)); + + std::string cmd = "cat /proc/meminfo | grep MemTotal"; + string result = ExecuteCmd(cmd.c_str(), Purpose::MEM, Function::TOTAL); + if (result.empty() != true) { + uint64_t totalRam = std::stoul(result) * 1024; + EXPECT_EQ(::Thunder::Core::SystemInfo::Instance().GetTotalRam(), totalRam); + EXPECT_EQ(::Thunder::Core::SystemInfo::Instance().GetPhysicalPageCount(), static_cast(totalRam / pageSize)); + } + cmd = "cat /proc/meminfo | grep SwapTotal:"; + result = ExecuteCmd(cmd.c_str(), Purpose::SWAP, Function::TOTAL); + if (result.empty() != true) { + uint64_t totalSwap = std::stoul(result) * 1024; + EXPECT_EQ(::Thunder::Core::SystemInfo::Instance().GetTotalSwap(), static_cast(totalSwap)); + } + #if 0 // Disabling this since this can be varied time to time and endup different value - // even the APIs functioning properly - // Returns the instant snapshot of the free memory/swap at that moment, - // hence it can be different values due to any change happens in between the calls. - // And onvert to KB to get nearly equal value - cmd = "cat /proc/meminfo | grep MemFree:"; - result = ExecuteCmd(cmd.c_str(), Purpose::MEM, Function::FREE); - if (result.empty() != true) { - // Ignore last digit to ignore difference - EXPECT_EQ((Core::SystemInfo::Instance().GetFreeRam() / (MegaBytesPerBytes * 10)), (stol(result) / (MegaBytesPerKBytes * 10))); - } - cmd = "cat /proc/meminfo | grep SwapFree:"; - result = ExecuteCmd(cmd.c_str(), Purpose::SWAP, Function::FREE); - if (result.empty() != true) { - EXPECT_EQ(Core::SystemInfo::Instance().GetFreeSwap() / 10, (stol(result) * 1024) / 10); - } + // even the APIs functioning properly + // Returns the instant snapshot of the free memory/swap at that moment, + // hence it can be different values due to any change happens in between the calls. + // And onvert to KB to get nearly equal value + cmd = "cat /proc/meminfo | grep MemFree:"; + result = ExecuteCmd(cmd.c_str(), Purpose::MEM, Function::FREE); + if (result.empty() != true) { + // Ignore last digit to ignore difference + EXPECT_EQ((::Thunder::Core::SystemInfo::Instance().GetFreeRam() / (MegaBytesPerBytes * 10)), (stol(result) / (MegaBytesPerKBytes * 10))); + } + cmd = "cat /proc/meminfo | grep SwapFree:"; + result = ExecuteCmd(cmd.c_str(), Purpose::SWAP, Function::FREE); + if (result.empty() != true) { + EXPECT_EQ(::Thunder::Core::SystemInfo::Instance().GetFreeSwap() / 10, (stol(result) * 1024) / 10); + } #endif -} -TEST(Core_SystemInfo, memorySnapShot) -{ - Core::SystemInfo::MemorySnapshot snapshot = Core::SystemInfo::Instance().TakeMemorySnapshot(); - snapshot.AsJSON(); - std::string cmd = "cat /proc/meminfo | grep MemTotal:"; - string result = ExecuteCmd(cmd.c_str(), Purpose::MEM, Function::TOTAL); - if (result.empty() != true) { - uint64_t total = std::stoul(result); - EXPECT_EQ(snapshot.Total(), total); } + TEST(Core_SystemInfo, memorySnapShot) + { + ::Thunder::Core::SystemInfo::MemorySnapshot snapshot = ::Thunder::Core::SystemInfo::Instance().TakeMemorySnapshot(); + snapshot.AsJSON(); + std::string cmd = "cat /proc/meminfo | grep MemTotal:"; + string result = ExecuteCmd(cmd.c_str(), Purpose::MEM, Function::TOTAL); + if (result.empty() != true) { + uint64_t total = std::stoul(result); + EXPECT_EQ(snapshot.Total(), total); + } #if 0 // Disabling this since this can be varied time to time and endup different value - // even the APIs functioning properly - // Returns the instant snapshot of the free/available/cached memory at that moment, - // hence it can be different values due to any change happens in between the calls. - // And use convert to KB/10 to get nearly equal value - cmd = "cat /proc/meminfo | grep MemFree:"; - result = ExecuteCmd(cmd.c_str(), Purpose::MEM, Function::FREE); - if (result.empty() != true) { - EXPECT_EQ((snapshot.Free() / (MegaBytesPerKBytes * 10)), (stol(result) / (MegaBytesPerKBytes * 10))); - } - cmd = "cat /proc/meminfo | grep MemAvailable:"; - result = ExecuteCmd(cmd.c_str(), Purpose::MEM, Function::AVAILABLE); - if (result.empty() != true) { - EXPECT_EQ((snapshot.Available() / (MegaBytesPerKBytes * 10)), (stol(result) / (MegaBytesPerKBytes * 10))); - } - cmd = "cat /proc/meminfo | grep Cached:"; - result = ExecuteCmd(cmd.c_str(), Purpose::MEM, Function::CACHED); - if (result.empty() != true) { - EXPECT_EQ((snapshot.Cached() / MegaBytesPerKBytes), (stol(result) / MegaBytesPerKBytes)); - } + // even the APIs functioning properly + // Returns the instant snapshot of the free/available/cached memory at that moment, + // hence it can be different values due to any change happens in between the calls. + // And use convert to KB/10 to get nearly equal value + cmd = "cat /proc/meminfo | grep MemFree:"; + result = ExecuteCmd(cmd.c_str(), Purpose::MEM, Function::FREE); + if (result.empty() != true) { + EXPECT_EQ((snapshot.Free() / (MegaBytesPerKBytes * 10)), (stol(result) / (MegaBytesPerKBytes * 10))); + } + cmd = "cat /proc/meminfo | grep MemAvailable:"; + result = ExecuteCmd(cmd.c_str(), Purpose::MEM, Function::AVAILABLE); + if (result.empty() != true) { + EXPECT_EQ((snapshot.Available() / (MegaBytesPerKBytes * 10)), (stol(result) / (MegaBytesPerKBytes * 10))); + } + cmd = "cat /proc/meminfo | grep Cached:"; + result = ExecuteCmd(cmd.c_str(), Purpose::MEM, Function::CACHED); + if (result.empty() != true) { + EXPECT_EQ((snapshot.Cached() / MegaBytesPerKBytes), (stol(result) / MegaBytesPerKBytes)); + } #endif - cmd = "cat /proc/meminfo | grep SwapTotal:"; - result = ExecuteCmd(cmd.c_str(), Purpose::SWAP, Function::TOTAL); - if (result.empty() != true) { - uint64_t total = std::stoul(result); - EXPECT_EQ((snapshot.SwapTotal() / MegaBytesPerKBytes), total / MegaBytesPerKBytes); - } + cmd = "cat /proc/meminfo | grep SwapTotal:"; + result = ExecuteCmd(cmd.c_str(), Purpose::SWAP, Function::TOTAL); + if (result.empty() != true) { + uint64_t total = std::stoul(result); + EXPECT_EQ((snapshot.SwapTotal() / MegaBytesPerKBytes), total / MegaBytesPerKBytes); + } #if 0 // Disabling this since this can be varied time to time and endup different value - // even the APIs functioning properly - // Returns the instant snapshot of the free/cached swap at that moment, - // hence it can be different values due to any change happens in between the calls. - // And use convert to KB to get nearly equal value - cmd = "cat /proc/meminfo | grep SwapFree:"; - result = ExecuteCmd(cmd.c_str(), Purpose::SWAP, Function::FREE); - if (result.empty() != true) { - EXPECT_EQ((snapshot.SwapFree() / (MegaBytesPerKBytes * 10)), (stol(result) / (MegaBytesPerKBytes * 10))); - } - cmd = "cat /proc/meminfo | grep SwapCached:"; - result = ExecuteCmd(cmd.c_str(), Purpose::SWAP, Function::CACHED); - if (result.empty() != true) { - EXPECT_EQ((snapshot.SwapCached() / (MegaBytesPerKBytes * 10)), (stol(result) / (MegaBytesPerKBytes * 10))); - } + // even the APIs functioning properly + // Returns the instant snapshot of the free/cached swap at that moment, + // hence it can be different values due to any change happens in between the calls. + // And use convert to KB to get nearly equal value + cmd = "cat /proc/meminfo | grep SwapFree:"; + result = ExecuteCmd(cmd.c_str(), Purpose::SWAP, Function::FREE); + if (result.empty() != true) { + EXPECT_EQ((snapshot.SwapFree() / (MegaBytesPerKBytes * 10)), (stol(result) / (MegaBytesPerKBytes * 10))); + } + cmd = "cat /proc/meminfo | grep SwapCached:"; + result = ExecuteCmd(cmd.c_str(), Purpose::SWAP, Function::CACHED); + if (result.empty() != true) { + EXPECT_EQ((snapshot.SwapCached() / (MegaBytesPerKBytes * 10)), (stol(result) / (MegaBytesPerKBytes * 10))); + } #endif -} -TEST(Core_SystemInfo, DISABLED_UPTime) -{ - EXPECT_FLOAT_EQ(static_cast(Core::SystemInfo::Instance().GetUpTime()), GetUpTime()); -} -TEST(Core_SystemInfo, DISABLED_CPUInfo) -{ - // CPULoad - string cmd = "top -b -n 1 | grep Cpu"; - string result = ExecuteCmd(cmd.c_str(), Purpose::CPULOAD, Function::NONE); - if (result.empty() != true) { - /* CPULoad values showing big differences sometimes - * Load can be vary in between the time, hence this test will be disabling - uint8_t cpuLoad = stoi(result); - uint8_t difference = std::abs(cpuLoad - static_cast(Core::SystemInfo::Instance().GetCpuLoad())); - // Checking nearly equal value, since the cpu load calculation is average in the test app code - EXPECT_EQ((difference <= 2), true); - */ } + TEST(Core_SystemInfo, DISABLED_UPTime) + { + EXPECT_FLOAT_EQ(static_cast(::Thunder::Core::SystemInfo::Instance().GetUpTime()), GetUpTime()); + } + TEST(Core_SystemInfo, DISABLED_CPUInfo) + { + // CPULoad + string cmd = "top -b -n 1 | grep Cpu"; + string result = ExecuteCmd(cmd.c_str(), Purpose::CPULOAD, Function::NONE); + if (result.empty() != true) { + /* CPULoad values showing big differences sometimes + * Load can be vary in between the time, hence this test will be disabling + uint8_t cpuLoad = stoi(result); + uint8_t difference = std::abs(cpuLoad - static_cast(::Thunder::Core::SystemInfo::Instance().GetCpuLoad())); + // Checking nearly equal value, since the cpu load calculation is average in the test app code + EXPECT_EQ((difference <= 2), true); + */ + } - // CPULoadAvg - double loadFromSystem[3]; - // Validate only if we get a valid value for comparison from the system - if (getloadavg(loadFromSystem, 3) != -1) { - // Round of values to get nearest equals - loadFromSystem[0] = Round(loadFromSystem[0], 2); - loadFromSystem[1] = Round(loadFromSystem[1], 2); - loadFromSystem[2] = Round(loadFromSystem[2], 2); - - uint64_t* cpuLoadAvg = Core::SystemInfo::Instance().GetCpuLoadAvg(); - double loadFromThunder[3]; - // Fixed point arithmetic - EXPECT_DOUBLE_EQ(loadFromSystem[0], cpuLoadAvg[0] / (1 << SI_LOAD_SHIFT)); - EXPECT_DOUBLE_EQ(loadFromSystem[1], cpuLoadAvg[1] / (1 << SI_LOAD_SHIFT)); - EXPECT_DOUBLE_EQ(loadFromSystem[2], cpuLoadAvg[2] / (1 << SI_LOAD_SHIFT)); + // CPULoadAvg + double loadFromSystem[3]; + // Validate only if we get a valid value for comparison from the system + if (getloadavg(loadFromSystem, 3) != -1) { + // Round of values to get nearest equals + loadFromSystem[0] = Round(loadFromSystem[0], 2); + loadFromSystem[1] = Round(loadFromSystem[1], 2); + loadFromSystem[2] = Round(loadFromSystem[2], 2); + + uint64_t* cpuLoadAvg = ::Thunder::Core::SystemInfo::Instance().GetCpuLoadAvg(); + double loadFromThunder[3]; + // Fixed point arithmetic + EXPECT_DOUBLE_EQ(loadFromSystem[0], cpuLoadAvg[0] / (1 << SI_LOAD_SHIFT)); + EXPECT_DOUBLE_EQ(loadFromSystem[1], cpuLoadAvg[1] / (1 << SI_LOAD_SHIFT)); + EXPECT_DOUBLE_EQ(loadFromSystem[2], cpuLoadAvg[2] / (1 << SI_LOAD_SHIFT)); + } } -} #endif -TEST(Core_SystemInfo, Ticks_withoutDelay) -{ - uint64_t tick1 = Core::SystemInfo::Instance().Ticks(); - uint64_t tick2 = Core::SystemInfo::Instance().Ticks(); - // Difference depends on the clock time resolution - EXPECT_LE(tick1, tick2); -} -TEST(Core_SystemInfo, Ticks_withDelay) -{ - uint8_t seconds = 1; - uint64_t tick1 = Core::SystemInfo::Instance().Ticks(); - sleep(seconds); - uint64_t tick2 = Core::SystemInfo::Instance().Ticks(); - std::chrono::duration elapsed(tick2 - tick1); - EXPECT_GE(elapsed.count(), seconds); -} - + TEST(Core_SystemInfo, Ticks_withoutDelay) + { + uint64_t tick1 = ::Thunder::Core::SystemInfo::Instance().Ticks(); + uint64_t tick2 = ::Thunder::Core::SystemInfo::Instance().Ticks(); + // Difference depends on the clock time resolution + EXPECT_LE(tick1, tick2); + } + TEST(Core_SystemInfo, Ticks_withDelay) + { + uint8_t seconds = 1; + uint64_t tick1 = ::Thunder::Core::SystemInfo::Instance().Ticks(); + sleep(seconds); + uint64_t tick2 = ::Thunder::Core::SystemInfo::Instance().Ticks(); + std::chrono::duration elapsed(tick2 - tick1); + EXPECT_GE(elapsed.count(), seconds); + } +} // Core } // Tests -ENUM_CONVERSION_BEGIN(Tests::Purpose) - { Thunder::Tests::Purpose::MEM, _TXT("mem") }, - { Thunder::Tests::Purpose::SWAP, _TXT("swap") }, - { Thunder::Tests::Purpose::HOST, _TXT("host") }, - { Thunder::Tests::Purpose::CHIPSET, _TXT("chipset") }, - { Thunder::Tests::Purpose::CPULOAD, _TXT("cpuload") }, -ENUM_CONVERSION_END(Tests::Purpose) - -ENUM_CONVERSION_BEGIN(Tests::Function) - { Thunder::Tests::Function::TOTAL, _TXT("total") }, - { Thunder::Tests::Function::FREE, _TXT("free") }, - { Thunder::Tests::Function::AVAILABLE, _TXT("available") }, - { Thunder::Tests::Function::CACHED, _TXT("cached") }, -ENUM_CONVERSION_END(Tests::Function) +ENUM_CONVERSION_BEGIN(Tests::Core::Purpose) + { Tests::Core::Purpose::MEM, _TXT("mem") }, + { Tests::Core::Purpose::SWAP, _TXT("swap") }, + { Tests::Core::Purpose::HOST, _TXT("host") }, + { Tests::Core::Purpose::CHIPSET, _TXT("chipset") }, + { Tests::Core::Purpose::CPULOAD, _TXT("cpuload") }, +ENUM_CONVERSION_END(Tests::Core::Purpose) + +ENUM_CONVERSION_BEGIN(Tests::Core::Function) + { Tests::Core::Function::TOTAL, _TXT("total") }, + { Tests::Core::Function::FREE, _TXT("free") }, + { Tests::Core::Function::AVAILABLE, _TXT("available") }, + { Tests::Core::Function::CACHED, _TXT("cached") }, +ENUM_CONVERSION_END(Tests::Core::Function) } // Thunder diff --git a/Tests/unit/core/test_textfragment.cpp b/Tests/unit/core/test_textfragment.cpp index ff2e979ef8..0c007ad523 100644 --- a/Tests/unit/core/test_textfragment.cpp +++ b/Tests/unit/core/test_textfragment.cpp @@ -25,56 +25,61 @@ #include -using namespace Thunder; -using namespace Thunder::Core; +namespace Thunder { +namespace Tests { +namespace Core { -TEST(test_textfragment, simple_textfragement) -{ - string buffer = "/Service/testing/test"; - TextFragment result; - result = TextFragment(string(buffer)); - TextFragment(string(buffer)); - TextSegmentIterator index(TextFragment(string(buffer), 16, 5), false,'/'); - index.Next(); - index.Next(); + TEST(test_textfragment, simple_textfragement) + { + string buffer = "/Service/testing/test"; + ::Thunder::Core::TextFragment result; + result = ::Thunder::Core::TextFragment(string(buffer)); + ::Thunder::Core::TextFragment(string(buffer)); + ::Thunder::Core::TextSegmentIterator index(::Thunder::Core::TextFragment(string(buffer), 16, 5), false,'/'); + index.Next(); + index.Next(); - EXPECT_STREQ(index.Remainder().Text().c_str(), _T("test")) << "The remainder string is not test"; - EXPECT_STREQ(index.Remainder().Data(), _T("test")) << "The remainder string is not test"; - EXPECT_STREQ(index.Current().Text().c_str(), _T("test")) << "The current string is not test"; - EXPECT_EQ(index.Remainder().Length(), 4u) << "The length of the string is not 4."; - EXPECT_FALSE(index.Remainder().IsEmpty()); - - TextFragment textFragment; - const TCHAR buffer_new[] = "/Service/testing/test"; - TextFragment textFragment1(buffer_new); - TextFragment textFragment2(buffer_new,21); - TextFragment textFragment3(buffer_new,16,5); + EXPECT_STREQ(index.Remainder().Text().c_str(), _T("test")) << "The remainder string is not test"; + EXPECT_STREQ(index.Remainder().Data(), _T("test")) << "The remainder string is not test"; + EXPECT_STREQ(index.Current().Text().c_str(), _T("test")) << "The current string is not test"; + EXPECT_EQ(index.Remainder().Length(), 4u) << "The length of the string is not 4."; + EXPECT_FALSE(index.Remainder().IsEmpty()); + + ::Thunder::Core::TextFragment textFragment; + const TCHAR buffer_new[] = "/Service/testing/test"; + ::Thunder::Core::TextFragment textFragment1(buffer_new); + ::Thunder::Core::TextFragment textFragment2(buffer_new,21); + ::Thunder::Core::TextFragment textFragment3(buffer_new,16,5); - char delimiter[] = {'/'}; - EXPECT_EQ(textFragment1.ForwardFind(delimiter),0u); - textFragment1.Clear(); - EXPECT_EQ(textFragment2[1],'S'); + char delimiter[] = {'/'}; + EXPECT_EQ(textFragment1.ForwardFind(delimiter),0u); + textFragment1.Clear(); + EXPECT_EQ(textFragment2[1],'S'); - EXPECT_FALSE(textFragment1 == buffer_new); - EXPECT_FALSE(textFragment1 == buffer); - EXPECT_TRUE(textFragment1 != buffer_new); - EXPECT_TRUE(textFragment1 != buffer); + EXPECT_FALSE(textFragment1 == buffer_new); + EXPECT_FALSE(textFragment1 == buffer); + EXPECT_TRUE(textFragment1 != buffer_new); + EXPECT_TRUE(textFragment1 != buffer); - EXPECT_TRUE(textFragment2.OnMarker(buffer_new)); - EXPECT_TRUE(textFragment2.EqualText(buffer_new)); + EXPECT_TRUE(textFragment2.OnMarker(buffer_new)); + EXPECT_TRUE(textFragment2.EqualText(buffer_new)); - const TCHAR begin[] = "Service"; - const TCHAR end[] = "test"; - const TCHAR middle[] = "testing"; - textFragment2.TrimBegin(begin); - textFragment2.TrimEnd(end); - EXPECT_EQ(textFragment2.ReverseFind(middle),15u); - EXPECT_EQ(textFragment2.ReverseSkip(middle),16u); + const TCHAR begin[] = "Service"; + const TCHAR end[] = "test"; + const TCHAR middle[] = "testing"; + textFragment2.TrimBegin(begin); + textFragment2.TrimEnd(end); + EXPECT_EQ(textFragment2.ReverseFind(middle),15u); + EXPECT_EQ(textFragment2.ReverseSkip(middle),16u); - const TCHAR splitters[] ={'/',','}; - TextSegmentIterator iterator1(TextFragment(string(buffer), 16, 5), false,splitters); - TextSegmentIterator iterator2(iterator1); - index = iterator2; - iterator2.Reset(); - TextSegmentIterator iterator3; -} + const TCHAR splitters[] ={'/',','}; + ::Thunder::Core::TextSegmentIterator iterator1(::Thunder::Core::TextFragment(string(buffer), 16, 5), false,splitters); + ::Thunder::Core::TextSegmentIterator iterator2(iterator1); + index = iterator2; + iterator2.Reset(); + ::Thunder::Core::TextSegmentIterator iterator3; + } + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_textreader.cpp b/Tests/unit/core/test_textreader.cpp index f075fb3cc5..8c08f68dde 100644 --- a/Tests/unit/core/test_textreader.cpp +++ b/Tests/unit/core/test_textreader.cpp @@ -25,21 +25,26 @@ #include -using namespace Thunder; -using namespace Thunder::Core; +namespace Thunder { +namespace Tests { +namespace Core { -TEST(test_TextReader, simple_TextReader) -{ - TextReader(); + TEST(test_TextReader, simple_TextReader) + { + ::Thunder::Core::TextReader(); - uint8_t* val = (uint8_t*) "Checking the fragment"; - DataElement element(21,val); + uint8_t* val = (uint8_t*) "Checking the fragment"; + ::Thunder::Core::DataElement element(21,val); - TextReader Reader(element); - TextReader Reader1(Reader); + ::Thunder::Core::TextReader Reader(element); + ::Thunder::Core::TextReader Reader1(Reader); - Reader.Reset(); - EXPECT_FALSE(Reader.EndOfText()); - TextFragment fragment = Reader.ReadLine(); - EXPECT_STREQ(fragment.Data(),"Checking the fragment"); -} + Reader.Reset(); + EXPECT_FALSE(Reader.EndOfText()); + ::Thunder::Core::TextFragment fragment = Reader.ReadLine(); + EXPECT_STREQ(fragment.Data(),"Checking the fragment"); + } + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_thread.cpp b/Tests/unit/core/test_thread.cpp index 2ef0e2aafd..02fc96f320 100644 --- a/Tests/unit/core/test_thread.cpp +++ b/Tests/unit/core/test_thread.cpp @@ -30,15 +30,16 @@ namespace Thunder { namespace Tests { +namespace Core { - class ThreadClass : public Core::Thread { + class ThreadClass : public ::Thunder::Core::Thread { public: ThreadClass() = delete; ThreadClass(const ThreadClass&) = delete; ThreadClass& operator=(const ThreadClass&) = delete; ThreadClass(volatile bool& threadDone, std::mutex& mutex, std::condition_variable& cv, ::ThreadId parentTid) - : Core::Thread(Core::Thread::DefaultStackSize(), _T("Test")) + : ::Thunder::Core::Thread(::Thunder::Core::Thread::DefaultStackSize(), _T("Test")) , _done(threadDone) , _threadMutex(mutex) , _threadCV(cv) @@ -53,12 +54,12 @@ namespace Tests { virtual uint32_t Worker() override { while (IsRunning() && (!_done)) { - EXPECT_NE(_parentTid, Core::Thread::ThreadId()); + EXPECT_NE(_parentTid, ::Thunder::Core::Thread::ThreadId()); std::unique_lock lk(_threadMutex); _done = true; _threadCV.notify_one(); } - return (Core::infinite); + return (::Thunder::Core::infinite); } private : @@ -68,7 +69,7 @@ namespace Tests { ::ThreadId _parentTid; }; - class Job : public Core::IDispatch { + class Job : public ::Thunder::Core::IDispatch { public: Job(const Job&) = delete; Job& operator=(const Job&) = delete; @@ -83,7 +84,7 @@ namespace Tests { virtual void Dispatch() override { - EXPECT_NE(_parentTPid, Core::Thread::ThreadId()); + EXPECT_NE(_parentTPid, ::Thunder::Core::Thread::ThreadId()); std::unique_lock lk(_mutex); _threadDone = true; _cv.notify_one(); @@ -106,25 +107,27 @@ namespace Tests { bool Job::_threadDone = false; std::mutex Job::_mutex; std::condition_variable Job::_cv; - ::ThreadId Job::_parentTPid = Core::Thread::ThreadId(); + ::ThreadId Job::_parentTPid = ::Thunder::Core::Thread::ThreadId(); TEST(Core_Thread, DISABLED_SimpleThread) { - ::ThreadId parentTid = Core::Thread::ThreadId(); + ::ThreadId parentTid = ::Thunder::Core::Thread::ThreadId(); volatile bool threadDone = false; std::mutex mutex; std::condition_variable cv; ThreadClass object(threadDone, mutex, cv, parentTid); object.Run(); - EXPECT_EQ(object.State(), Core::Thread::RUNNING); + EXPECT_EQ(object.State(), ::Thunder::Core::Thread::RUNNING); std::unique_lock lk(mutex); while (!threadDone) { cv.wait(lk); } object.Stop(); - EXPECT_EQ(object.State(), Core::Thread::STOPPING); - object.Wait(Core::Thread::BLOCKED | Core::Thread::STOPPED | Core::Thread::STOPPING, Core::infinite); + EXPECT_EQ(object.State(), ::Thunder::Core::Thread::STOPPING); + object.Wait(::Thunder::Core::Thread::BLOCKED | ::Thunder::Core::Thread::STOPPED | ::Thunder::Core::Thread::STOPPING, ::Thunder::Core::infinite); } + +} // Core } // Tests } // Thunder diff --git a/Tests/unit/core/test_threadpool.cpp b/Tests/unit/core/test_threadpool.cpp index 29295cf006..ea9211fa94 100644 --- a/Tests/unit/core/test_threadpool.cpp +++ b/Tests/unit/core/test_threadpool.cpp @@ -27,1413 +27,1420 @@ #include -using namespace Thunder; -using namespace Thunder::Core; - -static constexpr uint32_t MaxJobWaitTime = 1000; // In milliseconds -static constexpr uint8_t MaxAdditionalWorker = 5; - -class EventControl { -public: - EventControl(const EventControl&) = delete; - EventControl& operator=(const EventControl&) = delete; - EventControl() - : _event(false, true) - { - } - ~EventControl() = default; - -public: - void Notify() - { - _event.SetEvent(); - } - uint32_t WaitForEvent(uint32_t waitTime) - { - return _event.Lock(waitTime); - } - void Reset() - { - _event.ResetEvent(); - } +namespace Thunder { +namespace Tests { +namespace Core { -private: - Event _event; -}; - -template -class TestJob : public Core::IDispatch, public EventControl { -public: - enum Status { - INITIATED, - CANCELED, - COMPLETED, - }; + + - TestJob() = delete; - TestJob(const TestJob& copy) = delete; - TestJob& operator=(const TestJob& RHS) = delete; - ~TestJob() override = default; - TestJob(IMPLEMENTATION& parent, const Status status, const uint32_t waitTime = 0, const bool checkParentState = false) - : _parent(parent) - , _status(status) - , _waitTime(waitTime) - , _checkParentState(checkParentState) - { - } + static constexpr uint32_t MaxJobWaitTime = 1000; // In milliseconds + static constexpr uint8_t MaxAdditionalWorker = 5; -public: - Status GetStatus() - { - return _status; - } - void Cancelled() - { - _status = (_status != COMPLETED) ? CANCELED : _status; - } - void Dispatch() override - { - _status = COMPLETED; - usleep(_waitTime); - Notify(); - if (_checkParentState) { - _parent.WaitForReady(this, _waitTime * 10); + class EventControl { + public: + EventControl(const EventControl&) = delete; + EventControl& operator=(const EventControl&) = delete; + EventControl() + : _event(false, true) + { } - } + ~EventControl() = default; -private: - IMPLEMENTATION& _parent; - Status _status; - uint32_t _waitTime; - bool _checkParentState; -}; - - -template -class JobControl { -private: - typedef std::map JobMap; -private: - template - class ExternalWorker : public Thread { public: - ExternalWorker() = delete; - ExternalWorker& operator=(const ExternalWorker&) = delete; - ExternalWorker(const ExternalWorker& copy) - : _job(copy._job) - , _parent(copy._parent) - , _waitTime(copy._waitTime) + void Notify() { + _event.SetEvent(); } - - ExternalWorker(PARENTIMPL &parent, Core::ProxyType job, const uint32_t waitTime = 0) - : _job(job) - , _parent(parent) - , _waitTime(waitTime) + uint32_t WaitForEvent(uint32_t waitTime) { - - Core::Thread::Run(); + return _event.Lock(waitTime); } - ~ExternalWorker() + void Reset() { - Stop(); + _event.ResetEvent(); } + private: + ::Thunder::Core::Event _event; + }; + + template + class TestJob : public ::Thunder::Core::IDispatch, public EventControl { public: - void Stop() + enum Status { + INITIATED, + CANCELED, + COMPLETED, + }; + + TestJob() = delete; + TestJob(const TestJob& copy) = delete; + TestJob& operator=(const TestJob& RHS) = delete; + ~TestJob() override = default; + TestJob(IMPLEMENTATION& parent, const Status status, const uint32_t waitTime = 0, const bool checkParentState = false) + : _parent(parent) + , _status(status) + , _waitTime(waitTime) + , _checkParentState(checkParentState) { - Core::Thread::Stop(); - Core::Thread::Wait(Core::Thread::STOPPED|Core::Thread::BLOCKED, Core::infinite); } - virtual uint32_t Worker() override + + public: + Status GetStatus() { - if (IsRunning()) { - _parent.Submit(_job, _waitTime); + return _status; + } + void Cancelled() + { + _status = (_status != COMPLETED) ? CANCELED : _status; + } + void Dispatch() override + { + _status = COMPLETED; + usleep(_waitTime); + Notify(); + if (_checkParentState) { + _parent.WaitForReady(this, _waitTime * 10); } - Core::Thread::Block(); - return (Core::infinite); } + private: - Core::ProxyType _job; IMPLEMENTATION& _parent; + Status _status; uint32_t _waitTime; + bool _checkParentState; }; -public: - JobControl() = delete; - JobControl(const JobControl&) = delete; - JobControl& operator=(const JobControl&) = delete; - JobControl(IMPLEMENTATION &parent) - : _index(0) - , _parent(parent) - , _external() - { - } - ~JobControl() = default; -public: - void Stop() - { - for (auto& job: _jobs) { - delete job.second; + template + class JobControl { + private: + typedef std::map<::Thunder::Core::IDispatch*, EventControl*> JobMap; + private: + template + class ExternalWorker : public ::Thunder::Core::Thread { + public: + ExternalWorker() = delete; + ExternalWorker& operator=(const ExternalWorker&) = delete; + ExternalWorker(const ExternalWorker& copy) + : _job(copy._job) + , _parent(copy._parent) + , _waitTime(copy._waitTime) + { + } + + ExternalWorker(PARENTIMPL &parent, ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> job, const uint32_t waitTime = 0) + : _job(job) + , _parent(parent) + , _waitTime(waitTime) + { + + ::Thunder::Core::Thread::Run(); + } + ~ExternalWorker() + { + Stop(); + } + + public: + void Stop() + { + ::Thunder::Core::Thread::Stop(); + ::Thunder::Core::Thread::Wait(::Thunder::Core::Thread::STOPPED|::Thunder::Core::Thread::BLOCKED, ::Thunder::Core::infinite); + } + virtual uint32_t Worker() override + { + if (IsRunning()) { + _parent.Submit(_job, _waitTime); + } + ::Thunder::Core::Thread::Block(); + return (::Thunder::Core::infinite); + } + private: + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> _job; + IMPLEMENTATION& _parent; + uint32_t _waitTime; + }; + + public: + JobControl() = delete; + JobControl(const JobControl&) = delete; + JobControl& operator=(const JobControl&) = delete; + JobControl(IMPLEMENTATION &parent) + : _index(0) + , _parent(parent) + , _external() + { } - _jobs.clear(); - for (auto& external: _external) { - delete external; + ~JobControl() = default; + + public: + void Stop() + { + for (auto& job: _jobs) { + delete job.second; + } + _jobs.clear(); + for (auto& external: _external) { + delete external; + } + _external.clear(); + ::Thunder::Core::Singleton::Dispose(); } - _external.clear(); - Singleton::Dispose(); - } - uint32_t WaitForReady(IDispatch* job, const uint32_t waitTime = 0) - { - uint32_t result = Core::ERROR_NONE; - JobMap::iterator index = _jobs.find(job); - if (index != _jobs.end()) { - result = index->second->WaitForEvent(waitTime); + uint32_t WaitForReady(::Thunder::Core::IDispatch* job, const uint32_t waitTime = 0) + { + uint32_t result = ::Thunder::Core::ERROR_NONE; + JobMap::iterator index = _jobs.find(job); + if (index != _jobs.end()) { + result = index->second->WaitForEvent(waitTime); + } + return result; } - return result; - } - void NotifyReady(const Core::ProxyType& job) - { - JobMap::iterator index = _jobs.find(job.operator->()); - if (index != _jobs.end()) { - index->second->Notify(); + void NotifyReady(const ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>& job) + { + JobMap::iterator index = _jobs.find(job.operator->()); + if (index != _jobs.end()) { + index->second->Notify(); + } } - } - void SubmitUsingSelfWorker(Core::ProxyType& job, const uint32_t waitTime = 0) - { - _jobs.emplace(std::piecewise_construct, std::forward_as_tuple(job.operator->()), std::forward_as_tuple(new EventControl())); - - _parent.Submit(job, waitTime); - } - void SubmitUsingExternalWorker(Core::ProxyType& job, const uint32_t waitTime = 0) - { - if (_external.size() < MaxAdditionalWorker) { + void SubmitUsingSelfWorker(::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>& job, const uint32_t waitTime = 0) + { _jobs.emplace(std::piecewise_construct, std::forward_as_tuple(job.operator->()), std::forward_as_tuple(new EventControl())); - _external.push_back(new ExternalWorker(_parent, job, waitTime)); + _parent.Submit(job, waitTime); } - } + void SubmitUsingExternalWorker(::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>& job, const uint32_t waitTime = 0) + { + if (_external.size() < MaxAdditionalWorker) { + _jobs.emplace(std::piecewise_construct, std::forward_as_tuple(job.operator->()), std::forward_as_tuple(new EventControl())); -private: - uint8_t _index; - JobMap _jobs; - IMPLEMENTATION& _parent; - std::vector*> _external; -}; + _external.push_back(new ExternalWorker(_parent, job, waitTime)); + } + } + + private: + uint8_t _index; + JobMap _jobs; + IMPLEMENTATION& _parent; + std::vector*> _external; + }; -class Scheduler : public ThreadPool::IScheduler { -private: - class Timer { + class Scheduler : public ::Thunder::Core::ThreadPool::IScheduler { + private: + class Timer { + public: + Timer& operator=(const Timer& RHS) = delete; + Timer() + : _job() + , _pool(nullptr) + { + } + Timer(const Timer& copy) + : _job(copy._job) + , _pool(copy._pool) + { + } + Timer(::Thunder::Core::ThreadPool* pool, const ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>& job) + : _job(job) + , _pool(pool) + { + } + ~Timer() + { + } + + public: + uint64_t Timed(const uint64_t /* scheduledTime */) + { + ASSERT(_pool != nullptr); + _pool->Submit(_job, ::Thunder::Core::infinite); + //_job.Release(); + // No need to reschedule, just drop it.. + return (0); + } + + private: + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> _job; + ::Thunder::Core::ThreadPool* _pool; + }; public: - Timer& operator=(const Timer& RHS) = delete; - Timer() - : _job() - , _pool(nullptr) + Scheduler() = delete; + Scheduler(const Scheduler&) = delete; + Scheduler& operator=(const Scheduler&) = delete; + + Scheduler(::Thunder::Core::ThreadPool& pool) + : _pool(pool) + , _timer(1024 * 1024, _T("ThreadPool::Timer")) { } - Timer(const Timer& copy) - : _job(copy._job) - , _pool(copy._pool) + ~Scheduler() override = default; + + public: + void Schedule(const ::Thunder::Core::Time& time, const ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>& job) override { + _timer.Schedule(time, Timer(&_pool, job)); + } + + private: + ::Thunder::Core::ThreadPool& _pool; + ::Thunder::Core::TimerType _timer; + }; + + class Dispatcher : public ::Thunder::Core::ThreadPool::IDispatcher { + public: + Dispatcher(const Dispatcher&) = delete; + Dispatcher& operator=(const Dispatcher&) = delete; + + Dispatcher() = default; + ~Dispatcher() override = default; + + private: + void Initialize() override { + } + void Deinitialize() override { } - Timer(ThreadPool* pool, const ProxyType& job) - : _job(job) - , _pool(pool) + void Dispatch(::Thunder::Core::IDispatch* job) override { + job->Dispatch(); + } + }; + + class ThreadPoolTester : public EventControl, public JobControl, public ::Thunder::Core::ThreadPool { + private: + public: + ThreadPoolTester() = delete; + ThreadPoolTester(const ThreadPoolTester&) = delete; + ThreadPoolTester& operator=(const ThreadPoolTester&) = delete; + ThreadPoolTester(const uint8_t count, const uint32_t stackSize, const uint32_t queueSize) + : JobControl(*this) + , ThreadPool(count, stackSize, queueSize, &_dispatcher, &_scheduler, nullptr, nullptr) + , _queueSize(queueSize) + , _dispatcher() + , _scheduler(*this) { } - ~Timer() + ~ThreadPoolTester() { } public: - uint64_t Timed(const uint64_t /* scheduledTime */) + uint32_t WaitForJobEvent(const ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>& job, const uint32_t waitTime = 0) + { + return static_cast&>(*job).WaitForEvent(waitTime); + } + bool QueueIsFull() + { + return (ThreadPool::Pending() == _queueSize); + } + bool QueueIsEmpty() + { + return (ThreadPool::Pending() == 0); + } + void Stop() { - ASSERT(_pool != nullptr); - _pool->Submit(_job, Core::infinite); - //_job.Release(); - // No need to reschedule, just drop it.. - return (0); + ThreadPool::Stop(); + JobControl::Stop(); } - private: - ProxyType _job; - ThreadPool* _pool; + private: + uint32_t _queueSize; + Dispatcher _dispatcher; + Scheduler _scheduler; }; -public: - Scheduler() = delete; - Scheduler(const Scheduler&) = delete; - Scheduler& operator=(const Scheduler&) = delete; - - Scheduler(ThreadPool& pool) - : _pool(pool) - , _timer(1024 * 1024, _T("ThreadPool::Timer")) - { - } - ~Scheduler() override = default; -public: - void Schedule(const Time& time, const ProxyType& job) override - { - _timer.Schedule(time, Timer(&_pool, job)); - } + class MinionTester : public ::Thunder::Core::Thread, public JobControl, public ::Thunder::Core::ThreadPool::Minion { + public: -private: - ThreadPool& _pool; - Core::TimerType _timer; -}; + MinionTester() = delete; + MinionTester(const MinionTester&) = delete; + MinionTester& operator=(const MinionTester&) = delete; + MinionTester(ThreadPoolTester& threadPool, const uint32_t queueSize) + : JobControl(*this) + , ::Thunder::Core::ThreadPool::Minion(threadPool, &_dispatcher) + , _queueSize(queueSize) + , _threadPool(threadPool) + , _dispatcher() + { + } + ~MinionTester() + { + Stop(); + } -class Dispatcher : public Core::ThreadPool::IDispatcher { -public: - Dispatcher(const Dispatcher&) = delete; - Dispatcher& operator=(const Dispatcher&) = delete; + public: + void Submit(const ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>& job, const uint32_t waitTime = 0) + { + _threadPool.Submit(job, waitTime); + } + void RunThreadPool() + { + _threadPool.Run(); + } + void Shutdown() + { + _threadPool.Stop(); + } + void Revoke(const ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>& job, const uint32_t waitTime = 0) + { + _threadPool.Revoke(job, waitTime); + Completed(job, waitTime); + } + uint32_t Completed(const ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>& job, const uint32_t waitTime) + { + uint32_t result = ::Thunder::Core::ThreadPool::Minion::Completed(job, waitTime); - Dispatcher() = default; - ~Dispatcher() override = default; + TestJob& testJob = static_cast&>(*job); + const_cast&>(testJob).Cancelled(); + return result; + } + virtual uint32_t Worker() override + { + if (IsRunning()) { + ::Thunder::Core::ThreadPool::Minion::Process(); + } + ::Thunder::Core::Thread::Block(); + return (::Thunder::Core::infinite); + } + void Stop() + { + ::Thunder::Core::Thread::Stop(); + ::Thunder::Core::Thread::Wait(::Thunder::Core::Thread::STOPPED|::Thunder::Core::Thread::BLOCKED, ::Thunder::Core::infinite); + JobControl::Stop(); + } + uint32_t WaitForJobEvent(const ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>& job, const uint32_t waitTime = 0) + { + return static_cast&>(*job).WaitForEvent(waitTime); + } + bool QueueIsFull() + { + return (_threadPool.Pending() == _queueSize); + } + bool QueueIsEmpty() + { + return (_threadPool.Pending() == 0); + } -private: - void Initialize() override { - } - void Deinitialize() override { - } - void Dispatch(Core::IDispatch* job) override { - job->Dispatch(); - } -}; - -class ThreadPoolTester : public EventControl, public JobControl, public ThreadPool { -private: -public: - ThreadPoolTester() = delete; - ThreadPoolTester(const ThreadPoolTester&) = delete; - ThreadPoolTester& operator=(const ThreadPoolTester&) = delete; - ThreadPoolTester(const uint8_t count, const uint32_t stackSize, const uint32_t queueSize) - : JobControl(*this) - , ThreadPool(count, stackSize, queueSize, &_dispatcher, &_scheduler, nullptr, nullptr) - , _queueSize(queueSize) - , _dispatcher() - , _scheduler(*this) - { - } - ~ThreadPoolTester() + private: + uint32_t _queueSize; + ThreadPoolTester& _threadPool; + Dispatcher _dispatcher; + }; + TEST(Core_ThreadPool, CheckMinion_ProcessJob) { - } + uint8_t queueSize = 5; + ThreadPoolTester threadPool(0, 0, queueSize); + MinionTester minion(threadPool, queueSize); + + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> job = ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(minion, TestJob::INITIATED, 500)); + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); + minion.Submit(job); + minion.Run(); + + EXPECT_EQ(minion.WaitForJobEvent(job, MaxJobWaitTime * 2), ::Thunder::Core::ERROR_NONE); + minion.NotifyReady(job); + minion.Shutdown(); + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); -public: - uint32_t WaitForJobEvent(const Core::ProxyType& job, const uint32_t waitTime = 0) - { - return static_cast&>(*job).WaitForEvent(waitTime); - } - bool QueueIsFull() - { - return (ThreadPool::Pending() == _queueSize); - } - bool QueueIsEmpty() - { - return (ThreadPool::Pending() == 0); - } - void Stop() - { - ThreadPool::Stop(); - JobControl::Stop(); - } + ::Thunder::Core::ThreadPool::Metadata info; + minion.Info(info); + EXPECT_EQ(info.Runs, 1u); -private: - uint32_t _queueSize; - Dispatcher _dispatcher; - Scheduler _scheduler; -}; - -class MinionTester : public Thread, public JobControl, public ThreadPool::Minion { -public: - - MinionTester() = delete; - MinionTester(const MinionTester&) = delete; - MinionTester& operator=(const MinionTester&) = delete; - MinionTester(ThreadPoolTester& threadPool, const uint32_t queueSize) - : JobControl(*this) - , ThreadPool::Minion(threadPool, &_dispatcher) - , _queueSize(queueSize) - , _threadPool(threadPool) - , _dispatcher() - { + job.Release(); } - ~MinionTester() + TEST(Core_ThreadPool, CheckMinion_ProcessJob_CheckActiveStateInBetweenDispatch) { - Stop(); - } + uint8_t queueSize = 5; + ThreadPoolTester threadPool(0, 0, queueSize); + MinionTester minion(threadPool, queueSize); + + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> job = ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(minion, TestJob::INITIATED, 500, true)); + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); + EXPECT_EQ(minion.IsActive(), false); + minion.SubmitUsingSelfWorker(job); + EXPECT_EQ(minion.IsActive(), false); + minion.Run(); + EXPECT_EQ(minion.WaitForJobEvent(job, MaxJobWaitTime * 2), ::Thunder::Core::ERROR_NONE); + EXPECT_EQ(minion.IsActive(), true); + minion.NotifyReady(job); + minion.Shutdown(); -public: - void Submit(const Core::ProxyType& job, const uint32_t waitTime = 0) - { - _threadPool.Submit(job, waitTime); - } - void RunThreadPool() - { - _threadPool.Run(); - } - void Shutdown() - { - _threadPool.Stop(); - } - void Revoke(const Core::ProxyType& job, const uint32_t waitTime = 0) - { - _threadPool.Revoke(job, waitTime); - Completed(job, waitTime); + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); + + ::Thunder::Core::ThreadPool::Metadata info; + minion.Info(info); + EXPECT_EQ(info.Runs, 1u); + + job.Release(); } - uint32_t Completed(const Core::ProxyType& job, const uint32_t waitTime) + TEST(Core_ThreadPool, CheckMinion_CancelJob_BeforeProcessing) { - uint32_t result = ThreadPool::Minion::Completed(job, waitTime); + uint8_t queueSize = 5; + ThreadPoolTester threadPool(0, 0, queueSize); + MinionTester minion(threadPool, queueSize); + + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> job = ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(minion, TestJob::INITIATED)); + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); + EXPECT_EQ(minion.IsActive(), false); + minion.Submit(job); + EXPECT_EQ(minion.IsActive(), false); + minion.Revoke(job); + EXPECT_EQ(minion.IsActive(), false); + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::CANCELED); + + ::Thunder::Core::ThreadPool::Metadata info; + minion.Info(info); + EXPECT_EQ(info.Runs, 0u); - TestJob& testJob = static_cast&>(*job); - const_cast&>(testJob).Cancelled(); - return result; + job.Release(); } - virtual uint32_t Worker() override + TEST(Core_ThreadPool, CheckMinion_CancelJob_WhileProcessing) { - if (IsRunning()) { - ThreadPool::Minion::Process(); + uint8_t queueSize = 5; + ThreadPoolTester threadPool(0, 0, queueSize); + MinionTester minion(threadPool, queueSize); + + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> job = ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(minion, TestJob::INITIATED, 500)); + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); + EXPECT_EQ(minion.IsActive(), false); + minion.Submit(job); + EXPECT_EQ(minion.IsActive(), false); + minion.Run(); + + volatile bool queueIsEmpty = false; + while((queueIsEmpty = minion.QueueIsEmpty()) != true) { + __asm__ volatile("nop"); } - Core::Thread::Block(); - return (Core::infinite); - } - void Stop() - { - Core::Thread::Stop(); - Core::Thread::Wait(Core::Thread::STOPPED|Core::Thread::BLOCKED, Core::infinite); - JobControl::Stop(); - } - uint32_t WaitForJobEvent(const Core::ProxyType& job, const uint32_t waitTime = 0) - { - return static_cast&>(*job).WaitForEvent(waitTime); + minion.Revoke(job); + EXPECT_EQ(minion.WaitForJobEvent(job, MaxJobWaitTime * 3), ::Thunder::Core::ERROR_NONE); + minion.Shutdown(); + EXPECT_EQ(minion.IsActive(), false); + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); + + ::Thunder::Core::ThreadPool::Metadata info; + minion.Info(info); + EXPECT_EQ(info.Runs, 1u); + + job.Release(); } - bool QueueIsFull() + TEST(Core_ThreadPool, CheckMinion_CancelJob_WhileProcessing_ByAddingWaitOnTheDispatcher) { - return (_threadPool.Pending() == _queueSize); + uint8_t queueSize = 5; + ThreadPoolTester threadPool(0, 0, queueSize); + MinionTester minion(threadPool, queueSize); + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> job = ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(minion, TestJob::INITIATED, 500, true)); + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); + EXPECT_EQ(minion.IsActive(), false); + minion.SubmitUsingSelfWorker(job); + EXPECT_EQ(minion.IsActive(), false); + minion.Run(); + EXPECT_EQ(minion.WaitForJobEvent(job, MaxJobWaitTime * 3), ::Thunder::Core::ERROR_NONE); + minion.Revoke(job); + EXPECT_EQ(minion.IsActive(), true); + minion.NotifyReady(job); + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); + + ::Thunder::Core::ThreadPool::Metadata info; + minion.Info(info); + EXPECT_EQ(info.Runs, 1u); + + minion.Shutdown(); + usleep(100); + EXPECT_EQ(minion.IsActive(), false); + job.Release(); } - bool QueueIsEmpty() + TEST(Core_ThreadPool, CheckMinion_ProcessMultipleJobs) { - return (_threadPool.Pending() == 0); - } + uint8_t queueSize = 5; + uint8_t additionalJobs = 1; + ThreadPoolTester threadPool(0, 0, queueSize); + MinionTester minion(threadPool, queueSize); + std::vector<::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>> jobs; + for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { + jobs.push_back(::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(minion, TestJob::INITIATED, 500))); + } + for (auto& job: jobs) { + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); + if (minion.QueueIsFull() == false) { + minion.SubmitUsingSelfWorker(job); + } else { + EXPECT_EQ(minion.QueueIsFull(), true); + minion.SubmitUsingExternalWorker(job, ::Thunder::Core::infinite); + } + } + EXPECT_EQ(minion.QueueIsFull(), true); + EXPECT_EQ(minion.QueueIsEmpty(), false); -private: - uint32_t _queueSize; - ThreadPoolTester& _threadPool; - Dispatcher _dispatcher; -}; -TEST(Core_ThreadPool, CheckMinion_ProcessJob) -{ - uint8_t queueSize = 5; - ThreadPoolTester threadPool(0, 0, queueSize); - MinionTester minion(threadPool, queueSize); - - Core::ProxyType job = Core::ProxyType(Core::ProxyType>::Create(minion, TestJob::INITIATED, 500)); - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); - minion.Submit(job); - minion.Run(); - - EXPECT_EQ(minion.WaitForJobEvent(job, MaxJobWaitTime * 2), Core::ERROR_NONE); - minion.NotifyReady(job); - minion.Shutdown(); - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); - - Thunder::Core::ThreadPool::Metadata info; - minion.Info(info); - EXPECT_EQ(info.Runs, 1u); - - job.Release(); -} -TEST(Core_ThreadPool, CheckMinion_ProcessJob_CheckActiveStateInBetweenDispatch) -{ - uint8_t queueSize = 5; - ThreadPoolTester threadPool(0, 0, queueSize); - MinionTester minion(threadPool, queueSize); - - Core::ProxyType job = Core::ProxyType(Core::ProxyType>::Create(minion, TestJob::INITIATED, 500, true)); - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); - EXPECT_EQ(minion.IsActive(), false); - minion.SubmitUsingSelfWorker(job); - EXPECT_EQ(minion.IsActive(), false); - minion.Run(); - EXPECT_EQ(minion.WaitForJobEvent(job, MaxJobWaitTime * 2), Core::ERROR_NONE); - EXPECT_EQ(minion.IsActive(), true); - minion.NotifyReady(job); - minion.Shutdown(); - - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); - - Thunder::Core::ThreadPool::Metadata info; - minion.Info(info); - EXPECT_EQ(info.Runs, 1u); - - job.Release(); -} -TEST(Core_ThreadPool, CheckMinion_CancelJob_BeforeProcessing) -{ - uint8_t queueSize = 5; - ThreadPoolTester threadPool(0, 0, queueSize); - MinionTester minion(threadPool, queueSize); - - Core::ProxyType job = Core::ProxyType(Core::ProxyType>::Create(minion, TestJob::INITIATED)); - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); - EXPECT_EQ(minion.IsActive(), false); - minion.Submit(job); - EXPECT_EQ(minion.IsActive(), false); - minion.Revoke(job); - EXPECT_EQ(minion.IsActive(), false); - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::CANCELED); - - Thunder::Core::ThreadPool::Metadata info; - minion.Info(info); - EXPECT_EQ(info.Runs, 0u); - - job.Release(); -} -TEST(Core_ThreadPool, CheckMinion_CancelJob_WhileProcessing) -{ - uint8_t queueSize = 5; - ThreadPoolTester threadPool(0, 0, queueSize); - MinionTester minion(threadPool, queueSize); - - Core::ProxyType job = Core::ProxyType(Core::ProxyType>::Create(minion, TestJob::INITIATED, 500)); - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); - EXPECT_EQ(minion.IsActive(), false); - minion.Submit(job); - EXPECT_EQ(minion.IsActive(), false); - minion.Run(); - - volatile bool queueIsEmpty = false; - while((queueIsEmpty = minion.QueueIsEmpty()) != true) { - __asm__ volatile("nop"); - } - minion.Revoke(job); - EXPECT_EQ(minion.WaitForJobEvent(job, MaxJobWaitTime * 3), Core::ERROR_NONE); - minion.Shutdown(); - EXPECT_EQ(minion.IsActive(), false); - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); - - Thunder::Core::ThreadPool::Metadata info; - minion.Info(info); - EXPECT_EQ(info.Runs, 1u); - - job.Release(); -} -TEST(Core_ThreadPool, CheckMinion_CancelJob_WhileProcessing_ByAddingWaitOnTheDispatcher) -{ - uint8_t queueSize = 5; - ThreadPoolTester threadPool(0, 0, queueSize); - MinionTester minion(threadPool, queueSize); - Core::ProxyType job = Core::ProxyType(Core::ProxyType>::Create(minion, TestJob::INITIATED, 500, true)); - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); - EXPECT_EQ(minion.IsActive(), false); - minion.SubmitUsingSelfWorker(job); - EXPECT_EQ(minion.IsActive(), false); - minion.Run(); - EXPECT_EQ(minion.WaitForJobEvent(job, MaxJobWaitTime * 3), Core::ERROR_NONE); - minion.Revoke(job); - EXPECT_EQ(minion.IsActive(), true); - minion.NotifyReady(job); - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); - - Thunder::Core::ThreadPool::Metadata info; - minion.Info(info); - EXPECT_EQ(info.Runs, 1u); - - minion.Shutdown(); - usleep(100); - EXPECT_EQ(minion.IsActive(), false); - job.Release(); -} -TEST(Core_ThreadPool, CheckMinion_ProcessMultipleJobs) -{ - uint8_t queueSize = 5; - uint8_t additionalJobs = 1; - ThreadPoolTester threadPool(0, 0, queueSize); - MinionTester minion(threadPool, queueSize); - std::vector> jobs; - for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { - jobs.push_back(Core::ProxyType(Core::ProxyType>::Create(minion, TestJob::INITIATED, 500))); - } - for (auto& job: jobs) { - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); - if (minion.QueueIsFull() == false) { - minion.SubmitUsingSelfWorker(job); - } else { - EXPECT_EQ(minion.QueueIsFull(), true); - minion.SubmitUsingExternalWorker(job, Core::infinite); + minion.Run(); + for (auto& job: jobs) { + EXPECT_EQ(minion.WaitForJobEvent(job, MaxJobWaitTime), ::Thunder::Core::ERROR_NONE); } - } - EXPECT_EQ(minion.QueueIsFull(), true); - EXPECT_EQ(minion.QueueIsEmpty(), false); - minion.Run(); - for (auto& job: jobs) { - EXPECT_EQ(minion.WaitForJobEvent(job, MaxJobWaitTime), Core::ERROR_NONE); - } + minion.Shutdown(); + + for (auto& job: jobs) { + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); + } - minion.Shutdown(); + ::Thunder::Core::ThreadPool::Metadata info; + minion.Info(info); + EXPECT_EQ(info.Runs, 6u); - for (auto& job: jobs) { - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); + for (auto& job: jobs) { + job.Release(); + } + jobs.clear(); } + TEST(Core_ThreadPool, CheckMinion_ProcessMultipleJobs_CancelInBetween) + { + uint8_t queueSize = 5; + uint8_t additionalJobs = 2; + ThreadPoolTester threadPool(0, 0, queueSize); + MinionTester minion(threadPool, queueSize); + std::vector<::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>> jobs; + for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { + jobs.push_back(::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(minion, TestJob::INITIATED, 500))); + } - Thunder::Core::ThreadPool::Metadata info; - minion.Info(info); - EXPECT_EQ(info.Runs, 6u); + for (auto& job: jobs) { + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); + if (minion.QueueIsFull() == false) { + minion.SubmitUsingSelfWorker(job); + } else { + EXPECT_EQ(minion.QueueIsFull(), true); + minion.SubmitUsingExternalWorker(job, ::Thunder::Core::infinite); + } + } + EXPECT_EQ(minion.QueueIsFull(), true); + EXPECT_EQ(minion.QueueIsEmpty(), false); - for (auto& job: jobs) { - job.Release(); - } - jobs.clear(); -} -TEST(Core_ThreadPool, CheckMinion_ProcessMultipleJobs_CancelInBetween) -{ - uint8_t queueSize = 5; - uint8_t additionalJobs = 2; - ThreadPoolTester threadPool(0, 0, queueSize); - MinionTester minion(threadPool, queueSize); - std::vector> jobs; - for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { - jobs.push_back(Core::ProxyType(Core::ProxyType>::Create(minion, TestJob::INITIATED, 500))); - } + minion.Revoke(jobs[3]); + minion.Revoke(jobs[4]); - for (auto& job: jobs) { - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); - if (minion.QueueIsFull() == false) { - minion.SubmitUsingSelfWorker(job); - } else { - EXPECT_EQ(minion.QueueIsFull(), true); - minion.SubmitUsingExternalWorker(job, Core::infinite); + minion.Run(); + for (uint8_t i = 0; i < jobs.size(); ++i) { + if ((i == 3) || (i == 4)) { + EXPECT_EQ(minion.WaitForJobEvent(jobs[i], MaxJobWaitTime), ::Thunder::Core::ERROR_TIMEDOUT); + } else { + EXPECT_EQ(minion.WaitForJobEvent(jobs[i], MaxJobWaitTime), ::Thunder::Core::ERROR_NONE); + } } - } - EXPECT_EQ(minion.QueueIsFull(), true); - EXPECT_EQ(minion.QueueIsEmpty(), false); - minion.Revoke(jobs[3]); - minion.Revoke(jobs[4]); + for (uint8_t i = 0; i < jobs.size(); ++i) { + if ((i == 3) || (i == 4)) { + EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::CANCELED); + } else { + EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::COMPLETED); + } + } + + minion.Shutdown(); - minion.Run(); - for (uint8_t i = 0; i < jobs.size(); ++i) { - if ((i == 3) || (i == 4)) { - EXPECT_EQ(minion.WaitForJobEvent(jobs[i], MaxJobWaitTime), Core::ERROR_TIMEDOUT); - } else { - EXPECT_EQ(minion.WaitForJobEvent(jobs[i], MaxJobWaitTime), Core::ERROR_NONE); + ::Thunder::Core::ThreadPool::Metadata info; + minion.Info(info); + EXPECT_EQ(info.Runs, queueSize); + + for (auto& job: jobs) { + job.Release(); } + jobs.clear(); } - for (uint8_t i = 0; i < jobs.size(); ++i) { - if ((i == 3) || (i == 4)) { - EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::CANCELED); - } else { - EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::COMPLETED); + TEST(Core_ThreadPool, CheckThreadPool_ProcessJob) + { + uint32_t queueSize = 1; + uint32_t threadCount = 1; + ThreadPoolTester threadPool(threadCount, 0, queueSize); + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> job = ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(threadPool, TestJob::INITIATED, 500)); + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); + threadPool.Submit(job, 0); + EXPECT_EQ(threadPool.Pending(), queueSize); + EXPECT_EQ(threadPool.QueueIsEmpty(), false); + threadPool.Run(); + while(threadPool.QueueIsEmpty() != true) { + __asm__ volatile("nop"); } + EXPECT_EQ(threadPool.WaitForJobEvent(job, MaxJobWaitTime), ::Thunder::Core::ERROR_NONE); + EXPECT_EQ(threadPool.Pending(), 0u); + threadPool.Stop(); + + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); + job.Release(); } - minion.Shutdown(); + TEST(Core_ThreadPool, CheckThreadPool_RevokeJob) + { + uint32_t queueSize = 1; + uint32_t threadCount = 1; + ThreadPoolTester threadPool(threadCount, 0, queueSize); - Thunder::Core::ThreadPool::Metadata info; - minion.Info(info); - EXPECT_EQ(info.Runs, queueSize); + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> job = ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(threadPool, TestJob::INITIATED)); + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); + threadPool.Submit(job, 0); + EXPECT_EQ(threadPool.Pending(), queueSize); + threadPool.Revoke(job, 0); + EXPECT_EQ(threadPool.Pending(), 0u); + EXPECT_EQ(threadPool.QueueIsEmpty(), true); + threadPool.Run(); + threadPool.Stop(); - for (auto& job: jobs) { + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); job.Release(); } - jobs.clear(); -} - -TEST(Core_ThreadPool, CheckThreadPool_ProcessJob) -{ - uint32_t queueSize = 1; - uint32_t threadCount = 1; - ThreadPoolTester threadPool(threadCount, 0, queueSize); - Core::ProxyType job = Core::ProxyType(Core::ProxyType>::Create(threadPool, TestJob::INITIATED, 500)); - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); - threadPool.Submit(job, 0); - EXPECT_EQ(threadPool.Pending(), queueSize); - EXPECT_EQ(threadPool.QueueIsEmpty(), false); - threadPool.Run(); - while(threadPool.QueueIsEmpty() != true) { - __asm__ volatile("nop"); - } - EXPECT_EQ(threadPool.WaitForJobEvent(job, MaxJobWaitTime), Core::ERROR_NONE); - EXPECT_EQ(threadPool.Pending(), 0u); - threadPool.Stop(); - - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); - job.Release(); -} - -TEST(Core_ThreadPool, CheckThreadPool_RevokeJob) -{ - uint32_t queueSize = 1; - uint32_t threadCount = 1; - ThreadPoolTester threadPool(threadCount, 0, queueSize); - - Core::ProxyType job = Core::ProxyType(Core::ProxyType>::Create(threadPool, TestJob::INITIATED)); - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); - threadPool.Submit(job, 0); - EXPECT_EQ(threadPool.Pending(), queueSize); - threadPool.Revoke(job, 0); - EXPECT_EQ(threadPool.Pending(), 0u); - EXPECT_EQ(threadPool.QueueIsEmpty(), true); - threadPool.Run(); - threadPool.Stop(); - - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); - job.Release(); -} -TEST(Core_ThreadPool, CheckThreadPool_CancelJob_WhileProcessing) -{ - uint32_t queueSize = 1; - uint32_t threadCount = 1; - ThreadPoolTester threadPool(threadCount, 0, queueSize); - - Core::ProxyType job = Core::ProxyType(Core::ProxyType>::Create(threadPool, TestJob::INITIATED, 1000)); - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); - threadPool.Submit(job, 0); - EXPECT_EQ(threadPool.Pending(), queueSize); - EXPECT_EQ(threadPool.QueueIsEmpty(), false); - threadPool.Run(); - EXPECT_EQ(threadPool.QueueIsEmpty(), false); - while(threadPool.QueueIsEmpty() != true) { - __asm__ volatile("nop"); - } - threadPool.Revoke(job, 0); - EXPECT_EQ(threadPool.Pending(), 0u); - EXPECT_EQ(threadPool.WaitForJobEvent(job, MaxJobWaitTime * 3), Core::ERROR_NONE); - threadPool.Stop(); - - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); - job.Release(); -} -void CheckThreadPool_ProcessMultipleJobs(const uint8_t threadCount, const uint8_t queueSize, const uint8_t additionalJobs) -{ - ThreadPoolTester threadPool(threadCount, 0, queueSize); - - std::vector> jobs; - // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs - for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { - jobs.push_back(Core::ProxyType(Core::ProxyType>::Create(threadPool, TestJob::INITIATED, 500))); - } + TEST(Core_ThreadPool, CheckThreadPool_CancelJob_WhileProcessing) + { + uint32_t queueSize = 1; + uint32_t threadCount = 1; + ThreadPoolTester threadPool(threadCount, 0, queueSize); - for (auto& job: jobs) { + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> job = ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(threadPool, TestJob::INITIATED, 1000)); EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); - if (threadPool.QueueIsFull() == false) { - threadPool.SubmitUsingSelfWorker(job); - } else { - EXPECT_EQ(threadPool.QueueIsFull(), true); - threadPool.SubmitUsingExternalWorker(job, Core::infinite); + threadPool.Submit(job, 0); + EXPECT_EQ(threadPool.Pending(), queueSize); + EXPECT_EQ(threadPool.QueueIsEmpty(), false); + threadPool.Run(); + EXPECT_EQ(threadPool.QueueIsEmpty(), false); + while(threadPool.QueueIsEmpty() != true) { + __asm__ volatile("nop"); } - } - EXPECT_EQ(threadPool.QueueIsFull(), true); - EXPECT_EQ(threadPool.QueueIsEmpty(), false); - EXPECT_EQ(threadPool.Pending(), queueSize); - - threadPool.Run(); - for (auto& job: jobs) { - EXPECT_EQ(threadPool.WaitForJobEvent(job, MaxJobWaitTime * 3), Core::ERROR_NONE); - } + threadPool.Revoke(job, 0); + EXPECT_EQ(threadPool.Pending(), 0u); + EXPECT_EQ(threadPool.WaitForJobEvent(job, MaxJobWaitTime * 3), ::Thunder::Core::ERROR_NONE); + threadPool.Stop(); - for (auto& job: jobs) { EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); + job.Release(); } + void CheckThreadPool_ProcessMultipleJobs(const uint8_t threadCount, const uint8_t queueSize, const uint8_t additionalJobs) + { + ThreadPoolTester threadPool(threadCount, 0, queueSize); + + std::vector<::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>> jobs; + // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs + for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { + jobs.push_back(::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(threadPool, TestJob::INITIATED, 500))); + } - uint8_t totalRuns = 0; + for (auto& job: jobs) { + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); + if (threadPool.QueueIsFull() == false) { + threadPool.SubmitUsingSelfWorker(job); + } else { + EXPECT_EQ(threadPool.QueueIsFull(), true); + threadPool.SubmitUsingExternalWorker(job, ::Thunder::Core::infinite); + } + } + EXPECT_EQ(threadPool.QueueIsFull(), true); + EXPECT_EQ(threadPool.QueueIsEmpty(), false); + EXPECT_EQ(threadPool.Pending(), queueSize); - Thunder::Core::ThreadPool::Metadata info[threadCount]; - std::vector jobsStrings; + threadPool.Run(); + for (auto& job: jobs) { + EXPECT_EQ(threadPool.WaitForJobEvent(job, MaxJobWaitTime * 3), ::Thunder::Core::ERROR_NONE); + } - threadPool.Snapshot(threadCount, info, jobsStrings); + for (auto& job: jobs) { + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); + } - for (uint8_t i = 0; i < threadCount; ++i) { - totalRuns += info[i].Runs; - } - EXPECT_EQ(totalRuns, static_cast(queueSize + additionalJobs)); + uint8_t totalRuns = 0; - threadPool.Stop(); + ::Thunder::Core::ThreadPool::Metadata info[threadCount]; + std::vector jobsStrings; - for (auto& job: jobs) { - job.Release(); - } - jobs.clear(); -} -TEST(Core_ThreadPool, CheckThreadPool_ProcessMultipleJobs) -{ - CheckThreadPool_ProcessMultipleJobs(5, 1, 0); - CheckThreadPool_ProcessMultipleJobs(5, 5, 0); -} -TEST(Core_ThreadPool, CheckThreadPool_ProcessMultipleJobs_AdditionalJobs) -{ - //CheckThreadPool_ProcessMultipleJobs(5, 1, 1); - CheckThreadPool_ProcessMultipleJobs(5, 5, 5); -} - -TEST(Core_ThreadPool, CheckThreadPool_ProcessMultipleJobs_CancelInBetween) -{ - uint8_t queueSize = 5; - uint8_t additionalJobs = 2; - uint8_t threadCount = 1; - ThreadPoolTester threadPool(threadCount, 0, queueSize); - EXPECT_EQ(threadPool.Count(), threadCount); - - std::vector> jobs; - // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs - for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { - jobs.push_back(Core::ProxyType(Core::ProxyType>::Create(threadPool, TestJob::INITIATED, 500))); - } + threadPool.Snapshot(threadCount, info, jobsStrings); - for (auto& job: jobs) { - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); - if (threadPool.QueueIsFull() == false) { - threadPool.SubmitUsingSelfWorker(job); - } else { - EXPECT_EQ(threadPool.QueueIsFull(), true); - threadPool.SubmitUsingExternalWorker(job, Core::infinite); + for (uint8_t i = 0; i < threadCount; ++i) { + totalRuns += info[i].Runs; } - } - EXPECT_EQ(threadPool.QueueIsFull(), true); - EXPECT_EQ(threadPool.QueueIsEmpty(), false); - EXPECT_EQ(threadPool.Pending(), queueSize); - - threadPool.Run(); - threadPool.Revoke(jobs[3], 0); - threadPool.Revoke(jobs[4], 0); - - EXPECT_EQ(threadPool.QueueIsFull(), false); - Core::ProxyType newJob = Core::ProxyType(Core::ProxyType>::Create(threadPool, TestJob::INITIATED)); - EXPECT_EQ(static_cast&>(*newJob).GetStatus(), TestJob::INITIATED); - // Try to push additional job to queue from external worker - threadPool.SubmitUsingSelfWorker(newJob, MaxJobWaitTime); - jobs.push_back(newJob); - - for (uint8_t i = 0; i < jobs.size(); ++i) { - if ((i == 3) || (i == 4)) { - EXPECT_EQ(threadPool.WaitForJobEvent(jobs[i], MaxJobWaitTime), Core::ERROR_TIMEDOUT); - } else { - EXPECT_EQ(threadPool.WaitForJobEvent(jobs[i], MaxJobWaitTime * 2), Core::ERROR_NONE); + EXPECT_EQ(totalRuns, static_cast(queueSize + additionalJobs)); + + threadPool.Stop(); + + for (auto& job: jobs) { + job.Release(); } + jobs.clear(); } - for (uint8_t i = 0; i < jobs.size(); ++i) { - if ((i == 3) || (i == 4)) { - EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); - } else { - EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::COMPLETED); - } + TEST(Core_ThreadPool, CheckThreadPool_ProcessMultipleJobs) + { + CheckThreadPool_ProcessMultipleJobs(5, 1, 0); + CheckThreadPool_ProcessMultipleJobs(5, 5, 0); + } + TEST(Core_ThreadPool, CheckThreadPool_ProcessMultipleJobs_AdditionalJobs) + { + //CheckThreadPool_ProcessMultipleJobs(5, 1, 1); + CheckThreadPool_ProcessMultipleJobs(5, 5, 5); } - uint8_t totalRuns = 0; + TEST(Core_ThreadPool, CheckThreadPool_ProcessMultipleJobs_CancelInBetween) + { + uint8_t queueSize = 5; + uint8_t additionalJobs = 2; + uint8_t threadCount = 1; + ThreadPoolTester threadPool(threadCount, 0, queueSize); + EXPECT_EQ(threadPool.Count(), threadCount); + + std::vector<::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>> jobs; + // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs + for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { + jobs.push_back(::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(threadPool, TestJob::INITIATED, 500))); + } + + for (auto& job: jobs) { + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); + if (threadPool.QueueIsFull() == false) { + threadPool.SubmitUsingSelfWorker(job); + } else { + EXPECT_EQ(threadPool.QueueIsFull(), true); + threadPool.SubmitUsingExternalWorker(job, ::Thunder::Core::infinite); + } + } + EXPECT_EQ(threadPool.QueueIsFull(), true); + EXPECT_EQ(threadPool.QueueIsEmpty(), false); + EXPECT_EQ(threadPool.Pending(), queueSize); + + threadPool.Run(); + threadPool.Revoke(jobs[3], 0); + threadPool.Revoke(jobs[4], 0); + + EXPECT_EQ(threadPool.QueueIsFull(), false); + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> newJob = ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(threadPool, TestJob::INITIATED)); + EXPECT_EQ(static_cast&>(*newJob).GetStatus(), TestJob::INITIATED); + // Try to push additional job to queue from external worker + threadPool.SubmitUsingSelfWorker(newJob, MaxJobWaitTime); + jobs.push_back(newJob); + + for (uint8_t i = 0; i < jobs.size(); ++i) { + if ((i == 3) || (i == 4)) { + EXPECT_EQ(threadPool.WaitForJobEvent(jobs[i], MaxJobWaitTime), ::Thunder::Core::ERROR_TIMEDOUT); + } else { + EXPECT_EQ(threadPool.WaitForJobEvent(jobs[i], MaxJobWaitTime * 2), ::Thunder::Core::ERROR_NONE); + } + } + for (uint8_t i = 0; i < jobs.size(); ++i) { + if ((i == 3) || (i == 4)) { + EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); + } else { + EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::COMPLETED); + } + } - Thunder::Core::ThreadPool::Metadata info[threadCount]; - std::vector jobsStrings; + uint8_t totalRuns = 0; - threadPool.Snapshot(threadCount, info, jobsStrings); + ::Thunder::Core::ThreadPool::Metadata info[threadCount]; + std::vector jobsStrings; - for (uint8_t i = 0; i < threadCount; ++i) { - totalRuns += info[i].Runs; - } - EXPECT_EQ(totalRuns, queueSize + additionalJobs - 1); + threadPool.Snapshot(threadCount, info, jobsStrings); - threadPool.Stop(); + for (uint8_t i = 0; i < threadCount; ++i) { + totalRuns += info[i].Runs; + } + EXPECT_EQ(totalRuns, queueSize + additionalJobs - 1); - for (auto& job: jobs) { - job.Release(); - } - jobs.clear(); -} -void CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithMultiplePool(const uint8_t threadCount, const uint8_t queueSize, const uint8_t additionalJobs) -{ - ThreadPoolTester threadPool(threadCount, 0, queueSize); - EXPECT_EQ(threadPool.Count(), threadCount); - - std::vector> jobs; - // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs - for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { - jobs.push_back(Core::ProxyType(Core::ProxyType>::Create(threadPool, TestJob::INITIATED, 100, true))); - } + threadPool.Stop(); - for (auto& job: jobs) { - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); - if (threadPool.QueueIsFull() == false) { - threadPool.SubmitUsingSelfWorker(job); - } else { - EXPECT_EQ(threadPool.QueueIsFull(), true); - threadPool.SubmitUsingExternalWorker(job, Core::infinite); + for (auto& job: jobs) { + job.Release(); } + jobs.clear(); } - EXPECT_EQ(threadPool.QueueIsEmpty(), false); - EXPECT_EQ(threadPool.Pending(), queueSize); + void CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithMultiplePool(const uint8_t threadCount, const uint8_t queueSize, const uint8_t additionalJobs) + { + ThreadPoolTester threadPool(threadCount, 0, queueSize); + EXPECT_EQ(threadPool.Count(), threadCount); - threadPool.Run(); - usleep(100); + std::vector<::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>> jobs; + // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs + for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { + jobs.push_back(::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(threadPool, TestJob::INITIATED, 100, true))); + } - for (uint8_t i = 0; i < jobs.size(); ++i) { - EXPECT_EQ(threadPool.WaitForJobEvent(jobs[i], MaxJobWaitTime * 5), Core::ERROR_NONE); - if ((i == 3) || (i == 4)) { - threadPool.Revoke(jobs[i], 0); + for (auto& job: jobs) { + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); + if (threadPool.QueueIsFull() == false) { + threadPool.SubmitUsingSelfWorker(job); + } else { + EXPECT_EQ(threadPool.QueueIsFull(), true); + threadPool.SubmitUsingExternalWorker(job, ::Thunder::Core::infinite); + } } - threadPool.NotifyReady(jobs[i]); - } + EXPECT_EQ(threadPool.QueueIsEmpty(), false); + EXPECT_EQ(threadPool.Pending(), queueSize); - for (auto& job: jobs) { - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); - } + threadPool.Run(); + usleep(100); - uint8_t totalRuns = 0; + for (uint8_t i = 0; i < jobs.size(); ++i) { + EXPECT_EQ(threadPool.WaitForJobEvent(jobs[i], MaxJobWaitTime * 5), ::Thunder::Core::ERROR_NONE); + if ((i == 3) || (i == 4)) { + threadPool.Revoke(jobs[i], 0); + } + threadPool.NotifyReady(jobs[i]); + } - Thunder::Core::ThreadPool::Metadata info[threadCount]; - std::vector jobsStrings; + for (auto& job: jobs) { + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); + } - threadPool.Snapshot(threadCount, info, jobsStrings); + uint8_t totalRuns = 0; - for (uint8_t i = 0; i < threadCount; ++i) { - totalRuns += info[i].Runs; - } - EXPECT_EQ(totalRuns, queueSize + additionalJobs); + ::Thunder::Core::ThreadPool::Metadata info[threadCount]; + std::vector jobsStrings; - threadPool.Stop(); + threadPool.Snapshot(threadCount, info, jobsStrings); - for (auto& job: jobs) { - job.Release(); - } - jobs.clear(); -} -TEST(Core_ThreadPool, CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithSinglePool) -{ - CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithMultiplePool(1, 5, 0); -} -TEST(Core_ThreadPool, CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithSinglePool_AdditionalJob) -{ - CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithMultiplePool(1, 5, 1); - CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithMultiplePool(1, 5, 5); -} -TEST(Core_ThreadPool, CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithMultiplePool) -{ - CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithMultiplePool(5, 5, 0); -} -TEST(Core_ThreadPool, CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithMultiplePool_AdditionalJob) -{ - CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithMultiplePool(5, 5, 1); - CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithMultiplePool(5, 5, 5); -} -class ThreadJobTester : public EventControl { -public: - ThreadJobTester(const ThreadJobTester&) = delete; - ThreadJobTester& operator=(const ThreadJobTester&) = delete; - - ThreadJobTester() - : _expectedTime() - , _job(*this) - { - } - ~ThreadJobTester() = default; + for (uint8_t i = 0; i < threadCount; ++i) { + totalRuns += info[i].Runs; + } + EXPECT_EQ(totalRuns, queueSize + additionalJobs); - Core::ProxyType Submit() - { - return _job.Submit(); - } - Core::ProxyType Reschedule(const Time& time) - { - return _job.Reschedule(time); + threadPool.Stop(); + + for (auto& job: jobs) { + job.Release(); + } + jobs.clear(); } - Core::ProxyType Revoke() + TEST(Core_ThreadPool, CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithSinglePool) { - Core::ProxyType job = _job.Revoke(); - _job.Revoked(); - return job; + CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithMultiplePool(1, 5, 0); } - Core::ProxyType Idle() + TEST(Core_ThreadPool, CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithSinglePool_AdditionalJob) { - return _job.Idle(); + CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithMultiplePool(1, 5, 1); + CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithMultiplePool(1, 5, 5); } - bool IsIdle() + TEST(Core_ThreadPool, CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithMultiplePool) { - return _job.IsIdle(); + CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithMultiplePool(5, 5, 0); } - -public: - void Dispatch() + TEST(Core_ThreadPool, CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithMultiplePool_AdditionalJob) { - Notify(); + CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithMultiplePool(5, 5, 1); + CheckThreadPool_ProcessMultipleJobs_CancelInBetween_WithMultiplePool(5, 5, 5); } + class ThreadJobTester : public EventControl { + public: + ThreadJobTester(const ThreadJobTester&) = delete; + ThreadJobTester& operator=(const ThreadJobTester&) = delete; -private: - Core::Time _expectedTime; - Core::ThreadPool::JobType _job; -}; - -void CheckThreadPool_JobType_Submit_Using_Idle(const uint8_t threadCount, const uint8_t queueSize, const uint8_t additionalJobs, const uint8_t cancelJobsCount, const uint8_t* cancelJobsId) -{ - ThreadPoolTester threadPool(threadCount, 0, queueSize); - EXPECT_EQ(threadPool.Count(), threadCount); + ThreadJobTester() + : _expectedTime() + , _job(*this) + { + } + ~ThreadJobTester() = default; - std::vector> jobs; - // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs - for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { - jobs.push_back(Core::ProxyType(Core::ProxyType::Create())); - } + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> Submit() + { + return _job.Submit(); + } + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> Reschedule(const ::Thunder::Core::Time& time) + { + return _job.Reschedule(time); + } + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> Revoke() + { + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> job = _job.Revoke(); + _job.Revoked(); + return job; + } + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> Idle() + { + return _job.Idle(); + } + bool IsIdle() + { + return _job.IsIdle(); + } - for (uint8_t i = 0; i < jobs.size(); ++i) { - bool isCanceledJob = false; - for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) + public: + void Dispatch() { - if (i == cancelJobsId[cancelIndex]) { - isCanceledJob = true; - break; - } + Notify(); } - Core::ProxyType job; - if (isCanceledJob == true) { - EXPECT_EQ(jobs[i]->IsIdle(), true); - job = (jobs[i]->Idle()); - EXPECT_EQ(jobs[i]->IsIdle(), false); - job = (jobs[i]->Revoke()); - EXPECT_EQ(jobs[i]->IsIdle(), true); - } else { - EXPECT_EQ(jobs[i]->IsIdle(), true); - job = (jobs[i]->Idle()); - EXPECT_EQ(jobs[i]->IsIdle(), false); + private: + ::Thunder::Core::Time _expectedTime; + ::Thunder::Core::ThreadPool::JobType _job; + }; - // Try to get same job again - Core::ProxyType jobRetry = (jobs[i]->Idle()); - EXPECT_EQ(jobRetry.IsValid(), false); + void CheckThreadPool_JobType_Submit_Using_Idle(const uint8_t threadCount, const uint8_t queueSize, const uint8_t additionalJobs, const uint8_t cancelJobsCount, const uint8_t* cancelJobsId) + { + ThreadPoolTester threadPool(threadCount, 0, queueSize); + EXPECT_EQ(threadPool.Count(), threadCount); + + std::vector<::Thunder::Core::ProxyType> jobs; + // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs + for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { + jobs.push_back(::Thunder::Core::ProxyType(::Thunder::Core::ProxyType::Create())); } - if (job.IsValid() && (jobs[i]->IsIdle() != true)) { - if (threadPool.QueueIsFull() == false) { - threadPool.SubmitUsingSelfWorker(job); - } else { - EXPECT_EQ(threadPool.QueueIsFull(), true); - threadPool.SubmitUsingExternalWorker(job, Core::infinite); + + for (uint8_t i = 0; i < jobs.size(); ++i) { + bool isCanceledJob = false; + for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) + { + if (i == cancelJobsId[cancelIndex]) { + isCanceledJob = true; + break; + } } - } - } - EXPECT_EQ(threadPool.Pending(), static_cast(queueSize - cancelJobsCount)); + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> job; + if (isCanceledJob == true) { + EXPECT_EQ(jobs[i]->IsIdle(), true); + job = (jobs[i]->Idle()); + EXPECT_EQ(jobs[i]->IsIdle(), false); + job = (jobs[i]->Revoke()); + EXPECT_EQ(jobs[i]->IsIdle(), true); - threadPool.Run(); - usleep(100); + } else { + EXPECT_EQ(jobs[i]->IsIdle(), true); + job = (jobs[i]->Idle()); + EXPECT_EQ(jobs[i]->IsIdle(), false); - for (uint8_t i = 0; i < jobs.size(); ++i) { - bool isCanceledJob = false; - for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) - { - if (i == cancelJobsId[cancelIndex]) { - isCanceledJob = true; - break; + // Try to get same job again + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> jobRetry = (jobs[i]->Idle()); + EXPECT_EQ(jobRetry.IsValid(), false); + } + if (job.IsValid() && (jobs[i]->IsIdle() != true)) { + if (threadPool.QueueIsFull() == false) { + threadPool.SubmitUsingSelfWorker(job); + } else { + EXPECT_EQ(threadPool.QueueIsFull(), true); + threadPool.SubmitUsingExternalWorker(job, ::Thunder::Core::infinite); + } } } - if (isCanceledJob == true) { - EXPECT_EQ(jobs[i]->WaitForEvent(MaxJobWaitTime * 3), Core::ERROR_TIMEDOUT); - } else { - EXPECT_EQ(jobs[i]->WaitForEvent(MaxJobWaitTime * 3), Core::ERROR_NONE); - usleep(500); + EXPECT_EQ(threadPool.Pending(), static_cast(queueSize - cancelJobsCount)); + + threadPool.Run(); + usleep(100); + + for (uint8_t i = 0; i < jobs.size(); ++i) { + bool isCanceledJob = false; + for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) + { + if (i == cancelJobsId[cancelIndex]) { + isCanceledJob = true; + break; + } + } + if (isCanceledJob == true) { + EXPECT_EQ(jobs[i]->WaitForEvent(MaxJobWaitTime * 3), ::Thunder::Core::ERROR_TIMEDOUT); + } else { + EXPECT_EQ(jobs[i]->WaitForEvent(MaxJobWaitTime * 3), ::Thunder::Core::ERROR_NONE); + usleep(500); + } + EXPECT_EQ(jobs[i]->IsIdle(), true); } - EXPECT_EQ(jobs[i]->IsIdle(), true); - } - uint8_t totalRuns = 0; + uint8_t totalRuns = 0; - Thunder::Core::ThreadPool::Metadata info[threadCount]; - std::vector jobsStrings; + ::Thunder::Core::ThreadPool::Metadata info[threadCount]; + std::vector jobsStrings; - threadPool.Snapshot(threadCount, info, jobsStrings); + threadPool.Snapshot(threadCount, info, jobsStrings); - for (uint8_t i = 0; i < threadCount; ++i) { - totalRuns += info[i].Runs; - } - EXPECT_EQ(totalRuns, queueSize + additionalJobs - cancelJobsCount); + for (uint8_t i = 0; i < threadCount; ++i) { + totalRuns += info[i].Runs; + } + EXPECT_EQ(totalRuns, queueSize + additionalJobs - cancelJobsCount); - threadPool.Stop(); + threadPool.Stop(); - for (auto& job: jobs) { - job.Release(); + for (auto& job: jobs) { + job.Release(); + } + jobs.clear(); } - jobs.clear(); -} - -TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_SinglePool_SingleJob) -{ - CheckThreadPool_JobType_Submit_Using_Idle(1, 1, 0, 0, nullptr); -} -TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_SinglePool_SingleJob_CancelJobs) -{ - const uint8_t job = 0; - CheckThreadPool_JobType_Submit_Using_Idle(1, 1, 0, 1, &job); -} -TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_SinglePool_MultipleJobs) -{ - CheckThreadPool_JobType_Submit_Using_Idle(1, 5, 0, 0, nullptr); -} -TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_SinglePool_MultipleJobs_CancelJobs) -{ - const uint8_t jobs[] = {0, 2}; - CheckThreadPool_JobType_Submit_Using_Idle(1, 5, 0, sizeof(jobs), jobs); -} -TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_MultiplePool_MultipleJobs) -{ - CheckThreadPool_JobType_Submit_Using_Idle(5, 5, 0, 0, nullptr); -} -TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_MultiplePool_MultipleJobs_CancelJobs) -{ - const uint8_t jobs[] = {0, 2}; - CheckThreadPool_JobType_Submit_Using_Idle(5, 5, 0, sizeof(jobs), jobs); -} - -void CheckThreadPool_JobType_Submit_Using_Submit(const uint8_t threadCount, const uint8_t queueSize, const uint8_t additionalJobs, const uint8_t cancelJobsCount, const uint8_t* cancelJobsId) -{ - ThreadPoolTester threadPool(threadCount, 0, queueSize); - EXPECT_EQ(threadPool.Count(), threadCount); - - std::vector> jobs; - // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs - for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { - jobs.push_back(Core::ProxyType(Core::ProxyType::Create())); + + TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_SinglePool_SingleJob) + { + CheckThreadPool_JobType_Submit_Using_Idle(1, 1, 0, 0, nullptr); + } + TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_SinglePool_SingleJob_CancelJobs) + { + const uint8_t job = 0; + CheckThreadPool_JobType_Submit_Using_Idle(1, 1, 0, 1, &job); + } + TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_SinglePool_MultipleJobs) + { + CheckThreadPool_JobType_Submit_Using_Idle(1, 5, 0, 0, nullptr); + } + TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_SinglePool_MultipleJobs_CancelJobs) + { + const uint8_t jobs[] = {0, 2}; + CheckThreadPool_JobType_Submit_Using_Idle(1, 5, 0, sizeof(jobs), jobs); + } + TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_MultiplePool_MultipleJobs) + { + CheckThreadPool_JobType_Submit_Using_Idle(5, 5, 0, 0, nullptr); + } + TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_MultiplePool_MultipleJobs_CancelJobs) + { + const uint8_t jobs[] = {0, 2}; + CheckThreadPool_JobType_Submit_Using_Idle(5, 5, 0, sizeof(jobs), jobs); } - for (uint8_t i = 0; i < jobs.size(); ++i) { - bool isCanceledJob = false; - for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) - { - if (i == cancelJobsId[cancelIndex]) { - isCanceledJob = true; - break; - } - } - Core::ProxyType job; - if (isCanceledJob == true) { - EXPECT_EQ(jobs[i]->IsIdle(), true); - job = (jobs[i]->Idle()); - EXPECT_EQ(jobs[i]->IsIdle(), false); - job = (jobs[i]->Revoke()); - EXPECT_EQ(jobs[i]->IsIdle(), true); - } else { - EXPECT_EQ(jobs[i]->IsIdle(), true); - job = (jobs[i]->Submit()); - EXPECT_EQ(jobs[i]->IsIdle(), false); + void CheckThreadPool_JobType_Submit_Using_Submit(const uint8_t threadCount, const uint8_t queueSize, const uint8_t additionalJobs, const uint8_t cancelJobsCount, const uint8_t* cancelJobsId) + { + ThreadPoolTester threadPool(threadCount, 0, queueSize); + EXPECT_EQ(threadPool.Count(), threadCount); - // Try to get same job again - Core::ProxyType jobRetry = (jobs[i]->Submit()); - EXPECT_EQ(jobRetry.IsValid(), false); + std::vector<::Thunder::Core::ProxyType> jobs; + // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs + for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { + jobs.push_back(::Thunder::Core::ProxyType(::Thunder::Core::ProxyType::Create())); } - if (job.IsValid() && (jobs[i]->IsIdle() != true)) { - if (threadPool.QueueIsFull() == false) { - threadPool.SubmitUsingSelfWorker(job); - } else { - EXPECT_EQ(threadPool.QueueIsFull(), true); - threadPool.SubmitUsingExternalWorker(job, Core::infinite); - } - } - } - EXPECT_EQ(threadPool.Pending(), static_cast(queueSize - cancelJobsCount)); - threadPool.Run(); - usleep(100); + for (uint8_t i = 0; i < jobs.size(); ++i) { + bool isCanceledJob = false; + for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) + { + if (i == cancelJobsId[cancelIndex]) { + isCanceledJob = true; + break; + } + } + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> job; + if (isCanceledJob == true) { + EXPECT_EQ(jobs[i]->IsIdle(), true); + job = (jobs[i]->Idle()); + EXPECT_EQ(jobs[i]->IsIdle(), false); + job = (jobs[i]->Revoke()); + EXPECT_EQ(jobs[i]->IsIdle(), true); + } else { + EXPECT_EQ(jobs[i]->IsIdle(), true); + job = (jobs[i]->Submit()); + EXPECT_EQ(jobs[i]->IsIdle(), false); - for (uint8_t i = 0; i < jobs.size(); ++i) { - bool isCanceledJob = false; - for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) - { - if (i == cancelJobsId[cancelIndex]) { - isCanceledJob = true; - break; + // Try to get same job again + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> jobRetry = (jobs[i]->Submit()); + EXPECT_EQ(jobRetry.IsValid(), false); + } + if (job.IsValid() && (jobs[i]->IsIdle() != true)) { + if (threadPool.QueueIsFull() == false) { + threadPool.SubmitUsingSelfWorker(job); + } else { + EXPECT_EQ(threadPool.QueueIsFull(), true); + threadPool.SubmitUsingExternalWorker(job, ::Thunder::Core::infinite); + } } } - if (isCanceledJob == true) { - EXPECT_EQ(jobs[i]->WaitForEvent(MaxJobWaitTime * 3), Core::ERROR_TIMEDOUT); - } else { - EXPECT_EQ(jobs[i]->WaitForEvent(MaxJobWaitTime * 3), Core::ERROR_NONE); - usleep(100); + EXPECT_EQ(threadPool.Pending(), static_cast(queueSize - cancelJobsCount)); + + threadPool.Run(); + usleep(100); + + for (uint8_t i = 0; i < jobs.size(); ++i) { + bool isCanceledJob = false; + for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) + { + if (i == cancelJobsId[cancelIndex]) { + isCanceledJob = true; + break; + } + } + if (isCanceledJob == true) { + EXPECT_EQ(jobs[i]->WaitForEvent(MaxJobWaitTime * 3), ::Thunder::Core::ERROR_TIMEDOUT); + } else { + EXPECT_EQ(jobs[i]->WaitForEvent(MaxJobWaitTime * 3), ::Thunder::Core::ERROR_NONE); + usleep(100); + } + EXPECT_EQ(jobs[i]->IsIdle(), true); } - EXPECT_EQ(jobs[i]->IsIdle(), true); - } - uint8_t totalRuns = 0; + uint8_t totalRuns = 0; - Thunder::Core::ThreadPool::Metadata info[threadCount]; - std::vector jobsStrings; + ::Thunder::Core::ThreadPool::Metadata info[threadCount]; + std::vector jobsStrings; - threadPool.Snapshot(threadCount, info, jobsStrings); + threadPool.Snapshot(threadCount, info, jobsStrings); - for (uint8_t i = 0; i < threadCount; ++i) { - totalRuns += info[i].Runs; - } - EXPECT_EQ(totalRuns, queueSize + additionalJobs - cancelJobsCount); + for (uint8_t i = 0; i < threadCount; ++i) { + totalRuns += info[i].Runs; + } + EXPECT_EQ(totalRuns, queueSize + additionalJobs - cancelJobsCount); - threadPool.Stop(); + threadPool.Stop(); - for (auto& job: jobs) { - job.Release(); + for (auto& job: jobs) { + job.Release(); + } + jobs.clear(); } - jobs.clear(); -} -TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Submit_SinglePool_SingleJob) -{ - CheckThreadPool_JobType_Submit_Using_Submit(1, 1, 0, 0, nullptr); -} -TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Submit_SinglePool_SingleJob_CancelJobs) -{ - const uint8_t job = 0; - CheckThreadPool_JobType_Submit_Using_Submit(1, 1, 0, 1, &job); -} -TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Submit_SinglePool_MultipleJobs) -{ - CheckThreadPool_JobType_Submit_Using_Submit(1, 5, 0, 0, nullptr); -} -TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Submit_SinglePool_MultipleJobs_CancelJobs) -{ - const uint8_t jobs[] = {0, 2}; - CheckThreadPool_JobType_Submit_Using_Submit(1, 5, 0, sizeof(jobs), jobs); -} -TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Submit_MultiplePool_MultipleJobs) -{ - CheckThreadPool_JobType_Submit_Using_Submit(5, 5, 0, 0, nullptr); -} -TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Submit_MultiplePool_MultipleJobs_CancelJobs) -{ - const uint8_t jobs[] = {0, 2}; - CheckThreadPool_JobType_Submit_Using_Submit(5, 5, 0, sizeof(jobs), jobs); -} - -void CheckThreadPool_JobType_Submit_Using_Reschedule(const uint8_t threadCount, const uint8_t queueSize, const uint8_t additionalJobs, const uint8_t cancelJobsCount, const uint8_t* cancelJobsId, const uint16_t scheduledTimes[]) -{ - ThreadPoolTester threadPool(threadCount, 0, queueSize); - EXPECT_EQ(threadPool.Count(), threadCount); - threadPool.Run(); - - std::vector> jobs; - // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs - for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { - jobs.push_back(Core::ProxyType(Core::ProxyType::Create())); + TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Submit_SinglePool_SingleJob) + { + CheckThreadPool_JobType_Submit_Using_Submit(1, 1, 0, 0, nullptr); + } + TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Submit_SinglePool_SingleJob_CancelJobs) + { + const uint8_t job = 0; + CheckThreadPool_JobType_Submit_Using_Submit(1, 1, 0, 1, &job); + } + TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Submit_SinglePool_MultipleJobs) + { + CheckThreadPool_JobType_Submit_Using_Submit(1, 5, 0, 0, nullptr); + } + TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Submit_SinglePool_MultipleJobs_CancelJobs) + { + const uint8_t jobs[] = {0, 2}; + CheckThreadPool_JobType_Submit_Using_Submit(1, 5, 0, sizeof(jobs), jobs); + } + TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Submit_MultiplePool_MultipleJobs) + { + CheckThreadPool_JobType_Submit_Using_Submit(5, 5, 0, 0, nullptr); + } + TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Submit_MultiplePool_MultipleJobs_CancelJobs) + { + const uint8_t jobs[] = {0, 2}; + CheckThreadPool_JobType_Submit_Using_Submit(5, 5, 0, sizeof(jobs), jobs); } - for (uint8_t i = 0; i < jobs.size(); ++i) { - bool isCanceledJob = false; - for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) - { - if (i == cancelJobsId[cancelIndex]) { - isCanceledJob = true; - break; - } - } - Core::ProxyType job; - if (isCanceledJob == true) { - EXPECT_EQ(jobs[i]->IsIdle(), true); - job = (jobs[i]->Idle()); - EXPECT_EQ(jobs[i]->IsIdle(), false); - job = (jobs[i]->Revoke()); - EXPECT_EQ(jobs[i]->IsIdle(), true); - } else { - EXPECT_EQ(jobs[i]->IsIdle(), true); - job = (jobs[i]->Reschedule(Core::Time::Now().Add(scheduledTimes[i]))); - EXPECT_EQ(jobs[i]->IsIdle(), false); - // Try to get same job again - Core::ProxyType jobRetry = (jobs[i]->Reschedule(Core::Time::Now().Add(scheduledTimes[i]))); - EXPECT_EQ(jobRetry.IsValid(), false); + void CheckThreadPool_JobType_Submit_Using_Reschedule(const uint8_t threadCount, const uint8_t queueSize, const uint8_t additionalJobs, const uint8_t cancelJobsCount, const uint8_t* cancelJobsId, const uint16_t scheduledTimes[]) + { + ThreadPoolTester threadPool(threadCount, 0, queueSize); + EXPECT_EQ(threadPool.Count(), threadCount); + threadPool.Run(); + + std::vector<::Thunder::Core::ProxyType> jobs; + // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs + for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { + jobs.push_back(::Thunder::Core::ProxyType(::Thunder::Core::ProxyType::Create())); } - if (job.IsValid() && (jobs[i]->IsIdle() != true)) { - if (threadPool.QueueIsFull() == false) { - threadPool.SubmitUsingSelfWorker(job); + for (uint8_t i = 0; i < jobs.size(); ++i) { + bool isCanceledJob = false; + for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) + { + if (i == cancelJobsId[cancelIndex]) { + isCanceledJob = true; + break; + } + } + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> job; + if (isCanceledJob == true) { + EXPECT_EQ(jobs[i]->IsIdle(), true); + job = (jobs[i]->Idle()); + EXPECT_EQ(jobs[i]->IsIdle(), false); + job = (jobs[i]->Revoke()); + EXPECT_EQ(jobs[i]->IsIdle(), true); } else { - EXPECT_EQ(threadPool.QueueIsFull(), true); - threadPool.SubmitUsingExternalWorker(job, Core::infinite); + EXPECT_EQ(jobs[i]->IsIdle(), true); + job = (jobs[i]->Reschedule(::Thunder::Core::Time::Now().Add(scheduledTimes[i]))); + EXPECT_EQ(jobs[i]->IsIdle(), false); + + // Try to get same job again + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> jobRetry = (jobs[i]->Reschedule(::Thunder::Core::Time::Now().Add(scheduledTimes[i]))); + EXPECT_EQ(jobRetry.IsValid(), false); + } + if (job.IsValid() && (jobs[i]->IsIdle() != true)) { + if (threadPool.QueueIsFull() == false) { + threadPool.SubmitUsingSelfWorker(job); + } else { + EXPECT_EQ(threadPool.QueueIsFull(), true); + threadPool.SubmitUsingExternalWorker(job, ::Thunder::Core::infinite); + } } } - } - for (uint8_t i = 0; i < jobs.size(); ++i) { - bool isCanceledJob = false; - for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) - { - if (i == cancelJobsId[cancelIndex]) { - isCanceledJob = true; - break; + for (uint8_t i = 0; i < jobs.size(); ++i) { + bool isCanceledJob = false; + for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) + { + if (i == cancelJobsId[cancelIndex]) { + isCanceledJob = true; + break; + } } + if (isCanceledJob == true) { + EXPECT_EQ(jobs[i]->WaitForEvent(MaxJobWaitTime * 3), ::Thunder::Core::ERROR_TIMEDOUT); + } else { + EXPECT_EQ(jobs[i]->WaitForEvent(MaxJobWaitTime * 4), ::Thunder::Core::ERROR_NONE); + usleep(100); + } + EXPECT_EQ(jobs[i]->IsIdle(), true); } - if (isCanceledJob == true) { - EXPECT_EQ(jobs[i]->WaitForEvent(MaxJobWaitTime * 3), Core::ERROR_TIMEDOUT); - } else { - EXPECT_EQ(jobs[i]->WaitForEvent(MaxJobWaitTime * 4), Core::ERROR_NONE); - usleep(100); - } - EXPECT_EQ(jobs[i]->IsIdle(), true); - } - uint8_t totalRuns = 0; + uint8_t totalRuns = 0; - Thunder::Core::ThreadPool::Metadata info[threadCount]; - std::vector jobsStrings; + ::Thunder::Core::ThreadPool::Metadata info[threadCount]; + std::vector jobsStrings; - threadPool.Snapshot(threadCount, info, jobsStrings); + threadPool.Snapshot(threadCount, info, jobsStrings); - for (uint8_t i = 0; i < threadCount; ++i) { - totalRuns += info[i].Runs; - } - EXPECT_EQ(totalRuns, (queueSize + additionalJobs - cancelJobsCount) * 2); + for (uint8_t i = 0; i < threadCount; ++i) { + totalRuns += info[i].Runs; + } + EXPECT_EQ(totalRuns, (queueSize + additionalJobs - cancelJobsCount) * 2); - threadPool.Stop(); + threadPool.Stop(); - for (auto& job: jobs) { - job.Release(); + for (auto& job: jobs) { + job.Release(); + } + jobs.clear(); } - jobs.clear(); -} -TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Reschedule_SinglePool_SingleJob) -{ - const uint16_t scheduledTimes[] = {1000, 1000}; - CheckThreadPool_JobType_Submit_Using_Reschedule(1, 1, 1, 0, nullptr, scheduledTimes); -} -TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Reschedule_SinglePool_SingleJob_CancelJobs) -{ - const uint8_t job = 0; - const uint16_t scheduledTimes[] = {2000}; - CheckThreadPool_JobType_Submit_Using_Reschedule(1, 1, 0, 1, &job, scheduledTimes); -} -TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Reschedule_SinglePool_MultipleJobs) -{ - const uint16_t scheduledTimes[] = {1000, 2000, 4000, 1000, 2000, 1000}; - CheckThreadPool_JobType_Submit_Using_Reschedule(1, 5, 1, 0, nullptr, scheduledTimes); -} -TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Reschedule_SinglePool_MultipleJobs_CancelJobs) -{ - const uint8_t jobs[] = {0, 2}; - const uint16_t scheduledTimes[] = {2000, 2000, 2000, 1000, 2000}; - CheckThreadPool_JobType_Submit_Using_Reschedule(1, 5, 0, sizeof(jobs), jobs, scheduledTimes); -} -TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Reschedule_MultiplePool_MultipleJobs) -{ - const uint16_t scheduledTimes[] = {3000, 2000, 1000, 1000, 3000, 1000}; - CheckThreadPool_JobType_Submit_Using_Reschedule(5, 5, 1, 0, nullptr, scheduledTimes); -} -TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Reschedule_MultiplePool_MultipleJobs_CancelJobs) -{ - const uint8_t jobs[] = {0, 2}; - const uint16_t scheduledTimes[] = {3000, 2000, 2000, 1000, 2000}; - CheckThreadPool_JobType_Submit_Using_Reschedule(5, 5, 0, sizeof(jobs), jobs, scheduledTimes); -} - -TEST(Core_ThreadPool, CheckThreadPool_JobType_Reschedule_AfterSubmit) -{ - uint8_t queueSize = 5; - uint8_t additionalJobs = 1; - uint8_t threadCount = 5; - const uint16_t scheduledTimes[] = {2000, 2000, 3000, 1000, 2000, 1000}; - ThreadPoolTester threadPool(threadCount, 0, queueSize); - EXPECT_EQ(threadPool.Count(), threadCount); - threadPool.Run(); - - std::vector> jobs; - // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs - for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { - jobs.push_back(Core::ProxyType(Core::ProxyType::Create())); + TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Reschedule_SinglePool_SingleJob) + { + const uint16_t scheduledTimes[] = {1000, 1000}; + CheckThreadPool_JobType_Submit_Using_Reschedule(1, 1, 1, 0, nullptr, scheduledTimes); + } + TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Reschedule_SinglePool_SingleJob_CancelJobs) + { + const uint8_t job = 0; + const uint16_t scheduledTimes[] = {2000}; + CheckThreadPool_JobType_Submit_Using_Reschedule(1, 1, 0, 1, &job, scheduledTimes); + } + TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Reschedule_SinglePool_MultipleJobs) + { + const uint16_t scheduledTimes[] = {1000, 2000, 4000, 1000, 2000, 1000}; + CheckThreadPool_JobType_Submit_Using_Reschedule(1, 5, 1, 0, nullptr, scheduledTimes); + } + TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Reschedule_SinglePool_MultipleJobs_CancelJobs) + { + const uint8_t jobs[] = {0, 2}; + const uint16_t scheduledTimes[] = {2000, 2000, 2000, 1000, 2000}; + CheckThreadPool_JobType_Submit_Using_Reschedule(1, 5, 0, sizeof(jobs), jobs, scheduledTimes); + } + TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Reschedule_MultiplePool_MultipleJobs) + { + const uint16_t scheduledTimes[] = {3000, 2000, 1000, 1000, 3000, 1000}; + CheckThreadPool_JobType_Submit_Using_Reschedule(5, 5, 1, 0, nullptr, scheduledTimes); + } + TEST(Core_ThreadPool, Check_ThreadPool_JobType_Submit_Using_Reschedule_MultiplePool_MultipleJobs_CancelJobs) + { + const uint8_t jobs[] = {0, 2}; + const uint16_t scheduledTimes[] = {3000, 2000, 2000, 1000, 2000}; + CheckThreadPool_JobType_Submit_Using_Reschedule(5, 5, 0, sizeof(jobs), jobs, scheduledTimes); } - for (uint8_t i = 0; i < jobs.size(); ++i) { - Core::ProxyType job; - EXPECT_EQ(jobs[i]->IsIdle(), true); - job = (jobs[i]->Submit()); - EXPECT_EQ(jobs[i]->IsIdle(), false); + TEST(Core_ThreadPool, CheckThreadPool_JobType_Reschedule_AfterSubmit) + { + uint8_t queueSize = 5; + uint8_t additionalJobs = 1; + uint8_t threadCount = 5; + const uint16_t scheduledTimes[] = {2000, 2000, 3000, 1000, 2000, 1000}; + ThreadPoolTester threadPool(threadCount, 0, queueSize); + EXPECT_EQ(threadPool.Count(), threadCount); + threadPool.Run(); + + std::vector<::Thunder::Core::ProxyType> jobs; + // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs + for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { + jobs.push_back(::Thunder::Core::ProxyType(::Thunder::Core::ProxyType::Create())); + } - // Try to get same job again - Core::ProxyType jobRetry = (jobs[i]->Reschedule(Core::Time::Now().Add(scheduledTimes[i]))); - EXPECT_EQ(jobs[i]->IsIdle(), false); - EXPECT_EQ(job.IsValid(), true); + for (uint8_t i = 0; i < jobs.size(); ++i) { + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> job; + EXPECT_EQ(jobs[i]->IsIdle(), true); + job = (jobs[i]->Submit()); + EXPECT_EQ(jobs[i]->IsIdle(), false); - if (job.IsValid() && (jobs[i]->IsIdle() != true)) { - if (threadPool.QueueIsFull() == false) { - threadPool.SubmitUsingSelfWorker(job); - } else { - EXPECT_EQ(threadPool.QueueIsFull(), true); - threadPool.SubmitUsingExternalWorker(job, Core::infinite); + // Try to get same job again + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> jobRetry = (jobs[i]->Reschedule(::Thunder::Core::Time::Now().Add(scheduledTimes[i]))); + EXPECT_EQ(jobs[i]->IsIdle(), false); + EXPECT_EQ(job.IsValid(), true); + + if (job.IsValid() && (jobs[i]->IsIdle() != true)) { + if (threadPool.QueueIsFull() == false) { + threadPool.SubmitUsingSelfWorker(job); + } else { + EXPECT_EQ(threadPool.QueueIsFull(), true); + threadPool.SubmitUsingExternalWorker(job, ::Thunder::Core::infinite); + } } } - } - sleep(2); - for (uint8_t i = 0; i < jobs.size(); ++i) { - EXPECT_EQ(jobs[i]->WaitForEvent(MaxJobWaitTime * 3), Core::ERROR_NONE); - usleep(500); - EXPECT_EQ(jobs[i]->IsIdle(), true); - } + sleep(2); + for (uint8_t i = 0; i < jobs.size(); ++i) { + EXPECT_EQ(jobs[i]->WaitForEvent(MaxJobWaitTime * 3), ::Thunder::Core::ERROR_NONE); + usleep(500); + EXPECT_EQ(jobs[i]->IsIdle(), true); + } - uint8_t totalRuns = 0; + uint8_t totalRuns = 0; - Thunder::Core::ThreadPool::Metadata info[threadCount]; - std::vector jobsStrings; + ::Thunder::Core::ThreadPool::Metadata info[threadCount]; + std::vector jobsStrings; - threadPool.Snapshot(threadCount, info, jobsStrings); + threadPool.Snapshot(threadCount, info, jobsStrings); - for (uint8_t i = 0; i < threadCount; ++i) { - totalRuns += info[i].Runs; - } - EXPECT_EQ(totalRuns, (queueSize + additionalJobs) * 2); + for (uint8_t i = 0; i < threadCount; ++i) { + totalRuns += info[i].Runs; + } + EXPECT_EQ(totalRuns, (queueSize + additionalJobs) * 2); - threadPool.Stop(); + threadPool.Stop(); - for (auto& job: jobs) { - job.Release(); - } - jobs.clear(); -} -TEST(Core_ThreadPool, CheckThreadPool_JobType_Reschedule_AfterIdle) -{ - uint8_t queueSize = 5; - uint8_t additionalJobs = 1; - uint8_t threadCount = 5; - const uint16_t scheduledTimes[] = {1000, 2000, 3000, 1000, 4000, 1000}; - ThreadPoolTester threadPool(threadCount, 0, queueSize); - EXPECT_EQ(threadPool.Count(), threadCount); - threadPool.Run(); - - std::vector> jobs; - // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs - for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { - jobs.push_back(Core::ProxyType(Core::ProxyType::Create())); + for (auto& job: jobs) { + job.Release(); + } + jobs.clear(); } + TEST(Core_ThreadPool, CheckThreadPool_JobType_Reschedule_AfterIdle) + { + uint8_t queueSize = 5; + uint8_t additionalJobs = 1; + uint8_t threadCount = 5; + const uint16_t scheduledTimes[] = {1000, 2000, 3000, 1000, 4000, 1000}; + ThreadPoolTester threadPool(threadCount, 0, queueSize); + EXPECT_EQ(threadPool.Count(), threadCount); + threadPool.Run(); + + std::vector<::Thunder::Core::ProxyType> jobs; + // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs + for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { + jobs.push_back(::Thunder::Core::ProxyType(::Thunder::Core::ProxyType::Create())); + } - for (uint8_t i = 0; i < jobs.size(); ++i) { - Core::ProxyType job; - EXPECT_EQ(jobs[i]->IsIdle(), true); - job = (jobs[i]->Submit()); - EXPECT_EQ(jobs[i]->IsIdle(), false); - - // Try to get same job again - Core::ProxyType jobRetry = (jobs[i]->Reschedule(Core::Time::Now().Add(scheduledTimes[i]))); - EXPECT_EQ(jobs[i]->IsIdle(), false); - EXPECT_EQ(job.IsValid(), true); + for (uint8_t i = 0; i < jobs.size(); ++i) { + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> job; + EXPECT_EQ(jobs[i]->IsIdle(), true); + job = (jobs[i]->Submit()); + EXPECT_EQ(jobs[i]->IsIdle(), false); - if (job.IsValid() && (jobs[i]->IsIdle() != true)) { - if (threadPool.QueueIsFull() == false) { - threadPool.SubmitUsingSelfWorker(job); - } else { - EXPECT_EQ(threadPool.QueueIsFull(), true); - threadPool.SubmitUsingExternalWorker(job, Core::infinite); + // Try to get same job again + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> jobRetry = (jobs[i]->Reschedule(::Thunder::Core::Time::Now().Add(scheduledTimes[i]))); + EXPECT_EQ(jobs[i]->IsIdle(), false); + EXPECT_EQ(job.IsValid(), true); + + if (job.IsValid() && (jobs[i]->IsIdle() != true)) { + if (threadPool.QueueIsFull() == false) { + threadPool.SubmitUsingSelfWorker(job); + } else { + EXPECT_EQ(threadPool.QueueIsFull(), true); + threadPool.SubmitUsingExternalWorker(job, ::Thunder::Core::infinite); + } } } - } - sleep(2); - for (uint8_t i = 0; i < jobs.size(); ++i) { - EXPECT_EQ(jobs[i]->WaitForEvent(MaxJobWaitTime * 3), Core::ERROR_NONE); - usleep(500); - EXPECT_EQ(jobs[i]->IsIdle(), true); - } + sleep(2); + for (uint8_t i = 0; i < jobs.size(); ++i) { + EXPECT_EQ(jobs[i]->WaitForEvent(MaxJobWaitTime * 3), ::Thunder::Core::ERROR_NONE); + usleep(500); + EXPECT_EQ(jobs[i]->IsIdle(), true); + } - uint8_t totalRuns = 0; + uint8_t totalRuns = 0; - Thunder::Core::ThreadPool::Metadata info[threadCount]; - std::vector jobsStrings; + ::Thunder::Core::ThreadPool::Metadata info[threadCount]; + std::vector jobsStrings; - threadPool.Snapshot(threadCount, info, jobsStrings); + threadPool.Snapshot(threadCount, info, jobsStrings); - for (uint8_t i = 0; i < threadCount; ++i) { - totalRuns += info[i].Runs; - } - EXPECT_EQ(totalRuns, (queueSize + additionalJobs) * 2); + for (uint8_t i = 0; i < threadCount; ++i) { + totalRuns += info[i].Runs; + } + EXPECT_EQ(totalRuns, (queueSize + additionalJobs) * 2); - threadPool.Stop(); + threadPool.Stop(); - for (auto& job: jobs) { - job.Release(); + for (auto& job: jobs) { + job.Release(); + } + jobs.clear(); } - jobs.clear(); -} +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_time.cpp b/Tests/unit/core/test_time.cpp index 3a3ca588e9..0f2ce9fb7a 100644 --- a/Tests/unit/core/test_time.cpp +++ b/Tests/unit/core/test_time.cpp @@ -27,2096 +27,2100 @@ #include -using namespace Thunder; -using namespace Thunder::Core; - -int32_t GetMachineTimeDifference(const string& zone) -{ - time_t defineTime = 1325376000; - setenv("TZ", zone.c_str(), 1); - tzset(); - struct tm *time = localtime(&defineTime); - return time->tm_gmtoff; -} - -std::string ExecuteCmd(const char* cmd) { - char buffer[128]; - std::string result = ""; - FILE* pipe = popen(cmd, "r"); - - EXPECT_TRUE(pipe != nullptr); +namespace Thunder { +namespace Tests { +namespace Core { + + int32_t GetMachineTimeDifference(const string& zone) + { + time_t defineTime = 1325376000; + setenv("TZ", zone.c_str(), 1); + tzset(); + struct tm *time = localtime(&defineTime); + return time->tm_gmtoff; + } + + std::string ExecuteCmd(const char* cmd) { + char buffer[128]; + std::string result = ""; + FILE* pipe = popen(cmd, "r"); + + EXPECT_TRUE(pipe != nullptr); #ifdef __CORE_EXCEPTION_CATCHING__ - try { + try { #endif - while (fgets(buffer, sizeof buffer, pipe) != NULL) { - result = buffer; - break; - } + while (fgets(buffer, sizeof buffer, pipe) != NULL) { + result = buffer; + break; + } #ifdef __CORE_EXCEPTION_CATCHING__ - } catch (...) { + } catch (...) { + pclose(pipe); + throw; + } +#endif pclose(pipe); - throw; + + return result; } -#endif - pclose(pipe); - - return result; -} -std::string GetSystemTime(bool local) -{ - - std::string command = std::string("date +\"%a, %d %b %Y %H:%M:%S\""); - command.append((local != true) ? " -u" : ""); - std::string systemTime = ExecuteCmd(command.c_str()); - systemTime.erase(remove(systemTime.begin(), systemTime.end(), '\n'), systemTime.end()); - systemTime.append((local != true) ? " GMT" : ""); - return systemTime; -} - -TEST(Core_Time, DISABLED_Ctor_TimeSpec) -{ + std::string GetSystemTime(bool local) + { + + std::string command = std::string("date +\"%a, %d %b %Y %H:%M:%S\""); + command.append((local != true) ? " -u" : ""); + std::string systemTime = ExecuteCmd(command.c_str()); + systemTime.erase(remove(systemTime.begin(), systemTime.end(), '\n'), systemTime.end()); + systemTime.append((local != true) ? " GMT" : ""); + return systemTime; + } + + TEST(Core_Time, DISABLED_Ctor_TimeSpec) + { #ifdef __POSIX__ - struct timespec ts; - timespec_get(&ts, TIME_UTC); - Time time(ts); + struct timespec ts; + timespec_get(&ts, TIME_UTC); + ::Thunder::Core::Time time(ts); - string local; - time.ToString(local, true); - string utc; - time.ToString(utc, false); + string local; + time.ToString(local, true); + string utc; + time.ToString(utc, false); - EXPECT_STREQ(local.c_str(), GetSystemTime(true).c_str()); - EXPECT_STREQ(utc.c_str(), GetSystemTime(false).c_str()); + EXPECT_STREQ(local.c_str(), GetSystemTime(true).c_str()); + EXPECT_STREQ(utc.c_str(), GetSystemTime(false).c_str()); #endif -} -TEST(Core_Time, Ctor_Copy) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - setenv("TZ", "Europe/Amsterdam", 1); - tzset(); - - Time time1; - Time orig(1969,11, 1, 9, 10, 11, 500, true); - EXPECT_EQ(orig.IsValid(), true); - time1 = orig; - EXPECT_EQ(time1.IsValid(), true); - Time time2(orig); - EXPECT_EQ(time2.IsValid(), true); - - string timeString; - EXPECT_EQ(orig.MilliSeconds(), 500u); - orig.ToString(timeString, true); - std::cout << "Localtime 1969-11-01 09:10:11.500 : " << timeString << " ms: " << orig.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Sat, 01 Nov 1969 09:10:11"); - orig.ToString(timeString, false); - std::cout << "UTC 1969-11-01 09:10:11.500 : " << timeString << " ms: " << orig.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Sat, 01 Nov 1969 08:10:11 GMT"); - - EXPECT_EQ(time1.MilliSeconds(), 500u); - time1.ToString(timeString, true); - std::cout << "Localtime 1969-11-01 09:10:11.500 : " << timeString << " ms: " << time1.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Sat, 01 Nov 1969 09:10:11"); - time1.ToString(timeString, false); - std::cout << "UTC 1969-11-01 09:10:11.500 : " << timeString << " ms: " << time1.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Sat, 01 Nov 1969 08:10:11 GMT"); - - EXPECT_EQ(time2.MilliSeconds(), 500u); - time2.ToString(timeString, true); - std::cout << "Localtime 1969-11-01 09:10:11.500 : " << timeString << " ms: " << time2.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Sat, 01 Nov 1969 09:10:11"); - time2.ToString(timeString, false); - std::cout << "UTC 1969-11-01 09:10:11.500 : " << timeString << " ms: " << time2.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Sat, 01 Nov 1969 08:10:11 GMT"); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, MilliSeconds) -{ - Time time(2000, 1, 2, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.MilliSeconds(), static_cast(21)); - time = Time(2004, 2, 29, 11, 30, 23, 100, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.MilliSeconds(), static_cast(100)); - time = Time(2000, 11, 2, 11, 30, 23, 823, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.MilliSeconds(), static_cast(823)); - time = Time(2000, 12, 2, 11, 30, 23, 999, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.MilliSeconds(), static_cast(999)); -} -TEST(Core_Time, MilliSeconds_LocalTimeEnabled) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "Europe/Amsterdam", 1); - tzset(); - - Time time(2000, 1, 2, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.MilliSeconds(), static_cast(21)); - time = Time(2000, 2, 28, 11, 30, 23, 100, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.MilliSeconds(), static_cast(100)); - time = Time(2000, 3, 2, 11, 30, 23, 923, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.MilliSeconds(), static_cast(923)); - time = Time(2000, 5, 2, 11, 30, 23, 999, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.MilliSeconds(), static_cast(999)); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, Seconds) -{ - Time time(2000, 1, 2, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Seconds(), 23); - time = Time(1970, 2, 24, 12, 45, 58, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Seconds(), 58); - time = Time(2000, 1, 24, 14, 1, 59, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Seconds(), 59); - time = Time(2021, 2, 28, 23, 15, 0, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Seconds(), 0); - time = Time(2021, 3, 31, 0, 6, 39, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Seconds(), 39); -} -TEST(Core_Time, Seconds_LocalTimeEnabled) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "Europe/Amsterdam", 1); - tzset(); - - Time time(2000, 1, 2, 11, 46, 6, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Seconds(), 6); - time = Time(1970, 2, 13, 12, 1, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Seconds(), 23); - time = Time(2000, 1, 2, 15, 59, 0, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Seconds(), 0); - time = Time(2021, 4, 30, 1, 30, 59, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Seconds(), 59); - time = Time(2021, 6, 3, 22, 59, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Seconds(), 23); - time = Time(2021, 11, 30, 23, 33, 18, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Seconds(), 18); - time = Time(2021, 7, 3, 22, 59, 0, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Seconds(), 0); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, Minutes) -{ - Time time(2000, 1, 2, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Minutes(), 30); - time = Time(1971, 12, 31, 12, 45, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Minutes(), 45); - time = Time(2021, 4, 30, 1, 30, 56, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Minutes(), 30); - time = Time(2021, 2, 6, 23, 1, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Minutes(), 1); - time = Time(2021, 2, 26, 22, 45, 45, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Minutes(), 45); - time = Time(1981, 1, 30, 23, 0, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Minutes(), 0); - time = Time(1981, 1, 30, 23, 0, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Minutes(), 0); -} -TEST(Core_Time, Minutes_LocalTimeEnabled) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "Europe/Amsterdam", 1); - tzset(); - - Time time(2000, 1, 2, 11, 30, 30, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Minutes(), 30); - time = Time(1971, 11, 1, 12, 0, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Minutes(), 0); - time = Time(2000, 1, 20, 15, 10, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Minutes(), 10); - time = Time(2021, 4, 30, 2, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Minutes(), 30); - time = Time(2021, 2, 28, 22, 0, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Minutes(), 0); - time = Time(2021, 2, 28, 22, 0, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Minutes(), 0); - time = Time(2021, 2, 3, 23, 34, 18, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Minutes(), 34); - time = Time(1981, 1, 31, 23, 59, 59, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Minutes(), 59); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, Hours) -{ - Time time(2000, 1, 2, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Hours(), 11); - time = Time(1972, 2, 29, 12, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Hours(), 12); - time = Time(2000, 1, 26, 14, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Hours(), 14); - time = Time(2021, 4, 30, 0, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Hours(), 0); - time = Time(2021, 5, 31, 23, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Hours(), 23); - time = Time(2021, 6, 30, 0, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Hours(), 0); - time = Time(1981, 1, 17, 0, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Hours(), 0); -} -TEST(Core_Time, Hours_LocalTimeEnabled) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "Europe/Amsterdam", 1); - tzset(); - - Time time(2000, 1, 2, 11, 56, 46, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Hours(), 10); - time = Time(1971, 9, 12, 12, 10, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Hours(), 11); - time = Time(2000, 2, 29, 15, 10, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Hours(), 14); - time = Time(2021, 5, 28, 23, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Hours(), 21); - time = Time(2021, 5, 28, 0, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Hours(), 22); - time = Time(2021, 1, 10, 22, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Hours(), 21); - time = Time(2021, 7, 31, 1, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Hours(), 23); - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, Day) -{ - Time time(2000, 1, 2, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Day(), 2); - time = Time(1971, 2, 25, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Day(), 25); - time = Time(2000, 4, 30, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Day(), 30); - time = Time(2021, 2, 28, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Day(), 28); - time = Time(2021, 5, 31, 20, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Day(), 31); - time = Time(1981, 1, 31, 23, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Day(), 31); -} -TEST(Core_Time, Day_LocalTimeEnabled) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "Europe/Amsterdam", 1); - tzset(); - - Time time(2000, 1, 4, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Day(), 4); - time = Time(1976, 2, 29, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Day(), 29); - time = Time(2000, 1, 31, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Day(), 31); - time = Time(2021, 4, 30, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Day(), 30); - time = Time(2021, 2, 28, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Day(), 28); - time = Time(1981, 6, 24, 23, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Day(), 24); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, WeekDayName) -{ - Time time(2000, 1, 2, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.WeekDayName(), "Sun"); - time = Time(1971, 2, 1, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.WeekDayName(), "Mon"); - time = Time(2000, 3, 25, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.WeekDayName(), "Sat"); - time = Time(2021, 4, 28, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.WeekDayName(), "Wed"); - time = Time(2024, 2, 29, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.WeekDayName(), "Thu"); - time = Time(1981, 7, 13, 1, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.WeekDayName(), "Mon"); -} -TEST(Core_Time, WeekDayName_LocalTimeEnabled) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - Time time(2000, 1, 3, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.WeekDayName(), "Mon"); - time = Time(1971, 2, 2, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.WeekDayName(), "Tue"); - time = Time(2000, 3, 31, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.WeekDayName(), "Fri"); - time = Time(2021, 4, 30, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.WeekDayName(), "Fri"); - time = Time(2021, 2, 28, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.WeekDayName(), "Sun"); - time = Time(1981, 1, 31, 23, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.WeekDayName(), "Sat"); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, Month) -{ - Time time(2000, 1, 1, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Month(), 1); - time = Time(1971, 2, 2, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Month(), 2); - time = Time(2000, 3, 31, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Month(), 3); - time = Time(2021, 4, 30, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Month(), 4); - time = Time(2021, 7, 28, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Month(), 7); - time = Time(1981, 11, 30, 23, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Month(), 11); -} -TEST(Core_Time, Month_LocalTimeEnabled) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "Europe/Amsterdam", 1); - tzset(); - - Time time(2000, 9, 1, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Month(), 9); - time = Time(1971, 1, 2, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Month(), 1); - time = Time(2000, 8, 30, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Month(), 8); - time = Time(2021, 11, 28, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Month(), 11); - time = Time(2021, 6, 30, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Month(), 6); - time = Time(1981, 12, 31, 23, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Month(), 12); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, MonthName) -{ - Time time(2000, 1, 1, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.MonthName(), "Jan"); - time = Time(1971, 3, 2, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.MonthName(), "Mar"); - time = Time(2000, 5, 31, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.MonthName(), "May"); - time = Time(2021, 4, 30, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.MonthName(), "Apr"); - time = Time(2021, 1, 12, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.MonthName(), "Jan"); - time = Time(1983, 6, 30, 22, 59, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.MonthName(), "Jun"); - time = Time(1981, 7, 27, 23, 59, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.MonthName(), "Jul"); -} -TEST(Core_Time, MonthName_LocalTimeEnabled) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "Europe/Amsterdam", 1); - tzset(); - - Time time(2000, 1, 31, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.MonthName(), "Jan"); - time = Time(1971, 2, 28, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.MonthName(), "Feb"); - time = Time(2000, 8, 10, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.MonthName(), "Aug"); - time = Time(2021, 9, 30, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.MonthName(), "Sep"); - time = Time(2021, 10, 31, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.MonthName(), "Oct"); - time = Time(1981, 11, 26, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.MonthName(), "Nov"); - time = Time(1990, 12, 31, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_STREQ(time.MonthName(), "Dec"); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, Year) -{ - Time time(2000, 1, 1, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Year(), static_cast(2000)); - time = Time(1971, 2, 28, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Year(), static_cast(1971)); - time = Time(2000, 4, 10, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Year(), static_cast(2000)); - time = Time(2021, 6, 30, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Year(), static_cast(2021)); - time = Time(2022, 12, 31, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Year(), static_cast(2022)); - time = Time(1981, 9, 14, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Year(), static_cast(1981)); -} -TEST(Core_Time, Year_LocalTimeEnabled) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "Europe/Amsterdam", 1); - tzset(); - - Time time(2000, 3, 1, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Year(), static_cast(2000)); - time = Time(1971, 5, 25, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Year(), static_cast(1971)); - time = Time(2002, 7, 20, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Year(), static_cast(2002)); - time = Time(2021, 8, 30, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Year(), static_cast(2021)); - time = Time(2025, 12, 31, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Year(), static_cast(2025)); - time = Time(1981, 10, 10, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.Year(), static_cast(1981)); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, DayOfYear) -{ - Time time(2000, 1, 1, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfYear(), 0); - time = Time(2000, 2, 28, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfYear(), 58); - time = Time(2000, 3, 25, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfYear(), 84); - time = Time(2000, 4, 30, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfYear(), 120); - time = Time(2000, 5, 31, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfYear(), 151); - time = Time(2000, 6, 30, 11, 30, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfYear(), 181); -} -TEST(Core_Time, DayOfYear_LocalTimeEnabled) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "Europe/Amsterdam", 1); - tzset(); - - Time time(2002, 7, 1, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfYear(), 181); - time = Time(2000, 8, 10, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfYear(), 222); - time = Time(2000, 9, 25, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfYear(), 268); - time = Time(2000, 10, 29, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfYear(), 302); - time = Time(2000, 11, 30, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfYear(), 334); - time = Time(2000, 12, 6, 11, 30, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfYear(), 340); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, DayOfWeek) -{ - // Thu Jan 1 01:01:01 2004 - Time time(2004, 1, 1, 1, 1, 1, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfWeek(), 4); - // Thu Jan 1 11:30:24 2004 - time = Time(2004, 1, 1, 11, 30, 24, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfWeek(), 4); - // Thu Jun 20 20:20:22 2019 - time = Time(2019, 6, 20, 20, 20, 22, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfWeek(), 4); - // Mon Jul 1 13:40:33 2019 - time = Time(2019, 5, 31, 13, 40, 33, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfWeek(), 5); - // Mon Aug 31 11:50:31 2015 - time = Time(2015, 8, 31, 11, 50, 31, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfWeek(), 1); - // Tue Sep 1 11:50:23 2015 - time = Time(2015, 8, 31, 11, 50, 23, 21, false); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfWeek(), 1); -} -TEST(Core_Time, DayOfWeek_LocalTimeEnabled) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "Europe/Amsterdam", 1); - tzset(); - - // Thu Jan 1 01:01:01 2004 - Time time(2004, 1, 1, 1, 1, 1, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfWeek(), 4); - // Thu Jan 1 11:30:24 2004 - time = Time(2004, 5, 1, 11, 30, 24, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfWeek(), 6); - // Thu Jun 20 20:20:22 2019 - time = Time(2019, 6, 20, 20, 20, 22, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfWeek(), 4); - // Mon Jul 1 13:40:33 2019 - time = Time(2019, 7, 31, 13, 40, 33, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfWeek(), 3); - // Mon Aug 31 11:50:31 2015 - time = Time(2015, 8, 31, 11, 50, 31, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfWeek(), 1); - // Tue Sep 1 11:50:23 2015 - time = Time(2015, 9, 30, 11, 50, 23, 21, true); - EXPECT_EQ(time.IsValid(), true); - EXPECT_EQ(time.DayOfWeek(), 3); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, Ctor_TimeValues_InvalidValues) -{ - Time time(2000, 1, 2, 11, 30, 23, 1000, false); - EXPECT_EQ(time.IsValid(), false); - time = Time(2000, 1, 2, 11, 30, 67, 21, false); - EXPECT_EQ(time.IsValid(), false); - time = Time(2000, 1, 2, 11, 100, 23, 21, false); - EXPECT_EQ(time.IsValid(), false); - time = Time(2000, 1, 2, 25, 30, 23, 10, false); - EXPECT_EQ(time.IsValid(), false); - time = Time(2000, 1, 32, 11, 30, 6, 21, false); - EXPECT_EQ(time.IsValid(), false); - time = Time(2000, 1, 0, 11, 30, 23, 100, false); - EXPECT_EQ(time.IsValid(), false); - time = Time(2001, 2, 29, 11, 30, 23, 100, false); - EXPECT_EQ(time.IsValid(), false); - time = Time(2004, 2, 30, 11, 30, 23, 100, false); - EXPECT_EQ(time.IsValid(), false); - time = Time(2003, 6, 31, 11, 30, 23, 100, false); - EXPECT_EQ(time.IsValid(), false); - time = Time(2000, 15, 2, 11, 1, 23, 21, false); - EXPECT_EQ(time.IsValid(), false); - time = Time(2000, 0, 2, 11, 1, 23, 21, false); - EXPECT_EQ(time.IsValid(), false); - time = Time(1821, 1, 2, 11, 60, 23, 100, false); - EXPECT_EQ(time.IsValid(), false); - time = Time(1871, 1, 2, 11, 0, 60, 100, false); - EXPECT_EQ(time.IsValid(), false); - time = Time(1871, 1, 2, 24, 0, 35, 100, false); - EXPECT_EQ(time.IsValid(), false); - -} -TEST(Core_Time, Ctor_TimeValues_LocalTimeEnabled_InvalidValues) -{ - Time time(2000, 1, 2, 11, 30, 23, 1000, true); - EXPECT_EQ(time.IsValid(), false); - time = Time(2000, 1, 2, 11, 30, 60, 21, true); - EXPECT_EQ(time.IsValid(), false); - time = Time(2000, 1, 2, 11, 30, 67, 21, true); - EXPECT_EQ(time.IsValid(), false); - time = Time(2000, 1, 2, 11, 60, 23, 21, true); - EXPECT_EQ(time.IsValid(), false); - time = Time(2000, 1, 2, 11, 100, 23, 21, true); - EXPECT_EQ(time.IsValid(), false); - time = Time(2000, 1, 2, 24, 30, 23, 10, true); - EXPECT_EQ(time.IsValid(), false); - time = Time(2000, 1, 32, 11, 30, 6, 21, true); - EXPECT_EQ(time.IsValid(), false); - time = Time(1921, 1, 0, 11, 30, 23, 100, true); - EXPECT_EQ(time.IsValid(), false); - time = Time(1923, 2, 29, 11, 30, 23, 100, true); - EXPECT_EQ(time.IsValid(), false); - time = Time(2000, 15, 2, 11, 1, 23, 21, true); - EXPECT_EQ(time.IsValid(), false); - time = Time(2000, 0, 2, 11, 1, 23, 21, true); - EXPECT_EQ(time.IsValid(), false); - time = Time(2000, 9, 31, 11, 1, 23, 21, true); - EXPECT_EQ(time.IsValid(), false); - time = Time(1821, 1, 2, 24, 30, 23, 100, true); - EXPECT_EQ(time.IsValid(), false); -} -TEST(Core_Time, FromString_CurrentTime) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - Time time(Time::Now()); - std::string timeString1, timeString2; - time.ToString(timeString1); - - // LocalTime default (true) - EXPECT_EQ(time.FromString(timeString1), true); - time.ToString(timeString2); - EXPECT_STREQ(timeString1.c_str(), timeString2.c_str()); - // LocalTime true - EXPECT_EQ(time.FromString(timeString2, true), true); - time.ToString(timeString1); - EXPECT_STREQ(timeString2.c_str(), timeString1.c_str()); - - // LocalTime false - EXPECT_EQ(time.FromString(timeString1, false), true); - time.ToString(timeString1); - EXPECT_EQ(time.FromString(timeString2, false), true); - time.ToString(timeString2); - EXPECT_STREQ(timeString1.c_str(), timeString2.c_str()); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, FromString_TimeCtor) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - Time orig(1969,10, 3, 10, 11, 12, 666, true); - string timeString; - orig.ToString(timeString, true); - - Time time1; - time1.FromString(timeString, true); - orig.ToString(timeString, false); - - Time time2; - time2.FromString(timeString, false); - - EXPECT_EQ(orig.MilliSeconds(), 666u); - orig.ToString(timeString, true); - std::cout << "Localtime 1969-10-03 10:11:12 666 : " << timeString << " ms: " << orig.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Fri, 03 Oct 1969 10:11:12"); - orig.ToString(timeString, false); - std::cout << "UTC 1969-10-03 10:11:12 666 : " << timeString << " ms: " << orig.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Fri, 03 Oct 1969 10:11:12 GMT"); - - time1.ToString(timeString, true); - std::cout << "Localtime 1969-10-03 10:11:12 666 : " << timeString << " ms: " << time1.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Fri, 03 Oct 1969 10:11:12"); - time1.ToString(timeString, false); - std::cout << "UTC 1969-10-03 10:11:12 666 : " << timeString << " ms: " << time1.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Fri, 03 Oct 1969 10:11:12 GMT"); - - time2.ToString(timeString, true); - std::cout << "LocalTime 1969-10-03 10:11:12 666 : " << timeString << " ms: " << time2.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Fri, 03 Oct 1969 10:11:12"); - time2.ToString(timeString, false); - std::cout << "UTC 1969-10-03 10:11:12 666 : " << timeString << " ms: " << time2.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Fri, 03 Oct 1969 10:11:12 GMT"); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, FromString_ANSI) -{ - Time time; - std::string timeString; - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - // LocalTime true - EXPECT_EQ(time.FromString("Sun Nov 6 08:49:37 1994", true), true); - time.ToString(timeString); - EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 08:49:37"); - // LocalTime false - EXPECT_EQ(time.FromString("Sun Nov 6 12:49:37 1994", false), true); - time.ToString(timeString); - EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 12:49:37"); - - // Check time difference after set time zone to GST - setenv("TZ", "GST", 1); - tzset(); - EXPECT_EQ(time.FromString("Sun Nov 6 12:49:37 1994", false), true); - time.ToString(timeString); - EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 12:49:37"); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, FromString_ISO8601) -{ - Time time; - std::string timeString; - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - // LocalTime true - EXPECT_EQ(time.FromString("1994-11-06T08:49:37Z", true), true); - time.ToString(timeString); - EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 08:49:37"); - // LocalTime false - EXPECT_EQ(time.FromString("1994-11-06T08:49:37Z", false), true); - time.ToString(timeString); - EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 08:49:37"); - - // Check time difference after set time zone to GST - setenv("TZ", "GST", 1); - tzset(); - - // LocalTime true - EXPECT_EQ(time.FromString("1994-11-06T08:49:37Z", true), true); - time.ToString(timeString); - EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 08:49:37"); - // LocalTime false - EXPECT_EQ(time.FromString("1994-11-06T08:49:37Z", false), true); - time.ToString(timeString); - EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 08:49:37"); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, FromString_RFC1036) -{ - Time time; - std::string timeString; - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - // LocalTime true - EXPECT_EQ(time.FromString("Sunday, 06-Nov-94 08:49:37 GMT", true), true); - time.ToString(timeString); - EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 08:49:37"); - - // LocalTime false - EXPECT_EQ(time.FromString("Sunday, 06-Nov-94 08:49:37 GMT", false), true); - time.ToString(timeString); - EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 08:49:37"); - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, FromString_RFC1123) -{ - Time time; - std::string timeString; - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - // LocalTime true - EXPECT_EQ(time.FromString("Sun, 06 Nov 1994 08:49:37 GMT", true), true); - time.ToString(timeString); - EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 08:49:37"); - // LocalTime false - EXPECT_EQ(time.FromString("Sun, 06 Nov 1994 08:49:37 GMT", false), true); - time.ToString(timeString); - EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 08:49:37"); - - // Check time difference after set time zone to GST - setenv("TZ", "GST", 1); - tzset(); - - // LocalTime true - EXPECT_EQ(time.FromString("Sun, 06 Nov 1994 08:49:37 GMT", true), true); - time.ToString(timeString); - EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 08:49:37"); - // LocalTime false - EXPECT_EQ(time.FromString("Sun, 06 Nov 1994 12:49:37 GMT", false), true); - time.ToString(timeString); - EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 12:49:37"); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, FromStandard_ANSI_ValidFormat) -{ - Time time(Time::Now()); - EXPECT_EQ(time.FromANSI("Thu Aug11 23:47:20 2010", true), true); - EXPECT_EQ(time.FromANSI("Sun Sep 02 23:47:20 2012", false), true); - EXPECT_EQ(time.FromANSI("Sat Jul 13 23:47:20 2012", true), true); - EXPECT_EQ(time.FromANSI("Sun Jun3 3:47:20 2012", false), true); - EXPECT_EQ(time.FromANSI("Sun Jan01 23:7:20 2012", false), true); - EXPECT_EQ(time.FromANSI("Thu Nov22 23:47:0 2012", true), true); - EXPECT_EQ(time.FromANSI("Fri May 11 23:47:20 2012", false), true); - EXPECT_EQ(time.FromANSI("Fri Apr06 3:7:0 2012", true), true); - - EXPECT_EQ(time.FromANSI("Thu Mar08 23:47:20 2012 GMT", false), true); - EXPECT_EQ(time.FromANSI("Thu Mar08 23:47:20 2012 GMT", true), true); - EXPECT_EQ(time.FromANSI("Sun Feb05 23:47:20 2012 UTC", false), true); - EXPECT_EQ(time.FromANSI("Sun Feb05 23:47:20 2012 UTC", true), true); -} -TEST(Core_Time, FromStandard_ANSI_InvalidFormat) -{ - Time time(Time::Now()); - std::string timeString; - time.ToString(timeString); - // ToString is in RFC1123 format, hence it should fail - EXPECT_EQ(time.FromANSI(timeString, true), false); - EXPECT_EQ(time.FromANSI(timeString, false), false); - - EXPECT_EQ(time.FromANSI("1994Jan06T0a:49:37.123+06:45", true), false); - EXPECT_EQ(time.FromANSI("SAT Jan06T0a:49:37.123+06:45", false), false); - EXPECT_EQ(time.FromANSI("Sunday Feb06T08:4a:37.123+06:45", true), false); - EXPECT_EQ(time.FromANSI("Tues Mar0aT08:49:5a.123+06:45", true), false); - EXPECT_EQ(time.FromANSI("TMar0608:49:5a.123+06:45", true), false); - EXPECT_EQ(time.FromANSI("19Mar0608:49:5a.123+06:45", true), false); - EXPECT_EQ(time.FromANSI("No1v0608:49:5.123+06:45 UTC", true), false); - EXPECT_EQ(time.FromANSI("No0608:49:5.123+06:45 UTC", true), false); - EXPECT_EQ(time.FromANSI(" Sun Jan 8 TEST08:49:37.123+06:45", true), false); - EXPECT_EQ(time.FromANSI("Sun 0608:49:37.803+06:45", true), false); - EXPECT_EQ(time.FromANSI("Mon MarTEST0608:49:5a.123+06:45", true), false); - EXPECT_EQ(time.FromANSI("Sun Mar608:49:5TEST.123+06:45", true), false); - EXPECT_EQ(time.FromANSI("Sun Mar608:49:5.123+06:45 TEST GMT", true), false); -} -TEST(Core_Time, FromStandard_ISO8601_ValidFormat) -{ - Time time(Time::Now()); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37"), true); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37Z"), true); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37+01"), true); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37+06:45"), true); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37+06:45 GMT"), true); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37+06:45 UTC"), true); - EXPECT_EQ(time.FromISO8601("1994-11-06T8:49:37+06:45"), true); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:9:37+06:45"), true); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:7+06:45"), true); - EXPECT_EQ(time.FromISO8601("2094-11-06T08:49:37+06:45"), true); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37+06:45"), true); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123"), true); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123Z"), true); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123+01"), true); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123+06 45"), true); - EXPECT_EQ(time.FromISO8601("1994-12-06T08:49:37.123 06:45"), true); -} -TEST(Core_Time, FromStandard_ISO8601_InvalidFormat) -{ - Time time(Time::Now()); - std::string timeString; - // ToString is in RFC1123 format, hence it should fail - EXPECT_EQ(time.FromISO8601(timeString), false); - EXPECT_EQ(time.FromISO8601("1994-13-06T08:49:37.123+06:45"), false); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123-06:: 45"), false); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37."), false); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123+06- 45"), false); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123+24:45"), false); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123+24:4"), false); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123+06:45:"), false); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123+"), false); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123a"), false); - EXPECT_EQ(time.FromISO8601("1994-11-06 T08:49:37.123a"), false); - EXPECT_EQ(time.FromISO8601("1994-11-06T 08:49:37.123a"), false); - EXPECT_EQ(time.FromISO8601("1994-11-0608:49:37+06:45"), false); - EXPECT_EQ(time.FromISO8601("1994-Jan-06T08:49:37.123a"), false); - EXPECT_EQ(time.FromISO8601("94-11-06T08:49:37+06:45"), false); - EXPECT_EQ(time.FromISO8601("100-11-06T08:49:37.123a"), false); - EXPECT_EQ(time.FromISO8601("1000-11-06T08:49:37.123a"), false); - EXPECT_EQ(time.FromISO8601("1994-Apr-06T08:49:37+06:45"), false); - EXPECT_EQ(time.FromISO8601("1994-April-06T08:49:37+06:45"), false); -} -TEST(Core_Time, FromStandard_RFC1036_ValidFormat) -{ - Time time(Time::Now()); - - EXPECT_EQ(time.FromRFC1036("Sunday, 06-Nov-94 08:49:37 GMT"), true); - EXPECT_EQ(time.FromRFC1036("Sunday, 06-Nov-1994 08:49:37 GMT"), true); - EXPECT_EQ(time.FromRFC1036("Sunday, 06-Nov-1994 08:49:37 UTC"), true); - EXPECT_EQ(time.FromRFC1036("Sunday, 06-Nov-1994 08:49:37"), true); - EXPECT_EQ(time.FromRFC1036("Monday, 7-Nov-94 08:49:37"), true); - EXPECT_EQ(time.FromRFC1036("Monday, 7-Nov-94 8:09:07"), true); - EXPECT_EQ(time.FromRFC1036("Monday, 7-Nov-94 8:9:07"), true); - EXPECT_EQ(time.FromRFC1036("Monday, 7-Nov-94 8:09:7 "), true); - EXPECT_EQ(time.FromRFC1036("Monday, 7-Nov-94 8:09:7"), true); - EXPECT_EQ(time.FromRFC1036("Monday, 7-Nov-94 8:9:7 "), true); - EXPECT_EQ(time.FromRFC1036("Monday, 7-Nov-94 8:9:7 GMT"), true); - EXPECT_EQ(time.FromRFC1036("Monday, 7-Nov-94 8:9:7 GMT "), true); - EXPECT_EQ(time.FromRFC1036("Monday, 7-Nov-94 8:9:7 UTC"), true); - EXPECT_EQ(time.FromRFC1036("Monday, 7-Apr-94 8:9:7 GMT"), true); - EXPECT_EQ(time.FromRFC1036("Monday, 7-Nov-94 8:9:7"), true); - EXPECT_EQ(time.FromRFC1036("Sunday, 06-Nov-1994 08:49:37 PDT"), true); -} -TEST(Core_Time, FromStandard_RFC1036_InvalidFormat) -{ - Time time(Time::Now()); - std::string timeString; - time.ToString(timeString, true); - - // ToString is in RFC1123 format, hence it should fail - EXPECT_EQ(time.FromRFC1036(timeString), false); - - EXPECT_EQ(time.FromRFC1036("Wed, 27 Oct 2021 00:05:01 "), false); - EXPECT_EQ(time.FromRFC1036("Sunday, 06Nov94 08:49:37 GMT"), false); - EXPECT_EQ(time.FromRFC1036("Sunday, 06:Nov:94 08:49:37 GMT"), false); - EXPECT_EQ(time.FromRFC1036("1994-06-Nov 08:49:37 GMT"), false); - EXPECT_EQ(time.FromRFC1036("Sunday, 1994-06-Nov 08:49:37 GMT"), false); - EXPECT_EQ(time.FromRFC1036("19941105T08:49:37.123+06:45"), false); - EXPECT_EQ(time.FromRFC1036("Sunday, 06-Nov-1994 08:TEST49:37"), false); - EXPECT_EQ(time.FromRFC1036("Sunday, 06-Nov-1994 08:49:TEST37"), false); - EXPECT_EQ(time.FromRFC1036("1994-11-06T08:49:37.123+06:45"), false); - EXPECT_EQ(time.FromRFC1036("1994-11-Jan-08:49:07+06:45"), false); - EXPECT_EQ(time.FromRFC1036("1994Jan07T08:49:37.123+06:45"), false); - EXPECT_EQ(time.FromRFC1036("1994-Jan-09T08:49:37.123+06:45"), false); - EXPECT_EQ(time.FromRFC1036("Monday, 07-November-2014 08:49:37 GMT"), false); - EXPECT_EQ(time.FromRFC1036("XXXX,06-Nov-08:11:49:37 "), false); - EXPECT_EQ(time.FromRFC1036("XXXX-06-Nov-08:11:49:37 "), false); - EXPECT_EQ(time.FromRFC1036("XXXX:06-Nov-08:11:49:37 "), false); - EXPECT_EQ(time.FromRFC1036("XXXX, 06-Nov-08:11:49:37 "), false); - EXPECT_EQ(time.FromRFC1036("Sunday, 06-Nov-TEST1994 08:49:37"), false); - EXPECT_EQ(time.FromRFC1036("Sunday, TEST06-Nov-1994 08:49:37"), false); - EXPECT_EQ(time.FromRFC1036("Sunday, 06-Nov-1994 TEST08:49:37"), false); -} -TEST(Core_Time, FromStandard_RFC1123_ValidFormat) -{ - Time time; - EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08:49:37 GMT"), true); - EXPECT_EQ(time.FromRFC1123("Sun,06Nov199408:49:37GMT"), true); - EXPECT_EQ(time.FromRFC1123("Sun,06Nov199408:49:37"), true); - EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08:59:27"), true); - EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08:59:27 "), true); - EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08:59:27 FF "), true); - EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08:59:27 GMT"), true); -} -TEST(Core_Time, FromStandard_RFC1123_InvalidFormat) -{ - Time time; - EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 ff 08:49:37 GMT"), false); - EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994ff 08:49:37 GMT"), false); - EXPECT_EQ(time.FromRFC1123("1994Jan06T08:49:37.123+06:45"), false); - EXPECT_EQ(time.FromRFC1123("1994Jan0aT08:49:37.123+06:45"), false); - EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 0f:49:37 GMT"), false); - EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08f:49:37 GMT"), false); - EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08:ff49:37 GMT"), false); - EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08:49f:37 GMT"), false); - EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08:49:f37 GMT"), false); - EXPECT_EQ(time.FromRFC1123("Sun, 06-Nov-1994 08:49:37 GMT"), false); - EXPECT_EQ(time.FromRFC1123("06Nov1994:::08:49:37"), false); - EXPECT_EQ(time.FromRFC1123("Sun,Nov1994:::08:49:37"), false); - EXPECT_EQ(time.FromRFC1123("06 Nov 1994 08:59:27 GMT"), false); - EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994:08:49:37 GMT"), false); - EXPECT_EQ(time.FromRFC1123("Sun,06Nov1994TEST8:49:37"), false); - EXPECT_EQ(time.FromRFC1123("Sun,06Nov1994TEST8:49:37"), false); - EXPECT_EQ(time.FromRFC1123("Sund, 06 Nov 1994 08:49:37 GMT"), false); - EXPECT_EQ(time.FromRFC1123("TEST, 06 Nov 1994 08:49:37 GMT"), false); - EXPECT_EQ(time.FromRFC1123("Sun, TEST 06 Nov 1994 08:49:37 GMT"), false); - EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov TEST 1994 08:49:37 GMT"), false); - EXPECT_EQ(time.FromRFC1123("Sunday, 06 Nov 1994 08:59:27 GMT"), false); -} -TEST(Core_Time, FromStandard_RFC1123_TimeStringCreatedFromTime) -{ - Time time = Time(2018, 1, 23, 11, 30, 23, 21, false); - std::string timeString; - time.ToString(timeString, false); - time.FromRFC1123(timeString); - EXPECT_STREQ(timeString.c_str(), _T("Tue, 23 Jan 2018 11:30:23 GMT")); - - time = Time(2018, 2, 23, 11, 30, 23, 21, false); - time.ToString(timeString, false); - time.FromRFC1123(timeString); - EXPECT_STREQ(timeString.c_str(), _T("Fri, 23 Feb 2018 11:30:23 GMT")); - - time = Time(2018, 3, 23, 11, 30, 23, 21, false); - time.ToString(timeString, false); - time.FromRFC1123(timeString); - EXPECT_STREQ(timeString.c_str(), _T("Fri, 23 Mar 2018 11:30:23 GMT")); - - time = Time(2018, 4, 23, 11, 30, 23, 21, false); - time.ToString(timeString, false); - time.FromRFC1123(timeString); - EXPECT_STREQ(timeString.c_str(), _T("Mon, 23 Apr 2018 11:30:23 GMT")); - - time = Time(2018, 5, 23, 11, 30, 23, 21, false); - time.ToString(timeString, false); - time.FromRFC1123(timeString); - EXPECT_STREQ(timeString.c_str(), _T("Wed, 23 May 2018 11:30:23 GMT")); + } + TEST(Core_Time, Ctor_Copy) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + setenv("TZ", "Europe/Amsterdam", 1); + tzset(); + + ::Thunder::Core::Time time1; + ::Thunder::Core::Time orig(1969,11, 1, 9, 10, 11, 500, true); + EXPECT_EQ(orig.IsValid(), true); + time1 = orig; + EXPECT_EQ(time1.IsValid(), true); + ::Thunder::Core::Time time2(orig); + EXPECT_EQ(time2.IsValid(), true); + + string timeString; + EXPECT_EQ(orig.MilliSeconds(), 500u); + orig.ToString(timeString, true); + std::cout << "Localtime 1969-11-01 09:10:11.500 : " << timeString << " ms: " << orig.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Sat, 01 Nov 1969 09:10:11"); + orig.ToString(timeString, false); + std::cout << "UTC 1969-11-01 09:10:11.500 : " << timeString << " ms: " << orig.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Sat, 01 Nov 1969 08:10:11 GMT"); + + EXPECT_EQ(time1.MilliSeconds(), 500u); + time1.ToString(timeString, true); + std::cout << "Localtime 1969-11-01 09:10:11.500 : " << timeString << " ms: " << time1.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Sat, 01 Nov 1969 09:10:11"); + time1.ToString(timeString, false); + std::cout << "UTC 1969-11-01 09:10:11.500 : " << timeString << " ms: " << time1.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Sat, 01 Nov 1969 08:10:11 GMT"); + + EXPECT_EQ(time2.MilliSeconds(), 500u); + time2.ToString(timeString, true); + std::cout << "Localtime 1969-11-01 09:10:11.500 : " << timeString << " ms: " << time2.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Sat, 01 Nov 1969 09:10:11"); + time2.ToString(timeString, false); + std::cout << "UTC 1969-11-01 09:10:11.500 : " << timeString << " ms: " << time2.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Sat, 01 Nov 1969 08:10:11 GMT"); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, MilliSeconds) + { + ::Thunder::Core::Time time(2000, 1, 2, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.MilliSeconds(), static_cast(21)); + time = ::Thunder::Core::Time(2004, 2, 29, 11, 30, 23, 100, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.MilliSeconds(), static_cast(100)); + time = ::Thunder::Core::Time(2000, 11, 2, 11, 30, 23, 823, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.MilliSeconds(), static_cast(823)); + time = ::Thunder::Core::Time(2000, 12, 2, 11, 30, 23, 999, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.MilliSeconds(), static_cast(999)); + } + TEST(Core_Time, MilliSeconds_LocalTimeEnabled) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "Europe/Amsterdam", 1); + tzset(); + + ::Thunder::Core::Time time(2000, 1, 2, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.MilliSeconds(), static_cast(21)); + time = ::Thunder::Core::Time(2000, 2, 28, 11, 30, 23, 100, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.MilliSeconds(), static_cast(100)); + time = ::Thunder::Core::Time(2000, 3, 2, 11, 30, 23, 923, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.MilliSeconds(), static_cast(923)); + time = ::Thunder::Core::Time(2000, 5, 2, 11, 30, 23, 999, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.MilliSeconds(), static_cast(999)); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, Seconds) + { + ::Thunder::Core::Time time(2000, 1, 2, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Seconds(), 23); + time = ::Thunder::Core::Time(1970, 2, 24, 12, 45, 58, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Seconds(), 58); + time = ::Thunder::Core::Time(2000, 1, 24, 14, 1, 59, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Seconds(), 59); + time = ::Thunder::Core::Time(2021, 2, 28, 23, 15, 0, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Seconds(), 0); + time = ::Thunder::Core::Time(2021, 3, 31, 0, 6, 39, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Seconds(), 39); + } + TEST(Core_Time, Seconds_LocalTimeEnabled) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "Europe/Amsterdam", 1); + tzset(); + + ::Thunder::Core::Time time(2000, 1, 2, 11, 46, 6, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Seconds(), 6); + time = ::Thunder::Core::Time(1970, 2, 13, 12, 1, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Seconds(), 23); + time = ::Thunder::Core::Time(2000, 1, 2, 15, 59, 0, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Seconds(), 0); + time = ::Thunder::Core::Time(2021, 4, 30, 1, 30, 59, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Seconds(), 59); + time = ::Thunder::Core::Time(2021, 6, 3, 22, 59, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Seconds(), 23); + time = ::Thunder::Core::Time(2021, 11, 30, 23, 33, 18, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Seconds(), 18); + time = ::Thunder::Core::Time(2021, 7, 3, 22, 59, 0, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Seconds(), 0); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, Minutes) + { + ::Thunder::Core::Time time(2000, 1, 2, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Minutes(), 30); + time = ::Thunder::Core::Time(1971, 12, 31, 12, 45, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Minutes(), 45); + time = ::Thunder::Core::Time(2021, 4, 30, 1, 30, 56, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Minutes(), 30); + time = ::Thunder::Core::Time(2021, 2, 6, 23, 1, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Minutes(), 1); + time = ::Thunder::Core::Time(2021, 2, 26, 22, 45, 45, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Minutes(), 45); + time = ::Thunder::Core::Time(1981, 1, 30, 23, 0, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Minutes(), 0); + time = ::Thunder::Core::Time(1981, 1, 30, 23, 0, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Minutes(), 0); + } + TEST(Core_Time, Minutes_LocalTimeEnabled) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "Europe/Amsterdam", 1); + tzset(); + + ::Thunder::Core::Time time(2000, 1, 2, 11, 30, 30, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Minutes(), 30); + time = ::Thunder::Core::Time(1971, 11, 1, 12, 0, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Minutes(), 0); + time = ::Thunder::Core::Time(2000, 1, 20, 15, 10, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Minutes(), 10); + time = ::Thunder::Core::Time(2021, 4, 30, 2, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Minutes(), 30); + time = ::Thunder::Core::Time(2021, 2, 28, 22, 0, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Minutes(), 0); + time = ::Thunder::Core::Time(2021, 2, 28, 22, 0, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Minutes(), 0); + time = ::Thunder::Core::Time(2021, 2, 3, 23, 34, 18, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Minutes(), 34); + time = ::Thunder::Core::Time(1981, 1, 31, 23, 59, 59, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Minutes(), 59); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, Hours) + { + ::Thunder::Core::Time time(2000, 1, 2, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Hours(), 11); + time = ::Thunder::Core::Time(1972, 2, 29, 12, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Hours(), 12); + time = ::Thunder::Core::Time(2000, 1, 26, 14, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Hours(), 14); + time = ::Thunder::Core::Time(2021, 4, 30, 0, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Hours(), 0); + time = ::Thunder::Core::Time(2021, 5, 31, 23, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Hours(), 23); + time = ::Thunder::Core::Time(2021, 6, 30, 0, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Hours(), 0); + time = ::Thunder::Core::Time(1981, 1, 17, 0, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Hours(), 0); + } + TEST(Core_Time, Hours_LocalTimeEnabled) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "Europe/Amsterdam", 1); + tzset(); + + ::Thunder::Core::Time time(2000, 1, 2, 11, 56, 46, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Hours(), 10); + time = ::Thunder::Core::Time(1971, 9, 12, 12, 10, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Hours(), 11); + time = ::Thunder::Core::Time(2000, 2, 29, 15, 10, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Hours(), 14); + time = ::Thunder::Core::Time(2021, 5, 28, 23, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Hours(), 21); + time = ::Thunder::Core::Time(2021, 5, 28, 0, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Hours(), 22); + time = ::Thunder::Core::Time(2021, 1, 10, 22, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Hours(), 21); + time = ::Thunder::Core::Time(2021, 7, 31, 1, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Hours(), 23); + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, Day) + { + ::Thunder::Core::Time time(2000, 1, 2, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Day(), 2); + time = ::Thunder::Core::Time(1971, 2, 25, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Day(), 25); + time = ::Thunder::Core::Time(2000, 4, 30, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Day(), 30); + time = ::Thunder::Core::Time(2021, 2, 28, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Day(), 28); + time = ::Thunder::Core::Time(2021, 5, 31, 20, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Day(), 31); + time = ::Thunder::Core::Time(1981, 1, 31, 23, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Day(), 31); + } + TEST(Core_Time, Day_LocalTimeEnabled) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "Europe/Amsterdam", 1); + tzset(); + + ::Thunder::Core::Time time(2000, 1, 4, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Day(), 4); + time = ::Thunder::Core::Time(1976, 2, 29, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Day(), 29); + time = ::Thunder::Core::Time(2000, 1, 31, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Day(), 31); + time = ::Thunder::Core::Time(2021, 4, 30, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Day(), 30); + time = ::Thunder::Core::Time(2021, 2, 28, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Day(), 28); + time = ::Thunder::Core::Time(1981, 6, 24, 23, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Day(), 24); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, WeekDayName) + { + ::Thunder::Core::Time time(2000, 1, 2, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.WeekDayName(), "Sun"); + time = ::Thunder::Core::Time(1971, 2, 1, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.WeekDayName(), "Mon"); + time = ::Thunder::Core::Time(2000, 3, 25, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.WeekDayName(), "Sat"); + time = ::Thunder::Core::Time(2021, 4, 28, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.WeekDayName(), "Wed"); + time = ::Thunder::Core::Time(2024, 2, 29, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.WeekDayName(), "Thu"); + time = ::Thunder::Core::Time(1981, 7, 13, 1, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.WeekDayName(), "Mon"); + } + TEST(Core_Time, WeekDayName_LocalTimeEnabled) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + ::Thunder::Core::Time time(2000, 1, 3, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.WeekDayName(), "Mon"); + time = ::Thunder::Core::Time(1971, 2, 2, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.WeekDayName(), "Tue"); + time = ::Thunder::Core::Time(2000, 3, 31, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.WeekDayName(), "Fri"); + time = ::Thunder::Core::Time(2021, 4, 30, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.WeekDayName(), "Fri"); + time = ::Thunder::Core::Time(2021, 2, 28, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.WeekDayName(), "Sun"); + time = ::Thunder::Core::Time(1981, 1, 31, 23, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.WeekDayName(), "Sat"); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, Month) + { + ::Thunder::Core::Time time(2000, 1, 1, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Month(), 1); + time = ::Thunder::Core::Time(1971, 2, 2, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Month(), 2); + time = ::Thunder::Core::Time(2000, 3, 31, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Month(), 3); + time = ::Thunder::Core::Time(2021, 4, 30, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Month(), 4); + time = ::Thunder::Core::Time(2021, 7, 28, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Month(), 7); + time = ::Thunder::Core::Time(1981, 11, 30, 23, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Month(), 11); + } + TEST(Core_Time, Month_LocalTimeEnabled) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "Europe/Amsterdam", 1); + tzset(); + + ::Thunder::Core::Time time(2000, 9, 1, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Month(), 9); + time = ::Thunder::Core::Time(1971, 1, 2, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Month(), 1); + time = ::Thunder::Core::Time(2000, 8, 30, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Month(), 8); + time = ::Thunder::Core::Time(2021, 11, 28, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Month(), 11); + time = ::Thunder::Core::Time(2021, 6, 30, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Month(), 6); + time = ::Thunder::Core::Time(1981, 12, 31, 23, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Month(), 12); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, MonthName) + { + ::Thunder::Core::Time time(2000, 1, 1, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.MonthName(), "Jan"); + time = ::Thunder::Core::Time(1971, 3, 2, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.MonthName(), "Mar"); + time = ::Thunder::Core::Time(2000, 5, 31, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.MonthName(), "May"); + time = ::Thunder::Core::Time(2021, 4, 30, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.MonthName(), "Apr"); + time = ::Thunder::Core::Time(2021, 1, 12, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.MonthName(), "Jan"); + time = ::Thunder::Core::Time(1983, 6, 30, 22, 59, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.MonthName(), "Jun"); + time = ::Thunder::Core::Time(1981, 7, 27, 23, 59, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.MonthName(), "Jul"); + } + TEST(Core_Time, MonthName_LocalTimeEnabled) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "Europe/Amsterdam", 1); + tzset(); + + ::Thunder::Core::Time time(2000, 1, 31, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.MonthName(), "Jan"); + time = ::Thunder::Core::Time(1971, 2, 28, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.MonthName(), "Feb"); + time = ::Thunder::Core::Time(2000, 8, 10, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.MonthName(), "Aug"); + time = ::Thunder::Core::Time(2021, 9, 30, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.MonthName(), "Sep"); + time = ::Thunder::Core::Time(2021, 10, 31, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.MonthName(), "Oct"); + time = ::Thunder::Core::Time(1981, 11, 26, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.MonthName(), "Nov"); + time = ::Thunder::Core::Time(1990, 12, 31, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_STREQ(time.MonthName(), "Dec"); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, Year) + { + ::Thunder::Core::Time time(2000, 1, 1, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Year(), static_cast(2000)); + time = ::Thunder::Core::Time(1971, 2, 28, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Year(), static_cast(1971)); + time = ::Thunder::Core::Time(2000, 4, 10, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Year(), static_cast(2000)); + time = ::Thunder::Core::Time(2021, 6, 30, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Year(), static_cast(2021)); + time = ::Thunder::Core::Time(2022, 12, 31, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Year(), static_cast(2022)); + time = ::Thunder::Core::Time(1981, 9, 14, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Year(), static_cast(1981)); + } + TEST(Core_Time, Year_LocalTimeEnabled) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "Europe/Amsterdam", 1); + tzset(); + + ::Thunder::Core::Time time(2000, 3, 1, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Year(), static_cast(2000)); + time = ::Thunder::Core::Time(1971, 5, 25, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Year(), static_cast(1971)); + time = ::Thunder::Core::Time(2002, 7, 20, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Year(), static_cast(2002)); + time = ::Thunder::Core::Time(2021, 8, 30, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Year(), static_cast(2021)); + time = ::Thunder::Core::Time(2025, 12, 31, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Year(), static_cast(2025)); + time = ::Thunder::Core::Time(1981, 10, 10, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.Year(), static_cast(1981)); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, DayOfYear) + { + ::Thunder::Core::Time time(2000, 1, 1, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfYear(), 0); + time = ::Thunder::Core::Time(2000, 2, 28, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfYear(), 58); + time = ::Thunder::Core::Time(2000, 3, 25, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfYear(), 84); + time = ::Thunder::Core::Time(2000, 4, 30, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfYear(), 120); + time = ::Thunder::Core::Time(2000, 5, 31, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfYear(), 151); + time = ::Thunder::Core::Time(2000, 6, 30, 11, 30, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfYear(), 181); + } + TEST(Core_Time, DayOfYear_LocalTimeEnabled) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "Europe/Amsterdam", 1); + tzset(); + + ::Thunder::Core::Time time(2002, 7, 1, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfYear(), 181); + time = ::Thunder::Core::Time(2000, 8, 10, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfYear(), 222); + time = ::Thunder::Core::Time(2000, 9, 25, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfYear(), 268); + time = ::Thunder::Core::Time(2000, 10, 29, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfYear(), 302); + time = ::Thunder::Core::Time(2000, 11, 30, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfYear(), 334); + time = ::Thunder::Core::Time(2000, 12, 6, 11, 30, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfYear(), 340); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, DayOfWeek) + { + // Thu Jan 1 01:01:01 2004 + ::Thunder::Core::Time time(2004, 1, 1, 1, 1, 1, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfWeek(), 4); + // Thu Jan 1 11:30:24 2004 + time = ::Thunder::Core::Time(2004, 1, 1, 11, 30, 24, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfWeek(), 4); + // Thu Jun 20 20:20:22 2019 + time = ::Thunder::Core::Time(2019, 6, 20, 20, 20, 22, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfWeek(), 4); + // Mon Jul 1 13:40:33 2019 + time = ::Thunder::Core::Time(2019, 5, 31, 13, 40, 33, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfWeek(), 5); + // Mon Aug 31 11:50:31 2015 + time = ::Thunder::Core::Time(2015, 8, 31, 11, 50, 31, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfWeek(), 1); + // Tue Sep 1 11:50:23 2015 + time = ::Thunder::Core::Time(2015, 8, 31, 11, 50, 23, 21, false); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfWeek(), 1); + } + TEST(Core_Time, DayOfWeek_LocalTimeEnabled) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "Europe/Amsterdam", 1); + tzset(); + + // Thu Jan 1 01:01:01 2004 + ::Thunder::Core::Time time(2004, 1, 1, 1, 1, 1, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfWeek(), 4); + // Thu Jan 1 11:30:24 2004 + time = ::Thunder::Core::Time(2004, 5, 1, 11, 30, 24, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfWeek(), 6); + // Thu Jun 20 20:20:22 2019 + time = ::Thunder::Core::Time(2019, 6, 20, 20, 20, 22, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfWeek(), 4); + // Mon Jul 1 13:40:33 2019 + time = ::Thunder::Core::Time(2019, 7, 31, 13, 40, 33, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfWeek(), 3); + // Mon Aug 31 11:50:31 2015 + time = ::Thunder::Core::Time(2015, 8, 31, 11, 50, 31, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfWeek(), 1); + // Tue Sep 1 11:50:23 2015 + time = ::Thunder::Core::Time(2015, 9, 30, 11, 50, 23, 21, true); + EXPECT_EQ(time.IsValid(), true); + EXPECT_EQ(time.DayOfWeek(), 3); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, Ctor_TimeValues_InvalidValues) + { + ::Thunder::Core::Time time(2000, 1, 2, 11, 30, 23, 1000, false); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(2000, 1, 2, 11, 30, 67, 21, false); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(2000, 1, 2, 11, 100, 23, 21, false); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(2000, 1, 2, 25, 30, 23, 10, false); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(2000, 1, 32, 11, 30, 6, 21, false); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(2000, 1, 0, 11, 30, 23, 100, false); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(2001, 2, 29, 11, 30, 23, 100, false); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(2004, 2, 30, 11, 30, 23, 100, false); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(2003, 6, 31, 11, 30, 23, 100, false); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(2000, 15, 2, 11, 1, 23, 21, false); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(2000, 0, 2, 11, 1, 23, 21, false); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(1821, 1, 2, 11, 60, 23, 100, false); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(1871, 1, 2, 11, 0, 60, 100, false); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(1871, 1, 2, 24, 0, 35, 100, false); + EXPECT_EQ(time.IsValid(), false); + + } + TEST(Core_Time, Ctor_TimeValues_LocalTimeEnabled_InvalidValues) + { + ::Thunder::Core::Time time(2000, 1, 2, 11, 30, 23, 1000, true); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(2000, 1, 2, 11, 30, 60, 21, true); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(2000, 1, 2, 11, 30, 67, 21, true); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(2000, 1, 2, 11, 60, 23, 21, true); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(2000, 1, 2, 11, 100, 23, 21, true); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(2000, 1, 2, 24, 30, 23, 10, true); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(2000, 1, 32, 11, 30, 6, 21, true); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(1921, 1, 0, 11, 30, 23, 100, true); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(1923, 2, 29, 11, 30, 23, 100, true); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(2000, 15, 2, 11, 1, 23, 21, true); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(2000, 0, 2, 11, 1, 23, 21, true); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(2000, 9, 31, 11, 1, 23, 21, true); + EXPECT_EQ(time.IsValid(), false); + time = ::Thunder::Core::Time(1821, 1, 2, 24, 30, 23, 100, true); + EXPECT_EQ(time.IsValid(), false); + } + TEST(Core_Time, FromString_CurrentTime) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + ::Thunder::Core::Time time(::Thunder::Core::Time::Now()); + std::string timeString1, timeString2; + time.ToString(timeString1); + + // LocalTime default (true) + EXPECT_EQ(time.FromString(timeString1), true); + time.ToString(timeString2); + EXPECT_STREQ(timeString1.c_str(), timeString2.c_str()); + // LocalTime true + EXPECT_EQ(time.FromString(timeString2, true), true); + time.ToString(timeString1); + EXPECT_STREQ(timeString2.c_str(), timeString1.c_str()); + + // LocalTime false + EXPECT_EQ(time.FromString(timeString1, false), true); + time.ToString(timeString1); + EXPECT_EQ(time.FromString(timeString2, false), true); + time.ToString(timeString2); + EXPECT_STREQ(timeString1.c_str(), timeString2.c_str()); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, FromString_TimeCtor) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + ::Thunder::Core::Time orig(1969,10, 3, 10, 11, 12, 666, true); + string timeString; + orig.ToString(timeString, true); + + ::Thunder::Core::Time time1; + time1.FromString(timeString, true); + orig.ToString(timeString, false); + + ::Thunder::Core::Time time2; + time2.FromString(timeString, false); + + EXPECT_EQ(orig.MilliSeconds(), 666u); + orig.ToString(timeString, true); + std::cout << "Localtime 1969-10-03 10:11:12 666 : " << timeString << " ms: " << orig.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Fri, 03 Oct 1969 10:11:12"); + orig.ToString(timeString, false); + std::cout << "UTC 1969-10-03 10:11:12 666 : " << timeString << " ms: " << orig.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Fri, 03 Oct 1969 10:11:12 GMT"); + + time1.ToString(timeString, true); + std::cout << "Localtime 1969-10-03 10:11:12 666 : " << timeString << " ms: " << time1.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Fri, 03 Oct 1969 10:11:12"); + time1.ToString(timeString, false); + std::cout << "UTC 1969-10-03 10:11:12 666 : " << timeString << " ms: " << time1.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Fri, 03 Oct 1969 10:11:12 GMT"); + + time2.ToString(timeString, true); + std::cout << "LocalTime 1969-10-03 10:11:12 666 : " << timeString << " ms: " << time2.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Fri, 03 Oct 1969 10:11:12"); + time2.ToString(timeString, false); + std::cout << "UTC 1969-10-03 10:11:12 666 : " << timeString << " ms: " << time2.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Fri, 03 Oct 1969 10:11:12 GMT"); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, FromString_ANSI) + { + ::Thunder::Core::Time time; + std::string timeString; + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + // LocalTime true + EXPECT_EQ(time.FromString("Sun Nov 6 08:49:37 1994", true), true); + time.ToString(timeString); + EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 08:49:37"); + // LocalTime false + EXPECT_EQ(time.FromString("Sun Nov 6 12:49:37 1994", false), true); + time.ToString(timeString); + EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 12:49:37"); + + // Check time difference after set time zone to GST + setenv("TZ", "GST", 1); + tzset(); + EXPECT_EQ(time.FromString("Sun Nov 6 12:49:37 1994", false), true); + time.ToString(timeString); + EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 12:49:37"); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, FromString_ISO8601) + { + ::Thunder::Core::Time time; + std::string timeString; + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + // LocalTime true + EXPECT_EQ(time.FromString("1994-11-06T08:49:37Z", true), true); + time.ToString(timeString); + EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 08:49:37"); + // LocalTime false + EXPECT_EQ(time.FromString("1994-11-06T08:49:37Z", false), true); + time.ToString(timeString); + EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 08:49:37"); + + // Check time difference after set time zone to GST + setenv("TZ", "GST", 1); + tzset(); + + // LocalTime true + EXPECT_EQ(time.FromString("1994-11-06T08:49:37Z", true), true); + time.ToString(timeString); + EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 08:49:37"); + // LocalTime false + EXPECT_EQ(time.FromString("1994-11-06T08:49:37Z", false), true); + time.ToString(timeString); + EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 08:49:37"); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, FromString_RFC1036) + { + ::Thunder::Core::Time time; + std::string timeString; + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + // LocalTime true + EXPECT_EQ(time.FromString("Sunday, 06-Nov-94 08:49:37 GMT", true), true); + time.ToString(timeString); + EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 08:49:37"); + + // LocalTime false + EXPECT_EQ(time.FromString("Sunday, 06-Nov-94 08:49:37 GMT", false), true); + time.ToString(timeString); + EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 08:49:37"); + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, FromString_RFC1123) + { + ::Thunder::Core::Time time; + std::string timeString; + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + // LocalTime true + EXPECT_EQ(time.FromString("Sun, 06 Nov 1994 08:49:37 GMT", true), true); + time.ToString(timeString); + EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 08:49:37"); + // LocalTime false + EXPECT_EQ(time.FromString("Sun, 06 Nov 1994 08:49:37 GMT", false), true); + time.ToString(timeString); + EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 08:49:37"); + + // Check time difference after set time zone to GST + setenv("TZ", "GST", 1); + tzset(); + + // LocalTime true + EXPECT_EQ(time.FromString("Sun, 06 Nov 1994 08:49:37 GMT", true), true); + time.ToString(timeString); + EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 08:49:37"); + // LocalTime false + EXPECT_EQ(time.FromString("Sun, 06 Nov 1994 12:49:37 GMT", false), true); + time.ToString(timeString); + EXPECT_STREQ(timeString.c_str(), "Sun, 06 Nov 1994 12:49:37"); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, FromStandard_ANSI_ValidFormat) + { + ::Thunder::Core::Time time(::Thunder::Core::Time::Now()); + EXPECT_EQ(time.FromANSI("Thu Aug11 23:47:20 2010", true), true); + EXPECT_EQ(time.FromANSI("Sun Sep 02 23:47:20 2012", false), true); + EXPECT_EQ(time.FromANSI("Sat Jul 13 23:47:20 2012", true), true); + EXPECT_EQ(time.FromANSI("Sun Jun3 3:47:20 2012", false), true); + EXPECT_EQ(time.FromANSI("Sun Jan01 23:7:20 2012", false), true); + EXPECT_EQ(time.FromANSI("Thu Nov22 23:47:0 2012", true), true); + EXPECT_EQ(time.FromANSI("Fri May 11 23:47:20 2012", false), true); + EXPECT_EQ(time.FromANSI("Fri Apr06 3:7:0 2012", true), true); + + EXPECT_EQ(time.FromANSI("Thu Mar08 23:47:20 2012 GMT", false), true); + EXPECT_EQ(time.FromANSI("Thu Mar08 23:47:20 2012 GMT", true), true); + EXPECT_EQ(time.FromANSI("Sun Feb05 23:47:20 2012 UTC", false), true); + EXPECT_EQ(time.FromANSI("Sun Feb05 23:47:20 2012 UTC", true), true); + } + TEST(Core_Time, FromStandard_ANSI_InvalidFormat) + { + ::Thunder::Core::Time time(::Thunder::Core::Time::Now()); + std::string timeString; + time.ToString(timeString); + // ToString is in RFC1123 format, hence it should fail + EXPECT_EQ(time.FromANSI(timeString, true), false); + EXPECT_EQ(time.FromANSI(timeString, false), false); + + EXPECT_EQ(time.FromANSI("1994Jan06T0a:49:37.123+06:45", true), false); + EXPECT_EQ(time.FromANSI("SAT Jan06T0a:49:37.123+06:45", false), false); + EXPECT_EQ(time.FromANSI("Sunday Feb06T08:4a:37.123+06:45", true), false); + EXPECT_EQ(time.FromANSI("Tues Mar0aT08:49:5a.123+06:45", true), false); + EXPECT_EQ(time.FromANSI("TMar0608:49:5a.123+06:45", true), false); + EXPECT_EQ(time.FromANSI("19Mar0608:49:5a.123+06:45", true), false); + EXPECT_EQ(time.FromANSI("No1v0608:49:5.123+06:45 UTC", true), false); + EXPECT_EQ(time.FromANSI("No0608:49:5.123+06:45 UTC", true), false); + EXPECT_EQ(time.FromANSI(" Sun Jan 8 TEST08:49:37.123+06:45", true), false); + EXPECT_EQ(time.FromANSI("Sun 0608:49:37.803+06:45", true), false); + EXPECT_EQ(time.FromANSI("Mon MarTEST0608:49:5a.123+06:45", true), false); + EXPECT_EQ(time.FromANSI("Sun Mar608:49:5TEST.123+06:45", true), false); + EXPECT_EQ(time.FromANSI("Sun Mar608:49:5.123+06:45 TEST GMT", true), false); + } + TEST(Core_Time, FromStandard_ISO8601_ValidFormat) + { + ::Thunder::Core::Time time(::Thunder::Core::Time::Now()); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37"), true); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37Z"), true); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37+01"), true); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37+06:45"), true); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37+06:45 GMT"), true); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37+06:45 UTC"), true); + EXPECT_EQ(time.FromISO8601("1994-11-06T8:49:37+06:45"), true); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:9:37+06:45"), true); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:7+06:45"), true); + EXPECT_EQ(time.FromISO8601("2094-11-06T08:49:37+06:45"), true); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37+06:45"), true); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123"), true); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123Z"), true); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123+01"), true); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123+06 45"), true); + EXPECT_EQ(time.FromISO8601("1994-12-06T08:49:37.123 06:45"), true); + } + TEST(Core_Time, FromStandard_ISO8601_InvalidFormat) + { + ::Thunder::Core::Time time(::Thunder::Core::Time::Now()); + std::string timeString; + // ToString is in RFC1123 format, hence it should fail + EXPECT_EQ(time.FromISO8601(timeString), false); + EXPECT_EQ(time.FromISO8601("1994-13-06T08:49:37.123+06:45"), false); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123-06:: 45"), false); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37."), false); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123+06- 45"), false); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123+24:45"), false); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123+24:4"), false); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123+06:45:"), false); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123+"), false); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37.123a"), false); + EXPECT_EQ(time.FromISO8601("1994-11-06 T08:49:37.123a"), false); + EXPECT_EQ(time.FromISO8601("1994-11-06T 08:49:37.123a"), false); + EXPECT_EQ(time.FromISO8601("1994-11-0608:49:37+06:45"), false); + EXPECT_EQ(time.FromISO8601("1994-Jan-06T08:49:37.123a"), false); + EXPECT_EQ(time.FromISO8601("94-11-06T08:49:37+06:45"), false); + EXPECT_EQ(time.FromISO8601("100-11-06T08:49:37.123a"), false); + EXPECT_EQ(time.FromISO8601("1000-11-06T08:49:37.123a"), false); + EXPECT_EQ(time.FromISO8601("1994-Apr-06T08:49:37+06:45"), false); + EXPECT_EQ(time.FromISO8601("1994-April-06T08:49:37+06:45"), false); + } + TEST(Core_Time, FromStandard_RFC1036_ValidFormat) + { + ::Thunder::Core::Time time(::Thunder::Core::Time::Now()); + + EXPECT_EQ(time.FromRFC1036("Sunday, 06-Nov-94 08:49:37 GMT"), true); + EXPECT_EQ(time.FromRFC1036("Sunday, 06-Nov-1994 08:49:37 GMT"), true); + EXPECT_EQ(time.FromRFC1036("Sunday, 06-Nov-1994 08:49:37 UTC"), true); + EXPECT_EQ(time.FromRFC1036("Sunday, 06-Nov-1994 08:49:37"), true); + EXPECT_EQ(time.FromRFC1036("Monday, 7-Nov-94 08:49:37"), true); + EXPECT_EQ(time.FromRFC1036("Monday, 7-Nov-94 8:09:07"), true); + EXPECT_EQ(time.FromRFC1036("Monday, 7-Nov-94 8:9:07"), true); + EXPECT_EQ(time.FromRFC1036("Monday, 7-Nov-94 8:09:7 "), true); + EXPECT_EQ(time.FromRFC1036("Monday, 7-Nov-94 8:09:7"), true); + EXPECT_EQ(time.FromRFC1036("Monday, 7-Nov-94 8:9:7 "), true); + EXPECT_EQ(time.FromRFC1036("Monday, 7-Nov-94 8:9:7 GMT"), true); + EXPECT_EQ(time.FromRFC1036("Monday, 7-Nov-94 8:9:7 GMT "), true); + EXPECT_EQ(time.FromRFC1036("Monday, 7-Nov-94 8:9:7 UTC"), true); + EXPECT_EQ(time.FromRFC1036("Monday, 7-Apr-94 8:9:7 GMT"), true); + EXPECT_EQ(time.FromRFC1036("Monday, 7-Nov-94 8:9:7"), true); + EXPECT_EQ(time.FromRFC1036("Sunday, 06-Nov-1994 08:49:37 PDT"), true); + } + TEST(Core_Time, FromStandard_RFC1036_InvalidFormat) + { + ::Thunder::Core::Time time(::Thunder::Core::Time::Now()); + std::string timeString; + time.ToString(timeString, true); + + // ToString is in RFC1123 format, hence it should fail + EXPECT_EQ(time.FromRFC1036(timeString), false); + + EXPECT_EQ(time.FromRFC1036("Wed, 27 Oct 2021 00:05:01 "), false); + EXPECT_EQ(time.FromRFC1036("Sunday, 06Nov94 08:49:37 GMT"), false); + EXPECT_EQ(time.FromRFC1036("Sunday, 06:Nov:94 08:49:37 GMT"), false); + EXPECT_EQ(time.FromRFC1036("1994-06-Nov 08:49:37 GMT"), false); + EXPECT_EQ(time.FromRFC1036("Sunday, 1994-06-Nov 08:49:37 GMT"), false); + EXPECT_EQ(time.FromRFC1036("19941105T08:49:37.123+06:45"), false); + EXPECT_EQ(time.FromRFC1036("Sunday, 06-Nov-1994 08:TEST49:37"), false); + EXPECT_EQ(time.FromRFC1036("Sunday, 06-Nov-1994 08:49:TEST37"), false); + EXPECT_EQ(time.FromRFC1036("1994-11-06T08:49:37.123+06:45"), false); + EXPECT_EQ(time.FromRFC1036("1994-11-Jan-08:49:07+06:45"), false); + EXPECT_EQ(time.FromRFC1036("1994Jan07T08:49:37.123+06:45"), false); + EXPECT_EQ(time.FromRFC1036("1994-Jan-09T08:49:37.123+06:45"), false); + EXPECT_EQ(time.FromRFC1036("Monday, 07-November-2014 08:49:37 GMT"), false); + EXPECT_EQ(time.FromRFC1036("XXXX,06-Nov-08:11:49:37 "), false); + EXPECT_EQ(time.FromRFC1036("XXXX-06-Nov-08:11:49:37 "), false); + EXPECT_EQ(time.FromRFC1036("XXXX:06-Nov-08:11:49:37 "), false); + EXPECT_EQ(time.FromRFC1036("XXXX, 06-Nov-08:11:49:37 "), false); + EXPECT_EQ(time.FromRFC1036("Sunday, 06-Nov-TEST1994 08:49:37"), false); + EXPECT_EQ(time.FromRFC1036("Sunday, TEST06-Nov-1994 08:49:37"), false); + EXPECT_EQ(time.FromRFC1036("Sunday, 06-Nov-1994 TEST08:49:37"), false); + } + TEST(Core_Time, FromStandard_RFC1123_ValidFormat) + { + ::Thunder::Core::Time time; + EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08:49:37 GMT"), true); + EXPECT_EQ(time.FromRFC1123("Sun,06Nov199408:49:37GMT"), true); + EXPECT_EQ(time.FromRFC1123("Sun,06Nov199408:49:37"), true); + EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08:59:27"), true); + EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08:59:27 "), true); + EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08:59:27 FF "), true); + EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08:59:27 GMT"), true); + } + TEST(Core_Time, FromStandard_RFC1123_InvalidFormat) + { + ::Thunder::Core::Time time; + EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 ff 08:49:37 GMT"), false); + EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994ff 08:49:37 GMT"), false); + EXPECT_EQ(time.FromRFC1123("1994Jan06T08:49:37.123+06:45"), false); + EXPECT_EQ(time.FromRFC1123("1994Jan0aT08:49:37.123+06:45"), false); + EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 0f:49:37 GMT"), false); + EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08f:49:37 GMT"), false); + EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08:ff49:37 GMT"), false); + EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08:49f:37 GMT"), false); + EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08:49:f37 GMT"), false); + EXPECT_EQ(time.FromRFC1123("Sun, 06-Nov-1994 08:49:37 GMT"), false); + EXPECT_EQ(time.FromRFC1123("06Nov1994:::08:49:37"), false); + EXPECT_EQ(time.FromRFC1123("Sun,Nov1994:::08:49:37"), false); + EXPECT_EQ(time.FromRFC1123("06 Nov 1994 08:59:27 GMT"), false); + EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994:08:49:37 GMT"), false); + EXPECT_EQ(time.FromRFC1123("Sun,06Nov1994TEST8:49:37"), false); + EXPECT_EQ(time.FromRFC1123("Sun,06Nov1994TEST8:49:37"), false); + EXPECT_EQ(time.FromRFC1123("Sund, 06 Nov 1994 08:49:37 GMT"), false); + EXPECT_EQ(time.FromRFC1123("TEST, 06 Nov 1994 08:49:37 GMT"), false); + EXPECT_EQ(time.FromRFC1123("Sun, TEST 06 Nov 1994 08:49:37 GMT"), false); + EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov TEST 1994 08:49:37 GMT"), false); + EXPECT_EQ(time.FromRFC1123("Sunday, 06 Nov 1994 08:59:27 GMT"), false); + } + TEST(Core_Time, FromStandard_RFC1123_TimeStringCreatedFromTime) + { + ::Thunder::Core::Time time = ::Thunder::Core::Time(2018, 1, 23, 11, 30, 23, 21, false); + std::string timeString; + time.ToString(timeString, false); + time.FromRFC1123(timeString); + EXPECT_STREQ(timeString.c_str(), _T("Tue, 23 Jan 2018 11:30:23 GMT")); - time = Time(2018, 6, 23, 11, 30, 23, 21, false); - time.ToString(timeString, false); - time.FromRFC1123(timeString); - EXPECT_STREQ(timeString.c_str(), _T("Sat, 23 Jun 2018 11:30:23 GMT")); - - time = Time(2018, 7, 23, 11, 30, 23, 21, false); - time.ToString(timeString, false); - time.FromRFC1123(timeString); - EXPECT_STREQ(timeString.c_str(), _T("Mon, 23 Jul 2018 11:30:23 GMT")); - - time = Time(2018, 8, 23, 11, 30, 23, 21, false); - time.ToString(timeString, false); - time.FromRFC1123(timeString); - EXPECT_STREQ(timeString.c_str(), _T("Thu, 23 Aug 2018 11:30:23 GMT")); - - time = Time(2018, 9, 23, 11, 30, 23, 21, false); - time.ToString(timeString, false); - time.FromRFC1123(timeString); - EXPECT_STREQ(timeString.c_str(), _T("Sun, 23 Sep 2018 11:30:23 GMT")); - - time = Time(2018, 10, 23, 11, 30, 23, 21, false); - time.ToString(timeString, false); - time.FromRFC1123(timeString); - EXPECT_STREQ(timeString.c_str(), _T("Tue, 23 Oct 2018 11:30:23 GMT")); - - time = Time(2018, 11, 23, 11, 30, 23, 21, false); - time.ToString(timeString, false); - time.FromRFC1123(timeString); - EXPECT_STREQ(timeString.c_str(), _T("Fri, 23 Nov 2018 11:30:23 GMT")); - - time = Time(2018, 12, 23, 11, 30, 23, 21, false); - time.ToString(timeString, false); - EXPECT_EQ(time.FromRFC1123(timeString), true); - EXPECT_STREQ(timeString.c_str(), _T("Sun, 23 Dec 2018 11:30:23 GMT")); - - time = Time(1970, 12, 23, 11, 30, 23, 21, false); - time.ToString(timeString, false); - EXPECT_EQ(time.FromRFC1123(timeString), true); - - time = Time(1980, 12, 23, 11, 30, 23, 21, false); - time.ToString(timeString, false); - EXPECT_EQ(time.FromRFC1123(timeString), true); -} -TEST(Core_Time, FromStandard_RFC1123_TimeStringCreatedFromTime_InvalidCase) -{ - Time time = Time(2018, 1, 23, 11, 30, 23, 21, false); - std::string timeString; - time.ToString(timeString, false); - EXPECT_STREQ(timeString.c_str(), "Tue, 23 Jan 2018 11:30:23 GMT"); - EXPECT_EQ(time.FromRFC1123(timeString), true); - - time = Time(2080, 12, 23, 11, 30, 23, 21, false); - time.ToString(timeString, false); - EXPECT_STREQ(timeString.c_str(), "Mon, 23 Dec 2080 11:30:23 GMT"); - EXPECT_EQ(time.FromRFC1123(timeString), true); -} -TEST(Core_Time, FromStandard_RFC1123_TimeStringCreatedWithLocalTimeEnabled) -{ - Time time; - std::string timeString; - time = Time(2000, 12, 23, 11, 30, 23, 21, true); - time.ToString(timeString, false); - EXPECT_EQ(time.FromRFC1123(timeString), true); -} -TEST(Core_Time, FromStandard_RFC1123_LocalTimeDisabled) -{ - Time time; - std::string timeString; - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08:59:27 UTC"), true); - time.ToString(timeString, false); - EXPECT_STREQ(timeString.c_str(), _T("Sun, 06 Nov 1994 08:59:27 GMT")); - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, FromStandard_RFC1123_LocalTimeEnabled) -{ - Time time; - std::string timeString; - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08:59:27 UTC"), true); - time.ToString(timeString, true); - EXPECT_STREQ(timeString.c_str(), _T("Sun, 06 Nov 1994 08:59:27")); - - // Check time difference after set time zone to GST - setenv("TZ", "GST", 1); - tzset(); - - // Set without timezone - EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 09:59:27 UTC"), true); - time.ToString(timeString, true); - EXPECT_STREQ(timeString.c_str(), _T("Sun, 06 Nov 1994 09:59:27")); - - // Set timezone back - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, FromStandard_RFC1123_TimeConversion_WithLocalTimeDisabled) -{ - Time time(1980, 12, 23, 11, 30, 23, 21, true); - std::string timeString1, timeString2; - time.ToString(timeString1, false); - EXPECT_EQ(time.FromRFC1123(timeString1), true); - time.ToString(timeString2, false); - EXPECT_STREQ(timeString1.c_str(), timeString2.c_str()); -} -TEST(Core_Time, FromStandard_RFC1123_TimeConversion_WithCurrentTime_And_LocalTimeDisabled) -{ - Time time(Time::Now()); - std::string timeString1, timeString2; - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - time.ToString(timeString1, false); - EXPECT_EQ(time.FromRFC1123(timeString1), true); - time.ToString(timeString2, false); - EXPECT_STREQ(timeString1.c_str(), timeString2.c_str()); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, FromStandard_RFC1123_TimeConversion_WithLocalTimeEnabled) -{ - Time time(1980, 12, 23, 11, 30, 23, 21, true); - std::string timeString1, timeString2; - time.ToString(timeString1, true); - EXPECT_EQ(time.FromRFC1123(timeString1), true); - time.ToString(timeString2, true); - EXPECT_STREQ(timeString1.c_str(), timeString2.c_str()); -} -TEST(Core_Time, FromStandard_RFC1123_TimeConversion_WithLocalTimeEnabled_And_LocalTimeDisabled) -{ - Time time(Time::Now()); - std::string timeString1, timeString2; - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - time.ToString(timeString1, true); - EXPECT_EQ(time.FromRFC1123(timeString1), true); - time.ToString(timeString2, true); - EXPECT_STREQ(timeString1.c_str(), timeString2.c_str()); - EXPECT_EQ(time.FromRFC1123(timeString2), true); - time.ToString(timeString1, true); - EXPECT_STREQ(timeString2.c_str(), timeString1.c_str()); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, ToStandard_ISO8601) -{ - Time time(Time::Now()); - string timeString; - string timeISOString; - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - // localTime argument value as default - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37Z"), true); - EXPECT_STREQ((time.ToISO8601()).c_str(), "1994-11-06T08:49:37Z"); - EXPECT_EQ(time.FromISO8601("1994-11-06T00:49:37"), true); - EXPECT_STREQ((time.ToISO8601()).c_str(), "1994-11-06T00:49:37Z"); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37"), true); - EXPECT_STREQ((time.ToISO8601()).c_str(), "1994-11-06T08:49:37Z"); - - // localTime argument value as true - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37Z"), true); - EXPECT_STREQ((time.ToISO8601(true)).c_str(), "1994-11-06T08:49:37"); - EXPECT_EQ(time.FromISO8601("1994-11-06T00:49:37"), true); - EXPECT_STREQ((time.ToISO8601(true)).c_str(), "1994-11-06T00:49:37"); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37"), true); - EXPECT_STREQ((time.ToISO8601(true)).c_str(), "1994-11-06T08:49:37"); - - // localTime argument value as true - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37Z"), true); - EXPECT_STREQ((time.ToISO8601(false)).c_str(), "1994-11-06T08:49:37Z"); - EXPECT_EQ(time.FromISO8601("1994-11-06T00:49:37"), true); - EXPECT_STREQ((time.ToISO8601(false)).c_str(), "1994-11-06T00:49:37Z"); - EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37"), true); - EXPECT_STREQ((time.ToISO8601(false)).c_str(), "1994-11-06T08:49:37Z"); - - // Time with empty value return null string - EXPECT_STREQ((Time().ToISO8601(true)).c_str(), ""); - EXPECT_STREQ((Time().ToISO8601(false)).c_str(), ""); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, ToStandard_RFC1123_WithLocalTimeDisabled) -{ - Time time(1980, 12, 23, 11, 30, 23, 21, true); - std::string timeString1, timeString2; - timeString1 = time.ToRFC1123(false); - EXPECT_EQ(time.FromRFC1123(timeString1), true); - timeString2 = time.ToRFC1123(false); - EXPECT_STREQ(timeString1.c_str(), timeString2.c_str()); -} -TEST(Core_Time, ToStandard_RFC1123_WithCurrentTime_And_LocalTimeDisabled) -{ - Time time(Time::Now()); - std::string timeString1, timeString2; - timeString1 = time.ToRFC1123(false); - EXPECT_EQ(time.FromRFC1123(timeString1), true); - timeString2 = time.ToRFC1123(false); - EXPECT_STREQ(timeString1.c_str(), timeString2.c_str()); -} -TEST(Core_Time, ToStandard_RFC1123_WithLocalTimeEnabled) -{ - Time time(2000, 12, 23, 11, 30, 23, 21, true); - std::string timeString1, timeString2; - timeString1 = time.ToRFC1123(true); - EXPECT_EQ(time.FromRFC1123(timeString1), true); - timeString2 = time.ToRFC1123(true); - EXPECT_STREQ(timeString1.c_str(), timeString2.c_str()); - -} -TEST(Core_Time, ToStandard_RFC1123_WithLocalTimeEnabled_And_LocalTimeDisabled) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - Time time(Time::Now()); - std::string timeString1, timeString2; - timeString1 = time.ToRFC1123(true); - EXPECT_EQ(time.FromRFC1123(timeString1), true); - timeString2 = time.ToRFC1123(true); - EXPECT_STREQ(timeString1.c_str(), timeString2.c_str()); - EXPECT_EQ(time.FromRFC1123(timeString2), true); - timeString1 = time.ToRFC1123(true); - EXPECT_STREQ(timeString2.c_str(), timeString1.c_str()); - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, Ticks_withoutInterval) -{ - Core::Time time1 = Core::Time::Now(); - Core::Time time2 = Core::Time::Now(); - uint64_t diff = time2.Ticks() - time1.Ticks(); - uint32_t intervalInSeconds = diff / Time::MicroSecondsPerSecond; - EXPECT_EQ(intervalInSeconds, static_cast(0)); -} -TEST(Core_Time, Ticks_TimeCtor) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - setenv("TZ", "Europe/Amsterdam", 1); - tzset(); - - Time orig(2016,10, 3, 10, 11, 12, 666, true); - Time::microsecondsfromepoch flattime = orig.Ticks(); - - std::cout << " Ticks for local 2016-10-03 10:11:12 666 (so UTC ticks) : " << flattime << std::endl; - Time copyutc(flattime); - string timeString; - copyutc.ToString(timeString, true); - std::cout << "Localtime 2016-10-03 10:11:12 666 : " << timeString << " ms: " << copyutc.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Mon, 03 Oct 2016 10:11:12"); - - copyutc.ToString(timeString, false); - std::cout << "UTC 2016-10-03 08:11:12 666 : " << timeString << " ms: " << copyutc.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Mon, 03 Oct 2016 08:11:12 GMT"); - EXPECT_EQ(copyutc.MilliSeconds(), 666u); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, Ticks_withInterval) -{ - uint32_t givenIntervalInSeconds = 2; - Core::Time time1 = Core::Time::Now(); - sleep(givenIntervalInSeconds); - Core::Time time2 = Core::Time::Now(); - uint64_t diff = time2.Ticks() - time1.Ticks(); - uint32_t intervalInSeconds = diff / Time::MicroSecondsPerSecond; - EXPECT_EQ(intervalInSeconds, givenIntervalInSeconds); -} -TEST(Core_Time, AddTime) -{ - Time time(Time::Now()); - std::string timeString1, timeString2; - time.ToString(timeString1); - uint32_t currentTime = time.MilliSeconds(); - uint32_t timeTobeAdded = 2; - time.Add(timeTobeAdded); - uint32_t newTime = time.MilliSeconds(); - time.ToString(timeString2); - EXPECT_EQ(newTime, currentTime + timeTobeAdded); - currentTime = time.Seconds(); - timeTobeAdded = 3; - time.Add(timeTobeAdded * 1000); - time.ToString(timeString1); - EXPECT_STRNE(timeString1.c_str(), timeString2.c_str()); - uint32_t expectedAddedTime = 0; - if (currentTime + timeTobeAdded >= 60) { - expectedAddedTime = (currentTime + timeTobeAdded) - 60; - } else { - expectedAddedTime = (currentTime + timeTobeAdded); - } - - newTime = time.Seconds(); - EXPECT_EQ(newTime, expectedAddedTime); -} -TEST(Core_Time, DISABLED_SubTime) -{ - Time time(Time::Now()); - std::string timeString1, timeString2; - time.ToString(timeString1); - uint32_t currentTime = time.MilliSeconds(); - uint32_t timeTobeSubtracted = 4; - time.Sub(timeTobeSubtracted); - uint32_t newTime = time.MilliSeconds(); - time.ToString(timeString2); - EXPECT_EQ(newTime, currentTime - timeTobeSubtracted); - currentTime = time.Seconds(); - timeTobeSubtracted = 6; - time.Sub(timeTobeSubtracted * 1000); - time.ToString(timeString1); - EXPECT_STRNE(timeString1.c_str(), timeString2.c_str()); - uint32_t expectedSubtractedTime = 0; - if (currentTime <= timeTobeSubtracted) { - expectedSubtractedTime = 60 - (timeTobeSubtracted - currentTime); - expectedSubtractedTime = (expectedSubtractedTime == 60) ? 0 : expectedSubtractedTime; - } else { - expectedSubtractedTime = (currentTime - timeTobeSubtracted); - } - newTime = time.Seconds(); - EXPECT_EQ(newTime, expectedSubtractedTime);; -} -TEST(Core_Time, NTPTime) -{ - Time time(1970, 1, 1, 0, 0, 0, 1, true); - const uint64_t ntpTime = time.NTPTime(); - EXPECT_GE(ntpTime/Time::MicroSecondsPerSecond, static_cast(0)); - uint32_t timeTobeAdded = 4; - time.Add(timeTobeAdded); - - EXPECT_GE(time.NTPTime()/Time::MicroSecondsPerSecond, ntpTime/Time::MicroSecondsPerSecond + (timeTobeAdded * 4)); -} -TEST(Core_Time, Format) -{ - Time time(2002, 5, 10, 11, 30, 23, 21, false); - EXPECT_STREQ(time.Format("%Y-%m-%d").c_str(), "2002-05-10"); - EXPECT_STREQ(time.Format("%d-%m-%Y").c_str(), "10-05-2002"); - time = Time(1970, 5, 31, 11, 30, 23, 21, false); - EXPECT_STREQ(time.Format("%Y-%m-%d").c_str(), "1970-05-31"); - EXPECT_STREQ(time.Format("%Y %m %d").c_str(), "1970 05 31"); - EXPECT_STREQ(time.Format("%Y:%m:%d").c_str(), "1970:05:31"); - - time = Time(1969, 5, 31, 11, 30, 23, 21, false); - EXPECT_STREQ(time.Format("%Y-%m-%d").c_str(), "1969-05-31"); -} -TEST(Core_Time, ToTimeOnly) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - Time time(2002, 5, 10, 11, 30, 23, 21, false); - EXPECT_STREQ(time.ToTimeOnly(false).c_str(), "11:30:23GMT"); - EXPECT_EQ(time.MilliSeconds(), static_cast(21)); - time = Time(1970, 5, 31, 0, 30, 23, 21, false); - EXPECT_STREQ(time.ToTimeOnly(false).c_str(), "00:30:23GMT"); - time = Time(1970, 5, 31, 23, 0, 23, 21, false); - EXPECT_STREQ(time.ToTimeOnly(false).c_str(), "23:00:23GMT"); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, ToTimeOnly_LocalTimeEnabled) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - Time time(2002, 5, 10, 11, 30, 23, 21, false); - EXPECT_STREQ(time.ToTimeOnly(true).c_str(), "11:30:23"); - EXPECT_EQ(time.MilliSeconds(), static_cast(21)); - - // Check time difference after set time zone to GST - setenv("TZ", "GST", 1); - tzset(); - - // Check time after unset time zone - time = Time(2002, 5, 10, 11, 30, 23, 21, false); - EXPECT_STREQ(time.ToTimeOnly(true).c_str(), "11:30:23"); - EXPECT_EQ(time.MilliSeconds(), static_cast(21)); - - setenv("TZ", "Africa/Algiers", 1); - tzset(); - time = Time(1970, 5, 31, 0, 30, 23, 21, false); - EXPECT_STREQ(time.ToTimeOnly(true).c_str(), "00:30:23"); - - setenv("TZ", "Asia/Kolkata", 1); - tzset(); - time = Time(1970, 5, 31, 22, 0, 23, 21, false); - EXPECT_STREQ(time.ToTimeOnly(true).c_str(), "03:30:23"); - - setenv("TZ", "GST", 1); - tzset(); - setenv("TZ", "America/Los_Angeles", 1); - tzset(); - time = Time(80, 12, 23, 11, 30, 23, 21, false); - //EXPECT_STREQ(time.ToTimeOnly(true).c_str(), "03:30:23"); - - setenv("TZ", "GST", 1); - tzset(); - setenv("TZ", "Europe/Amsterdam", 1); - tzset(); - time = Time(80, 12, 23, 11, 30, 23, 21, false); - //EXPECT_STREQ(time.ToTimeOnly(true).c_str(), "12:30:23"); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, ToTimeOnly_LocalTimeDisabled) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - Time time(2002, 5, 10, 11, 30, 23, 21, false); - EXPECT_STREQ(time.ToTimeOnly(false).c_str(), "11:30:23GMT"); - EXPECT_EQ(time.MilliSeconds(), static_cast(21)); - - setenv("TZ", "Africa/Algiers", 1); - tzset(); - time = Time(1970, 5, 31, 0, 30, 23, 21, false); - EXPECT_STREQ(time.ToTimeOnly(false).c_str(), "00:30:23GMT"); - - setenv("TZ", "Asia/Kolkata", 1); - tzset(); - time = Time(1970, 5, 31, 0, 0, 23, 21, false); - EXPECT_STREQ(time.ToTimeOnly(false).c_str(), "00:00:23GMT"); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, TimeWithLocalTimeTrue_ConvertTo_UTC_And_Local) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - setenv("TZ", "Europe/Amsterdam", 1); - tzset(); - - string timeString; - Time time = Time(2021, 07, 05, 22, 10, 5, 999, true); - EXPECT_EQ(time.MilliSeconds(), 999u); - time.ToString(timeString, true); - std::cout << "LocalTime 2021-07-05 22:10:05.999 : " << timeString << " ms: " << time.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Mon, 05 Jul 2021 22:10:05"); - time.ToString(timeString, false); - std::cout << "UTC 2021-07-05 20:10:05.999 : " << timeString << " ms: " << time.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Mon, 05 Jul 2021 20:10:05 GMT"); - - time = Time(2021,12, 26, 23, 59, 59, 1, true); - EXPECT_EQ(time.MilliSeconds(), 1u); - time.ToString(timeString, true); - std::cout << "LocalTime 2021-12-26 23:59:59.001 : " << timeString << " ms: " << time.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Sun, 26 Dec 2021 23:59:59"); - time.ToString(timeString, false); - std::cout << "UTC 2021-12-26 22:59:59.001 : " << timeString << " ms: " << time.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Sun, 26 Dec 2021 22:59:59 GMT"); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, TimeWithLocalTimeFalse_ConvertTo_UTC_And_Local) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - setenv("TZ", "Europe/Amsterdam", 1); - tzset(); - - string timeString; - Time time = Time(2021, 07, 05, 22, 10, 5, 999, false); - EXPECT_EQ(time.MilliSeconds(), 999u); - time.ToString(timeString, true); - std::cout << "LocalTime 2021-07-06 00:10:05.999 : " << timeString << " ms: " << time.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Tue, 06 Jul 2021 00:10:05"); - time.ToString(timeString, false); - std::cout << "UTC 2021-07-05 22:10:05.999 : " << timeString << " ms: " << time.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Mon, 05 Jul 2021 22:10:05 GMT"); - - time = Time(2021,12, 26, 23, 59, 59, 1, false); - EXPECT_EQ(time.MilliSeconds(), 1u); - time.ToString(timeString, true); - std::cout << "LocalTime 2021-12-27 00:59:59.001 : " << timeString << " ms: " << time.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Mon, 27 Dec 2021 00:59:59"); - time.ToString(timeString, false); - std::cout << "UTC 2021-12-26 23:59:59.001 : " << timeString << " ms: " << time.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Sun, 26 Dec 2021 23:59:59 GMT"); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, TimeAsLocal) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "Asia/Kolkata", 1); - tzset(); - - - Time orig(2004, 12, 26, 8, 30, 45, 737, true); - - string timeString; - orig.ToString(timeString, true); - std::cout << "Reference local 2004-12-26 08:30:45 737 : " << timeString << " ms: " << orig.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Sun, 26 Dec 2004 08:30:45"); - EXPECT_EQ(orig.MilliSeconds(), 737u); - - TimeAsLocal l1(orig); - TimeAsLocal l2; - l2 = orig; - - l1.ToString(timeString); - std::cout << "AsLocal 1 tostring : " << timeString << " ms: " << l1.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Sun, 26 Dec 2004 08:30:45 GMT"); - EXPECT_EQ(l1.MilliSeconds(), 737u); - EXPECT_STREQ(l1.WeekDayName(), "Sun"); - EXPECT_STREQ(l1.MonthName(), "Dec"); - EXPECT_EQ(l1.DayOfYear(), 360u); - EXPECT_EQ(l1.DayOfWeek(), 0u); - EXPECT_EQ(l1.Year(), 2004u); - EXPECT_EQ(l1.Month(), 12u); - EXPECT_EQ(l1.Day(), 26u); - - std::cout << "WeekDayName:" << l1.WeekDayName() << " MonthName:" << l1.MonthName() << " DayOfYear:" << l1.DayOfYear() << " DayOfWeek:" << static_cast(l1.DayOfWeek()) << std::endl; - std::cout << "Year:" << static_cast(l1.Year()) << " Month:" << static_cast(l1.Month()) << " Day:" << static_cast(l1.Day()) << " Hours:" << static_cast(l1.Hours()) << " Minutes:" << static_cast(l1.Minutes()) << " Seconds:" << static_cast(l1.Seconds()) << " MilliSeconds:" << l1.MilliSeconds() << std::endl; - - l2.ToString(timeString); - std::cout << "AsLocal 2 tostring : " << timeString << " ms: " << l2.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), "Sun, 26 Dec 2004 08:30:45 GMT"); - EXPECT_EQ(l2.MilliSeconds(), 737u); - EXPECT_STREQ(l2.WeekDayName(), "Sun"); - EXPECT_STREQ(l2.MonthName(), "Dec"); - EXPECT_EQ(l2.DayOfYear(), 360u); - EXPECT_EQ(l2.DayOfWeek(), 0u); - EXPECT_EQ(l2.Year(), 2004u); - EXPECT_EQ(l2.Month(), 12u); - EXPECT_EQ(l2.Day(), 26u); - - std::cout << "WeekDayName:" << l2.WeekDayName() << " MonthName:" << l2.MonthName() << " DayOfYear:" << l2.DayOfYear() << " DayOfWeek:" << static_cast(l2.DayOfWeek()) << std::endl; - std::cout << "Year:" << static_cast(l2.Year()) << " Month:" << static_cast(l2.Month()) << " Day:" << static_cast(l2.Day()) << " Hours:" << static_cast(l2.Hours()) << " Minutes:" << static_cast(l2.Minutes()) << " Seconds:" << static_cast(l2.Seconds()) << " MilliSeconds:" << l2.MilliSeconds() << std::endl; - - l1.Add((3600 * 3 * 1000) + 500); // add 3 hours and 500 ms - l1.ToString(timeString); - EXPECT_STREQ(timeString.c_str(), "Sun, 26 Dec 2004 11:30:46 GMT"); - EXPECT_EQ(l1.MilliSeconds(), 237u); - - std::cout << "AsLocal + 3 hr and 500 ms : " << timeString << " ms: " << l1.MilliSeconds() << std::endl; - l1.Sub((3600 * 3 * 1000) + 500); // add 3 hours and 500 ms - l1.ToString(timeString); - EXPECT_STREQ(timeString.c_str(), "Sun, 26 Dec 2004 08:30:45 GMT"); - EXPECT_EQ(l1.MilliSeconds(), 737u); - std::cout << "AsLocal - 3 hr and 500 ms : " << timeString << " ms: " << l1.MilliSeconds() << std::endl; - - Time t1 = l1.ToUTC(); - orig.ToString(timeString, true); - EXPECT_STREQ(timeString.c_str(), "Sun, 26 Dec 2004 08:30:45"); - EXPECT_EQ(t1.MilliSeconds(), 737u); - std::cout << "Back to UTC local 2004-12-26 08:30:45 737 local: " << timeString << " ms: " << t1.MilliSeconds() << std::endl; - orig.ToString(timeString, false); - EXPECT_STREQ(timeString.c_str(), "Sun, 26 Dec 2004 03:00:45 GMT"); - std::cout << "Back to UTC local 2004-12-26 08:30:45 737 as UTC : " << timeString << " ms: " << t1.MilliSeconds() << std::endl; - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, JulianDate) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - Time time1(2002, 5, 10, 11, 30, 23, 21, true); - Time time2(2002, 5, 10, 11, 30, 24, 22, true); - // Doing simple comparison based on time difference - EXPECT_GE(time2.JulianDate(), time1.JulianDate()); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, OperatorOverloadingEqual) -{ - Time time1(2002, 5, 10, 11, 30, 23, 22, true); - Time time2(2002, 5, 10, 11, 30, 23, 22, true); - EXPECT_EQ(time1 == time2, true); - time1 = Time(1971, 5, 10, 11, 4, 24, 21, true); - time2 = Time(1971, 5, 10, 11, 4, 24, 21, true); - EXPECT_EQ(time1 == time2, true); -} -TEST(Core_Time, OperatorOverloadingEqual_CheckNotEqualValues) -{ - Time time1(2002, 5, 10, 11, 35, 23, 21, true); - Time time2(2002, 5, 10, 11, 30, 23, 22, true); - EXPECT_EQ(time1 == time2, false); - time1 = Time(1971, 5, 10, 11, 4, 24, 21, true); - time2 = Time(1971, 5, 11, 11, 4, 24, 21, true); - EXPECT_EQ(time1 == time2, false); -} -TEST(Core_Time, OperatorOverloadingNotEqual) -{ - Time time1(2001, 5, 10, 11, 30, 23, 20, true); - Time time2(2002, 5, 10, 11, 30, 23, 22, true); - EXPECT_EQ(time1 != time2, true); - time1 = Time(1971, 5, 10, 11, 4, 24, 21, true); - time2 = Time(1970, 5, 10, 11, 4, 24, 26, true); - EXPECT_EQ(time1 != time2, true); -} -TEST(Core_Time, OperatorOverloadingNotEqual_CheckEqualValues) -{ - Time time1(2015, 12, 10, 11, 30, 23, 55, true); - Time time2(2015, 12, 10, 11, 30, 23, 55, true); - EXPECT_EQ(time1 != time2, false); - time1 = Time(1971, 8, 11, 11, 4, 24, 21, true); - time2 = Time(1971, 8, 11, 11, 4, 24, 21, true); - EXPECT_EQ(time1 != time2, false); -} -TEST(Core_Time, OperatorOverloadingLessThan) -{ - // Difference in milliseconds - Time time1(2002, 5, 10, 11, 30, 23, 21, true); - Time time2(2002, 5, 10, 11, 30, 23, 22, true); - EXPECT_EQ(time1 < time2, true); - - // Difference in Seconds - time1 = Time(2002, 5, 10, 11, 30, 23, 21, true); - time2 = Time(2002, 5, 10, 11, 30, 24, 21, true); - EXPECT_EQ(time1 < time2, true); - - // Difference in minutes - time1 = Time(2002, 5, 10, 11, 30, 23, 21, true); - time2 = Time(2002, 5, 10, 11, 35, 23, 22, true); - EXPECT_EQ(time1 < time2, true); - - // Difference in hours - time1 = Time(2002, 5, 10, 11, 30, 23, 21, true); - time2 = Time(2002, 5, 10, 13, 30, 23, 21, true); - EXPECT_EQ(time1 < time2, true); - - // Difference in days - time1 = Time(2002, 5, 10, 11, 30, 23, 21, true); - time2 = Time(2002, 5, 12, 11, 30, 23, 21, true); - EXPECT_EQ(time1 < time2, true); - - // Difference in months - time1 = Time(2002, 5, 10, 11, 30, 23, 21, true); - time2 = Time(2002, 6, 10, 11, 30, 23, 21, true); - EXPECT_EQ(time1 < time2, true); - - // Difference in years - time1 = Time(2002, 5, 10, 11, 30, 23, 21, true); - time2 = Time(2004, 5, 10, 11, 30, 23, 21, true); - EXPECT_EQ(time1 < time2, true); -} -TEST(Core_Time, OperatorOverlessGreaterThan_CheckNotLessThanValues) -{ - // Check with equals - Time time1(2020, 2, 1, 14, 30, 35, 41, true); - Time time2(2020, 2, 1, 14, 30, 35, 41, true); - EXPECT_EQ(time1 > time2, false); - - // Check with greater values - time1 = Time(2008, 5, 10, 11, 30, 25, 21, true); - time2 = Time(2006, 5, 10, 11, 30, 26, 21, true); - EXPECT_EQ(time1 < time2, false); - time1 = Time(2002, 5, 10, 13, 40, 23, 21, true); - time2 = Time(2002, 5, 10, 12, 35, 23, 22, true); - EXPECT_EQ(time1 < time2, false); - time1 = Time(2002, 5, 10, 11, 30, 23, 26, true); - time2 = Time(2002, 5, 10, 11, 30, 23, 24, true); - EXPECT_EQ(time1 < time2, false); -} -TEST(Core_Time, OperatorOverloadingLessThanEqual) -{ - // Difference in milliseconds - Time time1(2002, 5, 10, 11, 30, 23, 21, true); - Time time2(2002, 5, 10, 11, 30, 23, 22, true); - EXPECT_EQ(time1 <= time2, true); - - // Difference in Seconds - time1 = Time(2002, 5, 10, 11, 30, 23, 21, true); - time2 = Time(2002, 5, 10, 11, 30, 24, 21, true); - EXPECT_EQ(time1 <= time2, true); - - // Difference in minutes - time1 = Time(2002, 5, 10, 11, 30, 23, 21, true); - time2 = Time(2002, 5, 10, 11, 35, 23, 22, true); - EXPECT_EQ(time1 <= time2, true); - - // Difference in hours - time1 = Time(2002, 5, 10, 11, 30, 23, 21, true); - time2 = Time(2002, 5, 10, 13, 30, 23, 21, true); - EXPECT_EQ(time1 <= time2, true); - - // Difference in days - time1 = Time(2002, 5, 10, 11, 30, 23, 21, true); - time2 = Time(2002, 5, 12, 11, 30, 23, 21, true); - EXPECT_EQ(time1 <= time2, true); - - // Difference in months - time1 = Time(2002, 5, 10, 11, 30, 23, 21, true); - time2 = Time(2002, 6, 10, 11, 30, 23, 21, true); - EXPECT_EQ(time1 <= time2, true); - - // Difference in years - time1 = Time(2002, 5, 10, 11, 30, 23, 21, true); - time2 = Time(2004, 5, 10, 11, 30, 23, 21, true); - EXPECT_EQ(time1 <= time2, true); - - // Using equal time - time1 = Time(2002, 5, 10, 11, 30, 23, 21, true); - time2 = Time(2002, 5, 10, 11, 30, 23, 21, true); - EXPECT_EQ(time1 <= time2, true); -} -TEST(Core_Time, OperatorOverloadingLessThanEqual_CheckNotLessThanEqualValues) -{ - // Check with greater values - Time time1(2004, 5, 10, 11, 30, 23, 21, true); - Time time2(2002, 5, 10, 11, 30, 24, 21, true); - EXPECT_EQ(time1 <= time2, false); - time1 = Time(2002, 5, 10, 14, 30, 23, 21, true); - time2 = Time(2002, 5, 10, 11, 35, 23, 22, true); - EXPECT_EQ(time1 <= time2, false); - time1 = Time(2004, 5, 10, 11, 30, 23, 22, true); - time2 = Time(2004, 5, 10, 11, 30, 23, 21, true); - EXPECT_EQ(time1 <= time2, false); -} -TEST(Core_Time, OperatorOverloadingGreaterThan) -{ - // Difference in milliseconds - Time time1(2002, 5, 10, 11, 30, 23, 23, true); - Time time2(2002, 5, 10, 11, 30, 23, 21, true); - EXPECT_EQ(time1 > time2, true); - - // Difference in Seconds - time1 = Time(2002, 5, 10, 11, 30, 25, 21, true); - time2 = Time(2002, 5, 10, 11, 30, 24, 21, true); - EXPECT_EQ(time1 > time2, true); - - // Difference in minutes - time1 = Time(2002, 5, 10, 11, 40, 23, 22, true); - time2 = Time(2002, 5, 10, 11, 35, 23, 22, true); - EXPECT_EQ(time1 > time2, true); - - // Difference in hours - time1 = Time(2002, 5, 10, 14, 30, 23, 21, true); - time2 = Time(2002, 5, 10, 13, 30, 23, 21, true); - EXPECT_EQ(time1 > time2, true); - - // Difference in days - time1 = Time(2002, 5, 24, 11, 30, 23, 21, true); - time2 = Time(2002, 5, 12, 11, 30, 23, 21, true); - EXPECT_EQ(time1 > time2, true); - - // Difference in months - time1 = Time(2002, 7, 10, 11, 30, 23, 21, true); - time2 = Time(2002, 6, 10, 11, 30, 23, 21, true); - EXPECT_EQ(time1 > time2, true); - - // Difference in years - time1 = Time(2010, 5, 10, 11, 30, 23, 21, true); - time2 = Time(2004, 5, 10, 11, 30, 23, 21, true); - EXPECT_EQ(time1 > time2, true); -} -TEST(Core_Time, OperatorOverloadingGreaterThan_CheckNotGreaterThanValues) -{ - // Check with equals - Time time1(2002, 5, 10, 11, 30, 23, 21, true); - Time time2(2002, 5, 10, 11, 30, 23, 21, true); - EXPECT_EQ(time1 > time2, false); - - // Check with lesser values - time1 = Time(2004, 5, 10, 11, 30, 25, 21, true); - time2 = Time(2006, 5, 10, 11, 30, 26, 21, true); - EXPECT_EQ(time1 > time2, false); - time1 = Time(2002, 5, 10, 11, 30, 23, 21, true); - time2 = Time(2002, 5, 10, 12, 35, 23, 22, true); - EXPECT_EQ(time1 > time2, false); - time1 = Time(2002, 5, 10, 11, 30, 23, 22, true); - time2 = Time(2002, 5, 10, 11, 30, 23, 24, true); - EXPECT_EQ(time1 > time2, false); -} -TEST(Core_Time, OperatorOverloadingGreaterThanEqual) -{ - // Difference in milliseconds - Time time1(2002, 5, 10, 11, 30, 23, 23, true); - Time time2(2002, 5, 10, 11, 30, 23, 21, true); - EXPECT_EQ(time1 >= time2, true); - - // Difference in Seconds - time1 = Time(2002, 5, 10, 11, 30, 25, 21, true); - time2 = Time(2002, 5, 10, 11, 30, 24, 21, true); - EXPECT_EQ(time1 >= time2, true); - - // Difference in minutes - time1 = Time(2002, 5, 10, 11, 40, 23, 22, true); - time2 = Time(2002, 5, 10, 11, 35, 23, 22, true); - EXPECT_EQ(time1 >= time2, true); - - // Difference in hours - time1 = Time(2002, 5, 10, 14, 30, 23, 21, true); - time2 = Time(2002, 5, 10, 13, 30, 23, 21, true); - EXPECT_EQ(time1 >= time2, true); - - // Difference in days - time1 = Time(2002, 5, 24, 11, 30, 23, 21, true); - time2 = Time(2002, 5, 12, 11, 30, 23, 21, true); - EXPECT_EQ(time1 >= time2, true); - - // Difference in months - time1 = Time(2002, 7, 10, 11, 30, 23, 21, true); - time2 = Time(2002, 6, 10, 11, 30, 23, 21, true); - EXPECT_EQ(time1 >= time2, true); - - // Difference in years - time1 = Time(2010, 5, 10, 11, 30, 23, 21, true); - time2 = Time(2004, 5, 10, 11, 30, 23, 21, true); - EXPECT_EQ(time1 >= time2, true); - - // Using equal time - time1 = Time(2012, 10, 1, 3, 45, 34, 10, true); - time2 = Time(2012, 10, 1, 3, 45, 34, 10, true); - EXPECT_EQ(time1 >= time2, true); -} -TEST(Core_Time, OperatorOverloadingGreaterThan_CheckNotGreaterThanEqualValues) -{ - // Check with lesser values - Time time1(2004, 5, 10, 11, 30, 25, 21, true); - Time time2(2006, 5, 10, 11, 30, 26, 21, true); - EXPECT_EQ(time1 >= time2, false); - time1 = Time(2000, 5, 9, 11, 30, 2, 21, true); - time2 = Time(2002, 5, 10, 12, 35, 23, 22, true); - EXPECT_EQ(time1 >= time2, false); - time1 = Time(1980, 5, 10, 11, 30, 23, 22, true); - time2 = Time(1980, 5, 10, 11, 30, 23, 24, true); - EXPECT_EQ(time1 >= time2, false); -} -TEST(Core_Time, OperatorOverloadingAssignment) -{ - Time time1(2002, 5, 10, 11, 30, 23, 22, true); - Time time2 = time1; - EXPECT_EQ(time1 == time2, true); - time2 = Time(1971, 5, 10, 11, 4, 24, 21, true); - time1 = time2; - EXPECT_EQ(time1 == time2, true); -} -TEST(Core_Time, OperatorOverloadingAddition) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - Time time1(2002, 5, 10, 11, 30, 23, 22, true); - Time time2; - Time time3 = time1 + time2; - EXPECT_EQ(time1 == time3, true); - - Time time4(2000, 5, 10, 11, 30, 23, 22, true); - Time time5 = time3 + time4; - string timeString; - time5.ToString(timeString); - - // Time will be saved/set based on 1st of January 1970, 00:00:00 time base. - // So the saved time values will be always the one subtracted with time base. - // Hence the '+=' works only on the subtracted values and here the value - // will be based on that differences - EXPECT_STREQ(timeString.c_str(), "Thu, 16 Sep 2032 23:00:46"); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, OperatorOverloadingSubtraction) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - Time time1(2002, 8, 8, 11, 30, 23, 22, true); - Time time2(2000, 3, 1, 8, 25, 22, 1, true); - - Time time3 = time1 - time2; - string timeString; - time3.ToString(timeString); - - // Time will be saved/set based on 1st of January 1970, 00:00:00 time base. - // So the saved time values will be always the one subtracted with time base. - // Hence the '-=' works only on the subtracted values and here the value - // will be based on that differences - EXPECT_STREQ(timeString.c_str(), "Fri, 09 Jun 1972 03:05:01"); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, OperatorOverloadingAdditionWithAssignment) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - Time time1(2002, 5, 10, 11, 30, 23, 22, true); - Time time2; - time2 += time1; - EXPECT_EQ(time1 == time2, true); - - Time time3(2000, 5, 10, 11, 30, 23, 22, true); - time3 += time2; - string timeString; - time3.ToString(timeString); - - // Time will be saved/set based on 1st of January 1970, 00:00:00 time base. - // So the saved time values will be always the one subtracted with time base. - // Hence the '+=' works only on the subtracted values and here the value - // will be based on that differences - EXPECT_STREQ(timeString.c_str(), "Thu, 16 Sep 2032 23:00:46"); - - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} -TEST(Core_Time, OperatorOverloadingSubtractionWithAssignment) -{ - char* currentZone = getenv("TZ"); - setenv("TZ", "", 1); - tzset(); - - Time time1(2002, 8, 8, 11, 30, 23, 22, true); - Time time2(2000, 3, 1, 8, 25, 22, 1, true);; - time1 -= time2; - - string timeString; - time1.ToString(timeString); - // Time will be saved/set based on 1st of January 1970, 00:00:00 time base. - // So the saved time values will be always the one subtracted with time base. - // Hence the '-=' works only on the subtracted values and here the value - // will be based on that differences - EXPECT_STREQ(timeString.c_str(), "Fri, 09 Jun 1972 03:05:01"); - (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); - tzset(); -} + time = ::Thunder::Core::Time(2018, 2, 23, 11, 30, 23, 21, false); + time.ToString(timeString, false); + time.FromRFC1123(timeString); + EXPECT_STREQ(timeString.c_str(), _T("Fri, 23 Feb 2018 11:30:23 GMT")); + + time = ::Thunder::Core::Time(2018, 3, 23, 11, 30, 23, 21, false); + time.ToString(timeString, false); + time.FromRFC1123(timeString); + EXPECT_STREQ(timeString.c_str(), _T("Fri, 23 Mar 2018 11:30:23 GMT")); + + time = ::Thunder::Core::Time(2018, 4, 23, 11, 30, 23, 21, false); + time.ToString(timeString, false); + time.FromRFC1123(timeString); + EXPECT_STREQ(timeString.c_str(), _T("Mon, 23 Apr 2018 11:30:23 GMT")); + + time = ::Thunder::Core::Time(2018, 5, 23, 11, 30, 23, 21, false); + time.ToString(timeString, false); + time.FromRFC1123(timeString); + EXPECT_STREQ(timeString.c_str(), _T("Wed, 23 May 2018 11:30:23 GMT")); + + time = ::Thunder::Core::Time(2018, 6, 23, 11, 30, 23, 21, false); + time.ToString(timeString, false); + time.FromRFC1123(timeString); + EXPECT_STREQ(timeString.c_str(), _T("Sat, 23 Jun 2018 11:30:23 GMT")); + + time = ::Thunder::Core::Time(2018, 7, 23, 11, 30, 23, 21, false); + time.ToString(timeString, false); + time.FromRFC1123(timeString); + EXPECT_STREQ(timeString.c_str(), _T("Mon, 23 Jul 2018 11:30:23 GMT")); + + time = ::Thunder::Core::Time(2018, 8, 23, 11, 30, 23, 21, false); + time.ToString(timeString, false); + time.FromRFC1123(timeString); + EXPECT_STREQ(timeString.c_str(), _T("Thu, 23 Aug 2018 11:30:23 GMT")); + + time = ::Thunder::Core::Time(2018, 9, 23, 11, 30, 23, 21, false); + time.ToString(timeString, false); + time.FromRFC1123(timeString); + EXPECT_STREQ(timeString.c_str(), _T("Sun, 23 Sep 2018 11:30:23 GMT")); + + time = ::Thunder::Core::Time(2018, 10, 23, 11, 30, 23, 21, false); + time.ToString(timeString, false); + time.FromRFC1123(timeString); + EXPECT_STREQ(timeString.c_str(), _T("Tue, 23 Oct 2018 11:30:23 GMT")); + + time = ::Thunder::Core::Time(2018, 11, 23, 11, 30, 23, 21, false); + time.ToString(timeString, false); + time.FromRFC1123(timeString); + EXPECT_STREQ(timeString.c_str(), _T("Fri, 23 Nov 2018 11:30:23 GMT")); + + time = ::Thunder::Core::Time(2018, 12, 23, 11, 30, 23, 21, false); + time.ToString(timeString, false); + EXPECT_EQ(time.FromRFC1123(timeString), true); + EXPECT_STREQ(timeString.c_str(), _T("Sun, 23 Dec 2018 11:30:23 GMT")); + + time = ::Thunder::Core::Time(1970, 12, 23, 11, 30, 23, 21, false); + time.ToString(timeString, false); + EXPECT_EQ(time.FromRFC1123(timeString), true); + + time = ::Thunder::Core::Time(1980, 12, 23, 11, 30, 23, 21, false); + time.ToString(timeString, false); + EXPECT_EQ(time.FromRFC1123(timeString), true); + } + TEST(Core_Time, FromStandard_RFC1123_TimeStringCreatedFromTime_InvalidCase) + { + ::Thunder::Core::Time time = ::Thunder::Core::Time(2018, 1, 23, 11, 30, 23, 21, false); + std::string timeString; + time.ToString(timeString, false); + EXPECT_STREQ(timeString.c_str(), "Tue, 23 Jan 2018 11:30:23 GMT"); + EXPECT_EQ(time.FromRFC1123(timeString), true); + + time = ::Thunder::Core::Time(2080, 12, 23, 11, 30, 23, 21, false); + time.ToString(timeString, false); + EXPECT_STREQ(timeString.c_str(), "Mon, 23 Dec 2080 11:30:23 GMT"); + EXPECT_EQ(time.FromRFC1123(timeString), true); + } + TEST(Core_Time, FromStandard_RFC1123_TimeStringCreatedWithLocalTimeEnabled) + { + ::Thunder::Core::Time time; + std::string timeString; + time = ::Thunder::Core::Time(2000, 12, 23, 11, 30, 23, 21, true); + time.ToString(timeString, false); + EXPECT_EQ(time.FromRFC1123(timeString), true); + } + TEST(Core_Time, FromStandard_RFC1123_LocalTimeDisabled) + { + ::Thunder::Core::Time time; + std::string timeString; + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08:59:27 UTC"), true); + time.ToString(timeString, false); + EXPECT_STREQ(timeString.c_str(), _T("Sun, 06 Nov 1994 08:59:27 GMT")); + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, FromStandard_RFC1123_LocalTimeEnabled) + { + ::Thunder::Core::Time time; + std::string timeString; + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 08:59:27 UTC"), true); + time.ToString(timeString, true); + EXPECT_STREQ(timeString.c_str(), _T("Sun, 06 Nov 1994 08:59:27")); + + // Check time difference after set time zone to GST + setenv("TZ", "GST", 1); + tzset(); + + // Set without timezone + EXPECT_EQ(time.FromRFC1123("Sun, 06 Nov 1994 09:59:27 UTC"), true); + time.ToString(timeString, true); + EXPECT_STREQ(timeString.c_str(), _T("Sun, 06 Nov 1994 09:59:27")); + + // Set timezone back + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, FromStandard_RFC1123_TimeConversion_WithLocalTimeDisabled) + { + ::Thunder::Core::Time time(1980, 12, 23, 11, 30, 23, 21, true); + std::string timeString1, timeString2; + time.ToString(timeString1, false); + EXPECT_EQ(time.FromRFC1123(timeString1), true); + time.ToString(timeString2, false); + EXPECT_STREQ(timeString1.c_str(), timeString2.c_str()); + } + TEST(Core_Time, FromStandard_RFC1123_TimeConversion_WithCurrentTime_And_LocalTimeDisabled) + { + ::Thunder::Core::Time time(::Thunder::Core::Time::Now()); + std::string timeString1, timeString2; + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + time.ToString(timeString1, false); + EXPECT_EQ(time.FromRFC1123(timeString1), true); + time.ToString(timeString2, false); + EXPECT_STREQ(timeString1.c_str(), timeString2.c_str()); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, FromStandard_RFC1123_TimeConversion_WithLocalTimeEnabled) + { + ::Thunder::Core::Time time(1980, 12, 23, 11, 30, 23, 21, true); + std::string timeString1, timeString2; + time.ToString(timeString1, true); + EXPECT_EQ(time.FromRFC1123(timeString1), true); + time.ToString(timeString2, true); + EXPECT_STREQ(timeString1.c_str(), timeString2.c_str()); + } + TEST(Core_Time, FromStandard_RFC1123_TimeConversion_WithLocalTimeEnabled_And_LocalTimeDisabled) + { + ::Thunder::Core::Time time(::Thunder::Core::Time::Now()); + std::string timeString1, timeString2; + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + time.ToString(timeString1, true); + EXPECT_EQ(time.FromRFC1123(timeString1), true); + time.ToString(timeString2, true); + EXPECT_STREQ(timeString1.c_str(), timeString2.c_str()); + EXPECT_EQ(time.FromRFC1123(timeString2), true); + time.ToString(timeString1, true); + EXPECT_STREQ(timeString2.c_str(), timeString1.c_str()); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, ToStandard_ISO8601) + { + ::Thunder::Core::Time time(::Thunder::Core::Time::Now()); + string timeString; + string timeISOString; + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + // localTime argument value as default + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37Z"), true); + EXPECT_STREQ((time.ToISO8601()).c_str(), "1994-11-06T08:49:37Z"); + EXPECT_EQ(time.FromISO8601("1994-11-06T00:49:37"), true); + EXPECT_STREQ((time.ToISO8601()).c_str(), "1994-11-06T00:49:37Z"); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37"), true); + EXPECT_STREQ((time.ToISO8601()).c_str(), "1994-11-06T08:49:37Z"); + + // localTime argument value as true + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37Z"), true); + EXPECT_STREQ((time.ToISO8601(true)).c_str(), "1994-11-06T08:49:37"); + EXPECT_EQ(time.FromISO8601("1994-11-06T00:49:37"), true); + EXPECT_STREQ((time.ToISO8601(true)).c_str(), "1994-11-06T00:49:37"); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37"), true); + EXPECT_STREQ((time.ToISO8601(true)).c_str(), "1994-11-06T08:49:37"); + + // localTime argument value as true + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37Z"), true); + EXPECT_STREQ((time.ToISO8601(false)).c_str(), "1994-11-06T08:49:37Z"); + EXPECT_EQ(time.FromISO8601("1994-11-06T00:49:37"), true); + EXPECT_STREQ((time.ToISO8601(false)).c_str(), "1994-11-06T00:49:37Z"); + EXPECT_EQ(time.FromISO8601("1994-11-06T08:49:37"), true); + EXPECT_STREQ((time.ToISO8601(false)).c_str(), "1994-11-06T08:49:37Z"); + + // Time with empty value return null string + EXPECT_STREQ((::Thunder::Core::Time().ToISO8601(true)).c_str(), ""); + EXPECT_STREQ((::Thunder::Core::Time().ToISO8601(false)).c_str(), ""); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, ToStandard_RFC1123_WithLocalTimeDisabled) + { + ::Thunder::Core::Time time(1980, 12, 23, 11, 30, 23, 21, true); + std::string timeString1, timeString2; + timeString1 = time.ToRFC1123(false); + EXPECT_EQ(time.FromRFC1123(timeString1), true); + timeString2 = time.ToRFC1123(false); + EXPECT_STREQ(timeString1.c_str(), timeString2.c_str()); + } + TEST(Core_Time, ToStandard_RFC1123_WithCurrentTime_And_LocalTimeDisabled) + { + ::Thunder::Core::Time time(::Thunder::Core::Time::Now()); + std::string timeString1, timeString2; + timeString1 = time.ToRFC1123(false); + EXPECT_EQ(time.FromRFC1123(timeString1), true); + timeString2 = time.ToRFC1123(false); + EXPECT_STREQ(timeString1.c_str(), timeString2.c_str()); + } + TEST(Core_Time, ToStandard_RFC1123_WithLocalTimeEnabled) + { + ::Thunder::Core::Time time(2000, 12, 23, 11, 30, 23, 21, true); + std::string timeString1, timeString2; + timeString1 = time.ToRFC1123(true); + EXPECT_EQ(time.FromRFC1123(timeString1), true); + timeString2 = time.ToRFC1123(true); + EXPECT_STREQ(timeString1.c_str(), timeString2.c_str()); + + } + TEST(Core_Time, ToStandard_RFC1123_WithLocalTimeEnabled_And_LocalTimeDisabled) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + ::Thunder::Core::Time time(::Thunder::Core::Time::Now()); + std::string timeString1, timeString2; + timeString1 = time.ToRFC1123(true); + EXPECT_EQ(time.FromRFC1123(timeString1), true); + timeString2 = time.ToRFC1123(true); + EXPECT_STREQ(timeString1.c_str(), timeString2.c_str()); + EXPECT_EQ(time.FromRFC1123(timeString2), true); + timeString1 = time.ToRFC1123(true); + EXPECT_STREQ(timeString2.c_str(), timeString1.c_str()); + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, Ticks_withoutInterval) + { + ::Thunder::Core::Time time1 = ::Thunder::Core::Time::Now(); + ::Thunder::Core::Time time2 = ::Thunder::Core::Time::Now(); + uint64_t diff = time2.Ticks() - time1.Ticks(); + uint32_t intervalInSeconds = diff / ::Thunder::Core::Time::MicroSecondsPerSecond; + EXPECT_EQ(intervalInSeconds, static_cast(0)); + } + TEST(Core_Time, Ticks_TimeCtor) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + setenv("TZ", "Europe/Amsterdam", 1); + tzset(); + + ::Thunder::Core::Time orig(2016,10, 3, 10, 11, 12, 666, true); + ::Thunder::Core::Time::microsecondsfromepoch flattime = orig.Ticks(); + + std::cout << " Ticks for local 2016-10-03 10:11:12 666 (so UTC ticks) : " << flattime << std::endl; + ::Thunder::Core::Time copyutc(flattime); + string timeString; + copyutc.ToString(timeString, true); + std::cout << "Localtime 2016-10-03 10:11:12 666 : " << timeString << " ms: " << copyutc.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Mon, 03 Oct 2016 10:11:12"); + + copyutc.ToString(timeString, false); + std::cout << "UTC 2016-10-03 08:11:12 666 : " << timeString << " ms: " << copyutc.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Mon, 03 Oct 2016 08:11:12 GMT"); + EXPECT_EQ(copyutc.MilliSeconds(), 666u); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, Ticks_withInterval) + { + uint32_t givenIntervalInSeconds = 2; + ::Thunder::Core::Time time1 = ::Thunder::Core::Time::Now(); + sleep(givenIntervalInSeconds); + ::Thunder::Core::Time time2 = ::Thunder::Core::Time::Now(); + uint64_t diff = time2.Ticks() - time1.Ticks(); + uint32_t intervalInSeconds = diff / ::Thunder::Core::Time::MicroSecondsPerSecond; + EXPECT_EQ(intervalInSeconds, givenIntervalInSeconds); + } + TEST(Core_Time, AddTime) + { + ::Thunder::Core::Time time(::Thunder::Core::Time::Now()); + std::string timeString1, timeString2; + time.ToString(timeString1); + uint32_t currentTime = time.MilliSeconds(); + uint32_t timeTobeAdded = 2; + time.Add(timeTobeAdded); + uint32_t newTime = time.MilliSeconds(); + time.ToString(timeString2); + EXPECT_EQ(newTime, currentTime + timeTobeAdded); + currentTime = time.Seconds(); + timeTobeAdded = 3; + time.Add(timeTobeAdded * 1000); + time.ToString(timeString1); + EXPECT_STRNE(timeString1.c_str(), timeString2.c_str()); + uint32_t expectedAddedTime = 0; + if (currentTime + timeTobeAdded >= 60) { + expectedAddedTime = (currentTime + timeTobeAdded) - 60; + } else { + expectedAddedTime = (currentTime + timeTobeAdded); + } + + newTime = time.Seconds(); + EXPECT_EQ(newTime, expectedAddedTime); + } + TEST(Core_Time, DISABLED_SubTime) + { + ::Thunder::Core::Time time(::Thunder::Core::Time::Now()); + std::string timeString1, timeString2; + time.ToString(timeString1); + uint32_t currentTime = time.MilliSeconds(); + uint32_t timeTobeSubtracted = 4; + time.Sub(timeTobeSubtracted); + uint32_t newTime = time.MilliSeconds(); + time.ToString(timeString2); + EXPECT_EQ(newTime, currentTime - timeTobeSubtracted); + currentTime = time.Seconds(); + timeTobeSubtracted = 6; + time.Sub(timeTobeSubtracted * 1000); + time.ToString(timeString1); + EXPECT_STRNE(timeString1.c_str(), timeString2.c_str()); + uint32_t expectedSubtractedTime = 0; + if (currentTime <= timeTobeSubtracted) { + expectedSubtractedTime = 60 - (timeTobeSubtracted - currentTime); + expectedSubtractedTime = (expectedSubtractedTime == 60) ? 0 : expectedSubtractedTime; + } else { + expectedSubtractedTime = (currentTime - timeTobeSubtracted); + } + newTime = time.Seconds(); + EXPECT_EQ(newTime, expectedSubtractedTime);; + } + TEST(Core_Time, NTPTime) + { + ::Thunder::Core::Time time(1970, 1, 1, 0, 0, 0, 1, true); + const uint64_t ntpTime = time.NTPTime(); + EXPECT_GE(ntpTime/::Thunder::Core::Time::MicroSecondsPerSecond, static_cast(0)); + uint32_t timeTobeAdded = 4; + time.Add(timeTobeAdded); + + EXPECT_GE(time.NTPTime()/::Thunder::Core::Time::MicroSecondsPerSecond, ntpTime/::Thunder::Core::Time::MicroSecondsPerSecond + (timeTobeAdded * 4)); + } + TEST(Core_Time, Format) + { + ::Thunder::Core::Time time(2002, 5, 10, 11, 30, 23, 21, false); + EXPECT_STREQ(time.Format("%Y-%m-%d").c_str(), "2002-05-10"); + EXPECT_STREQ(time.Format("%d-%m-%Y").c_str(), "10-05-2002"); + time = ::Thunder::Core::Time(1970, 5, 31, 11, 30, 23, 21, false); + EXPECT_STREQ(time.Format("%Y-%m-%d").c_str(), "1970-05-31"); + EXPECT_STREQ(time.Format("%Y %m %d").c_str(), "1970 05 31"); + EXPECT_STREQ(time.Format("%Y:%m:%d").c_str(), "1970:05:31"); + + time = ::Thunder::Core::Time(1969, 5, 31, 11, 30, 23, 21, false); + EXPECT_STREQ(time.Format("%Y-%m-%d").c_str(), "1969-05-31"); + } + TEST(Core_Time, ToTimeOnly) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + ::Thunder::Core::Time time(2002, 5, 10, 11, 30, 23, 21, false); + EXPECT_STREQ(time.ToTimeOnly(false).c_str(), "11:30:23GMT"); + EXPECT_EQ(time.MilliSeconds(), static_cast(21)); + time = ::Thunder::Core::Time(1970, 5, 31, 0, 30, 23, 21, false); + EXPECT_STREQ(time.ToTimeOnly(false).c_str(), "00:30:23GMT"); + time = ::Thunder::Core::Time(1970, 5, 31, 23, 0, 23, 21, false); + EXPECT_STREQ(time.ToTimeOnly(false).c_str(), "23:00:23GMT"); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, ToTimeOnly_LocalTimeEnabled) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + ::Thunder::Core::Time time(2002, 5, 10, 11, 30, 23, 21, false); + EXPECT_STREQ(time.ToTimeOnly(true).c_str(), "11:30:23"); + EXPECT_EQ(time.MilliSeconds(), static_cast(21)); + + // Check time difference after set time zone to GST + setenv("TZ", "GST", 1); + tzset(); + + // Check time after unset time zone + time = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 23, 21, false); + EXPECT_STREQ(time.ToTimeOnly(true).c_str(), "11:30:23"); + EXPECT_EQ(time.MilliSeconds(), static_cast(21)); + + setenv("TZ", "Africa/Algiers", 1); + tzset(); + time = ::Thunder::Core::Time(1970, 5, 31, 0, 30, 23, 21, false); + EXPECT_STREQ(time.ToTimeOnly(true).c_str(), "00:30:23"); + + setenv("TZ", "Asia/Kolkata", 1); + tzset(); + time = ::Thunder::Core::Time(1970, 5, 31, 22, 0, 23, 21, false); + EXPECT_STREQ(time.ToTimeOnly(true).c_str(), "03:30:23"); + + setenv("TZ", "GST", 1); + tzset(); + setenv("TZ", "America/Los_Angeles", 1); + tzset(); + time = ::Thunder::Core::Time(80, 12, 23, 11, 30, 23, 21, false); + //EXPECT_STREQ(time.ToTimeOnly(true).c_str(), "03:30:23"); + + setenv("TZ", "GST", 1); + tzset(); + setenv("TZ", "Europe/Amsterdam", 1); + tzset(); + time = ::Thunder::Core::Time(80, 12, 23, 11, 30, 23, 21, false); + //EXPECT_STREQ(time.ToTimeOnly(true).c_str(), "12:30:23"); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, ToTimeOnly_LocalTimeDisabled) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + ::Thunder::Core::Time time(2002, 5, 10, 11, 30, 23, 21, false); + EXPECT_STREQ(time.ToTimeOnly(false).c_str(), "11:30:23GMT"); + EXPECT_EQ(time.MilliSeconds(), static_cast(21)); + + setenv("TZ", "Africa/Algiers", 1); + tzset(); + time = ::Thunder::Core::Time(1970, 5, 31, 0, 30, 23, 21, false); + EXPECT_STREQ(time.ToTimeOnly(false).c_str(), "00:30:23GMT"); + + setenv("TZ", "Asia/Kolkata", 1); + tzset(); + time = ::Thunder::Core::Time(1970, 5, 31, 0, 0, 23, 21, false); + EXPECT_STREQ(time.ToTimeOnly(false).c_str(), "00:00:23GMT"); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, TimeWithLocalTimeTrue_ConvertTo_UTC_And_Local) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + setenv("TZ", "Europe/Amsterdam", 1); + tzset(); + + string timeString; + ::Thunder::Core::Time time = ::Thunder::Core::Time(2021, 07, 05, 22, 10, 5, 999, true); + EXPECT_EQ(time.MilliSeconds(), 999u); + time.ToString(timeString, true); + std::cout << "LocalTime 2021-07-05 22:10:05.999 : " << timeString << " ms: " << time.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Mon, 05 Jul 2021 22:10:05"); + time.ToString(timeString, false); + std::cout << "UTC 2021-07-05 20:10:05.999 : " << timeString << " ms: " << time.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Mon, 05 Jul 2021 20:10:05 GMT"); + + time = ::Thunder::Core::Time(2021,12, 26, 23, 59, 59, 1, true); + EXPECT_EQ(time.MilliSeconds(), 1u); + time.ToString(timeString, true); + std::cout << "LocalTime 2021-12-26 23:59:59.001 : " << timeString << " ms: " << time.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Sun, 26 Dec 2021 23:59:59"); + time.ToString(timeString, false); + std::cout << "UTC 2021-12-26 22:59:59.001 : " << timeString << " ms: " << time.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Sun, 26 Dec 2021 22:59:59 GMT"); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, TimeWithLocalTimeFalse_ConvertTo_UTC_And_Local) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + setenv("TZ", "Europe/Amsterdam", 1); + tzset(); + + string timeString; + ::Thunder::Core::Time time = ::Thunder::Core::Time(2021, 07, 05, 22, 10, 5, 999, false); + EXPECT_EQ(time.MilliSeconds(), 999u); + time.ToString(timeString, true); + std::cout << "LocalTime 2021-07-06 00:10:05.999 : " << timeString << " ms: " << time.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Tue, 06 Jul 2021 00:10:05"); + time.ToString(timeString, false); + std::cout << "UTC 2021-07-05 22:10:05.999 : " << timeString << " ms: " << time.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Mon, 05 Jul 2021 22:10:05 GMT"); + + time = ::Thunder::Core::Time(2021,12, 26, 23, 59, 59, 1, false); + EXPECT_EQ(time.MilliSeconds(), 1u); + time.ToString(timeString, true); + std::cout << "LocalTime 2021-12-27 00:59:59.001 : " << timeString << " ms: " << time.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Mon, 27 Dec 2021 00:59:59"); + time.ToString(timeString, false); + std::cout << "UTC 2021-12-26 23:59:59.001 : " << timeString << " ms: " << time.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Sun, 26 Dec 2021 23:59:59 GMT"); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, TimeAsLocal) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "Asia/Kolkata", 1); + tzset(); + + ::Thunder::Core::Time orig(2004, 12, 26, 8, 30, 45, 737, true); + + string timeString; + orig.ToString(timeString, true); + std::cout << "Reference local 2004-12-26 08:30:45 737 : " << timeString << " ms: " << orig.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Sun, 26 Dec 2004 08:30:45"); + EXPECT_EQ(orig.MilliSeconds(), 737u); + + ::Thunder::Core::TimeAsLocal l1(orig); + ::Thunder::Core::TimeAsLocal l2; + l2 = orig; + + l1.ToString(timeString); + std::cout << "AsLocal 1 tostring : " << timeString << " ms: " << l1.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Sun, 26 Dec 2004 08:30:45 GMT"); + EXPECT_EQ(l1.MilliSeconds(), 737u); + EXPECT_STREQ(l1.WeekDayName(), "Sun"); + EXPECT_STREQ(l1.MonthName(), "Dec"); + EXPECT_EQ(l1.DayOfYear(), 360u); + EXPECT_EQ(l1.DayOfWeek(), 0u); + EXPECT_EQ(l1.Year(), 2004u); + EXPECT_EQ(l1.Month(), 12u); + EXPECT_EQ(l1.Day(), 26u); + + std::cout << "WeekDayName:" << l1.WeekDayName() << " MonthName:" << l1.MonthName() << " DayOfYear:" << l1.DayOfYear() << " DayOfWeek:" << static_cast(l1.DayOfWeek()) << std::endl; + std::cout << "Year:" << static_cast(l1.Year()) << " Month:" << static_cast(l1.Month()) << " Day:" << static_cast(l1.Day()) << " Hours:" << static_cast(l1.Hours()) << " Minutes:" << static_cast(l1.Minutes()) << " Seconds:" << static_cast(l1.Seconds()) << " MilliSeconds:" << l1.MilliSeconds() << std::endl; + + l2.ToString(timeString); + std::cout << "AsLocal 2 tostring : " << timeString << " ms: " << l2.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), "Sun, 26 Dec 2004 08:30:45 GMT"); + EXPECT_EQ(l2.MilliSeconds(), 737u); + EXPECT_STREQ(l2.WeekDayName(), "Sun"); + EXPECT_STREQ(l2.MonthName(), "Dec"); + EXPECT_EQ(l2.DayOfYear(), 360u); + EXPECT_EQ(l2.DayOfWeek(), 0u); + EXPECT_EQ(l2.Year(), 2004u); + EXPECT_EQ(l2.Month(), 12u); + EXPECT_EQ(l2.Day(), 26u); + + std::cout << "WeekDayName:" << l2.WeekDayName() << " MonthName:" << l2.MonthName() << " DayOfYear:" << l2.DayOfYear() << " DayOfWeek:" << static_cast(l2.DayOfWeek()) << std::endl; + std::cout << "Year:" << static_cast(l2.Year()) << " Month:" << static_cast(l2.Month()) << " Day:" << static_cast(l2.Day()) << " Hours:" << static_cast(l2.Hours()) << " Minutes:" << static_cast(l2.Minutes()) << " Seconds:" << static_cast(l2.Seconds()) << " MilliSeconds:" << l2.MilliSeconds() << std::endl; + + l1.Add((3600 * 3 * 1000) + 500); // add 3 hours and 500 ms + l1.ToString(timeString); + EXPECT_STREQ(timeString.c_str(), "Sun, 26 Dec 2004 11:30:46 GMT"); + EXPECT_EQ(l1.MilliSeconds(), 237u); + + std::cout << "AsLocal + 3 hr and 500 ms : " << timeString << " ms: " << l1.MilliSeconds() << std::endl; + l1.Sub((3600 * 3 * 1000) + 500); // add 3 hours and 500 ms + l1.ToString(timeString); + EXPECT_STREQ(timeString.c_str(), "Sun, 26 Dec 2004 08:30:45 GMT"); + EXPECT_EQ(l1.MilliSeconds(), 737u); + std::cout << "AsLocal - 3 hr and 500 ms : " << timeString << " ms: " << l1.MilliSeconds() << std::endl; + + ::Thunder::Core::Time t1 = l1.ToUTC(); + orig.ToString(timeString, true); + EXPECT_STREQ(timeString.c_str(), "Sun, 26 Dec 2004 08:30:45"); + EXPECT_EQ(t1.MilliSeconds(), 737u); + std::cout << "Back to UTC local 2004-12-26 08:30:45 737 local: " << timeString << " ms: " << t1.MilliSeconds() << std::endl; + orig.ToString(timeString, false); + EXPECT_STREQ(timeString.c_str(), "Sun, 26 Dec 2004 03:00:45 GMT"); + std::cout << "Back to UTC local 2004-12-26 08:30:45 737 as UTC : " << timeString << " ms: " << t1.MilliSeconds() << std::endl; + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, JulianDate) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + ::Thunder::Core::Time time1(2002, 5, 10, 11, 30, 23, 21, true); + ::Thunder::Core::Time time2(2002, 5, 10, 11, 30, 24, 22, true); + // Doing simple comparison based on time difference + EXPECT_GE(time2.JulianDate(), time1.JulianDate()); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, OperatorOverloadingEqual) + { + ::Thunder::Core::Time time1(2002, 5, 10, 11, 30, 23, 22, true); + ::Thunder::Core::Time time2(2002, 5, 10, 11, 30, 23, 22, true); + EXPECT_EQ(time1 == time2, true); + time1 = ::Thunder::Core::Time(1971, 5, 10, 11, 4, 24, 21, true); + time2 = ::Thunder::Core::Time(1971, 5, 10, 11, 4, 24, 21, true); + EXPECT_EQ(time1 == time2, true); + } + TEST(Core_Time, OperatorOverloadingEqual_CheckNotEqualValues) + { + ::Thunder::Core::Time time1(2002, 5, 10, 11, 35, 23, 21, true); + ::Thunder::Core::Time time2(2002, 5, 10, 11, 30, 23, 22, true); + EXPECT_EQ(time1 == time2, false); + time1 = ::Thunder::Core::Time(1971, 5, 10, 11, 4, 24, 21, true); + time2 = ::Thunder::Core::Time(1971, 5, 11, 11, 4, 24, 21, true); + EXPECT_EQ(time1 == time2, false); + } + TEST(Core_Time, OperatorOverloadingNotEqual) + { + ::Thunder::Core::Time time1(2001, 5, 10, 11, 30, 23, 20, true); + ::Thunder::Core::Time time2(2002, 5, 10, 11, 30, 23, 22, true); + EXPECT_EQ(time1 != time2, true); + time1 = ::Thunder::Core::Time(1971, 5, 10, 11, 4, 24, 21, true); + time2 = ::Thunder::Core::Time(1970, 5, 10, 11, 4, 24, 26, true); + EXPECT_EQ(time1 != time2, true); + } + TEST(Core_Time, OperatorOverloadingNotEqual_CheckEqualValues) + { + ::Thunder::Core::Time time1(2015, 12, 10, 11, 30, 23, 55, true); + ::Thunder::Core::Time time2(2015, 12, 10, 11, 30, 23, 55, true); + EXPECT_EQ(time1 != time2, false); + time1 = ::Thunder::Core::Time(1971, 8, 11, 11, 4, 24, 21, true); + time2 = ::Thunder::Core::Time(1971, 8, 11, 11, 4, 24, 21, true); + EXPECT_EQ(time1 != time2, false); + } + TEST(Core_Time, OperatorOverloadingLessThan) + { + // Difference in milliseconds + ::Thunder::Core::Time time1(2002, 5, 10, 11, 30, 23, 21, true); + ::Thunder::Core::Time time2(2002, 5, 10, 11, 30, 23, 22, true); + EXPECT_EQ(time1 < time2, true); + + // Difference in Seconds + time1 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 24, 21, true); + EXPECT_EQ(time1 < time2, true); + + // Difference in minutes + time1 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2002, 5, 10, 11, 35, 23, 22, true); + EXPECT_EQ(time1 < time2, true); + + // Difference in hours + time1 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2002, 5, 10, 13, 30, 23, 21, true); + EXPECT_EQ(time1 < time2, true); + + // Difference in days + time1 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2002, 5, 12, 11, 30, 23, 21, true); + EXPECT_EQ(time1 < time2, true); + + // Difference in months + time1 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2002, 6, 10, 11, 30, 23, 21, true); + EXPECT_EQ(time1 < time2, true); + + // Difference in years + time1 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2004, 5, 10, 11, 30, 23, 21, true); + EXPECT_EQ(time1 < time2, true); + } + TEST(Core_Time, OperatorOverlessGreaterThan_CheckNotLessThanValues) + { + // Check with equals + ::Thunder::Core::Time time1(2020, 2, 1, 14, 30, 35, 41, true); + ::Thunder::Core::Time time2(2020, 2, 1, 14, 30, 35, 41, true); + EXPECT_EQ(time1 > time2, false); + + // Check with greater values + time1 = ::Thunder::Core::Time(2008, 5, 10, 11, 30, 25, 21, true); + time2 = ::Thunder::Core::Time(2006, 5, 10, 11, 30, 26, 21, true); + EXPECT_EQ(time1 < time2, false); + time1 = ::Thunder::Core::Time(2002, 5, 10, 13, 40, 23, 21, true); + time2 = ::Thunder::Core::Time(2002, 5, 10, 12, 35, 23, 22, true); + EXPECT_EQ(time1 < time2, false); + time1 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 23, 26, true); + time2 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 23, 24, true); + EXPECT_EQ(time1 < time2, false); + } + TEST(Core_Time, OperatorOverloadingLessThanEqual) + { + // Difference in milliseconds + ::Thunder::Core::Time time1(2002, 5, 10, 11, 30, 23, 21, true); + ::Thunder::Core::Time time2(2002, 5, 10, 11, 30, 23, 22, true); + EXPECT_EQ(time1 <= time2, true); + + // Difference in Seconds + time1 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 24, 21, true); + EXPECT_EQ(time1 <= time2, true); + + // Difference in minutes + time1 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2002, 5, 10, 11, 35, 23, 22, true); + EXPECT_EQ(time1 <= time2, true); + + // Difference in hours + time1 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2002, 5, 10, 13, 30, 23, 21, true); + EXPECT_EQ(time1 <= time2, true); + + // Difference in days + time1 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2002, 5, 12, 11, 30, 23, 21, true); + EXPECT_EQ(time1 <= time2, true); + + // Difference in months + time1 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2002, 6, 10, 11, 30, 23, 21, true); + EXPECT_EQ(time1 <= time2, true); + + // Difference in years + time1 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2004, 5, 10, 11, 30, 23, 21, true); + EXPECT_EQ(time1 <= time2, true); + + // Using equal time + time1 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 23, 21, true); + EXPECT_EQ(time1 <= time2, true); + } + TEST(Core_Time, OperatorOverloadingLessThanEqual_CheckNotLessThanEqualValues) + { + // Check with greater values + ::Thunder::Core::Time time1(2004, 5, 10, 11, 30, 23, 21, true); + ::Thunder::Core::Time time2(2002, 5, 10, 11, 30, 24, 21, true); + EXPECT_EQ(time1 <= time2, false); + time1 = ::Thunder::Core::Time(2002, 5, 10, 14, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2002, 5, 10, 11, 35, 23, 22, true); + EXPECT_EQ(time1 <= time2, false); + time1 = ::Thunder::Core::Time(2004, 5, 10, 11, 30, 23, 22, true); + time2 = ::Thunder::Core::Time(2004, 5, 10, 11, 30, 23, 21, true); + EXPECT_EQ(time1 <= time2, false); + } + TEST(Core_Time, OperatorOverloadingGreaterThan) + { + // Difference in milliseconds + ::Thunder::Core::Time time1(2002, 5, 10, 11, 30, 23, 23, true); + ::Thunder::Core::Time time2(2002, 5, 10, 11, 30, 23, 21, true); + EXPECT_EQ(time1 > time2, true); + + // Difference in Seconds + time1 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 25, 21, true); + time2 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 24, 21, true); + EXPECT_EQ(time1 > time2, true); + + // Difference in minutes + time1 = ::Thunder::Core::Time(2002, 5, 10, 11, 40, 23, 22, true); + time2 = ::Thunder::Core::Time(2002, 5, 10, 11, 35, 23, 22, true); + EXPECT_EQ(time1 > time2, true); + + // Difference in hours + time1 = ::Thunder::Core::Time(2002, 5, 10, 14, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2002, 5, 10, 13, 30, 23, 21, true); + EXPECT_EQ(time1 > time2, true); + + // Difference in days + time1 = ::Thunder::Core::Time(2002, 5, 24, 11, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2002, 5, 12, 11, 30, 23, 21, true); + EXPECT_EQ(time1 > time2, true); + + // Difference in months + time1 = ::Thunder::Core::Time(2002, 7, 10, 11, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2002, 6, 10, 11, 30, 23, 21, true); + EXPECT_EQ(time1 > time2, true); + + // Difference in years + time1 = ::Thunder::Core::Time(2010, 5, 10, 11, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2004, 5, 10, 11, 30, 23, 21, true); + EXPECT_EQ(time1 > time2, true); + } + TEST(Core_Time, OperatorOverloadingGreaterThan_CheckNotGreaterThanValues) + { + // Check with equals + ::Thunder::Core::Time time1(2002, 5, 10, 11, 30, 23, 21, true); + ::Thunder::Core::Time time2(2002, 5, 10, 11, 30, 23, 21, true); + EXPECT_EQ(time1 > time2, false); + + // Check with lesser values + time1 = ::Thunder::Core::Time(2004, 5, 10, 11, 30, 25, 21, true); + time2 = ::Thunder::Core::Time(2006, 5, 10, 11, 30, 26, 21, true); + EXPECT_EQ(time1 > time2, false); + time1 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2002, 5, 10, 12, 35, 23, 22, true); + EXPECT_EQ(time1 > time2, false); + time1 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 23, 22, true); + time2 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 23, 24, true); + EXPECT_EQ(time1 > time2, false); + } + TEST(Core_Time, OperatorOverloadingGreaterThanEqual) + { + // Difference in milliseconds + ::Thunder::Core::Time time1(2002, 5, 10, 11, 30, 23, 23, true); + ::Thunder::Core::Time time2(2002, 5, 10, 11, 30, 23, 21, true); + EXPECT_EQ(time1 >= time2, true); + + // Difference in Seconds + time1 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 25, 21, true); + time2 = ::Thunder::Core::Time(2002, 5, 10, 11, 30, 24, 21, true); + EXPECT_EQ(time1 >= time2, true); + + // Difference in minutes + time1 = ::Thunder::Core::Time(2002, 5, 10, 11, 40, 23, 22, true); + time2 = ::Thunder::Core::Time(2002, 5, 10, 11, 35, 23, 22, true); + EXPECT_EQ(time1 >= time2, true); + + // Difference in hours + time1 = ::Thunder::Core::Time(2002, 5, 10, 14, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2002, 5, 10, 13, 30, 23, 21, true); + EXPECT_EQ(time1 >= time2, true); + + // Difference in days + time1 = ::Thunder::Core::Time(2002, 5, 24, 11, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2002, 5, 12, 11, 30, 23, 21, true); + EXPECT_EQ(time1 >= time2, true); + + // Difference in months + time1 = ::Thunder::Core::Time(2002, 7, 10, 11, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2002, 6, 10, 11, 30, 23, 21, true); + EXPECT_EQ(time1 >= time2, true); + + // Difference in years + time1 = ::Thunder::Core::Time(2010, 5, 10, 11, 30, 23, 21, true); + time2 = ::Thunder::Core::Time(2004, 5, 10, 11, 30, 23, 21, true); + EXPECT_EQ(time1 >= time2, true); + + // Using equal time + time1 = ::Thunder::Core::Time(2012, 10, 1, 3, 45, 34, 10, true); + time2 = ::Thunder::Core::Time(2012, 10, 1, 3, 45, 34, 10, true); + EXPECT_EQ(time1 >= time2, true); + } + TEST(Core_Time, OperatorOverloadingGreaterThan_CheckNotGreaterThanEqualValues) + { + // Check with lesser values + ::Thunder::Core::Time time1(2004, 5, 10, 11, 30, 25, 21, true); + ::Thunder::Core::Time time2(2006, 5, 10, 11, 30, 26, 21, true); + EXPECT_EQ(time1 >= time2, false); + time1 = ::Thunder::Core::Time(2000, 5, 9, 11, 30, 2, 21, true); + time2 = ::Thunder::Core::Time(2002, 5, 10, 12, 35, 23, 22, true); + EXPECT_EQ(time1 >= time2, false); + time1 = ::Thunder::Core::Time(1980, 5, 10, 11, 30, 23, 22, true); + time2 = ::Thunder::Core::Time(1980, 5, 10, 11, 30, 23, 24, true); + EXPECT_EQ(time1 >= time2, false); + } + TEST(Core_Time, OperatorOverloadingAssignment) + { + ::Thunder::Core::Time time1(2002, 5, 10, 11, 30, 23, 22, true); + ::Thunder::Core::Time time2 = time1; + EXPECT_EQ(time1 == time2, true); + time2 = ::Thunder::Core::Time(1971, 5, 10, 11, 4, 24, 21, true); + time1 = time2; + EXPECT_EQ(time1 == time2, true); + } + TEST(Core_Time, OperatorOverloadingAddition) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + ::Thunder::Core::Time time1(2002, 5, 10, 11, 30, 23, 22, true); + ::Thunder::Core::Time time2; + ::Thunder::Core::Time time3 = time1 + time2; + EXPECT_EQ(time1 == time3, true); + + ::Thunder::Core::Time time4(2000, 5, 10, 11, 30, 23, 22, true); + ::Thunder::Core::Time time5 = time3 + time4; + string timeString; + time5.ToString(timeString); + + // Time will be saved/set based on 1st of January 1970, 00:00:00 time base. + // So the saved time values will be always the one subtracted with time base. + // Hence the '+=' works only on the subtracted values and here the value + // will be based on that differences + EXPECT_STREQ(timeString.c_str(), "Thu, 16 Sep 2032 23:00:46"); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, OperatorOverloadingSubtraction) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + ::Thunder::Core::Time time1(2002, 8, 8, 11, 30, 23, 22, true); + ::Thunder::Core::Time time2(2000, 3, 1, 8, 25, 22, 1, true); + + ::Thunder::Core::Time time3 = time1 - time2; + string timeString; + time3.ToString(timeString); + + // Time will be saved/set based on 1st of January 1970, 00:00:00 time base. + // So the saved time values will be always the one subtracted with time base. + // Hence the '-=' works only on the subtracted values and here the value + // will be based on that differences + EXPECT_STREQ(timeString.c_str(), "Fri, 09 Jun 1972 03:05:01"); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, OperatorOverloadingAdditionWithAssignment) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + ::Thunder::Core::Time time1(2002, 5, 10, 11, 30, 23, 22, true); + ::Thunder::Core::Time time2; + time2 += time1; + EXPECT_EQ(time1 == time2, true); + + ::Thunder::Core::Time time3(2000, 5, 10, 11, 30, 23, 22, true); + time3 += time2; + string timeString; + time3.ToString(timeString); + + // Time will be saved/set based on 1st of January 1970, 00:00:00 time base. + // So the saved time values will be always the one subtracted with time base. + // Hence the '+=' works only on the subtracted values and here the value + // will be based on that differences + EXPECT_STREQ(timeString.c_str(), "Thu, 16 Sep 2032 23:00:46"); + + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } + TEST(Core_Time, OperatorOverloadingSubtractionWithAssignment) + { + char* currentZone = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + + ::Thunder::Core::Time time1(2002, 8, 8, 11, 30, 23, 22, true); + ::Thunder::Core::Time time2(2000, 3, 1, 8, 25, 22, 1, true);; + time1 -= time2; + + string timeString; + time1.ToString(timeString); + // Time will be saved/set based on 1st of January 1970, 00:00:00 time base. + // So the saved time values will be always the one subtracted with time base. + // Hence the '-=' works only on the subtracted values and here the value + // will be based on that differences + EXPECT_STREQ(timeString.c_str(), "Fri, 09 Jun 1972 03:05:01"); + (currentZone == nullptr) ? unsetenv("TZ") : setenv("TZ", currentZone, 1); + tzset(); + } #if 0 -TEST(Core_Time, TimeHandle) -{ - Time time(2021,1, 1, 12, 00, 00, 333, true); + TEST(Core_Time, TimeHandle) + { + ::Thunder::Core::Time time(2021,1, 1, 12, 00, 00, 333, true); - string timeString; - time.ToString(timeString, true); - std::cout << "Reference local 2021-1-1 12:00:00 333 : " << timeString << " ms: " << time.MilliSeconds() << std::endl; - EXPECT_STREQ(timeString.c_str(), ""); - EXPECT_EQ(time.MilliSeconds(), 333u); - std::cout << " DayOfYear:" << static_cast(time.TMHandle().tm_yday) << " DayOfWeek:" << static_cast(time.TMHandle().tm_wday) << std::endl; + string timeString; + time.ToString(timeString, true); + std::cout << "Reference local 2021-1-1 12:00:00 333 : " << timeString << " ms: " << time.MilliSeconds() << std::endl; + EXPECT_STREQ(timeString.c_str(), ""); + EXPECT_EQ(time.MilliSeconds(), 333u); + std::cout << " DayOfYear:" << static_cast(time.TMHandle().tm_yday) << " DayOfWeek:" << static_cast(time.TMHandle().tm_wday) << std::endl; - EXPECT_EQ(static_cast(time.TMHandle().tm_yday), 0u); - EXPECT_EQ(static_cast(time.TMHandle().tm_wday), 0u); + EXPECT_EQ(static_cast(time.TMHandle().tm_yday), 0u); + EXPECT_EQ(static_cast(time.TMHandle().tm_wday), 0u); - std::cout << "Year:" << static_cast(time.TMHandle().tm_year) << " Month:" << static_cast(time.TMHandle().tm_mon) << " Day:" << static_cast(.timeTMHandle().tm_mday) << " Hours:"; + std::cout << "Year:" << static_cast(time.TMHandle().tm_year) << " Month:" << static_cast(time.TMHandle().tm_mon) << " Day:" << static_cast(.timeTMHandle().tm_mday) << " Hours:"; - EXPECT_EQ(static_cast(time.TMHandle().tm_year), 0u); - EXPECT_EQ(static_cast(time.TMHandle().tm_mon), 0u); - EXPECT_EQ(static_cast(time.TMHandle().tm_mday), 0u); + EXPECT_EQ(static_cast(time.TMHandle().tm_year), 0u); + EXPECT_EQ(static_cast(time.TMHandle().tm_mon), 0u); + EXPECT_EQ(static_cast(time.TMHandle().tm_mday), 0u); - std::cout << static_cast(time.TMHandle().tm_hour) << " Minutes:" << static_cast(.time.TMHandle().tm_min) << " Seconds:" << static_cast(time.TMHandle().tm_sec) << std::endl; + std::cout << static_cast(time.TMHandle().tm_hour) << " Minutes:" << static_cast(.time.TMHandle().tm_min) << " Seconds:" << static_cast(time.TMHandle().tm_sec) << std::endl; - EXPECT_EQ(static_cast(time.TMHandle().tm_hour), 0u); - EXPECT_EQ(static_cast(time.TMHandle().tm_min), 0u); - EXPECT_EQ(static_cast(time.TMHandle().tm_sec), 0u); -} + EXPECT_EQ(static_cast(time.TMHandle().tm_hour), 0u); + EXPECT_EQ(static_cast(time.TMHandle().tm_min), 0u); + EXPECT_EQ(static_cast(time.TMHandle().tm_sec), 0u); + } #endif + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_timer.cpp b/Tests/unit/core/test_timer.cpp index 0e91402e2f..e40e45aa92 100644 --- a/Tests/unit/core/test_timer.cpp +++ b/Tests/unit/core/test_timer.cpp @@ -30,6 +30,7 @@ namespace Thunder { namespace Tests { +namespace Core { class TimeHandler { public: @@ -54,7 +55,7 @@ namespace Tests { _cv.notify_one(); - Core::Time nextTick = Core::Time::Now() + time; + ::Thunder::Core::Time nextTick = ::Thunder::Core::Time::Now() + time; return nextTick.Ticks(); } @@ -80,14 +81,14 @@ namespace Tests { std::mutex TimeHandler::_mutex; std::condition_variable TimeHandler::_cv; - class WatchDogHandler : Core::WatchDogType { + class WatchDogHandler : ::Thunder::Core::WatchDogType { private: - typedef Core::WatchDogType BaseClass; + typedef ::Thunder::Core::WatchDogType BaseClass; public: WatchDogHandler& operator=(const WatchDogHandler&) = delete; WatchDogHandler() - : BaseClass(Core::Thread::DefaultStackSize(), _T("WatchDogTimer"), *this) + : BaseClass(::Thunder::Core::Thread::DefaultStackSize(), _T("WatchDogTimer"), *this) , _event(false, true) { } @@ -103,7 +104,7 @@ namespace Tests { uint32_t Expired() { _event.SetEvent(); - return Core::infinite; + return ::Thunder::Core::infinite; } int Wait(unsigned int milliseconds) const @@ -113,16 +114,16 @@ namespace Tests { private: uint32_t _delay; - mutable Core::Event _event; + mutable ::Thunder::Core::Event _event; }; TEST(Core_Timer, LoopedTimer) { constexpr uint32_t time = 100; - Core::TimerType timer(Core::Thread::DefaultStackSize(), _T("LoopedTimer")); + ::Thunder::Core::TimerType timer(::Thunder::Core::Thread::DefaultStackSize(), _T("LoopedTimer")); - Core::Time nextTick = Core::Time::Now() + time; + ::Thunder::Core::Time nextTick = ::Thunder::Core::Time::Now() + time; timer.Schedule(nextTick.Ticks(), TimeHandler()); @@ -136,9 +137,9 @@ namespace Tests { { constexpr uint32_t time = 100; - Core::TimerType timer(Core::Thread::DefaultStackSize(), _T("QueuedTimer")); + ::Thunder::Core::TimerType timer(::Thunder::Core::Thread::DefaultStackSize(), _T("QueuedTimer")); - Core::Time nextTick = Core::Time::Now(); + ::Thunder::Core::Time nextTick = ::Thunder::Core::Time::Now(); nextTick.Add(time); timer.Schedule(nextTick.Ticks(), TimeHandler()); @@ -159,9 +160,9 @@ namespace Tests { { constexpr uint32_t time = 100; - Core::TimerType timer(Core::Thread::DefaultStackSize(), _T("PastTime")); + ::Thunder::Core::TimerType timer(::Thunder::Core::Thread::DefaultStackSize(), _T("PastTime")); - Core::Time pastTime = Core::Time::Now(); + ::Thunder::Core::Time pastTime = ::Thunder::Core::Time::Now(); ASSERT_GT(pastTime.Ticks() / 1000, 0); @@ -180,7 +181,9 @@ namespace Tests { WatchDogHandler timer; timer.Start(100); // 100 milliseconds delay int ret = timer.Wait(200); // Wait for 200 milliseconds - EXPECT_EQ(ret, Core::ERROR_NONE); + EXPECT_EQ(ret, ::Thunder::Core::ERROR_NONE); } + +} // Core } // Tests } // Thunder diff --git a/Tests/unit/core/test_tracing.cpp b/Tests/unit/core/test_tracing.cpp index b85ff04c75..9fe06aea02 100644 --- a/Tests/unit/core/test_tracing.cpp +++ b/Tests/unit/core/test_tracing.cpp @@ -26,329 +26,334 @@ #include #include "../IPTestAdministrator.h" - -using namespace Thunder; -using namespace Thunder::Core; + +namespace Thunder { +namespace Tests { +namespace Core { #pragma pack(push) #pragma pack(1) -struct TraceHeader -{ - uint16_t _Length; - uint64_t _ClockTicks; - uint32_t _LineNumber; -}; + struct TraceHeader + { + uint16_t _Length; + uint64_t _ClockTicks; + uint32_t _LineNumber; + }; #pragma pack(pop) -struct TraceData -{ - TraceHeader _Header; - string _File; - string _Module; - string _Category; - string _Class; - string _Text; - - string ToString() + struct TraceData { - std::stringstream output; - output << _File << "(" << _Header._LineNumber << "): " << _Text; - return output.str(); - } -}; + TraceHeader _Header; + string _File; + string _Module; + string _Category; + string _Class; + string _Text; + + string ToString() + { + std::stringstream output; + output << _File << "(" << _Header._LineNumber << "): " << _Text; + return output.str(); + } + }; -class ServerCyclicBuffer01 : public CyclicBuffer -{ -public: - ServerCyclicBuffer01(const string& fileName, uint32_t size) - : CyclicBuffer(fileName, File::USER_WRITE|File::USER_READ|File::SHAREABLE, size, true) + class ServerCyclicBuffer01 : public CyclicBuffer { - } + public: + ServerCyclicBuffer01(const string& fileName, uint32_t size) + : CyclicBuffer(fileName, File::USER_WRITE|File::USER_READ|File::SHAREABLE, size, true) + { + } - virtual uint32_t GetReadSize(Cursor& cursor) override + virtual uint32_t GetReadSize(Cursor& cursor) override + { + uint16_t entrySize = 0; + cursor.Peek(entrySize); + return entrySize; + } + }; + + bool ReadTraceString(const uint8_t buffer[], uint32_t length, uint32_t& offset, string& output) { - uint16_t entrySize = 0; - cursor.Peek(entrySize); - return entrySize; - } -}; + output = ""; -bool ReadTraceString(const uint8_t buffer[], uint32_t length, uint32_t& offset, string& output) -{ - output = ""; + const char * charBuffer = reinterpret_cast(buffer); - const char * charBuffer = reinterpret_cast(buffer); + while (true) { + char c = charBuffer[offset]; - while (true) { - char c = charBuffer[offset]; + if (c == '\0') { + // Found the end + offset++; + return true; + } - if (c == '\0') { - // Found the end + output += string(1, c); offset++; - return true; - } - output += string(1, c); - offset++; - - if (offset >= length) { - // Buffer overrun - return false; + if (offset >= length) { + // Buffer overrun + return false; + } } - } - - return true; -} - -bool ParseTraceData(const uint8_t buffer[], uint32_t length, uint32_t& offset, TraceData& traceData, uint32_t bufferSize) -{ - uint32_t startOffset = offset; - const TraceHeader * header = reinterpret_cast(buffer + offset); - offset += sizeof(TraceHeader); - - if (offset > length) { - std::cerr << "Offset " << offset << " is larger than length " << length << std::endl; - return false; + return true; } - traceData._Header = *header; - uint16_t entrySize = traceData._Header._Length; - EXPECT_TRUE(entrySize <= bufferSize); - - if (!ReadTraceString(buffer, length, offset, traceData._File)) { - std::cerr << "Failed to read file name" << std::endl; - return false; - } + bool ParseTraceData(const uint8_t buffer[], uint32_t length, uint32_t& offset, TraceData& traceData, uint32_t bufferSize) + { + uint32_t startOffset = offset; - if (!ReadTraceString(buffer, length, offset, traceData._Module)) { - std::cerr << "Failed to read module name" << std::endl; - return false; - } + const TraceHeader * header = reinterpret_cast(buffer + offset); + offset += sizeof(TraceHeader); - if (!ReadTraceString(buffer, length, offset, traceData._Category)) { - std::cerr << "Failed to read category" << std::endl; - return false; - } - if (!ReadTraceString(buffer, length, offset, traceData._Class)) { - std::cerr << "Failed to read class name" << std::endl; - return false; - } + if (offset > length) { + std::cerr << "Offset " << offset << " is larger than length " << length << std::endl; + return false; + } - uint16_t totalHeaderLength = offset - startOffset; - uint16_t textLength = entrySize - totalHeaderLength; - uint16_t textBufferLength = textLength + 1; - char textBuffer[textBufferLength]; + traceData._Header = *header; + uint16_t entrySize = traceData._Header._Length; + EXPECT_TRUE(entrySize <= bufferSize); - memcpy(textBuffer, buffer + offset, textLength); - textBuffer[textLength] = '\0'; - traceData._Text = string(textBuffer); + if (!ReadTraceString(buffer, length, offset, traceData._File)) { + std::cerr << "Failed to read file name" << std::endl; + return false; + } - offset += textLength; + if (!ReadTraceString(buffer, length, offset, traceData._Module)) { + std::cerr << "Failed to read module name" << std::endl; + return false; + } - EXPECT_TRUE(offset == (startOffset + entrySize)); + if (!ReadTraceString(buffer, length, offset, traceData._Category)) { + std::cerr << "Failed to read category" << std::endl; + return false; + } + if (!ReadTraceString(buffer, length, offset, traceData._Class)) { + std::cerr << "Failed to read class name" << std::endl; + return false; + } - return true; -} + uint16_t totalHeaderLength = offset - startOffset; + uint16_t textLength = entrySize - totalHeaderLength; + uint16_t textBufferLength = textLength + 1; + char textBuffer[textBufferLength]; -void DebugCheckIfConsistent(const uint8_t * buffer, int length, CyclicBuffer& cycBuffer, uint32_t bufferSize) -{ - uint entryCount = 0; + memcpy(textBuffer, buffer + offset, textLength); + textBuffer[textLength] = '\0'; + traceData._Text = string(textBuffer); - int index = 0; - while (index < length) { - uint16_t entrySize = 0; - entrySize += static_cast(buffer[index]); - index++; - entrySize += static_cast(buffer[index]) << 8; + offset += textLength; - EXPECT_TRUE(entrySize < bufferSize); - index += entrySize - 1; + EXPECT_TRUE(offset == (startOffset + entrySize)); - entryCount++; + return true; } - EXPECT_TRUE(index == length); -} - -void CreateTraceBuffer(string tracePath) -{ - char systemCmd[1024]; - string command = "mkdir -p "; - snprintf(systemCmd, command.size()+tracePath.size()+1, "%s%s", command.c_str(),tracePath.c_str()); - system(systemCmd); -} - -TEST(Core_tracing, simpleTracing) -{ - // Call dispose to ensure there is no any resource handler registered to - // avoid hang on the poll - Core::Singleton::Dispose(); - - std::string tracePath = "/tmp/tracebuffer01"; - auto lambdaFunc = [tracePath](IPTestAdministrator & testAdmin) { - std::string db = (tracePath + "/tracebuffer.doorbell"); - string cycBufferName = (tracePath + "/tracebuffer"); - - testAdmin.Sync("client start"); - DoorBell doorBell(db.c_str()); - constexpr uint32_t bufferSize = ((8 * 1024) - (sizeof(struct CyclicBuffer::control))); /* 8Kb */ - ServerCyclicBuffer01 cycBuffer(cycBufferName, bufferSize); - - // Note: this test case is forking a child process with parent process space. - // In such case, signalfd:poll of parent will not get signal from pthread_kill(SIGUSR2) from child - // process. Hence please ensure parent process cleared all resource registration - // using Singleton::Dispose() call from parent context. - // https://lore.kernel.org/linux-man/20190923222413.5c79b179@kappa.digital-domain.net/T/ - - // TODO: maximum running time? - if (doorBell.Wait(infinite) == ERROR_NONE) { - doorBell.Acknowledge(); - uint32_t bufferLength = bufferSize; - uint8_t buffer[bufferLength]; - uint32_t actuallyRead = cycBuffer.Read(buffer, sizeof(buffer)); - testAdmin.Sync("server done"); - - EXPECT_TRUE(actuallyRead < cycBuffer.Size()); - - DebugCheckIfConsistent(buffer, actuallyRead, cycBuffer, bufferSize); + void DebugCheckIfConsistent(const uint8_t * buffer, int length, CyclicBuffer& cycBuffer, uint32_t bufferSize) + { + uint entryCount = 0; - uint32_t offset = 0; - int traceCount = 0; - while (offset < actuallyRead) { - TraceData traceData; - EXPECT_TRUE(ParseTraceData(buffer, actuallyRead, offset, traceData, bufferSize)); - string time(Time::Now().ToRFC1123(true)); + int index = 0; + while (index < length) { + uint16_t entrySize = 0; + entrySize += static_cast(buffer[index]); + index++; + entrySize += static_cast(buffer[index]) << 8; - EXPECT_STREQ(traceData._File.c_str(), "test_tracing.cpp"); - EXPECT_STREQ(traceData._Class.c_str(), "TestBody"); - EXPECT_STREQ(traceData._Category.c_str(), "Information"); - EXPECT_STREQ(traceData._Text.c_str(), "Trace Log"); + EXPECT_TRUE(entrySize < bufferSize); + index += entrySize - 1; - traceCount++; - } + entryCount++; } - doorBell.Relinquish(); - }; - static std::function lambdaVar = lambdaFunc; + EXPECT_TRUE(index == length); + } - IPTestAdministrator::OtherSideMain otherSide = [](IPTestAdministrator& testAdmin ) { lambdaVar(testAdmin); }; + void CreateTraceBuffer(string tracePath) + { + char systemCmd[1024]; + string command = "mkdir -p "; + snprintf(systemCmd, command.size()+tracePath.size()+1, "%s%s", command.c_str(),tracePath.c_str()); + system(systemCmd); + } - // This side (tested) acts as client. - IPTestAdministrator testAdmin(otherSide); + TEST(Core_tracing, simpleTracing) { - CreateTraceBuffer(tracePath); - Trace::TraceUnit::Instance().Open(tracePath); - testAdmin.Sync("client start"); - sleep(2); - Trace::TraceType::Enable(true); - - TRACE_GLOBAL(Trace::Information, (_T("Trace Log"))); - testAdmin.Sync("server done"); - - Trace::TraceUnit::Instance().SetCategories(true,"Tracing", reinterpret_cast("Information")); - Trace::TraceUnit::Iterator index = Trace::TraceUnit::Instance().GetCategories(); - - while (index.Next() == true) - if ((*index)->Enabled() == true) { - if ((strcmp((*index)->Module(), "Tracing")) == 0 ) { - EXPECT_STREQ((*index)->Category(), "Information"); + // Call dispose to ensure there is no any resource handler registered to + // avoid hang on the poll + ::Thunder::Core::Singleton::Dispose(); + + std::string tracePath = "/tmp/tracebuffer01"; + auto lambdaFunc = [tracePath](IPTestAdministrator & testAdmin) { + std::string db = (tracePath + "/tracebuffer.doorbell"); + string cycBufferName = (tracePath + "/tracebuffer"); + + testAdmin.Sync("client start"); + DoorBell doorBell(db.c_str()); + constexpr uint32_t bufferSize = ((8 * 1024) - (sizeof(struct CyclicBuffer::control))); /* 8Kb */ + ServerCyclicBuffer01 cycBuffer(cycBufferName, bufferSize); + + // Note: this test case is forking a child process with parent process space. + // In such case, signalfd:poll of parent will not get signal from pthread_kill(SIGUSR2) from child + // process. Hence please ensure parent process cleared all resource registration + // using Singleton::Dispose() call from parent context. + // https://lore.kernel.org/linux-man/20190923222413.5c79b179@kappa.digital-domain.net/T/ + + // TODO: maximum running time? + if (doorBell.Wait(infinite) == ERROR_NONE) { + doorBell.Acknowledge(); + uint32_t bufferLength = bufferSize; + uint8_t buffer[bufferLength]; + uint32_t actuallyRead = cycBuffer.Read(buffer, sizeof(buffer)); + testAdmin.Sync("server done"); + + EXPECT_TRUE(actuallyRead < cycBuffer.Size()); + + DebugCheckIfConsistent(buffer, actuallyRead, cycBuffer, bufferSize); + + uint32_t offset = 0; + int traceCount = 0; + while (offset < actuallyRead) { + TraceData traceData; + EXPECT_TRUE(ParseTraceData(buffer, actuallyRead, offset, traceData, bufferSize)); + string time(Time::Now().ToRFC1123(true)); + + EXPECT_STREQ(traceData._File.c_str(), "test_tracing.cpp"); + EXPECT_STREQ(traceData._Class.c_str(), "TestBody"); + EXPECT_STREQ(traceData._Category.c_str(), "Information"); + EXPECT_STREQ(traceData._Text.c_str(), "Trace Log"); + + traceCount++; } } + doorBell.Relinquish(); + }; - bool enabled = false; - Trace::TraceUnit::Instance().IsDefaultCategory("Tracing", reinterpret_cast("Information"), enabled); - TRACE(Trace::Information,(Trace::Format(_T("Checking the Format() with 1 parameter")))); - std::string text = "Hello"; - TRACE(Trace::Information,(Trace::Format(text.c_str(), _T("Checking the Format() with 2 parameter")))); - Trace::TraceUnit::Instance().Close(); - Trace::TraceUnit::Instance().Open(1); - } + static std::function lambdaVar = lambdaFunc; + + IPTestAdministrator::OtherSideMain otherSide = [](IPTestAdministrator& testAdmin ) { lambdaVar(testAdmin); }; - testAdmin. WaitForChildCompletion(); - Singleton::Dispose(); -} - -TEST(Core_tracing, simpleTracingReversed) -{ - std::string tracePath = "/tmp/tracebuffer02"; - auto lambdaFunc = [&](IPTestAdministrator & testAdmin) { - CreateTraceBuffer(tracePath); - Trace::TraceUnit::Instance().Open(tracePath); - testAdmin.Sync("client start"); - sleep(2); - Trace::TraceType::Enable(true); - - TRACE_GLOBAL(Trace::Information, (_T("Trace Log"))); - testAdmin.Sync("server done"); - - Trace::TraceUnit::Instance().SetCategories(true,"Tracing", reinterpret_cast("Information")); - Trace::TraceUnit::Iterator index = Trace::TraceUnit::Instance().GetCategories(); - - while (index.Next() == true) - if ((*index)->Enabled() == true) { - if ((strcmp((*index)->Module(), "Tracing")) == 0 ) { - EXPECT_STREQ((*index)->Category(), "Information"); + // This side (tested) acts as client. + IPTestAdministrator testAdmin(otherSide); + { + CreateTraceBuffer(tracePath); + Trace::TraceUnit::Instance().Open(tracePath); + testAdmin.Sync("client start"); + sleep(2); + Trace::TraceType::Enable(true); + + TRACE_GLOBAL(Trace::Information, (_T("Trace Log"))); + testAdmin.Sync("server done"); + + Trace::TraceUnit::Instance().SetCategories(true,"Tracing", reinterpret_cast("Information")); + Trace::TraceUnit::Iterator index = Trace::TraceUnit::Instance().GetCategories(); + + while (index.Next() == true) + if ((*index)->Enabled() == true) { + if ((strcmp((*index)->Module(), "Tracing")) == 0 ) { + EXPECT_STREQ((*index)->Category(), "Information"); + } } - } - bool enabled = false; - Trace::TraceUnit::Instance().IsDefaultCategory("Tracing", reinterpret_cast("Information"), enabled); - TRACE(Trace::Information,(Trace::Format(_T("Checking the Format() with 1 parameter")))); - std::string text = "Hello"; - TRACE(Trace::Information,(Trace::Format(text.c_str(), _T("Checking the Format() with 2 parameter")))); - Trace::TraceUnit::Instance().Close(); - Trace::TraceUnit::Instance().Open(1); + bool enabled = false; + Trace::TraceUnit::Instance().IsDefaultCategory("Tracing", reinterpret_cast("Information"), enabled); + TRACE(Trace::Information,(Trace::Format(_T("Checking the Format() with 1 parameter")))); + std::string text = "Hello"; + TRACE(Trace::Information,(Trace::Format(text.c_str(), _T("Checking the Format() with 2 parameter")))); + Trace::TraceUnit::Instance().Close(); + Trace::TraceUnit::Instance().Open(1); + } + testAdmin. WaitForChildCompletion(); Singleton::Dispose(); - }; + } - static std::function lambdaVar = lambdaFunc; + TEST(Core_tracing, simpleTracingReversed) + { + std::string tracePath = "/tmp/tracebuffer02"; + auto lambdaFunc = [&](IPTestAdministrator & testAdmin) { + CreateTraceBuffer(tracePath); + Trace::TraceUnit::Instance().Open(tracePath); + testAdmin.Sync("client start"); + sleep(2); + Trace::TraceType::Enable(true); + + TRACE_GLOBAL(Trace::Information, (_T("Trace Log"))); + testAdmin.Sync("server done"); - IPTestAdministrator::OtherSideMain otherSide = [](IPTestAdministrator& testAdmin ) { lambdaVar(testAdmin); }; + Trace::TraceUnit::Instance().SetCategories(true,"Tracing", reinterpret_cast("Information")); + Trace::TraceUnit::Iterator index = Trace::TraceUnit::Instance().GetCategories(); - // This side (tested) acts as client. - IPTestAdministrator testAdmin(otherSide); - { - std::string db = (tracePath + "/tracebuffer.doorbell"); - string cycBufferName = (tracePath + "/tracebuffer"); - - testAdmin.Sync("server start"); - DoorBell doorBell(db.c_str()); - constexpr uint32_t bufferSize = ((8 * 1024) - (sizeof(struct CyclicBuffer::control))); /* 8Kb */ - ServerCyclicBuffer01 cycBuffer(cycBufferName, bufferSize); - - // TODO: maximum running time? - if (doorBell.Wait(infinite) == ERROR_NONE) { - doorBell.Acknowledge(); - uint32_t bufferLength = bufferSize; - uint8_t buffer[bufferLength]; - uint32_t actuallyRead = cycBuffer.Read(buffer, sizeof(buffer)); - testAdmin.Sync("client done"); - - EXPECT_TRUE(actuallyRead < cycBuffer.Size()); - - DebugCheckIfConsistent(buffer, actuallyRead, cycBuffer, bufferSize); - - uint32_t offset = 0; - int traceCount = 0; - while (offset < actuallyRead) { - TraceData traceData; - EXPECT_TRUE(ParseTraceData(buffer, actuallyRead, offset, traceData, bufferSize)); - string time(Time::Now().ToRFC1123(true)); - - EXPECT_STREQ(traceData._File.c_str(), "test_tracing.cpp"); - EXPECT_STREQ(traceData._Class.c_str(), "operator()"); - EXPECT_STREQ(traceData._Category.c_str(), "Information"); - EXPECT_STREQ(traceData._Text.c_str(), "Trace Log"); - - traceCount++; + while (index.Next() == true) + if ((*index)->Enabled() == true) { + if ((strcmp((*index)->Module(), "Tracing")) == 0 ) { + EXPECT_STREQ((*index)->Category(), "Information"); + } + } + + bool enabled = false; + Trace::TraceUnit::Instance().IsDefaultCategory("Tracing", reinterpret_cast("Information"), enabled); + TRACE(Trace::Information,(Trace::Format(_T("Checking the Format() with 1 parameter")))); + std::string text = "Hello"; + TRACE(Trace::Information,(Trace::Format(text.c_str(), _T("Checking the Format() with 2 parameter")))); + Trace::TraceUnit::Instance().Close(); + Trace::TraceUnit::Instance().Open(1); + + Singleton::Dispose(); + }; + + static std::function lambdaVar = lambdaFunc; + + IPTestAdministrator::OtherSideMain otherSide = [](IPTestAdministrator& testAdmin ) { lambdaVar(testAdmin); }; + + // This side (tested) acts as client. + IPTestAdministrator testAdmin(otherSide); + { + std::string db = (tracePath + "/tracebuffer.doorbell"); + string cycBufferName = (tracePath + "/tracebuffer"); + + testAdmin.Sync("server start"); + DoorBell doorBell(db.c_str()); + constexpr uint32_t bufferSize = ((8 * 1024) - (sizeof(struct CyclicBuffer::control))); /* 8Kb */ + ServerCyclicBuffer01 cycBuffer(cycBufferName, bufferSize); + + // TODO: maximum running time? + if (doorBell.Wait(infinite) == ERROR_NONE) { + doorBell.Acknowledge(); + uint32_t bufferLength = bufferSize; + uint8_t buffer[bufferLength]; + uint32_t actuallyRead = cycBuffer.Read(buffer, sizeof(buffer)); + testAdmin.Sync("client done"); + + EXPECT_TRUE(actuallyRead < cycBuffer.Size()); + + DebugCheckIfConsistent(buffer, actuallyRead, cycBuffer, bufferSize); + + uint32_t offset = 0; + int traceCount = 0; + while (offset < actuallyRead) { + TraceData traceData; + EXPECT_TRUE(ParseTraceData(buffer, actuallyRead, offset, traceData, bufferSize)); + string time(Time::Now().ToRFC1123(true)); + + EXPECT_STREQ(traceData._File.c_str(), "test_tracing.cpp"); + EXPECT_STREQ(traceData._Class.c_str(), "operator()"); + EXPECT_STREQ(traceData._Category.c_str(), "Information"); + EXPECT_STREQ(traceData._Text.c_str(), "Trace Log"); + + traceCount++; + } } + doorBell.Relinquish(); } - doorBell.Relinquish(); + + testAdmin.WaitForChildCompletion(); + Singleton::Dispose(); } - testAdmin.WaitForChildCompletion(); - Singleton::Dispose(); -} +} // Core +} // Tests +} // Thunder \ No newline at end of file diff --git a/Tests/unit/core/test_tristate.cpp b/Tests/unit/core/test_tristate.cpp index 7067c55915..6ac6d2476f 100644 --- a/Tests/unit/core/test_tristate.cpp +++ b/Tests/unit/core/test_tristate.cpp @@ -25,23 +25,28 @@ #include -using namespace Thunder; -using namespace Thunder::Core; +namespace Thunder { +namespace Tests { +namespace Core { -TEST(test_TriState, simple_TriState) -{ - TriState(); - TriState tristate1("F"); - TriState tristate2("T"); - TriState tristate3("True"); - TriState tristate4("False"); - TriState tristate5(tristate1); - TriState tristate6 =tristate1; - TriState tristate7(TriState::EnumState::True); + TEST(test_TriState, simple_TriState) + { + ::Thunder::Core::TriState(); + ::Thunder::Core::TriState tristate1("F"); + ::Thunder::Core::TriState tristate2("T"); + ::Thunder::Core::TriState tristate3("True"); + ::Thunder::Core::TriState tristate4("False"); + ::Thunder::Core::TriState tristate5(tristate1); + ::Thunder::Core::TriState tristate6 =tristate1; + ::Thunder::Core::TriState tristate7(::Thunder::Core::TriState::EnumState::True); - EXPECT_EQ(tristate3.Get(),TriState::EnumState::True); - tristate3.Set(false); - EXPECT_EQ(tristate3.Get(),TriState::EnumState::False); - tristate3.Set(TriState::EnumState::Unknown); - EXPECT_EQ(tristate3.Get(),TriState::EnumState::Unknown); -} + EXPECT_EQ(tristate3.Get(),::Thunder::Core::TriState::EnumState::True); + tristate3.Set(false); + EXPECT_EQ(tristate3.Get(),::Thunder::Core::TriState::EnumState::False); + tristate3.Set(::Thunder::Core::TriState::EnumState::Unknown); + EXPECT_EQ(tristate3.Get(),::Thunder::Core::TriState::EnumState::Unknown); + } + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_valuerecorder.cpp b/Tests/unit/core/test_valuerecorder.cpp index f7e8446fb3..86f0dad72a 100644 --- a/Tests/unit/core/test_valuerecorder.cpp +++ b/Tests/unit/core/test_valuerecorder.cpp @@ -25,114 +25,121 @@ #include "core/core.h" -using namespace Thunder; -using namespace Thunder::Core; - -const unsigned int BLOCKSIZE = 20; - -class WriterClass : public RecorderType::Writer -{ - public: - WriterClass() = delete; - - WriterClass(string filename) - : Writer(filename) - , _file(filename) - { - } - - ~WriterClass() - { - } - - public: - void WriterJob() - { - uint8_t arr[] = {1,2,3}; - SetBuffer(arr); - auto object = Create(_file); - Record(10); - uint64_t TimeValue = Time(); - std::string storageName = Source(); - uint32_t value = Value(); - object.Release(); - } - - private: - string _file; -}; - -class ReaderClass : public RecorderType::Reader -{ - public: - ReaderClass() = delete; - - ReaderClass(string filename) - : Reader(filename) - , _file(filename) - { - } - - ReaderClass(const ProxyType& recorder, const uint32_t id = static_cast(~0)) - : Reader(recorder->Source()) - , _file(recorder->Source()) - { - } - - ~ReaderClass() - { - } - - public: - void ReaderJob() - { - Next(); - EXPECT_TRUE(IsValid()); - - uint32_t time = 20; - Core::Time curTime = Core::Time::Now(); - curTime.Add(time); - uint32_t index = Store(curTime.Ticks(), 1); - - StepForward(); - StepBack(); - ClearData(); - - Reader obj1(_file, 1u); - EXPECT_FALSE(obj1.Previous()); - EXPECT_TRUE(obj1.Next()); - - EXPECT_EQ(StartId(),1u); - - if (EndId() == StartId()) - EXPECT_EQ(EndId(),1u); - else - EXPECT_EQ(EndId(),2u); - - uint32_t id = EndId(); - std::string storageName = Source(); - } - - private: - string _file; -}; - -TEST(test_valuerecorder, test_writer) -{ - string filename = "baseRecorder.txt"; - - auto obj1 = RecorderType::Writer::Create(filename); - - obj1->Copy(*(obj1),1); - obj1->Copy(*(obj1),100); - - static_cast(*obj1).WriterJob(); - - ReaderClass obj2(filename); - obj2.ReaderJob(); - - ReaderClass obj4(ProxyType(obj3)); - - obj1.Release(); -} - +namespace Thunder { +namespace Tests { +namespace Core { + + + + + const unsigned int BLOCKSIZE = 20; + + class WriterClass : public RecorderType::Writer + { + public: + WriterClass() = delete; + + WriterClass(string filename) + : Writer(filename) + , _file(filename) + { + } + + ~WriterClass() + { + } + + public: + void WriterJob() + { + uint8_t arr[] = {1,2,3}; + SetBuffer(arr); + auto object = Create(_file); + Record(10); + uint64_t TimeValue = Time(); + std::string storageName = Source(); + uint32_t value = Value(); + object.Release(); + } + + private: + string _file; + }; + + class ReaderClass : public RecorderType::Reader + { + public: + ReaderClass() = delete; + + ReaderClass(string filename) + : Reader(filename) + , _file(filename) + { + } + + ReaderClass(const ProxyType& recorder, const uint32_t id = static_cast(~0)) + : Reader(recorder->Source()) + , _file(recorder->Source()) + { + } + + ~ReaderClass() + { + } + + public: + void ReaderJob() + { + Next(); + EXPECT_TRUE(IsValid()); + + uint32_t time = 20; + ::Thunder::Core::Time curTime = ::Thunder::Core::Time::Now(); + curTime.Add(time); + uint32_t index = Store(curTime.Ticks(), 1); + + StepForward(); + StepBack(); + ClearData(); + + Reader obj1(_file, 1u); + EXPECT_FALSE(obj1.Previous()); + EXPECT_TRUE(obj1.Next()); + + EXPECT_EQ(StartId(),1u); + + if (EndId() == StartId()) + EXPECT_EQ(EndId(),1u); + else + EXPECT_EQ(EndId(),2u); + + uint32_t id = EndId(); + std::string storageName = Source(); + } + + private: + string _file; + }; + + TEST(test_valuerecorder, test_writer) + { + string filename = "baseRecorder.txt"; + + auto obj1 = RecorderType::Writer::Create(filename); + + obj1->Copy(*(obj1),1); + obj1->Copy(*(obj1),100); + + static_cast(*obj1).WriterJob(); + + ReaderClass obj2(filename); + obj2.ReaderJob(); + + ReaderClass obj4(ProxyType(obj3)); + + obj1.Release(); + } + +} // Core +} // Tests +} // Thunder diff --git a/Tests/unit/core/test_weblinkjson.cpp b/Tests/unit/core/test_weblinkjson.cpp index a9821292ca..8a52afec34 100644 --- a/Tests/unit/core/test_weblinkjson.cpp +++ b/Tests/unit/core/test_weblinkjson.cpp @@ -30,22 +30,22 @@ namespace Thunder { namespace Tests { +namespace Core { -namespace { - enum class CommandType { + enum class CommandTypeWeblinkJSON { EXECUTESHELL, WIFISETTINGS, FANCONTROL, PLAYERCONTROL }; - class Parameters : public Core::JSON::Container { + class Parameters : public ::Thunder::Core::JSON::Container { public: Parameters(const Parameters&) = delete; Parameters& operator=(const Parameters&) = delete; Parameters() - : Core::JSON::Container() + : ::Thunder::Core::JSON::Container() , Speed(0) , Duration(0) , Command() @@ -62,19 +62,19 @@ namespace { } public: - Core::JSON::OctSInt16 Speed; - Core::JSON::DecUInt16 Duration; - Core::JSON::EnumType Command; - Core::JSON::ArrayType Settings; + ::Thunder::Core::JSON::OctSInt16 Speed; + ::Thunder::Core::JSON::DecUInt16 Duration; + ::Thunder::Core::JSON::EnumType Command; + ::Thunder::Core::JSON::ArrayType<::Thunder::Core::JSON::DecUInt16> Settings; }; - class Command : public Core::JSON::Container { + class Command : public ::Thunder::Core::JSON::Container { public: Command(const Command&) = delete; Command& operator=(const Command&) = delete; Command() - : Core::JSON::Container() + : ::Thunder::Core::JSON::Container() , Identifier(0) , Name() , BaseAddress(0) @@ -93,27 +93,25 @@ namespace { } public: - Core::JSON::DecUInt32 Identifier; - Core::JSON::String Name; - Core::JSON::HexUInt32 BaseAddress; - Core::JSON::Boolean TrickFlag; + ::Thunder::Core::JSON::DecUInt32 Identifier; + ::Thunder::Core::JSON::String Name; + ::Thunder::Core::JSON::HexUInt32 BaseAddress; + ::Thunder::Core::JSON::Boolean TrickFlag; Parameters Params; }; typedef Web::JSONBodyType CommandBody; - } - - class JSONWebServer : public Web::WebLinkType&> { + class JSONWebServer : public Web::WebLinkType<::Thunder::Core::SocketStream, Web::Request, Web::Response, ::Thunder::Core::ProxyPoolType&> { private: - typedef Web::WebLinkType&> BaseClass; + typedef Web::WebLinkType<::Thunder::Core::SocketStream, Web::Request, Web::Response, ::Thunder::Core::ProxyPoolType&> BaseClass; public: JSONWebServer() = delete; JSONWebServer(const JSONWebServer& copy) = delete; JSONWebServer& operator=(const JSONWebServer&) = delete; - JSONWebServer(const SOCKET& connector, const Core::NodeId& remoteId, Core::SocketServerType*) + JSONWebServer(const SOCKET& connector, const ::Thunder::Core::NodeId& remoteId, ::Thunder::Core::SocketServerType*) : BaseClass(5, _requestFactory, false, connector, remoteId, 2048, 2048) , _requestFactory(5) , _commandBodyFactory(5) @@ -122,18 +120,18 @@ namespace { virtual ~JSONWebServer() { - Close(Thunder::Core::infinite); + Close(::Thunder::Core::infinite); } public: // Notification of a Partial Request received, time to attach a body.. - virtual void LinkBody(Core::ProxyType& element) + virtual void LinkBody(::Thunder::Core::ProxyType<::Thunder::Web::Request>& element) { // Time to attach a Command Body element->Body(_commandBodyFactory.Element()); } - virtual void Received(Core::ProxyType& request) + virtual void Received(::Thunder::Core::ProxyType& request) { EXPECT_EQ(request->Verb, Web::Request::HTTP_GET); EXPECT_EQ(request->MajorVersion, 1); @@ -141,13 +139,13 @@ namespace { EXPECT_TRUE(request->HasBody()); EXPECT_EQ(request->ContentLength.Value(), 60u); - Core::ProxyType response(Core::ProxyType::Create()); + ::Thunder::Core::ProxyType response(::Thunder::Core::ProxyType::Create()); response->ErrorCode = 200; response->Body(request->Body()); Submit(response); } - virtual void Send(const Core::ProxyType& response) + virtual void Send(const ::Thunder::Core::ProxyType& response) { EXPECT_EQ(response->ErrorCode, 200); EXPECT_TRUE(response->HasBody()); @@ -158,20 +156,20 @@ namespace { } private: - Core::ProxyPoolType _requestFactory; - Core::ProxyPoolType _commandBodyFactory; + ::Thunder::Core::ProxyPoolType _requestFactory; + ::Thunder::Core::ProxyPoolType _commandBodyFactory; }; - class JSONWebClient : public Web::WebLinkType&> { + class JSONWebClient : public Web::WebLinkType<::Thunder::Core::SocketStream, Web::Response, Web::Request, ::Thunder::Core::ProxyPoolType&> { private: - typedef Web::WebLinkType&> BaseClass; + typedef Web::WebLinkType<::Thunder::Core::SocketStream, Web::Response, Web::Request, ::Thunder::Core::ProxyPoolType&> BaseClass; public: JSONWebClient() = delete; JSONWebClient(const JSONWebClient& copy) = delete; JSONWebClient& operator=(const JSONWebClient&) = delete; - JSONWebClient(const Thunder::Core::NodeId& remoteNode) + JSONWebClient(const ::Thunder::Core::NodeId& remoteNode) : BaseClass(5, _responseFactory, false, remoteNode.AnyInterface(), remoteNode, 2048, 208) , _dataPending(false, false) , _responseFactory(5) @@ -181,18 +179,18 @@ namespace { virtual ~JSONWebClient() { - Close(Thunder::Core::infinite); + Close(::Thunder::Core::infinite); } public: // Notification of a Partial Request received, time to attach a body.. - virtual void LinkBody(Core::ProxyType& element) + virtual void LinkBody(::Thunder::Core::ProxyType<::Thunder::Web::Response>& element) { // Time to attach a Command Body element->Body(_commandBodyFactory.Element()); } - virtual void Received(Core::ProxyType& response) + virtual void Received(::Thunder::Core::ProxyType& response) { EXPECT_EQ(response->ErrorCode, 200); EXPECT_STREQ(response->Message.c_str(), "OK"); @@ -205,7 +203,7 @@ namespace { _dataPending.Unlock(); } - virtual void Send(const Core::ProxyType& request) + virtual void Send(const ::Thunder::Core::ProxyType& request) { EXPECT_EQ(request->Verb, Web::Request::HTTP_GET); EXPECT_TRUE(request->HasBody()); @@ -227,18 +225,18 @@ namespace { } private: - mutable Thunder::Core::Event _dataPending; + mutable ::Thunder::Core::Event _dataPending; string _dataReceived; - Core::ProxyPoolType _responseFactory; - Core::ProxyPoolType _commandBodyFactory; + ::Thunder::Core::ProxyPoolType _responseFactory; + ::Thunder::Core::ProxyPoolType _commandBodyFactory; }; TEST(WebLink, Json) { std::string connector {"0.0.0.0"}; auto lambdaFunc = [connector](IPTestAdministrator & testAdmin) { - Core::SocketServerType webServer(Core::NodeId(connector.c_str(), 12341)); - webServer.Open(Core::infinite); + ::Thunder::Core::SocketServerType webServer(::Thunder::Core::NodeId(connector.c_str(), 12341)); + webServer.Open(::Thunder::Core::infinite); testAdmin.Sync("setup server"); testAdmin.Sync("client done"); }; @@ -250,11 +248,11 @@ namespace { IPTestAdministrator testAdmin(otherSide); testAdmin.Sync("setup server"); { - JSONWebClient jsonWebConnector(Core::NodeId(connector.c_str(), 12341)); - Core::ProxyType jsonRequest(Core::ProxyType::Create()); - Core::ProxyType jsonRequestBody(Core::ProxyType::Create()); + JSONWebClient jsonWebConnector(::Thunder::Core::NodeId(connector.c_str(), 12341)); + ::Thunder::Core::ProxyType jsonRequest(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType jsonRequestBody(::Thunder::Core::ProxyType::Create()); jsonRequest->Body(jsonRequestBody); - jsonWebConnector.Open(Core::infinite); + jsonWebConnector.Open(::Thunder::Core::infinite); while (!jsonWebConnector.IsOpen()); jsonRequest->Verb = Web::Request::HTTP_GET; jsonRequestBody->Identifier = 123; @@ -270,15 +268,17 @@ namespace { EXPECT_STREQ(received.c_str(), sent.c_str()); testAdmin.Sync("client done"); } - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } + +} // Core } // Tests -ENUM_CONVERSION_BEGIN(Tests::CommandType) - { Tests::CommandType::EXECUTESHELL, _TXT("ExecuteShell") }, - { Tests::CommandType::WIFISETTINGS, _TXT("WiFiSettings") }, - { Tests::CommandType::FANCONTROL, _TXT("FanControl") }, - { Tests::CommandType::PLAYERCONTROL, _TXT("PlayerControl") }, -ENUM_CONVERSION_END(Tests::CommandType) +ENUM_CONVERSION_BEGIN(Tests::Core::CommandTypeWeblinkJSON) + { Tests::Core::CommandTypeWeblinkJSON::EXECUTESHELL, _TXT("ExecuteShell") }, + { Tests::Core::CommandTypeWeblinkJSON::WIFISETTINGS, _TXT("WiFiSettings") }, + { Tests::Core::CommandTypeWeblinkJSON::FANCONTROL, _TXT("FanControl") }, + { Tests::Core::CommandTypeWeblinkJSON::PLAYERCONTROL, _TXT("PlayerControl") }, +ENUM_CONVERSION_END(Tests::Core::CommandTypeWeblinkJSON) } // Thunder diff --git a/Tests/unit/core/test_weblinktext.cpp b/Tests/unit/core/test_weblinktext.cpp index fcf37dcca8..0d8f2d3f3d 100644 --- a/Tests/unit/core/test_weblinktext.cpp +++ b/Tests/unit/core/test_weblinktext.cpp @@ -30,35 +30,36 @@ namespace Thunder { namespace Tests { +namespace Core { - class WebServer : public Web::WebLinkType > { + class WebServer : public Web::WebLinkType<::Thunder::Core::SocketStream, Web::Request, Web::Response, ::Thunder::Core::ProxyPoolType > { private: - typedef Web::WebLinkType > BaseClass; + typedef Web::WebLinkType<::Thunder::Core::SocketStream, Web::Request, Web::Response, ::Thunder::Core::ProxyPoolType > BaseClass; public: WebServer() = delete; WebServer(const WebServer& copy) = delete; WebServer& operator=(const WebServer&) = delete; - WebServer(const SOCKET& connector, const Core::NodeId& remoteId, Core::SocketServerType*) + WebServer(const SOCKET& connector, const ::Thunder::Core::NodeId& remoteId, ::Thunder::Core::SocketServerType*) : BaseClass(5, false, connector, remoteId, 2048, 2048) { } virtual ~WebServer() { - Close(Thunder::Core::infinite); + Close(::Thunder::Core::infinite); } public: // Notification of a Partial Request received, time to attach a body.. - virtual void LinkBody(Core::ProxyType& element) + virtual void LinkBody(::Thunder::Core::ProxyType<::Thunder::Web::Request>& element) { // Time to attach a String Body element->Body(_textBodyFactory.Element()); } - virtual void Received(Core::ProxyType& request) + virtual void Received(::Thunder::Core::ProxyType<::Thunder::Web::Request>& request) { EXPECT_EQ(request->Verb, Web::Request::HTTP_GET); EXPECT_EQ(request->MajorVersion, 1); @@ -66,13 +67,13 @@ namespace Tests { EXPECT_TRUE(request->HasBody()); EXPECT_EQ(request->ContentLength.Value(), 19u); - Core::ProxyType response(Core::ProxyType::Create()); + ::Thunder::Core::ProxyType response(::Thunder::Core::ProxyType::Create()); response->ErrorCode = 200; response->Body(request->Body()); Submit(response); } - virtual void Send(const Core::ProxyType& response) + virtual void Send(const ::Thunder::Core::ProxyType<::Thunder::Web::Response>& response) { EXPECT_EQ(response->ErrorCode, 200); EXPECT_TRUE(response->HasBody()); @@ -83,21 +84,21 @@ namespace Tests { } private: - static Core::ProxyPoolType _textBodyFactory; + static ::Thunder::Core::ProxyPoolType _textBodyFactory; }; - Core::ProxyPoolType WebServer::_textBodyFactory(5); + ::Thunder::Core::ProxyPoolType WebServer::_textBodyFactory(5); - class WebClient : public Web::WebLinkType&> { + class WebClient : public Web::WebLinkType<::Thunder::Core::SocketStream, Web::Response, Web::Request, ::Thunder::Core::ProxyPoolType&> { private: - typedef Web::WebLinkType&> BaseClass; + typedef Web::WebLinkType<::Thunder::Core::SocketStream, Web::Response, Web::Request, ::Thunder::Core::ProxyPoolType&> BaseClass; public: WebClient() = delete; WebClient(const WebClient& copy) = delete; WebClient& operator=(const WebClient&) = delete; - WebClient(const Thunder::Core::NodeId& remoteNode) + WebClient(const ::Thunder::Core::NodeId& remoteNode) : BaseClass(5,_responseFactory, false, remoteNode.AnyInterface(), remoteNode, 2048, 208) , _dataPending(false, false) { @@ -105,18 +106,18 @@ namespace Tests { virtual ~WebClient() { - Close(Thunder::Core::infinite); + Close(::Thunder::Core::infinite); } public: // Notification of a Partial Request received, time to attach a body.. - virtual void LinkBody(Core::ProxyType& element) + virtual void LinkBody(::Thunder::Core::ProxyType<::Thunder::Web::Response>& element) { // Time to attach a String Body element->Body(_textBodyFactory.Element()); } - virtual void Received(Core::ProxyType& response) + virtual void Received(::Thunder::Core::ProxyType<::Thunder::Web::Response>& response) { EXPECT_EQ(response->ErrorCode, 200); EXPECT_STREQ(response->Message.c_str(), "OK"); @@ -129,7 +130,7 @@ namespace Tests { _dataPending.Unlock(); } - virtual void Send(const Core::ProxyType& request) + virtual void Send(const ::Thunder::Core::ProxyType<::Thunder::Web::Request>& request) { EXPECT_EQ(request->Verb, Web::Request::HTTP_GET); EXPECT_TRUE(request->HasBody()); @@ -151,21 +152,21 @@ namespace Tests { } private: - mutable Thunder::Core::Event _dataPending; + mutable ::Thunder::Core::Event _dataPending; string _dataReceived; - static Core::ProxyPoolType _responseFactory; - static Core::ProxyPoolType _textBodyFactory; + static ::Thunder::Core::ProxyPoolType _responseFactory; + static ::Thunder::Core::ProxyPoolType _textBodyFactory; }; - Core::ProxyPoolType WebClient::_responseFactory(5); - Core::ProxyPoolType WebClient::_textBodyFactory(5); + ::Thunder::Core::ProxyPoolType WebClient::_responseFactory(5); + ::Thunder::Core::ProxyPoolType WebClient::_textBodyFactory(5); TEST(WebLink, Text) { std::string connector {"127.0.0.1"}; auto lambdaFunc = [connector](IPTestAdministrator & testAdmin) { - Core::SocketServerType _webServer(Core::NodeId(connector.c_str(), 12343)); - _webServer.Open(Core::infinite); + ::Thunder::Core::SocketServerType _webServer(::Thunder::Core::NodeId(connector.c_str(), 12343)); + _webServer.Open(::Thunder::Core::infinite); testAdmin.Sync("setup server"); testAdmin.Sync("client done"); }; @@ -177,11 +178,11 @@ namespace Tests { IPTestAdministrator testAdmin(otherSide); testAdmin.Sync("setup server"); { - WebClient webConnector(Core::NodeId(connector.c_str(), 12343)); - Core::ProxyType webRequest(Core::ProxyType::Create()); - Core::ProxyType webRequestBody(Core::ProxyType::Create()); + WebClient webConnector(::Thunder::Core::NodeId(connector.c_str(), 12343)); + ::Thunder::Core::ProxyType webRequest(::Thunder::Core::ProxyType::Create()); + ::Thunder::Core::ProxyType webRequestBody(::Thunder::Core::ProxyType::Create()); webRequest->Body(webRequestBody); - webConnector.Open(Core::infinite); + webConnector.Open(::Thunder::Core::infinite); while (!webConnector.IsOpen()); webRequest->Verb = Web::Request::HTTP_GET; string sent = "Just a body to send"; @@ -194,8 +195,9 @@ namespace Tests { EXPECT_STREQ(received.c_str(), sent.c_str()); testAdmin.Sync("client done"); } - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } +} // Core } // Tests } // Thunder diff --git a/Tests/unit/core/test_websocketjson.cpp b/Tests/unit/core/test_websocketjson.cpp index 54809313ed..744df0ac55 100644 --- a/Tests/unit/core/test_websocketjson.cpp +++ b/Tests/unit/core/test_websocketjson.cpp @@ -33,14 +33,15 @@ namespace Thunder { namespace Tests { +namespace Core { - class Message : public Core::JSON::Container { + class Message : public ::Thunder::Core::JSON::Container { public: Message(const Message&) = delete; Message& operator= (const Message&) = delete; Message() - : Core::JSON::Container() + : ::Thunder::Core::JSON::Container() , EventType() , Event() { @@ -53,17 +54,17 @@ namespace Tests { } public: - Core::JSON::String EventType; - Core::JSON::String Event; + ::Thunder::Core::JSON::String EventType; + ::Thunder::Core::JSON::String Event; }; - class Factory : public Core::ProxyPoolType { + class Factory : public ::Thunder::Core::ProxyPoolType { public: Factory() = delete; Factory(const Factory&) = delete; Factory& operator= (const Factory&) = delete; - Factory(const uint32_t number) : Core::ProxyPoolType(number) + Factory(const uint32_t number) : ::Thunder::Core::ProxyPoolType(number) { } @@ -72,23 +73,23 @@ namespace Tests { } public: - Core::ProxyType Element(const string&) + ::Thunder::Core::ProxyType<::Thunder::Core::JSON::IElement> Element(const string&) { - return (Core::ProxyType(Core::ProxyPoolType::Element())); + return (::Thunder::Core::ProxyType<::Thunder::Core::JSON::IElement>(::Thunder::Core::ProxyPoolType::Element())); } }; template - class JsonSocketServer : public Core::StreamJSONType< Web::WebSocketServerType, Factory&, INTERFACE> { + class JsonSocketServer : public ::Thunder::Core::StreamJSONType< Web::WebSocketServerType<::Thunder::Core::SocketStream>, Factory&, INTERFACE> { private: - typedef Core::StreamJSONType< Web::WebSocketServerType, Factory&, INTERFACE> BaseClass; + typedef ::Thunder::Core::StreamJSONType< Web::WebSocketServerType<::Thunder::Core::SocketStream>, Factory&, INTERFACE> BaseClass; public: JsonSocketServer() = delete; JsonSocketServer(const JsonSocketServer&) = delete; JsonSocketServer& operator=(const JsonSocketServer&) = delete; - JsonSocketServer(const SOCKET& socket, const Core::NodeId& remoteNode, Core::SocketServerType>*) + JsonSocketServer(const SOCKET& socket, const ::Thunder::Core::NodeId& remoteNode, ::Thunder::Core::SocketServerType>*) : BaseClass(2, _objectFactory, false, false, false, socket, remoteNode, 512, 512) , _objectFactory(1) { @@ -118,12 +119,12 @@ namespace Tests { return (this->IsOpen()); } - virtual void Received(Core::ProxyType& jsonObject) + virtual void Received(::Thunder::Core::ProxyType<::Thunder::Core::JSON::IElement>& jsonObject) { this->Submit(jsonObject); } - virtual void Send(Core::ProxyType& jsonObject) + virtual void Send(::Thunder::Core::ProxyType<::Thunder::Core::JSON::IElement>& jsonObject) { } @@ -149,16 +150,16 @@ namespace Tests { bool JsonSocketServer::_done = false; template - class JsonSocketClient : public Core::StreamJSONType, Factory&, INTERFACE> { + class JsonSocketClient : public ::Thunder::Core::StreamJSONType, Factory&, INTERFACE> { private: - typedef Core::StreamJSONType, Factory&, INTERFACE> BaseClass; + typedef ::Thunder::Core::StreamJSONType, Factory&, INTERFACE> BaseClass; public: JsonSocketClient() = delete; JsonSocketClient(const JsonSocketClient&) = delete; JsonSocketClient& operator=(const JsonSocketClient&) = delete; - JsonSocketClient(const Core::NodeId& remoteNode) + JsonSocketClient(const ::Thunder::Core::NodeId& remoteNode) : BaseClass(5, _objectFactory, _T(""), _T(""), _T(""), _T(""), false, true, false, remoteNode.AnyInterface(), remoteNode, 256, 256) , _objectFactory(2) , _dataPending(false, false) @@ -170,7 +171,7 @@ namespace Tests { } public: - virtual void Received(Core::ProxyType& jsonObject) + virtual void Received(::Thunder::Core::ProxyType<::Thunder::Core::JSON::IElement>& jsonObject) { string textElement; jsonObject->ToString(textElement); @@ -178,7 +179,7 @@ namespace Tests { _dataPending.Unlock(); } - virtual void Send(Core::ProxyType& jsonObject) + virtual void Send(::Thunder::Core::ProxyType<::Thunder::Core::JSON::IElement>& jsonObject) { } @@ -191,7 +192,7 @@ namespace Tests { return (true); } - Core::ProxyType Element() + ::Thunder::Core::ProxyType<::Thunder::Core::JSON::IElement> Element() { return _objectFactory.Element(""); } @@ -210,20 +211,20 @@ namespace Tests { private: Factory _objectFactory; string _dataReceived; - mutable Core::Event _dataPending; + mutable ::Thunder::Core::Event _dataPending; }; TEST(WebSocket, DISABLED_Json) { std::string connector {"/tmp/wpewebsocketjson0"}; auto lambdaFunc = [connector](IPTestAdministrator & testAdmin) { - Core::SocketServerType> jsonWebSocketServer(Core::NodeId(connector.c_str())); - jsonWebSocketServer.Open(Core::infinite); + ::Thunder::Core::SocketServerType> jsonWebSocketServer(::Thunder::Core::NodeId(connector.c_str())); + jsonWebSocketServer.Open(::Thunder::Core::infinite); testAdmin.Sync("setup server"); - std::unique_lock lk(JsonSocketServer::_mutex); - while (!JsonSocketServer::GetState()) { - JsonSocketServer::_cv.wait(lk); + std::unique_lock lk(JsonSocketServer<::Thunder::Core::JSON::IElement>::_mutex); + while (!JsonSocketServer<::Thunder::Core::JSON::IElement>::GetState()) { + JsonSocketServer<::Thunder::Core::JSON::IElement>::_cv.wait(lk); } testAdmin.Sync("server open"); testAdmin.Sync("client done"); @@ -236,25 +237,26 @@ namespace Tests { IPTestAdministrator testAdmin(otherSide); testAdmin.Sync("setup server"); { - Core::ProxyType sendObject = Core::ProxyType::Create(); + ::Thunder::Core::ProxyType sendObject = ::Thunder::Core::ProxyType::Create(); sendObject->EventType = _T("Test"); sendObject->Event = _T("TestSend"); std::string sendString; sendObject->ToString(sendString); - JsonSocketClient jsonWebSocketClient(Core::NodeId(connector.c_str())); - jsonWebSocketClient.Open(Core::infinite); + JsonSocketClient<::Thunder::Core::JSON::IElement> jsonWebSocketClient(::Thunder::Core::NodeId(connector.c_str())); + jsonWebSocketClient.Open(::Thunder::Core::infinite); testAdmin.Sync("server open"); - jsonWebSocketClient.Submit(Core::ProxyType(sendObject)); + jsonWebSocketClient.Submit(::Thunder::Core::ProxyType<::Thunder::Core::JSON::IElement>(sendObject)); jsonWebSocketClient.Wait(); string received; jsonWebSocketClient.Retrieve(received); EXPECT_STREQ(sendString.c_str(), received.c_str()); - jsonWebSocketClient.Close(Core::infinite); + jsonWebSocketClient.Close(::Thunder::Core::infinite); testAdmin.Sync("client done"); } - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } +} // Core } // Tests } // Thunder diff --git a/Tests/unit/core/test_websockettext.cpp b/Tests/unit/core/test_websockettext.cpp index c118e7e535..27deafab9a 100644 --- a/Tests/unit/core/test_websockettext.cpp +++ b/Tests/unit/core/test_websockettext.cpp @@ -33,17 +33,18 @@ namespace Thunder { namespace Tests { +namespace Core { - class TextSocketServer : public Core::StreamTextType, Core::TerminatorCarriageReturn> { + class TextSocketServer : public ::Thunder::Core::StreamTextType, ::Thunder::Core::TerminatorCarriageReturn> { private: - typedef Core::StreamTextType, Core::TerminatorCarriageReturn> BaseClass; + typedef ::Thunder::Core::StreamTextType, ::Thunder::Core::TerminatorCarriageReturn> BaseClass; public: TextSocketServer() = delete; TextSocketServer(const TextSocketServer&) = delete; TextSocketServer& operator=(const TextSocketServer&) = delete; - TextSocketServer(const SOCKET& socket, const Thunder::Core::NodeId& remoteNode, Thunder::Core::SocketServerType*) + TextSocketServer(const SOCKET& socket, const ::Thunder::Core::NodeId& remoteNode, ::Thunder::Core::SocketServerType*) : BaseClass(false, true, false, socket, remoteNode, 1024, 1024) { } @@ -88,16 +89,16 @@ namespace Tests { std::mutex TextSocketServer::_mutex; std::condition_variable TextSocketServer::_cv; - class TextSocketClient : public Core::StreamTextType, Core::TerminatorCarriageReturn> { + class TextSocketClient : public ::Thunder::Core::StreamTextType, ::Thunder::Core::TerminatorCarriageReturn> { private: - typedef Core::StreamTextType, Core::TerminatorCarriageReturn> BaseClass; + typedef ::Thunder::Core::StreamTextType, ::Thunder::Core::TerminatorCarriageReturn> BaseClass; public: TextSocketClient() = delete; TextSocketClient(const TextSocketClient&) = delete; TextSocketClient& operator=(const TextSocketClient&) = delete; - TextSocketClient(const Core::NodeId& remoteNode) + TextSocketClient(const ::Thunder::Core::NodeId& remoteNode) : BaseClass(_T("/"), _T("echo"), "", "", false, true, false, remoteNode.AnyInterface(), remoteNode, 1024, 1024) , _dataPending(false, false) { @@ -135,15 +136,15 @@ namespace Tests { private: string _dataReceived; - mutable Thunder::Core::Event _dataPending; + mutable ::Thunder::Core::Event _dataPending; }; TEST(WebSocket, DISABLED_Text) { std::string connector {"/tmp/wpewebsockettext0"}; auto lambdaFunc = [connector](IPTestAdministrator & testAdmin) { - Core::SocketServerType textWebSocketServer(Core::NodeId(connector.c_str())); - textWebSocketServer.Open(Core::infinite); + ::Thunder::Core::SocketServerType textWebSocketServer(::Thunder::Core::NodeId(connector.c_str())); + textWebSocketServer.Open(::Thunder::Core::infinite); testAdmin.Sync("setup server"); std::unique_lock lk(TextSocketServer::_mutex); while (!TextSocketServer::GetState()) { @@ -161,8 +162,8 @@ namespace Tests { IPTestAdministrator testAdmin(otherSide); testAdmin.Sync("setup server"); { - TextSocketClient textWebSocketClient(Core::NodeId(connector.c_str())); - textWebSocketClient.Open(Core::infinite); + TextSocketClient textWebSocketClient(::Thunder::Core::NodeId(connector.c_str())); + textWebSocketClient.Open(::Thunder::Core::infinite); testAdmin.Sync("server open"); string sentString = "Test String"; textWebSocketClient.Submit(sentString); @@ -170,11 +171,12 @@ namespace Tests { string received; textWebSocketClient.Retrieve(received); EXPECT_STREQ(sentString.c_str(), received.c_str()); - textWebSocketClient.Close(Core::infinite); + textWebSocketClient.Close(::Thunder::Core::infinite); testAdmin.Sync("client done"); } - Core::Singleton::Dispose(); + ::Thunder::Core::Singleton::Dispose(); } +} // Core } // Tests } // Thunder diff --git a/Tests/unit/core/test_workerpool.cpp b/Tests/unit/core/test_workerpool.cpp index a9bbae4986..909e0798d5 100644 --- a/Tests/unit/core/test_workerpool.cpp +++ b/Tests/unit/core/test_workerpool.cpp @@ -27,1416 +27,1421 @@ #include -using namespace Thunder; using namespace Thunder::Core; +namespace Thunder { +namespace Tests { +namespace Core { -static constexpr uint32_t MaxJobWaitTime = 1000; // In milliseconds -static constexpr uint8_t MaxAdditionalWorker = 5; + static constexpr uint32_t MaxJobWaitTime = 1000; // In milliseconds + static constexpr uint8_t MaxAdditionalWorker = 5; -class EventControl { -public: - EventControl(const EventControl&) = delete; - EventControl& operator=(const EventControl&) = delete; - EventControl() - : _event(false, true) + class EventControl { + public: + EventControl(const EventControl&) = delete; + EventControl& operator=(const EventControl&) = delete; + EventControl() + : _event(false, true) + { + } + ~EventControl() = default; + + public: + void Notify() + { + _event.SetEvent(); + } + uint32_t WaitForEvent(uint32_t waitTime) + { + return _event.Lock(waitTime); + } + void Reset() + { + _event.ResetEvent(); + } + + private: + ::Thunder::Core::Event _event; + }; + + template + class TestJob : public ::Thunder::Core::IDispatch, public EventControl { + public: + enum Status { + INITIATED, + CANCELED, + COMPLETED, + }; + + TestJob() = delete; + TestJob(const TestJob& copy) = delete; + TestJob& operator=(const TestJob& RHS) = delete; + ~TestJob() override = default; + TestJob(IMPLEMENTATION& parent, const Status status, const uint32_t waitTime = 0, const bool checkParentState = false, const bool notifyInvokedTime = false, const bool validateId = false) + : _parent(parent) + , _status(status) + , _waitTime(waitTime) + , _checkParentState(checkParentState) + , _notifyInvokedTime(notifyInvokedTime) + , _validateId(validateId) + { + } + + public: + Status GetStatus() + { + return _status; + } + void Dispatch() override + { + ::Thunder::Core::Time invokedTime = ::Thunder::Core::Time::Now(); + _status = COMPLETED; + usleep(_waitTime); + Notify(); + if (_checkParentState) { + _parent.WaitForReady(this, _waitTime * 10); + } + if (_notifyInvokedTime) { + _parent.InvokedTime(this, invokedTime); + } + if (_validateId) { + _parent.ValidateId(); + } + } + + private: + IMPLEMENTATION& _parent; + Status _status; + uint32_t _waitTime; + bool _checkParentState; + bool _notifyInvokedTime; + bool _validateId; + }; + + struct JobData { + EventControl* Event; + ::Thunder::Core::Time CurrentTime; + uint16_t ScheduledTime; + }; + + template + class JobControl { + private: + typedef std::map<::Thunder::Core::IDispatch*, JobData> JobMap; + private: + template + class ExternalWorker : public ::Thunder::Core::Thread { + public: + ExternalWorker() = delete; + ExternalWorker& operator=(const ExternalWorker&) = delete; + ExternalWorker(const ExternalWorker& copy) + : _job(copy._job) + , _parent(copy._parent) + { + } + + ExternalWorker(PARENTIMPL &parent) + : _job(nullptr) + , _parent(parent) + { + } + ~ExternalWorker() + { + Stop(); + } + + public: + void Stop() + { + ::Thunder::Core::Thread::Stop(); + ::Thunder::Core::Thread::Wait(::Thunder::Core::Thread::STOPPED|::Thunder::Core::Thread::BLOCKED, ::Thunder::Core::infinite); + } + virtual uint32_t Worker() override + { + if (IsRunning()) { + _parent.SubmitJob(*_job); + } + ::Thunder::Core::Thread::Block(); + return (::Thunder::Core::infinite); + } + + void Submit(::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>& job) + { + _job = &job; + ::Thunder::Core::Thread::Run(); + } + private: + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>* _job; + IMPLEMENTATION& _parent; + }; + + public: + JobControl() = delete; + JobControl(const JobControl&) = delete; + JobControl& operator=(const JobControl&) = delete; + JobControl(IMPLEMENTATION &parent, uint8_t threadsCount) + : _index(0) + , _threadsCount(threadsCount) + , _parent(parent) + , _external() + { + for (uint8_t index = 0; index < MaxAdditionalWorker; ++index) { + _external.push_back(new ExternalWorker(parent)); + } + } + ~JobControl() + { + for (auto& job: _jobs) { + delete job.second.Event; + } + _jobs.clear(); + for (auto& external: _external) { + delete external; + } + _external.clear(); + + ::Thunder::Core::Singleton::Dispose(); + } + + public: + static void CheckScheduledTime(::Thunder::Core::Time current, ::Thunder::Core::Time invokedTime, uint16_t scheduledTime) + { + uint8_t currentSecond = current.Seconds(); + uint8_t scheduledSecond = scheduledTime; // From milliseconds to seconds, integer division! + uint8_t invokedSecond = invokedTime.Seconds(); + + uint32_t expectedAddedTime = 0; + if (currentSecond + scheduledSecond >= 60) { + expectedAddedTime = (currentSecond + scheduledSecond) - 60; + } else { + expectedAddedTime = (currentSecond + scheduledSecond); + } + + EXPECT_LE(invokedSecond, expectedAddedTime); + } + uint32_t WaitForReady(::Thunder::Core::IDispatch* job, const uint32_t waitTime = 0) + { + uint32_t result = ::Thunder::Core::ERROR_NONE; + JobMap::iterator index = _jobs.find(job); + if (index != _jobs.end()) { + result = index->second.Event->WaitForEvent(waitTime); + } + return result; + } + void NotifyReady(const ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>& job) + { + JobMap::iterator index = _jobs.find(job.operator->()); + if (index != _jobs.end()) { + index->second.Event->Notify(); + } + } + void SubmitUsingSelfWorker(::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>& job) + { + InsertJobData(job, 0); + _parent.Submit(job); + } + void SubmitUsingExternalWorker(::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>& job) + { + if (_index < MaxAdditionalWorker) { + InsertJobData(job, 0); + _external[_index++]->Submit(job); + } + } + void ScheduleJobs(::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>& job, const uint16_t scheduledTime) + { + InsertJobData(job, scheduledTime); + _parent.Schedule(::Thunder::Core::Time::Now().Add(scheduledTime), job); + } + void RescheduleJobs(::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>& job, const uint16_t scheduledTime) + { + InsertJobData(job, scheduledTime); + _parent.Reschedule(::Thunder::Core::Time::Now().Add(scheduledTime), job); + } + void ValidateId() + { + const uint8_t MaxSize = 15; + bool isPoolId = false; + char id[MaxSize]; + sprintf(id, "%x", static_cast(pthread_self())); + for (uint8_t index = 0; index < _threadsCount + 2; index++) { + char workerId[MaxSize]; + sprintf(workerId, "%x", static_cast(::Thunder::Core::IWorkerPool::Instance().Id(index))); + + if (strcpy(workerId, id)) { + isPoolId = true; + break; + } + } + EXPECT_EQ(isPoolId, true); + } + void InvokedTime(::Thunder::Core::IDispatch* job, const ::Thunder::Core::Time& invokedTime) + { + JobMap::iterator index = _jobs.find(job); + if (index != _jobs.end()) { + CheckScheduledTime(index->second.CurrentTime, invokedTime, index->second.ScheduledTime); + } + } + void RemoveJobData(::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>& job) + { + JobMap::iterator index = _jobs.find(job.operator->()); + if (index != _jobs.end()) { + delete index->second.Event; + _jobs.erase(index); + } + } + + private: + void InsertJobData(::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>& job, uint16_t scheduledTime) + { + JobData jobData; + jobData.Event = new EventControl(); + jobData.ScheduledTime = scheduledTime; + jobData.CurrentTime = ::Thunder::Core::Time::Now(); + JobMap::iterator index = _jobs.find(job.operator->()); + if (index == _jobs.end()) { + _jobs.emplace(std::piecewise_construct, std::forward_as_tuple(job.operator->()), std::forward_as_tuple(jobData)); + } else { + index->second.CurrentTime = ::Thunder::Core::Time::Now(); + index->second.ScheduledTime = scheduledTime; + } + } + + private: + uint8_t _index; + uint8_t _threadsCount; + JobMap _jobs; + IMPLEMENTATION& _parent; + std::vector*> _external; + }; + + class WorkerPoolTester : public ::Thunder::Core::WorkerPool, public JobControl, public ::Thunder::Core::Thread { + public: + WorkerPoolTester() = delete; + WorkerPoolTester(const WorkerPoolTester&) = delete; + WorkerPoolTester& operator=(const WorkerPoolTester&) = delete; + + WorkerPoolTester(const uint8_t threads, const uint32_t stackSize, const uint32_t queueSize) + : WorkerPool(threads, stackSize, queueSize, &_dispatcher) + , JobControl(*this, threads) + { + } + + ~WorkerPoolTester() + { + // Diable the queue so the minions can stop, even if they are processing and waiting for work.. + Stop(); + ::Thunder::Core::Singleton::Dispose(); + } + + public: + void Stop() + { + ::Thunder::Core::WorkerPool::Stop(); + ::Thunder::Core::Thread::Wait(::Thunder::Core::Thread::STOPPED|::Thunder::Core::Thread::BLOCKED, ::Thunder::Core::infinite); + } + + uint32_t WaitForJobEvent(const ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>& job, const uint32_t waitTime = 0) + { + return static_cast&>(*job).WaitForEvent(waitTime); + } + void SubmitJob(const ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>& job) + { + Submit(job); + } + virtual uint32_t Worker() override + { + if (IsRunning()) { + Join(); + } + ::Thunder::Core::Thread::Block(); + return (::Thunder::Core::infinite); + } + void RunExternal() + { + ::Thunder::Core::Thread::Run(); + } + void RunThreadPool() + { + static_cast(this)->Run(); + } + + private: + class Dispatcher : public ::Thunder::Core::ThreadPool::IDispatcher { + public: + Dispatcher(const Dispatcher&) = delete; + Dispatcher& operator=(const Dispatcher&) = delete; + + Dispatcher() = default; + ~Dispatcher() override = default; + + private: + void Initialize() override { } + void Deinitialize() override { } + void Dispatch(::Thunder::Core::IDispatch* job) override + { job->Dispatch(); } + }; + + Dispatcher _dispatcher; + }; + TEST(Core_WorkerPool, CheckWorkerStaticMethods) + { + uint8_t queueSize = 5; + uint8_t threadCount = 1; + WorkerPoolTester workerPool(threadCount, 0, queueSize); + + EXPECT_EQ(::Thunder::Core::WorkerPool::IsAvailable(), false); + + ::Thunder::Core::WorkerPool::Assign(&workerPool); + EXPECT_EQ(&::Thunder::Core::WorkerPool::Instance(), &workerPool); + EXPECT_EQ(::Thunder::Core::WorkerPool::IsAvailable(), true); + + ::Thunder::Core::WorkerPool::Assign(nullptr); + EXPECT_EQ(::Thunder::Core::WorkerPool::IsAvailable(), false); + } + TEST(Core_WorkerPool, Check_WithSingleJob) + { + uint8_t queueSize = 5; + uint8_t threadCount = 1; + WorkerPoolTester workerPool(threadCount, 0, queueSize); + ::Thunder::Core::WorkerPool::Assign(&workerPool); + + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> job = ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(workerPool, TestJob::INITIATED, 500)); + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); + workerPool.Submit(job); + workerPool.RunThreadPool(); + EXPECT_EQ(workerPool.WaitForJobEvent(job, MaxJobWaitTime), ::Thunder::Core::ERROR_NONE); + workerPool.Stop(); + + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); + ::Thunder::Core::WorkerPool::Assign(nullptr); + job.Release(); + } + TEST(Core_WorkerPool, Check_WithSingleJob_CancelJob_BeforeProcessing) + { + uint8_t queueSize = 5; + uint8_t threadCount = 1; + WorkerPoolTester workerPool(threadCount, 0, queueSize); + ::Thunder::Core::WorkerPool::Assign(&workerPool); + + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> job = ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(workerPool, TestJob::INITIATED)); + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); + workerPool.Submit(job); + workerPool.Revoke(job); + workerPool.RunThreadPool(); + EXPECT_EQ(workerPool.WaitForJobEvent(job, MaxJobWaitTime), ::Thunder::Core::ERROR_TIMEDOUT); + workerPool.Stop(); + + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); + ::Thunder::Core::WorkerPool::Assign(nullptr); + job.Release(); + } + TEST(Core_WorkerPool, Check_WithSingleJob_CancelJob_WhileProcessing) + { + uint8_t queueSize = 5; + uint8_t threadCount = 1; + WorkerPoolTester workerPool(threadCount, 0, queueSize); + ::Thunder::Core::WorkerPool::Assign(&workerPool); + + ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch> job = ::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(workerPool, TestJob::INITIATED, 1000)); + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); + workerPool.Submit(job); + workerPool.RunThreadPool(); + usleep(100); + workerPool.Revoke(job); + EXPECT_EQ(workerPool.WaitForJobEvent(job, MaxJobWaitTime), ::Thunder::Core::ERROR_NONE); + workerPool.Stop(); + + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); + ::Thunder::Core::WorkerPool::Assign(nullptr); + job.Release(); + } + void CheckWorkerPool_MultipleJobs(const uint8_t threadCount, const uint8_t queueSize, const uint8_t additionalJobs, const bool runExternal = false) + { + WorkerPoolTester workerPool(threadCount, 0, queueSize); + ::Thunder::Core::WorkerPool::Assign(&workerPool); + + std::vector<::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>> jobs; + // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs + for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { + jobs.push_back(::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(workerPool, TestJob::INITIATED, 100))); + } + + if (runExternal == true) { + workerPool.RunExternal(); + } + + for (uint8_t i = 0; i < queueSize; ++i) { + EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); + workerPool.SubmitUsingSelfWorker(jobs[i]); + } + for (uint8_t i = queueSize; i < jobs.size(); ++i) { + EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); + workerPool.SubmitUsingExternalWorker(jobs[i]); + } + + workerPool.RunThreadPool(); + usleep(MaxJobWaitTime); + for (auto& job: jobs) { + EXPECT_EQ(workerPool.WaitForJobEvent(job, MaxJobWaitTime * 3), ::Thunder::Core::ERROR_NONE); + } + + for (auto& job: jobs) { + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); + } + + workerPool.Stop(); + + for (auto& job: jobs) { + job.Release(); + } + jobs.clear(); + ::Thunder::Core::WorkerPool::Assign(nullptr); + } + TEST(Core_WorkerPool, Check_SinglePool_WithSinglJob) + { + CheckWorkerPool_MultipleJobs(1, 1, 0); + } + TEST(Core_WorkerPool, Check_SinglePool_WithMultipleJobs) + { + CheckWorkerPool_MultipleJobs(1, 5, 0); + } + TEST(Core_WorkerPool, Check_SinglePool_WithMultipleJobs_AdditionalJobs_WithExternal) + { + CheckWorkerPool_MultipleJobs(1, 5, 5, true); + } + TEST(Core_WorkerPool, Check_MultiplePool_WithMultipleJobs) + { + CheckWorkerPool_MultipleJobs(5, 5, 0); + } + TEST(Core_WorkerPool, Check_MultiplePool_WithMultipleJobs_AdditionalJobs) + { + CheckWorkerPool_MultipleJobs(5, 2, 2); + CheckWorkerPool_MultipleJobs(5, 1, 2); + CheckWorkerPool_MultipleJobs(5, 5, MaxAdditionalWorker); + } + TEST(Core_WorkerPool, Check_MultiplePool_WithMultipleJobs_AdditionalJobs_WithExternal) + { + CheckWorkerPool_MultipleJobs(5, 5, 4, true); + } + void CheckWorkerPool_MultipleJobs_CancelJobs_InBetween(const uint8_t threadCount, const uint8_t queueSize, const uint8_t additionalJobs, const uint8_t cancelJobsCount, const uint8_t cancelJobsId[]) + { + WorkerPoolTester workerPool(threadCount, 0, queueSize); + ::Thunder::Core::WorkerPool::Assign(&workerPool); + + std::vector<::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>> jobs; + // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs + for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { + jobs.push_back(::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(workerPool, TestJob::INITIATED, 1000))); + } + + for (uint8_t i = 0; i < queueSize; ++i) { + EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); + workerPool.SubmitUsingSelfWorker(jobs[i]); + } + for (uint8_t i = queueSize; i < jobs.size(); ++i) { + EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); + workerPool.SubmitUsingExternalWorker(jobs[i]); + } + + // Multi Pool case jobs can be run in parallel once we start thread, hence revoke inbetween maynot work + // it just have to wait for processing jobs completion. + // Hence revoking before starting the job. Just to ensure the status meets + for (uint8_t index = 0; index < cancelJobsCount; index++) { + workerPool.Revoke(jobs[cancelJobsId[index]], 0); + } + workerPool.RunThreadPool(); + + for (uint8_t index = 0; index < jobs.size(); index++) { + bool isCanceledJob = false; + for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) + { + if (index == cancelJobsId[cancelIndex]) { + isCanceledJob = true; + break; + } + } + if (isCanceledJob == true) { + EXPECT_EQ(workerPool.WaitForJobEvent(jobs[index], MaxJobWaitTime * 3), ::Thunder::Core::ERROR_TIMEDOUT); + } else { + EXPECT_EQ(workerPool.WaitForJobEvent(jobs[index], MaxJobWaitTime * 3), ::Thunder::Core::ERROR_NONE); + } + } + + for (uint8_t index = 0; index < jobs.size(); index++) { + bool isCanceledJob = false; + for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) + { + if (index == cancelJobsId[cancelIndex]) { + isCanceledJob = true; + break; + } + } + if (isCanceledJob == true) { + EXPECT_EQ(static_cast&>(*jobs[index]).GetStatus(), TestJob::INITIATED); + } else { + EXPECT_EQ(static_cast&>(*jobs[index]).GetStatus(), TestJob::COMPLETED); + } + } + + workerPool.Stop(); + + for (auto& job: jobs) { + job.Release(); + } + jobs.clear(); + ::Thunder::Core::WorkerPool::Assign(nullptr); + } + TEST(Core_WorkerPool, Check_SinglePool_WithMultipleJobs_CancelJobs_InBetween) + { + uint8_t cancelJobsId[] = {3, 4}; + CheckWorkerPool_MultipleJobs_CancelJobs_InBetween(1, 5, 0, sizeof(cancelJobsId), cancelJobsId); + } + TEST(Core_WorkerPool, Check_SinglePool_WithMultipleJobs_AdditionalJobs_CancelJobs_InBetween) + { + uint8_t cancelJobsId[] = {3, 4}; + CheckWorkerPool_MultipleJobs_CancelJobs_InBetween(1, 5, 2, sizeof(cancelJobsId), cancelJobsId); + } + TEST(Core_WorkerPool, Check_MultiplePool_WithMultipleJobs_AdditionalJobs_CancelJobs_InBetween) + { + uint8_t cancelJobsId[] = {3, 4}; + CheckWorkerPool_MultipleJobs_CancelJobs_InBetween(5, 5, 2, sizeof(cancelJobsId), cancelJobsId); + CheckWorkerPool_MultipleJobs_CancelJobs_InBetween(5, 5, MaxAdditionalWorker, sizeof(cancelJobsId), cancelJobsId); + } + void CheckWorkerPool_ScheduleJobs(const uint8_t threadCount, const uint8_t queueSize, const uint8_t additionalJobs, const uint8_t cancelJobsCount, const uint8_t* cancelJobsId, const uint16_t scheduledTimes[]) + { + WorkerPoolTester workerPool(threadCount, 0, queueSize); + ::Thunder::Core::WorkerPool::Assign(&workerPool); + workerPool.RunThreadPool(); + + std::vector<::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>> jobs; + // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs + for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { + jobs.push_back(::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(workerPool, TestJob::INITIATED, 500, false, true))); + } + + for (uint8_t i = 0; i < queueSize; ++i) { + EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); + workerPool.ScheduleJobs(jobs[i], scheduledTimes[i]); + } + for (uint8_t i = queueSize; i < jobs.size(); ++i) { + EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); + workerPool.ScheduleJobs(jobs[i], scheduledTimes[i]); + } + + for (uint8_t index = 0; index < cancelJobsCount; index++) { + workerPool.Revoke(jobs[cancelJobsId[index]], 0); + } + + for (uint8_t index = 0; index < jobs.size(); index++) { + bool isCanceledJob = false; + for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) + { + if (index == cancelJobsId[cancelIndex]) { + isCanceledJob = true; + break; + } + } + if (isCanceledJob == true) { + EXPECT_EQ(workerPool.WaitForJobEvent(jobs[index], MaxJobWaitTime * 3), ::Thunder::Core::ERROR_TIMEDOUT); + } else { + EXPECT_EQ(workerPool.WaitForJobEvent(jobs[index], MaxJobWaitTime * 15), ::Thunder::Core::ERROR_NONE); + } + } + + for (uint8_t index = 0; index < jobs.size(); index++) { + bool isCanceledJob = false; + for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) + { + if (index == cancelJobsId[cancelIndex]) { + isCanceledJob = true; + break; + } + } + if (isCanceledJob == true) { + EXPECT_EQ(static_cast&>(*jobs[index]).GetStatus(), TestJob::INITIATED); + } else { + EXPECT_EQ(static_cast&>(*jobs[index]).GetStatus(), TestJob::COMPLETED); + } + } + + workerPool.Stop(); + + for (auto& job: jobs) { + job.Release(); + } + jobs.clear(); + ::Thunder::Core::WorkerPool::Assign(nullptr); + } + TEST(Core_WorkerPool, Check_ScheduleJobs_SinglePool_SingleJob) + { + const uint16_t scheduledTimes[] = {2000}; //In milliseconds + CheckWorkerPool_ScheduleJobs(1, 1, 0, 0, nullptr, scheduledTimes); + } + TEST(Core_WorkerPool, Check_ScheduleJobs_SinglePool_SingleJob_ZeroTime) + { + const uint16_t scheduledTimes[] = {0}; + CheckWorkerPool_ScheduleJobs(1, 1, 0, 0, nullptr, scheduledTimes); + } + TEST(Core_WorkerPool, Check_ScheduleJobs_SinglePool_AdditionalJob) + { + const uint16_t scheduledTimes[] = {3000, 2000}; + CheckWorkerPool_ScheduleJobs(2, 1, 1, 0, nullptr, scheduledTimes); + } + TEST(Core_WorkerPool, Check_ScheduleJobs_SinglePool_SingleJob_CancelJob) + { + const uint16_t scheduledTimes[] = {2000}; + const uint8_t job = 0; + CheckWorkerPool_ScheduleJobs(1, 1, 0, 1, &job, scheduledTimes); + } + TEST(Core_WorkerPool, Check_ScheduleJobs_SinglePool_AdditionalJob_CancelJob) + { + const uint16_t scheduledTimes[] = {2000, 2000}; + const uint8_t job = 0; + CheckWorkerPool_ScheduleJobs(1, 1, 1, 1, &job, scheduledTimes); + } + TEST(Core_WorkerPool, Check_ScheduleJobs_SinglePool_MultipleJobs) + { + uint8_t maxJobs = 5; + const uint16_t scheduledTimes[] = {2000, 3000, 1000, 2000, 3000}; + CheckWorkerPool_ScheduleJobs(1, maxJobs, 0, 0, nullptr, scheduledTimes); + } + TEST(Core_WorkerPool, Check_ScheduleJobs_SinglePool_MultipleJobs_ZeroTime) + { + uint8_t maxJobs = 5; + const uint16_t scheduledTimes[5] = {0}; + CheckWorkerPool_ScheduleJobs(1, maxJobs, 0, 0, nullptr, scheduledTimes); + } + TEST(Core_WorkerPool, Check_ScheduleJobs_SinglePool_MultipleJobs_CancelJob) + { + uint8_t maxJobs = 5; + const uint8_t jobs[] = {1, 2}; + const uint16_t scheduledTimes[] = {2000, 3000, 1000, 2000, 3000}; + CheckWorkerPool_ScheduleJobs(1, maxJobs, 0, sizeof(jobs), jobs, scheduledTimes); + } + TEST(Core_WorkerPool, Check_ScheduleJobs_MultiplePool_MultipleJobs) + { + uint8_t maxJobs = 5; + const uint16_t scheduledTimes[] = {2000, 3000, 1000, 2000, 3000}; + CheckWorkerPool_ScheduleJobs(5, maxJobs, 0, 0, nullptr, scheduledTimes); + CheckWorkerPool_ScheduleJobs(2, maxJobs, 0, 0, nullptr, scheduledTimes); + CheckWorkerPool_ScheduleJobs(2, 2, 0, 0, nullptr, scheduledTimes); + } + TEST(Core_WorkerPool, Check_ScheduleJobs_MultiplePool_MultipleJobs_ZeroTime) + { + uint8_t maxJobs = 5; + const uint16_t scheduledTimes[5] = {0}; + CheckWorkerPool_ScheduleJobs(5, maxJobs, 0, 0, nullptr, scheduledTimes); + CheckWorkerPool_ScheduleJobs(2, maxJobs, 0, 0, nullptr, scheduledTimes); + CheckWorkerPool_ScheduleJobs(2, 2, 0, 0, nullptr, scheduledTimes); + } + TEST(Core_WorkerPool, Check_ScheduleJobs_MultiplePool_MultipleJobs_CancelJob) + { + uint8_t maxJobs = 5; + const uint16_t scheduledTimes[] = {2000, 3000, 1000, 2000, 3000, 2000, 1000, 1000, 3000}; + const uint8_t jobs[] = {0, 4}; + CheckWorkerPool_ScheduleJobs(5, maxJobs, 0, 0, nullptr, scheduledTimes); + CheckWorkerPool_ScheduleJobs(2, maxJobs, 0, 0, nullptr, scheduledTimes); + CheckWorkerPool_ScheduleJobs(5, 5, 0, sizeof(jobs), jobs, scheduledTimes); + } + TEST(Core_WorkerPool, Check_ScheduleJobs_MultiplePool_MultipleJobs_AdditionalJobs) + { + uint8_t maxJobs = 5; + const uint16_t scheduledTimes[] = {2000, 3000, 1000, 2000, 3000, 1000}; + CheckWorkerPool_ScheduleJobs(5, maxJobs, 0, 0, nullptr, scheduledTimes); + CheckWorkerPool_ScheduleJobs(2, maxJobs, 0, 0, nullptr, scheduledTimes); + CheckWorkerPool_ScheduleJobs(2, 2, 1, 0, nullptr, scheduledTimes); + } + TEST(Core_WorkerPool, Check_ScheduleJobs_MultiplePool_MultipleJobs_AdditionalJobs_CancelJob) + { + uint8_t maxJobs = 5; + const uint16_t scheduledTimes[] = {2000, 3000, 1000, 2000, 3000, 1000, 1000, 2000, 3000}; + const uint8_t jobs[] = {3, 5}; + CheckWorkerPool_ScheduleJobs(5, maxJobs, 0, 0, nullptr, scheduledTimes); + CheckWorkerPool_ScheduleJobs(2, maxJobs, 0, 0, nullptr, scheduledTimes); + CheckWorkerPool_ScheduleJobs(5, 5, 4, sizeof(jobs), jobs, scheduledTimes); + } + void CheckWorkerPool_RescheduleJobs(const uint8_t threadCount, const uint8_t queueSize, const uint8_t additionalJobs, const uint8_t cancelJobsCount, const uint8_t* cancelJobsId, const uint16_t scheduledTimes[], const uint16_t rescheduledTimes[]) + { + WorkerPoolTester workerPool(threadCount, 0, queueSize); + ::Thunder::Core::WorkerPool::Assign(&workerPool); + workerPool.RunThreadPool(); + + std::vector<::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>> jobs; + // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs + for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { + jobs.push_back(::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(workerPool, TestJob::INITIATED, 500, false, true))); + } + + for (uint8_t i = 0; i < queueSize; ++i) { + EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); + workerPool.ScheduleJobs(jobs[i], scheduledTimes[i]); + } + for (uint8_t i = queueSize; i < jobs.size(); ++i) { + EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); + workerPool.ScheduleJobs(jobs[i], scheduledTimes[i]); + } + + for (uint8_t i = 0; i < jobs.size(); ++i) { + workerPool.RescheduleJobs(jobs[i], rescheduledTimes[i]); + } + for (uint8_t index = 0; index < cancelJobsCount; index++) { + workerPool.Revoke(jobs[cancelJobsId[index]], 0); + } + + for (uint8_t index = 0; index < jobs.size(); index++) { + bool isCanceledJob = false; + for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) + { + if (index == cancelJobsId[cancelIndex]) { + isCanceledJob = true; + break; + } + } + if (isCanceledJob == true) { + EXPECT_EQ(workerPool.WaitForJobEvent(jobs[index], MaxJobWaitTime * 3), ::Thunder::Core::ERROR_TIMEDOUT); + } else { + EXPECT_EQ(workerPool.WaitForJobEvent(jobs[index], MaxJobWaitTime * 15), ::Thunder::Core::ERROR_NONE); + } + } + + for (uint8_t index = 0; index < jobs.size(); index++) { + bool isCanceledJob = false; + for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) + { + if (index == cancelJobsId[cancelIndex]) { + isCanceledJob = true; + break; + } + } + if (isCanceledJob == true) { + EXPECT_EQ(static_cast&>(*jobs[index]).GetStatus(), TestJob::INITIATED); + } else { + EXPECT_EQ(static_cast&>(*jobs[index]).GetStatus(), TestJob::COMPLETED); + } + } + + workerPool.Stop(); + + jobs.clear(); + ::Thunder::Core::WorkerPool::Assign(nullptr); + } + TEST(Core_WorkerPool, Check_RescheduleJobs_SinglePool_SingleJob) { + const uint16_t scheduledTimes[] = {1000}; + const uint16_t rescheduledTimes[] = {2000}; + CheckWorkerPool_RescheduleJobs(1, 1, 0, 0, nullptr, scheduledTimes, rescheduledTimes); } - ~EventControl() = default; - -public: - void Notify() + TEST(Core_WorkerPool, Check_RescheduleJobs_SinglePool_SingleJob_ZeroTime) + { + const uint16_t scheduledTimes[] = {1000}; + const uint16_t rescheduledTimes[] = {0}; + CheckWorkerPool_RescheduleJobs(1, 1, 0, 0, nullptr, scheduledTimes, rescheduledTimes); + } + TEST(Core_WorkerPool, Check_RescheduleJobs_SinglePool_SingleJob_AdditionalJobs) + { + const uint16_t scheduledTimes[] = {1000, 2000}; + const uint16_t rescheduledTimes[] = {2000, 1000}; + CheckWorkerPool_RescheduleJobs(1, 1, 1, 0, nullptr, scheduledTimes, rescheduledTimes); + } + TEST(Core_WorkerPool, Check_RescheduleJobs_SinglePool_SingleJob_CancelJob) + { + uint16_t scheduledTimes[] = {1000}; + const uint16_t rescheduledTimes[] = {2000}; + const uint8_t job = 0; + CheckWorkerPool_RescheduleJobs(1, 1, 0, 1, &job, scheduledTimes, rescheduledTimes); + scheduledTimes[0] = 4000; + CheckWorkerPool_RescheduleJobs(1, 1, 0, 1, &job, scheduledTimes, rescheduledTimes); + } + TEST(Core_WorkerPool, Check_RescheduleJobs_SinglePool_AdditionalJob_CancelJob) { - _event.SetEvent(); + const uint16_t scheduledTimes[] = {4000, 1000}; + const uint16_t rescheduledTimes[] = {3000, 2000}; + const uint8_t job = 1; + CheckWorkerPool_RescheduleJobs(1, 1, 1, 1, &job, scheduledTimes, rescheduledTimes); } - uint32_t WaitForEvent(uint32_t waitTime) + TEST(Core_WorkerPool, Check_RescheduleJobs_SinglePool_MultipleJobs) { - return _event.Lock(waitTime); + const uint16_t scheduledTimes[] = {1000, 2000, 3000, 2000, 1000}; + const uint16_t rescheduledTimes[] = {2000, 2000, 1000, 2000, 3000}; + CheckWorkerPool_RescheduleJobs(1, 5, 0, 0, nullptr, scheduledTimes, rescheduledTimes); } - void Reset() + TEST(Core_WorkerPool, Check_RescheduleJobs_SinglePool_MultipleJobs_ZeroTime) { - _event.ResetEvent(); + const uint16_t scheduledTimes[] = {1000, 2000, 3000, 2000, 1000}; + const uint16_t rescheduledTimes[5] = {0}; + CheckWorkerPool_RescheduleJobs(1, 5, 0, 0, nullptr, scheduledTimes, rescheduledTimes); } + TEST(Core_WorkerPool, Check_RescheduleJobs_SinglePool_MultipleJobs_AdditionalJobs) + { + const uint16_t scheduledTimes[] = {5000, 2000, 6000, 1000, 2000, 3000, 1000, 1000, 2000, 4000}; + const uint16_t rescheduledTimes[] = {2000, 1000, 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000}; -private: - Event _event; -}; + CheckWorkerPool_RescheduleJobs(1, 5, 2, 0, nullptr, scheduledTimes, rescheduledTimes); + CheckWorkerPool_RescheduleJobs(1, 5, 5, 0, nullptr, scheduledTimes, rescheduledTimes); + } + TEST(Core_WorkerPool, Check_RescheduleJobs_SinglePool_MultipleJobs_CancelJob) + { + const uint16_t scheduledTimes[] = {1000, 2000, 3000, 2000, 1000}; + const uint16_t rescheduledTimes[] = {2000, 2000, 1000, 2000, 3000}; -template -class TestJob : public Core::IDispatch, public EventControl { -public: - enum Status { - INITIATED, - CANCELED, - COMPLETED, - }; + const uint8_t jobs[] = {1, 4}; + CheckWorkerPool_RescheduleJobs(1, 5, 0, sizeof(jobs), jobs, scheduledTimes, rescheduledTimes); + } + TEST(Core_WorkerPool, Check_RescheduleJobs_SinglePool_MultipleJobs_AdditionalJob_CancelJob) + { + const uint16_t scheduledTimes[] = {5000, 2000, 6000, 1000, 2000, 3000, 1000, 1000, 2000, 4000}; + const uint16_t rescheduledTimes[] = {2000, 1000, 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000}; - TestJob() = delete; - TestJob(const TestJob& copy) = delete; - TestJob& operator=(const TestJob& RHS) = delete; - ~TestJob() override = default; - TestJob(IMPLEMENTATION& parent, const Status status, const uint32_t waitTime = 0, const bool checkParentState = false, const bool notifyInvokedTime = false, const bool validateId = false) - : _parent(parent) - , _status(status) - , _waitTime(waitTime) - , _checkParentState(checkParentState) - , _notifyInvokedTime(notifyInvokedTime) - , _validateId(validateId) + const uint8_t jobs[] = {2, 6}; + CheckWorkerPool_RescheduleJobs(1, 5, 5, sizeof(jobs), jobs, scheduledTimes, rescheduledTimes); + } + TEST(Core_WorkerPool, Check_RescheduleJobs_MultiplePool_MultipleJobs) { + const uint16_t scheduledTimes[] = {1000, 2000, 3000, 2000, 1000}; + const uint16_t rescheduledTimes[] = {2000, 2000, 1000, 2000, 3000}; + CheckWorkerPool_RescheduleJobs(1, 5, 0, 0, nullptr, scheduledTimes, rescheduledTimes); } - -public: - Status GetStatus() + TEST(Core_WorkerPool, Check_RescheduleJobs_MultiplePool_MultipleJobs_ZeroTime) { - return _status; + const uint16_t scheduledTimes[] = {1000, 2000, 3000, 2000, 1000}; + const uint16_t rescheduledTimes[5] = {0}; + CheckWorkerPool_RescheduleJobs(1, 5, 0, 0, nullptr, scheduledTimes, rescheduledTimes); } - void Dispatch() override + TEST(Core_WorkerPool, Check_RescheduleJobs_MultiplePool_MultipleJobs_AdditionalJobs) { - Core::Time invokedTime = Core::Time::Now(); - _status = COMPLETED; - usleep(_waitTime); - Notify(); - if (_checkParentState) { - _parent.WaitForReady(this, _waitTime * 10); - } - if (_notifyInvokedTime) { - _parent.InvokedTime(this, invokedTime); - } - if (_validateId) { - _parent.ValidateId(); - } + const uint16_t scheduledTimes[] = {5000, 2000, 6000, 1000, 2000, 3000, 1000, 1000, 2000, 4000}; + const uint16_t rescheduledTimes[] = {2000, 1000, 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000}; + CheckWorkerPool_RescheduleJobs(1, 5, 2, 0, nullptr, scheduledTimes, rescheduledTimes); + CheckWorkerPool_RescheduleJobs(1, 5, 5, 0, nullptr, scheduledTimes, rescheduledTimes); } + TEST(Core_WorkerPool, Check_RescheduleJobs_MultiplePool_MultipleJobs_CancelJob) + { + const uint16_t scheduledTimes[] = {1000, 2000, 3000, 2000, 1000}; + const uint16_t rescheduledTimes[] = {2000, 2000, 1000, 2000, 3000}; -private: - IMPLEMENTATION& _parent; - Status _status; - uint32_t _waitTime; - bool _checkParentState; - bool _notifyInvokedTime; - bool _validateId; -}; - -struct JobData { - EventControl* Event; - Core::Time CurrentTime; - uint16_t ScheduledTime; -}; + const uint8_t jobs[] = {1, 4}; + CheckWorkerPool_RescheduleJobs(1, 5, 0, sizeof(jobs), jobs, scheduledTimes, rescheduledTimes); + } + TEST(Core_WorkerPool, Check_RescheduleJobs_MultiplePool_MultipleJobs_AdditionalJob_CancelJob) + { + const uint16_t scheduledTimes[] = {5000, 2000, 6000, 1000, 2000, 3000, 1000, 1000, 2000, 4000}; + const uint16_t rescheduledTimes[] = {2000, 1000, 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000}; -template -class JobControl { -private: - typedef std::map JobMap; -private: - template - class ExternalWorker : public Thread { - public: - ExternalWorker() = delete; - ExternalWorker& operator=(const ExternalWorker&) = delete; - ExternalWorker(const ExternalWorker& copy) - : _job(copy._job) - , _parent(copy._parent) - { - } + const uint8_t jobs[] = {3, 5}; + CheckWorkerPool_RescheduleJobs(5, 5, 2, sizeof(jobs), jobs, scheduledTimes, rescheduledTimes); + CheckWorkerPool_RescheduleJobs(5, 5, 5, sizeof(jobs), jobs, scheduledTimes, rescheduledTimes); + } + void CheckMetaData(const uint8_t pending, const uint8_t occupation, const uint8_t expectedRuns) + { + const ::Thunder::Core::IWorkerPool::Metadata& metaData = ::Thunder::Core::IWorkerPool::Instance().Snapshot(); - ExternalWorker(PARENTIMPL &parent) - : _job(nullptr) - , _parent(parent) - { - } - ~ExternalWorker() - { - Stop(); - } + EXPECT_EQ(metaData.Pending.size(), pending); // Whatever is in the ThreadPool::_queue is considered pending - public: - void Stop() - { - Core::Thread::Stop(); - Core::Thread::Wait(Core::Thread::STOPPED|Core::Thread::BLOCKED, Core::infinite); - } - virtual uint32_t Worker() override - { - if (IsRunning()) { - _parent.SubmitJob(*_job); - } - Core::Thread::Block(); - return (Core::infinite); + uint16_t totalRuns = 0, totalOccupation = 0; + for (uint8_t index = 0; index < metaData.Slots; index++) { + totalRuns += metaData.Slot[index].Runs; + totalOccupation += metaData.Slot[index].Job.IsSet(); } + EXPECT_EQ(totalRuns, expectedRuns); + EXPECT_EQ(totalOccupation, occupation); + } + void CheckWorkerPool_MetaData(uint8_t threadCount, uint8_t queueSize, uint8_t additionalJobs) + { + WorkerPoolTester workerPool(threadCount, 0, queueSize); + ::Thunder::Core::WorkerPool::Assign(&workerPool); - void Submit(Core::ProxyType& job) - { - _job = &job; - Core::Thread::Run(); + std::vector<::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>> jobs; + // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs + for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { + jobs.push_back(::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(workerPool, TestJob::INITIATED, 100))); } - private: - Core::ProxyType* _job; - IMPLEMENTATION& _parent; - }; -public: - JobControl() = delete; - JobControl(const JobControl&) = delete; - JobControl& operator=(const JobControl&) = delete; - JobControl(IMPLEMENTATION &parent, uint8_t threadsCount) - : _index(0) - , _threadsCount(threadsCount) - , _parent(parent) - , _external() - { - for (uint8_t index = 0; index < MaxAdditionalWorker; ++index) { - _external.push_back(new ExternalWorker(parent)); - } - } - ~JobControl() - { - for (auto& job: _jobs) { - delete job.second.Event; + for (uint8_t i = 0; i < queueSize; ++i) { + EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); + workerPool.SubmitUsingSelfWorker(jobs[i]); } - _jobs.clear(); - for (auto& external: _external) { - delete external; + for (uint8_t i = queueSize; i < jobs.size(); ++i) { + EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); + workerPool.SubmitUsingExternalWorker(jobs[i]); } - _external.clear(); - Singleton::Dispose(); - } + CheckMetaData(queueSize, 1, 0); + workerPool.RunThreadPool(); -public: - static void CheckScheduledTime(Core::Time current, Core::Time invokedTime, uint16_t scheduledTime) - { - uint8_t currentSecond = current.Seconds(); - uint8_t scheduledSecond = scheduledTime; // From milliseconds to seconds, integer division! - uint8_t invokedSecond = invokedTime.Seconds(); + usleep(MaxJobWaitTime); + for (auto& job: jobs) { + EXPECT_EQ(workerPool.WaitForJobEvent(job, MaxJobWaitTime * 3), ::Thunder::Core::ERROR_NONE); + } - uint32_t expectedAddedTime = 0; - if (currentSecond + scheduledSecond >= 60) { - expectedAddedTime = (currentSecond + scheduledSecond) - 60; - } else { - expectedAddedTime = (currentSecond + scheduledSecond); + for (auto& job: jobs) { + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); } - EXPECT_LE(invokedSecond, expectedAddedTime); + workerPool.Stop(); + CheckMetaData(queueSize, 1, queueSize + additionalJobs); + for (auto& job: jobs) { + job.Release(); + } + jobs.clear(); + ::Thunder::Core::WorkerPool::Assign(nullptr); } - uint32_t WaitForReady(IDispatch* job, const uint32_t waitTime = 0) + TEST(Core_WorkerPool, Check_MetaData_SinglePool_SingleJob) { - uint32_t result = Core::ERROR_NONE; - JobMap::iterator index = _jobs.find(job); - if (index != _jobs.end()) { - result = index->second.Event->WaitForEvent(waitTime); - } - return result; + CheckWorkerPool_MetaData(1, 1, 0); } - void NotifyReady(const Core::ProxyType& job) + TEST(Core_WorkerPool, Check_MetaData_SinglePool_SingleJob_AdditionalJobs) { - JobMap::iterator index = _jobs.find(job.operator->()); - if (index != _jobs.end()) { - index->second.Event->Notify(); - } + CheckWorkerPool_MetaData(1, 1, 2); } - void SubmitUsingSelfWorker(Core::ProxyType& job) + TEST(Core_WorkerPool, Check_MetaData_SinglePool_MultipleJobs) { - InsertJobData(job, 0); - _parent.Submit(job); + CheckWorkerPool_MetaData(1, 5, 0); } - void SubmitUsingExternalWorker(Core::ProxyType& job) + TEST(Core_WorkerPool, Check_MetaData_SinglePool_MultipleJobs_AdditionalJobs) { - if (_index < MaxAdditionalWorker) { - InsertJobData(job, 0); - _external[_index++]->Submit(job); - } + CheckWorkerPool_MetaData(1, 5, 2); } - void ScheduleJobs(Core::ProxyType& job, const uint16_t scheduledTime) + TEST(Core_WorkerPool, Check_MetaData_MultiplePool_MultipleJobs) { - InsertJobData(job, scheduledTime); - _parent.Schedule(Core::Time::Now().Add(scheduledTime), job); + CheckWorkerPool_MetaData(5, 5, 0); } - void RescheduleJobs(Core::ProxyType& job, const uint16_t scheduledTime) + TEST(Core_WorkerPool, Check_MetaData_MultiplePool_MultipleJobs_AdditionalJobs) { - InsertJobData(job, scheduledTime); - _parent.Reschedule(Core::Time::Now().Add(scheduledTime), job); + CheckWorkerPool_MetaData(5, 5, 5); } - void ValidateId() + void CheckWorkerPool_Ids(uint8_t threadCount, uint8_t queueSize, uint8_t additionalJobs) { - const uint8_t MaxSize = 15; - bool isPoolId = false; - char id[MaxSize]; - sprintf(id, "%x", static_cast(pthread_self())); - for (uint8_t index = 0; index < _threadsCount + 2; index++) { - char workerId[MaxSize]; - sprintf(workerId, "%x", static_cast(IWorkerPool::Instance().Id(index))); + WorkerPoolTester workerPool(threadCount, 0, queueSize); + ::Thunder::Core::WorkerPool::Assign(&workerPool); + workerPool.RunThreadPool(); - if (strcpy(workerId, id)) { - isPoolId = true; - break; - } + std::vector<::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>> jobs; + // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs + for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { + jobs.push_back(::Thunder::Core::ProxyType<::Thunder::Core::IDispatch>(::Thunder::Core::ProxyType>::Create(workerPool, TestJob::INITIATED, 100, false, false, true))); } - EXPECT_EQ(isPoolId, true); - } - void InvokedTime(IDispatch* job, const Core::Time& invokedTime) - { - JobMap::iterator index = _jobs.find(job); - if (index != _jobs.end()) { - CheckScheduledTime(index->second.CurrentTime, invokedTime, index->second.ScheduledTime); + + for (uint8_t i = 0; i < queueSize; ++i) { + EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); + workerPool.SubmitUsingSelfWorker(jobs[i]); } - } - void RemoveJobData(Core::ProxyType& job) - { - JobMap::iterator index = _jobs.find(job.operator->()); - if (index != _jobs.end()) { - delete index->second.Event; - _jobs.erase(index); + for (uint8_t i = queueSize; i < jobs.size(); ++i) { + EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); + workerPool.SubmitUsingExternalWorker(jobs[i]); } - } -private: - void InsertJobData(Core::ProxyType& job, uint16_t scheduledTime) - { - JobData jobData; - jobData.Event = new EventControl(); - jobData.ScheduledTime = scheduledTime; - jobData.CurrentTime = Core::Time::Now(); - JobMap::iterator index = _jobs.find(job.operator->()); - if (index == _jobs.end()) { - _jobs.emplace(std::piecewise_construct, std::forward_as_tuple(job.operator->()), std::forward_as_tuple(jobData)); - } else { - index->second.CurrentTime = Core::Time::Now(); - index->second.ScheduledTime = scheduledTime; + for (auto& job: jobs) { + EXPECT_EQ(workerPool.WaitForJobEvent(job, MaxJobWaitTime * 3), ::Thunder::Core::ERROR_NONE); } - } - -private: - uint8_t _index; - uint8_t _threadsCount; - JobMap _jobs; - IMPLEMENTATION& _parent; - std::vector*> _external; -}; -class WorkerPoolTester : public Core::WorkerPool, public JobControl, public Core::Thread { -public: - WorkerPoolTester() = delete; - WorkerPoolTester(const WorkerPoolTester&) = delete; - WorkerPoolTester& operator=(const WorkerPoolTester&) = delete; - - WorkerPoolTester(const uint8_t threads, const uint32_t stackSize, const uint32_t queueSize) - : WorkerPool(threads, stackSize, queueSize, &_dispatcher) - , JobControl(*this, threads) - { - } + for (auto& job: jobs) { + EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); + } - ~WorkerPoolTester() - { - // Diable the queue so the minions can stop, even if they are processing and waiting for work.. - Stop(); - Core::Singleton::Dispose(); + workerPool.Stop(); + for (auto& job: jobs) { + job.Release(); + } + jobs.clear(); + ::Thunder::Core::WorkerPool::Assign(nullptr); } - -public: - void Stop() + TEST(Core_WorkerPool, Check_Ids_SinglePool_SingleJob) { - Core::WorkerPool::Stop(); - Core::Thread::Wait(Core::Thread::STOPPED|Core::Thread::BLOCKED, Core::infinite); + CheckWorkerPool_Ids(1, 1, 0); } - - uint32_t WaitForJobEvent(const Core::ProxyType& job, const uint32_t waitTime = 0) + TEST(Core_WorkerPool, Check_Ids_SinglePool_SingleJob_AdditionalJobs) { - return static_cast&>(*job).WaitForEvent(waitTime); + CheckWorkerPool_Ids(1, 1, 2); } - void SubmitJob(const Core::ProxyType& job) + TEST(Core_WorkerPool, Check_Ids_SinglePool_MultipleJobs) { - Submit(job); + CheckWorkerPool_Ids(1, 5, 0); } - virtual uint32_t Worker() override + TEST(Core_WorkerPool, Check_Ids_SinglePool_MultipleJobs_AdditionalJobs) { - if (IsRunning()) { - Join(); - } - Core::Thread::Block(); - return (Core::infinite); + CheckWorkerPool_Ids(1, 5, 2); } - void RunExternal() + TEST(Core_WorkerPool, Check_Ids_MultiplePool_MultipleJobs) { - Core::Thread::Run(); + CheckWorkerPool_Ids(5, 5, 0); } - void RunThreadPool() + TEST(Core_WorkerPool, Check_Ids_MultiplePool_MultipleJobs_AdditionalJobs) { - static_cast(this)->Run(); + CheckWorkerPool_Ids(5, 5, 5); } -private: - class Dispatcher : public Core::ThreadPool::IDispatcher { + class WorkerJobTester : public EventControl { public: - Dispatcher(const Dispatcher&) = delete; - Dispatcher& operator=(const Dispatcher&) = delete; - - Dispatcher() = default; - ~Dispatcher() override = default; + WorkerJobTester(const WorkerJobTester&) = delete; + WorkerJobTester& operator=(const WorkerJobTester&) = delete; - private: - void Initialize() override { } - void Deinitialize() override { } - void Dispatch(Core::IDispatch* job) override - { job->Dispatch(); } - }; - - Dispatcher _dispatcher; -}; -TEST(Core_WorkerPool, CheckWorkerStaticMethods) -{ - uint8_t queueSize = 5; - uint8_t threadCount = 1; - WorkerPoolTester workerPool(threadCount, 0, queueSize); - - EXPECT_EQ(Core::WorkerPool::IsAvailable(), false); - - Core::WorkerPool::Assign(&workerPool); - EXPECT_EQ(&Core::WorkerPool::Instance(), &workerPool); - EXPECT_EQ(Core::WorkerPool::IsAvailable(), true); - - Core::WorkerPool::Assign(nullptr); - EXPECT_EQ(Core::WorkerPool::IsAvailable(), false); -} -TEST(Core_WorkerPool, Check_WithSingleJob) -{ - uint8_t queueSize = 5; - uint8_t threadCount = 1; - WorkerPoolTester workerPool(threadCount, 0, queueSize); - Core::WorkerPool::Assign(&workerPool); - - Core::ProxyType job = Core::ProxyType(Core::ProxyType>::Create(workerPool, TestJob::INITIATED, 500)); - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); - workerPool.Submit(job); - workerPool.RunThreadPool(); - EXPECT_EQ(workerPool.WaitForJobEvent(job, MaxJobWaitTime), Core::ERROR_NONE); - workerPool.Stop(); - - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); - Core::WorkerPool::Assign(nullptr); - job.Release(); -} -TEST(Core_WorkerPool, Check_WithSingleJob_CancelJob_BeforeProcessing) -{ - uint8_t queueSize = 5; - uint8_t threadCount = 1; - WorkerPoolTester workerPool(threadCount, 0, queueSize); - Core::WorkerPool::Assign(&workerPool); - - Core::ProxyType job = Core::ProxyType(Core::ProxyType>::Create(workerPool, TestJob::INITIATED)); - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); - workerPool.Submit(job); - workerPool.Revoke(job); - workerPool.RunThreadPool(); - EXPECT_EQ(workerPool.WaitForJobEvent(job, MaxJobWaitTime), Core::ERROR_TIMEDOUT); - workerPool.Stop(); - - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); - Core::WorkerPool::Assign(nullptr); - job.Release(); -} -TEST(Core_WorkerPool, Check_WithSingleJob_CancelJob_WhileProcessing) -{ - uint8_t queueSize = 5; - uint8_t threadCount = 1; - WorkerPoolTester workerPool(threadCount, 0, queueSize); - Core::WorkerPool::Assign(&workerPool); - - Core::ProxyType job = Core::ProxyType(Core::ProxyType>::Create(workerPool, TestJob::INITIATED, 1000)); - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::INITIATED); - workerPool.Submit(job); - workerPool.RunThreadPool(); - usleep(100); - workerPool.Revoke(job); - EXPECT_EQ(workerPool.WaitForJobEvent(job, MaxJobWaitTime), Core::ERROR_NONE); - workerPool.Stop(); - - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); - Core::WorkerPool::Assign(nullptr); - job.Release(); -} -void CheckWorkerPool_MultipleJobs(const uint8_t threadCount, const uint8_t queueSize, const uint8_t additionalJobs, const bool runExternal = false) -{ - WorkerPoolTester workerPool(threadCount, 0, queueSize); - Core::WorkerPool::Assign(&workerPool); - - std::vector> jobs; - // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs - for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { - jobs.push_back(Core::ProxyType(Core::ProxyType>::Create(workerPool, TestJob::INITIATED, 100))); - } - - if (runExternal == true) { - workerPool.RunExternal(); - } - - for (uint8_t i = 0; i < queueSize; ++i) { - EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); - workerPool.SubmitUsingSelfWorker(jobs[i]); - } - for (uint8_t i = queueSize; i < jobs.size(); ++i) { - EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); - workerPool.SubmitUsingExternalWorker(jobs[i]); - } - - workerPool.RunThreadPool(); - usleep(MaxJobWaitTime); - for (auto& job: jobs) { - EXPECT_EQ(workerPool.WaitForJobEvent(job, MaxJobWaitTime * 3), Core::ERROR_NONE); - } - - for (auto& job: jobs) { - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); - } + WorkerJobTester() = delete; - workerPool.Stop(); + WorkerJobTester(uint32_t waitTime, bool waitForCaller = false) + : _waitTime(waitTime) + , _expectedTime() + , _waitForCaller(waitForCaller) + , _job(*this) + { + } + ~WorkerJobTester() = default; - for (auto& job: jobs) { - job.Release(); - } - jobs.clear(); - Core::WorkerPool::Assign(nullptr); -} -TEST(Core_WorkerPool, Check_SinglePool_WithSinglJob) -{ - CheckWorkerPool_MultipleJobs(1, 1, 0); -} -TEST(Core_WorkerPool, Check_SinglePool_WithMultipleJobs) -{ - CheckWorkerPool_MultipleJobs(1, 5, 0); -} -TEST(Core_WorkerPool, Check_SinglePool_WithMultipleJobs_AdditionalJobs_WithExternal) -{ - CheckWorkerPool_MultipleJobs(1, 5, 5, true); -} -TEST(Core_WorkerPool, Check_MultiplePool_WithMultipleJobs) -{ - CheckWorkerPool_MultipleJobs(5, 5, 0); -} -TEST(Core_WorkerPool, Check_MultiplePool_WithMultipleJobs_AdditionalJobs) -{ - CheckWorkerPool_MultipleJobs(5, 2, 2); - CheckWorkerPool_MultipleJobs(5, 1, 2); - CheckWorkerPool_MultipleJobs(5, 5, MaxAdditionalWorker); -} -TEST(Core_WorkerPool, Check_MultiplePool_WithMultipleJobs_AdditionalJobs_WithExternal) -{ - CheckWorkerPool_MultipleJobs(5, 5, 4, true); -} -void CheckWorkerPool_MultipleJobs_CancelJobs_InBetween(const uint8_t threadCount, const uint8_t queueSize, const uint8_t additionalJobs, const uint8_t cancelJobsCount, const uint8_t cancelJobsId[]) -{ - WorkerPoolTester workerPool(threadCount, 0, queueSize); - Core::WorkerPool::Assign(&workerPool); - - std::vector> jobs; - // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs - for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { - jobs.push_back(Core::ProxyType(Core::ProxyType>::Create(workerPool, TestJob::INITIATED, 1000))); - } - - for (uint8_t i = 0; i < queueSize; ++i) { - EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); - workerPool.SubmitUsingSelfWorker(jobs[i]); - } - for (uint8_t i = queueSize; i < jobs.size(); ++i) { - EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); - workerPool.SubmitUsingExternalWorker(jobs[i]); - } - - // Multi Pool case jobs can be run in parallel once we start thread, hence revoke inbetween maynot work - // it just have to wait for processing jobs completion. - // Hence revoking before starting the job. Just to ensure the status meets - for (uint8_t index = 0; index < cancelJobsCount; index++) { - workerPool.Revoke(jobs[cancelJobsId[index]], 0); - } - workerPool.RunThreadPool(); - - for (uint8_t index = 0; index < jobs.size(); index++) { - bool isCanceledJob = false; - for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) + bool Submit() { - if (index == cancelJobsId[cancelIndex]) { - isCanceledJob = true; - break; - } + _expectedTime = ::Thunder::Core::Time::Now(); + return _job.Submit(); } - if (isCanceledJob == true) { - EXPECT_EQ(workerPool.WaitForJobEvent(jobs[index], MaxJobWaitTime * 3), Core::ERROR_TIMEDOUT); - } else { - EXPECT_EQ(workerPool.WaitForJobEvent(jobs[index], MaxJobWaitTime * 3), Core::ERROR_NONE); + bool Schedule(const ::Thunder::Core::Time& time) + { + _expectedTime = time; + return _job.Reschedule(time); + } + bool Reschedule(const ::Thunder::Core::Time& time) + { + _expectedTime = time; + return _job.Reschedule(time); + } + void Revoke() + { + _job.Revoke(); + } + bool IsIdle() + { + return _job.IsIdle(); } - } - for (uint8_t index = 0; index < jobs.size(); index++) { - bool isCanceledJob = false; - for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) + public: + void Dispatch() { - if (index == cancelJobsId[cancelIndex]) { - isCanceledJob = true; - break; + ::Thunder::Core::Time invokedTime = ::Thunder::Core::Time::Now(); + WorkerPoolTester::CheckScheduledTime(_expectedTime, invokedTime, 0); + Notify(); + usleep(_waitTime * 2); + if (_waitForCaller) { + WaitForEvent(_waitTime * 10); + Reset(); } } - if (isCanceledJob == true) { - EXPECT_EQ(static_cast&>(*jobs[index]).GetStatus(), TestJob::INITIATED); - } else { - EXPECT_EQ(static_cast&>(*jobs[index]).GetStatus(), TestJob::COMPLETED); - } - } - workerPool.Stop(); + private: + uint32_t _waitTime; + ::Thunder::Core::Time _expectedTime; + bool _waitForCaller; + ::Thunder::Core::WorkerPool::JobType _job; + }; - for (auto& job: jobs) { - job.Release(); + TEST(Core_WorkerPool, Check_JobType_Submit) + { + WorkerPoolTester workerPool(1, 0, 1); + ::Thunder::Core::WorkerPool::Assign(&workerPool); + workerPool.RunThreadPool(); + { + WorkerJobTester jobTester(0); + EXPECT_EQ(jobTester.Submit(), true); + EXPECT_EQ(jobTester.WaitForEvent(MaxJobWaitTime * 3), ::Thunder::Core::ERROR_NONE); + } + workerPool.Stop(); + ::Thunder::Core::WorkerPool::Assign(nullptr); } - jobs.clear(); - Core::WorkerPool::Assign(nullptr); -} -TEST(Core_WorkerPool, Check_SinglePool_WithMultipleJobs_CancelJobs_InBetween) -{ - uint8_t cancelJobsId[] = {3, 4}; - CheckWorkerPool_MultipleJobs_CancelJobs_InBetween(1, 5, 0, sizeof(cancelJobsId), cancelJobsId); -} -TEST(Core_WorkerPool, Check_SinglePool_WithMultipleJobs_AdditionalJobs_CancelJobs_InBetween) -{ - uint8_t cancelJobsId[] = {3, 4}; - CheckWorkerPool_MultipleJobs_CancelJobs_InBetween(1, 5, 2, sizeof(cancelJobsId), cancelJobsId); -} -TEST(Core_WorkerPool, Check_MultiplePool_WithMultipleJobs_AdditionalJobs_CancelJobs_InBetween) -{ - uint8_t cancelJobsId[] = {3, 4}; - CheckWorkerPool_MultipleJobs_CancelJobs_InBetween(5, 5, 2, sizeof(cancelJobsId), cancelJobsId); - CheckWorkerPool_MultipleJobs_CancelJobs_InBetween(5, 5, MaxAdditionalWorker, sizeof(cancelJobsId), cancelJobsId); -} -void CheckWorkerPool_ScheduleJobs(const uint8_t threadCount, const uint8_t queueSize, const uint8_t additionalJobs, const uint8_t cancelJobsCount, const uint8_t* cancelJobsId, const uint16_t scheduledTimes[]) -{ - WorkerPoolTester workerPool(threadCount, 0, queueSize); - Core::WorkerPool::Assign(&workerPool); - workerPool.RunThreadPool(); - - std::vector> jobs; - // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs - for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { - jobs.push_back(Core::ProxyType(Core::ProxyType>::Create(workerPool, TestJob::INITIATED, 500, false, true))); - } - - for (uint8_t i = 0; i < queueSize; ++i) { - EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); - workerPool.ScheduleJobs(jobs[i], scheduledTimes[i]); - } - for (uint8_t i = queueSize; i < jobs.size(); ++i) { - EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); - workerPool.ScheduleJobs(jobs[i], scheduledTimes[i]); - } - - for (uint8_t index = 0; index < cancelJobsCount; index++) { - workerPool.Revoke(jobs[cancelJobsId[index]], 0); - } - - for (uint8_t index = 0; index < jobs.size(); index++) { - bool isCanceledJob = false; - for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) + TEST(Core_WorkerPool, Check_JobType_Submit_Revoke) + { + WorkerPoolTester workerPool(4, 0, 1); + ::Thunder::Core::WorkerPool::Assign(&workerPool); { - if (index == cancelJobsId[cancelIndex]) { - isCanceledJob = true; - break; - } + WorkerJobTester jobTester(0); + EXPECT_EQ(jobTester.Submit(), true); + jobTester.Revoke(); + workerPool.RunThreadPool(); + EXPECT_EQ(jobTester.WaitForEvent(MaxJobWaitTime * 3), ::Thunder::Core::ERROR_TIMEDOUT); } - if (isCanceledJob == true) { - EXPECT_EQ(workerPool.WaitForJobEvent(jobs[index], MaxJobWaitTime * 3), Core::ERROR_TIMEDOUT); - } else { - EXPECT_EQ(workerPool.WaitForJobEvent(jobs[index], MaxJobWaitTime * 15), Core::ERROR_NONE); + workerPool.Stop(); + ::Thunder::Core::WorkerPool::Assign(nullptr); + } + TEST(Core_WorkerPool, Check_JobType_Schedule) + { + WorkerPoolTester workerPool(4, 0, 1); + ::Thunder::Core::WorkerPool::Assign(&workerPool); + workerPool.RunThreadPool(); + { + WorkerJobTester jobTester(0); + jobTester.Schedule(::Thunder::Core::Time::Now().Add(2000)); + EXPECT_EQ(jobTester.WaitForEvent(MaxJobWaitTime * 3), ::Thunder::Core::ERROR_NONE); } + workerPool.Stop(); + ::Thunder::Core::WorkerPool::Assign(nullptr); } - - for (uint8_t index = 0; index < jobs.size(); index++) { - bool isCanceledJob = false; - for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) + TEST(Core_WorkerPool, Check_JobType_Schedule_Revoke) + { + WorkerPoolTester workerPool(4, 0, 1); + ::Thunder::Core::WorkerPool::Assign(&workerPool); + workerPool.RunThreadPool(); { - if (index == cancelJobsId[cancelIndex]) { - isCanceledJob = true; - break; - } + WorkerJobTester jobTester(0); + jobTester.Schedule(::Thunder::Core::Time::Now().Add(2000)); + usleep(500); + jobTester.Revoke(); + EXPECT_EQ(jobTester.WaitForEvent(MaxJobWaitTime * 4), ::Thunder::Core::ERROR_TIMEDOUT); } - if (isCanceledJob == true) { - EXPECT_EQ(static_cast&>(*jobs[index]).GetStatus(), TestJob::INITIATED); - } else { - EXPECT_EQ(static_cast&>(*jobs[index]).GetStatus(), TestJob::COMPLETED); + workerPool.Stop(); + ::Thunder::Core::WorkerPool::Assign(nullptr); + } + void CheckJobType_Reschedule(const uint16_t scheduleTime, const uint16_t rescheduleTime) + { + WorkerPoolTester workerPool(4, 0, 1); + ::Thunder::Core::WorkerPool::Assign(&workerPool); + workerPool.RunThreadPool(); + { + WorkerJobTester jobTester(0); + jobTester.Schedule(::Thunder::Core::Time::Now().Add(scheduleTime)); + usleep(500); + EXPECT_EQ(jobTester.Reschedule(::Thunder::Core::Time::Now().Add(rescheduleTime)), true); + EXPECT_EQ(jobTester.WaitForEvent(MaxJobWaitTime * 4), ::Thunder::Core::ERROR_NONE); } + workerPool.Stop(); + ::Thunder::Core::WorkerPool::Assign(nullptr); } - - workerPool.Stop(); - - for (auto& job: jobs) { - job.Release(); + TEST(Core_WorkerPool, Check_JobType_Reschedule) + { + CheckJobType_Reschedule(2000, 3000); + CheckJobType_Reschedule(2000, 0); } - jobs.clear(); - Core::WorkerPool::Assign(nullptr); -} -TEST(Core_WorkerPool, Check_ScheduleJobs_SinglePool_SingleJob) -{ - const uint16_t scheduledTimes[] = {2000}; //In milliseconds - CheckWorkerPool_ScheduleJobs(1, 1, 0, 0, nullptr, scheduledTimes); -} -TEST(Core_WorkerPool, DISABLED_Check_ScheduleJobs_SinglePool_SingleJob_ZeroTime) -{ - const uint16_t scheduledTimes[] = {0}; - CheckWorkerPool_ScheduleJobs(1, 1, 0, 0, nullptr, scheduledTimes); -} -TEST(Core_WorkerPool, Check_ScheduleJobs_SinglePool_AdditionalJob) -{ - const uint16_t scheduledTimes[] = {3000, 2000}; - CheckWorkerPool_ScheduleJobs(2, 1, 1, 0, nullptr, scheduledTimes); -} -TEST(Core_WorkerPool, Check_ScheduleJobs_SinglePool_SingleJob_CancelJob) -{ - const uint16_t scheduledTimes[] = {2000}; - const uint8_t job = 0; - CheckWorkerPool_ScheduleJobs(1, 1, 0, 1, &job, scheduledTimes); -} -TEST(Core_WorkerPool, Check_ScheduleJobs_SinglePool_AdditionalJob_CancelJob) -{ - const uint16_t scheduledTimes[] = {2000, 2000}; - const uint8_t job = 0; - CheckWorkerPool_ScheduleJobs(1, 1, 1, 1, &job, scheduledTimes); -} -TEST(Core_WorkerPool, Check_ScheduleJobs_SinglePool_MultipleJobs) -{ - uint8_t maxJobs = 5; - const uint16_t scheduledTimes[] = {2000, 3000, 1000, 2000, 3000}; - CheckWorkerPool_ScheduleJobs(1, maxJobs, 0, 0, nullptr, scheduledTimes); -} -TEST(Core_WorkerPool, DISABLED_Check_ScheduleJobs_SinglePool_MultipleJobs_ZeroTime) -{ - uint8_t maxJobs = 5; - const uint16_t scheduledTimes[5] = {0}; - CheckWorkerPool_ScheduleJobs(1, maxJobs, 0, 0, nullptr, scheduledTimes); -} -TEST(Core_WorkerPool, Check_ScheduleJobs_SinglePool_MultipleJobs_CancelJob) -{ - uint8_t maxJobs = 5; - const uint8_t jobs[] = {1, 2}; - const uint16_t scheduledTimes[] = {2000, 3000, 1000, 2000, 3000}; - CheckWorkerPool_ScheduleJobs(1, maxJobs, 0, sizeof(jobs), jobs, scheduledTimes); -} -TEST(Core_WorkerPool, Check_ScheduleJobs_MultiplePool_MultipleJobs) -{ - uint8_t maxJobs = 5; - const uint16_t scheduledTimes[] = {2000, 3000, 1000, 2000, 3000}; - CheckWorkerPool_ScheduleJobs(5, maxJobs, 0, 0, nullptr, scheduledTimes); - CheckWorkerPool_ScheduleJobs(2, maxJobs, 0, 0, nullptr, scheduledTimes); - CheckWorkerPool_ScheduleJobs(2, 2, 0, 0, nullptr, scheduledTimes); -} -TEST(Core_WorkerPool, Check_ScheduleJobs_MultiplePool_MultipleJobs_ZeroTime) -{ - uint8_t maxJobs = 5; - const uint16_t scheduledTimes[5] = {0}; - CheckWorkerPool_ScheduleJobs(5, maxJobs, 0, 0, nullptr, scheduledTimes); - CheckWorkerPool_ScheduleJobs(2, maxJobs, 0, 0, nullptr, scheduledTimes); - CheckWorkerPool_ScheduleJobs(2, 2, 0, 0, nullptr, scheduledTimes); -} -TEST(Core_WorkerPool, Check_ScheduleJobs_MultiplePool_MultipleJobs_CancelJob) -{ - uint8_t maxJobs = 5; - const uint16_t scheduledTimes[] = {2000, 3000, 1000, 2000, 3000, 2000, 1000, 1000, 3000}; - const uint8_t jobs[] = {0, 4}; - CheckWorkerPool_ScheduleJobs(5, maxJobs, 0, 0, nullptr, scheduledTimes); - CheckWorkerPool_ScheduleJobs(2, maxJobs, 0, 0, nullptr, scheduledTimes); - CheckWorkerPool_ScheduleJobs(5, 5, 0, sizeof(jobs), jobs, scheduledTimes); -} -TEST(Core_WorkerPool, Check_ScheduleJobs_MultiplePool_MultipleJobs_AdditionalJobs) -{ - uint8_t maxJobs = 5; - const uint16_t scheduledTimes[] = {2000, 3000, 1000, 2000, 3000, 1000}; - CheckWorkerPool_ScheduleJobs(5, maxJobs, 0, 0, nullptr, scheduledTimes); - CheckWorkerPool_ScheduleJobs(2, maxJobs, 0, 0, nullptr, scheduledTimes); - CheckWorkerPool_ScheduleJobs(2, 2, 1, 0, nullptr, scheduledTimes); -} -TEST(Core_WorkerPool, Check_ScheduleJobs_MultiplePool_MultipleJobs_AdditionalJobs_CancelJob) -{ - uint8_t maxJobs = 5; - const uint16_t scheduledTimes[] = {2000, 3000, 1000, 2000, 3000, 1000, 1000, 2000, 3000}; - const uint8_t jobs[] = {3, 5}; - CheckWorkerPool_ScheduleJobs(5, maxJobs, 0, 0, nullptr, scheduledTimes); - CheckWorkerPool_ScheduleJobs(2, maxJobs, 0, 0, nullptr, scheduledTimes); - CheckWorkerPool_ScheduleJobs(5, 5, 4, sizeof(jobs), jobs, scheduledTimes); -} -void CheckWorkerPool_RescheduleJobs(const uint8_t threadCount, const uint8_t queueSize, const uint8_t additionalJobs, const uint8_t cancelJobsCount, const uint8_t* cancelJobsId, const uint16_t scheduledTimes[], const uint16_t rescheduledTimes[]) -{ - WorkerPoolTester workerPool(threadCount, 0, queueSize); - Core::WorkerPool::Assign(&workerPool); - workerPool.RunThreadPool(); - - std::vector> jobs; - // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs - for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { - jobs.push_back(Core::ProxyType(Core::ProxyType>::Create(workerPool, TestJob::INITIATED, 500, false, true))); - } - - for (uint8_t i = 0; i < queueSize; ++i) { - EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); - workerPool.ScheduleJobs(jobs[i], scheduledTimes[i]); - } - for (uint8_t i = queueSize; i < jobs.size(); ++i) { - EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); - workerPool.ScheduleJobs(jobs[i], scheduledTimes[i]); - } - - for (uint8_t i = 0; i < jobs.size(); ++i) { - workerPool.RescheduleJobs(jobs[i], rescheduledTimes[i]); - } - for (uint8_t index = 0; index < cancelJobsCount; index++) { - workerPool.Revoke(jobs[cancelJobsId[index]], 0); - } - - for (uint8_t index = 0; index < jobs.size(); index++) { - bool isCanceledJob = false; - for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) + TEST(Core_WorkerPool, Check_JobType_Reschedule_Revoke) + { + WorkerPoolTester workerPool(4, 0, 1); + ::Thunder::Core::WorkerPool::Assign(&workerPool); + workerPool.RunThreadPool(); { - if (index == cancelJobsId[cancelIndex]) { - isCanceledJob = true; - break; - } - } - if (isCanceledJob == true) { - EXPECT_EQ(workerPool.WaitForJobEvent(jobs[index], MaxJobWaitTime * 3), Core::ERROR_TIMEDOUT); - } else { - EXPECT_EQ(workerPool.WaitForJobEvent(jobs[index], MaxJobWaitTime * 15), Core::ERROR_NONE); + WorkerJobTester jobTester(0); + jobTester.Schedule(::Thunder::Core::Time::Now().Add(2000)); + usleep(500); + jobTester.Schedule(::Thunder::Core::Time::Now().Add(3000)); + usleep(500); + jobTester.Revoke(); + EXPECT_EQ(jobTester.WaitForEvent(MaxJobWaitTime * 4), ::Thunder::Core::ERROR_TIMEDOUT); } + workerPool.Stop(); + ::Thunder::Core::WorkerPool::Assign(nullptr); } - - for (uint8_t index = 0; index < jobs.size(); index++) { - bool isCanceledJob = false; - for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) + void CheckJobType_RescheduleJobs(const uint8_t threadCount, const uint8_t queueSize, const uint8_t additionalJobs, const uint8_t cancelJobsCount, const uint8_t* cancelJobsId, const uint16_t scheduledTimes[], const uint16_t rescheduledTimes[]) + { + WorkerPoolTester workerPool(threadCount, 0, queueSize); + ::Thunder::Core::WorkerPool::Assign(&workerPool); + workerPool.RunThreadPool(); { - if (index == cancelJobsId[cancelIndex]) { - isCanceledJob = true; - break; + std::vector<::Thunder::Core::ProxyType> jobs; + // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs + for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { + jobs.push_back(::Thunder::Core::ProxyType(::Thunder::Core::ProxyType::Create(0))); + } + for (uint8_t i = 0; i < jobs.size(); ++i) { + EXPECT_EQ(jobs[i]->IsIdle(), true); + } + + for (uint8_t i = 0; i < jobs.size(); ++i) { + jobs[i]->Schedule(::Thunder::Core::Time::Now().Add(scheduledTimes[i])); + } + + for (uint8_t i = 0; i < jobs.size(); ++i) { + EXPECT_EQ(jobs[i]->Reschedule(::Thunder::Core::Time::Now().Add(rescheduledTimes[i])), true); + } + for (uint8_t i = 0; i < jobs.size(); ++i) { + EXPECT_EQ(jobs[i]->IsIdle(), false); + } + + for (uint8_t i = 0; i < cancelJobsCount; i++) { + jobs[cancelJobsId[i]]->Revoke(); + EXPECT_EQ(jobs[cancelJobsId[i]]->IsIdle(), true); + } + + for (uint8_t index = 0; index < jobs.size(); index++) { + bool isCanceledJob = false; + for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) + { + if (index == cancelJobsId[cancelIndex]) { + isCanceledJob = true; + break; + } + } + if (isCanceledJob == true) { + EXPECT_EQ(jobs[index]->WaitForEvent(MaxJobWaitTime * 3), ::Thunder::Core::ERROR_TIMEDOUT); + } else { + EXPECT_EQ(jobs[index]->WaitForEvent(MaxJobWaitTime * 15), ::Thunder::Core::ERROR_NONE); + usleep(200); + } + + usleep(200); + EXPECT_EQ(jobs[index]->IsIdle(), true); } + for (auto& job: jobs) { + job.Release(); + } + jobs.clear(); } - if (isCanceledJob == true) { - EXPECT_EQ(static_cast&>(*jobs[index]).GetStatus(), TestJob::INITIATED); - } else { - EXPECT_EQ(static_cast&>(*jobs[index]).GetStatus(), TestJob::COMPLETED); - } - } - - workerPool.Stop(); - - jobs.clear(); - Core::WorkerPool::Assign(nullptr); -} -TEST(Core_WorkerPool, Check_RescheduleJobs_SinglePool_SingleJob) -{ - const uint16_t scheduledTimes[] = {1000}; - const uint16_t rescheduledTimes[] = {2000}; - CheckWorkerPool_RescheduleJobs(1, 1, 0, 0, nullptr, scheduledTimes, rescheduledTimes); -} -TEST(Core_WorkerPool, Check_RescheduleJobs_SinglePool_SingleJob_ZeroTime) -{ - const uint16_t scheduledTimes[] = {1000}; - const uint16_t rescheduledTimes[] = {0}; - CheckWorkerPool_RescheduleJobs(1, 1, 0, 0, nullptr, scheduledTimes, rescheduledTimes); -} -TEST(Core_WorkerPool, Check_RescheduleJobs_SinglePool_SingleJob_AdditionalJobs) -{ - const uint16_t scheduledTimes[] = {1000, 2000}; - const uint16_t rescheduledTimes[] = {2000, 1000}; - CheckWorkerPool_RescheduleJobs(1, 1, 1, 0, nullptr, scheduledTimes, rescheduledTimes); -} -TEST(Core_WorkerPool, Check_RescheduleJobs_SinglePool_SingleJob_CancelJob) -{ - uint16_t scheduledTimes[] = {1000}; - const uint16_t rescheduledTimes[] = {2000}; - const uint8_t job = 0; - CheckWorkerPool_RescheduleJobs(1, 1, 0, 1, &job, scheduledTimes, rescheduledTimes); - scheduledTimes[0] = 4000; - CheckWorkerPool_RescheduleJobs(1, 1, 0, 1, &job, scheduledTimes, rescheduledTimes); -} -TEST(Core_WorkerPool, Check_RescheduleJobs_SinglePool_AdditionalJob_CancelJob) -{ - const uint16_t scheduledTimes[] = {4000, 1000}; - const uint16_t rescheduledTimes[] = {3000, 2000}; - const uint8_t job = 1; - CheckWorkerPool_RescheduleJobs(1, 1, 1, 1, &job, scheduledTimes, rescheduledTimes); -} -TEST(Core_WorkerPool, Check_RescheduleJobs_SinglePool_MultipleJobs) -{ - const uint16_t scheduledTimes[] = {1000, 2000, 3000, 2000, 1000}; - const uint16_t rescheduledTimes[] = {2000, 2000, 1000, 2000, 3000}; - CheckWorkerPool_RescheduleJobs(1, 5, 0, 0, nullptr, scheduledTimes, rescheduledTimes); -} -TEST(Core_WorkerPool, Check_RescheduleJobs_SinglePool_MultipleJobs_ZeroTime) -{ - const uint16_t scheduledTimes[] = {1000, 2000, 3000, 2000, 1000}; - const uint16_t rescheduledTimes[5] = {0}; - CheckWorkerPool_RescheduleJobs(1, 5, 0, 0, nullptr, scheduledTimes, rescheduledTimes); -} -TEST(Core_WorkerPool, Check_RescheduleJobs_SinglePool_MultipleJobs_AdditionalJobs) -{ - const uint16_t scheduledTimes[] = {5000, 2000, 6000, 1000, 2000, 3000, 1000, 1000, 2000, 4000}; - const uint16_t rescheduledTimes[] = {2000, 1000, 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000}; - - CheckWorkerPool_RescheduleJobs(1, 5, 2, 0, nullptr, scheduledTimes, rescheduledTimes); - CheckWorkerPool_RescheduleJobs(1, 5, 5, 0, nullptr, scheduledTimes, rescheduledTimes); -} -TEST(Core_WorkerPool, Check_RescheduleJobs_SinglePool_MultipleJobs_CancelJob) -{ - const uint16_t scheduledTimes[] = {1000, 2000, 3000, 2000, 1000}; - const uint16_t rescheduledTimes[] = {2000, 2000, 1000, 2000, 3000}; - - const uint8_t jobs[] = {1, 4}; - CheckWorkerPool_RescheduleJobs(1, 5, 0, sizeof(jobs), jobs, scheduledTimes, rescheduledTimes); -} -TEST(Core_WorkerPool, Check_RescheduleJobs_SinglePool_MultipleJobs_AdditionalJob_CancelJob) -{ - const uint16_t scheduledTimes[] = {5000, 2000, 6000, 1000, 2000, 3000, 1000, 1000, 2000, 4000}; - const uint16_t rescheduledTimes[] = {2000, 1000, 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000}; - - const uint8_t jobs[] = {2, 6}; - CheckWorkerPool_RescheduleJobs(1, 5, 5, sizeof(jobs), jobs, scheduledTimes, rescheduledTimes); -} -TEST(Core_WorkerPool, Check_RescheduleJobs_MultiplePool_MultipleJobs) -{ - const uint16_t scheduledTimes[] = {1000, 2000, 3000, 2000, 1000}; - const uint16_t rescheduledTimes[] = {2000, 2000, 1000, 2000, 3000}; - CheckWorkerPool_RescheduleJobs(1, 5, 0, 0, nullptr, scheduledTimes, rescheduledTimes); -} -TEST(Core_WorkerPool, Check_RescheduleJobs_MultiplePool_MultipleJobs_ZeroTime) -{ - const uint16_t scheduledTimes[] = {1000, 2000, 3000, 2000, 1000}; - const uint16_t rescheduledTimes[5] = {0}; - CheckWorkerPool_RescheduleJobs(1, 5, 0, 0, nullptr, scheduledTimes, rescheduledTimes); -} -TEST(Core_WorkerPool, Check_RescheduleJobs_MultiplePool_MultipleJobs_AdditionalJobs) -{ - const uint16_t scheduledTimes[] = {5000, 2000, 6000, 1000, 2000, 3000, 1000, 1000, 2000, 4000}; - const uint16_t rescheduledTimes[] = {2000, 1000, 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000}; - CheckWorkerPool_RescheduleJobs(1, 5, 2, 0, nullptr, scheduledTimes, rescheduledTimes); - CheckWorkerPool_RescheduleJobs(1, 5, 5, 0, nullptr, scheduledTimes, rescheduledTimes); -} -TEST(Core_WorkerPool, Check_RescheduleJobs_MultiplePool_MultipleJobs_CancelJob) -{ - const uint16_t scheduledTimes[] = {1000, 2000, 3000, 2000, 1000}; - const uint16_t rescheduledTimes[] = {2000, 2000, 1000, 2000, 3000}; - - const uint8_t jobs[] = {1, 4}; - CheckWorkerPool_RescheduleJobs(1, 5, 0, sizeof(jobs), jobs, scheduledTimes, rescheduledTimes); -} -TEST(Core_WorkerPool, Check_RescheduleJobs_MultiplePool_MultipleJobs_AdditionalJob_CancelJob) -{ - const uint16_t scheduledTimes[] = {5000, 2000, 6000, 1000, 2000, 3000, 1000, 1000, 2000, 4000}; - const uint16_t rescheduledTimes[] = {2000, 1000, 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000}; - - const uint8_t jobs[] = {3, 5}; - CheckWorkerPool_RescheduleJobs(5, 5, 2, sizeof(jobs), jobs, scheduledTimes, rescheduledTimes); - CheckWorkerPool_RescheduleJobs(5, 5, 5, sizeof(jobs), jobs, scheduledTimes, rescheduledTimes); -} -void CheckMetaData(const uint8_t pending, const uint8_t occupation, const uint8_t expectedRuns) -{ - const IWorkerPool::Metadata& metaData = IWorkerPool::Instance().Snapshot(); - - EXPECT_EQ(metaData.Pending.size(), pending); // Whatever is in the ThreadPool::_queue is considered pending - - uint16_t totalRuns = 0, totalOccupation = 0; - for (uint8_t index = 0; index < metaData.Slots; index++) { - totalRuns += metaData.Slot[index].Runs; - totalOccupation += metaData.Slot[index].Job.IsSet(); - } - EXPECT_EQ(totalRuns, expectedRuns); - EXPECT_EQ(totalOccupation, occupation); -} -void CheckWorkerPool_MetaData(uint8_t threadCount, uint8_t queueSize, uint8_t additionalJobs) -{ - WorkerPoolTester workerPool(threadCount, 0, queueSize); - Core::WorkerPool::Assign(&workerPool); - - std::vector> jobs; - // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs - for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { - jobs.push_back(Core::ProxyType(Core::ProxyType>::Create(workerPool, TestJob::INITIATED, 100))); - } - - for (uint8_t i = 0; i < queueSize; ++i) { - EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); - workerPool.SubmitUsingSelfWorker(jobs[i]); - } - for (uint8_t i = queueSize; i < jobs.size(); ++i) { - EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); - workerPool.SubmitUsingExternalWorker(jobs[i]); - } - - CheckMetaData(queueSize, 1, 0); - workerPool.RunThreadPool(); - - usleep(MaxJobWaitTime); - for (auto& job: jobs) { - EXPECT_EQ(workerPool.WaitForJobEvent(job, MaxJobWaitTime * 3), Core::ERROR_NONE); - } - - for (auto& job: jobs) { - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); - } - workerPool.Stop(); - CheckMetaData(queueSize, 1, queueSize + additionalJobs); - for (auto& job: jobs) { - job.Release(); + workerPool.Stop(); + ::Thunder::Core::WorkerPool::Assign(nullptr); } - jobs.clear(); - Core::WorkerPool::Assign(nullptr); -} -TEST(Core_WorkerPool, Check_MetaData_SinglePool_SingleJob) -{ - CheckWorkerPool_MetaData(1, 1, 0); -} -TEST(Core_WorkerPool, Check_MetaData_SinglePool_SingleJob_AdditionalJobs) -{ - CheckWorkerPool_MetaData(1, 1, 2); -} -TEST(Core_WorkerPool, Check_MetaData_SinglePool_MultipleJobs) -{ - CheckWorkerPool_MetaData(1, 5, 0); -} -TEST(Core_WorkerPool, Check_MetaData_SinglePool_MultipleJobs_AdditionalJobs) -{ - CheckWorkerPool_MetaData(1, 5, 2); -} -TEST(Core_WorkerPool, Check_MetaData_MultiplePool_MultipleJobs) -{ - CheckWorkerPool_MetaData(5, 5, 0); -} -TEST(Core_WorkerPool, Check_MetaData_MultiplePool_MultipleJobs_AdditionalJobs) -{ - CheckWorkerPool_MetaData(5, 5, 5); -} -void CheckWorkerPool_Ids(uint8_t threadCount, uint8_t queueSize, uint8_t additionalJobs) -{ - WorkerPoolTester workerPool(threadCount, 0, queueSize); - Core::WorkerPool::Assign(&workerPool); - workerPool.RunThreadPool(); - - std::vector> jobs; - // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs - for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { - jobs.push_back(Core::ProxyType(Core::ProxyType>::Create(workerPool, TestJob::INITIATED, 100, false, false, true))); - } - - for (uint8_t i = 0; i < queueSize; ++i) { - EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); - workerPool.SubmitUsingSelfWorker(jobs[i]); - } - for (uint8_t i = queueSize; i < jobs.size(); ++i) { - EXPECT_EQ(static_cast&>(*jobs[i]).GetStatus(), TestJob::INITIATED); - workerPool.SubmitUsingExternalWorker(jobs[i]); - } - - for (auto& job: jobs) { - EXPECT_EQ(workerPool.WaitForJobEvent(job, MaxJobWaitTime * 3), Core::ERROR_NONE); - } - - for (auto& job: jobs) { - EXPECT_EQ(static_cast&>(*job).GetStatus(), TestJob::COMPLETED); + TEST(Core_WorkerPool, Check_JobType_Reschedule_MultipleJobs) + { + const uint16_t scheduledTimes[] = {5000, 2000, 6000, 1000, 2000, 3000, 1000, 1000, 2000, 4000}; + const uint16_t rescheduledTimes[] = {2000, 1000, 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000}; + + CheckJobType_RescheduleJobs(5, 5, 2, 0, nullptr, scheduledTimes, rescheduledTimes); } + TEST(Core_WorkerPool, Check_JobType_Reschedule_MultipleJobs_CancelJobs) + { + const uint16_t scheduledTimes[] = {5000, 2000, 6000, 1000, 2000, 3000, 1000, 1000, 2000, 4000}; + const uint16_t rescheduledTimes[] = {2000, 1000, 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000}; + const uint8_t jobs[] = {0, 2}; - workerPool.Stop(); - for (auto& job: jobs) { - job.Release(); + CheckJobType_RescheduleJobs(5, 5, 2, sizeof(jobs), jobs, scheduledTimes, rescheduledTimes); } - jobs.clear(); - Core::WorkerPool::Assign(nullptr); -} -TEST(Core_WorkerPool, Check_Ids_SinglePool_SingleJob) -{ - CheckWorkerPool_Ids(1, 1, 0); -} -TEST(Core_WorkerPool, Check_Ids_SinglePool_SingleJob_AdditionalJobs) -{ - CheckWorkerPool_Ids(1, 1, 2); -} -TEST(Core_WorkerPool, Check_Ids_SinglePool_MultipleJobs) -{ - CheckWorkerPool_Ids(1, 5, 0); -} -TEST(Core_WorkerPool, Check_Ids_SinglePool_MultipleJobs_AdditionalJobs) -{ - CheckWorkerPool_Ids(1, 5, 2); -} -TEST(Core_WorkerPool, Check_Ids_MultiplePool_MultipleJobs) -{ - CheckWorkerPool_Ids(5, 5, 0); -} -TEST(Core_WorkerPool, Check_Ids_MultiplePool_MultipleJobs_AdditionalJobs) -{ - CheckWorkerPool_Ids(5, 5, 5); -} - -class WorkerJobTester : public EventControl { -public: - WorkerJobTester(const WorkerJobTester&) = delete; - WorkerJobTester& operator=(const WorkerJobTester&) = delete; - - WorkerJobTester() = delete; - - WorkerJobTester(uint32_t waitTime, bool waitForCaller = false) - : _waitTime(waitTime) - , _expectedTime() - , _waitForCaller(waitForCaller) - , _job(*this) - { - } - ~WorkerJobTester() = default; - - bool Submit() - { - _expectedTime = Core::Time::Now(); - return _job.Submit(); - } - bool Schedule(const Core::Time& time) - { - _expectedTime = time; - return _job.Reschedule(time); - } - bool Reschedule(const Core::Time& time) - { - _expectedTime = time; - return _job.Reschedule(time); - } - void Revoke() - { - _job.Revoke(); - } - bool IsIdle() - { - return _job.IsIdle(); - } - -public: - void Dispatch() - { - Core::Time invokedTime = Core::Time::Now(); - WorkerPoolTester::CheckScheduledTime(_expectedTime, invokedTime, 0); - Notify(); - usleep(_waitTime * 2); - if (_waitForCaller) { - WaitForEvent(_waitTime * 10); - Reset(); - } - } - -private: - uint32_t _waitTime; - Core::Time _expectedTime; - bool _waitForCaller; - Core::WorkerPool::JobType _job; -}; - -TEST(Core_WorkerPool, Check_JobType_Submit) -{ - WorkerPoolTester workerPool(1, 0, 1); - Core::WorkerPool::Assign(&workerPool); - workerPool.RunThreadPool(); - { - WorkerJobTester jobTester(0); - EXPECT_EQ(jobTester.Submit(), true); - EXPECT_EQ(jobTester.WaitForEvent(MaxJobWaitTime * 3), Core::ERROR_NONE); - } - workerPool.Stop(); - Core::WorkerPool::Assign(nullptr); -} -TEST(Core_WorkerPool, Check_JobType_Submit_Revoke) -{ - WorkerPoolTester workerPool(4, 0, 1); - Core::WorkerPool::Assign(&workerPool); - { - WorkerJobTester jobTester(0); - EXPECT_EQ(jobTester.Submit(), true); - jobTester.Revoke(); + TEST(Core_WorkerPool, Check_JobType_Reschedule_WhileRunning) + { + WorkerPoolTester workerPool(4, 0, 1); + ::Thunder::Core::WorkerPool::Assign(&workerPool); workerPool.RunThreadPool(); - EXPECT_EQ(jobTester.WaitForEvent(MaxJobWaitTime * 3), Core::ERROR_TIMEDOUT); - } - workerPool.Stop(); - Core::WorkerPool::Assign(nullptr); -} -TEST(Core_WorkerPool, Check_JobType_Schedule) -{ - WorkerPoolTester workerPool(4, 0, 1); - Core::WorkerPool::Assign(&workerPool); - workerPool.RunThreadPool(); - { - WorkerJobTester jobTester(0); - jobTester.Schedule(Core::Time::Now().Add(2000)); - EXPECT_EQ(jobTester.WaitForEvent(MaxJobWaitTime * 3), Core::ERROR_NONE); - } - workerPool.Stop(); - Core::WorkerPool::Assign(nullptr); -} -TEST(Core_WorkerPool, Check_JobType_Schedule_Revoke) -{ - WorkerPoolTester workerPool(4, 0, 1); - Core::WorkerPool::Assign(&workerPool); - workerPool.RunThreadPool(); - { - WorkerJobTester jobTester(0); - jobTester.Schedule(Core::Time::Now().Add(2000)); - usleep(500); - jobTester.Revoke(); - EXPECT_EQ(jobTester.WaitForEvent(MaxJobWaitTime * 4), Core::ERROR_TIMEDOUT); - } - workerPool.Stop(); - Core::WorkerPool::Assign(nullptr); -} -void CheckJobType_Reschedule(const uint16_t scheduleTime, const uint16_t rescheduleTime) -{ - WorkerPoolTester workerPool(4, 0, 1); - Core::WorkerPool::Assign(&workerPool); - workerPool.RunThreadPool(); - { - WorkerJobTester jobTester(0); - jobTester.Schedule(Core::Time::Now().Add(scheduleTime)); - usleep(500); - EXPECT_EQ(jobTester.Reschedule(Core::Time::Now().Add(rescheduleTime)), true); - EXPECT_EQ(jobTester.WaitForEvent(MaxJobWaitTime * 4), Core::ERROR_NONE); - } - workerPool.Stop(); - Core::WorkerPool::Assign(nullptr); -} -TEST(Core_WorkerPool, Check_JobType_Reschedule) -{ - CheckJobType_Reschedule(2000, 3000); - CheckJobType_Reschedule(2000, 0); -} -TEST(Core_WorkerPool, Check_JobType_Reschedule_Revoke) -{ - WorkerPoolTester workerPool(4, 0, 1); - Core::WorkerPool::Assign(&workerPool); - workerPool.RunThreadPool(); - { - WorkerJobTester jobTester(0); - jobTester.Schedule(Core::Time::Now().Add(2000)); - usleep(500); - jobTester.Schedule(Core::Time::Now().Add(3000)); - usleep(500); - jobTester.Revoke(); - EXPECT_EQ(jobTester.WaitForEvent(MaxJobWaitTime * 4), Core::ERROR_TIMEDOUT); - } - workerPool.Stop(); - Core::WorkerPool::Assign(nullptr); -} -void CheckJobType_RescheduleJobs(const uint8_t threadCount, const uint8_t queueSize, const uint8_t additionalJobs, const uint8_t cancelJobsCount, const uint8_t* cancelJobsId, const uint16_t scheduledTimes[], const uint16_t rescheduledTimes[]) -{ - WorkerPoolTester workerPool(threadCount, 0, queueSize); - Core::WorkerPool::Assign(&workerPool); - workerPool.RunThreadPool(); - { - std::vector> jobs; - // Create Jobs with more than Queue size. i.e, queueSize + additionalJobs - for (uint8_t i = 0; i < queueSize + additionalJobs; ++i) { - jobs.push_back(Core::ProxyType(Core::ProxyType::Create(0))); + { + WorkerJobTester jobTester(1000); + jobTester.Schedule(::Thunder::Core::Time::Now().Add(0)); + EXPECT_EQ(jobTester.WaitForEvent(MaxJobWaitTime * 2), ::Thunder::Core::ERROR_NONE); + jobTester.Reset(); + EXPECT_EQ(jobTester.Reschedule(::Thunder::Core::Time::Now().Add(1000)), false); + jobTester.Notify(); + EXPECT_EQ(jobTester.WaitForEvent(MaxJobWaitTime * 2), ::Thunder::Core::ERROR_NONE); } - for (uint8_t i = 0; i < jobs.size(); ++i) { - EXPECT_EQ(jobs[i]->IsIdle(), true); + workerPool.Stop(); + ::Thunder::Core::WorkerPool::Assign(nullptr); + } + + class Job { + public: + Job(const Job&) = delete; + Job& operator=(const Job&) = delete; + Job(const uint16_t sleepTimeInSeconds) + : _sleepTimeInMilliSeconds(sleepTimeInSeconds * 1000) { } + ~Job() = default; - for (uint8_t i = 0; i < jobs.size(); ++i) { - jobs[i]->Schedule(Core::Time::Now().Add(scheduledTimes[i])); + public: + void Dispatch() { + _instancesActive++; + + if (_instancesActive > 1) { + printf("Ooopsie daisy, that is unexpected, it seems there are multiples of me running, thats not according to the spec !!!!\n"); + } + EXPECT_FALSE(_instancesActive > 1); + SleepMs(_sleepTimeInMilliSeconds); // Sleep for _sleepTimeInMilliSeconds + _instancesActive--; } - for (uint8_t i = 0; i < jobs.size(); ++i) { - EXPECT_EQ(jobs[i]->Reschedule(Core::Time::Now().Add(rescheduledTimes[i])), true); + private: + uint32_t _sleepTimeInMilliSeconds; + static std::atomic _instancesActive; + }; + + /* static */ std::atomic Job::_instancesActive; + + class Trigger : public EventControl { + public: + Trigger(const Trigger&) = delete; + Trigger& operator=(const Trigger&) = delete; + Trigger(const uint16_t intervalInSecond, const uint16_t sleepTimeInSeconds) + : _cycles(0) + , _intervalInMilliSeconds(intervalInSecond * 1000) + , _triggerJob(*this) + , _decoupledJob(sleepTimeInSeconds) + { } - for (uint8_t i = 0; i < jobs.size(); ++i) { - EXPECT_EQ(jobs[i]->IsIdle(), false); + ~Trigger() { + Stop(); + _decoupledJob.Revoke(); } - for (uint8_t i = 0; i < cancelJobsCount; i++) { - jobs[cancelJobsId[i]]->Revoke(); - EXPECT_EQ(jobs[cancelJobsId[i]]->IsIdle(), true); + public: + void Start(const uint8_t cycles) { + _cycles = cycles; + _triggerJob.Reschedule(::Thunder::Core::Time::Now().Add(_intervalInMilliSeconds)); } - for (uint8_t index = 0; index < jobs.size(); index++) { - bool isCanceledJob = false; - for (uint8_t cancelIndex = 0; cancelIndex < cancelJobsCount; cancelIndex++) - { - if (index == cancelJobsId[cancelIndex]) { - isCanceledJob = true; - break; - } - } - if (isCanceledJob == true) { - EXPECT_EQ(jobs[index]->WaitForEvent(MaxJobWaitTime * 3), Core::ERROR_TIMEDOUT); - } else { - EXPECT_EQ(jobs[index]->WaitForEvent(MaxJobWaitTime * 15), Core::ERROR_NONE); - usleep(200); - } + uint8_t Pending() + { + return _cycles; + } - usleep(200); - EXPECT_EQ(jobs[index]->IsIdle(), true); + void Stop () { + _triggerJob.Revoke(); } - for (auto& job: jobs) { - job.Release(); + void Dispatch() { + // If the TriggerJob is scheduled due to the fact that the _intervalInMilliSeconds time + // has elapsed, it's onluy purpose is to submit the _decoupledJob and reschedule itself + // to submit this job again after it the _intervalInMilliSeconds has elepased again from + // now! + + // The _decoupledJob is of type ::Thunder::Core::WorkerPool::JobType, which, according to the + // design will be decoupled from this thread and run the dispatch (of Job) on another + // thread. To avoid starvation, the Job will obnnly be ran once. If it is already + // running (Active) it will be scheduled (state changed) to be scheduled for rerun after + // it completed. + _decoupledJob.Submit(); + + // Reschedule our selves to submit another run for the Job in _intervalInMilliSeconds + // from now.. + if (--_cycles != 0) { + _triggerJob.Reschedule(::Thunder::Core::Time::Now().Add(_intervalInMilliSeconds)); + } else { + Notify(); + } } - jobs.clear(); - } - workerPool.Stop(); - Core::WorkerPool::Assign(nullptr); -} -TEST(Core_WorkerPool, Check_JobType_Reschedule_MultipleJobs) -{ - const uint16_t scheduledTimes[] = {5000, 2000, 6000, 1000, 2000, 3000, 1000, 1000, 2000, 4000}; - const uint16_t rescheduledTimes[] = {2000, 1000, 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000}; - - CheckJobType_RescheduleJobs(5, 5, 2, 0, nullptr, scheduledTimes, rescheduledTimes); -} -TEST(Core_WorkerPool, Check_JobType_Reschedule_MultipleJobs_CancelJobs) -{ - const uint16_t scheduledTimes[] = {5000, 2000, 6000, 1000, 2000, 3000, 1000, 1000, 2000, 4000}; - const uint16_t rescheduledTimes[] = {2000, 1000, 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000}; - const uint8_t jobs[] = {0, 2}; - - CheckJobType_RescheduleJobs(5, 5, 2, sizeof(jobs), jobs, scheduledTimes, rescheduledTimes); -} -TEST(Core_WorkerPool, Check_JobType_Reschedule_WhileRunning) -{ - WorkerPoolTester workerPool(4, 0, 1); - Core::WorkerPool::Assign(&workerPool); - workerPool.RunThreadPool(); - { - WorkerJobTester jobTester(1000); - jobTester.Schedule(Core::Time::Now().Add(0)); - EXPECT_EQ(jobTester.WaitForEvent(MaxJobWaitTime * 2), Core::ERROR_NONE); - jobTester.Reset(); - EXPECT_EQ(jobTester.Reschedule(Core::Time::Now().Add(1000)), false); - jobTester.Notify(); - EXPECT_EQ(jobTester.WaitForEvent(MaxJobWaitTime * 2), Core::ERROR_NONE); - } - workerPool.Stop(); - Core::WorkerPool::Assign(nullptr); -} - -class Job { -public: - Job(const Job&) = delete; - Job& operator=(const Job&) = delete; - Job(const uint16_t sleepTimeInSeconds) - : _sleepTimeInMilliSeconds(sleepTimeInSeconds * 1000) { - } - ~Job() = default; - -public: - void Dispatch() { - _instancesActive++; - - if (_instancesActive > 1) { - printf("Ooopsie daisy, that is unexpected, it seems there are multiples of me running, thats not according to the spec !!!!\n"); - } - EXPECT_FALSE(_instancesActive > 1); - SleepMs(_sleepTimeInMilliSeconds); // Sleep for _sleepTimeInMilliSeconds - _instancesActive--; - } - -private: - uint32_t _sleepTimeInMilliSeconds; - static std::atomic _instancesActive; -}; - -/* static */ std::atomic Job::_instancesActive; - -class Trigger : public EventControl { -public: - Trigger(const Trigger&) = delete; - Trigger& operator=(const Trigger&) = delete; - Trigger(const uint16_t intervalInSecond, const uint16_t sleepTimeInSeconds) - : _cycles(0) - , _intervalInMilliSeconds(intervalInSecond * 1000) - , _triggerJob(*this) - , _decoupledJob(sleepTimeInSeconds) - { - } - ~Trigger() { - Stop(); - _decoupledJob.Revoke(); - } - -public: - void Start(const uint8_t cycles) { - _cycles = cycles; - _triggerJob.Reschedule(Core::Time::Now().Add(_intervalInMilliSeconds)); - } - - uint8_t Pending() - { - return _cycles; - } - - void Stop () { - _triggerJob.Revoke(); - } - void Dispatch() { - // If the TriggerJob is scheduled due to the fact that the _intervalInMilliSeconds time - // has elapsed, it's onluy purpose is to submit the _decoupledJob and reschedule itself - // to submit this job again after it the _intervalInMilliSeconds has elepased again from - // now! - - // The _decoupledJob is of type Core::WorkerPool::JobType, which, according to the - // design will be decoupled from this thread and run the dispatch (of Job) on another - // thread. To avoid starvation, the Job will obnnly be ran once. If it is already - // running (Active) it will be scheduled (state changed) to be scheduled for rerun after - // it completed. - _decoupledJob.Submit(); - - // Reschedule our selves to submit another run for the Job in _intervalInMilliSeconds - // from now.. - if (--_cycles != 0) { - _triggerJob.Reschedule(Core::Time::Now().Add(_intervalInMilliSeconds)); - } else { - Notify(); + private: + uint8_t _cycles; + uint32_t _intervalInMilliSeconds; + ::Thunder::Core::WorkerPool::JobType _triggerJob; + ::Thunder::Core::WorkerPool::JobType _decoupledJob; + }; + void CheckWorkerPool_ReschduledTimedJob(const uint8_t threadCount, const uint8_t queueSize, const uint16_t timedWait, const uint16_t jobWait, const uint8_t times) + { + WorkerPoolTester workerPool(threadCount, 0, queueSize); + ::Thunder::Core::WorkerPool::Assign(&workerPool); + workerPool.RunThreadPool(); + { + // Schedule the Job every timedWait (eg: 10 Seconds) to run once.. + // The Job takes JobWait (eg: 40 Seconds) to run + Trigger triggerJob (timedWait /* param1 */, jobWait /* param2 */); + + // Submit the Job N times (so after N times * timedWait (eg: 5 x 10 Seconds) all scheduled submits occured... + triggerJob.Start(times /* param 3 */); + + // Now wait for 10 (first time to drop the first time the job param1) + 5 (number of submits param3) * 40 seconds (param2, duration of the job) for this to complete. + + // There is an issue if param1 < param2, as with the old code, the job would run multiple times the Job::Dispatch in parallel + // which is not according to spec. + + // with the old code, the following timeing is applicable: + // Assuming there are 5 threads in the threadpool: + // Total time is 5 * 10 + 40 seconds. The Job would be running 5 times spread over all available threads which is a total of 90 second and the job would have been ran 5 times + // if the thread count < 3 the duration will be longer as the last submit (after 50 seconds) still has to wait for the 3 submit to complete. + // if the thread count >= 2 the line "Ooopsie daisy, that is unexpected, it seems there are multiples of me running, thats not according to the spec !!!!\n" will be observed + // which indicates the flas in the current workerpool setup. + + EXPECT_EQ(triggerJob.WaitForEvent((timedWait + (times * jobWait)) * 1000), ::Thunder::Core::ERROR_NONE); + EXPECT_EQ(triggerJob.Pending(), 0u); + // In the new code the Job will never be running with more than one instance so the line: "Ooopsie daisy, that is unexpected, it seems there are multiples of me running, thats + // not according to the spec !!!!\n" should never be observed. + // However the job will not be ran 5 times as there are 3 schedule overruns due to the fact that the Job is still running when the next submit ocures. SO the job wll only run + // 3 times and it will take 10 + 3* 40 seconds to complete. } + ::Thunder::Core::WorkerPool::Assign(nullptr); + } + TEST(Core_WorkerPool, Check_ReschduledTimedJob_SinglePool) + { + CheckWorkerPool_ReschduledTimedJob(1, 5, 5, 10, 5); + } + TEST(Core_WorkerPool, Check_ReschduledTimedJob_MultiplePool) + { + CheckWorkerPool_ReschduledTimedJob(2, 5, 5, 10, 5); + CheckWorkerPool_ReschduledTimedJob(3, 5, 5, 10, 5); } -private: - uint8_t _cycles; - uint32_t _intervalInMilliSeconds; - Core::WorkerPool::JobType _triggerJob; - Core::WorkerPool::JobType _decoupledJob; -}; -void CheckWorkerPool_ReschduledTimedJob(const uint8_t threadCount, const uint8_t queueSize, const uint16_t timedWait, const uint16_t jobWait, const uint8_t times) -{ - WorkerPoolTester workerPool(threadCount, 0, queueSize); - Core::WorkerPool::Assign(&workerPool); - workerPool.RunThreadPool(); - { - // Schedule the Job every timedWait (eg: 10 Seconds) to run once.. - // The Job takes JobWait (eg: 40 Seconds) to run - Trigger triggerJob (timedWait /* param1 */, jobWait /* param2 */); - - // Submit the Job N times (so after N times * timedWait (eg: 5 x 10 Seconds) all scheduled submits occured... - triggerJob.Start(times /* param 3 */); - - // Now wait for 10 (first time to drop the first time the job param1) + 5 (number of submits param3) * 40 seconds (param2, duration of the job) for this to complete. - - // There is an issue if param1 < param2, as with the old code, the job would run multiple times the Job::Dispatch in parallel - // which is not according to spec. - - // with the old code, the following timeing is applicable: - // Assuming there are 5 threads in the threadpool: - // Total time is 5 * 10 + 40 seconds. The Job would be running 5 times spread over all available threads which is a total of 90 second and the job would have been ran 5 times - // if the thread count < 3 the duration will be longer as the last submit (after 50 seconds) still has to wait for the 3 submit to complete. - // if the thread count >= 2 the line "Ooopsie daisy, that is unexpected, it seems there are multiples of me running, thats not according to the spec !!!!\n" will be observed - // which indicates the flas in the current workerpool setup. - - EXPECT_EQ(triggerJob.WaitForEvent((timedWait + (times * jobWait)) * 1000), Core::ERROR_NONE); - EXPECT_EQ(triggerJob.Pending(), 0u); - // In the new code the Job will never be running with more than one instance so the line: "Ooopsie daisy, that is unexpected, it seems there are multiples of me running, thats - // not according to the spec !!!!\n" should never be observed. - // However the job will not be ran 5 times as there are 3 schedule overruns due to the fact that the Job is still running when the next submit ocures. SO the job wll only run - // 3 times and it will take 10 + 3* 40 seconds to complete. - } - Core::WorkerPool::Assign(nullptr); -} -TEST(Core_WorkerPool, Check_ReschduledTimedJob_SinglePool) -{ - CheckWorkerPool_ReschduledTimedJob(1, 5, 5, 10, 5); -} -TEST(Core_WorkerPool, Check_ReschduledTimedJob_MultiplePool) -{ - CheckWorkerPool_ReschduledTimedJob(2, 5, 5, 10, 5); - CheckWorkerPool_ReschduledTimedJob(3, 5, 5, 10, 5); -} - +} // Core +} // Tests +} // Thunder \ No newline at end of file diff --git a/Tests/unit/core/test_xgetopt.cpp b/Tests/unit/core/test_xgetopt.cpp index 320411080e..2d702b1b68 100644 --- a/Tests/unit/core/test_xgetopt.cpp +++ b/Tests/unit/core/test_xgetopt.cpp @@ -25,49 +25,54 @@ #include -int argumentCount = 3; -char* arguments[]= {(char*)"-c", (char*)"-h", (char*)"-b"}; +namespace Thunder { +namespace Tests { +namespace Core { -using namespace Thunder; -using namespace Thunder::Core; + int argumentCount = 3; + char* arguments[]= {(char*)"-c", (char*)"-h", (char*)"-b"}; -class ConsoleOptions : public Core::Options { - public: - ConsoleOptions() = delete; + class ConsoleOptions : public ::Thunder::Core::Options { + public: + ConsoleOptions() = delete; - ConsoleOptions(int argumentCount, TCHAR* arguments[]) - : Core::Options(argumentCount, arguments, _T("chb")) - { - Parse(); - } + ConsoleOptions(int argumentCount, TCHAR* arguments[]) + : ::Thunder::Core::Options(argumentCount, arguments, _T("chb")) + { + Parse(); + } - ~ConsoleOptions() - { - } + ~ConsoleOptions() + { + } - private: - virtual void Option(const TCHAR option, const TCHAR* argument) - { - switch (option) { - case 'c': - EXPECT_EQ(option,'c'); - break; + private: + virtual void Option(const TCHAR option, const TCHAR* argument) + { + switch (option) { + case 'c': + EXPECT_EQ(option,'c'); + break; #ifndef __WIN32__ - case 'b': - EXPECT_EQ(option,'b'); - break; + case 'b': + EXPECT_EQ(option,'b'); + break; #endif - case 'h': - EXPECT_EQ(option,'h'); - break; - default: - printf("default\n"); - break; + case 'h': + EXPECT_EQ(option,'h'); + break; + default: + printf("default\n"); + break; + } } - } -}; + }; + + TEST(test_xgetopt, simple_xgetopt) + { + ConsoleOptions consoleOptions(argumentCount,arguments); + } -TEST(test_xgetopt, simple_xgetopt) -{ - ConsoleOptions consoleOptions(argumentCount,arguments); -} +} // Core +} // Tests +} // Thunder