1 /* 2 * Copyright (C) 2023 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.ui.testutils 18 19 import android.content.Context 20 import android.content.Intent 21 import android.view.KeyEvent 22 import androidx.test.core.app.ApplicationProvider 23 import androidx.test.uiautomator.By 24 import androidx.test.uiautomator.BySelector 25 import androidx.test.uiautomator.Direction 26 import androidx.test.uiautomator.UiDevice 27 import androidx.test.uiautomator.UiObject2 28 import androidx.test.uiautomator.Until 29 import com.google.common.truth.Truth.assertWithMessage 30 31 object SettingsTestUtils { 32 const val SETTINGS_PACKAGE = "com.android.settings" 33 const val TIMEOUT = 2000L 34 waitObjectnull35 fun UiDevice.waitObject(bySelector: BySelector): UiObject2? = 36 wait(Until.findObject(bySelector), TIMEOUT) 37 38 fun UiDevice.assertObject(bySelector: BySelector): UiObject2 = 39 checkNotNull(waitObject(bySelector)) { "$bySelector not found" } 40 clickObjectnull41 fun UiDevice.clickObject(bySelector: BySelector) = assertObject(bySelector).click() 42 43 fun UiDevice.startMainActivityFromHomeScreen(action: String) { 44 startMainActivityFromHomeScreen(Intent(action)) 45 } 46 startMainActivityFromHomeScreennull47 fun UiDevice.startMainActivityFromHomeScreen(intent: Intent) { 48 pressKeyCodes(intArrayOf(KeyEvent.KEYCODE_MENU, KeyEvent.KEYCODE_MENU)) // unlock 49 50 // Start from the home screen 51 pressHome() 52 53 // Wait for launcher 54 waitObject(By.pkg(launcherPackageName).depth(0)) 55 56 // Launch the app 57 ApplicationProvider.getApplicationContext<Context>().startActivity(Intent(intent).apply { 58 addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) 59 addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) 60 }) 61 62 // Wait for the app to appear 63 waitObject(By.pkg(SETTINGS_PACKAGE).depth(0)) 64 } 65 assertHasTextsnull66 fun UiDevice.assertHasTexts(texts: List<String>) { 67 val scrollableObj = 68 findObject(By.res(SETTINGS_PACKAGE, "main_content")) 69 ?: findObject(By.scrollable(true)) 70 for (text in texts) { 71 val selector = By.text(text) 72 assertWithMessage("Missing text: $text").that( 73 findObject(selector) 74 ?: scrollableObj.scrollUntil(Direction.DOWN, Until.findObject(selector)) 75 ?: waitObject(selector) 76 ).isNotNull() 77 } 78 } 79 } 80