1 /*
2  * Copyright (C) 2020 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 package com.android.settings;
17 
18 import static com.android.settings.core.PreferenceXmlParserUtils.METADATA_KEY;
19 import static com.android.settings.core.PreferenceXmlParserUtils.MetadataFlag.FLAG_INCLUDE_PREF_SCREEN;
20 import static com.android.settings.core.PreferenceXmlParserUtils.MetadataFlag.FLAG_NEED_KEY;
21 
22 import android.annotation.XmlRes;
23 import android.content.Context;
24 import android.os.Bundle;
25 import android.provider.SearchIndexableResource;
26 
27 import com.android.settings.core.PreferenceXmlParserUtils;
28 import com.android.settings.search.BaseSearchIndexProvider;
29 
30 import java.util.ArrayList;
31 import java.util.List;
32 
33 /**
34  * Convenience methods and constants for testing.
35  */
36 public class TestUtils {
37     public static final long KILOBYTE = 1024L; // TODO: Change to 1000 in O Robolectric.
38     public static final long MEGABYTE = KILOBYTE * KILOBYTE;
39     public static final long GIGABYTE = KILOBYTE * MEGABYTE;
40 
getAllXmlKeys( Context context, BaseSearchIndexProvider indexProvider)41     public static List<String> getAllXmlKeys(
42             Context context, BaseSearchIndexProvider indexProvider)
43             throws Exception {
44         final List<SearchIndexableResource> resources = indexProvider.getXmlResourcesToIndex(
45                 context, true /* not used*/);
46         if (resources == null || resources.isEmpty()) {
47             return new ArrayList<>();
48         }
49         final List<String> keys = new ArrayList<>();
50         for (SearchIndexableResource res : resources) {
51             keys.addAll(getKeysFromXml(res.xmlResId, context));
52         }
53         return keys;
54     }
55 
getKeysFromXml(@mlRes int xmlResId, Context context)56     private static List<String> getKeysFromXml(@XmlRes int xmlResId, Context context)
57             throws Exception {
58         final List<String> keys = new ArrayList<>();
59         final List<Bundle> metadata = PreferenceXmlParserUtils.extractMetadata(context, xmlResId,
60                 FLAG_NEED_KEY | FLAG_INCLUDE_PREF_SCREEN);
61         for (Bundle bundle : metadata) {
62             keys.add(bundle.getString(METADATA_KEY));
63         }
64         return keys;
65     }
66 }
67