test_pubsub.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /* Copyright (c) 2016-2017, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file test_pubsub.c
  5. * \brief Unit tests for publish-subscribe abstraction.
  6. **/
  7. #include "or.h"
  8. #include "test.h"
  9. #include "pubsub.h"
  10. DECLARE_PUBSUB_STRUCT_TYPES(foobar)
  11. DECLARE_PUBSUB_TOPIC(foobar)
  12. DECLARE_NOTIFY_PUBSUB_TOPIC(static, foobar)
  13. IMPLEMENT_PUBSUB_TOPIC(static, foobar)
  14. struct foobar_event_data_t {
  15. unsigned u;
  16. const char *s;
  17. };
  18. struct foobar_subscriber_data_t {
  19. const char *name;
  20. long l;
  21. };
  22. static int
  23. foobar_sub1(foobar_event_data_t *ev, foobar_subscriber_data_t *mine)
  24. {
  25. ev->u += 10;
  26. mine->l += 100;
  27. return 0;
  28. }
  29. static int
  30. foobar_sub2(foobar_event_data_t *ev, foobar_subscriber_data_t *mine)
  31. {
  32. ev->u += 5;
  33. mine->l += 50;
  34. return 0;
  35. }
  36. static void
  37. test_pubsub_basic(void *arg)
  38. {
  39. (void)arg;
  40. foobar_subscriber_data_t subdata1 = { "hi", 0 };
  41. foobar_subscriber_data_t subdata2 = { "wow", 0 };
  42. const foobar_subscriber_t *sub1;
  43. const foobar_subscriber_t *sub2;
  44. foobar_event_data_t ed = { 0, "x" };
  45. foobar_event_data_t ed2 = { 0, "y" };
  46. sub1 = foobar_subscribe(foobar_sub1, &subdata1, SUBSCRIBE_ATSTART, 100);
  47. tt_assert(sub1);
  48. foobar_notify(&ed, 0);
  49. tt_int_op(subdata1.l, OP_EQ, 100);
  50. tt_int_op(subdata2.l, OP_EQ, 0);
  51. tt_int_op(ed.u, OP_EQ, 10);
  52. sub2 = foobar_subscribe(foobar_sub2, &subdata2, 0, 5);
  53. tt_assert(sub2);
  54. foobar_notify(&ed2, 0);
  55. tt_int_op(subdata1.l, OP_EQ, 200);
  56. tt_int_op(subdata2.l, OP_EQ, 50);
  57. tt_int_op(ed2.u, OP_EQ, 15);
  58. foobar_unsubscribe(sub1);
  59. foobar_notify(&ed, 0);
  60. tt_int_op(subdata1.l, OP_EQ, 200);
  61. tt_int_op(subdata2.l, OP_EQ, 100);
  62. tt_int_op(ed.u, OP_EQ, 15);
  63. done:
  64. foobar_clear();
  65. }
  66. struct testcase_t pubsub_tests[] = {
  67. { "pubsub_basic", test_pubsub_basic, TT_FORK, NULL, NULL },
  68. END_OF_TESTCASES
  69. };