1 /* 2 * Copyright (C) 2015 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 17 package com.android.support.car.apitest; 18 19 import android.util.Log; 20 21 import java.util.concurrent.Semaphore; 22 import java.util.concurrent.TimeUnit; 23 24 import junit.framework.Assert; 25 26 /** 27 * A generic test action, whose run method will be called with a parameter. 28 */ 29 public abstract class TestAction<T> { 30 /** for passing additional test specific parameters */ 31 public volatile Object arg0; 32 public volatile Object arg1; 33 private static final String TAG = "CAR.TEST"; 34 private Throwable mLastThrowable; 35 private Semaphore mWaitSemaphore = new Semaphore(0); 36 37 abstract public void run(T param); 38 39 public void doRun(T param) { 40 Log.i(TAG, "TestAction doRun " + this + " param:" + param); 41 try { 42 run(param); 43 } catch (Throwable t) { 44 Log.i(TAG, "TestAction doRun get exception", t); 45 mLastThrowable = t; 46 } 47 mWaitSemaphore.release(); 48 } 49 50 public void assertTestRun(long timeoutMs) throws Throwable { 51 if (!mWaitSemaphore.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS)) { 52 Assert.fail("timeout"); 53 } 54 if (mLastThrowable != null) { 55 throw mLastThrowable; 56 } 57 } 58 59 public void assertNotRun(long waitMs) throws Throwable { 60 if (!mWaitSemaphore.tryAcquire(waitMs, TimeUnit.MILLISECONDS)) { 61 return; 62 } 63 if (mLastThrowable != null) { 64 Log.e(TAG, "Action was run, but failed"); 65 throw mLastThrowable; 66 } 67 Assert.fail("Action was run"); 68 } 69 70 public boolean waitForTest(long timeoutMs) throws Throwable { 71 if (mWaitSemaphore.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS)) { 72 if (mLastThrowable != null) { 73 throw mLastThrowable; 74 } 75 return true; 76 } 77 return false; 78 } 79 80 public void resetRunState() { 81 mWaitSemaphore.drainPermits(); 82 } 83 84 public static <U> TestAction<U> buildEmptyAction() { 85 return new TestAction<U>() { 86 @Override 87 public void run(U param) { 88 } 89 }; 90 } 91 } 92