test_handles.c (2129B)
1 /* Copyright (c) 2016-2021, The Tor Project, Inc. */ 2 /* See LICENSE for licensing information */ 3 4 #include "orconfig.h" 5 #include "test/test.h" 6 7 #include "lib/container/handles.h" 8 #include "lib/log/util_bug.h" 9 10 #include <stdio.h> 11 12 typedef struct demo_t { 13 HANDLE_ENTRY(demo, demo_t); 14 int val; 15 } demo_t; 16 17 HANDLE_DECL(demo, demo_t, static) 18 #define demo_handle_free(h) \ 19 FREE_AND_NULL(demo_handle_t, demo_handle_free_, (h)) 20 HANDLE_IMPL(demo, demo_t, static) 21 22 static demo_t * 23 demo_new(int val) 24 { 25 demo_t *d = tor_malloc_zero(sizeof(demo_t)); 26 d->val = val; 27 return d; 28 } 29 30 static void 31 demo_free(demo_t *d) 32 { 33 if (d == NULL) 34 return; 35 demo_handles_clear(d); 36 tor_free(d); 37 } 38 39 static void 40 test_handle_basic(void *arg) 41 { 42 (void) arg; 43 demo_t *d1 = NULL, *d2 = NULL; 44 demo_handle_t *wr1 = NULL, *wr2 = NULL, *wr3 = NULL, *wr4 = NULL; 45 46 d1 = demo_new(9000); 47 d2 = demo_new(9009); 48 49 wr1 = demo_handle_new(d1); 50 wr2 = demo_handle_new(d1); 51 wr3 = demo_handle_new(d1); 52 wr4 = demo_handle_new(d2); 53 54 tt_assert(wr1); 55 tt_assert(wr2); 56 tt_assert(wr3); 57 tt_assert(wr4); 58 59 tt_ptr_op(demo_handle_get(wr1), OP_EQ, d1); 60 tt_ptr_op(demo_handle_get(wr2), OP_EQ, d1); 61 tt_ptr_op(demo_handle_get(wr3), OP_EQ, d1); 62 tt_ptr_op(demo_handle_get(wr4), OP_EQ, d2); 63 64 demo_handle_free(wr1); 65 wr1 = NULL; 66 tt_ptr_op(demo_handle_get(wr2), OP_EQ, d1); 67 tt_ptr_op(demo_handle_get(wr3), OP_EQ, d1); 68 tt_ptr_op(demo_handle_get(wr4), OP_EQ, d2); 69 70 demo_free(d1); 71 d1 = NULL; 72 tt_ptr_op(demo_handle_get(wr2), OP_EQ, NULL); 73 tt_ptr_op(demo_handle_get(wr3), OP_EQ, NULL); 74 tt_ptr_op(demo_handle_get(wr4), OP_EQ, d2); 75 76 demo_handle_free(wr2); 77 wr2 = NULL; 78 tt_ptr_op(demo_handle_get(wr3), OP_EQ, NULL); 79 tt_ptr_op(demo_handle_get(wr4), OP_EQ, d2); 80 81 demo_handle_free(wr3); 82 wr3 = NULL; 83 done: 84 demo_handle_free(wr1); 85 demo_handle_free(wr2); 86 demo_handle_free(wr3); 87 demo_handle_free(wr4); 88 demo_free(d1); 89 demo_free(d2); 90 } 91 92 #define HANDLE_TEST(name, flags) \ 93 { #name, test_handle_ ##name, (flags), NULL, NULL } 94 95 struct testcase_t handle_tests[] = { 96 HANDLE_TEST(basic, 0), 97 END_OF_TESTCASES 98 };