1 // Copyright 2014 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package org.chromium.testing.local; 6 7 import org.junit.runner.Computer; 8 import org.junit.runner.Description; 9 import org.junit.runner.Runner; 10 import org.junit.runner.manipulation.Filter; 11 import org.junit.runner.manipulation.Filterable; 12 import org.junit.runner.manipulation.NoTestsRemainException; 13 import org.junit.runner.notification.RunNotifier; 14 import org.junit.runners.model.InitializationError; 15 import org.junit.runners.model.RunnerBuilder; 16 17 /** A Computer that logs the start and end of test cases googletest-style. */ 18 public class GtestComputer extends Computer { 19 20 private final GtestLogger mLogger; 21 GtestComputer(GtestLogger logger)22 public GtestComputer(GtestLogger logger) { 23 mLogger = logger; 24 } 25 26 /** A wrapping Runner that logs the start and end of each test case. */ 27 private class GtestSuiteRunner extends Runner implements Filterable { 28 private final Runner mRunner; 29 GtestSuiteRunner(Runner contained)30 public GtestSuiteRunner(Runner contained) { 31 mRunner = contained; 32 } 33 34 @Override getDescription()35 public Description getDescription() { 36 return mRunner.getDescription(); 37 } 38 39 @Override run(RunNotifier notifier)40 public void run(RunNotifier notifier) { 41 long startTimeMillis = System.currentTimeMillis(); 42 // Robolectric 4.3 clears testExecutionContext after running so 43 // need to store data before running. 44 Description desc = mRunner.getDescription(); 45 int testcount = mRunner.getDescription().testCount(); 46 mLogger.testCaseStarted(desc, testcount); 47 mRunner.run(notifier); 48 mLogger.testCaseFinished(desc, testcount, System.currentTimeMillis() - startTimeMillis); 49 } 50 51 @Override filter(Filter filter)52 public void filter(Filter filter) throws NoTestsRemainException { 53 if (mRunner instanceof Filterable) { 54 ((Filterable) mRunner).filter(filter); 55 } 56 } 57 } 58 59 /** 60 * Returns a suite of unit tests with each class runner wrapped by a 61 * GtestSuiteRunner. 62 */ 63 @Override getSuite(final RunnerBuilder builder, Class<?>[] classes)64 public Runner getSuite(final RunnerBuilder builder, Class<?>[] classes) 65 throws InitializationError { 66 return super.getSuite( 67 new RunnerBuilder() { 68 @Override 69 public Runner runnerForClass(Class<?> testClass) throws Throwable { 70 return new GtestSuiteRunner(builder.runnerForClass(testClass)); 71 } 72 }, 73 classes); 74 } 75 } 76