test-assert.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /* Test assert().
  2. *
  3. * This is hairier than you'd think, involving games with
  4. * stdio and signals.
  5. *
  6. */
  7. #include <signal.h>
  8. #include <stdlib.h>
  9. #include <stdio.h>
  10. #include <string.h>
  11. #include <setjmp.h>
  12. #include <support/xstdio.h>
  13. jmp_buf rec;
  14. char buf[160];
  15. static void
  16. sigabrt (int unused)
  17. {
  18. longjmp (rec, 1); /* recover control */
  19. }
  20. #undef NDEBUG
  21. #include <assert.h>
  22. static void
  23. assert1 (void)
  24. {
  25. assert (1 == 2);
  26. }
  27. static void
  28. assert2 (void)
  29. {
  30. assert (1 == 1);
  31. }
  32. #define NDEBUG
  33. #include <assert.h>
  34. static void
  35. assert3 (void)
  36. {
  37. assert (2 == 3);
  38. }
  39. int
  40. main (void)
  41. {
  42. volatile int failed = 1;
  43. fclose (stderr);
  44. stderr = tmpfile ();
  45. if(!stderr)
  46. abort ();
  47. signal (SIGABRT, sigabrt);
  48. if (!setjmp (rec))
  49. assert1 ();
  50. else
  51. failed = 0; /* should happen */
  52. if (!setjmp (rec))
  53. assert2 ();
  54. else
  55. failed = 1; /* should not happen */
  56. if (!setjmp (rec))
  57. assert3 ();
  58. else
  59. failed = 1; /* should not happen */
  60. rewind (stderr);
  61. xfgets (buf, 160, stderr);
  62. if (!strstr (buf, "1 == 2"))
  63. failed = 1;
  64. xfgets (buf, 160, stderr);
  65. if (strstr (buf, "1 == 1"))
  66. failed = 1;
  67. xfgets (buf, 160, stderr);
  68. if (strstr (buf, "2 == 3"))
  69. failed = 1;
  70. return failed;
  71. }