blob: 1656574ea335fdbe405349c2d7afedd46a8543da [file] [log] [blame]
Primiano Tucci4f9b6d72017-12-05 20:59:16 +00001/*
2 * Copyright (C) 2017 The Android Open Source Project
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
Primiano Tucci2c5488f2019-06-01 03:27:28 +010017#include "perfetto/ext/base/weak_ptr.h"
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000018
Primiano Tucci919ca1e2019-08-21 20:26:58 +020019#include "test/gtest_and_gmock.h"
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000020
21namespace perfetto {
22namespace base {
23namespace {
24
25class WeakClass {
26 public:
27 WeakClass() : weak_factory(this) {}
28 WeakPtrFactory<WeakClass> weak_factory;
29};
30
31TEST(WeakPtrTest, AllCases) {
32 std::unique_ptr<WeakClass> owned_instance(new WeakClass());
33 WeakPtr<WeakClass> weak_ptr1 = owned_instance->weak_factory.GetWeakPtr();
34 WeakPtr<WeakClass> weak_ptr2;
35 weak_ptr2 = owned_instance->weak_factory.GetWeakPtr();
36 WeakPtr<WeakClass> weak_ptr_copied(weak_ptr2);
Florian Mayeraab53552018-01-24 14:13:55 +000037 WeakPtr<WeakClass> weak_ptr_copied2 = weak_ptr_copied; // NOLINT
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000038
39 ASSERT_TRUE(weak_ptr1);
40 ASSERT_TRUE(weak_ptr2);
41 ASSERT_TRUE(weak_ptr_copied);
42 ASSERT_TRUE(weak_ptr_copied2);
43
44 ASSERT_EQ(owned_instance.get(), weak_ptr1.get());
45 ASSERT_EQ(owned_instance.get(), weak_ptr2.get());
46 ASSERT_EQ(owned_instance.get(), weak_ptr_copied.get());
47 ASSERT_EQ(owned_instance.get(), weak_ptr_copied2.get());
48
49 WeakPtr<WeakClass> weak_ptr_moved1(std::move(weak_ptr1));
50 WeakPtr<WeakClass> weak_ptr_moved2(weak_ptr_copied2);
51 weak_ptr_moved2 = std::move(weak_ptr2);
52 ASSERT_FALSE(weak_ptr1);
53 ASSERT_FALSE(weak_ptr2);
54 ASSERT_TRUE(weak_ptr_moved1);
55 ASSERT_TRUE(weak_ptr_moved2);
56 ASSERT_TRUE(weak_ptr_copied2);
57 ASSERT_EQ(owned_instance.get(), weak_ptr_moved1.get());
58 ASSERT_EQ(owned_instance.get(), weak_ptr_moved2.get());
59
60 owned_instance.reset();
61
62 ASSERT_FALSE(weak_ptr1);
63 ASSERT_FALSE(weak_ptr2);
64 ASSERT_FALSE(weak_ptr_copied);
65 ASSERT_FALSE(weak_ptr_copied2);
66 ASSERT_FALSE(weak_ptr_moved1);
67 ASSERT_FALSE(weak_ptr_moved2);
68}
69
70} // namespace
71} // namespace base
72} // namespace perfetto