1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.permission.cts; 18 19 import android.app.AppOpsManager; 20 import android.content.Context; 21 import android.test.AndroidTestCase; 22 import android.test.suitebuilder.annotation.SmallTest; 23 import android.util.AttributeSet; 24 import junit.framework.AssertionFailedError; 25 26 import java.lang.reflect.InvocationTargetException; 27 import java.lang.reflect.Method; 28 29 public class AppOpsTest extends AndroidTestCase { 30 static final Class<?>[] sSetModeSignature = new Class[] { 31 Context.class, AttributeSet.class}; 32 33 private AppOpsManager mAppOps; 34 35 @Override setUp()36 protected void setUp() throws Exception { 37 super.setUp(); 38 mAppOps = (AppOpsManager)getContext().getSystemService(Context.APP_OPS_SERVICE); 39 assertNotNull(mAppOps); 40 } 41 42 /** 43 * Test that the app can not change the app op mode for itself. 44 */ 45 @SmallTest testSetMode()46 public void testSetMode() { 47 boolean gotToTest = false; 48 try { 49 Method setMode = mAppOps.getClass().getMethod("setMode", int.class, int.class, 50 String.class, int.class); 51 int writeSmsOp = mAppOps.getClass().getField("OP_WRITE_SMS").getInt(mAppOps); 52 gotToTest = true; 53 setMode.invoke(mAppOps, writeSmsOp, android.os.Process.myUid(), 54 getContext().getPackageName(), AppOpsManager.MODE_ALLOWED); 55 fail("Was able to set mode for self"); 56 } catch (NoSuchFieldException e) { 57 throw new AssertionError("Unable to find OP_WRITE_SMS", e); 58 } catch (NoSuchMethodException e) { 59 throw new AssertionError("Unable to find setMode method", e); 60 } catch (InvocationTargetException e) { 61 if (!gotToTest) { 62 throw new AssertionError("Whoops", e); 63 } 64 // If we got to the test, we want it to have thrown a security exception. 65 // We need to look inside of the wrapper exception to see. 66 Throwable t = e.getCause(); 67 if (!(t instanceof SecurityException)) { 68 throw new AssertionError("Did not throw SecurityException", e); 69 } 70 } catch (IllegalAccessException e) { 71 throw new AssertionError("Whoops", e); 72 } 73 } 74 } 75