lh | 9ed821d | 2023-04-07 01:36:19 -0700 | [diff] [blame^] | 1 | /* BZ 11040 */ |
| 2 | #include <getopt.h> |
| 3 | #include <unistd.h> |
| 4 | #include <stdio.h> |
| 5 | |
| 6 | static const struct option opts[] = |
| 7 | { |
| 8 | { "alpha", no_argument, NULL, 'a' }, |
| 9 | { "beta", required_argument, NULL, 'b' }, |
| 10 | { NULL, 0, NULL, 0 } |
| 11 | }; |
| 12 | |
| 13 | static int |
| 14 | one_test (const char *fmt, int argc, char *argv[], int n, int expected[n], |
| 15 | int out[n]) |
| 16 | { |
| 17 | optind = 1; |
| 18 | |
| 19 | int res = 0; |
| 20 | for (int i = 0; i < n; ++i) |
| 21 | { |
| 22 | rewind (stderr); |
| 23 | if (ftruncate (fileno (stderr), 0) != 0) |
| 24 | { |
| 25 | puts ("cannot truncate file"); |
| 26 | return 1; |
| 27 | } |
| 28 | |
| 29 | int c = getopt_long (argc, argv, fmt, opts, NULL); |
| 30 | if (c != expected[i]) |
| 31 | { |
| 32 | printf ("format '%s' test %d failed: expected '%c', got '%c'\n", |
| 33 | fmt, i, expected[i], c); |
| 34 | res = 1; |
| 35 | } |
| 36 | if ((ftell (stderr) != 0) != out[i]) |
| 37 | { |
| 38 | printf ("format '%s' test %d failed: %sprinted to stderr\n", |
| 39 | fmt, i, out[i] ? "not " : ""); |
| 40 | res = 1; |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | return res; |
| 45 | } |
| 46 | |
| 47 | |
| 48 | static int |
| 49 | do_test (void) |
| 50 | { |
| 51 | char *fname = tmpnam (NULL); |
| 52 | if (fname == NULL) |
| 53 | { |
| 54 | puts ("cannot generate name for temporary file"); |
| 55 | return 1; |
| 56 | } |
| 57 | |
| 58 | if (freopen (fname, "w+", stderr) == NULL) |
| 59 | { |
| 60 | puts ("cannot redirect stderr"); |
| 61 | return 1; |
| 62 | } |
| 63 | |
| 64 | remove (fname); |
| 65 | |
| 66 | int ret = one_test ("ab:W;", 2, |
| 67 | (char *[2]) { (char *) "bug-getopt3", (char *) "-a;" }, |
| 68 | 2, (int [2]) { 'a', '?' }, (int [2]) { 0, 1 }); |
| 69 | |
| 70 | ret |= one_test ("ab:W;", 2, |
| 71 | (char *[2]) { (char *) "bug-getopt3", (char *) "-a:" }, 2, |
| 72 | (int [2]) { 'a', '?' }, (int [2]) { 0, 1 }); |
| 73 | |
| 74 | if (ret == 0) |
| 75 | puts ("all OK"); |
| 76 | |
| 77 | return ret; |
| 78 | } |
| 79 | |
| 80 | #define TEST_FUNCTION do_test () |
| 81 | #include "../test-skeleton.c" |