From: Karol Pawlowski Date: Mon, 18 Feb 2013 10:44:53 +0000 (+0100) Subject: Renaming tests binaries X-Git-Tag: submit/trunk/20130222.060026~3 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=23b58cd276c18716e1201cd9bbe4d077b8c832b2;p=platform%2Fframework%2Fweb%2Fwrt-commons.git Renaming tests binaries [Issue#] LINUXWRT-130 [Problem] Tests binaries should be named -tests- [Cause] N/A [Solution] N/A [Verification] Build wrt-commons repository Change-Id: I09e8be4b79dda7fe03818aeb869af3fb6fa73d74 --- diff --git a/packaging/wrt-commons.spec b/packaging/wrt-commons.spec index cf92fb0..e0008d9 100644 --- a/packaging/wrt-commons.spec +++ b/packaging/wrt-commons.spec @@ -139,9 +139,7 @@ echo "[WRT] wrt-commons postinst done ..." %attr(755,root,root) %{_bindir}/wrt_commons_create_clean_db.sh %attr(755,root,root) %{_bindir}/wrt_commons_reset_db.sh %if %{with_tests} - %attr(755,root,root) %{_bindir}/dpl-tests-* - %attr(755,root,root) %{_bindir}/dpl-dbus-test-service - %attr(755,root,root) %{_bindir}/wrt-tests-* + %attr(755,root,root) %{_bindir}/wrt-commons-tests-* %attr(755,root,root) %{_bindir}/wrt_dao_tests_prepare_db.sh %{_datadir}/dbus-1/services/org.tizen.DBusTestService.service /opt/share/wrt/wrt-commons/tests/* diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 9a9007c..8ebf885 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -11,9 +11,15 @@ WRT_ADD_INTERNAL_DEPENDENCIES( ${TARGET_DPL_TEST_ENGINE_EFL} ) +ADD_SUBDIRECTORY(core) ADD_SUBDIRECTORY(dao) -ADD_SUBDIRECTORY(dpl) -ADD_SUBDIRECTORY(unit_tests) +ADD_SUBDIRECTORY(db) +ADD_SUBDIRECTORY(dbus) +ADD_SUBDIRECTORY(event) +#ADD_SUBDIRECTORY(files_localization) TODO localization mockups need to be fixed +ADD_SUBDIRECTORY(localizationTagsProvider) +ADD_SUBDIRECTORY(utils) +ADD_SUBDIRECTORY(test) # Rollback CXX flags #SET(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS_BACKUP}) \ No newline at end of file diff --git a/tests/core/CMakeLists.txt b/tests/core/CMakeLists.txt new file mode 100644 index 0000000..9e7ffa4 --- /dev/null +++ b/tests/core/CMakeLists.txt @@ -0,0 +1,61 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# 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. +# +# @file CMakeLists.txt +# @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) +# @version 1.0 +# @brief +# + +# +# Test files +# +# Define all DPL tests sources. +# Runner is responsible for runnint it all and +# generating proper output files +# + +SET(TARGET_NAME "wrt-commons-tests-core") + +# Set DPL tests sources +SET(DPL_TESTS_CORE_SOURCES + ${TESTS_DIR}/core/main.cpp + ${TESTS_DIR}/core/test_address.cpp + ${TESTS_DIR}/core/test_binary_queue.cpp + ${TESTS_DIR}/core/test_foreach.cpp + ${TESTS_DIR}/core/test_fast_delegate.cpp + ${TESTS_DIR}/core/test_log_unhandled_exception.cpp + ${TESTS_DIR}/core/test_once.cpp + ${TESTS_DIR}/core/test_serialization.cpp + ${TESTS_DIR}/core/test_scoped_array.cpp + ${TESTS_DIR}/core/test_scoped_close.cpp + ${TESTS_DIR}/core/test_scoped_fclose.cpp + ${TESTS_DIR}/core/test_scoped_free.cpp + ${TESTS_DIR}/core/test_scoped_ptr.cpp + ${TESTS_DIR}/core/test_semaphore.cpp + ${TESTS_DIR}/core/test_shared_ptr.cpp + ${TESTS_DIR}/core/test_string.cpp + ${TESTS_DIR}/core/test_thread.cpp + ${TESTS_DIR}/core/test_type_list.cpp + ${TESTS_DIR}/core/test_zip_input.cpp +) + +WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_NAME} ${TARGET_DPL_EFL}) +WRT_TEST_BUILD(${TARGET_NAME} ${DPL_TESTS_CORE_SOURCES}) +WRT_TEST_INSTALL(${TARGET_NAME}) + +INSTALL(FILES + ${TESTS_DIR}/core/data/sample.zip + DESTINATION /opt/share/wrt/wrt-commons/tests/core + ) diff --git a/tests/core/DESCRIPTION b/tests/core/DESCRIPTION new file mode 100644 index 0000000..48e5394 --- /dev/null +++ b/tests/core/DESCRIPTION @@ -0,0 +1,2 @@ +!!!options!!! stop +Test code diff --git a/tests/core/data/sample.zip b/tests/core/data/sample.zip new file mode 100644 index 0000000..02417d8 Binary files /dev/null and b/tests/core/data/sample.zip differ diff --git a/tests/core/main.cpp b/tests/core/main.cpp new file mode 100644 index 0000000..42ffe3a --- /dev/null +++ b/tests/core/main.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file main.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of main + */ +#include + +int main(int argc, char *argv[]) +{ + return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); +} + diff --git a/tests/core/test_address.cpp b/tests/core/test_address.cpp new file mode 100644 index 0000000..d887ca0 --- /dev/null +++ b/tests/core/test_address.cpp @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_address.cpp + * @author Tomasz Swierczek (t.swierczek@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test address + */ +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +/* +Name: Address_InitialEmpty +Description: tests empty constructor of DPL::Address +Expected: string version of empy address equals ":0" +*/ +RUNNER_TEST(Address_InitialEmpty) +{ + DPL::Address address; + RUNNER_ASSERT(address.ToString() == ":0"); +} + +/* +Name: Address_InitialAddress +Description: tests constructor of DPL::Address with name only +Expected: string version of address equals given name and appended ":0" +*/ +RUNNER_TEST(Address_InitialAddress) +{ + DPL::Address address("www.sample.com"); + RUNNER_ASSERT(address.ToString() == "www.sample.com:0"); +} + +/* +Name: Address_InitialAddress +Description: tests constructor of DPL::Address with name and port +Expected: string version of address should look lik "adress name:port" +*/ +RUNNER_TEST(Address_InitialAddressPort) +{ + DPL::Address address("www.somewhere.com", 8080); + RUNNER_ASSERT(address.ToString() == "www.somewhere.com:8080"); +} + +/* +Name: Address_InitialAddress +Description: tests getter of address +Expected: address name and port should matches those passed in constructor +*/ +RUNNER_TEST(Address_Getters) +{ + DPL::Address address("www.somewhere.com", 8080); + RUNNER_ASSERT(address.GetAddress() == "www.somewhere.com"); + RUNNER_ASSERT(address.GetPort() == 8080); +} diff --git a/tests/core/test_binary_queue.cpp b/tests/core/test_binary_queue.cpp new file mode 100644 index 0000000..cd8931d --- /dev/null +++ b/tests/core/test_binary_queue.cpp @@ -0,0 +1,468 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_binary_queue.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test binary queue + */ +#include +#include +RUNNER_TEST_GROUP_INIT(DPL) + +inline std::string BinaryQueueToString(const DPL::BinaryQueue &queue) +{ + char *buffer = new char[queue.Size()]; + queue.Flatten(buffer, queue.Size()); + std::string result = std::string(buffer, buffer + queue.Size()); + delete[] buffer; + return result; +} + +/* +Name: BinaryQueue_InitialEmpty +Description: tests emptiness of new constructed queue +Expected: new queue should be empty +*/ +RUNNER_TEST(BinaryQueue_InitialEmpty) +{ + DPL::BinaryQueue queue; + RUNNER_ASSERT(queue.Empty() == true); +} + +/* +Name: BinaryQueue_InitialSize +Description: tests emptiness of new constructed queue +Expected: new queue size should be equal 0 +*/ +RUNNER_TEST(BinaryQueue_InitialSize) +{ + DPL::BinaryQueue queue; + RUNNER_ASSERT(queue.Size() == 0); +} + +/* +Name: BinaryQueue_InitialCopy +Description: tests emptiness of new copy-constructed empty queue +Expected: queue constructed on base on empty queue should be empty +*/ +RUNNER_TEST(BinaryQueue_InitialCopy) +{ + DPL::BinaryQueue queue; + DPL::BinaryQueue copy = queue; + + RUNNER_ASSERT(copy.Size() == 0); +} + +/* +Name: BinaryQueue_InitialConsumeZero +Description: tests consume method accepts 0 bytes +Expected: it should be avaliable to discard 0 bytes from empty queue +*/ +RUNNER_TEST(BinaryQueue_InitialConsumeZero) +{ + DPL::BinaryQueue queue; + queue.Consume(0); +} + +/* +Name: BinaryQueue_InitialFlattenConsumeZero +Description: tests returning data from queue and discarding +Expected: it should be able to call flattenconsume with empty buffer if 0 bytes are read +*/ +RUNNER_TEST(BinaryQueue_InitialFlattenConsumeZero) +{ + DPL::BinaryQueue queue; + queue.FlattenConsume(NULL, 0); +} + +/* +Name: BinaryQueue_InitialFlattenZero +Description: tests returning data from queue +Expected: it should be able to call flatten with empty buffer if 0 bytes are read +*/ +RUNNER_TEST(BinaryQueue_InitialFlattenZero) +{ + DPL::BinaryQueue queue; + queue.Flatten(NULL, 0); +} + +/* +Name: BinaryQueue_InitialConsumeOne +Description: tests discarding more bytes than it is avaliable +Expected: exception throw +*/ +RUNNER_TEST(BinaryQueue_InitialConsumeOne) +{ + DPL::BinaryQueue queue; + + Try + { + queue.Consume(1); + } + Catch(DPL::BinaryQueue::Exception::OutOfData) + { + return; + } + + RUNNER_FAIL; +} + +/* +Name: BinaryQueue_InitialFlattenConsumeOne +Description: tests reading and discarding more bytes than it is avaliable +Expected: exception throw +*/ +RUNNER_TEST(BinaryQueue_InitialFlattenConsumeOne) +{ + DPL::BinaryQueue queue; + + Try + { + char data; + queue.FlattenConsume(&data, 1); + } + Catch(DPL::BinaryQueue::Exception::OutOfData) + { + return; + } + + RUNNER_FAIL; +} + +/* +Name: BinaryQueue_InitialFlattenOne +Description: tests reading more bytes than it is avaliable +Expected: exception throw +*/ +RUNNER_TEST(BinaryQueue_InitialFlattenOne) +{ + DPL::BinaryQueue queue; + + Try + { + char data; + queue.Flatten(&data, 1); + } + Catch(DPL::BinaryQueue::Exception::OutOfData) + { + return; + } + + RUNNER_FAIL; +} + +/* +Name: BinaryQueue_ZeroCopyFrom +Description: tests coping content of empty queue to another (AppendCopyFrom) +Expected: source queue should be empty +*/ +RUNNER_TEST(BinaryQueue_ZeroCopyFrom) +{ + DPL::BinaryQueue queue; + DPL::BinaryQueue copy; + + copy.AppendCopyFrom(queue); + RUNNER_ASSERT(queue.Empty()); +} + +/* +Name: BinaryQueue_ZeroMoveFrom +Description: tests moving content of empty queue to another +Expected: source queue should be empty +*/ +RUNNER_TEST(BinaryQueue_ZeroMoveFrom) +{ + DPL::BinaryQueue queue; + DPL::BinaryQueue copy; + + copy.AppendMoveFrom(queue); + RUNNER_ASSERT(queue.Empty()); +} + +/* +Name: BinaryQueue_ZeroCopyTo +Description: tests moving content of empty queue to another (AppendCopyTo) +Expected: source queue should be empty +*/ +RUNNER_TEST(BinaryQueue_ZeroCopyTo) +{ + DPL::BinaryQueue queue; + DPL::BinaryQueue copy; + + queue.AppendCopyTo(copy); + RUNNER_ASSERT(queue.Empty()); +} + +/* +Name: BinaryQueue_InsertSingleCharacters +Description: tests inserting single bytes to queue +Expected: stringified content and size shoudl match expected +*/ +RUNNER_TEST(BinaryQueue_InsertSingleCharacters) +{ + DPL::BinaryQueue queue; + + queue.AppendCopy("a", 1); + queue.AppendCopy("b", 1); + queue.AppendCopy("c", 1); + queue.AppendCopy("d", 1); + + RUNNER_ASSERT(queue.Size() == 4); + RUNNER_ASSERT(BinaryQueueToString(queue) == "abcd"); +} + +/* +Name: BinaryQueue_Consume +Description: tests comsuming portions of 1 or 2 bytes +Expected: stringified content and size should match expected + Bytes should be pope from begin. +*/ +RUNNER_TEST(BinaryQueue_Consume) +{ + DPL::BinaryQueue queue; + + queue.AppendCopy("abcd", 4); + queue.AppendCopy("ef", 2); + + RUNNER_ASSERT(queue.Size() == 6); + + queue.Consume(1); + RUNNER_ASSERT(queue.Size() == 5); + RUNNER_ASSERT(BinaryQueueToString(queue) == "bcdef"); + + queue.Consume(2); + RUNNER_ASSERT(queue.Size() == 3); + RUNNER_ASSERT(BinaryQueueToString(queue) == "def"); + + queue.Consume(1); + RUNNER_ASSERT(queue.Size() == 2); + RUNNER_ASSERT(BinaryQueueToString(queue) == "ef"); + + queue.Consume(2); + RUNNER_ASSERT(queue.Size() == 0); + RUNNER_ASSERT(BinaryQueueToString(queue) == ""); +} + +/* +Name: BinaryQueue_Flatten +Description: tests comsuming portions of 1 and more bytes +Expected: stringified content and size should match expected +*/ +RUNNER_TEST(BinaryQueue_Flatten) +{ + DPL::BinaryQueue queue; + + queue.AppendCopy("abcd", 4); + queue.AppendCopy("ef", 2); + queue.AppendCopy("g", 1); + + RUNNER_ASSERT(queue.Size() == 7); + + RUNNER_ASSERT(BinaryQueueToString(queue) == "abcdefg"); +} + +/* +Name: BinaryQueue_FlattenConsume +Description: tests comsuming portions of 1 and more bytes +Expected: stringified content and size should match expected + reading and discarding bytes should affect queue's size and content +*/ +RUNNER_TEST(BinaryQueue_FlattenConsume) +{ + DPL::BinaryQueue queue; + + queue.AppendCopy("abcd", 4); + queue.AppendCopy("ef", 2); + + RUNNER_ASSERT(queue.Size() == 6); + + char buffer[7] = { '\0' }; + queue.FlattenConsume(buffer, 3); + + RUNNER_ASSERT(queue.Size() == 3); + RUNNER_ASSERT(BinaryQueueToString(queue) == "def"); +} + +/* +Name: BinaryQueue_AppendCopyFrom +Description: tests creating copy of not empty queue (use of: AppendCopyFrom) +Expected: stringified content and size should match expected + from original queue and it's copy +*/ +RUNNER_TEST(BinaryQueue_AppendCopyFrom) +{ + DPL::BinaryQueue queue; + DPL::BinaryQueue copy; + + queue.AppendCopy("abcd", 4); + queue.AppendCopy("ef", 2); + + copy.AppendCopyFrom(queue); + + RUNNER_ASSERT(queue.Size() == 6); + RUNNER_ASSERT(copy.Size() == 6); + RUNNER_ASSERT(BinaryQueueToString(queue) == "abcdef"); + RUNNER_ASSERT(BinaryQueueToString(copy) == "abcdef"); +} + +/* +Name: BinaryQueue_AppendCopyTo +Description: tests creating copy of not empty queue (use of: AppendCopyTo) +Expected: stringified content and size should match expected + from original queue and it's copy +*/ +RUNNER_TEST(BinaryQueue_AppendCopyTo) +{ + DPL::BinaryQueue queue; + DPL::BinaryQueue copy; + + queue.AppendCopy("abcd", 4); + queue.AppendCopy("ef", 2); + + queue.AppendCopyTo(copy); + + RUNNER_ASSERT(queue.Size() == 6); + RUNNER_ASSERT(copy.Size() == 6); + RUNNER_ASSERT(BinaryQueueToString(queue) == "abcdef"); + RUNNER_ASSERT(BinaryQueueToString(copy) == "abcdef"); +} + +/* +Name: BinaryQueue_AppendMoveFrom +Description: tests moving content of not empty queue (use of: AppendMoveFrom) +Expected: stringified content and size should match expected + for new queue. Old queue should be empty after operation +*/ +RUNNER_TEST(BinaryQueue_AppendMoveFrom) +{ + DPL::BinaryQueue queue; + DPL::BinaryQueue copy; + + queue.AppendCopy("abcd", 4); + queue.AppendCopy("ef", 2); + + copy.AppendMoveFrom(queue); + + RUNNER_ASSERT(queue.Size() == 0); + RUNNER_ASSERT(copy.Size() == 6); + RUNNER_ASSERT(BinaryQueueToString(queue) == ""); + RUNNER_ASSERT(BinaryQueueToString(copy) == "abcdef"); +} + +/* +Name: BinaryQueue_AppendMoveFrom +Description: tests moving content of not empty queue (use of: AppendMoveTo) +Expected: stringified content and size should match expected + for new queue. Old queue should be empty after operation +*/ +RUNNER_TEST(BinaryQueue_AppendMoveTo) +{ + DPL::BinaryQueue queue; + DPL::BinaryQueue copy; + + queue.AppendCopy("abcd", 4); + queue.AppendCopy("ef", 2); + + queue.AppendMoveTo(copy); + + RUNNER_ASSERT(queue.Size() == 0); + RUNNER_ASSERT(copy.Size() == 6); + RUNNER_ASSERT(BinaryQueueToString(queue) == ""); + RUNNER_ASSERT(BinaryQueueToString(copy) == "abcdef"); +} + +class Visitor : + public DPL::BinaryQueue::BucketVisitor +{ + private: + int m_index; + + public: + Visitor() : + m_index(0) + {} + + virtual void OnVisitBucket(const void *buffer, size_t bufferSize) + { + const char *str = static_cast(buffer); + + if (m_index == 0) { + RUNNER_ASSERT(bufferSize == 4); + RUNNER_ASSERT(str[0] == 'a'); + RUNNER_ASSERT(str[1] == 'b'); + RUNNER_ASSERT(str[2] == 'c'); + RUNNER_ASSERT(str[3] == 'd'); + } else if (m_index == 1) { + RUNNER_ASSERT(bufferSize == 2); + RUNNER_ASSERT(str[0] == 'e'); + RUNNER_ASSERT(str[1] == 'f'); + } else { + RUNNER_FAIL; + } + + ++m_index; + } +}; + +/* +Name: BinaryQueue_Visitor +Description: tests byte by byte content of queue by use of visitor +Expected: stringified content and size should match expected + Each byte should be at right position +*/ +RUNNER_TEST(BinaryQueue_Visitor) +{ + DPL::BinaryQueue queue; + + queue.AppendCopy("abcd", 4); + queue.AppendCopy("ef", 2); + + Visitor visitor; + queue.VisitBuckets(&visitor); +} + +RUNNER_TEST(BinaryQueue_AbstracInputRead) +{ + DPL::BinaryQueue queue; + + queue.AppendCopy("abcd", 4); + + queue.Read(0); + + RUNNER_ASSERT(BinaryQueueToString(*queue.Read(1).get()) == "a"); + RUNNER_ASSERT(BinaryQueueToString(*queue.Read(2).get()) == "bc"); + RUNNER_ASSERT(BinaryQueueToString(*queue.Read(1).get()) == "d"); + + RUNNER_ASSERT(queue.Size() == 0); +} + +/* +Name: BinaryQueue_AbstracOutputWrite +Description: tests appending one queue to another +Expected: written bytes shoudl affect content and size of queue +*/ +RUNNER_TEST(BinaryQueue_AbstracOutputWrite) +{ + DPL::BinaryQueue queue; + queue.AppendCopy("abcd", 4); + + DPL::BinaryQueue stream; + + stream.Write(queue, 4); + + RUNNER_ASSERT(BinaryQueueToString(*queue.Read(4).get()) == "abcd"); +} diff --git a/tests/core/test_fast_delegate.cpp b/tests/core/test_fast_delegate.cpp new file mode 100644 index 0000000..dc9b34a --- /dev/null +++ b/tests/core/test_fast_delegate.cpp @@ -0,0 +1,247 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_fast_delegate.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of fast delegate tests. + */ +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +// Sample copied and adopted from +// http://www.codeproject.com/KB/cpp/FastDelegate.aspx +// +// Demonstrate the syntax for FastDelegates. +// -Don Clugston, May 2004. +// It's a really boring example, but it shows the most important cases. +// Declare some functions of varying complexity... +void SimpleStaticFunction(int num, const char *str); +void SimpleStaticFunction(int num, const char *str) +{ + LogDebug("In SimpleStaticFunction. Num=" << num << ", str =" << str); +} + +void SimpleVoidFunction(); +void SimpleVoidFunction() +{ + LogDebug("In SimpleVoidFunction with no parameters."); +} + +class CBaseClass +{ + protected: + const char *m_name; + + public: + CBaseClass(const char *name) : + m_name(name) + {} + + virtual ~CBaseClass() + {} + + void SimpleMemberFunction(int num, const char *str) + { + LogDebug("In SimpleMemberFunction in " << m_name << ". Num=" + << num << ", str = " << str); + } + + int SimpleMemberFunctionReturnsInt(int num, const char *str) + { + LogDebug( + "In SimpleMemberFunctionReturnsInt in " << m_name << ". Num=" + << num << + ", str = " << str); + return -1; + } + + void ConstMemberFunction(int num, const char *str) const + { + LogDebug("In ConstMemberFunction in " << m_name << ". Num=" + << num << ", str = " << str); + } + + virtual void SimpleVirtualFunction(int num, const char *str) + { + LogDebug("In SimpleVirtualFunction in " << m_name << ". Num=" + << num << ", str = " << str); + } + + static void StaticMemberFunction(int num, const char *str) + { + LogDebug("In StaticMemberFunction Num=" + << num << ", str = " << str); + } +}; + +class COtherClass +{ + double rubbish; // to ensure this class has non-zero size. + + public: + virtual ~COtherClass() + {} + + virtual void UnusedVirtualFunction(void) + {} + virtual void TrickyVirtualFunction(int num, const char *str) = 0; +}; + +class VeryBigClass +{ + int letsMakeThingsComplicated[400]; +}; + +// This declaration ensures that we get a convoluted class heirarchy. +class CDerivedClass : + public VeryBigClass, + virtual public COtherClass, + virtual public CBaseClass +{ + double m_somemember[8]; + + public: + CDerivedClass() : + CBaseClass("Base of Derived") + { + m_somemember[0] = 1.2345; + } + + void SimpleDerivedFunction(int num, const char *str) + { + LogDebug("In SimpleDerivedFunction Num=" + << num << ", str = " << str); + } + + virtual void AnotherUnusedVirtualFunction(int num, const char *str) + { + LogDebug( + "In AnotherUnusedVirtualFunction in " << m_name << ". Num=" + << num << ", str = " << + str); + } + + virtual void TrickyVirtualFunction(int num, const char *str) + { + LogDebug("In TrickyVirtualFunction in " << m_name << ". Num=" + << num << ", str = " << str); + } +}; + +/* +Name: FastDelegate_Test +Description: tests several scenarios of using fast delegates +Expected: function calls succeeded +*/ +RUNNER_TEST(FastDelegate_Test) +{ + // Delegates with up to 8 parameters are supported. + // Here's the case for a void function. + // We declare a delegate and attach it to SimpleVoidFunction() + DPL::FastDelegate0<> noparameterdelegate(&SimpleVoidFunction); + + // invoke the delegate - this calls SimpleVoidFunction() + noparameterdelegate(); + + LogDebug("-- Examples using two-parameter delegates (int, char *) --"); + + // By default, the return value is void. + typedef DPL::FastDelegate2 MyDelegate; + + // If you want to have a non-void return value, put it at the end. + typedef DPL::FastDelegate2 IntMyDelegate; + + MyDelegate funclist[12]; // delegates are initialized to empty + CBaseClass a("Base A"); + CBaseClass b("Base B"); + CDerivedClass d; + CDerivedClass c; + + IntMyDelegate newdeleg; + newdeleg = DPL::MakeDelegate(&a, + &CBaseClass::SimpleMemberFunctionReturnsInt); + + // Binding a simple member function + funclist[0].bind(&a, &CBaseClass::SimpleMemberFunction); + + // You can also bind static (free) functions + funclist[1].bind(&SimpleStaticFunction); + + // and static member functions + funclist[2].bind(&CBaseClass::StaticMemberFunction); + + // and const member functions (these only need a const class pointer). + funclist[3].bind((const CBaseClass *) &a, + &CBaseClass::ConstMemberFunction); + + funclist[4].bind(&a, &CBaseClass::ConstMemberFunction); + + // and virtual member functions + funclist[5].bind(&b, &CBaseClass::SimpleVirtualFunction); + + // You can also use the = operator. For static functions, a fastdelegate + // looks identical to a simple function pointer. + funclist[6] = &CBaseClass::StaticMemberFunction; + + // The weird rule about the class of derived member function pointers + // is avoided. For MSVC, you can use &CDerivedClass::SimpleVirtualFunction + // here, but DMC will complain. Note that as well as .bind(), you can also + // use the MakeDelegate() global function. + funclist[7] = DPL::MakeDelegate(&d, &CBaseClass::SimpleVirtualFunction); + + // The worst case is an abstract virtual function of a virtually-derived + // class with at least one non-virtual base class. This is a VERY obscure + // situation, which you're unlikely to encounter in the real world. + // FastDelegate versions prior to 1.3 had problems with this case on VC6. + // Now, it works without problems on all compilers. + funclist[8].bind(&c, &CDerivedClass::TrickyVirtualFunction); + + // BUT... in such cases you should be using the base class as an + // interface, anyway. + funclist[9].bind(&c, &COtherClass::TrickyVirtualFunction); + + // Calling a function that was first declared in the derived class is + // straightforward + funclist[10] = DPL::MakeDelegate(&c, &CDerivedClass::SimpleDerivedFunction); + + // You can also bind directly using the constructor + MyDelegate dg(&b, &CBaseClass::SimpleVirtualFunction); + + const char *msg = "Looking for equal delegate"; + + for (int i = 0; i < 12; i++) { + LogDebug(i << ":"); + + // The == and != operators are provided + // Note that they work even for inline functions. + if (funclist[i] == dg) { + msg = "Found equal delegate"; + } + + // operator ! can be used to test for an empty delegate + // You can also use the .empty() member function. + if (!funclist[i]) { + LogDebug("Delegate is empty"); + } else { + // Invocation generates optimal assembly code. + funclist[i](i, msg); + } + } +} diff --git a/tests/core/test_foreach.cpp b/tests/core/test_foreach.cpp new file mode 100644 index 0000000..08d66df --- /dev/null +++ b/tests/core/test_foreach.cpp @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_foreach.cpp + * @author Bartosz Janiak (b.janiak@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of foreach tests. + */ + +#include +#include +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +static const size_t testContainerSize = 1024; + +template +void VerifyForeach(Container& container) +{ + size_t i = 0; + FOREACH(it, container) + { + RUNNER_ASSERT(*it == i); + i++; + } + RUNNER_ASSERT(i == container.size()); +} + +#define VERIFY_FOREACH(container) \ + { \ + size_t i = 0; \ + FOREACH(it, container) \ + { \ + RUNNER_ASSERT(*it == i); \ + i++; \ + } \ + } + +static size_t numberOfCallsToTemporaryList = 0; +std::list temporaryList(); +std::list temporaryList() +{ + ++numberOfCallsToTemporaryList; + std::list list; + for (size_t i = 0; i < testContainerSize; i++) { + list.push_back(i); + } + return list; +} + +static size_t numberOfCallsToTemporaryVector = 0; +std::vector temporaryVector(); +std::vector temporaryVector() +{ + ++numberOfCallsToTemporaryVector; + std::vector vector; + for (size_t i = 0; i < testContainerSize; i++) { + vector.push_back(i); + } + return vector; +} + +static size_t numberOfCallsToTemporarySet = 0; +std::set temporarySet(); +std::set temporarySet() +{ + ++numberOfCallsToTemporarySet; + std::set set; + for (size_t i = 0; i < testContainerSize; i++) { + set.insert(i); + } + return set; +} + +/* +Name: Foreach_std_containers +Description: tests iterating contianers set, list, vector using foreach +Expected: value supplied by foreach matches sequence of integers +*/ +RUNNER_TEST(Foreach_std_containers) +{ + std::vector vector; + std::list list; + std::set set; + + for (size_t i = 0; i < testContainerSize; i++) { + vector.push_back(i); + list.push_back(i); + set.insert(i); + } + + VerifyForeach(vector); + VerifyForeach(list); + VerifyForeach(set); + + VERIFY_FOREACH(temporaryList()); + VERIFY_FOREACH(temporaryVector()); + VERIFY_FOREACH(temporarySet()); + + RUNNER_ASSERT(numberOfCallsToTemporaryList == 1); + RUNNER_ASSERT(numberOfCallsToTemporaryVector == 1); + RUNNER_ASSERT(numberOfCallsToTemporarySet == 1); +} diff --git a/tests/core/test_log_unhandled_exception.cpp b/tests/core/test_log_unhandled_exception.cpp new file mode 100644 index 0000000..3299357 --- /dev/null +++ b/tests/core/test_log_unhandled_exception.cpp @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_log_unhandled_exception.cpp + * @author Pawel Sikorski (p.marcinkiew@samsung.com) + * @version 1.0 + * @brief + */ +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +class MyException +{}; + +class MyDPLException +{ + public: + DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) + DECLARE_EXCEPTION_TYPE(Base, MyException) +}; + +class MySTDException : + public std::exception +{ + public: + virtual const char* what() const throw() + { + return "my std exception occurred"; + } +}; + +/* +Name: Log_Unknown_Exception +Description: tests exceptions catching macros +Expected: unknown exception should be catched + +TODO: workaround abort call +*/ +RUNNER_TEST(Log_Unknown_Exception) +{ + UNHANDLED_EXCEPTION_HANDLER_BEGIN + { + // throw MyException(); + } + UNHANDLED_EXCEPTION_HANDLER_END + RUNNER_ASSERT(true); +} + +/* +Name: Log_DPL_Exception +Description: tests exceptions catching macros +Expected: DPL exception should be catched + +TODO: workaround abort call +*/ +RUNNER_TEST(Log_DPL_Exception) +{ + UNHANDLED_EXCEPTION_HANDLER_BEGIN + { + // Throw(MyDPLException::MyException); + } + UNHANDLED_EXCEPTION_HANDLER_END + RUNNER_ASSERT(true); +} + +/* +Name: Log_STD_Exception +Description: tests exceptions catching macros +Expected: STD exception should be catched + +TODO: workaround abort call +*/ +RUNNER_TEST(Log_STD_Exception) +{ + UNHANDLED_EXCEPTION_HANDLER_BEGIN + { + // throw MySTDException(); + } + UNHANDLED_EXCEPTION_HANDLER_END + RUNNER_ASSERT(true); +} diff --git a/tests/core/test_once.cpp b/tests/core/test_once.cpp new file mode 100644 index 0000000..436aea4 --- /dev/null +++ b/tests/core/test_once.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_once.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of once tests + */ +#include +#include +#include +#include +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +namespace // anonymous +{ +gint g_counter; + +void Delegate() +{ + ++g_counter; +} +} // namespace anonymous + +RUNNER_TEST(Once_DoubleCall) +{ + g_counter = 0; + + DPL::Once once; + + once.Call(&Delegate); + once.Call(&Delegate); + + RUNNER_ASSERT_MSG(g_counter == 1, "Counter value is: " << g_counter); +} + +class MyThread : + public DPL::Thread +{ + protected: + virtual int ThreadEntry() + { + DPL::WaitForSingleHandle(m_event->GetHandle()); + m_once->Call(DPL::Once::Delegate(this, &MyThread::Call)); + return 0; + } + + void Call() + { + ++*m_atom; + } + + public: + MyThread(DPL::WaitableEvent *event, DPL::Once *once, DPL::Atomic *atom) : + m_event(event), m_once(once), m_atom(atom) + {} + + private: + DPL::WaitableEvent *m_event; + DPL::Once *m_once; + DPL::Atomic *m_atom; +}; + +/* +Name: Once_MultiThreadCall +Description: tests once call wrapper for use by multiple threads +Expected: function should be called just once from one of running threads +*/ +RUNNER_TEST(Once_MultiThreadCall) +{ + const size_t NUM_THREADS = 20; + typedef std::shared_ptr ThreadPtr; + + ThreadPtr threads[NUM_THREADS]; + DPL::WaitableEvent event; + DPL::Once once; + DPL::Atomic atom; + + for (size_t i = 0; i < NUM_THREADS; ++i) { + (threads[i] = ThreadPtr(new MyThread(&event, &once, &atom)))->Run(); + } + + event.Signal(); + + for (size_t i = 0; i < NUM_THREADS; ++i) { + threads[i]->Quit(); + } + + RUNNER_ASSERT_MSG(atom == 1, "Atom value is: " << atom); +} diff --git a/tests/core/test_scoped_array.cpp b/tests/core/test_scoped_array.cpp new file mode 100644 index 0000000..f2a3b4b --- /dev/null +++ b/tests/core/test_scoped_array.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_scoped_array.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test scoped array + */ +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +/* +Name: ScopedArray_Zero +Description: tests emptiness of empty scoped array +Expected: array should be empty +*/ +RUNNER_TEST(ScopedArray_Zero) +{ + DPL::ScopedArray array; + + RUNNER_ASSERT(!array); + RUNNER_ASSERT(!!!array); +} + +/* +Name: ScopedArray_NonZero +Description: tests emptiness of not empty scoped array +Expected: array should be not empty +*/ +RUNNER_TEST(ScopedArray_NonZero) +{ + DPL::ScopedArray array(new char[7]); + + RUNNER_ASSERT(array); + RUNNER_ASSERT(!!array); +} + +/* +Name: ScopedArray_Reset +Description: tests reseting content of array +Expected: array should be empty after reset +*/ +RUNNER_TEST(ScopedArray_Reset) +{ + DPL::ScopedArray array(new char[7]); + array.Reset(); + + RUNNER_ASSERT(!array); + + array.Reset(new char); + RUNNER_ASSERT(array); +} + +/* +Name: ScopedArray_ArrayOperator +Description: tests accessing elements of array +Expected: returned values should be equal to those which were set +*/ +RUNNER_TEST(ScopedArray_ArrayOperator) +{ + DPL::ScopedArray array(new char[7]); + + array[1] = array[2] = 3; + + RUNNER_ASSERT(array[1] == 3); + RUNNER_ASSERT(array[2] == 3); +} diff --git a/tests/core/test_scoped_close.cpp b/tests/core/test_scoped_close.cpp new file mode 100644 index 0000000..3549fed --- /dev/null +++ b/tests/core/test_scoped_close.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_scoped_close.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test scoped close + */ +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +// DUNNO diff --git a/tests/core/test_scoped_fclose.cpp b/tests/core/test_scoped_fclose.cpp new file mode 100644 index 0000000..7667a9e --- /dev/null +++ b/tests/core/test_scoped_fclose.cpp @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/*! + * @file test_scoped_fclose.cpp + * @author Piotr Marcinkiewicz (p.marcinkiew@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test scoped fclose + */ + +#include +#include + +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +namespace { +FILE* MakeTmp() +{ + FILE* result = NULL; + do { + result = tmpfile(); + } while (NULL != result && EINTR == errno); + return result; +} +} //anonymous namespace + +/* +Name: ScopedFClose_Zero +Description: tests if operator ! works correct for closed file +Expected: file should be closed +*/ +RUNNER_TEST(ScopedFClose_Zero) +{ + DPL::ScopedFClose file; + + RUNNER_ASSERT(!file); + RUNNER_ASSERT(!!!file); +} + +/* +Name: ScopedArray_NonZero +Description: tests if operator ! works correct for open file +Expected: file should be open +*/ +RUNNER_TEST(ScopedFClose_NonZero) +{ + DPL::ScopedFClose file(MakeTmp()); + + RUNNER_ASSERT(file); + RUNNER_ASSERT(!!file); +} + +/* +Name: ScopedFClose_Reset +Description: tests reseting of scoped file +Expected: file should be closed after reset +*/ +RUNNER_TEST(ScopedFClose_Reset) +{ + DPL::ScopedFClose file(MakeTmp()); + file.Reset(); + + RUNNER_ASSERT(!file); + + file.Reset(MakeTmp()); + RUNNER_ASSERT(file); +} + diff --git a/tests/core/test_scoped_free.cpp b/tests/core/test_scoped_free.cpp new file mode 100644 index 0000000..25bd6d6 --- /dev/null +++ b/tests/core/test_scoped_free.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_scoped_free.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test scoped free + */ +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +/* +Name: ScopedFree_Zero +Description: Checks emptiness of not set scoped free +Expected: resource should be freed +*/ +RUNNER_TEST(ScopedFree_Zero) +{ + DPL::ScopedFree free; + + RUNNER_ASSERT(!free); + RUNNER_ASSERT(!!!free); +} + +/* +Name: ScopedFree_NonZero +Description: Checks emptiness of set scoped free +Expected: resource should not be reported as freed +*/ +RUNNER_TEST(ScopedFree_NonZero) +{ + DPL::ScopedFree free(malloc(7)); + + RUNNER_ASSERT(free); + RUNNER_ASSERT(!!free); +} + +/* +Name: ScopedFree_Reset +Description: Checks reseting scoped free +Expected: resource should be freed after reset +*/ +RUNNER_TEST(ScopedFree_Reset) +{ + DPL::ScopedFree free(malloc(7)); + free.Reset(); + + RUNNER_ASSERT(!free); + + free.Reset(malloc(8)); + RUNNER_ASSERT(free); +} diff --git a/tests/core/test_scoped_ptr.cpp b/tests/core/test_scoped_ptr.cpp new file mode 100644 index 0000000..af17bac --- /dev/null +++ b/tests/core/test_scoped_ptr.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_scoped_ptr.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test scoped ptr + */ +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +/* +Name: ScopedPtr_Zero +Description: Checks if operator! works +Expected: resource should be not set +*/ +RUNNER_TEST(ScopedPtr_Zero) +{ + DPL::ScopedPtr ptr; + + RUNNER_ASSERT(!ptr); + RUNNER_ASSERT(!!!ptr); +} + +/* +Name: ScopedPtr_NonZero +Description: Checks if operator! works +Expected: resource should be set +*/ +RUNNER_TEST(ScopedPtr_NonZero) +{ + DPL::ScopedPtr ptr(new char(7)); + + RUNNER_ASSERT(ptr); + RUNNER_ASSERT(!!ptr); +} + +/* +Name: ScopedPtr_Reset +Description: Checks reseting scoped ptr +Expected: resource should be not set after reset +*/ +RUNNER_TEST(ScopedPtr_Reset) +{ + DPL::ScopedPtr ptr(new char(7)); + ptr.Reset(); + + RUNNER_ASSERT(!ptr); + + ptr.Reset(new char); + RUNNER_ASSERT(ptr); +} + +/* +Name: ScopedPtr_Operators +Description: Checks access operator +Expected: address of resource should be same as this, received from Get() method +*/ +RUNNER_TEST(ScopedPtr_Operators) +{ + DPL::ScopedPtr ptr(new char(7)); + + RUNNER_ASSERT(*ptr == *ptr.Get()); +} diff --git a/tests/core/test_semaphore.cpp b/tests/core/test_semaphore.cpp new file mode 100644 index 0000000..c93b365 --- /dev/null +++ b/tests/core/test_semaphore.cpp @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_semaphore.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of semaphore tests + */ +#include +#include +#include +#include +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +class SemaphoreThread : + public DPL::Thread +{ + int m_delta; + int m_times; + int *m_value; + std::string m_semaphoreName; + + public: + SemaphoreThread(int delta, + int times, + int *value, + const std::string &semaphoreName) : + m_delta(delta), + m_times(times), + m_value(value), + m_semaphoreName(semaphoreName) + {} + + protected: + virtual int ThreadEntry() + { + DPL::Semaphore semaphore(m_semaphoreName); + + for (int i = 0; i < m_times; ++i) { + // Take scoped semaphore lock + DPL::Semaphore::ScopedLock lock(&semaphore); + *m_value += m_delta; + } + + return 0; + } +}; + +/* +Name: Semaphore_NamedIncrementDecrement +Description: Checks if semaphore are working +Expected: value should not change after all +*/ +RUNNER_TEST(Semaphore_NamedIncrementDecrement) +{ + std::string semaphoreName = + "dpl_test_semaphore_" + + DPL::lexical_cast(std::time(NULL)); + + int value = 0; + SemaphoreThread threadA(-1, 10000, &value, semaphoreName); + SemaphoreThread threadB(+1, 10000, &value, semaphoreName); + + threadA.Run(); + threadB.Run(); + + threadA.Quit(); + threadB.Quit(); + + RUNNER_ASSERT_MSG(value == 0, "Final value is: " << value); +} diff --git a/tests/core/test_serialization.cpp b/tests/core/test_serialization.cpp new file mode 100644 index 0000000..202589b --- /dev/null +++ b/tests/core/test_serialization.cpp @@ -0,0 +1,302 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_address.cpp + * @author Tomasz Swierczek (t.swierczek@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of serialization tests + */ + +#include +#include +#include +#include + +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +// test stream class +class BinaryStream : public DPL::IStream +{ + public: + virtual void Read(size_t num, void * bytes) + { + for (unsigned i = 0; i < num; ++i) { + ((unsigned char*)bytes)[i] = data[i + readPosition]; + } + readPosition += num; + } + virtual void Write(size_t num, const void * bytes) + { + for (unsigned i = 0; i < num; ++i) { + data.push_back(((unsigned char*)bytes)[i]); + } + } + BinaryStream() + { + readPosition = 0; + } + virtual ~BinaryStream(){} + + private: + std::vector data; + unsigned readPosition; +}; + +//test ISerializable class +class TestClass : public DPL::ISerializable +{ + public: + TestClass(int val, std::string str1, std::string str2) + { + a = val; + b = str1; + c.push_back(str1); + c.push_back(str2); + c.push_back(str1 + str2); + } + TestClass(DPL::IStream& stream) + { + DPL::Deserialization::Deserialize(stream, a); + DPL::Deserialization::Deserialize(stream, b); + DPL::Deserialization::Deserialize(stream, c); + } + virtual void Serialize(DPL::IStream& stream) const + { + DPL::Serialization::Serialize(stream, a); + DPL::Serialization::Serialize(stream, b); + DPL::Serialization::Serialize(stream, c); + } + virtual ~TestClass(){} + virtual bool operator==(const TestClass& other) + { + return (a == other.a && + b == other.b && + c.size() == other.c.size() && + c[0] == other.c[0] && + c[1] == other.c[1] && + c[2] == other.c[2]); + } + + private: + int a; + std::string b; + std::vector c; +}; + +/* +Name: Serialize_primitives +Description: Tests serialization of primitives types +Expected: serialized value after deserialization + should be equal to deserialied value +*/ +RUNNER_TEST(Serialize_primitives) +{ + int a = 1; + bool b = true; + unsigned c = 23; + BinaryStream stream; + DPL::Serialization::Serialize(stream, a); + DPL::Serialization::Serialize(stream, b); + DPL::Serialization::Serialize(stream, c); + int test_int; + DPL::Deserialization::Deserialize(stream, test_int); + RUNNER_ASSERT(test_int == a); + bool test_bool; + DPL::Deserialization::Deserialize(stream, test_bool); + RUNNER_ASSERT(test_bool == b); + unsigned test_unsigned; + DPL::Deserialization::Deserialize(stream, test_unsigned); + RUNNER_ASSERT(test_unsigned == c); +} + +/* +Name: Serialize_primitive_pointers +Description: Tests serialization of primitives pointer types +Expected: serialized value after deserialization + should be equal to deserialied value +*/ +RUNNER_TEST(Serialize_primitive_pointers) +{ + int a = 1; + bool b = true; + unsigned c = 23; + BinaryStream stream; + DPL::Serialization::Serialize(stream, &a); + DPL::Serialization::Serialize(stream, &b); + DPL::Serialization::Serialize(stream, &c); + int* test_int; + DPL::Deserialization::Deserialize(stream, test_int); + RUNNER_ASSERT(test_int != NULL && *test_int == a); + bool* test_bool; + DPL::Deserialization::Deserialize(stream, test_bool); + RUNNER_ASSERT(test_bool != NULL && *test_bool == b); + unsigned* test_unsigned; + DPL::Deserialization::Deserialize(stream, test_unsigned); + RUNNER_ASSERT(test_unsigned != NULL && *test_unsigned == c); + delete test_int; + delete test_bool; + delete test_unsigned; +} + +/* +Name: Serialize_strings +Description: Tests serialization of strings +Expected: serialized value after deserialization + should be equal to deserialied value +*/ +RUNNER_TEST(Serialize_strings) +{ + std::string str1 = "ALA MA KOTA"; + std::string str2 = "MULTILINE\nTEST"; + BinaryStream stream; + DPL::Serialization::Serialize(stream, str1); + DPL::Serialization::Serialize(stream, str2); + std::string test_str1; + DPL::Deserialization::Deserialize(stream, test_str1); + RUNNER_ASSERT(test_str1 == str1); + std::string test_str2; + DPL::Deserialization::Deserialize(stream, test_str2); + RUNNER_ASSERT(test_str2 == str2); +} + +/* +Name: Serialize_string_pointers +Description: Tests serialization of string pointers +Expected: serialized value after deserialization + should be equal to deserialied value +*/ +RUNNER_TEST(Serialize_string_pointers) +{ + std::string str1 = "ALA MA KOTA"; + std::string str2 = "MULTILINE\nTEST"; + BinaryStream stream; + DPL::Serialization::Serialize(stream, &str1); + DPL::Serialization::Serialize(stream, &str2); + std::string* test_str1; + DPL::Deserialization::Deserialize(stream, test_str1); + RUNNER_ASSERT(test_str1 != NULL && *test_str1 == str1); + std::string* test_str2; + DPL::Deserialization::Deserialize(stream, test_str2); + RUNNER_ASSERT(test_str2 != NULL && *test_str2 == str2); + delete test_str1; + delete test_str2; +} + +/* +Name: Serialize_containers +Description: Tests serialization of containers +Expected: serialized value after deserialization + should be equal to deserialied value +*/ +RUNNER_TEST(Serialize_containers) +{ + std::vector vec; + vec.push_back(134); + vec.push_back(265); + std::list list; + list.push_back(true); + list.push_back(false); + std::pair pair; + pair.first = -23; + pair.second = 1234; + std::map map; + map.insert(std::pair(45, "ALA MA CZARNEGO KOTA")); + map.insert(std::pair(-78, "...A MOZE\nMA\nWIELE LINIJEK")); + BinaryStream stream; + DPL::Serialization::Serialize(stream, vec); + DPL::Serialization::Serialize(stream, list); + DPL::Serialization::Serialize(stream, pair); + DPL::Serialization::Serialize(stream, map); + std::vector test_vec; + DPL::Deserialization::Deserialize(stream, test_vec); + RUNNER_ASSERT(test_vec.size() == vec.size() && + test_vec[0] == vec[0] && test_vec[1] == vec[1]); + std::list test_list; + DPL::Deserialization::Deserialize(stream, test_list); + RUNNER_ASSERT(test_list.size() == list.size() && + test_list.front() == list.front() && + test_list.back() == test_list.back()); + std::pair test_pair; + DPL::Deserialization::Deserialize(stream, test_pair); + RUNNER_ASSERT(test_pair.first == pair.first && + test_pair.second == pair.second); + std::map test_map; + DPL::Deserialization::Deserialize(stream, test_map); + RUNNER_ASSERT(test_map.size() == map.size() && + test_map.at(45) == map.at(45) && + test_map.at(-78) == map.at(-78)); +} + +/* +Name: Serialize_objects +Description: Tests serialization of DPL::ISerializable derived objects +Expected: serialized value after deserialization + should be equal to deserialied value +*/ +RUNNER_TEST(Serialize_objects) +{ + TestClass a(123, "ASDGHUADB\n\n5679b^^()*", "TEST_STRING"), + b(679, "HUSPIDNSAHDPA", "\nASDSADASD\naDSADASD8"); + BinaryStream stream; + DPL::Serialization::Serialize(stream, a); + DPL::Serialization::Serialize(stream, b); + TestClass test_a(0, "", ""), test_b(0, "", ""); + DPL::Deserialization::Deserialize(stream, test_a); + RUNNER_ASSERT(test_a == a); + DPL::Deserialization::Deserialize(stream, test_b); + RUNNER_ASSERT(test_b == b); +} + +/* +Name: Serialize_all +Description: Tests serialization of compound objects +Expected: serialized value after deserialization + should be equal to deserialied value +*/ +RUNNER_TEST(Serialize_all) +{ + std::map > map; + std::vector vec; + vec.push_back(new TestClass(123, "ASDGHUADB\n\n5679b^^()*", "TEST_STRING")); + vec.push_back(new TestClass(679, "HUSPIDNSAHDPA", "\nASDSADASD\naDSADASD8")); + map.insert(std::pair >("KEY1", vec)); + map.insert(std::pair >("KEY2", vec)); + BinaryStream stream; + + DPL::Serialization::Serialize(stream, map); + + std::map > test_map; + DPL::Deserialization::Deserialize(stream, test_map); + RUNNER_ASSERT(map.size() == test_map.size()); + std::vector test_vec1, test_vec2; + test_vec1 = map.at("KEY1"); + test_vec2 = test_map.at("KEY1"); + RUNNER_ASSERT(test_vec1.size() == test_vec2.size()); + unsigned i; + for (i = 0; i < test_vec1.size(); ++i) { + RUNNER_ASSERT((*test_vec1[i]) == (*test_vec2[i])); + } + test_vec1 = map.at("KEY2"); + test_vec2 = test_map.at("KEY2"); + RUNNER_ASSERT(test_vec1.size() == test_vec2.size()); + for (i = 0; i < test_vec1.size(); ++i) { + RUNNER_ASSERT((*test_vec1[i]) == (*test_vec2[i])); + } +} + diff --git a/tests/core/test_shared_ptr.cpp b/tests/core/test_shared_ptr.cpp new file mode 100644 index 0000000..8e59075 --- /dev/null +++ b/tests/core/test_shared_ptr.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_shared_ptr.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test shared ptr + */ +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +/* +Name: SharedPtr_Zero +Description: Tests behaviour of null shared pointer +Expected: pointer should imitate null pointer +*/ +RUNNER_TEST(SharedPtr_Zero) +{ + DPL::SharedPtr ptr; + + RUNNER_ASSERT(!ptr); + RUNNER_ASSERT(!!!ptr); + RUNNER_ASSERT(ptr == DPL::SharedPtr()); +} + +/* +Name: SharedPtr_NonZero +Description: Tests behaviour of not null shared pointer +Expected: pointer should imitate null pointer +*/ +RUNNER_TEST(SharedPtr_NonZero) +{ + DPL::SharedPtr ptr(new char(7)); + + RUNNER_ASSERT(ptr); + RUNNER_ASSERT(!!ptr); + RUNNER_ASSERT(ptr != DPL::SharedPtr()); +} + +/* +Name: SharedPtr_Copy +Description: Tests equality of shared pointer pointing same resource +Expected: pointers should imitate primitive pointer bahaviour +*/ +RUNNER_TEST(SharedPtr_Copy) +{ + DPL::SharedPtr ptr1(new char(7)); + DPL::SharedPtr ptr2(new char(7)); + + RUNNER_ASSERT(ptr1 != ptr2); + + ptr2 = ptr1; + + RUNNER_ASSERT(ptr1 == ptr2); +} + +/* +Name: SharedPtr_Reset +Description: Tests reseting shared pointer +Expected: pointers should imitate primitive pointer bahaviour after reset +*/ +RUNNER_TEST(SharedPtr_Reset) +{ + DPL::SharedPtr ptr(new char(7)); + ptr.Reset(); + + RUNNER_ASSERT(!ptr); + + ptr.Reset(new char); + RUNNER_ASSERT(ptr); +} + +/* +Name: SharedPtr_RefCounting +Description: Tests use count od shared pointer +Expected: counters should be equal for equal pointers + Count number should match expected +*/ +RUNNER_TEST(SharedPtr_RefCounting) +{ + DPL::SharedPtr ptr1(new char(7)); + DPL::SharedPtr ptr2; + + ptr2 = ptr1; + + RUNNER_ASSERT(ptr1 == ptr2); + RUNNER_ASSERT(ptr1.GetUseCount() == ptr2.GetUseCount()); + RUNNER_ASSERT(ptr1.GetUseCount() == 2); +} + +/* +Name: SharedPtr_Operators +Description: Tests use of operator* +Expected: pointers should imitate primitive pointer bahaviour +*/ +RUNNER_TEST(SharedPtr_Operators) +{ + DPL::SharedPtr ptr(new char(7)); + + RUNNER_ASSERT(*ptr == *ptr.Get()); +} diff --git a/tests/core/test_string.cpp b/tests/core/test_string.cpp new file mode 100644 index 0000000..dd2bd8a --- /dev/null +++ b/tests/core/test_string.cpp @@ -0,0 +1,418 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_string.cpp + * @author Piotr Marcinkiewicz (p.marcinkiew@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of string tests + */ +#include +#include +#include +#include +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +unsigned char GetBaseCode(int index); +unsigned char GetBaseCode(int index) +{ + /* aaaack but it's fast and const should make it shared text page. */ + static const unsigned char pr2six[256] = { + /* ASCII table */ + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, + 64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64, + 64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64 + }; + return pr2six[index]; +} + +/* Function adapted from APR library (http://apr.apache.org/) */ +int wbxml_base64_decode(const char *buffer, char **result); +int wbxml_base64_decode(const char *buffer, char **result) +{ + int nbytesdecoded = 0, nprbytes = 0; + const char *bufin = NULL; + char *bufout = NULL; + + if ((buffer == NULL) || (result == NULL)) { + return 0; + } + + /* Initialize output buffer */ + *result = NULL; + + bufin = buffer; + while (GetBaseCode(*(bufin++)) <= 63) {} + + nprbytes = (bufin - buffer) - 1; + nbytesdecoded = ((nprbytes + 3) / 4) * 3; + + /* Malloc result buffer */ + if ((*result = (char*) malloc(nbytesdecoded + 1)) == NULL) { + return 0; + } + memset(*result, 0, nbytesdecoded + 1); + + bufout = *result; + bufin = buffer; + + while (nprbytes > 4) { + *(bufout++) = + (char)(GetBaseCode(*bufin) << 2 | GetBaseCode(bufin[1]) >> 4); + *(bufout++) = + (char)(GetBaseCode(bufin[1]) << 4 | GetBaseCode(bufin[2]) >> 2); + *(bufout++) = (char)(GetBaseCode(bufin[2]) << 6 | GetBaseCode(bufin[3])); + bufin += 4; + nprbytes -= 4; + } + + /* Note: (nprbytes == 1) would be an error, so just ingore that case */ + if (nprbytes > 1) { + *(bufout++) = + (char)(GetBaseCode(*bufin) << 2 | GetBaseCode(bufin[1]) >> 4); + } + if (nprbytes > 2) { + *(bufout++) = + (char)(GetBaseCode(bufin[1]) << 4 | GetBaseCode(bufin[2]) >> 2); + } + if (nprbytes > 3) { + *(bufout++) = (char)(GetBaseCode(bufin[2]) << 6 | GetBaseCode(bufin[3])); + } + + nbytesdecoded -= (4 - nprbytes) & 3; + + return nbytesdecoded; +} + +//#define TEST_CONVERSION(in_string, out_string, buffer_type, function + +const char utf32Encoded[] = + "RDAAAI0wAABvMAAAazAAAHswAAB4MAAAaDAAAAAwAABhMAAAijAAAGwwAACLMAAAkjAAAAAwAACP\ +MAAASzAAAIgwAABfMAAAjDAAAF0wAAAAMAAAZDAAAG0wAABqMAAAiTAAAIAwAAAAMAAARjAAAJAw\ +AABuMAAASjAAAE8wAACEMAAAfjAAAAAwAABRMAAAdTAAAFMwAABIMAAAZjAAAAAwAABCMAAAVTAA\ +AE0wAACGMAAAgTAAAH8wAABXMAAAADAAAJEwAAByMAAAgjAAAFswAABZMAAACgAAANsFAADaBQAA\ +IAAAANQFAADqBQAA6AUAAOEFAADnBQAAIAAAAOAFAADkBQAA5QUAACAAAADiBQAA3AUAACAAAADS\ +BQAA1QUAANYFAADcBQAAIAAAAOcFAADYBQAA3wUAACwAAAAgAAAA6QUAANMFAADXBQAA4wUAACAA\ +AADQBQAA6gUAACAAAADmBQAA0QUAANkFAAAgAAAA3AUAAN4FAADZBQAA3QUAAAoAAACk0AAApMIA\ +AFjHAAAgAAAA4KwAACDHAABwyAAAdKwAAEDHAAAgAAAAhccAACDCAAB8sAAArLkAACAAAADMuQAA\ +mLAAAHzFAAAgAAAAWNUAAOCsAAAgAAAAudIAAMS8AABc1QAAIAAAADCuAAAgwgAAQMcAACAAAABE\ +1QAAlMYAAFjOAAAgAAAASsUAAOSyAAAKAAAAUAAAAGMAAABoAAAAbgAAAAUBAAAHAQAAIAAAAHcA\ +AAAgAAAAdAAAABkBAAAgAAAAQgEAAPMAAABkAAAAegEAACAAAABqAAAAZQAAAHwBAABhAAAAIAAA\ +AGwAAAB1AAAAYgAAACAAAABvAAAAWwEAAG0AAAAgAAAAcwAAAGsAAAByAAAAegAAAHkAAABEAQAA\ +IAAAAGYAAABpAAAAZwAAAC4AAAAKAAAAQgAAAGwAAABvAAAAdwAAAHoAAAB5AAAAIAAAAG4AAABp\ +AAAAZwAAAGgAAAB0AAAALQAAAGYAAAByAAAAdQAAAG0AAABwAAAAcwAAACAAAAB2AAAAZQAAAHgA\ +AAAnAAAAZAAAACAAAABKAAAAYQAAAGMAAABrAAAAIAAAAFEAAAAuAAAACgAAAEYGAAA1BgAAIAAA\ +AC0GAABDBgAASgYAAEUGAAAgAAAARAYAAEcGAAAgAAAAMwYAADEGAAAgAAAAQgYAACcGAAA3BgAA\ +OQYAACAAAABIBgAAMAYAAEgGAAAgAAAANAYAACMGAABGBgAAIAAAADkGAAA4BgAASgYAAEUGAAAg\ +AAAARQYAAEMGAAAqBgAASAYAACgGAAAgAAAAOQYAAEQGAABJBgAAIAAAACsGAABIBgAAKAYAACAA\ +AAAjBgAALgYAADYGAAAxBgAAIAAAAEgGAABFBgAAOgYAAEQGAABBBgAAIAAAACgGAAAsBgAARAYA\ +AC8GAAAgAAAAIwYAADIGAAAxBgAAQgYAACAAAAAKAAAAEgQAACAAAABHBAAAMAQAAEkEAAAwBAAA\ +RQQAACAAAABOBAAAMwQAADAEAAAgAAAANgQAADgEAAA7BAAAIAAAADEEAABLBAAAIAAAAEYEAAA4\ +BAAAQgQAAEAEAABDBAAAQQQAAD8AAAAgAAAAFAQAADAEAAAsAAAAIAAAAD0EAAA+BAAAIAAAAEQE\ +AAAwBAAAOwQAAEwEAABIBAAAOAQAADIEAABLBAAAOQQAACAAAABNBAAAOgQAADcEAAA1BAAAPAQA\ +AD8EAAA7BAAATwQAAEAEAAAhAAAACgAAAKQDAACsAwAAxwMAALkDAADDAwAAxAMAALcDAAAgAAAA\ +sQMAALsDAADOAwAAwAMAALcDAAC+AwAAIAAAALIDAACxAwAAxgMAAK4DAADCAwAAIAAAAMgDAAC3\ +AwAAvAMAAK0DAAC9AwAAtwMAACAAAACzAwAAtwMAACwAAAAgAAAAtAMAAMEDAACxAwAAwwMAALoD\ +AAC1AwAAuwMAAK8DAAC2AwAAtQMAALkDAAAgAAAAxQMAAMADAACtAwAAwQMAACAAAAC9AwAAyQMA\ +ALgDAADBAwAAvwMAAM0DAAAgAAAAugMAAMUDAAC9AwAAzAMAAMIDAAAKAAAAVgAAAGkAAABjAAAA\ +dAAAAG8AAAByAAAAIAAAAGoAAABhAAAAZwAAAHQAAAAgAAAAegAAAHcAAAD2AAAAbAAAAGYAAAAg\ +AAAAQgAAAG8AAAB4AAAAawAAAOQAAABtAAAAcAAAAGYAAABlAAAAcgAAACAAAABxAAAAdQAAAGUA\ +AAByAAAAIAAAAPwAAABiAAAAZQAAAHIAAAAgAAAAZAAAAGUAAABuAAAAIAAAAGcAAAByAAAAbwAA\ +AN8AAABlAAAAbgAAACAAAABTAAAAeQAAAGwAAAB0AAAAZQAAAHIAAAAgAAAARAAAAGUAAABpAAAA\ +YwAAAGgAAAAKAAAAlokAAM6RAAAhcQAAUJYAAONeAAAM/wAAl3oAABZZAAAJZwAAzYUAAClZAAAK\ +AAAACgAAAAAAAAA="; + +const char utf8Encoded[] = + "44GE44KN44Gv44Gr44G744G444Go44CA44Gh44KK44Gs44KL44KS44CA44KP44GL44KI44Gf44KM\ +44Gd44CA44Gk44Gt44Gq44KJ44KA44CA44GG44KQ44Gu44GK44GP44KE44G+44CA44GR44G144GT\ +44GI44Gm44CA44GC44GV44GN44KG44KB44G/44GX44CA44KR44Gy44KC44Gb44GZCteb15og15TX\ +qteo16HXpyDXoNek16Ug16LXnCDXkteV15bXnCDXp9eY158sINep15PXl9ejINeQ16og16bXkdeZ\ +INec157XmdedCu2CpOyKpOydmCDqs6DsnKDsobDqsbTsnYAg7J6F7Iig64G866asIOunjOuCmOyV\ +vCDtlZjqs6Ag7Yq567OE7ZWcIOq4sOyIoOydgCDtlYTsmpTsuZgg7JWK64ukClBjaG7EhcSHIHcg\ +dMSZIMWCw7NkxbogamXFvGEgbHViIG/Fm20gc2tyennFhCBmaWcuCkJsb3d6eSBuaWdodC1mcnVt\ +cHMgdmV4J2QgSmFjayBRLgrZhti1INit2YPZitmFINmE2Ycg2LPYsSDZgtin2LfYuSDZiNiw2Ygg\ +2LTYo9mGINi52LjZitmFINmF2YPYqtmI2Kgg2LnZhNmJINir2YjYqCDYo9iu2LbYsSDZiNmF2LrZ\ +hNmBINio2KzZhNivINij2LLYsdmCIArQkiDRh9Cw0YnQsNGFINGO0LPQsCDQttC40Lsg0LHRiyDR\ +htC40YLRgNGD0YE/INCU0LAsINC90L4g0YTQsNC70YzRiNC40LLRi9C5INGN0LrQt9C10LzQv9C7\ +0Y/RgCEKzqTOrM+HzrnPg8+EzrcgzrHOu8+Oz4DOt86+IM6yzrHPhs6uz4Igz4jOt868zq3Ovc63\ +IM6zzrcsIM60z4HOsc+DzrrOtc67zq/Ots61zrkgz4XPgM6tz4Egzr3Pic64z4HOv8+NIM66z4XO\ +vc+Mz4IKVmljdG9yIGphZ3QgenfDtmxmIEJveGvDpG1wZmVyIHF1ZXIgw7xiZXIgZGVuIGdyb8Of\ +ZW4gU3lsdGVyIERlaWNoCuimlumHjueEoemZkOW7o++8jOeql+WkluacieiXjeWkqQoKAA=="; + +const char asciiEncodedIso1[] = + "ISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZ\ +WltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fgA="; + +const char asciiEncodedUtf32[] = + "IQAAACIAAAAjAAAAJAAAACUAAAAmAAAAJwAAACgAAAApAAAAKgAAACsAAAAsAAAALQAAAC4AAAAv\ +AAAAMAAAADEAAAAyAAAAMwAAADQAAAA1AAAANgAAADcAAAA4AAAAOQAAADoAAAA7AAAAPAAAAD0A\ +AAA+AAAAPwAAAEAAAABBAAAAQgAAAEMAAABEAAAARQAAAEYAAABHAAAASAAAAEkAAABKAAAASwAA\ +AEwAAABNAAAATgAAAE8AAABQAAAAUQAAAFIAAABTAAAAVAAAAFUAAABWAAAAVwAAAFgAAABZAAAA\ +WgAAAFsAAABcAAAAXQAAAF4AAABfAAAAYAAAAGEAAABiAAAAYwAAAGQAAABlAAAAZgAAAGcAAABo\ +AAAAaQAAAGoAAABrAAAAbAAAAG0AAABuAAAAbwAAAHAAAABxAAAAcgAAAHMAAAB0AAAAdQAAAHYA\ +AAB3AAAAeAAAAHkAAAB6AAAAewAAAHwAAAB9AAAAfgAAAAAAAAA="; + +/* +Name: String_ConverterFromASCII +Description: tests construction of string from ascii data +Expected: data stored in buffer should match expected +*/ +RUNNER_TEST(String_ConverterFromASCII) +{ + char* inStr = NULL; + int inSize = wbxml_base64_decode(asciiEncodedIso1, &inStr); + RUNNER_ASSERT(inSize > 0); + RUNNER_ASSERT(NULL != inStr); + inStr[inSize] = '\0'; + { + DPL::String asciiString = DPL::FromASCIIString(inStr); + + std::string result = DPL::ToUTF8String(asciiString); + + RUNNER_ASSERT(strlen(inStr) == result.size()); + + RUNNER_ASSERT(0 == memcmp(inStr, result.c_str(), result.size())); + } + + free(inStr); +} + +/* +Name: String_ConverterFromUTF8 +Description: tests construction of string from UTF-8 data +Expected: data stored in buffer should match expected +*/ +RUNNER_TEST(String_ConverterFromUTF8) +{ + char* inStr = NULL; + int inSize = wbxml_base64_decode(asciiEncodedIso1, &inStr); + RUNNER_ASSERT(inSize > 0); + RUNNER_ASSERT(NULL != inStr); + { + DPL::String asciiString = DPL::FromUTF8String(inStr); + + std::string result = DPL::ToUTF8String(asciiString); + + RUNNER_ASSERT(strlen(inStr) == result.size()); + + RUNNER_ASSERT(0 == memcmp(inStr, result.c_str(), result.size())); + } + + free(inStr); +} + +/* +Name: String_ConverterFromUTF32 +Description: tests construction of string from UTF-32 data +Expected: data stored in buffer should match expected +*/ +RUNNER_TEST(String_ConverterFromUTF32) +{ + wchar_t* inStr = NULL; + int inSize = + wbxml_base64_decode(utf32Encoded, reinterpret_cast(&inStr)); + RUNNER_ASSERT(inSize > 0); + RUNNER_ASSERT(NULL != inStr); + char* outStr = NULL; + int outSize = wbxml_base64_decode(utf8Encoded, &outStr); + RUNNER_ASSERT(outSize > 0); + RUNNER_ASSERT(NULL != outStr); + outStr[outSize] = '\0'; + { + DPL::String utfString = DPL::FromUTF32String(inStr); + std::string result = DPL::ToUTF8String(utfString); + + RUNNER_ASSERT(strlen(outStr) == result.size()); + RUNNER_ASSERT(0 == memcmp(outStr, result.c_str(), result.size())); + + RUNNER_ASSERT(inSize / sizeof(wchar_t) - 1 == utfString.size()); + RUNNER_ASSERT(0 == + memcmp(inStr, &(utfString[0]), utfString.size() * + sizeof(wchar_t))); + } + + free(inStr); +} + +template +void String_TokenizeReal(const DelimiterType& delimiter) +{ + DPL::String str(L".##..abc.#."); + std::vector tokens; + DPL::Tokenize(str, delimiter, std::back_inserter(tokens)); + + std::vector expectedTokens; + for (int i = 0; i < 5; i++) { + expectedTokens.push_back(L""); + } + expectedTokens.push_back(L"abc"); + for (int i = 0; i < 3; i++) { + expectedTokens.push_back(L""); + } + + RUNNER_ASSERT(expectedTokens == tokens); + tokens.clear(); + expectedTokens.clear(); + + DPL::Tokenize(str, delimiter, std::back_inserter(tokens), true); + expectedTokens.push_back(L"abc"); + RUNNER_ASSERT(expectedTokens == tokens); +} + +/* +Name: String_Tokenize +Description: tests of string splitting +Expected: returned substring should match expected values +*/ +RUNNER_TEST(String_Tokenize) +{ + String_TokenizeReal(L"#."); + String_TokenizeReal(L".#"); + String_TokenizeReal(L".....####.###.."); + String_TokenizeReal(DPL::String(L".#")); + + std::vector tokens; + DPL::Tokenize(std::string("abc.def"), '.', std::back_inserter(tokens)); + std::vector expectedTokens; + expectedTokens.push_back("abc"); + expectedTokens.push_back("def"); + + RUNNER_ASSERT(tokens == expectedTokens); +} + +template +void TestInStreams( + std::basic_string argumentInString, + std::basic_string argumentResultString) +{ + typedef std::basic_string + String; + std::basic_istringstream + istream(argumentInString); + int intValue = 0; + double doubleValue = 0.0; + float floatValue = 0.0; + String stringValue; + + istream >> intValue; + RUNNER_ASSERT(!istream.fail()); + istream >> doubleValue; + RUNNER_ASSERT(!istream.fail()); + istream >> floatValue; + RUNNER_ASSERT(!istream.fail()); + istream >> stringValue; + RUNNER_ASSERT(!istream.fail()); + + RUNNER_ASSERT(1 == intValue); + RUNNER_ASSERT(fabs(1.1f - doubleValue) < 0.00001); + RUNNER_ASSERT(fabs(1.1f - floatValue) < 0.00001); + RUNNER_ASSERT(argumentResultString == stringValue); +} + +template +void TestOutStreams( + std::basic_string argumentInString, + std::basic_string argumentResultString) +{ + typedef std::basic_string + String; + + std::basic_ostringstream + ostream; + + int intValue = 1; + double doubleValue = 1.1; + float floatValue = 1.1f; + String stringValue = argumentInString; + + ostream << intValue; + RUNNER_ASSERT(!ostream.fail()); + ostream << doubleValue; + RUNNER_ASSERT(!ostream.fail()); + ostream << floatValue; + RUNNER_ASSERT(!ostream.fail()); + ostream << stringValue; + RUNNER_ASSERT(!ostream.fail()); + + RUNNER_ASSERT(ostream.str() == argumentResultString); +} + +/* +Name: String_Streams +Description: tests of input/output stream +Expected: returned substrign should match expected values +*/ +RUNNER_TEST(String_Streams) +{ + TestInStreams >("1 1.1 1.1 test", "test"); + TestInStreams >(L"1 1.1 1.1 test", L"test"); + TestInStreams(L"1 1.1 1.1 test", L"test"); + TestOutStreams >("test", "11.11.1test"); + TestOutStreams >(L"test", L"11.11.1test"); + TestOutStreams(L"test", L"11.11.1test"); +} + +/* +Name: String_CompareCaseSensitive +Description: tests case sensitive comparision +Expected: strings should be equal +*/ +RUNNER_TEST(String_CompareCaseSensitive) +{ + RUNNER_ASSERT( + DPL::StringCompare( + DPL::FromUTF32String(L"Ala Makota ma żołądkówkę"), + DPL::FromUTF32String(L"Ala Makota ma żołądkówkę")) == 0); +} + +/* +Name: String_CompareCaseInsensitive +Description: tests case insensitive comparision +Expected: strings should be equal +*/ +RUNNER_TEST(String_CompareCaseInsensitive) +{ + RUNNER_ASSERT( + DPL::StringCompare( + DPL::FromUTF32String(L"Ala Makota ma żołądkówkę"), + DPL::FromUTF32String(L"AlA MakOTA ma ŻoŁąDKÓwkę"), + true) == 0); +} + diff --git a/tests/core/test_thread.cpp b/tests/core/test_thread.cpp new file mode 100644 index 0000000..5db0dc1 --- /dev/null +++ b/tests/core/test_thread.cpp @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_thread.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of thread tests + */ +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +bool g_wasFooDeleted; + +class Foo +{ + public: + int id; + Foo(int i = 0) : id(i) + { + LogInfo("Foo: ctor: " << id); + } + + ~Foo() + { + LogInfo("Foo: dtor: " << id); + g_wasFooDeleted = true; + } + + void Bar() + { + LogInfo("Foo: bar"); + } +}; + +typedef DPL::ThreadLocalVariable TlsFoo; +TlsFoo g_foo; + +class FooThread : + public DPL::Thread +{ + protected: + virtual int ThreadEntry() + { + LogInfo("In thread"); + + RUNNER_ASSERT(!g_foo); + RUNNER_ASSERT(g_foo.IsNull()); + + g_foo = Foo(); + g_foo->Bar(); + + return 0; + } +}; + +/* +Name: Thread_ThreadLocalVariable_FooDeletion +Description: tests local thread variable pattern +Expected: local thread variables should not be affected by other threads +*/ +RUNNER_TEST(Thread_ThreadLocalVariable_FooDeletion) +{ + static TlsFoo staticFooForMain; + staticFooForMain = Foo(1); + + TlsFoo fooForMain; + fooForMain = Foo(2); + + RUNNER_ASSERT(!g_foo); + RUNNER_ASSERT(g_foo.IsNull()); + + g_wasFooDeleted = false; + + FooThread thread1; + thread1.Run(); + thread1.Quit(); + + RUNNER_ASSERT(!g_foo); + RUNNER_ASSERT(g_foo.IsNull()); + + RUNNER_ASSERT(g_wasFooDeleted == true); + + FooThread thread2; + thread2.Run(); + thread2.Quit(); + + RUNNER_ASSERT(!g_foo); + RUNNER_ASSERT(g_foo.IsNull()); +} diff --git a/tests/core/test_type_list.cpp b/tests/core/test_type_list.cpp new file mode 100644 index 0000000..b3e6285 --- /dev/null +++ b/tests/core/test_type_list.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/** + * @file test_type_list.cpp + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +/* +Name: TypeList_TypeCount +Description: tests size of typelist idiom +Expected: size should match +*/ +RUNNER_TEST(TypeList_TypeCount) +{ + typedef DPL::TypeListDecl::Type TestTypeList1; + typedef DPL::TypeListDecl::Type TestTypeList2; + typedef DPL::TypeListDecl<>::Type TestTypeList3; + typedef DPL::TypeList TestTypeList4; + + RUNNER_ASSERT(TestTypeList1::Size == 3); + RUNNER_ASSERT(TestTypeList2::Size == 1); + RUNNER_ASSERT(TestTypeList3::Size == 0); + RUNNER_ASSERT(TestTypeList4::Size == 4); + + RUNNER_ASSERT(TestTypeList4::Tail::Tail::Size == 2); +} diff --git a/tests/core/test_zip_input.cpp b/tests/core/test_zip_input.cpp new file mode 100644 index 0000000..c62accb --- /dev/null +++ b/tests/core/test_zip_input.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_zip_input.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of zip input tests + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +const char* PATH_NO_FILE = "/opt/share/wrt/wrt-commons/tests/core/no_such_file"; +const char* PATH_ARCHIVE = "/opt/share/wrt/wrt-commons/tests/core/sample.zip"; +const char* ARCHIVED_FILE = "sample.txt"; +} + +RUNNER_TEST_GROUP_INIT(DPL) + +/* +Name: ZipInput_OpenFailed +Description: tests opening non existing file +Expected: exception throw +*/ +RUNNER_TEST(ZipInput_OpenFailed) +{ + bool opened = true; + + Try + { + DPL::ZipInput zip(PATH_NO_FILE); + (void)zip; + } + Catch(DPL::ZipInput::Exception::OpenFailed) + { + opened = false; + } + + RUNNER_ASSERT(opened == false); +} + +/* +Name: ZipInput_OpenFile +Description: tests opening existing file +Expected: zip stats should mkatch expected +*/ +RUNNER_TEST(ZipInput_OpenFile) +{ + DPL::ZipInput zip(PATH_ARCHIVE); + + FOREACH(iter, zip) + { + LogDebug("---------"); + LogDebug("FileInfo: "); +#define FIELD(X) LogDebug(#X ": " << iter->X) + FIELD(name); + FIELD(comment); + FIELD(compressedSize); + FIELD(uncompressedSize); +#undef FIELD + } +} + +/* +Name: ZipInput_UnzipSingleFile +Description: tests opening existing file and unzipping single file +Expected: right content +*/ +RUNNER_TEST(ZipInput_UnzipSingleFile) +{ + DPL::ZipInput zip(PATH_ARCHIVE); + DPL::ZipInput::File *file = zip.OpenFile(ARCHIVED_FILE); + DPL::AbstractWaitableInputAdapter fileAdapter(file); + DPL::BinaryQueue buffer; + DPL::AbstractWaitableOutputAdapter bufferAdapter(&buffer); + + DPL::Copy(&fileAdapter, &bufferAdapter); + + DPL::ScopedArray data(new char[buffer.Size() + 1]); + buffer.Flatten(data.Get(), buffer.Size()); + data[buffer.Size()] = '\0'; + + RUNNER_ASSERT(std::string(data.Get()) == "test"); +} diff --git a/tests/dao/CMakeLists.txt b/tests/dao/CMakeLists.txt index 350431c..4028598 100644 --- a/tests/dao/CMakeLists.txt +++ b/tests/dao/CMakeLists.txt @@ -22,13 +22,12 @@ FILE(GLOB DAO_TESTS_SOURCES "${PROJECT_SOURCE_DIR}/tests/dao/*DAO.cpp") # target wrt-tests-dao -SET(TARGET_DAO_TEST "wrt-tests-dao") +SET(TARGET_DAO_TEST "wrt-commons-tests-dao") WRT_TEST_INCLUDE_DIRECTORIES(${TARGET_DAO_TEST} ${PROJECT_SOURCE_DIR}/modules/support/) WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_DAO_TEST} ${TARGET_WRT_DAO_RW_LIB} ${TARGET_CUSTOM_HANDLER_DAO_RW_LIB}) WRT_TEST_BUILD(${TARGET_DAO_TEST} ${DAO_TESTS_SOURCES} tests_dao.cpp) WRT_TEST_INSTALL(${TARGET_DAO_TEST}) - # common installed files INSTALL(PROGRAMS ${PROJECT_SOURCE_DIR}/tests/dao/wrt_dao_tests_prepare_db.sh diff --git a/tests/db/CMakeLists.txt b/tests/db/CMakeLists.txt new file mode 100644 index 0000000..837679e --- /dev/null +++ b/tests/db/CMakeLists.txt @@ -0,0 +1,49 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# 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. +# +# @file CMakeLists.txt +# @author Lukasz Marek (l.marek@samsung.com) +# @version 1.0 +# @brief +# + +# +# Test files +# +# Define all DPL tests sources. +# Runner is responsible for runnint it all and +# generating proper output files +# + +SET(TARGET_NAME "wrt-commons-tests-db") + +# Set DPL tests sources +SET(DPL_TESTS_DB_SOURCES + ${TESTS_DIR}/db/main.cpp + ${TESTS_DIR}/db/test_orm.cpp + ${TESTS_DIR}/db/test_sql_connection.cpp +) + +ADD_SUBDIRECTORY(orm) + +#include subdirectory +WRT_INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/orm) +WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_NAME} ${TARGET_DPL_DB_EFL}) +WRT_TEST_BUILD(${TARGET_NAME} ${DPL_TESTS_DB_SOURCES}) +WRT_TEST_INSTALL(${TARGET_NAME}) + +INSTALL(FILES + ${TESTS_DIR}/db/orm/dpl_orm_test.db + DESTINATION /opt/share/wrt/wrt-commons/tests/db +) diff --git a/tests/db/main.cpp b/tests/db/main.cpp new file mode 100644 index 0000000..4ed6191 --- /dev/null +++ b/tests/db/main.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/** + * @file main.cpp + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of main. + */ + +#include + +int main(int argc, char *argv[]) +{ + return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); +} diff --git a/tests/db/orm/CMakeLists.txt b/tests/db/orm/CMakeLists.txt new file mode 100644 index 0000000..b7ebafb --- /dev/null +++ b/tests/db/orm/CMakeLists.txt @@ -0,0 +1,11 @@ +WRT_INTROSPECT_TARGET(db ${TARGET_DPL_DB_EFL}) +WRT_CONVERT_TO_GCC_LIST(db_INCLUDE_DIRS_GCC ${db_INCLUDE_DIRS}) + +ADD_CUSTOM_COMMAND( OUTPUT dpl_orm_test_db.sql + COMMAND rm -f ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test.db + COMMAND C_INCLUDE_PATH=${db_INCLUDE_DIRS_GCC} gcc -Wall -E ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test_db_sql_generator.h | grep --invert-match "^#" > ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test_db.sql + COMMAND sqlite3 ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test.db ".read ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test_db.sql" || rm -f ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test.db + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test_db_sql_generator.h ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test_db +) + +ADD_CUSTOM_TARGET( Sqlite3Db ALL DEPENDS dpl_orm_test_db.sql ) diff --git a/tests/db/orm/dpl_orm_test_db b/tests/db/orm/dpl_orm_test_db new file mode 100644 index 0000000..0d1963b --- /dev/null +++ b/tests/db/orm/dpl_orm_test_db @@ -0,0 +1,88 @@ + +CREATE_TABLE(TestTableInsert) + COLUMN(ColumnOptInt, INT,) + COLUMN(ColumnOptText, TEXT,) + COLUMN_NOT_NULL(ColumnInt, INT, DEFAULT 99) + COLUMN_NOT_NULL(ColumnInt2, INT,) + COLUMN_NOT_NULL(ColumnText, TEXT,) +CREATE_TABLE_END() + +CREATE_TABLE(TestTableDelete) + COLUMN(ColumnOptInt, INT,) + COLUMN(ColumnOptText, TEXT,) + COLUMN_NOT_NULL(ColumnInt, INT, DEFAULT 99) + COLUMN_NOT_NULL(ColumnInt2, INT,) + COLUMN_NOT_NULL(ColumnText, TEXT,) +CREATE_TABLE_END() + +SQL( + INSERT INTO TestTableDelete VALUES(1, "two", 3, 4, "five"); + INSERT INTO TestTableDelete VALUES(6, "seven", 8, 9, "ten"); + INSERT INTO TestTableDelete (ColumnInt2, ColumnText) VALUES(11, "twelve"); + INSERT INTO TestTableDelete (ColumnInt2, ColumnText) VALUES(13, "fourteen"); +) + +CREATE_TABLE(TestTable) + COLUMN(ColumnOptInt, INT,) + COLUMN(ColumnOptText, TEXT,) + COLUMN_NOT_NULL(ColumnInt, INT, DEFAULT 99) + COLUMN_NOT_NULL(ColumnInt2, INT,) + COLUMN_NOT_NULL(ColumnText, TEXT,) +CREATE_TABLE_END() + +SQL( + INSERT INTO TestTable VALUES(1, "two", 3, 4, "five"); + INSERT INTO TestTable VALUES(6, "seven", 8, 9, "ten"); + INSERT INTO TestTable (ColumnInt2, ColumnText) VALUES(11, "twelve"); + INSERT INTO TestTable (ColumnInt2, ColumnText) VALUES(13, "fourteen"); +) + +CREATE_TABLE(TestTableJoin1) + COLUMN_NOT_NULL(TestID, INT,) + COLUMN_NOT_NULL(TestText, TEXT,) + COLUMN(TestNumber, INT,) + TABLE_CONSTRAINTS( + PRIMARY KEY(TestID) + ) +CREATE_TABLE_END() + +CREATE_TABLE(TestTableJoin2) + COLUMN_NOT_NULL(TestID, INT,) + COLUMN_NOT_NULL(TestText1, TEXT,) + COLUMN_NOT_NULL(TestText2, TEXT,) + TABLE_CONSTRAINTS( + PRIMARY KEY(TestID) + ) +CREATE_TABLE_END() + +CREATE_TABLE(TestTableJoin3) + COLUMN_NOT_NULL(TestID, INT,) + COLUMN(Value3, INT,) + COLUMN(TestText33, TEXT,) + TABLE_CONSTRAINTS( + PRIMARY KEY(TestID) + ) +CREATE_TABLE_END() + +SQL( + INSERT INTO TestTableJoin1 VALUES(1, "text val 1", 111); + INSERT INTO TestTableJoin1 VALUES(2, "text val 2", 222); + INSERT INTO TestTableJoin1 VALUES(3, "text val 3", 333); + INSERT INTO TestTableJoin1 VALUES(4, "text val 4", 444); + INSERT INTO TestTableJoin1 VALUES(5, "text val 5", 555); + INSERT INTO TestTableJoin1 VALUES(6, "text val 6", 666); + + INSERT INTO TestTableJoin2 VALUES(1, "01", "text2 1"); + INSERT INTO TestTableJoin2 VALUES(2, "02", "text2 2"); + INSERT INTO TestTableJoin2 VALUES(3, "03", "text2 3"); + INSERT INTO TestTableJoin2 VALUES(4, " 4 ", "text2 4"); + INSERT INTO TestTableJoin2 VALUES(5, "*5*", "text2 5"); + INSERT INTO TestTableJoin2 VALUES(10, "6", "text2 6"); + + INSERT INTO TestTableJoin3 VALUES(1, 111, "test 1"); + INSERT INTO TestTableJoin3 VALUES(2, 111, "test 2"); + INSERT INTO TestTableJoin3 VALUES(3, 222, "test 3"); + INSERT INTO TestTableJoin3 VALUES(6, 222, "test 4"); + INSERT INTO TestTableJoin3 (TestID, TestText33) VALUES(7, "test 5"); + INSERT INTO TestTableJoin3 (TestID, TestText33) VALUES(10, "test 6"); +) diff --git a/tests/db/orm/dpl_orm_test_db_definitions b/tests/db/orm/dpl_orm_test_db_definitions new file mode 100644 index 0000000..da79427 --- /dev/null +++ b/tests/db/orm/dpl_orm_test_db_definitions @@ -0,0 +1,5 @@ +DATABASE_START(dpl_orm_test) + +#include "dpl_orm_test_db" + +DATABASE_END() diff --git a/tests/db/orm/dpl_orm_test_db_sql_generator.h b/tests/db/orm/dpl_orm_test_db_sql_generator.h new file mode 100644 index 0000000..cac41cc --- /dev/null +++ b/tests/db/orm/dpl_orm_test_db_sql_generator.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file dpl_orm_test_db_sql_generator.h + * @author Lukasz Marek (l.marek@samsung.com) + * @version 1.0 + * @brief Macro definitions for generating the SQL input file from + * database definition. + */ + +//Do not include this file directly! It is used only for SQL code generation. + +#include + +#include "dpl_orm_test_db_definitions" diff --git a/tests/db/orm/dpl_orm_test_db_sql_generator.h.gch b/tests/db/orm/dpl_orm_test_db_sql_generator.h.gch new file mode 100644 index 0000000..5bd675d Binary files /dev/null and b/tests/db/orm/dpl_orm_test_db_sql_generator.h.gch differ diff --git a/tests/db/orm/generator_dpl_orm_test.h b/tests/db/orm/generator_dpl_orm_test.h new file mode 100644 index 0000000..39bb1b7 --- /dev/null +++ b/tests/db/orm/generator_dpl_orm_test.h @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ + +#ifndef ORM_GENERATOR_DPL_ORM_TEST_H +#define ORM_GENERATOR_DPL_ORM_TEST_H + +#define ORM_GENERATOR_DATABASE_NAME dpl_orm_test_db_definitions +#include +#undef ORM_GENERATOR_DATABASE_NAME + +#endif diff --git a/tests/db/test_orm.cpp b/tests/db/test_orm.cpp new file mode 100644 index 0000000..500f43d --- /dev/null +++ b/tests/db/test_orm.cpp @@ -0,0 +1,1140 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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 +#include +#include +#include +#include + +const char* PATH_DB = "/opt/share/wrt/wrt-commons/tests/db/dpl_orm_test.db"; + +//utils + +#define TEST_REPETITION 16 + +class SmartAttach +{ + public: + + SmartAttach(bool autoattach = true) : + m_interface(PATH_DB, + DPL::DB::SqlConnection::Flag::UseLucene), + m_autoattach(autoattach) + { + if (m_autoattach) { + m_interface.AttachToThread(DPL::DB::SqlConnection::Flag::RW); + } + } + + ~SmartAttach() + { + if (m_autoattach) { + m_interface.DetachFromThread(); + } + } + + DPL::DB::ThreadDatabaseSupport* get() + { + return &m_interface; + } + + private: + DPL::DB::ThreadDatabaseSupport m_interface; + bool m_autoattach; +}; + +template +bool ContainerContentsEqual(const ContainerType1& container1, + const ContainerType2& container2) +{ + using namespace DPL::DB::ORM::dpl_orm_test::TestTableInsert; + typedef std::set Set1; + typedef std::set Set2; + Set1 set1(container1.begin(), container1.end()); + Set2 set2(container2.begin(), container2.end()); + + for (typename Set1::iterator it = set1.begin(); + it != set1.end(); + it++) + { + LogDebug("Set1 element: " << *it); + } + + for (typename Set2::iterator it = set2.begin(); it != set2.end(); it++) { + LogDebug("Set2 element: " << *it); + } + + return set1 == set2; +} + +template +std::list makeList(const T& a, const T& b) +{ + std::list list; + list.push_back(a); + list.push_back(b); + return list; +} + +//tests + +RUNNER_TEST_GROUP_INIT(DPL) + +/* +Name: ORM_SelectSingleValue +Description: tests quering single value of single row from database +Expected: Values should match those which were prepared +*/ +RUNNER_TEST(ORM_SelectSingleValue) +{ + SmartAttach interface; + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::dpl_orm_test; + //Getting each column + { + TestTable::Select select(interface.get()); + select.Where(Equals(8)); + int result; + RUNNER_ASSERT_MSG((result = + *select.GetSingleValue()) + == 6, "Got " << + result); + } + { + TestTable::Select select(interface.get()); + select.Where(Equals(8)); + DPL::String result; + RUNNER_ASSERT_MSG((result = + *select.GetSingleValue( + )) == L"seven", + "Got " << result); + } + { + TestTable::Select select(interface.get()); + select.Where(Equals(8)); + int result; + RUNNER_ASSERT_MSG((result = select.GetSingleValue( + )) == 8, "Got " << result); + } + { + TestTable::Select select(interface.get()); + select.Where(Equals(8)); + int result; + RUNNER_ASSERT_MSG((result = select.GetSingleValue( + )) == 9, "Got " << result); + } + { + TestTable::Select select(interface.get()); + select.Where(Equals(8)); + DPL::String result; + RUNNER_ASSERT_MSG((result = select.GetSingleValue( + )) == L"ten", "Got " << result); + } + + //Where on each column + { + TestTable::Select select(interface.get()); + select.Where(Equals(6)); + int result; + RUNNER_ASSERT_MSG((result = + *select.GetSingleValue()) + == 6, "Got " << + result); + } + { + TestTable::Select select(interface.get()); + select.Where(Equals(DPL::String(L"seven"))); + DPL::String result; + RUNNER_ASSERT_MSG((result = + *select.GetSingleValue( + )) == L"seven", + "Got " << result); + } + { + TestTable::Select select(interface.get()); + select.Where(Equals(8)); + int result; + RUNNER_ASSERT_MSG((result = select.GetSingleValue( + )) == 8, "Got " << result); + } + { + TestTable::Select select(interface.get()); + select.Where(Equals(9)); + int result; + RUNNER_ASSERT_MSG((result = select.GetSingleValue( + )) == 9, "Got " << result); + } + { + TestTable::Select select(interface.get()); + select.Where(Equals(L"ten")); + DPL::String result; + RUNNER_ASSERT_MSG((result = select.GetSingleValue( + )) == L"ten", "Got " << result); + } +} + +/* +Name: ORM_SelectSingleRow +Description: tests quering single row from database +Expected: Values should match those which were prepared +*/ +RUNNER_TEST(ORM_SelectSingleRow) +{ + SmartAttach interface; + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::dpl_orm_test; + { + TestTable::Select select(interface.get()); + select.Where(Equals(3)); + TestTable::Row result = select.GetSingleRow(); + TestTable::Row expected; + expected.Set_ColumnOptInt(1); + expected.Set_ColumnOptText(DPL::String(L"two")); + expected.Set_ColumnInt(3); + expected.Set_ColumnInt2(4); + expected.Set_ColumnText(L"five"); + RUNNER_ASSERT_MSG(result == expected, "Got " << result); + } + + { + TestTable::Select select(interface.get()); + select.Where(Equals(DPL::String(L"seven"))); + TestTable::Row result = select.GetSingleRow(); + TestTable::Row expected; + expected.Set_ColumnOptInt(6); + expected.Set_ColumnOptText(DPL::String(L"seven")); + expected.Set_ColumnInt(8); + expected.Set_ColumnInt2(9); + expected.Set_ColumnText(L"ten"); + RUNNER_ASSERT_MSG(result == expected, "Got " << result); + } +} + +/* +Name: ORM_SelectRowList +Description: tests quering multiple row from database +Expected: Values should match those which were prepared +*/ +RUNNER_TEST(ORM_SelectRowList) +{ + SmartAttach interface; + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::dpl_orm_test; + { + TestTable::Select select(interface.get()); + select.Where(Equals(3)); + std::list result = select.GetRowList(); + RUNNER_ASSERT_MSG(result.size() == 1, "Got " << result.size()); + + TestTable::Row expected; + expected.Set_ColumnOptInt(1); + expected.Set_ColumnOptText(DPL::String(L"two")); + expected.Set_ColumnInt(3); + expected.Set_ColumnInt2(4); + expected.Set_ColumnText(L"five"); + RUNNER_ASSERT_MSG(*(result.begin()) == expected, "Got " << + *(result.begin()) ); + } + + { + TestTable::Select select(interface.get()); + select.Where(Equals(DPL::String(L"seven"))); + std::list result = select.GetRowList(); + RUNNER_ASSERT_MSG(result.size() == 1, "Got " << result.size()); + + TestTable::Row expected; + expected.Set_ColumnOptInt(6); + expected.Set_ColumnOptText(DPL::String(L"seven")); + expected.Set_ColumnInt(8); + expected.Set_ColumnInt2(9); + expected.Set_ColumnText(L"ten"); + RUNNER_ASSERT_MSG(*(result.begin()) == expected, "Got " << + *(result.begin()) ); + } + + { + TestTable::Select select(interface.get()); + select.Where(Equals(99)); + std::list result = select.GetRowList(); + + TestTable::Row expected1; + expected1.Set_ColumnInt(99); + expected1.Set_ColumnInt2(11); + expected1.Set_ColumnText(L"twelve"); + + TestTable::Row expected2; + expected2.Set_ColumnInt(99); + expected2.Set_ColumnInt2(13); + expected2.Set_ColumnText(L"fourteen"); + + RUNNER_ASSERT(ContainerContentsEqual(makeList(expected1, + expected2), result)); + } +} + +/* +Name: ORM_SelectValueList +Description: tests quering single column from multiple row from database +Expected: Values should match those which were prepared +*/ +RUNNER_TEST(ORM_SelectValueList) +{ + SmartAttach interface; + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::dpl_orm_test; + //Getting each column + { + TestTable::Select select(interface.get()); + select.Where(Is(DPL::Optional::Null)); + RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), + makeList(99, 99))); + } + { + TestTable::Select select(interface.get()); + select.Where(Is(DPL::Optional::Null)); + RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), + makeList(11, 13))); + } + { + TestTable::Select select(interface.get()); + select.Where(Is(DPL::Optional::Null)); + RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), + makeList(DPL::String(L"twelve"), + DPL::String(L"fourteen")))); + } + { + TestTable::Select select(interface.get()); + select.Where(Is(DPL::Optional::Null)); + RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), + makeList(DPL::Optional + ::Null, + DPL::Optional + ::Null))); + } + + //Where on each column + { + TestTable::Select select(interface.get()); + select.Where(Is(DPL::Optional::Null)); + RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), + makeList(11, 13))); + } + { + TestTable::Select select(interface.get()); + select.Where(Is(DPL::Optional:: + Null)); + RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), + makeList(11, 13))); + } + { + TestTable::Select select(interface.get()); + select.Where(Is(99)); + RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), + makeList(11, 13))); + } +} + +/* +Name: ORM_MultipleCalls +Description: tests sequnece of different queries +Expected: Values should match those which were prepared +*/ +RUNNER_TEST(ORM_MultipleCalls) +{ + for (int j = 0; j < TEST_REPETITION; j++) { + for (int i = 0; i < TEST_REPETITION; i++) { + ORM_SelectSingleValue(); + } + + for (int i = 0; i < TEST_REPETITION; i++) { + ORM_SelectSingleRow(); + } + + for (int i = 0; i < TEST_REPETITION; i++) { + ORM_SelectRowList(); + } + + for (int i = 0; i < TEST_REPETITION; i++) { + ORM_SelectValueList(); + } + } +} + +/* +Name: ORM_Insert +Description: tests insering rows into database +Expected: Values should be inserted +*/ +RUNNER_TEST(ORM_Insert) +{ + SmartAttach interface; + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::dpl_orm_test; + + TestTableInsert::Select select1(interface.get()); + std::list resultList = select1.GetValueList(); + RUNNER_ASSERT_MSG(resultList.empty(), + "Returned list has wrong size: " << resultList.size()); + + std::list list; + + TestTableInsert::Insert insert(interface.get()); + TestTableInsert::Row row; + row.Set_ColumnOptInt(1); + row.Set_ColumnInt2(2); + row.Set_ColumnText(L"three"); + insert.Values(row); + insert.Execute(); + + row.Set_ColumnInt(99); + list.push_back(row); + { + TestTableInsert::Select select2(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select2.GetRowList(), + list), "Returned list doesn't match."); + } + + TestTableInsert::Insert insert2(interface.get()); + TestTableInsert::Row row2; + row2.Set_ColumnInt(4); + row2.Set_ColumnInt2(5); + row2.Set_ColumnText(L"six"); + insert2.Values(row2); + insert2.Execute(); + + list.push_back(row2); + { + TestTableInsert::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select.GetRowList(), + list), "Returned list doesn't match."); + } + + TestTableInsert::Insert insert3(interface.get()); + TestTableInsert::Row row3; + row3.Set_ColumnOptInt(1); + row3.Set_ColumnInt2(7); + row3.Set_ColumnText(L"eight"); + insert3.Values(row3); + insert3.Execute(); + + row3.Set_ColumnInt(99); + list.push_back(row3); + { + TestTableInsert::Select select3(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select3.GetRowList(), + list), "Returned list doesn't match."); + } + + TestTableInsert::Insert insert4(interface.get()); + TestTableInsert::Row row4; + row4.Set_ColumnOptInt(9); + row4.Set_ColumnInt2(10); + row4.Set_ColumnText(L"eleven"); + insert4.Values(row4); + insert4.Execute(); + + row4.Set_ColumnInt(99); + list.push_back(row4); + { + TestTableInsert::Select select4(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select4.GetRowList(), + list), "Returned list doesn't match."); + } + + // restore original table state + { + TestTableInsert::Delete del(interface.get()); + del.Execute(); + + TestTableInsert::Select select(interface.get()); + RUNNER_ASSERT(select.GetRowList().size() == 0); + } +} + +/* +Name: ORM_MultipleBindInsert +Description: repeats ORM_Insert test several times +Expected: Values should be inserted +*/ +RUNNER_TEST(ORM_MultipleBindInsert) +{ + for (int i = 0; i < TEST_REPETITION; i++) { + ORM_Insert(); + } +} + +/* +Name: ORM_Delete +Description: tests deleting rows from database +Expected: deleted rows should not exist +*/ +RUNNER_TEST(ORM_Delete) +{ + SmartAttach interface; + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::dpl_orm_test; + TestTableDelete::Select selectStart(interface.get()); + selectStart.OrderBy(DPL::TypeListDecl >()); + std::list list = selectStart.GetRowList(); + std::list originalList = list; + + std::vector vector(list.begin(), list.end()); + RUNNER_ASSERT_MSG( + list.size() == 4, "Returned list has wrong size: " << list.size()); + + typedef DPL::String S; + + //no-act deletes + { + TestTableDelete::Delete del(interface.get()); + del.Where(And(Equals(1), + Equals(S(L"seven")))); + del.Execute(); + + TestTableDelete::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select.GetRowList(), + list), "Returned list doesn't match."); + } + + { + TestTableDelete::Delete del(interface.get()); + del.Where(And(Equals(6), + Equals(S(L"two")))); + del.Execute(); + + TestTableDelete::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select.GetRowList(), + list), "Returned list doesn't match."); + } + + { + TestTableDelete::Delete del(interface.get()); + del.Where(Equals(10)); + del.Execute(); + + TestTableDelete::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select.GetRowList(), + list), "Returned list doesn't match."); + } + + //act deletes + { + list.remove(vector[1]); + + TestTableDelete::Delete del(interface.get()); + del.Where(And(Equals(6), + Equals(L"ten"))); + del.Execute(); + + TestTableDelete::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select.GetRowList(), + list), "Returned list doesn't match."); + } + + { + list.remove(vector[2]); + list.remove(vector[3]); + + TestTableDelete::Delete del(interface.get()); + del.Where(Is(DPL::Optional + ::Null)); + del.Execute(); + + TestTableDelete::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select.GetRowList(), + list), "Returned list doesn't match."); + } + + { + TestTableDelete::Delete del(interface.get()); + del.Execute(); + + TestTableDelete::Select select(interface.get()); + RUNNER_ASSERT_MSG( + select.GetRowList().size() == 0, "Returned list is not empty"); + } + + // Restore original table state + // This also tests if multiple different binds for Insert are working + // properly + for (std::list::iterator i = originalList.begin(); + i != originalList.end(); + i++) + { + TestTableDelete::Insert insert(interface.get()); + insert.Values(*i); + insert.Execute(); + } + + { + TestTableDelete::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select.GetRowList(), + originalList), + "Returned list doesn't match."); + } +} + +/* +Name: ORM_MultipleBindDelete +Description: repeats ORM_Delete test several times +Expected: Values should be deleted +*/ +RUNNER_TEST(ORM_MultipleBindDelete) +{ + for (int i = 0; i < TEST_REPETITION; i++) { + ORM_Delete(); + } +} + +/* +Name: ORM_MultipleBindWhere +Description: tests if multiple bind of same query obejct works +Expected: Each bind and execution of query should be correct +*/ +RUNNER_TEST(ORM_MultipleBindWhere) +{ + SmartAttach interface; + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::dpl_orm_test; + { + TestTable::Select select(interface.get()); + int result; + select.Where(Equals(8)); + RUNNER_ASSERT_MSG((result = + *select.GetSingleValue()) + == 6, "Got " << + result); + + select.Where(Equals(3)); + RUNNER_ASSERT_MSG((result = + *select.GetSingleValue()) + == 1, "Got " << + result); + + select.Where(Equals(8)); + RUNNER_ASSERT_MSG((result = + *select.GetSingleValue()) + == 6, "Got " << + result); + + select.Where(Equals(3)); + RUNNER_ASSERT_MSG((result = + *select.GetSingleValue()) + == 1, "Got " << + result); + } + + { + TestTable::Select select(interface.get()); + int result; + select.Where(And(Equals(99), + Equals(L"fourteen"))); + RUNNER_ASSERT_MSG((result = select.GetSingleValue( + )) == 13, "Got " << result); + + select.Where(And(Equals(99), + Equals(L"twelve"))); + RUNNER_ASSERT_MSG((result = select.GetSingleValue( + )) == 11, "Got " << result); + + select.Where(And(Equals(99), + Equals(L"fourteen"))); + RUNNER_ASSERT_MSG((result = select.GetSingleValue( + )) == 13, "Got " << result); + + select.Where(And(Equals(99), + Equals(L"twelve"))); + RUNNER_ASSERT_MSG((result = select.GetSingleValue( + )) == 11, "Got " << result); + } + + { + TestTable::Select select(interface.get()); + int result; + select.Where(And(Equals(L"fourteen"), + Equals(99))); + RUNNER_ASSERT_MSG((result = select.GetSingleValue( + )) == 13, "Got " << result); + + select.Where(And(Equals(L"twelve"), + Equals(99))); + RUNNER_ASSERT_MSG((result = select.GetSingleValue( + )) == 11, "Got " << result); + + select.Where(And(Equals(L"fourteen"), + Equals(99))); + RUNNER_ASSERT_MSG((result = select.GetSingleValue( + )) == 13, "Got " << result); + + select.Where(And(Equals(L"twelve"), + Equals(99))); + RUNNER_ASSERT_MSG((result = select.GetSingleValue( + )) == 11, "Got " << result); + } +} + +/* +Name: ORM_Update +Description: tests rows update in database +Expected: Successful update +*/ +RUNNER_TEST(ORM_Update) +{ + SmartAttach interface; + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::dpl_orm_test; + + std::list list; + + TestTableInsert::Delete del(interface.get()); + del.Execute(); + + // INSERT + { + TestTableInsert::Insert insert(interface.get()); + TestTableInsert::Row row; + row.Set_ColumnOptInt(5); + row.Set_ColumnInt2(2); + row.Set_ColumnText(L"two"); + insert.Values(row); + insert.Execute(); + + row.Set_ColumnInt(99); + list.push_back(row); + } + { + TestTableInsert::Insert insert(interface.get()); + TestTableInsert::Row row; + row.Set_ColumnOptInt(1); + row.Set_ColumnInt2(2); + row.Set_ColumnText(L"three"); + insert.Values(row); + insert.Execute(); + + row.Set_ColumnInt(99); + list.push_back(row); + } + { + TestTableInsert::Insert insert(interface.get()); + TestTableInsert::Row row; + row.Set_ColumnOptInt(2); + row.Set_ColumnInt2(3); + row.Set_ColumnText(L"three"); + insert.Values(row); + insert.Execute(); + + row.Set_ColumnInt(99); + list.push_back(row); + + // CHECK + TestTableInsert::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select.GetRowList(), + list), "Returned list doesn't match."); + } + { + // UPDATE - no rows + TestTableInsert::Update update(interface.get()); + TestTableInsert::Row row; + row.Set_ColumnInt2(4); + row.Set_ColumnText(L"four"); + update.Values(row); + update.Where(Equals(12)); + update.Execute(); + + // CHECK + TestTableInsert::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select.GetRowList(), + list), "Returned list doesn't match."); + } + { + // UPDATE - one row + TestTableInsert::Update update(interface.get()); + TestTableInsert::Row row; + row.Set_ColumnInt2(2); + row.Set_ColumnText(L"four"); + update.Values(row); + update.Where(Equals(3)); + update.Execute(); + + list.back().Set_ColumnInt2(2); + list.back().Set_ColumnText(L"four"); + + // CHECK + TestTableInsert::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select.GetRowList(), + list), "Returned list doesn't match."); + } + + { + // UPDATE - multiple rows + TestTableInsert::Update update(interface.get()); + TestTableInsert::Row row; + row.Set_ColumnText(L"dup"); + update.Values(row); + update.Where(Equals(2)); + update.Execute(); + + FOREACH(it, list) + { + it->Set_ColumnText(L"dup"); + } + + // CHECK + TestTableInsert::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select.GetRowList(), + list), "Returned list doesn't match."); + } + + // restore original table state + { + TestTableInsert::Delete del2(interface.get()); + del2.Execute(); + + TestTableInsert::Select select(interface.get()); + RUNNER_ASSERT(select.GetRowList().size() == 0); + } +} + +/* +Name: ORM_MultipleBindUpdate +Description: repeats ORM_Update severl times +Expected: Successful update +*/ +RUNNER_TEST(ORM_MultipleBindUpdate) +{ + for (int i = 0; i < TEST_REPETITION; i++) { + ORM_Update(); + } +} + +/* +Name: ORM_transactions +Description: checks creation of transation object +Expected: Successful creation of transaction object +*/ +RUNNER_TEST(ORM_transactions) +{ + SmartAttach interface; + DPL::DB::ORM::dpl_orm_test::ScopedTransaction transaction(interface.get()); +} + +/* +Name: ORM_MultiAttach +Description: checks correct behaviou in case of multiple tries to attach to database +Expected: Methods attaching/dettaching should be prepared for multiple calling +*/ +RUNNER_TEST(ORM_MultiAttach) +{ + SmartAttach interface(false); + RUNNER_ASSERT_MSG( + !interface.get()->IsAttached(), "Is attached, but shouldn't be."); + interface.get()->AttachToThread(); + RUNNER_ASSERT_MSG( + interface.get()->IsAttached(), "Isn't attached, but should be."); + interface.get()->AttachToThread(); + RUNNER_ASSERT_MSG( + interface.get()->IsAttached(), "Isn't attached, but should be."); + interface.get()->DetachFromThread(); + RUNNER_ASSERT_MSG( + interface.get()->IsAttached(), "Isn't attached, but should be."); + interface.get()->DetachFromThread(); + RUNNER_ASSERT_MSG( + !interface.get()->IsAttached(), "Is attached, but shouldn't be."); +} + +/* +Name: ORM_Join +Description: tests ORM's join operation +Expected: values should insist correct join operation +*/ +RUNNER_TEST(ORM_Join) +{ + SmartAttach interface; + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::dpl_orm_test; + + typedef DPL::TypeListDecl::Type JoinColumns; + + /* Test for correct join: + * 5 ids from first table matches 5 ids from second table thus join result + * contains 5 rows */ + TestTableJoin1::Select select(interface.get()); + select.Join(Equal()); + std::list > rowlist = + select.GetCustomRowList >(); + + RUNNER_ASSERT_MSG( + rowlist.size() == 5, "Invalid number of rows fetched: " << rowlist.size()); + + std::string text; + std::ostringstream oss; + int cnt = 0; + FOREACH(rowit, rowlist) + { + cnt++; + + text = + DPL::ToUTF8String((*rowit).GetColumnData()); + oss << "text val " << cnt; + RUNNER_ASSERT_MSG(text.compare( + oss.str()) == 0, + "Invalid value from first column: " + << text << " expected: " << oss.str()); + oss.str(std::string()); + + text = + DPL::ToUTF8String((*rowit).GetColumnData()); + oss << "text2 " << cnt; + RUNNER_ASSERT_MSG(text.compare( + oss.str()) == 0, + "Invalid value from second column: " + << text << " expected: " << oss.str()); + oss.str(std::string()); + } + /* Test for empty join: + * None of number values from first table matches ids from second table + * - join result should be empty */ + TestTableJoin1::Select select2(interface.get()); + select2.Join(Equal()); + rowlist = select2.GetCustomRowList >(); + + RUNNER_ASSERT_MSG(rowlist.empty(), "Result should be empty but it is not!"); + + /* Test for "converted" join: + * - join made with int column and text column as keys + * - expected 5 matching rows (one row of 6 should not be matched)*/ + TestTableJoin1::Select select3(interface.get()); + select3.Join(Equal()); + rowlist = select3.GetCustomRowList >(); + RUNNER_ASSERT_MSG( + rowlist.size() == 5, "Expected 5 rows while received: " << rowlist.size()); + cnt = 0; + FOREACH(rowit, rowlist) + { + cnt++; + // look at last two insertions into TestTableJoin2 + // for this skip understanding + if (cnt == 5) { + cnt = 6; + } + text = + DPL::ToUTF8String((*rowit).GetColumnData()); + oss << "text val " << cnt; + RUNNER_ASSERT_MSG(text.compare( + oss.str()) == 0, + "Invalid value from first column: " + << text << " expected: " << oss.str() << + " iteration: " << cnt); + oss.str(std::string()); + + text = + DPL::ToUTF8String((*rowit).GetColumnData()); + oss << "text2 " << cnt; + RUNNER_ASSERT_MSG(text.compare( + oss.str()) == 0, + "Invalid value from second column: " + << text << " expected: " << oss.str() << + " iteration: " << cnt); + oss.str(std::string()); + } + + /* Test for join with non-unique nullable columns given as keys*/ + typedef DPL::TypeListDecl::Type JoinTables2; + TestTableJoin1::Select select4(interface.get()); + select4.Join(Equal()); + std::list > rowlist2 = + select4.GetCustomRowList >(); + RUNNER_ASSERT_MSG( + rowlist2.size() == 4, "Expected 4 rows while received: " << + rowlist.size()); + cnt = 0; + DPL::Optional optext; + FOREACH(rowit, rowlist2) + { + cnt++; + + text = + DPL::ToUTF8String((*rowit).GetColumnData()); + // values expected in subsequent (1,2,3,4) iterations: 1 1 2 2 + oss << "text val " << (1 + (int)(cnt / 3)); + RUNNER_ASSERT_MSG(text.compare( + oss.str()) == 0, + "Invalid value from first column: " + << text << " expected: " << oss.str() << + " iteration: " << cnt); + oss.str(std::string()); + + optext = (*rowit).GetColumnData(); + text = DPL::ToUTF8String(*optext); + oss << "test " << cnt; + RUNNER_ASSERT_MSG(text.compare( + oss.str()) == 0, + "Invalid value from second column: " + << text << " expected: " << oss.str() << + " iteration: " << cnt); + oss.str(std::string()); + } + + /* Test for join made on three tables: + * - 3 text columns selected for join + * - Equal made for TestID of (table1 and table2) and (table1 and table3) */ + typedef DPL::TypeListDecl::Type Join3Tables; + TestTableJoin1::Select select5(interface.get()); + select5.Join(Equal()); + select5.Join(Equal()); + std::list > rowlist3tab = + select5.GetCustomRowList >(); + RUNNER_ASSERT_MSG( + rowlist3tab.size() == 3, "Expected 3 rows while received: " << + rowlist3tab.size()); + cnt = 0; + FOREACH(rowit, rowlist3tab) + { + cnt++; + + text = + DPL::ToUTF8String((*rowit).GetColumnData()); + oss << "text val " << cnt; + RUNNER_ASSERT_MSG(text.compare( + oss.str()) == 0, + "Invalid value from first column: " + << text << " expected: " << oss.str() << + " iteration: " << cnt); + oss.str(std::string()); + + text = + DPL::ToUTF8String((*rowit).GetColumnData()); + oss << "text2 " << cnt; + RUNNER_ASSERT_MSG(text.compare( + oss.str()) == 0, + "Invalid value from first column: " + << text << " expected: " << oss.str() << + " iteration: " << cnt); + oss.str(std::string()); + + optext = (*rowit).GetColumnData(); + text = DPL::ToUTF8String(*optext); + oss << "test " << cnt; + RUNNER_ASSERT_MSG(text.compare( + oss.str()) == 0, + "Invalid value from second column: " + << text << " expected: " << oss.str() << + " iteration: " << cnt); + oss.str(std::string()); + } +} + +RUNNER_TEST(ORM_SelectOrderByMultipleColumns) +{ + SmartAttach interface; + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::dpl_orm_test; + { + TestTableJoin3::Select select(interface.get()); + + // testing: " ORDER BY Value3 ASC, TestID DESC, TestID ASC" + select.OrderBy(DPL::TypeListDecl, + OrderingDescending, + OrderingAscending >()); + + std::list result = select.GetRowList(); + std::list::const_iterator iter = result.begin(); + { //1 row + RUNNER_ASSERT_MSG(*iter->Get_TestText33() == + DPL::FromASCIIString( + "test 6"), "Wrong row 1 order"); + RUNNER_ASSERT_MSG(iter->Get_TestID() == 10, "Wrong row 1 order"); + iter++; + } + { //2 row + RUNNER_ASSERT_MSG(*iter->Get_TestText33() == + DPL::FromASCIIString( + "test 5"), "Wrong row 2 order"); + RUNNER_ASSERT_MSG(iter->Get_TestID() == 7, "Wrong row 2 order"); + iter++; + } + { //3 row + RUNNER_ASSERT_MSG(iter->Get_Value3() == 111, "Wrong row 3 order"); + RUNNER_ASSERT_MSG(*iter->Get_TestText33() == + DPL::FromASCIIString( + "test 2"), "Wrong row 3 order"); + RUNNER_ASSERT_MSG(iter->Get_TestID() == 2, "Wrong row 3 order"); + iter++; + } + { //4 row + RUNNER_ASSERT_MSG(iter->Get_Value3() == 111, "Wrong row 4 order"); + RUNNER_ASSERT_MSG(*iter->Get_TestText33() == + DPL::FromASCIIString( + "test 1"), "Wrong row 4 order"); + RUNNER_ASSERT_MSG(iter->Get_TestID() == 1, "Wrong row 4 order"); + iter++; + } + { //5 row + RUNNER_ASSERT_MSG(iter->Get_Value3() == 222, "Wrong row 5 order"); + RUNNER_ASSERT_MSG(*iter->Get_TestText33() == + DPL::FromASCIIString( + "test 4"), "Wrong row 5 order"); + RUNNER_ASSERT_MSG(iter->Get_TestID() == 6, "Wrong row 5 order"); + iter++; + } + { //6 row + RUNNER_ASSERT_MSG(iter->Get_Value3() == 222, "Wrong row 6 order"); + RUNNER_ASSERT_MSG(*iter->Get_TestText33() == + DPL::FromASCIIString( + "test 3"), "Wrong row 6 order"); + RUNNER_ASSERT_MSG(iter->Get_TestID() == 3, "Wrong row 6 order"); + iter++; + } + } +} diff --git a/tests/db/test_sql_connection.cpp b/tests/db/test_sql_connection.cpp new file mode 100644 index 0000000..0f37b2d --- /dev/null +++ b/tests/db/test_sql_connection.cpp @@ -0,0 +1,248 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_sql_connection.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of sql connection tests + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern const char* PATH_DB; + +RUNNER_TEST_GROUP_INIT(DPL) + +class AbstractSynchronizationObjectGenerator +{ + public: + virtual ~AbstractSynchronizationObjectGenerator() {} + + virtual DPL::DB::SqlConnection::SynchronizationObject *Create() = 0; +}; + +class NaiveSynchronizationObjectGenerator : + public AbstractSynchronizationObjectGenerator +{ + public: + virtual DPL::DB::SqlConnection::SynchronizationObject *Create() + { + return new DPL::DB::NaiveSynchronizationObject(); + } +}; + +void MassiveReadWriteTest(AbstractSynchronizationObjectGenerator *generator); + +class StressGenerator : + public DPL::Thread +{ + private: + size_t m_prefix; + std::string m_dbFileName; + AbstractSynchronizationObjectGenerator *m_generator; + + protected: + virtual int ThreadEntry() + { + DPL::DB::SqlConnection connection( + m_dbFileName, + DPL::DB::SqlConnection::Flag::None, + DPL::DB::SqlConnection::Flag::RW, + m_generator->Create()); + + DPL::DB::SqlConnection::DataCommandAutoPtr countCommand = + connection.PrepareDataCommand( + "SELECT COUNT(*) FROM test WHERE value=?"); + + for (size_t i = 0; i < 10; ++i) { + std::ostringstream valueStream; + + valueStream << "value_"; + valueStream << static_cast(m_prefix); + valueStream << "_"; + valueStream << static_cast(i); + + std::string value = valueStream.str(); + + connection.ExecCommand( + "INSERT INTO test VALUES ('%s');", + value.c_str()); + + countCommand->BindString(1, value.c_str()); + + RUNNER_ASSERT(countCommand->Step()); + + RUNNER_ASSERT(countCommand->GetColumnString(0) == "1"); + + countCommand->Reset(); + } + + countCommand.reset(); + + return 0; + } + + public: + StressGenerator(size_t prefix, + const std::string &dbFileName, + AbstractSynchronizationObjectGenerator *generator) : + m_prefix(prefix), + m_dbFileName(dbFileName), + m_generator(generator) + {} +}; + +typedef std::shared_ptr ThreadPtr; + +void MassiveReadWriteTest(AbstractSynchronizationObjectGenerator *generator) +{ + DPL::DB::SqlConnection connection(PATH_DB, + DPL::DB::SqlConnection::Flag::UseLucene, + DPL::DB::SqlConnection::Flag::RW); + + connection.ExecCommand("CREATE TABLE test(value TEXT);"); + + const size_t STRESS_GENERATOR_COUNT = 5; + ThreadPtr stressGenerators[STRESS_GENERATOR_COUNT]; + + for (size_t i = 0; i < STRESS_GENERATOR_COUNT; ++i) { + stressGenerators[i].reset( + new StressGenerator(i, PATH_DB, generator)); + + stressGenerators[i]->Run(); + } + + for (size_t i = 0; i < STRESS_GENERATOR_COUNT; ++i) { + stressGenerators[i]->Quit(); + } + + connection.ExecCommand("DROP TABLE test;"); +} + +/* +Name: SqlConnection_MassiveReadWrite_NaiveSynchronization +Description: tests massive multiple quiries from many threads +Expected: no ORM/db failures +*/ +RUNNER_TEST(SqlConnection_MassiveReadWrite_NaiveSynchronization) +{ + srand(time(NULL)); + + NaiveSynchronizationObjectGenerator m_generator; + MassiveReadWriteTest(&m_generator); +} + +/* +Name: SqlConnection_Not_Connected_Lucene +Description: tests connection to not existing database with Lucene option +Expected: exception throw +*/ +RUNNER_TEST(SqlConnection_Not_Connected_Lucene) +{ + Try { + DPL::DB::SqlConnection connection( + "/notexisitingdirectiory/foo", + DPL::DB::SqlConnection::Flag:: + UseLucene, + DPL::DB::SqlConnection::Flag::RW); + RUNNER_ASSERT_MSG(false, + "connection should throw on accessing " + "nonexistent file as a database"); + } + Catch(DPL::DB::SqlConnection::Exception::ConnectionBroken) + { + RUNNER_ASSERT(true); + } catch (DPL::Exception) { + RUNNER_ASSERT_MSG(false, "Wrong exception found"); + } +} + +/* +Name: SqlConnection_Not_Connected +Description: tests connection to not existing database without Lucene option +Expected: exception throw +*/ +RUNNER_TEST(SqlConnection_Not_Connected) +{ + Try { + DPL::DB::SqlConnection connection("/notexisitingdirectiory/foo", + DPL::DB::SqlConnection::Flag::None, + DPL::DB::SqlConnection::Flag::RW); + RUNNER_ASSERT_MSG(false, + "connection should throw on accessing " + "nonexistent file as a database"); + } + Catch(DPL::DB::SqlConnection::Exception::ConnectionBroken) + { + RUNNER_ASSERT(true); + } catch (DPL::Exception) { + RUNNER_ASSERT_MSG(false, "Wrong exception found"); + } +} + +/* +Name: SqlConnection_Null_Query +Description: tests resistance to passing NULL as query in ExecCommand +Expected: exception throw +*/ +RUNNER_TEST(SqlConnection_Null_Query) +{ + DPL::DB::SqlConnection connection(PATH_DB, + DPL::DB::SqlConnection::Flag::UseLucene, + DPL::DB::SqlConnection::Flag::RW); + Try + { + connection.ExecCommand(NULL); + RUNNER_ASSERT_MSG(false, + "Null pointer should not be accepted"); + } + Catch(DPL::DB::SqlConnection::Exception::SyntaxError) + { + RUNNER_ASSERT(true); + } catch (DPL::Exception) { + RUNNER_ASSERT_MSG(false, "Wrong exception found"); + } +} + +/* +Name: SqlConnection_Bad_Query +Description: tests resistance to passing trash as query in ExecCommand +Expected: exception throw +*/ +RUNNER_TEST(SqlConnection_Bad_Query) +{ + DPL::DB::SqlConnection connection(PATH_DB, + DPL::DB::SqlConnection::Flag::UseLucene, + DPL::DB::SqlConnection::Flag::RW); + Try + { + connection.ExecCommand("Some stupid string"); + RUNNER_ASSERT_MSG(false, "This string should not be accepted"); + } + Catch(DPL::DB::SqlConnection::Exception::SyntaxError) + { + RUNNER_ASSERT(true); + } catch (DPL::Exception) { + RUNNER_ASSERT_MSG(false, "Wrong exception found"); + } +} diff --git a/tests/dbus/CMakeLists.txt b/tests/dbus/CMakeLists.txt new file mode 100644 index 0000000..4a1f338 --- /dev/null +++ b/tests/dbus/CMakeLists.txt @@ -0,0 +1,63 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# 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. +# +# @file CMakeLists.txt +# @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) +# @version 1.0 +# @brief +# + +INCLUDE(FindPkgConfig) + +PKG_CHECK_MODULES(DEPENDENCIES gthread-2.0 REQUIRED) + +SET(TARGET_DBUS_TESTS "wrt-commons-tests-dbus") +SET(TARGET_DBUS_TEST_SERVICE "wrt-commons-tests-dbus-test-service") + +SET(DBUS_TESTS_SRCS + ${TESTS_DIR}/dbus/main.cpp + ${TESTS_DIR}/dbus/test_cases.cpp + ${TESTS_DIR}/dbus/dbus_test.cpp + ${TESTS_COMMON_DIR}/src/loop_control.cpp +) + +SET(DBUS_TEST_SERVICE_SRCS + ${TESTS_DIR}/dbus/test_service.cpp + ${TESTS_COMMON_DIR}/src/loop_control.cpp +) + +WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_DBUS_TESTS} ${TARGET_DPL_DBUS_EFL}) +WRT_TEST_INCLUDE_DIRECTORIES(${TARGET_DBUS_TESTS} + ${TESTS_COMMON_DIR}/include + ${DEPENDENCIES_INCLUDE_DIRS} +) +WRT_TEST_LINK_DIRECTORIES(${TARGET_DBUS_TESTS} ${DEPENDENCIES_LIBRARY_DIRS}) +WRT_TEST_TARGET_LINK_LIBRARIES(${TARGET_DBUS_TESTS} ${DEPENDENCIES_LIBRARIES}) +WRT_TEST_BUILD(${TARGET_DBUS_TESTS} ${DBUS_TESTS_SRCS}) +WRT_TEST_INSTALL(${TARGET_DBUS_TESTS}) + +WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_DBUS_TEST_SERVICE} ${TARGET_DPL_DBUS_EFL}) +WRT_TEST_INCLUDE_DIRECTORIES(${TARGET_DBUS_TEST_SERVICE} + ${TESTS_COMMON_DIR}/include + ${DEPENDENCIES_INCLUDE_DIRS} +) +WRT_TEST_LINK_DIRECTORIES(${TARGET_DBUS_TEST_SERVICE} ${DEPENDENCIES_LIBRARY_DIRS}) +WRT_TEST_TARGET_LINK_LIBRARIES(${TARGET_DBUS_TEST_SERVICE} ${DEPENDENCIES_LIBRARIES}) +WRT_TEST_BUILD(${TARGET_DBUS_TEST_SERVICE} ${DBUS_TEST_SERVICE_SRCS}) +WRT_TEST_INSTALL(${TARGET_DBUS_TEST_SERVICE}) + +INSTALL(FILES + ${TESTS_DIR}/dbus/data/org.tizen.DBusTestService.service + DESTINATION /usr/share/dbus-1/services +) diff --git a/tests/dbus/data/org.tizen.DBusTestService.service b/tests/dbus/data/org.tizen.DBusTestService.service new file mode 100644 index 0000000..94b3d67 --- /dev/null +++ b/tests/dbus/data/org.tizen.DBusTestService.service @@ -0,0 +1,3 @@ +[D-BUS Service] +Name=org.tizen.DBusTestService +Exec=/usr/bin/wrt-commons-tests-dbus-test-service diff --git a/tests/dbus/dbus_test.cpp b/tests/dbus/dbus_test.cpp new file mode 100644 index 0000000..2e8d51b --- /dev/null +++ b/tests/dbus/dbus_test.cpp @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/** + * @file dbus_test.cpp + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @brief Implementation file for DBusTest and DBusTestManager. + */ + +#include +#include "loop_control.h" +#include "dbus_test.h" + +DBusTest::DBusTest(const std::string& name) : + m_name(name), + m_status(Status::NONE) +{} + +void DBusTest::run(unsigned int timeout) +{ + DPL::Event::ControllerEventHandler::Touch(); + DPL::Event::ControllerEventHandler::Touch(); + + DPL::Event::ControllerEventHandler::PostTimedEvent( + TimeoutEvent(), timeout); + + LoopControl::wrt_start_loop(); + + switch (m_status) { + case Status::FAILED: + throw DPL::Test::TestRunner::TestFailed(m_name.c_str(), + __FILE__, + __LINE__, + m_message); + + case Status::SUCCESS: + case Status::NONE: + default: + break; + } +} + +void DBusTest::quit() +{ + DPL::Event::ControllerEventHandler::PostEvent(QuitEvent()); +} + +void DBusTest::setStatus(Status status) +{ + m_status = status; +} + +void DBusTest::setMessage(const std::string& message) +{ + m_message = message; +} + +void DBusTest::success() +{ + m_status = Status::SUCCESS; +} + +void DBusTest::fail(const std::string& message) +{ + m_status = Status::FAILED; + m_message = message; +} + +void DBusTest::OnEventReceived(const TimeoutEvent& /*event*/) +{ + fail("Test timed out."); + + // Saving one event dispatch since Quit and Timeout work on the same thread. + LoopControl::wrt_end_loop(); +} + +void DBusTest::OnEventReceived(const QuitEvent& /*event*/) +{ + LoopControl::wrt_end_loop(); +} + +DBusTestManager& DBusTestManager::getInstance() +{ + static DBusTestManager instance; + return instance; +} + +DBusTestManager::DBusTestManager() : m_test(NULL) { } + +DBusTest& DBusTestManager::getCurrentTest() const +{ + Assert(NULL != m_test && "Test not set."); + + return *m_test; +} + +void DBusTestManager::setCurrentTest(DBusTest& test) +{ + m_test = &test; +} + +void DBusTestManager::clear() +{ + m_test = NULL; +} diff --git a/tests/dbus/dbus_test.h b/tests/dbus/dbus_test.h new file mode 100644 index 0000000..3c7ffe9 --- /dev/null +++ b/tests/dbus/dbus_test.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/** + * @file dbus_test.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @brief Header file for DBusTest and DBusTestManager. + */ + +#ifndef WRT_TESTS_DBUS_TESTS_DBUS_TEST_H +#define WRT_TESTS_DBUS_TESTS_DBUS_TEST_H + +#include +#include +#include + +DECLARE_GENERIC_EVENT_0(QuitEvent) +DECLARE_GENERIC_EVENT_0(TimeoutEvent) + +class DBusTest : + private DPL::Event::Controller::Type> +{ + public: + enum class Status + { + NONE, + SUCCESS, + FAILED + }; + + explicit DBusTest(const std::string& name); + + void run(unsigned int timeout); + void quit(); + + void setStatus(Status status); + void setMessage(const std::string& message); + + void success(); + void fail(const std::string& message = std::string()); + + private: + void OnEventReceived(const TimeoutEvent& event); + void OnEventReceived(const QuitEvent& event); + + std::string m_name; + Status m_status; + std::string m_message; +}; + +class DBusTestManager : private DPL::Noncopyable +{ + public: + static DBusTestManager& getInstance(); + + DBusTest& getCurrentTest() const; + void setCurrentTest(DBusTest& test); + + void clear(); + + private: + DBusTestManager(); + + DBusTest* m_test; +}; + +#define DBUS_TEST(TestProc) \ + void DBus##TestProc(); \ + RUNNER_TEST(TestProc) \ + { \ + DBusTest test(#TestProc); \ + DBusTestManager::getInstance().setCurrentTest(test); \ + DBus##TestProc(); \ + DBusTestManager::getInstance().clear(); \ + } \ + void DBus##TestProc() + +#endif diff --git a/tests/dbus/main.cpp b/tests/dbus/main.cpp new file mode 100644 index 0000000..d06a4c0 --- /dev/null +++ b/tests/dbus/main.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/** + * @file main.cpp + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of main. + */ + +#include "loop_control.h" +#include +#include + +int main(int argc, char *argv[]) +{ + LoopControl::init_loop(argc, argv); + + LogInfo("Running tests"); + int status = DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, + argv); + + return status; +} diff --git a/tests/dbus/test_cases.cpp b/tests/dbus/test_cases.cpp new file mode 100644 index 0000000..0d855ef --- /dev/null +++ b/tests/dbus/test_cases.cpp @@ -0,0 +1,198 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/** + * @file TestCases.cpp + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @version 1.0 + * @brief Implementation file for test cases for DBus internal tests. + */ + +#include +#include +#include +#include +#include +#include +#include "dbus_test.h" + +namespace { +const std::string dbusServiceName = "org.freedesktop.DBus"; +const std::string dbusObjectPath = "/"; +const std::string dbusInterfaceName = "org.freedesktop.DBus"; +const std::string dbusMethodGetId = "GetId"; + +const std::string serviceName = "org.tizen.DBusTestService"; +const std::string objectPath = "/org/tizen/DBusTestService"; +const std::string interfaceName = "org.tizen.DBusTestService"; +const std::string methodNameEcho = "echo"; +const std::string methodNameQuit = "quit"; +const std::string nodeInfo = + "" + "" + " " + " " + " " + " " + " " + " " + " " + " " + ""; + +const std::string challenge = "Hello world!"; + +const int DEFAULT_TIMEOUT = 2; // in seconds +} + +RUNNER_TEST_GROUP_INIT(DPL) + +/* +Name: AcquireSessionBus +Description: tests acquiring session bus +Expected: no exceptions +*/ +RUNNER_TEST(AcquireSessionBus) +{ + try { + DPL::DBus::Connection::sessionBus(); + } catch (const DPL::DBus::Exception& ex) { + RUNNER_ASSERT_MSG(false, ex.DumpToString()); + } +} + +/* +Name: AcquireSystemBus +Description: tests acquiring system bus +Expected: no exceptions +*/ +RUNNER_TEST(AcquireSystemBus) +{ + try { + DPL::DBus::Connection::systemBus(); + } catch (const DPL::DBus::Exception& ex) { + RUNNER_ASSERT_MSG(false, ex.DumpToString()); + } +} + +/* +Name: ParseNodeInfo +Description: creates dbus interface from xml string +Expected: interface should be created correctly +*/ +RUNNER_TEST(ParseNodeInfo) +{ + try { + auto ifaces = DPL::DBus::Interface::fromXMLString(nodeInfo); + RUNNER_ASSERT(!ifaces.empty()); + + auto iface = ifaces.at(0); + RUNNER_ASSERT(NULL != iface->getVTable()); + RUNNER_ASSERT(NULL != iface->getInfo()); + } catch (const DPL::DBus::Exception& ex) { + RUNNER_ASSERT_MSG(false, ex.DumpToString()); + } +} + +/* +Name: InvokeRemoteMethod +Description: performs procedure call via dbus +Expected: call should return not empty id +*/ +RUNNER_TEST(InvokeRemoteMethod) +{ + try { + auto connection = DPL::DBus::Connection::systemBus(); + auto freedesktop = connection->createObjectProxy(dbusServiceName, + dbusObjectPath); + auto getId = freedesktop->createMethodProxy + (dbusInterfaceName, dbusMethodGetId); + RUNNER_ASSERT(!getId().empty()); + } catch (const DPL::DBus::Exception& ex) { + RUNNER_ASSERT_MSG(false, ex.DumpToString()); + } +} + +class RegisterServiceListener : + public DPL::Event::EventListener +{ + public: + void OnEventReceived( + const DPL::DBus::ConnectionEvents::ServiceNameAcquiredEvent& event) + { + DBusTest& test = DBusTestManager::getInstance().getCurrentTest(); + + auto name = event.GetArg0(); + if (serviceName == name) { + test.success(); + } else { + test.fail("Acquired service name: " + name); + } + test.quit(); + } +}; + +/* +Name: RegisterService +Description: tests event listener for AcquiredEvent in context of dbus +Expected: event should be received +*/ +DBUS_TEST(RegisterService) +{ + try { + RegisterServiceListener listener; + + auto connection = DPL::DBus::Connection::sessionBus(); + connection->DPL::Event::EventSupport:: + AddListener(&listener); + connection->registerService(serviceName); + + DBusTestManager::getInstance().getCurrentTest().run(DEFAULT_TIMEOUT); + } catch (const DPL::DBus::Exception& ex) { + RUNNER_ASSERT_MSG(false, ex.DumpToString()); + } +} + +/** + * This test checks: + * - object registration (done on the wrt-dbus-test-service side) + * - service registration (done on the wrt-dbus-test-service side) + * - dispatching method calls (done on the wrt-dbus-test-service side) + * - launching dbus service on demand + * - invoking remote method(s) + */ +DBUS_TEST(InvokeTestService) +{ + try { + auto connection = DPL::DBus::Connection::sessionBus(); + auto testService = connection->createObjectProxy(serviceName, + objectPath); + auto echo = testService->createMethodProxy + (interfaceName, methodNameEcho); + auto response = echo(challenge); + + testService->createMethodProxy(interfaceName, methodNameQuit) (); + + RUNNER_ASSERT_MSG(response == challenge, + "[challenge = " << challenge << + ", response = " << response << "]"); + } catch (const DPL::DBus::Exception& ex) { + RUNNER_ASSERT_MSG(false, ex.DumpToString()); + } +} diff --git a/tests/dbus/test_service.cpp b/tests/dbus/test_service.cpp new file mode 100644 index 0000000..510e4c5 --- /dev/null +++ b/tests/dbus/test_service.cpp @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/** + * @file test_service.cpp + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @brief Implementation file for wrt-dbus-test-service. + */ + +#include +#include +#include +#include +#include +#include + +namespace { +const std::string serviceName = "org.tizen.DBusTestService"; +const std::string objectPath = "/org/tizen/DBusTestService"; +const std::string interfaceName = "org.tizen.DBusTestService"; +const std::string methodNameEcho = "echo"; +const std::string methodNameQuit = "quit"; +const std::string nodeInfo = + "" + "" + " " + " " + " " + " " + " " + " " + " " + " " + ""; +} + +class TestServiceDispatcher : public DPL::DBus::Dispatcher +{ + private: + void onMethodCall(GDBusConnection* /*connection*/, + const gchar* /*sender*/, + const gchar* /*objectPath*/, + const gchar* /*interfaceName*/, + const gchar* methodName, + GVariant* parameters, + GDBusMethodInvocation* invocation) + { + if (methodNameEcho == methodName) { + LogDebug("Echo"); + g_dbus_method_invocation_return_value(invocation, + parameters); + } else if (methodNameQuit == methodName) { + LogDebug("Quit"); + g_dbus_method_invocation_return_value(invocation, NULL); + LoopControl::wrt_end_loop(); + } + } +}; + +int main(int argc, char* argv[]) +{ + LoopControl::init_loop(argc, argv); + TestServiceDispatcher dispatcher; + + auto iface = DPL::DBus::Interface::fromXMLString(nodeInfo).at(0); + iface->setDispatcher(&dispatcher); + auto object = DPL::DBus::Object::create(objectPath, iface); + auto connection = DPL::DBus::Connection::sessionBus(); + connection->registerObject(object); + connection->registerService(serviceName); + LoopControl::wrt_start_loop(); + + return 0; +} diff --git a/tests/dpl/CMakeLists.txt b/tests/dpl/CMakeLists.txt deleted file mode 100644 index 1dea774..0000000 --- a/tests/dpl/CMakeLists.txt +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved -# -# 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. -# -# @file CMakeLists.txt -# @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) -# @version 1.0 -# @brief -# - -SET(TESTS_DPL_DIR "${TESTS_DIR}/dpl") - -ADD_SUBDIRECTORY(core) -ADD_SUBDIRECTORY(db) -ADD_SUBDIRECTORY(dbus) -ADD_SUBDIRECTORY(event) -#ADD_SUBDIRECTORY(localization) TODO localization mockups need to be fixed -ADD_SUBDIRECTORY(utils) -ADD_SUBDIRECTORY(test) diff --git a/tests/dpl/README b/tests/dpl/README deleted file mode 100644 index 6641953..0000000 --- a/tests/dpl/README +++ /dev/null @@ -1,13 +0,0 @@ -Unit tests for dpl library functionality. -There are 6 binaries: dpl-dbus-test-service, dpl-tests-core, dpl-tests-db, -dpl-tests-dbus, dpl-tests-event, dpl-tests-utils. -All binaries are using our test framework - it allows to use different types of -output. Text output shows results on console - green passed. -To run: -1. Install wrt-extra on target -2. Run for f in /usr/bin/dpl-tests-*; do $f --output=text; done - -Automatic: YES -Included in Daily Build: YES (http://build01.sprc.samsung.pl/browse/LINUXNGWAP-INT) -Included in Gerrit Builds: YES (http://build01.sprc.samsung.pl/browse/LINUXNGWAP-GERRIT) -Number of test cases: 151 \ No newline at end of file diff --git a/tests/dpl/core/.swp b/tests/dpl/core/.swp deleted file mode 100644 index e25a05b..0000000 Binary files a/tests/dpl/core/.swp and /dev/null differ diff --git a/tests/dpl/core/CMakeLists.txt b/tests/dpl/core/CMakeLists.txt deleted file mode 100644 index 48d2c93..0000000 --- a/tests/dpl/core/CMakeLists.txt +++ /dev/null @@ -1,61 +0,0 @@ -# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved -# -# 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. -# -# @file CMakeLists.txt -# @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) -# @version 1.0 -# @brief -# - -# -# Test files -# -# Define all DPL tests sources. -# Runner is responsible for runnint it all and -# generating proper output files -# - -SET(TARGET_NAME "dpl-tests-core") - -# Set DPL tests sources -SET(DPL_TESTS_CORE_SOURCES - ${TESTS_DPL_DIR}/core/main.cpp - ${TESTS_DPL_DIR}/core/test_address.cpp - ${TESTS_DPL_DIR}/core/test_binary_queue.cpp - ${TESTS_DPL_DIR}/core/test_foreach.cpp - ${TESTS_DPL_DIR}/core/test_fast_delegate.cpp - ${TESTS_DPL_DIR}/core/test_log_unhandled_exception.cpp - ${TESTS_DPL_DIR}/core/test_once.cpp - ${TESTS_DPL_DIR}/core/test_serialization.cpp - ${TESTS_DPL_DIR}/core/test_scoped_array.cpp - ${TESTS_DPL_DIR}/core/test_scoped_close.cpp - ${TESTS_DPL_DIR}/core/test_scoped_fclose.cpp - ${TESTS_DPL_DIR}/core/test_scoped_free.cpp - ${TESTS_DPL_DIR}/core/test_scoped_ptr.cpp - ${TESTS_DPL_DIR}/core/test_semaphore.cpp - ${TESTS_DPL_DIR}/core/test_shared_ptr.cpp - ${TESTS_DPL_DIR}/core/test_string.cpp - ${TESTS_DPL_DIR}/core/test_thread.cpp - ${TESTS_DPL_DIR}/core/test_type_list.cpp - ${TESTS_DPL_DIR}/core/test_zip_input.cpp -) - -WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_NAME} ${TARGET_DPL_EFL}) -WRT_TEST_BUILD(${TARGET_NAME} ${DPL_TESTS_CORE_SOURCES}) -WRT_TEST_INSTALL(${TARGET_NAME}) - -INSTALL(FILES - ${TESTS_DPL_DIR}/core/data/sample.zip - DESTINATION /opt/share/wrt/wrt-commons/tests/core - ) diff --git a/tests/dpl/core/DESCRIPTION b/tests/dpl/core/DESCRIPTION deleted file mode 100644 index 48e5394..0000000 --- a/tests/dpl/core/DESCRIPTION +++ /dev/null @@ -1,2 +0,0 @@ -!!!options!!! stop -Test code diff --git a/tests/dpl/core/data/sample.zip b/tests/dpl/core/data/sample.zip deleted file mode 100644 index 02417d8..0000000 Binary files a/tests/dpl/core/data/sample.zip and /dev/null differ diff --git a/tests/dpl/core/main.cpp b/tests/dpl/core/main.cpp deleted file mode 100644 index 42ffe3a..0000000 --- a/tests/dpl/core/main.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file main.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of main - */ -#include - -int main(int argc, char *argv[]) -{ - return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); -} - diff --git a/tests/dpl/core/test_address.cpp b/tests/dpl/core/test_address.cpp deleted file mode 100644 index d887ca0..0000000 --- a/tests/dpl/core/test_address.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_address.cpp - * @author Tomasz Swierczek (t.swierczek@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of test address - */ -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL) - -/* -Name: Address_InitialEmpty -Description: tests empty constructor of DPL::Address -Expected: string version of empy address equals ":0" -*/ -RUNNER_TEST(Address_InitialEmpty) -{ - DPL::Address address; - RUNNER_ASSERT(address.ToString() == ":0"); -} - -/* -Name: Address_InitialAddress -Description: tests constructor of DPL::Address with name only -Expected: string version of address equals given name and appended ":0" -*/ -RUNNER_TEST(Address_InitialAddress) -{ - DPL::Address address("www.sample.com"); - RUNNER_ASSERT(address.ToString() == "www.sample.com:0"); -} - -/* -Name: Address_InitialAddress -Description: tests constructor of DPL::Address with name and port -Expected: string version of address should look lik "adress name:port" -*/ -RUNNER_TEST(Address_InitialAddressPort) -{ - DPL::Address address("www.somewhere.com", 8080); - RUNNER_ASSERT(address.ToString() == "www.somewhere.com:8080"); -} - -/* -Name: Address_InitialAddress -Description: tests getter of address -Expected: address name and port should matches those passed in constructor -*/ -RUNNER_TEST(Address_Getters) -{ - DPL::Address address("www.somewhere.com", 8080); - RUNNER_ASSERT(address.GetAddress() == "www.somewhere.com"); - RUNNER_ASSERT(address.GetPort() == 8080); -} diff --git a/tests/dpl/core/test_binary_queue.cpp b/tests/dpl/core/test_binary_queue.cpp deleted file mode 100644 index cd8931d..0000000 --- a/tests/dpl/core/test_binary_queue.cpp +++ /dev/null @@ -1,468 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_binary_queue.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of test binary queue - */ -#include -#include -RUNNER_TEST_GROUP_INIT(DPL) - -inline std::string BinaryQueueToString(const DPL::BinaryQueue &queue) -{ - char *buffer = new char[queue.Size()]; - queue.Flatten(buffer, queue.Size()); - std::string result = std::string(buffer, buffer + queue.Size()); - delete[] buffer; - return result; -} - -/* -Name: BinaryQueue_InitialEmpty -Description: tests emptiness of new constructed queue -Expected: new queue should be empty -*/ -RUNNER_TEST(BinaryQueue_InitialEmpty) -{ - DPL::BinaryQueue queue; - RUNNER_ASSERT(queue.Empty() == true); -} - -/* -Name: BinaryQueue_InitialSize -Description: tests emptiness of new constructed queue -Expected: new queue size should be equal 0 -*/ -RUNNER_TEST(BinaryQueue_InitialSize) -{ - DPL::BinaryQueue queue; - RUNNER_ASSERT(queue.Size() == 0); -} - -/* -Name: BinaryQueue_InitialCopy -Description: tests emptiness of new copy-constructed empty queue -Expected: queue constructed on base on empty queue should be empty -*/ -RUNNER_TEST(BinaryQueue_InitialCopy) -{ - DPL::BinaryQueue queue; - DPL::BinaryQueue copy = queue; - - RUNNER_ASSERT(copy.Size() == 0); -} - -/* -Name: BinaryQueue_InitialConsumeZero -Description: tests consume method accepts 0 bytes -Expected: it should be avaliable to discard 0 bytes from empty queue -*/ -RUNNER_TEST(BinaryQueue_InitialConsumeZero) -{ - DPL::BinaryQueue queue; - queue.Consume(0); -} - -/* -Name: BinaryQueue_InitialFlattenConsumeZero -Description: tests returning data from queue and discarding -Expected: it should be able to call flattenconsume with empty buffer if 0 bytes are read -*/ -RUNNER_TEST(BinaryQueue_InitialFlattenConsumeZero) -{ - DPL::BinaryQueue queue; - queue.FlattenConsume(NULL, 0); -} - -/* -Name: BinaryQueue_InitialFlattenZero -Description: tests returning data from queue -Expected: it should be able to call flatten with empty buffer if 0 bytes are read -*/ -RUNNER_TEST(BinaryQueue_InitialFlattenZero) -{ - DPL::BinaryQueue queue; - queue.Flatten(NULL, 0); -} - -/* -Name: BinaryQueue_InitialConsumeOne -Description: tests discarding more bytes than it is avaliable -Expected: exception throw -*/ -RUNNER_TEST(BinaryQueue_InitialConsumeOne) -{ - DPL::BinaryQueue queue; - - Try - { - queue.Consume(1); - } - Catch(DPL::BinaryQueue::Exception::OutOfData) - { - return; - } - - RUNNER_FAIL; -} - -/* -Name: BinaryQueue_InitialFlattenConsumeOne -Description: tests reading and discarding more bytes than it is avaliable -Expected: exception throw -*/ -RUNNER_TEST(BinaryQueue_InitialFlattenConsumeOne) -{ - DPL::BinaryQueue queue; - - Try - { - char data; - queue.FlattenConsume(&data, 1); - } - Catch(DPL::BinaryQueue::Exception::OutOfData) - { - return; - } - - RUNNER_FAIL; -} - -/* -Name: BinaryQueue_InitialFlattenOne -Description: tests reading more bytes than it is avaliable -Expected: exception throw -*/ -RUNNER_TEST(BinaryQueue_InitialFlattenOne) -{ - DPL::BinaryQueue queue; - - Try - { - char data; - queue.Flatten(&data, 1); - } - Catch(DPL::BinaryQueue::Exception::OutOfData) - { - return; - } - - RUNNER_FAIL; -} - -/* -Name: BinaryQueue_ZeroCopyFrom -Description: tests coping content of empty queue to another (AppendCopyFrom) -Expected: source queue should be empty -*/ -RUNNER_TEST(BinaryQueue_ZeroCopyFrom) -{ - DPL::BinaryQueue queue; - DPL::BinaryQueue copy; - - copy.AppendCopyFrom(queue); - RUNNER_ASSERT(queue.Empty()); -} - -/* -Name: BinaryQueue_ZeroMoveFrom -Description: tests moving content of empty queue to another -Expected: source queue should be empty -*/ -RUNNER_TEST(BinaryQueue_ZeroMoveFrom) -{ - DPL::BinaryQueue queue; - DPL::BinaryQueue copy; - - copy.AppendMoveFrom(queue); - RUNNER_ASSERT(queue.Empty()); -} - -/* -Name: BinaryQueue_ZeroCopyTo -Description: tests moving content of empty queue to another (AppendCopyTo) -Expected: source queue should be empty -*/ -RUNNER_TEST(BinaryQueue_ZeroCopyTo) -{ - DPL::BinaryQueue queue; - DPL::BinaryQueue copy; - - queue.AppendCopyTo(copy); - RUNNER_ASSERT(queue.Empty()); -} - -/* -Name: BinaryQueue_InsertSingleCharacters -Description: tests inserting single bytes to queue -Expected: stringified content and size shoudl match expected -*/ -RUNNER_TEST(BinaryQueue_InsertSingleCharacters) -{ - DPL::BinaryQueue queue; - - queue.AppendCopy("a", 1); - queue.AppendCopy("b", 1); - queue.AppendCopy("c", 1); - queue.AppendCopy("d", 1); - - RUNNER_ASSERT(queue.Size() == 4); - RUNNER_ASSERT(BinaryQueueToString(queue) == "abcd"); -} - -/* -Name: BinaryQueue_Consume -Description: tests comsuming portions of 1 or 2 bytes -Expected: stringified content and size should match expected - Bytes should be pope from begin. -*/ -RUNNER_TEST(BinaryQueue_Consume) -{ - DPL::BinaryQueue queue; - - queue.AppendCopy("abcd", 4); - queue.AppendCopy("ef", 2); - - RUNNER_ASSERT(queue.Size() == 6); - - queue.Consume(1); - RUNNER_ASSERT(queue.Size() == 5); - RUNNER_ASSERT(BinaryQueueToString(queue) == "bcdef"); - - queue.Consume(2); - RUNNER_ASSERT(queue.Size() == 3); - RUNNER_ASSERT(BinaryQueueToString(queue) == "def"); - - queue.Consume(1); - RUNNER_ASSERT(queue.Size() == 2); - RUNNER_ASSERT(BinaryQueueToString(queue) == "ef"); - - queue.Consume(2); - RUNNER_ASSERT(queue.Size() == 0); - RUNNER_ASSERT(BinaryQueueToString(queue) == ""); -} - -/* -Name: BinaryQueue_Flatten -Description: tests comsuming portions of 1 and more bytes -Expected: stringified content and size should match expected -*/ -RUNNER_TEST(BinaryQueue_Flatten) -{ - DPL::BinaryQueue queue; - - queue.AppendCopy("abcd", 4); - queue.AppendCopy("ef", 2); - queue.AppendCopy("g", 1); - - RUNNER_ASSERT(queue.Size() == 7); - - RUNNER_ASSERT(BinaryQueueToString(queue) == "abcdefg"); -} - -/* -Name: BinaryQueue_FlattenConsume -Description: tests comsuming portions of 1 and more bytes -Expected: stringified content and size should match expected - reading and discarding bytes should affect queue's size and content -*/ -RUNNER_TEST(BinaryQueue_FlattenConsume) -{ - DPL::BinaryQueue queue; - - queue.AppendCopy("abcd", 4); - queue.AppendCopy("ef", 2); - - RUNNER_ASSERT(queue.Size() == 6); - - char buffer[7] = { '\0' }; - queue.FlattenConsume(buffer, 3); - - RUNNER_ASSERT(queue.Size() == 3); - RUNNER_ASSERT(BinaryQueueToString(queue) == "def"); -} - -/* -Name: BinaryQueue_AppendCopyFrom -Description: tests creating copy of not empty queue (use of: AppendCopyFrom) -Expected: stringified content and size should match expected - from original queue and it's copy -*/ -RUNNER_TEST(BinaryQueue_AppendCopyFrom) -{ - DPL::BinaryQueue queue; - DPL::BinaryQueue copy; - - queue.AppendCopy("abcd", 4); - queue.AppendCopy("ef", 2); - - copy.AppendCopyFrom(queue); - - RUNNER_ASSERT(queue.Size() == 6); - RUNNER_ASSERT(copy.Size() == 6); - RUNNER_ASSERT(BinaryQueueToString(queue) == "abcdef"); - RUNNER_ASSERT(BinaryQueueToString(copy) == "abcdef"); -} - -/* -Name: BinaryQueue_AppendCopyTo -Description: tests creating copy of not empty queue (use of: AppendCopyTo) -Expected: stringified content and size should match expected - from original queue and it's copy -*/ -RUNNER_TEST(BinaryQueue_AppendCopyTo) -{ - DPL::BinaryQueue queue; - DPL::BinaryQueue copy; - - queue.AppendCopy("abcd", 4); - queue.AppendCopy("ef", 2); - - queue.AppendCopyTo(copy); - - RUNNER_ASSERT(queue.Size() == 6); - RUNNER_ASSERT(copy.Size() == 6); - RUNNER_ASSERT(BinaryQueueToString(queue) == "abcdef"); - RUNNER_ASSERT(BinaryQueueToString(copy) == "abcdef"); -} - -/* -Name: BinaryQueue_AppendMoveFrom -Description: tests moving content of not empty queue (use of: AppendMoveFrom) -Expected: stringified content and size should match expected - for new queue. Old queue should be empty after operation -*/ -RUNNER_TEST(BinaryQueue_AppendMoveFrom) -{ - DPL::BinaryQueue queue; - DPL::BinaryQueue copy; - - queue.AppendCopy("abcd", 4); - queue.AppendCopy("ef", 2); - - copy.AppendMoveFrom(queue); - - RUNNER_ASSERT(queue.Size() == 0); - RUNNER_ASSERT(copy.Size() == 6); - RUNNER_ASSERT(BinaryQueueToString(queue) == ""); - RUNNER_ASSERT(BinaryQueueToString(copy) == "abcdef"); -} - -/* -Name: BinaryQueue_AppendMoveFrom -Description: tests moving content of not empty queue (use of: AppendMoveTo) -Expected: stringified content and size should match expected - for new queue. Old queue should be empty after operation -*/ -RUNNER_TEST(BinaryQueue_AppendMoveTo) -{ - DPL::BinaryQueue queue; - DPL::BinaryQueue copy; - - queue.AppendCopy("abcd", 4); - queue.AppendCopy("ef", 2); - - queue.AppendMoveTo(copy); - - RUNNER_ASSERT(queue.Size() == 0); - RUNNER_ASSERT(copy.Size() == 6); - RUNNER_ASSERT(BinaryQueueToString(queue) == ""); - RUNNER_ASSERT(BinaryQueueToString(copy) == "abcdef"); -} - -class Visitor : - public DPL::BinaryQueue::BucketVisitor -{ - private: - int m_index; - - public: - Visitor() : - m_index(0) - {} - - virtual void OnVisitBucket(const void *buffer, size_t bufferSize) - { - const char *str = static_cast(buffer); - - if (m_index == 0) { - RUNNER_ASSERT(bufferSize == 4); - RUNNER_ASSERT(str[0] == 'a'); - RUNNER_ASSERT(str[1] == 'b'); - RUNNER_ASSERT(str[2] == 'c'); - RUNNER_ASSERT(str[3] == 'd'); - } else if (m_index == 1) { - RUNNER_ASSERT(bufferSize == 2); - RUNNER_ASSERT(str[0] == 'e'); - RUNNER_ASSERT(str[1] == 'f'); - } else { - RUNNER_FAIL; - } - - ++m_index; - } -}; - -/* -Name: BinaryQueue_Visitor -Description: tests byte by byte content of queue by use of visitor -Expected: stringified content and size should match expected - Each byte should be at right position -*/ -RUNNER_TEST(BinaryQueue_Visitor) -{ - DPL::BinaryQueue queue; - - queue.AppendCopy("abcd", 4); - queue.AppendCopy("ef", 2); - - Visitor visitor; - queue.VisitBuckets(&visitor); -} - -RUNNER_TEST(BinaryQueue_AbstracInputRead) -{ - DPL::BinaryQueue queue; - - queue.AppendCopy("abcd", 4); - - queue.Read(0); - - RUNNER_ASSERT(BinaryQueueToString(*queue.Read(1).get()) == "a"); - RUNNER_ASSERT(BinaryQueueToString(*queue.Read(2).get()) == "bc"); - RUNNER_ASSERT(BinaryQueueToString(*queue.Read(1).get()) == "d"); - - RUNNER_ASSERT(queue.Size() == 0); -} - -/* -Name: BinaryQueue_AbstracOutputWrite -Description: tests appending one queue to another -Expected: written bytes shoudl affect content and size of queue -*/ -RUNNER_TEST(BinaryQueue_AbstracOutputWrite) -{ - DPL::BinaryQueue queue; - queue.AppendCopy("abcd", 4); - - DPL::BinaryQueue stream; - - stream.Write(queue, 4); - - RUNNER_ASSERT(BinaryQueueToString(*queue.Read(4).get()) == "abcd"); -} diff --git a/tests/dpl/core/test_fast_delegate.cpp b/tests/dpl/core/test_fast_delegate.cpp deleted file mode 100644 index dc9b34a..0000000 --- a/tests/dpl/core/test_fast_delegate.cpp +++ /dev/null @@ -1,247 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_fast_delegate.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of fast delegate tests. - */ -#include -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL) - -// Sample copied and adopted from -// http://www.codeproject.com/KB/cpp/FastDelegate.aspx -// -// Demonstrate the syntax for FastDelegates. -// -Don Clugston, May 2004. -// It's a really boring example, but it shows the most important cases. -// Declare some functions of varying complexity... -void SimpleStaticFunction(int num, const char *str); -void SimpleStaticFunction(int num, const char *str) -{ - LogDebug("In SimpleStaticFunction. Num=" << num << ", str =" << str); -} - -void SimpleVoidFunction(); -void SimpleVoidFunction() -{ - LogDebug("In SimpleVoidFunction with no parameters."); -} - -class CBaseClass -{ - protected: - const char *m_name; - - public: - CBaseClass(const char *name) : - m_name(name) - {} - - virtual ~CBaseClass() - {} - - void SimpleMemberFunction(int num, const char *str) - { - LogDebug("In SimpleMemberFunction in " << m_name << ". Num=" - << num << ", str = " << str); - } - - int SimpleMemberFunctionReturnsInt(int num, const char *str) - { - LogDebug( - "In SimpleMemberFunctionReturnsInt in " << m_name << ". Num=" - << num << - ", str = " << str); - return -1; - } - - void ConstMemberFunction(int num, const char *str) const - { - LogDebug("In ConstMemberFunction in " << m_name << ". Num=" - << num << ", str = " << str); - } - - virtual void SimpleVirtualFunction(int num, const char *str) - { - LogDebug("In SimpleVirtualFunction in " << m_name << ". Num=" - << num << ", str = " << str); - } - - static void StaticMemberFunction(int num, const char *str) - { - LogDebug("In StaticMemberFunction Num=" - << num << ", str = " << str); - } -}; - -class COtherClass -{ - double rubbish; // to ensure this class has non-zero size. - - public: - virtual ~COtherClass() - {} - - virtual void UnusedVirtualFunction(void) - {} - virtual void TrickyVirtualFunction(int num, const char *str) = 0; -}; - -class VeryBigClass -{ - int letsMakeThingsComplicated[400]; -}; - -// This declaration ensures that we get a convoluted class heirarchy. -class CDerivedClass : - public VeryBigClass, - virtual public COtherClass, - virtual public CBaseClass -{ - double m_somemember[8]; - - public: - CDerivedClass() : - CBaseClass("Base of Derived") - { - m_somemember[0] = 1.2345; - } - - void SimpleDerivedFunction(int num, const char *str) - { - LogDebug("In SimpleDerivedFunction Num=" - << num << ", str = " << str); - } - - virtual void AnotherUnusedVirtualFunction(int num, const char *str) - { - LogDebug( - "In AnotherUnusedVirtualFunction in " << m_name << ". Num=" - << num << ", str = " << - str); - } - - virtual void TrickyVirtualFunction(int num, const char *str) - { - LogDebug("In TrickyVirtualFunction in " << m_name << ". Num=" - << num << ", str = " << str); - } -}; - -/* -Name: FastDelegate_Test -Description: tests several scenarios of using fast delegates -Expected: function calls succeeded -*/ -RUNNER_TEST(FastDelegate_Test) -{ - // Delegates with up to 8 parameters are supported. - // Here's the case for a void function. - // We declare a delegate and attach it to SimpleVoidFunction() - DPL::FastDelegate0<> noparameterdelegate(&SimpleVoidFunction); - - // invoke the delegate - this calls SimpleVoidFunction() - noparameterdelegate(); - - LogDebug("-- Examples using two-parameter delegates (int, char *) --"); - - // By default, the return value is void. - typedef DPL::FastDelegate2 MyDelegate; - - // If you want to have a non-void return value, put it at the end. - typedef DPL::FastDelegate2 IntMyDelegate; - - MyDelegate funclist[12]; // delegates are initialized to empty - CBaseClass a("Base A"); - CBaseClass b("Base B"); - CDerivedClass d; - CDerivedClass c; - - IntMyDelegate newdeleg; - newdeleg = DPL::MakeDelegate(&a, - &CBaseClass::SimpleMemberFunctionReturnsInt); - - // Binding a simple member function - funclist[0].bind(&a, &CBaseClass::SimpleMemberFunction); - - // You can also bind static (free) functions - funclist[1].bind(&SimpleStaticFunction); - - // and static member functions - funclist[2].bind(&CBaseClass::StaticMemberFunction); - - // and const member functions (these only need a const class pointer). - funclist[3].bind((const CBaseClass *) &a, - &CBaseClass::ConstMemberFunction); - - funclist[4].bind(&a, &CBaseClass::ConstMemberFunction); - - // and virtual member functions - funclist[5].bind(&b, &CBaseClass::SimpleVirtualFunction); - - // You can also use the = operator. For static functions, a fastdelegate - // looks identical to a simple function pointer. - funclist[6] = &CBaseClass::StaticMemberFunction; - - // The weird rule about the class of derived member function pointers - // is avoided. For MSVC, you can use &CDerivedClass::SimpleVirtualFunction - // here, but DMC will complain. Note that as well as .bind(), you can also - // use the MakeDelegate() global function. - funclist[7] = DPL::MakeDelegate(&d, &CBaseClass::SimpleVirtualFunction); - - // The worst case is an abstract virtual function of a virtually-derived - // class with at least one non-virtual base class. This is a VERY obscure - // situation, which you're unlikely to encounter in the real world. - // FastDelegate versions prior to 1.3 had problems with this case on VC6. - // Now, it works without problems on all compilers. - funclist[8].bind(&c, &CDerivedClass::TrickyVirtualFunction); - - // BUT... in such cases you should be using the base class as an - // interface, anyway. - funclist[9].bind(&c, &COtherClass::TrickyVirtualFunction); - - // Calling a function that was first declared in the derived class is - // straightforward - funclist[10] = DPL::MakeDelegate(&c, &CDerivedClass::SimpleDerivedFunction); - - // You can also bind directly using the constructor - MyDelegate dg(&b, &CBaseClass::SimpleVirtualFunction); - - const char *msg = "Looking for equal delegate"; - - for (int i = 0; i < 12; i++) { - LogDebug(i << ":"); - - // The == and != operators are provided - // Note that they work even for inline functions. - if (funclist[i] == dg) { - msg = "Found equal delegate"; - } - - // operator ! can be used to test for an empty delegate - // You can also use the .empty() member function. - if (!funclist[i]) { - LogDebug("Delegate is empty"); - } else { - // Invocation generates optimal assembly code. - funclist[i](i, msg); - } - } -} diff --git a/tests/dpl/core/test_foreach.cpp b/tests/dpl/core/test_foreach.cpp deleted file mode 100644 index 08d66df..0000000 --- a/tests/dpl/core/test_foreach.cpp +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_foreach.cpp - * @author Bartosz Janiak (b.janiak@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of foreach tests. - */ - -#include -#include -#include -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL) - -static const size_t testContainerSize = 1024; - -template -void VerifyForeach(Container& container) -{ - size_t i = 0; - FOREACH(it, container) - { - RUNNER_ASSERT(*it == i); - i++; - } - RUNNER_ASSERT(i == container.size()); -} - -#define VERIFY_FOREACH(container) \ - { \ - size_t i = 0; \ - FOREACH(it, container) \ - { \ - RUNNER_ASSERT(*it == i); \ - i++; \ - } \ - } - -static size_t numberOfCallsToTemporaryList = 0; -std::list temporaryList(); -std::list temporaryList() -{ - ++numberOfCallsToTemporaryList; - std::list list; - for (size_t i = 0; i < testContainerSize; i++) { - list.push_back(i); - } - return list; -} - -static size_t numberOfCallsToTemporaryVector = 0; -std::vector temporaryVector(); -std::vector temporaryVector() -{ - ++numberOfCallsToTemporaryVector; - std::vector vector; - for (size_t i = 0; i < testContainerSize; i++) { - vector.push_back(i); - } - return vector; -} - -static size_t numberOfCallsToTemporarySet = 0; -std::set temporarySet(); -std::set temporarySet() -{ - ++numberOfCallsToTemporarySet; - std::set set; - for (size_t i = 0; i < testContainerSize; i++) { - set.insert(i); - } - return set; -} - -/* -Name: Foreach_std_containers -Description: tests iterating contianers set, list, vector using foreach -Expected: value supplied by foreach matches sequence of integers -*/ -RUNNER_TEST(Foreach_std_containers) -{ - std::vector vector; - std::list list; - std::set set; - - for (size_t i = 0; i < testContainerSize; i++) { - vector.push_back(i); - list.push_back(i); - set.insert(i); - } - - VerifyForeach(vector); - VerifyForeach(list); - VerifyForeach(set); - - VERIFY_FOREACH(temporaryList()); - VERIFY_FOREACH(temporaryVector()); - VERIFY_FOREACH(temporarySet()); - - RUNNER_ASSERT(numberOfCallsToTemporaryList == 1); - RUNNER_ASSERT(numberOfCallsToTemporaryVector == 1); - RUNNER_ASSERT(numberOfCallsToTemporarySet == 1); -} diff --git a/tests/dpl/core/test_log_unhandled_exception.cpp b/tests/dpl/core/test_log_unhandled_exception.cpp deleted file mode 100644 index 3299357..0000000 --- a/tests/dpl/core/test_log_unhandled_exception.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_log_unhandled_exception.cpp - * @author Pawel Sikorski (p.marcinkiew@samsung.com) - * @version 1.0 - * @brief - */ -#include -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL) - -class MyException -{}; - -class MyDPLException -{ - public: - DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) - DECLARE_EXCEPTION_TYPE(Base, MyException) -}; - -class MySTDException : - public std::exception -{ - public: - virtual const char* what() const throw() - { - return "my std exception occurred"; - } -}; - -/* -Name: Log_Unknown_Exception -Description: tests exceptions catching macros -Expected: unknown exception should be catched - -TODO: workaround abort call -*/ -RUNNER_TEST(Log_Unknown_Exception) -{ - UNHANDLED_EXCEPTION_HANDLER_BEGIN - { - // throw MyException(); - } - UNHANDLED_EXCEPTION_HANDLER_END - RUNNER_ASSERT(true); -} - -/* -Name: Log_DPL_Exception -Description: tests exceptions catching macros -Expected: DPL exception should be catched - -TODO: workaround abort call -*/ -RUNNER_TEST(Log_DPL_Exception) -{ - UNHANDLED_EXCEPTION_HANDLER_BEGIN - { - // Throw(MyDPLException::MyException); - } - UNHANDLED_EXCEPTION_HANDLER_END - RUNNER_ASSERT(true); -} - -/* -Name: Log_STD_Exception -Description: tests exceptions catching macros -Expected: STD exception should be catched - -TODO: workaround abort call -*/ -RUNNER_TEST(Log_STD_Exception) -{ - UNHANDLED_EXCEPTION_HANDLER_BEGIN - { - // throw MySTDException(); - } - UNHANDLED_EXCEPTION_HANDLER_END - RUNNER_ASSERT(true); -} diff --git a/tests/dpl/core/test_once.cpp b/tests/dpl/core/test_once.cpp deleted file mode 100644 index 436aea4..0000000 --- a/tests/dpl/core/test_once.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_once.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of once tests - */ -#include -#include -#include -#include -#include -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL) - -namespace // anonymous -{ -gint g_counter; - -void Delegate() -{ - ++g_counter; -} -} // namespace anonymous - -RUNNER_TEST(Once_DoubleCall) -{ - g_counter = 0; - - DPL::Once once; - - once.Call(&Delegate); - once.Call(&Delegate); - - RUNNER_ASSERT_MSG(g_counter == 1, "Counter value is: " << g_counter); -} - -class MyThread : - public DPL::Thread -{ - protected: - virtual int ThreadEntry() - { - DPL::WaitForSingleHandle(m_event->GetHandle()); - m_once->Call(DPL::Once::Delegate(this, &MyThread::Call)); - return 0; - } - - void Call() - { - ++*m_atom; - } - - public: - MyThread(DPL::WaitableEvent *event, DPL::Once *once, DPL::Atomic *atom) : - m_event(event), m_once(once), m_atom(atom) - {} - - private: - DPL::WaitableEvent *m_event; - DPL::Once *m_once; - DPL::Atomic *m_atom; -}; - -/* -Name: Once_MultiThreadCall -Description: tests once call wrapper for use by multiple threads -Expected: function should be called just once from one of running threads -*/ -RUNNER_TEST(Once_MultiThreadCall) -{ - const size_t NUM_THREADS = 20; - typedef std::shared_ptr ThreadPtr; - - ThreadPtr threads[NUM_THREADS]; - DPL::WaitableEvent event; - DPL::Once once; - DPL::Atomic atom; - - for (size_t i = 0; i < NUM_THREADS; ++i) { - (threads[i] = ThreadPtr(new MyThread(&event, &once, &atom)))->Run(); - } - - event.Signal(); - - for (size_t i = 0; i < NUM_THREADS; ++i) { - threads[i]->Quit(); - } - - RUNNER_ASSERT_MSG(atom == 1, "Atom value is: " << atom); -} diff --git a/tests/dpl/core/test_scoped_array.cpp b/tests/dpl/core/test_scoped_array.cpp deleted file mode 100644 index f2a3b4b..0000000 --- a/tests/dpl/core/test_scoped_array.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_scoped_array.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of test scoped array - */ -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL) - -/* -Name: ScopedArray_Zero -Description: tests emptiness of empty scoped array -Expected: array should be empty -*/ -RUNNER_TEST(ScopedArray_Zero) -{ - DPL::ScopedArray array; - - RUNNER_ASSERT(!array); - RUNNER_ASSERT(!!!array); -} - -/* -Name: ScopedArray_NonZero -Description: tests emptiness of not empty scoped array -Expected: array should be not empty -*/ -RUNNER_TEST(ScopedArray_NonZero) -{ - DPL::ScopedArray array(new char[7]); - - RUNNER_ASSERT(array); - RUNNER_ASSERT(!!array); -} - -/* -Name: ScopedArray_Reset -Description: tests reseting content of array -Expected: array should be empty after reset -*/ -RUNNER_TEST(ScopedArray_Reset) -{ - DPL::ScopedArray array(new char[7]); - array.Reset(); - - RUNNER_ASSERT(!array); - - array.Reset(new char); - RUNNER_ASSERT(array); -} - -/* -Name: ScopedArray_ArrayOperator -Description: tests accessing elements of array -Expected: returned values should be equal to those which were set -*/ -RUNNER_TEST(ScopedArray_ArrayOperator) -{ - DPL::ScopedArray array(new char[7]); - - array[1] = array[2] = 3; - - RUNNER_ASSERT(array[1] == 3); - RUNNER_ASSERT(array[2] == 3); -} diff --git a/tests/dpl/core/test_scoped_close.cpp b/tests/dpl/core/test_scoped_close.cpp deleted file mode 100644 index 3549fed..0000000 --- a/tests/dpl/core/test_scoped_close.cpp +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_scoped_close.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of test scoped close - */ -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL) - -// DUNNO diff --git a/tests/dpl/core/test_scoped_fclose.cpp b/tests/dpl/core/test_scoped_fclose.cpp deleted file mode 100644 index 7667a9e..0000000 --- a/tests/dpl/core/test_scoped_fclose.cpp +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/*! - * @file test_scoped_fclose.cpp - * @author Piotr Marcinkiewicz (p.marcinkiew@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of test scoped fclose - */ - -#include -#include - -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL) - -namespace { -FILE* MakeTmp() -{ - FILE* result = NULL; - do { - result = tmpfile(); - } while (NULL != result && EINTR == errno); - return result; -} -} //anonymous namespace - -/* -Name: ScopedFClose_Zero -Description: tests if operator ! works correct for closed file -Expected: file should be closed -*/ -RUNNER_TEST(ScopedFClose_Zero) -{ - DPL::ScopedFClose file; - - RUNNER_ASSERT(!file); - RUNNER_ASSERT(!!!file); -} - -/* -Name: ScopedArray_NonZero -Description: tests if operator ! works correct for open file -Expected: file should be open -*/ -RUNNER_TEST(ScopedFClose_NonZero) -{ - DPL::ScopedFClose file(MakeTmp()); - - RUNNER_ASSERT(file); - RUNNER_ASSERT(!!file); -} - -/* -Name: ScopedFClose_Reset -Description: tests reseting of scoped file -Expected: file should be closed after reset -*/ -RUNNER_TEST(ScopedFClose_Reset) -{ - DPL::ScopedFClose file(MakeTmp()); - file.Reset(); - - RUNNER_ASSERT(!file); - - file.Reset(MakeTmp()); - RUNNER_ASSERT(file); -} - diff --git a/tests/dpl/core/test_scoped_free.cpp b/tests/dpl/core/test_scoped_free.cpp deleted file mode 100644 index 25bd6d6..0000000 --- a/tests/dpl/core/test_scoped_free.cpp +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_scoped_free.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of test scoped free - */ -#include -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL) - -/* -Name: ScopedFree_Zero -Description: Checks emptiness of not set scoped free -Expected: resource should be freed -*/ -RUNNER_TEST(ScopedFree_Zero) -{ - DPL::ScopedFree free; - - RUNNER_ASSERT(!free); - RUNNER_ASSERT(!!!free); -} - -/* -Name: ScopedFree_NonZero -Description: Checks emptiness of set scoped free -Expected: resource should not be reported as freed -*/ -RUNNER_TEST(ScopedFree_NonZero) -{ - DPL::ScopedFree free(malloc(7)); - - RUNNER_ASSERT(free); - RUNNER_ASSERT(!!free); -} - -/* -Name: ScopedFree_Reset -Description: Checks reseting scoped free -Expected: resource should be freed after reset -*/ -RUNNER_TEST(ScopedFree_Reset) -{ - DPL::ScopedFree free(malloc(7)); - free.Reset(); - - RUNNER_ASSERT(!free); - - free.Reset(malloc(8)); - RUNNER_ASSERT(free); -} diff --git a/tests/dpl/core/test_scoped_ptr.cpp b/tests/dpl/core/test_scoped_ptr.cpp deleted file mode 100644 index af17bac..0000000 --- a/tests/dpl/core/test_scoped_ptr.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_scoped_ptr.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of test scoped ptr - */ -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL) - -/* -Name: ScopedPtr_Zero -Description: Checks if operator! works -Expected: resource should be not set -*/ -RUNNER_TEST(ScopedPtr_Zero) -{ - DPL::ScopedPtr ptr; - - RUNNER_ASSERT(!ptr); - RUNNER_ASSERT(!!!ptr); -} - -/* -Name: ScopedPtr_NonZero -Description: Checks if operator! works -Expected: resource should be set -*/ -RUNNER_TEST(ScopedPtr_NonZero) -{ - DPL::ScopedPtr ptr(new char(7)); - - RUNNER_ASSERT(ptr); - RUNNER_ASSERT(!!ptr); -} - -/* -Name: ScopedPtr_Reset -Description: Checks reseting scoped ptr -Expected: resource should be not set after reset -*/ -RUNNER_TEST(ScopedPtr_Reset) -{ - DPL::ScopedPtr ptr(new char(7)); - ptr.Reset(); - - RUNNER_ASSERT(!ptr); - - ptr.Reset(new char); - RUNNER_ASSERT(ptr); -} - -/* -Name: ScopedPtr_Operators -Description: Checks access operator -Expected: address of resource should be same as this, received from Get() method -*/ -RUNNER_TEST(ScopedPtr_Operators) -{ - DPL::ScopedPtr ptr(new char(7)); - - RUNNER_ASSERT(*ptr == *ptr.Get()); -} diff --git a/tests/dpl/core/test_semaphore.cpp b/tests/dpl/core/test_semaphore.cpp deleted file mode 100644 index c93b365..0000000 --- a/tests/dpl/core/test_semaphore.cpp +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_semaphore.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of semaphore tests - */ -#include -#include -#include -#include -#include -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL) - -class SemaphoreThread : - public DPL::Thread -{ - int m_delta; - int m_times; - int *m_value; - std::string m_semaphoreName; - - public: - SemaphoreThread(int delta, - int times, - int *value, - const std::string &semaphoreName) : - m_delta(delta), - m_times(times), - m_value(value), - m_semaphoreName(semaphoreName) - {} - - protected: - virtual int ThreadEntry() - { - DPL::Semaphore semaphore(m_semaphoreName); - - for (int i = 0; i < m_times; ++i) { - // Take scoped semaphore lock - DPL::Semaphore::ScopedLock lock(&semaphore); - *m_value += m_delta; - } - - return 0; - } -}; - -/* -Name: Semaphore_NamedIncrementDecrement -Description: Checks if semaphore are working -Expected: value should not change after all -*/ -RUNNER_TEST(Semaphore_NamedIncrementDecrement) -{ - std::string semaphoreName = - "dpl_test_semaphore_" + - DPL::lexical_cast(std::time(NULL)); - - int value = 0; - SemaphoreThread threadA(-1, 10000, &value, semaphoreName); - SemaphoreThread threadB(+1, 10000, &value, semaphoreName); - - threadA.Run(); - threadB.Run(); - - threadA.Quit(); - threadB.Quit(); - - RUNNER_ASSERT_MSG(value == 0, "Final value is: " << value); -} diff --git a/tests/dpl/core/test_serialization.cpp b/tests/dpl/core/test_serialization.cpp deleted file mode 100644 index 202589b..0000000 --- a/tests/dpl/core/test_serialization.cpp +++ /dev/null @@ -1,302 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_address.cpp - * @author Tomasz Swierczek (t.swierczek@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of serialization tests - */ - -#include -#include -#include -#include - -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL) - -// test stream class -class BinaryStream : public DPL::IStream -{ - public: - virtual void Read(size_t num, void * bytes) - { - for (unsigned i = 0; i < num; ++i) { - ((unsigned char*)bytes)[i] = data[i + readPosition]; - } - readPosition += num; - } - virtual void Write(size_t num, const void * bytes) - { - for (unsigned i = 0; i < num; ++i) { - data.push_back(((unsigned char*)bytes)[i]); - } - } - BinaryStream() - { - readPosition = 0; - } - virtual ~BinaryStream(){} - - private: - std::vector data; - unsigned readPosition; -}; - -//test ISerializable class -class TestClass : public DPL::ISerializable -{ - public: - TestClass(int val, std::string str1, std::string str2) - { - a = val; - b = str1; - c.push_back(str1); - c.push_back(str2); - c.push_back(str1 + str2); - } - TestClass(DPL::IStream& stream) - { - DPL::Deserialization::Deserialize(stream, a); - DPL::Deserialization::Deserialize(stream, b); - DPL::Deserialization::Deserialize(stream, c); - } - virtual void Serialize(DPL::IStream& stream) const - { - DPL::Serialization::Serialize(stream, a); - DPL::Serialization::Serialize(stream, b); - DPL::Serialization::Serialize(stream, c); - } - virtual ~TestClass(){} - virtual bool operator==(const TestClass& other) - { - return (a == other.a && - b == other.b && - c.size() == other.c.size() && - c[0] == other.c[0] && - c[1] == other.c[1] && - c[2] == other.c[2]); - } - - private: - int a; - std::string b; - std::vector c; -}; - -/* -Name: Serialize_primitives -Description: Tests serialization of primitives types -Expected: serialized value after deserialization - should be equal to deserialied value -*/ -RUNNER_TEST(Serialize_primitives) -{ - int a = 1; - bool b = true; - unsigned c = 23; - BinaryStream stream; - DPL::Serialization::Serialize(stream, a); - DPL::Serialization::Serialize(stream, b); - DPL::Serialization::Serialize(stream, c); - int test_int; - DPL::Deserialization::Deserialize(stream, test_int); - RUNNER_ASSERT(test_int == a); - bool test_bool; - DPL::Deserialization::Deserialize(stream, test_bool); - RUNNER_ASSERT(test_bool == b); - unsigned test_unsigned; - DPL::Deserialization::Deserialize(stream, test_unsigned); - RUNNER_ASSERT(test_unsigned == c); -} - -/* -Name: Serialize_primitive_pointers -Description: Tests serialization of primitives pointer types -Expected: serialized value after deserialization - should be equal to deserialied value -*/ -RUNNER_TEST(Serialize_primitive_pointers) -{ - int a = 1; - bool b = true; - unsigned c = 23; - BinaryStream stream; - DPL::Serialization::Serialize(stream, &a); - DPL::Serialization::Serialize(stream, &b); - DPL::Serialization::Serialize(stream, &c); - int* test_int; - DPL::Deserialization::Deserialize(stream, test_int); - RUNNER_ASSERT(test_int != NULL && *test_int == a); - bool* test_bool; - DPL::Deserialization::Deserialize(stream, test_bool); - RUNNER_ASSERT(test_bool != NULL && *test_bool == b); - unsigned* test_unsigned; - DPL::Deserialization::Deserialize(stream, test_unsigned); - RUNNER_ASSERT(test_unsigned != NULL && *test_unsigned == c); - delete test_int; - delete test_bool; - delete test_unsigned; -} - -/* -Name: Serialize_strings -Description: Tests serialization of strings -Expected: serialized value after deserialization - should be equal to deserialied value -*/ -RUNNER_TEST(Serialize_strings) -{ - std::string str1 = "ALA MA KOTA"; - std::string str2 = "MULTILINE\nTEST"; - BinaryStream stream; - DPL::Serialization::Serialize(stream, str1); - DPL::Serialization::Serialize(stream, str2); - std::string test_str1; - DPL::Deserialization::Deserialize(stream, test_str1); - RUNNER_ASSERT(test_str1 == str1); - std::string test_str2; - DPL::Deserialization::Deserialize(stream, test_str2); - RUNNER_ASSERT(test_str2 == str2); -} - -/* -Name: Serialize_string_pointers -Description: Tests serialization of string pointers -Expected: serialized value after deserialization - should be equal to deserialied value -*/ -RUNNER_TEST(Serialize_string_pointers) -{ - std::string str1 = "ALA MA KOTA"; - std::string str2 = "MULTILINE\nTEST"; - BinaryStream stream; - DPL::Serialization::Serialize(stream, &str1); - DPL::Serialization::Serialize(stream, &str2); - std::string* test_str1; - DPL::Deserialization::Deserialize(stream, test_str1); - RUNNER_ASSERT(test_str1 != NULL && *test_str1 == str1); - std::string* test_str2; - DPL::Deserialization::Deserialize(stream, test_str2); - RUNNER_ASSERT(test_str2 != NULL && *test_str2 == str2); - delete test_str1; - delete test_str2; -} - -/* -Name: Serialize_containers -Description: Tests serialization of containers -Expected: serialized value after deserialization - should be equal to deserialied value -*/ -RUNNER_TEST(Serialize_containers) -{ - std::vector vec; - vec.push_back(134); - vec.push_back(265); - std::list list; - list.push_back(true); - list.push_back(false); - std::pair pair; - pair.first = -23; - pair.second = 1234; - std::map map; - map.insert(std::pair(45, "ALA MA CZARNEGO KOTA")); - map.insert(std::pair(-78, "...A MOZE\nMA\nWIELE LINIJEK")); - BinaryStream stream; - DPL::Serialization::Serialize(stream, vec); - DPL::Serialization::Serialize(stream, list); - DPL::Serialization::Serialize(stream, pair); - DPL::Serialization::Serialize(stream, map); - std::vector test_vec; - DPL::Deserialization::Deserialize(stream, test_vec); - RUNNER_ASSERT(test_vec.size() == vec.size() && - test_vec[0] == vec[0] && test_vec[1] == vec[1]); - std::list test_list; - DPL::Deserialization::Deserialize(stream, test_list); - RUNNER_ASSERT(test_list.size() == list.size() && - test_list.front() == list.front() && - test_list.back() == test_list.back()); - std::pair test_pair; - DPL::Deserialization::Deserialize(stream, test_pair); - RUNNER_ASSERT(test_pair.first == pair.first && - test_pair.second == pair.second); - std::map test_map; - DPL::Deserialization::Deserialize(stream, test_map); - RUNNER_ASSERT(test_map.size() == map.size() && - test_map.at(45) == map.at(45) && - test_map.at(-78) == map.at(-78)); -} - -/* -Name: Serialize_objects -Description: Tests serialization of DPL::ISerializable derived objects -Expected: serialized value after deserialization - should be equal to deserialied value -*/ -RUNNER_TEST(Serialize_objects) -{ - TestClass a(123, "ASDGHUADB\n\n5679b^^()*", "TEST_STRING"), - b(679, "HUSPIDNSAHDPA", "\nASDSADASD\naDSADASD8"); - BinaryStream stream; - DPL::Serialization::Serialize(stream, a); - DPL::Serialization::Serialize(stream, b); - TestClass test_a(0, "", ""), test_b(0, "", ""); - DPL::Deserialization::Deserialize(stream, test_a); - RUNNER_ASSERT(test_a == a); - DPL::Deserialization::Deserialize(stream, test_b); - RUNNER_ASSERT(test_b == b); -} - -/* -Name: Serialize_all -Description: Tests serialization of compound objects -Expected: serialized value after deserialization - should be equal to deserialied value -*/ -RUNNER_TEST(Serialize_all) -{ - std::map > map; - std::vector vec; - vec.push_back(new TestClass(123, "ASDGHUADB\n\n5679b^^()*", "TEST_STRING")); - vec.push_back(new TestClass(679, "HUSPIDNSAHDPA", "\nASDSADASD\naDSADASD8")); - map.insert(std::pair >("KEY1", vec)); - map.insert(std::pair >("KEY2", vec)); - BinaryStream stream; - - DPL::Serialization::Serialize(stream, map); - - std::map > test_map; - DPL::Deserialization::Deserialize(stream, test_map); - RUNNER_ASSERT(map.size() == test_map.size()); - std::vector test_vec1, test_vec2; - test_vec1 = map.at("KEY1"); - test_vec2 = test_map.at("KEY1"); - RUNNER_ASSERT(test_vec1.size() == test_vec2.size()); - unsigned i; - for (i = 0; i < test_vec1.size(); ++i) { - RUNNER_ASSERT((*test_vec1[i]) == (*test_vec2[i])); - } - test_vec1 = map.at("KEY2"); - test_vec2 = test_map.at("KEY2"); - RUNNER_ASSERT(test_vec1.size() == test_vec2.size()); - for (i = 0; i < test_vec1.size(); ++i) { - RUNNER_ASSERT((*test_vec1[i]) == (*test_vec2[i])); - } -} - diff --git a/tests/dpl/core/test_shared_ptr.cpp b/tests/dpl/core/test_shared_ptr.cpp deleted file mode 100644 index 8e59075..0000000 --- a/tests/dpl/core/test_shared_ptr.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_shared_ptr.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of test shared ptr - */ -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL) - -/* -Name: SharedPtr_Zero -Description: Tests behaviour of null shared pointer -Expected: pointer should imitate null pointer -*/ -RUNNER_TEST(SharedPtr_Zero) -{ - DPL::SharedPtr ptr; - - RUNNER_ASSERT(!ptr); - RUNNER_ASSERT(!!!ptr); - RUNNER_ASSERT(ptr == DPL::SharedPtr()); -} - -/* -Name: SharedPtr_NonZero -Description: Tests behaviour of not null shared pointer -Expected: pointer should imitate null pointer -*/ -RUNNER_TEST(SharedPtr_NonZero) -{ - DPL::SharedPtr ptr(new char(7)); - - RUNNER_ASSERT(ptr); - RUNNER_ASSERT(!!ptr); - RUNNER_ASSERT(ptr != DPL::SharedPtr()); -} - -/* -Name: SharedPtr_Copy -Description: Tests equality of shared pointer pointing same resource -Expected: pointers should imitate primitive pointer bahaviour -*/ -RUNNER_TEST(SharedPtr_Copy) -{ - DPL::SharedPtr ptr1(new char(7)); - DPL::SharedPtr ptr2(new char(7)); - - RUNNER_ASSERT(ptr1 != ptr2); - - ptr2 = ptr1; - - RUNNER_ASSERT(ptr1 == ptr2); -} - -/* -Name: SharedPtr_Reset -Description: Tests reseting shared pointer -Expected: pointers should imitate primitive pointer bahaviour after reset -*/ -RUNNER_TEST(SharedPtr_Reset) -{ - DPL::SharedPtr ptr(new char(7)); - ptr.Reset(); - - RUNNER_ASSERT(!ptr); - - ptr.Reset(new char); - RUNNER_ASSERT(ptr); -} - -/* -Name: SharedPtr_RefCounting -Description: Tests use count od shared pointer -Expected: counters should be equal for equal pointers - Count number should match expected -*/ -RUNNER_TEST(SharedPtr_RefCounting) -{ - DPL::SharedPtr ptr1(new char(7)); - DPL::SharedPtr ptr2; - - ptr2 = ptr1; - - RUNNER_ASSERT(ptr1 == ptr2); - RUNNER_ASSERT(ptr1.GetUseCount() == ptr2.GetUseCount()); - RUNNER_ASSERT(ptr1.GetUseCount() == 2); -} - -/* -Name: SharedPtr_Operators -Description: Tests use of operator* -Expected: pointers should imitate primitive pointer bahaviour -*/ -RUNNER_TEST(SharedPtr_Operators) -{ - DPL::SharedPtr ptr(new char(7)); - - RUNNER_ASSERT(*ptr == *ptr.Get()); -} diff --git a/tests/dpl/core/test_string.cpp b/tests/dpl/core/test_string.cpp deleted file mode 100644 index dd2bd8a..0000000 --- a/tests/dpl/core/test_string.cpp +++ /dev/null @@ -1,418 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_string.cpp - * @author Piotr Marcinkiewicz (p.marcinkiew@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of string tests - */ -#include -#include -#include -#include -#include -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL) - -unsigned char GetBaseCode(int index); -unsigned char GetBaseCode(int index) -{ - /* aaaack but it's fast and const should make it shared text page. */ - static const unsigned char pr2six[256] = { - /* ASCII table */ - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63, - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, - 64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64, - 64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64, - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64 - }; - return pr2six[index]; -} - -/* Function adapted from APR library (http://apr.apache.org/) */ -int wbxml_base64_decode(const char *buffer, char **result); -int wbxml_base64_decode(const char *buffer, char **result) -{ - int nbytesdecoded = 0, nprbytes = 0; - const char *bufin = NULL; - char *bufout = NULL; - - if ((buffer == NULL) || (result == NULL)) { - return 0; - } - - /* Initialize output buffer */ - *result = NULL; - - bufin = buffer; - while (GetBaseCode(*(bufin++)) <= 63) {} - - nprbytes = (bufin - buffer) - 1; - nbytesdecoded = ((nprbytes + 3) / 4) * 3; - - /* Malloc result buffer */ - if ((*result = (char*) malloc(nbytesdecoded + 1)) == NULL) { - return 0; - } - memset(*result, 0, nbytesdecoded + 1); - - bufout = *result; - bufin = buffer; - - while (nprbytes > 4) { - *(bufout++) = - (char)(GetBaseCode(*bufin) << 2 | GetBaseCode(bufin[1]) >> 4); - *(bufout++) = - (char)(GetBaseCode(bufin[1]) << 4 | GetBaseCode(bufin[2]) >> 2); - *(bufout++) = (char)(GetBaseCode(bufin[2]) << 6 | GetBaseCode(bufin[3])); - bufin += 4; - nprbytes -= 4; - } - - /* Note: (nprbytes == 1) would be an error, so just ingore that case */ - if (nprbytes > 1) { - *(bufout++) = - (char)(GetBaseCode(*bufin) << 2 | GetBaseCode(bufin[1]) >> 4); - } - if (nprbytes > 2) { - *(bufout++) = - (char)(GetBaseCode(bufin[1]) << 4 | GetBaseCode(bufin[2]) >> 2); - } - if (nprbytes > 3) { - *(bufout++) = (char)(GetBaseCode(bufin[2]) << 6 | GetBaseCode(bufin[3])); - } - - nbytesdecoded -= (4 - nprbytes) & 3; - - return nbytesdecoded; -} - -//#define TEST_CONVERSION(in_string, out_string, buffer_type, function - -const char utf32Encoded[] = - "RDAAAI0wAABvMAAAazAAAHswAAB4MAAAaDAAAAAwAABhMAAAijAAAGwwAACLMAAAkjAAAAAwAACP\ -MAAASzAAAIgwAABfMAAAjDAAAF0wAAAAMAAAZDAAAG0wAABqMAAAiTAAAIAwAAAAMAAARjAAAJAw\ -AABuMAAASjAAAE8wAACEMAAAfjAAAAAwAABRMAAAdTAAAFMwAABIMAAAZjAAAAAwAABCMAAAVTAA\ -AE0wAACGMAAAgTAAAH8wAABXMAAAADAAAJEwAAByMAAAgjAAAFswAABZMAAACgAAANsFAADaBQAA\ -IAAAANQFAADqBQAA6AUAAOEFAADnBQAAIAAAAOAFAADkBQAA5QUAACAAAADiBQAA3AUAACAAAADS\ -BQAA1QUAANYFAADcBQAAIAAAAOcFAADYBQAA3wUAACwAAAAgAAAA6QUAANMFAADXBQAA4wUAACAA\ -AADQBQAA6gUAACAAAADmBQAA0QUAANkFAAAgAAAA3AUAAN4FAADZBQAA3QUAAAoAAACk0AAApMIA\ -AFjHAAAgAAAA4KwAACDHAABwyAAAdKwAAEDHAAAgAAAAhccAACDCAAB8sAAArLkAACAAAADMuQAA\ -mLAAAHzFAAAgAAAAWNUAAOCsAAAgAAAAudIAAMS8AABc1QAAIAAAADCuAAAgwgAAQMcAACAAAABE\ -1QAAlMYAAFjOAAAgAAAASsUAAOSyAAAKAAAAUAAAAGMAAABoAAAAbgAAAAUBAAAHAQAAIAAAAHcA\ -AAAgAAAAdAAAABkBAAAgAAAAQgEAAPMAAABkAAAAegEAACAAAABqAAAAZQAAAHwBAABhAAAAIAAA\ -AGwAAAB1AAAAYgAAACAAAABvAAAAWwEAAG0AAAAgAAAAcwAAAGsAAAByAAAAegAAAHkAAABEAQAA\ -IAAAAGYAAABpAAAAZwAAAC4AAAAKAAAAQgAAAGwAAABvAAAAdwAAAHoAAAB5AAAAIAAAAG4AAABp\ -AAAAZwAAAGgAAAB0AAAALQAAAGYAAAByAAAAdQAAAG0AAABwAAAAcwAAACAAAAB2AAAAZQAAAHgA\ -AAAnAAAAZAAAACAAAABKAAAAYQAAAGMAAABrAAAAIAAAAFEAAAAuAAAACgAAAEYGAAA1BgAAIAAA\ -AC0GAABDBgAASgYAAEUGAAAgAAAARAYAAEcGAAAgAAAAMwYAADEGAAAgAAAAQgYAACcGAAA3BgAA\ -OQYAACAAAABIBgAAMAYAAEgGAAAgAAAANAYAACMGAABGBgAAIAAAADkGAAA4BgAASgYAAEUGAAAg\ -AAAARQYAAEMGAAAqBgAASAYAACgGAAAgAAAAOQYAAEQGAABJBgAAIAAAACsGAABIBgAAKAYAACAA\ -AAAjBgAALgYAADYGAAAxBgAAIAAAAEgGAABFBgAAOgYAAEQGAABBBgAAIAAAACgGAAAsBgAARAYA\ -AC8GAAAgAAAAIwYAADIGAAAxBgAAQgYAACAAAAAKAAAAEgQAACAAAABHBAAAMAQAAEkEAAAwBAAA\ -RQQAACAAAABOBAAAMwQAADAEAAAgAAAANgQAADgEAAA7BAAAIAAAADEEAABLBAAAIAAAAEYEAAA4\ -BAAAQgQAAEAEAABDBAAAQQQAAD8AAAAgAAAAFAQAADAEAAAsAAAAIAAAAD0EAAA+BAAAIAAAAEQE\ -AAAwBAAAOwQAAEwEAABIBAAAOAQAADIEAABLBAAAOQQAACAAAABNBAAAOgQAADcEAAA1BAAAPAQA\ -AD8EAAA7BAAATwQAAEAEAAAhAAAACgAAAKQDAACsAwAAxwMAALkDAADDAwAAxAMAALcDAAAgAAAA\ -sQMAALsDAADOAwAAwAMAALcDAAC+AwAAIAAAALIDAACxAwAAxgMAAK4DAADCAwAAIAAAAMgDAAC3\ -AwAAvAMAAK0DAAC9AwAAtwMAACAAAACzAwAAtwMAACwAAAAgAAAAtAMAAMEDAACxAwAAwwMAALoD\ -AAC1AwAAuwMAAK8DAAC2AwAAtQMAALkDAAAgAAAAxQMAAMADAACtAwAAwQMAACAAAAC9AwAAyQMA\ -ALgDAADBAwAAvwMAAM0DAAAgAAAAugMAAMUDAAC9AwAAzAMAAMIDAAAKAAAAVgAAAGkAAABjAAAA\ -dAAAAG8AAAByAAAAIAAAAGoAAABhAAAAZwAAAHQAAAAgAAAAegAAAHcAAAD2AAAAbAAAAGYAAAAg\ -AAAAQgAAAG8AAAB4AAAAawAAAOQAAABtAAAAcAAAAGYAAABlAAAAcgAAACAAAABxAAAAdQAAAGUA\ -AAByAAAAIAAAAPwAAABiAAAAZQAAAHIAAAAgAAAAZAAAAGUAAABuAAAAIAAAAGcAAAByAAAAbwAA\ -AN8AAABlAAAAbgAAACAAAABTAAAAeQAAAGwAAAB0AAAAZQAAAHIAAAAgAAAARAAAAGUAAABpAAAA\ -YwAAAGgAAAAKAAAAlokAAM6RAAAhcQAAUJYAAONeAAAM/wAAl3oAABZZAAAJZwAAzYUAAClZAAAK\ -AAAACgAAAAAAAAA="; - -const char utf8Encoded[] = - "44GE44KN44Gv44Gr44G744G444Go44CA44Gh44KK44Gs44KL44KS44CA44KP44GL44KI44Gf44KM\ -44Gd44CA44Gk44Gt44Gq44KJ44KA44CA44GG44KQ44Gu44GK44GP44KE44G+44CA44GR44G144GT\ -44GI44Gm44CA44GC44GV44GN44KG44KB44G/44GX44CA44KR44Gy44KC44Gb44GZCteb15og15TX\ -qteo16HXpyDXoNek16Ug16LXnCDXkteV15bXnCDXp9eY158sINep15PXl9ejINeQ16og16bXkdeZ\ -INec157XmdedCu2CpOyKpOydmCDqs6DsnKDsobDqsbTsnYAg7J6F7Iig64G866asIOunjOuCmOyV\ -vCDtlZjqs6Ag7Yq567OE7ZWcIOq4sOyIoOydgCDtlYTsmpTsuZgg7JWK64ukClBjaG7EhcSHIHcg\ -dMSZIMWCw7NkxbogamXFvGEgbHViIG/Fm20gc2tyennFhCBmaWcuCkJsb3d6eSBuaWdodC1mcnVt\ -cHMgdmV4J2QgSmFjayBRLgrZhti1INit2YPZitmFINmE2Ycg2LPYsSDZgtin2LfYuSDZiNiw2Ygg\ -2LTYo9mGINi52LjZitmFINmF2YPYqtmI2Kgg2LnZhNmJINir2YjYqCDYo9iu2LbYsSDZiNmF2LrZ\ -hNmBINio2KzZhNivINij2LLYsdmCIArQkiDRh9Cw0YnQsNGFINGO0LPQsCDQttC40Lsg0LHRiyDR\ -htC40YLRgNGD0YE/INCU0LAsINC90L4g0YTQsNC70YzRiNC40LLRi9C5INGN0LrQt9C10LzQv9C7\ -0Y/RgCEKzqTOrM+HzrnPg8+EzrcgzrHOu8+Oz4DOt86+IM6yzrHPhs6uz4Igz4jOt868zq3Ovc63\ -IM6zzrcsIM60z4HOsc+DzrrOtc67zq/Ots61zrkgz4XPgM6tz4Egzr3Pic64z4HOv8+NIM66z4XO\ -vc+Mz4IKVmljdG9yIGphZ3QgenfDtmxmIEJveGvDpG1wZmVyIHF1ZXIgw7xiZXIgZGVuIGdyb8Of\ -ZW4gU3lsdGVyIERlaWNoCuimlumHjueEoemZkOW7o++8jOeql+WkluacieiXjeWkqQoKAA=="; - -const char asciiEncodedIso1[] = - "ISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZ\ -WltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fgA="; - -const char asciiEncodedUtf32[] = - "IQAAACIAAAAjAAAAJAAAACUAAAAmAAAAJwAAACgAAAApAAAAKgAAACsAAAAsAAAALQAAAC4AAAAv\ -AAAAMAAAADEAAAAyAAAAMwAAADQAAAA1AAAANgAAADcAAAA4AAAAOQAAADoAAAA7AAAAPAAAAD0A\ -AAA+AAAAPwAAAEAAAABBAAAAQgAAAEMAAABEAAAARQAAAEYAAABHAAAASAAAAEkAAABKAAAASwAA\ -AEwAAABNAAAATgAAAE8AAABQAAAAUQAAAFIAAABTAAAAVAAAAFUAAABWAAAAVwAAAFgAAABZAAAA\ -WgAAAFsAAABcAAAAXQAAAF4AAABfAAAAYAAAAGEAAABiAAAAYwAAAGQAAABlAAAAZgAAAGcAAABo\ -AAAAaQAAAGoAAABrAAAAbAAAAG0AAABuAAAAbwAAAHAAAABxAAAAcgAAAHMAAAB0AAAAdQAAAHYA\ -AAB3AAAAeAAAAHkAAAB6AAAAewAAAHwAAAB9AAAAfgAAAAAAAAA="; - -/* -Name: String_ConverterFromASCII -Description: tests construction of string from ascii data -Expected: data stored in buffer should match expected -*/ -RUNNER_TEST(String_ConverterFromASCII) -{ - char* inStr = NULL; - int inSize = wbxml_base64_decode(asciiEncodedIso1, &inStr); - RUNNER_ASSERT(inSize > 0); - RUNNER_ASSERT(NULL != inStr); - inStr[inSize] = '\0'; - { - DPL::String asciiString = DPL::FromASCIIString(inStr); - - std::string result = DPL::ToUTF8String(asciiString); - - RUNNER_ASSERT(strlen(inStr) == result.size()); - - RUNNER_ASSERT(0 == memcmp(inStr, result.c_str(), result.size())); - } - - free(inStr); -} - -/* -Name: String_ConverterFromUTF8 -Description: tests construction of string from UTF-8 data -Expected: data stored in buffer should match expected -*/ -RUNNER_TEST(String_ConverterFromUTF8) -{ - char* inStr = NULL; - int inSize = wbxml_base64_decode(asciiEncodedIso1, &inStr); - RUNNER_ASSERT(inSize > 0); - RUNNER_ASSERT(NULL != inStr); - { - DPL::String asciiString = DPL::FromUTF8String(inStr); - - std::string result = DPL::ToUTF8String(asciiString); - - RUNNER_ASSERT(strlen(inStr) == result.size()); - - RUNNER_ASSERT(0 == memcmp(inStr, result.c_str(), result.size())); - } - - free(inStr); -} - -/* -Name: String_ConverterFromUTF32 -Description: tests construction of string from UTF-32 data -Expected: data stored in buffer should match expected -*/ -RUNNER_TEST(String_ConverterFromUTF32) -{ - wchar_t* inStr = NULL; - int inSize = - wbxml_base64_decode(utf32Encoded, reinterpret_cast(&inStr)); - RUNNER_ASSERT(inSize > 0); - RUNNER_ASSERT(NULL != inStr); - char* outStr = NULL; - int outSize = wbxml_base64_decode(utf8Encoded, &outStr); - RUNNER_ASSERT(outSize > 0); - RUNNER_ASSERT(NULL != outStr); - outStr[outSize] = '\0'; - { - DPL::String utfString = DPL::FromUTF32String(inStr); - std::string result = DPL::ToUTF8String(utfString); - - RUNNER_ASSERT(strlen(outStr) == result.size()); - RUNNER_ASSERT(0 == memcmp(outStr, result.c_str(), result.size())); - - RUNNER_ASSERT(inSize / sizeof(wchar_t) - 1 == utfString.size()); - RUNNER_ASSERT(0 == - memcmp(inStr, &(utfString[0]), utfString.size() * - sizeof(wchar_t))); - } - - free(inStr); -} - -template -void String_TokenizeReal(const DelimiterType& delimiter) -{ - DPL::String str(L".##..abc.#."); - std::vector tokens; - DPL::Tokenize(str, delimiter, std::back_inserter(tokens)); - - std::vector expectedTokens; - for (int i = 0; i < 5; i++) { - expectedTokens.push_back(L""); - } - expectedTokens.push_back(L"abc"); - for (int i = 0; i < 3; i++) { - expectedTokens.push_back(L""); - } - - RUNNER_ASSERT(expectedTokens == tokens); - tokens.clear(); - expectedTokens.clear(); - - DPL::Tokenize(str, delimiter, std::back_inserter(tokens), true); - expectedTokens.push_back(L"abc"); - RUNNER_ASSERT(expectedTokens == tokens); -} - -/* -Name: String_Tokenize -Description: tests of string splitting -Expected: returned substring should match expected values -*/ -RUNNER_TEST(String_Tokenize) -{ - String_TokenizeReal(L"#."); - String_TokenizeReal(L".#"); - String_TokenizeReal(L".....####.###.."); - String_TokenizeReal(DPL::String(L".#")); - - std::vector tokens; - DPL::Tokenize(std::string("abc.def"), '.', std::back_inserter(tokens)); - std::vector expectedTokens; - expectedTokens.push_back("abc"); - expectedTokens.push_back("def"); - - RUNNER_ASSERT(tokens == expectedTokens); -} - -template -void TestInStreams( - std::basic_string argumentInString, - std::basic_string argumentResultString) -{ - typedef std::basic_string - String; - std::basic_istringstream - istream(argumentInString); - int intValue = 0; - double doubleValue = 0.0; - float floatValue = 0.0; - String stringValue; - - istream >> intValue; - RUNNER_ASSERT(!istream.fail()); - istream >> doubleValue; - RUNNER_ASSERT(!istream.fail()); - istream >> floatValue; - RUNNER_ASSERT(!istream.fail()); - istream >> stringValue; - RUNNER_ASSERT(!istream.fail()); - - RUNNER_ASSERT(1 == intValue); - RUNNER_ASSERT(fabs(1.1f - doubleValue) < 0.00001); - RUNNER_ASSERT(fabs(1.1f - floatValue) < 0.00001); - RUNNER_ASSERT(argumentResultString == stringValue); -} - -template -void TestOutStreams( - std::basic_string argumentInString, - std::basic_string argumentResultString) -{ - typedef std::basic_string - String; - - std::basic_ostringstream - ostream; - - int intValue = 1; - double doubleValue = 1.1; - float floatValue = 1.1f; - String stringValue = argumentInString; - - ostream << intValue; - RUNNER_ASSERT(!ostream.fail()); - ostream << doubleValue; - RUNNER_ASSERT(!ostream.fail()); - ostream << floatValue; - RUNNER_ASSERT(!ostream.fail()); - ostream << stringValue; - RUNNER_ASSERT(!ostream.fail()); - - RUNNER_ASSERT(ostream.str() == argumentResultString); -} - -/* -Name: String_Streams -Description: tests of input/output stream -Expected: returned substrign should match expected values -*/ -RUNNER_TEST(String_Streams) -{ - TestInStreams >("1 1.1 1.1 test", "test"); - TestInStreams >(L"1 1.1 1.1 test", L"test"); - TestInStreams(L"1 1.1 1.1 test", L"test"); - TestOutStreams >("test", "11.11.1test"); - TestOutStreams >(L"test", L"11.11.1test"); - TestOutStreams(L"test", L"11.11.1test"); -} - -/* -Name: String_CompareCaseSensitive -Description: tests case sensitive comparision -Expected: strings should be equal -*/ -RUNNER_TEST(String_CompareCaseSensitive) -{ - RUNNER_ASSERT( - DPL::StringCompare( - DPL::FromUTF32String(L"Ala Makota ma żołądkówkę"), - DPL::FromUTF32String(L"Ala Makota ma żołądkówkę")) == 0); -} - -/* -Name: String_CompareCaseInsensitive -Description: tests case insensitive comparision -Expected: strings should be equal -*/ -RUNNER_TEST(String_CompareCaseInsensitive) -{ - RUNNER_ASSERT( - DPL::StringCompare( - DPL::FromUTF32String(L"Ala Makota ma żołądkówkę"), - DPL::FromUTF32String(L"AlA MakOTA ma ŻoŁąDKÓwkę"), - true) == 0); -} - diff --git a/tests/dpl/core/test_thread.cpp b/tests/dpl/core/test_thread.cpp deleted file mode 100644 index 5db0dc1..0000000 --- a/tests/dpl/core/test_thread.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_thread.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of thread tests - */ -#include -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL) - -bool g_wasFooDeleted; - -class Foo -{ - public: - int id; - Foo(int i = 0) : id(i) - { - LogInfo("Foo: ctor: " << id); - } - - ~Foo() - { - LogInfo("Foo: dtor: " << id); - g_wasFooDeleted = true; - } - - void Bar() - { - LogInfo("Foo: bar"); - } -}; - -typedef DPL::ThreadLocalVariable TlsFoo; -TlsFoo g_foo; - -class FooThread : - public DPL::Thread -{ - protected: - virtual int ThreadEntry() - { - LogInfo("In thread"); - - RUNNER_ASSERT(!g_foo); - RUNNER_ASSERT(g_foo.IsNull()); - - g_foo = Foo(); - g_foo->Bar(); - - return 0; - } -}; - -/* -Name: Thread_ThreadLocalVariable_FooDeletion -Description: tests local thread variable pattern -Expected: local thread variables should not be affected by other threads -*/ -RUNNER_TEST(Thread_ThreadLocalVariable_FooDeletion) -{ - static TlsFoo staticFooForMain; - staticFooForMain = Foo(1); - - TlsFoo fooForMain; - fooForMain = Foo(2); - - RUNNER_ASSERT(!g_foo); - RUNNER_ASSERT(g_foo.IsNull()); - - g_wasFooDeleted = false; - - FooThread thread1; - thread1.Run(); - thread1.Quit(); - - RUNNER_ASSERT(!g_foo); - RUNNER_ASSERT(g_foo.IsNull()); - - RUNNER_ASSERT(g_wasFooDeleted == true); - - FooThread thread2; - thread2.Run(); - thread2.Quit(); - - RUNNER_ASSERT(!g_foo); - RUNNER_ASSERT(g_foo.IsNull()); -} diff --git a/tests/dpl/core/test_type_list.cpp b/tests/dpl/core/test_type_list.cpp deleted file mode 100644 index b3e6285..0000000 --- a/tests/dpl/core/test_type_list.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/** - * @file test_type_list.cpp - * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) - * @version 0.1 - * @brief - */ - -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL) - -/* -Name: TypeList_TypeCount -Description: tests size of typelist idiom -Expected: size should match -*/ -RUNNER_TEST(TypeList_TypeCount) -{ - typedef DPL::TypeListDecl::Type TestTypeList1; - typedef DPL::TypeListDecl::Type TestTypeList2; - typedef DPL::TypeListDecl<>::Type TestTypeList3; - typedef DPL::TypeList TestTypeList4; - - RUNNER_ASSERT(TestTypeList1::Size == 3); - RUNNER_ASSERT(TestTypeList2::Size == 1); - RUNNER_ASSERT(TestTypeList3::Size == 0); - RUNNER_ASSERT(TestTypeList4::Size == 4); - - RUNNER_ASSERT(TestTypeList4::Tail::Tail::Size == 2); -} diff --git a/tests/dpl/core/test_zip_input.cpp b/tests/dpl/core/test_zip_input.cpp deleted file mode 100644 index c62accb..0000000 --- a/tests/dpl/core/test_zip_input.cpp +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_zip_input.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of zip input tests - */ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { -const char* PATH_NO_FILE = "/opt/share/wrt/wrt-commons/tests/core/no_such_file"; -const char* PATH_ARCHIVE = "/opt/share/wrt/wrt-commons/tests/core/sample.zip"; -const char* ARCHIVED_FILE = "sample.txt"; -} - -RUNNER_TEST_GROUP_INIT(DPL) - -/* -Name: ZipInput_OpenFailed -Description: tests opening non existing file -Expected: exception throw -*/ -RUNNER_TEST(ZipInput_OpenFailed) -{ - bool opened = true; - - Try - { - DPL::ZipInput zip(PATH_NO_FILE); - (void)zip; - } - Catch(DPL::ZipInput::Exception::OpenFailed) - { - opened = false; - } - - RUNNER_ASSERT(opened == false); -} - -/* -Name: ZipInput_OpenFile -Description: tests opening existing file -Expected: zip stats should mkatch expected -*/ -RUNNER_TEST(ZipInput_OpenFile) -{ - DPL::ZipInput zip(PATH_ARCHIVE); - - FOREACH(iter, zip) - { - LogDebug("---------"); - LogDebug("FileInfo: "); -#define FIELD(X) LogDebug(#X ": " << iter->X) - FIELD(name); - FIELD(comment); - FIELD(compressedSize); - FIELD(uncompressedSize); -#undef FIELD - } -} - -/* -Name: ZipInput_UnzipSingleFile -Description: tests opening existing file and unzipping single file -Expected: right content -*/ -RUNNER_TEST(ZipInput_UnzipSingleFile) -{ - DPL::ZipInput zip(PATH_ARCHIVE); - DPL::ZipInput::File *file = zip.OpenFile(ARCHIVED_FILE); - DPL::AbstractWaitableInputAdapter fileAdapter(file); - DPL::BinaryQueue buffer; - DPL::AbstractWaitableOutputAdapter bufferAdapter(&buffer); - - DPL::Copy(&fileAdapter, &bufferAdapter); - - DPL::ScopedArray data(new char[buffer.Size() + 1]); - buffer.Flatten(data.Get(), buffer.Size()); - data[buffer.Size()] = '\0'; - - RUNNER_ASSERT(std::string(data.Get()) == "test"); -} diff --git a/tests/dpl/db/CMakeLists.txt b/tests/dpl/db/CMakeLists.txt deleted file mode 100644 index f4b5c22..0000000 --- a/tests/dpl/db/CMakeLists.txt +++ /dev/null @@ -1,49 +0,0 @@ -# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved -# -# 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. -# -# @file CMakeLists.txt -# @author Lukasz Marek (l.marek@samsung.com) -# @version 1.0 -# @brief -# - -# -# Test files -# -# Define all DPL tests sources. -# Runner is responsible for runnint it all and -# generating proper output files -# - -SET(TARGET_NAME "dpl-tests-db") - -# Set DPL tests sources -SET(DPL_TESTS_DB_SOURCES - ${TESTS_DPL_DIR}/db/main.cpp - ${TESTS_DPL_DIR}/db/test_orm.cpp - ${TESTS_DPL_DIR}/db/test_sql_connection.cpp -) - -ADD_SUBDIRECTORY(orm) - -#include subdirectory -WRT_INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/orm) -WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_NAME} ${TARGET_DPL_DB_EFL}) -WRT_TEST_BUILD(${TARGET_NAME} ${DPL_TESTS_DB_SOURCES}) -WRT_TEST_INSTALL(${TARGET_NAME}) - -INSTALL(FILES - ${TESTS_DPL_DIR}/db/orm/dpl_orm_test.db - DESTINATION /opt/share/wrt/wrt-commons/tests/db -) diff --git a/tests/dpl/db/main.cpp b/tests/dpl/db/main.cpp deleted file mode 100644 index 4ed6191..0000000 --- a/tests/dpl/db/main.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/** - * @file main.cpp - * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of main. - */ - -#include - -int main(int argc, char *argv[]) -{ - return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); -} diff --git a/tests/dpl/db/orm/CMakeLists.txt b/tests/dpl/db/orm/CMakeLists.txt deleted file mode 100644 index b7ebafb..0000000 --- a/tests/dpl/db/orm/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -WRT_INTROSPECT_TARGET(db ${TARGET_DPL_DB_EFL}) -WRT_CONVERT_TO_GCC_LIST(db_INCLUDE_DIRS_GCC ${db_INCLUDE_DIRS}) - -ADD_CUSTOM_COMMAND( OUTPUT dpl_orm_test_db.sql - COMMAND rm -f ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test.db - COMMAND C_INCLUDE_PATH=${db_INCLUDE_DIRS_GCC} gcc -Wall -E ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test_db_sql_generator.h | grep --invert-match "^#" > ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test_db.sql - COMMAND sqlite3 ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test.db ".read ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test_db.sql" || rm -f ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test.db - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test_db_sql_generator.h ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test_db -) - -ADD_CUSTOM_TARGET( Sqlite3Db ALL DEPENDS dpl_orm_test_db.sql ) diff --git a/tests/dpl/db/orm/dpl_orm_test_db b/tests/dpl/db/orm/dpl_orm_test_db deleted file mode 100644 index 0d1963b..0000000 --- a/tests/dpl/db/orm/dpl_orm_test_db +++ /dev/null @@ -1,88 +0,0 @@ - -CREATE_TABLE(TestTableInsert) - COLUMN(ColumnOptInt, INT,) - COLUMN(ColumnOptText, TEXT,) - COLUMN_NOT_NULL(ColumnInt, INT, DEFAULT 99) - COLUMN_NOT_NULL(ColumnInt2, INT,) - COLUMN_NOT_NULL(ColumnText, TEXT,) -CREATE_TABLE_END() - -CREATE_TABLE(TestTableDelete) - COLUMN(ColumnOptInt, INT,) - COLUMN(ColumnOptText, TEXT,) - COLUMN_NOT_NULL(ColumnInt, INT, DEFAULT 99) - COLUMN_NOT_NULL(ColumnInt2, INT,) - COLUMN_NOT_NULL(ColumnText, TEXT,) -CREATE_TABLE_END() - -SQL( - INSERT INTO TestTableDelete VALUES(1, "two", 3, 4, "five"); - INSERT INTO TestTableDelete VALUES(6, "seven", 8, 9, "ten"); - INSERT INTO TestTableDelete (ColumnInt2, ColumnText) VALUES(11, "twelve"); - INSERT INTO TestTableDelete (ColumnInt2, ColumnText) VALUES(13, "fourteen"); -) - -CREATE_TABLE(TestTable) - COLUMN(ColumnOptInt, INT,) - COLUMN(ColumnOptText, TEXT,) - COLUMN_NOT_NULL(ColumnInt, INT, DEFAULT 99) - COLUMN_NOT_NULL(ColumnInt2, INT,) - COLUMN_NOT_NULL(ColumnText, TEXT,) -CREATE_TABLE_END() - -SQL( - INSERT INTO TestTable VALUES(1, "two", 3, 4, "five"); - INSERT INTO TestTable VALUES(6, "seven", 8, 9, "ten"); - INSERT INTO TestTable (ColumnInt2, ColumnText) VALUES(11, "twelve"); - INSERT INTO TestTable (ColumnInt2, ColumnText) VALUES(13, "fourteen"); -) - -CREATE_TABLE(TestTableJoin1) - COLUMN_NOT_NULL(TestID, INT,) - COLUMN_NOT_NULL(TestText, TEXT,) - COLUMN(TestNumber, INT,) - TABLE_CONSTRAINTS( - PRIMARY KEY(TestID) - ) -CREATE_TABLE_END() - -CREATE_TABLE(TestTableJoin2) - COLUMN_NOT_NULL(TestID, INT,) - COLUMN_NOT_NULL(TestText1, TEXT,) - COLUMN_NOT_NULL(TestText2, TEXT,) - TABLE_CONSTRAINTS( - PRIMARY KEY(TestID) - ) -CREATE_TABLE_END() - -CREATE_TABLE(TestTableJoin3) - COLUMN_NOT_NULL(TestID, INT,) - COLUMN(Value3, INT,) - COLUMN(TestText33, TEXT,) - TABLE_CONSTRAINTS( - PRIMARY KEY(TestID) - ) -CREATE_TABLE_END() - -SQL( - INSERT INTO TestTableJoin1 VALUES(1, "text val 1", 111); - INSERT INTO TestTableJoin1 VALUES(2, "text val 2", 222); - INSERT INTO TestTableJoin1 VALUES(3, "text val 3", 333); - INSERT INTO TestTableJoin1 VALUES(4, "text val 4", 444); - INSERT INTO TestTableJoin1 VALUES(5, "text val 5", 555); - INSERT INTO TestTableJoin1 VALUES(6, "text val 6", 666); - - INSERT INTO TestTableJoin2 VALUES(1, "01", "text2 1"); - INSERT INTO TestTableJoin2 VALUES(2, "02", "text2 2"); - INSERT INTO TestTableJoin2 VALUES(3, "03", "text2 3"); - INSERT INTO TestTableJoin2 VALUES(4, " 4 ", "text2 4"); - INSERT INTO TestTableJoin2 VALUES(5, "*5*", "text2 5"); - INSERT INTO TestTableJoin2 VALUES(10, "6", "text2 6"); - - INSERT INTO TestTableJoin3 VALUES(1, 111, "test 1"); - INSERT INTO TestTableJoin3 VALUES(2, 111, "test 2"); - INSERT INTO TestTableJoin3 VALUES(3, 222, "test 3"); - INSERT INTO TestTableJoin3 VALUES(6, 222, "test 4"); - INSERT INTO TestTableJoin3 (TestID, TestText33) VALUES(7, "test 5"); - INSERT INTO TestTableJoin3 (TestID, TestText33) VALUES(10, "test 6"); -) diff --git a/tests/dpl/db/orm/dpl_orm_test_db_definitions b/tests/dpl/db/orm/dpl_orm_test_db_definitions deleted file mode 100644 index da79427..0000000 --- a/tests/dpl/db/orm/dpl_orm_test_db_definitions +++ /dev/null @@ -1,5 +0,0 @@ -DATABASE_START(dpl_orm_test) - -#include "dpl_orm_test_db" - -DATABASE_END() diff --git a/tests/dpl/db/orm/dpl_orm_test_db_sql_generator.h b/tests/dpl/db/orm/dpl_orm_test_db_sql_generator.h deleted file mode 100644 index cac41cc..0000000 --- a/tests/dpl/db/orm/dpl_orm_test_db_sql_generator.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file dpl_orm_test_db_sql_generator.h - * @author Lukasz Marek (l.marek@samsung.com) - * @version 1.0 - * @brief Macro definitions for generating the SQL input file from - * database definition. - */ - -//Do not include this file directly! It is used only for SQL code generation. - -#include - -#include "dpl_orm_test_db_definitions" diff --git a/tests/dpl/db/orm/dpl_orm_test_db_sql_generator.h.gch b/tests/dpl/db/orm/dpl_orm_test_db_sql_generator.h.gch deleted file mode 100644 index 5bd675d..0000000 Binary files a/tests/dpl/db/orm/dpl_orm_test_db_sql_generator.h.gch and /dev/null differ diff --git a/tests/dpl/db/orm/generator_dpl_orm_test.h b/tests/dpl/db/orm/generator_dpl_orm_test.h deleted file mode 100644 index 39bb1b7..0000000 --- a/tests/dpl/db/orm/generator_dpl_orm_test.h +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ - -#ifndef ORM_GENERATOR_DPL_ORM_TEST_H -#define ORM_GENERATOR_DPL_ORM_TEST_H - -#define ORM_GENERATOR_DATABASE_NAME dpl_orm_test_db_definitions -#include -#undef ORM_GENERATOR_DATABASE_NAME - -#endif diff --git a/tests/dpl/db/test_orm.cpp b/tests/dpl/db/test_orm.cpp deleted file mode 100644 index 500f43d..0000000 --- a/tests/dpl/db/test_orm.cpp +++ /dev/null @@ -1,1140 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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 -#include -#include -#include -#include - -const char* PATH_DB = "/opt/share/wrt/wrt-commons/tests/db/dpl_orm_test.db"; - -//utils - -#define TEST_REPETITION 16 - -class SmartAttach -{ - public: - - SmartAttach(bool autoattach = true) : - m_interface(PATH_DB, - DPL::DB::SqlConnection::Flag::UseLucene), - m_autoattach(autoattach) - { - if (m_autoattach) { - m_interface.AttachToThread(DPL::DB::SqlConnection::Flag::RW); - } - } - - ~SmartAttach() - { - if (m_autoattach) { - m_interface.DetachFromThread(); - } - } - - DPL::DB::ThreadDatabaseSupport* get() - { - return &m_interface; - } - - private: - DPL::DB::ThreadDatabaseSupport m_interface; - bool m_autoattach; -}; - -template -bool ContainerContentsEqual(const ContainerType1& container1, - const ContainerType2& container2) -{ - using namespace DPL::DB::ORM::dpl_orm_test::TestTableInsert; - typedef std::set Set1; - typedef std::set Set2; - Set1 set1(container1.begin(), container1.end()); - Set2 set2(container2.begin(), container2.end()); - - for (typename Set1::iterator it = set1.begin(); - it != set1.end(); - it++) - { - LogDebug("Set1 element: " << *it); - } - - for (typename Set2::iterator it = set2.begin(); it != set2.end(); it++) { - LogDebug("Set2 element: " << *it); - } - - return set1 == set2; -} - -template -std::list makeList(const T& a, const T& b) -{ - std::list list; - list.push_back(a); - list.push_back(b); - return list; -} - -//tests - -RUNNER_TEST_GROUP_INIT(DPL) - -/* -Name: ORM_SelectSingleValue -Description: tests quering single value of single row from database -Expected: Values should match those which were prepared -*/ -RUNNER_TEST(ORM_SelectSingleValue) -{ - SmartAttach interface; - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::dpl_orm_test; - //Getting each column - { - TestTable::Select select(interface.get()); - select.Where(Equals(8)); - int result; - RUNNER_ASSERT_MSG((result = - *select.GetSingleValue()) - == 6, "Got " << - result); - } - { - TestTable::Select select(interface.get()); - select.Where(Equals(8)); - DPL::String result; - RUNNER_ASSERT_MSG((result = - *select.GetSingleValue( - )) == L"seven", - "Got " << result); - } - { - TestTable::Select select(interface.get()); - select.Where(Equals(8)); - int result; - RUNNER_ASSERT_MSG((result = select.GetSingleValue( - )) == 8, "Got " << result); - } - { - TestTable::Select select(interface.get()); - select.Where(Equals(8)); - int result; - RUNNER_ASSERT_MSG((result = select.GetSingleValue( - )) == 9, "Got " << result); - } - { - TestTable::Select select(interface.get()); - select.Where(Equals(8)); - DPL::String result; - RUNNER_ASSERT_MSG((result = select.GetSingleValue( - )) == L"ten", "Got " << result); - } - - //Where on each column - { - TestTable::Select select(interface.get()); - select.Where(Equals(6)); - int result; - RUNNER_ASSERT_MSG((result = - *select.GetSingleValue()) - == 6, "Got " << - result); - } - { - TestTable::Select select(interface.get()); - select.Where(Equals(DPL::String(L"seven"))); - DPL::String result; - RUNNER_ASSERT_MSG((result = - *select.GetSingleValue( - )) == L"seven", - "Got " << result); - } - { - TestTable::Select select(interface.get()); - select.Where(Equals(8)); - int result; - RUNNER_ASSERT_MSG((result = select.GetSingleValue( - )) == 8, "Got " << result); - } - { - TestTable::Select select(interface.get()); - select.Where(Equals(9)); - int result; - RUNNER_ASSERT_MSG((result = select.GetSingleValue( - )) == 9, "Got " << result); - } - { - TestTable::Select select(interface.get()); - select.Where(Equals(L"ten")); - DPL::String result; - RUNNER_ASSERT_MSG((result = select.GetSingleValue( - )) == L"ten", "Got " << result); - } -} - -/* -Name: ORM_SelectSingleRow -Description: tests quering single row from database -Expected: Values should match those which were prepared -*/ -RUNNER_TEST(ORM_SelectSingleRow) -{ - SmartAttach interface; - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::dpl_orm_test; - { - TestTable::Select select(interface.get()); - select.Where(Equals(3)); - TestTable::Row result = select.GetSingleRow(); - TestTable::Row expected; - expected.Set_ColumnOptInt(1); - expected.Set_ColumnOptText(DPL::String(L"two")); - expected.Set_ColumnInt(3); - expected.Set_ColumnInt2(4); - expected.Set_ColumnText(L"five"); - RUNNER_ASSERT_MSG(result == expected, "Got " << result); - } - - { - TestTable::Select select(interface.get()); - select.Where(Equals(DPL::String(L"seven"))); - TestTable::Row result = select.GetSingleRow(); - TestTable::Row expected; - expected.Set_ColumnOptInt(6); - expected.Set_ColumnOptText(DPL::String(L"seven")); - expected.Set_ColumnInt(8); - expected.Set_ColumnInt2(9); - expected.Set_ColumnText(L"ten"); - RUNNER_ASSERT_MSG(result == expected, "Got " << result); - } -} - -/* -Name: ORM_SelectRowList -Description: tests quering multiple row from database -Expected: Values should match those which were prepared -*/ -RUNNER_TEST(ORM_SelectRowList) -{ - SmartAttach interface; - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::dpl_orm_test; - { - TestTable::Select select(interface.get()); - select.Where(Equals(3)); - std::list result = select.GetRowList(); - RUNNER_ASSERT_MSG(result.size() == 1, "Got " << result.size()); - - TestTable::Row expected; - expected.Set_ColumnOptInt(1); - expected.Set_ColumnOptText(DPL::String(L"two")); - expected.Set_ColumnInt(3); - expected.Set_ColumnInt2(4); - expected.Set_ColumnText(L"five"); - RUNNER_ASSERT_MSG(*(result.begin()) == expected, "Got " << - *(result.begin()) ); - } - - { - TestTable::Select select(interface.get()); - select.Where(Equals(DPL::String(L"seven"))); - std::list result = select.GetRowList(); - RUNNER_ASSERT_MSG(result.size() == 1, "Got " << result.size()); - - TestTable::Row expected; - expected.Set_ColumnOptInt(6); - expected.Set_ColumnOptText(DPL::String(L"seven")); - expected.Set_ColumnInt(8); - expected.Set_ColumnInt2(9); - expected.Set_ColumnText(L"ten"); - RUNNER_ASSERT_MSG(*(result.begin()) == expected, "Got " << - *(result.begin()) ); - } - - { - TestTable::Select select(interface.get()); - select.Where(Equals(99)); - std::list result = select.GetRowList(); - - TestTable::Row expected1; - expected1.Set_ColumnInt(99); - expected1.Set_ColumnInt2(11); - expected1.Set_ColumnText(L"twelve"); - - TestTable::Row expected2; - expected2.Set_ColumnInt(99); - expected2.Set_ColumnInt2(13); - expected2.Set_ColumnText(L"fourteen"); - - RUNNER_ASSERT(ContainerContentsEqual(makeList(expected1, - expected2), result)); - } -} - -/* -Name: ORM_SelectValueList -Description: tests quering single column from multiple row from database -Expected: Values should match those which were prepared -*/ -RUNNER_TEST(ORM_SelectValueList) -{ - SmartAttach interface; - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::dpl_orm_test; - //Getting each column - { - TestTable::Select select(interface.get()); - select.Where(Is(DPL::Optional::Null)); - RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), - makeList(99, 99))); - } - { - TestTable::Select select(interface.get()); - select.Where(Is(DPL::Optional::Null)); - RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), - makeList(11, 13))); - } - { - TestTable::Select select(interface.get()); - select.Where(Is(DPL::Optional::Null)); - RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), - makeList(DPL::String(L"twelve"), - DPL::String(L"fourteen")))); - } - { - TestTable::Select select(interface.get()); - select.Where(Is(DPL::Optional::Null)); - RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), - makeList(DPL::Optional - ::Null, - DPL::Optional - ::Null))); - } - - //Where on each column - { - TestTable::Select select(interface.get()); - select.Where(Is(DPL::Optional::Null)); - RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), - makeList(11, 13))); - } - { - TestTable::Select select(interface.get()); - select.Where(Is(DPL::Optional:: - Null)); - RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), - makeList(11, 13))); - } - { - TestTable::Select select(interface.get()); - select.Where(Is(99)); - RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), - makeList(11, 13))); - } -} - -/* -Name: ORM_MultipleCalls -Description: tests sequnece of different queries -Expected: Values should match those which were prepared -*/ -RUNNER_TEST(ORM_MultipleCalls) -{ - for (int j = 0; j < TEST_REPETITION; j++) { - for (int i = 0; i < TEST_REPETITION; i++) { - ORM_SelectSingleValue(); - } - - for (int i = 0; i < TEST_REPETITION; i++) { - ORM_SelectSingleRow(); - } - - for (int i = 0; i < TEST_REPETITION; i++) { - ORM_SelectRowList(); - } - - for (int i = 0; i < TEST_REPETITION; i++) { - ORM_SelectValueList(); - } - } -} - -/* -Name: ORM_Insert -Description: tests insering rows into database -Expected: Values should be inserted -*/ -RUNNER_TEST(ORM_Insert) -{ - SmartAttach interface; - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::dpl_orm_test; - - TestTableInsert::Select select1(interface.get()); - std::list resultList = select1.GetValueList(); - RUNNER_ASSERT_MSG(resultList.empty(), - "Returned list has wrong size: " << resultList.size()); - - std::list list; - - TestTableInsert::Insert insert(interface.get()); - TestTableInsert::Row row; - row.Set_ColumnOptInt(1); - row.Set_ColumnInt2(2); - row.Set_ColumnText(L"three"); - insert.Values(row); - insert.Execute(); - - row.Set_ColumnInt(99); - list.push_back(row); - { - TestTableInsert::Select select2(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual( - select2.GetRowList(), - list), "Returned list doesn't match."); - } - - TestTableInsert::Insert insert2(interface.get()); - TestTableInsert::Row row2; - row2.Set_ColumnInt(4); - row2.Set_ColumnInt2(5); - row2.Set_ColumnText(L"six"); - insert2.Values(row2); - insert2.Execute(); - - list.push_back(row2); - { - TestTableInsert::Select select(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual( - select.GetRowList(), - list), "Returned list doesn't match."); - } - - TestTableInsert::Insert insert3(interface.get()); - TestTableInsert::Row row3; - row3.Set_ColumnOptInt(1); - row3.Set_ColumnInt2(7); - row3.Set_ColumnText(L"eight"); - insert3.Values(row3); - insert3.Execute(); - - row3.Set_ColumnInt(99); - list.push_back(row3); - { - TestTableInsert::Select select3(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual( - select3.GetRowList(), - list), "Returned list doesn't match."); - } - - TestTableInsert::Insert insert4(interface.get()); - TestTableInsert::Row row4; - row4.Set_ColumnOptInt(9); - row4.Set_ColumnInt2(10); - row4.Set_ColumnText(L"eleven"); - insert4.Values(row4); - insert4.Execute(); - - row4.Set_ColumnInt(99); - list.push_back(row4); - { - TestTableInsert::Select select4(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual( - select4.GetRowList(), - list), "Returned list doesn't match."); - } - - // restore original table state - { - TestTableInsert::Delete del(interface.get()); - del.Execute(); - - TestTableInsert::Select select(interface.get()); - RUNNER_ASSERT(select.GetRowList().size() == 0); - } -} - -/* -Name: ORM_MultipleBindInsert -Description: repeats ORM_Insert test several times -Expected: Values should be inserted -*/ -RUNNER_TEST(ORM_MultipleBindInsert) -{ - for (int i = 0; i < TEST_REPETITION; i++) { - ORM_Insert(); - } -} - -/* -Name: ORM_Delete -Description: tests deleting rows from database -Expected: deleted rows should not exist -*/ -RUNNER_TEST(ORM_Delete) -{ - SmartAttach interface; - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::dpl_orm_test; - TestTableDelete::Select selectStart(interface.get()); - selectStart.OrderBy(DPL::TypeListDecl >()); - std::list list = selectStart.GetRowList(); - std::list originalList = list; - - std::vector vector(list.begin(), list.end()); - RUNNER_ASSERT_MSG( - list.size() == 4, "Returned list has wrong size: " << list.size()); - - typedef DPL::String S; - - //no-act deletes - { - TestTableDelete::Delete del(interface.get()); - del.Where(And(Equals(1), - Equals(S(L"seven")))); - del.Execute(); - - TestTableDelete::Select select(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual( - select.GetRowList(), - list), "Returned list doesn't match."); - } - - { - TestTableDelete::Delete del(interface.get()); - del.Where(And(Equals(6), - Equals(S(L"two")))); - del.Execute(); - - TestTableDelete::Select select(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual( - select.GetRowList(), - list), "Returned list doesn't match."); - } - - { - TestTableDelete::Delete del(interface.get()); - del.Where(Equals(10)); - del.Execute(); - - TestTableDelete::Select select(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual( - select.GetRowList(), - list), "Returned list doesn't match."); - } - - //act deletes - { - list.remove(vector[1]); - - TestTableDelete::Delete del(interface.get()); - del.Where(And(Equals(6), - Equals(L"ten"))); - del.Execute(); - - TestTableDelete::Select select(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual( - select.GetRowList(), - list), "Returned list doesn't match."); - } - - { - list.remove(vector[2]); - list.remove(vector[3]); - - TestTableDelete::Delete del(interface.get()); - del.Where(Is(DPL::Optional - ::Null)); - del.Execute(); - - TestTableDelete::Select select(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual( - select.GetRowList(), - list), "Returned list doesn't match."); - } - - { - TestTableDelete::Delete del(interface.get()); - del.Execute(); - - TestTableDelete::Select select(interface.get()); - RUNNER_ASSERT_MSG( - select.GetRowList().size() == 0, "Returned list is not empty"); - } - - // Restore original table state - // This also tests if multiple different binds for Insert are working - // properly - for (std::list::iterator i = originalList.begin(); - i != originalList.end(); - i++) - { - TestTableDelete::Insert insert(interface.get()); - insert.Values(*i); - insert.Execute(); - } - - { - TestTableDelete::Select select(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual( - select.GetRowList(), - originalList), - "Returned list doesn't match."); - } -} - -/* -Name: ORM_MultipleBindDelete -Description: repeats ORM_Delete test several times -Expected: Values should be deleted -*/ -RUNNER_TEST(ORM_MultipleBindDelete) -{ - for (int i = 0; i < TEST_REPETITION; i++) { - ORM_Delete(); - } -} - -/* -Name: ORM_MultipleBindWhere -Description: tests if multiple bind of same query obejct works -Expected: Each bind and execution of query should be correct -*/ -RUNNER_TEST(ORM_MultipleBindWhere) -{ - SmartAttach interface; - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::dpl_orm_test; - { - TestTable::Select select(interface.get()); - int result; - select.Where(Equals(8)); - RUNNER_ASSERT_MSG((result = - *select.GetSingleValue()) - == 6, "Got " << - result); - - select.Where(Equals(3)); - RUNNER_ASSERT_MSG((result = - *select.GetSingleValue()) - == 1, "Got " << - result); - - select.Where(Equals(8)); - RUNNER_ASSERT_MSG((result = - *select.GetSingleValue()) - == 6, "Got " << - result); - - select.Where(Equals(3)); - RUNNER_ASSERT_MSG((result = - *select.GetSingleValue()) - == 1, "Got " << - result); - } - - { - TestTable::Select select(interface.get()); - int result; - select.Where(And(Equals(99), - Equals(L"fourteen"))); - RUNNER_ASSERT_MSG((result = select.GetSingleValue( - )) == 13, "Got " << result); - - select.Where(And(Equals(99), - Equals(L"twelve"))); - RUNNER_ASSERT_MSG((result = select.GetSingleValue( - )) == 11, "Got " << result); - - select.Where(And(Equals(99), - Equals(L"fourteen"))); - RUNNER_ASSERT_MSG((result = select.GetSingleValue( - )) == 13, "Got " << result); - - select.Where(And(Equals(99), - Equals(L"twelve"))); - RUNNER_ASSERT_MSG((result = select.GetSingleValue( - )) == 11, "Got " << result); - } - - { - TestTable::Select select(interface.get()); - int result; - select.Where(And(Equals(L"fourteen"), - Equals(99))); - RUNNER_ASSERT_MSG((result = select.GetSingleValue( - )) == 13, "Got " << result); - - select.Where(And(Equals(L"twelve"), - Equals(99))); - RUNNER_ASSERT_MSG((result = select.GetSingleValue( - )) == 11, "Got " << result); - - select.Where(And(Equals(L"fourteen"), - Equals(99))); - RUNNER_ASSERT_MSG((result = select.GetSingleValue( - )) == 13, "Got " << result); - - select.Where(And(Equals(L"twelve"), - Equals(99))); - RUNNER_ASSERT_MSG((result = select.GetSingleValue( - )) == 11, "Got " << result); - } -} - -/* -Name: ORM_Update -Description: tests rows update in database -Expected: Successful update -*/ -RUNNER_TEST(ORM_Update) -{ - SmartAttach interface; - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::dpl_orm_test; - - std::list list; - - TestTableInsert::Delete del(interface.get()); - del.Execute(); - - // INSERT - { - TestTableInsert::Insert insert(interface.get()); - TestTableInsert::Row row; - row.Set_ColumnOptInt(5); - row.Set_ColumnInt2(2); - row.Set_ColumnText(L"two"); - insert.Values(row); - insert.Execute(); - - row.Set_ColumnInt(99); - list.push_back(row); - } - { - TestTableInsert::Insert insert(interface.get()); - TestTableInsert::Row row; - row.Set_ColumnOptInt(1); - row.Set_ColumnInt2(2); - row.Set_ColumnText(L"three"); - insert.Values(row); - insert.Execute(); - - row.Set_ColumnInt(99); - list.push_back(row); - } - { - TestTableInsert::Insert insert(interface.get()); - TestTableInsert::Row row; - row.Set_ColumnOptInt(2); - row.Set_ColumnInt2(3); - row.Set_ColumnText(L"three"); - insert.Values(row); - insert.Execute(); - - row.Set_ColumnInt(99); - list.push_back(row); - - // CHECK - TestTableInsert::Select select(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual( - select.GetRowList(), - list), "Returned list doesn't match."); - } - { - // UPDATE - no rows - TestTableInsert::Update update(interface.get()); - TestTableInsert::Row row; - row.Set_ColumnInt2(4); - row.Set_ColumnText(L"four"); - update.Values(row); - update.Where(Equals(12)); - update.Execute(); - - // CHECK - TestTableInsert::Select select(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual( - select.GetRowList(), - list), "Returned list doesn't match."); - } - { - // UPDATE - one row - TestTableInsert::Update update(interface.get()); - TestTableInsert::Row row; - row.Set_ColumnInt2(2); - row.Set_ColumnText(L"four"); - update.Values(row); - update.Where(Equals(3)); - update.Execute(); - - list.back().Set_ColumnInt2(2); - list.back().Set_ColumnText(L"four"); - - // CHECK - TestTableInsert::Select select(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual( - select.GetRowList(), - list), "Returned list doesn't match."); - } - - { - // UPDATE - multiple rows - TestTableInsert::Update update(interface.get()); - TestTableInsert::Row row; - row.Set_ColumnText(L"dup"); - update.Values(row); - update.Where(Equals(2)); - update.Execute(); - - FOREACH(it, list) - { - it->Set_ColumnText(L"dup"); - } - - // CHECK - TestTableInsert::Select select(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual( - select.GetRowList(), - list), "Returned list doesn't match."); - } - - // restore original table state - { - TestTableInsert::Delete del2(interface.get()); - del2.Execute(); - - TestTableInsert::Select select(interface.get()); - RUNNER_ASSERT(select.GetRowList().size() == 0); - } -} - -/* -Name: ORM_MultipleBindUpdate -Description: repeats ORM_Update severl times -Expected: Successful update -*/ -RUNNER_TEST(ORM_MultipleBindUpdate) -{ - for (int i = 0; i < TEST_REPETITION; i++) { - ORM_Update(); - } -} - -/* -Name: ORM_transactions -Description: checks creation of transation object -Expected: Successful creation of transaction object -*/ -RUNNER_TEST(ORM_transactions) -{ - SmartAttach interface; - DPL::DB::ORM::dpl_orm_test::ScopedTransaction transaction(interface.get()); -} - -/* -Name: ORM_MultiAttach -Description: checks correct behaviou in case of multiple tries to attach to database -Expected: Methods attaching/dettaching should be prepared for multiple calling -*/ -RUNNER_TEST(ORM_MultiAttach) -{ - SmartAttach interface(false); - RUNNER_ASSERT_MSG( - !interface.get()->IsAttached(), "Is attached, but shouldn't be."); - interface.get()->AttachToThread(); - RUNNER_ASSERT_MSG( - interface.get()->IsAttached(), "Isn't attached, but should be."); - interface.get()->AttachToThread(); - RUNNER_ASSERT_MSG( - interface.get()->IsAttached(), "Isn't attached, but should be."); - interface.get()->DetachFromThread(); - RUNNER_ASSERT_MSG( - interface.get()->IsAttached(), "Isn't attached, but should be."); - interface.get()->DetachFromThread(); - RUNNER_ASSERT_MSG( - !interface.get()->IsAttached(), "Is attached, but shouldn't be."); -} - -/* -Name: ORM_Join -Description: tests ORM's join operation -Expected: values should insist correct join operation -*/ -RUNNER_TEST(ORM_Join) -{ - SmartAttach interface; - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::dpl_orm_test; - - typedef DPL::TypeListDecl::Type JoinColumns; - - /* Test for correct join: - * 5 ids from first table matches 5 ids from second table thus join result - * contains 5 rows */ - TestTableJoin1::Select select(interface.get()); - select.Join(Equal()); - std::list > rowlist = - select.GetCustomRowList >(); - - RUNNER_ASSERT_MSG( - rowlist.size() == 5, "Invalid number of rows fetched: " << rowlist.size()); - - std::string text; - std::ostringstream oss; - int cnt = 0; - FOREACH(rowit, rowlist) - { - cnt++; - - text = - DPL::ToUTF8String((*rowit).GetColumnData()); - oss << "text val " << cnt; - RUNNER_ASSERT_MSG(text.compare( - oss.str()) == 0, - "Invalid value from first column: " - << text << " expected: " << oss.str()); - oss.str(std::string()); - - text = - DPL::ToUTF8String((*rowit).GetColumnData()); - oss << "text2 " << cnt; - RUNNER_ASSERT_MSG(text.compare( - oss.str()) == 0, - "Invalid value from second column: " - << text << " expected: " << oss.str()); - oss.str(std::string()); - } - /* Test for empty join: - * None of number values from first table matches ids from second table - * - join result should be empty */ - TestTableJoin1::Select select2(interface.get()); - select2.Join(Equal()); - rowlist = select2.GetCustomRowList >(); - - RUNNER_ASSERT_MSG(rowlist.empty(), "Result should be empty but it is not!"); - - /* Test for "converted" join: - * - join made with int column and text column as keys - * - expected 5 matching rows (one row of 6 should not be matched)*/ - TestTableJoin1::Select select3(interface.get()); - select3.Join(Equal()); - rowlist = select3.GetCustomRowList >(); - RUNNER_ASSERT_MSG( - rowlist.size() == 5, "Expected 5 rows while received: " << rowlist.size()); - cnt = 0; - FOREACH(rowit, rowlist) - { - cnt++; - // look at last two insertions into TestTableJoin2 - // for this skip understanding - if (cnt == 5) { - cnt = 6; - } - text = - DPL::ToUTF8String((*rowit).GetColumnData()); - oss << "text val " << cnt; - RUNNER_ASSERT_MSG(text.compare( - oss.str()) == 0, - "Invalid value from first column: " - << text << " expected: " << oss.str() << - " iteration: " << cnt); - oss.str(std::string()); - - text = - DPL::ToUTF8String((*rowit).GetColumnData()); - oss << "text2 " << cnt; - RUNNER_ASSERT_MSG(text.compare( - oss.str()) == 0, - "Invalid value from second column: " - << text << " expected: " << oss.str() << - " iteration: " << cnt); - oss.str(std::string()); - } - - /* Test for join with non-unique nullable columns given as keys*/ - typedef DPL::TypeListDecl::Type JoinTables2; - TestTableJoin1::Select select4(interface.get()); - select4.Join(Equal()); - std::list > rowlist2 = - select4.GetCustomRowList >(); - RUNNER_ASSERT_MSG( - rowlist2.size() == 4, "Expected 4 rows while received: " << - rowlist.size()); - cnt = 0; - DPL::Optional optext; - FOREACH(rowit, rowlist2) - { - cnt++; - - text = - DPL::ToUTF8String((*rowit).GetColumnData()); - // values expected in subsequent (1,2,3,4) iterations: 1 1 2 2 - oss << "text val " << (1 + (int)(cnt / 3)); - RUNNER_ASSERT_MSG(text.compare( - oss.str()) == 0, - "Invalid value from first column: " - << text << " expected: " << oss.str() << - " iteration: " << cnt); - oss.str(std::string()); - - optext = (*rowit).GetColumnData(); - text = DPL::ToUTF8String(*optext); - oss << "test " << cnt; - RUNNER_ASSERT_MSG(text.compare( - oss.str()) == 0, - "Invalid value from second column: " - << text << " expected: " << oss.str() << - " iteration: " << cnt); - oss.str(std::string()); - } - - /* Test for join made on three tables: - * - 3 text columns selected for join - * - Equal made for TestID of (table1 and table2) and (table1 and table3) */ - typedef DPL::TypeListDecl::Type Join3Tables; - TestTableJoin1::Select select5(interface.get()); - select5.Join(Equal()); - select5.Join(Equal()); - std::list > rowlist3tab = - select5.GetCustomRowList >(); - RUNNER_ASSERT_MSG( - rowlist3tab.size() == 3, "Expected 3 rows while received: " << - rowlist3tab.size()); - cnt = 0; - FOREACH(rowit, rowlist3tab) - { - cnt++; - - text = - DPL::ToUTF8String((*rowit).GetColumnData()); - oss << "text val " << cnt; - RUNNER_ASSERT_MSG(text.compare( - oss.str()) == 0, - "Invalid value from first column: " - << text << " expected: " << oss.str() << - " iteration: " << cnt); - oss.str(std::string()); - - text = - DPL::ToUTF8String((*rowit).GetColumnData()); - oss << "text2 " << cnt; - RUNNER_ASSERT_MSG(text.compare( - oss.str()) == 0, - "Invalid value from first column: " - << text << " expected: " << oss.str() << - " iteration: " << cnt); - oss.str(std::string()); - - optext = (*rowit).GetColumnData(); - text = DPL::ToUTF8String(*optext); - oss << "test " << cnt; - RUNNER_ASSERT_MSG(text.compare( - oss.str()) == 0, - "Invalid value from second column: " - << text << " expected: " << oss.str() << - " iteration: " << cnt); - oss.str(std::string()); - } -} - -RUNNER_TEST(ORM_SelectOrderByMultipleColumns) -{ - SmartAttach interface; - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::dpl_orm_test; - { - TestTableJoin3::Select select(interface.get()); - - // testing: " ORDER BY Value3 ASC, TestID DESC, TestID ASC" - select.OrderBy(DPL::TypeListDecl, - OrderingDescending, - OrderingAscending >()); - - std::list result = select.GetRowList(); - std::list::const_iterator iter = result.begin(); - { //1 row - RUNNER_ASSERT_MSG(*iter->Get_TestText33() == - DPL::FromASCIIString( - "test 6"), "Wrong row 1 order"); - RUNNER_ASSERT_MSG(iter->Get_TestID() == 10, "Wrong row 1 order"); - iter++; - } - { //2 row - RUNNER_ASSERT_MSG(*iter->Get_TestText33() == - DPL::FromASCIIString( - "test 5"), "Wrong row 2 order"); - RUNNER_ASSERT_MSG(iter->Get_TestID() == 7, "Wrong row 2 order"); - iter++; - } - { //3 row - RUNNER_ASSERT_MSG(iter->Get_Value3() == 111, "Wrong row 3 order"); - RUNNER_ASSERT_MSG(*iter->Get_TestText33() == - DPL::FromASCIIString( - "test 2"), "Wrong row 3 order"); - RUNNER_ASSERT_MSG(iter->Get_TestID() == 2, "Wrong row 3 order"); - iter++; - } - { //4 row - RUNNER_ASSERT_MSG(iter->Get_Value3() == 111, "Wrong row 4 order"); - RUNNER_ASSERT_MSG(*iter->Get_TestText33() == - DPL::FromASCIIString( - "test 1"), "Wrong row 4 order"); - RUNNER_ASSERT_MSG(iter->Get_TestID() == 1, "Wrong row 4 order"); - iter++; - } - { //5 row - RUNNER_ASSERT_MSG(iter->Get_Value3() == 222, "Wrong row 5 order"); - RUNNER_ASSERT_MSG(*iter->Get_TestText33() == - DPL::FromASCIIString( - "test 4"), "Wrong row 5 order"); - RUNNER_ASSERT_MSG(iter->Get_TestID() == 6, "Wrong row 5 order"); - iter++; - } - { //6 row - RUNNER_ASSERT_MSG(iter->Get_Value3() == 222, "Wrong row 6 order"); - RUNNER_ASSERT_MSG(*iter->Get_TestText33() == - DPL::FromASCIIString( - "test 3"), "Wrong row 6 order"); - RUNNER_ASSERT_MSG(iter->Get_TestID() == 3, "Wrong row 6 order"); - iter++; - } - } -} diff --git a/tests/dpl/db/test_sql_connection.cpp b/tests/dpl/db/test_sql_connection.cpp deleted file mode 100644 index 0f37b2d..0000000 --- a/tests/dpl/db/test_sql_connection.cpp +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_sql_connection.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of sql connection tests - */ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -extern const char* PATH_DB; - -RUNNER_TEST_GROUP_INIT(DPL) - -class AbstractSynchronizationObjectGenerator -{ - public: - virtual ~AbstractSynchronizationObjectGenerator() {} - - virtual DPL::DB::SqlConnection::SynchronizationObject *Create() = 0; -}; - -class NaiveSynchronizationObjectGenerator : - public AbstractSynchronizationObjectGenerator -{ - public: - virtual DPL::DB::SqlConnection::SynchronizationObject *Create() - { - return new DPL::DB::NaiveSynchronizationObject(); - } -}; - -void MassiveReadWriteTest(AbstractSynchronizationObjectGenerator *generator); - -class StressGenerator : - public DPL::Thread -{ - private: - size_t m_prefix; - std::string m_dbFileName; - AbstractSynchronizationObjectGenerator *m_generator; - - protected: - virtual int ThreadEntry() - { - DPL::DB::SqlConnection connection( - m_dbFileName, - DPL::DB::SqlConnection::Flag::None, - DPL::DB::SqlConnection::Flag::RW, - m_generator->Create()); - - DPL::DB::SqlConnection::DataCommandAutoPtr countCommand = - connection.PrepareDataCommand( - "SELECT COUNT(*) FROM test WHERE value=?"); - - for (size_t i = 0; i < 10; ++i) { - std::ostringstream valueStream; - - valueStream << "value_"; - valueStream << static_cast(m_prefix); - valueStream << "_"; - valueStream << static_cast(i); - - std::string value = valueStream.str(); - - connection.ExecCommand( - "INSERT INTO test VALUES ('%s');", - value.c_str()); - - countCommand->BindString(1, value.c_str()); - - RUNNER_ASSERT(countCommand->Step()); - - RUNNER_ASSERT(countCommand->GetColumnString(0) == "1"); - - countCommand->Reset(); - } - - countCommand.reset(); - - return 0; - } - - public: - StressGenerator(size_t prefix, - const std::string &dbFileName, - AbstractSynchronizationObjectGenerator *generator) : - m_prefix(prefix), - m_dbFileName(dbFileName), - m_generator(generator) - {} -}; - -typedef std::shared_ptr ThreadPtr; - -void MassiveReadWriteTest(AbstractSynchronizationObjectGenerator *generator) -{ - DPL::DB::SqlConnection connection(PATH_DB, - DPL::DB::SqlConnection::Flag::UseLucene, - DPL::DB::SqlConnection::Flag::RW); - - connection.ExecCommand("CREATE TABLE test(value TEXT);"); - - const size_t STRESS_GENERATOR_COUNT = 5; - ThreadPtr stressGenerators[STRESS_GENERATOR_COUNT]; - - for (size_t i = 0; i < STRESS_GENERATOR_COUNT; ++i) { - stressGenerators[i].reset( - new StressGenerator(i, PATH_DB, generator)); - - stressGenerators[i]->Run(); - } - - for (size_t i = 0; i < STRESS_GENERATOR_COUNT; ++i) { - stressGenerators[i]->Quit(); - } - - connection.ExecCommand("DROP TABLE test;"); -} - -/* -Name: SqlConnection_MassiveReadWrite_NaiveSynchronization -Description: tests massive multiple quiries from many threads -Expected: no ORM/db failures -*/ -RUNNER_TEST(SqlConnection_MassiveReadWrite_NaiveSynchronization) -{ - srand(time(NULL)); - - NaiveSynchronizationObjectGenerator m_generator; - MassiveReadWriteTest(&m_generator); -} - -/* -Name: SqlConnection_Not_Connected_Lucene -Description: tests connection to not existing database with Lucene option -Expected: exception throw -*/ -RUNNER_TEST(SqlConnection_Not_Connected_Lucene) -{ - Try { - DPL::DB::SqlConnection connection( - "/notexisitingdirectiory/foo", - DPL::DB::SqlConnection::Flag:: - UseLucene, - DPL::DB::SqlConnection::Flag::RW); - RUNNER_ASSERT_MSG(false, - "connection should throw on accessing " - "nonexistent file as a database"); - } - Catch(DPL::DB::SqlConnection::Exception::ConnectionBroken) - { - RUNNER_ASSERT(true); - } catch (DPL::Exception) { - RUNNER_ASSERT_MSG(false, "Wrong exception found"); - } -} - -/* -Name: SqlConnection_Not_Connected -Description: tests connection to not existing database without Lucene option -Expected: exception throw -*/ -RUNNER_TEST(SqlConnection_Not_Connected) -{ - Try { - DPL::DB::SqlConnection connection("/notexisitingdirectiory/foo", - DPL::DB::SqlConnection::Flag::None, - DPL::DB::SqlConnection::Flag::RW); - RUNNER_ASSERT_MSG(false, - "connection should throw on accessing " - "nonexistent file as a database"); - } - Catch(DPL::DB::SqlConnection::Exception::ConnectionBroken) - { - RUNNER_ASSERT(true); - } catch (DPL::Exception) { - RUNNER_ASSERT_MSG(false, "Wrong exception found"); - } -} - -/* -Name: SqlConnection_Null_Query -Description: tests resistance to passing NULL as query in ExecCommand -Expected: exception throw -*/ -RUNNER_TEST(SqlConnection_Null_Query) -{ - DPL::DB::SqlConnection connection(PATH_DB, - DPL::DB::SqlConnection::Flag::UseLucene, - DPL::DB::SqlConnection::Flag::RW); - Try - { - connection.ExecCommand(NULL); - RUNNER_ASSERT_MSG(false, - "Null pointer should not be accepted"); - } - Catch(DPL::DB::SqlConnection::Exception::SyntaxError) - { - RUNNER_ASSERT(true); - } catch (DPL::Exception) { - RUNNER_ASSERT_MSG(false, "Wrong exception found"); - } -} - -/* -Name: SqlConnection_Bad_Query -Description: tests resistance to passing trash as query in ExecCommand -Expected: exception throw -*/ -RUNNER_TEST(SqlConnection_Bad_Query) -{ - DPL::DB::SqlConnection connection(PATH_DB, - DPL::DB::SqlConnection::Flag::UseLucene, - DPL::DB::SqlConnection::Flag::RW); - Try - { - connection.ExecCommand("Some stupid string"); - RUNNER_ASSERT_MSG(false, "This string should not be accepted"); - } - Catch(DPL::DB::SqlConnection::Exception::SyntaxError) - { - RUNNER_ASSERT(true); - } catch (DPL::Exception) { - RUNNER_ASSERT_MSG(false, "Wrong exception found"); - } -} diff --git a/tests/dpl/dbus/CMakeLists.txt b/tests/dpl/dbus/CMakeLists.txt deleted file mode 100644 index 066ad79..0000000 --- a/tests/dpl/dbus/CMakeLists.txt +++ /dev/null @@ -1,63 +0,0 @@ -# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved -# -# 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. -# -# @file CMakeLists.txt -# @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) -# @version 1.0 -# @brief -# - -INCLUDE(FindPkgConfig) - -PKG_CHECK_MODULES(DEPENDENCIES gthread-2.0 REQUIRED) - -SET(TARGET_DBUS_TESTS "dpl-tests-dbus") -SET(TARGET_DBUS_TEST_SERVICE "dpl-dbus-test-service") - -SET(DBUS_TESTS_SRCS - ${TESTS_DPL_DIR}/dbus/main.cpp - ${TESTS_DPL_DIR}/dbus/test_cases.cpp - ${TESTS_DPL_DIR}/dbus/dbus_test.cpp - ${TESTS_COMMON_DIR}/src/loop_control.cpp -) - -SET(DBUS_TEST_SERVICE_SRCS - ${TESTS_DPL_DIR}/dbus/test_service.cpp - ${TESTS_COMMON_DIR}/src/loop_control.cpp -) - -WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_DBUS_TESTS} ${TARGET_DPL_DBUS_EFL}) -WRT_TEST_INCLUDE_DIRECTORIES(${TARGET_DBUS_TESTS} - ${TESTS_COMMON_DIR}/include - ${DEPENDENCIES_INCLUDE_DIRS} -) -WRT_TEST_LINK_DIRECTORIES(${TARGET_DBUS_TESTS} ${DEPENDENCIES_LIBRARY_DIRS}) -WRT_TEST_TARGET_LINK_LIBRARIES(${TARGET_DBUS_TESTS} ${DEPENDENCIES_LIBRARIES}) -WRT_TEST_BUILD(${TARGET_DBUS_TESTS} ${DBUS_TESTS_SRCS}) -WRT_TEST_INSTALL(${TARGET_DBUS_TESTS}) - -WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_DBUS_TEST_SERVICE} ${TARGET_DPL_DBUS_EFL}) -WRT_TEST_INCLUDE_DIRECTORIES(${TARGET_DBUS_TEST_SERVICE} - ${TESTS_COMMON_DIR}/include - ${DEPENDENCIES_INCLUDE_DIRS} -) -WRT_TEST_LINK_DIRECTORIES(${TARGET_DBUS_TEST_SERVICE} ${DEPENDENCIES_LIBRARY_DIRS}) -WRT_TEST_TARGET_LINK_LIBRARIES(${TARGET_DBUS_TEST_SERVICE} ${DEPENDENCIES_LIBRARIES}) -WRT_TEST_BUILD(${TARGET_DBUS_TEST_SERVICE} ${DBUS_TEST_SERVICE_SRCS}) -WRT_TEST_INSTALL(${TARGET_DBUS_TEST_SERVICE}) - -INSTALL(FILES - ${TESTS_DPL_DIR}/dbus/data/org.tizen.DBusTestService.service - DESTINATION /usr/share/dbus-1/services -) diff --git a/tests/dpl/dbus/data/org.tizen.DBusTestService.service b/tests/dpl/dbus/data/org.tizen.DBusTestService.service deleted file mode 100644 index f024543..0000000 --- a/tests/dpl/dbus/data/org.tizen.DBusTestService.service +++ /dev/null @@ -1,3 +0,0 @@ -[D-BUS Service] -Name=org.tizen.DBusTestService -Exec=/usr/bin/dpl-dbus-test-service diff --git a/tests/dpl/dbus/dbus_test.cpp b/tests/dpl/dbus/dbus_test.cpp deleted file mode 100644 index 2e8d51b..0000000 --- a/tests/dpl/dbus/dbus_test.cpp +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/** - * @file dbus_test.cpp - * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) - * @brief Implementation file for DBusTest and DBusTestManager. - */ - -#include -#include "loop_control.h" -#include "dbus_test.h" - -DBusTest::DBusTest(const std::string& name) : - m_name(name), - m_status(Status::NONE) -{} - -void DBusTest::run(unsigned int timeout) -{ - DPL::Event::ControllerEventHandler::Touch(); - DPL::Event::ControllerEventHandler::Touch(); - - DPL::Event::ControllerEventHandler::PostTimedEvent( - TimeoutEvent(), timeout); - - LoopControl::wrt_start_loop(); - - switch (m_status) { - case Status::FAILED: - throw DPL::Test::TestRunner::TestFailed(m_name.c_str(), - __FILE__, - __LINE__, - m_message); - - case Status::SUCCESS: - case Status::NONE: - default: - break; - } -} - -void DBusTest::quit() -{ - DPL::Event::ControllerEventHandler::PostEvent(QuitEvent()); -} - -void DBusTest::setStatus(Status status) -{ - m_status = status; -} - -void DBusTest::setMessage(const std::string& message) -{ - m_message = message; -} - -void DBusTest::success() -{ - m_status = Status::SUCCESS; -} - -void DBusTest::fail(const std::string& message) -{ - m_status = Status::FAILED; - m_message = message; -} - -void DBusTest::OnEventReceived(const TimeoutEvent& /*event*/) -{ - fail("Test timed out."); - - // Saving one event dispatch since Quit and Timeout work on the same thread. - LoopControl::wrt_end_loop(); -} - -void DBusTest::OnEventReceived(const QuitEvent& /*event*/) -{ - LoopControl::wrt_end_loop(); -} - -DBusTestManager& DBusTestManager::getInstance() -{ - static DBusTestManager instance; - return instance; -} - -DBusTestManager::DBusTestManager() : m_test(NULL) { } - -DBusTest& DBusTestManager::getCurrentTest() const -{ - Assert(NULL != m_test && "Test not set."); - - return *m_test; -} - -void DBusTestManager::setCurrentTest(DBusTest& test) -{ - m_test = &test; -} - -void DBusTestManager::clear() -{ - m_test = NULL; -} diff --git a/tests/dpl/dbus/dbus_test.h b/tests/dpl/dbus/dbus_test.h deleted file mode 100644 index 3c7ffe9..0000000 --- a/tests/dpl/dbus/dbus_test.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/** - * @file dbus_test.h - * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) - * @brief Header file for DBusTest and DBusTestManager. - */ - -#ifndef WRT_TESTS_DBUS_TESTS_DBUS_TEST_H -#define WRT_TESTS_DBUS_TESTS_DBUS_TEST_H - -#include -#include -#include - -DECLARE_GENERIC_EVENT_0(QuitEvent) -DECLARE_GENERIC_EVENT_0(TimeoutEvent) - -class DBusTest : - private DPL::Event::Controller::Type> -{ - public: - enum class Status - { - NONE, - SUCCESS, - FAILED - }; - - explicit DBusTest(const std::string& name); - - void run(unsigned int timeout); - void quit(); - - void setStatus(Status status); - void setMessage(const std::string& message); - - void success(); - void fail(const std::string& message = std::string()); - - private: - void OnEventReceived(const TimeoutEvent& event); - void OnEventReceived(const QuitEvent& event); - - std::string m_name; - Status m_status; - std::string m_message; -}; - -class DBusTestManager : private DPL::Noncopyable -{ - public: - static DBusTestManager& getInstance(); - - DBusTest& getCurrentTest() const; - void setCurrentTest(DBusTest& test); - - void clear(); - - private: - DBusTestManager(); - - DBusTest* m_test; -}; - -#define DBUS_TEST(TestProc) \ - void DBus##TestProc(); \ - RUNNER_TEST(TestProc) \ - { \ - DBusTest test(#TestProc); \ - DBusTestManager::getInstance().setCurrentTest(test); \ - DBus##TestProc(); \ - DBusTestManager::getInstance().clear(); \ - } \ - void DBus##TestProc() - -#endif diff --git a/tests/dpl/dbus/main.cpp b/tests/dpl/dbus/main.cpp deleted file mode 100644 index d06a4c0..0000000 --- a/tests/dpl/dbus/main.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/** - * @file main.cpp - * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of main. - */ - -#include "loop_control.h" -#include -#include - -int main(int argc, char *argv[]) -{ - LoopControl::init_loop(argc, argv); - - LogInfo("Running tests"); - int status = DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, - argv); - - return status; -} diff --git a/tests/dpl/dbus/test_cases.cpp b/tests/dpl/dbus/test_cases.cpp deleted file mode 100644 index 0d855ef..0000000 --- a/tests/dpl/dbus/test_cases.cpp +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/** - * @file TestCases.cpp - * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) - * @version 1.0 - * @brief Implementation file for test cases for DBus internal tests. - */ - -#include -#include -#include -#include -#include -#include -#include "dbus_test.h" - -namespace { -const std::string dbusServiceName = "org.freedesktop.DBus"; -const std::string dbusObjectPath = "/"; -const std::string dbusInterfaceName = "org.freedesktop.DBus"; -const std::string dbusMethodGetId = "GetId"; - -const std::string serviceName = "org.tizen.DBusTestService"; -const std::string objectPath = "/org/tizen/DBusTestService"; -const std::string interfaceName = "org.tizen.DBusTestService"; -const std::string methodNameEcho = "echo"; -const std::string methodNameQuit = "quit"; -const std::string nodeInfo = - "" - "" - " " - " " - " " - " " - " " - " " - " " - " " - ""; - -const std::string challenge = "Hello world!"; - -const int DEFAULT_TIMEOUT = 2; // in seconds -} - -RUNNER_TEST_GROUP_INIT(DPL) - -/* -Name: AcquireSessionBus -Description: tests acquiring session bus -Expected: no exceptions -*/ -RUNNER_TEST(AcquireSessionBus) -{ - try { - DPL::DBus::Connection::sessionBus(); - } catch (const DPL::DBus::Exception& ex) { - RUNNER_ASSERT_MSG(false, ex.DumpToString()); - } -} - -/* -Name: AcquireSystemBus -Description: tests acquiring system bus -Expected: no exceptions -*/ -RUNNER_TEST(AcquireSystemBus) -{ - try { - DPL::DBus::Connection::systemBus(); - } catch (const DPL::DBus::Exception& ex) { - RUNNER_ASSERT_MSG(false, ex.DumpToString()); - } -} - -/* -Name: ParseNodeInfo -Description: creates dbus interface from xml string -Expected: interface should be created correctly -*/ -RUNNER_TEST(ParseNodeInfo) -{ - try { - auto ifaces = DPL::DBus::Interface::fromXMLString(nodeInfo); - RUNNER_ASSERT(!ifaces.empty()); - - auto iface = ifaces.at(0); - RUNNER_ASSERT(NULL != iface->getVTable()); - RUNNER_ASSERT(NULL != iface->getInfo()); - } catch (const DPL::DBus::Exception& ex) { - RUNNER_ASSERT_MSG(false, ex.DumpToString()); - } -} - -/* -Name: InvokeRemoteMethod -Description: performs procedure call via dbus -Expected: call should return not empty id -*/ -RUNNER_TEST(InvokeRemoteMethod) -{ - try { - auto connection = DPL::DBus::Connection::systemBus(); - auto freedesktop = connection->createObjectProxy(dbusServiceName, - dbusObjectPath); - auto getId = freedesktop->createMethodProxy - (dbusInterfaceName, dbusMethodGetId); - RUNNER_ASSERT(!getId().empty()); - } catch (const DPL::DBus::Exception& ex) { - RUNNER_ASSERT_MSG(false, ex.DumpToString()); - } -} - -class RegisterServiceListener : - public DPL::Event::EventListener -{ - public: - void OnEventReceived( - const DPL::DBus::ConnectionEvents::ServiceNameAcquiredEvent& event) - { - DBusTest& test = DBusTestManager::getInstance().getCurrentTest(); - - auto name = event.GetArg0(); - if (serviceName == name) { - test.success(); - } else { - test.fail("Acquired service name: " + name); - } - test.quit(); - } -}; - -/* -Name: RegisterService -Description: tests event listener for AcquiredEvent in context of dbus -Expected: event should be received -*/ -DBUS_TEST(RegisterService) -{ - try { - RegisterServiceListener listener; - - auto connection = DPL::DBus::Connection::sessionBus(); - connection->DPL::Event::EventSupport:: - AddListener(&listener); - connection->registerService(serviceName); - - DBusTestManager::getInstance().getCurrentTest().run(DEFAULT_TIMEOUT); - } catch (const DPL::DBus::Exception& ex) { - RUNNER_ASSERT_MSG(false, ex.DumpToString()); - } -} - -/** - * This test checks: - * - object registration (done on the wrt-dbus-test-service side) - * - service registration (done on the wrt-dbus-test-service side) - * - dispatching method calls (done on the wrt-dbus-test-service side) - * - launching dbus service on demand - * - invoking remote method(s) - */ -DBUS_TEST(InvokeTestService) -{ - try { - auto connection = DPL::DBus::Connection::sessionBus(); - auto testService = connection->createObjectProxy(serviceName, - objectPath); - auto echo = testService->createMethodProxy - (interfaceName, methodNameEcho); - auto response = echo(challenge); - - testService->createMethodProxy(interfaceName, methodNameQuit) (); - - RUNNER_ASSERT_MSG(response == challenge, - "[challenge = " << challenge << - ", response = " << response << "]"); - } catch (const DPL::DBus::Exception& ex) { - RUNNER_ASSERT_MSG(false, ex.DumpToString()); - } -} diff --git a/tests/dpl/dbus/test_service.cpp b/tests/dpl/dbus/test_service.cpp deleted file mode 100644 index 510e4c5..0000000 --- a/tests/dpl/dbus/test_service.cpp +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/** - * @file test_service.cpp - * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) - * @brief Implementation file for wrt-dbus-test-service. - */ - -#include -#include -#include -#include -#include -#include - -namespace { -const std::string serviceName = "org.tizen.DBusTestService"; -const std::string objectPath = "/org/tizen/DBusTestService"; -const std::string interfaceName = "org.tizen.DBusTestService"; -const std::string methodNameEcho = "echo"; -const std::string methodNameQuit = "quit"; -const std::string nodeInfo = - "" - "" - " " - " " - " " - " " - " " - " " - " " - " " - ""; -} - -class TestServiceDispatcher : public DPL::DBus::Dispatcher -{ - private: - void onMethodCall(GDBusConnection* /*connection*/, - const gchar* /*sender*/, - const gchar* /*objectPath*/, - const gchar* /*interfaceName*/, - const gchar* methodName, - GVariant* parameters, - GDBusMethodInvocation* invocation) - { - if (methodNameEcho == methodName) { - LogDebug("Echo"); - g_dbus_method_invocation_return_value(invocation, - parameters); - } else if (methodNameQuit == methodName) { - LogDebug("Quit"); - g_dbus_method_invocation_return_value(invocation, NULL); - LoopControl::wrt_end_loop(); - } - } -}; - -int main(int argc, char* argv[]) -{ - LoopControl::init_loop(argc, argv); - TestServiceDispatcher dispatcher; - - auto iface = DPL::DBus::Interface::fromXMLString(nodeInfo).at(0); - iface->setDispatcher(&dispatcher); - auto object = DPL::DBus::Object::create(objectPath, iface); - auto connection = DPL::DBus::Connection::sessionBus(); - connection->registerObject(object); - connection->registerService(serviceName); - LoopControl::wrt_start_loop(); - - return 0; -} diff --git a/tests/dpl/event/CMakeLists.txt b/tests/dpl/event/CMakeLists.txt deleted file mode 100644 index de3db4a..0000000 --- a/tests/dpl/event/CMakeLists.txt +++ /dev/null @@ -1,42 +0,0 @@ -# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved -# -# 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. -# -# @file CMakeLists.txt -# @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) -# @version 1.0 -# @brief -# - -# -# Test files -# -# Define all DPL tests sources. -# Runner is responsible for runnint it all and -# generating proper output files -# - -SET(TARGET_NAME "dpl-tests-event") - -# Set DPL tests sources -SET(DPL_TESTS_EVENT_SOURCES - ${TESTS_DPL_DIR}/event/main.cpp - ${TESTS_DPL_DIR}/event/test_controller.cpp - ${TESTS_DPL_DIR}/event/test_event_support.cpp - ${TESTS_DPL_DIR}/event/test_ic_delegate.cpp - ${TESTS_DPL_DIR}/event/test_property.cpp -) - -WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_NAME} ${TARGET_DPL_EVENT_EFL}) -WRT_TEST_BUILD(${TARGET_NAME} ${DPL_TESTS_EVENT_SOURCES}) -WRT_TEST_INSTALL(${TARGET_NAME}) \ No newline at end of file diff --git a/tests/dpl/event/main.cpp b/tests/dpl/event/main.cpp deleted file mode 100644 index 4ed6191..0000000 --- a/tests/dpl/event/main.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/** - * @file main.cpp - * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of main. - */ - -#include - -int main(int argc, char *argv[]) -{ - return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); -} diff --git a/tests/dpl/event/test_controller.cpp b/tests/dpl/event/test_controller.cpp deleted file mode 100644 index 8f0a630..0000000 --- a/tests/dpl/event/test_controller.cpp +++ /dev/null @@ -1,422 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_controller.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of test controller - */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL) - -class IntController : - public DPL::Event::Controller::Type> -{ - private: - int m_value; - - protected: - virtual void OnEventReceived(const int &event) - { - m_value = event; - } - - public: - IntController() : - m_value(-1) - {} - - int Value() const - { - return m_value; - } -}; - -DECLARE_GENERIC_EVENT_1(DoneSignalEvent, DPL::WaitableEvent *) - -class ThreadController : - public DPL::Event::Controller::Type> -{ - private: - DPL::Thread *m_value; - - protected: - virtual void OnEventReceived(const DoneSignalEvent &event) - { - m_value = DPL::Thread::GetCurrentThread(); - event.GetArg0()->Signal(); - } - - public: - ThreadController() : - m_value(NULL) - {} - - DPL::Thread *Value() const - { - return m_value; - } -}; - -struct StrangeStruct -{ - int a; - float b; - double c; -}; - -class StrangeController : - public DPL::Event::Controller::Type> -{ - protected: - virtual void OnEventReceived(const char &event) - { - (void)event; - } - virtual void OnEventReceived(const short &event) - { - (void)event; - } - virtual void OnEventReceived(const int &event) - { - (void)event; - } - virtual void OnEventReceived(const long &event) - { - (void)event; - } - virtual void OnEventReceived(const unsigned char &event) - { - (void)event; - } - virtual void OnEventReceived(const unsigned short &event) - { - (void)event; - } - virtual void OnEventReceived(const unsigned int &event) - { - (void)event; - } - virtual void OnEventReceived(const unsigned long &event) - { - (void)event; - } - virtual void OnEventReceived(const float &event) - { - (void)event; - } - virtual void OnEventReceived(const double &event) - { - (void)event; - } - virtual void OnEventReceived(const StrangeStruct &event) - { - (void)event; - } -}; - -/* -Name: Controller_InitSimple -Description: tests initialization of simple int controller -Expected: no exceptions -*/ -RUNNER_TEST(Controller_InitSimple) -{ - IntController controller; - controller.Touch(); - RUNNER_ASSERT(controller.Value() == -1); -} - -/* -Name: Controller_InitStrange -Description: tests initialization of struct controller -Expected: no exceptions -*/ -RUNNER_TEST(Controller_InitStrange) -{ - StrangeController controller; - controller.Touch(); -} - -/* -Name: Controller_PostEventToThread -Description: tests post events to other thread -Expected: thread id gathered in event handling method should match id of created thread -*/ -RUNNER_TEST(Controller_PostEventToThread) -{ - ThreadController controller; - controller.Touch(); - - DPL::Thread thread; - thread.Run(); - - controller.SwitchToThread(&thread); - - DPL::WaitableEvent waitHandle; - - controller.PostEvent(DoneSignalEvent(&waitHandle)); - - DPL::WaitForSingleHandle(waitHandle.GetHandle()); - - controller.SwitchToThread(NULL); - - RUNNER_ASSERT(controller.Value() == &thread); -} - -/* -Name: Controller_PostTimedEventToThread -Description: tests post events to other thread with time delay -Expected: thread id gathered in event handling method should match id of created thread -*/ -RUNNER_TEST(Controller_PostTimedEventToThread) -{ - ThreadController controller; - controller.Touch(); - - DPL::Thread thread; - thread.Run(); - - controller.SwitchToThread(&thread); - - DPL::WaitableEvent waitHandle; - - controller.PostTimedEvent(DoneSignalEvent(&waitHandle), 0.5); - - DPL::WaitForSingleHandle(waitHandle.GetHandle()); - - controller.SwitchToThread(NULL); - - RUNNER_ASSERT(controller.Value() == &thread); -} - -DECLARE_GENERIC_EVENT_2(TouchInThread, DPL::WaitableEvent *, DPL::Thread * *) -DECLARE_GENERIC_EVENT_2(TouchedControllerSignal, - DPL::WaitableEvent *, - DPL::Thread * *) - -class TouchInThreadController : - public DPL::Event::Controller::Type>, - private DPL::Event::Controller:: - Type> -{ - public: - typedef DPL::Event::Controller::Type> - PublicController; - typedef DPL::Event::Controller:: - Type> PrivateController; - - virtual void OnEventReceived(const TouchInThread &event) - { - // Touch controller in thread - PrivateController::Touch(); - - // Post signal - PrivateController::PostEvent(TouchedControllerSignal(event.GetArg0(), - event.GetArg1())); - } - - virtual void OnEventReceived(const TouchedControllerSignal &event) - { - // Return touched thread - *event.GetArg1() = DPL::Thread::GetCurrentThread(); - - // Signal waitable event - event.GetArg0()->Signal(); - } -}; - -/* -Name: Controller_TouchInThread -Description: tests ability to touch (initizilize / set destination thread) in creatd thread - other than thread were controlelr object was created -Expected: thread id gathered in event handling method should match id of created thread -*/ -RUNNER_TEST(Controller_TouchInThread) -{ - TouchInThreadController controller; - controller.PublicController::Touch(); - - DPL::Thread thread; - thread.Run(); - - controller.PublicController::SwitchToThread(&thread); - - DPL::WaitableEvent waitHandle; - DPL::Thread *touchedThread = NULL; - - controller.PublicController::PostEvent(TouchInThread(&waitHandle, - &touchedThread)); - - DPL::WaitForSingleHandle(waitHandle.GetHandle()); - - controller.PublicController::SwitchToThread(NULL); - - RUNNER_ASSERT(touchedThread == &thread); -} - -/* -Name: Controller_SynchronizedEvent -Description: tests ability to post synchronized events to ther thread -Expected: correct value should be saved when event was handled -*/ -RUNNER_TEST(Controller_SynchronizedEvent) -{ - IntController controller; - controller.Touch(); - - DPL::Thread thread; - thread.Run(); - - controller.SwitchToThread(&thread); - controller.PostSyncEvent(12345); - controller.SwitchToThread(NULL); - - RUNNER_ASSERT(controller.Value() == 12345); -} - -const int ControllersNumber = 5; -const int MaxEventsPerController = 1; -const int MaxEvents = ControllersNumber * MaxEventsPerController; -const int ControllersPerThread = 1; - -class TestController; //Forward Declaration - -typedef std::shared_ptr ControllerPtr; -typedef std::shared_ptr ThreadPtr; -typedef std::vector ControllerList; -typedef std::list ThreadList; - -DECLARE_GENERIC_EVENT_0(QuitEvent) -class QuitController : - public DPL::Event::Controller::Type>, - public DPL::ApplicationExt -{ - public: - explicit QuitController() : DPL::ApplicationExt(1, NULL, "test-app") - { - Touch(); - } - - protected: - virtual void OnEventReceived(const QuitEvent &) - { - Quit(); - } -}; - -struct TestContext -{ - ControllerList controllers; - ThreadList threads; - QuitController quitter; - DPL::Atomic g_ReceivedCounter; - DPL::Atomic g_SentCounter; -}; -typedef std::unique_ptr TestContextPtr; -TestContextPtr testContextPtr; - -DECLARE_GENERIC_EVENT_0(StartSendEvent) -DECLARE_GENERIC_EVENT_0(RandomEvent) -class TestController : - public DPL::Event::Controller::Type> -{ - public: - explicit TestController() - { - Touch(); - } - - protected: - virtual void OnEventReceived(const RandomEvent &) - { - ++testContextPtr->g_ReceivedCounter; - if (testContextPtr->g_ReceivedCounter == MaxEvents) { - testContextPtr->quitter.DPL::Event::ControllerEventHandler< - QuitEvent>::PostEvent(QuitEvent()); - return; - } - } - virtual void OnEventReceived(const StartSendEvent &) - { - for (int i = 0; i < MaxEventsPerController; ++i) { - if (testContextPtr->g_SentCounter > MaxEvents) { - return; - } - ++testContextPtr->g_SentCounter; - int id = rand() % static_cast(testContextPtr->controllers.size()); - testContextPtr->controllers.at(id)->DPL::Event:: - ControllerEventHandler::PostEvent(RandomEvent()); - } - } -}; - -/* -Name: Controllers_MultipleEvents -Description: tests controller coooperation. - This runs many controllers in many threads. Each controller sends - to other randomly chosen controller events. -Expected: Test is supposed to be ended when all limits of sent event will be reach - -> all scheduled event will be sent and received. -*/ -RUNNER_TEST(Controllers_MultipleEvents) -{ - srand(time(NULL) ); - - testContextPtr.reset(new TestContext()); - testContextPtr->controllers.reserve(ControllersNumber); - - for (int i = 0; i < ControllersNumber; ++i) { - if (testContextPtr->controllers.size() % ControllersPerThread == 0) { - ThreadPtr thread = ThreadPtr(new DPL::Thread()); - testContextPtr->threads.push_back(thread); - thread->Run(); - } - - ControllerPtr controller = ControllerPtr(new TestController()); - testContextPtr->controllers.push_back(controller); - if (testContextPtr->controllers.size() % 2 == 0) { - //This controller is being switched to thread (otherwise it is - // touched to main thread) - ThreadPtr thread = testContextPtr->threads.back(); - controller->SwitchToThread(thread.get()); - } - controller->DPL::Event::ControllerEventHandler:: - PostEvent(StartSendEvent()); - } - testContextPtr->quitter.Exec(); - RUNNER_ASSERT( - testContextPtr->g_SentCounter == testContextPtr->g_ReceivedCounter); - testContextPtr.reset(); -} diff --git a/tests/dpl/event/test_event_support.cpp b/tests/dpl/event/test_event_support.cpp deleted file mode 100644 index e900e9c..0000000 --- a/tests/dpl/event/test_event_support.cpp +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_event_support.cpp - * @author Piotr Marcinkiewicz (p.marcinkiew@samsung.com) - * @author Pawel Sikorski (p.sikorski@samsung.com) - * @version 1.0 - * @brief This file contains test for event support - */ - -#include -#include -#include -#include -#include -#include -#include -#include - -DECLARE_GENERIC_EVENT_0(TestEvent) - -class TestListener : public DPL::Event::EventListener -{ - public: - explicit TestListener() : m_dummyVar(0) { } - void OnEventReceived(const TestEvent &) - { - m_dummyVar = 1; - } - int GetDummyVar() const - { - return m_dummyVar; - } - void ZeroDummyVar() - { - m_dummyVar = 0; - } - - private: - int m_dummyVar; -}; - -class TestEventSupport : - public DPL::Event::EventSupport -{ - public: - void TestEmitEvent() - { - EmitEvent(TestEvent()); - } -}; - -DECLARE_GENERIC_EVENT_0(QuitEvent) - -class QuitController : - public DPL::Event::Controller::Type>, - public DPL::ApplicationExt -{ - public: - QuitController() : DPL::ApplicationExt(1, NULL, "test-app") - { - Touch(); - } - - protected: - virtual void OnEventReceived(const QuitEvent &) - { - Quit(); - } -}; - -/* -Name: EventSupport_DestroyBeforeProcessing -Description: tests if remoign listener is full successfull -Expected: dummy var should be affected by explicit call of ZeroDummyVar(), - but no by emitting event after removing listener -*/ -RUNNER_TEST(EventSupport_DestroyBeforeProcessing) -{ - QuitController quitter; - quitter.PostTimedEvent(QuitEvent(), 1.0); - - TestListener eventListener; - { - TestEventSupport eventSupport; - eventSupport.AddListener(&eventListener); - eventSupport.TestEmitEvent(); - eventSupport.RemoveListener(&eventListener); - } - eventListener.ZeroDummyVar(); - - quitter.Exec(); - RUNNER_ASSERT(eventListener.GetDummyVar() == 0); -} - -int g_delegateTest; - -void OnDelegateTest(const int &k); - -void OnDelegateTest(const int &k) -{ - LogInfo("Got delegate call"); - g_delegateTest = k; -} - -class DelegateTestSupport : - public DPL::Event::EventSupport -{ - public: - void Test() - { - EmitEvent(7); - } -}; - -/* -Name: EventSupport_BindDelegate -Description: tests if event support derived class successfully propagates - event to registered listener -Expected: value of event should be passed to listener -*/ -RUNNER_TEST(EventSupport_BindDelegate) -{ - g_delegateTest = 0; - - DelegateTestSupport support; - support.AddListener(&OnDelegateTest); - - QuitController quitter; - quitter.PostTimedEvent(QuitEvent(), 1.0); - - support.Test(); - - quitter.Exec(); - - support.RemoveListener(&OnDelegateTest); - - RUNNER_ASSERT(g_delegateTest == 7); -} diff --git a/tests/dpl/event/test_ic_delegate.cpp b/tests/dpl/event/test_ic_delegate.cpp deleted file mode 100644 index 77856f4..0000000 --- a/tests/dpl/event/test_ic_delegate.cpp +++ /dev/null @@ -1,603 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_ic_delegate.cpp - * @author Pawel Sikorski (p.sikorski@samsung.com) - * @author Lukasz Wrzosek (l.wrzosek@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of fast delegate tests. - */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -RUNNER_TEST_GROUP_INIT(DPL) - -const int IntVal = 123; -const std::string StringVal = "someString"; - -typedef DPL::Event::ICDelegate<> GetNothingDlpType; -typedef DPL::Event::ICDelegate GetIntDlgType; -typedef DPL::Event::ICDelegate GetIntAndStringDlgType; -DECLARE_GENERIC_EVENT_1(GetNothingEvent, GetNothingDlpType) -DECLARE_GENERIC_EVENT_1(GetIntEvent, GetIntDlgType) -DECLARE_GENERIC_EVENT_1(GetIntAndStringEvent, GetIntAndStringDlgType) - -class ICTestController : - public DPL::Event::Controller::Type> -{ - public: - ICTestController() { } - - protected: - virtual void OnEventReceived(const GetNothingEvent& event) - { - event.GetArg0() (); //calling intercontext delegate - } - virtual void OnEventReceived(const GetIntEvent& event) - { - event.GetArg0() (IntVal); //calling intercontext delegate - } - - virtual void OnEventReceived(const GetIntAndStringEvent& event) - { - event.GetArg0() (IntVal, StringVal); //calling intercontext delegate - } -}; - -struct TestResult -{ - TestResult() : - m_correctThread0(false), - m_correctThread1(false), - m_correctThread2(false), - m_int(-1), - m_int2(-1), - m_string("") - {} - - void TestEventsPassed() - { - RUNNER_ASSERT(m_correctThread0); - RUNNER_ASSERT(m_correctThread1); - RUNNER_ASSERT(m_int == IntVal); - RUNNER_ASSERT(m_correctThread2); - RUNNER_ASSERT(m_int2 == IntVal); - RUNNER_ASSERT(m_string == StringVal); - } - - void TestEventsDidNotPass() - { - RUNNER_ASSERT(!m_correctThread0); - RUNNER_ASSERT(!m_correctThread1); - RUNNER_ASSERT(m_int == -1); - RUNNER_ASSERT(!m_correctThread2); - RUNNER_ASSERT(m_int2 == -1); - RUNNER_ASSERT(m_string == ""); - } - - bool m_correctThread0; - bool m_correctThread1; - bool m_correctThread2; - int m_int; - int m_int2; - std::string m_string; -}; - -class TestContextFreeClass : - protected DPL::Thread, - public DPL::Event::ICDelegateSupport -{ - public: - TestContextFreeClass(ICTestController* controller, TestResult* result) : - Thread(), - m_testResult(result), - m_controller(controller) - { - LogDebug("Context thread id = " << this); - } - - void Run() - { - LogDebug("Running Context Free thread"); - Thread::Run(); - } - - void Quit() - { - LogDebug("Exiting Context Free thread"); - Thread::Quit(); - } - - void Wait() - { - LogDebug("Waiting for thread"); - DPL::WaitForSingleHandle(m_waitable.GetHandle()); - } - - protected: - void OnNothing() - { - LogDebug("Received nothing in thread = " << GetCurrentThread()); - m_testResult->m_correctThread0 = (GetCurrentThread() == this); - } - - void OnIntReceive(int val) - { - LogDebug("Received int in thread = " << GetCurrentThread()); - m_testResult->m_correctThread1 = (GetCurrentThread() == this); - m_testResult->m_int = val; - } - - void OnIntAndStringReceive(int val, std::string stringval) - { - LogDebug("Received int and string in thread = " << GetCurrentThread()); - m_testResult->m_correctThread2 = (GetCurrentThread() == this); - m_testResult->m_int2 = val; - m_testResult->m_string = stringval; - m_waitable.Signal(); - } - - virtual int ThreadEntry() - { - GetNothingEvent getNothingEvent( - makeICDelegate( - &TestContextFreeClass::OnNothing)); - m_controller->DPL::Event::ControllerEventHandler:: - PostEvent( - getNothingEvent); - - GetIntEvent getIntEvent( - makeICDelegate( - &TestContextFreeClass::OnIntReceive)); - m_controller->DPL::Event::ControllerEventHandler:: - PostEvent( - getIntEvent); - - GetIntAndStringEvent getIntAndStringEvent( - makeICDelegate( - &TestContextFreeClass::OnIntAndStringReceive)); - m_controller->DPL::Event::ControllerEventHandler - ::PostEvent( - getIntAndStringEvent); - - return Thread::ThreadEntry(); - } - - private: - TestResult* m_testResult; - DPL::WaitableEvent m_waitable; - ICTestController* m_controller; -}; - -/* -Name: ICDelegate_0 -Description: checks if delegetes are correctly called -Expected: delegates should be called from right context -*/ -RUNNER_TEST(ICDelegate_0) -{ - DPL::Thread thread; - thread.Run(); - LogDebug("Controller thread id = " << &thread); - - ICTestController testController; - testController.Touch(); - testController.SwitchToThread(&thread); - - TestResult result; - TestContextFreeClass* contextFree = - new TestContextFreeClass(&testController, &result); - result.TestEventsDidNotPass(); - - thread.Run(); - contextFree->Run(); - contextFree->Wait(); - contextFree->Quit(); - thread.Quit(); - - delete contextFree; - - result.TestEventsPassed(); -} - -/* -Name: ICDelegate_1 -Description: checks if delegetes are correctly called -Expected: delegates should be called from right context -*/ -RUNNER_TEST(ICDelegate_1) -{ - DPL::Thread thread; - LogDebug("Controller thread id = " << &thread); - - ICTestController testController; - testController.Touch(); - testController.SwitchToThread(&thread); - - TestResult result; - TestContextFreeClass* contextFree = - new TestContextFreeClass(&testController, &result); - result.TestEventsDidNotPass(); - - contextFree->Run(); - contextFree->Quit(); - delete contextFree; //deleting Delegates before actual Events are worked out - thread.Run(); - thread.Quit(); - - result.TestEventsDidNotPass(); -} - -class TestContextFree; -class TestRunnerInThread; - -namespace { -const int ControllersPerThread = 40; -const int ContextFreePerThread = 180; -const int TestsPerController = 110; -const int TestThreads = 23; -const int TestsPerThread = 100; -const int NumberOfEvents = 230; - -typedef std::shared_ptr ICTestControllerPtr; -typedef std::shared_ptr TestContextFreePtr; -typedef std::shared_ptr TestRunnerInThreadPtr; -typedef std::shared_ptr ThreadPtr; - -DPL::Mutex mutex; -std::list frees; -std::list ctrls; -std::list frees_threads; -std::list ctrls_threads; -} - -class TestContextFree : public DPL::Event::ICDelegateSupport -{ - public: - TestContextFree(ICTestController* controller, - int eventsCount) : - m_controller(controller), - m_eventsCount(eventsCount) - {} - - void Wait() - { - LogDebug("Waiting for thread"); - DPL::WaitForSingleHandle(m_waitable.GetHandle()); - } - - void OnNothing() - { - LogDebug("Got"); - m_eventsCount--; - if (m_eventsCount > 0) { - LogDebug("posting next event"); - GetIntAndStringEvent getIntAndStringEvent( - makeICDelegate( - &TestContextFree::OnIntAndStringReceive)); - LogDebug("posting next event ..."); - m_controller->DPL::Event::ControllerEventHandler< - GetIntAndStringEvent>::PostEvent( - getIntAndStringEvent); - LogDebug("posting next event done"); - } else { - LogDebug("test finished"); - m_waitable.Signal(); - } - } - - void OnIntReceive(int) - { - LogDebug("Got"); - m_eventsCount--; - if (m_eventsCount > 0) { - LogDebug("posting next event"); - GetNothingEvent getNothingEvent( - makeICDelegate( - &TestContextFree::OnNothing)); - LogDebug("posting next event ..."); - m_controller->DPL::Event::ControllerEventHandler:: - PostEvent( - getNothingEvent); - LogDebug("posting next event done"); - } else { - LogDebug("test finished"); - m_waitable.Signal(); - } - } - - void OnIntAndStringReceive(int, std::string) - { - LogDebug("Got"); - m_eventsCount--; - if (m_eventsCount > 0) { - LogDebug("posting next event"); - - GetIntEvent getIntEvent( - makeICDelegate( - &TestContextFree::OnIntReceive)); - LogDebug("posting next event ..."); - m_controller->DPL::Event::ControllerEventHandler:: - PostEvent( - getIntEvent); - LogDebug("posting next event done"); - } else { - LogDebug("test finished"); - m_waitable.Signal(); - } - } - - void StartTestOnNothing() - { - GetNothingEvent getNothingEvent( - makeICDelegate( - &TestContextFree::OnNothing)); - m_controller->DPL::Event::ControllerEventHandler:: - PostEvent( - getNothingEvent); - } - - void StartTestOnInt() - { - GetIntEvent getIntEvent( - makeICDelegate( - &TestContextFree::OnIntReceive)); - m_controller->DPL::Event::ControllerEventHandler:: - PostEvent( - getIntEvent); - } - - void StartTestOnIntAndString() - { - GetIntAndStringEvent getIntAndStringEvent( - makeICDelegate( - &TestContextFree::OnIntAndStringReceive)); - m_controller->DPL::Event::ControllerEventHandler - ::PostEvent( - getIntAndStringEvent); - } - - bool CheckTest() - { - LogDebug("Checking test result"); - return m_eventsCount == 0; - } - - private: - ICTestController* m_controller; - int m_eventsCount; - DPL::WaitableEvent m_waitable; -}; - -class TestRunnerInThread : public DPL::Thread -{ - public: - TestRunnerInThread(int events, int tests) : - m_eventsCount(events), - m_tests(tests) {} - - void WaitForInit() - { - LogDebug("Waiting for thread"); - DPL::WaitForSingleHandle(m_init.GetHandle()); - } - - protected: - virtual int ThreadEntry() - { - LogDebug("Thread starts"); - { - DPL::Mutex::ScopedLock lock(&mutex); - for (int i = 0; i < m_tests; ++i) { - if (i % TestsPerController == 0) { - if (ctrls.size() % ControllersPerThread == 0) { - ThreadPtr thread(new DPL::Thread()); - thread->Run(); - ctrls_threads.push_back(thread); - } - ICTestControllerPtr ptr(new ICTestController()); - ptr->Touch(); - ptr->SwitchToThread(ctrls_threads.back().get()); - ctrls.push_back(ptr); - - TestContextFreePtr t(new TestContextFree(ctrls.back().get(), - m_eventsCount)); - t->StartTestOnNothing(); - LogDebug(""); - frees.push_back(t); - } - } - } - m_init.Signal(); - LogDebug("Thread starts loop"); - return DPL::Thread::ThreadEntry(); - } - - private: - DPL::WaitableEvent m_init; - int m_eventsCount; - int m_tests; -}; - -/* -Name: ICDelegate_2 -Description: checks if delegetes are correctly called -Expected: delegates should be called from right context -*/ -RUNNER_TEST(ICDelegate_2) -{ - LogDebug("Creating test threads"); - for (int i = 0; i < TestThreads; ++i) { - TestRunnerInThreadPtr ptr( - new TestRunnerInThread(NumberOfEvents, TestsPerThread)); - frees_threads.push_back(ptr); - frees_threads.back()->Run(); - } - - FOREACH(it, frees_threads) { - (*it)->WaitForInit(); - } - LogDebug("Creating test threads done"); - - FOREACH(it, frees) { - LogDebug("..."); - (*it)->Wait(); - } - - FOREACH(it, frees) { - RUNNER_ASSERT((*it)->CheckTest()); - } - - frees.clear(); - - FOREACH(it, frees_threads) { - (*it)->Quit(); - } - - frees_threads.clear(); - - FOREACH(it, ctrls) { - (*it)->SwitchToThread(NULL); - } - - FOREACH(it, ctrls_threads) { - (*it)->Quit(); - } - - ctrls.clear(); - ctrls_threads.clear(); -} - -namespace ReuseCheck { -const int ReuseCount = 5; -typedef DPL::Event::ICDelegate<> GetNothingDlpType; -DECLARE_GENERIC_EVENT_1(ReuseCountEvent, GetNothingDlpType) - -class ICReuseTestController : - public DPL::Event::Controller::Type> -{ - public: - ICReuseTestController() - { - m_reuseCount = 0; - } - - protected: - virtual void OnEventReceived(const ReuseCountEvent& event) - { - event.GetArg0() (); //calling intercontext delegate - if (++m_reuseCount < ReuseCount) { - LogInfo("[Send] Reuse: " << m_reuseCount); - DPL::Event::ControllerEventHandler::PostEvent( - event); - } - } - - int m_reuseCount; -}; - -class ReuseTestContextFreeClass : - protected DPL::Thread, - public DPL::Event::ICDelegateSupport -{ - public: - ReuseTestContextFreeClass(ICReuseTestController* controller) : - Thread(), - m_controller(controller), - m_reuseCount(0) - { } - - void Run() - { - Thread::Run(); - } - void Quit() - { - Thread::Quit(); - } - void Wait() - { - DPL::WaitForSingleHandle(m_waitable.GetHandle()); - } - - protected: - void OnReuseReceive() - { - LogDebug("[Received] : " << ++m_reuseCount); - if (m_reuseCount == ReuseCount) { - m_waitable.Signal(); - } - } - - virtual int ThreadEntry() - { - ReuseCountEvent reuseEvent( - makeICDelegate( - &ReuseTestContextFreeClass::OnReuseReceive, - DPL::Event::ICD::Reuse::Yes)); - m_controller->DPL::Event::ControllerEventHandler:: - PostEvent( - reuseEvent); - - return Thread::ThreadEntry(); - } - - private: - DPL::WaitableEvent m_waitable; - ICReuseTestController* m_controller; - int m_reuseCount; -}; - -/* -Name: ICDelegate_3 -Description: checks if delegetes are correctly called -Expected: delegates should be called from right context -*/ -RUNNER_TEST(ICDelegate_3) -{ - DPL::Thread thread; - thread.Run(); - LogDebug("Controller thread id = " << &thread); - - ICReuseTestController testController; - testController.Touch(); - testController.SwitchToThread(&thread); - - ReuseTestContextFreeClass* contextFree = - new ReuseTestContextFreeClass(&testController); - - thread.Run(); - contextFree->Run(); - contextFree->Wait(); - contextFree->Quit(); - thread.Quit(); - - delete contextFree; - - RUNNER_ASSERT(true); -} -} //namespace ReuseCheck diff --git a/tests/dpl/event/test_property.cpp b/tests/dpl/event/test_property.cpp deleted file mode 100644 index d72d02e..0000000 --- a/tests/dpl/event/test_property.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_property.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of test property - */ -#include -#include -#include -#include - -namespace { -const int PROPERTY_VALUE_INT = 2; -const std::string PROPERTY_VALUE_STRING = "aaa"; -} - -int ReadSomething2(DPL::Event::Model */*model*/); -int ReadSomething2(DPL::Event::Model */*model*/) -{ - return PROPERTY_VALUE_INT; -} - -std::string ReadSomething(DPL::Event::Model */*model*/); -std::string ReadSomething(DPL::Event::Model */*model*/) -{ - return PROPERTY_VALUE_STRING; -} - -void WriteSomething(const std::string & /*value*/, DPL::Event::Model */*model*/); -void WriteSomething(const std::string & /*value*/, DPL::Event::Model */*model*/) -{} - -class MyModel : - public DPL::Event::Model -{ - public: - ~MyModel() {} - - DPL::Event::Property - Caption; - - DPL::Event::Property - Testproperty0; - - DPL::Event::Property - Testproperty1; - - DPL::Event::Property - Testproperty2; - - DPL::Event::Property Testproperty3; - - DPL::Event::Property Testproperty4; - - DPL::Event::Property - Testproperty5; - - MyModel() : - Caption(this, "Foo caption"), - Testproperty0(this, "", &ReadSomething), - Testproperty1(this), - Testproperty2(this), - Testproperty3(this), - Testproperty4(this, "test", &ReadSomething, &WriteSomething), - Testproperty5(this, &ReadSomething2) - {} -}; - -std::string g_caption; - -void OnNameChanged(const DPL::Event::PropertyEvent &event); -void OnNameChanged(const DPL::Event::PropertyEvent &event) -{ - g_caption = event.value; -} - -/* -Name: Model_Test -Description: tests accessing and changing models properties -Expected: listener should get changed value -*/ -RUNNER_TEST(Model_Test) -{ - MyModel model; - - g_caption = "It is a bad caption"; - - model.Caption.AddListener(&OnNameChanged); - model.Caption.Set("Test name"); - - RUNNER_ASSERT(model.Testproperty4.Get() == PROPERTY_VALUE_STRING); - RUNNER_ASSERT(PROPERTY_VALUE_INT == model.Testproperty5.Get()); - RUNNER_ASSERT(g_caption == "Test name"); - RUNNER_ASSERT(model.Caption.Get() == "Test name"); - - model.Caption.RemoveListener(&OnNameChanged); -} diff --git a/tests/dpl/localization/CMakeLists.txt b/tests/dpl/localization/CMakeLists.txt deleted file mode 100644 index a50727a..0000000 --- a/tests/dpl/localization/CMakeLists.txt +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved -# -# 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. -# -# @file CMakeLists.txt -# @author Bartlomiej Grzelewski (b.grzelewski@samsung.com) -# @version 1.0 -# @brief -# - -# -# Test files -# -# Define all DPL tests sources. -# Runner is responsible for runnint it all and -# generating proper output files -# - -SET(TARGET_LOC "dpl-tests-loc") - -SET(LOC_TESTS_SOURCES - ${DPL_TESTS_DIR}/localization/test_localization.cpp - ${DPL_TESTS_DIR}/localization/test_suite01.cpp - #${DPL_TESTS_DIR}/localization/mockup_src/widget_dao.cpp - #${PROJECT_SOURCE_DIR}/modules/localization/src/localization_utils.cpp - #${PROJECT_SOURCE_DIR}/modules/localization/src/w3c_file_localization.cpp -) - -#WRT_INCLUDE_DIRECTORIES( - #${SYS_EFL_INCLUDE_DIRS} - #${DPL_TEST_INCLUDE_DIR} - #${DPL_TESTS_DIR}/localization/mockup_include - #${PROJECT_SOURCE_DIR}/modules/localization/include -#) - -#LINK_DIRECTORIES(${SYS_EFL_LIBRARY_DIRS}) - -WRT_TEST_BUILD(${TARGET_LOC} ${LOC_TESTS_SOURCES}) -WRT_TEST_INSTALL(${TARGET_LOC}) - -ADD_SUBDIRECTORY(files) diff --git a/tests/dpl/localization/files/CMakeLists.txt b/tests/dpl/localization/files/CMakeLists.txt deleted file mode 100644 index 17c7fda..0000000 --- a/tests/dpl/localization/files/CMakeLists.txt +++ /dev/null @@ -1,19 +0,0 @@ -INSTALL(FILES - ${DPL_TESTS_DIR}/localization/files/one - DESTINATION - /opt/share/widget/tests/localization/widget1/locales/pl-en - ) - -INSTALL(FILES - ${DPL_TESTS_DIR}/localization/files/one - ${DPL_TESTS_DIR}/localization/files/two - DESTINATION - /opt/share/widget/tests/localization/widget2/locales/pl-en - ) - -INSTALL(FILES - ${DPL_TESTS_DIR}/localization/files/two - DESTINATION - /opt/share/widget/tests/localization/widget2/locales/en-en - ) - diff --git a/tests/dpl/localization/files/one b/tests/dpl/localization/files/one deleted file mode 100644 index e69de29..0000000 diff --git a/tests/dpl/localization/files/two b/tests/dpl/localization/files/two deleted file mode 100644 index e69de29..0000000 diff --git a/tests/dpl/localization/mockup_include/dpl/wrt-dao-ro/common_dao_types.h b/tests/dpl/localization/mockup_include/dpl/wrt-dao-ro/common_dao_types.h deleted file mode 100644 index 06b7294..0000000 --- a/tests/dpl/localization/mockup_include/dpl/wrt-dao-ro/common_dao_types.h +++ /dev/null @@ -1,481 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/** - * - * @file common_dao_types.h - * @author Michal Ciepielski (m.ciepielski@samsung.com) - * @version 1.0 - * @brief This file contains the declaration of common data types for wrtdb - */ - -#ifndef WRT_SRC_CONFIGURATION_COMMON_DAO_TYPES_H_ -#define WRT_SRC_CONFIGURATION_COMMON_DAO_TYPES_H_ - -#include -#include -#include -#include -#include -#include -#include - -namespace WrtDB { -namespace Powder { -typedef std::set StringSet; -//! Widget description -struct Description -{ - //!Content level - typedef enum - { - Level0 = 0, - Level1, - Level2, - Level3, - Level4, - Level5, - LevelUnknown - } LevelEnum; - struct LevelEntry - { - LevelEnum level; //!< content level - - typedef StringSet Context; - - //! POWDER context - //! xa This material appears in an artistic context - //! xb This material appears in an educational context - //! xc This material appears in a medical context - //! xd This material appears in a sports context - //! xe This material appears in a violent context - Context context; - explicit LevelEntry(LevelEnum level = LevelUnknown); - //! Function checks if context is valid - //! \param[in] level POWDER content level - //! \param[in] context POWDER context - bool isContextValid(LevelEnum level, - const DPL::OptionalString& context) const; - }; - - struct CategoryEntry - { - //! Levels entries for POWDER description - typedef std::vector LevelsContainer; - LevelsContainer levels; - //! Function checks if context is valid - //! \param[out] reason set if context invalid - //! \param[in] level POWDER content level - //! \param[in] context POWDER context - bool isCategoryValid(LevelEntry& reason, - LevelEnum level, - const DPL::OptionalString& context) const; - }; - - //! POWDER Category -> Category entry map for Widget - //! - //! nu Nudity - //! se Sex - //! vi Violence - //! la Potentially offensive language - //! dr Drug use - //! ga Gambling - //! ha Hate or harmful activities - //! ug Use of user-generated content - typedef std::map CategoryEntries; - - CategoryEntries categories; - - //! Age rating for widget - //! If Null not set - DPL::OptionalInt ageRating; -}; -} // namespace Powder - -namespace ChildProtection { -//! Blacklist with forbidden URLs -//! It should be stored in WidgetDAO -typedef std::vector BlackList; - -//! Widget Child protection record -//! Record should be stored in WingetDAO -struct Record -{ - //! Child protection enabled - bool enabled; - explicit Record(bool enabled) : - enabled(enabled) - {} -}; - -//! Powder processing -struct PowderRules -{ - //! Rule set by parent about forbidden category - //! Powder category - //! nu Nudity - //! se Sex - //! vi Violence - //! la Potentially offensive language - //! dr Drug use - //! ga Gambling - //! ha Hate or harmful activities - //! ug Use of user-generated content - //! Powder context - //! xa This material appears in an artistic conteaxt - //! xb This material appears in an educational context - //! xc This material appears in a medical context - //! xd This material appears in a sports context - //! xe This material appears in a violent context - struct CategoryRule - { - DPL::String category; - Powder::Description::LevelEnum level; - DPL::OptionalString context; - explicit CategoryRule( - const DPL::String& category = DPL::String(), - Powder::Description::LevelEnum level = - Powder::Description::LevelUnknown, - const DPL::OptionalString& context = - DPL::OptionalString()); - }; - - struct PowderResult - { - //! Reasoning outcome: part of POWDER description used to invalidate - Powder::Description::LevelEntry invalidDescription; - //! Reasoning outcome: rule set by parent not full filed by description - CategoryRule invalidRule; - - //! Reasoning outcome: type of invalidity - enum InvalidReason - { - InvalidRule, //!< One of rules was not fulfilled - InvalidAge, //!< Age is invalid - AgeRatingNotSet, //!< Age rating for widget is not set - Valid //!< Description valid - }; - InvalidReason reason; - explicit PowderResult( - InvalidReason reason = Valid, - const Powder::Description::LevelEntry& - invalidDescription = - Powder::Description::LevelEntry(), - const CategoryRule& invalidRule = CategoryRule()); - }; - - typedef std::pair ResultPair; - - //! Function checks if rule is fulfilled by description - //! \param[in] rule checked rule - //! \param[in] description - //! \retval true rule is valid - //! \retval false rule is invalid - ResultPair isRuleValidForDescription(const CategoryRule& rule, - const Powder::Description& description) - const; - //! Function checks if age limit is fulfilled by description - //! \param[in] description - //! \retval true age is valid - //! \retval false age is invalid - ResultPair isAgeValidForDescription( - const Powder::Description& description) const; - - //! It is the maximum age rating valid for child - //! Uniform age is stored in WidgetDAO - DPL::OptionalInt ageLimit; - - //! Set to true if age rating is required - //! If ageLimit is not set value is ignored - bool isAgeRatingRequired; - - //! Set of rules configured by parent - //! Rules are stored in WidgetDAO and are uniform for all widgets - typedef std::vector RulesContainer; - RulesContainer rules; - - //! Function check if Widget description is valid for ChildProtection - //! configuration - //! \param description widget description - //! \retval true widget is valid - //! \retval false widget is invalid - ResultPair isDescriptionValid(const Powder::Description& description) - const; - - PowderRules() : - isAgeRatingRequired(false) - {} -}; -} // namespace ChildProtection - -class PluginMetafileData -{ - public: - struct Feature - { - std::string m_name; - std::set m_deviceCapabilities; - - bool operator< (const Feature& obj) const - { - return m_name < obj.m_name; - } - }; - typedef std::set FeatureContainer; - - public: - - PluginMetafileData() - {} - - std::string m_libraryName; - std::string m_featuresInstallURI; - std::string m_featuresKeyCN; - std::string m_featuresRootCN; - std::string m_featuresRootFingerprint; - - FeatureContainer m_featureContainer; -}; - -class PluginObjectsDAO -{ - public: - typedef std::set Objects; - typedef std::shared_ptr ObjectsPtr; - - public: - explicit PluginObjectsDAO() {} - - protected: - ObjectsPtr m_implemented; - ObjectsPtr m_dependent; -}; - -/** - * @brief Widget id describes web-runtime global widget identifier. - * - * Notice that only up to one widget can exist at the same time. - * DbWidgetHandle can be translated into corresponding WidgetModel by invoking - * FindWidgetModel routine. - */ -typedef int DbWidgetHandle; - -/** - * @brief Structure to hold the information of widget's size - */ -struct DbWidgetSize -{ - DPL::OptionalInt width; - DPL::OptionalInt height; - - DbWidgetSize(DPL::OptionalInt w = DPL::OptionalInt::Null, - DPL::OptionalInt h = DPL::OptionalInt::Null) : - width(w), - height(h) - {} -}; - -inline bool operator ==(const DbWidgetSize &objA, const DbWidgetSize &objB) -{ - if (!objA.height || !objA.width || !objB.width || !objB.height) { - return false; - } else { - return *objA.height == *objB.height && *objA.width == *objB.width; - } -} - -/** - * Widget [G]lobal [U]nique [ID]entifier - * Orginated from appstore ID - */ -typedef DPL::OptionalString WidgetGUID; - -struct WidgetAccessInfo -{ - DPL::String strIRI; /* origin iri */ - bool bSubDomains; /* do we want access to subdomains ? */ - - bool operator ==(const WidgetAccessInfo& info) const - { - return info.strIRI == strIRI && - info.bSubDomains == bSubDomains; - } -}; - -typedef std::list WidgetAccessInfoList; - -typedef std::list WindowModeList; - -/** - * @brief Widget configuration parameter key - */ -typedef DPL::String WidgetParamKey; - -/** - * @brief Widget configuration parameter value - */ -typedef DPL::String WidgetParamValue; - -/** - * @brief A map of widget configuration parameters. - * - * Widget configuration parameters are read from database and are stored - * along with feature that they describe. - */ -typedef std::multimap WidgetParamMap; - -/** - * @brief Widget feature host information about possible javascript extensions - * that widget may use - * - * Widget features are declared in configuration file in widget installation - * package. Each declared special feature is contained in some wrt-plugin that - * declares to implement it. After widget launch wrt searches for proper plugin - * libraries and load needed features. - * - * Widget features can be required or optional. It is possible to start widget - * without missing feature. When required feature cannot be loaded widget will - * not start. - */ - -enum { - INVALID_PLUGIN_HANDLE = -1 -}; -typedef int DbPluginHandle; - -struct DbWidgetFeature -{ - DPL::String name; /// Feature name - bool required; /// Whether feature is required - DbPluginHandle pluginId; /// Plugin id that implement this - // feature - WidgetParamMap params; /// Widget's params - - DbWidgetFeature() : - required(false), - pluginId(INVALID_PLUGIN_HANDLE) - {} -}; - -inline bool operator < (const DbWidgetFeature &objA, - const DbWidgetFeature &objB) -{ - return objA.name.compare(objB.name) < 0; -} - -inline bool operator==(const DbWidgetFeature &featureA, - const DbWidgetFeature &featureB) -{ - return featureA.name == featureB.name && - featureA.required == featureB.required && - featureA.pluginId == featureB.pluginId; -} - -/** - * @brief Default container for features list - */ -typedef std::multiset DbWidgetFeatureSet; - -/** - * @brief Default container with DbWidgetHandle's - */ -typedef std::list DbWidgetHandleList; - -/** - * @brief Widget specific type - * - * Widget type describes belowed in WAC, TIZEN WebApp - */ -enum AppType -{ - APP_TYPE_UNKNOWN = 0, // unknown - APP_TYPE_WAC20, // WAC 2.0 - APP_TYPE_TIZENWEBAPP, // slp webapp -}; - -class WidgetType -{ - public: - WidgetType() : - appType(APP_TYPE_UNKNOWN) - {} - WidgetType(const AppType type) : - appType(type) - {} - bool operator== (const AppType& other) const - { - return appType == other; - } - std::string getApptypeToString() - { - switch (appType) { -#define X(x) case x: return #x; - X(APP_TYPE_UNKNOWN) - X(APP_TYPE_WAC20) - X(APP_TYPE_TIZENWEBAPP) -#undef X - default: - return "UNKNOWN"; - } - } - - AppType appType; -}; -} // namespace WrtDB - -struct WidgetSetting -{ - DPL::String settingName; - DPL::String settingValue; - - bool operator ==(const WidgetSetting& info) const - { - return (info.settingName == settingName && - info.settingValue == settingValue); - } - bool operator !=(const WidgetSetting& info) const - { - return (info.settingName != settingName || - info.settingValue != settingValue); - } -}; - -typedef std::list WidgetSettings; - -/** - * @brief Widget Application Service - * - * Application sercvice describes details of behaviour - * when widget receives aul bundle data. - */ -struct WidgetApplicationService -{ - public: - DPL::String src; /* start uri */ - DPL::String operation; /* service name */ - DPL::String scheme; /* scheme type*/ - DPL::String mime; /* mime type */ - - bool operator== (const WidgetApplicationService& other) const - { - return src == other.src && - operation == other.operation && - scheme == other.scheme && - mime == other.mime; - } -}; - -typedef std::list WidgetApplicationServiceList; -#endif /* WRT_SRC_CONFIGURATION_COMMON_DAO_TYPES_H_ */ diff --git a/tests/dpl/localization/mockup_include/dpl/wrt-dao-rw/widget_dao.h b/tests/dpl/localization/mockup_include/dpl/wrt-dao-rw/widget_dao.h deleted file mode 100644 index 264c6e4..0000000 --- a/tests/dpl/localization/mockup_include/dpl/wrt-dao-rw/widget_dao.h +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/** - * This file contains the declaration of widget dao class. - * - * @file widget_dao_read_only.h - * @author Yang Jie (jie2.yang@samsung.com) - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @author Pawel Sikorski (p.sikorski@samsung.com) - * @version 1.0 - * @brief This file contains the declaration of widget dao - */ - -#ifndef _WRT_SRC_CONFIGURATION_WIDGET_DAO_READ_ONLY_H_ -#define _WRT_SRC_CONFIGURATION_WIDGET_DAO_READ_ONLY_H_ - -#include - -#include -#include -#include -#include - -#include -#include -#include - -#include -//#include "../wrt-dao-ro/common_dao_types.h" - -typedef DPL::OptionalString WidgetGUID; - -namespace ConfigParserData { -struct Icon -{ - Icon(const DPL::String& src) : src(src) - {} - DPL::String src; - DPL::OptionalInt width; - DPL::OptionalInt height; - bool operator==(const Icon&) const; - bool operator!=(const Icon&) const; - bool operator >(const Icon&) const; - bool operator>=(const Icon&) const; - bool operator <(const Icon&) const; - bool operator<=(const Icon&) const; -}; -} // namespace ConfigParserData -namespace WrtDB { -typedef std::list StringList; - -struct WidgetLocalizedInfo -{ - DPL::OptionalString name; - DPL::OptionalString shortName; - DPL::OptionalString description; - DPL::OptionalString license; - DPL::OptionalString licenseHref; -}; - -typedef std::list LanguageTagList; - -class WidgetDAO -{ - public: - /** - * WidgetDAO Exception classes - */ - class Exception - { - public: - DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) - DECLARE_EXCEPTION_TYPE(Base, DatabaseError) - DECLARE_EXCEPTION_TYPE(Base, ReadOnlyProperty) - DECLARE_EXCEPTION_TYPE(Base, GUIDisNull) - DECLARE_EXCEPTION_TYPE(Base, UnexpectedEmptyResult) - DECLARE_EXCEPTION_TYPE(Base, WidgetNotExist) - DECLARE_EXCEPTION_TYPE(Base, AlreadyRegistered) - }; - - protected: - DbWidgetHandle m_widgetHandle; - - public: - struct WidgetLocalizedIconRow - { - int appId; - int iconId; - DPL::String widgetLocale; - }; - typedef std::list WidgetLocalizedIconList; - - struct WidgetIconRow - { - int iconId; - int appId; - DPL::String iconSrc; - DPL::OptionalInt iconWidth; - DPL::OptionalInt iconHeight; - }; - typedef std::list WidgetIconList; - - struct WidgetStartFileRow - { - int startFileId; - int appId; - DPL::String src; - }; - typedef std::list WidgetStartFileList; - - struct WidgetLocalizedStartFileRow - { - int startFileId; - int appId; - DPL::String widgetLocale; - DPL::String type; - DPL::String encoding; - }; - typedef std::list LocalizedStartFileList; - - /** - * This is a constructor. - * - * @param[in] widgetHandle application id of widget. - */ - WidgetDAO(DbWidgetHandle widgetHandle) : - m_widgetHandle(widgetHandle) - {} - - /** - * Destructor - */ - virtual ~WidgetDAO(){} - - /** - * This method returns widget handle(m_widgetHandle). - * - * @return widget handle(m_widgetHandle). - * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. - * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in - * DB table. - */ - DbWidgetHandle getHandle() const - { - return m_widgetHandle; - } - DbWidgetHandle getHandle(const WidgetGUID GUID) const; - static DbWidgetHandle getHandle(const DPL::String tizenAppId); - - /** - * This method returns the root directory of widget resource. - * - * @return path name of root directory. - * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. - * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in - * DB table. - */ - DPL::String getPath() const; - void setPath(const DPL::String &path) const; - - /** - * This method returns the defaultlocale for the widget. - * - * @return defaultlocale - * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. - * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in - * DB table. - */ - DPL::OptionalString getDefaultlocale() const; - - /** - * This method returns list of localized icons files; - * - * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. - * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in - * DB table. - */ - WidgetLocalizedIconList getLocalizedIconList() const; - - /** - * This method returns list of icons files; - * - * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. - * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in - * DB table. - */ - WidgetIconList getIconList() const; - - /** - * This method returns list of localized start files; - * - * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. - * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in - * DB table. - */ - LocalizedStartFileList getLocalizedStartFileList() const; - void setLocalizedStartFileList(const LocalizedStartFileList &list) const; - /** - * This method returns list of start files; - * - * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. - * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in - * DB table. - */ - WidgetStartFileList getStartFileList() const; - void setStartFileList(const WidgetStartFileList &list) const; - - WidgetLocalizedInfo getLocalizedInfo(const DPL::String& languageTag) const; - - protected: - static std::map s_startFileMap; - static std::map s_localizedStartFileMap; - static std::map s_pathMap; -}; -} // namespace WrtDB - -#endif // _WRT_SRC_CONFIGURATION_WIDGET_DAO_READ_ONLY_H_ - diff --git a/tests/dpl/localization/mockup_src/widget_dao.cpp b/tests/dpl/localization/mockup_src/widget_dao.cpp deleted file mode 100644 index 170aad7..0000000 --- a/tests/dpl/localization/mockup_src/widget_dao.cpp +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/** - * This file contains the declaration of widget dao class. - * - * @file widget_dao_read_only.cpp - * @author Yang Jie (jie2.yang@samsung.com) - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @author Pawel Sikorski (p.sikorski@samsung.com) - * @version 1.0 - * @brief This file contains the declaration of widget dao - */ - -//#include "../mockup_include/dpl/wrt-dao-rw/widget_dao.h" -#include - -#include -#include -#include -#include - -namespace WrtDB { -std::map WidgetDAO::s_startFileMap; -std::map WidgetDAO::s_localizedStartFileMap; -std::map WidgetDAO::s_pathMap; - -DbWidgetHandle WidgetDAO::getHandle(const WidgetGUID /* GUID */) const -{ - LogError("Not impleneted!"); - return 0; -} - -DbWidgetHandle WidgetDAO::getHandle(const DPL::String /* tizenAppId */) -{ - LogError("Not implemented!"); - return 0; -} - -DPL::String WidgetDAO::getPath() const -{ - return s_pathMap[m_widgetHandle]; -} - -void WidgetDAO::setPath(const DPL::String &path) const -{ - s_pathMap[m_widgetHandle] = path; -} - -WidgetLocalizedInfo -WidgetDAO::getLocalizedInfo(const DPL::String& /* languageTag */) -const -{ - LogError("Not implemented!"); - return WidgetLocalizedInfo(); -} - -DPL::OptionalString WidgetDAO::getDefaultlocale() const -{ - LogError("Not implemented!"); - return DPL::OptionalString(); -} - -WidgetDAO::WidgetLocalizedIconList WidgetDAO::getLocalizedIconList() const -{ - LogError("Not implemented!"); - return WidgetLocalizedIconList(); -} - -WidgetDAO::WidgetIconList WidgetDAO::getIconList() const -{ - LogError("Not implemented!"); - return WidgetIconList(); -} - -WidgetDAO::LocalizedStartFileList WidgetDAO::getLocalizedStartFileList() const -{ - return s_localizedStartFileMap[m_widgetHandle]; -} - -void WidgetDAO::setLocalizedStartFileList(const LocalizedStartFileList &list) -const -{ - s_localizedStartFileMap[m_widgetHandle] = list; -} - -WidgetDAO::WidgetStartFileList WidgetDAO::getStartFileList() const -{ - return s_startFileMap[m_widgetHandle]; -} - -void WidgetDAO::setStartFileList(const WidgetStartFileList &list) const -{ - s_startFileMap[m_widgetHandle] = list; -} -} // namespace WrtDB diff --git a/tests/dpl/localization/test_localization.cpp b/tests/dpl/localization/test_localization.cpp deleted file mode 100644 index 42ffe3a..0000000 --- a/tests/dpl/localization/test_localization.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file main.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of main - */ -#include - -int main(int argc, char *argv[]) -{ - return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); -} - diff --git a/tests/dpl/localization/test_suite01.cpp b/tests/dpl/localization/test_suite01.cpp deleted file mode 100644 index d3cb174..0000000 --- a/tests/dpl/localization/test_suite01.cpp +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/** - * This file contains the declaration of widget dao class. - * - * @file test_suite01.cpp - * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) - * @version 1.0 - * @brief - */ - -#include -#include - -//#include "mockup_include/dpl/wrt-dao-rw/widget_dao.h" -#include -#include - -namespace { -WrtDB::LanguageTagList generateLanguageTags() -{ - WrtDB::LanguageTagList tags; - tags.push_back(L"pl-pl"); - tags.push_back(L"en-en"); - tags.push_back(L"pl-en"); - return tags; -} - -static const WrtDB::LanguageTagList languageTags = generateLanguageTags(); -static const DPL::String widget1Path = - L"/opt/share/widget/tests/localization/widget1/"; -static const DPL::String widget2Path = - L"/opt/share/widget/tests/localization/widget2/"; -} // anonymous namespace - -RUNNER_TEST(test01_getFilePathInWidgetPackageFromUrl){ - const int widgetHandle = 1; - WrtDB::WidgetDAO dao(widgetHandle); - //dao.setPath(widget1Path); - - auto result = W3CFileLocalization::getFilePathInWidgetPackageFromUrl( - widgetHandle, - languageTags, - L"widget://one"); - - RUNNER_ASSERT( - *result == - L"/opt/share/widget/tests/localization/widget1/locales/pl-en/one"); -} - -RUNNER_TEST(test02_getFilePathInWidgetPackageFromUrl){ - const int widgetHandle = 2; - WrtDB::WidgetDAO dao(widgetHandle); - //dao.setPath(widget2Path); - - auto result = W3CFileLocalization::getFilePathInWidgetPackageFromUrl( - widgetHandle, - languageTags, - L"widget://one"); - - RUNNER_ASSERT( - *result == - L"/opt/share/widget/tests/localization/widget2/locales/pl-en/one"); -} - -RUNNER_TEST(test03_getFilePathInWidgetPackageFromUrl){ - const int widgetHandle = 2; - WrtDB::WidgetDAO dao(widgetHandle); - //dao.setPath(widget2Path); - - auto result = W3CFileLocalization::getFilePathInWidgetPackageFromUrl( - widgetHandle, - languageTags, - L"widget://two"); - - RUNNER_ASSERT( - *result == - L"/opt/share/widget/tests/localization/widget2/locales/en-en/two"); -} - -RUNNER_TEST(test04_getFilePathInWidgetPackage){ - const int widgetHandle = 1; - WrtDB::WidgetDAO dao(widgetHandle); - //dao.setPath(widget1Path); - - auto result = W3CFileLocalization::getFilePathInWidgetPackage( - widgetHandle, - languageTags, - L"one"); - - RUNNER_ASSERT(*result == L"locales/pl-en/one"); -} - -RUNNER_TEST(test05_getFilePathInWidgetPackage){ - const int widgetHandle = 2; - WrtDB::WidgetDAO dao(widgetHandle); - //dao.setPath(widget2Path); - - auto result = W3CFileLocalization::getFilePathInWidgetPackage( - widgetHandle, - languageTags, - L"two"); - - RUNNER_ASSERT(*result == L"locales/en-en/two"); -} - diff --git a/tests/dpl/test/CMakeLists.txt b/tests/dpl/test/CMakeLists.txt deleted file mode 100644 index 6e34912..0000000 --- a/tests/dpl/test/CMakeLists.txt +++ /dev/null @@ -1,31 +0,0 @@ -# Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved -# -# 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. -# -# @file CMakeLists.txt -# @author Bartlomiej Grzelewski (b.grzelewski@samsung.com) -# @version 1.0 -# @brief -# - -SET(TARGET_NAME "dpl-tests-test") - -# Set DPL tests sources -SET(DPL_TESTS_UTIL_SOURCES - ${TESTS_DPL_DIR}/test/main.cpp - ${TESTS_DPL_DIR}/test/runner_child.cpp -) - -#WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_NAME} ${TARGET_DPL_UTILS_EFL}) -WRT_TEST_BUILD(${TARGET_NAME} ${DPL_TESTS_UTIL_SOURCES}) -WRT_TEST_INSTALL(${TARGET_NAME}) diff --git a/tests/dpl/test/main.cpp b/tests/dpl/test/main.cpp deleted file mode 100644 index 42ffe3a..0000000 --- a/tests/dpl/test/main.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file main.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of main - */ -#include - -int main(int argc, char *argv[]) -{ - return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); -} - diff --git a/tests/dpl/test/runner_child.cpp b/tests/dpl/test/runner_child.cpp deleted file mode 100644 index d911270..0000000 --- a/tests/dpl/test/runner_child.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file widget_version.cpp - * @author Bartlomiej Grzelewski (b.grzelewski@samsung.com) - * @version 1.0 - * @brief Implementation file for test cases for engine internal tests - */ -#include -#include -#include -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL_TESTS_TEST_CHILD) - -RUNNER_TEST(t00_pass) -{ - RUNNER_ASSERT_MSG(1, "This test should pass"); -} - -RUNNER_CHILD_TEST(t01_pass) -{ - RUNNER_ASSERT_MSG(1, "This test should pass"); -} - -RUNNER_CHILD_TEST(t02_fail) -{ - RUNNER_ASSERT_MSG(0, "This test should fail"); -} - -RUNNER_CHILD_TEST(t03_fail_timeout) -{ - sleep(20); - RUNNER_ASSERT_MSG(1, "This test should fail"); -} - -RUNNER_CHILD_TEST(t04_fail) -{ - RUNNER_ASSERT_MSG(1, "This test should fail"); - RUNNER_ASSERT_MSG(1, "This test should fail"); - RUNNER_ASSERT_MSG(1, "This test should fail"); - RUNNER_ASSERT_MSG(1, "This test should fail"); - RUNNER_ASSERT_MSG(0, "This test should fail"); -} - -RUNNER_CHILD_TEST(t05_fail_child_died) -{ - kill(getpid(), SIGKILL); - RUNNER_ASSERT_MSG(1, "This test should fail"); -} - -RUNNER_CHILD_TEST(t06_pass_8_second_test) -{ - sleep(8); - RUNNER_ASSERT_MSG(1, "This test should pass"); -} - -RUNNER_CHILD_TEST(t07_fail_unknown_exception) -{ - throw("hello"); -} - -RUNNER_CHILD_TEST(t08_fail_unknown_exception) -{ - throw(1); -} - -RUNNER_CHILD_TEST(t09_fail_you_should_see_text_normal_assert) -{ - RUNNER_ASSERT_MSG(0, "Normal assert"); -} - -RUNNER_CHILD_TEST(t10_pass) -{ - RUNNER_ASSERT_MSG(1, "Normal assert"); -} - diff --git a/tests/dpl/unused/test_caller.cpp b/tests/dpl/unused/test_caller.cpp deleted file mode 100644 index 6f1a1ff..0000000 --- a/tests/dpl/unused/test_caller.cpp +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_address.cpp - * @author Tomasz Swierczek (t.swierczek@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of caller tests - */ - -#include -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL) - -// test stream class -class BinaryStream : public DPL::IStream -{ - public: - virtual void Read(size_t num, void * bytes) - { - for (unsigned i = 0; i < num; ++i) { - ((unsigned char*)bytes)[i] = data[i + readPosition]; - } - readPosition += num; - } - virtual void Write(size_t num, const void * bytes) - { - for (unsigned i = 0; i < num; ++i) { - data.push_back(((unsigned char*)bytes)[i]); - } - } - BinaryStream() - { - readPosition = 0; - } - virtual ~BinaryStream(){} - - private: - std::vector data; - unsigned readPosition; -}; - -static int return_func(int a, bool b) -{ - if (b) { - return a; - } else { - return 0; - } -} - -static int called = 0; - -static void void_func(int a) -{ - called = a; -} - -static struct VoidDelegate -{ - void operator()(int a) - { - called = a; - } -} voidDelegate; - -static struct ReturnDelegate -{ - int operator()(int a) - { - return a; - } -} returnDelegate; - -RUNNER_TEST(Caller_function_void) -{ - int a = 23; - BinaryStream stream; - DPL::Serialization::Serialize(stream, a); - called = 0; - DPL::Caller::Call(stream, void_func); - RUNNER_ASSERT(called == a); -} - -RUNNER_TEST(Caller_function_return) -{ - int a = 23; - bool b = true; - BinaryStream stream; - DPL::Serialization::Serialize(stream, a); - DPL::Serialization::Serialize(stream, b); - int result = DPL::Caller::Call(stream, return_func); - RUNNER_ASSERT(result == a); -} - -RUNNER_TEST(Caller_delegate_void) -{ - int a = 23; - BinaryStream stream; - called = 0; - DPL::Serialization::Serialize(stream, a); - DPL::Caller::CallDelegate(stream, voidDelegate); - RUNNER_ASSERT(called == a); -} - -RUNNER_TEST(Caller_delegate_return) -{ - int a = 23; - BinaryStream stream; - called = 0; - DPL::Serialization::Serialize(stream, a); - int result = 0; - DPL::Caller::CallDelegate(stream, returnDelegate, result); - RUNNER_ASSERT(result == a); -} diff --git a/tests/dpl/unused/test_crypto_hash.cpp b/tests/dpl/unused/test_crypto_hash.cpp deleted file mode 100644 index dd208b6..0000000 --- a/tests/dpl/unused/test_crypto_hash.cpp +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_crypto_hash.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of test crypto hash - */ -#include -#include -RUNNER_TEST_GROUP_INIT(DPL) - -#define TEST_CRYPTO_HASH(Class, Input, Output) \ - Class crypto; \ - crypto.Append(Input); \ - crypto.Finish(); \ - RUNNER_ASSERT(crypto.ToString() == Output); - -RUNNER_TEST(CryptoHash_MD2) -{ - TEST_CRYPTO_HASH(DPL::Crypto::Hash::MD2, - "sample_input_string", - "c9f26439c9882cccc98467dbdf07b1fc"); -} - -RUNNER_TEST(CryptoHash_MD4) -{ - TEST_CRYPTO_HASH(DPL::Crypto::Hash::MD4, - "sample_input_string", - "8cd0720f7ec98c8e5f008afb54054677"); -} - -RUNNER_TEST(CryptoHash_MD5) -{ - TEST_CRYPTO_HASH(DPL::Crypto::Hash::MD5, - "sample_input_string", - "eb7ae4f28fecbd1fd777d9b7495fc8ec"); -} - -RUNNER_TEST(CryptoHash_SHA) -{ - TEST_CRYPTO_HASH(DPL::Crypto::Hash::SHA, - "sample_input_string", - "0a5725f3586616a4049730f3ba14c8aeda79ab21"); -} - -RUNNER_TEST(CryptoHash_SHA1) -{ - TEST_CRYPTO_HASH(DPL::Crypto::Hash::SHA1, - "sample_input_string", - "be0ed9040af0c2b772b2dd0776f6966b5f4d1206"); -} - -RUNNER_TEST(CryptoHash_DSS) -{ - TEST_CRYPTO_HASH(DPL::Crypto::Hash::DSS, - "sample_input_string", - "be0ed9040af0c2b772b2dd0776f6966b5f4d1206"); -} - -RUNNER_TEST(CryptoHash_DSS1) -{ - TEST_CRYPTO_HASH(DPL::Crypto::Hash::DSS1, - "sample_input_string", - "be0ed9040af0c2b772b2dd0776f6966b5f4d1206"); -} - -RUNNER_TEST(CryptoHash_ECDSA) -{ - TEST_CRYPTO_HASH(DPL::Crypto::Hash::ECDSA, - "sample_input_string", - "be0ed9040af0c2b772b2dd0776f6966b5f4d1206"); -} - -RUNNER_TEST(CryptoHash_SHA224) -{ - TEST_CRYPTO_HASH(DPL::Crypto::Hash::SHA224, - "sample_input_string", - "d4dde2370eb869f6e790133b94d58e45417392b9d899af883a274011"); -} - -RUNNER_TEST(CryptoHash_SHA256) -{ - TEST_CRYPTO_HASH( - DPL::Crypto::Hash::SHA256, - "sample_input_string", - "a470ec7c783ac51f9eb1772132e6bde1a053bbc81650719dd0ac62ecd93caf12"); -} - -RUNNER_TEST(CryptoHash_SHA384) -{ - TEST_CRYPTO_HASH( - DPL::Crypto::Hash::SHA384, - "sample_input_string", - "63d8bfa95c95c6906d1816965431c065278a655c60f786c9b246c1f73ba7ac557007f5064ba54ebd3a1988e6f37baa97"); -} - -RUNNER_TEST(CryptoHash_SHA512) -{ - TEST_CRYPTO_HASH( - DPL::Crypto::Hash::SHA512, - "sample_input_string", - "799317a140741937d9e5d8dbf9d3045d2c220de5ac33b3d5897acf873291ed14379eb15ef406d2284313d40edb0e01affac8efeb01cb47c2042e3e62a4a83d7d"); -} diff --git a/tests/dpl/unused/test_message_queue.cpp b/tests/dpl/unused/test_message_queue.cpp deleted file mode 100644 index 3322413..0000000 --- a/tests/dpl/unused/test_message_queue.cpp +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_message_queue.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of message queue tests - */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -DECLARE_GENERIC_EVENT_0(QuitEvent) - -class QuitController : - public DPL::Controller::Type>, - public DPL::ApplicationExt -{ - public: - QuitController() : DPL::ApplicationExt(1, NULL, "test-app") - { - Touch(); - } - - protected: - virtual void OnEventReceived(const QuitEvent &) - { - Quit(); - } -}; - -RUNNER_TEST_GROUP_INIT(DPL) - -class CopyThread : - public DPL::Thread -{ - private: - bool m_success; - DPL::AbstractWaitableInput *m_input; - DPL::AbstractWaitableOutput *m_output; - std::size_t m_dataSize; - - public: - CopyThread(DPL::AbstractWaitableInput *input, - DPL::AbstractWaitableOutput *output, - std::size_t dataSize) : - m_success(true), - m_input(input), - m_output(output), - m_dataSize(dataSize) - { - LogInfo("Thread created"); - } - - protected: - virtual int ThreadEntry() - { - LogInfo("Entering copy thread"); - - Try - { - DPL::Copy(m_input, m_output, m_dataSize); - } - Catch(DPL::CopyFailed) - { - m_success = false; - - LogWarning("Copy failed!"); - return 0; - } - - LogInfo("Copy finished"); - return 0; - } -}; - -inline std::string BinaryQueueToString(const DPL::BinaryQueue &queue) -{ - char *buffer = new char[queue.Size()]; - queue.Flatten(buffer, queue.Size()); - std::string result = std::string(buffer, buffer + queue.Size()); - delete[] buffer; - return result; -} - -RUNNER_TEST(MessageQueue_DoubleCopy) -{ - DPL::BinaryQueue dataA; - DPL::MessageQueue dataB("/test_mqueue_dataB", true, false, 0660, true); - DPL::MessageQueue dataC("/test_mqueue_dataC", true, false, 0660, true); - DPL::BinaryQueue dataD; - - DPL::AbstractWaitableInputAdapter dataAdapterA(&dataA); - DPL::AbstractWaitableOutputAdapter dataAdapterD(&dataD); - - const std::string testData = - "Lorem ipsum dolor sit amet, consectetur adipiscing elit." - "Cras elementum venenatis velit, sit amet vehicula odio gravida a." - "Curabitur id nibh id ante adipiscing sollicitudin." - "Maecenas in tellus vel augue vehicula pharetra hendrerit cursus est." - "" - "Ut malesuada quam porttitor dui euismod lacinia." - "Phasellus quis lectus sed lectus dictum tincidunt et vitae leo." - "Fusce id est massa, condimentum bibendum urna." - "Donec venenatis quam eget sapien vulputate egestas." - "Maecenas scelerisque lorem a neque molestie a varius erat condimentum." - "Maecenas varius hendrerit ligula, sed iaculis justo pretium id." - "Nunc sit amet nisl vitae justo tristique suscipit id eget tortor." - "" - "Pellentesque sollicitudin nulla at metus dapibus tincidunt." - "Integer consequat justo eget dui imperdiet iaculis." - "Sed vestibulum ipsum vitae libero accumsan non molestie metus adipiscing." - "" - "Vivamus quis dui enim, in blandit urna." - "In imperdiet lacus at orci elementum a scelerisque dui blandit." - "Donec vulputate enim metus, eget convallis ante." - "Etiam mollis enim eget eros pulvinar nec sagittis justo fermentum." - "" - "Vestibulum sed nunc eu leo lobortis ultrices." - "Nullam placerat nulla et est blandit nec interdum nunc pulvinar." - "Vivamus a lectus eget dui fermentum hendrerit."; - - QuitController quitter; - quitter.PostTimedEvent(QuitEvent(), 1.0); - - CopyThread threadA(&dataAdapterA, &dataB, testData.size()); - CopyThread threadB(&dataB, &dataC, testData.size()); - CopyThread threadC(&dataC, &dataAdapterD, testData.size()); - - dataA.AppendCopy(testData.c_str(), testData.size()); - - threadA.Run(); - threadB.Run(); - threadC.Run(); - - quitter.Exec(); - - threadA.Quit(); - threadB.Quit(); - threadC.Quit(); - - // Now, test data should be in dataD - RUNNER_ASSERT(BinaryQueueToString(dataD) == testData); -} diff --git a/tests/dpl/unused/test_shm.cpp b/tests/dpl/unused/test_shm.cpp deleted file mode 100644 index 4f2d93a..0000000 --- a/tests/dpl/unused/test_shm.cpp +++ /dev/null @@ -1,1664 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_shm.h - * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) - * @version 1.0 - * @brief Implementation file for test cases for shared data framework - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL) - -using namespace DPL; - -namespace { -const SharedMemory::Key SHM_KEY = 12345; -const char* SEM_NAME = "/wrt_engine_shared_object_semaphore"; -const size_t VERSION = 1; - -const size_t MAX_THREADS = 10; -const size_t TEST_AND_SET_REPEATS = 100; - -const size_t SHARED_PROP_REPEATS = 3; - -const size_t SINGLETON_TEST_REPEATS = 3; - -// maximum random delay in singleton listener addition/removal -const size_t MAX_SINGLETON_LISTENER_DELAY = 50; - -const int SINGLE_PROCESS_REPEATS = 50; - -/* - * 5 seconds expected timeout for waitable events - * 30 seconds unexpected timeout for waitable events - * We don't want to block tests - */ -const size_t EXPECTED_WAITABLE_TIMEOUT = 5 * 1000; -const size_t UNEXPECTED_WAITABLE_TIMEOUT = 30 * 1000; - -bool g_enumTestCorrect = false; -bool g_enumTestIncorrect = false; -size_t g_delegateCalls = 0; - -void Wait(DPL::WaitableEvent& event, bool expectedTimeout = false) -{ - LogDebug("WaitForSingleHandle..."); - DPL::WaitableHandleIndexList list = DPL::WaitForSingleHandle( - event.GetHandle(), - expectedTimeout ? - EXPECTED_WAITABLE_TIMEOUT : UNEXPECTED_WAITABLE_TIMEOUT); - if (list.size() == 0) { - LogDebug("...timeout."); - } else { - LogDebug("...signaled."); - event.Reset(); - } - - if (expectedTimeout) { - RUNNER_ASSERT(list.size() == 0); - } else { - RUNNER_ASSERT(list.size() == 1); - } -} - -void RemoveIpcs() -{ - Try { - SharedMemory::Remove(SHM_KEY); - } - Catch(SharedMemory::Exception::RemoveFailed) { - // ignore - } - - Try { - DPL::Semaphore::Remove(SEM_NAME); - } - Catch(DPL::Semaphore::Exception::RemoveFailed) { - // ignore - } -} - -typedef DPL::TypeListDecl::Type TestTypeList; -typedef DPL::TypeListDecl::Type TestTypeList2; -typedef DPL::TypeListDecl::Type TestTypeList3; - -typedef SharedObject TestSharedObject; -typedef SharedObject TestSharedObject2; -typedef SharedObject TestSharedObject3; - -typedef std::shared_ptr TestSharedObjectPtr; - -const int INIT_EVENT = 0; -const int DESTROY_EVENT = 1; - -int g_values[TestTypeList::Size]; - -/* - * helper listening controller - */ -template -class ListeningController : - public DPL::Controller::Type> -{ - public: - explicit ListeningController(DPL::WaitableEvent* waitable); - ~ListeningController(); - - virtual void OnEventReceived(const int &event); - - virtual void OnEvent(const int /*event*/) {} - - protected: - std::shared_ptr m_so; - DPL::Thread m_thread; - DPL::WaitableEvent* m_waitable; -}; - -template -ListeningController::ListeningController( - DPL::WaitableEvent* waitable) : - m_waitable(waitable) -{ - Touch(); - m_thread.Run(); - SwitchToThread(&m_thread); - PostEvent(INIT_EVENT); -} - -template -ListeningController::~ListeningController() -{ - m_thread.Quit(); -} - -template -void ListeningController::OnEventReceived(const int& event) -{ - if (event == INIT_EVENT) { - m_so = SharedObjectFactory::Create(SHM_KEY, SEM_NAME); - OnEvent(event); - m_waitable->Signal(); - } else if (event == DESTROY_EVENT) { - LogDebug("Destroying shared object"); - OnEvent(event); - - // deregister, destroy ad notify main thread - m_so.Reset(); - LogDebug("4"); - m_waitable->Signal(); - LogDebug("5"); - } else { - OnEvent(event); - } -} - -typedef DPL::TypeListDecl::Type SharedTypeList; - -class TestSharedObject4; -typedef std::shared_ptr TestSharedObject4Ptr; - -class TestSharedObject4 : public SharedObject -{ - public: - enum - { - SIZE_T, - BOOLEAN - }; - - static TestSharedObject4Ptr Create() - { - return SharedObjectFactory::Create(SHM_KEY, SEM_NAME); - } - - ~TestSharedObject4() - { - LogDebug("dtor"); - } - - protected: - explicit TestSharedObject4(const std::string& semaphore) : - SharedObject(semaphore) - {} - - private: - void Init() - { - SetPropertyInternal(false); - } - friend class SharedObjectFactory; -}; -} // anonymus namespace - -////////////////////////////////////////////// - -RUNNER_TEST(SharedMemory_002_AccessByType) -{ - RemoveIpcs(); - - SharedData str; - - // access by type - str.Embedded<0, int>::value = 4; - str.Embedded<1, int>::value = 5; - str.Embedded<2, char>::value = 'd'; - str.Embedded<3, int[64]>::value[0] = 1; - str.Embedded<3, int[64]>::value[1] = 20; - - RUNNER_ASSERT((str.Embedded<0, int>::value) == 4); - RUNNER_ASSERT((str.Embedded<1, int>::value) == 5); - RUNNER_ASSERT((str.Embedded<2, char>::value) == 'd'); - RUNNER_ASSERT((str.Embedded<3, int[64]>::value[0]) == 1); - RUNNER_ASSERT((str.Embedded<3, int[64]>::value[1]) == 20); -} - -////////////////////////////////////////////// - -RUNNER_TEST(SharedMemory_003_AccessByIndex) -{ - RemoveIpcs(); - - SharedData str; - // access by enum - str.Embedded<0, TestTypeList::Element<0>::Type>::value = 4; - str.Embedded<1, TestTypeList::Element<1>::Type>::value = 5; - str.Embedded<2, TestTypeList::Element<2>::Type>::value = 'd'; - str.Embedded<3, TestTypeList::Element<3>::Type>::value[0] = 1; - str.Embedded<3, TestTypeList::Element<3>::Type>::value[1] = 20; - - RUNNER_ASSERT( - (str.Embedded<0, TestTypeList::Element<0>::Type>::value) == 4); - RUNNER_ASSERT( - (str.Embedded<1, TestTypeList::Element<1>::Type>::value) == 5); - RUNNER_ASSERT( - (str.Embedded<2, TestTypeList::Element<2>::Type>::value) == 'd'); - RUNNER_ASSERT( - (str.Embedded<3, TestTypeList::Element<3>::Type>::value[0]) == 1); - RUNNER_ASSERT( - (str.Embedded<3, TestTypeList::Element<3>::Type>::value[1]) == 20); -} - -////////////////////////////////////////////// - -RUNNER_TEST(SharedMemory_004_SimplifiedAccess) -{ - RemoveIpcs(); - - SharedData str; - - // access via PropertyRef - str.PropertyRef<1>() = 3; - RUNNER_ASSERT(str.PropertyRef<1>() == 3); - - int (&array)[64] = str.PropertyRef<3>(); - array[0] = 2; - RUNNER_ASSERT(str.PropertyRef<3>()[0] == 2); - - str.PropertyRef<3>()[1] = 19; - RUNNER_ASSERT(str.PropertyRef<3>()[1] == 19); - - // access via macro - str.SHARED_PROPERTY(0) = 2; - RUNNER_ASSERT(str.SHARED_PROPERTY(0) == 2); - - str.SHARED_PROPERTY(2) = 'c'; - RUNNER_ASSERT(str.SHARED_PROPERTY(2) == 'c'); - - str.SHARED_PROPERTY(3)[2] = 10; - RUNNER_ASSERT(str.SHARED_PROPERTY(3)[2] == 10); - - // old style check - RUNNER_ASSERT((str.Embedded<0, int>::value) == 2); - RUNNER_ASSERT((str.Embedded<1, int>::value) == 3); - RUNNER_ASSERT((str.Embedded<2, char>::value) == 'c'); - RUNNER_ASSERT((str.Embedded<3, int[64]>::value[0]) == 2); - RUNNER_ASSERT((str.Embedded<3, int[64]>::value[1]) == 19); - RUNNER_ASSERT((str.Embedded<3, int[64]>::value[2]) == 10); -} - -////////////////////////////////////////////// - -struct SharedStruct -{ - int a; - int b; - char c; - int d[64]; -}; - -typedef std::shared_ptr > SharedStructPtr; - -RUNNER_TEST(SharedMemory_010_BaseShmTest) -{ - RemoveIpcs(); - - typedef std::unique_ptr SharedMemoryPtr; - - // write - SharedMemoryPtr shm; - Try { - shm.Reset(SharedMemory::Create(SHM_KEY, false)); - } - Catch(SharedMemory::Exception::NotFound) { - shm.Reset(SharedMemory::Create(SHM_KEY, true, true)); - } - - SharedStructPtr str = shm->Attach(); - - str->Data()->a = 1; - str->Data()->b = 2; - str->Data()->c = '3'; - str->Data()->d[0] = 4; - str->Data()->d[1] = 5; - - // read - SharedMemoryPtr shm2; - Try { - shm2.Reset(SharedMemory::Create(SHM_KEY, false)); - } - Catch(SharedMemory::Exception::NotFound) { - shm2.Reset(SharedMemory::Create(SHM_KEY, true, true)); - } - - SharedStructPtr str2 = shm2->Attach(); - SharedStructPtr str3 = shm2->Attach(); - - RUNNER_ASSERT(str2->Data()->a == 1); - RUNNER_ASSERT(str2->Data()->b == 2); - RUNNER_ASSERT(str2->Data()->c == '3'); - RUNNER_ASSERT(str2->Data()->d[0] == 4); - RUNNER_ASSERT(str2->Data()->d[1] == 5); - - RUNNER_ASSERT(str3->Data()->a == 1); - RUNNER_ASSERT(str3->Data()->b == 2); - RUNNER_ASSERT(str3->Data()->c == '3'); - RUNNER_ASSERT(str3->Data()->d[0] == 4); - RUNNER_ASSERT(str3->Data()->d[1] == 5); - - str2->Data()->b = 4; - str2->Data()->c = 'c'; - str2->Data()->d[0] = 0; - RUNNER_ASSERT(str3->Data()->a == 1); - RUNNER_ASSERT(str3->Data()->b == 4); - RUNNER_ASSERT(str3->Data()->c == 'c'); - RUNNER_ASSERT(str3->Data()->d[0] == 0); - RUNNER_ASSERT(str3->Data()->d[1] == 5); -} - -////////////////////////////////////////////// - -RUNNER_TEST(SharedMemory_020_SharedObjectTest) -{ - RemoveIpcs(); - - typedef SharedObject MySharedObj; - - MySharedObj::Ptr so = - SharedObjectFactory::Create(SHM_KEY, SEM_NAME); - - RUNNER_ASSERT((so->GetProperty<0, size_t>()) == 0); - so->SetProperty<0, size_t>(4); - RUNNER_ASSERT((so->GetProperty<0, size_t>()) == 4); -} - -////////////////////////////////////////////// - -class InitTestSharedObject : public TestSharedObject -{ - protected: - explicit InitTestSharedObject(const std::string& semaphore) : - TestSharedObject(semaphore) {} - - virtual void Init(); // from SharedObject - - private: - friend class SharedObjectFactory; -}; - -void InitTestSharedObject::Init() -{ - SetPropertyInternal<0>(1); - SetPropertyInternal<1>(2); - SetPropertyInternal<2>('c'); -} - -RUNNER_TEST(SharedMemory_021_InitTest) -{ - RemoveIpcs(); // we need non existing shm - - std::shared_ptr sho = - SharedObjectFactory::Create( - SHM_KEY, SEM_NAME); - RUNNER_ASSERT((sho->GetProperty<0, int>()) == 1); - RUNNER_ASSERT((sho->GetProperty<1, int>()) == 2); - RUNNER_ASSERT((sho->GetProperty<2, char>()) == 'c'); -} - -////////////////////////////////////////////// - -class VersionTestSO1 : public TestSharedObject -{ - protected: - explicit VersionTestSO1(const std::string& semaphore) : - TestSharedObject(semaphore) {} - - virtual SizeType GetVersion() const - { - return 1; - } // from SharedObject - - private: - friend class SharedObjectFactory; -}; - -class VersionTestSO2 : public TestSharedObject -{ - protected: - explicit VersionTestSO2(const std::string& semaphore) : - TestSharedObject(semaphore) {} - - virtual SizeType GetVersion() const - { - return 2; - } // from SharedObject - - private: - friend class SharedObjectFactory; -}; - -RUNNER_TEST(SharedMemory_022_InvalidVersionTest) -{ - RemoveIpcs(); // we need non existing shm - - std::shared_ptr sho = - SharedObjectFactory::Create(SHM_KEY, SEM_NAME); - - Try { - std::shared_ptr sho2 = - SharedObjectFactory::Create(SHM_KEY, SEM_NAME); - - RUNNER_ASSERT_MSG(false, "Invalid shm version has been accepted"); - } - Catch(SharedObjectBase::Exception::InvalidVersion) { - RUNNER_ASSERT(true); - } -} - -////////////////////////////////////////////// - -RUNNER_TEST(SharedMemory_023_InvalidSizeTest) -{ - RemoveIpcs(); // we need non existing shm - - typedef SharedObject SO1; - typedef SharedObject SO2; - - SO1::Ptr sho = SharedObjectFactory::Create(SHM_KEY, SEM_NAME); - - Try { - SO2::Ptr sho2 = SharedObjectFactory::Create(SHM_KEY, SEM_NAME); - - RUNNER_ASSERT_MSG(false, "Invalid shm size has been accepted"); - } - Catch(SharedObjectBase::Exception::InvalidSize) { - RUNNER_ASSERT(true); - } -} - -////////////////////////////////////////////// - -class MagicTestSO1 : public TestSharedObject -{ - protected: - explicit MagicTestSO1(const std::string& semaphore) : - TestSharedObject(semaphore) {} - - // from SharedObject - virtual MagicType GetMagicNumber() const - { - return 661; - } - - private: - friend class SharedObjectFactory; -}; - -class MagicTestSO2 : public TestSharedObject -{ - protected: - explicit MagicTestSO2(const std::string& semaphore) : - TestSharedObject(semaphore) {} - - // from SharedObject - virtual MagicType GetMagicNumber() const - { - return 662; - } - - private: - friend class SharedObjectFactory; -}; - -RUNNER_TEST(SharedMemory_024_InvalidMagicTest) -{ - RemoveIpcs(); // we need non existing shm - - std::shared_ptr sho = - SharedObjectFactory::Create(SHM_KEY, SEM_NAME); - - Try { - std::shared_ptr sho2 = - SharedObjectFactory::Create(SHM_KEY, SEM_NAME); - - RUNNER_ASSERT_MSG(false, "Invalid shm magic number has been accepted"); - } - Catch(SharedObjectBase::Exception::InvalidMagicNumber) { - RUNNER_ASSERT(true); - } -} - -////////////////////////////////////////////// - -/* - * Listening shared object - */ -class EnumTestSO1 : public TestSharedObject -{ - public: - void SetWaitable(DPL::WaitableEvent* waitable) - { - m_waitable = waitable; - } - - protected: - explicit EnumTestSO1(const std::string& semaphore) : - TestSharedObject(semaphore) {} - - virtual void PropertyChanged(size_t propertyEnum); - - private: - friend class SharedObjectFactory; - - DPL::WaitableEvent* m_waitable; -}; - -void EnumTestSO1::PropertyChanged(size_t propertyEnum) -{ - if (propertyEnum == 1) { - LogDebug("Property enum " << propertyEnum << " correctly set"); - g_enumTestCorrect = true; - } - if (propertyEnum == 4) { - // This is bad. We only have 4 types - LogError("Property enum " << propertyEnum << " should be skipped"); - g_enumTestIncorrect = true; - } - // confirm property change notification - m_waitable->Signal(); -} - -class EnumController : public ListeningController -{ - public: - explicit EnumController(DPL::WaitableEvent* waitable) : - ListeningController(waitable) {} - - virtual void OnEvent(const int event); -}; - -void EnumController::OnEvent(const int event) -{ - if (event == INIT_EVENT) { - m_so->SetWaitable(m_waitable); - } -} - -/* - * Writing shared object with correct size but different number of types - */ -class EnumTestSO2 : public TestSharedObject3 -{ - protected: - explicit EnumTestSO2(const std::string& semaphore) : - TestSharedObject3(semaphore) {} - - private: - friend class SharedObjectFactory; -}; - -RUNNER_TEST(SharedMemory_025_InvalidEnumTest) -{ - RemoveIpcs(); // we need non existing shm - - g_enumTestCorrect = false; - g_enumTestIncorrect = false; - - DPL::WaitableEvent waitable; - - // create listening controller and wait until it registers - EnumController controller(&waitable); - Wait(waitable); - LogDebug("Listening controller created"); - - // create writing shared object - std::shared_ptr sho2 = - SharedObjectFactory::Create(SHM_KEY, SEM_NAME); - DPL::WaitableHandleIndexList list; - - // write property and wait for confirmation - sho2->SetProperty<1>(2); - Wait(waitable); - - // write incorrect property and wait for confirmation - // we expect timeout - sho2->SetProperty<4>(2); - Wait(waitable, true); - - // schedule listener deregistration and wait for confirmation - controller.PostEvent(DESTROY_EVENT); - Wait(waitable); - - // check results - RUNNER_ASSERT(g_enumTestCorrect == true); - RUNNER_ASSERT(g_enumTestIncorrect == false); -} - -////////////////////////////////////////////// - -class MultiThreadSO : public TestSharedObject -{ - public: - void TestAndSetProperty(); - - protected: - explicit MultiThreadSO(const std::string& semaphore) : - TestSharedObject(semaphore) {} - - private: - friend class SharedObjectFactory; -}; - -void MultiThreadSO::TestAndSetProperty() -{ - ScopedFlaggedLock lock(*this); - - int value = PropertyRef<0, int>(); - DPL::Thread::MicroSleep(100); - SetPropertyInternal<0>(value + 1); -} - -class ShmController : public ListeningController -{ - public: - explicit ShmController(DPL::WaitableEvent* event) : - ListeningController(event), m_counter(0) - {} - - virtual void OnEventReceived(const int& event); - - private: - size_t m_counter; -}; - -void ShmController::OnEventReceived(const int& event) -{ - if (event == INIT_EVENT) { - m_so = SharedObjectFactory::Create(SHM_KEY, SEM_NAME); - PostEvent(2); - } else if (event == DESTROY_EVENT) { - LogDebug("Destroying shared object"); - // deregister, destroy ad notify main thread - m_so.Reset(); - m_waitable->Signal(); - } else if (event == 2) { - m_so->TestAndSetProperty(); - m_counter++; - if (m_counter >= TEST_AND_SET_REPEATS) { - LogDebug("Max tests reached. Finishing thread"); - PostEvent(DESTROY_EVENT); - return; - } - PostEvent(2); - } -} - -RUNNER_TEST(SharedMemory_030_MultithreadTest) -{ - RemoveIpcs(); // we need non existing shm - - typedef SharedObject SHO; - SHO::Ptr sho = SharedObjectFactory::Create(SHM_KEY, SEM_NAME); - - ShmController* controller[MAX_THREADS]; - DPL::WaitableEvent finalEvent[MAX_THREADS]; - - for (size_t i = 0; i < MAX_THREADS; ++i) { - controller[i] = new ShmController(&finalEvent[i]); - } - - for (size_t i = 0; i < MAX_THREADS; ++i) { - Wait(finalEvent[i]); - } - - for (size_t i = 0; i < MAX_THREADS; ++i) { - delete controller[i]; - controller[i] = NULL; - } - - int value = sho->GetProperty<0, int>(); - LogDebug("Final value is " << value << ", expected " << - MAX_THREADS * TEST_AND_SET_REPEATS); - RUNNER_ASSERT(value == MAX_THREADS * TEST_AND_SET_REPEATS); -} - -////////////////////////////////////////////// - -class MyModel10 : public DPL::Model -{ - public: - explicit MyModel10(const TestSharedObject4Ptr& shared_object) : - DPL::Model(), boolValue(this, shared_object) {} - - SharedProperty - boolValue; -}; - -/* - * Listening controller - */ -class ShmController3 : public ListeningController -{ - public: - explicit ShmController3(DPL::WaitableEvent* event) : - ListeningController(event) - {} - - virtual void OnEvent(const int event); - - void OnValueChanged(const DPL::PropertyEvent& event); - - private: - typedef std::unique_ptr MyModelPtr; - - // model with property bound to shared object - MyModelPtr m_model; -}; - -void ShmController3::OnEvent(const int event) -{ - if (event == INIT_EVENT) { - m_model.Reset(new MyModel10(m_so)); - m_model->boolValue.AddListener( - DPL::FastDelegate&)>( - this, - &ShmController3::OnValueChanged)); - } else if (event == DESTROY_EVENT) { - m_model->boolValue.RemoveListener( - DPL::FastDelegate&)>( - this, - &ShmController3::OnValueChanged)); - m_model.Reset(); - } -} - -void ShmController3::OnValueChanged(const DPL::PropertyEvent& event) -{ - if (event.value) { - // change back - m_model->boolValue.Set(false); - } else { - LogError("Expected value = true, got false"); - } - - m_waitable->Signal(); -} - -RUNNER_TEST(SharedMemory_050_SharedProperty) -{ - RemoveIpcs(); - - bool result = true; - DPL::WaitableEvent waitable; - // listener controller - ShmController3 controller(&waitable); - Wait(waitable); - - TestSharedObject4Ptr sharedObject = TestSharedObject4::Create(); - - for (size_t i = 0; i < SHARED_PROP_REPEATS; ++i) { - sharedObject->SetProperty(true); - Wait(waitable); - result = sharedObject->GetProperty(); - RUNNER_ASSERT(result == false); - } - controller.PostEvent(DESTROY_EVENT); - Wait(waitable); -} - -////////////////////////////////////////////// - -class MyModel2 : public DPL::Model -{ - public: - explicit MyModel2(const TestSharedObjectPtr& shared_object) : - counter(this, shared_object) {} - - SharedProperty counter; -}; - -class SPController : public ListeningController -{ - public: - explicit SPController(DPL::WaitableEvent* event) : - ListeningController(event), m_repeats(1) {} - - virtual void OnEvent(const int event); - - void OnValueChanged1(const DPL::PropertyEvent& event); - void OnValueChanged2(const DPL::PropertyEvent& event); - - private: - std::unique_ptr m_model1; - std::unique_ptr m_model2; - - int m_repeats; - std::shared_ptr m_so2; -}; - -void SPController::OnEvent(const int event) -{ - if (event == INIT_EVENT) { - m_so2 = SharedObjectFactory::Create(SHM_KEY, - SEM_NAME); - - // create and register 2 models sharing the same property - m_model1.Reset(new MyModel2(m_so)); - m_model2.Reset(new MyModel2(m_so2)); - m_model1->counter.AddListener( - DPL::FastDelegate&)>( - this, - &SPController::OnValueChanged1)); - m_model2->counter.AddListener( - DPL::FastDelegate&)>( - this, - &SPController::OnValueChanged2)); - m_model1->counter.Set(1); - } else if (event == DESTROY_EVENT) { - m_model1->counter.RemoveListener( - DPL::FastDelegate&)>( - this, - &SPController::OnValueChanged1)); - m_model2->counter.RemoveListener( - DPL::FastDelegate&)>( - this, - &SPController::OnValueChanged2)); - - m_model1.Reset(); - m_model2.Reset(); - m_so2.Reset(); - } -} - -void SPController::OnValueChanged1(const DPL::PropertyEvent& event) -{ - if (m_repeats >= SINGLE_PROCESS_REPEATS) { - PostEvent(DESTROY_EVENT); - return; - } - - LogDebug("[1] Value changed to " << event.value); - m_repeats++; - m_model1->counter.Set(event.value + 1); -} - -void SPController::OnValueChanged2(const DPL::PropertyEvent& event) -{ - if (m_repeats >= SINGLE_PROCESS_REPEATS) { - PostEvent(DESTROY_EVENT); - return; - } - - LogDebug("[2] Value changed to " << event.value); - m_repeats++; - m_model2->counter.Set(event.value + 1); -} - -RUNNER_TEST(SharedMemory_060_SingleProcess) -{ - RemoveIpcs(); - - DPL::WaitableEvent waitable; - SPController controller(&waitable); - TestSharedObjectPtr sho = SharedObjectFactory::Create( - SHM_KEY, - SEM_NAME); - - // wait for creation - Wait(waitable); - - // wait for destruction - Wait(waitable); - - int value = sho->GetProperty<0, int>(); - - LogDebug("final value: " << value); - - // check value - RUNNER_ASSERT(value == SINGLE_PROCESS_REPEATS); -} - -////////////////////////////////////////////// - -class ListenerTestController : public ListeningController, - public ISharedObjectListener<0, int>, - public ISharedObjectListener<1, int>, - public ISharedObjectListener<2, char>, - public ISharedObjectListener<3, int[64]> -{ - public: - explicit ListenerTestController(DPL::WaitableEvent* event) : - ListeningController(event) {} - - ~ListenerTestController(); - - virtual void OnEvent(const int event); - - virtual void ValueChanged(size_t propertyEnum, - const int& value, - const void* info = NULL); - virtual void ValueChanged(size_t propertyEnum, - const char& value, - const void* info = NULL); - virtual void ValueChanged(size_t propertyEnum, - const int(&value)[64], - const void* info = NULL); -}; - -ListenerTestController::~ListenerTestController() -{} - -void ListenerTestController::OnEvent(const int event) -{ - if (event == INIT_EVENT) { - // add self as a listener to shared object - m_so->AddListener<0, int>(this); - m_so->AddListener<1, int>(this); - m_so->AddListener<2, char>(this); - m_so->AddListener<3, int[64]>(this); - } else if (event == DESTROY_EVENT) { - // remove self from listener list - m_so->RemoveListener<0, int>(this); - m_so->RemoveListener<1, int>(this); - m_so->RemoveListener<2, char>(this); - m_so->RemoveListener<3, int[64]>(this); - } -} - -void ListenerTestController::ValueChanged(size_t propertyEnum, - const int& value, - const void* /*info*/) -{ - LogDebug("ValueChanged(int) " << propertyEnum << " " << value); - if ((propertyEnum == 0 && - value == 1) || (propertyEnum == 1 && value == 2)) - { - g_values[propertyEnum]++; - if (g_values[propertyEnum] == 3) { - m_waitable->Signal(); - } - } -} - -void ListenerTestController::ValueChanged(size_t propertyEnum, - const char& value, - const void* /*info*/) -{ - LogDebug("ValueChanged(char) " << propertyEnum << " " << value); - if (propertyEnum == 2 && value == 'c') { - g_values[propertyEnum]++; - if (g_values[propertyEnum] == 3) { - m_waitable->Signal(); - } - } -} - -void ListenerTestController::ValueChanged(size_t propertyEnum, - const int(&value)[64], - const void* /*info*/) -{ - LogDebug("ValueChanged(int[64]) " << propertyEnum << " " << value[5]); - if (propertyEnum == 3 && value[5] == 5) { - g_values[propertyEnum]++; - if (g_values[propertyEnum] == 3) { - m_waitable->Signal(); - } - } -} - -RUNNER_TEST(SharedMemory_070_SharedObjectListeners) -{ - RemoveIpcs(); - - // setup global flags - for (size_t i = 0; i < TestTypeList::Size; ++i) { - g_values[i] = 0; - } - - // create shared object - TestSharedObjectPtr sho = SharedObjectFactory::Create( - SHM_KEY, SEM_NAME); - - // create 1st listener and wait for it - DPL::WaitableEvent waitable; - ListenerTestController c1(&waitable); - Wait(waitable); - - // create 2nd listener and wait for it - ListenerTestController c2(&waitable); - Wait(waitable); - - // create 3rd listener and wait for it - ListenerTestController c3(&waitable); - Wait(waitable); - - // set properties and wait for result - sho->SetProperty<0, int>(1); - Wait(waitable); - - RUNNER_ASSERT(g_values[0] == 3); - - sho->SetProperty<1, int>(2); - Wait(waitable); - - RUNNER_ASSERT(g_values[1] == 3); - - sho->SetProperty<2, char>('c'); - Wait(waitable); - - RUNNER_ASSERT(g_values[2] == 3); - - int array[64]; - memset(array, 64 * sizeof(array[0]), 0); - array[5] = 5; - sho->SetProperty<3, int[64]>(array); - Wait(waitable); - - RUNNER_ASSERT(g_values[3] == 3); - - // finalize listeners - c1.PostEvent(DESTROY_EVENT); - Wait(waitable); - - c2.PostEvent(DESTROY_EVENT); - Wait(waitable); - - c3.PostEvent(DESTROY_EVENT); - Wait(waitable); -} - -////////////////////////////////////////////// - -/* - * class simulating DB access - */ -class DAO : public DPL::Noncopyable -{ - public: - DAO() : m_boolValue(false) {} - - void SetBoolValue(const bool& value) - { - m_boolValue = value; - } - - bool GetBoolValue() const - { - return m_boolValue; - } - - private: - bool m_boolValue; -}; - -/* - * Model with property having set delegate defined - */ -class MyModel3 : public DPL::Model -{ - public: - typedef SharedPropertyEx PropertyType; - - MyModel3(const TestSharedObject4Ptr& shared_object, DAO* dao) : - boolValue(this, - shared_object, - PropertyType::SetDelegate(dao, &DAO::SetBoolValue)) - {} - - PropertyType boolValue; -}; - -RUNNER_TEST(SharedMemory_090_SetPropertyDelegate) -{ - RemoveIpcs(); - - // dao object - DAO dao; - - // create shared object - TestSharedObject4Ptr sho = TestSharedObject4::Create(); - - // set property but call dao delegate within semaphore - sho->SetProperty( - true, - MyModel3::PropertyType::SetDelegate(&dao, &DAO::SetBoolValue)); - - // check dao value - RUNNER_ASSERT(dao.GetBoolValue() == true); - - // check shared object value - bool shoValue = sho->GetProperty(); - RUNNER_ASSERT(shoValue == true); - - // try the same with shared property - MyModel3 model(sho, &dao); - - // set property - model.boolValue.Set(false); - - // check dao value - RUNNER_ASSERT(dao.GetBoolValue() == false); - - // check sho value - shoValue = sho->GetProperty(); - RUNNER_ASSERT(shoValue == false); - - // check property value - RUNNER_ASSERT(model.boolValue.Get() == false); -} - -////////////////////////////////////////////// - -/* - * Lazy initialization test shared object - */ -class LazySharedObject : public SharedObject -{ - public: - explicit LazySharedObject(const std::string& semaphore) : - SharedObject(semaphore) - , m_read(false) - {} - - void Init(); - - bool IsRead() const - { - return m_read; - } - - private: - friend class SharedObjectFactory; - - bool m_read; -}; - -void LazySharedObject::Init() -{ - SetPropertyInternal<0>(42); - m_read = true; -} - -RUNNER_TEST(SharedMemory_100_LazyInit) -{ - RemoveIpcs(); - - typedef std::shared_ptr LazySharedObjectPtr; - - // create shared object - LazySharedObjectPtr sho = SharedObjectFactory::Create( - SHM_KEY, SEM_NAME); - - RUNNER_ASSERT(sho->IsRead() == false); - - // get property causing lazy init - int value = sho->GetProperty<0, int>(); - - RUNNER_ASSERT(sho->IsRead() == true); - RUNNER_ASSERT(value == 42); - - // create another object - LazySharedObjectPtr sho2 = SharedObjectFactory::Create( - SHM_KEY, SEM_NAME); - - RUNNER_ASSERT(sho2->IsRead() == false); - - // get property NOT causing lazy init - value = sho2->GetProperty<0, int>(); - - RUNNER_ASSERT(sho2->IsRead() == false); - RUNNER_ASSERT(value == 42); - - // destroy both objects - sho.Reset(); - sho2.Reset(); - - // create shared object - LazySharedObjectPtr sho3 = SharedObjectFactory::Create( - SHM_KEY, SEM_NAME); - - RUNNER_ASSERT(sho3->IsRead() == false); - - // set property causing lazy init - sho3->SetProperty<0>(43); - value = sho3->GetProperty<0, int>(); - - RUNNER_ASSERT(sho3->IsRead() == true); - RUNNER_ASSERT(value == 43); -} - -////////////////////////////////////////////// - -bool SetCondition(const int& readValue, int& setValue); -bool SetCondition(const int& readValue, int& setValue) -{ - LogDebug("Condition delegate called with read value = " << readValue << - " and set value = " << setValue); - - if (readValue > 3) { - LogDebug("Condition is false"); - return false; - } - - LogDebug("Condition is true"); - if (4 == setValue) { - setValue = 10; - LogDebug("Changing set value to " << setValue); - } - return true; -} - -void SetDelegate(const int& readValue); -void SetDelegate(const int& readValue) -{ - LogDebug("Set delegate called " << readValue); - g_delegateCalls++; -} - -RUNNER_TEST(SharedMemory_120_ConditionalSet) -{ - RemoveIpcs(); - - TestSharedObjectPtr sho = SharedObjectFactory::Create( - SHM_KEY, - SEM_NAME); - - g_delegateCalls = 0; - - RUNNER_ASSERT(0 == (sho->GetProperty<0, int>())); - - DPL::FastDelegate condition(&SetCondition); - DPL::FastDelegate delegate(&SetDelegate); - - bool succeeded = false; - - succeeded = sho->ConditionalSetProperty<0>(-2, condition); - - RUNNER_ASSERT(succeeded); - RUNNER_ASSERT(-2 == (sho->GetProperty<0, int>())); - - succeeded = sho->ConditionalSetProperty<0>(4, condition, delegate); - - RUNNER_ASSERT(succeeded); - RUNNER_ASSERT(10 == (sho->GetProperty<0, int>())); - RUNNER_ASSERT(1 == g_delegateCalls); - - succeeded = sho->ConditionalSetProperty<0>(5, condition); - - RUNNER_ASSERT(!succeeded); - RUNNER_ASSERT(10 == (sho->GetProperty<0, int>())); - - succeeded = sho->ConditionalSetProperty<0>(666, condition, delegate); - - RUNNER_ASSERT(!succeeded); - RUNNER_ASSERT(10 == (sho->GetProperty<0, int>())); - RUNNER_ASSERT(1 == g_delegateCalls); -} - -////////////////////////////////////////////// - -/* - * Shared object used by multiple threads as a singleton. - */ -class MTSharedObject : public SharedObject -{ - public: - explicit MTSharedObject(const std::string& semaphore) : - SharedObject(semaphore) - {} - - void Clear(); - - private: - friend class SharedObjectFactory; -}; - -typedef std::shared_ptr MTSharedObjectPtr; - -void MTSharedObject::Clear() -{ - int array[64] = {}; - SetProperty<0>(0); - SetProperty<1>(0); - SetProperty<2>(static_cast(0)); - SetProperty<3>(array); -} - -/* - * Shared object singleton - */ -class SharedObjectSingleton -{ - public: - static MTSharedObjectPtr Instance(); - static void Destroy(); - - private: - static MTSharedObjectPtr m_sho; - static DPL::Mutex m_mutex; -}; - -MTSharedObjectPtr SharedObjectSingleton::m_sho; -DPL::Mutex SharedObjectSingleton::m_mutex; - -MTSharedObjectPtr SharedObjectSingleton::Instance() -{ - DPL::Mutex::ScopedLock lock(&m_mutex); - if (!m_sho) { - m_sho = SharedObjectFactory::Create(SHM_KEY, SEM_NAME); - } - return m_sho; -} - -void SharedObjectSingleton::Destroy() -{ - DPL::Mutex::ScopedLock lock(&m_mutex); - m_sho.Reset(); -} - -/* - * Listening controller - */ -class ShmController4 : public ListeningController, - public ISharedObjectListener<0, int>, - public ISharedObjectListener<1, int>, - public ISharedObjectListener<2, char>, - public ISharedObjectListener<3, int[64]> -{ - public: - enum { - ADD_LISTENERS = 2, - REMOVE_LISTENERS = 3, - DESTROY_SINGLETON = 4 - }; - - explicit ShmController4(DPL::WaitableEvent* event) : - ListeningController(event) - {} - - virtual void OnEventReceived(const int& event); - - virtual void ValueChanged(size_t propertyEnum, - const int& value, - const void* info = NULL); - virtual void ValueChanged(size_t propertyEnum, - const char& value, - const void* info = NULL); - virtual void ValueChanged(size_t propertyEnum, - const int(&value)[64], - const void* info = NULL); - - bool NotRegistered(); - - private: - void Sleep(); - - size_t m_counter; -}; - -void ShmController4::ValueChanged(size_t propertyEnum, - const int& value, - const void* /*info*/) -{ - LogDebug("ValueChanged(int) " << propertyEnum << " " << value); - if ((propertyEnum == 0 && value == 1) || - (propertyEnum == 1 && value == 11)) - { - m_waitable->Signal(); - } -} - -void ShmController4::ValueChanged(size_t propertyEnum, - const char& value, - const void* /*info*/) -{ - LogDebug("ValueChanged(char) " << propertyEnum << " " << value); - if (propertyEnum == 2 && value == 'a') { - m_waitable->Signal(); - } -} - -void ShmController4::ValueChanged(size_t propertyEnum, - const int(&value)[64], - const void* /*info*/) -{ - LogDebug("ValueChanged(int[64]) " << propertyEnum << " " << value[5]); - if (propertyEnum == 3 && value[0] == 0 && value[1] == 1 && value[2] == 2) { - m_waitable->Signal(); - } -} - -void ShmController4::Sleep() -{ - DPL::Thread::GetCurrentThread()->MiliSleep( - rand() % MAX_SINGLETON_LISTENER_DELAY); -} - -void ShmController4::OnEventReceived(const int& event) -{ - switch (event) { - case INIT_EVENT: - m_so = SharedObjectSingleton::Instance(); - m_waitable->Signal(); - break; - - case DESTROY_EVENT: - LogDebug("Destroying shared object"); - // deregister, destroy and notify main thread - m_so.Reset(); - m_waitable->Signal(); - break; - - case ADD_LISTENERS: - // add listener and notify - m_so->AddListener<0, int>(this); - Sleep(); - m_so->AddListener<1, int>(this); - Sleep(); - m_so->AddListener<2, char>(this); - Sleep(); - m_so->AddListener<3, int[64]>(this); - Sleep(); - m_waitable->Signal(); - break; - - case REMOVE_LISTENERS: - // remove listener and notify - m_so->RemoveListener<0, int>(this); - Sleep(); - m_so->RemoveListener<1, int>(this); - Sleep(); - m_so->RemoveListener<2, char>(this); - Sleep(); - m_so->RemoveListener<3, int[64]>(this); - Sleep(); - m_waitable->Signal(); - break; - - case DESTROY_SINGLETON: - SharedObjectSingleton::Destroy(); - m_waitable->Signal(); - break; - - default: - LogError("Unsupported event received: " << event); - } -} - -void MultipleWait(DPL::WaitableEvent(&event)[MAX_THREADS]); -void MultipleWait(DPL::WaitableEvent(&event)[MAX_THREADS]) -{ - for (size_t i = 0; i < MAX_THREADS; ++i) { - Wait(event[i]); - } -} - -/* - * Try to remove property listener. If there's no such listener an exception - * should be thrown. - */ -#define LISTENER_ASSERT(property) \ - Try { \ - singleton->RemoveListener<(property)>(controller[i]); \ - LogError("Controller " << i << " is still listening for property " \ - << #property); \ - RUNNER_ASSERT_MSG(false, "No listeners expected"); \ - } \ - Catch(MTSharedObject::Exception::ListenerNotFound) { \ - RUNNER_ASSERT(true); \ - } \ - -// test -RUNNER_TEST(SharedMemory_130_SharedObjectSingleton) -{ - RemoveIpcs(); // we need non existing shm - - srand(time(NULL)); - - // writer shared object - TestSharedObjectPtr sho = SharedObjectFactory::Create( - SHM_KEY, SEM_NAME); - - ShmController4* controller[MAX_THREADS]; - DPL::WaitableEvent waitable[MAX_THREADS]; - - const int array[64] = { 0, 1, 2 }; - - // Create and wait for notification. Make sure that the thread/controller 0 - // is created first - LogInfo("Creating controllers"); - for (size_t i = 0; i < MAX_THREADS; ++i) { - controller[i] = new ShmController4(&waitable[i]); - Wait(waitable[i]); - } - - // singleton will be created by thread/controller 0 by now - MTSharedObjectPtr singleton = SharedObjectSingleton::Instance(); - - for (size_t repeats = 0; repeats < SINGLETON_TEST_REPEATS; ++repeats) { - LogInfo("%%%%%%%%%%%%%%%%%%%%%"); - LogInfo("Iteration " << repeats + 1 << " of " << SINGLETON_TEST_REPEATS); - singleton->Clear(); - - // add listeners - LogInfo("Adding listeners"); - for (size_t i = 0; i < MAX_THREADS; ++i) { - controller[i]->PostEvent(ShmController4::ADD_LISTENERS); - } - // wait for listeners - MultipleWait(waitable); - - RUNNER_ASSERT((singleton->GetProperty<0, int>()) == 0); - RUNNER_ASSERT((singleton->GetProperty<1, int>()) == 0); - RUNNER_ASSERT((singleton->GetProperty<2, char>()) == 0); - - int checkArray[64] = {}; - singleton->GetProperty<3>(checkArray); - RUNNER_ASSERT(checkArray[0] == 0); - RUNNER_ASSERT(checkArray[1] == 0); - RUNNER_ASSERT(checkArray[2] == 0); - - // change - LogInfo("Setting property 0"); - sho->SetProperty<0>(1); - // wait for confirmations - MultipleWait(waitable); - - // change - LogInfo("Setting property 1"); - sho->SetProperty<1>(11); - // wait for confirmations - MultipleWait(waitable); - - // change - LogInfo("Setting property 2"); - sho->SetProperty<2>('a'); - // wait for confirmations - MultipleWait(waitable); - - // change - LogInfo("Setting property 3"); - sho->SetProperty<3>(array); - // wait for confirmations - MultipleWait(waitable); - - // remove listeners - LogInfo("Removing listeners"); - for (size_t i = 0; i < MAX_THREADS; ++i) { - controller[i]->PostEvent(ShmController4::REMOVE_LISTENERS); - } - // wait for listeners - MultipleWait(waitable); - - // check if listeners array is empty - LogInfo("Checking listeners"); - for (size_t i = 0; i < MAX_THREADS; ++i) { - LISTENER_ASSERT(0); - LISTENER_ASSERT(1); - LISTENER_ASSERT(2); - LISTENER_ASSERT(3); - } - - RUNNER_ASSERT((singleton->GetProperty<0, int>()) == 1); - RUNNER_ASSERT((singleton->GetProperty<1, int>()) == 11); - RUNNER_ASSERT((singleton->GetProperty<2, char>()) == 'a'); - singleton->GetProperty<3>(checkArray); - RUNNER_ASSERT(checkArray[0] == 0); - RUNNER_ASSERT(checkArray[1] == 1); - RUNNER_ASSERT(checkArray[2] == 2); - } - - singleton.Reset(); - - // Destroy controllers and wait for confirmation. Make sure that - // thread/controller 0 is destroyed in the end - LogInfo("Destroying controllers"); - for (int i = MAX_THREADS - 1; i >= 0; --i) { - controller[i]->PostEvent(DESTROY_EVENT); - Wait(waitable[i]); - if (i == 0) { - /* - * Destroy singleton before thread that created it finishes. - * This is to properly close all waitable handles opened by - * SharedObject in thread 0. - */ - LogInfo("Destroying singleton"); - controller[i]->PostEvent(ShmController4::DESTROY_SINGLETON); - Wait(waitable[i]); - } - delete controller[i]; - } -} - -#undef LISTENER_ASSERT - -/* - * test preconditions & postconditions: - * - no existing shared memory with given SHM_KEY - * - no existing semaphore of given SEM_NAME - */ -RUNNER_TEST(SharedMemory_001_Preconditions) { - RemoveIpcs(); -} - -RUNNER_TEST(SharedMemory_999_Postconditions) { - RemoveIpcs(); -} diff --git a/tests/dpl/unused/test_sql_connection.cpp b/tests/dpl/unused/test_sql_connection.cpp deleted file mode 100644 index 4525c98..0000000 --- a/tests/dpl/unused/test_sql_connection.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_sql_connection.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of sql connection tests - */ - -/* - * - * This test has been saved from original test_sql_connection.cpp in wrt-commons - * project. - * - */ - -#include - -RUNNER_TEST(SqlConnection_MassiveReadWrite_SemaphoreSynchronization) -{ - srand(time(NULL)); - - std::ostringstream dbSemaporeFileNameStream; - dbSemaporeFileNameStream << "dpl_tests_dbso_sem_"; - dbSemaporeFileNameStream << rand() << ".sem"; - - std::string dbSemaphoreFileName = dbSemaporeFileNameStream.str(); - - SemaphoreSynchronizationObjectGenerator m_generator(dbSemaphoreFileName); - MassiveReadWriteTest(&m_generator); -} diff --git a/tests/dpl/unused/test_task.cpp b/tests/dpl/unused/test_task.cpp deleted file mode 100644 index 995f1cb..0000000 --- a/tests/dpl/unused/test_task.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file test_task.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of task tests - */ -#include -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL) - -class MySingleTask : - public DPL::TaskDecl -{ - protected: - void StepOne() - {} - - public: - MySingleTask() : - DPL::TaskDecl(this) - { - AddStep(&MySingleTask::StepOne); - } -}; - -class MyMultiTask : - public DPL::MultiTaskDecl -{ - protected: - typedef DPL::MultiTaskDecl BaseType; - - void StepOne() - { - LogInfo("Step one"); - } - - void StepTwo() - { - LogInfo("Step two"); - } - - void StepThree() - { - LogInfo("Step three"); - } - - public: - MyMultiTask() : - BaseType(this, 2) - { - BaseType::StepList depListStepThree; - depListStepThree.push_back(&MyMultiTask::StepOne); - depListStepThree.push_back(&MyMultiTask::StepTwo); - AddStep(&MyMultiTask::StepThree, depListStepThree); - - BaseType::StepList depListStepTwo; - depListStepTwo.push_back(&MyMultiTask::StepOne); - AddStep(&MyMultiTask::StepTwo, depListStepTwo); - - BaseType::StepList depListStepOne; - AddStep(&MyMultiTask::StepOne, depListStepOne); - } -}; - -RUNNER_TEST(Task_SingleTask) -{ - MySingleTask task; - while (task.NextStep()) {} -} - -RUNNER_TEST(Task_MultiTask) -{ - MyMultiTask task; - while (task.NextStep()) {} -} diff --git a/tests/dpl/utils/CMakeLists.txt b/tests/dpl/utils/CMakeLists.txt deleted file mode 100644 index b3ce494..0000000 --- a/tests/dpl/utils/CMakeLists.txt +++ /dev/null @@ -1,33 +0,0 @@ -# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved -# -# 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. -# -# @file CMakeLists.txt -# @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) -# @version 1.0 -# @brief -# - -SET(TARGET_NAME "dpl-tests-utils") - -# Set DPL tests sources -SET(DPL_TESTS_UTIL_SOURCES - ${TESTS_DPL_DIR}/utils/main.cpp - ${TESTS_DPL_DIR}/utils/widget_version.cpp - ${TESTS_DPL_DIR}/utils/bash_utils.cpp - ${TESTS_DPL_DIR}/utils/wrt_utility.cpp -) - -#WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_NAME} ${TARGET_DPL_UTILS_EFL}) -WRT_TEST_BUILD(${TARGET_NAME} ${DPL_TESTS_UTIL_SOURCES}) -WRT_TEST_INSTALL(${TARGET_NAME}) diff --git a/tests/dpl/utils/bash_utils.cpp b/tests/dpl/utils/bash_utils.cpp deleted file mode 100644 index 7dac1fc..0000000 --- a/tests/dpl/utils/bash_utils.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/** - * @file bash_utils.cpp - * @author Iwanek Tomasz - * @version 1.0 - */ -#include -#include -#include - -using namespace BashUtils; - -RUNNER_TEST_GROUP_INIT(DPL_BASH_UTILS) - -/* -Name: Bash_Utils_escape_arg -Description:tests ecaping bash special characters for command arguments -Expected: matching string -*/ -RUNNER_TEST(Bash_Utils_escape_arg) -{ - RUNNER_ASSERT_MSG(escape_arg(std::string( - "valid")) == "\"valid\"", - "Valid argument failed"); - LogDebug("\"val\\!d\"" << " " << escape_arg(std::string("val!d"))); - RUNNER_ASSERT_MSG(escape_arg(std::string( - "val!d")) == "\"val\\!d\"", - "Single escaped character in argument failed"); - LogDebug("\"v\\$l\\$\\$\"" << " " << escape_arg(std::string("v$l$$"))); - RUNNER_ASSERT_MSG(escape_arg(std::string( - "v$l$$")) == "\"v\\$l\\$\\$\"", - "Multiple occurences of single special character in argument failed"); - LogDebug("\"v\\`\\$\\\"\\!d\\`\"" << " " << - escape_arg(std::string("v`$\"!d`"))); - RUNNER_ASSERT_MSG(escape_arg(std::string( - "v`$\"!d`")) == "\"v\\`\\$\\\"\\!d\\`\"", - "Multiple occurences of multiple special character in argument failed"); -} diff --git a/tests/dpl/utils/main.cpp b/tests/dpl/utils/main.cpp deleted file mode 100644 index 42ffe3a..0000000 --- a/tests/dpl/utils/main.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file main.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of main - */ -#include - -int main(int argc, char *argv[]) -{ - return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); -} - diff --git a/tests/dpl/utils/widget_version.cpp b/tests/dpl/utils/widget_version.cpp deleted file mode 100644 index f00c715..0000000 --- a/tests/dpl/utils/widget_version.cpp +++ /dev/null @@ -1,436 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file widget_version.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief Implementation file for test cases for engine internal tests - */ -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL_WIDGET_VERSION) - -/* -Name: WidgetVersion_M2_O0 -Description: tests correct parsing of version widget in format: [major].[minor] -Expected: major and minor parts matches expected values -*/ -RUNNER_TEST(WidgetVersion_M2_O0) -{ - DPL::String raw(L"1.2"); - WidgetVersion version(raw); - - RUNNER_ASSERT(version.IsWac() == true); - RUNNER_ASSERT(version.Major() == DPL::String(L"1")); - RUNNER_ASSERT(version.Minor() == DPL::String(L"2")); - RUNNER_ASSERT(version.Micro() == DPL::Optional()); - RUNNER_ASSERT(version.Optional() == DPL::Optional()); - RUNNER_ASSERT(version.Raw() == raw); -} - -/* -Name: WidgetVersion_M2_O0_nonwac_1 -Description: tests if version is recognized as wac version number -Expected: version should not be recognized as wac compatible -*/ -RUNNER_TEST(WidgetVersion_M2_O0_nonwac_1) -{ - DPL::String raw(L"a1.2"); - WidgetVersion version(raw); - - RUNNER_ASSERT(version.IsWac() == false); - RUNNER_ASSERT(version.Raw() == raw); -} - -/* -Name: WidgetVersion_M2_O0_nonwac_2 -Description: tests if version is recognized as wac version number -Expected: version should not be recognized as wac compatible -*/ -RUNNER_TEST(WidgetVersion_M2_O0_nonwac_2) -{ - DPL::String raw(L"1.2a"); - WidgetVersion version(raw); - - RUNNER_ASSERT(version.IsWac() == false); - RUNNER_ASSERT(version.Raw() == raw); -} - -/* -Name: WidgetVersion_M2_O0_nonwac_3 -Description: tests if version is recognized as wac version number -Expected: version should not be recognized as wac compatible -*/ -RUNNER_TEST(WidgetVersion_M2_O0_nonwac_3) -{ - DPL::String raw(L"aaa1.2bbb"); - WidgetVersion version(raw); - - RUNNER_ASSERT(version.IsWac() == false); - RUNNER_ASSERT(version.Raw() == raw); -} - -/* -Name: WidgetVersion_M2_O0_nonwac_4 -Description: tests if version is recognized as wac version number -Expected: version should not be recognized as wac compatible -*/ -RUNNER_TEST(WidgetVersion_M2_O0_nonwac_4) -{ - DPL::String raw(L"1a.a2"); - WidgetVersion version(raw); - - RUNNER_ASSERT(version.IsWac() == false); - RUNNER_ASSERT(version.Raw() == raw); -} - -/* -Name: WidgetVersion_M2_O0_long -Description: tests correct parsing of version widget in format: [major].[minor] - for huge number -Expected: major and minor parts matches expected values -*/ -RUNNER_TEST(WidgetVersion_M2_O0_long) -{ - DPL::String raw( - L"123456789012345678901234567890.98765432109876543210987654321"); - WidgetVersion version(raw); - - RUNNER_ASSERT(version.IsWac() == true); - RUNNER_ASSERT(version.Major() == - DPL::String(L"123456789012345678901234567890")); - RUNNER_ASSERT(version.Minor() == - DPL::String(L"98765432109876543210987654321")); - RUNNER_ASSERT(version.Micro() == DPL::Optional()); - RUNNER_ASSERT(version.Optional() == DPL::Optional()); - RUNNER_ASSERT(version.Raw() == raw); -} - -/* -Name: WidgetVersion_M3_O0 -Description: tests correct wac version number -Expected: major and minor and micro parts matches expected values. - Version should be recognized as wac compatible -*/ -RUNNER_TEST(WidgetVersion_M3_O0) -{ - DPL::String raw(L"1.2.3"); - WidgetVersion version(raw); - - RUNNER_ASSERT(version.IsWac() == true); - RUNNER_ASSERT(version.Major() == DPL::String(L"1")); - RUNNER_ASSERT(version.Minor() == DPL::String(L"2")); - RUNNER_ASSERT(version.Micro() == DPL::Optional(L"3")); - RUNNER_ASSERT(version.Optional() == DPL::Optional()); - RUNNER_ASSERT(version.Raw() == raw); -} - -/* -Name: WidgetVersion_M3_O0_nonwac_1 -Description: tests if version is recognized as wac version number -Expected: version should not be recognized as wac compatible -*/ -RUNNER_TEST(WidgetVersion_M3_O0_nonwac_1) -{ - DPL::String raw(L"a1a.2.3"); - WidgetVersion version(raw); - - RUNNER_ASSERT(version.IsWac() == false); - RUNNER_ASSERT(version.Raw() == raw); -} - -/* -Name: WidgetVersion_M3_O0_nonwac_2 -Description: tests if version is recognized as wac version number -Expected: version should not be recognized as wac compatible -*/ -RUNNER_TEST(WidgetVersion_M3_O0_nonwac_2) -{ - DPL::String raw(L"1.b2.3"); - WidgetVersion version(raw); - - RUNNER_ASSERT(version.IsWac() == false); - RUNNER_ASSERT(version.Raw() == raw); -} - -/* -Name: WidgetVersion_M3_O0_nonwac_3 -Description: tests if version is recognized as wac version number -Expected: version should not be recognized as wac compatible -*/ -RUNNER_TEST(WidgetVersion_M3_O0_nonwac_3) -{ - DPL::String raw(L"1.2.3c"); - WidgetVersion version(raw); - - RUNNER_ASSERT(version.IsWac() == false); - RUNNER_ASSERT(version.Raw() == raw); -} - -/* -Name: WidgetVersion_M3_O0_nonwac_4 -Description: tests if version is recognized as wac version number -Expected: version should not be recognized as wac compatible -*/ -RUNNER_TEST(WidgetVersion_M3_O0_nonwac_4) -{ - DPL::String raw(L"1.2.3a"); - WidgetVersion version(raw); - - RUNNER_ASSERT(version.IsWac() == false); - RUNNER_ASSERT(version.Raw() == raw); -} - -/* -Name: WidgetVersion_M3_O1_1 -Description: tests correct wac version number with optional part -Expected: major and minor and micro and optional parts matches expected values. - Version should be recognized as wac compatible -*/ -RUNNER_TEST(WidgetVersion_M3_O1_1) -{ - DPL::String raw(L"1.2.3 test111"); - WidgetVersion version(raw); - - RUNNER_ASSERT(version.IsWac() == true); - RUNNER_ASSERT(version.Major() == DPL::String(L"1")); - RUNNER_ASSERT(version.Minor() == DPL::String(L"2")); - RUNNER_ASSERT(version.Micro() == DPL::Optional(L"3")); - RUNNER_ASSERT(version.Optional() == DPL::Optional(L"test111")); - RUNNER_ASSERT(version.Raw() == raw); -} - -/* -Name: WidgetVersion_M3_O1_1 -Description: tests correct wac version number with numeric optional part -Expected: major and minor and micro and optional parts matches expected values. - Version should be recognized as wac compatible -*/ -RUNNER_TEST(WidgetVersion_M3_O1_2) -{ - DPL::String raw(L"1.2.3 111"); - WidgetVersion version(raw); - - RUNNER_ASSERT(version.IsWac() == true); - RUNNER_ASSERT(version.Major() == DPL::String(L"1")); - RUNNER_ASSERT(version.Minor() == DPL::String(L"2")); - RUNNER_ASSERT(version.Micro() == DPL::Optional(L"3")); - RUNNER_ASSERT(version.Optional() == DPL::Optional(L"111")); - RUNNER_ASSERT(version.Raw() == raw); -} - -/* -Name: WidgetVersion_M3_O1_3 -Description: tests if version is recognized as wac version number - when trailer spaces exists -Expected: version should not be recognized as wac compatible -*/ -RUNNER_TEST(WidgetVersion_M3_O1_3) -{ - DPL::String raw(L"1.2.3 "); - WidgetVersion version(raw); - - RUNNER_ASSERT(version.IsWac() == false); - RUNNER_ASSERT(version.Raw() == raw); -} - -/* -Name: WidgetVersion_M2_O1_1 -Description: tests if version is recognized as wac version number - when optional part -Expected: version should be recognized as wac compatible -*/ -RUNNER_TEST(WidgetVersion_M2_O1_1) -{ - DPL::String raw(L"1.2 t"); - WidgetVersion version(raw); - - RUNNER_ASSERT(version.IsWac() == true); - RUNNER_ASSERT(version.Major() == DPL::String(L"1")); - RUNNER_ASSERT(version.Minor() == DPL::String(L"2")); - RUNNER_ASSERT(version.Micro() == DPL::Optional()); - RUNNER_ASSERT(version.Optional() == DPL::Optional(L"t")); - RUNNER_ASSERT(version.Raw() == raw); -} - -/* -Name: WidgetVersion_Strange_0 -Description: tests if version is recognized as wac version number -Expected: version should be recognized as wac compatible -*/ -RUNNER_TEST(WidgetVersion_Strange_0) -{ - DPL::String raw(L"1"); - WidgetVersion version(raw); - - RUNNER_ASSERT(version.IsWac() == false); - RUNNER_ASSERT(version.Raw() == raw); -} - -/* -Name: WidgetVersion_Strange_1 -Description: tests if version is recognized as wac version number -Expected: version should not be recognized as wac compatible -*/ -RUNNER_TEST(WidgetVersion_Strange_1) -{ - DPL::String raw(L".1"); - WidgetVersion version(raw); - - RUNNER_ASSERT(version.IsWac() == false); - RUNNER_ASSERT(version.Raw() == raw); -} - -/* -Name: WidgetVersion_Strange_2 -Description: tests if version is recognized as wac version number -Expected: version should not be recognized as wac compatible -*/ -RUNNER_TEST(WidgetVersion_Strange_2) -{ - DPL::String raw(L"..1"); - WidgetVersion version(raw); - - RUNNER_ASSERT(version.IsWac() == false); - RUNNER_ASSERT(version.Raw() == raw); -} - -/* -Name: WidgetVersion_Strange_3 -Description: tests if version is recognized as wac version number -Expected: version should not be recognized as wac compatible -*/ -RUNNER_TEST(WidgetVersion_Strange_3) -{ - DPL::String raw(L"...1"); - WidgetVersion version(raw); - - RUNNER_ASSERT(version.IsWac() == false); - RUNNER_ASSERT(version.Raw() == raw); -} - -/* -Name: WidgetVersion_Strange_4 -Description: tests if version is recognized as wac version number -Expected: version should not be recognized as wac compatible -*/ -RUNNER_TEST(WidgetVersion_Strange_4) -{ - DPL::String raw(L"qwerty"); - WidgetVersion version(raw); - - RUNNER_ASSERT(version.IsWac() == false); - RUNNER_ASSERT(version.Raw() == raw); -} - -/* -Name: WidgetVersion_Strange_5 -Description: tests if version is recognized as wac version number -Expected: version should not be recognized as wac compatible -*/ -RUNNER_TEST(WidgetVersion_Strange_5) -{ - DPL::String raw(L"!@#$%^&*()_+ ^&%^*&%$^*&%*()& JHKJLHKJLH 685685687"); - WidgetVersion version(raw); - - RUNNER_ASSERT(version.IsWac() == false); - RUNNER_ASSERT(version.Raw() == raw); -} - -/* -Name: WidgetVersion_Compare_0 -Description: tests version comparision in format [major].[minor] -Expected: compare should work as expected -*/ -RUNNER_TEST(WidgetVersion_Compare_0) -{ - RUNNER_ASSERT(WidgetVersion(L"1.1") < WidgetVersion(L"1.2")); -} - -/* -Name: WidgetVersion_Compare_1 -Description: tests version comparision in format [major].[minor] -Expected: compare should work as expected -*/ -RUNNER_TEST(WidgetVersion_Compare_1) -{ - RUNNER_ASSERT(WidgetVersion(L"01.001") < WidgetVersion(L"0001.002")); -} - -/* -Name: WidgetVersion_Compare_2 -Description: tests version equality in format [major].[minor] -Expected: versions should be equal -*/ -RUNNER_TEST(WidgetVersion_Compare_2) -{ - RUNNER_ASSERT(WidgetVersion(L"0.1") == WidgetVersion(L"00.1")); -} - -/* -Name: WidgetVersion_Compare_3 -Description: tests version comparision in format [major].[minor] [optional] -Expected: compare should work as expected -*/ -RUNNER_TEST(WidgetVersion_Compare_3) -{ - RUNNER_ASSERT(WidgetVersion(L"1.00000000000000") >= - WidgetVersion(L"1.0 test")); -} - -/* -Name: WidgetVersion_Compare_4 -Description: tests version comparision for huge numbers -Expected: compare should work as expected -*/ -RUNNER_TEST(WidgetVersion_Compare_4) -{ - RUNNER_ASSERT(WidgetVersion( - L"19647963733338932479072098437089778943732432.00000000000000004324324324324321") - > WidgetVersion(L"4324324324324324324321.000432")); -} - -/* -Name: WidgetVersion_Compare_5 -Description: tests equality in format [major].[minor] -Expected: versions should be equal -*/ -RUNNER_TEST(WidgetVersion_Compare_5) -{ - RUNNER_ASSERT(WidgetVersion(L"12345.1") == WidgetVersion(L"12345.1")); -} - -/* -Name: WidgetVersion_Compare_6 -Description: tests version equality in format [major].[minor] -Expected: versions should not be equal -*/ -RUNNER_TEST(WidgetVersion_Compare_6) -{ - RUNNER_ASSERT(WidgetVersion(L"1.1") != WidgetVersion(L"1.11")); -} - -/* -Name: WidgetVersion_Compare_7 -Description: tests version equality in format [major].[minor] [optional] -Expected: versions should be equal, optional part should not be taken into account -*/ -RUNNER_TEST(WidgetVersion_Compare_7) -{ - RUNNER_ASSERT(WidgetVersion(L"000123000.0 notatest") == - WidgetVersion(L"00123000.0 testtesttest")); -} diff --git a/tests/dpl/utils/wrt_utility.cpp b/tests/dpl/utils/wrt_utility.cpp deleted file mode 100644 index eb78ed6..0000000 --- a/tests/dpl/utils/wrt_utility.cpp +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/* - * @file wrt_utility.cpp - * @author Janusz Majnert (j.majnert@samsung.com) - * @version 1.0 - * @brief Implementation file for test cases for wrt_utility functions - */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -RUNNER_TEST_GROUP_INIT(DPL_WRT_UTILITY) - -/* -Name: wrt_utility_WrtUtilJoinPaths -Description: join paths test -Expected: correctly used separator -*/ -RUNNER_TEST(wrt_utility_WrtUtilJoinPaths) -{ - std::string result; - - WrtUtilJoinPaths(result, "a/b/c/", "e/f/g.asd"); - RUNNER_ASSERT(result == "a/b/c/e/f/g.asd"); - - WrtUtilJoinPaths(result, "/a/b/c", "/e/f/g/"); - RUNNER_ASSERT(result == "/a/b/c/e/f/g/"); - - WrtUtilJoinPaths(result, "/a/b/c/", "/e/f/g/"); - RUNNER_ASSERT(result == "/a/b/c/e/f/g/"); - - WrtUtilJoinPaths(result, "/a/b/c", "e/f/g/"); - RUNNER_ASSERT(result == "/a/b/c/e/f/g/"); -} - -/** - * Create recursive path with specified permissions. - * Check if folders exist. - * Check if permissions are set. - */ -RUNNER_TEST(wrt_utility_WrtUtilMakeDir) -{ - struct stat st; - //First delete the dir if it exists - WrtUtilRemove("/tmp/test"); - WrtUtilMakeDir("/tmp/test/1/2/3/4/5/6/7/8/9", 0755); - if (stat("/tmp/test/1/2/3/4/5/6/7/8/9", &st) == 0) { - RUNNER_ASSERT_MSG(st.st_mode & S_IRWXU, - "read, write, execute/search by owner"); - RUNNER_ASSERT_MSG(st.st_mode & S_IXGRP, - "execute/search permission, group"); - RUNNER_ASSERT_MSG(st.st_mode & S_IRGRP, "read permission, group"); - RUNNER_ASSERT_MSG(!(st.st_mode & S_IWGRP), - "NO write permission, group "); - RUNNER_ASSERT_MSG(st.st_mode & S_IXOTH, - "execute/search permission, others"); - RUNNER_ASSERT_MSG(st.st_mode & S_IROTH, "read permission, others"); - RUNNER_ASSERT_MSG(!(st.st_mode & S_IWOTH), - "NO write permission, others "); - } else { - RUNNER_ASSERT_MSG(false, "Cannot stat folder"); - } -} - -/** - * Create directory without permission to write. - */ -RUNNER_TEST(wrt_utility_WrtUtilMakeDir_PermissionError) -{ - if (0 == getuid()) { - //Change UID to execute the test correctly - errno = 0; - struct passwd *p = getpwnam("app"); - if (p == NULL) { - int error = errno; - RUNNER_ASSERT_MSG(false, "Getting app user UID failed: " - << (error == - 0 ? "No error detected" : strerror(error))); - } - if (setuid(p->pw_uid) != 0) { - int error = errno; - RUNNER_ASSERT_MSG(false, "Changing to app user's UID failed: " - << (error == - 0 ? "No error detected" : strerror(error))); - } - } - RUNNER_ASSERT_MSG(WrtUtilMakeDir("/tmp/test2/1", - 0055) == false, - "Creating directory '1' in /temp/test2/ should have failed"); - //Going back to root UID - if (setuid(0) != 0) { - int error = errno; - LogWarning("Changing back to root UID failed: " - << (error == 0 ? "No error detected" : strerror(error))); - } -} - -/** - * Create directory with file inside. - * Check if file was removed with directory. - */ -RUNNER_TEST(wrt_utility_WrtUtilRemoveDir) { - RUNNER_ASSERT_MSG(WrtUtilMakeDir("/tmp/test3/", 0755) == true, - "Could not set up directory for test"); - - std::ofstream file; - file.open("/tmp/test3/example.txt"); - file.close(); - struct stat tmp; - RUNNER_ASSERT_MSG(stat("/tmp/test3/example.txt", &tmp) == 0, - "Couldn't create the test file"); - - WrtUtilRemove("/tmp/test3"); - if (stat("/tmp/test3", &tmp) != 0) { - int error = errno; - RUNNER_ASSERT(error == ENOENT); - return; - } - RUNNER_ASSERT(false); -} - -/** - * Try to remove not existing folder. - */ -RUNNER_TEST(wrt_utility_WrtUtilRemoveDir_NoDirError) -{ - //First making sure the test dir doesn't exist - WrtUtilRemove("/tmp/NOT_EXISTING"); - - RUNNER_ASSERT_MSG(WrtUtilRemove("/tmp/NOT_EXISTING") == false, - "Removing non existing directory returned success"); -} - -/* -Name: wrt_utility_WrtUtilFileExists -Description: tests file existence -Expected: existing file should be reported as existing -*/ -RUNNER_TEST(wrt_utility_WrtUtilFileExists) -{ - std::ofstream file; - file.open("/tmp/test_file1"); - file.close(); - RUNNER_ASSERT(WrtUtilFileExists("/tmp/test_file1")); - - WrtUtilRemove("/tmp/test_file1"); - RUNNER_ASSERT(WrtUtilFileExists("/tmp/test_file1") == false); -} - -/* -Name: wrt_utility_WrtUtilDirExists -Description: tests directory existence -Expected: existing directory should be reported as existing -*/ -RUNNER_TEST(wrt_utility_WrtUtilDirExists) -{ - RUNNER_ASSERT(WrtUtilDirExists("/tmp")); - RUNNER_ASSERT(WrtUtilDirExists("/UNAVAILABLE_DIR") == false); -} diff --git a/tests/event/CMakeLists.txt b/tests/event/CMakeLists.txt new file mode 100644 index 0000000..08fa4fa --- /dev/null +++ b/tests/event/CMakeLists.txt @@ -0,0 +1,42 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# 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. +# +# @file CMakeLists.txt +# @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) +# @version 1.0 +# @brief +# + +# +# Test files +# +# Define all DPL tests sources. +# Runner is responsible for runnint it all and +# generating proper output files +# + +SET(TARGET_NAME "wrt-commons-tests-event") + +# Set DPL tests sources +SET(DPL_TESTS_EVENT_SOURCES + ${TESTS_DIR}/event/main.cpp + ${TESTS_DIR}/event/test_controller.cpp + ${TESTS_DIR}/event/test_event_support.cpp + ${TESTS_DIR}/event/test_ic_delegate.cpp + ${TESTS_DIR}/event/test_property.cpp +) + +WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_NAME} ${TARGET_DPL_EVENT_EFL}) +WRT_TEST_BUILD(${TARGET_NAME} ${DPL_TESTS_EVENT_SOURCES}) +WRT_TEST_INSTALL(${TARGET_NAME}) \ No newline at end of file diff --git a/tests/event/main.cpp b/tests/event/main.cpp new file mode 100644 index 0000000..4ed6191 --- /dev/null +++ b/tests/event/main.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/** + * @file main.cpp + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of main. + */ + +#include + +int main(int argc, char *argv[]) +{ + return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); +} diff --git a/tests/event/test_controller.cpp b/tests/event/test_controller.cpp new file mode 100644 index 0000000..8f0a630 --- /dev/null +++ b/tests/event/test_controller.cpp @@ -0,0 +1,422 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_controller.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test controller + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +class IntController : + public DPL::Event::Controller::Type> +{ + private: + int m_value; + + protected: + virtual void OnEventReceived(const int &event) + { + m_value = event; + } + + public: + IntController() : + m_value(-1) + {} + + int Value() const + { + return m_value; + } +}; + +DECLARE_GENERIC_EVENT_1(DoneSignalEvent, DPL::WaitableEvent *) + +class ThreadController : + public DPL::Event::Controller::Type> +{ + private: + DPL::Thread *m_value; + + protected: + virtual void OnEventReceived(const DoneSignalEvent &event) + { + m_value = DPL::Thread::GetCurrentThread(); + event.GetArg0()->Signal(); + } + + public: + ThreadController() : + m_value(NULL) + {} + + DPL::Thread *Value() const + { + return m_value; + } +}; + +struct StrangeStruct +{ + int a; + float b; + double c; +}; + +class StrangeController : + public DPL::Event::Controller::Type> +{ + protected: + virtual void OnEventReceived(const char &event) + { + (void)event; + } + virtual void OnEventReceived(const short &event) + { + (void)event; + } + virtual void OnEventReceived(const int &event) + { + (void)event; + } + virtual void OnEventReceived(const long &event) + { + (void)event; + } + virtual void OnEventReceived(const unsigned char &event) + { + (void)event; + } + virtual void OnEventReceived(const unsigned short &event) + { + (void)event; + } + virtual void OnEventReceived(const unsigned int &event) + { + (void)event; + } + virtual void OnEventReceived(const unsigned long &event) + { + (void)event; + } + virtual void OnEventReceived(const float &event) + { + (void)event; + } + virtual void OnEventReceived(const double &event) + { + (void)event; + } + virtual void OnEventReceived(const StrangeStruct &event) + { + (void)event; + } +}; + +/* +Name: Controller_InitSimple +Description: tests initialization of simple int controller +Expected: no exceptions +*/ +RUNNER_TEST(Controller_InitSimple) +{ + IntController controller; + controller.Touch(); + RUNNER_ASSERT(controller.Value() == -1); +} + +/* +Name: Controller_InitStrange +Description: tests initialization of struct controller +Expected: no exceptions +*/ +RUNNER_TEST(Controller_InitStrange) +{ + StrangeController controller; + controller.Touch(); +} + +/* +Name: Controller_PostEventToThread +Description: tests post events to other thread +Expected: thread id gathered in event handling method should match id of created thread +*/ +RUNNER_TEST(Controller_PostEventToThread) +{ + ThreadController controller; + controller.Touch(); + + DPL::Thread thread; + thread.Run(); + + controller.SwitchToThread(&thread); + + DPL::WaitableEvent waitHandle; + + controller.PostEvent(DoneSignalEvent(&waitHandle)); + + DPL::WaitForSingleHandle(waitHandle.GetHandle()); + + controller.SwitchToThread(NULL); + + RUNNER_ASSERT(controller.Value() == &thread); +} + +/* +Name: Controller_PostTimedEventToThread +Description: tests post events to other thread with time delay +Expected: thread id gathered in event handling method should match id of created thread +*/ +RUNNER_TEST(Controller_PostTimedEventToThread) +{ + ThreadController controller; + controller.Touch(); + + DPL::Thread thread; + thread.Run(); + + controller.SwitchToThread(&thread); + + DPL::WaitableEvent waitHandle; + + controller.PostTimedEvent(DoneSignalEvent(&waitHandle), 0.5); + + DPL::WaitForSingleHandle(waitHandle.GetHandle()); + + controller.SwitchToThread(NULL); + + RUNNER_ASSERT(controller.Value() == &thread); +} + +DECLARE_GENERIC_EVENT_2(TouchInThread, DPL::WaitableEvent *, DPL::Thread * *) +DECLARE_GENERIC_EVENT_2(TouchedControllerSignal, + DPL::WaitableEvent *, + DPL::Thread * *) + +class TouchInThreadController : + public DPL::Event::Controller::Type>, + private DPL::Event::Controller:: + Type> +{ + public: + typedef DPL::Event::Controller::Type> + PublicController; + typedef DPL::Event::Controller:: + Type> PrivateController; + + virtual void OnEventReceived(const TouchInThread &event) + { + // Touch controller in thread + PrivateController::Touch(); + + // Post signal + PrivateController::PostEvent(TouchedControllerSignal(event.GetArg0(), + event.GetArg1())); + } + + virtual void OnEventReceived(const TouchedControllerSignal &event) + { + // Return touched thread + *event.GetArg1() = DPL::Thread::GetCurrentThread(); + + // Signal waitable event + event.GetArg0()->Signal(); + } +}; + +/* +Name: Controller_TouchInThread +Description: tests ability to touch (initizilize / set destination thread) in creatd thread + other than thread were controlelr object was created +Expected: thread id gathered in event handling method should match id of created thread +*/ +RUNNER_TEST(Controller_TouchInThread) +{ + TouchInThreadController controller; + controller.PublicController::Touch(); + + DPL::Thread thread; + thread.Run(); + + controller.PublicController::SwitchToThread(&thread); + + DPL::WaitableEvent waitHandle; + DPL::Thread *touchedThread = NULL; + + controller.PublicController::PostEvent(TouchInThread(&waitHandle, + &touchedThread)); + + DPL::WaitForSingleHandle(waitHandle.GetHandle()); + + controller.PublicController::SwitchToThread(NULL); + + RUNNER_ASSERT(touchedThread == &thread); +} + +/* +Name: Controller_SynchronizedEvent +Description: tests ability to post synchronized events to ther thread +Expected: correct value should be saved when event was handled +*/ +RUNNER_TEST(Controller_SynchronizedEvent) +{ + IntController controller; + controller.Touch(); + + DPL::Thread thread; + thread.Run(); + + controller.SwitchToThread(&thread); + controller.PostSyncEvent(12345); + controller.SwitchToThread(NULL); + + RUNNER_ASSERT(controller.Value() == 12345); +} + +const int ControllersNumber = 5; +const int MaxEventsPerController = 1; +const int MaxEvents = ControllersNumber * MaxEventsPerController; +const int ControllersPerThread = 1; + +class TestController; //Forward Declaration + +typedef std::shared_ptr ControllerPtr; +typedef std::shared_ptr ThreadPtr; +typedef std::vector ControllerList; +typedef std::list ThreadList; + +DECLARE_GENERIC_EVENT_0(QuitEvent) +class QuitController : + public DPL::Event::Controller::Type>, + public DPL::ApplicationExt +{ + public: + explicit QuitController() : DPL::ApplicationExt(1, NULL, "test-app") + { + Touch(); + } + + protected: + virtual void OnEventReceived(const QuitEvent &) + { + Quit(); + } +}; + +struct TestContext +{ + ControllerList controllers; + ThreadList threads; + QuitController quitter; + DPL::Atomic g_ReceivedCounter; + DPL::Atomic g_SentCounter; +}; +typedef std::unique_ptr TestContextPtr; +TestContextPtr testContextPtr; + +DECLARE_GENERIC_EVENT_0(StartSendEvent) +DECLARE_GENERIC_EVENT_0(RandomEvent) +class TestController : + public DPL::Event::Controller::Type> +{ + public: + explicit TestController() + { + Touch(); + } + + protected: + virtual void OnEventReceived(const RandomEvent &) + { + ++testContextPtr->g_ReceivedCounter; + if (testContextPtr->g_ReceivedCounter == MaxEvents) { + testContextPtr->quitter.DPL::Event::ControllerEventHandler< + QuitEvent>::PostEvent(QuitEvent()); + return; + } + } + virtual void OnEventReceived(const StartSendEvent &) + { + for (int i = 0; i < MaxEventsPerController; ++i) { + if (testContextPtr->g_SentCounter > MaxEvents) { + return; + } + ++testContextPtr->g_SentCounter; + int id = rand() % static_cast(testContextPtr->controllers.size()); + testContextPtr->controllers.at(id)->DPL::Event:: + ControllerEventHandler::PostEvent(RandomEvent()); + } + } +}; + +/* +Name: Controllers_MultipleEvents +Description: tests controller coooperation. + This runs many controllers in many threads. Each controller sends + to other randomly chosen controller events. +Expected: Test is supposed to be ended when all limits of sent event will be reach + -> all scheduled event will be sent and received. +*/ +RUNNER_TEST(Controllers_MultipleEvents) +{ + srand(time(NULL) ); + + testContextPtr.reset(new TestContext()); + testContextPtr->controllers.reserve(ControllersNumber); + + for (int i = 0; i < ControllersNumber; ++i) { + if (testContextPtr->controllers.size() % ControllersPerThread == 0) { + ThreadPtr thread = ThreadPtr(new DPL::Thread()); + testContextPtr->threads.push_back(thread); + thread->Run(); + } + + ControllerPtr controller = ControllerPtr(new TestController()); + testContextPtr->controllers.push_back(controller); + if (testContextPtr->controllers.size() % 2 == 0) { + //This controller is being switched to thread (otherwise it is + // touched to main thread) + ThreadPtr thread = testContextPtr->threads.back(); + controller->SwitchToThread(thread.get()); + } + controller->DPL::Event::ControllerEventHandler:: + PostEvent(StartSendEvent()); + } + testContextPtr->quitter.Exec(); + RUNNER_ASSERT( + testContextPtr->g_SentCounter == testContextPtr->g_ReceivedCounter); + testContextPtr.reset(); +} diff --git a/tests/event/test_event_support.cpp b/tests/event/test_event_support.cpp new file mode 100644 index 0000000..e900e9c --- /dev/null +++ b/tests/event/test_event_support.cpp @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_event_support.cpp + * @author Piotr Marcinkiewicz (p.marcinkiew@samsung.com) + * @author Pawel Sikorski (p.sikorski@samsung.com) + * @version 1.0 + * @brief This file contains test for event support + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +DECLARE_GENERIC_EVENT_0(TestEvent) + +class TestListener : public DPL::Event::EventListener +{ + public: + explicit TestListener() : m_dummyVar(0) { } + void OnEventReceived(const TestEvent &) + { + m_dummyVar = 1; + } + int GetDummyVar() const + { + return m_dummyVar; + } + void ZeroDummyVar() + { + m_dummyVar = 0; + } + + private: + int m_dummyVar; +}; + +class TestEventSupport : + public DPL::Event::EventSupport +{ + public: + void TestEmitEvent() + { + EmitEvent(TestEvent()); + } +}; + +DECLARE_GENERIC_EVENT_0(QuitEvent) + +class QuitController : + public DPL::Event::Controller::Type>, + public DPL::ApplicationExt +{ + public: + QuitController() : DPL::ApplicationExt(1, NULL, "test-app") + { + Touch(); + } + + protected: + virtual void OnEventReceived(const QuitEvent &) + { + Quit(); + } +}; + +/* +Name: EventSupport_DestroyBeforeProcessing +Description: tests if remoign listener is full successfull +Expected: dummy var should be affected by explicit call of ZeroDummyVar(), + but no by emitting event after removing listener +*/ +RUNNER_TEST(EventSupport_DestroyBeforeProcessing) +{ + QuitController quitter; + quitter.PostTimedEvent(QuitEvent(), 1.0); + + TestListener eventListener; + { + TestEventSupport eventSupport; + eventSupport.AddListener(&eventListener); + eventSupport.TestEmitEvent(); + eventSupport.RemoveListener(&eventListener); + } + eventListener.ZeroDummyVar(); + + quitter.Exec(); + RUNNER_ASSERT(eventListener.GetDummyVar() == 0); +} + +int g_delegateTest; + +void OnDelegateTest(const int &k); + +void OnDelegateTest(const int &k) +{ + LogInfo("Got delegate call"); + g_delegateTest = k; +} + +class DelegateTestSupport : + public DPL::Event::EventSupport +{ + public: + void Test() + { + EmitEvent(7); + } +}; + +/* +Name: EventSupport_BindDelegate +Description: tests if event support derived class successfully propagates + event to registered listener +Expected: value of event should be passed to listener +*/ +RUNNER_TEST(EventSupport_BindDelegate) +{ + g_delegateTest = 0; + + DelegateTestSupport support; + support.AddListener(&OnDelegateTest); + + QuitController quitter; + quitter.PostTimedEvent(QuitEvent(), 1.0); + + support.Test(); + + quitter.Exec(); + + support.RemoveListener(&OnDelegateTest); + + RUNNER_ASSERT(g_delegateTest == 7); +} diff --git a/tests/event/test_ic_delegate.cpp b/tests/event/test_ic_delegate.cpp new file mode 100644 index 0000000..77856f4 --- /dev/null +++ b/tests/event/test_ic_delegate.cpp @@ -0,0 +1,603 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_ic_delegate.cpp + * @author Pawel Sikorski (p.sikorski@samsung.com) + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of fast delegate tests. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +RUNNER_TEST_GROUP_INIT(DPL) + +const int IntVal = 123; +const std::string StringVal = "someString"; + +typedef DPL::Event::ICDelegate<> GetNothingDlpType; +typedef DPL::Event::ICDelegate GetIntDlgType; +typedef DPL::Event::ICDelegate GetIntAndStringDlgType; +DECLARE_GENERIC_EVENT_1(GetNothingEvent, GetNothingDlpType) +DECLARE_GENERIC_EVENT_1(GetIntEvent, GetIntDlgType) +DECLARE_GENERIC_EVENT_1(GetIntAndStringEvent, GetIntAndStringDlgType) + +class ICTestController : + public DPL::Event::Controller::Type> +{ + public: + ICTestController() { } + + protected: + virtual void OnEventReceived(const GetNothingEvent& event) + { + event.GetArg0() (); //calling intercontext delegate + } + virtual void OnEventReceived(const GetIntEvent& event) + { + event.GetArg0() (IntVal); //calling intercontext delegate + } + + virtual void OnEventReceived(const GetIntAndStringEvent& event) + { + event.GetArg0() (IntVal, StringVal); //calling intercontext delegate + } +}; + +struct TestResult +{ + TestResult() : + m_correctThread0(false), + m_correctThread1(false), + m_correctThread2(false), + m_int(-1), + m_int2(-1), + m_string("") + {} + + void TestEventsPassed() + { + RUNNER_ASSERT(m_correctThread0); + RUNNER_ASSERT(m_correctThread1); + RUNNER_ASSERT(m_int == IntVal); + RUNNER_ASSERT(m_correctThread2); + RUNNER_ASSERT(m_int2 == IntVal); + RUNNER_ASSERT(m_string == StringVal); + } + + void TestEventsDidNotPass() + { + RUNNER_ASSERT(!m_correctThread0); + RUNNER_ASSERT(!m_correctThread1); + RUNNER_ASSERT(m_int == -1); + RUNNER_ASSERT(!m_correctThread2); + RUNNER_ASSERT(m_int2 == -1); + RUNNER_ASSERT(m_string == ""); + } + + bool m_correctThread0; + bool m_correctThread1; + bool m_correctThread2; + int m_int; + int m_int2; + std::string m_string; +}; + +class TestContextFreeClass : + protected DPL::Thread, + public DPL::Event::ICDelegateSupport +{ + public: + TestContextFreeClass(ICTestController* controller, TestResult* result) : + Thread(), + m_testResult(result), + m_controller(controller) + { + LogDebug("Context thread id = " << this); + } + + void Run() + { + LogDebug("Running Context Free thread"); + Thread::Run(); + } + + void Quit() + { + LogDebug("Exiting Context Free thread"); + Thread::Quit(); + } + + void Wait() + { + LogDebug("Waiting for thread"); + DPL::WaitForSingleHandle(m_waitable.GetHandle()); + } + + protected: + void OnNothing() + { + LogDebug("Received nothing in thread = " << GetCurrentThread()); + m_testResult->m_correctThread0 = (GetCurrentThread() == this); + } + + void OnIntReceive(int val) + { + LogDebug("Received int in thread = " << GetCurrentThread()); + m_testResult->m_correctThread1 = (GetCurrentThread() == this); + m_testResult->m_int = val; + } + + void OnIntAndStringReceive(int val, std::string stringval) + { + LogDebug("Received int and string in thread = " << GetCurrentThread()); + m_testResult->m_correctThread2 = (GetCurrentThread() == this); + m_testResult->m_int2 = val; + m_testResult->m_string = stringval; + m_waitable.Signal(); + } + + virtual int ThreadEntry() + { + GetNothingEvent getNothingEvent( + makeICDelegate( + &TestContextFreeClass::OnNothing)); + m_controller->DPL::Event::ControllerEventHandler:: + PostEvent( + getNothingEvent); + + GetIntEvent getIntEvent( + makeICDelegate( + &TestContextFreeClass::OnIntReceive)); + m_controller->DPL::Event::ControllerEventHandler:: + PostEvent( + getIntEvent); + + GetIntAndStringEvent getIntAndStringEvent( + makeICDelegate( + &TestContextFreeClass::OnIntAndStringReceive)); + m_controller->DPL::Event::ControllerEventHandler + ::PostEvent( + getIntAndStringEvent); + + return Thread::ThreadEntry(); + } + + private: + TestResult* m_testResult; + DPL::WaitableEvent m_waitable; + ICTestController* m_controller; +}; + +/* +Name: ICDelegate_0 +Description: checks if delegetes are correctly called +Expected: delegates should be called from right context +*/ +RUNNER_TEST(ICDelegate_0) +{ + DPL::Thread thread; + thread.Run(); + LogDebug("Controller thread id = " << &thread); + + ICTestController testController; + testController.Touch(); + testController.SwitchToThread(&thread); + + TestResult result; + TestContextFreeClass* contextFree = + new TestContextFreeClass(&testController, &result); + result.TestEventsDidNotPass(); + + thread.Run(); + contextFree->Run(); + contextFree->Wait(); + contextFree->Quit(); + thread.Quit(); + + delete contextFree; + + result.TestEventsPassed(); +} + +/* +Name: ICDelegate_1 +Description: checks if delegetes are correctly called +Expected: delegates should be called from right context +*/ +RUNNER_TEST(ICDelegate_1) +{ + DPL::Thread thread; + LogDebug("Controller thread id = " << &thread); + + ICTestController testController; + testController.Touch(); + testController.SwitchToThread(&thread); + + TestResult result; + TestContextFreeClass* contextFree = + new TestContextFreeClass(&testController, &result); + result.TestEventsDidNotPass(); + + contextFree->Run(); + contextFree->Quit(); + delete contextFree; //deleting Delegates before actual Events are worked out + thread.Run(); + thread.Quit(); + + result.TestEventsDidNotPass(); +} + +class TestContextFree; +class TestRunnerInThread; + +namespace { +const int ControllersPerThread = 40; +const int ContextFreePerThread = 180; +const int TestsPerController = 110; +const int TestThreads = 23; +const int TestsPerThread = 100; +const int NumberOfEvents = 230; + +typedef std::shared_ptr ICTestControllerPtr; +typedef std::shared_ptr TestContextFreePtr; +typedef std::shared_ptr TestRunnerInThreadPtr; +typedef std::shared_ptr ThreadPtr; + +DPL::Mutex mutex; +std::list frees; +std::list ctrls; +std::list frees_threads; +std::list ctrls_threads; +} + +class TestContextFree : public DPL::Event::ICDelegateSupport +{ + public: + TestContextFree(ICTestController* controller, + int eventsCount) : + m_controller(controller), + m_eventsCount(eventsCount) + {} + + void Wait() + { + LogDebug("Waiting for thread"); + DPL::WaitForSingleHandle(m_waitable.GetHandle()); + } + + void OnNothing() + { + LogDebug("Got"); + m_eventsCount--; + if (m_eventsCount > 0) { + LogDebug("posting next event"); + GetIntAndStringEvent getIntAndStringEvent( + makeICDelegate( + &TestContextFree::OnIntAndStringReceive)); + LogDebug("posting next event ..."); + m_controller->DPL::Event::ControllerEventHandler< + GetIntAndStringEvent>::PostEvent( + getIntAndStringEvent); + LogDebug("posting next event done"); + } else { + LogDebug("test finished"); + m_waitable.Signal(); + } + } + + void OnIntReceive(int) + { + LogDebug("Got"); + m_eventsCount--; + if (m_eventsCount > 0) { + LogDebug("posting next event"); + GetNothingEvent getNothingEvent( + makeICDelegate( + &TestContextFree::OnNothing)); + LogDebug("posting next event ..."); + m_controller->DPL::Event::ControllerEventHandler:: + PostEvent( + getNothingEvent); + LogDebug("posting next event done"); + } else { + LogDebug("test finished"); + m_waitable.Signal(); + } + } + + void OnIntAndStringReceive(int, std::string) + { + LogDebug("Got"); + m_eventsCount--; + if (m_eventsCount > 0) { + LogDebug("posting next event"); + + GetIntEvent getIntEvent( + makeICDelegate( + &TestContextFree::OnIntReceive)); + LogDebug("posting next event ..."); + m_controller->DPL::Event::ControllerEventHandler:: + PostEvent( + getIntEvent); + LogDebug("posting next event done"); + } else { + LogDebug("test finished"); + m_waitable.Signal(); + } + } + + void StartTestOnNothing() + { + GetNothingEvent getNothingEvent( + makeICDelegate( + &TestContextFree::OnNothing)); + m_controller->DPL::Event::ControllerEventHandler:: + PostEvent( + getNothingEvent); + } + + void StartTestOnInt() + { + GetIntEvent getIntEvent( + makeICDelegate( + &TestContextFree::OnIntReceive)); + m_controller->DPL::Event::ControllerEventHandler:: + PostEvent( + getIntEvent); + } + + void StartTestOnIntAndString() + { + GetIntAndStringEvent getIntAndStringEvent( + makeICDelegate( + &TestContextFree::OnIntAndStringReceive)); + m_controller->DPL::Event::ControllerEventHandler + ::PostEvent( + getIntAndStringEvent); + } + + bool CheckTest() + { + LogDebug("Checking test result"); + return m_eventsCount == 0; + } + + private: + ICTestController* m_controller; + int m_eventsCount; + DPL::WaitableEvent m_waitable; +}; + +class TestRunnerInThread : public DPL::Thread +{ + public: + TestRunnerInThread(int events, int tests) : + m_eventsCount(events), + m_tests(tests) {} + + void WaitForInit() + { + LogDebug("Waiting for thread"); + DPL::WaitForSingleHandle(m_init.GetHandle()); + } + + protected: + virtual int ThreadEntry() + { + LogDebug("Thread starts"); + { + DPL::Mutex::ScopedLock lock(&mutex); + for (int i = 0; i < m_tests; ++i) { + if (i % TestsPerController == 0) { + if (ctrls.size() % ControllersPerThread == 0) { + ThreadPtr thread(new DPL::Thread()); + thread->Run(); + ctrls_threads.push_back(thread); + } + ICTestControllerPtr ptr(new ICTestController()); + ptr->Touch(); + ptr->SwitchToThread(ctrls_threads.back().get()); + ctrls.push_back(ptr); + + TestContextFreePtr t(new TestContextFree(ctrls.back().get(), + m_eventsCount)); + t->StartTestOnNothing(); + LogDebug(""); + frees.push_back(t); + } + } + } + m_init.Signal(); + LogDebug("Thread starts loop"); + return DPL::Thread::ThreadEntry(); + } + + private: + DPL::WaitableEvent m_init; + int m_eventsCount; + int m_tests; +}; + +/* +Name: ICDelegate_2 +Description: checks if delegetes are correctly called +Expected: delegates should be called from right context +*/ +RUNNER_TEST(ICDelegate_2) +{ + LogDebug("Creating test threads"); + for (int i = 0; i < TestThreads; ++i) { + TestRunnerInThreadPtr ptr( + new TestRunnerInThread(NumberOfEvents, TestsPerThread)); + frees_threads.push_back(ptr); + frees_threads.back()->Run(); + } + + FOREACH(it, frees_threads) { + (*it)->WaitForInit(); + } + LogDebug("Creating test threads done"); + + FOREACH(it, frees) { + LogDebug("..."); + (*it)->Wait(); + } + + FOREACH(it, frees) { + RUNNER_ASSERT((*it)->CheckTest()); + } + + frees.clear(); + + FOREACH(it, frees_threads) { + (*it)->Quit(); + } + + frees_threads.clear(); + + FOREACH(it, ctrls) { + (*it)->SwitchToThread(NULL); + } + + FOREACH(it, ctrls_threads) { + (*it)->Quit(); + } + + ctrls.clear(); + ctrls_threads.clear(); +} + +namespace ReuseCheck { +const int ReuseCount = 5; +typedef DPL::Event::ICDelegate<> GetNothingDlpType; +DECLARE_GENERIC_EVENT_1(ReuseCountEvent, GetNothingDlpType) + +class ICReuseTestController : + public DPL::Event::Controller::Type> +{ + public: + ICReuseTestController() + { + m_reuseCount = 0; + } + + protected: + virtual void OnEventReceived(const ReuseCountEvent& event) + { + event.GetArg0() (); //calling intercontext delegate + if (++m_reuseCount < ReuseCount) { + LogInfo("[Send] Reuse: " << m_reuseCount); + DPL::Event::ControllerEventHandler::PostEvent( + event); + } + } + + int m_reuseCount; +}; + +class ReuseTestContextFreeClass : + protected DPL::Thread, + public DPL::Event::ICDelegateSupport +{ + public: + ReuseTestContextFreeClass(ICReuseTestController* controller) : + Thread(), + m_controller(controller), + m_reuseCount(0) + { } + + void Run() + { + Thread::Run(); + } + void Quit() + { + Thread::Quit(); + } + void Wait() + { + DPL::WaitForSingleHandle(m_waitable.GetHandle()); + } + + protected: + void OnReuseReceive() + { + LogDebug("[Received] : " << ++m_reuseCount); + if (m_reuseCount == ReuseCount) { + m_waitable.Signal(); + } + } + + virtual int ThreadEntry() + { + ReuseCountEvent reuseEvent( + makeICDelegate( + &ReuseTestContextFreeClass::OnReuseReceive, + DPL::Event::ICD::Reuse::Yes)); + m_controller->DPL::Event::ControllerEventHandler:: + PostEvent( + reuseEvent); + + return Thread::ThreadEntry(); + } + + private: + DPL::WaitableEvent m_waitable; + ICReuseTestController* m_controller; + int m_reuseCount; +}; + +/* +Name: ICDelegate_3 +Description: checks if delegetes are correctly called +Expected: delegates should be called from right context +*/ +RUNNER_TEST(ICDelegate_3) +{ + DPL::Thread thread; + thread.Run(); + LogDebug("Controller thread id = " << &thread); + + ICReuseTestController testController; + testController.Touch(); + testController.SwitchToThread(&thread); + + ReuseTestContextFreeClass* contextFree = + new ReuseTestContextFreeClass(&testController); + + thread.Run(); + contextFree->Run(); + contextFree->Wait(); + contextFree->Quit(); + thread.Quit(); + + delete contextFree; + + RUNNER_ASSERT(true); +} +} //namespace ReuseCheck diff --git a/tests/event/test_property.cpp b/tests/event/test_property.cpp new file mode 100644 index 0000000..d72d02e --- /dev/null +++ b/tests/event/test_property.cpp @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_property.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test property + */ +#include +#include +#include +#include + +namespace { +const int PROPERTY_VALUE_INT = 2; +const std::string PROPERTY_VALUE_STRING = "aaa"; +} + +int ReadSomething2(DPL::Event::Model */*model*/); +int ReadSomething2(DPL::Event::Model */*model*/) +{ + return PROPERTY_VALUE_INT; +} + +std::string ReadSomething(DPL::Event::Model */*model*/); +std::string ReadSomething(DPL::Event::Model */*model*/) +{ + return PROPERTY_VALUE_STRING; +} + +void WriteSomething(const std::string & /*value*/, DPL::Event::Model */*model*/); +void WriteSomething(const std::string & /*value*/, DPL::Event::Model */*model*/) +{} + +class MyModel : + public DPL::Event::Model +{ + public: + ~MyModel() {} + + DPL::Event::Property + Caption; + + DPL::Event::Property + Testproperty0; + + DPL::Event::Property + Testproperty1; + + DPL::Event::Property + Testproperty2; + + DPL::Event::Property Testproperty3; + + DPL::Event::Property Testproperty4; + + DPL::Event::Property + Testproperty5; + + MyModel() : + Caption(this, "Foo caption"), + Testproperty0(this, "", &ReadSomething), + Testproperty1(this), + Testproperty2(this), + Testproperty3(this), + Testproperty4(this, "test", &ReadSomething, &WriteSomething), + Testproperty5(this, &ReadSomething2) + {} +}; + +std::string g_caption; + +void OnNameChanged(const DPL::Event::PropertyEvent &event); +void OnNameChanged(const DPL::Event::PropertyEvent &event) +{ + g_caption = event.value; +} + +/* +Name: Model_Test +Description: tests accessing and changing models properties +Expected: listener should get changed value +*/ +RUNNER_TEST(Model_Test) +{ + MyModel model; + + g_caption = "It is a bad caption"; + + model.Caption.AddListener(&OnNameChanged); + model.Caption.Set("Test name"); + + RUNNER_ASSERT(model.Testproperty4.Get() == PROPERTY_VALUE_STRING); + RUNNER_ASSERT(PROPERTY_VALUE_INT == model.Testproperty5.Get()); + RUNNER_ASSERT(g_caption == "Test name"); + RUNNER_ASSERT(model.Caption.Get() == "Test name"); + + model.Caption.RemoveListener(&OnNameChanged); +} diff --git a/tests/files_localization/CMakeLists.txt b/tests/files_localization/CMakeLists.txt new file mode 100644 index 0000000..37d79c1 --- /dev/null +++ b/tests/files_localization/CMakeLists.txt @@ -0,0 +1,51 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# 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. +# +# @file CMakeLists.txt +# @author Bartlomiej Grzelewski (b.grzelewski@samsung.com) +# @version 1.0 +# @brief +# + +# +# Test files +# +# Define all DPL tests sources. +# Runner is responsible for runnint it all and +# generating proper output files +# + +SET(TARGET_LOC "wrt-commons-tests-loc") + +SET(LOC_TESTS_SOURCES + ${TESTS_DIR}/files_localization/test_localization.cpp + ${TESTS_DIR}/files_localization/test_suite01.cpp + #${DPL_TESTS_DIR}/localization/mockup_src/widget_dao.cpp + #${PROJECT_SOURCE_DIR}/modules/localization/src/localization_utils.cpp + #${PROJECT_SOURCE_DIR}/modules/localization/src/w3c_file_localization.cpp +) + +#WRT_INCLUDE_DIRECTORIES( + #${SYS_EFL_INCLUDE_DIRS} + #${DPL_TEST_INCLUDE_DIR} + #${DPL_TESTS_DIR}/localization/mockup_include + #${PROJECT_SOURCE_DIR}/modules/localization/include +#) + +#LINK_DIRECTORIES(${SYS_EFL_LIBRARY_DIRS}) + +WRT_TEST_BUILD(${TARGET_LOC} ${LOC_TESTS_SOURCES}) +WRT_TEST_INSTALL(${TARGET_LOC}) + +ADD_SUBDIRECTORY(files) diff --git a/tests/files_localization/files/CMakeLists.txt b/tests/files_localization/files/CMakeLists.txt new file mode 100644 index 0000000..17c7fda --- /dev/null +++ b/tests/files_localization/files/CMakeLists.txt @@ -0,0 +1,19 @@ +INSTALL(FILES + ${DPL_TESTS_DIR}/localization/files/one + DESTINATION + /opt/share/widget/tests/localization/widget1/locales/pl-en + ) + +INSTALL(FILES + ${DPL_TESTS_DIR}/localization/files/one + ${DPL_TESTS_DIR}/localization/files/two + DESTINATION + /opt/share/widget/tests/localization/widget2/locales/pl-en + ) + +INSTALL(FILES + ${DPL_TESTS_DIR}/localization/files/two + DESTINATION + /opt/share/widget/tests/localization/widget2/locales/en-en + ) + diff --git a/tests/files_localization/files/one b/tests/files_localization/files/one new file mode 100644 index 0000000..e69de29 diff --git a/tests/files_localization/files/two b/tests/files_localization/files/two new file mode 100644 index 0000000..e69de29 diff --git a/tests/files_localization/mockup_include/dpl/wrt-dao-ro/common_dao_types.h b/tests/files_localization/mockup_include/dpl/wrt-dao-ro/common_dao_types.h new file mode 100644 index 0000000..06b7294 --- /dev/null +++ b/tests/files_localization/mockup_include/dpl/wrt-dao-ro/common_dao_types.h @@ -0,0 +1,481 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/** + * + * @file common_dao_types.h + * @author Michal Ciepielski (m.ciepielski@samsung.com) + * @version 1.0 + * @brief This file contains the declaration of common data types for wrtdb + */ + +#ifndef WRT_SRC_CONFIGURATION_COMMON_DAO_TYPES_H_ +#define WRT_SRC_CONFIGURATION_COMMON_DAO_TYPES_H_ + +#include +#include +#include +#include +#include +#include +#include + +namespace WrtDB { +namespace Powder { +typedef std::set StringSet; +//! Widget description +struct Description +{ + //!Content level + typedef enum + { + Level0 = 0, + Level1, + Level2, + Level3, + Level4, + Level5, + LevelUnknown + } LevelEnum; + struct LevelEntry + { + LevelEnum level; //!< content level + + typedef StringSet Context; + + //! POWDER context + //! xa This material appears in an artistic context + //! xb This material appears in an educational context + //! xc This material appears in a medical context + //! xd This material appears in a sports context + //! xe This material appears in a violent context + Context context; + explicit LevelEntry(LevelEnum level = LevelUnknown); + //! Function checks if context is valid + //! \param[in] level POWDER content level + //! \param[in] context POWDER context + bool isContextValid(LevelEnum level, + const DPL::OptionalString& context) const; + }; + + struct CategoryEntry + { + //! Levels entries for POWDER description + typedef std::vector LevelsContainer; + LevelsContainer levels; + //! Function checks if context is valid + //! \param[out] reason set if context invalid + //! \param[in] level POWDER content level + //! \param[in] context POWDER context + bool isCategoryValid(LevelEntry& reason, + LevelEnum level, + const DPL::OptionalString& context) const; + }; + + //! POWDER Category -> Category entry map for Widget + //! + //! nu Nudity + //! se Sex + //! vi Violence + //! la Potentially offensive language + //! dr Drug use + //! ga Gambling + //! ha Hate or harmful activities + //! ug Use of user-generated content + typedef std::map CategoryEntries; + + CategoryEntries categories; + + //! Age rating for widget + //! If Null not set + DPL::OptionalInt ageRating; +}; +} // namespace Powder + +namespace ChildProtection { +//! Blacklist with forbidden URLs +//! It should be stored in WidgetDAO +typedef std::vector BlackList; + +//! Widget Child protection record +//! Record should be stored in WingetDAO +struct Record +{ + //! Child protection enabled + bool enabled; + explicit Record(bool enabled) : + enabled(enabled) + {} +}; + +//! Powder processing +struct PowderRules +{ + //! Rule set by parent about forbidden category + //! Powder category + //! nu Nudity + //! se Sex + //! vi Violence + //! la Potentially offensive language + //! dr Drug use + //! ga Gambling + //! ha Hate or harmful activities + //! ug Use of user-generated content + //! Powder context + //! xa This material appears in an artistic conteaxt + //! xb This material appears in an educational context + //! xc This material appears in a medical context + //! xd This material appears in a sports context + //! xe This material appears in a violent context + struct CategoryRule + { + DPL::String category; + Powder::Description::LevelEnum level; + DPL::OptionalString context; + explicit CategoryRule( + const DPL::String& category = DPL::String(), + Powder::Description::LevelEnum level = + Powder::Description::LevelUnknown, + const DPL::OptionalString& context = + DPL::OptionalString()); + }; + + struct PowderResult + { + //! Reasoning outcome: part of POWDER description used to invalidate + Powder::Description::LevelEntry invalidDescription; + //! Reasoning outcome: rule set by parent not full filed by description + CategoryRule invalidRule; + + //! Reasoning outcome: type of invalidity + enum InvalidReason + { + InvalidRule, //!< One of rules was not fulfilled + InvalidAge, //!< Age is invalid + AgeRatingNotSet, //!< Age rating for widget is not set + Valid //!< Description valid + }; + InvalidReason reason; + explicit PowderResult( + InvalidReason reason = Valid, + const Powder::Description::LevelEntry& + invalidDescription = + Powder::Description::LevelEntry(), + const CategoryRule& invalidRule = CategoryRule()); + }; + + typedef std::pair ResultPair; + + //! Function checks if rule is fulfilled by description + //! \param[in] rule checked rule + //! \param[in] description + //! \retval true rule is valid + //! \retval false rule is invalid + ResultPair isRuleValidForDescription(const CategoryRule& rule, + const Powder::Description& description) + const; + //! Function checks if age limit is fulfilled by description + //! \param[in] description + //! \retval true age is valid + //! \retval false age is invalid + ResultPair isAgeValidForDescription( + const Powder::Description& description) const; + + //! It is the maximum age rating valid for child + //! Uniform age is stored in WidgetDAO + DPL::OptionalInt ageLimit; + + //! Set to true if age rating is required + //! If ageLimit is not set value is ignored + bool isAgeRatingRequired; + + //! Set of rules configured by parent + //! Rules are stored in WidgetDAO and are uniform for all widgets + typedef std::vector RulesContainer; + RulesContainer rules; + + //! Function check if Widget description is valid for ChildProtection + //! configuration + //! \param description widget description + //! \retval true widget is valid + //! \retval false widget is invalid + ResultPair isDescriptionValid(const Powder::Description& description) + const; + + PowderRules() : + isAgeRatingRequired(false) + {} +}; +} // namespace ChildProtection + +class PluginMetafileData +{ + public: + struct Feature + { + std::string m_name; + std::set m_deviceCapabilities; + + bool operator< (const Feature& obj) const + { + return m_name < obj.m_name; + } + }; + typedef std::set FeatureContainer; + + public: + + PluginMetafileData() + {} + + std::string m_libraryName; + std::string m_featuresInstallURI; + std::string m_featuresKeyCN; + std::string m_featuresRootCN; + std::string m_featuresRootFingerprint; + + FeatureContainer m_featureContainer; +}; + +class PluginObjectsDAO +{ + public: + typedef std::set Objects; + typedef std::shared_ptr ObjectsPtr; + + public: + explicit PluginObjectsDAO() {} + + protected: + ObjectsPtr m_implemented; + ObjectsPtr m_dependent; +}; + +/** + * @brief Widget id describes web-runtime global widget identifier. + * + * Notice that only up to one widget can exist at the same time. + * DbWidgetHandle can be translated into corresponding WidgetModel by invoking + * FindWidgetModel routine. + */ +typedef int DbWidgetHandle; + +/** + * @brief Structure to hold the information of widget's size + */ +struct DbWidgetSize +{ + DPL::OptionalInt width; + DPL::OptionalInt height; + + DbWidgetSize(DPL::OptionalInt w = DPL::OptionalInt::Null, + DPL::OptionalInt h = DPL::OptionalInt::Null) : + width(w), + height(h) + {} +}; + +inline bool operator ==(const DbWidgetSize &objA, const DbWidgetSize &objB) +{ + if (!objA.height || !objA.width || !objB.width || !objB.height) { + return false; + } else { + return *objA.height == *objB.height && *objA.width == *objB.width; + } +} + +/** + * Widget [G]lobal [U]nique [ID]entifier + * Orginated from appstore ID + */ +typedef DPL::OptionalString WidgetGUID; + +struct WidgetAccessInfo +{ + DPL::String strIRI; /* origin iri */ + bool bSubDomains; /* do we want access to subdomains ? */ + + bool operator ==(const WidgetAccessInfo& info) const + { + return info.strIRI == strIRI && + info.bSubDomains == bSubDomains; + } +}; + +typedef std::list WidgetAccessInfoList; + +typedef std::list WindowModeList; + +/** + * @brief Widget configuration parameter key + */ +typedef DPL::String WidgetParamKey; + +/** + * @brief Widget configuration parameter value + */ +typedef DPL::String WidgetParamValue; + +/** + * @brief A map of widget configuration parameters. + * + * Widget configuration parameters are read from database and are stored + * along with feature that they describe. + */ +typedef std::multimap WidgetParamMap; + +/** + * @brief Widget feature host information about possible javascript extensions + * that widget may use + * + * Widget features are declared in configuration file in widget installation + * package. Each declared special feature is contained in some wrt-plugin that + * declares to implement it. After widget launch wrt searches for proper plugin + * libraries and load needed features. + * + * Widget features can be required or optional. It is possible to start widget + * without missing feature. When required feature cannot be loaded widget will + * not start. + */ + +enum { + INVALID_PLUGIN_HANDLE = -1 +}; +typedef int DbPluginHandle; + +struct DbWidgetFeature +{ + DPL::String name; /// Feature name + bool required; /// Whether feature is required + DbPluginHandle pluginId; /// Plugin id that implement this + // feature + WidgetParamMap params; /// Widget's params + + DbWidgetFeature() : + required(false), + pluginId(INVALID_PLUGIN_HANDLE) + {} +}; + +inline bool operator < (const DbWidgetFeature &objA, + const DbWidgetFeature &objB) +{ + return objA.name.compare(objB.name) < 0; +} + +inline bool operator==(const DbWidgetFeature &featureA, + const DbWidgetFeature &featureB) +{ + return featureA.name == featureB.name && + featureA.required == featureB.required && + featureA.pluginId == featureB.pluginId; +} + +/** + * @brief Default container for features list + */ +typedef std::multiset DbWidgetFeatureSet; + +/** + * @brief Default container with DbWidgetHandle's + */ +typedef std::list DbWidgetHandleList; + +/** + * @brief Widget specific type + * + * Widget type describes belowed in WAC, TIZEN WebApp + */ +enum AppType +{ + APP_TYPE_UNKNOWN = 0, // unknown + APP_TYPE_WAC20, // WAC 2.0 + APP_TYPE_TIZENWEBAPP, // slp webapp +}; + +class WidgetType +{ + public: + WidgetType() : + appType(APP_TYPE_UNKNOWN) + {} + WidgetType(const AppType type) : + appType(type) + {} + bool operator== (const AppType& other) const + { + return appType == other; + } + std::string getApptypeToString() + { + switch (appType) { +#define X(x) case x: return #x; + X(APP_TYPE_UNKNOWN) + X(APP_TYPE_WAC20) + X(APP_TYPE_TIZENWEBAPP) +#undef X + default: + return "UNKNOWN"; + } + } + + AppType appType; +}; +} // namespace WrtDB + +struct WidgetSetting +{ + DPL::String settingName; + DPL::String settingValue; + + bool operator ==(const WidgetSetting& info) const + { + return (info.settingName == settingName && + info.settingValue == settingValue); + } + bool operator !=(const WidgetSetting& info) const + { + return (info.settingName != settingName || + info.settingValue != settingValue); + } +}; + +typedef std::list WidgetSettings; + +/** + * @brief Widget Application Service + * + * Application sercvice describes details of behaviour + * when widget receives aul bundle data. + */ +struct WidgetApplicationService +{ + public: + DPL::String src; /* start uri */ + DPL::String operation; /* service name */ + DPL::String scheme; /* scheme type*/ + DPL::String mime; /* mime type */ + + bool operator== (const WidgetApplicationService& other) const + { + return src == other.src && + operation == other.operation && + scheme == other.scheme && + mime == other.mime; + } +}; + +typedef std::list WidgetApplicationServiceList; +#endif /* WRT_SRC_CONFIGURATION_COMMON_DAO_TYPES_H_ */ diff --git a/tests/files_localization/mockup_include/dpl/wrt-dao-rw/widget_dao.h b/tests/files_localization/mockup_include/dpl/wrt-dao-rw/widget_dao.h new file mode 100644 index 0000000..264c6e4 --- /dev/null +++ b/tests/files_localization/mockup_include/dpl/wrt-dao-rw/widget_dao.h @@ -0,0 +1,232 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/** + * This file contains the declaration of widget dao class. + * + * @file widget_dao_read_only.h + * @author Yang Jie (jie2.yang@samsung.com) + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @author Pawel Sikorski (p.sikorski@samsung.com) + * @version 1.0 + * @brief This file contains the declaration of widget dao + */ + +#ifndef _WRT_SRC_CONFIGURATION_WIDGET_DAO_READ_ONLY_H_ +#define _WRT_SRC_CONFIGURATION_WIDGET_DAO_READ_ONLY_H_ + +#include + +#include +#include +#include +#include + +#include +#include +#include + +#include +//#include "../wrt-dao-ro/common_dao_types.h" + +typedef DPL::OptionalString WidgetGUID; + +namespace ConfigParserData { +struct Icon +{ + Icon(const DPL::String& src) : src(src) + {} + DPL::String src; + DPL::OptionalInt width; + DPL::OptionalInt height; + bool operator==(const Icon&) const; + bool operator!=(const Icon&) const; + bool operator >(const Icon&) const; + bool operator>=(const Icon&) const; + bool operator <(const Icon&) const; + bool operator<=(const Icon&) const; +}; +} // namespace ConfigParserData +namespace WrtDB { +typedef std::list StringList; + +struct WidgetLocalizedInfo +{ + DPL::OptionalString name; + DPL::OptionalString shortName; + DPL::OptionalString description; + DPL::OptionalString license; + DPL::OptionalString licenseHref; +}; + +typedef std::list LanguageTagList; + +class WidgetDAO +{ + public: + /** + * WidgetDAO Exception classes + */ + class Exception + { + public: + DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) + DECLARE_EXCEPTION_TYPE(Base, DatabaseError) + DECLARE_EXCEPTION_TYPE(Base, ReadOnlyProperty) + DECLARE_EXCEPTION_TYPE(Base, GUIDisNull) + DECLARE_EXCEPTION_TYPE(Base, UnexpectedEmptyResult) + DECLARE_EXCEPTION_TYPE(Base, WidgetNotExist) + DECLARE_EXCEPTION_TYPE(Base, AlreadyRegistered) + }; + + protected: + DbWidgetHandle m_widgetHandle; + + public: + struct WidgetLocalizedIconRow + { + int appId; + int iconId; + DPL::String widgetLocale; + }; + typedef std::list WidgetLocalizedIconList; + + struct WidgetIconRow + { + int iconId; + int appId; + DPL::String iconSrc; + DPL::OptionalInt iconWidth; + DPL::OptionalInt iconHeight; + }; + typedef std::list WidgetIconList; + + struct WidgetStartFileRow + { + int startFileId; + int appId; + DPL::String src; + }; + typedef std::list WidgetStartFileList; + + struct WidgetLocalizedStartFileRow + { + int startFileId; + int appId; + DPL::String widgetLocale; + DPL::String type; + DPL::String encoding; + }; + typedef std::list LocalizedStartFileList; + + /** + * This is a constructor. + * + * @param[in] widgetHandle application id of widget. + */ + WidgetDAO(DbWidgetHandle widgetHandle) : + m_widgetHandle(widgetHandle) + {} + + /** + * Destructor + */ + virtual ~WidgetDAO(){} + + /** + * This method returns widget handle(m_widgetHandle). + * + * @return widget handle(m_widgetHandle). + * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. + * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in + * DB table. + */ + DbWidgetHandle getHandle() const + { + return m_widgetHandle; + } + DbWidgetHandle getHandle(const WidgetGUID GUID) const; + static DbWidgetHandle getHandle(const DPL::String tizenAppId); + + /** + * This method returns the root directory of widget resource. + * + * @return path name of root directory. + * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. + * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in + * DB table. + */ + DPL::String getPath() const; + void setPath(const DPL::String &path) const; + + /** + * This method returns the defaultlocale for the widget. + * + * @return defaultlocale + * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. + * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in + * DB table. + */ + DPL::OptionalString getDefaultlocale() const; + + /** + * This method returns list of localized icons files; + * + * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. + * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in + * DB table. + */ + WidgetLocalizedIconList getLocalizedIconList() const; + + /** + * This method returns list of icons files; + * + * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. + * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in + * DB table. + */ + WidgetIconList getIconList() const; + + /** + * This method returns list of localized start files; + * + * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. + * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in + * DB table. + */ + LocalizedStartFileList getLocalizedStartFileList() const; + void setLocalizedStartFileList(const LocalizedStartFileList &list) const; + /** + * This method returns list of start files; + * + * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. + * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in + * DB table. + */ + WidgetStartFileList getStartFileList() const; + void setStartFileList(const WidgetStartFileList &list) const; + + WidgetLocalizedInfo getLocalizedInfo(const DPL::String& languageTag) const; + + protected: + static std::map s_startFileMap; + static std::map s_localizedStartFileMap; + static std::map s_pathMap; +}; +} // namespace WrtDB + +#endif // _WRT_SRC_CONFIGURATION_WIDGET_DAO_READ_ONLY_H_ + diff --git a/tests/files_localization/mockup_src/widget_dao.cpp b/tests/files_localization/mockup_src/widget_dao.cpp new file mode 100644 index 0000000..170aad7 --- /dev/null +++ b/tests/files_localization/mockup_src/widget_dao.cpp @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/** + * This file contains the declaration of widget dao class. + * + * @file widget_dao_read_only.cpp + * @author Yang Jie (jie2.yang@samsung.com) + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @author Pawel Sikorski (p.sikorski@samsung.com) + * @version 1.0 + * @brief This file contains the declaration of widget dao + */ + +//#include "../mockup_include/dpl/wrt-dao-rw/widget_dao.h" +#include + +#include +#include +#include +#include + +namespace WrtDB { +std::map WidgetDAO::s_startFileMap; +std::map WidgetDAO::s_localizedStartFileMap; +std::map WidgetDAO::s_pathMap; + +DbWidgetHandle WidgetDAO::getHandle(const WidgetGUID /* GUID */) const +{ + LogError("Not impleneted!"); + return 0; +} + +DbWidgetHandle WidgetDAO::getHandle(const DPL::String /* tizenAppId */) +{ + LogError("Not implemented!"); + return 0; +} + +DPL::String WidgetDAO::getPath() const +{ + return s_pathMap[m_widgetHandle]; +} + +void WidgetDAO::setPath(const DPL::String &path) const +{ + s_pathMap[m_widgetHandle] = path; +} + +WidgetLocalizedInfo +WidgetDAO::getLocalizedInfo(const DPL::String& /* languageTag */) +const +{ + LogError("Not implemented!"); + return WidgetLocalizedInfo(); +} + +DPL::OptionalString WidgetDAO::getDefaultlocale() const +{ + LogError("Not implemented!"); + return DPL::OptionalString(); +} + +WidgetDAO::WidgetLocalizedIconList WidgetDAO::getLocalizedIconList() const +{ + LogError("Not implemented!"); + return WidgetLocalizedIconList(); +} + +WidgetDAO::WidgetIconList WidgetDAO::getIconList() const +{ + LogError("Not implemented!"); + return WidgetIconList(); +} + +WidgetDAO::LocalizedStartFileList WidgetDAO::getLocalizedStartFileList() const +{ + return s_localizedStartFileMap[m_widgetHandle]; +} + +void WidgetDAO::setLocalizedStartFileList(const LocalizedStartFileList &list) +const +{ + s_localizedStartFileMap[m_widgetHandle] = list; +} + +WidgetDAO::WidgetStartFileList WidgetDAO::getStartFileList() const +{ + return s_startFileMap[m_widgetHandle]; +} + +void WidgetDAO::setStartFileList(const WidgetStartFileList &list) const +{ + s_startFileMap[m_widgetHandle] = list; +} +} // namespace WrtDB diff --git a/tests/files_localization/test_localization.cpp b/tests/files_localization/test_localization.cpp new file mode 100644 index 0000000..42ffe3a --- /dev/null +++ b/tests/files_localization/test_localization.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file main.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of main + */ +#include + +int main(int argc, char *argv[]) +{ + return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); +} + diff --git a/tests/files_localization/test_suite01.cpp b/tests/files_localization/test_suite01.cpp new file mode 100644 index 0000000..d3cb174 --- /dev/null +++ b/tests/files_localization/test_suite01.cpp @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/** + * This file contains the declaration of widget dao class. + * + * @file test_suite01.cpp + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 1.0 + * @brief + */ + +#include +#include + +//#include "mockup_include/dpl/wrt-dao-rw/widget_dao.h" +#include +#include + +namespace { +WrtDB::LanguageTagList generateLanguageTags() +{ + WrtDB::LanguageTagList tags; + tags.push_back(L"pl-pl"); + tags.push_back(L"en-en"); + tags.push_back(L"pl-en"); + return tags; +} + +static const WrtDB::LanguageTagList languageTags = generateLanguageTags(); +static const DPL::String widget1Path = + L"/opt/share/widget/tests/localization/widget1/"; +static const DPL::String widget2Path = + L"/opt/share/widget/tests/localization/widget2/"; +} // anonymous namespace + +RUNNER_TEST(test01_getFilePathInWidgetPackageFromUrl){ + const int widgetHandle = 1; + WrtDB::WidgetDAO dao(widgetHandle); + //dao.setPath(widget1Path); + + auto result = W3CFileLocalization::getFilePathInWidgetPackageFromUrl( + widgetHandle, + languageTags, + L"widget://one"); + + RUNNER_ASSERT( + *result == + L"/opt/share/widget/tests/localization/widget1/locales/pl-en/one"); +} + +RUNNER_TEST(test02_getFilePathInWidgetPackageFromUrl){ + const int widgetHandle = 2; + WrtDB::WidgetDAO dao(widgetHandle); + //dao.setPath(widget2Path); + + auto result = W3CFileLocalization::getFilePathInWidgetPackageFromUrl( + widgetHandle, + languageTags, + L"widget://one"); + + RUNNER_ASSERT( + *result == + L"/opt/share/widget/tests/localization/widget2/locales/pl-en/one"); +} + +RUNNER_TEST(test03_getFilePathInWidgetPackageFromUrl){ + const int widgetHandle = 2; + WrtDB::WidgetDAO dao(widgetHandle); + //dao.setPath(widget2Path); + + auto result = W3CFileLocalization::getFilePathInWidgetPackageFromUrl( + widgetHandle, + languageTags, + L"widget://two"); + + RUNNER_ASSERT( + *result == + L"/opt/share/widget/tests/localization/widget2/locales/en-en/two"); +} + +RUNNER_TEST(test04_getFilePathInWidgetPackage){ + const int widgetHandle = 1; + WrtDB::WidgetDAO dao(widgetHandle); + //dao.setPath(widget1Path); + + auto result = W3CFileLocalization::getFilePathInWidgetPackage( + widgetHandle, + languageTags, + L"one"); + + RUNNER_ASSERT(*result == L"locales/pl-en/one"); +} + +RUNNER_TEST(test05_getFilePathInWidgetPackage){ + const int widgetHandle = 2; + WrtDB::WidgetDAO dao(widgetHandle); + //dao.setPath(widget2Path); + + auto result = W3CFileLocalization::getFilePathInWidgetPackage( + widgetHandle, + languageTags, + L"two"); + + RUNNER_ASSERT(*result == L"locales/en-en/two"); +} + diff --git a/tests/localizationTagsProvider/CMakeLists.txt b/tests/localizationTagsProvider/CMakeLists.txt new file mode 100644 index 0000000..fb3fee7 --- /dev/null +++ b/tests/localizationTagsProvider/CMakeLists.txt @@ -0,0 +1,42 @@ +# Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved +# +# 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. +# +# @file CMakeLists.txt +# @author Marcin Kaminski (marcin.ka@samsung.com) +# @author Karol Pawlowski (k.pawlowski@samsung.com) +# @version 1.0 +# @brief +# + +SET(LOCALIZATION_TESTS_DIR ${CMAKE_CURRENT_SOURCE_DIR}) + +PKG_CHECK_MODULES(TEST_PKGS + vconf + REQUIRED + ) + +WRT_INCLUDE_DIRECTORIES( + ${TEST_PKGS_INCLUDE_DIRS} + ${PROJECT_SOURCE_DIR}/modules/localization/include + ) + +WRT_LINK_DIRECTORIES(${TEST_PKGS_LIBRARY_DIRS}) +WRT_TARGET_LINK_LIBRARIES(${TEST_PKGS_LIBRARIES}) + +FILE(GLOB LOCALIZATION_TESTS_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/*testcases.cpp") + +SET(TARGET_LOCALIZATION_TEST "wrt-commons-tests-localization") +WRT_TEST_BUILD(${TARGET_LOCALIZATION_TEST} ${LOCALIZATION_TESTS_SOURCES} tests_miscunit.cpp) +WRT_TEST_INSTALL(${TARGET_LOCALIZATION_TEST}) + diff --git a/tests/localizationTagsProvider/Localization_testcases.cpp b/tests/localizationTagsProvider/Localization_testcases.cpp new file mode 100644 index 0000000..bd4b003 --- /dev/null +++ b/tests/localizationTagsProvider/Localization_testcases.cpp @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/** + * @file Localization_testcases.cpp + * @author Marcin Kaminski (marcin.ka@samsung.com) + * @version 1.0 + * @brief This file contains tests for localization related code. + */ + +#include +#include +#include + +#include + +RUNNER_TEST_GROUP_INIT(LanguageTagsProvider) + +RUNNER_TEST(tagsFromSystemLocales) +{ + LogInfo("Generating tags from system locales"); + + char* currlocals = vconf_get_str(VCONFKEY_LANGSET); + LogDebug("Locales fetched from system settings: " << currlocals); + RUNNER_ASSERT_MSG(!!currlocals, "NULL locales received from system"); + int result = vconf_set_str(VCONFKEY_LANGSET, "en_US.UTF-8"); + LogDebug("Returned vconf set execution status: " << result); + RUNNER_ASSERT_MSG(result == 0, "Invalid value returned by vconf_set_str on setting locales"); + + /* Ensure that system locales where fetched */ + LanguageTagsProviderSingleton::Instance().resetLanguageTags(); + LogDebug("Language tags set based on current system locales"); + + LanguageTags ltlist = LanguageTagsProviderSingleton::Instance().getLanguageTags(); + RUNNER_ASSERT_MSG(!ltlist.empty(), "Empty tag list returned"); + + /* Correct list generated from given locales should contain: "en-US", "en" and "" */ + LanguageTags correct; + correct.push_back(L"en-US"); + correct.push_back(L"en"); + correct.push_back(L""); + + RUNNER_ASSERT_MSG( correct==ltlist, "Received and expected language tags lists differ"); + + /* Restore system locales */ + result = vconf_set_str(VCONFKEY_LANGSET, currlocals); + RUNNER_ASSERT_MSG(result == 0, "Invalid value returned by vconf_set_str on restoring locales"); + LogDebug("System locales restored"); +} + +RUNNER_TEST(tagsFromGivenLocales) +{ + LogInfo("Generating tags from given locales"); + + const char *locales1 = "it_IT.UTF-8", *locales2="en_GB"; + + LogDebug("Using locales with codepage: " << locales1); + LanguageTagsProviderSingleton::Instance().setLanguageTagsFromLocales(locales1); + LanguageTags ltlist = LanguageTagsProviderSingleton::Instance().getLanguageTags(); + /* Correct list generated from given locales should contain: "it-IT", "it" and + * two default values: "en" and "" */ + LanguageTags correct; + correct.push_back(L"it-IT"); + correct.push_back(L"it"); + correct.push_back(L""); + RUNNER_ASSERT_MSG(correct==ltlist, "Received and expected language tags lists differ"); + + LogDebug("Using locales without codepage: " << locales2); + LanguageTagsProviderSingleton::Instance().setLanguageTagsFromLocales(locales2); + ltlist = LanguageTagsProviderSingleton::Instance().getLanguageTags(); + correct.clear(); + correct.push_back(L"en-GB"); + correct.push_back(L"en"); + correct.push_back(L""); + RUNNER_ASSERT_MSG(correct==ltlist, "Received and expected language tags lists differ"); +} + +RUNNER_TEST(tagsFromNullLocales) +{ + LogInfo("Generating tags when NULL locales given"); + + LanguageTagsProviderSingleton::Instance().setLanguageTagsFromLocales(NULL); + LanguageTags ltlist = LanguageTagsProviderSingleton::Instance().getLanguageTags(); + /* List with two values "en" and "" should be returned */ + LanguageTags correct; + correct.push_back(L""); + RUNNER_ASSERT_MSG(correct==ltlist, "Received and expected language tags lists differ"); +} + + +RUNNER_TEST(tagsFromGivenTagList) +{ + LogInfo("Copying given tags list"); + + LogDebug("Correct full list (with default values)"); + LanguageTags correct; + correct.push_back(L"de-DE"); + correct.push_back(L"de"); + correct.push_back(L""); + LanguageTagsProviderSingleton::Instance().setLanguageTags(correct); + LanguageTags result = LanguageTagsProviderSingleton::Instance().getLanguageTags(); + RUNNER_ASSERT_MSG(correct==result, "Received and expected language tags lists differ"); + + LogDebug("Tags list without default values)"); + LanguageTags nondef; + nondef.push_back(L"de-DE"); + nondef.push_back(L"de"); + LanguageTagsProviderSingleton::Instance().setLanguageTags(correct); + result = LanguageTagsProviderSingleton::Instance().getLanguageTags(); + + /* Received list should contains elements from input list with default + * values added (as "correct" list has) */ + RUNNER_ASSERT_MSG(!result.empty(), "Empty tags list should never be returned"); + RUNNER_ASSERT_MSG(nondef!=result, "Received list is same as given incomplete one"); + RUNNER_ASSERT_MSG(correct==result, "Received and expected language tags lists differ"); +} + +RUNNER_TEST(tagsFromEmptyList) +{ + LogInfo("Generating tags when empty tag list given"); + + LanguageTags input; + LanguageTagsProviderSingleton::Instance().setLanguageTags(input); + LanguageTags result = LanguageTagsProviderSingleton::Instance().getLanguageTags(); + RUNNER_ASSERT_MSG(!result.empty(), "Empty tags list should never be returned"); +} + +RUNNER_TEST(defaultWidgetLocale) +{ + LogInfo("Adding default widget locales to language tags list"); + + LanguageTags input; + input.push_back(L"de-DE"); + input.push_back(L"de"); + input.push_back(L""); + LanguageTagsProviderSingleton::Instance().setLanguageTags(input); + LanguageTagsProviderSingleton::Instance().addWidgetDefaultLocales(L"it"); + LanguageTags result = LanguageTagsProviderSingleton::Instance().getLanguageTags(); + RUNNER_ASSERT_MSG(result.size() == 4, "4 different language tags expected"); + LanguageTags reference; + reference.push_back(L"de-DE"); + reference.push_back(L"de"); + reference.push_back(L"it"); + reference.push_back(L""); + RUNNER_ASSERT_MSG(result == reference, "Received and expected language tags lists differ"); + LanguageTagsProviderSingleton::Instance().addWidgetDefaultLocales(L"it"); + LanguageTagsProviderSingleton::Instance().addWidgetDefaultLocales(L"de-DE"); + result = LanguageTagsProviderSingleton::Instance().getLanguageTags(); + RUNNER_ASSERT_MSG(result == reference, "Adding already included tag should not change tags list"); +} diff --git a/tests/localizationTagsProvider/README b/tests/localizationTagsProvider/README new file mode 100644 index 0000000..366e961 --- /dev/null +++ b/tests/localizationTagsProvider/README @@ -0,0 +1,13 @@ +Miscellaneous test suite +Unit tests (manifest files, wrt-api). Internal tests for new features in wrt. + +Binary file: wrt-tests-misc. Uses our test framework. Allows to use different +types of output. Text output shows results on console - green passed. +To run: +1. Install wrt-extra on target +2. Run wrt-tests-localization --output=text + +Automatic: YES +Included in Daily Build: NO +Included in Gerrit Builds: NO +Number of test cases: 75 \ No newline at end of file diff --git a/tests/localizationTagsProvider/tests_miscunit.cpp b/tests/localizationTagsProvider/tests_miscunit.cpp new file mode 100644 index 0000000..ba7a1d8 --- /dev/null +++ b/tests/localizationTagsProvider/tests_miscunit.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/** + * @file tests_miscunit.cpp + * @author Marcin Kaminski (marcin.ka@samsung.com) + * @version 1.0 + * @brief This is main file for miscellaneous unit tests (tests of different + * classes, namespaces and functions). + */ + +#include +#include + +int main (int argc, char *argv[]) +{ + LogInfo("Starting miscellaneous unit tests"); + int status = DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); + + return status; +} diff --git a/tests/test/CMakeLists.txt b/tests/test/CMakeLists.txt new file mode 100644 index 0000000..1c0bf55 --- /dev/null +++ b/tests/test/CMakeLists.txt @@ -0,0 +1,31 @@ +# Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved +# +# 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. +# +# @file CMakeLists.txt +# @author Bartlomiej Grzelewski (b.grzelewski@samsung.com) +# @version 1.0 +# @brief +# + +SET(TARGET_NAME "wrt-commons-tests-test-runner-child") + +# Set DPL tests sources +SET(DPL_TESTS_UTIL_SOURCES + ${TESTS_DIR}/test/main.cpp + ${TESTS_DIR}/test/runner_child.cpp +) + +#WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_NAME} ${TARGET_DPL_UTILS_EFL}) +WRT_TEST_BUILD(${TARGET_NAME} ${DPL_TESTS_UTIL_SOURCES}) +WRT_TEST_INSTALL(${TARGET_NAME}) diff --git a/tests/test/main.cpp b/tests/test/main.cpp new file mode 100644 index 0000000..42ffe3a --- /dev/null +++ b/tests/test/main.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file main.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of main + */ +#include + +int main(int argc, char *argv[]) +{ + return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); +} + diff --git a/tests/test/runner_child.cpp b/tests/test/runner_child.cpp new file mode 100644 index 0000000..d911270 --- /dev/null +++ b/tests/test/runner_child.cpp @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file widget_version.cpp + * @author Bartlomiej Grzelewski (b.grzelewski@samsung.com) + * @version 1.0 + * @brief Implementation file for test cases for engine internal tests + */ +#include +#include +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL_TESTS_TEST_CHILD) + +RUNNER_TEST(t00_pass) +{ + RUNNER_ASSERT_MSG(1, "This test should pass"); +} + +RUNNER_CHILD_TEST(t01_pass) +{ + RUNNER_ASSERT_MSG(1, "This test should pass"); +} + +RUNNER_CHILD_TEST(t02_fail) +{ + RUNNER_ASSERT_MSG(0, "This test should fail"); +} + +RUNNER_CHILD_TEST(t03_fail_timeout) +{ + sleep(20); + RUNNER_ASSERT_MSG(1, "This test should fail"); +} + +RUNNER_CHILD_TEST(t04_fail) +{ + RUNNER_ASSERT_MSG(1, "This test should fail"); + RUNNER_ASSERT_MSG(1, "This test should fail"); + RUNNER_ASSERT_MSG(1, "This test should fail"); + RUNNER_ASSERT_MSG(1, "This test should fail"); + RUNNER_ASSERT_MSG(0, "This test should fail"); +} + +RUNNER_CHILD_TEST(t05_fail_child_died) +{ + kill(getpid(), SIGKILL); + RUNNER_ASSERT_MSG(1, "This test should fail"); +} + +RUNNER_CHILD_TEST(t06_pass_8_second_test) +{ + sleep(8); + RUNNER_ASSERT_MSG(1, "This test should pass"); +} + +RUNNER_CHILD_TEST(t07_fail_unknown_exception) +{ + throw("hello"); +} + +RUNNER_CHILD_TEST(t08_fail_unknown_exception) +{ + throw(1); +} + +RUNNER_CHILD_TEST(t09_fail_you_should_see_text_normal_assert) +{ + RUNNER_ASSERT_MSG(0, "Normal assert"); +} + +RUNNER_CHILD_TEST(t10_pass) +{ + RUNNER_ASSERT_MSG(1, "Normal assert"); +} + diff --git a/tests/unit_tests/CMakeLists.txt b/tests/unit_tests/CMakeLists.txt deleted file mode 100644 index 9dfb50f..0000000 --- a/tests/unit_tests/CMakeLists.txt +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved -# -# 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. -# -# @file CMakeLists.txt -# @author Lukasz Marek (l.marek@samsung.com) -# - -ADD_SUBDIRECTORY(misc_unit) diff --git a/tests/unit_tests/misc_unit/CMakeLists.txt b/tests/unit_tests/misc_unit/CMakeLists.txt deleted file mode 100644 index 8429573..0000000 --- a/tests/unit_tests/misc_unit/CMakeLists.txt +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved -# -# 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. -# -# @file CMakeLists.txt -# @author Marcin Kaminski (marcin.ka@samsung.com) -# @author Karol Pawlowski (k.pawlowski@samsung.com) -# @version 1.0 -# @brief -# - -SET(MISCUNIT_TESTS_DIR ${CMAKE_CURRENT_SOURCE_DIR}) - -PKG_CHECK_MODULES(TEST_PKGS - vconf - REQUIRED - ) - -WRT_INCLUDE_DIRECTORIES( - ${TEST_PKGS_INCLUDE_DIRS} - ${PROJECT_SOURCE_DIR}/modules/localization/include - ) - -WRT_LINK_DIRECTORIES(${TEST_PKGS_LIBRARY_DIRS}) -WRT_TARGET_LINK_LIBRARIES(${TEST_PKGS_LIBRARIES}) - -FILE(GLOB MISCUNIT_TESTS_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/*testcases.cpp") - -# target wrt-test-miscunit -SET(TARGET_MISCUNIT_TEST "wrt-tests-localization") -WRT_TEST_BUILD(${TARGET_MISCUNIT_TEST} ${MISCUNIT_TESTS_SOURCES} tests_miscunit.cpp) -WRT_TEST_INSTALL(${TARGET_MISCUNIT_TEST}) - diff --git a/tests/unit_tests/misc_unit/Localization_testcases.cpp b/tests/unit_tests/misc_unit/Localization_testcases.cpp deleted file mode 100644 index bd4b003..0000000 --- a/tests/unit_tests/misc_unit/Localization_testcases.cpp +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/** - * @file Localization_testcases.cpp - * @author Marcin Kaminski (marcin.ka@samsung.com) - * @version 1.0 - * @brief This file contains tests for localization related code. - */ - -#include -#include -#include - -#include - -RUNNER_TEST_GROUP_INIT(LanguageTagsProvider) - -RUNNER_TEST(tagsFromSystemLocales) -{ - LogInfo("Generating tags from system locales"); - - char* currlocals = vconf_get_str(VCONFKEY_LANGSET); - LogDebug("Locales fetched from system settings: " << currlocals); - RUNNER_ASSERT_MSG(!!currlocals, "NULL locales received from system"); - int result = vconf_set_str(VCONFKEY_LANGSET, "en_US.UTF-8"); - LogDebug("Returned vconf set execution status: " << result); - RUNNER_ASSERT_MSG(result == 0, "Invalid value returned by vconf_set_str on setting locales"); - - /* Ensure that system locales where fetched */ - LanguageTagsProviderSingleton::Instance().resetLanguageTags(); - LogDebug("Language tags set based on current system locales"); - - LanguageTags ltlist = LanguageTagsProviderSingleton::Instance().getLanguageTags(); - RUNNER_ASSERT_MSG(!ltlist.empty(), "Empty tag list returned"); - - /* Correct list generated from given locales should contain: "en-US", "en" and "" */ - LanguageTags correct; - correct.push_back(L"en-US"); - correct.push_back(L"en"); - correct.push_back(L""); - - RUNNER_ASSERT_MSG( correct==ltlist, "Received and expected language tags lists differ"); - - /* Restore system locales */ - result = vconf_set_str(VCONFKEY_LANGSET, currlocals); - RUNNER_ASSERT_MSG(result == 0, "Invalid value returned by vconf_set_str on restoring locales"); - LogDebug("System locales restored"); -} - -RUNNER_TEST(tagsFromGivenLocales) -{ - LogInfo("Generating tags from given locales"); - - const char *locales1 = "it_IT.UTF-8", *locales2="en_GB"; - - LogDebug("Using locales with codepage: " << locales1); - LanguageTagsProviderSingleton::Instance().setLanguageTagsFromLocales(locales1); - LanguageTags ltlist = LanguageTagsProviderSingleton::Instance().getLanguageTags(); - /* Correct list generated from given locales should contain: "it-IT", "it" and - * two default values: "en" and "" */ - LanguageTags correct; - correct.push_back(L"it-IT"); - correct.push_back(L"it"); - correct.push_back(L""); - RUNNER_ASSERT_MSG(correct==ltlist, "Received and expected language tags lists differ"); - - LogDebug("Using locales without codepage: " << locales2); - LanguageTagsProviderSingleton::Instance().setLanguageTagsFromLocales(locales2); - ltlist = LanguageTagsProviderSingleton::Instance().getLanguageTags(); - correct.clear(); - correct.push_back(L"en-GB"); - correct.push_back(L"en"); - correct.push_back(L""); - RUNNER_ASSERT_MSG(correct==ltlist, "Received and expected language tags lists differ"); -} - -RUNNER_TEST(tagsFromNullLocales) -{ - LogInfo("Generating tags when NULL locales given"); - - LanguageTagsProviderSingleton::Instance().setLanguageTagsFromLocales(NULL); - LanguageTags ltlist = LanguageTagsProviderSingleton::Instance().getLanguageTags(); - /* List with two values "en" and "" should be returned */ - LanguageTags correct; - correct.push_back(L""); - RUNNER_ASSERT_MSG(correct==ltlist, "Received and expected language tags lists differ"); -} - - -RUNNER_TEST(tagsFromGivenTagList) -{ - LogInfo("Copying given tags list"); - - LogDebug("Correct full list (with default values)"); - LanguageTags correct; - correct.push_back(L"de-DE"); - correct.push_back(L"de"); - correct.push_back(L""); - LanguageTagsProviderSingleton::Instance().setLanguageTags(correct); - LanguageTags result = LanguageTagsProviderSingleton::Instance().getLanguageTags(); - RUNNER_ASSERT_MSG(correct==result, "Received and expected language tags lists differ"); - - LogDebug("Tags list without default values)"); - LanguageTags nondef; - nondef.push_back(L"de-DE"); - nondef.push_back(L"de"); - LanguageTagsProviderSingleton::Instance().setLanguageTags(correct); - result = LanguageTagsProviderSingleton::Instance().getLanguageTags(); - - /* Received list should contains elements from input list with default - * values added (as "correct" list has) */ - RUNNER_ASSERT_MSG(!result.empty(), "Empty tags list should never be returned"); - RUNNER_ASSERT_MSG(nondef!=result, "Received list is same as given incomplete one"); - RUNNER_ASSERT_MSG(correct==result, "Received and expected language tags lists differ"); -} - -RUNNER_TEST(tagsFromEmptyList) -{ - LogInfo("Generating tags when empty tag list given"); - - LanguageTags input; - LanguageTagsProviderSingleton::Instance().setLanguageTags(input); - LanguageTags result = LanguageTagsProviderSingleton::Instance().getLanguageTags(); - RUNNER_ASSERT_MSG(!result.empty(), "Empty tags list should never be returned"); -} - -RUNNER_TEST(defaultWidgetLocale) -{ - LogInfo("Adding default widget locales to language tags list"); - - LanguageTags input; - input.push_back(L"de-DE"); - input.push_back(L"de"); - input.push_back(L""); - LanguageTagsProviderSingleton::Instance().setLanguageTags(input); - LanguageTagsProviderSingleton::Instance().addWidgetDefaultLocales(L"it"); - LanguageTags result = LanguageTagsProviderSingleton::Instance().getLanguageTags(); - RUNNER_ASSERT_MSG(result.size() == 4, "4 different language tags expected"); - LanguageTags reference; - reference.push_back(L"de-DE"); - reference.push_back(L"de"); - reference.push_back(L"it"); - reference.push_back(L""); - RUNNER_ASSERT_MSG(result == reference, "Received and expected language tags lists differ"); - LanguageTagsProviderSingleton::Instance().addWidgetDefaultLocales(L"it"); - LanguageTagsProviderSingleton::Instance().addWidgetDefaultLocales(L"de-DE"); - result = LanguageTagsProviderSingleton::Instance().getLanguageTags(); - RUNNER_ASSERT_MSG(result == reference, "Adding already included tag should not change tags list"); -} diff --git a/tests/unit_tests/misc_unit/README b/tests/unit_tests/misc_unit/README deleted file mode 100644 index 366e961..0000000 --- a/tests/unit_tests/misc_unit/README +++ /dev/null @@ -1,13 +0,0 @@ -Miscellaneous test suite -Unit tests (manifest files, wrt-api). Internal tests for new features in wrt. - -Binary file: wrt-tests-misc. Uses our test framework. Allows to use different -types of output. Text output shows results on console - green passed. -To run: -1. Install wrt-extra on target -2. Run wrt-tests-localization --output=text - -Automatic: YES -Included in Daily Build: NO -Included in Gerrit Builds: NO -Number of test cases: 75 \ No newline at end of file diff --git a/tests/unit_tests/misc_unit/tests_miscunit.cpp b/tests/unit_tests/misc_unit/tests_miscunit.cpp deleted file mode 100644 index ba7a1d8..0000000 --- a/tests/unit_tests/misc_unit/tests_miscunit.cpp +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved - * - * 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. - */ -/** - * @file tests_miscunit.cpp - * @author Marcin Kaminski (marcin.ka@samsung.com) - * @version 1.0 - * @brief This is main file for miscellaneous unit tests (tests of different - * classes, namespaces and functions). - */ - -#include -#include - -int main (int argc, char *argv[]) -{ - LogInfo("Starting miscellaneous unit tests"); - int status = DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); - - return status; -} diff --git a/tests/unused/test_caller.cpp b/tests/unused/test_caller.cpp new file mode 100644 index 0000000..6f1a1ff --- /dev/null +++ b/tests/unused/test_caller.cpp @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_address.cpp + * @author Tomasz Swierczek (t.swierczek@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of caller tests + */ + +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +// test stream class +class BinaryStream : public DPL::IStream +{ + public: + virtual void Read(size_t num, void * bytes) + { + for (unsigned i = 0; i < num; ++i) { + ((unsigned char*)bytes)[i] = data[i + readPosition]; + } + readPosition += num; + } + virtual void Write(size_t num, const void * bytes) + { + for (unsigned i = 0; i < num; ++i) { + data.push_back(((unsigned char*)bytes)[i]); + } + } + BinaryStream() + { + readPosition = 0; + } + virtual ~BinaryStream(){} + + private: + std::vector data; + unsigned readPosition; +}; + +static int return_func(int a, bool b) +{ + if (b) { + return a; + } else { + return 0; + } +} + +static int called = 0; + +static void void_func(int a) +{ + called = a; +} + +static struct VoidDelegate +{ + void operator()(int a) + { + called = a; + } +} voidDelegate; + +static struct ReturnDelegate +{ + int operator()(int a) + { + return a; + } +} returnDelegate; + +RUNNER_TEST(Caller_function_void) +{ + int a = 23; + BinaryStream stream; + DPL::Serialization::Serialize(stream, a); + called = 0; + DPL::Caller::Call(stream, void_func); + RUNNER_ASSERT(called == a); +} + +RUNNER_TEST(Caller_function_return) +{ + int a = 23; + bool b = true; + BinaryStream stream; + DPL::Serialization::Serialize(stream, a); + DPL::Serialization::Serialize(stream, b); + int result = DPL::Caller::Call(stream, return_func); + RUNNER_ASSERT(result == a); +} + +RUNNER_TEST(Caller_delegate_void) +{ + int a = 23; + BinaryStream stream; + called = 0; + DPL::Serialization::Serialize(stream, a); + DPL::Caller::CallDelegate(stream, voidDelegate); + RUNNER_ASSERT(called == a); +} + +RUNNER_TEST(Caller_delegate_return) +{ + int a = 23; + BinaryStream stream; + called = 0; + DPL::Serialization::Serialize(stream, a); + int result = 0; + DPL::Caller::CallDelegate(stream, returnDelegate, result); + RUNNER_ASSERT(result == a); +} diff --git a/tests/unused/test_crypto_hash.cpp b/tests/unused/test_crypto_hash.cpp new file mode 100644 index 0000000..dd208b6 --- /dev/null +++ b/tests/unused/test_crypto_hash.cpp @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_crypto_hash.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test crypto hash + */ +#include +#include +RUNNER_TEST_GROUP_INIT(DPL) + +#define TEST_CRYPTO_HASH(Class, Input, Output) \ + Class crypto; \ + crypto.Append(Input); \ + crypto.Finish(); \ + RUNNER_ASSERT(crypto.ToString() == Output); + +RUNNER_TEST(CryptoHash_MD2) +{ + TEST_CRYPTO_HASH(DPL::Crypto::Hash::MD2, + "sample_input_string", + "c9f26439c9882cccc98467dbdf07b1fc"); +} + +RUNNER_TEST(CryptoHash_MD4) +{ + TEST_CRYPTO_HASH(DPL::Crypto::Hash::MD4, + "sample_input_string", + "8cd0720f7ec98c8e5f008afb54054677"); +} + +RUNNER_TEST(CryptoHash_MD5) +{ + TEST_CRYPTO_HASH(DPL::Crypto::Hash::MD5, + "sample_input_string", + "eb7ae4f28fecbd1fd777d9b7495fc8ec"); +} + +RUNNER_TEST(CryptoHash_SHA) +{ + TEST_CRYPTO_HASH(DPL::Crypto::Hash::SHA, + "sample_input_string", + "0a5725f3586616a4049730f3ba14c8aeda79ab21"); +} + +RUNNER_TEST(CryptoHash_SHA1) +{ + TEST_CRYPTO_HASH(DPL::Crypto::Hash::SHA1, + "sample_input_string", + "be0ed9040af0c2b772b2dd0776f6966b5f4d1206"); +} + +RUNNER_TEST(CryptoHash_DSS) +{ + TEST_CRYPTO_HASH(DPL::Crypto::Hash::DSS, + "sample_input_string", + "be0ed9040af0c2b772b2dd0776f6966b5f4d1206"); +} + +RUNNER_TEST(CryptoHash_DSS1) +{ + TEST_CRYPTO_HASH(DPL::Crypto::Hash::DSS1, + "sample_input_string", + "be0ed9040af0c2b772b2dd0776f6966b5f4d1206"); +} + +RUNNER_TEST(CryptoHash_ECDSA) +{ + TEST_CRYPTO_HASH(DPL::Crypto::Hash::ECDSA, + "sample_input_string", + "be0ed9040af0c2b772b2dd0776f6966b5f4d1206"); +} + +RUNNER_TEST(CryptoHash_SHA224) +{ + TEST_CRYPTO_HASH(DPL::Crypto::Hash::SHA224, + "sample_input_string", + "d4dde2370eb869f6e790133b94d58e45417392b9d899af883a274011"); +} + +RUNNER_TEST(CryptoHash_SHA256) +{ + TEST_CRYPTO_HASH( + DPL::Crypto::Hash::SHA256, + "sample_input_string", + "a470ec7c783ac51f9eb1772132e6bde1a053bbc81650719dd0ac62ecd93caf12"); +} + +RUNNER_TEST(CryptoHash_SHA384) +{ + TEST_CRYPTO_HASH( + DPL::Crypto::Hash::SHA384, + "sample_input_string", + "63d8bfa95c95c6906d1816965431c065278a655c60f786c9b246c1f73ba7ac557007f5064ba54ebd3a1988e6f37baa97"); +} + +RUNNER_TEST(CryptoHash_SHA512) +{ + TEST_CRYPTO_HASH( + DPL::Crypto::Hash::SHA512, + "sample_input_string", + "799317a140741937d9e5d8dbf9d3045d2c220de5ac33b3d5897acf873291ed14379eb15ef406d2284313d40edb0e01affac8efeb01cb47c2042e3e62a4a83d7d"); +} diff --git a/tests/unused/test_message_queue.cpp b/tests/unused/test_message_queue.cpp new file mode 100644 index 0000000..3322413 --- /dev/null +++ b/tests/unused/test_message_queue.cpp @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_message_queue.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of message queue tests + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +DECLARE_GENERIC_EVENT_0(QuitEvent) + +class QuitController : + public DPL::Controller::Type>, + public DPL::ApplicationExt +{ + public: + QuitController() : DPL::ApplicationExt(1, NULL, "test-app") + { + Touch(); + } + + protected: + virtual void OnEventReceived(const QuitEvent &) + { + Quit(); + } +}; + +RUNNER_TEST_GROUP_INIT(DPL) + +class CopyThread : + public DPL::Thread +{ + private: + bool m_success; + DPL::AbstractWaitableInput *m_input; + DPL::AbstractWaitableOutput *m_output; + std::size_t m_dataSize; + + public: + CopyThread(DPL::AbstractWaitableInput *input, + DPL::AbstractWaitableOutput *output, + std::size_t dataSize) : + m_success(true), + m_input(input), + m_output(output), + m_dataSize(dataSize) + { + LogInfo("Thread created"); + } + + protected: + virtual int ThreadEntry() + { + LogInfo("Entering copy thread"); + + Try + { + DPL::Copy(m_input, m_output, m_dataSize); + } + Catch(DPL::CopyFailed) + { + m_success = false; + + LogWarning("Copy failed!"); + return 0; + } + + LogInfo("Copy finished"); + return 0; + } +}; + +inline std::string BinaryQueueToString(const DPL::BinaryQueue &queue) +{ + char *buffer = new char[queue.Size()]; + queue.Flatten(buffer, queue.Size()); + std::string result = std::string(buffer, buffer + queue.Size()); + delete[] buffer; + return result; +} + +RUNNER_TEST(MessageQueue_DoubleCopy) +{ + DPL::BinaryQueue dataA; + DPL::MessageQueue dataB("/test_mqueue_dataB", true, false, 0660, true); + DPL::MessageQueue dataC("/test_mqueue_dataC", true, false, 0660, true); + DPL::BinaryQueue dataD; + + DPL::AbstractWaitableInputAdapter dataAdapterA(&dataA); + DPL::AbstractWaitableOutputAdapter dataAdapterD(&dataD); + + const std::string testData = + "Lorem ipsum dolor sit amet, consectetur adipiscing elit." + "Cras elementum venenatis velit, sit amet vehicula odio gravida a." + "Curabitur id nibh id ante adipiscing sollicitudin." + "Maecenas in tellus vel augue vehicula pharetra hendrerit cursus est." + "" + "Ut malesuada quam porttitor dui euismod lacinia." + "Phasellus quis lectus sed lectus dictum tincidunt et vitae leo." + "Fusce id est massa, condimentum bibendum urna." + "Donec venenatis quam eget sapien vulputate egestas." + "Maecenas scelerisque lorem a neque molestie a varius erat condimentum." + "Maecenas varius hendrerit ligula, sed iaculis justo pretium id." + "Nunc sit amet nisl vitae justo tristique suscipit id eget tortor." + "" + "Pellentesque sollicitudin nulla at metus dapibus tincidunt." + "Integer consequat justo eget dui imperdiet iaculis." + "Sed vestibulum ipsum vitae libero accumsan non molestie metus adipiscing." + "" + "Vivamus quis dui enim, in blandit urna." + "In imperdiet lacus at orci elementum a scelerisque dui blandit." + "Donec vulputate enim metus, eget convallis ante." + "Etiam mollis enim eget eros pulvinar nec sagittis justo fermentum." + "" + "Vestibulum sed nunc eu leo lobortis ultrices." + "Nullam placerat nulla et est blandit nec interdum nunc pulvinar." + "Vivamus a lectus eget dui fermentum hendrerit."; + + QuitController quitter; + quitter.PostTimedEvent(QuitEvent(), 1.0); + + CopyThread threadA(&dataAdapterA, &dataB, testData.size()); + CopyThread threadB(&dataB, &dataC, testData.size()); + CopyThread threadC(&dataC, &dataAdapterD, testData.size()); + + dataA.AppendCopy(testData.c_str(), testData.size()); + + threadA.Run(); + threadB.Run(); + threadC.Run(); + + quitter.Exec(); + + threadA.Quit(); + threadB.Quit(); + threadC.Quit(); + + // Now, test data should be in dataD + RUNNER_ASSERT(BinaryQueueToString(dataD) == testData); +} diff --git a/tests/unused/test_shm.cpp b/tests/unused/test_shm.cpp new file mode 100644 index 0000000..4f2d93a --- /dev/null +++ b/tests/unused/test_shm.cpp @@ -0,0 +1,1664 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_shm.h + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 1.0 + * @brief Implementation file for test cases for shared data framework + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +using namespace DPL; + +namespace { +const SharedMemory::Key SHM_KEY = 12345; +const char* SEM_NAME = "/wrt_engine_shared_object_semaphore"; +const size_t VERSION = 1; + +const size_t MAX_THREADS = 10; +const size_t TEST_AND_SET_REPEATS = 100; + +const size_t SHARED_PROP_REPEATS = 3; + +const size_t SINGLETON_TEST_REPEATS = 3; + +// maximum random delay in singleton listener addition/removal +const size_t MAX_SINGLETON_LISTENER_DELAY = 50; + +const int SINGLE_PROCESS_REPEATS = 50; + +/* + * 5 seconds expected timeout for waitable events + * 30 seconds unexpected timeout for waitable events + * We don't want to block tests + */ +const size_t EXPECTED_WAITABLE_TIMEOUT = 5 * 1000; +const size_t UNEXPECTED_WAITABLE_TIMEOUT = 30 * 1000; + +bool g_enumTestCorrect = false; +bool g_enumTestIncorrect = false; +size_t g_delegateCalls = 0; + +void Wait(DPL::WaitableEvent& event, bool expectedTimeout = false) +{ + LogDebug("WaitForSingleHandle..."); + DPL::WaitableHandleIndexList list = DPL::WaitForSingleHandle( + event.GetHandle(), + expectedTimeout ? + EXPECTED_WAITABLE_TIMEOUT : UNEXPECTED_WAITABLE_TIMEOUT); + if (list.size() == 0) { + LogDebug("...timeout."); + } else { + LogDebug("...signaled."); + event.Reset(); + } + + if (expectedTimeout) { + RUNNER_ASSERT(list.size() == 0); + } else { + RUNNER_ASSERT(list.size() == 1); + } +} + +void RemoveIpcs() +{ + Try { + SharedMemory::Remove(SHM_KEY); + } + Catch(SharedMemory::Exception::RemoveFailed) { + // ignore + } + + Try { + DPL::Semaphore::Remove(SEM_NAME); + } + Catch(DPL::Semaphore::Exception::RemoveFailed) { + // ignore + } +} + +typedef DPL::TypeListDecl::Type TestTypeList; +typedef DPL::TypeListDecl::Type TestTypeList2; +typedef DPL::TypeListDecl::Type TestTypeList3; + +typedef SharedObject TestSharedObject; +typedef SharedObject TestSharedObject2; +typedef SharedObject TestSharedObject3; + +typedef std::shared_ptr TestSharedObjectPtr; + +const int INIT_EVENT = 0; +const int DESTROY_EVENT = 1; + +int g_values[TestTypeList::Size]; + +/* + * helper listening controller + */ +template +class ListeningController : + public DPL::Controller::Type> +{ + public: + explicit ListeningController(DPL::WaitableEvent* waitable); + ~ListeningController(); + + virtual void OnEventReceived(const int &event); + + virtual void OnEvent(const int /*event*/) {} + + protected: + std::shared_ptr m_so; + DPL::Thread m_thread; + DPL::WaitableEvent* m_waitable; +}; + +template +ListeningController::ListeningController( + DPL::WaitableEvent* waitable) : + m_waitable(waitable) +{ + Touch(); + m_thread.Run(); + SwitchToThread(&m_thread); + PostEvent(INIT_EVENT); +} + +template +ListeningController::~ListeningController() +{ + m_thread.Quit(); +} + +template +void ListeningController::OnEventReceived(const int& event) +{ + if (event == INIT_EVENT) { + m_so = SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + OnEvent(event); + m_waitable->Signal(); + } else if (event == DESTROY_EVENT) { + LogDebug("Destroying shared object"); + OnEvent(event); + + // deregister, destroy ad notify main thread + m_so.Reset(); + LogDebug("4"); + m_waitable->Signal(); + LogDebug("5"); + } else { + OnEvent(event); + } +} + +typedef DPL::TypeListDecl::Type SharedTypeList; + +class TestSharedObject4; +typedef std::shared_ptr TestSharedObject4Ptr; + +class TestSharedObject4 : public SharedObject +{ + public: + enum + { + SIZE_T, + BOOLEAN + }; + + static TestSharedObject4Ptr Create() + { + return SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + } + + ~TestSharedObject4() + { + LogDebug("dtor"); + } + + protected: + explicit TestSharedObject4(const std::string& semaphore) : + SharedObject(semaphore) + {} + + private: + void Init() + { + SetPropertyInternal(false); + } + friend class SharedObjectFactory; +}; +} // anonymus namespace + +////////////////////////////////////////////// + +RUNNER_TEST(SharedMemory_002_AccessByType) +{ + RemoveIpcs(); + + SharedData str; + + // access by type + str.Embedded<0, int>::value = 4; + str.Embedded<1, int>::value = 5; + str.Embedded<2, char>::value = 'd'; + str.Embedded<3, int[64]>::value[0] = 1; + str.Embedded<3, int[64]>::value[1] = 20; + + RUNNER_ASSERT((str.Embedded<0, int>::value) == 4); + RUNNER_ASSERT((str.Embedded<1, int>::value) == 5); + RUNNER_ASSERT((str.Embedded<2, char>::value) == 'd'); + RUNNER_ASSERT((str.Embedded<3, int[64]>::value[0]) == 1); + RUNNER_ASSERT((str.Embedded<3, int[64]>::value[1]) == 20); +} + +////////////////////////////////////////////// + +RUNNER_TEST(SharedMemory_003_AccessByIndex) +{ + RemoveIpcs(); + + SharedData str; + // access by enum + str.Embedded<0, TestTypeList::Element<0>::Type>::value = 4; + str.Embedded<1, TestTypeList::Element<1>::Type>::value = 5; + str.Embedded<2, TestTypeList::Element<2>::Type>::value = 'd'; + str.Embedded<3, TestTypeList::Element<3>::Type>::value[0] = 1; + str.Embedded<3, TestTypeList::Element<3>::Type>::value[1] = 20; + + RUNNER_ASSERT( + (str.Embedded<0, TestTypeList::Element<0>::Type>::value) == 4); + RUNNER_ASSERT( + (str.Embedded<1, TestTypeList::Element<1>::Type>::value) == 5); + RUNNER_ASSERT( + (str.Embedded<2, TestTypeList::Element<2>::Type>::value) == 'd'); + RUNNER_ASSERT( + (str.Embedded<3, TestTypeList::Element<3>::Type>::value[0]) == 1); + RUNNER_ASSERT( + (str.Embedded<3, TestTypeList::Element<3>::Type>::value[1]) == 20); +} + +////////////////////////////////////////////// + +RUNNER_TEST(SharedMemory_004_SimplifiedAccess) +{ + RemoveIpcs(); + + SharedData str; + + // access via PropertyRef + str.PropertyRef<1>() = 3; + RUNNER_ASSERT(str.PropertyRef<1>() == 3); + + int (&array)[64] = str.PropertyRef<3>(); + array[0] = 2; + RUNNER_ASSERT(str.PropertyRef<3>()[0] == 2); + + str.PropertyRef<3>()[1] = 19; + RUNNER_ASSERT(str.PropertyRef<3>()[1] == 19); + + // access via macro + str.SHARED_PROPERTY(0) = 2; + RUNNER_ASSERT(str.SHARED_PROPERTY(0) == 2); + + str.SHARED_PROPERTY(2) = 'c'; + RUNNER_ASSERT(str.SHARED_PROPERTY(2) == 'c'); + + str.SHARED_PROPERTY(3)[2] = 10; + RUNNER_ASSERT(str.SHARED_PROPERTY(3)[2] == 10); + + // old style check + RUNNER_ASSERT((str.Embedded<0, int>::value) == 2); + RUNNER_ASSERT((str.Embedded<1, int>::value) == 3); + RUNNER_ASSERT((str.Embedded<2, char>::value) == 'c'); + RUNNER_ASSERT((str.Embedded<3, int[64]>::value[0]) == 2); + RUNNER_ASSERT((str.Embedded<3, int[64]>::value[1]) == 19); + RUNNER_ASSERT((str.Embedded<3, int[64]>::value[2]) == 10); +} + +////////////////////////////////////////////// + +struct SharedStruct +{ + int a; + int b; + char c; + int d[64]; +}; + +typedef std::shared_ptr > SharedStructPtr; + +RUNNER_TEST(SharedMemory_010_BaseShmTest) +{ + RemoveIpcs(); + + typedef std::unique_ptr SharedMemoryPtr; + + // write + SharedMemoryPtr shm; + Try { + shm.Reset(SharedMemory::Create(SHM_KEY, false)); + } + Catch(SharedMemory::Exception::NotFound) { + shm.Reset(SharedMemory::Create(SHM_KEY, true, true)); + } + + SharedStructPtr str = shm->Attach(); + + str->Data()->a = 1; + str->Data()->b = 2; + str->Data()->c = '3'; + str->Data()->d[0] = 4; + str->Data()->d[1] = 5; + + // read + SharedMemoryPtr shm2; + Try { + shm2.Reset(SharedMemory::Create(SHM_KEY, false)); + } + Catch(SharedMemory::Exception::NotFound) { + shm2.Reset(SharedMemory::Create(SHM_KEY, true, true)); + } + + SharedStructPtr str2 = shm2->Attach(); + SharedStructPtr str3 = shm2->Attach(); + + RUNNER_ASSERT(str2->Data()->a == 1); + RUNNER_ASSERT(str2->Data()->b == 2); + RUNNER_ASSERT(str2->Data()->c == '3'); + RUNNER_ASSERT(str2->Data()->d[0] == 4); + RUNNER_ASSERT(str2->Data()->d[1] == 5); + + RUNNER_ASSERT(str3->Data()->a == 1); + RUNNER_ASSERT(str3->Data()->b == 2); + RUNNER_ASSERT(str3->Data()->c == '3'); + RUNNER_ASSERT(str3->Data()->d[0] == 4); + RUNNER_ASSERT(str3->Data()->d[1] == 5); + + str2->Data()->b = 4; + str2->Data()->c = 'c'; + str2->Data()->d[0] = 0; + RUNNER_ASSERT(str3->Data()->a == 1); + RUNNER_ASSERT(str3->Data()->b == 4); + RUNNER_ASSERT(str3->Data()->c == 'c'); + RUNNER_ASSERT(str3->Data()->d[0] == 0); + RUNNER_ASSERT(str3->Data()->d[1] == 5); +} + +////////////////////////////////////////////// + +RUNNER_TEST(SharedMemory_020_SharedObjectTest) +{ + RemoveIpcs(); + + typedef SharedObject MySharedObj; + + MySharedObj::Ptr so = + SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + + RUNNER_ASSERT((so->GetProperty<0, size_t>()) == 0); + so->SetProperty<0, size_t>(4); + RUNNER_ASSERT((so->GetProperty<0, size_t>()) == 4); +} + +////////////////////////////////////////////// + +class InitTestSharedObject : public TestSharedObject +{ + protected: + explicit InitTestSharedObject(const std::string& semaphore) : + TestSharedObject(semaphore) {} + + virtual void Init(); // from SharedObject + + private: + friend class SharedObjectFactory; +}; + +void InitTestSharedObject::Init() +{ + SetPropertyInternal<0>(1); + SetPropertyInternal<1>(2); + SetPropertyInternal<2>('c'); +} + +RUNNER_TEST(SharedMemory_021_InitTest) +{ + RemoveIpcs(); // we need non existing shm + + std::shared_ptr sho = + SharedObjectFactory::Create( + SHM_KEY, SEM_NAME); + RUNNER_ASSERT((sho->GetProperty<0, int>()) == 1); + RUNNER_ASSERT((sho->GetProperty<1, int>()) == 2); + RUNNER_ASSERT((sho->GetProperty<2, char>()) == 'c'); +} + +////////////////////////////////////////////// + +class VersionTestSO1 : public TestSharedObject +{ + protected: + explicit VersionTestSO1(const std::string& semaphore) : + TestSharedObject(semaphore) {} + + virtual SizeType GetVersion() const + { + return 1; + } // from SharedObject + + private: + friend class SharedObjectFactory; +}; + +class VersionTestSO2 : public TestSharedObject +{ + protected: + explicit VersionTestSO2(const std::string& semaphore) : + TestSharedObject(semaphore) {} + + virtual SizeType GetVersion() const + { + return 2; + } // from SharedObject + + private: + friend class SharedObjectFactory; +}; + +RUNNER_TEST(SharedMemory_022_InvalidVersionTest) +{ + RemoveIpcs(); // we need non existing shm + + std::shared_ptr sho = + SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + + Try { + std::shared_ptr sho2 = + SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + + RUNNER_ASSERT_MSG(false, "Invalid shm version has been accepted"); + } + Catch(SharedObjectBase::Exception::InvalidVersion) { + RUNNER_ASSERT(true); + } +} + +////////////////////////////////////////////// + +RUNNER_TEST(SharedMemory_023_InvalidSizeTest) +{ + RemoveIpcs(); // we need non existing shm + + typedef SharedObject SO1; + typedef SharedObject SO2; + + SO1::Ptr sho = SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + + Try { + SO2::Ptr sho2 = SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + + RUNNER_ASSERT_MSG(false, "Invalid shm size has been accepted"); + } + Catch(SharedObjectBase::Exception::InvalidSize) { + RUNNER_ASSERT(true); + } +} + +////////////////////////////////////////////// + +class MagicTestSO1 : public TestSharedObject +{ + protected: + explicit MagicTestSO1(const std::string& semaphore) : + TestSharedObject(semaphore) {} + + // from SharedObject + virtual MagicType GetMagicNumber() const + { + return 661; + } + + private: + friend class SharedObjectFactory; +}; + +class MagicTestSO2 : public TestSharedObject +{ + protected: + explicit MagicTestSO2(const std::string& semaphore) : + TestSharedObject(semaphore) {} + + // from SharedObject + virtual MagicType GetMagicNumber() const + { + return 662; + } + + private: + friend class SharedObjectFactory; +}; + +RUNNER_TEST(SharedMemory_024_InvalidMagicTest) +{ + RemoveIpcs(); // we need non existing shm + + std::shared_ptr sho = + SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + + Try { + std::shared_ptr sho2 = + SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + + RUNNER_ASSERT_MSG(false, "Invalid shm magic number has been accepted"); + } + Catch(SharedObjectBase::Exception::InvalidMagicNumber) { + RUNNER_ASSERT(true); + } +} + +////////////////////////////////////////////// + +/* + * Listening shared object + */ +class EnumTestSO1 : public TestSharedObject +{ + public: + void SetWaitable(DPL::WaitableEvent* waitable) + { + m_waitable = waitable; + } + + protected: + explicit EnumTestSO1(const std::string& semaphore) : + TestSharedObject(semaphore) {} + + virtual void PropertyChanged(size_t propertyEnum); + + private: + friend class SharedObjectFactory; + + DPL::WaitableEvent* m_waitable; +}; + +void EnumTestSO1::PropertyChanged(size_t propertyEnum) +{ + if (propertyEnum == 1) { + LogDebug("Property enum " << propertyEnum << " correctly set"); + g_enumTestCorrect = true; + } + if (propertyEnum == 4) { + // This is bad. We only have 4 types + LogError("Property enum " << propertyEnum << " should be skipped"); + g_enumTestIncorrect = true; + } + // confirm property change notification + m_waitable->Signal(); +} + +class EnumController : public ListeningController +{ + public: + explicit EnumController(DPL::WaitableEvent* waitable) : + ListeningController(waitable) {} + + virtual void OnEvent(const int event); +}; + +void EnumController::OnEvent(const int event) +{ + if (event == INIT_EVENT) { + m_so->SetWaitable(m_waitable); + } +} + +/* + * Writing shared object with correct size but different number of types + */ +class EnumTestSO2 : public TestSharedObject3 +{ + protected: + explicit EnumTestSO2(const std::string& semaphore) : + TestSharedObject3(semaphore) {} + + private: + friend class SharedObjectFactory; +}; + +RUNNER_TEST(SharedMemory_025_InvalidEnumTest) +{ + RemoveIpcs(); // we need non existing shm + + g_enumTestCorrect = false; + g_enumTestIncorrect = false; + + DPL::WaitableEvent waitable; + + // create listening controller and wait until it registers + EnumController controller(&waitable); + Wait(waitable); + LogDebug("Listening controller created"); + + // create writing shared object + std::shared_ptr sho2 = + SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + DPL::WaitableHandleIndexList list; + + // write property and wait for confirmation + sho2->SetProperty<1>(2); + Wait(waitable); + + // write incorrect property and wait for confirmation + // we expect timeout + sho2->SetProperty<4>(2); + Wait(waitable, true); + + // schedule listener deregistration and wait for confirmation + controller.PostEvent(DESTROY_EVENT); + Wait(waitable); + + // check results + RUNNER_ASSERT(g_enumTestCorrect == true); + RUNNER_ASSERT(g_enumTestIncorrect == false); +} + +////////////////////////////////////////////// + +class MultiThreadSO : public TestSharedObject +{ + public: + void TestAndSetProperty(); + + protected: + explicit MultiThreadSO(const std::string& semaphore) : + TestSharedObject(semaphore) {} + + private: + friend class SharedObjectFactory; +}; + +void MultiThreadSO::TestAndSetProperty() +{ + ScopedFlaggedLock lock(*this); + + int value = PropertyRef<0, int>(); + DPL::Thread::MicroSleep(100); + SetPropertyInternal<0>(value + 1); +} + +class ShmController : public ListeningController +{ + public: + explicit ShmController(DPL::WaitableEvent* event) : + ListeningController(event), m_counter(0) + {} + + virtual void OnEventReceived(const int& event); + + private: + size_t m_counter; +}; + +void ShmController::OnEventReceived(const int& event) +{ + if (event == INIT_EVENT) { + m_so = SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + PostEvent(2); + } else if (event == DESTROY_EVENT) { + LogDebug("Destroying shared object"); + // deregister, destroy ad notify main thread + m_so.Reset(); + m_waitable->Signal(); + } else if (event == 2) { + m_so->TestAndSetProperty(); + m_counter++; + if (m_counter >= TEST_AND_SET_REPEATS) { + LogDebug("Max tests reached. Finishing thread"); + PostEvent(DESTROY_EVENT); + return; + } + PostEvent(2); + } +} + +RUNNER_TEST(SharedMemory_030_MultithreadTest) +{ + RemoveIpcs(); // we need non existing shm + + typedef SharedObject SHO; + SHO::Ptr sho = SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + + ShmController* controller[MAX_THREADS]; + DPL::WaitableEvent finalEvent[MAX_THREADS]; + + for (size_t i = 0; i < MAX_THREADS; ++i) { + controller[i] = new ShmController(&finalEvent[i]); + } + + for (size_t i = 0; i < MAX_THREADS; ++i) { + Wait(finalEvent[i]); + } + + for (size_t i = 0; i < MAX_THREADS; ++i) { + delete controller[i]; + controller[i] = NULL; + } + + int value = sho->GetProperty<0, int>(); + LogDebug("Final value is " << value << ", expected " << + MAX_THREADS * TEST_AND_SET_REPEATS); + RUNNER_ASSERT(value == MAX_THREADS * TEST_AND_SET_REPEATS); +} + +////////////////////////////////////////////// + +class MyModel10 : public DPL::Model +{ + public: + explicit MyModel10(const TestSharedObject4Ptr& shared_object) : + DPL::Model(), boolValue(this, shared_object) {} + + SharedProperty + boolValue; +}; + +/* + * Listening controller + */ +class ShmController3 : public ListeningController +{ + public: + explicit ShmController3(DPL::WaitableEvent* event) : + ListeningController(event) + {} + + virtual void OnEvent(const int event); + + void OnValueChanged(const DPL::PropertyEvent& event); + + private: + typedef std::unique_ptr MyModelPtr; + + // model with property bound to shared object + MyModelPtr m_model; +}; + +void ShmController3::OnEvent(const int event) +{ + if (event == INIT_EVENT) { + m_model.Reset(new MyModel10(m_so)); + m_model->boolValue.AddListener( + DPL::FastDelegate&)>( + this, + &ShmController3::OnValueChanged)); + } else if (event == DESTROY_EVENT) { + m_model->boolValue.RemoveListener( + DPL::FastDelegate&)>( + this, + &ShmController3::OnValueChanged)); + m_model.Reset(); + } +} + +void ShmController3::OnValueChanged(const DPL::PropertyEvent& event) +{ + if (event.value) { + // change back + m_model->boolValue.Set(false); + } else { + LogError("Expected value = true, got false"); + } + + m_waitable->Signal(); +} + +RUNNER_TEST(SharedMemory_050_SharedProperty) +{ + RemoveIpcs(); + + bool result = true; + DPL::WaitableEvent waitable; + // listener controller + ShmController3 controller(&waitable); + Wait(waitable); + + TestSharedObject4Ptr sharedObject = TestSharedObject4::Create(); + + for (size_t i = 0; i < SHARED_PROP_REPEATS; ++i) { + sharedObject->SetProperty(true); + Wait(waitable); + result = sharedObject->GetProperty(); + RUNNER_ASSERT(result == false); + } + controller.PostEvent(DESTROY_EVENT); + Wait(waitable); +} + +////////////////////////////////////////////// + +class MyModel2 : public DPL::Model +{ + public: + explicit MyModel2(const TestSharedObjectPtr& shared_object) : + counter(this, shared_object) {} + + SharedProperty counter; +}; + +class SPController : public ListeningController +{ + public: + explicit SPController(DPL::WaitableEvent* event) : + ListeningController(event), m_repeats(1) {} + + virtual void OnEvent(const int event); + + void OnValueChanged1(const DPL::PropertyEvent& event); + void OnValueChanged2(const DPL::PropertyEvent& event); + + private: + std::unique_ptr m_model1; + std::unique_ptr m_model2; + + int m_repeats; + std::shared_ptr m_so2; +}; + +void SPController::OnEvent(const int event) +{ + if (event == INIT_EVENT) { + m_so2 = SharedObjectFactory::Create(SHM_KEY, + SEM_NAME); + + // create and register 2 models sharing the same property + m_model1.Reset(new MyModel2(m_so)); + m_model2.Reset(new MyModel2(m_so2)); + m_model1->counter.AddListener( + DPL::FastDelegate&)>( + this, + &SPController::OnValueChanged1)); + m_model2->counter.AddListener( + DPL::FastDelegate&)>( + this, + &SPController::OnValueChanged2)); + m_model1->counter.Set(1); + } else if (event == DESTROY_EVENT) { + m_model1->counter.RemoveListener( + DPL::FastDelegate&)>( + this, + &SPController::OnValueChanged1)); + m_model2->counter.RemoveListener( + DPL::FastDelegate&)>( + this, + &SPController::OnValueChanged2)); + + m_model1.Reset(); + m_model2.Reset(); + m_so2.Reset(); + } +} + +void SPController::OnValueChanged1(const DPL::PropertyEvent& event) +{ + if (m_repeats >= SINGLE_PROCESS_REPEATS) { + PostEvent(DESTROY_EVENT); + return; + } + + LogDebug("[1] Value changed to " << event.value); + m_repeats++; + m_model1->counter.Set(event.value + 1); +} + +void SPController::OnValueChanged2(const DPL::PropertyEvent& event) +{ + if (m_repeats >= SINGLE_PROCESS_REPEATS) { + PostEvent(DESTROY_EVENT); + return; + } + + LogDebug("[2] Value changed to " << event.value); + m_repeats++; + m_model2->counter.Set(event.value + 1); +} + +RUNNER_TEST(SharedMemory_060_SingleProcess) +{ + RemoveIpcs(); + + DPL::WaitableEvent waitable; + SPController controller(&waitable); + TestSharedObjectPtr sho = SharedObjectFactory::Create( + SHM_KEY, + SEM_NAME); + + // wait for creation + Wait(waitable); + + // wait for destruction + Wait(waitable); + + int value = sho->GetProperty<0, int>(); + + LogDebug("final value: " << value); + + // check value + RUNNER_ASSERT(value == SINGLE_PROCESS_REPEATS); +} + +////////////////////////////////////////////// + +class ListenerTestController : public ListeningController, + public ISharedObjectListener<0, int>, + public ISharedObjectListener<1, int>, + public ISharedObjectListener<2, char>, + public ISharedObjectListener<3, int[64]> +{ + public: + explicit ListenerTestController(DPL::WaitableEvent* event) : + ListeningController(event) {} + + ~ListenerTestController(); + + virtual void OnEvent(const int event); + + virtual void ValueChanged(size_t propertyEnum, + const int& value, + const void* info = NULL); + virtual void ValueChanged(size_t propertyEnum, + const char& value, + const void* info = NULL); + virtual void ValueChanged(size_t propertyEnum, + const int(&value)[64], + const void* info = NULL); +}; + +ListenerTestController::~ListenerTestController() +{} + +void ListenerTestController::OnEvent(const int event) +{ + if (event == INIT_EVENT) { + // add self as a listener to shared object + m_so->AddListener<0, int>(this); + m_so->AddListener<1, int>(this); + m_so->AddListener<2, char>(this); + m_so->AddListener<3, int[64]>(this); + } else if (event == DESTROY_EVENT) { + // remove self from listener list + m_so->RemoveListener<0, int>(this); + m_so->RemoveListener<1, int>(this); + m_so->RemoveListener<2, char>(this); + m_so->RemoveListener<3, int[64]>(this); + } +} + +void ListenerTestController::ValueChanged(size_t propertyEnum, + const int& value, + const void* /*info*/) +{ + LogDebug("ValueChanged(int) " << propertyEnum << " " << value); + if ((propertyEnum == 0 && + value == 1) || (propertyEnum == 1 && value == 2)) + { + g_values[propertyEnum]++; + if (g_values[propertyEnum] == 3) { + m_waitable->Signal(); + } + } +} + +void ListenerTestController::ValueChanged(size_t propertyEnum, + const char& value, + const void* /*info*/) +{ + LogDebug("ValueChanged(char) " << propertyEnum << " " << value); + if (propertyEnum == 2 && value == 'c') { + g_values[propertyEnum]++; + if (g_values[propertyEnum] == 3) { + m_waitable->Signal(); + } + } +} + +void ListenerTestController::ValueChanged(size_t propertyEnum, + const int(&value)[64], + const void* /*info*/) +{ + LogDebug("ValueChanged(int[64]) " << propertyEnum << " " << value[5]); + if (propertyEnum == 3 && value[5] == 5) { + g_values[propertyEnum]++; + if (g_values[propertyEnum] == 3) { + m_waitable->Signal(); + } + } +} + +RUNNER_TEST(SharedMemory_070_SharedObjectListeners) +{ + RemoveIpcs(); + + // setup global flags + for (size_t i = 0; i < TestTypeList::Size; ++i) { + g_values[i] = 0; + } + + // create shared object + TestSharedObjectPtr sho = SharedObjectFactory::Create( + SHM_KEY, SEM_NAME); + + // create 1st listener and wait for it + DPL::WaitableEvent waitable; + ListenerTestController c1(&waitable); + Wait(waitable); + + // create 2nd listener and wait for it + ListenerTestController c2(&waitable); + Wait(waitable); + + // create 3rd listener and wait for it + ListenerTestController c3(&waitable); + Wait(waitable); + + // set properties and wait for result + sho->SetProperty<0, int>(1); + Wait(waitable); + + RUNNER_ASSERT(g_values[0] == 3); + + sho->SetProperty<1, int>(2); + Wait(waitable); + + RUNNER_ASSERT(g_values[1] == 3); + + sho->SetProperty<2, char>('c'); + Wait(waitable); + + RUNNER_ASSERT(g_values[2] == 3); + + int array[64]; + memset(array, 64 * sizeof(array[0]), 0); + array[5] = 5; + sho->SetProperty<3, int[64]>(array); + Wait(waitable); + + RUNNER_ASSERT(g_values[3] == 3); + + // finalize listeners + c1.PostEvent(DESTROY_EVENT); + Wait(waitable); + + c2.PostEvent(DESTROY_EVENT); + Wait(waitable); + + c3.PostEvent(DESTROY_EVENT); + Wait(waitable); +} + +////////////////////////////////////////////// + +/* + * class simulating DB access + */ +class DAO : public DPL::Noncopyable +{ + public: + DAO() : m_boolValue(false) {} + + void SetBoolValue(const bool& value) + { + m_boolValue = value; + } + + bool GetBoolValue() const + { + return m_boolValue; + } + + private: + bool m_boolValue; +}; + +/* + * Model with property having set delegate defined + */ +class MyModel3 : public DPL::Model +{ + public: + typedef SharedPropertyEx PropertyType; + + MyModel3(const TestSharedObject4Ptr& shared_object, DAO* dao) : + boolValue(this, + shared_object, + PropertyType::SetDelegate(dao, &DAO::SetBoolValue)) + {} + + PropertyType boolValue; +}; + +RUNNER_TEST(SharedMemory_090_SetPropertyDelegate) +{ + RemoveIpcs(); + + // dao object + DAO dao; + + // create shared object + TestSharedObject4Ptr sho = TestSharedObject4::Create(); + + // set property but call dao delegate within semaphore + sho->SetProperty( + true, + MyModel3::PropertyType::SetDelegate(&dao, &DAO::SetBoolValue)); + + // check dao value + RUNNER_ASSERT(dao.GetBoolValue() == true); + + // check shared object value + bool shoValue = sho->GetProperty(); + RUNNER_ASSERT(shoValue == true); + + // try the same with shared property + MyModel3 model(sho, &dao); + + // set property + model.boolValue.Set(false); + + // check dao value + RUNNER_ASSERT(dao.GetBoolValue() == false); + + // check sho value + shoValue = sho->GetProperty(); + RUNNER_ASSERT(shoValue == false); + + // check property value + RUNNER_ASSERT(model.boolValue.Get() == false); +} + +////////////////////////////////////////////// + +/* + * Lazy initialization test shared object + */ +class LazySharedObject : public SharedObject +{ + public: + explicit LazySharedObject(const std::string& semaphore) : + SharedObject(semaphore) + , m_read(false) + {} + + void Init(); + + bool IsRead() const + { + return m_read; + } + + private: + friend class SharedObjectFactory; + + bool m_read; +}; + +void LazySharedObject::Init() +{ + SetPropertyInternal<0>(42); + m_read = true; +} + +RUNNER_TEST(SharedMemory_100_LazyInit) +{ + RemoveIpcs(); + + typedef std::shared_ptr LazySharedObjectPtr; + + // create shared object + LazySharedObjectPtr sho = SharedObjectFactory::Create( + SHM_KEY, SEM_NAME); + + RUNNER_ASSERT(sho->IsRead() == false); + + // get property causing lazy init + int value = sho->GetProperty<0, int>(); + + RUNNER_ASSERT(sho->IsRead() == true); + RUNNER_ASSERT(value == 42); + + // create another object + LazySharedObjectPtr sho2 = SharedObjectFactory::Create( + SHM_KEY, SEM_NAME); + + RUNNER_ASSERT(sho2->IsRead() == false); + + // get property NOT causing lazy init + value = sho2->GetProperty<0, int>(); + + RUNNER_ASSERT(sho2->IsRead() == false); + RUNNER_ASSERT(value == 42); + + // destroy both objects + sho.Reset(); + sho2.Reset(); + + // create shared object + LazySharedObjectPtr sho3 = SharedObjectFactory::Create( + SHM_KEY, SEM_NAME); + + RUNNER_ASSERT(sho3->IsRead() == false); + + // set property causing lazy init + sho3->SetProperty<0>(43); + value = sho3->GetProperty<0, int>(); + + RUNNER_ASSERT(sho3->IsRead() == true); + RUNNER_ASSERT(value == 43); +} + +////////////////////////////////////////////// + +bool SetCondition(const int& readValue, int& setValue); +bool SetCondition(const int& readValue, int& setValue) +{ + LogDebug("Condition delegate called with read value = " << readValue << + " and set value = " << setValue); + + if (readValue > 3) { + LogDebug("Condition is false"); + return false; + } + + LogDebug("Condition is true"); + if (4 == setValue) { + setValue = 10; + LogDebug("Changing set value to " << setValue); + } + return true; +} + +void SetDelegate(const int& readValue); +void SetDelegate(const int& readValue) +{ + LogDebug("Set delegate called " << readValue); + g_delegateCalls++; +} + +RUNNER_TEST(SharedMemory_120_ConditionalSet) +{ + RemoveIpcs(); + + TestSharedObjectPtr sho = SharedObjectFactory::Create( + SHM_KEY, + SEM_NAME); + + g_delegateCalls = 0; + + RUNNER_ASSERT(0 == (sho->GetProperty<0, int>())); + + DPL::FastDelegate condition(&SetCondition); + DPL::FastDelegate delegate(&SetDelegate); + + bool succeeded = false; + + succeeded = sho->ConditionalSetProperty<0>(-2, condition); + + RUNNER_ASSERT(succeeded); + RUNNER_ASSERT(-2 == (sho->GetProperty<0, int>())); + + succeeded = sho->ConditionalSetProperty<0>(4, condition, delegate); + + RUNNER_ASSERT(succeeded); + RUNNER_ASSERT(10 == (sho->GetProperty<0, int>())); + RUNNER_ASSERT(1 == g_delegateCalls); + + succeeded = sho->ConditionalSetProperty<0>(5, condition); + + RUNNER_ASSERT(!succeeded); + RUNNER_ASSERT(10 == (sho->GetProperty<0, int>())); + + succeeded = sho->ConditionalSetProperty<0>(666, condition, delegate); + + RUNNER_ASSERT(!succeeded); + RUNNER_ASSERT(10 == (sho->GetProperty<0, int>())); + RUNNER_ASSERT(1 == g_delegateCalls); +} + +////////////////////////////////////////////// + +/* + * Shared object used by multiple threads as a singleton. + */ +class MTSharedObject : public SharedObject +{ + public: + explicit MTSharedObject(const std::string& semaphore) : + SharedObject(semaphore) + {} + + void Clear(); + + private: + friend class SharedObjectFactory; +}; + +typedef std::shared_ptr MTSharedObjectPtr; + +void MTSharedObject::Clear() +{ + int array[64] = {}; + SetProperty<0>(0); + SetProperty<1>(0); + SetProperty<2>(static_cast(0)); + SetProperty<3>(array); +} + +/* + * Shared object singleton + */ +class SharedObjectSingleton +{ + public: + static MTSharedObjectPtr Instance(); + static void Destroy(); + + private: + static MTSharedObjectPtr m_sho; + static DPL::Mutex m_mutex; +}; + +MTSharedObjectPtr SharedObjectSingleton::m_sho; +DPL::Mutex SharedObjectSingleton::m_mutex; + +MTSharedObjectPtr SharedObjectSingleton::Instance() +{ + DPL::Mutex::ScopedLock lock(&m_mutex); + if (!m_sho) { + m_sho = SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + } + return m_sho; +} + +void SharedObjectSingleton::Destroy() +{ + DPL::Mutex::ScopedLock lock(&m_mutex); + m_sho.Reset(); +} + +/* + * Listening controller + */ +class ShmController4 : public ListeningController, + public ISharedObjectListener<0, int>, + public ISharedObjectListener<1, int>, + public ISharedObjectListener<2, char>, + public ISharedObjectListener<3, int[64]> +{ + public: + enum { + ADD_LISTENERS = 2, + REMOVE_LISTENERS = 3, + DESTROY_SINGLETON = 4 + }; + + explicit ShmController4(DPL::WaitableEvent* event) : + ListeningController(event) + {} + + virtual void OnEventReceived(const int& event); + + virtual void ValueChanged(size_t propertyEnum, + const int& value, + const void* info = NULL); + virtual void ValueChanged(size_t propertyEnum, + const char& value, + const void* info = NULL); + virtual void ValueChanged(size_t propertyEnum, + const int(&value)[64], + const void* info = NULL); + + bool NotRegistered(); + + private: + void Sleep(); + + size_t m_counter; +}; + +void ShmController4::ValueChanged(size_t propertyEnum, + const int& value, + const void* /*info*/) +{ + LogDebug("ValueChanged(int) " << propertyEnum << " " << value); + if ((propertyEnum == 0 && value == 1) || + (propertyEnum == 1 && value == 11)) + { + m_waitable->Signal(); + } +} + +void ShmController4::ValueChanged(size_t propertyEnum, + const char& value, + const void* /*info*/) +{ + LogDebug("ValueChanged(char) " << propertyEnum << " " << value); + if (propertyEnum == 2 && value == 'a') { + m_waitable->Signal(); + } +} + +void ShmController4::ValueChanged(size_t propertyEnum, + const int(&value)[64], + const void* /*info*/) +{ + LogDebug("ValueChanged(int[64]) " << propertyEnum << " " << value[5]); + if (propertyEnum == 3 && value[0] == 0 && value[1] == 1 && value[2] == 2) { + m_waitable->Signal(); + } +} + +void ShmController4::Sleep() +{ + DPL::Thread::GetCurrentThread()->MiliSleep( + rand() % MAX_SINGLETON_LISTENER_DELAY); +} + +void ShmController4::OnEventReceived(const int& event) +{ + switch (event) { + case INIT_EVENT: + m_so = SharedObjectSingleton::Instance(); + m_waitable->Signal(); + break; + + case DESTROY_EVENT: + LogDebug("Destroying shared object"); + // deregister, destroy and notify main thread + m_so.Reset(); + m_waitable->Signal(); + break; + + case ADD_LISTENERS: + // add listener and notify + m_so->AddListener<0, int>(this); + Sleep(); + m_so->AddListener<1, int>(this); + Sleep(); + m_so->AddListener<2, char>(this); + Sleep(); + m_so->AddListener<3, int[64]>(this); + Sleep(); + m_waitable->Signal(); + break; + + case REMOVE_LISTENERS: + // remove listener and notify + m_so->RemoveListener<0, int>(this); + Sleep(); + m_so->RemoveListener<1, int>(this); + Sleep(); + m_so->RemoveListener<2, char>(this); + Sleep(); + m_so->RemoveListener<3, int[64]>(this); + Sleep(); + m_waitable->Signal(); + break; + + case DESTROY_SINGLETON: + SharedObjectSingleton::Destroy(); + m_waitable->Signal(); + break; + + default: + LogError("Unsupported event received: " << event); + } +} + +void MultipleWait(DPL::WaitableEvent(&event)[MAX_THREADS]); +void MultipleWait(DPL::WaitableEvent(&event)[MAX_THREADS]) +{ + for (size_t i = 0; i < MAX_THREADS; ++i) { + Wait(event[i]); + } +} + +/* + * Try to remove property listener. If there's no such listener an exception + * should be thrown. + */ +#define LISTENER_ASSERT(property) \ + Try { \ + singleton->RemoveListener<(property)>(controller[i]); \ + LogError("Controller " << i << " is still listening for property " \ + << #property); \ + RUNNER_ASSERT_MSG(false, "No listeners expected"); \ + } \ + Catch(MTSharedObject::Exception::ListenerNotFound) { \ + RUNNER_ASSERT(true); \ + } \ + +// test +RUNNER_TEST(SharedMemory_130_SharedObjectSingleton) +{ + RemoveIpcs(); // we need non existing shm + + srand(time(NULL)); + + // writer shared object + TestSharedObjectPtr sho = SharedObjectFactory::Create( + SHM_KEY, SEM_NAME); + + ShmController4* controller[MAX_THREADS]; + DPL::WaitableEvent waitable[MAX_THREADS]; + + const int array[64] = { 0, 1, 2 }; + + // Create and wait for notification. Make sure that the thread/controller 0 + // is created first + LogInfo("Creating controllers"); + for (size_t i = 0; i < MAX_THREADS; ++i) { + controller[i] = new ShmController4(&waitable[i]); + Wait(waitable[i]); + } + + // singleton will be created by thread/controller 0 by now + MTSharedObjectPtr singleton = SharedObjectSingleton::Instance(); + + for (size_t repeats = 0; repeats < SINGLETON_TEST_REPEATS; ++repeats) { + LogInfo("%%%%%%%%%%%%%%%%%%%%%"); + LogInfo("Iteration " << repeats + 1 << " of " << SINGLETON_TEST_REPEATS); + singleton->Clear(); + + // add listeners + LogInfo("Adding listeners"); + for (size_t i = 0; i < MAX_THREADS; ++i) { + controller[i]->PostEvent(ShmController4::ADD_LISTENERS); + } + // wait for listeners + MultipleWait(waitable); + + RUNNER_ASSERT((singleton->GetProperty<0, int>()) == 0); + RUNNER_ASSERT((singleton->GetProperty<1, int>()) == 0); + RUNNER_ASSERT((singleton->GetProperty<2, char>()) == 0); + + int checkArray[64] = {}; + singleton->GetProperty<3>(checkArray); + RUNNER_ASSERT(checkArray[0] == 0); + RUNNER_ASSERT(checkArray[1] == 0); + RUNNER_ASSERT(checkArray[2] == 0); + + // change + LogInfo("Setting property 0"); + sho->SetProperty<0>(1); + // wait for confirmations + MultipleWait(waitable); + + // change + LogInfo("Setting property 1"); + sho->SetProperty<1>(11); + // wait for confirmations + MultipleWait(waitable); + + // change + LogInfo("Setting property 2"); + sho->SetProperty<2>('a'); + // wait for confirmations + MultipleWait(waitable); + + // change + LogInfo("Setting property 3"); + sho->SetProperty<3>(array); + // wait for confirmations + MultipleWait(waitable); + + // remove listeners + LogInfo("Removing listeners"); + for (size_t i = 0; i < MAX_THREADS; ++i) { + controller[i]->PostEvent(ShmController4::REMOVE_LISTENERS); + } + // wait for listeners + MultipleWait(waitable); + + // check if listeners array is empty + LogInfo("Checking listeners"); + for (size_t i = 0; i < MAX_THREADS; ++i) { + LISTENER_ASSERT(0); + LISTENER_ASSERT(1); + LISTENER_ASSERT(2); + LISTENER_ASSERT(3); + } + + RUNNER_ASSERT((singleton->GetProperty<0, int>()) == 1); + RUNNER_ASSERT((singleton->GetProperty<1, int>()) == 11); + RUNNER_ASSERT((singleton->GetProperty<2, char>()) == 'a'); + singleton->GetProperty<3>(checkArray); + RUNNER_ASSERT(checkArray[0] == 0); + RUNNER_ASSERT(checkArray[1] == 1); + RUNNER_ASSERT(checkArray[2] == 2); + } + + singleton.Reset(); + + // Destroy controllers and wait for confirmation. Make sure that + // thread/controller 0 is destroyed in the end + LogInfo("Destroying controllers"); + for (int i = MAX_THREADS - 1; i >= 0; --i) { + controller[i]->PostEvent(DESTROY_EVENT); + Wait(waitable[i]); + if (i == 0) { + /* + * Destroy singleton before thread that created it finishes. + * This is to properly close all waitable handles opened by + * SharedObject in thread 0. + */ + LogInfo("Destroying singleton"); + controller[i]->PostEvent(ShmController4::DESTROY_SINGLETON); + Wait(waitable[i]); + } + delete controller[i]; + } +} + +#undef LISTENER_ASSERT + +/* + * test preconditions & postconditions: + * - no existing shared memory with given SHM_KEY + * - no existing semaphore of given SEM_NAME + */ +RUNNER_TEST(SharedMemory_001_Preconditions) { + RemoveIpcs(); +} + +RUNNER_TEST(SharedMemory_999_Postconditions) { + RemoveIpcs(); +} diff --git a/tests/unused/test_sql_connection.cpp b/tests/unused/test_sql_connection.cpp new file mode 100644 index 0000000..4525c98 --- /dev/null +++ b/tests/unused/test_sql_connection.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_sql_connection.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of sql connection tests + */ + +/* + * + * This test has been saved from original test_sql_connection.cpp in wrt-commons + * project. + * + */ + +#include + +RUNNER_TEST(SqlConnection_MassiveReadWrite_SemaphoreSynchronization) +{ + srand(time(NULL)); + + std::ostringstream dbSemaporeFileNameStream; + dbSemaporeFileNameStream << "dpl_tests_dbso_sem_"; + dbSemaporeFileNameStream << rand() << ".sem"; + + std::string dbSemaphoreFileName = dbSemaporeFileNameStream.str(); + + SemaphoreSynchronizationObjectGenerator m_generator(dbSemaphoreFileName); + MassiveReadWriteTest(&m_generator); +} diff --git a/tests/unused/test_task.cpp b/tests/unused/test_task.cpp new file mode 100644 index 0000000..995f1cb --- /dev/null +++ b/tests/unused/test_task.cpp @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file test_task.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of task tests + */ +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +class MySingleTask : + public DPL::TaskDecl +{ + protected: + void StepOne() + {} + + public: + MySingleTask() : + DPL::TaskDecl(this) + { + AddStep(&MySingleTask::StepOne); + } +}; + +class MyMultiTask : + public DPL::MultiTaskDecl +{ + protected: + typedef DPL::MultiTaskDecl BaseType; + + void StepOne() + { + LogInfo("Step one"); + } + + void StepTwo() + { + LogInfo("Step two"); + } + + void StepThree() + { + LogInfo("Step three"); + } + + public: + MyMultiTask() : + BaseType(this, 2) + { + BaseType::StepList depListStepThree; + depListStepThree.push_back(&MyMultiTask::StepOne); + depListStepThree.push_back(&MyMultiTask::StepTwo); + AddStep(&MyMultiTask::StepThree, depListStepThree); + + BaseType::StepList depListStepTwo; + depListStepTwo.push_back(&MyMultiTask::StepOne); + AddStep(&MyMultiTask::StepTwo, depListStepTwo); + + BaseType::StepList depListStepOne; + AddStep(&MyMultiTask::StepOne, depListStepOne); + } +}; + +RUNNER_TEST(Task_SingleTask) +{ + MySingleTask task; + while (task.NextStep()) {} +} + +RUNNER_TEST(Task_MultiTask) +{ + MyMultiTask task; + while (task.NextStep()) {} +} diff --git a/tests/utils/CMakeLists.txt b/tests/utils/CMakeLists.txt new file mode 100644 index 0000000..9898084 --- /dev/null +++ b/tests/utils/CMakeLists.txt @@ -0,0 +1,33 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# 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. +# +# @file CMakeLists.txt +# @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) +# @version 1.0 +# @brief +# + +SET(TARGET_NAME "wrt-commons-tests-utils") + +# Set DPL tests sources +SET(DPL_TESTS_UTIL_SOURCES + ${TESTS_DIR}/utils/main.cpp + ${TESTS_DIR}/utils/widget_version.cpp + ${TESTS_DIR}/utils/bash_utils.cpp + ${TESTS_DIR}/utils/wrt_utility.cpp +) + +#WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_NAME} ${TARGET_DPL_UTILS_EFL}) +WRT_TEST_BUILD(${TARGET_NAME} ${DPL_TESTS_UTIL_SOURCES}) +WRT_TEST_INSTALL(${TARGET_NAME}) diff --git a/tests/utils/bash_utils.cpp b/tests/utils/bash_utils.cpp new file mode 100644 index 0000000..7dac1fc --- /dev/null +++ b/tests/utils/bash_utils.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/** + * @file bash_utils.cpp + * @author Iwanek Tomasz + * @version 1.0 + */ +#include +#include +#include + +using namespace BashUtils; + +RUNNER_TEST_GROUP_INIT(DPL_BASH_UTILS) + +/* +Name: Bash_Utils_escape_arg +Description:tests ecaping bash special characters for command arguments +Expected: matching string +*/ +RUNNER_TEST(Bash_Utils_escape_arg) +{ + RUNNER_ASSERT_MSG(escape_arg(std::string( + "valid")) == "\"valid\"", + "Valid argument failed"); + LogDebug("\"val\\!d\"" << " " << escape_arg(std::string("val!d"))); + RUNNER_ASSERT_MSG(escape_arg(std::string( + "val!d")) == "\"val\\!d\"", + "Single escaped character in argument failed"); + LogDebug("\"v\\$l\\$\\$\"" << " " << escape_arg(std::string("v$l$$"))); + RUNNER_ASSERT_MSG(escape_arg(std::string( + "v$l$$")) == "\"v\\$l\\$\\$\"", + "Multiple occurences of single special character in argument failed"); + LogDebug("\"v\\`\\$\\\"\\!d\\`\"" << " " << + escape_arg(std::string("v`$\"!d`"))); + RUNNER_ASSERT_MSG(escape_arg(std::string( + "v`$\"!d`")) == "\"v\\`\\$\\\"\\!d\\`\"", + "Multiple occurences of multiple special character in argument failed"); +} diff --git a/tests/utils/main.cpp b/tests/utils/main.cpp new file mode 100644 index 0000000..42ffe3a --- /dev/null +++ b/tests/utils/main.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file main.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of main + */ +#include + +int main(int argc, char *argv[]) +{ + return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); +} + diff --git a/tests/utils/widget_version.cpp b/tests/utils/widget_version.cpp new file mode 100644 index 0000000..f00c715 --- /dev/null +++ b/tests/utils/widget_version.cpp @@ -0,0 +1,436 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file widget_version.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief Implementation file for test cases for engine internal tests + */ +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL_WIDGET_VERSION) + +/* +Name: WidgetVersion_M2_O0 +Description: tests correct parsing of version widget in format: [major].[minor] +Expected: major and minor parts matches expected values +*/ +RUNNER_TEST(WidgetVersion_M2_O0) +{ + DPL::String raw(L"1.2"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == true); + RUNNER_ASSERT(version.Major() == DPL::String(L"1")); + RUNNER_ASSERT(version.Minor() == DPL::String(L"2")); + RUNNER_ASSERT(version.Micro() == DPL::Optional()); + RUNNER_ASSERT(version.Optional() == DPL::Optional()); + RUNNER_ASSERT(version.Raw() == raw); +} + +/* +Name: WidgetVersion_M2_O0_nonwac_1 +Description: tests if version is recognized as wac version number +Expected: version should not be recognized as wac compatible +*/ +RUNNER_TEST(WidgetVersion_M2_O0_nonwac_1) +{ + DPL::String raw(L"a1.2"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +/* +Name: WidgetVersion_M2_O0_nonwac_2 +Description: tests if version is recognized as wac version number +Expected: version should not be recognized as wac compatible +*/ +RUNNER_TEST(WidgetVersion_M2_O0_nonwac_2) +{ + DPL::String raw(L"1.2a"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +/* +Name: WidgetVersion_M2_O0_nonwac_3 +Description: tests if version is recognized as wac version number +Expected: version should not be recognized as wac compatible +*/ +RUNNER_TEST(WidgetVersion_M2_O0_nonwac_3) +{ + DPL::String raw(L"aaa1.2bbb"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +/* +Name: WidgetVersion_M2_O0_nonwac_4 +Description: tests if version is recognized as wac version number +Expected: version should not be recognized as wac compatible +*/ +RUNNER_TEST(WidgetVersion_M2_O0_nonwac_4) +{ + DPL::String raw(L"1a.a2"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +/* +Name: WidgetVersion_M2_O0_long +Description: tests correct parsing of version widget in format: [major].[minor] + for huge number +Expected: major and minor parts matches expected values +*/ +RUNNER_TEST(WidgetVersion_M2_O0_long) +{ + DPL::String raw( + L"123456789012345678901234567890.98765432109876543210987654321"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == true); + RUNNER_ASSERT(version.Major() == + DPL::String(L"123456789012345678901234567890")); + RUNNER_ASSERT(version.Minor() == + DPL::String(L"98765432109876543210987654321")); + RUNNER_ASSERT(version.Micro() == DPL::Optional()); + RUNNER_ASSERT(version.Optional() == DPL::Optional()); + RUNNER_ASSERT(version.Raw() == raw); +} + +/* +Name: WidgetVersion_M3_O0 +Description: tests correct wac version number +Expected: major and minor and micro parts matches expected values. + Version should be recognized as wac compatible +*/ +RUNNER_TEST(WidgetVersion_M3_O0) +{ + DPL::String raw(L"1.2.3"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == true); + RUNNER_ASSERT(version.Major() == DPL::String(L"1")); + RUNNER_ASSERT(version.Minor() == DPL::String(L"2")); + RUNNER_ASSERT(version.Micro() == DPL::Optional(L"3")); + RUNNER_ASSERT(version.Optional() == DPL::Optional()); + RUNNER_ASSERT(version.Raw() == raw); +} + +/* +Name: WidgetVersion_M3_O0_nonwac_1 +Description: tests if version is recognized as wac version number +Expected: version should not be recognized as wac compatible +*/ +RUNNER_TEST(WidgetVersion_M3_O0_nonwac_1) +{ + DPL::String raw(L"a1a.2.3"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +/* +Name: WidgetVersion_M3_O0_nonwac_2 +Description: tests if version is recognized as wac version number +Expected: version should not be recognized as wac compatible +*/ +RUNNER_TEST(WidgetVersion_M3_O0_nonwac_2) +{ + DPL::String raw(L"1.b2.3"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +/* +Name: WidgetVersion_M3_O0_nonwac_3 +Description: tests if version is recognized as wac version number +Expected: version should not be recognized as wac compatible +*/ +RUNNER_TEST(WidgetVersion_M3_O0_nonwac_3) +{ + DPL::String raw(L"1.2.3c"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +/* +Name: WidgetVersion_M3_O0_nonwac_4 +Description: tests if version is recognized as wac version number +Expected: version should not be recognized as wac compatible +*/ +RUNNER_TEST(WidgetVersion_M3_O0_nonwac_4) +{ + DPL::String raw(L"1.2.3a"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +/* +Name: WidgetVersion_M3_O1_1 +Description: tests correct wac version number with optional part +Expected: major and minor and micro and optional parts matches expected values. + Version should be recognized as wac compatible +*/ +RUNNER_TEST(WidgetVersion_M3_O1_1) +{ + DPL::String raw(L"1.2.3 test111"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == true); + RUNNER_ASSERT(version.Major() == DPL::String(L"1")); + RUNNER_ASSERT(version.Minor() == DPL::String(L"2")); + RUNNER_ASSERT(version.Micro() == DPL::Optional(L"3")); + RUNNER_ASSERT(version.Optional() == DPL::Optional(L"test111")); + RUNNER_ASSERT(version.Raw() == raw); +} + +/* +Name: WidgetVersion_M3_O1_1 +Description: tests correct wac version number with numeric optional part +Expected: major and minor and micro and optional parts matches expected values. + Version should be recognized as wac compatible +*/ +RUNNER_TEST(WidgetVersion_M3_O1_2) +{ + DPL::String raw(L"1.2.3 111"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == true); + RUNNER_ASSERT(version.Major() == DPL::String(L"1")); + RUNNER_ASSERT(version.Minor() == DPL::String(L"2")); + RUNNER_ASSERT(version.Micro() == DPL::Optional(L"3")); + RUNNER_ASSERT(version.Optional() == DPL::Optional(L"111")); + RUNNER_ASSERT(version.Raw() == raw); +} + +/* +Name: WidgetVersion_M3_O1_3 +Description: tests if version is recognized as wac version number + when trailer spaces exists +Expected: version should not be recognized as wac compatible +*/ +RUNNER_TEST(WidgetVersion_M3_O1_3) +{ + DPL::String raw(L"1.2.3 "); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +/* +Name: WidgetVersion_M2_O1_1 +Description: tests if version is recognized as wac version number + when optional part +Expected: version should be recognized as wac compatible +*/ +RUNNER_TEST(WidgetVersion_M2_O1_1) +{ + DPL::String raw(L"1.2 t"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == true); + RUNNER_ASSERT(version.Major() == DPL::String(L"1")); + RUNNER_ASSERT(version.Minor() == DPL::String(L"2")); + RUNNER_ASSERT(version.Micro() == DPL::Optional()); + RUNNER_ASSERT(version.Optional() == DPL::Optional(L"t")); + RUNNER_ASSERT(version.Raw() == raw); +} + +/* +Name: WidgetVersion_Strange_0 +Description: tests if version is recognized as wac version number +Expected: version should be recognized as wac compatible +*/ +RUNNER_TEST(WidgetVersion_Strange_0) +{ + DPL::String raw(L"1"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +/* +Name: WidgetVersion_Strange_1 +Description: tests if version is recognized as wac version number +Expected: version should not be recognized as wac compatible +*/ +RUNNER_TEST(WidgetVersion_Strange_1) +{ + DPL::String raw(L".1"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +/* +Name: WidgetVersion_Strange_2 +Description: tests if version is recognized as wac version number +Expected: version should not be recognized as wac compatible +*/ +RUNNER_TEST(WidgetVersion_Strange_2) +{ + DPL::String raw(L"..1"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +/* +Name: WidgetVersion_Strange_3 +Description: tests if version is recognized as wac version number +Expected: version should not be recognized as wac compatible +*/ +RUNNER_TEST(WidgetVersion_Strange_3) +{ + DPL::String raw(L"...1"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +/* +Name: WidgetVersion_Strange_4 +Description: tests if version is recognized as wac version number +Expected: version should not be recognized as wac compatible +*/ +RUNNER_TEST(WidgetVersion_Strange_4) +{ + DPL::String raw(L"qwerty"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +/* +Name: WidgetVersion_Strange_5 +Description: tests if version is recognized as wac version number +Expected: version should not be recognized as wac compatible +*/ +RUNNER_TEST(WidgetVersion_Strange_5) +{ + DPL::String raw(L"!@#$%^&*()_+ ^&%^*&%$^*&%*()& JHKJLHKJLH 685685687"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +/* +Name: WidgetVersion_Compare_0 +Description: tests version comparision in format [major].[minor] +Expected: compare should work as expected +*/ +RUNNER_TEST(WidgetVersion_Compare_0) +{ + RUNNER_ASSERT(WidgetVersion(L"1.1") < WidgetVersion(L"1.2")); +} + +/* +Name: WidgetVersion_Compare_1 +Description: tests version comparision in format [major].[minor] +Expected: compare should work as expected +*/ +RUNNER_TEST(WidgetVersion_Compare_1) +{ + RUNNER_ASSERT(WidgetVersion(L"01.001") < WidgetVersion(L"0001.002")); +} + +/* +Name: WidgetVersion_Compare_2 +Description: tests version equality in format [major].[minor] +Expected: versions should be equal +*/ +RUNNER_TEST(WidgetVersion_Compare_2) +{ + RUNNER_ASSERT(WidgetVersion(L"0.1") == WidgetVersion(L"00.1")); +} + +/* +Name: WidgetVersion_Compare_3 +Description: tests version comparision in format [major].[minor] [optional] +Expected: compare should work as expected +*/ +RUNNER_TEST(WidgetVersion_Compare_3) +{ + RUNNER_ASSERT(WidgetVersion(L"1.00000000000000") >= + WidgetVersion(L"1.0 test")); +} + +/* +Name: WidgetVersion_Compare_4 +Description: tests version comparision for huge numbers +Expected: compare should work as expected +*/ +RUNNER_TEST(WidgetVersion_Compare_4) +{ + RUNNER_ASSERT(WidgetVersion( + L"19647963733338932479072098437089778943732432.00000000000000004324324324324321") + > WidgetVersion(L"4324324324324324324321.000432")); +} + +/* +Name: WidgetVersion_Compare_5 +Description: tests equality in format [major].[minor] +Expected: versions should be equal +*/ +RUNNER_TEST(WidgetVersion_Compare_5) +{ + RUNNER_ASSERT(WidgetVersion(L"12345.1") == WidgetVersion(L"12345.1")); +} + +/* +Name: WidgetVersion_Compare_6 +Description: tests version equality in format [major].[minor] +Expected: versions should not be equal +*/ +RUNNER_TEST(WidgetVersion_Compare_6) +{ + RUNNER_ASSERT(WidgetVersion(L"1.1") != WidgetVersion(L"1.11")); +} + +/* +Name: WidgetVersion_Compare_7 +Description: tests version equality in format [major].[minor] [optional] +Expected: versions should be equal, optional part should not be taken into account +*/ +RUNNER_TEST(WidgetVersion_Compare_7) +{ + RUNNER_ASSERT(WidgetVersion(L"000123000.0 notatest") == + WidgetVersion(L"00123000.0 testtesttest")); +} diff --git a/tests/utils/wrt_utility.cpp b/tests/utils/wrt_utility.cpp new file mode 100644 index 0000000..eb78ed6 --- /dev/null +++ b/tests/utils/wrt_utility.cpp @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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. + */ +/* + * @file wrt_utility.cpp + * @author Janusz Majnert (j.majnert@samsung.com) + * @version 1.0 + * @brief Implementation file for test cases for wrt_utility functions + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL_WRT_UTILITY) + +/* +Name: wrt_utility_WrtUtilJoinPaths +Description: join paths test +Expected: correctly used separator +*/ +RUNNER_TEST(wrt_utility_WrtUtilJoinPaths) +{ + std::string result; + + WrtUtilJoinPaths(result, "a/b/c/", "e/f/g.asd"); + RUNNER_ASSERT(result == "a/b/c/e/f/g.asd"); + + WrtUtilJoinPaths(result, "/a/b/c", "/e/f/g/"); + RUNNER_ASSERT(result == "/a/b/c/e/f/g/"); + + WrtUtilJoinPaths(result, "/a/b/c/", "/e/f/g/"); + RUNNER_ASSERT(result == "/a/b/c/e/f/g/"); + + WrtUtilJoinPaths(result, "/a/b/c", "e/f/g/"); + RUNNER_ASSERT(result == "/a/b/c/e/f/g/"); +} + +/** + * Create recursive path with specified permissions. + * Check if folders exist. + * Check if permissions are set. + */ +RUNNER_TEST(wrt_utility_WrtUtilMakeDir) +{ + struct stat st; + //First delete the dir if it exists + WrtUtilRemove("/tmp/test"); + WrtUtilMakeDir("/tmp/test/1/2/3/4/5/6/7/8/9", 0755); + if (stat("/tmp/test/1/2/3/4/5/6/7/8/9", &st) == 0) { + RUNNER_ASSERT_MSG(st.st_mode & S_IRWXU, + "read, write, execute/search by owner"); + RUNNER_ASSERT_MSG(st.st_mode & S_IXGRP, + "execute/search permission, group"); + RUNNER_ASSERT_MSG(st.st_mode & S_IRGRP, "read permission, group"); + RUNNER_ASSERT_MSG(!(st.st_mode & S_IWGRP), + "NO write permission, group "); + RUNNER_ASSERT_MSG(st.st_mode & S_IXOTH, + "execute/search permission, others"); + RUNNER_ASSERT_MSG(st.st_mode & S_IROTH, "read permission, others"); + RUNNER_ASSERT_MSG(!(st.st_mode & S_IWOTH), + "NO write permission, others "); + } else { + RUNNER_ASSERT_MSG(false, "Cannot stat folder"); + } +} + +/** + * Create directory without permission to write. + */ +RUNNER_TEST(wrt_utility_WrtUtilMakeDir_PermissionError) +{ + if (0 == getuid()) { + //Change UID to execute the test correctly + errno = 0; + struct passwd *p = getpwnam("app"); + if (p == NULL) { + int error = errno; + RUNNER_ASSERT_MSG(false, "Getting app user UID failed: " + << (error == + 0 ? "No error detected" : strerror(error))); + } + if (setuid(p->pw_uid) != 0) { + int error = errno; + RUNNER_ASSERT_MSG(false, "Changing to app user's UID failed: " + << (error == + 0 ? "No error detected" : strerror(error))); + } + } + RUNNER_ASSERT_MSG(WrtUtilMakeDir("/tmp/test2/1", + 0055) == false, + "Creating directory '1' in /temp/test2/ should have failed"); + //Going back to root UID + if (setuid(0) != 0) { + int error = errno; + LogWarning("Changing back to root UID failed: " + << (error == 0 ? "No error detected" : strerror(error))); + } +} + +/** + * Create directory with file inside. + * Check if file was removed with directory. + */ +RUNNER_TEST(wrt_utility_WrtUtilRemoveDir) { + RUNNER_ASSERT_MSG(WrtUtilMakeDir("/tmp/test3/", 0755) == true, + "Could not set up directory for test"); + + std::ofstream file; + file.open("/tmp/test3/example.txt"); + file.close(); + struct stat tmp; + RUNNER_ASSERT_MSG(stat("/tmp/test3/example.txt", &tmp) == 0, + "Couldn't create the test file"); + + WrtUtilRemove("/tmp/test3"); + if (stat("/tmp/test3", &tmp) != 0) { + int error = errno; + RUNNER_ASSERT(error == ENOENT); + return; + } + RUNNER_ASSERT(false); +} + +/** + * Try to remove not existing folder. + */ +RUNNER_TEST(wrt_utility_WrtUtilRemoveDir_NoDirError) +{ + //First making sure the test dir doesn't exist + WrtUtilRemove("/tmp/NOT_EXISTING"); + + RUNNER_ASSERT_MSG(WrtUtilRemove("/tmp/NOT_EXISTING") == false, + "Removing non existing directory returned success"); +} + +/* +Name: wrt_utility_WrtUtilFileExists +Description: tests file existence +Expected: existing file should be reported as existing +*/ +RUNNER_TEST(wrt_utility_WrtUtilFileExists) +{ + std::ofstream file; + file.open("/tmp/test_file1"); + file.close(); + RUNNER_ASSERT(WrtUtilFileExists("/tmp/test_file1")); + + WrtUtilRemove("/tmp/test_file1"); + RUNNER_ASSERT(WrtUtilFileExists("/tmp/test_file1") == false); +} + +/* +Name: wrt_utility_WrtUtilDirExists +Description: tests directory existence +Expected: existing directory should be reported as existing +*/ +RUNNER_TEST(wrt_utility_WrtUtilDirExists) +{ + RUNNER_ASSERT(WrtUtilDirExists("/tmp")); + RUNNER_ASSERT(WrtUtilDirExists("/UNAVAILABLE_DIR") == false); +}