1 /*
2  * Copyright (c) 2018 Intel Corporation.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <string.h>
8 #include <fcntl.h>
9 #include <ff.h>
10 #include <zephyr/fs/fs.h>
11 #include <zephyr/posix/unistd.h>
12 #include <zephyr/ztest.h>
13 
14 static const char test_str[] = "Hello World!";
15 
16 #define FATFS_MNTP "/RAM:"
17 #define TEST_FILE  FATFS_MNTP "/testfile.txt"
18 
19 static FATFS fat_fs;
20 
21 static struct fs_mount_t fatfs_mnt = {
22 	.type = FS_FATFS,
23 	.mnt_point = FATFS_MNTP,
24 	.fs_data = &fat_fs,
25 };
26 
test_mount(void)27 static void test_mount(void)
28 {
29 	int res;
30 
31 	res = fs_mount(&fatfs_mnt);
32 	zassert_ok(res, "Error mounting fs [%d]\n", res);
33 }
34 
test_unmount(void)35 void test_unmount(void)
36 {
37 	int res;
38 
39 	res = fs_unmount(&fatfs_mnt);
40 	zassert_ok(res, "Error unmounting fs [%d]", res);
41 }
42 
file_open(void)43 static int file_open(void)
44 {
45 	int res;
46 
47 	res = open(TEST_FILE, O_CREAT | O_RDWR, 0660);
48 	zassert_not_equal(res, -1, "Error opening file [%d], errno [%d]", res, errno);
49 	return res;
50 }
51 
file_write(int file)52 static int file_write(int file)
53 {
54 	ssize_t brw;
55 	off_t res;
56 
57 	res = lseek(file, 0, SEEK_SET);
58 	zassert_ok((int)res, "lseek failed [%d]\n", (int)res);
59 
60 	brw = write(file, (char *)test_str, strlen(test_str));
61 	zassert_ok((int)res, "Failed writing to file [%d]\n", (int)brw);
62 
63 	zassert_ok(brw < strlen(test_str),
64 		   "Unable to complete write. Volume full. Number of bytes written: [%d]\n",
65 		   (int)brw);
66 	return res;
67 }
68 
69 /**
70  * @brief Test for POSIX fsync API
71  *
72  * @details Test sync the file through POSIX fsync API.
73  */
ZTEST(xsi_realtime,test_fs_sync)74 ZTEST(xsi_realtime, test_fs_sync)
75 {
76 	test_mount();
77 	int res = 0;
78 	int file = file_open();
79 
80 	res = file_write(file);
81 	res = fsync(file);
82 	zassert_ok(res, "Failed to sync file: %d, errno = %d\n", res, errno);
83 	zassert_ok(close(file), "Failed to close file");
84 	test_unmount();
85 }
86 
87 /**
88  * @brief Test for POSIX fdatasync API
89  *
90  * @details Test sync the file through POSIX fdatasync API.
91  */
ZTEST(xsi_realtime,test_fs_datasync)92 ZTEST(xsi_realtime, test_fs_datasync)
93 {
94 	test_mount();
95 	int res = 0;
96 	int file = file_open();
97 
98 	res = file_write(file);
99 	res = fdatasync(file);
100 	zassert_ok(res, "Failed to sync file: %d, errno = %d\n", res, errno);
101 	zassert_ok(close(file), "Failed to close file");
102 	test_unmount();
103 }
104