blob: 4f009e406ca7e9ea956637210f029b10f7795e92 [file] [log] [blame]
Jason Monkd01cef92017-12-08 09:48:25 -05001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
5 * except in compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the
10 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
11 * KIND, either express or implied. See the License for the specific language governing
12 * permissions and limitations under the License.
13 */
14
15package android.testing;
16
17import android.content.pm.PackageManager;
18import android.net.Uri;
19import android.util.ArrayMap;
20
21/**
22 * Simple class for simulating basic permission states for tests.
23 *
24 * All enforce* and check* calls on TestableContext are considered the same
25 * and routed through the same check here. If more fine-grained control is
26 * required, then either a sub-class or spy on TestableContext is recommended.
27 */
28public class TestablePermissions {
29
30 private final ArrayMap<String, Integer> mPermissions = new ArrayMap<>();
31 private final ArrayMap<Uri, Integer> mUris = new ArrayMap<>();
32
33 /**
34 * Sets the return value for checkPermission* calls on TestableContext
35 * for a specific permission value. For all enforcePermission* calls
36 * they will throw a security exception if value != PERMISSION_GRANTED.
37 */
38 public void setPermission(String permission, int value) {
39 mPermissions.put(permission, value);
40 }
41
42 /**
43 * Sets the return value for checkUriPermission* calls on TestableContext
44 * for a specific permission value. For all enforceUriPermission* calls
45 * they will throw a security exception if value != PERMISSION_GRANTED.
46 */
47 public void setPermission(Uri uri, int value) {
48 // TODO: Support modeFlags
49 mUris.put(uri, value);
50 }
51
52 boolean wantsCall(String permission) {
53 return mPermissions.containsKey(permission);
54 }
55
56 boolean wantsCall(Uri uri) {
57 return mUris.containsKey(uri);
58 }
59
60 int check(String permission) {
61 return mPermissions.get(permission);
62 }
63
64 int check(Uri uri, int modeFlags) {
65 // TODO: Support modeFlags
66 return mUris.get(uri);
67 }
68
69 public void enforce(String permission) {
70 if (check(permission) != PackageManager.PERMISSION_GRANTED) {
71 throw new SecurityException();
72 }
73 }
74
75 public void enforce(Uri uri, int modeFlags) {
76 if (check(uri, modeFlags) != PackageManager.PERMISSION_GRANTED) {
77 throw new SecurityException();
78 }
79 }
80}