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