testsupport.h 2.1 KB

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