1 // Copyright (C) 2014 The Android Open Source Project
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 #include "emugl/common/smart_ptr.h"
17 #include <gtest/gtest.h>
21 // This Test sub-class is used to track allocations and deallocations of
22 // the MyTestClass instances that are created through newInstance().
23 // See below for typical usage.
24 class SmartPtrTest : public testing::Test {
26 SmartPtrTest() : mNewCount(0), mDeleteCount(0), mDoCount(0) {}
36 MyClass* newInstance() {
37 return new MyClass(this);
42 MyClass(SmartPtrTest* test) : mTest(test) {
51 mTest->mDeleteCount++;
63 TEST_F(SmartPtrTest, Empty) {
64 SmartPtr<MyClass> ptr;
65 EXPECT_FALSE(ptr.Ptr());
67 EXPECT_EQ(0, mNewCount);
68 EXPECT_EQ(0, mDeleteCount);
69 EXPECT_EQ(0, mDoCount);
73 TEST_F(SmartPtrTest, SingleRef) {
74 MyClass* obj = newInstance();
75 EXPECT_EQ(1, mNewCount);
78 SmartPtr<MyClass> ptr(obj);
79 EXPECT_EQ(obj, ptr.Ptr());
81 EXPECT_EQ(1, mNewCount);
82 EXPECT_EQ(0, mDeleteCount);
83 EXPECT_EQ(0, mDoCount);
85 // Check that the object was deleted.
86 EXPECT_EQ(1, mDeleteCount);
90 TEST_F(SmartPtrTest, CopyConstructor) {
91 MyClass* obj = newInstance();
92 EXPECT_EQ(1, mNewCount);
95 SmartPtr<MyClass> ptr1(obj);
97 SmartPtr<MyClass> ptr2(ptr1);
98 EXPECT_EQ(2, ptr1.getRefCount());
99 EXPECT_EQ(2, ptr2.getRefCount());
100 EXPECT_EQ(1, mNewCount);
101 EXPECT_EQ(0, mDeleteCount);
102 EXPECT_EQ(0, mDoCount);
104 EXPECT_EQ(1, mNewCount);
105 EXPECT_EQ(0, mDeleteCount);
106 EXPECT_EQ(0, mDoCount);
108 EXPECT_EQ(1, mNewCount);
109 EXPECT_EQ(1, mDeleteCount);
110 EXPECT_EQ(0, mDoCount);
114 TEST_F(SmartPtrTest, AssignmentOperator) {
115 SmartPtr<MyClass> ptr1(newInstance());
116 SmartPtr<MyClass> ptr2(newInstance());
117 EXPECT_EQ(2, mNewCount);
118 EXPECT_EQ(0, mDeleteCount);
119 EXPECT_EQ(0, mDoCount);
122 EXPECT_EQ(2, mNewCount);
123 EXPECT_EQ(1, mDeleteCount);
125 EXPECT_EQ(ptr1.Ptr(), ptr2.Ptr());
126 EXPECT_EQ(2, ptr1.getRefCount());
127 EXPECT_EQ(2, ptr2.getRefCount());
131 TEST_F(SmartPtrTest, ArrowOperator) {
132 SmartPtr<MyClass> ptr(newInstance());
134 EXPECT_EQ(1, mDoCount);
137 EXPECT_EQ(2, mDoCount);