1 #include <ftw.h>
2 #include <gtest/gtest.h>
3 #include <sys/stat.h>
4
5 using namespace testing::ext;
6
7 #define TEST_FD_LIMIT 128
8 #define TEST_FLAG_SIZE 4
9 #define TEST_DIGIT_TWO 2
10
11 class MiscNftw64Test : public testing::Test {
SetUp()12 void SetUp() override {}
TearDown()13 void TearDown() override {}
14 };
15
NftwCallback(const char * pathName,const struct stat * sb,int flag,struct FTW * ftw)16 static int NftwCallback(const char* pathName, const struct stat* sb, int flag, struct FTW* ftw)
17 {
18 EXPECT_TRUE(pathName != nullptr);
19 EXPECT_TRUE(sb != nullptr);
20 if (flag == FTW_NS) {
21 struct stat st;
22 EXPECT_EQ(-1, stat(pathName, &st));
23 return 0;
24 }
25 if (S_ISDIR(sb->st_mode)) {
26 if (access(pathName, R_OK) == 0) {
27 EXPECT_TRUE(flag == FTW_D || flag == FTW_DP);
28 } else {
29 EXPECT_EQ(flag, FTW_DNR);
30 }
31 } else if (S_ISLNK(sb->st_mode)) {
32 EXPECT_EQ(flag, FTW_SL);
33 } else {
34 EXPECT_EQ(flag, FTW_F);
35 }
36 return 0;
37 }
38
CheckNftw64(const char * fpath,const struct stat64 * sb,int tflag,FTW * ftwbuf)39 static int CheckNftw64(const char* fpath, const struct stat64* sb, int tflag, FTW* ftwbuf)
40 {
41 NftwCallback(fpath, reinterpret_cast<const struct stat*>(sb), tflag, ftwbuf);
42 return 0;
43 }
44
NullCallback(const char * fpath,const struct stat64 * sb,int,FTW * ftwbuf)45 static int NullCallback(const char* fpath, const struct stat64* sb, int, FTW* ftwbuf)
46 {
47 return 0;
48 }
49
50 /**
51 * @tc.name: nftw64_001
52 * @tc.desc: Traverse directory /data.
53 * @tc.type: FUNC
54 * */
55 HWTEST_F(MiscNftw64Test, nftw64_001, TestSize.Level1)
56 {
57 int flag[TEST_FLAG_SIZE] = { FTW_PHYS, FTW_MOUNT, FTW_CHDIR, FTW_DEPTH };
58 const char* path = "/data";
59
60 for (int i = 0; i < TEST_FLAG_SIZE; i++) {
61 int ret = nftw64(path, CheckNftw64, TEST_FD_LIMIT, flag[i]);
62 EXPECT_EQ(0, ret);
63 }
64 }
65
66 /**
67 * @tc.name: nftw64_002
68 * @tc.desc: Verify if the nftw64 function handles non-existent paths as expected.
69 * @tc.type: FUNC
70 * */
71 HWTEST_F(MiscNftw64Test, nftw64_002, TestSize.Level1)
72 {
73 errno = 0;
74 int result = nftw64("/does/not/exist", NullCallback, TEST_FD_LIMIT, FTW_PHYS);
75 EXPECT_EQ(-1, result);
76 EXPECT_EQ(ENOENT, errno);
77 }
78
79 /**
80 * @tc.name: nftw64_003
81 * @tc.desc: Check if the behavior of the nftw64 function matches expectations when given an empty path.
82 * @tc.type: FUNC
83 * */
84 HWTEST_F(MiscNftw64Test, nftw64_003, TestSize.Level1)
85 {
86 errno = 0;
87 int result = nftw64("", NullCallback, TEST_FD_LIMIT, FTW_PHYS);
88 EXPECT_EQ(-1, result);
89 EXPECT_EQ(ENOENT, errno);
90 }