1//===-- Unittests for truncate --------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "src/__support/CPP/string_view.h"
10#include "src/fcntl/open.h"
11#include "src/unistd/close.h"
12#include "src/unistd/read.h"
13#include "src/unistd/truncate.h"
14#include "src/unistd/unlink.h"
15#include "src/unistd/write.h"
16#include "test/UnitTest/ErrnoCheckingTest.h"
17#include "test/UnitTest/ErrnoSetterMatcher.h"
18#include "test/UnitTest/Test.h"
19
20#include <sys/stat.h>
21
22namespace cpp = LIBC_NAMESPACE::cpp;
23
24using LlvmLibcTruncateTest = LIBC_NAMESPACE::testing::ErrnoCheckingTest;
25
26TEST_F(LlvmLibcTruncateTest, CreateAndTruncate) {
27 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;
28 constexpr const char *FILENAME = "truncate.test";
29 auto TEST_FILE = libc_make_test_file_path(FILENAME);
30 constexpr const char WRITE_DATA[] = "hello, truncate";
31 constexpr size_t WRITE_SIZE = sizeof(WRITE_DATA);
32 char buf[WRITE_SIZE];
33
34 // The test strategy is as follows:
35 // 1. Create a normal file with some data in it.
36 // 2. Read it to make sure what was written is actually in the file.
37 // 3. Truncate to 1 byte.
38 // 4. Try to read more than 1 byte and fail.
39 int fd = LIBC_NAMESPACE::open(TEST_FILE, O_WRONLY | O_CREAT, S_IRWXU);
40 ASSERT_ERRNO_SUCCESS();
41 ASSERT_GT(fd, 0);
42 ASSERT_EQ(ssize_t(WRITE_SIZE),
43 LIBC_NAMESPACE::write(fd, WRITE_DATA, WRITE_SIZE));
44 ASSERT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0));
45
46 fd = LIBC_NAMESPACE::open(TEST_FILE, O_RDONLY);
47 ASSERT_ERRNO_SUCCESS();
48 ASSERT_GT(fd, 0);
49 ASSERT_EQ(ssize_t(WRITE_SIZE), LIBC_NAMESPACE::read(fd, buf, WRITE_SIZE));
50 ASSERT_EQ(cpp::string_view(buf), cpp::string_view(WRITE_DATA));
51 ASSERT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0));
52
53 ASSERT_THAT(LIBC_NAMESPACE::truncate(TEST_FILE, off_t(1)), Succeeds(0));
54
55 fd = LIBC_NAMESPACE::open(TEST_FILE, O_RDONLY);
56 ASSERT_ERRNO_SUCCESS();
57 ASSERT_GT(fd, 0);
58 ASSERT_EQ(ssize_t(1), LIBC_NAMESPACE::read(fd, buf, WRITE_SIZE));
59 ASSERT_EQ(buf[0], WRITE_DATA[0]);
60 ASSERT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0));
61
62 ASSERT_THAT(LIBC_NAMESPACE::unlink(TEST_FILE), Succeeds(0));
63}
64
65TEST_F(LlvmLibcTruncateTest, TruncateNonExistentFile) {
66 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
67 ASSERT_THAT(
68 LIBC_NAMESPACE::truncate("non-existent-dir/non-existent-file", off_t(1)),
69 Fails(ENOENT));
70}
71

Provided by KDAB

Privacy Policy
Update your C++ knowledge – Modern C++11/14/17 Training
Find out more

source code of libc/test/src/unistd/truncate_test.cpp