1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.internal.telephony.dataconnection;
18 
19 import static com.android.internal.telephony.TelephonyTestUtils.waitForMs;
20 import static com.android.internal.telephony.dataconnection.ApnSettingTest.createApnSetting;
21 
22 import static org.junit.Assert.assertArrayEquals;
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertFalse;
25 import static org.junit.Assert.assertNotEquals;
26 import static org.junit.Assert.assertTrue;
27 import static org.junit.Assert.fail;
28 import static org.mockito.Matchers.any;
29 import static org.mockito.Matchers.anyBoolean;
30 import static org.mockito.Matchers.anyInt;
31 import static org.mockito.Matchers.anyLong;
32 import static org.mockito.Matchers.anyString;
33 import static org.mockito.Matchers.eq;
34 import static org.mockito.Mockito.clearInvocations;
35 import static org.mockito.Mockito.doAnswer;
36 import static org.mockito.Mockito.doReturn;
37 import static org.mockito.Mockito.never;
38 import static org.mockito.Mockito.spy;
39 import static org.mockito.Mockito.timeout;
40 import static org.mockito.Mockito.times;
41 import static org.mockito.Mockito.verify;
42 
43 import android.app.AlarmManager;
44 import android.app.PendingIntent;
45 import android.content.ContentResolver;
46 import android.content.ContentValues;
47 import android.content.Context;
48 import android.content.Intent;
49 import android.content.IntentFilter;
50 import android.content.pm.ServiceInfo;
51 import android.database.Cursor;
52 import android.database.MatrixCursor;
53 import android.hardware.radio.V1_0.SetupDataCallResult;
54 import android.net.LinkProperties;
55 import android.net.NetworkAgent;
56 import android.net.NetworkCapabilities;
57 import android.net.NetworkPolicyManager;
58 import android.net.NetworkRequest;
59 import android.net.Uri;
60 import android.os.AsyncResult;
61 import android.os.Bundle;
62 import android.os.Handler;
63 import android.os.HandlerThread;
64 import android.os.IBinder;
65 import android.os.Message;
66 import android.os.PersistableBundle;
67 import android.os.SystemClock;
68 import android.provider.Settings;
69 import android.provider.Telephony;
70 import android.telephony.AccessNetworkConstants;
71 import android.telephony.AccessNetworkConstants.AccessNetworkType;
72 import android.telephony.Annotation;
73 import android.telephony.CarrierConfigManager;
74 import android.telephony.DataFailCause;
75 import android.telephony.NetworkRegistrationInfo;
76 import android.telephony.PreciseDataConnectionState;
77 import android.telephony.ServiceState;
78 import android.telephony.SignalStrength;
79 import android.telephony.SubscriptionInfo;
80 import android.telephony.SubscriptionManager;
81 import android.telephony.SubscriptionPlan;
82 import android.telephony.TelephonyDisplayInfo;
83 import android.telephony.TelephonyManager;
84 import android.telephony.data.ApnSetting;
85 import android.telephony.data.DataCallResponse;
86 import android.telephony.data.DataProfile;
87 import android.telephony.data.DataService;
88 import android.telephony.data.TrafficDescriptor;
89 import android.test.mock.MockContentProvider;
90 import android.test.mock.MockContentResolver;
91 import android.test.suitebuilder.annotation.MediumTest;
92 import android.test.suitebuilder.annotation.SmallTest;
93 import android.text.TextUtils;
94 import android.util.Pair;
95 import android.util.SparseArray;
96 
97 import androidx.test.filters.FlakyTest;
98 
99 import com.android.internal.R;
100 import com.android.internal.telephony.DctConstants;
101 import com.android.internal.telephony.ISub;
102 import com.android.internal.telephony.PhoneConstants;
103 import com.android.internal.telephony.RetryManager;
104 import com.android.internal.telephony.TelephonyTest;
105 import com.android.internal.telephony.dataconnection.DataConnectionReasons.DataDisallowedReasonType;
106 
107 import org.junit.After;
108 import org.junit.Before;
109 import org.junit.Ignore;
110 import org.junit.Test;
111 import org.mockito.ArgumentCaptor;
112 import org.mockito.Mock;
113 import org.mockito.Mockito;
114 import org.mockito.invocation.InvocationOnMock;
115 import org.mockito.stubbing.Answer;
116 
117 import java.lang.reflect.Field;
118 import java.lang.reflect.Method;
119 import java.time.Period;
120 import java.time.ZonedDateTime;
121 import java.util.ArrayList;
122 import java.util.Arrays;
123 import java.util.HashMap;
124 import java.util.List;
125 import java.util.Map;
126 import java.util.Objects;
127 import java.util.Optional;
128 import java.util.concurrent.ConcurrentHashMap;
129 import java.util.concurrent.atomic.AtomicInteger;
130 import java.util.stream.Collectors;
131 
132 public class DcTrackerTest extends TelephonyTest {
133     public static final String FAKE_APN1 = "FAKE APN 1";
134     public static final String FAKE_APN2 = "FAKE APN 2";
135     public static final String FAKE_APN3 = "FAKE APN 3";
136     public static final String FAKE_APN4 = "FAKE APN 4";
137     public static final String FAKE_APN5 = "FAKE APN 5";
138     public static final String FAKE_APN6 = "FAKE APN 6";
139     public static final String FAKE_APN7 = "FAKE APN 7";
140     public static final String FAKE_APN8 = "FAKE APN 8";
141     public static final String FAKE_APN9 = "FAKE APN 9";
142     public static final String FAKE_IFNAME = "FAKE IFNAME";
143     public static final String FAKE_PCSCF_ADDRESS = "22.33.44.55";
144     public static final String FAKE_GATEWAY = "11.22.33.44";
145     public static final String FAKE_DNS = "55.66.77.88";
146     public static final String FAKE_ADDRESS = "99.88.77.66";
147     private static final int NETWORK_TYPE_NR_BITMASK =
148             1 << (TelephonyManager.NETWORK_TYPE_NR - 1);
149     private static final int NETWORK_TYPE_LTE_BITMASK =
150             1 << (TelephonyManager.NETWORK_TYPE_LTE - 1);
151     private static final int NETWORK_TYPE_EHRPD_BITMASK =
152             1 << (TelephonyManager.NETWORK_TYPE_EHRPD - 1);
153     private static final Uri PREFERAPN_URI = Uri.parse(
154             Telephony.Carriers.CONTENT_URI + "/preferapn");
155     private static final int DATA_ENABLED_CHANGED = 0;
156     private static final String FAKE_PLMN = "44010";
157     private static final long TEST_TIMEOUT = 1000;
158 
159     @Mock
160     ISub mIsub;
161     @Mock
162     IBinder mBinder;
163     @Mock
164     SubscriptionInfo mSubscriptionInfo;
165     @Mock
166     ApnContext mApnContext;
167     @Mock
168     DataConnection mDataConnection;
169     @Mock
170     Handler mHandler;
171     @Mock
172     NetworkPolicyManager mNetworkPolicyManager;
173 
174     private DcTracker mDct;
175     private DcTrackerTestHandler mDcTrackerTestHandler;
176 
177     private AlarmManager mAlarmManager;
178 
179     private PersistableBundle mBundle;
180 
181     private SubscriptionManager.OnSubscriptionsChangedListener mOnSubscriptionsChangedListener;
182 
183     private final ApnSettingContentProvider mApnSettingContentProvider =
184             new ApnSettingContentProvider();
185 
186     private Message mMessage;
187 
188     private CellularDataService mCellularDataService;
189 
addDataService()190     private void addDataService() {
191         mCellularDataService = new CellularDataService();
192         ServiceInfo serviceInfo = new ServiceInfo();
193         serviceInfo.packageName = "com.android.phone";
194         serviceInfo.permission = "android.permission.BIND_TELEPHONY_DATA_SERVICE";
195         IntentFilter filter = new IntentFilter();
196         mContextFixture.addService(
197                 DataService.SERVICE_INTERFACE,
198                 null,
199                 "com.android.phone",
200                 mCellularDataService.mBinder,
201                 serviceInfo,
202                 filter);
203     }
204 
205     private class DcTrackerTestHandler extends HandlerThread {
206 
DcTrackerTestHandler(String name)207         private DcTrackerTestHandler(String name) {
208             super(name);
209         }
210 
211         @Override
onLooperPrepared()212         public void onLooperPrepared() {
213             mDct = new DcTracker(mPhone, AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
214             setReady(true);
215         }
216     }
217 
218     private class ApnSettingContentProvider extends MockContentProvider {
219         public final String[] FAKE_APN_COLUMNS = new String[]{
220                 Telephony.Carriers._ID, Telephony.Carriers.NUMERIC,
221                 Telephony.Carriers.NAME, Telephony.Carriers.APN,
222                 Telephony.Carriers.PROXY, Telephony.Carriers.PORT,
223                 Telephony.Carriers.MMSC, Telephony.Carriers.MMSPROXY,
224                 Telephony.Carriers.MMSPORT, Telephony.Carriers.USER,
225                 Telephony.Carriers.PASSWORD, Telephony.Carriers.AUTH_TYPE,
226                 Telephony.Carriers.TYPE,
227                 Telephony.Carriers.PROTOCOL,
228                 Telephony.Carriers.ROAMING_PROTOCOL,
229                 Telephony.Carriers.CARRIER_ENABLED, Telephony.Carriers.BEARER,
230                 Telephony.Carriers.BEARER_BITMASK,
231                 Telephony.Carriers.PROFILE_ID,
232                 Telephony.Carriers.MODEM_PERSIST,
233                 Telephony.Carriers.MAX_CONNECTIONS,
234                 Telephony.Carriers.WAIT_TIME_RETRY,
235                 Telephony.Carriers.TIME_LIMIT_FOR_MAX_CONNECTIONS,
236                 Telephony.Carriers.MTU,
237                 Telephony.Carriers.MVNO_TYPE,
238                 Telephony.Carriers.MVNO_MATCH_DATA,
239                 Telephony.Carriers.NETWORK_TYPE_BITMASK,
240                 Telephony.Carriers.APN_SET_ID,
241                 Telephony.Carriers.CARRIER_ID,
242                 Telephony.Carriers.SKIP_464XLAT
243         };
244 
245         private int mPreferredApnSet = 0;
246 
247         private Object[] mPreferredApn = null;
248 
249         private String mFakeApn1Types = "default,supl";
250 
251         private String mFakeApn5Types = "dun";
252 
253         private int mFakeApn1Bitmask = NETWORK_TYPE_LTE_BITMASK;
254 
255         private int mRowIdOffset = 0;
256 
setFakeApn1Types(String apnTypes)257         public void setFakeApn1Types(String apnTypes) {
258             mFakeApn1Types = apnTypes;
259         }
260 
setFakeApn5Types(String apnTypes)261         public void setFakeApn5Types(String apnTypes) {
262             mFakeApn5Types = apnTypes;
263         }
264 
setFakeApn1NetworkTypeBitmask(int bitmask)265         public void setFakeApn1NetworkTypeBitmask(int bitmask) {
266             mFakeApn1Bitmask = bitmask;
267         }
268 
setRowIdOffset(int rowIdOffset)269         public void setRowIdOffset(int rowIdOffset) {
270             mRowIdOffset = rowIdOffset;
271         }
272 
setFakePreferredApn(Object[] fakeApn)273         public void setFakePreferredApn(Object[] fakeApn) {
274             mPreferredApn = fakeApn;
275         }
276 
getFakeApn1()277         public Object[] getFakeApn1() {
278             return new Object[]{
279                     2163 + mRowIdOffset,    // id
280                     FAKE_PLMN,              // numeric
281                     "sp-mode",              // name
282                     FAKE_APN1,              // apn
283                     "",                     // proxy
284                     "",                     // port
285                     "",                     // mmsc
286                     "",                     // mmsproxy
287                     "",                     // mmsport
288                     "",                     // user
289                     "",                     // password
290                     -1,                     // authtype
291                     mFakeApn1Types,         // types
292                     "IP",                   // protocol
293                     "IP",                   // roaming_protocol
294                     1,                      // carrier_enabled
295                     ServiceState.RIL_RADIO_TECHNOLOGY_LTE, // bearer
296                     0,                      // bearer_bitmask
297                     0,                      // profile_id
298                     1,                      // modem_cognitive
299                     0,                      // max_conns
300                     0,                      // wait_time
301                     0,                      // max_conns_time
302                     0,                      // mtu
303                     "",                     // mvno_type
304                     "",                     // mnvo_match_data
305                     mFakeApn1Bitmask,       // network_type_bitmask
306                     0,                      // apn_set_id
307                     -1,                     // carrier_id
308                     -1                      // skip_464xlat
309             };
310         }
311 
getFakeApn2()312         public Object[] getFakeApn2() {
313             return new Object[]{
314                     2164 + mRowIdOffset,    // id
315                     FAKE_PLMN,              // numeric
316                     "mopera U",             // name
317                     FAKE_APN2,              // apn
318                     "",                     // proxy
319                     "",                     // port
320                     "",                     // mmsc
321                     "",                     // mmsproxy
322                     "",                     // mmsport
323                     "",                     // user
324                     "",                     // password
325                     -1,                     // authtype
326                     "default,supl",         // types
327                     "IP",                   // protocol
328                     "IP",                   // roaming_protocol
329                     1,                      // carrier_enabled
330                     ServiceState.RIL_RADIO_TECHNOLOGY_LTE, // bearer,
331                     0,                      // bearer_bitmask
332                     0,                      // profile_id
333                     1,                      // modem_cognitive
334                     0,                      // max_conns
335                     0,                      // wait_time
336                     0,                      // max_conns_time
337                     0,                      // mtu
338                     "",                     // mvno_type
339                     "",                     // mnvo_match_data
340                     NETWORK_TYPE_LTE_BITMASK, // network_type_bitmask
341                     0,                      // apn_set_id
342                     -1,                     // carrier_id
343                     -1                      // skip_464xlat
344             };
345         }
346 
getFakeApn3()347         public Object[] getFakeApn3() {
348             return new Object[]{
349                     2165 + mRowIdOffset,    // id
350                     FAKE_PLMN,              // numeric
351                     "b-mobile for Nexus",   // name
352                     FAKE_APN3,              // apn
353                     "",                     // proxy
354                     "",                     // port
355                     "",                     // mmsc
356                     "",                     // mmsproxy
357                     "",                     // mmsport
358                     "",                     // user
359                     "",                     // password
360                     -1,                     // authtype
361                     "ims",                  // types
362                     "IP",                   // protocol
363                     "IP",                   // roaming_protocol
364                     1,                      // carrier_enabled
365                     0,                      // bearer
366                     0,                      // bearer_bitmask
367                     0,                      // profile_id
368                     1,                      // modem_cognitive
369                     0,                      // max_conns
370                     0,                      // wait_time
371                     0,                      // max_conns_time
372                     0,                      // mtu
373                     "",                     // mvno_type
374                     "",                     // mnvo_match_data
375                     0,                      // network_type_bitmask
376                     0,                      // apn_set_id
377                     -1,                     // carrier_id
378                     -1                      // skip_464xlat
379             };
380         }
381 
getFakeApn4()382         public Object[] getFakeApn4() {
383             return new Object[]{
384                     2166 + mRowIdOffset,    // id
385                     FAKE_PLMN,              // numeric
386                     "sp-mode ehrpd",        // name
387                     FAKE_APN4,              // apn
388                     "",                     // proxy
389                     "",                     // port
390                     "",                     // mmsc
391                     "",                     // mmsproxy
392                     "",                     // mmsport
393                     "",                     // user
394                     "",                     // password
395                     -1,                     // authtype
396                     "default,supl",         // types
397                     "IP",                   // protocol
398                     "IP",                   // roaming_protocol
399                     1,                      // carrier_enabled
400                     ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD, // bearer
401                     0,                      // bearer_bitmask
402                     0,                      // profile_id
403                     1,                      // modem_cognitive
404                     0,                      // max_conns
405                     0,                      // wait_time
406                     0,                      // max_conns_time
407                     0,                      // mtu
408                     "",                     // mvno_type
409                     "",                     // mnvo_match_data
410                     NETWORK_TYPE_EHRPD_BITMASK, // network_type_bitmask
411                     0,                      // apn_set_id
412                     -1,                     // carrier_id
413                     -1                      // skip_464xlat
414             };
415         }
416 
getFakeApn5()417         public Object[] getFakeApn5() {
418             return new Object[]{
419                     2167 + mRowIdOffset,    // id
420                     FAKE_PLMN,              // numeric
421                     "b-mobile for Nexus",   // name
422                     FAKE_APN5,              // apn
423                     "",                     // proxy
424                     "",                     // port
425                     "",                     // mmsc
426                     "",                     // mmsproxy
427                     "",                     // mmsport
428                     "",                     // user
429                     "",                     // password
430                     -1,                     // authtype
431                     mFakeApn5Types,         // types
432                     "IP",                   // protocol
433                     "IP",                   // roaming_protocol
434                     1,                      // carrier_enabled
435                     0,                      // bearer
436                     0,                      // bearer_bitmask
437                     0,                      // profile_id
438                     1,                      // modem_cognitive
439                     0,                      // max_conns
440                     0,                      // wait_time
441                     0,                      // max_conns_time
442                     0,                      // mtu
443                     "",                     // mvno_type
444                     "",                     // mnvo_match_data
445                     0,                      // network_type_bitmask
446                     0,                      // apn_set_id
447                     -1,                     // carrier_id
448                     -1                      // skip_464xlat
449             };
450         }
451 
getFakeApn6()452         public Object[] getFakeApn6() {
453             return new Object[]{
454                     2168 + mRowIdOffset,    // id
455                     FAKE_PLMN,              // numeric
456                     "sp-mode",              // name
457                     FAKE_APN6,              // apn
458                     "",                     // proxy
459                     "",                     // port
460                     "",                     // mmsc
461                     "",                     // mmsproxy
462                     "",                     // mmsport
463                     "",                     // user
464                     "",                     // password
465                     -1,                     // authtype
466                     "mms,xcap",             // types
467                     "IP",                   // protocol
468                     "IP",                   // roaming_protocol
469                     1,                      // carrier_enabled
470                     ServiceState.RIL_RADIO_TECHNOLOGY_LTE, // bearer
471                     0,                      // bearer_bitmask
472                     0,                      // profile_id
473                     1,                      // modem_cognitive
474                     0,                      // max_conns
475                     0,                      // wait_time
476                     0,                      // max_conns_time
477                     0,                      // mtu
478                     "",                     // mvno_type
479                     "",                     // mnvo_match_data
480                     NETWORK_TYPE_LTE_BITMASK, // network_type_bitmask
481                     0,                      // apn_set_id
482                     -1,                     // carrier_id
483                     -1                      // skip_464xlat
484             };
485         }
486 
getFakeApn7()487         public Object[] getFakeApn7() {
488             return new Object[]{
489                     2169 + mRowIdOffset,    // id
490                     FAKE_PLMN,              // numeric
491                     "sp-mode",              // name
492                     FAKE_APN7,              // apn
493                     "",                     // proxy
494                     "",                     // port
495                     "",                     // mmsc
496                     "",                     // mmsproxy
497                     "",                     // mmsport
498                     "",                     // user
499                     "",                     // password
500                     -1,                     // authtype
501                     "default",              // types
502                     "IP",                   // protocol
503                     "IP",                   // roaming_protocol
504                     1,                      // carrier_enabled
505                     ServiceState.RIL_RADIO_TECHNOLOGY_LTE, // bearer
506                     0,                      // bearer_bitmask
507                     0,                      // profile_id
508                     1,                      // modem_cognitive
509                     0,                      // max_conns
510                     0,                      // wait_time
511                     0,                      // max_conns_time
512                     0,                      // mtu
513                     "",                     // mvno_type
514                     "",                     // mnvo_match_data
515                     NETWORK_TYPE_LTE_BITMASK,  // network_type_bitmask
516                     1,                      // apn_set_id
517                     -1,                     // carrier_id
518                     -1                      // skip_464xlat
519             };
520         }
521 
getFakeApn8()522         public Object[] getFakeApn8() {
523             return new Object[]{
524                     2170 + mRowIdOffset,    // id
525                     FAKE_PLMN,              // numeric
526                     "IMS",                  // name
527                     FAKE_APN8,              // apn
528                     "",                     // proxy
529                     "",                     // port
530                     "",                     // mmsc
531                     "",                     // mmsproxy
532                     "",                     // mmsport
533                     "",                     // user
534                     "",                     // password
535                     -1,                     // authtype
536                     "ims",                  // types
537                     "IP",                   // protocol
538                     "IP",                   // roaming_protocol
539                     1,                      // carrier_enabled
540                     ServiceState.RIL_RADIO_TECHNOLOGY_LTE, // bearer
541                     0,                      // bearer_bitmask
542                     0,                      // profile_id
543                     1,                      // modem_cognitive
544                     0,                      // max_conns
545                     0,                      // wait_time
546                     0,                      // max_conns_time
547                     0,                      // mtu
548                     "",                     // mvno_type
549                     "",                     // mnvo_match_data
550                     NETWORK_TYPE_LTE_BITMASK,  // network_type_bitmask
551                     -1,                      // apn_set_id
552                     -1,                     // carrier_id
553                     -1                      // skip_464xlat
554             };
555         }
556 
getFakeApn9()557         public Object[] getFakeApn9() {
558             return new Object[]{
559                     2171 + mRowIdOffset,    // id
560                     FAKE_PLMN,              // numeric
561                     "sp-mode nr",           // name
562                     FAKE_APN9,              // apn
563                     "",                     // proxy
564                     "",                     // port
565                     "",                     // mmsc
566                     "",                     // mmsproxy
567                     "",                     // mmsport
568                     "",                     // user
569                     "",                     // password
570                     -1,                     // authtype
571                     "default,enterprise",   // types
572                     "IP",                   // protocol
573                     "IP",                   // roaming_protocol
574                     1,                      // carrier_enabled
575                     ServiceState.RIL_RADIO_TECHNOLOGY_LTE, // bearer
576                     0,                      // bearer_bitmask
577                     0,                      // profile_id
578                     1,                      // modem_cognitive
579                     0,                      // max_conns
580                     0,                      // wait_time
581                     0,                      // max_conns_time
582                     0,                      // mtu
583                     "",                     // mvno_type
584                     "",                     // mnvo_match_data
585                     NETWORK_TYPE_NR_BITMASK, // network_type_bitmask
586                     0,                      // apn_set_id
587                     -1,                     // carrier_id
588                     -1                      // skip_464xlat
589             };
590         }
591 
592         @Override
query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)593         public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
594                             String sortOrder) {
595             logd("ApnSettingContentProvider: query");
596             logd("   uri = " + uri);
597             logd("   projection = " + Arrays.toString(projection));
598             logd("   selection = " + selection);
599             logd("   selectionArgs = " + Arrays.toString(selectionArgs));
600             logd("   sortOrder = " + sortOrder);
601 
602             if (uri.compareTo(Telephony.Carriers.CONTENT_URI) == 0
603                     || uri.toString().startsWith(Uri.withAppendedPath(
604                             Telephony.Carriers.CONTENT_URI, "filtered").toString())
605                     || uri.toString().startsWith(Uri.withAppendedPath(
606                             Telephony.Carriers.SIM_APN_URI, "filtered").toString())) {
607                 if (projection == null) {
608 
609                     logd("Query '" + FAKE_PLMN + "' APN settings");
610                     MatrixCursor mc = new MatrixCursor(FAKE_APN_COLUMNS);
611                     mc.addRow(getFakeApn1());
612                     mc.addRow(getFakeApn2());
613                     mc.addRow(getFakeApn3());
614                     mc.addRow(getFakeApn4());
615                     mc.addRow(getFakeApn5());
616                     mc.addRow(getFakeApn6());
617                     mc.addRow(getFakeApn7());
618                     mc.addRow(getFakeApn8());
619                     mc.addRow(getFakeApn9());
620 
621                     return mc;
622                 }
623             } else if (isPathPrefixMatch(uri,
624                     Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "preferapnset"))) {
625                 MatrixCursor mc = new MatrixCursor(
626                         new String[]{Telephony.Carriers.APN_SET_ID});
627                 // apn_set_id is the only field used with this URL
628                 mc.addRow(new Object[]{ mPreferredApnSet });
629                 mc.addRow(new Object[]{ 0 });
630                 return mc;
631             } else if (isPathPrefixMatch(uri,
632                     Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "preferapn_no_update"))) {
633                 if (mPreferredApn == null) {
634                     return null;
635                 } else {
636                     MatrixCursor mc = new MatrixCursor(FAKE_APN_COLUMNS);
637                     mc.addRow(mPreferredApn);
638                     return mc;
639                 }
640             }
641 
642             return null;
643         }
644 
645         @Override
update(Uri url, ContentValues values, String where, String[] whereArgs)646         public int update(Uri url, ContentValues values, String where, String[] whereArgs) {
647             mPreferredApnSet = values.getAsInteger(Telephony.Carriers.APN_SET_ID);
648             return 1;
649         }
650 
651         @Override
delete(Uri uri, String selection, String[] selectionArgs)652         public int delete(Uri uri, String selection, String[] selectionArgs) {
653             return 0;
654         }
655 
656         @Override
insert(Uri uri, ContentValues values)657         public Uri insert(Uri uri, ContentValues values) {
658             return null;
659         }
660     }
661 
662     @Before
setUp()663     public void setUp() throws Exception {
664         logd("DcTrackerTest +Setup!");
665         super.setUp(getClass().getSimpleName());
666 
667         doReturn("fake.action_detached").when(mPhone).getActionDetached();
668         doReturn("fake.action_attached").when(mPhone).getActionAttached();
669         doReturn(ServiceState.RIL_RADIO_TECHNOLOGY_LTE).when(mServiceState)
670                 .getRilDataRadioTechnology();
671 
672         mContextFixture.putStringArrayResource(com.android.internal.R.array
673                 .config_mobile_tcp_buffers, new String[]{
674                     "umts:131072,262144,1452032,4096,16384,399360",
675                     "hspa:131072,262144,2441216,4096,16384,399360",
676                     "hsupa:131072,262144,2441216,4096,16384,399360",
677                     "hsdpa:131072,262144,2441216,4096,16384,399360",
678                     "hspap:131072,262144,2441216,4096,16384,399360",
679                     "edge:16384,32768,131072,4096,16384,65536",
680                     "gprs:4096,8192,24576,4096,8192,24576",
681                     "1xrtt:16384,32768,131070,4096,16384,102400",
682                     "evdo:131072,262144,1048576,4096,16384,524288",
683                     "lte:524288,1048576,8388608,262144,524288,4194304"});
684 
685         mContextFixture.putResource(R.string.config_wwan_data_service_package,
686                 "com.android.phone");
687 
688         ((MockContentResolver) mContext.getContentResolver()).addProvider(
689                 Telephony.Carriers.CONTENT_URI.getAuthority(), mApnSettingContentProvider);
690         Settings.Global.putInt(mContext.getContentResolver(),
691                 Settings.Global.DATA_STALL_RECOVERY_ON_BAD_NETWORK, 0);
692 
693         doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WWAN).when(mTransportManager)
694                 .getPreferredTransport(anyInt());
695         doReturn(PhoneConstants.State.IDLE).when(mCT).getState();
696         doReturn(true).when(mSST).getDesiredPowerState();
697         doReturn(true).when(mSST).getPowerStateFromCarrier();
698         doAnswer(
699                 new Answer<Void>() {
700                     @Override
701                     public Void answer(InvocationOnMock invocation) throws Throwable {
702                         mOnSubscriptionsChangedListener =
703                                 (SubscriptionManager.OnSubscriptionsChangedListener)
704                                         invocation.getArguments()[0];
705                         return null;
706                     }
707                 }
708         ).when(mSubscriptionManager).addOnSubscriptionsChangedListener(any());
709         doReturn(mSubscriptionInfo).when(mSubscriptionManager).getActiveSubscriptionInfo(anyInt());
710         doReturn(mNetworkPolicyManager).when(mContext)
711                 .getSystemService(Context.NETWORK_POLICY_SERVICE);
712         doReturn(1).when(mIsub).getDefaultDataSubId();
713         doReturn(mIsub).when(mBinder).queryLocalInterface(anyString());
714         mServiceManagerMockedServices.put("isub", mBinder);
715 
716         mContextFixture.putStringArrayResource(
717                 com.android.internal.R.array.config_cell_retries_per_error_code,
718                 new String[]{"36,2"});
719 
720         mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
721         mBundle = mContextFixture.getCarrierConfigBundle();
722 
723         mBundle.putBoolean(CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL, true);
724 
725         mSimulatedCommands.setDataCallResult(true, createSetupDataCallResult());
726         addDataService();
727 
728         mDcTrackerTestHandler = new DcTrackerTestHandler(getClass().getSimpleName());
729         mDcTrackerTestHandler.start();
730         waitUntilReady();
731 
732         Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
733         intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, mPhone.getPhoneId());
734         intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, mPhone.getSubId());
735         mContext.sendBroadcast(intent);
736 
737         waitForMs(600);
738         logd("DcTrackerTest -Setup!");
739     }
740 
741     @After
tearDown()742     public void tearDown() throws Exception {
743         logd("DcTrackerTest -tearDown");
744         mDct.removeCallbacksAndMessages(null);
745         mDct.stopHandlerThread();
746         mDct = null;
747         mDcTrackerTestHandler.quit();
748         mDcTrackerTestHandler.join();
749         mCellularDataService.onDestroy();
750         waitForMs(100);
751         super.tearDown();
752     }
753 
754     // Create a successful data response
createSetupDataCallResult()755     private static SetupDataCallResult createSetupDataCallResult() {
756         SetupDataCallResult result = new SetupDataCallResult();
757         result.status = 0;
758         result.suggestedRetryTime = -1;
759         result.cid = 1;
760         result.active = 2;
761         result.type = "IP";
762         result.ifname = FAKE_IFNAME;
763         result.addresses = FAKE_ADDRESS;
764         result.dnses = FAKE_DNS;
765         result.gateways = FAKE_GATEWAY;
766         result.pcscf = FAKE_PCSCF_ADDRESS;
767         result.mtu = 1440;
768         return result;
769     }
770 
verifyDataProfile(DataProfile dp, String apn, int profileId, int supportedApnTypesBitmap, int type, int bearerBitmask)771     private void verifyDataProfile(DataProfile dp, String apn, int profileId,
772                                    int supportedApnTypesBitmap, int type, int bearerBitmask) {
773         assertEquals(profileId, dp.getProfileId());
774         assertEquals(apn, dp.getApn());
775         assertEquals(ApnSetting.PROTOCOL_IP, dp.getProtocolType());
776         assertEquals(0, dp.getAuthType());
777         assertEquals("", dp.getUserName());
778         assertEquals("", dp.getPassword());
779         assertEquals(type, dp.getType());
780         assertEquals(0, dp.getWaitTime());
781         assertTrue(dp.isEnabled());
782         assertEquals(supportedApnTypesBitmap, dp.getSupportedApnTypesBitmask());
783         assertEquals(ApnSetting.PROTOCOL_IP, dp.getRoamingProtocolType());
784         assertEquals(bearerBitmask, dp.getBearerBitmask());
785         assertEquals(0, dp.getMtu());
786         assertTrue(dp.isPersistent());
787         assertFalse(dp.isPreferred());
788     }
789 
verifyDataConnected(final String apnSetting)790     private void verifyDataConnected(final String apnSetting) {
791         verify(mAlarmManager, times(1)).set(eq(AlarmManager.ELAPSED_REALTIME), anyLong(),
792                 any(PendingIntent.class));
793 
794         assertEquals(apnSetting, mDct.getActiveApnString(ApnSetting.TYPE_DEFAULT_STRING));
795         assertArrayEquals(new String[]{ApnSetting.TYPE_DEFAULT_STRING}, mDct.getActiveApnTypes());
796 
797         assertTrue(mDct.isAnyDataConnected());
798         assertEquals(DctConstants.State.CONNECTED, mDct.getState(ApnSetting.TYPE_DEFAULT_STRING));
799 
800         LinkProperties linkProperties = mDct.getLinkProperties(ApnSetting.TYPE_DEFAULT_STRING);
801         assertEquals(FAKE_IFNAME, linkProperties.getInterfaceName());
802         assertEquals(1, linkProperties.getAddresses().size());
803         assertEquals(FAKE_ADDRESS, linkProperties.getAddresses().get(0).getHostAddress());
804         assertEquals(1, linkProperties.getDnsServers().size());
805         assertEquals(FAKE_DNS, linkProperties.getDnsServers().get(0).getHostAddress());
806         assertEquals(FAKE_GATEWAY, linkProperties.getRoutes().get(0).getGateway().getHostAddress());
807     }
808 
isHandoverPending(int apnType)809     private boolean isHandoverPending(int apnType) {
810         try {
811             Method method = DcTracker.class.getDeclaredMethod("isHandoverPending",
812                     int.class);
813             method.setAccessible(true);
814             return (boolean) method.invoke(mDct, apnType);
815         } catch (Exception e) {
816             fail(e.toString());
817             return false;
818         }
819     }
820 
addHandoverCompleteMsg(Message onCompleteMsg, @Annotation.ApnType int apnType)821     private void addHandoverCompleteMsg(Message onCompleteMsg,
822             @Annotation.ApnType int apnType) {
823         try {
824             Method method = DcTracker.class.getDeclaredMethod("addHandoverCompleteMsg",
825                     Message.class, int.class);
826             method.setAccessible(true);
827             method.invoke(mDct, onCompleteMsg, apnType);
828         } catch (Exception e) {
829             fail(e.toString());
830         }
831     }
832 
sendInitializationEvents()833     private void sendInitializationEvents() {
834         sendCarrierConfigChanged("");
835 
836         sendSimStateUpdated("");
837 
838         sendEventDataConnectionAttached("");
839 
840         waitForMs(200);
841     }
842 
sendCarrierConfigChanged(String messagePrefix)843     private void sendCarrierConfigChanged(String messagePrefix) {
844         logd(messagePrefix + "Sending EVENT_CARRIER_CONFIG_CHANGED");
845         mDct.sendEmptyMessage(DctConstants.EVENT_CARRIER_CONFIG_CHANGED);
846         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
847     }
848 
sendSimStateUpdated(String messagePrefix)849     private void sendSimStateUpdated(String messagePrefix) {
850         logd(messagePrefix + "Sending EVENT_SIM_STATE_UPDATED");
851         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_SIM_STATE_UPDATED,
852                 TelephonyManager.SIM_STATE_LOADED, 0));
853         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
854     }
855 
sendEventDataConnectionAttached(String messagePrefix)856     private void sendEventDataConnectionAttached(String messagePrefix) {
857         logd(messagePrefix + "Sending EVENT_DATA_CONNECTION_ATTACHED");
858         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
859         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
860     }
861 
862     // Test the unmetered APN setup when data is disabled.
863     @Test
864     @SmallTest
testTrySetupDataUnmeteredDefaultNotSelected()865     public void testTrySetupDataUnmeteredDefaultNotSelected() throws Exception {
866         initApns(ApnSetting.TYPE_XCAP_STRING, new String[]{ApnSetting.TYPE_XCAP_STRING});
867         doReturn(SubscriptionManager.INVALID_SUBSCRIPTION_ID).when(mIsub).getDefaultDataSubId();
868 
869         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
870                 new String[]{ApnSetting.TYPE_DEFAULT_STRING});
871 
872         sendInitializationEvents();
873 
874         mDct.enableApn(ApnSetting.TYPE_XCAP, DcTracker.REQUEST_TYPE_NORMAL, null);
875         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
876 
877         // Data connection is running on a different thread. Have to wait.
878         waitForMs(200);
879         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
880                 eq(AccessNetworkType.EUTRAN), any(DataProfile.class),
881                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
882                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
883     }
884 
885     // Test the normal data call setup scenario.
886     @Test
887     @MediumTest
testDataSetup()888     public void testDataSetup() throws Exception {
889         DataConnectionReasons dataConnectionReasons = new DataConnectionReasons();
890         boolean allowed = mDct.isDataAllowed(dataConnectionReasons);
891         assertFalse(dataConnectionReasons.toString(), allowed);
892 
893         logd("Sending EVENT_ENABLE_APN");
894         // APN id 0 is APN_TYPE_DEFAULT
895         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
896         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
897 
898         sendInitializationEvents();
899 
900         dataConnectionReasons = new DataConnectionReasons();
901         allowed = mDct.isDataAllowed(dataConnectionReasons);
902         assertTrue(dataConnectionReasons.toString(), allowed);
903 
904         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
905         // Verify if RIL command was sent properly.
906         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
907                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
908                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
909                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
910         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
911 
912         verifyDataConnected(FAKE_APN1);
913     }
914 
915     // Test the scenario where the first data call setup is failed, and then retry the setup later.
916     @Test
917     @MediumTest
testDataRetry()918     public void testDataRetry() throws Exception {
919         AsyncResult ar = new AsyncResult(null,
920                 new Pair<>(true, DataEnabledSettings.REASON_USER_DATA_ENABLED), null);
921         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_ENABLED_CHANGED, ar));
922         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
923 
924         // LOST_CONNECTION(0x10004) is a non-permanent failure, so we'll retry data setup later.
925         SetupDataCallResult result = createSetupDataCallResult();
926         result.status = 0x10004;
927 
928         // Simulate RIL fails the data call setup
929         mSimulatedCommands.setDataCallResult(true, result);
930 
931         DataConnectionReasons dataConnectionReasons = new DataConnectionReasons();
932         boolean allowed = mDct.isDataAllowed(dataConnectionReasons);
933         assertFalse(dataConnectionReasons.toString(), allowed);
934 
935         logd("Sending EVENT_ENABLE_APN");
936         // APN id 0 is APN_TYPE_DEFAULT
937         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
938         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
939 
940         sendInitializationEvents();
941 
942         dataConnectionReasons = new DataConnectionReasons();
943         allowed = mDct.isDataAllowed(dataConnectionReasons);
944         assertTrue(dataConnectionReasons.toString(), allowed);
945 
946         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
947         // Verify if RIL command was sent properly.
948         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
949                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
950                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
951                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
952         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
953 
954         // This time we'll let RIL command succeed.
955         mSimulatedCommands.setDataCallResult(true, createSetupDataCallResult());
956 
957         //Send event for reconnecting data
958         initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
959         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_RECONNECT,
960                         mPhone.getPhoneId(), DcTracker.REQUEST_TYPE_NORMAL, mApnContext));
961         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
962 
963         // Data connection is running on a different thread. Have to wait.
964         waitForMs(200);
965         dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
966         // Verify if RIL command was sent properly.
967         verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
968                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
969                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
970                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
971         verifyDataProfile(dpCaptor.getValue(), FAKE_APN2, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
972 
973         // Verify connected with APN2 setting.
974         verifyDataConnected(FAKE_APN2);
975     }
976 
977     @Test
978     @MediumTest
979     @Ignore
980     @FlakyTest
testUserDisableData()981     public void testUserDisableData() {
982         //step 1: setup two DataCalls one for Metered: default, another one for Non-metered: IMS
983         //set Default and MMS to be metered in the CarrierConfigManager
984         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
985                 new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
986         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
987         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
988 
989         sendInitializationEvents();
990 
991         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
992         verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
993                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
994                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
995                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
996         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 5, 1, NETWORK_TYPE_LTE_BITMASK);
997 
998         logd("Sending DATA_DISABLED_CMD");
999         doReturn(false).when(mDataEnabledSettings).isDataEnabled();
1000         doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
1001         AsyncResult ar = new AsyncResult(null,
1002                 new Pair<>(false, DataEnabledSettings.REASON_USER_DATA_ENABLED), null);
1003         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_ENABLED_CHANGED, ar));
1004         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1005 
1006         // Data connection is running on a different thread. Have to wait.
1007         waitForMs(200);
1008         // expected tear down all metered DataConnections
1009         verify(mSimulatedCommandsVerifier, times(1)).deactivateDataCall(
1010                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
1011                 any(Message.class));
1012         assertTrue(mDct.isAnyDataConnected());
1013         assertEquals(DctConstants.State.IDLE, mDct.getState(ApnSetting.TYPE_DEFAULT_STRING));
1014         assertEquals(DctConstants.State.CONNECTED, mDct.getState(ApnSetting.TYPE_IMS_STRING));
1015     }
1016 
1017     @Test
1018     @MediumTest
testTrySetupDataMmsAllowedDataDisabled()1019     public void testTrySetupDataMmsAllowedDataDisabled() {
1020         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1021                 new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
1022         mDct.enableApn(ApnSetting.TYPE_MMS, DcTracker.REQUEST_TYPE_NORMAL, null);
1023         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1024 
1025         sendInitializationEvents();
1026 
1027         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1028         verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
1029                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1030                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1031                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
1032 
1033         List<DataProfile> dataProfiles = dpCaptor.getAllValues();
1034         assertEquals(2, dataProfiles.size());
1035 
1036         //Verify FAKE_APN1
1037         Optional<DataProfile> fakeApn1 = dataProfiles.stream()
1038                 .filter(dp -> dp.getApn().equals(FAKE_APN1))
1039                 .findFirst();
1040         assertTrue(fakeApn1.isPresent());
1041         verifyDataProfile(fakeApn1.get(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
1042 
1043         //Verify FAKE_APN6
1044         Optional<DataProfile> fakeApn6 = dataProfiles.stream()
1045                 .filter(dp -> dp.getApn().equals(FAKE_APN6))
1046                 .findFirst();
1047         assertTrue(fakeApn6.isPresent());
1048         verifyDataProfile(fakeApn6.get(), FAKE_APN6, 0, ApnSetting.TYPE_MMS | ApnSetting.TYPE_XCAP,
1049                 1, NETWORK_TYPE_LTE_BITMASK);
1050 
1051         logd("Sending DATA_DISABLED_CMD for default data");
1052         doReturn(false).when(mDataEnabledSettings).isDataEnabled();
1053         doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
1054         mDct.obtainMessage(DctConstants.EVENT_DATA_ENABLED_OVERRIDE_RULES_CHANGED).sendToTarget();
1055         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1056 
1057         // Data connection is running on a different thread. Have to wait.
1058         waitForMs(200);
1059         // expected tear down all metered DataConnections
1060         verify(mSimulatedCommandsVerifier, times(2)).deactivateDataCall(
1061                 anyInt(), eq(DataService.REQUEST_REASON_NORMAL), any(Message.class));
1062         assertEquals(DctConstants.State.IDLE, mDct.getState(ApnSetting.TYPE_DEFAULT_STRING));
1063         assertEquals(DctConstants.State.IDLE, mDct.getState(ApnSetting.TYPE_MMS_STRING));
1064 
1065         clearInvocations(mSimulatedCommandsVerifier);
1066         doReturn(true).when(mDataEnabledSettings).isDataEnabled(ApnSetting.TYPE_MMS);
1067         mDct.obtainMessage(DctConstants.EVENT_DATA_ENABLED_OVERRIDE_RULES_CHANGED).sendToTarget();
1068         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1069 
1070         // Data connection is running on a different thread. Have to wait.
1071         waitForMs(200);
1072         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
1073                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1074                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1075                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
1076         assertEquals(DctConstants.State.IDLE, mDct.getState(ApnSetting.TYPE_DEFAULT_STRING));
1077         assertEquals(DctConstants.State.CONNECTED, mDct.getState(ApnSetting.TYPE_MMS_STRING));
1078     }
1079 
1080     @Test
1081     @MediumTest
testTrySetupDataMmsAlwaysAllowedDataDisabled()1082     public void testTrySetupDataMmsAlwaysAllowedDataDisabled() {
1083         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1084                 new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
1085         mApnSettingContentProvider.setFakeApn1Types("mms,xcap,default");
1086         mDct.enableApn(ApnSetting.TYPE_MMS, DcTracker.REQUEST_TYPE_NORMAL, null);
1087         sendInitializationEvents();
1088 
1089         // Verify MMS was set up and is connected
1090         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1091         verify(mSimulatedCommandsVerifier).setupDataCall(
1092                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1093                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1094                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
1095         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0,
1096                 ApnSetting.TYPE_MMS | ApnSetting.TYPE_XCAP | ApnSetting.TYPE_DEFAULT,
1097                 1, NETWORK_TYPE_LTE_BITMASK);
1098         assertEquals(DctConstants.State.CONNECTED, mDct.getState(ApnSetting.TYPE_MMS_STRING));
1099 
1100         // Verify DC has all capabilities specified in fakeApn1Types
1101         Map<Integer, ApnContext> apnContexts = mDct.getApnContexts().stream().collect(
1102                 Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
1103         assertTrue(apnContexts.get(ApnSetting.TYPE_MMS).getDataConnection()
1104                 .getNetworkCapabilities().hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS));
1105         assertTrue(apnContexts.get(ApnSetting.TYPE_MMS).getDataConnection()
1106                 .getNetworkCapabilities().hasCapability(NetworkCapabilities.NET_CAPABILITY_XCAP));
1107         assertTrue(apnContexts.get(ApnSetting.TYPE_MMS).getDataConnection()
1108                 .getNetworkCapabilities().hasCapability(
1109                         NetworkCapabilities.NET_CAPABILITY_INTERNET));
1110 
1111         // Disable mobile data
1112         doReturn(false).when(mDataEnabledSettings).isDataEnabled();
1113         doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
1114         doReturn(false).when(mDataEnabledSettings).isMmsAlwaysAllowed();
1115         mDct.obtainMessage(DctConstants.EVENT_DATA_ENABLED_OVERRIDE_RULES_CHANGED).sendToTarget();
1116         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1117 
1118         // Expected tear down all metered DataConnections
1119         waitForMs(200);
1120         verify(mSimulatedCommandsVerifier).deactivateDataCall(
1121                 anyInt(), eq(DataService.REQUEST_REASON_NORMAL), any(Message.class));
1122         assertEquals(DctConstants.State.IDLE, mDct.getState(ApnSetting.TYPE_MMS_STRING));
1123 
1124         // Allow MMS unconditionally
1125         clearInvocations(mSimulatedCommandsVerifier);
1126         doReturn(true).when(mDataEnabledSettings).isMmsAlwaysAllowed();
1127         doReturn(true).when(mDataEnabledSettings).isDataEnabled(ApnSetting.TYPE_MMS);
1128         mDct.obtainMessage(DctConstants.EVENT_DATA_ENABLED_OVERRIDE_RULES_CHANGED).sendToTarget();
1129         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1130 
1131         // Verify MMS was set up and is connected
1132         waitForMs(200);
1133         verify(mSimulatedCommandsVerifier).setupDataCall(
1134                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1135                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1136                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
1137         assertEquals(DctConstants.State.CONNECTED, mDct.getState(ApnSetting.TYPE_MMS_STRING));
1138 
1139         // Ensure MMS data connection has the MMS capability only.
1140         apnContexts = mDct.getApnContexts().stream().collect(
1141                 Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
1142         assertTrue(apnContexts.get(ApnSetting.TYPE_MMS).getDataConnection()
1143                 .getNetworkCapabilities().hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS));
1144         assertFalse(apnContexts.get(ApnSetting.TYPE_MMS).getDataConnection()
1145                 .getNetworkCapabilities().hasCapability(NetworkCapabilities.NET_CAPABILITY_XCAP));
1146         assertFalse(apnContexts.get(ApnSetting.TYPE_MMS).getDataConnection()
1147                 .getNetworkCapabilities().hasCapability(
1148                         NetworkCapabilities.NET_CAPABILITY_INTERNET));
1149     }
1150 
1151     @Test
1152     @MediumTest
testUserDisableRoaming()1153     public void testUserDisableRoaming() {
1154         //step 1: setup two DataCalls one for Metered: default, another one for Non-metered: IMS
1155         //step 2: set roaming disabled, data is enabled
1156         //step 3: under roaming service
1157         //step 4: only tear down metered data connections.
1158 
1159         //set Default and MMS to be metered in the CarrierConfigManager
1160         boolean roamingEnabled = mDct.getDataRoamingEnabled();
1161 
1162         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_ROAMING_APN_TYPES_STRINGS,
1163                 new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
1164 
1165         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
1166         waitForHandlerAction(mDct, 1000);
1167         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1168         waitForHandlerAction(mDct, 1000);
1169 
1170         sendInitializationEvents();
1171 
1172         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1173         verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
1174                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1175                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1176                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
1177         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
1178 
1179         //user is in roaming
1180         doReturn(true).when(mServiceState).getDataRoaming();
1181         logd("Sending DISABLE_ROAMING_CMD");
1182         mDct.setDataRoamingEnabledByUser(false);
1183         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_ROAMING_ON));
1184         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1185 
1186         // Data connection is running on a different thread. Have to wait.
1187         waitForMs(200);
1188         // expected tear down all metered DataConnections
1189         verify(mSimulatedCommandsVerifier, times(1)).deactivateDataCall(
1190                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
1191                 any(Message.class));
1192         assertTrue(mDct.isAnyDataConnected());
1193         assertEquals(DctConstants.State.IDLE, mDct.getState(ApnSetting.TYPE_DEFAULT_STRING));
1194         assertEquals(DctConstants.State.CONNECTED, mDct.getState(ApnSetting.TYPE_IMS_STRING));
1195 
1196         // reset roaming settings / data enabled settings at end of this test
1197         mDct.setDataRoamingEnabledByUser(roamingEnabled);
1198         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1199     }
1200 
1201     @Test
1202     @MediumTest
testDataCallOnUserDisableRoaming()1203     public void testDataCallOnUserDisableRoaming() {
1204         //step 1: mock under roaming service and user disabled roaming from settings.
1205         //step 2: user toggled data settings on
1206         //step 3: only non-metered data call is established
1207 
1208         boolean roamingEnabled = mDct.getDataRoamingEnabled();
1209         doReturn(true).when(mServiceState).getDataRoaming();
1210 
1211         //set Default and MMS to be metered in the CarrierConfigManager
1212         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_ROAMING_APN_TYPES_STRINGS,
1213                 new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
1214         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
1215         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1216 
1217         logd("Sending DISABLE_ROAMING_CMD");
1218         mDct.setDataRoamingEnabledByUser(false);
1219 
1220         sendInitializationEvents();
1221 
1222         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1223 
1224         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
1225                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1226                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1227                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
1228         verifyDataProfile(dpCaptor.getValue(), FAKE_APN3, 2, 64, 0, 0);
1229 
1230         assertTrue(mDct.isAnyDataConnected());
1231         assertEquals(DctConstants.State.IDLE, mDct.getState(ApnSetting.TYPE_DEFAULT_STRING));
1232         assertEquals(DctConstants.State.CONNECTED, mDct.getState(ApnSetting.TYPE_IMS_STRING));
1233 
1234         // reset roaming settings / data enabled settings at end of this test
1235         mDct.setDataRoamingEnabledByUser(roamingEnabled);
1236         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1237     }
1238 
1239     // Test the default data switch scenario.
1240     @FlakyTest /* flakes 1.57% of the time */
1241     @Test
1242     @MediumTest
testDDSResetAutoAttach()1243     public void testDDSResetAutoAttach() throws Exception {
1244         mContextFixture.putBooleanResource(
1245                 com.android.internal.R.bool.config_auto_attach_data_on_creation, true);
1246         testDataSetup();
1247         assertTrue(mDct.shouldAutoAttach());
1248         mDct.sendEmptyMessage(DctConstants.EVENT_CARRIER_CONFIG_CHANGED);
1249         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1250         // The auto attach flag should be reset after update
1251         assertFalse(mDct.shouldAutoAttach());
1252     }
1253 
1254     // Test for API carrierActionSetMeteredApnsEnabled.
1255     @FlakyTest
1256     @Ignore
1257     @Test
1258     @MediumTest
testCarrierActionSetMeteredApnsEnabled()1259     public void testCarrierActionSetMeteredApnsEnabled() {
1260         //step 1: setup two DataCalls one for Internet and IMS
1261         //step 2: set data is enabled
1262         //step 3: cold sim is detected
1263         //step 4: all data connection is torn down
1264         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1265                 new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
1266 
1267         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
1268         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1269 
1270         sendInitializationEvents();
1271 
1272         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1273         verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
1274                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1275                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1276                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
1277         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 5, 1, NETWORK_TYPE_LTE_BITMASK);
1278         assertTrue(mDct.isAnyDataConnected());
1279 
1280         AsyncResult ar = new AsyncResult(null,
1281                 new Pair<>(false, DataEnabledSettings.REASON_DATA_ENABLED_BY_CARRIER), null);
1282         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_ENABLED_CHANGED, ar));
1283         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1284 
1285         // Data connection is running on a different thread. Have to wait.
1286         waitForMs(200);
1287         // Validate all metered data connections have been torn down
1288         verify(mSimulatedCommandsVerifier, times(1)).deactivateDataCall(
1289                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
1290                 any(Message.class));
1291         assertTrue(mDct.isAnyDataConnected());
1292         assertEquals(DctConstants.State.IDLE, mDct.getState(ApnSetting.TYPE_DEFAULT_STRING));
1293     }
1294 
initApns(String targetApn, String[] canHandleTypes)1295     private void initApns(String targetApn, String[] canHandleTypes) {
1296         doReturn(targetApn).when(mApnContext).getApnType();
1297         doReturn(ApnSetting.getApnTypesBitmaskFromString(mApnContext.getApnType()))
1298                 .when(mApnContext).getApnTypeBitmask();
1299         doReturn(true).when(mApnContext).isConnectable();
1300         ApnSetting apnSetting = createApnSetting(ApnSetting.getApnTypesBitmaskFromString(
1301                 TextUtils.join(",", canHandleTypes)));
1302         doReturn(apnSetting).when(mApnContext).getNextApnSetting();
1303         doReturn(apnSetting).when(mApnContext).getApnSetting();
1304         doReturn(mDataConnection).when(mApnContext).getDataConnection();
1305         doReturn(true).when(mApnContext).isEnabled();
1306         doReturn(true).when(mApnContext).isDependencyMet();
1307         doReturn(true).when(mApnContext).isReady();
1308         doReturn(false).when(mApnContext).hasRestrictedRequests(eq(true));
1309     }
1310 
1311     // Test the emergency APN setup.
1312     @Test
1313     @SmallTest
testTrySetupDataEmergencyApn()1314     public void testTrySetupDataEmergencyApn() {
1315         initApns(ApnSetting.TYPE_EMERGENCY_STRING,
1316                 new String[]{ApnSetting.TYPE_EMERGENCY_STRING});
1317         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TRY_SETUP_DATA, mApnContext));
1318         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1319 
1320         waitForMs(200);
1321 
1322         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
1323                 eq(AccessNetworkType.EUTRAN), any(DataProfile.class), eq(false), eq(false),
1324                 eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), any(),
1325                 anyBoolean(), any(Message.class));
1326     }
1327 
1328     // Test the XCAP APN setup.
1329     @Test
1330     @SmallTest
testTrySetupDataXcapApn()1331     public void testTrySetupDataXcapApn() {
1332         initApns(ApnSetting.TYPE_XCAP_STRING, new String[]{ApnSetting.TYPE_XCAP_STRING});
1333         mDct.enableApn(ApnSetting.TYPE_XCAP, DcTracker.REQUEST_TYPE_NORMAL, null);
1334 
1335         sendInitializationEvents();
1336 
1337         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
1338                 eq(AccessNetworkType.EUTRAN), any(DataProfile.class), eq(false), eq(false),
1339                 eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), any(),
1340                 anyBoolean(), any(Message.class));
1341     }
1342 
1343     // Test the ENTERPRISE APN setup.
1344     @Test
testTrySetupDataEnterpriseApn()1345     public void testTrySetupDataEnterpriseApn() {
1346         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1347         sendInitializationEvents();
1348 
1349         ArgumentCaptor<TrafficDescriptor> tdCaptor =
1350                 ArgumentCaptor.forClass(TrafficDescriptor.class);
1351         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
1352                 eq(AccessNetworkType.EUTRAN), any(DataProfile.class), eq(false), eq(false),
1353                 eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), tdCaptor.capture(),
1354                 anyBoolean(), any(Message.class));
1355         assertEquals(FAKE_APN1, tdCaptor.getValue().getDataNetworkName());
1356         assertEquals(null, tdCaptor.getValue().getOsAppId());
1357 
1358         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
1359                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_NR)
1360                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
1361                 .build();
1362         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
1363                 anyInt(), anyInt());
1364         SetupDataCallResult result = createSetupDataCallResult();
1365         result.cid = 10;
1366         mSimulatedCommands.setDataCallResult(true, result);
1367         mDct.enableApn(ApnSetting.TYPE_ENTERPRISE, DcTracker.REQUEST_TYPE_NORMAL, null);
1368         waitForMs(200);
1369 
1370         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
1371                 eq(AccessNetworkType.NGRAN), any(DataProfile.class), eq(false), eq(false),
1372                 eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), tdCaptor.capture(),
1373                 anyBoolean(), any(Message.class));
1374         assertEquals(null, tdCaptor.getValue().getDataNetworkName());
1375         assertTrue(Arrays.equals(DataConnection.getEnterpriseOsAppId(),
1376                 tdCaptor.getValue().getOsAppId()));
1377     }
1378 
1379     // Test the ENTERPRISE APN setup when default data is not set up yet.
1380     @Test
testTrySetupDataEnterpriseApnNoDefaultData()1381     public void testTrySetupDataEnterpriseApnNoDefaultData() {
1382         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
1383                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_NR)
1384                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
1385                 .build();
1386         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
1387                 anyInt(), anyInt());
1388         mDct.enableApn(ApnSetting.TYPE_ENTERPRISE, DcTracker.REQUEST_TYPE_NORMAL, null);
1389         sendInitializationEvents();
1390 
1391         ArgumentCaptor<TrafficDescriptor> tdCaptor =
1392                 ArgumentCaptor.forClass(TrafficDescriptor.class);
1393         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
1394                 eq(AccessNetworkType.NGRAN), any(DataProfile.class), eq(false), eq(false),
1395                 eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), tdCaptor.capture(),
1396                 anyBoolean(), any(Message.class));
1397         assertEquals(null, tdCaptor.getValue().getDataNetworkName());
1398         assertTrue(Arrays.equals(DataConnection.getEnterpriseOsAppId(),
1399                 tdCaptor.getValue().getOsAppId()));
1400 
1401         // Check APN contexts with no DEFAULT set up
1402         Map<Integer, ApnContext> apnContexts = mDct.getApnContexts()
1403                 .stream().collect(Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
1404         assertEquals(DctConstants.State.IDLE, apnContexts.get(ApnSetting.TYPE_DEFAULT).getState());
1405         assertEquals(DctConstants.State.FAILED,
1406                 apnContexts.get(ApnSetting.TYPE_ENTERPRISE).getState());
1407 
1408         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
1409                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_LTE)
1410                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
1411                 .build();
1412         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
1413                 anyInt(), anyInt());
1414         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1415         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1416         waitForMs(200);
1417 
1418         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
1419                 eq(AccessNetworkType.EUTRAN), any(DataProfile.class), eq(false), eq(false),
1420                 eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), tdCaptor.capture(),
1421                 anyBoolean(), any(Message.class));
1422         assertEquals(FAKE_APN1, tdCaptor.getValue().getDataNetworkName());
1423         assertEquals(null, tdCaptor.getValue().getOsAppId());
1424 
1425         // Check APN contexts after DEFAULT is set up (and ENTERPRISE failure)
1426         apnContexts = mDct.getApnContexts()
1427                 .stream().collect(Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
1428         assertEquals(DctConstants.State.CONNECTED,
1429                 apnContexts.get(ApnSetting.TYPE_DEFAULT).getState());
1430         assertEquals(DctConstants.State.FAILED,
1431                 apnContexts.get(ApnSetting.TYPE_ENTERPRISE).getState());
1432 
1433         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
1434                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_NR)
1435                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
1436                 .build();
1437         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
1438                 anyInt(), anyInt());
1439         SetupDataCallResult result = createSetupDataCallResult();
1440         result.cid = 10;
1441         mSimulatedCommands.setDataCallResult(true, result);
1442         mDct.enableApn(ApnSetting.TYPE_ENTERPRISE, DcTracker.REQUEST_TYPE_NORMAL, null);
1443         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1444         waitForMs(200);
1445 
1446         verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
1447                 eq(AccessNetworkType.NGRAN), any(DataProfile.class), eq(false), eq(false),
1448                 eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), tdCaptor.capture(),
1449                 anyBoolean(), any(Message.class));
1450         assertEquals(null, tdCaptor.getValue().getDataNetworkName());
1451         assertTrue(Arrays.equals(DataConnection.getEnterpriseOsAppId(),
1452                 tdCaptor.getValue().getOsAppId()));
1453 
1454         // Check APN contexts after DEFAULT is set up (and ENTERPRISE reenabled)
1455         apnContexts = mDct.getApnContexts()
1456                 .stream().collect(Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
1457         assertEquals(DctConstants.State.CONNECTED,
1458                 apnContexts.get(ApnSetting.TYPE_DEFAULT).getState());
1459         assertEquals(DctConstants.State.CONNECTED,
1460                 apnContexts.get(ApnSetting.TYPE_ENTERPRISE).getState());
1461     }
1462 
1463     // Test the ENTERPRISE APN setup when the same CID is returned.
1464     @Test
testTrySetupDataEnterpriseApnDuplicateCid()1465     public void testTrySetupDataEnterpriseApnDuplicateCid() {
1466         mApnSettingContentProvider.setFakeApn1NetworkTypeBitmask(
1467                 NETWORK_TYPE_LTE_BITMASK | NETWORK_TYPE_NR_BITMASK);
1468         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
1469                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_NR)
1470                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
1471                 .build();
1472         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
1473                 anyInt(), anyInt());
1474         // mSimulatedCommandsVerifier will return the same CID in SetupDataCallResult
1475         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1476         mDct.enableApn(ApnSetting.TYPE_ENTERPRISE, DcTracker.REQUEST_TYPE_NORMAL, null);
1477         sendInitializationEvents();
1478         waitForMs(200);
1479 
1480         ArgumentCaptor<TrafficDescriptor> tdCaptor =
1481                 ArgumentCaptor.forClass(TrafficDescriptor.class);
1482         verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
1483                 eq(AccessNetworkType.NGRAN), any(DataProfile.class), eq(false), eq(false),
1484                 eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), tdCaptor.capture(),
1485                 anyBoolean(), any(Message.class));
1486         List<TrafficDescriptor> tds = tdCaptor.getAllValues();
1487         // [0] is default and [1] is enterprise, since default should be set up first
1488         assertEquals(FAKE_APN1, tds.get(0).getDataNetworkName());
1489         assertEquals(null, tds.get(0).getOsAppId());
1490         assertEquals(null, tds.get(1).getDataNetworkName());
1491         assertTrue(Arrays.equals(DataConnection.getEnterpriseOsAppId(), tds.get(1).getOsAppId()));
1492 
1493         // Check APN contexts after DEFAULT and ENTERPRISE set up
1494         Map<Integer, ApnContext> apnContexts = mDct.getApnContexts()
1495                 .stream().collect(Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
1496         assertEquals(DctConstants.State.CONNECTED,
1497                 apnContexts.get(ApnSetting.TYPE_DEFAULT).getState());
1498         assertEquals(DctConstants.State.FAILED,
1499                 apnContexts.get(ApnSetting.TYPE_ENTERPRISE).getState());
1500     }
1501 
1502     @Test
1503     @SmallTest
testGetDataConnectionState()1504     public void testGetDataConnectionState() {
1505         initApns(ApnSetting.TYPE_SUPL_STRING,
1506                 new String[]{ApnSetting.TYPE_SUPL_STRING, ApnSetting.TYPE_DEFAULT_STRING});
1507         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1508                 new String[]{ApnSetting.TYPE_DEFAULT_STRING});
1509         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1510         mDct.enableApn(ApnSetting.TYPE_SUPL, DcTracker.REQUEST_TYPE_NORMAL, null);
1511 
1512         sendInitializationEvents();
1513 
1514         // Assert that both APN_TYPE_SUPL & APN_TYPE_DEFAULT are connected even we only setup data
1515         // for APN_TYPE_SUPL
1516         assertEquals(DctConstants.State.CONNECTED, mDct.getState(ApnSetting.TYPE_SUPL_STRING));
1517         assertEquals(DctConstants.State.CONNECTED, mDct.getState(ApnSetting.TYPE_DEFAULT_STRING));
1518     }
1519 
1520     // Test the unmetered APN setup when data is disabled.
1521     @Test
1522     @SmallTest
testTrySetupDataUnmeteredDataDisabled()1523     public void testTrySetupDataUnmeteredDataDisabled() {
1524         initApns(ApnSetting.TYPE_SUPL_STRING, new String[]{ApnSetting.TYPE_SUPL_STRING});
1525         doReturn(false).when(mDataEnabledSettings).isDataEnabled();
1526         doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
1527 
1528         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1529                 new String[]{ApnSetting.TYPE_FOTA_STRING});
1530 
1531         mDct.enableApn(ApnSetting.TYPE_SUPL, DcTracker.REQUEST_TYPE_NORMAL, null);
1532 
1533         sendInitializationEvents();
1534 
1535         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
1536                 eq(AccessNetworkType.EUTRAN), any(DataProfile.class),
1537                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1538                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
1539     }
1540 
1541     // Test the unmetered default APN setup when data is disabled. Default APN should always honor
1542     // the users's setting.
1543     @Test
1544     @SmallTest
testTrySetupDataUnmeteredDefaultDataDisabled()1545     public void testTrySetupDataUnmeteredDefaultDataDisabled() {
1546         initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_DEFAULT_STRING});
1547         doReturn(false).when(mDataEnabledSettings).isDataEnabled();
1548         doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
1549 
1550         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1551                 new String[]{ApnSetting.TYPE_MMS_STRING});
1552 
1553         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1554 
1555         sendInitializationEvents();
1556 
1557         verify(mSimulatedCommandsVerifier, never()).setupDataCall(
1558                 eq(AccessNetworkType.EUTRAN), any(DataProfile.class),
1559                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1560                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
1561     }
1562 
1563 
1564     // Test the metered APN setup when data is disabled.
1565     @Test
1566     @SmallTest
testTrySetupMeteredDataDisabled()1567     public void testTrySetupMeteredDataDisabled() {
1568         initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_DEFAULT_STRING});
1569         doReturn(false).when(mDataEnabledSettings).isDataEnabled();
1570         doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
1571 
1572         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1573                 new String[]{ApnSetting.TYPE_DEFAULT_STRING});
1574 
1575         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1576 
1577         sendInitializationEvents();
1578 
1579         verify(mSimulatedCommandsVerifier, times(0)).setupDataCall(anyInt(), any(DataProfile.class),
1580                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1581                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
1582     }
1583 
1584     // Test the restricted data request when data is disabled.
1585     @Test
1586     @SmallTest
testTrySetupRestrictedDataDisabled()1587     public void testTrySetupRestrictedDataDisabled() {
1588         initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_DEFAULT_STRING});
1589         doReturn(false).when(mDataEnabledSettings).isDataEnabled();
1590         doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
1591 
1592         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1593                 new String[]{ApnSetting.TYPE_DEFAULT_STRING});
1594 
1595         sendInitializationEvents();
1596 
1597         NetworkRequest nr = new NetworkRequest.Builder()
1598                 .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
1599                 .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
1600                 .build();
1601         mDct.requestNetwork(nr, DcTracker.REQUEST_TYPE_NORMAL, null);
1602         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1603 
1604         // Data connection is running on a different thread. Have to wait.
1605         waitForMs(200);
1606         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(anyInt(), any(DataProfile.class),
1607                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1608                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
1609     }
1610 
1611     // Test the restricted data request when roaming is disabled.
1612     @Test
1613     @SmallTest
testTrySetupRestrictedRoamingDisabled()1614     public void testTrySetupRestrictedRoamingDisabled() {
1615         initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_DEFAULT_STRING});
1616 
1617         mDct.setDataRoamingEnabledByUser(false);
1618         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1619                 new String[]{ApnSetting.TYPE_DEFAULT_STRING});
1620         //user is in roaming
1621         doReturn(true).when(mServiceState).getDataRoaming();
1622 
1623         sendInitializationEvents();
1624 
1625         NetworkRequest nr = new NetworkRequest.Builder()
1626                 .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
1627                 .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
1628                 .build();
1629         mDct.requestNetwork(nr, DcTracker.REQUEST_TYPE_NORMAL, null);
1630         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1631 
1632         // Data connection is running on a different thread. Have to wait.
1633         waitForMs(200);
1634         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(anyInt(), any(DataProfile.class),
1635                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1636                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
1637     }
1638 
1639     // Test the default data when data is not connectable.
1640     @Test
1641     @SmallTest
testTrySetupNotConnectable()1642     public void testTrySetupNotConnectable() {
1643         initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
1644         doReturn(false).when(mApnContext).isConnectable();
1645 
1646         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1647                 new String[]{ApnSetting.TYPE_DEFAULT_STRING});
1648 
1649         sendInitializationEvents();
1650 
1651         verify(mSimulatedCommandsVerifier, times(0)).setupDataCall(anyInt(), any(DataProfile.class),
1652                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1653                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
1654     }
1655 
1656     // Test the default data on IWLAN.
1657     @Test
1658     @SmallTest
testTrySetupDefaultOnIWLAN()1659     public void testTrySetupDefaultOnIWLAN() {
1660         doReturn(true).when(mTransportManager).isInLegacyMode();
1661         initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
1662         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
1663                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_IWLAN)
1664                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
1665                 .build();
1666         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
1667                 anyInt(), anyInt());
1668 
1669         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1670                 new String[]{ApnSetting.TYPE_DEFAULT_STRING});
1671 
1672         sendInitializationEvents();
1673 
1674         verify(mSimulatedCommandsVerifier, times(0)).setupDataCall(anyInt(), any(DataProfile.class),
1675                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1676                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
1677     }
1678 
1679     // Test the default data when the phone is in ECBM.
1680     @Test
1681     @SmallTest
testTrySetupDefaultInECBM()1682     public void testTrySetupDefaultInECBM() {
1683         initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
1684         doReturn(true).when(mPhone).isInEcm();
1685 
1686         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1687                 new String[]{ApnSetting.TYPE_DEFAULT_STRING});
1688 
1689         sendInitializationEvents();
1690 
1691         verify(mSimulatedCommandsVerifier, times(0)).setupDataCall(anyInt(), any(DataProfile.class),
1692                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1693                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
1694     }
1695 
1696     // Test update waiting apn list when on data rat change
1697     @FlakyTest /* flakes 0.86% of the time */
1698     @Ignore
1699     @Test
1700     @SmallTest
testUpdateWaitingApnListOnDataRatChange()1701     public void testUpdateWaitingApnListOnDataRatChange() {
1702         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
1703                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_EHRPD)
1704                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
1705                 .build();
1706         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
1707                 anyInt(), anyInt());
1708         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
1709                 new String[]{ApnSetting.TYPE_DEFAULT_STRING});
1710         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1711         initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
1712 
1713         sendInitializationEvents();
1714 
1715         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
1716         // Verify if RIL command was sent properly.
1717         verify(mSimulatedCommandsVerifier).setupDataCall(
1718                 eq(AccessNetworkType.CDMA2000), dpCaptor.capture(),
1719                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1720                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
1721         verifyDataProfile(dpCaptor.getValue(), FAKE_APN4, 0, 21, 2, NETWORK_TYPE_EHRPD_BITMASK);
1722         assertTrue(mDct.isAnyDataConnected());
1723 
1724         //data rat change from ehrpd to lte
1725         logd("Sending EVENT_DATA_RAT_CHANGED");
1726         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
1727                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_LTE)
1728                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
1729                 .build();
1730         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
1731                 anyInt(), anyInt());
1732         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_RAT_CHANGED, null));
1733         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1734 
1735         // Data connection is running on a different thread. Have to wait.
1736         waitForMs(200);
1737         // Verify the disconnected data call due to rat change and retry manger schedule another
1738         // data call setup
1739         verify(mSimulatedCommandsVerifier, times(1)).deactivateDataCall(
1740                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
1741                 any(Message.class));
1742         verify(mAlarmManager, times(1)).setExact(eq(AlarmManager.ELAPSED_REALTIME_WAKEUP),
1743                 anyLong(), any(PendingIntent.class));
1744 
1745         //Send event for reconnecting data
1746         initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
1747         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_RECONNECT,
1748                         mPhone.getPhoneId(), DcTracker.RELEASE_TYPE_NORMAL, mApnContext));
1749         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1750 
1751         // Data connection is running on a different thread. Have to wait.
1752         waitForMs(200);
1753         // Verify if RIL command was sent properly.
1754         verify(mSimulatedCommandsVerifier).setupDataCall(
1755                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
1756                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
1757                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
1758         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
1759         assertTrue(mDct.isAnyDataConnected());
1760     }
1761 
1762     // Test for fetchDunApns()
1763     @Test
1764     @SmallTest
testFetchDunApn()1765     public void testFetchDunApn() {
1766 
1767         sendInitializationEvents();
1768 
1769         String dunApnString = "[ApnSettingV3]HOT mobile PC,pc.hotm,,,,,,,,,440,10,,DUN,,,true,"
1770                 + "0,,,,,,,,";
1771         ApnSetting dunApnExpected = ApnSetting.fromString(dunApnString);
1772 
1773         Settings.Global.putString(mContext.getContentResolver(),
1774                 Settings.Global.TETHER_DUN_APN, dunApnString);
1775         // should return APN from Setting
1776         ApnSetting dunApn = mDct.fetchDunApns().get(0);
1777         assertTrue(dunApnExpected.equals(dunApn));
1778 
1779         Settings.Global.putString(mContext.getContentResolver(),
1780                 Settings.Global.TETHER_DUN_APN, null);
1781         // should return APN from db
1782         dunApn = mDct.fetchDunApns().get(0);
1783         assertEquals(FAKE_APN5, dunApn.getApnName());
1784     }
1785 
1786     // Test for fetchDunApns() with apn set id
1787     @Test
1788     @SmallTest
testFetchDunApnWithPreferredApnSet()1789     public void testFetchDunApnWithPreferredApnSet() {
1790         sendCarrierConfigChanged("testFetchDunApnWithPreferredApnSet: ");
1791 
1792         // apnSetId=1
1793         String dunApnString1 = "[ApnSettingV5]HOT mobile PC,pc.hotm,,,,,,,,,440,10,,DUN,,,true,"
1794                 + "0,,,,,,,,,,1";
1795         // apnSetId=0
1796         String dunApnString2 = "[ApnSettingV5]HOT mobile PC,pc.coldm,,,,,,,,,440,10,,DUN,,,true,"
1797                 + "0,,,,,,,,,,2";
1798 
1799         ApnSetting dunApnExpected = ApnSetting.fromString(dunApnString1);
1800 
1801         ContentResolver cr = mContext.getContentResolver();
1802         Settings.Global.putString(cr, Settings.Global.TETHER_DUN_APN,
1803                 dunApnString1 + ";" + dunApnString2);
1804 
1805         // set that we prefer apn set 1
1806         ContentValues values = new ContentValues();
1807         values.put(Telephony.Carriers.APN_SET_ID, 1);
1808         cr.update(PREFERAPN_URI, values, null, null);
1809 
1810         // return APN from Setting with apnSetId=1
1811         ArrayList<ApnSetting> dunApns = mDct.fetchDunApns();
1812         assertEquals(1, dunApns.size());
1813         assertEquals(1, dunApns.get(0).getApnSetId());
1814         assertTrue(dunApnExpected.equals(dunApns.get(0)));
1815 
1816         // set that we prefer apn set 2
1817         values = new ContentValues();
1818         values.put(Telephony.Carriers.APN_SET_ID, 2);
1819         cr.update(PREFERAPN_URI, values, null, null);
1820 
1821         // return APN from Setting with apnSetId=2
1822         dunApns = mDct.fetchDunApns();
1823         assertEquals(1, dunApns.size());
1824         assertEquals(2, dunApns.get(0).getApnSetId());
1825         dunApnExpected = ApnSetting.fromString(dunApnString2);
1826         assertTrue(dunApnExpected.equals(dunApns.get(0)));
1827     }
1828 
1829     @Test
1830     @SmallTest
testFetchDunApnWhileRoaming()1831     public void testFetchDunApnWhileRoaming() {
1832         doReturn(true).when(mServiceState).getRoaming();
1833         mBundle.putBoolean(CarrierConfigManager
1834                 .KEY_DISABLE_DUN_APN_WHILE_ROAMING_WITH_PRESET_APN_BOOL, true);
1835 
1836         sendInitializationEvents();
1837 
1838         String dunApnString = "[ApnSettingV3]HOT mobile PC,pc.hotm,,,,,,,,,440,10,,DUN,,,true,"
1839                 + "0,,,,,,,,";
1840 
1841         Settings.Global.putString(mContext.getContentResolver(),
1842                 Settings.Global.TETHER_DUN_APN, dunApnString);
1843 
1844         DcTracker spyDct = spy(mDct);
1845         doReturn(true).when(spyDct).isPreferredApnUserEdited();
1846         // Expect non-empty DUN APN list
1847         assertEquals(1, spyDct.fetchDunApns().size());
1848 
1849         doReturn(false).when(spyDct).isPreferredApnUserEdited();
1850         // Expect empty DUN APN list
1851         assertEquals(0, spyDct.fetchDunApns().size());
1852 
1853         Settings.Global.putString(mContext.getContentResolver(),
1854                 Settings.Global.TETHER_DUN_APN, null);
1855     }
1856 
1857     /**
1858      * Test that fetchDunApns() returns list that prioritize the preferred APN when the preferred
1859      * APN including DUN type.
1860      */
1861     @Test
testFetchDunApnWithPreferredApn()1862     public void testFetchDunApnWithPreferredApn() {
1863         // Set support APN types of FAKE_APN1 and FAKE_APN5
1864         mApnSettingContentProvider.setFakeApn1Types("default,dun");
1865         mApnSettingContentProvider.setFakeApn5Types("default,dun");
1866 
1867         // Set prefer apn set id.
1868         ContentResolver cr = mContext.getContentResolver();
1869         ContentValues values = new ContentValues();
1870         values.put(Telephony.Carriers.APN_SET_ID, 0);
1871         cr.update(PREFERAPN_URI, values, null, null);
1872         // Set FAKE_APN5 as the preferred APN.
1873         mApnSettingContentProvider.setFakePreferredApn(mApnSettingContentProvider.getFakeApn5());
1874 
1875         sendInitializationEvents();
1876 
1877         // Return the APN list that set the preferred APN at the top.
1878         ArrayList<ApnSetting> dunApns = mDct.fetchDunApns();
1879         assertEquals(2, dunApns.size());
1880         assertEquals(FAKE_APN5, dunApns.get(0).getApnName());
1881         assertEquals(FAKE_APN1, dunApns.get(1).getApnName());
1882     }
1883 
1884     // This tests simulates the race case where the sim status change event is triggered, the
1885     // default data connection is attached, and then the carrier config gets changed which bumps
1886     // the database id which we want to ignore when cleaning up connections and matching against
1887     // the dun APN.  Tests b/158908392.
1888     @Test
1889     @SmallTest
testCheckForCompatibleDataConnectionWithDunWhenIdsChange()1890     public void testCheckForCompatibleDataConnectionWithDunWhenIdsChange() {
1891         //Set dun as a support apn type of FAKE_APN1
1892         mApnSettingContentProvider.setFakeApn1Types("default,supl,dun");
1893 
1894         // Enable the default apn
1895         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1896         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1897 
1898         //Load the sim and attach the data connection without firing the carrier changed event
1899         final String logMsgPrefix = "testCheckForCompatibleDataConnectionWithDunWhenIdsChange: ";
1900         sendSimStateUpdated(logMsgPrefix);
1901         sendEventDataConnectionAttached(logMsgPrefix);
1902         waitForMs(200);
1903 
1904         // Confirm that FAKE_APN1 comes up as a dun candidate
1905         ApnSetting dunApn = mDct.fetchDunApns().get(0);
1906         assertEquals(dunApn.getApnName(), FAKE_APN1);
1907         Map<Integer, ApnContext> apnContexts = mDct.getApnContexts()
1908                 .stream().collect(Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
1909 
1910         //Double check that the default apn content is connected while the dun apn context is not
1911         assertEquals(apnContexts.get(ApnSetting.TYPE_DEFAULT).getState(),
1912                 DctConstants.State.CONNECTED);
1913         assertNotEquals(apnContexts.get(ApnSetting.TYPE_DUN).getState(),
1914                 DctConstants.State.CONNECTED);
1915 
1916 
1917         //Change the row ids the same way as what happens when we have old apn values in the
1918         //carrier table
1919         mApnSettingContentProvider.setRowIdOffset(100);
1920         sendCarrierConfigChanged(logMsgPrefix);
1921         waitForMs(200);
1922 
1923         mDct.enableApn(ApnSetting.TYPE_DUN, DcTracker.REQUEST_TYPE_NORMAL, null);
1924         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1925 
1926         Map<Integer, ApnContext> apnContextsAfterRowIdsChanged = mDct.getApnContexts()
1927                 .stream().collect(Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
1928 
1929         //Make sure that the data connection used earlier wasn't cleaned up and still in use.
1930         assertEquals(apnContexts.get(ApnSetting.TYPE_DEFAULT).getDataConnection(),
1931                 apnContextsAfterRowIdsChanged.get(ApnSetting.TYPE_DEFAULT).getDataConnection());
1932 
1933         //Check that the DUN is using the same active data connection
1934         assertEquals(apnContexts.get(ApnSetting.TYPE_DEFAULT).getDataConnection(),
1935                 apnContextsAfterRowIdsChanged.get(ApnSetting.TYPE_DUN).getDataConnection());
1936     }
1937 
1938     @Test
1939     @SmallTest
testCheckForCompatibleDataConnectionWithEnterprise()1940     public void testCheckForCompatibleDataConnectionWithEnterprise() {
1941         // Allow both DEFAULT and ENTERPRISE to use APN 1
1942         mApnSettingContentProvider.setFakeApn1NetworkTypeBitmask(
1943                 NETWORK_TYPE_LTE_BITMASK | NETWORK_TYPE_NR_BITMASK);
1944 
1945         // Enable the DEFAULT APN
1946         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
1947         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
1948         sendInitializationEvents();
1949 
1950         ArgumentCaptor<TrafficDescriptor> tdCaptor =
1951                 ArgumentCaptor.forClass(TrafficDescriptor.class);
1952         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
1953                 eq(AccessNetworkType.EUTRAN), any(DataProfile.class), eq(false), eq(false),
1954                 eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), tdCaptor.capture(),
1955                 anyBoolean(), any(Message.class));
1956         assertEquals(FAKE_APN1, tdCaptor.getValue().getDataNetworkName());
1957         assertEquals(null, tdCaptor.getValue().getOsAppId());
1958 
1959         // Check APN contexts after DEFAULT is set up
1960         Map<Integer, ApnContext> apnContexts = mDct.getApnContexts()
1961                 .stream().collect(Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
1962         assertEquals(apnContexts.get(ApnSetting.TYPE_DEFAULT).getState(),
1963                 DctConstants.State.CONNECTED);
1964         assertNotEquals(apnContexts.get(ApnSetting.TYPE_ENTERPRISE).getState(),
1965                 DctConstants.State.CONNECTED);
1966 
1967         // Enable the ENTERPRISE APN
1968         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
1969                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_NR)
1970                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
1971                 .build();
1972         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
1973                 anyInt(), anyInt());
1974         SetupDataCallResult result = createSetupDataCallResult();
1975         result.cid = 10;
1976         mSimulatedCommands.setDataCallResult(true, result);
1977         mDct.enableApn(ApnSetting.TYPE_ENTERPRISE, DcTracker.REQUEST_TYPE_NORMAL, null);
1978         waitForMs(200);
1979 
1980         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
1981                 eq(AccessNetworkType.NGRAN), any(DataProfile.class), eq(false), eq(false),
1982                 eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), tdCaptor.capture(),
1983                 anyBoolean(), any(Message.class));
1984         assertEquals(null, tdCaptor.getValue().getDataNetworkName());
1985         assertTrue(Arrays.equals(DataConnection.getEnterpriseOsAppId(),
1986                 tdCaptor.getValue().getOsAppId()));
1987 
1988         // Check APN contexts after ENTERPRISE is set up
1989         Map<Integer, ApnContext> apnContextsAfterRowIdsChanged = mDct.getApnContexts()
1990                 .stream().collect(Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
1991 
1992         // Make sure that the data connection used earlier wasn't cleaned up and still in use.
1993         assertEquals(apnContexts.get(ApnSetting.TYPE_DEFAULT).getDataConnection(),
1994                 apnContextsAfterRowIdsChanged.get(ApnSetting.TYPE_DEFAULT).getDataConnection());
1995 
1996         // Check that ENTERPRISE isn't using the same data connection as DEFAULT
1997         assertNotEquals(apnContexts.get(ApnSetting.TYPE_DEFAULT).getDataConnection(),
1998                 apnContextsAfterRowIdsChanged.get(ApnSetting.TYPE_ENTERPRISE).getDataConnection());
1999     }
2000 
2001     // Test for Data setup with APN Set ID
2002     @Test
2003     @SmallTest
testDataSetupWithApnSetId()2004     public void testDataSetupWithApnSetId() throws Exception {
2005         // Set the prefer apn set id to "1"
2006         ContentResolver cr = mContext.getContentResolver();
2007         ContentValues values = new ContentValues();
2008         values.put(Telephony.Carriers.APN_SET_ID, 1);
2009         cr.update(PREFERAPN_URI, values, null, null);
2010 
2011         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
2012         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
2013 
2014         sendInitializationEvents();
2015 
2016         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
2017         verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
2018                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
2019                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
2020                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
2021 
2022         List<DataProfile> dataProfiles = dpCaptor.getAllValues();
2023         assertEquals(2, dataProfiles.size());
2024 
2025         // Verify to use FAKE APN7 which is Default APN with apnSetId=1(Same as the pereferred
2026         // APN's set id).
2027         Optional<DataProfile> fakeApn7 = dataProfiles.stream()
2028                 .filter(dp -> dp.getApn().equals(FAKE_APN7)).findFirst();
2029         assertTrue(fakeApn7.isPresent());
2030         verifyDataProfile(fakeApn7.get(), FAKE_APN7, 0, 17, 1, NETWORK_TYPE_LTE_BITMASK);
2031 
2032         // Verify to use FAKE APN8 which is IMS APN with apnSetId=-1
2033         // (Telephony.Carriers.MATCH_ALL_APN_SET_ID).
2034         Optional<DataProfile> fakeApn8 = dataProfiles.stream()
2035                 .filter(dp -> dp.getApn().equals(FAKE_APN8)).findFirst();
2036         assertTrue(fakeApn8.isPresent());
2037         verifyDataProfile(fakeApn8.get(), FAKE_APN8, 2, 64, 1, NETWORK_TYPE_LTE_BITMASK);
2038     }
2039 
2040     // Test oos
2041     @Test
2042     @SmallTest
testDataRatChangeOOS()2043     public void testDataRatChangeOOS() {
2044         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
2045                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_EHRPD)
2046                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
2047                 .build();
2048         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
2049                 anyInt(), anyInt());
2050 
2051         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
2052                 new String[]{ApnSetting.TYPE_DEFAULT_STRING});
2053         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
2054         initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
2055 
2056         sendInitializationEvents();
2057 
2058         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
2059         // Verify if RIL command was sent properly.
2060         verify(mSimulatedCommandsVerifier).setupDataCall(
2061                 eq(AccessNetworkType.CDMA2000), dpCaptor.capture(),
2062                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
2063                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
2064         verifyDataProfile(dpCaptor.getValue(), FAKE_APN4, 0, 21, 2, NETWORK_TYPE_EHRPD_BITMASK);
2065         assertTrue(mDct.isAnyDataConnected());
2066 
2067         // Data rat change from ehrpd to unknown due to OOS
2068         logd("Sending EVENT_DATA_RAT_CHANGED");
2069         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
2070                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_UNKNOWN)
2071                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
2072                 .build();
2073         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
2074                 anyInt(), anyInt());
2075         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_RAT_CHANGED, null));
2076         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2077 
2078         // Data connection is running on a different thread. Have to wait.
2079         waitForMs(200);
2080         // Verify data connection is on
2081         verify(mSimulatedCommandsVerifier, times(0)).deactivateDataCall(
2082                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
2083                 any(Message.class));
2084 
2085         // Data rat resume from unknown to ehrpd
2086         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
2087                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_EHRPD)
2088                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
2089                 .build();
2090         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
2091                 anyInt(), anyInt());
2092         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_RAT_CHANGED, null));
2093         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2094 
2095         // Verify the same data connection
2096         assertEquals(FAKE_APN4, mDct.getActiveApnString(ApnSetting.TYPE_DEFAULT_STRING));
2097         assertTrue(mDct.isAnyDataConnected());
2098     }
2099 
2100     // Test provisioning
2101     /*@Test
2102     @SmallTest
2103     public void testDataEnableInProvisioning() throws Exception {
2104         ContentResolver resolver = mContext.getContentResolver();
2105 
2106         assertEquals(1, Settings.Global.getInt(resolver, Settings.Global.MOBILE_DATA));
2107         assertTrue(mDct.isDataEnabled());
2108         assertTrue(mDct.isUserDataEnabled());
2109 
2110         mDct.setUserDataEnabled(false);
2111         waitForMs(200);
2112 
2113         assertEquals(0, Settings.Global.getInt(resolver, Settings.Global.MOBILE_DATA));
2114         assertFalse(mDct.isDataEnabled());
2115         assertFalse(mDct.isUserDataEnabled());
2116 
2117         // Changing provisioned to 0.
2118         Settings.Global.putInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0);
2119         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DEVICE_PROVISIONED_CHANGE, null));
2120         waitForMs(200);
2121 
2122         assertTrue(mDct.isDataEnabled());
2123         assertTrue(mDct.isUserDataEnabled());
2124 
2125         // Enable user data during provisioning. It should write to
2126         // Settings.Global.MOBILE_DATA and keep data enabled when provisioned.
2127         mDct.setUserDataEnabled(true);
2128         Settings.Global.putInt(resolver, Settings.Global.DEVICE_PROVISIONED, 1);
2129         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DEVICE_PROVISIONED_CHANGE, null));
2130         waitForMs(200);
2131 
2132         assertTrue(mDct.isDataEnabled());
2133         assertTrue(mDct.isUserDataEnabled());
2134         assertEquals(1, Settings.Global.getInt(resolver, Settings.Global.MOBILE_DATA));
2135     }*/
2136 
2137     /*
2138     @Test
2139     @SmallTest
2140     public void testNotifyDataEnabledChanged() throws Exception {
2141         doAnswer(invocation -> {
2142             mMessage = (Message) invocation.getArguments()[0];
2143             return true;
2144         }).when(mHandler).sendMessageDelayed(any(), anyLong());
2145 
2146         // Test registration.
2147         mDct.registerForDataEnabledChanged(mHandler, DATA_ENABLED_CHANGED, null);
2148         verifyDataEnabledChangedMessage(true, DataEnabledSettings.REASON_REGISTERED);
2149 
2150         // Disable user data. Should receive data enabled change to false.
2151         mDct.setUserDataEnabled(false);
2152         waitForMs(200);
2153         verifyDataEnabledChangedMessage(false, DataEnabledSettings.REASON_USER_DATA_ENABLED);
2154 
2155         // Changing provisioned to 0. Shouldn't receive any message, as data enabled remains false.
2156         ContentResolver resolver = mContext.getContentResolver();
2157         Settings.Global.putInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0);
2158         Settings.Global.putInt(resolver, Settings.Global.DEVICE_PROVISIONING_MOBILE_DATA_ENABLED,
2159                 0);
2160         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DEVICE_PROVISIONED_CHANGE, null));
2161         waitForMs(200);
2162         assertFalse(mDct.isDataEnabled());
2163         verify(mHandler, never()).sendMessageDelayed(any(), anyLong());
2164 
2165         // Changing provisioningDataEnabled to 1. It should trigger data enabled change to true.
2166         Settings.Global.putInt(resolver,
2167                 Settings.Global.DEVICE_PROVISIONING_MOBILE_DATA_ENABLED, 1);
2168         mDct.sendMessage(mDct.obtainMessage(
2169                 DctConstants.EVENT_DEVICE_PROVISIONING_DATA_SETTING_CHANGE, null));
2170         waitForMs(200);
2171         verifyDataEnabledChangedMessage(
2172                 true, DataEnabledSettings.REASON_PROVISIONING_DATA_ENABLED_CHANGED);
2173     }*/
2174 
2175     @Test
2176     @SmallTest
testNetworkStatusChangedRecoveryOFF()2177     public void testNetworkStatusChangedRecoveryOFF() {
2178         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
2179                 new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
2180         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
2181         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
2182 
2183         sendInitializationEvents();
2184 
2185         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
2186         verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
2187                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
2188                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
2189                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
2190         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
2191 
2192         logd("Sending EVENT_NETWORK_STATUS_CHANGED");
2193         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NETWORK_STATUS_CHANGED,
2194                 NetworkAgent.VALID_NETWORK, 1, null));
2195         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2196 
2197         logd("Sending EVENT_NETWORK_STATUS_CHANGED");
2198         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NETWORK_STATUS_CHANGED,
2199                 NetworkAgent.INVALID_NETWORK, 1, null));
2200         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2201 
2202         waitForMs(200);
2203 
2204         // Verify that its no-op when the new data stall detection feature is disabled
2205         verify(mSimulatedCommandsVerifier, times(0)).getDataCallList(any(Message.class));
2206     }
2207 
2208     @FlakyTest
2209     @Test
2210     @SmallTest
testNetworkStatusChangedRecoveryON()2211     public void testNetworkStatusChangedRecoveryON() {
2212         ContentResolver resolver = mContext.getContentResolver();
2213         Settings.Global.putInt(resolver, Settings.Global.DATA_STALL_RECOVERY_ON_BAD_NETWORK, 1);
2214         Settings.System.putInt(resolver, "radio.data.stall.recovery.action", 0);
2215         doReturn(new SignalStrength()).when(mPhone).getSignalStrength();
2216 
2217         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
2218                 new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
2219         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
2220         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
2221 
2222         sendInitializationEvents();
2223 
2224         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
2225         verify(mSimulatedCommandsVerifier, timeout(TEST_TIMEOUT).times(2)).setupDataCall(
2226                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
2227                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
2228                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
2229         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2230         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
2231 
2232         logd("Sending EVENT_NETWORK_STATUS_CHANGED");
2233         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NETWORK_STATUS_CHANGED,
2234                 NetworkAgent.VALID_NETWORK, 1, null));
2235         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2236 
2237         logd("Sending EVENT_NETWORK_STATUS_CHANGED");
2238         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NETWORK_STATUS_CHANGED,
2239                 NetworkAgent.INVALID_NETWORK, 1, null));
2240         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2241 
2242         // Data connection is running on a different thread. Have to wait.
2243         waitForMs(200);
2244         verify(mSimulatedCommandsVerifier, times(1)).getDataCallList(any(Message.class));
2245     }
2246 
2247     @FlakyTest
2248     @Test
2249     @SmallTest
testRecoveryStepPDPReset()2250     public void testRecoveryStepPDPReset() {
2251         ContentResolver resolver = mContext.getContentResolver();
2252         Settings.Global.putInt(resolver, Settings.Global.DATA_STALL_RECOVERY_ON_BAD_NETWORK, 1);
2253         Settings.Global.putLong(resolver,
2254                 Settings.Global.MIN_DURATION_BETWEEN_RECOVERY_STEPS_IN_MS, 100);
2255         Settings.System.putInt(resolver, "radio.data.stall.recovery.action", 1);
2256         doReturn(new SignalStrength()).when(mPhone).getSignalStrength();
2257 
2258         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
2259                 new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
2260         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
2261         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
2262 
2263         sendInitializationEvents();
2264 
2265         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
2266         verify(mSimulatedCommandsVerifier, timeout(TEST_TIMEOUT).times(2)).setupDataCall(
2267                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
2268                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
2269                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
2270         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
2271 
2272         logd("Sending EVENT_NETWORK_STATUS_CHANGED false");
2273         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NETWORK_STATUS_CHANGED,
2274                 NetworkAgent.INVALID_NETWORK, 1, null));
2275         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2276 
2277         waitForMs(200);
2278 
2279         // expected tear down all DataConnections
2280         verify(mSimulatedCommandsVerifier, times(1)).deactivateDataCall(
2281                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
2282                 any(Message.class));
2283     }
2284 
2285 
2286     @Test
2287     @SmallTest
testRecoveryStepReRegister()2288     public void testRecoveryStepReRegister() {
2289         ContentResolver resolver = mContext.getContentResolver();
2290         Settings.Global.putInt(resolver, Settings.Global.DATA_STALL_RECOVERY_ON_BAD_NETWORK, 1);
2291         Settings.Global.putLong(resolver,
2292                 Settings.Global.MIN_DURATION_BETWEEN_RECOVERY_STEPS_IN_MS, 100);
2293         Settings.System.putInt(resolver, "radio.data.stall.recovery.action", 2);
2294         doReturn(new SignalStrength()).when(mPhone).getSignalStrength();
2295         doReturn(PhoneConstants.State.IDLE).when(mPhone).getState();
2296 
2297         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
2298                 new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
2299         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
2300 
2301         sendInitializationEvents();
2302 
2303         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
2304         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
2305                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
2306                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
2307                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
2308         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
2309 
2310         logd("Sending EVENT_NETWORK_STATUS_CHANGED false");
2311         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NETWORK_STATUS_CHANGED,
2312                 NetworkAgent.INVALID_NETWORK, 1, null));
2313         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2314 
2315         // expected to get preferred network type
2316         verify(mSST, times(1)).reRegisterNetwork(eq(null));
2317     }
2318 
2319     @Test
2320     @SmallTest
testRecoveryStepRestartRadio()2321     public void testRecoveryStepRestartRadio() {
2322         ContentResolver resolver = mContext.getContentResolver();
2323         Settings.Global.putInt(resolver, Settings.Global.DATA_STALL_RECOVERY_ON_BAD_NETWORK, 1);
2324         Settings.Global.putLong(resolver,
2325                 Settings.Global.MIN_DURATION_BETWEEN_RECOVERY_STEPS_IN_MS, 100);
2326         Settings.System.putInt(resolver, "radio.data.stall.recovery.action", 3);
2327         doReturn(new SignalStrength()).when(mPhone).getSignalStrength();
2328         doReturn(PhoneConstants.State.IDLE).when(mPhone).getState();
2329 
2330         mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
2331                 new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
2332         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
2333 
2334         sendInitializationEvents();
2335 
2336         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
2337         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
2338                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
2339                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
2340                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
2341         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
2342 
2343         logd("Sending EVENT_NETWORK_STATUS_CHANGED false");
2344         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NETWORK_STATUS_CHANGED,
2345                 NetworkAgent.INVALID_NETWORK, 1, null));
2346         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2347 
2348         // expected to get preferred network type
2349         verify(mSST, times(1)).powerOffRadioSafely();
2350     }
2351 
verifyDataEnabledChangedMessage(boolean enabled, int reason)2352     private void verifyDataEnabledChangedMessage(boolean enabled, int reason) {
2353         verify(mHandler, times(1)).sendMessageDelayed(any(), anyLong());
2354         Pair<Boolean, Integer> result = (Pair) ((AsyncResult) mMessage.obj).result;
2355         assertEquals(DATA_ENABLED_CHANGED, mMessage.what);
2356         assertEquals(enabled, result.first);
2357         assertEquals(reason, (int) result.second);
2358         clearInvocations(mHandler);
2359     }
2360 
setUpSubscriptionPlans(boolean isNrUnmetered)2361     private void setUpSubscriptionPlans(boolean isNrUnmetered) throws Exception {
2362         List<SubscriptionPlan> plans = new ArrayList<>();
2363         if (isNrUnmetered) {
2364             plans.add(SubscriptionPlan.Builder
2365                     .createRecurring(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"),
2366                             Period.ofMonths(1))
2367                     .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2368                             SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2369                     .setNetworkTypes(new int[] {TelephonyManager.NETWORK_TYPE_NR})
2370                     .build());
2371         }
2372         plans.add(SubscriptionPlan.Builder
2373                 .createRecurring(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"),
2374                         Period.ofMonths(1))
2375                 .setDataLimit(1_000_000_000, SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2376                 .setDataUsage(500_000_000, System.currentTimeMillis())
2377                 .build());
2378         replaceInstance(DcTracker.class, "mSubscriptionPlans", mDct, plans);
2379     }
2380 
resetSubscriptionPlans()2381     private void resetSubscriptionPlans() throws Exception {
2382         replaceInstance(DcTracker.class, "mSubscriptionPlans", mDct, null);
2383     }
2384 
setUpSubscriptionOverride(int[] networkTypes, boolean isUnmetered)2385     private void setUpSubscriptionOverride(int[] networkTypes, boolean isUnmetered)
2386             throws Exception {
2387         List<Integer> networkTypesList = null;
2388         if (networkTypes != null) {
2389             networkTypesList = new ArrayList<>();
2390             for (int networkType : networkTypes) {
2391                 networkTypesList.add(networkType);
2392             }
2393         }
2394         replaceInstance(DcTracker.class, "mUnmeteredNetworkTypes", mDct, networkTypesList);
2395         replaceInstance(DcTracker.class, "mUnmeteredOverride", mDct, isUnmetered);
2396     }
2397 
resetSubscriptionOverride()2398     private void resetSubscriptionOverride() throws Exception {
2399         replaceInstance(DcTracker.class, "mUnmeteredNetworkTypes", mDct, null);
2400         replaceInstance(DcTracker.class, "mUnmeteredOverride", mDct, false);
2401     }
2402 
isNetworkTypeUnmetered(int networkType)2403     private boolean isNetworkTypeUnmetered(int networkType) throws Exception {
2404         Method method = DcTracker.class.getDeclaredMethod(
2405                 "isNetworkTypeUnmetered", int.class);
2406         method.setAccessible(true);
2407         return (boolean) method.invoke(mDct, networkType);
2408     }
2409 
setUpDataConnection()2410     private int setUpDataConnection() throws Exception {
2411         Field dc = DcTracker.class.getDeclaredField("mDataConnections");
2412         dc.setAccessible(true);
2413         Field uig = DcTracker.class.getDeclaredField("mUniqueIdGenerator");
2414         uig.setAccessible(true);
2415         int id = ((AtomicInteger) uig.get(mDct)).getAndIncrement();
2416         ((HashMap<Integer, DataConnection>) dc.get(mDct)).put(id, mDataConnection);
2417         return id;
2418     }
2419 
resetDataConnection(int id)2420     private void resetDataConnection(int id) throws Exception {
2421         Field dc = DcTracker.class.getDeclaredField("mDataConnections");
2422         dc.setAccessible(true);
2423         ((HashMap<Integer, DataConnection>) dc.get(mDct)).remove(id);
2424     }
2425 
setUpWatchdogTimer()2426     private void setUpWatchdogTimer() {
2427         // Watchdog active for 10s
2428         mBundle.putLong(CarrierConfigManager.KEY_5G_WATCHDOG_TIME_MS_LONG, 10000);
2429         Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
2430         intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, mPhone.getPhoneId());
2431         intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, mPhone.getSubId());
2432         mContext.sendBroadcast(intent);
2433         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2434     }
2435 
getWatchdogStatus()2436     private boolean getWatchdogStatus() throws Exception {
2437         Field field = DcTracker.class.getDeclaredField(("mWatchdog"));
2438         field.setAccessible(true);
2439         return (boolean) field.get(mDct);
2440     }
2441 
getHandoverCompletionMessages()2442     private Map<Integer, List<Message>> getHandoverCompletionMessages() throws Exception {
2443         Field field = DcTracker.class.getDeclaredField(("mHandoverCompletionMsgs"));
2444         field.setAccessible(true);
2445         return (Map<Integer, List<Message>>) field.get(mDct);
2446     }
2447 
setUpTempNotMetered()2448     private void setUpTempNotMetered() {
2449         doReturn((int) TelephonyManager.NETWORK_TYPE_BITMASK_NR)
2450                 .when(mPhone).getRadioAccessFamily();
2451         doReturn(1).when(mPhone).getSubId();
2452         mBundle.putBoolean(CarrierConfigManager.KEY_NETWORK_TEMP_NOT_METERED_SUPPORTED_BOOL, true);
2453         Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
2454         intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, mPhone.getPhoneId());
2455         intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, mPhone.getSubId());
2456         mContext.sendBroadcast(intent);
2457         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2458     }
2459 
2460     @Test
testIsNetworkTypeUnmetered()2461     public void testIsNetworkTypeUnmetered() throws Exception {
2462         initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
2463 
2464         // only 5G unmetered
2465         setUpSubscriptionOverride(new int[]{TelephonyManager.NETWORK_TYPE_NR}, true);
2466 
2467         assertTrue(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_NR));
2468         assertFalse(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_LTE));
2469         assertFalse(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_UNKNOWN));
2470 
2471         // all network types metered
2472         setUpSubscriptionOverride(TelephonyManager.getAllNetworkTypes(), false);
2473 
2474         assertFalse(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_NR));
2475         assertFalse(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_LTE));
2476         assertFalse(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_UNKNOWN));
2477 
2478         // all network types unmetered
2479         setUpSubscriptionOverride(TelephonyManager.getAllNetworkTypes(), true);
2480 
2481         assertTrue(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_NR));
2482         assertTrue(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_LTE));
2483         assertTrue(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_UNKNOWN));
2484 
2485         resetSubscriptionOverride();
2486     }
2487 
2488     @Test
testIsNetworkTypeUnmeteredViaSubscriptionPlans()2489     public void testIsNetworkTypeUnmeteredViaSubscriptionPlans() throws Exception {
2490         initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
2491 
2492         // only 5G unmetered
2493         setUpSubscriptionPlans(true);
2494 
2495         assertTrue(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_NR));
2496         assertFalse(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_LTE));
2497         assertFalse(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_UNKNOWN));
2498 
2499         // all network types metered
2500         setUpSubscriptionPlans(false);
2501 
2502         assertFalse(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_NR));
2503         assertFalse(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_LTE));
2504         assertFalse(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_UNKNOWN));
2505 
2506         // all network types unmetered
2507         List<SubscriptionPlan> plans = new ArrayList<>();
2508         plans.add(SubscriptionPlan.Builder
2509                 .createRecurring(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"),
2510                         Period.ofMonths(1))
2511                 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2512                         SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2513                 .build());
2514         replaceInstance(DcTracker.class, "mSubscriptionPlans", mDct, plans);
2515 
2516         assertTrue(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_NR));
2517         assertTrue(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_LTE));
2518         assertTrue(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_UNKNOWN));
2519 
2520         resetSubscriptionPlans();
2521     }
2522 
2523     @Test
testIsNrUnmeteredSubscriptionPlans()2524     public void testIsNrUnmeteredSubscriptionPlans() throws Exception {
2525         initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
2526         int id = setUpDataConnection();
2527         setUpSubscriptionPlans(false);
2528         setUpWatchdogTimer();
2529         doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
2530                 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA))
2531                 .when(mDisplayInfoController).getTelephonyDisplayInfo();
2532         setUpTempNotMetered();
2533 
2534         // NetCapability should be metered when connected to 5G with no unmetered plan or frequency
2535         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
2536         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2537         verify(mDataConnection, times(1)).onMeterednessChanged(false);
2538 
2539         // Set SubscriptionPlans unmetered
2540         setUpSubscriptionPlans(true);
2541 
2542         // NetCapability should switch to unmetered with an unmetered plan
2543         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
2544         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2545         verify(mDataConnection, times(1)).onMeterednessChanged(true);
2546 
2547         // Set MMWAVE frequency to unmetered
2548         mBundle.putBoolean(CarrierConfigManager.KEY_UNMETERED_NR_NSA_MMWAVE_BOOL, true);
2549         Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
2550         intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, mPhone.getPhoneId());
2551         intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, mPhone.getSubId());
2552         mContext.sendBroadcast(intent);
2553         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2554 
2555         // NetCapability should switch to metered without fr=MMWAVE
2556         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
2557         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2558         verify(mDataConnection, times(2)).onMeterednessChanged(false);
2559 
2560         // NetCapability should switch to unmetered with fr=MMWAVE
2561         doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
2562                 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED))
2563                 .when(mDisplayInfoController).getTelephonyDisplayInfo();
2564         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
2565         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2566         verify(mDataConnection, times(2)).onMeterednessChanged(true);
2567 
2568         resetDataConnection(id);
2569         resetSubscriptionPlans();
2570     }
2571 
2572     @Test
testIsNrUnmeteredCarrierConfigs()2573     public void testIsNrUnmeteredCarrierConfigs() throws Exception {
2574         initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
2575         int id = setUpDataConnection();
2576         setUpSubscriptionPlans(false);
2577         setUpWatchdogTimer();
2578         doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
2579                 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA))
2580                 .when(mDisplayInfoController).getTelephonyDisplayInfo();
2581         setUpTempNotMetered();
2582 
2583         // NetCapability should be metered when connected to 5G with no unmetered plan or frequency
2584         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
2585         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2586         verify(mDataConnection, times(1)).onMeterednessChanged(false);
2587 
2588         // Set MMWAVE frequency to unmetered
2589         mBundle.putBoolean(CarrierConfigManager.KEY_UNMETERED_NR_NSA_BOOL, true);
2590         mBundle.putBoolean(CarrierConfigManager.KEY_UNMETERED_NR_NSA_MMWAVE_BOOL, true);
2591         Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
2592         intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, mPhone.getPhoneId());
2593         intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, mPhone.getSubId());
2594         mContext.sendBroadcast(intent);
2595         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2596 
2597         // NetCapability should switch to unmetered when fr=MMWAVE and MMWAVE unmetered
2598         doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
2599                 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED))
2600                 .when(mDisplayInfoController).getTelephonyDisplayInfo();
2601         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
2602         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2603         verify(mDataConnection, times(1)).onMeterednessChanged(true);
2604 
2605         // NetCapability should switch to metered when fr=SUB6 and MMWAVE unmetered
2606         doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
2607                 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA))
2608                 .when(mDisplayInfoController).getTelephonyDisplayInfo();
2609         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
2610         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2611         verify(mDataConnection, times(2)).onMeterednessChanged(false);
2612 
2613         // Set SUB6 frequency to unmetered
2614         doReturn(2).when(mPhone).getSubId();
2615         mBundle.putBoolean(CarrierConfigManager.KEY_UNMETERED_NR_NSA_MMWAVE_BOOL, false);
2616         mBundle.putBoolean(CarrierConfigManager.KEY_UNMETERED_NR_NSA_SUB6_BOOL, true);
2617         intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
2618         intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, mPhone.getPhoneId());
2619         intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, mPhone.getSubId());
2620         mContext.sendBroadcast(intent);
2621         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2622 
2623         // NetCapability should switch to unmetered when fr=SUB6 and SUB6 unmetered
2624         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
2625         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2626         // Data connection is running on a different thread. Have to wait.
2627         waitForMs(200);
2628         verify(mDataConnection, times(2)).onMeterednessChanged(true);
2629 
2630         resetDataConnection(id);
2631         resetSubscriptionPlans();
2632     }
2633 
2634     @Test
testReevaluateUnmeteredConnectionsOnNetworkChange()2635     public void testReevaluateUnmeteredConnectionsOnNetworkChange() throws Exception {
2636         initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
2637         int id = setUpDataConnection();
2638         setUpSubscriptionPlans(true);
2639         setUpWatchdogTimer();
2640         setUpTempNotMetered();
2641 
2642         // NetCapability should be unmetered when connected to 5G
2643         doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
2644                 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA))
2645                 .when(mDisplayInfoController).getTelephonyDisplayInfo();
2646         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
2647         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2648         verify(mDataConnection, times(1)).onMeterednessChanged(true);
2649 
2650         // NetCapability should be metered when disconnected from 5G
2651         doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
2652                 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE))
2653                 .when(mDisplayInfoController).getTelephonyDisplayInfo();
2654         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
2655         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2656         // Data connection is running on a different thread. Have to wait.
2657         waitForMs(200);
2658         verify(mDataConnection, times(1)).onMeterednessChanged(false);
2659 
2660         resetDataConnection(id);
2661         resetSubscriptionPlans();
2662     }
2663 
2664     @Test
testReevaluateUnmeteredConnectionsOnWatchdog()2665     public void testReevaluateUnmeteredConnectionsOnWatchdog() throws Exception {
2666         initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
2667         int id = setUpDataConnection();
2668         setUpSubscriptionPlans(true);
2669         setUpWatchdogTimer();
2670 
2671         // Watchdog inactive when unmetered and not connected to 5G
2672         doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
2673                 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE))
2674                 .when(mDisplayInfoController).getTelephonyDisplayInfo();
2675         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_NR_TIMER_WATCHDOG));
2676         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2677         assertFalse(getWatchdogStatus());
2678 
2679         // Watchdog active when unmetered and connected to 5G
2680         doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
2681                 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA))
2682                 .when(mDisplayInfoController).getTelephonyDisplayInfo();
2683         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
2684         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2685         assertTrue(getWatchdogStatus());
2686 
2687         // Watchdog inactive when metered
2688         setUpSubscriptionPlans(false);
2689         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
2690         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2691         assertFalse(getWatchdogStatus());
2692 
2693         resetDataConnection(id);
2694         resetSubscriptionPlans();
2695     }
2696 
2697     /**
2698      * Test if this is a path prefix match against the given Uri. Verifies that
2699      * scheme, authority, and atomic path segments match.
2700      *
2701      * Copied from frameworks/base/core/java/android/net/Uri.java
2702      */
isPathPrefixMatch(Uri uriA, Uri uriB)2703     private boolean isPathPrefixMatch(Uri uriA, Uri uriB) {
2704         if (!Objects.equals(uriA.getScheme(), uriB.getScheme())) return false;
2705         if (!Objects.equals(uriA.getAuthority(), uriB.getAuthority())) return false;
2706 
2707         List<String> segA = uriA.getPathSegments();
2708         List<String> segB = uriB.getPathSegments();
2709 
2710         final int size = segB.size();
2711         if (segA.size() < size) return false;
2712 
2713         for (int i = 0; i < size; i++) {
2714             if (!Objects.equals(segA.get(i), segB.get(i))) {
2715                 return false;
2716             }
2717         }
2718 
2719         return true;
2720     }
2721 
2722     @Test
testNoApnContextsWhenDataIsDisabled()2723     public void testNoApnContextsWhenDataIsDisabled() throws java.lang.InterruptedException {
2724         //Check that apn contexts are loaded.
2725         assertTrue(mDct.getApnContexts().size() > 0);
2726 
2727         //Do work normally done in teardown.
2728         mDct.removeCallbacksAndMessages(null);
2729         mDcTrackerTestHandler.quit();
2730         mDcTrackerTestHandler.join();
2731 
2732         //Set isDataCapable to false for the new DcTracker being created in DcTrackerTestHandler.
2733         doReturn(false).when(mTelephonyManager).isDataCapable();
2734         mDcTrackerTestHandler = new DcTrackerTestHandler(getClass().getSimpleName());
2735         setReady(false);
2736 
2737         mDcTrackerTestHandler.start();
2738         waitUntilReady();
2739         assertEquals(0, mDct.getApnContexts().size());
2740 
2741         //No need to clean up handler because that work is done in teardown.
2742     }
2743 
2744     @Test
testRatChanged()2745     public void testRatChanged() throws Exception {
2746         DataConnectionReasons dataConnectionReasons = new DataConnectionReasons();
2747         boolean allowed = mDct.isDataAllowed(dataConnectionReasons);
2748         assertFalse(dataConnectionReasons.toString(), allowed);
2749 
2750         logd("Sending EVENT_ENABLE_APN");
2751         // APN id 0 is APN_TYPE_DEFAULT
2752         mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
2753 
2754         sendInitializationEvents();
2755 
2756         dataConnectionReasons = new DataConnectionReasons();
2757         allowed = mDct.isDataAllowed(dataConnectionReasons);
2758         assertTrue(dataConnectionReasons.toString(), allowed);
2759 
2760         ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
2761         // Verify if RIL command was sent properly.
2762         verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
2763                 eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
2764                 eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
2765                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
2766         verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
2767 
2768         verifyDataConnected(FAKE_APN1);
2769 
2770         doReturn(ServiceState.RIL_RADIO_TECHNOLOGY_UMTS).when(mServiceState)
2771                 .getRilDataRadioTechnology();
2772 
2773         logd("Sending EVENT_DATA_RAT_CHANGED");
2774         mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
2775                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_UMTS)
2776                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
2777                 .build();
2778         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
2779                 anyInt(), anyInt());
2780         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_RAT_CHANGED, null));
2781         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2782 
2783         // Data connection is running on a different thread. Have to wait.
2784         waitForMs(200);
2785         // expected tear down all metered DataConnections
2786         verify(mSimulatedCommandsVerifier).deactivateDataCall(
2787                 eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
2788                 any(Message.class));
2789     }
2790 
2791     @Test
testApnConfigRepositoryUpdatedOnCarrierConfigChange()2792     public void testApnConfigRepositoryUpdatedOnCarrierConfigChange() {
2793         assertPriority(ApnSetting.TYPE_CBS_STRING, 2);
2794         assertPriority(ApnSetting.TYPE_MMS_STRING, 2);
2795 
2796         mBundle.putStringArray(CarrierConfigManager.KEY_APN_PRIORITY_STRING_ARRAY,
2797                 new String[] {
2798                         ApnSetting.TYPE_CBS_STRING + ":11",
2799                         ApnSetting.TYPE_MMS_STRING + ":19",
2800                 });
2801 
2802         sendInitializationEvents();
2803 
2804         Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
2805         intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, mPhone.getPhoneId());
2806         intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, mPhone.getSubId());
2807         mContext.sendBroadcast(intent);
2808         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2809 
2810         assertPriority(ApnSetting.TYPE_CBS_STRING, 11);
2811         assertPriority(ApnSetting.TYPE_MMS_STRING, 19);
2812 
2813         //Ensure apns are in sorted order.
2814         ApnContext lastApnContext = null;
2815         for (ApnContext apnContext : mDct.getApnContexts()) {
2816             if (lastApnContext != null) {
2817                 assertTrue(apnContext.getPriority() <= lastApnContext.getPriority());
2818             }
2819             lastApnContext = apnContext;
2820         }
2821     }
2822 
assertPriority(String type, int priority)2823     private void assertPriority(String type, int priority) {
2824         assertEquals(priority, mDct.getApnContexts().stream()
2825                 .filter(x -> x.getApnType().equals(type))
2826                 .findFirst().get().getPriority());
2827     }
2828 
2829     @Test
testProvisionBroadcastReceiver()2830     public void testProvisionBroadcastReceiver() {
2831         Intent intent = new Intent("com.android.internal.telephony.PROVISION");
2832         intent.putExtra("provision.phone.id", mPhone.getPhoneId());
2833         try {
2834             mContext.sendBroadcast(intent);
2835         } catch (SecurityException e) {
2836             fail();
2837         }
2838         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2839     }
2840 
2841     @Test
testRetryHandoverWhenDisconnecting()2842     public void testRetryHandoverWhenDisconnecting() throws Exception {
2843         initApns(ApnSetting.TYPE_IMS_STRING, new String[]{ApnSetting.TYPE_IMS_STRING});
2844         setUpDataConnection();
2845         SparseArray<ApnContext> apnContextsByType = Mockito.mock(SparseArray.class);
2846         ConcurrentHashMap<String, ApnContext> apnContexts = Mockito.mock(ConcurrentHashMap.class);
2847         doReturn(mApnContext).when(apnContextsByType).get(eq(ApnSetting.TYPE_IMS));
2848         doReturn(mApnContext).when(apnContexts).get(eq(ApnSetting.TYPE_IMS_STRING));
2849         doReturn(false).when(mApnContext).isConnectable();
2850         doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
2851         doReturn(DctConstants.State.DISCONNECTING).when(mApnContext).getState();
2852         replaceInstance(DcTracker.class, "mApnContextsByType", mDct, apnContextsByType);
2853         replaceInstance(DcTracker.class, "mApnContexts", mDct, apnContexts);
2854 
2855         sendInitializationEvents();
2856 
2857         logd("Sending EVENT_ENABLE_APN");
2858         // APN id 0 is APN_TYPE_DEFAULT
2859         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_HANDOVER,
2860                 mDct.obtainMessage(12345));
2861         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2862 
2863         assertTrue(isHandoverPending(ApnSetting.TYPE_IMS));
2864 
2865         // Verify no handover request was sent
2866         verify(mDataConnection, never()).bringUp(any(ApnContext.class), anyInt(), anyInt(),
2867                 any(Message.class), anyInt(), anyInt(), anyInt(), anyBoolean());
2868 
2869         doReturn(DctConstants.State.RETRYING).when(mApnContext).getState();
2870         // Data now is disconnected
2871         doReturn(true).when(mApnContext).isConnectable();
2872         doReturn(true).when(mDataEnabledSettings).isDataEnabled(anyInt());
2873         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DISCONNECT_DONE,
2874                 new AsyncResult(Pair.create(mApnContext, 0), null, null)));
2875 
2876         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2877 
2878         verify(mDataConnection).bringUp(any(ApnContext.class), anyInt(), anyInt(),
2879                 any(Message.class), anyInt(), eq(DcTracker.REQUEST_TYPE_HANDOVER), anyInt(),
2880                 anyBoolean());
2881     }
2882 
2883     @Test
testDataUnthrottled()2884     public void testDataUnthrottled() throws Exception {
2885         initApns(ApnSetting.TYPE_IMS_STRING, new String[]{ApnSetting.TYPE_IMS_STRING});
2886         replaceInstance(DcTracker.class, "mDataThrottler", mDct, mDataThrottler);
2887         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
2888         sendInitializationEvents();
2889         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_APN_UNTHROTTLED,
2890                 new AsyncResult(null, FAKE_APN3, null)));
2891         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2892 
2893         verify(mDataThrottler).setRetryTime(
2894                 eq(ApnSetting.TYPE_IMS),
2895                 eq(RetryManager.NO_SUGGESTED_RETRY_DELAY),
2896                 eq(DcTracker.REQUEST_TYPE_NORMAL));
2897     }
2898 
2899     @Test
testDataUnthrottledAfterAPNChanged()2900     public void testDataUnthrottledAfterAPNChanged() throws Exception {
2901         initApns(ApnSetting.TYPE_IMS_STRING, new String[]{ApnSetting.TYPE_IMS_STRING});
2902         replaceInstance(DcTracker.class, "mDataThrottler", mDct, mDataThrottler);
2903 
2904         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
2905         sendInitializationEvents();
2906         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_APN_CHANGED, null));
2907         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2908 
2909         // Verify unthrottling
2910         verify(mDataThrottler, times(2)).reset();
2911     }
2912 
2913     @Test
testDataUnthrottledOnSimStateChanged()2914     public void testDataUnthrottledOnSimStateChanged() throws Exception {
2915         initApns(ApnSetting.TYPE_IMS_STRING, new String[]{ApnSetting.TYPE_IMS_STRING});
2916         replaceInstance(DcTracker.class, "mDataThrottler", mDct, mDataThrottler);
2917 
2918         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
2919         sendInitializationEvents();
2920         sendSimStateUpdated("testDataUnthrottledOnSimStateChanged");
2921 
2922         // Verify unthrottling
2923         verify(mDataThrottler, times(2)).reset();
2924     }
2925 
2926     @Test
testHandlingSecondHandoverRequest()2927     public void testHandlingSecondHandoverRequest() throws Exception {
2928         initApns(ApnSetting.TYPE_IMS_STRING, new String[]{ApnSetting.TYPE_IMS_STRING});
2929         setUpDataConnection();
2930         SparseArray<ApnContext> apnContextsByType = Mockito.mock(SparseArray.class);
2931         ConcurrentHashMap<String, ApnContext> apnContexts = Mockito.mock(ConcurrentHashMap.class);
2932         doReturn(mApnContext).when(apnContextsByType).get(eq(ApnSetting.TYPE_IMS));
2933         doReturn(mApnContext).when(apnContexts).get(eq(ApnSetting.TYPE_IMS_STRING));
2934         doReturn(false).when(mApnContext).isConnectable();
2935         doReturn(DctConstants.State.CONNECTING).when(mApnContext).getState();
2936         replaceInstance(DcTracker.class, "mApnContextsByType", mDct, apnContextsByType);
2937         replaceInstance(DcTracker.class, "mApnContexts", mDct, apnContexts);
2938 
2939         sendInitializationEvents();
2940 
2941         logd("Sending EVENT_ENABLE_APN");
2942         // APN id 0 is APN_TYPE_DEFAULT
2943         Message msg = mDct.obtainMessage(12345);
2944         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_HANDOVER, msg);
2945         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2946         Map<Integer, List<Message>> msgs = getHandoverCompletionMessages();
2947         // Make sure the messages was queued properly instead of fired right away.
2948         assertTrue(msgs.get(ApnSetting.TYPE_IMS).contains(msg));
2949     }
2950 
2951     @Test
testDataThrottledNotAllowData()2952     public void testDataThrottledNotAllowData() throws Exception {
2953         initApns(ApnSetting.TYPE_IMS_STRING, new String[]{ApnSetting.TYPE_IMS_STRING});
2954         replaceInstance(DcTracker.class, "mDataThrottler", mDct, mDataThrottler);
2955         doReturn(SystemClock.elapsedRealtime() + 100000).when(mDataThrottler)
2956                 .getRetryTime(ApnSetting.TYPE_IMS);
2957         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
2958         sendInitializationEvents();
2959 
2960         DataConnectionReasons dataConnectionReasons = new DataConnectionReasons();
2961         boolean allowed = mDct.isDataAllowed(mApnContext, DcTracker.REQUEST_TYPE_NORMAL,
2962                 dataConnectionReasons);
2963         assertFalse(dataConnectionReasons.toString(), allowed);
2964         assertTrue(dataConnectionReasons.contains(DataDisallowedReasonType.DATA_THROTTLED));
2965 
2966         // Makre sure no data setup request
2967         verify(mSimulatedCommandsVerifier, never()).setupDataCall(
2968                 anyInt(), any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(),
2969                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
2970     }
2971 
2972     @Test
testNotifyDataDisconnected()2973     public void testNotifyDataDisconnected() {
2974         // Verify notify data disconnected on DCT constructor, initialized in setUp()
2975         ArgumentCaptor<PreciseDataConnectionState> captor =
2976                 ArgumentCaptor.forClass(PreciseDataConnectionState.class);
2977         verify(mPhone, times(13)).notifyDataConnection(captor.capture());
2978         for (PreciseDataConnectionState state : captor.getAllValues()) {
2979             assertEquals(TelephonyManager.DATA_DISCONNECTED, state.getState());
2980         }
2981     }
2982 
2983     /**
2984      * There is a corresponding test {@link DataConnectionTest#testDataServiceTempUnavailable()} to
2985      * test DataConnection behavior.
2986      */
2987     @Test
testDataServiceTempUnavailable()2988     public void testDataServiceTempUnavailable() {
2989         Handler handler = Mockito.mock(Handler.class);
2990         Message handoverCompleteMessage = Message.obtain(handler);
2991         addHandoverCompleteMsg(handoverCompleteMessage, ApnSetting.TYPE_IMS);
2992         initApns(ApnSetting.TYPE_IMS_STRING, new String[]{ApnSetting.TYPE_IMS_STRING});
2993         mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_SETUP_COMPLETE,
2994                 DcTracker.REQUEST_TYPE_HANDOVER, DataCallResponse.HANDOVER_FAILURE_MODE_UNKNOWN,
2995                 new AsyncResult(Pair.create(mApnContext, 0),
2996                         DataFailCause.SERVICE_TEMPORARILY_UNAVAILABLE, new Exception())));
2997         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
2998         // Ensure handover is not completed yet
2999         verify(handler, never()).sendMessageDelayed(any(), anyLong());
3000     }
3001 
3002     @Test
testNormalRequestDoesNotFailHandoverRequest()3003     public void testNormalRequestDoesNotFailHandoverRequest() {
3004         Handler handler = Mockito.mock(Handler.class);
3005         Message handoverCompleteMessage = Message.obtain(handler);
3006         addHandoverCompleteMsg(handoverCompleteMessage, ApnSetting.TYPE_IMS);
3007         initApns(ApnSetting.TYPE_IMS_STRING, new String[]{ApnSetting.TYPE_IMS_STRING});
3008         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
3009         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
3010         // Ensure handover is not completed yet
3011         verify(handler, never()).sendMessageDelayed(any(), anyLong());
3012     }
3013 
3014     @Test
testPreferenceChangedFallback()3015     public void testPreferenceChangedFallback() {
3016         Handler handler = Mockito.mock(Handler.class);
3017         doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WLAN).when(mTransportManager)
3018                 .getPreferredTransport(anyInt());
3019         Message handoverCompleteMessage = Message.obtain(handler);
3020         addHandoverCompleteMsg(handoverCompleteMessage, ApnSetting.TYPE_IMS);
3021         initApns(ApnSetting.TYPE_IMS_STRING, new String[]{ApnSetting.TYPE_IMS_STRING});
3022         mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_HANDOVER,
3023                 handoverCompleteMessage);
3024         waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
3025         Bundle bundle = handoverCompleteMessage.getData();
3026         assertTrue(bundle.getBoolean("extra_handover_failure_fallback"));
3027     }
3028 }
3029