1 /*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <gtest/gtest.h>
18
19 #include <errno.h>
20 #include <limits.h>
21 #include <unistd.h>
22
TEST(getcwd,auto_full)23 TEST(getcwd, auto_full) {
24 // If we let the library do all the work, everything's fine.
25 errno = 0;
26 char* cwd = getcwd(NULL, 0);
27 ASSERT_TRUE(cwd != NULL);
28 ASSERT_EQ(0, errno);
29 ASSERT_GE(strlen(cwd), 1U);
30 free(cwd);
31 }
32
TEST(getcwd,auto_reasonable)33 TEST(getcwd, auto_reasonable) {
34 // If we ask the library to allocate a reasonable buffer, everything's fine.
35 errno = 0;
36 char* cwd = getcwd(NULL, PATH_MAX);
37 ASSERT_TRUE(cwd != NULL);
38 ASSERT_EQ(0, errno);
39 ASSERT_GE(strlen(cwd), 1U);
40 free(cwd);
41 }
42
TEST(getcwd,auto_too_small)43 TEST(getcwd, auto_too_small) {
44 // If we ask the library to allocate a too-small buffer, ERANGE.
45 errno = 0;
46 char* cwd = getcwd(NULL, 1);
47 ASSERT_TRUE(cwd == NULL);
48 ASSERT_EQ(ERANGE, errno);
49 }
50
TEST(getcwd,auto_too_large)51 TEST(getcwd, auto_too_large) {
52 // If we ask the library to allocate an unreasonably large buffer, ERANGE.
53 errno = 0;
54 char* cwd = getcwd(NULL, static_cast<size_t>(-1));
55 ASSERT_TRUE(cwd == NULL);
56 ASSERT_EQ(ENOMEM, errno);
57 }
58
TEST(getcwd,manual_too_small)59 TEST(getcwd, manual_too_small) {
60 // If we allocate a too-small buffer, ERANGE.
61 char tiny_buf[1];
62 errno = 0;
63 char* cwd = getcwd(tiny_buf, sizeof(tiny_buf));
64 ASSERT_TRUE(cwd == NULL);
65 ASSERT_EQ(ERANGE, errno);
66 }
67
TEST(getcwd,manual_zero)68 TEST(getcwd, manual_zero) {
69 // If we allocate a zero-length buffer, EINVAL.
70 char tiny_buf[1];
71 errno = 0;
72 char* cwd = getcwd(tiny_buf, 0);
73 ASSERT_TRUE(cwd == NULL);
74 ASSERT_EQ(EINVAL, errno);
75 }
76
TEST(getcwd,manual_path_max)77 TEST(getcwd, manual_path_max) {
78 char* buf = new char[PATH_MAX];
79 errno = 0;
80 char* cwd = getcwd(buf, PATH_MAX);
81 ASSERT_TRUE(cwd == buf);
82 ASSERT_EQ(0, errno);
83 ASSERT_GE(strlen(cwd), 1U);
84 delete[] cwd;
85 }
86