1 /* 2 * Copyright (C) 2020 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.settings.testutils; 18 19 import android.os.ParcelFileDescriptor; 20 import android.text.TextUtils; 21 import android.util.Log; 22 23 import androidx.test.platform.app.InstrumentationRegistry; 24 25 import java.io.BufferedReader; 26 import java.io.InputStreamReader; 27 import java.nio.charset.StandardCharsets; 28 import java.util.Optional; 29 30 public class AdbUtils { checkStringInAdbCommandOutput(String logTag, String command, String prefix, String target, int timeoutInMillis)31 public static boolean checkStringInAdbCommandOutput(String logTag, String command, 32 String prefix, String target, int timeoutInMillis) throws Exception { 33 long start = System.nanoTime(); 34 //Sometimes the change do no reflect in adn output immediately, so need a wait and poll here 35 while (System.nanoTime() - start < (timeoutInMillis * 1000000)) { 36 try (ParcelFileDescriptor.AutoCloseInputStream in = 37 new ParcelFileDescriptor.AutoCloseInputStream( 38 InstrumentationRegistry.getInstrumentation() 39 .getUiAutomation() 40 .executeShellCommand(command))) { 41 try (BufferedReader br = 42 new BufferedReader( 43 new InputStreamReader(in, StandardCharsets.UTF_8))) { 44 Optional<String> resultOptional = br.lines().filter(line -> { 45 Log.d(logTag, line); 46 return TextUtils.isEmpty(prefix) || line.contains(prefix); 47 }).findFirst(); 48 String result = resultOptional.get(); 49 if (result.contains(target)) { 50 return true; 51 } else { 52 Thread.sleep(100); 53 } 54 } 55 } catch (Exception e) { 56 throw e; 57 } 58 } 59 60 return false; 61 } 62 } 63