1//===-- Unittests for fchmod ----------------------------------------------===//
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/fchmod.h"
12#include "src/unistd/close.h"
13#include "src/unistd/write.h"
14#include "test/UnitTest/ErrnoSetterMatcher.h"
15#include "test/UnitTest/Test.h"
16
17#include <fcntl.h>
18#include <sys/stat.h>
19
20TEST(LlvmLibcChmodTest, ChangeAndOpen) {
21 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
22 using LIBC_NAMESPACE::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/fchmod.test";
29 const char WRITE_DATA[] = "test data";
30 constexpr ssize_t WRITE_SIZE = ssize_t(sizeof(WRITE_DATA));
31 LIBC_NAMESPACE::libc_errno = 0;
32
33 int fd = LIBC_NAMESPACE::open(path: TEST_FILE, O_APPEND | O_WRONLY);
34 ASSERT_GT(fd, 0);
35 ASSERT_ERRNO_SUCCESS();
36 ASSERT_EQ(LIBC_NAMESPACE::write(fd, WRITE_DATA, sizeof(WRITE_DATA)),
37 WRITE_SIZE);
38 ASSERT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0));
39
40 fd = LIBC_NAMESPACE::open(path: TEST_FILE, O_APPEND | O_WRONLY);
41 ASSERT_GT(fd, 0);
42 ASSERT_ERRNO_SUCCESS();
43 EXPECT_THAT(LIBC_NAMESPACE::fchmod(fd, S_IRUSR), Succeeds(0));
44 ASSERT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0));
45
46 // Opening for writing should fail.
47 EXPECT_EQ(LIBC_NAMESPACE::open(TEST_FILE, O_APPEND | O_WRONLY), -1);
48 ASSERT_ERRNO_FAILURE();
49 LIBC_NAMESPACE::libc_errno = 0;
50 // But opening for reading should succeed.
51 fd = LIBC_NAMESPACE::open(path: TEST_FILE, O_APPEND | O_RDONLY);
52 EXPECT_GT(fd, 0);
53 ASSERT_ERRNO_SUCCESS();
54
55 EXPECT_THAT(LIBC_NAMESPACE::fchmod(fd, S_IRWXU), Succeeds(0));
56 EXPECT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0));
57}
58
59TEST(LlvmLibcChmodTest, NonExistentFile) {
60 LIBC_NAMESPACE::libc_errno = 0;
61 ASSERT_EQ(LIBC_NAMESPACE::fchmod(-1, S_IRUSR), -1);
62 ASSERT_ERRNO_FAILURE();
63 LIBC_NAMESPACE::libc_errno = 0;
64}
65

source code of libc/test/src/sys/stat/fchmod_test.cpp