test_handles.c 2.1 KB

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