1/*
2 * Copyright (C) 2010 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
17package libcore.dalvik.system;
18
19import dalvik.system.CloseGuard;
20import java.io.Closeable;
21import java.io.IOException;
22import java.util.List;
23import java.util.concurrent.CopyOnWriteArrayList;
24import java.util.logging.ConsoleHandler;
25import java.util.logging.Handler;
26import java.util.logging.LogRecord;
27import java.util.logging.Logger;
28import junit.framework.Assert;
29import libcore.java.lang.ref.FinalizationTester;
30
31public final class CloseGuardTester implements Closeable {
32
33    private final List<LogRecord> logRecords = new CopyOnWriteArrayList<LogRecord>();
34    private final Logger logger = Logger.getLogger(CloseGuard.class.getName());
35
36    private final Handler logWatcher = new Handler() {
37        @Override public void close() {}
38        @Override public void flush() {}
39        @Override public void publish(LogRecord record) {
40            logRecords.add(record);
41        }
42    };
43
44    public CloseGuardTester() {
45        /*
46         * Collect immediately before we start monitoring the CloseGuard logs.
47         * This lowers the chance that we'll report an unrelated leak.
48         */
49        FinalizationTester.induceFinalization();
50        logger.addHandler(logWatcher);
51    }
52
53    public void assertEverythingWasClosed() {
54        FinalizationTester.induceFinalization();
55
56        if (!logRecords.isEmpty()) {
57            // print the log records with the output of this test
58            for (LogRecord leak : logRecords) {
59                new ConsoleHandler().publish(leak);
60            }
61            Assert.fail("CloseGuard detected unclosed resources!");
62        }
63    }
64
65    @Override public void close() throws IOException {
66        Logger.getLogger(CloseGuard.class.getName()).removeHandler(logWatcher);
67    }
68}
69