[flang] Accept polymorphic component element in storage_size
[llvm-project.git] / libc / test / src / unistd / dup2_test.cpp
blobb595a66a5a109c62feb7ba3172ecb5f6721151f6
1 //===-- Unittests for dup -------------------------------------------------===//
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/fcntl/open.h"
10 #include "src/unistd/close.h"
11 #include "src/unistd/dup2.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"
19 #include <errno.h>
21 TEST(LlvmLibcdupTest, ReadAndWriteViaDup) {
22 constexpr int DUPFD = 0xD0;
23 errno = 0;
24 using __llvm_libc::testing::ErrnoSetterMatcher::Succeeds;
25 constexpr const char *TEST_FILE = "testdata/dup2.test";
26 int fd = __llvm_libc::open(TEST_FILE, O_WRONLY | O_CREAT, S_IRWXU);
27 ASSERT_EQ(errno, 0);
28 ASSERT_GT(fd, 0);
29 int dupfd = __llvm_libc::dup2(fd, DUPFD);
30 ASSERT_EQ(errno, 0);
31 ASSERT_EQ(dupfd, DUPFD);
33 // Write something via the dup
34 constexpr char WRITE_DATA[] = "Hello, dup!";
35 constexpr size_t WRITE_SIZE = sizeof(WRITE_DATA);
36 ASSERT_EQ(ssize_t(WRITE_SIZE),
37 __llvm_libc::write(dupfd, WRITE_DATA, WRITE_SIZE));
38 ASSERT_THAT(__llvm_libc::close(dupfd), Succeeds(0));
40 // Reopen the file for reading and create a dup.
41 fd = __llvm_libc::open(TEST_FILE, O_RDONLY);
42 ASSERT_EQ(errno, 0);
43 ASSERT_GT(fd, 0);
44 dupfd = __llvm_libc::dup2(fd, DUPFD);
45 ASSERT_EQ(errno, 0);
46 ASSERT_EQ(dupfd, DUPFD);
48 // Read the file content via the dup.
49 char buf[WRITE_SIZE];
50 ASSERT_THAT(__llvm_libc::read(dupfd, buf, WRITE_SIZE), Succeeds(WRITE_SIZE));
51 ASSERT_STREQ(buf, WRITE_DATA);
53 // Verify that duping to the same fd value succeeds.
54 ASSERT_THAT(__llvm_libc::dup2(dupfd, dupfd), Succeeds(dupfd));
56 ASSERT_THAT(__llvm_libc::close(dupfd), Succeeds(0));
57 ASSERT_THAT(__llvm_libc::unlink(TEST_FILE), Succeeds(0));
60 TEST(LlvmLibcdupTest, DupBadFD) {
61 using __llvm_libc::testing::ErrnoSetterMatcher::Fails;
62 ASSERT_THAT(__llvm_libc::dup2(-1, 123), Fails(EBADF));