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.assertTrue;
26 import static org.junit.Assert.fail;
27 import static org.mockito.Matchers.any;
28 import static org.mockito.Matchers.anyInt;
29 import static org.mockito.Matchers.anyLong;
30 import static org.mockito.Matchers.anyString;
31 import static org.mockito.Matchers.eq;
32 import static org.mockito.Mockito.atLeastOnce;
33 import static org.mockito.Mockito.clearInvocations;
34 import static org.mockito.Mockito.doAnswer;
35 import static org.mockito.Mockito.doReturn;
36 import static org.mockito.Mockito.timeout;
37 import static org.mockito.Mockito.times;
38 import static org.mockito.Mockito.verify;
39 
40 import android.app.AlarmManager;
41 import android.app.PendingIntent;
42 import android.content.ContentResolver;
43 import android.content.ContentValues;
44 import android.content.Context;
45 import android.content.Intent;
46 import android.content.IntentFilter;
47 import android.content.pm.ServiceInfo;
48 import android.database.Cursor;
49 import android.database.MatrixCursor;
50 import android.hardware.radio.V1_0.SetupDataCallResult;
51 import android.net.LinkProperties;
52 import android.net.NetworkAgent;
53 import android.net.NetworkCapabilities;
54 import android.net.NetworkRequest;
55 import android.net.Uri;
56 import android.os.AsyncResult;
57 import android.os.Handler;
58 import android.os.HandlerThread;
59 import android.os.IBinder;
60 import android.os.Message;
61 import android.os.PersistableBundle;
62 import android.provider.Settings;
63 import android.provider.Telephony;
64 import android.telephony.AccessNetworkConstants;
65 import android.telephony.AccessNetworkConstants.AccessNetworkType;
66 import android.telephony.CarrierConfigManager;
67 import android.telephony.NetworkRegistrationInfo;
68 import android.telephony.ServiceState;
69 import android.telephony.SubscriptionInfo;
70 import android.telephony.SubscriptionManager;
71 import android.telephony.TelephonyManager;
72 import android.telephony.data.ApnSetting;
73 import android.telephony.data.DataProfile;
74 import android.telephony.data.DataService;
75 import android.test.mock.MockContentProvider;
76 import android.test.mock.MockContentResolver;
77 import android.test.suitebuilder.annotation.MediumTest;
78 import android.test.suitebuilder.annotation.SmallTest;
79 import android.text.TextUtils;
80 import android.util.Pair;
81 
82 import androidx.test.filters.FlakyTest;
83 
84 import com.android.internal.R;
85 import com.android.internal.telephony.DctConstants;
86 import com.android.internal.telephony.ISub;
87 import com.android.internal.telephony.PhoneConstants;
88 import com.android.internal.telephony.TelephonyTest;
89 import com.android.server.pm.PackageManagerService;
90 
91 import org.junit.After;
92 import org.junit.Before;
93 import org.junit.Ignore;
94 import org.junit.Test;
95 import org.mockito.ArgumentCaptor;
96 import org.mockito.Mock;
97 import org.mockito.invocation.InvocationOnMock;
98 import org.mockito.stubbing.Answer;
99 
100 import java.lang.reflect.Method;
101 import java.util.ArrayList;
102 import java.util.Arrays;
103 
104 public class DcTrackerTest extends TelephonyTest {
105 
106     private final static String[] sNetworkAttributes = new String[]{
107             "mobile,0,0,0,-1,true", "mobile_mms,2,0,2,60000,true",
108             "mobile_supl,3,0,2,60000,true", "mobile_dun,4,0,2,60000,true",
109             "mobile_hipri,5,0,3,60000,true", "mobile_fota,10,0,2,60000,true",
110             "mobile_ims,11,0,2,60000,true", "mobile_cbs,12,0,2,60000,true",
111             "mobile_ia,14,0,2,-1,true", "mobile_emergency,15,0,2,-1,true"};
112 
113     public static final String FAKE_APN1 = "FAKE APN 1";
114     public static final String FAKE_APN2 = "FAKE APN 2";
115     public static final String FAKE_APN3 = "FAKE APN 3";
116     public static final String FAKE_APN4 = "FAKE APN 4";
117     public static final String FAKE_APN5 = "FAKE APN 5";
118     public static final String FAKE_APN6 = "FAKE APN 6";
119     public static final String FAKE_IFNAME = "FAKE IFNAME";
120     public static final String FAKE_PCSCF_ADDRESS = "22.33.44.55";
121     public static final String FAKE_GATEWAY = "11.22.33.44";
122     public static final String FAKE_DNS = "55.66.77.88";
123     public static final String FAKE_ADDRESS = "99.88.77.66";
124     private static final int NETWORK_TYPE_LTE_BITMASK =
125             1 << (TelephonyManager.NETWORK_TYPE_LTE - 1);
126     private static final int NETWORK_TYPE_EHRPD_BITMASK =
127             1 << (TelephonyManager.NETWORK_TYPE_EHRPD - 1);
128     private static final Uri PREFERAPN_URI = Uri.parse(
129             Telephony.Carriers.CONTENT_URI + "/preferapn");
130     private static final int DATA_ENABLED_CHANGED = 0;
131     private static final String FAKE_PLMN = "44010";
132     private static final long TEST_TIMEOUT = 1000;
133 
134     @Mock
135     ISub mIsub;
136     @Mock
137     IBinder mBinder;
138     @Mock
139     SubscriptionInfo mSubscriptionInfo;
140     @Mock
141     ApnContext mApnContext;
142     @Mock
143     DataConnection mDataConnection;
144     @Mock
145     PackageManagerService mMockPackageManagerInternal;
146     @Mock
147     Handler mHandler;
148 
149     private DcTracker mDct;
150     private DcTrackerTestHandler mDcTrackerTestHandler;
151 
152     private AlarmManager mAlarmManager;
153 
154     private PersistableBundle mBundle;
155 
156     private SubscriptionManager.OnSubscriptionsChangedListener mOnSubscriptionsChangedListener;
157 
158     private final ApnSettingContentProvider mApnSettingContentProvider =
159             new ApnSettingContentProvider();
160 
161     private Message mMessage;
162 
addDataService()163     private void addDataService() {
164         CellularDataService cellularDataService = new CellularDataService();
165         ServiceInfo serviceInfo = new ServiceInfo();
166         serviceInfo.packageName = "com.android.phone";
167         serviceInfo.permission = "android.permission.BIND_TELEPHONY_DATA_SERVICE";
168         IntentFilter filter = new IntentFilter();
169         mContextFixture.addService(
170                 DataService.SERVICE_INTERFACE,
171                 null,
172                 "com.android.phone",
173                 cellularDataService.mBinder,
174                 serviceInfo,
175                 filter);
176     }
177 
178     private class DcTrackerTestHandler extends HandlerThread {
179 
DcTrackerTestHandler(String name)180         private DcTrackerTestHandler(String name) {
181             super(name);
182         }
183 
184         @Override
onLooperPrepared()185         public void onLooperPrepared() {
186             mDct = new DcTracker(mPhone, AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
187             setReady(true);
188         }
189     }
190 
191     private class ApnSettingContentProvider extends MockContentProvider {
192         private int mPreferredApnSet = 0;
193 
194         @Override
query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)195         public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
196                             String sortOrder) {
197             logd("ApnSettingContentProvider: query");
198             logd("   uri = " + uri);
199             logd("   projection = " + Arrays.toString(projection));
200             logd("   selection = " + selection);
201             logd("   selectionArgs = " + Arrays.toString(selectionArgs));
202             logd("   sortOrder = " + sortOrder);
203 
204             if (uri.compareTo(Telephony.Carriers.CONTENT_URI) == 0
205                     || uri.toString().startsWith(Uri.withAppendedPath(
206                             Telephony.Carriers.CONTENT_URI, "filtered").toString())
207                     || uri.toString().startsWith(Uri.withAppendedPath(
208                             Telephony.Carriers.SIM_APN_URI, "filtered").toString())) {
209                 if (projection == null) {
210 
211                     logd("Query '" + FAKE_PLMN + "' APN settings");
212                     MatrixCursor mc = new MatrixCursor(
213                             new String[]{Telephony.Carriers._ID, Telephony.Carriers.NUMERIC,
214                                     Telephony.Carriers.NAME, Telephony.Carriers.APN,
215                                     Telephony.Carriers.PROXY, Telephony.Carriers.PORT,
216                                     Telephony.Carriers.MMSC, Telephony.Carriers.MMSPROXY,
217                                     Telephony.Carriers.MMSPORT, Telephony.Carriers.USER,
218                                     Telephony.Carriers.PASSWORD, Telephony.Carriers.AUTH_TYPE,
219                                     Telephony.Carriers.TYPE,
220                                     Telephony.Carriers.PROTOCOL,
221                                     Telephony.Carriers.ROAMING_PROTOCOL,
222                                     Telephony.Carriers.CARRIER_ENABLED, Telephony.Carriers.BEARER,
223                                     Telephony.Carriers.BEARER_BITMASK,
224                                     Telephony.Carriers.PROFILE_ID,
225                                     Telephony.Carriers.MODEM_PERSIST,
226                                     Telephony.Carriers.MAX_CONNECTIONS,
227                                     Telephony.Carriers.WAIT_TIME_RETRY,
228                                     Telephony.Carriers.TIME_LIMIT_FOR_MAX_CONNECTIONS,
229                                     Telephony.Carriers.MTU,
230                                     Telephony.Carriers.MVNO_TYPE,
231                                     Telephony.Carriers.MVNO_MATCH_DATA,
232                                     Telephony.Carriers.NETWORK_TYPE_BITMASK,
233                                     Telephony.Carriers.APN_SET_ID,
234                                     Telephony.Carriers.CARRIER_ID,
235                                     Telephony.Carriers.SKIP_464XLAT});
236 
237                     mc.addRow(new Object[]{
238                             2163,                   // id
239                             FAKE_PLMN,              // numeric
240                             "sp-mode",              // name
241                             FAKE_APN1,              // apn
242                             "",                     // proxy
243                             "",                     // port
244                             "",                     // mmsc
245                             "",                     // mmsproxy
246                             "",                     // mmsport
247                             "",                     // user
248                             "",                     // password
249                             -1,                     // authtype
250                             "default,supl",         // types
251                             "IP",                   // protocol
252                             "IP",                   // roaming_protocol
253                             1,                      // carrier_enabled
254                             ServiceState.RIL_RADIO_TECHNOLOGY_LTE, // bearer
255                             0,                      // bearer_bitmask
256                             0,                      // profile_id
257                             1,                      // modem_cognitive
258                             0,                      // max_conns
259                             0,                      // wait_time
260                             0,                      // max_conns_time
261                             0,                      // mtu
262                             "",                     // mvno_type
263                             "",                     // mnvo_match_data
264                             NETWORK_TYPE_LTE_BITMASK, // network_type_bitmask
265                             0,                      // apn_set_id
266                             -1,                     // carrier_id
267                             -1                      // skip_464xlat
268                     });
269 
270                     mc.addRow(new Object[]{
271                             2164,                   // id
272                             FAKE_PLMN,              // numeric
273                             "mopera U",             // name
274                             FAKE_APN2,              // apn
275                             "",                     // proxy
276                             "",                     // port
277                             "",                     // mmsc
278                             "",                     // mmsproxy
279                             "",                     // mmsport
280                             "",                     // user
281                             "",                     // password
282                             -1,                     // authtype
283                             "default,supl",         // types
284                             "IP",                   // protocol
285                             "IP",                   // roaming_protocol
286                             1,                      // carrier_enabled
287                             ServiceState.RIL_RADIO_TECHNOLOGY_LTE, // bearer,
288                             0,                      // bearer_bitmask
289                             0,                      // profile_id
290                             1,                      // modem_cognitive
291                             0,                      // max_conns
292                             0,                      // wait_time
293                             0,                      // max_conns_time
294                             0,                      // mtu
295                             "",                     // mvno_type
296                             "",                     // mnvo_match_data
297                             NETWORK_TYPE_LTE_BITMASK, // network_type_bitmask
298                             0,                      // apn_set_id
299                             -1,                     // carrier_id
300                             -1                      // skip_464xlat
301                     });
302 
303                     mc.addRow(new Object[]{
304                             2165,                   // id
305                             FAKE_PLMN,              // numeric
306                             "b-mobile for Nexus",   // name
307                             FAKE_APN3,              // apn
308                             "",                     // proxy
309                             "",                     // port
310                             "",                     // mmsc
311                             "",                     // mmsproxy
312                             "",                     // mmsport
313                             "",                     // user
314                             "",                     // password
315                             -1,                     // authtype
316                             "ims",                  // types
317                             "IP",                   // protocol
318                             "IP",                   // roaming_protocol
319                             1,                      // carrier_enabled
320                             0,                      // bearer
321                             0,                      // bearer_bitmask
322                             0,                      // profile_id
323                             1,                      // modem_cognitive
324                             0,                      // max_conns
325                             0,                      // wait_time
326                             0,                      // max_conns_time
327                             0,                      // mtu
328                             "",                     // mvno_type
329                             "",                     // mnvo_match_data
330                             0,                      // network_type_bitmask
331                             0,                      // apn_set_id
332                             -1,                     // carrier_id
333                             -1                      // skip_464xlat
334                     });
335 
336                     mc.addRow(new Object[]{
337                             2166,                   // id
338                             FAKE_PLMN,              // numeric
339                             "sp-mode ehrpd",        // name
340                             FAKE_APN4,              // apn
341                             "",                     // proxy
342                             "",                     // port
343                             "",                     // mmsc
344                             "",                     // mmsproxy
345                             "",                     // mmsport
346                             "",                     // user
347                             "",                     // password
348                             -1,                     // authtype
349                             "default,supl",         // types
350                             "IP",                   // protocol
351                             "IP",                   // roaming_protocol
352                             1,                      // carrier_enabled
353                             ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD, // bearer
354                             0,                      // bearer_bitmask
355                             0,                      // profile_id
356                             1,                      // modem_cognitive
357                             0,                      // max_conns
358                             0,                      // wait_time
359                             0,                      // max_conns_time
360                             0,                      // mtu
361                             "",                     // mvno_type
362                             "",                     // mnvo_match_data
363                             NETWORK_TYPE_EHRPD_BITMASK, // network_type_bitmask
364                             0,                      // apn_set_id
365                             -1,                     // carrier_id
366                             -1                      // skip_464xlat
367                     });
368 
369                     mc.addRow(new Object[]{
370                             2167,                   // id
371                             FAKE_PLMN,              // numeric
372                             "b-mobile for Nexus",   // name
373                             FAKE_APN5,              // apn
374                             "",                     // proxy
375                             "",                     // port
376                             "",                     // mmsc
377                             "",                     // mmsproxy
378                             "",                     // mmsport
379                             "",                     // user
380                             "",                     // password
381                             -1,                     // authtype
382                             "dun",                  // types
383                             "IP",                   // protocol
384                             "IP",                   // roaming_protocol
385                             1,                      // carrier_enabled
386                             0,                      // bearer
387                             0,                      // bearer_bitmask
388                             0,                      // profile_id
389                             1,                      // modem_cognitive
390                             0,                      // max_conns
391                             0,                      // wait_time
392                             0,                      // max_conns_time
393                             0,                      // mtu
394                             "",                     // mvno_type
395                             "",                     // mnvo_match_data
396                             0,                      // network_type_bitmask
397                             0,                      // apn_set_id
398                             -1,                     // carrier_id
399                             -1                      // skip_464xlat
400                     });
401 
402                     mc.addRow(new Object[]{
403                             2168,                   // id
404                             FAKE_PLMN,              // numeric
405                             "sp-mode",              // name
406                             FAKE_APN6,              // apn
407                             "",                     // proxy
408                             "",                     // port
409                             "",                     // mmsc
410                             "",                     // mmsproxy
411                             "",                     // mmsport
412                             "",                     // user
413                             "",                     // password
414                             -1,                     // authtype
415                             "mms",                  // types
416                             "IP",                   // protocol
417                             "IP",                   // roaming_protocol
418                             1,                      // carrier_enabled
419                             ServiceState.RIL_RADIO_TECHNOLOGY_LTE, // bearer
420                             0,                      // bearer_bitmask
421                             0,                      // profile_id
422                             1,                      // modem_cognitive
423                             0,                      // max_conns
424                             0,                      // wait_time
425                             0,                      // max_conns_time
426                             0,                      // mtu
427                             "",                     // mvno_type
428                             "",                     // mnvo_match_data
429                             NETWORK_TYPE_LTE_BITMASK, // network_type_bitmask
430                             0,                      // apn_set_id
431                             -1,                     // carrier_id
432                             -1                      // skip_464xlat
433                     });
434 
435                     return mc;
436                 }
437             } else if (uri.isPathPrefixMatch(
438                     Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "preferapnset"))) {
439                 MatrixCursor mc = new MatrixCursor(
440                         new String[]{Telephony.Carriers.APN_SET_ID});
441                 // apn_set_id is the only field used with this URL
442                 mc.addRow(new Object[]{ mPreferredApnSet });
443                 mc.addRow(new Object[]{ 0 });
444                 return mc;
445             }
446 
447             return null;
448         }
449 
450         @Override
update(Uri url, ContentValues values, String where, String[] whereArgs)451         public int update(Uri url, ContentValues values, String where, String[] whereArgs) {
452             mPreferredApnSet = values.getAsInteger(Telephony.Carriers.APN_SET_ID);
453             return 1;
454         }
455     }
456 
457     @Before
setUp()458     public void setUp() throws Exception {
459         logd("DcTrackerTest +Setup!");
460         super.setUp(getClass().getSimpleName());
461 
462         doReturn("fake.action_detached").when(mPhone).getActionDetached();
463         doReturn("fake.action_attached").when(mPhone).getActionAttached();
464         doReturn(ServiceState.RIL_RADIO_TECHNOLOGY_LTE).when(mServiceState)
465                 .getRilDataRadioTechnology();
466 
467         mContextFixture.putStringArrayResource(com.android.internal.R.array.networkAttributes,
468                 sNetworkAttributes);
469         mContextFixture.putStringArrayResource(com.android.internal.R.array.
470                 config_mobile_tcp_buffers, new String[]{
471                 "umts:131072,262144,1452032,4096,16384,399360",
472                 "hspa:131072,262144,2441216,4096,16384,399360",
473                 "hsupa:131072,262144,2441216,4096,16384,399360",
474                 "hsdpa:131072,262144,2441216,4096,16384,399360",
475                 "hspap:131072,262144,2441216,4096,16384,399360",
476                 "edge:16384,32768,131072,4096,16384,65536",
477                 "gprs:4096,8192,24576,4096,8192,24576",
478                 "1xrtt:16384,32768,131070,4096,16384,102400",
479                 "evdo:131072,262144,1048576,4096,16384,524288",
480                 "lte:524288,1048576,8388608,262144,524288,4194304"});
481 
482         mContextFixture.putResource(R.string.config_wwan_data_service_package,
483                 "com.android.phone");
484 
485         ((MockContentResolver) mContext.getContentResolver()).addProvider(
486                 Telephony.Carriers.CONTENT_URI.getAuthority(), mApnSettingContentProvider);
487         Settings.Global.putInt(mContext.getContentResolver(),
488                 Settings.Global.DATA_STALL_RECOVERY_ON_BAD_NETWORK, 0);
489 
490         doReturn(true).when(mSimRecords).getRecordsLoaded();
491         doReturn(PhoneConstants.State.IDLE).when(mCT).getState();
492         doReturn(true).when(mSST).getDesiredPowerState();
493         doReturn(true).when(mSST).getPowerStateFromCarrier();
494         doAnswer(
495                 new Answer<Void>() {
496                     @Override
497                     public Void answer(InvocationOnMock invocation) throws Throwable {
498                         mOnSubscriptionsChangedListener =
499                                 (SubscriptionManager.OnSubscriptionsChangedListener)
500                                         invocation.getArguments()[0];
501                         return null;
502                     }
503                 }
504         ).when(mSubscriptionManager).addOnSubscriptionsChangedListener(any());
505         doReturn(mSubscriptionInfo).when(mSubscriptionManager).getActiveSubscriptionInfo(anyInt());
506 
507         doReturn(1).when(mIsub).getDefaultDataSubId();
508         doReturn(mIsub).when(mBinder).queryLocalInterface(anyString());
509         mServiceManagerMockedServices.put("isub", mBinder);
510         mServiceManagerMockedServices.put("package", mMockPackageManagerInternal);
511 
512         mContextFixture.putStringArrayResource(
513                 com.android.internal.R.array.config_cell_retries_per_error_code,
514                 new String[]{"36,2"});
515 
516         mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
517         mBundle = mContextFixture.getCarrierConfigBundle();
518 
519         mSimulatedCommands.setDataCallResult(true, createSetupDataCallResult());
520         addDataService();
521 
522         mDcTrackerTestHandler = new DcTrackerTestHandler(getClass().getSimpleName());
523         mDcTrackerTestHandler.start();
524         waitUntilReady();
525 
526         Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
527         intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, 0);
528         mContext.sendBroadcast(intent);
529 
530         waitForMs(600);
531         logd("DcTrackerTest -Setup!");
532     }
533 
534     @After
tearDown()535     public void tearDown() throws Exception {
536         logd("DcTrackerTest -tearDown");
537         mDct.removeCallbacksAndMessages(null);
538         mDct = null;
539         mDcTrackerTestHandler.quit();
540         super.tearDown();
541     }
542 
543     // Create a successful data response
createSetupDataCallResult()544     private static SetupDataCallResult createSetupDataCallResult() throws Exception {
545         SetupDataCallResult result = new SetupDataCallResult();
546         result.status = 0;
547         result.suggestedRetryTime = -1;
548         result.cid = 1;
549         result.active = 2;
550         result.type = "IP";
551         result.ifname = FAKE_IFNAME;
552         result.addresses = FAKE_ADDRESS;
553         result.dnses = FAKE_DNS;
554         result.gateways = FAKE_GATEWAY;
555         result.pcscf = FAKE_PCSCF_ADDRESS;
556         result.mtu = 1440;
557         return result;
558     }
559 
verifyDataProfile(DataProfile dp, String apn, int profileId, int supportedApnTypesBitmap, int type, int bearerBitmask)560     private void verifyDataProfile(DataProfile dp, String apn, int profileId,
561                                    int supportedApnTypesBitmap, int type, int bearerBitmask) {
562         assertEquals(profileId, dp.getProfileId());
563         assertEquals(apn, dp.getApn());
564         assertEquals(ApnSetting.PROTOCOL_IP, dp.getProtocolType());
565         assertEquals(0, dp.getAuthType());
566         assertEquals("", dp.getUserName());
567         assertEquals("", dp.getPassword());
568         assertEquals(type, dp.getType());
569         assertEquals(0, dp.getWaitTime());
570         assertTrue(dp.isEnabled());
571         assertEquals(supportedApnTypesBitmap, dp.getSupportedApnTypesBitmask());
572         assertEquals(ApnSetting.PROTOCOL_IP, dp.getRoamingProtocolType());
573         assertEquals(bearerBitmask, dp.getBearerBitmask());
574         assertEquals(0, dp.getMtu());
575         assertTrue(dp.isPersistent());
576         assertFalse(dp.isPreferred());
577     }
578 
verifyDataConnected(final String apnSetting)579     private void verifyDataConnected(final String apnSetting) {
580         verify(mPhone, atLeastOnce()).notifyDataConnection(
581                 eq(PhoneConstants.APN_TYPE_DEFAULT));
582 
583         verify(mAlarmManager, times(1)).set(eq(AlarmManager.ELAPSED_REALTIME), anyLong(),
584                 any(PendingIntent.class));
585 
586         assertEquals(apnSetting, mDct.getActiveApnString(PhoneConstants.APN_TYPE_DEFAULT));
587         assertArrayEquals(new String[]{PhoneConstants.APN_TYPE_DEFAULT}, mDct.getActiveApnTypes());
588 
589         assertEquals(DctConstants.State.CONNECTED, mDct.getOverallState());
590         assertEquals(DctConstants.State.CONNECTED, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
591 
592         LinkProperties linkProperties = mDct.getLinkProperties(PhoneConstants.APN_TYPE_DEFAULT);
593         assertEquals(FAKE_IFNAME, linkProperties.getInterfaceName());
594         assertEquals(1, linkProperties.getAddresses().size());
595         assertEquals(FAKE_ADDRESS, linkProperties.getAddresses().get(0).getHostAddress());
596         assertEquals(1, linkProperties.getDnsServers().size());
597         assertEquals(FAKE_DNS, linkProperties.getDnsServers().get(0).getHostAddress());
598         assertEquals(FAKE_GATEWAY, linkProperties.getRoutes().get(0).getGateway().getHostAddress());
599     }
600 
isDataAllowed(DataConnectionReasons dataConnectionReasons)601     private boolean isDataAllowed(DataConnectionReasons dataConnectionReasons) {
602         try {
603             Method method = DcTracker.class.getDeclaredMethod("isDataAllowed",
604                     DataConnectionReasons.class);
605             method.setAccessible(true);
606             return (boolean) method.invoke(mDct, dataConnectionReasons);
607         } catch (Exception e) {
608             fail(e.toString());
609             return false;
610         }
611     }
612 
613     // Test the normal data call setup scenario.
614     @Test
615     @MediumTest
testDataSetup()616     public void testDataSetup() throws Exception {
617         mSimulatedCommands.setDataCallResult(true, createSetupDataCallResult());
618 
619         DataConnectionReasons dataConnectionReasons = new DataConnectionReasons();
620         boolean allowed = isDataAllowed(dataConnectionReasons);
621         assertFalse(dataConnectionReasons.toString(), allowed);
622 
623         logd("Sending EVENT_RECORDS_LOADED");
624         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
625         waitForMs(200);
626 
627         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
628         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
629         waitForMs(200);
630 
631         logd("Sending EVENT_ENABLE_APN");
632         // APN id 0 is APN_TYPE_DEFAULT
633         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
634         waitForMs(200);
635 
636         dataConnectionReasons = new DataConnectionReasons();
637         allowed = isDataAllowed(dataConnectionReasons);
638         assertTrue(dataConnectionReasons.toString(), allowed);
639 
640         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
641         // Verify if RIL command was sent properly.
642         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
643                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
644                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
645                 any(Message.class));
646         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
647 
648         verifyDataConnected(FAKE_APN1);
649     }
650 
651     // Test the scenario where the first data call setup is failed, and then retry the setup later.
652     @Test
653     @MediumTest
testDataRetry()654     public void testDataRetry() throws Exception {
655         AsyncResult ar = new AsyncResult(null,
656                 new Pair<>(true, DataEnabledSettings.REASON_USER_DATA_ENABLED), null);
657         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_ENABLED_CHANGED, ar));
658         waitForMs(200);
659 
660         // LOST_CONNECTION(0x10004) is a non-permanent failure, so we'll retry data setup later.
661         SetupDataCallResult result = createSetupDataCallResult();
662         result.status = 0x10004;
663 
664         // Simulate RIL fails the data call setup
665         mSimulatedCommands.setDataCallResult(true, result);
666 
667         DataConnectionReasons dataConnectionReasons = new DataConnectionReasons();
668         boolean allowed = isDataAllowed(dataConnectionReasons);
669         assertFalse(dataConnectionReasons.toString(), allowed);
670 
671         logd("Sending EVENT_RECORDS_LOADED");
672         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
673         waitForMs(200);
674 
675         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
676         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
677         waitForMs(200);
678 
679         logd("Sending EVENT_ENABLE_APN");
680         // APN id 0 is APN_TYPE_DEFAULT
681         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
682         waitForMs(200);
683 
684         dataConnectionReasons = new DataConnectionReasons();
685         allowed = isDataAllowed(dataConnectionReasons);
686         assertTrue(dataConnectionReasons.toString(), allowed);
687 
688         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
689         // Verify if RIL command was sent properly.
690         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
691                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
692                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
693                 any(Message.class));
694         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
695 
696         // Verify the retry manger schedule another data call setup.
697         verify(mAlarmManager, times(1)).setExact(eq(AlarmManager.ELAPSED_REALTIME_WAKEUP),
698                 anyLong(), any(PendingIntent.class));
699 
700         // This time we'll let RIL command succeed.
701         mSimulatedCommands.setDataCallResult(true, createSetupDataCallResult());
702 
703         // Simulate the timer expires.
704         Intent intent = new Intent("com.android.internal.telephony.data-reconnect.default");
705         intent.putExtra("reconnect_alarm_extra_type", PhoneConstants.APN_TYPE_DEFAULT);
706         intent.putExtra("reconnect_alarm_extra_transport_type",
707                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
708         intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, 0);
709         intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
710         mContext.sendBroadcast(intent);
711         waitForMs(200);
712 
713         dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
714         // Verify if RIL command was sent properly.
715         verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
716                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
717                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
718                 any(Message.class));
719         verifyDataProfile(dpCaptor.getValue(), FAKE_APN2, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
720 
721         // Verify connected with APN2 setting.
722         verifyDataConnected(FAKE_APN2);
723     }
724 
725     @Test
726     @MediumTest
727     @Ignore
728     @FlakyTest
testUserDisableData()729     public void testUserDisableData() throws Exception {
730         //step 1: setup two DataCalls one for Metered: default, another one for Non-metered: IMS
731         //set Default and MMS to be metered in the CarrierConfigManager
732         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
733                 new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
734         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
735         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
736 
737         logd("Sending EVENT_RECORDS_LOADED");
738         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
739         waitForMs(200);
740 
741         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
742         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
743         waitForMs(200);
744 
745         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
746         verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
747                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
748                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
749                 any(Message.class));
750         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 5, 1, NETWORK_TYPE_LTE_BITMASK);
751 
752         logd("Sending DATA_DISABLED_CMD");
753         doReturn(false).when(mDataEnabledSettings).isDataEnabled();
754         doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
755         AsyncResult ar = new AsyncResult(null,
756                 new Pair<>(false, DataEnabledSettings.REASON_USER_DATA_ENABLED), null);
757         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_ENABLED_CHANGED, ar));
758         waitForMs(200);
759 
760         // expected tear down all metered DataConnections
761         verify(mSimulatedCommandsVerifier, times(1)).deactivateDataCall(
762                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
763                 any(Message.class));
764         assertEquals(DctConstants.State.CONNECTED, mDct.getOverallState());
765         assertEquals(DctConstants.State.IDLE, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
766         assertEquals(DctConstants.State.CONNECTED, mDct.getState(PhoneConstants.APN_TYPE_IMS));
767     }
768 
769 
770     @Test
771     @MediumTest
testTrySetupDataMmsAllowedDataDisabled()772     public void testTrySetupDataMmsAllowedDataDisabled() throws Exception {
773         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
774                 new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
775         mDct.enableApn(ApnSetting.TYPE_MMS, DcTracker.REQUEST_TYPE_NORMAL, null);
776         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
777 
778         logd("Sending EVENT_RECORDS_LOADED");
779         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
780         waitForMs(200);
781 
782         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
783         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
784         waitForMs(500);
785 
786         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
787         verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
788                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
789                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
790                 any(Message.class));
791         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
792 
793         logd("Sending DATA_DISABLED_CMD for default data");
794         doReturn(false).when(mDataEnabledSettings).isDataEnabled();
795         doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
796         mDct.obtainMessage(DctConstants.EVENT_DATA_ENABLED_OVERRIDE_RULES_CHANGED).sendToTarget();
797         waitForMs(200);
798 
799         // expected tear down all metered DataConnections
800         verify(mSimulatedCommandsVerifier, times(2)).deactivateDataCall(
801                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
802                 any(Message.class));
803         assertEquals(DctConstants.State.IDLE, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
804         assertEquals(DctConstants.State.IDLE, mDct.getState(PhoneConstants.APN_TYPE_MMS));
805 
806         clearInvocations(mSimulatedCommandsVerifier);
807         doReturn(true).when(mDataEnabledSettings).isDataEnabled(ApnSetting.TYPE_MMS);
808         mDct.obtainMessage(DctConstants.EVENT_DATA_ENABLED_OVERRIDE_RULES_CHANGED).sendToTarget();
809         waitForMs(200);
810 
811         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
812                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
813                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
814                 any(Message.class));
815         assertEquals(DctConstants.State.IDLE, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
816         assertEquals(DctConstants.State.CONNECTED, mDct.getState(PhoneConstants.APN_TYPE_MMS));
817     }
818 
819     @Test
820     @MediumTest
testUserDisableRoaming()821     public void testUserDisableRoaming() throws Exception {
822         //step 1: setup two DataCalls one for Metered: default, another one for Non-metered: IMS
823         //step 2: set roaming disabled, data is enabled
824         //step 3: under roaming service
825         //step 4: only tear down metered data connections.
826 
827         //set Default and MMS to be metered in the CarrierConfigManager
828         boolean roamingEnabled = mDct.getDataRoamingEnabled();
829 
830         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_ROAMING_APN_TYPES_STRINGS,
831                 new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
832 
833         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
834         waitForHandlerAction(mDct, 1000);
835         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
836         waitForHandlerAction(mDct, 1000);
837 
838         logd("Sending EVENT_RECORDS_LOADED");
839         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
840         waitForHandlerAction(mDct, 1000);
841 
842         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
843         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
844         waitForHandlerAction(mDct, 1000);
845         logd("Handling EVENT_DATA_CONNECTION_ATTACHED complete");
846         // dataconnection is on a different handler
847         waitForMs(200);
848 
849         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
850         verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
851                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
852                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
853                 any(Message.class));
854         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
855 
856         //user is in roaming
857         doReturn(true).when(mServiceState).getDataRoaming();
858         logd("Sending DISABLE_ROAMING_CMD");
859         mDct.setDataRoamingEnabledByUser(false);
860         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_ROAMING_ON));
861         waitForMs(200);
862 
863         // expected tear down all metered DataConnections
864         verify(mSimulatedCommandsVerifier, times(1)).deactivateDataCall(
865                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
866                 any(Message.class));
867         assertEquals(DctConstants.State.CONNECTED, mDct.getOverallState());
868         assertEquals(DctConstants.State.IDLE, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
869         assertEquals(DctConstants.State.CONNECTED, mDct.getState(PhoneConstants.APN_TYPE_IMS));
870 
871         // reset roaming settings / data enabled settings at end of this test
872         mDct.setDataRoamingEnabledByUser(roamingEnabled);
873         waitForMs(200);
874     }
875 
876     @Test
877     @MediumTest
testDataCallOnUserDisableRoaming()878     public void testDataCallOnUserDisableRoaming() throws Exception {
879         //step 1: mock under roaming service and user disabled roaming from settings.
880         //step 2: user toggled data settings on
881         //step 3: only non-metered data call is established
882 
883         boolean roamingEnabled = mDct.getDataRoamingEnabled();
884         doReturn(true).when(mServiceState).getDataRoaming();
885 
886         //set Default and MMS to be metered in the CarrierConfigManager
887         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_ROAMING_APN_TYPES_STRINGS,
888                 new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
889         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
890         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
891 
892         logd("Sending DISABLE_ROAMING_CMD");
893         mDct.setDataRoamingEnabledByUser(false);
894 
895         logd("Sending EVENT_RECORDS_LOADED");
896         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
897         waitForMs(200);
898 
899         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
900         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
901         waitForMs(200);
902 
903         waitForMs(200);
904         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
905         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
906                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
907                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
908                 any(Message.class));
909         verifyDataProfile(dpCaptor.getValue(), FAKE_APN3, 2, 64, 0, 0);
910 
911         assertEquals(DctConstants.State.CONNECTED, mDct.getOverallState());
912         assertEquals(DctConstants.State.IDLE, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
913         assertEquals(DctConstants.State.CONNECTED, mDct.getState(PhoneConstants.APN_TYPE_IMS));
914 
915         // reset roaming settings / data enabled settings at end of this test
916         mDct.setDataRoamingEnabledByUser(roamingEnabled);
917         waitForMs(200);
918     }
919 
920     // Test the default data switch scenario.
921     @FlakyTest /* flakes 1.57% of the time */
922     @Test
923     @MediumTest
testDDSResetAutoAttach()924     public void testDDSResetAutoAttach() throws Exception {
925 
926         ContentResolver resolver = mContext.getContentResolver();
927         Settings.Global.putInt(resolver, Settings.Global.DEVICE_PROVISIONED, 1);
928 
929         mContextFixture.putBooleanResource(
930                 com.android.internal.R.bool.config_auto_attach_data_on_creation, true);
931 
932         mSimulatedCommands.setDataCallResult(true, createSetupDataCallResult());
933 
934         AsyncResult ar = new AsyncResult(null,
935                 new Pair<>(true, DataEnabledSettings.REASON_USER_DATA_ENABLED), null);
936         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_ENABLED_CHANGED, ar));
937         waitForMs(200);
938 
939         DataConnectionReasons dataConnectionReasons = new DataConnectionReasons();
940         boolean allowed = isDataAllowed(dataConnectionReasons);
941         assertFalse(dataConnectionReasons.toString(), allowed);
942 
943         ArgumentCaptor<Integer> intArgumentCaptor = ArgumentCaptor.forClass(Integer.class);
944         verify(mUiccController, times(1)).registerForIccChanged(eq(mDct),
945                 intArgumentCaptor.capture(), eq(null));
946         // Ideally this should send EVENT_ICC_CHANGED.
947         mDct.sendMessage(mDct.obtainMessage(intArgumentCaptor.getValue(), null));
948         waitForMs(100);
949 
950         verify(mSimRecords, times(1)).registerForRecordsLoaded(eq(mDct),
951                 intArgumentCaptor.capture(), eq(null));
952         // Ideally this should send EVENT_RECORDS_LOADED.
953         mDct.sendMessage(mDct.obtainMessage(intArgumentCaptor.getValue(), null));
954         waitForMs(100);
955 
956         verify(mSST, times(1)).registerForDataConnectionAttached(
957                 eq(AccessNetworkConstants.TRANSPORT_TYPE_WWAN), eq(mDct),
958                 intArgumentCaptor.capture(), eq(null));
959         // Ideally this should send EVENT_DATA_CONNECTION_ATTACHED");
960         mDct.sendMessage(mDct.obtainMessage(intArgumentCaptor.getValue(), null));
961         waitForMs(200);
962 
963         NetworkRequest nr = new NetworkRequest.Builder()
964                 .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
965         mDct.requestNetwork(nr, DcTracker.REQUEST_TYPE_NORMAL, null);
966         waitForMs(200);
967 
968         verifyDataConnected(FAKE_APN1);
969 
970         assertTrue(mDct.shouldAutoAttach());
971         mDct.update();
972         // The auto attach flag should be reset after update
973         assertFalse(mDct.shouldAutoAttach());
974 
975         verify(mSST, times(1)).registerForDataConnectionDetached(
976                 eq(AccessNetworkConstants.TRANSPORT_TYPE_WWAN), eq(mDct),
977                 intArgumentCaptor.capture(), eq(null));
978         // Ideally this should send EVENT_DATA_CONNECTION_DETACHED
979         mDct.sendMessage(mDct.obtainMessage(intArgumentCaptor.getValue(), null));
980         waitForMs(200);
981 
982         // Data should not be allowed since auto attach flag has been reset.
983         dataConnectionReasons = new DataConnectionReasons();
984         allowed = isDataAllowed(dataConnectionReasons);
985         assertFalse(dataConnectionReasons.toString(), allowed);
986     }
987 
988     // Test for API carrierActionSetMeteredApnsEnabled.
989     @FlakyTest
990     @Ignore
991     @Test
992     @MediumTest
testCarrierActionSetMeteredApnsEnabled()993     public void testCarrierActionSetMeteredApnsEnabled() throws Exception {
994         //step 1: setup two DataCalls one for Internet and IMS
995         //step 2: set data is enabled
996         //step 3: cold sim is detected
997         //step 4: all data connection is torn down
998         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
999                 new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
1000 
1001         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
1002         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1003 
1004         logd("Sending EVENT_RECORDS_LOADED");
1005         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
1006         waitForMs(200);
1007 
1008         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
1009         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
1010         waitForMs(200);
1011 
1012         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1013         verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
1014                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1015                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1016                 any(Message.class));
1017         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 5, 1, NETWORK_TYPE_LTE_BITMASK);
1018         assertEquals(DctConstants.State.CONNECTED, mDct.getOverallState());
1019 
1020         AsyncResult ar = new AsyncResult(null,
1021                 new Pair<>(false, DataEnabledSettings.REASON_DATA_ENABLED_BY_CARRIER), null);
1022         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_ENABLED_CHANGED, ar));
1023         waitForMs(200);
1024 
1025         // Validate all metered data connections have been torn down
1026         verify(mSimulatedCommandsVerifier, times(1)).deactivateDataCall(
1027                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
1028                 any(Message.class));
1029         assertEquals(DctConstants.State.CONNECTED, mDct.getOverallState());
1030         assertEquals(DctConstants.State.IDLE, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
1031     }
1032 
initApns(String targetApn, String[] canHandleTypes)1033     private void initApns(String targetApn, String[] canHandleTypes) {
1034         doReturn(targetApn).when(mApnContext).getApnType();
1035         doReturn(true).when(mApnContext).isConnectable();
1036         ApnSetting apnSetting = createApnSetting(ApnSetting.getApnTypesBitmaskFromString(
1037                 TextUtils.join(",", canHandleTypes)));
1038         doReturn(apnSetting).when(mApnContext).getNextApnSetting();
1039         doReturn(apnSetting).when(mApnContext).getApnSetting();
1040         doReturn(mDataConnection).when(mApnContext).getDataConnection();
1041         doReturn(true).when(mApnContext).isEnabled();
1042         doReturn(true).when(mApnContext).isDependencyMet();
1043         doReturn(true).when(mApnContext).isReady();
1044         doReturn(false).when(mApnContext).hasRestrictedRequests(eq(true));
1045     }
1046 
1047     // Test the emergency APN setup.
1048     @Test
1049     @SmallTest
testTrySetupDataEmergencyApn()1050     public void testTrySetupDataEmergencyApn() throws Exception {
1051         initApns(PhoneConstants.APN_TYPE_EMERGENCY, new String[]{PhoneConstants.APN_TYPE_ALL});
1052         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TRY_SETUP_DATA, mApnContext));
1053         waitForMs(200);
1054 
1055         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
1056                 eq(AccessNetworkType.EUTRAN), any(DataProfile.class),
1057                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1058                 any(Message.class));
1059     }
1060 
1061     @Test
1062     @SmallTest
testGetDataConnectionState()1063     public void testGetDataConnectionState() throws Exception {
1064         initApns(PhoneConstants.APN_TYPE_SUPL,
1065                 new String[]{PhoneConstants.APN_TYPE_SUPL, PhoneConstants.APN_TYPE_DEFAULT});
1066         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1067                 new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1068 
1069         logd("Sending EVENT_RECORDS_LOADED");
1070         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
1071         waitForMs(200);
1072 
1073         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
1074         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
1075         waitForMs(200);
1076 
1077         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TRY_SETUP_DATA, mApnContext));
1078         waitForMs(200);
1079 
1080         // Assert that both APN_TYPE_SUPL & APN_TYPE_DEFAULT are connected even we only setup data
1081         // for APN_TYPE_SUPL
1082         assertEquals(DctConstants.State.CONNECTED, mDct.getState(PhoneConstants.APN_TYPE_SUPL));
1083         assertEquals(DctConstants.State.CONNECTED, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
1084     }
1085 
1086     // Test the unmetered APN setup when data is disabled.
1087     @Test
1088     @SmallTest
testTrySetupDataUnmeteredDataDisabled()1089     public void testTrySetupDataUnmeteredDataDisabled() throws Exception {
1090         initApns(PhoneConstants.APN_TYPE_FOTA, new String[]{PhoneConstants.APN_TYPE_ALL});
1091         //mDct.setUserDataEnabled(false);
1092         doReturn(false).when(mDataEnabledSettings).isDataEnabled();
1093         doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
1094 
1095         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1096                 new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1097 
1098         logd("Sending EVENT_RECORDS_LOADED");
1099         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
1100         waitForMs(200);
1101 
1102         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
1103         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
1104         waitForMs(200);
1105 
1106         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TRY_SETUP_DATA, mApnContext));
1107         waitForMs(200);
1108 
1109         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
1110                 eq(AccessNetworkType.EUTRAN), any(DataProfile.class),
1111                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1112                 any(Message.class));
1113     }
1114 
1115     // Test the metered APN setup when data is disabled.
1116     @Test
1117     @SmallTest
testTrySetupMeteredDataDisabled()1118     public void testTrySetupMeteredDataDisabled() throws Exception {
1119         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
1120         //mDct.setUserDataEnabled(false);
1121         doReturn(false).when(mDataEnabledSettings).isDataEnabled();
1122         doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
1123 
1124         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1125                 new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1126 
1127         logd("Sending EVENT_RECORDS_LOADED");
1128         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
1129         waitForMs(200);
1130 
1131         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
1132         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
1133         waitForMs(200);
1134 
1135         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TRY_SETUP_DATA, mApnContext));
1136         waitForMs(200);
1137 
1138         verify(mSimulatedCommandsVerifier, times(0)).setupDataCall(anyInt(), any(DataProfile.class),
1139                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1140                 any(Message.class));
1141     }
1142 
1143     // Test the restricted data request when data is disabled.
1144     @Test
1145     @SmallTest
testTrySetupRestrictedDataDisabled()1146     public void testTrySetupRestrictedDataDisabled() throws Exception {
1147         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
1148         doReturn(true).when(mApnContext).hasRestrictedRequests(eq(true));
1149 
1150         //mDct.setUserDataEnabled(false);
1151         doReturn(false).when(mDataEnabledSettings).isDataEnabled();
1152         doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
1153 
1154         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1155                 new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1156 
1157         logd("Sending EVENT_RECORDS_LOADED");
1158         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
1159         waitForMs(200);
1160 
1161         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
1162         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
1163         waitForMs(200);
1164 
1165         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TRY_SETUP_DATA, mApnContext));
1166         waitForMs(200);
1167 
1168         verify(mSimulatedCommandsVerifier, times(1)).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 roaming is disabled.
1174     @Test
1175     @SmallTest
testTrySetupRestrictedRoamingDisabled()1176     public void testTrySetupRestrictedRoamingDisabled() throws Exception {
1177         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
1178         doReturn(true).when(mApnContext).hasRestrictedRequests(eq(true));
1179 
1180         mDct.setDataRoamingEnabledByUser(false);
1181         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1182                 new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1183         //user is in roaming
1184         doReturn(true).when(mServiceState).getDataRoaming();
1185 
1186         logd("Sending EVENT_RECORDS_LOADED");
1187         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
1188         waitForMs(200);
1189 
1190         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
1191         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
1192         waitForMs(200);
1193 
1194         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TRY_SETUP_DATA, mApnContext));
1195         waitForMs(200);
1196 
1197         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(anyInt(), any(DataProfile.class),
1198                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1199                 any(Message.class));
1200     }
1201 
1202     // Test the default data when data is not connectable.
1203     @Test
1204     @SmallTest
testTrySetupNotConnectable()1205     public void testTrySetupNotConnectable() throws Exception {
1206         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
1207         doReturn(false).when(mApnContext).isConnectable();
1208 
1209         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1210                 new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1211 
1212         logd("Sending EVENT_RECORDS_LOADED");
1213         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
1214         waitForMs(200);
1215 
1216         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
1217         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
1218         waitForMs(200);
1219 
1220         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TRY_SETUP_DATA, mApnContext));
1221         waitForMs(200);
1222 
1223         verify(mSimulatedCommandsVerifier, times(0)).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 on IWLAN.
1229     @Test
1230     @SmallTest
testTrySetupDefaultOnIWLAN()1231     public void testTrySetupDefaultOnIWLAN() throws Exception {
1232         doReturn(true).when(mTransportManager).isInLegacyMode();
1233         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
1234         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
1235                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_IWLAN)
1236                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
1237                 .build();
1238         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
1239                 anyInt(), anyInt());
1240 
1241         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1242                 new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1243 
1244         logd("Sending EVENT_RECORDS_LOADED");
1245         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
1246         waitForMs(200);
1247 
1248         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
1249         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
1250         waitForMs(200);
1251 
1252         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TRY_SETUP_DATA, mApnContext));
1253         waitForMs(200);
1254 
1255         verify(mSimulatedCommandsVerifier, times(0)).setupDataCall(anyInt(), any(DataProfile.class),
1256                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1257                 any(Message.class));
1258     }
1259 
1260     // Test the default data when the phone is in ECBM.
1261     @Test
1262     @SmallTest
testTrySetupDefaultInECBM()1263     public void testTrySetupDefaultInECBM() throws Exception {
1264         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
1265         doReturn(true).when(mPhone).isInEcm();
1266 
1267         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1268                 new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1269 
1270         logd("Sending EVENT_RECORDS_LOADED");
1271         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
1272         waitForMs(200);
1273 
1274         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
1275         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
1276         waitForMs(200);
1277 
1278         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TRY_SETUP_DATA, mApnContext));
1279         waitForMs(200);
1280 
1281         verify(mSimulatedCommandsVerifier, times(0)).setupDataCall(anyInt(), any(DataProfile.class),
1282                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1283                 any(Message.class));
1284     }
1285 
1286     // Test update waiting apn list when on data rat change
1287     @FlakyTest /* flakes 0.86% of the time */
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         logd("Sending EVENT_RECORDS_LOADED");
1303         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
1304         waitForMs(200);
1305 
1306         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
1307         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
1308         waitForMs(200);
1309 
1310         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1311         // Verify if RIL command was sent properly.
1312         verify(mSimulatedCommandsVerifier).setupDataCall(
1313                 eq(AccessNetworkType.CDMA2000), dpCaptor.capture(),
1314                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1315                 any(Message.class));
1316         verifyDataProfile(dpCaptor.getValue(), FAKE_APN4, 0, 21, 2, NETWORK_TYPE_EHRPD_BITMASK);
1317         assertEquals(DctConstants.State.CONNECTED, mDct.getOverallState());
1318 
1319         //data rat change from ehrpd to lte
1320         logd("Sending EVENT_DATA_RAT_CHANGED");
1321         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
1322                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_LTE)
1323                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
1324                 .build();
1325         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
1326                 anyInt(), anyInt());
1327         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_RAT_CHANGED, null));
1328         waitForMs(200);
1329 
1330         // Verify the disconnected data call due to rat change and retry manger schedule another
1331         // data call setup
1332         verify(mSimulatedCommandsVerifier, times(1)).deactivateDataCall(
1333                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
1334                 any(Message.class));
1335         verify(mAlarmManager, times(1)).setExact(eq(AlarmManager.ELAPSED_REALTIME_WAKEUP),
1336                 anyLong(), any(PendingIntent.class));
1337 
1338         // Simulate the timer expires.
1339         Intent intent = new Intent("com.android.internal.telephony.data-reconnect.default");
1340         intent.putExtra("reconnect_alarm_extra_type", PhoneConstants.APN_TYPE_DEFAULT);
1341         intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, 0);
1342         intent.putExtra("reconnect_alarm_extra_transport_type",
1343                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
1344         intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1345         mContext.sendBroadcast(intent);
1346         waitForMs(200);
1347 
1348         // Verify if RIL command was sent properly.
1349         verify(mSimulatedCommandsVerifier).setupDataCall(
1350                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1351                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1352                 any(Message.class));
1353         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
1354         assertEquals(DctConstants.State.CONNECTED, mDct.getOverallState());
1355     }
1356 
1357     // Test for fetchDunApns()
1358     @Test
1359     @SmallTest
testFetchDunApn()1360     public void testFetchDunApn() {
1361         logd("Sending EVENT_RECORDS_LOADED");
1362         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
1363         waitForMs(200);
1364 
1365         String dunApnString = "[ApnSettingV3]HOT mobile PC,pc.hotm,,,,,,,,,440,10,,DUN,,,true,"
1366                 + "0,,,,,,,,";
1367         ApnSetting dunApnExpected = ApnSetting.fromString(dunApnString);
1368 
1369         Settings.Global.putString(mContext.getContentResolver(),
1370                 Settings.Global.TETHER_DUN_APN, dunApnString);
1371         // should return APN from Setting
1372         ApnSetting dunApn = mDct.fetchDunApns().get(0);
1373         assertTrue(dunApnExpected.equals(dunApn));
1374 
1375         Settings.Global.putString(mContext.getContentResolver(),
1376                 Settings.Global.TETHER_DUN_APN, null);
1377         // should return APN from db
1378         dunApn = mDct.fetchDunApns().get(0);
1379         assertEquals(FAKE_APN5, dunApn.getApnName());
1380     }
1381 
1382     // Test for fetchDunApns() with apn set id
1383     @Test
1384     @SmallTest
testFetchDunApnWithPreferredApnSet()1385     public void testFetchDunApnWithPreferredApnSet() {
1386         logd("Sending EVENT_RECORDS_LOADED");
1387         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
1388         waitForMs(200);
1389 
1390         // apnSetId=1
1391         String dunApnString1 = "[ApnSettingV5]HOT mobile PC,pc.hotm,,,,,,,,,440,10,,DUN,,,true,"
1392                 + "0,,,,,,,,,,1";
1393         // apnSetId=0
1394         String dunApnString2 = "[ApnSettingV5]HOT mobile PC,pc.coldm,,,,,,,,,440,10,,DUN,,,true,"
1395                 + "0,,,,,,,,,,0";
1396 
1397         ApnSetting dunApnExpected = ApnSetting.fromString(dunApnString1);
1398 
1399         ContentResolver cr = mContext.getContentResolver();
1400         Settings.Global.putString(cr, Settings.Global.TETHER_DUN_APN,
1401                 dunApnString1 + ";" + dunApnString2);
1402 
1403         // set that we prefer apn set 1
1404         ContentValues values = new ContentValues();
1405         values.put(Telephony.Carriers.APN_SET_ID, 1);
1406         cr.update(PREFERAPN_URI, values, null, null);
1407 
1408         // return APN from Setting with apnSetId=1
1409         ArrayList<ApnSetting> dunApns = mDct.sortApnListByPreferred(mDct.fetchDunApns());
1410         assertEquals(2, dunApns.size());
1411         assertTrue(dunApnExpected.equals(dunApns.get(0)));
1412     }
1413 
1414     // Test oos
1415     @Test
1416     @SmallTest
testDataRatChangeOOS()1417     public void testDataRatChangeOOS() throws Exception {
1418         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
1419                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_EHRPD)
1420                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
1421                 .build();
1422         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
1423                 anyInt(), anyInt());
1424 
1425         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1426                 new String[]{PhoneConstants.APN_TYPE_DEFAULT});
1427         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1428         initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
1429 
1430         logd("Sending EVENT_RECORDS_LOADED");
1431         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
1432         waitForMs(200);
1433 
1434         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
1435         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
1436         waitForMs(200);
1437 
1438         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1439         // Verify if RIL command was sent properly.
1440         verify(mSimulatedCommandsVerifier).setupDataCall(
1441                 eq(AccessNetworkType.CDMA2000), dpCaptor.capture(),
1442                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1443                 any(Message.class));
1444         verifyDataProfile(dpCaptor.getValue(), FAKE_APN4, 0, 21, 2, NETWORK_TYPE_EHRPD_BITMASK);
1445         assertEquals(DctConstants.State.CONNECTED, mDct.getOverallState());
1446 
1447         // Data rat change from ehrpd to unknown due to OOS
1448         logd("Sending EVENT_DATA_RAT_CHANGED");
1449         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
1450                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_UNKNOWN)
1451                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
1452                 .build();
1453         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
1454                 anyInt(), anyInt());
1455         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_RAT_CHANGED, null));
1456         waitForMs(200);
1457 
1458         // Verify data connection is on
1459         verify(mSimulatedCommandsVerifier, times(0)).deactivateDataCall(
1460                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
1461                 any(Message.class));
1462 
1463         // Data rat resume from unknown to ehrpd
1464         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
1465                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_EHRPD)
1466                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
1467                 .build();
1468         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
1469                 anyInt(), anyInt());
1470         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_RAT_CHANGED, null));
1471         waitForMs(200);
1472 
1473         // Verify the same data connection
1474         assertEquals(FAKE_APN4, mDct.getActiveApnString(PhoneConstants.APN_TYPE_DEFAULT));
1475         assertEquals(DctConstants.State.CONNECTED, mDct.getOverallState());
1476     }
1477 
1478     // Test provisioning
1479     /*@Test
1480     @SmallTest
1481     public void testDataEnableInProvisioning() throws Exception {
1482         ContentResolver resolver = mContext.getContentResolver();
1483 
1484         assertEquals(1, Settings.Global.getInt(resolver, Settings.Global.MOBILE_DATA));
1485         assertTrue(mDct.isDataEnabled());
1486         assertTrue(mDct.isUserDataEnabled());
1487 
1488         mDct.setUserDataEnabled(false);
1489         waitForMs(200);
1490 
1491         assertEquals(0, Settings.Global.getInt(resolver, Settings.Global.MOBILE_DATA));
1492         assertFalse(mDct.isDataEnabled());
1493         assertFalse(mDct.isUserDataEnabled());
1494 
1495         // Changing provisioned to 0.
1496         Settings.Global.putInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0);
1497         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DEVICE_PROVISIONED_CHANGE, null));
1498         waitForMs(200);
1499 
1500         assertTrue(mDct.isDataEnabled());
1501         assertTrue(mDct.isUserDataEnabled());
1502 
1503         // Enable user data during provisioning. It should write to
1504         // Settings.Global.MOBILE_DATA and keep data enabled when provisioned.
1505         mDct.setUserDataEnabled(true);
1506         Settings.Global.putInt(resolver, Settings.Global.DEVICE_PROVISIONED, 1);
1507         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DEVICE_PROVISIONED_CHANGE, null));
1508         waitForMs(200);
1509 
1510         assertTrue(mDct.isDataEnabled());
1511         assertTrue(mDct.isUserDataEnabled());
1512         assertEquals(1, Settings.Global.getInt(resolver, Settings.Global.MOBILE_DATA));
1513     }*/
1514 
1515     /*
1516     @Test
1517     @SmallTest
1518     public void testNotifyDataEnabledChanged() throws Exception {
1519         doAnswer(invocation -> {
1520             mMessage = (Message) invocation.getArguments()[0];
1521             return true;
1522         }).when(mHandler).sendMessageDelayed(any(), anyLong());
1523 
1524         // Test registration.
1525         mDct.registerForDataEnabledChanged(mHandler, DATA_ENABLED_CHANGED, null);
1526         verifyDataEnabledChangedMessage(true, DataEnabledSettings.REASON_REGISTERED);
1527 
1528         // Disable user data. Should receive data enabled change to false.
1529         mDct.setUserDataEnabled(false);
1530         waitForMs(200);
1531         verifyDataEnabledChangedMessage(false, DataEnabledSettings.REASON_USER_DATA_ENABLED);
1532 
1533         // Changing provisioned to 0. Shouldn't receive any message, as data enabled remains false.
1534         ContentResolver resolver = mContext.getContentResolver();
1535         Settings.Global.putInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0);
1536         Settings.Global.putInt(resolver, Settings.Global.DEVICE_PROVISIONING_MOBILE_DATA_ENABLED,
1537                 0);
1538         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DEVICE_PROVISIONED_CHANGE, null));
1539         waitForMs(200);
1540         assertFalse(mDct.isDataEnabled());
1541         verify(mHandler, never()).sendMessageDelayed(any(), anyLong());
1542 
1543         // Changing provisioningDataEnabled to 1. It should trigger data enabled change to true.
1544         Settings.Global.putInt(resolver,
1545                 Settings.Global.DEVICE_PROVISIONING_MOBILE_DATA_ENABLED, 1);
1546         mDct.sendMessage(mDct.obtainMessage(
1547                 DctConstants.EVENT_DEVICE_PROVISIONING_DATA_SETTING_CHANGE, null));
1548         waitForMs(200);
1549         verifyDataEnabledChangedMessage(
1550                 true, DataEnabledSettings.REASON_PROVISIONING_DATA_ENABLED_CHANGED);
1551     }*/
1552 
1553     @Test
1554     @SmallTest
testNetworkStatusChangedRecoveryOFF()1555     public void testNetworkStatusChangedRecoveryOFF() throws Exception {
1556         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1557                 new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
1558         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
1559         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1560 
1561         logd("Sending EVENT_RECORDS_LOADED");
1562         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
1563         waitForMs(200);
1564 
1565         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
1566         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
1567         waitForMs(200);
1568 
1569         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1570         verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
1571                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1572                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1573                 any(Message.class));
1574         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
1575 
1576         logd("Sending EVENT_NETWORK_STATUS_CHANGED");
1577         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NETWORK_STATUS_CHANGED,
1578                 NetworkAgent.VALID_NETWORK, 0, null));
1579         waitForMs(200);
1580 
1581         logd("Sending EVENT_NETWORK_STATUS_CHANGED");
1582         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NETWORK_STATUS_CHANGED,
1583                 NetworkAgent.INVALID_NETWORK, 0, null));
1584         waitForMs(200);
1585 
1586         // Verify that its no-op when the new data stall detection feature is disabled
1587         verify(mSimulatedCommandsVerifier, times(0)).getDataCallList(any(Message.class));
1588     }
1589 
1590     @FlakyTest
1591     @Test
1592     @SmallTest
testNetworkStatusChangedRecoveryON()1593     public void testNetworkStatusChangedRecoveryON() throws Exception {
1594         ContentResolver resolver = mContext.getContentResolver();
1595         Settings.Global.putInt(resolver, Settings.Global.DATA_STALL_RECOVERY_ON_BAD_NETWORK, 1);
1596         Settings.System.putInt(resolver, "radio.data.stall.recovery.action", 0);
1597 
1598         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1599                 new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
1600         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
1601         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1602 
1603         logd("Sending EVENT_RECORDS_LOADED");
1604         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
1605         waitForMs(200);
1606 
1607         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
1608         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
1609 
1610         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1611         verify(mSimulatedCommandsVerifier, timeout(TEST_TIMEOUT).times(2)).setupDataCall(
1612                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1613                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1614                 any(Message.class));
1615         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
1616 
1617         logd("Sending EVENT_NETWORK_STATUS_CHANGED");
1618         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NETWORK_STATUS_CHANGED,
1619                 NetworkAgent.VALID_NETWORK, 0, null));
1620         waitForMs(200);
1621 
1622         logd("Sending EVENT_NETWORK_STATUS_CHANGED");
1623         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NETWORK_STATUS_CHANGED,
1624                 NetworkAgent.INVALID_NETWORK, 0, null));
1625         waitForMs(200);
1626 
1627         verify(mSimulatedCommandsVerifier, times(1)).getDataCallList(any(Message.class));
1628     }
1629 
1630     @FlakyTest
1631     @Test
1632     @SmallTest
testRecoveryStepPDPReset()1633     public void testRecoveryStepPDPReset() throws Exception {
1634         ContentResolver resolver = mContext.getContentResolver();
1635         Settings.Global.putInt(resolver, Settings.Global.DATA_STALL_RECOVERY_ON_BAD_NETWORK, 1);
1636         Settings.Global.putLong(resolver,
1637                 Settings.Global.MIN_DURATION_BETWEEN_RECOVERY_STEPS_IN_MS, 100);
1638         Settings.System.putInt(resolver, "radio.data.stall.recovery.action", 1);
1639 
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         logd("Sending EVENT_RECORDS_LOADED");
1646         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
1647         waitForMs(200);
1648 
1649         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
1650         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
1651 
1652         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1653         verify(mSimulatedCommandsVerifier, timeout(TEST_TIMEOUT).times(2)).setupDataCall(
1654                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1655                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1656                 any(Message.class));
1657         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
1658 
1659         logd("Sending EVENT_NETWORK_STATUS_CHANGED false");
1660         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NETWORK_STATUS_CHANGED,
1661                 NetworkAgent.INVALID_NETWORK, 0, null));
1662         waitForMs(200);
1663 
1664         // expected tear down all DataConnections
1665         verify(mSimulatedCommandsVerifier, times(1)).deactivateDataCall(
1666                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
1667                 any(Message.class));
1668     }
1669 
1670 
1671     @Test
1672     @SmallTest
testRecoveryStepReRegister()1673     public void testRecoveryStepReRegister() throws Exception {
1674         ContentResolver resolver = mContext.getContentResolver();
1675         Settings.Global.putInt(resolver, Settings.Global.DATA_STALL_RECOVERY_ON_BAD_NETWORK, 1);
1676         Settings.Global.putLong(resolver,
1677                 Settings.Global.MIN_DURATION_BETWEEN_RECOVERY_STEPS_IN_MS, 100);
1678         Settings.System.putInt(resolver, "radio.data.stall.recovery.action", 2);
1679 
1680         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1681                 new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
1682         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1683 
1684         logd("Sending EVENT_RECORDS_LOADED");
1685         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
1686         waitForMs(200);
1687 
1688         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
1689         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
1690         waitForMs(200);
1691 
1692         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1693         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
1694                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1695                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1696                 any(Message.class));
1697         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
1698 
1699         logd("Sending EVENT_NETWORK_STATUS_CHANGED false");
1700         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NETWORK_STATUS_CHANGED,
1701                 NetworkAgent.INVALID_NETWORK, 0, null));
1702         waitForMs(200);
1703 
1704         // expected to get preferred network type
1705         verify(mSST, times(1)).reRegisterNetwork(eq(null));
1706     }
1707 
1708     @Test
1709     @SmallTest
testRecoveryStepRestartRadio()1710     public void testRecoveryStepRestartRadio() throws Exception {
1711         ContentResolver resolver = mContext.getContentResolver();
1712         Settings.Global.putInt(resolver, Settings.Global.DATA_STALL_RECOVERY_ON_BAD_NETWORK, 1);
1713         Settings.Global.putLong(resolver,
1714                 Settings.Global.MIN_DURATION_BETWEEN_RECOVERY_STEPS_IN_MS, 100);
1715         Settings.System.putInt(resolver, "radio.data.stall.recovery.action", 3);
1716 
1717         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1718                 new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
1719         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1720 
1721         logd("Sending EVENT_RECORDS_LOADED");
1722         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_RECORDS_LOADED, null));
1723         waitForMs(200);
1724 
1725         logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
1726         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
1727         waitForMs(200);
1728 
1729         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1730         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
1731                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1732                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1733                 any(Message.class));
1734         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
1735 
1736         logd("Sending EVENT_NETWORK_STATUS_CHANGED false");
1737         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NETWORK_STATUS_CHANGED,
1738                 NetworkAgent.INVALID_NETWORK, 0, null));
1739         waitForMs(200);
1740 
1741         // expected to get preferred network type
1742         verify(mSST, times(1)).powerOffRadioSafely();
1743     }
1744 
verifyDataEnabledChangedMessage(boolean enabled, int reason)1745     private void verifyDataEnabledChangedMessage(boolean enabled, int reason) {
1746         verify(mHandler, times(1)).sendMessageDelayed(any(), anyLong());
1747         Pair<Boolean, Integer> result = (Pair) ((AsyncResult) mMessage.obj).result;
1748         assertEquals(DATA_ENABLED_CHANGED, mMessage.what);
1749         assertEquals(enabled, result.first);
1750         assertEquals(reason, (int) result.second);
1751         clearInvocations(mHandler);
1752     }
1753 }
1754