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 <fcntl.h>
17 #include <stdlib.h>
18 #include <unistd.h>
19 #include "functionalext.h"
20 
21 #define TEST_BUFFER_SIZE 64
22 
rm_file(const char *name)23 void rm_file(const char *name)
24 {
25     if (access(name, F_OK) == 0) {
26         unlink(name);
27     }
28 }
29 
30 /**
31  * @tc.name      : pwrite_0100
32  * @tc.desc      : Write to a file descriptor at a given offset
33  * @tc.level     : Level 0
34  */
pwrite_0100(void)35 void pwrite_0100(void)
36 {
37     const char *txt = "This is pwrite_0100 test.";
38     char buffer[TEST_BUFFER_SIZE];
39     memset(buffer, 0x0, sizeof(buffer));
40 
41     int fd = open("pwrite_0100", O_CREAT | O_RDWR, TEST_MODE);
42     EXPECT_NE("pwrite_0100", fd, ERREXPECT);
43     if (fd == -1) {
44         return;
45     }
46     size_t cnt = pwrite(fd, txt, strlen(txt), 0);
47     EXPECT_EQ("pwrite_0100", cnt, strlen(txt));
48 
49     lseek(fd, 0, SEEK_SET);
50     cnt = pread(fd, buffer, TEST_BUFFER_SIZE, 0);
51     EXPECT_EQ("pwrite_0100", cnt, strlen(txt));
52     EXPECT_STREQ("pwrite_0100", txt, buffer);
53     close(fd);
54     rm_file("pwrite_0100");
55 }
56 
57 /**
58  * @tc.name      : pwrite_0200
59  * @tc.desc      : Provide illegal parameter data, write data to the open file
60  * @tc.level     : Level 2
61  */
pwrite_0200(void)62 void pwrite_0200(void)
63 {
64     const char *txt = "This is pwrite_0200 test.";
65     size_t cnt = pwrite(-1, txt, strlen(txt), 0);
66     EXPECT_EQ("pwrite_0200", cnt, (size_t)(-1));
67 
68     int fd = open("pwrite_0200", O_CREAT | O_RDWR, TEST_MODE);
69     EXPECT_NE("pwrite_0200", fd, -1);
70     if (fd == -1) {
71         return;
72     }
73 
74     cnt = pwrite(fd, txt, 0, 0);
75     EXPECT_EQ("pwrite_0200", cnt, CMPFLAG);
76 
77     cnt = pwrite(fd, NULL, 0, 0);
78     EXPECT_EQ("pwrite_0200", cnt, CMPFLAG);
79     close(fd);
80     rm_file("pwrite_0200");
81 }
82 
main(void)83 int main(void)
84 {
85     pwrite_0100();
86     pwrite_0200();
87     return t_status;
88 }
89