1 /*
2 * Copyright (c) 2023 Nikhef
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #undef _POSIX_C_SOURCE
8 #define _POSIX_C_SOURCE 200809L
9
10 #include <string.h>
11 #include <zephyr/posix/fcntl.h>
12 #include <zephyr/posix/unistd.h>
13 #include <zephyr/posix/dirent.h>
14 #include "test_fs.h"
15
16 #define FILL_SIZE 128
17
18 #define TEST_FILE_SIZE 80
19 #define TEST_DIR_FILE_SIZE 1000
20
21 #define TEST_EMPTY_FILE FATFS_MNTP "/empty.dat"
22
create_file(const char * filename,uint32_t size)23 static void create_file(const char *filename, uint32_t size)
24 {
25 int fh;
26
27 fh = open(filename, O_CREAT | O_WRONLY, 0440);
28 zassert(fh >= 0, "Failed creating test file");
29
30 uint8_t filling[FILL_SIZE];
31
32 while (size > FILL_SIZE) {
33 zassert_equal(FILL_SIZE, write(fh, filling, FILL_SIZE));
34 size -= FILL_SIZE;
35 }
36
37 zassert_equal(size, write(fh, filling, size));
38
39 zassert_ok(close(fh));
40 }
41
before_fn(void * unused)42 static void before_fn(void *unused)
43 {
44 ARG_UNUSED(unused);
45
46 zassert_ok(mkdir(TEST_DIR, 0070));
47
48 create_file(TEST_FILE, TEST_FILE_SIZE);
49 create_file(TEST_DIR_FILE, TEST_DIR_FILE_SIZE);
50 create_file(TEST_EMPTY_FILE, 0);
51 }
52
after_fn(void * unused)53 static void after_fn(void *unused)
54 {
55 ARG_UNUSED(unused);
56
57 zassert_ok(unlink(TEST_FILE));
58 zassert_ok(unlink(TEST_DIR_FILE));
59 zassert_ok(unlink(TEST_DIR));
60 }
61
62 ZTEST_SUITE(posix_fs_stat_test, NULL, test_mount, before_fn, after_fn, test_unmount);
63
64 /**
65 * @brief Test stat command on file
66 *
67 * @details Tests file in root, file in directroy, non-existing file and empty file.
68 */
ZTEST(posix_fs_stat_test,test_fs_stat_file)69 ZTEST(posix_fs_stat_test, test_fs_stat_file)
70 {
71 struct stat buf;
72
73 zassert_equal(0, stat(TEST_FILE, &buf));
74 zassert_equal(TEST_FILE_SIZE, buf.st_size);
75 zassert_equal(S_IFREG, buf.st_mode);
76
77 zassert_equal(0, stat(TEST_DIR_FILE, &buf));
78 zassert_equal(TEST_DIR_FILE_SIZE, buf.st_size);
79 zassert_equal(S_IFREG, buf.st_mode);
80
81 zassert_not_equal(0, stat(TEST_ROOT "foo.txt", &buf));
82 zassert_not_equal(0, stat("", &buf));
83
84 zassert_equal(0, stat(TEST_EMPTY_FILE, &buf));
85
86 zassert_equal(0, buf.st_size);
87 zassert_equal(S_IFREG, buf.st_mode);
88 }
89
90 /**
91 * @brief Test stat command on dir
92 *
93 * @details Tests if we can retrieve stastics for a directory. This should only provide S_IFDIR
94 * return value.
95 */
ZTEST(posix_fs_stat_test,test_fs_stat_dir)96 ZTEST(posix_fs_stat_test, test_fs_stat_dir)
97 {
98 struct stat buf;
99
100 zassert_equal(0, stat(TEST_DIR, &buf));
101
102 zassert_equal(0, buf.st_size);
103 zassert_equal(S_IFDIR, buf.st_mode);
104
105 /* note: for posix compatibility should should actually work */
106 zassert_not_equal(0, stat(TEST_ROOT, &buf));
107 }
108