1 /**
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
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 <errno.h>
17 #include <ftw.h>
18 #include <limits.h>
19 #include <stdlib.h>
20 #include <sys/stat.h>
21 #include "functionalext.h"
22
23 #define TEST_FD_LIMIT 128
24 #define TEST_FLAG_SIZE 4
25 #define TEST_DIGIT_TWO 2
26
nftw_callback(const char * pathname,const struct stat * sb,int flag,struct FTW * ftw)27 static int nftw_callback(const char *pathname, const struct stat *sb, int flag, struct FTW *ftw)
28 {
29 EXPECT_TRUE("nftw_callback", pathname != NULL);
30 EXPECT_TRUE("nftw_callback", sb != NULL);
31 if (flag == FTW_NS) {
32 struct stat st;
33 EXPECT_EQ("nftw_callback", stat(pathname, &st), -1);
34 return 0;
35 }
36
37 if (S_ISDIR(sb->st_mode)) {
38 if (access(pathname, R_OK) == 0) {
39 EXPECT_TRUE("nftw_callback", flag == FTW_D || flag == FTW_DP);
40 } else {
41 EXPECT_EQ("nftw_callback", flag, FTW_DNR);
42 }
43 } else if (S_ISLNK(sb->st_mode)) {
44 EXPECT_EQ("nftw_callback", flag, FTW_SL);
45 } else {
46 EXPECT_EQ("nftw_callback", flag, FTW_F);
47 }
48 return 0;
49 }
50
51 /**
52 * @tc.name : nftw_0100
53 * @tc.desc : Traverse directory /data
54 * @tc.level : Level 0
55 */
nftw_0100(void)56 void nftw_0100(void)
57 {
58 int flag[TEST_FLAG_SIZE] = {FTW_PHYS, FTW_MOUNT, FTW_CHDIR, FTW_DEPTH};
59 const char *path = "/data";
60 int i;
61 for (i = 0; i < TEST_FLAG_SIZE; i++) {
62 int ret = nftw(path, nftw_callback, TEST_FD_LIMIT, flag[i]);
63 EXPECT_EQ("nftw_0100", ret, 0);
64 }
65 }
66
67 /**
68 * @tc.name : nftw_0200
69 * @tc.desc : Traverse directory /data, but the maximum number of file descriptors is 0
70 * @tc.level : Level 0
71 */
nftw_0200(void)72 void nftw_0200(void)
73 {
74 const char *path = "/data";
75 int ret = nftw(path, nftw_callback, 0, FTW_PHYS);
76 EXPECT_EQ("nftw_0200", ret, 0);
77 }
78
79 /**
80 * @tc.name : nftw_0300
81 * @tc.desc : The file path length exceeds PATH_MAX, traverse the directory
82 * @tc.level : Level 2
83 */
nftw_0300(void)84 void nftw_0300(void)
85 {
86 char path[PATH_MAX * TEST_DIGIT_TWO];
87 memset(path, 'a', sizeof(path));
88 path[PATH_MAX * TEST_DIGIT_TWO - 1] = 0;
89 int ret = nftw(path, nftw_callback, TEST_FD_LIMIT, FTW_PHYS);
90 EXPECT_EQ("nftw_0300", ret, -1);
91 EXPECT_EQ("nftw_0300", errno, ENAMETOOLONG);
92 }
93
main(void)94 int main(void)
95 {
96 nftw_0100();
97 nftw_0200();
98 nftw_0300();
99 return t_status;
100 }