blob: c71e2722a886c73ebaab9b3e3a74bd8e6736f6ba [file] [log] [blame]
James Kuszmaul731a05d2022-01-07 17:59:26 -08001#include "aos/util/scoped_pipe.h"
2
James Kuszmauld42edb42022-01-07 18:00:16 -08003#include <fcntl.h>
4
James Kuszmaul731a05d2022-01-07 17:59:26 -08005#include <array>
6#include <string>
7
8#include "gtest/gtest.h"
9
10namespace aos {
11namespace util {
12namespace testing {
13
14// Tests using uint32_t read/write methods on the ScopedPipe objects.
15TEST(ScopedPipeTest, IntegerPipe) {
James Kuszmauld42edb42022-01-07 18:00:16 -080016 ScopedPipe::PipePair pipe = ScopedPipe::MakePipe();
17 ASSERT_FALSE(pipe.read->Read().has_value())
James Kuszmaul731a05d2022-01-07 17:59:26 -080018 << "Shouldn't get anything on empty read.";
James Kuszmauld42edb42022-01-07 18:00:16 -080019 pipe.write->Write(971);
20 ASSERT_EQ(971, pipe.read->Read().value());
James Kuszmaul731a05d2022-01-07 17:59:26 -080021}
22
23// Tests using string read/write methods on the ScopedPipe objects.
24TEST(ScopedPipeTest, StringPipe) {
James Kuszmauld42edb42022-01-07 18:00:16 -080025 ScopedPipe::PipePair pipe = ScopedPipe::MakePipe();
James Kuszmaul731a05d2022-01-07 17:59:26 -080026 std::string buffer;
James Kuszmauld42edb42022-01-07 18:00:16 -080027 ASSERT_EQ(0u, pipe.read->Read(&buffer))
James Kuszmaul731a05d2022-01-07 17:59:26 -080028 << "Shouldn't get anything on empty read.";
29 ASSERT_TRUE(buffer.empty());
30
31 const char *const kAbc = "abcdef";
James Kuszmauld42edb42022-01-07 18:00:16 -080032 pipe.write->Write(
James Kuszmaul731a05d2022-01-07 17:59:26 -080033 absl::Span<const uint8_t>(reinterpret_cast<const uint8_t *>(kAbc), 6));
James Kuszmauld42edb42022-01-07 18:00:16 -080034 ASSERT_EQ(6u, pipe.read->Read(&buffer));
James Kuszmaul731a05d2022-01-07 17:59:26 -080035 ASSERT_EQ("abcdef", buffer);
36
37 std::array<uint8_t, 10000> large_buffer;
38 large_buffer.fill(99);
James Kuszmauld42edb42022-01-07 18:00:16 -080039 pipe.write->Write(
James Kuszmaul731a05d2022-01-07 17:59:26 -080040 absl::Span<const uint8_t>(large_buffer.data(), large_buffer.size()));
James Kuszmauld42edb42022-01-07 18:00:16 -080041 ASSERT_EQ(large_buffer.size(), pipe.read->Read(&buffer));
James Kuszmaul731a05d2022-01-07 17:59:26 -080042 for (size_t ii = 0; ii < large_buffer.size(); ++ii) {
43 ASSERT_EQ(large_buffer[ii], buffer[ii + 6]);
44 }
45}
46
James Kuszmauld42edb42022-01-07 18:00:16 -080047// Tests that calling SetCloexec succeeds and does indeed set FD_CLOEXEC.
48TEST(ScopedPipeTest, SetCloexec) {
49 ScopedPipe::PipePair pipe = ScopedPipe::MakePipe();
50 ASSERT_EQ(0, fcntl(pipe.read->fd(), F_GETFD) & FD_CLOEXEC);
51 pipe.read->SetCloexec();
52 ASSERT_NE(0, fcntl(pipe.read->fd(), F_GETFD) & FD_CLOEXEC);
53}
54
James Kuszmaul731a05d2022-01-07 17:59:26 -080055} // namespace testing
56} // namespace util
57} // namespace aos