test-getopt: test stderr behavior
[gnulib.git] / tests / test-getopt.c
index 591cf0b..6811a02 100644 (file)
 
 #include <config.h>
 
+/* None of the files accessed by this test are large, so disable the
+   ftell link warning if we are not using the gnulib ftell module.  */
+#if !GNULIB_FTELL
+# undef GL_LINK_WARNING
+# define GL_LINK_WARNING(ignored) ((void) 0)
+#endif
+
 #if GNULIB_GETOPT_GNU
 # include <getopt.h>
 #endif
 #include <stdlib.h>
 #include <string.h>
 
+/* This test intentionally remaps stderr.  So, we arrange to have fd 10
+   (outside the range of interesting fd's during the test) set up to
+   duplicate the original stderr.  */
+
+#define BACKUP_STDERR_FILENO 10
+static FILE *myerr;
+
 #define ASSERT(expr) \
   do                                                                         \
     {                                                                        \
       if (!(expr))                                                           \
         {                                                                    \
-          fprintf (stderr, "%s:%d: assertion failed\n", __FILE__, __LINE__); \
-          fflush (stderr);                                                   \
+          fprintf (myerr, "%s:%d: assertion failed\n", __FILE__, __LINE__);  \
+          fflush (myerr);                                                    \
           abort ();                                                          \
         }                                                                    \
     }                                                                        \
 int
 main (void)
 {
+   /* This test validates that stderr is used correctly, so move the
+      original into fd 10.  */
+  if (dup2 (STDERR_FILENO, BACKUP_STDERR_FILENO) != BACKUP_STDERR_FILENO
+      || (myerr = fdopen (BACKUP_STDERR_FILENO, "w")) == NULL)
+    return 2;
+
+  ASSERT (freopen ("test-getopt.tmp", "w", stderr) == stderr);
+
   /* These default values are required by POSIX.  */
   ASSERT (optind == 1);
   ASSERT (opterr != 0);
@@ -66,5 +88,8 @@ main (void)
   test_getopt_long_only ();
 #endif
 
+  ASSERT (fclose (stderr) == 0);
+  ASSERT (remove ("test-getopt.tmp") == 0);
+
   return 0;
 }