2 // Copyright 2020 gRPC authors.
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
8 // http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "src/core/lib/gprpp/dual_ref_counted.h"
21 #include <gmock/gmock.h>
22 #include <gtest/gtest.h>
24 #include "test/core/util/test_config.h"
30 class Foo : public DualRefCounted<Foo> {
33 ~Foo() override { GPR_ASSERT(shutting_down_); }
35 void Orphan() override { shutting_down_ = true; }
38 bool shutting_down_ = false;
41 TEST(DualRefCounted, Basic) {
46 TEST(DualRefCounted, ExtraRef) {
53 TEST(DualRefCounted, ExtraWeakRef) {
55 foo->WeakRef().release();
60 TEST(DualRefCounted, RefIfNonZero) {
62 foo->WeakRef().release();
64 RefCountedPtr<Foo> foop = foo->RefIfNonZero();
65 EXPECT_NE(foop.get(), nullptr);
69 RefCountedPtr<Foo> foop = foo->RefIfNonZero();
70 EXPECT_EQ(foop.get(), nullptr);
75 class FooWithTracing : public DualRefCounted<FooWithTracing> {
77 FooWithTracing() : DualRefCounted("FooWithTracing") {}
78 ~FooWithTracing() override { GPR_ASSERT(shutting_down_); }
80 void Orphan() override { shutting_down_ = true; }
83 bool shutting_down_ = false;
86 TEST(DualRefCountedWithTracing, Basic) {
87 FooWithTracing* foo = new FooWithTracing();
88 foo->Ref(DEBUG_LOCATION, "extra_ref").release();
89 foo->Unref(DEBUG_LOCATION, "extra_ref");
90 foo->WeakRef(DEBUG_LOCATION, "extra_ref").release();
91 foo->WeakUnref(DEBUG_LOCATION, "extra_ref");
92 // Can use the no-argument methods, too.
95 foo->WeakRef().release();
97 foo->Unref(DEBUG_LOCATION, "original_ref");
101 } // namespace testing
102 } // namespace grpc_core
104 int main(int argc, char** argv) {
105 grpc::testing::TestEnvironment env(argc, argv);
106 ::testing::InitGoogleTest(&argc, argv);
107 return RUN_ALL_TESTS();