1 /* 2 * Copyright (C) 2024 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.launcher3.util.rule; 18 19 import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; 20 21 import android.text.TextUtils; 22 23 import androidx.annotation.NonNull; 24 import androidx.test.uiautomator.UiDevice; 25 26 import org.junit.rules.TestRule; 27 import org.junit.runner.Description; 28 import org.junit.runners.model.Statement; 29 30 /** 31 * Test rule which executes a set prop command at the start of the test. 32 * This rule needs the property tag and property value so that value can be set to a tag. 33 */ 34 public class SetPropRule implements TestRule { 35 private static final String SETPROP_PREFIX = "setprop"; 36 private static final String GETPROP_PREFIX = "getprop"; 37 private static final String UNKNOWN = "UNKNOWN"; 38 @NonNull private final String mPropTag; 39 @NonNull private final String mPropValue; 40 SetPropRule(@onNull String propTag, @NonNull String propValue)41 public SetPropRule(@NonNull String propTag, @NonNull String propValue) { 42 mPropTag = propTag.trim(); 43 mPropValue = propValue.trim(); 44 } 45 46 @Override apply(Statement base, Description description)47 public Statement apply(Statement base, Description description) { 48 return new Statement() { 49 @Override 50 public void evaluate() throws Throwable { 51 String getpropCmd = GETPROP_PREFIX + " " + mPropTag; 52 String initialValue = UiDevice.getInstance(getInstrumentation()) 53 .executeShellCommand(getpropCmd); 54 if (TextUtils.isEmpty(initialValue.trim())) { 55 initialValue = UNKNOWN; 56 } 57 // setprop command always follows format : setprop <TAG> <value> 58 String revertSetPropCmd = SETPROP_PREFIX + " " + mPropTag + " " + initialValue; 59 String setPropCmd = SETPROP_PREFIX + " " + mPropTag + " " + mPropValue; 60 new ShellCommandRule(setPropCmd, revertSetPropCmd) 61 .apply(base, description).evaluate(); 62 } 63 }; 64 } 65 66 /** 67 * Enables "InputTransportPublisher" debug flag. This prints the key input events dispatched by 68 * the system server. 69 * adb shell setprop log.tag.InputTransportPublisher DEBUG 70 * See {@link com.android.cts.input.DebugInputRule} for more details. 71 */ 72 public static SetPropRule createEnableInputTransportPublisherRule() { 73 return new SetPropRule("log.tag.InputTransportPublisher", "DEBUG"); 74 } 75 } 76