63 lines · 2.4 KB · KotlinRaw
package com.cottondb.android.platformimport android.Manifestimport android.content.Intentimport android.content.pm.PackageManagerimport androidx.test.ext.junit.runners.AndroidJUnit4import androidx.test.platform.app.InstrumentationRegistryimport kotlinx.coroutines.Deferredimport kotlinx.coroutines.delayimport kotlinx.coroutines.runBlockingimport kotlinx.coroutines.withTimeoutimport org.junit.Afterimport org.junit.Assert.assertFalseimport org.junit.Assume.assumeTrueimport org.junit.Testimport org.junit.runner.RunWith/** Exercises the platform Activity Result registry, not a fake permission callback. */@RunWith(AndroidJUnit4::class)class PermissionHarnessActivityTest { private val instrumentation = InstrumentationRegistry.getInstrumentation() private val context = instrumentation.targetContext private var activity: PermissionHarnessActivity? = null @After fun finishHarness() { instrumentation.runOnMainSync { activity?.finish() } } @Test fun deniedMicrophoneRequestLaunchesAndCompletesThroughTheRealActivityResultRegistry() = runBlocking { assumeTrue( "This test needs RECORD_AUDIO denied so Android presents the real request path.", context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED, ) val harness = startHarness() lateinit var pending: Deferred<Boolean> instrumentation.runOnMainSync { pending = harness.requestMicrophone() } // Give Android a chance to show the native sheet before dismissing it. It is harmless if // this image has already recorded a permanent denial and the contract returned instead. delay(PROMPT_SETTLE_MS) instrumentation.uiAutomation.executeShellCommand("input keyevent KEYCODE_BACK").close() val granted = withTimeout(PROMPT_TIMEOUT_MS) { pending.await() } assertFalse(granted) Unit } private fun startHarness(): PermissionHarnessActivity { activity?.let { return it } val started = instrumentation.startActivitySync( Intent(context, PermissionHarnessActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), ) check(started is PermissionHarnessActivity) { "Unexpected test activity: $started" } return started.also { activity = it } } private companion object { const val PROMPT_SETTLE_MS = 250L const val PROMPT_TIMEOUT_MS = 10_000L }}