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/file.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include "securec.h"
28
29 using namespace testing::ext;
30 using namespace std;
31
32 static const char *TEST_FILE = "/data/local/tmp/fchown.txt";
33 mode_t MODE_0644 = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
34
35 class FchownApiTest : public testing::Test {
36 public:
37 static void SetUpTestCase();
38 static void TearDownTestCase();
39 void SetUp();
40 void TearDown();
41 private:
42 };
SetUp()43 void FchownApiTest::SetUp()
44 {
45 }
TearDown()46 void FchownApiTest::TearDown()
47 {
48 }
SetUpTestCase()49 void FchownApiTest::SetUpTestCase()
50 {
51 }
TearDownTestCase()52 void FchownApiTest::TearDownTestCase()
53 {
54 }
55
56 /*
57 * @tc.number : SUB_KERNEL_SYSCALL_FCHOWN_0100
58 * @tc.name : FchownFileSuccess_0001
59 * @tc.desc : fchown change valid file owner success.
60 * @tc.size : MediumTest
61 * @tc.type : Function
62 * @tc.level : Level 1
63 */
HWTEST_F(FchownApiTest, FchownFileSuccess_0001, Function | MediumTest | Level1)64 HWTEST_F(FchownApiTest, FchownFileSuccess_0001, Function | MediumTest | Level1)
65 {
66 int ret = -1;
67 struct stat stat1;
68 struct stat stat2;
69
70 int fd = open(TEST_FILE, O_RDWR | O_CREAT, MODE_0644);
71 EXPECT_TRUE(fd > 0);
72 ret = fstat(fd, &stat1);
73 uid_t uid = stat1.st_uid + 1;
74 gid_t gid = stat1.st_gid + 1;
75
76 ret = fchown(fd, uid, gid);
77 EXPECT_EQ(ret, 0);
78 ret = fstat(fd, &stat2);
79 EXPECT_EQ(stat2.st_uid, uid);
80 EXPECT_EQ(stat2.st_gid, gid);
81
82 close(fd);
83 remove(TEST_FILE);
84 }
85
86 /*
87 * @tc.number : SUB_KERNEL_SYSCALL_FCHOWN_0200
88 * @tc.name : FchownInvalidFdFail_0002
89 * @tc.desc : fchown change invalid file owner fail, errno EBADF.
90 * @tc.size : MediumTest
91 * @tc.type : Function
92 * @tc.level : Level 2
93 */
HWTEST_F(FchownApiTest, FchownInvalidFdFail_0002, Function | MediumTest | Level2)94 HWTEST_F(FchownApiTest, FchownInvalidFdFail_0002, Function | MediumTest | Level2)
95 {
96 uid_t uid = getuid();
97 gid_t gid = getgid();
98 errno = 0;
99 int ret = fchown(-1, uid, gid);
100 EXPECT_EQ(ret, -1);
101 EXPECT_EQ(errno, EBADF);
102 }
103