summaryrefslogtreecommitdiff
path: root/tests/PhotoPicker/src/android/photopicker/cts/ActionUserSelectImagesForAppTest.java
blob: 9c5105bcbcc251b6a13a422955872b34a43554f1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
/*
 * Copyright (C) 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.photopicker.cts;

import static android.photopicker.cts.PhotoPickerCloudUtils.containsExcept;
import static android.photopicker.cts.PhotoPickerCloudUtils.disableCloudMediaAndClearAllowedCloudProviders;
import static android.photopicker.cts.PhotoPickerCloudUtils.enableCloudMediaAndSetAllowedCloudProviders;
import static android.photopicker.cts.PhotoPickerCloudUtils.extractMediaIds;
import static android.photopicker.cts.PhotoPickerCloudUtils.fetchPickerMedia;
import static android.photopicker.cts.PhotoPickerCloudUtils.getAllowedProvidersDeviceConfig;
import static android.photopicker.cts.PhotoPickerCloudUtils.initCloudProviderWithImage;
import static android.photopicker.cts.PhotoPickerCloudUtils.isCloudMediaEnabled;
import static android.photopicker.cts.PhotoPickerCloudUtils.selectAndAddPickerMedia;
import static android.photopicker.cts.PickerProviderMediaGenerator.getMediaGenerator;
import static android.photopicker.cts.util.PhotoPickerFilesUtils.createImagesAndGetUris;

import static com.android.compatibility.common.util.SystemUtil.runWithShellPermissionIdentity;

import static com.google.common.truth.Truth.assertThat;

import static org.junit.Assert.assertThrows;

import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Process;
import android.photopicker.cts.PickerProviderMediaGenerator.MediaGenerator;
import android.photopicker.cts.cloudproviders.CloudProviderPrimary;
import android.photopicker.cts.util.PhotoPickerFilesUtils;
import android.photopicker.cts.util.UiAssertionUtils;
import android.provider.MediaStore;
import android.util.Log;
import android.util.Pair;

import androidx.annotation.Nullable;
import androidx.test.filters.SdkSuppress;
import androidx.test.runner.AndroidJUnit4;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/** PhotoPicker tests for {@link MediaStore#ACTION_USER_SELECT_IMAGES_FOR_APP} intent. */
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE, codeName = "UpsideDownCake")
@RunWith(AndroidJUnit4.class)
public class ActionUserSelectImagesForAppTest extends PhotoPickerBaseTest {
    private static final String TAG = ActionUserSelectImagesForAppTest.class.getSimpleName();
    private static boolean sCloudMediaPreviouslyEnabled;
    @Nullable
    private static String sPreviouslyAllowedCloudProviders;
    @Nullable
    private static String sPreviouslySetCloudProvider;

    @BeforeClass
    public static void setUpClass() throws IOException {
        // Store the current Cloud-Media feature configs which we will override during the test,
        // and will need to restore after the test finished.
        sCloudMediaPreviouslyEnabled = isCloudMediaEnabled();
        if (sCloudMediaPreviouslyEnabled) {
            sPreviouslyAllowedCloudProviders = getAllowedProvidersDeviceConfig();
        }

        try {
            sPreviouslySetCloudProvider = getCurrentCloudProvider();
        } catch (RuntimeException e) {
            Log.e(TAG, "Could not get previously set cloud provider", e);
            sPreviouslySetCloudProvider = INVALID_CLOUD_PROVIDER;
        }

        // Override the allowed cloud providers config to enable the banners
        // (this is a self-instrumenting test, so "target" package name and "own" package name are
        // same: android.photopicker.cts).
        enableCloudMediaAndSetAllowedCloudProviders(sTargetPackageName);

    }

    @AfterClass
    public static void tearDownClass() throws Exception {
        // Restore Cloud-Media feature configs.
        if (sCloudMediaPreviouslyEnabled) {
            enableCloudMediaAndSetAllowedCloudProviders(sPreviouslyAllowedCloudProviders);
        } else {
            disableCloudMediaAndClearAllowedCloudProviders();
        }
        setCloudProvider(sPreviouslySetCloudProvider);
    }

    @After
    public void tearDown() throws Exception {
        if (mActivity != null) {
            mActivity.finish();
        }
    }

    private static Intent getUserSelectImagesIntent() {
        final Intent intent = new Intent(MediaStore.ACTION_USER_SELECT_IMAGES_FOR_APP);
        intent.putExtra(Intent.EXTRA_UID, Process.myUid());
        return intent;
    }

    private static Intent getUserSelectImagesIntent(String mimeType) {
        Intent intent = getUserSelectImagesIntent();
        intent.setType(mimeType);
        return intent;
    }

    @Test
    public void testInvalidMimeTypeFilter() throws Exception {
        runWithShellPermissionIdentity(
                () -> {
                    Intent intent = getUserSelectImagesIntent("audio/*");
                    assertThrows(
                            ActivityNotFoundException.class,
                            () -> mActivity.startActivityForResult(intent, REQUEST_CODE));
                },
                Manifest.permission.GRANT_RUNTIME_PERMISSIONS);
    }

    @Test
    public void testActivityCancelledWithMissingAppUid() throws Exception {
        runWithShellPermissionIdentity(
                () -> {
                    final Intent intent = new Intent(MediaStore.ACTION_USER_SELECT_IMAGES_FOR_APP);
                    mActivity.startActivityForResult(intent, REQUEST_CODE);
                    final GetResultActivity.Result res = mActivity.getResult();
                    assertThat(res.resultCode).isEqualTo(Activity.RESULT_CANCELED);
                },
                Manifest.permission.GRANT_RUNTIME_PERMISSIONS);
    }

    @Test
    public void testCannotStartActivityWithoutGrantRuntimePermissions() throws Exception {
        assertThrows(
                SecurityException.class,
                () -> mActivity.startActivityForResult(getUserSelectImagesIntent(), REQUEST_CODE));
    }

    @Test
    public void testUserSelectImagesForAppHandledByPhotopicker() throws Exception {
        launchActivityForResult(getUserSelectImagesIntent());
        UiAssertionUtils.assertThatShowsPickerUi();
    }

    @Test
    public void testPhotosMimeTypeFilter() throws Exception {
        Intent intent = getUserSelectImagesIntent("image/*");
        launchActivityForResult(intent);
        UiAssertionUtils.assertThatShowsPickerUi();
    }

    @Test
    public void testVideosMimeTypeFilter() throws Exception {
        Intent intent = getUserSelectImagesIntent("video/*");
        launchActivityForResult(intent);
        UiAssertionUtils.assertThatShowsPickerUi();
    }

    @Test
    public void testNoCloudContent() throws Exception {
        final List<Uri> uriList = new ArrayList<>();
        final String cloudId = "cloud_id1";

        try {
            uriList.addAll(createImagesAndGetUris(1, mContext.getUserId()));
            final long localId = Long.parseLong(uriList.get(0).getLastPathSegment());
            setupCloudProviderWithImage(cloudId);

            // 1. Verify we can see cloud item in Photo Picker
            final Intent photoPickerIntent = new Intent(MediaStore.ACTION_PICK_IMAGES);
            photoPickerIntent.putExtra(MediaStore.EXTRA_PICK_IMAGES_MAX,
                    MediaStore.getPickImagesMaxLimit());
            launchActivityForResult(photoPickerIntent);
            final ClipData clipData = fetchPickerMedia(mActivity, sDevice, 1);
            // Verify that selected item is a cloud item
            containsExcept(extractMediaIds(clipData, 1), cloudId, String.valueOf(localId));

            // 2. Verify we can't see cloud item in Picker choice.
            launchActivityForResult(getUserSelectImagesIntent());
            selectAndAddPickerMedia(sDevice, 1);

            // Query the media_grants to verify that the grant was on local id.
            // Please note that READ_MEDIA_VISUAL_USER_SELECTED is granted by declaring it in
            // AndroidManifest of this test. Launching ActionUserSelectForApp activity directly
            // doesn't grant any manifest permissions.
            try (Cursor c = mContext.getContentResolver().query(
                    MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL),
                    new String[]{MediaStore.MediaColumns._ID}, null, null)) {
                assertThat(c.getCount()).isEqualTo(1);
                assertThat(c.moveToFirst()).isTrue();
                // Verify that the access is given on an id that is not cloud_id
                assertThat(c.getLong(c.getColumnIndexOrThrow(MediaStore.MediaColumns._ID)))
                        .isNotEqualTo(cloudId);
                // verify that the access was given on local id.
                assertThat(c.getLong(c.getColumnIndexOrThrow(MediaStore.MediaColumns._ID)))
                        .isEqualTo(localId);
            }
        } finally {
            for (Uri uri : uriList) {
                PhotoPickerFilesUtils.deleteMedia(uri, mContext);
            }
            uriList.clear();
            setCloudProvider(null);
        }
    }

    private void setupCloudProviderWithImage(String cloudId) throws Exception {
        MediaGenerator cloudPrimaryMediaGenerator = getMediaGenerator(
                mContext, CloudProviderPrimary.AUTHORITY);
        cloudPrimaryMediaGenerator.resetAll();
        cloudPrimaryMediaGenerator.setMediaCollectionId("collection_1");
        initCloudProviderWithImage(mContext, cloudPrimaryMediaGenerator,
                CloudProviderPrimary.AUTHORITY, Pair.create(null, cloudId));
    }

    private void launchActivityForResult(Intent intent) throws Exception {
        runWithShellPermissionIdentity(
                () -> mActivity.startActivityForResult(intent, REQUEST_CODE),
                Manifest.permission.GRANT_RUNTIME_PERMISSIONS);
    }
}