1 //===-- Unittests for send/recv -------------------------------------------===//
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/sys/socket/recv.h"
10 #include "src/sys/socket/send.h"
11 #include "src/sys/socket/socketpair.h"
12
13 #include "src/unistd/close.h"
14
15 #include "test/UnitTest/ErrnoCheckingTest.h"
16 #include "test/UnitTest/ErrnoSetterMatcher.h"
17 #include "test/UnitTest/Test.h"
18
19 #include <sys/socket.h> // For AF_UNIX and SOCK_DGRAM
20
21 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
22 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;
23 using LlvmLibcSendRecvTest = LIBC_NAMESPACE::testing::ErrnoCheckingTest;
24
TEST_F(LlvmLibcSendRecvTest,SucceedsWithSocketPair)25 TEST_F(LlvmLibcSendRecvTest, SucceedsWithSocketPair) {
26 const char TEST_MESSAGE[] = "connection successful";
27 const size_t MESSAGE_LEN = sizeof(TEST_MESSAGE);
28
29 int sockpair[2] = {0, 0};
30
31 ASSERT_THAT(LIBC_NAMESPACE::socketpair(AF_UNIX, SOCK_STREAM, 0, sockpair),
32 Succeeds(0));
33
34 ASSERT_THAT(LIBC_NAMESPACE::send(sockpair[0], TEST_MESSAGE, MESSAGE_LEN, 0),
35 Succeeds(static_cast<ssize_t>(MESSAGE_LEN)));
36
37 char buffer[256];
38
39 ASSERT_THAT(LIBC_NAMESPACE::recv(sockpair[1], buffer, sizeof(buffer), 0),
40 Succeeds(static_cast<ssize_t>(MESSAGE_LEN)));
41
42 ASSERT_STREQ(buffer, TEST_MESSAGE);
43
44 // close both ends of the socket
45 ASSERT_THAT(LIBC_NAMESPACE::close(sockpair[0]), Succeeds(0));
46 ASSERT_THAT(LIBC_NAMESPACE::close(sockpair[1]), Succeeds(0));
47 }
48
TEST_F(LlvmLibcSendRecvTest,SendFails)49 TEST_F(LlvmLibcSendRecvTest, SendFails) {
50 const char TEST_MESSAGE[] = "connection terminated";
51 const size_t MESSAGE_LEN = sizeof(TEST_MESSAGE);
52
53 ASSERT_THAT(LIBC_NAMESPACE::send(-1, TEST_MESSAGE, MESSAGE_LEN, 0),
54 Fails(EBADF));
55 }
56
TEST_F(LlvmLibcSendRecvTest,RecvFails)57 TEST_F(LlvmLibcSendRecvTest, RecvFails) {
58 char buffer[256];
59
60 ASSERT_THAT(LIBC_NAMESPACE::recv(-1, buffer, sizeof(buffer), 0),
61 Fails(EBADF));
62 }
63