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.
4
5package org.chromium.testing.local;
6
7import org.junit.runner.Description;
8import org.junit.runner.Result;
9import org.junit.runner.notification.Failure;
10import org.junit.runner.notification.RunListener;
11
12import java.util.HashSet;
13import java.util.Set;
14
15/** A JUnit RunListener that emulates GTest output to the extent that it can.
16 */
17public class GtestListener extends RunListener {
18
19    private Set<Description> mFailedTests;
20    private final GtestLogger mLogger;
21    private long mRunStartTimeMillis;
22    private long mTestStartTimeMillis;
23    private int mTestsPassed;
24    private boolean mCurrentTestPassed;
25
26    public GtestListener(GtestLogger logger) {
27        mLogger = logger;
28    }
29
30    /** Called before any tests run.
31     */
32    @Override
33    public void testRunStarted(Description d) throws Exception {
34        mLogger.testRunStarted(d.testCount());
35        mRunStartTimeMillis = System.currentTimeMillis();
36        mTestsPassed = 0;
37        mFailedTests = new HashSet<Description>();
38        mCurrentTestPassed = true;
39    }
40
41    /** Called after all tests run.
42     */
43    @Override
44    public void testRunFinished(Result r) throws Exception {
45        long elapsedTimeMillis = System.currentTimeMillis() - mRunStartTimeMillis;
46        mLogger.testRunFinished(mTestsPassed, mFailedTests, elapsedTimeMillis);
47    }
48
49    /** Called when a test is about to start.
50     */
51    @Override
52    public void testStarted(Description d) throws Exception {
53        mCurrentTestPassed = true;
54        mLogger.testStarted(d);
55        mTestStartTimeMillis = System.currentTimeMillis();
56    }
57
58    /** Called when a test has just finished.
59     */
60    @Override
61    public void testFinished(Description d) throws Exception {
62        long testElapsedTimeMillis = System.currentTimeMillis() - mTestStartTimeMillis;
63        mLogger.testFinished(d, mCurrentTestPassed, testElapsedTimeMillis);
64        if (mCurrentTestPassed) {
65            ++mTestsPassed;
66        } else {
67            mFailedTests.add(d);
68        }
69    }
70
71    /** Called when a test fails.
72     */
73    @Override
74    public void testFailure(Failure f) throws Exception {
75        mCurrentTestPassed = false;
76        mLogger.testFailed(f);
77    }
78
79}
80
81