From 6675830090d228598a6304102075d6c0788caa17 Mon Sep 17 00:00:00 2001 From: Bartek Pacia Date: Thu, 28 Sep 2023 12:45:24 +0200 Subject: [PATCH] create CustomPatrolJUnitRunner --- .../patrol/CustomPatrolJUnitRunner.kt | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 packages/patrol/android/src/main/kotlin/pl/leancode/patrol/CustomPatrolJUnitRunner.kt diff --git a/packages/patrol/android/src/main/kotlin/pl/leancode/patrol/CustomPatrolJUnitRunner.kt b/packages/patrol/android/src/main/kotlin/pl/leancode/patrol/CustomPatrolJUnitRunner.kt new file mode 100644 index 000000000..94fa44674 --- /dev/null +++ b/packages/patrol/android/src/main/kotlin/pl/leancode/patrol/CustomPatrolJUnitRunner.kt @@ -0,0 +1,52 @@ +package pl.leancode.patrol + +import android.os.Build +import android.os.Bundle +import androidx.annotation.OptIn +import androidx.test.annotation.ExperimentalTestApi +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.services.storage.TestStorage +import org.junit.runner.* +import org.junit.runner.notification.* +import java.io.FileNotFoundException + +@OptIn(ExperimentalTestApi::class) +class CustomPatrolJUnitRunner : PatrolJUnitRunner() { + private var testStorage: TestStorage? = null + override fun onCreate(arguments: Bundle) { + super.onCreate(arguments) + testStorage = TestStorage() + try { + testStorage!!.openOutputFile("patrol_state/teardowns.txt") + } catch (e: FileNotFoundException) { + throw RuntimeException(e) + } + + val listeners = listOf( + arguments.getCharSequence("listener"), + PatrolStoragePermissionListener::class.java.name, + ).joinToString(separator = ",") + + arguments.putCharSequence("listener", listeners) + super.onCreate(arguments) + } +} + +class PatrolStoragePermissionListener : RunListener() { + @Throws(Exception::class) + override fun testRunStarted(description: Description) { + InstrumentationRegistry.getInstrumentation().uiAutomation.apply { + val testServicesPackage = "androidx.test.services" + when { + Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> { + executeShellCommand("appops set $testServicesPackage MANAGE_EXTERNAL_STORAGE allow") + } + + Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP -> { + executeShellCommand("pm grant $testServicesPackage android.permission.READ_EXTERNAL_STORAGE") + executeShellCommand("pm grant $testServicesPackage android.permission.WRITE_EXTERNAL_STORAGE") + } + } + } + } +}