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/fcntl/open.h"
10 #include "src/unistd/close.h"
11 #include "src/unistd/dup.h"
12 #include "src/unistd/read.h"
13 #include "src/unistd/unlink.h"
14 #include "src/unistd/write.h"
15 #include "test/ErrnoSetterMatcher.h"
16 #include "test/UnitTest/Test.h"
17 #include "utils/testutils/FDReader.h"
21 TEST(LlvmLibcdupTest
, ReadAndWriteViaDup
) {
23 using __llvm_libc::testing::ErrnoSetterMatcher::Succeeds
;
24 constexpr const char *TEST_FILE
= "testdata/dup.test";
25 int fd
= __llvm_libc::open(TEST_FILE
, O_WRONLY
| O_CREAT
, S_IRWXU
);
28 int dupfd
= __llvm_libc::dup(fd
);
32 // Write something via the dup
33 constexpr char WRITE_DATA
[] = "Hello, dup!";
34 constexpr size_t WRITE_SIZE
= sizeof(WRITE_DATA
);
35 ASSERT_EQ(ssize_t(WRITE_SIZE
),
36 __llvm_libc::write(dupfd
, WRITE_DATA
, WRITE_SIZE
));
37 ASSERT_THAT(__llvm_libc::close(dupfd
), Succeeds(0));
39 // Reopen the file for reading and create a dup.
40 fd
= __llvm_libc::open(TEST_FILE
, O_RDONLY
);
43 dupfd
= __llvm_libc::dup(fd
);
47 // Read the file content via the dup.
49 ASSERT_THAT(__llvm_libc::read(dupfd
, buf
, WRITE_SIZE
), Succeeds(WRITE_SIZE
));
50 ASSERT_STREQ(buf
, WRITE_DATA
);
52 ASSERT_THAT(__llvm_libc::close(dupfd
), Succeeds(0));
53 ASSERT_THAT(__llvm_libc::unlink(TEST_FILE
), Succeeds(0));
56 TEST(LlvmLibcdupTest
, DupBadFD
) {
57 using __llvm_libc::testing::ErrnoSetterMatcher::Fails
;
58 ASSERT_THAT(__llvm_libc::dup(-1), Fails(EBADF
));