Workaround for memory garbage in SafeBuffer test
[platform/core/security/key-manager.git] / tests / test_safe-buffer.cpp
1 #include <vector>
2
3 #include <boost/test/unit_test.hpp>
4 #include <test_common.h>
5
6 #include <ckm/ckm-raw-buffer.h>
7
8 BOOST_GLOBAL_FIXTURE(TestConfig)
9
10 using namespace CKM;
11
12 namespace {
13
14 const size_t LEN = 100;
15
16 struct Item
17 {
18     Item(size_t a) : mA(a) {}
19     ~Item() {}
20
21     bool operator==(const size_t& other) const {
22         return mA == other;
23     }
24
25     size_t mA;
26 };
27
28 template <typename T>
29 size_t buffer_erase_test()
30 {
31     typename T::value_type* data = NULL;
32     typename T::size_type i = 0;
33     {
34         T buffer;
35         for (i=0;i<LEN;++i)
36             buffer.push_back(typename T::value_type(i));
37
38         data = buffer.data();
39
40         for (i=0;i<LEN;++i)
41             BOOST_CHECK(data[i] == i);
42     }
43
44     /*
45      *  operator delete of RawBuffer which is called after buffer memory is erased
46      *  (see erase_on_dealloc::deallocate) sometimes leaves garbage in the beginning of that memory.
47      *  Therefore the test will be marked as failing only if more than 1/10 of the data matches
48      *  original
49      */
50     size_t cnt = 0;
51     for (i=0;i<LEN;++i)
52         cnt += (data[i] == i?1:0);
53
54     return cnt;
55 }
56
57 } // namespace anonymous
58
59 BOOST_AUTO_TEST_SUITE(SAFE_BUFFER_TEST)
60
61 // Tests for SafeBuffer. Checks if memory occupied by the buffer is wiped after it's deleted.
62
63 BOOST_AUTO_TEST_CASE(SafeBufferTest_uc_control_group) {
64     size_t cnt = buffer_erase_test<std::vector<unsigned char> >();
65
66     BOOST_REQUIRE_MESSAGE(cnt > LEN/2, "Less than 1/2 of data matches the original.");
67 }
68
69 BOOST_AUTO_TEST_CASE(SafeBufferTest_item_control_group) {
70     size_t cnt = buffer_erase_test<std::vector<Item> >();
71
72     BOOST_REQUIRE_MESSAGE(cnt > LEN/2, "Less than 1/2 of data matches the original.");
73 }
74
75 BOOST_AUTO_TEST_CASE(SafeBufferTest_uc) {
76     size_t cnt = buffer_erase_test<RawBuffer>();
77
78     BOOST_REQUIRE_MESSAGE(cnt <= LEN/10, "More than 1/10 of data matches the original.");
79 }
80
81 BOOST_AUTO_TEST_CASE(SafeBufferTest_item) {
82     size_t cnt = buffer_erase_test<SafeBuffer<Item>::Type>();
83
84     BOOST_REQUIRE_MESSAGE(cnt <= LEN/10, "More than 1/10 of data matches the original.");
85 }
86
87 BOOST_AUTO_TEST_SUITE_END()