1 //===-- Unittests for dup -------------------------------------------------===//
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/errno/libc_errno.h"
10 #include "src/fcntl/open.h"
11 #include "src/unistd/close.h"
12 #include "src/unistd/dup.h"
13 #include "src/unistd/read.h"
14 #include "src/unistd/unlink.h"
15 #include "src/unistd/write.h"
16 #include "test/UnitTest/ErrnoSetterMatcher.h"
17 #include "test/UnitTest/Test.h"
19 TEST(LlvmLibcdupTest
, ReadAndWriteViaDup
) {
21 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds
;
22 constexpr const char *TEST_FILE
= "testdata/dup.test";
23 int fd
= LIBC_NAMESPACE::open(TEST_FILE
, O_WRONLY
| O_CREAT
, S_IRWXU
);
24 ASSERT_EQ(libc_errno
, 0);
26 int dupfd
= LIBC_NAMESPACE::dup(fd
);
27 ASSERT_EQ(libc_errno
, 0);
30 // Write something via the dup
31 constexpr char WRITE_DATA
[] = "Hello, dup!";
32 constexpr size_t WRITE_SIZE
= sizeof(WRITE_DATA
);
33 ASSERT_EQ(ssize_t(WRITE_SIZE
),
34 LIBC_NAMESPACE::write(dupfd
, WRITE_DATA
, WRITE_SIZE
));
35 ASSERT_THAT(LIBC_NAMESPACE::close(dupfd
), Succeeds(0));
37 // Reopen the file for reading and create a dup.
38 fd
= LIBC_NAMESPACE::open(TEST_FILE
, O_RDONLY
);
39 ASSERT_EQ(libc_errno
, 0);
41 dupfd
= LIBC_NAMESPACE::dup(fd
);
42 ASSERT_EQ(libc_errno
, 0);
45 // Read the file content via the dup.
47 ASSERT_THAT(LIBC_NAMESPACE::read(dupfd
, buf
, WRITE_SIZE
),
48 Succeeds(WRITE_SIZE
));
49 ASSERT_STREQ(buf
, WRITE_DATA
);
51 ASSERT_THAT(LIBC_NAMESPACE::close(dupfd
), Succeeds(0));
52 ASSERT_THAT(LIBC_NAMESPACE::unlink(TEST_FILE
), Succeeds(0));
55 TEST(LlvmLibcdupTest
, DupBadFD
) {
56 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails
;
57 ASSERT_THAT(LIBC_NAMESPACE::dup(-1), Fails(EBADF
));