1/*
2 * Copyright (C) 2024 HiHope Open Source Organization.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#include <cerrno>
17#include <cstdio>
18#include <cstdlib>
19#include <string>
20#include <vector>
21#include <fcntl.h>
22#include <unistd.h>
23#include <gtest/gtest.h>
24#include <sys/stat.h>
25#include <sys/types.h>
26#include "securec.h"
27
28using namespace testing::ext;
29using namespace std;
30
31class FchmodApiTest : public testing::Test {
32public:
33    static void SetUpTestCase();
34    static void TearDownTestCase();
35    void SetUp();
36    void TearDown();
37private:
38};
39void FchmodApiTest::SetUp()
40{
41}
42void FchmodApiTest::TearDown()
43{
44}
45void FchmodApiTest::SetUpTestCase()
46{
47}
48void FchmodApiTest::TearDownTestCase()
49{
50}
51
52static const char *TEST_FILE = "/data/local/tmp/test.txt";
53mode_t MODE_0644 = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
54mode_t MODE_0755 = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
55struct stat g_statbuf;
56
57/*
58 * @tc.number : SUB_KERNEL_SYSCALL_FCHMOD_0100
59 * @tc.name   : FchmodFileModeSuccess_0001
60 * @tc.desc   : fchmod change file mode bits success.
61 * @tc.size   : MediumTest
62 * @tc.type   : Function
63 * @tc.level  : Level 1
64 */
65HWTEST_F(FchmodApiTest, FchmodFileModeSuccess_0001, Function | MediumTest | Level1)
66{
67    int ret = -1;
68
69    int fd = open(TEST_FILE, O_CREAT | O_RDWR, MODE_0644);
70    EXPECT_TRUE(fd > 0);
71
72    ret = fchmod(fd, MODE_0755);
73    EXPECT_EQ(ret, 0);
74
75    ret = fstat(fd, &g_statbuf);
76    EXPECT_EQ(ret, 0);
77    EXPECT_EQ((g_statbuf.st_mode & S_IXUSR), S_IXUSR);
78    EXPECT_EQ((g_statbuf.st_mode & S_IXGRP), S_IXGRP);
79    EXPECT_EQ((g_statbuf.st_mode & S_IXOTH), S_IXOTH);
80
81    close(fd);
82}
83
84/*
85 * @tc.number : SUB_KERNEL_SYSCALL_FCHMOD_0200
86 * @tc.name   : FchmodInvalidFdModeFail_0002
87 * @tc.desc   : fchmod change invalid fd mode bits fail, errno EBADF.
88 * @tc.size   : MediumTest
89 * @tc.type   : Function
90 * @tc.level  : Level 2
91 */
92HWTEST_F(FchmodApiTest, FchmodInvalidFdModeFail_0002, Function | MediumTest | Level2)
93{
94    int ret = -1;
95    int invalidFd = -1;
96    errno = 0;
97    ret = fchmod(invalidFd, MODE_0644);
98    EXPECT_NE(ret, 0);
99    EXPECT_EQ(errno, EBADF);
100}
101