1 | //===-- Unittests for chmod -----------------------------------------------===// |
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/fcntl/open.h" |
10 | #include "src/sys/stat/chmod.h" |
11 | #include "src/unistd/close.h" |
12 | #include "src/unistd/write.h" |
13 | #include "test/UnitTest/ErrnoCheckingTest.h" |
14 | #include "test/UnitTest/ErrnoSetterMatcher.h" |
15 | #include "test/UnitTest/Test.h" |
16 | |
17 | #include "hdr/fcntl_macros.h" |
18 | #include <sys/stat.h> |
19 | |
20 | using namespace LIBC_NAMESPACE::testing::ErrnoSetterMatcher; |
21 | using LlvmLibcChmodTest = LIBC_NAMESPACE::testing::ErrnoCheckingTest; |
22 | |
23 | TEST_F(LlvmLibcChmodTest, ChangeAndOpen) { |
24 | // The test file is initially writable. We open it for writing and ensure |
25 | // that it indeed can be opened for writing. Next, we close the file and |
26 | // make it readonly using chmod. We test that chmod actually succeeded by |
27 | // trying to open the file for writing and failing. |
28 | constexpr const char *TEST_FILE = "testdata/chmod.test" ; |
29 | const char WRITE_DATA[] = "test data" ; |
30 | constexpr ssize_t WRITE_SIZE = ssize_t(sizeof(WRITE_DATA)); |
31 | |
32 | int fd = LIBC_NAMESPACE::open(TEST_FILE, O_APPEND | O_WRONLY); |
33 | ASSERT_GT(fd, 0); |
34 | ASSERT_ERRNO_SUCCESS(); |
35 | ASSERT_EQ(LIBC_NAMESPACE::write(fd, WRITE_DATA, sizeof(WRITE_DATA)), |
36 | WRITE_SIZE); |
37 | ASSERT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0)); |
38 | |
39 | fd = LIBC_NAMESPACE::open(TEST_FILE, O_PATH); |
40 | ASSERT_GT(fd, 0); |
41 | ASSERT_ERRNO_SUCCESS(); |
42 | ASSERT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0)); |
43 | EXPECT_THAT(LIBC_NAMESPACE::chmod(TEST_FILE, S_IRUSR), Succeeds(0)); |
44 | |
45 | // Opening for writing should fail. |
46 | EXPECT_EQ(LIBC_NAMESPACE::open(TEST_FILE, O_APPEND | O_WRONLY), -1); |
47 | ASSERT_ERRNO_FAILURE(); |
48 | // But opening for reading should succeed. |
49 | fd = LIBC_NAMESPACE::open(TEST_FILE, O_APPEND | O_RDONLY); |
50 | EXPECT_GT(fd, 0); |
51 | ASSERT_ERRNO_SUCCESS(); |
52 | |
53 | EXPECT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0)); |
54 | EXPECT_THAT(LIBC_NAMESPACE::chmod(TEST_FILE, S_IRWXU), Succeeds(0)); |
55 | } |
56 | |
57 | TEST_F(LlvmLibcChmodTest, NonExistentFile) { |
58 | ASSERT_THAT(LIBC_NAMESPACE::chmod("non-existent-file" , S_IRUSR), |
59 | Fails(ENOENT)); |
60 | } |
61 | |