xref: /aosp_15_r20/external/llvm-libc/test/src/sys/sendfile/sendfile_test.cpp (revision 71db0c75aadcf003ffe3238005f61d7618a3fead)
1 //===-- Unittests for sendfile --------------------------------------------===//
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 //===----------------------------------------------------------------------===//
8 
9 #include "src/__support/CPP/string_view.h"
10 #include "src/errno/libc_errno.h"
11 #include "src/fcntl/open.h"
12 #include "src/sys/sendfile/sendfile.h"
13 #include "src/unistd/close.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"
19 
20 #include "hdr/fcntl_macros.h"
21 #include <sys/stat.h>
22 
23 namespace cpp = LIBC_NAMESPACE::cpp;
24 
TEST(LlvmLibcSendfileTest,CreateAndTransfer)25 TEST(LlvmLibcSendfileTest, CreateAndTransfer) {
26   using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
27   using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;
28 
29   // The test strategy is to
30   //   1. Create a temporary file with known data.
31   //   2. Use sendfile to copy it to another file.
32   //   3. Make sure that the data was actually copied.
33   //   4. Clean up the temporary files.
34   constexpr const char *IN_FILE = "testdata/sendfile_in.test";
35   constexpr const char *OUT_FILE = "testdata/sendfile_out.test";
36   const char IN_DATA[] = "sendfile test";
37   constexpr ssize_t IN_SIZE = ssize_t(sizeof(IN_DATA));
38   LIBC_NAMESPACE::libc_errno = 0;
39 
40   int in_fd = LIBC_NAMESPACE::open(IN_FILE, O_CREAT | O_WRONLY, S_IRWXU);
41   ASSERT_GT(in_fd, 0);
42   ASSERT_ERRNO_SUCCESS();
43   ASSERT_EQ(LIBC_NAMESPACE::write(in_fd, IN_DATA, IN_SIZE), IN_SIZE);
44   ASSERT_THAT(LIBC_NAMESPACE::close(in_fd), Succeeds(0));
45 
46   in_fd = LIBC_NAMESPACE::open(IN_FILE, O_RDONLY);
47   ASSERT_GT(in_fd, 0);
48   ASSERT_ERRNO_SUCCESS();
49   int out_fd = LIBC_NAMESPACE::open(OUT_FILE, O_CREAT | O_WRONLY, S_IRWXU);
50   ASSERT_GT(out_fd, 0);
51   ASSERT_ERRNO_SUCCESS();
52   ssize_t size = LIBC_NAMESPACE::sendfile(in_fd, out_fd, nullptr, IN_SIZE);
53   ASSERT_EQ(size, IN_SIZE);
54   ASSERT_THAT(LIBC_NAMESPACE::close(in_fd), Succeeds(0));
55   ASSERT_THAT(LIBC_NAMESPACE::close(out_fd), Succeeds(0));
56 
57   out_fd = LIBC_NAMESPACE::open(OUT_FILE, O_RDONLY);
58   ASSERT_GT(out_fd, 0);
59   ASSERT_ERRNO_SUCCESS();
60   char buf[IN_SIZE];
61   ASSERT_EQ(IN_SIZE, LIBC_NAMESPACE::read(out_fd, buf, IN_SIZE));
62   ASSERT_EQ(cpp::string_view(buf), cpp::string_view(IN_DATA));
63 
64   ASSERT_THAT(LIBC_NAMESPACE::unlink(IN_FILE), Succeeds(0));
65   ASSERT_THAT(LIBC_NAMESPACE::unlink(OUT_FILE), Succeeds(0));
66 }
67