summaryrefslogtreecommitdiff
path: root/tests/tests/permission3/src/android/permission3/cts/BaseUsePermissionTest.kt
blob: bea7a1629c1aceda3045ea5ebe337822b133ccab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.permission3.cts

import android.app.Activity
import android.app.Instrumentation
import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.support.test.uiautomator.By
import android.support.test.uiautomator.BySelector
import android.support.test.uiautomator.UiScrollable
import android.support.test.uiautomator.UiSelector
import android.text.Spanned
import android.text.style.ClickableSpan
import android.view.View
import com.android.compatibility.common.util.SystemUtil.eventually
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Before
import java.util.concurrent.TimeUnit
import java.util.regex.Pattern

abstract class BaseUsePermissionTest : BasePermissionTest() {
    companion object {
        const val APP_APK_PATH_22 = "$APK_DIRECTORY/CtsUsePermissionApp22.apk"
        const val APP_APK_PATH_22_CALENDAR_ONLY =
            "$APK_DIRECTORY/CtsUsePermissionApp22CalendarOnly.apk"
        const val APP_APK_PATH_23 = "$APK_DIRECTORY/CtsUsePermissionApp23.apk"
        const val APP_APK_PATH_25 = "$APK_DIRECTORY/CtsUsePermissionApp25.apk"
        const val APP_APK_PATH_26 = "$APK_DIRECTORY/CtsUsePermissionApp26.apk"
        const val APP_APK_PATH_28 = "$APK_DIRECTORY/CtsUsePermissionApp28.apk"
        const val APP_APK_PATH_29 = "$APK_DIRECTORY/CtsUsePermissionApp29.apk"
        const val APP_APK_PATH_LATEST = "$APK_DIRECTORY/CtsUsePermissionAppLatest.apk"
        const val APP_APK_PATH_LATEST_WITH_BACKGROUND =
                "$APK_DIRECTORY/CtsUsePermissionAppLatestWithBackground.apk"
        const val APP_APK_PATH_WITH_OVERLAY = "$APK_DIRECTORY/CtsUsePermissionAppWithOverlay.apk"
        const val APP_PACKAGE_NAME = "android.permission3.cts.usepermission"

        const val ALLOW_BUTTON =
                "com.android.permissioncontroller:id/permission_allow_button"
        const val ALLOW_FOREGROUND_BUTTON =
                "com.android.permissioncontroller:id/permission_allow_foreground_only_button"
        const val DENY_BUTTON = "com.android.permissioncontroller:id/permission_deny_button"
        const val DENY_AND_DONT_ASK_AGAIN_BUTTON =
                "com.android.permissioncontroller:id/permission_deny_and_dont_ask_again_button"
        const val NO_UPGRADE_BUTTON =
                "com.android.permissioncontroller:id/permission_no_upgrade_button"
        const val NO_UPGRADE_AND_DONT_ASK_AGAIN_BUTTON =
                "com.android.permissioncontroller:" +
                        "id/permission_no_upgrade_and_dont_ask_again_button"

        const val ALLOW_BUTTON_TEXT = "grant_dialog_button_allow"
        const val ALLOW_FOREGROUND_BUTTON_TEXT = "grant_dialog_button_allow_foreground"
        const val DENY_BUTTON_TEXT = "grant_dialog_button_deny"
        const val DENY_AND_DONT_ASK_AGAIN_BUTTON_TEXT =
                "grant_dialog_button_deny_and_dont_ask_again"
        const val NO_UPGRADE_AND_DONT_ASK_AGAIN_BUTTON_TEXT = "grant_dialog_button_no_upgrade"
    }

    enum class PermissionState {
        ALLOWED,
        DENIED,
        DENIED_WITH_PREJUDICE
    }

    protected val isTv = packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
    protected val isWatch = packageManager.hasSystemFeature(PackageManager.FEATURE_WATCH)
    protected val isAutomotive = packageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)

    private val platformResources = context.createPackageContext("android", 0).resources
    private val permissionToLabelResNameMap =
        if (!packageManager.arePermissionsIndividuallyControlled()) {
            mapOf(
                // Contacts
                android.Manifest.permission.READ_CONTACTS
                    to "@android:string/permgrouplab_contacts",
                android.Manifest.permission.WRITE_CONTACTS
                    to "@android:string/permgrouplab_contacts",
                // Calendar
                android.Manifest.permission.READ_CALENDAR
                    to "@android:string/permgrouplab_calendar",
                android.Manifest.permission.WRITE_CALENDAR
                    to "@android:string/permgrouplab_calendar",
                // SMS
                android.Manifest.permission.SEND_SMS to "@android:string/permgrouplab_sms",
                android.Manifest.permission.RECEIVE_SMS to "@android:string/permgrouplab_sms",
                android.Manifest.permission.READ_SMS to "@android:string/permgrouplab_sms",
                android.Manifest.permission.RECEIVE_WAP_PUSH to "@android:string/permgrouplab_sms",
                android.Manifest.permission.RECEIVE_MMS to "@android:string/permgrouplab_sms",
                "android.permission.READ_CELL_BROADCASTS" to "@android:string/permgrouplab_sms",
                // Storage
                android.Manifest.permission.READ_EXTERNAL_STORAGE
                    to "@android:string/permgrouplab_storage",
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE
                    to "@android:string/permgrouplab_storage",
                // Location
                android.Manifest.permission.ACCESS_FINE_LOCATION
                    to "@android:string/permgrouplab_location",
                android.Manifest.permission.ACCESS_COARSE_LOCATION
                    to "@android:string/permgrouplab_location",
                // Phone
                android.Manifest.permission.READ_PHONE_STATE
                    to "@android:string/permgrouplab_phone",
                android.Manifest.permission.CALL_PHONE to "@android:string/permgrouplab_phone",
                "android.permission.ACCESS_IMS_CALL_SERVICE"
                    to "@android:string/permgrouplab_phone",
                android.Manifest.permission.READ_CALL_LOG to "@android:string/permgrouplab_phone",
                android.Manifest.permission.WRITE_CALL_LOG to "@android:string/permgrouplab_phone",
                android.Manifest.permission.ADD_VOICEMAIL to "@android:string/permgrouplab_phone",
                android.Manifest.permission.USE_SIP to "@android:string/permgrouplab_phone",
                android.Manifest.permission.PROCESS_OUTGOING_CALLS
                    to "@android:string/permgrouplab_phone",
                // Microphone
                android.Manifest.permission.RECORD_AUDIO
                    to "@android:string/permgrouplab_microphone",
                // Camera
                android.Manifest.permission.CAMERA to "@android:string/permgrouplab_camera",
                // Body sensors
                android.Manifest.permission.BODY_SENSORS to "@android:string/permgrouplab_sensors"
            )
        } else {
            mapOf(
                // Contacts
                android.Manifest.permission.READ_CONTACTS to "@android:string/permlab_readContacts",
                android.Manifest.permission.WRITE_CONTACTS
                    to "@android:string/permlab_writeContacts",
                // Calendar
                android.Manifest.permission.READ_CALENDAR
                    to "@android:string/permgrouplab_calendar",
                android.Manifest.permission.WRITE_CALENDAR
                    to "@android:string/permgrouplab_calendar",
                // SMS
                android.Manifest.permission.SEND_SMS to "@android:string/permlab_sendSms",
                android.Manifest.permission.RECEIVE_SMS to "@android:string/permlab_receiveSms",
                android.Manifest.permission.READ_SMS to "@android:string/permlab_readSms",
                android.Manifest.permission.RECEIVE_WAP_PUSH
                    to "@android:string/permlab_receiveWapPush",
                android.Manifest.permission.RECEIVE_MMS to "@android:string/permlab_receiveMms",
                "android.permission.READ_CELL_BROADCASTS"
                    to "@android:string/permlab_readCellBroadcasts",
                // Storage
                android.Manifest.permission.READ_EXTERNAL_STORAGE
                    to "@android:string/permgrouplab_storage",
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE
                    to "@android:string/permgrouplab_storage",
                // Location
                android.Manifest.permission.ACCESS_FINE_LOCATION
                    to "@android:string/permgrouplab_location",
                android.Manifest.permission.ACCESS_COARSE_LOCATION
                    to "@android:string/permgrouplab_location",
                // Phone
                android.Manifest.permission.READ_PHONE_STATE
                    to "@android:string/permlab_readPhoneState",
                android.Manifest.permission.CALL_PHONE to "@android:string/permlab_callPhone",
                "android.permission.ACCESS_IMS_CALL_SERVICE"
                    to "@android:string/permlab_accessImsCallService",
                android.Manifest.permission.READ_CALL_LOG to "@android:string/permlab_readCallLog",
                android.Manifest.permission.WRITE_CALL_LOG
                    to "@android:string/permlab_writeCallLog",
                android.Manifest.permission.ADD_VOICEMAIL to "@android:string/permlab_addVoicemail",
                android.Manifest.permission.USE_SIP to "@android:string/permlab_use_sip",
                android.Manifest.permission.PROCESS_OUTGOING_CALLS
                    to "@android:string/permlab_processOutgoingCalls",
                // Microphone
                android.Manifest.permission.RECORD_AUDIO
                    to "@android:string/permgrouplab_microphone",
                // Camera
                android.Manifest.permission.CAMERA to "@android:string/permgrouplab_camera",
                // Body sensors
                android.Manifest.permission.BODY_SENSORS to "@android:string/permgrouplab_sensors"
            )
        }

    @Before
    @After
    fun uninstallApp() {
        uninstallPackage(APP_PACKAGE_NAME, requireSuccess = false)
    }

    protected fun clearTargetSdkWarning() =
        click(By.res("android:id/button1"))

    protected fun clickPermissionReviewContinue() {
        if (isAutomotive) {
            click(By.text(getPermissionControllerString("review_button_continue")))
        } else {
            click(By.res("com.android.permissioncontroller:id/continue_button"))
        }
    }

    protected fun clickPermissionReviewCancel() {
        if (isAutomotive) {
            click(By.text(getPermissionControllerString("review_button_cancel")))
        } else {
            click(By.res("com.android.permissioncontroller:id/cancel_button"))
        }
    }

    protected fun approvePermissionReview() {
        startAppActivityAndAssertResultCode(Activity.RESULT_OK) {
            clickPermissionReviewContinue()
        }
    }

    protected fun cancelPermissionReview() {
        startAppActivityAndAssertResultCode(Activity.RESULT_CANCELED) {
            clickPermissionReviewCancel()
        }
    }

    protected fun assertAppDoesNotNeedPermissionReview() {
        startAppActivityAndAssertResultCode(Activity.RESULT_OK) {}
    }

    protected inline fun startAppActivityAndAssertResultCode(
        expectedResultCode: Int,
        block: () -> Unit
    ) {
        val future = startActivityForFuture(
            Intent().apply {
                component = ComponentName(
                    APP_PACKAGE_NAME, "$APP_PACKAGE_NAME.FinishOnCreateActivity"
                )
            }
        )
        block()
        assertEquals(
            expectedResultCode, future.get(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS).resultCode
        )
    }

    protected inline fun requestAppPermissionsForNoResult(
        vararg permissions: String?,
        block: () -> Unit
    ) {
        // Request the permissions
        context.startActivity(
                Intent().apply {
                    component = ComponentName(
                            APP_PACKAGE_NAME, "$APP_PACKAGE_NAME.RequestPermissionsActivity"
                    )
                    putExtra("$APP_PACKAGE_NAME.PERMISSIONS", permissions)
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                }
        )
        waitForIdle()
        // Perform the post-request action
        block()
    }

    protected inline fun requestAppPermissions(
        vararg permissions: String?,
        block: () -> Unit
    ): Instrumentation.ActivityResult {
        // Request the permissions
        val future = startActivityForFuture(
            Intent().apply {
                component = ComponentName(
                    APP_PACKAGE_NAME, "$APP_PACKAGE_NAME.RequestPermissionsActivity"
                )
                putExtra("$APP_PACKAGE_NAME.PERMISSIONS", permissions)
            }
        )
        waitForIdle()
        // Perform the post-request action
        block()
        return future.get(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
    }

    protected inline fun requestAppPermissionsAndAssertResult(
        permissions: Array<out String?>,
        permissionAndExpectedGrantResults: Array<out Pair<String?, Boolean>>,
        block: () -> Unit
    ) {
        val result = requestAppPermissions(*permissions, block = block)
        assertEquals(Activity.RESULT_OK, result.resultCode)
        assertEquals(
            permissionAndExpectedGrantResults.toList(),
            result.resultData!!.getStringArrayExtra("$APP_PACKAGE_NAME.PERMISSIONS")!!
                .zip(
                    result.resultData!!.getIntArrayExtra("$APP_PACKAGE_NAME.GRANT_RESULTS")!!
                        .map { it == PackageManager.PERMISSION_GRANTED }
                )
        )
        permissionAndExpectedGrantResults.forEach {
            it.first?.let { permission ->
                assertAppHasPermission(permission, it.second)
            }
        }
    }

    protected inline fun requestAppPermissionsAndAssertResult(
        vararg permissionAndExpectedGrantResults: Pair<String?, Boolean>,
        block: () -> Unit
    ) = requestAppPermissionsAndAssertResult(
        permissionAndExpectedGrantResults.map { it.first }.toTypedArray(),
        permissionAndExpectedGrantResults,
        block
    )

    protected fun clickPermissionRequestAllowButton() {
        if (isAutomotive) {
            click(By.text(getPermissionControllerString(ALLOW_BUTTON_TEXT)))
        } else {
            click(By.res(ALLOW_BUTTON))
        }
    }

    protected fun clickPermissionRequestSettingsLinkAndAllowAlways() {
        clickPermissionRequestSettingsLink()
        eventually({
            clickAllowAlwaysInSettings()
        }, TIMEOUT_MILLIS * 2)
        pressBack()
    }

    protected fun clickAllowAlwaysInSettings() {
        if (isAutomotive || isTv) {
            click(By.text(getPermissionControllerString("app_permission_button_allow_always")))
        } else {
            click(By.res("com.android.permissioncontroller:id/allow_always_radio_button"))
        }
    }

    protected fun clickPermissionRequestAllowForegroundButton(timeoutMillis: Long = 10_000) {
        if (isAutomotive) {
            click(By.text(
                    getPermissionControllerString(ALLOW_FOREGROUND_BUTTON_TEXT)), timeoutMillis)
        } else {
            click(By.res(ALLOW_FOREGROUND_BUTTON), timeoutMillis)
        }
    }

    protected fun clickPermissionRequestDenyButton() {
        if (isAutomotive) {
            click(By.text(getPermissionControllerString(DENY_BUTTON_TEXT)))
        } else {
            click(By.res(DENY_BUTTON))
        }
    }

    protected fun clickPermissionRequestSettingsLinkAndDeny() {
        clickPermissionRequestSettingsLink()
        if (isAutomotive) {
            click(By.text(getPermissionControllerString("app_permission_button_deny")))
        } else {
            click(By.res("com.android.permissioncontroller:id/deny_radio_button"))
        }
        waitForIdle()
        pressBack()
    }

    protected fun clickPermissionRequestSettingsLink() {
        waitForIdle()
        eventually {
            // UiObject2 doesn't expose CharSequence.
            val node = if (isAutomotive) {
                uiAutomation.rootInActiveWindow.findAccessibilityNodeInfosByText(
                        "Allow in settings."
                )[0]
            } else {
                uiAutomation.rootInActiveWindow.findAccessibilityNodeInfosByViewId(
                        "com.android.permissioncontroller:id/detail_message"
                )[0]
            }
            assertTrue(node.isVisibleToUser)
            val text = node.text as Spanned
            val clickableSpan = text.getSpans(0, text.length, ClickableSpan::class.java)[0]
            // We could pass in null here in Java, but we need an instance in Kotlin.
            clickableSpan.onClick(View(context))
        }
        waitForIdle()
    }

    protected fun clickPermissionRequestDenyAndDontAskAgainButton() {
        if (isAutomotive) {
            click(By.text(getPermissionControllerString(DENY_AND_DONT_ASK_AGAIN_BUTTON_TEXT)))
        } else {
            click(By.res(DENY_AND_DONT_ASK_AGAIN_BUTTON))
        }
    }

    // Only used in TV and Watch form factors
    protected fun clickPermissionRequestDontAskAgainButton() =
        click(By.res("com.android.permissioncontroller:id/permission_deny_dont_ask_again_button"))

    protected fun clickPermissionRequestNoUpgradeAndDontAskAgainButton() {
        if (isAutomotive) {
            click(By.text(getPermissionControllerString(NO_UPGRADE_AND_DONT_ASK_AGAIN_BUTTON_TEXT)))
        } else {
            click(By.res(NO_UPGRADE_AND_DONT_ASK_AGAIN_BUTTON))
        }
    }

    protected fun grantAppPermissions(vararg permissions: String, targetSdk: Int = 30) {
        setAppPermissionState(*permissions, state = PermissionState.ALLOWED, isLegacyApp = false,
                targetSdk = targetSdk)
    }

    protected fun revokeAppPermissions(
        vararg permissions: String,
        isLegacyApp: Boolean = false,
        targetSdk: Int = 30
    ) {
        setAppPermissionState(*permissions, state = PermissionState.DENIED,
                isLegacyApp = isLegacyApp, targetSdk = targetSdk)
    }

    private fun setAppPermissionState(
        vararg permissions: String,
        state: PermissionState,
        isLegacyApp: Boolean,
        targetSdk: Int
    ) {
        pressBack()
        pressBack()
        pressBack()
        if (isTv) {
            pressHome()
        }

        // Try multiple times as the AppInfo page might have read stale data
        eventually({
            try {
                // Open the app details settings
                context.startActivity(
                        Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                            data = Uri.fromParts("package", APP_PACKAGE_NAME, null)
                            addCategory(Intent.CATEGORY_DEFAULT)
                            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                            addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
                        }
                )
                // Open the permissions UI
                click(byTextRes(R.string.permissions).enabled(true))
            } catch (e: Exception) {
                pressBack()
                throw e
            }
        }, TIMEOUT_MILLIS)

        for (permission in permissions) {
            // Find the permission screen
            val permissionLabel = getPermissionLabel(permission)
            click(By.text(permissionLabel))
            val wasGranted = if (isAutomotive) {
                // Automotive doesn't support one time permissions, and thus
                // won't show an "Ask every time" message
                !waitFindObject(byTextRes(R.string.deny)).isChecked
            } else {
                !(waitFindObject(byTextRes(R.string.deny)).isChecked ||
                    (!isLegacyApp && hasAskButton(permission) &&
                        waitFindObject(byTextRes(R.string.ask)).isChecked))
            }
            var alreadyChecked = false
            val button = waitFindObject(
                byTextRes(
                    if (isAutomotive) {
                        // Automotive doesn't support one time permissions, and thus
                        // won't show an "Ask every time" message
                        when (state) {
                            PermissionState.ALLOWED -> R.string.allow
                            PermissionState.DENIED -> R.string.deny
                            PermissionState.DENIED_WITH_PREJUDICE -> R.string.deny
                        }
                    } else {
                        when (state) {
                            PermissionState.ALLOWED ->
                                if (showsForegroundOnlyButton(permission)) {
                                    R.string.allow_foreground
                                } else if (isMediaStorageButton(permission, targetSdk)) {
                                    R.string.allow_media_storage
                                } else if (isAllStorageButton(permission, targetSdk)) {
                                    R.string.allow_external_storage
                                } else {
                                    R.string.allow
                                }
                            PermissionState.DENIED ->
                                if (!isLegacyApp && hasAskButton(permission)) {
                                    R.string.ask
                                } else {
                                    R.string.deny
                                }
                            PermissionState.DENIED_WITH_PREJUDICE -> R.string.deny
                        }
                    }
                )
            )
            alreadyChecked = button.isChecked
            if (!alreadyChecked) {
                button.click()
            }
            if (!alreadyChecked && isLegacyApp && wasGranted) {
                scrollToBottom()
                val resources = context.createPackageContext(
                    packageManager.permissionControllerPackageName, 0
                ).resources
                val confirmTextRes = resources.getIdentifier(
                    "com.android.permissioncontroller:string/grant_dialog_button_deny_anyway", null,
                    null
                )
                val confirmText = resources.getString(confirmTextRes)
                click(byTextStartsWithCaseInsensitive(confirmText))
            }
            pressBack()
        }
        pressBack()
        pressBack()
    }

    private fun getPermissionLabel(permission: String): String {
        val labelResName = permissionToLabelResNameMap[permission]
        assertNotNull("Unknown permission $permission", labelResName)
        val labelRes = platformResources.getIdentifier(labelResName, null, null)
        return platformResources.getString(labelRes)
    }

    private fun hasAskButton(permission: String): Boolean =
        when (permission) {
            android.Manifest.permission.CAMERA,
            android.Manifest.permission.RECORD_AUDIO,
            android.Manifest.permission.ACCESS_FINE_LOCATION,
            android.Manifest.permission.ACCESS_COARSE_LOCATION,
            android.Manifest.permission.ACCESS_BACKGROUND_LOCATION -> true
            else -> false
        }

    private fun showsForegroundOnlyButton(permission: String): Boolean =
        when (permission) {
            android.Manifest.permission.CAMERA,
            android.Manifest.permission.RECORD_AUDIO -> true
            else -> false
        }

    private fun isMediaStorageButton(permission: String, targetSdk: Int): Boolean =
            if (isTv) {
                false
            } else {
                when (permission) {
                    android.Manifest.permission.READ_EXTERNAL_STORAGE,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    android.Manifest.permission.ACCESS_MEDIA_LOCATION ->
                        // Default behavior, can cause issues if OPSTR_LEGACY_STORAGE is set
                        targetSdk >= Build.VERSION_CODES.P
                    else -> false
                }
            }

    private fun isAllStorageButton(permission: String, targetSdk: Int): Boolean =
            if (isTv) {
                false
            } else {
                when (permission) {
                    android.Manifest.permission.READ_EXTERNAL_STORAGE,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    android.Manifest.permission.ACCESS_MEDIA_LOCATION ->
                        // Default behavior, can cause issues if OPSTR_LEGACY_STORAGE is set
                        targetSdk < Build.VERSION_CODES.P
                    android.Manifest.permission.MANAGE_EXTERNAL_STORAGE -> true
                    else -> false
                }
            }

    private fun scrollToBottom() {
        val scrollable = UiScrollable(UiSelector().scrollable(true)).apply {
            swipeDeadZonePercentage = 0.25
        }
        waitForIdle()
        if (scrollable.exists()) {
            scrollable.flingToEnd(10)
        }
    }

    private fun byTextRes(textRes: Int): BySelector = By.text(context.getString(textRes))

    private fun byTextStartsWithCaseInsensitive(prefix: String): BySelector =
        By.text(Pattern.compile("(?i)^${Pattern.quote(prefix)}.*$"))

    protected fun assertAppHasPermission(permissionName: String, expectPermission: Boolean) {
        assertEquals(
            if (expectPermission) {
                PackageManager.PERMISSION_GRANTED
            } else {
                PackageManager.PERMISSION_DENIED
            },
            packageManager.checkPermission(permissionName, APP_PACKAGE_NAME)
        )
    }

    protected fun assertAppHasCalendarAccess(expectAccess: Boolean) {
        val future = startActivityForFuture(
            Intent().apply {
                component = ComponentName(
                    APP_PACKAGE_NAME, "$APP_PACKAGE_NAME.CheckCalendarAccessActivity"
                )
            }
        )
        val result = future.get(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
        assertEquals(Activity.RESULT_OK, result.resultCode)
        assertTrue(result.resultData!!.hasExtra("$APP_PACKAGE_NAME.HAS_ACCESS"))
        assertEquals(
            expectAccess,
            result.resultData!!.getBooleanExtra("$APP_PACKAGE_NAME.HAS_ACCESS", false)
        )
    }
}