xref: /llvm-project/libc/test/src/sys/stat/chmod_test.cpp (revision fc121d0c73a2d950434653089cf8b9747dfda3bb)
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/errno/libc_errno.h"
10 #include "src/fcntl/open.h"
11 #include "src/sys/stat/chmod.h"
12 #include "src/unistd/close.h"
13 #include "src/unistd/write.h"
14 #include "test/ErrnoSetterMatcher.h"
15 #include "test/UnitTest/Test.h"
16 
17 #include <fcntl.h>
18 #include <sys/stat.h>
19 
20 TEST(LlvmLibcChmodTest, ChangeAndOpen) {
21   using __llvm_libc::testing::ErrnoSetterMatcher::Fails;
22   using __llvm_libc::testing::ErrnoSetterMatcher::Succeeds;
23 
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   libc_errno = 0;
32 
33   int fd = __llvm_libc::open(TEST_FILE, O_APPEND | O_WRONLY);
34   ASSERT_GT(fd, 0);
35   ASSERT_EQ(libc_errno, 0);
36   ASSERT_EQ(__llvm_libc::write(fd, WRITE_DATA, sizeof(WRITE_DATA)), WRITE_SIZE);
37   ASSERT_THAT(__llvm_libc::close(fd), Succeeds(0));
38 
39   fd = __llvm_libc::open(TEST_FILE, O_PATH);
40   ASSERT_GT(fd, 0);
41   ASSERT_EQ(libc_errno, 0);
42   ASSERT_THAT(__llvm_libc::close(fd), Succeeds(0));
43   EXPECT_THAT(__llvm_libc::chmod(TEST_FILE, S_IRUSR), Succeeds(0));
44 
45   // Opening for writing should fail.
46   EXPECT_EQ(__llvm_libc::open(TEST_FILE, O_APPEND | O_WRONLY), -1);
47   EXPECT_NE(libc_errno, 0);
48   libc_errno = 0;
49   // But opening for reading should succeed.
50   fd = __llvm_libc::open(TEST_FILE, O_APPEND | O_RDONLY);
51   EXPECT_GT(fd, 0);
52   EXPECT_EQ(libc_errno, 0);
53 
54   EXPECT_THAT(__llvm_libc::close(fd), Succeeds(0));
55   EXPECT_THAT(__llvm_libc::chmod(TEST_FILE, S_IRWXU), Succeeds(0));
56 }
57 
58 TEST(LlvmLibcChmodTest, NonExistentFile) {
59   libc_errno = 0;
60   using __llvm_libc::testing::ErrnoSetterMatcher::Fails;
61   ASSERT_THAT(__llvm_libc::chmod("non-existent-file", S_IRUSR), Fails(ENOENT));
62   libc_errno = 0;
63 }
64