• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 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 com.android.internal.telephony.dataconnection;
18 
19 import static com.android.internal.telephony.TelephonyTestUtils.waitForMs;
20 import static com.android.internal.telephony.dataconnection.ApnSettingTest.createApnSetting;
21 
22 import static org.junit.Assert.assertArrayEquals;
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertFalse;
25 import static org.junit.Assert.assertNotEquals;
26 import static org.junit.Assert.assertTrue;
27 import static org.junit.Assert.fail;
28 import static org.mockito.Matchers.any;
29 import static org.mockito.Matchers.anyInt;
30 import static org.mockito.Matchers.anyLong;
31 import static org.mockito.Matchers.anyString;
32 import static org.mockito.Matchers.eq;
33 import static org.mockito.Mockito.atLeastOnce;
34 import static org.mockito.Mockito.clearInvocations;
35 import static org.mockito.Mockito.doAnswer;
36 import static org.mockito.Mockito.doReturn;
37 import static org.mockito.Mockito.never;
38 import static org.mockito.Mockito.spy;
39 import static org.mockito.Mockito.timeout;
40 import static org.mockito.Mockito.times;
41 import static org.mockito.Mockito.verify;
42 
43 import android.app.AlarmManager;
44 import android.app.PendingIntent;
45 import android.content.ContentResolver;
46 import android.content.ContentValues;
47 import android.content.Context;
48 import android.content.Intent;
49 import android.content.IntentFilter;
50 import android.content.pm.ServiceInfo;
51 import android.database.Cursor;
52 import android.database.MatrixCursor;
53 import android.hardware.radio.V1_0.SetupDataCallResult;
54 import android.net.LinkProperties;
55 import android.net.NetworkAgent;
56 import android.net.NetworkCapabilities;
57 import android.net.NetworkPolicyManager;
58 import android.net.NetworkRequest;
59 import android.net.Uri;
60 import android.os.AsyncResult;
61 import android.os.Handler;
62 import android.os.HandlerThread;
63 import android.os.IBinder;
64 import android.os.Message;
65 import android.os.PersistableBundle;
66 import android.provider.Settings;
67 import android.provider.Telephony;
68 import android.telephony.AccessNetworkConstants;
69 import android.telephony.AccessNetworkConstants.AccessNetworkType;
70 import android.telephony.CarrierConfigManager;
71 import android.telephony.NetworkRegistrationInfo;
72 import android.telephony.ServiceState;
73 import android.telephony.SignalStrength;
74 import android.telephony.SubscriptionInfo;
75 import android.telephony.SubscriptionManager;
76 import android.telephony.SubscriptionPlan;
77 import android.telephony.TelephonyDisplayInfo;
78 import android.telephony.TelephonyManager;
79 import android.telephony.data.ApnSetting;
80 import android.telephony.data.DataProfile;
81 import android.telephony.data.DataService;
82 import android.test.mock.MockContentProvider;
83 import android.test.mock.MockContentResolver;
84 import android.test.suitebuilder.annotation.MediumTest;
85 import android.test.suitebuilder.annotation.SmallTest;
86 import android.text.TextUtils;
87 import android.util.Pair;
88 
89 import androidx.test.filters.FlakyTest;
90 
91 import com.android.internal.R;
92 import com.android.internal.telephony.DctConstants;
93 import com.android.internal.telephony.ISub;
94 import com.android.internal.telephony.PhoneConstants;
95 import com.android.internal.telephony.TelephonyTest;
96 
97 import org.junit.After;
98 import org.junit.Before;
99 import org.junit.Ignore;
100 import org.junit.Test;
101 import org.mockito.ArgumentCaptor;
102 import org.mockito.Mock;
103 import org.mockito.invocation.InvocationOnMock;
104 import org.mockito.stubbing.Answer;
105 
106 import java.lang.reflect.Field;
107 import java.lang.reflect.Method;
108 import java.time.Period;
109 import java.time.ZonedDateTime;
110 import java.util.ArrayList;
111 import java.util.Arrays;
112 import java.util.HashMap;
113 import java.util.List;
114 import java.util.Map;
115 import java.util.Objects;
116 import java.util.Optional;
117 import java.util.concurrent.atomic.AtomicInteger;
118 import java.util.stream.Collectors;
119 
120 public class DcTrackerTest extends TelephonyTest {
121     public static final String FAKE_APN1 = "FAKE APN 1";
122     public static final String FAKE_APN2 = "FAKE APN 2";
123     public static final String FAKE_APN3 = "FAKE APN 3";
124     public static final String FAKE_APN4 = "FAKE APN 4";
125     public static final String FAKE_APN5 = "FAKE APN 5";
126     public static final String FAKE_APN6 = "FAKE APN 6";
127     public static final String FAKE_IFNAME = "FAKE IFNAME";
128     public static final String FAKE_PCSCF_ADDRESS = "22.33.44.55";
129     public static final String FAKE_GATEWAY = "11.22.33.44";
130     public static final String FAKE_DNS = "55.66.77.88";
131     public static final String FAKE_ADDRESS = "99.88.77.66";
132     private static final int NETWORK_TYPE_LTE_BITMASK =
133             1 << (TelephonyManager.NETWORK_TYPE_LTE - 1);
134     private static final int NETWORK_TYPE_EHRPD_BITMASK =
135             1 << (TelephonyManager.NETWORK_TYPE_EHRPD - 1);
136     private static final Uri PREFERAPN_URI = Uri.parse(
137             Telephony.Carriers.CONTENT_URI + "/preferapn");
138     private static final int DATA_ENABLED_CHANGED = 0;
139     private static final String FAKE_PLMN = "44010";
140     private static final long TEST_TIMEOUT = 1000;
141 
142     @Mock
143     ISub mIsub;
144     @Mock
145     IBinder mBinder;
146     @Mock
147     SubscriptionInfo mSubscriptionInfo;
148     @Mock
149     ApnContext mApnContext;
150     @Mock
151     DataConnection mDataConnection;
152     @Mock
153     Handler mHandler;
154     @Mock
155     NetworkPolicyManager mNetworkPolicyManager;
156 
157     private DcTracker mDct;
158     private DcTrackerTestHandler mDcTrackerTestHandler;
159 
160     private AlarmManager mAlarmManager;
161 
162     private PersistableBundle mBundle;
163 
164     private SubscriptionManager.OnSubscriptionsChangedListener mOnSubscriptionsChangedListener;
165 
166     private final ApnSettingContentProvider mApnSettingContentProvider =
167             new ApnSettingContentProvider();
168 
169     private Message mMessage;
170 
171     private CellularDataService mCellularDataService;
172 
addDataService()173     private void addDataService() {
174         mCellularDataService = new CellularDataService();
175         ServiceInfo serviceInfo = new ServiceInfo();
176         serviceInfo.packageName = "com.android.phone";
177         serviceInfo.permission = "android.permission.BIND_TELEPHONY_DATA_SERVICE";
178         IntentFilter filter = new IntentFilter();
179         mContextFixture.addService(
180                 DataService.SERVICE_INTERFACE,
181                 null,
182                 "com.android.phone",
183                 mCellularDataService.mBinder,
184                 serviceInfo,
185                 filter);
186     }
187 
188     private class DcTrackerTestHandler extends HandlerThread {
189 
DcTrackerTestHandler(String name)190         private DcTrackerTestHandler(String name) {
191             super(name);
192         }
193 
194         @Override
onLooperPrepared()195         public void onLooperPrepared() {
196             mDct = new DcTracker(mPhone, AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
197             setReady(true);
198         }
199     }
200 
201     private class ApnSettingContentProvider extends MockContentProvider {
202         private int mPreferredApnSet = 0;
203 
204         private String mFakeApn1Types = "default,supl";
205 
206         private int mRowIdOffset = 0;
207 
setFakeApn1Types(String apnTypes)208         public void setFakeApn1Types(String apnTypes) {
209             mFakeApn1Types = apnTypes;
210         }
211 
setRowIdOffset(int rowIdOffset)212         public void setRowIdOffset(int rowIdOffset) {
213             mRowIdOffset = rowIdOffset;
214         }
215 
216         @Override
query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)217         public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
218                             String sortOrder) {
219             logd("ApnSettingContentProvider: query");
220             logd("   uri = " + uri);
221             logd("   projection = " + Arrays.toString(projection));
222             logd("   selection = " + selection);
223             logd("   selectionArgs = " + Arrays.toString(selectionArgs));
224             logd("   sortOrder = " + sortOrder);
225 
226             if (uri.compareTo(Telephony.Carriers.CONTENT_URI) == 0
227                     || uri.toString().startsWith(Uri.withAppendedPath(
228                             Telephony.Carriers.CONTENT_URI, "filtered").toString())
229                     || uri.toString().startsWith(Uri.withAppendedPath(
230                             Telephony.Carriers.SIM_APN_URI, "filtered").toString())) {
231                 if (projection == null) {
232 
233                     logd("Query '" + FAKE_PLMN + "' APN settings");
234                     MatrixCursor mc = new MatrixCursor(
235                             new String[]{Telephony.Carriers._ID, Telephony.Carriers.NUMERIC,
236                                     Telephony.Carriers.NAME, Telephony.Carriers.APN,
237                                     Telephony.Carriers.PROXY, Telephony.Carriers.PORT,
238                                     Telephony.Carriers.MMSC, Telephony.Carriers.MMSPROXY,
239                                     Telephony.Carriers.MMSPORT, Telephony.Carriers.USER,
240                                     Telephony.Carriers.PASSWORD, Telephony.Carriers.AUTH_TYPE,
241                                     Telephony.Carriers.TYPE,
242                                     Telephony.Carriers.PROTOCOL,
243                                     Telephony.Carriers.ROAMING_PROTOCOL,
244                                     Telephony.Carriers.CARRIER_ENABLED, Telephony.Carriers.BEARER,
245                                     Telephony.Carriers.BEARER_BITMASK,
246                                     Telephony.Carriers.PROFILE_ID,
247                                     Telephony.Carriers.MODEM_PERSIST,
248                                     Telephony.Carriers.MAX_CONNECTIONS,
249                                     Telephony.Carriers.WAIT_TIME_RETRY,
250                                     Telephony.Carriers.TIME_LIMIT_FOR_MAX_CONNECTIONS,
251                                     Telephony.Carriers.MTU,
252                                     Telephony.Carriers.MVNO_TYPE,
253                                     Telephony.Carriers.MVNO_MATCH_DATA,
254                                     Telephony.Carriers.NETWORK_TYPE_BITMASK,
255                                     Telephony.Carriers.APN_SET_ID,
256                                     Telephony.Carriers.CARRIER_ID,
257                                     Telephony.Carriers.SKIP_464XLAT});
258 
259                     mc.addRow(new Object[]{
260                             2163 + mRowIdOffset,    // id
261                             FAKE_PLMN,              // numeric
262                             "sp-mode",              // name
263                             FAKE_APN1,              // apn
264                             "",                     // proxy
265                             "",                     // port
266                             "",                     // mmsc
267                             "",                     // mmsproxy
268                             "",                     // mmsport
269                             "",                     // user
270                             "",                     // password
271                             -1,                     // authtype
272                             mFakeApn1Types,         // types
273                             "IP",                   // protocol
274                             "IP",                   // roaming_protocol
275                             1,                      // carrier_enabled
276                             ServiceState.RIL_RADIO_TECHNOLOGY_LTE, // bearer
277                             0,                      // bearer_bitmask
278                             0,                      // profile_id
279                             1,                      // modem_cognitive
280                             0,                      // max_conns
281                             0,                      // wait_time
282                             0,                      // max_conns_time
283                             0,                      // mtu
284                             "",                     // mvno_type
285                             "",                     // mnvo_match_data
286                             NETWORK_TYPE_LTE_BITMASK, // network_type_bitmask
287                             0,                      // apn_set_id
288                             -1,                     // carrier_id
289                             -1                      // skip_464xlat
290                     });
291 
292                     mc.addRow(new Object[]{
293                             2164 + mRowIdOffset,    // id
294                             FAKE_PLMN,              // numeric
295                             "mopera U",             // name
296                             FAKE_APN2,              // apn
297                             "",                     // proxy
298                             "",                     // port
299                             "",                     // mmsc
300                             "",                     // mmsproxy
301                             "",                     // mmsport
302                             "",                     // user
303                             "",                     // password
304                             -1,                     // authtype
305                             "default,supl",         // types
306                             "IP",                   // protocol
307                             "IP",                   // roaming_protocol
308                             1,                      // carrier_enabled
309                             ServiceState.RIL_RADIO_TECHNOLOGY_LTE, // bearer,
310                             0,                      // bearer_bitmask
311                             0,                      // profile_id
312                             1,                      // modem_cognitive
313                             0,                      // max_conns
314                             0,                      // wait_time
315                             0,                      // max_conns_time
316                             0,                      // mtu
317                             "",                     // mvno_type
318                             "",                     // mnvo_match_data
319                             NETWORK_TYPE_LTE_BITMASK, // network_type_bitmask
320                             0,                      // apn_set_id
321                             -1,                     // carrier_id
322                             -1                      // skip_464xlat
323                     });
324 
325                     mc.addRow(new Object[]{
326                             2165 + mRowIdOffset,    // id
327                             FAKE_PLMN,              // numeric
328                             "b-mobile for Nexus",   // name
329                             FAKE_APN3,              // apn
330                             "",                     // proxy
331                             "",                     // port
332                             "",                     // mmsc
333                             "",                     // mmsproxy
334                             "",                     // mmsport
335                             "",                     // user
336                             "",                     // password
337                             -1,                     // authtype
338                             "ims",                  // types
339                             "IP",                   // protocol
340                             "IP",                   // roaming_protocol
341                             1,                      // carrier_enabled
342                             0,                      // bearer
343                             0,                      // bearer_bitmask
344                             0,                      // profile_id
345                             1,                      // modem_cognitive
346                             0,                      // max_conns
347                             0,                      // wait_time
348                             0,                      // max_conns_time
349                             0,                      // mtu
350                             "",                     // mvno_type
351                             "",                     // mnvo_match_data
352                             0,                      // network_type_bitmask
353                             0,                      // apn_set_id
354                             -1,                     // carrier_id
355                             -1                      // skip_464xlat
356                     });
357 
358                     mc.addRow(new Object[]{
359                             2166 + mRowIdOffset,    // id
360                             FAKE_PLMN,              // numeric
361                             "sp-mode ehrpd",        // name
362                             FAKE_APN4,              // apn
363                             "",                     // proxy
364                             "",                     // port
365                             "",                     // mmsc
366                             "",                     // mmsproxy
367                             "",                     // mmsport
368                             "",                     // user
369                             "",                     // password
370                             -1,                     // authtype
371                             "default,supl",         // types
372                             "IP",                   // protocol
373                             "IP",                   // roaming_protocol
374                             1,                      // carrier_enabled
375                             ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD, // bearer
376                             0,                      // bearer_bitmask
377                             0,                      // profile_id
378                             1,                      // modem_cognitive
379                             0,                      // max_conns
380                             0,                      // wait_time
381                             0,                      // max_conns_time
382                             0,                      // mtu
383                             "",                     // mvno_type
384                             "",                     // mnvo_match_data
385                             NETWORK_TYPE_EHRPD_BITMASK, // network_type_bitmask
386                             0,                      // apn_set_id
387                             -1,                     // carrier_id
388                             -1                      // skip_464xlat
389                     });
390 
391                     mc.addRow(new Object[]{
392                             2167 + mRowIdOffset,    // id
393                             FAKE_PLMN,              // numeric
394                             "b-mobile for Nexus",   // name
395                             FAKE_APN5,              // apn
396                             "",                     // proxy
397                             "",                     // port
398                             "",                     // mmsc
399                             "",                     // mmsproxy
400                             "",                     // mmsport
401                             "",                     // user
402                             "",                     // password
403                             -1,                     // authtype
404                             "dun",                  // types
405                             "IP",                   // protocol
406                             "IP",                   // roaming_protocol
407                             1,                      // carrier_enabled
408                             0,                      // bearer
409                             0,                      // bearer_bitmask
410                             0,                      // profile_id
411                             1,                      // modem_cognitive
412                             0,                      // max_conns
413                             0,                      // wait_time
414                             0,                      // max_conns_time
415                             0,                      // mtu
416                             "",                     // mvno_type
417                             "",                     // mnvo_match_data
418                             0,                      // network_type_bitmask
419                             0,                      // apn_set_id
420                             -1,                     // carrier_id
421                             -1                      // skip_464xlat
422                     });
423 
424                     mc.addRow(new Object[]{
425                             2168 + mRowIdOffset,    // id
426                             FAKE_PLMN,              // numeric
427                             "sp-mode",              // name
428                             FAKE_APN6,              // apn
429                             "",                     // proxy
430                             "",                     // port
431                             "",                     // mmsc
432                             "",                     // mmsproxy
433                             "",                     // mmsport
434                             "",                     // user
435                             "",                     // password
436                             -1,                     // authtype
437                             "mms,xcap",             // types
438                             "IP",                   // protocol
439                             "IP",                   // roaming_protocol
440                             1,                      // carrier_enabled
441                             ServiceState.RIL_RADIO_TECHNOLOGY_LTE, // bearer
442                             0,                      // bearer_bitmask
443                             0,                      // profile_id
444                             1,                      // modem_cognitive
445                             0,                      // max_conns
446                             0,                      // wait_time
447                             0,                      // max_conns_time
448                             0,                      // mtu
449                             "",                     // mvno_type
450                             "",                     // mnvo_match_data
451                             NETWORK_TYPE_LTE_BITMASK, // network_type_bitmask
452                             0,                      // apn_set_id
453                             -1,                     // carrier_id
454                             -1                      // skip_464xlat
455                     });
456 
457                     return mc;
458                 }
459             } else if (isPathPrefixMatch(uri,
460                     Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "preferapnset"))) {
461                 MatrixCursor mc = new MatrixCursor(
462                         new String[]{Telephony.Carriers.APN_SET_ID});
463                 // apn_set_id is the only field used with this URL
464                 mc.addRow(new Object[]{ mPreferredApnSet });
465                 mc.addRow(new Object[]{ 0 });
466                 return mc;
467             }
468 
469             return null;
470         }
471 
472         @Override
update(Uri url, ContentValues values, String where, String[] whereArgs)473         public int update(Uri url, ContentValues values, String where, String[] whereArgs) {
474             mPreferredApnSet = values.getAsInteger(Telephony.Carriers.APN_SET_ID);
475             return 1;
476         }
477 
478         @Override
delete(Uri uri, String selection, String[] selectionArgs)479         public int delete(Uri uri, String selection, String[] selectionArgs) {
480             return 0;
481         }
482 
483         @Override
insert(Uri uri, ContentValues values)484         public Uri insert(Uri uri, ContentValues values) {
485             return null;
486         }
487     }
488 
489     @Before
setUp()490     public void setUp() throws Exception {
491         logd("DcTrackerTest +Setup!");
492         super.setUp(getClass().getSimpleName());
493 
494         doReturn("fake.action_detached").when(mPhone).getActionDetached();
495         doReturn("fake.action_attached").when(mPhone).getActionAttached();
496         doReturn(ServiceState.RIL_RADIO_TECHNOLOGY_LTE).when(mServiceState)
497                 .getRilDataRadioTechnology();
498 
499         mContextFixture.putStringArrayResource(com.android.internal.R.array
500                 .config_mobile_tcp_buffers, new String[]{
501                     "umts:131072,262144,1452032,4096,16384,399360",
502                     "hspa:131072,262144,2441216,4096,16384,399360",
503                     "hsupa:131072,262144,2441216,4096,16384,399360",
504                     "hsdpa:131072,262144,2441216,4096,16384,399360",
505                     "hspap:131072,262144,2441216,4096,16384,399360",
506                     "edge:16384,32768,131072,4096,16384,65536",
507                     "gprs:4096,8192,24576,4096,8192,24576",
508                     "1xrtt:16384,32768,131070,4096,16384,102400",
509                     "evdo:131072,262144,1048576,4096,16384,524288",
510                     "lte:524288,1048576,8388608,262144,524288,4194304"});
511 
512         mContextFixture.putResource(R.string.config_wwan_data_service_package,
513                 "com.android.phone");
514 
515         ((MockContentResolver) mContext.getContentResolver()).addProvider(
516                 Telephony.Carriers.CONTENT_URI.getAuthority(), mApnSettingContentProvider);
517         Settings.Global.putInt(mContext.getContentResolver(),
518                 Settings.Global.DATA_STALL_RECOVERY_ON_BAD_NETWORK, 0);
519 
520         doReturn(PhoneConstants.State.IDLE).when(mCT).getState();
521         doReturn(true).when(mSST).getDesiredPowerState();
522         doReturn(true).when(mSST).getPowerStateFromCarrier();
523         doAnswer(
524                 new Answer<Void>() {
525                     @Override
526                     public Void answer(InvocationOnMock invocation) throws Throwable {
527                         mOnSubscriptionsChangedListener =
528                                 (SubscriptionManager.OnSubscriptionsChangedListener)
529                                         invocation.getArguments()[0];
530                         return null;
531                     }
532                 }
533         ).when(mSubscriptionManager).addOnSubscriptionsChangedListener(any());
534         doReturn(mSubscriptionInfo).when(mSubscriptionManager).getActiveSubscriptionInfo(anyInt());
535         doReturn(mNetworkPolicyManager).when(mContext)
536                 .getSystemService(Context.NETWORK_POLICY_SERVICE);
537         doReturn(1).when(mIsub).getDefaultDataSubId();
538         doReturn(mIsub).when(mBinder).queryLocalInterface(anyString());
539         mServiceManagerMockedServices.put("isub", mBinder);
540 
541         mContextFixture.putStringArrayResource(
542                 com.android.internal.R.array.config_cell_retries_per_error_code,
543                 new String[]{"36,2"});
544 
545         mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
546         mBundle = mContextFixture.getCarrierConfigBundle();
547 
548         mBundle.putBoolean(CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL, true);
549 
550         mSimulatedCommands.setDataCallResult(true, createSetupDataCallResult());
551         addDataService();
552 
553         mDcTrackerTestHandler = new DcTrackerTestHandler(getClass().getSimpleName());
554         mDcTrackerTestHandler.start();
555         waitUntilReady();
556 
557         Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
558         intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, mPhone.getPhoneId());
559         intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, mPhone.getSubId());
560         mContext.sendBroadcast(intent);
561 
562         waitForMs(600);
563         logd("DcTrackerTest -Setup!");
564     }
565 
566     @After
tearDown()567     public void tearDown() throws Exception {
568         logd("DcTrackerTest -tearDown");
569         mDct.removeCallbacksAndMessages(null);
570         mDct.stopHandlerThread();
571         mDct = null;
572         mDcTrackerTestHandler.quit();
573         mDcTrackerTestHandler.join();
574         mCellularDataService.onDestroy();
575         waitForMs(100);
576         super.tearDown();
577     }
578 
579     // Create a successful data response
createSetupDataCallResult()580     private static SetupDataCallResult createSetupDataCallResult() throws Exception {
581         SetupDataCallResult result = new SetupDataCallResult();
582         result.status = 0;
583         result.suggestedRetryTime = -1;
584         result.cid = 1;
585         result.active = 2;
586         result.type = "IP";
587         result.ifname = FAKE_IFNAME;
588         result.addresses = FAKE_ADDRESS;
589         result.dnses = FAKE_DNS;
590         result.gateways = FAKE_GATEWAY;
591         result.pcscf = FAKE_PCSCF_ADDRESS;
592         result.mtu = 1440;
593         return result;
594     }
595 
verifyDataProfile(DataProfile dp, String apn, int profileId, int supportedApnTypesBitmap, int type, int bearerBitmask)596     private void verifyDataProfile(DataProfile dp, String apn, int profileId,
597                                    int supportedApnTypesBitmap, int type, int bearerBitmask) {
598         assertEquals(profileId, dp.getProfileId());
599         assertEquals(apn, dp.getApn());
600         assertEquals(ApnSetting.PROTOCOL_IP, dp.getProtocolType());
601         assertEquals(0, dp.getAuthType());
602         assertEquals("", dp.getUserName());
603         assertEquals("", dp.getPassword());
604         assertEquals(type, dp.getType());
605         assertEquals(0, dp.getWaitTime());
606         assertTrue(dp.isEnabled());
607         assertEquals(supportedApnTypesBitmap, dp.getSupportedApnTypesBitmask());
608         assertEquals(ApnSetting.PROTOCOL_IP, dp.getRoamingProtocolType());
609         assertEquals(bearerBitmask, dp.getBearerBitmask());
610         assertEquals(0, dp.getMtu());
611         assertTrue(dp.isPersistent());
612         assertFalse(dp.isPreferred());
613     }
614 
verifyDataConnected(final String apnSetting)615     private void verifyDataConnected(final String apnSetting) {
616         verify(mPhone, atLeastOnce()).notifyDataConnection(
617                 eq(PhoneConstants.APN_TYPE_DEFAULT));
618 
619         verify(mAlarmManager, times(1)).set(eq(AlarmManager.ELAPSED_REALTIME), anyLong(),
620                 any(PendingIntent.class));
621 
622         assertEquals(apnSetting, mDct.getActiveApnString(PhoneConstants.APN_TYPE_DEFAULT));
623         assertArrayEquals(new String[]{PhoneConstants.APN_TYPE_DEFAULT}, mDct.getActiveApnTypes());
624 
625         assertTrue(mDct.isAnyDataConnected());
626         assertEquals(DctConstants.State.CONNECTED, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
627 
628         LinkProperties linkProperties = mDct.getLinkProperties(PhoneConstants.APN_TYPE_DEFAULT);
629         assertEquals(FAKE_IFNAME, linkProperties.getInterfaceName());
630         assertEquals(1, linkProperties.getAddresses().size());
631         assertEquals(FAKE_ADDRESS, linkProperties.getAddresses().get(0).getHostAddress());
632         assertEquals(1, linkProperties.getDnsServers().size());
633         assertEquals(FAKE_DNS, linkProperties.getDnsServers().get(0).getHostAddress());
634         assertEquals(FAKE_GATEWAY, linkProperties.getRoutes().get(0).getGateway().getHostAddress());
635     }
636 
isDataAllowed(DataConnectionReasons dataConnectionReasons)637     private boolean isDataAllowed(DataConnectionReasons dataConnectionReasons) {
638         try {
639             Method method = DcTracker.class.getDeclaredMethod("isDataAllowed",
640                     DataConnectionReasons.class);
641             method.setAccessible(true);
642             return (boolean) method.invoke(mDct, dataConnectionReasons);
643         } catch (Exception e) {
644             fail(e.toString());
645             return false;
646         }
647     }
648 
sendInitializationEvents()649     private void sendInitializationEvents() {
650         sendCarrierConfigChanged("");
651 
652         sendSimStateUpdated("");
653 
654         sendEventDataConnectionAttached("");
655 
656         waitForMs(200);
657     }
658 
sendCarrierConfigChanged(String messagePrefix)659     private void sendCarrierConfigChanged(String messagePrefix) {
660         logd(messagePrefix + "Sending EVENT_CARRIER_CONFIG_CHANGED");
661         mDct.sendEmptyMessage(DctConstants.EVENT_CARRIER_CONFIG_CHANGED);
662         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
663     }
664 
sendSimStateUpdated(String messagePrefix)665     private void sendSimStateUpdated(String messagePrefix) {
666         logd(messagePrefix + "Sending EVENT_SIM_STATE_UPDATED");
667         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_SIM_STATE_UPDATED,
668                 TelephonyManager.SIM_STATE_LOADED, 0));
669         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
670     }
671 
sendEventDataConnectionAttached(String messagePrefix)672     private void sendEventDataConnectionAttached(String messagePrefix) {
673         logd(messagePrefix + "Sending EVENT_DATA_CONNECTION_ATTACHED");
674         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
675         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
676     }
677 
678     // Test the unmetered APN setup when data is disabled.
679     @Test
680     @SmallTest
testTrySetupDataUnmeteredDefaultNotSelected()681     public void testTrySetupDataUnmeteredDefaultNotSelected() throws Exception {
682         initApns(PhoneConstants.APN_TYPE_XCAP, new String[]{PhoneConstants.APN_TYPE_XCAP});
683         doReturn(SubscriptionManager.INVALID_SUBSCRIPTION_ID).when(mIsub).getDefaultDataSubId();
684 
685         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
686                 new String[]{PhoneConstants.APN_TYPE_DEFAULT});
687 
688         sendInitializationEvents();
689 
690         mDct.enableApn(ApnSetting.TYPE_XCAP, DcTracker.REQUEST_TYPE_NORMAL, null);
691         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
692 
693         // Data connection is running on a different thread. Have to wait.
694         waitForMs(200);
695         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
696                 eq(AccessNetworkType.EUTRAN), any(DataProfile.class),
697                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
698                 any(Message.class));
699     }
700 
701     // Test the normal data call setup scenario.
702     @Test
703     @MediumTest
testDataSetup()704     public void testDataSetup() throws Exception {
705         mSimulatedCommands.setDataCallResult(true, createSetupDataCallResult());
706 
707         DataConnectionReasons dataConnectionReasons = new DataConnectionReasons();
708         boolean allowed = isDataAllowed(dataConnectionReasons);
709         assertFalse(dataConnectionReasons.toString(), allowed);
710 
711         logd("Sending EVENT_ENABLE_APN");
712         // APN id 0 is APN_TYPE_DEFAULT
713         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
714         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
715 
716         sendInitializationEvents();
717 
718         dataConnectionReasons = new DataConnectionReasons();
719         allowed = isDataAllowed(dataConnectionReasons);
720         assertTrue(dataConnectionReasons.toString(), allowed);
721 
722         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
723         // Verify if RIL command was sent properly.
724         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
725                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
726                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
727                 any(Message.class));
728         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
729 
730         verifyDataConnected(FAKE_APN1);
731     }
732 
733     // Test the scenario where the first data call setup is failed, and then retry the setup later.
734     @Test
735     @MediumTest
testDataRetry()736     public void testDataRetry() throws Exception {
737         AsyncResult ar = new AsyncResult(null,
738                 new Pair<>(true, DataEnabledSettings.REASON_USER_DATA_ENABLED), null);
739         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_ENABLED_CHANGED, ar));
740         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
741 
742         // LOST_CONNECTION(0x10004) is a non-permanent failure, so we'll retry data setup later.
743         SetupDataCallResult result = createSetupDataCallResult();
744         result.status = 0x10004;
745 
746         // Simulate RIL fails the data call setup
747         mSimulatedCommands.setDataCallResult(true, result);
748 
749         DataConnectionReasons dataConnectionReasons = new DataConnectionReasons();
750         boolean allowed = isDataAllowed(dataConnectionReasons);
751         assertFalse(dataConnectionReasons.toString(), allowed);
752 
753         logd("Sending EVENT_ENABLE_APN");
754         // APN id 0 is APN_TYPE_DEFAULT
755         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
756         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
757 
758         sendInitializationEvents();
759 
760         dataConnectionReasons = new DataConnectionReasons();
761         allowed = isDataAllowed(dataConnectionReasons);
762         assertTrue(dataConnectionReasons.toString(), allowed);
763 
764         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
765         // Verify if RIL command was sent properly.
766         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
767                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
768                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
769                 any(Message.class));
770         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
771 
772         // This time we'll let RIL command succeed.
773         mSimulatedCommands.setDataCallResult(true, createSetupDataCallResult());
774 
775         //Send event for reconnecting data
776         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
777         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_RECONNECT,
778                         mPhone.getPhoneId(), AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
779                         mApnContext));
780         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
781 
782         // Data connection is running on a different thread. Have to wait.
783         waitForMs(200);
784         dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
785         // Verify if RIL command was sent properly.
786         verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
787                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
788                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
789                 any(Message.class));
790         verifyDataProfile(dpCaptor.getValue(), FAKE_APN2, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
791 
792         // Verify connected with APN2 setting.
793         verifyDataConnected(FAKE_APN2);
794     }
795 
796     @Test
797     @MediumTest
798     @Ignore
799     @FlakyTest
testUserDisableData()800     public void testUserDisableData() throws Exception {
801         //step 1: setup two DataCalls one for Metered: default, another one for Non-metered: IMS
802         //set Default and MMS to be metered in the CarrierConfigManager
803         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
804                 new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
805         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
806         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
807 
808         sendInitializationEvents();
809 
810         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
811         verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
812                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
813                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
814                 any(Message.class));
815         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 5, 1, NETWORK_TYPE_LTE_BITMASK);
816 
817         logd("Sending DATA_DISABLED_CMD");
818         doReturn(false).when(mDataEnabledSettings).isDataEnabled();
819         doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
820         AsyncResult ar = new AsyncResult(null,
821                 new Pair<>(false, DataEnabledSettings.REASON_USER_DATA_ENABLED), null);
822         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_ENABLED_CHANGED, ar));
823         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
824 
825         // Data connection is running on a different thread. Have to wait.
826         waitForMs(200);
827         // expected tear down all metered DataConnections
828         verify(mSimulatedCommandsVerifier, times(1)).deactivateDataCall(
829                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
830                 any(Message.class));
831         assertTrue(mDct.isAnyDataConnected());
832         assertEquals(DctConstants.State.IDLE, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
833         assertEquals(DctConstants.State.CONNECTED, mDct.getState(PhoneConstants.APN_TYPE_IMS));
834     }
835 
836     @Test
837     @MediumTest
testTrySetupDataMmsAllowedDataDisabled()838     public void testTrySetupDataMmsAllowedDataDisabled() throws Exception {
839         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
840                 new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
841         mDct.enableApn(ApnSetting.TYPE_MMS, DcTracker.REQUEST_TYPE_NORMAL, null);
842         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
843 
844         sendInitializationEvents();
845 
846         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
847         verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
848                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
849                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
850                 any(Message.class));
851 
852 
853         List<DataProfile> dataProfiles = dpCaptor.getAllValues();
854         assertEquals(2, dataProfiles.size());
855 
856         //Verify FAKE_APN1
857         Optional<DataProfile> fakeApn1 = dataProfiles.stream()
858                 .filter(dp -> dp.getApn().equals(FAKE_APN1))
859                 .findFirst();
860         assertTrue(fakeApn1.isPresent());
861         verifyDataProfile(fakeApn1.get(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
862 
863         //Verify FAKE_APN6
864         Optional<DataProfile> fakeApn6 = dataProfiles.stream()
865                 .filter(dp -> dp.getApn().equals(FAKE_APN6))
866                 .findFirst();
867         assertTrue(fakeApn6.isPresent());
868         verifyDataProfile(fakeApn6.get(), FAKE_APN6, 0, ApnSetting.TYPE_MMS | ApnSetting.TYPE_XCAP,
869                 1, NETWORK_TYPE_LTE_BITMASK);
870 
871         logd("Sending DATA_DISABLED_CMD for default data");
872         doReturn(false).when(mDataEnabledSettings).isDataEnabled();
873         doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
874         mDct.obtainMessage(DctConstants.EVENT_DATA_ENABLED_OVERRIDE_RULES_CHANGED).sendToTarget();
875         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
876 
877         // Data connection is running on a different thread. Have to wait.
878         waitForMs(200);
879         // expected tear down all metered DataConnections
880         verify(mSimulatedCommandsVerifier, times(2)).deactivateDataCall(
881                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
882                 any(Message.class));
883         assertEquals(DctConstants.State.IDLE, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
884         assertEquals(DctConstants.State.IDLE, mDct.getState(PhoneConstants.APN_TYPE_MMS));
885 
886         clearInvocations(mSimulatedCommandsVerifier);
887         doReturn(true).when(mDataEnabledSettings).isDataEnabled(ApnSetting.TYPE_MMS);
888         mDct.obtainMessage(DctConstants.EVENT_DATA_ENABLED_OVERRIDE_RULES_CHANGED).sendToTarget();
889         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
890 
891         // Data connection is running on a different thread. Have to wait.
892         waitForMs(200);
893         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
894                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
895                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
896                 any(Message.class));
897         assertEquals(DctConstants.State.IDLE, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
898         assertEquals(DctConstants.State.CONNECTED, mDct.getState(PhoneConstants.APN_TYPE_MMS));
899     }
900 
901     @Test
902     @MediumTest
testUserDisableRoaming()903     public void testUserDisableRoaming() throws Exception {
904         //step 1: setup two DataCalls one for Metered: default, another one for Non-metered: IMS
905         //step 2: set roaming disabled, data is enabled
906         //step 3: under roaming service
907         //step 4: only tear down metered data connections.
908 
909         //set Default and MMS to be metered in the CarrierConfigManager
910         boolean roamingEnabled = mDct.getDataRoamingEnabled();
911 
912         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_ROAMING_APN_TYPES_STRINGS,
913                 new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
914 
915         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
916         waitForHandlerAction(mDct, 1000);
917         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
918         waitForHandlerAction(mDct, 1000);
919 
920         sendInitializationEvents();
921 
922         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
923         verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
924                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
925                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
926                 any(Message.class));
927         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
928 
929         //user is in roaming
930         doReturn(true).when(mServiceState).getDataRoaming();
931         logd("Sending DISABLE_ROAMING_CMD");
932         mDct.setDataRoamingEnabledByUser(false);
933         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_ROAMING_ON));
934         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
935 
936         // Data connection is running on a different thread. Have to wait.
937         waitForMs(200);
938         // expected tear down all metered DataConnections
939         verify(mSimulatedCommandsVerifier, times(1)).deactivateDataCall(
940                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
941                 any(Message.class));
942         assertTrue(mDct.isAnyDataConnected());
943         assertEquals(DctConstants.State.IDLE, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
944         assertEquals(DctConstants.State.CONNECTED, mDct.getState(PhoneConstants.APN_TYPE_IMS));
945 
946         // reset roaming settings / data enabled settings at end of this test
947         mDct.setDataRoamingEnabledByUser(roamingEnabled);
948         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
949     }
950 
951     @Test
952     @MediumTest
testDataCallOnUserDisableRoaming()953     public void testDataCallOnUserDisableRoaming() throws Exception {
954         //step 1: mock under roaming service and user disabled roaming from settings.
955         //step 2: user toggled data settings on
956         //step 3: only non-metered data call is established
957 
958         boolean roamingEnabled = mDct.getDataRoamingEnabled();
959         doReturn(true).when(mServiceState).getDataRoaming();
960 
961         //set Default and MMS to be metered in the CarrierConfigManager
962         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_ROAMING_APN_TYPES_STRINGS,
963                 new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
964         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
965         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
966 
967         logd("Sending DISABLE_ROAMING_CMD");
968         mDct.setDataRoamingEnabledByUser(false);
969 
970         sendInitializationEvents();
971 
972         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
973 
974         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
975                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
976                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
977                 any(Message.class));
978         verifyDataProfile(dpCaptor.getValue(), FAKE_APN3, 2, 64, 0, 0);
979 
980         assertTrue(mDct.isAnyDataConnected());
981         assertEquals(DctConstants.State.IDLE, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
982         assertEquals(DctConstants.State.CONNECTED, mDct.getState(PhoneConstants.APN_TYPE_IMS));
983 
984         // reset roaming settings / data enabled settings at end of this test
985         mDct.setDataRoamingEnabledByUser(roamingEnabled);
986         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
987     }
988 
989     // Test the default data switch scenario.
990     @FlakyTest /* flakes 1.57% of the time */
991     @Test
992     @MediumTest
testDDSResetAutoAttach()993     public void testDDSResetAutoAttach() throws Exception {
994         mContextFixture.putBooleanResource(
995                 com.android.internal.R.bool.config_auto_attach_data_on_creation, true);
996         testDataSetup();
997         assertTrue(mDct.shouldAutoAttach());
998         mDct.sendEmptyMessage(DctConstants.EVENT_CARRIER_CONFIG_CHANGED);
999         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1000         // The auto attach flag should be reset after update
1001         assertFalse(mDct.shouldAutoAttach());
1002     }
1003 
1004     // Test for API carrierActionSetMeteredApnsEnabled.
1005     @FlakyTest
1006     @Ignore
1007     @Test
1008     @MediumTest
testCarrierActionSetMeteredApnsEnabled()1009     public void testCarrierActionSetMeteredApnsEnabled() throws Exception {
1010         //step 1: setup two DataCalls one for Internet and IMS
1011         //step 2: set data is enabled
1012         //step 3: cold sim is detected
1013         //step 4: all data connection is torn down
1014         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1015                 new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
1016 
1017         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
1018         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1019 
1020         sendInitializationEvents();
1021 
1022         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1023         verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
1024                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1025                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1026                 any(Message.class));
1027         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 5, 1, NETWORK_TYPE_LTE_BITMASK);
1028         assertTrue(mDct.isAnyDataConnected());
1029 
1030         AsyncResult ar = new AsyncResult(null,
1031                 new Pair<>(false, DataEnabledSettings.REASON_DATA_ENABLED_BY_CARRIER), null);
1032         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_ENABLED_CHANGED, ar));
1033         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1034 
1035         // Data connection is running on a different thread. Have to wait.
1036         waitForMs(200);
1037         // Validate all metered data connections have been torn down
1038         verify(mSimulatedCommandsVerifier, times(1)).deactivateDataCall(
1039                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
1040                 any(Message.class));
1041         assertTrue(mDct.isAnyDataConnected());
1042         assertEquals(DctConstants.State.IDLE, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
1043     }
1044 
initApns(String targetApn, String[] canHandleTypes)1045     private void initApns(String targetApn, String[] canHandleTypes) {
1046         doReturn(targetApn).when(mApnContext).getApnType();
1047         doReturn(ApnSetting.getApnTypesBitmaskFromString(mApnContext.getApnType()))
1048                 .when(mApnContext).getApnTypeBitmask();
1049         doReturn(true).when(mApnContext).isConnectable();
1050         ApnSetting apnSetting = createApnSetting(ApnSetting.getApnTypesBitmaskFromString(
1051                 TextUtils.join(",", canHandleTypes)));
1052         doReturn(apnSetting).when(mApnContext).getNextApnSetting();
1053         doReturn(apnSetting).when(mApnContext).getApnSetting();
1054         doReturn(mDataConnection).when(mApnContext).getDataConnection();
1055         doReturn(true).when(mApnContext).isEnabled();
1056         doReturn(true).when(mApnContext).isDependencyMet();
1057         doReturn(true).when(mApnContext).isReady();
1058         doReturn(false).when(mApnContext).hasRestrictedRequests(eq(true));
1059     }
1060 
1061     // Test the emergency APN setup.
1062     @Test
1063     @SmallTest
testTrySetupDataEmergencyApn()1064     public void testTrySetupDataEmergencyApn() throws Exception {
1065         initApns(PhoneConstants.APN_TYPE_EMERGENCY,
1066                 new String[]{PhoneConstants.APN_TYPE_EMERGENCY});
1067         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TRY_SETUP_DATA, mApnContext));
1068         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1069 
1070         waitForMs(200);
1071 
1072         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
1073                 eq(AccessNetworkType.EUTRAN), any(DataProfile.class), eq(false), eq(false),
1074                 eq(DataService.REQUEST_REASON_NORMAL), any(), any(Message.class));
1075     }
1076 
1077     // Test the XCAP APN setup.
1078     @Test
1079     @SmallTest
testTrySetupDataXcapApn()1080     public void testTrySetupDataXcapApn() throws Exception {
1081         initApns(PhoneConstants.APN_TYPE_XCAP, new String[]{PhoneConstants.APN_TYPE_XCAP});
1082         mDct.enableApn(ApnSetting.TYPE_XCAP, DcTracker.REQUEST_TYPE_NORMAL, null);
1083 
1084         sendInitializationEvents();
1085 
1086         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
1087                 eq(AccessNetworkType.EUTRAN), any(DataProfile.class), eq(false), eq(false),
1088                 eq(DataService.REQUEST_REASON_NORMAL), any(), any(Message.class));
1089     }
1090 
1091     @Test
1092     @SmallTest
testGetDataConnectionState()1093     public void testGetDataConnectionState() throws Exception {
1094         initApns(PhoneConstants.APN_TYPE_SUPL,
1095                 new String[]{PhoneConstants.APN_TYPE_SUPL, PhoneConstants.APN_TYPE_DEFAULT});
1096         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1097                 new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1098         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1099         mDct.enableApn(ApnSetting.TYPE_SUPL, DcTracker.REQUEST_TYPE_NORMAL, null);
1100 
1101         sendInitializationEvents();
1102 
1103         // Assert that both APN_TYPE_SUPL & APN_TYPE_DEFAULT are connected even we only setup data
1104         // for APN_TYPE_SUPL
1105         assertEquals(DctConstants.State.CONNECTED, mDct.getState(PhoneConstants.APN_TYPE_SUPL));
1106         assertEquals(DctConstants.State.CONNECTED, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
1107     }
1108 
1109     // Test the unmetered APN setup when data is disabled.
1110     @Test
1111     @SmallTest
testTrySetupDataUnmeteredDataDisabled()1112     public void testTrySetupDataUnmeteredDataDisabled() throws Exception {
1113         initApns(PhoneConstants.APN_TYPE_SUPL, new String[]{PhoneConstants.APN_TYPE_SUPL});
1114         doReturn(false).when(mDataEnabledSettings).isDataEnabled();
1115         doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
1116 
1117         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1118                 new String[]{PhoneConstants.APN_TYPE_FOTA});
1119 
1120         mDct.enableApn(ApnSetting.TYPE_SUPL, DcTracker.REQUEST_TYPE_NORMAL, null);
1121 
1122         sendInitializationEvents();
1123 
1124         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
1125                 eq(AccessNetworkType.EUTRAN), any(DataProfile.class),
1126                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1127                 any(Message.class));
1128     }
1129 
1130     // Test the unmetered default APN setup when data is disabled. Default APN should always honor
1131     // the users's setting.
1132     @Test
1133     @SmallTest
testTrySetupDataUnmeteredDefaultDataDisabled()1134     public void testTrySetupDataUnmeteredDefaultDataDisabled() throws Exception {
1135         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1136         doReturn(false).when(mDataEnabledSettings).isDataEnabled();
1137         doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
1138 
1139         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1140                 new String[]{PhoneConstants.APN_TYPE_MMS});
1141 
1142         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1143 
1144         sendInitializationEvents();
1145 
1146         verify(mSimulatedCommandsVerifier, never()).setupDataCall(
1147                 eq(AccessNetworkType.EUTRAN), any(DataProfile.class),
1148                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1149                 any(Message.class));
1150     }
1151 
1152 
1153     // Test the metered APN setup when data is disabled.
1154     @Test
1155     @SmallTest
testTrySetupMeteredDataDisabled()1156     public void testTrySetupMeteredDataDisabled() throws Exception {
1157         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1158         doReturn(false).when(mDataEnabledSettings).isDataEnabled();
1159         doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
1160 
1161         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1162                 new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1163 
1164         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1165 
1166         sendInitializationEvents();
1167 
1168         verify(mSimulatedCommandsVerifier, times(0)).setupDataCall(anyInt(), any(DataProfile.class),
1169                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1170                 any(Message.class));
1171     }
1172 
1173     // Test the restricted data request when data is disabled.
1174     @Test
1175     @SmallTest
testTrySetupRestrictedDataDisabled()1176     public void testTrySetupRestrictedDataDisabled() throws Exception {
1177         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1178         doReturn(false).when(mDataEnabledSettings).isDataEnabled();
1179         doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
1180 
1181         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1182                 new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1183 
1184         sendInitializationEvents();
1185 
1186         NetworkRequest nr = new NetworkRequest.Builder()
1187                 .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
1188                 .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
1189                 .build();
1190         mDct.requestNetwork(nr, DcTracker.REQUEST_TYPE_NORMAL, null);
1191         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1192 
1193         // Data connection is running on a different thread. Have to wait.
1194         waitForMs(200);
1195         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(anyInt(), any(DataProfile.class),
1196                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1197                 any(Message.class));
1198     }
1199 
1200     // Test the restricted data request when roaming is disabled.
1201     @Test
1202     @SmallTest
testTrySetupRestrictedRoamingDisabled()1203     public void testTrySetupRestrictedRoamingDisabled() throws Exception {
1204         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1205 
1206         mDct.setDataRoamingEnabledByUser(false);
1207         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1208                 new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1209         //user is in roaming
1210         doReturn(true).when(mServiceState).getDataRoaming();
1211 
1212         sendInitializationEvents();
1213 
1214         NetworkRequest nr = new NetworkRequest.Builder()
1215                 .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
1216                 .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
1217                 .build();
1218         mDct.requestNetwork(nr, DcTracker.REQUEST_TYPE_NORMAL, null);
1219         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1220 
1221         // Data connection is running on a different thread. Have to wait.
1222         waitForMs(200);
1223         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(anyInt(), any(DataProfile.class),
1224                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1225                 any(Message.class));
1226     }
1227 
1228     // Test the default data when data is not connectable.
1229     @Test
1230     @SmallTest
testTrySetupNotConnectable()1231     public void testTrySetupNotConnectable() throws Exception {
1232         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
1233         doReturn(false).when(mApnContext).isConnectable();
1234 
1235         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1236                 new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1237 
1238         sendInitializationEvents();
1239 
1240         verify(mSimulatedCommandsVerifier, times(0)).setupDataCall(anyInt(), any(DataProfile.class),
1241                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1242                 any(Message.class));
1243     }
1244 
1245     // Test the default data on IWLAN.
1246     @Test
1247     @SmallTest
testTrySetupDefaultOnIWLAN()1248     public void testTrySetupDefaultOnIWLAN() throws Exception {
1249         doReturn(true).when(mTransportManager).isInLegacyMode();
1250         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
1251         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
1252                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_IWLAN)
1253                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
1254                 .build();
1255         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
1256                 anyInt(), anyInt());
1257 
1258         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1259                 new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1260 
1261         sendInitializationEvents();
1262 
1263         verify(mSimulatedCommandsVerifier, times(0)).setupDataCall(anyInt(), any(DataProfile.class),
1264                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1265                 any(Message.class));
1266     }
1267 
1268     // Test the default data when the phone is in ECBM.
1269     @Test
1270     @SmallTest
testTrySetupDefaultInECBM()1271     public void testTrySetupDefaultInECBM() throws Exception {
1272         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
1273         doReturn(true).when(mPhone).isInEcm();
1274 
1275         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1276                 new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1277 
1278         sendInitializationEvents();
1279 
1280         verify(mSimulatedCommandsVerifier, times(0)).setupDataCall(anyInt(), any(DataProfile.class),
1281                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1282                 any(Message.class));
1283     }
1284 
1285     // Test update waiting apn list when on data rat change
1286     @FlakyTest /* flakes 0.86% of the time */
1287     @Ignore
1288     @Test
1289     @SmallTest
testUpdateWaitingApnListOnDataRatChange()1290     public void testUpdateWaitingApnListOnDataRatChange() throws Exception {
1291         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
1292                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_EHRPD)
1293                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
1294                 .build();
1295         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
1296                 anyInt(), anyInt());
1297         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1298                 new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1299         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1300         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
1301 
1302         sendInitializationEvents();
1303 
1304         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1305         // Verify if RIL command was sent properly.
1306         verify(mSimulatedCommandsVerifier).setupDataCall(
1307                 eq(AccessNetworkType.CDMA2000), dpCaptor.capture(),
1308                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1309                 any(Message.class));
1310         verifyDataProfile(dpCaptor.getValue(), FAKE_APN4, 0, 21, 2, NETWORK_TYPE_EHRPD_BITMASK);
1311         assertTrue(mDct.isAnyDataConnected());
1312 
1313         //data rat change from ehrpd to lte
1314         logd("Sending EVENT_DATA_RAT_CHANGED");
1315         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
1316                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_LTE)
1317                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
1318                 .build();
1319         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
1320                 anyInt(), anyInt());
1321         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_RAT_CHANGED, null));
1322         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1323 
1324         // Data connection is running on a different thread. Have to wait.
1325         waitForMs(200);
1326         // Verify the disconnected data call due to rat change and retry manger schedule another
1327         // data call setup
1328         verify(mSimulatedCommandsVerifier, times(1)).deactivateDataCall(
1329                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
1330                 any(Message.class));
1331         verify(mAlarmManager, times(1)).setExact(eq(AlarmManager.ELAPSED_REALTIME_WAKEUP),
1332                 anyLong(), any(PendingIntent.class));
1333 
1334         //Send event for reconnecting data
1335         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
1336         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_RECONNECT,
1337                         mPhone.getPhoneId(), AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
1338                         mApnContext));
1339         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1340 
1341         // Data connection is running on a different thread. Have to wait.
1342         waitForMs(200);
1343         // Verify if RIL command was sent properly.
1344         verify(mSimulatedCommandsVerifier).setupDataCall(
1345                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1346                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1347                 any(Message.class));
1348         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
1349         assertTrue(mDct.isAnyDataConnected());
1350     }
1351 
1352     // Test for fetchDunApns()
1353     @Test
1354     @SmallTest
testFetchDunApn()1355     public void testFetchDunApn() {
1356 
1357         sendInitializationEvents();
1358 
1359         String dunApnString = "[ApnSettingV3]HOT mobile PC,pc.hotm,,,,,,,,,440,10,,DUN,,,true,"
1360                 + "0,,,,,,,,";
1361         ApnSetting dunApnExpected = ApnSetting.fromString(dunApnString);
1362 
1363         Settings.Global.putString(mContext.getContentResolver(),
1364                 Settings.Global.TETHER_DUN_APN, dunApnString);
1365         // should return APN from Setting
1366         ApnSetting dunApn = mDct.fetchDunApns().get(0);
1367         assertTrue(dunApnExpected.equals(dunApn));
1368 
1369         Settings.Global.putString(mContext.getContentResolver(),
1370                 Settings.Global.TETHER_DUN_APN, null);
1371         // should return APN from db
1372         dunApn = mDct.fetchDunApns().get(0);
1373         assertEquals(FAKE_APN5, dunApn.getApnName());
1374     }
1375 
1376     // Test for fetchDunApns() with apn set id
1377     @Test
1378     @SmallTest
testFetchDunApnWithPreferredApnSet()1379     public void testFetchDunApnWithPreferredApnSet() {
1380         sendCarrierConfigChanged("testFetchDunApnWithPreferredApnSet: ");
1381 
1382         // apnSetId=1
1383         String dunApnString1 = "[ApnSettingV5]HOT mobile PC,pc.hotm,,,,,,,,,440,10,,DUN,,,true,"
1384                 + "0,,,,,,,,,,1";
1385         // apnSetId=0
1386         String dunApnString2 = "[ApnSettingV5]HOT mobile PC,pc.coldm,,,,,,,,,440,10,,DUN,,,true,"
1387                 + "0,,,,,,,,,,2";
1388 
1389         ApnSetting dunApnExpected = ApnSetting.fromString(dunApnString1);
1390 
1391         ContentResolver cr = mContext.getContentResolver();
1392         Settings.Global.putString(cr, Settings.Global.TETHER_DUN_APN,
1393                 dunApnString1 + ";" + dunApnString2);
1394 
1395         // set that we prefer apn set 1
1396         ContentValues values = new ContentValues();
1397         values.put(Telephony.Carriers.APN_SET_ID, 1);
1398         cr.update(PREFERAPN_URI, values, null, null);
1399 
1400         // return APN from Setting with apnSetId=1
1401         ArrayList<ApnSetting> dunApns = mDct.fetchDunApns();
1402         assertEquals(1, dunApns.size());
1403         assertEquals(1, dunApns.get(0).getApnSetId());
1404         assertTrue(dunApnExpected.equals(dunApns.get(0)));
1405 
1406         // set that we prefer apn set 2
1407         values = new ContentValues();
1408         values.put(Telephony.Carriers.APN_SET_ID, 2);
1409         cr.update(PREFERAPN_URI, values, null, null);
1410 
1411         // return APN from Setting with apnSetId=2
1412         dunApns = mDct.fetchDunApns();
1413         assertEquals(1, dunApns.size());
1414         assertEquals(2, dunApns.get(0).getApnSetId());
1415         dunApnExpected = ApnSetting.fromString(dunApnString2);
1416         assertTrue(dunApnExpected.equals(dunApns.get(0)));
1417     }
1418 
1419     @Test
1420     @SmallTest
testFetchDunApnWhileRoaming()1421     public void testFetchDunApnWhileRoaming() {
1422         doReturn(true).when(mServiceState).getRoaming();
1423         mBundle.putBoolean(CarrierConfigManager
1424                 .KEY_DISABLE_DUN_APN_WHILE_ROAMING_WITH_PRESET_APN_BOOL, true);
1425 
1426         sendInitializationEvents();
1427 
1428         String dunApnString = "[ApnSettingV3]HOT mobile PC,pc.hotm,,,,,,,,,440,10,,DUN,,,true,"
1429                 + "0,,,,,,,,";
1430 
1431         Settings.Global.putString(mContext.getContentResolver(),
1432                 Settings.Global.TETHER_DUN_APN, dunApnString);
1433 
1434         DcTracker spyDct = spy(mDct);
1435         doReturn(true).when(spyDct).isPreferredApnUserEdited();
1436         // Expect non-empty DUN APN list
1437         assertEquals(1, spyDct.fetchDunApns().size());
1438 
1439         doReturn(false).when(spyDct).isPreferredApnUserEdited();
1440         // Expect empty DUN APN list
1441         assertEquals(0, spyDct.fetchDunApns().size());
1442 
1443         Settings.Global.putString(mContext.getContentResolver(),
1444                 Settings.Global.TETHER_DUN_APN, null);
1445     }
1446 
1447     // This tests simulates the race case where the sim status change event is triggered, the
1448     // default data connection is attached, and then the carrier config gets changed which bumps
1449     // the database id which we want to ignore when cleaning up connections and matching against
1450     // the dun APN.  Tests b/158908392.
1451     @Test
1452     @SmallTest
testCheckForCompatibleDataConnectionWithDunWhenIdsChange()1453     public void testCheckForCompatibleDataConnectionWithDunWhenIdsChange() throws Exception {
1454         //Set dun as a support apn type of FAKE_APN1
1455         mApnSettingContentProvider.setFakeApn1Types("default,supl,dun");
1456 
1457         // Enable the default apn
1458         mSimulatedCommands.setDataCallResult(true, createSetupDataCallResult());
1459         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1460         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1461 
1462         //Load the sim and attach the data connection without firing the carrier changed event
1463         final String logMsgPrefix = "testCheckForCompatibleDataConnectionWithDunWhenIdsChange: ";
1464         sendSimStateUpdated(logMsgPrefix);
1465         sendEventDataConnectionAttached(logMsgPrefix);
1466         waitForMs(200);
1467 
1468         // Confirm that FAKE_APN1 comes up as a dun candidate
1469         ApnSetting dunApn = mDct.fetchDunApns().get(0);
1470         assertEquals(dunApn.getApnName(), FAKE_APN1);
1471         Map<Integer, ApnContext> apnContexts = mDct.getApnContexts()
1472                 .stream().collect(Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
1473 
1474         //Double check that the default apn content is connected while the dun apn context is not
1475         assertEquals(apnContexts.get(ApnSetting.TYPE_DEFAULT).getState(),
1476                 DctConstants.State.CONNECTED);
1477         assertNotEquals(apnContexts.get(ApnSetting.TYPE_DUN).getState(),
1478                 DctConstants.State.CONNECTED);
1479 
1480 
1481         //Change the row ids the same way as what happens when we have old apn values in the
1482         //carrier table
1483         mApnSettingContentProvider.setRowIdOffset(100);
1484         sendCarrierConfigChanged(logMsgPrefix);
1485         waitForMs(200);
1486 
1487         mDct.enableApn(ApnSetting.TYPE_DUN, DcTracker.REQUEST_TYPE_NORMAL, null);
1488         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1489 
1490         Map<Integer, ApnContext> apnContextsAfterRowIdsChanged = mDct.getApnContexts()
1491                 .stream().collect(Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
1492 
1493         //Make sure that the data connection used earlier wasn't cleaned up and still in use.
1494         assertEquals(apnContexts.get(ApnSetting.TYPE_DEFAULT).getDataConnection(),
1495                 apnContextsAfterRowIdsChanged.get(ApnSetting.TYPE_DEFAULT).getDataConnection());
1496 
1497         //Check that the DUN is using the same active data connection
1498         assertEquals(apnContexts.get(ApnSetting.TYPE_DEFAULT).getDataConnection(),
1499                 apnContextsAfterRowIdsChanged.get(ApnSetting.TYPE_DUN).getDataConnection());
1500     }
1501 
1502     // Test oos
1503     @Test
1504     @SmallTest
testDataRatChangeOOS()1505     public void testDataRatChangeOOS() throws Exception {
1506         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
1507                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_EHRPD)
1508                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
1509                 .build();
1510         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
1511                 anyInt(), anyInt());
1512 
1513         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1514                 new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1515         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1516         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
1517 
1518         sendInitializationEvents();
1519 
1520         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1521         // Verify if RIL command was sent properly.
1522         verify(mSimulatedCommandsVerifier).setupDataCall(
1523                 eq(AccessNetworkType.CDMA2000), dpCaptor.capture(),
1524                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1525                 any(Message.class));
1526         verifyDataProfile(dpCaptor.getValue(), FAKE_APN4, 0, 21, 2, NETWORK_TYPE_EHRPD_BITMASK);
1527         assertTrue(mDct.isAnyDataConnected());
1528 
1529         // Data rat change from ehrpd to unknown due to OOS
1530         logd("Sending EVENT_DATA_RAT_CHANGED");
1531         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
1532                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_UNKNOWN)
1533                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
1534                 .build();
1535         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
1536                 anyInt(), anyInt());
1537         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_RAT_CHANGED, null));
1538         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1539 
1540         // Data connection is running on a different thread. Have to wait.
1541         waitForMs(200);
1542         // Verify data connection is on
1543         verify(mSimulatedCommandsVerifier, times(0)).deactivateDataCall(
1544                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
1545                 any(Message.class));
1546 
1547         // Data rat resume from unknown to ehrpd
1548         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
1549                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_EHRPD)
1550                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
1551                 .build();
1552         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
1553                 anyInt(), anyInt());
1554         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_RAT_CHANGED, null));
1555         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1556 
1557         // Verify the same data connection
1558         assertEquals(FAKE_APN4, mDct.getActiveApnString(PhoneConstants.APN_TYPE_DEFAULT));
1559         assertTrue(mDct.isAnyDataConnected());
1560     }
1561 
1562     // Test provisioning
1563     /*@Test
1564     @SmallTest
1565     public void testDataEnableInProvisioning() throws Exception {
1566         ContentResolver resolver = mContext.getContentResolver();
1567 
1568         assertEquals(1, Settings.Global.getInt(resolver, Settings.Global.MOBILE_DATA));
1569         assertTrue(mDct.isDataEnabled());
1570         assertTrue(mDct.isUserDataEnabled());
1571 
1572         mDct.setUserDataEnabled(false);
1573         waitForMs(200);
1574 
1575         assertEquals(0, Settings.Global.getInt(resolver, Settings.Global.MOBILE_DATA));
1576         assertFalse(mDct.isDataEnabled());
1577         assertFalse(mDct.isUserDataEnabled());
1578 
1579         // Changing provisioned to 0.
1580         Settings.Global.putInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0);
1581         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DEVICE_PROVISIONED_CHANGE, null));
1582         waitForMs(200);
1583 
1584         assertTrue(mDct.isDataEnabled());
1585         assertTrue(mDct.isUserDataEnabled());
1586 
1587         // Enable user data during provisioning. It should write to
1588         // Settings.Global.MOBILE_DATA and keep data enabled when provisioned.
1589         mDct.setUserDataEnabled(true);
1590         Settings.Global.putInt(resolver, Settings.Global.DEVICE_PROVISIONED, 1);
1591         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DEVICE_PROVISIONED_CHANGE, null));
1592         waitForMs(200);
1593 
1594         assertTrue(mDct.isDataEnabled());
1595         assertTrue(mDct.isUserDataEnabled());
1596         assertEquals(1, Settings.Global.getInt(resolver, Settings.Global.MOBILE_DATA));
1597     }*/
1598 
1599     /*
1600     @Test
1601     @SmallTest
1602     public void testNotifyDataEnabledChanged() throws Exception {
1603         doAnswer(invocation -> {
1604             mMessage = (Message) invocation.getArguments()[0];
1605             return true;
1606         }).when(mHandler).sendMessageDelayed(any(), anyLong());
1607 
1608         // Test registration.
1609         mDct.registerForDataEnabledChanged(mHandler, DATA_ENABLED_CHANGED, null);
1610         verifyDataEnabledChangedMessage(true, DataEnabledSettings.REASON_REGISTERED);
1611 
1612         // Disable user data. Should receive data enabled change to false.
1613         mDct.setUserDataEnabled(false);
1614         waitForMs(200);
1615         verifyDataEnabledChangedMessage(false, DataEnabledSettings.REASON_USER_DATA_ENABLED);
1616 
1617         // Changing provisioned to 0. Shouldn't receive any message, as data enabled remains false.
1618         ContentResolver resolver = mContext.getContentResolver();
1619         Settings.Global.putInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0);
1620         Settings.Global.putInt(resolver, Settings.Global.DEVICE_PROVISIONING_MOBILE_DATA_ENABLED,
1621                 0);
1622         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DEVICE_PROVISIONED_CHANGE, null));
1623         waitForMs(200);
1624         assertFalse(mDct.isDataEnabled());
1625         verify(mHandler, never()).sendMessageDelayed(any(), anyLong());
1626 
1627         // Changing provisioningDataEnabled to 1. It should trigger data enabled change to true.
1628         Settings.Global.putInt(resolver,
1629                 Settings.Global.DEVICE_PROVISIONING_MOBILE_DATA_ENABLED, 1);
1630         mDct.sendMessage(mDct.obtainMessage(
1631                 DctConstants.EVENT_DEVICE_PROVISIONING_DATA_SETTING_CHANGE, null));
1632         waitForMs(200);
1633         verifyDataEnabledChangedMessage(
1634                 true, DataEnabledSettings.REASON_PROVISIONING_DATA_ENABLED_CHANGED);
1635     }*/
1636 
1637     @Test
1638     @SmallTest
testNetworkStatusChangedRecoveryOFF()1639     public void testNetworkStatusChangedRecoveryOFF() throws Exception {
1640         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1641                 new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
1642         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
1643         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1644 
1645         sendInitializationEvents();
1646 
1647         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1648         verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
1649                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1650                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1651                 any(Message.class));
1652         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
1653 
1654         logd("Sending EVENT_NETWORK_STATUS_CHANGED");
1655         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NETWORK_STATUS_CHANGED,
1656                 NetworkAgent.VALID_NETWORK, 1, null));
1657         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1658 
1659         logd("Sending EVENT_NETWORK_STATUS_CHANGED");
1660         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NETWORK_STATUS_CHANGED,
1661                 NetworkAgent.INVALID_NETWORK, 1, null));
1662         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1663 
1664         waitForMs(200);
1665 
1666         // Verify that its no-op when the new data stall detection feature is disabled
1667         verify(mSimulatedCommandsVerifier, times(0)).getDataCallList(any(Message.class));
1668     }
1669 
1670     @FlakyTest
1671     @Test
1672     @SmallTest
testNetworkStatusChangedRecoveryON()1673     public void testNetworkStatusChangedRecoveryON() throws Exception {
1674         ContentResolver resolver = mContext.getContentResolver();
1675         Settings.Global.putInt(resolver, Settings.Global.DATA_STALL_RECOVERY_ON_BAD_NETWORK, 1);
1676         Settings.System.putInt(resolver, "radio.data.stall.recovery.action", 0);
1677         doReturn(new SignalStrength()).when(mPhone).getSignalStrength();
1678 
1679         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1680                 new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
1681         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
1682         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1683 
1684         sendInitializationEvents();
1685 
1686         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1687         verify(mSimulatedCommandsVerifier, timeout(TEST_TIMEOUT).times(2)).setupDataCall(
1688                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1689                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1690                 any(Message.class));
1691         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1692         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
1693 
1694         logd("Sending EVENT_NETWORK_STATUS_CHANGED");
1695         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NETWORK_STATUS_CHANGED,
1696                 NetworkAgent.VALID_NETWORK, 1, null));
1697         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1698 
1699         logd("Sending EVENT_NETWORK_STATUS_CHANGED");
1700         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NETWORK_STATUS_CHANGED,
1701                 NetworkAgent.INVALID_NETWORK, 1, null));
1702         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1703 
1704         // Data connection is running on a different thread. Have to wait.
1705         waitForMs(200);
1706         verify(mSimulatedCommandsVerifier, times(1)).getDataCallList(any(Message.class));
1707     }
1708 
1709     @FlakyTest
1710     @Test
1711     @SmallTest
testRecoveryStepPDPReset()1712     public void testRecoveryStepPDPReset() throws Exception {
1713         ContentResolver resolver = mContext.getContentResolver();
1714         Settings.Global.putInt(resolver, Settings.Global.DATA_STALL_RECOVERY_ON_BAD_NETWORK, 1);
1715         Settings.Global.putLong(resolver,
1716                 Settings.Global.MIN_DURATION_BETWEEN_RECOVERY_STEPS_IN_MS, 100);
1717         Settings.System.putInt(resolver, "radio.data.stall.recovery.action", 1);
1718         doReturn(new SignalStrength()).when(mPhone).getSignalStrength();
1719 
1720         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1721                 new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
1722         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
1723         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1724 
1725         sendInitializationEvents();
1726 
1727         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1728         verify(mSimulatedCommandsVerifier, timeout(TEST_TIMEOUT).times(2)).setupDataCall(
1729                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1730                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1731                 any(Message.class));
1732         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
1733 
1734         logd("Sending EVENT_NETWORK_STATUS_CHANGED false");
1735         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NETWORK_STATUS_CHANGED,
1736                 NetworkAgent.INVALID_NETWORK, 1, null));
1737         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1738 
1739         waitForMs(200);
1740 
1741         // expected tear down all DataConnections
1742         verify(mSimulatedCommandsVerifier, times(1)).deactivateDataCall(
1743                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
1744                 any(Message.class));
1745     }
1746 
1747 
1748     @Test
1749     @SmallTest
testRecoveryStepReRegister()1750     public void testRecoveryStepReRegister() throws Exception {
1751         ContentResolver resolver = mContext.getContentResolver();
1752         Settings.Global.putInt(resolver, Settings.Global.DATA_STALL_RECOVERY_ON_BAD_NETWORK, 1);
1753         Settings.Global.putLong(resolver,
1754                 Settings.Global.MIN_DURATION_BETWEEN_RECOVERY_STEPS_IN_MS, 100);
1755         Settings.System.putInt(resolver, "radio.data.stall.recovery.action", 2);
1756         doReturn(new SignalStrength()).when(mPhone).getSignalStrength();
1757         doReturn(PhoneConstants.State.IDLE).when(mPhone).getState();
1758 
1759         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1760                 new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
1761         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1762 
1763         sendInitializationEvents();
1764 
1765         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1766         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
1767                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1768                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1769                 any(Message.class));
1770         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
1771 
1772         logd("Sending EVENT_NETWORK_STATUS_CHANGED false");
1773         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NETWORK_STATUS_CHANGED,
1774                 NetworkAgent.INVALID_NETWORK, 1, null));
1775         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1776 
1777         // expected to get preferred network type
1778         verify(mSST, times(1)).reRegisterNetwork(eq(null));
1779     }
1780 
1781     @Test
1782     @SmallTest
testRecoveryStepRestartRadio()1783     public void testRecoveryStepRestartRadio() throws Exception {
1784         ContentResolver resolver = mContext.getContentResolver();
1785         Settings.Global.putInt(resolver, Settings.Global.DATA_STALL_RECOVERY_ON_BAD_NETWORK, 1);
1786         Settings.Global.putLong(resolver,
1787                 Settings.Global.MIN_DURATION_BETWEEN_RECOVERY_STEPS_IN_MS, 100);
1788         Settings.System.putInt(resolver, "radio.data.stall.recovery.action", 3);
1789         doReturn(new SignalStrength()).when(mPhone).getSignalStrength();
1790         doReturn(PhoneConstants.State.IDLE).when(mPhone).getState();
1791 
1792         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1793                 new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
1794         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1795 
1796         sendInitializationEvents();
1797 
1798         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1799         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
1800                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1801                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1802                 any(Message.class));
1803         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
1804 
1805         logd("Sending EVENT_NETWORK_STATUS_CHANGED false");
1806         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NETWORK_STATUS_CHANGED,
1807                 NetworkAgent.INVALID_NETWORK, 1, null));
1808         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1809 
1810         // expected to get preferred network type
1811         verify(mSST, times(1)).powerOffRadioSafely();
1812     }
1813 
verifyDataEnabledChangedMessage(boolean enabled, int reason)1814     private void verifyDataEnabledChangedMessage(boolean enabled, int reason) {
1815         verify(mHandler, times(1)).sendMessageDelayed(any(), anyLong());
1816         Pair<Boolean, Integer> result = (Pair) ((AsyncResult) mMessage.obj).result;
1817         assertEquals(DATA_ENABLED_CHANGED, mMessage.what);
1818         assertEquals(enabled, result.first);
1819         assertEquals(reason, (int) result.second);
1820         clearInvocations(mHandler);
1821     }
1822 
setUpSubscriptionPlans(boolean isNrUnmetered)1823     private void setUpSubscriptionPlans(boolean isNrUnmetered) throws Exception {
1824         List<SubscriptionPlan> plans = new ArrayList<>();
1825         if (isNrUnmetered) {
1826             plans.add(SubscriptionPlan.Builder
1827                     .createRecurring(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"),
1828                             Period.ofMonths(1))
1829                     .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
1830                             SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
1831                     .setNetworkTypes(new int[] {TelephonyManager.NETWORK_TYPE_NR})
1832                     .build());
1833         }
1834         plans.add(SubscriptionPlan.Builder
1835                 .createRecurring(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"),
1836                         Period.ofMonths(1))
1837                 .setDataLimit(1_000_000_000, SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
1838                 .setDataUsage(500_000_000, System.currentTimeMillis())
1839                 .build());
1840         replaceInstance(DcTracker.class, "mSubscriptionPlans", mDct, plans);
1841     }
1842 
resetSubscriptionPlans()1843     private void resetSubscriptionPlans() throws Exception {
1844         replaceInstance(DcTracker.class, "mSubscriptionPlans", mDct, null);
1845     }
1846 
isNetworkTypeUnmetered(int networkType)1847     private boolean isNetworkTypeUnmetered(int networkType) throws Exception {
1848         Method method = DcTracker.class.getDeclaredMethod(
1849                 "isNetworkTypeUnmetered", int.class);
1850         method.setAccessible(true);
1851         return (boolean) method.invoke(mDct, networkType);
1852     }
1853 
setUpDataConnection()1854     private int setUpDataConnection() throws Exception {
1855         Field dc = DcTracker.class.getDeclaredField("mDataConnections");
1856         dc.setAccessible(true);
1857         Field uig = DcTracker.class.getDeclaredField("mUniqueIdGenerator");
1858         uig.setAccessible(true);
1859         int id = ((AtomicInteger) uig.get(mDct)).getAndIncrement();
1860         ((HashMap<Integer, DataConnection>) dc.get(mDct)).put(id, mDataConnection);
1861         return id;
1862     }
1863 
resetDataConnection(int id)1864     private void resetDataConnection(int id) throws Exception {
1865         Field dc = DcTracker.class.getDeclaredField("mDataConnections");
1866         dc.setAccessible(true);
1867         ((HashMap<Integer, DataConnection>) dc.get(mDct)).remove(id);
1868     }
1869 
setUpWatchdogTimer()1870     private void setUpWatchdogTimer() {
1871         // Watchdog active for 10s
1872         mBundle.putLong(CarrierConfigManager.KEY_5G_WATCHDOG_TIME_MS_LONG, 10000);
1873         Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
1874         intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, mPhone.getPhoneId());
1875         intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, mPhone.getSubId());
1876         mContext.sendBroadcast(intent);
1877         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1878     }
1879 
getWatchdogStatus()1880     private boolean getWatchdogStatus() throws Exception {
1881         Field field = DcTracker.class.getDeclaredField(("mWatchdog"));
1882         field.setAccessible(true);
1883         return (boolean) field.get(mDct);
1884     }
1885 
setUpTempNotMetered()1886     private void setUpTempNotMetered() {
1887         doReturn((int) TelephonyManager.NETWORK_TYPE_BITMASK_NR)
1888                 .when(mPhone).getRadioAccessFamily();
1889         doReturn(1).when(mPhone).getSubId();
1890         mBundle.putBoolean(CarrierConfigManager.KEY_NETWORK_TEMP_NOT_METERED_SUPPORTED_BOOL, true);
1891         Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
1892         intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, mPhone.getPhoneId());
1893         intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, mPhone.getSubId());
1894         mContext.sendBroadcast(intent);
1895         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1896     }
1897 
1898     @Test
testIsNetworkTypeUnmetered()1899     public void testIsNetworkTypeUnmetered() throws Exception {
1900         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
1901 
1902         // only 5G unmetered
1903         setUpSubscriptionPlans(true);
1904 
1905         assertTrue(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_NR));
1906         assertFalse(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_LTE));
1907         assertFalse(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_UNKNOWN));
1908 
1909         // all network types metered
1910         setUpSubscriptionPlans(false);
1911 
1912         assertFalse(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_NR));
1913         assertFalse(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_LTE));
1914         assertFalse(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_UNKNOWN));
1915 
1916         // all network types unmetered
1917         List<SubscriptionPlan> plans = new ArrayList<>();
1918         plans.add(SubscriptionPlan.Builder
1919                 .createRecurring(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"),
1920                         Period.ofMonths(1))
1921                 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
1922                         SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
1923                 .build());
1924         replaceInstance(DcTracker.class, "mSubscriptionPlans", mDct, plans);
1925 
1926         assertTrue(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_NR));
1927         assertTrue(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_LTE));
1928         assertTrue(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_UNKNOWN));
1929 
1930         resetSubscriptionPlans();
1931     }
1932 
1933     @Test
testIsNrUnmeteredSubscriptionPlans()1934     public void testIsNrUnmeteredSubscriptionPlans() throws Exception {
1935         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
1936         int id = setUpDataConnection();
1937         setUpSubscriptionPlans(false);
1938         setUpWatchdogTimer();
1939         doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
1940                 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA))
1941                 .when(mDisplayInfoController).getTelephonyDisplayInfo();
1942         setUpTempNotMetered();
1943 
1944         // NetCapability should be metered when connected to 5G with no unmetered plan or frequency
1945         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
1946         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1947         verify(mDataConnection, times(1)).onMeterednessChanged(false);
1948 
1949         // Set SubscriptionPlans unmetered
1950         setUpSubscriptionPlans(true);
1951 
1952         // NetCapability should switch to unmetered with an unmetered plan
1953         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
1954         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1955         verify(mDataConnection, times(1)).onMeterednessChanged(true);
1956 
1957         // Set MMWAVE frequency to unmetered
1958         mBundle.putBoolean(CarrierConfigManager.KEY_UNMETERED_NR_NSA_MMWAVE_BOOL, true);
1959         Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
1960         intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, mPhone.getPhoneId());
1961         intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, mPhone.getSubId());
1962         mContext.sendBroadcast(intent);
1963         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1964 
1965         // NetCapability should switch to metered without fr=MMWAVE
1966         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
1967         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1968         verify(mDataConnection, times(2)).onMeterednessChanged(false);
1969 
1970         // NetCapability should switch to unmetered with fr=MMWAVE
1971         doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
1972                 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA_MMWAVE))
1973                 .when(mDisplayInfoController).getTelephonyDisplayInfo();
1974         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
1975         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1976         verify(mDataConnection, times(2)).onMeterednessChanged(true);
1977 
1978         resetDataConnection(id);
1979         resetSubscriptionPlans();
1980     }
1981 
1982     @Test
testIsNrUnmeteredCarrierConfigs()1983     public void testIsNrUnmeteredCarrierConfigs() throws Exception {
1984         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
1985         int id = setUpDataConnection();
1986         setUpSubscriptionPlans(false);
1987         setUpWatchdogTimer();
1988         doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
1989                 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA))
1990                 .when(mDisplayInfoController).getTelephonyDisplayInfo();
1991         setUpTempNotMetered();
1992 
1993         // NetCapability should be metered when connected to 5G with no unmetered plan or frequency
1994         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
1995         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1996         verify(mDataConnection, times(1)).onMeterednessChanged(false);
1997 
1998         // Set MMWAVE frequency to unmetered
1999         mBundle.putBoolean(CarrierConfigManager.KEY_UNMETERED_NR_NSA_BOOL, true);
2000         mBundle.putBoolean(CarrierConfigManager.KEY_UNMETERED_NR_NSA_MMWAVE_BOOL, true);
2001         Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
2002         intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, mPhone.getPhoneId());
2003         intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, mPhone.getSubId());
2004         mContext.sendBroadcast(intent);
2005         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2006 
2007         // NetCapability should switch to unmetered when fr=MMWAVE and MMWAVE unmetered
2008         doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
2009                 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA_MMWAVE))
2010                 .when(mDisplayInfoController).getTelephonyDisplayInfo();
2011         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
2012         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2013         verify(mDataConnection, times(1)).onMeterednessChanged(true);
2014 
2015         // NetCapability should switch to metered when fr=SUB6 and MMWAVE unmetered
2016         doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
2017                 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA))
2018                 .when(mDisplayInfoController).getTelephonyDisplayInfo();
2019         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
2020         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2021         verify(mDataConnection, times(2)).onMeterednessChanged(false);
2022 
2023         // Set SUB6 frequency to unmetered
2024         doReturn(2).when(mPhone).getSubId();
2025         mBundle.putBoolean(CarrierConfigManager.KEY_UNMETERED_NR_NSA_MMWAVE_BOOL, false);
2026         mBundle.putBoolean(CarrierConfigManager.KEY_UNMETERED_NR_NSA_SUB6_BOOL, true);
2027         intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
2028         intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, mPhone.getPhoneId());
2029         intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, mPhone.getSubId());
2030         mContext.sendBroadcast(intent);
2031         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2032 
2033         // NetCapability should switch to unmetered when fr=SUB6 and SUB6 unmetered
2034         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
2035         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2036         // Data connection is running on a different thread. Have to wait.
2037         waitForMs(200);
2038         verify(mDataConnection, times(2)).onMeterednessChanged(true);
2039 
2040         resetDataConnection(id);
2041         resetSubscriptionPlans();
2042     }
2043 
2044     @Test
testReevaluateUnmeteredConnectionsOnNetworkChange()2045     public void testReevaluateUnmeteredConnectionsOnNetworkChange() throws Exception {
2046         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
2047         int id = setUpDataConnection();
2048         setUpSubscriptionPlans(true);
2049         setUpWatchdogTimer();
2050         setUpTempNotMetered();
2051 
2052         // NetCapability should be unmetered when connected to 5G
2053         doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
2054                 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA))
2055                 .when(mDisplayInfoController).getTelephonyDisplayInfo();
2056         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
2057         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2058         verify(mDataConnection, times(1)).onMeterednessChanged(true);
2059 
2060         // NetCapability should be metered when disconnected from 5G
2061         doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
2062                 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE))
2063                 .when(mDisplayInfoController).getTelephonyDisplayInfo();
2064         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
2065         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2066         // Data connection is running on a different thread. Have to wait.
2067         waitForMs(200);
2068         verify(mDataConnection, times(1)).onMeterednessChanged(false);
2069 
2070         resetDataConnection(id);
2071         resetSubscriptionPlans();
2072     }
2073 
2074     @Test
testReevaluateUnmeteredConnectionsOnWatchdog()2075     public void testReevaluateUnmeteredConnectionsOnWatchdog() throws Exception {
2076         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
2077         int id = setUpDataConnection();
2078         setUpSubscriptionPlans(true);
2079         setUpWatchdogTimer();
2080 
2081         // Watchdog inactive when unmetered and not connected to 5G
2082         doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
2083                 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE))
2084                 .when(mDisplayInfoController).getTelephonyDisplayInfo();
2085         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NR_TIMER_WATCHDOG));
2086         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2087         assertFalse(getWatchdogStatus());
2088 
2089         // Watchdog active when unmetered and connected to 5G
2090         doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
2091                 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA))
2092                 .when(mDisplayInfoController).getTelephonyDisplayInfo();
2093         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
2094         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2095         assertTrue(getWatchdogStatus());
2096 
2097         // Watchdog inactive when metered
2098         setUpSubscriptionPlans(false);
2099         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
2100         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2101         assertFalse(getWatchdogStatus());
2102 
2103         resetDataConnection(id);
2104         resetSubscriptionPlans();
2105     }
2106 
2107     /**
2108      * Test if this is a path prefix match against the given Uri. Verifies that
2109      * scheme, authority, and atomic path segments match.
2110      *
2111      * Copied from frameworks/base/core/java/android/net/Uri.java
2112      */
isPathPrefixMatch(Uri uriA, Uri uriB)2113     private boolean isPathPrefixMatch(Uri uriA, Uri uriB) {
2114         if (!Objects.equals(uriA.getScheme(), uriB.getScheme())) return false;
2115         if (!Objects.equals(uriA.getAuthority(), uriB.getAuthority())) return false;
2116 
2117         List<String> segA = uriA.getPathSegments();
2118         List<String> segB = uriB.getPathSegments();
2119 
2120         final int size = segB.size();
2121         if (segA.size() < size) return false;
2122 
2123         for (int i = 0; i < size; i++) {
2124             if (!Objects.equals(segA.get(i), segB.get(i))) {
2125                 return false;
2126             }
2127         }
2128 
2129         return true;
2130     }
2131 
2132     @Test
testNoApnContextsWhenDataIsDisabled()2133     public void testNoApnContextsWhenDataIsDisabled() throws java.lang.InterruptedException {
2134         //Check that apn contexts are loaded.
2135         assertTrue(mDct.getApnContexts().size() > 0);
2136 
2137         //Do work normally done in teardown.
2138         mDct.removeCallbacksAndMessages(null);
2139         mDcTrackerTestHandler.quit();
2140         mDcTrackerTestHandler.join();
2141 
2142         //Set isDataCapable to false for the new DcTracker being created in DcTrackerTestHandler.
2143         doReturn(false).when(mTelephonyManager).isDataCapable();
2144         mDcTrackerTestHandler = new DcTrackerTestHandler(getClass().getSimpleName());
2145         setReady(false);
2146 
2147         mDcTrackerTestHandler.start();
2148         waitUntilReady();
2149         assertEquals(0, mDct.getApnContexts().size());
2150 
2151         //No need to clean up handler because that work is done in teardown.
2152     }
2153 
2154     @Test
testRatChanged()2155     public void testRatChanged() throws Exception {
2156         mSimulatedCommands.setDataCallResult(true, createSetupDataCallResult());
2157 
2158         DataConnectionReasons dataConnectionReasons = new DataConnectionReasons();
2159         boolean allowed = isDataAllowed(dataConnectionReasons);
2160         assertFalse(dataConnectionReasons.toString(), allowed);
2161 
2162         logd("Sending EVENT_ENABLE_APN");
2163         // APN id 0 is APN_TYPE_DEFAULT
2164         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
2165 
2166         sendInitializationEvents();
2167 
2168         dataConnectionReasons = new DataConnectionReasons();
2169         allowed = isDataAllowed(dataConnectionReasons);
2170         assertTrue(dataConnectionReasons.toString(), allowed);
2171 
2172         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
2173         // Verify if RIL command was sent properly.
2174         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
2175                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
2176                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
2177                 any(Message.class));
2178         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
2179 
2180         verifyDataConnected(FAKE_APN1);
2181 
2182         doReturn(ServiceState.RIL_RADIO_TECHNOLOGY_UMTS).when(mServiceState)
2183                 .getRilDataRadioTechnology();
2184 
2185         logd("Sending EVENT_DATA_RAT_CHANGED");
2186         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
2187                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_UMTS)
2188                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
2189                 .build();
2190         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
2191                 anyInt(), anyInt());
2192         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_RAT_CHANGED, null));
2193         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2194 
2195         // Data connection is running on a different thread. Have to wait.
2196         waitForMs(200);
2197         // expected tear down all metered DataConnections
2198         verify(mSimulatedCommandsVerifier).deactivateDataCall(
2199                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
2200                 any(Message.class));
2201     }
2202 
2203     @Test
testApnConfigRepositoryUpdatedOnCarrierConfigChange()2204     public void testApnConfigRepositoryUpdatedOnCarrierConfigChange() throws Exception {
2205         assertPriority(ApnSetting.TYPE_CBS_STRING, 2);
2206         assertPriority(ApnSetting.TYPE_MMS_STRING, 2);
2207 
2208         mBundle.putStringArray(CarrierConfigManager.KEY_APN_PRIORITY_STRING_ARRAY,
2209                 new String[] {
2210                         ApnSetting.TYPE_CBS_STRING + ":11",
2211                         ApnSetting.TYPE_MMS_STRING + ":19",
2212                 });
2213 
2214         sendInitializationEvents();
2215 
2216         Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
2217         intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, mPhone.getPhoneId());
2218         intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, mPhone.getSubId());
2219         mContext.sendBroadcast(intent);
2220         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2221 
2222         assertPriority(ApnSetting.TYPE_CBS_STRING, 11);
2223         assertPriority(ApnSetting.TYPE_MMS_STRING, 19);
2224 
2225         //Ensure apns are in sorted order.
2226         ApnContext lastApnContext = null;
2227         for (ApnContext apnContext : mDct.getApnContexts()) {
2228             if (lastApnContext != null) {
2229                 assertTrue(apnContext.getPriority() <= lastApnContext.getPriority());
2230             }
2231             lastApnContext = apnContext;
2232         }
2233     }
2234 
assertPriority(String type, int priority)2235     private void assertPriority(String type, int priority) {
2236         assertEquals(priority, mDct.getApnContexts().stream()
2237                 .filter(x -> x.getApnType().equals(type))
2238                 .findFirst().get().getPriority());
2239     }
2240 
2241     @Test
testProvisionBroadcastReceiver()2242     public void testProvisionBroadcastReceiver() {
2243         Intent intent = new Intent("com.android.internal.telephony.PROVISION");
2244         intent.putExtra("provision.phone.id", mPhone.getPhoneId());
2245         try {
2246             mContext.sendBroadcast(intent);
2247         } catch (SecurityException e) {
2248             fail();
2249         }
2250         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2251     }
2252 }
2253