1 //===-- Unittests for fchmod ----------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "src/fcntl/open.h"
10 #include "src/sys/stat/fchmod.h"
11 #include "src/unistd/close.h"
12 #include "src/unistd/write.h"
13 #include "test/ErrnoSetterMatcher.h"
14 #include "test/UnitTest/Test.h"
15 #include "utils/testutils/FDReader.h"
21 TEST(LlvmLibcChmodTest
, ChangeAndOpen
) {
22 using __llvm_libc::testing::ErrnoSetterMatcher::Fails
;
23 using __llvm_libc::testing::ErrnoSetterMatcher::Succeeds
;
25 // The test file is initially writable. We open it for writing and ensure
26 // that it indeed can be opened for writing. Next, we close the file and
27 // make it readonly using chmod. We test that chmod actually succeeded by
28 // trying to open the file for writing and failing.
29 constexpr const char *TEST_FILE
= "testdata/fchmod.test";
30 const char WRITE_DATA
[] = "test data";
31 constexpr ssize_t WRITE_SIZE
= ssize_t(sizeof(WRITE_DATA
));
34 int fd
= __llvm_libc::open(TEST_FILE
, O_APPEND
| O_WRONLY
);
37 ASSERT_EQ(__llvm_libc::write(fd
, WRITE_DATA
, sizeof(WRITE_DATA
)), WRITE_SIZE
);
38 ASSERT_THAT(__llvm_libc::close(fd
), Succeeds(0));
40 fd
= __llvm_libc::open(TEST_FILE
, O_APPEND
| O_WRONLY
);
43 EXPECT_THAT(__llvm_libc::fchmod(fd
, S_IRUSR
), Succeeds(0));
44 ASSERT_THAT(__llvm_libc::close(fd
), Succeeds(0));
46 // Opening for writing should fail.
47 EXPECT_EQ(__llvm_libc::open(TEST_FILE
, O_APPEND
| O_WRONLY
), -1);
50 // But opening for reading should succeed.
51 fd
= __llvm_libc::open(TEST_FILE
, O_APPEND
| O_RDONLY
);
55 EXPECT_THAT(__llvm_libc::fchmod(fd
, S_IRWXU
), Succeeds(0));
56 EXPECT_THAT(__llvm_libc::close(fd
), Succeeds(0));
59 TEST(LlvmLibcChmodTest
, NonExistentFile
) {
61 ASSERT_EQ(__llvm_libc::fchmod(-1, S_IRUSR
), -1);