aboutsummaryrefslogtreecommitdiff
path: root/tests/src/com/android/carrierconfig/CarrierConfigTest.java
blob: 4d753a18811e18c5963e8fe2660abb2f4d37a52b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
/*
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.carrierconfig;

import android.Manifest;
import android.annotation.NonNull;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.PersistableBundle;
import android.provider.Telephony;
import android.service.carrier.CarrierIdentifier;
import android.telephony.CarrierConfigManager;
import android.telephony.TelephonyManager;
import android.test.InstrumentationTestCase;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import junit.framework.AssertionFailedError;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

public class CarrierConfigTest extends InstrumentationTestCase {
    private static final String TAG = "CarrierConfigTest";

    /**
     * Iterate over all XML files in assets/ and ensure they parse without error.
     */
    public void testAllFilesParse() {
        forEachConfigXml(new ParserChecker() {
            public void check(XmlPullParser parser, String mccmnc) throws XmlPullParserException,
                    IOException {
                PersistableBundle b = DefaultCarrierConfigService.readConfigFromXml(parser,
                        new CarrierIdentifier("001", "001", "Test", "001001123456789", "", ""), "");
                assertNotNull("got null bundle", b);
            }
        });
    }

    /**
     * Check that the config bundles in XML files have valid filter attributes.
     * This checks the attribute names only.
     */
    public void testFilterValidAttributes() {
        forEachConfigXml(new ParserChecker() {
            public void check(XmlPullParser parser, String mccmnc) throws XmlPullParserException,
                    IOException {
                int event;
                while (((event = parser.next()) != XmlPullParser.END_DOCUMENT)) {
                    if (event == XmlPullParser.START_TAG
                            && "carrier_config".equals(parser.getName())) {
                        for (int i = 0; i < parser.getAttributeCount(); ++i) {
                            String attribute = parser.getAttributeName(i);
                            switch (attribute) {
                                case "mcc":
                                case "mnc":
                                case "gid1":
                                case "gid2":
                                case "spn":
                                case "imsi":
                                case "device":
                                case "vendorSku":
                                case "hardwareSku":
                                case "board":
                                case "cid":
                                case "name":
                                case "sku":
                                    break;
                                default:
                                    fail("Unknown attribute '" + attribute
                                            + "' at " + parser.getPositionDescription());
                                    break;
                            }
                        }
                    }
                }
            }
        });
    }

    /**
     * Check that XML files named after mccmnc are those without matching carrier id.
     * If there is a matching carrier id, all configurations should move to carrierid.xml which
     * has a higher matching priority than mccmnc.xml
     */
    public void testCarrierConfigFileNaming() {
        forEachConfigXml(new ParserChecker() {
            public void check(XmlPullParser parser, String mccmnc) throws XmlPullParserException,
                    IOException {
                if (mccmnc == null) {
                    // only check file named after mccmnc
                    return;
                }
                int event;
                while (((event = parser.next()) != XmlPullParser.END_DOCUMENT)) {
                    if (event == XmlPullParser.START_TAG
                            && "carrier_config".equals(parser.getName())) {
                        String mcc = null;
                        String mnc = null;
                        String spn = null;
                        String gid1 = null;
                        String gid2 = null;
                        String imsi = null;
                        for (int i = 0; i < parser.getAttributeCount(); ++i) {
                            String attribute = parser.getAttributeName(i);
                            switch (attribute) {
                                case "mcc":
                                    mcc = parser.getAttributeValue(i);
                                    break;
                                case "mnc":
                                    mnc = parser.getAttributeValue(i);
                                    break;
                                case "gid1":
                                    gid1 = parser.getAttributeValue(i);
                                    break;
                                case "gid2":
                                    gid2 = parser.getAttributeValue(i);
                                    break;
                                case "spn":
                                    spn = parser.getAttributeValue(i);
                                    break;
                                case "imsi":
                                    imsi = parser.getAttributeValue(i);
                                    break;
                                default:
                                    fail("Unknown attribute '" + attribute
                                            + "' at " + parser.getPositionDescription());
                                    break;
                            }
                        }
                        mcc = (mcc != null) ? mcc : mccmnc.substring(0, 3);
                        mnc = (mnc != null) ? mnc : mccmnc.substring(3);
                        // check if there is a valid carrier id
                        int carrierId = getCarrierId(getInstrumentation().getTargetContext(),
                                new CarrierIdentifier(mcc, mnc, spn, imsi, gid1, gid2));
                        if (carrierId != TelephonyManager.UNKNOWN_CARRIER_ID) {
                            fail("unexpected carrier_config_mccmnc.xml with matching carrier id: "
                                    + carrierId + ", please move to carrier_config_carrierid.xml");
                        }
                    }
                }
            }
        });
    }

    /**
     * Tests that the variable names in each XML file match actual keys in CarrierConfigManager.
     */
    public void testVariableNames() {
        final Set<String> varXmlNames = getCarrierConfigXmlNames();
        // organize them into sets by type or unknown
        forEachConfigXml(new ParserChecker() {
            public void check(XmlPullParser parser, String mccmnc) throws XmlPullParserException,
                    IOException {
                int event;
                while (((event = parser.next()) != XmlPullParser.END_DOCUMENT)) {
                    if (event == XmlPullParser.START_TAG) {
                        switch (parser.getName()) {
                            case "int-array":
                            case "string-array":
                                // string-array and int-array require the 'num' attribute
                                final String varNum = parser.getAttributeValue(null, "num");
                                assertNotNull("No 'num' attribute in array: "
                                        + parser.getPositionDescription(), varNum);
                            case "int":
                            case "long":
                            case "boolean":
                            case "string":
                                // NOTE: This doesn't check for other valid Bundle values, but it
                                // is limited to the key types in CarrierConfigManager.
                                final String varName = parser.getAttributeValue(null, "name");
                                assertNotNull("No 'name' attribute: "
                                        + parser.getPositionDescription(), varName);
                                assertTrue("Unknown variable: '" + varName
                                        + "' at " + parser.getPositionDescription(),
                                        varXmlNames.contains(varName));
                                // TODO: Check that the type is correct.
                                break;
                            case "carrier_config_list":
                            case "item":
                            case "carrier_config":
                                // do nothing
                                break;
                            default:
                                fail("unexpected tag: '" + parser.getName()
                                        + "' at " + parser.getPositionDescription());
                                break;
                        }
                    }
                }
            }
        });
    }

    /**
     * Utility for iterating over each XML document in the assets folder.
     *
     * This can be used with {@link #forEachConfigXml} to run checks on each XML document.
     * {@link #check} should {@link #fail} if the test does not pass.
     */
    private interface ParserChecker {
        void check(XmlPullParser parser, String mccmnc) throws XmlPullParserException, IOException;
    }

    /**
     * Utility for iterating over each XML document in the assets folder.
     */
    private void forEachConfigXml(ParserChecker checker) {
        AssetManager assetMgr = getInstrumentation().getTargetContext().getAssets();
        String mccmnc = null;
        try {
            String[] files = assetMgr.list("");
            assertNotNull("failed to list files", files);
            assertTrue("no files", files.length > 0);
            for (String fileName : files) {
                try {
                    if (!fileName.startsWith("carrier_config_")) continue;
                    if (fileName.startsWith("carrier_config_mccmnc_")) {
                        mccmnc = fileName.substring("carrier_config_mccmnc_".length(),
                                fileName.indexOf(".xml"));

                    }
                    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                    XmlPullParser parser = factory.newPullParser();
                    parser.setInput(assetMgr.open(fileName), "utf-8");

                    checker.check(parser, mccmnc);

                } catch (Throwable e) {
                    throw new AssertionError("Problem in " + fileName + ": " + e.getMessage(), e);
                }
            }
            // Check vendor.xml too
            try {
                Resources res = getInstrumentation().getTargetContext().getResources();
                checker.check(res.getXml(R.xml.vendor), mccmnc);
            } catch (Throwable e) {
                throw new AssertionError("Problem in vendor.xml: " + e.getMessage(), e);
            }
        } catch (IOException e) {
            fail(e.toString());
        }
    }

    /**
     * Get the set of config variable names, as used in XML files.
     */
    private Set<String> getCarrierConfigXmlNames() {
        Set<String> names = new HashSet<>();
        // get values of all KEY_ members of CarrierConfigManager as well as its nested classes.
        names.addAll(getCarrierConfigXmlNames(CarrierConfigManager.class));
        for (Class nested : CarrierConfigManager.class.getDeclaredClasses()) {
            Log.i("CarrierConfigTest", nested.toString());
            if (nested.isInterface()) {
                continue;
            }
            if (Modifier.isStatic(nested.getModifiers())) {
                names.addAll(getCarrierConfigXmlNames(nested));
            }
        }
        return names;
    }

    private Set<String> getCarrierConfigXmlNames(Class clazz) {
        // get values of all KEY_ members of clazz
        Field[] fields = clazz.getDeclaredFields();
        HashSet<String> varXmlNames = new HashSet<>();
        for (Field f : fields) {
            if (!f.getName().startsWith("KEY_")) continue;
            if (!Modifier.isStatic(f.getModifiers())) {
                fail("non-static key in " + clazz.getName() + ":" + f.toString());
            }
            try {
                String value = (String) f.get(null);
                varXmlNames.add(value);
            }
            catch (IllegalAccessException e) {
                throw new AssertionError("Failed to get config key: " + e.getMessage(), e);
            }
        }
        assertTrue("Found zero keys", varXmlNames.size() > 0);
        return varXmlNames;
    }

    // helper function to get carrier id from carrierIdentifier
    private int getCarrierId(@NonNull Context context,
                             @NonNull CarrierIdentifier carrierIdentifier) {
        try {
            getInstrumentation().getUiAutomation().adoptShellPermissionIdentity(
                    Manifest.permission.READ_PRIVILEGED_PHONE_STATE);
            List<String> args = new ArrayList<>();
            args.add(carrierIdentifier.getMcc() + carrierIdentifier.getMnc());
            if (carrierIdentifier.getGid1() != null) {
                args.add(carrierIdentifier.getGid1());
            }
            if (carrierIdentifier.getGid2() != null) {
                args.add(carrierIdentifier.getGid2());
            }
            if (carrierIdentifier.getImsi() != null) {
                args.add(carrierIdentifier.getImsi());
            }
            if (carrierIdentifier.getSpn() != null) {
                args.add(carrierIdentifier.getSpn());
            }
            try (Cursor cursor = context.getContentResolver().query(
                    Telephony.CarrierId.All.CONTENT_URI,
                    /* projection */ null,
                    /* selection */ Telephony.CarrierId.All.MCCMNC + "=? AND "
                            + Telephony.CarrierId.All.GID1
                            + ((carrierIdentifier.getGid1() == null) ? " is NULL" : "=?") + " AND "
                            + Telephony.CarrierId.All.GID2
                            + ((carrierIdentifier.getGid2() == null) ? " is NULL" : "=?") + " AND "
                            + Telephony.CarrierId.All.IMSI_PREFIX_XPATTERN
                            + ((carrierIdentifier.getImsi() == null) ? " is NULL" : "=?") + " AND "
                            + Telephony.CarrierId.All.SPN
                            + ((carrierIdentifier.getSpn() == null) ? " is NULL" : "=?"),
                /* selectionArgs */ args.toArray(new String[args.size()]), null)) {
                if (cursor != null) {
                    while (cursor.moveToNext()) {
                        return cursor.getInt(cursor.getColumnIndex(Telephony.CarrierId.CARRIER_ID));
                    }
                }
            }
        } catch (SecurityException e) {
            fail("Should be able to access APIs protected by a permission apps cannot get");
        } finally {
            getInstrumentation().getUiAutomation().dropShellPermissionIdentity();
        }
        return TelephonyManager.UNKNOWN_CARRIER_ID;
    }
}