1 // Copyright 2018 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "platform/impl/scoped_pipe.h"
6
7 #include <vector>
8
9 #include "gmock/gmock.h"
10 #include "gtest/gtest.h"
11 #include "util/osp_logging.h"
12
13 namespace openscreen {
14 namespace {
15
16 using ::testing::ElementsAre;
17
18 std::vector<int>* g_freed_values = nullptr;
19
20 struct IntTraits {
21 using PipeType = int;
22 static constexpr int kInvalidValue = -1;
23
Closeopenscreen::__anon6117d79b0111::IntTraits24 static void Close(int fd) { g_freed_values->push_back(fd); }
25 };
26
27 constexpr int IntTraits::kInvalidValue;
28
29 class ScopedPipeTest : public ::testing::Test {
30 protected:
SetUp()31 void SetUp() override {
32 OSP_DCHECK(!g_freed_values);
33 g_freed_values = new std::vector<int>();
34 }
35
TearDown()36 void TearDown() override {
37 delete g_freed_values;
38 g_freed_values = nullptr;
39 }
40 };
41
42 } // namespace
43
TEST_F(ScopedPipeTest,Close)44 TEST_F(ScopedPipeTest, Close) {
45 { ScopedPipe<IntTraits> x; }
46 ASSERT_TRUE(g_freed_values->empty());
47
48 { ScopedPipe<IntTraits> x(3); }
49 EXPECT_THAT(*g_freed_values, ElementsAre(3));
50 g_freed_values->clear();
51
52 {
53 ScopedPipe<IntTraits> x(3);
54 EXPECT_EQ(3, x.release());
55
56 ScopedPipe<IntTraits> y;
57 EXPECT_EQ(IntTraits::kInvalidValue, y.release());
58 }
59 ASSERT_TRUE(g_freed_values->empty());
60
61 {
62 ScopedPipe<IntTraits> x(3);
63 ScopedPipe<IntTraits> y(std::move(x));
64 EXPECT_EQ(IntTraits::kInvalidValue, x.get());
65 EXPECT_EQ(3, y.get());
66 EXPECT_TRUE(g_freed_values->empty());
67 }
68 EXPECT_THAT(*g_freed_values, ElementsAre(3));
69 g_freed_values->clear();
70
71 {
72 ScopedPipe<IntTraits> x(3);
73 ScopedPipe<IntTraits> y(4);
74 y = std::move(x);
75 EXPECT_EQ(IntTraits::kInvalidValue, x.get());
76 EXPECT_EQ(3, y.get());
77 EXPECT_EQ(1u, g_freed_values->size());
78 EXPECT_EQ(4, g_freed_values->front());
79 }
80 EXPECT_THAT(*g_freed_values, ElementsAre(4, 3));
81 g_freed_values->clear();
82 }
83
TEST_F(ScopedPipeTest,Comparisons)84 TEST_F(ScopedPipeTest, Comparisons) {
85 std::vector<int> g_freed_values;
86 ScopedPipe<IntTraits> x;
87 ScopedPipe<IntTraits> y;
88 EXPECT_FALSE(x);
89 EXPECT_EQ(x, y);
90
91 x = ScopedPipe<IntTraits>(3);
92 EXPECT_TRUE(x);
93 EXPECT_NE(x, y);
94
95 y = ScopedPipe<IntTraits>(4);
96 EXPECT_TRUE(y);
97 EXPECT_NE(x, y);
98
99 y = ScopedPipe<IntTraits>(3);
100 EXPECT_EQ(x, y);
101 }
102
103 } // namespace openscreen
104