1 // Copyright 2014 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.
5 #import "ios/web/weak_nsobject_counter.h"
7 #import <Foundation/Foundation.h>
9 #import "base/ios/weak_nsobject.h"
10 #import "base/mac/scoped_nsobject.h"
11 #include "testing/gtest/include/gtest/gtest.h"
15 // Tests that a WeakNSObjectCounter correctly maintains a weak reference and
16 // calculates the size correctly when many objects are added.
17 TEST(WeakNSObjectCounter, ManyObjects) {
18 web::WeakNSObjectCounter object_counter;
19 base::scoped_nsobject<NSObject> p1([[NSObject alloc] init]);
20 base::scoped_nsobject<NSObject> p2([[NSObject alloc] init]);
21 base::scoped_nsobject<NSObject> p3([[NSObject alloc] init]);
22 object_counter.Insert(p1);
23 EXPECT_EQ(1U, object_counter.Size());
24 object_counter.Insert(p2);
25 EXPECT_EQ(2U, object_counter.Size());
26 object_counter.Insert(p3);
27 EXPECT_EQ(3U, object_counter.Size());
28 // Make sure p3 is correctly removed from the object counter.
31 EXPECT_EQ(2U, object_counter.Size());
32 // Make sure p2 is correctly removed from the object counter.
34 EXPECT_EQ(1U, object_counter.Size());
35 // Make sure p1 is correctly removed from the object counter.
38 EXPECT_EQ(0U, object_counter.Size());
41 // Tests that WeakNSObjectCounter correctly works when the object outlives the
42 // WeakNSObjectCounter that is observing it.
43 TEST(WeakNSObjectCounter, ObjectOutlivesWeakNSObjectCounter) {
44 base::scoped_nsobject<NSObject> p1([[NSObject alloc] init]);
46 web::WeakNSObjectCounter object_counter;
47 object_counter.Insert(p1);
48 EXPECT_EQ(1U, object_counter.Size());
54 // Tests that WeakNSObjectCounter does not add the same object twice.
55 TEST(WeakNSObjectCounter, SameObject) {
56 base::scoped_nsobject<NSObject> p1([[NSObject alloc] init]);
57 base::WeakNSObject<NSObject> p2(p1);
58 // Make sure they are the same object.
60 web::WeakNSObjectCounter object_counter;
61 object_counter.Insert(p1);
62 EXPECT_EQ(1U, object_counter.Size());
63 object_counter.Insert(p2);
64 EXPECT_EQ(1U, object_counter.Size());
67 // Tests that WeakNSObjectCounter correctly maintains a reference to the object
68 // and reduces its size only when the last reference to the object goes away.
69 TEST(WeakNSObjectCounter, LastReference) {
70 web::WeakNSObjectCounter object_counter;
71 base::scoped_nsobject<NSObject> p1([[NSObject alloc] init]);
72 object_counter.Insert(p1);
73 EXPECT_EQ(1U, object_counter.Size());
74 base::scoped_nsobject<NSObject> p2(p1);
75 base::scoped_nsobject<NSObject> p3(p1);
77 EXPECT_EQ(1U, object_counter.Size());
79 EXPECT_EQ(1U, object_counter.Size());
80 // Last reference goes away.
82 EXPECT_FALSE(object_counter.Size());