1 /* 2 * Copyright (C) 2008 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.content.cts; 18 19 import static android.content.pm.PackageManager.PERMISSION_DENIED; 20 import static android.content.pm.PackageManager.PERMISSION_GRANTED; 21 22 import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; 23 24 import android.app.Activity; 25 import android.app.AppOpsManager; 26 import android.app.Instrumentation; 27 import android.app.WallpaperManager; 28 import android.content.ActivityNotFoundException; 29 import android.content.AttributionSource; 30 import android.content.BroadcastReceiver; 31 import android.content.ComponentName; 32 import android.content.Context; 33 import android.content.ContextParams; 34 import android.content.Intent; 35 import android.content.IntentFilter; 36 import android.content.ServiceConnection; 37 import android.content.SharedPreferences; 38 import android.content.pm.PackageInfo; 39 import android.content.pm.PackageManager; 40 import android.content.res.ColorStateList; 41 import android.content.res.Resources.NotFoundException; 42 import android.content.res.Resources.Theme; 43 import android.content.res.TypedArray; 44 import android.content.res.XmlResourceParser; 45 import android.database.Cursor; 46 import android.database.sqlite.SQLiteCursorDriver; 47 import android.database.sqlite.SQLiteDatabase; 48 import android.database.sqlite.SQLiteQuery; 49 import android.graphics.Bitmap; 50 import android.graphics.drawable.BitmapDrawable; 51 import android.graphics.drawable.Drawable; 52 import android.net.Uri; 53 import android.os.Binder; 54 import android.os.Bundle; 55 import android.os.Handler; 56 import android.os.IBinder; 57 import android.os.Looper; 58 import android.os.Process; 59 import android.os.UserHandle; 60 import android.platform.test.annotations.AppModeFull; 61 import android.preference.PreferenceManager; 62 import android.test.AndroidTestCase; 63 import android.util.AttributeSet; 64 import android.util.Log; 65 import android.util.Xml; 66 import android.view.WindowManager; 67 68 import com.android.compatibility.common.util.PollingCheck; 69 import com.android.compatibility.common.util.ShellIdentityUtils; 70 import com.android.compatibility.common.util.SystemUtil; 71 import com.android.cts.IBinderPermissionTestService; 72 73 import org.xmlpull.v1.XmlPullParser; 74 import org.xmlpull.v1.XmlPullParserException; 75 76 import java.io.File; 77 import java.io.FileOutputStream; 78 import java.io.IOException; 79 import java.io.InputStream; 80 import java.util.ArrayList; 81 import java.util.Arrays; 82 import java.util.List; 83 84 @AppModeFull // TODO(Instant) Figure out which APIs should work. 85 public class ContextTest extends AndroidTestCase { 86 private static final String TAG = "ContextTest"; 87 private static final String ACTUAL_RESULT = "ResultSetByReceiver"; 88 89 private static final String INTIAL_RESULT = "IntialResult"; 90 91 private static final String VALUE_ADDED = "ValueAdded"; 92 private static final String KEY_ADDED = "AddedByReceiver"; 93 94 private static final String VALUE_REMOVED = "ValueWillBeRemove"; 95 private static final String KEY_REMOVED = "ToBeRemoved"; 96 97 private static final String VALUE_KEPT = "ValueKept"; 98 private static final String KEY_KEPT = "ToBeKept"; 99 100 private static final String MOCK_STICKY_ACTION = "android.content.cts.ContextTest." 101 + "STICKY_BROADCAST_RESULT"; 102 103 private static final String ACTION_BROADCAST_TESTORDER = 104 "android.content.cts.ContextTest.BROADCAST_TESTORDER"; 105 private final static String MOCK_ACTION1 = ACTION_BROADCAST_TESTORDER + "1"; 106 private final static String MOCK_ACTION2 = ACTION_BROADCAST_TESTORDER + "2"; 107 108 // Note: keep these constants in sync with the permissions used by BinderPermissionTestService. 109 // 110 // A permission that's granted to this test package. 111 public static final String GRANTED_PERMISSION = "android.permission.USE_CREDENTIALS"; 112 // A permission that's not granted to this test package. 113 public static final String NOT_GRANTED_PERMISSION = "android.permission.HARDWARE_TEST"; 114 115 private static final int BROADCAST_TIMEOUT = 10000; 116 private static final int ROOT_UID = 0; 117 118 private Object mLockObj; 119 120 private ArrayList<BroadcastReceiver> mRegisteredReceiverList; 121 122 private boolean mWallpaperChanged; 123 private BitmapDrawable mOriginalWallpaper; 124 private volatile IBinderPermissionTestService mBinderPermissionTestService; 125 private ServiceConnection mBinderPermissionTestConnection; 126 127 protected Context mContext; 128 129 /** 130 * Returns the Context object that's being tested. 131 */ getContextUnderTest()132 protected Context getContextUnderTest() { 133 return getContext(); 134 } 135 136 @Override setUp()137 protected void setUp() throws Exception { 138 super.setUp(); 139 mContext = getContextUnderTest(); 140 mContext.setTheme(R.style.Test_Theme); 141 142 mLockObj = new Object(); 143 144 mRegisteredReceiverList = new ArrayList<BroadcastReceiver>(); 145 146 mOriginalWallpaper = (BitmapDrawable) mContext.getWallpaper(); 147 } 148 149 @Override tearDown()150 protected void tearDown() throws Exception { 151 if (mWallpaperChanged) { 152 mContext.setWallpaper(mOriginalWallpaper.getBitmap()); 153 } 154 155 for (BroadcastReceiver receiver : mRegisteredReceiverList) { 156 mContext.unregisterReceiver(receiver); 157 } 158 159 super.tearDown(); 160 } 161 testGetString()162 public void testGetString() { 163 String testString = mContext.getString(R.string.context_test_string1); 164 assertEquals("This is %s string.", testString); 165 166 testString = mContext.getString(R.string.context_test_string1, "expected"); 167 assertEquals("This is expected string.", testString); 168 169 testString = mContext.getString(R.string.context_test_string2); 170 assertEquals("This is test string.", testString); 171 172 // Test wrong resource id 173 try { 174 testString = mContext.getString(0, "expected"); 175 fail("Wrong resource id should not be accepted."); 176 } catch (NotFoundException e) { 177 } 178 179 // Test wrong resource id 180 try { 181 testString = mContext.getString(0); 182 fail("Wrong resource id should not be accepted."); 183 } catch (NotFoundException e) { 184 } 185 } 186 testGetText()187 public void testGetText() { 188 CharSequence testCharSequence = mContext.getText(R.string.context_test_string2); 189 assertEquals("This is test string.", testCharSequence.toString()); 190 191 // Test wrong resource id 192 try { 193 testCharSequence = mContext.getText(0); 194 fail("Wrong resource id should not be accepted."); 195 } catch (NotFoundException e) { 196 } 197 } 198 testCreateAttributionContext()199 public void testCreateAttributionContext() throws Exception { 200 final String tag = "testCreateAttributionContext"; 201 final Context attrib = mContext.createAttributionContext(tag); 202 assertEquals(tag, attrib.getAttributionTag()); 203 assertEquals(null, mContext.getAttributionTag()); 204 } 205 testCreateAttributionContextFromParams()206 public void testCreateAttributionContextFromParams() throws Exception { 207 final ContextParams params = new ContextParams.Builder() 208 .setAttributionTag("foo") 209 .setNextAttributionSource(new AttributionSource.Builder(1) 210 .setPackageName("bar") 211 .setAttributionTag("baz") 212 .build()) 213 .build(); 214 final Context attributionContext = getContext().createContext(params); 215 216 assertEquals(params, attributionContext.getParams()); 217 assertEquals(params.getNextAttributionSource(), 218 attributionContext.getAttributionSource().getNext()); 219 assertEquals(params.getAttributionTag(), 220 attributionContext.getAttributionSource().getAttributionTag()); 221 } 222 testContextParams()223 public void testContextParams() throws Exception { 224 final ContextParams params = new ContextParams.Builder() 225 .setAttributionTag("foo") 226 .setNextAttributionSource(new AttributionSource.Builder(1) 227 .setPackageName("bar") 228 .setAttributionTag("baz") 229 .build()) 230 .build(); 231 232 assertEquals("foo", params.getAttributionTag()); 233 assertEquals(1, params.getNextAttributionSource().getUid()); 234 assertEquals("bar", params.getNextAttributionSource().getPackageName()); 235 assertEquals("baz", params.getNextAttributionSource().getAttributionTag()); 236 } 237 testAttributionSourceSetNext()238 public void testAttributionSourceSetNext() throws Exception { 239 final AttributionSource next = new AttributionSource.Builder(2) 240 .setPackageName("nextBar") 241 .setAttributionTag("nextBaz") 242 .build(); 243 final ContextParams params = new ContextParams.Builder() 244 .setAttributionTag("foo") 245 .setNextAttributionSource(new AttributionSource.Builder(1) 246 .setPackageName("bar") 247 .setAttributionTag("baz") 248 .setNext(next) 249 .build()) 250 .build(); 251 252 // Setting a 'next' should not affect prev. 253 assertEquals("foo", params.getAttributionTag()); 254 assertEquals(1, params.getNextAttributionSource().getUid()); 255 assertEquals("bar", params.getNextAttributionSource().getPackageName()); 256 assertEquals("baz", params.getNextAttributionSource().getAttributionTag()); 257 258 final AttributionSource check = 259 params.getNextAttributionSource().getNext(); 260 assertEquals(2, check.getUid()); 261 assertEquals("nextBar", check.getPackageName()); 262 assertEquals("nextBaz", check.getAttributionTag()); 263 } 264 testContextParams_Inherit()265 public void testContextParams_Inherit() throws Exception { 266 final ContextParams orig = new ContextParams.Builder() 267 .setAttributionTag("foo").build(); 268 { 269 final ContextParams params = new ContextParams.Builder(orig).build(); 270 assertEquals("foo", params.getAttributionTag()); 271 } 272 { 273 final ContextParams params = new ContextParams.Builder(orig) 274 .setAttributionTag("bar").build(); 275 assertEquals("bar", params.getAttributionTag()); 276 } 277 { 278 final ContextParams params = new ContextParams.Builder(orig) 279 .setAttributionTag(null).build(); 280 assertEquals(null, params.getAttributionTag()); 281 } 282 } 283 284 /** 285 * Ensure that default and device encrypted storage areas are stored 286 * separately on disk. All devices must support these storage areas, even if 287 * they don't have file-based encryption, so that apps can go through a 288 * backup/restore cycle between FBE and non-FBE devices. 289 */ testCreateDeviceProtectedStorageContext()290 public void testCreateDeviceProtectedStorageContext() throws Exception { 291 final Context deviceContext = mContext.createDeviceProtectedStorageContext(); 292 293 assertFalse(mContext.isDeviceProtectedStorage()); 294 assertTrue(deviceContext.isDeviceProtectedStorage()); 295 296 final File defaultFile = new File(mContext.getFilesDir(), "test"); 297 final File deviceFile = new File(deviceContext.getFilesDir(), "test"); 298 299 assertFalse(deviceFile.equals(defaultFile)); 300 301 deviceFile.createNewFile(); 302 303 // Make sure storage areas are mutually exclusive 304 assertFalse(defaultFile.exists()); 305 assertTrue(deviceFile.exists()); 306 } 307 testMoveSharedPreferencesFrom()308 public void testMoveSharedPreferencesFrom() throws Exception { 309 final Context deviceContext = mContext.createDeviceProtectedStorageContext(); 310 311 mContext.getSharedPreferences("test", Context.MODE_PRIVATE).edit().putInt("answer", 42) 312 .commit(); 313 314 // Verify that we can migrate 315 assertTrue(deviceContext.moveSharedPreferencesFrom(mContext, "test")); 316 assertEquals(0, mContext.getSharedPreferences("test", Context.MODE_PRIVATE) 317 .getInt("answer", 0)); 318 assertEquals(42, deviceContext.getSharedPreferences("test", Context.MODE_PRIVATE) 319 .getInt("answer", 0)); 320 321 // Trying to migrate again when already done is a no-op 322 assertTrue(deviceContext.moveSharedPreferencesFrom(mContext, "test")); 323 assertEquals(0, mContext.getSharedPreferences("test", Context.MODE_PRIVATE) 324 .getInt("answer", 0)); 325 assertEquals(42, deviceContext.getSharedPreferences("test", Context.MODE_PRIVATE) 326 .getInt("answer", 0)); 327 328 // Add a new value and verify that we can migrate back 329 deviceContext.getSharedPreferences("test", Context.MODE_PRIVATE).edit() 330 .putInt("question", 24).commit(); 331 332 assertTrue(mContext.moveSharedPreferencesFrom(deviceContext, "test")); 333 assertEquals(42, mContext.getSharedPreferences("test", Context.MODE_PRIVATE) 334 .getInt("answer", 0)); 335 assertEquals(24, mContext.getSharedPreferences("test", Context.MODE_PRIVATE) 336 .getInt("question", 0)); 337 assertEquals(0, deviceContext.getSharedPreferences("test", Context.MODE_PRIVATE) 338 .getInt("answer", 0)); 339 assertEquals(0, deviceContext.getSharedPreferences("test", Context.MODE_PRIVATE) 340 .getInt("question", 0)); 341 } 342 testMoveDatabaseFrom()343 public void testMoveDatabaseFrom() throws Exception { 344 final Context deviceContext = mContext.createDeviceProtectedStorageContext(); 345 346 SQLiteDatabase db = mContext.openOrCreateDatabase("test.db", 347 Context.MODE_PRIVATE | Context.MODE_ENABLE_WRITE_AHEAD_LOGGING, null); 348 db.execSQL("CREATE TABLE list(item TEXT);"); 349 db.execSQL("INSERT INTO list VALUES ('cat')"); 350 db.execSQL("INSERT INTO list VALUES ('dog')"); 351 db.close(); 352 353 // Verify that we can migrate 354 assertTrue(deviceContext.moveDatabaseFrom(mContext, "test.db")); 355 db = deviceContext.openOrCreateDatabase("test.db", 356 Context.MODE_PRIVATE | Context.MODE_ENABLE_WRITE_AHEAD_LOGGING, null); 357 Cursor c = db.query("list", null, null, null, null, null, null); 358 assertEquals(2, c.getCount()); 359 assertTrue(c.moveToFirst()); 360 assertEquals("cat", c.getString(0)); 361 assertTrue(c.moveToNext()); 362 assertEquals("dog", c.getString(0)); 363 c.close(); 364 db.execSQL("INSERT INTO list VALUES ('mouse')"); 365 db.close(); 366 367 // Trying to migrate again when already done is a no-op 368 assertTrue(deviceContext.moveDatabaseFrom(mContext, "test.db")); 369 370 // Verify that we can migrate back 371 assertTrue(mContext.moveDatabaseFrom(deviceContext, "test.db")); 372 db = mContext.openOrCreateDatabase("test.db", 373 Context.MODE_PRIVATE | Context.MODE_ENABLE_WRITE_AHEAD_LOGGING, null); 374 c = db.query("list", null, null, null, null, null, null); 375 assertEquals(3, c.getCount()); 376 assertTrue(c.moveToFirst()); 377 assertEquals("cat", c.getString(0)); 378 assertTrue(c.moveToNext()); 379 assertEquals("dog", c.getString(0)); 380 assertTrue(c.moveToNext()); 381 assertEquals("mouse", c.getString(0)); 382 c.close(); 383 db.close(); 384 } 385 testAccessTheme()386 public void testAccessTheme() { 387 mContext.setTheme(R.style.Test_Theme); 388 final Theme testTheme = mContext.getTheme(); 389 assertNotNull(testTheme); 390 391 int[] attrs = { 392 android.R.attr.windowNoTitle, 393 android.R.attr.panelColorForeground, 394 android.R.attr.panelColorBackground 395 }; 396 TypedArray attrArray = null; 397 try { 398 attrArray = testTheme.obtainStyledAttributes(attrs); 399 assertTrue(attrArray.getBoolean(0, false)); 400 assertEquals(0xff000000, attrArray.getColor(1, 0)); 401 assertEquals(0xffffffff, attrArray.getColor(2, 0)); 402 } finally { 403 if (attrArray != null) { 404 attrArray.recycle(); 405 attrArray = null; 406 } 407 } 408 409 // setTheme only works for the first time 410 mContext.setTheme(android.R.style.Theme_Black); 411 assertSame(testTheme, mContext.getTheme()); 412 } 413 testObtainStyledAttributes()414 public void testObtainStyledAttributes() { 415 // Test obtainStyledAttributes(int[]) 416 TypedArray testTypedArray = mContext 417 .obtainStyledAttributes(android.R.styleable.View); 418 assertNotNull(testTypedArray); 419 assertTrue(testTypedArray.length() > 2); 420 assertTrue(testTypedArray.length() > 0); 421 testTypedArray.recycle(); 422 423 // Test obtainStyledAttributes(int, int[]) 424 testTypedArray = mContext.obtainStyledAttributes(android.R.style.TextAppearance_Small, 425 android.R.styleable.TextAppearance); 426 assertNotNull(testTypedArray); 427 assertTrue(testTypedArray.length() > 2); 428 testTypedArray.recycle(); 429 430 // Test wrong null array pointer 431 try { 432 testTypedArray = mContext.obtainStyledAttributes(-1, null); 433 fail("obtainStyledAttributes will throw a NullPointerException here."); 434 } catch (NullPointerException e) { 435 } 436 437 // Test obtainStyledAttributes(AttributeSet, int[]) with unavailable resource id. 438 int testInt[] = { 0, 0 }; 439 testTypedArray = mContext.obtainStyledAttributes(-1, testInt); 440 // fail("Wrong resource id should not be accepted."); 441 assertNotNull(testTypedArray); 442 assertEquals(2, testTypedArray.length()); 443 testTypedArray.recycle(); 444 445 // Test obtainStyledAttributes(AttributeSet, int[]) 446 int[] attrs = android.R.styleable.DatePicker; 447 testTypedArray = mContext.obtainStyledAttributes(getAttributeSet(R.layout.context_layout), 448 attrs); 449 assertNotNull(testTypedArray); 450 assertEquals(attrs.length, testTypedArray.length()); 451 testTypedArray.recycle(); 452 453 // Test obtainStyledAttributes(AttributeSet, int[], int, int) 454 testTypedArray = mContext.obtainStyledAttributes(getAttributeSet(R.layout.context_layout), 455 attrs, 0, 0); 456 assertNotNull(testTypedArray); 457 assertEquals(attrs.length, testTypedArray.length()); 458 testTypedArray.recycle(); 459 } 460 testGetSystemService()461 public void testGetSystemService() { 462 // Test invalid service name 463 assertNull(mContext.getSystemService("invalid")); 464 465 // Test valid service name 466 assertNotNull(mContext.getSystemService(Context.WINDOW_SERVICE)); 467 } 468 testGetSystemServiceByClass()469 public void testGetSystemServiceByClass() { 470 // Test invalid service class 471 assertNull(mContext.getSystemService(Object.class)); 472 473 // Test valid service name 474 assertNotNull(mContext.getSystemService(WindowManager.class)); 475 assertEquals(mContext.getSystemService(Context.WINDOW_SERVICE), 476 mContext.getSystemService(WindowManager.class)); 477 } 478 testGetColorStateList()479 public void testGetColorStateList() { 480 try { 481 mContext.getColorStateList(0); 482 fail("Failed at testGetColorStateList"); 483 } catch (NotFoundException e) { 484 //expected 485 } 486 487 final ColorStateList colorStateList = mContext.getColorStateList(R.color.color2); 488 final int[] focusedState = {android.R.attr.state_focused}; 489 final int focusColor = colorStateList.getColorForState(focusedState, R.color.failColor); 490 assertEquals(0xffff0000, focusColor); 491 } 492 testGetColor()493 public void testGetColor() { 494 try { 495 mContext.getColor(0); 496 fail("Failed at testGetColor"); 497 } catch (NotFoundException e) { 498 //expected 499 } 500 501 final int color = mContext.getColor(R.color.color2); 502 assertEquals(0xffffff00, color); 503 } 504 505 /** 506 * Developers have come to expect at least ext4-style filename behavior, so 507 * verify that the underlying filesystem supports them. 508 */ testFilenames()509 public void testFilenames() throws Exception { 510 final File base = mContext.getFilesDir(); 511 assertValidFile(new File(base, "foo")); 512 assertValidFile(new File(base, ".bar")); 513 assertValidFile(new File(base, "foo.bar")); 514 assertValidFile(new File(base, "\u2603")); 515 assertValidFile(new File(base, "\uD83D\uDCA9")); 516 517 final int pid = android.os.Process.myPid(); 518 final StringBuilder sb = new StringBuilder(255); 519 while (sb.length() <= 255) { 520 sb.append(pid); 521 sb.append(mContext.getPackageName()); 522 } 523 sb.setLength(255); 524 525 final String longName = sb.toString(); 526 final File longDir = new File(base, longName); 527 assertValidFile(longDir); 528 longDir.mkdir(); 529 final File longFile = new File(longDir, longName); 530 assertValidFile(longFile); 531 } 532 testMainLooper()533 public void testMainLooper() throws Exception { 534 final Thread mainThread = Looper.getMainLooper().getThread(); 535 final Handler handler = new Handler(mContext.getMainLooper()); 536 handler.post(() -> { 537 assertEquals(mainThread, Thread.currentThread()); 538 }); 539 } 540 testMainExecutor()541 public void testMainExecutor() throws Exception { 542 final Thread mainThread = Looper.getMainLooper().getThread(); 543 mContext.getMainExecutor().execute(() -> { 544 assertEquals(mainThread, Thread.currentThread()); 545 }); 546 } 547 assertValidFile(File file)548 private void assertValidFile(File file) throws Exception { 549 Log.d(TAG, "Checking " + file); 550 if (file.exists()) { 551 assertTrue("File already exists and couldn't be deleted before test: " + file, 552 file.delete()); 553 } 554 assertTrue("Failed to create " + file, file.createNewFile()); 555 assertTrue("Doesn't exist after create " + file, file.exists()); 556 assertTrue("Failed to delete after create " + file, file.delete()); 557 new FileOutputStream(file).close(); 558 assertTrue("Doesn't exist after stream " + file, file.exists()); 559 assertTrue("Failed to delete after stream " + file, file.delete()); 560 } 561 beginDocument(XmlPullParser parser, String firstElementName)562 static void beginDocument(XmlPullParser parser, String firstElementName) 563 throws XmlPullParserException, IOException 564 { 565 int type; 566 while ((type=parser.next()) != parser.START_TAG 567 && type != parser.END_DOCUMENT) { 568 ; 569 } 570 571 if (type != parser.START_TAG) { 572 throw new XmlPullParserException("No start tag found"); 573 } 574 575 if (!parser.getName().equals(firstElementName)) { 576 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() + 577 ", expected " + firstElementName); 578 } 579 } 580 getAttributeSet(int resourceId)581 private AttributeSet getAttributeSet(int resourceId) { 582 final XmlResourceParser parser = mContext.getResources().getXml( 583 resourceId); 584 585 try { 586 beginDocument(parser, "RelativeLayout"); 587 } catch (XmlPullParserException e) { 588 e.printStackTrace(); 589 } catch (IOException e) { 590 e.printStackTrace(); 591 } 592 593 final AttributeSet attr = Xml.asAttributeSet(parser); 594 assertNotNull(attr); 595 return attr; 596 } 597 registerBroadcastReceiver(BroadcastReceiver receiver, IntentFilter filter)598 private void registerBroadcastReceiver(BroadcastReceiver receiver, IntentFilter filter) { 599 mContext.registerReceiver(receiver, filter); 600 601 mRegisteredReceiverList.add(receiver); 602 } 603 testSendOrderedBroadcast1()604 public void testSendOrderedBroadcast1() throws InterruptedException { 605 final HighPriorityBroadcastReceiver highPriorityReceiver = 606 new HighPriorityBroadcastReceiver(); 607 final LowPriorityBroadcastReceiver lowPriorityReceiver = 608 new LowPriorityBroadcastReceiver(); 609 610 final IntentFilter filterHighPriority = new IntentFilter(ResultReceiver.MOCK_ACTION); 611 filterHighPriority.setPriority(1); 612 final IntentFilter filterLowPriority = new IntentFilter(ResultReceiver.MOCK_ACTION); 613 registerBroadcastReceiver(highPriorityReceiver, filterHighPriority); 614 registerBroadcastReceiver(lowPriorityReceiver, filterLowPriority); 615 616 final Intent broadcastIntent = new Intent(ResultReceiver.MOCK_ACTION); 617 broadcastIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 618 mContext.sendOrderedBroadcast(broadcastIntent, null); 619 new PollingCheck(BROADCAST_TIMEOUT) { 620 @Override 621 protected boolean check() { 622 return highPriorityReceiver.hasReceivedBroadCast() 623 && !lowPriorityReceiver.hasReceivedBroadCast(); 624 } 625 }.run(); 626 627 synchronized (highPriorityReceiver) { 628 highPriorityReceiver.notify(); 629 } 630 631 new PollingCheck(BROADCAST_TIMEOUT) { 632 @Override 633 protected boolean check() { 634 return highPriorityReceiver.hasReceivedBroadCast() 635 && lowPriorityReceiver.hasReceivedBroadCast(); 636 } 637 }.run(); 638 } 639 testSendOrderedBroadcast2()640 public void testSendOrderedBroadcast2() throws InterruptedException { 641 final TestBroadcastReceiver broadcastReceiver = new TestBroadcastReceiver(); 642 broadcastReceiver.mIsOrderedBroadcasts = true; 643 644 Bundle bundle = new Bundle(); 645 bundle.putString(KEY_KEPT, VALUE_KEPT); 646 bundle.putString(KEY_REMOVED, VALUE_REMOVED); 647 Intent intent = new Intent(ResultReceiver.MOCK_ACTION); 648 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 649 mContext.sendOrderedBroadcast(intent, null, broadcastReceiver, null, 1, 650 INTIAL_RESULT, bundle); 651 652 synchronized (mLockObj) { 653 try { 654 mLockObj.wait(BROADCAST_TIMEOUT); 655 } catch (InterruptedException e) { 656 fail("unexpected InterruptedException."); 657 } 658 } 659 660 assertTrue("Receiver didn't make any response.", broadcastReceiver.hadReceivedBroadCast()); 661 assertEquals("Incorrect code: " + broadcastReceiver.getResultCode(), 3, 662 broadcastReceiver.getResultCode()); 663 assertEquals(ACTUAL_RESULT, broadcastReceiver.getResultData()); 664 Bundle resultExtras = broadcastReceiver.getResultExtras(false); 665 assertEquals(VALUE_ADDED, resultExtras.getString(KEY_ADDED)); 666 assertEquals(VALUE_KEPT, resultExtras.getString(KEY_KEPT)); 667 assertNull(resultExtras.getString(KEY_REMOVED)); 668 } 669 testSendOrderedBroadcastWithAppOp()670 public void testSendOrderedBroadcastWithAppOp() { 671 // we use a HighPriorityBroadcastReceiver because the final receiver should get the 672 // broadcast only at the end. 673 final ResultReceiver receiver = new HighPriorityBroadcastReceiver(); 674 final ResultReceiver finalReceiver = new ResultReceiver(); 675 676 AppOpsManager aom = 677 (AppOpsManager) getContextUnderTest().getSystemService(Context.APP_OPS_SERVICE); 678 ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(aom, 679 (appOpsMan) -> appOpsMan.setUidMode(AppOpsManager.OPSTR_READ_CELL_BROADCASTS, 680 Process.myUid(), AppOpsManager.MODE_ALLOWED)); 681 682 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION)); 683 684 mContext.sendOrderedBroadcast( 685 new Intent(ResultReceiver.MOCK_ACTION), 686 null, // permission 687 AppOpsManager.OPSTR_READ_CELL_BROADCASTS, 688 finalReceiver, 689 null, // scheduler 690 0, // initial code 691 null, //initial data 692 null); // initial extras 693 694 new PollingCheck(BROADCAST_TIMEOUT){ 695 @Override 696 protected boolean check() { 697 return receiver.hasReceivedBroadCast() 698 && !finalReceiver.hasReceivedBroadCast(); 699 } 700 }.run(); 701 702 synchronized (receiver) { 703 receiver.notify(); 704 } 705 706 new PollingCheck(BROADCAST_TIMEOUT){ 707 @Override 708 protected boolean check() { 709 // ensure that first receiver has received broadcast before final receiver 710 return receiver.hasReceivedBroadCast() 711 && finalReceiver.hasReceivedBroadCast(); 712 } 713 }.run(); 714 } 715 testSendOrderedBroadcastWithAppOp_NotGranted()716 public void testSendOrderedBroadcastWithAppOp_NotGranted() { 717 final ResultReceiver receiver = new ResultReceiver(); 718 719 AppOpsManager aom = 720 (AppOpsManager) getContextUnderTest().getSystemService(Context.APP_OPS_SERVICE); 721 ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(aom, 722 (appOpsMan) -> appOpsMan.setUidMode(AppOpsManager.OPSTR_READ_CELL_BROADCASTS, 723 Process.myUid(), AppOpsManager.MODE_ERRORED)); 724 725 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION)); 726 727 mContext.sendOrderedBroadcast( 728 new Intent(ResultReceiver.MOCK_ACTION), 729 null, // permission 730 AppOpsManager.OPSTR_READ_CELL_BROADCASTS, 731 null, // final receiver 732 null, // scheduler 733 0, // initial code 734 null, //initial data 735 null); // initial extras 736 737 boolean broadcastNeverSent = false; 738 try { 739 new PollingCheck(BROADCAST_TIMEOUT) { 740 @Override 741 protected boolean check() { 742 return receiver.hasReceivedBroadCast(); 743 } 744 745 public void runWithInterruption() throws InterruptedException { 746 if (check()) { 747 return; 748 } 749 750 long timeout = BROADCAST_TIMEOUT; 751 while (timeout > 0) { 752 try { 753 Thread.sleep(50 /* time slice */); 754 } catch (InterruptedException e) { 755 fail("unexpected InterruptedException"); 756 } 757 758 if (check()) { 759 return; 760 } 761 762 timeout -= 50; // time slice 763 } 764 throw new InterruptedException(); 765 } 766 }.runWithInterruption(); 767 } catch (InterruptedException e) { 768 broadcastNeverSent = true; 769 } 770 771 assertTrue(broadcastNeverSent); 772 } 773 testRegisterReceiver1()774 public void testRegisterReceiver1() throws InterruptedException { 775 final FilteredReceiver broadcastReceiver = new FilteredReceiver(); 776 final IntentFilter filter = new IntentFilter(MOCK_ACTION1); 777 778 // Test registerReceiver 779 mContext.registerReceiver(broadcastReceiver, filter); 780 781 // Test unwanted intent(action = MOCK_ACTION2) 782 broadcastReceiver.reset(); 783 waitForFilteredIntent(mContext, MOCK_ACTION2); 784 assertFalse(broadcastReceiver.hadReceivedBroadCast1()); 785 assertFalse(broadcastReceiver.hadReceivedBroadCast2()); 786 787 // Send wanted intent(action = MOCK_ACTION1) 788 broadcastReceiver.reset(); 789 waitForFilteredIntent(mContext, MOCK_ACTION1); 790 assertTrue(broadcastReceiver.hadReceivedBroadCast1()); 791 assertFalse(broadcastReceiver.hadReceivedBroadCast2()); 792 793 mContext.unregisterReceiver(broadcastReceiver); 794 795 // Test unregisterReceiver 796 FilteredReceiver broadcastReceiver2 = new FilteredReceiver(); 797 mContext.registerReceiver(broadcastReceiver2, filter); 798 mContext.unregisterReceiver(broadcastReceiver2); 799 800 // Test unwanted intent(action = MOCK_ACTION2) 801 broadcastReceiver2.reset(); 802 waitForFilteredIntent(mContext, MOCK_ACTION2); 803 assertFalse(broadcastReceiver2.hadReceivedBroadCast1()); 804 assertFalse(broadcastReceiver2.hadReceivedBroadCast2()); 805 806 // Send wanted intent(action = MOCK_ACTION1), but the receiver is unregistered. 807 broadcastReceiver2.reset(); 808 waitForFilteredIntent(mContext, MOCK_ACTION1); 809 assertFalse(broadcastReceiver2.hadReceivedBroadCast1()); 810 assertFalse(broadcastReceiver2.hadReceivedBroadCast2()); 811 } 812 testRegisterReceiver2()813 public void testRegisterReceiver2() throws InterruptedException { 814 FilteredReceiver broadcastReceiver = new FilteredReceiver(); 815 IntentFilter filter = new IntentFilter(); 816 filter.addAction(MOCK_ACTION1); 817 818 // Test registerReceiver 819 mContext.registerReceiver(broadcastReceiver, filter, null, null); 820 821 // Test unwanted intent(action = MOCK_ACTION2) 822 broadcastReceiver.reset(); 823 waitForFilteredIntent(mContext, MOCK_ACTION2); 824 assertFalse(broadcastReceiver.hadReceivedBroadCast1()); 825 assertFalse(broadcastReceiver.hadReceivedBroadCast2()); 826 827 // Send wanted intent(action = MOCK_ACTION1) 828 broadcastReceiver.reset(); 829 waitForFilteredIntent(mContext, MOCK_ACTION1); 830 assertTrue(broadcastReceiver.hadReceivedBroadCast1()); 831 assertFalse(broadcastReceiver.hadReceivedBroadCast2()); 832 833 mContext.unregisterReceiver(broadcastReceiver); 834 } 835 testRegisterReceiverForAllUsers()836 public void testRegisterReceiverForAllUsers() throws InterruptedException { 837 FilteredReceiver broadcastReceiver = new FilteredReceiver(); 838 IntentFilter filter = new IntentFilter(); 839 filter.addAction(MOCK_ACTION1); 840 841 // Test registerReceiverForAllUsers without permission: verify SecurityException. 842 try { 843 mContext.registerReceiverForAllUsers(broadcastReceiver, filter, null, null); 844 fail("testRegisterReceiverForAllUsers: " 845 + "SecurityException expected on registerReceiverForAllUsers"); 846 } catch (SecurityException se) { 847 // expected 848 } 849 850 // Test registerReceiverForAllUsers with permission. 851 try { 852 ShellIdentityUtils.invokeMethodWithShellPermissions( 853 mContext, 854 (ctx) -> ctx.registerReceiverForAllUsers(broadcastReceiver, filter, null, null) 855 ); 856 } catch (SecurityException se) { 857 fail("testRegisterReceiverForAllUsers: SecurityException not expected"); 858 } 859 860 // Test unwanted intent(action = MOCK_ACTION2) 861 broadcastReceiver.reset(); 862 waitForFilteredIntent(mContext, MOCK_ACTION2); 863 assertFalse(broadcastReceiver.hadReceivedBroadCast1()); 864 assertFalse(broadcastReceiver.hadReceivedBroadCast2()); 865 866 // Send wanted intent(action = MOCK_ACTION1) 867 broadcastReceiver.reset(); 868 waitForFilteredIntent(mContext, MOCK_ACTION1); 869 assertTrue(broadcastReceiver.hadReceivedBroadCast1()); 870 assertEquals(broadcastReceiver.getSendingUser(), Process.myUserHandle()); 871 assertFalse(broadcastReceiver.hadReceivedBroadCast2()); 872 873 mContext.unregisterReceiver(broadcastReceiver); 874 } 875 testAccessWallpaper()876 public void testAccessWallpaper() throws IOException, InterruptedException { 877 if (!isWallpaperSupported()) return; 878 879 // set Wallpaper by context#setWallpaper(Bitmap) 880 Bitmap bitmap = Bitmap.createBitmap(20, 30, Bitmap.Config.RGB_565); 881 // Test getWallpaper 882 Drawable testDrawable = mContext.getWallpaper(); 883 // Test peekWallpaper 884 Drawable testDrawable2 = mContext.peekWallpaper(); 885 886 mContext.setWallpaper(bitmap); 887 mWallpaperChanged = true; 888 synchronized(this) { 889 wait(500); 890 } 891 892 assertNotSame(testDrawable, mContext.peekWallpaper()); 893 assertNotNull(mContext.getWallpaper()); 894 assertNotSame(testDrawable2, mContext.peekWallpaper()); 895 assertNotNull(mContext.peekWallpaper()); 896 897 // set Wallpaper by context#setWallpaper(InputStream) 898 mContext.clearWallpaper(); 899 900 testDrawable = mContext.getWallpaper(); 901 InputStream stream = mContext.getResources().openRawResource(R.drawable.scenery); 902 903 mContext.setWallpaper(stream); 904 synchronized (this) { 905 wait(1000); 906 } 907 908 assertNotSame(testDrawable, mContext.peekWallpaper()); 909 } 910 testAccessDatabase()911 public void testAccessDatabase() { 912 String DATABASE_NAME = "databasetest"; 913 String DATABASE_NAME1 = DATABASE_NAME + "1"; 914 String DATABASE_NAME2 = DATABASE_NAME + "2"; 915 SQLiteDatabase mDatabase; 916 File mDatabaseFile; 917 918 SQLiteDatabase.CursorFactory factory = new SQLiteDatabase.CursorFactory() { 919 public Cursor newCursor(SQLiteDatabase db, SQLiteCursorDriver masterQuery, 920 String editTable, SQLiteQuery query) { 921 return new android.database.sqlite.SQLiteCursor(db, masterQuery, editTable, query) { 922 @Override 923 public boolean requery() { 924 setSelectionArguments(new String[] { "2" }); 925 return super.requery(); 926 } 927 }; 928 } 929 }; 930 931 // FIXME: Move cleanup into tearDown() 932 for (String db : mContext.databaseList()) { 933 File f = mContext.getDatabasePath(db); 934 if (f.exists()) { 935 mContext.deleteDatabase(db); 936 } 937 } 938 939 // Test openOrCreateDatabase with null and actual factory 940 mDatabase = mContext.openOrCreateDatabase(DATABASE_NAME1, 941 Context.MODE_ENABLE_WRITE_AHEAD_LOGGING, factory); 942 assertNotNull(mDatabase); 943 mDatabase.close(); 944 mDatabase = mContext.openOrCreateDatabase(DATABASE_NAME2, 945 Context.MODE_ENABLE_WRITE_AHEAD_LOGGING, factory); 946 assertNotNull(mDatabase); 947 mDatabase.close(); 948 949 // Test getDatabasePath 950 File actualDBPath = mContext.getDatabasePath(DATABASE_NAME1); 951 952 // Test databaseList() 953 List<String> list = Arrays.asList(mContext.databaseList()); 954 assertTrue("1) database list: " + list, list.contains(DATABASE_NAME1)); 955 assertTrue("2) database list: " + list, list.contains(DATABASE_NAME2)); 956 957 // Test deleteDatabase() 958 for (int i = 1; i < 3; i++) { 959 mDatabaseFile = mContext.getDatabasePath(DATABASE_NAME + i); 960 assertTrue(mDatabaseFile.exists()); 961 mContext.deleteDatabase(DATABASE_NAME + i); 962 mDatabaseFile = new File(actualDBPath, DATABASE_NAME + i); 963 assertFalse(mDatabaseFile.exists()); 964 } 965 } 966 testEnforceUriPermission1()967 public void testEnforceUriPermission1() { 968 try { 969 Uri uri = Uri.parse("content://ctstest"); 970 mContext.enforceUriPermission(uri, Binder.getCallingPid(), 971 Binder.getCallingUid(), Intent.FLAG_GRANT_WRITE_URI_PERMISSION, 972 "enforceUriPermission is not working without possessing an IPC."); 973 fail("enforceUriPermission is not working without possessing an IPC."); 974 } catch (SecurityException e) { 975 // If the function is OK, it should throw a SecurityException here because currently no 976 // IPC is handled by this process. 977 } 978 } 979 testEnforceUriPermission2()980 public void testEnforceUriPermission2() { 981 Uri uri = Uri.parse("content://ctstest"); 982 try { 983 mContext.enforceUriPermission(uri, NOT_GRANTED_PERMISSION, 984 NOT_GRANTED_PERMISSION, Binder.getCallingPid(), Binder.getCallingUid(), 985 Intent.FLAG_GRANT_WRITE_URI_PERMISSION, 986 "enforceUriPermission is not working without possessing an IPC."); 987 fail("enforceUriPermission is not working without possessing an IPC."); 988 } catch (SecurityException e) { 989 // If the function is ok, it should throw a SecurityException here because currently no 990 // IPC is handled by this process. 991 } 992 } 993 testGetPackageResourcePath()994 public void testGetPackageResourcePath() { 995 assertNotNull(mContext.getPackageResourcePath()); 996 } 997 testStartActivityWithActivityNotFound()998 public void testStartActivityWithActivityNotFound() { 999 Intent intent = new Intent(mContext, ContextCtsActivity.class); 1000 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 1001 try { 1002 mContext.startActivity(intent); 1003 fail("Test startActivity should throw a ActivityNotFoundException here."); 1004 } catch (ActivityNotFoundException e) { 1005 // Because ContextWrapper is a wrapper class, so no need to test 1006 // the details of the function's performance. Getting a result 1007 // from the wrapped class is enough for testing. 1008 } 1009 } 1010 testStartActivities()1011 public void testStartActivities() throws Exception { 1012 final Intent[] intents = { 1013 new Intent().setComponent(new ComponentName(mContext, 1014 AvailableIntentsActivity.class)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 1015 new Intent().setComponent(new ComponentName(mContext, 1016 ImageCaptureActivity.class)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) 1017 }; 1018 1019 final Instrumentation.ActivityMonitor firstMonitor = getInstrumentation() 1020 .addMonitor(AvailableIntentsActivity.class.getName(), null /* result */, 1021 false /* block */); 1022 final Instrumentation.ActivityMonitor secondMonitor = getInstrumentation() 1023 .addMonitor(ImageCaptureActivity.class.getName(), null /* result */, 1024 false /* block */); 1025 1026 mContext.startActivities(intents); 1027 1028 Activity firstActivity = getInstrumentation().waitForMonitorWithTimeout(firstMonitor, 5000); 1029 assertNotNull(firstActivity); 1030 1031 Activity secondActivity = getInstrumentation().waitForMonitorWithTimeout(secondMonitor, 1032 5000); 1033 assertNotNull(secondActivity); 1034 } 1035 testStartActivityAsUser()1036 public void testStartActivityAsUser() { 1037 try (ActivitySession activitySession = new ActivitySession()) { 1038 Intent intent = new Intent(mContext, AvailableIntentsActivity.class); 1039 1040 activitySession.assertActivityLaunched(intent.getComponent().getClassName(), 1041 () -> SystemUtil.runWithShellPermissionIdentity(() -> 1042 mContext.startActivityAsUser(intent, UserHandle.CURRENT))); 1043 } 1044 } 1045 testStartActivity()1046 public void testStartActivity() { 1047 try (ActivitySession activitySession = new ActivitySession()) { 1048 Intent intent = new Intent(mContext, AvailableIntentsActivity.class); 1049 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 1050 1051 activitySession.assertActivityLaunched(intent.getComponent().getClassName(), 1052 () -> mContext.startActivity(intent)); 1053 } 1054 } 1055 1056 /** 1057 * Helper class to launch / close test activity. 1058 */ 1059 private class ActivitySession implements AutoCloseable { 1060 private Activity mTestActivity; 1061 private static final int ACTIVITY_LAUNCH_TIMEOUT = 5000; 1062 assertActivityLaunched(String activityClassName, Runnable activityStarter)1063 void assertActivityLaunched(String activityClassName, Runnable activityStarter) { 1064 final Instrumentation.ActivityMonitor monitor = getInstrumentation() 1065 .addMonitor(activityClassName, null /* result */, 1066 false /* block */); 1067 activityStarter.run(); 1068 // Wait for activity launch with timeout. 1069 mTestActivity = getInstrumentation().waitForMonitorWithTimeout(monitor, 1070 ACTIVITY_LAUNCH_TIMEOUT); 1071 assertNotNull(mTestActivity); 1072 } 1073 1074 @Override close()1075 public void close() { 1076 if (mTestActivity != null) { 1077 mTestActivity.finishAndRemoveTask(); 1078 } 1079 } 1080 } 1081 testCreatePackageContext()1082 public void testCreatePackageContext() throws PackageManager.NameNotFoundException { 1083 Context actualContext = mContext.createPackageContext(getValidPackageName(), 1084 Context.CONTEXT_IGNORE_SECURITY); 1085 1086 assertNotNull(actualContext); 1087 } 1088 testCreatePackageContextAsUser()1089 public void testCreatePackageContextAsUser() throws Exception { 1090 for (UserHandle user : new UserHandle[] { 1091 android.os.Process.myUserHandle(), 1092 UserHandle.ALL, UserHandle.CURRENT, UserHandle.SYSTEM 1093 }) { 1094 assertEquals(user, mContext 1095 .createPackageContextAsUser(getValidPackageName(), 0, user).getUser()); 1096 } 1097 } 1098 testCreateContextAsUser()1099 public void testCreateContextAsUser() throws Exception { 1100 for (UserHandle user : new UserHandle[] { 1101 android.os.Process.myUserHandle(), 1102 UserHandle.ALL, UserHandle.CURRENT, UserHandle.SYSTEM 1103 }) { 1104 assertEquals(user, mContext.createContextAsUser(user, 0).getUser()); 1105 } 1106 } 1107 1108 /** 1109 * Helper method to retrieve a valid application package name to use for tests. 1110 */ getValidPackageName()1111 protected String getValidPackageName() { 1112 List<PackageInfo> packages = mContext.getPackageManager().getInstalledPackages( 1113 PackageManager.GET_ACTIVITIES); 1114 assertTrue(packages.size() >= 1); 1115 return packages.get(0).packageName; 1116 } 1117 testGetMainLooper()1118 public void testGetMainLooper() { 1119 assertNotNull(mContext.getMainLooper()); 1120 } 1121 testGetApplicationContext()1122 public void testGetApplicationContext() { 1123 assertSame(mContext.getApplicationContext(), mContext.getApplicationContext()); 1124 } 1125 testGetSharedPreferences()1126 public void testGetSharedPreferences() { 1127 SharedPreferences sp; 1128 SharedPreferences localSP; 1129 1130 sp = PreferenceManager.getDefaultSharedPreferences(mContext); 1131 String packageName = mContext.getPackageName(); 1132 localSP = mContext.getSharedPreferences(packageName + "_preferences", 1133 Context.MODE_PRIVATE); 1134 assertSame(sp, localSP); 1135 } 1136 testRevokeUriPermission()1137 public void testRevokeUriPermission() { 1138 Uri uri = Uri.parse("contents://ctstest"); 1139 mContext.revokeUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1140 } 1141 testAccessService()1142 public void testAccessService() throws InterruptedException { 1143 MockContextService.reset(); 1144 bindExpectResult(mContext, new Intent(mContext, MockContextService.class)); 1145 1146 // Check startService 1147 assertTrue(MockContextService.hadCalledOnStart()); 1148 // Check bindService 1149 assertTrue(MockContextService.hadCalledOnBind()); 1150 1151 assertTrue(MockContextService.hadCalledOnDestory()); 1152 // Check unbinService 1153 assertTrue(MockContextService.hadCalledOnUnbind()); 1154 } 1155 testGetPackageCodePath()1156 public void testGetPackageCodePath() { 1157 assertNotNull(mContext.getPackageCodePath()); 1158 } 1159 testGetPackageName()1160 public void testGetPackageName() { 1161 assertEquals("android.content.cts", mContext.getPackageName()); 1162 } 1163 testGetCacheDir()1164 public void testGetCacheDir() { 1165 assertNotNull(mContext.getCacheDir()); 1166 } 1167 testGetContentResolver()1168 public void testGetContentResolver() { 1169 assertSame(mContext.getContentResolver(), mContext.getContentResolver()); 1170 } 1171 testGetFileStreamPath()1172 public void testGetFileStreamPath() { 1173 String TEST_FILENAME = "TestGetFileStreamPath"; 1174 1175 // Test the path including the input filename 1176 String fileStreamPath = mContext.getFileStreamPath(TEST_FILENAME).toString(); 1177 assertTrue(fileStreamPath.indexOf(TEST_FILENAME) >= 0); 1178 } 1179 testGetClassLoader()1180 public void testGetClassLoader() { 1181 assertSame(mContext.getClassLoader(), mContext.getClassLoader()); 1182 } 1183 testGetWallpaperDesiredMinimumHeightAndWidth()1184 public void testGetWallpaperDesiredMinimumHeightAndWidth() { 1185 if (!isWallpaperSupported()) return; 1186 1187 int height = mContext.getWallpaperDesiredMinimumHeight(); 1188 int width = mContext.getWallpaperDesiredMinimumWidth(); 1189 1190 // returned value is <= 0, the caller should use the height of the 1191 // default display instead. 1192 // That is to say, the return values of desired minimumHeight and 1193 // minimunWidth are at the same side of 0-dividing line. 1194 assertTrue((height > 0 && width > 0) || (height <= 0 && width <= 0)); 1195 } 1196 testAccessStickyBroadcast()1197 public void testAccessStickyBroadcast() throws InterruptedException { 1198 ResultReceiver resultReceiver = new ResultReceiver(); 1199 1200 Intent intent = new Intent(MOCK_STICKY_ACTION); 1201 TestBroadcastReceiver stickyReceiver = new TestBroadcastReceiver(); 1202 1203 mContext.sendStickyBroadcast(intent); 1204 1205 waitForReceiveBroadCast(resultReceiver); 1206 1207 assertEquals(intent.getAction(), mContext.registerReceiver(stickyReceiver, 1208 new IntentFilter(MOCK_STICKY_ACTION)).getAction()); 1209 1210 synchronized (mLockObj) { 1211 mLockObj.wait(BROADCAST_TIMEOUT); 1212 } 1213 1214 assertTrue("Receiver didn't make any response.", stickyReceiver.hadReceivedBroadCast()); 1215 1216 mContext.unregisterReceiver(stickyReceiver); 1217 mContext.removeStickyBroadcast(intent); 1218 1219 assertNull(mContext.registerReceiver(stickyReceiver, 1220 new IntentFilter(MOCK_STICKY_ACTION))); 1221 mContext.unregisterReceiver(stickyReceiver); 1222 } 1223 testCheckCallingOrSelfUriPermissions()1224 public void testCheckCallingOrSelfUriPermissions() { 1225 List<Uri> uris = new ArrayList<>(); 1226 Uri uri1 = Uri.parse("content://ctstest1"); 1227 uris.add(uri1); 1228 Uri uri2 = Uri.parse("content://ctstest2"); 1229 uris.add(uri2); 1230 1231 int[] retValue = mContext.checkCallingOrSelfUriPermissions(uris, 1232 Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1233 assertEquals(retValue.length, 2); 1234 // This package does not have access to the given URIs 1235 assertEquals(PERMISSION_DENIED, retValue[0]); 1236 assertEquals(PERMISSION_DENIED, retValue[1]); 1237 } 1238 testCheckCallingOrSelfUriPermission()1239 public void testCheckCallingOrSelfUriPermission() { 1240 Uri uri = Uri.parse("content://ctstest"); 1241 1242 int retValue = mContext.checkCallingOrSelfUriPermission(uri, 1243 Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1244 assertEquals(PackageManager.PERMISSION_DENIED, retValue); 1245 } 1246 testGrantUriPermission()1247 public void testGrantUriPermission() { 1248 mContext.grantUriPermission("com.android.mms", Uri.parse("contents://ctstest"), 1249 Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1250 } 1251 testCheckPermissionGranted()1252 public void testCheckPermissionGranted() { 1253 int returnValue = mContext.checkPermission( 1254 GRANTED_PERMISSION, Process.myPid(), Process.myUid()); 1255 assertEquals(PackageManager.PERMISSION_GRANTED, returnValue); 1256 } 1257 testCheckPermissionNotGranted()1258 public void testCheckPermissionNotGranted() { 1259 int returnValue = mContext.checkPermission( 1260 NOT_GRANTED_PERMISSION, Process.myPid(), Process.myUid()); 1261 assertEquals(PackageManager.PERMISSION_DENIED, returnValue); 1262 } 1263 testCheckPermissionRootUser()1264 public void testCheckPermissionRootUser() { 1265 // Test with root user, everything will be granted. 1266 int returnValue = mContext.checkPermission(NOT_GRANTED_PERMISSION, 1, ROOT_UID); 1267 assertEquals(PackageManager.PERMISSION_GRANTED, returnValue); 1268 } 1269 testCheckPermissionInvalidRequest()1270 public void testCheckPermissionInvalidRequest() { 1271 // Test with null permission. 1272 try { 1273 int returnValue = mContext.checkPermission(null, 0, ROOT_UID); 1274 fail("checkPermission should not accept null permission"); 1275 } catch (IllegalArgumentException e) { 1276 } 1277 1278 // Test with invalid uid and included granted permission. 1279 int returnValue = mContext.checkPermission(GRANTED_PERMISSION, 1, -11); 1280 assertEquals(PackageManager.PERMISSION_DENIED, returnValue); 1281 } 1282 testCheckSelfPermissionGranted()1283 public void testCheckSelfPermissionGranted() { 1284 int returnValue = mContext.checkSelfPermission(GRANTED_PERMISSION); 1285 assertEquals(PackageManager.PERMISSION_GRANTED, returnValue); 1286 } 1287 testCheckSelfPermissionNotGranted()1288 public void testCheckSelfPermissionNotGranted() { 1289 int returnValue = mContext.checkSelfPermission(NOT_GRANTED_PERMISSION); 1290 assertEquals(PackageManager.PERMISSION_DENIED, returnValue); 1291 } 1292 testEnforcePermissionGranted()1293 public void testEnforcePermissionGranted() { 1294 mContext.enforcePermission( 1295 GRANTED_PERMISSION, Process.myPid(), Process.myUid(), 1296 "permission isn't granted"); 1297 } 1298 testEnforcePermissionNotGranted()1299 public void testEnforcePermissionNotGranted() { 1300 try { 1301 mContext.enforcePermission( 1302 NOT_GRANTED_PERMISSION, Process.myPid(), Process.myUid(), 1303 "permission isn't granted"); 1304 fail("Permission shouldn't be granted."); 1305 } catch (SecurityException expected) { 1306 } 1307 } 1308 testCheckCallingOrSelfPermission_noIpc()1309 public void testCheckCallingOrSelfPermission_noIpc() { 1310 // There's no ongoing Binder call, so this package's permissions are checked. 1311 int retValue = mContext.checkCallingOrSelfPermission(GRANTED_PERMISSION); 1312 assertEquals(PackageManager.PERMISSION_GRANTED, retValue); 1313 1314 retValue = mContext.checkCallingOrSelfPermission(NOT_GRANTED_PERMISSION); 1315 assertEquals(PackageManager.PERMISSION_DENIED, retValue); 1316 } 1317 testCheckCallingOrSelfPermission_ipc()1318 public void testCheckCallingOrSelfPermission_ipc() throws Exception { 1319 bindBinderPermissionTestService(); 1320 try { 1321 int retValue = mBinderPermissionTestService.doCheckCallingOrSelfPermission( 1322 GRANTED_PERMISSION); 1323 assertEquals(PackageManager.PERMISSION_GRANTED, retValue); 1324 1325 retValue = mBinderPermissionTestService.doCheckCallingOrSelfPermission( 1326 NOT_GRANTED_PERMISSION); 1327 assertEquals(PackageManager.PERMISSION_DENIED, retValue); 1328 } finally { 1329 mContext.unbindService(mBinderPermissionTestConnection); 1330 } 1331 } 1332 testEnforceCallingOrSelfPermission_noIpc()1333 public void testEnforceCallingOrSelfPermission_noIpc() { 1334 // There's no ongoing Binder call, so this package's permissions are checked. 1335 mContext.enforceCallingOrSelfPermission( 1336 GRANTED_PERMISSION, "permission isn't granted"); 1337 1338 try { 1339 mContext.enforceCallingOrSelfPermission( 1340 NOT_GRANTED_PERMISSION, "permission isn't granted"); 1341 fail("Permission shouldn't be granted."); 1342 } catch (SecurityException expected) { 1343 } 1344 } 1345 testEnforceCallingOrSelfPermission_ipc()1346 public void testEnforceCallingOrSelfPermission_ipc() throws Exception { 1347 bindBinderPermissionTestService(); 1348 try { 1349 mBinderPermissionTestService.doEnforceCallingOrSelfPermission(GRANTED_PERMISSION); 1350 1351 try { 1352 mBinderPermissionTestService.doEnforceCallingOrSelfPermission( 1353 NOT_GRANTED_PERMISSION); 1354 fail("Permission shouldn't be granted."); 1355 } catch (SecurityException expected) { 1356 } 1357 } finally { 1358 mContext.unbindService(mBinderPermissionTestConnection); 1359 } 1360 } 1361 testCheckCallingPermission_noIpc()1362 public void testCheckCallingPermission_noIpc() { 1363 // Denied because no IPC is active. 1364 int retValue = mContext.checkCallingPermission(GRANTED_PERMISSION); 1365 assertEquals(PackageManager.PERMISSION_DENIED, retValue); 1366 } 1367 testEnforceCallingPermission_noIpc()1368 public void testEnforceCallingPermission_noIpc() { 1369 try { 1370 mContext.enforceCallingPermission( 1371 GRANTED_PERMISSION, 1372 "enforceCallingPermission is not working without possessing an IPC."); 1373 fail("enforceCallingPermission is not working without possessing an IPC."); 1374 } catch (SecurityException e) { 1375 // Currently no IPC is handled by this process, this exception is expected 1376 } 1377 } 1378 testEnforceCallingPermission_ipc()1379 public void testEnforceCallingPermission_ipc() throws Exception { 1380 bindBinderPermissionTestService(); 1381 try { 1382 mBinderPermissionTestService.doEnforceCallingPermission(GRANTED_PERMISSION); 1383 1384 try { 1385 mBinderPermissionTestService.doEnforceCallingPermission(NOT_GRANTED_PERMISSION); 1386 fail("Permission shouldn't be granted."); 1387 } catch (SecurityException expected) { 1388 } 1389 } finally { 1390 mContext.unbindService(mBinderPermissionTestConnection); 1391 } 1392 } 1393 testCheckCallingPermission_ipc()1394 public void testCheckCallingPermission_ipc() throws Exception { 1395 bindBinderPermissionTestService(); 1396 try { 1397 int returnValue = mBinderPermissionTestService.doCheckCallingPermission( 1398 GRANTED_PERMISSION); 1399 assertEquals(PackageManager.PERMISSION_GRANTED, returnValue); 1400 1401 returnValue = mBinderPermissionTestService.doCheckCallingPermission( 1402 NOT_GRANTED_PERMISSION); 1403 assertEquals(PackageManager.PERMISSION_DENIED, returnValue); 1404 } finally { 1405 mContext.unbindService(mBinderPermissionTestConnection); 1406 } 1407 } 1408 bindBinderPermissionTestService()1409 private void bindBinderPermissionTestService() { 1410 Intent intent = new Intent(mContext, IBinderPermissionTestService.class); 1411 intent.setComponent(new ComponentName( 1412 "com.android.cts", "com.android.cts.BinderPermissionTestService")); 1413 1414 mBinderPermissionTestConnection = new ServiceConnection() { 1415 @Override 1416 public void onServiceConnected(ComponentName componentName, IBinder iBinder) { 1417 mBinderPermissionTestService = 1418 IBinderPermissionTestService.Stub.asInterface(iBinder); 1419 } 1420 1421 @Override 1422 public void onServiceDisconnected(ComponentName componentName) { 1423 } 1424 }; 1425 1426 assertTrue("Service not bound", mContext.bindService( 1427 intent, mBinderPermissionTestConnection, Context.BIND_AUTO_CREATE)); 1428 1429 new PollingCheck(15 * 1000) { 1430 protected boolean check() { 1431 return mBinderPermissionTestService != null; // Service was bound. 1432 } 1433 }.run(); 1434 } 1435 testCheckUriPermissions()1436 public void testCheckUriPermissions() { 1437 List<Uri> uris = new ArrayList<>(); 1438 Uri uri1 = Uri.parse("content://ctstest1"); 1439 uris.add(uri1); 1440 Uri uri2 = Uri.parse("content://ctstest2"); 1441 uris.add(uri2); 1442 1443 // Root has access to all URIs 1444 int[] retValue = mContext.checkUriPermissions(uris, Binder.getCallingPid(), 0, 1445 Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1446 assertEquals(retValue.length, 2); 1447 assertEquals(PERMISSION_GRANTED, retValue[0]); 1448 assertEquals(PERMISSION_GRANTED, retValue[1]); 1449 1450 retValue = mContext.checkUriPermissions(uris, Binder.getCallingPid(), 1451 Binder.getCallingUid(), Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1452 assertEquals(retValue.length, 2); 1453 // This package does not have access to the given URIs 1454 assertEquals(PERMISSION_DENIED, retValue[0]); 1455 assertEquals(PERMISSION_DENIED, retValue[1]); 1456 } 1457 testCheckUriPermission1()1458 public void testCheckUriPermission1() { 1459 Uri uri = Uri.parse("content://ctstest"); 1460 1461 int retValue = mContext.checkUriPermission(uri, Binder.getCallingPid(), 0, 1462 Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1463 assertEquals(PackageManager.PERMISSION_GRANTED, retValue); 1464 1465 retValue = mContext.checkUriPermission(uri, Binder.getCallingPid(), 1466 Binder.getCallingUid(), Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1467 assertEquals(PackageManager.PERMISSION_DENIED, retValue); 1468 } 1469 testCheckUriPermission2()1470 public void testCheckUriPermission2() { 1471 Uri uri = Uri.parse("content://ctstest"); 1472 1473 int retValue = mContext.checkUriPermission(uri, NOT_GRANTED_PERMISSION, 1474 NOT_GRANTED_PERMISSION, Binder.getCallingPid(), 0, 1475 Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1476 assertEquals(PackageManager.PERMISSION_GRANTED, retValue); 1477 1478 retValue = mContext.checkUriPermission(uri, NOT_GRANTED_PERMISSION, 1479 NOT_GRANTED_PERMISSION, Binder.getCallingPid(), Binder.getCallingUid(), 1480 Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1481 assertEquals(PackageManager.PERMISSION_DENIED, retValue); 1482 } 1483 testCheckCallingUriPermissions()1484 public void testCheckCallingUriPermissions() { 1485 List<Uri> uris = new ArrayList<>(); 1486 Uri uri1 = Uri.parse("content://ctstest1"); 1487 uris.add(uri1); 1488 Uri uri2 = Uri.parse("content://ctstest2"); 1489 uris.add(uri2); 1490 1491 int[] retValue = mContext.checkCallingUriPermissions(uris, 1492 Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1493 assertEquals(retValue.length, 2); 1494 // This package does not have access to the given URIs 1495 assertEquals(PERMISSION_DENIED, retValue[0]); 1496 assertEquals(PERMISSION_DENIED, retValue[1]); 1497 } 1498 testCheckCallingUriPermission()1499 public void testCheckCallingUriPermission() { 1500 Uri uri = Uri.parse("content://ctstest"); 1501 1502 int retValue = mContext.checkCallingUriPermission(uri, 1503 Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1504 assertEquals(PackageManager.PERMISSION_DENIED, retValue); 1505 } 1506 testEnforceCallingUriPermission()1507 public void testEnforceCallingUriPermission() { 1508 try { 1509 Uri uri = Uri.parse("content://ctstest"); 1510 mContext.enforceCallingUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION, 1511 "enforceCallingUriPermission is not working without possessing an IPC."); 1512 fail("enforceCallingUriPermission is not working without possessing an IPC."); 1513 } catch (SecurityException e) { 1514 // If the function is OK, it should throw a SecurityException here because currently no 1515 // IPC is handled by this process. 1516 } 1517 } 1518 testGetDir()1519 public void testGetDir() { 1520 File dir = mContext.getDir("testpath", Context.MODE_PRIVATE); 1521 assertNotNull(dir); 1522 dir.delete(); 1523 } 1524 testGetPackageManager()1525 public void testGetPackageManager() { 1526 assertSame(mContext.getPackageManager(), mContext.getPackageManager()); 1527 } 1528 testSendBroadcast1()1529 public void testSendBroadcast1() throws InterruptedException { 1530 final ResultReceiver receiver = new ResultReceiver(); 1531 1532 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION)); 1533 1534 mContext.sendBroadcast(new Intent(ResultReceiver.MOCK_ACTION)); 1535 1536 new PollingCheck(BROADCAST_TIMEOUT){ 1537 @Override 1538 protected boolean check() { 1539 return receiver.hasReceivedBroadCast(); 1540 } 1541 }.run(); 1542 } 1543 testSendBroadcast2()1544 public void testSendBroadcast2() throws InterruptedException { 1545 final ResultReceiver receiver = new ResultReceiver(); 1546 1547 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION)); 1548 1549 mContext.sendBroadcast(new Intent(ResultReceiver.MOCK_ACTION), null); 1550 1551 new PollingCheck(BROADCAST_TIMEOUT){ 1552 @Override 1553 protected boolean check() { 1554 return receiver.hasReceivedBroadCast(); 1555 } 1556 }.run(); 1557 } 1558 1559 /** The receiver should get the broadcast if it has all the permissions. */ testSendBroadcastWithMultiplePermissions_receiverHasAllPermissions()1560 public void testSendBroadcastWithMultiplePermissions_receiverHasAllPermissions() 1561 throws Exception { 1562 final ResultReceiver receiver = new ResultReceiver(); 1563 1564 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION)); 1565 1566 mContext.sendBroadcastWithMultiplePermissions( 1567 new Intent(ResultReceiver.MOCK_ACTION), 1568 new String[] { // this test APK has both these permissions 1569 android.Manifest.permission.ACCESS_WIFI_STATE, 1570 android.Manifest.permission.ACCESS_NETWORK_STATE, 1571 }); 1572 1573 new PollingCheck(BROADCAST_TIMEOUT) { 1574 @Override 1575 protected boolean check() { 1576 return receiver.hasReceivedBroadCast(); 1577 } 1578 }.run(); 1579 } 1580 1581 /** The receiver should not get the broadcast if it does not have all the permissions. */ testSendBroadcastWithMultiplePermissions_receiverHasSomePermissions()1582 public void testSendBroadcastWithMultiplePermissions_receiverHasSomePermissions() 1583 throws Exception { 1584 final ResultReceiver receiver = new ResultReceiver(); 1585 1586 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION)); 1587 1588 mContext.sendBroadcastWithMultiplePermissions( 1589 new Intent(ResultReceiver.MOCK_ACTION), 1590 new String[] { // this test APK only has ACCESS_WIFI_STATE 1591 android.Manifest.permission.ACCESS_WIFI_STATE, 1592 android.Manifest.permission.NETWORK_STACK, 1593 }); 1594 1595 Thread.sleep(BROADCAST_TIMEOUT); 1596 assertFalse(receiver.hasReceivedBroadCast()); 1597 } 1598 1599 /** The receiver should not get the broadcast if it has none of the permissions. */ testSendBroadcastWithMultiplePermissions_receiverHasNoPermissions()1600 public void testSendBroadcastWithMultiplePermissions_receiverHasNoPermissions() 1601 throws Exception { 1602 final ResultReceiver receiver = new ResultReceiver(); 1603 1604 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION)); 1605 1606 mContext.sendBroadcastWithMultiplePermissions( 1607 new Intent(ResultReceiver.MOCK_ACTION), 1608 new String[] { // this test APK has neither of these permissions 1609 android.Manifest.permission.NETWORK_SETTINGS, 1610 android.Manifest.permission.NETWORK_STACK, 1611 }); 1612 1613 Thread.sleep(BROADCAST_TIMEOUT); 1614 assertFalse(receiver.hasReceivedBroadCast()); 1615 } 1616 testEnforceCallingOrSelfUriPermission()1617 public void testEnforceCallingOrSelfUriPermission() { 1618 try { 1619 Uri uri = Uri.parse("content://ctstest"); 1620 mContext.enforceCallingOrSelfUriPermission(uri, 1621 Intent.FLAG_GRANT_WRITE_URI_PERMISSION, 1622 "enforceCallingOrSelfUriPermission is not working without possessing an IPC."); 1623 fail("enforceCallingOrSelfUriPermission is not working without possessing an IPC."); 1624 } catch (SecurityException e) { 1625 // If the function is OK, it should throw a SecurityException here because currently no 1626 // IPC is handled by this process. 1627 } 1628 } 1629 testGetAssets()1630 public void testGetAssets() { 1631 assertSame(mContext.getAssets(), mContext.getAssets()); 1632 } 1633 testGetResources()1634 public void testGetResources() { 1635 assertSame(mContext.getResources(), mContext.getResources()); 1636 } 1637 testStartInstrumentation()1638 public void testStartInstrumentation() { 1639 // Use wrong name 1640 ComponentName cn = new ComponentName("com.android", 1641 "com.android.content.FalseLocalSampleInstrumentation"); 1642 assertNotNull(cn); 1643 assertNotNull(mContext); 1644 // If the target instrumentation is wrong, the function should return false. 1645 assertFalse(mContext.startInstrumentation(cn, null, null)); 1646 } 1647 bindExpectResult(Context context, Intent service)1648 private void bindExpectResult(Context context, Intent service) 1649 throws InterruptedException { 1650 if (service == null) { 1651 fail("No service created!"); 1652 } 1653 TestConnection conn = new TestConnection(true, false); 1654 1655 context.bindService(service, conn, Context.BIND_AUTO_CREATE); 1656 context.startService(service); 1657 1658 // Wait for a short time, so the service related operations could be 1659 // working. 1660 synchronized (this) { 1661 wait(2500); 1662 } 1663 // Test stop Service 1664 assertTrue(context.stopService(service)); 1665 context.unbindService(conn); 1666 1667 synchronized (this) { 1668 wait(1000); 1669 } 1670 } 1671 1672 private interface Condition { onCondition()1673 public boolean onCondition(); 1674 } 1675 waitForCondition(Condition con)1676 private synchronized void waitForCondition(Condition con) throws InterruptedException { 1677 // check the condition every 1 second until the condition is fulfilled 1678 // and wait for 3 seconds at most 1679 for (int i = 0; !con.onCondition() && i <= 3; i++) { 1680 wait(1000); 1681 } 1682 } 1683 waitForReceiveBroadCast(final ResultReceiver receiver)1684 private void waitForReceiveBroadCast(final ResultReceiver receiver) 1685 throws InterruptedException { 1686 Condition con = new Condition() { 1687 public boolean onCondition() { 1688 return receiver.hasReceivedBroadCast(); 1689 } 1690 }; 1691 waitForCondition(con); 1692 } 1693 waitForFilteredIntent(Context context, final String action)1694 private void waitForFilteredIntent(Context context, final String action) 1695 throws InterruptedException { 1696 context.sendBroadcast(new Intent(action), null); 1697 1698 synchronized (mLockObj) { 1699 mLockObj.wait(BROADCAST_TIMEOUT); 1700 } 1701 } 1702 1703 private final class TestBroadcastReceiver extends BroadcastReceiver { 1704 boolean mHadReceivedBroadCast; 1705 boolean mIsOrderedBroadcasts; 1706 1707 @Override onReceive(Context context, Intent intent)1708 public void onReceive(Context context, Intent intent) { 1709 synchronized (this) { 1710 if (mIsOrderedBroadcasts) { 1711 setResultCode(3); 1712 setResultData(ACTUAL_RESULT); 1713 } 1714 1715 Bundle map = getResultExtras(false); 1716 if (map != null) { 1717 map.remove(KEY_REMOVED); 1718 map.putString(KEY_ADDED, VALUE_ADDED); 1719 } 1720 mHadReceivedBroadCast = true; 1721 this.notifyAll(); 1722 } 1723 1724 synchronized (mLockObj) { 1725 mLockObj.notify(); 1726 } 1727 } 1728 hadReceivedBroadCast()1729 boolean hadReceivedBroadCast() { 1730 return mHadReceivedBroadCast; 1731 } 1732 reset()1733 void reset(){ 1734 mHadReceivedBroadCast = false; 1735 } 1736 } 1737 1738 private class FilteredReceiver extends BroadcastReceiver { 1739 private boolean mHadReceivedBroadCast1 = false; 1740 private boolean mHadReceivedBroadCast2 = false; 1741 onReceive(Context context, Intent intent)1742 public void onReceive(Context context, Intent intent) { 1743 String action = intent.getAction(); 1744 if (MOCK_ACTION1.equals(action)) { 1745 mHadReceivedBroadCast1 = true; 1746 } else if (MOCK_ACTION2.equals(action)) { 1747 mHadReceivedBroadCast2 = true; 1748 } 1749 1750 synchronized (mLockObj) { 1751 mLockObj.notify(); 1752 } 1753 } 1754 hadReceivedBroadCast1()1755 public boolean hadReceivedBroadCast1() { 1756 return mHadReceivedBroadCast1; 1757 } 1758 hadReceivedBroadCast2()1759 public boolean hadReceivedBroadCast2() { 1760 return mHadReceivedBroadCast2; 1761 } 1762 reset()1763 public void reset(){ 1764 mHadReceivedBroadCast1 = false; 1765 mHadReceivedBroadCast2 = false; 1766 } 1767 } 1768 1769 private class TestConnection implements ServiceConnection { TestConnection(boolean expectDisconnect, boolean setReporter)1770 public TestConnection(boolean expectDisconnect, boolean setReporter) { 1771 } 1772 setMonitor(boolean v)1773 void setMonitor(boolean v) { 1774 } 1775 onServiceConnected(ComponentName name, IBinder service)1776 public void onServiceConnected(ComponentName name, IBinder service) { 1777 } 1778 onServiceDisconnected(ComponentName name)1779 public void onServiceDisconnected(ComponentName name) { 1780 } 1781 } 1782 testOpenFileOutput_mustNotCreateWorldReadableFile()1783 public void testOpenFileOutput_mustNotCreateWorldReadableFile() throws Exception { 1784 try { 1785 mContext.openFileOutput("test.txt", Context.MODE_WORLD_READABLE); 1786 fail("Exception expected"); 1787 } catch (SecurityException expected) { 1788 } 1789 } 1790 testOpenFileOutput_mustNotCreateWorldWriteableFile()1791 public void testOpenFileOutput_mustNotCreateWorldWriteableFile() throws Exception { 1792 try { 1793 mContext.openFileOutput("test.txt", Context.MODE_WORLD_WRITEABLE); 1794 fail("Exception expected"); 1795 } catch (SecurityException expected) { 1796 } 1797 } 1798 testOpenFileOutput_mustNotWriteToParentDirectory()1799 public void testOpenFileOutput_mustNotWriteToParentDirectory() throws Exception { 1800 try { 1801 // Created files must be under the application's private directory. 1802 mContext.openFileOutput("../test.txt", Context.MODE_PRIVATE); 1803 fail("Exception expected"); 1804 } catch (IllegalArgumentException expected) { 1805 } 1806 } 1807 testOpenFileOutput_mustNotUseAbsolutePath()1808 public void testOpenFileOutput_mustNotUseAbsolutePath() throws Exception { 1809 try { 1810 // Created files must be under the application's private directory. 1811 mContext.openFileOutput("/tmp/test.txt", Context.MODE_PRIVATE); 1812 fail("Exception expected"); 1813 } catch (IllegalArgumentException expected) { 1814 } 1815 } 1816 isWallpaperSupported()1817 private boolean isWallpaperSupported() { 1818 return WallpaperManager.getInstance(mContext).isWallpaperSupported(); 1819 } 1820 } 1821