1 // Copyright (c) 2012 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.
7 #include "base/basictypes.h"
8 #include "base/mac/scoped_nsautorelease_pool.h"
9 #include "base/mac/scoped_nsobject.h"
10 #include "testing/gtest/include/gtest/gtest.h"
14 TEST(ScopedNSObjectTest, ScopedNSObject) {
15 base::scoped_nsobject<NSObject> p1([[NSObject alloc] init]);
16 ASSERT_TRUE(p1.get());
17 ASSERT_EQ(1u, [p1 retainCount]);
18 base::scoped_nsobject<NSObject> p2(p1);
19 ASSERT_EQ(p1.get(), p2.get());
20 ASSERT_EQ(2u, [p1 retainCount]);
22 ASSERT_EQ(nil, p2.get());
23 ASSERT_EQ(1u, [p1 retainCount]);
25 base::scoped_nsobject<NSObject> p3 = p1;
26 ASSERT_EQ(p1.get(), p3.get());
27 ASSERT_EQ(2u, [p1 retainCount]);
29 ASSERT_EQ(p1.get(), p3.get());
30 ASSERT_EQ(2u, [p1 retainCount]);
32 ASSERT_EQ(1u, [p1 retainCount]);
33 base::scoped_nsobject<NSObject> p4([p1.get() retain]);
34 ASSERT_EQ(2u, [p1 retainCount]);
35 ASSERT_TRUE(p1 == p1.get());
36 ASSERT_TRUE(p1 == p1);
37 ASSERT_FALSE(p1 != p1);
38 ASSERT_FALSE(p1 != p1.get());
39 base::scoped_nsobject<NSObject> p5([[NSObject alloc] init]);
40 ASSERT_TRUE(p1 != p5);
41 ASSERT_TRUE(p1 != p5.get());
42 ASSERT_FALSE(p1 == p5);
43 ASSERT_FALSE(p1 == p5.get());
45 base::scoped_nsobject<NSObject> p6 = p1;
46 ASSERT_EQ(3u, [p6 retainCount]);
48 base::mac::ScopedNSAutoreleasePool pool;
50 ASSERT_EQ(nil, p6.get());
51 ASSERT_EQ(3u, [p1 retainCount]);
53 ASSERT_EQ(2u, [p1 retainCount]);
56 TEST(ScopedNSObjectTest, ScopedNSObjectInContainer) {
57 base::scoped_nsobject<id> p([[NSObject alloc] init]);
59 ASSERT_EQ(1u, [p retainCount]);
61 std::vector<base::scoped_nsobject<id>> objects;
63 ASSERT_EQ(2u, [p retainCount]);
64 ASSERT_EQ(p.get(), objects[0].get());
65 objects.push_back(base::scoped_nsobject<id>([[NSObject alloc] init]));
66 ASSERT_TRUE(objects[1].get());
67 ASSERT_EQ(1u, [objects[1] retainCount]);
69 ASSERT_EQ(1u, [p retainCount]);
72 TEST(ScopedNSObjectTest, ScopedNSObjectFreeFunctions) {
73 base::scoped_nsobject<id> p1([[NSObject alloc] init]);
75 ASSERT_TRUE(o1 == p1);
76 ASSERT_FALSE(o1 != p1);
77 base::scoped_nsobject<id> p2([[NSObject alloc] init]);
78 ASSERT_TRUE(o1 != p2);
79 ASSERT_FALSE(o1 == p2);
82 ASSERT_EQ(o2, p1.get());
83 ASSERT_EQ(o1, p2.get());