Blame posix/bug-getopt3.c

Packit 6c4009
/* BZ 11040 */
Packit 6c4009
#include <getopt.h>
Packit 6c4009
#include <unistd.h>
Packit 6c4009
#include <stdio.h>
Packit 6c4009
#include <stdlib.h>
Packit 6c4009
Packit 6c4009
static const struct option opts[] =
Packit 6c4009
  {
Packit 6c4009
    { "alpha",	no_argument,       NULL, 'a' },
Packit 6c4009
    { "beta",	required_argument, NULL, 'b' },
Packit 6c4009
    { NULL,	0,                 NULL, 0 }
Packit 6c4009
  };
Packit 6c4009
Packit 6c4009
static int
Packit 6c4009
one_test (const char *fmt, int argc, char *argv[], int n, int expected[n],
Packit 6c4009
	  int out[n])
Packit 6c4009
{
Packit 6c4009
  optind = 1;
Packit 6c4009
Packit 6c4009
  int res = 0;
Packit 6c4009
  for (int i = 0; i < n; ++i)
Packit 6c4009
    {
Packit 6c4009
      rewind (stderr);
Packit 6c4009
      if (ftruncate (fileno (stderr), 0) != 0)
Packit 6c4009
	{
Packit 6c4009
	  puts ("cannot truncate file");
Packit 6c4009
	  return 1;
Packit 6c4009
	}
Packit 6c4009
Packit 6c4009
      int c = getopt_long (argc, argv, fmt, opts, NULL);
Packit 6c4009
      if (c != expected[i])
Packit 6c4009
	{
Packit 6c4009
	  printf ("format '%s' test %d failed: expected '%c', got '%c'\n",
Packit 6c4009
		  fmt, i, expected[i], c);
Packit 6c4009
	  res = 1;
Packit 6c4009
	}
Packit 6c4009
      if ((ftell (stderr) != 0) != out[i])
Packit 6c4009
	{
Packit 6c4009
	  printf ("format '%s' test %d failed: %sprinted to stderr\n",
Packit 6c4009
		  fmt, i, out[i] ? "not " : "");
Packit 6c4009
	  res = 1;
Packit 6c4009
	}
Packit 6c4009
    }
Packit 6c4009
Packit 6c4009
  return res;
Packit 6c4009
}
Packit 6c4009
Packit 6c4009
Packit 6c4009
static int
Packit 6c4009
do_test (void)
Packit 6c4009
{
Packit 6c4009
  char fname[] = "/tmp/bug-getopt3.XXXXXX";
Packit 6c4009
  int fd = mkstemp (fname);
Packit 6c4009
  if (fd == -1)
Packit 6c4009
    {
Packit 6c4009
      printf ("mkstemp failed: %m\n");
Packit 6c4009
      return 1;
Packit 6c4009
    }
Packit 6c4009
  close (fd);
Packit 6c4009
Packit 6c4009
  if (freopen (fname, "w+", stderr) == NULL)
Packit 6c4009
    {
Packit 6c4009
      puts ("cannot redirect stderr");
Packit 6c4009
      return 1;
Packit 6c4009
    }
Packit 6c4009
Packit 6c4009
  remove (fname);
Packit 6c4009
Packit 6c4009
  int ret = one_test ("ab:W;", 2,
Packit 6c4009
		      (char *[2]) { (char *) "bug-getopt3", (char *) "-a;" },
Packit 6c4009
		      2, (int [2]) { 'a', '?' }, (int [2]) { 0, 1 });
Packit 6c4009
Packit 6c4009
  ret |= one_test ("ab:W;", 2,
Packit 6c4009
		   (char *[2]) { (char *) "bug-getopt3", (char *) "-a:" }, 2,
Packit 6c4009
		   (int [2]) { 'a', '?' }, (int [2]) { 0, 1 });
Packit 6c4009
Packit 6c4009
  if (ret == 0)
Packit 6c4009
    puts ("all OK");
Packit 6c4009
Packit 6c4009
  return ret;
Packit 6c4009
}
Packit 6c4009
Packit 6c4009
#define TEST_FUNCTION do_test ()
Packit 6c4009
#include "../test-skeleton.c"