1 /* 2 * Copyright (C) 2017 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 package android.host.test.longevity.listener; 17 18 import org.junit.runner.Description; 19 import org.junit.runner.notification.RunNotifier; 20 21 import java.util.Map; 22 import java.util.concurrent.TimeUnit; 23 24 /** 25 * A {@link RunTerminator} for terminating early on test end due to long duration for host suites. 26 */ 27 public class TimeoutTerminator extends RunTerminator { 28 public static final String OPTION = "suite-timeout_msec"; 29 protected static final long DEFAULT = TimeUnit.MINUTES.toMillis(30L); 30 protected static final long UNSET_TIMESTAMP = -1; 31 32 protected long mStartTimestamp = UNSET_TIMESTAMP; 33 protected long mSuiteTimeout; // ms 34 TimeoutTerminator(RunNotifier notifier, Map<String, String> args)35 public TimeoutTerminator(RunNotifier notifier, Map<String, String> args) { 36 super(notifier); 37 mSuiteTimeout = args.containsKey(OPTION) ? Long.parseLong(args.get(OPTION)) : DEFAULT; 38 } 39 40 /** 41 * {@inheritDoc} 42 * 43 * <p>Note: this initializes the countdown timer if unset. 44 */ 45 @Override testRunStarted(Description description)46 public void testRunStarted(Description description) { 47 if (mStartTimestamp == UNSET_TIMESTAMP) { 48 mStartTimestamp = getCurrentTimestamp(); 49 } 50 } 51 52 /** {@inheritDoc} */ 53 @Override testFinished(Description description)54 public void testFinished(Description description) { 55 if (mStartTimestamp != UNSET_TIMESTAMP 56 && (getCurrentTimestamp() - mStartTimestamp) > mSuiteTimeout) { 57 kill("the suite timed out"); 58 } 59 } 60 61 /** Returns the total timeout set for the suite. */ getTotalSuiteTimeoutMs()62 public long getTotalSuiteTimeoutMs() { 63 return mSuiteTimeout; 64 } 65 66 /** 67 * Returns the current timestamp in ms for calculating time differences. 68 * <p> 69 * Note: this is exposed for the platform-specific {@code TimeoutTerminator}. 70 */ getCurrentTimestamp()71 protected long getCurrentTimestamp() { 72 return System.currentTimeMillis(); 73 } 74 } 75