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