test-assert.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. jmp_buf rec;
  13. char buf[160];
  14. static void
  15. sigabrt (int unused)
  16. {
  17. longjmp (rec, 1); /* recover control */
  18. }
  19. #undef NDEBUG
  20. #include <assert.h>
  21. static void
  22. assert1 (void)
  23. {
  24. assert (1 == 2);
  25. }
  26. static void
  27. assert2 (void)
  28. {
  29. assert (1 == 1);
  30. }
  31. #define NDEBUG
  32. #include <assert.h>
  33. static void
  34. assert3 (void)
  35. {
  36. assert (2 == 3);
  37. }
  38. int
  39. main (void)
  40. {
  41. volatile int failed = 1;
  42. fclose (stderr);
  43. stderr = tmpfile ();
  44. if(!stderr)
  45. abort ();
  46. signal (SIGABRT, sigabrt);
  47. if (!setjmp (rec))
  48. assert1 ();
  49. else
  50. failed = 0; /* should happen */
  51. if (!setjmp (rec))
  52. assert2 ();
  53. else
  54. failed = 1; /* should not happen */
  55. if (!setjmp (rec))
  56. assert3 ();
  57. else
  58. failed = 1; /* should not happen */
  59. rewind (stderr);
  60. fgets (buf, 160, stderr);
  61. if (!strstr (buf, "1 == 2"))
  62. failed = 1;
  63. fgets (buf, 160, stderr);
  64. if (strstr (buf, "1 == 1"))
  65. failed = 1;
  66. fgets (buf, 160, stderr);
  67. if (strstr (buf, "2 == 3"))
  68. failed = 1;
  69. return failed;
  70. }