Line data Source code
1 : // Copyright (c) 2016 The Bitcoin Core developers 2 : // Distributed under the MIT software license, see the accompanying 3 : // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 : 5 : #include <event2/event.h> 6 : 7 : #ifdef EVENT_SET_MEM_FUNCTIONS_IMPLEMENTED 8 : // It would probably be ideal to define dummy test(s) that report skipped, but boost::test doesn't seem to make that practical (at least not in versions available with common distros) 9 : 10 : #include <map> 11 : #include <stdlib.h> 12 : 13 : #include "support/events.h" 14 : 15 : #include "test/test_pivx.h" 16 : 17 : #include <boost/test/unit_test.hpp> 18 : 19 : static std::map<void*, short> tags; 20 : static std::map<void*, uint16_t> orders; 21 : static uint16_t tagSequence = 0; 22 : 23 17 : static void* tag_malloc(size_t sz) { 24 17 : void* mem = malloc(sz); 25 17 : if (!mem) return mem; 26 17 : tags[mem]++; 27 17 : orders[mem] = tagSequence++; 28 17 : return mem; 29 : } 30 : 31 17 : static void tag_free(void* mem) { 32 17 : tags[mem]--; 33 17 : orders[mem] = tagSequence++; 34 17 : free(mem); 35 17 : } 36 : 37 : BOOST_FIXTURE_TEST_SUITE(raii_event_tests, BasicTestingSetup) 38 : 39 2 : BOOST_AUTO_TEST_CASE(raii_event_creation) 40 : { 41 1 : event_set_mem_functions(tag_malloc, realloc, tag_free); 42 : 43 1 : void* base_ptr = nullptr; 44 1 : { 45 1 : auto base = obtain_event_base(); 46 1 : base_ptr = (void*)base.get(); 47 2 : BOOST_CHECK(tags[base_ptr] == 1); 48 : } 49 2 : BOOST_CHECK(tags[base_ptr] == 0); 50 : 51 1 : void* event_ptr = nullptr; 52 1 : { 53 1 : auto base = obtain_event_base(); 54 2 : auto event = obtain_event(base.get(), -1, 0, nullptr, nullptr); 55 : 56 1 : base_ptr = (void*)base.get(); 57 1 : event_ptr = (void*)event.get(); 58 : 59 2 : BOOST_CHECK(tags[base_ptr] == 1); 60 2 : BOOST_CHECK(tags[event_ptr] == 1); 61 : } 62 2 : BOOST_CHECK(tags[base_ptr] == 0); 63 2 : BOOST_CHECK(tags[event_ptr] == 0); 64 : 65 1 : event_set_mem_functions(malloc, realloc, free); 66 1 : } 67 : 68 2 : BOOST_AUTO_TEST_CASE(raii_event_order) 69 : { 70 1 : event_set_mem_functions(tag_malloc, realloc, tag_free); 71 : 72 1 : void* base_ptr = nullptr; 73 1 : void* event_ptr = nullptr; 74 1 : { 75 1 : auto base = obtain_event_base(); 76 2 : auto event = obtain_event(base.get(), -1, 0, nullptr, nullptr); 77 : 78 1 : base_ptr = (void*)base.get(); 79 1 : event_ptr = (void*)event.get(); 80 : 81 : // base should have allocated before event 82 2 : BOOST_CHECK(orders[base_ptr] < orders[event_ptr]); 83 : } 84 : // base should be freed after event 85 2 : BOOST_CHECK(orders[base_ptr] > orders[event_ptr]); 86 : 87 1 : event_set_mem_functions(malloc, realloc, free); 88 1 : } 89 : 90 : BOOST_AUTO_TEST_SUITE_END() 91 : 92 : #endif // EVENT_SET_MEM_FUNCTIONS_IMPLEMENTED