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