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 /** 18 * A Computer that logs the start and end of test cases googletest-style. 19 */ 20 public class GtestComputer extends Computer { 21 22 private final GtestLogger mLogger; 23 GtestComputer(GtestLogger logger)24 public GtestComputer(GtestLogger logger) { 25 mLogger = logger; 26 } 27 28 /** 29 * A wrapping Runner that logs the start and end of each test case. 30 */ 31 private class GtestSuiteRunner extends Runner implements Filterable { 32 private final Runner mRunner; 33 GtestSuiteRunner(Runner contained)34 public GtestSuiteRunner(Runner contained) { 35 mRunner = contained; 36 } 37 38 @Override getDescription()39 public Description getDescription() { 40 return mRunner.getDescription(); 41 } 42 43 @Override run(RunNotifier notifier)44 public void run(RunNotifier notifier) { 45 long startTimeMillis = System.currentTimeMillis(); 46 // Robolectric 4.3 clears testExecutionContext after running so 47 // need to store data before running. 48 Description desc = mRunner.getDescription(); 49 int testcount = mRunner.getDescription().testCount(); 50 mLogger.testCaseStarted(desc, testcount); 51 mRunner.run(notifier); 52 mLogger.testCaseFinished(desc, testcount, System.currentTimeMillis() - startTimeMillis); 53 } 54 55 @Override filter(Filter filter)56 public void filter(Filter filter) throws NoTestsRemainException { 57 if (mRunner instanceof Filterable) { 58 ((Filterable) mRunner).filter(filter); 59 } 60 } 61 } 62 63 /** 64 * Returns a suite of unit tests with each class runner wrapped by a 65 * GtestSuiteRunner. 66 */ 67 @Override getSuite(final RunnerBuilder builder, Class<?>[] classes)68 public Runner getSuite(final RunnerBuilder builder, Class<?>[] classes) 69 throws InitializationError { 70 return super.getSuite( 71 new RunnerBuilder() { 72 @Override 73 public Runner runnerForClass(Class<?> testClass) throws Throwable { 74 return new GtestSuiteRunner(builder.runnerForClass(testClass)); 75 } 76 }, classes); 77 } 78 79 } 80 81