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 "securec.h"
26
27using namespace testing::ext;
28using namespace std;
29
30class FtruncateApiTest : public testing::Test {
31public:
32    static void SetUpTestCase();
33    static void TearDownTestCase();
34    void SetUp();
35    void TearDown();
36private:
37};
38void FtruncateApiTest::SetUp()
39{
40}
41void FtruncateApiTest::TearDown()
42{
43}
44void FtruncateApiTest::SetUpTestCase()
45{
46}
47void FtruncateApiTest::TearDownTestCase()
48{
49}
50
51static const char* TEST_FILE = "/data/local/tmp/test.txt";
52
53/*
54 * @tc.number : SUB_KERNEL_SYSCALL_FTRUNCATE_0100
55 * @tc.name   : FtruncateModifyFileSizeSuccess_0001
56 * @tc.desc   : modify file size to 50 success.
57 * @tc.size   : MediumTest
58 * @tc.type   : Function
59 * @tc.level  : Level 1
60 */
61HWTEST_F(FtruncateApiTest, FtruncateModifyFileSizeSuccess_0001, Function | MediumTest | Level1)
62{
63    int ret;
64    int fd = -1;
65    off_t len = 50;
66    struct stat stat;
67
68    fd = open(TEST_FILE, O_WRONLY | O_CREAT, 0644);
69    EXPECT_TRUE(fd > 0);
70
71    ret = ftruncate(fd, len);
72    EXPECT_EQ(ret, 0);
73    ret = fstat(fd, &stat);
74    EXPECT_EQ(ret, 0);
75
76    // Check whether the file size is len
77    EXPECT_EQ(stat.st_size, len);
78
79    close(fd);
80}
81
82/*
83 * @tc.number : SUB_KERNEL_SYSCALL_FTRUNCATE_0200
84 * @tc.name   : FtruncateUseInvalidFdFailed_0002
85 * @tc.desc   : ftruncate modify illegal fd size failed, errno EBADF.
86 * @tc.size   : MediumTest
87 * @tc.type   : Function
88 * @tc.level  : Level 2
89 */
90HWTEST_F(FtruncateApiTest, FtruncateUseInvalidFdFailed_0002, Function | MediumTest | Level2)
91{
92    int ret;
93    off_t len = 20;
94    errno = 0;
95    ret = ftruncate(-1, len);
96    EXPECT_EQ(ret, -1);
97    EXPECT_EQ(errno, EBADF);
98}