1 /* 2 * Copyright (C) 2018 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.platform.test.rule; 17 18 import android.os.Bundle; 19 import android.support.test.uiautomator.UiDevice; 20 import android.util.Log; 21 import androidx.test.InstrumentationRegistry; 22 23 import java.io.IOException; 24 25 /** 26 * A base {@link org.junit.rules.TestWatcher} with common support for platform testing. 27 */ 28 public class TestWatcher extends org.junit.rules.TestWatcher { 29 private static final String LOG_TAG = TestWatcher.class.getSimpleName(); 30 31 private UiDevice mDevice; 32 33 /** 34 * Returns the active {@link UiDevice} to interact with. 35 * 36 * <p>Override this for unit testing device calls. 37 */ getUiDevice()38 protected UiDevice getUiDevice() { 39 if (mDevice == null) { 40 mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); 41 } 42 return mDevice; 43 } 44 45 /** 46 * Runs a shell command, {@code cmd}, and returns the output. 47 * 48 * <p>Override this for unit testing shell commands. 49 */ executeShellCommand(String cmd)50 protected String executeShellCommand(String cmd) { 51 try { 52 Log.v(LOG_TAG, String.format("Executing command from %s: %s", this.getClass(), cmd)); 53 return getUiDevice().executeShellCommand(cmd); 54 } catch (IOException e) { 55 throw new RuntimeException(e); 56 } 57 } 58 59 /** 60 * Returns the {@link Bundle} containing registered arguments. 61 * 62 * <p>Override this for unit testing device calls. 63 */ getArguments()64 protected Bundle getArguments() { 65 return InstrumentationRegistry.getArguments(); 66 } 67 } 68