1 /*
2  * Copyright 2021 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.data;
18 
19 import static android.telephony.TelephonyManager.HAL_SERVICE_DATA;
20 
21 import static com.android.internal.telephony.data.DataNetworkController.DataNetworkControllerCallback;
22 import static com.android.internal.telephony.data.DataNetworkController.NetworkRequestList;
23 
24 import static com.google.common.truth.Truth.assertThat;
25 import static com.google.common.truth.Truth.assertWithMessage;
26 
27 import static org.junit.Assert.assertEquals;
28 import static org.junit.Assert.assertFalse;
29 import static org.junit.Assert.assertSame;
30 import static org.junit.Assert.assertThrows;
31 import static org.junit.Assert.assertTrue;
32 import static org.junit.Assert.fail;
33 import static org.mockito.ArgumentMatchers.any;
34 import static org.mockito.ArgumentMatchers.anyBoolean;
35 import static org.mockito.ArgumentMatchers.anyInt;
36 import static org.mockito.ArgumentMatchers.anyString;
37 import static org.mockito.ArgumentMatchers.eq;
38 import static org.mockito.Mockito.clearInvocations;
39 import static org.mockito.Mockito.doAnswer;
40 import static org.mockito.Mockito.doReturn;
41 import static org.mockito.Mockito.never;
42 import static org.mockito.Mockito.times;
43 import static org.mockito.Mockito.verify;
44 import static org.mockito.Mockito.when;
45 
46 import android.annotation.NonNull;
47 import android.net.ConnectivityManager;
48 import android.net.InetAddresses;
49 import android.net.LinkAddress;
50 import android.net.LinkProperties;
51 import android.net.NetworkCapabilities;
52 import android.net.NetworkPolicyManager;
53 import android.net.NetworkRequest;
54 import android.net.Uri;
55 import android.net.vcn.VcnManager.VcnNetworkPolicyChangeListener;
56 import android.net.vcn.VcnNetworkPolicyResult;
57 import android.os.AsyncResult;
58 import android.os.Handler;
59 import android.os.Looper;
60 import android.os.Message;
61 import android.os.PersistableBundle;
62 import android.os.RegistrantList;
63 import android.provider.Telephony;
64 import android.telephony.AccessNetworkConstants;
65 import android.telephony.AccessNetworkConstants.AccessNetworkType;
66 import android.telephony.AccessNetworkConstants.TransportType;
67 import android.telephony.Annotation;
68 import android.telephony.Annotation.DataFailureCause;
69 import android.telephony.Annotation.NetCapability;
70 import android.telephony.Annotation.NetworkType;
71 import android.telephony.CarrierConfigManager;
72 import android.telephony.DataFailCause;
73 import android.telephony.DataSpecificRegistrationInfo;
74 import android.telephony.LteVopsSupportInfo;
75 import android.telephony.NetworkRegistrationInfo;
76 import android.telephony.NetworkRegistrationInfo.RegistrationState;
77 import android.telephony.PreciseDataConnectionState;
78 import android.telephony.ServiceState;
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.DataCallResponse.LinkStatus;
87 import android.telephony.data.DataProfile;
88 import android.telephony.data.DataService;
89 import android.telephony.data.DataServiceCallback;
90 import android.telephony.data.ThrottleStatus;
91 import android.telephony.data.TrafficDescriptor;
92 import android.telephony.data.TrafficDescriptor.OsAppId;
93 import android.telephony.ims.ImsManager;
94 import android.telephony.ims.ImsMmTelManager;
95 import android.telephony.ims.ImsRcsManager;
96 import android.telephony.ims.ImsReasonInfo;
97 import android.telephony.ims.ImsRegistrationAttributes;
98 import android.telephony.ims.ImsStateCallback;
99 import android.telephony.ims.RegistrationManager.RegistrationCallback;
100 import android.telephony.ims.feature.ImsFeature;
101 import android.telephony.ims.stub.ImsRegistrationImplBase;
102 import android.testing.AndroidTestingRunner;
103 import android.testing.TestableLooper;
104 import android.util.ArraySet;
105 import android.util.SparseArray;
106 
107 import com.android.internal.telephony.ISub;
108 import com.android.internal.telephony.MultiSimSettingController;
109 import com.android.internal.telephony.Phone;
110 import com.android.internal.telephony.PhoneConstants;
111 import com.android.internal.telephony.PhoneFactory;
112 import com.android.internal.telephony.RIL;
113 import com.android.internal.telephony.TelephonyTest;
114 import com.android.internal.telephony.data.AccessNetworksManager.AccessNetworksManagerCallback;
115 import com.android.internal.telephony.data.DataEvaluation.DataDisallowedReason;
116 import com.android.internal.telephony.data.DataNetworkController.HandoverRule;
117 import com.android.internal.telephony.data.DataRetryManager.DataRetryManagerCallback;
118 import com.android.internal.telephony.data.LinkBandwidthEstimator.LinkBandwidthEstimatorCallback;
119 import com.android.internal.telephony.flags.FeatureFlags;
120 import com.android.internal.telephony.ims.ImsResolver;
121 import com.android.internal.telephony.subscription.SubscriptionInfoInternal;
122 
123 import org.junit.After;
124 import org.junit.Before;
125 import org.junit.Test;
126 import org.junit.runner.RunWith;
127 import org.mockito.ArgumentCaptor;
128 import org.mockito.Mockito;
129 
130 import java.lang.reflect.Field;
131 import java.time.Period;
132 import java.time.ZonedDateTime;
133 import java.util.ArrayList;
134 import java.util.Arrays;
135 import java.util.Collections;
136 import java.util.HashMap;
137 import java.util.List;
138 import java.util.Map;
139 import java.util.Set;
140 import java.util.concurrent.Executor;
141 
142 import javax.annotation.Nullable;
143 
144 @RunWith(AndroidTestingRunner.class)
145 @TestableLooper.RunWithLooper
146 public class DataNetworkControllerTest extends TelephonyTest {
147     private static final String IPV4_ADDRESS = "10.0.2.15";
148     private static final String IPV6_ADDRESS = "2607:fb90:a620:651d:eabe:f8da:c107:44be";
149 
150     private static final String FAKE_MMTEL_PACKAGE = "fake.mmtel.package";
151     private static final String FAKE_RCS_PACKAGE = "fake.rcs.package";
152 
153     // Events
154     private static final int EVENT_SIM_STATE_CHANGED = 9;
155     private static final int EVENT_REEVALUATE_EXISTING_DATA_NETWORKS = 16;
156     private static final int EVENT_SERVICE_STATE_CHANGED = 17;
157     private static final int EVENT_VOICE_CALL_ENDED = 18;
158     private static final int EVENT_SUBSCRIPTION_OVERRIDE = 23;
159 
160     // Mocked classes
161     private PhoneSwitcher mMockedPhoneSwitcher;
162     protected ISub mMockedIsub;
163     private DataNetworkControllerCallback mMockedDataNetworkControllerCallback;
164     private DataRetryManagerCallback mMockedDataRetryManagerCallback;
165     private ImsResolver mMockedImsResolver;
166     private DataStallRecoveryManager mMockedDataStallRecoveryManager;
167     private ImsManager mMockedImsManager;
168     private ImsMmTelManager mMockedImsMmTelManager;
169     private ImsRcsManager mMockedImsRcsManager;
170     private ImsStateCallback mMmtelStateCallback;
171     private ImsStateCallback mRcsStateCallback;
172     private RegistrationCallback mMmtelRegCallback;
173     private RegistrationCallback mRcsRegCallback;
174     private SubscriptionInfo mMockSubInfo;
175 
176     private int mNetworkRequestId = 0;
177 
178     private final SparseArray<DataServiceManager> mMockedDataServiceManagers = new SparseArray<>();
179     private final SparseArray<RegistrantList> mDataCallListChangedRegistrants = new SparseArray<>();
180     private DataNetworkController mDataNetworkControllerUT;
181     private PersistableBundle mCarrierConfig;
182     private CarrierConfigManager.CarrierConfigChangeListener mCarrierConfigChangeListener;
183 
184     private AccessNetworksManagerCallback mAccessNetworksManagerCallback;
185     private LinkBandwidthEstimatorCallback mLinkBandwidthEstimatorCallback;
186 
187     private boolean mIsNonTerrestrialNetwork = false;
188 
189     private final DataProfile mGeneralPurposeDataProfile = new DataProfile.Builder()
190             .setApnSetting(new ApnSetting.Builder()
191                     .setId(2163)
192                     .setOperatorNumeric("12345")
193                     .setEntryName("internet_supl_mms_apn")
194                     .setApnName("internet_supl_mms_apn")
195                     .setUser("user")
196                     .setPassword("passwd")
197                     .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT | ApnSetting.TYPE_SUPL
198                             | ApnSetting.TYPE_MMS)
199                     .setProtocol(ApnSetting.PROTOCOL_IPV6)
200                     .setRoamingProtocol(ApnSetting.PROTOCOL_IP)
201                     .setCarrierEnabled(true)
202                     .setNetworkTypeBitmask((int) (TelephonyManager.NETWORK_TYPE_BITMASK_LTE
203                             | TelephonyManager.NETWORK_TYPE_BITMASK_NR
204                             | TelephonyManager.NETWORK_TYPE_BITMASK_IWLAN
205                             | TelephonyManager.NETWORK_TYPE_BITMASK_1xRTT))
206                     .setLingeringNetworkTypeBitmask((int) (TelephonyManager.NETWORK_TYPE_BITMASK_LTE
207                             | TelephonyManager.NETWORK_TYPE_BITMASK_1xRTT
208                             | TelephonyManager.NETWORK_TYPE_BITMASK_UMTS
209                             | TelephonyManager.NETWORK_TYPE_BITMASK_NR))
210                     .setProfileId(1234)
211                     .setMaxConns(321)
212                     .setWaitTime(456)
213                     .setMaxConnsTime(789)
214                     .setInfrastructureBitmask(ApnSetting.INFRASTRUCTURE_SATELLITE
215                             | ApnSetting.INFRASTRUCTURE_CELLULAR)
216                     .build())
217             .setPreferred(false)
218             .build();
219 
220     // The same data profile but with different auto generated ID, should be considered the same as
221     // mGeneralPurposeDataProfile
222     private final DataProfile mDuplicatedGeneralPurposeDataProfile = new DataProfile.Builder()
223             .setApnSetting(new ApnSetting.Builder()
224                     .setId(3612)
225                     .setOperatorNumeric("12345")
226                     .setEntryName("internet_supl_mms_apn")
227                     .setApnName("internet_supl_mms_apn")
228                     .setUser("user")
229                     .setPassword("passwd")
230                     .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT | ApnSetting.TYPE_SUPL
231                             | ApnSetting.TYPE_MMS)
232                     .setProtocol(ApnSetting.PROTOCOL_IPV6)
233                     .setRoamingProtocol(ApnSetting.PROTOCOL_IP)
234                     .setCarrierEnabled(true)
235                     .setNetworkTypeBitmask((int) (TelephonyManager.NETWORK_TYPE_BITMASK_LTE
236                             | TelephonyManager.NETWORK_TYPE_BITMASK_IWLAN
237                             | TelephonyManager.NETWORK_TYPE_BITMASK_1xRTT))
238                     .setLingeringNetworkTypeBitmask((int) (TelephonyManager.NETWORK_TYPE_BITMASK_LTE
239                             | TelephonyManager.NETWORK_TYPE_BITMASK_1xRTT
240                             | TelephonyManager.NETWORK_TYPE_BITMASK_UMTS
241                             | TelephonyManager.NETWORK_TYPE_BITMASK_NR))
242                     .setProfileId(1234)
243                     .setMaxConns(321)
244                     .setWaitTime(456)
245                     .setMaxConnsTime(789)
246                     .build())
247             .setPreferred(false)
248             .build();
249 
250     // Created to test preferred data profiles that apply to different network types
251     private final DataProfile mGeneralPurposeDataProfileAlternative = new DataProfile.Builder()
252             .setApnSetting(new ApnSetting.Builder()
253                     .setId(2161)
254                     .setOperatorNumeric("12345")
255                     .setEntryName("internet_supl_mms_apn")
256                     .setApnName("internet_supl_mms_apn")
257                     .setUser("user")
258                     .setPassword("passwd")
259                     .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT | ApnSetting.TYPE_SUPL
260                             | ApnSetting.TYPE_MMS)
261                     .setProtocol(ApnSetting.PROTOCOL_IPV6)
262                     .setRoamingProtocol(ApnSetting.PROTOCOL_IP)
263                     .setCarrierEnabled(true)
264                     .setNetworkTypeBitmask((int) (TelephonyManager.NETWORK_TYPE_BITMASK_LTE
265                             | TelephonyManager.NETWORK_TYPE_BITMASK_NR
266                             | TelephonyManager.NETWORK_TYPE_BITMASK_IWLAN
267                             | TelephonyManager.NETWORK_TYPE_BITMASK_1xRTT))
268                     .setLingeringNetworkTypeBitmask((int) (TelephonyManager.NETWORK_TYPE_BITMASK_LTE
269                             | TelephonyManager.NETWORK_TYPE_BITMASK_1xRTT
270                             | TelephonyManager.NETWORK_TYPE_BITMASK_UMTS
271                             | TelephonyManager.NETWORK_TYPE_BITMASK_NR))
272                     .setProfileId(4321)
273                     .setMaxConns(321)
274                     .setWaitTime(456)
275                     .setMaxConnsTime(789)
276                     .build())
277             .setPreferred(false)
278             .build();
279 
280     private final DataProfile mImsCellularDataProfile = new DataProfile.Builder()
281             .setApnSetting(new ApnSetting.Builder()
282                     .setId(2164)
283                     .setOperatorNumeric("12345")
284                     .setEntryName("ims_apn")
285                     .setApnName("ims_apn")
286                     .setUser("user")
287                     .setPassword("passwd")
288                     .setApnTypeBitmask(ApnSetting.TYPE_IMS)
289                     .setProtocol(ApnSetting.PROTOCOL_IPV6)
290                     .setRoamingProtocol(ApnSetting.PROTOCOL_IP)
291                     .setCarrierEnabled(true)
292                     .setNetworkTypeBitmask((int) (TelephonyManager.NETWORK_TYPE_BITMASK_LTE
293                             | TelephonyManager.NETWORK_TYPE_BITMASK_1xRTT))
294                     .setLingeringNetworkTypeBitmask((int) (TelephonyManager.NETWORK_TYPE_BITMASK_LTE
295                             | TelephonyManager.NETWORK_TYPE_BITMASK_1xRTT
296                             | TelephonyManager.NETWORK_TYPE_BITMASK_IWLAN
297                             | TelephonyManager.NETWORK_TYPE_BITMASK_UMTS
298                             | TelephonyManager.NETWORK_TYPE_BITMASK_NR))
299                     .setProfileId(1235)
300                     .setMaxConns(321)
301                     .setWaitTime(456)
302                     .setMaxConnsTime(789)
303                     .build())
304             .setPreferred(false)
305             .build();
306 
307     private final DataProfile mImsIwlanDataProfile = new DataProfile.Builder()
308             .setApnSetting(new ApnSetting.Builder()
309                     .setId(2164)
310                     .setOperatorNumeric("12345")
311                     .setEntryName("ims_apn")
312                     .setApnName("ims_apn")
313                     .setUser("user")
314                     .setPassword("passwd")
315                     .setApnTypeBitmask(ApnSetting.TYPE_IMS)
316                     .setProtocol(ApnSetting.PROTOCOL_IPV6)
317                     .setRoamingProtocol(ApnSetting.PROTOCOL_IPV6)
318                     .setCarrierEnabled(true)
319                     .setNetworkTypeBitmask((int) (TelephonyManager.NETWORK_TYPE_BITMASK_IWLAN))
320                     .setProfileId(1235)
321                     .setMaxConns(321)
322                     .setWaitTime(456)
323                     .setMaxConnsTime(789)
324                     .build())
325             .setPreferred(false)
326             .build();
327 
328     private final DataProfile mEmergencyDataProfile = new DataProfile.Builder()
329             .setApnSetting(new ApnSetting.Builder()
330                     .setEntryName("DEFAULT EIMS")
331                     .setId(2165)
332                     .setProtocol(ApnSetting.PROTOCOL_IPV4V6)
333                     .setRoamingProtocol(ApnSetting.PROTOCOL_IPV4V6)
334                     .setApnName("sos")
335                     .setApnTypeBitmask(ApnSetting.TYPE_EMERGENCY)
336                     .setCarrierEnabled(true)
337                     .setApnSetId(Telephony.Carriers.MATCH_ALL_APN_SET_ID)
338                     .build())
339             .build();
340 
341     private final DataProfile mFotaDataProfile = new DataProfile.Builder()
342             .setApnSetting(new ApnSetting.Builder()
343                     .setId(2166)
344                     .setOperatorNumeric("12345")
345                     .setEntryName("fota_apn")
346                     .setApnName("fota_apn")
347                     .setUser("user")
348                     .setPassword("passwd")
349                     .setApnTypeBitmask(ApnSetting.TYPE_FOTA)
350                     .setProtocol(ApnSetting.PROTOCOL_IPV6)
351                     .setRoamingProtocol(ApnSetting.PROTOCOL_IP)
352                     .setCarrierEnabled(true)
353                     .setNetworkTypeBitmask((int) TelephonyManager.NETWORK_TYPE_BITMASK_LTE
354                             | (int) TelephonyManager.NETWORK_TYPE_BITMASK_1xRTT)
355                     .setProfileId(1236)
356                     .setMaxConns(321)
357                     .setWaitTime(456)
358                     .setMaxConnsTime(789)
359                     .build())
360             .setPreferred(false)
361             .build();
362 
363     private final DataProfile mTetheringDataProfile = new DataProfile.Builder()
364             .setApnSetting(new ApnSetting.Builder()
365                     .setId(2167)
366                     .setOperatorNumeric("12345")
367                     .setEntryName("dun_apn")
368                     .setApnName("dun_apn")
369                     .setUser("user")
370                     .setPassword("passwd")
371                     .setApnTypeBitmask(ApnSetting.TYPE_DUN | ApnSetting.TYPE_DEFAULT)
372                     .setProtocol(ApnSetting.PROTOCOL_IPV6)
373                     .setRoamingProtocol(ApnSetting.PROTOCOL_IP)
374                     .setCarrierEnabled(true)
375                     .setNetworkTypeBitmask((int) TelephonyManager.NETWORK_TYPE_BITMASK_LTE
376                             | (int) TelephonyManager.NETWORK_TYPE_BITMASK_1xRTT)
377                     .setProfileId(1236)
378                     .setMaxConns(321)
379                     .setWaitTime(456)
380                     .setMaxConnsTime(789)
381                     .build())
382             .setPreferred(false)
383             .build();
384 
385     private final DataProfile mEnterpriseDataProfile = new DataProfile.Builder()
386             .setTrafficDescriptor(new TrafficDescriptor(null,
387                     new TrafficDescriptor.OsAppId(TrafficDescriptor.OsAppId.ANDROID_OS_ID,
388                             "ENTERPRISE", 1).getBytes()))
389             .build();
390 
391     private final DataProfile mLowLatencyDataProfile = new DataProfile.Builder()
392             .setTrafficDescriptor(new TrafficDescriptor(null,
393                     new TrafficDescriptor.OsAppId(TrafficDescriptor.OsAppId.ANDROID_OS_ID,
394                             "PRIORITIZE_LATENCY", 1).getBytes()))
395             .build();
396 
397     private final DataProfile mNtnDataProfile = new DataProfile.Builder()
398             .setApnSetting(new ApnSetting.Builder()
399                     .setEntryName("ntn")
400                     .setApnName("ntn")
401                     .setApnTypeBitmask(ApnSetting.TYPE_RCS)
402                     .setCarrierEnabled(true)
403                     .setInfrastructureBitmask(ApnSetting.INFRASTRUCTURE_SATELLITE)
404                     .build())
405             .setPreferred(false)
406             .build();
407 
408     private final DataProfile mEsimBootstrapDataProfile = new DataProfile.Builder()
409             .setApnSetting(new ApnSetting.Builder()
410                     .setEntryName("ESIM BOOTSTRAP")
411                     .setApnName("ESIM BOOTSTRAP")
412                     .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
413                     .setNetworkTypeBitmask((int) TelephonyManager.NETWORK_TYPE_BITMASK_LTE
414                             | (int) TelephonyManager.NETWORK_TYPE_BITMASK_NR)
415                     .setCarrierEnabled(true)
416                     .setEsimBootstrapProvisioning(true)
417                     .build())
418             .setPreferred(false)
419             .build();
420 
421     private final DataProfile mEsimBootstrapImsProfile = new DataProfile.Builder()
422             .setApnSetting(new ApnSetting.Builder()
423                     .setEntryName("IMS BOOTSTRAP")
424                     .setApnName("IMS BOOTSTRAP")
425                     .setApnTypeBitmask(ApnSetting.TYPE_IMS)
426                     .setNetworkTypeBitmask((int) TelephonyManager.NETWORK_TYPE_BITMASK_LTE
427                             | (int) TelephonyManager.NETWORK_TYPE_BITMASK_NR)
428                     .setCarrierEnabled(true)
429                     .setEsimBootstrapProvisioning(true)
430                     .build())
431             .setPreferred(false)
432             .build();
433 
434     private final DataProfile mEsimBootstrapRcsInfraStructureProfile =
435             new DataProfile.Builder()
436             .setApnSetting(new ApnSetting.Builder()
437                     .setEntryName("INFRASTRUCTURE BOOTSTRAP")
438                     .setApnName("INFRASTRUCTURE BOOTSTRAP")
439                     .setApnTypeBitmask(ApnSetting.TYPE_RCS)
440                     .setNetworkTypeBitmask((int) TelephonyManager.NETWORK_TYPE_BITMASK_LTE
441                             | (int) TelephonyManager.NETWORK_TYPE_BITMASK_NR)
442                     .setCarrierEnabled(true)
443                     .setInfrastructureBitmask(2)
444                     .setEsimBootstrapProvisioning(true)
445                     .build())
446             .setPreferred(false)
447             .build();
448 
449     /** Data call response map. The first key is the transport type, the second key is the cid. */
450     private final Map<Integer, Map<Integer, DataCallResponse>> mDataCallResponses = new HashMap<>();
451 
createDataCallResponse(int cid, @LinkStatus int linkStatus)452     private @NonNull DataCallResponse createDataCallResponse(int cid, @LinkStatus int linkStatus) {
453         return createDataCallResponse(cid, linkStatus, Collections.emptyList());
454     }
455 
createDataCallResponse(int cid, @LinkStatus int linkStatus, @NonNull List<TrafficDescriptor> tdList)456     private @NonNull DataCallResponse createDataCallResponse(int cid, @LinkStatus int linkStatus,
457             @NonNull List<TrafficDescriptor> tdList) {
458         return new DataCallResponse.Builder()
459                 .setCause(0)
460                 .setRetryDurationMillis(-1L)
461                 .setId(cid)
462                 .setLinkStatus(linkStatus)
463                 .setProtocolType(ApnSetting.PROTOCOL_IPV4V6)
464                 .setInterfaceName("ifname" + cid)
465                 .setAddresses(Arrays.asList(
466                         new LinkAddress(InetAddresses.parseNumericAddress(IPV4_ADDRESS), 32),
467                         new LinkAddress(IPV6_ADDRESS + "/64")))
468                 .setDnsAddresses(Arrays.asList(InetAddresses.parseNumericAddress("10.0.2.3"),
469                         InetAddresses.parseNumericAddress("fd00:976a::9")))
470                 .setGatewayAddresses(Arrays.asList(
471                         InetAddresses.parseNumericAddress("10.0.2.15"),
472                         InetAddresses.parseNumericAddress("fe80::2")))
473                 .setPcscfAddresses(Arrays.asList(
474                         InetAddresses.parseNumericAddress("fd00:976a:c305:1d::8"),
475                         InetAddresses.parseNumericAddress("fd00:976a:c202:1d::7"),
476                         InetAddresses.parseNumericAddress("fd00:976a:c305:1d::5")))
477                 .setMtu(1500)
478                 .setMtuV4(1500)
479                 .setMtuV6(1500)
480                 .setPduSessionId(1)
481                 .setQosBearerSessions(new ArrayList<>())
482                 .setTrafficDescriptors(tdList)
483                 .build();
484     }
485 
setFailedSetupDataResponse(DataServiceManager dsm, @DataFailureCause int cause, long retryMillis, boolean forHandover)486     private void setFailedSetupDataResponse(DataServiceManager dsm, @DataFailureCause int cause,
487             long retryMillis, boolean forHandover) {
488         setFailedSetupDataResponse(dsm, cause, retryMillis, forHandover, 0);
489     }
490 
setFailedSetupDataResponse(DataServiceManager dsm, @DataFailureCause int cause, long retryMillis, boolean forHandover, long delay)491     private void setFailedSetupDataResponse(DataServiceManager dsm, @DataFailureCause int cause,
492             long retryMillis, boolean forHandover, long delay) {
493         doAnswer(invocation -> {
494             final Message msg = (Message) invocation.getArguments()[10];
495 
496             DataCallResponse response = new DataCallResponse.Builder()
497                     .setCause(cause)
498                     .setRetryDurationMillis(retryMillis)
499                     .setHandoverFailureMode(
500                             DataCallResponse.HANDOVER_FAILURE_MODE_NO_FALLBACK_RETRY_HANDOVER)
501                     .build();
502             msg.getData().putParcelable("data_call_response", response);
503             msg.arg1 = DataServiceCallback.RESULT_SUCCESS;
504             msg.getTarget().sendMessageDelayed(msg, delay);
505             return null;
506         }).when(dsm).setupDataCall(anyInt(), any(DataProfile.class), anyBoolean(),
507                 anyBoolean(), forHandover ? eq(DataService.REQUEST_REASON_HANDOVER)
508                         : eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), any(),
509                 anyBoolean(), any(Message.class));
510     }
511 
setSuccessfulSetupDataResponse(DataServiceManager dsm, DataCallResponse response)512     private void setSuccessfulSetupDataResponse(DataServiceManager dsm, DataCallResponse response) {
513         doAnswer(invocation -> {
514             final Message msg = (Message) invocation.getArguments()[10];
515 
516             int transport = AccessNetworkConstants.TRANSPORT_TYPE_INVALID;
517             if (dsm == mMockedWwanDataServiceManager) {
518                 transport = AccessNetworkConstants.TRANSPORT_TYPE_WWAN;
519             } else if (dsm == mMockedWlanDataServiceManager) {
520                 transport = AccessNetworkConstants.TRANSPORT_TYPE_WLAN;
521             }
522             mDataCallResponses.computeIfAbsent(transport, v -> new HashMap<>());
523             mDataCallResponses.get(transport).put(response.getId(), response);
524             msg.getData().putParcelable("data_call_response", response);
525             msg.arg1 = DataServiceCallback.RESULT_SUCCESS;
526             msg.sendToTarget();
527 
528             mDataCallListChangedRegistrants.get(transport).notifyRegistrants(
529                     new AsyncResult(transport, new ArrayList<>(mDataCallResponses.get(
530                             transport).values()), null));
531             return null;
532         }).when(dsm).setupDataCall(anyInt(), any(DataProfile.class), anyBoolean(),
533                 anyBoolean(), anyInt(), any(), anyInt(), any(), any(), anyBoolean(),
534                 any(Message.class));
535     }
536 
setSuccessfulSetupDataResponse(DataServiceManager dsm, int cid)537     private void setSuccessfulSetupDataResponse(DataServiceManager dsm, int cid) {
538         setSuccessfulSetupDataResponse(dsm, cid, 0L);
539     }
540 
setSuccessfulSetupDataResponse(DataServiceManager dsm, int cid, long delay)541     private void setSuccessfulSetupDataResponse(DataServiceManager dsm, int cid, long delay) {
542         doAnswer(invocation -> {
543             final Message msg = (Message) invocation.getArguments()[10];
544 
545             DataCallResponse response = createDataCallResponse(cid,
546                     DataCallResponse.LINK_STATUS_ACTIVE);
547             int transport = AccessNetworkConstants.TRANSPORT_TYPE_INVALID;
548             if (dsm == mMockedWwanDataServiceManager) {
549                 transport = AccessNetworkConstants.TRANSPORT_TYPE_WWAN;
550             } else if (dsm == mMockedWlanDataServiceManager) {
551                 transport = AccessNetworkConstants.TRANSPORT_TYPE_WLAN;
552             }
553             mDataCallResponses.computeIfAbsent(transport, v -> new HashMap<>());
554             mDataCallResponses.get(transport).put(cid, response);
555             msg.getData().putParcelable("data_call_response", response);
556             msg.arg1 = DataServiceCallback.RESULT_SUCCESS;
557             msg.getTarget().sendMessageDelayed(msg, delay);
558 
559             final int t = transport;
560             msg.getTarget().postDelayed(() -> {
561                 mDataCallListChangedRegistrants.get(t).notifyRegistrants(
562                         new AsyncResult(t, new ArrayList<>(mDataCallResponses.get(
563                                 t).values()), null));
564 
565             }, delay + 100);
566             return null;
567         }).when(dsm).setupDataCall(anyInt(), any(DataProfile.class), anyBoolean(),
568                 anyBoolean(), anyInt(), any(), anyInt(), any(), any(), anyBoolean(),
569                 any(Message.class));
570     }
571 
clearCallbacks()572     private void clearCallbacks() throws Exception {
573         Field field = DataNetworkController.class
574                 .getDeclaredField("mDataNetworkControllerCallbacks");
575         field.setAccessible(true);
576         ((Set<DataNetworkControllerCallback>) field.get(mDataNetworkControllerUT)).clear();
577     }
578 
carrierConfigChanged()579     private void carrierConfigChanged() {
580         // Trigger carrier config reloading
581         mCarrierConfigChangeListener.onCarrierConfigChanged(0 /* logicalSlotIndex */,
582                 SubscriptionManager.INVALID_SUBSCRIPTION_ID,
583                 TelephonyManager.UNKNOWN_CARRIER_ID, TelephonyManager.UNKNOWN_CARRIER_ID);
584 
585         processAllMessages();
586     }
587 
setImsRegistered(boolean registered)588     private void setImsRegistered(boolean registered) {
589         if (registered) {
590             final ArraySet<String> features = new ArraySet<>();
591             features.add("feature1");
592             features.add("feature2");
593             ImsRegistrationAttributes attr = new ImsRegistrationAttributes.Builder(
594                     ImsRegistrationImplBase.REGISTRATION_TECH_LTE).setFeatureTags(features).build();
595 
596             mMmtelRegCallback.onRegistered(attr);
597         } else {
598             ImsReasonInfo info = new ImsReasonInfo(ImsReasonInfo.CODE_LOCAL_ILLEGAL_STATE, -1, "");
599             mMmtelRegCallback.onUnregistered(info);
600         }
601     }
602 
setRcsRegistered(boolean registered)603     private void setRcsRegistered(boolean registered) {
604         if (registered) {
605             final ArraySet<String> features = new ArraySet<>();
606             features.add("feature1");
607             features.add("feature2");
608             ImsRegistrationAttributes attr = new ImsRegistrationAttributes.Builder(
609                     ImsRegistrationImplBase.REGISTRATION_TECH_LTE).setFeatureTags(features).build();
610 
611             mRcsRegCallback.onRegistered(attr);
612         } else {
613             ImsReasonInfo info = new ImsReasonInfo(ImsReasonInfo.CODE_LOCAL_ILLEGAL_STATE, -1, "");
614             mRcsRegCallback.onUnregistered(info);
615         }
616     }
617 
serviceStateChanged(@etworkType int networkType, @RegistrationState int regState)618     private void serviceStateChanged(@NetworkType int networkType,
619             @RegistrationState int regState) {
620         DataSpecificRegistrationInfo dsri = new DataSpecificRegistrationInfo.Builder(8)
621                 .setNrAvailable(true)
622                 .setEnDcAvailable(true)
623                 .setVopsSupportInfo(new LteVopsSupportInfo(
624                         LteVopsSupportInfo.LTE_STATUS_SUPPORTED,
625                         LteVopsSupportInfo.LTE_STATUS_SUPPORTED))
626                 .build();
627 
628         serviceStateChanged(networkType, regState, regState,
629                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, dsri);
630     }
631 
serviceStateChanged(@etworkType int networkType, @RegistrationState int regState, DataSpecificRegistrationInfo dsri)632     private void serviceStateChanged(@NetworkType int networkType,
633             @RegistrationState int regState, DataSpecificRegistrationInfo dsri) {
634         serviceStateChanged(networkType, regState, regState,
635                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, dsri);
636     }
637 
serviceStateChanged(@etworkType int networkType, @RegistrationState int dataRegState, @RegistrationState int voiceRegState, @RegistrationState int iwlanRegState, DataSpecificRegistrationInfo dsri)638     private void serviceStateChanged(@NetworkType int networkType,
639             @RegistrationState int dataRegState, @RegistrationState int voiceRegState,
640             @RegistrationState int iwlanRegState, DataSpecificRegistrationInfo dsri) {
641         boolean isEmergencyOnly = false;
642         if (dataRegState == NetworkRegistrationInfo.REGISTRATION_STATE_DENIED) {
643             isEmergencyOnly = true;
644         }
645         ServiceState ss = createSS(networkType, networkType, dataRegState, voiceRegState,
646                 iwlanRegState, dsri, isEmergencyOnly);
647 
648         doReturn(ss).when(mSST).getServiceState();
649         doReturn(ss).when(mPhone).getServiceState();
650 
651         mDataNetworkControllerUT.obtainMessage(17/*EVENT_SERVICE_STATE_CHANGED*/).sendToTarget();
652         processAllMessages();
653     }
654 
serviceStateChanged(@etworkType int networkType, @RegistrationState int dataRegState, @RegistrationState int voiceRegState, @RegistrationState int iwlanRegState, DataSpecificRegistrationInfo dsri, boolean isEmergencyOnly)655     private void serviceStateChanged(@NetworkType int networkType,
656             @RegistrationState int dataRegState, @RegistrationState int voiceRegState,
657             @RegistrationState int iwlanRegState, DataSpecificRegistrationInfo dsri,
658             boolean isEmergencyOnly) {
659         ServiceState ss = createSS(networkType, networkType, dataRegState, voiceRegState,
660                 iwlanRegState, dsri, isEmergencyOnly);
661 
662         doReturn(ss).when(mSST).getServiceState();
663         doReturn(ss).when(mPhone).getServiceState();
664 
665         mDataNetworkControllerUT.obtainMessage(EVENT_SERVICE_STATE_CHANGED).sendToTarget();
666         processAllMessages();
667     }
668 
createSS(@etworkType int dataNetworkType, @NetworkType int voiceNetworkType, @RegistrationState int dataRegState, @RegistrationState int voiceRegState, @RegistrationState int iwlanRegState, DataSpecificRegistrationInfo dsri, boolean isEmergencyOnly)669     private ServiceState createSS(@NetworkType int dataNetworkType,
670             @NetworkType int voiceNetworkType,
671             @RegistrationState int dataRegState, @RegistrationState int voiceRegState,
672             @RegistrationState int iwlanRegState, DataSpecificRegistrationInfo dsri,
673             boolean isEmergencyOnly) {
674         if (dsri == null) {
675             dsri = new DataSpecificRegistrationInfo.Builder(8)
676                     .setNrAvailable(true)
677                     .setEnDcAvailable(true)
678                     .setVopsSupportInfo(new LteVopsSupportInfo(
679                             LteVopsSupportInfo.LTE_STATUS_SUPPORTED,
680                             LteVopsSupportInfo.LTE_STATUS_SUPPORTED))
681                     .build();
682         }
683 
684         ServiceState ss = new ServiceState();
685 
686         ss.addNetworkRegistrationInfo(new NetworkRegistrationInfo.Builder()
687                 .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
688                 .setAccessNetworkTechnology(dataNetworkType)
689                 .setRegistrationState(dataRegState)
690                 .setDomain(NetworkRegistrationInfo.DOMAIN_PS)
691                 .setDataSpecificInfo(dsri)
692                 .setIsNonTerrestrialNetwork(mIsNonTerrestrialNetwork)
693                 .setEmergencyOnly(isEmergencyOnly)
694                 .build());
695 
696         ss.addNetworkRegistrationInfo(new NetworkRegistrationInfo.Builder()
697                 .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WLAN)
698                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_IWLAN)
699                 .setRegistrationState(iwlanRegState)
700                 .setDomain(NetworkRegistrationInfo.DOMAIN_PS)
701                 .setIsNonTerrestrialNetwork(mIsNonTerrestrialNetwork)
702                 .setEmergencyOnly(isEmergencyOnly)
703                 .build());
704 
705         ss.addNetworkRegistrationInfo(new NetworkRegistrationInfo.Builder()
706                 .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
707                 .setAccessNetworkTechnology(voiceNetworkType)
708                 .setRegistrationState(voiceRegState)
709                 .setDomain(NetworkRegistrationInfo.DOMAIN_CS)
710                 .setEmergencyOnly(isEmergencyOnly)
711                 .build());
712 
713         ss.setDataRoamingFromRegistration(dataRegState
714                 == NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
715         processServiceStateRegStateForTest(ss);
716         return ss;
717     }
718 
719     // set SS reg state base on SST impl, where WLAN overrides WWAN's data reg.
processServiceStateRegStateForTest(ServiceState ss)720     private void processServiceStateRegStateForTest(ServiceState ss) {
721         int wlanRegState = ss.getNetworkRegistrationInfo(NetworkRegistrationInfo.DOMAIN_PS,
722                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN).getRegistrationState();
723         if (wlanRegState == NetworkRegistrationInfo.REGISTRATION_STATE_HOME) {
724             ss.setDataRegState(ServiceState.STATE_IN_SERVICE);
725         } else {
726             int cellularRegState = ss.getNetworkRegistrationInfo(NetworkRegistrationInfo.DOMAIN_PS,
727                     AccessNetworkConstants.TRANSPORT_TYPE_WWAN).getRegistrationState();
728             int dataState = (cellularRegState == NetworkRegistrationInfo.REGISTRATION_STATE_HOME
729                     || cellularRegState == NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING)
730                     ? ServiceState.STATE_IN_SERVICE : ServiceState.STATE_OUT_OF_SERVICE;
731             ss.setDataRegState(dataState);
732         }
733         int voiceRegState = ss.getNetworkRegistrationInfo(NetworkRegistrationInfo.DOMAIN_CS,
734                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN).getRegistrationState();
735         int voiceState = (voiceRegState == NetworkRegistrationInfo.REGISTRATION_STATE_HOME
736                 || voiceRegState == NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING)
737                 ? ServiceState.STATE_IN_SERVICE : ServiceState.STATE_OUT_OF_SERVICE;
738         ss.setVoiceRegState(voiceState);
739     }
740 
updateTransport(@etCapability int capability, @TransportType int transport)741     private void updateTransport(@NetCapability int capability, @TransportType int transport) {
742         doReturn(transport).when(mAccessNetworksManager)
743                 .getPreferredTransportByNetworkCapability(capability);
744         mAccessNetworksManagerCallback.onPreferredTransportChanged(capability, false);
745         processAllMessages();
746     }
747 
reconnectTransport(@etCapability int capability, @TransportType int transport)748     private void reconnectTransport(@NetCapability int capability, @TransportType int transport) {
749         doReturn(transport).when(mAccessNetworksManager)
750                 .getPreferredTransportByNetworkCapability(capability);
751         mAccessNetworksManagerCallback.onPreferredTransportChanged(capability, true);
752         processAllMessages();
753     }
754 
setVcnManagerPolicy(boolean vcnManaged, boolean shouldTearDown)755     private void setVcnManagerPolicy(boolean vcnManaged, boolean shouldTearDown) {
756         doAnswer(invocation -> {
757             final NetworkCapabilities networkCapabilities =
758                     (NetworkCapabilities) invocation.getArguments()[0];
759             if (vcnManaged) {
760                 networkCapabilities.removeCapability(
761                         NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED);
762             } else {
763                 networkCapabilities.addCapability(
764                         NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED);
765             }
766             return new VcnNetworkPolicyResult(
767                     shouldTearDown, networkCapabilities);
768         }).when(mVcnManager).applyVcnNetworkPolicy(any(NetworkCapabilities.class),
769                 any(LinkProperties.class));
770     }
771 
initializeConfig()772     private void initializeConfig() {
773         mCarrierConfig = mContextFixture.getCarrierConfigBundle();
774         when(mCarrierConfigManager.getConfigForSubId(anyInt(), any())).thenReturn(mCarrierConfig);
775         mCarrierConfig.putStringArray(
776                 CarrierConfigManager.KEY_TELEPHONY_NETWORK_CAPABILITY_PRIORITIES_STRING_ARRAY,
777                 new String[]{
778                         "eims:90", "supl:80", "mms:70", "xcap:70", "cbs:50", "mcx:50", "fota:50",
779                         "ims:40", "dun:30", "enterprise:20", "internet:20"
780                 });
781         mCarrierConfig.putBoolean(CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL, true);
782         mCarrierConfig.putStringArray(
783                 CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
784                 new String[]{"default", "mms", "dun", "supl", "enterprise"});
785         mCarrierConfig.putStringArray(
786                 CarrierConfigManager.KEY_CARRIER_METERED_ROAMING_APN_TYPES_STRINGS,
787                 new String[]{"default", "mms", "dun", "supl", "enterprise"});
788 
789         mCarrierConfig.putStringArray(
790                 CarrierConfigManager.KEY_TELEPHONY_DATA_SETUP_RETRY_RULES_STRING_ARRAY,
791                 new String[]{
792                         "capabilities=eims, retry_interval=1000, maximum_retries=20",
793                         "permanent_fail_causes=8|27|28|29|30|32|33|35|50|51|111|-5|-6|65537|65538|"
794                                 + "-3|65543|65547|2252|2253|2254, retry_interval=2500",
795                         "capabilities=mms|supl|cbs|rcs, retry_interval=2000",
796                         "capabilities=internet|enterprise|dun|ims|fota|xcap|mcx|"
797                                 + "prioritize_bandwidth|prioritize_latency, retry_interval="
798                                 + "2500|3000|5000|10000|15000|20000|40000|60000|120000|240000|"
799                                 + "600000|1200000|1800000, maximum_retries=20"
800                 });
801         mCarrierConfig.putStringArray(
802                 CarrierConfigManager.KEY_TELEPHONY_DATA_HANDOVER_RETRY_RULES_STRING_ARRAY,
803                 new String[] {"retry_interval=1000|2000|4000|8000|16000, maximum_retries=5"
804                 });
805 
806         mCarrierConfig.putInt(CarrierConfigManager.KEY_NR_ADVANCED_CAPABLE_PCO_ID_INT, 1234);
807 
808         mCarrierConfig.putBoolean(CarrierConfigManager.KEY_NETWORK_TEMP_NOT_METERED_SUPPORTED_BOOL,
809                 true);
810         mCarrierConfig.putStringArray(CarrierConfigManager.KEY_UNMETERED_NETWORK_TYPES_STRING_ARRAY,
811                 new String[] {"NR_NSA", "NR_NSA_MMWAVE", "NR_SA", "NR_SA_MMWAVE"});
812 
813         mCarrierConfig.putIntArray(CarrierConfigManager.KEY_ONLY_SINGLE_DC_ALLOWED_INT_ARRAY,
814                 new int[]{TelephonyManager.NETWORK_TYPE_CDMA, TelephonyManager.NETWORK_TYPE_1xRTT,
815                         TelephonyManager.NETWORK_TYPE_EVDO_0, TelephonyManager.NETWORK_TYPE_EVDO_A,
816                         TelephonyManager.NETWORK_TYPE_EVDO_B});
817 
818         mCarrierConfig.putIntArray(CarrierConfigManager
819                         .KEY_CAPABILITIES_EXEMPT_FROM_SINGLE_DC_CHECK_INT_ARRAY,
820                 new int[]{NetworkCapabilities.NET_CAPABILITY_IMS});
821         mCarrierConfig.putBooleanArray(
822                 CarrierConfigManager.KEY_DATA_STALL_RECOVERY_SHOULD_SKIP_BOOL_ARRAY,
823                 new boolean[] {false, false, true, false, false}
824         );
825         mCarrierConfig.putLongArray(CarrierConfigManager.KEY_DATA_STALL_RECOVERY_TIMERS_LONG_ARRAY,
826                 new long[] {180000, 180000, 180000, 180000});
827 
828         mCarrierConfig.putLongArray(CarrierConfigManager.KEY_DATA_STALL_RECOVERY_TIMERS_LONG_ARRAY,
829                 new long[] {100, 100, 100, 100});
830         mCarrierConfig.putBooleanArray(
831                 CarrierConfigManager.KEY_DATA_STALL_RECOVERY_SHOULD_SKIP_BOOL_ARRAY,
832                 new boolean[] {false, false, true, false, false});
833 
834         mContextFixture.putResource(com.android.internal.R.string.config_bandwidthEstimateSource,
835                 "bandwidth_estimator");
836 
837         mContextFixture.putBooleanResource(com.android.internal.R.bool
838                 .config_honor_data_retry_timer_for_emergency_network, true);
839         mContextFixture.putIntResource(com.android.internal.R.integer
840                         .config_delay_for_ims_dereg_millis, 3000);
841         mContextFixture.putBooleanResource(com.android.internal.R.bool
842                 .config_enable_iwlan_handover_policy, true);
843         mContextFixture.putBooleanResource(com.android.internal.R.bool
844                 .config_enhanced_iwlan_handover_check, true);
845         mContextFixture.putStringArrayResource(com.android.internal.R.array
846                 .config_force_cellular_transport_capabilities,
847                 new String[] {"ims", "eims", "xcap"});
848         mContextFixture.putIntResource(com.android.internal.R.integer
849                 .config_reevaluate_bootstrap_sim_data_usage_millis, 60000);
850     }
851 
852     @Before
setUp()853     public void setUp() throws Exception {
854         logd("DataNetworkControllerTest +Setup!");
855         super.setUp(getClass().getSimpleName());
856         mMockedPhoneSwitcher = Mockito.mock(PhoneSwitcher.class);
857         mMockedIsub = Mockito.mock(ISub.class);
858         mMockedImsManager = mContext.getSystemService(ImsManager.class);
859         mMockedImsMmTelManager = Mockito.mock(ImsMmTelManager.class);
860         mMockedImsRcsManager = Mockito.mock(ImsRcsManager.class);
861         mMockedImsResolver = Mockito.mock(ImsResolver.class);
862         mMockedDataStallRecoveryManager = Mockito.mock(DataStallRecoveryManager.class);
863         mMockedDataNetworkControllerCallback = Mockito.mock(DataNetworkControllerCallback.class);
864         mMockedDataRetryManagerCallback = Mockito.mock(DataRetryManagerCallback.class);
865         mMockSubInfo = Mockito.mock(SubscriptionInfo.class);
866         when(mTelephonyComponentFactory.makeDataSettingsManager(any(Phone.class),
867                 any(DataNetworkController.class), any(FeatureFlags.class), any(Looper.class),
868                 any(DataSettingsManager.DataSettingsManagerCallback.class))).thenCallRealMethod();
869         doReturn(mMockedImsMmTelManager).when(mMockedImsManager).getImsMmTelManager(anyInt());
870         doReturn(mMockedImsRcsManager).when(mMockedImsManager).getImsRcsManager(anyInt());
871 
872         initializeConfig();
873         mMockedDataServiceManagers.put(AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
874                 mMockedWwanDataServiceManager);
875         mMockedDataServiceManagers.put(AccessNetworkConstants.TRANSPORT_TYPE_WLAN,
876                 mMockedWlanDataServiceManager);
877 
878         replaceInstance(PhoneSwitcher.class, "sPhoneSwitcher", null, mMockedPhoneSwitcher);
879         doReturn(1).when(mMockedIsub).getDefaultDataSubId();
880         doReturn(mMockedIsub).when(mIBinder).queryLocalInterface(anyString());
881         doReturn(mPhone).when(mPhone).getImsPhone();
882         mServiceManagerMockedServices.put("isub", mIBinder);
883         doReturn(new SubscriptionPlan[]{}).when(mNetworkPolicyManager)
884                 .getSubscriptionPlans(anyInt(), any());
885         doReturn(true).when(mSST).getDesiredPowerState();
886         doReturn(true).when(mSST).getPowerStateFromCarrier();
887         doReturn(true).when(mSST).isConcurrentVoiceAndDataAllowed();
888         doReturn(PhoneConstants.State.IDLE).when(mCT).getState();
889         doReturn(new SubscriptionInfoInternal.Builder().setId(1).build())
890                 .when(mSubscriptionManagerService).getSubscriptionInfoInternal(anyInt());
891         doReturn(true).when(mFeatureFlags).carrierEnabledSatelliteFlag();
892         doReturn(true).when(mFeatureFlags).satelliteInternet();
893         doReturn(true).when(mFeatureFlags)
894                 .ignoreExistingNetworksForInternetAllowedChecking();
895 
896         List<SubscriptionInfo> infoList = new ArrayList<>();
897         infoList.add(mMockSubInfo);
898         doReturn(0).when(mSubscriptionManagerService).getPhoneId(1);
899         doReturn(1).when(mSubscriptionManagerService).getPhoneId(2);
900 
901         for (int transport : new int[]{AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
902                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN}) {
903             mDataCallListChangedRegistrants.put(transport, new RegistrantList());
904             setSuccessfulSetupDataResponse(mMockedDataServiceManagers.get(transport), 1);
905             doAnswer(invocation -> {
906                 int cid = (int) invocation.getArguments()[0];
907                 Message msg = (Message) invocation.getArguments()[2];
908                 msg.sendToTarget();
909                 mDataCallResponses.get(transport).remove(cid);
910                 mDataCallListChangedRegistrants.get(transport).notifyRegistrants(
911                         new AsyncResult(transport, new ArrayList<>(mDataCallResponses.get(
912                                 transport).values()), null));
913                 return null;
914             }).when(mMockedDataServiceManagers.get(transport)).deactivateDataCall(
915                     anyInt(), anyInt(), any(Message.class));
916 
917             doAnswer(invocation -> {
918                 Handler h = (Handler) invocation.getArguments()[0];
919                 int what = (int) invocation.getArguments()[1];
920                 mDataCallListChangedRegistrants.get(transport).addUnique(h, what, transport);
921                 return null;
922             }).when(mMockedDataServiceManagers.get(transport)).registerForDataCallListChanged(any(
923                     Handler.class), anyInt());
924 
925             doAnswer(invocation -> {
926                 Message msg = (Message) invocation.getArguments()[1];
927                 msg.sendToTarget();
928                 return null;
929             }).when(mMockedDataServiceManagers.get(transport)).startHandover(anyInt(),
930                     any(Message.class));
931 
932             doAnswer(invocation -> {
933                 Message msg = (Message) invocation.getArguments()[1];
934                 msg.sendToTarget();
935                 return null;
936             }).when(mMockedDataServiceManagers.get(transport)).cancelHandover(anyInt(),
937                     any(Message.class));
938         }
939 
940         doReturn(-1).when(mPhone).getSubId();
941 
942         // Capture listener to emulate the carrier config change notification used later
943         ArgumentCaptor<CarrierConfigManager.CarrierConfigChangeListener> listenerArgumentCaptor =
944                 ArgumentCaptor.forClass(CarrierConfigManager.CarrierConfigChangeListener.class);
945         // Note that creating a "real" data network controller will also result in creating
946         // real DataRetryManager, DataConfigManager, etc...Normally in unit test we should isolate
947         // other modules and make them mocked, but only focusing on testing the unit we would like
948         // to test, in this case, DataNetworkController. But since there are too many interactions
949         // between DataNetworkController and its sub-modules, we intend to make those modules "real"
950         // as well, except some modules below we replaced with mocks.
951         mDataNetworkControllerUT = new DataNetworkController(mPhone, Looper.myLooper(),
952                 mFeatureFlags);
953         // First two come from DataServiceManager and the third comes from DataConfigManager which
954         // is what we want to capture and assign to mCarrierConfigChangeListener
955         verify(mCarrierConfigManager, times(3)).registerCarrierConfigChangeListener(any(),
956                 listenerArgumentCaptor.capture());
957         mCarrierConfigChangeListener = listenerArgumentCaptor.getAllValues().get(2);
958         assertThat(mCarrierConfigChangeListener).isNotNull();
959         doReturn(mDataNetworkControllerUT).when(mPhone).getDataNetworkController();
960 
961         doReturn(1).when(mPhone).getSubId();
962         mDataNetworkControllerUT.obtainMessage(15/*EVENT_SUBSCRIPTION_CHANGED*/).sendToTarget();
963 
964         processAllMessages();
965         // Clear the callbacks created by the real sub-modules created by DataNetworkController.
966         clearCallbacks();
967         SparseArray<DataServiceManager> dataServiceManagers = new SparseArray<>();
968         dataServiceManagers.put(AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
969                 mMockedWwanDataServiceManager);
970         dataServiceManagers.put(AccessNetworkConstants.TRANSPORT_TYPE_WLAN,
971                 mMockedWlanDataServiceManager);
972         replaceInstance(DataNetworkController.class, "mDataServiceManagers",
973                 mDataNetworkControllerUT, dataServiceManagers);
974         replaceInstance(DataNetworkController.class, "mDataProfileManager",
975                 mDataNetworkControllerUT, mDataProfileManager);
976         replaceInstance(DataNetworkController.class, "mAccessNetworksManager",
977                 mDataNetworkControllerUT, mAccessNetworksManager);
978         replaceInstance(ImsResolver.class, "sInstance", null, mMockedImsResolver);
979         replaceInstance(DataNetworkController.class, "mDataStallRecoveryManager",
980                 mDataNetworkControllerUT, mMockedDataStallRecoveryManager);
981 
982         ArgumentCaptor<AccessNetworksManagerCallback> callbackCaptor =
983                 ArgumentCaptor.forClass(AccessNetworksManagerCallback.class);
984         verify(mAccessNetworksManager).registerCallback(callbackCaptor.capture());
985         mAccessNetworksManagerCallback = callbackCaptor.getValue();
986 
987         ArgumentCaptor<LinkBandwidthEstimatorCallback> linkBandwidthEstimatorCallbackCaptor =
988                 ArgumentCaptor.forClass(LinkBandwidthEstimatorCallback.class);
989         verify(mLinkBandwidthEstimator).registerCallback(
990                 linkBandwidthEstimatorCallbackCaptor.capture());
991         mLinkBandwidthEstimatorCallback = linkBandwidthEstimatorCallbackCaptor.getValue();
992 
993         List<DataProfile> profiles = List.of(mGeneralPurposeDataProfile,
994                 mGeneralPurposeDataProfileAlternative, mImsCellularDataProfile,
995                 mImsIwlanDataProfile, mEmergencyDataProfile, mFotaDataProfile,
996                 mTetheringDataProfile, mLowLatencyDataProfile,
997                 mNtnDataProfile, mEsimBootstrapDataProfile,
998                 mEsimBootstrapImsProfile, mEsimBootstrapRcsInfraStructureProfile);
999 
1000         doAnswer(invocation -> {
1001             DataProfile dp = (DataProfile) invocation.getArguments()[0];
1002 
1003             if (dp.getApnSetting() == null) return true;
1004 
1005             for (DataProfile dataProfile : profiles) {
1006                 if (dataProfile.getApnSetting() != null
1007                         && dataProfile.getApnSetting().equals(dp.getApnSetting(), false)) {
1008                     return true;
1009                 }
1010             }
1011             return null;
1012         }).when(mDataProfileManager).isDataProfileCompatible(any(DataProfile.class));
1013 
1014         doAnswer(invocation -> {
1015             DataProfile a = (DataProfile) invocation.getArguments()[0];
1016             DataProfile b = (DataProfile) invocation.getArguments()[1];
1017             return a != null
1018                     && b != null
1019                     && a.getApnSetting() != null
1020                     && a.getApnSetting().equals(b.getApnSetting(),
1021                     mPhone.getServiceState().getDataRoamingFromRegistration());
1022         }).when(mDataProfileManager).areDataProfilesSharingApn(any(DataProfile.class),
1023                 any(DataProfile.class));
1024 
1025         doAnswer(invocation -> {
1026             TelephonyNetworkRequest networkRequest =
1027                     (TelephonyNetworkRequest) invocation.getArguments()[0];
1028             int networkType = (int) invocation.getArguments()[1];
1029             boolean isNtn = (boolean) invocation.getArguments()[2];
1030             boolean isEsimBootstrapProvisioning = (boolean) invocation.getArguments()[3];
1031             boolean ignorePermanentFailure = (boolean) invocation.getArguments()[4];
1032 
1033             for (DataProfile dataProfile : profiles) {
1034                 ApnSetting apnSetting = dataProfile.getApnSetting();
1035                 if (apnSetting != null
1036                         && dataProfile.canSatisfy(networkRequest.getCapabilities())
1037                         && (apnSetting.getNetworkTypeBitmask() == 0
1038                         || (apnSetting.getNetworkTypeBitmask()
1039                         & ServiceState.getBitmaskForTech(networkType)) != 0)
1040                         && (isEsimBootstrapProvisioning
1041                         == apnSetting.isEsimBootstrapProvisioning())
1042                         && ((isNtn && apnSetting.isForInfrastructure(
1043                         ApnSetting.INFRASTRUCTURE_SATELLITE))
1044                         || (!isNtn && apnSetting.isForInfrastructure(
1045                         ApnSetting.INFRASTRUCTURE_CELLULAR)))
1046                         && (ignorePermanentFailure || !apnSetting.getPermanentFailed())) {
1047                     return dataProfile;
1048                 }
1049             }
1050             logd("Cannot find data profile to satisfy " + networkRequest + ", network type="
1051                     + TelephonyManager.getNetworkTypeName(networkType) + ", ignorePermanentFailure="
1052                     + ignorePermanentFailure + ", isNtn=" + isNtn + ","
1053                     + "isEsimBootstrapProvisioning=" + isEsimBootstrapProvisioning);
1054             return null;
1055         }).when(mDataProfileManager).getDataProfileForNetworkRequest(
1056                 any(TelephonyNetworkRequest.class), anyInt(), anyBoolean(), anyBoolean(),
1057                 anyBoolean());
1058 
1059         doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WWAN).when(mAccessNetworksManager)
1060                 .getPreferredTransportByNetworkCapability(anyInt());
1061 
1062         doAnswer(invocation -> {
1063             ((Runnable) invocation.getArguments()[0]).run();
1064             return null;
1065         }).when(mMockedDataNetworkControllerCallback).invokeFromExecutor(any(Runnable.class));
1066         doAnswer(invocation -> {
1067             ((Runnable) invocation.getArguments()[0]).run();
1068             return null;
1069         }).when(mMockedDataRetryManagerCallback).invokeFromExecutor(any(Runnable.class));
1070 
1071         mDataNetworkControllerUT.registerDataNetworkControllerCallback(
1072                 mMockedDataNetworkControllerCallback);
1073 
1074         mDataNetworkControllerUT.obtainMessage(EVENT_SIM_STATE_CHANGED,
1075                 10/*SIM_STATE_LOADED*/, 0).sendToTarget();
1076         mDataNetworkControllerUT.obtainMessage(8/*EVENT_DATA_SERVICE_BINDING_CHANGED*/,
1077                 new AsyncResult(AccessNetworkConstants.TRANSPORT_TYPE_WWAN, true, null))
1078                 .sendToTarget();
1079         mDataNetworkControllerUT.obtainMessage(8/*EVENT_DATA_SERVICE_BINDING_CHANGED*/,
1080                 new AsyncResult(AccessNetworkConstants.TRANSPORT_TYPE_WLAN, true, null))
1081                 .sendToTarget();
1082 
1083         ArgumentCaptor<ImsStateCallback> imsCallbackCaptor =
1084                 ArgumentCaptor.forClass(ImsStateCallback.class);
1085         verify(mMockedImsMmTelManager).registerImsStateCallback(any(Executor.class),
1086                 imsCallbackCaptor.capture());
1087         mMmtelStateCallback = imsCallbackCaptor.getValue();
1088 
1089         verify(mMockedImsRcsManager).registerImsStateCallback(any(Executor.class),
1090                 imsCallbackCaptor.capture());
1091         mRcsStateCallback = imsCallbackCaptor.getValue();
1092 
1093         carrierConfigChanged();
1094 
1095         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
1096                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1097 
1098         // IMS registration
1099         doReturn(FAKE_MMTEL_PACKAGE).when(mMockedImsResolver).getConfiguredImsServicePackageName(
1100                 anyInt(), eq(ImsFeature.FEATURE_MMTEL));
1101         doReturn(FAKE_RCS_PACKAGE).when(mMockedImsResolver).getConfiguredImsServicePackageName(
1102                 anyInt(), eq(ImsFeature.FEATURE_RCS));
1103 
1104         mMmtelStateCallback.onAvailable();
1105         mRcsStateCallback.onAvailable();
1106 
1107         ArgumentCaptor<RegistrationCallback> regCallbackCaptor =
1108                 ArgumentCaptor.forClass(RegistrationCallback.class);
1109 
1110         verify(mMockedImsMmTelManager).registerImsRegistrationCallback(any(Executor.class),
1111                 regCallbackCaptor.capture());
1112         mMmtelRegCallback = regCallbackCaptor.getValue();
1113 
1114         verify(mMockedImsRcsManager).registerImsRegistrationCallback(any(Executor.class),
1115                 regCallbackCaptor.capture());
1116         mRcsRegCallback = regCallbackCaptor.getValue();
1117 
1118         processAllMessages();
1119         Mockito.clearInvocations(mMockedDataNetworkControllerCallback);
1120 
1121         logd("DataNetworkControllerTest -Setup!");
1122     }
1123 
1124     @After
tearDown()1125     public void tearDown() throws Exception {
1126         logd("tearDown");
1127         mMockedDataServiceManagers.clear();
1128         mDataCallListChangedRegistrants.clear();
1129         mDataNetworkControllerUT = null;
1130         mCarrierConfig = null;
1131         super.tearDown();
1132     }
1133 
createNetworkRequest(Integer... capabilities)1134     private @NonNull TelephonyNetworkRequest createNetworkRequest(Integer... capabilities) {
1135         return createNetworkRequest(null, capabilities);
1136     }
1137 
createNetworkRequest(@ullable Boolean restricted, Integer... capabilities)1138     private @NonNull TelephonyNetworkRequest createNetworkRequest(@Nullable Boolean restricted,
1139                                                                   Integer... capabilities) {
1140         NetworkCapabilities netCaps = new NetworkCapabilities();
1141         for (int networkCapability : capabilities) {
1142             netCaps.addCapability(networkCapability);
1143         }
1144 
1145         if (restricted != null) {
1146             if (restricted) {
1147                 netCaps.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
1148             }
1149         } else {
1150             // Data Network uses the same to define its own capabilities.
1151             netCaps.maybeMarkCapabilitiesRestricted();
1152         }
1153 
1154         NetworkRequest nativeNetworkRequest = new NetworkRequest(netCaps,
1155                 ConnectivityManager.TYPE_MOBILE, ++mNetworkRequestId, NetworkRequest.Type.REQUEST);
1156 
1157         return new TelephonyNetworkRequest(nativeNetworkRequest, mPhone, mFeatureFlags);
1158     }
1159 
1160     // The purpose of this test is to make sure the network request insertion/removal works as
1161     // expected, and make sure it is always sorted.
1162     @Test
testNetworkRequestList()1163     public void testNetworkRequestList() {
1164         NetworkRequestList networkRequestList = new NetworkRequestList();
1165 
1166         TelephonyNetworkRequest internetNetworkRequest = createNetworkRequest(
1167                 NetworkCapabilities.NET_CAPABILITY_INTERNET);
1168         TelephonyNetworkRequest eimsNetworkRequest = createNetworkRequest(
1169                 NetworkCapabilities.NET_CAPABILITY_EIMS);
1170         TelephonyNetworkRequest mmsNetworkRequest = createNetworkRequest(
1171                 NetworkCapabilities.NET_CAPABILITY_MMS);
1172         networkRequestList.add(internetNetworkRequest);
1173         networkRequestList.add(eimsNetworkRequest);
1174         networkRequestList.add(mmsNetworkRequest);
1175 
1176         // Check if emergency has the highest priority, then mms, then internet.
1177         assertThat(networkRequestList.get(0).getCapabilities()[0])
1178                 .isEqualTo(NetworkCapabilities.NET_CAPABILITY_EIMS);
1179         assertThat(networkRequestList.get(1).getCapabilities()[0])
1180                 .isEqualTo(NetworkCapabilities.NET_CAPABILITY_MMS);
1181         assertThat(networkRequestList.get(2).getCapabilities()[0])
1182                 .isEqualTo(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1183 
1184         // Add IMS
1185         TelephonyNetworkRequest imsNetworkRequest = createNetworkRequest(
1186                 NetworkCapabilities.NET_CAPABILITY_IMS);
1187         assertThat(networkRequestList.add(imsNetworkRequest)).isTrue();
1188 
1189         assertThat(networkRequestList.get(0).getCapabilities()[0])
1190                 .isEqualTo(NetworkCapabilities.NET_CAPABILITY_EIMS);
1191         assertThat(networkRequestList.get(1).getCapabilities()[0])
1192                 .isEqualTo(NetworkCapabilities.NET_CAPABILITY_MMS);
1193         assertThat(networkRequestList.get(2).getCapabilities()[0])
1194                 .isEqualTo(NetworkCapabilities.NET_CAPABILITY_IMS);
1195         assertThat(networkRequestList.get(3).getCapabilities()[0])
1196                 .isEqualTo(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1197 
1198         // Add IMS again
1199         assertThat(networkRequestList.add(imsNetworkRequest)).isFalse();
1200         assertThat(networkRequestList.size()).isEqualTo(4);
1201 
1202         // Remove MMS
1203         assertThat(networkRequestList.remove(mmsNetworkRequest)).isTrue();
1204         assertThat(networkRequestList.get(0).getCapabilities()[0])
1205                 .isEqualTo(NetworkCapabilities.NET_CAPABILITY_EIMS);
1206         assertThat(networkRequestList.get(1).getCapabilities()[0])
1207                 .isEqualTo(NetworkCapabilities.NET_CAPABILITY_IMS);
1208         assertThat(networkRequestList.get(2).getCapabilities()[0])
1209                 .isEqualTo(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1210 
1211         // Remove EIMS
1212         assertThat(networkRequestList.remove(eimsNetworkRequest)).isTrue();
1213         assertThat(networkRequestList.get(0).getCapabilities()[0])
1214                 .isEqualTo(NetworkCapabilities.NET_CAPABILITY_IMS);
1215         assertThat(networkRequestList.get(1).getCapabilities()[0])
1216                 .isEqualTo(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1217 
1218         // Remove Internet
1219         assertThat(networkRequestList.remove(internetNetworkRequest)).isTrue();
1220         assertThat(networkRequestList.get(0).getCapabilities()[0])
1221                 .isEqualTo(NetworkCapabilities.NET_CAPABILITY_IMS);
1222 
1223         // Remove XCAP (which does not exist)
1224         assertThat(networkRequestList.remove(
1225                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_XCAP))).isFalse();
1226         assertThat(networkRequestList.get(0).getCapabilities()[0])
1227                 .isEqualTo(NetworkCapabilities.NET_CAPABILITY_IMS);
1228 
1229         // Remove IMS
1230         assertThat(networkRequestList.remove(imsNetworkRequest)).isTrue();
1231         assertThat(networkRequestList).isEmpty();
1232     }
1233 
getDataNetworks()1234     private @NonNull List<DataNetwork> getDataNetworks() throws Exception {
1235         Field field = DataNetworkController.class.getDeclaredField("mDataNetworkList");
1236         field.setAccessible(true);
1237         return (List<DataNetwork>) field.get(mDataNetworkControllerUT);
1238     }
1239 
verifyInternetConnected()1240     private void verifyInternetConnected() throws Exception {
1241         verify(mMockedDataNetworkControllerCallback).onConnectedInternetDataNetworksChanged(any());
1242         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1243     }
1244 
verifyConnectedNetworkHasCapabilities(@etCapability int... networkCapabilities)1245     private void verifyConnectedNetworkHasCapabilities(@NetCapability int... networkCapabilities)
1246             throws Exception {
1247         List<DataNetwork> dataNetworkList = getDataNetworks();
1248         for (DataNetwork dataNetwork : getDataNetworks()) {
1249             if (dataNetwork.isConnected() && Arrays.stream(networkCapabilities).boxed()
1250                     .allMatch(dataNetwork.getNetworkCapabilities()::hasCapability)) {
1251                 return;
1252             }
1253         }
1254         fail("No network with " + DataUtils.networkCapabilitiesToString(networkCapabilities)
1255                 + " is connected. dataNetworkList=" + dataNetworkList);
1256     }
1257 
verifyNoConnectedNetworkHasCapability(@etCapability int networkCapability)1258     private void verifyNoConnectedNetworkHasCapability(@NetCapability int networkCapability)
1259             throws Exception {
1260         for (DataNetwork dataNetwork : getDataNetworks()) {
1261             assertWithMessage("Network " + dataNetwork + " should not be connected.")
1262                     .that(dataNetwork.isConnected() && dataNetwork.getNetworkCapabilities()
1263                             .hasCapability(networkCapability)).isFalse();
1264         }
1265     }
1266 
verifyConnectedNetworkHasDataProfile(@onNull DataProfile dataProfile)1267     private void verifyConnectedNetworkHasDataProfile(@NonNull DataProfile dataProfile)
1268             throws Exception {
1269         List<DataNetwork> dataNetworkList = getDataNetworks();
1270         for (DataNetwork dataNetwork : getDataNetworks()) {
1271             if (dataNetwork.isConnected() && dataNetwork.getDataProfile().equals(dataProfile)) {
1272                 return;
1273             }
1274         }
1275         fail("No network with " + dataProfile + " is connected. dataNetworkList="
1276                 + dataNetworkList);
1277     }
1278 
verifyConnectedNetworkHasNoDataProfile(@onNull DataProfile dataProfile)1279     private void verifyConnectedNetworkHasNoDataProfile(@NonNull DataProfile dataProfile)
1280             throws Exception {
1281         List<DataNetwork> dataNetworkList = getDataNetworks();
1282         for (DataNetwork dataNetwork : getDataNetworks()) {
1283             if (dataNetwork.isConnected() && dataNetwork.getDataProfile().equals(dataProfile)) {
1284                 fail("network with " + dataProfile + " is connected. dataNetworkList="
1285                         + dataNetworkList);
1286             }
1287         }
1288         return;
1289     }
1290 
verifyAllDataDisconnected()1291     private void verifyAllDataDisconnected() throws Exception {
1292         List<DataNetwork> dataNetworkList = getDataNetworks();
1293         assertWithMessage("All data should be disconnected but it's not. " + dataNetworkList)
1294                 .that(dataNetworkList).isEmpty();
1295     }
1296 
1297     // To test the basic data setup. Copy this as example for other tests.
1298     @Test
testSetupDataNetwork()1299     public void testSetupDataNetwork() throws Exception {
1300         mDataNetworkControllerUT.addNetworkRequest(
1301                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
1302         processAllMessages();
1303         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1304         verifyConnectedNetworkHasDataProfile(mGeneralPurposeDataProfile);
1305 
1306         List<DataNetwork> dataNetworkList = getDataNetworks();
1307         assertThat(dataNetworkList).hasSize(1);
1308         DataNetwork dataNetwork = dataNetworkList.get(0);
1309         assertThat(dataNetworkList.get(0).getLinkProperties().getAddresses()).containsExactly(
1310                 InetAddresses.parseNumericAddress(IPV4_ADDRESS),
1311                 InetAddresses.parseNumericAddress(IPV6_ADDRESS));
1312 
1313         verify(mMockedDataNetworkControllerCallback).onConnectedInternetDataNetworksChanged(any());
1314     }
1315 
1316     @Test
testSetupDataNetworkWithSimilarDataProfile()1317     public void testSetupDataNetworkWithSimilarDataProfile() throws Exception {
1318         mDataNetworkControllerUT.addNetworkRequest(
1319                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
1320         processAllMessages();
1321         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1322         verifyConnectedNetworkHasDataProfile(mGeneralPurposeDataProfile);
1323 
1324         List<DataNetwork> dataNetworkList = getDataNetworks();
1325         assertThat(dataNetworkList).hasSize(1);
1326         DataNetwork dataNetwork = dataNetworkList.get(0);
1327         assertThat(dataNetworkList.get(0).getLinkProperties().getAddresses()).containsExactly(
1328                 InetAddresses.parseNumericAddress(IPV4_ADDRESS),
1329                 InetAddresses.parseNumericAddress(IPV6_ADDRESS));
1330 
1331         verify(mMockedDataNetworkControllerCallback).onConnectedInternetDataNetworksChanged(any());
1332 
1333         // database updated/reloaded, causing data profile id change
1334         List<DataProfile> profiles = List.of(mDuplicatedGeneralPurposeDataProfile);
1335         doAnswer(invocation -> {
1336             DataProfile dp = (DataProfile) invocation.getArguments()[0];
1337 
1338             if (dp.getApnSetting() == null) return true;
1339 
1340             for (DataProfile dataProfile : profiles) {
1341                 if (dataProfile.getApnSetting() != null
1342                         && dataProfile.getApnSetting().equals(dp.getApnSetting(), false)) {
1343                     return true;
1344                 }
1345             }
1346             return null;
1347         }).when(mDataProfileManager).isDataProfileCompatible(any(DataProfile.class));
1348         doAnswer(invocation -> {
1349             TelephonyNetworkRequest networkRequest =
1350                     (TelephonyNetworkRequest) invocation.getArguments()[0];
1351             int networkType = (int) invocation.getArguments()[1];
1352 
1353             for (DataProfile dataProfile : profiles) {
1354                 if (dataProfile.canSatisfy(networkRequest.getCapabilities())
1355                         && (dataProfile.getApnSetting().getNetworkTypeBitmask() == 0
1356                         || (dataProfile.getApnSetting().getNetworkTypeBitmask()
1357                         & ServiceState.getBitmaskForTech(networkType)) != 0)) {
1358                     return dataProfile;
1359                 }
1360             }
1361             logd("Cannot find data profile to satisfy " + networkRequest + ", network type="
1362                     + TelephonyManager.getNetworkTypeName(networkType));
1363             return null;
1364         }).when(mDataProfileManager).getDataProfileForNetworkRequest(
1365                 any(TelephonyNetworkRequest.class), anyInt(), anyBoolean(), anyBoolean(),
1366                 anyBoolean());
1367 
1368         // verify the network still connects
1369         verify(mMockedDataNetworkControllerCallback).onConnectedInternetDataNetworksChanged(any());
1370 
1371         // A NOT_VCN_MANAGED request cannot be satisfied by the existing network, but will adopt the
1372         // same data profile
1373         mDataNetworkControllerUT.addNetworkRequest(
1374                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET,
1375                         NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED));
1376 
1377         processAllMessages();
1378 
1379         // verify the network still connects
1380         verify(mMockedDataNetworkControllerCallback).onConnectedInternetDataNetworksChanged(any());
1381         // verify we don't try to setup a separate network for the not_vcn_managed request
1382         dataNetworkList = getDataNetworks();
1383         assertThat(dataNetworkList).hasSize(1);
1384     }
1385 
1386     @Test
testSetupImsDataNetwork()1387     public void testSetupImsDataNetwork() throws Exception {
1388         mDataNetworkControllerUT.addNetworkRequest(
1389                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS,
1390                         NetworkCapabilities.NET_CAPABILITY_MMTEL));
1391         processAllMessages();
1392         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
1393                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
1394         verifyConnectedNetworkHasDataProfile(mImsCellularDataProfile);
1395         List<DataNetwork> dataNetworkList = getDataNetworks();
1396         assertThat(dataNetworkList.get(0).getLinkProperties().getAddresses()).containsExactly(
1397                 InetAddresses.parseNumericAddress(IPV4_ADDRESS),
1398                 InetAddresses.parseNumericAddress(IPV6_ADDRESS));
1399     }
1400 
1401     @Test
testSetupEnterpriseDataNetwork()1402     public void testSetupEnterpriseDataNetwork() throws Exception {
1403         List<TrafficDescriptor> tdList = new ArrayList<>();
1404         tdList.add(new TrafficDescriptor.Builder()
1405                 .setOsAppId(new OsAppId(OsAppId.ANDROID_OS_ID, "ENTERPRISE", 1).getBytes())
1406                 .build());
1407         setSuccessfulSetupDataResponse(mMockedWwanDataServiceManager,
1408                 createDataCallResponse(1, DataCallResponse.LINK_STATUS_ACTIVE, tdList));
1409         doReturn(mEnterpriseDataProfile).when(mDataProfileManager)
1410                 .getDataProfileForNetworkRequest(any(TelephonyNetworkRequest.class), anyInt(),
1411                         anyBoolean(), anyBoolean(), anyBoolean());
1412 
1413         NetworkCapabilities netCaps = new NetworkCapabilities();
1414         netCaps.addCapability(NetworkCapabilities.NET_CAPABILITY_ENTERPRISE);
1415         netCaps.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
1416         mDataNetworkControllerUT.addNetworkRequest(new TelephonyNetworkRequest(
1417                 new NetworkRequest(netCaps, ConnectivityManager.TYPE_MOBILE, ++mNetworkRequestId,
1418                         NetworkRequest.Type.REQUEST), mPhone, mFeatureFlags));
1419         processAllMessages();
1420         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_ENTERPRISE);
1421         List<DataNetwork> dataNetworkList = getDataNetworks();
1422         assertThat(dataNetworkList.get(0).getLinkProperties().getAddresses()).containsExactly(
1423                 InetAddresses.parseNumericAddress(IPV4_ADDRESS),
1424                 InetAddresses.parseNumericAddress(IPV6_ADDRESS));
1425     }
1426 
1427     @Test
testDataNetworkControllerCallback()1428     public void testDataNetworkControllerCallback() throws Exception {
1429         Field field = DataNetworkController.class.getDeclaredField(
1430                 "mDataNetworkControllerCallbacks");
1431         field.setAccessible(true);
1432         Set<DataNetworkControllerCallback> dataNetworkControllerCallbacks =
1433                 (Set<DataNetworkControllerCallback>) field.get(mDataNetworkControllerUT);
1434 
1435         // Verify register callback
1436         mDataNetworkControllerUT.registerDataNetworkControllerCallback(
1437                 mMockedDataNetworkControllerCallback);
1438         TelephonyNetworkRequest request = createNetworkRequest(
1439                 NetworkCapabilities.NET_CAPABILITY_INTERNET);
1440         mDataNetworkControllerUT.addNetworkRequest(request);
1441         processAllMessages();
1442         verify(mMockedDataNetworkControllerCallback).onAnyDataNetworkExistingChanged(eq(true));
1443         verify(mMockedDataNetworkControllerCallback).onConnectedInternetDataNetworksChanged(any());
1444 
1445         int countOfCallbacks = dataNetworkControllerCallbacks.size();
1446 
1447         // Verify unregister callback
1448         mDataNetworkControllerUT.removeNetworkRequest(request);
1449         processAllMessages();
1450         getDataNetworks().get(0).tearDown(DataNetwork
1451                 .TEAR_DOWN_REASON_CONNECTIVITY_SERVICE_UNWANTED);
1452         processAllFutureMessages();
1453 
1454         assertEquals(countOfCallbacks - 1, dataNetworkControllerCallbacks.size());
1455     }
1456 
1457     @Test
testSimRemovalDataTearDown()1458     public void testSimRemovalDataTearDown() throws Exception {
1459         testSetupDataNetwork();
1460 
1461         mDataNetworkControllerUT.obtainMessage(EVENT_SIM_STATE_CHANGED,
1462                 TelephonyManager.SIM_STATE_ABSENT, 0).sendToTarget();
1463         processAllMessages();
1464         verifyAllDataDisconnected();
1465         verify(mMockedDataNetworkControllerCallback).onAnyDataNetworkExistingChanged(eq(false));
1466         verify(mMockedDataNetworkControllerCallback).onConnectedInternetDataNetworksChanged(
1467                 eq(Collections.emptySet()));
1468         verify(mMockedDataNetworkControllerCallback).onPhysicalLinkStatusChanged(
1469                 eq(DataCallResponse.LINK_STATUS_INACTIVE));
1470     }
1471 
1472     @Test
testSimRemovalAndThenInserted()1473     public void testSimRemovalAndThenInserted() throws Exception {
1474         testSimRemovalDataTearDown();
1475         Mockito.clearInvocations(mMockedDataNetworkControllerCallback);
1476 
1477         // Insert the SIM again.
1478         mDataNetworkControllerUT.obtainMessage(EVENT_SIM_STATE_CHANGED,
1479                 TelephonyManager.SIM_STATE_LOADED, 0).sendToTarget();
1480         processAllMessages();
1481 
1482         verifyInternetConnected();
1483     }
1484 
1485     @Test
testDuplicateInterface()1486     public void testDuplicateInterface() throws Exception {
1487         mDataNetworkControllerUT.addNetworkRequest(
1488                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
1489         processAllMessages();
1490 
1491         // The fota network request would result in duplicate interface.
1492         mDataNetworkControllerUT.addNetworkRequest(
1493                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_FOTA));
1494         processAllFutureMessages();
1495 
1496         // There should be only one network.
1497         List<DataNetwork> dataNetworkList = getDataNetworks();
1498         assertThat(dataNetworkList).hasSize(1);
1499         assertThat(dataNetworkList.get(0).getDataProfile()).isEqualTo(mGeneralPurposeDataProfile);
1500         verifyInternetConnected();
1501         // Fota should not be connected.
1502         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA);
1503 
1504         // There should be exactly 2 setup data call requests.
1505         verify(mMockedWwanDataServiceManager, times(2)).setupDataCall(anyInt(),
1506                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
1507                 any(), any(), anyBoolean(), any(Message.class));
1508     }
1509 
1510     @Test
testMovingFromNoServiceToInService()1511     public void testMovingFromNoServiceToInService() throws Exception {
1512         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
1513                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING);
1514 
1515         mDataNetworkControllerUT.addNetworkRequest(
1516                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
1517         processAllMessages();
1518 
1519         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1520 
1521         // Network becomes in-service.
1522         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
1523                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1524 
1525         verifyInternetConnected();
1526     }
1527 
1528     @Test
testMovingFromInServiceToNoService()1529     public void testMovingFromInServiceToNoService() throws Exception {
1530         testSetupDataNetwork();
1531 
1532         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
1533                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING);
1534         // Verify we don't tear down the data network.
1535         verifyInternetConnected();
1536 
1537         serviceStateChanged(TelephonyManager.NETWORK_TYPE_UNKNOWN,
1538                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING);
1539         // Verify we don't tear down the data network.
1540         verifyInternetConnected();
1541     }
1542 
1543     @Test
testPsRestrictedAndLifted()1544     public void testPsRestrictedAndLifted() throws Exception {
1545         testSetupDataNetwork();
1546         Mockito.clearInvocations(mMockedDataNetworkControllerCallback);
1547 
1548         // PS restricted, existing PDN should stay.
1549         mDataNetworkControllerUT.obtainMessage(6/*EVENT_PS_RESTRICT_ENABLED*/).sendToTarget();
1550         processAllMessages();
1551 
1552         List<DataNetwork> dataNetworkList = getDataNetworks();
1553         assertThat(dataNetworkList).hasSize(1);
1554         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1555 
1556         // PS restricted, new setup NOT allowed
1557         mDataNetworkControllerUT.addNetworkRequest(
1558                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS,
1559                         NetworkCapabilities.NET_CAPABILITY_MMTEL));
1560         setSuccessfulSetupDataResponse(mMockedDataServiceManagers
1561                 .get(AccessNetworkConstants.TRANSPORT_TYPE_WWAN), 2);
1562         processAllMessages();
1563         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_IMS);
1564         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1565 
1566 
1567         // PS unrestricted, new setup is allowed
1568         mDataNetworkControllerUT.obtainMessage(7/*EVENT_PS_RESTRICT_DISABLED*/).sendToTarget();
1569         processAllMessages();
1570 
1571         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
1572                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
1573         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1574     }
1575 
1576     @Test
testPsRestrictedAllowIwlan()1577     public void testPsRestrictedAllowIwlan() throws Exception {
1578         // IMS preferred on IWLAN.
1579         doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WLAN).when(mAccessNetworksManager)
1580                 .getPreferredTransportByNetworkCapability(
1581                         eq(NetworkCapabilities.NET_CAPABILITY_IMS));
1582 
1583         // PS restricted
1584         mDataNetworkControllerUT.obtainMessage(6/*EVENT_PS_RESTRICT_ENABLED*/).sendToTarget();
1585         processAllMessages();
1586 
1587         // PS restricted, new setup NOT allowed
1588         mDataNetworkControllerUT.addNetworkRequest(
1589                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
1590         setSuccessfulSetupDataResponse(mMockedDataServiceManagers
1591                 .get(AccessNetworkConstants.TRANSPORT_TYPE_WWAN), 2);
1592         processAllMessages();
1593         verifyAllDataDisconnected();
1594 
1595         // Request IMS
1596         mDataNetworkControllerUT.addNetworkRequest(
1597                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS,
1598                         NetworkCapabilities.NET_CAPABILITY_MMTEL));
1599         setSuccessfulSetupDataResponse(mMockedDataServiceManagers
1600                 .get(AccessNetworkConstants.TRANSPORT_TYPE_WLAN), 3);
1601         processAllMessages();
1602 
1603         // Make sure IMS on IWLAN.
1604         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS);
1605         assertThat(getDataNetworks()).hasSize(1);
1606         DataNetwork dataNetwork = getDataNetworks().get(0);
1607         assertThat(dataNetwork.getTransport()).isEqualTo(
1608                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
1609     }
1610 
1611     @Test
testRatChanges()1612     public void testRatChanges() throws Exception {
1613         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
1614                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1615 
1616         testSetupDataNetwork();
1617 
1618         // Now RAT changes from LTE to UMTS, make sure the network is lingered.
1619         serviceStateChanged(TelephonyManager.NETWORK_TYPE_UMTS,
1620                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1621         verifyInternetConnected();
1622 
1623         // Now RAT changes from UMTS to GSM
1624         doReturn(null).when(mDataProfileManager).getDataProfileForNetworkRequest(
1625                 any(TelephonyNetworkRequest.class), eq(TelephonyManager.NETWORK_TYPE_GSM),
1626                 anyBoolean(), anyBoolean(), anyBoolean());
1627         serviceStateChanged(TelephonyManager.NETWORK_TYPE_GSM,
1628                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1629         verifyAllDataDisconnected();
1630         verify(mMockedDataNetworkControllerCallback).onAnyDataNetworkExistingChanged(eq(false));
1631         verify(mMockedDataNetworkControllerCallback).onConnectedInternetDataNetworksChanged(
1632                 eq(Collections.emptySet()));
1633         verify(mMockedDataNetworkControllerCallback).onPhysicalLinkStatusChanged(
1634                 eq(DataCallResponse.LINK_STATUS_INACTIVE));
1635 
1636         Mockito.clearInvocations(mMockedDataNetworkControllerCallback);
1637         // Now RAT changes from GSM to UMTS
1638         doReturn(null).when(mDataProfileManager).getDataProfileForNetworkRequest(
1639                 any(TelephonyNetworkRequest.class), eq(TelephonyManager.NETWORK_TYPE_UMTS),
1640                 anyBoolean(), anyBoolean(), anyBoolean());
1641         serviceStateChanged(TelephonyManager.NETWORK_TYPE_UMTS,
1642                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1643         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1644 
1645         doReturn(mGeneralPurposeDataProfile).when(mDataProfileManager)
1646                 .getDataProfileForNetworkRequest(any(TelephonyNetworkRequest.class), anyInt(),
1647                         anyBoolean(), anyBoolean(), anyBoolean());
1648         // Now RAT changes from UMTS to LTE
1649         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
1650                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1651         verifyInternetConnected();
1652     }
1653 
1654     @Test
testRatChangesLingeringNotSet()1655     public void testRatChangesLingeringNotSet() throws Exception {
1656         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
1657                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1658         TelephonyNetworkRequest fotaRequest = createNetworkRequest(
1659                 NetworkCapabilities.NET_CAPABILITY_FOTA);
1660         mDataNetworkControllerUT.addNetworkRequest(fotaRequest);
1661         processAllMessages();
1662 
1663         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_FOTA);
1664 
1665         // Now RAT changes from LTE to UMTS, since FOTA APN does not have lingering set, only
1666         // network type bitmask should be used. Fota network should be torn down.
1667         serviceStateChanged(TelephonyManager.NETWORK_TYPE_UMTS,
1668                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1669         processAllMessages();
1670 
1671         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA);
1672         verifyAllDataDisconnected();
1673     }
1674 
1675     @Test
testVoiceCallEndedOnVoiceDataNonConcurrentNetwork()1676     public void testVoiceCallEndedOnVoiceDataNonConcurrentNetwork() throws Exception {
1677         doReturn(false).when(mSST).isConcurrentVoiceAndDataAllowed();
1678         doReturn(PhoneConstants.State.OFFHOOK).when(mCT).getState();
1679 
1680         mDataNetworkControllerUT.addNetworkRequest(
1681                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
1682         processAllMessages();
1683 
1684         // Data should not be allowed when voice/data concurrent is not supported.
1685         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1686 
1687         // Call ended.
1688         doReturn(PhoneConstants.State.IDLE).when(mCT).getState();
1689         mDataNetworkControllerUT.obtainMessage(EVENT_VOICE_CALL_ENDED).sendToTarget();
1690         processAllMessages();
1691 
1692         // It should have no internet setup at the beginning.
1693         verifyAllDataDisconnected();
1694 
1695         // But after some delays data should be restored.
1696         moveTimeForward(500);
1697         processAllMessages();
1698         verifyInternetConnected();
1699     }
1700 
1701     @Test
testEcbmChanged()1702     public void testEcbmChanged() throws Exception {
1703         doReturn(true).when(mPhone).isInCdmaEcm();
1704         mDataNetworkControllerUT.addNetworkRequest(
1705                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
1706         processAllMessages();
1707 
1708         // Data should not be allowed when the device is in ECBM.
1709         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1710 
1711         // Exit ECBM
1712         doReturn(false).when(mPhone).isInCdmaEcm();
1713         mDataNetworkControllerUT.obtainMessage(20/*EVENT_EMERGENCY_CALL_CHANGED*/).sendToTarget();
1714         processAllMessages();
1715 
1716         // Verify data is restored.
1717         verifyInternetConnected();
1718     }
1719 
1720     @Test
testIsNetworkRequestSatisfiedByTransportCellularTransportRequest()1721     public void testIsNetworkRequestSatisfiedByTransportCellularTransportRequest() {
1722         mIsNonTerrestrialNetwork = true;
1723 
1724         // Data is not supported for cellular transport network request while using satellite
1725         // network
1726         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
1727                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1728 
1729         // Set network request transport as Cellular in satellite network
1730         NetworkCapabilities netCaps = new NetworkCapabilities();
1731         netCaps.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
1732         netCaps.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1733         netCaps.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
1734         mDataNetworkControllerUT.addNetworkRequest(new TelephonyNetworkRequest(
1735                 new NetworkRequest(netCaps, ConnectivityManager.TYPE_MOBILE, ++mNetworkRequestId,
1736                         NetworkRequest.Type.REQUEST), mPhone, mFeatureFlags));
1737         processAllMessages();
1738 
1739         // Verify data is not connected since Network request cannot satisfy by transport
1740         verify(mMockedDataNetworkControllerCallback, never())
1741                 .onConnectedInternetDataNetworksChanged(any());
1742 
1743         // However, WLAN network setup shouldn't be affected
1744         doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WLAN).when(mAccessNetworksManager)
1745                 .getPreferredTransportByNetworkCapability(anyInt());
1746         mDataNetworkControllerUT.obtainMessage(5 /*EVENT_REEVALUATE_UNSATISFIED_NETWORK_REQUESTS*/,
1747                 DataEvaluation.DataEvaluationReason.PREFERRED_TRANSPORT_CHANGED).sendToTarget();
1748         processAllMessages();
1749         verify(mMockedDataNetworkControllerCallback).onConnectedInternetDataNetworksChanged(any());
1750 
1751         mIsNonTerrestrialNetwork = false;
1752     }
1753 
1754     @Test
testMobileDataDisabledIsValidRestrictedRequestWithSatelliteInternetRequest()1755     public void testMobileDataDisabledIsValidRestrictedRequestWithSatelliteInternetRequest() {
1756         mIsNonTerrestrialNetwork = true;
1757 
1758         //Mobile Data Disabled
1759         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
1760                 TelephonyManager.DATA_ENABLED_REASON_USER, false, mContext.getOpPackageName());
1761         processAllMessages();
1762 
1763         // Data is not supported for cellular transport network request while using satellite
1764         // network
1765         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
1766                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1767 
1768         // Set network request transport as Satellite with restricted capability + internet
1769         NetworkCapabilities netCaps = new NetworkCapabilities();
1770         netCaps.addTransportType(NetworkCapabilities.TRANSPORT_SATELLITE);
1771         netCaps.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1772         netCaps.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
1773         mDataNetworkControllerUT.addNetworkRequest(new TelephonyNetworkRequest(
1774                 new NetworkRequest(netCaps, ConnectivityManager.TYPE_MOBILE, ++mNetworkRequestId,
1775                         NetworkRequest.Type.REQUEST), mPhone, mFeatureFlags));
1776         processAllMessages();
1777 
1778         // Verify data is not connected since Network request cannot satisfy by transport
1779         verify(mMockedDataNetworkControllerCallback, never())
1780                 .onConnectedInternetDataNetworksChanged(any());
1781 
1782         mIsNonTerrestrialNetwork = false;
1783     }
1784 
1785     @Test
testMobileDataDisabledIsValidRestrictedRequestWithTransportSatelliteMMSRequest()1786     public void testMobileDataDisabledIsValidRestrictedRequestWithTransportSatelliteMMSRequest()
1787             throws Exception {
1788         mIsNonTerrestrialNetwork = true;
1789 
1790         // Data disabled
1791         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
1792                 TelephonyManager.DATA_ENABLED_REASON_USER, false, mContext.getOpPackageName());
1793         // Always allow MMS off
1794         mDataNetworkControllerUT.getDataSettingsManager().setMobileDataPolicy(TelephonyManager
1795                 .MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED, false);
1796         processAllMessages();
1797 
1798         // Data is not supported for cellular transport network request while using satellite
1799         // network
1800         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
1801                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1802 
1803         // Set network request transport as Cellular+Satellite with restricted capability + mms
1804         NetworkCapabilities netCaps = new NetworkCapabilities();
1805         netCaps.addTransportType(NetworkCapabilities.TRANSPORT_SATELLITE);
1806         netCaps.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
1807         netCaps.addCapability(NetworkCapabilities.NET_CAPABILITY_MMS);
1808         netCaps.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
1809         mDataNetworkControllerUT.addNetworkRequest(new TelephonyNetworkRequest(
1810                 new NetworkRequest(netCaps, ConnectivityManager.TYPE_MOBILE, ++mNetworkRequestId,
1811                         NetworkRequest.Type.REQUEST), mPhone, mFeatureFlags));
1812         processAllMessages();
1813 
1814         // Verify mms is not connected
1815         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_MMS);
1816 
1817         mIsNonTerrestrialNetwork = false;
1818     }
1819 
1820     @Test
testOnMmsAlwaysALlowedIsValidRestrictedRequestWithTransportSatelliteMMSRequest()1821     public void testOnMmsAlwaysALlowedIsValidRestrictedRequestWithTransportSatelliteMMSRequest()
1822             throws Exception {
1823         mIsNonTerrestrialNetwork = true;
1824 
1825         // Data disabled
1826         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
1827                 TelephonyManager.DATA_ENABLED_REASON_USER, false, mContext.getOpPackageName());
1828         // Always allow MMS On
1829         mDataNetworkControllerUT.getDataSettingsManager().setMobileDataPolicy(TelephonyManager
1830                 .MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED, true);
1831         processAllMessages();
1832 
1833         // Data is not supported for cellular transport network request while using satellite
1834         // network
1835         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
1836                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1837 
1838         // Set network request transport as Cellular+Satellite with restricted capability + mms
1839         NetworkCapabilities netCaps = new NetworkCapabilities();
1840         netCaps.addTransportType(NetworkCapabilities.TRANSPORT_SATELLITE);
1841         netCaps.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
1842         netCaps.addCapability(NetworkCapabilities.NET_CAPABILITY_MMS);
1843         netCaps.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
1844         mDataNetworkControllerUT.addNetworkRequest(new TelephonyNetworkRequest(
1845                 new NetworkRequest(netCaps, ConnectivityManager.TYPE_MOBILE, ++mNetworkRequestId,
1846                         NetworkRequest.Type.REQUEST), mPhone, mFeatureFlags));
1847         processAllMessages();
1848 
1849         // Verify mms is connected if mms always allowed is on
1850         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_MMS);
1851 
1852         mIsNonTerrestrialNetwork = false;
1853     }
1854 
1855     @Test
testIsNetworkRequestSatisfiedByTransportSatelliteTransportRequest_Terrestrial()1856     public void testIsNetworkRequestSatisfiedByTransportSatelliteTransportRequest_Terrestrial() {
1857         // Set network request transport as satellite in satellite network
1858         NetworkCapabilities netCaps = new NetworkCapabilities();
1859         netCaps.addTransportType(NetworkCapabilities.TRANSPORT_SATELLITE);
1860         netCaps.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1861         netCaps.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
1862         mDataNetworkControllerUT.addNetworkRequest(new TelephonyNetworkRequest(
1863                 new NetworkRequest(netCaps, ConnectivityManager.TYPE_MOBILE, ++mNetworkRequestId,
1864                         NetworkRequest.Type.REQUEST), mPhone, mFeatureFlags));
1865         processAllMessages();
1866 
1867         // Verify data is not supported for satellite transport network request while using cellular
1868         verify(mMockedDataNetworkControllerCallback, never())
1869                 .onConnectedInternetDataNetworksChanged(any());
1870 
1871     }
1872 
1873     @Test
testIsNetworkRequestSatisfiedByTransportSatelliteTransportRequest()1874     public void testIsNetworkRequestSatisfiedByTransportSatelliteTransportRequest() {
1875         mIsNonTerrestrialNetwork = true;
1876 
1877         // Data is supported for satellite transport network request while using satellite network
1878         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
1879                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1880 
1881         // Set network request transport as satellite while using satellite network
1882         NetworkCapabilities netCaps = new NetworkCapabilities();
1883         netCaps.addTransportType(NetworkCapabilities.TRANSPORT_SATELLITE);
1884         netCaps.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1885         netCaps.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
1886         mDataNetworkControllerUT.addNetworkRequest(new TelephonyNetworkRequest(
1887                 new NetworkRequest(netCaps, ConnectivityManager.TYPE_MOBILE, ++mNetworkRequestId,
1888                         NetworkRequest.Type.REQUEST), mPhone, mFeatureFlags));
1889         processAllMessages();
1890 
1891         // Verify data is connected since Network request satisfy by transport
1892         verify(mMockedDataNetworkControllerCallback).onConnectedInternetDataNetworksChanged(any());
1893 
1894         mIsNonTerrestrialNetwork = false;
1895     }
1896 
1897     @Test
testIsNetworkRequestSatisfiedByTransportNoTransportRequest()1898     public void testIsNetworkRequestSatisfiedByTransportNoTransportRequest() {
1899         mIsNonTerrestrialNetwork = true;
1900 
1901         // Data is supported for no transport network request while using satellite network
1902         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
1903                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1904 
1905         // Set network request transport as no transport with Internet capability
1906         NetworkCapabilities netCaps = new NetworkCapabilities();
1907         netCaps.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1908         netCaps.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
1909         mDataNetworkControllerUT.addNetworkRequest(new TelephonyNetworkRequest(
1910                 new NetworkRequest(netCaps, ConnectivityManager.TYPE_MOBILE, ++mNetworkRequestId,
1911                         NetworkRequest.Type.REQUEST), mPhone, mFeatureFlags));
1912         processAllMessages();
1913 
1914         // Verify data is connected since Network request satisfy by transport
1915         verify(mMockedDataNetworkControllerCallback).onConnectedInternetDataNetworksChanged(any());
1916 
1917         mIsNonTerrestrialNetwork = false;
1918     }
1919 
1920     @Test
testIsNetworkCapabilitySatelliteAndCellularCapableImsCellularTransportRequest()1921     public void testIsNetworkCapabilitySatelliteAndCellularCapableImsCellularTransportRequest()
1922             throws Exception {
1923         mIsNonTerrestrialNetwork = true;
1924 
1925         // IMS PDN is supported for cellular network request while using satellite network
1926         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
1927                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1928 
1929         // Set network request transport as Cellular + IMS
1930         NetworkCapabilities netCaps = new NetworkCapabilities();
1931         netCaps.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
1932         netCaps.addCapability(NetworkCapabilities.NET_CAPABILITY_IMS);
1933         netCaps.addCapability(NetworkCapabilities.NET_CAPABILITY_MMTEL);
1934         netCaps.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
1935         mDataNetworkControllerUT.addNetworkRequest(new TelephonyNetworkRequest(
1936                 new NetworkRequest(netCaps, ConnectivityManager.TYPE_MOBILE, ++mNetworkRequestId,
1937                         NetworkRequest.Type.REQUEST), mPhone, mFeatureFlags));
1938         processAllMessages();
1939 
1940         // Verify ims is connected since, cellular network request for ims is allowed while using
1941         // satellite network
1942         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
1943                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
1944 
1945         mIsNonTerrestrialNetwork = false;
1946     }
1947 
1948     @Test
testRoamingDataChanged()1949     public void testRoamingDataChanged() throws Exception {
1950         doReturn(true).when(mServiceState).getDataRoaming();
1951 
1952         // Roaming data disabled
1953         mDataNetworkControllerUT.getDataSettingsManager().setDataRoamingEnabled(false);
1954         processAllMessages();
1955 
1956         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
1957                 NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1958         mDataNetworkControllerUT.addNetworkRequest(
1959                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
1960         processAllMessages();
1961 
1962         // Data should not be allowed when roaming data is disabled.
1963         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1964         Mockito.clearInvocations(mMockedDataNetworkControllerCallback);
1965 
1966         // Roaming data enabled
1967         mDataNetworkControllerUT.getDataSettingsManager().setDataRoamingEnabled(true);
1968         processAllMessages();
1969 
1970         // Verify data is restored.
1971         verifyInternetConnected();
1972 
1973         // Roaming data disabled
1974         mDataNetworkControllerUT.getDataSettingsManager().setDataRoamingEnabled(false);
1975         processAllMessages();
1976 
1977         // Verify data is torn down.
1978         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1979         Mockito.clearInvocations(mMockedDataNetworkControllerCallback);
1980 
1981         // Registration is back to HOME.
1982         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
1983                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1984         processAllFutureMessages();
1985 
1986         // Verify data is restored.
1987         verifyInternetConnected();
1988     }
1989 
1990     @Test
testDataEnabledChanged()1991     public void testDataEnabledChanged() throws Exception {
1992         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
1993                 TelephonyManager.DATA_ENABLED_REASON_USER, false, mContext.getOpPackageName());
1994         mDataNetworkControllerUT.addNetworkRequest(
1995                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
1996         processAllMessages();
1997 
1998         // Data should not be allowed when user data is disabled.
1999         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
2000         Mockito.clearInvocations(mMockedDataNetworkControllerCallback);
2001 
2002         // User data enabled
2003         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
2004                 TelephonyManager.DATA_ENABLED_REASON_USER, true, mContext.getOpPackageName());
2005         processAllMessages();
2006 
2007         // Verify data is restored.
2008         verifyInternetConnected();
2009         Mockito.clearInvocations(mMockedDataNetworkControllerCallback);
2010 
2011         // User data disabled
2012         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
2013                 TelephonyManager.DATA_ENABLED_REASON_USER, false, mContext.getOpPackageName());
2014         processAllMessages();
2015 
2016         // Verify data is torn down.
2017         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
2018     }
2019 
2020     @Test
testNotifyWhenSetDataEnabled()2021     public void testNotifyWhenSetDataEnabled() throws Exception {
2022         // Set a valid sub id, DEFAULT_SUBSCRIPTION_ID
2023         int subId = Integer.MAX_VALUE;
2024         Field field = DataSettingsManager.class.getDeclaredField("mSubId");
2025         field.setAccessible(true);
2026         field.setInt(mDataNetworkControllerUT.getDataSettingsManager(), subId);
2027         boolean isDataEnabled = mDataNetworkControllerUT.getDataSettingsManager().isDataEnabled();
2028         doReturn(mDataNetworkControllerUT.getDataSettingsManager())
2029                 .when(mPhone).getDataSettingsManager();
2030         MultiSimSettingController controller = Mockito.spy(new MultiSimSettingController(mContext,
2031                 mFeatureFlags));
2032         doReturn(true).when(controller).isCarrierConfigLoadedForAllSub();
2033         replaceInstance(MultiSimSettingController.class, "sInstance", null, controller);
2034 
2035         // Mock Data Overall data is always enabled due to auto data switch,
2036         // verify the test shouldn't rely on the overall data status
2037         doReturn(1).when(mPhone).getSubId();
2038         doReturn(2).when(mSubscriptionManagerService).getDefaultDataSubId();
2039         Phone phone2 = Mockito.mock(Phone.class);
2040         phone2.mCi = mSimulatedCommands;
2041         doReturn(true).when(phone2).isUserDataEnabled();
2042         doReturn(mDataSettingsManager).when(phone2).getDataSettingsManager();
2043         replaceInstance(PhoneFactory.class, "sPhones", null, new Phone[]{mPhone, phone2});
2044         mDataNetworkControllerUT.getDataSettingsManager().setMobileDataPolicy(TelephonyManager
2045                 .MOBILE_DATA_POLICY_AUTO_DATA_SWITCH, true);
2046         processAllMessages();
2047         clearInvocations(mPhone);
2048 
2049         controller.notifyAllSubscriptionLoaded();
2050         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
2051                 TelephonyManager.DATA_ENABLED_REASON_USER, !isDataEnabled,
2052                 mContext.getOpPackageName());
2053         processAllMessages();
2054 
2055         // Verify not to notify MultiSimSettingController due to internal calling package
2056         verify(controller, never()).notifyUserDataEnabled(anyInt(), anyBoolean());
2057 
2058         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
2059                 TelephonyManager.DATA_ENABLED_REASON_USER, isDataEnabled,
2060                 mContext.getOpPackageName());
2061         processAllMessages();
2062 
2063         // Verify not to notify MultiSimSettingController due to internal calling package
2064         verify(controller, never()).notifyUserDataEnabled(anyInt(), anyBoolean());
2065 
2066         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
2067                 TelephonyManager.DATA_ENABLED_REASON_USER, !isDataEnabled, "com.android.settings");
2068         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
2069                 TelephonyManager.DATA_ENABLED_REASON_USER, isDataEnabled, "com.android.settings");
2070         processAllMessages();
2071 
2072         // Verify to notify MultiSimSettingController exactly 2 times
2073         verify(controller, times(2)).notifyUserDataEnabled(anyInt(), anyBoolean());
2074         verify(mPhone, never()).notifyDataEnabled(anyBoolean(), anyInt());
2075     }
2076 
2077     @Test
testMmsAlwaysAllowedDataDisabled()2078     public void testMmsAlwaysAllowedDataDisabled() throws Exception {
2079         // Data disabled
2080         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
2081                 TelephonyManager.DATA_ENABLED_REASON_USER, false, mContext.getOpPackageName());
2082         // Always allow MMS
2083         mDataNetworkControllerUT.getDataSettingsManager().setMobileDataPolicy(TelephonyManager
2084                 .MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED, true);
2085         processAllMessages();
2086         mDataNetworkControllerUT.addNetworkRequest(
2087                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_MMS));
2088         processAllMessages();
2089 
2090         // Make sure MMS is the only capability advertised, but not internet or SUPL.
2091         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_MMS);
2092         verifyConnectedNetworkHasDataProfile(mGeneralPurposeDataProfile);
2093         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
2094         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL);
2095 
2096         mDataNetworkControllerUT.obtainMessage(16 /*EVENT_REEVALUATE_EXISTING_DATA_NETWORKS*/,
2097                 DataEvaluation.DataEvaluationReason.DATA_SERVICE_STATE_CHANGED).sendToTarget();
2098 
2099         processAllFutureMessages();
2100 
2101         // Make sure IMS network is not torn down
2102         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_MMS);
2103 
2104         // Remove MMS data enabled override
2105         mDataNetworkControllerUT.getDataSettingsManager().setMobileDataPolicy(TelephonyManager
2106                 .MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED, false);
2107         processAllMessages();
2108 
2109         // Make sure MMS is torn down when the override is disabled.
2110         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_MMS);
2111     }
2112 
2113     @Test
testMmsAlwaysAllowedRoamingDisabled()2114     public void testMmsAlwaysAllowedRoamingDisabled() throws Exception {
2115         // Data roaming disabled
2116         doReturn(true).when(mServiceState).getDataRoaming();
2117         mDataNetworkControllerUT.getDataSettingsManager().setDataRoamingEnabled(false);
2118         processAllMessages();
2119 
2120         // Device is roaming
2121         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
2122                 NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
2123         // Always allow MMS
2124         mDataNetworkControllerUT.getDataSettingsManager().setMobileDataPolicy(TelephonyManager
2125                 .MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED, true);
2126         processAllMessages();
2127 
2128         mDataNetworkControllerUT.addNetworkRequest(
2129                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_MMS));
2130         processAllMessages();
2131 
2132         // Make sure MMS is not allowed. MMS always allowed should be only applicable to data
2133         // disabled case.
2134         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_MMS);
2135     }
2136 
2137     @Test
testIsDataEnabledOverriddenForApnDataDuringCall()2138     public void testIsDataEnabledOverriddenForApnDataDuringCall() throws Exception {
2139         // Assume phone2 is the default data phone
2140         Phone phone2 = Mockito.mock(Phone.class);
2141         replaceInstance(PhoneFactory.class, "sPhones", null, new Phone[]{mPhone, phone2});
2142         doReturn(2).when(mSubscriptionManagerService).getDefaultDataSubId();
2143         doReturn(1).when(mPhone).getSubId();
2144 
2145         // Data disabled on nonDDS
2146         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
2147                 TelephonyManager.DATA_ENABLED_REASON_USER, false, mContext.getOpPackageName());
2148 
2149         // Enable during data call mobile policy
2150         mDataNetworkControllerUT.getDataSettingsManager().setMobileDataPolicy(TelephonyManager
2151                 .MOBILE_DATA_POLICY_DATA_ON_NON_DEFAULT_DURING_VOICE_CALL, true);
2152         processAllMessages();
2153 
2154         // No active phone call
2155         doReturn(PhoneConstants.State.IDLE).when(mPhone).getState();
2156         mDataNetworkControllerUT.addNetworkRequest(
2157                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
2158         processAllMessages();
2159 
2160         // Verify no internet connection due to no active phone call
2161         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
2162 
2163         // Phone ringing
2164         doReturn(PhoneConstants.State.RINGING).when(mPhone).getState();
2165         // Data is user enabled on DDS
2166         doReturn(true).when(phone2).isUserDataEnabled();
2167         mDataNetworkControllerUT.addNetworkRequest(
2168                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
2169         processAllMessages();
2170 
2171         // Verify internet connection
2172         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_INTERNET);
2173 
2174         // Disable during data call mobile policy
2175         mDataNetworkControllerUT.getDataSettingsManager().setMobileDataPolicy(TelephonyManager
2176                 .MOBILE_DATA_POLICY_DATA_ON_NON_DEFAULT_DURING_VOICE_CALL, false);
2177         processAllMessages();
2178 
2179         // Verify no internet connection
2180         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
2181     }
2182 
2183     @Test
testIsDataEnabledOverriddenForApnAutoDataSwitch()2184     public void testIsDataEnabledOverriddenForApnAutoDataSwitch() throws Exception {
2185         // Assume phone2 is the default data phone
2186         Phone phone2 = Mockito.mock(Phone.class);
2187         replaceInstance(PhoneFactory.class, "sPhones", null, new Phone[]{mPhone, phone2});
2188         doReturn(2).when(mSubscriptionManagerService).getDefaultDataSubId();
2189 
2190         // Data disabled on nonDDS
2191         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
2192                 TelephonyManager.DATA_ENABLED_REASON_USER, false, mContext.getOpPackageName());
2193 
2194         // Enable auto data switch mobile policy
2195         mDataNetworkControllerUT.getDataSettingsManager().setMobileDataPolicy(TelephonyManager
2196                 .MOBILE_DATA_POLICY_AUTO_DATA_SWITCH, true);
2197         processAllMessages();
2198 
2199         // use disabled data on DDS
2200         doReturn(false).when(phone2).isUserDataEnabled();
2201         mDataNetworkControllerUT.addNetworkRequest(
2202                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
2203         processAllMessages();
2204 
2205         // Verify no internet connection
2206         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
2207 
2208         // use enabled data on DDS
2209         doReturn(true).when(phone2).isUserDataEnabled();
2210         mDataNetworkControllerUT.addNetworkRequest(
2211                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
2212         processAllMessages();
2213 
2214         // Verify internet connection
2215         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_INTERNET);
2216 
2217         // Disable auto data switch mobile policy, but enabled data during call
2218         mDataNetworkControllerUT.getDataSettingsManager().setMobileDataPolicy(TelephonyManager
2219                 .MOBILE_DATA_POLICY_AUTO_DATA_SWITCH, false);
2220         mDataNetworkControllerUT.getDataSettingsManager().setMobileDataPolicy(TelephonyManager
2221                 .MOBILE_DATA_POLICY_DATA_ON_NON_DEFAULT_DURING_VOICE_CALL, true);
2222         doReturn(PhoneConstants.State.RINGING).when(phone2).getState();
2223         processAllMessages();
2224 
2225         // Verify internet connection
2226         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_INTERNET);
2227 
2228         // Disable data during call
2229         mDataNetworkControllerUT.getDataSettingsManager().setMobileDataPolicy(TelephonyManager
2230                 .MOBILE_DATA_POLICY_DATA_ON_NON_DEFAULT_DURING_VOICE_CALL, false);
2231         processAllMessages();
2232 
2233         // Verify no internet connection
2234         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
2235     }
2236 
2237     @Test
testUnmeteredRequestPreferredOnIwlan()2238     public void testUnmeteredRequestPreferredOnIwlan() throws Exception {
2239         // Preferred on cellular
2240         doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WWAN).when(mAccessNetworksManager)
2241                 .getPreferredTransportByNetworkCapability(anyInt());
2242         // Data disabled
2243         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
2244                 TelephonyManager.DATA_ENABLED_REASON_USER, false, mContext.getOpPackageName());
2245         mDataNetworkControllerUT.addNetworkRequest(
2246                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
2247         processAllMessages();
2248 
2249         // Data should not be allowed when roaming + user data are disabled (soft failure reasons)
2250         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
2251 
2252         // Set transport to WLAN (unmetered)
2253         doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WLAN).when(mAccessNetworksManager)
2254                 .getPreferredTransportByNetworkCapability(
2255                         eq(NetworkCapabilities.NET_CAPABILITY_INTERNET));
2256         // Data remain disabled, but trigger the preference evaluation.
2257         mDataNetworkControllerUT.obtainMessage(21 /*EVENT_EVALUATE_PREFERRED_TRANSPORT*/,
2258                 NetworkCapabilities.NET_CAPABILITY_INTERNET, 0).sendToTarget();
2259         mDataNetworkControllerUT.obtainMessage(5 /*EVENT_REEVALUATE_UNSATISFIED_NETWORK_REQUESTS*/,
2260                 DataEvaluation.DataEvaluationReason.PREFERRED_TRANSPORT_CHANGED).sendToTarget();
2261         processAllMessages();
2262 
2263         // Verify data is allowed even if data is disabled.
2264         verifyInternetConnected();
2265     }
2266 
2267     @Test
testUnmeteredRequestDataRoamingDisabled()2268     public void testUnmeteredRequestDataRoamingDisabled() throws Exception {
2269         // Data roaming disabled
2270         doReturn(true).when(mServiceState).getDataRoaming();
2271         mDataNetworkControllerUT.getDataSettingsManager().setDataRoamingEnabled(false);
2272         processAllMessages();
2273 
2274         // MMS is unmetered
2275         mCarrierConfig.putStringArray(
2276                 CarrierConfigManager.KEY_CARRIER_METERED_ROAMING_APN_TYPES_STRINGS,
2277                 new String[]{"default", "dun", "supl"});
2278         carrierConfigChanged();
2279         // Manually set data roaming to false in case ro.com.android.dataroaming is true.
2280         // TODO(b/232575718): Figure out a way to mock ro.com.android.dataroaming for tests.
2281         mDataNetworkControllerUT.getDataSettingsManager().setDataRoamingEnabled(false);
2282         // Device is roaming
2283         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
2284                 NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
2285 
2286         mDataNetworkControllerUT.addNetworkRequest(
2287                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_MMS));
2288         processAllMessages();
2289 
2290         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_MMS);
2291         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
2292     }
2293 
2294     @Test
testUnmeteredRequestDataDisabled()2295     public void testUnmeteredRequestDataDisabled() throws Exception {
2296         // MMS is unmetered
2297         mCarrierConfig.putStringArray(
2298                 CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
2299                 new String[]{"default", "dun", "supl"});
2300         carrierConfigChanged();
2301 
2302         // Data disabled
2303         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
2304                 TelephonyManager.DATA_ENABLED_REASON_USER, false, mContext.getOpPackageName());
2305 
2306         mDataNetworkControllerUT.addNetworkRequest(
2307                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_MMS));
2308 
2309         processAllMessages();
2310 
2311         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_MMS);
2312         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
2313     }
2314 
2315     @Test
testEmergencyRequest()2316     public void testEmergencyRequest() throws Exception {
2317         // Data disabled
2318         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
2319                 TelephonyManager.DATA_ENABLED_REASON_USER, false, mContext.getOpPackageName());
2320         mDataNetworkControllerUT.addNetworkRequest(
2321                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_EIMS));
2322         processAllMessages();
2323 
2324         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_EIMS);
2325         verifyConnectedNetworkHasDataProfile(mEmergencyDataProfile);
2326     }
2327 
2328     @Test
testEmergencyRequestWithThrottling()2329     public void testEmergencyRequestWithThrottling() throws Exception {
2330         serviceStateChanged(TelephonyManager.NETWORK_TYPE_UNKNOWN,
2331                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING, /* data */
2332                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING, /* voice */
2333                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING, /* iwlan */
2334                 null, false);
2335         mDataNetworkControllerUT.getDataRetryManager()
2336                 .registerCallback(mMockedDataRetryManagerCallback);
2337 
2338         setFailedSetupDataResponse(mMockedWwanDataServiceManager, DataFailCause.PROTOCOL_ERRORS,
2339                 10000, false);
2340         mDataNetworkControllerUT.addNetworkRequest(
2341                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_EIMS));
2342         processAllMessages();
2343 
2344         // There should be only one attempt, and no retry should happen because the second one
2345         // was throttled.
2346         verify(mMockedWwanDataServiceManager, times(1)).setupDataCall(anyInt(),
2347                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
2348                 any(), any(), anyBoolean(), any(Message.class));
2349 
2350         ArgumentCaptor<List<ThrottleStatus>> throttleStatusCaptor =
2351                 ArgumentCaptor.forClass(List.class);
2352         verify(mMockedDataRetryManagerCallback)
2353                 .onThrottleStatusChanged(throttleStatusCaptor.capture());
2354         assertThat(throttleStatusCaptor.getValue()).hasSize(1);
2355         ThrottleStatus throttleStatus = throttleStatusCaptor.getValue().get(0);
2356         assertThat(throttleStatus.getApnType()).isEqualTo(ApnSetting.TYPE_EMERGENCY);
2357         assertThat(throttleStatus.getRetryType())
2358                 .isEqualTo(ThrottleStatus.RETRY_TYPE_NEW_CONNECTION);
2359         assertThat(throttleStatus.getTransportType())
2360                 .isEqualTo(AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
2361 
2362         Mockito.reset(mMockedWwanDataServiceManager);
2363         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
2364                 NetworkRegistrationInfo.REGISTRATION_STATE_DENIED, /* data */
2365                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING, /* voice */
2366                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING, /* iwlan */
2367                 null, true);
2368 
2369         // No retry should happen because the second one was throttled.
2370         verify(mMockedWwanDataServiceManager, never()).setupDataCall(anyInt(),
2371                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
2372                 any(), any(), anyBoolean(), any(Message.class));
2373     }
2374 
2375     @Test
testHandoverRuleFromString()2376     public void testHandoverRuleFromString() {
2377         HandoverRule handoverRule = new HandoverRule("source=GERAN|UTRAN|EUTRAN|NGRAN|IWLAN, "
2378                 + "target=GERAN|UTRAN|EUTRAN|NGRAN|IWLAN, type=allowed");
2379         assertThat(handoverRule.sourceAccessNetworks).containsExactly(AccessNetworkType.GERAN,
2380                 AccessNetworkType.UTRAN, AccessNetworkType.EUTRAN, AccessNetworkType.NGRAN,
2381                 AccessNetworkType.IWLAN);
2382         assertThat(handoverRule.targetAccessNetworks).containsExactly(AccessNetworkType.GERAN,
2383                 AccessNetworkType.UTRAN, AccessNetworkType.EUTRAN, AccessNetworkType.NGRAN,
2384                 AccessNetworkType.IWLAN);
2385         assertThat(handoverRule.type).isEqualTo(HandoverRule.RULE_TYPE_ALLOWED);
2386         assertThat(handoverRule.isOnlyForRoaming).isFalse();
2387         assertThat(handoverRule.networkCapabilities).isEmpty();
2388 
2389         handoverRule = new HandoverRule("source=   NGRAN|     IWLAN, "
2390                 + "target  =    EUTRAN,    type  =    disallowed ");
2391         assertThat(handoverRule.sourceAccessNetworks).containsExactly(AccessNetworkType.NGRAN,
2392                 AccessNetworkType.IWLAN);
2393         assertThat(handoverRule.targetAccessNetworks).containsExactly(AccessNetworkType.EUTRAN);
2394         assertThat(handoverRule.type).isEqualTo(HandoverRule.RULE_TYPE_DISALLOWED);
2395         assertThat(handoverRule.isOnlyForRoaming).isFalse();
2396         assertThat(handoverRule.networkCapabilities).isEmpty();
2397 
2398         handoverRule = new HandoverRule("source=   IWLAN, "
2399                 + "target  =    EUTRAN,    type  =    disallowed, roaming = true,"
2400                 + " capabilities = IMS | EIMS ");
2401         assertThat(handoverRule.sourceAccessNetworks).containsExactly(AccessNetworkType.IWLAN);
2402         assertThat(handoverRule.targetAccessNetworks).containsExactly(AccessNetworkType.EUTRAN);
2403         assertThat(handoverRule.type).isEqualTo(HandoverRule.RULE_TYPE_DISALLOWED);
2404         assertThat(handoverRule.networkCapabilities).containsExactly(
2405                 NetworkCapabilities.NET_CAPABILITY_IMS, NetworkCapabilities.NET_CAPABILITY_EIMS);
2406         assertThat(handoverRule.isOnlyForRoaming).isTrue();
2407 
2408         handoverRule = new HandoverRule("source=EUTRAN|NGRAN|IWLAN|UNKNOWN, "
2409                 + "target=EUTRAN|NGRAN|IWLAN, type=disallowed, capabilities = IMS|EIMS");
2410         assertThat(handoverRule.sourceAccessNetworks).containsExactly(AccessNetworkType.EUTRAN,
2411                 AccessNetworkType.NGRAN, AccessNetworkType.IWLAN, AccessNetworkType.UNKNOWN);
2412         assertThat(handoverRule.targetAccessNetworks).containsExactly(AccessNetworkType.EUTRAN,
2413                 AccessNetworkType.NGRAN, AccessNetworkType.IWLAN);
2414         assertThat(handoverRule.type).isEqualTo(HandoverRule.RULE_TYPE_DISALLOWED);
2415         assertThat(handoverRule.networkCapabilities).containsExactly(
2416                 NetworkCapabilities.NET_CAPABILITY_IMS, NetworkCapabilities.NET_CAPABILITY_EIMS);
2417 
2418         assertThrows(IllegalArgumentException.class,
2419                 () -> new HandoverRule("V2hhdCBUaGUgRnVjayBpcyB0aGlzIQ=="));
2420 
2421         assertThrows(IllegalArgumentException.class,
2422                 () -> new HandoverRule("target=GERAN|UTRAN|EUTRAN|NGRAN|IWLAN, type=allowed"));
2423 
2424         assertThrows(IllegalArgumentException.class,
2425                 () -> new HandoverRule("source=GERAN|UTRAN|EUTRAN|NGRAN|IWLAN, type=allowed"));
2426 
2427         assertThrows(IllegalArgumentException.class,
2428                 () -> new HandoverRule("source=GERAN, target=UNKNOWN, type=disallowed, "
2429                         + "capabilities=IMS"));
2430 
2431         assertThrows(IllegalArgumentException.class,
2432                 () -> new HandoverRule("source=UNKNOWN, target=IWLAN, type=allowed, "
2433                         + "capabilities=IMS"));
2434 
2435         assertThrows(IllegalArgumentException.class,
2436                 () -> new HandoverRule("source=GERAN, target=IWLAN, type=wtf"));
2437 
2438         assertThrows(IllegalArgumentException.class,
2439                 () -> new HandoverRule("source=GERAN, target=NGRAN, type=allowed"));
2440 
2441         assertThrows(IllegalArgumentException.class,
2442                 () -> new HandoverRule("source=IWLAN, target=WTFRAN, type=allowed"));
2443 
2444         assertThrows(IllegalArgumentException.class,
2445                 () -> new HandoverRule("source=IWLAN, target=|, type=allowed"));
2446 
2447         assertThrows(IllegalArgumentException.class,
2448                 () -> new HandoverRule("source=GERAN, target=IWLAN, type=allowed, capabilities=|"));
2449 
2450         assertThrows(IllegalArgumentException.class,
2451                 () -> new HandoverRule("source=GERAN, target=IWLAN, type=allowed, capabilities="));
2452 
2453         assertThrows(IllegalArgumentException.class,
2454                 () -> new HandoverRule("source=GERAN, target=IWLAN, type=allowed, "
2455                         + "capabilities=wtf"));
2456     }
2457 
2458     @Test
testIsNetworkTypeCongested()2459     public void testIsNetworkTypeCongested() throws Exception {
2460         Set<Integer> congestedNetworkTypes = new ArraySet<>();
2461         doReturn(congestedNetworkTypes).when(mDataNetworkController)
2462                 .getCongestedOverrideNetworkTypes();
2463         testSetupDataNetwork();
2464         DataNetwork dataNetwork = getDataNetworks().get(0);
2465 
2466         // Set 5G unmetered
2467         congestedNetworkTypes.add(TelephonyManager.NETWORK_TYPE_NR);
2468         mDataNetworkControllerUT.obtainMessage(EVENT_SUBSCRIPTION_OVERRIDE,
2469                 NetworkPolicyManager.SUBSCRIPTION_OVERRIDE_CONGESTED,
2470                 NetworkPolicyManager.SUBSCRIPTION_OVERRIDE_CONGESTED,
2471                 new int[]{TelephonyManager.NETWORK_TYPE_NR}).sendToTarget();
2472         dataNetwork.sendMessage(16/*EVENT_SUBSCRIPTION_PLAN_OVERRIDE*/);
2473         processAllMessages();
2474         assertEquals(congestedNetworkTypes,
2475                 mDataNetworkControllerUT.getCongestedOverrideNetworkTypes());
2476         assertTrue(dataNetwork.getNetworkCapabilities().hasCapability(
2477                 NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED));
2478 
2479         // Change data network type to NR
2480         doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_NR,
2481                 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE, false))
2482                 .when(mDisplayInfoController).getTelephonyDisplayInfo();
2483         dataNetwork.sendMessage(13/*EVENT_DISPLAY_INFO_CHANGED*/);
2484         processAllMessages();
2485         assertFalse(dataNetwork.getNetworkCapabilities().hasCapability(
2486                 NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED));
2487 
2488         // Set all network types metered
2489         congestedNetworkTypes.clear();
2490         mDataNetworkControllerUT.obtainMessage(EVENT_SUBSCRIPTION_OVERRIDE,
2491                 NetworkPolicyManager.SUBSCRIPTION_OVERRIDE_CONGESTED, 0,
2492                 TelephonyManager.getAllNetworkTypes()).sendToTarget();
2493         dataNetwork.sendMessage(16/*EVENT_SUBSCRIPTION_PLAN_OVERRIDE*/);
2494         processAllMessages();
2495         assertTrue(mDataNetworkControllerUT.getCongestedOverrideNetworkTypes().isEmpty());
2496         assertTrue(dataNetwork.getNetworkCapabilities().hasCapability(
2497                 NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED));
2498     }
2499 
2500     @Test
testIsNetworkTypeUnmeteredViaSubscriptionOverride()2501     public void testIsNetworkTypeUnmeteredViaSubscriptionOverride() throws Exception {
2502         Set<Integer> unmeteredNetworkTypes = new ArraySet<>();
2503         doReturn(unmeteredNetworkTypes).when(mDataNetworkController)
2504                 .getUnmeteredOverrideNetworkTypes();
2505         testSetupDataNetwork();
2506         DataNetwork dataNetwork = getDataNetworks().get(0);
2507 
2508         // Set 5G unmetered
2509         unmeteredNetworkTypes.add(TelephonyManager.NETWORK_TYPE_NR);
2510         mDataNetworkControllerUT.obtainMessage(EVENT_SUBSCRIPTION_OVERRIDE,
2511                 NetworkPolicyManager.SUBSCRIPTION_OVERRIDE_UNMETERED,
2512                 NetworkPolicyManager.SUBSCRIPTION_OVERRIDE_UNMETERED,
2513                 new int[]{TelephonyManager.NETWORK_TYPE_NR}).sendToTarget();
2514         dataNetwork.sendMessage(16/*EVENT_SUBSCRIPTION_PLAN_OVERRIDE*/);
2515         processAllMessages();
2516         assertEquals(unmeteredNetworkTypes,
2517                 mDataNetworkControllerUT.getUnmeteredOverrideNetworkTypes());
2518         assertFalse(dataNetwork.getNetworkCapabilities().hasCapability(
2519                 NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED));
2520         assertThat(mDataNetworkControllerUT.isInternetUnmetered()).isFalse();
2521 
2522         // Change data network type to NR
2523         doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_NR,
2524                 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE, false))
2525                 .when(mDisplayInfoController).getTelephonyDisplayInfo();
2526         dataNetwork.sendMessage(13/*EVENT_DISPLAY_INFO_CHANGED*/);
2527         processAllMessages();
2528         assertTrue(dataNetwork.getNetworkCapabilities().hasCapability(
2529                 NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED));
2530         assertThat(mDataNetworkControllerUT.isInternetUnmetered()).isTrue();
2531 
2532         // Set all network types metered
2533         unmeteredNetworkTypes.clear();
2534         mDataNetworkControllerUT.obtainMessage(EVENT_SUBSCRIPTION_OVERRIDE,
2535                 NetworkPolicyManager.SUBSCRIPTION_OVERRIDE_UNMETERED, 0,
2536                 TelephonyManager.getAllNetworkTypes()).sendToTarget();
2537         dataNetwork.sendMessage(16/*EVENT_SUBSCRIPTION_PLAN_OVERRIDE*/);
2538         processAllMessages();
2539         assertTrue(mDataNetworkControllerUT.getUnmeteredOverrideNetworkTypes().isEmpty());
2540         assertFalse(dataNetwork.getNetworkCapabilities().hasCapability(
2541                 NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED));
2542         assertThat(mDataNetworkControllerUT.isInternetUnmetered()).isFalse();
2543     }
2544 
2545     @Test
testIsNetworkTypeUnmeteredViaSubscriptionPlans()2546     public void testIsNetworkTypeUnmeteredViaSubscriptionPlans() throws Exception {
2547         List<SubscriptionPlan> subscriptionPlans = new ArrayList<>();
2548         doReturn(subscriptionPlans).when(mDataNetworkController).getSubscriptionPlans();
2549         testSetupDataNetwork();
2550         DataNetwork dataNetwork = getDataNetworks().get(0);
2551 
2552         // Set 5G unmetered
2553         SubscriptionPlan unmetered5GPlan = SubscriptionPlan.Builder
2554                 .createRecurring(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"),
2555                         Period.ofMonths(1))
2556                 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2557                         SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2558                 .setNetworkTypes(new int[]{TelephonyManager.NETWORK_TYPE_NR})
2559                 .build();
2560         SubscriptionPlan generalMeteredPlan = SubscriptionPlan.Builder
2561                 .createRecurring(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"),
2562                         Period.ofMonths(1))
2563                 .setDataLimit(1_000_000_000, SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2564                 .setDataUsage(500_000_000, System.currentTimeMillis())
2565                 .build();
2566         subscriptionPlans.add(generalMeteredPlan);
2567         subscriptionPlans.add(unmetered5GPlan);
2568         mDataNetworkControllerUT.obtainMessage(22/*EVENT_SUBSCRIPTION_PLANS_CHANGED*/,
2569                 new SubscriptionPlan[]{generalMeteredPlan, unmetered5GPlan}).sendToTarget();
2570         dataNetwork.sendMessage(16/*EVENT_SUBSCRIPTION_PLAN_OVERRIDE*/);
2571         processAllMessages();
2572         assertEquals(subscriptionPlans, mDataNetworkControllerUT.getSubscriptionPlans());
2573         assertFalse(dataNetwork.getNetworkCapabilities().hasCapability(
2574                 NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED));
2575         assertThat(mDataNetworkControllerUT.isInternetUnmetered()).isFalse();
2576 
2577 
2578         // Change data network type to NR
2579         doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_NR,
2580                 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE, false))
2581                 .when(mDisplayInfoController).getTelephonyDisplayInfo();
2582         dataNetwork.sendMessage(13/*EVENT_DISPLAY_INFO_CHANGED*/);
2583         processAllMessages();
2584         assertTrue(dataNetwork.getNetworkCapabilities().hasCapability(
2585                 NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED));
2586         assertThat(mDataNetworkControllerUT.isInternetUnmetered()).isTrue();
2587 
2588         // Set all network types metered
2589         subscriptionPlans.clear();
2590         mDataNetworkControllerUT.obtainMessage(22/*EVENT_SUBSCRIPTION_PLANS_CHANGED*/,
2591                 new SubscriptionPlan[]{}).sendToTarget();
2592         dataNetwork.sendMessage(16/*EVENT_SUBSCRIPTION_PLAN_OVERRIDE*/);
2593         processAllMessages();
2594         assertTrue(mDataNetworkControllerUT.getSubscriptionPlans().isEmpty());
2595         assertFalse(dataNetwork.getNetworkCapabilities().hasCapability(
2596                 NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED));
2597         assertThat(mDataNetworkControllerUT.isInternetUnmetered()).isFalse();
2598     }
2599 
2600     @Test
testOnSinglePdnArbitrationExemptIms()2601     public void testOnSinglePdnArbitrationExemptIms() throws Exception {
2602         // On CDMA network, only one data network is allowed.
2603         serviceStateChanged(TelephonyManager.NETWORK_TYPE_1xRTT,
2604                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
2605         // Preferred on cellular
2606         doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WWAN).when(mAccessNetworksManager)
2607                 .getPreferredTransportByNetworkCapability(anyInt());
2608         // Add IMS
2609         TelephonyNetworkRequest ims = createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS,
2610                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
2611         mDataNetworkControllerUT.addNetworkRequest(ims);
2612         processAllMessages();
2613 
2614         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
2615                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
2616 
2617         // Add internet, should be compatible
2618         mDataNetworkControllerUT.addNetworkRequest(
2619                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
2620         setSuccessfulSetupDataResponse(mMockedDataServiceManagers
2621                 .get(AccessNetworkConstants.TRANSPORT_TYPE_WWAN), 2);
2622         processAllMessages();
2623 
2624         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_INTERNET);
2625         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
2626                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
2627 
2628         // Both internet and IMS should be retained after network re-evaluation
2629         mDataNetworkControllerUT.obtainMessage(EVENT_REEVALUATE_EXISTING_DATA_NETWORKS)
2630                 .sendToTarget();
2631         processAllMessages();
2632 
2633         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_INTERNET);
2634         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
2635                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
2636 
2637         // Add MMS, whose priority > internet, internet should be town down, IMS left untouched
2638         mDataNetworkControllerUT.addNetworkRequest(
2639                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_MMS));
2640         setSuccessfulSetupDataResponse(mMockedDataServiceManagers
2641                 .get(AccessNetworkConstants.TRANSPORT_TYPE_WWAN), 3);
2642         processAllMessages();
2643 
2644         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_MMS);
2645         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
2646                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
2647 
2648         // Both internet and IMS should be retained after network re-evaluation
2649         mDataNetworkControllerUT.obtainMessage(EVENT_REEVALUATE_EXISTING_DATA_NETWORKS)
2650                 .sendToTarget();
2651         processAllMessages();
2652 
2653         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_MMS);
2654         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
2655                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
2656 
2657         // Temporarily remove IMS
2658         mDataNetworkControllerUT.removeNetworkRequest(ims);
2659         processAllMessages();
2660         List<DataNetwork> dataNetworks = getDataNetworks();
2661         dataNetworks.get(0).tearDown(DataNetwork.TEAR_DOWN_REASON_CONNECTIVITY_SERVICE_UNWANTED);
2662         processAllMessages();
2663 
2664         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_IMS);
2665 
2666         // Add IMS, should be compatible with the existing internet
2667         setSuccessfulSetupDataResponse(mMockedDataServiceManagers
2668                 .get(AccessNetworkConstants.TRANSPORT_TYPE_WWAN), 4);
2669         mDataNetworkControllerUT.addNetworkRequest(
2670                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS));
2671         processAllMessages();
2672         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_INTERNET);
2673         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
2674                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
2675     }
2676 
2677     @Test
testLinkStatusChanged()2678     public void testLinkStatusChanged() throws Exception {
2679         testSetupDataNetwork();
2680         verify(mMockedDataNetworkControllerCallback).onPhysicalLinkStatusChanged(
2681                 eq(DataCallResponse.LINK_STATUS_ACTIVE));
2682 
2683         DataNetwork dataNetwork = getDataNetworks().get(0);
2684 
2685         DataCallResponse response = createDataCallResponse(1, DataCallResponse.LINK_STATUS_DORMANT);
2686         dataNetwork.obtainMessage(8 /*EVENT_DATA_STATE_CHANGED */,
2687                 new AsyncResult(AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
2688                         List.of(response), null)).sendToTarget();
2689 
2690         processAllMessages();
2691         verify(mMockedDataNetworkControllerCallback).onPhysicalLinkStatusChanged(
2692                 eq(DataCallResponse.LINK_STATUS_DORMANT));
2693         assertThat(mDataNetworkControllerUT.getDataActivity()).isEqualTo(
2694                 TelephonyManager.DATA_ACTIVITY_DORMANT);
2695     }
2696 
2697     @Test
testHandoverDataNetwork()2698     public void testHandoverDataNetwork() throws Exception {
2699         testSetupImsDataNetwork();
2700 
2701         DataNetwork dataNetwork = getDataNetworks().get(0);
2702         // Before handover the data profile is the cellular IMS data profile
2703         verifyConnectedNetworkHasDataProfile(mImsCellularDataProfile);
2704 
2705         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
2706                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
2707 
2708         // Verify that IWLAN handover succeeded.
2709         assertThat(dataNetwork.getTransport()).isEqualTo(
2710                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
2711 
2712         // After handover the data profile is the IWLAN IMS data profile
2713         verifyConnectedNetworkHasDataProfile(mImsIwlanDataProfile);
2714     }
2715 
2716     @Test
testHandoverDataNetworkBackToBackPreferenceChanged()2717     public void testHandoverDataNetworkBackToBackPreferenceChanged() throws Exception {
2718         testSetupImsDataNetwork();
2719 
2720         Mockito.reset(mMockedWlanDataServiceManager);
2721         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
2722                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
2723 
2724         // Capture the message for setup data call response. We want to delay it.
2725         ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
2726         verify(mMockedWlanDataServiceManager).setupDataCall(anyInt(), any(DataProfile.class),
2727                 anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(), any(), any(), anyBoolean(),
2728                 messageCaptor.capture());
2729 
2730         // Before setup data call response, change the preference back to cellular.
2731         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
2732                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
2733 
2734         // Before setup data call response, change the preference back to IWLAN.
2735         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
2736                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
2737 
2738         // Finally handover is completed.
2739         Message msg = messageCaptor.getValue();
2740         DataCallResponse response = new DataCallResponse.Builder()
2741                 .setCause(DataFailCause.NONE)
2742                 .build();
2743         msg.getData().putParcelable("data_call_response", response);
2744         msg.arg1 = DataServiceCallback.RESULT_SUCCESS;
2745         msg.sendToTarget();
2746         processAllMessages();
2747 
2748         // Make sure handover request is only sent once.
2749         verify(mMockedWlanDataServiceManager, times(1)).setupDataCall(anyInt(),
2750                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
2751                 any(), any(), anyBoolean(), messageCaptor.capture());
2752     }
2753 
2754     @Test
testHandoverDataNetworkBackToBackPreferenceChangedHandoverFail()2755     public void testHandoverDataNetworkBackToBackPreferenceChangedHandoverFail() throws Exception {
2756         testSetupImsDataNetwork();
2757         DataNetwork dataNetwork = getDataNetworks().get(0);
2758 
2759         Mockito.reset(mMockedWlanDataServiceManager);
2760         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
2761                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
2762 
2763         // Capture the message for setup data call response. We want to delay it.
2764         ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
2765         verify(mMockedWlanDataServiceManager).setupDataCall(anyInt(), any(DataProfile.class),
2766                 anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(), any(), any(), anyBoolean(),
2767                 messageCaptor.capture());
2768 
2769         // Before setup data call response, change the preference back to cellular.
2770         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
2771                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
2772 
2773         // Finally handover is completed.
2774         Message msg = messageCaptor.getValue();
2775         DataCallResponse response = new DataCallResponse.Builder()
2776                 .setCause(DataFailCause.ERROR_UNSPECIFIED)
2777                 .setRetryDurationMillis(123)
2778                 .setHandoverFailureMode(
2779                         DataCallResponse.HANDOVER_FAILURE_MODE_NO_FALLBACK_RETRY_SETUP_NORMAL)
2780                 .build();
2781         msg.getData().putParcelable("data_call_response", response);
2782         msg.arg1 = DataServiceCallback.RESULT_ERROR_UNSUPPORTED;
2783         msg.sendToTarget();
2784         processAllMessages();
2785 
2786         // Make sure handover request is only sent once.
2787         verify(mMockedWlanDataServiceManager, times(1)).setupDataCall(anyInt(),
2788                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
2789                 any(), any(), anyBoolean(), messageCaptor.capture());
2790         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS);
2791         assertSame(dataNetwork, getDataNetworks().get(0));
2792     }
2793 
2794     @Test
testHandoverDataNetworkNotAllowedByPolicy()2795     public void testHandoverDataNetworkNotAllowedByPolicy() throws Exception {
2796         mCarrierConfig.putStringArray(CarrierConfigManager.KEY_IWLAN_HANDOVER_POLICY_STRING_ARRAY,
2797                 new String[]{"source=EUTRAN, target=IWLAN, type=disallowed, capabilities=MMS|IMS",
2798                         "source=IWLAN, target=EUTRAN, type=disallowed, capabilities=MMS"});
2799         // Force data config manager to reload the carrier config.
2800         carrierConfigChanged();
2801         processAllMessages();
2802 
2803         testSetupImsDataNetwork();
2804 
2805         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
2806                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
2807         // After this, IMS data network should be disconnected, and DNC should attempt to
2808         // establish a new one on IWLAN
2809 
2810         // Verify all data disconnected.
2811         verify(mMockedDataNetworkControllerCallback).onAnyDataNetworkExistingChanged(eq(false));
2812         verify(mMockedDataNetworkControllerCallback).onPhysicalLinkStatusChanged(
2813                 eq(DataCallResponse.LINK_STATUS_INACTIVE));
2814 
2815         // A new data network should be connected on IWLAN
2816         List<DataNetwork> dataNetworkList = getDataNetworks();
2817         assertThat(dataNetworkList).hasSize(1);
2818         assertThat(dataNetworkList.get(0).isConnected()).isTrue();
2819         assertThat(dataNetworkList.get(0).getNetworkCapabilities().hasCapability(
2820                 NetworkCapabilities.NET_CAPABILITY_IMS)).isTrue();
2821         assertThat(dataNetworkList.get(0).getTransport())
2822                 .isEqualTo(AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
2823 
2824         // test IWLAN -> EUTRAN no need to tear down because the disallowed rule only applies to MMS
2825         doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WWAN).when(mAccessNetworksManager)
2826                 .getPreferredTransportByNetworkCapability(NetworkCapabilities.NET_CAPABILITY_IMS);
2827         mDataNetworkControllerUT.obtainMessage(21/*EVENT_PREFERRED_TRANSPORT_CHANGED*/,
2828                 NetworkCapabilities.NET_CAPABILITY_IMS, 0).sendToTarget();
2829         Mockito.clearInvocations(mMockedWwanDataServiceManager);
2830         processAllMessages();
2831         // Verify that IWWAN handover succeeded.
2832         assertThat(getDataNetworks().get(0).getTransport()).isEqualTo(
2833                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
2834         verify(mMockedWwanDataServiceManager, times(1)).setupDataCall(
2835                 anyInt(), any(), anyBoolean(), anyBoolean(),
2836                 eq(DataService.REQUEST_REASON_HANDOVER), any(), anyInt(), any(), any(), eq(true),
2837                 any());
2838     }
2839 
2840     @Test
testHandoverDataNetworkNotAllowedByPolicyDelayDueToVoiceCall()2841     public void testHandoverDataNetworkNotAllowedByPolicyDelayDueToVoiceCall() throws Exception {
2842         doReturn(true).when(mFeatureFlags).relaxHoTeardown();
2843         // Config delay IMS tear down enabled
2844         mCarrierConfig.putBoolean(CarrierConfigManager.KEY_DELAY_IMS_TEAR_DOWN_UNTIL_CALL_END_BOOL,
2845                 true);
2846         mCarrierConfig.putStringArray(CarrierConfigManager.KEY_IWLAN_HANDOVER_POLICY_STRING_ARRAY,
2847                 new String[]{"source=EUTRAN, target=IWLAN, type=disallowed, capabilities=MMS|IMS"});
2848         carrierConfigChanged();
2849 
2850         testSetupImsDataNetwork();
2851 
2852         // Ringing an active call, should delay handover tear down
2853         doReturn(PhoneConstants.State.RINGING).when(mCT).getState();
2854         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
2855                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
2856 
2857         // Verify network is still connected due to active voice call
2858         verify(mMockedWwanDataServiceManager, never()).deactivateDataCall(anyInt(),
2859                 eq(DataService.REQUEST_REASON_NORMAL), any(Message.class));
2860 
2861         // Verify tear down after call ends
2862         doReturn(PhoneConstants.State.IDLE).when(mCT).getState();
2863         mDataNetworkControllerUT.obtainMessage(EVENT_VOICE_CALL_ENDED).sendToTarget();
2864         processAllFutureMessages();
2865 
2866         verify(mMockedWwanDataServiceManager).deactivateDataCall(anyInt(),
2867                 eq(DataService.REQUEST_REASON_NORMAL), any(Message.class));
2868     }
2869 
2870     @Test
testHandoverDataNetworkNotAllowedByRoamingPolicy()2871     public void testHandoverDataNetworkNotAllowedByRoamingPolicy() throws Exception {
2872         mCarrierConfig.putStringArray(CarrierConfigManager.KEY_IWLAN_HANDOVER_POLICY_STRING_ARRAY,
2873                 new String[]{"source=EUTRAN|NGRAN|IWLAN, target=EUTRAN|NGRAN|IWLAN, roaming=true, "
2874                         + "type=disallowed, capabilities=IMS"});
2875         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
2876                 NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
2877         // Force data config manager to reload the carrier config.
2878         mDataNetworkControllerUT.getDataConfigManager().obtainMessage(
2879                 1/*EVENT_CARRIER_CONFIG_CHANGED*/).sendToTarget();
2880         doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WLAN).when(mAccessNetworksManager)
2881                 .getPreferredTransportByNetworkCapability(NetworkCapabilities.NET_CAPABILITY_IMS);
2882 
2883         processAllMessages();
2884 
2885         // Bring up IMS PDN on IWLAN
2886         mDataNetworkControllerUT.addNetworkRequest(
2887                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS));
2888         processAllMessages();
2889         verifyConnectedNetworkHasDataProfile(mImsIwlanDataProfile);
2890 
2891         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
2892                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
2893 
2894         // Verify IMS PDN is connected.
2895         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
2896                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
2897 
2898         // After this, IMS data network should be disconnected, and DNC should attempt to
2899         // establish a new one on cellular
2900         processAllMessages();
2901 
2902         // Verify all data disconnected.
2903         verify(mMockedDataNetworkControllerCallback).onAnyDataNetworkExistingChanged(eq(false));
2904         verify(mMockedDataNetworkControllerCallback).onPhysicalLinkStatusChanged(
2905                 eq(DataCallResponse.LINK_STATUS_INACTIVE));
2906 
2907         // Should setup a new one instead of handover.
2908         verify(mMockedWwanDataServiceManager).setupDataCall(anyInt(), any(DataProfile.class),
2909                 anyBoolean(), anyBoolean(), eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(),
2910                 any(), any(), anyBoolean(), any(Message.class));
2911 
2912 
2913         // A new data network should be connected on IWLAN
2914         List<DataNetwork> dataNetworkList = getDataNetworks();
2915         assertThat(dataNetworkList).hasSize(1);
2916         assertThat(dataNetworkList.get(0).isConnected()).isTrue();
2917         assertThat(dataNetworkList.get(0).getNetworkCapabilities().hasCapability(
2918                 NetworkCapabilities.NET_CAPABILITY_IMS)).isTrue();
2919         assertThat(dataNetworkList.get(0).getTransport())
2920                 .isEqualTo(AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
2921     }
2922 
2923     @Test
testHandoverDataNetworkRetry()2924     public void testHandoverDataNetworkRetry() throws Exception {
2925         testSetupImsDataNetwork();
2926 
2927         setFailedSetupDataResponse(mMockedWlanDataServiceManager,
2928                 DataFailCause.HANDOVER_FAILED, -1, true);
2929         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
2930                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
2931 
2932         DataNetwork dataNetwork = getDataNetworks().get(0);
2933         // Verify that data network is still on cellular
2934         assertThat(dataNetwork.getTransport()).isEqualTo(
2935                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
2936 
2937         // Set target transport OOS
2938         serviceStateChanged(TelephonyManager.NETWORK_TYPE_UNKNOWN,
2939                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, /* data */
2940                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, /* voice */
2941                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING, /* iwlan */
2942                 null);
2943         setSuccessfulSetupDataResponse(mMockedWlanDataServiceManager, 1);
2944 
2945         processAllFutureMessages();
2946         // Verify that data network is still on cellular
2947         assertThat(dataNetwork.getTransport()).isEqualTo(
2948                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
2949 
2950         // Set target transport back to service
2951         serviceStateChanged(TelephonyManager.NETWORK_TYPE_UNKNOWN,
2952                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, /* data */
2953                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, /* voice */
2954                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, /* iwlan */
2955                 null);
2956         processAllFutureMessages();
2957 
2958         dataNetwork = getDataNetworks().get(0);
2959         // Verify that data network is handovered to IWLAN
2960         assertThat(dataNetwork.getTransport()).isEqualTo(
2961                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
2962     }
2963 
2964     @Test
testHandoverDataNetworkDuplicateRetry()2965     public void testHandoverDataNetworkDuplicateRetry() throws Exception {
2966         testSetupImsDataNetwork();
2967         DataNetwork dataNetwork = getDataNetworks().get(0);
2968         doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WLAN)
2969                 .when(mAccessNetworksManager).getPreferredTransportByNetworkCapability(anyInt());
2970 
2971         DataRetryManager.DataHandoverRetryEntry retry1 =
2972                 new DataRetryManager.DataHandoverRetryEntry.Builder<>()
2973                         .setDataNetwork(dataNetwork)
2974                         .build();
2975         DataRetryManager.DataHandoverRetryEntry retry2 =
2976                 new DataRetryManager.DataHandoverRetryEntry.Builder<>()
2977                         .setDataNetwork(dataNetwork)
2978                         .build();
2979         final Message msg1 = new Message();
2980         msg1.what = 4 /*EVENT_DATA_HANDOVER_RETRY*/;
2981         msg1.obj = retry1;
2982 
2983         final Message msg2 = new Message();
2984         msg2.what = 4 /*EVENT_DATA_HANDOVER_RETRY*/;
2985         msg2.obj = retry2;
2986 
2987         Field field = DataRetryManager.class.getDeclaredField("mDataRetryEntries");
2988         field.setAccessible(true);
2989         List<DataRetryManager.DataRetryEntry> dataRetryEntries =
2990                 (List<DataRetryManager.DataRetryEntry>)
2991                         field.get(mDataNetworkControllerUT.getDataRetryManager());
2992         dataRetryEntries.add(retry1);
2993         dataRetryEntries.add(retry2);
2994 
2995         mDataNetworkControllerUT.getDataRetryManager().sendMessageDelayed(msg1, 0);
2996         mDataNetworkControllerUT.getDataRetryManager().sendMessageDelayed(msg2, 0);
2997 
2998         processAllFutureMessages();
2999 
3000         setSuccessfulSetupDataResponse(mMockedWlanDataServiceManager, 1);
3001         processAllMessages();
3002 
3003         dataNetwork = getDataNetworks().get(0);
3004         assertThat(dataNetwork.getTransport()).isEqualTo(
3005                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
3006         verify(mMockedWlanDataServiceManager).setupDataCall(anyInt(), any(DataProfile.class),
3007                 anyBoolean(), anyBoolean(), eq(DataService.REQUEST_REASON_HANDOVER), any(),
3008                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
3009         assertThat(mDataNetworkControllerUT.getDataRetryManager()
3010                 .isAnyHandoverRetryScheduled(dataNetwork)).isFalse();
3011     }
3012 
3013     @Test
testHandoverDataNetworkRetryReachedMaximum()3014     public void testHandoverDataNetworkRetryReachedMaximum() throws Exception {
3015         testSetupImsDataNetwork();
3016 
3017         // 1. Normal case
3018         setFailedSetupDataResponse(mMockedWlanDataServiceManager,
3019                 DataFailCause.HANDOVER_FAILED, -1, true);
3020         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
3021                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
3022         processAllFutureMessages();
3023 
3024         // Should retried 5 times, which is the maximum based on the retry config rules.
3025         verify(mMockedWlanDataServiceManager, times(6)).setupDataCall(anyInt(),
3026                 any(DataProfile.class), anyBoolean(), anyBoolean(),
3027                 eq(DataService.REQUEST_REASON_HANDOVER), any(), anyInt(), any(), any(),
3028                 anyBoolean(), any(Message.class));
3029 
3030         DataNetwork dataNetwork = getDataNetworks().get(0);
3031         // Verify that data network is finally setup on IWLAN.
3032         assertThat(dataNetwork.getTransport()).isEqualTo(
3033                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
3034 
3035         verify(mMockedWlanDataServiceManager).setupDataCall(anyInt(), any(DataProfile.class),
3036                 anyBoolean(), anyBoolean(), eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(),
3037                 any(), any(), anyBoolean(), any(Message.class));
3038 
3039         // 2. Active VoPS call, should delay tear down
3040         doReturn(PhoneConstants.State.RINGING).when(mCT).getState();
3041         mCarrierConfig.putBoolean(CarrierConfigManager.KEY_DELAY_IMS_TEAR_DOWN_UNTIL_CALL_END_BOOL,
3042                 true);
3043         carrierConfigChanged();
3044 
3045         setFailedSetupDataResponse(mMockedWwanDataServiceManager,
3046                 DataFailCause.HANDOVER_FAILED, -1, true);
3047         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
3048                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
3049         processAllFutureMessages();
3050 
3051         // Verify the network wasn't torn down
3052         verify(mMockedWlanDataServiceManager, never()).deactivateDataCall(anyInt(),
3053                 eq(DataService.REQUEST_REASON_NORMAL), any(Message.class));
3054 
3055         // Verify tear down after call ends
3056         doReturn(PhoneConstants.State.IDLE).when(mCT).getState();
3057         mDataNetworkControllerUT.obtainMessage(EVENT_VOICE_CALL_ENDED).sendToTarget();
3058         processAllFutureMessages();
3059 
3060         verify(mMockedWlanDataServiceManager).deactivateDataCall(anyInt(),
3061                 eq(DataService.REQUEST_REASON_NORMAL), any(Message.class));
3062     }
3063 
3064     @Test
testHandoverDataNetworkRetryReachedMaximumNetworkRequestRemoved()3065     public void testHandoverDataNetworkRetryReachedMaximumNetworkRequestRemoved() throws Exception {
3066         TelephonyNetworkRequest networkRequest = createNetworkRequest(
3067                 NetworkCapabilities.NET_CAPABILITY_IMS);
3068         mDataNetworkControllerUT.addNetworkRequest(networkRequest);
3069         processAllMessages();
3070 
3071         setFailedSetupDataResponse(mMockedWlanDataServiceManager,
3072                 DataFailCause.HANDOVER_FAILED, -1, true);
3073         mDataNetworkControllerUT.removeNetworkRequest(networkRequest);
3074         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
3075                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
3076         processAllMessages();
3077 
3078         DataNetwork dataNetwork = getDataNetworks().get(0);
3079         // Verify that data network should remain on cellular.
3080         assertThat(dataNetwork.getTransport()).isEqualTo(
3081                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
3082 
3083         // There shouldn't be any attempt to retry handover on IWLAN.
3084         verify(mMockedWlanDataServiceManager, times(1)).setupDataCall(anyInt(),
3085                 any(DataProfile.class), anyBoolean(), anyBoolean(),
3086                 eq(DataService.REQUEST_REASON_HANDOVER), any(), anyInt(), any(), any(),
3087                 anyBoolean(), any(Message.class));
3088 
3089         // There shouldn't be any attempt to bring up a new one on IWLAN as well.
3090         verify(mMockedWlanDataServiceManager, never()).setupDataCall(anyInt(),
3091                 any(DataProfile.class), anyBoolean(), anyBoolean(),
3092                 eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), any(),
3093                 anyBoolean(), any(Message.class));
3094     }
3095 
3096     @Test
testHandoverDataNetworkRetryReachedMaximumDelayImsTearDown()3097     public void testHandoverDataNetworkRetryReachedMaximumDelayImsTearDown() throws Exception {
3098         // Voice call is ongoing
3099         doReturn(PhoneConstants.State.OFFHOOK).when(mCT).getState();
3100         mCarrierConfig.putBoolean(CarrierConfigManager.KEY_DELAY_IMS_TEAR_DOWN_UNTIL_CALL_END_BOOL,
3101                 true);
3102         carrierConfigChanged();
3103 
3104         testSetupImsDataNetwork();
3105 
3106         setFailedSetupDataResponse(mMockedWlanDataServiceManager,
3107                 DataFailCause.HANDOVER_FAILED, -1, true);
3108         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
3109                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
3110         processAllFutureMessages();
3111 
3112         // Should retried 5 times, which is the maximum based on the retry config rules.
3113         verify(mMockedWlanDataServiceManager, times(6)).setupDataCall(anyInt(),
3114                 any(DataProfile.class), anyBoolean(), anyBoolean(),
3115                 eq(DataService.REQUEST_REASON_HANDOVER), any(), anyInt(), any(), any(),
3116                 anyBoolean(), any(Message.class));
3117 
3118         DataNetwork dataNetwork = getDataNetworks().get(0);
3119         // Verify that data network is still on WWAN because voice call is still ongoing.
3120         assertThat(dataNetwork.getTransport()).isEqualTo(
3121                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
3122 
3123     }
3124 
3125     // Test the device enters from 4G to 3G, and QNS switches the pref just before that happens.
3126     // Make sure we don't tear down the network and let it handover to IWLAN successfully.
3127     @Test
testHandoverDataNetworkWhileSwitchTo3G()3128     public void testHandoverDataNetworkWhileSwitchTo3G() throws Exception {
3129         testSetupImsDataNetwork();
3130 
3131         // Before handover the data profile is the cellular IMS data profile
3132         verifyConnectedNetworkHasDataProfile(mImsCellularDataProfile);
3133 
3134         // Long delay handover
3135         setSuccessfulSetupDataResponse(mMockedWlanDataServiceManager, 1, 3000);
3136         doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WLAN).when(mAccessNetworksManager)
3137                 .getPreferredTransportByNetworkCapability(NetworkCapabilities.NET_CAPABILITY_IMS);
3138         mAccessNetworksManagerCallback.onPreferredTransportChanged(
3139                 NetworkCapabilities.NET_CAPABILITY_IMS, false);
3140         serviceStateChanged(TelephonyManager.NETWORK_TYPE_UMTS,
3141                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
3142         processAllMessages();
3143 
3144         // Move the time a little bit, handover still not responded.
3145         moveTimeForward(500);
3146         processAllMessages();
3147         DataNetwork dataNetwork = getDataNetworks().get(0);
3148         // Verify the network is still on cellular, waiting for handover, although already on 3G.
3149         assertThat(dataNetwork.getTransport()).isEqualTo(
3150                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
3151 
3152         // Now handover should complete.
3153         moveTimeForward(5000);
3154         processAllMessages();
3155 
3156         dataNetwork = getDataNetworks().get(0);
3157         // Verify that IWLAN handover succeeded.
3158         assertThat(dataNetwork.getTransport()).isEqualTo(
3159                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
3160 
3161         // After handover the data profile is the IWLAN IMS data profile
3162         verifyConnectedNetworkHasDataProfile(mImsIwlanDataProfile);
3163     }
3164 
3165     @Test
testHandoverDataNetworkFailedNullResponse()3166     public void testHandoverDataNetworkFailedNullResponse() throws Exception {
3167         testSetupImsDataNetwork();
3168         DataNetwork dataNetwork = getDataNetworks().get(0);
3169 
3170         // Set failed null response
3171         doAnswer(invocation -> {
3172             final Message msg = (Message) invocation.getArguments()[10];
3173             msg.getData().putParcelable("data_call_response", null);
3174             msg.arg1 = DataServiceCallback.RESULT_ERROR_TEMPORARILY_UNAVAILABLE;
3175             msg.getTarget().sendMessageDelayed(msg, 0);
3176             return null;
3177         }).when(mMockedWlanDataServiceManager).setupDataCall(anyInt(), any(DataProfile.class),
3178                 anyBoolean(), anyBoolean(), eq(DataService.REQUEST_REASON_HANDOVER), any(),
3179                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
3180 
3181         // Attempt handover
3182         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
3183                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
3184         processAllMessages();
3185 
3186         // Verify that data network is still on cellular and data network was not torn down
3187         assertThat(dataNetwork.getTransport()).isEqualTo(
3188                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
3189         assertThat(dataNetwork.isConnected()).isTrue();
3190 
3191         // Process all handover retries and failures
3192         processAllFutureMessages();
3193 
3194         // Verify that original data network was torn down and new connection set up on cellular
3195         assertThat(dataNetwork.getTransport()).isEqualTo(
3196                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
3197         assertThat(dataNetwork.isConnected()).isFalse();
3198         dataNetwork = getDataNetworks().get(0);
3199         assertThat(dataNetwork.getTransport()).isEqualTo(
3200                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
3201         assertThat(dataNetwork.isConnected()).isTrue();
3202     }
3203 
3204     @Test
testSetupDataNetworkRetrySuggestedByNetwork()3205     public void testSetupDataNetworkRetrySuggestedByNetwork() {
3206         setFailedSetupDataResponse(mMockedWwanDataServiceManager, DataFailCause.CONGESTION,
3207                 DataCallResponse.RETRY_DURATION_UNDEFINED, false);
3208         mDataNetworkControllerUT.addNetworkRequest(
3209                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
3210         processAllFutureMessages();
3211 
3212         // The first 8 retries are short timers that scheduled by handler, future retries are
3213         // scheduled by intent and require more complex mock, so we only verify the first 8 here.
3214         verify(mMockedWwanDataServiceManager, times(9)).setupDataCall(anyInt(),
3215                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
3216                 any(), any(), anyBoolean(), any(Message.class));
3217     }
3218 
3219     @Test
testSetupDataNetworkRetryFailed()3220     public void testSetupDataNetworkRetryFailed() {
3221         mDataNetworkControllerUT.getDataRetryManager()
3222                 .registerCallback(mMockedDataRetryManagerCallback);
3223         setFailedSetupDataResponse(mMockedWwanDataServiceManager, DataFailCause.CONGESTION,
3224                 DataCallResponse.RETRY_DURATION_UNDEFINED, false);
3225         mDataNetworkControllerUT.addNetworkRequest(
3226                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
3227         processAllMessages();
3228 
3229         verify(mMockedWwanDataServiceManager, times(1)).setupDataCall(anyInt(),
3230                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
3231                 any(), any(), anyBoolean(), any(Message.class));
3232 
3233         // Process first retry
3234         moveTimeForward(2500);
3235         processAllMessages();
3236         verify(mMockedWwanDataServiceManager, times(2)).setupDataCall(anyInt(),
3237                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
3238                 any(), any(), anyBoolean(), any(Message.class));
3239         ArgumentCaptor<DataRetryManager.DataSetupRetryEntry> retryEntry =
3240                 ArgumentCaptor.forClass(DataRetryManager.DataSetupRetryEntry.class);
3241         verify(mMockedDataRetryManagerCallback, times(1))
3242                 .onDataNetworkSetupRetry(retryEntry.capture());
3243         assertThat(retryEntry.getValue().getState()).isEqualTo(
3244                 DataRetryManager.DataRetryEntry.RETRY_STATE_FAILED);
3245 
3246         // Cause data network setup failed due to RADIO_DISABLED_BY_CARRIER
3247         doReturn(false).when(mSST).getPowerStateFromCarrier();
3248 
3249         // Process second retry and ensure data network setup failed
3250         moveTimeForward(3000);
3251         processAllMessages();
3252         verify(mMockedWwanDataServiceManager, times(2)).setupDataCall(anyInt(),
3253                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
3254                 any(), any(), anyBoolean(), any(Message.class));
3255         verify(mMockedDataRetryManagerCallback, times(2))
3256                 .onDataNetworkSetupRetry(retryEntry.capture());
3257         assertThat(retryEntry.getValue().getState()).isEqualTo(
3258                 DataRetryManager.DataRetryEntry.RETRY_STATE_FAILED);
3259 
3260         // Data network setup allowed again
3261         doReturn(true).when(mSST).getPowerStateFromCarrier();
3262 
3263         // Should not retry again after retry failure
3264         processAllFutureMessages();
3265         verify(mMockedWwanDataServiceManager, times(2)).setupDataCall(anyInt(),
3266                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
3267                 any(), any(), anyBoolean(), any(Message.class));
3268     }
3269 
3270     @Test
testSetupDataNetworkRetryFailedNetworkRequestRemoved()3271     public void testSetupDataNetworkRetryFailedNetworkRequestRemoved() {
3272         mDataNetworkControllerUT.getDataRetryManager()
3273                 .registerCallback(mMockedDataRetryManagerCallback);
3274         setFailedSetupDataResponse(mMockedWwanDataServiceManager, DataFailCause.CONGESTION,
3275                 DataCallResponse.RETRY_DURATION_UNDEFINED, false);
3276         TelephonyNetworkRequest tnr = createNetworkRequest(
3277                 NetworkCapabilities.NET_CAPABILITY_INTERNET);
3278         mDataNetworkControllerUT.addNetworkRequest(tnr);
3279 
3280         processAllMessages();
3281 
3282         verify(mMockedWwanDataServiceManager, times(1)).setupDataCall(anyInt(),
3283                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
3284                 any(), any(), anyBoolean(), any(Message.class));
3285         Mockito.clearInvocations(mMockedWwanDataServiceManager);
3286 
3287         logd("Remove internet network request");
3288         mDataNetworkControllerUT.removeNetworkRequest(tnr);
3289 
3290         moveTimeForward(2500);
3291         processAllMessages();
3292 
3293         // There should be no retry since request has been removed.
3294         verify(mMockedWwanDataServiceManager, never()).setupDataCall(anyInt(),
3295                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
3296                 any(), any(), anyBoolean(), any(Message.class));
3297         Mockito.clearInvocations(mMockedWwanDataServiceManager);
3298 
3299         // Now send another IMS request
3300         tnr = createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS);
3301         mDataNetworkControllerUT.addNetworkRequest(tnr);
3302         processAllMessages();
3303 
3304         verify(mMockedWwanDataServiceManager, times(1)).setupDataCall(anyInt(),
3305                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
3306                 any(), any(), anyBoolean(), any(Message.class));
3307         Mockito.clearInvocations(mMockedWwanDataServiceManager);
3308 
3309         logd("Remove IMS network request");
3310         mDataNetworkControllerUT.removeNetworkRequest(tnr);
3311 
3312         // There should be no retry since request has been removed.
3313         verify(mMockedWwanDataServiceManager, never()).setupDataCall(anyInt(),
3314                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
3315                 any(), any(), anyBoolean(), any(Message.class));
3316     }
3317 
3318     @Test
testSetupDataNetworkRetryFailedNetworkRequestRemovedAndAdded()3319     public void testSetupDataNetworkRetryFailedNetworkRequestRemovedAndAdded() throws Exception {
3320         mDataNetworkControllerUT.getDataRetryManager()
3321                 .registerCallback(mMockedDataRetryManagerCallback);
3322         setFailedSetupDataResponse(mMockedWwanDataServiceManager, DataFailCause.CONGESTION,
3323                 10000, false);
3324 
3325         TelephonyNetworkRequest firstTnr = createNetworkRequest(
3326                 NetworkCapabilities.NET_CAPABILITY_IMS);
3327         TelephonyNetworkRequest secondTnr = createNetworkRequest(
3328                 NetworkCapabilities.NET_CAPABILITY_IMS);
3329         TelephonyNetworkRequest thirdTnr = new TelephonyNetworkRequest(
3330                 new NetworkRequest((new NetworkCapabilities.Builder())
3331                         .addCapability(NetworkCapabilities.NET_CAPABILITY_IMS)
3332                         .addTransportType(NetworkCapabilities.TRANSPORT_SATELLITE)
3333                         .build(),
3334                         ConnectivityManager.TYPE_MOBILE, ++mNetworkRequestId,
3335                         NetworkRequest.Type.REQUEST), mPhone, mFeatureFlags);
3336 
3337         mDataNetworkControllerUT.addNetworkRequest(firstTnr);
3338         processAllMessages();
3339 
3340         mDataNetworkControllerUT.removeNetworkRequest(firstTnr);
3341         mDataNetworkControllerUT.addNetworkRequest(secondTnr);
3342         mDataNetworkControllerUT.addNetworkRequest(thirdTnr);
3343         processAllFutureMessages();
3344 
3345         verify(mMockedWwanDataServiceManager, times(1)).setupDataCall(anyInt(),
3346                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
3347                 any(), any(), anyBoolean(), any(Message.class));
3348 
3349         ArgumentCaptor<DataRetryManager.DataSetupRetryEntry> retryEntry =
3350                 ArgumentCaptor.forClass(DataRetryManager.DataSetupRetryEntry.class);
3351         verify(mMockedDataRetryManagerCallback, times(1))
3352                 .onDataNetworkSetupRetry(retryEntry.capture());
3353         assertThat(retryEntry.getValue().getState()).isEqualTo(
3354                 DataRetryManager.DataRetryEntry.RETRY_STATE_FAILED);
3355         assertThat(retryEntry.getValue().networkRequestList.size()).isEqualTo(1);
3356         assertThat(retryEntry.getValue().networkRequestList.get(0)).isEqualTo(firstTnr);
3357 
3358         DataRetryManager.DataSetupRetryEntry dataSetupRetryEntry = retryEntry.getValue();
3359         logd("DataSetupRetryEntry:" + dataSetupRetryEntry);
3360 
3361         processAllMessages();
3362         processAllFutureMessages();
3363 
3364         setSuccessfulSetupDataResponse(mMockedWwanDataServiceManager, 1);
3365         logd("Sending TAC_CHANGED event");
3366         mDataNetworkControllerUT.obtainMessage(25/*EVENT_TAC_CHANGED*/).sendToTarget();
3367         mDataNetworkControllerUT.getDataRetryManager().obtainMessage(10/*EVENT_TAC_CHANGED*/)
3368                 .sendToTarget();
3369         processAllFutureMessages();
3370 
3371         // TAC changes should clear the already-scheduled retry and throttling.
3372         assertThat(mDataNetworkControllerUT.getDataRetryManager().isDataProfileThrottled(
3373                 mImsCellularDataProfile, AccessNetworkConstants.TRANSPORT_TYPE_WWAN)).isFalse();
3374 
3375         // But DNC should re-evaluate unsatisfied request and setup IMS again.
3376         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
3377                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
3378 
3379         verify(mMockedWwanDataServiceManager, times(2)).setupDataCall(anyInt(),
3380                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
3381                 any(), any(), anyBoolean(), any(Message.class));
3382     }
3383 
3384     @Test
testSetupDataNetworkPermanentFailure()3385     public void testSetupDataNetworkPermanentFailure() {
3386         setFailedSetupDataResponse(mMockedWwanDataServiceManager, DataFailCause.PROTOCOL_ERRORS,
3387                 DataCallResponse.RETRY_DURATION_UNDEFINED, false);
3388         mDataNetworkControllerUT.addNetworkRequest(
3389                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
3390         processAllFutureMessages();
3391 
3392         // There should be only one attempt, and no retry should happen because it's a permanent
3393         // failure.
3394         verify(mMockedWwanDataServiceManager, times(1)).setupDataCall(anyInt(),
3395                 eq(mGeneralPurposeDataProfile), anyBoolean(), anyBoolean(), anyInt(), any(),
3396                 anyInt(), any(), any(), anyBoolean(), any(Message.class));
3397 
3398         Mockito.clearInvocations(mMockedWwanDataServiceManager);
3399         mDataNetworkControllerUT.addNetworkRequest(
3400                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
3401         processAllFutureMessages();
3402 
3403         // Even receiving a new network request, setup data call should not be sent.
3404         verify(mMockedWwanDataServiceManager, never()).setupDataCall(anyInt(),
3405                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
3406                 any(), any(), anyBoolean(), any(Message.class));
3407         // APN should be marked as permanent failure.
3408         assertThat(mGeneralPurposeDataProfile.getApnSetting().getPermanentFailed()).isTrue();
3409     }
3410 
3411     @Test
testSetupDataNetworkConditionChangesAfterPermanentFailure()3412     public void testSetupDataNetworkConditionChangesAfterPermanentFailure() throws Exception {
3413         testSetupDataNetworkPermanentFailure();
3414 
3415         setSuccessfulSetupDataResponse(mMockedDataServiceManagers
3416                 .get(AccessNetworkConstants.TRANSPORT_TYPE_WWAN), 1);
3417 
3418         // From LTE to NR
3419         serviceStateChanged(TelephonyManager.NETWORK_TYPE_NR,
3420                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
3421 
3422         // condition change should trigger setup data, even though previously the APN has been
3423         // marked as permanent failure.
3424         verifyInternetConnected();
3425     }
3426 
3427     @Test
testSetupDataNetworkNetworkSuggestedNeverRetry()3428     public void testSetupDataNetworkNetworkSuggestedNeverRetry() {
3429         setFailedSetupDataResponse(mMockedWwanDataServiceManager, DataFailCause.PROTOCOL_ERRORS,
3430                 Long.MAX_VALUE, false);
3431         mDataNetworkControllerUT.addNetworkRequest(
3432                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
3433         processAllFutureMessages();
3434 
3435         // There should be only one attempt, and no retry should happen because it's a permanent
3436         // failure.
3437         verify(mMockedWwanDataServiceManager, times(1)).setupDataCall(anyInt(),
3438                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
3439                 any(), any(), anyBoolean(), any(Message.class));
3440     }
3441 
3442     @Test
testSetupDataNetworkNetworkSuggestedRetryTimerDataThrottled()3443     public void testSetupDataNetworkNetworkSuggestedRetryTimerDataThrottled() {
3444         mDataNetworkControllerUT.getDataRetryManager()
3445                 .registerCallback(mMockedDataRetryManagerCallback);
3446 
3447         setFailedSetupDataResponse(mMockedWwanDataServiceManager, DataFailCause.PROTOCOL_ERRORS,
3448                 10000, false);
3449         mDataNetworkControllerUT.addNetworkRequest(
3450                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS));
3451         processAllMessages();
3452 
3453         mDataNetworkControllerUT.addNetworkRequest(
3454                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS));
3455         processAllMessages();
3456 
3457         // There should be only one attempt, and no retry should happen because the second one
3458         // was throttled.
3459         verify(mMockedWwanDataServiceManager, times(1)).setupDataCall(anyInt(),
3460                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
3461                 any(), any(), anyBoolean(), any(Message.class));
3462 
3463         ArgumentCaptor<List<ThrottleStatus>> throttleStatusCaptor =
3464                 ArgumentCaptor.forClass(List.class);
3465         verify(mMockedDataRetryManagerCallback)
3466                 .onThrottleStatusChanged(throttleStatusCaptor.capture());
3467         assertThat(throttleStatusCaptor.getValue()).hasSize(1);
3468         ThrottleStatus throttleStatus = throttleStatusCaptor.getValue().get(0);
3469         assertThat(throttleStatus.getApnType()).isEqualTo(ApnSetting.TYPE_IMS);
3470         assertThat(throttleStatus.getRetryType())
3471                 .isEqualTo(ThrottleStatus.RETRY_TYPE_NEW_CONNECTION);
3472         assertThat(throttleStatus.getTransportType())
3473                 .isEqualTo(AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
3474     }
3475 
3476     @Test
testHandoverDataNetworkNetworkSuggestedRetryTimerDataThrottled()3477     public void testHandoverDataNetworkNetworkSuggestedRetryTimerDataThrottled() throws Exception {
3478         testSetupImsDataNetwork();
3479 
3480         DataNetwork network = getDataNetworks().get(0);
3481         setFailedSetupDataResponse(mMockedWlanDataServiceManager,
3482                 DataFailCause.HANDOVER_FAILED, 10000, true);
3483         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
3484                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
3485 
3486         // Verify retry scheduled on this network
3487         assertThat(mDataNetworkControllerUT.getDataRetryManager()
3488                 .isAnyHandoverRetryScheduled(network)).isTrue();
3489         // Verify the data profile is throttled on WLAN
3490         assertThat(mDataNetworkControllerUT.getDataRetryManager().isDataProfileThrottled(
3491                 network.getDataProfile(), AccessNetworkConstants.TRANSPORT_TYPE_WLAN)).isTrue();
3492 
3493         // Test even if network disconnected, the throttle status should remain
3494         network.tearDown(DataNetwork.TEAR_DOWN_REASON_CONNECTIVITY_SERVICE_UNWANTED);
3495         processAllFutureMessages();
3496 
3497         // Verify retry is cleared on this network
3498         assertThat(mDataNetworkControllerUT.getDataRetryManager()
3499                 .isAnyHandoverRetryScheduled(network)).isFalse();
3500     }
3501 
3502     @Test
testTacChangesClearThrottlingAndRetryHappens()3503     public void testTacChangesClearThrottlingAndRetryHappens() throws Exception {
3504         testSetupDataNetworkNetworkSuggestedRetryTimerDataThrottled();
3505         processAllFutureMessages();
3506 
3507         setSuccessfulSetupDataResponse(mMockedWwanDataServiceManager, 1);
3508         logd("Sending TAC_CHANGED event");
3509         mDataNetworkControllerUT.obtainMessage(25/*EVENT_TAC_CHANGED*/).sendToTarget();
3510         mDataNetworkControllerUT.getDataRetryManager().obtainMessage(10/*EVENT_TAC_CHANGED*/)
3511                 .sendToTarget();
3512         processAllFutureMessages();
3513 
3514         // TAC changes should clear the already-scheduled retry and throttling.
3515         assertThat(mDataNetworkControllerUT.getDataRetryManager().isDataProfileThrottled(
3516                 mImsCellularDataProfile, AccessNetworkConstants.TRANSPORT_TYPE_WWAN)).isFalse();
3517 
3518         // But DNC should re-evaluate unsatisfied request and setup IMS again.
3519         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
3520                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
3521     }
3522 
3523     @Test
testNrAdvancedByPco()3524     public void testNrAdvancedByPco() throws Exception {
3525         testSetupDataNetwork();
3526         verify(mMockedDataNetworkControllerCallback, never())
3527                 .onNrAdvancedCapableByPcoChanged(anyBoolean());
3528         mSimulatedCommands.triggerPcoData(1, "IPV6", 1234, new byte[]{1});
3529         processAllMessages();
3530         verify(mMockedDataNetworkControllerCallback).onNrAdvancedCapableByPcoChanged(eq(true));
3531 
3532         mSimulatedCommands.triggerPcoData(1, "IPV6", 1234, new byte[]{0});
3533         processAllMessages();
3534         verify(mMockedDataNetworkControllerCallback).onNrAdvancedCapableByPcoChanged(eq(false));
3535     }
3536 
3537     @Test
testNrAdvancedByEarlyPco()3538     public void testNrAdvancedByEarlyPco() {
3539         Mockito.reset(mMockedWwanDataServiceManager);
3540         mDataNetworkControllerUT.addNetworkRequest(
3541                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
3542         processAllMessages();
3543 
3544         // PCO data arrives before data network entering connected state.
3545         mSimulatedCommands.triggerPcoData(1, "IPV6", 1234, new byte[]{1});
3546         processAllMessages();
3547 
3548         ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
3549         verify(mMockedWwanDataServiceManager).setupDataCall(anyInt(), any(DataProfile.class),
3550                 anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(), any(), any(), anyBoolean(),
3551                 messageCaptor.capture());
3552 
3553         // Send setup data call complete message.
3554         Message msg = messageCaptor.getValue();
3555         msg.getData().putParcelable("data_call_response",
3556                 createDataCallResponse(1, DataCallResponse.LINK_STATUS_ACTIVE));
3557         msg.arg1 = DataServiceCallback.RESULT_SUCCESS;
3558         msg.sendToTarget();
3559         processAllMessages();
3560 
3561         verify(mMockedDataNetworkControllerCallback).onNrAdvancedCapableByPcoChanged(eq(true));
3562     }
3563 
3564     @Test
testNrAdvancedByPcoMultipleNetworks()3565     public void testNrAdvancedByPcoMultipleNetworks() throws Exception {
3566         testSetupDataNetwork();
3567         setSuccessfulSetupDataResponse(mMockedDataServiceManagers
3568                 .get(AccessNetworkConstants.TRANSPORT_TYPE_WWAN), 2);
3569         testSetupImsDataNetwork();
3570 
3571         verify(mMockedDataNetworkControllerCallback, never())
3572                 .onNrAdvancedCapableByPcoChanged(anyBoolean());
3573         mSimulatedCommands.triggerPcoData(2, "IPV6", 1234, new byte[]{1});
3574         processAllMessages();
3575         verify(mMockedDataNetworkControllerCallback).onNrAdvancedCapableByPcoChanged(eq(true));
3576     }
3577 
3578     @Test
testNrAdvancedByEarlyUnrelatedPco()3579     public void testNrAdvancedByEarlyUnrelatedPco() {
3580         Mockito.reset(mMockedWwanDataServiceManager);
3581         mDataNetworkControllerUT.addNetworkRequest(
3582                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
3583         processAllMessages();
3584 
3585         // Unrelated PCO data arrives before data network entering connected state.
3586         mSimulatedCommands.triggerPcoData(2, "IPV6", 1234, new byte[]{1});
3587         processAllMessages();
3588 
3589         ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
3590         verify(mMockedWwanDataServiceManager).setupDataCall(anyInt(), any(DataProfile.class),
3591                 anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(), any(), any(), anyBoolean(),
3592                 messageCaptor.capture());
3593 
3594         // Send setup data call complete message.
3595         Message msg = messageCaptor.getValue();
3596         msg.getData().putParcelable("data_call_response",
3597                 createDataCallResponse(1, DataCallResponse.LINK_STATUS_ACTIVE));
3598         msg.arg1 = DataServiceCallback.RESULT_SUCCESS;
3599         msg.sendToTarget();
3600         processAllMessages();
3601 
3602         verify(mMockedDataNetworkControllerCallback, never()).onNrAdvancedCapableByPcoChanged(
3603                 anyBoolean());
3604     }
3605 
3606 
3607     @Test
testSetupDataNetworkVcnManaged()3608     public void testSetupDataNetworkVcnManaged() throws Exception {
3609         // VCN managed
3610         setVcnManagerPolicy(true, false);
3611         NetworkRequest request = new NetworkRequest.Builder()
3612                 .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
3613                 .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED)
3614                 .build();
3615         TelephonyNetworkRequest tnr = new TelephonyNetworkRequest(request, mPhone, mFeatureFlags);
3616 
3617         mDataNetworkControllerUT.addNetworkRequest(tnr);
3618         processAllMessages();
3619 
3620         verify(mMockedDataNetworkControllerCallback)
3621                 .onConnectedInternetDataNetworksChanged(any());
3622         List<DataNetwork> dataNetworks = getDataNetworks();
3623         assertThat(dataNetworks).hasSize(1);
3624         assertThat(dataNetworks.get(0).getNetworkCapabilities().hasCapability(
3625                 NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED)).isFalse();
3626         assertThat(dataNetworks.get(0).isInternetSupported()).isTrue();
3627         assertThat(dataNetworks.get(0).getNetworkCapabilities().hasCapability(
3628                 NetworkCapabilities.NET_CAPABILITY_INTERNET)).isTrue();
3629     }
3630 
3631     @Test
testSetupDataNetworkVcnRequestedTeardown()3632     public void testSetupDataNetworkVcnRequestedTeardown() throws Exception {
3633         // VCN managed, tear down on setup.
3634         setVcnManagerPolicy(true, true);
3635         NetworkRequest request = new NetworkRequest.Builder()
3636                 .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
3637                 .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED)
3638                 .build();
3639         TelephonyNetworkRequest tnr = new TelephonyNetworkRequest(request, mPhone, mFeatureFlags);
3640 
3641         mDataNetworkControllerUT.addNetworkRequest(tnr);
3642         processAllMessages();
3643 
3644         // Should not be any data network created.
3645         List<DataNetwork> dataNetworks = getDataNetworks();
3646         assertThat(dataNetworks).hasSize(0);
3647     }
3648 
3649     @Test
testVcnManagedNetworkPolicyChanged()3650     public void testVcnManagedNetworkPolicyChanged() throws Exception {
3651         testSetupDataNetworkVcnManaged();
3652 
3653         setVcnManagerPolicy(true, true);
3654         ArgumentCaptor<VcnNetworkPolicyChangeListener> listenerCaptor =
3655                 ArgumentCaptor.forClass(VcnNetworkPolicyChangeListener.class);
3656         verify(mVcnManager).addVcnNetworkPolicyChangeListener(any(Executor.class),
3657                 listenerCaptor.capture());
3658 
3659         // Trigger policy changed event
3660         VcnNetworkPolicyChangeListener listener = listenerCaptor.getValue();
3661         listener.onPolicyChanged();
3662         processAllMessages();
3663 
3664         List<DataNetwork> dataNetworks = getDataNetworks();
3665         assertThat(dataNetworks).hasSize(0);
3666     }
3667 
3668     @Test
testDataDisableNotTearingDownUnmetered()3669     public void testDataDisableNotTearingDownUnmetered() throws Exception {
3670         // User data enabled
3671         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
3672                 TelephonyManager.DATA_ENABLED_REASON_USER, true, mContext.getOpPackageName());
3673         processAllMessages();
3674 
3675         testSetupImsDataNetwork();
3676         Mockito.clearInvocations(mMockedDataNetworkControllerCallback);
3677 
3678         // User data disabled
3679         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
3680                 TelephonyManager.DATA_ENABLED_REASON_USER, false, mContext.getOpPackageName());
3681         processAllMessages();
3682 
3683         // There shouldn't be all data disconnected event.
3684         verify(mMockedDataNetworkControllerCallback, never())
3685                 .onAnyDataNetworkExistingChanged(anyBoolean());
3686 
3687         // Verify IMS is still alive.
3688         List<DataNetwork> dataNetworkList = getDataNetworks();
3689         assertThat(dataNetworkList).hasSize(1);
3690         assertThat(dataNetworkList.get(0).getNetworkCapabilities()
3691                 .hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)).isTrue();
3692         assertThat(dataNetworkList.get(0).isConnected()).isTrue();
3693     }
3694 
3695     @Test
testDataDisableTearingDownTetheringNetwork()3696     public void testDataDisableTearingDownTetheringNetwork() throws Exception {
3697         // User data enabled
3698         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
3699                 TelephonyManager.DATA_ENABLED_REASON_USER, true, mContext.getOpPackageName());
3700         processAllMessages();
3701 
3702         // Request the restricted tethering network.
3703         NetworkCapabilities netCaps = new NetworkCapabilities();
3704         netCaps.addCapability(NetworkCapabilities.NET_CAPABILITY_DUN);
3705         netCaps.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
3706 
3707         NetworkRequest nativeNetworkRequest = new NetworkRequest(netCaps,
3708                 ConnectivityManager.TYPE_MOBILE, ++mNetworkRequestId, NetworkRequest.Type.REQUEST);
3709 
3710         mDataNetworkControllerUT.addNetworkRequest(
3711                 new TelephonyNetworkRequest(nativeNetworkRequest, mPhone, mFeatureFlags));
3712         processAllMessages();
3713 
3714         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_DUN);
3715 
3716         // User data disabled
3717         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
3718                 TelephonyManager.DATA_ENABLED_REASON_USER, false, mContext.getOpPackageName());
3719         processAllMessages();
3720 
3721         // Everything should be disconnected.
3722         verifyAllDataDisconnected();
3723     }
3724 
3725     @Test
testDataDisableTearingDownEnterpriseNetwork()3726     public void testDataDisableTearingDownEnterpriseNetwork() throws Exception {
3727         // User data enabled
3728         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
3729                 TelephonyManager.DATA_ENABLED_REASON_USER, true, mContext.getOpPackageName());
3730         processAllMessages();
3731 
3732         // Request the restricted enterprise network.
3733         testSetupEnterpriseDataNetwork();
3734 
3735         // User data disabled
3736         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
3737                 TelephonyManager.DATA_ENABLED_REASON_USER, false, mContext.getOpPackageName());
3738         processAllMessages();
3739 
3740         // Everything should be disconnected.
3741         verifyAllDataDisconnected();
3742     }
3743 
3744     @Test
testSetPreferredDataProfileMultiInternetDataProfile()3745     public void testSetPreferredDataProfileMultiInternetDataProfile() throws Exception {
3746         // No preferred data profile in the beginning
3747         doReturn(false).when(mDataProfileManager).canPreferredDataProfileSatisfy(
3748                 any(NetworkRequestList.class));
3749 
3750         testSetupDataNetwork();
3751 
3752         // Verify this network still alive after evaluation
3753         mDataNetworkControllerUT.obtainMessage(EVENT_REEVALUATE_EXISTING_DATA_NETWORKS)
3754                 .sendToTarget();
3755         processAllMessages();
3756 
3757         verifyConnectedNetworkHasDataProfile(mGeneralPurposeDataProfile);
3758 
3759         // Network connected, became preferred data profile
3760         doAnswer(invocation -> {
3761             NetworkRequestList networkRequests =
3762                     (NetworkRequestList) invocation.getArguments()[0];
3763             return networkRequests.stream()
3764                     .allMatch(request -> request.canBeSatisfiedBy(mGeneralPurposeDataProfile));
3765         }).when(mDataProfileManager).canPreferredDataProfileSatisfy(
3766                 any(NetworkRequestList.class));
3767         doReturn(true).when(mDataProfileManager)
3768                 .isDataProfilePreferred(mGeneralPurposeDataProfile);
3769 
3770         // 1. Test DUN | DEFAULT data profile is compatible with preferred default internet
3771         mDataNetworkControllerUT.addNetworkRequest(
3772                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_DUN));
3773         setSuccessfulSetupDataResponse(mMockedWwanDataServiceManager, 2);
3774         processAllMessages();
3775 
3776         // Verify both DUN and preferred default network are alive
3777         verifyConnectedNetworkHasDataProfile(mGeneralPurposeDataProfile);
3778         verifyConnectedNetworkHasDataProfile(mTetheringDataProfile);
3779 
3780         // Verify this network still alive after evaluation
3781         mDataNetworkControllerUT.obtainMessage(EVENT_REEVALUATE_EXISTING_DATA_NETWORKS)
3782                 .sendToTarget();
3783         processAllMessages();
3784 
3785         verifyConnectedNetworkHasDataProfile(mGeneralPurposeDataProfile);
3786         verifyConnectedNetworkHasDataProfile(mTetheringDataProfile);
3787 
3788         // 2. Test tear down when user changes preferred data profile
3789         doAnswer(invocation -> {
3790             NetworkRequestList networkRequests =
3791                     (NetworkRequestList) invocation.getArguments()[0];
3792             return networkRequests.stream()
3793                     .allMatch(request -> request.canBeSatisfiedBy(
3794                             mGeneralPurposeDataProfileAlternative));
3795         }).when(mDataProfileManager).canPreferredDataProfileSatisfy(
3796                 any(NetworkRequestList.class));
3797         doReturn(true).when(mDataProfileManager)
3798                 .isDataProfilePreferred(mGeneralPurposeDataProfileAlternative);
3799         doReturn(false).when(mDataProfileManager)
3800                 .isDataProfilePreferred(mGeneralPurposeDataProfile);
3801 
3802         mDataNetworkControllerUT.obtainMessage(EVENT_REEVALUATE_EXISTING_DATA_NETWORKS)
3803                 .sendToTarget();
3804         processAllMessages();
3805 
3806         List<DataNetwork> dataNetworks = getDataNetworks();
3807         assertThat(dataNetworks).hasSize(1);
3808         verifyConnectedNetworkHasDataProfile(mTetheringDataProfile);
3809     }
3810 
3811     @Test
testDataDisableNotAllowingBringingUpTetheringNetwork()3812     public void testDataDisableNotAllowingBringingUpTetheringNetwork() throws Exception {
3813         // User data disabled
3814         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
3815                 TelephonyManager.DATA_ENABLED_REASON_USER, false, mContext.getOpPackageName());
3816         processAllMessages();
3817 
3818         // Request the restricted tethering network.
3819         NetworkCapabilities netCaps = new NetworkCapabilities();
3820         netCaps.addCapability(NetworkCapabilities.NET_CAPABILITY_DUN);
3821         netCaps.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
3822 
3823         NetworkRequest nativeNetworkRequest = new NetworkRequest(netCaps,
3824                 ConnectivityManager.TYPE_MOBILE, ++mNetworkRequestId, NetworkRequest.Type.REQUEST);
3825 
3826         mDataNetworkControllerUT.addNetworkRequest(
3827                 new TelephonyNetworkRequest(nativeNetworkRequest, mPhone, mFeatureFlags));
3828         processAllMessages();
3829 
3830         // Everything should be disconnected.
3831         verifyAllDataDisconnected();
3832 
3833         // Telephony should not try to setup a data call for DUN.
3834         verify(mMockedWwanDataServiceManager, never()).setupDataCall(anyInt(),
3835                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
3836                 any(), any(), anyBoolean(), any(Message.class));
3837     }
3838 
3839     @Test
testDataDisableNotAllowingBringingUpEnterpriseNetwork()3840     public void testDataDisableNotAllowingBringingUpEnterpriseNetwork() throws Exception {
3841         // User data disabled
3842         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
3843                 TelephonyManager.DATA_ENABLED_REASON_USER, false, mContext.getOpPackageName());
3844         processAllMessages();
3845 
3846         // Request the restricted tethering network.
3847         List<TrafficDescriptor> tdList = new ArrayList<>();
3848         tdList.add(new TrafficDescriptor.Builder()
3849                 .setOsAppId(new OsAppId(OsAppId.ANDROID_OS_ID, "ENTERPRISE", 1).getBytes())
3850                 .build());
3851         setSuccessfulSetupDataResponse(mMockedWwanDataServiceManager,
3852                 createDataCallResponse(1, DataCallResponse.LINK_STATUS_ACTIVE, tdList));
3853         doReturn(mEnterpriseDataProfile).when(mDataProfileManager)
3854                 .getDataProfileForNetworkRequest(any(TelephonyNetworkRequest.class), anyInt(),
3855                         anyBoolean(), anyBoolean(), anyBoolean());
3856 
3857         NetworkCapabilities netCaps = new NetworkCapabilities();
3858         netCaps.addCapability(NetworkCapabilities.NET_CAPABILITY_ENTERPRISE);
3859         netCaps.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
3860 
3861         NetworkRequest nativeNetworkRequest = new NetworkRequest(netCaps,
3862                 ConnectivityManager.TYPE_MOBILE, ++mNetworkRequestId, NetworkRequest.Type.REQUEST);
3863 
3864         mDataNetworkControllerUT.addNetworkRequest(
3865                 new TelephonyNetworkRequest(nativeNetworkRequest, mPhone, mFeatureFlags));
3866         processAllMessages();
3867 
3868         // Everything should be disconnected.
3869         verifyAllDataDisconnected();
3870 
3871         // Telephony should not try to setup a data call for Enterprise.
3872         verify(mMockedWwanDataServiceManager, never()).setupDataCall(anyInt(),
3873                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
3874                 any(), any(), anyBoolean(), any(Message.class));
3875     }
3876     @Test
testNonVoPSNoIMSSetup()3877     public void testNonVoPSNoIMSSetup() throws Exception {
3878         DataSpecificRegistrationInfo dsri = new DataSpecificRegistrationInfo.Builder(8)
3879                 .setNrAvailable(true)
3880                 .setEnDcAvailable(true)
3881                 .setVopsSupportInfo(new LteVopsSupportInfo(
3882                         LteVopsSupportInfo.LTE_STATUS_NOT_SUPPORTED,
3883                         LteVopsSupportInfo.LTE_STATUS_NOT_SUPPORTED))
3884                 .build();
3885         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
3886                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, dsri);
3887 
3888         mDataNetworkControllerUT.addNetworkRequest(
3889                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS,
3890                         NetworkCapabilities.NET_CAPABILITY_MMTEL));
3891         processAllMessages();
3892 
3893         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_IMS);
3894         verifyAllDataDisconnected();
3895     }
3896 
3897     @Test
testNonVoPStoVoPSImsSetup()3898     public void testNonVoPStoVoPSImsSetup() throws Exception {
3899         doReturn(true).when(mFeatureFlags).allowMmtelInNonVops();
3900         mDataNetworkControllerUT.getDataSettingsManager().setDataRoamingEnabled(true);
3901         // Config that allows non-vops bring up when Roaming
3902         mCarrierConfig.putIntArray(CarrierConfigManager.Ims
3903                 .KEY_IMS_PDN_ENABLED_IN_NO_VOPS_SUPPORT_INT_ARRAY, new int[]
3904                 {CarrierConfigManager.Ims.NETWORK_TYPE_ROAMING});
3905         carrierConfigChanged();
3906 
3907         // VOPS not supported
3908         DataSpecificRegistrationInfo dsri = new DataSpecificRegistrationInfo.Builder(8)
3909                 .setNrAvailable(true)
3910                 .setEnDcAvailable(true)
3911                 .setVopsSupportInfo(new LteVopsSupportInfo(
3912                         LteVopsSupportInfo.LTE_STATUS_NOT_SUPPORTED,
3913                         LteVopsSupportInfo.LTE_STATUS_NOT_SUPPORTED))
3914                 .build();
3915         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
3916                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, dsri);
3917 
3918         mDataNetworkControllerUT.addNetworkRequest(
3919                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS,
3920                         NetworkCapabilities.NET_CAPABILITY_MMTEL));
3921         processAllMessages();
3922         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_IMS);
3923 
3924         // Verify bring up in Home is not allowed.
3925         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
3926                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, dsri);
3927         processAllMessages();
3928         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_IMS);
3929 
3930         // Verify bring up in Roaming is allowed.
3931         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
3932                 NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING, dsri);
3933         processAllMessages();
3934         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
3935                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
3936 
3937         // Verify the roaming network survives network re-evaluation.
3938         mDataNetworkControllerUT.obtainMessage(EVENT_REEVALUATE_EXISTING_DATA_NETWORKS)
3939                 .sendToTarget();
3940         processAllMessages();
3941 
3942         // Service state changed to Home, non-vops area is no longer allowed
3943         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
3944                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, dsri);
3945         processAllMessages();
3946         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_IMS);
3947 
3948         // VoPS supported
3949         dsri = new DataSpecificRegistrationInfo.Builder(8)
3950                 .setNrAvailable(true)
3951                 .setEnDcAvailable(true)
3952                 .setVopsSupportInfo(new LteVopsSupportInfo(
3953                         LteVopsSupportInfo.LTE_STATUS_SUPPORTED,
3954                         LteVopsSupportInfo.LTE_STATUS_SUPPORTED))
3955                 .build();
3956         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
3957                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, dsri);
3958 
3959         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
3960                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
3961     }
3962 
3963     @Test
testDelayImsTearDownCsRequestsToTearDown()3964     public void testDelayImsTearDownCsRequestsToTearDown() throws Exception {
3965         mCarrierConfig.putBoolean(CarrierConfigManager.KEY_DELAY_IMS_TEAR_DOWN_UNTIL_CALL_END_BOOL,
3966                 true);
3967         TelephonyNetworkRequest networkRequest = createNetworkRequest(
3968                 NetworkCapabilities.NET_CAPABILITY_IMS);
3969         mDataNetworkControllerUT.addNetworkRequest(networkRequest);
3970         processAllMessages();
3971 
3972         // Call is ongoing
3973         doReturn(PhoneConstants.State.OFFHOOK).when(mCT).getState();
3974         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
3975                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
3976         verifyConnectedNetworkHasDataProfile(mImsCellularDataProfile);
3977         List<DataNetwork> dataNetworks = getDataNetworks();
3978         assertThat(dataNetworks).hasSize(1);
3979         dataNetworks.get(0).tearDown(DataNetwork.TEAR_DOWN_REASON_RAT_NOT_ALLOWED);
3980         processAllMessages();
3981 
3982         // Make sure IMS network is still connected.
3983         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
3984                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
3985         verifyConnectedNetworkHasDataProfile(mImsCellularDataProfile);
3986 
3987         // Now connectivity service requests to tear down the data network.
3988         mDataNetworkControllerUT.removeNetworkRequest(networkRequest);
3989         dataNetworks.get(0).tearDown(DataNetwork.TEAR_DOWN_REASON_CONNECTIVITY_SERVICE_UNWANTED);
3990         processAllMessages();
3991 
3992         // All data (including IMS) should be torn down.
3993         verifyAllDataDisconnected();
3994     }
3995 
3996     @Test
testDelayImsTearDownDuringSrvcc()3997     public void testDelayImsTearDownDuringSrvcc() throws Exception {
3998         testSetupImsDataNetwork();
3999         // SRVCC in progress, delay tear down
4000         mDataNetworkControllerUT.obtainMessage(4 /*EVENT_SRVCC_STATE_CHANGED*/,
4001                 new AsyncResult(null,
4002                         new int[]{TelephonyManager.SRVCC_STATE_HANDOVER_STARTED}, null))
4003                 .sendToTarget();
4004         serviceStateChanged(TelephonyManager.NETWORK_TYPE_HSPAP,
4005                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
4006         processAllMessages();
4007 
4008         // Make sure IMS network is still connected.
4009         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
4010                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
4011 
4012         // SRVCC handover ends, tear down as normal
4013         mDataNetworkControllerUT.obtainMessage(4 /*EVENT_SRVCC_STATE_CHANGED*/,
4014                         new AsyncResult(null,
4015                                 new int[]{TelephonyManager.SRVCC_STATE_HANDOVER_CANCELED}, null))
4016                 .sendToTarget();
4017         processAllFutureMessages();
4018 
4019         // Make sure IMS network is torn down
4020         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_MMTEL);
4021     }
4022 
4023     @Test
testUnmeteredMmsWhenDataDisabled()4024     public void testUnmeteredMmsWhenDataDisabled() throws Exception {
4025         mCarrierConfig.putStringArray(
4026                 CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
4027                 new String[]{"default", "dun", "supl"});
4028         carrierConfigChanged();
4029 
4030         // User data disabled
4031         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
4032                 TelephonyManager.DATA_ENABLED_REASON_USER, false, mContext.getOpPackageName());
4033         processAllMessages();
4034 
4035         mDataNetworkControllerUT.addNetworkRequest(
4036                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_MMS));
4037         processAllMessages();
4038 
4039         // Make sure MMS is the only capability advertised, but not internet or SUPL.
4040         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_MMS);
4041         verifyConnectedNetworkHasDataProfile(mGeneralPurposeDataProfile);
4042         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
4043         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL);
4044     }
4045 
4046     @Test
testUnmeteredMmsWhenRoamingDisabled()4047     public void testUnmeteredMmsWhenRoamingDisabled() throws Exception {
4048         mCarrierConfig.putStringArray(
4049                 CarrierConfigManager.KEY_CARRIER_METERED_ROAMING_APN_TYPES_STRINGS,
4050                 new String[]{"default", "dun", "supl"});
4051         carrierConfigChanged();
4052 
4053         // Roaming data disabled
4054         mDataNetworkControllerUT.getDataSettingsManager().setDataRoamingEnabled(false);
4055         processAllMessages();
4056 
4057         // Device is roaming
4058         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
4059                 NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
4060 
4061         mDataNetworkControllerUT.addNetworkRequest(
4062                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_MMS));
4063         processAllMessages();
4064 
4065         // Make sure MMS is the only capability advertised, but not internet or SUPL.
4066         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_MMS);
4067         verifyConnectedNetworkHasDataProfile(mGeneralPurposeDataProfile);
4068         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
4069         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL);
4070     }
4071 
4072     @Test
testRestrictedNetworkRequestDataDisabled()4073     public void testRestrictedNetworkRequestDataDisabled() throws Exception {
4074         // User data disabled
4075         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
4076                 TelephonyManager.DATA_ENABLED_REASON_USER, false, mContext.getOpPackageName());
4077         processAllMessages();
4078 
4079         // Create a restricted network request.
4080         NetworkCapabilities netCaps = new NetworkCapabilities();
4081         netCaps.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
4082         netCaps.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
4083 
4084         NetworkRequest nativeNetworkRequest = new NetworkRequest(netCaps,
4085                 ConnectivityManager.TYPE_MOBILE, ++mNetworkRequestId, NetworkRequest.Type.REQUEST);
4086 
4087         mDataNetworkControllerUT.addNetworkRequest(
4088                 new TelephonyNetworkRequest(nativeNetworkRequest, mPhone, mFeatureFlags));
4089         processAllMessages();
4090 
4091         verifyConnectedNetworkHasDataProfile(mGeneralPurposeDataProfile);
4092         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_INTERNET,
4093                 NetworkCapabilities.NET_CAPABILITY_SUPL, NetworkCapabilities.NET_CAPABILITY_MMS);
4094 
4095         List<DataNetwork> dataNetworks = getDataNetworks();
4096         // Make sure the network is restricted.
4097         assertThat(dataNetworks.get(0).getNetworkCapabilities()
4098                 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)).isFalse();
4099     }
4100 
4101     @Test
testRestrictedNetworkRequestDataEnabled()4102     public void testRestrictedNetworkRequestDataEnabled() throws Exception {
4103         // Create a restricted network request.
4104         NetworkCapabilities netCaps = new NetworkCapabilities();
4105         netCaps.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
4106         netCaps.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
4107 
4108         NetworkRequest nativeNetworkRequest = new NetworkRequest(netCaps,
4109                 ConnectivityManager.TYPE_MOBILE, ++mNetworkRequestId, NetworkRequest.Type.REQUEST);
4110 
4111         mDataNetworkControllerUT.addNetworkRequest(
4112                 new TelephonyNetworkRequest(nativeNetworkRequest, mPhone, mFeatureFlags));
4113         processAllMessages();
4114 
4115         verifyConnectedNetworkHasDataProfile(mGeneralPurposeDataProfile);
4116         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_INTERNET,
4117                 NetworkCapabilities.NET_CAPABILITY_SUPL, NetworkCapabilities.NET_CAPABILITY_MMS,
4118                 // Because data is enabled, even though the network request is restricted, the
4119                 // network should still be not-restricted.
4120                 NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
4121     }
4122 
4123     @Test
testSinglePdnArbitration()4124     public void testSinglePdnArbitration() throws Exception {
4125         // On old 1x network, only one data network is allowed.
4126         serviceStateChanged(TelephonyManager.NETWORK_TYPE_1xRTT,
4127                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
4128 
4129         mDataNetworkControllerUT.addNetworkRequest(
4130                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_DUN));
4131         processAllMessages();
4132         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_DUN);
4133 
4134         mDataNetworkControllerUT.addNetworkRequest(
4135                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_ENTERPRISE));
4136         processAllFutureMessages();
4137         // Lower priority network should not trump the higher priority network.
4138         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_DUN);
4139         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_ENTERPRISE);
4140 
4141         // Now send a higher priority network request
4142         TelephonyNetworkRequest fotaRequest = createNetworkRequest(
4143                 NetworkCapabilities.NET_CAPABILITY_FOTA);
4144         mDataNetworkControllerUT.addNetworkRequest(fotaRequest);
4145 
4146         processAllFutureMessages();
4147         // The existing internet data network should be torn down.
4148         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_DUN);
4149         // The higher priority emergency data network should be established.
4150         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_FOTA);
4151 
4152         // Now remove the fota request and tear down fota network.
4153         mDataNetworkControllerUT.removeNetworkRequest(fotaRequest);
4154         processAllMessages();
4155         List<DataNetwork> dataNetworks = getDataNetworks();
4156         dataNetworks.get(0).tearDown(DataNetwork.TEAR_DOWN_REASON_CONNECTIVITY_SERVICE_UNWANTED);
4157         processAllMessages();
4158 
4159         // The tethering data network should come back since now it has the highest priority after
4160         // fota is gone.
4161         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_DUN);
4162         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA);
4163     }
4164 
4165     @Test
testNetworkValidationStatusChangeCallback()4166     public void testNetworkValidationStatusChangeCallback() throws Exception {
4167         // Request not restricted network
4168         TelephonyNetworkRequest request = createNetworkRequest(
4169                 NetworkCapabilities.NET_CAPABILITY_INTERNET);
4170         mDataNetworkControllerUT.addNetworkRequest(request);
4171         processAllMessages();
4172         TelephonyNetworkAgent agent = getPrivateField(getDataNetworks().get(0), "mNetworkAgent",
4173                 TelephonyNetworkAgent.class);
4174         agent.onValidationStatus(1/*status*/, Uri.EMPTY);
4175         processAllMessages();
4176 
4177         // Verify notify
4178         verify(mMockedDataNetworkControllerCallback)
4179                 .onInternetDataNetworkValidationStatusChanged(1);
4180 
4181         // Request restricted network
4182         mDataNetworkControllerUT.removeNetworkRequest(request);
4183         getDataNetworks().get(0).tearDown(DataNetwork.TEAR_DOWN_REASON_NONE);
4184         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(0, false, "");
4185         processAllMessages();
4186         clearInvocations(mMockedDataNetworkControllerCallback);
4187         mDataNetworkControllerUT.addNetworkRequest(createNetworkRequest(
4188                 true, NetworkCapabilities.NET_CAPABILITY_INTERNET));
4189         processAllMessages();
4190         agent = getPrivateField(getDataNetworks().get(0), "mNetworkAgent",
4191                 TelephonyNetworkAgent.class);
4192         agent.onValidationStatus(1/*status*/, Uri.EMPTY);
4193         processAllMessages();
4194 
4195         // Verify not notified
4196         verify(mMockedDataNetworkControllerCallback, never())
4197                 .onInternetDataNetworkValidationStatusChanged(anyInt());
4198     }
4199 
4200     @Test
testImsGracefulTearDown()4201     public void testImsGracefulTearDown() throws Exception {
4202         setImsRegistered(true);
4203         setRcsRegistered(true);
4204 
4205         NetworkCapabilities netCaps = new NetworkCapabilities();
4206         netCaps.addCapability(NetworkCapabilities.NET_CAPABILITY_IMS);
4207         netCaps.maybeMarkCapabilitiesRestricted();
4208         netCaps.setRequestorPackageName(FAKE_MMTEL_PACKAGE);
4209 
4210         NetworkRequest nativeNetworkRequest = new NetworkRequest(netCaps,
4211                 ConnectivityManager.TYPE_MOBILE, ++mNetworkRequestId, NetworkRequest.Type.REQUEST);
4212         TelephonyNetworkRequest networkRequest = new TelephonyNetworkRequest(
4213                 nativeNetworkRequest, mPhone, mFeatureFlags);
4214 
4215         mDataNetworkControllerUT.addNetworkRequest(networkRequest);
4216 
4217         processAllMessages();
4218         Mockito.clearInvocations(mPhone);
4219 
4220         // SIM removal
4221         mDataNetworkControllerUT.obtainMessage(9/*EVENT_SIM_STATE_CHANGED*/,
4222                 TelephonyManager.SIM_STATE_ABSENT, 0).sendToTarget();
4223         processAllMessages();
4224 
4225         // Make sure data network enters disconnecting state
4226         ArgumentCaptor<PreciseDataConnectionState> pdcsCaptor =
4227                 ArgumentCaptor.forClass(PreciseDataConnectionState.class);
4228         verify(mPhone).notifyDataConnection(pdcsCaptor.capture());
4229         PreciseDataConnectionState pdcs = pdcsCaptor.getValue();
4230         assertThat(pdcs.getState()).isEqualTo(TelephonyManager.DATA_DISCONNECTING);
4231 
4232         // IMS de-registered. Now data network is safe to be torn down.
4233         Mockito.clearInvocations(mPhone);
4234         setImsRegistered(false);
4235         setRcsRegistered(false);
4236         processAllMessages();
4237 
4238         // All data should be disconnected.
4239         verifyAllDataDisconnected();
4240         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_IMS);
4241         verify(mPhone).notifyDataConnection(pdcsCaptor.capture());
4242         pdcs = pdcsCaptor.getValue();
4243         assertThat(pdcs.getState()).isEqualTo(TelephonyManager.DATA_DISCONNECTED);
4244     }
4245 
4246     @Test
testNoGracefulTearDownForEmergencyDataNetwork()4247     public void testNoGracefulTearDownForEmergencyDataNetwork() throws Exception {
4248         setImsRegistered(true);
4249 
4250         mCarrierConfig.putStringArray(CarrierConfigManager.KEY_IWLAN_HANDOVER_POLICY_STRING_ARRAY,
4251                 new String[]{"source=EUTRAN, target=IWLAN, type=disallowed, capabilities=EIMS|IMS",
4252                         "source=IWLAN, target=EUTRAN, type=disallowed, capabilities=MMS"});
4253         // Force data config manager to reload the carrier config.
4254         carrierConfigChanged();
4255         processAllMessages();
4256 
4257         // setup emergency data network.
4258         NetworkCapabilities netCaps = new NetworkCapabilities();
4259         netCaps.addCapability(NetworkCapabilities.NET_CAPABILITY_EIMS);
4260         netCaps.maybeMarkCapabilitiesRestricted();
4261         netCaps.setRequestorPackageName(FAKE_MMTEL_PACKAGE);
4262 
4263         NetworkRequest nativeNetworkRequest = new NetworkRequest(netCaps,
4264                 ConnectivityManager.TYPE_MOBILE, ++mNetworkRequestId, NetworkRequest.Type.REQUEST);
4265         TelephonyNetworkRequest networkRequest = new TelephonyNetworkRequest(
4266                 nativeNetworkRequest, mPhone, mFeatureFlags);
4267 
4268         mDataNetworkControllerUT.addNetworkRequest(networkRequest);
4269         processAllMessages();
4270 
4271         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_EIMS);
4272 
4273         updateTransport(NetworkCapabilities.NET_CAPABILITY_EIMS,
4274                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
4275 
4276         // Verify all data disconnected.
4277         verify(mMockedDataNetworkControllerCallback).onAnyDataNetworkExistingChanged(eq(false));
4278         verify(mMockedDataNetworkControllerCallback).onPhysicalLinkStatusChanged(
4279                 eq(DataCallResponse.LINK_STATUS_INACTIVE));
4280 
4281         // A new data network should be connected on IWLAN
4282         List<DataNetwork> dataNetworkList = getDataNetworks();
4283         assertThat(dataNetworkList).hasSize(1);
4284         assertThat(dataNetworkList.get(0).isConnected()).isTrue();
4285         assertThat(dataNetworkList.get(0).getNetworkCapabilities().hasCapability(
4286                 NetworkCapabilities.NET_CAPABILITY_EIMS)).isTrue();
4287         assertThat(dataNetworkList.get(0).getTransport())
4288                 .isEqualTo(AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
4289     }
4290 
4291     @Test
testNetworkRequestRemovedBeforeRetry()4292     public void testNetworkRequestRemovedBeforeRetry() {
4293         setFailedSetupDataResponse(mMockedWwanDataServiceManager, DataFailCause.CONGESTION,
4294                 DataCallResponse.RETRY_DURATION_UNDEFINED, false);
4295         TelephonyNetworkRequest networkRequest = createNetworkRequest(
4296                 NetworkCapabilities.NET_CAPABILITY_INTERNET);
4297         mDataNetworkControllerUT.addNetworkRequest(networkRequest);
4298         logd("Removing network request.");
4299         mDataNetworkControllerUT.removeNetworkRequest(networkRequest);
4300         processAllMessages();
4301 
4302         // There should be only one invocation, which is the original setup data request. There
4303         // shouldn't be more than 1 (i.e. should not retry).
4304         verify(mMockedWwanDataServiceManager, times(1)).setupDataCall(anyInt(),
4305                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
4306                 any(), any(), anyBoolean(), any(Message.class));
4307     }
4308 
4309     @Test
testGetInternetDataDisallowedReasons()4310     public void testGetInternetDataDisallowedReasons() {
4311         List<DataDisallowedReason> reasons = mDataNetworkControllerUT
4312                 .getInternetDataDisallowedReasons();
4313         assertThat(reasons).isEmpty();
4314 
4315         serviceStateChanged(TelephonyManager.NETWORK_TYPE_UNKNOWN,
4316                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING);
4317 
4318         reasons = mDataNetworkControllerUT.getInternetDataDisallowedReasons();
4319         assertThat(reasons).containsExactly(DataDisallowedReason.NOT_IN_SERVICE,
4320                 DataDisallowedReason.NO_SUITABLE_DATA_PROFILE);
4321     }
4322 
4323     @Test
testEmergencySuplDataDisabled()4324     public void testEmergencySuplDataDisabled() throws Exception {
4325         // Data disabled
4326         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
4327                 TelephonyManager.DATA_ENABLED_REASON_USER, false, mContext.getOpPackageName());
4328         processAllMessages();
4329         doReturn(true).when(mTelecomManager).isInEmergencyCall();
4330         mDataNetworkControllerUT.addNetworkRequest(
4331                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_SUPL));
4332         processAllMessages();
4333 
4334         // Make sure SUPL is the only capability advertised, but not internet or MMS.
4335         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_SUPL);
4336         verifyConnectedNetworkHasDataProfile(mGeneralPurposeDataProfile);
4337         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
4338         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_MMS);
4339     }
4340 
4341     @Test
testEmergencyCallDataDisabled()4342     public void testEmergencyCallDataDisabled() throws Exception {
4343         doReturn(true).when(mTelecomManager).isInEmergencyCall();
4344         mDataNetworkControllerUT.addNetworkRequest(
4345                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
4346         processAllMessages();
4347 
4348         verifyInternetConnected();
4349 
4350         // Data disabled
4351         mDataNetworkControllerUT.getDataSettingsManager().setDataEnabled(
4352                 TelephonyManager.DATA_ENABLED_REASON_USER, false, mContext.getOpPackageName());
4353         processAllMessages();
4354 
4355         // Make sure internet is not connected. (Previously it has a bug due to incorrect logic
4356         // to determine it's for emergency SUPL).
4357         verifyAllDataDisconnected();
4358     }
4359 
4360     @Test
testDataActivity()4361     public void testDataActivity() {
4362         doReturn(TelephonyManager.DATA_ACTIVITY_IN).when(mLinkBandwidthEstimator).getDataActivity();
4363         mLinkBandwidthEstimatorCallback.onDataActivityChanged(TelephonyManager.DATA_ACTIVITY_IN);
4364         processAllMessages();
4365         assertThat(mDataNetworkControllerUT.getDataActivity()).isEqualTo(
4366                 TelephonyManager.DATA_ACTIVITY_IN);
4367 
4368         doReturn(TelephonyManager.DATA_ACTIVITY_OUT).when(mLinkBandwidthEstimator)
4369                 .getDataActivity();
4370         mLinkBandwidthEstimatorCallback.onDataActivityChanged(TelephonyManager.DATA_ACTIVITY_OUT);
4371         processAllMessages();
4372         assertThat(mDataNetworkControllerUT.getDataActivity()).isEqualTo(
4373                 TelephonyManager.DATA_ACTIVITY_OUT);
4374 
4375         doReturn(TelephonyManager.DATA_ACTIVITY_INOUT).when(mLinkBandwidthEstimator)
4376                 .getDataActivity();
4377         mLinkBandwidthEstimatorCallback.onDataActivityChanged(TelephonyManager.DATA_ACTIVITY_INOUT);
4378         processAllMessages();
4379         assertThat(mDataNetworkControllerUT.getDataActivity()).isEqualTo(
4380                 TelephonyManager.DATA_ACTIVITY_INOUT);
4381 
4382         doReturn(TelephonyManager.DATA_ACTIVITY_NONE).when(mLinkBandwidthEstimator)
4383                 .getDataActivity();
4384         mLinkBandwidthEstimatorCallback.onDataActivityChanged(TelephonyManager.DATA_ACTIVITY_NONE);
4385         processAllMessages();
4386         assertThat(mDataNetworkControllerUT.getDataActivity()).isEqualTo(
4387                 TelephonyManager.DATA_ACTIVITY_NONE);
4388     }
4389 
4390     @Test
testHandoverDataNetworkOos()4391     public void testHandoverDataNetworkOos() throws Exception {
4392         // Config delay IMS tear down enabled
4393         mCarrierConfig.putBoolean(CarrierConfigManager.KEY_DELAY_IMS_TEAR_DOWN_UNTIL_CALL_END_BOOL,
4394                 true);
4395         carrierConfigChanged();
4396 
4397         // VoPS supported
4398         DataSpecificRegistrationInfo dsri = new DataSpecificRegistrationInfo.Builder(8)
4399                 .setNrAvailable(true)
4400                 .setEnDcAvailable(true)
4401                 .setVopsSupportInfo(new LteVopsSupportInfo(
4402                         LteVopsSupportInfo.LTE_STATUS_SUPPORTED,
4403                         LteVopsSupportInfo.LTE_STATUS_SUPPORTED))
4404                 .build();
4405         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
4406                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME /*data*/,
4407                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME /*voice*/,
4408                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING /*iwlan*/,
4409                 dsri);
4410 
4411         testSetupImsDataNetwork();
4412         DataNetwork dataNetwork = getDataNetworks().get(0);
4413 
4414         // 1. Active VoPS call, mock target IWLAN OOS, should schedule retry
4415         doReturn(PhoneConstants.State.RINGING).when(mCT).getState();
4416         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
4417                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
4418         // Process DRM event to schedule retry
4419         processAllMessages();
4420 
4421         // Verify scheduled new handover retry
4422         assertTrue(mDataNetworkControllerUT.getDataRetryManager()
4423                 .isAnyHandoverRetryScheduled(dataNetwork));
4424         // Verify the network wasn't torn down
4425         verify(mMockedWwanDataServiceManager, never()).deactivateDataCall(anyInt(),
4426                 eq(DataService.REQUEST_REASON_NORMAL), any(Message.class));
4427 
4428         // Get the scheduled retry
4429         Field field = DataRetryManager.class.getDeclaredField("mDataRetryEntries");
4430         field.setAccessible(true);
4431         DataRetryManager.DataHandoverRetryEntry dataRetryEntry =
4432                 (DataRetryManager.DataHandoverRetryEntry) ((List<DataRetryManager.DataRetryEntry>)
4433                         field.get(mDataNetworkControllerUT.getDataRetryManager())).get(0);
4434 
4435         // Process the retry
4436         moveTimeForward(1000 /*The retry delay of the first attempt*/);
4437         processAllMessages();
4438 
4439         // Verify the previous retry is set to FAILED
4440         assertEquals(DataRetryManager.DataRetryEntry.RETRY_STATE_FAILED, dataRetryEntry.getState());
4441         // Verify a new retry is scheduled
4442         assertTrue(mDataNetworkControllerUT.getDataRetryManager()
4443                 .isAnyHandoverRetryScheduled(dataNetwork));
4444 
4445         // 2. Normal case (call ended), should tear down
4446         doReturn(PhoneConstants.State.IDLE).when(mCT).getState();
4447         mDataNetworkControllerUT.obtainMessage(EVENT_VOICE_CALL_ENDED).sendToTarget();
4448         processAllFutureMessages();
4449 
4450         // Verify that handover is not performed.
4451         verify(mMockedWlanDataServiceManager, never()).setupDataCall(anyInt(),
4452                 any(DataProfile.class), anyBoolean(), anyBoolean(),
4453                 eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), any(), anyBoolean(),
4454                 any(Message.class));
4455 
4456         // Verify IMS network should be torn down.
4457         verifyAllDataDisconnected();
4458     }
4459 
4460     @Test
testHandoverDataNetworkSourceOos()4461     public void testHandoverDataNetworkSourceOos() throws Exception {
4462         testSetupImsDataNetwork();
4463         // Configured handover is disallowed from OOS to 4G/5G/IWLAN.
4464         mCarrierConfig.putStringArray(
4465                 CarrierConfigManager.KEY_IWLAN_HANDOVER_POLICY_STRING_ARRAY,
4466                 new String[]{
4467                         "source=EUTRAN|NGRAN|IWLAN|UNKNOWN, target=EUTRAN|NGRAN|IWLAN, "
4468                                 + "type=disallowed, capabilities=IMS|EIMS|MMS|XCAP|CBS"
4469                 });
4470         carrierConfigChanged();
4471         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
4472                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING);
4473 
4474         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
4475                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
4476 
4477         // Verify IMS network was torn down on source first.
4478         verify(mMockedWwanDataServiceManager).deactivateDataCall(anyInt(),
4479                 eq(DataService.REQUEST_REASON_NORMAL), any(Message.class));
4480 
4481         // Verify that IWLAN is brought up again on IWLAN.
4482         verify(mMockedWlanDataServiceManager).setupDataCall(anyInt(),
4483                 any(DataProfile.class), anyBoolean(), anyBoolean(),
4484                 eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), any(), anyBoolean(),
4485                 any(Message.class));
4486 
4487         DataNetwork dataNetwork = getDataNetworks().get(0);
4488         assertThat(dataNetwork.getTransport()).isEqualTo(
4489                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
4490     }
4491 
4492     @Test
testHandoverDataNetworkRoamingOos()4493     public void testHandoverDataNetworkRoamingOos() throws Exception {
4494         testSetupImsDataNetwork();
4495         // Configured handover is disallowed at Roaming.
4496         mCarrierConfig.putStringArray(
4497                 CarrierConfigManager.KEY_IWLAN_HANDOVER_POLICY_STRING_ARRAY,
4498                 new String[]{
4499                         "source=GERAN|UTRAN|EUTRAN|NGRAN|IWLAN|UNKNOWN, "
4500                                 + "target=GERAN|UTRAN|EUTRAN|NGRAN|IWLAN, roaming=true, "
4501                                 + "type=disallowed, capabilities=IMS"
4502                 });
4503         carrierConfigChanged();
4504         DataNetwork dataNetwork = getDataNetworks().get(0);
4505         //Enter ROAMING
4506         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
4507                 NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
4508         updateServiceStateForDatatNetwork(TelephonyManager.NETWORK_TYPE_LTE,
4509                 NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING, dataNetwork);
4510         //OOS
4511         serviceStateChanged(TelephonyManager.NETWORK_TYPE_UNKNOWN,
4512                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING);
4513         updateServiceStateForDatatNetwork(TelephonyManager.NETWORK_TYPE_UNKNOWN,
4514                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING,
4515                 dataNetwork);
4516 
4517         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
4518                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
4519 
4520         // Verify IMS network was torn down on source first.
4521         verify(mMockedWwanDataServiceManager).deactivateDataCall(anyInt(),
4522                 eq(DataService.REQUEST_REASON_NORMAL), any(Message.class));
4523 
4524         // Verify that IWLAN is brought up again on IWLAN.
4525         verify(mMockedWlanDataServiceManager).setupDataCall(anyInt(),
4526                 any(DataProfile.class), anyBoolean(), anyBoolean(),
4527                 eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), any(), anyBoolean(),
4528                 any(Message.class));
4529 
4530         DataNetwork dataNetworkIwlan = getDataNetworks().get(0);
4531         assertThat(dataNetworkIwlan.getTransport()).isEqualTo(
4532                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
4533     }
4534 
updateServiceStateForDatatNetwork(@nnotation.NetworkType int networkType, @NetworkRegistrationInfo.RegistrationState int regState, DataNetwork dataNetwork)4535     private void updateServiceStateForDatatNetwork(@Annotation.NetworkType int networkType,
4536             @NetworkRegistrationInfo.RegistrationState int regState, DataNetwork dataNetwork) {
4537         ServiceState ss = new ServiceState();
4538         ss.addNetworkRegistrationInfo(new NetworkRegistrationInfo.Builder()
4539                 .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
4540                 .setAccessNetworkTechnology(networkType)
4541                 .setRegistrationState(regState)
4542                 .setDomain(NetworkRegistrationInfo.DOMAIN_PS)
4543                 .setDataSpecificInfo(null)
4544                 .build());
4545 
4546         ss.addNetworkRegistrationInfo(new NetworkRegistrationInfo.Builder()
4547                 .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WLAN)
4548                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_IWLAN)
4549                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
4550                 .setDomain(NetworkRegistrationInfo.DOMAIN_PS)
4551                 .build());
4552 
4553         ss.addNetworkRegistrationInfo(new NetworkRegistrationInfo.Builder()
4554                 .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
4555                 .setAccessNetworkTechnology(networkType)
4556                 .setRegistrationState(regState)
4557                 .setDomain(NetworkRegistrationInfo.DOMAIN_CS)
4558                 .build());
4559         ss.setDataRoamingFromRegistration(regState
4560                 == NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
4561         doReturn(ss).when(mSST).getServiceState();
4562         doReturn(ss).when(mPhone).getServiceState();
4563 
4564         if (dataNetwork != null) {
4565             dataNetwork.obtainMessage(9/*EVENT_SERVICE_STATE_CHANGED*/).sendToTarget();
4566             processAllMessages();
4567         }
4568     }
4569 
4570     @Test
testHandoverDataNetworkSourceOosNoUnknownRule()4571     public void testHandoverDataNetworkSourceOosNoUnknownRule() throws Exception {
4572         testSetupImsDataNetwork();
4573         // Configured handover is allowed from OOS to 4G/5G/IWLAN.
4574         mCarrierConfig.putStringArray(
4575                 CarrierConfigManager.KEY_IWLAN_HANDOVER_POLICY_STRING_ARRAY,
4576                 new String[]{
4577                         "source=EUTRAN|NGRAN|IWLAN, target=EUTRAN|NGRAN|IWLAN, "
4578                                 + "type=disallowed, capabilities=IMS|EIMS|MMS|XCAP|CBS"
4579                 });
4580         carrierConfigChanged();
4581         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
4582                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING);
4583 
4584         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
4585                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
4586 
4587         // Verify IMS network was torn down on source first.
4588         verify(mMockedWwanDataServiceManager).deactivateDataCall(anyInt(),
4589                 eq(DataService.REQUEST_REASON_NORMAL), any(Message.class));
4590 
4591         // Verify that IWLAN is brought up again on IWLAN.
4592         verify(mMockedWlanDataServiceManager).setupDataCall(anyInt(),
4593                 any(DataProfile.class), anyBoolean(), anyBoolean(),
4594                 eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), any(), anyBoolean(),
4595                 any(Message.class));
4596 
4597         DataNetwork dataNetwork = getDataNetworks().get(0);
4598         assertThat(dataNetwork.getTransport()).isEqualTo(
4599                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
4600     }
4601 
4602     @Test
testHandoverDataNetworkNonVops()4603     public void testHandoverDataNetworkNonVops() throws Exception {
4604         DataSpecificRegistrationInfo dsri = new DataSpecificRegistrationInfo.Builder(8)
4605                 .setNrAvailable(true)
4606                 .setEnDcAvailable(true)
4607                 .setVopsSupportInfo(new LteVopsSupportInfo(
4608                         LteVopsSupportInfo.LTE_STATUS_NOT_SUPPORTED,
4609                         LteVopsSupportInfo.LTE_STATUS_NOT_SUPPORTED))
4610                 .build();
4611         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
4612                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, dsri);
4613 
4614         doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WLAN).when(mAccessNetworksManager)
4615                 .getPreferredTransportByNetworkCapability(NetworkCapabilities.NET_CAPABILITY_IMS);
4616 
4617         mDataNetworkControllerUT.obtainMessage(EVENT_SERVICE_STATE_CHANGED).sendToTarget();
4618         processAllMessages();
4619 
4620         mDataNetworkControllerUT.addNetworkRequest(
4621                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS,
4622                         NetworkCapabilities.NET_CAPABILITY_MMTEL));
4623         processAllMessages();
4624         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
4625                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
4626 
4627         // Change the preference to cellular
4628         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
4629                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
4630 
4631         // Verify that handover is not performed.
4632         verify(mMockedWwanDataServiceManager, never()).setupDataCall(anyInt(),
4633                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
4634                 any(), any(), anyBoolean(), any(Message.class));
4635 
4636         // IMS network should be torn down.
4637         verifyAllDataDisconnected();
4638     }
4639 
4640     @Test
testHandoverDataNetworkNonVopsAllowLingeringVoPS()4641     public void testHandoverDataNetworkNonVopsAllowLingeringVoPS() throws Exception {
4642         // Allow lingering IMS PDN when enter area VoPS -> no VoPS
4643         mCarrierConfig.putBoolean(CarrierConfigManager.Ims.KEY_KEEP_PDN_UP_IN_NO_VOPS_BOOL, true);
4644         carrierConfigChanged();
4645 
4646         DataSpecificRegistrationInfo dsri = new DataSpecificRegistrationInfo.Builder(8)
4647                 .setNrAvailable(true)
4648                 .setEnDcAvailable(true)
4649                 .setVopsSupportInfo(new LteVopsSupportInfo(
4650                         LteVopsSupportInfo.LTE_STATUS_NOT_SUPPORTED,
4651                         LteVopsSupportInfo.LTE_STATUS_NOT_SUPPORTED))
4652                 .build();
4653         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
4654                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, dsri);
4655 
4656         doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WLAN).when(mAccessNetworksManager)
4657                 .getPreferredTransportByNetworkCapability(NetworkCapabilities.NET_CAPABILITY_IMS);
4658 
4659         mDataNetworkControllerUT.obtainMessage(EVENT_SERVICE_STATE_CHANGED).sendToTarget();
4660         processAllMessages();
4661 
4662         mDataNetworkControllerUT.addNetworkRequest(
4663                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS,
4664                         NetworkCapabilities.NET_CAPABILITY_MMTEL));
4665         processAllMessages();
4666         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
4667                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
4668 
4669         // Change the preference to cellular
4670         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
4671                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
4672 
4673         // Verify that handover is not performed.
4674         verify(mMockedWwanDataServiceManager).setupDataCall(anyInt(),
4675                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
4676                 any(), any(), anyBoolean(), any(Message.class));
4677 
4678         // IMS network still alive.
4679         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
4680                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
4681     }
4682 
4683     @Test
testNonMmtelImsHandoverDataNetworkNonVops()4684     public void testNonMmtelImsHandoverDataNetworkNonVops() throws Exception {
4685         DataSpecificRegistrationInfo dsri = new DataSpecificRegistrationInfo.Builder(8)
4686                 .setNrAvailable(true)
4687                 .setEnDcAvailable(true)
4688                 .setVopsSupportInfo(new LteVopsSupportInfo(
4689                         LteVopsSupportInfo.LTE_STATUS_NOT_SUPPORTED,
4690                         LteVopsSupportInfo.LTE_STATUS_NOT_SUPPORTED))
4691                 .build();
4692 
4693         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
4694                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, dsri);
4695 
4696         doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WLAN).when(mAccessNetworksManager)
4697                 .getPreferredTransportByNetworkCapability(NetworkCapabilities.NET_CAPABILITY_IMS);
4698 
4699         mDataNetworkControllerUT.obtainMessage(EVENT_SERVICE_STATE_CHANGED).sendToTarget();
4700         processAllMessages();
4701 
4702         // Bring up the IMS network that does not require MMTEL
4703         mDataNetworkControllerUT.addNetworkRequest(
4704                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS));
4705         processAllMessages();
4706 
4707         // Even though the network request does not have MMTEL, the WLAN network support it, so
4708         // the network capabilities should still have MMTEL.
4709         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
4710                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
4711 
4712         // Change the preference to cellular
4713         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
4714                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
4715 
4716         // Verify that handover is performed
4717         verify(mMockedWwanDataServiceManager).setupDataCall(anyInt(),
4718                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
4719                 any(), any(), anyBoolean(), any(Message.class));
4720 
4721         // The IMS network should still have IMS, but MMTEL is removed.
4722         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS);
4723         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_MMTEL);
4724     }
4725 
4726     @Test
testMmtelImsDataNetworkMovingToNonVops()4727     public void testMmtelImsDataNetworkMovingToNonVops() throws Exception {
4728         // Allow lingering IMS PDN when enter area VoPS -> no VoPS
4729         mCarrierConfig.putBoolean(CarrierConfigManager.Ims.KEY_KEEP_PDN_UP_IN_NO_VOPS_BOOL, true);
4730         carrierConfigChanged();
4731 
4732         // VoPS network
4733         DataSpecificRegistrationInfo dsri = new DataSpecificRegistrationInfo.Builder(8)
4734                 .setNrAvailable(true)
4735                 .setEnDcAvailable(true)
4736                 .setVopsSupportInfo(new LteVopsSupportInfo(
4737                         LteVopsSupportInfo.LTE_STATUS_SUPPORTED,
4738                         LteVopsSupportInfo.LTE_STATUS_SUPPORTED))
4739                 .build();
4740 
4741         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
4742                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, dsri);
4743 
4744         doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WWAN).when(mAccessNetworksManager)
4745                 .getPreferredTransportByNetworkCapability(NetworkCapabilities.NET_CAPABILITY_IMS);
4746 
4747         mDataNetworkControllerUT.obtainMessage(EVENT_SERVICE_STATE_CHANGED).sendToTarget();
4748         processAllMessages();
4749 
4750         // Bring up the IMS network that does require MMTEL
4751         mDataNetworkControllerUT.addNetworkRequest(
4752                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS,
4753                         NetworkCapabilities.NET_CAPABILITY_MMTEL));
4754         processAllMessages();
4755 
4756         // the network capabilities should have IMS and MMTEL.
4757         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
4758                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
4759 
4760         // Non VoPS network
4761         dsri = new DataSpecificRegistrationInfo.Builder(8)
4762                 .setNrAvailable(true)
4763                 .setEnDcAvailable(true)
4764                 .setVopsSupportInfo(new LteVopsSupportInfo(
4765                         LteVopsSupportInfo.LTE_STATUS_NOT_SUPPORTED,
4766                         LteVopsSupportInfo.LTE_STATUS_NOT_SUPPORTED))
4767                 .build();
4768 
4769         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
4770                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, dsri);
4771 
4772         mDataNetworkControllerUT.obtainMessage(EVENT_SERVICE_STATE_CHANGED).sendToTarget();
4773         processAllMessages();
4774 
4775         // The IMS network is alive due to KEY_KEEP_PDN_UP_IN_NO_VOPS_BOOL = true
4776         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
4777                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
4778 
4779         mCarrierConfig.putBoolean(CarrierConfigManager.Ims.KEY_KEEP_PDN_UP_IN_NO_VOPS_BOOL, false);
4780         carrierConfigChanged();
4781         mDataNetworkControllerUT.obtainMessage(EVENT_REEVALUATE_EXISTING_DATA_NETWORKS)
4782                 .sendToTarget();
4783         processAllMessages();
4784 
4785         // The IMS network should be torn down by data network controller.
4786         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_IMS);
4787         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_MMTEL);
4788     }
4789 
4790     @Test
testVoPStoNonVoPSDelayImsTearDown()4791     public void testVoPStoNonVoPSDelayImsTearDown() throws Exception {
4792         mCarrierConfig.putBoolean(CarrierConfigManager.KEY_DELAY_IMS_TEAR_DOWN_UNTIL_CALL_END_BOOL,
4793                 true);
4794         carrierConfigChanged();
4795 
4796         // VoPS supported
4797         DataSpecificRegistrationInfo dsri = new DataSpecificRegistrationInfo.Builder(8)
4798                 .setNrAvailable(true)
4799                 .setEnDcAvailable(true)
4800                 .setVopsSupportInfo(new LteVopsSupportInfo(
4801                         LteVopsSupportInfo.LTE_STATUS_SUPPORTED,
4802                         LteVopsSupportInfo.LTE_STATUS_SUPPORTED))
4803                 .build();
4804         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
4805                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, dsri);
4806 
4807         mDataNetworkControllerUT.addNetworkRequest(
4808                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS,
4809                         NetworkCapabilities.NET_CAPABILITY_MMTEL));
4810         processAllMessages();
4811         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS);
4812 
4813         doReturn(PhoneConstants.State.OFFHOOK).when(mCT).getState();
4814 
4815         dsri = new DataSpecificRegistrationInfo.Builder(8)
4816                 .setNrAvailable(true)
4817                 .setEnDcAvailable(true)
4818                 .setVopsSupportInfo(new LteVopsSupportInfo(
4819                         LteVopsSupportInfo.LTE_STATUS_NOT_SUPPORTED,
4820                         LteVopsSupportInfo.LTE_STATUS_NOT_SUPPORTED))
4821                 .build();
4822         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
4823                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, dsri);
4824 
4825         // Make sure IMS is still connected.
4826         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
4827                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
4828 
4829         // Call ends
4830         doReturn(PhoneConstants.State.IDLE).when(mCT).getState();
4831         mDataNetworkControllerUT.obtainMessage(EVENT_VOICE_CALL_ENDED).sendToTarget();
4832         processAllMessages();
4833 
4834         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_IMS);
4835     }
4836 
4837     @Test
testDeactivateDataOnOldHal()4838     public void testDeactivateDataOnOldHal() throws Exception {
4839         doAnswer(invocation -> {
4840             // Only send the deactivation data response, no data call list changed event.
4841             Message msg = (Message) invocation.getArguments()[2];
4842             msg.sendToTarget();
4843             return null;
4844         }).when(mMockedWwanDataServiceManager).deactivateDataCall(
4845                 anyInt(), anyInt(), any(Message.class));
4846         // Simulate old devices
4847         doReturn(RIL.RADIO_HAL_VERSION_1_6).when(mPhone).getHalVersion(HAL_SERVICE_DATA);
4848 
4849         testSetupDataNetwork();
4850 
4851         mDataNetworkControllerUT.obtainMessage(EVENT_SIM_STATE_CHANGED,
4852                 TelephonyManager.SIM_STATE_ABSENT, 0).sendToTarget();
4853         processAllMessages();
4854         verifyAllDataDisconnected();
4855         verify(mMockedDataNetworkControllerCallback).onAnyDataNetworkExistingChanged(eq(false));
4856         verify(mMockedDataNetworkControllerCallback).onConnectedInternetDataNetworksChanged(
4857                 eq(Collections.emptySet()));
4858         verify(mMockedDataNetworkControllerCallback).onPhysicalLinkStatusChanged(
4859                 eq(DataCallResponse.LINK_STATUS_INACTIVE));
4860     }
4861 
4862     @Test
testHandoverWhileSetupDataCallInProgress()4863     public void testHandoverWhileSetupDataCallInProgress() throws Exception {
4864         // Long delay setup failure
4865         setFailedSetupDataResponse(mMockedWwanDataServiceManager, DataFailCause.CONGESTION,
4866                 DataCallResponse.RETRY_DURATION_UNDEFINED, false, 10000);
4867 
4868         mDataNetworkControllerUT.addNetworkRequest(
4869                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS,
4870                         NetworkCapabilities.NET_CAPABILITY_MMTEL));
4871         processAllMessages();
4872 
4873         // Change the preference to IWLAN while setup data is still ongoing.
4874         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
4875                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
4876 
4877         // Data should not be connected.
4878         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_IMS);
4879 
4880         // There shouldn't be any attempt to bring up IMS on IWLAN even though the preference
4881         // has already changed, because the previous setup is still ongoing.
4882         verify(mMockedWlanDataServiceManager, never()).setupDataCall(eq(AccessNetworkType.IWLAN),
4883                 any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(),
4884                 any(), any(), anyBoolean(), any(Message.class));
4885 
4886         processAllFutureMessages();
4887 
4888         // Should setup a new one instead of handover.
4889         verify(mMockedWlanDataServiceManager).setupDataCall(eq(AccessNetworkType.IWLAN),
4890                 any(DataProfile.class), anyBoolean(), anyBoolean(),
4891                 eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), any(), anyBoolean(),
4892                 any(Message.class));
4893 
4894         // IMS should be connected.
4895         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS,
4896                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
4897     }
4898 
4899     @Test
testRemoveNetworkRequest()4900     public void testRemoveNetworkRequest() throws Exception {
4901         NetworkCapabilities netCaps = new NetworkCapabilities();
4902         netCaps.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
4903 
4904         NetworkRequest nativeNetworkRequest = new NetworkRequest(netCaps,
4905                 ConnectivityManager.TYPE_MOBILE, 0, NetworkRequest.Type.REQUEST);
4906 
4907         mDataNetworkControllerUT.addNetworkRequest(new TelephonyNetworkRequest(
4908                 nativeNetworkRequest, mPhone, mFeatureFlags));
4909         processAllMessages();
4910 
4911         // Intentionally create a new telephony request with the original native network request.
4912         TelephonyNetworkRequest request = new TelephonyNetworkRequest(
4913                 nativeNetworkRequest, mPhone, mFeatureFlags);
4914 
4915         mDataNetworkControllerUT.removeNetworkRequest(request);
4916         processAllFutureMessages();
4917 
4918         List<DataNetwork> dataNetworkList = getDataNetworks();
4919         // The data network should not be torn down after network request removal.
4920         assertThat(dataNetworkList).hasSize(1);
4921         // But should be detached from the data network.
4922         assertThat(dataNetworkList.get(0).getAttachedNetworkRequestList()).isEmpty();
4923         assertThat(dataNetworkList.get(0).isConnected()).isTrue();
4924     }
4925 
4926     @Test
testTempDdsSwitchTearDown()4927     public void testTempDdsSwitchTearDown() throws Exception {
4928         TelephonyNetworkRequest request = createNetworkRequest(
4929                 NetworkCapabilities.NET_CAPABILITY_INTERNET);
4930         mDataNetworkControllerUT.addNetworkRequest(request);
4931         processAllMessages();
4932 
4933         // this slot is 0, modem preferred on slot 1
4934         doReturn(1).when(mMockedPhoneSwitcher).getPreferredDataPhoneId();
4935 
4936         // Simulate telephony network factory remove request due to switch.
4937         mDataNetworkControllerUT.removeNetworkRequest(request);
4938         processAllMessages();
4939 
4940         // Data should be torn down on this non-preferred sub.
4941         verifyAllDataDisconnected();
4942     }
4943 
4944     @Test
testSetupDataOnNonDds()4945     public void testSetupDataOnNonDds() throws Exception {
4946         // this slot is 0, modem preferred on slot 1
4947         doReturn(1).when(mMockedPhoneSwitcher).getPreferredDataPhoneId();
4948         TelephonyNetworkRequest request = createNetworkRequest(
4949                 NetworkCapabilities.NET_CAPABILITY_MMS);
4950 
4951         // Test Don't allow setup if both data and voice OOS
4952         serviceStateChanged(TelephonyManager.NETWORK_TYPE_1xRTT,
4953                 // data, voice, Iwlan reg state
4954                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING,
4955                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING,
4956                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING, null);
4957         mDataNetworkControllerUT.addNetworkRequest(request);
4958         processAllMessages();
4959 
4960         verifyAllDataDisconnected();
4961 
4962         // Test Don't allow setup if CS is in service, but current RAT is already PS(e.g. LTE)
4963         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
4964                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING,
4965                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME,
4966                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING, null);
4967 
4968         verifyAllDataDisconnected();
4969 
4970         // Test Allow if voice is in service if RAT is 2g/3g, use voice RAT to select data profile
4971         ServiceState ss = createSS(TelephonyManager.NETWORK_TYPE_UNKNOWN /* data RAT */,
4972                 TelephonyManager.NETWORK_TYPE_1xRTT /* voice RAT */,
4973                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING ,
4974                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME,
4975                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING, null, true);
4976         doReturn(ss).when(mSST).getServiceState();
4977         mDataNetworkControllerUT.obtainMessage(EVENT_SERVICE_STATE_CHANGED).sendToTarget();
4978         mDataNetworkControllerUT.removeNetworkRequest(request);
4979         mDataNetworkControllerUT.addNetworkRequest(request);
4980         processAllMessages();
4981 
4982         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_MMS);
4983     }
4984 
4985     @Test
testTrafficDescriptionChangedDataRetry()4986     public void testTrafficDescriptionChangedDataRetry() throws Exception {
4987         List<TrafficDescriptor> tdList = List.of(
4988                 new TrafficDescriptor.Builder()
4989                         .setOsAppId(new OsAppId(OsAppId.ANDROID_OS_ID, "PRIORITIZE_LATENCY", 1)
4990                                 .getBytes()).build(),
4991                 new TrafficDescriptor.Builder()
4992                         .setOsAppId(new OsAppId(OsAppId.ANDROID_OS_ID, "ENTERPRISE", 1).getBytes())
4993                         .build()
4994                 );
4995         setSuccessfulSetupDataResponse(mMockedWwanDataServiceManager,
4996                 createDataCallResponse(1, DataCallResponse.LINK_STATUS_ACTIVE, tdList));
4997         doReturn(mEnterpriseDataProfile).when(mDataProfileManager)
4998                 .getDataProfileForNetworkRequest(any(TelephonyNetworkRequest.class), anyInt(),
4999                         anyBoolean(), anyBoolean(), anyBoolean());
5000         mDataNetworkControllerUT.addNetworkRequest(new TelephonyNetworkRequest(
5001                 new NetworkRequest.Builder()
5002                         .addCapability(NetworkCapabilities.NET_CAPABILITY_ENTERPRISE)
5003                         .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
5004                         .build(), mPhone, mFeatureFlags));
5005         processAllMessages();
5006         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_ENTERPRISE,
5007                 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
5008 
5009         mDataNetworkControllerUT.addNetworkRequest(new TelephonyNetworkRequest(
5010                 new NetworkRequest.Builder()
5011                         .addCapability(NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY)
5012                         .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
5013                         .build(), mPhone, mFeatureFlags));
5014         processAllMessages();
5015         List<DataNetwork> dataNetworkList = getDataNetworks();
5016         assertThat(dataNetworkList).hasSize(1);
5017 
5018         // Now remove low latency TD from the data call response.
5019         logd("Now remove PRIORITIZE_LATENCY");
5020         tdList = List.of(new TrafficDescriptor.Builder()
5021                 .setOsAppId(new OsAppId(OsAppId.ANDROID_OS_ID, "ENTERPRISE", 1).getBytes())
5022                 .build());
5023         mDataCallResponses.get(AccessNetworkConstants.TRANSPORT_TYPE_WWAN).put(1,
5024                 createDataCallResponse(1, DataCallResponse.LINK_STATUS_ACTIVE, tdList));
5025         mDataCallListChangedRegistrants.get(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
5026                 .notifyRegistrants(new AsyncResult(AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
5027                         List.of(createDataCallResponse(1, DataCallResponse.LINK_STATUS_ACTIVE,
5028                                 tdList)), null));
5029 
5030         tdList = List.of(new TrafficDescriptor.Builder()
5031                 .setOsAppId(new OsAppId(OsAppId.ANDROID_OS_ID, "PRIORITIZE_LATENCY", 1).getBytes())
5032                 .build());
5033         setSuccessfulSetupDataResponse(mMockedWwanDataServiceManager,
5034                 createDataCallResponse(2, DataCallResponse.LINK_STATUS_ACTIVE, tdList));
5035         doReturn(mLowLatencyDataProfile).when(mDataProfileManager)
5036                 .getDataProfileForNetworkRequest(any(TelephonyNetworkRequest.class), anyInt(),
5037                         anyBoolean(), anyBoolean(), anyBoolean());
5038         processAllFutureMessages();
5039 
5040         dataNetworkList = getDataNetworks();
5041         assertThat(dataNetworkList).hasSize(2);
5042 
5043         assertThat(dataNetworkList.get(0).getNetworkCapabilities().hasCapability(
5044                 NetworkCapabilities.NET_CAPABILITY_ENTERPRISE)).isTrue();
5045         assertThat(dataNetworkList.get(0).getNetworkCapabilities().hasCapability(
5046                 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY)).isFalse();
5047         assertThat(dataNetworkList.get(1).getNetworkCapabilities().hasCapability(
5048                 NetworkCapabilities.NET_CAPABILITY_ENTERPRISE)).isFalse();
5049         assertThat(dataNetworkList.get(1).getNetworkCapabilities().hasCapability(
5050                 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY)).isTrue();
5051     }
5052 
5053     @Test
testNonTerrestrialNetwork()5054     public void testNonTerrestrialNetwork() throws Exception {
5055         TelephonyNetworkRequest request;
5056         mIsNonTerrestrialNetwork = true;
5057         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
5058                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
5059         // By default, Test only support restricted network, regardless whether constrained.
5060         // Verify not_restricted network not supported.
5061         request = createNetworkRequest(false, NetworkCapabilities.NET_CAPABILITY_RCS);
5062         mDataNetworkControllerUT.addNetworkRequest(request);
5063         processAllMessages();
5064         verifyAllDataDisconnected();
5065         mDataNetworkControllerUT.removeNetworkRequest(request);
5066 
5067         // Verify restricted network is supported.
5068         request = createNetworkRequest(true, NetworkCapabilities.NET_CAPABILITY_RCS);
5069         mDataNetworkControllerUT.addNetworkRequest(request);
5070         processAllMessages();
5071         verifyConnectedNetworkHasDataProfile(mNtnDataProfile);
5072         mDataNetworkControllerUT.removeNetworkRequest(request);
5073         getDataNetworks().get(0).tearDown(DataNetwork
5074                 .TEAR_DOWN_REASON_CONNECTIVITY_SERVICE_UNWANTED);
5075 
5076         // Test constrained network is supported, regardless whether it's restricted
5077         processAllFutureMessages();
5078         verifyAllDataDisconnected();
5079         mCarrierConfig.putInt(CarrierConfigManager.KEY_SATELLITE_DATA_SUPPORT_MODE_INT,
5080                 CarrierConfigManager.SATELLITE_DATA_SUPPORT_BANDWIDTH_CONSTRAINED);
5081         carrierConfigChanged();
5082         // Verify not_restricted, not_constrained network not supported.
5083         NetworkCapabilities netCaps = new NetworkCapabilities();
5084         netCaps.addCapability(NetworkCapabilities.NET_CAPABILITY_RCS);
5085         try {
5086             netCaps.addCapability(DataUtils.NET_CAPABILITY_NOT_BANDWIDTH_CONSTRAINED);
5087         } catch (Exception ignored) { }
5088         request = new TelephonyNetworkRequest(new NetworkRequest(netCaps,
5089                 ConnectivityManager.TYPE_MOBILE, ++mNetworkRequestId,
5090                 NetworkRequest.Type.REQUEST), mPhone, mFeatureFlags);
5091 
5092         mDataNetworkControllerUT.addNetworkRequest(request);
5093         processAllMessages();
5094         verifyAllDataDisconnected();
5095         mDataNetworkControllerUT.removeNetworkRequest(request);
5096 
5097         // Verify restricted, not_constrained network is supported.
5098         netCaps = new NetworkCapabilities();
5099         netCaps.addCapability(NetworkCapabilities.NET_CAPABILITY_RCS);
5100         netCaps.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
5101         try {
5102             netCaps.addCapability(DataUtils.NET_CAPABILITY_NOT_BANDWIDTH_CONSTRAINED);
5103         } catch (Exception ignored) { }
5104         request = new TelephonyNetworkRequest(new NetworkRequest(netCaps,
5105                 ConnectivityManager.TYPE_MOBILE, ++mNetworkRequestId,
5106                 NetworkRequest.Type.REQUEST), mPhone, mFeatureFlags);
5107         mDataNetworkControllerUT.addNetworkRequest(request);
5108         processAllMessages();
5109         verifyConnectedNetworkHasDataProfile(mNtnDataProfile);
5110         mDataNetworkControllerUT.removeNetworkRequest(request);
5111         getDataNetworks().get(0).tearDown(DataNetwork
5112                 .TEAR_DOWN_REASON_CONNECTIVITY_SERVICE_UNWANTED);
5113 
5114         // TODO(enable after NET_CAPABILITY_NOT_BANDWIDTH_CONSTRAINED become a default cap)
5115         // Test not constrained network supported
5116 //        processAllFutureMessages();
5117 //        verifyAllDataDisconnected();
5118 //        mCarrierConfig.putInt(CarrierConfigManager.KEY_SATELLITE_DATA_SUPPORT_MODE_INT,
5119 //                CarrierConfigManager.SATELLITE_DATA_SUPPORT_ALL);
5120 //        carrierConfigChanged();
5121 //
5122 //        netCaps = new NetworkCapabilities();
5123 //        netCaps.addCapability(NetworkCapabilities.NET_CAPABILITY_RCS);
5124 //        try {
5125 //            netCaps.addCapability(DataUtils.NET_CAPABILITY_NOT_BANDWIDTH_CONSTRAINED);
5126 //        } catch (Exception ignored) {}
5127 //        mDataNetworkControllerUT.addNetworkRequest(
5128 //                new TelephonyNetworkRequest(new NetworkRequest(netCaps,
5129 //                        ConnectivityManager.TYPE_MOBILE, ++mNetworkRequestId,
5130 //                        NetworkRequest.Type.REQUEST), mPhone, mFeatureFlags));
5131 //        processAllMessages();
5132 //        verifyConnectedNetworkHasDataProfile(mNtnDataProfile);
5133     }
5134 
5135     @Test
testIsEsimBootStrapProvisioningActivatedWithFlagEnabledAndProvisioningClass()5136     public void testIsEsimBootStrapProvisioningActivatedWithFlagEnabledAndProvisioningClass() {
5137         when(mFeatureFlags.esimBootstrapProvisioningFlag()).thenReturn(true);
5138         doReturn(new SubscriptionInfoInternal.Builder().setId(1)
5139                 .setProfileClass(SubscriptionManager.PROFILE_CLASS_PROVISIONING).build())
5140                 .when(mSubscriptionManagerService).getSubscriptionInfoInternal(anyInt());
5141 
5142         assertThat(mDataNetworkControllerUT.isEsimBootStrapProvisioningActivated()).isTrue();
5143     }
5144 
5145     @Test
testIsEsimBootStrapProvisioningActivatedWithFlagEnabledAndNoProvisioningClass()5146     public void testIsEsimBootStrapProvisioningActivatedWithFlagEnabledAndNoProvisioningClass() {
5147         when(mFeatureFlags.esimBootstrapProvisioningFlag()).thenReturn(true);
5148         doReturn(new SubscriptionInfoInternal.Builder().setId(1)
5149                 .setProfileClass(SubscriptionManager.PROFILE_CLASS_UNSET).build())
5150                 .when(mSubscriptionManagerService).getSubscriptionInfoInternal(anyInt());
5151 
5152         assertThat(mDataNetworkControllerUT.isEsimBootStrapProvisioningActivated()).isFalse();
5153     }
5154 
5155     @Test
testIsEsimBootStrapProvisioningActivatedWithFlagDisabledAndNoProvisioningClass()5156     public void testIsEsimBootStrapProvisioningActivatedWithFlagDisabledAndNoProvisioningClass() {
5157         when(mFeatureFlags.esimBootstrapProvisioningFlag()).thenReturn(false);
5158         doReturn(new SubscriptionInfoInternal.Builder().setId(1)
5159                 .setProfileClass(SubscriptionManager.PROFILE_CLASS_UNSET).build())
5160                 .when(mSubscriptionManagerService).getSubscriptionInfoInternal(anyInt());
5161 
5162         assertThat(mDataNetworkControllerUT.isEsimBootStrapProvisioningActivated()).isFalse();
5163     }
5164 
5165     @Test
testIsEsimBootStrapProvisioningActivatedWithFlagDisabledAndProvisioningClass()5166     public void testIsEsimBootStrapProvisioningActivatedWithFlagDisabledAndProvisioningClass() {
5167         when(mFeatureFlags.esimBootstrapProvisioningFlag()).thenReturn(false);
5168         doReturn(new SubscriptionInfoInternal.Builder().setId(1)
5169                 .setProfileClass(SubscriptionManager.PROFILE_CLASS_PROVISIONING).build())
5170                 .when(mSubscriptionManagerService).getSubscriptionInfoInternal(anyInt());
5171 
5172         assertThat(mDataNetworkControllerUT.isEsimBootStrapProvisioningActivated()).isFalse();
5173     }
5174 
5175     @Test
testNetworkOnProvisioningProfileClass_WithFlagEnabled()5176     public void testNetworkOnProvisioningProfileClass_WithFlagEnabled() throws Exception {
5177         when(mFeatureFlags.esimBootstrapProvisioningFlag()).thenReturn(true);
5178         // Allowed data limit Unlimited
5179         mContextFixture.putIntResource(com.android.internal.R.integer
5180                 .config_esim_bootstrap_data_limit_bytes, -1);
5181         doReturn(new SubscriptionInfoInternal.Builder().setId(1)
5182                 .setProfileClass(SubscriptionManager.PROFILE_CLASS_PROVISIONING).build())
5183                 .when(mSubscriptionManagerService).getSubscriptionInfoInternal(anyInt());
5184         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
5185                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
5186         mDataNetworkControllerUT.addNetworkRequest(
5187                 createNetworkRequest(true/*restricted*/,
5188                         NetworkCapabilities.NET_CAPABILITY_INTERNET));
5189         processAllMessages();
5190         verifyConnectedNetworkHasDataProfile(mEsimBootstrapDataProfile);
5191 
5192         mDataNetworkControllerUT.addNetworkRequest(
5193                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS,
5194                         NetworkCapabilities.NET_CAPABILITY_MMTEL));
5195         setSuccessfulSetupDataResponse(mMockedDataServiceManagers
5196                 .get(AccessNetworkConstants.TRANSPORT_TYPE_WWAN), 2);
5197         processAllMessages();
5198         verifyConnectedNetworkHasDataProfile(mEsimBootstrapImsProfile);
5199     }
5200 
5201     @Test
testSetUpPdn_WithBootStrapDataLimit_Zero()5202     public void testSetUpPdn_WithBootStrapDataLimit_Zero() throws Exception {
5203         when(mFeatureFlags.esimBootstrapProvisioningFlag()).thenReturn(true);
5204         // Allowed data limit set as zero
5205         doReturn(new SubscriptionInfoInternal.Builder().setId(1)
5206                 .setProfileClass(SubscriptionManager.PROFILE_CLASS_PROVISIONING).build())
5207                 .when(mSubscriptionManagerService).getSubscriptionInfoInternal(anyInt());
5208         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
5209                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
5210         mDataNetworkControllerUT.addNetworkRequest(
5211                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
5212         processAllMessages();
5213         // With current consumed bytes is zero, same as allowed limit, data_limit_reached
5214         // disallowed reason is met
5215         verifyConnectedNetworkHasNoDataProfile(mEsimBootstrapDataProfile);
5216 
5217         mDataNetworkControllerUT.addNetworkRequest(
5218                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS,
5219                         NetworkCapabilities.NET_CAPABILITY_MMTEL));
5220         processAllMessages();
5221         // New network request also meets with data limit reached disallowed reason
5222         verifyConnectedNetworkHasNoDataProfile(mEsimBootstrapImsProfile);
5223     }
5224 
5225     @Test
testSetUpPdn_WithBootStrapDataLimit_Unlimited()5226     public void testSetUpPdn_WithBootStrapDataLimit_Unlimited() throws Exception {
5227         when(mFeatureFlags.esimBootstrapProvisioningFlag()).thenReturn(true);
5228         // Allowed data limit
5229         mContextFixture.putIntResource(com.android.internal.R.integer
5230                  .config_esim_bootstrap_data_limit_bytes, -1/*unlimited*/);
5231         doReturn(new SubscriptionInfoInternal.Builder().setId(1)
5232                 .setProfileClass(SubscriptionManager.PROFILE_CLASS_PROVISIONING).build())
5233                 .when(mSubscriptionManagerService).getSubscriptionInfoInternal(anyInt());
5234         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
5235                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
5236         mDataNetworkControllerUT.addNetworkRequest(
5237                 createNetworkRequest(true, NetworkCapabilities.NET_CAPABILITY_INTERNET));
5238         processAllMessages();
5239         // With allowed data limit unlimited, connection is allowed
5240         verifyConnectedNetworkHasDataProfile(mEsimBootstrapDataProfile);
5241 
5242         mDataNetworkControllerUT.addNetworkRequest(
5243                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS,
5244                         NetworkCapabilities.NET_CAPABILITY_MMTEL));
5245         setSuccessfulSetupDataResponse(mMockedDataServiceManagers
5246                 .get(AccessNetworkConstants.TRANSPORT_TYPE_WWAN), 2);
5247         processAllMessages();
5248         // With allowed data limit unlimited, connection is allowed
5249         verifyConnectedNetworkHasDataProfile(mEsimBootstrapImsProfile);
5250 
5251         // Both internet and IMS should be retained after network re-evaluation
5252         mDataNetworkControllerUT.obtainMessage(16 /*EVENT_REEVALUATE_EXISTING_DATA_NETWORKS*/,
5253                 DataEvaluation.DataEvaluationReason.CHECK_DATA_USAGE).sendToTarget();
5254         processAllMessages();
5255         // With allowed data limit unlimited, connection is allowed
5256         verifyConnectedNetworkHasDataProfile(mEsimBootstrapDataProfile);
5257         verifyConnectedNetworkHasDataProfile(mEsimBootstrapImsProfile);
5258     }
5259 
5260     @Test
testNetworkOnNonProvisioningProfileClass_WithFlagEnabled()5261     public void testNetworkOnNonProvisioningProfileClass_WithFlagEnabled() throws Exception {
5262         when(mFeatureFlags.esimBootstrapProvisioningFlag()).thenReturn(true);
5263         doReturn(new SubscriptionInfoInternal.Builder().setId(1)
5264                 .setProfileClass(SubscriptionManager.PROFILE_CLASS_UNSET).build())
5265                 .when(mSubscriptionManagerService).getSubscriptionInfoInternal(anyInt());
5266         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
5267                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
5268         mDataNetworkControllerUT.addNetworkRequest(
5269                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
5270         processAllMessages();
5271         verifyConnectedNetworkHasNoDataProfile(mEsimBootstrapDataProfile);
5272 
5273         mDataNetworkControllerUT.addNetworkRequest(
5274                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS,
5275                         NetworkCapabilities.NET_CAPABILITY_MMTEL));
5276         setSuccessfulSetupDataResponse(mMockedDataServiceManagers
5277                 .get(AccessNetworkConstants.TRANSPORT_TYPE_WWAN), 2);
5278         processAllMessages();
5279         verifyConnectedNetworkHasNoDataProfile(mEsimBootstrapImsProfile);
5280     }
5281 
5282     @Test
testNtnNetworkOnProvisioningProfileClassWithFlagEnabled()5283     public void testNtnNetworkOnProvisioningProfileClassWithFlagEnabled() throws Exception {
5284         when(mFeatureFlags.esimBootstrapProvisioningFlag()).thenReturn(true);
5285         // Allowed data limit Unlimited
5286         mContextFixture.putIntResource(com.android.internal.R.integer
5287                 .config_esim_bootstrap_data_limit_bytes, -1);
5288         doReturn(new SubscriptionInfoInternal.Builder().setId(1)
5289                 .setProfileClass(SubscriptionManager.PROFILE_CLASS_PROVISIONING).build())
5290                 .when(mSubscriptionManagerService).getSubscriptionInfoInternal(anyInt());
5291         mIsNonTerrestrialNetwork = true;
5292         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
5293                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
5294         mDataNetworkControllerUT.addNetworkRequest(
5295                 createNetworkRequest(true, NetworkCapabilities.NET_CAPABILITY_RCS));
5296         processAllMessages();
5297 
5298         assertThat(mDataNetworkControllerUT.isEsimBootStrapProvisioningActivated()).isTrue();
5299         verifyConnectedNetworkHasNoDataProfile(mNtnDataProfile);
5300         verifyConnectedNetworkHasDataProfile(mEsimBootstrapRcsInfraStructureProfile);
5301     }
5302 
5303     @Test
testNonNtnNetworkOnProvisioningProfileClassWithFlagEnabled()5304     public void testNonNtnNetworkOnProvisioningProfileClassWithFlagEnabled() throws Exception {
5305         when(mFeatureFlags.esimBootstrapProvisioningFlag()).thenReturn(true);
5306         doReturn(new SubscriptionInfoInternal.Builder().setId(1)
5307                 .setProfileClass(SubscriptionManager.PROFILE_CLASS_PROVISIONING).build())
5308                 .when(mSubscriptionManagerService).getSubscriptionInfoInternal(anyInt());
5309         serviceStateChanged(TelephonyManager.NETWORK_TYPE_LTE,
5310                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
5311         mDataNetworkControllerUT.addNetworkRequest(
5312                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_RCS));
5313         processAllMessages();
5314 
5315         assertThat(mDataNetworkControllerUT.isEsimBootStrapProvisioningActivated()).isTrue();
5316         verifyConnectedNetworkHasNoDataProfile(mNtnDataProfile);
5317         verifyConnectedNetworkHasNoDataProfile(mEsimBootstrapRcsInfraStructureProfile);
5318     }
5319 
5320     @Test
testRequestNetworkValidationWithConnectedNetwork()5321     public void testRequestNetworkValidationWithConnectedNetwork() throws Exception {
5322         // IMS preferred on IWLAN.
5323         doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WLAN).when(mAccessNetworksManager)
5324                 .getPreferredTransportByNetworkCapability(
5325                         eq(NetworkCapabilities.NET_CAPABILITY_IMS));
5326 
5327         // Request IMS
5328         mDataNetworkControllerUT.addNetworkRequest(
5329                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_IMS,
5330                         NetworkCapabilities.NET_CAPABILITY_MMTEL));
5331         setSuccessfulSetupDataResponse(mMockedDataServiceManagers
5332                 .get(AccessNetworkConstants.TRANSPORT_TYPE_WLAN), 3);
5333         processAllMessages();
5334 
5335         // Make sure IMS on IWLAN.
5336         verifyConnectedNetworkHasCapabilities(NetworkCapabilities.NET_CAPABILITY_IMS);
5337         DataNetwork dataNetwork = getDataNetworks().get(0);
5338         assertThat(dataNetwork.getTransport()).isEqualTo(
5339                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
5340 
5341         mDataNetworkControllerUT.requestNetworkValidation(NetworkCapabilities.NET_CAPABILITY_IMS,
5342                 mIntegerConsumer);
5343         processAllMessages();
5344         assertThat(waitForIntegerConsumerResponse(1 /*numOfEvents*/)).isFalse();
5345     }
5346 
5347     @Test
testRequestNetworkValidationWithNoConnectedNetwork()5348     public void testRequestNetworkValidationWithNoConnectedNetwork()
5349             throws Exception {
5350         // IMS preferred on IWLAN.
5351         doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WLAN).when(mAccessNetworksManager)
5352                 .getPreferredTransportByNetworkCapability(
5353                         eq(NetworkCapabilities.NET_CAPABILITY_IMS));
5354 
5355         // IMS On Wlan not connected
5356         verifyNoConnectedNetworkHasCapability(NetworkCapabilities.NET_CAPABILITY_IMS);
5357 
5358         //Connected List is Empty
5359         mDataNetworkControllerUT.requestNetworkValidation(NetworkCapabilities.NET_CAPABILITY_IMS,
5360                 mIntegerConsumer);
5361         processAllMessages();
5362         assertThat(waitForIntegerConsumerResponse(1 /*numOfEvents*/)).isTrue();
5363         assertThat(mIntegerConsumerResult).isEqualTo(DataServiceCallback.RESULT_ERROR_INVALID_ARG);
5364     }
5365 
5366     @Test
testRequestNetworkValidationWithInvalidArg()5367     public void testRequestNetworkValidationWithInvalidArg() {
5368         mDataNetworkControllerUT.requestNetworkValidation(
5369                 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY,
5370                 mIntegerConsumer);
5371         processAllMessages();
5372         assertThat(waitForIntegerConsumerResponse(1 /*numOfEvents*/)).isTrue();
5373         assertThat(mIntegerConsumerResult).isEqualTo(DataServiceCallback.RESULT_ERROR_INVALID_ARG);
5374     }
5375 
5376     @Test
testForceReconnectToPreferredTransportType()5377     public void testForceReconnectToPreferredTransportType() throws Exception {
5378         testSetupImsDataNetwork();
5379         reconnectTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
5380                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
5381 
5382         // Verify IMS network was torn down on source first.
5383         verify(mMockedWwanDataServiceManager).deactivateDataCall(anyInt(),
5384                 eq(DataService.REQUEST_REASON_NORMAL), any(Message.class));
5385 
5386         // Verify that IWLAN is brought up again on IWLAN.
5387         verify(mMockedWlanDataServiceManager).setupDataCall(anyInt(),
5388                 any(DataProfile.class), anyBoolean(), anyBoolean(),
5389                 eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), any(), anyBoolean(),
5390                 any(Message.class));
5391 
5392         DataNetwork dataNetwork = getDataNetworks().get(0);
5393         assertThat(dataNetwork.getTransport()).isEqualTo(
5394                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
5395     }
5396 
5397     @Test
testForceReconnectIgnored()5398     public void testForceReconnectIgnored() throws Exception {
5399         mCarrierConfig.putStringArray(
5400                 CarrierConfigManager.KEY_IWLAN_HANDOVER_POLICY_STRING_ARRAY,
5401                 new String[]{
5402                         "source=EUTRAN|NGRAN|IWLAN|UNKNOWN, target=EUTRAN|NGRAN|IWLAN, "
5403                                 + "type=allowed, capabilities=IMS"
5404                 });
5405         carrierConfigChanged();
5406 
5407         testSetupImsDataNetwork();
5408         reconnectTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
5409                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
5410 
5411         // request reconnection to current transport type, tear down should not happen.
5412         verify(mMockedWwanDataServiceManager, never()).deactivateDataCall(anyInt(),
5413                 eq(DataService.REQUEST_REASON_NORMAL), any(Message.class));
5414 
5415         Mockito.reset(mMockedWlanDataServiceManager);
5416 
5417         // Trigger Handover to IWLAN.
5418         updateTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
5419                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
5420 
5421         // Capture the message for setup data call response. We want to delay it.
5422         ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
5423         verify(mMockedWlanDataServiceManager).setupDataCall(anyInt(), any(DataProfile.class),
5424                 anyBoolean(), anyBoolean(), anyInt(), any(), anyInt(), any(), any(), anyBoolean(),
5425                 messageCaptor.capture());
5426 
5427         // Force reconnect to preferred transport type while handover is in progress.
5428         reconnectTransport(NetworkCapabilities.NET_CAPABILITY_IMS,
5429                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
5430 
5431         // Finally handover is completed.
5432         Message msg = messageCaptor.getValue();
5433         DataCallResponse response = new DataCallResponse.Builder()
5434                 .setCause(DataFailCause.NONE)
5435                 .build();
5436         msg.getData().putParcelable("data_call_response", response);
5437         msg.arg1 = DataServiceCallback.RESULT_SUCCESS;
5438         msg.sendToTarget();
5439         processAllMessages();
5440 
5441         verify(mMockedWwanDataServiceManager, never()).deactivateDataCall(anyInt(),
5442                 eq(DataService.REQUEST_REASON_NORMAL), any(Message.class));
5443     }
5444 
5445     @Test
testRadioOffTearDown()5446     public void testRadioOffTearDown() throws Exception  {
5447         testSetupDataNetwork();
5448         doReturn(true).when(mSST).isPendingRadioPowerOffAfterDataOff();
5449         mDataNetworkControllerUT.tearDownAllDataNetworks(
5450                 DataNetwork.TEAR_DOWN_REASON_AIRPLANE_MODE_ON);
5451         processAllMessages();
5452         verifyAllDataDisconnected();
5453         verify(mMockedDataNetworkControllerCallback).onAnyDataNetworkExistingChanged(eq(false));
5454 
5455         clearInvocations(mMockedDataNetworkControllerCallback);
5456         mDataNetworkControllerUT.addNetworkRequest(
5457                 createNetworkRequest(NetworkCapabilities.NET_CAPABILITY_INTERNET));
5458         processAllMessages();
5459         verifyAllDataDisconnected();
5460         verify(mMockedDataNetworkControllerCallback, never()).onAnyDataNetworkExistingChanged(
5461                 anyBoolean());
5462     }
5463 
5464     @Test
testGetInternetEvaluation()5465     public void testGetInternetEvaluation() throws Exception {
5466         testSetupDataNetwork();
5467         doReturn(true).when(mSST).isPendingRadioPowerOffAfterDataOff();
5468         assertThat(mDataNetworkControllerUT.getInternetEvaluation(false/*ignoreExistingNetworks*/)
5469                 .containsDisallowedReasons()).isFalse();
5470         assertThat(mDataNetworkControllerUT.getInternetEvaluation(true/*ignoreExistingNetworks*/)
5471                 .containsDisallowedReasons()).isTrue();
5472     }
5473 }
5474