Browse Source

GrantStoragePermissionRule: grant MANAGE_EXTERNAL_STORAGE on sdk >=30

Feels a bit hacky but it's the actual recommended way:
https://developer.android.com/training/data-storage/manage-all-files#enable-manage-external-storage-for-testing

Signed-off-by: Álvaro Brey Vilas <alvaro.brey@nextcloud.com>
Álvaro Brey Vilas 3 years ago
parent
commit
6a76372fde

+ 15 - 3
src/androidTest/java/com/nextcloud/client/GrantStoragePermissionRule.kt

@@ -22,9 +22,12 @@
 package com.nextcloud.client
 package com.nextcloud.client
 
 
 import android.os.Build
 import android.os.Build
+import androidx.test.platform.app.InstrumentationRegistry
 import androidx.test.rule.GrantPermissionRule
 import androidx.test.rule.GrantPermissionRule
 import com.owncloud.android.utils.PermissionUtil
 import com.owncloud.android.utils.PermissionUtil
 import org.junit.rules.TestRule
 import org.junit.rules.TestRule
+import org.junit.runner.Description
+import org.junit.runners.model.Statement
 
 
 class GrantStoragePermissionRule private constructor() {
 class GrantStoragePermissionRule private constructor() {
 
 
@@ -35,9 +38,18 @@ class GrantStoragePermissionRule private constructor() {
                 PermissionUtil
                 PermissionUtil
                     .getExternalStoragePermission()
                     .getExternalStoragePermission()
             )
             )
-            else -> {
-                // This rule does nothing. For now, MANAGE_EXTERNAL_STORAGE must be granted manually
-                TestRule { base, _ -> base }
+            else -> GrantManageExternalStoragePermissionRule()
+        }
+    }
+
+    private class GrantManageExternalStoragePermissionRule : TestRule {
+        override fun apply(base: Statement, description: Description): Statement = object : Statement() {
+            override fun evaluate() {
+                InstrumentationRegistry.getInstrumentation().uiAutomation.executeShellCommand(
+                    "appops set --uid ${InstrumentationRegistry.getInstrumentation().targetContext.packageName} " +
+                        "MANAGE_EXTERNAL_STORAGE allow"
+                )
+                base.evaluate()
             }
             }
         }
         }
     }
     }