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