Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / libc / test / src / unistd / ftruncate_test.cpp
blobae743b385e220dbe611e230c0f737e61185c760b
1 //===-- Unittests for ftruncate -------------------------------------------===//
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 //===----------------------------------------------------------------------===//
9 #include "src/__support/CPP/string_view.h"
10 #include "src/errno/libc_errno.h"
11 #include "src/fcntl/open.h"
12 #include "src/unistd/close.h"
13 #include "src/unistd/ftruncate.h"
14 #include "src/unistd/read.h"
15 #include "src/unistd/unlink.h"
16 #include "src/unistd/write.h"
17 #include "test/UnitTest/ErrnoSetterMatcher.h"
18 #include "test/UnitTest/Test.h"
20 namespace cpp = LIBC_NAMESPACE::cpp;
22 TEST(LlvmLibcFtruncateTest, CreateAndTruncate) {
23 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;
24 constexpr const char TEST_FILE[] = "testdata/ftruncate.test";
25 constexpr const char WRITE_DATA[] = "hello, ftruncate";
26 constexpr size_t WRITE_SIZE = sizeof(WRITE_DATA);
27 char buf[WRITE_SIZE];
29 // The test strategy is as follows:
30 // 1. Create a normal file with some data in it.
31 // 2. Read it to make sure what was written is actually in the file.
32 // 3. Truncate to 1 byte.
33 // 4. Try to read more than 1 byte and fail.
34 libc_errno = 0;
35 int fd = LIBC_NAMESPACE::open(TEST_FILE, O_WRONLY | O_CREAT, S_IRWXU);
36 ASSERT_EQ(libc_errno, 0);
37 ASSERT_GT(fd, 0);
38 ASSERT_EQ(ssize_t(WRITE_SIZE),
39 LIBC_NAMESPACE::write(fd, WRITE_DATA, WRITE_SIZE));
40 ASSERT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0));
42 fd = LIBC_NAMESPACE::open(TEST_FILE, O_RDONLY);
43 ASSERT_EQ(libc_errno, 0);
44 ASSERT_GT(fd, 0);
45 ASSERT_EQ(ssize_t(WRITE_SIZE), LIBC_NAMESPACE::read(fd, buf, WRITE_SIZE));
46 ASSERT_EQ(cpp::string_view(buf), cpp::string_view(WRITE_DATA));
47 ASSERT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0));
49 // For ftruncate operation to succeed, the file should be opened for
50 // writing.
51 fd = LIBC_NAMESPACE::open(TEST_FILE, O_WRONLY);
52 ASSERT_GT(fd, 0);
53 ASSERT_EQ(libc_errno, 0);
54 ASSERT_THAT(LIBC_NAMESPACE::ftruncate(fd, off_t(1)), Succeeds(0));
55 ASSERT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0));
57 fd = LIBC_NAMESPACE::open(TEST_FILE, O_RDONLY);
58 ASSERT_EQ(libc_errno, 0);
59 ASSERT_GT(fd, 0);
60 ASSERT_EQ(ssize_t(1), LIBC_NAMESPACE::read(fd, buf, WRITE_SIZE));
61 ASSERT_EQ(buf[0], WRITE_DATA[0]);
62 ASSERT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0));
64 ASSERT_THAT(LIBC_NAMESPACE::unlink(TEST_FILE), Succeeds(0));
67 TEST(LlvmLibcFtruncateTest, TruncateBadFD) {
68 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
69 ASSERT_THAT(LIBC_NAMESPACE::ftruncate(1, off_t(1)), Fails(EINVAL));