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

Provided by KDAB

Privacy Policy
Learn to use CMake with our Intro Training
Find out more

source code of libc/test/src/sys/sendfile/sendfile_test.cpp