Back to index

glibc  2.9
test-assert.c
Go to the documentation of this file.
00001 /* Test assert().
00002  *
00003  * This is hairier than you'd think, involving games with
00004  * stdio and signals.
00005  *
00006  */
00007 
00008 #include <signal.h>
00009 #include <stdlib.h>
00010 #include <stdio.h>
00011 #include <string.h>
00012 #include <setjmp.h>
00013 
00014 jmp_buf rec;
00015 char buf[160];
00016 
00017 static void
00018 sigabrt (int unused)
00019 {
00020   longjmp (rec, 1);  /* recover control */
00021 }
00022 
00023 #undef NDEBUG
00024 #include <assert.h>
00025 static void
00026 assert1 (void)
00027 {
00028   assert (1 == 2);
00029 }
00030 
00031 static void
00032 assert2 (void)
00033 {
00034   assert (1 == 1);
00035 }
00036 
00037 
00038 #define NDEBUG
00039 #include <assert.h>
00040 static void
00041 assert3 (void)
00042 {
00043   assert (2 == 3);
00044 }
00045 
00046 int
00047 main (void)
00048 {
00049 
00050   volatile int failed = 1;
00051 
00052   fclose (stderr);
00053   stderr = tmpfile ();
00054   if(!stderr)
00055     abort ();
00056 
00057   signal (SIGABRT, sigabrt);
00058 
00059   if (!setjmp (rec))
00060     assert1 ();
00061   else
00062     failed = 0;  /* should happen */
00063 
00064   if (!setjmp (rec))
00065     assert2 ();
00066   else
00067     failed = 1; /* should not happen */
00068 
00069   if (!setjmp (rec))
00070     assert3 ();
00071   else
00072     failed = 1; /* should not happen */
00073 
00074   rewind (stderr);
00075   fgets (buf, 160, stderr);
00076   if (!strstr (buf, "1 == 2"))
00077     failed = 1;
00078 
00079   fgets (buf, 160, stderr);
00080   if (strstr (buf, "1 == 1"))
00081     failed = 1;
00082 
00083   fgets (buf, 160, stderr);
00084   if (strstr (buf, "2 == 3"))
00085     failed = 1;
00086 
00087   return failed;
00088 }