WritingTests.txt 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. Writing tests for Tor: an incomplete guide
  2. ==========================================
  3. Tor uses a variety of testing frameworks and methodologies to try to
  4. keep from introducing bugs. The major ones are:
  5. 1. Unit tests written in C and shipped with the Tor distribution.
  6. 2. Integration tests written in Python and shipped with the Tor
  7. distribution.
  8. 3. Integration tests written in Python and shipped with the Stem
  9. library. Some of these use the Tor controller protocol.
  10. 4. System tests written in Python and SH, and shipped with the
  11. Chutney package. These work by running many instances of Tor
  12. locally, and sending traffic through them.
  13. 5. The Shadow network simulator.
  14. How to run these tests
  15. ----------------------
  16. === The easy version
  17. To run all the tests that come bundled with Tor, run "make check"
  18. To run the Stem tests as well, fetch stem from the git repository,
  19. set STEM_SOURCE_DIR to the checkout, and run "make test-stem".
  20. To run the Chutney tests as well, fetch chutney from the git repository,
  21. set CHUTNEY_PATH to the checkout, and run "make test-network".
  22. To run all of the above, run "make test-full".
  23. To run all of the above, plus tests that require a working connection to the
  24. internet, run "make test-full-online".
  25. === Running particular subtests
  26. The Tor unit tests are divided into separate programs and a couple of
  27. bundled unit test programs.
  28. Separate programs are easy. For example, to run the memwipe tests in
  29. isolation, you just run ./src/test/test-memwipe .
  30. To run tests within the unit test programs, you can specify the name
  31. of the test. The string ".." can be used as a wildcard at the end of the
  32. test name. For example, to run all the cell format tests, enter
  33. "./src/test/test cellfmt/..". To run
  34. Many tests that need to mess with global state run in forked subprocesses in
  35. order to keep from contaminating one another. But when debugging a failing test,
  36. you might want to run it without forking a subprocess. To do so, use the
  37. "--no-fork" option with a single test. (If you specify it along with
  38. multiple tests, they might interfere.)
  39. You can turn on logging in the unit tests by passing one of "--debug",
  40. "--info", "--notice", or "--warn". By default only errors are displayed.
  41. Unit tests are divided into "./src/test/test" and "./src/test/test-slow".
  42. The former are those that should finish in a few seconds; the latter tend to
  43. take more time, and may include CPU-intensive operations, deliberate delays,
  44. and stuff like that.
  45. === Finding test coverage
  46. When you configure Tor with the --enable-coverage option, it should
  47. build with support for coverage in the unit tests, and in a special
  48. "tor-cov" binary.
  49. Then, run the tests you'd like to see coverage from. If you have old
  50. coverage output, you may need to run "reset-gcov" first.
  51. Now you've got a bunch of files scattered around your build directories
  52. called "*.gcda". In order to extract the coverage output from them, make a
  53. temporary directory for them and run "./scripts/test/coverage ${TMPDIR}",
  54. where ${TMPDIR} is the temporary directory you made. This will create a
  55. ".gcov" file for each source file under tests, containing that file's source
  56. annotated with the number of times the tests hit each line. (You'll need to
  57. have gcov installed.)
  58. You can get a summary of the test coverage for each file by running
  59. "./scripts/test/cov-display ${TMPDIR}/*" . Each line lists the file's name,
  60. the number of uncovered lines, the number of uncovered lines, and the
  61. coverage percentage.
  62. For a summary of the test coverage for each _function_, run
  63. "./scripts/test/cov-display -f ${TMPDIR}/*" .
  64. === Comparing test coverage
  65. Sometimes it's useful to compare test coverage for a branch you're writing to
  66. coverage from another branch (such as git master, for example). But you
  67. can't run "diff" on the two coverage outputs directly, since the actual
  68. number of times each line is executed aren't so important, and aren't wholly
  69. deterministic.
  70. Instead, follow the instructions above for each branch, creating a separate
  71. temporary directory for each. Then, run "./scripts/test/cov-diff ${D1}
  72. ${D2}", where D1 and D2 are the directories you want to compare. This will
  73. produce a diff of the two directories, with all lines normalized to be either
  74. covered or uncovered.
  75. To count new or modified uncovered lines in D2, you can run:
  76. "./scripts/test/cov-diff ${D1} ${D2}" | grep '^+ *\#' |wc -l
  77. What kinds of test should I write?
  78. ----------------------------------
  79. Integration testing and unit testing are complementary: it's probably a
  80. good idea to make sure that your code is hit by both if you can.
  81. If your code is very-low level, and its behavior is easily described in
  82. terms of a relation between inputs and outputs, or a set of state
  83. transitions, then it's a natural fit for unit tests. (If not, please
  84. consider refactoring it until most of it _is_ a good fit for unit
  85. tests!)
  86. If your code adds new externally visible functionality to Tor, it would
  87. be great to have a test for that functionality. That's where
  88. integration tests more usually come in.
  89. Unit and regression tests: Does this function do what it's supposed to?
  90. -----------------------------------------------------------------------
  91. Most of Tor's unit tests are made using the "tinytest" testing framework.
  92. You can see a guide to using it in the tinytest manual at
  93. https://github.com/nmathewson/tinytest/blob/master/tinytest-manual.md
  94. To add a new test of this kind, either edit an existing C file in src/test/,
  95. or create a new C file there. Each test is a single function that must
  96. be indexed in the table at the end of the file. We use the label "done:" as
  97. a cleanup point for all test functions.
  98. (Make sure you read tinytest-manual.md before proceeding.)
  99. I use the term "unit test" and "regression tests" very sloppily here.
  100. === A simple example
  101. Here's an example of a test function for a simple function in util.c:
  102. static void
  103. test_util_writepid(void *arg)
  104. {
  105. (void) arg;
  106. char *contents = NULL;
  107. const char *fname = get_fname("tmp_pid");
  108. unsigned long pid;
  109. char c;
  110. write_pidfile(fname);
  111. contents = read_file_to_str(fname, 0, NULL);
  112. tt_assert(contents);
  113. int n = sscanf(contents, "%lu\n%c", &pid, &c);
  114. tt_int_op(n, OP_EQ, 1);
  115. tt_int_op(pid, OP_EQ, getpid());
  116. done:
  117. tor_free(contents);
  118. }
  119. This should look pretty familiar to you if you've read the tinytest
  120. manual. One thing to note here is that we use the testing-specific
  121. function "get_fname" to generate a file with respect to a temporary
  122. directory that the tests use. You don't need to delete the file;
  123. it will get removed when the tests are done.
  124. Also note our use of OP_EQ instead of == in the tt_int_op() calls.
  125. We define OP_* macros to use instead of the binary comparison
  126. operators so that analysis tools can more easily parse our code.
  127. (Coccinelle really hates to see == used as a macro argument.)
  128. Finally, remember that by convention, all *_free() functions that
  129. Tor defines are defined to accept NULL harmlessly. Thus, you don't
  130. need to say "if (contents)" in the cleanup block.
  131. === Exposing static functions for testing
  132. Sometimes you need to test a function, but you don't want to expose
  133. it outside its usual module.
  134. To support this, Tor's build system compiles a testing version of
  135. each module, with extra identifiers exposed. If you want to
  136. declare a function as static but available for testing, use the
  137. macro "STATIC" instead of "static". Then, make sure there's a
  138. macro-protected declaration of the function in the module's header.
  139. For example, crypto_curve25519.h contains:
  140. #ifdef CRYPTO_CURVE25519_PRIVATE
  141. STATIC int curve25519_impl(uint8_t *output, const uint8_t *secret,
  142. const uint8_t *basepoint);
  143. #endif
  144. The crypto_curve25519.c file and the test_crypto.c file both define
  145. CRYPTO_CURVE25519_PRIVATE, so they can see this declaration.
  146. === Mock functions for testing in isolation
  147. Often we want to test that a function works right, but the function to
  148. be tested depends on other functions whose behavior is hard to observe,
  149. or which require a working Tor network, or something like that.
  150. To write tests for this case, you can replace the underlying functions
  151. with testing stubs while your unit test is running. You need to declare
  152. the underlying function as 'mockable', as follows:
  153. MOCK_DECL(returntype, functionname, (argument list));
  154. and then later implement it as:
  155. MOCK_IMPL(returntype, functionname, (argument list))
  156. {
  157. /* implementation here */
  158. }
  159. For example, if you had a 'connect to remote server' function, you could
  160. declare it as:
  161. MOCK_DECL(int, connect_to_remote, (const char *name, status_t *status));
  162. When you declare a function this way, it will be declared as normal in
  163. regular builds, but when the module is built for testing, it is declared
  164. as a function pointer initialized to the actual implementation.
  165. In your tests, if you want to override the function with a temporary
  166. replacement, you say:
  167. MOCK(functionname, replacement_function_name);
  168. And later, you can restore the original function with:
  169. UNMOCK(functionname);
  170. For more information, see the definitions of this mocking logic in
  171. testsupport.h.
  172. === Advanced techniques: Namespaces
  173. XXXX write this. danah boyd made us some really awesome stuff here.
  174. Integration tests: Calling Tor from the outside
  175. -----------------------------------------------
  176. XXXX WRITEME
  177. Writing integration tests with Stem
  178. -----------------------------------
  179. XXXX WRITEME
  180. System testing with Chutney
  181. ---------------------------
  182. XXXX WRITEME
  183. Who knows what evil lurks in the timings of networks? The Shadow knows!
  184. -----------------------------------------------------------------------
  185. XXXX WRITEME