testsupport.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /* Copyright (c) 2013-2016, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. #ifndef TOR_TESTSUPPORT_H
  4. #define TOR_TESTSUPPORT_H
  5. #ifdef TOR_UNIT_TESTS
  6. #define STATIC
  7. #define EXTERN(type, name) extern type name;
  8. #else
  9. #define STATIC static
  10. #define EXTERN(type, name)
  11. #endif
  12. /** Quick and dirty macros to implement test mocking.
  13. *
  14. * To use them, suppose that you have a function you'd like to mock
  15. * with the signature "void writebuf(size_t n, char *buf)". You can then
  16. * declare the function as:
  17. *
  18. * MOCK_DECL(void, writebuf, (size_t n, char *buf));
  19. *
  20. * and implement it as:
  21. *
  22. * MOCK_IMPL(void,
  23. * writebuf,(size_t n, char *buf))
  24. * {
  25. * ...
  26. * }
  27. *
  28. * For the non-testing build, this will expand simply into:
  29. *
  30. * void writebuf(size_t n, char *buf);
  31. * void
  32. * writebuf(size_t n, char *buf)
  33. * {
  34. * ...
  35. * }
  36. *
  37. * But for the testing case, it will expand into:
  38. *
  39. * void writebuf__real(size_t n, char *buf);
  40. * extern void (*writebuf)(size_t n, char *buf);
  41. *
  42. * void (*writebuf)(size_t n, char *buf) = writebuf__real;
  43. * void
  44. * writebuf__real(size_t n, char *buf)
  45. * {
  46. * ...
  47. * }
  48. *
  49. * This is not a great mocking system! It is deliberately "the simplest
  50. * thing that could work", and pays for its simplicity in its lack of
  51. * features, and in its uglification of the Tor code. Replacing it with
  52. * something clever would be a fine thing.
  53. *
  54. * @{ */
  55. #ifdef TOR_UNIT_TESTS
  56. #define MOCK_DECL(rv, funcname, arglist) \
  57. rv funcname ##__real arglist; \
  58. extern rv(*funcname) arglist
  59. #define MOCK_IMPL(rv, funcname, arglist) \
  60. rv(*funcname) arglist = funcname ##__real; \
  61. rv funcname ##__real arglist
  62. #define MOCK_DECL_ATTR(rv, funcname, arglist, attr) \
  63. rv funcname ##__real arglist attr; \
  64. extern rv(*funcname) arglist
  65. #define MOCK_IMPL(rv, funcname, arglist) \
  66. rv(*funcname) arglist = funcname ##__real; \
  67. rv funcname ##__real arglist
  68. #define MOCK(func, replacement) \
  69. do { \
  70. (func) = (replacement); \
  71. } while (0)
  72. #define UNMOCK(func) \
  73. do { \
  74. func = func ##__real; \
  75. } while (0)
  76. #else
  77. #define MOCK_DECL(rv, funcname, arglist) \
  78. rv funcname arglist
  79. #define MOCK_DECL_ATTR(rv, funcname, arglist, attr) \
  80. rv funcname arglist attr
  81. #define MOCK_IMPL(rv, funcname, arglist) \
  82. rv funcname arglist
  83. #endif
  84. /** @} */
  85. #endif