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