7

My activity needs to request a new document from a document provider.

I want to test this in my espresso test by intenting an activity result with a uri. However, the returned uri does not have the correct permissions granted. At least I get a SecurityException: No persistable permission grants found for [user] and [uri] when I try to takePersistableUriPermission

The relevant code of my activity in onActivityResult:

val takeFlags = data.getFlags() and (Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
contentResolver.takePersistableUriPermission(it, takeFlags)

The relevant code for the espresso test

val file = File(InstrumentationRegistry.getTargetContext().filesDir, "abc.txt2)
val uri = Uri.parse("file://" + file.absoluteFile)
Intents.intending(hasAction(Intent.ACTION_CREATE_DOCUMENT))
            .respondWith(Instrumentation.ActivityResult(RESULT_OK, Intent().setData(uri)))
 <click on button to request document>

How to intenting an activity result with a uri that comes with granted permissions?

friedger
  • 645
  • 7
  • 21

2 Answers2

0

use

val uri = Uri.fromFile(file)

instead

val uri = Uri.parse("file://" + file.absoluteFile)

and dont forget provide permission

@get:Rule
var permissionRule: GrantPermissionRule = GrantPermissionRule.grant(
        android.Manifest.permission.READ_EXTERNAL_STORAGE
)

it works for my case

Alexandr Larin
  • 793
  • 7
  • 13
0

The following code works well for me

val intent = TestGeneralUtil.genIntentWithPersistedReadPermissionForFile(att)
intending(
    allOf(
        hasAction(Intent.ACTION_CHOOSER),
        hasExtra(`is`(Intent.EXTRA_INTENT),
            allOf(
                hasAction(Intent.ACTION_OPEN_DOCUMENT),
                hasType("*/*"),
                hasCategories(hasItem(equalTo(Intent.CATEGORY_OPENABLE)))
            )
        )
    )
).respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, intent))

And

/**
     * Generate an [Intent] with [Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION]
     * and [Intent.FLAG_GRANT_READ_URI_PERMISSION]
     */
    fun genIntentWithPersistedReadPermissionForFile(file: File): Intent {
      return Intent().apply {
        val context: Context = ApplicationProvider.getApplicationContext()
        val uri = FileProvider.getUriForFile(context, Constants.FILE_PROVIDER_AUTHORITY, file)
        context.grantUriPermission(
            BuildConfig.APPLICATION_ID,
            uri,
            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION)
        data = uri
        flags = Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION
      }
    }
Den
  • 23
  • 5