DHTModules_handleIncoming_test.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include "dht/DHTModule.h"
  16. #include "dht/DHTModuleRegistry.h"
  17. #include "memory/Allocator.h"
  18. #include <stdio.h>
  19. struct Context
  20. {
  21. struct DHTMessage* theMessage;
  22. int ret;
  23. };
  24. static int handleIncoming(struct DHTMessage* message, void* vcontext)
  25. {
  26. struct Context* context = (struct Context*) vcontext;
  27. if (message == context->theMessage) {
  28. context->ret = 0;
  29. } else {
  30. context->ret = -2;
  31. }
  32. return 0;
  33. }
  34. static int testInputHandler()
  35. {
  36. struct DHTMessage theMessage;
  37. struct Context context =
  38. {
  39. .theMessage = &theMessage,
  40. .ret = -1
  41. };
  42. struct Context context2 =
  43. {
  44. .theMessage = &theMessage,
  45. .ret = -1
  46. };
  47. struct DHTModule module = {
  48. .name = "TestModule",
  49. .context = &context,
  50. .handleIncoming = handleIncoming
  51. };
  52. struct DHTModule module2 = {
  53. .name = "TestModule2",
  54. .context = &context2,
  55. .handleIncoming = handleIncoming
  56. };
  57. struct Allocator* allocator = Allocator_new(2048);
  58. struct DHTModuleRegistry* reg = DHTModuleRegistry_new(allocator, NULL);
  59. DHTModuleRegistry_register(&module, reg);
  60. DHTModuleRegistry_register(&module2, reg);
  61. DHTModuleRegistry_handleIncoming(&theMessage, reg);
  62. /* This should be ignored. */
  63. DHTModuleRegistry_handleOutgoing(&theMessage, reg);
  64. if (context.ret == -1) {
  65. printf("message not received");
  66. } else if (context.ret == -2) {
  67. printf("wrong message received");
  68. } else if (context2.ret == -1) {
  69. printf("message not received by all handlers.");
  70. } else if (context2.ret == -2) {
  71. printf("wrong message received by second handler.");
  72. } else {
  73. Allocator_free(allocator);
  74. return 0;
  75. }
  76. return -1;
  77. }
  78. int main()
  79. {
  80. return testInputHandler();
  81. }