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