testlib.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. /* testlib.c --- reporting test results
  2. Jim Blandy <jimb@red-bean.com> --- August 1999 */
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include "testlib.h"
  6. /* Dying. */
  7. static void
  8. fatal (char *message)
  9. {
  10. fprintf (stderr, "%s\n", message);
  11. exit (1);
  12. }
  13. /* Contexts. */
  14. /* If it gets deeper than this, that's probably an error, right? */
  15. #define MAX_NESTING 10
  16. int depth = 0;
  17. char *context_name_stack[MAX_NESTING];
  18. int marker;
  19. int context_marker_stack[MAX_NESTING];
  20. test_context_t
  21. test_enter_context (char *name)
  22. {
  23. if (depth >= MAX_NESTING)
  24. fatal ("test contexts nested too deeply");
  25. /* Generate a unique marker value for this context. */
  26. marker++;
  27. context_name_stack[depth] = name;
  28. context_marker_stack[depth] = marker;
  29. depth++;
  30. return marker;
  31. }
  32. void
  33. test_restore_context (test_context_t context)
  34. {
  35. if (depth <= 0)
  36. fatal ("attempt to leave outermost context");
  37. depth--;
  38. /* Make sure that we're exiting the same context we last entered. */
  39. if (context_marker_stack[depth] != context)
  40. fatal ("contexts not nested properly");
  41. }
  42. /* Reporting results. */
  43. int count_passes, count_fails;
  44. static void
  45. print_test_name (char *name)
  46. {
  47. int i;
  48. for (i = 0; i < depth; i++)
  49. printf ("%s: ", context_name_stack[i]);
  50. printf ("%s", name);
  51. }
  52. static void
  53. print_result (char *result, char *name)
  54. {
  55. printf ("%s: ", result);
  56. print_test_name (name);
  57. putchar ('\n');
  58. }
  59. void
  60. test_pass (char *name)
  61. {
  62. print_result ("PASS", name);
  63. count_passes++;
  64. }
  65. void
  66. test_fail (char *name)
  67. {
  68. print_result ("FAIL", name);
  69. count_fails++;
  70. }
  71. void
  72. test_pass_if (char *name, int condition)
  73. {
  74. (condition ? test_pass : test_fail) (name);
  75. }
  76. /* Printing a summary. */
  77. /* Print a summary of the reported test results. Return zero if
  78. no failures occurred, one otherwise. */
  79. int
  80. test_summarize ()
  81. {
  82. putchar ('\n');
  83. printf ("passes: %d\n", count_passes);
  84. printf ("failures: %d\n", count_fails);
  85. printf ("total tests: %d\n", count_passes + count_fails);
  86. return (count_fails != 0);
  87. }