1//===-- Unittests for read and write --------------------------------------===//
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/errno/libc_errno.h"
10#include "src/fcntl/open.h"
11#include "src/stdio/remove.h"
12#include "src/unistd/close.h"
13#include "src/unistd/fsync.h"
14#include "src/unistd/read.h"
15#include "src/unistd/write.h"
16#include "test/UnitTest/ErrnoSetterMatcher.h"
17#include "test/UnitTest/Test.h"
18
19#include <sys/stat.h>
20
21TEST(LlvmLibcUniStd, WriteAndReadBackTest) {
22 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;
23 constexpr const char *FILENAME = "__unistd_read_write.test";
24 auto TEST_FILE = libc_make_test_file_path(FILENAME);
25
26 int write_fd = LIBC_NAMESPACE::open(path: TEST_FILE, O_WRONLY | O_CREAT, S_IRWXU);
27 ASSERT_ERRNO_SUCCESS();
28 ASSERT_GT(write_fd, 0);
29 constexpr const char HELLO[] = "hello";
30 constexpr int HELLO_SIZE = sizeof(HELLO);
31 ASSERT_THAT(LIBC_NAMESPACE::write(write_fd, HELLO, HELLO_SIZE),
32 Succeeds(HELLO_SIZE));
33 ASSERT_THAT(LIBC_NAMESPACE::fsync(write_fd), Succeeds(0));
34 ASSERT_THAT(LIBC_NAMESPACE::close(write_fd), Succeeds(0));
35
36 int read_fd = LIBC_NAMESPACE::open(path: TEST_FILE, O_RDONLY);
37 ASSERT_ERRNO_SUCCESS();
38 ASSERT_GT(read_fd, 0);
39 char read_buf[10];
40 ASSERT_THAT(LIBC_NAMESPACE::read(read_fd, read_buf, HELLO_SIZE),
41 Succeeds(HELLO_SIZE));
42 EXPECT_STREQ(read_buf, HELLO);
43 ASSERT_THAT(LIBC_NAMESPACE::close(read_fd), Succeeds(0));
44
45 ASSERT_THAT(LIBC_NAMESPACE::remove(TEST_FILE), Succeeds(0));
46}
47
48TEST(LlvmLibcUniStd, WriteFails) {
49 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
50
51 EXPECT_THAT(LIBC_NAMESPACE::write(-1, "", 1), Fails(EBADF));
52 EXPECT_THAT(LIBC_NAMESPACE::write(1, reinterpret_cast<const void *>(-1), 1),
53 Fails(EFAULT));
54}
55
56TEST(LlvmLibcUniStd, ReadFails) {
57 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
58
59 EXPECT_THAT(LIBC_NAMESPACE::read(-1, nullptr, 1), Fails(EBADF));
60 EXPECT_THAT(LIBC_NAMESPACE::read(0, reinterpret_cast<void *>(-1), 1),
61 Fails(EFAULT));
62}
63

source code of libc/test/src/unistd/read_write_test.cpp