tests: add signature checks
[gnulib.git] / tests / test-getcwd.c
1 /* Test of getcwd() function.
2    Copyright (C) 2009 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 #include <config.h>
18
19 #include <unistd.h>
20
21 #include "signature.h"
22 SIGNATURE_CHECK (getcwd, char *, (char *, size_t));
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27
28 #define ASSERT(expr) \
29   do                                                                         \
30     {                                                                        \
31       if (!(expr))                                                           \
32         {                                                                    \
33           fprintf (stderr, "%s:%d: assertion failed\n", __FILE__, __LINE__); \
34           fflush (stderr);                                                   \
35           abort ();                                                          \
36         }                                                                    \
37     }                                                                        \
38   while (0)
39
40 int
41 main (int argc, char **argv)
42 {
43   char *pwd1;
44   char *pwd2;
45   /* If the user provides an argument, attempt to chdir there first.  */
46   if (1 < argc)
47     {
48       if (chdir (argv[1]) == 0)
49         printf ("changed to directory %s\n", argv[1]);
50     }
51
52   pwd1 = getcwd (NULL, 0);
53   ASSERT (pwd1 && *pwd1);
54   if (1 < argc)
55     printf ("cwd=%s\n", pwd1);
56
57   /* Make sure the result is usable.  */
58   ASSERT (chdir (pwd1) == 0);
59   ASSERT (chdir ("././.") == 0);
60
61   /* Make sure that result is normalized.  */
62   pwd2 = getcwd (NULL, 0);
63   ASSERT (pwd2);
64   ASSERT (strcmp (pwd1, pwd2) == 0);
65   free (pwd2);
66   {
67     size_t len = strlen (pwd1);
68     ssize_t i = len - 10;
69     if (i < 0)
70       i = 0;
71     pwd2 = malloc (len + 2);
72     for ( ; i < len; i++)
73       ASSERT (getcwd (pwd2, i) == NULL);
74     pwd2 = getcwd (pwd2, len + 1);
75     ASSERT (pwd2);
76     pwd2[len] = '/';
77     pwd2[len + 1] = '\0';
78   }
79   ASSERT (strstr (pwd2, "/./") == NULL);
80   ASSERT (strstr (pwd2, "/../") == NULL);
81
82   free (pwd1);
83   free (pwd2);
84
85   return 0;
86 }