1/*
2 * Copyright (C) 2014 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 */
16package libcore.java.util;
17
18import dalvik.system.CloseGuard;
19import junit.framework.TestCase;
20
21/**
22 * Test for {@link ResourceLeakageDetector}
23 */
24public class ResourceLeakageDetectorTest extends TestCase {
25  /**
26   * This test will not work on RI as it does not support the <code>CloseGuard</code> or similar
27   * mechanism.
28   */
29  public void testDetectsUnclosedCloseGuard() throws Exception {
30    ResourceLeakageDetector detector = ResourceLeakageDetector.newDetector();
31    try {
32      CloseGuard closeGuard = createCloseGuard();
33      closeGuard.open("open");
34    } finally {
35      try {
36        System.logI("Checking for leaks");
37        detector.checkForLeaks();
38        fail();
39      } catch (AssertionError expected) {
40      }
41    }
42  }
43
44  public void testIgnoresClosedCloseGuard() throws Exception {
45    ResourceLeakageDetector detector = ResourceLeakageDetector.newDetector();
46    try {
47      CloseGuard closeGuard = createCloseGuard();
48      closeGuard.open("open");
49      closeGuard.close();
50    } finally {
51      detector.checkForLeaks();
52    }
53  }
54
55  /**
56   * Private method to ensure that the CloseGuard object is garbage collected.
57   */
58  private CloseGuard createCloseGuard() {
59    final CloseGuard closeGuard = CloseGuard.get();
60    new Object() {
61      @Override
62      protected void finalize() throws Throwable {
63        try {
64          closeGuard.warnIfOpen();
65        } finally {
66          super.finalize();
67        }
68      }
69    };
70
71    return closeGuard;
72  }
73}
74