1 /* 2 * Copyright 2018 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 * https://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.res.cts; 18 19 import android.content.Context; 20 import android.content.cts.R; 21 import android.content.cts.util.XmlUtils; 22 import android.content.pm.ActivityInfo; 23 import android.content.res.AssetManager; 24 import android.content.res.ColorStateList; 25 import android.content.res.Configuration; 26 import android.content.res.Resources; 27 import android.content.res.Resources.NotFoundException; 28 import android.content.res.TypedArray; 29 import android.content.res.XmlResourceParser; 30 import android.graphics.Paint; 31 import android.graphics.Typeface; 32 import android.graphics.drawable.AdaptiveIconDrawable; 33 import android.graphics.drawable.ColorDrawable; 34 import android.graphics.drawable.ColorStateListDrawable; 35 import android.graphics.drawable.Drawable; 36 import android.os.Bundle; 37 import android.os.LocaleList; 38 import android.test.AndroidTestCase; 39 import android.util.AttributeSet; 40 import android.util.DisplayMetrics; 41 import android.util.TypedValue; 42 import android.util.Xml; 43 import android.view.Display; 44 import android.view.LayoutInflater; 45 import android.view.View; 46 import android.view.WindowManager; 47 48 import org.xmlpull.v1.XmlPullParser; 49 import org.xmlpull.v1.XmlPullParserException; 50 51 import java.io.IOException; 52 import java.io.InputStream; 53 import java.util.Locale; 54 55 public class ResourcesTest extends AndroidTestCase { 56 private static final String CONFIG_VARYING = "configVarying"; 57 private static final String SIMPLE = "simple"; 58 private static final String CONFIG_VARYING_SIMPLE = "configVarying/simple"; 59 private static final String PACKAGE_NAME = "android.content.cts"; 60 private static final String COM_ANDROID_CTS_STUB_IDENTIFIER = 61 "android.content.cts:configVarying/simple"; 62 private Resources mResources; 63 64 @Override setUp()65 protected void setUp() throws Exception { 66 super.setUp(); 67 68 mResources = getContext().getResources(); 69 } 70 testIdNull()71 public void testIdNull() { 72 assertEquals(0, Resources.ID_NULL); 73 } 74 testResources()75 public void testResources() { 76 final AssetManager am = new AssetManager(); 77 final Configuration cfg = new Configuration(); 78 cfg.keyboard = Configuration.KEYBOARDHIDDEN_YES; 79 final DisplayMetrics dm = new DisplayMetrics(); 80 dm.setToDefaults(); 81 82 final Resources r = new Resources(am, dm, cfg); 83 final Configuration c = r.getConfiguration(); 84 assertEquals(Configuration.KEYBOARDHIDDEN_YES, c.keyboard); 85 } 86 testGetString()87 public void testGetString() { 88 try { 89 mResources.getString(-1, "%s"); 90 fail("Failed at testGetString2"); 91 } catch (NotFoundException e) { 92 //expected 93 } 94 95 final String strGo = mResources.getString(R.string.go, "%1$s%%", 12); 96 assertEquals("Go", strGo); 97 } 98 testObtainAttributes()99 public void testObtainAttributes() throws XmlPullParserException, IOException { 100 final XmlPullParser parser = mResources.getXml(R.xml.test_color); 101 XmlUtils.beginDocument(parser, "resources"); 102 final AttributeSet set = Xml.asAttributeSet(parser); 103 final TypedArray testTypedArray = mResources.obtainAttributes(set, R.styleable.Style1); 104 assertNotNull(testTypedArray); 105 assertEquals(2, testTypedArray.length()); 106 assertEquals(0, testTypedArray.getColor(0, 0)); 107 assertEquals(128, testTypedArray.getColor(1, 128)); 108 assertEquals(mResources, testTypedArray.getResources()); 109 testTypedArray.recycle(); 110 } 111 testObtainTypedArray()112 public void testObtainTypedArray() { 113 try { 114 mResources.obtainTypedArray(-1); 115 fail("Failed at testObtainTypedArray"); 116 } catch (NotFoundException e) { 117 //expected 118 } 119 120 final TypedArray ta = mResources.obtainTypedArray(R.array.string); 121 assertEquals(3, ta.length()); 122 assertEquals("Test String 1", ta.getString(0)); 123 assertEquals("Test String 2", ta.getString(1)); 124 assertEquals("Test String 3", ta.getString(2)); 125 assertEquals(mResources, ta.getResources()); 126 } 127 getResources(final Configuration config, final int mcc, final int mnc, final int touchscreen, final int keyboard, final int keysHidden, final int navigation, final int width, final int height)128 private Resources getResources(final Configuration config, final int mcc, final int mnc, 129 final int touchscreen, final int keyboard, final int keysHidden, final int navigation, 130 final int width, final int height) { 131 final AssetManager assmgr = new AssetManager(); 132 assmgr.addAssetPath(mContext.getPackageResourcePath()); 133 final DisplayMetrics metrics = new DisplayMetrics(); 134 final WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); 135 final Display d = wm.getDefaultDisplay(); 136 d.getMetrics(metrics); 137 config.mcc = mcc; 138 config.mnc = mnc; 139 config.touchscreen = touchscreen; 140 config.keyboard = keyboard; 141 config.keyboardHidden = keysHidden; 142 config.navigation = navigation; 143 metrics.widthPixels = width; 144 metrics.heightPixels = height; 145 return new Resources(assmgr, metrics, config); 146 } 147 checkGetText1(final Resources res, final int resId, final String expectedValue)148 private static void checkGetText1(final Resources res, final int resId, 149 final String expectedValue) { 150 final String actual = res.getText(resId).toString(); 151 assertNotNull("Returned wrong configuration-based simple value: expected <nothing>, " 152 + "got '" + actual + "' from resource 0x" + Integer.toHexString(resId), 153 expectedValue); 154 assertEquals("Returned wrong configuration-based simple value: expected " + expectedValue 155 + ", got '" + actual + "' from resource 0x" + Integer.toHexString(resId), 156 expectedValue, actual); 157 } 158 checkGetText2(final Resources res, final int resId, final String expectedValue)159 private static void checkGetText2(final Resources res, final int resId, 160 final String expectedValue) { 161 final String actual = res.getText(resId, null).toString(); 162 assertNotNull("Returned wrong configuration-based simple value: expected <nothing>, " 163 + "got '" + actual + "' from resource 0x" + Integer.toHexString(resId), 164 expectedValue); 165 assertEquals("Returned wrong configuration-based simple value: expected " + expectedValue 166 + ", got '" + actual + "' from resource 0x" + Integer.toHexString(resId), 167 expectedValue, actual); 168 } 169 testGetMovie()170 public void testGetMovie() { 171 try { 172 mResources.getMovie(-1); 173 fail("Failed at testGetMovie"); 174 } catch (NotFoundException e) { 175 //expected 176 } 177 } 178 testGetDimension()179 public void testGetDimension() { 180 try { 181 mResources.getDimension(-1); 182 fail("Failed at testGetDimension"); 183 } catch (NotFoundException e) { 184 //expected 185 } 186 187 // app_icon_size is 48px, as defined in cts/tests/res/values/resources_test.xml 188 final float dim = mResources.getDimension(R.dimen.app_icon_size); 189 assertEquals(48.0f, dim); 190 } 191 testGetDimensionPixelOffset()192 public void testGetDimensionPixelOffset() { 193 try { 194 mResources.getDimensionPixelOffset(-1); 195 fail("Failed at testGetDimensionPixelOffset"); 196 } catch (NotFoundException e) { 197 //expected 198 } 199 200 // app_icon_size is 48px, as defined in cts/tests/res/values/resources_test.xml 201 final int dim = mResources.getDimensionPixelOffset(R.dimen.app_icon_size); 202 assertEquals(48, dim); 203 } 204 testGetColorStateList()205 public void testGetColorStateList() { 206 try { 207 mResources.getColorStateList(-1); 208 fail("Failed at testGetColorStateList"); 209 } catch (NotFoundException e) { 210 //expected 211 } 212 213 final ColorStateList colorStateList = mResources.getColorStateList(R.color.color1); 214 final int[] focusedState = {android.R.attr.state_focused}; 215 final int focusColor = colorStateList.getColorForState(focusedState, R.color.failColor); 216 assertEquals(mResources.getColor(R.color.testcolor1), focusColor); 217 } 218 testGetColorStateListThrows()219 public void testGetColorStateListThrows() { 220 try { 221 // XML that's not a selector or gradient throws 222 mResources.getColorStateList(R.drawable.density_test); 223 fail("Failed at testGetColorStateList"); 224 } catch (NotFoundException expected) { 225 // expected 226 } 227 } 228 testGetColor()229 public void testGetColor() { 230 try { 231 mResources.getColor(-1); 232 fail("Failed at testGetColor"); 233 } catch (NotFoundException e) { 234 //expected 235 } 236 237 final int color = mResources.getColor(R.color.testcolor1); 238 assertEquals(0xff00ff00, color); 239 } 240 createNewResources()241 public Resources createNewResources() { 242 final DisplayMetrics dm = new DisplayMetrics(); 243 dm.setToDefaults(); 244 final Configuration cfg = new Configuration(); 245 cfg.setToDefaults(); 246 return new Resources(new AssetManager(), dm, cfg); 247 } 248 testUpdateConfiguration()249 public void testUpdateConfiguration() { 250 Resources res = createNewResources(); 251 final Configuration cfg = new Configuration(res.getConfiguration()); 252 assertTrue(cfg.fontScale != 5); 253 254 cfg.fontScale = 5; 255 res.updateConfiguration(cfg, null); 256 assertEquals(5.0f, res.getConfiguration().fontScale, 0.001f); 257 } 258 testUpdateConfiguration_emptyLocaleIsOverridden()259 public void testUpdateConfiguration_emptyLocaleIsOverridden() { 260 Resources res = createNewResources(); 261 res.getConfiguration().setLocales(null); 262 assertTrue(res.getConfiguration().getLocales().isEmpty()); 263 264 final Configuration cfg = new Configuration(); 265 cfg.setToDefaults(); 266 assertTrue(cfg.getLocales().isEmpty()); 267 268 res.updateConfiguration(cfg, null); 269 assertEquals(LocaleList.getDefault(), res.getConfiguration().getLocales()); 270 } 271 testUpdateConfiguration_copyLocales()272 public void testUpdateConfiguration_copyLocales() { 273 Resources res = createNewResources(); 274 final Configuration cfg = new Configuration(res.getConfiguration()); 275 276 cfg.setLocales(LocaleList.forLanguageTags("az-Arab,ru")); 277 278 res.updateConfiguration(cfg, null); 279 280 // Depending on the locales available in the framework resources, the LocaleList may be 281 // re-arranged. Check that any valid permutation is present. 282 final LocaleList locales = res.getConfiguration().getLocales(); 283 assertTrue(LocaleList.forLanguageTags("az-Arab,ru").equals(locales) || 284 LocaleList.forLanguageTags("ru,az-Arab").equals(locales)); 285 } 286 testUpdateConfiguration_emptyAfterUpdate()287 public void testUpdateConfiguration_emptyAfterUpdate() { 288 Resources res = createNewResources(); 289 final Configuration cfg = new Configuration(res.getConfiguration()); 290 cfg.setLocales(LocaleList.forLanguageTags("az-Arab")); 291 292 res.updateConfiguration(cfg, null); 293 assertEquals(LocaleList.forLanguageTags("az-Arab"), res.getConfiguration().getLocales()); 294 295 res.getConfiguration().setLocales(null); 296 cfg.setLocales(null); 297 res.updateConfiguration(cfg, null); 298 assertEquals(LocaleList.getDefault(), res.getConfiguration().getLocales()); 299 } 300 testGetDimensionPixelSize()301 public void testGetDimensionPixelSize() { 302 try { 303 mResources.getDimensionPixelSize(-1); 304 fail("Failed at testGetDimensionPixelSize"); 305 } catch (NotFoundException e) { 306 //expected 307 } 308 309 // app_icon_size is 48px, as defined in cts/tests/res/values/resources_test.xml 310 final int size = mResources.getDimensionPixelSize(R.dimen.app_icon_size); 311 assertEquals(48, size); 312 assertEquals(1, mResources.getDimensionPixelSize(R.dimen.pos_dimen_149)); 313 assertEquals(2, mResources.getDimensionPixelSize(R.dimen.pos_dimen_151)); 314 assertEquals(-1, mResources.getDimensionPixelSize(R.dimen.neg_dimen_149)); 315 assertEquals(-2, mResources.getDimensionPixelSize(R.dimen.neg_dimen_151)); 316 } 317 testGetDrawable()318 public void testGetDrawable() { 319 try { 320 mResources.getDrawable(-1); 321 fail("Failed at testGetDrawable"); 322 } catch (NotFoundException e) { 323 //expected 324 } 325 326 // testimage is defined in cts/tests/res/drawable/testimage.jpg and measures 212px x 142px 327 final Drawable draw = mResources.getDrawable(R.drawable.testimage); 328 int targetDensity = mResources.getDisplayMetrics().densityDpi; 329 int defaultDensity = DisplayMetrics.DENSITY_DEFAULT; 330 assertNotNull(draw); 331 assertEquals(212 * targetDensity / defaultDensity, draw.getIntrinsicWidth(), 1); 332 assertEquals(142 * targetDensity / defaultDensity, draw.getIntrinsicHeight(), 1); 333 334 // Some apps rely on the fact that this will return null (rather than throwing). 335 assertNull(mResources.getDrawable(R.drawable.fake_image_will_not_decode)); 336 } 337 testGetDrawable_ColorResource()338 public void testGetDrawable_ColorResource() { 339 final Drawable drawable = mResources.getDrawable(R.color.testcolor1, null); 340 assertTrue(drawable instanceof ColorDrawable); 341 assertEquals( 342 mResources.getColor(R.color.testcolor1, null), 343 ((ColorDrawable) drawable).getColor() 344 ); 345 } 346 testGetDrawable_ColorStateListResource()347 public void testGetDrawable_ColorStateListResource() { 348 final Drawable drawable = mResources.getDrawable(R.color.testcolor, null); 349 assertTrue(drawable instanceof ColorStateListDrawable); 350 351 final ColorStateList colorStateList = mResources.getColorStateList( 352 R.color.testcolor, null); 353 assertEquals( 354 colorStateList.getDefaultColor(), 355 ((ColorStateListDrawable) drawable).getColorStateList().getDefaultColor()); 356 } 357 testGetDrawable_ColorStateListConfigurations()358 public void testGetDrawable_ColorStateListConfigurations() { 359 final Configuration dayConfiguration = new Configuration(mResources.getConfiguration()); 360 final Configuration nightConfiguration = new Configuration(mResources.getConfiguration()); 361 362 dayConfiguration.uiMode = dayConfiguration.uiMode 363 & (~Configuration.UI_MODE_NIGHT_MASK) 364 | Configuration.UI_MODE_NIGHT_NO; 365 366 nightConfiguration.uiMode = nightConfiguration.uiMode 367 & (~Configuration.UI_MODE_NIGHT_MASK) 368 | Configuration.UI_MODE_NIGHT_YES; 369 370 final ColorStateListDrawable dayDrawable = (ColorStateListDrawable) getContext() 371 .createConfigurationContext(dayConfiguration) 372 .getResources() 373 .getDrawable(R.color.testcolor_daynight, null); 374 375 final ColorStateListDrawable nightDrawable = (ColorStateListDrawable) getContext() 376 .createConfigurationContext(nightConfiguration) 377 .getResources() 378 .getDrawable(R.color.testcolor_daynight, null); 379 380 assertEquals( 381 mResources.getColor(android.R.color.white, null), 382 dayDrawable.getColorStateList().getDefaultColor()); 383 384 assertEquals( 385 mResources.getColor(android.R.color.black, null), 386 nightDrawable.getColorStateList().getDefaultColor()); 387 388 assertEquals(ActivityInfo.CONFIG_UI_MODE, dayDrawable.getChangingConfigurations()); 389 assertEquals(ActivityInfo.CONFIG_UI_MODE, nightDrawable.getChangingConfigurations()); 390 } 391 testGetDrawable_StackOverflowErrorDrawable()392 public void testGetDrawable_StackOverflowErrorDrawable() { 393 try { 394 mResources.getDrawable(R.drawable.drawable_recursive); 395 fail("Failed at testGetDrawable_StackOverflowErrorDrawable"); 396 } catch (NotFoundException e) { 397 //expected 398 } 399 } 400 testGetDrawable_StackOverflowErrorDrawable_mipmap()401 public void testGetDrawable_StackOverflowErrorDrawable_mipmap() { 402 try { 403 mResources.getDrawable(R.mipmap.icon_recursive); 404 fail("Failed at testGetDrawable_StackOverflowErrorDrawable_mipmap"); 405 } catch (NotFoundException e) { 406 //expected 407 } 408 } 409 testGetDrawableForDensity()410 public void testGetDrawableForDensity() { 411 final Drawable ldpi = mResources.getDrawableForDensity( 412 R.drawable.density_test, DisplayMetrics.DENSITY_LOW); 413 assertEquals(300, ldpi.getIntrinsicWidth()); 414 415 final Drawable mdpi = mResources.getDrawableForDensity( 416 R.drawable.density_test, DisplayMetrics.DENSITY_MEDIUM); 417 assertEquals(200, mdpi.getIntrinsicWidth()); 418 419 final Drawable hdpi = mResources.getDrawableForDensity( 420 R.drawable.density_test, DisplayMetrics.DENSITY_HIGH); 421 assertEquals(100, hdpi.getIntrinsicWidth()); 422 } 423 testGetDrawableForDensityWithZeroDensityIsSameAsGetDrawable()424 public void testGetDrawableForDensityWithZeroDensityIsSameAsGetDrawable() { 425 final Drawable defaultDrawable = mResources.getDrawable(R.drawable.density_test, null); 426 assertNotNull(defaultDrawable); 427 428 final Drawable densityDrawable = mResources.getDrawableForDensity(R.drawable.density_test, 429 0 /*density*/, null); 430 assertNotNull(densityDrawable); 431 432 assertEquals(defaultDrawable.getIntrinsicWidth(), densityDrawable.getIntrinsicWidth()); 433 } 434 extractForegroundFromAdaptiveIconDrawable(int id, int density)435 private Drawable extractForegroundFromAdaptiveIconDrawable(int id, int density) { 436 final Drawable drawable = mResources.getDrawableForDensity(id, density, null); 437 assertTrue(drawable instanceof AdaptiveIconDrawable); 438 return ((AdaptiveIconDrawable) drawable).getForeground(); 439 } 440 testGetDrawableForDensityWithAdaptiveIconDrawable()441 public void testGetDrawableForDensityWithAdaptiveIconDrawable() { 442 final Drawable ldpi = extractForegroundFromAdaptiveIconDrawable(R.drawable.adaptive_icon, 443 DisplayMetrics.DENSITY_LOW); 444 assertNotNull(ldpi); 445 assertEquals(300, ldpi.getIntrinsicWidth()); 446 447 final Drawable mdpi = extractForegroundFromAdaptiveIconDrawable(R.drawable.adaptive_icon, 448 DisplayMetrics.DENSITY_MEDIUM); 449 assertNotNull(mdpi); 450 assertEquals(200, mdpi.getIntrinsicWidth()); 451 452 final Drawable hdpi = extractForegroundFromAdaptiveIconDrawable(R.drawable.adaptive_icon, 453 DisplayMetrics.DENSITY_HIGH); 454 assertNotNull(hdpi); 455 assertEquals(100, hdpi.getIntrinsicWidth()); 456 } 457 testGetAnimation()458 public void testGetAnimation() throws Exception { 459 try { 460 mResources.getAnimation(-1); 461 fail("Failed at testGetAnimation"); 462 } catch (NotFoundException e) { 463 //expected 464 } 465 466 final XmlResourceParser ani = mResources.getAnimation(R.anim.anim_rotate); 467 assertNotNull(ani); 468 XmlUtils.beginDocument(ani, "rotate"); 469 assertEquals(7, ani.getAttributeCount()); 470 assertEquals("Binary XML file line #18", ani.getPositionDescription()); 471 assertEquals("interpolator", ani.getAttributeName(0)); 472 assertEquals("@17432582", ani.getAttributeValue(0)); 473 } 474 testGetQuantityString1()475 public void testGetQuantityString1() { 476 try { 477 mResources.getQuantityString(-1, 1, ""); 478 fail("Failed at testGetQuantityString1"); 479 } catch (NotFoundException e) { 480 //expected 481 } 482 483 final String strGo = mResources.getQuantityString(R.plurals.plurals_test, 1, ""); 484 assertEquals("A dog", strGo); 485 } 486 testGetQuantityString2()487 public void testGetQuantityString2() { 488 try { 489 mResources.getQuantityString(-1, 1); 490 fail("Failed at testGetQuantityString2"); 491 } catch (NotFoundException e) { 492 //expected 493 } 494 495 final String strGo = mResources.getQuantityString(R.plurals.plurals_test, 1); 496 assertEquals("A dog", strGo); 497 } 498 testGetInteger()499 public void testGetInteger() { 500 try { 501 mResources.getInteger(-1); 502 fail("Failed at testGetInteger"); 503 } catch (NotFoundException e) { 504 //expected 505 } 506 507 final int i = mResources.getInteger(R.integer.resource_test_int); 508 assertEquals(10, i); 509 } 510 testGetValue()511 public void testGetValue() { 512 final TypedValue tv = new TypedValue(); 513 514 try { 515 mResources.getValue("null", tv, false); 516 fail("Failed at testGetValue"); 517 } catch (NotFoundException e) { 518 //expected 519 } 520 521 mResources.getValue("android.content.cts:raw/text", tv, false); 522 assertNotNull(tv); 523 assertEquals("res/raw/text.txt", tv.coerceToString()); 524 } 525 testGetValueForDensity()526 public void testGetValueForDensity() { 527 final TypedValue tv = new TypedValue(); 528 529 mResources.getValueForDensity(R.string.density_string, 530 DisplayMetrics.DENSITY_LOW, tv, false); 531 assertEquals("ldpi", tv.coerceToString()); 532 533 mResources.getValueForDensity(R.string.density_string, 534 DisplayMetrics.DENSITY_MEDIUM, tv, false); 535 assertEquals("mdpi", tv.coerceToString()); 536 537 mResources.getValueForDensity(R.string.density_string, 538 DisplayMetrics.DENSITY_HIGH, tv, false); 539 assertEquals("hdpi", tv.coerceToString()); 540 } 541 testGetValueForDensityWithZeroDensityIsSameAsGetValue()542 public void testGetValueForDensityWithZeroDensityIsSameAsGetValue() { 543 final TypedValue defaultTv = new TypedValue(); 544 mResources.getValue(R.string.density_string, defaultTv, false); 545 546 final TypedValue densityTv = new TypedValue(); 547 mResources.getValueForDensity(R.string.density_string, 0 /*density*/, densityTv, false); 548 549 assertEquals(defaultTv.assetCookie, densityTv.assetCookie); 550 assertEquals(defaultTv.data, densityTv.data); 551 assertEquals(defaultTv.type, densityTv.type); 552 assertEquals(defaultTv.string, densityTv.string); 553 } 554 testGetAssets()555 public void testGetAssets() { 556 final AssetManager aM = mResources.getAssets(); 557 assertNotNull(aM); 558 assertTrue(aM.isUpToDate()); 559 } 560 testGetSystem()561 public void testGetSystem() { 562 assertNotNull(Resources.getSystem()); 563 } 564 testGetLayout()565 public void testGetLayout() throws Exception { 566 try { 567 mResources.getLayout(-1); 568 fail("Failed at testGetLayout"); 569 } catch (NotFoundException e) { 570 //expected 571 } 572 573 final XmlResourceParser layout = mResources.getLayout(R.layout.abslistview_layout); 574 assertNotNull(layout); 575 XmlUtils.beginDocument(layout, "ViewGroup_Layout"); 576 assertEquals(3, layout.getAttributeCount()); 577 assertEquals("id", layout.getAttributeName(0)); 578 assertEquals("@" + R.id.abslistview_root, layout.getAttributeValue(0)); 579 } 580 testGetBoolean()581 public void testGetBoolean() { 582 try { 583 mResources.getBoolean(-1); 584 fail("Failed at testGetBoolean"); 585 } catch (NotFoundException e) { 586 //expected 587 } 588 589 final boolean b = mResources.getBoolean(R.integer.resource_test_int); 590 assertTrue(b); 591 } 592 testgetFraction()593 public void testgetFraction() { 594 assertEquals(1, (int)mResources.getFraction(R.dimen.frac100perc, 1, 1)); 595 assertEquals(100, (int)mResources.getFraction(R.dimen.frac100perc, 100, 1)); 596 } 597 testParseBundleExtras()598 public void testParseBundleExtras() throws XmlPullParserException, IOException { 599 final Bundle b = new Bundle(); 600 XmlResourceParser parser = mResources.getXml(R.xml.extra); 601 XmlUtils.beginDocument(parser, "tag"); 602 603 assertEquals(0, b.size()); 604 mResources.parseBundleExtras(parser, b); 605 assertEquals(1, b.size()); 606 assertEquals("android", b.getString("google")); 607 } 608 testParseBundleExtra()609 public void testParseBundleExtra() throws XmlPullParserException, IOException { 610 final Bundle b = new Bundle(); 611 XmlResourceParser parser = mResources.getXml(R.xml.extra); 612 613 XmlUtils.beginDocument(parser, "tag"); 614 assertEquals(0, b.size()); 615 mResources.parseBundleExtra("test", parser, b); 616 assertEquals(1, b.size()); 617 assertEquals("Lee", b.getString("Bruce")); 618 } 619 testGetIdentifier()620 public void testGetIdentifier() { 621 622 int resid = mResources.getIdentifier(COM_ANDROID_CTS_STUB_IDENTIFIER, null, null); 623 assertEquals(R.configVarying.simple, resid); 624 625 resid = mResources.getIdentifier(CONFIG_VARYING_SIMPLE, null, PACKAGE_NAME); 626 assertEquals(R.configVarying.simple, resid); 627 628 resid = mResources.getIdentifier(SIMPLE, CONFIG_VARYING, PACKAGE_NAME); 629 assertEquals(R.configVarying.simple, resid); 630 } 631 testGetIntArray()632 public void testGetIntArray() { 633 final int NO_EXIST_ID = -1; 634 try { 635 mResources.getIntArray(NO_EXIST_ID); 636 fail("should throw out NotFoundException"); 637 } catch (NotFoundException e) { 638 // expected 639 } 640 // expected value is defined in res/value/arrays.xml 641 final int[] expectedArray1 = new int[] { 642 0, 0, 0 643 }; 644 final int[] expectedArray2 = new int[] { 645 0, 1, 101 646 }; 647 int[]array1 = mResources.getIntArray(R.array.strings); 648 int[]array2 = mResources.getIntArray(R.array.integers); 649 650 checkArrayEqual(expectedArray1, array1); 651 checkArrayEqual(expectedArray2, array2); 652 653 } 654 checkArrayEqual(int[] array1, int[] array2)655 private void checkArrayEqual(int[] array1, int[] array2) { 656 assertNotNull(array2); 657 assertEquals(array1.length, array2.length); 658 for (int i = 0; i < array1.length; i++) { 659 assertEquals(array1[i], array2[i]); 660 } 661 } 662 testGetQuantityText()663 public void testGetQuantityText() { 664 CharSequence cs; 665 final Resources res = resourcesForLanguage("cs"); 666 667 cs = res.getQuantityText(R.plurals.plurals_test, 0); 668 assertEquals("Some Czech dogs", cs.toString()); 669 670 cs = res.getQuantityText(R.plurals.plurals_test, 1); 671 assertEquals("A Czech dog", cs.toString()); 672 673 cs = res.getQuantityText(R.plurals.plurals_test, 2); 674 assertEquals("Few Czech dogs", cs.toString()); 675 676 cs = res.getQuantityText(R.plurals.plurals_test, 5); 677 assertEquals("Some Czech dogs", cs.toString()); 678 679 cs = res.getQuantityText(R.plurals.plurals_test, 500); 680 assertEquals("Some Czech dogs", cs.toString()); 681 682 } 683 testChangingConfiguration()684 public void testChangingConfiguration() { 685 ColorDrawable dr1 = (ColorDrawable) mResources.getDrawable(R.color.varies_uimode); 686 assertEquals(ActivityInfo.CONFIG_UI_MODE, dr1.getChangingConfigurations()); 687 688 // Test again with a drawable obtained from the cache. 689 ColorDrawable dr2 = (ColorDrawable) mResources.getDrawable(R.color.varies_uimode); 690 assertEquals(ActivityInfo.CONFIG_UI_MODE, dr2.getChangingConfigurations()); 691 } 692 resourcesForLanguage(final String lang)693 private Resources resourcesForLanguage(final String lang) { 694 final Configuration config = new Configuration(); 695 config.updateFrom(mResources.getConfiguration()); 696 config.setLocale(new Locale(lang)); 697 return new Resources(mResources.getAssets(), mResources.getDisplayMetrics(), config); 698 } 699 testGetResourceEntryName()700 public void testGetResourceEntryName() { 701 assertEquals(SIMPLE, mResources.getResourceEntryName(R.configVarying.simple)); 702 } 703 testGetResourceName()704 public void testGetResourceName() { 705 final String fullName = mResources.getResourceName(R.configVarying.simple); 706 assertEquals(COM_ANDROID_CTS_STUB_IDENTIFIER, fullName); 707 708 final String packageName = mResources.getResourcePackageName(R.configVarying.simple); 709 assertEquals(PACKAGE_NAME, packageName); 710 711 final String typeName = mResources.getResourceTypeName(R.configVarying.simple); 712 assertEquals(CONFIG_VARYING, typeName); 713 } 714 testGetStringWithIntParam()715 public void testGetStringWithIntParam() { 716 checkString(R.string.formattedStringNone, 717 mResources.getString(R.string.formattedStringNone), 718 "Format[]"); 719 checkString(R.string.formattedStringOne, 720 mResources.getString(R.string.formattedStringOne), 721 "Format[%d]"); 722 checkString(R.string.formattedStringTwo, mResources.getString(R.string.formattedStringTwo), 723 "Format[%3$d,%2$s]"); 724 // Make sure the formatted one works 725 checkString(R.string.formattedStringNone, 726 mResources.getString(R.string.formattedStringNone), 727 "Format[]"); 728 checkString(R.string.formattedStringOne, 729 mResources.getString(R.string.formattedStringOne, 42), 730 "Format[42]"); 731 checkString(R.string.formattedStringTwo, 732 mResources.getString(R.string.formattedStringTwo, "unused", "hi", 43), 733 "Format[43,hi]"); 734 } 735 checkString(final int resid, final String actual, final String expected)736 private static void checkString(final int resid, final String actual, final String expected) { 737 assertEquals("Expecting string value \"" + expected + "\" got \"" 738 + actual + "\" in resources 0x" + Integer.toHexString(resid), 739 expected, actual); 740 } 741 testGetStringArray()742 public void testGetStringArray() { 743 checkStringArray(R.array.strings, new String[] { 744 "zero", "1", "here" 745 }); 746 checkTextArray(R.array.strings, new String[] { 747 "zero", "1", "here" 748 }); 749 checkStringArray(R.array.integers, new String[] { 750 null, null, null 751 }); 752 checkTextArray(R.array.integers, new String[] { 753 null, null, null 754 }); 755 } 756 checkStringArray(final int resid, final String[] expected)757 private void checkStringArray(final int resid, final String[] expected) { 758 final String[] res = mResources.getStringArray(resid); 759 assertEquals(res.length, expected.length); 760 for (int i = 0; i < expected.length; i++) { 761 checkEntry(resid, i, res[i], expected[i]); 762 } 763 } 764 checkEntry(final int resid, final int index, final Object res, final Object expected)765 private void checkEntry(final int resid, final int index, final Object res, 766 final Object expected) { 767 assertEquals("in resource 0x" + Integer.toHexString(resid) 768 + " at index " + index, expected, res); 769 } 770 checkTextArray(final int resid, final String[] expected)771 private void checkTextArray(final int resid, final String[] expected) { 772 final CharSequence[] res = mResources.getTextArray(resid); 773 assertEquals(res.length, expected.length); 774 for (int i = 0; i < expected.length; i++) { 775 checkEntry(resid, i, res[i], expected[i]); 776 } 777 } 778 testGetValueWithID()779 public void testGetValueWithID() { 780 tryBoolean(R.bool.trueRes, true); 781 tryBoolean(R.bool.falseRes, false); 782 783 tryString(R.string.coerceIntegerToString, "100"); 784 tryString(R.string.coerceBooleanToString, "true"); 785 tryString(R.string.coerceColorToString, "#fff"); 786 tryString(R.string.coerceFloatToString, "100.0"); 787 tryString(R.string.coerceDimensionToString, "100px"); 788 tryString(R.string.coerceFractionToString, "100%"); 789 } 790 tryBoolean(final int resid, final boolean expected)791 private void tryBoolean(final int resid, final boolean expected) { 792 final TypedValue v = new TypedValue(); 793 mContext.getResources().getValue(resid, v, true); 794 assertEquals(TypedValue.TYPE_INT_BOOLEAN, v.type); 795 assertEquals("Expecting boolean value " + expected + " got " + v 796 + " from TypedValue: in resource 0x" + Integer.toHexString(resid), 797 expected, v.data != 0); 798 assertEquals("Expecting boolean value " + expected + " got " + v 799 + " from getBoolean(): in resource 0x" + Integer.toHexString(resid), 800 expected, mContext.getResources().getBoolean(resid)); 801 } 802 tryString(final int resid, final String expected)803 private void tryString(final int resid, final String expected) { 804 final TypedValue v = new TypedValue(); 805 mContext.getResources().getValue(resid, v, true); 806 assertEquals(TypedValue.TYPE_STRING, v.type); 807 assertEquals("Expecting string value " + expected + " got " + v 808 + ": in resource 0x" + Integer.toHexString(resid), 809 expected, v.string); 810 } 811 testRawResource()812 public void testRawResource() throws Exception { 813 assertNotNull(mResources.newTheme()); 814 815 InputStream is = mResources.openRawResource(R.raw.text); 816 verifyTextAsset(is); 817 818 is = mResources.openRawResource(R.raw.text, new TypedValue()); 819 verifyTextAsset(is); 820 821 assertNotNull(mResources.openRawResourceFd(R.raw.text)); 822 } 823 verifyTextAsset(final InputStream is)824 static void verifyTextAsset(final InputStream is) throws IOException { 825 final String expectedString = "OneTwoThreeFourFiveSixSevenEightNineTen"; 826 final byte[] buffer = new byte[10]; 827 828 int readCount; 829 int curIndex = 0; 830 while ((readCount = is.read(buffer, 0, buffer.length)) > 0) { 831 for (int i = 0; i < readCount; i++) { 832 assertEquals("At index " + curIndex 833 + " expected " + expectedString.charAt(curIndex) 834 + " but found " + ((char) buffer[i]), 835 buffer[i], expectedString.charAt(curIndex)); 836 curIndex++; 837 } 838 } 839 840 readCount = is.read(buffer, 0, buffer.length); 841 assertEquals("Reading end of buffer: expected readCount=-1 but got " + readCount, 842 -1, readCount); 843 844 readCount = is.read(buffer, buffer.length, 0); 845 assertEquals("Reading end of buffer length 0: expected readCount=0 but got " + readCount, 846 0, readCount); 847 848 is.close(); 849 } 850 testGetFont_invalidResourceId()851 public void testGetFont_invalidResourceId() { 852 try { 853 mResources.getFont(-1); 854 fail("Font resource -1 should not be found."); 855 } catch (NotFoundException e) { 856 //expected 857 } 858 } 859 testGetFont_fontFile()860 public void testGetFont_fontFile() { 861 Typeface font = mResources.getFont(R.font.sample_regular_font); 862 863 assertNotNull(font); 864 assertNotSame(Typeface.DEFAULT, font); 865 } 866 testGetFont_xmlFile()867 public void testGetFont_xmlFile() { 868 Typeface font = mResources.getFont(R.font.samplexmlfont); 869 870 assertNotNull(font); 871 assertNotSame(Typeface.DEFAULT, font); 872 } 873 getLargerTypeface(String text, Typeface typeface1, Typeface typeface2)874 private Typeface getLargerTypeface(String text, Typeface typeface1, Typeface typeface2) { 875 Paint p1 = new Paint(); 876 p1.setTypeface(typeface1); 877 float width1 = p1.measureText(text); 878 Paint p2 = new Paint(); 879 p2.setTypeface(typeface2); 880 float width2 = p2.measureText(text); 881 882 if (width1 > width2) { 883 return typeface1; 884 } else if (width1 < width2) { 885 return typeface2; 886 } else { 887 fail("The widths of the text should not be the same"); 888 return null; 889 } 890 } 891 testGetFont_xmlFileWithTtc()892 public void testGetFont_xmlFileWithTtc() { 893 // Here we test that building typefaces by indexing in font collections works correctly. 894 // We want to ensure that the built typefaces correspond to the fonts with the right index. 895 // sample_font_collection.ttc contains two fonts (with indices 0 and 1). The first one has 896 // glyph "a" of 3em width, and all the other glyphs 1em. The second one has glyph "b" of 897 // 3em width, and all the other glyphs 1em. Hence, we can compare the width of these 898 // glyphs to assert that ttc indexing works. 899 Typeface normalFont = mResources.getFont(R.font.sample_ttc_family); 900 assertNotNull(normalFont); 901 Typeface italicFont = Typeface.create(normalFont, Typeface.ITALIC); 902 assertNotNull(italicFont); 903 904 assertEquals(getLargerTypeface("a", normalFont, italicFont), normalFont); 905 assertEquals(getLargerTypeface("b", normalFont, italicFont), italicFont); 906 } 907 testGetFont_xmlFileWithVariationSettings()908 public void testGetFont_xmlFileWithVariationSettings() { 909 // Here we test that specifying variation settings for fonts in XMLs works. 910 // We build typefaces from two families containing one font each, using the same font 911 // resource, but having different values for the 'wdth' tag. Then we measure the painted 912 // text to ensure that the tag affects the text width. The font resource used supports 913 // the 'wdth' axis for the dash (-) character. 914 Typeface typeface1 = mResources.getFont(R.font.sample_variation_settings_family1); 915 assertNotNull(typeface1); 916 Typeface typeface2 = mResources.getFont(R.font.sample_variation_settings_family2); 917 assertNotNull(typeface2); 918 919 assertNotSame(typeface1, typeface2); 920 assertEquals(getLargerTypeface("-", typeface1, typeface2), typeface2); 921 } 922 testGetFont_invalidXmlFile()923 public void testGetFont_invalidXmlFile() { 924 try { 925 assertNull(mResources.getFont(R.font.invalid_xmlfamily)); 926 } catch (NotFoundException e) { 927 // pass 928 } 929 930 try { 931 assertNull(mResources.getFont(R.font.invalid_xmlempty)); 932 } catch (NotFoundException e) { 933 // pass 934 } 935 } 936 testGetFont_invalidFontFiles()937 public void testGetFont_invalidFontFiles() { 938 try { 939 mResources.getFont(R.font.invalid_xmlfont); 940 fail(); 941 } catch (RuntimeException e) { 942 // pass 943 } 944 945 try { 946 mResources.getFont(R.font.invalid_font); 947 fail(); 948 } catch (RuntimeException e) { 949 // pass 950 } 951 952 try { 953 mResources.getFont(R.font.invalid_xmlfont_contains_invalid_font_file); 954 fail(); 955 } catch (RuntimeException e) { 956 // pass 957 } 958 959 try { 960 mResources.getFont(R.font.invalid_xmlfont_nosource); 961 fail(); 962 } catch (RuntimeException e) { 963 // pass 964 } 965 966 } 967 testGetFont_brokenFontFiles()968 public void testGetFont_brokenFontFiles() { 969 try { 970 mResources.getFont(R.font.brokenfont); 971 fail(); 972 } catch (RuntimeException e) { 973 // pass 974 } 975 976 try { 977 mResources.getFont(R.font.broken_xmlfont); 978 fail(); 979 } catch (RuntimeException e) { 980 // pass 981 } 982 } 983 testGetFont_fontFileIsCached()984 public void testGetFont_fontFileIsCached() { 985 Typeface font = mResources.getFont(R.font.sample_regular_font); 986 Typeface font2 = mResources.getFont(R.font.sample_regular_font); 987 988 assertEquals(font, font2); 989 } 990 testGetFont_xmlFileIsCached()991 public void testGetFont_xmlFileIsCached() { 992 Typeface font = mResources.getFont(R.font.samplexmlfont); 993 Typeface font2 = mResources.getFont(R.font.samplexmlfont); 994 995 assertEquals(font, font2); 996 } 997 testGetFont_resolveByFontTable()998 public void testGetFont_resolveByFontTable() { 999 assertEquals(Typeface.NORMAL, mResources.getFont(R.font.sample_regular_font).getStyle()); 1000 assertEquals(Typeface.BOLD, mResources.getFont(R.font.sample_bold_font).getStyle()); 1001 assertEquals(Typeface.ITALIC, mResources.getFont(R.font.sample_italic_font).getStyle()); 1002 assertEquals(Typeface.BOLD_ITALIC, 1003 mResources.getFont(R.font.sample_bolditalic_font).getStyle()); 1004 1005 assertEquals(Typeface.NORMAL, mResources.getFont(R.font.sample_regular_family).getStyle()); 1006 assertEquals(Typeface.BOLD, mResources.getFont(R.font.sample_bold_family).getStyle()); 1007 assertEquals(Typeface.ITALIC, mResources.getFont(R.font.sample_italic_family).getStyle()); 1008 assertEquals(Typeface.BOLD_ITALIC, 1009 mResources.getFont(R.font.sample_bolditalic_family).getStyle()); 1010 } 1011 testComplexColorDrawableAttributeInflation()1012 public void testComplexColorDrawableAttributeInflation() { 1013 final LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService( 1014 Context.LAYOUT_INFLATER_SERVICE); 1015 1016 final View view = layoutInflater.inflate( 1017 R.layout.complex_color_drawable_attr_layout, null); 1018 assertTrue(view.getBackground() instanceof ColorStateListDrawable); 1019 } 1020 testGetAttributeSetSourceResId()1021 public void testGetAttributeSetSourceResId() { 1022 assertEquals(Resources.ID_NULL, Resources.getAttributeSetSourceResId(null)); 1023 1024 XmlPullParser test_color_parser = mResources.getXml(R.xml.test_color); 1025 AttributeSet test_color_set = Xml.asAttributeSet(test_color_parser); 1026 assertEquals(R.xml.test_color, Resources.getAttributeSetSourceResId(test_color_set)); 1027 1028 XmlPullParser colors_parser = mResources.getXml(R.xml.colors); 1029 AttributeSet colors_set = Xml.asAttributeSet(colors_parser); 1030 assertEquals(R.xml.colors, Resources.getAttributeSetSourceResId(colors_set)); 1031 1032 XmlPullParser content_layout_parser = mResources.getLayout(R.layout.context_layout); 1033 AttributeSet content_layout_set = Xml.asAttributeSet(content_layout_parser); 1034 assertEquals(R.layout.context_layout, 1035 Resources.getAttributeSetSourceResId(content_layout_set)); 1036 1037 XmlPullParser anim_rotate_parser = mResources.getAnimation(R.anim.anim_rotate); 1038 AttributeSet anim_rotate_set = Xml.asAttributeSet(anim_rotate_parser); 1039 assertEquals(R.anim.anim_rotate, Resources.getAttributeSetSourceResId(anim_rotate_set)); 1040 } 1041 testSystemFontFamilyReturnsSystemFont()1042 public void testSystemFontFamilyReturnsSystemFont() { 1043 Typeface typeface = mResources.getFont(R.font.sample_downloadable_font); 1044 assertEquals(typeface, Typeface.create("sans-serif", Typeface.NORMAL)); 1045 } 1046 testThemeCompare()1047 public void testThemeCompare() { 1048 Resources.Theme t1 = mResources.newTheme(); 1049 Resources.Theme t2 = mResources.newTheme(); 1050 assertTrue(t1.equals(t1)); 1051 assertTrue(t1.equals(t2)); 1052 assertTrue(t1.hashCode() == t2.hashCode()); 1053 assertFalse(t1.equals(null)); 1054 assertFalse(t1.equals(this)); 1055 1056 t1.applyStyle(1, false); 1057 assertFalse(t1.equals(t2)); 1058 assertFalse(t1.hashCode() == t2.hashCode()); 1059 t2.applyStyle(1, false); 1060 assertTrue(t1.equals(t2)); 1061 assertTrue(t1.hashCode() == t2.hashCode()); 1062 t1.applyStyle(2, true); 1063 assertFalse(t1.hashCode() == t2.hashCode()); 1064 assertFalse(t1.equals(t2)); 1065 t2.applyStyle(2, false); 1066 assertFalse(t1.equals(t2)); 1067 assertFalse(t1.hashCode() == t2.hashCode()); 1068 } 1069 } 1070