1 //===-- Unittests for truncate --------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
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/ErrnoSetterMatcher.h"
17 #include "test/UnitTest/Test.h"
21 namespace cpp
= __llvm_libc::cpp
;
23 TEST(LlvmLibcTruncateTest
, CreateAndTruncate
) {
24 using __llvm_libc::testing::ErrnoSetterMatcher::Succeeds
;
25 constexpr const char TEST_FILE
[] = "testdata/truncate.test";
26 constexpr const char WRITE_DATA
[] = "hello, truncate";
27 constexpr size_t WRITE_SIZE
= sizeof(WRITE_DATA
);
30 // The test strategy is as follows:
31 // 1. Create a normal file with some data in it.
32 // 2. Read it to make sure what was written is actually in the file.
33 // 3. Truncate to 1 byte.
34 // 4. Try to read more than 1 byte and fail.
36 int fd
= __llvm_libc::open(TEST_FILE
, O_WRONLY
| O_CREAT
, S_IRWXU
);
39 ASSERT_EQ(ssize_t(WRITE_SIZE
),
40 __llvm_libc::write(fd
, WRITE_DATA
, WRITE_SIZE
));
41 ASSERT_THAT(__llvm_libc::close(fd
), Succeeds(0));
43 fd
= __llvm_libc::open(TEST_FILE
, O_RDONLY
);
46 ASSERT_EQ(ssize_t(WRITE_SIZE
), __llvm_libc::read(fd
, buf
, WRITE_SIZE
));
47 ASSERT_EQ(cpp::string_view(buf
), cpp::string_view(WRITE_DATA
));
48 ASSERT_THAT(__llvm_libc::close(fd
), Succeeds(0));
50 ASSERT_THAT(__llvm_libc::truncate(TEST_FILE
, off_t(1)), Succeeds(0));
52 fd
= __llvm_libc::open(TEST_FILE
, O_RDONLY
);
55 ASSERT_EQ(ssize_t(1), __llvm_libc::read(fd
, buf
, WRITE_SIZE
));
56 ASSERT_EQ(buf
[0], WRITE_DATA
[0]);
57 ASSERT_THAT(__llvm_libc::close(fd
), Succeeds(0));
59 ASSERT_THAT(__llvm_libc::unlink(TEST_FILE
), Succeeds(0));
62 TEST(LlvmLibcTruncateTest
, TruncateNonExistentFile
) {
63 using __llvm_libc::testing::ErrnoSetterMatcher::Fails
;
65 __llvm_libc::truncate("non-existent-dir/non-existent-file", off_t(1)),