1 /*
2  * Copyright (c) 2018 Intel Corporation.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <stdio.h>
8 #include <fcntl.h>
9 #include <zephyr/posix/unistd.h>
10 #include <zephyr/posix/dirent.h>
11 #include "test_fs.h"
12 
13 extern int test_file_write(void);
14 extern int test_file_close(void);
15 extern int file;
16 
test_mkdir(void)17 static int test_mkdir(void)
18 {
19 	int res;
20 
21 	TC_PRINT("\nmkdir tests:\n");
22 
23 	/* Verify fs_mkdir() */
24 	res = mkdir(TEST_DIR, S_IRWXG);
25 	if (res) {
26 		TC_PRINT("Error creating dir[%d]\n", res);
27 		return res;
28 	}
29 
30 	res = open(TEST_DIR_FILE, O_CREAT | O_RDWR);
31 
32 	if (res < 0) {
33 		TC_PRINT("Failed opening file [%d]\n", res);
34 		return res;
35 	}
36 	file = res;
37 
38 	res = test_file_write();
39 	if (res) {
40 		return res;
41 	}
42 
43 	res = close(file);
44 	if (res) {
45 		TC_PRINT("Error closing file [%d]\n", res);
46 		return res;
47 	}
48 
49 	TC_PRINT("Created dir %s!\n", TEST_DIR);
50 
51 	return res;
52 }
53 
test_lsdir(const char * path)54 static int test_lsdir(const char *path)
55 {
56 	DIR *dirp;
57 	int res = 0;
58 	struct dirent *entry;
59 
60 	TC_PRINT("\nreaddir test:\n");
61 
62 	/* Verify fs_opendir() */
63 	dirp = opendir(path);
64 	if (dirp == NULL) {
65 		TC_PRINT("Error opening dir %s\n", path);
66 		return -EIO;
67 	}
68 
69 	TC_PRINT("\nListing dir %s:\n", path);
70 	/* Verify fs_readdir() */
71 	errno = 0;
72 	while ((entry = readdir(dirp)) != NULL) {
73 		if (entry->d_name[0] == 0) {
74 			res = -EIO;
75 			break;
76 		}
77 
78 		TC_PRINT("[FILE] %s\n", entry->d_name);
79 	}
80 
81 	if (errno) {
82 		res = -EIO;
83 	}
84 
85 	/* Verify fs_closedir() */
86 	closedir(dirp);
87 
88 	return res;
89 }
90 
after_fn(void * unused)91 static void after_fn(void *unused)
92 {
93 	ARG_UNUSED(unused);
94 
95 	unlink(TEST_DIR_FILE);
96 	unlink(TEST_DIR);
97 }
98 
99 /* FIXME: restructure tests as per #46897 */
100 ZTEST_SUITE(posix_fs_dir_test, NULL, test_mount, NULL, after_fn,
101 	    test_unmount);
102 
103 /**
104  * @brief Test for POSIX mkdir API
105  *
106  * @details Test creates a new directory through POSIX
107  * mkdir API and open a new file under the directory and
108  * writes some data into the file.
109  */
ZTEST(posix_fs_dir_test,test_fs_mkdir)110 ZTEST(posix_fs_dir_test, test_fs_mkdir)
111 {
112 	/* FIXME: restructure tests as per #46897 */
113 	zassert_true(test_mkdir() == TC_PASS);
114 }
115 
116 /**
117  * @brief Test for POSIX opendir, readdir and closedir API
118  *
119  * @details Test opens an existing directory through POSIX
120  * opendir API, reads the contents of the directory through
121  * readdir API and closes it through closedir API.
122  */
ZTEST(posix_fs_dir_test,test_fs_readdir)123 ZTEST(posix_fs_dir_test, test_fs_readdir)
124 {
125 	/* FIXME: restructure tests as per #46897 */
126 	zassert_true(test_mkdir() == TC_PASS);
127 	zassert_true(test_lsdir(TEST_DIR) == TC_PASS);
128 }
129