1/*
2 * Copyright (C) 2024 HiHope Open Source Organization.
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 <cstdio>
17#include <cstdlib>
18#include <string>
19#include <vector>
20#include <fcntl.h>
21#include <unistd.h>
22#include <gtest/gtest.h>
23#include <sys/stat.h>
24#include <sys/types.h>
25#include <sys/uio.h>
26#include "securec.h"
27
28using namespace testing::ext;
29using namespace std;
30static const char *TEST_FILE = "/data/local/tmp/testfile";
31
32class PwritevApiTest : public testing::Test {
33public:
34    static void SetUpTestCase();
35    static void TearDownTestCase();
36    void SetUp();
37    void TearDown();
38private:
39};
40void PwritevApiTest::SetUp()
41{
42}
43void PwritevApiTest::TearDown()
44{
45}
46void PwritevApiTest::SetUpTestCase()
47{
48}
49void PwritevApiTest::TearDownTestCase()
50{
51}
52
53/*
54 * @tc.number : SUB_KERNEL_SYSCALL_PWRITEV_0100
55 * @tc.name   : PwritevNormalWriteSuccess_0001
56 * @tc.desc   : pwritev should write data to the file at the specified offset.
57 * @tc.size   : MediumTest
58 * @tc.type   : Function
59 * @tc.level  : Level 1
60 */
61HWTEST_F(PwritevApiTest, PwritevNormalWriteSuccess_0001, Function | MediumTest | Level1)
62{
63    char data1[] = "Hello";
64    char data2[] = "World!";
65    int fd = open(TEST_FILE, O_RDWR | O_CREAT | O_TRUNC, 0644);
66
67    struct iovec iov[2] = {
68        {.iov_base = data1, .iov_len = sizeof(data1)},
69        {.iov_base = data2, .iov_len = sizeof(data2)}
70    };
71
72    ssize_t size = pwritev(fd, iov, 2, 0);
73    EXPECT_EQ(size, sizeof(data1) + sizeof(data2));
74
75    close(fd);
76    unlink(TEST_FILE);
77}
78
79/*
80 * @tc.number : SUB_KERNEL_SYSCALL_PWRITEV_0200
81 * @tc.name   : PwritevInvalidFdFailed_0002
82 * @tc.desc   : pwritev should return -1 and set errno to EBADF for invalid fd, errno EBADF.
83 * @tc.size   : MediumTest
84 * @tc.type   : Function
85 * @tc.level  : Level 2
86 */
87HWTEST_F(PwritevApiTest, PwritevInvalidFdFailed_0002, Function | MediumTest | Level2)
88{
89    char data[] = "Hello, world!";
90    struct iovec iov = {
91        .iov_base = data,
92        .iov_len = sizeof(data),
93    };
94    errno = 0;
95    ssize_t size = pwritev(-1, &iov, 1, 0);
96    EXPECT_EQ(size, -1);
97    EXPECT_EQ(errno, EBADF);
98}
99