Debian Codegraph @

test/core/gprpp/dual_ref_counted_test.cc

raw
1 //
2 // Copyright 2020 gRPC authors.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16
17 #include "src/core/lib/gprpp/dual_ref_counted.h"
18
19 #include "gtest/gtest.h"
20
21 #include "test/core/util/test_config.h"
22
23 namespace grpc_core {
24 namespace testing {
25 namespace {
26
27 class Foo : public DualRefCounted<Foo> {
28 public:
29 Foo() = default;
30 ~Foo() override { GPR_ASSERT(shutting_down_); }
31
32 void Orphan() override { shutting_down_ = true; }
33
34 private:
35 bool shutting_down_ = false;
36 };
37
38 TEST(DualRefCounted, Basic) {
39 Foo* foo = new Foo();
40 foo->Unref();
41 }
42
43 TEST(DualRefCounted, ExtraRef) {
44 Foo* foo = new Foo();
45 foo->Ref().release();
46 foo->Unref();
47 foo->Unref();
48 }
49
50 TEST(DualRefCounted, ExtraWeakRef) {
51 Foo* foo = new Foo();
52 foo->WeakRef().release();
53 foo->Unref();
54 foo->WeakUnref();
55 }
56
57 TEST(DualRefCounted, RefIfNonZero) {
58 Foo* foo = new Foo();
59 foo->WeakRef().release();
60 {
61 RefCountedPtr<Foo> foop = foo->RefIfNonZero();
62 EXPECT_NE(foop.get(), nullptr);
63 }
64 foo->Unref();
65 {
66 RefCountedPtr<Foo> foop = foo->RefIfNonZero();
67 EXPECT_EQ(foop.get(), nullptr);
68 }
69 foo->WeakUnref();
70 }
71
72 class FooWithTracing : public DualRefCounted<FooWithTracing> {
73 public:
74 FooWithTracing() : DualRefCounted("FooWithTracing") {}
75 ~FooWithTracing() override { GPR_ASSERT(shutting_down_); }
76
77 void Orphan() override { shutting_down_ = true; }
78
79 private:
80 bool shutting_down_ = false;
81 };
82
83 TEST(DualRefCountedWithTracing, Basic) {
84 FooWithTracing* foo = new FooWithTracing();
85 foo->Ref(DEBUG_LOCATION, "extra_ref").release();
86 foo->Unref(DEBUG_LOCATION, "extra_ref");
87 foo->WeakRef(DEBUG_LOCATION, "extra_ref").release();
88 foo->WeakUnref(DEBUG_LOCATION, "extra_ref");
89 // Can use the no-argument methods, too.
90 foo->Ref().release();
91 foo->Unref();
92 foo->WeakRef().release();
93 foo->WeakUnref();
94 foo->Unref(DEBUG_LOCATION, "original_ref");
95 }
96
97 } // namespace
98 } // namespace testing
99 } // namespace grpc_core
100
101 int main(int argc, char** argv) {
102 grpc::testing::TestEnvironment env(&argc, argv);
103 ::testing::InitGoogleTest(&argc, argv);
104 return RUN_ALL_TESTS();
105 }