]>
Commit | Line | Data |
---|---|---|
e3267684 UD |
1 | /* BZ 11041 */ |
2 | #include <getopt.h> | |
3 | #include <unistd.h> | |
4 | #include <stdio.h> | |
5c112f1b | 5 | #include <stdlib.h> |
e3267684 UD |
6 | |
7 | static const struct option opts[] = | |
8 | { | |
9 | { "alpha", optional_argument, NULL, 'a' }, | |
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 | { | |
16 | optind = 1; | |
17 | ||
18 | int res = 0; | |
19 | for (int i = 0; i < n; ++i) | |
20 | { | |
21 | rewind (stderr); | |
22 | if (ftruncate (fileno (stderr), 0) != 0) | |
23 | { | |
24 | puts ("cannot truncate file"); | |
25 | return 1; | |
26 | } | |
27 | ||
28 | int c = getopt_long (argc, argv, fmt, opts, NULL); | |
29 | if (c != expected[i]) | |
30 | { | |
dfbea09f ZW |
31 | printf ("%s: format '%s' test %d failed: expected '%c', got '%c'\n", |
32 | argv[0], fmt, i, expected[i], c); | |
e3267684 UD |
33 | res = 1; |
34 | } | |
35 | else if (optarg != NULL) | |
36 | { | |
dfbea09f ZW |
37 | printf ("%s: format '%s' test %d failed: optarg is \"%s\", not NULL\n", |
38 | argv[0], fmt, i, optarg); | |
e3267684 UD |
39 | res = 1; |
40 | } | |
41 | if (ftell (stderr) != 0) | |
42 | { | |
dfbea09f ZW |
43 | printf ("%s: format '%s' test %d failed: printed to stderr\n", |
44 | argv[0], fmt, i); | |
e3267684 UD |
45 | res = 1; |
46 | } | |
47 | } | |
48 | ||
49 | return res; | |
50 | } | |
51 | ||
52 | ||
53 | static int | |
54 | do_test (void) | |
55 | { | |
5c112f1b JM |
56 | char fname[] = "/tmp/bug-getopt4.XXXXXX"; |
57 | int fd = mkstemp (fname); | |
58 | if (fd == -1) | |
e3267684 | 59 | { |
5c112f1b | 60 | printf ("mkstemp failed: %m\n"); |
e3267684 UD |
61 | return 1; |
62 | } | |
5c112f1b | 63 | close (fd); |
e3267684 UD |
64 | |
65 | if (freopen (fname, "w+", stderr) == NULL) | |
66 | { | |
67 | puts ("cannot redirect stderr"); | |
68 | return 1; | |
69 | } | |
70 | ||
71 | remove (fname); | |
72 | ||
73 | int ret = one_test ("W;", 2, | |
dfbea09f | 74 | (char *[2]) { (char *) "bug-getopt4a", (char *) "--a" }, |
e3267684 UD |
75 | 1, (int [1]) { 'a' }); |
76 | ||
77 | ret |= one_test ("W;", 3, | |
dfbea09f | 78 | (char *[3]) { (char *) "bug-getopt4b", (char *) "-W", |
e3267684 UD |
79 | (char *) "a" }, |
80 | 1, (int [1]) { 'a' }); | |
81 | ||
82 | if (ret == 0) | |
83 | puts ("all OK"); | |
84 | ||
85 | return ret; | |
86 | } | |
87 | ||
88 | #define TEST_FUNCTION do_test () | |
89 | #include "../test-skeleton.c" |