1 | //===-- Unittests for access ----------------------------------------------===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | |
9 | #include "src/errno/libc_errno.h" |
10 | #include "src/fcntl/open.h" |
11 | #include "src/unistd/access.h" |
12 | #include "src/unistd/close.h" |
13 | #include "src/unistd/unlink.h" |
14 | #include "test/UnitTest/ErrnoSetterMatcher.h" |
15 | #include "test/UnitTest/LibcTest.h" |
16 | #include "test/UnitTest/Test.h" |
17 | |
18 | #include <sys/stat.h> |
19 | #include <unistd.h> |
20 | |
21 | TEST(LlvmLibcAccessTest, CreateAndTest) { |
22 | // The test strategy is to repeatedly create a file in different modes and |
23 | // test that it is accessable in those modes but not in others. |
24 | LIBC_NAMESPACE::libc_errno = 0; |
25 | using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds; |
26 | constexpr const char *FILENAME = "access.test" ; |
27 | auto TEST_FILE = libc_make_test_file_path(FILENAME); |
28 | int fd = LIBC_NAMESPACE::open(path: TEST_FILE, O_WRONLY | O_CREAT, S_IRWXU); |
29 | ASSERT_ERRNO_SUCCESS(); |
30 | ASSERT_GT(fd, 0); |
31 | ASSERT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0)); |
32 | |
33 | ASSERT_EQ(LIBC_NAMESPACE::access(TEST_FILE, F_OK), 0); |
34 | ASSERT_ERRNO_SUCCESS(); |
35 | ASSERT_EQ(LIBC_NAMESPACE::access(TEST_FILE, X_OK | W_OK | R_OK), 0); |
36 | ASSERT_ERRNO_SUCCESS(); |
37 | ASSERT_THAT(LIBC_NAMESPACE::unlink(TEST_FILE), Succeeds(0)); |
38 | |
39 | fd = LIBC_NAMESPACE::open(path: TEST_FILE, O_WRONLY | O_CREAT, S_IXUSR); |
40 | ASSERT_ERRNO_SUCCESS(); |
41 | ASSERT_GT(fd, 0); |
42 | ASSERT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0)); |
43 | ASSERT_EQ(LIBC_NAMESPACE::access(TEST_FILE, F_OK), 0); |
44 | ASSERT_ERRNO_SUCCESS(); |
45 | ASSERT_EQ(LIBC_NAMESPACE::access(TEST_FILE, X_OK), 0); |
46 | ASSERT_ERRNO_SUCCESS(); |
47 | ASSERT_EQ(LIBC_NAMESPACE::access(TEST_FILE, R_OK), -1); |
48 | ASSERT_ERRNO_EQ(EACCES); |
49 | LIBC_NAMESPACE::libc_errno = 0; |
50 | ASSERT_EQ(LIBC_NAMESPACE::access(TEST_FILE, W_OK), -1); |
51 | ASSERT_ERRNO_EQ(EACCES); |
52 | LIBC_NAMESPACE::libc_errno = 0; |
53 | ASSERT_THAT(LIBC_NAMESPACE::unlink(TEST_FILE), Succeeds(0)); |
54 | } |
55 | |
56 | TEST(LlvmLibcAccessTest, AccessNonExistentFile) { |
57 | using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails; |
58 | ASSERT_THAT(LIBC_NAMESPACE::access("testdata/non-existent-file" , F_OK), |
59 | Fails(ENOENT)); |
60 | } |
61 | |