package com.cottondb.android.platform import android.Manifest import android.content.Intent import android.content.pm.PackageManager import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import kotlinx.coroutines.Deferred import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout import org.junit.After import org.junit.Assert.assertFalse import org.junit.Assume.assumeTrue import org.junit.Test import 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 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 } }