aboutsummaryrefslogtreecommitdiff
path: root/tests/telephonytests
diff options
context:
space:
mode:
Diffstat (limited to 'tests/telephonytests')
-rw-r--r--tests/telephonytests/Android.bp13
-rw-r--r--tests/telephonytests/AndroidManifest.xml21
-rw-r--r--tests/telephonytests/AndroidTest.xml2
-rw-r--r--tests/telephonytests/assets/eccdatabin51 -> 51 bytes
-rw-r--r--tests/telephonytests/assets/eccdata_input.txt15
-rw-r--r--tests/telephonytests/assets/eccdata_otabin49 -> 0 bytes
-rw-r--r--tests/telephonytests/assets/eccdata_ota_input.txt11
-rw-r--r--tests/telephonytests/jarjar-rules-tests.txt6
-rw-r--r--tests/telephonytests/src/android/telephony/BinderCacheManagerTest.java123
-rw-r--r--tests/telephonytests/src/android/telephony/SmsMessageTest.java1
-rw-r--r--tests/telephonytests/src/android/telephony/ims/ImsCallSessionListenerTests.java56
-rw-r--r--tests/telephonytests/src/android/telephony/ims/ImsConfigImplTest.java166
-rw-r--r--tests/telephonytests/src/android/telephony/ims/ImsFeatureTest.java2
-rw-r--r--tests/telephonytests/src/android/telephony/ims/ImsMmTelManagerTests.java34
-rw-r--r--tests/telephonytests/src/android/telephony/ims/ImsRegistrationTests.java66
-rw-r--r--tests/telephonytests/src/android/telephony/ims/ImsServiceTest.java34
-rw-r--r--tests/telephonytests/src/android/telephony/ims/MmTelFeatureTests.java20
-rw-r--r--tests/telephonytests/src/android/telephony/ims/RcsConfigTest.java303
-rw-r--r--tests/telephonytests/src/android/telephony/ims/SipTransportImplBaseTest.java171
-rw-r--r--tests/telephonytests/src/android/telephony/ims/TestImsService.java7
-rw-r--r--tests/telephonytests/src/android/telephony/ims/TestMmTelFeature.java11
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/AdnRecordTest.java24
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/BarringInfoTest.java4
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/CarrierDisplayNameResolverTest.java95
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/CarrierKeyDownloadMgrTest.java93
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/CarrierPrivilegesTrackerTest.java138
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/CarrierResolverTest.java4
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/CarrierServiceStateTrackerTest.java32
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/CarrierSignalAgentTest.java211
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/CellIdentityLteTest.java14
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/CellSignalStrengthNrTest.java132
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/CellularNetworkServiceTest.java277
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/CellularNetworkValidatorTest.java4
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/ContextFixture.java73
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/DefaultPhoneNotifierTest.java36
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/DeviceStateMonitorTest.java12
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/FakeTelephonyProvider.java8
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/GbaManagerTest.java259
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/GsmCdmaCallTest.java2
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/GsmCdmaCallTrackerTest.java20
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/GsmCdmaConnectionTest.java73
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/GsmCdmaPhoneTest.java308
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/IccSmsInterfaceManagerTest.java145
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/ImsSmsDispatcherTest.java52
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/InboundSmsTrackerTest.java4
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/IntRangeManagerTest.java2
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/LocaleTrackerTest.java9
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/MultiSimSettingControllerTest.java270
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/NetworkTypeControllerTest.java583
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/PhoneCapabilityTest.java43
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/PhoneConfigurationManagerTest.java84
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/PhoneStateListenerTest.java8
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/PhoneSubInfoControllerTest.java178
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/PhoneSwitcherTest.java233
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/PhysicalChannelConfigTest.java163
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/RILTest.java359
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/RadioConfigResponseTest.java96
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/RadioInterfaceCapabilityControllerTest.java117
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/RatRatcheterTest.java7
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/ServiceStateTest.java2
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/ServiceStateTrackerTest.java523
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/SignalStrengthTest.java12
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/SignalStrengthUpdateRequestTest.java125
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/SignalThresholdInfoTest.java381
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/SimPhoneBookTest.java72
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/SimulatedCommands.java156
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/SimulatedCommandsVerifier.java76
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/SlidingWindowEventCounterTest.java79
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/SmsDispatchersControllerTest.java24
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/SubscriptionControllerTest.java364
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/SubscriptionInfoUpdaterTest.java132
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/TelephonyPermissionsTest.java129
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/TelephonyRegistryTest.java617
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/TelephonyTest.java125
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/TestExecutorService.java274
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/WapPushOverSmsTest.java5
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/cdma/CdmaInboundSmsHandlerTest.java13
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/cdma/CdmaSmsCbTest.java4
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/d2d/CommunicatorTest.java174
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/d2d/DtmfTransportConversionTest.java189
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/d2d/DtmfTransportTest.java400
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/d2d/RtpTransportConversionTest.java193
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/d2d/RtpTransportTest.java120
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/dataconnection/ApnConfigTypeRepositoryTest.java10
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/dataconnection/ApnContextTest.java11
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/dataconnection/ApnSettingTest.java64
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataCallResponseTest.java28
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataConnectionTest.java559
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataEnabledSettingsTest.java21
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataProfileTest.java31
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataThrottlerTest.java235
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/dataconnection/DcControllerTest.java146
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/dataconnection/DcTrackerTest.java1774
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/dataconnection/LinkBandwidthEstimatorTest.java660
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/dataconnection/QosCallbackTrackerTest.java490
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/dataconnection/RetryManagerTest.java141
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/dataconnection/TelephonyNetworkFactoryTest.java83
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/dataconnection/TransportManagerTest.java12
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/emergency/EmergencyNumberTrackerTest.java186
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/euicc/EuiccControllerTest.java27
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/gsm/GsmInboundSmsHandlerTest.java488
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/gsm/GsmMmiCodeTest.java116
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/gsm/GsmSmsDispatcherTest.java258
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/ims/FeatureConnectionTest.java220
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/ims/FeatureConnectorTest.java155
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/ims/ImsCallProfileTest.java66
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/ims/ImsManagerTest.java899
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/ims/ImsResolverTest.java309
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/ims/ImsServiceControllerTest.java487
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/ims/ImsTestBase.java59
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/ims/ImsUtTest.java153
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/ims/MmTelFeatureConnectionTest.java296
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/ims/TestImsServiceControllerAdapter.java117
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsCallTest.java50
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneCallTest.java58
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneCallTrackerTest.java272
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneConnectionTest.java103
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneMmiCodeTest.java122
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneTest.java149
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/metrics/ImsStatsTest.java725
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/metrics/MetricsCollectorTest.java109
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/metrics/PersistAtomsStorageTest.java979
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/metrics/ServiceStateStatsTest.java826
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/metrics/SimSlotStateTest.java73
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/metrics/TelephonyMetricsTest.java89
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/metrics/VoiceCallSessionStatsTest.java316
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/nitz/NitzStateMachineImplTest.java2
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/nitz/TimeZoneLookupHelperTest.java15
-rw-r--r--[-rwxr-xr-x]tests/telephonytests/src/com/android/internal/telephony/uicc/IccPhoneBookInterfaceManagerTest.java119
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/uicc/IccRecordsTest.java103
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/uicc/IccUtilsTest.java73
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/uicc/PinStorageTest.java414
-rwxr-xr-xtests/telephonytests/src/com/android/internal/telephony/uicc/RuimRecordsTest.java86
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/uicc/SIMRecordsTest.java113
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/uicc/SimPhonebookRecordCacheTest.java150
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/uicc/UiccCardTest.java4
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/uicc/UiccCarrierPrivilegeRulesTest.java241
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/uicc/UiccControllerTest.java32
-rw-r--r--tests/telephonytests/src/com/android/internal/telephony/uicc/UiccProfileTest.java72
139 files changed, 4145 insertions, 18674 deletions
diff --git a/tests/telephonytests/Android.bp b/tests/telephonytests/Android.bp
index a4861df4fb..52cd7c5649 100644
--- a/tests/telephonytests/Android.bp
+++ b/tests/telephonytests/Android.bp
@@ -1,17 +1,5 @@
-package {
- // See: http://go/android-license-faq
- // A large-scale-change added 'default_applicable_licenses' to import
- // all of the 'license_kinds' from "frameworks_opt_telephony_license"
- // to get the below license kinds:
- // SPDX-license-identifier-Apache-2.0
- // SPDX-license-identifier-BSD
- default_applicable_licenses: ["frameworks_opt_telephony_license"],
-}
-
android_test {
name: "FrameworksTelephonyTests",
- // For access hidden connectivity methods in tests
- defaults: ["framework-connectivity-test-defaults"],
srcs: ["**/*.java"],
@@ -37,6 +25,7 @@ android_test {
"testables",
],
+ platform_apis: true,
jarjar_rules: ":jarjar-rules-telephony-tests",
test_suites: [
diff --git a/tests/telephonytests/AndroidManifest.xml b/tests/telephonytests/AndroidManifest.xml
index dc367774d7..3fbaacc2f3 100644
--- a/tests/telephonytests/AndroidManifest.xml
+++ b/tests/telephonytests/AndroidManifest.xml
@@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
+
<!-- Copyright (C) 2009 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
@@ -15,30 +16,28 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.frameworks.telephonytests">
+ package="com.android.frameworks.telephonytests">
<application android:name="com.android.internal.telephony.TestApplication">
- <uses-library android:name="android.test.runner"/>
+ <uses-library android:name="android.test.runner" />
<activity android:label="TelephonyTest"
- android:name="TelephonyTest"
- android:exported="true">
+ android:name="TelephonyTest">
<intent-filter>
- <action android:name="android.intent.action.MAIN"/>
+ <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
<instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
- android:targetPackage="com.android.frameworks.telephonytests"
- android:label="Frameworks Telephony Tests">
+ android:targetPackage="com.android.frameworks.telephonytests"
+ android:label="Frameworks Telephony Tests">
</instrumentation>
- <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
- <uses-permission android:name="android.permission.INTERNET"/>
+ <uses-permission android:name="android.permission.READ_PHONE_STATE" />
+ <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS"/>
<uses-permission android:name="android.permission.BIND_TELEPHONY_NETWORK_SERVICE"/>
- <uses-permission android:name="android.permission.BIND_TELEPHONY_DATA_SERVICE"/>
- <uses-permission android:name="android.permission.BATTERY_STATS"/>
+ <uses-permission android:name="android.permission.BIND_TELEPHONY_DATA_SERVICE" />
</manifest>
diff --git a/tests/telephonytests/AndroidTest.xml b/tests/telephonytests/AndroidTest.xml
index 5aa89221c4..c3a405b1ef 100644
--- a/tests/telephonytests/AndroidTest.xml
+++ b/tests/telephonytests/AndroidTest.xml
@@ -23,8 +23,6 @@
<test class="com.android.tradefed.testtype.AndroidJUnitTest" >
<option name="package" value="com.android.frameworks.telephonytests" />
<option name="runner" value="androidx.test.runner.AndroidJUnitRunner" />
- <option name="exclude-annotation" value="androidx.test.filters.FlakyTest" />
- <option name="exclude-annotation" value="org.junit.Ignore" />
<option name="hidden-api-checks" value="false"/>
</test>
</configuration>
diff --git a/tests/telephonytests/assets/eccdata b/tests/telephonytests/assets/eccdata
index 4c5959b4e8..2bce958585 100644
--- a/tests/telephonytests/assets/eccdata
+++ b/tests/telephonytests/assets/eccdata
Binary files differ
diff --git a/tests/telephonytests/assets/eccdata_input.txt b/tests/telephonytests/assets/eccdata_input.txt
deleted file mode 100644
index 8dcfa753b5..0000000000
--- a/tests/telephonytests/assets/eccdata_input.txt
+++ /dev/null
@@ -1,15 +0,0 @@
-revision: 1
-countries {
- iso_code: "US"
- eccs {
- phone_number: "54321"
- types: POLICE
- types: AMBULANCE
- types: FIRE
- types: MARINE_GUARD
- types: MOUNTAIN_RESCUE
- types: MIEC
- types: AIEC
- }
- ecc_fallback: "911"
-}
diff --git a/tests/telephonytests/assets/eccdata_ota b/tests/telephonytests/assets/eccdata_ota
deleted file mode 100644
index 69ddb46dcd..0000000000
--- a/tests/telephonytests/assets/eccdata_ota
+++ /dev/null
Binary files differ
diff --git a/tests/telephonytests/assets/eccdata_ota_input.txt b/tests/telephonytests/assets/eccdata_ota_input.txt
deleted file mode 100644
index 43795ce60e..0000000000
--- a/tests/telephonytests/assets/eccdata_ota_input.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-revision: 999999
-countries {
- iso_code: "US"
- eccs {
- phone_number: "98765"
- types: POLICE
- types: AMBULANCE
- types: FIRE
- }
- ecc_fallback: "911"
-} \ No newline at end of file
diff --git a/tests/telephonytests/jarjar-rules-tests.txt b/tests/telephonytests/jarjar-rules-tests.txt
index dd698704d7..7f7246956a 100644
--- a/tests/telephonytests/jarjar-rules-tests.txt
+++ b/tests/telephonytests/jarjar-rules-tests.txt
@@ -7,8 +7,6 @@ rule android.net.NetworkFactory* android.net.services.NetworkFactory@1
# Telephony-common has already included net-utils-framework-common lib and jarjars
# the package name. FrameworksTelephonyTests also includes net-utils-framework-common
-# via net-tests-utils and tries to jarjar it again. Rename the package names with
-# a different prefix in the test jarjar rule to avoid duplicate jar entries.
+# via net-tests-utils and tries to jarjar it again. Rename the package name with
+# differnt prefix in the test jarjar rule to avoid duplicate jar entries.
rule com.android.net.module.util.** com.android.internal.telephony.util.test.@1
-# Similarly, this is needed for the build utils.
-rule com.android.modules.utils.** com.android.internal.telephony.util.test.@1
diff --git a/tests/telephonytests/src/android/telephony/BinderCacheManagerTest.java b/tests/telephonytests/src/android/telephony/BinderCacheManagerTest.java
deleted file mode 100644
index e5b5f3afcc..0000000000
--- a/tests/telephonytests/src/android/telephony/BinderCacheManagerTest.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.telephony;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import android.os.IBinder;
-import android.os.IInterface;
-import android.test.suitebuilder.annotation.SmallTest;
-
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.util.concurrent.CountDownLatch;
-
-@RunWith(AndroidJUnit4.class)
-public class BinderCacheManagerTest {
-
- @Mock IInterface mInterface;
- @Mock IBinder mIBinder;
-
- private BinderCacheManager<IInterface> mBinderCache;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- when(mInterface.asBinder()).thenReturn(mIBinder);
- mBinderCache = new BinderCacheManager<>(() -> mInterface);
- }
-
- @Test
- @SmallTest
- public void testGetConnection() {
- when(mIBinder.isBinderAlive()).thenReturn(true);
- assertEquals(mInterface, mBinderCache.getBinder());
- when(mIBinder.isBinderAlive()).thenReturn(false);
- assertNull(mBinderCache.getBinder());
- }
-
- @Test
- @SmallTest
- public void testAddListenerAndDie() throws Exception {
- IBinder.DeathRecipient recipient = populateCacheCaptureDeathRecipent();
- CountDownLatch l = new CountDownLatch(1);
- assertEquals(mInterface, mBinderCache.listenOnBinder(l, l::countDown));
- when(mIBinder.isBinderAlive()).thenReturn(false);
- recipient.binderDied();
- assertEquals(0, l.getCount());
- assertNull(mBinderCache.getBinder());
- // Listeners should not be abailable wile remote process is not available.
- assertNull(mBinderCache.listenOnBinder(l, l::countDown));
- assertNull(mBinderCache.removeRunnable(l));
- verify(mIBinder).unlinkToDeath(eq(recipient), anyInt());
- }
-
- @Test
- @SmallTest
- public void testListenerNotCalledAfterRemoved() throws Exception {
- IBinder.DeathRecipient recipient = populateCacheCaptureDeathRecipent();
- CountDownLatch l = new CountDownLatch(1);
- assertEquals(mInterface, mBinderCache.listenOnBinder(l, l::countDown));
- assertEquals(mInterface, mBinderCache.removeRunnable(l));
- when(mIBinder.isBinderAlive()).thenReturn(false);
- recipient.binderDied();
- // Callback should never have been called because the runnable was removed before it died.
- assertNotEquals(0, l.getCount());
- }
-
- @Test
- @SmallTest
- public void testAddListenerAlreadyDead() throws Exception {
- IBinder.DeathRecipient recipient = populateCacheCaptureDeathRecipent();
- when(mIBinder.isBinderAlive()).thenReturn(false);
- recipient.binderDied();
- CountDownLatch l = new CountDownLatch(1);
- assertNull(mBinderCache.listenOnBinder(l, l::countDown));
- assertNull(mBinderCache.removeRunnable(l));
- // Callback shouldn't be called if it was never added in the first place.
- assertNotEquals(0, l.getCount());
- }
-
- /**
- * Populate the cache with mInterface & capture the associated DeathRecipient
- */
- private IBinder.DeathRecipient populateCacheCaptureDeathRecipent() throws Exception {
- when(mIBinder.isBinderAlive()).thenReturn(true);
- // Call getBinder() to populate cache the first time.
- assertEquals(mInterface, mBinderCache.getBinder());
- ArgumentCaptor<IBinder.DeathRecipient> captor = ArgumentCaptor.forClass(
- IBinder.DeathRecipient.class);
- verify(mIBinder).linkToDeath(captor.capture(), anyInt());
- IBinder.DeathRecipient recipient = captor.getValue();
- assertNotNull(recipient);
- return recipient;
- }
-}
diff --git a/tests/telephonytests/src/android/telephony/SmsMessageTest.java b/tests/telephonytests/src/android/telephony/SmsMessageTest.java
index 2bd865de81..2bbad419be 100644
--- a/tests/telephonytests/src/android/telephony/SmsMessageTest.java
+++ b/tests/telephonytests/src/android/telephony/SmsMessageTest.java
@@ -31,5 +31,6 @@ public class SmsMessageTest {
assertEquals(null, SmsMessage.createFromPdu(null, SmsConstants.FORMAT_3GPP2));
assertEquals(null, SmsMessage.createFromPdu(null, SmsConstants.FORMAT_3GPP));
assertEquals(null, SmsMessage.createFromPdu(null));
+ assertEquals(null, SmsMessage.newFromCMT(null));
}
}
diff --git a/tests/telephonytests/src/android/telephony/ims/ImsCallSessionListenerTests.java b/tests/telephonytests/src/android/telephony/ims/ImsCallSessionListenerTests.java
index cf4abb4365..99461c1a8d 100644
--- a/tests/telephonytests/src/android/telephony/ims/ImsCallSessionListenerTests.java
+++ b/tests/telephonytests/src/android/telephony/ims/ImsCallSessionListenerTests.java
@@ -16,29 +16,21 @@
package android.telephony.ims;
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.fail;
-
import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import android.telephony.ServiceState;
import android.telephony.TelephonyManager;
import android.telephony.ims.aidl.IImsCallSessionListener;
-import android.util.ArraySet;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import java.util.List;
-
@RunWith(AndroidJUnit4.class)
public class ImsCallSessionListenerTests {
@@ -83,52 +75,4 @@ public class ImsCallSessionListenerTests {
eq(TelephonyManager.NETWORK_TYPE_IWLAN), eq(imsReasonInfo));
}
- @Test
- public void testCallSessionDtmfReceived() throws Exception {
- ImsCallSessionListener mTestListener = new ImsCallSessionListener(mMockListener);
- mTestListener.callSessionDtmfReceived('A');
- mTestListener.callSessionDtmfReceived('a');
- verify(mMockListener, times(2)).callSessionDtmfReceived(eq('A'));
-
- mTestListener.callSessionDtmfReceived('B');
- mTestListener.callSessionDtmfReceived('b');
- verify(mMockListener, times(2)).callSessionDtmfReceived(eq('B'));
-
- mTestListener.callSessionDtmfReceived('0');
- verify(mMockListener, times(1)).callSessionDtmfReceived(eq('0'));
-
- mTestListener.callSessionDtmfReceived('*');
- verify(mMockListener, times(1)).callSessionDtmfReceived(eq('*'));
- mTestListener.callSessionDtmfReceived('#');
- verify(mMockListener, times(1)).callSessionDtmfReceived(eq('#'));
-
- try {
- mTestListener.callSessionDtmfReceived('P');
- fail("expected exception");
- } catch (IllegalArgumentException illegalArgumentException) {
- // expected
- }
- }
-
- @Test
- public void testCallSessionRtpExtensionHeadersReceived() throws Exception {
- ImsCallSessionListener mTestListener = new ImsCallSessionListener(mMockListener);
- ArraySet<RtpHeaderExtension> headers = new ArraySet<RtpHeaderExtension>();
- RtpHeaderExtension extension = new RtpHeaderExtension(1, new byte[1]);
- headers.add(extension);
- mTestListener.callSessionRtpHeaderExtensionsReceived(headers);
- final ArgumentCaptor<List<RtpHeaderExtension>> listCaptor =
- ArgumentCaptor.forClass((Class) List.class);
- verify(mMockListener).callSessionRtpHeaderExtensionsReceived(
- listCaptor.capture());
- assertEquals(1, listCaptor.getValue().size());
- assertEquals(extension.getLocalIdentifier(),
- listCaptor.getValue().get(0).getLocalIdentifier());
- try {
- mTestListener.callSessionRtpHeaderExtensionsReceived(null);
- fail("expected exception");
- } catch (NullPointerException npe) {
- // expected
- }
- }
}
diff --git a/tests/telephonytests/src/android/telephony/ims/ImsConfigImplTest.java b/tests/telephonytests/src/android/telephony/ims/ImsConfigImplTest.java
deleted file mode 100644
index ccf494b26a..0000000000
--- a/tests/telephonytests/src/android/telephony/ims/ImsConfigImplTest.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.telephony.ims;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-
-import android.telephony.ims.aidl.IImsConfig;
-import android.telephony.ims.aidl.IImsConfigCallback;
-import android.telephony.ims.stub.ImsConfigImplBase;
-import android.util.Pair;
-
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.concurrent.LinkedBlockingQueue;
-
-@RunWith(AndroidJUnit4.class)
-public class ImsConfigImplTest {
-
- private static final int TEST_KEY = 1;
- private static final int TEST_INT_VALUE = 2;
- private static final String TEST_STRING_VALUE = "abc";
-
- private static class ImsConfigImpl extends ImsConfigImplBase {
-
- public Pair<Integer, Integer> latestIntConfig;
- public Pair<Integer, String> latestStringConfig;
- // for testing caching
- private boolean mIsGetConfigCalled = false;
-
- @Override
- public int setConfig(int item, int value) {
- latestIntConfig = new Pair<>(item, value);
- return CONFIG_RESULT_SUCCESS;
- }
-
- @Override
- public int setConfig(int item, String value) {
- latestStringConfig = new Pair<>(item, value);
- return CONFIG_RESULT_SUCCESS;
- }
-
- @Override
- public int getConfigInt(int item) {
- mIsGetConfigCalled = true;
- if (latestIntConfig == null) {
- return CONFIG_RESULT_UNKNOWN;
- }
- if (latestIntConfig.first == item) {
- return latestIntConfig.second;
- }
- return CONFIG_RESULT_UNKNOWN;
- }
-
- @Override
- public String getConfigString(int item) {
- mIsGetConfigCalled = true;
- if (latestStringConfig == null) {
- return null;
- }
- if (latestStringConfig.first == item) {
- return latestStringConfig.second;
- }
- return null;
- }
-
- public boolean getIsGetConfigCalledAndReset() {
- boolean result = mIsGetConfigCalled;
- mIsGetConfigCalled = false;
- return result;
- }
- }
-
- private ImsConfigImpl mConfigUT;
- private IImsConfig mConfigBinder;
-
- @Before
- public void setUp() throws Exception {
- mConfigUT = new ImsConfigImpl();
- mConfigBinder = mConfigUT.getIImsConfig();
- }
-
- @After
- public void tearDown() {
- mConfigUT = null;
- mConfigBinder = null;
- }
-
- @Test
- public void testIntCaching() throws Exception {
- final LinkedBlockingQueue<Pair<Integer, Integer>> mConfigChanges =
- new LinkedBlockingQueue<>();
- final IImsConfigCallback mConfigCallback = new IImsConfigCallback.Stub() {
-
- @Override
- public void onIntConfigChanged(int item, int value) {
- mConfigChanges.offer(new Pair<>(item, value));
- }
- @Override
- public void onStringConfigChanged(int item, String value) {}
- };
- mConfigBinder.addImsConfigCallback(mConfigCallback);
- mConfigBinder.setConfigInt(TEST_KEY, TEST_INT_VALUE);
- // verify callback is called properly
- Pair<Integer, Integer> callbackResult = mConfigChanges.poll();
- assertNotNull(callbackResult);
- assertEquals(TEST_KEY, callbackResult.first.intValue());
- assertEquals(TEST_INT_VALUE, callbackResult.second.intValue());
- // verify set is called on Impl
- assertNotNull(mConfigUT.latestIntConfig);
- assertEquals(TEST_KEY, mConfigUT.latestIntConfig.first.intValue());
- assertEquals(TEST_INT_VALUE, mConfigUT.latestIntConfig.second.intValue());
- // Now get the test key, this impl should not be called, as it is cached internally.
- assertEquals(TEST_INT_VALUE, mConfigBinder.getConfigInt(TEST_KEY));
- assertFalse(mConfigUT.getIsGetConfigCalledAndReset());
- }
-
- @Test
- public void testStringCaching() throws Exception {
- final LinkedBlockingQueue<Pair<Integer, String>> mConfigChanges =
- new LinkedBlockingQueue<>();
- final IImsConfigCallback mConfigCallback = new IImsConfigCallback.Stub() {
-
- @Override
- public void onIntConfigChanged(int item, int value) {}
- @Override
- public void onStringConfigChanged(int item, String value) {
- mConfigChanges.offer(new Pair<>(item, value));
- }
- };
- mConfigBinder.addImsConfigCallback(mConfigCallback);
- mConfigBinder.setConfigString(TEST_KEY, TEST_STRING_VALUE);
- // verify callback is called properly
- Pair<Integer, String> callbackResult = mConfigChanges.poll();
- assertNotNull(callbackResult);
- assertEquals(TEST_KEY, callbackResult.first.intValue());
- assertEquals(TEST_STRING_VALUE, callbackResult.second);
- // verify set is called on Impl
- assertNotNull(mConfigUT.latestStringConfig);
- assertEquals(TEST_KEY, mConfigUT.latestStringConfig.first.intValue());
- assertEquals(TEST_STRING_VALUE, mConfigUT.latestStringConfig.second);
- // Now get the test key, this impl should not be called, as it is cached internally.
- assertEquals(TEST_STRING_VALUE, mConfigBinder.getConfigString(TEST_KEY));
- assertFalse(mConfigUT.getIsGetConfigCalledAndReset());
- }
-}
diff --git a/tests/telephonytests/src/android/telephony/ims/ImsFeatureTest.java b/tests/telephonytests/src/android/telephony/ims/ImsFeatureTest.java
index 80167d6ece..319d2008fa 100644
--- a/tests/telephonytests/src/android/telephony/ims/ImsFeatureTest.java
+++ b/tests/telephonytests/src/android/telephony/ims/ImsFeatureTest.java
@@ -248,8 +248,6 @@ public class ImsFeatureTest {
// add some capabilities
request.addCapabilitiesToEnableForTech(MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN);
- request.addCapabilitiesToEnableForTech(MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
- ImsRegistrationImplBase.REGISTRATION_TECH_CROSS_SIM);
request.addCapabilitiesToEnableForTech(
MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VIDEO
| MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
diff --git a/tests/telephonytests/src/android/telephony/ims/ImsMmTelManagerTests.java b/tests/telephonytests/src/android/telephony/ims/ImsMmTelManagerTests.java
index ac151bb4e5..7cfb8b0ead 100644
--- a/tests/telephonytests/src/android/telephony/ims/ImsMmTelManagerTests.java
+++ b/tests/telephonytests/src/android/telephony/ims/ImsMmTelManagerTests.java
@@ -18,11 +18,14 @@ package android.telephony.ims;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
+import android.content.pm.IPackageManager;
+import android.content.pm.PackageManager;
import android.telephony.AccessNetworkConstants;
-import android.telephony.BinderCacheManager;
import android.telephony.ims.aidl.IImsRegistrationCallback;
import android.telephony.ims.stub.ImsRegistrationImplBase;
import android.test.suitebuilder.annotation.SmallTest;
@@ -38,8 +41,10 @@ import org.mockito.Mock;
public class ImsMmTelManagerTests extends TelephonyTest {
- @Mock ITelephony mMockTelephonyInterface;
- @Mock BinderCacheManager<ITelephony> mBinderCache;
+ @Mock
+ ITelephony.Stub mMockTelephonyInterface;
+ @Mock
+ IPackageManager.Stub mMockPackageManager;
public class LocalCallback extends ImsMmTelManager.RegistrationCallback {
int mRegResult = -1;
@@ -53,7 +58,13 @@ public class ImsMmTelManagerTests extends TelephonyTest {
@Before
public void setUp() throws Exception {
super.setUp("ImsMmTelManagerTests");
- doReturn(mMockTelephonyInterface).when(mBinderCache).getBinder();
+ doReturn(mMockTelephonyInterface).when(mMockTelephonyInterface).queryLocalInterface(
+ anyString());
+ doReturn(mMockPackageManager).when(mMockPackageManager).queryLocalInterface(anyString());
+ doReturn(true).when(mMockPackageManager).hasSystemFeature(
+ eq(PackageManager.FEATURE_TELEPHONY_IMS), anyInt());
+ mServiceManagerMockedServices.put("phone", mMockTelephonyInterface);
+ mServiceManagerMockedServices.put("package", mMockPackageManager);
}
@After
@@ -67,9 +78,9 @@ public class ImsMmTelManagerTests extends TelephonyTest {
*/
@SmallTest
@Test
- public void testDeprecatedCallbackValues() throws Exception {
+ public void testCallbackValues() throws Exception {
LocalCallback cb = new LocalCallback();
- ImsMmTelManager managerUT = new ImsMmTelManager(0, mBinderCache);
+ ImsMmTelManager managerUT = new ImsMmTelManager(0);
managerUT.registerImsRegistrationCallback(Runnable::run, cb);
// Capture the RegistrationCallback that was registered.
@@ -80,17 +91,14 @@ public class ImsMmTelManagerTests extends TelephonyTest {
IImsRegistrationCallback cbBinder = callbackCaptor.getValue();
// Ensure the transport types are correct
- cbBinder.onRegistered(new ImsRegistrationAttributes.Builder(
- ImsRegistrationImplBase.REGISTRATION_TECH_LTE).build());
+ cbBinder.onRegistered(ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
assertEquals(AccessNetworkConstants.TRANSPORT_TYPE_WWAN, cb.mRegResult);
- cbBinder.onRegistered(new ImsRegistrationAttributes.Builder(
- ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN).build());
+ cbBinder.onRegistered(ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN);
assertEquals(AccessNetworkConstants.TRANSPORT_TYPE_WLAN, cb.mRegResult);
- cbBinder.onRegistered(new ImsRegistrationAttributes.Builder(
- ImsRegistrationImplBase.REGISTRATION_TECH_NONE).build());
+ cbBinder.onRegistered(ImsRegistrationImplBase.REGISTRATION_TECH_NONE);
assertEquals(-1, cb.mRegResult);
// Wacky value
- cbBinder.onRegistered(new ImsRegistrationAttributes.Builder(0xDEADBEEF).build());
+ cbBinder.onRegistered(0xDEADBEEF);
assertEquals(-1, cb.mRegResult);
}
}
diff --git a/tests/telephonytests/src/android/telephony/ims/ImsRegistrationTests.java b/tests/telephonytests/src/android/telephony/ims/ImsRegistrationTests.java
index ce375f3176..aa37ff7efb 100644
--- a/tests/telephonytests/src/android/telephony/ims/ImsRegistrationTests.java
+++ b/tests/telephonytests/src/android/telephony/ims/ImsRegistrationTests.java
@@ -26,13 +26,13 @@ import static org.mockito.Mockito.verify;
import android.net.Uri;
import android.os.Parcel;
import android.os.RemoteException;
+import android.telephony.ServiceState;
import android.telephony.ims.aidl.IImsRegistration;
import android.telephony.ims.aidl.IImsRegistrationCallback;
import android.telephony.ims.feature.ImsFeature;
import android.telephony.ims.stub.ImsFeatureConfiguration;
import android.telephony.ims.stub.ImsRegistrationImplBase;
import android.test.suitebuilder.annotation.SmallTest;
-import android.util.ArraySet;
import androidx.test.runner.AndroidJUnit4;
@@ -40,7 +40,6 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.mockito.AdditionalMatchers;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
@@ -121,24 +120,17 @@ public class ImsRegistrationTests {
@SmallTest
@Test
public void testRegistrationCallbackOnRegistered() throws RemoteException {
- final ArraySet<String> features = new ArraySet<>();
- features.add("feature1");
- features.add("feature2");
- ImsRegistrationAttributes attr = new ImsRegistrationAttributes.Builder(
- ImsRegistrationImplBase.REGISTRATION_TECH_LTE).setFeatureTags(features).build();
- mRegistration.onRegistered(attr);
-
- verify(mCallback).onRegistered(attr);
+ mRegistration.onRegistered(ServiceState.RIL_RADIO_TECHNOLOGY_LTE);
+
+ verify(mCallback).onRegistered(ServiceState.RIL_RADIO_TECHNOLOGY_LTE);
}
@SmallTest
@Test
public void testRegistrationCallbackOnRegistering() throws RemoteException {
- ImsRegistrationAttributes attr = new ImsRegistrationAttributes.Builder(
- ImsRegistrationImplBase.REGISTRATION_TECH_LTE).build();
- mRegistration.onRegistering(ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
+ mRegistration.onRegistering(ServiceState.RIL_RADIO_TECHNOLOGY_LTE);
- verify(mCallback).onRegistering(attr);
+ verify(mCallback).onRegistering(ServiceState.RIL_RADIO_TECHNOLOGY_LTE);
}
@SmallTest
@@ -177,26 +169,19 @@ public class ImsRegistrationTests {
public void testRegistrationCallbackAfterUnregistered() throws RemoteException {
mRegBinder.removeRegistrationCallback(mCallback);
- ImsRegistrationAttributes attr = new ImsRegistrationAttributes.Builder(
- ImsRegistrationImplBase.REGISTRATION_TECH_LTE).build();
- mRegistration.onRegistered(attr);
+ mRegistration.onRegistered(ServiceState.RIL_RADIO_TECHNOLOGY_LTE);
- verify(mCallback, never()).onRegistered(attr);
+ verify(mCallback, never()).onRegistered(ServiceState.RIL_RADIO_TECHNOLOGY_LTE);
}
@SmallTest
@Test
public void testRegistrationCallbackSendCurrentState() throws RemoteException {
- final ArraySet<String> features = new ArraySet<>();
- features.add("feature1");
- features.add("feature2");
- ImsRegistrationAttributes attr = new ImsRegistrationAttributes.Builder(
- ImsRegistrationImplBase.REGISTRATION_TECH_LTE).setFeatureTags(features).build();
- mRegistration.onRegistered(attr);
+ mRegistration.onRegistered(ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
mRegBinder.addRegistrationCallback(mCallback2);
- verify(mCallback2).onRegistered(attr);
+ verify(mCallback2).onRegistered(eq(ImsRegistrationImplBase.REGISTRATION_TECH_LTE));
}
@SmallTest
@@ -244,35 +229,4 @@ public class ImsRegistrationTests {
// with onUnregistered.
verify(mCallback2, never()).onDeregistered(any(ImsReasonInfo.class));
}
-
- @SmallTest
- @Test
- public void testRegistrationCallbackCalledOnAdd() throws RemoteException {
- mRegistration.onSubscriberAssociatedUriChanged(new Uri[] { null, null });
-
- mRegBinder.addRegistrationCallback(mCallback2);
-
- verify(mCallback2).onSubscriberAssociatedUriChanged(
- AdditionalMatchers.aryEq(new Uri[] { null, null }));
- }
-
- @SmallTest
- @Test
- public void testRegistrationCallbackNotCalledOnAddAfterDeregistered() throws RemoteException {
- ImsReasonInfo info = new ImsReasonInfo(ImsReasonInfo.CODE_LOCAL_NETWORK_NO_LTE_COVERAGE, 0);
- mRegistration.onSubscriberAssociatedUriChanged(new Uri[] { null, null });
-
- mRegistration.onDeregistered(info);
- mRegBinder.addRegistrationCallback(mCallback2);
-
- verify(mCallback2, never()).onSubscriberAssociatedUriChanged(any());
- }
-
- @SmallTest
- @Test
- public void testRegistrationCallbackNotCalledOnAddAndNoSubscriberChanged()
- throws RemoteException {
- mRegBinder.addRegistrationCallback(mCallback2);
- verify(mCallback2, never()).onSubscriberAssociatedUriChanged(any());
- }
}
diff --git a/tests/telephonytests/src/android/telephony/ims/ImsServiceTest.java b/tests/telephonytests/src/android/telephony/ims/ImsServiceTest.java
index 79395a1ee3..80cae9485b 100644
--- a/tests/telephonytests/src/android/telephony/ims/ImsServiceTest.java
+++ b/tests/telephonytests/src/android/telephony/ims/ImsServiceTest.java
@@ -85,9 +85,7 @@ public class ImsServiceTest {
@Test
@SmallTest
public void testCreateMMTelFeature() throws RemoteException {
- IImsMmTelFeature f = mTestImsServiceBinder.createMmTelFeature(TEST_SLOT_0);
- mTestImsServiceBinder.addFeatureStatusCallback(TEST_SLOT_0, ImsFeature.FEATURE_MMTEL,
- mTestCallback);
+ IImsMmTelFeature f = mTestImsServiceBinder.createMmTelFeature(TEST_SLOT_0, mTestCallback);
mTestImsService.mTestMmTelFeature.sendSetFeatureState(ImsFeature.STATE_READY);
SparseArray<ImsFeature> features = mTestImsService.getFeatures(TEST_SLOT_0);
@@ -108,13 +106,10 @@ public class ImsServiceTest {
@Test
@SmallTest
public void testRemoveMMTelFeature() throws RemoteException {
- mTestImsServiceBinder.createMmTelFeature(TEST_SLOT_0);
- mTestImsServiceBinder.addFeatureStatusCallback(TEST_SLOT_0, ImsFeature.FEATURE_MMTEL,
- mTestCallback);
+ mTestImsServiceBinder.createMmTelFeature(TEST_SLOT_0, mTestCallback);
- mTestImsServiceBinder.removeFeatureStatusCallback(TEST_SLOT_0, ImsFeature.FEATURE_MMTEL,
+ mTestImsServiceBinder.removeImsFeature(TEST_SLOT_0, ImsFeature.FEATURE_MMTEL,
mTestCallback);
- mTestImsServiceBinder.removeImsFeature(TEST_SLOT_0, ImsFeature.FEATURE_MMTEL);
verify(mTestImsService.mSpyMmTelFeature).onFeatureRemoved();
verify(mTestImsService.mSpyMmTelFeature).removeImsFeatureStatusCallback(mTestCallback);
@@ -125,9 +120,7 @@ public class ImsServiceTest {
@Test
@SmallTest
public void testCallMethodOnCreatedFeature() throws RemoteException {
- IImsMmTelFeature f = mTestImsServiceBinder.createMmTelFeature(TEST_SLOT_0);
- mTestImsServiceBinder.addFeatureStatusCallback(TEST_SLOT_0, ImsFeature.FEATURE_MMTEL,
- mTestCallback);
+ IImsMmTelFeature f = mTestImsServiceBinder.createMmTelFeature(TEST_SLOT_0, mTestCallback);
f.getUtInterface();
@@ -150,23 +143,4 @@ public class ImsServiceTest {
assertEquals(config, result);
}
-
- /**
- * Tests that ImsService capability sanitization works correctly.
- */
- @Test
- @SmallTest
- public void testCapsSanitized() throws RemoteException {
- long validCaps =
- ImsService.CAPABILITY_SIP_DELEGATE_CREATION;
- // emergency over MMTEL should not be set here, but rather internally in Telephony.
- long invalidCaps = 0xDEADBEEF00000000L | ImsService.CAPABILITY_EMERGENCY_OVER_MMTEL;
- invalidCaps |= validCaps;
-
- mTestImsService.testCaps = validCaps;
- assertEquals(validCaps, mTestImsServiceBinder.getImsServiceCapabilities());
- mTestImsService.testCaps = invalidCaps;
- // The extra bits should have been removed, leaving only the valid remaining
- assertEquals(validCaps, mTestImsServiceBinder.getImsServiceCapabilities());
- }
}
diff --git a/tests/telephonytests/src/android/telephony/ims/MmTelFeatureTests.java b/tests/telephonytests/src/android/telephony/ims/MmTelFeatureTests.java
index a067604237..a1a9baf7b1 100644
--- a/tests/telephonytests/src/android/telephony/ims/MmTelFeatureTests.java
+++ b/tests/telephonytests/src/android/telephony/ims/MmTelFeatureTests.java
@@ -24,7 +24,6 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
-import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
@@ -48,9 +47,6 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
-import java.util.ArrayList;
-import java.util.concurrent.TimeUnit;
-
@RunWith(AndroidJUnit4.class)
public class MmTelFeatureTests extends ImsTestBase {
@@ -175,20 +171,4 @@ public class MmTelFeatureTests extends ImsTestBase {
waitForHandlerAction(mHandler, TEST_RESULT_DELAY_MS);
assertTrue(mHandlerResults[TEST_SEND_DTMF_RESULT]);
}
-
- @SmallTest
- @Test
- public void testChangeOfferedRtpHeaderExtensionTypes() throws Exception {
- Message resultMessage = Message.obtain(mHandler, TEST_SEND_DTMF_RESULT);
- resultMessage.replyTo = mHandlerMessenger;
- RtpHeaderExtensionType type = new RtpHeaderExtensionType(1,
- Uri.parse("http://developer.android.com/test"));
- ArrayList<RtpHeaderExtensionType> types = new ArrayList<>();
- types.add(type);
- mFeatureBinder.changeOfferedRtpHeaderExtensionTypes(types);
- waitForHandlerAction(mHandler, TEST_RESULT_DELAY_MS);
- mFeature.configuredRtpHeaderExtensions.await(TEST_RESULT_DELAY_MS, TimeUnit.MILLISECONDS);
- assertEquals(types.size(), mFeature.receivedExtensions.size());
- assertEquals(types.get(0), mFeature.receivedExtensions.iterator().next());
- }
}
diff --git a/tests/telephonytests/src/android/telephony/ims/RcsConfigTest.java b/tests/telephonytests/src/android/telephony/ims/RcsConfigTest.java
deleted file mode 100644
index a81e93fef3..0000000000
--- a/tests/telephonytests/src/android/telephony/ims/RcsConfigTest.java
+++ /dev/null
@@ -1,303 +0,0 @@
-/*
- * Copyright 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.telephony.ims;
-
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertFalse;
-import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.assertNull;
-import static junit.framework.Assert.assertTrue;
-
-import static org.mockito.Mockito.when;
-
-import android.content.ContentValues;
-import android.content.Context;
-import android.telephony.SubscriptionManager;
-import android.telephony.ims.RcsConfig;
-import android.telephony.ims.RcsConfig.Characteristic;
-import android.test.mock.MockContentResolver;
-import android.test.suitebuilder.annotation.SmallTest;
-
-import androidx.test.ext.junit.runners.AndroidJUnit4;
-
-import com.android.internal.telephony.FakeTelephonyProvider;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.util.Arrays;
-
-@RunWith(AndroidJUnit4.class)
-public final class RcsConfigTest {
-
- private static final String TEST_RCS_CONFIG = "<?xml version=\"1.0\"?>\n"
- + "<wap-provisioningdoc version=\"1.1\">\n"
- + "\t<characteristic type=\"APPLICATION\">\n"
- + "\t\t<parm name=\"AppID\" value=\"urn:oma:mo:ext-3gpp-ims:1.0\"/>\n"
- + "\t\t<characteristic type=\"3GPP_IMS\">\n"
- + "\t\t\t<parm name=\"AppID\" value=\"ap2001\"/>\n"
- + "\t\t\t<parm name=\"Name\" value=\"RCS IMS Settings\"/>\n"
- + "\t\t\t<characteristic type=\"Ext\">\n"
- + "\t\t\t\t<characteristic type=\"GSMA\">\n"
- + "\t\t\t\t\t<parm name=\"AppRef\" value=\"IMS-Setting\"/>\n"
- + "\t\t\t\t\t<parm name=\"rcsVolteSingleRegistration\" value=\"1\"/>\n"
- + "\t\t\t\t</characteristic>\n"
- + "\t\t\t</characteristic>\n"
- + "\t\t</characteristic>\n"
- + "\t\t<characteristic type=\"SERVICES\">\n"
- + "\t\t\t<parm name=\"SupportedRCSProfileVersions\" value=\"UP_2.3\"/>\n"
- + "\t\t\t<parm name=\"ChatAuth\" value=\"1\"/>\n"
- + "\t\t\t<parm name=\"GroupChatAuth\" value=\"1\"/>\n"
- + "\t\t\t<parm name=\"ftAuth\" value=\"1\"/>\n"
- + "\t\t\t<parm name=\"standaloneMsgAuth\" value=\"1\"/>\n"
- + "\t\t\t<parm name=\"geolocPushAuth\" value=\"1\"/>\n"
- + "\t\t\t<characteristic type=\"Ext\">\n"
- + "\t\t\t\t<characteristic type=\"DataOff\">\n"
- + "\t\t\t\t\t<parm name=\"rcsMessagingDataOff\" value=\"1\"/>\n"
- + "\t\t\t\t\t<parm name=\"fileTransferDataOff\" value=\"1\"/>\n"
- + "\t\t\t\t\t<parm name=\"mmsDataOff\" value=\"1\"/>\n"
- + "\t\t\t\t\t<parm name=\"syncDataOff\" value=\"1\"/>\n"
- + "\t\t\t\t\t<characteristic type=\"Ext\"/>\n"
- + "\t\t\t\t</characteristic>\n"
- + "\t\t\t</characteristic>\n"
- + "\t\t</characteristic>\n"
- + "\t\t<characteristic type=\"PRESENCE\">\n"
- + "\t\t\t<parm name=\"client-obj-datalimit\" value=\"8192\"/>\n"
- + "\t\t\t<parm name=\"content-serveruri\" value=\"X\"/>\n"
- + "\t\t\t<parm name=\"source-throttlepublish\" value=\"32\"/>\n"
- + "\t\t\t<parm name=\"max-number-ofsubscriptions-inpresence-list\" value=\"8\"/>\n"
- + "\t\t\t<parm name=\"service-uritemplate\" value=\"X\"/>\n"
- + "\t\t\t<parm name=\"RLS-URI\" value=\"X\"/>\n"
- + "\t\t</characteristic>\n"
- + "\t\t<characteristic type=\"MESSAGING\">\n"
- + "\t\t\t<characteristic type=\"StandaloneMsg\">\n"
- + "\t\t\t\t<parm name=\"MaxSize\" value=\"8192\"/>\n"
- + "\t\t\t\t<parm name=\"SwitchoverSize\" value=\"1024\"/>\n"
- + "\t\t\t\t<parm name=\"exploder-uri\" value=\"X\"/>\n"
- + "\t\t\t</characteristic>\n"
- + "\t\t\t<characteristic type=\"Chat\">\n"
- + "\t\t\t\t<parm name=\"max_adhoc_group_size\" value=\"60\"/>\n"
- + "\t\t\t\t<parm name=\"conf-fcty-uri\" value=\"X\"/>\n"
- + "\t\t\t\t<parm name=\"AutAccept\" value=\"1\"/>\n"
- + "\t\t\t\t<parm name=\"AutAcceptGroupChat\" value=\"1\"/>\n"
- + "\t\t\t\t<parm name=\"TimerIdle\" value=\"120\"/>\n"
- + "\t\t\t\t<parm name=\"MaxSize\" value=\"16384\"/>\n"
- + "\t\t\t\t<parm name=\"ChatRevokeTimer\" value=\"0\"/>\n"
- + "\t\t\t\t<parm name=\"reconnectGuardTimer\" value=\"0\"/>\n"
- + "\t\t\t\t<parm name=\"cfsTrigger\" value=\"1\"/>\n"
- + "\t\t\t</characteristic>\n"
- + "\t\t\t<parm name=\"max1ToManyRecipients\" value=\"8\"/>\n"
- + "\t\t\t<parm name=\"1toManySelectedTech\" value=\"1\"/>\n"
- + "\t\t\t<parm name=\"displayNotificationSwitch\" value=\"0\"/>\n"
- + "\t\t\t<parm name=\"contentCompressSize\" value=\"1024\"/>\n"
- + "\t\t\t<characteristic type=\"FileTransfer\">\n"
- + "\t\t\t\t<parm name=\"ftWarnSize\" value=\"0\"/>\n"
- + "\t\t\t\t<parm name=\"MaxSizeFileTr\" value=\"65536\"/>\n"
- + "\t\t\t\t<parm name=\"ftAutAccept\" value=\"1\"/>\n"
- + "\t\t\t\t<parm name=\"ftHTTPCSURI\" value=\"X\"/>\n"
- + "\t\t\t\t<parm name=\"ftHTTPDLURI\" value=\"X\"/>\n"
- + "\t\t\t\t<parm name=\"ftHTTPCSUser\" value=\"X\"/>\n"
- + "\t\t\t\t<parm name=\"ftHTTPCSPwd\" value=\"X\"/>\n"
- + "\t\t\t\t<parm name=\"ftHTTPFallback\" value=\"X\"/>\n"
- + "\t\t\t\t<parm name=\" ftMax1ToManyRecipients\" value=\"0\"/>\n"
- + "\t\t\t</characteristic>\n"
- + "\t\t\t<characteristic type=\"Chatbot\">\n"
- + "\t\t\t\t<parm name=\"ChatbotDirectory\" value=\"X\"/>\n"
- + "\t\t\t\t<parm name=\"BotinfoFQDNRoot\" value=\"X\"/>\n"
- + "\t\t\t\t<part name=\"SpecificChatbotsList\" value=\"X\"/>\n"
- + "\t\t\t\t<parm name=\"IdentityInEnrichedSearch\" value=\"1\"/>\n"
- + "\t\t\t\t<parm name=\"PrivacyDisable\" value=\"0\"/>\n"
- + "\t\t\t\t<parm name=\"ChatbotMsgTech\" value=\"1\"/>\n"
- + "\t\t\t</characteristic>\n"
- + "\t\t\t<characteristic type=\"MessageStore\">\n"
- + "\t\t\t\t<parm name=\"MsgStoreUrl\" value=\"X\"/>\n"
- + "\t\t\t\t<parm name=\"MsgStoreNotifUrl\" value=\"X\"/>\n"
- + "\t\t\t\t<parm name=\"MsgStoreAuth\" value=\"X\"/>\n"
- + "\t\t\t\t<parm name=\"MsgStoreUserName\" value=\"X\"/>\n"
- + "\t\t\t\t<parm name=\"MsgStoreUserPwd\" value=\"X\"/>\n"
- + "\t\t\t\t<parm name=\"EventRpting\" value=\"1\"/>\n"
- + "\t\t\t\t<parm name=\"AuthArchive\" value=\"1\"/>\n"
- + "\t\t\t\t<parm name=\"SMSStore\" value=\"1\"/>\n"
- + "\t\t\t\t<parm name=\"MMSStore\" value=\"1\"/>\n"
- + "\t\t\t</characteristic>\n"
- + "\t\t\t<characteristic type=\"Ext\"/>\n"
- + "\t\t</characteristic>\n"
- + "\t</characteristic>\n"
- + "</wap-provisioningdoc>\n";
-
- private static final String[][] TEST_CONFIG_VALUES = {{"rcsVolteSingleRegistration", "1"},
- {"SupportedRCSProfileVersions", "UP_2.3"}, {"ChatAuth", "1"}, {"GroupChatAuth", "1"},
- {"ftAuth", "1"}, {"standaloneMsgAuth", "1"}, {"geolocPushAuth", "1"},
- {"rcsMessagingDataOff", "1"}, {"fileTransferDataOff", "1"}, {"mmsDataOff", "1"},
- {"syncDataOff", "1"}};
-
- private static final String[] VALID_CHARACTERISTICS = {"APPLICATION", "3GPP_IMS", "Ext",
- "GSMA", "SERVICES", "DaTAOFF", "PRESENCE", "MESSAGING", "Chat", "FileTransfer",
- "Chatbot", "MessageSTORE"};
- private static final String[] INVALID_CHARACTERISTICS = {"APP2LICATION", "3GPPIMS", "Exte",
- "GSMf", "SERVICE", "DaTAOn", "PRESENCE2", "MESSAG", "Ch", "File", "STORE"};
- private static final String[][] SUB_CHARACTERISTICS = {
- {"APPLICATION", "3GPP_IMS", "Ext", "GSMA"},
- {"APPLICATION", "SERVICES", "Ext", "DataOff", "Ext"}};
- private static final String[][] SAME_PARMS_DIFF_CHARS_VALUE_MAP = {
- {"MaxSize", "Chat", "16384"}, {"MaxSize", "StandaloneMsg", "8192"}};
-
- private static final int FAKE_SUB_ID = 1;
- private MockContentResolver mContentResolver;
- private FakeTelephonyProvider mFakeTelephonyProvider;
- @Mock
- Context mContext;
-
- @Before
- public void setUp() {
- MockitoAnnotations.initMocks(this);
- mFakeTelephonyProvider = new FakeTelephonyProvider();
- mContentResolver = new MockContentResolver();
- mContentResolver.addProvider(SubscriptionManager.CONTENT_URI.getAuthority(),
- mFakeTelephonyProvider);
- when(mContext.getContentResolver()).thenReturn(mContentResolver);
- createFakeSimInfo();
- }
-
- @Test
- @SmallTest
- public void testLoadAndUpdateConfigForSub() {
-
- byte[] currentData = RcsConfig.loadRcsConfigForSub(mContext, FAKE_SUB_ID, false);
-
- RcsConfig.updateConfigForSub(mContext, FAKE_SUB_ID, null, false);
- byte[] updatedData = RcsConfig.loadRcsConfigForSub(mContext, FAKE_SUB_ID, false);
- assertNull(updatedData);
-
- RcsConfig.updateConfigForSub(mContext, FAKE_SUB_ID, TEST_RCS_CONFIG.getBytes(), false);
- updatedData = RcsConfig.loadRcsConfigForSub(mContext, FAKE_SUB_ID, false);
- assertTrue(Arrays.equals(updatedData, TEST_RCS_CONFIG.getBytes()));
-
- RcsConfig.updateConfigForSub(mContext, FAKE_SUB_ID, currentData, false);
- updatedData = RcsConfig.loadRcsConfigForSub(mContext, FAKE_SUB_ID, false);
- assertTrue(Arrays.equals(currentData, updatedData));
- }
-
- @Test
- @SmallTest
- public void testCompressAndDecompress() {
- byte[] compressedData = RcsConfig.compressGzip(TEST_RCS_CONFIG.getBytes());
- assertFalse(Arrays.equals(compressedData, TEST_RCS_CONFIG.getBytes()));
- byte[] decompressedData = RcsConfig.decompressGzip(compressedData);
- assertTrue(Arrays.equals(decompressedData, TEST_RCS_CONFIG.getBytes()));
- assertNull(RcsConfig.compressGzip(null));
- assertNull(RcsConfig.decompressGzip(null));
- byte[] emptyData = new byte[0];
- assertEquals(emptyData, RcsConfig.compressGzip(emptyData));
- assertEquals(emptyData, RcsConfig.decompressGzip(emptyData));
- }
-
- @Test
- @SmallTest
- public void testParseConfig() {
- RcsConfig config = new RcsConfig(TEST_RCS_CONFIG.getBytes());
-
- for (int i = 0; i < TEST_CONFIG_VALUES.length; i++) {
- assertEquals(config.getString(TEST_CONFIG_VALUES[i][0], null),
- TEST_CONFIG_VALUES[i][1]);
- }
- }
-
- @Test
- @SmallTest
- public void testGetCharacteristic() {
- RcsConfig config = new RcsConfig(TEST_RCS_CONFIG.getBytes());
-
- for (int i = 0; i < VALID_CHARACTERISTICS.length; i++) {
- assertNotNull(config.getCharacteristic(VALID_CHARACTERISTICS[i]));
- }
-
- for (int i = 0; i < INVALID_CHARACTERISTICS.length; i++) {
- assertNull(config.getCharacteristic(INVALID_CHARACTERISTICS[i]));
- }
- }
-
- @Test
- @SmallTest
- public void testSetAndMoveCharacteristic() {
- RcsConfig config = new RcsConfig(TEST_RCS_CONFIG.getBytes());
-
- for (String[] sub : SUB_CHARACTERISTICS) {
- Characteristic[] cl = new Characteristic[sub.length];
- int c = 0;
- for (String cur : sub) {
- cl[c] = config.getCharacteristic(cur);
- assertNotNull(cl[c]);
- config.setCurrentCharacteristic(cl[c]);
- c++;
- }
-
- while (c > 0) {
- assertEquals(cl[--c], config.getCurrentCharacteristic());
- config.moveToParent();
- }
-
- assertEquals(config.getRoot(), config.getCurrentCharacteristic());
- }
- }
-
- @Test
- @SmallTest
- public void testGetDuplicateParmInDifferentCharacteristics() {
- RcsConfig config = new RcsConfig(TEST_RCS_CONFIG.getBytes());
- for (String[] sub : SAME_PARMS_DIFF_CHARS_VALUE_MAP) {
- config.moveToRoot();
- if (!sub[1].isEmpty()) {
- config.setCurrentCharacteristic(config.getCharacteristic(sub[1]));
- }
-
- String value = config.getString(sub[0], "");
-
- assertEquals(value, sub[2]);
- }
- }
-
- @Test
- @SmallTest
- public void testIsRcsVolteSingleRegistrationSupported() {
- String[] vals = new String[]{"0", "1", "2"};
- boolean[] expectedResHome = new boolean[]{false, true, true};
- boolean[] expectedResRoaming = new boolean[]{false, true, false};
- for (int i = 0; i < vals.length; i++) {
- String xml = "\t\t\t\t<characteristic type=\"GSMA\">\n"
- + "\t\t\t\t\t<parm name=\"rcsVolteSingleRegistration\" value=\""
- + vals[i] + "\"/>\n" + "\t\t\t\t</characteristic>\n";
- RcsConfig config = new RcsConfig(xml.getBytes());
- assertEquals(config.isRcsVolteSingleRegistrationSupported(false), expectedResHome[i]);
- assertEquals(config.isRcsVolteSingleRegistrationSupported(true),
- expectedResRoaming[i]);
- }
- }
-
- private void createFakeSimInfo() {
- ContentValues contentValues = new ContentValues();
- final String fakeIccId = "fakeleIccId";
- final String fakeCardId = "fakeCardId";
- contentValues.put(SubscriptionManager.UNIQUE_KEY_SUBSCRIPTION_ID, FAKE_SUB_ID);
- contentValues.put(SubscriptionManager.ICC_ID, fakeIccId);
- contentValues.put(SubscriptionManager.CARD_ID, fakeCardId);
- mContentResolver.insert(SubscriptionManager.CONTENT_URI, contentValues);
- }
-}
diff --git a/tests/telephonytests/src/android/telephony/ims/SipTransportImplBaseTest.java b/tests/telephonytests/src/android/telephony/ims/SipTransportImplBaseTest.java
deleted file mode 100644
index 11b1d22ae6..0000000000
--- a/tests/telephonytests/src/android/telephony/ims/SipTransportImplBaseTest.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.telephony.ims;
-
-import static junit.framework.Assert.assertFalse;
-import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.assertTrue;
-
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.ArgumentMatchers.anyList;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-
-import android.os.IBinder;
-import android.telephony.ims.aidl.ISipDelegate;
-import android.telephony.ims.aidl.ISipDelegateMessageCallback;
-import android.telephony.ims.aidl.ISipDelegateStateCallback;
-import android.telephony.ims.aidl.ISipTransport;
-import android.telephony.ims.stub.SipDelegate;
-import android.telephony.ims.stub.SipTransportImplBase;
-import android.util.ArraySet;
-
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
-
-import java.util.Collections;
-import java.util.Set;
-import java.util.concurrent.Executor;
-
-@RunWith(AndroidJUnit4.class)
-public class SipTransportImplBaseTest {
-
- private static final int TEST_SUB_ID = 1;
-
- private static class TestSipTransport extends SipTransportImplBase {
-
- private static class SipDelegateContainer {
- public final int subId;
- public final DelegateRequest delegateRequest;
- public final DelegateStateCallback delegateStateCallback;
- public final DelegateMessageCallback delegateMessageCallback;
- public final SipDelegate sipDelegate;
-
- SipDelegateContainer(int subId, DelegateRequest request,
- DelegateStateCallback dc, DelegateMessageCallback mc, SipDelegate delegate) {
- this.subId = subId;
- delegateRequest = request;
- delegateStateCallback = dc;
- delegateMessageCallback = mc;
- sipDelegate = delegate;
- }
- }
-
- private final Set<SipDelegateContainer> mDelegates = new ArraySet<>();
-
- TestSipTransport(Executor executor) {
- super(executor);
- }
-
- @Override
- public void createSipDelegate(int subscriptionId, DelegateRequest request,
- DelegateStateCallback dc, DelegateMessageCallback mc) {
- SipDelegate mockDelegate = mock(SipDelegate.class);
- SipDelegateContainer container = new SipDelegateContainer(subscriptionId, request, dc,
- mc, mockDelegate);
- mDelegates.add(container);
- dc.onCreated(mockDelegate, Collections.emptySet());
- }
-
- @Override
- public void destroySipDelegate(SipDelegate delegate, int reason) {
- mDelegates.removeIf(candidate -> {
- if (delegate.equals(candidate.sipDelegate)) {
- candidate.delegateStateCallback.onDestroyed(reason);
- return true;
- }
- return false;
- });
- }
-
- public boolean isTrackedDelegateSetEmpty() {
- return mDelegates.isEmpty();
- }
- }
-
- @Test
- public void createDestroyDelegate() throws Exception {
- // Set up the executor to simply run inline
- TestSipTransport t = new TestSipTransport(Runnable::run);
-
- ISipDelegateStateCallback stateCb = mock(ISipDelegateStateCallback.class);
- IBinder stateBinder = mock(IBinder.class);
- doReturn(stateBinder).when(stateCb).asBinder();
- ISipDelegateMessageCallback messageCb = mock(ISipDelegateMessageCallback.class);
-
- ISipDelegate delegate = createSipDelegate(t, stateCb, messageCb);
- assertFalse(t.isTrackedDelegateSetEmpty());
- ArgumentCaptor<IBinder.DeathRecipient> captor =
- ArgumentCaptor.forClass(IBinder.DeathRecipient.class);
- verify(stateBinder).linkToDeath(captor.capture(), anyInt());
- assertNotNull(captor.getValue());
-
- destroySipDelegate(t, delegate,
- SipDelegateManager.SIP_DELEGATE_DESTROY_REASON_REQUESTED_BY_APP);
- verify(stateBinder).unlinkToDeath(eq(captor.getValue()), anyInt());
- verify(stateCb).onDestroyed(
- eq(SipDelegateManager.SIP_DELEGATE_DESTROY_REASON_REQUESTED_BY_APP));
- }
-
-
- @Test
- public void testPhoneProcessCrash() throws Exception {
- // Set up the executor to simply run inline
- TestSipTransport t = new TestSipTransport(Runnable::run);
-
- ISipDelegateStateCallback stateCb = mock(ISipDelegateStateCallback.class);
- IBinder stateBinder = mock(IBinder.class);
- doReturn(stateBinder).when(stateCb).asBinder();
- ISipDelegateMessageCallback messageCb = mock(ISipDelegateMessageCallback.class);
-
- createSipDelegate(t, stateCb, messageCb);
- assertFalse(t.isTrackedDelegateSetEmpty());
- ArgumentCaptor<IBinder.DeathRecipient> captor =
- ArgumentCaptor.forClass(IBinder.DeathRecipient.class);
- verify(stateBinder).linkToDeath(captor.capture(), anyInt());
- assertNotNull(captor.getValue());
- IBinder.DeathRecipient recipient = captor.getValue();
-
- // simulate phone process crash
- recipient.binderDied(stateBinder);
- verify(stateCb).onDestroyed(SipDelegateManager.SIP_DELEGATE_DESTROY_REASON_SERVICE_DEAD);
- assertTrue(t.isTrackedDelegateSetEmpty());
- }
-
- private ISipDelegate createSipDelegate(TestSipTransport transport,
- ISipDelegateStateCallback stateCb,
- ISipDelegateMessageCallback messageCb) throws Exception {
- ISipTransport transportBinder = transport.getBinder();
- transportBinder.createSipDelegate(TEST_SUB_ID, new DelegateRequest(Collections.emptySet()),
- stateCb, messageCb);
- ArgumentCaptor<ISipDelegate> captor = ArgumentCaptor.forClass(ISipDelegate.class);
- verify(stateCb).onCreated(captor.capture(), anyList());
- assertNotNull(captor.getValue());
- return captor.getValue();
- }
-
- private void destroySipDelegate(TestSipTransport transport, ISipDelegate delegate,
- int reason) throws Exception {
- ISipTransport transportBinder = transport.getBinder();
- transportBinder.destroySipDelegate(delegate, reason);
- }
-}
diff --git a/tests/telephonytests/src/android/telephony/ims/TestImsService.java b/tests/telephonytests/src/android/telephony/ims/TestImsService.java
index ff4781e47a..944514a118 100644
--- a/tests/telephonytests/src/android/telephony/ims/TestImsService.java
+++ b/tests/telephonytests/src/android/telephony/ims/TestImsService.java
@@ -36,8 +36,6 @@ public class TestImsService extends android.telephony.ims.ImsService {
public ImsFeatureConfiguration testFeatureConfig;
- public long testCaps;
-
public TestImsService(Context context) {
attachBaseContext(context);
MockitoAnnotations.initMocks(this);
@@ -60,9 +58,4 @@ public class TestImsService extends android.telephony.ims.ImsService {
public ImsFeatureConfiguration querySupportedImsFeatures() {
return testFeatureConfig;
}
-
- @Override
- public long getImsServiceCapabilities() {
- return testCaps;
- }
}
diff --git a/tests/telephonytests/src/android/telephony/ims/TestMmTelFeature.java b/tests/telephonytests/src/android/telephony/ims/TestMmTelFeature.java
index 67b9bad410..fc1d67007a 100644
--- a/tests/telephonytests/src/android/telephony/ims/TestMmTelFeature.java
+++ b/tests/telephonytests/src/android/telephony/ims/TestMmTelFeature.java
@@ -28,17 +28,12 @@ import android.telephony.ims.stub.ImsMultiEndpointImplBase;
import android.telephony.ims.stub.ImsRegistrationImplBase;
import android.telephony.ims.stub.ImsUtImplBase;
-import java.util.Set;
-import java.util.concurrent.CountDownLatch;
-
public class TestMmTelFeature extends MmTelFeature {
public boolean queryConfigurationResult = false;
public int setCapabilitiesResult = ImsFeature.CAPABILITY_SUCCESS;
public CapabilityChangeRequest lastRequest;
public boolean isUtInterfaceCalled = false;
- public CountDownLatch configuredRtpHeaderExtensions = new CountDownLatch(1);
- Set<RtpHeaderExtensionType> receivedExtensions = null;
private final TestImsCallSession mCallSession = new TestImsCallSession();
private class TestImsCallSession extends ImsCallSessionImplBase {
@@ -66,12 +61,6 @@ public class TestMmTelFeature extends MmTelFeature {
}
@Override
- public void changeOfferedRtpHeaderExtensionTypes(Set<RtpHeaderExtensionType> types) {
- receivedExtensions = types;
- configuredRtpHeaderExtensions.countDown();
- }
-
- @Override
public ImsCallSessionImplBase createCallSession(ImsCallProfile profile) {
return mCallSession;
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/AdnRecordTest.java b/tests/telephonytests/src/com/android/internal/telephony/AdnRecordTest.java
index 8fe809c9f0..3b786b0162 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/AdnRecordTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/AdnRecordTest.java
@@ -16,23 +16,19 @@
package com.android.internal.telephony;
-import static com.google.common.truth.Truth.assertThat;
-
import android.os.Parcel;
+import java.util.Arrays;
+import junit.framework.TestCase;
import android.test.suitebuilder.annotation.SmallTest;
import com.android.internal.telephony.uicc.AdnRecord;
import com.android.internal.telephony.uicc.IccUtils;
-import junit.framework.TestCase;
-
-import java.util.Arrays;
-
/**
* {@hide}
*/
public class AdnRecordTest extends TestCase {
-
+
@SmallTest
public void testBasic() throws Exception {
AdnRecord adn;
@@ -193,20 +189,6 @@ public class AdnRecordTest extends TestCase {
assertEquals(adn.getNumber(), copy.getNumber());
assertTrue(Arrays.equals(adn.getEmails(), copy.getEmails()));
}
-
- public void testGetMaxAlphaTagBytes() {
- assertThat(AdnRecord.getMaxAlphaTagBytes(-1)).isEqualTo(0);
- assertThat(AdnRecord.getMaxAlphaTagBytes(0)).isEqualTo(0);
- assertThat(AdnRecord.getMaxAlphaTagBytes(5)).isEqualTo(0);
- assertThat(AdnRecord.getMaxAlphaTagBytes(14)).isEqualTo(0);
- assertThat(AdnRecord.getMaxAlphaTagBytes(15)).isEqualTo(1);
- assertThat(AdnRecord.getMaxAlphaTagBytes(25)).isEqualTo(11);
- assertThat(AdnRecord.getMaxAlphaTagBytes(30)).isEqualTo(16);
- }
-
- public void testGetMaxPhoneNumberDigits() {
- assertThat(AdnRecord.getMaxPhoneNumberDigits()).isEqualTo(20);
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/BarringInfoTest.java b/tests/telephonytests/src/com/android/internal/telephony/BarringInfoTest.java
index 7718774d2d..6720b41287 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/BarringInfoTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/BarringInfoTest.java
@@ -49,12 +49,12 @@ public class BarringInfoTest {
BarringInfo.BARRING_SERVICE_TYPE_SMS,
};
- /** Return a placeholder set of barring info */
+ /** Return a dummy set of barring info */
private static SparseArray<BarringServiceInfo> getBarringServiceInfos() {
return getBarringServiceInfos(false);
}
- /** Return a placeholder set of barring info
+ /** Return a dummy set of barring info
*
* @param isConditionallyBarred set the flag for whether the conditionally barred service has
* been evaluated and is actually barred based on the conditional barring parameters.
diff --git a/tests/telephonytests/src/com/android/internal/telephony/CarrierDisplayNameResolverTest.java b/tests/telephonytests/src/com/android/internal/telephony/CarrierDisplayNameResolverTest.java
index ff18a07720..fd9ef94822 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/CarrierDisplayNameResolverTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/CarrierDisplayNameResolverTest.java
@@ -173,99 +173,4 @@ public class CarrierDisplayNameResolverTest extends TelephonyTest {
CarrierDisplayNameData data = mCdnr.getCarrierDisplayNameData();
assertThat(data.getPlmn()).isEqualTo(PNN_HOME_NAME_FROM_USIM);
}
-
- @Test
- public void testShouldShowPLMNFromSourceBandOverride_notShowPLMN() {
- // Update ef records from brand override
- mCdnr.updateEfForBrandOverride("spn from brand override");
-
- mSS.setRoaming(ROAMING);
-
- CarrierDisplayNameData data = mCdnr.getCarrierDisplayNameData();
- assertThat(data.shouldShowPlmn()).isFalse();
- }
-
- @Test
- public void testShouldShowSPNFromSourceCC_conditionOverrideShowPLMN_notShowSPN() {
- // Carrier config source > sim record source
- mConfig.putInt(CarrierConfigManager.KEY_SPN_DISPLAY_CONDITION_OVERRIDE_INT, 1);
-
- // Update ef records from carrier config
- mCdnr.updateEfFromCarrierConfig(mConfig);
-
- CarrierDisplayNameData data = mCdnr.getCarrierDisplayNameData();
- assertThat(data.shouldShowSpn()).isFalse();
- }
-
- @Test
- public void testShouldShowPLMNFromSourceCC_conditionOverrideShowPLMN_shouldShowPLMN() {
- // Carrier config source > sim record source
- mConfig.putInt(CarrierConfigManager.KEY_SPN_DISPLAY_CONDITION_OVERRIDE_INT, 1);
-
- // Update ef records from carrier config
- mCdnr.updateEfFromCarrierConfig(mConfig);
-
- CarrierDisplayNameData data = mCdnr.getCarrierDisplayNameData();
- assertThat(data.shouldShowPlmn()).isTrue();
- }
-
- @Test
- public void testShouldShowPLMNLongName_plmnNotInProvidedList_showPLMNLongName() {
- // Carrier config source > sim record source
- mConfig.putInt(CarrierConfigManager.KEY_SPN_DISPLAY_CONDITION_OVERRIDE_INT, 1);
-
- // Update ef records from carrier config
- mCdnr.updateEfFromCarrierConfig(mConfig);
-
- SIMRecords usim = Mockito.mock(SIMRecords.class);
- doReturn(SPN_FROM_USIM).when(usim).getServiceProviderName();
- mCdnr.updateEfFromUsim(usim);
-
- CarrierDisplayNameData data = mCdnr.getCarrierDisplayNameData();
-
- assertThat(data.shouldShowPlmn()).isTrue();
- assertThat(data.getPlmn()).isEqualTo("long name");
- }
-
- @Test
- public void testShouldShowPLMNShortName_plmnNotInProvidedList_showPLMNShortName() {
- // Carrier config source > sim record source
- mConfig.putInt(CarrierConfigManager.KEY_SPN_DISPLAY_CONDITION_OVERRIDE_INT, 1);
-
- // Update ef records from carrier config
- mCdnr.updateEfFromCarrierConfig(mConfig);
-
- SIMRecords usim = Mockito.mock(SIMRecords.class);
- doReturn(SPN_FROM_USIM).when(usim).getServiceProviderName();
- mCdnr.updateEfFromUsim(usim);
-
- // long name empty
- mSS.setOperatorName("", "short name", HOME_PLMN_NUMERIC);
-
- CarrierDisplayNameData data = mCdnr.getCarrierDisplayNameData();
-
- assertThat(data.shouldShowPlmn()).isTrue();
- assertThat(data.getPlmn()).isEqualTo("short name");
- }
-
- @Test
- public void testShouldShowPLMNNumeric_plmnNotInProvidedList_showPLMNNumeric() {
- // Carrier config source > sim record source
- mConfig.putInt(CarrierConfigManager.KEY_SPN_DISPLAY_CONDITION_OVERRIDE_INT, 1);
-
- // Update ef records from carrier config
- mCdnr.updateEfFromCarrierConfig(mConfig);
-
- SIMRecords usim = Mockito.mock(SIMRecords.class);
- doReturn(SPN_FROM_USIM).when(usim).getServiceProviderName();
- mCdnr.updateEfFromUsim(usim);
-
- // long name and short name empty
- mSS.setOperatorName("", "", HOME_PLMN_NUMERIC);
-
- CarrierDisplayNameData data = mCdnr.getCarrierDisplayNameData();
-
- assertThat(data.shouldShowPlmn()).isTrue();
- assertThat(data.getPlmn()).isEqualTo(HOME_PLMN_NUMERIC);
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/CarrierKeyDownloadMgrTest.java b/tests/telephonytests/src/com/android/internal/telephony/CarrierKeyDownloadMgrTest.java
index 4cd5d68960..5a7f688ff2 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/CarrierKeyDownloadMgrTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/CarrierKeyDownloadMgrTest.java
@@ -15,14 +15,13 @@
*/
package com.android.internal.telephony;
-import static junit.framework.Assert.assertNull;
+import static android.preference.PreferenceManager.getDefaultSharedPreferences;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -31,10 +30,10 @@ import static org.mockito.Mockito.when;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
+import android.content.SharedPreferences;
import android.os.PersistableBundle;
import android.telephony.CarrierConfigManager;
import android.telephony.ImsiEncryptionInfo;
-import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.test.suitebuilder.annotation.SmallTest;
import android.testing.AndroidTestingRunner;
@@ -105,8 +104,7 @@ public class CarrierKeyDownloadMgrTest extends TelephonyTest {
String dateExpected = dt.format(expectedCal.getTime());
ImsiEncryptionInfo imsiEncryptionInfo = new ImsiEncryptionInfo("mcc", "mnc", 1,
"keyIdentifier", publicKey, date);
- when(mPhone.getCarrierInfoForImsiEncryption(anyInt(), anyBoolean()))
- .thenReturn(imsiEncryptionInfo);
+ when(mPhone.getCarrierInfoForImsiEncryption(anyInt())).thenReturn(imsiEncryptionInfo);
Date expirationDate = new Date(mCarrierKeyDM.getExpirationDate());
assertTrue(dt.format(expirationDate).equals(dateExpected));
}
@@ -132,8 +130,7 @@ public class CarrierKeyDownloadMgrTest extends TelephonyTest {
Date maxExpirationDate = maxExpirationCal.getTime();
ImsiEncryptionInfo imsiEncryptionInfo = new ImsiEncryptionInfo("mcc", "mnc", 1,
"keyIdentifier", publicKey, date);
- when(mPhone.getCarrierInfoForImsiEncryption(anyInt(), anyBoolean()))
- .thenReturn(imsiEncryptionInfo);
+ when(mPhone.getCarrierInfoForImsiEncryption(anyInt())).thenReturn(imsiEncryptionInfo);
Date expirationDate = new Date(mCarrierKeyDM.getExpirationDate());
assertTrue(expirationDate.before(minExpirationDate));
assertTrue(expirationDate.after(maxExpirationDate));
@@ -154,7 +151,7 @@ public class CarrierKeyDownloadMgrTest extends TelephonyTest {
}
ImsiEncryptionInfo imsiEncryptionInfo = new ImsiEncryptionInfo("310", "270", 2,
"key1=value", keyInfo.first, new Date(keyInfo.second));
- String mccMnc = "310270";
+ String mccMnc = "310:270";
mCarrierKeyDM.parseJsonAndPersistKey(mJsonStr, mccMnc);
verify(mPhone, times(2)).setCarrierInfoForImsiEncryption(
(Matchers.refEq(imsiEncryptionInfo)));
@@ -175,7 +172,7 @@ public class CarrierKeyDownloadMgrTest extends TelephonyTest {
}
ImsiEncryptionInfo imsiEncryptionInfo = new ImsiEncryptionInfo("310", "270", 2,
"key1=value", keyInfo.first, new Date(keyInfo.second));
- String mccMnc = "310270";
+ String mccMnc = "310:270";
mCarrierKeyDM.parseJsonAndPersistKey(mJsonStr1, mccMnc);
verify(mPhone, times(2)).setCarrierInfoForImsiEncryption(
(Matchers.refEq(imsiEncryptionInfo)));
@@ -188,7 +185,7 @@ public class CarrierKeyDownloadMgrTest extends TelephonyTest {
@Test
@SmallTest
public void testParseBadJsonFail() {
- String mccMnc = "310290";
+ String mccMnc = "310:290";
String badJsonStr = "{badJsonString}";
mCarrierKeyDM.parseJsonAndPersistKey(badJsonStr, mccMnc);
verify(mPhone, times(0)).setCarrierInfoForImsiEncryption(any());
@@ -201,13 +198,9 @@ public class CarrierKeyDownloadMgrTest extends TelephonyTest {
@Test
@SmallTest
public void testIsValidDownload() {
- String currentMccMnc = "310260";
- long currentDownloadId = 1;
- // mock downloadId to match
- mCarrierKeyDM.mMccMncForDownload = currentMccMnc;
- mCarrierKeyDM.mDownloadId = currentDownloadId;
-
- assertTrue(mCarrierKeyDM.isValidDownload(currentMccMnc, currentDownloadId));
+ String mccMnc = "310:260";
+ when(mTelephonyManager.getSimOperator(anyInt())).thenReturn("310260");
+ assertTrue(mCarrierKeyDM.isValidDownload(mccMnc));
}
/**
@@ -217,18 +210,9 @@ public class CarrierKeyDownloadMgrTest extends TelephonyTest {
@Test
@SmallTest
public void testIsValidDownloadFail() {
- String currentMccMnc = "310260";
- long currentDownloadId = 1;
-
- // mock downloadId to match, mccmnc so it doesn't match
- mCarrierKeyDM.mMccMncForDownload = "310290";
- mCarrierKeyDM.mDownloadId = currentDownloadId;
- assertFalse(mCarrierKeyDM.isValidDownload(currentMccMnc, currentDownloadId));
-
- // pass in mccmnc to match, and mock shared pref downloadId so it doesn't match
- currentMccMnc = "310290";
- mCarrierKeyDM.mDownloadId = currentDownloadId + 1;
- assertFalse(mCarrierKeyDM.isValidDownload(currentMccMnc, currentDownloadId));
+ String mccMnc = "310:290";
+ when(mTelephonyManager.getSimOperator(anyInt())).thenReturn("310260");
+ assertFalse(mCarrierKeyDM.isValidDownload(mccMnc));
}
/**
@@ -256,10 +240,11 @@ public class CarrierKeyDownloadMgrTest extends TelephonyTest {
@Test
@SmallTest
public void testDownloadComplete() {
- String mccMnc = "310260";
- long downloadId = 1;
- mCarrierKeyDM.mMccMncForDownload = mccMnc;
- mCarrierKeyDM.mDownloadId = downloadId;
+ SharedPreferences.Editor editor = getDefaultSharedPreferences(mContext).edit();
+ String mccMnc = "310:260";
+ int slotId = mPhone.getPhoneId();
+ editor.putString("CARRIER_KEY_DM_MCC_MNC" + slotId, mccMnc);
+ editor.commit();
SimpleDateFormat dt = new SimpleDateFormat("yyyy-mm-dd");
Calendar expectedCal = new GregorianCalendar();
@@ -268,7 +253,6 @@ public class CarrierKeyDownloadMgrTest extends TelephonyTest {
when(mTelephonyManager.getSimOperator(anyInt())).thenReturn("310260");
Intent mIntent = new Intent(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
- mIntent.putExtra(DownloadManager.EXTRA_DOWNLOAD_ID, downloadId);
mContext.sendBroadcast(mIntent);
processAllMessages();
Date expirationDate = new Date(mCarrierKeyDM.getExpirationDate());
@@ -294,30 +278,9 @@ public class CarrierKeyDownloadMgrTest extends TelephonyTest {
mIntent.putExtra(PhoneConstants.PHONE_KEY, 0);
mContext.sendBroadcast(mIntent);
processAllMessages();
- assertEquals("310260", mCarrierKeyDM.mMccMncForDownload);
- }
-
- /**
- * Tests sending the ACTION_CARRIER_CONFIG_CHANGED intent with an empty key.
- * Verify that the carrier keys are removed if IMSI_KEY_DOWNLOAD_URL_STRING is null.
- */
- @Test
- @SmallTest
- public void testCarrierConfigChangedEmptyKey() {
- CarrierConfigManager carrierConfigManager = (CarrierConfigManager)
- mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE);
- int slotId = mPhone.getPhoneId();
- PersistableBundle bundle = carrierConfigManager.getConfigForSubId(slotId);
- bundle.putInt(CarrierConfigManager.IMSI_KEY_AVAILABILITY_INT, 3);
- bundle.putString(CarrierConfigManager.IMSI_KEY_DOWNLOAD_URL_STRING, null);
-
- Intent mIntent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
- mIntent.putExtra(PhoneConstants.PHONE_KEY, 0);
- mContext.sendBroadcast(mIntent);
- processAllMessages();
- assertNull(mCarrierKeyDM.mMccMncForDownload);
-
- verify(mPhone).deleteCarrierInfoForImsiEncryption();
+ SharedPreferences preferences = getDefaultSharedPreferences(mContext);
+ String mccMnc = preferences.getString("CARRIER_KEY_DM_MCC_MNC" + slotId, null);
+ assertTrue(mccMnc.equals("310:260"));
}
/**
@@ -329,17 +292,19 @@ public class CarrierKeyDownloadMgrTest extends TelephonyTest {
public void testAlarmRenewal() {
CarrierConfigManager carrierConfigManager = (CarrierConfigManager)
mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE);
- int slotIndex = SubscriptionManager.getSlotIndex(mPhone.getSubId());
- PersistableBundle bundle = carrierConfigManager.getConfigForSubId(slotIndex);
+ int slotId = mPhone.getPhoneId();
+ PersistableBundle bundle = carrierConfigManager.getConfigForSubId(slotId);
bundle.putInt(CarrierConfigManager.IMSI_KEY_AVAILABILITY_INT, 3);
bundle.putString(CarrierConfigManager.IMSI_KEY_DOWNLOAD_URL_STRING, mURL);
when(mTelephonyManager.getSimOperator(anyInt())).thenReturn("310260");
- Intent mIntent = new Intent("com.android.internal.telephony.carrier_key_download_alarm");
- mIntent.putExtra(SubscriptionManager.EXTRA_SLOT_INDEX, slotIndex);
+ Intent mIntent = new Intent("com.android.internal.telephony.carrier_key_download_alarm"
+ + slotId);
mContext.sendBroadcast(mIntent);
processAllMessages();
- assertEquals("310260", mCarrierKeyDM.mMccMncForDownload);
+ SharedPreferences preferences = getDefaultSharedPreferences(mContext);
+ String mccMnc = preferences.getString("CARRIER_KEY_DM_MCC_MNC" + slotId, null);
+ assertTrue(mccMnc.equals("310:260"));
}
/**
@@ -357,7 +322,7 @@ public class CarrierKeyDownloadMgrTest extends TelephonyTest {
ImsiEncryptionInfo imsiEncryptionInfo = new ImsiEncryptionInfo("310", "270",
TelephonyManager.KEY_TYPE_WLAN, "key1=value", keyInfo.first,
new Date(CERT_EXPIRATION));
- String mccMnc = "310270";
+ String mccMnc = "310:270";
mCarrierKeyDM.parseJsonAndPersistKey(mJsonStr3GppSpec, mccMnc);
verify(mPhone).setCarrierInfoForImsiEncryption(
(Matchers.refEq(imsiEncryptionInfo)));
diff --git a/tests/telephonytests/src/com/android/internal/telephony/CarrierPrivilegesTrackerTest.java b/tests/telephonytests/src/com/android/internal/telephony/CarrierPrivilegesTrackerTest.java
index aa5d726e4c..79c8042347 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/CarrierPrivilegesTrackerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/CarrierPrivilegesTrackerTest.java
@@ -46,7 +46,6 @@ import android.os.Message;
import android.os.PersistableBundle;
import android.telephony.CarrierConfigManager;
import android.telephony.TelephonyManager;
-import android.telephony.UiccAccessRule;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
import android.util.ArraySet;
@@ -115,8 +114,8 @@ public class CarrierPrivilegesTrackerTest extends TelephonyTest {
mHandler = new CarrierPrivilegesTrackerTestHandler();
// set mock behavior so CarrierPrivilegeTracker initializes with no privileged UIDs
- setupCarrierConfigRules();
- setupSimLoadedRules();
+ setupCarrierConfigCerts();
+ setupSimLoadedCerts();
setupInstalledPackages();
}
@@ -125,33 +124,16 @@ public class CarrierPrivilegesTrackerTest extends TelephonyTest {
super.tearDown();
}
- /** @param rules can either be "hash" or "hash:package[,package...]" */
- private void setupCarrierConfigRules(String... rules) {
- mCarrierConfigs.putStringArray(KEY_CARRIER_CERTIFICATE_STRING_ARRAY, rules);
+ private void setupCarrierConfigCerts(String... certHashes) {
+ mCarrierConfigs.putStringArray(KEY_CARRIER_CERTIFICATE_STRING_ARRAY, certHashes);
mCarrierConfigs.putBoolean(KEY_CARRIER_CONFIG_APPLIED_BOOL, true);
when(mCarrierConfigManager.getConfigForSubId(SUB_ID)).thenReturn(mCarrierConfigs);
}
- private static String carrierConfigRuleString(String certificateHash, String... packageNames) {
- if (packageNames == null || packageNames.length == 0) {
- return certificateHash;
- }
- return certificateHash + ':' + String.join(",", packageNames);
- }
-
- private void setupSimLoadedRules(UiccAccessRule... certHashes) {
+ private void setupSimLoadedCerts(String... certHashes) {
when(mTelephonyManager.hasIccCard(PHONE_ID)).thenReturn(true);
- when(mUiccProfile.getCarrierPrivilegeAccessRules()).thenReturn(Arrays.asList(certHashes));
- }
-
- private static UiccAccessRule ruleWithHashOnly(String certificateHash) {
- return ruleWithHashAndPackage(certificateHash, null /* packageName */);
- }
-
- private static UiccAccessRule ruleWithHashAndPackage(
- String certificateHash, String packageName) {
- return new UiccAccessRule(
- IccUtils.hexStringToBytes(certificateHash), packageName, /* accessType= */ 0L);
+ when(mTelephonyManager.getCertsFromCarrierPrivilegeAccessRules())
+ .thenReturn(Arrays.asList(certHashes));
}
private void setupInstalledPackages(PackageCertInfo... pkgCertInfos) throws Exception {
@@ -183,8 +165,7 @@ public class CarrierPrivilegesTrackerTest extends TelephonyTest {
* <p>The initial configuration of the CarrierPrivilegesTracker will be based on the current
* state of certificate hashes and installed packages.
*
- * <p>See {@link #setupCarrierConfigRules}, {@link #setupSimLoadedRules}, {@link
- * #setupInstalledPackages}.
+ * See #setupCarrierConfigCerts, #setupSimLoadedCerts, #setupInstalledPackages.
*/
private CarrierPrivilegesTracker createCarrierPrivilegesTracker() throws Exception {
CarrierPrivilegesTracker cpt =
@@ -199,8 +180,7 @@ public class CarrierPrivilegesTrackerTest extends TelephonyTest {
}
private void setupCarrierPrivilegesTrackerWithCarrierConfigUids() throws Exception {
- setupCarrierConfigRules(
- carrierConfigRuleString(getHash(CERT_1)), carrierConfigRuleString(getHash(CERT_2)));
+ setupCarrierConfigCerts(getHash(CERT_1), getHash(CERT_2));
setupInstalledPackages(
new PackageCertInfo(PACKAGE_1, CERT_1, USER_1, UID_1),
new PackageCertInfo(PACKAGE_2, CERT_2, USER_1, UID_2));
@@ -208,7 +188,7 @@ public class CarrierPrivilegesTrackerTest extends TelephonyTest {
}
private void setupCarrierPrivilegesTrackerWithSimLoadedUids() throws Exception {
- setupSimLoadedRules(ruleWithHashOnly(getHash(CERT_1)), ruleWithHashOnly(getHash(CERT_2)));
+ setupSimLoadedCerts(getHash(CERT_1), getHash(CERT_2));
setupInstalledPackages(
new PackageCertInfo(PACKAGE_1, CERT_1, USER_1, UID_1),
new PackageCertInfo(PACKAGE_2, CERT_2, USER_1, UID_2));
@@ -222,13 +202,15 @@ public class CarrierPrivilegesTrackerTest extends TelephonyTest {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
- case REGISTRANT_WHAT:
+ case REGISTRANT_WHAT: {
AsyncResult asyncResult = (AsyncResult) msg.obj;
privilegedUids = (int[]) asyncResult.result;
numUidUpdates++;
break;
- default:
+ }
+ default: {
fail("Unexpected msg received. what=" + msg.what);
+ }
}
}
@@ -289,8 +271,10 @@ public class CarrierPrivilegesTrackerTest extends TelephonyTest {
new PackageCertInfo(PACKAGE_1, CERT_1, USER_1, UID_1),
new PackageCertInfo(PACKAGE_2, CERT_2, USER_1, UID_2));
mCarrierPrivilegesTracker = createCarrierPrivilegesTracker();
- setupCarrierConfigRules(
- carrierConfigRuleString(getHash(CERT_1)), carrierConfigRuleString(getHash(CERT_2)));
+ mCarrierConfigs.putStringArray(
+ KEY_CARRIER_CERTIFICATE_STRING_ARRAY,
+ new String[] {getHash(CERT_1), getHash(CERT_2)});
+ when(mCarrierConfigManager.getConfigForSubId(SUB_ID)).thenReturn(mCarrierConfigs);
sendCarrierConfigChangedIntent(SUB_ID, PHONE_ID);
mTestableLooper.processAllMessages();
@@ -335,34 +319,6 @@ public class CarrierPrivilegesTrackerTest extends TelephonyTest {
}
@Test
- public void testCarrierConfigUpdatedExplicitPackageNames() throws Exception {
- // Start with privileges specified just by wildcard certificate hashes, verify specifying
- // package names clears privileges on UIDs that don't match the updated rules.
- setupCarrierPrivilegesTrackerWithCarrierConfigUids();
-
- // Package 1 keeps its privileges by matching the first rule; the second rule no longer
- // matches package 2.
- setupCarrierConfigRules(
- carrierConfigRuleString(getHash(CERT_1), PACKAGE_1),
- carrierConfigRuleString(getHash(CERT_2), PACKAGE_1));
-
- sendCarrierConfigChangedIntent(SUB_ID, PHONE_ID);
- mTestableLooper.processAllMessages();
-
- verifyPrivilegedUids(new int[] {UID_1} /* expectedUids */, 1 /* expectedUidUpdates */);
-
- // Give package 2 privileges again.
- setupCarrierConfigRules(
- carrierConfigRuleString(getHash(CERT_1), PACKAGE_1),
- carrierConfigRuleString(getHash(CERT_2), PACKAGE_1, PACKAGE_2));
-
- sendCarrierConfigChangedIntent(SUB_ID, PHONE_ID);
- mTestableLooper.processAllMessages();
-
- verifyPrivilegedUids(PRIVILEGED_UIDS /* expectedUids */, 2 /* expectedUidUpdates */);
- }
-
- @Test
public void testSimCardStateChanged() throws Exception {
// Start with packages installed and no certs
setupInstalledPackages(
@@ -370,7 +326,9 @@ public class CarrierPrivilegesTrackerTest extends TelephonyTest {
new PackageCertInfo(PACKAGE_2, CERT_2, USER_1, UID_2));
mCarrierPrivilegesTracker = createCarrierPrivilegesTracker();
- setupSimLoadedRules(ruleWithHashOnly(getHash(CERT_1)), ruleWithHashOnly(getHash(CERT_2)));
+ when(mTelephonyManager.getCertsFromCarrierPrivilegeAccessRules())
+ .thenReturn(Arrays.asList(getHash(CERT_1), getHash(CERT_2)));
+ when(mTelephonyManager.hasIccCard(PHONE_ID)).thenReturn(true);
sendSimCardStateChangedIntent(PHONE_ID, SIM_STATE_LOADED);
mTestableLooper.processAllMessages();
@@ -386,7 +344,9 @@ public class CarrierPrivilegesTrackerTest extends TelephonyTest {
new PackageCertInfo(PACKAGE_2, CERT_2, USER_1, UID_2));
mCarrierPrivilegesTracker = createCarrierPrivilegesTracker();
- setupSimLoadedRules(ruleWithHashOnly(getHash(CERT_1)), ruleWithHashOnly(getHash(CERT_2)));
+ when(mTelephonyManager.getCertsFromCarrierPrivilegeAccessRules())
+ .thenReturn(Arrays.asList(getHash(CERT_1), getHash(CERT_2)));
+ when(mTelephonyManager.hasIccCard(PHONE_ID)).thenReturn(true);
sendSimApplicationStateChangedIntent(PHONE_ID, SIM_STATE_LOADED);
mTestableLooper.processAllMessages();
@@ -432,38 +392,9 @@ public class CarrierPrivilegesTrackerTest extends TelephonyTest {
}
@Test
- public void testSimStateChangedExplicitPackageNames() throws Exception {
- // Start with privileges specified just by wildcard certificate hashes, verify specifying
- // package names clears privileges on UIDs that don't match the updated rules.
- setupCarrierPrivilegesTrackerWithSimLoadedUids();
-
- // Package 1 keeps its privileges by matching the first rule; the second rule no longer
- // matches package 2.
- setupSimLoadedRules(
- ruleWithHashAndPackage(getHash(CERT_1), PACKAGE_1),
- ruleWithHashAndPackage(getHash(CERT_2), PACKAGE_1));
-
- sendSimCardStateChangedIntent(PHONE_ID, SIM_STATE_LOADED);
- mTestableLooper.processAllMessages();
-
- verifyPrivilegedUids(new int[] {UID_1} /* expectedUids */, 1 /* expectedUidUpdates */);
-
- // Give package 2 privileges again.
- setupSimLoadedRules(
- ruleWithHashAndPackage(getHash(CERT_1), PACKAGE_1),
- ruleWithHashAndPackage(getHash(CERT_2), PACKAGE_1),
- ruleWithHashAndPackage(getHash(CERT_2), PACKAGE_2));
-
- sendSimCardStateChangedIntent(PHONE_ID, SIM_STATE_LOADED);
- mTestableLooper.processAllMessages();
-
- verifyPrivilegedUids(PRIVILEGED_UIDS /* expectedUids */, 2 /* expectedUidUpdates */);
- }
-
- @Test
public void testPackageAdded() throws Exception {
// Start with certs and no packages installed
- setupCarrierConfigRules(carrierConfigRuleString(getHash(CERT_1)));
+ setupCarrierConfigCerts(getHash(CERT_1));
mCarrierPrivilegesTracker = createCarrierPrivilegesTracker();
setupInstalledPackages(new PackageCertInfo(PACKAGE_1, CERT_1, USER_1, UID_1));
@@ -477,8 +408,7 @@ public class CarrierPrivilegesTrackerTest extends TelephonyTest {
@Test
public void testPackageAddedMultipleUsers() throws Exception {
// Start with certs and no packages installed
- setupCarrierConfigRules(
- carrierConfigRuleString(getHash(CERT_1)), carrierConfigRuleString(getHash(CERT_2)));
+ setupCarrierConfigCerts(getHash(CERT_1), getHash(CERT_2));
mCarrierPrivilegesTracker = createCarrierPrivilegesTracker();
setupInstalledPackages(
@@ -494,8 +424,7 @@ public class CarrierPrivilegesTrackerTest extends TelephonyTest {
@Test
public void testPackageReplaced() throws Exception {
// Start with certs and an unmatched package
- setupCarrierConfigRules(
- carrierConfigRuleString(getHash(CERT_1)), carrierConfigRuleString(getHash(CERT_2)));
+ setupCarrierConfigCerts(getHash(CERT_1), getHash(CERT_2));
setupInstalledPackages(new PackageCertInfo(PACKAGE_1, CERT_3, USER_1, UID_1));
mCarrierPrivilegesTracker = createCarrierPrivilegesTracker();
@@ -512,8 +441,7 @@ public class CarrierPrivilegesTrackerTest extends TelephonyTest {
@Test
public void testPackageAddedOrReplacedNoSignatures() throws Exception {
// Start with certs and packages installed
- setupCarrierConfigRules(
- carrierConfigRuleString(getHash(CERT_1)), carrierConfigRuleString(getHash(CERT_2)));
+ setupCarrierConfigCerts(getHash(CERT_1), getHash(CERT_2));
setupInstalledPackages(
new PackageCertInfo(PACKAGE_1, CERT_1, USER_1, UID_1),
new PackageCertInfo(PACKAGE_2, CERT_2, USER_1, UID_2));
@@ -534,8 +462,7 @@ public class CarrierPrivilegesTrackerTest extends TelephonyTest {
@Test
public void testPackageAddedOrReplacedSignatureChanged() throws Exception {
// Start with certs and packages installed
- setupCarrierConfigRules(
- carrierConfigRuleString(getHash(CERT_1)), carrierConfigRuleString(getHash(CERT_2)));
+ setupCarrierConfigCerts(getHash(CERT_1), getHash(CERT_2));
setupInstalledPackages(
new PackageCertInfo(PACKAGE_1, CERT_1, USER_1, UID_1),
new PackageCertInfo(PACKAGE_2, CERT_2, USER_1, UID_2));
@@ -555,8 +482,7 @@ public class CarrierPrivilegesTrackerTest extends TelephonyTest {
@Test
public void testPackageRemoved() throws Exception {
// Start with certs and packages installed
- setupCarrierConfigRules(
- carrierConfigRuleString(getHash(CERT_1)), carrierConfigRuleString(getHash(CERT_2)));
+ setupCarrierConfigCerts(getHash(CERT_1), getHash(CERT_2));
setupInstalledPackages(
new PackageCertInfo(PACKAGE_1, CERT_1, USER_1, UID_1),
new PackageCertInfo(PACKAGE_2, CERT_2, USER_1, UID_2));
@@ -605,7 +531,9 @@ public class CarrierPrivilegesTrackerTest extends TelephonyTest {
mContext.sendBroadcast(new Intent(action, new Uri.Builder().path(pkgName).build()));
}
- /** Returns the SHA-1 hash (as a hex String) for the given hex String. */
+ /**
+ * Returns the SHA-1 hash (as a hex String) for the given hex String.
+ */
private static String getHash(String hexString) throws Exception {
MessageDigest sha1 = MessageDigest.getInstance(SHA_1);
byte[] result = sha1.digest(IccUtils.hexStringToBytes(hexString));
diff --git a/tests/telephonytests/src/com/android/internal/telephony/CarrierResolverTest.java b/tests/telephonytests/src/com/android/internal/telephony/CarrierResolverTest.java
index 453dbd6994..f72ee2fef8 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/CarrierResolverTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/CarrierResolverTest.java
@@ -20,7 +20,6 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.verify;
import android.database.Cursor;
import android.database.MatrixCursor;
@@ -258,15 +257,12 @@ public class CarrierResolverTest extends TelephonyTest {
assertEquals(CID_VZW, mCarrierResolver.getCarrierId());
assertEquals(NAME, mCarrierResolver.getCarrierName());
// mock apn
- doReturn(IccCardConstants.State.LOADED).when(mUiccProfile).getState();
((MockContentResolver) mContext.getContentResolver()).addProvider(
Carriers.CONTENT_URI.getAuthority(), new CarrierIdContentProvider());
mCarrierResolver.sendEmptyMessage(PREFER_APN_SET_EVENT);
processAllMessages();
assertEquals(CID_DOCOMO, mCarrierResolver.getCarrierId());
assertEquals(NAME_DOCOMO, mCarrierResolver.getCarrierName());
- verify(mCarrierConfigManager).updateConfigForPhoneId(phoneId,
- IccCardConstants.INTENT_VALUE_ICC_LOADED);
}
private class CarrierIdContentProvider extends MockContentProvider {
diff --git a/tests/telephonytests/src/com/android/internal/telephony/CarrierServiceStateTrackerTest.java b/tests/telephonytests/src/com/android/internal/telephony/CarrierServiceStateTrackerTest.java
index c3eac09a1e..27ffeefb2a 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/CarrierServiceStateTrackerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/CarrierServiceStateTrackerTest.java
@@ -31,10 +31,9 @@ import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.os.PersistableBundle;
+import android.provider.Settings;
import android.telephony.CarrierConfigManager;
-import android.telephony.RadioAccessFamily;
import android.telephony.ServiceState;
-import android.telephony.TelephonyManager;
import android.test.suitebuilder.annotation.SmallTest;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
@@ -70,15 +69,12 @@ public class CarrierServiceStateTrackerTest extends TelephonyTest {
super.setUp(getClass().getSimpleName());
mBundle = mContextFixture.getCarrierConfigBundle();
when(mPhone.getSubId()).thenReturn(SUB_ID);
-
mCarrierSST = new CarrierServiceStateTracker(mPhone, mSST);
mSpyCarrierSST = spy(mCarrierSST);
mNotificationManager = (NotificationManager) mContext.getSystemService(
Context.NOTIFICATION_SERVICE);
- setCarrierPrivilegesForSubId(true, SUB_ID);
-
setDefaultValues();
processAllMessages();
}
@@ -154,29 +150,21 @@ public class CarrierServiceStateTrackerTest extends TelephonyTest {
doReturn(true).when(mSST).isRadioOn();
doReturn(mNotificationBuilder).when(spyPrefNetworkNotification).getNotificationBuilder();
-
- long networkType = (long) RadioAccessFamily.getRafFromNetworkType(
- TelephonyManager.NETWORK_MODE_LTE_CDMA_EVDO);
- int allowedNetworkTypeReason = TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER;
- long allowedNetworkTypeValue = networkType;
- doReturn(networkType).when(mPhone).getAllowedNetworkTypes(
- TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER);
- mSpyCarrierSST.getAllowedNetworkTypesChangedListener().onAllowedNetworkTypesChanged(
- allowedNetworkTypeReason, allowedNetworkTypeValue);
-
+ String prefNetworkMode = Settings.Global.PREFERRED_NETWORK_MODE + mPhone.getSubId();
+ Settings.Global.putInt(mContext.getContentResolver(), prefNetworkMode,
+ RILConstants.NETWORK_MODE_LTE_CDMA_EVDO);
+ mSpyCarrierSST.getContentObserver().dispatchChange(false,
+ Settings.Global.getUriFor(prefNetworkMode));
processAllMessages();
verify(mNotificationManager, atLeast(1)).notify(
eq(CarrierServiceStateTracker.PREF_NETWORK_NOTIFICATION_TAG),
eq(SUB_ID), isA(Notification.class));
- networkType = (long) RadioAccessFamily.getRafFromNetworkType(
- TelephonyManager.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA);
- allowedNetworkTypeValue = networkType;
- doReturn(networkType).when(mPhone).getAllowedNetworkTypes(
- TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER);
- mSpyCarrierSST.getAllowedNetworkTypesChangedListener().onAllowedNetworkTypesChanged(
- allowedNetworkTypeReason, allowedNetworkTypeValue);
+ Settings.Global.putInt(mContext.getContentResolver(), prefNetworkMode,
+ RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA);
+ mSpyCarrierSST.getContentObserver().dispatchChange(false,
+ Settings.Global.getUriFor(prefNetworkMode));
processAllMessages();
verify(mNotificationManager, atLeast(1)).cancel(
CarrierServiceStateTracker.PREF_NETWORK_NOTIFICATION_TAG, SUB_ID);
diff --git a/tests/telephonytests/src/com/android/internal/telephony/CarrierSignalAgentTest.java b/tests/telephonytests/src/com/android/internal/telephony/CarrierSignalAgentTest.java
index 85aafcfb61..9030124f81 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/CarrierSignalAgentTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/CarrierSignalAgentTest.java
@@ -18,34 +18,20 @@ package com.android.internal.telephony;
import static android.telephony.TelephonyManager.ACTION_CARRIER_SIGNAL_PCO_VALUE;
import static android.telephony.TelephonyManager.ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED;
-import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyLong;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import android.content.ComponentName;
import android.content.Intent;
-import android.content.pm.ApplicationInfo;
import android.content.pm.ResolveInfo;
-import android.os.Build;
import android.os.Message;
import android.os.PersistableBundle;
import android.telephony.CarrierConfigManager;
-import android.telephony.DataFailCause;
-import android.telephony.SubscriptionManager;
-import android.telephony.TelephonyManager;
-import android.telephony.data.ApnSetting;
import android.test.suitebuilder.annotation.SmallTest;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
@@ -59,10 +45,7 @@ import org.mockito.Mock;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Map;
import java.util.Objects;
-import java.util.function.Function;
-import java.util.stream.Collectors;
@RunWith(AndroidTestingRunner.class)
@TestableLooper.RunWithLooper
@@ -72,38 +55,6 @@ public class CarrierSignalAgentTest extends TelephonyTest {
private PersistableBundle mBundle;
private static final String PCO_RECEIVER = "pak/PCO_RECEIVER";
private static final String DC_ERROR_RECEIVER = "pak/DC_ERROR_RECEIVER";
- private static final String LEGACY_RECEIVER = "old.pkg/LEGACY_RECEIVER";
- private static final String PCO_PACKAGE = "pak";
-
- private static final Intent FAKE_PCO_INTENT;
- private static final Intent FAKE_REDIRECTED_INTENT;
- private static final Intent FAKE_NETWORK_FAILED_INTENT;
- private static final Intent FAKE_RESET_INTENT;
- private static final Intent FAKE_DEFAULT_NETWORK_INTENT;
- static {
- FAKE_PCO_INTENT = new Intent(ACTION_CARRIER_SIGNAL_PCO_VALUE);
- FAKE_PCO_INTENT.putExtra(TelephonyManager.EXTRA_APN_TYPE, ApnSetting.TYPE_MMS);
- FAKE_PCO_INTENT.putExtra(TelephonyManager.EXTRA_APN_PROTOCOL, ApnSetting.PROTOCOL_IP);
- FAKE_PCO_INTENT.putExtra(TelephonyManager.EXTRA_PCO_ID, 500);
- FAKE_PCO_INTENT.putExtra(TelephonyManager.EXTRA_PCO_VALUE, new byte[]{1, 2, 3});
-
- FAKE_REDIRECTED_INTENT = new Intent(TelephonyManager.ACTION_CARRIER_SIGNAL_REDIRECTED);
- FAKE_REDIRECTED_INTENT.putExtra(TelephonyManager.EXTRA_APN_TYPE, ApnSetting.TYPE_MMS);
- FAKE_REDIRECTED_INTENT.putExtra(TelephonyManager.EXTRA_REDIRECTION_URL, "example.com");
-
- FAKE_NETWORK_FAILED_INTENT = new Intent(ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED);
- FAKE_NETWORK_FAILED_INTENT.putExtra(TelephonyManager.EXTRA_APN_TYPE, ApnSetting.TYPE_MMS);
- FAKE_NETWORK_FAILED_INTENT.putExtra(TelephonyManager.EXTRA_DATA_FAIL_CAUSE,
- DataFailCause.UNKNOWN_PDP_CONTEXT);
-
- FAKE_RESET_INTENT = new Intent(TelephonyManager.ACTION_CARRIER_SIGNAL_RESET);
-
- FAKE_DEFAULT_NETWORK_INTENT =
- new Intent(TelephonyManager.ACTION_CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE);
- FAKE_DEFAULT_NETWORK_INTENT.putExtra(
- TelephonyManager.EXTRA_DEFAULT_NETWORK_AVAILABLE, true);
- }
-
@Mock
ResolveInfo mResolveInfo;
@@ -113,21 +64,6 @@ public class CarrierSignalAgentTest extends TelephonyTest {
super.setUp(getClass().getSimpleName());
mBundle = mContextFixture.getCarrierConfigBundle();
mCarrierSignalAgentUT = new CarrierSignalAgent(mPhone);
-
- ComponentName legacyReceiverComponent = ComponentName.unflattenFromString(LEGACY_RECEIVER);
- ApplicationInfo fakeLegacyApplicationInfo = new ApplicationInfo();
- fakeLegacyApplicationInfo.targetSdkVersion = Build.VERSION_CODES.R;
-
- ApplicationInfo fakeApplicationInfo = new ApplicationInfo();
- fakeApplicationInfo.targetSdkVersion = Build.VERSION_CODES.CUR_DEVELOPMENT;
-
- when(mContext.getPackageManager().getApplicationInfo(
- nullable(String.class), anyInt()))
- .thenReturn(fakeApplicationInfo);
- when(mContext.getPackageManager().getApplicationInfo(
- eq(legacyReceiverComponent.getPackageName()), anyInt()))
- .thenReturn(fakeLegacyApplicationInfo);
-
processAllMessages();
logd("CarrierSignalAgentTest -Setup!");
}
@@ -142,12 +78,11 @@ public class CarrierSignalAgentTest extends TelephonyTest {
public void testNotifyManifestReceivers() throws Exception {
// Broadcast count
int count = 0;
- Intent intent = new Intent(FAKE_PCO_INTENT);
+ Intent intent = new Intent(ACTION_CARRIER_SIGNAL_PCO_VALUE);
mBundle.putStringArray(
CarrierConfigManager.KEY_CARRIER_APP_WAKE_SIGNAL_CONFIG_STRING_ARRAY,
new String[]{PCO_RECEIVER + ":" + ACTION_CARRIER_SIGNAL_PCO_VALUE,
- DC_ERROR_RECEIVER + ":" + ACTION_CARRIER_SIGNAL_PCO_VALUE,
- LEGACY_RECEIVER + ":" + TelephonyIntents.ACTION_CARRIER_SIGNAL_PCO_VALUE
+ DC_ERROR_RECEIVER + ":" + ACTION_CARRIER_SIGNAL_PCO_VALUE
});
// Verify no broadcast has been sent without carrier config
@@ -168,142 +103,18 @@ public class CarrierSignalAgentTest extends TelephonyTest {
doReturn(new ArrayList<>(Arrays.asList(mResolveInfo)))
.when(mPackageManager).queryBroadcastReceivers((Intent) any(), anyInt());
mCarrierSignalAgentUT.notifyCarrierSignalReceivers(intent);
- count += 3;
+ count += 2;
mCaptorIntent = ArgumentCaptor.forClass(Intent.class);
verify(mContext, times(count)).sendBroadcast(mCaptorIntent.capture());
logd(mCaptorIntent.getAllValues().toString());
- Map<String, Intent> componentToIntent = mCaptorIntent.getAllValues().stream()
- .collect(Collectors.toMap((i) ->
- i.getComponent() == null ? "null" : i.getComponent().flattenToString(),
- Function.identity()));
- Intent dcErrorIntent = componentToIntent.get(DC_ERROR_RECEIVER);
- assertNotNull(dcErrorIntent);
- assertEquals(ACTION_CARRIER_SIGNAL_PCO_VALUE, dcErrorIntent.getAction());
-
- Intent pcoReceiverIntent = componentToIntent.get(PCO_RECEIVER);
- assertNotNull(pcoReceiverIntent);
- assertEquals(ACTION_CARRIER_SIGNAL_PCO_VALUE, pcoReceiverIntent.getAction());
-
- Intent legacyReceiverIntent = componentToIntent.get(LEGACY_RECEIVER);
- assertNotNull(legacyReceiverIntent);
- assertEquals(TelephonyIntents.ACTION_CARRIER_SIGNAL_PCO_VALUE,
- legacyReceiverIntent.getAction());
- }
-
- @Test
- @SmallTest
- public void testLegacyConversionSupport() {
- mBundle.putStringArray(
- CarrierConfigManager.KEY_CARRIER_APP_WAKE_SIGNAL_CONFIG_STRING_ARRAY,
- new String[]{LEGACY_RECEIVER + ":" + String.join(",",
- TelephonyIntents.ACTION_CARRIER_SIGNAL_PCO_VALUE,
- TelephonyIntents.ACTION_CARRIER_SIGNAL_REDIRECTED,
- TelephonyIntents.ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED,
- TelephonyIntents.ACTION_CARRIER_SIGNAL_RESET,
- TelephonyIntents.ACTION_CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE)
- });
-
- // Trigger carrier config reloading
- mContext.sendBroadcast(new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
- processAllMessages();
-
- // Verify broadcast has been sent to two different registered manifest receivers
- doReturn(new ArrayList<>(Arrays.asList(mResolveInfo)))
- .when(mPackageManager).queryBroadcastReceivers((Intent) any(), anyInt());
-
- int broadcastCount = 1;
- {
- mCarrierSignalAgentUT.notifyCarrierSignalReceivers(new Intent(FAKE_PCO_INTENT));
- broadcastCount++;
- ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
- verify(mContext, times(broadcastCount)).sendBroadcast(intentCaptor.capture());
- Intent intent = intentCaptor.getValue();
- assertTrue(intent.hasExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX));
-
- assertEquals(TelephonyIntents.ACTION_CARRIER_SIGNAL_PCO_VALUE, intent.getAction());
- verifyLegacyApnTypes(intent, FAKE_PCO_INTENT);
- assertEquals(FAKE_PCO_INTENT.getIntExtra(
- TelephonyManager.EXTRA_PCO_ID, Integer.MAX_VALUE),
- intent.getIntExtra(TelephonyIntents.EXTRA_PCO_ID, Integer.MIN_VALUE));
- assertArrayEquals(FAKE_PCO_INTENT.getByteArrayExtra(
- TelephonyManager.EXTRA_PCO_VALUE),
- intent.getByteArrayExtra(TelephonyIntents.EXTRA_PCO_VALUE));
- }
-
- {
- mCarrierSignalAgentUT.notifyCarrierSignalReceivers(new Intent(FAKE_REDIRECTED_INTENT));
- broadcastCount++;
- ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
- verify(mContext, times(broadcastCount)).sendBroadcast(intentCaptor.capture());
- Intent intent = intentCaptor.getValue();
- assertTrue(intent.hasExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX));
-
- assertEquals(TelephonyIntents.ACTION_CARRIER_SIGNAL_REDIRECTED, intent.getAction());
- verifyLegacyApnTypes(intent, FAKE_REDIRECTED_INTENT);
- assertEquals(
- FAKE_REDIRECTED_INTENT.getStringExtra(TelephonyManager.EXTRA_REDIRECTION_URL),
- intent.getStringExtra(TelephonyIntents.EXTRA_REDIRECTION_URL));
- }
+ Intent capturedIntent = mCaptorIntent.getAllValues().get(1);
+ assertEquals(ACTION_CARRIER_SIGNAL_PCO_VALUE, capturedIntent.getAction());
+ assertEquals(DC_ERROR_RECEIVER, capturedIntent.getComponent().flattenToString());
- {
- mCarrierSignalAgentUT.notifyCarrierSignalReceivers(
- new Intent(FAKE_NETWORK_FAILED_INTENT));
- broadcastCount++;
- ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
- verify(mContext, times(broadcastCount)).sendBroadcast(intentCaptor.capture());
- Intent intent = intentCaptor.getValue();
- assertTrue(intent.hasExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX));
-
- assertEquals(TelephonyIntents.ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED,
- intent.getAction());
- verifyLegacyApnTypes(intent, FAKE_REDIRECTED_INTENT);
- assertEquals(
- FAKE_NETWORK_FAILED_INTENT.getIntExtra(
- TelephonyManager.EXTRA_DATA_FAIL_CAUSE, Integer.MAX_VALUE),
- intent.getIntExtra(TelephonyIntents.EXTRA_ERROR_CODE, Integer.MIN_VALUE));
- }
-
- {
- mCarrierSignalAgentUT.notifyCarrierSignalReceivers(new Intent(FAKE_RESET_INTENT));
- broadcastCount++;
- ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
- verify(mContext, times(broadcastCount)).sendBroadcast(intentCaptor.capture());
- Intent intent = intentCaptor.getValue();
- assertTrue(intent.hasExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX));
-
- assertEquals(TelephonyIntents.ACTION_CARRIER_SIGNAL_RESET, intent.getAction());
- }
-
- {
- mCarrierSignalAgentUT.notifyCarrierSignalReceivers(
- new Intent(FAKE_DEFAULT_NETWORK_INTENT));
- broadcastCount++;
- ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
- verify(mContext, times(broadcastCount)).sendBroadcast(intentCaptor.capture());
- Intent intent = intentCaptor.getValue();
- assertTrue(intent.hasExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX));
-
- assertEquals(TelephonyIntents.ACTION_CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE,
- intent.getAction());
-
- assertEquals(
- FAKE_DEFAULT_NETWORK_INTENT.getBooleanExtra(
- TelephonyManager.EXTRA_DEFAULT_NETWORK_AVAILABLE, false),
- intent.getBooleanExtra(TelephonyIntents.EXTRA_DEFAULT_NETWORK_AVAILABLE, true));
- }
- }
-
- private void verifyLegacyApnTypes(Intent legacyIntent, Intent originalIntent) {
- int apnType = originalIntent.getIntExtra(TelephonyManager.EXTRA_APN_TYPE,
- Integer.MAX_VALUE);
- String apnTypeString = ApnSetting.getApnTypeString(apnType);
- assertNotEquals("Unknown", apnTypeString);
-
- assertEquals(apnTypeString,
- legacyIntent.getStringExtra(TelephonyIntents.EXTRA_APN_TYPE));
- assertEquals(apnType,
- legacyIntent.getIntExtra(TelephonyIntents.EXTRA_APN_TYPE_INT, Integer.MIN_VALUE));
+ capturedIntent = mCaptorIntent.getAllValues().get(2);
+ assertEquals(ACTION_CARRIER_SIGNAL_PCO_VALUE, capturedIntent.getAction());
+ assertEquals(PCO_RECEIVER, capturedIntent.getComponent().flattenToString());
}
@Test
@@ -331,7 +142,7 @@ public class CarrierSignalAgentTest extends TelephonyTest {
verify(mContext, times(++count)).sendBroadcast(mCaptorIntent.capture());
assertEquals(ACTION_CARRIER_SIGNAL_PCO_VALUE,
mCaptorIntent.getValue().getAction());
- assertEquals(PCO_PACKAGE, mCaptorIntent.getValue().getPackage());
+ assertEquals(PCO_RECEIVER, mCaptorIntent.getValue().getComponent().flattenToString());
// Verify no broadcast has been sent to manifest receivers (bad config)
doReturn(new ArrayList<>(Arrays.asList(mResolveInfo)))
@@ -378,7 +189,7 @@ public class CarrierSignalAgentTest extends TelephonyTest {
verify(mContext, times(++count)).sendBroadcast(mCaptorIntent.capture());
assertEquals(ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED,
mCaptorIntent.getValue().getAction());
- assertEquals(PCO_PACKAGE, mCaptorIntent.getValue().getPackage());
+ assertEquals(PCO_RECEIVER, mCaptorIntent.getValue().getComponent().flattenToString());
// Both wake and no-wake signals are declared in the manifest
doReturn(new ArrayList<>(Arrays.asList(mResolveInfo)))
diff --git a/tests/telephonytests/src/com/android/internal/telephony/CellIdentityLteTest.java b/tests/telephonytests/src/com/android/internal/telephony/CellIdentityLteTest.java
index d3b3e59720..77bea60049 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/CellIdentityLteTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/CellIdentityLteTest.java
@@ -22,10 +22,7 @@ import android.telephony.CellInfo;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;
-import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collections;
-import java.util.stream.Collectors;
/** Unit tests for {@link CellIdentityLte}. */
@@ -256,15 +253,4 @@ public class CellIdentityLteTest extends AndroidTestCase {
CellIdentityLte newCi = CellIdentityLte.CREATOR.createFromParcel(p);
assertEquals(ci, newCi);
}
-
- @SmallTest
- public void testBands() {
- android.hardware.radio.V1_5.CellIdentityLte cid =
- new android.hardware.radio.V1_5.CellIdentityLte();
- cid.bands = Arrays.stream(BANDS).boxed().collect(Collectors.toCollection(ArrayList::new));
-
- CellIdentityLte cellIdentityLte = new CellIdentityLte(cid);
- assertTrue(Arrays.equals(cellIdentityLte.getBands(), BANDS));
-
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/CellSignalStrengthNrTest.java b/tests/telephonytests/src/com/android/internal/telephony/CellSignalStrengthNrTest.java
index a29447102d..a2e765ed5e 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/CellSignalStrengthNrTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/CellSignalStrengthNrTest.java
@@ -18,31 +18,19 @@ package com.android.internal.telephony;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.doReturn;
-
-import android.hardware.radio.V1_6.NrSignalStrength;
+import android.hardware.radio.V1_4.NrSignalStrength;
import android.os.Parcel;
import android.telephony.CellInfo;
import android.telephony.CellSignalStrength;
import android.telephony.CellSignalStrengthNr;
-import android.telephony.ServiceState;
+import android.test.AndroidTestCase;
import com.google.common.collect.BoundType;
import com.google.common.collect.Range;
-import org.junit.After;
-import org.junit.Before;
import org.junit.Test;
-import org.mockito.Mock;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.stream.Collectors;
-public class CellSignalStrengthNrTest extends TelephonyTest {
+public class CellSignalStrengthNrTest extends AndroidTestCase {
private static final int CSIRSRP = -123;
private static final int CSIRSRQ = -11;
private static final int ANOTHER_CSIRSRP = -111;
@@ -50,44 +38,20 @@ public class CellSignalStrengthNrTest extends TelephonyTest {
private static final int INVALID_CSIRSRP = Integer.MAX_VALUE;
private static final int INVALID_SSRSRP = Integer.MAX_VALUE;
private static final int CSISINR = 18;
- private static final int CSICQI_TABLE_INDEX = 1;
- private static final ArrayList<Byte> CSICQI_REPORT =
- new ArrayList<>(Arrays.asList((byte) 3, (byte) 2, (byte) 1));
private static final int SSRSRP = -112;
private static final int SSRSRQ = -13;
private static final int SSSINR = 32;
- @Mock
- ServiceState mSS;
-
- @Before
- public void setUp() throws Exception {
- super.setUp(this.getClass().getSimpleName());
- }
-
- @After
- public void tearDown() throws Exception {
- super.tearDown();
- }
-
- private List<Integer> getCsiCqiList() {
- return CSICQI_REPORT.stream()
- .map(cqi -> new Integer(Byte.toUnsignedInt(cqi)))
- .collect(Collectors.toList());
- }
-
@Test
public void testGetMethod() {
// GIVEN an instance of CellSignalStrengthNr
- CellSignalStrengthNr css = new CellSignalStrengthNr(CSIRSRP, CSIRSRQ, CSISINR,
- CSICQI_TABLE_INDEX, CSICQI_REPORT, SSRSRP, SSRSRQ, SSSINR);
+ CellSignalStrengthNr css = new CellSignalStrengthNr(
+ CSIRSRP, CSIRSRQ, CSISINR, SSRSRP, SSRSRQ, SSSINR);
// THEN the get method should return correct value
assertThat(css.getCsiRsrp()).isEqualTo(CSIRSRP);
assertThat(css.getCsiRsrq()).isEqualTo(CSIRSRQ);
assertThat(css.getCsiSinr()).isEqualTo(CSISINR);
- assertThat(css.getCsiCqiTableIndex()).isEqualTo(CSICQI_TABLE_INDEX);
- assertThat(css.getCsiCqiReport()).isEqualTo(getCsiCqiList());
assertThat(css.getSsRsrp()).isEqualTo(SSRSRP);
assertThat(css.getSsRsrq()).isEqualTo(SSRSRQ);
assertThat(css.getSsSinr()).isEqualTo(SSSINR);
@@ -98,22 +62,18 @@ public class CellSignalStrengthNrTest extends TelephonyTest {
public void testGetMethodWithHal() {
// GIVEN an instance of NrSignalStrength with some positive values
NrSignalStrength nrSignalStrength = new NrSignalStrength();
- nrSignalStrength.base.csiRsrp = -CSIRSRP;
- nrSignalStrength.base.csiRsrq = -CSIRSRQ;
- nrSignalStrength.base.csiSinr = CSISINR;
- nrSignalStrength.csiCqiTableIndex = CSICQI_TABLE_INDEX;
- nrSignalStrength.csiCqiReport = CSICQI_REPORT;
- nrSignalStrength.base.ssRsrp = -SSRSRP;
- nrSignalStrength.base.ssRsrq = -SSRSRQ;
- nrSignalStrength.base.ssSinr = SSSINR;
+ nrSignalStrength.csiRsrp = -CSIRSRP;
+ nrSignalStrength.csiRsrq = -CSIRSRQ;
+ nrSignalStrength.csiSinr = CSISINR;
+ nrSignalStrength.ssRsrp = -SSRSRP;
+ nrSignalStrength.ssRsrq = -SSRSRQ;
+ nrSignalStrength.ssSinr = SSSINR;
// THEN the get method should return the correct value
CellSignalStrengthNr css = new CellSignalStrengthNr(nrSignalStrength);
assertThat(css.getCsiRsrp()).isEqualTo(CSIRSRP);
assertThat(css.getCsiRsrq()).isEqualTo(CSIRSRQ);
assertThat(css.getCsiSinr()).isEqualTo(CSISINR);
- assertThat(css.getCsiCqiTableIndex()).isEqualTo(CSICQI_TABLE_INDEX);
- assertThat(css.getCsiCqiReport()).isEqualTo(getCsiCqiList());
assertThat(css.getSsRsrp()).isEqualTo(SSRSRP);
assertThat(css.getSsRsrq()).isEqualTo(SSRSRQ);
assertThat(css.getSsSinr()).isEqualTo(SSSINR);
@@ -124,22 +84,18 @@ public class CellSignalStrengthNrTest extends TelephonyTest {
public void testUnavailableValueWithHal() {
// GIVEN an instance of NrSignalStrength
NrSignalStrength nrSignalStrength = new NrSignalStrength();
- nrSignalStrength.base.csiRsrp = CellInfo.UNAVAILABLE;
- nrSignalStrength.base.csiRsrq = CellInfo.UNAVAILABLE;
- nrSignalStrength.base.csiSinr = CellInfo.UNAVAILABLE;
- nrSignalStrength.csiCqiTableIndex = CellInfo.UNAVAILABLE;
- nrSignalStrength.csiCqiReport = new ArrayList<Byte>();
- nrSignalStrength.base.ssRsrp = CellInfo.UNAVAILABLE;
- nrSignalStrength.base.ssRsrq = CellInfo.UNAVAILABLE;
- nrSignalStrength.base.ssSinr = CellInfo.UNAVAILABLE;
+ nrSignalStrength.csiRsrp = CellInfo.UNAVAILABLE;
+ nrSignalStrength.csiRsrq = CellInfo.UNAVAILABLE;
+ nrSignalStrength.csiSinr = CellInfo.UNAVAILABLE;
+ nrSignalStrength.ssRsrp = CellInfo.UNAVAILABLE;
+ nrSignalStrength.ssRsrq = CellInfo.UNAVAILABLE;
+ nrSignalStrength.ssSinr = CellInfo.UNAVAILABLE;
// THEN the get method should return unavailable value
CellSignalStrengthNr css = new CellSignalStrengthNr(nrSignalStrength);
assertThat(css.getCsiRsrp()).isEqualTo(CellInfo.UNAVAILABLE);
assertThat(css.getCsiRsrq()).isEqualTo(CellInfo.UNAVAILABLE);
assertThat(css.getCsiSinr()).isEqualTo(CellInfo.UNAVAILABLE);
- assertThat(css.getCsiCqiTableIndex()).isEqualTo(CellInfo.UNAVAILABLE);
- assertThat(css.getCsiCqiReport()).isEqualTo(Collections.emptyList());
assertThat(css.getSsRsrp()).isEqualTo(CellInfo.UNAVAILABLE);
assertThat(css.getSsRsrq()).isEqualTo(CellInfo.UNAVAILABLE);
assertThat(css.getSsSinr()).isEqualTo(CellInfo.UNAVAILABLE);
@@ -149,10 +105,10 @@ public class CellSignalStrengthNrTest extends TelephonyTest {
@Test
public void testEquals_sameParameters() {
// GIVEN an instance of CellSignalStrengthNr and another object with the same parameters
- CellSignalStrengthNr css = new CellSignalStrengthNr(CSIRSRP, CSIRSRQ, CSISINR,
- CSICQI_TABLE_INDEX, CSICQI_REPORT, SSRSRP, SSRSRQ, SSSINR);
- CellSignalStrengthNr anotherCss = new CellSignalStrengthNr(CSIRSRP, CSIRSRQ, CSISINR,
- CSICQI_TABLE_INDEX, CSICQI_REPORT, SSRSRP, SSRSRQ, SSSINR);
+ CellSignalStrengthNr css = new CellSignalStrengthNr(
+ CSIRSRP, CSIRSRQ, CSISINR, SSRSRP, SSRSRQ, SSSINR);
+ CellSignalStrengthNr anotherCss = new CellSignalStrengthNr(
+ CSIRSRP, CSIRSRQ, CSISINR, SSRSRP, SSRSRQ, SSSINR);
// THEN this two objects are equivalent
assertThat(css).isEqualTo(anotherCss);
@@ -162,11 +118,10 @@ public class CellSignalStrengthNrTest extends TelephonyTest {
public void testEquals_differentParameters() {
// GIVEN an instance of CellSignalStrengthNr and another object with some different
// parameters
- CellSignalStrengthNr css = new CellSignalStrengthNr(CSIRSRP, CSIRSRQ, CSISINR,
- CSICQI_TABLE_INDEX, CSICQI_REPORT, SSRSRP, SSRSRQ, SSSINR);
- CellSignalStrengthNr anotherCss = new CellSignalStrengthNr(ANOTHER_CSIRSRP,
- ANOTHER_CSIRSRQ, CSISINR, CSICQI_TABLE_INDEX, CSICQI_REPORT,
- SSRSRP, SSRSRQ, SSSINR);
+ CellSignalStrengthNr css = new CellSignalStrengthNr(
+ CSIRSRP, CSIRSRQ, CSISINR, SSRSRP, SSRSRQ, SSSINR);
+ CellSignalStrengthNr anotherCss = new CellSignalStrengthNr(
+ ANOTHER_CSIRSRP, ANOTHER_CSIRSRQ, CSISINR, SSRSRP, SSRSRQ, SSSINR);
// THEN this two objects are different
assertThat(css).isNotEqualTo(anotherCss);
@@ -175,8 +130,8 @@ public class CellSignalStrengthNrTest extends TelephonyTest {
@Test
public void testAusLevel_validValue() {
// GIVEN an instance of CellSignalStrengthNr with valid csirsrp
- CellSignalStrengthNr css = new CellSignalStrengthNr(CSIRSRP, CSIRSRQ, CSISINR,
- CSICQI_TABLE_INDEX, CSICQI_REPORT, SSRSRP, SSRSRQ, SSSINR);
+ CellSignalStrengthNr css = new CellSignalStrengthNr(
+ CSIRSRP, CSIRSRQ, CSISINR, SSRSRP, SSRSRQ, SSSINR);
// THEN the asu level is in range [0, 97]
assertThat(css.getAsuLevel()).isIn(Range.range(0, BoundType.CLOSED, 97, BoundType.CLOSED));
@@ -185,8 +140,8 @@ public class CellSignalStrengthNrTest extends TelephonyTest {
@Test
public void testAsuLevel_invalidValue() {
// GIVEN an instance of CellSignalStrengthNr with invalid csirsrp
- CellSignalStrengthNr css = new CellSignalStrengthNr(CSIRSRP, CSIRSRQ, CSISINR,
- CSICQI_TABLE_INDEX, CSICQI_REPORT, INVALID_SSRSRP, SSRSRQ, SSSINR);
+ CellSignalStrengthNr css = new CellSignalStrengthNr(
+ CSIRSRP, CSIRSRQ, CSISINR, INVALID_SSRSRP, SSRSRQ, SSSINR);
// THEN the asu level is unknown
assertThat(css.getAsuLevel()).isEqualTo(CellSignalStrengthNr.UNKNOWN_ASU_LEVEL);
@@ -196,8 +151,8 @@ public class CellSignalStrengthNrTest extends TelephonyTest {
public void testSignalLevel_validValue() {
for (int ssRsrp = -140; ssRsrp <= -44; ssRsrp++) {
// GIVEN an instance of CellSignalStrengthNr with valid csirsrp
- CellSignalStrengthNr css = new CellSignalStrengthNr(CSIRSRP, CSIRSRQ, CSISINR,
- CSICQI_TABLE_INDEX, CSICQI_REPORT, INVALID_SSRSRP, SSRSRQ, SSSINR);
+ CellSignalStrengthNr css = new CellSignalStrengthNr(
+ CSIRSRP, CSIRSRQ, CSISINR, ssRsrp, SSRSRQ, SSSINR);
// THEN the signal level is valid
assertThat(css.getLevel()).isIn(Range.range(
@@ -209,8 +164,8 @@ public class CellSignalStrengthNrTest extends TelephonyTest {
@Test
public void testSignalLevel_invalidValue() {
// GIVEN an instance of CellSignalStrengthNr with invalid csirsrp
- CellSignalStrengthNr css = new CellSignalStrengthNr(CSIRSRP, CSIRSRQ, CSISINR,
- CSICQI_TABLE_INDEX, CSICQI_REPORT, SSRSRP, SSRSRQ, SSSINR);
+ CellSignalStrengthNr css = new CellSignalStrengthNr(
+ CSIRSRP, CSIRSRQ, CSISINR, INVALID_SSRSRP, SSRSRQ, SSSINR);
// THEN the signal level is unknown
assertThat(css.getLevel()).isEqualTo(CellSignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN);
@@ -219,8 +174,8 @@ public class CellSignalStrengthNrTest extends TelephonyTest {
@Test
public void testParcel() {
// GIVEN an instance of CellSignalStrengthNr
- CellSignalStrengthNr css = new CellSignalStrengthNr(CSIRSRP, CSIRSRQ, CSISINR,
- CSICQI_TABLE_INDEX, CSICQI_REPORT, SSRSRP, SSRSRQ, SSSINR);
+ CellSignalStrengthNr css = new CellSignalStrengthNr(
+ CSIRSRP, CSIRSRQ, CSISINR, SSRSRP, SSRSRQ, SSSINR);
// WHEN write the object to parcel and create another object with that parcel
Parcel parcel = Parcel.obtain();
@@ -233,25 +188,8 @@ public class CellSignalStrengthNrTest extends TelephonyTest {
assertThat(anotherCss.getCsiRsrp()).isEqualTo(CSIRSRP);
assertThat(anotherCss.getCsiRsrq()).isEqualTo(CSIRSRQ);
assertThat(anotherCss.getCsiSinr()).isEqualTo(CSISINR);
- assertThat(css.getCsiCqiTableIndex()).isEqualTo(CSICQI_TABLE_INDEX);
- assertThat(css.getCsiCqiReport()).isEqualTo(getCsiCqiList());
assertThat(anotherCss.getSsRsrp()).isEqualTo(SSRSRP);
assertThat(anotherCss.getSsRsrq()).isEqualTo(SSRSRQ);
assertThat(anotherCss.getSsSinr()).isEqualTo(SSSINR);
}
-
- @Test
- public void testLevel() {
- CellSignalStrengthNr css = new CellSignalStrengthNr(CSIRSRP, CSIRSRQ, CSISINR, SSRSRP,
- SSRSRQ, SSSINR);
-
- // No keys in the bundle - should use RSRP and default levels.
- css.updateLevel(null, null);
- assertEquals(0 /* NONE or UNKNOWN */, css.getLevel());
-
- doReturn(10).when(mSS).getArfcnRsrpBoost();
- // Add rsrp boost and level should change to 1 - POOR
- css.updateLevel(null, mSS);
- assertEquals(1 /* MODERATE */, css.getLevel());
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/CellularNetworkServiceTest.java b/tests/telephonytests/src/com/android/internal/telephony/CellularNetworkServiceTest.java
index 1b187ef452..e2bacc24bf 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/CellularNetworkServiceTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/CellularNetworkServiceTest.java
@@ -32,10 +32,8 @@ import android.telephony.LteVopsSupportInfo;
import android.telephony.NetworkRegistrationInfo;
import android.telephony.NetworkService;
import android.telephony.NetworkServiceCallback;
-import android.telephony.NrVopsSupportInfo;
import android.telephony.ServiceState;
import android.telephony.SubscriptionManager;
-import android.telephony.VopsSupportInfo;
import android.test.suitebuilder.annotation.MediumTest;
import com.android.internal.R;
@@ -158,7 +156,7 @@ public class CellularNetworkServiceTest extends TelephonyTest {
assertTrue(false);
}
- VopsSupportInfo lteVopsSupportInfo =
+ LteVopsSupportInfo lteVopsSupportInfo =
new LteVopsSupportInfo(LteVopsSupportInfo.LTE_STATUS_NOT_AVAILABLE,
LteVopsSupportInfo.LTE_STATUS_NOT_AVAILABLE);
@@ -166,278 +164,7 @@ public class CellularNetworkServiceTest extends TelephonyTest {
domain, AccessNetworkConstants.TRANSPORT_TYPE_WWAN, voiceRegState,
ServiceState.rilRadioTechnologyToNetworkType(voiceRadioTech), reasonForDenial,
false, availableServices, null, "", maxDataCalls, false, false, false,
- lteVopsSupportInfo);
-
- try {
- verify(mCallback, timeout(1000).times(1)).onRequestNetworkRegistrationInfoComplete(
- eq(NetworkServiceCallback.RESULT_SUCCESS), eq(expectedState));
- } catch (RemoteException e) {
- assertTrue(false);
- }
- }
-
- @Test
- @MediumTest
- public void testGetNetworkRegistrationInfoV1_5() {
- // common parameters
- int regState = NetworkRegistrationInfo.REGISTRATION_STATE_HOME;
- int radioTech = ServiceState.RIL_RADIO_TECHNOLOGY_LTE;
- int reasonForDenial = 0;
-
- // voice services
- List<Integer> availableVoiceServices = new ArrayList<>(Arrays.asList(new Integer[] {
- NetworkRegistrationInfo.SERVICE_TYPE_VOICE,
- NetworkRegistrationInfo.SERVICE_TYPE_SMS,
- NetworkRegistrationInfo.SERVICE_TYPE_VIDEO
- }));
-
- // Default value per 24.008
- int maxDataCalls = 16;
- // data service
- List<Integer> availableDataServices = Arrays.asList(
- NetworkRegistrationInfo.SERVICE_TYPE_DATA);
-
- // ENDC parameters
- boolean isEndcAvailable = true;
- boolean isDcNrRestricted = false;
- boolean isNrAvailable = true;
-
- // LTE VoPS parameters
- boolean isVopsSupported = true;
- boolean isEmcBearerSupported = true;
-
- android.hardware.radio.V1_5.RegStateResult regResult =
- new android.hardware.radio.V1_5.RegStateResult();
-
- regResult.regState = regState;
- regResult.rat = radioTech;
- regResult.reasonForDenial = reasonForDenial;
-
- android.hardware.radio.V1_5.RegStateResult.AccessTechnologySpecificInfo
- .EutranRegistrationInfo eutranInfo = new android.hardware.radio.V1_5
- .RegStateResult.AccessTechnologySpecificInfo.EutranRegistrationInfo();
- eutranInfo.lteVopsInfo.isVopsSupported = isVopsSupported;
- eutranInfo.lteVopsInfo.isEmcBearerSupported = isEmcBearerSupported;
- eutranInfo.nrIndicators.isEndcAvailable = isEndcAvailable;
- eutranInfo.nrIndicators.isDcNrRestricted = isDcNrRestricted;
- eutranInfo.nrIndicators.isNrAvailable = isNrAvailable;
- regResult.accessTechnologySpecificInfo.eutranInfo(eutranInfo);
-
- VopsSupportInfo vops = new LteVopsSupportInfo(
- LteVopsSupportInfo.LTE_STATUS_SUPPORTED, LteVopsSupportInfo.LTE_STATUS_SUPPORTED);
-
- mSimulatedCommands.setVoiceRegStateResult(regResult);
- mSimulatedCommands.setDataRegStateResult(regResult);
-
- // test voice registration state
- try {
- mBinder.requestNetworkRegistrationInfo(0, NetworkRegistrationInfo.DOMAIN_CS, mCallback);
- } catch (RemoteException e) {
- assertTrue(false);
- }
-
- NetworkRegistrationInfo expectedState = new NetworkRegistrationInfo(
- NetworkRegistrationInfo.DOMAIN_CS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
- regState, ServiceState.rilRadioTechnologyToNetworkType(radioTech), reasonForDenial,
- false, availableVoiceServices, null, "", false, 0, 0, 0);
-
- try {
- verify(mCallback, timeout(1000).times(1)).onRequestNetworkRegistrationInfoComplete(
- eq(NetworkServiceCallback.RESULT_SUCCESS), eq(expectedState));
- } catch (RemoteException e) {
- assertTrue(false);
- }
-
- // test data registration state
- try {
- mBinder.requestNetworkRegistrationInfo(0, NetworkRegistrationInfo.DOMAIN_PS, mCallback);
- } catch (RemoteException e) {
- assertTrue(false);
- }
-
- expectedState = new NetworkRegistrationInfo(
- NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
- regState, ServiceState.rilRadioTechnologyToNetworkType(radioTech), reasonForDenial,
- false, availableDataServices, null, "", maxDataCalls, isDcNrRestricted,
- isNrAvailable, isEndcAvailable, vops);
-
- try {
- verify(mCallback, timeout(1000).times(1)).onRequestNetworkRegistrationInfoComplete(
- eq(NetworkServiceCallback.RESULT_SUCCESS), eq(expectedState));
- } catch (RemoteException e) {
- assertTrue(false);
- }
- }
-
- @Test
- @MediumTest
- public void testGetNetworkRegistrationInfoV1_6WithLte() {
- // common parameters
- int regState = NetworkRegistrationInfo.REGISTRATION_STATE_HOME;
- int radioTech = ServiceState.RIL_RADIO_TECHNOLOGY_LTE;
- int reasonForDenial = 0;
-
- // voice services
- List<Integer> availableVoiceServices = new ArrayList<>(Arrays.asList(new Integer[] {
- NetworkRegistrationInfo.SERVICE_TYPE_VOICE,
- NetworkRegistrationInfo.SERVICE_TYPE_SMS,
- NetworkRegistrationInfo.SERVICE_TYPE_VIDEO
- }));
-
- // Default value per 24.008
- int maxDataCalls = 16;
- // data service
- List<Integer> availableDataServices = Arrays.asList(
- NetworkRegistrationInfo.SERVICE_TYPE_DATA);
-
- // ENDC parameters
- boolean isEndcAvailable = true;
- boolean isDcNrRestricted = false;
- boolean isNrAvailable = true;
-
- // LTE VoPS parameters
- boolean isVopsSupported = true;
- boolean isEmcBearerSupported = true;
-
- android.hardware.radio.V1_6.RegStateResult regResult =
- new android.hardware.radio.V1_6.RegStateResult();
-
- regResult.regState = regState;
- regResult.rat = radioTech;
- regResult.reasonForDenial = reasonForDenial;
-
- android.hardware.radio.V1_5.RegStateResult.AccessTechnologySpecificInfo
- .EutranRegistrationInfo eutranInfo = new android.hardware.radio.V1_5
- .RegStateResult.AccessTechnologySpecificInfo.EutranRegistrationInfo();
- eutranInfo.lteVopsInfo.isVopsSupported = isVopsSupported;
- eutranInfo.lteVopsInfo.isEmcBearerSupported = isEmcBearerSupported;
- eutranInfo.nrIndicators.isEndcAvailable = isEndcAvailable;
- eutranInfo.nrIndicators.isDcNrRestricted = isDcNrRestricted;
- eutranInfo.nrIndicators.isNrAvailable = isNrAvailable;
- regResult.accessTechnologySpecificInfo.eutranInfo(eutranInfo);
-
- VopsSupportInfo vops = new LteVopsSupportInfo(
- LteVopsSupportInfo.LTE_STATUS_SUPPORTED, LteVopsSupportInfo.LTE_STATUS_SUPPORTED);
-
- mSimulatedCommands.setVoiceRegStateResult(regResult);
- mSimulatedCommands.setDataRegStateResult(regResult);
-
- // test voice registration state
- try {
- mBinder.requestNetworkRegistrationInfo(0, NetworkRegistrationInfo.DOMAIN_CS, mCallback);
- } catch (RemoteException e) {
- assertTrue(false);
- }
-
- NetworkRegistrationInfo expectedState = new NetworkRegistrationInfo(
- NetworkRegistrationInfo.DOMAIN_CS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
- regState, ServiceState.rilRadioTechnologyToNetworkType(radioTech), reasonForDenial,
- false, availableVoiceServices, null, "", false, 0, 0, 0);
-
- try {
- verify(mCallback, timeout(1000).times(1)).onRequestNetworkRegistrationInfoComplete(
- eq(NetworkServiceCallback.RESULT_SUCCESS), eq(expectedState));
- } catch (RemoteException e) {
- assertTrue(false);
- }
-
- // test data registration state
- try {
- mBinder.requestNetworkRegistrationInfo(0, NetworkRegistrationInfo.DOMAIN_PS, mCallback);
- } catch (RemoteException e) {
- assertTrue(false);
- }
-
- expectedState = new NetworkRegistrationInfo(
- NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
- regState, ServiceState.rilRadioTechnologyToNetworkType(radioTech), reasonForDenial,
- false, availableDataServices, null, "", maxDataCalls, isDcNrRestricted,
- isNrAvailable, isEndcAvailable, vops);
-
- try {
- verify(mCallback, timeout(1000).times(1)).onRequestNetworkRegistrationInfoComplete(
- eq(NetworkServiceCallback.RESULT_SUCCESS), eq(expectedState));
- } catch (RemoteException e) {
- assertTrue(false);
- }
- }
-
-
- @Test
- @MediumTest
- public void testGetNetworkRegistrationInfoV1_6WithNr() {
- // common parameters
- int regState = NetworkRegistrationInfo.REGISTRATION_STATE_HOME;
- int radioTech = ServiceState.RIL_RADIO_TECHNOLOGY_NR;
- int reasonForDenial = 0;
-
- // voice services
- List<Integer> availableVoiceServices = new ArrayList<>(Arrays.asList(new Integer[] {
- NetworkRegistrationInfo.SERVICE_TYPE_VOICE,
- NetworkRegistrationInfo.SERVICE_TYPE_SMS,
- NetworkRegistrationInfo.SERVICE_TYPE_VIDEO
- }));
-
- // Default value per 24.008
- int maxDataCalls = 16;
- // data service
- List<Integer> availableDataServices = Arrays.asList(
- NetworkRegistrationInfo.SERVICE_TYPE_DATA);
-
- // NR VoPS parameters
- byte vopsSupported = android.hardware.radio.V1_6.VopsIndicator.VOPS_OVER_3GPP;
- byte emcSupported = android.hardware.radio.V1_6.EmcIndicator.EMC_NR_CONNECTED_TO_5GCN;
- byte emfSupported = android.hardware.radio.V1_6.EmfIndicator.EMF_NR_CONNECTED_TO_5GCN;
-
- android.hardware.radio.V1_6.RegStateResult regResult =
- new android.hardware.radio.V1_6.RegStateResult();
-
- regResult.regState = regState;
- regResult.rat = radioTech;
- regResult.reasonForDenial = reasonForDenial;
-
- regResult.accessTechnologySpecificInfo.ngranNrVopsInfo(new android.hardware.radio.V1_6
- .NrVopsInfo());
- regResult.accessTechnologySpecificInfo.ngranNrVopsInfo().vopsSupported = vopsSupported;
- regResult.accessTechnologySpecificInfo.ngranNrVopsInfo().emcSupported = emcSupported;
- regResult.accessTechnologySpecificInfo.ngranNrVopsInfo().emfSupported = emfSupported;
- regResult.accessTechnologySpecificInfo.ngranNrVopsInfo(
- regResult.accessTechnologySpecificInfo.ngranNrVopsInfo());
-
- VopsSupportInfo vops = new NrVopsSupportInfo(vopsSupported, emcSupported, emfSupported);
- mSimulatedCommands.setVoiceRegStateResult(regResult);
- mSimulatedCommands.setDataRegStateResult(regResult);
-
- // test voice registration state
- try {
- mBinder.requestNetworkRegistrationInfo(0, NetworkRegistrationInfo.DOMAIN_CS, mCallback);
- } catch (RemoteException e) {
- assertTrue(false);
- }
-
- NetworkRegistrationInfo expectedState = new NetworkRegistrationInfo(
- NetworkRegistrationInfo.DOMAIN_CS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
- regState, ServiceState.rilRadioTechnologyToNetworkType(radioTech), reasonForDenial,
- false, availableVoiceServices, null, "", false, 0, 0, 0);
-
- try {
- verify(mCallback, timeout(1000).times(1)).onRequestNetworkRegistrationInfoComplete(
- eq(NetworkServiceCallback.RESULT_SUCCESS), eq(expectedState));
- } catch (RemoteException e) {
- assertTrue(false);
- }
-
- // test data registration state
- try {
- mBinder.requestNetworkRegistrationInfo(0, NetworkRegistrationInfo.DOMAIN_PS, mCallback);
- } catch (RemoteException e) {
- assertTrue(false);
- }
-
- expectedState = new NetworkRegistrationInfo(
- NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
- regState, ServiceState.rilRadioTechnologyToNetworkType(radioTech), reasonForDenial,
- false, availableDataServices, null, "", maxDataCalls, false, false, false, vops);
+ lteVopsSupportInfo, false);
try {
verify(mCallback, timeout(1000).times(1)).onRequestNetworkRegistrationInfoComplete(
diff --git a/tests/telephonytests/src/com/android/internal/telephony/CellularNetworkValidatorTest.java b/tests/telephonytests/src/com/android/internal/telephony/CellularNetworkValidatorTest.java
index 2c1e18b275..0601384d0b 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/CellularNetworkValidatorTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/CellularNetworkValidatorTest.java
@@ -57,9 +57,9 @@ import org.mockito.Mock;
public class CellularNetworkValidatorTest extends TelephonyTest {
private CellularNetworkValidator mValidatorUT;
private static final PhoneCapability CAPABILITY_WITH_VALIDATION_SUPPORTED =
- new PhoneCapability(1, 1, null, true, new int[0]);
+ new PhoneCapability(1, 1, 0, null, true);
private static final PhoneCapability CAPABILITY_WITHOUT_VALIDATION_SUPPORTED =
- new PhoneCapability(1, 1, null, false, new int[0]);
+ new PhoneCapability(1, 1, 0, null, false);
private final CellIdentityLte mCellIdentityLte1 = new CellIdentityLte(123, 456, 0, 0, 111);
private final CellIdentityLte mCellIdentityLte2 = new CellIdentityLte(321, 654, 0, 0, 222);
@Mock
diff --git a/tests/telephonytests/src/com/android/internal/telephony/ContextFixture.java b/tests/telephonytests/src/com/android/internal/telephony/ContextFixture.java
index 14f5aa14cf..106a2a8576 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/ContextFixture.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/ContextFixture.java
@@ -31,9 +31,7 @@ import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.AppOpsManager;
import android.app.DownloadManager;
-import android.app.KeyguardManager;
import android.app.NotificationManager;
-import android.app.UiModeManager;
import android.app.usage.UsageStatsManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
@@ -56,11 +54,9 @@ import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.MatrixCursor;
-import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.Uri;
-import android.net.vcn.VcnManager;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Bundle;
@@ -83,7 +79,6 @@ import android.telephony.euicc.EuiccManager;
import android.test.mock.MockContentProvider;
import android.test.mock.MockContentResolver;
import android.test.mock.MockContext;
-import android.util.DisplayMetrics;
import android.util.Log;
import com.google.common.collect.ArrayListMultimap;
@@ -101,7 +96,6 @@ import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
-import java.util.Set;
/**
* Controls a test {@link Context} as would be provided by the Android framework to an
@@ -198,9 +192,6 @@ public class ContextFixture implements TestFixture<Context> {
Intent serviceIntent,
ServiceConnection connection,
int flags) {
- if (mMockBindingFailureForPackage.contains(serviceIntent.getPackage())) {
- return false;
- }
if (mServiceByServiceConnection.containsKey(connection)) {
throw new RuntimeException("ServiceConnection already bound: " + connection);
}
@@ -222,11 +213,10 @@ public class ContextFixture implements TestFixture<Context> {
public void unbindService(
ServiceConnection connection) {
IInterface service = mServiceByServiceConnection.remove(connection);
- if (service != null) {
- connection.onServiceDisconnected(mComponentNameByService.get(service));
- } else {
- logd("unbindService: ServiceConnection not found: " + connection);
+ if (service == null) {
+ throw new RuntimeException("ServiceConnection not found: " + connection);
}
+ connection.onServiceDisconnected(mComponentNameByService.get(service));
}
@Override
@@ -270,22 +260,15 @@ public class ContextFixture implements TestFixture<Context> {
return mTelephonyRegistryManager;
case Context.SYSTEM_CONFIG_SERVICE:
return mSystemConfigManager;
- case Context.KEYGUARD_SERVICE:
- return mKeyguardManager;
- case Context.VCN_MANAGEMENT_SERVICE:
- return mVcnManager;
case Context.BATTERY_STATS_SERVICE:
case Context.DISPLAY_SERVICE:
case Context.POWER_SERVICE:
case Context.PERMISSION_SERVICE:
- case Context.LEGACY_PERMISSION_SERVICE:
// These are final classes so cannot be mocked,
// return real services.
return TestApplication.getAppContext().getSystemService(name);
case Context.POWER_WHITELIST_MANAGER:
return mPowerWhitelistManager;
- case Context.LOCATION_SERVICE:
- return mLocationManager;
default:
return null;
}
@@ -307,20 +290,6 @@ public class ContextFixture implements TestFixture<Context> {
return Context.POWER_WHITELIST_MANAGER;
} else if (serviceClass == SystemConfigManager.class) {
return Context.SYSTEM_CONFIG_SERVICE;
- } else if (serviceClass == ActivityManager.class) {
- return Context.ACTIVITY_SERVICE;
- } else if (serviceClass == LocationManager.class) {
- return Context.LOCATION_SERVICE;
- } else if (serviceClass == CarrierConfigManager.class) {
- return Context.CARRIER_CONFIG_SERVICE;
- } else if (serviceClass == TelephonyManager.class) {
- return Context.TELEPHONY_SERVICE;
- } else if (serviceClass == UiModeManager.class) {
- return Context.UI_MODE_SERVICE;
- } else if (serviceClass == KeyguardManager.class) {
- return Context.KEYGUARD_SERVICE;
- } else if (serviceClass == VcnManager.class) {
- return Context.VCN_MANAGEMENT_SERVICE;
}
return super.getSystemServiceName(serviceClass);
}
@@ -341,11 +310,6 @@ public class ContextFixture implements TestFixture<Context> {
}
@Override
- public Context createConfigurationContext(Configuration overrideConfiguration) {
- return spy(new FakeContext());
- }
-
- @Override
public ApplicationInfo getApplicationInfo() {
return mApplicationInfo;
}
@@ -424,12 +388,6 @@ public class ContextFixture implements TestFixture<Context> {
}
@Override
- public void sendBroadcast(Intent intent, String receiverPermission, Bundle initialExtras) {
- logd("sendBroadcast called for " + intent.getAction());
- sendBroadcast(intent);
- }
-
- @Override
public void sendOrderedBroadcast(Intent intent, String receiverPermission) {
logd("sendOrderedBroadcast called for " + intent.getAction());
sendBroadcast(intent);
@@ -482,12 +440,6 @@ public class ContextFixture implements TestFixture<Context> {
}
@Override
- public void sendBroadcastMultiplePermissions(Intent intent,
- String[] includePermissions, String[] excludePermissions) {
- sendBroadcast(intent);
- }
-
- @Override
public Context createContextAsUser(UserHandle user, int flags) {
return this;
}
@@ -584,11 +536,6 @@ public class ContextFixture implements TestFixture<Context> {
}
@Override
- public void enforceCallingPermission(String permission, String message) {
- enforceCallingOrSelfPermission(permission, message);
- }
-
- @Override
public int checkCallingOrSelfPermission(String permission) {
if (mPermissionTable.contains(permission)
|| mPermissionTable.contains(PERMISSION_ENABLE_ALL)) {
@@ -635,7 +582,6 @@ public class ContextFixture implements TestFixture<Context> {
private final Map<ComponentName, IntentFilter> mIntentFilterByComponentName = new HashMap<>();
private final Map<IInterface, ComponentName> mComponentNameByService =
new HashMap<IInterface, ComponentName>();
- private final Set<String> mMockBindingFailureForPackage = new HashSet();
private final Map<ServiceConnection, IInterface> mServiceByServiceConnection =
new HashMap<ServiceConnection, IInterface>();
private final Multimap<String, BroadcastReceiver> mBroadcastReceiversByAction =
@@ -652,6 +598,7 @@ public class ContextFixture implements TestFixture<Context> {
// The application context is the most important object this class provides to the system
// under test.
private final Context mContext = spy(new FakeContext());
+
// We then create a spy on the application context allowing standard Mockito-style
// when(...) logic to be used to add specific little responses where needed.
@@ -679,14 +626,10 @@ public class ContextFixture implements TestFixture<Context> {
mock(TelephonyRegistryManager.class);
private final SystemConfigManager mSystemConfigManager = mock(SystemConfigManager.class);
private final PowerWhitelistManager mPowerWhitelistManager = mock(PowerWhitelistManager.class);
- private final LocationManager mLocationManager = mock(LocationManager.class);
- private final KeyguardManager mKeyguardManager = mock(KeyguardManager.class);
- private final VcnManager mVcnManager = mock(VcnManager.class);
private final ContentProvider mContentProvider = spy(new FakeContentProvider());
private final Configuration mConfiguration = new Configuration();
- private final DisplayMetrics mDisplayMetrics = new DisplayMetrics();
private final SharedPreferences mSharedPreferences = PreferenceManager
.getDefaultSharedPreferences(TestApplication.getAppContext());
private final MockContentResolver mContentResolver = new MockContentResolver();
@@ -734,15 +677,13 @@ public class ContextFixture implements TestFixture<Context> {
doReturn(mBundle).when(mCarrierConfigManager).getConfig();
doReturn(mock(Network.class)).when(mConnectivityManager).registerNetworkAgent(
- any(), any(), any(), any(), any(), any(), anyInt());
+ any(), any(), any(), any(), anyInt(), any(), anyInt());
doReturn(true).when(mEuiccManager).isEnabled();
mConfiguration.locale = Locale.US;
doReturn(mConfiguration).when(mResources).getConfiguration();
- mDisplayMetrics.density = 2.25f;
- doReturn(mDisplayMetrics).when(mResources).getDisplayMetrics();
mContentResolver.addProvider(Settings.AUTHORITY, mContentProvider);
// Settings caches the provider after first get/set call, this is needed to make sure
// Settings is using mContentProvider as the cached provider across all tests.
@@ -803,10 +744,6 @@ public class ContextFixture implements TestFixture<Context> {
mComponentNameByService.put(service, name);
}
- public void mockBindingFailureForPackage(String packageName) {
- mMockBindingFailureForPackage.add(packageName);
- }
-
private List<ResolveInfo> doQueryIntentServices(Intent intent, int flags) {
List<ResolveInfo> result = new ArrayList<ResolveInfo>();
for (ComponentName componentName : mComponentNamesByAction.get(intent.getAction())) {
diff --git a/tests/telephonytests/src/com/android/internal/telephony/DefaultPhoneNotifierTest.java b/tests/telephonytests/src/com/android/internal/telephony/DefaultPhoneNotifierTest.java
index c6be1a47ef..81c2f5607d 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/DefaultPhoneNotifierTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/DefaultPhoneNotifierTest.java
@@ -24,11 +24,13 @@ import static org.mockito.Mockito.verify;
import android.telephony.CellIdentityGsm;
import android.telephony.CellInfo;
+import android.telephony.DataFailCause;
import android.telephony.DisconnectCause;
import android.telephony.PreciseCallState;
import android.telephony.PreciseDisconnectCause;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
+import android.telephony.data.ApnSetting;
import android.test.suitebuilder.annotation.SmallTest;
import com.android.internal.telephony.PhoneInternalInterface.DataActivityState;
@@ -112,7 +114,7 @@ public class DefaultPhoneNotifierTest extends TelephonyTest {
doReturn(1).when(mPhone).getSubId();
doReturn(2).when(mPhone).getPhoneId();
mDefaultPhoneNotifierUT.notifySignalStrength(mPhone);
- verify(mTelephonyRegistryManager).notifySignalStrengthChanged(eq(2), eq(1),
+ verify(mTelephonyRegistryManager).notifySignalStrengthChanged(eq(1), eq(2),
signalStrengthArgumentCaptor.capture());
assertEquals(99, signalStrengthArgumentCaptor.getValue().getGsmSignalStrength());
}
@@ -135,19 +137,19 @@ public class DefaultPhoneNotifierTest extends TelephonyTest {
public void testNotifyMessageWaiting() throws Exception {
doReturn(1).when(mPhone).getPhoneId();
mDefaultPhoneNotifierUT.notifyMessageWaitingChanged(mPhone);
- verify(mTelephonyRegistryManager).notifyMessageWaitingChanged(1, 0, false);
+ verify(mTelephonyRegistryManager).notifyMessageWaitingChanged(0, 1, false);
doReturn(2).when(mPhone).getPhoneId();
mDefaultPhoneNotifierUT.notifyMessageWaitingChanged(mPhone);
- verify(mTelephonyRegistryManager).notifyMessageWaitingChanged(2, 0, false);
+ verify(mTelephonyRegistryManager).notifyMessageWaitingChanged(0, 2, false);
doReturn(1).when(mPhone).getSubId();
mDefaultPhoneNotifierUT.notifyMessageWaitingChanged(mPhone);
- verify(mTelephonyRegistryManager).notifyMessageWaitingChanged(2, 1, false);
+ verify(mTelephonyRegistryManager).notifyMessageWaitingChanged(1, 2, false);
doReturn(true).when(mPhone).getMessageWaitingIndicator();
mDefaultPhoneNotifierUT.notifyMessageWaitingChanged(mPhone);
- verify(mTelephonyRegistryManager).notifyMessageWaitingChanged(2, 1, true);
+ verify(mTelephonyRegistryManager).notifyMessageWaitingChanged(1, 2, true);
}
@Test @SmallTest
@@ -166,6 +168,28 @@ public class DefaultPhoneNotifierTest extends TelephonyTest {
}
@Test @SmallTest
+ public void testNotifyDataConnectionFailed() throws Exception {
+ mDefaultPhoneNotifierUT.notifyDataConnectionFailed(mPhone, "default", "APN_0",
+ DataFailCause.INSUFFICIENT_RESOURCES);
+ verify(mTelephonyRegistryManager).notifyPreciseDataConnectionFailed(
+ eq(0), eq(0), eq(ApnSetting.TYPE_DEFAULT), eq("APN_0"),
+ eq(DataFailCause.INSUFFICIENT_RESOURCES));
+
+ mDefaultPhoneNotifierUT.notifyDataConnectionFailed(mPhone, "default", "APN_1",
+ DataFailCause.INSUFFICIENT_RESOURCES);
+ verify(mTelephonyRegistryManager).notifyPreciseDataConnectionFailed(
+ eq(0), eq(0), eq(ApnSetting.TYPE_DEFAULT), eq("APN_1"),
+ eq(DataFailCause.INSUFFICIENT_RESOURCES));
+
+ doReturn(1).when(mPhone).getSubId();
+ mDefaultPhoneNotifierUT.notifyDataConnectionFailed(mPhone, "default", "APN_1",
+ DataFailCause.INSUFFICIENT_RESOURCES);
+ verify(mTelephonyRegistryManager).notifyPreciseDataConnectionFailed(
+ eq(1), eq(0), eq(ApnSetting.TYPE_DEFAULT), eq("APN_1"),
+ eq(DataFailCause.INSUFFICIENT_RESOURCES));
+ }
+
+ @Test @SmallTest
public void testNotifyPreciseCallState() throws Exception {
//mock forground/background/ringing call and call state
@@ -229,7 +253,7 @@ public class DefaultPhoneNotifierTest extends TelephonyTest {
// mock gsm cell location
CellIdentityGsm mGsmCellLocation = new CellIdentityGsm(
2, 3, 0, 0, null, null, null, null, Collections.emptyList());
- doReturn(mGsmCellLocation).when(mPhone).getCurrentCellIdentity();
+ doReturn(mGsmCellLocation).when(mPhone).getCellIdentity();
ArgumentCaptor<CellIdentityGsm> cellLocationCapture =
ArgumentCaptor.forClass(CellIdentityGsm.class);
diff --git a/tests/telephonytests/src/com/android/internal/telephony/DeviceStateMonitorTest.java b/tests/telephonytests/src/com/android/internal/telephony/DeviceStateMonitorTest.java
index 44f3aa5bfd..be03ecaefc 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/DeviceStateMonitorTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/DeviceStateMonitorTest.java
@@ -25,7 +25,6 @@ import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.nullable;
-import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
@@ -33,12 +32,9 @@ import static org.mockito.Mockito.verify;
import static java.util.Arrays.asList;
import android.annotation.IntDef;
-import android.app.UiModeManager;
-import android.content.Context;
import android.content.Intent;
import android.hardware.radio.V1_5.IndicationFilter;
import android.net.ConnectivityManager;
-import android.net.TetheringManager;
import android.os.BatteryManager;
import android.os.Message;
import android.test.suitebuilder.annotation.MediumTest;
@@ -50,7 +46,6 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
-import org.mockito.Mock;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -132,8 +127,6 @@ public class DeviceStateMonitorTest extends TelephonyTest {
STATE_TYPE_CHARGING, STATE_TYPE_SCREEN, STATE_TYPE_TETHERING}
);
- @Mock
- UiModeManager mUiModeManager;
private DeviceStateMonitor mDSM;
// Given a stateType, return the event type that can change the state
private int state2Event(@StateType int stateType) {
@@ -161,9 +154,6 @@ public class DeviceStateMonitorTest extends TelephonyTest {
@Before
public void setUp() throws Exception {
super.setUp(getClass().getSimpleName());
- mContextFixture.setSystemService(Context.UI_MODE_SERVICE, mUiModeManager);
- // We don't even need a mock executor, we just need to not throw.
- doReturn(null).when(mContextFixture.getTestDouble()).getMainExecutor();
mDSM = new DeviceStateMonitor(mPhone);
// Initialize with ALL states off
@@ -251,7 +241,7 @@ public class DeviceStateMonitorTest extends TelephonyTest {
@Test
public void testTethering() {
// Turn tethering on
- Intent intent = new Intent(TetheringManager.ACTION_TETHER_STATE_CHANGED);
+ Intent intent = new Intent(ConnectivityManager.ACTION_TETHER_STATE_CHANGED);
intent.putExtra(ConnectivityManager.EXTRA_ACTIVE_TETHER, new ArrayList<>(asList("abc")));
mContext.sendBroadcast(intent);
processAllMessages();
diff --git a/tests/telephonytests/src/com/android/internal/telephony/FakeTelephonyProvider.java b/tests/telephonytests/src/com/android/internal/telephony/FakeTelephonyProvider.java
index f2624afae5..86cf43f8c3 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/FakeTelephonyProvider.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/FakeTelephonyProvider.java
@@ -112,12 +112,8 @@ public class FakeTelephonyProvider extends MockContentProvider {
+ Telephony.SimInfo.COLUMN_IMSI + " TEXT,"
+ Telephony.SimInfo.COLUMN_ACCESS_RULES_FROM_CARRIER_CONFIGS + " BLOB,"
+ Telephony.SimInfo.COLUMN_UICC_APPLICATIONS_ENABLED + " INTEGER DEFAULT 1,"
- + Telephony.SimInfo.COLUMN_ALLOWED_NETWORK_TYPES + " BIGINT DEFAULT -1,"
- + Telephony.SimInfo.COLUMN_IMS_RCS_UCE_ENABLED + " INTEGER DEFAULT 0, "
- + Telephony.SimInfo.COLUMN_RCS_CONFIG + " BLOB,"
- + Telephony.SimInfo.COLUMN_ALLOWED_NETWORK_TYPES_FOR_REASONS + " TEXT,"
- + Telephony.SimInfo.COLUMN_D2D_STATUS_SHARING + " INTEGER DEFAULT 0,"
- + Telephony.SimInfo.COLUMN_D2D_STATUS_SHARING_SELECTED_CONTACTS + "TEXT"
+ + Telephony.SimInfo.COLUMN_ALLOWED_NETWORK_TYPES + " BIGINT DEFAULT -1, "
+ + Telephony.SimInfo.COLUMN_IMS_RCS_UCE_ENABLED + " INTEGER DEFAULT 0"
+ ");";
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/GbaManagerTest.java b/tests/telephonytests/src/com/android/internal/telephony/GbaManagerTest.java
deleted file mode 100644
index 8939977166..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/GbaManagerTest.java
+++ /dev/null
@@ -1,259 +0,0 @@
-/*
- * Copyright 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.internal.telephony;
-
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertTrue;
-import static junit.framework.Assert.fail;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.atLeastOnce;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.ServiceConnection;
-import android.net.Uri;
-import android.os.Handler;
-import android.os.IBinder;
-import android.os.Looper;
-import android.os.RemoteException;
-import android.telephony.IBootstrapAuthenticationCallback;
-import android.telephony.TelephonyManager;
-import android.telephony.gba.GbaAuthRequest;
-import android.telephony.gba.GbaService;
-import android.telephony.gba.IGbaService;
-import android.telephony.gba.UaSecurityProtocolIdentifier;
-import android.test.suitebuilder.annotation.SmallTest;
-import android.testing.AndroidTestingRunner;
-import android.testing.TestableLooper;
-import android.util.Log;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-/**
- * Unit tests for GbaManager
- */
-@RunWith(AndroidTestingRunner.class)
-@TestableLooper.RunWithLooper
-public final class GbaManagerTest {
- private static final String LOG_TAG = "GbaManagerTest";
-
- private static final ComponentName TEST_DEFAULT_SERVICE_NAME = new ComponentName(
- "TestGbaPkg", "TestGbaService");
- private static final ComponentName TEST_SERVICE2_NAME = new ComponentName(
- "TestGbaPkg2", "TestGbaService2");
- private static final int RELEASE_NEVER = -1;
- private static final int RELEASE_IMMEDIATELY = 0;
- private static final int RELEASE_TIME_60S = 60 * 1000;
- private static final int TEST_SUB_ID = Integer.MAX_VALUE;
-
- @Mock Context mMockContext;
- @Mock IBinder mMockBinder;
- @Mock IGbaService mMockGbaServiceBinder;
- @Mock IBootstrapAuthenticationCallback mMockCallback;
- private GbaManager mTestGbaManager;
- private Handler mHandler;
- private TestableLooper mLooper;
-
- @Before
- public void setUp() throws Exception {
- log("setUp");
- MockitoAnnotations.initMocks(this);
- if (Looper.myLooper() == null) {
- Looper.prepare();
- }
- when(mMockContext.bindService(any(), any(), anyInt())).thenReturn(true);
- when(mMockGbaServiceBinder.asBinder()).thenReturn(mMockBinder);
- mTestGbaManager = new GbaManager(mMockContext, TEST_SUB_ID, null, 0);
- mHandler = mTestGbaManager.getHandler();
- try {
- mLooper = new TestableLooper(mHandler.getLooper());
- } catch (Exception e) {
- fail("Unable to create looper from handler.");
- }
- }
-
- @After
- public void tearDown() throws Exception {
- log("tearDown");
- mTestGbaManager.destroy();
- mTestGbaManager = null;
- mLooper.destroy();
- mLooper = null;
- }
-
- @Test
- @SmallTest
- public void testFailOnRequest() throws Exception {
- GbaAuthRequest request = createDefaultRequest();
-
- mTestGbaManager.bootstrapAuthenticationRequest(request);
- mLooper.processAllMessages();
-
- verify(mMockContext, never()).bindService(any(), any(), anyInt());
- verify(mMockCallback).onAuthenticationFailure(anyInt(), anyInt());
- assertTrue(!mTestGbaManager.isServiceConnected());
- }
-
- @Test
- @SmallTest
- public void testBindServiceOnRequest() throws Exception {
- mTestGbaManager.overrideServicePackage(TEST_DEFAULT_SERVICE_NAME.getPackageName());
- GbaAuthRequest request = createDefaultRequest();
-
- mTestGbaManager.bootstrapAuthenticationRequest(request);
- mLooper.processAllMessages();
- bindAndConnectService(TEST_DEFAULT_SERVICE_NAME);
- mLooper.processAllMessages();
-
- verify(mMockGbaServiceBinder).authenticationRequest(any());
- assertTrue(mTestGbaManager.isServiceConnected());
- }
-
- @Test
- @SmallTest
- public void testFailAndRetryOnRequest() throws RemoteException {
- when(mMockContext.bindService(any(), any(), anyInt())).thenReturn(false);
- mTestGbaManager.overrideServicePackage(TEST_DEFAULT_SERVICE_NAME.getPackageName());
- GbaAuthRequest request = createDefaultRequest();
-
- mTestGbaManager.bootstrapAuthenticationRequest(request);
-
- for (int i = 0; i < GbaManager.MAX_RETRY; i++) {
- mLooper.processAllMessages();
- verify(mMockContext, times(i + 1)).bindService(any(), any(), anyInt());
- try {
- Thread.sleep(GbaManager.RETRY_TIME_MS + 500);
- } catch (InterruptedException e) {
- }
- }
- assertTrue(!mTestGbaManager.isServiceConnected());
- mLooper.processAllMessages();
- verify(mMockCallback).onAuthenticationFailure(anyInt(), anyInt());
- }
-
- @Test
- @SmallTest
- public void testBindServiceWhenPackageNameChanged() {
- mTestGbaManager.overrideServicePackage(TEST_DEFAULT_SERVICE_NAME.getPackageName());
- mTestGbaManager.overrideReleaseTime(RELEASE_TIME_60S);
- GbaAuthRequest request = createDefaultRequest();
-
- mTestGbaManager.bootstrapAuthenticationRequest(request);
- mLooper.processAllMessages();
- ServiceConnection conn = bindAndConnectService(TEST_DEFAULT_SERVICE_NAME);
- mTestGbaManager.overrideServicePackage(TEST_SERVICE2_NAME.getPackageName());
-
- assertEquals(TEST_SERVICE2_NAME.getPackageName(), mTestGbaManager.getServicePackage());
-
- mLooper.processAllMessages();
- unbindService(conn);
- bindAndConnectService(TEST_SERVICE2_NAME);
- assertTrue(mTestGbaManager.isServiceConnected());
- }
-
- @Test
- @SmallTest
- public void testBindServiceWhenReleaseTimeChanged() {
- mTestGbaManager.overrideServicePackage(TEST_DEFAULT_SERVICE_NAME.getPackageName());
- mTestGbaManager.overrideReleaseTime(RELEASE_NEVER);
-
- assertEquals(RELEASE_NEVER, mTestGbaManager.getReleaseTime());
- mLooper.processAllMessages();
- bindAndConnectService(TEST_DEFAULT_SERVICE_NAME);
-
- assertTrue(mTestGbaManager.isServiceConnected());
- }
-
- @Test
- @SmallTest
- public void testDontBindServiceWhenPackageNameChanged() {
- mTestGbaManager.overrideServicePackage(TEST_SERVICE2_NAME.getPackageName());
-
- mLooper.processAllMessages();
-
- verify(mMockContext, never()).bindService(any(), any(), anyInt());
- assertTrue(!mTestGbaManager.isServiceConnected());
- }
-
- @Test
- @SmallTest
- public void testDontBindServiceWhenReleaseTimeChanged() {
- mTestGbaManager.overrideServicePackage(TEST_DEFAULT_SERVICE_NAME.getPackageName());
- mTestGbaManager.overrideReleaseTime(RELEASE_TIME_60S);
-
- mLooper.processAllMessages();
-
- verify(mMockContext, never()).bindService(any(), any(), anyInt());
- assertTrue(!mTestGbaManager.isServiceConnected());
- }
-
- private ServiceConnection bindAndConnectService(ComponentName component) {
- ServiceConnection connection = bindService(component);
- IGbaService.Stub serviceStub = mock(IGbaService.Stub.class);
- when(mMockBinder.isBinderAlive()).thenReturn(true);
- when(serviceStub.queryLocalInterface(any())).thenReturn(mMockGbaServiceBinder);
- connection.onServiceConnected(component, serviceStub);
- return connection;
- }
-
- private ServiceConnection bindService(ComponentName component) {
- ArgumentCaptor<Intent> intentCaptor =
- ArgumentCaptor.forClass(Intent.class);
- ArgumentCaptor<ServiceConnection> serviceCaptor =
- ArgumentCaptor.forClass(ServiceConnection.class);
- verify(mMockContext, atLeastOnce()).bindService(intentCaptor.capture(),
- serviceCaptor.capture(), eq(
- Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE));
- Intent testIntent = intentCaptor.getValue();
- assertEquals(GbaService.SERVICE_INTERFACE, testIntent.getAction());
- assertEquals(component.getPackageName(), testIntent.getPackage());
- return serviceCaptor.getValue();
- }
-
- private void unbindService(ServiceConnection conn) {
- verify(mMockContext).unbindService(eq(conn));
- }
-
- private GbaAuthRequest createDefaultRequest() {
- final String naf = "3GPP-bootstrapping@naf1.operator.com";
- final UaSecurityProtocolIdentifier.Builder builder =
- new UaSecurityProtocolIdentifier.Builder();
- builder.setOrg(UaSecurityProtocolIdentifier.ORG_3GPP).setProtocol(
- UaSecurityProtocolIdentifier.UA_SECURITY_PROTOCOL_3GPP_HTTP_BASED_MBMS);
- return new GbaAuthRequest(TEST_SUB_ID, TelephonyManager.APPTYPE_USIM,
- Uri.parse(naf), builder.build().toByteArray(), true, mMockCallback);
- }
-
- private void log(String str) {
- Log.d(LOG_TAG, str);
- }
-}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/GsmCdmaCallTest.java b/tests/telephonytests/src/com/android/internal/telephony/GsmCdmaCallTest.java
index 15eb59eed3..d4c3d029a8 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/GsmCdmaCallTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/GsmCdmaCallTest.java
@@ -121,8 +121,6 @@ public class GsmCdmaCallTest extends TelephonyTest {
doReturn(Call.State.DISCONNECTED).when(mConnection2).getState();
mCallUnderTest.connectionDisconnected(null);
assertEquals(Call.State.DISCONNECTED, mCallUnderTest.getState());
- mCallUnderTest.onHangupLocal();
- assertEquals(Call.State.DISCONNECTED, mCallUnderTest.getState());
}
} \ No newline at end of file
diff --git a/tests/telephonytests/src/com/android/internal/telephony/GsmCdmaCallTrackerTest.java b/tests/telephonytests/src/com/android/internal/telephony/GsmCdmaCallTrackerTest.java
index 3fdcc78c75..c0b07a8437 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/GsmCdmaCallTrackerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/GsmCdmaCallTrackerTest.java
@@ -32,7 +32,6 @@ import android.os.Message;
import android.telephony.DisconnectCause;
import android.telephony.PhoneNumberUtils;
import android.telephony.ServiceState;
-import android.telephony.emergency.EmergencyNumber;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.testing.AndroidTestingRunner;
@@ -40,8 +39,6 @@ import android.testing.TestableLooper;
import androidx.test.filters.FlakyTest;
-import com.android.internal.telephony.PhoneInternalInterface.DialArgs;
-
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
@@ -56,7 +53,6 @@ import org.mockito.Mock;
public class GsmCdmaCallTrackerTest extends TelephonyTest {
private static final int VOICE_CALL_STARTED_EVENT = 0;
private static final int VOICE_CALL_ENDED_EVENT = 1;
- private static final String TEST_DIAL_STRING = "54321";
private String mDialString = PhoneNumberUtils.stripSeparators("+17005554141");
/* Handler class initiated at the HandlerThread */
private GsmCdmaCallTracker mCTUT;
@@ -87,16 +83,6 @@ public class GsmCdmaCallTrackerTest extends TelephonyTest {
@Test
@SmallTest
- public void testCLIRMode() throws Exception {
- DialArgs dialArgs = new DialArgs.Builder().setIsEmergency(true).build();
- mCTUT.dialGsm(TEST_DIAL_STRING, dialArgs);
- verify(mSimulatedCommandsVerifier).dial(eq(TEST_DIAL_STRING), eq(true),
- isA(EmergencyNumber.class), eq(false), eq(CommandsInterface.CLIR_SUPPRESSION),
- eq((UUSInfo) null), isA(Message.class));
- }
-
- @Test
- @SmallTest
public void testMOCallDial() {
doReturn(ServiceState.STATE_IN_SERVICE).when(mServiceState).getState();
assertEquals(PhoneConstants.State.IDLE, mCTUT.getState());
@@ -104,7 +90,7 @@ public class GsmCdmaCallTrackerTest extends TelephonyTest {
assertEquals(GsmCdmaCall.State.IDLE, mCTUT.mBackgroundCall.getState());
assertEquals(0, mCTUT.mForegroundCall.getConnections().size());
try {
- mCTUT.dial(mDialString, new DialArgs.Builder().build());
+ mCTUT.dial(mDialString, new Bundle());
processAllMessages();
} catch(Exception ex) {
ex.printStackTrace();
@@ -217,7 +203,7 @@ public class GsmCdmaCallTrackerTest extends TelephonyTest {
String mDialString = PhoneNumberUtils.stripSeparators("+17005554142");
try {
- mCTUT.dial(mDialString, new DialArgs.Builder().build());
+ mCTUT.dial(mDialString, new Bundle());
} catch(Exception ex) {
ex.printStackTrace();
Assert.fail("unexpected exception thrown" + ex.getMessage());
@@ -463,7 +449,7 @@ public class GsmCdmaCallTrackerTest extends TelephonyTest {
processAllMessages();
// Try to place another call.
try {
- mCTUT.dial("650-555-1212", new DialArgs.Builder().build());
+ mCTUT.dial("650-555-1212", new Bundle());
} catch (CallStateException cse) {
assertEquals(CallStateException.ERROR_OTASP_PROVISIONING_IN_PROCESS, cse.getError());
return;
diff --git a/tests/telephonytests/src/com/android/internal/telephony/GsmCdmaConnectionTest.java b/tests/telephonytests/src/com/android/internal/telephony/GsmCdmaConnectionTest.java
index a078642b1a..93e3d87997 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/GsmCdmaConnectionTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/GsmCdmaConnectionTest.java
@@ -30,17 +30,12 @@ import android.test.suitebuilder.annotation.SmallTest;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
-import com.android.internal.telephony.PhoneInternalInterface.DialArgs;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
-import java.util.ArrayList;
-import java.util.Arrays;
-
@RunWith(AndroidTestingRunner.class)
@TestableLooper.RunWithLooper
public class GsmCdmaConnectionTest extends TelephonyTest {
@@ -62,10 +57,7 @@ public class GsmCdmaConnectionTest extends TelephonyTest {
@After
public void tearDown() throws Exception {
- if (connection != null) {
- connection.dispose();
- connection = null;
- }
+ connection = null;
super.tearDown();
}
@@ -73,7 +65,7 @@ public class GsmCdmaConnectionTest extends TelephonyTest {
public void testFormatDialString(){
connection = new GsmCdmaConnection(mPhone, String.format(
"+1 (700).555-41NN%c1234", PhoneNumberUtils.PAUSE), mCT, null,
- new DialArgs.Builder().build());
+ false /*isEmergencyCall*/);
/* case 1: If PAUSE/WAIT sequence at the end, ignore them */
String formattedDialStr = connection.formatDialString(
String.format("+1 (700).555-41NN1234%c", PhoneNumberUtils.PAUSE));
@@ -89,12 +81,12 @@ public class GsmCdmaConnectionTest extends TelephonyTest {
public void testOriginalDialString(){
doReturn(PhoneConstants.PHONE_TYPE_CDMA).when(mPhone).getPhoneType();
connection = new GsmCdmaConnection(mPhone, "+8610000", mCT, null,
- new DialArgs.Builder().build());
+ false /*isEmergencyCall*/);
assertEquals("+8610000", connection.getOrigDialString());
doReturn(PhoneConstants.PHONE_TYPE_GSM).when(mPhone).getPhoneType();
connection = new GsmCdmaConnection(mPhone, "+8610000", mCT, null,
- new DialArgs.Builder().build());
+ false /*isEmergencyCall*/);
assertEquals("+8610000", connection.getOrigDialString());
}
@@ -102,7 +94,7 @@ public class GsmCdmaConnectionTest extends TelephonyTest {
public void testSanityGSM() {
connection = new GsmCdmaConnection(mPhone, String.format(
"+1 (700).555-41NN%c1234", PhoneNumberUtils.PAUSE), mCT, null,
- new DialArgs.Builder().build());
+ false /*isEmergencyCall*/);
logd("Testing initial state of GsmCdmaConnection");
assertEquals(GsmCdmaCall.State.IDLE, connection.getState());
assertEquals(Connection.PostDialState.NOT_STARTED, connection.getPostDialState());
@@ -120,7 +112,7 @@ public class GsmCdmaConnectionTest extends TelephonyTest {
doReturn(PhoneConstants.PHONE_TYPE_CDMA).when(mPhone).getPhoneType();
connection = new GsmCdmaConnection(mPhone, String.format(
"+1 (700).555-41NN%c1234", PhoneNumberUtils.PAUSE), mCT, null,
- new DialArgs.Builder().build());
+ false /*isEmergencyCall*/);
logd("Testing initial state of GsmCdmaConnection");
assertEquals(GsmCdmaCall.State.IDLE, connection.getState());
assertEquals(Connection.PostDialState.NOT_STARTED, connection.getPostDialState());
@@ -137,7 +129,7 @@ public class GsmCdmaConnectionTest extends TelephonyTest {
public void testConnectionStateUpdate() {
connection = new GsmCdmaConnection(mPhone, String.format(
"+1 (700).555-41NN%c1234", PhoneNumberUtils.PAUSE), mCT, null,
- new DialArgs.Builder().build());
+ false /*isEmergencyCall*/);
logd("Update the connection state from idle to active");
mDC.state = DriverCall.State.ACTIVE;
connection.update(mDC);
@@ -157,7 +149,7 @@ public class GsmCdmaConnectionTest extends TelephonyTest {
doReturn(PhoneConstants.PHONE_TYPE_CDMA).when(mPhone).getPhoneType();
connection = new GsmCdmaConnection(mPhone, String.format(
"+1 (700).555-41NN%c1234", PhoneNumberUtils.PAUSE), mCT, null,
- new DialArgs.Builder().build());
+ false /*isEmergencyCall*/);
logd("Mock connection state from alerting to active ");
mDC.state = DriverCall.State.ALERTING;
connection.update(mDC);
@@ -175,7 +167,7 @@ public class GsmCdmaConnectionTest extends TelephonyTest {
public void testGSMPostDialPause() {
connection = new GsmCdmaConnection(mPhone, String.format(
"+1 (700).555-41NN%c1234", PhoneNumberUtils.PAUSE), mCT, null,
- new DialArgs.Builder().build());
+ false /*isEmergencyCall*/);
logd("Mock connection state from alerting to active ");
mDC.state = DriverCall.State.ALERTING;
connection.update(mDC);
@@ -195,7 +187,7 @@ public class GsmCdmaConnectionTest extends TelephonyTest {
doReturn(PhoneConstants.PHONE_TYPE_CDMA).when(mPhone).getPhoneType();
connection = new GsmCdmaConnection(mPhone,
String.format("+1 (700).555-41NN%c1234", PhoneNumberUtils.WAIT),mCT,null,
- new DialArgs.Builder().build());
+ false /*isEmergencyCall*/);
logd("Mock connection state transition from alerting to active ");
mDC.state = DriverCall.State.ALERTING;
connection.update(mDC);
@@ -212,7 +204,7 @@ public class GsmCdmaConnectionTest extends TelephonyTest {
public void testHangUpConnection() {
connection = new GsmCdmaConnection(mPhone, String.format(
"+1 (700).555-41NN%c1234", PhoneNumberUtils.PAUSE), mCT, null,
- new DialArgs.Builder().build());
+ false /*isEmergencyCall*/);
mDC.state = DriverCall.State.ACTIVE;
connection.update(mDC);
logd("Hangup the connection locally");
@@ -237,8 +229,7 @@ public class GsmCdmaConnectionTest extends TelephonyTest {
{"+8112345*00000", "+8112345", "+8112345*00000"}};
mDC.state = DriverCall.State.ALERTING;
for (String[] testAddress : testAddressMappingSet) {
- connection = new GsmCdmaConnection(mPhone, testAddress[0], mCT, null,
- new DialArgs.Builder().build());
+ connection = new GsmCdmaConnection(mPhone, testAddress[0], mCT, null, false);
connection.setIsIncoming(true);
mDC.number = testAddress[1];
connection.update(mDC);
@@ -252,48 +243,10 @@ public class GsmCdmaConnectionTest extends TelephonyTest {
@Test @SmallTest
public void testAddressUpdateOutgoing() {
mDC.state = DriverCall.State.ALERTING;
- connection = new GsmCdmaConnection(mPhone, "12345", mCT, null,
- new DialArgs.Builder().build());
+ connection = new GsmCdmaConnection(mPhone, "12345", mCT, null, false);
connection.setIsIncoming(false);
mDC.number = "678";
connection.update(mDC);
assertEquals("12345", connection.getAddress());
}
-
- @Test @SmallTest
- public void testRedirectingAddressUpdate() {
- String forwardedNumber = "11111";
-
- connection = new GsmCdmaConnection(mPhone, "12345", mCT, null,
- new DialArgs.Builder().build());
- connection.setIsIncoming(true);
- assertEquals(null, connection.getForwardedNumber());
- mDC.state = DriverCall.State.ALERTING;
- mDC.forwardedNumber = forwardedNumber;
- connection.update(mDC);
- assertEquals(new ArrayList<String>(Arrays.asList(forwardedNumber)),
- connection.getForwardedNumber());
-
- connection = new GsmCdmaConnection(mPhone, mDC, mCT, 0);
- assertEquals(new ArrayList<String>(Arrays.asList(forwardedNumber)),
- connection.getForwardedNumber());
- }
-
- @Test @SmallTest
- public void testForwardedNumberEmptyNull() {
- mDC.state = DriverCall.State.INCOMING;
- mDC.forwardedNumber = "";
- connection = new GsmCdmaConnection(mPhone, mDC, mCT, 0);
- assertNull(connection.getForwardedNumber());
- mDC.forwardedNumber = null;
- connection.update(mDC);
- assertNull(connection.getForwardedNumber());
-
- mDC.forwardedNumber = null;
- connection = new GsmCdmaConnection(mPhone, mDC, mCT, 0);
- assertNull(connection.getForwardedNumber());
- mDC.forwardedNumber = "";
- connection.update(mDC);
- assertNull(connection.getForwardedNumber());
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/GsmCdmaPhoneTest.java b/tests/telephonytests/src/com/android/internal/telephony/GsmCdmaPhoneTest.java
index 2f98164b68..562a60808c 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/GsmCdmaPhoneTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/GsmCdmaPhoneTest.java
@@ -25,8 +25,6 @@ import static com.android.internal.telephony.TelephonyTestUtils.waitForMs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
@@ -45,7 +43,6 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
import android.content.Intent;
import android.content.SharedPreferences;
@@ -61,12 +58,10 @@ import android.telephony.CarrierConfigManager;
import android.telephony.CellIdentity;
import android.telephony.CellIdentityCdma;
import android.telephony.CellIdentityGsm;
-import android.telephony.LinkCapacityEstimate;
import android.telephony.NetworkRegistrationInfo;
import android.telephony.ServiceState;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
-import android.telephony.data.ApnSetting;
import android.test.suitebuilder.annotation.SmallTest;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
@@ -74,7 +69,6 @@ import android.testing.TestableLooper;
import androidx.test.filters.FlakyTest;
import com.android.internal.telephony.test.SimulatedCommands;
-import com.android.internal.telephony.test.SimulatedCommandsVerifier;
import com.android.internal.telephony.uicc.IccCardApplicationStatus;
import com.android.internal.telephony.uicc.IccCardStatus;
import com.android.internal.telephony.uicc.IccRecords;
@@ -93,7 +87,6 @@ import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Mockito;
-import java.util.ArrayList;
import java.util.List;
@RunWith(AndroidTestingRunner.class)
@@ -134,10 +127,9 @@ public class GsmCdmaPhoneTest extends TelephonyTest {
super.setUp(getClass().getSimpleName());
doReturn(false).when(mSST).isDeviceShuttingDown();
- doReturn(true).when(mImsManager).isVolteEnabledByPlatform();
mPhoneUT = new GsmCdmaPhone(mContext, mSimulatedCommands, mNotifier, true, 0,
- PhoneConstants.PHONE_TYPE_GSM, mTelephonyComponentFactory, (c, p) -> mImsManager);
+ PhoneConstants.PHONE_TYPE_GSM, mTelephonyComponentFactory);
mPhoneUT.setVoiceCallSessionStats(mVoiceCallSessionStats);
ArgumentCaptor<Integer> integerArgumentCaptor = ArgumentCaptor.forClass(Integer.class);
verify(mUiccController).registerForIccChanged(eq(mPhoneUT), integerArgumentCaptor.capture(),
@@ -388,7 +380,7 @@ public class GsmCdmaPhoneTest extends TelephonyTest {
WorkSource workSource = new WorkSource(Process.myUid(),
mContext.getPackageName());
doReturn(cellLocation).when(mSST).getCellIdentity();
- assertEquals(cellLocation, mPhoneUT.getCurrentCellIdentity());
+ assertEquals(cellLocation, mPhoneUT.getCellIdentity());
// Switch to CDMA
switchToCdma();
@@ -397,7 +389,7 @@ public class GsmCdmaPhoneTest extends TelephonyTest {
doReturn(cdmaCellLocation).when(mSST).getCellIdentity();
CellIdentityCdma actualCellLocation =
- (CellIdentityCdma) mPhoneUT.getCurrentCellIdentity();
+ (CellIdentityCdma) mPhoneUT.getCellIdentity();
assertEquals(actualCellLocation, cdmaCellLocation);
}
@@ -420,29 +412,29 @@ public class GsmCdmaPhoneTest extends TelephonyTest {
// 1. GSM, getCurrentDataConnectionState != STATE_IN_SERVICE, apn != APN_TYPE_EMERGENCY
doReturn(ServiceState.STATE_OUT_OF_SERVICE).when(mSST).getCurrentDataConnectionState();
assertEquals(PhoneConstants.DataState.DISCONNECTED, mPhoneUT.getDataConnectionState(
- ApnSetting.TYPE_ALL_STRING));
+ PhoneConstants.APN_TYPE_ALL));
// 2. GSM, getCurrentDataConnectionState != STATE_IN_SERVICE, apn = APN_TYPE_EMERGENCY, apn
// not connected
doReturn(DctConstants.State.IDLE).when(mDcTracker).getState(
- ApnSetting.TYPE_EMERGENCY_STRING);
+ PhoneConstants.APN_TYPE_EMERGENCY);
assertEquals(PhoneConstants.DataState.DISCONNECTED, mPhoneUT.getDataConnectionState(
- ApnSetting.TYPE_EMERGENCY_STRING));
+ PhoneConstants.APN_TYPE_EMERGENCY));
// 3. GSM, getCurrentDataConnectionState != STATE_IN_SERVICE, apn = APN_TYPE_EMERGENCY,
// APN is connected, callTracker state = idle
doReturn(DctConstants.State.CONNECTED).when(mDcTracker).getState(
- ApnSetting.TYPE_EMERGENCY_STRING);
+ PhoneConstants.APN_TYPE_EMERGENCY);
mCT.mState = PhoneConstants.State.IDLE;
assertEquals(PhoneConstants.DataState.CONNECTED, mPhoneUT.getDataConnectionState(
- ApnSetting.TYPE_EMERGENCY_STRING));
+ PhoneConstants.APN_TYPE_EMERGENCY));
// 3. GSM, getCurrentDataConnectionState != STATE_IN_SERVICE, apn = APN_TYPE_EMERGENCY,
// APN enabled and CONNECTED, callTracker state != idle, !isConcurrentVoiceAndDataAllowed
mCT.mState = PhoneConstants.State.RINGING;
doReturn(false).when(mSST).isConcurrentVoiceAndDataAllowed();
assertEquals(PhoneConstants.DataState.SUSPENDED, mPhoneUT.getDataConnectionState(
- ApnSetting.TYPE_EMERGENCY_STRING));
+ PhoneConstants.APN_TYPE_EMERGENCY));
}
@Test
@@ -494,140 +486,7 @@ public class GsmCdmaPhoneTest extends TelephonyTest {
Connection connection = mPhoneUT.dial("1234567890",
new PhoneInternalInterface.DialArgs.Builder().build());
- verify(mCT).dialGsm(eq("1234567890"), any(PhoneInternalInterface.DialArgs.class));
- } catch (CallStateException e) {
- fail();
- }
- }
-
- @Test
- @SmallTest
- public void testWpsDialOverCs() throws Exception {
- try {
- setupForWpsCallTest();
-
- mContextFixture.getCarrierConfigBundle().putBoolean(
- CarrierConfigManager.KEY_SUPPORT_WPS_OVER_IMS_BOOL, false);
-
- mPhoneUT.dial("*27216505551212", new PhoneInternalInterface.DialArgs.Builder().build());
-
- verify(mCT).dialGsm(eq("*27216505551212"), any(PhoneInternalInterface.DialArgs.class));
- verify(mImsCT).hangupAllConnections();
- } catch (CallStateException e) {
- fail();
- }
- }
-
- @Test
- @SmallTest
- public void testClirCs() {
- mPhoneUT.mCi = mMockCi;
- // Start out with no preference set and ensure CommandsInterface receives setClir with
- // the default set.
- mPhoneUT.sendEmptyMessage(Phone.EVENT_REGISTERED_TO_NETWORK);
- processAllMessages();
- verify(mMockCi).setCLIR(eq(CommandsInterface.CLIR_DEFAULT), any());
- // Now set the CLIR mode explicitly
- mPhoneUT.setOutgoingCallerIdDisplay(CommandsInterface.CLIR_SUPPRESSION, null);
- ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
- verify(mMockCi).setCLIR(eq(CommandsInterface.CLIR_SUPPRESSION), messageCaptor.capture());
- Message message = messageCaptor.getValue();
- assertNotNull(message);
- message.obj = AsyncResult.forMessage(message);
- // Now Call registered to network again and the CLIR mode sent should reflect the new value.
- mPhoneUT.sendEmptyMessage(Phone.EVENT_REGISTERED_TO_NETWORK);
- processAllMessages();
- verify(mMockCi).setCLIR(eq(CommandsInterface.CLIR_SUPPRESSION), any());
- }
-
- @Test
- @SmallTest
- public void testWpsClirActiveDialOverCs() throws Exception {
- try {
- setupForWpsCallTest();
-
- mContextFixture.getCarrierConfigBundle().putBoolean(
- CarrierConfigManager.KEY_SUPPORT_WPS_OVER_IMS_BOOL, false);
-
- mPhoneUT.dial("*31#*27216505551212",
- new PhoneInternalInterface.DialArgs.Builder().build());
-
- verify(mCT).dialGsm("*27216505551212", CommandsInterface.CLIR_SUPPRESSION, null, null);
- verify(mImsCT).hangupAllConnections();
- } catch (CallStateException e) {
- fail();
- }
- }
-
- @Test
- @SmallTest
- public void testWpsClirInactiveDialOverCs() throws Exception {
- try {
- setupForWpsCallTest();
-
- mContextFixture.getCarrierConfigBundle().putBoolean(
- CarrierConfigManager.KEY_SUPPORT_WPS_OVER_IMS_BOOL, false);
-
- mPhoneUT.dial("#31#*27216505551212",
- new PhoneInternalInterface.DialArgs.Builder().build());
-
- verify(mCT).dialGsm("*27216505551212", CommandsInterface.CLIR_INVOCATION, null, null);
- verify(mImsCT).hangupAllConnections();
- } catch (CallStateException e) {
- fail();
- }
- }
-
- @Test
- @SmallTest
- public void testWpsDialOverIms() throws Exception {
- try {
- setupForWpsCallTest();
-
- mContextFixture.getCarrierConfigBundle().putBoolean(
- CarrierConfigManager.KEY_SUPPORT_WPS_OVER_IMS_BOOL, true);
-
- mPhoneUT.dial("*27216505551212",
- new PhoneInternalInterface.DialArgs.Builder().build());
- verify(mCT).dialGsm(eq("*27216505551212"), any(PhoneInternalInterface.DialArgs.class));
- verify(mImsCT, never()).hangupAllConnections();
- } catch (CallStateException e) {
- fail();
- }
- }
-
- @Test
- @SmallTest
- public void testWpsClirActiveDialOverIms() throws Exception {
- try {
- setupForWpsCallTest();
-
- mContextFixture.getCarrierConfigBundle().putBoolean(
- CarrierConfigManager.KEY_SUPPORT_WPS_OVER_IMS_BOOL, true);
-
- mPhoneUT.dial("*31#*27216505551212",
- new PhoneInternalInterface.DialArgs.Builder().build());
- verify(mCT).dialGsm("*27216505551212", CommandsInterface.CLIR_SUPPRESSION, null, null);
- verify(mImsCT, never()).hangupAllConnections();
- } catch (CallStateException e) {
- fail();
- }
- }
-
- @Test
- @SmallTest
- public void testWpsClirInactiveDialOverIms() throws Exception {
- try {
- setupForWpsCallTest();
-
- mContextFixture.getCarrierConfigBundle().putBoolean(
- CarrierConfigManager.KEY_SUPPORT_WPS_OVER_IMS_BOOL, true);
-
- mPhoneUT.dial("#31#*27216505551212",
- new PhoneInternalInterface.DialArgs.Builder().build());
-
- verify(mCT).dialGsm("*27216505551212", CommandsInterface.CLIR_INVOCATION, null, null);
- verify(mImsCT, never()).hangupAllConnections();
+ verify(mCT).dialGsm("1234567890", null, null);
} catch (CallStateException e) {
fail();
}
@@ -1010,32 +869,6 @@ public class GsmCdmaPhoneTest extends TelephonyTest {
}
@Test
- public void testZeroMeid() {
- doReturn(false).when(mSST).isDeviceShuttingDown();
-
- SimulatedCommands sc = new SimulatedCommands() {
- @Override
- public void getDeviceIdentity(Message response) {
- SimulatedCommandsVerifier.getInstance().getDeviceIdentity(response);
- resultSuccess(response, new String[] {FAKE_IMEI, FAKE_IMEISV, FAKE_ESN, "0000000"});
- }
- };
-
- Phone phone = new GsmCdmaPhone(mContext, sc, mNotifier, true, 0,
- PhoneConstants.PHONE_TYPE_GSM, mTelephonyComponentFactory, (c, p) -> mImsManager);
- phone.setVoiceCallSessionStats(mVoiceCallSessionStats);
- ArgumentCaptor<Integer> integerArgumentCaptor = ArgumentCaptor.forClass(Integer.class);
- verify(mUiccController).registerForIccChanged(eq(phone), integerArgumentCaptor.capture(),
- nullable(Object.class));
- Message msg = Message.obtain();
- msg.what = integerArgumentCaptor.getValue();
- phone.sendMessage(msg);
- processAllMessages();
-
- assertNull(phone.getMeid());
- }
-
- @Test
@SmallTest
public void testEmergencyCallbackMessages() throws Exception {
verify(mSimulatedCommandsVerifier).setEmergencyCallbackMode(eq(mPhoneUT), anyInt(),
@@ -1236,7 +1069,7 @@ public class GsmCdmaPhoneTest extends TelephonyTest {
@Test
@SmallTest
public void testGetIccCardUnknownAndAbsent() {
- // If UiccSlot.isStateUnknown is true, we should return a placeholder IccCard with the state
+ // If UiccSlot.isStateUnknown is true, we should return a dummy IccCard with the state
// set to UNKNOWN
doReturn(null).when(mUiccController).getUiccProfileForPhone(anyInt());
UiccSlot mockSlot = mock(UiccSlot.class);
@@ -1246,7 +1079,7 @@ public class GsmCdmaPhoneTest extends TelephonyTest {
IccCard iccCard = mPhoneUT.getIccCard();
assertEquals(IccCardConstants.State.UNKNOWN, iccCard.getState());
- // if isStateUnknown is false, we should return a placeholder IccCard with the state set to
+ // if isStateUnknown is false, we should return a dummy IccCard with the state set to
// ABSENT
doReturn(false).when(mockSlot).isStateUnknown();
iccCard = mPhoneUT.getIccCard();
@@ -1260,7 +1093,7 @@ public class GsmCdmaPhoneTest extends TelephonyTest {
IccCard iccCard = mPhoneUT.getIccCard();
- // The iccCard should be a placeholder object, not null.
+ // The iccCard should be a dummy object, not null.
assertTrue(!(iccCard instanceof UiccProfile));
assertTrue(iccCard != null);
@@ -1426,25 +1259,11 @@ public class GsmCdmaPhoneTest extends TelephonyTest {
@SmallTest
public void testSetRadioPower() throws Exception {
mPhoneUT.setRadioPower(false);
- verify(mSST).setRadioPowerForReason(false, false, false, false,
- Phone.RADIO_POWER_REASON_USER);
+ verify(mSST).setRadioPower(false, false, false, false);
// Turn on radio for emergency call.
mPhoneUT.setRadioPower(true, true, false, true);
- verify(mSST).setRadioPowerForReason(true, true, false, true, Phone.RADIO_POWER_REASON_USER);
- }
-
- @Test
- @SmallTest
- public void testSetRadioPowerOnForTestEmergencyCall() {
- mPhoneUT.setRadioPower(false);
- verify(mSST).setRadioPowerForReason(false, false, false, false,
- Phone.RADIO_POWER_REASON_USER);
-
- mPhoneUT.setRadioPowerOnForTestEmergencyCall(false);
- verify(mSST).clearAllRadioOffReasons();
- verify(mSST).setRadioPowerForReason(eq(true), eq(false), anyBoolean(), eq(false),
- eq(Phone.RADIO_POWER_REASON_USER));
+ verify(mSST).setRadioPower(true, true, false, true);
}
@Test
@@ -1552,103 +1371,8 @@ public class GsmCdmaPhoneTest extends TelephonyTest {
// Throw CallStateException(Phone.CS_FALLBACK) from ImsPhone.dial().
doReturn(Phone.CS_FALLBACK).when(callStateException).getMessage();
- doThrow(callStateException).when(mImsPhone).dial(eq("*135#"),
- any(PhoneInternalInterface.DialArgs.class));
+ doThrow(callStateException).when(mImsPhone).dial("*135#", dialArgs);
replaceInstance(Phone.class, "mImsPhone", mPhoneUT, mImsPhone);
}
-
- @Test
- public void testEventCarrierConfigChanged() {
- mPhoneUT.mCi = mMockCi;
- mPhoneUT.sendMessage(mPhoneUT.obtainMessage(Phone.EVENT_CARRIER_CONFIG_CHANGED));
- processAllMessages();
-
- ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
- verify(mMockCi).getRadioCapability(captor.capture());
- assertEquals(captor.getValue().what, Phone.EVENT_GET_RADIO_CAPABILITY);
- }
-
- private void setupForWpsCallTest() throws Exception {
- mSST.mSS = mServiceState;
- doReturn(ServiceState.STATE_IN_SERVICE).when(mServiceState).getState();
- when(mImsPhone.getCallTracker()).thenReturn(mImsCT);
- mCT.mForegroundCall = mGsmCdmaCall;
- mCT.mBackgroundCall = mGsmCdmaCall;
- mCT.mRingingCall = mGsmCdmaCall;
- doReturn(GsmCdmaCall.State.IDLE).when(mGsmCdmaCall).getState();
- replaceInstance(Phone.class, "mImsPhone", mPhoneUT, mImsPhone);
- }
-
- @Test
- public void testEventLceUpdate() {
- mPhoneUT.mCi = mMockCi;
-
- ArgumentCaptor<List<LinkCapacityEstimate>> captor = ArgumentCaptor.forClass(List.class);
- List<LinkCapacityEstimate> lceList1 = new ArrayList<>();
- lceList1.add(new LinkCapacityEstimate(LinkCapacityEstimate.LCE_TYPE_PRIMARY, 2000, 5000));
- lceList1.add(new LinkCapacityEstimate(LinkCapacityEstimate.LCE_TYPE_SECONDARY, 1000, 1500));
-
- List<LinkCapacityEstimate> lceList2 = new ArrayList<>();
- lceList2.add(new LinkCapacityEstimate(LinkCapacityEstimate.LCE_TYPE_COMBINED, 2000, 5000));
-
- List<LinkCapacityEstimate> lceList3 = new ArrayList<>();
- lceList3.add(new LinkCapacityEstimate(LinkCapacityEstimate.LCE_TYPE_COMBINED, 2000,
- LinkCapacityEstimate.INVALID));
-
- mPhoneUT.sendMessage(mPhoneUT.obtainMessage(GsmCdmaPhone.EVENT_LINK_CAPACITY_CHANGED,
- new AsyncResult(null, lceList1, null)));
- processAllMessages();
- verify(mNotifier, times(1))
- .notifyLinkCapacityEstimateChanged(any(), captor.capture());
- assertEquals(2, captor.getValue().size());
- LinkCapacityEstimate lce1 = captor.getValue().get(1);
- assertEquals(1000, lce1.getDownlinkCapacityKbps());
- assertEquals(LinkCapacityEstimate.LCE_TYPE_SECONDARY, lce1.getType());
-
- mPhoneUT.sendMessage(mPhoneUT.obtainMessage(GsmCdmaPhone.EVENT_LINK_CAPACITY_CHANGED,
- new AsyncResult(null, lceList2, null)));
- processAllMessages();
- verify(mNotifier, times(2))
- .notifyLinkCapacityEstimateChanged(any(), captor.capture());
- assertEquals(1, captor.getValue().size());
-
- mPhoneUT.sendMessage(mPhoneUT.obtainMessage(GsmCdmaPhone.EVENT_LINK_CAPACITY_CHANGED,
- new AsyncResult(null, lceList3, null)));
- processAllMessages();
- verify(mNotifier, times(3))
- .notifyLinkCapacityEstimateChanged(any(), captor.capture());
- LinkCapacityEstimate lce3 = captor.getValue().get(0);
- assertEquals(LinkCapacityEstimate.INVALID, lce3.getUplinkCapacityKbps());
- assertEquals(LinkCapacityEstimate.LCE_TYPE_COMBINED, lce3.getType());
- }
-
- @Test
- @SmallTest
- public void testLoadAllowedNetworksFromSubscriptionDatabase_loadTheNullValue_isLoadedTrue() {
- int subId = 1;
- doReturn(subId).when(mSubscriptionController).getSubIdUsingPhoneId(anyInt());
-
- doReturn(null).when(mSubscriptionController).getSubscriptionProperty(anyInt(),
- eq(SubscriptionManager.ALLOWED_NETWORK_TYPES));
-
- mPhoneUT.loadAllowedNetworksFromSubscriptionDatabase();
-
- assertEquals(true, mPhoneUT.isAllowedNetworkTypesLoadedFromDb());
- }
-
- @Test
- @SmallTest
- public void testLoadAllowedNetworksFromSubscriptionDatabase_subIdNotValid_isLoadedFalse() {
- int subId = -1;
- doReturn(subId).when(mSubscriptionController).getSubIdUsingPhoneId(anyInt());
-
- when(mSubscriptionController.getSubscriptionProperty(anyInt(),
- eq(SubscriptionManager.ALLOWED_NETWORK_TYPES))).thenReturn(null);
-
-
- mPhoneUT.loadAllowedNetworksFromSubscriptionDatabase();
-
- assertEquals(false, mPhoneUT.isAllowedNetworkTypesLoadedFromDb());
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/IccSmsInterfaceManagerTest.java b/tests/telephonytests/src/com/android/internal/telephony/IccSmsInterfaceManagerTest.java
deleted file mode 100644
index 93cc4e9466..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/IccSmsInterfaceManagerTest.java
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.internal.telephony;
-
-import static com.android.internal.telephony.TelephonyTestUtils.waitForMs;
-
-import android.os.AsyncResult;
-import android.os.Message;
-import android.testing.AndroidTestingRunner;
-import android.testing.TestableLooper;
-
-import androidx.test.filters.SmallTest;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mock;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-@RunWith(AndroidTestingRunner.class)
-@TestableLooper.RunWithLooper
-public class IccSmsInterfaceManagerTest extends TelephonyTest {
- // object under test
- private IccSmsInterfaceManager mIccSmsInterfaceManager;
-
- @Mock
- private SmsPermissions mMockSmsPermissions;
-
- @Before
- public void setUp() throws Exception {
- super.setUp(getClass().getSimpleName());
- mIccSmsInterfaceManager = new IccSmsInterfaceManager(mPhone, mContext, mAppOpsManager,
- mSmsDispatchersController, mMockSmsPermissions);
- }
-
- @After
- public void tearDown() throws Exception {
- super.tearDown();
- }
-
- @Test
- @SmallTest
- public void testSynchronization() throws Exception {
- mContextFixture.addCallingOrSelfPermission(android.Manifest.permission
- .RECEIVE_EMERGENCY_BROADCAST);
- when(mMockSmsPermissions.checkCallingOrSelfCanGetSmscAddress(anyString(), anyString()))
- .thenReturn(true);
- mSimulatedCommands.mSendSetGsmBroadcastConfigResponse = false;
- mSimulatedCommands.mSendGetSmscAddressResponse = false;
- CountDownLatch enableRangeLatch = new CountDownLatch(1);
- CountDownLatch getSmscLatch = new CountDownLatch(1);
-
- // call enableGsmBroadcastRange from first thread
- Thread enableRangeThread = new Thread(new Runnable() {
- @Override
- public void run() {
- mIccSmsInterfaceManager.enableGsmBroadcastRange(0, 5);
- enableRangeLatch.countDown();
- }
- });
- enableRangeThread.start();
-
- // call getSmscAddressFromIccEf from second thread
- Thread getSmscThread = new Thread(new Runnable() {
- @Override
- public void run() {
- mIccSmsInterfaceManager.getSmscAddressFromIccEf("calling package");
- getSmscLatch.countDown();
- }
- });
- getSmscThread.start();
-
- // wait for half a second to let the threads send their messages
- waitForMs(500);
- processAllMessages();
-
- // latch count should not be reduced until response is sent
- assertEquals("enableRangeLatch.getCount should be 1", 1, enableRangeLatch.getCount());
- assertEquals("getSmscLatch.getCount should be 1", 1, getSmscLatch.getCount());
-
- // send back response for first request and assert that only the first thread is unblocked
- ArgumentCaptor<Message> enableRangeCaptor = ArgumentCaptor.forClass(Message.class);
- verify(mSimulatedCommandsVerifier).setGsmBroadcastConfig(any(),
- enableRangeCaptor.capture());
- Message enableRangeResponse = enableRangeCaptor.getValue();
- AsyncResult.forMessage(enableRangeResponse);
- enableRangeResponse.sendToTarget();
- processAllMessages();
-
- // the response triggers setGsmBroadcastActivation and since that's on another thread
- // (enableRangeThread), wait for half a second for the response message of that to reach
- // the handler before calling processAllMessages(). Consider increasing this timeout if the
- // test fails.
- waitForMs(500);
- processAllMessages();
-
- try {
- assertEquals("enableRangeLatch.await should be true", true,
- enableRangeLatch.await(5, TimeUnit.SECONDS));
- } catch (InterruptedException ie) {
- fail("enableRangeLatch.await interrupted");
- }
- assertEquals("getSmscLatch.getCount should still be 1", 1, getSmscLatch.getCount());
-
- // send back response for second request and assert that the second thread gets unblocked
- ArgumentCaptor<Message> getSmscCaptor = ArgumentCaptor.forClass(Message.class);
- verify(mSimulatedCommandsVerifier).getSmscAddress(getSmscCaptor.capture());
- Message getSmscResponse = getSmscCaptor.getValue();
- AsyncResult.forMessage(getSmscResponse);
- getSmscResponse.sendToTarget();
- processAllMessages();
-
- try {
- assertEquals("getSmscLatch.await should be true", true,
- getSmscLatch.await(5, TimeUnit.SECONDS));
- } catch (InterruptedException ie) {
- fail("getSmscLatch.await interrupted");
- }
- }
-}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/ImsSmsDispatcherTest.java b/tests/telephonytests/src/com/android/internal/telephony/ImsSmsDispatcherTest.java
index d4ac4d5fc0..d13152efb1 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/ImsSmsDispatcherTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/ImsSmsDispatcherTest.java
@@ -21,71 +21,49 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.nullable;
-import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
+import android.os.Looper;
import android.telephony.SmsMessage;
import android.telephony.ims.stub.ImsSmsImplBase;
import android.test.suitebuilder.annotation.SmallTest;
-import android.testing.AndroidTestingRunner;
-import android.testing.TestableLooper;
+import android.util.Pair;
-import com.android.ims.FeatureConnector;
-import com.android.ims.ImsManager;
import com.android.internal.util.HexDump;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
-import org.mockito.stubbing.Answer;
import java.util.HashMap;
-@RunWith(AndroidTestingRunner.class)
-@TestableLooper.RunWithLooper
public class ImsSmsDispatcherTest extends TelephonyTest {
@Mock private SmsDispatchersController mSmsDispatchersController;
@Mock private SMSDispatcher.SmsTracker mSmsTracker;
- @Mock private ImsSmsDispatcher.FeatureConnectorFactory mConnectorFactory;
- @Mock private FeatureConnector<ImsManager> mMockConnector;
- private FeatureConnector.Listener<ImsManager> mImsManagerListener;
private HashMap<String, Object> mTrackerData;
private ImsSmsDispatcher mImsSmsDispatcher;
@Before
public void setUp() throws Exception {
super.setUp(getClass().getSimpleName());
+ if (Looper.myLooper() == null) {
+ Looper.prepare();
+ }
- doAnswer((Answer<FeatureConnector<ImsManager>>) invocation -> {
- mImsManagerListener =
- (FeatureConnector.Listener<ImsManager>) invocation.getArguments()[3];
- return mMockConnector;
- }).when(mConnectorFactory).create(any(), anyInt(), anyString(), any(), any());
- mImsSmsDispatcher = new ImsSmsDispatcher(mPhone, mSmsDispatchersController,
- mConnectorFactory);
- processAllMessages();
- // set the ImsManager instance
- verify(mMockConnector).connect();
- mImsManagerListener.connectionReady(mImsManager);
+ mImsSmsDispatcher = spy(new ImsSmsDispatcher(mPhone, mSmsDispatchersController));
when(mSmsDispatchersController.isIms()).thenReturn(true);
+
mTrackerData = new HashMap<>(1);
when(mSmsTracker.getData()).thenReturn(mTrackerData);
}
- @After
- public void tearDown() throws Exception {
- mImsSmsDispatcher = null;
- super.tearDown();
- }
-
/**
* Send an SMS and verify that the token and PDU is correct.
*/
@@ -171,15 +149,22 @@ public class ImsSmsDispatcherTest extends TelephonyTest {
@Test
@SmallTest
public void testReceiveGsmSmsStatusReport() throws Exception {
+ int sentSmsToken = mImsSmsDispatcher.mNextToken.get();
int statusReportToken = 456; // Generated by IMS providers
int messageRef = 123; // TP-MR for sent SMS
+ int trackersSize = mImsSmsDispatcher.mTrackers.size();
// PDU for SMS-STATUS-REPORT
byte[] pdu = HexDump.hexStringToByteArray("0006000681214365919061800000639190618000006300");
// Set TP-MR
pdu[2] = (byte) messageRef;
+ mSmsTracker.mMessageRef = messageRef;
+ mImsSmsDispatcher.mTrackers.put(sentSmsToken, mSmsTracker);
when(mPhone.getPhoneType()).thenReturn(PhoneConstants.PHONE_TYPE_GSM);
+ when(mSmsDispatchersController.handleSmsStatusReport(
+ eq(mSmsTracker), eq(SmsMessage.FORMAT_3GPP), eq(pdu)))
+ .thenReturn(new Pair(true, true));
// Receive the status report
mImsSmsDispatcher
@@ -192,6 +177,7 @@ public class ImsSmsDispatcherTest extends TelephonyTest {
eq(statusReportToken),
eq(messageRef),
eq(ImsSmsImplBase.STATUS_REPORT_STATUS_OK));
+ assertEquals(trackersSize, mImsSmsDispatcher.mTrackers.size());
}
/**
@@ -213,4 +199,10 @@ public class ImsSmsDispatcherTest extends TelephonyTest {
ImsSmsImplBase.SEND_STATUS_ERROR, 0, 41);
verify(mSmsTracker).onFailed(any(Context.class), anyInt(), eq(41));
}
+
+ @After
+ public void tearDown() throws Exception {
+ mImsSmsDispatcher = null;
+ super.tearDown();
+ }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/InboundSmsTrackerTest.java b/tests/telephonytests/src/com/android/internal/telephony/InboundSmsTrackerTest.java
index 7bc26b79ca..cd97bdc1d2 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/InboundSmsTrackerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/InboundSmsTrackerTest.java
@@ -51,8 +51,7 @@ public class InboundSmsTrackerTest {
mInboundSmsTracker = new InboundSmsTracker(InstrumentationRegistry.getContext(),
FAKE_PDU, FAKE_TIMESTAMP, FAKE_DEST_PORT, false,
FAKE_ADDRESS, FAKE_DISPLAY_ADDRESS, FAKE_REFERENCE_NUMBER, FAKE_SEQUENCE_NUMBER,
- FAKE_MESSAGE_COUNT, false, FAKE_MESSAGE_BODY, false /* isClass0 */, FAKE_SUBID,
- InboundSmsHandler.SOURCE_NOT_INJECTED);
+ FAKE_MESSAGE_COUNT, false, FAKE_MESSAGE_BODY, false /* isClass0 */, FAKE_SUBID);
}
public static MatrixCursor createFakeCursor() {
@@ -88,7 +87,6 @@ public class InboundSmsTrackerTest {
assertEquals(FAKE_DISPLAY_ADDRESS, mInboundSmsTracker.getDisplayAddress());
assertEquals(false, mInboundSmsTracker.isClass0());
assertEquals(FAKE_SUBID, mInboundSmsTracker.getSubId());
- assertEquals(InboundSmsHandler.SOURCE_NOT_INJECTED, mInboundSmsTracker.getSource());
// assertNotEquals(0L, mInboundSmsTracker.getMessageId());
String[] args = new String[]{"123"};
diff --git a/tests/telephonytests/src/com/android/internal/telephony/IntRangeManagerTest.java b/tests/telephonytests/src/com/android/internal/telephony/IntRangeManagerTest.java
index ee75826822..a6fb620cbe 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/IntRangeManagerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/IntRangeManagerTest.java
@@ -40,7 +40,7 @@ public class IntRangeManagerTest extends AndroidTestCase {
private static final int ALL_FLAGS_SET = FLAG_START_UPDATE_CALLED | FLAG_ADD_RANGE_CALLED |
FLAG_FINISH_UPDATE_CALLED;
- /** IntRangeManager for testing. */
+ /** Dummy IntRangeManager for testing. */
class TestIntRangeManager extends IntRangeManager {
ArrayList<SmsBroadcastConfigInfo> mConfigList =
new ArrayList<SmsBroadcastConfigInfo>();
diff --git a/tests/telephonytests/src/com/android/internal/telephony/LocaleTrackerTest.java b/tests/telephonytests/src/com/android/internal/telephony/LocaleTrackerTest.java
index bab6408e34..5b147c0cd1 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/LocaleTrackerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/LocaleTrackerTest.java
@@ -87,7 +87,6 @@ public class LocaleTrackerTest extends TelephonyTest {
m.sendToTarget();
return null; }).when(mPhone).requestCellInfoUpdate(any(), any());
- doReturn(true).when(mPhone).isRadioOn();
processAllMessages();
logd("LocaleTrackerTest -Setup!");
}
@@ -136,7 +135,6 @@ public class LocaleTrackerTest extends TelephonyTest {
@Test
@SmallTest
public void testUpdateOperatorNumericSync() throws Exception {
- doReturn(false).when(mPhone).isRadioOn();
mLocaleTracker.updateOperatorNumeric(US_MCC + FAKE_MNC);
// Because the service state is in APM, the country ISO should be set empty.
assertEquals(COUNTRY_CODE_UNAVAILABLE, mLocaleTracker.getCurrentCountry());
@@ -163,7 +161,6 @@ public class LocaleTrackerTest extends TelephonyTest {
@SmallTest
public void testBootupInAirplaneModeOn() throws Exception {
mLocaleTracker.updateOperatorNumeric("");
- doReturn(false).when(mPhone).isRadioOn();
sendServiceState(ServiceState.STATE_POWER_OFF);
assertEquals(COUNTRY_CODE_UNAVAILABLE, mLocaleTracker.getCurrentCountry());
verifyCountryCodeNotified(new String[]{COUNTRY_CODE_UNAVAILABLE});
@@ -173,7 +170,6 @@ public class LocaleTrackerTest extends TelephonyTest {
@Test
@SmallTest
public void testToggleAirplaneModeOn() throws Exception {
- doReturn(true).when(mPhone).isRadioOn();
sendServiceState(ServiceState.STATE_IN_SERVICE);
mLocaleTracker.updateOperatorNumeric(US_MCC + FAKE_MNC);
assertEquals(US_COUNTRY_CODE, mLocaleTracker.getCurrentCountry());
@@ -187,7 +183,6 @@ public class LocaleTrackerTest extends TelephonyTest {
assertEquals(US_COUNTRY_CODE, mLocaleTracker.getCurrentCountry());
assertEquals(US_COUNTRY_CODE, mLocaleTracker.getLastKnownCountryIso());
verifyCountryCodeNotified(new String[]{COUNTRY_CODE_UNAVAILABLE, US_COUNTRY_CODE});
- doReturn(false).when(mPhone).isRadioOn();
sendServiceState(ServiceState.STATE_POWER_OFF);
assertFalse(mLocaleTracker.isTracking());
@@ -203,7 +198,6 @@ public class LocaleTrackerTest extends TelephonyTest {
@Test
@SmallTest
public void testToggleAirplaneModeOff() throws Exception {
- doReturn(false).when(mPhone).isRadioOn();
sendServiceState(ServiceState.STATE_POWER_OFF);
mLocaleTracker.updateOperatorNumeric("");
processAllMessages();
@@ -211,7 +205,6 @@ public class LocaleTrackerTest extends TelephonyTest {
verifyCountryCodeNotified(new String[]{COUNTRY_CODE_UNAVAILABLE});
assertFalse(mLocaleTracker.isTracking());
- doReturn(true).when(mPhone).isRadioOn();
sendServiceState(ServiceState.STATE_OUT_OF_SERVICE);
processAllMessages();
assertTrue(mLocaleTracker.isTracking());
@@ -221,7 +214,6 @@ public class LocaleTrackerTest extends TelephonyTest {
@Test
@SmallTest
public void testToggleAirplaneModeOosPlmn() throws Exception {
- doReturn(false).when(mPhone).isRadioOn();
sendServiceState(ServiceState.STATE_POWER_OFF);
mLocaleTracker.updateOperatorNumeric("");
processAllMessages();
@@ -236,7 +228,6 @@ public class LocaleTrackerTest extends TelephonyTest {
m.sendToTarget();
return null; }).when(mPhone).requestCellInfoUpdate(any(), any());
- doReturn(true).when(mPhone).isRadioOn();
sendServiceState(ServiceState.STATE_OUT_OF_SERVICE);
processAllMessages();
assertTrue(mLocaleTracker.isTracking());
diff --git a/tests/telephonytests/src/com/android/internal/telephony/MultiSimSettingControllerTest.java b/tests/telephonytests/src/com/android/internal/telephony/MultiSimSettingControllerTest.java
index 56689f4fc2..af72c705a2 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/MultiSimSettingControllerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/MultiSimSettingControllerTest.java
@@ -20,7 +20,6 @@ import static android.telephony.TelephonyManager.ACTION_PRIMARY_SUBSCRIPTION_LIS
import static android.telephony.TelephonyManager.EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE;
import static android.telephony.TelephonyManager.EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_ALL;
import static android.telephony.TelephonyManager.EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DATA;
-import static android.telephony.TelephonyManager.EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DISMISS;
import static android.telephony.TelephonyManager.EXTRA_SUBSCRIPTION_ID;
import static org.junit.Assert.assertEquals;
@@ -35,12 +34,9 @@ import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import android.content.Intent;
-import android.content.res.Resources;
-import android.os.HandlerThread;
import android.os.ParcelUuid;
import android.os.PersistableBundle;
import android.provider.Settings;
@@ -52,25 +48,18 @@ import android.test.suitebuilder.annotation.SmallTest;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
-import androidx.test.InstrumentationRegistry;
-
import com.android.internal.telephony.dataconnection.DataEnabledSettings;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
@RunWith(AndroidTestingRunner.class)
@TestableLooper.RunWithLooper
@@ -89,8 +78,6 @@ public class MultiSimSettingControllerTest extends TelephonyTest {
@Mock
private DataEnabledSettings mDataEnabledSettingsMock2;
private Phone[] mPhones;
- @Mock
- private CommandsInterface mMockCi;
ParcelUuid mGroupUuid1 = new ParcelUuid(UUID.randomUUID());
@@ -135,8 +122,6 @@ public class MultiSimSettingControllerTest extends TelephonyTest {
doReturn(true).when(mSubControllerMock).isOpportunistic(5);
doReturn(1).when(mPhoneMock1).getSubId();
doReturn(2).when(mPhoneMock2).getSubId();
- mPhoneMock1.mCi = mSimulatedCommands;
- mPhoneMock2.mCi = mSimulatedCommands;
List<SubscriptionInfo> infoList = Arrays.asList(mSubInfo1, mSubInfo2);
doReturn(infoList).when(mSubControllerMock)
.getActiveSubscriptionInfoList(anyString(), nullable(String.class));
@@ -168,7 +153,7 @@ public class MultiSimSettingControllerTest extends TelephonyTest {
@Test
@SmallTest
- public void testSubInfoChangeBeforeAllSubReady() throws Exception {
+ public void testTestSubInfoChangeBeforeAllSubReady() throws Exception {
doReturn(SubscriptionManager.INVALID_SUBSCRIPTION_ID).when(mSubControllerMock)
.getDefaultDataSubId();
doReturn(SubscriptionManager.INVALID_SUBSCRIPTION_ID).when(mSubControllerMock)
@@ -200,59 +185,8 @@ public class MultiSimSettingControllerTest extends TelephonyTest {
verify(mSubControllerMock).setDefaultDataSubId(1);
verify(mSubControllerMock).setDefaultVoiceSubId(1);
verify(mSubControllerMock).setDefaultSmsSubId(1);
- verifyDismissIntentSent();
- }
-
- @Test
- public void testSubInfoChangeAfterRadioUnavailable() throws Exception {
- mMultiSimSettingControllerUT.notifyAllSubscriptionLoaded();
- mMultiSimSettingControllerUT.notifyCarrierConfigChanged(0, 1);
- mMultiSimSettingControllerUT.notifyCarrierConfigChanged(1, 2);
- processAllMessages();
-
- // Ensure all subscription loaded only updates state once
- clearInvocations(mSubControllerMock);
- mMultiSimSettingControllerUT.notifyAllSubscriptionLoaded();
- processAllMessages();
- verify(mSubControllerMock, never()).setDefaultDataSubId(anyInt());
- verify(mSubControllerMock, never()).setDefaultVoiceSubId(anyInt());
- verify(mSubControllerMock, never()).setDefaultSmsSubId(anyInt());
-
- // Notify radio unavailable.
- replaceInstance(BaseCommands.class, "mState", mSimulatedCommands,
- TelephonyManager.RADIO_POWER_UNAVAILABLE);
- mMultiSimSettingControllerUT.obtainMessage(
- MultiSimSettingController.EVENT_RADIO_STATE_CHANGED).sendToTarget();
-
- // Mark all subs as inactive.
- doReturn(false).when(mSubControllerMock).isActiveSubId(1);
- doReturn(false).when(mSubControllerMock).isActiveSubId(2);
- doReturn(SubscriptionManager.INVALID_PHONE_INDEX).when(mSubControllerMock).getPhoneId(1);
- doReturn(SubscriptionManager.INVALID_PHONE_INDEX).when(mSubControllerMock).getPhoneId(2);
- doReturn(SubscriptionManager.INVALID_SUBSCRIPTION_ID).when(mPhoneMock1).getSubId();
- doReturn(SubscriptionManager.INVALID_SUBSCRIPTION_ID).when(mPhoneMock2).getSubId();
- List<SubscriptionInfo> infoList = new ArrayList<>();
- doReturn(infoList).when(mSubControllerMock).getActiveSubscriptionInfoList(anyString(),
- nullable(String.class));
- doReturn(new int[]{}).when(mSubControllerMock).getActiveSubIdList(anyBoolean());
- clearInvocations(mSubControllerMock);
-
- // The below sub info change should be ignored.
- mMultiSimSettingControllerUT.notifySubscriptionInfoChanged();
- processAllMessages();
- verify(mSubControllerMock, never()).setDefaultDataSubId(anyInt());
- verify(mSubControllerMock, never()).setDefaultVoiceSubId(anyInt());
- verify(mSubControllerMock, never()).setDefaultSmsSubId(anyInt());
-
- // Send all sub ready notification
- mMultiSimSettingControllerUT.notifyAllSubscriptionLoaded();
- processAllMessages();
-
- // Everything should be set to invalid since nothing is active.
- verify(mSubControllerMock).setDefaultDataSubId(SubscriptionManager.INVALID_SUBSCRIPTION_ID);
- verify(mSubControllerMock)
- .setDefaultVoiceSubId(SubscriptionManager.INVALID_SUBSCRIPTION_ID);
- verify(mSubControllerMock).setDefaultSmsSubId(SubscriptionManager.INVALID_SUBSCRIPTION_ID);
+ // No dialog or notification is needed. So no intent is expected to be broadcast.
+ verify(mContext, never()).sendBroadcast(any());
}
@Test
@@ -277,8 +211,6 @@ public class MultiSimSettingControllerTest extends TelephonyTest {
mMultiSimSettingControllerUT.notifyAllSubscriptionLoaded();
mMultiSimSettingControllerUT.notifyCarrierConfigChanged(0, 1);
processAllMessages();
- verifyDismissIntentSent();
- clearInvocations(mContext);
// Sub 1 should be default sub silently.
// Sub 1 switches to sub 2 in the same slot.
@@ -300,7 +232,8 @@ public class MultiSimSettingControllerTest extends TelephonyTest {
verify(mSubControllerMock).setDefaultDataSubId(2);
verify(mSubControllerMock).setDefaultVoiceSubId(2);
verify(mSubControllerMock).setDefaultSmsSubId(2);
- verifyDismissIntentSent();
+ // No dialog or notification is needed. So no intent is expected to be broadcast.
+ verify(mContext, never()).sendBroadcast(any());
}
@Test
@@ -323,11 +256,11 @@ public class MultiSimSettingControllerTest extends TelephonyTest {
verify(mSubControllerMock).setDefaultDataSubId(1);
verify(mSubControllerMock).setDefaultVoiceSubId(1);
verify(mSubControllerMock).setDefaultSmsSubId(1);
- verifyDismissIntentSent();
+ // No dialog or notification is needed. So no intent is expected to be broadcast.
+ verify(mContext, never()).sendBroadcast(any());
// Mark sub 2 as active in phone[1].
clearInvocations(mSubControllerMock);
- clearInvocations(mContext);
doReturn(true).when(mSubControllerMock).isActiveSubId(2);
doReturn(1).when(mSubControllerMock).getPhoneId(2);
doReturn(2).when(mPhoneMock2).getSubId();
@@ -380,8 +313,7 @@ public class MultiSimSettingControllerTest extends TelephonyTest {
mMultiSimSettingControllerUT.notifyCarrierConfigChanged(0, 1);
mMultiSimSettingControllerUT.notifyCarrierConfigChanged(1, 2);
processAllMessages();
- verify(mDataEnabledSettingsMock2).setDataEnabled(
- TelephonyManager.DATA_ENABLED_REASON_USER, false);
+ verify(mDataEnabledSettingsMock2).setUserDataEnabled(false);
// Enable on non-default sub should trigger setDefaultDataSubId.
mMultiSimSettingControllerUT.notifyUserDataEnabled(2, true);
@@ -392,8 +324,7 @@ public class MultiSimSettingControllerTest extends TelephonyTest {
doReturn(2).when(mSubControllerMock).getDefaultDataSubId();
mMultiSimSettingControllerUT.notifyDefaultDataSubChanged();
processAllMessages();
- verify(mDataEnabledSettingsMock1).setDataEnabled(
- TelephonyManager.DATA_ENABLED_REASON_USER, false);
+ verify(mDataEnabledSettingsMock1).setUserDataEnabled(false);
doReturn(1).when(mSubControllerMock).getDefaultDataSubId();
doReturn(1).when(mSubControllerMock).getDefaultSmsSubId();
@@ -424,41 +355,6 @@ public class MultiSimSettingControllerTest extends TelephonyTest {
@Test
@SmallTest
- public void testSimpleDsdsFirstBoot() {
- // at first boot default is not set
- doReturn(-1).when(mSubControllerMock).getDefaultDataSubId();
-
- doReturn(true).when(mPhoneMock1).isUserDataEnabled();
- doReturn(true).when(mPhoneMock2).isUserDataEnabled();
- // After initialization, sub 2 should have mobile data off.
- mMultiSimSettingControllerUT.notifyAllSubscriptionLoaded();
- mMultiSimSettingControllerUT.notifyCarrierConfigChanged(0, 1);
- mMultiSimSettingControllerUT.notifyCarrierConfigChanged(1, 2);
- processAllMessages();
- verify(mDataEnabledSettingsMock1).setDataEnabled(
- TelephonyManager.DATA_ENABLED_REASON_USER, false);
- verify(mDataEnabledSettingsMock2).setDataEnabled(
- TelephonyManager.DATA_ENABLED_REASON_USER, false);
-
- // as a result of the above calls, update new values to be returned
- doReturn(false).when(mPhoneMock1).isUserDataEnabled();
- doReturn(false).when(mPhoneMock2).isUserDataEnabled();
-
- Intent intent = captureBroadcastIntent();
- assertEquals(ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED, intent.getAction());
- assertEquals(EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DATA,
- intent.getIntExtra(EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE, -1));
-
- // Setting default data should not trigger any more setDataEnabled().
- doReturn(2).when(mSubControllerMock).getDefaultDataSubId();
- mMultiSimSettingControllerUT.notifyDefaultDataSubChanged();
- processAllMessages();
- verify(mDataEnabledSettingsMock1, times(1)).setDataEnabled(anyInt(), anyBoolean());
- verify(mDataEnabledSettingsMock2, times(1)).setDataEnabled(anyInt(), anyBoolean());
- }
-
- @Test
- @SmallTest
public void testDsdsGrouping() {
doReturn(2).when(mSubControllerMock).getDefaultDataSubId();
doReturn(false).when(mPhoneMock1).isUserDataEnabled();
@@ -495,8 +391,7 @@ public class MultiSimSettingControllerTest extends TelephonyTest {
doReturn(1).when(mSubControllerMock).getDefaultDataSubId();
mMultiSimSettingControllerUT.notifyDefaultDataSubChanged();
processAllMessages();
- verify(mDataEnabledSettingsMock2).setDataEnabled(
- TelephonyManager.DATA_ENABLED_REASON_USER, false);
+ verify(mDataEnabledSettingsMock2).setUserDataEnabled(false);
mMultiSimSettingControllerUT.notifyUserDataEnabled(2, false);
processAllMessages();
assertFalse(GlobalSettingsHelper.getBoolean(
@@ -544,9 +439,9 @@ public class MultiSimSettingControllerTest extends TelephonyTest {
mMultiSimSettingControllerUT.notifyCarrierConfigChanged(1, 2);
processAllMessages();
verify(mSubControllerMock).setDefaultDataSubId(2);
- verify(mDataEnabledSettingsMock1, never()).setDataEnabled(
- anyInt(), anyBoolean());
- verifyDismissIntentSent();
+ verify(mDataEnabledSettingsMock1, never()).setUserDataEnabled(anyBoolean());
+ // No user selection needed, no intent should be sent.
+ verify(mContext, never()).sendBroadcast(any());
clearInvocations(mSubControllerMock);
clearInvocations(mDataEnabledSettingsMock1);
@@ -561,17 +456,8 @@ public class MultiSimSettingControllerTest extends TelephonyTest {
mMultiSimSettingControllerUT.notifyUserDataEnabled(2, true);
processAllMessages();
verify(mSubControllerMock, never()).setDefaultDataSubId(anyInt());
- verify(mDataEnabledSettingsMock1, never()).setDataEnabled(
- eq(TelephonyManager.DATA_ENABLED_REASON_USER), anyBoolean());
- verify(mDataEnabledSettingsMock2, never()).setDataEnabled(
- TelephonyManager.DATA_ENABLED_REASON_USER, false);
- }
-
- private void verifyDismissIntentSent() {
- Intent intentSent = captureBroadcastIntent();
- assertEquals(EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DISMISS,
- intentSent.getIntExtra(EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE, -1));
- assertEquals(ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED, intentSent.getAction());
+ verify(mDataEnabledSettingsMock1, never()).setUserDataEnabled(anyBoolean());
+ verify(mDataEnabledSettingsMock2, never()).setUserDataEnabled(anyBoolean());
}
@Test
@@ -592,6 +478,8 @@ public class MultiSimSettingControllerTest extends TelephonyTest {
mMultiSimSettingControllerUT.notifyCarrierConfigChanged(1, 2);
processAllMessages();
verify(mSubControllerMock).setDefaultDataSubId(2);
+ // No user selection needed, no intent should be sent.
+ verify(mContext, never()).sendBroadcast(any());
// Mark sub 2 as data off.
doReturn(false).when(mPhoneMock2).isUserDataEnabled();
@@ -612,47 +500,8 @@ public class MultiSimSettingControllerTest extends TelephonyTest {
mMultiSimSettingControllerUT.notifyUserDataEnabled(2, true);
processAllMessages();
verify(mDataEnabledSettingsMock1).setUserDataEnabled(true, false);
- verifyDismissIntentSent();
- }
-
- @Test
- @SmallTest
- public void testGroupedPrimaryRemoved() throws Exception {
- // Create subscription grouping of subs 1 and 2.
- replaceInstance(SubscriptionInfo.class, "mGroupUUID", mSubInfo1, mGroupUuid1);
- doReturn(mGroupUuid1).when(mSubControllerMock).getGroupUuid(1);
- doReturn(mGroupUuid1).when(mSubControllerMock).getGroupUuid(2);
- doReturn(Arrays.asList(mSubInfo1, mSubInfo2)).when(mSubControllerMock)
- .getSubscriptionsInGroup(any(), anyString(), nullable(String.class));
-
- mMultiSimSettingControllerUT.notifyAllSubscriptionLoaded();
- mMultiSimSettingControllerUT.notifySubscriptionGroupChanged(mGroupUuid1);
- mMultiSimSettingControllerUT.notifyCarrierConfigChanged(0, 1);
- mMultiSimSettingControllerUT.notifyCarrierConfigChanged(1, 2);
- processAllMessages();
-
- // Defaults not touched, sub 1 is already default.
- verify(mSubControllerMock, never()).setDefaultDataSubId(anyInt());
-
- // Take out SIM 1.
- clearInvocations(mSubControllerMock);
- doReturn(false).when(mSubControllerMock).isActiveSubId(1);
- doReturn(SubscriptionManager.INVALID_PHONE_INDEX).when(mSubControllerMock).getPhoneId(1);
- doReturn(SubscriptionManager.INVALID_SUBSCRIPTION_ID).when(mPhoneMock1).getSubId();
- List<SubscriptionInfo> infoList = Arrays.asList(mSubInfo2);
- doReturn(infoList).when(mSubControllerMock).getActiveSubscriptionInfoList(anyString(),
- nullable(String.class));
- doReturn(new int[]{2}).when(mSubControllerMock).getActiveSubIdList(anyBoolean());
- mMultiSimSettingControllerUT.notifySubscriptionInfoChanged();
- mMultiSimSettingControllerUT.notifyCarrierConfigChanged(
- 0, SubscriptionManager.INVALID_SUBSCRIPTION_ID);
- processAllMessages();
-
- // Sub 2 should be made the default sub silently.
- verify(mSubControllerMock).setDefaultDataSubId(2);
- verify(mSubControllerMock).setDefaultVoiceSubId(2);
- verify(mSubControllerMock).setDefaultSmsSubId(2);
- verifyDismissIntentSent();
+ // No user selection needed, no intent should be sent.
+ verify(mContext, never()).sendBroadcast(any());
}
private Intent captureBroadcastIntent() {
@@ -702,16 +551,13 @@ public class MultiSimSettingControllerTest extends TelephonyTest {
// loaded on both subscriptions.
mMultiSimSettingControllerUT.notifyAllSubscriptionLoaded();
processAllMessages();
- verify(mDataEnabledSettingsMock2, never()).setDataEnabled(
- TelephonyManager.DATA_ENABLED_REASON_USER, false);
+ verify(mDataEnabledSettingsMock2, never()).setUserDataEnabled(false);
mMultiSimSettingControllerUT.notifyCarrierConfigChanged(0, 1);
processAllMessages();
- verify(mDataEnabledSettingsMock2, never()).setDataEnabled(
- TelephonyManager.DATA_ENABLED_REASON_USER, false);
+ verify(mDataEnabledSettingsMock2, never()).setUserDataEnabled(false);
mMultiSimSettingControllerUT.notifyCarrierConfigChanged(1, 2);
processAllMessages();
- verify(mDataEnabledSettingsMock2).setDataEnabled(
- TelephonyManager.DATA_ENABLED_REASON_USER, false);
+ verify(mDataEnabledSettingsMock2).setUserDataEnabled(false);
// Switch from sub 2 to sub 3 in phone[1].
clearInvocations(mSubControllerMock);
@@ -793,8 +639,7 @@ public class MultiSimSettingControllerTest extends TelephonyTest {
SubscriptionManager.INVALID_SUBSCRIPTION_ID);
processAllMessages();
// Nothing should happen as carrier config is not ready for sub 2.
- verify(mDataEnabledSettingsMock2, never()).setDataEnabled(
- TelephonyManager.DATA_ENABLED_REASON_USER, false);
+ verify(mDataEnabledSettingsMock2, never()).setUserDataEnabled(false);
// Still notify carrier config without specifying subId2, but this time subController
// and CarrierConfigManager have subId 2 active and ready.
@@ -806,73 +651,6 @@ public class MultiSimSettingControllerTest extends TelephonyTest {
SubscriptionManager.INVALID_SUBSCRIPTION_ID);
processAllMessages();
// This time user data should be disabled on phone1.
- verify(mDataEnabledSettingsMock2).setDataEnabled(
- TelephonyManager.DATA_ENABLED_REASON_USER, false);
- }
-
- @Test
- @SmallTest
- public void testOnPhoneRemoved() {
- try {
- mMultiSimSettingControllerUT.onPhoneRemoved();
- } catch (RuntimeException re) {
- Assert.fail("Exception not expected when calling from the same thread");
- }
- }
-
- @Test
- @SmallTest
- public void testOnPhoneRemoved_DifferentThread() {
- AtomicBoolean result = new AtomicBoolean(false);
- CountDownLatch latch = new CountDownLatch(1);
- HandlerThread handlerThread = new HandlerThread("MultiSimSettingControllerTest") {
- public void onLooperPrepared() {
- try {
- mMultiSimSettingControllerUT.onPhoneRemoved();
- } catch (RuntimeException re) {
- result.set(true); // true to indicate that the test passed
- }
- latch.countDown();
- }
- };
- handlerThread.start();
- try {
- if (!latch.await(5, TimeUnit.SECONDS)) {
- Assert.fail("CountDownLatch did not reach 0");
- } else if (!result.get()) {
- Assert.fail("Exception expected when not calling from the same thread");
- }
- } catch (InterruptedException ie) {
- Assert.fail("InterruptedException during latch.await");
- }
- }
-
- @Test
- @SmallTest
- public void testVoiceDataSmsAutoFallback() throws Exception {
- doReturn(1).when(mSubControllerMock).getDefaultDataSubId();
- mMultiSimSettingControllerUT.notifyAllSubscriptionLoaded();
- mMultiSimSettingControllerUT.notifyCarrierConfigChanged(0,1);
- mMultiSimSettingControllerUT.notifyCarrierConfigChanged(2, 3);
- processAllMessages();
- verify(mSubControllerMock, never()).setDefaultDataSubId(anyInt());
- verify(mSubControllerMock, never()).getActiveSubInfoCountMax();
- doReturn(2).when(mSubControllerMock).getActiveSubInfoCountMax();
- mPhoneMock1.mCi = mMockCi;
- mPhoneMock2.mCi = mMockCi;
- doReturn(TelephonyManager.RADIO_POWER_ON).when(mMockCi).getRadioState();
- doReturn(false).when(mPhoneMock1).isShuttingDown();
- doReturn(false).when(mPhoneMock2).isShuttingDown();
- android.provider.Settings.Global.putInt(InstrumentationRegistry.getTargetContext().
- getContentResolver(), "user_preferred_data_sub", 2);
- Resources resources = mContext.getResources();
- doReturn(true).when(resources).getBoolean(
- com.android.internal.R.bool.config_voice_data_sms_auto_fallback);
- mMultiSimSettingControllerUT.notifyAllSubscriptionLoaded();
- mMultiSimSettingControllerUT.notifyCarrierConfigChanged(0,1);
- mMultiSimSettingControllerUT.notifyCarrierConfigChanged(1, 2);
- processAllMessages();
- verify(mSubControllerMock).getActiveSubInfoCountMax();
- verify(mSubControllerMock).setDefaultDataSubId(anyInt());
+ verify(mDataEnabledSettingsMock2).setUserDataEnabled(false);
}
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/NetworkTypeControllerTest.java b/tests/telephonytests/src/com/android/internal/telephony/NetworkTypeControllerTest.java
index be23df8ba1..eafc486e70 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/NetworkTypeControllerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/NetworkTypeControllerTest.java
@@ -17,9 +17,6 @@
package com.android.internal.telephony;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doReturn;
import android.content.Intent;
@@ -29,17 +26,12 @@ import android.os.Looper;
import android.os.PersistableBundle;
import android.telephony.CarrierConfigManager;
import android.telephony.NetworkRegistrationInfo;
-import android.telephony.PcoData;
-import android.telephony.PhysicalChannelConfig;
-import android.telephony.RadioAccessFamily;
import android.telephony.ServiceState;
import android.telephony.TelephonyDisplayInfo;
import android.telephony.TelephonyManager;
-import android.telephony.data.ApnSetting;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
-import com.android.internal.telephony.dataconnection.DataConnection;
import com.android.internal.telephony.dataconnection.DcController;
import com.android.internal.util.IState;
import com.android.internal.util.StateMachine;
@@ -48,11 +40,8 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.mockito.Mock;
import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.List;
@RunWith(AndroidTestingRunner.class)
@TestableLooper.RunWithLooper
@@ -69,15 +58,9 @@ public class NetworkTypeControllerTest extends TelephonyTest {
private static final int EVENT_RADIO_OFF_OR_UNAVAILABLE = 10;
private static final int EVENT_PREFERRED_NETWORK_MODE_CHANGED = 11;
private static final int EVENT_INITIALIZE = 12;
- private static final int EVENT_PHYSICAL_CHANNEL_CONFIG_CHANGED = 13;
- private static final int EVENT_PCO_DATA_CHANGED = 14;
private NetworkTypeController mNetworkTypeController;
private PersistableBundle mBundle;
- @Mock
- DataConnection mDataConnection;
- @Mock
- ApnSetting mApnSetting;
private IState getCurrentState() throws Exception {
Method method = StateMachine.class.getDeclaredMethod("getCurrentState");
@@ -109,11 +92,8 @@ public class NetworkTypeControllerTest extends TelephonyTest {
broadcastCarrierConfigs();
replaceInstance(Handler.class, "mLooper", mDisplayInfoController, Looper.myLooper());
- doReturn(RadioAccessFamily.getRafFromNetworkType(
- TelephonyManager.NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA)).when(
- mPhone).getCachedAllowedNetworkTypesBitmask();
- doReturn(false).when(mTelephonyManager).isRadioInterfaceCapabilitySupported(
- TelephonyManager.CAPABILITY_PHYSICAL_CHANNEL_CONFIG_1_6_SUPPORTED);
+ doReturn(TelephonyManager.NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA).when(mPhone)
+ .getCachedPreferredNetworkType();
mNetworkTypeController = new NetworkTypeController(mPhone, mDisplayInfoController);
processAllMessages();
}
@@ -127,6 +107,8 @@ public class NetworkTypeControllerTest extends TelephonyTest {
@Test
public void testUpdateOverrideNetworkTypeNrNsa() throws Exception {
+ doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
+
// not NR
doReturn(NetworkRegistrationInfo.NR_STATE_NONE).when(mServiceState).getNrState();
updateOverrideNetworkType();
@@ -155,73 +137,21 @@ public class NetworkTypeControllerTest extends TelephonyTest {
// NR NSA, millimeter wave frequency
doReturn(ServiceState.FREQUENCY_RANGE_MMWAVE).when(mServiceState).getNrFrequencyRange();
updateOverrideNetworkType();
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED,
+ assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA_MMWAVE,
mNetworkTypeController.getOverrideNetworkType());
}
@Test
- public void testUpdateOverrideNetworkTypeNrSa() throws Exception {
- // not NR
+ public void testUpdateOverrideNetworkTypeLte() throws Exception {
doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- doReturn(NetworkRegistrationInfo.NR_STATE_NONE).when(mServiceState).getNrState();
- updateOverrideNetworkType();
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE,
- mNetworkTypeController.getOverrideNetworkType());
-
- // NR SA connected
- mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
- .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_NR)
- .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
- .build();
- doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
- anyInt(), anyInt());
-
- updateOverrideNetworkType();
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE,
- mNetworkTypeController.getOverrideNetworkType());
- }
-
- @Test
- public void testUpdateOverrideNetworkTypeNrSaMmwave() throws Exception {
- // not NR
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- doReturn(NetworkRegistrationInfo.NR_STATE_NONE).when(mServiceState).getNrState();
- updateOverrideNetworkType();
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE,
- mNetworkTypeController.getOverrideNetworkType());
-
- // NR SA connected and millimeter wave frequency
- mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
- .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_NR)
- .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
- .build();
- doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
- anyInt(), anyInt());
- doReturn(ServiceState.FREQUENCY_RANGE_MMWAVE).when(mServiceState).getNrFrequencyRange();
-
- updateOverrideNetworkType();
-
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED,
- mNetworkTypeController.getOverrideNetworkType());
- }
-
- @Test
- public void testUpdateOverrideNetworkTypeLte() throws Exception {
// normal LTE
updateOverrideNetworkType();
assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE,
mNetworkTypeController.getOverrideNetworkType());
- // LTE CA at bandwidth threshold
+ // LTE CA
doReturn(true).when(mServiceState).isUsingCarrierAggregation();
- doReturn(new int[] {20000}).when(mServiceState).getCellBandwidths();
- updateOverrideNetworkType();
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE,
- mNetworkTypeController.getOverrideNetworkType());
-
- // LTE CA above bandwidth threshold
- doReturn(new int[] {20000, 1400}).when(mServiceState).getCellBandwidths();
updateOverrideNetworkType();
assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_LTE_CA,
mNetworkTypeController.getOverrideNetworkType());
@@ -237,22 +167,6 @@ public class NetworkTypeControllerTest extends TelephonyTest {
}
@Test
- public void testUpdateOverrideNetworkType() throws Exception {
- doReturn(NetworkRegistrationInfo.NR_STATE_CONNECTED).when(mServiceState).getNrState();
- doReturn(ServiceState.FREQUENCY_RANGE_LOW).when(mServiceState).getNrFrequencyRange();
- NetworkRegistrationInfo nri = new NetworkRegistrationInfo.Builder()
- .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_HSPAP)
- .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
- .build();
- doReturn(nri).when(mServiceState).getNetworkRegistrationInfo(anyInt(), anyInt());
- updateOverrideNetworkType();
-
- // override shouldn't be NR if not on LTE despite NR_STATE_CONNECTED
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE,
- mNetworkTypeController.getOverrideNetworkType());
- }
-
- @Test
public void testTransitionToCurrentStateLegacy() throws Exception {
assertEquals("DefaultState", getCurrentState().getName());
doReturn(TelephonyManager.NETWORK_TYPE_HSPAP).when(mServiceState).getDataNetworkType();
@@ -286,43 +200,6 @@ public class NetworkTypeControllerTest extends TelephonyTest {
}
@Test
- public void testTransitionToCurrentStateIdleSupportPhysicalChannelConfig1_6() throws Exception {
- doReturn(true).when(mTelephonyManager).isRadioInterfaceCapabilitySupported(
- TelephonyManager.CAPABILITY_PHYSICAL_CHANNEL_CONFIG_1_6_SUPPORTED);
- mNetworkTypeController = new NetworkTypeController(mPhone, mDisplayInfoController);
- processAllMessages();
- assertEquals("DefaultState", getCurrentState().getName());
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- doReturn(NetworkRegistrationInfo.NR_STATE_NOT_RESTRICTED).when(mServiceState).getNrState();
- setPhysicalLinkState(false);
- mNetworkTypeController.sendMessage(EVENT_PHYSICAL_CHANNEL_CONFIG_CHANGED);
- mNetworkTypeController.sendMessage(NetworkTypeController.EVENT_UPDATE);
- processAllMessages();
- assertEquals("not_restricted_rrc_idle", getCurrentState().getName());
- }
-
- @Test
- public void testTransitionToCurrentStateIdle_usingUserDataForRrcDetection() throws Exception {
- mBundle.putBoolean(
- CarrierConfigManager.KEY_LTE_ENDC_USING_USER_DATA_FOR_RRC_DETECTION_BOOL, true);
- doReturn(true).when(mTelephonyManager).isRadioInterfaceCapabilitySupported(
- TelephonyManager.CAPABILITY_PHYSICAL_CHANNEL_CONFIG_1_6_SUPPORTED);
- mNetworkTypeController = new NetworkTypeController(mPhone, mDisplayInfoController);
- broadcastCarrierConfigs();
- processAllMessages();
- assertEquals("DefaultState", getCurrentState().getName());
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- doReturn(NetworkRegistrationInfo.NR_STATE_NOT_RESTRICTED).when(mServiceState).getNrState();
- mNetworkTypeController.sendMessage(EVENT_PHYSICAL_LINK_STATE_CHANGED,
- new AsyncResult(null, DcController.PHYSICAL_LINK_NOT_ACTIVE, null));
- mNetworkTypeController.sendMessage(NetworkTypeController.EVENT_UPDATE);
-
- processAllMessages();
-
- assertEquals("not_restricted_rrc_idle", getCurrentState().getName());
- }
-
- @Test
public void testTransitionToCurrentStateLteConnected() throws Exception {
assertEquals("DefaultState", getCurrentState().getName());
doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
@@ -335,46 +212,6 @@ public class NetworkTypeControllerTest extends TelephonyTest {
}
@Test
- public void testTransitionToCurrentStateLteConnectedSupportPhysicalChannelConfig1_6()
- throws Exception {
- doReturn(true).when(mTelephonyManager).isRadioInterfaceCapabilitySupported(
- TelephonyManager.CAPABILITY_PHYSICAL_CHANNEL_CONFIG_1_6_SUPPORTED);
- mNetworkTypeController = new NetworkTypeController(mPhone, mDisplayInfoController);
- broadcastCarrierConfigs();
- processAllMessages();
- assertEquals("DefaultState", getCurrentState().getName());
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- doReturn(NetworkRegistrationInfo.NR_STATE_NOT_RESTRICTED).when(mServiceState).getNrState();
- setPhysicalLinkState(true);
- mNetworkTypeController.sendMessage(EVENT_PHYSICAL_CHANNEL_CONFIG_CHANGED);
- mNetworkTypeController.sendMessage(NetworkTypeController.EVENT_UPDATE);
- processAllMessages();
- assertEquals("not_restricted_rrc_con", getCurrentState().getName());
- }
-
- @Test
- public void testTransitionToCurrentStateLteConnected_usingUserDataForRrcDetection()
- throws Exception {
- mBundle.putBoolean(
- CarrierConfigManager.KEY_LTE_ENDC_USING_USER_DATA_FOR_RRC_DETECTION_BOOL, true);
- doReturn(true).when(mTelephonyManager).isRadioInterfaceCapabilitySupported(
- TelephonyManager.CAPABILITY_PHYSICAL_CHANNEL_CONFIG_1_6_SUPPORTED);
- mNetworkTypeController = new NetworkTypeController(mPhone, mDisplayInfoController);
- broadcastCarrierConfigs();
- processAllMessages();
- assertEquals("DefaultState", getCurrentState().getName());
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- doReturn(NetworkRegistrationInfo.NR_STATE_NOT_RESTRICTED).when(mServiceState).getNrState();
- mNetworkTypeController.sendMessage(EVENT_PHYSICAL_LINK_STATE_CHANGED,
- new AsyncResult(null, DcController.PHYSICAL_LINK_ACTIVE, null));
- mNetworkTypeController.sendMessage(NetworkTypeController.EVENT_UPDATE);
-
- processAllMessages();
-
- assertEquals("not_restricted_rrc_con", getCurrentState().getName());
- }
-
- @Test
public void testTransitionToCurrentStateNrConnected() throws Exception {
assertEquals("DefaultState", getCurrentState().getName());
doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
@@ -398,138 +235,6 @@ public class NetworkTypeControllerTest extends TelephonyTest {
}
@Test
- public void testTransitionToCurrentStateNrConnectedMmwaveWithAdditionalBandAndNoMmwave()
- throws Exception {
- assertEquals("DefaultState", getCurrentState().getName());
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- doReturn(NetworkRegistrationInfo.NR_STATE_CONNECTED).when(mServiceState).getNrState();
- doReturn(ServiceState.FREQUENCY_RANGE_HIGH).when(mServiceState).getNrFrequencyRange();
- mBundle.putIntArray(CarrierConfigManager.KEY_ADDITIONAL_NR_ADVANCED_BANDS_INT_ARRAY,
- new int[]{41});
- PhysicalChannelConfig physicalChannelConfig = new PhysicalChannelConfig.Builder()
- .setNetworkType(TelephonyManager.NETWORK_TYPE_NR)
- .setBand(41)
- .build();
- List<PhysicalChannelConfig> lastPhysicalChannelConfigList = new ArrayList<>();
- lastPhysicalChannelConfigList.add(physicalChannelConfig);
- doReturn(lastPhysicalChannelConfigList).when(mSST).getPhysicalChannelConfigList();
- broadcastCarrierConfigs();
-
- mNetworkTypeController.sendMessage(NetworkTypeController.EVENT_UPDATE);
- processAllMessages();
- assertEquals("connected_mmwave", getCurrentState().getName());
- }
-
- @Test
- public void testTransitionToCurrentStateNrConnectedWithNoAdditionalBandAndNoMmwave()
- throws Exception {
- assertEquals("DefaultState", getCurrentState().getName());
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- doReturn(NetworkRegistrationInfo.NR_STATE_CONNECTED).when(mServiceState).getNrState();
- doReturn(ServiceState.FREQUENCY_RANGE_HIGH).when(mServiceState).getNrFrequencyRange();
- mBundle.putIntArray(CarrierConfigManager.KEY_ADDITIONAL_NR_ADVANCED_BANDS_INT_ARRAY,
- new int[]{41});
- PhysicalChannelConfig physicalChannelConfig = new PhysicalChannelConfig.Builder()
- .setNetworkType(TelephonyManager.NETWORK_TYPE_NR)
- .setBand(2)
- .build();
- List<PhysicalChannelConfig> lastPhysicalChannelConfigList = new ArrayList<>();
- lastPhysicalChannelConfigList.add(physicalChannelConfig);
- doReturn(lastPhysicalChannelConfigList).when(mSST).getPhysicalChannelConfigList();
- broadcastCarrierConfigs();
-
- mNetworkTypeController.sendMessage(NetworkTypeController.EVENT_UPDATE);
- processAllMessages();
- assertEquals("connected", getCurrentState().getName());
- }
-
- @Test
- public void testTransitionToCurrentStateNrConnectedWithNrAdvancedCapable() throws Exception {
- assertEquals("DefaultState", getCurrentState().getName());
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- doReturn(NetworkRegistrationInfo.NR_STATE_CONNECTED).when(mServiceState).getNrState();
- doReturn(ServiceState.FREQUENCY_RANGE_MMWAVE).when(mServiceState).getNrFrequencyRange();
- mBundle.putInt(CarrierConfigManager.KEY_NR_ADVANCED_CAPABLE_PCO_ID_INT, 0);
- broadcastCarrierConfigs();
-
- mNetworkTypeController.sendMessage(NetworkTypeController.EVENT_UPDATE);
- processAllMessages();
- assertEquals("connected_mmwave", getCurrentState().getName());
- }
-
- @Test
- public void testTransitionToCurrentStateNrConnectedWithPcoAndNoNrAdvancedCapable()
- throws Exception {
- assertEquals("DefaultState", getCurrentState().getName());
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- doReturn(NetworkRegistrationInfo.NR_STATE_CONNECTED).when(mServiceState).getNrState();
- doReturn(ServiceState.FREQUENCY_RANGE_MMWAVE).when(mServiceState).getNrFrequencyRange();
- mBundle.putInt(CarrierConfigManager.KEY_NR_ADVANCED_CAPABLE_PCO_ID_INT, 0xFF03);
- broadcastCarrierConfigs();
- int cid = 1;
- byte[] contents = new byte[]{0};
- doReturn(mDataConnection).when(mDcTracker).getDataConnectionByContextId(cid);
- doReturn(mApnSetting).when(mDataConnection).getApnSetting();
- doReturn(true).when(mApnSetting).canHandleType(ApnSetting.TYPE_DEFAULT);
- mBundle.putInt(CarrierConfigManager.KEY_NR_ADVANCED_CAPABLE_PCO_ID_INT, 0xFF03);
- broadcastCarrierConfigs();
-
-
- mNetworkTypeController.sendMessage(EVENT_PCO_DATA_CHANGED,
- new AsyncResult(null, new PcoData(cid, "", 0xff03, contents), null));
- mNetworkTypeController.sendMessage(NetworkTypeController.EVENT_UPDATE);
- processAllMessages();
- assertEquals("connected", getCurrentState().getName());
- }
-
- @Test
- public void testTransitionToCurrentStateNrConnectedWithWrongPcoAndNoNrAdvancedCapable()
- throws Exception {
- assertEquals("DefaultState", getCurrentState().getName());
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- doReturn(NetworkRegistrationInfo.NR_STATE_CONNECTED).when(mServiceState).getNrState();
- doReturn(ServiceState.FREQUENCY_RANGE_MMWAVE).when(mServiceState).getNrFrequencyRange();
- mBundle.putInt(CarrierConfigManager.KEY_NR_ADVANCED_CAPABLE_PCO_ID_INT, 0xFF03);
- broadcastCarrierConfigs();
- int cid = 1;
- byte[] contents = new byte[]{1};
- doReturn(mDataConnection).when(mDcTracker).getDataConnectionByContextId(cid);
- doReturn(mApnSetting).when(mDataConnection).getApnSetting();
- doReturn(true).when(mApnSetting).canHandleType(ApnSetting.TYPE_DEFAULT);
- mBundle.putInt(CarrierConfigManager.KEY_NR_ADVANCED_CAPABLE_PCO_ID_INT, 0xFF00);
- broadcastCarrierConfigs();
-
-
- mNetworkTypeController.sendMessage(EVENT_PCO_DATA_CHANGED,
- new AsyncResult(null, new PcoData(cid, "", 0xff03, contents), null));
- mNetworkTypeController.sendMessage(NetworkTypeController.EVENT_UPDATE);
- processAllMessages();
- assertEquals("connected", getCurrentState().getName());
- }
-
- @Test
- public void testTransitionToCurrentStateNrConnectedWithNrAdvancedCapableAndPco()
- throws Exception {
- assertEquals("DefaultState", getCurrentState().getName());
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- doReturn(NetworkRegistrationInfo.NR_STATE_CONNECTED).when(mServiceState).getNrState();
- doReturn(ServiceState.FREQUENCY_RANGE_MMWAVE).when(mServiceState).getNrFrequencyRange();
- int cid = 1;
- byte[] contents = new byte[]{1};
- doReturn(mDataConnection).when(mDcTracker).getDataConnectionByContextId(cid);
- doReturn(mApnSetting).when(mDataConnection).getApnSetting();
- doReturn(true).when(mApnSetting).canHandleType(ApnSetting.TYPE_DEFAULT);
- mBundle.putInt(CarrierConfigManager.KEY_NR_ADVANCED_CAPABLE_PCO_ID_INT, 0xFF03);
- broadcastCarrierConfigs();
-
- mNetworkTypeController.sendMessage(EVENT_PCO_DATA_CHANGED,
- new AsyncResult(null, new PcoData(cid, "", 0xff03, contents), null));
- mNetworkTypeController.sendMessage(NetworkTypeController.EVENT_UPDATE);
- processAllMessages();
- assertEquals("connected_mmwave", getCurrentState().getName());
- }
-
- @Test
public void testEventDataRatChanged() throws Exception {
testTransitionToCurrentStateLegacy();
doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
@@ -589,170 +294,12 @@ public class NetworkTypeControllerTest extends TelephonyTest {
}
@Test
- public void testNrPhysicalChannelChange1_6FromNrConnectedMmwaveToLteConnected()
- throws Exception {
- doReturn(true).when(mTelephonyManager).isRadioInterfaceCapabilitySupported(
- TelephonyManager.CAPABILITY_PHYSICAL_CHANNEL_CONFIG_1_6_SUPPORTED);
- mNetworkTypeController = new NetworkTypeController(mPhone, mDisplayInfoController);
- processAllMessages();
- testTransitionToCurrentStateNrConnectedMmwave();
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- doReturn(NetworkRegistrationInfo.NR_STATE_NOT_RESTRICTED).when(mServiceState).getNrState();
- setPhysicalLinkState(true);
- mNetworkTypeController.sendMessage(EVENT_PHYSICAL_CHANNEL_CONFIG_CHANGED);
- mNetworkTypeController.sendMessage(EVENT_NR_FREQUENCY_CHANGED);
- mNetworkTypeController.sendMessage(EVENT_NR_STATE_CHANGED);
-
- processAllMessages();
-
- assertEquals("not_restricted_rrc_con", getCurrentState().getName());
- }
-
-
- @Test
- public void testUsingUserDataForRrcDetection_FromNrConnectedMmwaveToLteConnected()
- throws Exception {
- mBundle.putBoolean(
- CarrierConfigManager.KEY_LTE_ENDC_USING_USER_DATA_FOR_RRC_DETECTION_BOOL, true);
- doReturn(true).when(mTelephonyManager).isRadioInterfaceCapabilitySupported(
- TelephonyManager.CAPABILITY_PHYSICAL_CHANNEL_CONFIG_1_6_SUPPORTED);
- mNetworkTypeController = new NetworkTypeController(mPhone, mDisplayInfoController);
- broadcastCarrierConfigs();
- processAllMessages();
- testTransitionToCurrentStateNrConnectedMmwave();
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- doReturn(NetworkRegistrationInfo.NR_STATE_NOT_RESTRICTED).when(mServiceState).getNrState();
- mNetworkTypeController.sendMessage(EVENT_PHYSICAL_LINK_STATE_CHANGED,
- new AsyncResult(null, DcController.PHYSICAL_LINK_ACTIVE, null));
- mNetworkTypeController.sendMessage(EVENT_NR_FREQUENCY_CHANGED);
- mNetworkTypeController.sendMessage(EVENT_NR_STATE_CHANGED);
-
- processAllMessages();
-
- assertEquals("not_restricted_rrc_con", getCurrentState().getName());
- }
-
- @Test
- public void testEventPhysicalChannelChangeFromLteToLteCaInLegacyState() throws Exception {
- testTransitionToCurrentStateLegacy();
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- updateOverrideNetworkType();
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE,
- mNetworkTypeController.getOverrideNetworkType());
-
- doReturn(true).when(mServiceState).isUsingCarrierAggregation();
- doReturn(new int[] {30000}).when(mServiceState).getCellBandwidths();
- mNetworkTypeController.sendMessage(EVENT_PHYSICAL_CHANNEL_CONFIG_CHANGED);
- processAllMessages();
-
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_LTE_CA,
- mNetworkTypeController.getOverrideNetworkType());
- }
-
- @Test
- public void testEventPhysicalChannelChangeFromLteToLteCaInLteConnectedState() throws Exception {
- // Remove RRC idle/RRC connected from 5G override
- mBundle = mContextFixture.getCarrierConfigBundle();
- mBundle.putString(CarrierConfigManager.KEY_5G_ICON_CONFIGURATION_STRING,
- "connected_mmwave:5G_Plus,connected:5G");
- broadcastCarrierConfigs();
-
- // Transition to LTE connected state
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- doReturn(NetworkRegistrationInfo.NR_STATE_NOT_RESTRICTED).when(mServiceState).getNrState();
- mNetworkTypeController.sendMessage(EVENT_PHYSICAL_LINK_STATE_CHANGED,
- new AsyncResult(null, DcController.PHYSICAL_LINK_ACTIVE, null));
- mNetworkTypeController.sendMessage(NetworkTypeController.EVENT_UPDATE);
- processAllMessages();
- assertEquals("not_restricted_rrc_con", getCurrentState().getName());
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE,
- mNetworkTypeController.getOverrideNetworkType());
-
- // LTE -> LTE+
- doReturn(true).when(mServiceState).isUsingCarrierAggregation();
- doReturn(new int[] {30000}).when(mServiceState).getCellBandwidths();
- mNetworkTypeController.sendMessage(EVENT_PHYSICAL_CHANNEL_CONFIG_CHANGED);
- processAllMessages();
-
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_LTE_CA,
- mNetworkTypeController.getOverrideNetworkType());
- }
-
- @Test
- public void testEventPhysicalChannelChangeFromLteToLteCaInIdleState() throws Exception {
- // Remove RRC idle/RRC connected from 5G override
- mBundle = mContextFixture.getCarrierConfigBundle();
- mBundle.putString(CarrierConfigManager.KEY_5G_ICON_CONFIGURATION_STRING,
- "connected_mmwave:5G_Plus,connected:5G");
- broadcastCarrierConfigs();
-
- // Transition to idle state
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- doReturn(NetworkRegistrationInfo.NR_STATE_NOT_RESTRICTED).when(mServiceState).getNrState();
- mNetworkTypeController.sendMessage(EVENT_PHYSICAL_LINK_STATE_CHANGED,
- new AsyncResult(null, DcController.PHYSICAL_LINK_NOT_ACTIVE, null));
- mNetworkTypeController.sendMessage(NetworkTypeController.EVENT_UPDATE);
- processAllMessages();
- assertEquals("not_restricted_rrc_idle", getCurrentState().getName());
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE,
- mNetworkTypeController.getOverrideNetworkType());
-
- // LTE -> LTE+
- doReturn(true).when(mServiceState).isUsingCarrierAggregation();
- doReturn(new int[] {30000}).when(mServiceState).getCellBandwidths();
- mNetworkTypeController.sendMessage(EVENT_PHYSICAL_CHANNEL_CONFIG_CHANGED);
- processAllMessages();
-
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_LTE_CA,
- mNetworkTypeController.getOverrideNetworkType());
- }
-
- @Test
public void testEventPhysicalLinkStateChanged() throws Exception {
testTransitionToCurrentStateLteConnected();
doReturn(ServiceState.FREQUENCY_RANGE_MMWAVE).when(mServiceState).getNrFrequencyRange();
mNetworkTypeController.sendMessage(EVENT_PHYSICAL_LINK_STATE_CHANGED,
new AsyncResult(null, DcController.PHYSICAL_LINK_NOT_ACTIVE, null));
-
processAllMessages();
-
- assertEquals("not_restricted_rrc_idle", getCurrentState().getName());
- }
-
- @Test
- public void testEventPhysicalLinkStateChangedSupportPhysicalChannelConfig1_6()
- throws Exception {
- doReturn(true).when(mTelephonyManager).isRadioInterfaceCapabilitySupported(
- TelephonyManager.CAPABILITY_PHYSICAL_CHANNEL_CONFIG_1_6_SUPPORTED);
- mNetworkTypeController = new NetworkTypeController(mPhone, mDisplayInfoController);
- processAllMessages();
- testTransitionToCurrentStateLteConnectedSupportPhysicalChannelConfig1_6();
- doReturn(ServiceState.FREQUENCY_RANGE_MMWAVE).when(mServiceState).getNrFrequencyRange();
- setPhysicalLinkState(false);
- mNetworkTypeController.sendMessage(EVENT_PHYSICAL_CHANNEL_CONFIG_CHANGED);
-
- processAllMessages();
-
- assertEquals("not_restricted_rrc_idle", getCurrentState().getName());
- }
-
- @Test
- public void testEventPhysicalLinkStateChanged_UsingUserDataForRrcDetection()
- throws Exception {
- mBundle.putBoolean(
- CarrierConfigManager.KEY_LTE_ENDC_USING_USER_DATA_FOR_RRC_DETECTION_BOOL, true);
- doReturn(true).when(mTelephonyManager).isRadioInterfaceCapabilitySupported(
- TelephonyManager.CAPABILITY_PHYSICAL_CHANNEL_CONFIG_1_6_SUPPORTED);
- mNetworkTypeController = new NetworkTypeController(mPhone, mDisplayInfoController);
- broadcastCarrierConfigs();
- processAllMessages();
- testTransitionToCurrentStateLteConnected_usingUserDataForRrcDetection();
- doReturn(ServiceState.FREQUENCY_RANGE_MMWAVE).when(mServiceState).getNrFrequencyRange();
- mNetworkTypeController.sendMessage(EVENT_PHYSICAL_LINK_STATE_CHANGED,
- new AsyncResult(null, DcController.PHYSICAL_LINK_NOT_ACTIVE, null));
-
- processAllMessages();
-
assertEquals("not_restricted_rrc_idle", getCurrentState().getName());
}
@@ -791,9 +338,8 @@ public class NetworkTypeControllerTest extends TelephonyTest {
mNetworkTypeController.getOverrideNetworkType());
// remove NR from preferred network types
- doReturn(RadioAccessFamily.getRafFromNetworkType(
- TelephonyManager.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA)).when(
- mPhone).getCachedAllowedNetworkTypesBitmask();
+ doReturn(TelephonyManager.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA).when(mPhone)
+ .getCachedPreferredNetworkType();
mNetworkTypeController.sendMessage(EVENT_PREFERRED_NETWORK_MODE_CHANGED);
processAllMessages();
@@ -803,7 +349,6 @@ public class NetworkTypeControllerTest extends TelephonyTest {
@Test
public void testPrimaryTimerExpire() throws Exception {
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
doReturn(NetworkRegistrationInfo.NR_STATE_CONNECTED).when(mServiceState).getNrState();
mBundle.putString(CarrierConfigManager.KEY_5G_ICON_DISPLAY_GRACE_PERIOD_STRING,
"connected_mmwave,any,10;connected,any,10;not_restricted_rrc_con,any,10");
@@ -821,7 +366,6 @@ public class NetworkTypeControllerTest extends TelephonyTest {
assertEquals("legacy", getCurrentState().getName());
assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA,
mNetworkTypeController.getOverrideNetworkType());
- assertTrue(mNetworkTypeController.is5GHysteresisActive());
// timer expires
moveTimeForward(10 * 1000);
@@ -830,12 +374,10 @@ public class NetworkTypeControllerTest extends TelephonyTest {
assertEquals("legacy", getCurrentState().getName());
assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE,
mNetworkTypeController.getOverrideNetworkType());
- assertFalse(mNetworkTypeController.is5GHysteresisActive());
}
@Test
public void testPrimaryTimerReset() throws Exception {
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
doReturn(NetworkRegistrationInfo.NR_STATE_CONNECTED).when(mServiceState).getNrState();
mBundle.putString(CarrierConfigManager.KEY_5G_ICON_DISPLAY_GRACE_PERIOD_STRING,
"connected_mmwave,any,10;connected,any,10;not_restricted_rrc_con,any,10");
@@ -853,7 +395,6 @@ public class NetworkTypeControllerTest extends TelephonyTest {
assertEquals("legacy", getCurrentState().getName());
assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA,
mNetworkTypeController.getOverrideNetworkType());
- assertTrue(mNetworkTypeController.is5GHysteresisActive());
// reconnect to NR in the middle of the timer
doReturn(NetworkRegistrationInfo.NR_STATE_CONNECTED).when(mServiceState).getNrState();
@@ -867,12 +408,10 @@ public class NetworkTypeControllerTest extends TelephonyTest {
assertEquals("connected", getCurrentState().getName());
assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA,
mNetworkTypeController.getOverrideNetworkType());
- assertFalse(mNetworkTypeController.is5GHysteresisActive());
}
@Test
public void testPrimaryTimerExpireMmwave() throws Exception {
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
doReturn(NetworkRegistrationInfo.NR_STATE_CONNECTED).when(mServiceState).getNrState();
doReturn(ServiceState.FREQUENCY_RANGE_MMWAVE).when(mServiceState).getNrFrequencyRange();
mBundle.putString(CarrierConfigManager.KEY_5G_ICON_DISPLAY_GRACE_PERIOD_STRING,
@@ -880,7 +419,7 @@ public class NetworkTypeControllerTest extends TelephonyTest {
broadcastCarrierConfigs();
assertEquals("connected_mmwave", getCurrentState().getName());
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED,
+ assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA_MMWAVE,
mNetworkTypeController.getOverrideNetworkType());
// should trigger 10 second timer
@@ -888,10 +427,10 @@ public class NetworkTypeControllerTest extends TelephonyTest {
mNetworkTypeController.sendMessage(EVENT_NR_FREQUENCY_CHANGED);
processAllMessages();
+
assertEquals("connected", getCurrentState().getName());
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED,
+ assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA_MMWAVE,
mNetworkTypeController.getOverrideNetworkType());
- assertTrue(mNetworkTypeController.is5GHysteresisActive());
// timer expires
moveTimeForward(10 * 1000);
@@ -900,12 +439,10 @@ public class NetworkTypeControllerTest extends TelephonyTest {
assertEquals("connected", getCurrentState().getName());
assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA,
mNetworkTypeController.getOverrideNetworkType());
- assertFalse(mNetworkTypeController.is5GHysteresisActive());
}
@Test
public void testPrimaryTimerResetMmwave() throws Exception {
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
doReturn(NetworkRegistrationInfo.NR_STATE_CONNECTED).when(mServiceState).getNrState();
doReturn(ServiceState.FREQUENCY_RANGE_MMWAVE).when(mServiceState).getNrFrequencyRange();
mBundle.putString(CarrierConfigManager.KEY_5G_ICON_DISPLAY_GRACE_PERIOD_STRING,
@@ -913,7 +450,7 @@ public class NetworkTypeControllerTest extends TelephonyTest {
broadcastCarrierConfigs();
assertEquals("connected_mmwave", getCurrentState().getName());
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED,
+ assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA_MMWAVE,
mNetworkTypeController.getOverrideNetworkType());
// trigger 10 second timer after disconnecting from NR
@@ -922,9 +459,8 @@ public class NetworkTypeControllerTest extends TelephonyTest {
processAllMessages();
assertEquals("connected", getCurrentState().getName());
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED,
+ assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA_MMWAVE,
mNetworkTypeController.getOverrideNetworkType());
- assertTrue(mNetworkTypeController.is5GHysteresisActive());
// reconnect to NR in the middle of the timer
doReturn(ServiceState.FREQUENCY_RANGE_MMWAVE).when(mServiceState).getNrFrequencyRange();
@@ -936,14 +472,12 @@ public class NetworkTypeControllerTest extends TelephonyTest {
// timer should not have gone off
assertEquals("connected_mmwave", getCurrentState().getName());
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED,
+ assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA_MMWAVE,
mNetworkTypeController.getOverrideNetworkType());
- assertFalse(mNetworkTypeController.is5GHysteresisActive());
}
@Test
public void testSecondaryTimerExpire() throws Exception {
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
doReturn(NetworkRegistrationInfo.NR_STATE_CONNECTED).when(mServiceState).getNrState();
mBundle.putString(CarrierConfigManager.KEY_5G_ICON_DISPLAY_GRACE_PERIOD_STRING,
"connected_mmwave,any,10;connected,any,10;not_restricted_rrc_con,any,10");
@@ -963,7 +497,6 @@ public class NetworkTypeControllerTest extends TelephonyTest {
assertEquals("legacy", getCurrentState().getName());
assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA,
mNetworkTypeController.getOverrideNetworkType());
- assertTrue(mNetworkTypeController.is5GHysteresisActive());
// primary timer expires
moveTimeForward(10 * 1000);
@@ -973,7 +506,6 @@ public class NetworkTypeControllerTest extends TelephonyTest {
assertEquals("legacy", getCurrentState().getName());
assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA,
mNetworkTypeController.getOverrideNetworkType());
- assertTrue(mNetworkTypeController.is5GHysteresisActive());
// secondary timer expires
moveTimeForward(30 * 1000);
@@ -982,12 +514,10 @@ public class NetworkTypeControllerTest extends TelephonyTest {
assertEquals("legacy", getCurrentState().getName());
assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE,
mNetworkTypeController.getOverrideNetworkType());
- assertFalse(mNetworkTypeController.is5GHysteresisActive());
}
@Test
public void testSecondaryTimerReset() throws Exception {
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
doReturn(NetworkRegistrationInfo.NR_STATE_CONNECTED).when(mServiceState).getNrState();
mBundle.putString(CarrierConfigManager.KEY_5G_ICON_DISPLAY_GRACE_PERIOD_STRING,
"connected_mmwave,any,10;connected,any,10;not_restricted_rrc_con,any,10");
@@ -1007,7 +537,6 @@ public class NetworkTypeControllerTest extends TelephonyTest {
assertEquals("legacy", getCurrentState().getName());
assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA,
mNetworkTypeController.getOverrideNetworkType());
- assertTrue(mNetworkTypeController.is5GHysteresisActive());
// primary timer expires
moveTimeForward(10 * 1000);
@@ -1017,7 +546,6 @@ public class NetworkTypeControllerTest extends TelephonyTest {
assertEquals("legacy", getCurrentState().getName());
assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA,
mNetworkTypeController.getOverrideNetworkType());
- assertTrue(mNetworkTypeController.is5GHysteresisActive());
// reconnect to NR in the middle of the timer
doReturn(NetworkRegistrationInfo.NR_STATE_CONNECTED).when(mServiceState).getNrState();
@@ -1031,12 +559,10 @@ public class NetworkTypeControllerTest extends TelephonyTest {
assertEquals("connected", getCurrentState().getName());
assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA,
mNetworkTypeController.getOverrideNetworkType());
- assertFalse(mNetworkTypeController.is5GHysteresisActive());
}
@Test
public void testSecondaryTimerExpireMmwave() throws Exception {
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
doReturn(NetworkRegistrationInfo.NR_STATE_CONNECTED).when(mServiceState).getNrState();
doReturn(ServiceState.FREQUENCY_RANGE_MMWAVE).when(mServiceState).getNrFrequencyRange();
mBundle.putString(CarrierConfigManager.KEY_5G_ICON_DISPLAY_GRACE_PERIOD_STRING,
@@ -1046,7 +572,7 @@ public class NetworkTypeControllerTest extends TelephonyTest {
broadcastCarrierConfigs();
assertEquals("connected_mmwave", getCurrentState().getName());
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED,
+ assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA_MMWAVE,
mNetworkTypeController.getOverrideNetworkType());
// should trigger 10 second primary timer
@@ -1055,9 +581,8 @@ public class NetworkTypeControllerTest extends TelephonyTest {
processAllMessages();
assertEquals("connected", getCurrentState().getName());
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED,
+ assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA_MMWAVE,
mNetworkTypeController.getOverrideNetworkType());
- assertTrue(mNetworkTypeController.is5GHysteresisActive());
// primary timer expires
moveTimeForward(10 * 1000);
@@ -1065,9 +590,8 @@ public class NetworkTypeControllerTest extends TelephonyTest {
// should trigger 30 second secondary timer
assertEquals("connected", getCurrentState().getName());
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED,
+ assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA_MMWAVE,
mNetworkTypeController.getOverrideNetworkType());
- assertTrue(mNetworkTypeController.is5GHysteresisActive());
// secondary timer expires
moveTimeForward(30 * 1000);
@@ -1076,12 +600,10 @@ public class NetworkTypeControllerTest extends TelephonyTest {
assertEquals("connected", getCurrentState().getName());
assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA,
mNetworkTypeController.getOverrideNetworkType());
- assertFalse(mNetworkTypeController.is5GHysteresisActive());
}
@Test
public void testSecondaryTimerResetMmwave() throws Exception {
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
doReturn(NetworkRegistrationInfo.NR_STATE_CONNECTED).when(mServiceState).getNrState();
doReturn(ServiceState.FREQUENCY_RANGE_MMWAVE).when(mServiceState).getNrFrequencyRange();
mBundle.putString(CarrierConfigManager.KEY_5G_ICON_DISPLAY_GRACE_PERIOD_STRING,
@@ -1091,7 +613,7 @@ public class NetworkTypeControllerTest extends TelephonyTest {
broadcastCarrierConfigs();
assertEquals("connected_mmwave", getCurrentState().getName());
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED,
+ assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA_MMWAVE,
mNetworkTypeController.getOverrideNetworkType());
// should trigger 10 second primary timer
@@ -1100,9 +622,8 @@ public class NetworkTypeControllerTest extends TelephonyTest {
processAllMessages();
assertEquals("connected", getCurrentState().getName());
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED,
+ assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA_MMWAVE,
mNetworkTypeController.getOverrideNetworkType());
- assertTrue(mNetworkTypeController.is5GHysteresisActive());
// primary timer expires
moveTimeForward(10 * 1000);
@@ -1110,9 +631,8 @@ public class NetworkTypeControllerTest extends TelephonyTest {
// should trigger 30 second secondary timer
assertEquals("connected", getCurrentState().getName());
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED,
+ assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA_MMWAVE,
mNetworkTypeController.getOverrideNetworkType());
- assertTrue(mNetworkTypeController.is5GHysteresisActive());
// reconnect to NR in the middle of the timer
doReturn(ServiceState.FREQUENCY_RANGE_MMWAVE).when(mServiceState).getNrFrequencyRange();
@@ -1124,66 +644,7 @@ public class NetworkTypeControllerTest extends TelephonyTest {
// timer should not have gone off
assertEquals("connected_mmwave", getCurrentState().getName());
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED,
- mNetworkTypeController.getOverrideNetworkType());
- assertFalse(mNetworkTypeController.is5GHysteresisActive());
- }
-
- @Test
- public void testNrTimerResetIn3g() throws Exception {
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- doReturn(NetworkRegistrationInfo.NR_STATE_CONNECTED).when(mServiceState).getNrState();
- doReturn(ServiceState.FREQUENCY_RANGE_MMWAVE).when(mServiceState).getNrFrequencyRange();
- mBundle.putString(CarrierConfigManager.KEY_5G_ICON_DISPLAY_GRACE_PERIOD_STRING,
- "connected_mmwave,any,10;connected,any,10;not_restricted_rrc_con,any,10");
- mBundle.putString(CarrierConfigManager.KEY_5G_ICON_DISPLAY_SECONDARY_GRACE_PERIOD_STRING,
- "connected_mmwave,any,30");
- broadcastCarrierConfigs();
-
- assertEquals("connected_mmwave", getCurrentState().getName());
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED,
+ assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA_MMWAVE,
mNetworkTypeController.getOverrideNetworkType());
-
- // should trigger 10 second primary timer
- doReturn(ServiceState.FREQUENCY_RANGE_LOW).when(mServiceState).getNrFrequencyRange();
- mNetworkTypeController.sendMessage(EVENT_NR_FREQUENCY_CHANGED);
- processAllMessages();
-
- assertEquals("connected", getCurrentState().getName());
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED,
- mNetworkTypeController.getOverrideNetworkType());
- assertTrue(mNetworkTypeController.is5GHysteresisActive());
-
- // rat is UMTS, should stop timer
- NetworkRegistrationInfo nri = new NetworkRegistrationInfo.Builder()
- .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_UMTS)
- .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
- .build();
- doReturn(nri).when(mServiceState).getNetworkRegistrationInfo(anyInt(), anyInt());
- doReturn(NetworkRegistrationInfo.NR_STATE_NONE).when(mServiceState).getNrState();
- mNetworkTypeController.sendMessage(EVENT_DATA_RAT_CHANGED);
- processAllMessages();
-
- assertEquals("legacy", getCurrentState().getName());
- assertEquals(TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE,
- mNetworkTypeController.getOverrideNetworkType());
- assertFalse(mNetworkTypeController.is5GHysteresisActive());
- }
-
- private void setPhysicalLinkState(Boolean state) {
- List<PhysicalChannelConfig> lastPhysicalChannelConfigList = new ArrayList<>();
- // If PhysicalChannelConfigList is empty, PhysicalLinkState is DcController
- // .PHYSICAL_LINK_NOT_ACTIVE
- // If PhysicalChannelConfigList is not empty, PhysicalLinkState is DcController
- // .PHYSICAL_LINK_ACTIVE
-
- if (state) {
- PhysicalChannelConfig physicalChannelConfig = new PhysicalChannelConfig.Builder()
- .setNetworkType(TelephonyManager.NETWORK_TYPE_NR)
- .setBand(41)
- .build();
- lastPhysicalChannelConfigList.add(physicalChannelConfig);
- }
- doReturn(lastPhysicalChannelConfigList).when(mSST).getPhysicalChannelConfigList();
}
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/PhoneCapabilityTest.java b/tests/telephonytests/src/com/android/internal/telephony/PhoneCapabilityTest.java
index 24106251b7..a504dc14df 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/PhoneCapabilityTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/PhoneCapabilityTest.java
@@ -16,7 +16,6 @@
package com.android.internal.telephony;
-import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
@@ -36,25 +35,23 @@ public class PhoneCapabilityTest {
public void basicTests() throws Exception {
int maxActiveVoiceCalls = 1;
int maxActiveData = 2;
+ int max5G = 3;
ModemInfo modemInfo = new ModemInfo(1, 2, true, false);
List<ModemInfo> logicalModemList = new ArrayList<>();
logicalModemList.add(modemInfo);
- int[] deviceNrCapabilities = new int[]{PhoneCapability.DEVICE_NR_CAPABILITY_SA};
- PhoneCapability capability = new PhoneCapability(maxActiveVoiceCalls, maxActiveData,
- logicalModemList, false, deviceNrCapabilities);
+ PhoneCapability capability = new PhoneCapability(maxActiveVoiceCalls, maxActiveData, max5G,
+ logicalModemList, false);
- assertEquals(maxActiveVoiceCalls, capability.getMaxActiveVoiceSubscriptions());
- assertEquals(maxActiveData, capability.getMaxActiveDataSubscriptions());
- assertEquals(1, capability.getLogicalModemList().size());
- assertEquals(modemInfo, capability.getLogicalModemList().get(0));
- assertArrayEquals(deviceNrCapabilities, capability.getDeviceNrCapabilities());
-
- PhoneCapability toCompare = new PhoneCapability(maxActiveVoiceCalls + 1, maxActiveData - 1,
- logicalModemList, false, deviceNrCapabilities);
- assertEquals(capability,
- new PhoneCapability(maxActiveVoiceCalls, maxActiveData, logicalModemList,
- false, deviceNrCapabilities));
+ assertEquals(maxActiveVoiceCalls, capability.maxActiveVoiceCalls);
+ assertEquals(maxActiveData, capability.maxActiveData);
+ assertEquals(max5G, capability.max5G);
+ assertEquals(1, capability.logicalModemList.size());
+ assertEquals(modemInfo, capability.logicalModemList.get(0));
+ PhoneCapability toCompare = new PhoneCapability(
+ maxActiveVoiceCalls + 1, maxActiveData - 1, max5G, logicalModemList, false);
+ assertEquals(capability, new PhoneCapability(
+ maxActiveVoiceCalls, maxActiveData, max5G, logicalModemList, false));
assertNotEquals(capability, toCompare);
}
@@ -63,24 +60,24 @@ public class PhoneCapabilityTest {
public void parcelReadWrite() throws Exception {
int maxActiveVoiceCalls = 1;
int maxActiveData = 2;
+ int max5G = 3;
ModemInfo modemInfo = new ModemInfo(1, 2, true, false);
List<ModemInfo> logicalModemList = new ArrayList<>();
logicalModemList.add(modemInfo);
- int[] deviceNrCapabilities = new int[]{};
- PhoneCapability capability = new PhoneCapability(maxActiveVoiceCalls, maxActiveData,
- logicalModemList, false, deviceNrCapabilities);
+ PhoneCapability capability = new PhoneCapability(maxActiveVoiceCalls, maxActiveData, max5G,
+ logicalModemList, false);
Parcel parcel = Parcel.obtain();
capability.writeToParcel(parcel, 0);
parcel.setDataPosition(0);
PhoneCapability toCompare = PhoneCapability.CREATOR.createFromParcel(parcel);
- assertEquals(maxActiveVoiceCalls, toCompare.getMaxActiveVoiceSubscriptions());
- assertEquals(maxActiveData, toCompare.getMaxActiveDataSubscriptions());
- assertEquals(1, toCompare.getLogicalModemList().size());
- assertEquals(modemInfo, toCompare.getLogicalModemList().get(0));
- assertArrayEquals(deviceNrCapabilities, toCompare.getDeviceNrCapabilities());
+ assertEquals(maxActiveVoiceCalls, toCompare.maxActiveVoiceCalls);
+ assertEquals(maxActiveData, toCompare.maxActiveData);
+ assertEquals(max5G, toCompare.max5G);
+ assertEquals(1, toCompare.logicalModemList.size());
+ assertEquals(modemInfo, toCompare.logicalModemList.get(0));
assertEquals(capability, toCompare);
}
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/PhoneConfigurationManagerTest.java b/tests/telephonytests/src/com/android/internal/telephony/PhoneConfigurationManagerTest.java
index a702aace4c..07edd34ad1 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/PhoneConfigurationManagerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/PhoneConfigurationManagerTest.java
@@ -21,14 +21,12 @@ import static android.telephony.TelephonyManager.EXTRA_ACTIVE_SIM_SUPPORTED_COUN
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import android.content.Intent;
@@ -53,11 +51,7 @@ public class PhoneConfigurationManagerTest extends TelephonyTest {
@Mock
Handler mHandler;
@Mock
- CommandsInterface mMockCi0;
- @Mock
- CommandsInterface mMockCi1;
- @Mock
- private Phone mPhone1; // mPhone as phone 0 is already defined in TelephonyTest.
+ CommandsInterface mMockCi;
@Mock
PhoneConfigurationManager.MockableInterface mMi;
@@ -67,9 +61,8 @@ public class PhoneConfigurationManagerTest extends TelephonyTest {
@Before
public void setUp() throws Exception {
super.setUp(getClass().getSimpleName());
- mPhone.mCi = mMockCi0;
- mCT.mCi = mMockCi0;
- mPhone1.mCi = mMockCi1;
+ mPhone.mCi = mMockCi;
+ mCT.mCi = mMockCi;
}
@After
@@ -112,7 +105,7 @@ public class PhoneConfigurationManagerTest extends TelephonyTest {
Message message = new Message();
mPcm.enablePhone(mPhone, false, message);
- verify(mMockCi0).enableModem(eq(false), eq(message));
+ verify(mMockCi).enableModem(eq(false), eq(message));
}
@Test
@@ -147,8 +140,6 @@ public class PhoneConfigurationManagerTest extends TelephonyTest {
@SmallTest
public void testSwitchMultiSimConfig_dsdsCapable_noRebootRequired() throws Exception {
init(1);
- verify(mMockCi0, times(1)).registerForAvailable(any(), anyInt(), any());
-
// Register for multi SIM config change.
mPcm.registerForMultiSimConfigChange(mHandler, EVENT_MULTI_SIM_CONFIG_CHANGED, null);
verify(mHandler, never()).sendMessageAtTime(any(), anyLong());
@@ -160,13 +151,9 @@ public class PhoneConfigurationManagerTest extends TelephonyTest {
// Send static capability back to indicate DSDS is supported.
clearInvocations(mMockRadioConfig);
testGetDsdsCapability();
- // testGetDsdsCapability leads to another call to registerForAvailable()
- verify(mMockCi0, times(2)).registerForAvailable(any(), anyInt(), any());
// Try to switch to DSDS.
setRebootRequiredForConfigSwitch(false);
- mPhones = new Phone[]{mPhone, mPhone1};
- replaceInstance(PhoneFactory.class, "sPhones", null, mPhones);
mPcm.switchMultiSimConfig(2);
ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
verify(mMockRadioConfig).setModemsConfig(eq(2), captor.capture());
@@ -195,66 +182,7 @@ public class PhoneConfigurationManagerTest extends TelephonyTest {
assertEquals(2, intent.getIntExtra(
EXTRA_ACTIVE_SIM_SUPPORTED_COUNT, 0));
- // Verify registerForAvailable() and onSlotActiveStatusChange() are called for the second
- // phone, and not for the first phone (registerForAvailable() was already called twice
- // earlier so verify that the count is still at 2)
- verify(mMockCi0, times(2)).registerForAvailable(any(), anyInt(), any());
- verify(mMockCi0, never()).onSlotActiveStatusChange(anyBoolean());
- verify(mMockCi1, times(1)).registerForAvailable(any(), anyInt(), any());
- verify(mMockCi1, times(1)).onSlotActiveStatusChange(anyBoolean());
- }
-
- @Test
- @SmallTest
- public void testSwitchMultiSimConfig_multiSimToSingleSim() throws Exception {
- mPhones = new Phone[]{mPhone, mPhone1};
- replaceInstance(PhoneFactory.class, "sPhones", null, mPhones);
- init(2);
- verify(mMockCi0, times(1)).registerForAvailable(any(), anyInt(), any());
- verify(mMockCi1, times(1)).registerForAvailable(any(), anyInt(), any());
-
- // Register for multi SIM config change.
- mPcm.registerForMultiSimConfigChange(mHandler, EVENT_MULTI_SIM_CONFIG_CHANGED, null);
- verify(mHandler, never()).sendMessageAtTime(any(), anyLong());
-
- // Switch to single sim.
- setRebootRequiredForConfigSwitch(false);
- mPcm.switchMultiSimConfig(1);
- ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
- verify(mMockRadioConfig).setModemsConfig(eq(1), captor.capture());
-
- // Send message back to indicate switch success.
- Message message = captor.getValue();
- AsyncResult.forMessage(message, null, null);
- message.sendToTarget();
- processAllMessages();
-
- // Verify set system property being called.
- verify(mMi).setMultiSimProperties(1);
- verify(mMi).notifyPhoneFactoryOnMultiSimConfigChanged(any(), eq(1));
-
- // Capture and verify registration notification.
- verify(mHandler).sendMessageAtTime(captor.capture(), anyLong());
- message = captor.getValue();
- assertEquals(EVENT_MULTI_SIM_CONFIG_CHANGED, message.what);
- assertEquals(1, ((AsyncResult) message.obj).result);
-
- // Capture and verify broadcast.
- ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
- verify(mContext).sendBroadcast(intentCaptor.capture());
- Intent intent = intentCaptor.getValue();
- assertEquals(ACTION_MULTI_SIM_CONFIG_CHANGED, intent.getAction());
- assertEquals(1, intent.getIntExtra(
- EXTRA_ACTIVE_SIM_SUPPORTED_COUNT, 0));
-
- // Verify clearSubInfoRecord() and onSlotActiveStatusChange() are called for second phone,
- // and not for the first one
- verify(mSubscriptionController).clearSubInfoRecord(1);
- verify(mMockCi1).onSlotActiveStatusChange(anyBoolean());
- verify(mSubscriptionController, never()).clearSubInfoRecord(0);
- verify(mMockCi0, never()).onSlotActiveStatusChange(anyBoolean());
-
- // Verify onPhoneRemoved() gets called on MultiSimSettingController phone
- verify(mMultiSimSettingController).onPhoneRemoved();
+ // Verify RIL notification.
+ verify(mMockCi).onSlotActiveStatusChange(true);
}
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/PhoneStateListenerTest.java b/tests/telephonytests/src/com/android/internal/telephony/PhoneStateListenerTest.java
index 4747598530..8c55442922 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/PhoneStateListenerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/PhoneStateListenerTest.java
@@ -22,7 +22,6 @@ import static org.mockito.Mockito.verify;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
-import android.telephony.SubscriptionManager;
import android.telephony.emergency.EmergencyNumber;
import android.test.suitebuilder.annotation.SmallTest;
import android.testing.AndroidTestingRunner;
@@ -62,8 +61,7 @@ public class PhoneStateListenerTest extends TelephonyTest {
mUserMobileDataState = true;
}
- public void onOutgoingEmergencyCall(EmergencyNumber emergencyNumber,
- int subscriptionId) {
+ public void onOutgoingEmergencyCall(EmergencyNumber emergencyNumber) {
logd("OutgoingCallEmergencyNumber Changed");
mCalledEmergencyNumber = emergencyNumber;
}
@@ -127,7 +125,7 @@ public class PhoneStateListenerTest extends TelephonyTest {
EmergencyNumber.EMERGENCY_CALL_ROUTING_NORMAL);
((IPhoneStateListener) field.get(mPhoneStateListenerUT)).onOutgoingEmergencyCall(
- emergencyNumber, SubscriptionManager.INVALID_SUBSCRIPTION_ID);
+ emergencyNumber);
processAllMessages();
assertTrue(mCalledEmergencyNumber.equals(emergencyNumber));
@@ -150,7 +148,7 @@ public class PhoneStateListenerTest extends TelephonyTest {
EmergencyNumber.EMERGENCY_CALL_ROUTING_NORMAL);
((IPhoneStateListener) field.get(mPhoneStateListenerUT)).onOutgoingEmergencySms(
- emergencyNumber, SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
+ emergencyNumber);
processAllMessages();
assertTrue(mTextedEmergencyNumber.equals(emergencyNumber));
diff --git a/tests/telephonytests/src/com/android/internal/telephony/PhoneSubInfoControllerTest.java b/tests/telephonytests/src/com/android/internal/telephony/PhoneSubInfoControllerTest.java
index 05256b8d67..6480f65438 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/PhoneSubInfoControllerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/PhoneSubInfoControllerTest.java
@@ -16,6 +16,8 @@
package com.android.internal.telephony;
import static android.Manifest.permission.READ_PHONE_STATE;
+import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
+import static android.Manifest.permission.READ_SMS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@@ -29,8 +31,6 @@ import static org.mockito.Mockito.eq;
import android.app.AppOpsManager;
import android.app.PropertyInvalidatedCache;
import android.content.Context;
-import android.content.pm.PackageManager;
-import android.os.Binder;
import android.os.Build;
import android.test.suitebuilder.annotation.SmallTest;
@@ -45,7 +45,6 @@ public class PhoneSubInfoControllerTest extends TelephonyTest {
private PhoneSubInfoController mPhoneSubInfoControllerUT;
private AppOpsManager mAppOsMgr;
- private PackageManager mPm;
@Mock
GsmCdmaPhone mSecondPhone;
@@ -71,7 +70,6 @@ public class PhoneSubInfoControllerTest extends TelephonyTest {
doReturn(mContext).when(mSecondPhone).getContext();
mAppOsMgr = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
- mPm = mContext.getPackageManager();
replaceInstance(PhoneFactory.class, "sPhones", null, new Phone[]{mPhone, mSecondPhone});
mPhoneSubInfoControllerUT = new PhoneSubInfoController(mContext);
@@ -84,9 +82,6 @@ public class PhoneSubInfoControllerTest extends TelephonyTest {
doReturn(AppOpsManager.MODE_ERRORED).when(mAppOsMgr).noteOpNoThrow(
eq(AppOpsManager.OPSTR_READ_DEVICE_IDENTIFIERS), anyInt(), eq(TAG), eq(FEATURE_ID),
nullable(String.class));
-
- // Bypass calling package check.
- doReturn(Binder.getCallingUid()).when(mPm).getPackageUid(eq(TAG), anyInt());
}
@After
@@ -594,11 +589,16 @@ public class PhoneSubInfoControllerTest extends TelephonyTest {
/* case 1: no READ_PRIVILEGED_PHONE_STATE & READ_PHONE_STATE &
READ_SMS and no OP_WRITE_SMS & OP_READ_SMS from appOsMgr */
- // All permission checks are handled by the LegacyPermissionManager, so this test only
- // requires three case; all permissions / appops denied, READ_PHONE_STATE permission
- // granted without the appop, and one or more of the permissions / appops granted.
mContextFixture.removeCallingOrSelfPermission(ContextFixture.PERMISSION_ENABLE_ALL);
- setPhoneNumberAccess(PackageManager.PERMISSION_DENIED);
+ doReturn(AppOpsManager.MODE_ERRORED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_READ_SMS), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
+ doReturn(AppOpsManager.MODE_ERRORED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_WRITE_SMS), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
+ doReturn(AppOpsManager.MODE_ERRORED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_READ_PHONE_STATE), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
try {
mPhoneSubInfoControllerUT.getLine1NumberForSubscriber(0, TAG, FEATURE_ID);
Assert.fail("expected Security Exception Thrown");
@@ -613,13 +613,61 @@ public class PhoneSubInfoControllerTest extends TelephonyTest {
assertTrue(ex instanceof SecurityException);
}
- /* case 2: only enable READ_PHONE_STATE permission */
- setPhoneNumberAccess(AppOpsManager.MODE_IGNORED);
+ /* case 2: only enable WRITE_SMS permission */
+ doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_WRITE_SMS), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
+ assertEquals("+18051234567",
+ mPhoneSubInfoControllerUT.getLine1NumberForSubscriber(0, TAG, FEATURE_ID));
+ assertEquals("+18052345678",
+ mPhoneSubInfoControllerUT.getLine1NumberForSubscriber(1, TAG, FEATURE_ID));
+
+ /* case 3: only enable READ_PRIVILEGED_PHONE_STATE */
+ doReturn(AppOpsManager.MODE_ERRORED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_WRITE_SMS), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
+ mContextFixture.addCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE);
+ assertEquals("+18051234567",
+ mPhoneSubInfoControllerUT.getLine1NumberForSubscriber(0, TAG, FEATURE_ID));
+ assertEquals("+18052345678",
+ mPhoneSubInfoControllerUT.getLine1NumberForSubscriber(1, TAG, FEATURE_ID));
+
+ /* case 4: only enable READ_PHONE_STATE permission */
+ mContextFixture.removeCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE);
+ mContextFixture.addCallingOrSelfPermission(READ_PHONE_STATE);
assertNull(mPhoneSubInfoControllerUT.getLine1NumberForSubscriber(0, TAG, FEATURE_ID));
assertNull(mPhoneSubInfoControllerUT.getLine1NumberForSubscriber(1, TAG, FEATURE_ID));
- /* case 3: enable READ_SMS and OP_READ_SMS */
- setPhoneNumberAccess(PackageManager.PERMISSION_GRANTED);
+ /* case 5: enable appOsMgr READ_PHONE_PERMISSION & READ_PHONE_STATE */
+ doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_READ_PHONE_STATE), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
+ assertEquals("+18051234567",
+ mPhoneSubInfoControllerUT.getLine1NumberForSubscriber(0, TAG, FEATURE_ID));
+ assertEquals("+18052345678",
+ mPhoneSubInfoControllerUT.getLine1NumberForSubscriber(1, TAG, FEATURE_ID));
+
+ /* case 6: only enable READ_SMS; without the appop should throw SecurityException */
+ doReturn(AppOpsManager.MODE_ERRORED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_READ_PHONE_STATE), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
+ mContextFixture.removeCallingOrSelfPermission(READ_PHONE_STATE);
+ mContextFixture.addCallingOrSelfPermission(READ_SMS);
+ try {
+ mPhoneSubInfoControllerUT.getLine1NumberForSubscriber(0, TAG, FEATURE_ID);
+ Assert.fail("expected SecurityException thrown");
+ } catch (SecurityException expected) {
+ }
+ try {
+ mPhoneSubInfoControllerUT.getLine1NumberForSubscriber(1, TAG, FEATURE_ID);
+ Assert.fail("expected SecurityException thrown");
+ } catch (SecurityException expected) {
+ }
+
+ /* case 7: enable READ_SMS and OP_READ_SMS */
+ doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_READ_SMS), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
assertEquals("+18051234567",
mPhoneSubInfoControllerUT.getLine1NumberForSubscriber(0, TAG, FEATURE_ID));
assertEquals("+18052345678",
@@ -636,7 +684,15 @@ public class PhoneSubInfoControllerTest extends TelephonyTest {
/* case 1: no READ_PRIVILEGED_PHONE_STATE & READ_PHONE_STATE &
READ_SMS and no OP_WRITE_SMS & OP_READ_SMS from appOsMgr */
mContextFixture.removeCallingOrSelfPermission(ContextFixture.PERMISSION_ENABLE_ALL);
- setPhoneNumberAccess(PackageManager.PERMISSION_DENIED);
+ doReturn(AppOpsManager.MODE_ERRORED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_READ_SMS), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
+ doReturn(AppOpsManager.MODE_ERRORED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_WRITE_SMS), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
+ doReturn(AppOpsManager.MODE_ERRORED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_READ_PHONE_STATE), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
try {
mPhoneSubInfoControllerUT.getLine1NumberForSubscriber(0, TAG, FEATURE_ID);
Assert.fail("expected Security Exception Thrown");
@@ -651,8 +707,32 @@ public class PhoneSubInfoControllerTest extends TelephonyTest {
assertTrue(ex instanceof SecurityException);
}
- /* case 2: enable READ_SMS and OP_READ_SMS */
- setPhoneNumberAccess(PackageManager.PERMISSION_GRANTED);
+ /* case 2: enable READ_PHONE_STATE permission */
+ doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_READ_PHONE_STATE), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
+ try {
+ mPhoneSubInfoControllerUT.getLine1NumberForSubscriber(0, TAG, FEATURE_ID);
+ Assert.fail("expected Security Exception Thrown");
+ } catch (Exception ex) {
+ assertTrue(ex instanceof SecurityException);
+ }
+
+ try {
+ mPhoneSubInfoControllerUT.getLine1NumberForSubscriber(1, TAG, FEATURE_ID);
+ Assert.fail("expected Security Exception Thrown");
+ } catch (Exception ex) {
+ assertTrue(ex instanceof SecurityException);
+ }
+
+ /* case 3: enable READ_SMS and OP_READ_SMS */
+ doReturn(AppOpsManager.MODE_ERRORED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_READ_PHONE_STATE), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
+ mContextFixture.addCallingOrSelfPermission(READ_SMS);
+ doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_READ_SMS), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
assertEquals("+18051234567",
mPhoneSubInfoControllerUT.getLine1NumberForSubscriber(0, TAG, FEATURE_ID));
assertEquals("+18052345678",
@@ -737,10 +817,16 @@ public class PhoneSubInfoControllerTest extends TelephonyTest {
doReturn("+18052345678").when(mSecondPhone).getMsisdn();
/* case 1: no READ_PRIVILEGED_PHONE_STATE & READ_PHONE_STATE from appOsMgr */
- // The LegacyPermissionManager handles these checks, so set its return code to indicate
- // none of these have been granted.
mContextFixture.removeCallingOrSelfPermission(ContextFixture.PERMISSION_ENABLE_ALL);
- setPhoneNumberAccess(PackageManager.PERMISSION_DENIED);
+ doReturn(AppOpsManager.MODE_ERRORED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_READ_SMS), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
+ doReturn(AppOpsManager.MODE_ERRORED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_WRITE_SMS), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
+ doReturn(AppOpsManager.MODE_ERRORED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_READ_PHONE_STATE), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
try {
mPhoneSubInfoControllerUT.getMsisdnForSubscriber(0, TAG, FEATURE_ID);
Assert.fail("expected Security Exception Thrown");
@@ -756,14 +842,14 @@ public class PhoneSubInfoControllerTest extends TelephonyTest {
}
/* case 2: only enable READ_PHONE_STATE permission */
- // The LegacyPermissionManager will return AppOpsManager.MODE_IGNORED if the target SDK
- // version < R and the READ_PHONE_STATE permission has been granted without the appop.
- setPhoneNumberAccess(AppOpsManager.MODE_IGNORED);
+ mContextFixture.addCallingOrSelfPermission(READ_PHONE_STATE);
assertNull(mPhoneSubInfoControllerUT.getMsisdnForSubscriber(0, TAG, FEATURE_ID));
assertNull(mPhoneSubInfoControllerUT.getMsisdnForSubscriber(1, TAG, FEATURE_ID));
/* case 3: enable appOsMgr READ_PHONE_PERMISSION & READ_PHONE_STATE */
- setPhoneNumberAccess(PackageManager.PERMISSION_GRANTED);
+ doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_READ_PHONE_STATE), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
assertEquals("+18051234567",
mPhoneSubInfoControllerUT.getMsisdnForSubscriber(0, TAG, FEATURE_ID));
assertEquals("+18052345678",
@@ -779,12 +865,16 @@ public class PhoneSubInfoControllerTest extends TelephonyTest {
/* case 1: no READ_PRIVILEGED_PHONE_STATE & READ_PHONE_STATE &
READ_SMS and no OP_WRITE_SMS & OP_READ_SMS from appOsMgr */
- // Since the LegacyPermissionManager is performing this check the service will perform
- // the READ_PHONE_STATE checks based on target SDK version; for apps targeting R+ it
- // will not check the READ_PHONE_STATE permission and appop and will only return
- // permission granted / denied.
mContextFixture.removeCallingOrSelfPermission(ContextFixture.PERMISSION_ENABLE_ALL);
- setPhoneNumberAccess(PackageManager.PERMISSION_DENIED);
+ doReturn(AppOpsManager.MODE_ERRORED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_READ_SMS), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
+ doReturn(AppOpsManager.MODE_ERRORED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_WRITE_SMS), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
+ doReturn(AppOpsManager.MODE_ERRORED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_READ_PHONE_STATE), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
try {
mPhoneSubInfoControllerUT.getMsisdnForSubscriber(0, TAG, FEATURE_ID);
Assert.fail("expected Security Exception Thrown");
@@ -799,8 +889,32 @@ public class PhoneSubInfoControllerTest extends TelephonyTest {
assertTrue(ex instanceof SecurityException);
}
- /* case 2: enable READ_SMS and OP_READ_SMS */
- setPhoneNumberAccess(PackageManager.PERMISSION_GRANTED);
+ /* case 2: only enable READ_PHONE_STATE permission */
+ doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_READ_PHONE_STATE), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
+ try {
+ mPhoneSubInfoControllerUT.getMsisdnForSubscriber(0, TAG, FEATURE_ID);
+ Assert.fail("expected Security Exception Thrown");
+ } catch (Exception ex) {
+ assertTrue(ex instanceof SecurityException);
+ }
+
+ try {
+ mPhoneSubInfoControllerUT.getMsisdnForSubscriber(1, TAG, FEATURE_ID);
+ Assert.fail("expected Security Exception Thrown");
+ } catch (Exception ex) {
+ assertTrue(ex instanceof SecurityException);
+ }
+
+ /* case 3: enable READ_SMS and OP_READ_SMS */
+ doReturn(AppOpsManager.MODE_ERRORED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_READ_PHONE_STATE), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
+ mContextFixture.addCallingOrSelfPermission(READ_SMS);
+ doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOsMgr).noteOp(
+ eq(AppOpsManager.OPSTR_READ_SMS), anyInt(), eq(TAG), eq(FEATURE_ID),
+ nullable(String.class));
assertEquals("+18051234567",
mPhoneSubInfoControllerUT.getMsisdnForSubscriber(0, TAG, FEATURE_ID));
assertEquals("+18052345678",
diff --git a/tests/telephonytests/src/com/android/internal/telephony/PhoneSwitcherTest.java b/tests/telephonytests/src/com/android/internal/telephony/PhoneSwitcherTest.java
index b0e9a37c4b..e13bacaa97 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/PhoneSwitcherTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/PhoneSwitcherTest.java
@@ -17,19 +17,12 @@
package com.android.internal.telephony;
import static android.telephony.CarrierConfigManager.KEY_DATA_SWITCH_VALIDATION_TIMEOUT_LONG;
-import static android.telephony.TelephonyManager.ACTION_SIM_APPLICATION_STATE_CHANGED;
-import static android.telephony.TelephonyManager.EXTRA_SIM_STATE;
import static android.telephony.TelephonyManager.SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION;
import static android.telephony.TelephonyManager.SET_OPPORTUNISTIC_SUB_SUCCESS;
import static android.telephony.TelephonyManager.SET_OPPORTUNISTIC_SUB_VALIDATION_FAILED;
-import static android.telephony.TelephonyManager.SIM_STATE_LOADED;
-import static android.telephony.ims.stub.ImsRegistrationImplBase.REGISTRATION_TECH_CROSS_SIM;
-import static android.telephony.ims.stub.ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN;
-import static android.telephony.ims.stub.ImsRegistrationImplBase.REGISTRATION_TECH_LTE;
import static com.android.internal.telephony.PhoneSwitcher.ECBM_DEFAULT_DATA_SWITCH_BASE_TIME_MS;
import static com.android.internal.telephony.PhoneSwitcher.EVENT_DATA_ENABLED_CHANGED;
-import static com.android.internal.telephony.PhoneSwitcher.EVENT_IMS_RADIO_TECH_CHANGED;
import static com.android.internal.telephony.PhoneSwitcher.EVENT_MULTI_SIM_CONFIG_CHANGED;
import static com.android.internal.telephony.PhoneSwitcher.EVENT_PRECISE_CALL_STATE_CHANGED;
@@ -62,9 +55,7 @@ import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.telephony.PhoneCapability;
-import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
-import android.telephony.data.ApnSetting;
import android.test.suitebuilder.annotation.SmallTest;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
@@ -85,8 +76,6 @@ import java.util.concurrent.LinkedBlockingQueue;
@TestableLooper.RunWithLooper
public class PhoneSwitcherTest extends TelephonyTest {
private static final int ACTIVE_PHONE_SWITCH = 1;
- private static final int EVENT_RADIO_ON = 108;
- private static final int EVENT_MODEM_COMMAND_DONE = 112;
@Mock
private CommandsInterface mCommandsInterface0;
@@ -95,8 +84,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
@Mock
private Phone mPhone2; // mPhone as phone 1 is already defined in TelephonyTest.
@Mock
- private Phone mImsPhone;
- @Mock
private DataEnabledSettings mDataEnabledSettings2;
@Mock
private Handler mActivePhoneSwitchHandler;
@@ -112,10 +99,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
private ISetOpportunisticDataCallback mSetOpptDataCallback2;
@Mock
CompletableFuture<Boolean> mFuturePhone;
- @Mock
- PhoneSwitcher.ImsRegTechProvider mMockImsRegTechProvider;
- @Mock
- private SubscriptionInfo mSubscriptionInfo;
private PhoneSwitcher mPhoneSwitcher;
private SubscriptionManager.OnSubscriptionsChangedListener mSubChangedListener;
@@ -133,7 +116,7 @@ public class PhoneSwitcherTest extends TelephonyTest {
public void setUp() throws Exception {
super.setUp(getClass().getSimpleName());
- PhoneCapability phoneCapability = new PhoneCapability(1, 1, null, false, new int[0]);
+ PhoneCapability phoneCapability = new PhoneCapability(1, 1, 0, null, false);
doReturn(phoneCapability).when(mPhoneConfigurationManager).getCurrentPhoneCapability();
doReturn(Call.State.ACTIVE).when(mActiveCall).getState();
@@ -183,9 +166,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
mSubChangedListener.onSubscriptionsChanged();
processAllMessages();
- AsyncResult res = new AsyncResult(1, null, null);
- Message.obtain(mPhoneSwitcher, EVENT_MODEM_COMMAND_DONE, res).sendToTarget();
- processAllMessages();
verify(mActivePhoneSwitchHandler, times(1)).sendMessageAtTime(any(), anyLong());
clearInvocations(mActivePhoneSwitchHandler);
assertTrue("data not allowed", mDataAllowed[0]);
@@ -205,8 +185,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
// 1 lose default via default sub change
setDefaultDataSubId(1);
- Message.obtain(mPhoneSwitcher, EVENT_MODEM_COMMAND_DONE, res).sendToTarget();
- processAllMessages();
verify(mActivePhoneSwitchHandler, times(1)).sendMessageAtTime(any(), anyLong());
clearInvocations(mActivePhoneSwitchHandler);
assertFalse("data allowed", mDataAllowed[0]);
@@ -215,8 +193,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
mSubChangedListener.onSubscriptionsChanged();
processAllMessages();
- Message.obtain(mPhoneSwitcher, EVENT_MODEM_COMMAND_DONE, res).sendToTarget();
- processAllMessages();
verify(mActivePhoneSwitchHandler, times(1)).sendMessageAtTime(any(), anyLong());
clearInvocations(mActivePhoneSwitchHandler);
assertFalse("data allowed", mDataAllowed[0]);
@@ -225,8 +201,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
// 2 gain default via default sub change
setDefaultDataSubId(0);
- Message.obtain(mPhoneSwitcher, EVENT_MODEM_COMMAND_DONE, res).sendToTarget();
- processAllMessages();
verify(mActivePhoneSwitchHandler, times(1)).sendMessageAtTime(any(), anyLong());
clearInvocations(mActivePhoneSwitchHandler);
assertFalse("data allowed", mDataAllowed[1]);
@@ -236,8 +210,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
setSlotIndexToSubId(0, 2);
mSubChangedListener.onSubscriptionsChanged();
processAllMessages();
- Message.obtain(mPhoneSwitcher, EVENT_MODEM_COMMAND_DONE, res).sendToTarget();
- processAllMessages();
verify(mActivePhoneSwitchHandler, times(1)).sendMessageAtTime(any(), anyLong());
clearInvocations(mActivePhoneSwitchHandler);
@@ -249,8 +221,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
mSubChangedListener.onSubscriptionsChanged();
processAllMessages();
- Message.obtain(mPhoneSwitcher, EVENT_MODEM_COMMAND_DONE, res).sendToTarget();
- processAllMessages();
verify(mActivePhoneSwitchHandler, times(1)).sendMessageAtTime(any(), anyLong());
clearInvocations(mActivePhoneSwitchHandler);
assertTrue("data not allowed", mDataAllowed[0]);
@@ -259,8 +229,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
// 5 lose default network request
releaseNetworkRequest(internetNetworkRequest);
- Message.obtain(mPhoneSwitcher, EVENT_MODEM_COMMAND_DONE, res).sendToTarget();
- processAllMessages();
verify(mActivePhoneSwitchHandler, times(1)).sendMessageAtTime(any(), anyLong());
clearInvocations(mActivePhoneSwitchHandler);
assertFalse("data allowed", mDataAllowed[0]);
@@ -269,8 +237,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
// 6 gain subscription-specific request
NetworkRequest specificInternetRequest = addInternetNetworkRequest(0, 50);
- Message.obtain(mPhoneSwitcher, EVENT_MODEM_COMMAND_DONE, res).sendToTarget();
- processAllMessages();
verify(mActivePhoneSwitchHandler, times(1)).sendMessageAtTime(any(), anyLong());
clearInvocations(mActivePhoneSwitchHandler);
assertTrue("data not allowed", mDataAllowed[0]);
@@ -281,8 +247,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
mSubChangedListener.onSubscriptionsChanged();
processAllMessages();
- Message.obtain(mPhoneSwitcher, EVENT_MODEM_COMMAND_DONE, res).sendToTarget();
- processAllMessages();
verify(mActivePhoneSwitchHandler, times(1)).sendMessageAtTime(any(), anyLong());
clearInvocations(mActivePhoneSwitchHandler);
assertFalse("data allowed", mDataAllowed[0]);
@@ -293,8 +257,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
mSubChangedListener.onSubscriptionsChanged();
processAllMessages();
- Message.obtain(mPhoneSwitcher, EVENT_MODEM_COMMAND_DONE, res).sendToTarget();
- processAllMessages();
verify(mActivePhoneSwitchHandler, times(1)).sendMessageAtTime(any(), anyLong());
clearInvocations(mActivePhoneSwitchHandler);
assertTrue("data not allowed", mDataAllowed[0]);
@@ -303,8 +265,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
// 9 lose subscription-specific request
releaseNetworkRequest(specificInternetRequest);
- Message.obtain(mPhoneSwitcher, EVENT_MODEM_COMMAND_DONE, res).sendToTarget();
- processAllMessages();
verify(mActivePhoneSwitchHandler, times(1)).sendMessageAtTime(any(), anyLong());
clearInvocations(mActivePhoneSwitchHandler);
assertFalse("data allowed", mDataAllowed[0]);
@@ -368,10 +328,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
// now start a higher priority connection on the other sub
addMmsNetworkRequest(1);
- AsyncResult res = new AsyncResult(1, null, null);
- Message.obtain(mPhoneSwitcher, EVENT_MODEM_COMMAND_DONE, res).sendToTarget();
- processAllMessages();
-
// After gain of network request, mActivePhoneSwitchHandler should be notified 2 times.
verify(mActivePhoneSwitchHandler, times(2)).sendMessageAtTime(any(), anyLong());
assertFalse("data allowed", mDataAllowed[0]);
@@ -473,10 +429,8 @@ public class PhoneSwitcherTest extends TelephonyTest {
setDefaultDataSubId(1);
// Phone 0 (sub 1) should be preferred data phone as it has default data sub.
verify(mMockRadioConfig).setPreferredDataModem(eq(0), any());
- AsyncResult res = new AsyncResult(1, null, null);
- Message.obtain(mPhoneSwitcher, EVENT_MODEM_COMMAND_DONE, res).sendToTarget();
- processAllMessages();
verify(mActivePhoneSwitchHandler, times(2)).sendMessageAtTime(any(), anyLong());
+
clearInvocations(mMockRadioConfig);
clearInvocations(mActivePhoneSwitchHandler);
@@ -498,8 +452,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
mPhoneSwitcher.mValidationCallback.onNetworkAvailable(null, 2);
processAllMessages();
verify(mMockRadioConfig).setPreferredDataModem(eq(1), any());
- Message.obtain(mPhoneSwitcher, EVENT_MODEM_COMMAND_DONE, res).sendToTarget();
- processAllMessages();
verify(mActivePhoneSwitchHandler, times(2)).sendMessageAtTime(any(), anyLong());
assertFalse(mPhoneSwitcher.shouldApplyNetworkRequest(internetRequest, 0));
assertFalse(mPhoneSwitcher.shouldApplyNetworkRequest(mmsRequest, 0));
@@ -517,8 +469,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
processAllMessages();
verify(mMockRadioConfig).setPreferredDataModem(eq(0), any());
- Message.obtain(mPhoneSwitcher, EVENT_MODEM_COMMAND_DONE, res).sendToTarget();
- processAllMessages();
verify(mActivePhoneSwitchHandler, times(2)).sendMessageAtTime(any(), anyLong());
assertTrue(mPhoneSwitcher.shouldApplyNetworkRequest(internetRequest, 0));
assertFalse(mPhoneSwitcher.shouldApplyNetworkRequest(mmsRequest, 0));
@@ -528,12 +478,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
// SetDataAllowed should never be triggered.
verify(mCommandsInterface0, never()).setDataAllowed(anyBoolean(), any());
verify(mCommandsInterface1, never()).setDataAllowed(anyBoolean(), any());
-
- // Set preferred data modem should be triggered after radio on or available.
- clearInvocations(mMockRadioConfig);
- Message.obtain(mPhoneSwitcher, EVENT_RADIO_ON, res).sendToTarget();
- processAllMessages();
- verify(mMockRadioConfig).setPreferredDataModem(eq(0), any());
}
@Test
@@ -585,102 +529,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
assertEquals(0, mPhoneSwitcher.getPreferredDataPhoneId());
}
- private void mockImsRegTech(int phoneId, int regTech) {
- doReturn(regTech).when(mMockImsRegTechProvider).get(any(), eq(phoneId));
- mPhoneSwitcher.mImsRegTechProvider = mMockImsRegTechProvider;
- }
-
- @Test
- @SmallTest
- public void testNonDefaultDataPhoneInCall_ImsCallOnLte_shouldSwitchDds() throws Exception {
- initialize();
- setAllPhonesInactive();
-
- // Phone 0 has sub 1, phone 1 has sub 2.
- // Sub 1 is default data sub.
- // Both are active subscriptions are active sub, as they are in both active slots.
- setSlotIndexToSubId(0, 1);
- setSlotIndexToSubId(1, 2);
- setDefaultDataSubId(1);
- processAllMessages();
-
- // Phone 0 should be the default data phoneId.
- assertEquals(0, mPhoneSwitcher.getPreferredDataPhoneId());
-
- // Phone2 has active IMS call on LTE. And data of DEFAULT apn is enabled. This should
- // trigger data switch.
- doReturn(mImsPhone).when(mPhone2).getImsPhone();
- doReturn(true).when(mDataEnabledSettings2).isDataEnabled(ApnSetting.TYPE_DEFAULT);
- mockImsRegTech(1, REGISTRATION_TECH_LTE);
- notifyPhoneAsInCall(mImsPhone);
-
- // Phone 1 should become the default data phone.
- assertEquals(1, mPhoneSwitcher.getPreferredDataPhoneId());
- }
-
- @Test
- @SmallTest
- public void testNonDefaultDataPhoneInCall_ImsCallOnWlan_shouldNotSwitchDds() throws Exception {
- initialize();
- setAllPhonesInactive();
-
- // Phone 0 has sub 1, phone 1 has sub 2.
- // Sub 1 is default data sub.
- // Both are active subscriptions are active sub, as they are in both active slots.
- setSlotIndexToSubId(0, 1);
- setSlotIndexToSubId(1, 2);
- setDefaultDataSubId(1);
- processAllMessages();
-
- // Phone 0 should be the default data phoneId.
- assertEquals(0, mPhoneSwitcher.getPreferredDataPhoneId());
-
- // Phone2 has active call, but data is turned off. So no data switching should happen.
- doReturn(mImsPhone).when(mPhone2).getImsPhone();
- doReturn(true).when(mDataEnabledSettings2).isDataEnabled(ApnSetting.TYPE_DEFAULT);
- mockImsRegTech(1, REGISTRATION_TECH_IWLAN);
- notifyPhoneAsInCall(mImsPhone);
-
- // Phone 0 should remain the default data phone.
- assertEquals(0, mPhoneSwitcher.getPreferredDataPhoneId());
- }
-
- @Test
- @SmallTest
- public void testNonDefaultDataPhoneInCall_ImsCallOnCrossSIM_HandoverToLTE() throws Exception {
- initialize();
- setAllPhonesInactive();
-
- // Phone 0 has sub 1, phone 1 has sub 2.
- // Sub 1 is default data sub.
- // Both are active subscriptions are active sub, as they are in both active slots.
- setSlotIndexToSubId(0, 1);
- setSlotIndexToSubId(1, 2);
- setDefaultDataSubId(1);
- processAllMessages();
-
- // Phone 0 should be the default data phoneId.
- assertEquals(0, mPhoneSwitcher.getPreferredDataPhoneId());
-
- // Phone 1 has active IMS call on CROSS_SIM. And data of DEFAULT apn is enabled. This should
- // not trigger data switch.
- doReturn(mImsPhone).when(mPhone2).getImsPhone();
- doReturn(true).when(mDataEnabledSettings2).isDataEnabled(ApnSetting.TYPE_DEFAULT);
- mockImsRegTech(1, REGISTRATION_TECH_CROSS_SIM);
- notifyPhoneAsInCall(mImsPhone);
-
- // Phone 0 should remain the default data phone.
- assertEquals(0, mPhoneSwitcher.getPreferredDataPhoneId());
-
- // Phone 1 has has handed over the call to LTE. And data of DEFAULT apn is enabled.
- // This should trigger data switch.
- mockImsRegTech(1, REGISTRATION_TECH_LTE);
- notifyImsRegistrationTechChange(mPhone2);
-
- // Phone 1 should become the default data phone.
- assertEquals(1, mPhoneSwitcher.getPreferredDataPhoneId());
- }
-
@Test
@SmallTest
public void testNonDefaultDataPhoneInCall() throws Exception {
@@ -765,7 +613,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
sendPreferredDataSuccessResult(1);
processAllMessages();
verify(mFuturePhone).complete(true);
-
// Make sure the correct broadcast is sent out for the overridden phone ID
verify(mTelephonyRegistryManager).notifyActiveDataSubIdChanged(eq(2));
}
@@ -820,10 +667,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
moveTimeForward(ECBM_DEFAULT_DATA_SWITCH_BASE_TIME_MS + 1000);
processAllMessages();
verify(mMockRadioConfig).setPreferredDataModem(eq(0), any());
- AsyncResult res = new AsyncResult(1, null, null);
- Message.obtain(mPhoneSwitcher, EVENT_MODEM_COMMAND_DONE, res).sendToTarget();
- processAllMessages();
-
// Make sure the correct broadcast is sent out for the phone ID
verify(mTelephonyRegistryManager).notifyActiveDataSubIdChanged(eq(1));
}
@@ -871,9 +714,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
moveTimeForward(1000);
processAllMessages();
verify(mMockRadioConfig).setPreferredDataModem(eq(0), any());
- AsyncResult res = new AsyncResult(1, null, null);
- Message.obtain(mPhoneSwitcher, EVENT_MODEM_COMMAND_DONE, res).sendToTarget();
- processAllMessages();
// Make sure the correct broadcast is sent out for the phone ID
verify(mTelephonyRegistryManager).notifyActiveDataSubIdChanged(eq(1));
}
@@ -902,10 +742,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
moveTimeForward(PhoneSwitcher.DEFAULT_DATA_OVERRIDE_TIMEOUT_MS);
processAllMessages();
verify(mMockRadioConfig).setPreferredDataModem(eq(0), any());
- AsyncResult res = new AsyncResult(1, null, null);
- Message.obtain(mPhoneSwitcher, EVENT_MODEM_COMMAND_DONE, res).sendToTarget();
- processAllMessages();
-
// Make sure the correct broadcast is sent out for the phone ID
verify(mTelephonyRegistryManager).notifyActiveDataSubIdChanged(eq(1));
}
@@ -953,10 +789,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
moveTimeForward(ECBM_DEFAULT_DATA_SWITCH_BASE_TIME_MS + 1000);
processAllMessages();
verify(mMockRadioConfig).setPreferredDataModem(eq(0), any());
- AsyncResult res = new AsyncResult(1, null, null);
- Message.obtain(mPhoneSwitcher, EVENT_MODEM_COMMAND_DONE, res).sendToTarget();
- processAllMessages();
-
// Make sure the correct broadcast is sent out for the phone ID
verify(mTelephonyRegistryManager).notifyActiveDataSubIdChanged(eq(1));
}
@@ -1164,59 +996,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
verify(mMockRadioConfig).setPreferredDataModem(eq(1), any());
}
- @Test
- public void testRetry_DDS_switch_Failure() throws Exception {
- doReturn(true).when(mMockRadioConfig).isSetPreferredDataCommandSupported();
- mActiveModemCount = 2;
- initialize();
- setSlotIndexToSubId(0, 1);
- setDefaultDataSubId(1);
-
- clearInvocations(mMockRadioConfig);
- // for exceptions OP_NOT_ALLOWED_DURING_VOICE_CALL and INVALID_SIM_STATE,
- // modem retry not invoked.
- AsyncResult res1 = new AsyncResult(0, null,
- new CommandException(CommandException.Error.INVALID_SIM_STATE));
- Message.obtain(mPhoneSwitcher, EVENT_MODEM_COMMAND_DONE, res1).sendToTarget();
- processAllMessages();
- moveTimeForward(5000);
- processAllMessages();
- verify(mMockRadioConfig, times(0)).setPreferredDataModem(eq(0), any());
-
- doReturn(0).when(mSubscriptionController).getPhoneId(anyInt());
- AsyncResult res2 = new AsyncResult(0, null,
- new CommandException(CommandException.Error.NETWORK_NOT_READY));
- Message.obtain(mPhoneSwitcher, EVENT_MODEM_COMMAND_DONE, res2).sendToTarget();
- processAllMessages();
- moveTimeForward(5000);
- processAllMessages();
-
- verify(mMockRadioConfig, times(1)).setPreferredDataModem(eq(0), any());
-
- clearInvocations(mMockRadioConfig);
- doReturn(mSubscriptionInfo).when(mSubscriptionController)
- .getActiveSubscriptionInfoForSimSlotIndex(eq(0), any(), any());
- doReturn(true).when(mSubscriptionInfo).areUiccApplicationsEnabled();
- doReturn(mIccCard).when(mPhone).getIccCard();
- doReturn(true).when(mIccCard).isEmptyProfile();
- final Intent intent1 = new Intent(ACTION_SIM_APPLICATION_STATE_CHANGED);
- intent1.putExtra(EXTRA_SIM_STATE, SIM_STATE_LOADED);
- intent1.putExtra(SubscriptionManager.EXTRA_SLOT_INDEX, 0);
- mContext.sendBroadcast(intent1);
- processAllMessages();
-
- verify(mMockRadioConfig, times(0)).setPreferredDataModem(eq(0), any());
-
- doReturn(false).when(mIccCard).isEmptyProfile();
- final Intent intent2 = new Intent(ACTION_SIM_APPLICATION_STATE_CHANGED);
- intent2.putExtra(EXTRA_SIM_STATE, SIM_STATE_LOADED);
- intent2.putExtra(SubscriptionManager.EXTRA_SLOT_INDEX, 0);
- mContext.sendBroadcast(intent2);
- processAllMessages();
-
- verify(mMockRadioConfig, times(1)).setPreferredDataModem(eq(0), any());
- }
-
/* Private utility methods start here */
private void setAllPhonesInactive() {
@@ -1226,9 +1005,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
doReturn(mInactiveCall).when(mPhone2).getForegroundCall();
doReturn(mInactiveCall).when(mPhone2).getBackgroundCall();
doReturn(mInactiveCall).when(mPhone2).getRingingCall();
- doReturn(mInactiveCall).when(mImsPhone).getForegroundCall();
- doReturn(mInactiveCall).when(mImsPhone).getBackgroundCall();
- doReturn(mInactiveCall).when(mImsPhone).getRingingCall();
}
private void notifyPhoneAsInCall(Phone phone) {
@@ -1256,11 +1032,6 @@ public class PhoneSwitcherTest extends TelephonyTest {
processAllMessages();
}
- private void notifyImsRegistrationTechChange(Phone phone) {
- mPhoneSwitcher.sendEmptyMessage(EVENT_IMS_RADIO_TECH_CHANGED);
- processAllMessages();
- }
-
private Message getEcbmRegistration(Phone phone) {
ArgumentCaptor<Handler> handlerCaptor = ArgumentCaptor.forClass(Handler.class);
ArgumentCaptor<Integer> intCaptor = ArgumentCaptor.forClass(Integer.class);
diff --git a/tests/telephonytests/src/com/android/internal/telephony/PhysicalChannelConfigTest.java b/tests/telephonytests/src/com/android/internal/telephony/PhysicalChannelConfigTest.java
index 853162a03b..535f7b28c5 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/PhysicalChannelConfigTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/PhysicalChannelConfigTest.java
@@ -17,176 +17,63 @@ package com.android.internal.telephony;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.fail;
-
import android.os.Parcel;
-import android.telephony.AccessNetworkConstants;
import android.telephony.PhysicalChannelConfig;
import android.telephony.PhysicalChannelConfig.Builder;
import android.telephony.ServiceState;
-import android.telephony.TelephonyManager;
import org.junit.Test;
/** Unit test for {@link android.telephony.PhysicalChannelConfig}. */
public class PhysicalChannelConfigTest {
- private static final int NETWORK_TYPE_NR = TelephonyManager.NETWORK_TYPE_NR;
- private static final int NETWORK_TYPE_LTE = TelephonyManager.NETWORK_TYPE_LTE;
- private static final int NETWORK_TYPE_UMTS = TelephonyManager.NETWORK_TYPE_UMTS;
- private static final int NETWORK_TYPE_GSM = TelephonyManager.NETWORK_TYPE_GSM;
+ private static final int RAT = ServiceState.RIL_RADIO_TECHNOLOGY_LTE;
private static final int CONNECTION_STATUS = PhysicalChannelConfig.CONNECTION_PRIMARY_SERVING;
private static final int CELL_BANDWIDTH = 12345;
private static final int FREQUENCY_RANGE = 1;
private static final int CHANNEL_NUMBER = 1234;
- private static final int CHANNEL_NUMBER_UNKNOWN = PhysicalChannelConfig.CHANNEL_NUMBER_UNKNOWN;
private static final int[] CONTEXT_IDS = new int[] {123, 555, 1, 0};
private static final int PHYSICAL_CELL_ID = 502;
- private static final int BAND = 1;
- public static final int INVALID_FREQUENCY = -1;
-
- private PhysicalChannelConfig mPhysicalChannelConfig;
- private void setUpPhysicalChannelConfig(int networkType, int band, int downlinkChannelNumber,
- int uplinkChannelNumber, int frequencyRange) {
- mPhysicalChannelConfig = new Builder()
+ @Test
+ public void testBuilder() {
+ PhysicalChannelConfig config = new Builder()
+ .setRat(RAT)
.setCellConnectionStatus(CONNECTION_STATUS)
.setCellBandwidthDownlinkKhz(CELL_BANDWIDTH)
- .setCellBandwidthUplinkKhz(CELL_BANDWIDTH)
+ .setFrequencyRange(FREQUENCY_RANGE)
+ .setChannelNumber(CHANNEL_NUMBER)
.setContextIds(CONTEXT_IDS)
.setPhysicalCellId(PHYSICAL_CELL_ID)
- .setNetworkType(networkType)
- .setFrequencyRange(frequencyRange)
- .setDownlinkChannelNumber(downlinkChannelNumber)
- .setUplinkChannelNumber(uplinkChannelNumber)
- .setBand(band)
.build();
- }
-
- @Test
- public void testDownlinkFrequencyForNrArfcn(){
- setUpPhysicalChannelConfig(NETWORK_TYPE_NR, AccessNetworkConstants.NgranBands.BAND_1,
- CHANNEL_NUMBER, CHANNEL_NUMBER, ServiceState.FREQUENCY_RANGE_MID);
-
- // 3GPP TS 38.104 Table 5.4.2.1-1, {@link AccessNetworkUtils#getFrequencyFromNrArfcn}.
- // Formula of NR-ARFCN convert to actual frequency:
- // Actual frequency(kHz) = (RANGE_OFFSET + GLOBAL_KHZ * (ARFCN - ARFCN_OFFSET))
- assertThat(mPhysicalChannelConfig.getDownlinkFrequencyKhz()).isEqualTo(6170);
- }
-
- @Test
- public void testDownlinkandUplinkFrequencyForEarfcn(){
- setUpPhysicalChannelConfig(NETWORK_TYPE_LTE, AccessNetworkConstants.EutranBand.BAND_3,
- CHANNEL_NUMBER, 19500, ServiceState.FREQUENCY_RANGE_MID);
-
- // 3GPP TS 36.101 Table 5.7.3-1, {@link AccessNetworkUtils#getFrequencyFromEarfcn}.
- // Formula of E-UTRA ARFCN convert to actual frequency:
- // Actual frequency(kHz) = (DOWNLINK_LOW + 0.1 * (ARFCN - DOWNLINK_OFFSET)) * FREQUENCY_KHZ
- // Actual frequency(kHz) = (UPLINK_LOW + 0.1 * (ARFCN - UPLINK_OFFSET)) * FREQUENCY_KHZ
- assertThat(mPhysicalChannelConfig.getDownlinkFrequencyKhz()).isEqualTo(1808400);
- assertThat(mPhysicalChannelConfig.getUplinkFrequencyKhz()).isEqualTo(1740000);
- }
-
- @Test
- public void testDownlinkandUplinkFrequencyForUarfcn(){
- setUpPhysicalChannelConfig(NETWORK_TYPE_UMTS, AccessNetworkConstants.UtranBand.BAND_3,
- CHANNEL_NUMBER, 940, ServiceState.FREQUENCY_RANGE_MID);
-
- // 3GPP TS 25.101, {@link AccessNetworkUtils#getFrequencyFromUarfcn}.
- // Formula of UTRA ARFCN convert to actual frequency:
- // For general bands:
- // Downlink actual frequency(kHz) = (DOWNLINK_OFFSET + 0.2 * ARFCN) * FREQUENCY_KHZ
- // Uplink actual frequency(kHz) = (UPLINK_OFFSET + 0.2 * ARFCN) * FREQUENCY_KHZ
- assertThat(mPhysicalChannelConfig.getDownlinkFrequencyKhz()).isEqualTo(1821800);
- assertThat(mPhysicalChannelConfig.getUplinkFrequencyKhz()).isEqualTo(1713000);
- }
-
- @Test
- public void testDownlinkFrequencyForArfcn(){
- setUpPhysicalChannelConfig(NETWORK_TYPE_GSM, AccessNetworkConstants.GeranBand.BAND_450,
- 270, 270, ServiceState.FREQUENCY_RANGE_LOW);
-
- // 3GPP TS 45.005 Table 2-1 Dynamically mapped ARFCN
- // Formula of Geran ARFCN convert to actual frequency:
- // Uplink actual frequency(kHz) =
- // (UPLINK_FREQUENCY_FIRST + 0.2 * (ARFCN - ARFCN_RANGE_FIRST)) * FREQUENCY_KHZ
- // Downlink actual frequency(kHz) = Uplink actual frequency + 10
- assertThat(mPhysicalChannelConfig.getDownlinkFrequencyKhz()).isEqualTo(452810);
- }
-
- @Test
- public void testDownlinkandUplinkFrequencyForEarfcnWithIncorrectRange() {
- setUpPhysicalChannelConfig(NETWORK_TYPE_LTE, AccessNetworkConstants.EutranBand.BAND_3,
- 900, 900, ServiceState.FREQUENCY_RANGE_MID);
-
- assertThat(mPhysicalChannelConfig.getDownlinkFrequencyKhz()).isEqualTo(INVALID_FREQUENCY);
- }
-
- @Test
- public void testFrequencyRangeWithoutBand() {
- try {
- setUpPhysicalChannelConfig(NETWORK_TYPE_UMTS, 0, CHANNEL_NUMBER, CHANNEL_NUMBER,
- ServiceState.FREQUENCY_RANGE_UNKNOWN);
- fail("Frequency range: 0 is invalid.");
- } catch (IllegalArgumentException e) {
- }
- }
-
- @Test
- public void testFrequencyRangeForNrArfcn() {
- setUpPhysicalChannelConfig(NETWORK_TYPE_NR, AccessNetworkConstants.NgranBands.BAND_79,
- 4500, 4500, ServiceState.FREQUENCY_RANGE_HIGH);
-
- assertThat(mPhysicalChannelConfig.getFrequencyRange()).isEqualTo(
- ServiceState.FREQUENCY_RANGE_HIGH);
- }
-
- @Test
- public void testUplinkFrequencyForNrArfcnWithUnknownChannelNumber(){
- setUpPhysicalChannelConfig(NETWORK_TYPE_NR, AccessNetworkConstants.NgranBands.BAND_1,
- CHANNEL_NUMBER, CHANNEL_NUMBER_UNKNOWN, ServiceState.FREQUENCY_RANGE_MID);
-
- assertThat(mPhysicalChannelConfig.getUplinkFrequencyKhz()).isEqualTo(INVALID_FREQUENCY);
- }
- @Test
- public void testUplinkFrequencyForNrArfcn(){
- setUpPhysicalChannelConfig(NETWORK_TYPE_NR, AccessNetworkConstants.NgranBands.BAND_1,
- CHANNEL_NUMBER, CHANNEL_NUMBER, ServiceState.FREQUENCY_RANGE_MID);
-
- // 3GPP TS 38.104 Table 5.4.2.1-1, {@link AccessNetworkUtils#getFrequencyFromNrArfcn}.
- // Formula of NR-ARFCN convert to actual frequency:
- // Actual frequency(kHz) = (RANGE_OFFSET + GLOBAL_KHZ * (ARFCN - ARFCN_OFFSET))
- assertThat(mPhysicalChannelConfig.getUplinkFrequencyKhz()).isEqualTo(6170);
- }
-
- @Test
- public void testBuilder() {
- setUpPhysicalChannelConfig(NETWORK_TYPE_LTE, BAND, CHANNEL_NUMBER, CHANNEL_NUMBER,
- FREQUENCY_RANGE);
-
- assertThat(mPhysicalChannelConfig.getNetworkType()).isEqualTo(NETWORK_TYPE_LTE);
- assertThat(mPhysicalChannelConfig.getConnectionStatus()).isEqualTo(CONNECTION_STATUS);
- assertThat(mPhysicalChannelConfig.getCellBandwidthDownlinkKhz()).isEqualTo(CELL_BANDWIDTH);
- assertThat(mPhysicalChannelConfig.getCellBandwidthUplinkKhz()).isEqualTo(CELL_BANDWIDTH);
- assertThat(mPhysicalChannelConfig.getFrequencyRange()).isEqualTo(FREQUENCY_RANGE);
- assertThat(mPhysicalChannelConfig.getContextIds()).isEqualTo(CONTEXT_IDS);
- assertThat(mPhysicalChannelConfig.getPhysicalCellId()).isEqualTo(PHYSICAL_CELL_ID);
- assertThat(mPhysicalChannelConfig.getDownlinkChannelNumber()).isEqualTo(CHANNEL_NUMBER);
- assertThat(mPhysicalChannelConfig.getUplinkChannelNumber()).isEqualTo(CHANNEL_NUMBER);
+ assertThat(config.getRat()).isEqualTo(RAT);
+ assertThat(config.getConnectionStatus()).isEqualTo(CONNECTION_STATUS);
+ assertThat(config.getCellBandwidthDownlink()).isEqualTo(CELL_BANDWIDTH);
+ assertThat(config.getFrequencyRange()).isEqualTo(FREQUENCY_RANGE);
+ assertThat(config.getChannelNumber()).isEqualTo(CHANNEL_NUMBER);
+ assertThat(config.getContextIds()).isEqualTo(CONTEXT_IDS);
+ assertThat(config.getPhysicalCellId()).isEqualTo(PHYSICAL_CELL_ID);
}
@Test
public void testParcel() {
- setUpPhysicalChannelConfig(NETWORK_TYPE_LTE, BAND, CHANNEL_NUMBER, CHANNEL_NUMBER,
- ServiceState.FREQUENCY_RANGE_MID);
+ PhysicalChannelConfig config = new Builder()
+ .setRat(RAT)
+ .setCellConnectionStatus(CONNECTION_STATUS)
+ .setCellBandwidthDownlinkKhz(CELL_BANDWIDTH)
+ .setFrequencyRange(FREQUENCY_RANGE)
+ .setChannelNumber(CHANNEL_NUMBER)
+ .setContextIds(CONTEXT_IDS)
+ .setPhysicalCellId(PHYSICAL_CELL_ID)
+ .build();
Parcel parcel = Parcel.obtain();
- mPhysicalChannelConfig.writeToParcel(parcel, 0 /* flags */);
+ config.writeToParcel(parcel, 0 /* flags */);
parcel.setDataPosition(0);
PhysicalChannelConfig fromParcel = PhysicalChannelConfig.CREATOR.createFromParcel(parcel);
- assertThat(fromParcel).isEqualTo(mPhysicalChannelConfig);
+ assertThat(fromParcel).isEqualTo(config);
}
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/RILTest.java b/tests/telephonytests/src/com/android/internal/telephony/RILTest.java
index 2b4e484899..792e525b22 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/RILTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/RILTest.java
@@ -19,8 +19,6 @@ package com.android.internal.telephony;
import static com.android.internal.telephony.RILConstants.RIL_REQUEST_ACKNOWLEDGE_INCOMING_GSM_SMS_WITH_PDU;
import static com.android.internal.telephony.RILConstants.RIL_REQUEST_ALLOW_DATA;
import static com.android.internal.telephony.RILConstants.RIL_REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE;
-import static com.android.internal.telephony.RILConstants.RIL_REQUEST_CDMA_SEND_SMS;
-import static com.android.internal.telephony.RILConstants.RIL_REQUEST_CDMA_SEND_SMS_EXPECT_MORE;
import static com.android.internal.telephony.RILConstants.RIL_REQUEST_CHANGE_SIM_PIN;
import static com.android.internal.telephony.RILConstants.RIL_REQUEST_CHANGE_SIM_PIN2;
import static com.android.internal.telephony.RILConstants.RIL_REQUEST_CONFERENCE;
@@ -43,7 +41,6 @@ import static com.android.internal.telephony.RILConstants.RIL_REQUEST_GET_HARDWA
import static com.android.internal.telephony.RILConstants.RIL_REQUEST_GET_IMSI;
import static com.android.internal.telephony.RILConstants.RIL_REQUEST_GET_RADIO_CAPABILITY;
import static com.android.internal.telephony.RILConstants.RIL_REQUEST_GET_SIM_STATUS;
-import static com.android.internal.telephony.RILConstants.RIL_REQUEST_GET_SLICING_CONFIG;
import static com.android.internal.telephony.RILConstants.RIL_REQUEST_GET_SMSC_ADDRESS;
import static com.android.internal.telephony.RILConstants.RIL_REQUEST_GET_UICC_APPLICATIONS_ENABLEMENT;
import static com.android.internal.telephony.RILConstants.RIL_REQUEST_HANGUP;
@@ -113,9 +110,9 @@ import android.hardware.radio.V1_0.NvWriteItem;
import android.hardware.radio.V1_0.RadioError;
import android.hardware.radio.V1_0.RadioResponseInfo;
import android.hardware.radio.V1_0.RadioResponseType;
-import android.hardware.radio.V1_0.RadioTechnologyFamily;
import android.hardware.radio.V1_0.SmsWriteArgs;
-import android.hardware.radio.V1_6.IRadio;
+import android.hardware.radio.V1_5.IRadio;
+import android.hardware.radio.deprecated.V1_0.IOemHook;
import android.net.ConnectivityManager;
import android.net.InetAddresses;
import android.net.LinkAddress;
@@ -148,7 +145,6 @@ import android.telephony.CellSignalStrengthNr;
import android.telephony.CellSignalStrengthTdscdma;
import android.telephony.CellSignalStrengthWcdma;
import android.telephony.NetworkScanRequest;
-import android.telephony.RadioAccessFamily;
import android.telephony.RadioAccessSpecifier;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
@@ -157,10 +153,6 @@ import android.telephony.TelephonyManager;
import android.telephony.data.ApnSetting;
import android.telephony.data.DataCallResponse;
import android.telephony.data.DataProfile;
-import android.telephony.data.EpsQos;
-import android.telephony.data.QosBearerFilter;
-import android.telephony.data.QosBearerSession;
-import android.telephony.data.TrafficDescriptor;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
@@ -175,9 +167,6 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
-import java.io.ByteArrayInputStream;
-import java.io.DataInputStream;
-import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -202,6 +191,8 @@ public class RILTest extends TelephonyTest {
private TelephonyManager mTelephonyManager;
@Mock
private IRadio mRadioProxy;
+ @Mock
+ private IOemHook mOemHookProxy;
private HalVersion mRadioVersionV10 = new HalVersion(1, 0);
private HalVersion mRadioVersionV11 = new HalVersion(1, 1);
@@ -209,7 +200,6 @@ public class RILTest extends TelephonyTest {
private HalVersion mRadioVersionV13 = new HalVersion(1, 3);
private HalVersion mRadioVersionV14 = new HalVersion(1, 4);
private HalVersion mRadioVersionV15 = new HalVersion(1, 5);
- private HalVersion mRadioVersionV16 = new HalVersion(1, 6);
private RIL mRILInstance;
private RIL mRILUnderTest;
@@ -276,7 +266,7 @@ public class RILTest extends TelephonyTest {
private static final int MAX_CONNS = 3;
private static final int WAIT_TIME = 10;
private static final boolean APN_ENABLED = true;
- private static final int SUPPORTED_APN_TYPES_BITMASK = 123456;
+ private static final int SUPPORTED_APNT_YPES_BITMAK = 123456;
private static final int ROAMING_PROTOCOL = ApnSetting.PROTOCOL_IPV6;
private static final int BEARER_BITMASK = 123123;
private static final int MTU = 1234;
@@ -308,11 +298,11 @@ public class RILTest extends TelephonyTest {
doReturn(powerManager).when(context).getSystemService(Context.POWER_SERVICE);
doReturn(new ApplicationInfo()).when(context).getApplicationInfo();
- mRILInstance = new RIL(context,
- RadioAccessFamily.getRafFromNetworkType(RILConstants.PREFERRED_NETWORK_MODE),
+ mRILInstance = new RIL(context, RILConstants.PREFERRED_NETWORK_MODE,
Phone.PREFERRED_CDMA_SUBSCRIPTION, 0);
mRILUnderTest = spy(mRILInstance);
doReturn(mRadioProxy).when(mRILUnderTest).getRadioProxy(any());
+ doReturn(mOemHookProxy).when(mRILUnderTest).getOemHookProxy(any());
try {
replaceInstance(RIL.class, "mRadioVersion", mRILUnderTest, mRadioVersionV10);
@@ -717,29 +707,6 @@ public class RILTest extends TelephonyTest {
@FlakyTest
@Test
- public void testSetRadioPower_1_6() throws Exception {
- boolean on = true, forEmergencyCall = false, preferredForEmergencyCall = false;
-
- // Use Radio HAL v1.6
- try {
- replaceInstance(RIL.class, "mRadioVersion", mRILUnderTest, mRadioVersionV16);
- } catch (Exception e) {
- }
-
- mRILUnderTest.setRadioPower(
- on, forEmergencyCall, preferredForEmergencyCall, obtainMessage());
- verify(mRadioProxy)
- .setRadioPower_1_6(
- mSerialNumberCaptor.capture(),
- eq(on),
- eq(forEmergencyCall),
- eq(preferredForEmergencyCall));
- verifyRILResponse_1_6(
- mRILUnderTest, mSerialNumberCaptor.getValue(), RIL_REQUEST_RADIO_POWER);
- }
-
- @FlakyTest
- @Test
public void testSendDtmf() throws Exception {
char c = 'c';
mRILUnderTest.sendDtmf(c, obtainMessage());
@@ -762,24 +729,6 @@ public class RILTest extends TelephonyTest {
@FlakyTest
@Test
- public void testSendSMS_1_6() throws Exception {
- // Use Radio HAL v1.6
- try {
- replaceInstance(RIL.class, "mRadioVersion", mRILUnderTest, mRadioVersionV16);
- } catch (Exception e) {
- }
- String smscPdu = "smscPdu";
- String pdu = "pdu";
- GsmSmsMessage msg = new GsmSmsMessage();
- msg.smscPdu = smscPdu;
- msg.pdu = pdu;
- mRILUnderTest.sendSMS(smscPdu, pdu, obtainMessage());
- verify(mRadioProxy).sendSms_1_6(mSerialNumberCaptor.capture(), eq(msg));
- verifyRILResponse(mRILUnderTest, mSerialNumberCaptor.getValue(), RIL_REQUEST_SEND_SMS);
- }
-
- @FlakyTest
- @Test
public void testSendSMSExpectMore() throws Exception {
String smscPdu = "smscPdu";
String pdu = "pdu";
@@ -794,93 +743,6 @@ public class RILTest extends TelephonyTest {
@FlakyTest
@Test
- public void testSendSMSExpectMore_1_6() throws Exception {
- // Use Radio HAL v1.6
- try {
- replaceInstance(RIL.class, "mRadioVersion", mRILUnderTest, mRadioVersionV16);
- } catch (Exception e) {
- }
- String smscPdu = "smscPdu";
- String pdu = "pdu";
- GsmSmsMessage msg = new GsmSmsMessage();
- msg.smscPdu = smscPdu;
- msg.pdu = pdu;
- mRILUnderTest.sendSMSExpectMore(smscPdu, pdu, obtainMessage());
- verify(mRadioProxy).sendSmsExpectMore_1_6(mSerialNumberCaptor.capture(), eq(msg));
- verifyRILResponse(
- mRILUnderTest, mSerialNumberCaptor.getValue(), RIL_REQUEST_SEND_SMS_EXPECT_MORE);
- }
-
- @FlakyTest
- @Test
- public void testSendCdmaSMS_1_6() throws Exception {
- // Use Radio HAL v1.6
- try {
- replaceInstance(RIL.class, "mRadioVersion", mRILUnderTest, mRadioVersionV16);
- } catch (Exception e) {
- }
- byte[] pdu = "000010020000000000000000000000000000000000".getBytes();
- CdmaSmsMessage msg = new CdmaSmsMessage();
- constructCdmaSendSmsRilRequest(msg, pdu);
- mRILUnderTest.sendCdmaSms(pdu, obtainMessage());
- verify(mRadioProxy).sendCdmaSms_1_6(mSerialNumberCaptor.capture(), eq(msg));
- verifyRILResponse(mRILUnderTest, mSerialNumberCaptor.getValue(), RIL_REQUEST_CDMA_SEND_SMS);
- }
-
- @FlakyTest
- @Test
- public void testSendCdmaSMSExpectMore_1_6() throws Exception {
- // Use Radio HAL v1.6
- try {
- replaceInstance(RIL.class, "mRadioVersion", mRILUnderTest, mRadioVersionV16);
- } catch (Exception e) {
- }
- byte[] pdu = "000010020000000000000000000000000000000000".getBytes();
- CdmaSmsMessage msg = new CdmaSmsMessage();
- constructCdmaSendSmsRilRequest(msg, pdu);
- mRILUnderTest.sendCdmaSMSExpectMore(pdu, obtainMessage());
- verify(mRadioProxy).sendCdmaSmsExpectMore_1_6(mSerialNumberCaptor.capture(), eq(msg));
- verifyRILResponse(mRILUnderTest, mSerialNumberCaptor.getValue(),
- RIL_REQUEST_CDMA_SEND_SMS_EXPECT_MORE);
- }
-
- private void constructCdmaSendSmsRilRequest(CdmaSmsMessage msg, byte[] pdu) {
- int addrNbrOfDigits;
- int subaddrNbrOfDigits;
- int bearerDataLength;
- ByteArrayInputStream bais = new ByteArrayInputStream(pdu);
- DataInputStream dis = new DataInputStream(bais);
-
- try {
- msg.teleserviceId = dis.readInt(); // teleServiceId
- msg.isServicePresent = (byte) dis.readInt() == 1 ? true : false; // servicePresent
- msg.serviceCategory = dis.readInt(); // serviceCategory
- msg.address.digitMode = dis.read(); // address digit mode
- msg.address.numberMode = dis.read(); // address number mode
- msg.address.numberType = dis.read(); // address number type
- msg.address.numberPlan = dis.read(); // address number plan
- addrNbrOfDigits = (byte) dis.read();
- for (int i = 0; i < addrNbrOfDigits; i++) {
- msg.address.digits.add(dis.readByte()); // address_orig_bytes[i]
- }
- msg.subAddress.subaddressType = dis.read(); //subaddressType
- msg.subAddress.odd = (byte) dis.read() == 1 ? true : false; //subaddr odd
- subaddrNbrOfDigits = (byte) dis.read();
- for (int i = 0; i < subaddrNbrOfDigits; i++) {
- msg.subAddress.digits.add(dis.readByte()); //subaddr_orig_bytes[i]
- }
-
- bearerDataLength = dis.read();
- for (int i = 0; i < bearerDataLength; i++) {
- msg.bearerData.add(dis.readByte()); //bearerData[i]
- }
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
-
- @FlakyTest
- @Test
public void testWriteSmsToSim() throws Exception {
String smscPdu = "smscPdu";
String pdu = "pdu";
@@ -1066,13 +928,13 @@ public class RILTest extends TelephonyTest {
gsmMsg.pdu = pdu;
ImsSmsMessage firstMsg = new ImsSmsMessage();
- firstMsg.tech = RadioTechnologyFamily.THREE_GPP;
+ firstMsg.tech = RILConstants.GSM_PHONE;
firstMsg.retry = false;
firstMsg.messageRef = 0;
firstMsg.gsmMessage.add(gsmMsg);
ImsSmsMessage retryMsg = new ImsSmsMessage();
- retryMsg.tech = RadioTechnologyFamily.THREE_GPP;
+ retryMsg.tech = RILConstants.GSM_PHONE;
retryMsg.retry = true;
retryMsg.messageRef = 0;
retryMsg.gsmMessage.add(gsmMsg);
@@ -1101,13 +963,13 @@ public class RILTest extends TelephonyTest {
CdmaSmsMessage cdmaMsg = new CdmaSmsMessage();
ImsSmsMessage firstMsg = new ImsSmsMessage();
- firstMsg.tech = RadioTechnologyFamily.THREE_GPP2;
+ firstMsg.tech = RILConstants.CDMA_PHONE;
firstMsg.retry = false;
firstMsg.messageRef = 0;
firstMsg.cdmaMessage.add(cdmaMsg);
ImsSmsMessage retryMsg = new ImsSmsMessage();
- retryMsg.tech = RadioTechnologyFamily.THREE_GPP2;
+ retryMsg.tech = RILConstants.CDMA_PHONE;
retryMsg.retry = true;
retryMsg.messageRef = 0;
retryMsg.cdmaMessage.add(cdmaMsg);
@@ -1379,6 +1241,22 @@ public class RILTest extends TelephonyTest {
mRILUnderTest, mSerialNumberCaptor.getValue(), RIL_REQUEST_GET_BARRING_INFO);
}
+ @Test
+ public void testInvokeOemRilRequestStrings() throws Exception {
+ String[] strings = new String[]{"a", "b", "c"};
+ mRILUnderTest.invokeOemRilRequestStrings(strings, obtainMessage());
+ verify(mOemHookProxy).sendRequestStrings(
+ mSerialNumberCaptor.capture(), eq(new ArrayList<>(Arrays.asList(strings))));
+ }
+
+ @Test
+ public void testInvokeOemRilRequestRaw() throws Exception {
+ byte[] data = new byte[]{1, 2, 3};
+ mRILUnderTest.invokeOemRilRequestRaw(data, obtainMessage());
+ verify(mOemHookProxy).sendRequestRaw(
+ mSerialNumberCaptor.capture(), eq(mRILUnderTest.primitiveArrayToArrayList(data)));
+ }
+
private Message obtainMessage() {
return mRILUnderTest.getRilHandler().obtainMessage();
}
@@ -1399,23 +1277,6 @@ public class RILTest extends TelephonyTest {
assertFalse(ril.getWakeLock(RIL.FOR_WAKELOCK).isHeld());
}
- private static void verifyRILResponse_1_6(RIL ril, int serial, int requestType) {
- android.hardware.radio.V1_6.RadioResponseInfo responseInfo =
- createFakeRadioResponseInfo_1_6(
- serial, RadioError.NONE, RadioResponseType.SOLICITED);
-
- RILRequest rr = ril.processResponse_1_6(responseInfo);
- assertNotNull(rr);
-
- assertEquals(serial, rr.getSerial());
- assertEquals(requestType, rr.getRequest());
- assertTrue(ril.getWakeLock(RIL.FOR_WAKELOCK).isHeld());
-
- ril.processResponseDone_1_6(rr, responseInfo, null);
- assertEquals(0, ril.getRilRequestList().size());
- assertFalse(ril.getWakeLock(RIL.FOR_WAKELOCK).isHeld());
- }
-
private static void verifyRILErrorResponse(RIL ril, int serial, int requestType, int error) {
RadioResponseInfo responseInfo =
createFakeRadioResponseInfo(serial, error, RadioResponseType.SOLICITED);
@@ -1461,16 +1322,6 @@ public class RILTest extends TelephonyTest {
return respInfo;
}
- private static android.hardware.radio.V1_6.RadioResponseInfo createFakeRadioResponseInfo_1_6(
- int serial, int error, int type) {
- android.hardware.radio.V1_6.RadioResponseInfo respInfo =
- new android.hardware.radio.V1_6.RadioResponseInfo();
- respInfo.serial = serial;
- respInfo.error = error;
- respInfo.type = type;
- return respInfo;
- }
-
@Test
public void testConvertHalCellInfoListForLTE() {
android.hardware.radio.V1_0.CellInfoLte lte = new android.hardware.radio.V1_0.CellInfoLte();
@@ -2143,7 +1994,7 @@ public class RILTest extends TelephonyTest {
DataCallResponse response = new DataCallResponse.Builder()
.setCause(0)
- .setRetryDurationMillis(-1L)
+ .setSuggestedRetryTime(-1)
.setId(0)
.setLinkStatus(2)
.setProtocolType(ApnSetting.PROTOCOL_IPV4V6)
@@ -2162,8 +2013,6 @@ public class RILTest extends TelephonyTest {
.setMtu(1500)
.setMtuV4(1500)
.setMtuV6(1500)
- .setQosBearerSessions(new ArrayList<>())
- .setTrafficDescriptors(new ArrayList<>())
.build();
assertEquals(response, RIL.convertDataCallResult(result10));
@@ -2218,7 +2067,7 @@ public class RILTest extends TelephonyTest {
response = new DataCallResponse.Builder()
.setCause(0)
- .setRetryDurationMillis(-1L)
+ .setSuggestedRetryTime(-1)
.setId(0)
.setLinkStatus(2)
.setProtocolType(ApnSetting.PROTOCOL_IPV4V6)
@@ -2237,138 +2086,9 @@ public class RILTest extends TelephonyTest {
.setMtu(3000)
.setMtuV4(1500)
.setMtuV6(3000)
- .setQosBearerSessions(new ArrayList<>())
- .setTrafficDescriptors(new ArrayList<>())
.build();
assertEquals(response, RIL.convertDataCallResult(result15));
-
- // Test V1.6 SetupDataCallResult
- android.hardware.radio.V1_6.SetupDataCallResult result16 =
- new android.hardware.radio.V1_6.SetupDataCallResult();
- result16.cause = android.hardware.radio.V1_4.DataCallFailCause.NONE;
- result16.suggestedRetryTime = -1;
- result16.cid = 0;
- result16.active = android.hardware.radio.V1_4.DataConnActiveStatus.ACTIVE;
- result16.type = android.hardware.radio.V1_4.PdpProtocolType.IPV4V6;
- result16.ifname = "ifname";
-
- result16.addresses = new ArrayList<>(Arrays.asList(la1, la2));
- result16.dnses = new ArrayList<>(Arrays.asList("10.0.2.3", "fd00:976a::9"));
- result16.gateways = new ArrayList<>(Arrays.asList("10.0.2.15", "fe80::2"));
- result16.pcscf = new ArrayList<>(Arrays.asList(
- "fd00:976a:c206:20::6", "fd00:976a:c206:20::9", "fd00:976a:c202:1d::9"));
- result16.mtuV4 = 1500;
- result16.mtuV6 = 3000;
- result16.handoverFailureMode = android.hardware.radio.V1_6.HandoverFailureMode.LEGACY;
-
- // Build android.hardware.radio.V1_6.EpsQos
- android.hardware.radio.V1_6.EpsQos halEpsQos = new android.hardware.radio.V1_6.EpsQos();
- halEpsQos.qci = 4;
- halEpsQos.downlink.maxBitrateKbps = 4;
- halEpsQos.downlink.guaranteedBitrateKbps = 7;
- halEpsQos.uplink.maxBitrateKbps = 5;
- halEpsQos.uplink.guaranteedBitrateKbps = 8;
-
- result16.defaultQos.eps(halEpsQos);
-
- // android.hardware.radio.V1_6.PortRange
- android.hardware.radio.V1_6.PortRange localPort =
- new android.hardware.radio.V1_6.PortRange();
- android.hardware.radio.V1_6.PortRange remotePort =
- new android.hardware.radio.V1_6.PortRange();
- localPort.start = 123;
- localPort.end = 123;
- remotePort.start = 223;
- remotePort.end = 223;
-
- // android.hardware.radio.V1_6.QosFilter
- android.hardware.radio.V1_6.QosFilter halQosFilter =
- new android.hardware.radio.V1_6.QosFilter();
- halQosFilter.localAddresses = new ArrayList<>(Arrays.asList("122.22.22.22"));
- halQosFilter.remoteAddresses = new ArrayList<>(Arrays.asList("144.44.44.44"));
- halQosFilter.localPort.range(localPort);
- halQosFilter.remotePort.range(remotePort);
- halQosFilter.protocol = android.hardware.radio.V1_6.QosProtocol.UDP;
- halQosFilter.tos.value((byte)7);
- halQosFilter.flowLabel.value(987);
- halQosFilter.spi.value(678);
- halQosFilter.direction = android.hardware.radio.V1_6.QosFilterDirection.BIDIRECTIONAL;
- halQosFilter.precedence = 45;
-
- // android.hardware.radio.V1_6.QosSession
- android.hardware.radio.V1_6.QosSession halQosSession =
- new android.hardware.radio.V1_6.QosSession();
- halQosSession.qosSessionId = 1234;
- halQosSession.qos.eps(halEpsQos);
- halQosSession.qosFilters = new ArrayList<>(Arrays.asList(halQosFilter));
-
- result16.qosSessions = new ArrayList<>(Arrays.asList(halQosSession));
-
- EpsQos epsQos = new EpsQos(halEpsQos);
- QosBearerFilter qosFilter = new QosBearerFilter(
- Arrays.asList(
- new LinkAddress(InetAddresses.parseNumericAddress("122.22.22.22"), 32)),
- Arrays.asList(
- new LinkAddress(InetAddresses.parseNumericAddress("144.44.44.44"), 32)),
- new QosBearerFilter.PortRange(123, 123), new QosBearerFilter.PortRange(223, 223),
- QosBearerFilter.QOS_PROTOCOL_UDP, 7, 987, 678,
- QosBearerFilter.QOS_FILTER_DIRECTION_BIDIRECTIONAL, 45);
- ArrayList<QosBearerFilter> qosFilters = new ArrayList<>();
- ArrayList<QosBearerSession> qosSessions = new ArrayList<>();
- qosFilters.add(qosFilter);
- QosBearerSession qosSession = new QosBearerSession(1234, epsQos, qosFilters);
- qosSessions.add(qosSession);
-
- // android.hardware.radio.V1_6.TrafficDescriptor
- android.hardware.radio.V1_6.TrafficDescriptor halTrafficDescriptor =
- new android.hardware.radio.V1_6.TrafficDescriptor();
- android.hardware.radio.V1_6.OptionalDnn halDnn =
- new android.hardware.radio.V1_6.OptionalDnn();
- halDnn.value("DNN");
-
- android.hardware.radio.V1_6.OptionalOsAppId halOsAppId =
- new android.hardware.radio.V1_6.OptionalOsAppId();
- android.hardware.radio.V1_6.OsAppId osAppId = new android.hardware.radio.V1_6.OsAppId();
- byte[] osAppIdArray = {1, 2, 3, 4};
- osAppId.osAppId = mRILUnderTest.primitiveArrayToArrayList(osAppIdArray);
- halOsAppId.value(osAppId);
-
- halTrafficDescriptor.dnn = halDnn;
- halTrafficDescriptor.osAppId = halOsAppId;
- result16.trafficDescriptors = new ArrayList<>(Arrays.asList(halTrafficDescriptor));
-
- List<TrafficDescriptor> trafficDescriptors = Arrays.asList(
- new TrafficDescriptor("DNN", osAppIdArray));
-
- response = new DataCallResponse.Builder()
- .setCause(0)
- .setRetryDurationMillis(-1L)
- .setId(0)
- .setLinkStatus(2)
- .setProtocolType(ApnSetting.PROTOCOL_IPV4V6)
- .setInterfaceName("ifname")
- .setAddresses(Arrays.asList(
- new LinkAddress(InetAddresses.parseNumericAddress("10.0.2.15"), 32),
- new LinkAddress("2607:fb90:a620:651d:eabe:f8da:c107:44be/64")))
- .setDnsAddresses(Arrays.asList(InetAddresses.parseNumericAddress("10.0.2.3"),
- InetAddresses.parseNumericAddress("fd00:976a::9")))
- .setGatewayAddresses(Arrays.asList(InetAddresses.parseNumericAddress("10.0.2.15"),
- InetAddresses.parseNumericAddress("fe80::2")))
- .setPcscfAddresses(Arrays.asList(
- InetAddresses.parseNumericAddress("fd00:976a:c206:20::6"),
- InetAddresses.parseNumericAddress("fd00:976a:c206:20::9"),
- InetAddresses.parseNumericAddress("fd00:976a:c202:1d::9")))
- .setMtu(3000)
- .setMtuV4(1500)
- .setMtuV6(3000)
- .setHandoverFailureMode(DataCallResponse.HANDOVER_FAILURE_MODE_LEGACY)
- .setDefaultQos(epsQos)
- .setQosBearerSessions(qosSessions)
- .setTrafficDescriptors(trafficDescriptors)
- .build();
-
- assertEquals(response, RIL.convertDataCallResult(result16));
}
@Test
@@ -2614,7 +2334,7 @@ public class RILTest extends TelephonyTest {
.setMaxConnections(MAX_CONNS)
.setWaitTime(WAIT_TIME)
.enable(APN_ENABLED)
- .setSupportedApnTypesBitmask(SUPPORTED_APN_TYPES_BITMASK)
+ .setSupportedApnTypesBitmask(SUPPORTED_APNT_YPES_BITMAK)
.setRoamingProtocolType(ROAMING_PROTOCOL)
.setBearerBitmask(BEARER_BITMASK)
.setMtu(MTU)
@@ -2623,8 +2343,7 @@ public class RILTest extends TelephonyTest {
.build();
mRILUnderTest.setupDataCall(AccessNetworkConstants.AccessNetworkType.EUTRAN, dp, false,
- false, 0, null,
- DataCallResponse.PDU_SESSION_ID_NOT_SET, null, null, true, obtainMessage());
+ false, 0, null, obtainMessage());
ArgumentCaptor<DataProfileInfo> dpiCaptor = ArgumentCaptor.forClass(DataProfileInfo.class);
verify(mRadioProxy).setupDataCall(
mSerialNumberCaptor.capture(), eq(AccessNetworkConstants.AccessNetworkType.EUTRAN),
@@ -2643,7 +2362,7 @@ public class RILTest extends TelephonyTest {
assertEquals(MAX_CONNS, dpi.maxConns);
assertEquals(WAIT_TIME, dpi.waitTime);
assertEquals(APN_ENABLED, dpi.enabled);
- assertEquals(SUPPORTED_APN_TYPES_BITMASK, dpi.supportedApnTypesBitmap);
+ assertEquals(SUPPORTED_APNT_YPES_BITMAK, dpi.supportedApnTypesBitmap);
assertEquals(ROAMING_PROTOCOL, ApnSetting.getProtocolIntFromString(dpi.protocol));
assertEquals(
BEARER_BITMASK,
@@ -2803,18 +2522,4 @@ public class RILTest extends TelephonyTest {
mRILUnderTest.setCompatVersion(testRequest, RIL.RADIO_HAL_VERSION_1_5);
assertEquals(RIL.RADIO_HAL_VERSION_1_3, mRILUnderTest.getCompatVersion(testRequest));
}
-
- @FlakyTest
- @Test
- public void testGetSlicingConfig() throws Exception {
- // Use Radio HAL v1.6
- try {
- replaceInstance(RIL.class, "mRadioVersion", mRILUnderTest, mRadioVersionV16);
- } catch (Exception e) {
- }
- mRILUnderTest.getSlicingConfig(obtainMessage());
- verify(mRadioProxy).getSlicingConfig(mSerialNumberCaptor.capture());
- verifyRILResponse_1_6(
- mRILUnderTest, mSerialNumberCaptor.getValue(), RIL_REQUEST_GET_SLICING_CONFIG);
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/RadioConfigResponseTest.java b/tests/telephonytests/src/com/android/internal/telephony/RadioConfigResponseTest.java
deleted file mode 100644
index d529d6791b..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/RadioConfigResponseTest.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.internal.telephony;
-
-import static junit.framework.Assert.assertTrue;
-
-import static org.junit.Assert.assertFalse;
-
-import android.telephony.TelephonyManager;
-import android.testing.AndroidTestingRunner;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.Set;
-
-@RunWith(AndroidTestingRunner.class)
-public class RadioConfigResponseTest extends TelephonyTest {
- @Before
- public void setUp() throws Exception {
- super.setUp(RadioConfigResponseTest.class.getSimpleName());
- }
-
- @After
- public void tearDown() throws Exception {
- super.tearDown();
- }
-
- @Test
- public void testVersion_1_5() {
- Set<String> caps = RadioConfigResponse.getCaps(RIL.RADIO_HAL_VERSION_1_5, false);
- assertFalse(
- caps.contains(TelephonyManager.CAPABILITY_SECONDARY_LINK_BANDWIDTH_VISIBLE));
- assertFalse(
- caps.contains(TelephonyManager.CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK));
- assertFalse(
- caps.contains(
- TelephonyManager.CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE));
- assertFalse(
- caps.contains(TelephonyManager.CAPABILITY_THERMAL_MITIGATION_DATA_THROTTLING));
- assertFalse(
- caps.contains(TelephonyManager.CAPABILITY_SLICING_CONFIG_SUPPORTED));
- }
-
- @Test
- public void testReducedFeatureSet() {
- Set<String> caps = RadioConfigResponse.getCaps(RIL.RADIO_HAL_VERSION_1_6, true);
- assertFalse(
- caps.contains(TelephonyManager.CAPABILITY_SECONDARY_LINK_BANDWIDTH_VISIBLE));
- assertTrue(
- caps.contains(TelephonyManager.CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK));
- assertFalse(
- caps.contains(
- TelephonyManager.CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE));
- assertFalse(
- caps.contains(TelephonyManager.CAPABILITY_THERMAL_MITIGATION_DATA_THROTTLING));
- assertFalse(
- caps.contains(TelephonyManager.CAPABILITY_SLICING_CONFIG_SUPPORTED));
- assertTrue(
- caps.contains(TelephonyManager.CAPABILITY_SIM_PHONEBOOK_IN_MODEM));
- }
-
- @Test
- public void testNonReducedFeatureSet() {
- Set<String> caps = RadioConfigResponse.getCaps(RIL.RADIO_HAL_VERSION_1_6, false);
- assertTrue(
- caps.contains(TelephonyManager.CAPABILITY_SECONDARY_LINK_BANDWIDTH_VISIBLE));
- assertTrue(
- caps.contains(TelephonyManager.CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK));
- assertTrue(
- caps.contains(
- TelephonyManager.CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE));
- assertTrue(
- caps.contains(TelephonyManager.CAPABILITY_THERMAL_MITIGATION_DATA_THROTTLING));
- assertTrue(
- caps.contains(TelephonyManager.CAPABILITY_SLICING_CONFIG_SUPPORTED));
- assertFalse(
- caps.contains(TelephonyManager.CAPABILITY_SIM_PHONEBOOK_IN_MODEM));
- }
-}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/RadioInterfaceCapabilityControllerTest.java b/tests/telephonytests/src/com/android/internal/telephony/RadioInterfaceCapabilityControllerTest.java
deleted file mode 100644
index e8e11249ea..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/RadioInterfaceCapabilityControllerTest.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.internal.telephony;
-
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertTrue;
-
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
-import android.os.AsyncResult;
-import android.os.Handler;
-import android.os.Message;
-import android.telephony.TelephonyManager;
-import android.testing.AndroidTestingRunner;
-import android.testing.TestableLooper;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mock;
-
-import java.util.HashSet;
-import java.util.Set;
-
-@RunWith(AndroidTestingRunner.class)
-@TestableLooper.RunWithLooper
-public class RadioInterfaceCapabilityControllerTest extends TelephonyTest {
- @Mock
- RadioConfig mMockRadioConfig;
-
- @Mock
- CommandsInterface mMockCommandsInterface;
-
- @Before
- public void setUp() throws Exception {
- super.setUp(getClass().getSimpleName());
- }
-
- @After
- public void tearDown() throws Exception {
- super.tearDown();
- }
-
- @Test
- public void testRadioInterfaceCapabilities() {
- final RadioInterfaceCapabilityController capabilities =
- new RadioInterfaceCapabilityController(mMockRadioConfig, mMockCommandsInterface,
- mTestableLooper.getLooper());
-
- // The capabilities to test for
- final Set<String> capabilitySet = new HashSet<>();
- capabilitySet.add(TelephonyManager.CAPABILITY_SECONDARY_LINK_BANDWIDTH_VISIBLE);
-
- registerForRadioAvailable();
- getHalDeviceCapabilities(capabilitySet);
-
- // Test for the capabilities
- assertEquals(1, capabilities.getCapabilities().size());
- assertTrue(capabilities.getCapabilities()
- .contains(TelephonyManager.CAPABILITY_SECONDARY_LINK_BANDWIDTH_VISIBLE));
- }
-
- private void registerForRadioAvailable() {
- // Capture radio avaialble
- final ArgumentCaptor<Handler> handlerCaptor = ArgumentCaptor.forClass(Handler.class);
- final ArgumentCaptor<Integer> whatCaptor = ArgumentCaptor.forClass(Integer.class);
- final ArgumentCaptor<Object> objCaptor = ArgumentCaptor.forClass(Object.class);
- verify(mMockCommandsInterface, times(1)).registerForAvailable(
- handlerCaptor.capture(), whatCaptor.capture(), objCaptor.capture());
-
- // Send Message back through handler
- final Message m = Message.obtain(
- handlerCaptor.getValue(), whatCaptor.getValue(), objCaptor.getValue());
- m.sendToTarget();
- processAllMessages();
- }
-
- private void getHalDeviceCapabilities(final Set<String> capabilitySet) {
- // Capture Message when the capabilities are requested
- final ArgumentCaptor<Message> deviceCapsMessage = ArgumentCaptor.forClass(Message.class);
- verify(mMockRadioConfig, times(1))
- .getHalDeviceCapabilities(deviceCapsMessage.capture());
-
- // Send Message back through handler
- final Message m = deviceCapsMessage.getValue();
- AsyncResult.forMessage(m, capabilitySet, null);
- m.sendToTarget();
- processAllMessages();
- }
-
- @Test
- public void testEmptyRadioInterfaceCapabilities() {
- final RadioInterfaceCapabilityController capabilities =
- new RadioInterfaceCapabilityController(mMockRadioConfig, null,
- mTestableLooper.getLooper());
-
- // Test for the capabilities
- assertEquals(0, capabilities.getCapabilities().size());
- }
-}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/RatRatcheterTest.java b/tests/telephonytests/src/com/android/internal/telephony/RatRatcheterTest.java
index c3789950ee..b0cc83ee16 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/RatRatcheterTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/RatRatcheterTest.java
@@ -104,7 +104,8 @@ public class RatRatcheterTest extends TelephonyTest {
false, // isDcNrRestricted
false, // isNrAvailable
false, // isEndcAvailable
- lteVopsSupportInfo); // lteVopsSupportInfo
+ lteVopsSupportInfo, // lteVopsSupportInfo
+ isUsingCarrierAggregation); // isUsingCarrierAggregation
}
private void setNetworkRegistrationInfo(ServiceState ss, int accessNetworkTechnology) {
@@ -140,7 +141,7 @@ public class RatRatcheterTest extends TelephonyTest {
setNetworkRegistrationInfo(newSS, TelephonyManager.NETWORK_TYPE_LTE);
RatRatcheter ratRatcheter = new RatRatcheter(mPhone);
- ratRatcheter.ratchet(oldSS, newSS);
+ ratRatcheter.ratchet(oldSS, newSS, false);
assertTrue(newSS.isUsingCarrierAggregation());
}
@@ -157,7 +158,7 @@ public class RatRatcheterTest extends TelephonyTest {
setNetworkRegistrationInfo(newSS, TelephonyManager.NETWORK_TYPE_LTE);
RatRatcheter ratRatcheter = new RatRatcheter(mPhone);
- ratRatcheter.ratchet(oldSS, newSS);
+ ratRatcheter.ratchet(oldSS, newSS, false);
assertFalse(newSS.isUsingCarrierAggregation());
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/ServiceStateTest.java b/tests/telephonytests/src/com/android/internal/telephony/ServiceStateTest.java
index 9057935ee9..7bb6476a90 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/ServiceStateTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/ServiceStateTest.java
@@ -335,7 +335,7 @@ public class ServiceStateTest extends TestCase {
wwanDataRegState = new NetworkRegistrationInfo(
NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
- 0, 0, 0, true, null, null, "", 0, false, false, false, lteVopsSupportInfo);
+ 0, 0, 0, true, null, null, "", 0, false, false, false, lteVopsSupportInfo, false);
ss.addNetworkRegistrationInfo(wwanDataRegState);
assertEquals(ss.getNetworkRegistrationInfo(NetworkRegistrationInfo.DOMAIN_PS,
AccessNetworkConstants.TRANSPORT_TYPE_WWAN), wwanDataRegState);
diff --git a/tests/telephonytests/src/com/android/internal/telephony/ServiceStateTrackerTest.java b/tests/telephonytests/src/com/android/internal/telephony/ServiceStateTrackerTest.java
index 98d5da31c2..cc7c8e904f 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/ServiceStateTrackerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/ServiceStateTrackerTest.java
@@ -36,6 +36,7 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import android.app.IAlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.ComponentName;
@@ -64,9 +65,6 @@ import android.telephony.CellIdentity;
import android.telephony.CellIdentityCdma;
import android.telephony.CellIdentityGsm;
import android.telephony.CellIdentityLte;
-import android.telephony.CellIdentityNr;
-import android.telephony.CellIdentityTdscdma;
-import android.telephony.CellIdentityWcdma;
import android.telephony.CellInfo;
import android.telephony.CellInfoGsm;
import android.telephony.CellSignalStrength;
@@ -80,7 +78,6 @@ import android.telephony.INetworkService;
import android.telephony.LteVopsSupportInfo;
import android.telephony.NetworkRegistrationInfo;
import android.telephony.NetworkService;
-import android.telephony.NrVopsSupportInfo;
import android.telephony.PhysicalChannelConfig;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
@@ -89,7 +86,6 @@ import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
-import android.telephony.ims.stub.ImsRegistrationImplBase;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.text.TextUtils;
@@ -99,7 +95,6 @@ import androidx.test.filters.FlakyTest;
import com.android.internal.R;
import com.android.internal.telephony.cdma.CdmaSubscriptionSourceManager;
-import com.android.internal.telephony.metrics.ServiceStateStats;
import com.android.internal.telephony.test.SimulatedCommands;
import com.android.internal.telephony.uicc.IccCardApplicationStatus;
import com.android.internal.telephony.uicc.IccRecords;
@@ -112,7 +107,6 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
-import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -125,6 +119,8 @@ public class ServiceStateTrackerTest extends TelephonyTest {
private ProxyController mProxyController;
@Mock
private Handler mTestHandler;
+ @Mock
+ protected IAlarmManager mAlarmManager;
private CellularNetworkService mCellularNetworkService;
@@ -136,9 +132,6 @@ public class ServiceStateTrackerTest extends TelephonyTest {
@Mock
private SubscriptionInfo mSubInfo;
- @Mock
- private ServiceStateStats mServiceStateStats;
-
private ServiceStateTracker sst;
private ServiceStateTrackerTestHandler mSSTTestHandler;
private PersistableBundle mBundle;
@@ -161,7 +154,6 @@ public class ServiceStateTrackerTest extends TelephonyTest {
private static final String CARRIER_NAME_DISPLAY_NO_SERVICE = "No service";
private static final String CARRIER_NAME_DISPLAY_EMERGENCY_CALL = "emergency call";
private static final String WIFI_CALLING_VOICE_FORMAT = "%s wifi calling";
- private static final String CROSS_SIM_CALLING_VOICE_FORMAT = "%s Cross-SIM Calling";
private static final String WIFI_CALLING_DATA_FORMAT = "%s wifi data";
private static final String WIFI_CALLING_FLIGHT_MODE_FORMAT = "%s flight mode";
@@ -189,8 +181,6 @@ public class ServiceStateTrackerTest extends TelephonyTest {
@Override
public void onLooperPrepared() {
sst = new ServiceStateTracker(mPhone, mSimulatedCommands);
- sst.setServiceStateStats(mServiceStateStats);
- doReturn(sst).when(mPhone).getServiceStateTracker();
setReady(true);
}
}
@@ -239,7 +229,7 @@ public class ServiceStateTrackerTest extends TelephonyTest {
doReturn(mIwlanNetworkServiceStub).when(mIwlanNetworkServiceStub).asBinder();
addNetworkService();
- doReturn(true).when(mDcTracker).areAllDataDisconnected();
+ doReturn(true).when(mDcTracker).isDisconnected();
doReturn(new ServiceState()).when(mPhone).getServiceState();
@@ -324,10 +314,10 @@ public class ServiceStateTrackerTest extends TelephonyTest {
});
mBundle.putIntArray(CarrierConfigManager.KEY_5G_NR_SSRSRQ_THRESHOLDS_INT_ARRAY,
new int[] {
- -31, /* SIGNAL_STRENGTH_POOR */
- -19, /* SIGNAL_STRENGTH_MODERATE */
- -7, /* SIGNAL_STRENGTH_GOOD */
- 6 /* SIGNAL_STRENGTH_GREAT */
+ -16, /* SIGNAL_STRENGTH_POOR */
+ -12, /* SIGNAL_STRENGTH_MODERATE */
+ -9, /* SIGNAL_STRENGTH_GOOD */
+ -6 /* SIGNAL_STRENGTH_GREAT */
});
mBundle.putIntArray(CarrierConfigManager.KEY_5G_NR_SSSINR_THRESHOLDS_INT_ARRAY,
new int[] {
@@ -403,42 +393,6 @@ public class ServiceStateTrackerTest extends TelephonyTest {
@Test
@MediumTest
- public void testSetRadioPowerForReason() {
- // Radio does not turn on if off for other reason and not emergency call.
- assertTrue(mSimulatedCommands.getRadioState() == TelephonyManager.RADIO_POWER_ON);
- assertTrue(sst.getRadioPowerOffReasons().isEmpty());
- sst.setRadioPowerForReason(false, false, false, false, Phone.RADIO_POWER_REASON_THERMAL);
- assertTrue(sst.getRadioPowerOffReasons().contains(Phone.RADIO_POWER_REASON_THERMAL));
- assertTrue(sst.getRadioPowerOffReasons().size() == 1);
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
- assertTrue(mSimulatedCommands.getRadioState() == TelephonyManager.RADIO_POWER_OFF);
- sst.setRadioPowerForReason(true, false, false, false, Phone.RADIO_POWER_REASON_USER);
- assertTrue(sst.getRadioPowerOffReasons().contains(Phone.RADIO_POWER_REASON_THERMAL));
- assertTrue(sst.getRadioPowerOffReasons().size() == 1);
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
- assertTrue(mSimulatedCommands.getRadioState() == TelephonyManager.RADIO_POWER_OFF);
-
- // Radio power state reason is removed and radio turns on if turned on for same reason it
- // had been turned off for.
- sst.setRadioPowerForReason(true, false, false, false, Phone.RADIO_POWER_REASON_THERMAL);
- assertTrue(sst.getRadioPowerOffReasons().isEmpty());
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
- assertTrue(mSimulatedCommands.getRadioState() == TelephonyManager.RADIO_POWER_ON);
-
- // Turn radio off, then successfully turn radio on for emergency call.
- sst.setRadioPowerForReason(false, false, false, false, Phone.RADIO_POWER_REASON_THERMAL);
- assertTrue(sst.getRadioPowerOffReasons().contains(Phone.RADIO_POWER_REASON_THERMAL));
- assertTrue(sst.getRadioPowerOffReasons().size() == 1);
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
- assertTrue(mSimulatedCommands.getRadioState() == TelephonyManager.RADIO_POWER_OFF);
- sst.setRadioPower(true, true, true, false);
- assertTrue(sst.getRadioPowerOffReasons().isEmpty());
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
- assertTrue(mSimulatedCommands.getRadioState() == TelephonyManager.RADIO_POWER_ON);
- }
-
- @Test
- @MediumTest
public void testSetRadioPowerFromCarrier() {
// Carrier disable radio power
sst.setRadioPowerFromCarrier(false);
@@ -836,7 +790,7 @@ public class ServiceStateTrackerTest extends TelephonyTest {
-20, /** csiRsrq NONE */
-23, /** CsiSinr NONE */
-44, /** SsRsrp SIGNAL_STRENGTH_GREAT */
- -32, /** SsRsrq NONE */
+ -20, /** SsRsrq NONE */
-23) /** SsSinr NONE */
);
@@ -1839,6 +1793,22 @@ public class ServiceStateTrackerTest extends TelephonyTest {
}
@Test
+ @MediumTest
+ public void testEnableLocationUpdates() throws Exception {
+ sst.enableLocationUpdates();
+ verify(mSimulatedCommandsVerifier, times(1)).setLocationUpdates(eq(true),
+ any(Message.class));
+ }
+
+ @Test
+ @SmallTest
+ public void testDisableLocationUpdates() throws Exception {
+ sst.disableLocationUpdates();
+ verify(mSimulatedCommandsVerifier, times(1)).setLocationUpdates(eq(false),
+ nullable(Message.class));
+ }
+
+ @Test
@SmallTest
public void testGetCurrentDataRegState() throws Exception {
sst.mSS.setDataRegState(ServiceState.STATE_OUT_OF_SERVICE);
@@ -1920,93 +1890,6 @@ public class ServiceStateTrackerTest extends TelephonyTest {
@Test
@SmallTest
- public void testSetImsRegisteredStateRunsShutdownImmediately() throws Exception {
- doReturn(true).when(mPhone).isPhoneTypeGsm();
- sst.setImsRegistrationState(true);
- mSimulatedCommands.setRadioPowerFailResponse(false);
- sst.setRadioPower(true);
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
-
- assertEquals(TelephonyManager.RADIO_POWER_ON, mSimulatedCommands.getRadioState());
- sst.requestShutdown();
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
-
- sst.setImsRegistrationState(false);
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
- assertEquals(TelephonyManager.RADIO_POWER_UNAVAILABLE, mSimulatedCommands.getRadioState());
- }
-
- @Test
- @SmallTest
- public void testImsRegisteredDelayShutDown() throws Exception {
- doReturn(true).when(mPhone).isPhoneTypeGsm();
- sst.setImsRegistrationState(true);
- mSimulatedCommands.setRadioPowerFailResponse(false);
- sst.setRadioPower(true);
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
-
- // Turn off the radio and ensure radio power is still on
- assertEquals(TelephonyManager.RADIO_POWER_ON, mSimulatedCommands.getRadioState());
- sst.setRadioPower(false);
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
- assertEquals(TelephonyManager.RADIO_POWER_ON, mSimulatedCommands.getRadioState());
-
- // Now set IMS reg state to false and ensure we see the modem move to power off.
- sst.setImsRegistrationState(false);
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
- assertEquals(TelephonyManager.RADIO_POWER_OFF, mSimulatedCommands.getRadioState());
- }
-
- @Test
- @SmallTest
- public void testImsRegisteredDelayShutDownTimeout() throws Exception {
- doReturn(true).when(mPhone).isPhoneTypeGsm();
- sst.setImsRegistrationState(true);
- mSimulatedCommands.setRadioPowerFailResponse(false);
- sst.setRadioPower(true);
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
-
- // Turn off the radio and ensure radio power is still on
- assertEquals(TelephonyManager.RADIO_POWER_ON, mSimulatedCommands.getRadioState());
- sst.setRadioPower(false);
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
- assertEquals(TelephonyManager.RADIO_POWER_ON, mSimulatedCommands.getRadioState());
-
- // Ensure that if we never turn deregister for IMS, we still eventually see radio state
- // move to off.
- // Timeout for IMS reg + some extra time to remove race conditions
- waitForDelayedHandlerAction(mSSTTestHandler.getThreadHandler(),
- ServiceStateTracker.DELAY_RADIO_OFF_FOR_IMS_DEREG_TIMEOUT + 100, 1000);
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
- assertEquals(TelephonyManager.RADIO_POWER_OFF, mSimulatedCommands.getRadioState());
- }
-
- @Test
- @SmallTest
- public void testImsRegisteredAPMOnOffToggle() throws Exception {
- doReturn(true).when(mPhone).isPhoneTypeGsm();
- sst.setImsRegistrationState(true);
- mSimulatedCommands.setRadioPowerFailResponse(false);
- sst.setRadioPower(true);
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
-
- // Turn off the radio and ensure radio power is still on and then turn it back on again
- assertEquals(TelephonyManager.RADIO_POWER_ON, mSimulatedCommands.getRadioState());
- sst.setRadioPower(false);
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
- sst.setRadioPower(true);
- assertEquals(TelephonyManager.RADIO_POWER_ON, mSimulatedCommands.getRadioState());
-
- // Ensure the timeout was cancelled and we still see radio power is on.
- // Timeout for IMS reg + some extra time to remove race conditions
- waitForDelayedHandlerAction(mSSTTestHandler.getThreadHandler(),
- ServiceStateTracker.DELAY_RADIO_OFF_FOR_IMS_DEREG_TIMEOUT + 100, 1000);
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
- assertEquals(TelephonyManager.RADIO_POWER_ON, mSimulatedCommands.getRadioState());
- }
-
- @Test
- @SmallTest
public void testSetTimeFromNITZStr() throws Exception {
{
// Mock sending incorrect nitz str from RIL
@@ -2044,7 +1927,7 @@ public class ServiceStateTrackerTest extends TelephonyTest {
NetworkRegistrationInfo dataResult = new NetworkRegistrationInfo(
NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
state, dataRat, 0, false, null, cid, getPlmnFromCellIdentity(cid),
- 1, false, false, false, lteVopsSupportInfo);
+ 1, false, false, false, lteVopsSupportInfo, false);
sst.mPollingContext[0] = 2;
// update data reg state to be in service
sst.sendMessage(sst.obtainMessage(
@@ -2072,7 +1955,7 @@ public class ServiceStateTrackerTest extends TelephonyTest {
NetworkRegistrationInfo dataResult = new NetworkRegistrationInfo(
NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
state, dataRat, 0, false, null, cid, getPlmnFromCellIdentity(cid),
- 1, false, false, false, lteVopsSupportInfo);
+ 1, false, false, false, lteVopsSupportInfo, false);
sst.sendMessage(sst.obtainMessage(
ServiceStateTracker.EVENT_POLL_STATE_PS_CELLULAR_REGISTRATION,
new AsyncResult(sst.mPollingContext, dataResult, null)));
@@ -2091,7 +1974,7 @@ public class ServiceStateTrackerTest extends TelephonyTest {
NetworkRegistrationInfo dataIwlanResult = new NetworkRegistrationInfo(
NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WLAN,
iwlanState, iwlanDataRat, 0, false,
- null, null, "", 1, false, false, false, lteVopsSupportInfo);
+ null, null, "", 1, false, false, false, lteVopsSupportInfo, false);
sst.sendMessage(sst.obtainMessage(
ServiceStateTracker.EVENT_POLL_STATE_PS_IWLAN_REGISTRATION,
new AsyncResult(sst.mPollingContext, dataIwlanResult, null)));
@@ -2118,64 +2001,6 @@ public class ServiceStateTrackerTest extends TelephonyTest {
assertEquals(null, sst.getServiceState().getOperatorAlpha());
}
- @Test
- public void testCSEmergencyRegistrationState() throws Exception {
- CellIdentityGsm cellIdentity =
- new CellIdentityGsm(0, 1, 900, 5, "001", "01", "test", "tst",
- Collections.emptyList());
-
- NetworkRegistrationInfo dataReg = new NetworkRegistrationInfo(
- NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
- 0, 16, 0, false, null, cellIdentity, getPlmnFromCellIdentity(cellIdentity),
- 1, false, false, false, null);
-
- NetworkRegistrationInfo voiceReg = new NetworkRegistrationInfo(
- NetworkRegistrationInfo.DOMAIN_CS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
- 0, 16, 0, true, null, cellIdentity, getPlmnFromCellIdentity(cellIdentity),
- false, 0, 0, 0);
-
- sst.mPollingContext[0] = 2;
- // update data reg state to be in oos
- sst.sendMessage(sst.obtainMessage(
- ServiceStateTracker.EVENT_POLL_STATE_PS_CELLULAR_REGISTRATION,
- new AsyncResult(sst.mPollingContext, dataReg, null)));
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
- sst.sendMessage(sst.obtainMessage(
- ServiceStateTracker.EVENT_POLL_STATE_CS_CELLULAR_REGISTRATION,
- new AsyncResult(sst.mPollingContext, voiceReg, null)));
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
- assertTrue(sst.mSS.isEmergencyOnly());
- }
-
- @Test
- public void testPSEmergencyRegistrationState() throws Exception {
- CellIdentityGsm cellIdentity =
- new CellIdentityGsm(0, 1, 900, 5, "001", "01", "test", "tst",
- Collections.emptyList());
-
- NetworkRegistrationInfo dataReg = new NetworkRegistrationInfo(
- NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
- 0, 16, 0, true, null, cellIdentity, getPlmnFromCellIdentity(cellIdentity),
- 1, false, false, false, null);
-
- NetworkRegistrationInfo voiceReg = new NetworkRegistrationInfo(
- NetworkRegistrationInfo.DOMAIN_CS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
- 0, 16, 0, false, null, cellIdentity, getPlmnFromCellIdentity(cellIdentity),
- false, 0, 0, 0);
-
- sst.mPollingContext[0] = 2;
- // update data reg state to be in oos
- sst.sendMessage(sst.obtainMessage(
- ServiceStateTracker.EVENT_POLL_STATE_PS_CELLULAR_REGISTRATION,
- new AsyncResult(sst.mPollingContext, dataReg, null)));
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
- sst.sendMessage(sst.obtainMessage(
- ServiceStateTracker.EVENT_POLL_STATE_CS_CELLULAR_REGISTRATION,
- new AsyncResult(sst.mPollingContext, voiceReg, null)));
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
- assertTrue(sst.mSS.isEmergencyOnly());
- }
-
// Edge and GPRS are grouped under the same family and Edge has higher rate than GPRS.
// Expect no rat update when move from E to G.
@Test
@@ -2215,15 +2040,37 @@ public class ServiceStateTrackerTest extends TelephonyTest {
}
- private void sendPhyChanConfigChange(int[] bandwidths, int networkType, int pci) {
+ // TODO(nharold): This actually seems like broken behavior; rather than preserve it, we should
+ // probably remove it.
+ // GSM, Edge, GPRS are grouped under the same family where Edge > GPRS > GSM.
+ // Expect no rat update from E to G immediately following cell id change.
+ // Expect ratratchet (from G to E) for the following rat update within the cell location.
+ @Test
+ public void testRatRatchetWithCellChangeBeforeRatChange() throws Exception {
+ // cell ID update
+ CellIdentityGsm cellIdentity =
+ new CellIdentityGsm(0, 1, 900, 5, "001", "01", "test", "tst",
+ Collections.emptyList());
+ changeRegState(1, cellIdentity, 16, 2);
+ assertEquals(ServiceState.STATE_IN_SERVICE, sst.getCurrentDataConnectionState());
+ assertEquals(ServiceState.RIL_RADIO_TECHNOLOGY_EDGE, sst.mSS.getRilDataRadioTechnology());
+
+ // RAT: EDGE -> GPRS, cell ID unchanged. Expect no rat ratchet following cell Id change.
+ changeRegState(1, cellIdentity, 16, 1);
+ assertEquals(ServiceState.RIL_RADIO_TECHNOLOGY_GPRS, sst.mSS.getRilDataRadioTechnology());
+
+ // RAT: GPRS -> EDGE should ratchet.
+ changeRegState(1, cellIdentity, 16, 2);
+ assertEquals(ServiceState.RIL_RADIO_TECHNOLOGY_EDGE, sst.mSS.getRilDataRadioTechnology());
+ }
+
+ private void sendPhyChanConfigChange(int[] bandwidths) {
ArrayList<PhysicalChannelConfig> pc = new ArrayList<>();
int ssType = PhysicalChannelConfig.CONNECTION_PRIMARY_SERVING;
for (int bw : bandwidths) {
pc.add(new PhysicalChannelConfig.Builder()
.setCellConnectionStatus(ssType)
.setCellBandwidthDownlinkKhz(bw)
- .setNetworkType(networkType)
- .setPhysicalCellId(pci)
.build());
// All cells after the first are secondary serving cells.
@@ -2242,7 +2089,7 @@ public class ServiceStateTrackerTest extends TelephonyTest {
NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
NetworkRegistrationInfo.REGISTRATION_STATE_HOME, TelephonyManager.NETWORK_TYPE_LTE,
0, false, null, cellId, getPlmnFromCellIdentity(cellId), 1, false, false, false,
- lteVopsSupportInfo);
+ lteVopsSupportInfo, false);
NetworkRegistrationInfo voiceResult = new NetworkRegistrationInfo(
NetworkRegistrationInfo.DOMAIN_CS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
NetworkRegistrationInfo.REGISTRATION_STATE_HOME, TelephonyManager.NETWORK_TYPE_LTE,
@@ -2259,31 +2106,6 @@ public class ServiceStateTrackerTest extends TelephonyTest {
waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
}
- private void sendRegStateUpdateForNrCellId(CellIdentityNr cellId) {
- LteVopsSupportInfo lteVopsSupportInfo =
- new LteVopsSupportInfo(LteVopsSupportInfo.LTE_STATUS_NOT_AVAILABLE,
- LteVopsSupportInfo.LTE_STATUS_NOT_AVAILABLE);
- NetworkRegistrationInfo dataResult = new NetworkRegistrationInfo(
- NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
- NetworkRegistrationInfo.REGISTRATION_STATE_HOME, TelephonyManager.NETWORK_TYPE_NR,
- 0, false, null, cellId, getPlmnFromCellIdentity(cellId), 1, false, false, false,
- lteVopsSupportInfo);
- NetworkRegistrationInfo voiceResult = new NetworkRegistrationInfo(
- NetworkRegistrationInfo.DOMAIN_CS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
- NetworkRegistrationInfo.REGISTRATION_STATE_HOME, TelephonyManager.NETWORK_TYPE_NR,
- 0, false, null, cellId, getPlmnFromCellIdentity(cellId), false, 0, 0, 0);
- sst.mPollingContext[0] = 2;
- // update data reg state to be in service
- sst.sendMessage(sst.obtainMessage(
- ServiceStateTracker.EVENT_POLL_STATE_PS_CELLULAR_REGISTRATION,
- new AsyncResult(sst.mPollingContext, dataResult, null)));
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
- sst.sendMessage(sst.obtainMessage(
- ServiceStateTracker.EVENT_POLL_STATE_CS_CELLULAR_REGISTRATION,
- new AsyncResult(sst.mPollingContext, voiceResult, null)));
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
- }
-
@Test
public void testPhyChanBandwidthUpdatedOnDataRegState() throws Exception {
// Cell ID change should trigger hasLocationChanged.
@@ -2291,7 +2113,7 @@ public class ServiceStateTrackerTest extends TelephonyTest {
new CellIdentityLte(1, 1, 5, 1, new int[] {1, 2}, 5000, "001", "01", "test",
"tst", Collections.emptyList(), null);
- sendPhyChanConfigChange(new int[] {10000}, TelephonyManager.NETWORK_TYPE_LTE, 1);
+ sendPhyChanConfigChange(new int[] {10000});
sendRegStateUpdateForLteCellId(cellIdentity5);
assertTrue(Arrays.equals(new int[] {5000}, sst.mSS.getCellBandwidths()));
}
@@ -2303,7 +2125,7 @@ public class ServiceStateTrackerTest extends TelephonyTest {
new CellIdentityLte(1, 1, 5, 1, new int[] {1, 2}, 12345, "001", "01", "test",
"tst", Collections.emptyList(), null);
- sendPhyChanConfigChange(new int[] {10000}, TelephonyManager.NETWORK_TYPE_LTE, 1);
+ sendPhyChanConfigChange(new int[] {10000});
sendRegStateUpdateForLteCellId(cellIdentityInv);
assertTrue(Arrays.equals(new int[] {10000}, sst.mSS.getCellBandwidths()));
}
@@ -2315,7 +2137,7 @@ public class ServiceStateTrackerTest extends TelephonyTest {
new CellIdentityLte(1, 1, 5, 1, new int[] {1, 2}, 10000, "001", "01", "test",
"tst", Collections.emptyList(), null);
- sendPhyChanConfigChange(new int[] {10000, 5000}, TelephonyManager.NETWORK_TYPE_LTE, 1);
+ sendPhyChanConfigChange(new int[] {10000, 5000});
sendRegStateUpdateForLteCellId(cellIdentity10);
assertTrue(Arrays.equals(new int[] {10000, 5000}, sst.mSS.getCellBandwidths()));
}
@@ -2329,7 +2151,7 @@ public class ServiceStateTrackerTest extends TelephonyTest {
sendRegStateUpdateForLteCellId(cellIdentity10);
assertTrue(Arrays.equals(new int[] {10000}, sst.mSS.getCellBandwidths()));
- sendPhyChanConfigChange(new int[] {10000, 5000}, TelephonyManager.NETWORK_TYPE_LTE, 1);
+ sendPhyChanConfigChange(new int[] {10000, 5000});
assertTrue(Arrays.equals(new int[] {10000, 5000}, sst.mSS.getCellBandwidths()));
}
@@ -2343,7 +2165,7 @@ public class ServiceStateTrackerTest extends TelephonyTest {
NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING,
TelephonyManager.NETWORK_TYPE_UNKNOWN, 0, false, null, null, "", 1, false, false,
- false, lteVopsSupportInfo);
+ false, lteVopsSupportInfo, false);
NetworkRegistrationInfo voiceResult = new NetworkRegistrationInfo(
NetworkRegistrationInfo.DOMAIN_CS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING,
@@ -2360,17 +2182,6 @@ public class ServiceStateTrackerTest extends TelephonyTest {
assertTrue(Arrays.equals(new int[0], sst.mSS.getCellBandwidths()));
}
- @Test
- public void testPhyChanBandwidthForNr() {
- // NR Cell with bandwidth = 10000
- CellIdentityNr nrCi = new CellIdentityNr(
- 0, 0, 0, new int[] {}, "", "", 5, "", "", Collections.emptyList());
-
- sendPhyChanConfigChange(new int[] {10000, 5000}, TelephonyManager.NETWORK_TYPE_NR, 0);
- sendRegStateUpdateForNrCellId(nrCi);
- assertTrue(Arrays.equals(new int[] {10000, 5000}, sst.mSS.getCellBandwidths()));
- }
-
/**
* Ensure that TransportManager changes due to transport preference changes are picked up in the
* new ServiceState when a poll event occurs. This causes ServiceState#getRilDataRadioTechnology
@@ -2532,7 +2343,7 @@ public class ServiceStateTrackerTest extends TelephonyTest {
@Test
@SmallTest
- public void testOnLteVopsInfoChanged() {
+ public void testOnVopsInfoChanged() {
ServiceState ss = new ServiceState();
ss.setVoiceRegState(ServiceState.STATE_IN_SERVICE);
ss.setDataRegState(ServiceState.STATE_IN_SERVICE);
@@ -2548,7 +2359,7 @@ public class ServiceStateTrackerTest extends TelephonyTest {
NetworkRegistrationInfo dataResult = new NetworkRegistrationInfo(
NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
NetworkRegistrationInfo.REGISTRATION_STATE_HOME, TelephonyManager.NETWORK_TYPE_LTE,
- 0, false, null, cellId, "00101", 1, false, false, false, lteVopsSupportInfo);
+ 0, false, null, cellId, "00101", 1, false, false, false, lteVopsSupportInfo, false);
sst.mPollingContext[0] = 2;
sst.sendMessage(sst.obtainMessage(
@@ -2578,7 +2389,7 @@ public class ServiceStateTrackerTest extends TelephonyTest {
AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
NetworkRegistrationInfo.REGISTRATION_STATE_HOME,
TelephonyManager.NETWORK_TYPE_LTE, 0, false, null, cellId, "00101",
- 1, false, false, false, lteVopsSupportInfo);
+ 1, false, false, false, lteVopsSupportInfo, false);
sst.mPollingContext[0] = 1;
sst.sendMessage(sst.obtainMessage(
ServiceStateTracker.EVENT_POLL_STATE_PS_CELLULAR_REGISTRATION,
@@ -2593,70 +2404,6 @@ public class ServiceStateTrackerTest extends TelephonyTest {
@Test
@SmallTest
- public void testOnNrVopsInfoChanged() {
- ServiceState ss = new ServiceState();
- ss.setVoiceRegState(ServiceState.STATE_IN_SERVICE);
- ss.setDataRegState(ServiceState.STATE_IN_SERVICE);
- sst.mSS = ss;
-
- CellIdentityLte cellId =
- new CellIdentityLte(1, 1, 5, 1, new int[] {1, 2}, 5000, "001", "01", "test",
- "tst", Collections.emptyList(), null);
- NrVopsSupportInfo nrVopsSupportInfo = new NrVopsSupportInfo(
- NrVopsSupportInfo.NR_STATUS_VOPS_NOT_SUPPORTED,
- NrVopsSupportInfo.NR_STATUS_EMC_NOT_SUPPORTED,
- NrVopsSupportInfo.NR_STATUS_EMF_NOT_SUPPORTED);
-
- NetworkRegistrationInfo dataResult = new NetworkRegistrationInfo(
- NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
- NetworkRegistrationInfo.REGISTRATION_STATE_HOME, TelephonyManager.NETWORK_TYPE_NR,
- 0, false, null, cellId, "00101", 1, false, false, false, nrVopsSupportInfo);
- sst.mPollingContext[0] = 2;
-
- sst.sendMessage(sst.obtainMessage(
- ServiceStateTracker.EVENT_POLL_STATE_PS_CELLULAR_REGISTRATION,
- new AsyncResult(sst.mPollingContext, dataResult, null)));
- NetworkRegistrationInfo voiceResult = new NetworkRegistrationInfo(
- NetworkRegistrationInfo.DOMAIN_CS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
- NetworkRegistrationInfo.REGISTRATION_STATE_HOME,
- TelephonyManager.NETWORK_TYPE_NR, 0,
- false, null, cellId, "00101", false, 0, 0, 0);
- sst.sendMessage(sst.obtainMessage(
- ServiceStateTracker.EVENT_POLL_STATE_CS_CELLULAR_REGISTRATION,
- new AsyncResult(sst.mPollingContext, voiceResult, null)));
-
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
- assertEquals(ServiceState.STATE_IN_SERVICE, sst.getCurrentDataConnectionState());
- NetworkRegistrationInfo sSnetworkRegistrationInfo =
- sst.mSS.getNetworkRegistrationInfo(NetworkRegistrationInfo.DOMAIN_PS,
- AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
- assertEquals(nrVopsSupportInfo,
- sSnetworkRegistrationInfo.getDataSpecificInfo().getVopsSupportInfo());
-
- nrVopsSupportInfo = new NrVopsSupportInfo(
- NrVopsSupportInfo.NR_STATUS_VOPS_3GPP_SUPPORTED,
- NrVopsSupportInfo.NR_STATUS_EMC_5GCN_ONLY,
- NrVopsSupportInfo.NR_STATUS_EMF_5GCN_ONLY);
- dataResult = new NetworkRegistrationInfo(NetworkRegistrationInfo.DOMAIN_PS,
- AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
- NetworkRegistrationInfo.REGISTRATION_STATE_HOME,
- TelephonyManager.NETWORK_TYPE_NR, 0, false, null, cellId, "00101",
- 1, false, false, false, nrVopsSupportInfo);
- sst.mPollingContext[0] = 1;
- sst.sendMessage(sst.obtainMessage(
- ServiceStateTracker.EVENT_POLL_STATE_PS_CELLULAR_REGISTRATION,
- new AsyncResult(sst.mPollingContext, dataResult, null)));
- waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
-
- sSnetworkRegistrationInfo =
- sst.mSS.getNetworkRegistrationInfo(2, 1);
- assertEquals(nrVopsSupportInfo,
- sSnetworkRegistrationInfo.getDataSpecificInfo().getVopsSupportInfo());
- }
-
-
- @Test
- @SmallTest
public void testEriLoading() {
sst.obtainMessage(GsmCdmaPhone.EVENT_CARRIER_CONFIG_CHANGED, null).sendToTarget();
waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
@@ -2673,7 +2420,7 @@ public class ServiceStateTrackerTest extends TelephonyTest {
ss.setVoiceRegState(ServiceState.STATE_EMERGENCY_ONLY);
ss.setDataRegState(ServiceState.STATE_OUT_OF_SERVICE);
ss.setEmergencyOnly(true);
- sst.mSS = ss;
+ doReturn(ss).when(mSST).getServiceState();
// update the spn
sst.updateSpnDisplay();
@@ -2695,7 +2442,7 @@ public class ServiceStateTrackerTest extends TelephonyTest {
ss.setVoiceRegState(ServiceState.STATE_OUT_OF_SERVICE);
ss.setDataRegState(ServiceState.STATE_OUT_OF_SERVICE);
ss.setEmergencyOnly(false);
- sst.mSS = ss;
+ doReturn(ss).when(mSST).getServiceState();
// update the spn
sst.updateSpnDisplay();
@@ -2708,7 +2455,7 @@ public class ServiceStateTrackerTest extends TelephonyTest {
}
@Test
- public void testUpdateSpnDisplay_flightMode_displayNull() {
+ public void testUpdateSpnDisplay_flightMode_displayOOS() {
// GSM phone
doReturn(true).when(mPhone).isPhoneTypeGsm();
@@ -2716,80 +2463,19 @@ public class ServiceStateTrackerTest extends TelephonyTest {
ServiceState ss = new ServiceState();
ss.setVoiceRegState(ServiceState.STATE_POWER_OFF);
ss.setDataRegState(ServiceState.STATE_POWER_OFF);
- sst.mSS = ss;
+ doReturn(ss).when(mSST).getServiceState();
// update the spn
sst.updateSpnDisplay();
- // Plmn should be shown, and the string is null
- Bundle b = getExtrasFromLastSpnUpdateIntent();
- assertThat(b.getString(TelephonyManager.EXTRA_PLMN)).isEqualTo(null);
- assertThat(b.getBoolean(TelephonyManager.EXTRA_SHOW_PLMN)).isTrue();
- }
-
- @Test
- public void testUpdateSpnDisplay_flightModeNoWifiCalling_showSpnAndPlmn() {
- // GSM phone
- doReturn(true).when(mPhone).isPhoneTypeGsm();
-
- // Flight mode and connected to WiFI
- doReturn(ServiceState.STATE_POWER_OFF).when(mServiceState).getVoiceRegState();
- doReturn(ServiceState.STATE_POWER_OFF).when(mServiceState).getDataRegState();
- doReturn(TelephonyManager.NETWORK_TYPE_IWLAN).when(mServiceState).getDataNetworkType();
- sst.mSS = mServiceState;
-
- // wifi-calling is disable
- doReturn(false).when(mPhone).isWifiCallingEnabled();
-
- // update the spn
- sst.updateSpnDisplay();
-
- // Show both spn & plmn
- String spn = mBundle.getString(CarrierConfigManager.KEY_CARRIER_NAME_STRING);
- String plmn = mBundle.getStringArray(CarrierConfigManager.KEY_PNN_OVERRIDE_STRING_ARRAY)[0];
- plmn = plmn.split("\\s*,\\s*")[0];
+ // Plmn should be shown, and the string is "No service"
Bundle b = getExtrasFromLastSpnUpdateIntent();
- assertThat(b.getString(TelephonyManager.EXTRA_SPN)).isEqualTo(spn);
- assertThat(b.getBoolean(TelephonyManager.EXTRA_SHOW_SPN)).isTrue();
- assertThat(b.getString(TelephonyManager.EXTRA_PLMN)).isEqualTo(plmn);
+ assertThat(b.getString(TelephonyManager.EXTRA_PLMN))
+ .isEqualTo(CARRIER_NAME_DISPLAY_NO_SERVICE);
assertThat(b.getBoolean(TelephonyManager.EXTRA_SHOW_PLMN)).isTrue();
}
@Test
- public void testUpdateSpnDisplay_spnNotEmptyAndCrossSimCallingEnabled_showSpnOnly() {
- // GSM phone
-
- doReturn(true).when(mPhone).isPhoneTypeGsm();
-
- // In Service
- ServiceState ss = new ServiceState();
- ss.setVoiceRegState(ServiceState.STATE_IN_SERVICE);
- ss.setDataRegState(ServiceState.STATE_IN_SERVICE);
- sst.mSS = ss;
-
- // cross-sim-calling is enable
- doReturn(mImsPhone).when(mPhone).getImsPhone();
- doReturn(ImsRegistrationImplBase.REGISTRATION_TECH_CROSS_SIM).when(mImsPhone)
- .getImsRegistrationTech();
- String[] formats = {CROSS_SIM_CALLING_VOICE_FORMAT, "%s"};
- Resources r = mContext.getResources();
- doReturn(formats).when(r).getStringArray(anyInt());
-
- // update the spn
- sst.updateSpnDisplay();
-
- // Only spn should be shown
- String spn = mBundle.getString(CarrierConfigManager.KEY_CARRIER_NAME_STRING);
- Bundle b = getExtrasFromLastSpnUpdateIntent();
- assertThat(b.getString(TelephonyManager.EXTRA_SPN))
- .isEqualTo(String.format(CROSS_SIM_CALLING_VOICE_FORMAT, spn));
- assertThat(b.getBoolean(TelephonyManager.EXTRA_SHOW_SPN)).isTrue();
- assertThat(b.getString(TelephonyManager.EXTRA_DATA_SPN))
- .isEqualTo(String.format(CROSS_SIM_CALLING_VOICE_FORMAT, spn));
- assertThat(b.getBoolean(TelephonyManager.EXTRA_SHOW_PLMN)).isFalse();
- }
-
- @Test
public void testUpdateSpnDisplay_spnNotEmptyAndWifiCallingEnabled_showSpnOnly() {
// GSM phone
doReturn(true).when(mPhone).isPhoneTypeGsm();
@@ -2878,7 +2564,7 @@ public class ServiceStateTrackerTest extends TelephonyTest {
@Test
public void testShouldForceDisplayNoService_forceBasedOnLocale() {
// set up unaffected locale (US) and clear the resource
- doReturn("us").when(mLocaleTracker).getLastKnownCountryIso();
+ doReturn("us").when(mLocaleTracker).getCurrentCountry();
mContextFixture.putStringArrayResource(
com.android.internal.R.array.config_display_no_service_when_sim_unready,
new String[0]);
@@ -2888,11 +2574,11 @@ public class ServiceStateTrackerTest extends TelephonyTest {
mContextFixture.putStringArrayResource(
com.android.internal.R.array.config_display_no_service_when_sim_unready,
new String[]{"de"});
- doReturn("us").when(mLocaleTracker).getLastKnownCountryIso();
+ doReturn("us").when(mLocaleTracker).getCurrentCountry();
assertFalse(sst.shouldForceDisplayNoService());
// mock the locale to Germany
- doReturn("de").when(mLocaleTracker).getLastKnownCountryIso();
+ doReturn("de").when(mLocaleTracker).getCurrentCountry();
assertTrue(sst.shouldForceDisplayNoService());
}
@@ -3006,69 +2692,4 @@ public class ServiceStateTrackerTest extends TelephonyTest {
assertEquals(cids.get(0), cellIdentityLte);
assertEquals(cids.get(1), cellIdentityGsm);
}
-
- @Test
- public void testGetCidFromCellIdentity() throws Exception {
- CellIdentity gsmCi = new CellIdentityGsm(
- 0, 1, 0, 0, "", "", "", "", Collections.emptyList());
- CellIdentity wcdmaCi = new CellIdentityWcdma(
- 0, 2, 0, 0, "", "", "", "", Collections.emptyList(), null);
- CellIdentity tdscdmaCi = new CellIdentityTdscdma(
- "", "", 0, 3, 0, 0, "", "", Collections.emptyList(), null);
- CellIdentity lteCi = new CellIdentityLte(0, 0, 4, 0, 0);
- CellIdentity nrCi = new CellIdentityNr(
- 0, 0, 0, new int[] {}, "", "", 5, "", "", Collections.emptyList());
-
- Method method = ServiceStateTracker.class.getDeclaredMethod(
- "getCidFromCellIdentity", CellIdentity.class);
- method.setAccessible(true);
- assertEquals(1, (long) method.invoke(mSST, gsmCi));
- assertEquals(2, (long) method.invoke(mSST, wcdmaCi));
- assertEquals(3, (long) method.invoke(mSST, tdscdmaCi));
- assertEquals(4, (long) method.invoke(mSST, lteCi));
- assertEquals(5, (long) method.invoke(mSST, nrCi));
- }
-
- @Test
- public void testGetCombinedRegState() {
- doReturn(mImsPhone).when(mPhone).getImsPhone();
-
- // If voice/data out of service, return out of service.
- doReturn(ServiceState.STATE_OUT_OF_SERVICE).when(mServiceState).getState();
- doReturn(ServiceState.STATE_OUT_OF_SERVICE).when(mServiceState).getDataRegistrationState();
- assertEquals(ServiceState.STATE_OUT_OF_SERVICE, sst.getCombinedRegState(mServiceState));
-
- // If voice is emergency only, return emergency only
- doReturn(ServiceState.STATE_EMERGENCY_ONLY).when(mServiceState).getState();
- assertEquals(ServiceState.STATE_EMERGENCY_ONLY, sst.getCombinedRegState(mServiceState));
-
- // If data in service, return in service.
- doReturn(ServiceState.STATE_OUT_OF_SERVICE).when(mServiceState).getState();
- doReturn(ServiceState.STATE_IN_SERVICE).when(mServiceState).getDataRegistrationState();
- assertEquals(ServiceState.STATE_IN_SERVICE, sst.getCombinedRegState(mServiceState));
-
- // Check emergency
- doReturn(ServiceState.STATE_EMERGENCY_ONLY).when(mServiceState).getState();
- assertEquals(ServiceState.STATE_EMERGENCY_ONLY, sst.getCombinedRegState(mServiceState));
-
- // If data in service and network is IWLAN but WiFi calling is off, return out of service.
- doReturn(ServiceState.STATE_OUT_OF_SERVICE).when(mServiceState).getState();
- doReturn(TelephonyManager.NETWORK_TYPE_IWLAN).when(mServiceState).getDataNetworkType();
- doReturn(false).when(mImsPhone).isWifiCallingEnabled();
- assertEquals(ServiceState.STATE_OUT_OF_SERVICE, sst.getCombinedRegState(mServiceState));
-
- // Check emrgency
- doReturn(ServiceState.STATE_EMERGENCY_ONLY).when(mServiceState).getState();
- assertEquals(ServiceState.STATE_EMERGENCY_ONLY, sst.getCombinedRegState(mServiceState));
-
- // If data in service and network is IWLAN and WiFi calling is on, return in service.
- doReturn(ServiceState.STATE_OUT_OF_SERVICE).when(mServiceState).getState();
- doReturn(TelephonyManager.NETWORK_TYPE_IWLAN).when(mServiceState).getDataNetworkType();
- doReturn(true).when(mImsPhone).isWifiCallingEnabled();
- assertEquals(ServiceState.STATE_IN_SERVICE, sst.getCombinedRegState(mServiceState));
-
- // Check emergency
- doReturn(ServiceState.STATE_EMERGENCY_ONLY).when(mServiceState).getState();
- assertEquals(ServiceState.STATE_EMERGENCY_ONLY, sst.getCombinedRegState(mServiceState));
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/SignalStrengthTest.java b/tests/telephonytests/src/com/android/internal/telephony/SignalStrengthTest.java
index f15845cd42..589d6b61a3 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/SignalStrengthTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/SignalStrengthTest.java
@@ -38,8 +38,6 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.util.ArrayList;
-import java.util.Arrays;
import java.util.List;
/** Unit tests for {@link IpSecConfig}. */
@@ -90,15 +88,13 @@ public class SignalStrengthTest {
public void testParcelUnparcel() throws Exception {
assertParcelingIsLossless(new SignalStrength());
- ArrayList<Byte> NrCqiReport = new ArrayList<>(
- Arrays.asList((byte) 3, (byte) 2 , (byte) 1));
SignalStrength s = new SignalStrength(
new CellSignalStrengthCdma(-93, -132, -89, -125, 5),
new CellSignalStrengthGsm(-79, 2, 5),
new CellSignalStrengthWcdma(-94, 4, -102, -5),
new CellSignalStrengthTdscdma(-95, 2, -103),
- new CellSignalStrengthLte(-85, -91, -6, -10, 1, 12, 1),
- new CellSignalStrengthNr(-91, -6, 3, 1, NrCqiReport, -80, -7, 4));
+ new CellSignalStrengthLte(-85, -91, -6, -10, 12, 1),
+ new CellSignalStrengthNr(-91, -6, 3, -80, -7, 4));
assertParcelingIsLossless(s);
PersistableBundle bundle = new PersistableBundle();
@@ -129,7 +125,7 @@ public class SignalStrengthTest {
@Test
public void testGetCellSignalStrengths() throws Exception {
- CellSignalStrengthLte lte = new CellSignalStrengthLte(-85, -91, -6, -10, 1, 12, 1);
+ CellSignalStrengthLte lte = new CellSignalStrengthLte(-85, -91, -6, -10, 12, 1);
CellSignalStrengthGsm gsm = new CellSignalStrengthGsm(-79, 2, 5);
CellSignalStrengthCdma cdma = new CellSignalStrengthCdma(-93, -132, -89, -125, 5);
CellSignalStrengthWcdma wcdma = new CellSignalStrengthWcdma(-94, 4, -102, -5);
@@ -170,7 +166,6 @@ public class SignalStrengthTest {
lteRsrp, // rsrp
lteRsrq, // rsrq
-25, // rssnr
- CellInfo.UNAVAILABLE, // cqiTableIndex
CellInfo.UNAVAILABLE, // cqi
CellInfo.UNAVAILABLE); // timingAdvance
@@ -203,7 +198,6 @@ public class SignalStrengthTest {
lteRsrp, // rsrp
15, // rsrq
lteRssnr, // rssnr
- CellInfo.UNAVAILABLE, // cqiTableIndex
CellInfo.UNAVAILABLE, // cqi
CellInfo.UNAVAILABLE); // timingAdvance
diff --git a/tests/telephonytests/src/com/android/internal/telephony/SignalStrengthUpdateRequestTest.java b/tests/telephonytests/src/com/android/internal/telephony/SignalStrengthUpdateRequestTest.java
deleted file mode 100644
index 9c29eda557..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/SignalStrengthUpdateRequestTest.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.internal.telephony;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.os.Parcel;
-import android.telephony.AccessNetworkConstants;
-import android.telephony.SignalStrengthUpdateRequest;
-import android.telephony.SignalThresholdInfo;
-
-import androidx.test.filters.SmallTest;
-
-import junit.framework.TestCase;
-
-import org.junit.Test;
-
-import java.util.Collection;
-import java.util.List;
-
-public class SignalStrengthUpdateRequestTest extends TestCase {
-
- private SignalThresholdInfo mRssiInfo = new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.GERAN)
- .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI)
- .setThresholds(new int[]{-109, -103, -97, -89})
- .build();
-
- private SignalThresholdInfo mRscpInfo = new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.UTRAN)
- .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSCP)
- .setThresholds(new int[]{-115, -105, -95, -85})
- .build();
-
- @Test
- @SmallTest
- public void testPublicConstructorWithInvalidParam() {
- // null Collection
- validateBuilderWithInvalidParam(null);
-
- // duplication of SignalMeasurementType in Collection
- validateBuilderWithInvalidParam(List.of(mRssiInfo, mRssiInfo));
-
- // The following two cases can not turn on until the implement is ready:
- // empty Collections
- // validateBuilderWithInvalidParam(List.of());
- }
-
- @Test
- @SmallTest
- public void testPublicConstructorWithValidParam() {
- Collection<SignalThresholdInfo> infos = List.of(mRssiInfo, mRscpInfo);
- SignalStrengthUpdateRequest request = new SignalStrengthUpdateRequest.Builder()
- .setSignalThresholdInfos(infos).setReportingRequestedWhileIdle(false).build();
- assertFalse(request.isReportingRequestedWhileIdle());
- assertFalse(request.isSystemThresholdReportingRequestedWhileIdle());
- assertEquals(infos, request.getSignalThresholdInfos());
- }
-
- @Test
- @SmallTest
- public void testParcel() {
- Collection<SignalThresholdInfo> infos = List.of(mRssiInfo, mRscpInfo);
- SignalStrengthUpdateRequest request = new SignalStrengthUpdateRequest.Builder()
- .setSignalThresholdInfos(infos).setReportingRequestedWhileIdle(true).build();
-
- Parcel p = Parcel.obtain();
- request.writeToParcel(p, 0);
- p.setDataPosition(0);
-
- SignalStrengthUpdateRequest newRequest =
- SignalStrengthUpdateRequest.CREATOR.createFromParcel(p);
- assertThat(newRequest).isEqualTo(request);
- }
-
- @Test
- @SmallTest
- public void testEquals() {
- Collection<SignalThresholdInfo> infos1 = List.of(mRssiInfo, mRscpInfo);
- SignalStrengthUpdateRequest request1 = new SignalStrengthUpdateRequest.Builder()
- .setSignalThresholdInfos(infos1).setReportingRequestedWhileIdle(false).build();
-
- assertTrue(request1.equals(request1));
-
- // Ordering does not matter
- Collection<SignalThresholdInfo> infos2 = List.of(mRscpInfo, mRssiInfo);
- SignalStrengthUpdateRequest request2 = new SignalStrengthUpdateRequest.Builder()
- .setSignalThresholdInfos(infos2).setReportingRequestedWhileIdle(false).build();
- assertTrue(request1.equals(request2));
-
- SignalStrengthUpdateRequest request3 = new SignalStrengthUpdateRequest.Builder()
- .setSignalThresholdInfos(infos1).setReportingRequestedWhileIdle(true).build();
- assertFalse(request1.equals(request3));
-
- SignalStrengthUpdateRequest request4 = new SignalStrengthUpdateRequest.Builder()
- .setSignalThresholdInfos(infos1).setReportingRequestedWhileIdle(false)
- .setSystemThresholdReportingRequestedWhileIdle(true).build();
-
- // return false if the object is not SignalStrengthUpdateRequest
- assertFalse(request1.equals("test"));
- }
-
- private void validateBuilderWithInvalidParam(Collection<SignalThresholdInfo> infos) {
- try {
- new SignalStrengthUpdateRequest.Builder()
- .setSignalThresholdInfos(infos).setReportingRequestedWhileIdle(false).build();
- fail("Exception expected");
- } catch (IllegalArgumentException | NullPointerException expected) {
- }
- }
-}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/SignalThresholdInfoTest.java b/tests/telephonytests/src/com/android/internal/telephony/SignalThresholdInfoTest.java
index b282c55cbf..ddf5bcdaea 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/SignalThresholdInfoTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/SignalThresholdInfoTest.java
@@ -21,7 +21,6 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import android.os.Parcel;
-import android.telephony.AccessNetworkConstants;
import android.telephony.SignalThresholdInfo;
import androidx.test.filters.SmallTest;
@@ -34,94 +33,32 @@ import org.junit.runners.JUnit4;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
@RunWith(JUnit4.class)
public class SignalThresholdInfoTest extends TestCase {
private static final int HYSTERESIS_DB = 2;
private static final int HYSTERESIS_MS = 30;
- private static final int[] SSRSRP_THRESHOLDS = new int[]{-120, -100, -80, -60};
+ private static final int[] SSRSRP_THRESHOLDS = new int[] {-30, 10, 45, 130};
- // Map of SignalMeasurementType to invalid thresholds edge values.
- // Each invalid value will be constructed with a thresholds array to test separately.
- private static final Map<Integer, List<Integer>> INVALID_THRESHOLDS_MAP = Map.of(
- SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI,
- List.of(SignalThresholdInfo.SIGNAL_RSSI_MIN_VALUE - 1,
- SignalThresholdInfo.SIGNAL_RSSI_MAX_VALUE + 1),
- SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSCP,
- List.of(SignalThresholdInfo.SIGNAL_RSCP_MIN_VALUE - 1,
- SignalThresholdInfo.SIGNAL_RSCP_MAX_VALUE + 1),
- SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSRP,
- List.of(SignalThresholdInfo.SIGNAL_RSRP_MIN_VALUE - 1,
- SignalThresholdInfo.SIGNAL_RSRP_MAX_VALUE + 1),
- SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSRQ,
- List.of(SignalThresholdInfo.SIGNAL_RSRQ_MIN_VALUE - 1,
- SignalThresholdInfo.SIGNAL_RSRQ_MAX_VALUE + 1),
- SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSNR,
- List.of(SignalThresholdInfo.SIGNAL_RSSNR_MIN_VALUE - 1,
- SignalThresholdInfo.SIGNAL_RSSNR_MAX_VALUE + 1),
- SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSRSRP,
- List.of(SignalThresholdInfo.SIGNAL_SSRSRP_MIN_VALUE - 1,
- SignalThresholdInfo.SIGNAL_SSRSRP_MAX_VALUE + 1),
- SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSRSRQ,
- List.of(SignalThresholdInfo.SIGNAL_SSRSRQ_MIN_VALUE - 1,
- SignalThresholdInfo.SIGNAL_SSRSRQ_MAX_VALUE + 1),
- SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSSINR,
- List.of(SignalThresholdInfo.SIGNAL_SSSINR_MIN_VALUE - 1,
- SignalThresholdInfo.SIGNAL_SSSINR_MAX_VALUE + 1)
- );
-
- // Map of RAN to allowed SignalMeasurementType set.
- // RAN/TYPE pair will be used to verify the validation of the combo
- private static final Map<Integer, Set<Integer>> VALID_RAN_TO_MEASUREMENT_TYPE_MAP = Map.of(
- AccessNetworkConstants.AccessNetworkType.GERAN,
- Set.of(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI),
- AccessNetworkConstants.AccessNetworkType.CDMA2000,
- Set.of(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI),
- AccessNetworkConstants.AccessNetworkType.UTRAN,
- Set.of(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSCP),
- AccessNetworkConstants.AccessNetworkType.EUTRAN,
- Set.of(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSRP,
- SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSRQ,
- SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSNR),
- AccessNetworkConstants.AccessNetworkType.NGRAN,
- Set.of(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSRSRP,
- SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSRSRQ,
- SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSSINR)
- );
-
- // Deliberately picking up the max/min value in each range to test the edge cases
- private final int[] mRssiThresholds = new int[]{-113, -103, -97, -51};
- private final int[] mRscpThresholds = new int[]{-120, -105, -95, -25};
- private final int[] mRsrpThresholds = new int[]{-140, -118, -108, -44};
- private final int[] mRsrqThresholds = new int[]{-34, -17, -14, 3};
- private final int[] mRssnrThresholds = new int[]{-20, 10, 20, 30};
- private final int[] mSsrsrpThresholds = new int[]{-140, -118, -98, -44};
- private final int[] mSsrsrqThresholds = new int[]{-43, -17, -14, 20};
- private final int[] mSssinrThresholds = new int[]{-23, -16, -10, 40};
-
- private final int[][] mThresholds = {mRssiThresholds, mRscpThresholds, mRsrpThresholds,
- mRsrqThresholds, mRssnrThresholds, mSsrsrpThresholds, mSsrsrqThresholds,
- mSssinrThresholds};
+ private final int[] mRssiThresholds = new int[] {-109, -103, -97, -89};
+ private final int[] mRscpThresholds = new int[] {-115, -105, -95, -85};
+ private final int[] mRsrpThresholds = new int[] {-128, -118, -108, -98};
+ private final int[] mRsrqThresholds = new int[] {-19, -17, -14, -12};
+ private final int[] mRssnrThresholds = new int[] {-30, 10, 45, 130};
+ private final int[][] mThresholds = new int[5][];
@Test
@SmallTest
public void testSignalThresholdInfo() throws Exception {
- SignalThresholdInfo signalThresholdInfo =
- new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.NGRAN)
- .setSignalMeasurementType(
- SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSRSRP)
- .setHysteresisMs(HYSTERESIS_MS)
- .setHysteresisDb(HYSTERESIS_DB)
- .setThresholds(SSRSRP_THRESHOLDS)
- .setIsEnabled(false)
- .build();
-
- assertEquals(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSRSRP,
- signalThresholdInfo.getSignalMeasurementType());
+ SignalThresholdInfo signalThresholdInfo = new SignalThresholdInfo(
+ SignalThresholdInfo.SIGNAL_SSRSRP,
+ HYSTERESIS_MS,
+ HYSTERESIS_DB,
+ SSRSRP_THRESHOLDS,
+ false);
+
+ assertEquals(SignalThresholdInfo.SIGNAL_SSRSRP,
+ signalThresholdInfo.getSignalMeasurement());
assertEquals(HYSTERESIS_MS, signalThresholdInfo.getHysteresisMs());
assertEquals(HYSTERESIS_DB, signalThresholdInfo.getHysteresisDb());
assertEquals(Arrays.toString(SSRSRP_THRESHOLDS), Arrays.toString(
@@ -131,8 +68,9 @@ public class SignalThresholdInfoTest extends TestCase {
@Test
@SmallTest
- public void testBuilderWithAllFields() {
- ArrayList<SignalThresholdInfo> stList = buildSignalThresholdInfoWithAllFields();
+ public void testDefaultThresholdsConstruction() {
+ setThresholds();
+ ArrayList<SignalThresholdInfo> stList = setSignalThresholdInfoConstructor();
int count = 0;
for (SignalThresholdInfo st : stList) {
@@ -144,7 +82,7 @@ public class SignalThresholdInfoTest extends TestCase {
@Test
@SmallTest
public void testDefaultThresholdsParcel() {
- ArrayList<SignalThresholdInfo> stList = buildSignalThresholdInfoWithAllFields();
+ ArrayList<SignalThresholdInfo> stList = setSignalThresholdInfoConstructor();
for (SignalThresholdInfo st : stList) {
Parcel p = Parcel.obtain();
@@ -160,275 +98,58 @@ public class SignalThresholdInfoTest extends TestCase {
@SmallTest
public void testGetSignalThresholdInfo() {
ArrayList<SignalThresholdInfo> stList = new ArrayList<>();
- stList.add(new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.GERAN)
- .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI)
- .setHysteresisMs(0)
- .setHysteresisDb(0)
- .setThresholds(new int[]{}, true /*isSystem*/)
- .setIsEnabled(false)
- .build());
- stList.add(new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.GERAN)
- .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI)
- .setHysteresisMs(HYSTERESIS_MS).setHysteresisDb(HYSTERESIS_DB)
- .setThresholds(mRssiThresholds)
- .setIsEnabled(false)
- .build());
+ stList.add(new SignalThresholdInfo(0, 0, 0, null, false));
+ stList.add(new SignalThresholdInfo(SignalThresholdInfo.SIGNAL_RSSI, HYSTERESIS_MS,
+ HYSTERESIS_DB, mRssiThresholds, false));
- assertThat(stList.get(0).getThresholds()).isEqualTo(new int[]{});
- assertThat(stList.get(1).getSignalMeasurementType()).isEqualTo(
- SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI);
+ assertThat(stList.get(0).getThresholds()).isEqualTo(null);
+ assertThat(stList.get(1).getSignalMeasurement()).isEqualTo(SignalThresholdInfo.SIGNAL_RSSI);
assertThat(stList.get(1).getThresholds()).isEqualTo(mRssiThresholds);
}
@Test
@SmallTest
public void testEqualsSignalThresholdInfo() {
- final int[] dummyThresholds = new int[]{-100, -90, -70, -60};
- final int[] dummyThreholdsDisordered = new int[]{-60, -90, -100, -70};
- SignalThresholdInfo st1 = new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(1).setSignalMeasurementType(1)
- .setHysteresisMs(HYSTERESIS_MS).setHysteresisDb(HYSTERESIS_DB)
- .setThresholds(mRssiThresholds).setIsEnabled(false)
- .build();
- SignalThresholdInfo st2 = new SignalThresholdInfo.Builder().setRadioAccessNetworkType(2)
- .setSignalMeasurementType(2).setHysteresisMs(HYSTERESIS_MS)
- .setHysteresisDb(HYSTERESIS_DB).setThresholds(mRssiThresholds).setIsEnabled(false)
- .build();
- SignalThresholdInfo st3 = new SignalThresholdInfo.Builder().setRadioAccessNetworkType(1)
- .setSignalMeasurementType(1).setHysteresisMs(HYSTERESIS_MS)
- .setHysteresisDb(HYSTERESIS_DB).setThresholds(dummyThresholds).setIsEnabled(false)
- .build();
- SignalThresholdInfo st4 = new SignalThresholdInfo.Builder().setRadioAccessNetworkType(1)
- .setSignalMeasurementType(1).setHysteresisMs(HYSTERESIS_MS)
- .setHysteresisDb(HYSTERESIS_DB).setThresholds(mRssiThresholds).setIsEnabled(false)
- .build();
- SignalThresholdInfo st5 = new SignalThresholdInfo.Builder().setRadioAccessNetworkType(1)
- .setSignalMeasurementType(1).setHysteresisMs(HYSTERESIS_MS)
- .setHysteresisDb(HYSTERESIS_DB).setThresholds(dummyThreholdsDisordered)
- .setIsEnabled(false).build();
+ final int[] dummyThresholds = new int[] {-100, -1, 1, 100};
+ SignalThresholdInfo st1 = new SignalThresholdInfo(1, HYSTERESIS_MS, HYSTERESIS_DB,
+ mRssiThresholds, false);
+ SignalThresholdInfo st2 = new SignalThresholdInfo(2, HYSTERESIS_MS, HYSTERESIS_DB,
+ mRssiThresholds, false);
+ SignalThresholdInfo st3 = new SignalThresholdInfo(1, HYSTERESIS_MS, HYSTERESIS_DB,
+ dummyThresholds, false);
+ SignalThresholdInfo st4 = new SignalThresholdInfo(1, HYSTERESIS_MS, HYSTERESIS_DB,
+ mRssiThresholds, false);
//Return true if all SignalThresholdInfo values match.
assertTrue(st1.equals(st1));
assertFalse(st1.equals(st2));
assertFalse(st1.equals(st3));
assertTrue(st1.equals(st4));
- //Threshold values ordering doesn't matter
- assertTrue(st3.equals(st5));
//Return false if the object of argument is other than SignalThresholdInfo.
assertFalse(st1.equals(new String("test")));
}
- @Test
- @SmallTest
- public void testBuilderWithValidParameters() {
- ArrayList<SignalThresholdInfo> stList = buildSignalThresholdInfoWithPublicFields();
-
- for (int i = 0; i < stList.size(); i++) {
- SignalThresholdInfo st = stList.get(i);
- assertThat(st.getThresholds()).isEqualTo(mThresholds[i]);
- assertThat(st.getHysteresisMs()).isEqualTo(SignalThresholdInfo.HYSTERESIS_MS_DISABLED);
- assertThat(st.getHysteresisDb()).isEqualTo(SignalThresholdInfo.HYSTERESIS_DB_DISABLED);
- assertFalse(st.isEnabled());
- }
- }
-
- @Test
- @SmallTest
- public void testBuilderWithInvalidParameter() {
- // Invalid signal measurement type
- int[] invalidSignalMeasurementTypes = new int[]{-1, 0, 9};
- for (int signalMeasurementType : invalidSignalMeasurementTypes) {
- buildWithInvalidParameterThrowException(
- AccessNetworkConstants.AccessNetworkType.GERAN, signalMeasurementType,
- new int[]{-1});
- }
-
- // Null thresholds array
- buildWithInvalidParameterThrowException(AccessNetworkConstants.AccessNetworkType.GERAN,
- SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI, null);
-
- // Empty thresholds
- buildWithInvalidParameterThrowException(AccessNetworkConstants.AccessNetworkType.GERAN,
- SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI, new int[]{});
-
-
- // Too long thresholds array
- buildWithInvalidParameterThrowException(AccessNetworkConstants.AccessNetworkType.GERAN,
- SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI,
- new int[]{-100, -90, -70, -60, -58});
-
- // Thresholds value out of range
- for (int signalMeasurementType : INVALID_THRESHOLDS_MAP.keySet()) {
- List<Integer> invalidThresholds = INVALID_THRESHOLDS_MAP.get(signalMeasurementType);
- for (int threshold : invalidThresholds) {
- buildWithInvalidParameterThrowException(getValidRan(signalMeasurementType),
- signalMeasurementType, new int[]{threshold});
- }
- }
-
- // Invalid RAN/Measurement type combos
- for (int ran : VALID_RAN_TO_MEASUREMENT_TYPE_MAP.keySet()) {
- Set validTypes = VALID_RAN_TO_MEASUREMENT_TYPE_MAP.get(ran);
- for (int type = SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI;
- type <= SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSSINR; type++) {
- if (!validTypes.contains(type)) {
- buildWithInvalidParameterThrowException(ran, type, new int[]{-1});
- }
- }
- }
- }
-
- private void buildWithInvalidParameterThrowException(int ran, int signalMeasurementType,
- int[] thresholds) {
- try {
- new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(ran)
- .setSignalMeasurementType(signalMeasurementType)
- .setThresholds(thresholds)
- .build();
- fail("exception expected");
- } catch (IllegalArgumentException | NullPointerException expected) {
- }
+ private void setThresholds() {
+ mThresholds[0] = mRssiThresholds;
+ mThresholds[1] = mRscpThresholds;
+ mThresholds[2] = mRsrpThresholds;
+ mThresholds[3] = mRsrqThresholds;
+ mThresholds[4] = mRssnrThresholds;
}
- private ArrayList<SignalThresholdInfo> buildSignalThresholdInfoWithAllFields() {
+ private ArrayList<SignalThresholdInfo> setSignalThresholdInfoConstructor() {
ArrayList<SignalThresholdInfo> stList = new ArrayList<>();
-
- stList.add(new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.GERAN)
- .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI)
- .setHysteresisMs(HYSTERESIS_MS).setHysteresisDb(HYSTERESIS_DB)
- .setThresholds(mRssiThresholds).setIsEnabled(false)
- .build());
- stList.add(new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.UTRAN)
- .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSCP)
- .setHysteresisMs(HYSTERESIS_MS)
- .setHysteresisDb(HYSTERESIS_DB)
- .setThresholds(mRscpThresholds)
- .setIsEnabled(false)
- .build());
- stList.add(new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.EUTRAN)
- .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSRP)
- .setHysteresisMs(HYSTERESIS_MS)
- .setHysteresisDb(HYSTERESIS_DB)
- .setThresholds(mRsrpThresholds)
- .setIsEnabled(false)
- .build());
- stList.add(new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.EUTRAN)
- .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSRQ)
- .setHysteresisMs(HYSTERESIS_MS)
- .setHysteresisDb(HYSTERESIS_DB)
- .setThresholds(mRsrqThresholds)
- .setIsEnabled(false)
- .build());
- stList.add(new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.EUTRAN)
- .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSNR)
- .setHysteresisMs(HYSTERESIS_MS)
- .setHysteresisDb(HYSTERESIS_DB)
- .setThresholds(mRssnrThresholds)
- .setIsEnabled(false)
- .build());
- stList.add(new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.NGRAN)
- .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSRSRP)
- .setHysteresisMs(HYSTERESIS_MS)
- .setHysteresisDb(HYSTERESIS_DB)
- .setThresholds(mSsrsrpThresholds)
- .setIsEnabled(false)
- .build());
- stList.add(new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.NGRAN)
- .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSRSRQ)
- .setHysteresisMs(HYSTERESIS_MS)
- .setHysteresisDb(HYSTERESIS_DB)
- .setThresholds(mSsrsrqThresholds)
- .setIsEnabled(false)
- .build());
- stList.add(new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.NGRAN)
- .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSSINR)
- .setHysteresisMs(HYSTERESIS_MS)
- .setHysteresisDb(HYSTERESIS_DB)
- .setThresholds(mSssinrThresholds)
- .setIsEnabled(false)
- .build());
+ stList.add(new SignalThresholdInfo(SignalThresholdInfo.SIGNAL_RSSI, HYSTERESIS_MS,
+ HYSTERESIS_DB, mRssiThresholds, false));
+ stList.add(new SignalThresholdInfo(SignalThresholdInfo.SIGNAL_RSCP, HYSTERESIS_MS,
+ HYSTERESIS_DB, mRscpThresholds, false));
+ stList.add(new SignalThresholdInfo(SignalThresholdInfo.SIGNAL_RSRP, HYSTERESIS_MS,
+ HYSTERESIS_DB, mRsrpThresholds, false));
+ stList.add(new SignalThresholdInfo(SignalThresholdInfo.SIGNAL_RSRQ, HYSTERESIS_MS,
+ HYSTERESIS_DB, mRsrqThresholds, false));
+ stList.add(new SignalThresholdInfo(SignalThresholdInfo.SIGNAL_RSSNR, HYSTERESIS_MS,
+ HYSTERESIS_DB, mRssnrThresholds, false));
return stList;
}
-
- private ArrayList<SignalThresholdInfo> buildSignalThresholdInfoWithPublicFields() {
- ArrayList<SignalThresholdInfo> stList = new ArrayList<>();
-
- stList.add(new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.GERAN)
- .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI)
- .setThresholds(mRssiThresholds)
- .build());
- stList.add(new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.UTRAN)
- .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSCP)
- .setThresholds(mRscpThresholds)
- .build());
- stList.add(new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.EUTRAN)
- .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSRP)
- .setThresholds(mRsrpThresholds)
- .build());
- stList.add(new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.EUTRAN)
- .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSRQ)
- .setThresholds(mRsrqThresholds)
- .build());
- stList.add(new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.EUTRAN)
- .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSNR)
- .setThresholds(mRssnrThresholds)
- .build());
- stList.add(new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.NGRAN)
- .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSRSRP)
- .setThresholds(mSsrsrpThresholds)
- .build());
- stList.add(new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.NGRAN)
- .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSRSRQ)
- .setThresholds(mSsrsrqThresholds)
- .build());
- stList.add(new SignalThresholdInfo.Builder()
- .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.NGRAN)
- .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSSINR)
- .setThresholds(mSssinrThresholds)
- .build());
-
- return stList;
- }
-
- /**
- * Return a possible valid RAN value for the measurement type. This is used to prevent the
- * invalid ran/type causing IllegalArgumentException when testing other invalid input cases.
- */
- private static int getValidRan(@SignalThresholdInfo.SignalMeasurementType int type) {
- switch (type) {
- case SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI:
- return AccessNetworkConstants.AccessNetworkType.GERAN;
- case SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSCP:
- return AccessNetworkConstants.AccessNetworkType.UTRAN;
- case SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSRP:
- case SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSRQ:
- case SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSNR:
- return AccessNetworkConstants.AccessNetworkType.EUTRAN;
- case SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSRSRP:
- case SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSRSRQ:
- case SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSSINR:
- return AccessNetworkConstants.AccessNetworkType.NGRAN;
- default:
- return AccessNetworkConstants.AccessNetworkType.UNKNOWN;
- }
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/SimPhoneBookTest.java b/tests/telephonytests/src/com/android/internal/telephony/SimPhoneBookTest.java
index ea6f19ddae..15e16fbcbf 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/SimPhoneBookTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/SimPhoneBookTest.java
@@ -16,12 +16,9 @@
package com.android.internal.telephony;
-import android.content.ContentValues;
-import android.telephony.SubscriptionManager;
import android.telephony.TelephonyFrameworkInitializer;
import android.test.suitebuilder.annotation.Suppress;
-import com.android.internal.telephony.IccProvider;
import com.android.internal.telephony.uicc.AdnRecord;
import com.android.internal.telephony.uicc.IccConstants;
@@ -41,17 +38,15 @@ public class SimPhoneBookTest extends TestCase {
.get());
assertNotNull(simPhoneBook);
- final int subId = SubscriptionManager.getDefaultSubscriptionId();
- int size[] = simPhoneBook.getAdnRecordsSizeForSubscriber(subId, IccConstants.EF_ADN);
+ int size[] = simPhoneBook.getAdnRecordsSize(IccConstants.EF_ADN);
assertNotNull(size);
assertEquals(3, size.length);
assertEquals(size[0] * size[2], size[1]);
assertTrue(size[2] >= 100);
- List<AdnRecord> adnRecordList =
- simPhoneBook.getAdnRecordsInEfForSubscriber(subId, IccConstants.EF_ADN);
+ List<AdnRecord> adnRecordList = simPhoneBook.getAdnRecordsInEf(IccConstants.EF_ADN);
// do it twice cause the second time shall read from cache only
- adnRecordList = simPhoneBook.getAdnRecordsInEfForSubscriber(subId, IccConstants.EF_ADN);
+ adnRecordList = simPhoneBook.getAdnRecordsInEf(IccConstants.EF_ADN);
assertNotNull(adnRecordList);
// Test for phone book update
@@ -80,66 +75,37 @@ public class SimPhoneBookTest extends TestCase {
String pin2 = null;
// udpate by index
- ContentValues values = new ContentValues();
- values.put(IccProvider.STR_NEW_TAG, firstAdn.getAlphaTag());
- values.put(IccProvider.STR_NEW_NUMBER, firstAdn.getNumber());
- values.put(IccProvider.STR_NEW_EMAILS, "");
- values.put(IccProvider.STR_NEW_ANRS, "");
- boolean success = simPhoneBook.updateAdnRecordsInEfByIndexForSubscriber(subId,
- IccConstants.EF_ADN, values, adnIndex, pin2);
- adnRecordList =
- simPhoneBook.getAdnRecordsInEfForSubscriber(subId, IccConstants.EF_ADN);
- AdnRecord tmpAdn = adnRecordList.get(listIndex);
+ boolean success = simPhoneBook.updateAdnRecordsInEfByIndex(IccConstants.EF_ADN,
+ firstAdn.getAlphaTag(), firstAdn.getNumber(), adnIndex, pin2);
+ adnRecordList = simPhoneBook.getAdnRecordsInEf(IccConstants.EF_ADN);
+ AdnRecord tmpAdn = adnRecordList.get(listIndex);
assertTrue(success);
assertTrue(firstAdn.isEqual(tmpAdn));
// replace by search
- ContentValues values2 = new ContentValues();
- values.put(IccProvider.STR_TAG, firstAdn.getAlphaTag());
- values.put(IccProvider.STR_NUMBER, firstAdn.getNumber());
- values.put(IccProvider.STR_EMAILS, "");
- values.put(IccProvider.STR_ANRS, "");
- values.put(IccProvider.STR_NEW_TAG, secondAdn.getAlphaTag());
- values.put(IccProvider.STR_NEW_NUMBER, secondAdn.getNumber());
- values.put(IccProvider.STR_NEW_EMAILS, "");
- values.put(IccProvider.STR_NEW_ANRS, "");
- success = simPhoneBook.updateAdnRecordsInEfBySearchForSubscriber(subId,
- IccConstants.EF_ADN, values2, pin2);
- adnRecordList =
- simPhoneBook.getAdnRecordsInEfForSubscriber(subId, IccConstants.EF_ADN);
+ success = simPhoneBook.updateAdnRecordsInEfBySearch(IccConstants.EF_ADN,
+ firstAdn.getAlphaTag(), firstAdn.getNumber(),
+ secondAdn.getAlphaTag(), secondAdn.getNumber(), pin2);
+ adnRecordList = simPhoneBook.getAdnRecordsInEf(IccConstants.EF_ADN);
tmpAdn = adnRecordList.get(listIndex);
assertTrue(success);
assertFalse(firstAdn.isEqual(tmpAdn));
assertTrue(secondAdn.isEqual(tmpAdn));
// erase be search
- ContentValues values3 = new ContentValues();
- values.put(IccProvider.STR_TAG, secondAdn.getAlphaTag());
- values.put(IccProvider.STR_NUMBER, secondAdn.getNumber());
- values.put(IccProvider.STR_EMAILS, "");
- values.put(IccProvider.STR_ANRS, "");
- values.put(IccProvider.STR_NEW_TAG, emptyAdn.getAlphaTag());
- values.put(IccProvider.STR_NEW_NUMBER, emptyAdn.getNumber());
- values.put(IccProvider.STR_NEW_EMAILS, "");
- values.put(IccProvider.STR_NEW_ANRS, "");
- success = simPhoneBook.updateAdnRecordsInEfBySearchForSubscriber(subId,
- IccConstants.EF_ADN, values3, pin2);
- adnRecordList =
- simPhoneBook.getAdnRecordsInEfForSubscriber(subId, IccConstants.EF_ADN);
+ success = simPhoneBook.updateAdnRecordsInEfBySearch(IccConstants.EF_ADN,
+ secondAdn.getAlphaTag(), secondAdn.getNumber(),
+ emptyAdn.getAlphaTag(), emptyAdn.getNumber(), pin2);
+ adnRecordList = simPhoneBook.getAdnRecordsInEf(IccConstants.EF_ADN);
tmpAdn = adnRecordList.get(listIndex);
assertTrue(success);
assertTrue(tmpAdn.isEmpty());
// restore the orginial adn
- ContentValues values4 = new ContentValues();
- values.put(IccProvider.STR_NEW_TAG, originalAdn.getAlphaTag());
- values.put(IccProvider.STR_NEW_NUMBER, originalAdn.getNumber());
- values.put(IccProvider.STR_NEW_EMAILS, "");
- values.put(IccProvider.STR_NEW_ANRS, "");
- success = simPhoneBook.updateAdnRecordsInEfByIndexForSubscriber(subId,
- IccConstants.EF_ADN, values4, adnIndex, pin2);
- adnRecordList =
- simPhoneBook.getAdnRecordsInEfForSubscriber(subId, IccConstants.EF_ADN);
+ success = simPhoneBook.updateAdnRecordsInEfByIndex(IccConstants.EF_ADN,
+ originalAdn.getAlphaTag(), originalAdn.getNumber(), adnIndex,
+ pin2);
+ adnRecordList = simPhoneBook.getAdnRecordsInEf(IccConstants.EF_ADN);
tmpAdn = adnRecordList.get(listIndex);
assertTrue(success);
assertTrue(originalAdn.isEqual(tmpAdn));
diff --git a/tests/telephonytests/src/com/android/internal/telephony/SimulatedCommands.java b/tests/telephonytests/src/com/android/internal/telephony/SimulatedCommands.java
index c545cdd43f..967ed49d93 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/SimulatedCommands.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/SimulatedCommands.java
@@ -47,10 +47,9 @@ import android.telephony.ServiceState;
import android.telephony.SignalStrength;
import android.telephony.SignalThresholdInfo;
import android.telephony.TelephonyManager;
+import android.telephony.data.ApnSetting;
import android.telephony.data.DataCallResponse;
import android.telephony.data.DataProfile;
-import android.telephony.data.NetworkSliceInfo;
-import android.telephony.data.TrafficDescriptor;
import android.telephony.emergency.EmergencyNumber;
import com.android.internal.annotations.VisibleForTesting;
@@ -68,9 +67,6 @@ import com.android.internal.telephony.UUSInfo;
import com.android.internal.telephony.cdma.CdmaSmsBroadcastConfigInfo;
import com.android.internal.telephony.gsm.SmsBroadcastConfigInfo;
import com.android.internal.telephony.gsm.SuppServiceNotification;
-import com.android.internal.telephony.uicc.AdnCapacity;
-import com.android.internal.telephony.uicc.ReceivedPhonebookRecords;
-import com.android.internal.telephony.uicc.SimPhonebookRecord;
import com.android.internal.telephony.uicc.IccCardApplicationStatus.PersoSubState;
import com.android.internal.telephony.uicc.IccCardStatus;
import com.android.internal.telephony.uicc.IccIoResult;
@@ -140,8 +136,7 @@ public class SimulatedCommands extends BaseCommands
boolean mSimFdnEnabled;
int mPin2UnlockAttempts;
int mPuk2UnlockAttempts;
- int mPreferredNetworkType;
- int mAllowedNetworkType;
+ int mNetworkType;
String mPin2Code;
boolean mSsnNotifyOn = false;
private int mVoiceRegState = NetworkRegistrationInfo.REGISTRATION_STATE_HOME;
@@ -154,8 +149,6 @@ public class SimulatedCommands extends BaseCommands
public int mDefaultRoamingIndicator;
public int mReasonForDenial;
public int mMaxDataCalls;
- public boolean mSendSetGsmBroadcastConfigResponse = true;
- public boolean mSendGetSmscAddressResponse = true;
private SignalStrength mSignalStrength;
private List<CellInfo> mCellInfoList = null;
@@ -166,9 +159,6 @@ public class SimulatedCommands extends BaseCommands
private IccIoResult mIccIoResultForApduLogicalChannel;
private int mChannelId = IccOpenLogicalChannelResponse.INVALID_CHANNEL;
- private Object mDataRegStateResult;
- private Object mVoiceRegStateResult;
-
int mPausedResponseCount;
ArrayList<Message> mPausedResponses = new ArrayList<Message>();
@@ -1007,17 +997,14 @@ public class SimulatedCommands extends BaseCommands
public void getVoiceRegistrationState(Message result) {
mGetVoiceRegistrationStateCallCount.incrementAndGet();
- Object ret = mVoiceRegStateResult;
- if (ret == null) {
- ret = new VoiceRegStateResult();
- ((VoiceRegStateResult) ret).regState = mVoiceRegState;
- ((VoiceRegStateResult) ret).rat = mVoiceRadioTech;
- ((VoiceRegStateResult) ret).cssSupported = mCssSupported;
- ((VoiceRegStateResult) ret).roamingIndicator = mRoamingIndicator;
- ((VoiceRegStateResult) ret).systemIsInPrl = mSystemIsInPrl;
- ((VoiceRegStateResult) ret).defaultRoamingIndicator = mDefaultRoamingIndicator;
- ((VoiceRegStateResult) ret).reasonForDenial = mReasonForDenial;
- }
+ VoiceRegStateResult ret = new VoiceRegStateResult();
+ ret.regState = mVoiceRegState;
+ ret.rat = mVoiceRadioTech;
+ ret.cssSupported = mCssSupported;
+ ret.roamingIndicator = mRoamingIndicator;
+ ret.systemIsInPrl = mSystemIsInPrl;
+ ret.defaultRoamingIndicator = mDefaultRoamingIndicator;
+ ret.reasonForDenial = mReasonForDenial;
resultSuccess(result, ret);
}
@@ -1038,17 +1025,14 @@ public class SimulatedCommands extends BaseCommands
}
@Override
- public void getDataRegistrationState(Message result) {
+ public void getDataRegistrationState (Message result) {
mGetDataRegistrationStateCallCount.incrementAndGet();
- Object ret = mDataRegStateResult;
- if (ret == null) {
- ret = new DataRegStateResult();
- ((DataRegStateResult) ret).regState = mDataRegState;
- ((DataRegStateResult) ret).rat = mDataRadioTech;
- ((DataRegStateResult) ret).maxDataCalls = mMaxDataCalls;
- ((DataRegStateResult) ret).reasonDataDenied = mReasonForDenial;
- }
+ DataRegStateResult ret = new DataRegStateResult();
+ ret.regState = mDataRegState;
+ ret.rat = mDataRadioTech;
+ ret.maxDataCalls = mMaxDataCalls;
+ ret.reasonDataDenied = mReasonForDenial;
resultSuccess(result, ret);
}
@@ -1149,8 +1133,7 @@ public class SimulatedCommands extends BaseCommands
*/
@Override
public void sendSMSExpectMore (String smscPDU, String pdu, Message result) {
- SimulatedCommandsVerifier.getInstance().sendSMSExpectMore(smscPDU, pdu, result);
- resultSuccess(result, new SmsResponse(0 /*messageRef*/, null, SmsResponse.NO_ERROR_CODE));
+ unimplemented(result);
}
@Override
@@ -1191,13 +1174,11 @@ public class SimulatedCommands extends BaseCommands
@Override
public void setupDataCall(int accessNetworkType, DataProfile dataProfile, boolean isRoaming,
- boolean allowRoaming, int reason, LinkProperties linkProperties, int pduSessionId,
- NetworkSliceInfo sliceInfo, TrafficDescriptor trafficDescriptor,
- boolean matchAllRuleAllowed, Message result) {
+ boolean allowRoaming, int reason, LinkProperties linkProperties,
+ Message result) {
SimulatedCommandsVerifier.getInstance().setupDataCall(accessNetworkType, dataProfile,
- isRoaming, allowRoaming, reason, linkProperties, pduSessionId, sliceInfo,
- trafficDescriptor, matchAllRuleAllowed, result);
+ isRoaming, allowRoaming, reason, linkProperties, result);
if (mSetupDataCallResult == null) {
try {
@@ -1219,6 +1200,14 @@ public class SimulatedCommands extends BaseCommands
}
}
+ // Store different cids to simulate concurrent IMS and default data calls
+ if ((dataProfile.getSupportedApnTypesBitmask() & ApnSetting.TYPE_IMS)
+ == ApnSetting.TYPE_IMS) {
+ mSetupDataCallResult.cid = 0;
+ } else {
+ mSetupDataCallResult.cid = 1;
+ }
+
DataCallResponse response = RIL.convertDataCallResult(mSetupDataCallResult);
if (mDcSuccess) {
resultSuccess(result, response);
@@ -1236,7 +1225,7 @@ public class SimulatedCommands extends BaseCommands
@Override
public void setPreferredNetworkType(int networkType , Message result) {
SimulatedCommandsVerifier.getInstance().setPreferredNetworkType(networkType, result);
- mPreferredNetworkType = networkType;
+ mNetworkType = networkType;
resultSuccess(result, null);
}
@@ -1245,29 +1234,11 @@ public class SimulatedCommands extends BaseCommands
SimulatedCommandsVerifier.getInstance().getPreferredNetworkType(result);
int ret[] = new int[1];
- ret[0] = mPreferredNetworkType;
+ ret[0] = mNetworkType;
resultSuccess(result, ret);
}
@Override
- public void setAllowedNetworkTypesBitmap(
- @TelephonyManager.NetworkTypeBitMask int networkTypeBitmask, Message response) {
- SimulatedCommandsVerifier.getInstance()
- .setAllowedNetworkTypesBitmap(networkTypeBitmask, response);
- mAllowedNetworkType = networkTypeBitmask;
- resultSuccess(response, null);
- }
-
- @Override
- public void getAllowedNetworkTypesBitmap(Message response) {
- SimulatedCommandsVerifier.getInstance().getAllowedNetworkTypesBitmap(response);
- int[] ret = new int[1];
-
- ret[0] = mAllowedNetworkType;
- resultSuccess(response, ret);
- }
-
- @Override
public void setLocationUpdates(boolean enable, Message response) {
SimulatedCommandsVerifier.getInstance().setLocationUpdates(enable, response);
resultSuccess(response, null);
@@ -1275,10 +1246,7 @@ public class SimulatedCommands extends BaseCommands
@Override
public void getSmscAddress(Message result) {
- SimulatedCommandsVerifier.getInstance().getSmscAddress(result);
- if (mSendGetSmscAddressResponse) {
- unimplemented(result);
- }
+ unimplemented(result);
}
@Override
@@ -1740,7 +1708,7 @@ public class SimulatedCommands extends BaseCommands
}
@UnsupportedAppUsage
- protected void resultSuccess(Message result, Object ret) {
+ private void resultSuccess(Message result, Object ret) {
if (result != null) {
AsyncResult.forMessage(result).result = ret;
if (mPausedResponseCount > 0) {
@@ -1899,10 +1867,7 @@ public class SimulatedCommands extends BaseCommands
@Override
public void setGsmBroadcastConfig(SmsBroadcastConfigInfo[] config, Message response) {
- SimulatedCommandsVerifier.getInstance().setGsmBroadcastConfig(config, response);
- if (mSendSetGsmBroadcastConfigResponse) {
- unimplemented(response);
- }
+ unimplemented(response);
}
@Override
@@ -2427,59 +2392,4 @@ public class SimulatedCommands extends BaseCommands
SimulatedCommandsVerifier.getInstance().getBarringInfo(result);
resultSuccess(result, null);
}
-
- @Override
- public void allocatePduSessionId(Message message) {
- SimulatedCommandsVerifier.getInstance().allocatePduSessionId(message);
- resultSuccess(message, 1);
- }
-
- @Override
- public void releasePduSessionId(Message message, int pduSessionId) {
- SimulatedCommandsVerifier.getInstance().releasePduSessionId(message, pduSessionId);
- resultSuccess(message, null);
- }
-
- @Override
- public void getSlicingConfig(Message result) {
- SimulatedCommandsVerifier.getInstance().getSlicingConfig(result);
- resultSuccess(result, null);
- }
-
- @VisibleForTesting
- public void setDataRegStateResult(Object regStateResult) {
- mDataRegStateResult = regStateResult;
- }
-
- @VisibleForTesting
- public void setVoiceRegStateResult(Object regStateResult) {
- mVoiceRegStateResult = regStateResult;
- }
-
- @Override
- public void getSimPhonebookRecords(Message result) {
- resultSuccess(result, null);
-
- // send a fake result
- List<SimPhonebookRecord> phonebookRecordInfoGroup = new ArrayList<SimPhonebookRecord>();
- mSimPhonebookRecordsReceivedRegistrants.notifyRegistrants(
- new AsyncResult(null,
- new ReceivedPhonebookRecords(4, phonebookRecordInfoGroup), null));
- }
-
- @Override
- public void getSimPhonebookCapacity(Message result) {
- resultSuccess(result, new AdnCapacity(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
- }
-
- @Override
- public void updateSimPhonebookRecord(SimPhonebookRecord phonebookRecord, Message result) {
- resultSuccess(result, new int[]{phonebookRecord.getRecordIndex()});
- notifySimPhonebookChanged();
- }
-
- @VisibleForTesting
- public void notifySimPhonebookChanged() {
- mSimPhonebookChangedRegistrants.notifyRegistrants();
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/SimulatedCommandsVerifier.java b/tests/telephonytests/src/com/android/internal/telephony/SimulatedCommandsVerifier.java
index e9c74ae237..6646c35d59 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/SimulatedCommandsVerifier.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/SimulatedCommandsVerifier.java
@@ -26,17 +26,14 @@ import android.telephony.NetworkScanRequest;
import android.telephony.SignalThresholdInfo;
import android.telephony.TelephonyManager;
import android.telephony.data.DataProfile;
-import android.telephony.data.NetworkSliceInfo;
-import android.telephony.data.TrafficDescriptor;
import android.telephony.emergency.EmergencyNumber;
import com.android.internal.telephony.CommandsInterface;
import com.android.internal.telephony.RadioCapability;
import com.android.internal.telephony.UUSInfo;
+import com.android.internal.telephony.uicc.IccCardApplicationStatus.PersoSubState;
import com.android.internal.telephony.cdma.CdmaSmsBroadcastConfigInfo;
import com.android.internal.telephony.gsm.SmsBroadcastConfigInfo;
-import com.android.internal.telephony.uicc.IccCardApplicationStatus.PersoSubState;
-import com.android.internal.telephony.uicc.SimPhonebookRecord;
public class SimulatedCommandsVerifier implements CommandsInterface {
private static SimulatedCommandsVerifier sInstance;
@@ -184,16 +181,6 @@ public class SimulatedCommandsVerifier implements CommandsInterface {
}
@Override
- public void registerForApnUnthrottled(Handler h, int what, Object obj) {
-
- }
-
- @Override
- public void unregisterForApnUnthrottled(Handler h) {
-
- }
-
- @Override
public void registerForInCallVoicePrivacyOn(Handler h, int what, Object obj) {
}
@@ -1062,17 +1049,6 @@ public class SimulatedCommandsVerifier implements CommandsInterface {
}
@Override
- public void setAllowedNetworkTypesBitmap(
- @TelephonyManager.NetworkTypeBitMask int networkTypeBitmask, Message response) {
-
- }
-
- @Override
- public void getAllowedNetworkTypesBitmap(Message response) {
-
- }
-
- @Override
public void setLocationUpdates(boolean enable, Message response) {
}
@@ -1204,9 +1180,8 @@ public class SimulatedCommandsVerifier implements CommandsInterface {
@Override
public void setupDataCall(int accessNetworkType, DataProfile dataProfile, boolean isRoaming,
- boolean allowRoaming, int reason, LinkProperties linkProperties, int pduSessionId,
- NetworkSliceInfo sliceInfo, TrafficDescriptor trafficDescriptor,
- boolean matchAllRuleAllowed, Message result) {
+ boolean allowRoaming, int reason, LinkProperties linkProperties,
+ Message result) {
}
@Override
@@ -1248,6 +1223,11 @@ public class SimulatedCommandsVerifier implements CommandsInterface {
}
@Override
+ public int getLteOnCdmaMode() {
+ return 0;
+ }
+
+ @Override
public void requestIccSimAuthentication(int authContext, String data, String aid,
Message response) {
@@ -1485,44 +1465,4 @@ public class SimulatedCommandsVerifier implements CommandsInterface {
@Override
public void getBarringInfo(Message result) {
}
-
- @Override
- public void allocatePduSessionId(Message result) {
- }
-
- @Override
- public void releasePduSessionId(Message result, int pduSessionId) {
- }
-
- @Override
- public void getSlicingConfig(Message result) {
- }
-
- @Override
- public void getSimPhonebookRecords(Message result){
- }
-
- @Override
- public void getSimPhonebookCapacity(Message result){
- }
-
- @Override
- public void updateSimPhonebookRecord(SimPhonebookRecord phonebookRecord, Message result){
- }
-
- @Override
- public void registerForSimPhonebookChanged(Handler h, int what, Object obj){
- }
-
- @Override
- public void unregisterForSimPhonebookChanged(Handler h){
- }
-
- @Override
- public void registerForSimPhonebookRecordsReceived(Handler h, int what, Object obj){
- }
-
- @Override
- public void unregisterForSimPhonebookRecordsReceived(Handler h){
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/SlidingWindowEventCounterTest.java b/tests/telephonytests/src/com/android/internal/telephony/SlidingWindowEventCounterTest.java
deleted file mode 100644
index da8b4c2f6c..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/SlidingWindowEventCounterTest.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.internal.telephony;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import android.os.SystemClock;
-
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-@RunWith(AndroidJUnit4.class)
-public class SlidingWindowEventCounterTest {
- long mInitialTime;
-
- @Before
- public void setUp() throws Exception {
- mInitialTime = SystemClock.elapsedRealtime();
- }
-
- @Test
- public void test_returnsTrue_ifEnoughEntriesInWindow() {
- SlidingWindowEventCounter counter = new SlidingWindowEventCounter(100, 3);
- for (int i = 0; i < 3; i++) {
- counter.addOccurrence(mInitialTime + i);
- }
- assertTrue(counter.isInWindow());
- }
-
- @Test
- public void test_returnsTrue_ifMoreThanEnoughEntriesInWindow() {
- SlidingWindowEventCounter counter = new SlidingWindowEventCounter(100, 3);
- for (int i = 0; i < 3; i++) {
- counter.addOccurrence(mInitialTime + i);
- }
- for (int i = 0; i < 3; i++) {
- counter.addOccurrence(mInitialTime + i + 50);
- }
- assertTrue(counter.isInWindow());
- }
-
- @Test
- public void test_returnsFalse_ifNotEnoughEntriesInWindow() {
- SlidingWindowEventCounter counter = new SlidingWindowEventCounter(100, 3);
- for (int i = 0; i < 2; i++) {
- counter.addOccurrence(mInitialTime + i);
- }
- assertFalse(counter.isInWindow());
- }
-
- @Test
- public void test_returnsFalse_ifEnoughEntriesButTooFarApart() {
- SlidingWindowEventCounter counter = new SlidingWindowEventCounter(100, 3);
- for (int i = 0; i < 2; i++) {
- counter.addOccurrence(mInitialTime + i);
- }
- counter.addOccurrence(mInitialTime + 101);
- counter.addOccurrence(mInitialTime + 102);
- assertFalse(counter.isInWindow());
- }
-}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/SmsDispatchersControllerTest.java b/tests/telephonytests/src/com/android/internal/telephony/SmsDispatchersControllerTest.java
index ee9e2b865f..90ec3d5865 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/SmsDispatchersControllerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/SmsDispatchersControllerTest.java
@@ -16,8 +16,6 @@
package com.android.internal.telephony;
-import static com.android.internal.telephony.SmsResponse.NO_ERROR_CODE;
-
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@@ -29,12 +27,10 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
import android.app.ActivityManager;
import android.os.Message;
import android.provider.Telephony.Sms.Intents;
-import android.telephony.SmsManager;
import android.test.FlakyTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.testing.AndroidTestingRunner;
@@ -48,8 +44,6 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
-import java.util.HashMap;
-
@RunWith(AndroidTestingRunner.class)
@TestableLooper.RunWithLooper
public class SmsDispatchersControllerTest extends TelephonyTest {
@@ -144,22 +138,6 @@ public class SmsDispatchersControllerTest extends TelephonyTest {
}
@Test @SmallTest
- public void testSendRetrySmsNullPdu() throws Exception {
- HashMap<String, Object> map = new HashMap<>();
- map.put("scAddr", "");
- map.put("destAddr", "");
- map.put("text", null);
- map.put("destPort", 0);
- switchImsSmsFormat(PhoneConstants.PHONE_TYPE_GSM);
- replaceInstance(SMSDispatcher.SmsTracker.class, "mFormat", mTracker,
- SmsConstants.FORMAT_3GPP2);
- when(mTracker.getData()).thenReturn(map);
- mSmsDispatchersController.sendRetrySms(mTracker);
- verify(mTracker).onFailed(eq(mContext), eq(SmsManager.RESULT_SMS_SEND_RETRY_FAILED),
- eq(NO_ERROR_CODE));
- }
-
- @Test @SmallTest
public void testInjectNullSmsPdu() throws Exception {
// unmock ActivityManager to be able to register receiver, create real PendingIntent and
// receive TEST_INTENT
@@ -167,7 +145,7 @@ public class SmsDispatchersControllerTest extends TelephonyTest {
restoreInstance(ActivityManager.class, "IActivityManagerSingleton", null);
// inject null sms pdu. This should cause intent to be received since pdu is null.
- mSmsDispatchersController.injectSmsPdu(null, SmsConstants.FORMAT_3GPP, true,
+ mSmsDispatchersController.injectSmsPdu(null, SmsConstants.FORMAT_3GPP,
(SmsDispatchersController.SmsInjectionCallback) result -> {
mInjectionCallbackTriggered = true;
assertEquals(Intents.RESULT_SMS_GENERIC_ERROR, result);
diff --git a/tests/telephonytests/src/com/android/internal/telephony/SubscriptionControllerTest.java b/tests/telephonytests/src/com/android/internal/telephony/SubscriptionControllerTest.java
index b79b3178d9..57c9eb28cf 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/SubscriptionControllerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/SubscriptionControllerTest.java
@@ -24,41 +24,37 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
import android.Manifest;
+import android.app.AppOpsManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
-import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
-import android.os.Looper;
import android.os.ParcelUuid;
-import android.os.PersistableBundle;
import android.os.UserHandle;
import android.provider.Settings;
-import android.telephony.CarrierConfigManager;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.UiccSlotInfo;
import android.test.mock.MockContentResolver;
+import android.test.suitebuilder.annotation.SmallTest;
import androidx.test.filters.FlakyTest;
-import androidx.test.filters.SmallTest;
import com.android.internal.telephony.uicc.IccCardStatus;
import com.android.internal.telephony.uicc.UiccController;
@@ -80,7 +76,6 @@ import java.util.UUID;
public class SubscriptionControllerTest extends TelephonyTest {
private static final int SINGLE_SIM = 1;
private static final int DUAL_SIM = 2;
- private static final int FAKE_SUBID = 123;
private String mCallingPackage;
private String mCallingFeature;
private SubscriptionController mSubscriptionControllerUT;
@@ -96,9 +91,6 @@ public class SubscriptionControllerTest extends TelephonyTest {
private ISetOpportunisticDataCallback mSetOpptDataCallback;
@Mock
private Handler mHandler;
- @Mock
- private SubscriptionInfo mMockSubscriptionInfo;
- private PersistableBundle mCarrierConfigs;
private static final String MAC_ADDRESS_PREFIX = "mac_";
private static final String DISPLAY_NAME_PREFIX = "my_phone_";
@@ -106,16 +98,11 @@ public class SubscriptionControllerTest extends TelephonyTest {
private static final String UNAVAILABLE_ICCID = "";
private static final String UNAVAILABLE_NUMBER = "";
private static final String DISPLAY_NUMBER = "123456";
- private static final String DISPLAY_NAME = "testing_display_name";
@Before
public void setUp() throws Exception {
super.setUp("SubscriptionControllerTest");
- if (Looper.myLooper() == null) {
- Looper.prepare();
- }
-
doReturn(SINGLE_SIM).when(mTelephonyManager).getSimCount();
doReturn(SINGLE_SIM).when(mTelephonyManager).getPhoneCount();
mMockContentResolver = (MockContentResolver) mContext.getContentResolver();
@@ -131,10 +118,6 @@ public class SubscriptionControllerTest extends TelephonyTest {
mCallingFeature = mContext.getAttributionTag();
doReturn(1).when(mProxyController).getMaxRafSupported();
-
- // Carrier Config
- mCarrierConfigs = mContextFixture.getCarrierConfigBundle();
-
mContextFixture.putIntArrayResource(com.android.internal.R.array.sim_colors, new int[]{5});
setupMocksForTelephonyPermissions(Build.VERSION_CODES.R);
@@ -148,10 +131,8 @@ public class SubscriptionControllerTest extends TelephonyTest {
/*clear sub info in mSubscriptionControllerUT since they will otherwise be persistent
* between each test case. */
- if (mSubscriptionControllerUT != null) {
- mSubscriptionControllerUT.clearSubInfo();
- mSubscriptionControllerUT.resetStaticMembers();
- }
+ mSubscriptionControllerUT.clearSubInfo();
+ mSubscriptionControllerUT.resetStaticMembers();
/* clear settings for default voice/data/sms sub ID */
Settings.Global.putInt(mContext.getContentResolver(),
@@ -263,244 +244,6 @@ public class SubscriptionControllerTest extends TelephonyTest {
}
- private void setSimEmbedded(boolean isEmbedded) throws Exception {
- ContentValues values = new ContentValues();
- values.put(SubscriptionManager.IS_EMBEDDED, isEmbedded ? 1 : 0);
- mFakeTelephonyProvider.update(SubscriptionManager.CONTENT_URI, values,
- SubscriptionManager.UNIQUE_KEY_SUBSCRIPTION_ID + "=" + getFirstSubId(),
- null);
- }
-
- @Test @SmallTest
- public void testSetGetDisplayNameSrc_updateNameSourceCarrierWithEmbeddedSim()
- throws Exception {
- testInsertSim();
-
- // Set values of DB
- setSimEmbedded(true);
- int subId = getFirstSubId();
- int nameSource = SubscriptionManager.NAME_SOURCE_CARRIER;
- mSubscriptionControllerUT.setDisplayNameUsingSrc(DISPLAY_NAME, subId, nameSource);
-
- // Update with new value
- String newDisplayName = "display_name_pnn";
- int newNameSource = SubscriptionManager.NAME_SOURCE_SIM_PNN;
-
- // Save to DB after updated
- mSubscriptionControllerUT.setDisplayNameUsingSrc(newDisplayName, subId, newNameSource);
-
- SubscriptionInfo subInfo = mSubscriptionControllerUT
- .getActiveSubscriptionInfo(subId, mCallingPackage, mCallingFeature);
-
- assertNotNull(subInfo);
- assertEquals(DISPLAY_NAME, subInfo.getDisplayName());
- assertEquals(nameSource, subInfo.getNameSource());
- }
-
- @Test @SmallTest
- public void testSetGetDisplayNameSrc_updateNameSourceCarrierWithConfigIsNull()
- throws Exception {
- testInsertSim();
-
- // Set values of DB
- setSimEmbedded(false);
- int subId = getFirstSubId();
- int nameSource = SubscriptionManager.NAME_SOURCE_CARRIER;
- mSubscriptionControllerUT.setDisplayNameUsingSrc(DISPLAY_NAME, subId, nameSource);
-
- // Update with new value
- String newDisplayName = "display_name_spn";
- int newNameSource = SubscriptionManager.NAME_SOURCE_SIM_SPN;
- when(mCarrierConfigManager.getConfigForSubId(subId)).thenReturn(null);
-
- // Save to DB after updated
- mSubscriptionControllerUT.setDisplayNameUsingSrc(newDisplayName, subId, newNameSource);
-
- SubscriptionInfo subInfo = mSubscriptionControllerUT
- .getActiveSubscriptionInfo(subId, mCallingPackage, mCallingFeature);
-
- assertNotNull(subInfo);
- assertEquals(DISPLAY_NAME, subInfo.getDisplayName());
- assertEquals(nameSource, subInfo.getNameSource());
- }
-
- @Test @SmallTest
- public void testSetGetDisplayNameSrc_updateNameSourceCarrierWithCarrierNameOverride()
- throws Exception {
- testInsertSim();
-
- // Set values of DB
- setSimEmbedded(false);
- int subId = getFirstSubId();
- int nameSource = SubscriptionManager.NAME_SOURCE_CARRIER;
- mSubscriptionControllerUT.setDisplayNameUsingSrc(DISPLAY_NAME, subId, nameSource);
-
- // Update with new value
- int newNameSource = SubscriptionManager.NAME_SOURCE_SIM_SPN;
- String newDisplayName = "display_name_spn";
- mCarrierConfigs.putBoolean(CarrierConfigManager.KEY_CARRIER_NAME_OVERRIDE_BOOL, true);
-
- // Save to DB after updated
- mSubscriptionControllerUT.setDisplayNameUsingSrc(newDisplayName, subId, newNameSource);
-
- SubscriptionInfo subInfo = mSubscriptionControllerUT
- .getActiveSubscriptionInfo(subId, mCallingPackage, mCallingFeature);
-
- assertNotNull(subInfo);
- assertEquals(DISPLAY_NAME, subInfo.getDisplayName());
- assertEquals(nameSource, subInfo.getNameSource());
- }
-
- @Test @SmallTest
- public void testSetGetDisplayNameSrc_updateNameSourceCarrierWithSpnAndCarrierName()
- throws Exception {
- testInsertSim();
-
- // Set values of DB
- setSimEmbedded(false);
- int subId = getFirstSubId();
- int nameSource = SubscriptionManager.NAME_SOURCE_CARRIER;
- mSubscriptionControllerUT.setDisplayNameUsingSrc(DISPLAY_NAME, subId, nameSource);
-
- // Update with new value
- int newNameSource = SubscriptionManager.NAME_SOURCE_SIM_SPN;
- String carrierName = "testing_carrier_name";
- String newDisplayName = "display_name_spn";
- when(mUiccController.getUiccProfileForPhone(anyInt())).thenReturn(mUiccProfile);
- when(mUiccProfile.getServiceProviderName()).thenReturn(null);
- mCarrierConfigs.putBoolean(CarrierConfigManager.KEY_CARRIER_NAME_OVERRIDE_BOOL, false);
- mCarrierConfigs.putString(CarrierConfigManager.KEY_CARRIER_NAME_STRING, carrierName);
-
- // Save to DB after updated
- mSubscriptionControllerUT.setDisplayNameUsingSrc(newDisplayName, subId, newNameSource);
-
- SubscriptionInfo subInfo = mSubscriptionControllerUT
- .getActiveSubscriptionInfo(subId, mCallingPackage, mCallingFeature);
-
- assertNotNull(subInfo);
- assertEquals(DISPLAY_NAME, subInfo.getDisplayName());
- assertEquals(nameSource, subInfo.getNameSource());
- }
-
- @Test @SmallTest
- public void testSetGetDisplayNameSrc_updateNameSourcePnnToNameSourceCarrierId()
- throws Exception {
- testInsertSim();
-
- // Set values of DB
- int subId = getFirstSubId();
- int nameSource = SubscriptionManager.NAME_SOURCE_SIM_PNN;
- mSubscriptionControllerUT.setDisplayNameUsingSrc(DISPLAY_NAME, subId, nameSource);
-
- // Update with new value
- String newDisplayName = "display_name_carrier_id";
- int newNameSource = SubscriptionManager.NAME_SOURCE_CARRIER_ID;
- when(mPhone.getPlmn()).thenReturn("testing_pnn");
-
- // Save to DB after updated
- mSubscriptionControllerUT.setDisplayNameUsingSrc(newDisplayName, subId, newNameSource);
-
- SubscriptionInfo subInfo = mSubscriptionControllerUT
- .getActiveSubscriptionInfo(subId, mCallingPackage, mCallingFeature);
-
- assertNotNull(subInfo);
- assertEquals(DISPLAY_NAME, subInfo.getDisplayName());
- assertEquals(nameSource, subInfo.getNameSource());
- }
-
- @Test @SmallTest
- public void testSetGetDisplayNameSrc_updateNameSourceUserInputToNameSourceSpn()
- throws Exception {
- testInsertSim();
-
- // Set values of DB
- int subId = getFirstSubId();
- int nameSource = SubscriptionManager.NAME_SOURCE_USER_INPUT;
- mSubscriptionControllerUT.setDisplayNameUsingSrc(DISPLAY_NAME, subId, nameSource);
-
- // Update with new value
- String newDisplayName = "display_name_spn";
- int newNameSource = SubscriptionManager.NAME_SOURCE_SIM_SPN;
-
- // Save to DB after updated
- mSubscriptionControllerUT.setDisplayNameUsingSrc(newDisplayName, subId, newNameSource);
-
- SubscriptionInfo subInfo = mSubscriptionControllerUT
- .getActiveSubscriptionInfo(subId, mCallingPackage, mCallingFeature);
-
- assertNotNull(subInfo);
- assertEquals(DISPLAY_NAME, subInfo.getDisplayName());
- assertEquals(nameSource, subInfo.getNameSource());
- }
-
- @Test @SmallTest
- public void testIsExistingNameSourceStillValid_pnnIsNotNull_returnTrue() {
- when((mMockSubscriptionInfo).getSubscriptionId()).thenReturn(FAKE_SUBID);
- when(mMockSubscriptionInfo.getNameSource())
- .thenReturn(SubscriptionManager.NAME_SOURCE_SIM_PNN);
- when(mPhone.getPlmn()).thenReturn("testing_pnn");
-
- assertTrue(mSubscriptionControllerUT.isExistingNameSourceStillValid(mMockSubscriptionInfo));
- }
-
- @Test @SmallTest
- public void testIsExistingNameSourceStillValid_spnIsNotNull_returnTrue() {
- when((mMockSubscriptionInfo).getSubscriptionId()).thenReturn(FAKE_SUBID);
- when(mMockSubscriptionInfo.getNameSource())
- .thenReturn(SubscriptionManager.NAME_SOURCE_SIM_SPN);
- when(mUiccController.getUiccProfileForPhone(anyInt())).thenReturn(mUiccProfile);
- when(mUiccProfile.getServiceProviderName()).thenReturn("testing_spn");
-
- assertTrue(mSubscriptionControllerUT.isExistingNameSourceStillValid(mMockSubscriptionInfo));
- }
-
- @Test @SmallTest
- public void testIsExistingNameSourceStillValid_simIsEmbedded_returnTrue() {
- when(mMockSubscriptionInfo.isEmbedded()).thenReturn(true);
- when((mMockSubscriptionInfo).getSubscriptionId()).thenReturn(FAKE_SUBID);
- when(mMockSubscriptionInfo.getNameSource())
- .thenReturn(SubscriptionManager.NAME_SOURCE_CARRIER);
-
- assertTrue(mSubscriptionControllerUT.isExistingNameSourceStillValid(mMockSubscriptionInfo));
- }
-
- @Test @SmallTest
- public void testIsExistingNameSourceStillValid_carrierConfigIsNull_returnTrue() {
- when(mMockSubscriptionInfo.isEmbedded()).thenReturn(false);
- when((mMockSubscriptionInfo).getSubscriptionId()).thenReturn(FAKE_SUBID);
- when(mMockSubscriptionInfo.getNameSource())
- .thenReturn(SubscriptionManager.NAME_SOURCE_CARRIER);
- when(mCarrierConfigManager.getConfigForSubId(FAKE_SUBID)).thenReturn(null);
-
- assertTrue(mSubscriptionControllerUT.isExistingNameSourceStillValid(mMockSubscriptionInfo));
- }
-
- @Test @SmallTest
- public void testIsExistingNameSourceStillValid_carrierNameOverrideIsTrue_returnTrue() {
- when(mMockSubscriptionInfo.isEmbedded()).thenReturn(false);
- when((mMockSubscriptionInfo).getSubscriptionId()).thenReturn(FAKE_SUBID);
- when(mMockSubscriptionInfo.getNameSource())
- .thenReturn(SubscriptionManager.NAME_SOURCE_CARRIER);
- mCarrierConfigs.putBoolean(CarrierConfigManager.KEY_CARRIER_NAME_OVERRIDE_BOOL, true);
-
- assertTrue(mSubscriptionControllerUT.isExistingNameSourceStillValid(mMockSubscriptionInfo));
- }
-
- @Test @SmallTest
- public void testIsExistingNameSourceStillValid_spnIsNullAndCarrierNameIsNotNull_returnTrue() {
- when(mMockSubscriptionInfo.isEmbedded()).thenReturn(false);
- when((mMockSubscriptionInfo).getSubscriptionId()).thenReturn(FAKE_SUBID);
- when(mMockSubscriptionInfo.getNameSource())
- .thenReturn(SubscriptionManager.NAME_SOURCE_CARRIER);
- when(mUiccController.getUiccProfileForPhone(anyInt())).thenReturn(mUiccProfile);
- when(mUiccProfile.getServiceProviderName()).thenReturn(null);
- mCarrierConfigs.putBoolean(CarrierConfigManager.KEY_CARRIER_NAME_OVERRIDE_BOOL, false);
- mCarrierConfigs.putString(CarrierConfigManager.KEY_CARRIER_NAME_STRING,
- "testing_carrier_name");
-
- assertTrue(mSubscriptionControllerUT.isExistingNameSourceStillValid(mMockSubscriptionInfo));
- }
-
@Test @SmallTest
public void testCleanUpSIM() {
testInsertSim();
@@ -1327,13 +1070,12 @@ public class SubscriptionControllerTest extends TelephonyTest {
}
@Test
- public void testGetActiveSubscriptionWithPhoneNumberAccess() throws Exception {
- // If the calling package meets any of the requirements for the
- // LegacyPermissionManager#checkPhoneNumberAccess test then the number should be available
- // in the SubscriptionInfo.
+ public void testGetActiveSubscriptionWithReadPhoneNumbers() throws Exception {
+ // If the calling package has the READ_PHONE_NUMBERS permission the number should be
+ // available in the SubscriptionInfo.
testInsertSim();
setupReadPhoneNumbersTest();
- setPhoneNumberAccess(PackageManager.PERMISSION_GRANTED);
+ mContextFixture.addCallingOrSelfPermission(Manifest.permission.READ_PHONE_NUMBERS);
int subId = getFirstSubId();
SubscriptionInfo subscriptionInfo = mSubscriptionControllerUT.getActiveSubscriptionInfo(
@@ -1411,14 +1153,13 @@ public class SubscriptionControllerTest extends TelephonyTest {
}
@Test
- public void testGetActiveSubscriptionInfoForSimSlotIndexWithPhoneNumberAccess()
+ public void testGetActiveSubscriptionInfoForSimSlotIndexWithReadPhoneNumbers()
throws Exception {
- // If the calling package meets any of the requirements for the
- // LegacyPermissionManager#checkPhoneNumberAccess test then the number should be available
- // in the SubscriptionInfo.
+ // If the calling package has the READ_PHONE_NUMBERS permission the number should be
+ // available in the SubscriptionInfo.
testInsertSim();
setupReadPhoneNumbersTest();
- setPhoneNumberAccess(PackageManager.PERMISSION_GRANTED);
+ mContextFixture.addCallingOrSelfPermission(Manifest.permission.READ_PHONE_NUMBERS);
SubscriptionInfo subscriptionInfo =
mSubscriptionControllerUT.getActiveSubscriptionInfoForSimSlotIndex(0,
@@ -1498,13 +1239,12 @@ public class SubscriptionControllerTest extends TelephonyTest {
}
@Test
- public void testGetActiveSubscriptionInfoListWithPhoneNumberAccess() throws Exception {
- // If the calling package meets any of the requirements for the
- // LegacyPermissionManager#checkPhoneNumberAccess test then the number should be available
- // in the SubscriptionInfo.
+ public void testGetActiveSubscriptionInfoListWithReadPhoneNumbers() throws Exception {
+ // If the calling package has the READ_PHONE_NUMBERS permission the number should be
+ // available in the SubscriptionInfo.
testInsertSim();
setupReadPhoneNumbersTest();
- setPhoneNumberAccess(PackageManager.PERMISSION_GRANTED);
+ mContextFixture.addCallingOrSelfPermission(Manifest.permission.READ_PHONE_NUMBERS);
List<SubscriptionInfo> subInfoList =
mSubscriptionControllerUT.getActiveSubscriptionInfoList(mCallingPackage,
@@ -1561,29 +1301,6 @@ public class SubscriptionControllerTest extends TelephonyTest {
}
@Test
- public void testGetActiveSubscriptionInfoListCheckOrder()
- throws Exception {
- // If an app does not have the READ_PHONE_STATE permission but has carrier privileges on one
- // out of multiple sub IDs then the SubscriptionInfo for that subId should be returned with
- // the ICC ID and phone number.
- testInsertSim();
- doReturn(2).when(mTelephonyManager).getPhoneCount();
- mSubscriptionControllerUT.addSubInfoRecord("test2", 1);
- int firstSubId = getFirstSubId();
- int secondSubId = getSubIdAtIndex(1);
- setupIdentifierCarrierPrivilegesTest();
- setCarrierPrivilegesForSubId(false, firstSubId);
- setCarrierPrivilegesForSubId(true, secondSubId);
-
- List<SubscriptionInfo> subInfoList =
- mSubscriptionControllerUT.getActiveSubscriptionInfoList(mCallingPackage,
- mCallingFeature);
-
- assertEquals(2, subInfoList.size());
- assertTrue(subInfoList.get(0).getSubscriptionId() < subInfoList.get(1).getSubscriptionId());
- }
-
- @Test
public void testGetActiveSubscriptionInfoListWithIdentifierAccessWithoutNumberAccess()
throws Exception {
// An app with access to device identifiers may not have access to the device phone number
@@ -1658,13 +1375,12 @@ public class SubscriptionControllerTest extends TelephonyTest {
}
@Test
- public void testGetSubscriptionInGroupWithPhoneNumberAccess() throws Exception {
- // If the calling package meets any of the requirements for the
- // LegacyPermissionManager#checkPhoneNumberAccess test then the number should be available
- // in the SubscriptionInfo.
+ public void testGetSubscriptionInGroupWithReadPhoneNumbers() throws Exception {
+ // If the calling package has the READ_PHONE_NUMBERS permission the number should be
+ // available in the SubscriptionInfo.
ParcelUuid groupUuid = setupGetSubscriptionsInGroupTest();
setupReadPhoneNumbersTest();
- setPhoneNumberAccess(PackageManager.PERMISSION_GRANTED);
+ mContextFixture.addCallingOrSelfPermission(Manifest.permission.READ_PHONE_NUMBERS);
List<SubscriptionInfo> subInfoList = mSubscriptionControllerUT.getSubscriptionsInGroup(
groupUuid, mCallingPackage, mCallingFeature);
@@ -1721,7 +1437,9 @@ public class SubscriptionControllerTest extends TelephonyTest {
mContextFixture.removeCallingOrSelfPermission(ContextFixture.PERMISSION_ENABLE_ALL);
mContextFixture.addCallingOrSelfPermission(Manifest.permission.READ_PHONE_STATE);
setupMocksForTelephonyPermissions(Build.VERSION_CODES.R);
- setPhoneNumberAccess(PackageManager.PERMISSION_DENIED);
+ doReturn(AppOpsManager.MODE_DEFAULT).when(mAppOpsManager).noteOp(
+ eq(AppOpsManager.OPSTR_WRITE_SMS), anyInt(), anyString(),
+ nullable(String.class), nullable(String.class));
}
private void setupIdentifierCarrierPrivilegesTest() throws Exception {
@@ -1923,38 +1641,4 @@ public class SubscriptionControllerTest extends TelephonyTest {
assertFalse(mSubscriptionControllerUT.getActiveSubscriptionInfo(
1, mContext.getOpPackageName(), null).areUiccApplicationsEnabled());
}
-
- @Test
- @SmallTest
- public void testInsertEmptySubInfoRecord_returnsNull_ifRecordExists() {
- final String mockedIccid = "123456789";
- final int mockedSlotIndex = 1;
-
- assertNotNull(mSubscriptionControllerUT.insertEmptySubInfoRecord(
- mockedIccid, mockedSlotIndex));
- // Insert second time with the same iccid should result in no-op and return null.
- assertNull(mSubscriptionControllerUT.insertEmptySubInfoRecord(
- mockedIccid, mockedSlotIndex));
- assertEquals(
- 1,
- mSubscriptionControllerUT
- .getAllSubInfoList(mCallingPackage, mCallingFeature).size());
- }
-
- @Test
- @SmallTest
- public void testCheckPhoneIdAndIccIdMatch() {
- try {
- testSetSubscriptionGroupWithModifyPermission();
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- mSubscriptionControllerUT.addSubInfoRecord("test3",
- SubscriptionManager.INVALID_SIM_SLOT_INDEX);
-
- assertTrue(mSubscriptionControllerUT.checkPhoneIdAndIccIdMatch(0, "test"));
- assertTrue(mSubscriptionControllerUT.checkPhoneIdAndIccIdMatch(0, "test2"));
- assertFalse(mSubscriptionControllerUT.checkPhoneIdAndIccIdMatch(0, "test3"));
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/SubscriptionInfoUpdaterTest.java b/tests/telephonytests/src/com/android/internal/telephony/SubscriptionInfoUpdaterTest.java
index 1161792685..ce5be8e50d 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/SubscriptionInfoUpdaterTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/SubscriptionInfoUpdaterTest.java
@@ -42,6 +42,7 @@ import android.net.Uri;
import android.os.Looper;
import android.os.ParcelUuid;
import android.os.PersistableBundle;
+import android.permission.IPermissionManager;
import android.service.euicc.EuiccProfileInfo;
import android.service.euicc.EuiccService;
import android.service.euicc.GetEuiccProfileInfoListResult;
@@ -84,10 +85,8 @@ public class SubscriptionInfoUpdaterTest extends TelephonyTest {
private static final int FAKE_SUB_ID_2 = 1;
private static final int FAKE_CARD_ID = 0;
private static final String FAKE_EID = "89049032000001000000031328322874";
- private static final String FAKE_ICCID_1 = "89012604200000000000";
private static final String FAKE_MCC_MNC_1 = "123456";
private static final String FAKE_MCC_MNC_2 = "456789";
- private static final int FAKE_PHONE_ID_1 = 0;
private SubscriptionInfoUpdater mUpdater;
private IccRecords mIccRecord;
@@ -108,6 +107,8 @@ public class SubscriptionInfoUpdaterTest extends TelephonyTest {
@Mock
private IPackageManager mPackageManager;
@Mock
+ private IPermissionManager mPermissionManager;
+ @Mock
private UiccSlot mUiccSlot;
/*Custom ContentProvider */
@@ -160,8 +161,8 @@ public class SubscriptionInfoUpdaterTest extends TelephonyTest {
.getActiveSubIdList(/*visibleOnly*/false);
mIccRecord = mUiccProfile.getIccRecords();
- mUpdater =
- new SubscriptionInfoUpdater(Looper.myLooper(), mContext, mSubscriptionController);
+ mUpdater = new SubscriptionInfoUpdater(Looper.myLooper(), mContext,
+ new CommandsInterface[]{mSimulatedCommands});
processAllMessages();
assertFalse(mUpdater.isSubInfoInitialized());
@@ -237,16 +238,16 @@ public class SubscriptionInfoUpdaterTest extends TelephonyTest {
@SmallTest
public void testSimNotReady() throws Exception {
mUpdater.updateInternalIccState(
- IccCardConstants.INTENT_VALUE_ICC_NOT_READY, null, FAKE_PHONE_ID_1);
+ IccCardConstants.INTENT_VALUE_ICC_NOT_READY, null, FAKE_SUB_ID_1);
processAllMessages();
assertFalse(mUpdater.isSubInfoInitialized());
verify(mSubscriptionContent, never()).put(anyString(), any());
CarrierConfigManager mConfigManager = (CarrierConfigManager)
mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE);
- verify(mConfigManager, never()).updateConfigForPhoneId(eq(FAKE_PHONE_ID_1),
+ verify(mConfigManager, never()).updateConfigForPhoneId(eq(FAKE_SUB_ID_1),
eq(IccCardConstants.INTENT_VALUE_ICC_NOT_READY));
- verify(mSubscriptionController, never()).clearSubInfoRecord(FAKE_PHONE_ID_1);
+ verify(mSubscriptionController, never()).clearSubInfo();
verify(mSubscriptionController, never()).notifySubscriptionInfoChanged();
}
@@ -257,19 +258,19 @@ public class SubscriptionInfoUpdaterTest extends TelephonyTest {
doReturn(true).when(mIccCard).isEmptyProfile();
mUpdater.updateInternalIccState(
- IccCardConstants.INTENT_VALUE_ICC_NOT_READY, null, FAKE_PHONE_ID_1);
+ IccCardConstants.INTENT_VALUE_ICC_NOT_READY, null, FAKE_SUB_ID_1);
processAllMessages();
assertTrue(mUpdater.isSubInfoInitialized());
// Sub info should be cleared and change should be notified.
- verify(mSubscriptionController).clearSubInfoRecord(eq(FAKE_PHONE_ID_1));
+ verify(mSubscriptionController).clearSubInfoRecord(eq(FAKE_SUB_ID_1));
verify(mSubscriptionController).notifySubscriptionInfoChanged();
// No new sub should be added.
verify(mSubscriptionManager, never()).addSubscriptionInfoRecord(any(), anyInt());
verify(mSubscriptionContent, never()).put(anyString(), any());
CarrierConfigManager mConfigManager = (CarrierConfigManager)
mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE);
- verify(mConfigManager).updateConfigForPhoneId(eq(FAKE_PHONE_ID_1),
+ verify(mConfigManager).updateConfigForPhoneId(eq(FAKE_SUB_ID_1),
eq(IccCardConstants.INTENT_VALUE_ICC_NOT_READY));
}
@@ -284,46 +285,28 @@ public class SubscriptionInfoUpdaterTest extends TelephonyTest {
doReturn(false).when(mSubInfo).areUiccApplicationsEnabled();
mUpdater.updateInternalIccState(
- IccCardConstants.INTENT_VALUE_ICC_NOT_READY, null, FAKE_PHONE_ID_1);
+ IccCardConstants.INTENT_VALUE_ICC_NOT_READY, null, FAKE_SUB_ID_1);
processAllMessages();
assertTrue(mUpdater.isSubInfoInitialized());
// Sub info should be cleared and change should be notified.
- verify(mSubscriptionController).clearSubInfoRecord(eq(FAKE_PHONE_ID_1));
+ verify(mSubscriptionController).clearSubInfoRecord(eq(FAKE_SUB_ID_1));
verify(mSubscriptionController).notifySubscriptionInfoChanged();
// No new sub should be added.
verify(mSubscriptionManager, never()).addSubscriptionInfoRecord(any(), anyInt());
verify(mSubscriptionContent, never()).put(anyString(), any());
CarrierConfigManager mConfigManager = (CarrierConfigManager)
mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE);
- verify(mConfigManager).updateConfigForPhoneId(eq(FAKE_PHONE_ID_1),
+ verify(mConfigManager).updateConfigForPhoneId(eq(FAKE_SUB_ID_1),
eq(IccCardConstants.INTENT_VALUE_ICC_NOT_READY));
// When becomes ABSENT, UICC_APPLICATIONS_ENABLED should be reset to true.
mUpdater.updateInternalIccState(
- IccCardConstants.INTENT_VALUE_ICC_ABSENT, null, FAKE_PHONE_ID_1);
- processAllMessages();
- ArgumentCaptor<ContentValues> valueCapture = ArgumentCaptor.forClass(ContentValues.class);
- verify(mContentProvider).update(eq(SubscriptionManager.CONTENT_URI), valueCapture.capture(),
- eq(SubscriptionManager.ICC_ID + "=\'" + iccId + "\'"), eq(null));
- ContentValues contentValues = valueCapture.getValue();
- assertTrue(contentValues != null && contentValues.getAsBoolean(
- UICC_APPLICATIONS_ENABLED));
- }
-
- @Test
- @SmallTest
- public void testSimRemovedWhileDisablingUiccApps() throws Exception {
- loadSim();
-
- mUpdater.updateInternalIccState(
IccCardConstants.INTENT_VALUE_ICC_ABSENT, null, FAKE_SUB_ID_1);
processAllMessages();
-
- // UICC_APPLICATIONS_ENABLED should be reset to true.
ArgumentCaptor<ContentValues> valueCapture = ArgumentCaptor.forClass(ContentValues.class);
verify(mContentProvider).update(eq(SubscriptionManager.CONTENT_URI), valueCapture.capture(),
- eq(SubscriptionManager.ICC_ID + "=\'" + FAKE_ICCID_1 + "\'"), eq(null));
+ eq(SubscriptionManager.ICC_ID + "=\'" + iccId + "\'"), eq(null));
ContentValues contentValues = valueCapture.getValue();
assertTrue(contentValues != null && contentValues.getAsBoolean(
UICC_APPLICATIONS_ENABLED));
@@ -363,11 +346,13 @@ public class SubscriptionInfoUpdaterTest extends TelephonyTest {
verify(mSubscriptionController, times(0)).notifySubscriptionInfoChanged();
}
- private void loadSim() {
+ @Test
+ @SmallTest
+ public void testSimLoaded() throws Exception {
doReturn(FAKE_SUB_ID_1).when(mSubInfo).getSubscriptionId();
doReturn(Arrays.asList(mSubInfo)).when(mSubscriptionController)
.getSubInfoUsingSlotIndexPrivileged(eq(FAKE_SUB_ID_1));
- doReturn(FAKE_ICCID_1).when(mIccRecord).getFullIccId();
+ doReturn("89012604200000000000").when(mIccRecord).getFullIccId();
doReturn(FAKE_MCC_MNC_1).when(mTelephonyManager).getSimOperatorNumeric(FAKE_SUB_ID_1);
when(mActivityManager.updateMccMncConfiguration(anyString(), anyString())).thenReturn(
true);
@@ -378,17 +363,6 @@ public class SubscriptionInfoUpdaterTest extends TelephonyTest {
processAllMessages();
assertTrue(mUpdater.isSubInfoInitialized());
- CarrierConfigManager mConfigManager = (CarrierConfigManager)
- mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE);
- verify(mConfigManager).updateConfigForPhoneId(eq(FAKE_SUB_ID_1),
- eq(IccCardConstants.INTENT_VALUE_ICC_LOADED));
- }
-
- @Test
- @SmallTest
- public void testSimLoaded() throws Exception {
- loadSim();
-
// verify SIM_STATE_CHANGED broadcast. It should be broadcast twice, once for
// READ_PHONE_STATE and once for READ_PRIVILEGED_PHONE_STATE
/* todo: cannot verify as intent is sent using ActivityManagerNative.broadcastStickyIntent()
@@ -410,7 +384,7 @@ public class SubscriptionInfoUpdaterTest extends TelephonyTest {
SubscriptionManager mSubscriptionManager = SubscriptionManager.from(mContext);
verify(mTelephonyManager).getSimOperatorNumeric(FAKE_SUB_ID_1);
verify(mSubscriptionManager, times(1)).addSubscriptionInfoRecord(
- eq(FAKE_ICCID_1), eq(FAKE_SUB_ID_1));
+ eq("89012604200000000000"), eq(FAKE_SUB_ID_1));
verify(mSubscriptionController, times(1)).notifySubscriptionInfoChanged();
verify(mSubscriptionController, times(1)).setMccMnc(FAKE_MCC_MNC_1, FAKE_SUB_ID_1);
verify(mSubscriptionController, times(0)).clearSubInfo();
@@ -443,7 +417,7 @@ public class SubscriptionInfoUpdaterTest extends TelephonyTest {
@Test
@SmallTest
public void testSimLoadedEmptyOperatorNumeric() throws Exception {
- doReturn(FAKE_ICCID_1).when(mIccRecord).getFullIccId();
+ doReturn("89012604200000000000").when(mIccRecord).getFullIccId();
// operator numeric is empty
doReturn("").when(mTelephonyManager).getSimOperatorNumeric(FAKE_SUB_ID_1);
doReturn(FAKE_SUB_ID_1).when(mSubInfo).getSubscriptionId();
@@ -457,7 +431,7 @@ public class SubscriptionInfoUpdaterTest extends TelephonyTest {
SubscriptionManager mSubscriptionManager = SubscriptionManager.from(mContext);
verify(mTelephonyManager).getSimOperatorNumeric(FAKE_SUB_ID_1);
verify(mSubscriptionManager, times(1)).addSubscriptionInfoRecord(
- eq(FAKE_ICCID_1), eq(FAKE_SUB_ID_1));
+ eq("89012604200000000000"), eq(FAKE_SUB_ID_1));
verify(mSubscriptionController, times(1)).notifySubscriptionInfoChanged();
verify(mSubscriptionController, times(0)).setMccMnc(anyString(), anyInt());
verify(mSubscriptionController, times(0)).clearSubInfo();
@@ -517,7 +491,7 @@ public class SubscriptionInfoUpdaterTest extends TelephonyTest {
doReturn(FAKE_MCC_MNC_1).when(mTelephonyManager).getSimOperatorNumeric(eq(FAKE_SUB_ID_1));
doReturn(FAKE_MCC_MNC_2).when(mTelephonyManager).getSimOperatorNumeric(eq(FAKE_SUB_ID_2));
verify(mSubscriptionController, times(0)).clearSubInfo();
- doReturn(FAKE_ICCID_1).when(mIccRecord).getFullIccId();
+ doReturn("89012604200000000000").when(mIccRecord).getFullIccId();
SubscriptionManager mSubscriptionManager = SubscriptionManager.from(mContext);
verify(mSubscriptionManager, times(0)).addSubscriptionInfoRecord(anyString(), anyInt());
verify(mSubscriptionController, times(0)).notifySubscriptionInfoChanged();
@@ -545,7 +519,7 @@ public class SubscriptionInfoUpdaterTest extends TelephonyTest {
IccCardConstants.INTENT_VALUE_ICC_LOADED, null, FAKE_SUB_ID_2);
processAllMessages();
- verify(mSubscriptionManager, times(1)).addSubscriptionInfoRecord(eq(FAKE_ICCID_1),
+ verify(mSubscriptionManager, times(1)).addSubscriptionInfoRecord(eq("89012604200000000000"),
eq(FAKE_SUB_ID_1));
verify(mSubscriptionManager, times(1)).addSubscriptionInfoRecord(eq("89012604200000000001"),
eq(FAKE_SUB_ID_2));
@@ -562,7 +536,7 @@ public class SubscriptionInfoUpdaterTest extends TelephonyTest {
doReturn("98106240020000000000").when(mIccRecord).getFullIccId();
replaceInstance(SubscriptionInfoUpdater.class, "sIccId", null,
- new String[]{FAKE_ICCID_1});
+ new String[]{"89012604200000000000"});
mUpdater.updateInternalIccState(
IccCardConstants.INTENT_VALUE_ICC_LOCKED, "TESTING", FAKE_SUB_ID_1);
@@ -751,10 +725,9 @@ public class SubscriptionInfoUpdaterTest extends TelephonyTest {
mUpdater.updateSubscriptionByCarrierConfig(mPhone.getPhoneId(),
carrierPackageName, new PersistableBundle());
- //at each call to updateSubscriptionByCarrierConfig, only carrier certs are updated
- verify(mContentProvider, times(1)).update(any(), any(), any(), any());
- verify(mSubscriptionController, times(1)).notifySubscriptionInfoChanged();
- verify(mSubscriptionController, times(1)).refreshCachedActiveSubscriptionInfoList();
+ verify(mContentProvider, never()).update(any(), any(), any(), any());
+ verify(mSubscriptionController, never()).refreshCachedActiveSubscriptionInfoList();
+ verify(mSubscriptionController, never()).notifySubscriptionInfoChanged();
}
@Test
@@ -783,8 +756,7 @@ public class SubscriptionInfoUpdaterTest extends TelephonyTest {
cvCaptor.capture(), eq(null), eq(null));
assertEquals(1, cvCaptor.getValue().getAsInteger(
SubscriptionManager.IS_OPPORTUNISTIC).intValue());
- // 2 updates: isOpportunistic, and carrier certs:
- assertEquals(2, cvCaptor.getValue().size());
+ assertEquals(1, cvCaptor.getValue().size());
verify(mSubscriptionController, times(1)).refreshCachedActiveSubscriptionInfoList();
verify(mSubscriptionController, times(1)).notifySubscriptionInfoChanged();
}
@@ -820,8 +792,7 @@ public class SubscriptionInfoUpdaterTest extends TelephonyTest {
cvCaptor.getValue().getAsString(SubscriptionManager.GROUP_UUID));
assertEquals(carrierPackageName,
cvCaptor.getValue().getAsString(SubscriptionManager.GROUP_OWNER));
- // 4 updates: isOpportunistic, groupUuid, groupOwner, and carrier certs:
- assertEquals(4, cvCaptor.getValue().size());
+ assertEquals(3, cvCaptor.getValue().size());
}
@Test
@@ -854,8 +825,7 @@ public class SubscriptionInfoUpdaterTest extends TelephonyTest {
assertEquals(1, cvCaptor.getValue().getAsInteger(
SubscriptionManager.IS_OPPORTUNISTIC).intValue());
assertNull(cvCaptor.getValue().getAsString(SubscriptionManager.GROUP_UUID));
- // 3 updates: isOpportunistic, groupUuid, and carrier certs:
- assertEquals(3, cvCaptor.getValue().size());
+ assertEquals(2, cvCaptor.getValue().size());
}
@Test
@@ -900,44 +870,4 @@ public class SubscriptionInfoUpdaterTest extends TelephonyTest {
verify(mSubscriptionController, times(1)).refreshCachedActiveSubscriptionInfoList();
verify(mSubscriptionController, times(1)).notifySubscriptionInfoChanged();
}
-
- @Test
- @SmallTest
- public void testSimReady() throws Exception {
- replaceInstance(SubscriptionInfoUpdater.class, "sIccId", null,new String[]{""});
-
- doReturn(FAKE_ICCID_1).when(mUiccSlot).getIccId();
-
- mUpdater.updateInternalIccState(
- IccCardConstants.INTENT_VALUE_ICC_READY, "TESTING", FAKE_SUB_ID_1);
- processAllMessages();
-
- verify(mSubscriptionController).clearSubInfoRecord(eq(FAKE_SUB_ID_1));
- verify(mSubscriptionManager, times(1)).addSubscriptionInfoRecord(
- eq(FAKE_ICCID_1), eq(FAKE_SUB_ID_1));
- assertTrue(mUpdater.isSubInfoInitialized());
- verify(mSubscriptionController, times(1)).notifySubscriptionInfoChanged();
- }
-
- @Test
- @SmallTest
- public void testSimReadyAndLoaded() throws Exception {
- replaceInstance(SubscriptionInfoUpdater.class, "sIccId", null,new String[]{""});
-
- doReturn(null).when(mUiccSlot).getIccId();
-
- mUpdater.updateInternalIccState(
- IccCardConstants.INTENT_VALUE_ICC_READY, "TESTING", FAKE_SUB_ID_1);
- processAllMessages();
-
- verify(mSubscriptionManager, times(0)).addSubscriptionInfoRecord(
- eq(FAKE_ICCID_1), eq(FAKE_SUB_ID_1));
-
- loadSim();
-
- SubscriptionManager mSubscriptionManager = SubscriptionManager.from(mContext);
- verify(mSubscriptionManager, times(1)).addSubscriptionInfoRecord(
- eq(FAKE_ICCID_1), eq(FAKE_SUB_ID_1));
- verify(mSubscriptionController, times(1)).notifySubscriptionInfoChanged();
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/TelephonyPermissionsTest.java b/tests/telephonytests/src/com/android/internal/telephony/TelephonyPermissionsTest.java
index b545c2b7d1..dbaa29a76d 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/TelephonyPermissionsTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/TelephonyPermissionsTest.java
@@ -36,7 +36,7 @@ import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.ServiceManager;
-import android.permission.LegacyPermissionManager;
+import android.permission.PermissionManager;
import android.provider.DeviceConfig;
import android.provider.Settings;
import android.telephony.SubscriptionManager;
@@ -46,7 +46,7 @@ import android.test.mock.MockContentResolver;
import android.test.suitebuilder.annotation.SmallTest;
import com.android.internal.util.test.FakeSettingsProvider;
-import com.android.server.pm.permission.LegacyPermissionManagerService;
+import com.android.server.pm.permission.PermissionManagerService;
import org.junit.Before;
import org.junit.Test;
@@ -88,7 +88,7 @@ public class TelephonyPermissionsTest {
@Mock
private TelephonyManager mTelephonyManagerMockForSub2;
@Mock
- private LegacyPermissionManagerService mMockLegacyPermissionManagerService;
+ private PermissionManagerService mMockPermissionManagerService;
private MockContentResolver mMockContentResolver;
private FakeSettingsConfigProvider mFakeSettingsConfigProvider;
@@ -107,10 +107,10 @@ public class TelephonyPermissionsTest {
when(mMockSubscriptionManager.getCompleteActiveSubscriptionIdList()).thenReturn(
new int[]{SUB_ID});
- LegacyPermissionManager legacyPermissionManager = new LegacyPermissionManager(
- mMockLegacyPermissionManagerService);
- when(mMockContext.getSystemService(Context.LEGACY_PERMISSION_SERVICE)).thenReturn(
- legacyPermissionManager);
+ PermissionManager permissionManager = new PermissionManager(mMockContext, null,
+ mMockPermissionManagerService);
+ when(mMockContext.getSystemService(Context.PERMISSION_SERVICE)).thenReturn(
+ permissionManager);
// By default, assume we have no permissions or app-ops bits.
doThrow(new SecurityException()).when(mMockContext)
@@ -233,42 +233,79 @@ public class TelephonyPermissionsTest {
}
@Test
- public void testCheckReadPhoneNumber_targetPreRWithReadPhoneStateNoAppop() throws Exception {
- // If ap app is targeting SDK version < R then the phone number should be accessible with
- // both the READ_PHONE_STATE permission and appop granted; if only the permission is granted
- // but the appop is denied then the LegacyPermissionManager should return MODE_IGNORED
- // to indicate the check should fail silently (return empty / null data).
- when(mMockLegacyPermissionManagerService.checkPhoneNumberAccess(PACKAGE, MSG, FEATURE,
- PID, UID)).thenReturn(AppOpsManager.MODE_IGNORED);
- assertFalse(
- TelephonyPermissions.checkReadPhoneNumber(mMockContext, SUB_ID, PID, UID, PACKAGE,
- FEATURE, MSG));
+ public void testCheckReadPhoneNumber_defaultSmsApp() throws Exception {
+ setupMocksForDeviceIdentifiersErrorPath();
+ when(mMockAppOps.noteOp(eq(AppOpsManager.OPSTR_WRITE_SMS), eq(UID), eq(PACKAGE),
+ eq(FEATURE), nullable(String.class))).thenReturn(AppOpsManager.MODE_ALLOWED);
+ assertTrue(TelephonyPermissions.checkReadPhoneNumber(
+ mMockContext, SUB_ID, PID, UID, PACKAGE, FEATURE, MSG));
}
@Test
- public void testCheckReadPhoneNumber_hasPermissionManagerPhoneNumberAccess() {
- // To limit binder transactions the targetSdkVersion, permission, and appop checks are all
- // performed by the LegacyPermissionManager; this test verifies when this API returns
- // the calling package meets the requirements for phone number access the telephony
- // check also returns true.
- when(mMockLegacyPermissionManagerService.checkPhoneNumberAccess(PACKAGE, MSG, FEATURE,
- PID, UID)).thenReturn(PackageManager.PERMISSION_GRANTED);
- assertTrue(
- TelephonyPermissions.checkReadPhoneNumber(mMockContext, SUB_ID, PID, UID, PACKAGE,
- FEATURE, MSG));
+ public void testCheckReadPhoneNumber_hasPrivilegedPhoneStatePermission() throws Exception {
+ setupMocksForDeviceIdentifiersErrorPath();
+ doNothing().when(mMockContext).enforcePermission(
+ android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, PID, UID, MSG);
+ assertTrue(TelephonyPermissions.checkReadPhoneNumber(
+ mMockContext, SUB_ID, PID, UID, PACKAGE, FEATURE, MSG));
}
@Test
- public void testCheckReadPhoneNumber_hasCarrierPrivileges() throws Exception {
- when(mTelephonyManagerMock.createForSubscriptionId(eq(SUB_ID))).thenReturn(
- mTelephonyManagerMockForSub1);
- when(mTelephonyManagerMockForSub1.getCarrierPrivilegeStatus(anyInt())).thenReturn(
- TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS);
- assertTrue(
- TelephonyPermissions.checkReadPhoneNumber(mMockContext, SUB_ID, PID, UID, PACKAGE,
- FEATURE, MSG));
+ public void testCheckReadPhoneNumber_hasReadSms() throws Exception {
+ setupMocksForDeviceIdentifiersErrorPath();
+ doNothing().when(mMockContext).enforcePermission(
+ android.Manifest.permission.READ_SMS, PID, UID, MSG);
+ when(mMockAppOps.noteOp(eq(AppOpsManager.OPSTR_READ_SMS), eq(UID), eq(PACKAGE), eq(FEATURE),
+ nullable(String.class))).thenReturn(AppOpsManager.MODE_ALLOWED);
+ assertTrue(TelephonyPermissions.checkReadPhoneNumber(
+ mMockContext, SUB_ID, PID, UID, PACKAGE, FEATURE, MSG));
}
+ @Test
+ public void testCheckReadPhoneNumber_hasReadPhoneNumbers() throws Exception {
+ setupMocksForDeviceIdentifiersErrorPath();
+ doNothing().when(mMockContext).enforcePermission(
+ android.Manifest.permission.READ_PHONE_NUMBERS, PID, UID, MSG);
+ when(mMockAppOps.noteOp(eq(AppOpsManager.OPSTR_READ_PHONE_NUMBERS), eq(UID), eq(PACKAGE),
+ eq(FEATURE), nullable(String.class))).thenReturn(AppOpsManager.MODE_ALLOWED);
+ assertTrue(TelephonyPermissions.checkReadPhoneNumber(
+ mMockContext, SUB_ID, PID, UID, PACKAGE, FEATURE, MSG));
+ }
+
+ @Test
+ public void testCheckReadPhoneNumber_hasReadSmsNoAppop() throws Exception {
+ // If an app has been granted the READ_SMS permission, but the OPSTR_READ_SMS appop has been
+ // revoked then instead of immediately returning false the phone number access check should
+ // check if the caller has the READ_PHONE_NUMBERS permission and appop.
+ setupMocksForDeviceIdentifiersErrorPath();
+ doNothing().when(mMockContext).enforcePermission(
+ android.Manifest.permission.READ_SMS, PID, UID, MSG);
+ doNothing().when(mMockContext).enforcePermission(
+ android.Manifest.permission.READ_PHONE_NUMBERS, PID, UID, MSG);
+ when(mMockAppOps.noteOp(eq(AppOpsManager.OPSTR_READ_PHONE_NUMBERS), eq(UID), eq(PACKAGE),
+ eq(FEATURE), nullable(String.class))).thenReturn(AppOpsManager.MODE_ALLOWED);
+ assertTrue(TelephonyPermissions.checkReadPhoneNumber(
+ mMockContext, SUB_ID, PID, UID, PACKAGE, FEATURE, MSG));
+ }
+
+ @Test
+ public void testCheckReadPhoneNumber_hasReadSmsAndReadPhoneNumbersNoAppops() throws Exception {
+ // If an app has both the READ_SMS and READ_PHONE_NUMBERS permissions granted but does not
+ // have the corresponding appops instead of returning false for not having the appop granted
+ // a SecurityException should be thrown.
+ setupMocksForDeviceIdentifiersErrorPath();
+ doNothing().when(mMockContext).enforcePermission(
+ android.Manifest.permission.READ_SMS, PID, UID, MSG);
+ doNothing().when(mMockContext).enforcePermission(
+ android.Manifest.permission.READ_PHONE_NUMBERS, PID, UID, MSG);
+ try {
+ TelephonyPermissions.checkReadPhoneNumber(
+ mMockContext, SUB_ID, PID, UID, PACKAGE, FEATURE, MSG);
+ fail("Should have thrown SecurityException");
+ } catch (SecurityException e) {
+ // expected
+ }
+ }
@Test
public void testCheckReadDeviceIdentifiers_noPermissions() throws Exception {
@@ -288,8 +325,8 @@ public class TelephonyPermissionsTest {
// performed by a SystemAPI in PermissionManager; this test verifies when this API returns
// the calling package meets the requirements for device identifier access the telephony
// check also returns true.
- when(mMockLegacyPermissionManagerService.checkDeviceIdentifierAccess(PACKAGE, MSG, FEATURE,
- PID, UID)).thenReturn(PackageManager.PERMISSION_GRANTED);
+ when(mMockPermissionManagerService.checkDeviceIdentifierAccess(PACKAGE, MSG, FEATURE, PID,
+ UID)).thenReturn(PackageManager.PERMISSION_GRANTED);
assertTrue(
TelephonyPermissions.checkCallingOrSelfReadDeviceIdentifiers(mMockContext,
SUB_ID, PACKAGE, FEATURE, MSG));
@@ -436,7 +473,7 @@ public class TelephonyPermissionsTest {
*/
@Test
public void
- testEnforceCallingOrSelfReadPrecisePhoneStatePermissionOrCarrierPrivilege_noPermissions()
+ testEnforeceCallingOrSelfReadPrecisePhoneStatePermissionOrCarrierPrivilege_noPermissions()
throws Exception {
// revoke permission READ_PRIVILEGED_PHONE_STATE
when(mMockContext.checkCallingOrSelfPermission(
@@ -448,7 +485,7 @@ public class TelephonyPermissionsTest {
PackageManager.PERMISSION_DENIED);
try {
TelephonyPermissions
- .enforceCallingOrSelfReadPrecisePhoneStatePermissionOrCarrierPrivilege(
+ .enforeceCallingOrSelfReadPrecisePhoneStatePermissionOrCarrierPrivilege(
mMockContext, SUB_ID, MSG);
fail("Should have thrown SecurityException");
} catch (SecurityException se) {
@@ -462,7 +499,7 @@ public class TelephonyPermissionsTest {
*/
@Test
public void
- testEnforceCallingOrSelfReadPrecisePhoneStatePermissionOrCarrierPrivilege_withPermissions()
+ testEnforeceCallingOrSelfReadPrecisePhoneStatePermissionOrCarrierPrivilege_withPermissions()
throws Exception {
// grant READ_PRIVILEGED_PHONE_STATE permission
when(mMockContext.checkCallingOrSelfPermission(
@@ -470,7 +507,7 @@ public class TelephonyPermissionsTest {
PackageManager.PERMISSION_GRANTED);
try {
TelephonyPermissions
- .enforceCallingOrSelfReadPrecisePhoneStatePermissionOrCarrierPrivilege(
+ .enforeceCallingOrSelfReadPrecisePhoneStatePermissionOrCarrierPrivilege(
mMockContext, SUB_ID, MSG);
} catch (SecurityException se) {
fail();
@@ -487,7 +524,7 @@ public class TelephonyPermissionsTest {
PackageManager.PERMISSION_GRANTED);
try {
TelephonyPermissions
- .enforceCallingOrSelfReadPrecisePhoneStatePermissionOrCarrierPrivilege(
+ .enforeceCallingOrSelfReadPrecisePhoneStatePermissionOrCarrierPrivilege(
mMockContext, SUB_ID, MSG);
} catch (SecurityException se) {
fail();
@@ -499,7 +536,7 @@ public class TelephonyPermissionsTest {
*/
@Test
public void
- testEnforceCallingOrSelfReadPrecisePhoneStatePermissionOrCarrierPrivilege_withPrivileges()
+ testEnforeceCallingOrSelfReadPrecisePhoneStatePermissionOrCarrierPrivilege_withPrivileges()
throws Exception {
// revoke permission READ_PRIVILEGED_PHONE_STATE
when(mMockContext.checkCallingOrSelfPermission(
@@ -517,7 +554,7 @@ public class TelephonyPermissionsTest {
TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS);
try {
TelephonyPermissions
- .enforceCallingOrSelfReadPrecisePhoneStatePermissionOrCarrierPrivilege(
+ .enforeceCallingOrSelfReadPrecisePhoneStatePermissionOrCarrierPrivilege(
mMockContext, SUB_ID, MSG);
} catch (SecurityException se) {
fail("Should NOT throw SecurityException");
@@ -579,9 +616,7 @@ public class TelephonyPermissionsTest {
android.Manifest.permission.READ_DEVICE_CONFIG)).thenReturn(
PackageManager.PERMISSION_GRANTED);
- when(mMockLegacyPermissionManagerService.checkDeviceIdentifierAccess(any(), any(), any(),
- anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED);
- when(mMockLegacyPermissionManagerService.checkPhoneNumberAccess(any(), any(), any(),
+ when(mMockPermissionManagerService.checkDeviceIdentifierAccess(any(), any(), any(),
anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED);
// TelephonyPermissions queries DeviceConfig to determine if the identifier access
diff --git a/tests/telephonytests/src/com/android/internal/telephony/TelephonyRegistryTest.java b/tests/telephonytests/src/com/android/internal/telephony/TelephonyRegistryTest.java
index d14bbd0801..626dee2d86 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/TelephonyRegistryTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/TelephonyRegistryTest.java
@@ -15,8 +15,10 @@
*/
package com.android.internal.telephony;
-import static android.telephony.PhysicalChannelConfig.PHYSICAL_CELL_ID_UNKNOWN;
-import static android.telephony.ServiceState.FREQUENCY_RANGE_LOW;
+import static android.telephony.PhoneStateListener.LISTEN_ACTIVE_DATA_SUBSCRIPTION_ID_CHANGE;
+import static android.telephony.PhoneStateListener.LISTEN_PHONE_CAPABILITY_CHANGE;
+import static android.telephony.PhoneStateListener.LISTEN_RADIO_POWER_STATE_CHANGED;
+import static android.telephony.PhoneStateListener.LISTEN_SRVCC_STATE_CHANGED;
import static android.telephony.SubscriptionManager.ACTION_DEFAULT_SUBSCRIPTION_CHANGED;
import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
import static android.telephony.TelephonyManager.ACTION_MULTI_SIM_CONFIG_CHANGED;
@@ -25,34 +27,21 @@ import static android.telephony.TelephonyManager.RADIO_POWER_ON;
import static android.telephony.TelephonyManager.RADIO_POWER_UNAVAILABLE;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
-import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import android.content.Intent;
-import android.content.pm.UserInfo;
import android.net.LinkProperties;
-import android.os.RemoteException;
import android.os.ServiceManager;
-import android.os.UserHandle;
-import android.telephony.AccessNetworkConstants;
import android.telephony.Annotation;
-import android.telephony.CellIdentity;
-import android.telephony.CellIdentityGsm;
-import android.telephony.CellLocation;
-import android.telephony.LinkCapacityEstimate;
import android.telephony.PhoneCapability;
-import android.telephony.PhysicalChannelConfig;
+import android.telephony.PhoneStateListener;
import android.telephony.PreciseDataConnectionState;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
-import android.telephony.TelephonyCallback;
import android.telephony.TelephonyDisplayInfo;
import android.telephony.TelephonyManager;
import android.telephony.data.ApnSetting;
@@ -60,22 +49,16 @@ import android.test.suitebuilder.annotation.SmallTest;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
-import androidx.annotation.NonNull;
-
import com.android.server.TelephonyRegistry;
import org.junit.After;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.Executor;
+import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
@RunWith(AndroidTestingRunner.class)
@@ -83,82 +66,59 @@ import java.util.concurrent.atomic.AtomicInteger;
public class TelephonyRegistryTest extends TelephonyTest {
@Mock
private SubscriptionInfo mMockSubInfo;
- private TelephonyCallbackWrapper mTelephonyCallback;
- private List<LinkCapacityEstimate> mLinkCapacityEstimateList;
+ private PhoneStateListenerWrapper mPhoneStateListener;
private TelephonyRegistry mTelephonyRegistry;
private PhoneCapability mPhoneCapability;
private int mActiveSubId;
private TelephonyDisplayInfo mTelephonyDisplayInfo;
private int mSrvccState = -1;
private int mRadioPowerState = RADIO_POWER_UNAVAILABLE;
- private List<PhysicalChannelConfig> mPhysicalChannelConfigs;
- private TelephonyRegistry.ConfigurationProvider mMockConfigurationProvider;
- private CellLocation mCellLocation;
-
- // All events contribute to TelephonyRegistry#isPhoneStatePermissionRequired
- private static final Set<Integer> READ_PHONE_STATE_EVENTS;
- static {
- READ_PHONE_STATE_EVENTS = new HashSet<>();
- READ_PHONE_STATE_EVENTS.add(TelephonyCallback.EVENT_CALL_FORWARDING_INDICATOR_CHANGED);
- READ_PHONE_STATE_EVENTS.add(TelephonyCallback.EVENT_MESSAGE_WAITING_INDICATOR_CHANGED);
- READ_PHONE_STATE_EVENTS.add(TelephonyCallback.EVENT_EMERGENCY_NUMBER_LIST_CHANGED);
- }
-
- // All events contribute to TelephonyRegistry#isPrecisePhoneStatePermissionRequired
- private static final Set<Integer> READ_PRECISE_PHONE_STATE_EVENTS;
- static {
- READ_PRECISE_PHONE_STATE_EVENTS = new HashSet<>();
- READ_PRECISE_PHONE_STATE_EVENTS.add(
- TelephonyCallback.EVENT_PRECISE_CALL_STATE_CHANGED);
- READ_PRECISE_PHONE_STATE_EVENTS.add(
- TelephonyCallback.EVENT_PRECISE_DATA_CONNECTION_STATE_CHANGED);
- READ_PRECISE_PHONE_STATE_EVENTS.add(
- TelephonyCallback.EVENT_CALL_DISCONNECT_CAUSE_CHANGED);
- READ_PRECISE_PHONE_STATE_EVENTS.add(
- TelephonyCallback.EVENT_CALL_ATTRIBUTES_CHANGED);
- READ_PRECISE_PHONE_STATE_EVENTS.add(
- TelephonyCallback.EVENT_IMS_CALL_DISCONNECT_CAUSE_CHANGED);
- READ_PRECISE_PHONE_STATE_EVENTS.add(TelephonyCallback.EVENT_REGISTRATION_FAILURE);
- READ_PRECISE_PHONE_STATE_EVENTS.add(TelephonyCallback.EVENT_BARRING_INFO_CHANGED);
- READ_PRECISE_PHONE_STATE_EVENTS.add(
- TelephonyCallback.EVENT_PHYSICAL_CHANNEL_CONFIG_CHANGED);
- READ_PRECISE_PHONE_STATE_EVENTS.add(TelephonyCallback.EVENT_DATA_ENABLED_CHANGED);
- }
-
- // All events contribute to TelephonyRegistry#isPrivilegedPhoneStatePermissionRequired
+ // All events contribute to TelephonyRegistry.ENFORCE_PHONE_STATE_PERMISSION_MASK
+ private static final Map<Integer, String> READ_PHONE_STATE_EVENTS = Map.of(
+ PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR,
+ "PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR",
+ PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR,
+ "PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR",
+ PhoneStateListener.LISTEN_EMERGENCY_NUMBER_LIST,
+ "PhoneStateListener.LISTEN_EMERGENCY_NUMBER_LIST");
+
+ // All events contribute to TelephonyRegistry.PRECISE_PHONE_STATE_PERMISSION_MASK
+ private static final Map<Integer, String> READ_PRECISE_PHONE_STATE_EVENTS = Map.of(
+ PhoneStateListener.LISTEN_PRECISE_CALL_STATE,
+ "PhoneStateListener.LISTEN_PRECISE_CALL_STATE",
+ PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE,
+ "PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE",
+ PhoneStateListener.LISTEN_CALL_DISCONNECT_CAUSES,
+ "PhoneStateListener.LISTEN_CALL_DISCONNECT_CAUSES",
+ PhoneStateListener.LISTEN_CALL_ATTRIBUTES_CHANGED,
+ "PhoneStateListener.LISTEN_CALL_ATTRIBUTES_CHANGED",
+ PhoneStateListener.LISTEN_IMS_CALL_DISCONNECT_CAUSES,
+ "PhoneStateListener.LISTEN_IMS_CALL_DISCONNECT_CAUSES",
+ PhoneStateListener.LISTEN_REGISTRATION_FAILURE,
+ "PhoneStateListener.LISTEN_REGISTRATION_FAILURE",
+ PhoneStateListener.LISTEN_BARRING_INFO,
+ "PhoneStateListener.LISTEN_BARRING_INFO");
+
+ // All events contribute to TelephonyRegistry.PREVILEGED_PHONE_STATE_PERMISSION_MASK
// TODO: b/148021947 will create the permission group with PREVILIGED_STATE_PERMISSION_MASK
- private static final Set<Integer> READ_PRIVILEGED_PHONE_STATE_EVENTS;
- static {
- READ_PRIVILEGED_PHONE_STATE_EVENTS = new HashSet<>();
- READ_PRIVILEGED_PHONE_STATE_EVENTS.add( TelephonyCallback.EVENT_SRVCC_STATE_CHANGED);
- READ_PRIVILEGED_PHONE_STATE_EVENTS.add( TelephonyCallback.EVENT_OEM_HOOK_RAW);
- READ_PRIVILEGED_PHONE_STATE_EVENTS.add( TelephonyCallback.EVENT_RADIO_POWER_STATE_CHANGED);
- READ_PRIVILEGED_PHONE_STATE_EVENTS.add(
- TelephonyCallback.EVENT_VOICE_ACTIVATION_STATE_CHANGED);
- READ_PRIVILEGED_PHONE_STATE_EVENTS.add(
- TelephonyCallback.EVENT_ALLOWED_NETWORK_TYPE_LIST_CHANGED);
- }
-
- // All events contribute to TelephonyRegistry#isActiveEmergencySessionPermissionRequired
- private static final Set<Integer> READ_ACTIVE_EMERGENCY_SESSION_EVENTS;
- static {
- READ_ACTIVE_EMERGENCY_SESSION_EVENTS = new HashSet<>();
- READ_ACTIVE_EMERGENCY_SESSION_EVENTS.add(
- TelephonyCallback.EVENT_OUTGOING_EMERGENCY_CALL);
- READ_ACTIVE_EMERGENCY_SESSION_EVENTS.add(
- TelephonyCallback.EVENT_OUTGOING_EMERGENCY_SMS);
- }
-
- public class TelephonyCallbackWrapper extends TelephonyCallback implements
- TelephonyCallback.SrvccStateListener,
- TelephonyCallback.PhoneCapabilityListener,
- TelephonyCallback.ActiveDataSubscriptionIdListener,
- TelephonyCallback.RadioPowerStateListener,
- TelephonyCallback.PreciseDataConnectionStateListener,
- TelephonyCallback.DisplayInfoListener,
- TelephonyCallback.LinkCapacityEstimateChangedListener,
- TelephonyCallback.PhysicalChannelConfigListener,
- TelephonyCallback.CellLocationListener {
+ private static final Map<Integer, String> READ_PREVILIGED_PHONE_STATE_EVENTS = Map.of(
+ PhoneStateListener.LISTEN_SRVCC_STATE_CHANGED,
+ "PhoneStateListener.LISTEN_SRVCC_STATE_CHANGED",
+ PhoneStateListener.LISTEN_OEM_HOOK_RAW_EVENT,
+ "PhoneStateListener.LISTEN_OEM_HOOK_RAW_EVENT",
+ PhoneStateListener.LISTEN_RADIO_POWER_STATE_CHANGED,
+ "PhoneStateListener.LISTEN_RADIO_POWER_STATE_CHANGED",
+ PhoneStateListener.LISTEN_VOICE_ACTIVATION_STATE,
+ "PhoneStateListener.LISTEN_VOICE_ACTIVATION_STATE");
+
+ // All events contribute to TelephonyRegistry.READ_ACTIVE_EMERGENCY_SESSION_PERMISSION_MASK
+ private static final Map<Integer, String> READ_ACTIVE_EMERGENCY_SESSION_EVENTS = Map.of(
+ PhoneStateListener.LISTEN_OUTGOING_EMERGENCY_CALL,
+ "PhoneStateListener.LISTEN_OUTGOING_EMERGENCY_CALL",
+ PhoneStateListener.LISTEN_OUTGOING_EMERGENCY_SMS,
+ "PhoneStateListener.LISTEN_OUTGOING_EMERGENCY_SMS");
+
+ public class PhoneStateListenerWrapper extends PhoneStateListener {
// This class isn't mockable to get invocation counts because the IBinder is null and
// crashes the TelephonyRegistry. Make a cheesy verify(times()) alternative.
public AtomicInteger invocationCount = new AtomicInteger(0);
@@ -192,22 +152,6 @@ public class TelephonyRegistryTest extends TelephonyTest {
public void onDisplayInfoChanged(TelephonyDisplayInfo displayInfo) {
mTelephonyDisplayInfo = displayInfo;
}
-
- @Override
- public void onLinkCapacityEstimateChanged(
- List<LinkCapacityEstimate> linkCapacityEstimateList) {
- mLinkCapacityEstimateList = linkCapacityEstimateList;
- }
-
- @Override
- public void onCellLocationChanged(CellLocation location) {
- mCellLocation = location;
- }
-
- @Override
- public void onPhysicalChannelConfigChanged(@NonNull List<PhysicalChannelConfig> configs) {
- mPhysicalChannelConfigs = configs;
- }
}
private void addTelephonyRegistryService() {
@@ -215,34 +159,17 @@ public class TelephonyRegistryTest extends TelephonyTest {
mTelephonyRegistry.systemRunning();
}
- private Executor mSimpleExecutor = new Executor() {
- @Override
- public void execute(Runnable r) {
- r.run();
- }
- };
-
@Before
public void setUp() throws Exception {
super.setUp("TelephonyRegistryTest");
- mMockConfigurationProvider = mock(TelephonyRegistry.ConfigurationProvider.class);
- when(mMockConfigurationProvider.getRegistrationLimit()).thenReturn(-1);
- when(mMockConfigurationProvider.isRegistrationLimitEnabledInPlatformCompat(anyInt()))
+ TelephonyRegistry.ConfigurationProvider mockConfigurationProvider =
+ mock(TelephonyRegistry.ConfigurationProvider.class);
+ when(mockConfigurationProvider.getRegistrationLimit()).thenReturn(-1);
+ when(mockConfigurationProvider.isRegistrationLimitEnabledInPlatformCompat(anyInt()))
.thenReturn(false);
- when(mMockConfigurationProvider.isCallStateReadPhoneStateEnforcedInPlatformCompat(
- anyString(), any())).thenReturn(false);
- when(mMockConfigurationProvider.isActiveDataSubIdReadPhoneStateEnforcedInPlatformCompat(
- anyString(), any())).thenReturn(false);
- when(mMockConfigurationProvider.isCellInfoReadPhoneStateEnforcedInPlatformCompat(
- anyString(), any())).thenReturn(false);
- when(mMockConfigurationProvider.isDisplayInfoReadPhoneStateEnforcedInPlatformCompat(
- anyString(), any())).thenReturn(false);
- when(mMockConfigurationProvider.isDisplayInfoNrAdvancedSupported(
- anyString(), any())).thenReturn(false);
- mTelephonyRegistry = new TelephonyRegistry(mContext, mMockConfigurationProvider);
+ mTelephonyRegistry = new TelephonyRegistry(mContext, mockConfigurationProvider);
addTelephonyRegistryService();
- mTelephonyCallback = new TelephonyCallbackWrapper();
- mTelephonyCallback.init(mSimpleExecutor);
+ mPhoneStateListener = new PhoneStateListenerWrapper();
processAllMessages();
assertEquals(mTelephonyRegistry.asBinder(),
ServiceManager.getService("telephony.registry"));
@@ -259,31 +186,32 @@ public class TelephonyRegistryTest extends TelephonyTest {
doReturn(mMockSubInfo).when(mSubscriptionManager).getActiveSubscriptionInfo(anyInt());
doReturn(0/*slotIndex*/).when(mMockSubInfo).getSimSlotIndex();
// mTelephonyRegistry.listen with notifyNow = true should trigger callback immediately.
- PhoneCapability phoneCapability = new PhoneCapability(1, 2, null, false, new int[0]);
- int[] events = {TelephonyCallback.EVENT_PHONE_CAPABILITY_CHANGED};
+ PhoneCapability phoneCapability = new PhoneCapability(1, 2, 3, null, false);
mTelephonyRegistry.notifyPhoneCapabilityChanged(phoneCapability);
- mTelephonyRegistry.listenWithEventList(0, mContext.getOpPackageName(),
- mContext.getAttributionTag(), mTelephonyCallback.callback, events, true);
+ mTelephonyRegistry.listenWithFeature(mContext.getOpPackageName(),
+ mContext.getAttributionTag(), mPhoneStateListener.callback,
+ LISTEN_PHONE_CAPABILITY_CHANGE, true);
processAllMessages();
assertEquals(phoneCapability, mPhoneCapability);
// notifyPhoneCapabilityChanged with a new capability. Callback should be triggered.
- phoneCapability = new PhoneCapability(3, 2, null, false, new int[0]);
+ phoneCapability = new PhoneCapability(3, 2, 2, null, false);
mTelephonyRegistry.notifyPhoneCapabilityChanged(phoneCapability);
processAllMessages();
assertEquals(phoneCapability, mPhoneCapability);
}
+
@Test @SmallTest
public void testActiveDataSubChanged() {
// mTelephonyRegistry.listen with notifyNow = true should trigger callback immediately.
int[] activeSubs = {0, 1, 2};
- int[] events = {TelephonyCallback.EVENT_ACTIVE_DATA_SUBSCRIPTION_ID_CHANGED};
when(mSubscriptionManager.getActiveSubscriptionIdList()).thenReturn(activeSubs);
int activeSubId = 0;
mTelephonyRegistry.notifyActiveDataSubIdChanged(activeSubId);
- mTelephonyRegistry.listenWithEventList(activeSubId, mContext.getOpPackageName(),
- mContext.getAttributionTag(), mTelephonyCallback.callback, events, true);
+ mTelephonyRegistry.listenWithFeature(mContext.getOpPackageName(),
+ mContext.getAttributionTag(), mPhoneStateListener.callback,
+ LISTEN_ACTIVE_DATA_SUBSCRIPTION_ID_CHANGE, true);
processAllMessages();
assertEquals(activeSubId, mActiveSubId);
@@ -306,11 +234,11 @@ public class TelephonyRegistryTest extends TelephonyTest {
doReturn(mMockSubInfo).when(mSubscriptionManager).getActiveSubscriptionInfo(anyInt());
doReturn(0/*slotIndex*/).when(mMockSubInfo).getSimSlotIndex();
int srvccState = TelephonyManager.SRVCC_STATE_HANDOVER_STARTED;
- int[] events = {TelephonyCallback.EVENT_SRVCC_STATE_CHANGED};
mTelephonyRegistry.notifySrvccStateChanged(1 /*subId*/, srvccState);
// Should receive callback when listen is called that contains the latest notify result.
- mTelephonyRegistry.listenWithEventList(1 /*subId*/, mContext.getOpPackageName(),
- mContext.getAttributionTag(), mTelephonyCallback.callback, events, true);
+ mTelephonyRegistry.listenForSubscriber(1 /*subId*/, mContext.getOpPackageName(),
+ mContext.getAttributionTag(), mPhoneStateListener.callback,
+ LISTEN_SRVCC_STATE_CHANGED, true);
processAllMessages();
assertEquals(srvccState, mSrvccState);
@@ -331,11 +259,11 @@ public class TelephonyRegistryTest extends TelephonyTest {
// Clear all permission grants for test.
mContextFixture.addCallingOrSelfPermission("");
int srvccState = TelephonyManager.SRVCC_STATE_HANDOVER_STARTED;
- int[] events = {TelephonyCallback.EVENT_SRVCC_STATE_CHANGED};
mTelephonyRegistry.notifySrvccStateChanged(0 /*subId*/, srvccState);
try {
- mTelephonyRegistry.listenWithEventList(0 /*subId*/, mContext.getOpPackageName(),
- mContext.getAttributionTag(), mTelephonyCallback.callback, events, true);
+ mTelephonyRegistry.listenForSubscriber(0 /*subId*/, mContext.getOpPackageName(),
+ mContext.getAttributionTag(), mPhoneStateListener.callback,
+ LISTEN_SRVCC_STATE_CHANGED, true);
fail();
} catch (SecurityException e) {
// pass test!
@@ -347,9 +275,9 @@ public class TelephonyRegistryTest extends TelephonyTest {
*/
@Test
public void testMultiSimConfigChange() {
- int[] events = {TelephonyCallback.EVENT_RADIO_POWER_STATE_CHANGED};
- mTelephonyRegistry.listenWithEventList(1, mContext.getOpPackageName(),
- mContext.getAttributionTag(), mTelephonyCallback.callback, events, true);
+ mTelephonyRegistry.listenForSubscriber(1, mContext.getOpPackageName(),
+ mContext.getAttributionTag(), mPhoneStateListener.callback,
+ LISTEN_RADIO_POWER_STATE_CHANGED, true);
processAllMessages();
assertEquals(RADIO_POWER_UNAVAILABLE, mRadioPowerState);
@@ -379,108 +307,50 @@ public class TelephonyRegistryTest extends TelephonyTest {
@Test
public void testPreciseDataConnectionStateChanged() {
final int subId = 1;
- int[] events = {TelephonyCallback.EVENT_PRECISE_DATA_CONNECTION_STATE_CHANGED};
doReturn(mMockSubInfo).when(mSubscriptionManager).getActiveSubscriptionInfo(anyInt());
doReturn(0/*slotIndex*/).when(mMockSubInfo).getSimSlotIndex();
// Initialize the PSL with a PreciseDataConnection
mTelephonyRegistry.notifyDataConnectionForSubscriber(
- /*phoneId*/ 0, subId,
- new PreciseDataConnectionState.Builder()
- .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
- .setId(1)
- .setState(TelephonyManager.DATA_CONNECTED)
- .setNetworkType(TelephonyManager.NETWORK_TYPE_LTE)
- .setApnSetting(new ApnSetting.Builder()
- .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
- .setApnName("default")
- .setEntryName("default")
- .build())
- .setLinkProperties(new LinkProperties())
- .setFailCause(0)
- .build());
- mTelephonyRegistry.listenWithEventList(subId, mContext.getOpPackageName(),
- mContext.getAttributionTag(), mTelephonyCallback.callback, events, true);
+ /*phoneId*/ 0, subId, ApnSetting.TYPE_DEFAULT,
+ new PreciseDataConnectionState(
+ 0, 0, 0, "default", new LinkProperties(), 0, null));
+ mTelephonyRegistry.listenForSubscriber(subId, mContext.getOpPackageName(),
+ mContext.getAttributionTag(), mPhoneStateListener.callback,
+ PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE, true);
processAllMessages();
// Verify that the PDCS is reported for the only APN
- assertEquals(1, mTelephonyCallback.invocationCount.get());
+ assertEquals(mPhoneStateListener.invocationCount.get(), 1);
// Add IMS APN and verify that the listener is invoked for the IMS APN
mTelephonyRegistry.notifyDataConnectionForSubscriber(
- /*phoneId*/ 0, subId,
- new PreciseDataConnectionState.Builder()
- .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
- .setId(2)
- .setState(TelephonyManager.DATA_CONNECTED)
- .setNetworkType(TelephonyManager.NETWORK_TYPE_LTE)
- .setApnSetting(new ApnSetting.Builder()
- .setApnTypeBitmask(ApnSetting.TYPE_IMS)
- .setApnName("ims")
- .setEntryName("ims")
- .build())
- .setLinkProperties(new LinkProperties())
- .setFailCause(0)
- .build());
+ /*phoneId*/ 0, subId, ApnSetting.TYPE_IMS,
+ new PreciseDataConnectionState(
+ 0, 0, 0, "ims", new LinkProperties(), 0, null));
processAllMessages();
- assertEquals(mTelephonyCallback.invocationCount.get(), 2);
+ assertEquals(mPhoneStateListener.invocationCount.get(), 2);
// Unregister the listener
- mTelephonyRegistry.listenWithEventList(subId, mContext.getOpPackageName(),
- mContext.getAttributionTag(), mTelephonyCallback.callback, new int[0], true);
+ mTelephonyRegistry.listenForSubscriber(subId, mContext.getOpPackageName(),
+ mContext.getAttributionTag(), mPhoneStateListener.callback,
+ PhoneStateListener.LISTEN_NONE, true);
processAllMessages();
// Re-register the listener and ensure that both APN types are reported
- mTelephonyRegistry.listenWithEventList(subId, mContext.getOpPackageName(),
- mContext.getAttributionTag(), mTelephonyCallback.callback, events, true);
+ mTelephonyRegistry.listenForSubscriber(subId, mContext.getOpPackageName(),
+ mContext.getAttributionTag(), mPhoneStateListener.callback,
+ PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE, true);
processAllMessages();
- assertEquals(4, mTelephonyCallback.invocationCount.get());
+ assertEquals(mPhoneStateListener.invocationCount.get(), 4);
// Send a duplicate event to the TelephonyRegistry and verify that the listener isn't
// invoked.
mTelephonyRegistry.notifyDataConnectionForSubscriber(
- /*phoneId*/ 0, subId,
- new PreciseDataConnectionState.Builder()
- .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
- .setId(2)
- .setState(TelephonyManager.DATA_CONNECTED)
- .setNetworkType(TelephonyManager.NETWORK_TYPE_LTE)
- .setApnSetting(new ApnSetting.Builder()
- .setApnTypeBitmask(ApnSetting.TYPE_IMS)
- .setApnName("ims")
- .setEntryName("ims")
- .build())
- .setLinkProperties(new LinkProperties())
- .setFailCause(0)
- .build());
- processAllMessages();
- assertEquals(4, mTelephonyCallback.invocationCount.get());
- }
-
- @Test
- public void testPhysicalChannelConfigChanged() {
- // Return a slotIndex / phoneId of 0 for all sub ids given.
- doReturn(mMockSubInfo).when(mSubscriptionManager).getActiveSubscriptionInfo(anyInt());
- doReturn(0/*slotIndex*/).when(mMockSubInfo).getSimSlotIndex();
-
- final int subId = 1;
- int[] events = {TelephonyCallback.EVENT_PHYSICAL_CHANNEL_CONFIG_CHANGED};
- // Construct PhysicalChannelConfig with minimum fields set (The default value for
- // frequencyRange and band fields throw IAE)
- PhysicalChannelConfig config = new PhysicalChannelConfig.Builder()
- .setFrequencyRange(FREQUENCY_RANGE_LOW)
- .setBand(1)
- .setPhysicalCellId(2)
- .build();
- List<PhysicalChannelConfig> configs = new ArrayList<>(1);
- configs.add(config);
-
- mTelephonyRegistry.notifyPhysicalChannelConfigForSubscriber(0, subId, configs);
- mTelephonyRegistry.listenWithEventList(subId, mContext.getOpPackageName(),
- mContext.getAttributionTag(), mTelephonyCallback.callback, events, true);
+ /*phoneId*/ 0, subId, ApnSetting.TYPE_IMS,
+ new PreciseDataConnectionState(
+ 0, 0, 0, "ims", new LinkProperties(), 0, null));
processAllMessages();
-
- assertNotNull(mPhysicalChannelConfigs);
- assertEquals(PHYSICAL_CELL_ID_UNKNOWN, mPhysicalChannelConfigs.get(0).getPhysicalCellId());
+ assertEquals(mPhoneStateListener.invocationCount.get(), 4);
}
/**
@@ -490,86 +360,37 @@ public class TelephonyRegistryTest extends TelephonyTest {
public void testReadPhoneStatePermission() {
// Clear all permission grants for test.
mContextFixture.addCallingOrSelfPermission("");
- assertSecurityExceptionThrown(
- READ_PHONE_STATE_EVENTS.stream().mapToInt(i -> i).toArray());
+ for (Map.Entry<Integer, String> entry : READ_PHONE_STATE_EVENTS.entrySet()) {
+ assertSecurityExceptionThrown(entry.getKey(), entry.getValue());
+ }
- // Grant permission
+ // Grant permssion
mContextFixture.addCallingOrSelfPermission(android.Manifest.permission.READ_PHONE_STATE);
- assertSecurityExceptionNotThrown(
- READ_PHONE_STATE_EVENTS.stream().mapToInt(i -> i).toArray());
- }
-
- /**
- * Test enforcement of READ_PHONE_STATE for call state related events.
- */
- @Test
- public void testCallStateChangedPermission() {
- int[] events = new int[] {TelephonyCallback.EVENT_CALL_STATE_CHANGED,
- TelephonyCallback.EVENT_LEGACY_CALL_STATE_CHANGED};
- // Disable change ID for READ_PHONE_STATE enforcement
- when(mMockConfigurationProvider.isCallStateReadPhoneStateEnforcedInPlatformCompat(
- anyString(), any())).thenReturn(false);
- // Start without READ_PHONE_STATE permission
- mContextFixture.addCallingOrSelfPermission("");
- assertSecurityExceptionNotThrown(events);
- // Grant permission
- mContextFixture.addCallingOrSelfPermission(android.Manifest.permission.READ_PHONE_STATE);
- assertSecurityExceptionNotThrown(events);
- //Enable READ_PHONE_STATE enforcement
- when(mMockConfigurationProvider.isCallStateReadPhoneStateEnforcedInPlatformCompat(
- anyString(), any())).thenReturn(true);
- assertSecurityExceptionNotThrown(events);
- // revoke READ_PHONE_STATE permission
- mContextFixture.removeCallingOrSelfPermission(android.Manifest.permission.READ_PHONE_STATE);
- assertSecurityExceptionThrown(events);
-
+ for (Map.Entry<Integer, String> entry : READ_PHONE_STATE_EVENTS.entrySet()) {
+ assertSecurityExceptionNotThrown(entry.getKey(), entry.getValue());
+ }
}
/**
* Test listen to events that require READ_PRECISE_PHONE_STATE permission.
*/
+ // FIXME(b/159082270) - Simply not granting location permission doesn't fix the test because
+ // Location is soft-denied to apps that aren't in the foreground, and soft-denial currently
+ // short-circuits the test.
+ @Ignore("Skip due to b/159082270")
@Test
public void testReadPrecisePhoneStatePermission() {
// Clear all permission grants for test.
mContextFixture.addCallingOrSelfPermission("");
- // Many of the events require LOCATION permission, but without READ_PHONE_STATE, they will
- // still throw exceptions. Since this test is testing READ_PRECISE_PHONE_STATE, all other
- // permissions should be granted up-front.
- mContextFixture.addCallingOrSelfPermission(
- android.Manifest.permission.READ_PHONE_STATE);
- mContextFixture.addCallingOrSelfPermission(
- android.Manifest.permission.ACCESS_FINE_LOCATION);
- assertSecurityExceptionThrown(
- READ_PRECISE_PHONE_STATE_EVENTS.stream().mapToInt(i -> i).toArray());
+ for (Map.Entry<Integer, String> entry : READ_PRECISE_PHONE_STATE_EVENTS.entrySet()) {
+ assertSecurityExceptionThrown(entry.getKey(), entry.getValue());
+ }
- // Grant permission
+ // Grant permssion
mContextFixture.addCallingOrSelfPermission(
android.Manifest.permission.READ_PRECISE_PHONE_STATE);
- assertSecurityExceptionNotThrown(
- READ_PRECISE_PHONE_STATE_EVENTS.stream().mapToInt(i -> i).toArray());
-
- }
-
- /**
- * Test a bit-fiddling method in TelephonyRegistry
- */
- @Test
- public void testGetApnTypesStringFromBitmask() {
- {
- int mask = 0;
- assertEquals("", TelephonyRegistry.getApnTypesStringFromBitmask(mask));
- }
-
- {
- int mask = ApnSetting.TYPE_DEFAULT | ApnSetting.TYPE_MMS;
- assertEquals(String.join(
- ",", ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING),
- TelephonyRegistry.getApnTypesStringFromBitmask(mask));
- }
-
- {
- int mask = 1 << 31;
- assertEquals("", TelephonyRegistry.getApnTypesStringFromBitmask(mask));
+ for (Map.Entry<Integer, String> entry : READ_PRECISE_PHONE_STATE_EVENTS.entrySet()) {
+ assertSecurityExceptionNotThrown(entry.getKey(), entry.getValue());
}
}
@@ -580,14 +401,16 @@ public class TelephonyRegistryTest extends TelephonyTest {
public void testReadPrivilegedPhoneStatePermission() {
// Clear all permission grants for test.
mContextFixture.addCallingOrSelfPermission("");
- assertSecurityExceptionThrown(
- READ_PRIVILEGED_PHONE_STATE_EVENTS.stream().mapToInt(i -> i).toArray());
+ for (Map.Entry<Integer, String> entry : READ_PREVILIGED_PHONE_STATE_EVENTS.entrySet()) {
+ assertSecurityExceptionThrown(entry.getKey(), entry.getValue());
+ }
- // Grant permission
+ // Grant permssion
mContextFixture.addCallingOrSelfPermission(
android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE);
- assertSecurityExceptionNotThrown(
- READ_PRIVILEGED_PHONE_STATE_EVENTS.stream().mapToInt(i -> i).toArray());
+ for (Map.Entry<Integer, String> entry : READ_PREVILIGED_PHONE_STATE_EVENTS.entrySet()) {
+ assertSecurityExceptionNotThrown(entry.getKey(), entry.getValue());
+ }
}
/**
@@ -597,14 +420,16 @@ public class TelephonyRegistryTest extends TelephonyTest {
public void testReadActiveEmergencySessionPermission() {
// Clear all permission grants for test.
mContextFixture.addCallingOrSelfPermission("");
- assertSecurityExceptionThrown(
- READ_ACTIVE_EMERGENCY_SESSION_EVENTS.stream().mapToInt(i -> i).toArray());
+ for (Map.Entry<Integer, String> entry : READ_ACTIVE_EMERGENCY_SESSION_EVENTS.entrySet()) {
+ assertSecurityExceptionThrown(entry.getKey(), entry.getValue());
+ }
- // Grant permission
+ // Grant permssion
mContextFixture.addCallingOrSelfPermission(
android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION);
- assertSecurityExceptionNotThrown(
- READ_ACTIVE_EMERGENCY_SESSION_EVENTS.stream().mapToInt(i -> i).toArray());
+ for (Map.Entry<Integer, String> entry : READ_ACTIVE_EMERGENCY_SESSION_EVENTS.entrySet()) {
+ assertSecurityExceptionNotThrown(entry.getKey(), entry.getValue());
+ }
}
@Test
@@ -613,16 +438,12 @@ public class TelephonyRegistryTest extends TelephonyTest {
.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, 12)
.putExtra(SubscriptionManager.EXTRA_SLOT_INDEX, 0));
processAllMessages();
- int[] events = {TelephonyCallback.EVENT_DISPLAY_INFO_CHANGED};
- mTelephonyRegistry.listenWithEventList(2, mContext.getOpPackageName(),
- mContext.getAttributionTag(), mTelephonyCallback.callback, events, false);
- when(mMockConfigurationProvider.isDisplayInfoNrAdvancedSupported(
- anyString(), any())).thenReturn(true);
- TelephonyDisplayInfo displayInfo = new TelephonyDisplayInfo(
- TelephonyManager.NETWORK_TYPE_LTE,
- TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED);
+ mTelephonyRegistry.listenForSubscriber(2, mContext.getOpPackageName(),
+ mContext.getAttributionTag(), mPhoneStateListener.callback,
+ PhoneStateListener.LISTEN_DISPLAY_INFO_CHANGED, false);
// Notify with invalid subId on default phone. Should NOT trigger callback.
+ TelephonyDisplayInfo displayInfo = new TelephonyDisplayInfo(0, 0);
mTelephonyRegistry.notifyDisplayInfoChanged(0, INVALID_SUBSCRIPTION_ID, displayInfo);
processAllMessages();
assertEquals(null, mTelephonyDisplayInfo);
@@ -633,175 +454,21 @@ public class TelephonyRegistryTest extends TelephonyTest {
assertEquals(displayInfo, mTelephonyDisplayInfo);
}
- @Test
- public void testDisplayInfoCompatibility() {
- mContext.sendBroadcast(new Intent(ACTION_DEFAULT_SUBSCRIPTION_CHANGED)
- .putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, 12)
- .putExtra(SubscriptionManager.EXTRA_SLOT_INDEX, 0));
- processAllMessages();
- int[] events = {TelephonyCallback.EVENT_DISPLAY_INFO_CHANGED};
- mTelephonyRegistry.listenWithEventList(2, mContext.getOpPackageName(),
- mContext.getAttributionTag(), mTelephonyCallback.callback, events, false);
- when(mMockConfigurationProvider.isDisplayInfoNrAdvancedSupported(
- anyString(), any())).thenReturn(false);
- TelephonyDisplayInfo displayInfo = new TelephonyDisplayInfo(
- TelephonyManager.NETWORK_TYPE_LTE,
- TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED);
- TelephonyDisplayInfo expectDisplayInfo = new TelephonyDisplayInfo(
- TelephonyManager.NETWORK_TYPE_LTE,
- TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA_MMWAVE);
-
- // Notify with invalid subId on default phone. Should NOT trigger callback.
- mTelephonyRegistry.notifyDisplayInfoChanged(0, INVALID_SUBSCRIPTION_ID, displayInfo);
- processAllMessages();
- assertEquals(null, mTelephonyDisplayInfo);
-
- // Notify with the matching subId on default phone. Should trigger callback.
- mTelephonyRegistry.notifyDisplayInfoChanged(0, 2, displayInfo);
- processAllMessages();
- assertEquals(expectDisplayInfo, mTelephonyDisplayInfo);
- }
-
- @Test
- public void testDisplayInfoCompatibility_moreCallingPackages() {
- mContext.sendBroadcast(new Intent(ACTION_DEFAULT_SUBSCRIPTION_CHANGED)
- .putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, 12)
- .putExtra(SubscriptionManager.EXTRA_SLOT_INDEX, 0));
- processAllMessages();
- int[] events = {TelephonyCallback.EVENT_DISPLAY_INFO_CHANGED};
- TelephonyDisplayInfo displayInfo = new TelephonyDisplayInfo(
- TelephonyManager.NETWORK_TYPE_LTE,
- TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED);
- TelephonyDisplayInfo expectDisplayInfo = new TelephonyDisplayInfo(
- TelephonyManager.NETWORK_TYPE_LTE,
- TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA_MMWAVE);
- TelephonyCallback telephonyCallback2 = new TelephonyCallbackWrapper() {
- @Override
- public void onDisplayInfoChanged(TelephonyDisplayInfo displayInfoNotify) {
- assertEquals(displayInfo, displayInfoNotify);
- }
- };
- Executor mSimpleExecutor2 = new Executor() {
- @Override
- public void execute(Runnable r) {
- r.run();
- }
- };
- telephonyCallback2.init(mSimpleExecutor2);
- mTelephonyRegistry.listenWithEventList(2, "pkg1",
- mContext.getAttributionTag(), mTelephonyCallback.callback, events, false);
- mTelephonyRegistry.listenWithEventList(2, "pkg2",
- mContext.getAttributionTag(), telephonyCallback2.callback, events, false);
- when(mMockConfigurationProvider.isDisplayInfoNrAdvancedSupported(
- eq("pkg1"), any())).thenReturn(false);
- when(mMockConfigurationProvider.isDisplayInfoNrAdvancedSupported(
- eq("pkg2"), any())).thenReturn(true);
-
-
- // Notify with invalid subId on default phone. Should NOT trigger callback.
- mTelephonyRegistry.notifyDisplayInfoChanged(0, INVALID_SUBSCRIPTION_ID, displayInfo);
- processAllMessages();
- assertEquals(null, mTelephonyDisplayInfo);
-
- // Notify with the matching subId on default phone. Should trigger callback.
- mTelephonyRegistry.notifyDisplayInfoChanged(0, 2, displayInfo);
- processAllMessages();
- assertEquals(expectDisplayInfo, mTelephonyDisplayInfo);
- }
-
- @Test
- public void testNotifyCellLocationForSubscriberByUserSwitched() throws RemoteException {
- final int phoneId = 0;
- final int subId = 1;
-
- // Return a slotIndex / phoneId of 0 for subId 1.
- doReturn(new int[] {subId}).when(mSubscriptionController).getSubId(phoneId);
- doReturn(mMockSubInfo).when(mSubscriptionManager).getActiveSubscriptionInfo(subId);
- doReturn(phoneId).when(mMockSubInfo).getSimSlotIndex();
- mServiceManagerMockedServices.put("isub", mSubscriptionController);
- doReturn(mSubscriptionController).when(mSubscriptionController)
- .queryLocalInterface(anyString());
-
- UserInfo userInfo = new UserInfo(UserHandle.myUserId(), "" /* name */, 0 /* flags */);
- doReturn(userInfo.id).when(mIActivityManager).getCurrentUserId();
-
- doReturn(true).when(mLocationManager).isLocationEnabledForUser(any(UserHandle.class));
-
- CellIdentity cellIdentity = new CellIdentityGsm(-1, -1, -1, -1, null, null, null, null,
- Collections.emptyList());
- mTelephonyRegistry.notifyCellLocationForSubscriber(subId, cellIdentity);
- processAllMessages();
-
- // Listen to EVENT_CELL_LOCATION_CHANGED for the current user Id.
- int[] events = {TelephonyCallback.EVENT_CELL_LOCATION_CHANGED};
- mTelephonyRegistry.listenWithEventList(subId, mContext.getOpPackageName(),
- mContext.getAttributionTag(), mTelephonyCallback.callback, events, false);
-
- // Broadcast ACTION_USER_SWITCHED for USER_SYSTEM. Callback should be triggered.
- mCellLocation = null;
- mContext.sendBroadcast(new Intent(Intent.ACTION_USER_SWITCHED));
-
- processAllMessages();
- assertEquals(cellIdentity.asCellLocation(), mCellLocation);
-
- // Broadcast ACTION_USER_SWITCHED for the current user Id + 1. Callback shouldn't be
- // triggered.
- userInfo.id++;
- doReturn(userInfo.id).when(mIActivityManager).getCurrentUserId();
- mCellLocation = null;
- mContext.sendBroadcast(new Intent(Intent.ACTION_USER_SWITCHED));
-
- processAllMessages();
- assertEquals(null, mCellLocation);
- }
-
- private void assertSecurityExceptionThrown(int[] event) {
+ private void assertSecurityExceptionThrown(int event, String eventDesc) {
try {
- mTelephonyRegistry.listenWithEventList(
- SubscriptionManager.DEFAULT_SUBSCRIPTION_ID, mContext.getOpPackageName(),
- mContext.getAttributionTag(), mTelephonyCallback.callback, event, true);
- fail("SecurityException should throw without permission");
+ mTelephonyRegistry.listen(mContext.getOpPackageName(),
+ mPhoneStateListener.callback, event, true);
+ fail("SecurityException should throw when listen " + eventDesc + " without permission");
} catch (SecurityException expected) {
}
}
- private void assertSecurityExceptionNotThrown(int[] event) {
+ private void assertSecurityExceptionNotThrown(int event, String eventDesc) {
try {
- mTelephonyRegistry.listenWithEventList(
- SubscriptionManager.DEFAULT_SUBSCRIPTION_ID, mContext.getOpPackageName(),
- mContext.getAttributionTag(), mTelephonyCallback.callback, event, true);
+ mTelephonyRegistry.listen(mContext.getOpPackageName(),
+ mPhoneStateListener.callback, event, true);
} catch (SecurityException unexpected) {
- fail("SecurityException thrown with permission");
+ fail("SecurityException thrown when listen " + eventDesc + " with permission");
}
}
-
- @Test
- public void testNotifyLinkCapacityEstimateChanged() {
- mContext.sendBroadcast(new Intent(ACTION_DEFAULT_SUBSCRIPTION_CHANGED)
- .putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, 2)
- .putExtra(SubscriptionManager.EXTRA_SLOT_INDEX, 0));
- processAllMessages();
- int[] events = {TelephonyCallback.EVENT_LINK_CAPACITY_ESTIMATE_CHANGED};
- mTelephonyRegistry.listenWithEventList(2, mContext.getOpPackageName(),
- mContext.getAttributionTag(), mTelephonyCallback.callback,
- events, false);
-
- // Notify with invalid subId / phoneId on default phone. Should NOT trigger callback.
- List<LinkCapacityEstimate> lceList = new ArrayList<>();
- lceList.add(new LinkCapacityEstimate(LinkCapacityEstimate.LCE_TYPE_COMBINED, 4000,
- LinkCapacityEstimate.INVALID));
- mTelephonyRegistry.notifyLinkCapacityEstimateChanged(1, INVALID_SUBSCRIPTION_ID, lceList);
- processAllMessages();
- assertEquals(null, mLinkCapacityEstimateList);
-
- // Notify with invalid phoneId. Should NOT trigger callback.
- mTelephonyRegistry.notifyLinkCapacityEstimateChanged(2, 2, lceList);
- processAllMessages();
- assertEquals(null, mLinkCapacityEstimateList);
-
- // Notify with the matching subId on default phone. Should trigger callback.
- mTelephonyRegistry.notifyLinkCapacityEstimateChanged(0, 2, lceList);
- processAllMessages();
- assertEquals(lceList, mLinkCapacityEstimateList);
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/TelephonyTest.java b/tests/telephonytests/src/com/android/internal/telephony/TelephonyTest.java
index 2242d55cb9..b8277ad9e5 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/TelephonyTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/TelephonyTest.java
@@ -31,7 +31,6 @@ import static org.mockito.Mockito.eq;
import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.app.IActivityManager;
-import android.app.KeyguardManager;
import android.app.usage.NetworkStatsManager;
import android.content.ContentResolver;
import android.content.Context;
@@ -41,13 +40,7 @@ import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
-import android.location.LocationManager;
import android.net.ConnectivityManager;
-import android.net.NetworkCapabilities;
-import android.net.vcn.VcnManager;
-import android.net.vcn.VcnNetworkPolicyResult;
-import android.net.wifi.WifiInfo;
-import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
@@ -58,17 +51,14 @@ import android.os.MessageQueue;
import android.os.RegistrantList;
import android.os.ServiceManager;
import android.os.UserManager;
-import android.permission.LegacyPermissionManager;
+import android.permission.PermissionManager;
import android.provider.BlockedNumberContract;
import android.provider.DeviceConfig;
import android.provider.Settings;
import android.telephony.AccessNetworkConstants;
import android.telephony.CarrierConfigManager;
-import android.telephony.CellIdentity;
-import android.telephony.CellLocation;
import android.telephony.NetworkRegistrationInfo;
import android.telephony.ServiceState;
-import android.telephony.SignalStrength;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.telephony.TelephonyRegistryManager;
@@ -88,34 +78,28 @@ import com.android.internal.telephony.cdma.CdmaSubscriptionSourceManager;
import com.android.internal.telephony.cdma.EriManager;
import com.android.internal.telephony.dataconnection.DataEnabledOverride;
import com.android.internal.telephony.dataconnection.DataEnabledSettings;
-import com.android.internal.telephony.dataconnection.DataThrottler;
import com.android.internal.telephony.dataconnection.DcTracker;
-import com.android.internal.telephony.dataconnection.LinkBandwidthEstimator;
import com.android.internal.telephony.dataconnection.TransportManager;
import com.android.internal.telephony.emergency.EmergencyNumberTracker;
import com.android.internal.telephony.imsphone.ImsExternalCallTracker;
import com.android.internal.telephony.imsphone.ImsPhone;
import com.android.internal.telephony.imsphone.ImsPhoneCallTracker;
-import com.android.internal.telephony.metrics.ImsStats;
import com.android.internal.telephony.metrics.MetricsCollector;
import com.android.internal.telephony.metrics.PersistAtomsStorage;
-import com.android.internal.telephony.metrics.SmsStats;
import com.android.internal.telephony.metrics.VoiceCallSessionStats;
import com.android.internal.telephony.test.SimulatedCommands;
import com.android.internal.telephony.test.SimulatedCommandsVerifier;
import com.android.internal.telephony.uicc.IccCardStatus;
import com.android.internal.telephony.uicc.IccRecords;
import com.android.internal.telephony.uicc.IsimUiccRecords;
-import com.android.internal.telephony.uicc.PinStorage;
import com.android.internal.telephony.uicc.RuimRecords;
import com.android.internal.telephony.uicc.SIMRecords;
import com.android.internal.telephony.uicc.UiccCard;
import com.android.internal.telephony.uicc.UiccCardApplication;
import com.android.internal.telephony.uicc.UiccController;
import com.android.internal.telephony.uicc.UiccProfile;
-import com.android.internal.telephony.uicc.UiccSlot;
import com.android.server.pm.PackageManagerService;
-import com.android.server.pm.permission.LegacyPermissionManagerService;
+import com.android.server.pm.permission.PermissionManagerService;
import org.mockito.Mock;
import org.mockito.Mockito;
@@ -211,7 +195,7 @@ public abstract class TelephonyTest {
@Mock
protected PackageManagerService mMockPackageManager;
@Mock
- protected LegacyPermissionManagerService mMockLegacyPermissionManager;
+ protected PermissionManagerService mMockPermissionManager;
protected NetworkRegistrationInfo mNetworkRegistrationInfo =
new NetworkRegistrationInfo.Builder()
@@ -310,28 +294,6 @@ public abstract class TelephonyTest {
protected PersistAtomsStorage mPersistAtomsStorage;
@Mock
protected MetricsCollector mMetricsCollector;
- @Mock
- protected SmsStats mSmsStats;
- @Mock
- protected DataThrottler mDataThrottler;
- @Mock
- protected SignalStrength mSignalStrength;
- @Mock
- protected WifiManager mWifiManager;
- @Mock
- protected WifiInfo mWifiInfo;
- @Mock
- protected ImsStats mImsStats;
- @Mock
- protected LinkBandwidthEstimator mLinkBandwidthEstimator;
- @Mock
- protected PinStorage mPinStorage;
- @Mock
- protected LocationManager mLocationManager;
- @Mock
- protected CellIdentity mCellIdentity;
- @Mock
- protected CellLocation mCellLocation;
protected ActivityManager mActivityManager;
protected ImsCallProfile mImsCallProfile;
@@ -344,8 +306,6 @@ public abstract class TelephonyTest {
protected AppOpsManager mAppOpsManager;
protected CarrierConfigManager mCarrierConfigManager;
protected UserManager mUserManager;
- protected KeyguardManager mKeyguardManager;
- protected VcnManager mVcnManager;
protected SimulatedCommands mSimulatedCommands;
protected ContextFixture mContextFixture;
protected Context mContext;
@@ -357,6 +317,7 @@ public abstract class TelephonyTest {
protected List<TestableLooper> mTestableLoopers = new ArrayList<>();
protected TestableLooper mTestableLooper;
+ protected HashMap<Integer, ImsManager> mImsManagerInstances = new HashMap<>();
private HashMap<InstanceKey, Object> mOldInstances = new HashMap<InstanceKey, Object>();
private LinkedList<InstanceKey> mInstanceKeys = new LinkedList<InstanceKey>();
@@ -455,9 +416,6 @@ public abstract class TelephonyTest {
MockitoAnnotations.initMocks(this);
TelephonyManager.disableServiceHandleCaching();
SubscriptionController.disableCaching();
- // For testing do not allow Log.WTF as it can cause test process to crash
- Log.setWtfHandler((tagString, what, system) -> Log.d(TAG, "WTF captured, ignoring. Tag: "
- + tagString + ", exception: " + what));
mPhones = new Phone[] {mPhone};
mImsCallProfile = new ImsCallProfile();
@@ -488,9 +446,6 @@ public abstract class TelephonyTest {
mCarrierConfigManager =
(CarrierConfigManager) mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE);
mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
- mKeyguardManager = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
- mVcnManager = mContext.getSystemService(VcnManager.class);
- mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
//mTelephonyComponentFactory
doReturn(mTelephonyComponentFactory).when(mTelephonyComponentFactory).inject(anyString());
@@ -543,8 +498,6 @@ public abstract class TelephonyTest {
.makeDataEnabledSettings(nullable(Phone.class));
doReturn(mEriManager).when(mTelephonyComponentFactory)
.makeEriManager(nullable(Phone.class), anyInt());
- doReturn(mLinkBandwidthEstimator).when(mTelephonyComponentFactory)
- .makeLinkBandwidthEstimator(nullable(Phone.class));
//mPhone
doReturn(mContext).when(mPhone).getContext();
@@ -569,15 +522,9 @@ public abstract class TelephonyTest {
doReturn(mDataEnabledSettings).when(mPhone).getDataEnabledSettings();
doReturn(mDcTracker).when(mPhone).getDcTracker(anyInt());
doReturn(mCarrierPrivilegesTracker).when(mPhone).getCarrierPrivilegesTracker();
- doReturn(mSignalStrength).when(mPhone).getSignalStrength();
doReturn(mVoiceCallSessionStats).when(mPhone).getVoiceCallSessionStats();
doReturn(mVoiceCallSessionStats).when(mImsPhone).getVoiceCallSessionStats();
- doReturn(mSmsStats).when(mPhone).getSmsStats();
- doReturn(mImsStats).when(mImsPhone).getImsStats();
mIccSmsInterfaceManager.mDispatchersController = mSmsDispatchersController;
- doReturn(mLinkBandwidthEstimator).when(mPhone).getLinkBandwidthEstimator();
- doReturn(mCellIdentity).when(mPhone).getCurrentCellIdentity();
- doReturn(mCellLocation).when(mCellIdentity).asCellLocation();
//mUiccController
doReturn(mUiccCardApplication3gpp).when(mUiccController).getUiccCardApplication(anyInt(),
@@ -586,7 +533,6 @@ public abstract class TelephonyTest {
eq(UiccController.APP_FAM_3GPP2));
doReturn(mUiccCardApplicationIms).when(mUiccController).getUiccCardApplication(anyInt(),
eq(UiccController.APP_FAM_IMS));
- doReturn(mUiccCard).when(mUiccController).getUiccCard(anyInt());
doAnswer(new Answer<IccRecords>() {
public IccRecords answer(InvocationOnMock invocation) {
@@ -603,8 +549,6 @@ public abstract class TelephonyTest {
}
}
}).when(mUiccController).getIccRecords(anyInt(), anyInt());
- doReturn(new UiccSlot[] {}).when(mUiccController).getUiccSlots();
- doReturn(mPinStorage).when(mUiccController).getPinStorage();
//UiccCardApplication
doReturn(mSimRecords).when(mUiccCardApplication3gpp).getIccRecords();
@@ -638,6 +582,7 @@ public abstract class TelephonyTest {
doReturn(ServiceState.RIL_RADIO_TECHNOLOGY_UMTS).when(mServiceState).
getRilDataRadioTechnology();
doReturn(mPhone).when(mCT).getPhone();
+ mImsManagerInstances.put(mPhone.getPhoneId(), mImsManager);
doReturn(mImsEcbm).when(mImsManager).getEcbmInterface();
doReturn(mPhone).when(mInboundSmsHandler).getPhone();
doReturn(mImsCallProfile).when(mImsCall).getCallProfile();
@@ -655,8 +600,8 @@ public abstract class TelephonyTest {
mSST.mRestrictedState = mRestrictedState;
mServiceManagerMockedServices.put("connectivity_metrics_logger", mConnMetLoggerBinder);
mServiceManagerMockedServices.put("package", mMockPackageManager);
- mServiceManagerMockedServices.put("legacy_permission", mMockLegacyPermissionManager);
- logd("mMockLegacyPermissionManager replaced");
+ mServiceManagerMockedServices.put("permissionmgr", mMockPermissionManager);
+ logd("mMockPermissionManager replaced");
doReturn(new int[]{AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
AccessNetworkConstants.TRANSPORT_TYPE_WLAN})
.when(mTransportManager).getAvailableTransports();
@@ -668,18 +613,6 @@ public abstract class TelephonyTest {
doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
anyInt(), anyInt());
doReturn(new HalVersion(1, 4)).when(mPhone).getHalVersion();
- doReturn(2).when(mSignalStrength).getLevel();
-
- // WiFi
- doReturn(mWifiInfo).when(mWifiManager).getConnectionInfo();
- doReturn(2).when(mWifiManager).calculateSignalLevel(anyInt());
- doReturn(4).when(mWifiManager).getMaxSignalLevel();
-
- doAnswer(invocation -> {
- NetworkCapabilities nc = invocation.getArgument(0);
- return new VcnNetworkPolicyResult(
- false /* isTearDownRequested */, nc);
- }).when(mVcnManager).applyVcnNetworkPolicy(any(), any());
//SIM
doReturn(1).when(mTelephonyManager).getSimCount();
@@ -698,8 +631,6 @@ public abstract class TelephonyTest {
Settings.Global.putInt(resolver, Settings.Global.DEVICE_PROVISIONED, 1);
Settings.Global.putInt(resolver,
Settings.Global.DEVICE_PROVISIONING_MOBILE_DATA_ENABLED, 1);
- doReturn(mDataThrottler).when(mDcTracker).getDataThrottler();
- doReturn(-1L).when(mDataThrottler).getRetryTime(anyInt());
// CellularNetworkValidator
doReturn(SubscriptionManager.INVALID_PHONE_INDEX)
@@ -709,7 +640,6 @@ public abstract class TelephonyTest {
// Metrics
doReturn(null).when(mContext).getFileStreamPath(anyString());
doReturn(mPersistAtomsStorage).when(mMetricsCollector).getAtomsStorage();
- doReturn(mWifiManager).when(mContext).getSystemService(eq(Context.WIFI_SERVICE));
//Use reflection to mock singletons
replaceInstance(CallManager.class, "INSTANCE", null, mCallManager);
@@ -717,6 +647,7 @@ public abstract class TelephonyTest {
mTelephonyComponentFactory);
replaceInstance(UiccController.class, "mInstance", null, mUiccController);
replaceInstance(CdmaSubscriptionSourceManager.class, "sInstance", null, mCdmaSSM);
+ replaceInstance(ImsManager.class, "sImsManagerInstances", null, mImsManagerInstances);
replaceInstance(SubscriptionController.class, "sInstance", null, mSubscriptionController);
replaceInstance(ProxyController.class, "sProxyController", null, mProxyController);
replaceInstance(ActivityManager.class, "IActivityManagerSingleton", null,
@@ -865,21 +796,12 @@ public abstract class TelephonyTest {
// TelephonyPermissions uses a SystemAPI to check if the calling package meets any of the
// generic requirements for device identifier access (currently READ_PRIVILEGED_PHONE_STATE,
- // appop, and device / profile owner checks). This sets up the PermissionManager to return
+ // appop, and device / profile owner checks. This sets up the PermissionManager to return
// that access requirements are met.
setIdentifierAccess(true);
- LegacyPermissionManager legacyPermissionManager =
- new LegacyPermissionManager(mMockLegacyPermissionManager);
- doReturn(legacyPermissionManager).when(mContext)
- .getSystemService(Context.LEGACY_PERMISSION_SERVICE);
- // Also make sure all appop checks fails, to not interfere tests. Tests should explicitly
- // mock AppOpManager to return allowed/default mode. Note by default a mock returns 0 which
- // is MODE_ALLOWED, hence this setup is necessary.
- doReturn(AppOpsManager.MODE_IGNORED).when(mAppOpsManager).noteOpNoThrow(
- /* op= */ anyString(), /* uid= */ anyInt(),
- /* packageName= */ nullable(String.class),
- /* attributionTag= */ nullable(String.class),
- /* message= */ nullable(String.class));
+ PermissionManager permissionManager = new PermissionManager(mContext, null,
+ mMockPermissionManager);
+ doReturn(permissionManager).when(mContext).getSystemService(eq(Context.PERMISSION_SERVICE));
// TelephonyPermissions queries DeviceConfig to determine if the identifier access
// restrictions should be enabled; this results in a NPE when DeviceConfig uses
@@ -906,13 +828,9 @@ public abstract class TelephonyTest {
protected void setIdentifierAccess(boolean hasAccess) {
doReturn(hasAccess ? PackageManager.PERMISSION_GRANTED
- : PackageManager.PERMISSION_DENIED).when(mMockLegacyPermissionManager)
- .checkDeviceIdentifierAccess(any(), any(), any(), anyInt(), anyInt());
- }
-
- protected void setPhoneNumberAccess(int value) {
- doReturn(value).when(mMockLegacyPermissionManager).checkPhoneNumberAccess(any(), any(),
- any(), anyInt(), anyInt());
+ : PackageManager.PERMISSION_DENIED).when(
+ mMockPermissionManager).checkDeviceIdentifierAccess(any(), any(), any(), anyInt(),
+ anyInt());
}
protected void setCarrierPrivileges(boolean hasCarrierPrivileges) {
@@ -930,19 +848,6 @@ public abstract class TelephonyTest {
mockTelephonyManager).getCarrierPrivilegeStatus(anyInt());
}
- protected final void waitForDelayedHandlerAction(Handler h, long delayMillis,
- long timeoutMillis) {
- final CountDownLatch lock = new CountDownLatch(1);
- h.postDelayed(lock::countDown, delayMillis);
- while (lock.getCount() > 0) {
- try {
- lock.await(delayMillis + timeoutMillis, TimeUnit.MILLISECONDS);
- } catch (InterruptedException e) {
- // do nothing
- }
- }
- }
-
protected final void waitForHandlerAction(Handler h, long timeoutMillis) {
final CountDownLatch lock = new CountDownLatch(1);
h.post(lock::countDown);
diff --git a/tests/telephonytests/src/com/android/internal/telephony/TestExecutorService.java b/tests/telephonytests/src/com/android/internal/telephony/TestExecutorService.java
deleted file mode 100644
index b2d3315c37..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/TestExecutorService.java
+++ /dev/null
@@ -1,274 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.internal.telephony;
-
-import android.util.Log;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.concurrent.Callable;
-import java.util.concurrent.Delayed;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-
-public class TestExecutorService implements ScheduledExecutorService {
- private static final String TAG = "TestExecutorService";
-
- private class CompletedFuture<T> implements Future<T>, ScheduledFuture<T> {
-
- private final Callable<T> mTask;
- private final long mDelayMs;
- private Runnable mRunnable;
-
- CompletedFuture(Callable<T> task) {
- mTask = task;
- mDelayMs = 0;
- }
-
- CompletedFuture(Callable<T> task, long delayMs) {
- mTask = task;
- mDelayMs = delayMs;
- }
-
- CompletedFuture(Runnable task, long delayMs) {
- mRunnable = task;
- mTask = (Callable<T>) Executors.callable(task);
- mDelayMs = delayMs;
- }
-
- @Override
- public boolean cancel(boolean mayInterruptIfRunning) {
- cancelRunnable(mRunnable);
- return true;
- }
-
- @Override
- public boolean isCancelled() {
- return false;
- }
-
- @Override
- public boolean isDone() {
- return true;
- }
-
- @Override
- public T get() throws InterruptedException, ExecutionException {
- try {
- return mTask.call();
- } catch (Exception e) {
- throw new ExecutionException(e);
- }
- }
-
- @Override
- public T get(long timeout, TimeUnit unit)
- throws InterruptedException, ExecutionException, TimeoutException {
- try {
- return mTask.call();
- } catch (Exception e) {
- throw new ExecutionException(e);
- }
- }
-
- @Override
- public long getDelay(TimeUnit unit) {
- if (unit == TimeUnit.MILLISECONDS) {
- return mDelayMs;
- } else {
- // not implemented
- return 0;
- }
- }
-
- @Override
- public int compareTo(Delayed o) {
- if (o == null) return 1;
- if (o.getDelay(TimeUnit.MILLISECONDS) > mDelayMs) return -1;
- if (o.getDelay(TimeUnit.MILLISECONDS) < mDelayMs) return 1;
- return 0;
- }
- }
-
- private long mClock = 0;
- private Map<Long, Runnable> mScheduledRunnables = new HashMap<>();
- private Map<Runnable, Long> mRepeatDuration = new HashMap<>();
-
- @Override
- public void shutdown() {
- }
-
- @Override
- public List<Runnable> shutdownNow() {
- return null;
- }
-
- @Override
- public boolean isShutdown() {
- return false;
- }
-
- @Override
- public boolean isTerminated() {
- return false;
- }
-
- @Override
- public boolean awaitTermination(long timeout, TimeUnit unit) {
- return false;
- }
-
- @Override
- public <T> Future<T> submit(Callable<T> task) {
- return new com.android.internal.telephony.TestExecutorService.CompletedFuture<>(task);
- }
-
- @Override
- public <T> Future<T> submit(Runnable task, T result) {
- throw new UnsupportedOperationException("Not implemented");
- }
-
- @Override
- public Future<?> submit(Runnable task) {
- task.run();
- return new com.android.internal.telephony.TestExecutorService.CompletedFuture<>(() -> null);
- }
-
- @Override
- public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
- throw new UnsupportedOperationException("Not implemented");
- }
-
- @Override
- public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout,
- TimeUnit unit) {
- throw new UnsupportedOperationException("Not implemented");
- }
-
- @Override
- public <T> T invokeAny(Collection<? extends Callable<T>> tasks) {
- throw new UnsupportedOperationException("Not implemented");
- }
-
- @Override
- public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) {
- throw new UnsupportedOperationException("Not implemented");
- }
-
- @Override
- public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
- // Schedule the runnable for execution at the specified time.
- long scheduledTime = getNextExecutionTime(delay, unit);
- mScheduledRunnables.put(scheduledTime, command);
-
- Log.i(TAG, "schedule: runnable=" + System.identityHashCode(command) + ", time="
- + scheduledTime);
-
- return new com.android.internal.telephony.TestExecutorService.CompletedFuture<Runnable>(
- command, delay);
- }
-
- @Override
- public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
- throw new UnsupportedOperationException("Not implemented");
- }
-
- @Override
- public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period,
- TimeUnit unit) {
- return scheduleWithFixedDelay(command, initialDelay, period, unit);
- }
-
- @Override
- public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay,
- long delay, TimeUnit unit) {
- // Schedule the runnable for execution at the specified time.
- long nextScheduledTime = getNextExecutionTime(delay, unit);
- mScheduledRunnables.put(nextScheduledTime, command);
- mRepeatDuration.put(command, unit.toMillis(delay));
-
- return new com.android.internal.telephony.TestExecutorService.CompletedFuture<Runnable>(
- command, delay);
- }
-
- private long getNextExecutionTime(long delay, TimeUnit unit) {
- long delayMillis = unit.toMillis(delay);
- return mClock + delayMillis;
- }
-
- @Override
- public void execute(Runnable command) {
- command.run();
- }
-
- /**
- * Used in unit tests, used to add a delta to the "clock" so that we can fire off scheduled
- * items and reschedule the repeats.
- * @param duration The duration (millis) to add to the clock.
- */
- public void advanceTime(long duration) {
- Map<Long, Runnable> nextRepeats = new HashMap<>();
- List<Runnable> toRun = new ArrayList<>();
- mClock += duration;
- Iterator<Map.Entry<Long, Runnable>> iterator = mScheduledRunnables.entrySet().iterator();
- while (iterator.hasNext()) {
- Map.Entry<Long, Runnable> entry = iterator.next();
- if (mClock >= entry.getKey()) {
- toRun.add(entry.getValue());
-
- Runnable r = entry.getValue();
- Log.i(TAG, "advanceTime: runningRunnable=" + System.identityHashCode(r));
- // If this is a repeating scheduled item, schedule the repeat.
- if (mRepeatDuration.containsKey(r)) {
- // schedule next execution
- nextRepeats.put(mClock + mRepeatDuration.get(r), entry.getValue());
- }
- iterator.remove();
- }
- }
-
- // Update things at the end to avoid concurrent access.
- mScheduledRunnables.putAll(nextRepeats);
- toRun.forEach(r -> r.run());
- }
-
- /**
- * Used from a {@link CompletedFuture} as defined above to cancel a scheduled task.
- * @param r The runnable to cancel.
- */
- private void cancelRunnable(Runnable r) {
- Optional<Map.Entry<Long, Runnable>> found = mScheduledRunnables.entrySet().stream()
- .filter(e -> e.getValue() == r)
- .findFirst();
- if (found.isPresent()) {
- mScheduledRunnables.remove(found.get().getKey());
- }
- mRepeatDuration.remove(r);
- Log.i(TAG, "cancelRunnable: runnable=" + System.identityHashCode(r));
- }
-}
-
diff --git a/tests/telephonytests/src/com/android/internal/telephony/WapPushOverSmsTest.java b/tests/telephonytests/src/com/android/internal/telephony/WapPushOverSmsTest.java
index ca1fca8b0d..48adb64d41 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/WapPushOverSmsTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/WapPushOverSmsTest.java
@@ -29,6 +29,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.AppOpsManager;
+import android.content.BroadcastReceiver;
import android.content.Intent;
import android.os.Bundle;
import android.os.UserHandle;
@@ -91,7 +92,7 @@ public class WapPushOverSmsTest extends TelephonyTest {
eq(android.Manifest.permission.RECEIVE_WAP_PUSH),
eq(AppOpsManager.OPSTR_RECEIVE_WAP_PUSH),
nullable(Bundle.class),
- isNull(InboundSmsHandler.SmsBroadcastReceiver.class),
+ isNull(BroadcastReceiver.class),
eq(UserHandle.SYSTEM),
anyInt());
Intent intent = intentArgumentCaptor.getValue();
@@ -146,7 +147,7 @@ public class WapPushOverSmsTest extends TelephonyTest {
any(String.class),
any(String.class),
any(Bundle.class),
- any(InboundSmsHandler.SmsBroadcastReceiver.class),
+ any(BroadcastReceiver.class),
any(UserHandle.class),
anyInt());
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/cdma/CdmaInboundSmsHandlerTest.java b/tests/telephonytests/src/com/android/internal/telephony/cdma/CdmaInboundSmsHandlerTest.java
index 68831f66d8..a6d30f90af 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/cdma/CdmaInboundSmsHandlerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/cdma/CdmaInboundSmsHandlerTest.java
@@ -130,20 +130,18 @@ public class CdmaInboundSmsHandlerTest extends TelephonyTest {
"1234567890", /* displayAddress */
"This is the message body of a single-part message" /* messageBody */,
false, /* isClass0 */
- mSubId0,
- InboundSmsHandler.SOURCE_NOT_INJECTED);
+ mSubId0);
doReturn(mInboundSmsTracker).when(mTelephonyComponentFactory)
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
anyBoolean(), nullable(String.class), nullable(String.class),
- nullable(String.class), anyBoolean(), anyInt(), anyInt());
+ nullable(String.class), anyBoolean(), anyInt());
doReturn(mInboundSmsTracker).when(mTelephonyComponentFactory)
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
nullable(String.class), nullable(String.class), anyInt(), anyInt(),
- anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt(),
- anyInt());
+ anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt());
doReturn(mInboundSmsTracker).when(mTelephonyComponentFactory)
.makeInboundSmsTracker(any(Context.class), nullable(Cursor.class), anyBoolean());
@@ -236,13 +234,12 @@ public class CdmaInboundSmsHandlerTest extends TelephonyTest {
blockedNumber, /* displayAddress */
"This is the message body of a single-part message" /* messageBody */,
false, /* isClass0 */
- mSubId0,
- InboundSmsHandler.SOURCE_NOT_INJECTED);
+ mSubId0);
doReturn(mInboundSmsTracker).when(mTelephonyComponentFactory)
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
anyBoolean(), nullable(String.class), nullable(String.class),
- nullable(String.class), anyBoolean(), anyInt(), anyInt());
+ nullable(String.class), anyBoolean(), anyInt());
mFakeBlockedNumberContentProvider.mBlockedNumbers.add(blockedNumber);
transitionFromStartupToIdle();
diff --git a/tests/telephonytests/src/com/android/internal/telephony/cdma/CdmaSmsCbTest.java b/tests/telephonytests/src/com/android/internal/telephony/cdma/CdmaSmsCbTest.java
index 0dc96476ab..3d707dacaf 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/cdma/CdmaSmsCbTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/cdma/CdmaSmsCbTest.java
@@ -65,7 +65,7 @@ public class CdmaSmsCbTest extends AndroidTestCase {
msg.isServicePresent = true;
msg.serviceCategory = serviceCategory;
- // placeholder address (RIL may generate a different placeholder address for broadcasts)
+ // dummy address (RIL may generate a different dummy address for broadcasts)
msg.address.digitMode = CdmaSmsAddress.DIGIT_MODE_4BIT_DTMF;
msg.address.numberMode = CdmaSmsAddress.NUMBER_MODE_NOT_DATA_NETWORK;
msg.address.numberType = CdmaSmsAddress.TON_UNKNOWN;
@@ -601,7 +601,7 @@ public class CdmaSmsCbTest extends AndroidTestCase {
msg.isServicePresent = false;
msg.serviceCategory = 0;
- // placeholder address (RIL may generate a different placeholder address for broadcasts)
+ // dummy address (RIL may generate a different dummy address for broadcasts)
msg.address.digitMode = CdmaSmsAddress.DIGIT_MODE_4BIT_DTMF;
msg.address.numberMode = CdmaSmsAddress.NUMBER_MODE_NOT_DATA_NETWORK;
msg.address.numberType = CdmaSmsAddress.TON_UNKNOWN;
diff --git a/tests/telephonytests/src/com/android/internal/telephony/d2d/CommunicatorTest.java b/tests/telephonytests/src/com/android/internal/telephony/d2d/CommunicatorTest.java
deleted file mode 100644
index 5681dc444f..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/d2d/CommunicatorTest.java
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.internal.telephony.d2d;
-
-import static junit.framework.Assert.assertEquals;
-
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.verify;
-
-import android.telecom.Connection;
-import android.test.suitebuilder.annotation.SmallTest;
-import android.util.ArraySet;
-
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Captor;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-
-@RunWith(AndroidJUnit4.class)
-public class CommunicatorTest {
- private List<TransportProtocol> mTransportProtocols = new ArrayList<>();
- private TransportProtocol.Callback mCallback;
- private Communicator mCommunicator;
- @Mock
- private Communicator.Callback mCommunicatorCallback;
- @Captor
- private ArgumentCaptor<Set<Communicator.Message>> mMessagesCaptor;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- TransportProtocol protocol1 = getMockTransportProtocol();
- TransportProtocol protocol2 = getMockTransportProtocol();
- mTransportProtocols.add(protocol1);
- mTransportProtocols.add(protocol2);
- }
-
- /**
- * Verifies that we can setup the communicator and negotiate a transport.
- */
- @SmallTest
- @Test
- public void testNegotiate() {
- mCommunicator = new Communicator(mTransportProtocols, mCommunicatorCallback);
- mCommunicator.onStateChanged(null, Connection.STATE_ACTIVE);
- verify(mTransportProtocols.get(0)).startNegotiation();
- assertEquals(mTransportProtocols.get(0), mCommunicator.getActiveTransport());
- // Assume negotiation on the first one failed.
- mCallback.onNegotiationFailed(mTransportProtocols.get(0));
- verify(mTransportProtocols.get(1)).startNegotiation();
- assertEquals(mTransportProtocols.get(1), mCommunicator.getActiveTransport());
- mCallback.onNegotiationSuccess(mTransportProtocols.get(1));
- verify(mCommunicatorCallback).onD2DAvailabilitychanged(eq(true));
- }
-
- /**
- * Verifies that D2D negotiation failed callback is invoked when D2D could not be negotiated.
- */
- @SmallTest
- @Test
- public void testNegotiationFailed() {
- mCommunicator = new Communicator(mTransportProtocols, mCommunicatorCallback);
- mCommunicator.onStateChanged(null, Connection.STATE_ACTIVE);
- verify(mTransportProtocols.get(0)).startNegotiation();
- assertEquals(mTransportProtocols.get(0), mCommunicator.getActiveTransport());
- // Assume negotiation on the first one failed.
- mCallback.onNegotiationFailed(mTransportProtocols.get(0));
- verify(mTransportProtocols.get(1)).startNegotiation();
- assertEquals(mTransportProtocols.get(1), mCommunicator.getActiveTransport());
- // Oops, the second one failed too; not negotiated!
- mCallback.onNegotiationFailed(mTransportProtocols.get(1));
- verify(mCommunicatorCallback).onD2DAvailabilitychanged(eq(false));
- }
-
- /**
- * Verifies that D2D negotiation failed callback is invoked when no transports are available.
- */
- @SmallTest
- @Test
- public void testNegotiationFailedNoProtocols() {
- mCommunicator = new Communicator(Collections.EMPTY_LIST, mCommunicatorCallback);
- mCommunicator.onStateChanged(null, Connection.STATE_ACTIVE);
- verify(mCommunicatorCallback).onD2DAvailabilitychanged(eq(false));
- }
-
- /**
- * Verifies that we can relay messages to send via the active transport.
- */
- @SmallTest
- @Test
- public void testSendMessage() {
- testNegotiate();
- TransportProtocol protocol = mCommunicator.getActiveTransport();
-
- // Send a couple test messages.
- ArraySet<Communicator.Message> test = new ArraySet<>();
- test.add(new Communicator.Message(Communicator.MESSAGE_DEVICE_BATTERY_STATE,
- Communicator.BATTERY_STATE_GOOD));
- test.add(new Communicator.Message(Communicator.MESSAGE_CALL_AUDIO_CODEC,
- Communicator.AUDIO_CODEC_EVS));
- mCommunicator.sendMessages(test);
-
- // Ensure they got relayed to the transport protocol intact.
- verify(protocol).sendMessages(mMessagesCaptor.capture());
- Set<Communicator.Message> send = mMessagesCaptor.getValue();
- assertEquals(test, send);
- }
-
- /**
- * Verifies that we can relay messages received via the active transport to interested parties.
- */
- @SmallTest
- @Test
- public void testReceiveMessage() {
- testNegotiate();
- TransportProtocol protocol = mCommunicator.getActiveTransport();
-
- // Receive some messages
- ArraySet<Communicator.Message> test = new ArraySet<>();
- test.add(new Communicator.Message(Communicator.MESSAGE_DEVICE_BATTERY_STATE,
- Communicator.BATTERY_STATE_GOOD));
- test.add(new Communicator.Message(Communicator.MESSAGE_CALL_AUDIO_CODEC,
- Communicator.AUDIO_CODEC_EVS));
- mCallback.onMessagesReceived(test);
-
- // Ensure they got relayed to the communicator listener.
- verify(mCommunicatorCallback).onMessagesReceived(mMessagesCaptor.capture());
- Set<Communicator.Message> send = mMessagesCaptor.getValue();
- assertEquals(test, send);
- }
-
-
- /**
- * @return a mocked instance of {@link TransportProtocol}.
- */
- private TransportProtocol getMockTransportProtocol() {
- TransportProtocol transportProtocol = Mockito.mock(TransportProtocol.class);
- doNothing().when(transportProtocol).startNegotiation();
- doNothing().when(transportProtocol).sendMessages(any());
- doAnswer(invocation -> {
- mCallback = (TransportProtocol.Callback) invocation.getArgument(0);
- return true;
- }).when(transportProtocol).setCallback(any());
- return transportProtocol;
- }
-}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/d2d/DtmfTransportConversionTest.java b/tests/telephonytests/src/com/android/internal/telephony/d2d/DtmfTransportConversionTest.java
deleted file mode 100644
index 6662bbdb99..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/d2d/DtmfTransportConversionTest.java
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.internal.telephony.d2d;
-
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertTrue;
-
-import static org.junit.Assert.assertArrayEquals;
-
-import android.test.suitebuilder.annotation.SmallTest;
-import android.util.Pair;
-
-import com.android.internal.telephony.TestExecutorService;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-/**
- * Verifies bidirectional conversion between {@link Communicator.Message}s and DTMF character
- * sequences.
- * This class verifies only the conversion between the two and not the actual sending/receipt. See
- * {@link DtmfTransportTest} for verification of the send/receive of messages using DTMF.
- */
-@RunWith(Parameterized.class)
-public class DtmfTransportConversionTest {
- private static class TestParams {
- public Communicator.Message commMessage;
- public Pair<String,String> messageAndValueDigits;
- public String fullMessage;
-
- TestParams(Communicator.Message theMessage, Pair<String,String> theDigits,
- String theFullMessage) {
- commMessage = theMessage;
- messageAndValueDigits = theDigits;
- fullMessage = theFullMessage;
- }
-
- public String toString() {
- return "Params{msg = " + commMessage + ", digits = " + messageAndValueDigits
- + ", enc=" + fullMessage + "}";
- }
- }
-
- @Mock
- private DtmfAdapter mDtmfAdapter;
- @Mock
- private TransportProtocol.Callback mCallback;
- @Mock
- private Timeouts.Adapter mTimeouts;
- private TestExecutorService mScheduledExecutorService = new TestExecutorService();
-
- private final TestParams mParams;
- private DtmfTransport mDtmfTransport;
-
- public DtmfTransportConversionTest(DtmfTransportConversionTest.TestParams params) {
- mParams = params;
- }
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- mDtmfTransport = new DtmfTransport(mDtmfAdapter, mTimeouts, mScheduledExecutorService);
- mDtmfTransport.setCallback(mCallback);
- }
-
- /**
- * Setup the test cases.
- *
- * @return the test cases
- */
- @Parameterized.Parameters(name = "{0}")
- public static Collection<DtmfTransportConversionTest.TestParams> generateTestCases() {
- List<DtmfTransportConversionTest.TestParams> result = new ArrayList<>();
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_CALL_RADIO_ACCESS_TYPE,
- Communicator.RADIO_ACCESS_TYPE_LTE),
- new Pair<>("A", "A"),
- "AADAD"
- ));
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_CALL_RADIO_ACCESS_TYPE,
- Communicator.RADIO_ACCESS_TYPE_IWLAN),
- new Pair<>("A", "B"),
- "AADBD"
- ));
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_CALL_RADIO_ACCESS_TYPE,
- Communicator.RADIO_ACCESS_TYPE_NR),
- new Pair<>("A", "C"),
- "AADCD"
- ));
-
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_CALL_AUDIO_CODEC,
- Communicator.AUDIO_CODEC_EVS),
- new Pair<>("B", "A"),
- "ABDAD"
- ));
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_CALL_AUDIO_CODEC,
- Communicator.AUDIO_CODEC_AMR_WB),
- new Pair<>("B", "B"),
- "ABDBD"
- ));
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_CALL_AUDIO_CODEC,
- Communicator.AUDIO_CODEC_AMR_NB),
- new Pair<>("B", "C"),
- "ABDCD"
- ));
-
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_DEVICE_BATTERY_STATE,
- Communicator.BATTERY_STATE_LOW),
- new Pair<>("C", "A"),
- "ACDAD"
- ));
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_DEVICE_BATTERY_STATE,
- Communicator.BATTERY_STATE_GOOD),
- new Pair<>("C", "B"),
- "ACDBD"
- ));
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_DEVICE_BATTERY_STATE,
- Communicator.BATTERY_STATE_CHARGING),
- new Pair<>("C", "C"),
- "ACDCD"
- ));
-
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_DEVICE_NETWORK_COVERAGE,
- Communicator.COVERAGE_GOOD),
- new Pair<>("AA", "A"),
- "AAADAD"
- ));
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_DEVICE_NETWORK_COVERAGE,
- Communicator.COVERAGE_POOR),
- new Pair<>("AA", "B"),
- "AAADBD"
- ));
-
- return result;
- }
-
- /**
- * Verify generation of DTMF digits for messages.
- */
- @SmallTest
- @Test
- public void testMessageToDtmf() {
- char[] dtmfSequence = mDtmfTransport.getMessageDigits(mParams.commMessage);
- assertArrayEquals(mParams.fullMessage.toCharArray(), dtmfSequence);
- }
-
- /**
- * Verify generation of messages from DTMF digits
- */
- @SmallTest
- @Test
- public void testDtmfToMessage() {
- Communicator.Message message = mDtmfTransport.extractMessage(
- mParams.messageAndValueDigits.first, mParams.messageAndValueDigits.second);
- assertEquals(mParams.commMessage, message);
- }
-}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/d2d/DtmfTransportTest.java b/tests/telephonytests/src/com/android/internal/telephony/d2d/DtmfTransportTest.java
deleted file mode 100644
index a35abd1927..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/d2d/DtmfTransportTest.java
+++ /dev/null
@@ -1,400 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.internal.telephony.d2d;
-
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertTrue;
-
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import android.test.suitebuilder.annotation.SmallTest;
-import android.util.ArraySet;
-
-import androidx.test.runner.AndroidJUnit4;
-
-import com.android.internal.telephony.TestExecutorService;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Captor;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.util.Set;
-import java.util.stream.Collectors;
-
-@RunWith(AndroidJUnit4.class)
-public class DtmfTransportTest {
- private static final long DIGIT_INTERVAL_MILLIS = 10L;
- private static final long MSG_TIMEOUT_MILLIS = 1000L;
- private static final long NEGOTIATION_TIMEOUT_MILLIS = 2000L;
- private static final String EXPECTED_PROBE = "AAD";
-
- @Mock
- private DtmfAdapter mDtmfAdapter;
- @Mock
- private TransportProtocol.Callback mCallback;
- @Mock
- private Timeouts.Adapter mTimeouts;
- @Captor
- private ArgumentCaptor<Set<Communicator.Message>> mMessagesCaptor;
- @Captor
- private ArgumentCaptor<Character> mDigitsCaptor;
-
- private TestExecutorService mTestExecutorService = new TestExecutorService();
- private DtmfTransport mDtmfTransport;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- when(mTimeouts.getDtmfMinimumIntervalMillis()).thenReturn(DIGIT_INTERVAL_MILLIS);
- when(mTimeouts.getMaxDurationOfDtmfMessageMillis()).thenReturn(MSG_TIMEOUT_MILLIS);
- when(mTimeouts.getDtmfNegotiationTimeoutMillis()).thenReturn(NEGOTIATION_TIMEOUT_MILLIS);
- when(mTimeouts.getDtmfDurationFuzzMillis()).thenReturn(0L);
- mDtmfTransport = new DtmfTransport(mDtmfAdapter, mTimeouts,
- mTestExecutorService /* Executors.newSingleThreadScheduledExecutor() in prod. */);
- mDtmfTransport.setCallback(mCallback);
- }
-
- /**
- * Verify starting state when newly initialized.
- */
- @SmallTest
- @Test
- public void testIdle() {
- assertEquals(DtmfTransport.STATE_IDLE, mDtmfTransport.getTransportState());
- }
-
- /**
- * Verify negotiation start
- */
- @SmallTest
- @Test
- public void testStartNegotiation() {
- mDtmfTransport.startNegotiation();
- assertEquals(DtmfTransport.STATE_NEGOTIATING, mDtmfTransport.getTransportState());
-
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
-
- verify(mDtmfAdapter, times(3)).sendDtmf(mDigitsCaptor.capture());
- String probeString = mDigitsCaptor.getAllValues().stream()
- .map(c -> String.valueOf(c)).collect(Collectors.joining());
- assertEquals(EXPECTED_PROBE, probeString);
- }
-
- /**
- * Verify negotiation fails due to lack of received digit prior to timeout.
- */
- @SmallTest
- @Test
- public void testNegotiationFailsDueToTimeout() {
- mDtmfTransport.startNegotiation();
-
- mTestExecutorService.advanceTime(NEGOTIATION_TIMEOUT_MILLIS);
-
- verify(mCallback).onNegotiationFailed(eq(mDtmfTransport));
- assertEquals(DtmfTransport.STATE_NEGOTIATION_FAILED, mDtmfTransport.getTransportState());
- }
-
- /**
- * Verify negotiation failed due to invalid response
- */
- @SmallTest
- @Test
- public void testNegotiationFailedInvalidResponse() {
- testStartNegotiation();
-
- // Received something other than the probe; it should be ignored
- mDtmfTransport.onDtmfReceived('1');
- // Super short message.
- mDtmfTransport.onDtmfReceived('A');
- mDtmfTransport.onDtmfReceived('D');
-
- verify(mCallback).onNegotiationFailed(eq(mDtmfTransport));
- }
-
- /**
- * Verify negotiation completed
- */
- @SmallTest
- @Test
- public void testNegotiationSuccess() {
- testStartNegotiation();
-
- mDtmfTransport.onDtmfReceived('A');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('A');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('D');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
-
- verify(mCallback).onNegotiationSuccess(eq(mDtmfTransport));
- assertEquals(DtmfTransport.STATE_NEGOTIATED, mDtmfTransport.getTransportState());
- }
-
- /**
- * Verify negotiation completed and that we don't subsequently cancel the negotiation
- */
- @SmallTest
- @Test
- public void testNegotiationSuccessAndDoesNotTimeOut() {
- testNegotiationSuccess();
-
- mTestExecutorService.advanceTime(NEGOTIATION_TIMEOUT_MILLIS);
-
- // Even though we timeout period has passed, we should NOT have failed negotiation and the
- // state should remain negotiated.
- verify(mCallback, never()).onNegotiationFailed(eq(mDtmfTransport));
- assertEquals(DtmfTransport.STATE_NEGOTIATED, mDtmfTransport.getTransportState());
- }
-
- /**
- * Verify receipt of a single message within the overall {@link #MSG_TIMEOUT_MILLIS} message
- * window.
- */
- @SmallTest
- @Test
- public void testReceiveSuccess() {
- testNegotiationSuccess();
-
- // Receive message with typical digit spacing
- mDtmfTransport.onDtmfReceived('A');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('B');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('D');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('C');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('D');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
-
- verify(mCallback).onMessagesReceived(mMessagesCaptor.capture());
- assertEquals(1, mMessagesCaptor.getValue().size());
- assertTrue(mMessagesCaptor.getValue().contains(
- new Communicator.Message(Communicator.MESSAGE_CALL_AUDIO_CODEC,
- Communicator.AUDIO_CODEC_AMR_NB)));
- }
-
- /**
- * Verify invalid message start digits are ignored.
- */
- @SmallTest
- @Test
- public void testReceiveInvalidMessageStart() {
- testNegotiationSuccess();
-
- // Receive message with invalid start digit; it should be ignored.
- mDtmfTransport.onDtmfReceived('B');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('A');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('B');
- // Receive random 0-9 digits user might have typed; should be ignored.
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('1');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('2');
-
- // Back to regularly scheduled message.
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('D');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('C');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('D');
- mTestExecutorService.advanceTime(MSG_TIMEOUT_MILLIS);
-
- verify(mCallback, times(1)).onMessagesReceived(mMessagesCaptor.capture());
- assertEquals(1, mMessagesCaptor.getAllValues().get(0).size());
- assertTrue(mMessagesCaptor.getAllValues().get(0).contains(
- new Communicator.Message(Communicator.MESSAGE_CALL_AUDIO_CODEC,
- Communicator.AUDIO_CODEC_AMR_NB)));
- }
-
- /**
- * Verify invalid messages
- */
- @SmallTest
- @Test
- public void testReceiveInvalidMessage() {
- testNegotiationSuccess();
-
- // Garbage message with no actual values.
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('A');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('D');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('D');
-
- // An unknown message!
- mTestExecutorService.advanceTime(MSG_TIMEOUT_MILLIS);
- mDtmfTransport.onDtmfReceived('A');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('B');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('B');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('D');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('B');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('B');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('D');
-
- verify(mCallback, never()).onMessagesReceived(mMessagesCaptor.capture());
- }
-
- /**
- * Verify receipt of two messages back to back..
- */
- @SmallTest
- @Test
- public void testReceiveMultipleSuccess() {
- testNegotiationSuccess();
-
- // Receive message with typical digit spacing
- mDtmfTransport.onDtmfReceived('A');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('B');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('D');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('C');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('D');
- mTestExecutorService.advanceTime(MSG_TIMEOUT_MILLIS);
-
- verify(mCallback, times(1)).onMessagesReceived(mMessagesCaptor.capture());
- assertEquals(1, mMessagesCaptor.getAllValues().get(0).size());
- assertTrue(mMessagesCaptor.getAllValues().get(0).contains(
- new Communicator.Message(Communicator.MESSAGE_CALL_AUDIO_CODEC,
- Communicator.AUDIO_CODEC_AMR_NB)));
-
- mDtmfTransport.onDtmfReceived('A');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('C');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('D');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('A');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('D');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
-
- // Note: Reusing the captor here appends all call arguments on to mMessagesCaptor, so
- // we need to look at index 2 in getAllValues.
- verify(mCallback, times(2)).onMessagesReceived(mMessagesCaptor.capture());
- assertEquals(1, mMessagesCaptor.getAllValues().get(2).size());
- assertTrue(mMessagesCaptor.getAllValues().get(2).contains(
- new Communicator.Message(Communicator.MESSAGE_DEVICE_BATTERY_STATE,
- Communicator.BATTERY_STATE_LOW)));
- }
-
- /**
- * Verify operation of timeout when receiving a first message, followed by successful receipt of
- * a second message.
- */
- @SmallTest
- @Test
- public void testReceiveTimeout() {
- testNegotiationSuccess();
-
- // Receive a partial first message.
- mDtmfTransport.onDtmfReceived('A');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('B');
- // Timeout
- mTestExecutorService.advanceTime(MSG_TIMEOUT_MILLIS);
-
- // Receive second message.
- mDtmfTransport.onDtmfReceived('A');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('C');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('D');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('A');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
- mDtmfTransport.onDtmfReceived('D');
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS);
-
- // First message should not be present, but the second one should be.
- verify(mCallback, times(1)).onMessagesReceived(mMessagesCaptor.capture());
- assertTrue(mMessagesCaptor.getValue().contains(
- new Communicator.Message(Communicator.MESSAGE_DEVICE_BATTERY_STATE,
- Communicator.BATTERY_STATE_LOW)));
- }
-
- /**
- * Basic test of sending a message using the DTMF transport.
- * See {@link DtmfTransportConversionTest} for tests that confirm the translation between
- * messages and DTMF sequences.
- * This test verifies that trans of DMTF digits are sent in groups separated by the required
- * inter-message delay and that digits are separated by the inter-digit delay.
- */
- @SmallTest
- @Test
- public void testSendSuccess() {
- testNegotiationSuccess();
-
- Set<Communicator.Message> messages = new ArraySet<>();
- messages.add(new Communicator.Message(Communicator.MESSAGE_CALL_AUDIO_CODEC,
- Communicator.AUDIO_CODEC_AMR_NB));
- messages.add(new Communicator.Message(Communicator.MESSAGE_DEVICE_NETWORK_COVERAGE,
- Communicator.COVERAGE_POOR));
- mDtmfTransport.sendMessages(messages);
-
- // Advance the "clock" by the DTMF interval to cause the scheduler to run the scheduled
- // repeating task which sends the digits.
- // First digit train; sequences are separated by the longer timeout.
- mTestExecutorService.advanceTime(MSG_TIMEOUT_MILLIS); // A message start
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS); // B audio codec
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS); // D message type terminator
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS); // C AMR NB value
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS); // D message value terminator
-
- // Second digit train; longer due to longer message type.
- mTestExecutorService.advanceTime(MSG_TIMEOUT_MILLIS); // A message start
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS); // A coverage
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS); // A coverage
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS); // D message type terminator
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS); // B poor value
- mTestExecutorService.advanceTime(DIGIT_INTERVAL_MILLIS); // D message value terminator
-
- ArgumentCaptor<Character> captor = ArgumentCaptor.forClass(Character.class);
- // Extra invocations are from negotiation
- verify(mDtmfAdapter, times(14)).sendDtmf(captor.capture());
-
- // Expected digits includes initial probe send.
- String expectedDigits = "AADABDCDAAADBD";
- String actualDigits = captor.getAllValues().stream()
- .map( c-> String.valueOf(c) )
- .collect(Collectors.joining());
- assertEquals(expectedDigits, actualDigits);
- }
-}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/d2d/RtpTransportConversionTest.java b/tests/telephonytests/src/com/android/internal/telephony/d2d/RtpTransportConversionTest.java
deleted file mode 100644
index 0c251a0392..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/d2d/RtpTransportConversionTest.java
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.internal.telephony.d2d;
-
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertTrue;
-
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import android.os.Handler;
-import android.telephony.ims.RtpHeaderExtension;
-import android.test.suitebuilder.annotation.SmallTest;
-import android.util.ArraySet;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Captor;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Set;
-
-/**
- * Verifies the ability of the {@link RtpTransport} class to successfully encode and decode the
- * device to device communication messages we expect to handle.
- */
-@RunWith(Parameterized.class)
-public class RtpTransportConversionTest {
- private static class TestParams {
- public Communicator.Message commMessage;
- public RtpHeaderExtension extension;
-
- public TestParams(Communicator.Message theMessage, RtpHeaderExtension theExtension) {
- commMessage = theMessage;
- extension = theExtension;
- }
-
- public String toString() {
- return "Params{msg = " + commMessage + ", ext = "
- + Integer.toBinaryString(extension.getExtensionData()[0]) + "}";
- }
- }
-
- private static final int CALL_STATE_LOCAL_IDENTIFIER = 1;
- private static final int DEVICE_STATE_LOCAL_IDENTIFIER = 2;
-
- private RtpTransport mRtpTransport;
- @Mock private Timeouts.Adapter mTimeoutsAdapter;
- @Mock private RtpAdapter mRtpAdapter;
- @Mock private Handler mHandler;
- @Mock private TransportProtocol.Callback mCallback;
- @Captor private ArgumentCaptor<Set<RtpHeaderExtension>> mHeaderExtensionCaptor;
- @Captor private ArgumentCaptor<Set<Communicator.Message>> mMessagesCaptor;
- private final TestParams mParams;
-
- public RtpTransportConversionTest(TestParams params) {
- mParams = params;
- }
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- mRtpTransport = new RtpTransport(mRtpAdapter, mTimeoutsAdapter, mHandler, true /* sdp */);
- mRtpTransport.setCallback(mCallback);
-
- when(mRtpAdapter.getAcceptedRtpHeaderExtensions()).thenReturn(
- RtpTransportTest.ALL_HEADER_EXTENSION_TYPES);
- mRtpTransport.startNegotiation();
- verify(mCallback).onNegotiationSuccess(any());
- verify(mCallback, never()).onNegotiationFailed(any());
- }
-
- /**
- * Setup the test cases.
- * @return the test cases
- */
- @Parameterized.Parameters(name = "{0}")
- public static Collection<TestParams> generateTestCases() {
- List<TestParams> result = new ArrayList<>();
-
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_CALL_AUDIO_CODEC,
- Communicator.AUDIO_CODEC_EVS),
- new RtpHeaderExtension(CALL_STATE_LOCAL_IDENTIFIER,
- new byte[]{0b00010010})));
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_CALL_AUDIO_CODEC,
- Communicator.AUDIO_CODEC_AMR_WB),
- new RtpHeaderExtension(CALL_STATE_LOCAL_IDENTIFIER,
- new byte[]{0b00100010})));
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_CALL_AUDIO_CODEC,
- Communicator.AUDIO_CODEC_AMR_NB),
- new RtpHeaderExtension(CALL_STATE_LOCAL_IDENTIFIER,
- new byte[]{0b00110010})));
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_CALL_RADIO_ACCESS_TYPE,
- Communicator.RADIO_ACCESS_TYPE_LTE),
- new RtpHeaderExtension(CALL_STATE_LOCAL_IDENTIFIER,
- new byte[]{0b00010001})));
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_CALL_RADIO_ACCESS_TYPE,
- Communicator.RADIO_ACCESS_TYPE_IWLAN),
- new RtpHeaderExtension(CALL_STATE_LOCAL_IDENTIFIER,
- new byte[]{0b00100001})));
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_CALL_RADIO_ACCESS_TYPE,
- Communicator.RADIO_ACCESS_TYPE_NR),
- new RtpHeaderExtension(CALL_STATE_LOCAL_IDENTIFIER,
- new byte[]{0b00110001})));
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_DEVICE_BATTERY_STATE,
- Communicator.BATTERY_STATE_LOW),
- new RtpHeaderExtension(DEVICE_STATE_LOCAL_IDENTIFIER,
- new byte[]{0b00000001})));
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_DEVICE_BATTERY_STATE,
- Communicator.BATTERY_STATE_GOOD),
- new RtpHeaderExtension(DEVICE_STATE_LOCAL_IDENTIFIER,
- new byte[]{0b00010001})));
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_DEVICE_BATTERY_STATE,
- Communicator.BATTERY_STATE_CHARGING),
- new RtpHeaderExtension(DEVICE_STATE_LOCAL_IDENTIFIER,
- new byte[]{0b00110001})));
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_DEVICE_NETWORK_COVERAGE,
- Communicator.COVERAGE_POOR),
- new RtpHeaderExtension(DEVICE_STATE_LOCAL_IDENTIFIER,
- new byte[]{0b00000010})));
- result.add(new TestParams(
- new Communicator.Message(Communicator.MESSAGE_DEVICE_NETWORK_COVERAGE,
- Communicator.COVERAGE_GOOD),
- new RtpHeaderExtension(DEVICE_STATE_LOCAL_IDENTIFIER,
- new byte[]{0b00010010})));
- return result;
- }
-
- /**
- * Verify generation of RTP header extension data for messages.
- */
- @SmallTest
- @Test
- public void testSendMessages() {
- ArraySet<Communicator.Message> messages = new ArraySet<>();
- messages.add(mParams.commMessage);
-
- mRtpTransport.sendMessages(messages);
- verify(mRtpAdapter).sendRtpHeaderExtensions(mHeaderExtensionCaptor.capture());
- Set<RtpHeaderExtension> extensions = mHeaderExtensionCaptor.getValue();
- assertEquals(1, extensions.size());
- assertTrue(extensions.contains(mParams.extension));
- }
-
- /**
- * Verify translation from raw RTP data into message/value pairs.
- */
- @SmallTest
- @Test
- public void testReceiveMessage() {
- ArraySet<RtpHeaderExtension> extension = new ArraySet<>();
- extension.add(mParams.extension);
- mRtpTransport.onRtpHeaderExtensionsReceived(extension);
-
- verify(mCallback).onMessagesReceived(mMessagesCaptor.capture());
- Set<Communicator.Message> messages = mMessagesCaptor.getValue();
- assertEquals(1, messages.size());
- assertTrue(messages.contains(mParams.commMessage));
- }
-}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/d2d/RtpTransportTest.java b/tests/telephonytests/src/com/android/internal/telephony/d2d/RtpTransportTest.java
deleted file mode 100644
index c241cf285d..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/d2d/RtpTransportTest.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.internal.telephony.d2d;
-
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import android.os.Handler;
-import android.telephony.ims.RtpHeaderExtension;
-import android.telephony.ims.RtpHeaderExtensionType;
-import android.test.suitebuilder.annotation.SmallTest;
-import android.util.ArraySet;
-
-import androidx.test.runner.AndroidJUnit4;
-
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Captor;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.util.Set;
-
-@RunWith(AndroidJUnit4.class)
-public class RtpTransportTest {
- private static final int CALL_STATE_LOCAL_IDENTIFIER = 1;
- private static final int DEVICE_STATE_LOCAL_IDENTIFIER = 2;
-
- public static final ArraySet<RtpHeaderExtensionType> ALL_HEADER_EXTENSION_TYPES =
- new ArraySet<>();
- static {
- ALL_HEADER_EXTENSION_TYPES.add(new RtpHeaderExtensionType(CALL_STATE_LOCAL_IDENTIFIER,
- RtpTransport.CALL_STATE_RTP_HEADER_EXTENSION));
- ALL_HEADER_EXTENSION_TYPES.add(new RtpHeaderExtensionType(DEVICE_STATE_LOCAL_IDENTIFIER,
- RtpTransport.DEVICE_STATE_RTP_HEADER_EXTENSION));
- }
- private static final ArraySet<RtpHeaderExtensionType> NO_SUPPORTED_HEADER_EXTENSION_TYPES =
- new ArraySet<>();
-
- private RtpTransport mRtpTransport;
- @Mock private Timeouts.Adapter mTimeoutsAdapter;
- @Mock private RtpAdapter mRtpAdapter;
- @Mock private Handler mHandler;
- @Mock private TransportProtocol.Callback mCallback;
- @Captor private ArgumentCaptor<Set<RtpHeaderExtension>> mHeaderExtensionCaptor;
- @Captor private ArgumentCaptor<Set<Communicator.Message>> mMessagesCaptor;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- mRtpTransport = new RtpTransport(mRtpAdapter, mTimeoutsAdapter, mHandler, true /* sdp */);
- mRtpTransport.setCallback(mCallback);
- }
-
- /**
- * Nominal case; assume the remote side accepted all RTP header extension types we need for D2D
- * communications. The should get an instant negotiation success.
- */
- @SmallTest
- @Test
- public void testAllHeaderExtensionsSupported() {
- when(mRtpAdapter.getAcceptedRtpHeaderExtensions()).thenReturn(ALL_HEADER_EXTENSION_TYPES);
- mRtpTransport.startNegotiation();
- verify(mCallback).onNegotiationSuccess(any());
- verify(mCallback, never()).onNegotiationFailed(any());
- }
-
- /**
- * Verify the case where the RTP header extensions are not supported.
- */
- @SmallTest
- @Test
- public void testRtpHeaderExtensionsNotSupported() {
- when(mRtpAdapter.getAcceptedRtpHeaderExtensions()).thenReturn(
- NO_SUPPORTED_HEADER_EXTENSION_TYPES);
- mRtpTransport.startNegotiation();
- verify(mCallback, never()).onNegotiationSuccess(any());
- verify(mCallback).onNegotiationFailed(any());
- }
-
- /**
- * Verifies that unrecognized RTP header extensions are ignored.
- */
- @SmallTest
- @Test
- public void testIgnoreInvalidMessage() {
- testAllHeaderExtensionsSupported();
-
- ArraySet<RtpHeaderExtension> extensions = new ArraySet<>();
- // Invalid because it has an unrecognized local identifier
- extensions.add(new RtpHeaderExtension(1, new byte[] {0b01010101}));
- // Invalid because it has an unknown message type within a valid identifier.
- extensions.add(new RtpHeaderExtension(CALL_STATE_LOCAL_IDENTIFIER,
- new byte[] {0b00101111}));
- // Invalid because it has an unknown message value within a valid type.
- extensions.add(new RtpHeaderExtension(CALL_STATE_LOCAL_IDENTIFIER,
- new byte[] {0b01110010}));
- mRtpTransport.onRtpHeaderExtensionsReceived(extensions);
- verify(mCallback, never()).onMessagesReceived(any());
- }
-}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/ApnConfigTypeRepositoryTest.java b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/ApnConfigTypeRepositoryTest.java
index 532dbe0f35..aa97c0244f 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/ApnConfigTypeRepositoryTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/ApnConfigTypeRepositoryTest.java
@@ -75,7 +75,7 @@ public class ApnConfigTypeRepositoryTest {
//Priorities must be integers
apnConfigStringArray.add("default:10a");
- //Key isn't case sensitive, which means that this priority should be taken
+ //Key isn't case sensitive, which means that this prority should be taken
apnConfigStringArray.add("fotA:10");
mCarrierConfig.putStringArray(CarrierConfigManager.KEY_APN_PRIORITY_STRING_ARRAY,
@@ -87,17 +87,11 @@ public class ApnConfigTypeRepositoryTest {
}
private void checkDefaults(ApnConfigTypeRepository repository) {
- assertEquals(0, repository.getByType(ApnSetting.TYPE_ENTERPRISE).getPriority());
- assertEquals(1, repository.getByType(ApnSetting.TYPE_DEFAULT).getPriority());
- assertEquals(2, repository.getByType(ApnSetting.TYPE_MMS).getPriority());
+ assertEquals(0, repository.getByType(ApnSetting.TYPE_DEFAULT).getPriority());
assertEquals(2, repository.getByType(ApnSetting.TYPE_SUPL).getPriority());
- assertEquals(2, repository.getByType(ApnSetting.TYPE_DUN).getPriority());
assertEquals(3, repository.getByType(ApnSetting.TYPE_HIPRI).getPriority());
- assertEquals(2, repository.getByType(ApnSetting.TYPE_IMS).getPriority());
assertEquals(2, repository.getByType(ApnSetting.TYPE_CBS).getPriority());
- assertEquals(2, repository.getByType(ApnSetting.TYPE_IA).getPriority());
assertEquals(2, repository.getByType(ApnSetting.TYPE_EMERGENCY).getPriority());
- assertEquals(3, repository.getByType(ApnSetting.TYPE_MCX).getPriority());
assertEquals(3, repository.getByType(ApnSetting.TYPE_XCAP).getPriority());
}
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/ApnContextTest.java b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/ApnContextTest.java
index 85d1e5e750..525afe2e60 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/ApnContextTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/ApnContextTest.java
@@ -26,12 +26,14 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import android.net.NetworkCapabilities;
+import android.net.NetworkConfig;
import android.net.NetworkRequest;
import android.telephony.data.ApnSetting;
import android.test.suitebuilder.annotation.SmallTest;
import com.android.internal.R;
import com.android.internal.telephony.DctConstants;
+import com.android.internal.telephony.PhoneConstants;
import com.android.internal.telephony.TelephonyTest;
import org.junit.After;
@@ -40,6 +42,9 @@ import org.junit.Test;
import org.mockito.Mock;
public class ApnContextTest extends TelephonyTest {
+
+ @Mock
+ NetworkConfig mNetworkConfig;
@Mock
ApnSetting mApnSetting;
@@ -48,7 +53,7 @@ public class ApnContextTest extends TelephonyTest {
@Before
public void setUp() throws Exception {
super.setUp(getClass().getSimpleName());
-
+ mNetworkConfig.dependencyMet = true;
mApnContext = new ApnContext(mPhone, ApnSetting.TYPE_DEFAULT, TAG, mDcTracker, 1);
}
@@ -67,8 +72,8 @@ public class ApnContextTest extends TelephonyTest {
@Test
@SmallTest
- public void testGetApnType() {
- assertEquals(ApnSetting.TYPE_DEFAULT_STRING, mApnContext.getApnType());
+ public void testGetApnType() throws Exception {
+ assertEquals(PhoneConstants.APN_TYPE_DEFAULT, mApnContext.getApnType());
}
@Test
diff --git a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/ApnSettingTest.java b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/ApnSettingTest.java
index 0b19baf19b..de7d12a966 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/ApnSettingTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/ApnSettingTest.java
@@ -31,6 +31,7 @@ import android.telephony.TelephonyManager;
import android.telephony.data.ApnSetting;
import android.test.suitebuilder.annotation.SmallTest;
+import com.android.internal.telephony.PhoneConstants;
import com.android.internal.telephony.TelephonyTest;
import org.junit.After;
@@ -72,17 +73,17 @@ public class ApnSettingTest extends TelephonyTest {
"44010", // numeric
"sp-mode", // name
"spmode.ne.jp", // apn
- null, // proxy
+ null, // proxy
-1, // port
- null, // mmsc
- null, // mmsproxy
+ null, // mmsc
+ null, // mmsproxy
-1, // mmsport
"", // user
"", // password
-1, // authtype
- apnTypeBitmask, // types
- ApnSetting.PROTOCOL_IP, // protocol
- ApnSetting.PROTOCOL_IP, // roaming_protocol
+ apnTypeBitmask, // types
+ ApnSetting.PROTOCOL_IP, // protocol
+ ApnSetting.PROTOCOL_IP, // roaming_protocol
carrierEnabled, // carrier_enabled
0, // networktype_bitmask
0, // profile_id
@@ -134,7 +135,7 @@ public class ApnSettingTest extends TelephonyTest {
@Test
@SmallTest
- public void testFromString() {
+ public void testFromString() throws Exception {
final int dunTypesBitmask = ApnSetting.TYPE_DUN;
final int mmsTypesBitmask = ApnSetting.TYPE_MMS | ApnSetting.TYPE_ALL;
@@ -263,7 +264,7 @@ public class ApnSettingTest extends TelephonyTest {
@Test
@SmallTest
- public void testArrayFromString() {
+ public void testArrayFromString() throws Exception {
final int mmsTypesBitmask = ApnSetting.TYPE_MMS;
// Test a multiple v3 string.
String testString =
@@ -296,7 +297,7 @@ public class ApnSettingTest extends TelephonyTest {
@Test
@SmallTest
- public void testToString() {
+ public void testToString() throws Exception {
// Use default apn_set_id constructor.
ApnSetting apn = ApnSetting.makeApnSetting(
99, "12345", "Name", "apn", null, 10,
@@ -322,9 +323,9 @@ public class ApnSettingTest extends TelephonyTest {
@Test
@SmallTest
- public void testIsMetered() {
+ public void testIsMetered() throws Exception {
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
doReturn(false).when(mServiceState).getDataRoaming();
doReturn(1).when(mPhone).getSubId();
@@ -359,11 +360,10 @@ public class ApnSettingTest extends TelephonyTest {
assertFalse(ApnSettingUtils.isMeteredApnType(ApnSetting.TYPE_IA, mPhone));
assertFalse(ApnSettingUtils.isMeteredApnType(ApnSetting.TYPE_HIPRI, mPhone));
assertFalse(ApnSettingUtils.isMeteredApnType(ApnSetting.TYPE_XCAP, mPhone));
- assertFalse(ApnSettingUtils.isMeteredApnType(ApnSetting.TYPE_ENTERPRISE, mPhone));
// Carrier config settings changes.
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT});
assertTrue(ApnSettingUtils.isMeteredApnType(ApnSetting.TYPE_DEFAULT, mPhone));
assertFalse(ApnSettingUtils.isMeteredApnType(ApnSetting.TYPE_MMS, mPhone));
@@ -371,9 +371,9 @@ public class ApnSettingTest extends TelephonyTest {
@Test
@SmallTest
- public void testIsRoamingMetered() {
+ public void testIsRoamingMetered() throws Exception {
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_ROAMING_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
doReturn(true).when(mServiceState).getDataRoaming();
doReturn(1).when(mPhone).getSubId();
@@ -400,20 +400,19 @@ public class ApnSettingTest extends TelephonyTest {
// Carrier config settings changes.
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_ROAMING_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_FOTA_STRING});
+ new String[]{PhoneConstants.APN_TYPE_FOTA});
assertFalse(ApnSettingUtils.isMeteredApnType(ApnSetting.TYPE_DEFAULT, mPhone));
assertFalse(ApnSettingUtils.isMeteredApnType(ApnSetting.TYPE_MMS, mPhone));
assertTrue(ApnSettingUtils.isMeteredApnType(ApnSetting.TYPE_FOTA, mPhone));
assertFalse(ApnSettingUtils.isMeteredApnType(ApnSetting.TYPE_XCAP, mPhone));
- assertFalse(ApnSettingUtils.isMeteredApnType(ApnSetting.TYPE_ENTERPRISE, mPhone));
}
@Test
@SmallTest
- public void testIsMeteredAnother() {
+ public void testIsMeteredAnother() throws Exception {
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_SUPL_STRING, ApnSetting.TYPE_CBS_STRING});
+ new String[]{PhoneConstants.APN_TYPE_SUPL, PhoneConstants.APN_TYPE_CBS});
doReturn(false).when(mServiceState).getDataRoaming();
doReturn(1).when(mPhone).getSubId();
@@ -438,15 +437,13 @@ public class ApnSettingTest extends TelephonyTest {
assertFalse(ApnSettingUtils.isMetered(createApnSetting(ApnSetting.TYPE_IMS), mPhone));
assertFalse(ApnSettingUtils.isMetered(createApnSetting(ApnSetting.TYPE_XCAP), mPhone));
- assertFalse(ApnSettingUtils.isMetered(
- createApnSetting(ApnSetting.TYPE_ENTERPRISE), mPhone));
}
@Test
@SmallTest
- public void testIsRoamingMeteredAnother() {
+ public void testIsRoamingMeteredAnother() throws Exception {
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_ROAMING_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_SUPL_STRING, ApnSetting.TYPE_CBS_STRING});
+ new String[]{PhoneConstants.APN_TYPE_SUPL, PhoneConstants.APN_TYPE_CBS});
doReturn(true).when(mServiceState).getDataRoaming();
doReturn(2).when(mPhone).getSubId();
@@ -479,12 +476,11 @@ public class ApnSettingTest extends TelephonyTest {
assertFalse(ApnSettingUtils.isMeteredApnType(ApnSetting.TYPE_IA, mPhone));
assertFalse(ApnSettingUtils.isMeteredApnType(ApnSetting.TYPE_HIPRI, mPhone));
assertFalse(ApnSettingUtils.isMeteredApnType(ApnSetting.TYPE_XCAP, mPhone));
- assertFalse(ApnSettingUtils.isMeteredApnType(ApnSetting.TYPE_ENTERPRISE, mPhone));
}
@Test
@SmallTest
- public void testIsMeteredNothingCharged() {
+ public void testIsMeteredNothingCharged() throws Exception {
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
new String[]{});
@@ -505,7 +501,7 @@ public class ApnSettingTest extends TelephonyTest {
@Test
@SmallTest
- public void testIsRoamingMeteredNothingCharged() {
+ public void testIsRoamingMeteredNothingCharged() throws Exception {
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_ROAMING_APN_TYPES_STRINGS,
new String[]{});
doReturn(true).when(mServiceState).getDataRoaming();
@@ -525,7 +521,7 @@ public class ApnSettingTest extends TelephonyTest {
@Test
@SmallTest
- public void testCanHandleType() {
+ public void testCanHandleType() throws Exception {
String types[] = {"mms"};
assertTrue(createApnSetting(ApnSetting.TYPE_ALL)
@@ -560,7 +556,7 @@ public class ApnSettingTest extends TelephonyTest {
ApnSetting.TYPE_DEFAULT | ApnSetting.TYPE_MMS | ApnSetting.TYPE_IA)
.canHandleType(ApnSetting.TYPE_IA));
- // same for emergency, mcx, xcap, and enterprise
+ // same for emergency, mcx, and xcap
assertFalse(createApnSetting(ApnSetting.TYPE_ALL)
.canHandleType(ApnSetting.TYPE_EMERGENCY));
assertTrue(createApnSetting(
@@ -576,11 +572,6 @@ public class ApnSettingTest extends TelephonyTest {
assertTrue(createApnSetting(
ApnSetting.TYPE_DEFAULT | ApnSetting.TYPE_MMS | ApnSetting.TYPE_XCAP)
.canHandleType(ApnSetting.TYPE_XCAP));
- assertFalse(createApnSetting(ApnSetting.TYPE_ALL)
- .canHandleType(ApnSetting.TYPE_ENTERPRISE));
- assertTrue(createApnSetting(
- ApnSetting.TYPE_DEFAULT | ApnSetting.TYPE_MMS | ApnSetting.TYPE_ENTERPRISE)
- .canHandleType(ApnSetting.TYPE_ENTERPRISE));
// check carrier disabled
assertFalse(createDisabledApnSetting(ApnSetting.TYPE_ALL)
@@ -599,9 +590,6 @@ public class ApnSettingTest extends TelephonyTest {
assertFalse(createDisabledApnSetting(
ApnSetting.TYPE_DEFAULT | ApnSetting.TYPE_MMS | ApnSetting.TYPE_XCAP)
.canHandleType(ApnSetting.TYPE_XCAP));
- assertFalse(createDisabledApnSetting(
- ApnSetting.TYPE_DEFAULT | ApnSetting.TYPE_MMS | ApnSetting.TYPE_ENTERPRISE)
- .canHandleType(ApnSetting.TYPE_ENTERPRISE));
}
@Test
@@ -651,7 +639,7 @@ public class ApnSettingTest extends TelephonyTest {
@Test
@SmallTest
- public void testEqualsRoamingProtocol() {
+ public void testEqualsRoamingProtocol() throws Exception {
ApnSetting apn1 = ApnSetting.makeApnSetting(
1234,
"310260",
@@ -712,7 +700,7 @@ public class ApnSettingTest extends TelephonyTest {
@Test
@SmallTest
- public void testCanHandleNetwork() {
+ public void testCanHandleNetwork() throws Exception {
ApnSetting apn1 = ApnSetting.makeApnSetting(
1234,
"310260",
diff --git a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataCallResponseTest.java b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataCallResponseTest.java
index 6f9170938a..529e81e89f 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataCallResponseTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataCallResponseTest.java
@@ -27,24 +27,18 @@ import android.net.LinkAddress;
import android.os.Parcel;
import android.telephony.data.ApnSetting;
import android.telephony.data.DataCallResponse;
-import android.telephony.data.EpsQos;
-import android.telephony.data.TrafficDescriptor;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;
-import java.util.ArrayList;
import java.util.Arrays;
public class DataCallResponseTest extends AndroidTestCase {
- public static final String FAKE_DNN = "FAKE_DNN";
- public static final byte[] FAKE_OS_APP_ID = {1, 2, 3, 4};
- public static final byte[] FAKE_OS_APP_ID_2 = {5, 6, 8, 9};
@SmallTest
- public void testParcel() {
+ public void testParcel() throws Exception {
DataCallResponse response = new DataCallResponse.Builder()
.setCause(0)
- .setRetryDurationMillis(-1L)
+ .setSuggestedRetryTime(-1)
.setId(1)
.setLinkStatus(2)
.setProtocolType(ApnSetting.PROTOCOL_IP)
@@ -57,10 +51,6 @@ public class DataCallResponseTest extends AndroidTestCase {
Arrays.asList(InetAddresses.parseNumericAddress(FAKE_PCSCF_ADDRESS)))
.setMtuV4(1440)
.setMtuV6(1440)
- .setDefaultQos(new EpsQos())
- .setQosBearerSessions(new ArrayList<>())
- .setTrafficDescriptors(
- Arrays.asList(new TrafficDescriptor(FAKE_DNN, FAKE_OS_APP_ID)))
.build();
Parcel p = Parcel.obtain();
@@ -72,10 +62,10 @@ public class DataCallResponseTest extends AndroidTestCase {
}
@SmallTest
- public void testEquals() {
+ public void testEquals() throws Exception {
DataCallResponse response = new DataCallResponse.Builder()
.setCause(0)
- .setRetryDurationMillis(-1L)
+ .setSuggestedRetryTime(-1)
.setId(1)
.setLinkStatus(2)
.setProtocolType(ApnSetting.PROTOCOL_IP)
@@ -88,13 +78,11 @@ public class DataCallResponseTest extends AndroidTestCase {
Arrays.asList(InetAddresses.parseNumericAddress(FAKE_PCSCF_ADDRESS)))
.setMtuV4(1440)
.setMtuV6(1400)
- .setTrafficDescriptors(
- Arrays.asList(new TrafficDescriptor(FAKE_DNN, FAKE_OS_APP_ID)))
.build();
DataCallResponse response1 = new DataCallResponse.Builder()
.setCause(0)
- .setRetryDurationMillis(-1L)
+ .setSuggestedRetryTime(-1)
.setId(1)
.setLinkStatus(2)
.setProtocolType(ApnSetting.PROTOCOL_IP)
@@ -107,8 +95,6 @@ public class DataCallResponseTest extends AndroidTestCase {
Arrays.asList(InetAddresses.parseNumericAddress(FAKE_PCSCF_ADDRESS)))
.setMtuV4(1440)
.setMtuV6(1400)
- .setTrafficDescriptors(
- Arrays.asList(new TrafficDescriptor(FAKE_DNN, FAKE_OS_APP_ID)))
.build();
assertEquals(response, response);
@@ -116,7 +102,7 @@ public class DataCallResponseTest extends AndroidTestCase {
DataCallResponse response2 = new DataCallResponse.Builder()
.setCause(1)
- .setRetryDurationMillis(-1L)
+ .setSuggestedRetryTime(-1)
.setId(1)
.setLinkStatus(3)
.setProtocolType(ApnSetting.PROTOCOL_IP)
@@ -131,8 +117,6 @@ public class DataCallResponseTest extends AndroidTestCase {
InetAddresses.parseNumericAddress(FAKE_PCSCF_ADDRESS)))
.setMtuV4(1441)
.setMtuV6(1440)
- .setTrafficDescriptors(
- Arrays.asList(new TrafficDescriptor("FAKE_DNN_2", FAKE_OS_APP_ID_2)))
.build();
assertNotSame(response1, response2);
diff --git a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataConnectionTest.java b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataConnectionTest.java
index ca8abeb603..e79bdfdf22 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataConnectionTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataConnectionTest.java
@@ -19,6 +19,8 @@ package com.android.internal.telephony.dataconnection;
import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
import static android.net.NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED;
+import static android.net.NetworkPolicyManager.SUBSCRIPTION_OVERRIDE_CONGESTED;
+import static android.net.NetworkPolicyManager.SUBSCRIPTION_OVERRIDE_UNMETERED;
import static com.android.internal.telephony.TelephonyTestUtils.waitForMs;
import static com.android.internal.telephony.dataconnection.DcTrackerTest.FAKE_ADDRESS;
@@ -30,26 +32,22 @@ import static com.android.internal.telephony.dataconnection.DcTrackerTest.FAKE_P
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.anyInt;
-import static org.mockito.Mockito.atLeastOnce;
-import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
-import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+import android.content.IntentFilter;
+import android.content.pm.ServiceInfo;
import android.net.InetAddresses;
import android.net.KeepalivePacketData;
import android.net.LinkAddress;
import android.net.LinkProperties;
import android.net.NattKeepalivePacketData;
-import android.net.Network;
import android.net.NetworkCapabilities;
+import android.net.NetworkInfo;
import android.os.AsyncResult;
import android.os.Handler;
import android.os.HandlerThread;
@@ -58,17 +56,12 @@ import android.telephony.AccessNetworkConstants;
import android.telephony.AccessNetworkConstants.AccessNetworkType;
import android.telephony.CarrierConfigManager;
import android.telephony.ServiceState;
-import android.telephony.ServiceState.RegState;
-import android.telephony.ServiceState.RilRadioTechnology;
import android.telephony.data.ApnSetting;
import android.telephony.data.DataCallResponse;
import android.telephony.data.DataProfile;
import android.telephony.data.DataService;
-import android.telephony.data.DataServiceCallback;
-import android.telephony.data.TrafficDescriptor;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
-import android.util.Pair;
import com.android.internal.R;
import com.android.internal.telephony.PhoneConstants;
@@ -77,7 +70,8 @@ import com.android.internal.telephony.TelephonyTest;
import com.android.internal.telephony.dataconnection.DataConnection.ConnectionParams;
import com.android.internal.telephony.dataconnection.DataConnection.DisconnectParams;
import com.android.internal.telephony.dataconnection.DataConnection.SetupResult;
-import com.android.internal.telephony.metrics.DataCallSessionStats;
+import com.android.internal.util.IState;
+import com.android.internal.util.StateMachine;
import org.junit.After;
import org.junit.Before;
@@ -87,13 +81,9 @@ import org.mockito.Mock;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
-import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Collections;
-import java.util.function.Consumer;
public class DataConnectionTest extends TelephonyTest {
- private static final int DEFAULT_DC_CID = 10;
@Mock
DcTesterFailBringUpAll mDcTesterFailBringUpAll;
@@ -104,36 +94,29 @@ public class DataConnectionTest extends TelephonyTest {
@Mock
ApnContext mApnContext;
@Mock
- ApnContext mEnterpriseApnContext;
- @Mock
DcFailBringUp mDcFailBringUp;
- @Mock
- DataCallSessionStats mDataCallSessionStats;
- @Mock
- DataConnection mDefaultDc;
- @Mock
- DataServiceManager mDataServiceManager;
private DataConnection mDc;
private DataConnectionTestHandler mDataConnectionTestHandler;
private DcController mDcc;
+ private CellularDataService mCellularDataService;
private ApnSetting mApn1 = ApnSetting.makeApnSetting(
2163, // id
"44010", // numeric
"sp-mode", // name
"spmode.ne.jp", // apn
- null, // proxy
+ null, // proxy
-1, // port
- null, // mmsc
- null, // mmsproxy
+ null, // mmsc
+ null, // mmsproxy
-1, // mmsport
"", // user
"", // password
-1, // authtype
- ApnSetting.TYPE_DEFAULT | ApnSetting.TYPE_SUPL, // types
- ApnSetting.PROTOCOL_IP, // protocol
- ApnSetting.PROTOCOL_IP, // roaming_protocol
+ ApnSetting.TYPE_DEFAULT | ApnSetting.TYPE_SUPL, // types
+ ApnSetting.PROTOCOL_IP, // protocol
+ ApnSetting.PROTOCOL_IP, // roaming_protocol
true, // carrier_enabled
0, // networktype_bitmask
0, // profile_id
@@ -150,17 +133,17 @@ public class DataConnectionTest extends TelephonyTest {
"44010", // numeric
"sp-mode", // name
"spmode.ne.jp", // apn
- null, // proxy
+ null, // proxy
-1, // port
- null, // mmsc
- null, // mmsproxy
+ null, // mmsc
+ null, // mmsproxy
-1, // mmsport
"", // user
"", // password
-1, // authtype
- ApnSetting.TYPE_DEFAULT | ApnSetting.TYPE_DUN, // types
- ApnSetting.PROTOCOL_IP, // protocol
- ApnSetting.PROTOCOL_IP, // roaming_protocol
+ ApnSetting.TYPE_DEFAULT | ApnSetting.TYPE_DUN, // types
+ ApnSetting.PROTOCOL_IP, // protocol
+ ApnSetting.PROTOCOL_IP, // roaming_protocol
true, // carrier_enabled
0, // networktype_bitmask
0, // profile_id
@@ -173,7 +156,7 @@ public class DataConnectionTest extends TelephonyTest {
""); // mnvo_match_data
private ApnSetting mApn3 = ApnSetting.makeApnSetting(
- 2165, // id
+ 2164, // id
"44010", // numeric
"sp-mode", // name
"spmode.ne.jp", // apn
@@ -203,7 +186,7 @@ public class DataConnectionTest extends TelephonyTest {
1); // skip_464xlat
private ApnSetting mApn4 = ApnSetting.makeApnSetting(
- 2166, // id
+ 2164, // id
"44010", // numeric
"sp-mode", // name
"spmode.ne.jp", // apn
@@ -230,7 +213,7 @@ public class DataConnectionTest extends TelephonyTest {
""); // mnvo_match_data
private ApnSetting mApn5 = ApnSetting.makeApnSetting(
- 2167, // id
+ 2164, // id
"44010", // numeric
"sp-mode", // name
"spmode.ne.jp", // apn
@@ -259,33 +242,6 @@ public class DataConnectionTest extends TelephonyTest {
-1, // carrier_id
0); // skip_464xlat
- private ApnSetting mApn6 = ApnSetting.makeApnSetting(
- 2168, // id
- "44010", // numeric
- "sp-mode", // name
- "spmode.ne.jp", // apn
- null, // proxy
- -1, // port
- null, // mmsc
- null, // mmsproxy
- -1, // mmsport
- "", // user
- "", // password
- -1, // authtype
- ApnSetting.TYPE_EMERGENCY, // types
- ApnSetting.PROTOCOL_IP, // protocol
- ApnSetting.PROTOCOL_IP, // roaming_protocol
- true, // carrier_enabled
- 0, // networktype_bitmask
- 0, // profile_id
- false, // modem_cognitive
- 0, // max_conns
- 0, // wait_time
- 0, // max_conns_time
- 0, // mtu
- -1, // mvno_type
- ""); // mnvo_match_data
-
private class DataConnectionTestHandler extends HandlerThread {
private DataConnectionTestHandler(String name) {
@@ -295,61 +251,31 @@ public class DataConnectionTest extends TelephonyTest {
@Override
public void onLooperPrepared() {
Handler h = new Handler();
- mDcc = DcController.makeDcc(mPhone, mDcTracker, mDataServiceManager, h.getLooper(), "");
- mDc = DataConnection.makeDataConnection(mPhone, 0, mDcTracker, mDataServiceManager,
- mDcTesterFailBringUpAll, mDcc, true);
+
+ DataServiceManager manager = new DataServiceManager(mPhone,
+ AccessNetworkConstants.TRANSPORT_TYPE_WWAN, "");
+ mDcc = DcController.makeDcc(mPhone, mDcTracker, manager, h, "");
+ mDcc.start();
+ mDc = DataConnection.makeDataConnection(mPhone, 0, mDcTracker, manager,
+ mDcTesterFailBringUpAll, mDcc);
}
}
- private void setSuccessfulSetupDataResponse(int cid) {
- doAnswer(invocation -> {
- final Message msg = (Message) invocation.getArguments()[10];
-
- DataCallResponse response = new DataCallResponse.Builder()
- .setCause(0)
- .setRetryDurationMillis(-1L)
- .setId(cid)
- .setLinkStatus(2)
- .setProtocolType(ApnSetting.PROTOCOL_IPV4V6)
- .setInterfaceName("ifname")
- .setAddresses(Arrays.asList(
- new LinkAddress(InetAddresses.parseNumericAddress("10.0.2.15"), 32),
- new LinkAddress("2607:fb90:a620:651d:eabe:f8da:c107:44be/64")))
- .setDnsAddresses(Arrays.asList(InetAddresses.parseNumericAddress("10.0.2.3"),
- InetAddresses.parseNumericAddress("fd00:976a::9")))
- .setGatewayAddresses(Arrays.asList(
- InetAddresses.parseNumericAddress("10.0.2.15"),
- InetAddresses.parseNumericAddress("fe80::2")))
- .setPcscfAddresses(Arrays.asList(
- InetAddresses.parseNumericAddress("fd00:976a:c305:1d::8"),
- InetAddresses.parseNumericAddress("fd00:976a:c202:1d::7"),
- InetAddresses.parseNumericAddress("fd00:976a:c305:1d::5")))
- .setMtu(1500)
- .setMtuV4(1500)
- .setMtuV6(1500)
- .setPduSessionId(1)
- .setQosBearerSessions(new ArrayList<>())
- .setTrafficDescriptors(new ArrayList<>())
- .build();
- msg.getData().putParcelable("data_call_response", response);
- msg.arg1 = DataServiceCallback.RESULT_SUCCESS;
- msg.sendToTarget();
- return null;
- }).when(mDataServiceManager).setupDataCall(anyInt(), any(DataProfile.class), anyBoolean(),
- anyBoolean(), anyInt(), any(), anyInt(), any(), any(), anyBoolean(),
- any(Message.class));
+ private void addDataService() {
+ mCellularDataService = new CellularDataService();
+ ServiceInfo serviceInfo = new ServiceInfo();
+ serviceInfo.packageName = "com.android.phone";
+ serviceInfo.permission = "android.permission.BIND_TELEPHONY_DATA_SERVICE";
+ IntentFilter filter = new IntentFilter();
+ mContextFixture.addService(
+ DataService.SERVICE_INTERFACE,
+ null,
+ "com.android.phone",
+ mCellularDataService.mBinder,
+ serviceInfo,
+ filter);
}
- private void setFailedSetupDataResponse(@DataServiceCallback.ResultCode int resultCode) {
- doAnswer(invocation -> {
- final Message msg = (Message) invocation.getArguments()[10];
- msg.arg1 = resultCode;
- msg.sendToTarget();
- return null;
- }).when(mDataServiceManager).setupDataCall(anyInt(), any(DataProfile.class), anyBoolean(),
- anyBoolean(), anyInt(), any(), anyInt(), any(), any(), anyBoolean(),
- any(Message.class));
- }
@Before
public void setUp() throws Exception {
@@ -360,8 +286,7 @@ public class DataConnectionTest extends TelephonyTest {
replaceInstance(ConnectionParams.class, "mRilRat", mCp,
ServiceState.RIL_RADIO_TECHNOLOGY_UMTS);
doReturn(mApn1).when(mApnContext).getApnSetting();
- doReturn(ApnSetting.TYPE_DEFAULT_STRING).when(mApnContext).getApnType();
- doReturn(ApnSetting.TYPE_DEFAULT).when(mApnContext).getApnTypeBitmask();
+ doReturn(PhoneConstants.APN_TYPE_DEFAULT).when(mApnContext).getApnType();
mDcFailBringUp.saveParameters(0, 0, -2);
doReturn(mDcFailBringUp).when(mDcTesterFailBringUpAll).getDcFailBringUp();
@@ -383,25 +308,12 @@ public class DataConnectionTest extends TelephonyTest {
"com.android.phone");
mDcp.mApnContext = mApnContext;
-
- setSuccessfulSetupDataResponse(DEFAULT_DC_CID);
-
- doAnswer(invocation -> {
- final Message msg = (Message) invocation.getArguments()[2];
- msg.arg1 = DataServiceCallback.RESULT_SUCCESS;
- msg.sendToTarget();
- return null;
- }).when(mDataServiceManager).deactivateDataCall(anyInt(), anyInt(), any(Message.class));
-
- doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WWAN).when(mDataServiceManager)
- .getTransportType();
+ addDataService();
mDataConnectionTestHandler = new DataConnectionTestHandler(getClass().getSimpleName());
mDataConnectionTestHandler.start();
waitForMs(200);
- mDc.setDataCallSessionStats(mDataCallSessionStats);
-
logd("-Setup!");
}
@@ -412,9 +324,16 @@ public class DataConnectionTest extends TelephonyTest {
mDcc = null;
mDataConnectionTestHandler.quit();
mDataConnectionTestHandler.join();
+ mCellularDataService.onDestroy();
super.tearDown();
}
+ private IState getCurrentState() throws Exception {
+ Method method = StateMachine.class.getDeclaredMethod("getCurrentState");
+ method.setAccessible(true);
+ return (IState) method.invoke(mDc);
+ }
+
private long getSuggestedRetryDelay(DataCallResponse response) throws Exception {
Class[] cArgs = new Class[1];
cArgs[0] = DataCallResponse.class;
@@ -429,19 +348,8 @@ public class DataConnectionTest extends TelephonyTest {
return (boolean) method.invoke(mDc);
}
- private boolean isEnterpriseUse() throws Exception {
- Method method = DataConnection.class.getDeclaredMethod("isEnterpriseUse");
- method.setAccessible(true);
- return (boolean) method.invoke(mDc);
- }
-
- private boolean isSuspended() throws Exception {
- Field field = DataConnection.class.getDeclaredField("mIsSuspended");
- field.setAccessible(true);
- return field.getBoolean(mDc);
- }
-
- private SetupResult setLinkProperties(DataCallResponse response, LinkProperties linkProperties)
+ private SetupResult setLinkProperties(DataCallResponse response,
+ LinkProperties linkProperties)
throws Exception {
Class[] cArgs = new Class[2];
cArgs[0] = DataCallResponse.class;
@@ -453,9 +361,17 @@ public class DataConnectionTest extends TelephonyTest {
@Test
@SmallTest
- public void testConnectEvent() {
- assertTrue(mDc.isInactive());
- connectEvent(true);
+ public void testSanity() throws Exception {
+ assertEquals("DcInactiveState", getCurrentState().getName());
+ }
+
+ @Test
+ @SmallTest
+ public void testConnectEvent() throws Exception {
+ testSanity();
+
+ mDc.sendMessage(DataConnection.EVENT_CONNECT, mCp);
+ waitForMs(200);
verify(mCT, times(1)).registerForVoiceCallStarted(any(Handler.class),
eq(DataConnection.EVENT_DATA_CONNECTION_VOICE_CALL_STARTED), eq(null));
@@ -467,38 +383,16 @@ public class DataConnectionTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, times(1))
.registerForLceInfo(any(Handler.class),
eq(DataConnection.EVENT_LINK_CAPACITY_CHANGED), eq(null));
- verify(mVcnManager, atLeastOnce())
- .applyVcnNetworkPolicy(
- argThat(caps ->
- caps.hasCapability(
- NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED)),
- any());
ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
- ArgumentCaptor<TrafficDescriptor> tdCaptor =
- ArgumentCaptor.forClass(TrafficDescriptor.class);
- verify(mDataServiceManager, times(1)).setupDataCall(
+ verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
eq(AccessNetworkType.UTRAN), dpCaptor.capture(), eq(false),
- eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), tdCaptor.capture(), anyBoolean(), any(Message.class));
-
- verify(mSimulatedCommandsVerifier, times(1))
- .allocatePduSessionId(any());
+ eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(), any(Message.class));
assertEquals("spmode.ne.jp", dpCaptor.getValue().getApn());
- if (tdCaptor.getValue() != null) {
- if (mApnContext.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) {
- assertEquals(null, tdCaptor.getValue().getDataNetworkName());
- assertTrue(Arrays.equals(DataConnection.getEnterpriseOsAppId(),
- tdCaptor.getValue().getOsAppId()));
- } else {
- assertEquals("spmode.ne.jp", tdCaptor.getValue().getDataNetworkName());
- assertEquals(null, tdCaptor.getValue().getOsAppId());
- }
- }
- assertTrue(mDc.isActive());
- assertEquals(mDc.getPduSessionId(), 1);
+ assertEquals("DcActiveState", getCurrentState().getName());
+
assertEquals(3, mDc.getPcscfAddresses().length);
assertTrue(Arrays.stream(mDc.getPcscfAddresses()).anyMatch("fd00:976a:c305:1d::8"::equals));
assertTrue(Arrays.stream(mDc.getPcscfAddresses()).anyMatch("fd00:976a:c202:1d::7"::equals));
@@ -506,79 +400,20 @@ public class DataConnectionTest extends TelephonyTest {
}
@Test
- public void testConnectEventDuplicateContextIds() throws Exception {
- setUpDefaultData(DEFAULT_DC_CID);
-
- // Try to connect ENTERPRISE with the same CID as default
- replaceInstance(ConnectionParams.class, "mApnContext", mCp, mEnterpriseApnContext);
- doReturn(mApn1).when(mEnterpriseApnContext).getApnSetting();
- doReturn(ApnSetting.TYPE_ENTERPRISE_STRING).when(mEnterpriseApnContext).getApnType();
- doReturn(ApnSetting.TYPE_ENTERPRISE).when(mEnterpriseApnContext).getApnTypeBitmask();
-
- // Verify that ENTERPRISE wasn't set up
- connectEvent(false);
- assertTrue(mDc.isInactive());
-
- // Change the CID
- setSuccessfulSetupDataResponse(DEFAULT_DC_CID + 1);
-
- // Verify that ENTERPRISE was set up
- connectEvent(true);
- assertTrue(mDc.getNetworkCapabilities().hasCapability(
- NetworkCapabilities.NET_CAPABILITY_ENTERPRISE));
- }
-
- @Test
- public void testConnectEventNoDefaultData() throws Exception {
- assertFalse(mDefaultDc.isActive());
-
- // Try to connect ENTERPRISE when default data doesn't exist
- replaceInstance(ConnectionParams.class, "mApnContext", mCp, mEnterpriseApnContext);
- doReturn(mApn1).when(mEnterpriseApnContext).getApnSetting();
- doReturn(ApnSetting.TYPE_ENTERPRISE_STRING).when(mEnterpriseApnContext).getApnType();
- doReturn(ApnSetting.TYPE_ENTERPRISE).when(mEnterpriseApnContext).getApnTypeBitmask();
-
- // Verify that ENTERPRISE wasn't set up
- connectEvent(false);
- assertTrue(mDc.isInactive());
-
- // Set up default data
- replaceInstance(ConnectionParams.class, "mApnContext", mCp, mApnContext);
- setUpDefaultData(1);
-
- // Verify that ENTERPRISE was set up
- replaceInstance(ConnectionParams.class, "mApnContext", mCp, mEnterpriseApnContext);
- connectEvent(true);
- assertTrue(mDc.getNetworkCapabilities().hasCapability(
- NetworkCapabilities.NET_CAPABILITY_ENTERPRISE));
- }
-
- private void setUpDefaultData(int cid) throws Exception {
- replaceInstance(DataConnection.class, "mCid", mDefaultDc, cid);
- doReturn(true).when(mDefaultDc).isActive();
- doReturn(Arrays.asList(mApnContext)).when(mDefaultDc).getApnContexts();
- mDcc.addActiveDcByCid(mDefaultDc);
- assertTrue(mDefaultDc.getApnContexts().stream()
- .anyMatch(apn -> apn.getApnTypeBitmask() == ApnSetting.TYPE_DEFAULT));
- }
-
- @Test
@SmallTest
- public void testDisconnectEvent() {
+ public void testDisconnectEvent() throws Exception {
testConnectEvent();
- mDc.setPduSessionId(5);
- disconnectEvent();
+ mDc.sendMessage(DataConnection.EVENT_DISCONNECT, mDcp);
+ waitForMs(100);
verify(mSimulatedCommandsVerifier, times(1)).unregisterForLceInfo(any(Handler.class));
verify(mSimulatedCommandsVerifier, times(1))
.unregisterForNattKeepaliveStatus(any(Handler.class));
- verify(mDataServiceManager, times(1)).deactivateDataCall(eq(DEFAULT_DC_CID),
+ verify(mSimulatedCommandsVerifier, times(1)).deactivateDataCall(eq(1),
eq(DataService.REQUEST_REASON_NORMAL), any(Message.class));
- verify(mSimulatedCommandsVerifier, times(1))
- .releasePduSessionId(any(), eq(5));
- assertTrue(mDc.isInactive());
+ assertEquals("DcInactiveState", getCurrentState().getName());
}
@Test
@@ -586,7 +421,7 @@ public class DataConnectionTest extends TelephonyTest {
public void testModemSuggestRetry() throws Exception {
DataCallResponse response = new DataCallResponse.Builder()
.setCause(0)
- .setRetryDurationMillis(0)
+ .setSuggestedRetryTime(0)
.setId(1)
.setLinkStatus(2)
.setProtocolType(ApnSetting.PROTOCOL_IP)
@@ -604,7 +439,7 @@ public class DataConnectionTest extends TelephonyTest {
response = new DataCallResponse.Builder()
.setCause(0)
- .setRetryDurationMillis(1000)
+ .setSuggestedRetryTime(1000)
.setId(1)
.setLinkStatus(2)
.setProtocolType(ApnSetting.PROTOCOL_IP)
@@ -622,7 +457,7 @@ public class DataConnectionTest extends TelephonyTest {
response = new DataCallResponse.Builder()
.setCause(0)
- .setRetryDurationMillis(9999)
+ .setSuggestedRetryTime(9999)
.setId(1)
.setLinkStatus(2)
.setProtocolType(ApnSetting.PROTOCOL_IP)
@@ -644,7 +479,7 @@ public class DataConnectionTest extends TelephonyTest {
public void testModemNotSuggestRetry() throws Exception {
DataCallResponse response = new DataCallResponse.Builder()
.setCause(0)
- .setRetryDurationMillis(-1)
+ .setSuggestedRetryTime(-1)
.setId(1)
.setLinkStatus(2)
.setProtocolType(ApnSetting.PROTOCOL_IP)
@@ -662,7 +497,7 @@ public class DataConnectionTest extends TelephonyTest {
response = new DataCallResponse.Builder()
.setCause(0)
- .setRetryDurationMillis(-5)
+ .setSuggestedRetryTime(-5)
.setId(1)
.setLinkStatus(2)
.setProtocolType(ApnSetting.PROTOCOL_IP)
@@ -680,7 +515,7 @@ public class DataConnectionTest extends TelephonyTest {
response = new DataCallResponse.Builder()
.setCause(0)
- .setRetryDurationMillis(Long.MIN_VALUE)
+ .setSuggestedRetryTime(Integer.MIN_VALUE)
.setId(1)
.setLinkStatus(2)
.setProtocolType(ApnSetting.PROTOCOL_IP)
@@ -702,7 +537,7 @@ public class DataConnectionTest extends TelephonyTest {
public void testModemSuggestNoRetry() throws Exception {
DataCallResponse response = new DataCallResponse.Builder()
.setCause(0)
- .setRetryDurationMillis(Long.MAX_VALUE)
+ .setSuggestedRetryTime(Integer.MAX_VALUE)
.setId(1)
.setLinkStatus(2)
.setProtocolType(ApnSetting.PROTOCOL_IP)
@@ -719,6 +554,12 @@ public class DataConnectionTest extends TelephonyTest {
assertEquals(RetryManager.NO_RETRY, getSuggestedRetryDelay(response));
}
+ private NetworkInfo getNetworkInfo() throws Exception {
+ Field f = DataConnection.class.getDeclaredField("mNetworkInfo");
+ f.setAccessible(true);
+ return (NetworkInfo) f.get(mDc);
+ }
+
private NetworkCapabilities getNetworkCapabilities() throws Exception {
Method method = DataConnection.class.getDeclaredMethod("getNetworkCapabilities");
method.setAccessible(true);
@@ -746,52 +587,16 @@ public class DataConnectionTest extends TelephonyTest {
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET));
assertFalse("capabilities: " + getNetworkCapabilities(), getNetworkCapabilities()
.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS));
- assertFalse("capabilities: " + getNetworkCapabilities(), getNetworkCapabilities()
- .hasCapability(NetworkCapabilities.NET_CAPABILITY_ENTERPRISE));
mContextFixture.getCarrierConfigBundle().putStringArray(
CarrierConfigManager.KEY_CARRIER_WWAN_DISALLOWED_APN_TYPES_STRING_ARRAY,
new String[] {"supl"});
- disconnectEvent();
+ mDc.sendMessage(DataConnection.EVENT_DISCONNECT, mDcp);
+ waitForMs(100);
doReturn(mApn1).when(mApnContext).getApnSetting();
- connectEvent(true);
-
- assertFalse("capabilities: " + getNetworkCapabilities(), getNetworkCapabilities()
- .hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN));
- assertTrue("capabilities: " + getNetworkCapabilities(), getNetworkCapabilities()
- .hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET));
- assertFalse("capabilities: " + getNetworkCapabilities(), getNetworkCapabilities()
- .hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL));
- assertFalse("capabilities: " + getNetworkCapabilities(), getNetworkCapabilities()
- .hasCapability(NetworkCapabilities.NET_CAPABILITY_ENTERPRISE));
- }
-
- @Test
- @SmallTest
- public void testEnterpriseNetworkCapability() throws Exception {
- mContextFixture.getCarrierConfigBundle().putStringArray(
- CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[] { "default" });
- doReturn(mApn2).when(mApnContext).getApnSetting();
- testConnectEvent();
-
- assertTrue("capabilities: " + getNetworkCapabilities(), getNetworkCapabilities()
- .hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN));
- assertTrue("capabilities: " + getNetworkCapabilities(), getNetworkCapabilities()
- .hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET));
- assertFalse("capabilities: " + getNetworkCapabilities(), getNetworkCapabilities()
- .hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS));
- assertFalse("capabilities: " + getNetworkCapabilities(), getNetworkCapabilities()
- .hasCapability(NetworkCapabilities.NET_CAPABILITY_ENTERPRISE));
-
- disconnectEvent();
- setUpDefaultData(1);
- replaceInstance(ConnectionParams.class, "mApnContext", mCp, mEnterpriseApnContext);
- doReturn(mApn1).when(mEnterpriseApnContext).getApnSetting();
- doReturn(ApnSetting.TYPE_ENTERPRISE_STRING).when(mEnterpriseApnContext).getApnType();
- doReturn(ApnSetting.TYPE_ENTERPRISE).when(mEnterpriseApnContext).getApnTypeBitmask();
- connectEvent(true);
+ mDc.sendMessage(DataConnection.EVENT_CONNECT, mCp);
+ waitForMs(200);
assertFalse("capabilities: " + getNetworkCapabilities(), getNetworkCapabilities()
.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN));
@@ -799,8 +604,6 @@ public class DataConnectionTest extends TelephonyTest {
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET));
assertFalse("capabilities: " + getNetworkCapabilities(), getNetworkCapabilities()
.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL));
- assertTrue("capabilities: " + getNetworkCapabilities(), getNetworkCapabilities()
- .hasCapability(NetworkCapabilities.NET_CAPABILITY_ENTERPRISE));
}
@Test
@@ -814,6 +617,7 @@ public class DataConnectionTest extends TelephonyTest {
testConnectEvent();
assertFalse(getNetworkCapabilities().hasCapability(NET_CAPABILITY_NOT_METERED));
+ assertFalse(getNetworkCapabilities().hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED));
}
@Test
@@ -837,21 +641,17 @@ public class DataConnectionTest extends TelephonyTest {
new String[] { "default" });
testConnectEvent();
- assertFalse(getNetworkCapabilities().hasCapability(NET_CAPABILITY_NOT_METERED));
assertFalse(getNetworkCapabilities().hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED));
assertTrue(getNetworkCapabilities().hasCapability(NET_CAPABILITY_NOT_CONGESTED));
- mDc.onMeterednessChanged(true);
- waitForMs(100);
+ mDc.onSubscriptionOverride(SUBSCRIPTION_OVERRIDE_UNMETERED,
+ SUBSCRIPTION_OVERRIDE_UNMETERED);
- assertFalse(getNetworkCapabilities().hasCapability(NET_CAPABILITY_NOT_METERED));
assertTrue(getNetworkCapabilities().hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED));
assertTrue(getNetworkCapabilities().hasCapability(NET_CAPABILITY_NOT_CONGESTED));
- mDc.onMeterednessChanged(false);
- waitForMs(100);
+ mDc.onSubscriptionOverride(SUBSCRIPTION_OVERRIDE_UNMETERED, 0);
- assertFalse(getNetworkCapabilities().hasCapability(NET_CAPABILITY_NOT_METERED));
assertFalse(getNetworkCapabilities().hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED));
assertTrue(getNetworkCapabilities().hasCapability(NET_CAPABILITY_NOT_CONGESTED));
}
@@ -864,35 +664,21 @@ public class DataConnectionTest extends TelephonyTest {
testConnectEvent();
assertFalse(getNetworkCapabilities().hasCapability(NET_CAPABILITY_NOT_METERED));
- assertFalse(getNetworkCapabilities().hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED));
assertTrue(getNetworkCapabilities().hasCapability(NET_CAPABILITY_NOT_CONGESTED));
- mDc.onCongestednessChanged(true);
- waitForMs(100);
+ mDc.onSubscriptionOverride(SUBSCRIPTION_OVERRIDE_CONGESTED,
+ SUBSCRIPTION_OVERRIDE_CONGESTED);
assertFalse(getNetworkCapabilities().hasCapability(NET_CAPABILITY_NOT_METERED));
- assertFalse(getNetworkCapabilities().hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED));
assertFalse(getNetworkCapabilities().hasCapability(NET_CAPABILITY_NOT_CONGESTED));
- mDc.onCongestednessChanged(false);
- waitForMs(100);
+ mDc.onSubscriptionOverride(SUBSCRIPTION_OVERRIDE_CONGESTED, 0);
assertFalse(getNetworkCapabilities().hasCapability(NET_CAPABILITY_NOT_METERED));
- assertFalse(getNetworkCapabilities().hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED));
assertTrue(getNetworkCapabilities().hasCapability(NET_CAPABILITY_NOT_CONGESTED));
}
@Test
- public void testSubscriptionIds() throws Exception {
- mContextFixture.getCarrierConfigBundle().putStringArray(
- CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[] { "default" });
- testConnectEvent();
-
- assertEquals(Collections.singleton(0), getNetworkCapabilities().getSubscriptionIds());
- }
-
- @Test
public void testShouldSkip464Xlat() throws Exception {
assertFalse(testShouldSkip464XlatEvent(mApn1));
disconnectEvent();
@@ -912,36 +698,27 @@ public class DataConnectionTest extends TelephonyTest {
method.setAccessible(true);
doReturn(apn).when(mApnContext).getApnSetting();
- doReturn(apn.getApnTypeBitmask()).when(mApnContext).getApnTypeBitmask();
- connectEvent(true);
+ connectEvent();
logd(getNetworkCapabilities().toString());
return (Boolean) method.invoke(mDc);
}
- private void connectEvent(boolean validate) {
+ private void connectEvent() throws Exception {
mDc.sendMessage(DataConnection.EVENT_CONNECT, mCp);
waitForMs(200);
- if (validate) {
- assertTrue(mDc.isActive());
- }
+ assertEquals("DcActiveState", getCurrentState().getName());
}
- private void disconnectEvent() {
+ private void disconnectEvent() throws Exception {
mDc.sendMessage(DataConnection.EVENT_DISCONNECT, mDcp);
waitForMs(100);
- assertTrue(mDc.isInactive());
- }
-
- private void serviceStateChangedEvent(@RegState int dataRegState, @RilRadioTechnology int rat) {
- mDc.obtainMessage(DataConnection.EVENT_DATA_CONNECTION_DRS_OR_RAT_CHANGED,
- new AsyncResult(null, new Pair<>(dataRegState, rat), null)).sendToTarget();
- waitForMs(100);
+ assertEquals("DcInactiveState", getCurrentState().getName());
}
@Test
@SmallTest
- public void testIsIpAddress() {
+ public void testIsIpAddress() throws Exception {
// IPv4
assertTrue(DataConnection.isIpAddress("1.2.3.4"));
assertTrue(DataConnection.isIpAddress("127.0.0.1"));
@@ -956,7 +733,7 @@ public class DataConnectionTest extends TelephonyTest {
public void testSetLinkProperties() throws Exception {
DataCallResponse response = new DataCallResponse.Builder()
.setCause(0)
- .setRetryDurationMillis(-1)
+ .setSuggestedRetryTime(-1)
.setId(1)
.setLinkStatus(2)
.setProtocolType(ApnSetting.PROTOCOL_IP)
@@ -1012,7 +789,7 @@ public class DataConnectionTest extends TelephonyTest {
// 224.224.224.224 is an invalid address.
DataCallResponse response = new DataCallResponse.Builder()
.setCause(0)
- .setRetryDurationMillis(-1)
+ .setSuggestedRetryTime(-1)
.setId(1)
.setLinkStatus(2)
.setProtocolType(ApnSetting.PROTOCOL_IP)
@@ -1035,7 +812,7 @@ public class DataConnectionTest extends TelephonyTest {
// Empty dns entry.
DataCallResponse response = new DataCallResponse.Builder()
.setCause(0)
- .setRetryDurationMillis(-1)
+ .setSuggestedRetryTime(-1)
.setId(1)
.setLinkStatus(2)
.setProtocolType(ApnSetting.PROTOCOL_IP)
@@ -1248,24 +1025,6 @@ public class DataConnectionTest extends TelephonyTest {
}
@Test
- public void testIsEnterpriseUse() throws Exception {
- assertFalse(isEnterpriseUse());
- assertFalse(mDc.getNetworkCapabilities().hasCapability(
- NetworkCapabilities.NET_CAPABILITY_ENTERPRISE));
-
- setUpDefaultData(1);
- replaceInstance(ConnectionParams.class, "mApnContext", mCp, mEnterpriseApnContext);
- doReturn(mApn1).when(mEnterpriseApnContext).getApnSetting();
- doReturn(ApnSetting.TYPE_ENTERPRISE_STRING).when(mEnterpriseApnContext).getApnType();
- doReturn(ApnSetting.TYPE_ENTERPRISE).when(mEnterpriseApnContext).getApnTypeBitmask();
- connectEvent(true);
-
- assertTrue(isEnterpriseUse());
- assertTrue(mDc.getNetworkCapabilities().hasCapability(
- NetworkCapabilities.NET_CAPABILITY_ENTERPRISE));
- }
-
- @Test
@SmallTest
public void testGetDisallowedApnTypes() throws Exception {
mContextFixture.getCarrierConfigBundle().putStringArray(
@@ -1276,108 +1035,4 @@ public class DataConnectionTest extends TelephonyTest {
assertEquals(ApnSetting.TYPE_MMS | ApnSetting.TYPE_SUPL | ApnSetting.TYPE_FOTA,
getDisallowedApnTypes());
}
-
- @Test
- public void testIsSuspended() throws Exception {
- // Return false if not active state
- assertTrue(mDc.isInactive());
- assertFalse(isSuspended());
-
- // Return false for emergency APN
- doReturn(mApn6).when(mApnContext).getApnSetting();
- doReturn(ApnSetting.TYPE_EMERGENCY).when(mApnContext).getApnTypeBitmask();
- connectEvent(true);
- assertFalse(isSuspended());
-
- // Back to DEFAULT APN
- disconnectEvent();
- assertTrue(mDc.isInactive());
- doReturn(mApn1).when(mApnContext).getApnSetting();
- doReturn(ApnSetting.TYPE_DEFAULT).when(mApnContext).getApnTypeBitmask();
- doReturn(true).when(mSST).isConcurrentVoiceAndDataAllowed();
- connectEvent(true);
-
- // Before getting any service state event, the connection should not be suspended.
- assertFalse(isSuspended());
-
- // Return true if combined reg state is not in service
- serviceStateChangedEvent(ServiceState.STATE_OUT_OF_SERVICE,
- ServiceState.RIL_RADIO_TECHNOLOGY_UNKNOWN);
- assertTrue(isSuspended());
-
- // Return false if in service and concurrent voice and data is allowed
- serviceStateChangedEvent(ServiceState.STATE_IN_SERVICE,
- ServiceState.RIL_RADIO_TECHNOLOGY_LTE);
- assertFalse(isSuspended());
-
- // Return false if in service and concurrent voice/data not allowed but call state is idle
- doReturn(false).when(mSST).isConcurrentVoiceAndDataAllowed();
- doReturn(PhoneConstants.State.IDLE).when(mCT).getState();
- mDc.sendMessage(DataConnection.EVENT_DATA_CONNECTION_VOICE_CALL_STARTED);
- waitForMs(100);
- assertFalse(isSuspended());
-
- // Return true if in service, concurrent voice/data not allowed, and call state not idle
- doReturn(PhoneConstants.State.RINGING).when(mCT).getState();
- mDc.sendMessage(DataConnection.EVENT_DATA_CONNECTION_VOICE_CALL_STARTED);
- waitForMs(100);
- assertTrue(isSuspended());
- }
-
- @Test
- public void testDataCreatedWhenOutOfService() throws Exception {
- serviceStateChangedEvent(ServiceState.STATE_OUT_OF_SERVICE,
- ServiceState.RIL_RADIO_TECHNOLOGY_UNKNOWN);
- ArgumentCaptor<NetworkCapabilities> ncCaptor =
- ArgumentCaptor.forClass(NetworkCapabilities.class);
- doReturn(mock(Network.class)).when(mConnectivityManager).registerNetworkAgent(
- any(), any(), any(), ncCaptor.capture(), any(), any(), anyInt());
-
- doReturn(mApn1).when(mApnContext).getApnSetting();
- doReturn(ApnSetting.TYPE_DEFAULT).when(mApnContext).getApnTypeBitmask();
- doReturn(true).when(mSST).isConcurrentVoiceAndDataAllowed();
- connectEvent(true);
- waitForMs(100);
-
- NetworkCapabilities nc = ncCaptor.getValue();
- // The network must be created with NOT_SUSPENDED capability.
- assertTrue(nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED));
-
- // But it's final state must be suspended.
- assertTrue(isSuspended());
- }
-
- @Test
- public void testDataServiceTempUnavailable() throws Exception {
- setFailedSetupDataResponse(DataServiceCallback.RESULT_ERROR_TEMPORARILY_UNAVAILABLE);
- replaceInstance(ConnectionParams.class, "mRequestType", mCp,
- DcTracker.REQUEST_TYPE_NORMAL);
- // Verify that no data was setup
- connectEvent(false);
- assertTrue(mDc.isInactive());
-
- // Verify that data service did not suggest any retry (i.e. Frameworks uses configured
- // retry timer).
- verify(mDataThrottler).setRetryTime(eq(ApnSetting.TYPE_DEFAULT | ApnSetting.TYPE_SUPL),
- eq(RetryManager.NO_SUGGESTED_RETRY_DELAY), eq(DcTracker.REQUEST_TYPE_NORMAL));
- }
-
- @Test
- public void testDataHandoverFailed() throws Exception {
- doReturn(mDefaultDc).when(mDcTracker).getDataConnectionByApnType(anyString());
-
- doAnswer(invocation -> {
- final Consumer<Integer> consumer = (Consumer<Integer>) invocation.getArguments()[0];
- consumer.accept(DataServiceCallback.RESULT_SUCCESS);
- return null;
- }).when(mDefaultDc).startHandover(any(Consumer.class));
-
- replaceInstance(ConnectionParams.class, "mRequestType", mCp,
- DcTracker.REQUEST_TYPE_HANDOVER);
- assertTrue(mDc.isInactive());
- connectEvent(false);
-
- // Make sure the data connection is still in inactive state
- assertTrue(mDc.isInactive());
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataEnabledSettingsTest.java b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataEnabledSettingsTest.java
index 08fa5b640b..52c9573a87 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataEnabledSettingsTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataEnabledSettingsTest.java
@@ -27,7 +27,6 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
import android.os.HandlerThread;
-import android.telephony.TelephonyManager;
import android.telephony.data.ApnSetting;
import android.test.suitebuilder.annotation.SmallTest;
@@ -105,7 +104,7 @@ public class DataEnabledSettingsTest extends TelephonyTest {
@Test
@SmallTest
public void testSetAlwaysAllowMmsData() throws Exception {
- mDataEnabledSettingsUT.setDataEnabled(TelephonyManager.DATA_ENABLED_REASON_USER, false);
+ mDataEnabledSettingsUT.setUserDataEnabled(false);
assertTrue(mDataEnabledSettingsUT.setAlwaysAllowMmsData(true));
ArgumentCaptor<String> stringCaptor = ArgumentCaptor.forClass(String.class);
verify(mSubscriptionController).setDataEnabledOverrideRules(anyInt(),
@@ -121,23 +120,7 @@ public class DataEnabledSettingsTest extends TelephonyTest {
assertEquals("", stringCaptor.getValue());
assertFalse(mDataEnabledSettingsUT.isDataEnabled(ApnSetting.TYPE_MMS));
- mDataEnabledSettingsUT.setDataEnabled(TelephonyManager.DATA_ENABLED_REASON_USER, true);
+ mDataEnabledSettingsUT.setUserDataEnabled(true);
assertTrue(mDataEnabledSettingsUT.isDataEnabled(ApnSetting.TYPE_MMS));
}
-
- @Test
- @SmallTest
- public void testSetThermalDataEnabled() throws Exception {
- mDataEnabledSettingsUT.setDataEnabled(TelephonyManager.DATA_ENABLED_REASON_THERMAL,
- false);
- assertFalse(mDataEnabledSettingsUT.isDataEnabledForReason(
- TelephonyManager.DATA_ENABLED_REASON_THERMAL));
- assertFalse(mDataEnabledSettingsUT.isDataEnabled());
-
- mDataEnabledSettingsUT.setDataEnabled(TelephonyManager.DATA_ENABLED_REASON_THERMAL,
- true);
- assertTrue(mDataEnabledSettingsUT.isDataEnabledForReason(
- TelephonyManager.DATA_ENABLED_REASON_THERMAL));
- assertTrue(mDataEnabledSettingsUT.isDataEnabled());
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataProfileTest.java b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataProfileTest.java
index b641ecd6ff..55f621ab64 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataProfileTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataProfileTest.java
@@ -107,33 +107,6 @@ public class DataProfileTest extends TestCase {
-1, // mvno_type
""); // mnvo_match_data
- private ApnSetting mApn4 = ApnSetting.makeApnSetting(
- 2163, // id
- "44010", // numeric
- "sp-mode", // name
- "fake_apn", // apn
- null, // proxy
- -1, // port
- null, // mmsc
- null, // mmsproxy
- -1, // mmsport
- "user", // user
- "passwd", // password
- -1, // authtype
- ApnSetting.TYPE_DEFAULT | ApnSetting.TYPE_SUPL, // types
- ApnSetting.PROTOCOL_IP, // protocol
- ApnSetting.PROTOCOL_IP, // roaming_protocol
- true, // carrier_enabled
- 10360, // networktype_bitmask
- 1234, // profile_id
- false, // modem_cognitive
- 111, // max_conns
- 456, // wait_time
- 789, // max_conns_time
- 0, // mtu
- -1, // mvno_type
- ""); // mnvo_match_data
-
@SmallTest
public void testCreateFromApnSetting() throws Exception {
DataProfile dp = DcTracker.createDataProfile(mApn1, mApn1.getProfileId(), false);
@@ -159,13 +132,11 @@ public class DataProfileTest extends TestCase {
assertEquals(RILConstants.SETUP_DATA_AUTH_PAP_CHAP, dp.getAuthType());
assertEquals(mApn3.getUser(), dp.getUserName());
assertEquals(mApn3.getPassword(), dp.getPassword());
- assertEquals(0, dp.getType()); // TYPE_COMMON
+ assertEquals(2, dp.getType()); // TYPE_3GPP2
assertEquals(mApn3.getWaitTime(), dp.getWaitTime());
assertEquals(mApn3.isEnabled(), dp.isEnabled());
int expectedBearerBitmap = mApn3.getNetworkTypeBitmask();
assertEquals(expectedBearerBitmap, dp.getBearerBitmask());
- dp = DcTracker.createDataProfile(mApn4, mApn4.getProfileId(), false);
- assertEquals(2, dp.getType()); // TYPE_3GPP2
}
@SmallTest
diff --git a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataThrottlerTest.java b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataThrottlerTest.java
deleted file mode 100644
index fb9a8b679b..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DataThrottlerTest.java
+++ /dev/null
@@ -1,235 +0,0 @@
-/**
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.internal.telephony.dataconnection;
-
-import static com.android.internal.telephony.dataconnection.DcTracker.REQUEST_TYPE_HANDOVER;
-import static com.android.internal.telephony.dataconnection.DcTracker.REQUEST_TYPE_NORMAL;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
-import android.telephony.AccessNetworkConstants;
-import android.telephony.data.ApnSetting;
-import android.telephony.data.ThrottleStatus;
-import android.test.suitebuilder.annotation.SmallTest;
-import android.testing.AndroidTestingRunner;
-import android.testing.TestableLooper;
-
-import com.android.internal.telephony.RetryManager;
-import com.android.internal.telephony.TelephonyTest;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mock;
-
-import java.util.ArrayList;
-import java.util.Comparator;
-import java.util.List;
-
-/**
- * Data throttler tests
- */
-@RunWith(AndroidTestingRunner.class)
-@TestableLooper.RunWithLooper
-public class DataThrottlerTest extends TelephonyTest {
-
- private static final boolean DBG = true;
- private DataThrottler mDataThrottler;
-
- @Mock
- private DataThrottler.Callback mMockChangedCallback1;
-
- @Mock
- private DataThrottler.Callback mMockChangedCallback2;
-
- private static final int DEFAULT_APN_TYPE = ApnSetting.TYPE_DEFAULT & ~(ApnSetting.TYPE_HIPRI);
-
- @Before
- public void setUp() throws Exception {
- super.setUp(getClass().getSimpleName());
- mDataThrottler = new DataThrottler(mPhone, AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
- mDataThrottler.registerForThrottleStatusChanges(mMockChangedCallback1);
- }
-
- @After
- public void tearDown() throws Exception {
- super.tearDown();
- }
-
- /**
- * Test the behavior of a retry manager with no waiting APNs set.
- */
- @Test
- @SmallTest
- public void testSetRetryTime() throws Exception {
- final ArgumentCaptor<List<ThrottleStatus>> statusCaptor =
- ArgumentCaptor.forClass((Class) List.class);
-
- List<List<ThrottleStatus>> expectedStatuses = new ArrayList<>();
- processAllMessages();
- expectedStatuses.add(List.of());
-
- mDataThrottler.setRetryTime(ApnSetting.TYPE_DEFAULT, 1234567890L,
- REQUEST_TYPE_NORMAL);
- processAllMessages();
- assertEquals(1234567890L, mDataThrottler.getRetryTime(ApnSetting.TYPE_DEFAULT));
- assertEquals(RetryManager.NO_SUGGESTED_RETRY_DELAY,
- mDataThrottler.getRetryTime(ApnSetting.TYPE_MMS));
-
- processAllMessages();
- expectedStatuses.add(List.of(
- new ThrottleStatus.Builder()
- .setSlotIndex(0)
- .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
- .setApnType(ApnSetting.TYPE_HIPRI)
- .setThrottleExpiryTimeMillis(1234567890L)
- .setRetryType(ThrottleStatus.RETRY_TYPE_NEW_CONNECTION)
- .build(),
- new ThrottleStatus.Builder()
- .setSlotIndex(0)
- .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
- .setApnType(DEFAULT_APN_TYPE)
- .setThrottleExpiryTimeMillis(1234567890L)
- .setRetryType(ThrottleStatus.RETRY_TYPE_NEW_CONNECTION)
- .build())
- );
-
-
- mDataThrottler.setRetryTime(ApnSetting.TYPE_DEFAULT | ApnSetting.TYPE_DUN, 13579L,
- REQUEST_TYPE_HANDOVER);
- processAllMessages();
- assertEquals(13579L, mDataThrottler.getRetryTime(ApnSetting.TYPE_DEFAULT));
- assertEquals(13579L, mDataThrottler.getRetryTime(ApnSetting.TYPE_DUN));
-
- processAllMessages();
- expectedStatuses.add(List.of(
- new ThrottleStatus.Builder()
- .setSlotIndex(0)
- .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
- .setApnType(ApnSetting.TYPE_HIPRI)
- .setThrottleExpiryTimeMillis(13579L)
- .setRetryType(ThrottleStatus.RETRY_TYPE_HANDOVER)
- .build(),
- new ThrottleStatus.Builder()
- .setSlotIndex(0)
- .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
- .setApnType(ApnSetting.TYPE_DUN)
- .setThrottleExpiryTimeMillis(13579L)
- .setRetryType(ThrottleStatus.RETRY_TYPE_HANDOVER)
- .build(),
- new ThrottleStatus.Builder()
- .setSlotIndex(0)
- .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
- .setApnType(DEFAULT_APN_TYPE)
- .setThrottleExpiryTimeMillis(13579L)
- .setRetryType(ThrottleStatus.RETRY_TYPE_HANDOVER)
- .build())
- );
-
-
- mDataThrottler.setRetryTime(ApnSetting.TYPE_MMS, -10,
- REQUEST_TYPE_NORMAL);
- processAllMessages();
- assertEquals(RetryManager.NO_SUGGESTED_RETRY_DELAY,
- mDataThrottler.getRetryTime(ApnSetting.TYPE_MMS));
- processAllMessages();
- expectedStatuses.add(List.of(
- new ThrottleStatus.Builder()
- .setSlotIndex(0)
- .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
- .setNoThrottle()
- .setApnType(ApnSetting.TYPE_MMS)
- .setRetryType(ThrottleStatus.RETRY_TYPE_NEW_CONNECTION)
- .build()
- ));
-
- mDataThrottler.setRetryTime(ApnSetting.TYPE_FOTA | ApnSetting.TYPE_EMERGENCY,
- RetryManager.NO_RETRY, REQUEST_TYPE_HANDOVER);
-
- processAllMessages();
- expectedStatuses.add(List.of(
- new ThrottleStatus.Builder()
- .setSlotIndex(0)
- .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
- .setApnType(ApnSetting.TYPE_EMERGENCY)
- .setThrottleExpiryTimeMillis(RetryManager.NO_RETRY)
- .setRetryType(ThrottleStatus.RETRY_TYPE_NONE)
- .build(),
- new ThrottleStatus.Builder()
- .setSlotIndex(0)
- .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
- .setApnType(ApnSetting.TYPE_FOTA)
- .setThrottleExpiryTimeMillis(RetryManager.NO_RETRY)
- .setRetryType(ThrottleStatus.RETRY_TYPE_NONE)
- .build()
- ));
-
- assertEquals(RetryManager.NO_RETRY, mDataThrottler.getRetryTime(ApnSetting.TYPE_FOTA));
- assertEquals(RetryManager.NO_RETRY, mDataThrottler.getRetryTime(ApnSetting.TYPE_EMERGENCY));
-
-
- // Loop through statuses and test everything
- verify(mMockChangedCallback1, times(expectedStatuses.size()))
- .onThrottleStatusChanged(statusCaptor.capture());
-
- // Check actual statuses
- List<List<ThrottleStatus>> actualStatuses =
- (List<List<ThrottleStatus>>) statusCaptor.getAllValues();
- assertEquals(expectedStatuses.size(), actualStatuses.size());
-
- if (DBG) {
- logd("expectedStatuses.size() = " + expectedStatuses.size());
- logd("actualStatuses.size() = " + actualStatuses.size());
- }
-
- Comparator<ThrottleStatus> comparator = (o1, o2) ->
- Integer.compare(o1.getApnType(), o2.getApnType());
-
- for (int i = 0; i < expectedStatuses.size(); i++) {
- List<ThrottleStatus> atsExpected = new ArrayList<>(expectedStatuses.get(i));
- List<ThrottleStatus> atsActual = new ArrayList<>(actualStatuses.get(i));
-
- atsExpected.sort(comparator);
- atsActual.sort(comparator);
- assertEquals("Lists at index " + i + " don't match",
- atsExpected, atsActual);
- }
-
- this.mDataThrottler.registerForThrottleStatusChanges(mMockChangedCallback2);
- }
-
- /**
- * Test the behavior of a retry manager with no waiting APNs set.
- */
- @Test
- @SmallTest
- public void testUnthrottle() throws Exception {
- mDataThrottler.setRetryTime(ApnSetting.TYPE_DEFAULT, 1234567890L,
- REQUEST_TYPE_NORMAL);
- processAllMessages();
- assertEquals(1234567890L, mDataThrottler.getRetryTime(ApnSetting.TYPE_DEFAULT));
-
- mDataThrottler.reset();
- processAllMessages();
- assertEquals(RetryManager.NO_SUGGESTED_RETRY_DELAY,
- mDataThrottler.getRetryTime(ApnSetting.TYPE_DEFAULT));
- }
-}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DcControllerTest.java b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DcControllerTest.java
index 003f74eef4..a0c9913e0a 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DcControllerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DcControllerTest.java
@@ -24,7 +24,6 @@ import static com.android.internal.telephony.dataconnection.DcTrackerTest.FAKE_P
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
-import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
@@ -37,7 +36,6 @@ import android.net.LinkProperties;
import android.os.AsyncResult;
import android.os.Handler;
import android.os.Looper;
-import android.os.Message;
import android.telephony.AccessNetworkConstants;
import android.telephony.data.ApnSetting;
import android.telephony.data.DataCallResponse;
@@ -55,7 +53,6 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import java.lang.reflect.Method;
@@ -68,10 +65,7 @@ import java.util.List;
public class DcControllerTest extends TelephonyTest {
private static final int DATA_CONNECTION_ACTIVE_PH_LINK_DORMANT = 1;
- private static final int DATA_CONNECTION_ACTIVE_PH_LINK_ACTIVE = 2;
-
private static final int EVENT_DATA_STATE_CHANGED = 0x00040007;
- private static final int EVENT_PHYSICAL_LINK_STATE_CHANGED = 1;
@Mock
private DataConnection mDc;
@@ -79,8 +73,6 @@ public class DcControllerTest extends TelephonyTest {
private List<ApnContext> mApnContexts;
@Mock
private DataServiceManager mDataServiceManager;
- @Mock
- private Handler mTestHandler;
UpdateLinkPropertyResult mResult;
@@ -111,8 +103,9 @@ public class DcControllerTest extends TelephonyTest {
doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
.when(mDataServiceManager).getTransportType();
- mDcc = DcController.makeDcc(mPhone, mDcTracker, mDataServiceManager, Looper.myLooper(),
- "");
+ mDcc = DcController.makeDcc(mPhone, mDcTracker, mDataServiceManager,
+ new Handler(Looper.myLooper()), "");
+ mDcc.start();
processAllMessages();
}
@@ -124,10 +117,11 @@ public class DcControllerTest extends TelephonyTest {
@Test
@SmallTest
public void testDataDormant() throws Exception {
+ assertEquals("DccDefaultState", getCurrentState().getName());
ArrayList<DataCallResponse> l = new ArrayList<>();
DataCallResponse dcResponse = new DataCallResponse.Builder()
.setCause(0)
- .setRetryDurationMillis(-1)
+ .setSuggestedRetryTime(-1)
.setId(1)
.setLinkStatus(DATA_CONNECTION_ACTIVE_PH_LINK_DORMANT)
.setProtocolType(ApnSetting.PROTOCOL_IP)
@@ -146,137 +140,9 @@ public class DcControllerTest extends TelephonyTest {
mDc.mCid = 1;
mDcc.addActiveDcByCid(mDc);
- mDcc.sendMessage(mDcc.obtainMessage(EVENT_DATA_STATE_CHANGED,
- new AsyncResult(null, l, null)));
+ mDcc.sendMessage(EVENT_DATA_STATE_CHANGED, new AsyncResult(null, l, null));
processAllMessages();
verify(mDcTracker, times(1)).sendStopNetStatPoll(eq(DctConstants.Activity.DORMANT));
}
-
- @Test
- @SmallTest
- public void testPhysicalLinkStateChanged_defaultApnTypeAndDormant_registrantNotifyResult()
- throws Exception {
- ArrayList<DataCallResponse> l = new ArrayList<>();
- DataCallResponse dcResponse = new DataCallResponse.Builder()
- .setCause(0)
- .setRetryDurationMillis(-1)
- .setId(1)
- .setLinkStatus(DATA_CONNECTION_ACTIVE_PH_LINK_DORMANT)
- .setProtocolType(ApnSetting.PROTOCOL_IP)
- .setInterfaceName(FAKE_IFNAME)
- .setAddresses(Arrays.asList(
- new LinkAddress(InetAddresses.parseNumericAddress(FAKE_ADDRESS), 0)))
- .setDnsAddresses(Arrays.asList(InetAddresses.parseNumericAddress(FAKE_DNS)))
- .setGatewayAddresses(Arrays.asList(InetAddresses.parseNumericAddress(FAKE_GATEWAY)))
- .setPcscfAddresses(
- Arrays.asList(InetAddresses.parseNumericAddress(FAKE_PCSCF_ADDRESS)))
- .setMtuV4(1440)
- .setMtuV6(1440)
- .build();
- l.add(dcResponse);
- mDc.mCid = 1;
- mDcc.addActiveDcByCid(mDc);
- ApnContext apnContext = new ApnContext(mPhone, ApnSetting.TYPE_DEFAULT, TAG, mDcTracker, 1);
- List<ApnContext> apnContextList = new ArrayList<>();
- apnContextList.add(apnContext);
- doReturn(apnContextList).when(mDc).getApnContexts();
- doReturn(true).when(mDcTracker).getLteEndcUsingUserDataForIdleDetection();
- mDcc.registerForPhysicalLinkStateChanged(mTestHandler, EVENT_PHYSICAL_LINK_STATE_CHANGED);
-
- mDcc.sendMessage(mDcc.obtainMessage(EVENT_DATA_STATE_CHANGED,
- new AsyncResult(null, l, null)));
- processAllMessages();
-
- ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
- verify(mTestHandler, times(1)).sendMessageDelayed(messageCaptor.capture(), anyLong());
- Message message = messageCaptor.getValue();
- assertEquals(EVENT_PHYSICAL_LINK_STATE_CHANGED, message.what);
- AsyncResult ar = (AsyncResult) message.obj;
- assertEquals(DcController.PHYSICAL_LINK_NOT_ACTIVE, (int) ar.result);
- }
-
- @Test
- @SmallTest
- public void testPhysicalLinkStateChanged_imsApnTypeAndDormant_NoNotifyResult()
- throws Exception {
- testPhysicalLinkStateChanged_defaultApnTypeAndDormant_registrantNotifyResult();
-
- ArrayList<DataCallResponse> l = new ArrayList<>();
- DataCallResponse dcResponse = new DataCallResponse.Builder()
- .setCause(0)
- .setRetryDurationMillis(-1)
- .setId(1)
- .setLinkStatus(DATA_CONNECTION_ACTIVE_PH_LINK_ACTIVE)
- .setProtocolType(ApnSetting.PROTOCOL_IP)
- .setInterfaceName(FAKE_IFNAME)
- .setAddresses(Arrays.asList(
- new LinkAddress(InetAddresses.parseNumericAddress(FAKE_ADDRESS), 0)))
- .setDnsAddresses(Arrays.asList(InetAddresses.parseNumericAddress(FAKE_DNS)))
- .setGatewayAddresses(Arrays.asList(InetAddresses.parseNumericAddress(FAKE_GATEWAY)))
- .setPcscfAddresses(
- Arrays.asList(InetAddresses.parseNumericAddress(FAKE_PCSCF_ADDRESS)))
- .setMtuV4(1440)
- .setMtuV6(1440)
- .build();
- l.add(dcResponse);
- mDc.mCid = 1;
- mDcc.addActiveDcByCid(mDc);
- ApnContext apnContext = new ApnContext(mPhone, ApnSetting.TYPE_IMS, TAG, mDcTracker, 1);
- List<ApnContext> apnContextList = new ArrayList<>();
- apnContextList.add(apnContext);
- doReturn(apnContextList).when(mDc).getApnContexts();
- doReturn(true).when(mDcTracker).getLteEndcUsingUserDataForIdleDetection();
-
- mDcc.sendMessage(mDcc.obtainMessage(EVENT_DATA_STATE_CHANGED,
- new AsyncResult(null, l, null)));
- processAllMessages();
-
- ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
- verify(mTestHandler, times(1)).sendMessageDelayed(messageCaptor.capture(), anyLong());
- }
-
- @Test
- @SmallTest
- public void testPhysicalLinkStateChanged_defaultApnTypeAndStateChanged_registrantNotifyResult()
- throws Exception {
- testPhysicalLinkStateChanged_imsApnTypeAndDormant_NoNotifyResult();
-
- ArrayList<DataCallResponse> l = new ArrayList<>();
- DataCallResponse dcResponse = new DataCallResponse.Builder()
- .setCause(0)
- .setRetryDurationMillis(-1)
- .setId(1)
- .setLinkStatus(DATA_CONNECTION_ACTIVE_PH_LINK_ACTIVE)
- .setProtocolType(ApnSetting.PROTOCOL_IP)
- .setInterfaceName(FAKE_IFNAME)
- .setAddresses(Arrays.asList(
- new LinkAddress(InetAddresses.parseNumericAddress(FAKE_ADDRESS), 0)))
- .setDnsAddresses(Arrays.asList(InetAddresses.parseNumericAddress(FAKE_DNS)))
- .setGatewayAddresses(Arrays.asList(InetAddresses.parseNumericAddress(FAKE_GATEWAY)))
- .setPcscfAddresses(
- Arrays.asList(InetAddresses.parseNumericAddress(FAKE_PCSCF_ADDRESS)))
- .setMtuV4(1440)
- .setMtuV6(1440)
- .build();
- l.add(dcResponse);
- mDc.mCid = 1;
- mDcc.addActiveDcByCid(mDc);
- ApnContext apnContext = new ApnContext(mPhone, ApnSetting.TYPE_DEFAULT, TAG, mDcTracker, 1);
- List<ApnContext> apnContextList = new ArrayList<>();
- apnContextList.add(apnContext);
- doReturn(apnContextList).when(mDc).getApnContexts();
- doReturn(true).when(mDcTracker).getLteEndcUsingUserDataForIdleDetection();
-
- mDcc.sendMessage(mDcc.obtainMessage(EVENT_DATA_STATE_CHANGED,
- new AsyncResult(null, l, null)));
- processAllMessages();
-
- ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
- verify(mTestHandler, times(2)).sendMessageDelayed(messageCaptor.capture(), anyLong());
- Message message = messageCaptor.getValue();
- assertEquals(EVENT_PHYSICAL_LINK_STATE_CHANGED, message.what);
- AsyncResult ar = (AsyncResult) message.obj;
- assertEquals(DcController.PHYSICAL_LINK_ACTIVE, (int) ar.result);
- }
} \ No newline at end of file
diff --git a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DcTrackerTest.java b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DcTrackerTest.java
index 89a59b412f..3bcf99f85a 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DcTrackerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/DcTrackerTest.java
@@ -22,20 +22,18 @@ import static com.android.internal.telephony.dataconnection.ApnSettingTest.creat
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -58,22 +56,17 @@ import android.net.NetworkPolicyManager;
import android.net.NetworkRequest;
import android.net.Uri;
import android.os.AsyncResult;
-import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.os.PersistableBundle;
-import android.os.SystemClock;
import android.provider.Settings;
import android.provider.Telephony;
import android.telephony.AccessNetworkConstants;
import android.telephony.AccessNetworkConstants.AccessNetworkType;
-import android.telephony.Annotation;
import android.telephony.CarrierConfigManager;
-import android.telephony.DataFailCause;
import android.telephony.NetworkRegistrationInfo;
-import android.telephony.PreciseDataConnectionState;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
import android.telephony.SubscriptionInfo;
@@ -82,17 +75,14 @@ import android.telephony.SubscriptionPlan;
import android.telephony.TelephonyDisplayInfo;
import android.telephony.TelephonyManager;
import android.telephony.data.ApnSetting;
-import android.telephony.data.DataCallResponse;
import android.telephony.data.DataProfile;
import android.telephony.data.DataService;
-import android.telephony.data.TrafficDescriptor;
import android.test.mock.MockContentProvider;
import android.test.mock.MockContentResolver;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.text.TextUtils;
import android.util.Pair;
-import android.util.SparseArray;
import androidx.test.filters.FlakyTest;
@@ -100,9 +90,7 @@ import com.android.internal.R;
import com.android.internal.telephony.DctConstants;
import com.android.internal.telephony.ISub;
import com.android.internal.telephony.PhoneConstants;
-import com.android.internal.telephony.RetryManager;
import com.android.internal.telephony.TelephonyTest;
-import com.android.internal.telephony.dataconnection.DataConnectionReasons.DataDisallowedReasonType;
import org.junit.After;
import org.junit.Before;
@@ -110,7 +98,6 @@ import org.junit.Ignore;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
-import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
@@ -122,12 +109,9 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
-import java.util.Map;
import java.util.Objects;
import java.util.Optional;
-import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
-import java.util.stream.Collectors;
public class DcTrackerTest extends TelephonyTest {
public static final String FAKE_APN1 = "FAKE APN 1";
@@ -136,16 +120,11 @@ public class DcTrackerTest extends TelephonyTest {
public static final String FAKE_APN4 = "FAKE APN 4";
public static final String FAKE_APN5 = "FAKE APN 5";
public static final String FAKE_APN6 = "FAKE APN 6";
- public static final String FAKE_APN7 = "FAKE APN 7";
- public static final String FAKE_APN8 = "FAKE APN 8";
- public static final String FAKE_APN9 = "FAKE APN 9";
public static final String FAKE_IFNAME = "FAKE IFNAME";
public static final String FAKE_PCSCF_ADDRESS = "22.33.44.55";
public static final String FAKE_GATEWAY = "11.22.33.44";
public static final String FAKE_DNS = "55.66.77.88";
public static final String FAKE_ADDRESS = "99.88.77.66";
- private static final int NETWORK_TYPE_NR_BITMASK =
- 1 << (TelephonyManager.NETWORK_TYPE_NR - 1);
private static final int NETWORK_TYPE_LTE_BITMASK =
1 << (TelephonyManager.NETWORK_TYPE_LTE - 1);
private static final int NETWORK_TYPE_EHRPD_BITMASK =
@@ -216,379 +195,8 @@ public class DcTrackerTest extends TelephonyTest {
}
private class ApnSettingContentProvider extends MockContentProvider {
- public final String[] FAKE_APN_COLUMNS = new String[]{
- Telephony.Carriers._ID, Telephony.Carriers.NUMERIC,
- Telephony.Carriers.NAME, Telephony.Carriers.APN,
- Telephony.Carriers.PROXY, Telephony.Carriers.PORT,
- Telephony.Carriers.MMSC, Telephony.Carriers.MMSPROXY,
- Telephony.Carriers.MMSPORT, Telephony.Carriers.USER,
- Telephony.Carriers.PASSWORD, Telephony.Carriers.AUTH_TYPE,
- Telephony.Carriers.TYPE,
- Telephony.Carriers.PROTOCOL,
- Telephony.Carriers.ROAMING_PROTOCOL,
- Telephony.Carriers.CARRIER_ENABLED, Telephony.Carriers.BEARER,
- Telephony.Carriers.BEARER_BITMASK,
- Telephony.Carriers.PROFILE_ID,
- Telephony.Carriers.MODEM_PERSIST,
- Telephony.Carriers.MAX_CONNECTIONS,
- Telephony.Carriers.WAIT_TIME_RETRY,
- Telephony.Carriers.TIME_LIMIT_FOR_MAX_CONNECTIONS,
- Telephony.Carriers.MTU,
- Telephony.Carriers.MVNO_TYPE,
- Telephony.Carriers.MVNO_MATCH_DATA,
- Telephony.Carriers.NETWORK_TYPE_BITMASK,
- Telephony.Carriers.APN_SET_ID,
- Telephony.Carriers.CARRIER_ID,
- Telephony.Carriers.SKIP_464XLAT
- };
-
private int mPreferredApnSet = 0;
- private Object[] mPreferredApn = null;
-
- private String mFakeApn1Types = "default,supl";
-
- private String mFakeApn5Types = "dun";
-
- private int mFakeApn1Bitmask = NETWORK_TYPE_LTE_BITMASK;
-
- private int mRowIdOffset = 0;
-
- public void setFakeApn1Types(String apnTypes) {
- mFakeApn1Types = apnTypes;
- }
-
- public void setFakeApn5Types(String apnTypes) {
- mFakeApn5Types = apnTypes;
- }
-
- public void setFakeApn1NetworkTypeBitmask(int bitmask) {
- mFakeApn1Bitmask = bitmask;
- }
-
- public void setRowIdOffset(int rowIdOffset) {
- mRowIdOffset = rowIdOffset;
- }
-
- public void setFakePreferredApn(Object[] fakeApn) {
- mPreferredApn = fakeApn;
- }
-
- public Object[] getFakeApn1() {
- return new Object[]{
- 2163 + mRowIdOffset, // id
- FAKE_PLMN, // numeric
- "sp-mode", // name
- FAKE_APN1, // apn
- "", // proxy
- "", // port
- "", // mmsc
- "", // mmsproxy
- "", // mmsport
- "", // user
- "", // password
- -1, // authtype
- mFakeApn1Types, // types
- "IP", // protocol
- "IP", // roaming_protocol
- 1, // carrier_enabled
- ServiceState.RIL_RADIO_TECHNOLOGY_LTE, // bearer
- 0, // bearer_bitmask
- 0, // profile_id
- 1, // modem_cognitive
- 0, // max_conns
- 0, // wait_time
- 0, // max_conns_time
- 0, // mtu
- "", // mvno_type
- "", // mnvo_match_data
- mFakeApn1Bitmask, // network_type_bitmask
- 0, // apn_set_id
- -1, // carrier_id
- -1 // skip_464xlat
- };
- }
-
- public Object[] getFakeApn2() {
- return new Object[]{
- 2164 + mRowIdOffset, // id
- FAKE_PLMN, // numeric
- "mopera U", // name
- FAKE_APN2, // apn
- "", // proxy
- "", // port
- "", // mmsc
- "", // mmsproxy
- "", // mmsport
- "", // user
- "", // password
- -1, // authtype
- "default,supl", // types
- "IP", // protocol
- "IP", // roaming_protocol
- 1, // carrier_enabled
- ServiceState.RIL_RADIO_TECHNOLOGY_LTE, // bearer,
- 0, // bearer_bitmask
- 0, // profile_id
- 1, // modem_cognitive
- 0, // max_conns
- 0, // wait_time
- 0, // max_conns_time
- 0, // mtu
- "", // mvno_type
- "", // mnvo_match_data
- NETWORK_TYPE_LTE_BITMASK, // network_type_bitmask
- 0, // apn_set_id
- -1, // carrier_id
- -1 // skip_464xlat
- };
- }
-
- public Object[] getFakeApn3() {
- return new Object[]{
- 2165 + mRowIdOffset, // id
- FAKE_PLMN, // numeric
- "b-mobile for Nexus", // name
- FAKE_APN3, // apn
- "", // proxy
- "", // port
- "", // mmsc
- "", // mmsproxy
- "", // mmsport
- "", // user
- "", // password
- -1, // authtype
- "ims", // types
- "IP", // protocol
- "IP", // roaming_protocol
- 1, // carrier_enabled
- 0, // bearer
- 0, // bearer_bitmask
- 0, // profile_id
- 1, // modem_cognitive
- 0, // max_conns
- 0, // wait_time
- 0, // max_conns_time
- 0, // mtu
- "", // mvno_type
- "", // mnvo_match_data
- 0, // network_type_bitmask
- 0, // apn_set_id
- -1, // carrier_id
- -1 // skip_464xlat
- };
- }
-
- public Object[] getFakeApn4() {
- return new Object[]{
- 2166 + mRowIdOffset, // id
- FAKE_PLMN, // numeric
- "sp-mode ehrpd", // name
- FAKE_APN4, // apn
- "", // proxy
- "", // port
- "", // mmsc
- "", // mmsproxy
- "", // mmsport
- "", // user
- "", // password
- -1, // authtype
- "default,supl", // types
- "IP", // protocol
- "IP", // roaming_protocol
- 1, // carrier_enabled
- ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD, // bearer
- 0, // bearer_bitmask
- 0, // profile_id
- 1, // modem_cognitive
- 0, // max_conns
- 0, // wait_time
- 0, // max_conns_time
- 0, // mtu
- "", // mvno_type
- "", // mnvo_match_data
- NETWORK_TYPE_EHRPD_BITMASK, // network_type_bitmask
- 0, // apn_set_id
- -1, // carrier_id
- -1 // skip_464xlat
- };
- }
-
- public Object[] getFakeApn5() {
- return new Object[]{
- 2167 + mRowIdOffset, // id
- FAKE_PLMN, // numeric
- "b-mobile for Nexus", // name
- FAKE_APN5, // apn
- "", // proxy
- "", // port
- "", // mmsc
- "", // mmsproxy
- "", // mmsport
- "", // user
- "", // password
- -1, // authtype
- mFakeApn5Types, // types
- "IP", // protocol
- "IP", // roaming_protocol
- 1, // carrier_enabled
- 0, // bearer
- 0, // bearer_bitmask
- 0, // profile_id
- 1, // modem_cognitive
- 0, // max_conns
- 0, // wait_time
- 0, // max_conns_time
- 0, // mtu
- "", // mvno_type
- "", // mnvo_match_data
- 0, // network_type_bitmask
- 0, // apn_set_id
- -1, // carrier_id
- -1 // skip_464xlat
- };
- }
-
- public Object[] getFakeApn6() {
- return new Object[]{
- 2168 + mRowIdOffset, // id
- FAKE_PLMN, // numeric
- "sp-mode", // name
- FAKE_APN6, // apn
- "", // proxy
- "", // port
- "", // mmsc
- "", // mmsproxy
- "", // mmsport
- "", // user
- "", // password
- -1, // authtype
- "mms,xcap", // types
- "IP", // protocol
- "IP", // roaming_protocol
- 1, // carrier_enabled
- ServiceState.RIL_RADIO_TECHNOLOGY_LTE, // bearer
- 0, // bearer_bitmask
- 0, // profile_id
- 1, // modem_cognitive
- 0, // max_conns
- 0, // wait_time
- 0, // max_conns_time
- 0, // mtu
- "", // mvno_type
- "", // mnvo_match_data
- NETWORK_TYPE_LTE_BITMASK, // network_type_bitmask
- 0, // apn_set_id
- -1, // carrier_id
- -1 // skip_464xlat
- };
- }
-
- public Object[] getFakeApn7() {
- return new Object[]{
- 2169 + mRowIdOffset, // id
- FAKE_PLMN, // numeric
- "sp-mode", // name
- FAKE_APN7, // apn
- "", // proxy
- "", // port
- "", // mmsc
- "", // mmsproxy
- "", // mmsport
- "", // user
- "", // password
- -1, // authtype
- "default", // types
- "IP", // protocol
- "IP", // roaming_protocol
- 1, // carrier_enabled
- ServiceState.RIL_RADIO_TECHNOLOGY_LTE, // bearer
- 0, // bearer_bitmask
- 0, // profile_id
- 1, // modem_cognitive
- 0, // max_conns
- 0, // wait_time
- 0, // max_conns_time
- 0, // mtu
- "", // mvno_type
- "", // mnvo_match_data
- NETWORK_TYPE_LTE_BITMASK, // network_type_bitmask
- 1, // apn_set_id
- -1, // carrier_id
- -1 // skip_464xlat
- };
- }
-
- public Object[] getFakeApn8() {
- return new Object[]{
- 2170 + mRowIdOffset, // id
- FAKE_PLMN, // numeric
- "IMS", // name
- FAKE_APN8, // apn
- "", // proxy
- "", // port
- "", // mmsc
- "", // mmsproxy
- "", // mmsport
- "", // user
- "", // password
- -1, // authtype
- "ims", // types
- "IP", // protocol
- "IP", // roaming_protocol
- 1, // carrier_enabled
- ServiceState.RIL_RADIO_TECHNOLOGY_LTE, // bearer
- 0, // bearer_bitmask
- 0, // profile_id
- 1, // modem_cognitive
- 0, // max_conns
- 0, // wait_time
- 0, // max_conns_time
- 0, // mtu
- "", // mvno_type
- "", // mnvo_match_data
- NETWORK_TYPE_LTE_BITMASK, // network_type_bitmask
- -1, // apn_set_id
- -1, // carrier_id
- -1 // skip_464xlat
- };
- }
-
- public Object[] getFakeApn9() {
- return new Object[]{
- 2171 + mRowIdOffset, // id
- FAKE_PLMN, // numeric
- "sp-mode nr", // name
- FAKE_APN9, // apn
- "", // proxy
- "", // port
- "", // mmsc
- "", // mmsproxy
- "", // mmsport
- "", // user
- "", // password
- -1, // authtype
- "default,enterprise", // types
- "IP", // protocol
- "IP", // roaming_protocol
- 1, // carrier_enabled
- ServiceState.RIL_RADIO_TECHNOLOGY_LTE, // bearer
- 0, // bearer_bitmask
- 0, // profile_id
- 1, // modem_cognitive
- 0, // max_conns
- 0, // wait_time
- 0, // max_conns_time
- 0, // mtu
- "", // mvno_type
- "", // mnvo_match_data
- NETWORK_TYPE_NR_BITMASK, // network_type_bitmask
- 0, // apn_set_id
- -1, // carrier_id
- -1 // skip_464xlat
- };
- }
-
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
@@ -607,16 +215,228 @@ public class DcTrackerTest extends TelephonyTest {
if (projection == null) {
logd("Query '" + FAKE_PLMN + "' APN settings");
- MatrixCursor mc = new MatrixCursor(FAKE_APN_COLUMNS);
- mc.addRow(getFakeApn1());
- mc.addRow(getFakeApn2());
- mc.addRow(getFakeApn3());
- mc.addRow(getFakeApn4());
- mc.addRow(getFakeApn5());
- mc.addRow(getFakeApn6());
- mc.addRow(getFakeApn7());
- mc.addRow(getFakeApn8());
- mc.addRow(getFakeApn9());
+ MatrixCursor mc = new MatrixCursor(
+ new String[]{Telephony.Carriers._ID, Telephony.Carriers.NUMERIC,
+ Telephony.Carriers.NAME, Telephony.Carriers.APN,
+ Telephony.Carriers.PROXY, Telephony.Carriers.PORT,
+ Telephony.Carriers.MMSC, Telephony.Carriers.MMSPROXY,
+ Telephony.Carriers.MMSPORT, Telephony.Carriers.USER,
+ Telephony.Carriers.PASSWORD, Telephony.Carriers.AUTH_TYPE,
+ Telephony.Carriers.TYPE,
+ Telephony.Carriers.PROTOCOL,
+ Telephony.Carriers.ROAMING_PROTOCOL,
+ Telephony.Carriers.CARRIER_ENABLED, Telephony.Carriers.BEARER,
+ Telephony.Carriers.BEARER_BITMASK,
+ Telephony.Carriers.PROFILE_ID,
+ Telephony.Carriers.MODEM_PERSIST,
+ Telephony.Carriers.MAX_CONNECTIONS,
+ Telephony.Carriers.WAIT_TIME_RETRY,
+ Telephony.Carriers.TIME_LIMIT_FOR_MAX_CONNECTIONS,
+ Telephony.Carriers.MTU,
+ Telephony.Carriers.MVNO_TYPE,
+ Telephony.Carriers.MVNO_MATCH_DATA,
+ Telephony.Carriers.NETWORK_TYPE_BITMASK,
+ Telephony.Carriers.APN_SET_ID,
+ Telephony.Carriers.CARRIER_ID,
+ Telephony.Carriers.SKIP_464XLAT});
+
+ mc.addRow(new Object[]{
+ 2163, // id
+ FAKE_PLMN, // numeric
+ "sp-mode", // name
+ FAKE_APN1, // apn
+ "", // proxy
+ "", // port
+ "", // mmsc
+ "", // mmsproxy
+ "", // mmsport
+ "", // user
+ "", // password
+ -1, // authtype
+ "default,supl", // types
+ "IP", // protocol
+ "IP", // roaming_protocol
+ 1, // carrier_enabled
+ ServiceState.RIL_RADIO_TECHNOLOGY_LTE, // bearer
+ 0, // bearer_bitmask
+ 0, // profile_id
+ 1, // modem_cognitive
+ 0, // max_conns
+ 0, // wait_time
+ 0, // max_conns_time
+ 0, // mtu
+ "", // mvno_type
+ "", // mnvo_match_data
+ NETWORK_TYPE_LTE_BITMASK, // network_type_bitmask
+ 0, // apn_set_id
+ -1, // carrier_id
+ -1 // skip_464xlat
+ });
+
+ mc.addRow(new Object[]{
+ 2164, // id
+ FAKE_PLMN, // numeric
+ "mopera U", // name
+ FAKE_APN2, // apn
+ "", // proxy
+ "", // port
+ "", // mmsc
+ "", // mmsproxy
+ "", // mmsport
+ "", // user
+ "", // password
+ -1, // authtype
+ "default,supl", // types
+ "IP", // protocol
+ "IP", // roaming_protocol
+ 1, // carrier_enabled
+ ServiceState.RIL_RADIO_TECHNOLOGY_LTE, // bearer,
+ 0, // bearer_bitmask
+ 0, // profile_id
+ 1, // modem_cognitive
+ 0, // max_conns
+ 0, // wait_time
+ 0, // max_conns_time
+ 0, // mtu
+ "", // mvno_type
+ "", // mnvo_match_data
+ NETWORK_TYPE_LTE_BITMASK, // network_type_bitmask
+ 0, // apn_set_id
+ -1, // carrier_id
+ -1 // skip_464xlat
+ });
+
+ mc.addRow(new Object[]{
+ 2165, // id
+ FAKE_PLMN, // numeric
+ "b-mobile for Nexus", // name
+ FAKE_APN3, // apn
+ "", // proxy
+ "", // port
+ "", // mmsc
+ "", // mmsproxy
+ "", // mmsport
+ "", // user
+ "", // password
+ -1, // authtype
+ "ims", // types
+ "IP", // protocol
+ "IP", // roaming_protocol
+ 1, // carrier_enabled
+ 0, // bearer
+ 0, // bearer_bitmask
+ 0, // profile_id
+ 1, // modem_cognitive
+ 0, // max_conns
+ 0, // wait_time
+ 0, // max_conns_time
+ 0, // mtu
+ "", // mvno_type
+ "", // mnvo_match_data
+ 0, // network_type_bitmask
+ 0, // apn_set_id
+ -1, // carrier_id
+ -1 // skip_464xlat
+ });
+
+ mc.addRow(new Object[]{
+ 2166, // id
+ FAKE_PLMN, // numeric
+ "sp-mode ehrpd", // name
+ FAKE_APN4, // apn
+ "", // proxy
+ "", // port
+ "", // mmsc
+ "", // mmsproxy
+ "", // mmsport
+ "", // user
+ "", // password
+ -1, // authtype
+ "default,supl", // types
+ "IP", // protocol
+ "IP", // roaming_protocol
+ 1, // carrier_enabled
+ ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD, // bearer
+ 0, // bearer_bitmask
+ 0, // profile_id
+ 1, // modem_cognitive
+ 0, // max_conns
+ 0, // wait_time
+ 0, // max_conns_time
+ 0, // mtu
+ "", // mvno_type
+ "", // mnvo_match_data
+ NETWORK_TYPE_EHRPD_BITMASK, // network_type_bitmask
+ 0, // apn_set_id
+ -1, // carrier_id
+ -1 // skip_464xlat
+ });
+
+ mc.addRow(new Object[]{
+ 2167, // id
+ FAKE_PLMN, // numeric
+ "b-mobile for Nexus", // name
+ FAKE_APN5, // apn
+ "", // proxy
+ "", // port
+ "", // mmsc
+ "", // mmsproxy
+ "", // mmsport
+ "", // user
+ "", // password
+ -1, // authtype
+ "dun", // types
+ "IP", // protocol
+ "IP", // roaming_protocol
+ 1, // carrier_enabled
+ 0, // bearer
+ 0, // bearer_bitmask
+ 0, // profile_id
+ 1, // modem_cognitive
+ 0, // max_conns
+ 0, // wait_time
+ 0, // max_conns_time
+ 0, // mtu
+ "", // mvno_type
+ "", // mnvo_match_data
+ 0, // network_type_bitmask
+ 0, // apn_set_id
+ -1, // carrier_id
+ -1 // skip_464xlat
+ });
+
+ mc.addRow(new Object[]{
+ 2168, // id
+ FAKE_PLMN, // numeric
+ "sp-mode", // name
+ FAKE_APN6, // apn
+ "", // proxy
+ "", // port
+ "", // mmsc
+ "", // mmsproxy
+ "", // mmsport
+ "", // user
+ "", // password
+ -1, // authtype
+ "mms,xcap", // types
+ "IP", // protocol
+ "IP", // roaming_protocol
+ 1, // carrier_enabled
+ ServiceState.RIL_RADIO_TECHNOLOGY_LTE, // bearer
+ 0, // bearer_bitmask
+ 0, // profile_id
+ 1, // modem_cognitive
+ 0, // max_conns
+ 0, // wait_time
+ 0, // max_conns_time
+ 0, // mtu
+ "", // mvno_type
+ "", // mnvo_match_data
+ NETWORK_TYPE_LTE_BITMASK, // network_type_bitmask
+ 0, // apn_set_id
+ -1, // carrier_id
+ -1 // skip_464xlat
+ });
return mc;
}
@@ -628,15 +448,6 @@ public class DcTrackerTest extends TelephonyTest {
mc.addRow(new Object[]{ mPreferredApnSet });
mc.addRow(new Object[]{ 0 });
return mc;
- } else if (isPathPrefixMatch(uri,
- Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "preferapn_no_update"))) {
- if (mPreferredApn == null) {
- return null;
- } else {
- MatrixCursor mc = new MatrixCursor(FAKE_APN_COLUMNS);
- mc.addRow(mPreferredApn);
- return mc;
- }
}
return null;
@@ -647,16 +458,6 @@ public class DcTrackerTest extends TelephonyTest {
mPreferredApnSet = values.getAsInteger(Telephony.Carriers.APN_SET_ID);
return 1;
}
-
- @Override
- public int delete(Uri uri, String selection, String[] selectionArgs) {
- return 0;
- }
-
- @Override
- public Uri insert(Uri uri, ContentValues values) {
- return null;
- }
}
@Before
@@ -690,8 +491,6 @@ public class DcTrackerTest extends TelephonyTest {
Settings.Global.putInt(mContext.getContentResolver(),
Settings.Global.DATA_STALL_RECOVERY_ON_BAD_NETWORK, 0);
- doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WWAN).when(mTransportManager)
- .getPreferredTransport(anyInt());
doReturn(PhoneConstants.State.IDLE).when(mCT).getState();
doReturn(true).when(mSST).getDesiredPowerState();
doReturn(true).when(mSST).getPowerStateFromCarrier();
@@ -752,7 +551,7 @@ public class DcTrackerTest extends TelephonyTest {
}
// Create a successful data response
- private static SetupDataCallResult createSetupDataCallResult() {
+ private static SetupDataCallResult createSetupDataCallResult() throws Exception {
SetupDataCallResult result = new SetupDataCallResult();
result.status = 0;
result.suggestedRetryTime = -1;
@@ -788,16 +587,19 @@ public class DcTrackerTest extends TelephonyTest {
}
private void verifyDataConnected(final String apnSetting) {
+ verify(mPhone, atLeastOnce()).notifyDataConnection(
+ eq(PhoneConstants.APN_TYPE_DEFAULT));
+
verify(mAlarmManager, times(1)).set(eq(AlarmManager.ELAPSED_REALTIME), anyLong(),
any(PendingIntent.class));
- assertEquals(apnSetting, mDct.getActiveApnString(ApnSetting.TYPE_DEFAULT_STRING));
- assertArrayEquals(new String[]{ApnSetting.TYPE_DEFAULT_STRING}, mDct.getActiveApnTypes());
+ assertEquals(apnSetting, mDct.getActiveApnString(PhoneConstants.APN_TYPE_DEFAULT));
+ assertArrayEquals(new String[]{PhoneConstants.APN_TYPE_DEFAULT}, mDct.getActiveApnTypes());
- assertTrue(mDct.isAnyDataConnected());
- assertEquals(DctConstants.State.CONNECTED, mDct.getState(ApnSetting.TYPE_DEFAULT_STRING));
+ assertEquals(DctConstants.State.CONNECTED, mDct.getOverallState());
+ assertEquals(DctConstants.State.CONNECTED, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
- LinkProperties linkProperties = mDct.getLinkProperties(ApnSetting.TYPE_DEFAULT_STRING);
+ LinkProperties linkProperties = mDct.getLinkProperties(PhoneConstants.APN_TYPE_DEFAULT);
assertEquals(FAKE_IFNAME, linkProperties.getInterfaceName());
assertEquals(1, linkProperties.getAddresses().size());
assertEquals(FAKE_ADDRESS, linkProperties.getAddresses().get(0).getHostAddress());
@@ -806,68 +608,44 @@ public class DcTrackerTest extends TelephonyTest {
assertEquals(FAKE_GATEWAY, linkProperties.getRoutes().get(0).getGateway().getHostAddress());
}
- private boolean isHandoverPending(int apnType) {
+ private boolean isDataAllowed(DataConnectionReasons dataConnectionReasons) {
try {
- Method method = DcTracker.class.getDeclaredMethod("isHandoverPending",
- int.class);
+ Method method = DcTracker.class.getDeclaredMethod("isDataAllowed",
+ DataConnectionReasons.class);
method.setAccessible(true);
- return (boolean) method.invoke(mDct, apnType);
+ return (boolean) method.invoke(mDct, dataConnectionReasons);
} catch (Exception e) {
fail(e.toString());
return false;
}
}
- private void addHandoverCompleteMsg(Message onCompleteMsg,
- @Annotation.ApnType int apnType) {
- try {
- Method method = DcTracker.class.getDeclaredMethod("addHandoverCompleteMsg",
- Message.class, int.class);
- method.setAccessible(true);
- method.invoke(mDct, onCompleteMsg, apnType);
- } catch (Exception e) {
- fail(e.toString());
- }
- }
-
private void sendInitializationEvents() {
- sendCarrierConfigChanged("");
-
- sendSimStateUpdated("");
-
- sendEventDataConnectionAttached("");
-
- waitForMs(200);
- }
-
- private void sendCarrierConfigChanged(String messagePrefix) {
- logd(messagePrefix + "Sending EVENT_CARRIER_CONFIG_CHANGED");
+ logd("Sending EVENT_CARRIER_CONFIG_CHANGED");
mDct.sendEmptyMessage(DctConstants.EVENT_CARRIER_CONFIG_CHANGED);
waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
- }
- private void sendSimStateUpdated(String messagePrefix) {
- logd(messagePrefix + "Sending EVENT_SIM_STATE_UPDATED");
+ logd("Sending EVENT_SIM_STATE_UPDATED");
mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_SIM_STATE_UPDATED,
TelephonyManager.SIM_STATE_LOADED, 0));
waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
- }
- private void sendEventDataConnectionAttached(String messagePrefix) {
- logd(messagePrefix + "Sending EVENT_DATA_CONNECTION_ATTACHED");
+ logd("Sending EVENT_DATA_CONNECTION_ATTACHED");
mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null));
waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
+
+ waitForMs(200);
}
// Test the unmetered APN setup when data is disabled.
@Test
@SmallTest
public void testTrySetupDataUnmeteredDefaultNotSelected() throws Exception {
- initApns(ApnSetting.TYPE_XCAP_STRING, new String[]{ApnSetting.TYPE_XCAP_STRING});
+ initApns(PhoneConstants.APN_TYPE_XCAP, new String[]{PhoneConstants.APN_TYPE_XCAP});
doReturn(SubscriptionManager.INVALID_SUBSCRIPTION_ID).when(mIsub).getDefaultDataSubId();
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT});
sendInitializationEvents();
@@ -879,15 +657,17 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
eq(AccessNetworkType.EUTRAN), any(DataProfile.class),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
}
// Test the normal data call setup scenario.
@Test
@MediumTest
public void testDataSetup() throws Exception {
+ mSimulatedCommands.setDataCallResult(true, createSetupDataCallResult());
+
DataConnectionReasons dataConnectionReasons = new DataConnectionReasons();
- boolean allowed = mDct.isDataAllowed(dataConnectionReasons);
+ boolean allowed = isDataAllowed(dataConnectionReasons);
assertFalse(dataConnectionReasons.toString(), allowed);
logd("Sending EVENT_ENABLE_APN");
@@ -898,7 +678,7 @@ public class DcTrackerTest extends TelephonyTest {
sendInitializationEvents();
dataConnectionReasons = new DataConnectionReasons();
- allowed = mDct.isDataAllowed(dataConnectionReasons);
+ allowed = isDataAllowed(dataConnectionReasons);
assertTrue(dataConnectionReasons.toString(), allowed);
ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
@@ -906,7 +686,7 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
verifyDataConnected(FAKE_APN1);
@@ -929,7 +709,7 @@ public class DcTrackerTest extends TelephonyTest {
mSimulatedCommands.setDataCallResult(true, result);
DataConnectionReasons dataConnectionReasons = new DataConnectionReasons();
- boolean allowed = mDct.isDataAllowed(dataConnectionReasons);
+ boolean allowed = isDataAllowed(dataConnectionReasons);
assertFalse(dataConnectionReasons.toString(), allowed);
logd("Sending EVENT_ENABLE_APN");
@@ -940,7 +720,7 @@ public class DcTrackerTest extends TelephonyTest {
sendInitializationEvents();
dataConnectionReasons = new DataConnectionReasons();
- allowed = mDct.isDataAllowed(dataConnectionReasons);
+ allowed = isDataAllowed(dataConnectionReasons);
assertTrue(dataConnectionReasons.toString(), allowed);
ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
@@ -948,16 +728,17 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
// This time we'll let RIL command succeed.
mSimulatedCommands.setDataCallResult(true, createSetupDataCallResult());
//Send event for reconnecting data
- initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
+ initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_RECONNECT,
- mPhone.getPhoneId(), DcTracker.REQUEST_TYPE_NORMAL, mApnContext));
+ mPhone.getPhoneId(), AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
+ mApnContext));
waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
// Data connection is running on a different thread. Have to wait.
@@ -967,7 +748,7 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
verifyDataProfile(dpCaptor.getValue(), FAKE_APN2, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
// Verify connected with APN2 setting.
@@ -978,11 +759,11 @@ public class DcTrackerTest extends TelephonyTest {
@MediumTest
@Ignore
@FlakyTest
- public void testUserDisableData() {
+ public void testUserDisableData() throws Exception {
//step 1: setup two DataCalls one for Metered: default, another one for Non-metered: IMS
//set Default and MMS to be metered in the CarrierConfigManager
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
@@ -992,7 +773,7 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 5, 1, NETWORK_TYPE_LTE_BITMASK);
logd("Sending DATA_DISABLED_CMD");
@@ -1009,16 +790,16 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, times(1)).deactivateDataCall(
eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
any(Message.class));
- assertTrue(mDct.isAnyDataConnected());
- assertEquals(DctConstants.State.IDLE, mDct.getState(ApnSetting.TYPE_DEFAULT_STRING));
- assertEquals(DctConstants.State.CONNECTED, mDct.getState(ApnSetting.TYPE_IMS_STRING));
+ assertEquals(DctConstants.State.CONNECTED, mDct.getOverallState());
+ assertEquals(DctConstants.State.IDLE, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
+ assertEquals(DctConstants.State.CONNECTED, mDct.getState(PhoneConstants.APN_TYPE_IMS));
}
@Test
@MediumTest
- public void testTrySetupDataMmsAllowedDataDisabled() {
+ public void testTrySetupDataMmsAllowedDataDisabled() throws Exception {
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
mDct.enableApn(ApnSetting.TYPE_MMS, DcTracker.REQUEST_TYPE_NORMAL, null);
mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
@@ -1028,7 +809,8 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
+
List<DataProfile> dataProfiles = dpCaptor.getAllValues();
assertEquals(2, dataProfiles.size());
@@ -1058,9 +840,10 @@ public class DcTrackerTest extends TelephonyTest {
waitForMs(200);
// expected tear down all metered DataConnections
verify(mSimulatedCommandsVerifier, times(2)).deactivateDataCall(
- anyInt(), eq(DataService.REQUEST_REASON_NORMAL), any(Message.class));
- assertEquals(DctConstants.State.IDLE, mDct.getState(ApnSetting.TYPE_DEFAULT_STRING));
- assertEquals(DctConstants.State.IDLE, mDct.getState(ApnSetting.TYPE_MMS_STRING));
+ eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
+ any(Message.class));
+ assertEquals(DctConstants.State.IDLE, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
+ assertEquals(DctConstants.State.IDLE, mDct.getState(PhoneConstants.APN_TYPE_MMS));
clearInvocations(mSimulatedCommandsVerifier);
doReturn(true).when(mDataEnabledSettings).isDataEnabled(ApnSetting.TYPE_MMS);
@@ -1072,85 +855,14 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
- assertEquals(DctConstants.State.IDLE, mDct.getState(ApnSetting.TYPE_DEFAULT_STRING));
- assertEquals(DctConstants.State.CONNECTED, mDct.getState(ApnSetting.TYPE_MMS_STRING));
- }
-
- @Test
- @MediumTest
- public void testTrySetupDataMmsAlwaysAllowedDataDisabled() {
- mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
- mApnSettingContentProvider.setFakeApn1Types("mms,xcap,default");
- mDct.enableApn(ApnSetting.TYPE_MMS, DcTracker.REQUEST_TYPE_NORMAL, null);
- sendInitializationEvents();
-
- // Verify MMS was set up and is connected
- ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
- verify(mSimulatedCommandsVerifier).setupDataCall(
- eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
- eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
- verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0,
- ApnSetting.TYPE_MMS | ApnSetting.TYPE_XCAP | ApnSetting.TYPE_DEFAULT,
- 1, NETWORK_TYPE_LTE_BITMASK);
- assertEquals(DctConstants.State.CONNECTED, mDct.getState(ApnSetting.TYPE_MMS_STRING));
-
- // Verify DC has all capabilities specified in fakeApn1Types
- Map<Integer, ApnContext> apnContexts = mDct.getApnContexts().stream().collect(
- Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
- assertTrue(apnContexts.get(ApnSetting.TYPE_MMS).getDataConnection()
- .getNetworkCapabilities().hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS));
- assertTrue(apnContexts.get(ApnSetting.TYPE_MMS).getDataConnection()
- .getNetworkCapabilities().hasCapability(NetworkCapabilities.NET_CAPABILITY_XCAP));
- assertTrue(apnContexts.get(ApnSetting.TYPE_MMS).getDataConnection()
- .getNetworkCapabilities().hasCapability(
- NetworkCapabilities.NET_CAPABILITY_INTERNET));
-
- // Disable mobile data
- doReturn(false).when(mDataEnabledSettings).isDataEnabled();
- doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
- doReturn(false).when(mDataEnabledSettings).isMmsAlwaysAllowed();
- mDct.obtainMessage(DctConstants.EVENT_DATA_ENABLED_OVERRIDE_RULES_CHANGED).sendToTarget();
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
-
- // Expected tear down all metered DataConnections
- waitForMs(200);
- verify(mSimulatedCommandsVerifier).deactivateDataCall(
- anyInt(), eq(DataService.REQUEST_REASON_NORMAL), any(Message.class));
- assertEquals(DctConstants.State.IDLE, mDct.getState(ApnSetting.TYPE_MMS_STRING));
-
- // Allow MMS unconditionally
- clearInvocations(mSimulatedCommandsVerifier);
- doReturn(true).when(mDataEnabledSettings).isMmsAlwaysAllowed();
- doReturn(true).when(mDataEnabledSettings).isDataEnabled(ApnSetting.TYPE_MMS);
- mDct.obtainMessage(DctConstants.EVENT_DATA_ENABLED_OVERRIDE_RULES_CHANGED).sendToTarget();
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
-
- // Verify MMS was set up and is connected
- waitForMs(200);
- verify(mSimulatedCommandsVerifier).setupDataCall(
- eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
- eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
- assertEquals(DctConstants.State.CONNECTED, mDct.getState(ApnSetting.TYPE_MMS_STRING));
-
- // Ensure MMS data connection has the MMS capability only.
- apnContexts = mDct.getApnContexts().stream().collect(
- Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
- assertTrue(apnContexts.get(ApnSetting.TYPE_MMS).getDataConnection()
- .getNetworkCapabilities().hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS));
- assertFalse(apnContexts.get(ApnSetting.TYPE_MMS).getDataConnection()
- .getNetworkCapabilities().hasCapability(NetworkCapabilities.NET_CAPABILITY_XCAP));
- assertFalse(apnContexts.get(ApnSetting.TYPE_MMS).getDataConnection()
- .getNetworkCapabilities().hasCapability(
- NetworkCapabilities.NET_CAPABILITY_INTERNET));
+ any(Message.class));
+ assertEquals(DctConstants.State.IDLE, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
+ assertEquals(DctConstants.State.CONNECTED, mDct.getState(PhoneConstants.APN_TYPE_MMS));
}
@Test
@MediumTest
- public void testUserDisableRoaming() {
+ public void testUserDisableRoaming() throws Exception {
//step 1: setup two DataCalls one for Metered: default, another one for Non-metered: IMS
//step 2: set roaming disabled, data is enabled
//step 3: under roaming service
@@ -1160,7 +872,7 @@ public class DcTrackerTest extends TelephonyTest {
boolean roamingEnabled = mDct.getDataRoamingEnabled();
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_ROAMING_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
waitForHandlerAction(mDct, 1000);
@@ -1173,7 +885,7 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
//user is in roaming
@@ -1189,9 +901,9 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, times(1)).deactivateDataCall(
eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
any(Message.class));
- assertTrue(mDct.isAnyDataConnected());
- assertEquals(DctConstants.State.IDLE, mDct.getState(ApnSetting.TYPE_DEFAULT_STRING));
- assertEquals(DctConstants.State.CONNECTED, mDct.getState(ApnSetting.TYPE_IMS_STRING));
+ assertEquals(DctConstants.State.CONNECTED, mDct.getOverallState());
+ assertEquals(DctConstants.State.IDLE, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
+ assertEquals(DctConstants.State.CONNECTED, mDct.getState(PhoneConstants.APN_TYPE_IMS));
// reset roaming settings / data enabled settings at end of this test
mDct.setDataRoamingEnabledByUser(roamingEnabled);
@@ -1200,7 +912,7 @@ public class DcTrackerTest extends TelephonyTest {
@Test
@MediumTest
- public void testDataCallOnUserDisableRoaming() {
+ public void testDataCallOnUserDisableRoaming() throws Exception {
//step 1: mock under roaming service and user disabled roaming from settings.
//step 2: user toggled data settings on
//step 3: only non-metered data call is established
@@ -1210,7 +922,7 @@ public class DcTrackerTest extends TelephonyTest {
//set Default and MMS to be metered in the CarrierConfigManager
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_ROAMING_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
@@ -1224,12 +936,12 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
verifyDataProfile(dpCaptor.getValue(), FAKE_APN3, 2, 64, 0, 0);
- assertTrue(mDct.isAnyDataConnected());
- assertEquals(DctConstants.State.IDLE, mDct.getState(ApnSetting.TYPE_DEFAULT_STRING));
- assertEquals(DctConstants.State.CONNECTED, mDct.getState(ApnSetting.TYPE_IMS_STRING));
+ assertEquals(DctConstants.State.CONNECTED, mDct.getOverallState());
+ assertEquals(DctConstants.State.IDLE, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
+ assertEquals(DctConstants.State.CONNECTED, mDct.getState(PhoneConstants.APN_TYPE_IMS));
// reset roaming settings / data enabled settings at end of this test
mDct.setDataRoamingEnabledByUser(roamingEnabled);
@@ -1256,13 +968,13 @@ public class DcTrackerTest extends TelephonyTest {
@Ignore
@Test
@MediumTest
- public void testCarrierActionSetMeteredApnsEnabled() {
+ public void testCarrierActionSetMeteredApnsEnabled() throws Exception {
//step 1: setup two DataCalls one for Internet and IMS
//step 2: set data is enabled
//step 3: cold sim is detected
//step 4: all data connection is torn down
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
@@ -1273,9 +985,9 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 5, 1, NETWORK_TYPE_LTE_BITMASK);
- assertTrue(mDct.isAnyDataConnected());
+ assertEquals(DctConstants.State.CONNECTED, mDct.getOverallState());
AsyncResult ar = new AsyncResult(null,
new Pair<>(false, DataEnabledSettings.REASON_DATA_ENABLED_BY_CARRIER), null);
@@ -1288,8 +1000,8 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, times(1)).deactivateDataCall(
eq(DataService.REQUEST_REASON_NORMAL), anyInt(),
any(Message.class));
- assertTrue(mDct.isAnyDataConnected());
- assertEquals(DctConstants.State.IDLE, mDct.getState(ApnSetting.TYPE_DEFAULT_STRING));
+ assertEquals(DctConstants.State.CONNECTED, mDct.getOverallState());
+ assertEquals(DctConstants.State.IDLE, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
}
private void initApns(String targetApn, String[] canHandleTypes) {
@@ -1311,9 +1023,9 @@ public class DcTrackerTest extends TelephonyTest {
// Test the emergency APN setup.
@Test
@SmallTest
- public void testTrySetupDataEmergencyApn() {
- initApns(ApnSetting.TYPE_EMERGENCY_STRING,
- new String[]{ApnSetting.TYPE_EMERGENCY_STRING});
+ public void testTrySetupDataEmergencyApn() throws Exception {
+ initApns(PhoneConstants.APN_TYPE_EMERGENCY,
+ new String[]{PhoneConstants.APN_TYPE_EMERGENCY});
mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TRY_SETUP_DATA, mApnContext));
waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
@@ -1321,191 +1033,30 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
eq(AccessNetworkType.EUTRAN), any(DataProfile.class), eq(false), eq(false),
- eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), any(),
- anyBoolean(), any(Message.class));
+ eq(DataService.REQUEST_REASON_NORMAL), any(), any(Message.class));
}
// Test the XCAP APN setup.
@Test
@SmallTest
- public void testTrySetupDataXcapApn() {
- initApns(ApnSetting.TYPE_XCAP_STRING, new String[]{ApnSetting.TYPE_XCAP_STRING});
+ public void testTrySetupDataXcapApn() throws Exception {
+ initApns(PhoneConstants.APN_TYPE_XCAP, new String[]{PhoneConstants.APN_TYPE_XCAP});
mDct.enableApn(ApnSetting.TYPE_XCAP, DcTracker.REQUEST_TYPE_NORMAL, null);
sendInitializationEvents();
verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
eq(AccessNetworkType.EUTRAN), any(DataProfile.class), eq(false), eq(false),
- eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), any(),
- anyBoolean(), any(Message.class));
- }
-
- // Test the ENTERPRISE APN setup.
- @Test
- public void testTrySetupDataEnterpriseApn() {
- mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
- sendInitializationEvents();
-
- ArgumentCaptor<TrafficDescriptor> tdCaptor =
- ArgumentCaptor.forClass(TrafficDescriptor.class);
- verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
- eq(AccessNetworkType.EUTRAN), any(DataProfile.class), eq(false), eq(false),
- eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), tdCaptor.capture(),
- anyBoolean(), any(Message.class));
- assertEquals(FAKE_APN1, tdCaptor.getValue().getDataNetworkName());
- assertEquals(null, tdCaptor.getValue().getOsAppId());
-
- mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
- .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_NR)
- .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
- .build();
- doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
- anyInt(), anyInt());
- SetupDataCallResult result = createSetupDataCallResult();
- result.cid = 10;
- mSimulatedCommands.setDataCallResult(true, result);
- mDct.enableApn(ApnSetting.TYPE_ENTERPRISE, DcTracker.REQUEST_TYPE_NORMAL, null);
- waitForMs(200);
-
- verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
- eq(AccessNetworkType.NGRAN), any(DataProfile.class), eq(false), eq(false),
- eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), tdCaptor.capture(),
- anyBoolean(), any(Message.class));
- assertEquals(null, tdCaptor.getValue().getDataNetworkName());
- assertTrue(Arrays.equals(DataConnection.getEnterpriseOsAppId(),
- tdCaptor.getValue().getOsAppId()));
- }
-
- // Test the ENTERPRISE APN setup when default data is not set up yet.
- @Test
- public void testTrySetupDataEnterpriseApnNoDefaultData() {
- mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
- .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_NR)
- .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
- .build();
- doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
- anyInt(), anyInt());
- mDct.enableApn(ApnSetting.TYPE_ENTERPRISE, DcTracker.REQUEST_TYPE_NORMAL, null);
- sendInitializationEvents();
-
- ArgumentCaptor<TrafficDescriptor> tdCaptor =
- ArgumentCaptor.forClass(TrafficDescriptor.class);
- verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
- eq(AccessNetworkType.NGRAN), any(DataProfile.class), eq(false), eq(false),
- eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), tdCaptor.capture(),
- anyBoolean(), any(Message.class));
- assertEquals(null, tdCaptor.getValue().getDataNetworkName());
- assertTrue(Arrays.equals(DataConnection.getEnterpriseOsAppId(),
- tdCaptor.getValue().getOsAppId()));
-
- // Check APN contexts with no DEFAULT set up
- Map<Integer, ApnContext> apnContexts = mDct.getApnContexts()
- .stream().collect(Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
- assertEquals(DctConstants.State.IDLE, apnContexts.get(ApnSetting.TYPE_DEFAULT).getState());
- assertEquals(DctConstants.State.FAILED,
- apnContexts.get(ApnSetting.TYPE_ENTERPRISE).getState());
-
- mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
- .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_LTE)
- .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
- .build();
- doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
- anyInt(), anyInt());
- mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
- waitForMs(200);
-
- verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
- eq(AccessNetworkType.EUTRAN), any(DataProfile.class), eq(false), eq(false),
- eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), tdCaptor.capture(),
- anyBoolean(), any(Message.class));
- assertEquals(FAKE_APN1, tdCaptor.getValue().getDataNetworkName());
- assertEquals(null, tdCaptor.getValue().getOsAppId());
-
- // Check APN contexts after DEFAULT is set up (and ENTERPRISE failure)
- apnContexts = mDct.getApnContexts()
- .stream().collect(Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
- assertEquals(DctConstants.State.CONNECTED,
- apnContexts.get(ApnSetting.TYPE_DEFAULT).getState());
- assertEquals(DctConstants.State.FAILED,
- apnContexts.get(ApnSetting.TYPE_ENTERPRISE).getState());
-
- mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
- .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_NR)
- .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
- .build();
- doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
- anyInt(), anyInt());
- SetupDataCallResult result = createSetupDataCallResult();
- result.cid = 10;
- mSimulatedCommands.setDataCallResult(true, result);
- mDct.enableApn(ApnSetting.TYPE_ENTERPRISE, DcTracker.REQUEST_TYPE_NORMAL, null);
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
- waitForMs(200);
-
- verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
- eq(AccessNetworkType.NGRAN), any(DataProfile.class), eq(false), eq(false),
- eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), tdCaptor.capture(),
- anyBoolean(), any(Message.class));
- assertEquals(null, tdCaptor.getValue().getDataNetworkName());
- assertTrue(Arrays.equals(DataConnection.getEnterpriseOsAppId(),
- tdCaptor.getValue().getOsAppId()));
-
- // Check APN contexts after DEFAULT is set up (and ENTERPRISE reenabled)
- apnContexts = mDct.getApnContexts()
- .stream().collect(Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
- assertEquals(DctConstants.State.CONNECTED,
- apnContexts.get(ApnSetting.TYPE_DEFAULT).getState());
- assertEquals(DctConstants.State.CONNECTED,
- apnContexts.get(ApnSetting.TYPE_ENTERPRISE).getState());
- }
-
- // Test the ENTERPRISE APN setup when the same CID is returned.
- @Test
- public void testTrySetupDataEnterpriseApnDuplicateCid() {
- mApnSettingContentProvider.setFakeApn1NetworkTypeBitmask(
- NETWORK_TYPE_LTE_BITMASK | NETWORK_TYPE_NR_BITMASK);
- mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
- .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_NR)
- .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
- .build();
- doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
- anyInt(), anyInt());
- // mSimulatedCommandsVerifier will return the same CID in SetupDataCallResult
- mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
- mDct.enableApn(ApnSetting.TYPE_ENTERPRISE, DcTracker.REQUEST_TYPE_NORMAL, null);
- sendInitializationEvents();
- waitForMs(200);
-
- ArgumentCaptor<TrafficDescriptor> tdCaptor =
- ArgumentCaptor.forClass(TrafficDescriptor.class);
- verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
- eq(AccessNetworkType.NGRAN), any(DataProfile.class), eq(false), eq(false),
- eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), tdCaptor.capture(),
- anyBoolean(), any(Message.class));
- List<TrafficDescriptor> tds = tdCaptor.getAllValues();
- // [0] is default and [1] is enterprise, since default should be set up first
- assertEquals(FAKE_APN1, tds.get(0).getDataNetworkName());
- assertEquals(null, tds.get(0).getOsAppId());
- assertEquals(null, tds.get(1).getDataNetworkName());
- assertTrue(Arrays.equals(DataConnection.getEnterpriseOsAppId(), tds.get(1).getOsAppId()));
-
- // Check APN contexts after DEFAULT and ENTERPRISE set up
- Map<Integer, ApnContext> apnContexts = mDct.getApnContexts()
- .stream().collect(Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
- assertEquals(DctConstants.State.CONNECTED,
- apnContexts.get(ApnSetting.TYPE_DEFAULT).getState());
- assertEquals(DctConstants.State.FAILED,
- apnContexts.get(ApnSetting.TYPE_ENTERPRISE).getState());
+ eq(DataService.REQUEST_REASON_NORMAL), any(), any(Message.class));
}
@Test
@SmallTest
- public void testGetDataConnectionState() {
- initApns(ApnSetting.TYPE_SUPL_STRING,
- new String[]{ApnSetting.TYPE_SUPL_STRING, ApnSetting.TYPE_DEFAULT_STRING});
+ public void testGetDataConnectionState() throws Exception {
+ initApns(PhoneConstants.APN_TYPE_SUPL,
+ new String[]{PhoneConstants.APN_TYPE_SUPL, PhoneConstants.APN_TYPE_DEFAULT});
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT});
mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
mDct.enableApn(ApnSetting.TYPE_SUPL, DcTracker.REQUEST_TYPE_NORMAL, null);
@@ -1513,20 +1064,20 @@ public class DcTrackerTest extends TelephonyTest {
// Assert that both APN_TYPE_SUPL & APN_TYPE_DEFAULT are connected even we only setup data
// for APN_TYPE_SUPL
- assertEquals(DctConstants.State.CONNECTED, mDct.getState(ApnSetting.TYPE_SUPL_STRING));
- assertEquals(DctConstants.State.CONNECTED, mDct.getState(ApnSetting.TYPE_DEFAULT_STRING));
+ assertEquals(DctConstants.State.CONNECTED, mDct.getState(PhoneConstants.APN_TYPE_SUPL));
+ assertEquals(DctConstants.State.CONNECTED, mDct.getState(PhoneConstants.APN_TYPE_DEFAULT));
}
// Test the unmetered APN setup when data is disabled.
@Test
@SmallTest
- public void testTrySetupDataUnmeteredDataDisabled() {
- initApns(ApnSetting.TYPE_SUPL_STRING, new String[]{ApnSetting.TYPE_SUPL_STRING});
+ public void testTrySetupDataUnmeteredDataDisabled() throws Exception {
+ initApns(PhoneConstants.APN_TYPE_SUPL, new String[]{PhoneConstants.APN_TYPE_SUPL});
doReturn(false).when(mDataEnabledSettings).isDataEnabled();
doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_FOTA_STRING});
+ new String[]{PhoneConstants.APN_TYPE_FOTA});
mDct.enableApn(ApnSetting.TYPE_SUPL, DcTracker.REQUEST_TYPE_NORMAL, null);
@@ -1535,20 +1086,20 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
eq(AccessNetworkType.EUTRAN), any(DataProfile.class),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
}
// Test the unmetered default APN setup when data is disabled. Default APN should always honor
// the users's setting.
@Test
@SmallTest
- public void testTrySetupDataUnmeteredDefaultDataDisabled() {
- initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_DEFAULT_STRING});
+ public void testTrySetupDataUnmeteredDefaultDataDisabled() throws Exception {
+ initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_DEFAULT});
doReturn(false).when(mDataEnabledSettings).isDataEnabled();
doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_MMS_STRING});
+ new String[]{PhoneConstants.APN_TYPE_MMS});
mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
@@ -1557,20 +1108,20 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, never()).setupDataCall(
eq(AccessNetworkType.EUTRAN), any(DataProfile.class),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
}
// Test the metered APN setup when data is disabled.
@Test
@SmallTest
- public void testTrySetupMeteredDataDisabled() {
- initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_DEFAULT_STRING});
+ public void testTrySetupMeteredDataDisabled() throws Exception {
+ initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_DEFAULT});
doReturn(false).when(mDataEnabledSettings).isDataEnabled();
doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT});
mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
@@ -1578,19 +1129,19 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, times(0)).setupDataCall(anyInt(), any(DataProfile.class),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
}
// Test the restricted data request when data is disabled.
@Test
@SmallTest
- public void testTrySetupRestrictedDataDisabled() {
- initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_DEFAULT_STRING});
+ public void testTrySetupRestrictedDataDisabled() throws Exception {
+ initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_DEFAULT});
doReturn(false).when(mDataEnabledSettings).isDataEnabled();
doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT});
sendInitializationEvents();
@@ -1605,18 +1156,18 @@ public class DcTrackerTest extends TelephonyTest {
waitForMs(200);
verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(anyInt(), any(DataProfile.class),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
}
// Test the restricted data request when roaming is disabled.
@Test
@SmallTest
- public void testTrySetupRestrictedRoamingDisabled() {
- initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_DEFAULT_STRING});
+ public void testTrySetupRestrictedRoamingDisabled() throws Exception {
+ initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_DEFAULT});
mDct.setDataRoamingEnabledByUser(false);
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT});
//user is in roaming
doReturn(true).when(mServiceState).getDataRoaming();
@@ -1633,32 +1184,32 @@ public class DcTrackerTest extends TelephonyTest {
waitForMs(200);
verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(anyInt(), any(DataProfile.class),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
}
// Test the default data when data is not connectable.
@Test
@SmallTest
- public void testTrySetupNotConnectable() {
- initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
+ public void testTrySetupNotConnectable() throws Exception {
+ initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
doReturn(false).when(mApnContext).isConnectable();
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT});
sendInitializationEvents();
verify(mSimulatedCommandsVerifier, times(0)).setupDataCall(anyInt(), any(DataProfile.class),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
}
// Test the default data on IWLAN.
@Test
@SmallTest
- public void testTrySetupDefaultOnIWLAN() {
+ public void testTrySetupDefaultOnIWLAN() throws Exception {
doReturn(true).when(mTransportManager).isInLegacyMode();
- initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
+ initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
.setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_IWLAN)
.setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
@@ -1667,30 +1218,30 @@ public class DcTrackerTest extends TelephonyTest {
anyInt(), anyInt());
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT});
sendInitializationEvents();
verify(mSimulatedCommandsVerifier, times(0)).setupDataCall(anyInt(), any(DataProfile.class),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
}
// Test the default data when the phone is in ECBM.
@Test
@SmallTest
- public void testTrySetupDefaultInECBM() {
- initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
+ public void testTrySetupDefaultInECBM() throws Exception {
+ initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
doReturn(true).when(mPhone).isInEcm();
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT});
sendInitializationEvents();
verify(mSimulatedCommandsVerifier, times(0)).setupDataCall(anyInt(), any(DataProfile.class),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
}
// Test update waiting apn list when on data rat change
@@ -1698,7 +1249,7 @@ public class DcTrackerTest extends TelephonyTest {
@Ignore
@Test
@SmallTest
- public void testUpdateWaitingApnListOnDataRatChange() {
+ public void testUpdateWaitingApnListOnDataRatChange() throws Exception {
mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
.setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_EHRPD)
.setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
@@ -1706,9 +1257,9 @@ public class DcTrackerTest extends TelephonyTest {
doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
anyInt(), anyInt());
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT});
mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
- initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
+ initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
sendInitializationEvents();
@@ -1717,9 +1268,9 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier).setupDataCall(
eq(AccessNetworkType.CDMA2000), dpCaptor.capture(),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
verifyDataProfile(dpCaptor.getValue(), FAKE_APN4, 0, 21, 2, NETWORK_TYPE_EHRPD_BITMASK);
- assertTrue(mDct.isAnyDataConnected());
+ assertEquals(DctConstants.State.CONNECTED, mDct.getOverallState());
//data rat change from ehrpd to lte
logd("Sending EVENT_DATA_RAT_CHANGED");
@@ -1743,9 +1294,10 @@ public class DcTrackerTest extends TelephonyTest {
anyLong(), any(PendingIntent.class));
//Send event for reconnecting data
- initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
+ initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_RECONNECT,
- mPhone.getPhoneId(), DcTracker.RELEASE_TYPE_NORMAL, mApnContext));
+ mPhone.getPhoneId(), AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
+ mApnContext));
waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
// Data connection is running on a different thread. Have to wait.
@@ -1754,9 +1306,9 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier).setupDataCall(
eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
- assertTrue(mDct.isAnyDataConnected());
+ assertEquals(DctConstants.State.CONNECTED, mDct.getOverallState());
}
// Test for fetchDunApns()
@@ -1787,14 +1339,16 @@ public class DcTrackerTest extends TelephonyTest {
@Test
@SmallTest
public void testFetchDunApnWithPreferredApnSet() {
- sendCarrierConfigChanged("testFetchDunApnWithPreferredApnSet: ");
+ logd("Sending EVENT_CARRIER_CONFIG_CHANGED");
+ mDct.sendEmptyMessage(DctConstants.EVENT_CARRIER_CONFIG_CHANGED);
+ waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
// apnSetId=1
String dunApnString1 = "[ApnSettingV5]HOT mobile PC,pc.hotm,,,,,,,,,440,10,,DUN,,,true,"
+ "0,,,,,,,,,,1";
// apnSetId=0
String dunApnString2 = "[ApnSettingV5]HOT mobile PC,pc.coldm,,,,,,,,,440,10,,DUN,,,true,"
- + "0,,,,,,,,,,2";
+ + "0,,,,,,,,,,0";
ApnSetting dunApnExpected = ApnSetting.fromString(dunApnString1);
@@ -1808,239 +1362,15 @@ public class DcTrackerTest extends TelephonyTest {
cr.update(PREFERAPN_URI, values, null, null);
// return APN from Setting with apnSetId=1
- ArrayList<ApnSetting> dunApns = mDct.fetchDunApns();
- assertEquals(1, dunApns.size());
- assertEquals(1, dunApns.get(0).getApnSetId());
- assertTrue(dunApnExpected.equals(dunApns.get(0)));
-
- // set that we prefer apn set 2
- values = new ContentValues();
- values.put(Telephony.Carriers.APN_SET_ID, 2);
- cr.update(PREFERAPN_URI, values, null, null);
-
- // return APN from Setting with apnSetId=2
- dunApns = mDct.fetchDunApns();
- assertEquals(1, dunApns.size());
- assertEquals(2, dunApns.get(0).getApnSetId());
- dunApnExpected = ApnSetting.fromString(dunApnString2);
- assertTrue(dunApnExpected.equals(dunApns.get(0)));
- }
-
- @Test
- @SmallTest
- public void testFetchDunApnWhileRoaming() {
- doReturn(true).when(mServiceState).getRoaming();
- mBundle.putBoolean(CarrierConfigManager
- .KEY_DISABLE_DUN_APN_WHILE_ROAMING_WITH_PRESET_APN_BOOL, true);
-
- sendInitializationEvents();
-
- String dunApnString = "[ApnSettingV3]HOT mobile PC,pc.hotm,,,,,,,,,440,10,,DUN,,,true,"
- + "0,,,,,,,,";
-
- Settings.Global.putString(mContext.getContentResolver(),
- Settings.Global.TETHER_DUN_APN, dunApnString);
-
- DcTracker spyDct = spy(mDct);
- doReturn(true).when(spyDct).isPreferredApnUserEdited();
- // Expect non-empty DUN APN list
- assertEquals(1, spyDct.fetchDunApns().size());
-
- doReturn(false).when(spyDct).isPreferredApnUserEdited();
- // Expect empty DUN APN list
- assertEquals(0, spyDct.fetchDunApns().size());
-
- Settings.Global.putString(mContext.getContentResolver(),
- Settings.Global.TETHER_DUN_APN, null);
- }
-
- /**
- * Test that fetchDunApns() returns list that prioritize the preferred APN when the preferred
- * APN including DUN type.
- */
- @Test
- public void testFetchDunApnWithPreferredApn() {
- // Set support APN types of FAKE_APN1 and FAKE_APN5
- mApnSettingContentProvider.setFakeApn1Types("default,dun");
- mApnSettingContentProvider.setFakeApn5Types("default,dun");
-
- // Set prefer apn set id.
- ContentResolver cr = mContext.getContentResolver();
- ContentValues values = new ContentValues();
- values.put(Telephony.Carriers.APN_SET_ID, 0);
- cr.update(PREFERAPN_URI, values, null, null);
- // Set FAKE_APN5 as the preferred APN.
- mApnSettingContentProvider.setFakePreferredApn(mApnSettingContentProvider.getFakeApn5());
-
- sendInitializationEvents();
-
- // Return the APN list that set the preferred APN at the top.
- ArrayList<ApnSetting> dunApns = mDct.fetchDunApns();
+ ArrayList<ApnSetting> dunApns = mDct.sortApnListByPreferred(mDct.fetchDunApns());
assertEquals(2, dunApns.size());
- assertEquals(FAKE_APN5, dunApns.get(0).getApnName());
- assertEquals(FAKE_APN1, dunApns.get(1).getApnName());
- }
-
- // This tests simulates the race case where the sim status change event is triggered, the
- // default data connection is attached, and then the carrier config gets changed which bumps
- // the database id which we want to ignore when cleaning up connections and matching against
- // the dun APN. Tests b/158908392.
- @Test
- @SmallTest
- public void testCheckForCompatibleDataConnectionWithDunWhenIdsChange() {
- //Set dun as a support apn type of FAKE_APN1
- mApnSettingContentProvider.setFakeApn1Types("default,supl,dun");
-
- // Enable the default apn
- mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
-
- //Load the sim and attach the data connection without firing the carrier changed event
- final String logMsgPrefix = "testCheckForCompatibleDataConnectionWithDunWhenIdsChange: ";
- sendSimStateUpdated(logMsgPrefix);
- sendEventDataConnectionAttached(logMsgPrefix);
- waitForMs(200);
-
- // Confirm that FAKE_APN1 comes up as a dun candidate
- ApnSetting dunApn = mDct.fetchDunApns().get(0);
- assertEquals(dunApn.getApnName(), FAKE_APN1);
- Map<Integer, ApnContext> apnContexts = mDct.getApnContexts()
- .stream().collect(Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
-
- //Double check that the default apn content is connected while the dun apn context is not
- assertEquals(apnContexts.get(ApnSetting.TYPE_DEFAULT).getState(),
- DctConstants.State.CONNECTED);
- assertNotEquals(apnContexts.get(ApnSetting.TYPE_DUN).getState(),
- DctConstants.State.CONNECTED);
-
-
- //Change the row ids the same way as what happens when we have old apn values in the
- //carrier table
- mApnSettingContentProvider.setRowIdOffset(100);
- sendCarrierConfigChanged(logMsgPrefix);
- waitForMs(200);
-
- mDct.enableApn(ApnSetting.TYPE_DUN, DcTracker.REQUEST_TYPE_NORMAL, null);
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
-
- Map<Integer, ApnContext> apnContextsAfterRowIdsChanged = mDct.getApnContexts()
- .stream().collect(Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
-
- //Make sure that the data connection used earlier wasn't cleaned up and still in use.
- assertEquals(apnContexts.get(ApnSetting.TYPE_DEFAULT).getDataConnection(),
- apnContextsAfterRowIdsChanged.get(ApnSetting.TYPE_DEFAULT).getDataConnection());
-
- //Check that the DUN is using the same active data connection
- assertEquals(apnContexts.get(ApnSetting.TYPE_DEFAULT).getDataConnection(),
- apnContextsAfterRowIdsChanged.get(ApnSetting.TYPE_DUN).getDataConnection());
- }
-
- @Test
- @SmallTest
- public void testCheckForCompatibleDataConnectionWithEnterprise() {
- // Allow both DEFAULT and ENTERPRISE to use APN 1
- mApnSettingContentProvider.setFakeApn1NetworkTypeBitmask(
- NETWORK_TYPE_LTE_BITMASK | NETWORK_TYPE_NR_BITMASK);
-
- // Enable the DEFAULT APN
- mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
- sendInitializationEvents();
-
- ArgumentCaptor<TrafficDescriptor> tdCaptor =
- ArgumentCaptor.forClass(TrafficDescriptor.class);
- verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
- eq(AccessNetworkType.EUTRAN), any(DataProfile.class), eq(false), eq(false),
- eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), tdCaptor.capture(),
- anyBoolean(), any(Message.class));
- assertEquals(FAKE_APN1, tdCaptor.getValue().getDataNetworkName());
- assertEquals(null, tdCaptor.getValue().getOsAppId());
-
- // Check APN contexts after DEFAULT is set up
- Map<Integer, ApnContext> apnContexts = mDct.getApnContexts()
- .stream().collect(Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
- assertEquals(apnContexts.get(ApnSetting.TYPE_DEFAULT).getState(),
- DctConstants.State.CONNECTED);
- assertNotEquals(apnContexts.get(ApnSetting.TYPE_ENTERPRISE).getState(),
- DctConstants.State.CONNECTED);
-
- // Enable the ENTERPRISE APN
- mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
- .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_NR)
- .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
- .build();
- doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
- anyInt(), anyInt());
- SetupDataCallResult result = createSetupDataCallResult();
- result.cid = 10;
- mSimulatedCommands.setDataCallResult(true, result);
- mDct.enableApn(ApnSetting.TYPE_ENTERPRISE, DcTracker.REQUEST_TYPE_NORMAL, null);
- waitForMs(200);
-
- verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
- eq(AccessNetworkType.NGRAN), any(DataProfile.class), eq(false), eq(false),
- eq(DataService.REQUEST_REASON_NORMAL), any(), anyInt(), any(), tdCaptor.capture(),
- anyBoolean(), any(Message.class));
- assertEquals(null, tdCaptor.getValue().getDataNetworkName());
- assertTrue(Arrays.equals(DataConnection.getEnterpriseOsAppId(),
- tdCaptor.getValue().getOsAppId()));
-
- // Check APN contexts after ENTERPRISE is set up
- Map<Integer, ApnContext> apnContextsAfterRowIdsChanged = mDct.getApnContexts()
- .stream().collect(Collectors.toMap(ApnContext::getApnTypeBitmask, x -> x));
-
- // Make sure that the data connection used earlier wasn't cleaned up and still in use.
- assertEquals(apnContexts.get(ApnSetting.TYPE_DEFAULT).getDataConnection(),
- apnContextsAfterRowIdsChanged.get(ApnSetting.TYPE_DEFAULT).getDataConnection());
-
- // Check that ENTERPRISE isn't using the same data connection as DEFAULT
- assertNotEquals(apnContexts.get(ApnSetting.TYPE_DEFAULT).getDataConnection(),
- apnContextsAfterRowIdsChanged.get(ApnSetting.TYPE_ENTERPRISE).getDataConnection());
- }
-
- // Test for Data setup with APN Set ID
- @Test
- @SmallTest
- public void testDataSetupWithApnSetId() throws Exception {
- // Set the prefer apn set id to "1"
- ContentResolver cr = mContext.getContentResolver();
- ContentValues values = new ContentValues();
- values.put(Telephony.Carriers.APN_SET_ID, 1);
- cr.update(PREFERAPN_URI, values, null, null);
-
- mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
- mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
-
- sendInitializationEvents();
-
- ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
- verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
- eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
- eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
-
- List<DataProfile> dataProfiles = dpCaptor.getAllValues();
- assertEquals(2, dataProfiles.size());
-
- // Verify to use FAKE APN7 which is Default APN with apnSetId=1(Same as the pereferred
- // APN's set id).
- Optional<DataProfile> fakeApn7 = dataProfiles.stream()
- .filter(dp -> dp.getApn().equals(FAKE_APN7)).findFirst();
- assertTrue(fakeApn7.isPresent());
- verifyDataProfile(fakeApn7.get(), FAKE_APN7, 0, 17, 1, NETWORK_TYPE_LTE_BITMASK);
-
- // Verify to use FAKE APN8 which is IMS APN with apnSetId=-1
- // (Telephony.Carriers.MATCH_ALL_APN_SET_ID).
- Optional<DataProfile> fakeApn8 = dataProfiles.stream()
- .filter(dp -> dp.getApn().equals(FAKE_APN8)).findFirst();
- assertTrue(fakeApn8.isPresent());
- verifyDataProfile(fakeApn8.get(), FAKE_APN8, 2, 64, 1, NETWORK_TYPE_LTE_BITMASK);
+ assertTrue(dunApnExpected.equals(dunApns.get(0)));
}
// Test oos
@Test
@SmallTest
- public void testDataRatChangeOOS() {
+ public void testDataRatChangeOOS() throws Exception {
mNetworkRegistrationInfo = new NetworkRegistrationInfo.Builder()
.setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_EHRPD)
.setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
@@ -2049,9 +1379,9 @@ public class DcTrackerTest extends TelephonyTest {
anyInt(), anyInt());
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT});
mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
- initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
+ initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
sendInitializationEvents();
@@ -2060,9 +1390,9 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier).setupDataCall(
eq(AccessNetworkType.CDMA2000), dpCaptor.capture(),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
verifyDataProfile(dpCaptor.getValue(), FAKE_APN4, 0, 21, 2, NETWORK_TYPE_EHRPD_BITMASK);
- assertTrue(mDct.isAnyDataConnected());
+ assertEquals(DctConstants.State.CONNECTED, mDct.getOverallState());
// Data rat change from ehrpd to unknown due to OOS
logd("Sending EVENT_DATA_RAT_CHANGED");
@@ -2093,8 +1423,8 @@ public class DcTrackerTest extends TelephonyTest {
waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
// Verify the same data connection
- assertEquals(FAKE_APN4, mDct.getActiveApnString(ApnSetting.TYPE_DEFAULT_STRING));
- assertTrue(mDct.isAnyDataConnected());
+ assertEquals(FAKE_APN4, mDct.getActiveApnString(PhoneConstants.APN_TYPE_DEFAULT));
+ assertEquals(DctConstants.State.CONNECTED, mDct.getOverallState());
}
// Test provisioning
@@ -2174,9 +1504,9 @@ public class DcTrackerTest extends TelephonyTest {
@Test
@SmallTest
- public void testNetworkStatusChangedRecoveryOFF() {
+ public void testNetworkStatusChangedRecoveryOFF() throws Exception {
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
@@ -2186,7 +1516,7 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, times(2)).setupDataCall(
eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
logd("Sending EVENT_NETWORK_STATUS_CHANGED");
@@ -2208,14 +1538,14 @@ public class DcTrackerTest extends TelephonyTest {
@FlakyTest
@Test
@SmallTest
- public void testNetworkStatusChangedRecoveryON() {
+ public void testNetworkStatusChangedRecoveryON() throws Exception {
ContentResolver resolver = mContext.getContentResolver();
Settings.Global.putInt(resolver, Settings.Global.DATA_STALL_RECOVERY_ON_BAD_NETWORK, 1);
Settings.System.putInt(resolver, "radio.data.stall.recovery.action", 0);
doReturn(new SignalStrength()).when(mPhone).getSignalStrength();
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
@@ -2225,7 +1555,7 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, timeout(TEST_TIMEOUT).times(2)).setupDataCall(
eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
@@ -2247,7 +1577,7 @@ public class DcTrackerTest extends TelephonyTest {
@FlakyTest
@Test
@SmallTest
- public void testRecoveryStepPDPReset() {
+ public void testRecoveryStepPDPReset() throws Exception {
ContentResolver resolver = mContext.getContentResolver();
Settings.Global.putInt(resolver, Settings.Global.DATA_STALL_RECOVERY_ON_BAD_NETWORK, 1);
Settings.Global.putLong(resolver,
@@ -2256,7 +1586,7 @@ public class DcTrackerTest extends TelephonyTest {
doReturn(new SignalStrength()).when(mPhone).getSignalStrength();
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
@@ -2266,7 +1596,7 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, timeout(TEST_TIMEOUT).times(2)).setupDataCall(
eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
logd("Sending EVENT_NETWORK_STATUS_CHANGED false");
@@ -2285,17 +1615,16 @@ public class DcTrackerTest extends TelephonyTest {
@Test
@SmallTest
- public void testRecoveryStepReRegister() {
+ public void testRecoveryStepReRegister() throws Exception {
ContentResolver resolver = mContext.getContentResolver();
Settings.Global.putInt(resolver, Settings.Global.DATA_STALL_RECOVERY_ON_BAD_NETWORK, 1);
Settings.Global.putLong(resolver,
Settings.Global.MIN_DURATION_BETWEEN_RECOVERY_STEPS_IN_MS, 100);
Settings.System.putInt(resolver, "radio.data.stall.recovery.action", 2);
doReturn(new SignalStrength()).when(mPhone).getSignalStrength();
- doReturn(PhoneConstants.State.IDLE).when(mPhone).getState();
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
sendInitializationEvents();
@@ -2304,7 +1633,7 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
logd("Sending EVENT_NETWORK_STATUS_CHANGED false");
@@ -2318,17 +1647,16 @@ public class DcTrackerTest extends TelephonyTest {
@Test
@SmallTest
- public void testRecoveryStepRestartRadio() {
+ public void testRecoveryStepRestartRadio() throws Exception {
ContentResolver resolver = mContext.getContentResolver();
Settings.Global.putInt(resolver, Settings.Global.DATA_STALL_RECOVERY_ON_BAD_NETWORK, 1);
Settings.Global.putLong(resolver,
Settings.Global.MIN_DURATION_BETWEEN_RECOVERY_STEPS_IN_MS, 100);
Settings.System.putInt(resolver, "radio.data.stall.recovery.action", 3);
doReturn(new SignalStrength()).when(mPhone).getSignalStrength();
- doReturn(PhoneConstants.State.IDLE).when(mPhone).getState();
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS,
- new String[]{ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_MMS_STRING});
+ new String[]{PhoneConstants.APN_TYPE_DEFAULT, PhoneConstants.APN_TYPE_MMS});
mDct.enableApn(ApnSetting.TYPE_DEFAULT, DcTracker.REQUEST_TYPE_NORMAL, null);
sendInitializationEvents();
@@ -2337,7 +1665,7 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
logd("Sending EVENT_NETWORK_STATUS_CHANGED false");
@@ -2358,9 +1686,9 @@ public class DcTrackerTest extends TelephonyTest {
clearInvocations(mHandler);
}
- private void setUpSubscriptionPlans(boolean isNrUnmetered) throws Exception {
+ private void setUpSubscriptionPlans(boolean is5GUnmetered) throws Exception {
List<SubscriptionPlan> plans = new ArrayList<>();
- if (isNrUnmetered) {
+ if (is5GUnmetered) {
plans.add(SubscriptionPlan.Builder
.createRecurring(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"),
Period.ofMonths(1))
@@ -2378,28 +1706,6 @@ public class DcTrackerTest extends TelephonyTest {
replaceInstance(DcTracker.class, "mSubscriptionPlans", mDct, plans);
}
- private void resetSubscriptionPlans() throws Exception {
- replaceInstance(DcTracker.class, "mSubscriptionPlans", mDct, null);
- }
-
- private void setUpSubscriptionOverride(int[] networkTypes, boolean isUnmetered)
- throws Exception {
- List<Integer> networkTypesList = null;
- if (networkTypes != null) {
- networkTypesList = new ArrayList<>();
- for (int networkType : networkTypes) {
- networkTypesList.add(networkType);
- }
- }
- replaceInstance(DcTracker.class, "mUnmeteredNetworkTypes", mDct, networkTypesList);
- replaceInstance(DcTracker.class, "mUnmeteredOverride", mDct, isUnmetered);
- }
-
- private void resetSubscriptionOverride() throws Exception {
- replaceInstance(DcTracker.class, "mUnmeteredNetworkTypes", mDct, null);
- replaceInstance(DcTracker.class, "mUnmeteredOverride", mDct, false);
- }
-
private boolean isNetworkTypeUnmetered(int networkType) throws Exception {
Method method = DcTracker.class.getDeclaredMethod(
"isNetworkTypeUnmetered", int.class);
@@ -2439,55 +1745,9 @@ public class DcTrackerTest extends TelephonyTest {
return (boolean) field.get(mDct);
}
- private Map<Integer, List<Message>> getHandoverCompletionMessages() throws Exception {
- Field field = DcTracker.class.getDeclaredField(("mHandoverCompletionMsgs"));
- field.setAccessible(true);
- return (Map<Integer, List<Message>>) field.get(mDct);
- }
-
- private void setUpTempNotMetered() {
- doReturn((int) TelephonyManager.NETWORK_TYPE_BITMASK_NR)
- .when(mPhone).getRadioAccessFamily();
- doReturn(1).when(mPhone).getSubId();
- mBundle.putBoolean(CarrierConfigManager.KEY_NETWORK_TEMP_NOT_METERED_SUPPORTED_BOOL, true);
- Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
- intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, mPhone.getPhoneId());
- intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, mPhone.getSubId());
- mContext.sendBroadcast(intent);
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
- }
-
@Test
public void testIsNetworkTypeUnmetered() throws Exception {
- initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
-
- // only 5G unmetered
- setUpSubscriptionOverride(new int[]{TelephonyManager.NETWORK_TYPE_NR}, true);
-
- assertTrue(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_NR));
- assertFalse(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_LTE));
- assertFalse(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_UNKNOWN));
-
- // all network types metered
- setUpSubscriptionOverride(TelephonyManager.getAllNetworkTypes(), false);
-
- assertFalse(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_NR));
- assertFalse(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_LTE));
- assertFalse(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_UNKNOWN));
-
- // all network types unmetered
- setUpSubscriptionOverride(TelephonyManager.getAllNetworkTypes(), true);
-
- assertTrue(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_NR));
- assertTrue(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_LTE));
- assertTrue(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_UNKNOWN));
-
- resetSubscriptionOverride();
- }
-
- @Test
- public void testIsNetworkTypeUnmeteredViaSubscriptionPlans() throws Exception {
- initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
+ initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
// only 5G unmetered
setUpSubscriptionPlans(true);
@@ -2508,6 +1768,7 @@ public class DcTrackerTest extends TelephonyTest {
plans.add(SubscriptionPlan.Builder
.createRecurring(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"),
Period.ofMonths(1))
+ .setTitle("Some 5GB Plan")
.setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
.build());
@@ -2516,69 +1777,18 @@ public class DcTrackerTest extends TelephonyTest {
assertTrue(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_NR));
assertTrue(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_LTE));
assertTrue(isNetworkTypeUnmetered(TelephonyManager.NETWORK_TYPE_UNKNOWN));
-
- resetSubscriptionPlans();
}
@Test
- public void testIsNrUnmeteredSubscriptionPlans() throws Exception {
- initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
+ public void testIsFrequencyRangeUnmetered() throws Exception {
+ initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
int id = setUpDataConnection();
setUpSubscriptionPlans(false);
setUpWatchdogTimer();
doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA))
.when(mDisplayInfoController).getTelephonyDisplayInfo();
- setUpTempNotMetered();
-
- // NetCapability should be metered when connected to 5G with no unmetered plan or frequency
- mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
- verify(mDataConnection, times(1)).onMeterednessChanged(false);
-
- // Set SubscriptionPlans unmetered
- setUpSubscriptionPlans(true);
-
- // NetCapability should switch to unmetered with an unmetered plan
- mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
- verify(mDataConnection, times(1)).onMeterednessChanged(true);
-
- // Set MMWAVE frequency to unmetered
- mBundle.putBoolean(CarrierConfigManager.KEY_UNMETERED_NR_NSA_MMWAVE_BOOL, true);
- Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
- intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, mPhone.getPhoneId());
- intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, mPhone.getSubId());
- mContext.sendBroadcast(intent);
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
-
- // NetCapability should switch to metered without fr=MMWAVE
- mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
- verify(mDataConnection, times(2)).onMeterednessChanged(false);
-
- // NetCapability should switch to unmetered with fr=MMWAVE
- doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
- TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED))
- .when(mDisplayInfoController).getTelephonyDisplayInfo();
- mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
- verify(mDataConnection, times(2)).onMeterednessChanged(true);
-
- resetDataConnection(id);
- resetSubscriptionPlans();
- }
-
- @Test
- public void testIsNrUnmeteredCarrierConfigs() throws Exception {
- initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
- int id = setUpDataConnection();
- setUpSubscriptionPlans(false);
- setUpWatchdogTimer();
- doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
- TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA))
- .when(mDisplayInfoController).getTelephonyDisplayInfo();
- setUpTempNotMetered();
+ doReturn(1).when(mPhone).getSubId();
// NetCapability should be metered when connected to 5G with no unmetered plan or frequency
mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
@@ -2586,7 +1796,6 @@ public class DcTrackerTest extends TelephonyTest {
verify(mDataConnection, times(1)).onMeterednessChanged(false);
// Set MMWAVE frequency to unmetered
- mBundle.putBoolean(CarrierConfigManager.KEY_UNMETERED_NR_NSA_BOOL, true);
mBundle.putBoolean(CarrierConfigManager.KEY_UNMETERED_NR_NSA_MMWAVE_BOOL, true);
Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, mPhone.getPhoneId());
@@ -2596,7 +1805,7 @@ public class DcTrackerTest extends TelephonyTest {
// NetCapability should switch to unmetered when fr=MMWAVE and MMWAVE unmetered
doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
- TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED))
+ TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA_MMWAVE))
.when(mDisplayInfoController).getTelephonyDisplayInfo();
mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_TELEPHONY_DISPLAY_INFO_CHANGED));
waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
@@ -2612,7 +1821,6 @@ public class DcTrackerTest extends TelephonyTest {
// Set SUB6 frequency to unmetered
doReturn(2).when(mPhone).getSubId();
- mBundle.putBoolean(CarrierConfigManager.KEY_UNMETERED_NR_NSA_MMWAVE_BOOL, false);
mBundle.putBoolean(CarrierConfigManager.KEY_UNMETERED_NR_NSA_SUB6_BOOL, true);
intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, mPhone.getPhoneId());
@@ -2628,16 +1836,14 @@ public class DcTrackerTest extends TelephonyTest {
verify(mDataConnection, times(2)).onMeterednessChanged(true);
resetDataConnection(id);
- resetSubscriptionPlans();
}
@Test
public void testReevaluateUnmeteredConnectionsOnNetworkChange() throws Exception {
- initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
+ initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
int id = setUpDataConnection();
setUpSubscriptionPlans(true);
setUpWatchdogTimer();
- setUpTempNotMetered();
// NetCapability should be unmetered when connected to 5G
doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE,
@@ -2658,12 +1864,11 @@ public class DcTrackerTest extends TelephonyTest {
verify(mDataConnection, times(1)).onMeterednessChanged(false);
resetDataConnection(id);
- resetSubscriptionPlans();
}
@Test
public void testReevaluateUnmeteredConnectionsOnWatchdog() throws Exception {
- initApns(ApnSetting.TYPE_DEFAULT_STRING, new String[]{ApnSetting.TYPE_ALL_STRING});
+ initApns(PhoneConstants.APN_TYPE_DEFAULT, new String[]{PhoneConstants.APN_TYPE_ALL});
int id = setUpDataConnection();
setUpSubscriptionPlans(true);
setUpWatchdogTimer();
@@ -2691,7 +1896,6 @@ public class DcTrackerTest extends TelephonyTest {
assertFalse(getWatchdogStatus());
resetDataConnection(id);
- resetSubscriptionPlans();
}
/**
@@ -2743,8 +1947,10 @@ public class DcTrackerTest extends TelephonyTest {
@Test
public void testRatChanged() throws Exception {
+ mSimulatedCommands.setDataCallResult(true, createSetupDataCallResult());
+
DataConnectionReasons dataConnectionReasons = new DataConnectionReasons();
- boolean allowed = mDct.isDataAllowed(dataConnectionReasons);
+ boolean allowed = isDataAllowed(dataConnectionReasons);
assertFalse(dataConnectionReasons.toString(), allowed);
logd("Sending EVENT_ENABLE_APN");
@@ -2754,7 +1960,7 @@ public class DcTrackerTest extends TelephonyTest {
sendInitializationEvents();
dataConnectionReasons = new DataConnectionReasons();
- allowed = mDct.isDataAllowed(dataConnectionReasons);
+ allowed = isDataAllowed(dataConnectionReasons);
assertTrue(dataConnectionReasons.toString(), allowed);
ArgumentCaptor<DataProfile> dpCaptor = ArgumentCaptor.forClass(DataProfile.class);
@@ -2762,7 +1968,7 @@ public class DcTrackerTest extends TelephonyTest {
verify(mSimulatedCommandsVerifier, times(1)).setupDataCall(
eq(AccessNetworkType.EUTRAN), dpCaptor.capture(),
eq(false), eq(false), eq(DataService.REQUEST_REASON_NORMAL), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
+ any(Message.class));
verifyDataProfile(dpCaptor.getValue(), FAKE_APN1, 0, 21, 1, NETWORK_TYPE_LTE_BITMASK);
verifyDataConnected(FAKE_APN1);
@@ -2789,7 +1995,7 @@ public class DcTrackerTest extends TelephonyTest {
}
@Test
- public void testApnConfigRepositoryUpdatedOnCarrierConfigChange() {
+ public void testApnConfigRepositoryUpdatedOnCarrierConfigChange() throws Exception {
assertPriority(ApnSetting.TYPE_CBS_STRING, 2);
assertPriority(ApnSetting.TYPE_MMS_STRING, 2);
@@ -2825,204 +2031,4 @@ public class DcTrackerTest extends TelephonyTest {
.filter(x -> x.getApnType().equals(type))
.findFirst().get().getPriority());
}
-
- @Test
- public void testProvisionBroadcastReceiver() {
- Intent intent = new Intent("com.android.internal.telephony.PROVISION");
- intent.putExtra("provision.phone.id", mPhone.getPhoneId());
- try {
- mContext.sendBroadcast(intent);
- } catch (SecurityException e) {
- fail();
- }
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
- }
-
- @Test
- public void testRetryHandoverWhenDisconnecting() throws Exception {
- initApns(ApnSetting.TYPE_IMS_STRING, new String[]{ApnSetting.TYPE_IMS_STRING});
- setUpDataConnection();
- SparseArray<ApnContext> apnContextsByType = Mockito.mock(SparseArray.class);
- ConcurrentHashMap<String, ApnContext> apnContexts = Mockito.mock(ConcurrentHashMap.class);
- doReturn(mApnContext).when(apnContextsByType).get(eq(ApnSetting.TYPE_IMS));
- doReturn(mApnContext).when(apnContexts).get(eq(ApnSetting.TYPE_IMS_STRING));
- doReturn(false).when(mApnContext).isConnectable();
- doReturn(false).when(mDataEnabledSettings).isDataEnabled(anyInt());
- doReturn(DctConstants.State.DISCONNECTING).when(mApnContext).getState();
- replaceInstance(DcTracker.class, "mApnContextsByType", mDct, apnContextsByType);
- replaceInstance(DcTracker.class, "mApnContexts", mDct, apnContexts);
-
- sendInitializationEvents();
-
- logd("Sending EVENT_ENABLE_APN");
- // APN id 0 is APN_TYPE_DEFAULT
- mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_HANDOVER,
- mDct.obtainMessage(12345));
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
-
- assertTrue(isHandoverPending(ApnSetting.TYPE_IMS));
-
- // Verify no handover request was sent
- verify(mDataConnection, never()).bringUp(any(ApnContext.class), anyInt(), anyInt(),
- any(Message.class), anyInt(), anyInt(), anyInt(), anyBoolean());
-
- doReturn(DctConstants.State.RETRYING).when(mApnContext).getState();
- // Data now is disconnected
- doReturn(true).when(mApnContext).isConnectable();
- doReturn(true).when(mDataEnabledSettings).isDataEnabled(anyInt());
- mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DISCONNECT_DONE,
- new AsyncResult(Pair.create(mApnContext, 0), null, null)));
-
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
-
- verify(mDataConnection).bringUp(any(ApnContext.class), anyInt(), anyInt(),
- any(Message.class), anyInt(), eq(DcTracker.REQUEST_TYPE_HANDOVER), anyInt(),
- anyBoolean());
- }
-
- @Test
- public void testDataUnthrottled() throws Exception {
- initApns(ApnSetting.TYPE_IMS_STRING, new String[]{ApnSetting.TYPE_IMS_STRING});
- replaceInstance(DcTracker.class, "mDataThrottler", mDct, mDataThrottler);
- mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
- sendInitializationEvents();
- mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_APN_UNTHROTTLED,
- new AsyncResult(null, FAKE_APN3, null)));
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
-
- verify(mDataThrottler).setRetryTime(
- eq(ApnSetting.TYPE_IMS),
- eq(RetryManager.NO_SUGGESTED_RETRY_DELAY),
- eq(DcTracker.REQUEST_TYPE_NORMAL));
- }
-
- @Test
- public void testDataUnthrottledAfterAPNChanged() throws Exception {
- initApns(ApnSetting.TYPE_IMS_STRING, new String[]{ApnSetting.TYPE_IMS_STRING});
- replaceInstance(DcTracker.class, "mDataThrottler", mDct, mDataThrottler);
-
- mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
- sendInitializationEvents();
- mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_APN_CHANGED, null));
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
-
- // Verify unthrottling
- verify(mDataThrottler, times(2)).reset();
- }
-
- @Test
- public void testDataUnthrottledOnSimStateChanged() throws Exception {
- initApns(ApnSetting.TYPE_IMS_STRING, new String[]{ApnSetting.TYPE_IMS_STRING});
- replaceInstance(DcTracker.class, "mDataThrottler", mDct, mDataThrottler);
-
- mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
- sendInitializationEvents();
- sendSimStateUpdated("testDataUnthrottledOnSimStateChanged");
-
- // Verify unthrottling
- verify(mDataThrottler, times(2)).reset();
- }
-
- @Test
- public void testHandlingSecondHandoverRequest() throws Exception {
- initApns(ApnSetting.TYPE_IMS_STRING, new String[]{ApnSetting.TYPE_IMS_STRING});
- setUpDataConnection();
- SparseArray<ApnContext> apnContextsByType = Mockito.mock(SparseArray.class);
- ConcurrentHashMap<String, ApnContext> apnContexts = Mockito.mock(ConcurrentHashMap.class);
- doReturn(mApnContext).when(apnContextsByType).get(eq(ApnSetting.TYPE_IMS));
- doReturn(mApnContext).when(apnContexts).get(eq(ApnSetting.TYPE_IMS_STRING));
- doReturn(false).when(mApnContext).isConnectable();
- doReturn(DctConstants.State.CONNECTING).when(mApnContext).getState();
- replaceInstance(DcTracker.class, "mApnContextsByType", mDct, apnContextsByType);
- replaceInstance(DcTracker.class, "mApnContexts", mDct, apnContexts);
-
- sendInitializationEvents();
-
- logd("Sending EVENT_ENABLE_APN");
- // APN id 0 is APN_TYPE_DEFAULT
- Message msg = mDct.obtainMessage(12345);
- mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_HANDOVER, msg);
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
- Map<Integer, List<Message>> msgs = getHandoverCompletionMessages();
- // Make sure the messages was queued properly instead of fired right away.
- assertTrue(msgs.get(ApnSetting.TYPE_IMS).contains(msg));
- }
-
- @Test
- public void testDataThrottledNotAllowData() throws Exception {
- initApns(ApnSetting.TYPE_IMS_STRING, new String[]{ApnSetting.TYPE_IMS_STRING});
- replaceInstance(DcTracker.class, "mDataThrottler", mDct, mDataThrottler);
- doReturn(SystemClock.elapsedRealtime() + 100000).when(mDataThrottler)
- .getRetryTime(ApnSetting.TYPE_IMS);
- mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
- sendInitializationEvents();
-
- DataConnectionReasons dataConnectionReasons = new DataConnectionReasons();
- boolean allowed = mDct.isDataAllowed(mApnContext, DcTracker.REQUEST_TYPE_NORMAL,
- dataConnectionReasons);
- assertFalse(dataConnectionReasons.toString(), allowed);
- assertTrue(dataConnectionReasons.contains(DataDisallowedReasonType.DATA_THROTTLED));
-
- // Makre sure no data setup request
- verify(mSimulatedCommandsVerifier, never()).setupDataCall(
- anyInt(), any(DataProfile.class), anyBoolean(), anyBoolean(), anyInt(), any(),
- anyInt(), any(), any(), anyBoolean(), any(Message.class));
- }
-
- @Test
- public void testNotifyDataDisconnected() {
- // Verify notify data disconnected on DCT constructor, initialized in setUp()
- ArgumentCaptor<PreciseDataConnectionState> captor =
- ArgumentCaptor.forClass(PreciseDataConnectionState.class);
- verify(mPhone, times(13)).notifyDataConnection(captor.capture());
- for (PreciseDataConnectionState state : captor.getAllValues()) {
- assertEquals(TelephonyManager.DATA_DISCONNECTED, state.getState());
- }
- }
-
- /**
- * There is a corresponding test {@link DataConnectionTest#testDataServiceTempUnavailable()} to
- * test DataConnection behavior.
- */
- @Test
- public void testDataServiceTempUnavailable() {
- Handler handler = Mockito.mock(Handler.class);
- Message handoverCompleteMessage = Message.obtain(handler);
- addHandoverCompleteMsg(handoverCompleteMessage, ApnSetting.TYPE_IMS);
- initApns(ApnSetting.TYPE_IMS_STRING, new String[]{ApnSetting.TYPE_IMS_STRING});
- mDct.sendMessage(mDct.obtainMessage(DctConstants.EVENT_DATA_SETUP_COMPLETE,
- DcTracker.REQUEST_TYPE_HANDOVER, DataCallResponse.HANDOVER_FAILURE_MODE_UNKNOWN,
- new AsyncResult(Pair.create(mApnContext, 0),
- DataFailCause.SERVICE_TEMPORARILY_UNAVAILABLE, new Exception())));
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
- // Ensure handover is not completed yet
- verify(handler, never()).sendMessageDelayed(any(), anyLong());
- }
-
- @Test
- public void testNormalRequestDoesNotFailHandoverRequest() {
- Handler handler = Mockito.mock(Handler.class);
- Message handoverCompleteMessage = Message.obtain(handler);
- addHandoverCompleteMsg(handoverCompleteMessage, ApnSetting.TYPE_IMS);
- initApns(ApnSetting.TYPE_IMS_STRING, new String[]{ApnSetting.TYPE_IMS_STRING});
- mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_NORMAL, null);
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
- // Ensure handover is not completed yet
- verify(handler, never()).sendMessageDelayed(any(), anyLong());
- }
-
- @Test
- public void testPreferenceChangedFallback() {
- Handler handler = Mockito.mock(Handler.class);
- doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WLAN).when(mTransportManager)
- .getPreferredTransport(anyInt());
- Message handoverCompleteMessage = Message.obtain(handler);
- addHandoverCompleteMsg(handoverCompleteMessage, ApnSetting.TYPE_IMS);
- initApns(ApnSetting.TYPE_IMS_STRING, new String[]{ApnSetting.TYPE_IMS_STRING});
- mDct.enableApn(ApnSetting.TYPE_IMS, DcTracker.REQUEST_TYPE_HANDOVER,
- handoverCompleteMessage);
- waitForLastHandlerAction(mDcTrackerTestHandler.getThreadHandler());
- Bundle bundle = handoverCompleteMessage.getData();
- assertTrue(bundle.getBoolean("extra_handover_failure_fallback"));
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/LinkBandwidthEstimatorTest.java b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/LinkBandwidthEstimatorTest.java
deleted file mode 100644
index 80fe817387..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/LinkBandwidthEstimatorTest.java
+++ /dev/null
@@ -1,660 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.internal.telephony.dataconnection;
-
-import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
-
-import static com.android.internal.telephony.dataconnection.LinkBandwidthEstimator.BW_STATS_COUNT_THRESHOLD;
-import static com.android.internal.telephony.dataconnection.LinkBandwidthEstimator.LINK_RX;
-import static com.android.internal.telephony.dataconnection.LinkBandwidthEstimator.LINK_TX;
-import static com.android.internal.telephony.dataconnection.LinkBandwidthEstimator.MSG_ACTIVE_PHONE_CHANGED;
-import static com.android.internal.telephony.dataconnection.LinkBandwidthEstimator.MSG_DEFAULT_NETWORK_CHANGED;
-import static com.android.internal.telephony.dataconnection.LinkBandwidthEstimator.MSG_MODEM_ACTIVITY_RETURNED;
-import static com.android.internal.telephony.dataconnection.LinkBandwidthEstimator.MSG_NR_FREQUENCY_CHANGED;
-import static com.android.internal.telephony.dataconnection.LinkBandwidthEstimator.MSG_SCREEN_STATE_CHANGED;
-import static com.android.internal.telephony.dataconnection.LinkBandwidthEstimator.MSG_SIGNAL_STRENGTH_CHANGED;
-import static com.android.internal.telephony.dataconnection.LinkBandwidthEstimator.UNKNOWN_TAC;
-
-import static org.junit.Assert.*;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.ArgumentMatchers.anyLong;
-import static org.mockito.Mockito.atLeast;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import android.net.NetworkCapabilities;
-import android.os.AsyncResult;
-import android.os.Handler;
-import android.os.Message;
-import android.telephony.CellIdentityLte;
-import android.telephony.ModemActivityInfo;
-import android.telephony.NetworkRegistrationInfo;
-import android.telephony.ServiceState;
-import android.telephony.TelephonyManager;
-import android.testing.AndroidTestingRunner;
-import android.testing.TestableLooper;
-import android.util.Pair;
-
-import com.android.internal.telephony.TelephonyFacade;
-import com.android.internal.telephony.TelephonyTest;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mock;
-
-@RunWith(AndroidTestingRunner.class)
-@TestableLooper.RunWithLooper
-public class LinkBandwidthEstimatorTest extends TelephonyTest {
- private LinkBandwidthEstimator mLBE;
- private static final int [] TX_TIME_1_MS = new int[]{0, 0, 0, 0, 0};
- private static final int [] TX_TIME_2_MS = new int[]{100, 0, 0, 0, 100};
- private static final int RX_TIME_1_MS = 100;
- private static final int RX_TIME_2_MS = 200;
- private static final ModemActivityInfo MAI_INIT =
- new ModemActivityInfo(0, 0, 0, TX_TIME_1_MS, RX_TIME_1_MS);
- private static final ModemActivityInfo MAI_TX_RX_TIME_HIGH =
- new ModemActivityInfo(100L, 0, 0, TX_TIME_2_MS, RX_TIME_2_MS);
- private static final ModemActivityInfo MAI_RX_TIME_HIGH =
- new ModemActivityInfo(100L, 0, 0, TX_TIME_1_MS, RX_TIME_2_MS);
- private static final int EVENT_BANDWIDTH_ESTIMATOR_UPDATE = 1;
- private NetworkCapabilities mNetworkCapabilities;
- private CellIdentityLte mCellIdentity;
- private long mElapsedTimeMs = 0;
- private long mTxBytes = 0;
- private long mRxBytes = 0;
- @Mock
- TelephonyFacade mTelephonyFacade;
- @Mock
- private Handler mTestHandler;
- private NetworkRegistrationInfo mNri;
-
- @Before
- public void setUp() throws Exception {
- super.setUp(getClass().getSimpleName());
- mNetworkCapabilities = new NetworkCapabilities.Builder()
- .addTransportType(TRANSPORT_CELLULAR)
- .build();
-
- mCellIdentity = new CellIdentityLte(310, 260, 1234, 123456, 366);
- mNri = new NetworkRegistrationInfo.Builder()
- .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_LTE)
- .build();
- when(mServiceState.getNetworkRegistrationInfo(anyInt(), anyInt())).thenReturn(mNri);
- when(mServiceState.getOperatorNumeric()).thenReturn("310260");
- when(mTelephonyFacade.getElapsedSinceBootMillis()).thenReturn(0L);
- when(mTelephonyFacade.getMobileTxBytes()).thenReturn(0L);
- when(mTelephonyFacade.getMobileTxBytes()).thenReturn(0L);
- when(mPhone.getCurrentCellIdentity()).thenReturn(mCellIdentity);
- when(mPhone.getSubId()).thenReturn(1);
- when(mSignalStrength.getDbm()).thenReturn(-100);
- when(mSignalStrength.getLevel()).thenReturn(1);
- mLBE = new LinkBandwidthEstimator(mPhone, mTelephonyFacade);
- mLBE.registerForBandwidthChanged(mTestHandler, EVENT_BANDWIDTH_ESTIMATOR_UPDATE, null);
- mLBE.obtainMessage(MSG_DEFAULT_NETWORK_CHANGED, mNetworkCapabilities).sendToTarget();
- mLBE.obtainMessage(MSG_SCREEN_STATE_CHANGED, false).sendToTarget();
- mLBE.obtainMessage(MSG_ACTIVE_PHONE_CHANGED, 1).sendToTarget();
- processAllMessages();
- }
-
- private void addElapsedTime(long timeMs) {
- mElapsedTimeMs += timeMs;
- when(mTelephonyFacade.getElapsedSinceBootMillis()).thenReturn(mElapsedTimeMs);
- }
-
- private void addTxBytes(long txBytes) {
- mTxBytes += txBytes;
- when(mTelephonyFacade.getMobileTxBytes()).thenReturn(mTxBytes);
- }
-
- private void addRxBytes(long rxBytes) {
- mRxBytes += rxBytes;
- when(mTelephonyFacade.getMobileRxBytes()).thenReturn(mRxBytes);
- }
-
- private void subtractRxBytes(long rxBytes) {
- mRxBytes -= rxBytes;
- when(mTelephonyFacade.getMobileRxBytes()).thenReturn(mRxBytes);
- }
-
- @After
- public void tearDown() throws Exception {
- super.tearDown();
- }
-
- @Test
- public void testScreenOnTxTrafficHighOneModemPoll() throws Exception {
- addElapsedTime(4_100);
- moveTimeForward(4_100);
- mLBE.obtainMessage(MSG_SCREEN_STATE_CHANGED, true).sendToTarget();
- addTxBytes(500_000L);
- addRxBytes(10_000L);
- addElapsedTime(2_100);
- moveTimeForward(2_100);
- processAllMessages();
-
- verify(mTelephonyManager, times(1)).requestModemActivityInfo(any(), any());
- }
-
- @Test
- public void testScreenOnTxTrafficHighNotActivePhoneNoModemPoll() throws Exception {
- mLBE.obtainMessage(MSG_ACTIVE_PHONE_CHANGED, 0).sendToTarget();
- addElapsedTime(4_100);
- moveTimeForward(4_100);
- processAllMessages();
-
- mLBE.obtainMessage(MSG_SCREEN_STATE_CHANGED, true).sendToTarget();
- addTxBytes(500_000L);
- addRxBytes(10_000L);
- addElapsedTime(2_100);
- moveTimeForward(2_100);
- processAllMessages();
-
- verify(mTelephonyManager, times(0)).requestModemActivityInfo(any(), any());
- }
-
- private void verifyUpdateBandwidth(int txKbps, int rxKbps) {
- ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
- verify(mTestHandler, atLeast(1))
- .sendMessageAtTime(messageArgumentCaptor.capture(), anyLong());
- assertEquals(EVENT_BANDWIDTH_ESTIMATOR_UPDATE, messageArgumentCaptor.getValue().what);
- assertEquals(new Pair<Integer, Integer>(txKbps, rxKbps),
- ((AsyncResult) messageArgumentCaptor.getValue().obj).result);
- }
-
- @Test
- public void testScreenOnTxRxTrafficHighTwoModemPoll() throws Exception {
- addElapsedTime(4_100);
- moveTimeForward(4_100);
- mLBE.obtainMessage(MSG_SCREEN_STATE_CHANGED, true).sendToTarget();
- processAllMessages();
-
- addTxBytes(10_000L);
- addRxBytes(20_000L);
- addElapsedTime(2_100);
- moveTimeForward(2_100);
- processAllMessages();
- verify(mTelephonyManager, times(1)).requestModemActivityInfo(any(), any());
-
- mLBE.obtainMessage(MSG_MODEM_ACTIVITY_RETURNED, MAI_INIT).sendToTarget();
- processAllMessages();
-
- addTxBytes(100_000L);
- addRxBytes(200_000L);
- addElapsedTime(5_100);
- moveTimeForward(5_100);
- processAllMessages();
-
- mLBE.obtainMessage(MSG_MODEM_ACTIVITY_RETURNED, MAI_TX_RX_TIME_HIGH).sendToTarget();
- processAllMessages();
-
- verify(mTelephonyManager, times(2)).requestModemActivityInfo(any(), any());
- verifyUpdateBandwidth(-1, -1);
- }
-
- @Test
- public void testScreenOnRxTrafficHighTwoModemPollRxTimeHigh() throws Exception {
- addElapsedTime(4_100);
- moveTimeForward(4_100);
- mLBE.obtainMessage(MSG_SCREEN_STATE_CHANGED, true).sendToTarget();
- processAllMessages();
-
- addTxBytes(10_000L);
- addRxBytes(20_000L);
- addElapsedTime(2_100);
- moveTimeForward(2_100);
- processAllMessages();
- verify(mTelephonyManager, times(1)).requestModemActivityInfo(any(), any());
-
- mLBE.obtainMessage(MSG_MODEM_ACTIVITY_RETURNED, MAI_INIT).sendToTarget();
- processAllMessages();
-
- addTxBytes(100_000L);
- addRxBytes(200_000L);
- addElapsedTime(5_100);
- moveTimeForward(5_100);
- processAllMessages();
-
- mLBE.obtainMessage(MSG_MODEM_ACTIVITY_RETURNED, MAI_RX_TIME_HIGH).sendToTarget();
- processAllMessages();
-
- verify(mTelephonyManager, times(2)).requestModemActivityInfo(any(), any());
- verifyUpdateBandwidth(-1, -1);
- }
-
- @Test
- public void testScreenOnTxRxTrafficLow() throws Exception {
- addElapsedTime(4_100);
- moveTimeForward(4_100);
- mLBE.obtainMessage(MSG_SCREEN_STATE_CHANGED, true).sendToTarget();
- addTxBytes(10_000L);
- addRxBytes(10_000L);
- addElapsedTime(2_100);
- moveTimeForward(2_100);
- processAllMessages();
- verify(mTelephonyManager, never()).requestModemActivityInfo(any(), any());
- }
-
- @Test
- public void testScreenOnTrafficLowSampleHighAcc() throws Exception {
- addElapsedTime(4_100);
- moveTimeForward(4_100);
- mLBE.obtainMessage(MSG_SCREEN_STATE_CHANGED, true).sendToTarget();
- for (int i = 0; i < 30; i++) {
- addTxBytes(10_000L);
- addRxBytes(19_000L);
- addElapsedTime(1_100);
- moveTimeForward(1_100);
- processAllMessages();
- }
- verify(mTelephonyManager, times(2)).requestModemActivityInfo(any(), any());
- }
-
- @Test
- public void testScreenOnDefaultNetworkToggleNoExtraTrafficPoll() throws Exception {
- mLBE.obtainMessage(MSG_SCREEN_STATE_CHANGED, true).sendToTarget();
- addElapsedTime(500);
- moveTimeForward(500);
- processAllMessages();
- mLBE.obtainMessage(MSG_DEFAULT_NETWORK_CHANGED, null).sendToTarget();
- addElapsedTime(500);
- moveTimeForward(500);
- processAllMessages();
- mLBE.obtainMessage(MSG_DEFAULT_NETWORK_CHANGED, mNetworkCapabilities).sendToTarget();
- for (int i = 0; i < 3; i++) {
- addElapsedTime(1_100);
- moveTimeForward(1_100);
- processAllMessages();
- }
-
- verify(mTelephonyFacade, times(4)).getMobileTxBytes();
- }
-
- @Test
- public void testRatChangeTriggerBandwidthUpdate() throws Exception {
- mLBE.obtainMessage(MSG_SCREEN_STATE_CHANGED, true).sendToTarget();
- addTxBytes(10_000L);
- addRxBytes(19_000L);
- addElapsedTime(2000);
- moveTimeForward(2000);
- processAllMessages();
-
- addTxBytes(10_000L);
- addRxBytes(19_000L);
- mNri = new NetworkRegistrationInfo.Builder()
- .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_NR)
- .build();
- when(mServiceState.getNetworkRegistrationInfo(anyInt(), anyInt())).thenReturn(mNri);
- addElapsedTime(6000);
- moveTimeForward(6000);
- processAllMessages();
-
- verify(mTelephonyManager, times(0)).requestModemActivityInfo(any(), any());
- verifyUpdateBandwidth(-1, -1);
- }
-
- @Test
- public void testSignalLevelChangeTriggerBandwidthUpdate() throws Exception {
- mLBE.obtainMessage(MSG_SCREEN_STATE_CHANGED, true).sendToTarget();
- processAllMessages();
-
- for (int i = 0; i < BW_STATS_COUNT_THRESHOLD + 2; i++) {
- addTxBytes(10_000L);
- addRxBytes(500_000L);
- addElapsedTime(5_100);
- moveTimeForward(5_100);
- processAllMessages();
- mLBE.obtainMessage(MSG_MODEM_ACTIVITY_RETURNED, new ModemActivityInfo(
- i * 5_100L, 0, 0, TX_TIME_2_MS, i * RX_TIME_2_MS)).sendToTarget();
- processAllMessages();
- }
-
- verifyUpdateBandwidth(-1, 19_597);
-
- addTxBytes(20_000L);
- addRxBytes(50_000L);
- when(mSignalStrength.getDbm()).thenReturn(-110);
- mLBE.obtainMessage(MSG_SIGNAL_STRENGTH_CHANGED, mSignalStrength).sendToTarget();
- addElapsedTime(6000);
- moveTimeForward(6000);
- processAllMessages();
-
- verifyUpdateBandwidth(-1, -1);
- }
-
- @Test
- public void testAvgBwForAllPossibleRat() throws Exception {
- Pair<Integer, Integer> values = mLBE.getStaticAvgBw(TelephonyManager.NETWORK_TYPE_GPRS);
- assertEquals(24, (int) values.second);
- values = mLBE.getStaticAvgBw(TelephonyManager.NETWORK_TYPE_EDGE);
- assertEquals(18, (int) values.second);
- values = mLBE.getStaticAvgBw(TelephonyManager.NETWORK_TYPE_UMTS);
- assertEquals(115, (int) values.second);
- values = mLBE.getStaticAvgBw(TelephonyManager.NETWORK_TYPE_CDMA);
- assertEquals(14, (int) values.second);
- values = mLBE.getStaticAvgBw(TelephonyManager.NETWORK_TYPE_1xRTT);
- assertEquals(30, (int) values.second);
- values = mLBE.getStaticAvgBw(TelephonyManager.NETWORK_TYPE_EVDO_0);
- assertEquals(48, (int) values.second);
- values = mLBE.getStaticAvgBw(TelephonyManager.NETWORK_TYPE_EVDO_A);
- assertEquals(550, (int) values.second);
- values = mLBE.getStaticAvgBw(TelephonyManager.NETWORK_TYPE_HSDPA);
- assertEquals(620, (int) values.second);
- values = mLBE.getStaticAvgBw(TelephonyManager.NETWORK_TYPE_HSUPA);
- assertEquals(1800, (int) values.second);
- values = mLBE.getStaticAvgBw(TelephonyManager.NETWORK_TYPE_HSPA);
- assertEquals(1800, (int) values.second);
- values = mLBE.getStaticAvgBw(TelephonyManager.NETWORK_TYPE_EVDO_B);
- assertEquals(550, (int) values.second);
- values = mLBE.getStaticAvgBw(TelephonyManager.NETWORK_TYPE_EHRPD);
- assertEquals(750, (int) values.first);
- values = mLBE.getStaticAvgBw(TelephonyManager.NETWORK_TYPE_HSPAP);
- assertEquals(3400, (int) values.second);
- values = mLBE.getStaticAvgBw(TelephonyManager.NETWORK_TYPE_TD_SCDMA);
- assertEquals(115, (int) values.first);
- values = mLBE.getStaticAvgBw(TelephonyManager.NETWORK_TYPE_LTE);
- assertEquals(15000, (int) values.second);
- when(mServiceState.getNrState()).thenReturn(NetworkRegistrationInfo.NR_STATE_CONNECTED);
- when(mServiceState.getNrFrequencyRange()).thenReturn(ServiceState.FREQUENCY_RANGE_MMWAVE);
- values = mLBE.getStaticAvgBw(TelephonyManager.NETWORK_TYPE_LTE);
- assertEquals(145000, (int) values.first);
- when(mServiceState.getNrFrequencyRange()).thenReturn(ServiceState.FREQUENCY_RANGE_UNKNOWN);
- values = mLBE.getStaticAvgBw(TelephonyManager.NETWORK_TYPE_LTE);
- assertEquals(47000, (int) values.first);
- values = mLBE.getStaticAvgBw(TelephonyManager.NETWORK_TYPE_NR);
- assertEquals(145_000, (int) values.first);
- when(mServiceState.getNrFrequencyRange()).thenReturn(ServiceState.FREQUENCY_RANGE_MMWAVE);
- values = mLBE.getStaticAvgBw(TelephonyManager.NETWORK_TYPE_NR);
- assertEquals("NR_MMWAVE", mLBE.getDataRatName(TelephonyManager.NETWORK_TYPE_NR));
- assertEquals(145_000, (int) values.first);
- }
-
- @Test
- public void testSwitchToNrMmwaveTriggerBandwidthUpdate() throws Exception {
- mLBE.obtainMessage(MSG_SCREEN_STATE_CHANGED, true).sendToTarget();
- addTxBytes(10_000L);
- addRxBytes(19_000L);
- addElapsedTime(2000);
- moveTimeForward(2000);
- processAllMessages();
-
- addTxBytes(10_000L);
- addRxBytes(19_000L);
- when(mServiceState.getNrState()).thenReturn(NetworkRegistrationInfo.NR_STATE_CONNECTED);
- when(mServiceState.getNrFrequencyRange()).thenReturn(ServiceState.FREQUENCY_RANGE_MMWAVE);
- when(mSignalStrength.getLevel()).thenReturn(2);
- mLBE.obtainMessage(MSG_NR_FREQUENCY_CHANGED).sendToTarget();
- addElapsedTime(6000);
- moveTimeForward(6000);
- processAllMessages();
-
- verifyUpdateBandwidth(-1, -1);
- }
-
- @Test
- public void testEnoughModemPollTriggerBwUpdate() throws Exception {
- mLBE.obtainMessage(MSG_SCREEN_STATE_CHANGED, true).sendToTarget();
- processAllMessages();
-
- for (int i = 0; i < BW_STATS_COUNT_THRESHOLD + 2; i++) {
- addTxBytes(10_000L);
- addRxBytes(500_000L);
- addElapsedTime(5_100);
- moveTimeForward(5_100);
- processAllMessages();
- mLBE.obtainMessage(MSG_MODEM_ACTIVITY_RETURNED, new ModemActivityInfo(
- i * 5_100L, 0, 0, TX_TIME_2_MS, i * RX_TIME_2_MS)).sendToTarget();
- processAllMessages();
- }
-
- verify(mTelephonyManager, times(BW_STATS_COUNT_THRESHOLD + 2))
- .requestModemActivityInfo(any(), any());
- verifyUpdateBandwidth(-1, 19_597);
- }
-
- @Test
- public void testAbnormalTrafficCountTriggerLessBwUpdate() throws Exception {
- mLBE.obtainMessage(MSG_SCREEN_STATE_CHANGED, true).sendToTarget();
- processAllMessages();
-
- for (int i = 0; i < BW_STATS_COUNT_THRESHOLD + 2; i++) {
- if (i == 1) {
- addTxBytes(10_000L);
- subtractRxBytes(500_000L);
- } else {
- addTxBytes(10_000L);
- addRxBytes(500_000L);
- }
- addElapsedTime(5_100);
- moveTimeForward(5_100);
- processAllMessages();
- mLBE.obtainMessage(MSG_MODEM_ACTIVITY_RETURNED, new ModemActivityInfo(
- i * 5_100L, 0, 0, TX_TIME_2_MS, i * RX_TIME_2_MS)).sendToTarget();
- processAllMessages();
- }
-
- verify(mTelephonyManager, times(BW_STATS_COUNT_THRESHOLD))
- .requestModemActivityInfo(any(), any());
- verifyUpdateBandwidth(-1, -1);
- }
-
- @Test
- public void testUseCurrentTacStatsWithEnoughData() throws Exception {
- mLBE.obtainMessage(MSG_SCREEN_STATE_CHANGED, true).sendToTarget();
- processAllMessages();
-
- for (int i = 0; i < BW_STATS_COUNT_THRESHOLD; i++) {
- addTxBytes(10_000L);
- addRxBytes(500_000L);
- addElapsedTime(5_100);
- moveTimeForward(5_100);
- processAllMessages();
- mLBE.obtainMessage(MSG_MODEM_ACTIVITY_RETURNED, new ModemActivityInfo(
- i * 5_100L, 0, 0, TX_TIME_2_MS, i * RX_TIME_2_MS)).sendToTarget();
- processAllMessages();
- }
-
- mCellIdentity = new CellIdentityLte(310, 260, 1235, 123457, 367);
- when(mPhone.getCurrentCellIdentity()).thenReturn(mCellIdentity);
- for (int i = BW_STATS_COUNT_THRESHOLD; i < 3 * BW_STATS_COUNT_THRESHOLD; i++) {
- addTxBytes(10_000L);
- addRxBytes(500_000L);
- addElapsedTime(5_100);
- moveTimeForward(5_100);
- processAllMessages();
- mLBE.obtainMessage(MSG_MODEM_ACTIVITY_RETURNED, new ModemActivityInfo(
- i * 5_100L, 0, 0, TX_TIME_2_MS, i * RX_TIME_2_MS)).sendToTarget();
- processAllMessages();
- }
-
- verifyUpdateBandwidth(-1, 19_597);
- }
-
- @Test
- public void testUseAllTacStatsIfNoEnoughDataWithCurrentTac() throws Exception {
- mLBE.obtainMessage(MSG_SCREEN_STATE_CHANGED, true).sendToTarget();
- processAllMessages();
- mLBE.obtainMessage(MSG_SIGNAL_STRENGTH_CHANGED, mSignalStrength).sendToTarget();
- processAllMessages();
-
- for (int i = 0; i < BW_STATS_COUNT_THRESHOLD; i++) {
- addTxBytes(10_000L);
- addRxBytes(900_000L);
- addElapsedTime(5_100);
- moveTimeForward(5_100);
- processAllMessages();
- mLBE.obtainMessage(MSG_MODEM_ACTIVITY_RETURNED, new ModemActivityInfo(
- i * 5_100L, 0, 0, TX_TIME_2_MS, i * RX_TIME_2_MS)).sendToTarget();
- processAllMessages();
- }
-
- mCellIdentity = new CellIdentityLte(310, 260, 1234, 123456, 367);
- when(mPhone.getCurrentCellIdentity()).thenReturn(mCellIdentity);
- for (int i = BW_STATS_COUNT_THRESHOLD; i < BW_STATS_COUNT_THRESHOLD * 3 / 2; i++) {
- addTxBytes(10_000L);
- addRxBytes(1_000_000L);
- addElapsedTime(5_100);
- moveTimeForward(5_100);
- processAllMessages();
- mLBE.obtainMessage(MSG_MODEM_ACTIVITY_RETURNED, new ModemActivityInfo(
- i * 5_100L, 0, 0, TX_TIME_2_MS, i * RX_TIME_2_MS)).sendToTarget();
- processAllMessages();
- }
-
- LinkBandwidthEstimator.NetworkBandwidth network = mLBE.lookupNetwork("310260", 366, "LTE");
- assertEquals(BW_STATS_COUNT_THRESHOLD - 1, network.getCount(LINK_RX, 1));
- assertEquals(900_000L * 8 * 1000 / 200 / 1024 * (BW_STATS_COUNT_THRESHOLD - 1),
- network.getValue(LINK_RX, 1));
- network = mLBE.lookupNetwork("310260", 367, "LTE");
- assertEquals(1, network.getCount(LINK_RX, 1));
- assertEquals(1_000_000L * 8 * 1000 / 200 / 1024,
- network.getValue(LINK_RX, 1));
- network = mLBE.lookupNetwork("310260", UNKNOWN_TAC, "LTE");
- assertEquals(BW_STATS_COUNT_THRESHOLD * 3 / 2 - 2, network.getCount(LINK_RX, 1));
- assertEquals(179_686, network.getValue(LINK_RX, 1));
- verifyUpdateBandwidth(-1, 37_350);
- }
-
- @Test
- public void testSwitchCarrierFallbackToColdStartValue() throws Exception {
- mLBE.obtainMessage(MSG_SCREEN_STATE_CHANGED, true).sendToTarget();
- processAllMessages();
-
- for (int i = 0; i < BW_STATS_COUNT_THRESHOLD + 5; i++) {
- addTxBytes(10_000L);
- addRxBytes(500_000L);
- addElapsedTime(5_100);
- moveTimeForward(5_100);
- processAllMessages();
- mLBE.obtainMessage(MSG_MODEM_ACTIVITY_RETURNED, new ModemActivityInfo(
- i * 5_100L, 0, 0, TX_TIME_2_MS, i * RX_TIME_2_MS)).sendToTarget();
- processAllMessages();
- }
-
- verifyUpdateBandwidth(-1, 19_597);
-
- mCellIdentity = new CellIdentityLte(320, 265, 1234, 123456, 366);
- when(mPhone.getCurrentCellIdentity()).thenReturn(mCellIdentity);
- when(mServiceState.getOperatorNumeric()).thenReturn("320265");
-
- addTxBytes(10_000L);
- addRxBytes(10_000L);
- addElapsedTime(5_100);
- moveTimeForward(5_100);
- processAllMessages();
-
- verifyUpdateBandwidth(-1, -1);
- }
-
- @Test
- public void testIgnoreLowTxRxTime() throws Exception {
- mLBE.obtainMessage(MSG_SCREEN_STATE_CHANGED, true).sendToTarget();
- processAllMessages();
-
- for (int i = 0; i < BW_STATS_COUNT_THRESHOLD + 5; i++) {
- addTxBytes(10_000L);
- addRxBytes(500_000L);
- addElapsedTime(5_100);
- moveTimeForward(5_100);
- processAllMessages();
- mLBE.obtainMessage(MSG_MODEM_ACTIVITY_RETURNED, new ModemActivityInfo(
- i * 5_100L, 0, 0, TX_TIME_2_MS, i * 80)).sendToTarget();
- processAllMessages();
- }
-
- verifyUpdateBandwidth(-1, -1);
- }
-
- @Test
- public void testEdgeThenLteShouldIgnoreTransitionStats() throws Exception {
- mLBE.obtainMessage(MSG_SCREEN_STATE_CHANGED, true).sendToTarget();
- processAllMessages();
- mNri = new NetworkRegistrationInfo.Builder()
- .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_EDGE)
- .build();
- when(mServiceState.getNetworkRegistrationInfo(anyInt(), anyInt())).thenReturn(mNri);
- mLBE.obtainMessage(MSG_SIGNAL_STRENGTH_CHANGED, mSignalStrength).sendToTarget();
- processAllMessages();
- for (int i = 0; i < BW_STATS_COUNT_THRESHOLD * 2; i++) {
- addTxBytes(12_000L);
- addRxBytes(24_000L);
- addElapsedTime(5_100);
- moveTimeForward(5_100);
- processAllMessages();
- mLBE.obtainMessage(MSG_MODEM_ACTIVITY_RETURNED, new ModemActivityInfo(
- i * 5_100L, 0, 0, TX_TIME_2_MS, i * RX_TIME_2_MS * 5)).sendToTarget();
- processAllMessages();
- }
-
- LinkBandwidthEstimator.NetworkBandwidth network = mLBE.lookupNetwork("310260", 366, "EDGE");
-
- assertEquals(0, network.getCount(LINK_TX, 1));
- assertEquals(BW_STATS_COUNT_THRESHOLD * 2 - 1, network.getCount(LINK_RX, 1));
- assertEquals(24_000L * 8 / 1024 * (BW_STATS_COUNT_THRESHOLD * 2 - 1),
- network.getValue(LINK_RX, 1));
-
- mNri = new NetworkRegistrationInfo.Builder()
- .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_LTE)
- .build();
- when(mServiceState.getNetworkRegistrationInfo(anyInt(), anyInt())).thenReturn(mNri);
- for (int i = BW_STATS_COUNT_THRESHOLD * 2; i < BW_STATS_COUNT_THRESHOLD * 4; i++) {
- addTxBytes(1_200_000L);
- addRxBytes(2_400_000L);
- addElapsedTime(5_100);
- moveTimeForward(5_100);
- processAllMessages();
- mLBE.obtainMessage(MSG_MODEM_ACTIVITY_RETURNED, new ModemActivityInfo(
- i * 5_100L, 0, 0, TX_TIME_2_MS, i * RX_TIME_2_MS * 10)).sendToTarget();
- processAllMessages();
- }
- network = mLBE.lookupNetwork("310260", 366, "LTE");
-
- assertEquals(BW_STATS_COUNT_THRESHOLD * 2 - 2, network.getCount(LINK_RX, 1));
- assertEquals(0, network.getCount(LINK_TX, 1));
- }
-
-
- @Test
- public void testVeryHighByteCountReturnNonNegativeValue() throws Exception {
- mLBE.obtainMessage(MSG_SCREEN_STATE_CHANGED, true).sendToTarget();
- processAllMessages();
- mLBE.obtainMessage(MSG_SIGNAL_STRENGTH_CHANGED, mSignalStrength).sendToTarget();
- processAllMessages();
- for (int i = 0; i < BW_STATS_COUNT_THRESHOLD + 5; i++) {
- addTxBytes(8_000_000_000L);
- addRxBytes(16_000_000_000L);
- addElapsedTime(5_100);
- moveTimeForward(5_100);
- processAllMessages();
- mLBE.obtainMessage(MSG_MODEM_ACTIVITY_RETURNED, new ModemActivityInfo(
- i * 5_100L, 0, 0, TX_TIME_2_MS, i * RX_TIME_2_MS * 5)).sendToTarget();
- processAllMessages();
- }
-
- LinkBandwidthEstimator.NetworkBandwidth network = mLBE.lookupNetwork("310260", 366, "LTE");
-
- assertEquals(BW_STATS_COUNT_THRESHOLD + 4, network.getCount(LINK_RX, 1));
- assertEquals(0, network.getValue(LINK_TX, 1));
- assertEquals(16_000_000_000L * 8 / 1024 * (BW_STATS_COUNT_THRESHOLD + 4),
- network.getValue(LINK_RX, 1));
- }
-}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/QosCallbackTrackerTest.java b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/QosCallbackTrackerTest.java
deleted file mode 100644
index 5a8b54028a..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/QosCallbackTrackerTest.java
+++ /dev/null
@@ -1,490 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.internal.telephony.dataconnection;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.anyInt;
-import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.reset;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
-import android.annotation.NonNull;
-import android.net.InetAddresses;
-import android.net.LinkAddress;
-import android.net.Network;
-import android.net.NetworkAgent;
-import android.telephony.data.EpsBearerQosSessionAttributes;
-import android.telephony.data.EpsQos;
-import android.telephony.data.QosBearerFilter;
-import android.telephony.data.QosBearerSession;
-
-import android.test.suitebuilder.annotation.SmallTest;
-import android.testing.AndroidTestingRunner;
-import android.testing.TestableLooper;
-
-import com.android.internal.telephony.TelephonyTest;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mock;
-
-import java.lang.reflect.Field;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-@RunWith(AndroidTestingRunner.class)
-@TestableLooper.RunWithLooper
-public class QosCallbackTrackerTest extends TelephonyTest {
-
- class Filter implements QosCallbackTracker.IFilter {
- InetSocketAddress localAddress;
- InetSocketAddress remoteAddress;
-
- Filter(@NonNull final InetSocketAddress localAddress) {
- this.localAddress = localAddress;
- this.remoteAddress = null;
- }
-
- Filter(@NonNull final InetSocketAddress localAddress,
- @NonNull final InetSocketAddress remoteAddress) {
- this.localAddress = localAddress;
- this.remoteAddress = remoteAddress;
- }
-
- public boolean matchesLocalAddress(@NonNull final InetAddress address,
- final int startPort, final int endPort) {
- return startPort <= localAddress.getPort()
- && endPort >= localAddress.getPort()
- && localAddress.getAddress().equals(address);
- }
-
- public boolean matchesRemoteAddress(@NonNull final InetAddress address,
- final int startPort, final int endPort) {
- return remoteAddress != null
- && startPort <= remoteAddress.getPort()
- && endPort >= remoteAddress.getPort()
- && remoteAddress.getAddress().equals(address);
- }
- }
-
- @Mock
- private DcNetworkAgent mDcNetworkAgent;
- @Mock
- private Network mNetwork;
-
- private QosCallbackTracker mQosCallbackTracker;
-
- @Before
- public void setUp() throws Exception {
- super.setUp(getClass().getSimpleName());
- doReturn(mNetwork).when(mDcNetworkAgent).getNetwork();
- doReturn(100).when(mNetwork).getNetId();
- mQosCallbackTracker = new QosCallbackTracker(mDcNetworkAgent);
- processAllMessages();
- }
-
- @After
- public void tearDown() throws Exception {
- super.tearDown();
- }
-
- private EpsQos createEpsQos(int dlMbr, int ulMbr, int dlGbr, int ulGbr) {
- // Build android.hardware.radio.V1_6.EpsQos
- android.hardware.radio.V1_6.EpsQos halEpsQos = new android.hardware.radio.V1_6.EpsQos();
- halEpsQos.qci = 4;
- halEpsQos.downlink.maxBitrateKbps = dlMbr;
- halEpsQos.downlink.guaranteedBitrateKbps = dlGbr;
- halEpsQos.uplink.maxBitrateKbps = ulMbr;
- halEpsQos.uplink.guaranteedBitrateKbps = ulGbr;
-
- return new EpsQos(halEpsQos);
- }
-
- private QosBearerFilter createIpv4QosFilter(String localAddress,
- QosBearerFilter.PortRange localPort, int precedence) {
- return new QosBearerFilter(
- Arrays.asList(
- new LinkAddress(InetAddresses.parseNumericAddress(localAddress), 32)),
- new ArrayList<LinkAddress>(), localPort, null, QosBearerFilter.QOS_PROTOCOL_TCP,
- 7, 987, 678, QosBearerFilter.QOS_FILTER_DIRECTION_BIDIRECTIONAL, precedence);
- }
-
- private QosBearerFilter createIpv4QosFilter(String localAddress, String remoteAddress,
- QosBearerFilter.PortRange localPort, QosBearerFilter.PortRange remotePort,
- int precedence) {
- return new QosBearerFilter(
- Arrays.asList(
- new LinkAddress(InetAddresses.parseNumericAddress(localAddress), 32)),
- Arrays.asList(
- new LinkAddress(InetAddresses.parseNumericAddress(remoteAddress), 32)),
- localPort, remotePort,
- QosBearerFilter.QOS_PROTOCOL_TCP, 7, 987, 678,
- QosBearerFilter.QOS_FILTER_DIRECTION_BIDIRECTIONAL, precedence);
- }
-
- @Test
- @SmallTest
- public void testAddFilterBeforeUpdateSessions() throws Exception {
- Filter filter = new Filter(new InetSocketAddress(
- InetAddresses.parseNumericAddress("122.22.22.22"), 2222));
- mQosCallbackTracker.addFilter(1, filter);
-
- // Non-matching QosBearerFilter
- ArrayList<QosBearerFilter> qosFilters1 = new ArrayList<>();
- qosFilters1.add(createIpv4QosFilter("155.55.55.55",
- new QosBearerFilter.PortRange(2222, 2222), 45));
-
- ArrayList<QosBearerSession> qosSessions = new ArrayList<>();
- qosSessions.add(new QosBearerSession(1234, createEpsQos(5, 6, 7, 8), qosFilters1));
-
- mQosCallbackTracker.updateSessions(qosSessions);
-
- verify(mDcNetworkAgent, never()).notifyQosSessionAvailable(eq(1),
- eq(1234), any(EpsBearerQosSessionAttributes.class));
-
- // Matching QosBearerFilter
- ArrayList<QosBearerFilter> qosFilters2 = new ArrayList<>();
- qosFilters2.add(createIpv4QosFilter("122.22.22.22",
- new QosBearerFilter.PortRange(2222, 2222), 45));
- qosSessions.add(new QosBearerSession(1235, createEpsQos(5, 6, 7, 8), qosFilters2));
-
- mQosCallbackTracker.updateSessions(qosSessions);
-
- verify(mDcNetworkAgent, times(1)).notifyQosSessionAvailable(eq(1),
- eq(1235), any(EpsBearerQosSessionAttributes.class));
-
- }
-
-
- @Test
- @SmallTest
- public void testAddFilterAfterUpdateSessions() throws Exception {
- // Non-matching QosBearerFilter
- ArrayList<QosBearerFilter> qosFilters1 = new ArrayList<>();
- qosFilters1.add(createIpv4QosFilter("155.55.55.55",
- new QosBearerFilter.PortRange(2222, 2222), 45));
-
- ArrayList<QosBearerSession> qosSessions = new ArrayList<>();
- qosSessions.add(new QosBearerSession(1234, createEpsQos(5, 6, 7, 8), qosFilters1));
-
- // Matching QosBearerFilter
- ArrayList<QosBearerFilter> qosFilters2 = new ArrayList<>();
- qosFilters2.add(createIpv4QosFilter("122.22.22.22",
- new QosBearerFilter.PortRange(2222, 2222), 45));
- qosSessions.add(new QosBearerSession(1235, createEpsQos(5, 6, 7, 8), qosFilters2));
-
- mQosCallbackTracker.updateSessions(qosSessions);
-
- // Add filter after updateSessions
- Filter filter = new Filter(new InetSocketAddress(
- InetAddresses.parseNumericAddress("122.22.22.22"), 2222));
- mQosCallbackTracker.addFilter(1, filter);
-
- verify(mDcNetworkAgent, times(1)).notifyQosSessionAvailable(eq(1),
- eq(1235), any(EpsBearerQosSessionAttributes.class));
-
- }
-
- @Test
- @SmallTest
- public void testRemoveFilter() throws Exception {
- // Add filter
- Filter filter = new Filter(new InetSocketAddress(
- InetAddresses.parseNumericAddress("122.22.22.22"), 2222));
- mQosCallbackTracker.addFilter(1, filter);
-
- // Non-matching QosBearerFilter
- ArrayList<QosBearerFilter> qosFilters1 = new ArrayList<>();
- qosFilters1.add(createIpv4QosFilter("155.55.55.55",
- new QosBearerFilter.PortRange(2222, 2222), 45));
-
- ArrayList<QosBearerSession> qosSessions = new ArrayList<>();
- qosSessions.add(new QosBearerSession(1234, createEpsQos(5, 6, 7, 8), qosFilters1));
-
- mQosCallbackTracker.updateSessions(qosSessions);
-
- verify(mDcNetworkAgent, never()).notifyQosSessionAvailable(eq(1),
- eq(1234), any(EpsBearerQosSessionAttributes.class));
-
- // Remove the filter
- mQosCallbackTracker.removeFilter(1);
-
- // Matching QosBearerFilter
- ArrayList<QosBearerFilter> qosFilters2 = new ArrayList<>();
- qosFilters2.add(createIpv4QosFilter("122.22.22.22",
- new QosBearerFilter.PortRange(2222, 2222), 45));
- qosSessions.add(new QosBearerSession(1235, createEpsQos(5, 6, 7, 8), qosFilters2));
-
- mQosCallbackTracker.updateSessions(qosSessions);
-
- // Verify that notifyQosSessionAvailable is not invoked as the filter is already removed
- verify(mDcNetworkAgent, never()).notifyQosSessionAvailable(eq(1),
- eq(1235), any(EpsBearerQosSessionAttributes.class));
-
- }
-
- @Test
- @SmallTest
- public void testSessionLost() throws Exception {
- // Non-matching QosBearerFilter
- ArrayList<QosBearerFilter> qosFilters1 = new ArrayList<>();
- qosFilters1.add(createIpv4QosFilter("155.55.55.55", "144.44.44.44",
- new QosBearerFilter.PortRange(2222, 2222),
- new QosBearerFilter.PortRange(2223, 2223), 45));
-
- ArrayList<QosBearerSession> qosSessions = new ArrayList<>();
- qosSessions.add(new QosBearerSession(1234, createEpsQos(5, 6, 7, 8), qosFilters1));
-
- // Matching QosBearerFilter
- ArrayList<QosBearerFilter> qosFilters2 = new ArrayList<>();
- qosFilters2.add(createIpv4QosFilter("122.22.22.22", "144.44.44.44",
- new QosBearerFilter.PortRange(2222, 2222),
- new QosBearerFilter.PortRange(2223, 2223), 45));
- qosSessions.add(new QosBearerSession(1235, createEpsQos(5, 6, 7, 8), qosFilters2));
-
- mQosCallbackTracker.updateSessions(qosSessions);
-
- // Add filter after updateSessions
- Filter filter = new Filter(new InetSocketAddress(
- InetAddresses.parseNumericAddress("122.22.22.22"), 2222),
- new InetSocketAddress(InetAddresses.parseNumericAddress("144.44.44.44"), 2223));
- mQosCallbackTracker.addFilter(1, filter);
-
- verify(mDcNetworkAgent, times(1)).notifyQosSessionAvailable(eq(1),
- eq(1235), any(EpsBearerQosSessionAttributes.class));
-
- // Remove the matching QosBearerFilter
- qosSessions.remove(1);
- mQosCallbackTracker.updateSessions(qosSessions);
-
- verify(mDcNetworkAgent, times(1)).notifyQosSessionLost(eq(1), eq(1235), eq(1));
- }
-
- @Test
- @SmallTest
- public void testModifiedQos() throws Exception {
- // Non-matching QosBearerFilter
- ArrayList<QosBearerFilter> qosFilters1 = new ArrayList<>();
- qosFilters1.add(createIpv4QosFilter("155.55.55.55", "144.44.44.44",
- new QosBearerFilter.PortRange(2222, 2222),
- new QosBearerFilter.PortRange(2223, 2223), 45));
-
- ArrayList<QosBearerSession> qosSessions = new ArrayList<>();
- qosSessions.add(new QosBearerSession(1234, createEpsQos(5, 6, 7, 8), qosFilters1));
-
- // Matching QosBearerFilter
- ArrayList<QosBearerFilter> qosFilters2 = new ArrayList<>();
- qosFilters2.add(createIpv4QosFilter("122.22.22.22", "144.44.44.44",
- new QosBearerFilter.PortRange(2222, 2222),
- new QosBearerFilter.PortRange(2223, 2223), 45));
- qosSessions.add(new QosBearerSession(1235, createEpsQos(5, 6, 7, 8), qosFilters2));
-
- mQosCallbackTracker.updateSessions(qosSessions);
-
- // Add filter after updateSessions
- Filter filter = new Filter(new InetSocketAddress(
- InetAddresses.parseNumericAddress("122.22.22.22"), 2222),
- new InetSocketAddress(InetAddresses.parseNumericAddress("144.44.44.44"), 2223));
- mQosCallbackTracker.addFilter(1, filter);
-
- verify(mDcNetworkAgent, times(1)).notifyQosSessionAvailable(eq(1),
- eq(1235), any(EpsBearerQosSessionAttributes.class));
-
- reset(mDcNetworkAgent);
-
- // Update the QOS
- qosSessions.remove(1);
- qosSessions.add(new QosBearerSession(1235, createEpsQos(10, 12, 14, 16), qosFilters2));
- mQosCallbackTracker.updateSessions(qosSessions);
-
- verify(mDcNetworkAgent, times(1)).notifyQosSessionAvailable(eq(1),
- eq(1235), any(EpsBearerQosSessionAttributes.class));
- }
-
- @Test
- @SmallTest
- public void testUnmodifiedQos() throws Exception {
- // Non-matching QosBearerFilter
- ArrayList<QosBearerFilter> qosFilters1 = new ArrayList<>();
- qosFilters1.add(createIpv4QosFilter("155.55.55.55", "144.44.44.44",
- new QosBearerFilter.PortRange(2222, 2222),
- new QosBearerFilter.PortRange(2223, 2223), 45));
-
- ArrayList<QosBearerSession> qosSessions = new ArrayList<>();
- qosSessions.add(new QosBearerSession(1234, createEpsQos(5, 6, 7, 8), qosFilters1));
-
- // Matching QosBearerFilter
- ArrayList<QosBearerFilter> qosFilters2 = new ArrayList<>();
- qosFilters2.add(createIpv4QosFilter("122.22.22.22", "144.44.44.44",
- new QosBearerFilter.PortRange(2222, 2222),
- new QosBearerFilter.PortRange(2223, 2223), 45));
- qosSessions.add(new QosBearerSession(1235, createEpsQos(5, 6, 7, 8), qosFilters2));
-
- mQosCallbackTracker.updateSessions(qosSessions);
-
- // Add filter after updateSessions
- Filter filter = new Filter(new InetSocketAddress(
- InetAddresses.parseNumericAddress("122.22.22.22"), 2222),
- new InetSocketAddress(InetAddresses.parseNumericAddress("144.44.44.44"), 2223));
- mQosCallbackTracker.addFilter(1, filter);
-
- verify(mDcNetworkAgent, times(1)).notifyQosSessionAvailable(eq(1),
- eq(1235), any(EpsBearerQosSessionAttributes.class));
-
- reset(mDcNetworkAgent);
-
- // Update the same QOS
- qosSessions.remove(1);
- qosSessions.add(new QosBearerSession(1235, createEpsQos(5, 6, 7, 8), qosFilters2));
- mQosCallbackTracker.updateSessions(qosSessions);
-
- verify(mDcNetworkAgent, never()).notifyQosSessionAvailable(eq(1),
- eq(1235), any(EpsBearerQosSessionAttributes.class));
- }
-
- @Test
- @SmallTest
- public void testEmptyQosSessions() throws Exception {
- // Add filter
- Filter filter = new Filter(new InetSocketAddress(
- InetAddresses.parseNumericAddress("155.55.55.55"), 2222),
- new InetSocketAddress(InetAddresses.parseNumericAddress("144.44.44.44"), 2223));
- mQosCallbackTracker.addFilter(1, filter);
-
- // Matching QosBearerFilter
- ArrayList<QosBearerFilter> qosFilters1 = new ArrayList<>();
- qosFilters1.add(createIpv4QosFilter("155.55.55.55", "144.44.44.44",
- new QosBearerFilter.PortRange(2222, 2222),
- new QosBearerFilter.PortRange(2223, 2223), 45));
-
- ArrayList<QosBearerSession> qosSessions = new ArrayList<>();
- qosSessions.add(new QosBearerSession(1234, createEpsQos(5, 6, 7, 8), qosFilters1));
-
- // Matching QosBearerFilter
- ArrayList<QosBearerFilter> qosFilters2 = new ArrayList<>();
- qosFilters2.add(createIpv4QosFilter("122.22.22.22", "144.44.44.44",
- new QosBearerFilter.PortRange(2222, 2222),
- new QosBearerFilter.PortRange(2223, 2223), 45));
- qosSessions.add(new QosBearerSession(1235, createEpsQos(5, 6, 7, 8), qosFilters2));
-
- mQosCallbackTracker.updateSessions(qosSessions);
-
- // Add filter after updateSessions
- Filter filter2 = new Filter(new InetSocketAddress(
- InetAddresses.parseNumericAddress("122.22.22.22"), 2222),
- new InetSocketAddress(InetAddresses.parseNumericAddress("144.44.44.44"), 2223));
- mQosCallbackTracker.addFilter(2, filter2);
-
- verify(mDcNetworkAgent, times(1)).notifyQosSessionAvailable(eq(1),
- eq(1234), any(EpsBearerQosSessionAttributes.class));
- verify(mDcNetworkAgent, times(1)).notifyQosSessionAvailable(eq(2),
- eq(1235), any(EpsBearerQosSessionAttributes.class));
-
- // Update empty QOS sessions list
- mQosCallbackTracker.updateSessions(new ArrayList<>());
-
- verify(mDcNetworkAgent, times(1)).notifyQosSessionLost(eq(1), eq(1234), eq(1));
- verify(mDcNetworkAgent, times(1)).notifyQosSessionLost(eq(2), eq(1235), eq(1));
- }
-
- @Test
- @SmallTest
- public void testMultipleQosSessions() throws Exception {
- // Add filter 1
- Filter filter1 = new Filter(new InetSocketAddress(
- InetAddresses.parseNumericAddress("155.55.55.55"), 2222),
- new InetSocketAddress(InetAddresses.parseNumericAddress("144.44.44.44"), 2223));
- mQosCallbackTracker.addFilter(1, filter1);
-
- // Add filter 2
- Filter filter2 = new Filter(new InetSocketAddress(
- InetAddresses.parseNumericAddress("122.22.22.22"), 2222),
- new InetSocketAddress(InetAddresses.parseNumericAddress("177.77.77.77"), 2227));
- mQosCallbackTracker.addFilter(2, filter2);
-
- // QosBearerFilter 1
- ArrayList<QosBearerFilter> qosFilters1 = new ArrayList<>();
- qosFilters1.add(createIpv4QosFilter("155.55.55.55", "144.44.44.44",
- new QosBearerFilter.PortRange(2222, 2222),
- new QosBearerFilter.PortRange(2223, 2223), 45));
-
- // QosBearerFilter 2
- ArrayList<QosBearerFilter> qosFilters2 = new ArrayList<>();
- qosFilters2.add(createIpv4QosFilter("122.22.22.22", "177.77.77.77",
- new QosBearerFilter.PortRange(2222, 2222),
- new QosBearerFilter.PortRange(2223, 2227), 45));
-
- ArrayList<QosBearerSession> qosSessions = new ArrayList<>();
- qosSessions.add(new QosBearerSession(1234, createEpsQos(5, 6, 7, 8), qosFilters1));
- qosSessions.add(new QosBearerSession(1235, createEpsQos(7, 8, 9, 10), qosFilters2));
-
- mQosCallbackTracker.updateSessions(qosSessions);
-
- verify(mDcNetworkAgent, times(1)).notifyQosSessionAvailable(eq(1),
- eq(1234), any(EpsBearerQosSessionAttributes.class));
- verify(mDcNetworkAgent, times(1)).notifyQosSessionAvailable(eq(2),
- eq(1235), any(EpsBearerQosSessionAttributes.class));
-
- // Update empty QOS sessions list
- mQosCallbackTracker.updateSessions(new ArrayList<>());
-
- verify(mDcNetworkAgent, times(1)).notifyQosSessionLost(eq(1), eq(1234), eq(1));
- verify(mDcNetworkAgent, times(1)).notifyQosSessionLost(eq(2), eq(1235), eq(1));
- }
-
- @Test
- @SmallTest
- public void testQosSessionWithInvalidPortRange() throws Exception {
- // Non-matching QosBearerFilter
- ArrayList<QosBearerFilter> qosFilters1 = new ArrayList<>();
- qosFilters1.add(createIpv4QosFilter("155.55.55.55",
- new QosBearerFilter.PortRange(0,0), 45));
-
- ArrayList<QosBearerSession> qosSessions = new ArrayList<>();
- qosSessions.add(new QosBearerSession(1234, createEpsQos(5, 6, 7, 8), qosFilters1));
-
- // Matching QosBearerFilter
- ArrayList<QosBearerFilter> qosFilters2 = new ArrayList<>();
- qosFilters2.add(createIpv4QosFilter("122.22.22.22",
- new QosBearerFilter.PortRange(-1, 1), 45));
- qosSessions.add(new QosBearerSession(1235, createEpsQos(5, 6, 7, 8), qosFilters2));
-
- mQosCallbackTracker.updateSessions(qosSessions);
-
- // Add filter after updateSessions
- Filter filter = new Filter(new InetSocketAddress(
- InetAddresses.parseNumericAddress("122.22.22.22"), 2222));
- mQosCallbackTracker.addFilter(1, filter);
-
- verify(mDcNetworkAgent, never()).notifyQosSessionAvailable(eq(1),
- eq(1235), any(EpsBearerQosSessionAttributes.class));
-
- }
-}
-
diff --git a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/RetryManagerTest.java b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/RetryManagerTest.java
index 159e20416a..334917f3bc 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/RetryManagerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/RetryManagerTest.java
@@ -18,11 +18,8 @@ package com.android.internal.telephony.dataconnection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.doReturn;
import android.os.PersistableBundle;
-import android.os.SystemClock;
import android.telephony.CarrierConfigManager;
import android.telephony.data.ApnSetting;
import android.test.suitebuilder.annotation.SmallTest;
@@ -151,7 +148,7 @@ public class RetryManagerTest extends TelephonyTest {
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_DATA_CALL_RETRY_CONFIG_STRINGS,
new String[]{"default:2000"});
- RetryManager rm = new RetryManager(mPhone, mDataThrottler, ApnSetting.TYPE_DEFAULT);
+ RetryManager rm = new RetryManager(mPhone, "default");
long delay = rm.getDelayForNextApn(false);
assertEquals(RetryManager.NO_RETRY, delay);
@@ -176,7 +173,7 @@ public class RetryManagerTest extends TelephonyTest {
ArrayList<ApnSetting> waitingApns = new ArrayList<ApnSetting>();
waitingApns.add(ApnSetting.makeApnSetting(mApn1));
- RetryManager rm = new RetryManager(mPhone, mDataThrottler, ApnSetting.TYPE_DEFAULT);
+ RetryManager rm = new RetryManager(mPhone, "default");
rm.setWaitingApns(waitingApns);
ApnSetting nextApn = rm.getNextApnSetting();
@@ -198,7 +195,7 @@ public class RetryManagerTest extends TelephonyTest {
ArrayList<ApnSetting> waitingApns = new ArrayList<ApnSetting>();
waitingApns.add(ApnSetting.makeApnSetting(mApn1));
- RetryManager rm = new RetryManager(mPhone, mDataThrottler, ApnSetting.TYPE_SUPL);
+ RetryManager rm = new RetryManager(mPhone, "supl");
rm.setWaitingApns(waitingApns);
ApnSetting nextApn = rm.getNextApnSetting();
@@ -253,7 +250,7 @@ public class RetryManagerTest extends TelephonyTest {
waitingApns.add(ApnSetting.makeApnSetting(mApn1));
waitingApns.add(ApnSetting.makeApnSetting(mApn2));
- RetryManager rm = new RetryManager(mPhone, mDataThrottler, ApnSetting.TYPE_DEFAULT);
+ RetryManager rm = new RetryManager(mPhone, "default");
rm.setWaitingApns(waitingApns);
ApnSetting nextApn = rm.getNextApnSetting();
@@ -291,7 +288,7 @@ public class RetryManagerTest extends TelephonyTest {
waitingApns.add(ApnSetting.makeApnSetting(mApn1));
waitingApns.add(ApnSetting.makeApnSetting(mApn2));
- RetryManager rm = new RetryManager(mPhone, mDataThrottler, ApnSetting.TYPE_DUN);
+ RetryManager rm = new RetryManager(mPhone, "dun");
rm.setWaitingApns(waitingApns);
ApnSetting nextApn = rm.getNextApnSetting();
@@ -339,7 +336,7 @@ public class RetryManagerTest extends TelephonyTest {
waitingApns.add(ApnSetting.makeApnSetting(mApn1));
waitingApns.add(ApnSetting.makeApnSetting(mApn2));
- RetryManager rm = new RetryManager(mPhone, mDataThrottler, ApnSetting.TYPE_MMS);
+ RetryManager rm = new RetryManager(mPhone, "mms");
rm.setWaitingApns(waitingApns);
ApnSetting nextApn = rm.getNextApnSetting();
@@ -387,7 +384,7 @@ public class RetryManagerTest extends TelephonyTest {
ApnSetting apn = ApnSetting.makeApnSetting(mApn1);
waitingApns.add(apn);
- RetryManager rm = new RetryManager(mPhone, mDataThrottler, ApnSetting.TYPE_FOTA);
+ RetryManager rm = new RetryManager(mPhone, "fota");
rm.setWaitingApns(waitingApns);
ApnSetting nextApn = rm.getNextApnSetting();
@@ -414,7 +411,7 @@ public class RetryManagerTest extends TelephonyTest {
public void testRetryManagerApnPermanentFailedWithTwoApns() throws Exception {
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_DATA_CALL_RETRY_CONFIG_STRINGS,
- new String[]{"mms : 1000,4000,7000"});
+ new String[]{"xyz : 1000,4000,7000"});
ArrayList<ApnSetting> waitingApns = new ArrayList<ApnSetting>();
ApnSetting myApn1 = ApnSetting.makeApnSetting(mApn1);
@@ -422,7 +419,7 @@ public class RetryManagerTest extends TelephonyTest {
waitingApns.add(myApn1);
waitingApns.add(myApn2);
- RetryManager rm = new RetryManager(mPhone, mDataThrottler, ApnSetting.TYPE_MMS);
+ RetryManager rm = new RetryManager(mPhone, "xyz");
rm.setWaitingApns(waitingApns);
ApnSetting nextApn = rm.getNextApnSetting();
@@ -481,7 +478,7 @@ public class RetryManagerTest extends TelephonyTest {
waitingApns.add(myApn2);
waitingApns.add(myApn3);
- RetryManager rm = new RetryManager(mPhone, mDataThrottler, ApnSetting.TYPE_IMS);
+ RetryManager rm = new RetryManager(mPhone, "ims");
rm.setWaitingApns(waitingApns);
ApnSetting nextApn = rm.getNextApnSetting();
@@ -538,7 +535,7 @@ public class RetryManagerTest extends TelephonyTest {
waitingApns.add(myApn1);
waitingApns.add(myApn2);
- RetryManager rm = new RetryManager(mPhone, mDataThrottler, ApnSetting.TYPE_DEFAULT);
+ RetryManager rm = new RetryManager(mPhone, "default");
rm.setWaitingApns(waitingApns);
ApnSetting nextApn = rm.getNextApnSetting();
@@ -590,7 +587,7 @@ public class RetryManagerTest extends TelephonyTest {
ArrayList<ApnSetting> waitingApns = new ArrayList<ApnSetting>();
waitingApns.add(ApnSetting.makeApnSetting(mApn1));
- RetryManager rm = new RetryManager(mPhone, mDataThrottler, ApnSetting.TYPE_DEFAULT);
+ RetryManager rm = new RetryManager(mPhone, "default");
rm.setWaitingApns(waitingApns);
ApnSetting nextApn = rm.getNextApnSetting();
@@ -628,7 +625,7 @@ public class RetryManagerTest extends TelephonyTest {
waitingApns.add(ApnSetting.makeApnSetting(mApn1));
waitingApns.add(ApnSetting.makeApnSetting(mApn2));
- RetryManager rm = new RetryManager(mPhone, mDataThrottler, ApnSetting.TYPE_DEFAULT);
+ RetryManager rm = new RetryManager(mPhone, "default");
rm.setWaitingApns(waitingApns);
ApnSetting nextApn = rm.getNextApnSetting();
@@ -686,7 +683,7 @@ public class RetryManagerTest extends TelephonyTest {
waitingApns.add(ApnSetting.makeApnSetting(mApn1));
waitingApns.add(ApnSetting.makeApnSetting(mApn2));
- RetryManager rm = new RetryManager(mPhone, mDataThrottler, ApnSetting.TYPE_HIPRI);
+ RetryManager rm = new RetryManager(mPhone, "hipri");
rm.setWaitingApns(waitingApns);
ApnSetting nextApn = rm.getNextApnSetting();
@@ -756,7 +753,7 @@ public class RetryManagerTest extends TelephonyTest {
waitingApns.add(ApnSetting.makeApnSetting(mApn1));
waitingApns.add(ApnSetting.makeApnSetting(mApn2));
- RetryManager rm = new RetryManager(mPhone, mDataThrottler, ApnSetting.TYPE_DEFAULT);
+ RetryManager rm = new RetryManager(mPhone, "default");
rm.setWaitingApns(waitingApns);
ApnSetting nextApn = rm.getNextApnSetting();
@@ -806,7 +803,7 @@ public class RetryManagerTest extends TelephonyTest {
waitingApns.add(myApn1);
waitingApns.add(myApn2);
- RetryManager rm = new RetryManager(mPhone, mDataThrottler, ApnSetting.TYPE_DUN);
+ RetryManager rm = new RetryManager(mPhone, "dun");
rm.setWaitingApns(waitingApns);
ApnSetting nextApn = rm.getNextApnSetting();
@@ -871,11 +868,6 @@ public class RetryManagerTest extends TelephonyTest {
assertEquals(RetryManager.NO_RETRY, delay);
}
- private void assertRange(long low, long high, long value) {
- if (value >= low && value <= high) return;
- fail("Not in range[" + low + "," + high + "], value=" + value);
- }
-
/**
* Test the scenario where modem suggests retry the current APN once
*/
@@ -892,7 +884,7 @@ public class RetryManagerTest extends TelephonyTest {
waitingApns.add(myApn1);
waitingApns.add(myApn2);
- RetryManager rm = new RetryManager(mPhone, mDataThrottler, ApnSetting.TYPE_MMS);
+ RetryManager rm = new RetryManager(mPhone, "mms");
rm.setWaitingApns(waitingApns);
ApnSetting nextApn = rm.getNextApnSetting();
@@ -907,32 +899,27 @@ public class RetryManagerTest extends TelephonyTest {
nextApn = rm.getNextApnSetting();
assertTrue(nextApn.equals(mApn1));
- // Network suggests retrying the current APN
- doReturn(2500 + SystemClock.elapsedRealtime()).when(mDataThrottler)
- .getRetryTime(ApnSetting.TYPE_MMS);
+ // Modem suggests retrying the current APN
+ rm.setModemSuggestedDelay(2500);
delay = rm.getDelayForNextApn(false);
- assertRange(2450, 2500, delay);
+ assertEquals(2500, delay);
nextApn = rm.getNextApnSetting();
assertTrue(nextApn.equals(mApn1));
- doReturn(RetryManager.NO_SUGGESTED_RETRY_DELAY).when(mDataThrottler)
- .getRetryTime(ApnSetting.TYPE_MMS);
+ rm.setModemSuggestedDelay(RetryManager.NO_SUGGESTED_RETRY_DELAY);
delay = rm.getDelayForNextApn(false);
assertEquals(20000, delay);
nextApn = rm.getNextApnSetting();
assertTrue(nextApn.equals(mApn2));
// Modem suggests retrying the current APN
- //rm.setModemSuggestedDelay(30000);
- doReturn(30000 + SystemClock.elapsedRealtime()).when(mDataThrottler)
- .getRetryTime(ApnSetting.TYPE_MMS);
+ rm.setModemSuggestedDelay(30000);
delay = rm.getDelayForNextApn(false);
- assertRange(29950, 30000, delay);
+ assertEquals(30000, delay);
nextApn = rm.getNextApnSetting();
assertTrue(nextApn.equals(mApn2));
- doReturn(RetryManager.NO_SUGGESTED_RETRY_DELAY).when(mDataThrottler)
- .getRetryTime(ApnSetting.TYPE_MMS);
+ rm.setModemSuggestedDelay(RetryManager.NO_SUGGESTED_RETRY_DELAY);
delay = rm.getDelayForNextApn(false);
assertEquals(4000, delay);
}
@@ -953,7 +940,7 @@ public class RetryManagerTest extends TelephonyTest {
waitingApns.add(myApn1);
waitingApns.add(myApn2);
- RetryManager rm = new RetryManager(mPhone, mDataThrottler, ApnSetting.TYPE_DEFAULT);
+ RetryManager rm = new RetryManager(mPhone, "default");
rm.setWaitingApns(waitingApns);
ApnSetting nextApn = rm.getNextApnSetting();
@@ -969,42 +956,34 @@ public class RetryManagerTest extends TelephonyTest {
nextApn = rm.getNextApnSetting();
assertTrue(nextApn.equals(mApn1));
// Modem suggests retrying the current APN
- doReturn(2500 + SystemClock.elapsedRealtime()).when(mDataThrottler)
- .getRetryTime(ApnSetting.TYPE_DEFAULT);
+ rm.setModemSuggestedDelay(2500);
delay = rm.getDelayForNextApn(false);
- assertRange(2450, 2500, delay);
+ assertEquals(2500, delay);
nextApn = rm.getNextApnSetting();
assertTrue(nextApn.equals(mApn1));
- doReturn(RetryManager.NO_RETRY).when(mDataThrottler)
- .getRetryTime(ApnSetting.TYPE_DEFAULT);
+ rm.setModemSuggestedDelay(RetryManager.NO_RETRY);
delay = rm.getDelayForNextApn(false);
assertEquals(RetryManager.NO_RETRY, delay);
}
/**
- * Test the scenario that network suggests the same retry for too many times
+ * Test the scenario where modem suggests the same retry for too many times
*/
@Test
@SmallTest
- public void testRetryNetworkSuggestedRetryTooManyTimes() throws Exception {
+ public void testRetryManagerModemSuggestedRetryTooManyTimes() throws Exception {
mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_DATA_CALL_RETRY_CONFIG_STRINGS,
new String[]{"mms:2000,3000", "default:1000,4000,7000,9000"});
- int maxRetryCount = 10;
-
- mBundle.putInt(CarrierConfigManager
- .KEY_CARRIER_DATA_CALL_RETRY_NETWORK_REQUESTED_MAX_COUNT_INT,
- maxRetryCount);
-
ArrayList<ApnSetting> waitingApns = new ArrayList<ApnSetting>();
ApnSetting myApn1 = ApnSetting.makeApnSetting(mApn1);
ApnSetting myApn2 = ApnSetting.makeApnSetting(mApn2);
waitingApns.add(myApn1);
waitingApns.add(myApn2);
- RetryManager rm = new RetryManager(mPhone, mDataThrottler, ApnSetting.TYPE_DEFAULT);
+ RetryManager rm = new RetryManager(mPhone, "default");
rm.setWaitingApns(waitingApns);
ApnSetting nextApn = rm.getNextApnSetting();
@@ -1017,27 +996,61 @@ public class RetryManagerTest extends TelephonyTest {
delay = rm.getDelayForNextApn(false);
assertEquals(1000, delay);
- for (int i = 0; i < maxRetryCount; i++) {
- nextApn = rm.getNextApnSetting();
- assertTrue(nextApn.equals(mApn1));
- doReturn(2500 + SystemClock.elapsedRealtime()).when(mDataThrottler)
- .getRetryTime(ApnSetting.TYPE_DEFAULT);
- delay = rm.getDelayForNextApn(false);
- assertRange(2450, 2500, delay);
- }
+ nextApn = rm.getNextApnSetting();
+ assertTrue(nextApn.equals(mApn1));
+ rm.setModemSuggestedDelay(2500);
+ delay = rm.getDelayForNextApn(false);
+ assertEquals(2500, delay);
+
+ nextApn = rm.getNextApnSetting();
+ assertTrue(nextApn.equals(mApn1));
+ rm.setModemSuggestedDelay(2500);
+ delay = rm.getDelayForNextApn(false);
+ assertEquals(2500, delay);
+
+ nextApn = rm.getNextApnSetting();
+ assertTrue(nextApn.equals(mApn1));
+ rm.setModemSuggestedDelay(2500);
+ delay = rm.getDelayForNextApn(false);
+ assertEquals(2500, delay);
nextApn = rm.getNextApnSetting();
assertTrue(nextApn.equals(mApn1));
- doReturn(2500 + SystemClock.elapsedRealtime()).when(mDataThrottler)
- .getRetryTime(ApnSetting.TYPE_DEFAULT);
+ rm.setModemSuggestedDelay(2500);
delay = rm.getDelayForNextApn(false);
assertEquals(20000, delay);
nextApn = rm.getNextApnSetting();
assertTrue(nextApn.equals(mApn2));
- doReturn(RetryManager.NO_SUGGESTED_RETRY_DELAY).when(mDataThrottler)
- .getRetryTime(ApnSetting.TYPE_DEFAULT);
+ rm.setModemSuggestedDelay(RetryManager.NO_SUGGESTED_RETRY_DELAY);
delay = rm.getDelayForNextApn(false);
assertEquals(4000, delay);
}
+
+ /**
+ * Test the scenario where reset happens before modem suggests retry.
+ */
+ @Test
+ @SmallTest
+ public void testRetryManagerResetBeforeModemSuggestedRetry() throws Exception {
+
+ mBundle.putStringArray(CarrierConfigManager.KEY_CARRIER_DATA_CALL_RETRY_CONFIG_STRINGS,
+ new String[]{"others:1000,4000,7000,9000"});
+
+ ArrayList<ApnSetting> waitingApns = new ArrayList<ApnSetting>();
+ ApnSetting myApn1 = ApnSetting.makeApnSetting(mApn1);
+ ApnSetting myApn2 = ApnSetting.makeApnSetting(mApn2);
+ waitingApns.add(myApn1);
+ waitingApns.add(myApn2);
+
+ RetryManager rm = new RetryManager(mPhone, "mms");
+ rm.setWaitingApns(waitingApns);
+
+ rm.setModemSuggestedDelay(10);
+
+ ApnSetting nextApn = rm.getNextApnSetting();
+ assertTrue(nextApn.equals(mApn1));
+ long delay = rm.getDelayForNextApn(false);
+ assertEquals(20000, delay);
+ }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/TelephonyNetworkFactoryTest.java b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/TelephonyNetworkFactoryTest.java
index 30bd8b27ff..0aa2a4d173 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/TelephonyNetworkFactoryTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/TelephonyNetworkFactoryTest.java
@@ -32,19 +32,16 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import android.net.NetworkCapabilities;
-import android.net.NetworkProvider;
import android.net.NetworkRequest;
import android.net.TelephonyNetworkSpecifier;
import android.os.AsyncResult;
import android.os.Handler;
import android.os.Looper;
-import android.os.Message;
import android.telephony.AccessNetworkConstants;
import android.telephony.data.ApnSetting;
import android.test.suitebuilder.annotation.SmallTest;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
-import android.util.ArraySet;
import androidx.test.filters.FlakyTest;
@@ -59,14 +56,11 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import java.lang.reflect.Field;
import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
@RunWith(AndroidTestingRunner.class)
@TestableLooper.RunWithLooper
@@ -83,12 +77,7 @@ public class TelephonyNetworkFactoryTest extends TelephonyTest {
private String mTestName = "";
- // List of all requests filed by a test
- private final ArraySet<NetworkRequest> mAllNetworkRequestSet = new ArraySet<>();
- // List of requests active in DcTracker
private final ArrayList<NetworkRequest> mNetworkRequestList = new ArrayList<>();
- // List of complete messages associated with the network requests
- private final Map<NetworkRequest, Message> mNetworkRequestMessageMap = new HashMap<>();
private TelephonyNetworkFactory mTelephonyNetworkFactoryUT;
private int mRequestId = 0;
@@ -166,11 +155,7 @@ public class TelephonyNetworkFactoryTest extends TelephonyTest {
"mobile_ia,14,0,2,-1,true", "mobile_emergency,15,0,2,-1,true"});
doAnswer(invocation -> {
- final NetworkRequest req = (NetworkRequest) invocation.getArguments()[0];
- final Message msg = (Message) invocation.getArguments()[2];
- mNetworkRequestList.add(req);
- mAllNetworkRequestSet.add(req);
- mNetworkRequestMessageMap.put(req, msg);
+ mNetworkRequestList.add((NetworkRequest) invocation.getArguments()[0]);
return null;
}).when(mDcTracker).requestNetwork(any(), anyInt(), any());
@@ -189,36 +174,8 @@ public class TelephonyNetworkFactoryTest extends TelephonyTest {
replaceInstance(PhoneSwitcher.class, "sPhoneSwitcher", null, mPhoneSwitcher);
mTelephonyNetworkFactoryUT = new TelephonyNetworkFactory(Looper.myLooper(), mPhone);
- final ArgumentCaptor<NetworkProvider> providerCaptor =
- ArgumentCaptor.forClass(NetworkProvider.class);
- verify(mConnectivityManager).registerNetworkProvider(providerCaptor.capture());
- // For NetworkFactory to function as expected, the provider ID must be set to some
- // number > 0.
- providerCaptor.getValue().setProviderId(1);
+ verify(mConnectivityManager).registerNetworkProvider(any());
verify(mPhoneSwitcher).registerForActivePhoneSwitch(any(), anyInt(), any());
-
- // Simulate the behavior of the system server. When offerNetwork is called, it will
- // update the factory about all requests that pass the registered filter, by calling
- // NetworkProvider#onNetworkNeeded or onNetworkUnneeded.
- // Note that this simulation is a little bit incomplete, as the system server will
- // *update* only for those requests for which the status has changed, but this
- // simulation will send REQUEST_NETWORK or CANCEL_REQUEST for all registered requests.
- // At this time it makes no difference in this test.
- // Also, this test reads from mAllNetworkRequestSet, which is not really the list of
- // requests sent to the system server as the test doesn't instrument that. Instead, it's
- // the list of requests ever sent to the factory. This also makes no difference in this
- // test at this time.
- doAnswer(invocation -> {
- final NetworkCapabilities capabilitiesFilter =
- mTelephonyNetworkFactoryUT.makeNetworkFilter(
- mSubscriptionController.getSubIdUsingPhoneId(0));
- for (final NetworkRequest request : mAllNetworkRequestSet) {
- final int message = request.canBeSatisfiedBy(capabilitiesFilter)
- ? CMD_REQUEST_NETWORK : CMD_CANCEL_REQUEST;
- mTelephonyNetworkFactoryUT.obtainMessage(message, 0, 0, request).sendToTarget();
- }
- return null;
- }).when(mConnectivityManager).offerNetwork(anyInt(), any(), any(), any());
}
/**
@@ -431,40 +388,4 @@ public class TelephonyNetworkFactoryTest extends TelephonyTest {
verify(mDcTracker, times(1)).requestNetwork(any(), eq(1), any());
}
- @Test
- @SmallTest
- public void testNetworkRequestReleasedDuringHandover() throws Exception {
- createMockedTelephonyComponents();
- doReturn(0).when(mSubscriptionController).getSubIdUsingPhoneId(0);
- mTelephonyNetworkFactoryUT.mInternalHandler.sendEmptyMessage(
- TelephonyNetworkFactory.EVENT_SUBSCRIPTION_CHANGED);
-
- activatePhoneInPhoneSwitcher(0, true);
- makeDefaultInternetRequest();
-
- NetworkRequest mmsNetworkRequest = makeSubSpecificMmsRequest(0);
- processAllMessages();
-
- Field f = TelephonyNetworkFactory.class.getDeclaredField("mInternalHandler");
- f.setAccessible(true);
- Handler h = (Handler) f.get(mTelephonyNetworkFactoryUT);
-
- HandoverCallback handoverCallback = mock(HandoverCallback.class);
- //Mockito.reset(mDcTracker);
- doReturn(mDataConnection).when(mDcTracker).getDataConnectionByApnType(anyString());
- doReturn(true).when(mDataConnection).isActive();
-
- HandoverParams hp = new HandoverParams(ApnSetting.TYPE_MMS,
- AccessNetworkConstants.TRANSPORT_TYPE_WLAN, handoverCallback);
- AsyncResult ar = new AsyncResult(null, hp, null);
- h.sendMessage(h.obtainMessage(5 /* EVENT_DATA_HANDOVER_NEEDED */, ar));
- processAllMessages();
-
- // Now release the network request while handover is still ongoing.
- mTelephonyNetworkFactoryUT.releaseNetworkFor(mmsNetworkRequest);
- processAllMessages();
-
- // Ensure the release is called one more time after the normal release
- verify(mDcTracker, times(2)).releaseNetwork(any(), eq(1));
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/TransportManagerTest.java b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/TransportManagerTest.java
index 1e79ae1649..12c72030c8 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/dataconnection/TransportManagerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/dataconnection/TransportManagerTest.java
@@ -45,9 +45,9 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import java.lang.reflect.Field;
-import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.LinkedList;
import java.util.List;
@RunWith(AndroidTestingRunner.class)
@@ -175,10 +175,10 @@ public class TransportManagerTest extends TelephonyTest {
verify(mTestHandler, never()).sendMessageAtTime(any(Message.class), anyLong());
}
- private ArrayDeque<List<QualifiedNetworks>> getQueuedNetworksList() throws Exception {
- Field f = TransportManager.class.getDeclaredField("mQueuedNetworksList");
+ private LinkedList<List<QualifiedNetworks>> getAvailableNetworksList() throws Exception {
+ Field f = TransportManager.class.getDeclaredField("mAvailableNetworksList");
f.setAccessible(true);
- return (ArrayDeque<List<QualifiedNetworks>>) f.get(mTransportManager);
+ return (LinkedList<List<QualifiedNetworks>>) f.get(mTransportManager);
}
@Test
@@ -235,7 +235,7 @@ public class TransportManagerTest extends TelephonyTest {
verify(mTestHandler, times(1)).sendMessageAtTime(messageArgumentCaptor.capture(),
anyLong());
- ArrayDeque<List<QualifiedNetworks>> listQueue = getQueuedNetworksList();
+ LinkedList<List<QualifiedNetworks>> listQueue = getAvailableNetworksList();
// Verify the list has been queued.
assertEquals(1, listQueue.size());
@@ -245,7 +245,7 @@ public class TransportManagerTest extends TelephonyTest {
mTransportManager.getCurrentTransport(ApnSetting.TYPE_IMS));
processAllMessages();
- listQueue = getQueuedNetworksList();
+ listQueue = getAvailableNetworksList();
// Verify the queue is empty.
assertEquals(0, listQueue.size());
diff --git a/tests/telephonytests/src/com/android/internal/telephony/emergency/EmergencyNumberTrackerTest.java b/tests/telephonytests/src/com/android/internal/telephony/emergency/EmergencyNumberTrackerTest.java
index 2aa3f18900..7a637cf1eb 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/emergency/EmergencyNumberTrackerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/emergency/EmergencyNumberTrackerTest.java
@@ -22,8 +22,6 @@ import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import android.os.AsyncResult;
-import android.os.Environment;
-import android.os.ParcelFileDescriptor;
import android.telephony.emergency.EmergencyNumber;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
@@ -41,14 +39,6 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.InputStream;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -60,31 +50,6 @@ import java.util.List;
@TestableLooper.RunWithLooper
public class EmergencyNumberTrackerTest extends TelephonyTest {
- private static final String LOCAL_DOWNLOAD_DIRECTORY = "Download/Emergency_number_db_unit_test";
- private static final String EMERGENCY_NUMBER_DB_OTA_FILE = "eccdata_ota";
- private static final int CONFIG_UNIT_TEST_EMERGENCY_NUMBER_DB_VERSION = 99999;
- private static final String CONFIG_EMERGENCY_NUMBER_ADDRESS = "54321";
- private static final String CONFIG_EMERGENCY_NUMBER_COUNTRY = "us";
- private static final String CONFIG_EMERGENCY_NUMBER_MNC = "";
- private static final int CONFIG_EMERGENCY_NUMBER_SERVICE_CATEGORIES =
- EmergencyNumber.EMERGENCY_SERVICE_CATEGORY_POLICE
- | EmergencyNumber.EMERGENCY_SERVICE_CATEGORY_AMBULANCE
- | EmergencyNumber.EMERGENCY_SERVICE_CATEGORY_FIRE_BRIGADE
- | EmergencyNumber.EMERGENCY_SERVICE_CATEGORY_MARINE_GUARD
- | EmergencyNumber.EMERGENCY_SERVICE_CATEGORY_MOUNTAIN_RESCUE
- | EmergencyNumber.EMERGENCY_SERVICE_CATEGORY_MIEC
- | EmergencyNumber.EMERGENCY_SERVICE_CATEGORY_AIEC;
- private static final ArrayList<String> CONFIG_EMERGENCY_NUMBER_SERVICE_URNS =
- new ArrayList<String>();
- private static final EmergencyNumber CONFIG_EMERGENCY_NUMBER = new EmergencyNumber(
- CONFIG_EMERGENCY_NUMBER_ADDRESS, CONFIG_EMERGENCY_NUMBER_COUNTRY,
- CONFIG_EMERGENCY_NUMBER_MNC, CONFIG_EMERGENCY_NUMBER_SERVICE_CATEGORIES,
- CONFIG_EMERGENCY_NUMBER_SERVICE_URNS,
- EmergencyNumber.EMERGENCY_NUMBER_SOURCE_DATABASE,
- EmergencyNumber.EMERGENCY_CALL_ROUTING_UNKNOWN);
- private static final int OTA_UNIT_TEST_EMERGENCY_NUMBER_DB_VERSION = 999999;
- private static final String OTA_EMERGENCY_NUMBER_ADDRESS = "98765";
-
@Mock
private Phone mPhone2; // mPhone as phone 1 is already defined in TelephonyTest.
@@ -97,8 +62,6 @@ public class EmergencyNumberTrackerTest extends TelephonyTest {
private EmergencyNumber mUsEmergencyNumber;
private String[] mEmergencyNumberPrefixTestSample = {"123", "456"};
- private File mLocalDownloadDirectory;
-
@Before
public void setUp() throws Exception {
logd("EmergencyNumberTrackerTest +Setup!");
@@ -116,10 +79,6 @@ public class EmergencyNumberTrackerTest extends TelephonyTest {
mEmergencyNumberTrackerMock2 = new EmergencyNumberTracker(mPhone2, mSimulatedCommands);
doReturn(mEmergencyNumberTrackerMock2).when(mPhone2).getEmergencyNumberTracker();
mEmergencyNumberTrackerMock.DBG = true;
-
- // Copy an OTA file to the test directory to similate the OTA mechanism
- simulateOtaEmergencyNumberDb(mPhone);
-
processAllMessages();
logd("EmergencyNumberTrackerTest -Setup!");
}
@@ -128,9 +87,6 @@ public class EmergencyNumberTrackerTest extends TelephonyTest {
public void tearDown() throws Exception {
// Set back to single sim mode
setSinglePhone();
- Path target = Paths.get(mLocalDownloadDirectory.getPath(), EMERGENCY_NUMBER_DB_OTA_FILE);
- Files.deleteIfExists(target);
- mLocalDownloadDirectory.delete();
super.tearDown();
}
@@ -169,75 +125,6 @@ public class EmergencyNumberTrackerTest extends TelephonyTest {
processAllMessages();
}
- private void setOtaEmergencyNumberDbFileFolderForTesting(
- EmergencyNumberTracker emergencyNumberTrackerMock, Phone phone) {
- // Override the OTA emergency number database file path for testing
- File file = new File(Environment.getExternalStorageDirectory(), LOCAL_DOWNLOAD_DIRECTORY
- + "/" + EMERGENCY_NUMBER_DB_OTA_FILE);
- try {
- final ParcelFileDescriptor otaParcelFileDescriptor = ParcelFileDescriptor.open(
- file, ParcelFileDescriptor.MODE_READ_ONLY);
- emergencyNumberTrackerMock.obtainMessage(
- EmergencyNumberTracker.EVENT_OVERRIDE_OTA_EMERGENCY_NUMBER_DB_FILE_PATH,
- otaParcelFileDescriptor).sendToTarget();
- logd("Changed emergency number db file folder for testing ");
- } catch (FileNotFoundException e) {
- logd("Failed to open emergency number db file folder for testing " + e.toString());
- }
- processAllMessages();
- }
-
- private void resetOtaEmergencyNumberDbFileFolderForTesting(
- EmergencyNumberTracker emergencyNumberTrackerMock) {
- emergencyNumberTrackerMock.obtainMessage(
- EmergencyNumberTracker.EVENT_OVERRIDE_OTA_EMERGENCY_NUMBER_DB_FILE_PATH, null)
- .sendToTarget();
- processAllMessages();
- }
-
- private void sendOtaEmergencyNumberDb(EmergencyNumberTracker emergencyNumberTrackerMock) {
- emergencyNumberTrackerMock.obtainMessage(
- EmergencyNumberTracker.EVENT_UPDATE_OTA_EMERGENCY_NUMBER_DB).sendToTarget();
- processAllMessages();
- }
-
- /**
- * Copy an OTA file to the test directory to similate the OTA mechanism.
- *
- * Version: 999999
- * Number: US, 98765, POLICE | AMBULANCE | FIRE
- */
- private void simulateOtaEmergencyNumberDb(Phone phone) {
- try {
- mLocalDownloadDirectory = new File(
- Environment.getExternalStorageDirectory(), LOCAL_DOWNLOAD_DIRECTORY);
- mLocalDownloadDirectory.mkdir();
- final Path target = Paths.get(
- mLocalDownloadDirectory.getPath(), EMERGENCY_NUMBER_DB_OTA_FILE);
- Files.deleteIfExists(target);
- final InputStream source = new BufferedInputStream(
- phone.getContext().getAssets().open(EMERGENCY_NUMBER_DB_OTA_FILE));
- Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
- logd("Copied test OTA database file to " + target);
- } catch (Exception e) {
- logd("Unable to copy downloaded file " + e);
- }
- }
-
- private boolean hasDbEmergencyNumber(EmergencyNumber number, List<EmergencyNumber> list) {
- return list.contains(number);
- }
-
- private boolean hasDbEmergencyNumber(String number, List<EmergencyNumber> list) {
- boolean foundDbNumber = false;
- for (EmergencyNumber num : list) {
- if (num.getNumber().equals(number)) {
- foundDbNumber = true;
- }
- }
- return foundDbNumber;
- }
-
private void setDsdsPhones() throws Exception {
mPhones = new Phone[] {mPhone, mPhone2};
replaceInstance(PhoneFactory.class, "sPhones", null, mPhones);
@@ -258,16 +145,10 @@ public class EmergencyNumberTrackerTest extends TelephonyTest {
@Test
public void testUpdateEmergencyCountryIso() throws Exception {
sendEmergencyNumberPrefix(mEmergencyNumberTrackerMock);
-
mEmergencyNumberTrackerMock.updateEmergencyNumberDatabaseCountryChange("us");
processAllMessages();
- assertTrue(mEmergencyNumberTrackerMock.getEmergencyCountryIso().equals("us"));
- assertTrue(mEmergencyNumberTrackerMock.getLastKnownEmergencyCountryIso().equals("us"));
- mEmergencyNumberTrackerMock.updateEmergencyNumberDatabaseCountryChange("");
- processAllMessages();
- assertTrue(mEmergencyNumberTrackerMock.getEmergencyCountryIso().equals(""));
- assertTrue(mEmergencyNumberTrackerMock.getLastKnownEmergencyCountryIso().equals("us"));
+ assertTrue(mEmergencyNumberTrackerMock.getEmergencyCountryIso().equals("us"));
}
@Test
@@ -275,20 +156,11 @@ public class EmergencyNumberTrackerTest extends TelephonyTest {
setDsdsPhones();
sendEmergencyNumberPrefix(mEmergencyNumberTrackerMock);
sendEmergencyNumberPrefix(mEmergencyNumberTrackerMock2);
-
mEmergencyNumberTrackerMock.updateEmergencyCountryIsoAllPhones("jp");
processAllMessages();
- assertTrue(mEmergencyNumberTrackerMock.getEmergencyCountryIso().equals("jp"));
- assertTrue(mEmergencyNumberTrackerMock.getLastKnownEmergencyCountryIso().equals("jp"));
- assertTrue(mEmergencyNumberTrackerMock2.getEmergencyCountryIso().equals("jp"));
- assertTrue(mEmergencyNumberTrackerMock2.getLastKnownEmergencyCountryIso().equals("jp"));
- mEmergencyNumberTrackerMock.updateEmergencyCountryIsoAllPhones("");
- processAllMessages();
- assertTrue(mEmergencyNumberTrackerMock.getEmergencyCountryIso().equals(""));
- assertTrue(mEmergencyNumberTrackerMock.getLastKnownEmergencyCountryIso().equals("jp"));
+ assertTrue(mEmergencyNumberTrackerMock.getEmergencyCountryIso().equals("jp"));
assertTrue(mEmergencyNumberTrackerMock2.getEmergencyCountryIso().equals("jp"));
- assertTrue(mEmergencyNumberTrackerMock2.getLastKnownEmergencyCountryIso().equals("jp"));
}
@Test
@@ -354,53 +226,15 @@ public class EmergencyNumberTrackerTest extends TelephonyTest {
sendEmergencyNumberPrefix(mEmergencyNumberTrackerMock);
mEmergencyNumberTrackerMock.updateEmergencyCountryIsoAllPhones("us");
processAllMessages();
- assertTrue(hasDbEmergencyNumber(CONFIG_EMERGENCY_NUMBER,
- mEmergencyNumberTrackerMock.getEmergencyNumberList()));
- }
-
- /**
- * Test OTA Emergency Number Database Update Status.
- */
- @Test
- public void testOtaEmergencyNumberDatabase() {
- // Set up the Hal version as 1.4 to apply emergency number database
- doReturn(new HalVersion(1, 4)).when(mPhone).getHalVersion();
-
- sendEmergencyNumberPrefix(mEmergencyNumberTrackerMock);
- mEmergencyNumberTrackerMock.updateEmergencyCountryIsoAllPhones("");
- processAllMessages();
-
- // Emergency Number Db is cached per country, given the country is empty at this time,
- // we should not expect any db number there.
- assertFalse(hasDbEmergencyNumber(CONFIG_EMERGENCY_NUMBER,
- mEmergencyNumberTrackerMock.getEmergencyNumberList()));
- // Set up the OTA database file folder as sdcard for testing purposes
- setOtaEmergencyNumberDbFileFolderForTesting(mEmergencyNumberTrackerMock, mPhone);
- // Notify EmergerncyNumberTracker OTA database is installed.
- sendOtaEmergencyNumberDb(mEmergencyNumberTrackerMock);
- processAllMessages();
-
- assertEquals(OTA_UNIT_TEST_EMERGENCY_NUMBER_DB_VERSION,
- mEmergencyNumberTrackerMock.getEmergencyNumberDbVersion());
-
- // Emergency Number Db is cached per country, given the country is empty at this time,
- // we should not expect any db number there.
- assertFalse(hasDbEmergencyNumber(OTA_EMERGENCY_NUMBER_ADDRESS,
- mEmergencyNumberTrackerMock.getEmergencyNumberList()));
-
- mEmergencyNumberTrackerMock.updateEmergencyCountryIsoAllPhones("us");
- processAllMessages();
- assertEquals(OTA_UNIT_TEST_EMERGENCY_NUMBER_DB_VERSION,
- mEmergencyNumberTrackerMock.getEmergencyNumberDbVersion());
-
- // Emergency Number Db is cached per country, given the country is 'us' at this time,
- // we should expect the 'us' db number there.
- assertTrue(hasDbEmergencyNumber(OTA_EMERGENCY_NUMBER_ADDRESS,
- mEmergencyNumberTrackerMock.getEmergencyNumberList()));
-
- // Reset the OTA database file to default after testing completion
- resetOtaEmergencyNumberDbFileFolderForTesting(mEmergencyNumberTrackerMock);
+ boolean hasDatabaseNumber = false;
+ for (EmergencyNumber number : mEmergencyNumberTrackerMock.getEmergencyNumberList()) {
+ if (number.isFromSources(EmergencyNumber.EMERGENCY_NUMBER_SOURCE_DATABASE)) {
+ hasDatabaseNumber = true;
+ break;
+ }
+ }
+ assertTrue(hasDatabaseNumber);
}
@Test
diff --git a/tests/telephonytests/src/com/android/internal/telephony/euicc/EuiccControllerTest.java b/tests/telephonytests/src/com/android/internal/telephony/euicc/EuiccControllerTest.java
index 43de6f64b8..7c33f34e6e 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/euicc/EuiccControllerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/euicc/EuiccControllerTest.java
@@ -1290,8 +1290,7 @@ public class EuiccControllerTest extends TelephonyTest {
private void callGetDownloadableSubscriptionMetadata(DownloadableSubscription subscription,
boolean complete, GetDownloadableSubscriptionMetadataResult result) {
prepareGetDownloadableSubscriptionMetadataCall(complete, result);
- PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(),
- PendingIntent.FLAG_IMMUTABLE);
+ PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(), 0);
mController.getDownloadableSubscriptionMetadata(0, subscription, PACKAGE_NAME,
resultCallback);
}
@@ -1312,16 +1311,14 @@ public class EuiccControllerTest extends TelephonyTest {
}
}).when(mMockConnector).getDefaultDownloadableSubscriptionList(anyInt(), anyBoolean(),
any());
- PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(),
- PendingIntent.FLAG_IMMUTABLE);
+ PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(), 0);
mController.getDefaultDownloadableSubscriptionList(CARD_ID, PACKAGE_NAME, resultCallback);
}
private void callDownloadSubscription(DownloadableSubscription subscription,
boolean switchAfterDownload, final boolean complete, final int result,
final int resolvableError, String callingPackage) {
- PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(),
- PendingIntent.FLAG_IMMUTABLE);
+ PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(), 0);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Exception {
@@ -1348,8 +1345,7 @@ public class EuiccControllerTest extends TelephonyTest {
private void callDeleteSubscription(int subscriptionId, String iccid, final boolean complete,
final int result, String callingPackage) {
- PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(),
- PendingIntent.FLAG_IMMUTABLE);
+ PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(), 0);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Exception {
@@ -1368,8 +1364,7 @@ public class EuiccControllerTest extends TelephonyTest {
private void callSwitchToSubscription(int subscriptionId, String iccid, final boolean complete,
final int result, String callingPackage) {
- PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(),
- PendingIntent.FLAG_IMMUTABLE);
+ PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(), 0);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Exception {
@@ -1388,8 +1383,7 @@ public class EuiccControllerTest extends TelephonyTest {
private void callUpdateSubscriptionNickname(int subscriptionId, String iccid, String nickname,
final boolean complete, final int result, String callingPackage) {
- PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(),
- PendingIntent.FLAG_IMMUTABLE);
+ PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(), 0);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Exception {
@@ -1409,8 +1403,7 @@ public class EuiccControllerTest extends TelephonyTest {
}
private void callEraseSubscriptions(final boolean complete, final int result) {
- PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(),
- PendingIntent.FLAG_IMMUTABLE);
+ PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(), 0);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Exception {
@@ -1428,8 +1421,7 @@ public class EuiccControllerTest extends TelephonyTest {
}
private void callEraseSubscriptionsWithOptions(final boolean complete, final int result) {
- PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(),
- PendingIntent.FLAG_IMMUTABLE);
+ PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(), 0);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Exception {
@@ -1448,8 +1440,7 @@ public class EuiccControllerTest extends TelephonyTest {
}
private void callRetainSubscriptionsForFactoryReset(final boolean complete, final int result) {
- PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(),
- PendingIntent.FLAG_IMMUTABLE);
+ PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(), 0);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Exception {
diff --git a/tests/telephonytests/src/com/android/internal/telephony/gsm/GsmInboundSmsHandlerTest.java b/tests/telephonytests/src/com/android/internal/telephony/gsm/GsmInboundSmsHandlerTest.java
index 298c3e4daa..552b548174 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/gsm/GsmInboundSmsHandlerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/gsm/GsmInboundSmsHandlerTest.java
@@ -20,13 +20,13 @@ import static com.android.internal.telephony.TelephonyTestUtils.waitForMs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyLong;
-import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.nullable;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doReturn;
@@ -34,10 +34,7 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import android.app.Notification;
-import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
@@ -63,10 +60,12 @@ import com.android.internal.telephony.InboundSmsHandler;
import com.android.internal.telephony.InboundSmsTracker;
import com.android.internal.telephony.PhoneConstants;
import com.android.internal.telephony.SmsBroadcastUndelivered;
+import com.android.internal.telephony.SmsConstants;
import com.android.internal.telephony.SmsHeader;
import com.android.internal.telephony.SmsStorageMonitor;
import com.android.internal.telephony.TelephonyTest;
import com.android.internal.telephony.cdma.CdmaInboundSmsHandler;
+import com.android.internal.util.HexDump;
import com.android.internal.util.IState;
import com.android.internal.util.StateMachine;
@@ -76,13 +75,9 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.stubbing.Answer;
-import org.mockito.verification.VerificationMode;
import java.lang.reflect.Method;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
@RunWith(AndroidTestingRunner.class)
@@ -97,16 +92,16 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
@Mock
private SmsHeader mSmsHeader;
private InboundSmsTracker mInboundSmsTracker;
- private InboundSmsTracker mInboundSmsTrackerSub1;
private InboundSmsTracker mInboundSmsTrackerPart1;
private InboundSmsTracker mInboundSmsTrackerPart2;
@Mock
- private CdmaInboundSmsHandler mCdmaInboundSmsHandler;
+ private InboundSmsTracker mMockInboundSmsTracker;
+ private ContentValues mInboundSmsTrackerCV;
@Mock
- private InboundSmsHandler.SmsFilter mSmsFilter;
+ private InboundSmsTracker mMockInboundSmsTrackerSub1;
+ private ContentValues mInboundSmsTrackerCVSub1;
@Mock
- private InboundSmsHandler.SmsFilter mSmsFilter2;
- private List<InboundSmsHandler.SmsFilter> mSmsFilters;
+ private CdmaInboundSmsHandler mCdmaInboundSmsHandler;
private GsmInboundSmsHandler mGsmInboundSmsHandler;
@@ -135,25 +130,63 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
}
/**
- * This is used only for InboundSmsTracker constructed through Cursor. This should be used only
- * for tests related to SmsBroadcastUndelivered. Also, this adds a second tracker for multisim.
+ * This is used only for InboundSmsTracker constructed through Cursor. For other cases
+ * real objects should be used. This should be used only for tests related to
+ * SmsBroadcastUndelivered.
*/
- private void createInboundSmsTrackerMultiSim() {
- mInboundSmsTrackerSub1 = new InboundSmsTracker(
- mContext,
- mSmsPdu, /* pdu */
- System.currentTimeMillis(), /* timestamp */
- -1, /* destPort */
- false, /* is3gpp2 */
- false, /* is3gpp2WapPdu */
- "1234567890", /* address */
- "1234567890", /* displayAddress */
- mMessageBody, /* messageBody */
- false, /* isClass0 */
- mSubId1,
- InboundSmsHandler.SOURCE_NOT_INJECTED);
-
- doReturn(mInboundSmsTracker).doReturn(mInboundSmsTrackerSub1)
+ private void createMockInboundSmsTracker() {
+ mInboundSmsTrackerCV = new ContentValues();
+ mInboundSmsTrackerCV.put("destination_port", InboundSmsTracker.DEST_PORT_FLAG_NO_PORT);
+ mInboundSmsTrackerCV.put("pdu", HexDump.toHexString(mSmsPdu));
+ mInboundSmsTrackerCV.put("address", "1234567890");
+ mInboundSmsTrackerCV.put("reference_number", 1);
+ mInboundSmsTrackerCV.put("sequence", 1);
+ mInboundSmsTrackerCV.put("count", 1);
+ mInboundSmsTrackerCV.put("date", System.currentTimeMillis());
+ mInboundSmsTrackerCV.put("message_body", mMessageBody);
+ mInboundSmsTrackerCV.put("display_originating_addr", "1234567890");
+ mInboundSmsTrackerCV.put("sub_id", mSubId0);
+
+ doReturn(1).when(mMockInboundSmsTracker).getMessageCount();
+ doReturn(1).when(mMockInboundSmsTracker).getReferenceNumber();
+ doReturn("1234567890").when(mMockInboundSmsTracker).getAddress();
+ doReturn(1).when(mMockInboundSmsTracker).getSequenceNumber();
+ doReturn(1).when(mMockInboundSmsTracker).getIndexOffset();
+ doReturn(-1).when(mMockInboundSmsTracker).getDestPort();
+ doReturn(mMessageBody).when(mMockInboundSmsTracker).getMessageBody();
+ doReturn(mSmsPdu).when(mMockInboundSmsTracker).getPdu();
+ doReturn(mInboundSmsTrackerCV.get("date")).when(mMockInboundSmsTracker).getTimestamp();
+ doReturn(SmsConstants.FORMAT_3GPP).when(mMockInboundSmsTracker).getFormat();
+ doReturn(mInboundSmsTrackerCV).when(mMockInboundSmsTracker).getContentValues();
+ doReturn(mSubId0).when(mMockInboundSmsTracker).getSubId();
+
+ mInboundSmsTrackerCVSub1 = new ContentValues();
+ mInboundSmsTrackerCVSub1.put("destination_port", InboundSmsTracker.DEST_PORT_FLAG_NO_PORT);
+ mInboundSmsTrackerCVSub1.put("pdu", HexDump.toHexString(mSmsPdu));
+ mInboundSmsTrackerCVSub1.put("address", "1234567890");
+ mInboundSmsTrackerCVSub1.put("reference_number", 1);
+ mInboundSmsTrackerCVSub1.put("sequence", 1);
+ mInboundSmsTrackerCVSub1.put("count", 1);
+ mInboundSmsTrackerCVSub1.put("date", System.currentTimeMillis());
+ mInboundSmsTrackerCVSub1.put("message_body", mMessageBody);
+ mInboundSmsTrackerCVSub1.put("display_originating_addr", "1234567890");
+ mInboundSmsTrackerCVSub1.put("sub_id", mSubId1);
+
+ doReturn(1).when(mMockInboundSmsTrackerSub1).getMessageCount();
+ doReturn(1).when(mMockInboundSmsTrackerSub1).getReferenceNumber();
+ doReturn("1234567890").when(mMockInboundSmsTrackerSub1).getAddress();
+ doReturn(1).when(mMockInboundSmsTrackerSub1).getSequenceNumber();
+ doReturn(1).when(mMockInboundSmsTrackerSub1).getIndexOffset();
+ doReturn(-1).when(mMockInboundSmsTrackerSub1).getDestPort();
+ doReturn(mMessageBody).when(mMockInboundSmsTrackerSub1).getMessageBody();
+ doReturn(mSmsPdu).when(mMockInboundSmsTrackerSub1).getPdu();
+ doReturn(mInboundSmsTrackerCVSub1.get("date")).when(mMockInboundSmsTrackerSub1)
+ .getTimestamp();
+ doReturn(SmsConstants.FORMAT_3GPP).when(mMockInboundSmsTrackerSub1).getFormat();
+ doReturn(mInboundSmsTrackerCVSub1).when(mMockInboundSmsTrackerSub1).getContentValues();
+ doReturn(mSubId1).when(mMockInboundSmsTrackerSub1).getSubId();
+
+ doReturn(mMockInboundSmsTracker).doReturn(mMockInboundSmsTrackerSub1)
.when(mTelephonyComponentFactory)
.makeInboundSmsTracker(any(Context.class), nullable(Cursor.class),
anyBoolean());
@@ -187,15 +220,14 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
"1234567890", /* displayAddress */
mMessageBody, /* messageBody */
false, /* isClass0 */
- mSubId0,
- InboundSmsHandler.SOURCE_NOT_INJECTED);
+ mSubId0);
doReturn(mInboundSmsTracker).when(mTelephonyComponentFactory)
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
anyBoolean(), nullable(String.class), nullable(String.class),
- nullable(String.class), anyBoolean(), anyInt(), anyInt());
+ nullable(String.class), anyBoolean(), anyInt());
- createInboundSmsTrackerMultiSim();
+ createMockInboundSmsTracker();
mContentProvider = new FakeSmsContentProvider();
((MockContentResolver)mContext.getContentResolver()).addProvider(
@@ -203,17 +235,8 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
mGsmInboundSmsHandler = GsmInboundSmsHandler.makeInboundSmsHandler(mContext,
mSmsStorageMonitor, mPhone);
- mSmsFilters = new ArrayList<>();
- mSmsFilters.add(mSmsFilter);
- mSmsFilters.add(mSmsFilter2);
- mGsmInboundSmsHandler.setSmsFiltersForTesting(mSmsFilters);
monitorTestableLooper(new TestableLooper(mGsmInboundSmsHandler.getHandler().getLooper()));
-
- doReturn(mGsmInboundSmsHandler).when(mPhone).getInboundSmsHandler(false);
- doReturn(mCdmaInboundSmsHandler).when(mPhone).getInboundSmsHandler(true);
-
processAllMessages();
- logd("setUp: complete");
}
@After
@@ -319,11 +342,8 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
verify(mContext, times(2)).sendBroadcast(any(Intent.class));
assertEquals("IdleState", getCurrentState().getName());
-
- verifySmsFiltersInvoked(times(1));
}
- @FlakyTest // temporarily disabled, see b/182498318
@Test
@MediumTest
public void testNewSmsFromBlockedNumber_noBroadcastsSent() {
@@ -336,126 +356,6 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
verify(mContext, never()).sendBroadcast(any(Intent.class));
assertEquals("IdleState", getCurrentState().getName());
-
- // Filter should still be invoked.
- verifySmsFiltersInvoked(times(1));
- }
-
- @FlakyTest // temporarily disabled, see b/182498318
- @Test
- @MediumTest
- public void testNewSmsWithUserLocked_notificationShown() {
- // user locked
- UserManager userManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
- doReturn(false).when(userManager).isUserUnlocked();
-
- transitionFromStartupToIdle();
-
- sendNewSms();
-
- verify(mContext, never()).sendBroadcast(any(Intent.class));
- assertEquals("IdleState", getCurrentState().getName());
-
- // Filter should be invoked.
- verifySmsFiltersInvoked(times(1));
-
- // New message notification should be shown.
- NotificationManager notificationManager =
- (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
- verify(notificationManager).notify(
- eq(InboundSmsHandler.NOTIFICATION_TAG),
- eq(InboundSmsHandler.NOTIFICATION_ID_NEW_MESSAGE),
- any(Notification.class));
- }
-
- @FlakyTest // temporarily disabled, see b/182498318
- @Test
- @MediumTest
- public void testNewSmsFromBlockedNumberWithUserLocked_noNotificationShown() {
- String blockedNumber = "1234567890";
- mFakeBlockedNumberContentProvider.mBlockedNumbers.add(blockedNumber);
-
- // user locked
- UserManager userManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
- doReturn(false).when(userManager).isUserUnlocked();
-
- transitionFromStartupToIdle();
-
- sendNewSms();
-
- verify(mContext, never()).sendBroadcast(any(Intent.class));
- assertEquals("IdleState", getCurrentState().getName());
-
- // Filter should be invoked.
- verifySmsFiltersInvoked(times(1));
-
- // No new message notification should be shown.
- NotificationManager notificationManager =
- (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
- verify(notificationManager, never()).notify(
- eq(InboundSmsHandler.NOTIFICATION_TAG),
- eq(InboundSmsHandler.NOTIFICATION_ID_NEW_MESSAGE),
- any(Notification.class));
- }
-
- @FlakyTest // temporarily disabled, see b/182498318
- @Test
- @MediumTest
- public void testNewSms_filterInvoked_noBroadcastsSent() {
- // Configure the first filter to drop the SMS.
- when(mSmsFilter.filterSms(any(byte[][].class), anyInt(),
- any(InboundSmsTracker.class), any(InboundSmsHandler.SmsBroadcastReceiver.class),
- anyBoolean(), anyBoolean(), Mockito.<List<InboundSmsHandler.SmsFilter>>any()))
- .thenAnswer((Answer<Boolean>) invocation -> {
- mGsmInboundSmsHandler.sendMessage(InboundSmsHandler.EVENT_BROADCAST_COMPLETE);
- return true;
- });
-
- transitionFromStartupToIdle();
-
- sendNewSms();
-
- verify(mContext, never()).sendBroadcast(any(Intent.class));
- assertEquals("IdleState", getCurrentState().getName());
-
- // verify second filter was never invoked.
- verify(mSmsFilter2, never()).filterSms(any(byte[][].class), anyInt(),
- any(InboundSmsTracker.class), any(InboundSmsHandler.SmsBroadcastReceiver.class),
- anyBoolean(), anyBoolean(), Mockito.<List<InboundSmsHandler.SmsFilter>>any());
- }
-
- @FlakyTest // temporarily disabled, see b/182498318
- @Test
- @MediumTest
- public void testNewSms_filterChaining_noBroadcastsSent() {
- // Have the first filter indicate it matched without completing the flow.
- when(mSmsFilter.filterSms(any(byte[][].class), anyInt(),
- any(InboundSmsTracker.class), any(InboundSmsHandler.SmsBroadcastReceiver.class),
- anyBoolean(), anyBoolean(), Mockito.<List<InboundSmsHandler.SmsFilter>>any()))
- .thenReturn(true);
-
- transitionFromStartupToIdle();
-
- sendNewSms();
-
- verify(mContext, never()).sendBroadcast(any(Intent.class));
- // Now waiting for the first filter to complete.
- assertEquals("WaitingState", getCurrentState().getName());
-
- // Verify the first filter was invoked with the right set of remaining filters.
- verify(mSmsFilter).filterSms(any(byte[][].class), anyInt(),
- any(InboundSmsTracker.class), any(InboundSmsHandler.SmsBroadcastReceiver.class),
- anyBoolean(), anyBoolean(), eq(Collections.singletonList(mSmsFilter2)));
-
- // Verify second filter was never invoked.
- verify(mSmsFilter2, never()).filterSms(any(byte[][].class), anyInt(),
- any(InboundSmsTracker.class), any(InboundSmsHandler.SmsBroadcastReceiver.class),
- anyBoolean(), anyBoolean(), Mockito.<List<InboundSmsHandler.SmsFilter>>any());
-
- // Clean up by completing the broadcast, as an asynchronous filter must do.
- mGsmInboundSmsHandler.sendMessage(InboundSmsHandler.EVENT_BROADCAST_COMPLETE);
- processAllMessages();
- assertEquals("IdleState", getCurrentState().getName());
}
private void verifyDataSmsIntentBroadcasts(int numPastBroadcasts) {
@@ -464,10 +364,9 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
intentArgumentCaptor.capture());
assertEquals(Telephony.Sms.Intents.DATA_SMS_RECEIVED_ACTION,
intentArgumentCaptor.getAllValues().get(numPastBroadcasts).getAction());
- // TODO mock messageId correctly in InboundSmsTracker
- /* assertNotEquals(0L,
+ assertNotEquals(0L,
intentArgumentCaptor.getAllValues().get(numPastBroadcasts)
- .getLongExtra("messageId", 0L)); */
+ .getLongExtra("messageId", 0L));
assertEquals("WaitingState", getCurrentState().getName());
mContextFixture.sendBroadcastToOrderedBroadcastReceivers();
@@ -476,7 +375,6 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
assertEquals("IdleState", getCurrentState().getName());
}
- @FlakyTest // temporarily disabled, see b/182498318
@Test
@MediumTest
public void testClass0Sms() {
@@ -493,22 +391,19 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
"1234567890", /* displayAddress */
mMessageBody, /* messageBody */
true, /* isClass0 */
- mSubId0,
- InboundSmsHandler.SOURCE_NOT_INJECTED);
+ mSubId0);
doReturn(mInboundSmsTracker).when(mTelephonyComponentFactory)
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
anyBoolean(), nullable(String.class), nullable(String.class),
- nullable(String.class), anyBoolean(), anyInt(), anyInt());
+ nullable(String.class), anyBoolean(), anyInt());
mGsmInboundSmsHandler.sendMessage(InboundSmsHandler.EVENT_BROADCAST_SMS,
mInboundSmsTracker);
processAllMessages();
verifySmsIntentBroadcasts(0, true /* allowBgActivityStarts */);
- verifySmsFiltersInvoked(times(1));
}
- @FlakyTest // temporarily disabled, see b/182498318
@Test
@MediumTest
public void testBroadcastSms() {
@@ -525,13 +420,12 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
"1234567890", /* displayAddress */
mMessageBody, /* messageBody */
false, /* isClass0 */
- mSubId0,
- InboundSmsHandler.SOURCE_NOT_INJECTED));
+ mSubId0));
doReturn(mInboundSmsTracker).when(mTelephonyComponentFactory)
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
anyBoolean(), nullable(String.class), nullable(String.class),
- nullable(String.class), anyBoolean(), anyInt(), anyInt());
+ nullable(String.class), anyBoolean(), anyInt());
doReturn(2131L).when(mInboundSmsTracker).getMessageId();
mGsmInboundSmsHandler.sendMessage(InboundSmsHandler.EVENT_BROADCAST_SMS,
mInboundSmsTracker);
@@ -545,8 +439,6 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
processAllMessages();
verifyDataSmsIntentBroadcasts(1);
-
- verifySmsFiltersInvoked(times(2));
}
@FlakyTest
@@ -568,8 +460,6 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
verify(mContext, times(2)).sendBroadcast(any(Intent.class));
assertEquals("IdleState", getCurrentState().getName());
-
- verifySmsFiltersInvoked(times(1));
}
private void prepareMultiPartSms(boolean is3gpp2WapPush) {
@@ -588,8 +478,7 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
is3gpp2WapPush, /* is3gpp2WapPdu */
mMessageBodyPart1, /* messageBody */
false, /* isClass0 */
- mSubId0,
- InboundSmsHandler.SOURCE_NOT_INJECTED);
+ mSubId0);
// Part 2
mInboundSmsTrackerPart2 = new InboundSmsTracker(
@@ -606,11 +495,9 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
is3gpp2WapPush, /* is3gpp2WapPdu */
mMessageBodyPart2, /* messageBody */
false, /* isClass0 */
- mSubId0,
- InboundSmsHandler.SOURCE_NOT_INJECTED);
+ mSubId0);
}
- @FlakyTest // temporarily disabled, see b/182498318
@Test
@MediumTest
public void testMultiPartSmsWithIncompleteWAP() {
@@ -632,8 +519,7 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
nullable(String.class), nullable(String.class), anyInt(), anyInt(),
- anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt(),
- anyInt());
+ anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt());
sendNewSms();
// State machine should go back to idle and wait for second part
@@ -645,8 +531,7 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
nullable(String.class), nullable(String.class), anyInt(), anyInt(),
- anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt(),
- anyInt());
+ anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt());
sendNewSms();
// State machine should go back to idle and wait for second part
@@ -654,7 +539,6 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
// verify no broadcast sent.
verify(mContext, times(0)).sendBroadcast(any(Intent.class));
- verifySmsFiltersInvoked(never());
// additional copy of part 1 of non-3gpp2wap
prepareMultiPartSms(false);
@@ -662,8 +546,7 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
nullable(String.class), nullable(String.class), anyInt(), anyInt(),
- anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt(),
- anyInt());
+ anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt());
sendNewSms();
// verify broadcast intents
@@ -672,8 +555,6 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
// verify there are three segments in the db and only one of them is not marked as deleted.
assertEquals(3, mContentProvider.getNumRows());
assertEquals(1, mContentProvider.query(sRawUri, null, "deleted=0", null, null).getCount());
-
- verifySmsFiltersInvoked(times(1));
}
@FlakyTest
@@ -692,8 +573,7 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
nullable(String.class), nullable(String.class), anyInt(), anyInt(),
- anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt(),
- anyInt());
+ anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt());
sendNewSms();
// State machine should go back to idle and wait for second part
@@ -703,13 +583,11 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
nullable(String.class), nullable(String.class), anyInt(), anyInt(),
- anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt(),
- anyInt());
+ anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt());
sendNewSms();
// verify broadcast intents
verifySmsIntentBroadcasts(0);
- verifySmsFiltersInvoked(times(1));
// if an additional copy of one of the segments above is received, it should not be kept in
// the db and should not be combined with any subsequent messages received from the same
@@ -720,13 +598,11 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
nullable(String.class), nullable(String.class), anyInt(), anyInt(),
- anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt(),
- anyInt());
+ anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt());
sendNewSms();
// verify no additional broadcasts sent
verify(mContext, times(2)).sendBroadcast(any(Intent.class));
- verifySmsFiltersInvoked(times(1));
// part 1 of new sms recieved from same sender with same parameters, just different
// timestamps, should not be combined with the additional part 2 received above
@@ -739,18 +615,15 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
nullable(String.class), nullable(String.class), anyInt(), anyInt(),
- anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt(),
- anyInt());
+ anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt());
sendNewSms();
// verify no additional broadcasts sent
verify(mContext, times(2)).sendBroadcast(any(Intent.class));
- verifySmsFiltersInvoked(times(1));
assertEquals("IdleState", getCurrentState().getName());
}
- @FlakyTest // temporarily disabled, see b/182498318
@Test
@MediumTest
public void testMultiPartIncompleteSms() {
@@ -777,8 +650,7 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
false, /* is3gpp2WapPdu */
mMessageBodyPart2, /* messageBody */
false, /* isClass0 */
- mSubId0,
- InboundSmsHandler.SOURCE_NOT_INJECTED);
+ mSubId0);
mSmsHeader.concatRef = new SmsHeader.ConcatRef();
doReturn(mSmsHeader).when(mGsmSmsMessage).getUserDataHeader();
@@ -787,8 +659,7 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
nullable(String.class), nullable(String.class), anyInt(), anyInt(),
- anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt(),
- anyInt());
+ anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt());
sendNewSms();
// State machine should go back to idle and wait for second part
@@ -798,8 +669,7 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
nullable(String.class), nullable(String.class), anyInt(), anyInt(),
- anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt(),
- anyInt());
+ anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt());
sendNewSms();
// verify no broadcasts sent
@@ -812,10 +682,8 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
assertEquals(mMessageBodyPart2, c.getString(c.getColumnIndex("message_body")));
// State machine should go back to idle
assertEquals("IdleState", getCurrentState().getName());
- verifySmsFiltersInvoked(never());
}
- @FlakyTest // temporarily disabled, see b/182498318
@Test
@MediumTest
public void testMultiPartSmsWithInvalidSeqNumber() {
@@ -831,8 +699,7 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
nullable(String.class), nullable(String.class), anyInt(), anyInt(),
- anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt(),
- anyInt());
+ anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt());
sendNewSms();
// verify the message is stored in the raw table
@@ -857,25 +724,21 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
false, /* is3gpp2WapPdu */
mMessageBodyPart2, /* messageBody */
false, /* isClass0 */
- mSubId0,
- InboundSmsHandler.SOURCE_NOT_INJECTED);
+ mSubId0);
doReturn(mInboundSmsTrackerPart2).when(mTelephonyComponentFactory)
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
nullable(String.class), nullable(String.class), anyInt(), anyInt(),
- anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt(),
- anyInt());
+ anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt());
sendNewSms();
// verify no broadcasts sent
verify(mContext, never()).sendBroadcast(any(Intent.class));
// State machine should go back to idle
assertEquals("IdleState", getCurrentState().getName());
- verifySmsFiltersInvoked(never());
}
- @FlakyTest // temporarily disabled, see b/182498318
@Test
@MediumTest
public void testMultipartSmsFromBlockedNumber_noBroadcastsSent() {
@@ -892,8 +755,7 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
nullable(String.class), nullable(String.class), anyInt(), anyInt(),
- anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt(),
- anyInt());
+ anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt());
sendNewSms();
@@ -904,17 +766,13 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
nullable(String.class), nullable(String.class), anyInt(), anyInt(),
- anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt(),
- anyInt());
+ anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt());
sendNewSms();
verify(mContext, never()).sendBroadcast(any(Intent.class));
assertEquals("IdleState", getCurrentState().getName());
- // Filter should still be invoked.
- verifySmsFiltersInvoked(times(1));
}
- @FlakyTest // temporarily disabled, see b/182498318
@Test
@MediumTest
public void testMultipartSmsFromBlockedEmail_noBroadcastsSent() {
@@ -939,8 +797,7 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
false, /* is3gpp2WapPdu */
mMessageBodyPart1, /* messageBody */
false, /* isClass0 */
- mSubId0,
- InboundSmsHandler.SOURCE_NOT_INJECTED);
+ mSubId0);
mSmsHeader.concatRef = new SmsHeader.ConcatRef();
doReturn(mSmsHeader).when(mGsmSmsMessage).getUserDataHeader();
@@ -948,8 +805,7 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
nullable(String.class), nullable(String.class), anyInt(), anyInt(),
- anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt(),
- anyInt());
+ anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt());
sendNewSms();
@@ -960,93 +816,22 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
nullable(String.class), nullable(String.class), anyInt(), anyInt(),
- anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt(),
- anyInt());
+ anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt());
sendNewSms();
verify(mContext, never()).sendBroadcast(any(Intent.class));
assertEquals("IdleState", getCurrentState().getName());
- // Filter should still be invoked.
- verifySmsFiltersInvoked(times(1));
}
- @FlakyTest // temporarily disabled, see b/182498318
- @Test
- @MediumTest
- public void testMultipartSms_filterInvoked_noBroadcastsSent() {
- // Configure the first filter to drop the SMS.
- when(mSmsFilter.filterSms(any(byte[][].class), anyInt(),
- any(InboundSmsTracker.class), any(InboundSmsHandler.SmsBroadcastReceiver.class),
- anyBoolean(), anyBoolean(), Mockito.<List<InboundSmsHandler.SmsFilter>>any()))
- .thenAnswer((Answer<Boolean>) invocation -> {
- mGsmInboundSmsHandler.sendMessage(InboundSmsHandler.EVENT_BROADCAST_COMPLETE);
- return true;
- });
-
- transitionFromStartupToIdle();
-
- // prepare SMS part 1 and part 2
- prepareMultiPartSms(false);
-
- mSmsHeader.concatRef = new SmsHeader.ConcatRef();
- doReturn(mSmsHeader).when(mGsmSmsMessage).getUserDataHeader();
-
- doReturn(mInboundSmsTrackerPart1).when(mTelephonyComponentFactory)
- .makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
- anyInt(), anyBoolean(),
- nullable(String.class), nullable(String.class), anyInt(), anyInt(),
- anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt(),
- anyInt());
- sendNewSms();
-
- // State machine should go back to idle and wait for second part
- assertEquals("IdleState", getCurrentState().getName());
-
- doReturn(mInboundSmsTrackerPart2).when(mTelephonyComponentFactory)
- .makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
- anyInt(), anyBoolean(),
- nullable(String.class), nullable(String.class), anyInt(), anyInt(),
- anyInt(), anyBoolean(), nullable(String.class), anyBoolean(), anyInt(),
- anyInt());
- sendNewSms();
-
- // verify no broadcasts sent
- verify(mContext, never()).sendBroadcast(any(Intent.class));
- assertEquals("IdleState", getCurrentState().getName());
-
- // verify second filter was never invoked.
- verify(mSmsFilter2, never()).filterSms(any(byte[][].class), anyInt(),
- any(InboundSmsTracker.class), any(InboundSmsHandler.SmsBroadcastReceiver.class),
- anyBoolean(), anyBoolean(), Mockito.<List<InboundSmsHandler.SmsFilter>>any());
- }
-
- @FlakyTest // temporarily disabled, see b/182498318
@Test
@MediumTest
public void testBroadcastUndeliveredUserLocked() throws Exception {
replaceInstance(SmsBroadcastUndelivered.class, "instance", null, null);
-
- mInboundSmsTracker = new InboundSmsTracker(
- mContext,
- mSmsPdu, /* pdu */
- System.currentTimeMillis(), /* timestamp */
- 0, /* destPort */
- false, /* is3gpp2 */
- false, /* is3gpp2WapPdu */
- "1234567890", /* address */
- "1234567890", /* displayAddress */
- mMessageBody, /* messageBody */
- false, /* isClass0 */
- mSubId0,
- InboundSmsHandler.SOURCE_NOT_INJECTED);
-
- doReturn(mInboundSmsTracker)
- .when(mTelephonyComponentFactory)
- .makeInboundSmsTracker(any(Context.class), nullable(Cursor.class),
- anyBoolean());
+ doReturn(0).when(mMockInboundSmsTracker).getDestPort();
+ doReturn(2131L).when(mMockInboundSmsTracker).getMessageId();
// add a fake entry to db
- mContentProvider.insert(sRawUri, mInboundSmsTracker.getContentValues());
+ mContentProvider.insert(sRawUri, mMockInboundSmsTracker.getContentValues());
// user locked
UserManager userManager = (UserManager)mContext.getSystemService(Context.USER_SERVICE);
@@ -1075,35 +860,17 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
processAllMessages();
verifyDataSmsIntentBroadcasts(1);
- verifySmsFiltersInvoked(times(1));
}
- @FlakyTest // temporarily disabled, see b/182498318
@Test
@MediumTest
public void testBroadcastUndeliveredUserUnlocked() throws Exception {
replaceInstance(SmsBroadcastUndelivered.class, "instance", null, null);
- mInboundSmsTracker = new InboundSmsTracker(
- mContext,
- mSmsPdu, /* pdu */
- System.currentTimeMillis(), /* timestamp */
- 0, /* destPort */
- false, /* is3gpp2 */
- false, /* is3gpp2WapPdu */
- "1234567890", /* address */
- "1234567890", /* displayAddress */
- mMessageBody, /* messageBody */
- false, /* isClass0 */
- mSubId0,
- InboundSmsHandler.SOURCE_NOT_INJECTED);
-
- doReturn(mInboundSmsTracker)
- .when(mTelephonyComponentFactory)
- .makeInboundSmsTracker(any(Context.class), nullable(Cursor.class),
- anyBoolean());
+ doReturn(0).when(mMockInboundSmsTracker).getDestPort();
+ doReturn(2131L).when(mMockInboundSmsTracker).getMessageId();
// add a fake entry to db
- mContentProvider.insert(sRawUri, mInboundSmsTracker.getContentValues());
+ mContentProvider.insert(sRawUri, mMockInboundSmsTracker.getContentValues());
SmsBroadcastUndelivered.initialize(mContext, mGsmInboundSmsHandler, mCdmaInboundSmsHandler);
@@ -1113,10 +880,8 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
// user is unlocked; intent should be broadcast right away
verifyDataSmsIntentBroadcasts(0);
- verifySmsFiltersInvoked(times(1));
}
- @FlakyTest // temporarily disabled, see b/182498318
@Test
@MediumTest
public void testBroadcastUndeliveredDeleted() throws Exception {
@@ -1133,13 +898,12 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
"1234567890", /* displayAddress */
mMessageBody, /* messageBody */
false, /* isClass0 */
- mSubId0,
- InboundSmsHandler.SOURCE_NOT_INJECTED);
+ mSubId0);
doReturn(mInboundSmsTracker).when(mTelephonyComponentFactory)
.makeInboundSmsTracker(any(Context.class), nullable(byte[].class), anyLong(),
anyInt(), anyBoolean(),
anyBoolean(), nullable(String.class), nullable(String.class),
- nullable(String.class), anyBoolean(), anyInt(), anyInt());
+ nullable(String.class), anyBoolean(), anyInt());
//add a fake entry to db
ContentValues rawSms = new ContentValues();
@@ -1154,7 +918,7 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
verify(mContext, times(1)).sendBroadcast(any(Intent.class));
assertEquals("IdleState", getCurrentState().getName());
- verifySmsFiltersInvoked(never());
+
}
@FlakyTest
@@ -1181,18 +945,16 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
processAllMessages();
verifySmsIntentBroadcasts(0);
- verifySmsFiltersInvoked(times(1));
}
- @FlakyTest // temporarily disabled, see b/182498318
@Test
@MediumTest
public void testBroadcastUndeliveredMultiSim() throws Exception {
replaceInstance(SmsBroadcastUndelivered.class, "instance", null, null);
// add SMSs from different subs to db
- mContentProvider.insert(sRawUri, mInboundSmsTracker.getContentValues());
- mContentProvider.insert(sRawUri, mInboundSmsTrackerSub1.getContentValues());
+ mContentProvider.insert(sRawUri, mMockInboundSmsTracker.getContentValues());
+ mContentProvider.insert(sRawUri, mMockInboundSmsTrackerSub1.getContentValues());
SmsBroadcastUndelivered.initialize(mContext, mGsmInboundSmsHandler, mCdmaInboundSmsHandler);
// wait for ScanRawTableThread
@@ -1201,47 +963,5 @@ public class GsmInboundSmsHandlerTest extends TelephonyTest {
verifySmsIntentBroadcasts(0, mSubId0, true);
verifySmsIntentBroadcasts(2, mSubId1, false);
- verifySmsFiltersInvoked(times(2));
- }
-
- private void verifySmsFiltersInvoked(VerificationMode verificationMode) {
- verify(mSmsFilter, verificationMode).filterSms(any(byte[][].class), anyInt(),
- any(InboundSmsTracker.class), any(InboundSmsHandler.SmsBroadcastReceiver.class),
- anyBoolean(), anyBoolean(), Mockito.<List<InboundSmsHandler.SmsFilter>>any());
- verify(mSmsFilter2, verificationMode).filterSms(any(byte[][].class), anyInt(),
- any(InboundSmsTracker.class), any(InboundSmsHandler.SmsBroadcastReceiver.class),
- anyBoolean(), anyBoolean(), Mockito.<List<InboundSmsHandler.SmsFilter>>any());
- }
-
- @Test
- @MediumTest
- public void testBroadcastTimeout() {
- InboundSmsHandler.sTimeoutDurationMillis = 100;
- transitionFromStartupToIdle();
-
- // send new SMS to state machine and verify that triggers SMS_DELIVER_ACTION
- sendNewSms();
-
- ArgumentCaptor<Intent> intentArgumentCaptor = ArgumentCaptor.forClass(Intent.class);
- verify(mContext).sendBroadcast(intentArgumentCaptor.capture());
- Intent intent = intentArgumentCaptor.getAllValues().get(0);
- assertEquals(Telephony.Sms.Intents.SMS_DELIVER_ACTION, intent.getAction());
- assertEquals("WaitingState", getCurrentState().getName());
-
- // don't send broadcast back to InboundSmsHandler, instead wait for timeout
- waitForMs(300);
- processAllMessages();
-
- intentArgumentCaptor = ArgumentCaptor.forClass(Intent.class);
- verify(mContext, times(2)).sendBroadcast(intentArgumentCaptor.capture());
- intent = intentArgumentCaptor.getAllValues().get(1);
- assertEquals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION, intent.getAction());
-
- // don't send broadcast back to InboundSmsHandler, instead wait for timeout
- waitForMs(300);
- processAllMessages();
-
- assertEquals("IdleState", getCurrentState().getName());
-
}
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/gsm/GsmMmiCodeTest.java b/tests/telephonytests/src/com/android/internal/telephony/gsm/GsmMmiCodeTest.java
deleted file mode 100644
index ee4f6e5a26..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/gsm/GsmMmiCodeTest.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.internal.telephony.gsm;
-
-import static junit.framework.Assert.fail;
-
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.Mockito.doReturn;
-
-import android.os.PersistableBundle;
-import android.telephony.CarrierConfigManager;
-import android.testing.AndroidTestingRunner;
-import android.testing.TestableLooper;
-
-import com.android.internal.telephony.GsmCdmaPhone;
-import com.android.internal.telephony.PhoneConstants;
-import com.android.internal.telephony.TelephonyTest;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.concurrent.Executor;
-
-/**
- * Unit tests for the {@link GsmMmiCodeTest}.
- */
-@RunWith(AndroidTestingRunner.class)
-@TestableLooper.RunWithLooper
-public class GsmMmiCodeTest extends TelephonyTest {
- private static final String TEST_DIAL_STRING_SERVICE_CODE = "*67911";
- private static final String TEST_DIAL_STRING_NO_SERVICE_CODE = "*767911";
- private static final String TEST_DIAL_STRING_NON_EMERGENCY_NUMBER = "11976";
- private GsmMmiCode mGsmMmiCode;
- private GsmCdmaPhone mGsmCdmaPhoneUT;
-
- private Executor mExecutor = new Executor() {
- @Override
- public void execute(Runnable r) {
- r.run();
- }
- };
-
- @Before
- public void setUp() throws Exception {
- super.setUp(getClass().getSimpleName());
- doReturn(mExecutor).when(mContext).getMainExecutor();
- mGsmCdmaPhoneUT = new GsmCdmaPhone(mContext, mSimulatedCommands, mNotifier, true, 0,
- PhoneConstants.PHONE_TYPE_GSM, mTelephonyComponentFactory, (c, p) -> mImsManager);
- setCarrierSupportsCallerIdVerticalServiceCodesCarrierConfig();
- }
-
- @After
- public void tearDown() throws Exception {
- super.tearDown();
- }
-
- @Test
- public void testIsTemporaryModeCLIRFromCarrierConfig() {
- // Test *67911 is treated as temporary mode CLIR
- doReturn(true).when(mTelephonyManager).isEmergencyNumber(TEST_DIAL_STRING_SERVICE_CODE);
- mGsmMmiCode = GsmMmiCode.newFromDialString(TEST_DIAL_STRING_SERVICE_CODE, mGsmCdmaPhoneUT,
- null, null);
- assertTrue(mGsmMmiCode.isTemporaryModeCLIR());
- }
-
- @Test
- public void testIsTemporaryModeCLIRForNonServiceCode() {
- // Test if prefix isn't *67 or *82
- doReturn(true).when(mTelephonyManager).isEmergencyNumber(TEST_DIAL_STRING_NO_SERVICE_CODE);
- mGsmMmiCode = GsmMmiCode.newFromDialString(TEST_DIAL_STRING_NO_SERVICE_CODE,
- mGsmCdmaPhoneUT, null, null);
- assertTrue(mGsmMmiCode == null);
- }
-
- @Test
- public void testIsTemporaryModeCLIRForNonEmergencyNumber() {
- // Test if dialing string isn't an emergency number
- mGsmMmiCode = GsmMmiCode.newFromDialString(TEST_DIAL_STRING_NON_EMERGENCY_NUMBER,
- mGsmCdmaPhoneUT, null, null);
- assertTrue(mGsmMmiCode == null);
- }
-
- @Test
- public void testNoCrashOnEmptyMessage() {
- GsmMmiCode mmi = GsmMmiCode.newNetworkInitiatedUssd(null, true, mGsmCdmaPhoneUT, null);
- try {
- mmi.onUssdFinishedError();
- } catch (Exception e) {
- fail("Shouldn't crash!!!");
- }
- }
-
- private void setCarrierSupportsCallerIdVerticalServiceCodesCarrierConfig() {
- final PersistableBundle bundle = new PersistableBundle();
- bundle.putBoolean(CarrierConfigManager
- .KEY_CARRIER_SUPPORTS_CALLER_ID_VERTICAL_SERVICE_CODES_BOOL, true);
- doReturn(bundle).when(mCarrierConfigManager).getConfigForSubId(anyInt());
- }
-}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/gsm/GsmSmsDispatcherTest.java b/tests/telephonytests/src/com/android/internal/telephony/gsm/GsmSmsDispatcherTest.java
index 3fdbe7935d..94b8987a70 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/gsm/GsmSmsDispatcherTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/gsm/GsmSmsDispatcherTest.java
@@ -23,44 +23,33 @@ import static com.android.internal.telephony.SmsUsageMonitor.PREMIUM_SMS_PERMISS
import static com.android.internal.telephony.TelephonyTestUtils.waitForMs;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-import android.app.Activity;
import android.app.ActivityManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
-import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
-import android.content.pm.PackageManager;
-import android.content.pm.ServiceInfo;
import android.location.Country;
import android.location.CountryDetector;
import android.os.HandlerThread;
import android.os.Message;
-import android.os.RemoteException;
import android.os.SystemProperties;
import android.provider.Settings;
-import android.service.carrier.CarrierMessagingService;
-import android.service.carrier.ICarrierMessagingCallback;
-import android.service.carrier.ICarrierMessagingService;
+import android.provider.Telephony;
import android.telephony.SmsManager;
-import android.testing.AndroidTestingRunner;
-import android.testing.TestableLooper;
+import android.test.suitebuilder.annotation.MediumTest;
+import android.test.suitebuilder.annotation.SmallTest;
import android.util.Singleton;
import androidx.test.filters.FlakyTest;
-import androidx.test.filters.MediumTest;
-import androidx.test.filters.SmallTest;
import com.android.internal.telephony.ContextFixture;
import com.android.internal.telephony.ISub;
@@ -74,22 +63,15 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
-import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import java.util.ArrayList;
import java.util.HashMap;
-import java.util.List;
-@RunWith(AndroidTestingRunner.class)
-@TestableLooper.RunWithLooper
public class GsmSmsDispatcherTest extends TelephonyTest {
private static final long TIMEOUT_MS = 500;
- private static final String CARRIER_APP_PACKAGE_NAME = "com.android.carrier";
@Mock
private android.telephony.SmsMessage mSmsMessage;
@@ -105,9 +87,6 @@ public class GsmSmsDispatcherTest extends TelephonyTest {
private SMSDispatcher.SmsTracker mSmsTracker;
@Mock
private ISub.Stub mISubStub;
- @Mock
- private ICarrierMessagingService.Stub mICarrierAppMessagingService;
-
private Object mLock = new Object();
private boolean mReceivedTestIntent;
private static final String TEST_INTENT = "com.android.internal.telephony.TEST_INTENT";
@@ -117,7 +96,6 @@ public class GsmSmsDispatcherTest extends TelephonyTest {
logd("onReceive");
synchronized (mLock) {
mReceivedTestIntent = true;
- mLock.notifyAll();
}
}
};
@@ -152,9 +130,6 @@ public class GsmSmsDispatcherTest extends TelephonyTest {
mGsmSmsDispatcherTestHandler = new GsmSmsDispatcherTestHandler(getClass().getSimpleName());
mGsmSmsDispatcherTestHandler.start();
waitUntilReady();
- mGsmSmsDispatcher = new GsmSMSDispatcher(mPhone, mSmsDispatchersController,
- mGsmInboundSmsHandler);
- processAllMessages();
}
@After
@@ -168,8 +143,9 @@ public class GsmSmsDispatcherTest extends TelephonyTest {
@Test @SmallTest
public void testSmsStatus() {
mSimulatedCommands.notifySmsStatus(new byte[]{(byte)0xFF, (byte)0xFF, (byte)0xFF});
- processAllMessages();
- verify(mSimulatedCommandsVerifier).acknowledgeLastIncomingGsmSms(true, 0, null);
+ TelephonyTestUtils.waitForMs(50);
+ verify(mSimulatedCommandsVerifier).acknowledgeLastIncomingGsmSms(true,
+ Telephony.Sms.Intents.RESULT_SMS_HANDLED, null);
}
@Test @MediumTest
@@ -228,22 +204,18 @@ public class GsmSmsDispatcherTest extends TelephonyTest {
}
}
- private void registerTestIntentReceiver() throws Exception {
+ @Test
+ @SmallTest
+ @FlakyTest
+ @Ignore
+ public void testSendTextWithInvalidDestAddr() throws Exception {
// unmock ActivityManager to be able to register receiver, create real PendingIntent and
// receive TEST_INTENT
restoreInstance(Singleton.class, "mInstance", mIActivityManagerSingleton);
restoreInstance(ActivityManager.class, "IActivityManagerSingleton", null);
Context realContext = TestApplication.getAppContext();
realContext.registerReceiver(mTestReceiver, new IntentFilter(TEST_INTENT));
- }
-
- @Test
- @SmallTest
- @FlakyTest
- @Ignore
- public void testSendTextWithInvalidDestAddr() throws Exception {
- registerTestIntentReceiver();
- PendingIntent pendingIntent = PendingIntent.getBroadcast(TestApplication.getAppContext(), 0,
+ PendingIntent pendingIntent = PendingIntent.getBroadcast(realContext, 0,
new Intent(TEST_INTENT), 0);
// send invalid dest address: +
mReceivedTestIntent = false;
@@ -280,8 +252,7 @@ public class GsmSmsDispatcherTest extends TelephonyTest {
Settings.Global.DEVICE_PROVISIONED, 1);
mGsmSmsDispatcher.sendRawPdu(new SMSDispatcher.SmsTracker[] {mSmsTracker});
- //waitForHandlerAction(mGsmSmsDispatcher, TIMEOUT_MS);
- processAllMessages();
+ waitForHandlerAction(mGsmSmsDispatcher, TIMEOUT_MS);
verify(mSmsUsageMonitor, times(1)).checkDestination(any(), any());
verify(mSmsUsageMonitor, times(1)).getPremiumSmsPermission(any());
@@ -292,10 +263,14 @@ public class GsmSmsDispatcherTest extends TelephonyTest {
}
@Test @SmallTest
- @FlakyTest
- @Ignore
public void testSendMultipartTextWithInvalidText() throws Exception {
- registerTestIntentReceiver();
+ // unmock ActivityManager to be able to register receiver, create real PendingIntent and
+ // receive TEST_INTENT
+ restoreInstance(Singleton.class, "mInstance", mIActivityManagerSingleton);
+ restoreInstance(ActivityManager.class, "IActivityManagerSingleton", null);
+
+ Context realContext = TestApplication.getAppContext();
+ realContext.registerReceiver(mTestReceiver, new IntentFilter(TEST_INTENT));
// initiate parameters for an invalid text MO SMS (the 2nd segmeant has 161 characters)
ArrayList<String> parts = new ArrayList<>();
@@ -305,8 +280,8 @@ public class GsmSmsDispatcherTest extends TelephonyTest {
+ "8");
ArrayList<PendingIntent> sentIntents = new ArrayList<>();
- PendingIntent sentIntent = PendingIntent.getBroadcast(TestApplication.getAppContext(), 0,
- new Intent(TEST_INTENT), PendingIntent.FLAG_IMMUTABLE);
+ PendingIntent sentIntent = PendingIntent.getBroadcast(realContext, 0,
+ new Intent(TEST_INTENT), 0);
sentIntents.add(sentIntent);
sentIntents.add(sentIntent);
@@ -321,193 +296,4 @@ public class GsmSmsDispatcherTest extends TelephonyTest {
assertEquals(SmsManager.RESULT_ERROR_GENERIC_FAILURE, mTestReceiver.getResultCode());
}
}
-
- private void mockCarrierApp()
- throws RemoteException {
- mContextFixture.addService(
- CarrierMessagingService.SERVICE_INTERFACE,
- new ComponentName(CARRIER_APP_PACKAGE_NAME, "CarrierAppFilterClass"),
- CARRIER_APP_PACKAGE_NAME,
- mICarrierAppMessagingService,
- new ServiceInfo());
- when(mICarrierAppMessagingService.asBinder()).thenReturn(mICarrierAppMessagingService);
- mockUiccWithCarrierApp();
- }
-
- private void mockUiccWithCarrierApp() {
- when(mUiccController.getUiccCard(mPhone.getPhoneId())).thenReturn(mUiccCard);
- List<String> carrierPackages = new ArrayList<>();
- carrierPackages.add(CARRIER_APP_PACKAGE_NAME);
- when(mUiccCard.getCarrierPackageNamesForIntent(
- any(PackageManager.class), any(Intent.class))).thenReturn(carrierPackages);
- }
-
- private void mockCarrierAppStubResults(final int result, ICarrierMessagingService.Stub stub,
- boolean callOnFilterComplete)
- throws RemoteException {
- when(stub.queryLocalInterface(anyString())).thenReturn(stub);
- when(stub.asBinder()).thenReturn(stub);
- // for single part
- doAnswer(new Answer<Void>() {
- @Override
- public Void answer(InvocationOnMock invocation) throws Throwable {
- Object[] args = invocation.getArguments();
- ICarrierMessagingCallback callback = (ICarrierMessagingCallback) args[4];
- if (callOnFilterComplete) {
- callback.onSendSmsComplete(result, 0);
- }
- return null;
- }
- }).when(stub).sendTextSms(
- anyString(), anyInt(), anyString(), anyInt(),
- any(ICarrierMessagingCallback.class));
-
- // for multi part
- doAnswer(new Answer<Void>() {
- @Override
- public Void answer(InvocationOnMock invocation) throws Throwable {
- Object[] args = invocation.getArguments();
- ICarrierMessagingCallback callback = (ICarrierMessagingCallback) args[4];
- if (callOnFilterComplete) {
- callback.onSendMultipartSmsComplete(result, null);
- }
- return null;
- }
- }).when(stub).sendMultipartTextSms(
- any(), anyInt(), anyString(), anyInt(),
- any(ICarrierMessagingCallback.class));
- }
-
- @Test
- @SmallTest
- public void testSendSmsByCarrierApp() throws Exception {
- mockCarrierApp();
- mockCarrierAppStubResults(CarrierMessagingService.SEND_STATUS_OK,
- mICarrierAppMessagingService, true);
- registerTestIntentReceiver();
-
- PendingIntent pendingIntent = PendingIntent.getBroadcast(TestApplication.getAppContext(), 0,
- new Intent(TEST_INTENT), PendingIntent.FLAG_MUTABLE);
- mReceivedTestIntent = false;
-
- mGsmSmsDispatcher.sendText("6501002000", "121" /*scAddr*/, "test sms",
- pendingIntent, null, null, null, false, -1, false, -1, false, 0L);
- processAllMessages();
- synchronized (mLock) {
- if (!mReceivedTestIntent) {
- // long wait since sometimes broadcasts can take a long time if the system is loaded
- mLock.wait(60000);
- }
- assertEquals(true, mReceivedTestIntent);
- int resultCode = mTestReceiver.getResultCode();
- assertTrue("Unexpected result code: " + resultCode,
- resultCode == SmsManager.RESULT_ERROR_NONE || resultCode == Activity.RESULT_OK);
- verify(mSimulatedCommandsVerifier, times(0)).sendSMS(anyString(), anyString(),
- any(Message.class));
- }
- }
-
- @Test
- @SmallTest
- public void testSendSmsByCarrierAppNoResponse() throws Exception {
- mockCarrierApp();
- // do not mock result, instead reduce the timeout for test
- mGsmSmsDispatcher.mCarrierMessagingTimeout = 100;
-
- mGsmSmsDispatcher.sendText("6501002000", "121" /*scAddr*/, "test sms",
- null, null, null, null, false, -1, false, -1, false, 0L);
- // wait for timeout
- waitForMs(150);
- verify(mSimulatedCommandsVerifier).sendSMS(anyString(), anyString(), any(Message.class));
- }
-
- @Test
- @SmallTest
- public void testSendSmsByCarrierAppBindingFailed() throws Exception {
- mContextFixture.mockBindingFailureForPackage(CARRIER_APP_PACKAGE_NAME);
- // mock presence of carrier app, but do not create a mock service to make binding fail
- mockUiccWithCarrierApp();
-
- mGsmSmsDispatcher.sendText("6501002000", "121" /*scAddr*/, "test sms",
- null, null, null, null, false, -1, false, -1, false, 0L);
- processAllMessages();
- verify(mSimulatedCommandsVerifier).sendSMS(anyString(), anyString(), any(Message.class));
- }
-
- private void sendMultipartTextSms(boolean withSentIntents) {
- // initiate parameters for a multipart sms
- ArrayList<String> parts = new ArrayList<>();
- parts.add("segment1");
- parts.add("segment2");
-
- ArrayList<PendingIntent> sentIntents = new ArrayList<>();
- PendingIntent sentIntent1 = PendingIntent.getBroadcast(TestApplication.getAppContext(), 0,
- new Intent(TEST_INTENT), PendingIntent.FLAG_MUTABLE);
- PendingIntent sentIntent2 = PendingIntent.getBroadcast(TestApplication.getAppContext(), 0,
- new Intent(TEST_INTENT), PendingIntent.FLAG_MUTABLE);
- sentIntents.add(sentIntent1);
- sentIntents.add(sentIntent2);
-
- mGsmSmsDispatcher.sendMultipartText("6501002000" /*destAddr*/, "222" /*scAddr*/, parts,
- withSentIntents ? sentIntents : null, null, null, null, false, -1, false, -1, 0L);
- }
-
- @Test
- @SmallTest
- public void testSendMultipartSmsByCarrierApp() throws Exception {
- mockCarrierApp();
- mockCarrierAppStubResults(CarrierMessagingService.SEND_STATUS_OK,
- mICarrierAppMessagingService, true);
- registerTestIntentReceiver();
-
- // send SMS and check sentIntent
- mReceivedTestIntent = false;
- sendMultipartTextSms(true);
- processAllMessages();
- synchronized (mLock) {
- if (!mReceivedTestIntent) {
- // long wait since sometimes broadcasts can take a long time if the system is loaded
- mLock.wait(60000);
- }
- assertEquals(true, mReceivedTestIntent);
- int resultCode = mTestReceiver.getResultCode();
- assertTrue("Unexpected result code: " + resultCode,
- resultCode == SmsManager.RESULT_ERROR_NONE || resultCode == Activity.RESULT_OK);
- verify(mSimulatedCommandsVerifier, times(0)).sendSMS(anyString(), anyString(),
- any(Message.class));
- }
- }
-
- @Test
- @SmallTest
- public void testSendMultipartSmsByCarrierAppNoResponse() throws Exception {
- mockCarrierApp();
- // do not mock result, instead reduce the timeout for test
- mGsmSmsDispatcher.mCarrierMessagingTimeout = 100;
-
- sendMultipartTextSms(false);
-
- // wait for timeout
- waitForMs(150);
- verify(mSimulatedCommandsVerifier).sendSMSExpectMore(anyString(), anyString(),
- any(Message.class));
- verify(mSimulatedCommandsVerifier).sendSMS(anyString(), anyString(),
- any(Message.class));
- }
-
- @Test
- @SmallTest
- public void testSendMultipartSmsByCarrierAppBindingFailed() throws Exception {
- mContextFixture.mockBindingFailureForPackage(CARRIER_APP_PACKAGE_NAME);
- // mock presence of carrier app, but do not create a mock service to make binding fail
- mockUiccWithCarrierApp();
-
- sendMultipartTextSms(false);
-
- processAllMessages();
- verify(mSimulatedCommandsVerifier).sendSMSExpectMore(anyString(), anyString(),
- any(Message.class));
- verify(mSimulatedCommandsVerifier).sendSMS(anyString(), anyString(),
- any(Message.class));
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/ims/FeatureConnectionTest.java b/tests/telephonytests/src/com/android/internal/telephony/ims/FeatureConnectionTest.java
new file mode 100644
index 0000000000..bac45efdb1
--- /dev/null
+++ b/tests/telephonytests/src/com/android/internal/telephony/ims/FeatureConnectionTest.java
@@ -0,0 +1,220 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.telephony.ims;
+
+import junit.framework.AssertionFailedError;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.telephony.ims.aidl.IImsRegistration;
+import android.telephony.ims.feature.ImsFeature;
+import android.telephony.ims.stub.ImsRegistrationImplBase;
+import android.test.suitebuilder.annotation.SmallTest;
+
+import com.android.ims.FeatureConnection;
+import com.android.ims.ImsManager;
+import com.android.ims.internal.IImsServiceFeatureCallback;
+import com.android.internal.telephony.TelephonyTest;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+
+import java.util.concurrent.Executor;
+
+public class FeatureConnectionTest extends TelephonyTest {
+
+ private Executor mSimpleExecutor = new Executor() {
+ @Override
+ public void execute(Runnable r) {
+ r.run();
+ }
+ };
+
+ private class TestFeatureConnection extends FeatureConnection {
+ private Integer mFeatureState = ImsFeature.STATE_READY;
+
+ public boolean isFeatureCreatedCalled = false;
+ public boolean isFeatureRemovedCalled = false;
+ public int mNewStatus = ImsFeature.STATE_UNAVAILABLE;
+
+ TestFeatureConnection(Context context, int slotId) {
+ super(context, slotId);
+ if (!ImsManager.isImsSupportedOnDevice(context)) {
+ sImsSupportedOnDevice = false;
+ }
+ }
+
+ @Override
+ public void checkServiceIsReady() throws RemoteException {
+ super.checkServiceIsReady();
+ }
+
+ @Override
+ protected void handleImsFeatureCreatedCallback(int slotId, int feature) {
+ isFeatureCreatedCalled = true;
+ }
+
+ @Override
+ protected void handleImsFeatureRemovedCallback(int slotId, int feature) {
+ isFeatureRemovedCalled = true;
+ }
+
+ @Override
+ protected void handleImsStatusChangedCallback(int slotId, int feature, int status) {
+ mNewStatus = status;
+ }
+
+ @Override
+ protected Integer retrieveFeatureState() {
+ return mFeatureState;
+ }
+
+ @Override
+ protected IImsRegistration getRegistrationBinder() {
+ return getTestRegistrationBinder();
+ }
+
+ public void setFeatureState(int state) {
+ mFeatureState = state;
+ }
+ };
+
+ private int mPhoneId;
+ private TestFeatureConnection mTestFeatureConnection;
+ @Mock IBinder mBinder;
+ @Mock IImsRegistration mRegistrationBinder;
+
+ @Before
+ public void setUp() throws Exception {
+ super.setUp("FeatureConnectionTest");
+ mPhoneId = mPhone.getPhoneId();
+
+ doReturn(null).when(mContext).getMainLooper();
+ doReturn(true).when(mPackageManager).hasSystemFeature(PackageManager.FEATURE_TELEPHONY_IMS);
+
+ mTestFeatureConnection = new TestFeatureConnection(mContext, mPhoneId);
+ mTestFeatureConnection.mExecutor = mSimpleExecutor;
+ mTestFeatureConnection.setBinder(mBinder);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ /**
+ * Test service is ready when binder is alive and IMS status is ready.
+ */
+ @Test
+ @SmallTest
+ public void testServiceIsReady() {
+ when(mBinder.isBinderAlive()).thenReturn(true);
+ mTestFeatureConnection.setFeatureState(ImsFeature.STATE_READY);
+
+ try {
+ mTestFeatureConnection.checkServiceIsReady();
+ } catch (RemoteException e) {
+ throw new AssertionFailedError("Exception in testServiceIsReady: " + e);
+ }
+ }
+
+ /**
+ * Test service is not ready when binder is not alive or status is not ready.
+ */
+ @Test
+ @SmallTest
+ public void testServiceIsNotReady() {
+ // Binder is not alive
+ when(mBinder.isBinderAlive()).thenReturn(false);
+
+ try {
+ mTestFeatureConnection.checkServiceIsReady();
+ throw new AssertionFailedError("testServiceIsNotReady: binder isn't alive");
+ } catch (RemoteException e) {
+ // expected result
+ }
+
+ // IMS feature status is unavailable
+ when(mBinder.isBinderAlive()).thenReturn(true);
+ mTestFeatureConnection.setFeatureState(ImsFeature.STATE_UNAVAILABLE);
+
+ try {
+ mTestFeatureConnection.checkServiceIsReady();
+ throw new AssertionFailedError("testServiceIsNotReady: status unavailable");
+ } catch (RemoteException e) {
+ // expected result
+ }
+ }
+
+ /**
+ * Test registration tech callbacks.
+ */
+ @Test
+ @SmallTest
+ public void testRegistrationTech() throws Exception {
+ when(mRegistrationBinder.getRegistrationTechnology()).thenReturn(
+ ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN);
+
+ assertEquals(ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN,
+ mTestFeatureConnection.getRegistrationTech());
+
+ }
+
+ /**
+ * Test callback is called when IMS feature created/removed/changed.
+ */
+ @Test
+ @SmallTest
+ public void testListenerCallback() {
+ IImsServiceFeatureCallback featureCallback = mTestFeatureConnection.getListener();
+
+ try {
+ featureCallback.imsFeatureCreated(anyInt(), anyInt());
+ assertTrue(mTestFeatureConnection.isFeatureCreatedCalled);
+ } catch (RemoteException e) {
+ throw new AssertionFailedError("testListenerCallback(Created): " + e);
+ }
+
+ try {
+ featureCallback.imsFeatureRemoved(anyInt(), anyInt());
+ assertTrue(mTestFeatureConnection.isFeatureRemovedCalled);
+ } catch (RemoteException e) {
+ throw new AssertionFailedError("testListenerCallback(Removed): " + e);
+ }
+
+ try {
+ featureCallback.imsStatusChanged(anyInt(), anyInt(), ImsFeature.STATE_READY);
+ assertEquals(mTestFeatureConnection.mNewStatus, ImsFeature.STATE_READY);
+ } catch (RemoteException e) {
+ throw new AssertionFailedError("testListenerCallback(Changed): " + e);
+ }
+ }
+
+ private IImsRegistration getTestRegistrationBinder() {
+ return mRegistrationBinder;
+ }
+}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/ims/FeatureConnectorTest.java b/tests/telephonytests/src/com/android/internal/telephony/ims/FeatureConnectorTest.java
new file mode 100644
index 0000000000..a2b4de84bb
--- /dev/null
+++ b/tests/telephonytests/src/com/android/internal/telephony/ims/FeatureConnectorTest.java
@@ -0,0 +1,155 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.telephony.ims;
+
+import junit.framework.AssertionFailedError;
+
+import static org.mockito.ArgumentMatchers.anyObject;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.content.pm.PackageManager;
+import android.os.HandlerThread;
+import android.os.Looper;
+import android.telephony.ims.feature.ImsFeature;
+import android.test.suitebuilder.annotation.SmallTest;
+
+import com.android.ims.FeatureConnector;
+import com.android.ims.ImsException;
+import com.android.ims.ImsManager;
+import com.android.internal.telephony.TelephonyTest;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+
+import java.util.concurrent.Executor;
+
+public class FeatureConnectorTest extends TelephonyTest {
+
+ private Executor mExecutor = new Executor() {
+ @Override
+ public void execute(Runnable r) {
+ r.run();
+ }
+ };
+
+ private HandlerThread mHandlerThread;
+ private FeatureConnector<ImsManager> mFeatureConnector;
+ @Mock
+ ImsManager mImsManager;
+ @Mock
+ FeatureConnector.Listener<ImsManager> mListener;
+ @Mock
+ FeatureConnector.RetryTimeout mRetryTimeout;
+
+ @Before
+ public void setUp() throws Exception {
+ super.setUp("FeatureConnectorTest");
+ if (Looper.myLooper() == null) {
+ Looper.prepare();
+ }
+
+ int phoneId = mPhone.getPhoneId();
+ mHandlerThread = new HandlerThread("ConnectorHandlerThread");
+ mHandlerThread.start();
+
+ mFeatureConnector = new FeatureConnector<>(mContext, phoneId,
+ mListener, mExecutor, mHandlerThread.getLooper());
+ mFeatureConnector.mListener = mListener;
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ mHandlerThread.quit();
+ super.tearDown();
+ }
+
+ @Test
+ @SmallTest
+ public void testConnect() {
+ // ImsManager is supported on device
+ setImsSupportedFeature(true);
+ when(mListener.getFeatureManager()).thenReturn(mImsManager);
+
+ mFeatureConnector.connect();
+ waitForHandlerAction(mFeatureConnector, 1000);
+
+ // Verify that mListener will retrieve feature manager
+ verify(mListener).getFeatureManager();
+
+ reset(mListener);
+
+ // ImsManager is NOT supported on device
+ setImsSupportedFeature(false);
+ when(mListener.getFeatureManager()).thenReturn(mImsManager);
+
+ mFeatureConnector.connect();
+ waitForHandlerAction(mFeatureConnector, 1000);
+
+ // Verify that mListener won't retrieve feature manager
+ verify(mListener, never()).getFeatureManager();
+ }
+
+ @Test
+ @SmallTest
+ public void testDisconnect() {
+ // Verify mListener will call connectionUnavailable if disconnect() is called.
+ mFeatureConnector.disconnect();
+ verify(mListener).connectionUnavailable();
+ }
+
+ @Test
+ @SmallTest
+ public void testNotifyStateChanged() {
+ try {
+ mFeatureConnector.mManager = mImsManager;
+ when(mImsManager.getImsServiceState()).thenReturn(ImsFeature.STATE_READY);
+ // Trigger status changed
+ mFeatureConnector.mNotifyStatusChangedCallback.notifyStateChanged();
+ // Verify NotifyReady is called
+ verify(mListener).connectionReady(anyObject());
+ } catch (ImsException e) {
+ throw new AssertionFailedError("Exception in testNotifyStateChanged: " + e);
+ }
+ }
+
+ @Test
+ @SmallTest
+ public void testRetryGetImsService() {
+ mFeatureConnector.mManager = mImsManager;
+ mFeatureConnector.mRetryTimeout = mRetryTimeout;
+
+ when(mRetryTimeout.get()).thenReturn(1);
+ when(mListener.getFeatureManager()).thenReturn(mImsManager);
+
+ mFeatureConnector.retryGetImsService();
+ waitForHandlerAction(mFeatureConnector, 2000);
+
+ // Verify removeNotifyStatusChangedCallback will be called if ImsManager is not null.
+ verify(mImsManager).removeNotifyStatusChangedCallback(anyObject());
+ }
+
+ private void setImsSupportedFeature(boolean isSupported) {
+ doReturn(isSupported).when(mPackageManager).hasSystemFeature(
+ PackageManager.FEATURE_TELEPHONY_IMS);
+ }
+}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/ims/ImsCallProfileTest.java b/tests/telephonytests/src/com/android/internal/telephony/ims/ImsCallProfileTest.java
index 48148ba624..751db91af0 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/ims/ImsCallProfileTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/ims/ImsCallProfileTest.java
@@ -22,7 +22,6 @@ import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
-import android.location.Location;
import android.os.Parcel;
import android.os.Parcelable;
import android.telecom.DisconnectCause;
@@ -75,71 +74,6 @@ public class ImsCallProfileTest {
}
}
- @Test
- @SmallTest
- public void testCallComposerExtras() {
- ImsCallProfile data = new ImsCallProfile();
-
- // EXTRA_PRIORITY
- data.setCallExtraInt(ImsCallProfile.EXTRA_PRIORITY,
- ImsCallProfile.PRIORITY_URGENT);
- assertEquals(ImsCallProfile.PRIORITY_URGENT,
- data.getCallExtraInt(ImsCallProfile.EXTRA_PRIORITY));
- data.setCallExtraInt(ImsCallProfile.EXTRA_PRIORITY,
- ImsCallProfile.PRIORITY_NORMAL);
- assertEquals(ImsCallProfile.PRIORITY_NORMAL,
- data.getCallExtraInt(ImsCallProfile.EXTRA_PRIORITY));
-
- // EXTRA_CALL_SUBJECT
- String testCallSubject = "TEST_CALL_SUBJECT";
- data.setCallExtra(ImsCallProfile.EXTRA_CALL_SUBJECT, testCallSubject);
- assertEquals(testCallSubject, data.getCallExtra(ImsCallProfile.EXTRA_CALL_SUBJECT));
-
- // EXTRA_CALL_LOCATION
- Location testLocation = new Location("ImsCallProfileTest");
- double latitude = 123;
- double longitude = 456;
- testLocation.setLatitude(latitude);
- testLocation.setLongitude(longitude);
- data.setCallExtraParcelable(ImsCallProfile.EXTRA_LOCATION, testLocation);
- Location testGetLocation = (Location) data.getCallExtraParcelable(
- ImsCallProfile.EXTRA_LOCATION);
- assertEquals(latitude, testGetLocation.getLatitude(), 0);
- assertEquals(longitude, testGetLocation.getLongitude(), 0);
-
- // EXTRA_PICTURE_URL
- String testPictureUrl = "TEST_PICTURE_URL";
- data.setCallExtra(ImsCallProfile.EXTRA_PICTURE_URL, testPictureUrl);
- assertEquals(testPictureUrl, data.getCallExtra(ImsCallProfile.EXTRA_PICTURE_URL));
-
- // Test the whole Parcel ImsCallProfile
- Parcel dataParceled = Parcel.obtain();
- data.writeToParcel(dataParceled, 0);
- dataParceled.setDataPosition(0);
- ImsCallProfile unparceledData = ImsCallProfile.CREATOR.createFromParcel(dataParceled);
- dataParceled.recycle();
-
- assertEquals("unparceled data for EXTRA_PRIORITY is not valid!",
- data.getCallExtraInt(ImsCallProfile.EXTRA_PRIORITY),
- unparceledData.getCallExtraInt(ImsCallProfile.EXTRA_PRIORITY));
-
- assertEquals("unparceled data for EXTRA_CALL_SUBJECT is not valid!",
- data.getCallExtra(ImsCallProfile.EXTRA_CALL_SUBJECT),
- unparceledData.getCallExtra(ImsCallProfile.EXTRA_CALL_SUBJECT));
-
- Location locationFromData = data.getCallExtraParcelable(ImsCallProfile.EXTRA_LOCATION);
- Location locationFromUnparceledData = unparceledData.getCallExtraParcelable(
- ImsCallProfile.EXTRA_LOCATION);
- assertEquals("unparceled data for EXTRA_LOCATION latitude is not valid!",
- locationFromData.getLatitude(), locationFromUnparceledData.getLatitude(), 0);
- assertEquals("unparceled data for EXTRA_LOCATION Longitude is not valid!",
- locationFromData.getLongitude(), locationFromUnparceledData.getLongitude(), 0);
-
- assertEquals("unparceled data for EXTRA_PICTURE_URL is not valid!",
- data.getCallExtra(ImsCallProfile.EXTRA_PICTURE_URL),
- unparceledData.getCallExtra(ImsCallProfile.EXTRA_PICTURE_URL));
- }
-
/**
* Ensures that the {@link ImsCallProfile} will discard invalid extras when it is parceled.
*/
diff --git a/tests/telephonytests/src/com/android/internal/telephony/ims/ImsManagerTest.java b/tests/telephonytests/src/com/android/internal/telephony/ims/ImsManagerTest.java
new file mode 100644
index 0000000000..7088024e2b
--- /dev/null
+++ b/tests/telephonytests/src/com/android/internal/telephony/ims/ImsManagerTest.java
@@ -0,0 +1,899 @@
+/*
+ * Copyright 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.telephony.ims;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Mockito.anyInt;
+import static org.mockito.Mockito.anyString;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.content.pm.PackageManager;
+import android.os.IBinder;
+import android.os.PersistableBundle;
+import android.telephony.CarrierConfigManager;
+import android.telephony.SubscriptionManager;
+import android.telephony.ims.ImsMmTelManager;
+import android.telephony.ims.ProvisioningManager;
+import android.telephony.ims.stub.ImsConfigImplBase;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.ims.ImsConfig;
+import com.android.ims.ImsManager;
+import com.android.ims.MmTelFeatureConnection;
+import com.android.internal.telephony.TelephonyTest;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+
+import java.util.Hashtable;
+
+@RunWith(AndroidJUnit4.class)
+public class ImsManagerTest extends TelephonyTest {
+ private static final String UNSET_PROVISIONED_STRING = "unset";
+ private static final boolean ENHANCED_4G_MODE_DEFAULT_VAL = true;
+ private static final boolean ENHANCED_4G_MODE_EDITABLE = true;
+ private static final boolean WFC_IMS_ENABLE_DEFAULT_VAL = false;
+ private static final boolean WFC_IMS_ROAMING_ENABLE_DEFAULT_VAL = true;
+ private static final boolean VT_IMS_ENABLE_DEFAULT_VAL = true;
+ private static final boolean WFC_IMS_EDITABLE_VAL = true;
+ private static final boolean WFC_IMS_NOT_EDITABLE_VAL = false;
+ private static final boolean WFC_IMS_ROAMING_EDITABLE_VAL = true;
+ private static final boolean WFC_IMS_ROAMING_NOT_EDITABLE_VAL = false;
+ private static final int WFC_IMS_MODE_DEFAULT_VAL =
+ ImsConfig.WfcModeFeatureValueConstants.CELLULAR_PREFERRED;
+ private static final int WFC_IMS_ROAMING_MODE_DEFAULT_VAL =
+ ImsConfig.WfcModeFeatureValueConstants.WIFI_PREFERRED;
+ private static final boolean WFC_USE_HOME_MODE_FOR_ROAMING_VAL = true;
+ private static final boolean WFC_NOT_USE_HOME_MODE_FOR_ROAMING_VAL = false;
+
+ PersistableBundle mBundle;
+ @Mock IBinder mBinder;
+ @Mock ImsConfigImplBase mImsConfigImplBaseMock;
+ Hashtable<Integer, Integer> mProvisionedIntVals = new Hashtable<>();
+ Hashtable<Integer, String> mProvisionedStringVals = new Hashtable<>();
+ ImsConfigImplBase.ImsConfigStub mImsConfigStub;
+ @Mock MmTelFeatureConnection mMmTelFeatureConnection;
+
+ private final int[] mSubId = {0};
+ private int mPhoneId;
+
+ @Before
+ public void setUp() throws Exception {
+ super.setUp("ImsManagerTest");
+ mPhoneId = mPhone.getPhoneId();
+ mBundle = mContextFixture.getCarrierConfigBundle();
+ // Force MmTelFeatureConnection to create an executor using Looper.myLooper().
+ doReturn(null).when(mContext).getMainLooper();
+
+ doReturn(mSubId).when(mSubscriptionController).getSubId(mPhoneId);
+
+ doReturn(mSubscriptionController).when(mBinder).queryLocalInterface(anyString());
+ mServiceManagerMockedServices.put("isub", mBinder);
+ // Stick to the CarrierConfig defaults unless explicitly overwritten.
+ doReturn("-1").when(mSubscriptionController).getSubscriptionProperty(anyInt(), anyString(),
+ anyString(), nullable(String.class));
+
+
+ doReturn(true).when(mMmTelFeatureConnection).isBinderAlive();
+ mContextFixture.addSystemFeature(PackageManager.FEATURE_TELEPHONY_IMS);
+
+ mImsManagerInstances.remove(mPhoneId);
+
+ setDefaultValues();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ private void setDefaultValues() {
+ mBundle.putBoolean(CarrierConfigManager.KEY_EDITABLE_ENHANCED_4G_LTE_BOOL,
+ ENHANCED_4G_MODE_EDITABLE);
+ mBundle.putBoolean(CarrierConfigManager.KEY_EDITABLE_WFC_MODE_BOOL,
+ WFC_IMS_EDITABLE_VAL);
+ mBundle.putBoolean(CarrierConfigManager.KEY_EDITABLE_WFC_ROAMING_MODE_BOOL,
+ WFC_IMS_ROAMING_EDITABLE_VAL);
+ mBundle.putBoolean(CarrierConfigManager.KEY_CARRIER_DEFAULT_WFC_IMS_ENABLED_BOOL,
+ WFC_IMS_ENABLE_DEFAULT_VAL);
+ mBundle.putBoolean(CarrierConfigManager.KEY_CARRIER_DEFAULT_WFC_IMS_ROAMING_ENABLED_BOOL,
+ WFC_IMS_ROAMING_ENABLE_DEFAULT_VAL);
+ mBundle.putInt(CarrierConfigManager.KEY_CARRIER_DEFAULT_WFC_IMS_MODE_INT,
+ WFC_IMS_MODE_DEFAULT_VAL);
+ mBundle.putInt(CarrierConfigManager.KEY_CARRIER_DEFAULT_WFC_IMS_ROAMING_MODE_INT,
+ WFC_IMS_ROAMING_MODE_DEFAULT_VAL);
+ mBundle.putBoolean(CarrierConfigManager.KEY_ENHANCED_4G_LTE_ON_BY_DEFAULT_BOOL,
+ ENHANCED_4G_MODE_DEFAULT_VAL);
+ mBundle.putBoolean(CarrierConfigManager.KEY_CARRIER_VOLTE_PROVISIONING_REQUIRED_BOOL, true);
+ mBundle.putBoolean(
+ CarrierConfigManager.KEY_USE_WFC_HOME_NETWORK_MODE_IN_ROAMING_NETWORK_BOOL,
+ WFC_NOT_USE_HOME_MODE_FOR_ROAMING_VAL);
+ mBundle.putBoolean(CarrierConfigManager.KEY_CARRIER_RCS_PROVISIONING_REQUIRED_BOOL, true);
+
+ }
+
+ @Test @SmallTest
+ public void testGetDefaultValues() {
+ ImsManager imsManager = getImsManagerAndInitProvisionedValues();
+
+ assertEquals(WFC_IMS_ENABLE_DEFAULT_VAL, imsManager.isWfcEnabledByUser());
+ verify(mSubscriptionController, times(1)).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_ENABLED),
+ anyString(),
+ nullable(String.class));
+
+ assertEquals(WFC_IMS_ROAMING_ENABLE_DEFAULT_VAL, imsManager.isWfcRoamingEnabledByUser());
+ verify(mSubscriptionController, times(1)).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_ROAMING_ENABLED),
+ anyString(),
+ nullable(String.class));
+
+ assertEquals(ENHANCED_4G_MODE_DEFAULT_VAL,
+ imsManager.isEnhanced4gLteModeSettingEnabledByUser());
+ verify(mSubscriptionController, times(1)).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.ENHANCED_4G_MODE_ENABLED),
+ anyString(),
+ nullable(String.class));
+
+ assertEquals(WFC_IMS_MODE_DEFAULT_VAL, imsManager.getWfcMode(false));
+ verify(mSubscriptionController, times(1)).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_MODE),
+ anyString(),
+ nullable(String.class));
+
+ assertEquals(WFC_IMS_ROAMING_MODE_DEFAULT_VAL, imsManager.getWfcMode(true));
+ verify(mSubscriptionController, times(1)).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_ROAMING_MODE),
+ anyString(),
+ nullable(String.class));
+
+ assertEquals(VT_IMS_ENABLE_DEFAULT_VAL, imsManager.isVtEnabledByUser());
+ verify(mSubscriptionController, times(1)).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.VT_IMS_ENABLED),
+ anyString(),
+ nullable(String.class));
+ }
+
+ @Test @SmallTest
+ public void testSetValues() {
+ ImsManager imsManager = getImsManagerAndInitProvisionedValues();
+
+ imsManager.setWfcMode(ImsConfig.WfcModeFeatureValueConstants.CELLULAR_PREFERRED);
+ verify(mSubscriptionController, times(1)).setSubscriptionProperty(
+ eq(mSubId[0]),
+ eq(SubscriptionManager.WFC_IMS_MODE),
+ eq("1"));
+
+ imsManager.setWfcMode(ImsConfig.WfcModeFeatureValueConstants.CELLULAR_PREFERRED, true);
+ verify(mSubscriptionController, times(1)).setSubscriptionProperty(
+ eq(mSubId[0]),
+ eq(SubscriptionManager.WFC_IMS_ROAMING_MODE),
+ eq("1"));
+
+ imsManager.setVtSetting(false);
+ verify(mSubscriptionController, times(1)).setSubscriptionProperty(
+ eq(mSubId[0]),
+ eq(SubscriptionManager.VT_IMS_ENABLED),
+ eq("0"));
+
+ // enhanced 4g mode must be editable to use setEnhanced4gLteModeSetting
+ mBundle.putBoolean(CarrierConfigManager.KEY_EDITABLE_ENHANCED_4G_LTE_BOOL,
+ ENHANCED_4G_MODE_EDITABLE);
+ imsManager.setEnhanced4gLteModeSetting(true);
+ verify(mSubscriptionController, times(1)).setSubscriptionProperty(
+ eq(mSubId[0]),
+ eq(SubscriptionManager.ENHANCED_4G_MODE_ENABLED),
+ eq("1"));
+
+ imsManager.setWfcSetting(true);
+ verify(mSubscriptionController, times(1)).setSubscriptionProperty(
+ eq(mSubId[0]),
+ eq(SubscriptionManager.WFC_IMS_ENABLED),
+ eq("1"));
+ }
+ @Test
+ public void testGetProvisionedValues() throws Exception {
+ ImsManager imsManager = getImsManagerAndInitProvisionedValues();
+
+ assertEquals(true, imsManager.isWfcProvisionedOnDevice());
+ verify(mImsConfigImplBaseMock, times(1)).getConfigInt(
+ eq(ImsConfig.ConfigConstants.VOICE_OVER_WIFI_SETTING_ENABLED));
+
+ assertEquals(true, imsManager.isVtProvisionedOnDevice());
+ verify(mImsConfigImplBaseMock, times(1)).getConfigInt(
+ eq(ImsConfig.ConfigConstants.LVC_SETTING_ENABLED));
+
+ assertEquals(true, imsManager.isVolteProvisionedOnDevice());
+ verify(mImsConfigImplBaseMock, times(1)).getConfigInt(
+ eq(ImsConfig.ConfigConstants.VLT_SETTING_ENABLED));
+
+ // If we call get again, times should still be one because the value should be fetched
+ // from cache.
+ assertEquals(true, imsManager.isWfcProvisionedOnDevice());
+ verify(mImsConfigImplBaseMock, times(1)).getConfigInt(
+ eq(ImsConfig.ConfigConstants.VOICE_OVER_WIFI_SETTING_ENABLED));
+
+ assertEquals(true, imsManager.isVtProvisionedOnDevice());
+ verify(mImsConfigImplBaseMock, times(1)).getConfigInt(
+ eq(ImsConfig.ConfigConstants.LVC_SETTING_ENABLED));
+
+ assertEquals(true, imsManager.isVolteProvisionedOnDevice());
+ verify(mImsConfigImplBaseMock, times(1)).getConfigInt(
+ eq(ImsConfig.ConfigConstants.VLT_SETTING_ENABLED));
+
+ assertEquals(true, imsManager.isEabProvisionedOnDevice());
+ verify(mImsConfigImplBaseMock, times(1)).getConfigInt(
+ eq(ImsConfig.ConfigConstants.EAB_SETTING_ENABLED));
+ }
+
+ @Test
+ public void testSetProvisionedValues() throws Exception {
+ ImsManager imsManager = getImsManagerAndInitProvisionedValues();
+
+ assertEquals(true, imsManager.isWfcProvisionedOnDevice());
+ verify(mImsConfigImplBaseMock, times(1)).getConfigInt(
+ eq(ImsConfig.ConfigConstants.VOICE_OVER_WIFI_SETTING_ENABLED));
+
+ imsManager.getConfigInterface().setProvisionedValue(
+ ImsConfig.ConfigConstants.VOICE_OVER_WIFI_SETTING_ENABLED,
+ ImsConfig.FeatureValueConstants.OFF);
+
+ assertEquals(0, (int) mProvisionedIntVals.get(
+ ImsConfig.ConfigConstants.VOICE_OVER_WIFI_SETTING_ENABLED));
+
+ assertEquals(false, imsManager.isWfcProvisionedOnDevice());
+
+ verify(mImsConfigImplBaseMock, times(1)).setConfig(
+ eq(ImsConfig.ConfigConstants.VOICE_OVER_WIFI_SETTING_ENABLED),
+ eq(0));
+ verify(mImsConfigImplBaseMock, times(1)).getConfigInt(
+ eq(ImsConfig.ConfigConstants.VOICE_OVER_WIFI_SETTING_ENABLED));
+ }
+
+ @Test
+ public void testEabSetProvisionedValues() throws Exception {
+ ImsManager imsManager = getImsManagerAndInitProvisionedValues();
+
+ assertEquals(true, imsManager.isEabProvisionedOnDevice());
+ verify(mImsConfigImplBaseMock, times(1)).getConfigInt(
+ eq(ImsConfig.ConfigConstants.EAB_SETTING_ENABLED));
+
+ imsManager.getConfigInterface().setProvisionedValue(
+ ImsConfig.ConfigConstants.EAB_SETTING_ENABLED,
+ ImsConfig.FeatureValueConstants.OFF);
+
+ assertEquals(0, (int) mProvisionedIntVals.get(
+ ImsConfig.ConfigConstants.EAB_SETTING_ENABLED));
+
+ assertEquals(false, imsManager.isEabProvisionedOnDevice());
+
+ verify(mImsConfigImplBaseMock, times(1)).setConfig(
+ eq(ImsConfig.ConfigConstants.EAB_SETTING_ENABLED),
+ eq(0));
+ verify(mImsConfigImplBaseMock, times(1)).getConfigInt(
+ eq(ImsConfig.ConfigConstants.EAB_SETTING_ENABLED));
+ }
+
+ /**
+ * Tests that when WFC is enabled/disabled for home/roaming, that setting is sent to the
+ * ImsService correctly.
+ *
+ * Preconditions:
+ * - CarrierConfigManager.KEY_EDITABLE_WFC_MODE_BOOL = true
+ * - CarrierConfigManager.KEY_CARRIER_DEFAULT_WFC_IMS_ROAMING_ENABLED_BOOL = true
+ */
+ @Test @SmallTest
+ public void testSetWfcSetting_true_shouldSetWfcModeWrtRoamingState() throws Exception {
+ // First, Set WFC home/roaming mode that is not the Carrier Config default.
+ doReturn(String.valueOf(ImsConfig.WfcModeFeatureValueConstants.WIFI_PREFERRED))
+ .when(mSubscriptionController).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_MODE),
+ anyString(),
+ nullable(String.class));
+ doReturn(String.valueOf(ImsConfig.WfcModeFeatureValueConstants.CELLULAR_PREFERRED))
+ .when(mSubscriptionController).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_ROAMING_MODE),
+ anyString(),
+ nullable(String.class));
+ ImsManager imsManager = getImsManagerAndInitProvisionedValues();
+
+ // Roaming
+ doReturn(true).when(mTelephonyManager).isNetworkRoaming(eq(mSubId[0]));
+ // Turn on WFC
+ imsManager.setWfcSetting(true);
+ // Roaming mode (CELLULAR_PREFERRED) should be set.
+ verify(mImsConfigImplBaseMock).setConfig(
+ eq(ImsConfig.ConfigConstants.VOICE_OVER_WIFI_MODE),
+ eq(ImsConfig.WfcModeFeatureValueConstants.CELLULAR_PREFERRED));
+ // WFC is enabled, so we should set user roaming setting
+ verify(mImsConfigImplBaseMock).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_ROAMING_ENABLED_OVERRIDE),
+ eq(ProvisioningManager.PROVISIONING_VALUE_ENABLED));
+
+ // Not roaming
+ doReturn(false).when(mTelephonyManager).isNetworkRoaming(eq(mSubId[0]));
+ // Turn on WFC
+ imsManager.setWfcSetting(true);
+ // Home mode (WIFI_PREFERRED) should be set.
+ verify(mImsConfigImplBaseMock).setConfig(
+ eq(ImsConfig.ConfigConstants.VOICE_OVER_WIFI_MODE),
+ eq(ImsConfig.WfcModeFeatureValueConstants.WIFI_PREFERRED));
+ // WFC is enabled, so we should set user roaming setting
+ verify(mImsConfigImplBaseMock, times(2)).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_ROAMING_ENABLED_OVERRIDE),
+ eq(ProvisioningManager.PROVISIONING_VALUE_ENABLED));
+
+
+ // Turn off WFC and ensure that roaming setting is disabled.
+ doReturn(false).when(mTelephonyManager).isNetworkRoaming(eq(mSubId[0]));
+ imsManager.setWfcSetting(false);
+ verify(mImsConfigImplBaseMock).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_ROAMING_ENABLED_OVERRIDE),
+ eq(ProvisioningManager.PROVISIONING_VALUE_DISABLED));
+ }
+
+
+ /**
+ * Tests that when user changed WFC setting while NOT roaming, the home WFC mode is sent to the
+ * modem and the roaming enabled configuration is pushed.
+ *
+ * Preconditions:
+ * - CarrierConfigManager.KEY_EDITABLE_WFC_MODE_BOOL = true
+ * - CarrierConfigManager.KEY_CARRIER_DEFAULT_WFC_IMS_ROAMING_ENABLED_BOOL = true
+ */
+ @Test @SmallTest
+ public void testSetWfcSetting_shouldSetWfcModeRoamingDisabledUserEnabled() throws Exception {
+ // The user has previously enabled "WFC while roaming" setting in UI and then turned WFC
+ // off.
+ doReturn(String.valueOf(1 /*true*/))
+ .when(mSubscriptionController).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_ROAMING_ENABLED),
+ anyString(),
+ nullable(String.class));
+
+ ImsManager imsManager = getImsManagerAndInitProvisionedValues();
+
+ // We are currently on the home network, not roaming.
+ doReturn(false).when(mTelephonyManager).isNetworkRoaming(eq(mSubId[0]));
+
+ // User enables WFC from UI
+ imsManager.setWfcSetting(true /*enabled*/);
+ verify(mImsConfigImplBaseMock).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_MODE_OVERRIDE),
+ eq(ImsMmTelManager.WIFI_MODE_CELLULAR_PREFERRED));
+ verify(mImsConfigImplBaseMock).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_ROAMING_ENABLED_OVERRIDE),
+ // Should be enabled because the user enabled the "WFC while roaming" setting
+ // independent of whether or not we are roaming.
+ eq(ProvisioningManager.PROVISIONING_VALUE_ENABLED));
+ }
+
+ /**
+ * Tests that when user changed WFC setting while roaming, that the correct user setting
+ * is sent to the ImsService when changing the roaming mode.
+ *
+ * Preconditions:
+ * - CarrierConfigManager.KEY_EDITABLE_WFC_MODE_BOOL = true
+ * - CarrierConfigManager.KEY_CARRIER_DEFAULT_WFC_IMS_ROAMING_ENABLED_BOOL = true
+ */
+ @Test @SmallTest
+ public void testSetWfcSetting_shouldSetWfcModeRoamingEnabledUserEnabled() throws Exception {
+ // The user has previously enabled "WFC while roaming" setting in UI and then turned WFC
+ // off.
+ doReturn(String.valueOf(1 /*true*/))
+ .when(mSubscriptionController).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_ROAMING_ENABLED),
+ anyString(),
+ nullable(String.class));
+
+ ImsManager imsManager = getImsManagerAndInitProvisionedValues();
+
+ // The device is currently roaming
+ doReturn(true).when(mTelephonyManager).isNetworkRoaming(eq(mSubId[0]));
+
+ // The user has enabled WFC in the UI while the device is roaming.
+ imsManager.setWfcSetting(true /*enabled*/);
+
+ verify(mImsConfigImplBaseMock).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_MODE_OVERRIDE),
+ // Default for roaming is WFC_IMS_ROAMING_MODE_DEFAULT_VAL
+ eq(ImsMmTelManager.WIFI_MODE_WIFI_PREFERRED));
+ verify(mImsConfigImplBaseMock).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_ROAMING_ENABLED_OVERRIDE),
+ // Should be enabled because user enabled the setting in the UI previously.
+ eq(ProvisioningManager.PROVISIONING_VALUE_ENABLED));
+ }
+
+ /**
+ * Tests that when a WFC mode is updated for home, that setting is sent to the
+ * ImsService correctly or ignored if the roaming mode is changed.
+ *
+ * Preconditions:
+ * - CarrierConfigManager.KEY_EDITABLE_WFC_MODE_BOOL = true
+ * - CarrierConfigManager.KEY_CARRIER_DEFAULT_WFC_IMS_ROAMING_ENABLED_BOOL = true
+ */
+ @Test @SmallTest
+ public void testSetWfcMode_shouldSetWfcModeRoamingDisabled() throws Exception {
+ ImsManager imsManager = getImsManagerAndInitProvisionedValues();
+
+ // the device is not currently roaming
+ doReturn(false).when(mTelephonyManager).isNetworkRoaming(eq(mSubId[0]));
+
+ // set the WFC roaming mode while the device is not roaming, so any changes to roaming mode
+ // should be ignored
+ imsManager.setWfcMode(ImsMmTelManager.WIFI_MODE_CELLULAR_PREFERRED, true /*IsRoaming*/);
+ verify(mImsConfigImplBaseMock, never()).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_MODE_OVERRIDE),
+ anyInt());
+ verify(mImsConfigImplBaseMock, never()).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_ROAMING_ENABLED_OVERRIDE),
+ anyInt());
+
+ // set home WFC mode setting while not roaming, the configuration should be set correctly.
+ imsManager.setWfcMode(ImsMmTelManager.WIFI_MODE_CELLULAR_PREFERRED, false /*IsRoaming*/);
+ verify(mImsConfigImplBaseMock).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_MODE_OVERRIDE),
+ eq(ImsMmTelManager.WIFI_MODE_CELLULAR_PREFERRED));
+ // WiFi Roaming enabled setting is not related to WFC mode
+ verify(mImsConfigImplBaseMock, never()).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_ROAMING_ENABLED_OVERRIDE),
+ anyInt());
+ }
+
+ /**
+ * Tests that when a WFC mode is updated for roaming while WFC is enabled, that setting is sent
+ * to the ImsService correctly when changing the roaming mode or ignored if the home setting is
+ * changed.
+ *
+ * Preconditions:
+ * - CarrierConfigManager.KEY_EDITABLE_WFC_MODE_BOOL = true
+ * - CarrierConfigManager.KEY_CARRIER_DEFAULT_WFC_IMS_ROAMING_ENABLED_BOOL = true
+ */
+ @Test @SmallTest
+ public void testSetWfcMode_wfcEnabledShouldSetWfcModeRoamingEnabled() throws Exception {
+ ImsManager imsManager = getImsManagerAndInitProvisionedValues();
+
+ // The user has previously enabled WFC in the settings UI.
+ doReturn(String.valueOf(1 /*true*/))
+ .when(mSubscriptionController).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_ENABLED),
+ anyString(),
+ nullable(String.class));
+
+ // The device is roaming
+ doReturn(true).when(mTelephonyManager).isNetworkRoaming(eq(mSubId[0]));
+
+ // The carrier app has changed the WFC mode for roaming while the device is home. The
+ // result of this operation is that the neither the WFC mode or the roaming enabled
+ // configuration should change.
+ imsManager.setWfcMode(ImsMmTelManager.WIFI_MODE_CELLULAR_PREFERRED, false /*IsRoaming*/);
+ verify(mImsConfigImplBaseMock, never()).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_MODE_OVERRIDE),
+ anyInt());
+ verify(mImsConfigImplBaseMock, never()).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_ROAMING_ENABLED_OVERRIDE),
+ anyInt());
+
+ // The carrier app has set the WFC mode for roaming while the device is roaming. The
+ // WFC mode should be updated to reflect the roaming setting and the roaming enabled
+ // configuration should be changed to enabled.
+ imsManager.setWfcMode(ImsMmTelManager.WIFI_MODE_CELLULAR_PREFERRED, true /*IsRoaming*/);
+ verify(mImsConfigImplBaseMock).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_MODE_OVERRIDE),
+ eq(ImsMmTelManager.WIFI_MODE_CELLULAR_PREFERRED));
+ // WiFi Roaming enabled setting is not related to WFC mode
+ verify(mImsConfigImplBaseMock, never()).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_ROAMING_ENABLED_OVERRIDE),
+ anyInt());
+ }
+
+ /**
+ * Tests that when a WFC mode is updated for roaming while WFC is disabled, the WFC roaming
+ * setting is always set to disabled.
+ *
+ * Preconditions:
+ * - CarrierConfigManager.KEY_EDITABLE_WFC_MODE_BOOL = true
+ * - CarrierConfigManager.KEY_CARRIER_DEFAULT_WFC_IMS_ROAMING_ENABLED_BOOL = true
+ */
+ @Test @SmallTest
+ public void testSetWfcMode_WfcDisabledShouldNotSetWfcModeRoamingEnabled() throws Exception {
+ ImsManager imsManager = getImsManagerAndInitProvisionedValues();
+
+ // The user has previously disabled WFC in the settings UI.
+ doReturn(String.valueOf(0 /*false*/))
+ .when(mSubscriptionController).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_ENABLED),
+ anyString(),
+ nullable(String.class));
+
+ // The device is roaming
+ doReturn(true).when(mTelephonyManager).isNetworkRoaming(eq(mSubId[0]));
+
+ // WFC is disabled and the carrier app has set the WFC mode for roaming while the device is
+ // roaming. The WFC mode should be updated to reflect the roaming setting and the roaming
+ // enabled configuration should be disabled because WFC is disabled.
+ imsManager.setWfcMode(ImsMmTelManager.WIFI_MODE_CELLULAR_PREFERRED, true /*IsRoaming*/);
+ verify(mImsConfigImplBaseMock).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_MODE_OVERRIDE),
+ eq(ImsMmTelManager.WIFI_MODE_CELLULAR_PREFERRED));
+ // WiFi Roaming enabled setting is not related to WFC mode
+ verify(mImsConfigImplBaseMock, never()).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_ROAMING_ENABLED_OVERRIDE),
+ anyInt());
+ }
+
+ /**
+ * Tests that when user changed WFC mode while not roaming, the new mode is sent to the modem
+ * and roaming enabled indication is sent to the ImsService correctly when changing the roaming
+ * mode.
+ *
+ * Preconditions:
+ * - CarrierConfigManager.KEY_EDITABLE_WFC_MODE_BOOL = true
+ * - CarrierConfigManager.KEY_CARRIER_DEFAULT_WFC_IMS_ROAMING_ENABLED_BOOL = true
+ */
+ @Test @SmallTest
+ public void testSetWfcMode_shouldSetWfcModeRoamingDisabledUserEnabled() throws Exception {
+ // The user has enabled the WFC setting in the UI.
+ doReturn(String.valueOf(1 /*true*/))
+ .when(mSubscriptionController).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_ENABLED),
+ anyString(),
+ nullable(String.class));
+ // The user has enabled the "WFC while roaming" setting in the UI while WFC was enabled
+ doReturn(String.valueOf(1 /*true*/))
+ .when(mSubscriptionController).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_ROAMING_ENABLED),
+ anyString(),
+ nullable(String.class));
+
+ ImsManager imsManager = getImsManagerAndInitProvisionedValues();
+
+ // The device is currently on the home network
+ doReturn(false).when(mTelephonyManager).isNetworkRoaming(eq(mSubId[0]));
+
+ // The user has changed the WFC mode in the UI for the non-roaming configuration
+ imsManager.setWfcMode(ImsMmTelManager.WIFI_MODE_CELLULAR_PREFERRED, false /*IsRoaming*/);
+ verify(mImsConfigImplBaseMock).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_MODE_OVERRIDE),
+ // ensure that the correct cellular preferred config change is sent
+ eq(ImsMmTelManager.WIFI_MODE_CELLULAR_PREFERRED));
+ // WiFi Roaming enabled setting is not related to WFC mode
+ verify(mImsConfigImplBaseMock, never()).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_ROAMING_ENABLED_OVERRIDE),
+ anyInt());
+ }
+
+ /**
+ * Tests that when user changed WFC mode while roaming, that setting is sent to the
+ * ImsService correctly when changing the roaming mode.
+ *
+ * Preconditions:
+ * - CarrierConfigManager.KEY_EDITABLE_WFC_MODE_BOOL = true
+ * - CarrierConfigManager.KEY_CARRIER_DEFAULT_WFC_IMS_ROAMING_ENABLED_BOOL = true
+ */
+ @Test @SmallTest
+ public void testSetWfcMode_shouldSetWfcModeRoamingEnabledUserDisabled() throws Exception {
+ // The user disabled "WFC while roaming" setting in the UI
+ doReturn(String.valueOf(0 /*false*/))
+ .when(mSubscriptionController).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_ROAMING_ENABLED),
+ anyString(),
+ nullable(String.class));
+
+ ImsManager imsManager = getImsManagerAndInitProvisionedValues();
+
+ // the device is currently roaming
+ doReturn(true).when(mTelephonyManager).isNetworkRoaming(eq(mSubId[0]));
+
+ // The carrier app has changed the WFC mode while roaming, so we must set the WFC mode
+ // to the new configuration.
+ imsManager.setWfcMode(ImsMmTelManager.WIFI_MODE_CELLULAR_PREFERRED, true /*IsRoaming*/);
+ verify(mImsConfigImplBaseMock).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_MODE_OVERRIDE),
+ eq(ImsMmTelManager.WIFI_MODE_CELLULAR_PREFERRED));
+ // WiFi Roaming enabled setting is not related to WFC mode
+ verify(mImsConfigImplBaseMock, never()).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_ROAMING_ENABLED_OVERRIDE),
+ anyInt());
+ }
+
+ /**
+ * Tests that the settings for WFC mode are ignored if the Carrier sets the settings to not
+ * editable.
+ *
+ * Preconditions:
+ * - CarrierConfigManager.KEY_EDITABLE_WFC_MODE_BOOL = false
+ */
+ @Test @SmallTest
+ public void testSetWfcSetting_wfcNotEditable() throws Exception {
+ mBundle.putBoolean(CarrierConfigManager.KEY_EDITABLE_WFC_MODE_BOOL,
+ WFC_IMS_NOT_EDITABLE_VAL);
+ // Set some values that are different than the defaults for WFC mode.
+ doReturn(String.valueOf(ImsConfig.WfcModeFeatureValueConstants.WIFI_ONLY))
+ .when(mSubscriptionController).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_MODE),
+ anyString(),
+ nullable(String.class));
+ doReturn(String.valueOf(ImsConfig.WfcModeFeatureValueConstants.WIFI_ONLY))
+ .when(mSubscriptionController).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_ROAMING_MODE),
+ anyString(),
+ nullable(String.class));
+ ImsManager imsManager = getImsManagerAndInitProvisionedValues();
+
+ // Roaming
+ doReturn(true).when(mTelephonyManager).isNetworkRoaming(eq(mSubId[0]));
+ // Turn on WFC
+ imsManager.setWfcSetting(true);
+ // User defined setting for Roaming mode (WIFI_ONLY) should be set independent of whether or
+ // not WFC mode is editable. With 1000 ms timeout.
+ verify(mImsConfigImplBaseMock).setConfig(
+ eq(ImsConfig.ConfigConstants.VOICE_OVER_WIFI_MODE),
+ eq(ImsConfig.WfcModeFeatureValueConstants.WIFI_ONLY));
+
+ // Not roaming
+ doReturn(false).when(mTelephonyManager).isNetworkRoaming(eq(mSubId[0]));
+ // Turn on WFC
+ imsManager.setWfcSetting(true);
+ // Default Home mode (CELLULAR_PREFERRED) should be set. With 1000 ms timeout.
+ verify(mImsConfigImplBaseMock).setConfig(
+ eq(ImsConfig.ConfigConstants.VOICE_OVER_WIFI_MODE),
+ eq(WFC_IMS_MODE_DEFAULT_VAL));
+ }
+
+ /**
+ * Tests that the CarrierConfig defaults will be used if no setting is set in the Subscription
+ * Manager.
+ *
+ * Preconditions:
+ * - CarrierConfigManager.KEY_EDITABLE_WFC_MODE_BOOL = true
+ * - CarrierConfigManager.KEY_CARRIER_DEFAULT_WFC_IMS_MODE_INT = Carrier preferred
+ * - CarrierConfigManager.KEY_CARRIER_DEFAULT_WFC_IMS_ROAMING_MODE_INT = WiFi preferred
+ */
+ @Test @SmallTest
+ public void testSetWfcSetting_noUserSettingSet() throws Exception {
+ ImsManager imsManager = getImsManagerAndInitProvisionedValues();
+
+ // Roaming
+ doReturn(true).when(mTelephonyManager).isNetworkRoaming(eq(mSubId[0]));
+ // Turn on WFC
+ imsManager.setWfcSetting(true);
+
+ // Default Roaming mode (WIFI_PREFERRED) for carrier should be set. With 1000 ms timeout.
+ verify(mImsConfigImplBaseMock).setConfig(
+ eq(ImsConfig.ConfigConstants.VOICE_OVER_WIFI_MODE),
+ eq(WFC_IMS_ROAMING_MODE_DEFAULT_VAL));
+
+ // Not roaming
+ doReturn(false).when(mTelephonyManager).isNetworkRoaming(eq(mSubId[0]));
+ // Turn on WFC
+ imsManager.setWfcSetting(true);
+
+ // Default Home mode (CELLULAR_PREFERRED) for carrier should be set. With 1000 ms timeout.
+ verify(mImsConfigImplBaseMock).setConfig(
+ eq(ImsConfig.ConfigConstants.VOICE_OVER_WIFI_MODE),
+ eq(WFC_IMS_MODE_DEFAULT_VAL));
+ }
+
+ /**
+ * Tests the operation of getWfcMode when the configuration to use the home network mode when
+ * roaming for WFC is false. First, it checks that the user setting for WFC_IMS_ROAMING_MODE is
+ * returned when WFC roaming is set to editable. Then, it switches the WFC roaming mode to not
+ * editable and ensures that the default WFC roaming mode is returned.
+ *
+ * Preconditions:
+ * - CarrierConfigManager.KEY_USE_WFC_HOME_NETWORK_MODE_IN_ROAMING_NETWORK_BOOL = false
+ */
+ @Test @SmallTest
+ public void getWfcMode_useWfcHomeModeConfigFalse_shouldUseWfcRoamingMode() {
+ // Set some values that are different than the defaults for WFC mode.
+ doReturn(String.valueOf(ImsConfig.WfcModeFeatureValueConstants.WIFI_ONLY))
+ .when(mSubscriptionController).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_MODE),
+ anyString(),
+ nullable(String.class));
+ doReturn(String.valueOf(ImsConfig.WfcModeFeatureValueConstants.CELLULAR_PREFERRED))
+ .when(mSubscriptionController).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_ROAMING_MODE),
+ anyString(),
+ nullable(String.class));
+
+ ImsManager imsManager = getImsManagerAndInitProvisionedValues();
+
+ // Check that use the WFC roaming network mode.
+ assertEquals(ImsConfig.WfcModeFeatureValueConstants.CELLULAR_PREFERRED,
+ imsManager.getWfcMode(true));
+ verify(mSubscriptionController, times(1)).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_ROAMING_MODE),
+ anyString(),
+ nullable(String.class));
+
+ // Set WFC roaming network mode to not editable.
+ mBundle.putBoolean(CarrierConfigManager.KEY_EDITABLE_WFC_ROAMING_MODE_BOOL,
+ WFC_IMS_ROAMING_NOT_EDITABLE_VAL);
+
+ // Check that use the default WFC roaming network mode.
+ assertEquals(WFC_IMS_ROAMING_MODE_DEFAULT_VAL, imsManager.getWfcMode(true));
+ verify(mSubscriptionController, times(1)).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_ROAMING_MODE),
+ anyString(),
+ nullable(String.class));
+ }
+
+ /**
+ * Tests the operation of getWfcMode when the configuration to use the home network mode when
+ * roaming for WFC is true independent of whether or not the WFC roaming mode is editable.
+ *
+ * Preconditions:
+ * - CarrierConfigManager.KEY_USE_WFC_HOME_NETWORK_MODE_IN_ROAMING_NETWORK_BOOL = true
+ */
+ @Test @SmallTest
+ public void getWfcMode_useWfcHomeModeConfigTrue_shouldUseWfcHomeMode() {
+ // Set some values that are different than the defaults for WFC mode.
+ doReturn(String.valueOf(ImsConfig.WfcModeFeatureValueConstants.WIFI_ONLY))
+ .when(mSubscriptionController).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_MODE),
+ anyString(),
+ nullable(String.class));
+ doReturn(String.valueOf(ImsConfig.WfcModeFeatureValueConstants.CELLULAR_PREFERRED))
+ .when(mSubscriptionController).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_ROAMING_MODE),
+ anyString(),
+ nullable(String.class));
+
+ // Set to use WFC home network mode in roaming network.
+ mBundle.putBoolean(
+ CarrierConfigManager.KEY_USE_WFC_HOME_NETWORK_MODE_IN_ROAMING_NETWORK_BOOL,
+ WFC_USE_HOME_MODE_FOR_ROAMING_VAL);
+
+ ImsManager imsManager = getImsManagerAndInitProvisionedValues();
+
+ // Check that use the WFC home network mode.
+ assertEquals(ImsConfig.WfcModeFeatureValueConstants.WIFI_ONLY, imsManager.getWfcMode(true));
+ verify(mSubscriptionController, times(1)).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_MODE),
+ anyString(),
+ nullable(String.class));
+
+ // Set WFC home network mode to not editable.
+ mBundle.putBoolean(CarrierConfigManager.KEY_EDITABLE_WFC_MODE_BOOL,
+ WFC_IMS_NOT_EDITABLE_VAL);
+
+ // Check that use the default WFC home network mode.
+ assertEquals(WFC_IMS_MODE_DEFAULT_VAL, imsManager.getWfcMode(true));
+ verify(mSubscriptionController, times(1)).getSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_MODE),
+ anyString(),
+ nullable(String.class));
+ }
+
+ /**
+ * Tests the operation of setWfcRoamingSetting and ensures that the user setting for WFC roaming
+ * and the ImsConfig setting are both called properly.
+ */
+ @Test @SmallTest
+ public void setWfcRoamingSettingTest() {
+ ImsManager imsManager = getImsManagerAndInitProvisionedValues();
+
+ imsManager.setWfcRoamingSetting(true);
+ verify(mSubscriptionController, times(1)).setSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_ROAMING_ENABLED),
+ eq("1"));
+ verify(mImsConfigImplBaseMock).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_ROAMING_ENABLED_OVERRIDE),
+ eq(ProvisioningManager.PROVISIONING_VALUE_ENABLED));
+
+ imsManager.setWfcRoamingSetting(false);
+ verify(mSubscriptionController, times(1)).setSubscriptionProperty(
+ anyInt(),
+ eq(SubscriptionManager.WFC_IMS_ROAMING_ENABLED),
+ eq("0"));
+ verify(mImsConfigImplBaseMock).setConfig(
+ eq(ProvisioningManager.KEY_VOICE_OVER_WIFI_ROAMING_ENABLED_OVERRIDE),
+ eq(ProvisioningManager.PROVISIONING_VALUE_DISABLED));
+
+ }
+
+ private ImsManager getImsManagerAndInitProvisionedValues() {
+ when(mImsConfigImplBaseMock.getConfigInt(anyInt()))
+ .thenAnswer(invocation -> {
+ return getProvisionedInt((Integer) (invocation.getArguments()[0]));
+ });
+
+ when(mImsConfigImplBaseMock.setConfig(anyInt(), anyInt()))
+ .thenAnswer(invocation -> {
+ mProvisionedIntVals.put((Integer) (invocation.getArguments()[0]),
+ (Integer) (invocation.getArguments()[1]));
+ return ImsConfig.OperationStatusConstants.SUCCESS;
+ });
+
+
+ // Configure ImsConfigStub
+ mImsConfigStub = new ImsConfigImplBase.ImsConfigStub(mImsConfigImplBaseMock);
+ doReturn(mImsConfigStub).when(mMmTelFeatureConnection).getConfigInterface();
+
+ // Configure ImsManager
+ ImsManager imsManager = ImsManager.getInstance(mContext, mPhoneId);
+ try {
+ replaceInstance(ImsManager.class, "mMmTelFeatureConnection", imsManager,
+ mMmTelFeatureConnection);
+ } catch (Exception ex) {
+ fail("failed with " + ex);
+ }
+
+ ((ImsManager.ImsExecutorFactory) imsManager.mExecutorFactory).destroy();
+ imsManager.mExecutorFactory = Runnable::run;
+
+ return imsManager;
+ }
+
+ // If the value is ever set, return the set value. If not, return a constant value 1000.
+ private int getProvisionedInt(int item) {
+ if (mProvisionedIntVals.containsKey(item)) {
+ return mProvisionedIntVals.get(item);
+ } else {
+ return ImsConfig.FeatureValueConstants.ON;
+ }
+ }
+
+ // If the value is ever set, return the set value. If not, return a constant value "unset".
+ private String getProvisionedString(int item) {
+ if (mProvisionedStringVals.containsKey(item)) {
+ return mProvisionedStringVals.get(item);
+ } else {
+ return UNSET_PROVISIONED_STRING;
+ }
+ }
+}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/ims/ImsResolverTest.java b/tests/telephonytests/src/com/android/internal/telephony/ims/ImsResolverTest.java
index d5c88e3efc..1770764dfd 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/ims/ImsResolverTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/ims/ImsResolverTest.java
@@ -58,7 +58,6 @@ import android.testing.TestableLooper;
import android.util.ArrayMap;
import android.util.ArraySet;
-import com.android.ims.ImsFeatureBinderRepository;
import com.android.internal.telephony.PhoneConfigurationManager;
import org.junit.After;
@@ -111,8 +110,6 @@ public class ImsResolverTest extends ImsTestBase {
ImsResolver.ImsDynamicQueryManagerFactory mMockQueryManagerFactory;
@Mock
ImsServiceFeatureQueryManager mMockQueryManager;
- @Mock
- ImsFeatureBinderRepository mMockRepo;
private ImsResolver mTestImsResolver;
private BroadcastReceiver mTestPackageBroadcastReceiver;
private BroadcastReceiver mTestCarrierConfigReceiver;
@@ -132,6 +129,8 @@ public class ImsResolverTest extends ImsTestBase {
public void tearDown() throws Exception {
mTestImsResolver.destroy();
mTestImsResolver = null;
+ mLooper.destroy();
+ mLooper = null;
super.tearDown();
}
@@ -192,215 +191,6 @@ public class ImsResolverTest extends ImsTestBase {
}
/**
- * Add a device ImsService and ensure that querying ImsResolver to see if an ImsService is
- * configured succeeds.
- */
- @Test
- @SmallTest
- public void testIsDeviceImsServiceConfigured() throws Exception {
- setupResolver(1 /*numSlots*/, TEST_DEVICE_DEFAULT_NAME.getPackageName(),
- TEST_DEVICE_DEFAULT_NAME.getPackageName());
- HashSet<String> features = new HashSet<>();
- features.add(ImsResolver.METADATA_EMERGENCY_MMTEL_FEATURE);
- features.add(ImsResolver.METADATA_MMTEL_FEATURE);
- features.add(ImsResolver.METADATA_RCS_FEATURE);
- setupPackageQuery(TEST_DEVICE_DEFAULT_NAME, features, true);
- setupController();
-
- // Complete package manager lookup and cache.
- startBindCarrierConfigAlreadySet();
-
- // device package name should be returned for both features.
- final Boolean[] isConfigured = new Boolean[1];
- // Calling this method will block us until the looper processes the command, so use
- // runWithLooper to allow the message to be processed.
- mLooper.runWithLooper(() ->
- isConfigured[0] = mTestImsResolver.isImsServiceConfiguredForFeature(0,
- ImsFeature.FEATURE_MMTEL));
- assertTrue(isConfigured[0]);
- mLooper.runWithLooper(() ->
- isConfigured[0] = mTestImsResolver.isImsServiceConfiguredForFeature(0,
- ImsFeature.FEATURE_RCS));
- assertTrue(isConfigured[0]);
- }
-
- /**
- * Add a device ImsService and ensure that querying the configured ImsService for all features
- * reports the device ImsService.
- */
- @Test
- @SmallTest
- public void testGetConfiguredImsServiceDevice() throws Exception {
- setupResolver(1 /*numSlots*/, TEST_DEVICE_DEFAULT_NAME.getPackageName(),
- TEST_DEVICE_DEFAULT_NAME.getPackageName());
- HashSet<String> features = new HashSet<>();
- features.add(ImsResolver.METADATA_EMERGENCY_MMTEL_FEATURE);
- features.add(ImsResolver.METADATA_MMTEL_FEATURE);
- features.add(ImsResolver.METADATA_RCS_FEATURE);
- setupPackageQuery(TEST_DEVICE_DEFAULT_NAME, features, true);
- setupController();
-
- // Complete package manager lookup and cache.
- startBindCarrierConfigAlreadySet();
-
- // device package name should be returned for both features.
- final String[] packageName = new String[1];
- // Calling this method will block us until the looper processes the command, so use
- // runWithLooper to allow the message to be processed.
- mLooper.runWithLooper(() ->
- packageName[0] = mTestImsResolver.getConfiguredImsServicePackageName(0,
- ImsFeature.FEATURE_MMTEL));
- assertEquals(TEST_DEVICE_DEFAULT_NAME.getPackageName(), packageName[0]);
- mLooper.runWithLooper(() ->
- packageName[0] = mTestImsResolver.getConfiguredImsServicePackageName(0,
- ImsFeature.FEATURE_RCS));
- assertEquals(TEST_DEVICE_DEFAULT_NAME.getPackageName(), packageName[0]);
- }
-
- /**
- * In the case that there is no device or carrier ImsService found, we return null for
- * configuration queries.
- */
- @Test
- @SmallTest
- public void testGetConfiguredImsServiceNoDeviceOrCarrier() throws Exception {
- setupResolver(1 /*numSlots*/, TEST_DEVICE_DEFAULT_NAME.getPackageName(),
- TEST_DEVICE_DEFAULT_NAME.getPackageName());
- // package query returns null
- setupController();
- // Complete package manager lookup and cache.
- startBindCarrierConfigAlreadySet();
-
- // device package name should be returned for both features.
- final String[] packageName = new String[1];
- // Calling this method will block us until the looper processes the command, so use
- // runWithLooper to allow the message to be processed.
- mLooper.runWithLooper(() ->
- packageName[0] = mTestImsResolver.getConfiguredImsServicePackageName(0,
- ImsFeature.FEATURE_MMTEL));
- assertNull(packageName[0]);
- mLooper.runWithLooper(() ->
- packageName[0] = mTestImsResolver.getConfiguredImsServicePackageName(0,
- ImsFeature.FEATURE_RCS));
- assertNull(packageName[0]);
- }
-
- /**
- * In the case that there is no device or carrier ImsService configured, we return null for
- * configuration queries.
- */
- @Test
- @SmallTest
- public void testGetConfiguredImsServiceNoDeviceConfig() throws Exception {
- // device configuration for MMTEL and RCS is null
- setupResolver(1 /*numSlots*/, null, null);
- HashSet<String> features = new HashSet<>();
- features.add(ImsResolver.METADATA_EMERGENCY_MMTEL_FEATURE);
- features.add(ImsResolver.METADATA_MMTEL_FEATURE);
- features.add(ImsResolver.METADATA_RCS_FEATURE);
- // ImsService query does report a device ImsService
- setupPackageQuery(TEST_DEVICE_DEFAULT_NAME, features, true);
- setupController();
- // Complete package manager lookup and cache.
- startBindCarrierConfigAlreadySet();
-
- // device package name should be returned for both features.
- final String[] packageName = new String[1];
- // Calling this method will block us until the looper processes the command, so use
- // runWithLooper to allow the message to be processed.
- mLooper.runWithLooper(() ->
- packageName[0] = mTestImsResolver.getConfiguredImsServicePackageName(0,
- ImsFeature.FEATURE_MMTEL));
- assertNull(packageName[0]);
- mLooper.runWithLooper(() ->
- packageName[0] = mTestImsResolver.getConfiguredImsServicePackageName(0,
- ImsFeature.FEATURE_RCS));
- assertNull(packageName[0]);
- }
-
- /**
- * Add a device and carrier ImsService and ensure that querying the configured ImsService for
- * all features reports the carrier ImsService and not device.
- */
- @Test
- @SmallTest
- public void testGetConfiguredImsServiceCarrier() throws Exception {
- setupResolver(1 /*numSlots*/, TEST_DEVICE_DEFAULT_NAME.getPackageName(),
- TEST_DEVICE_DEFAULT_NAME.getPackageName());
- HashSet<String> features = new HashSet<>();
- features.add(ImsResolver.METADATA_EMERGENCY_MMTEL_FEATURE);
- features.add(ImsResolver.METADATA_MMTEL_FEATURE);
- features.add(ImsResolver.METADATA_RCS_FEATURE);
- setConfigCarrierStringMmTelRcs(0, TEST_CARRIER_DEFAULT_NAME.getPackageName());
- List<ResolveInfo> info = new ArrayList<>();
- info.add(getResolveInfo(TEST_DEVICE_DEFAULT_NAME, features, true));
- info.add(getResolveInfo(TEST_CARRIER_DEFAULT_NAME, new HashSet<>(), true));
- setupPackageQuery(info);
- setupController();
-
- // Complete package manager lookup and cache.
- startBindCarrierConfigAlreadySet();
- // Setup the carrier features and response.
- HashSet<ImsFeatureConfiguration.FeatureSlotPair> carrierFeatures = new HashSet<>();
- carrierFeatures.add(new ImsFeatureConfiguration.FeatureSlotPair(0,
- ImsFeature.FEATURE_MMTEL));
- carrierFeatures.add(new ImsFeatureConfiguration.FeatureSlotPair(0,
- ImsFeature.FEATURE_RCS));
- setupDynamicQueryFeatures(TEST_CARRIER_DEFAULT_NAME, carrierFeatures, 1);
-
- // carrier package name should be returned for both features.
- final String[] packageName = new String[1];
- // Calling this method will block us until the looper processes the command, so use
- // runWithLooper to allow the message to be processed.
- mLooper.runWithLooper(() ->
- packageName[0] = mTestImsResolver.getConfiguredImsServicePackageName(0,
- ImsFeature.FEATURE_MMTEL));
- assertEquals(TEST_CARRIER_DEFAULT_NAME.getPackageName(), packageName[0]);
- mLooper.runWithLooper(() ->
- packageName[0] = mTestImsResolver.getConfiguredImsServicePackageName(0,
- ImsFeature.FEATURE_RCS));
- assertEquals(TEST_CARRIER_DEFAULT_NAME.getPackageName(), packageName[0]);
- }
-
- /**
- * Add a device ImsService and ensure that querying the configured ImsService for all features
- * reports the device ImsService though there is a configuration for carrier (but no cached
- * ImsService).
- */
- @Test
- @SmallTest
- public void testGetConfiguredImsServiceCarrierDevice() throws Exception {
- setupResolver(1 /*numSlots*/, TEST_DEVICE_DEFAULT_NAME.getPackageName(),
- TEST_DEVICE_DEFAULT_NAME.getPackageName());
- HashSet<String> features = new HashSet<>();
- features.add(ImsResolver.METADATA_EMERGENCY_MMTEL_FEATURE);
- features.add(ImsResolver.METADATA_MMTEL_FEATURE);
- features.add(ImsResolver.METADATA_RCS_FEATURE);
- // Carrier service is configured
- setConfigCarrierStringMmTelRcs(0, TEST_CARRIER_DEFAULT_NAME.getPackageName());
- List<ResolveInfo> info = new ArrayList<>();
- // Carrier ImsService is not found during package query.
- info.add(getResolveInfo(TEST_DEVICE_DEFAULT_NAME, features, true));
- setupPackageQuery(info);
- setupController();
-
- // Complete package manager lookup and cache.
- startBindCarrierConfigAlreadySet();
-
- final String[] packageName = new String[1];
- // Calling this method will block us until the looper processes the command, so use
- // runWithLooper to allow the message to be processed.
- mLooper.runWithLooper(() ->
- packageName[0] = mTestImsResolver.getConfiguredImsServicePackageName(0,
- ImsFeature.FEATURE_MMTEL));
- assertEquals(TEST_DEVICE_DEFAULT_NAME.getPackageName(), packageName[0]);
- mLooper.runWithLooper(() ->
- packageName[0] = mTestImsResolver.getConfiguredImsServicePackageName(0,
- ImsFeature.FEATURE_RCS));
- assertEquals(TEST_DEVICE_DEFAULT_NAME.getPackageName(), packageName[0]);
- }
-
- /**
* Set the carrier config override value and ensure that ImsResolver calls .bind on that
* package name with the correct ImsFeatures.
*/
@@ -644,7 +434,7 @@ public class ImsResolverTest extends ImsTestBase {
setConfigCarrierStringMmTelRcs(0, null);
startBindCarrierConfigAlreadySet();
- processAllMessages();
+ mLooper.processAllMessages();
verify(mMockQueryManager, never()).startQuery(any(), any());
verify(controller, never()).bind(any());
verify(controller, never()).unbind();
@@ -671,7 +461,7 @@ public class ImsResolverTest extends ImsTestBase {
startBindNoCarrierConfig(1);
- processAllMessages();
+ mLooper.processAllMessages();
// There is no carrier override set, so make sure that the ImsServiceController binds
// to all SIMs.
@@ -704,7 +494,7 @@ public class ImsResolverTest extends ImsTestBase {
startBindNoCarrierConfig(1);
- processAllMessages();
+ mLooper.processAllMessages();
// There is no carrier override set, so make sure that the ImsServiceController binds
// to all SIMs.
@@ -718,7 +508,7 @@ public class ImsResolverTest extends ImsTestBase {
// Change number of SIMs and verify the features in the ImsServiceController are changed
// as well
PhoneConfigurationManager.notifyMultiSimConfigChange(1);
- processAllMessages();
+ mLooper.processAllMessages();
featureSet = convertToHashSet(features, 0);
verify(controller).changeImsServiceFeatures(featureSet);
verify(controller, never()).unbind();
@@ -746,7 +536,7 @@ public class ImsResolverTest extends ImsTestBase {
startBindNoCarrierConfig(1);
- processAllMessages();
+ mLooper.processAllMessages();
// There is no carrier override set, so make sure that the ImsServiceController binds
// to all SIMs.
@@ -805,7 +595,7 @@ public class ImsResolverTest extends ImsTestBase {
convertToFeatureSlotPairs(0, ImsResolver.METADATA_RCS_FEATURE);
startBindNoCarrierConfig(1);
- processAllMessages();
+ mLooper.processAllMessages();
// ensure that startQuery was called
verify(mMockQueryManager, times(1)).startQuery(eq(TEST_DEVICE_DEFAULT_NAME),
any(String.class));
@@ -815,7 +605,7 @@ public class ImsResolverTest extends ImsTestBase {
mDynamicQueryListener.onComplete(TEST_DEVICE_DEFAULT_NAME, deviceFeatures1);
mDynamicQueryListener.onComplete(TEST_DEVICE2_DEFAULT_NAME, deviceFeatures2);
- processAllMessages();
+ mLooper.processAllMessages();
verify(deviceController, times(2)).bind(eq(deviceFeatures1));
verify(deviceController2, times(1)).bind(eq(deviceFeatures2));
@@ -933,7 +723,7 @@ public class ImsResolverTest extends ImsTestBase {
// Move to single SIM and verify the features in the ImsServiceController are changed as
// well.
PhoneConfigurationManager.notifyMultiSimConfigChange(1);
- processAllMessages();
+ mLooper.processAllMessages();
carrierFeatures = new HashSet<>();
carrierFeatures.add(new ImsFeatureConfiguration.FeatureSlotPair(0, ImsFeature.FEATURE_RCS));
verify(carrierController).changeImsServiceFeatures(carrierFeatures);
@@ -964,7 +754,7 @@ public class ImsResolverTest extends ImsTestBase {
startBindNoCarrierConfig(1);
- processAllMessages();
+ mLooper.processAllMessages();
// There is no carrier override set, so make sure that the ImsServiceController binds
// to all SIMs.
@@ -1039,6 +829,15 @@ public class ImsResolverTest extends ImsTestBase {
mTestImsResolver.imsServiceFeatureCreated(0, ImsFeature.FEATURE_MMTEL, deviceController);
// The carrier override contains this feature
mTestImsResolver.imsServiceFeatureCreated(0, ImsFeature.FEATURE_RCS, carrierController);
+ // Get the IImsServiceControllers for each feature on each slot and verify they are correct.
+ assertEquals(deviceController, mTestImsResolver.getImsServiceControllerAndListen(
+ 1 /*Slot id*/, ImsFeature.FEATURE_MMTEL, null));
+ assertEquals(deviceController, mTestImsResolver.getImsServiceControllerAndListen(
+ 1 /*Slot id*/, ImsFeature.FEATURE_RCS, null));
+ assertEquals(deviceController, mTestImsResolver.getImsServiceControllerAndListen(
+ 0 /*Slot id*/, ImsFeature.FEATURE_MMTEL, null));
+ assertEquals(carrierController, mTestImsResolver.getImsServiceControllerAndListen(
+ 0 /*Slot id*/, ImsFeature.FEATURE_RCS, null));
}
/**
@@ -1581,7 +1380,7 @@ public class ImsResolverTest extends ImsTestBase {
info.add(getResolveInfo(TEST_CARRIER_DEFAULT_NAME, new HashSet<>(), true));
// Boot complete has happened and the carrier ImsService is now available.
mTestBootCompleteReceiver.onReceive(null, new Intent(Intent.ACTION_BOOT_COMPLETED));
- processAllMessages();
+ mLooper.processAllMessages();
setupDynamicQueryFeatures(TEST_CARRIER_DEFAULT_NAME, carrierFeatures, 1);
// Verify that all features that have been defined for the carrier override are bound
@@ -1678,7 +1477,7 @@ public class ImsResolverTest extends ImsTestBase {
assertEquals(TEST_DEVICE_DEFAULT_NAME, deviceController.getComponentName());
mTestImsResolver.imsServiceBindPermanentError(TEST_CARRIER_DEFAULT_NAME);
- processAllMessages();
+ mLooper.processAllMessages();
verify(carrierController).unbind();
// Verify that the device ImsService features are changed to include the ones previously
// taken by the carrier app.
@@ -1709,7 +1508,7 @@ public class ImsResolverTest extends ImsTestBase {
setImsServiceControllerFactory(deviceController1, deviceController2, null, null);
startBindNoCarrierConfig(1);
- processAllMessages();
+ mLooper.processAllMessages();
Set<String> featureResult = new HashSet<>();
featureResult.add(ImsResolver.METADATA_MMTEL_FEATURE);
@@ -1746,7 +1545,7 @@ public class ImsResolverTest extends ImsTestBase {
setImsServiceControllerFactory(deviceController1, deviceController2, null, null);
startBindNoCarrierConfig(1);
- processAllMessages();
+ mLooper.processAllMessages();
Set<String> featureResult = new HashSet<>();
featureResult.add(ImsResolver.METADATA_RCS_FEATURE);
@@ -1787,7 +1586,7 @@ public class ImsResolverTest extends ImsTestBase {
setImsServiceControllerFactory(deviceController1, deviceController2, null, null);
startBindNoCarrierConfig(1);
- processAllMessages();
+ mLooper.processAllMessages();
HashSet<ImsFeatureConfiguration.FeatureSlotPair> featureSet1 =
convertToHashSet(features1, 0);
@@ -1828,7 +1627,7 @@ public class ImsResolverTest extends ImsTestBase {
setImsServiceControllerFactory(deviceController1, deviceController2, null, null);
startBindNoCarrierConfig(1);
- processAllMessages();
+ mLooper.processAllMessages();
verify(deviceController1, never()).bind(any());
verify(deviceController1, never()).unbind();
@@ -1863,20 +1662,25 @@ public class ImsResolverTest extends ImsTestBase {
}
mTestImsResolver = new ImsResolver(mMockContext, deviceMmTelPkgName, deviceRcsPkgName,
- numSlots, mMockRepo);
+ numSlots);
try {
mLooper = new TestableLooper(mTestImsResolver.getHandler().getLooper());
- monitorTestableLooper(mLooper);
} catch (Exception e) {
fail("Unable to create looper from handler.");
}
+ ArgumentCaptor<BroadcastReceiver> receiversCaptor =
+ ArgumentCaptor.forClass(BroadcastReceiver.class);
+ verify(mMockContext, times(3)).registerReceiver(receiversCaptor.capture(), any());
+ mTestPackageBroadcastReceiver = receiversCaptor.getAllValues().get(0);
+ mTestCarrierConfigReceiver = receiversCaptor.getAllValues().get(1);
+ mTestBootCompleteReceiver = receiversCaptor.getAllValues().get(2);
mTestImsResolver.setSubscriptionManagerProxy(mTestSubscriptionManagerProxy);
mTestImsResolver.setTelephonyManagerProxy(mTestTelephonyManagerProxy);
when(mMockQueryManagerFactory.create(any(Context.class),
any(ImsServiceFeatureQueryManager.Listener.class))).thenReturn(mMockQueryManager);
mTestImsResolver.setImsDynamicQueryManagerFactory(mMockQueryManagerFactory);
- processAllMessages();
+ mLooper.processAllMessages();
}
private void setupPackageQuery(List<ResolveInfo> infos) {
@@ -1907,8 +1711,7 @@ public class ImsResolverTest extends ImsTestBase {
@Override
public ImsServiceController create(Context context, ComponentName componentName,
- ImsServiceController.ImsServiceControllerCallbacks callbacks,
- ImsFeatureBinderRepository r) {
+ ImsServiceController.ImsServiceControllerCallbacks callbacks) {
when(controller.getComponentName()).thenReturn(componentName);
return controller;
}
@@ -1922,19 +1725,13 @@ public class ImsResolverTest extends ImsTestBase {
*/
private void startBindCarrierConfigAlreadySet() {
mTestImsResolver.initialize();
- ArgumentCaptor<BroadcastReceiver> receiversCaptor =
- ArgumentCaptor.forClass(BroadcastReceiver.class);
- verify(mMockContext, times(3)).registerReceiver(receiversCaptor.capture(), any());
- mTestPackageBroadcastReceiver = receiversCaptor.getAllValues().get(0);
- mTestCarrierConfigReceiver = receiversCaptor.getAllValues().get(1);
- mTestBootCompleteReceiver = receiversCaptor.getAllValues().get(2);
ArgumentCaptor<ImsServiceFeatureQueryManager.Listener> queryManagerCaptor =
ArgumentCaptor.forClass(ImsServiceFeatureQueryManager.Listener.class);
verify(mMockQueryManagerFactory).create(any(Context.class), queryManagerCaptor.capture());
mDynamicQueryListener = queryManagerCaptor.getValue();
when(mMockQueryManager.startQuery(any(ComponentName.class), any(String.class)))
.thenReturn(true);
- processAllMessages();
+ mLooper.processAllMessages();
}
/**
@@ -1943,17 +1740,11 @@ public class ImsResolverTest extends ImsTestBase {
*/
private void startBindNoCarrierConfig(int numSlots) {
mTestImsResolver.initialize();
- ArgumentCaptor<BroadcastReceiver> receiversCaptor =
- ArgumentCaptor.forClass(BroadcastReceiver.class);
- verify(mMockContext, times(3)).registerReceiver(receiversCaptor.capture(), any());
- mTestPackageBroadcastReceiver = receiversCaptor.getAllValues().get(0);
- mTestCarrierConfigReceiver = receiversCaptor.getAllValues().get(1);
- mTestBootCompleteReceiver = receiversCaptor.getAllValues().get(2);
ArgumentCaptor<ImsServiceFeatureQueryManager.Listener> queryManagerCaptor =
ArgumentCaptor.forClass(ImsServiceFeatureQueryManager.Listener.class);
verify(mMockQueryManagerFactory).create(any(Context.class), queryManagerCaptor.capture());
mDynamicQueryListener = queryManagerCaptor.getValue();
- processAllMessages();
+ mLooper.processAllMessages();
// For ease of testing, slotId = subId
for (int i = 0; i < numSlots; i++) {
sendCarrierConfigChanged(i, i);
@@ -1962,19 +1753,19 @@ public class ImsResolverTest extends ImsTestBase {
private void setupDynamicQueryFeatures(ComponentName name,
HashSet<ImsFeatureConfiguration.FeatureSlotPair> features, int times) {
- processAllMessages();
+ mLooper.processAllMessages();
// ensure that startQuery was called
verify(mMockQueryManager, times(times)).startQuery(eq(name), any(String.class));
mDynamicQueryListener.onComplete(name, features);
- processAllMessages();
+ mLooper.processAllMessages();
}
private void setupDynamicQueryFeaturesFailure(ComponentName name, int times) {
- processAllMessages();
+ mLooper.processAllMessages();
// ensure that startQuery was called
verify(mMockQueryManager, times(times)).startQuery(eq(name), any(String.class));
mDynamicQueryListener.onPermanentError(name);
- processAllMessages();
+ mLooper.processAllMessages();
}
public void packageChanged(String packageName) {
@@ -1984,7 +1775,7 @@ public class ImsResolverTest extends ImsTestBase {
addPackageIntent.setData(new Uri.Builder().scheme("package").opaquePart(packageName)
.build());
mTestPackageBroadcastReceiver.onReceive(null, addPackageIntent);
- processAllMessages();
+ mLooper.processAllMessages();
}
public void packageRemoved(String packageName) {
@@ -1993,7 +1784,7 @@ public class ImsResolverTest extends ImsTestBase {
removePackageIntent.setData(new Uri.Builder().scheme("package")
.opaquePart(TEST_CARRIER_DEFAULT_NAME.getPackageName()).build());
mTestPackageBroadcastReceiver.onReceive(null, removePackageIntent);
- processAllMessages();
+ mLooper.processAllMessages();
}
private void setImsServiceControllerFactory(Map<String, ImsServiceController> controllerMap) {
@@ -2006,8 +1797,7 @@ public class ImsResolverTest extends ImsTestBase {
@Override
public ImsServiceController create(Context context, ComponentName componentName,
- ImsServiceController.ImsServiceControllerCallbacks callbacks,
- ImsFeatureBinderRepository r) {
+ ImsServiceController.ImsServiceControllerCallbacks callbacks) {
return controllerMap.get(componentName.getPackageName());
}
});
@@ -2024,8 +1814,7 @@ public class ImsResolverTest extends ImsTestBase {
@Override
public ImsServiceController create(Context context, ComponentName componentName,
- ImsServiceController.ImsServiceControllerCallbacks callbacks,
- ImsFeatureBinderRepository r) {
+ ImsServiceController.ImsServiceControllerCallbacks callbacks) {
if (TEST_DEVICE_DEFAULT_NAME.getPackageName().equals(
componentName.getPackageName())) {
when(deviceController.getComponentName()).thenReturn(componentName);
@@ -2051,8 +1840,7 @@ public class ImsResolverTest extends ImsTestBase {
@Override
public ImsServiceController create(Context context, ComponentName componentName,
- ImsServiceController.ImsServiceControllerCallbacks callbacks,
- ImsFeatureBinderRepository r) {
+ ImsServiceController.ImsServiceControllerCallbacks callbacks) {
if (TEST_DEVICE_DEFAULT_NAME.getPackageName().equals(
componentName.getPackageName())) {
when(deviceController.getComponentName()).thenReturn(componentName);
@@ -2083,8 +1871,7 @@ public class ImsResolverTest extends ImsTestBase {
@Override
public ImsServiceController create(Context context, ComponentName componentName,
- ImsServiceController.ImsServiceControllerCallbacks callbacks,
- ImsFeatureBinderRepository r) {
+ ImsServiceController.ImsServiceControllerCallbacks callbacks) {
if (TEST_DEVICE_DEFAULT_NAME.getPackageName().equals(
componentName.getPackageName())) {
when(deviceController1.getComponentName()).thenReturn(componentName);
@@ -2113,7 +1900,7 @@ public class ImsResolverTest extends ImsTestBase {
carrierConfigIntent.putExtra(CarrierConfigManager.EXTRA_SUBSCRIPTION_INDEX, subId);
carrierConfigIntent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, slotId);
mTestCarrierConfigReceiver.onReceive(null, carrierConfigIntent);
- processAllMessages();
+ mLooper.processAllMessages();
}
private void setConfigCarrierStringMmTelRcs(int subId, String packageName) {
diff --git a/tests/telephonytests/src/com/android/internal/telephony/ims/ImsServiceControllerTest.java b/tests/telephonytests/src/com/android/internal/telephony/ims/ImsServiceControllerTest.java
index 0d72364c6f..ff17216e3f 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/ims/ImsServiceControllerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/ims/ImsServiceControllerTest.java
@@ -20,8 +20,6 @@ import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.eq;
@@ -36,14 +34,9 @@ import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
-import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.telephony.ims.ImsService;
-import android.telephony.ims.aidl.IImsConfig;
-import android.telephony.ims.aidl.IImsMmTelFeature;
-import android.telephony.ims.aidl.IImsRcsFeature;
-import android.telephony.ims.aidl.IImsRegistration;
import android.telephony.ims.aidl.IImsServiceController;
import android.telephony.ims.feature.ImsFeature;
import android.telephony.ims.stub.ImsFeatureConfiguration;
@@ -51,14 +44,10 @@ import android.test.suitebuilder.annotation.SmallTest;
import androidx.test.runner.AndroidJUnit4;
-import com.android.ims.ImsFeatureBinderRepository;
-import com.android.ims.ImsFeatureContainer;
-import com.android.ims.internal.IImsFeatureStatusCallback;
import com.android.ims.internal.IImsServiceFeatureCallback;
import org.junit.After;
import org.junit.Before;
-import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
@@ -88,64 +77,23 @@ public class ImsServiceControllerTest extends ImsTestBase {
}
};
- private static class TestCallback extends IImsServiceFeatureCallback.Stub {
- public ImsFeatureContainer container;
-
- @Override
- public void imsFeatureCreated(ImsFeatureContainer c) {
- container = c;
- }
-
- @Override
- public void imsFeatureRemoved(int reason) {
- container = null;
- }
-
- @Override
- public void imsStatusChanged(int stat) {
- container.setState(stat);
- }
-
- @Override
- public void updateCapabilities(long caps) {
- container.setCapabilities(caps);
- }
- }
-
- @Mock IImsMmTelFeature mMockMmTelFeature;
- @Mock IBinder mMockMmTelBinder;
- @Mock IImsRcsFeature mMockRcsFeature;
- @Mock IBinder mMockRcsBinder;
- @Mock IImsConfig mMockImsConfig;
- @Mock IImsRegistration mMockRcsRegistration;
-
@Mock IImsServiceController mMockServiceControllerBinder;
@Mock ImsServiceController.ImsServiceControllerCallbacks mMockCallbacks;
+ @Mock IImsServiceFeatureCallback mMockProxyCallbacks;
@Mock Context mMockContext;
private final ComponentName mTestComponentName = new ComponentName("TestPkg",
"ImsServiceControllerTest");
private final Handler mHandler = new Handler(Looper.getMainLooper());
private ImsServiceController mTestImsServiceController;
- private ImsFeatureBinderRepository mRepo;
@Before
@Override
public void setUp() throws Exception {
super.setUp();
- mRepo = new ImsFeatureBinderRepository();
mTestImsServiceController = new ImsServiceController(mMockContext, mTestComponentName,
- mMockCallbacks, mHandler, REBIND_RETRY, mRepo);
+ mMockCallbacks, mHandler, REBIND_RETRY);
+ mTestImsServiceController.addImsServiceFeatureCallback(mMockProxyCallbacks);
when(mMockContext.bindService(any(), any(), anyInt())).thenReturn(true);
- when(mMockServiceControllerBinder.createMmTelFeature(anyInt()))
- .thenReturn(mMockMmTelFeature);
- when(mMockServiceControllerBinder.createRcsFeature(anyInt()))
- .thenReturn(mMockRcsFeature);
- when(mMockServiceControllerBinder.getConfig(anyInt()))
- .thenReturn(mMockImsConfig);
- when(mMockServiceControllerBinder.getRegistration(anyInt()))
- .thenReturn(mMockRcsRegistration);
- when(mMockMmTelFeature.asBinder()).thenReturn(mMockMmTelBinder);
- when(mMockRcsFeature.asBinder()).thenReturn(mMockRcsBinder);
}
@@ -215,73 +163,14 @@ public class ImsServiceControllerTest extends ImsTestBase {
bindAndConnectService(testFeatures);
- verify(mMockServiceControllerBinder).createMmTelFeature(SLOT_0);
- verify(mMockServiceControllerBinder).addFeatureStatusCallback(eq(SLOT_0),
- eq(ImsFeature.FEATURE_MMTEL), any());
- verify(mMockServiceControllerBinder).createRcsFeature(SLOT_0);
- verify(mMockServiceControllerBinder).addFeatureStatusCallback(eq(SLOT_0),
- eq(ImsFeature.FEATURE_RCS), any());
+ verify(mMockServiceControllerBinder).createMmTelFeature(eq(SLOT_0), any());
+ verify(mMockServiceControllerBinder).createRcsFeature(eq(SLOT_0), any());
verify(mMockCallbacks).imsServiceFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL),
eq(mTestImsServiceController));
verify(mMockCallbacks).imsServiceFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_RCS),
eq(mTestImsServiceController));
- validateMmTelFeatureContainerExists(SLOT_0);
- validateRcsFeatureContainerExists(SLOT_0);
- }
-
- /**
- * Tests ImsServiceController keeps SIP delegate creation flags if MMTEL and RCS are supported.
- */
- @SmallTest
- @Test
- public void testBindServiceSipDelegateCapability() throws RemoteException {
- HashSet<ImsFeatureConfiguration.FeatureSlotPair> testFeatures = new HashSet<>();
- testFeatures.add(new ImsFeatureConfiguration.FeatureSlotPair(SLOT_0,
- ImsFeature.FEATURE_MMTEL));
- testFeatures.add(new ImsFeatureConfiguration.FeatureSlotPair(SLOT_0,
- ImsFeature.FEATURE_RCS));
- when(mMockServiceControllerBinder.getImsServiceCapabilities()).thenReturn(
- ImsService.CAPABILITY_SIP_DELEGATE_CREATION);
-
- bindAndConnectService(testFeatures);
-
- verify(mMockServiceControllerBinder).createMmTelFeature(SLOT_0);
- verify(mMockServiceControllerBinder).addFeatureStatusCallback(eq(SLOT_0),
- eq(ImsFeature.FEATURE_MMTEL), any());
- verify(mMockServiceControllerBinder).createRcsFeature(SLOT_0);
- verify(mMockServiceControllerBinder).addFeatureStatusCallback(eq(SLOT_0),
- eq(ImsFeature.FEATURE_RCS), any());
- verify(mMockCallbacks).imsServiceFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL),
- eq(mTestImsServiceController));
- verify(mMockCallbacks).imsServiceFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_RCS),
- eq(mTestImsServiceController));
- validateFeatureContainerExistsWithSipDelegate(ImsFeature.FEATURE_MMTEL, SLOT_0);
- validateFeatureContainerExistsWithSipDelegate(ImsFeature.FEATURE_RCS, SLOT_0);
- }
-
- /**
- * Tests ImsServiceController loses SIP delegate creation flag if MMTEL and RCS are not both
- * supported.
- */
- @Ignore("Disabling for integration b/175766573")
- @SmallTest
- @Test
- public void testBindServiceSipDelegateCapabilityLost() throws RemoteException {
- HashSet<ImsFeatureConfiguration.FeatureSlotPair> testFeatures = new HashSet<>();
- testFeatures.add(new ImsFeatureConfiguration.FeatureSlotPair(SLOT_0,
- ImsFeature.FEATURE_MMTEL));
- when(mMockServiceControllerBinder.getImsServiceCapabilities()).thenReturn(
- ImsService.CAPABILITY_SIP_DELEGATE_CREATION);
-
- bindAndConnectService(testFeatures);
-
- verify(mMockServiceControllerBinder).createMmTelFeature(SLOT_0);
- verify(mMockServiceControllerBinder).addFeatureStatusCallback(eq(SLOT_0),
- eq(ImsFeature.FEATURE_MMTEL), any());
- verify(mMockCallbacks).imsServiceFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL),
- eq(mTestImsServiceController));
- // verify CAPABILITY_SIP_DELEGATE_CREATION is not set because MMTEL and RCS are not set.
- validateFeatureContainerDoesNotHaveSipDelegate(ImsFeature.FEATURE_MMTEL, SLOT_0);
+ verify(mMockProxyCallbacks).imsFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL));
+ verify(mMockProxyCallbacks).imsFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_RCS));
}
/**
@@ -299,16 +188,16 @@ public class ImsServiceControllerTest extends ImsTestBase {
bindAndConnectService(testFeatures);
- verify(mMockServiceControllerBinder).createMmTelFeature(SLOT_0);
- verify(mMockServiceControllerBinder).addFeatureStatusCallback(eq(SLOT_0),
- eq(ImsFeature.FEATURE_MMTEL), any());
+ verify(mMockServiceControllerBinder).createMmTelFeature(eq(SLOT_0), any());
verify(mMockCallbacks).imsServiceFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL),
eq(mTestImsServiceController));
verify(mMockCallbacks).imsServiceFeatureCreated(eq(SLOT_0),
eq(ImsFeature.FEATURE_EMERGENCY_MMTEL), eq(mTestImsServiceController));
// Make sure this callback happens, which will notify the framework of emergency calling
// availability.
- validateMmTelFeatureContainerExistsWithEmergency(SLOT_0);
+ verify(mMockProxyCallbacks).imsFeatureCreated(eq(SLOT_0),
+ eq(ImsFeature.FEATURE_EMERGENCY_MMTEL));
+ verify(mMockProxyCallbacks).imsFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL));
}
/**
@@ -328,21 +217,20 @@ public class ImsServiceControllerTest extends ImsTestBase {
bindAndConnectService(testFeatures);
// Verify no MMTEL or EMERGENCY_MMTEL features are created
- verify(mMockServiceControllerBinder, never()).createMmTelFeature(SLOT_0);
- verify(mMockServiceControllerBinder, never()).addFeatureStatusCallback(eq(SLOT_0),
- eq(ImsFeature.FEATURE_MMTEL), any());
+ verify(mMockServiceControllerBinder, never()).createMmTelFeature(eq(SLOT_0), any());
verify(mMockCallbacks, never()).imsServiceFeatureCreated(eq(SLOT_0),
eq(ImsFeature.FEATURE_MMTEL), eq(mTestImsServiceController));
verify(mMockCallbacks, never()).imsServiceFeatureCreated(eq(SLOT_0),
eq(ImsFeature.FEATURE_EMERGENCY_MMTEL), eq(mTestImsServiceController));
- validateMmTelFeatureContainerDoesntExist(SLOT_0);
+ verify(mMockProxyCallbacks, never()).imsFeatureCreated(eq(SLOT_0),
+ eq(ImsFeature.FEATURE_EMERGENCY_MMTEL));
+ verify(mMockProxyCallbacks, never()).imsFeatureCreated(eq(SLOT_0),
+ eq(ImsFeature.FEATURE_MMTEL));
// verify RCS feature is created
- verify(mMockServiceControllerBinder).createRcsFeature(SLOT_0);
- verify(mMockServiceControllerBinder).addFeatureStatusCallback(eq(SLOT_0),
- eq(ImsFeature.FEATURE_RCS), any());
+ verify(mMockServiceControllerBinder).createRcsFeature(eq(SLOT_0), any());
verify(mMockCallbacks).imsServiceFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_RCS),
eq(mTestImsServiceController));
- validateRcsFeatureContainerExists(SLOT_0);
+ verify(mMockProxyCallbacks).imsFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_RCS));
}
/**
@@ -357,11 +245,16 @@ public class ImsServiceControllerTest extends ImsTestBase {
ImsFeature.FEATURE_EMERGENCY_MMTEL));
testFeatures.add(new ImsFeatureConfiguration.FeatureSlotPair(SLOT_0,
ImsFeature.FEATURE_MMTEL));
+ mTestImsServiceController.removeImsServiceFeatureCallbacks();
bindAndConnectService(testFeatures);
+ // add the callback after bind
+ mTestImsServiceController.addImsServiceFeatureCallback(mMockProxyCallbacks);
- validateMmTelFeatureContainerExistsWithEmergency(SLOT_0);
- validateMmTelFeatureExistsInCallback(SLOT_0, ImsService.CAPABILITY_EMERGENCY_OVER_MMTEL);
+ // Make sure this callback happens for Emergency MMTEL and MMTEL
+ verify(mMockProxyCallbacks).imsFeatureCreated(eq(SLOT_0),
+ eq(ImsFeature.FEATURE_EMERGENCY_MMTEL));
+ verify(mMockProxyCallbacks).imsFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL));
}
/**
@@ -384,72 +277,8 @@ public class ImsServiceControllerTest extends ImsTestBase {
eq(mTestImsServiceController));
verify(mMockCallbacks).imsServiceFeatureRemoved(eq(SLOT_0), eq(ImsFeature.FEATURE_RCS),
eq(mTestImsServiceController));
- validateMmTelFeatureContainerDoesntExist(SLOT_0);
- validateRcsFeatureContainerDoesntExist(SLOT_0);
- }
-
- /**
- * Tests that when unbind is called while the ImsService is disconnected, we still handle
- * unbinding to the service correctly.
- */
- @SmallTest
- @Test
- public void testBindServiceAndConnectedDisconnectedUnbind() throws RemoteException {
- HashSet<ImsFeatureConfiguration.FeatureSlotPair> testFeatures = new HashSet<>();
- testFeatures.add(new ImsFeatureConfiguration.FeatureSlotPair(SLOT_0,
- ImsFeature.FEATURE_MMTEL));
- testFeatures.add(new ImsFeatureConfiguration.FeatureSlotPair(SLOT_0,
- ImsFeature.FEATURE_RCS));
- ServiceConnection conn = bindAndConnectService(testFeatures);
-
- conn.onServiceDisconnected(mTestComponentName);
-
- verify(mMockCallbacks).imsServiceFeatureRemoved(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL),
- eq(mTestImsServiceController));
- verify(mMockCallbacks).imsServiceFeatureRemoved(eq(SLOT_0), eq(ImsFeature.FEATURE_RCS),
- eq(mTestImsServiceController));
- validateMmTelFeatureContainerDoesntExist(SLOT_0);
- validateRcsFeatureContainerDoesntExist(SLOT_0);
-
- mTestImsServiceController.unbind();
- verify(mMockContext).unbindService(eq(conn));
-
- // Even though we unbound, this was already sent after service disconnected, so we shouldn't
- // see it again
- verify(mMockCallbacks, times(1)).imsServiceFeatureRemoved(eq(SLOT_0),
- eq(ImsFeature.FEATURE_MMTEL), eq(mTestImsServiceController));
- verify(mMockCallbacks, times(1)).imsServiceFeatureRemoved(eq(SLOT_0),
- eq(ImsFeature.FEATURE_RCS), eq(mTestImsServiceController));
- }
-
- /**
- * Tests ImsServiceController callbacks are properly called when an ImsService is bound and
- * subsequently unbound.
- */
- @SmallTest
- @Test
- public void testBindMoveToReady() throws RemoteException {
- HashSet<ImsFeatureConfiguration.FeatureSlotPair> testFeatures = new HashSet<>();
- testFeatures.add(new ImsFeatureConfiguration.FeatureSlotPair(SLOT_0,
- ImsFeature.FEATURE_MMTEL));
- TestCallback cb = new TestCallback();
- mRepo.registerForConnectionUpdates(SLOT_0, ImsFeature.FEATURE_MMTEL, cb, Runnable::run);
-
- bindAndConnectService(testFeatures);
-
- verify(mMockServiceControllerBinder).createMmTelFeature(eq(SLOT_0));
- ArgumentCaptor<IImsFeatureStatusCallback> captor =
- ArgumentCaptor.forClass(IImsFeatureStatusCallback.class);
- verify(mMockServiceControllerBinder).addFeatureStatusCallback(eq(SLOT_0),
- eq(ImsFeature.FEATURE_MMTEL), captor.capture());
- IImsFeatureStatusCallback mmtelStatusCb = captor.getValue();
- assertNotNull(mmtelStatusCb);
- validateMmTelFeatureContainerExists(SLOT_0);
- assertEquals(mMockMmTelBinder, cb.container.imsFeature);
- assertEquals(ImsFeature.STATE_UNAVAILABLE, cb.container.getState());
-
- mmtelStatusCb.notifyImsFeatureStatus(ImsFeature.STATE_READY);
- assertEquals(ImsFeature.STATE_READY, cb.container.getState());
+ verify(mMockProxyCallbacks).imsFeatureRemoved(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL));
+ verify(mMockProxyCallbacks).imsFeatureRemoved(eq(SLOT_0), eq(ImsFeature.FEATURE_RCS));
}
/**
@@ -470,19 +299,15 @@ public class ImsServiceControllerTest extends ImsTestBase {
verify(mMockContext).unbindService(eq(conn));
verify(mMockServiceControllerBinder).removeImsFeature(eq(SLOT_0),
- eq(ImsFeature.FEATURE_MMTEL));
- verify(mMockServiceControllerBinder).removeFeatureStatusCallback(eq(SLOT_0),
eq(ImsFeature.FEATURE_MMTEL), any());
verify(mMockServiceControllerBinder).removeImsFeature(eq(SLOT_0),
- eq(ImsFeature.FEATURE_RCS));
- verify(mMockServiceControllerBinder).removeFeatureStatusCallback(eq(SLOT_0),
eq(ImsFeature.FEATURE_RCS), any());
verify(mMockCallbacks).imsServiceFeatureRemoved(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL),
eq(mTestImsServiceController));
verify(mMockCallbacks).imsServiceFeatureRemoved(eq(SLOT_0), eq(ImsFeature.FEATURE_RCS),
eq(mTestImsServiceController));
- validateMmTelFeatureContainerDoesntExist(SLOT_0);
- validateRcsFeatureContainerDoesntExist(SLOT_0);
+ verify(mMockProxyCallbacks).imsFeatureRemoved(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL));
+ verify(mMockProxyCallbacks).imsFeatureRemoved(eq(SLOT_0), eq(ImsFeature.FEATURE_RCS));
}
/**
@@ -500,13 +325,12 @@ public class ImsServiceControllerTest extends ImsTestBase {
conn.onBindingDied(null /*null*/);
- verify(mMockContext).unbindService(eq(conn));
verify(mMockCallbacks).imsServiceFeatureRemoved(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL),
eq(mTestImsServiceController));
verify(mMockCallbacks).imsServiceFeatureRemoved(eq(SLOT_0), eq(ImsFeature.FEATURE_RCS),
eq(mTestImsServiceController));
- validateMmTelFeatureContainerDoesntExist(SLOT_0);
- validateRcsFeatureContainerDoesntExist(SLOT_0);
+ verify(mMockProxyCallbacks).imsFeatureRemoved(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL));
+ verify(mMockProxyCallbacks).imsFeatureRemoved(eq(SLOT_0), eq(ImsFeature.FEATURE_RCS));
}
/**
@@ -525,29 +349,8 @@ public class ImsServiceControllerTest extends ImsTestBase {
verify(mMockCallbacks, never()).imsServiceFeatureCreated(anyInt(), anyInt(),
eq(mTestImsServiceController));
+ verify(mMockProxyCallbacks, never()).imsFeatureCreated(anyInt(), anyInt());
verify(mMockCallbacks).imsServiceBindPermanentError(eq(mTestComponentName));
- validateMmTelFeatureContainerDoesntExist(SLOT_0);
- validateRcsFeatureContainerDoesntExist(SLOT_0);
- }
-
- /**
- * Ensures that ImsServiceController handles a null ImsFeature instance properly.
- */
- @SmallTest
- @Test
- public void testBindServiceAndImsFeatureReturnedNull() throws RemoteException {
- when(mMockServiceControllerBinder.createRcsFeature(anyInt()))
- .thenReturn(null);
- HashSet<ImsFeatureConfiguration.FeatureSlotPair> testFeatures = new HashSet<>();
- testFeatures.add(new ImsFeatureConfiguration.FeatureSlotPair(SLOT_0,
- ImsFeature.FEATURE_RCS));
-
- bindAndConnectService(testFeatures);
-
- verify(mMockServiceControllerBinder).createRcsFeature(SLOT_0);
- verify(mMockCallbacks).imsServiceFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_RCS),
- eq(mTestImsServiceController));
- validateRcsFeatureContainerDoesntExist(SLOT_0);
}
/**
@@ -560,11 +363,10 @@ public class ImsServiceControllerTest extends ImsTestBase {
testFeatures.add(new ImsFeatureConfiguration.FeatureSlotPair(SLOT_0,
ImsFeature.FEATURE_MMTEL));
bindAndConnectService(testFeatures);
- verify(mMockServiceControllerBinder).createMmTelFeature(SLOT_0);
- verify(mMockServiceControllerBinder).addFeatureStatusCallback(eq(SLOT_0),
- eq(ImsFeature.FEATURE_MMTEL), any());
+ verify(mMockServiceControllerBinder).createMmTelFeature(eq(SLOT_0), any());
verify(mMockCallbacks).imsServiceFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL),
eq(mTestImsServiceController));
+ verify(mMockProxyCallbacks).imsFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL));
// Create a new list with an additional item
HashSet<ImsFeatureConfiguration.FeatureSlotPair> testFeaturesWithAddition = new HashSet<>(
testFeatures);
@@ -573,64 +375,10 @@ public class ImsServiceControllerTest extends ImsTestBase {
mTestImsServiceController.changeImsServiceFeatures(testFeaturesWithAddition);
- verify(mMockServiceControllerBinder).createMmTelFeature(SLOT_1);
- verify(mMockServiceControllerBinder).addFeatureStatusCallback(eq(SLOT_1),
- eq(ImsFeature.FEATURE_MMTEL), any());
+ verify(mMockServiceControllerBinder).createMmTelFeature(eq(SLOT_1), any());
verify(mMockCallbacks).imsServiceFeatureCreated(eq(SLOT_1), eq(ImsFeature.FEATURE_MMTEL),
eq(mTestImsServiceController));
- validateMmTelFeatureContainerExists(SLOT_0);
- validateMmTelFeatureContainerExists(SLOT_1);
- }
-
- /**
- * Ensure changes in emergency calling status are tracked
- */
- @SmallTest
- @Test
- public void testBindServiceAndAddRemoveEmergency() throws RemoteException {
- HashSet<ImsFeatureConfiguration.FeatureSlotPair> testFeatures = new HashSet<>();
- testFeatures.add(new ImsFeatureConfiguration.FeatureSlotPair(SLOT_0,
- ImsFeature.FEATURE_MMTEL));
- TestCallback cb = new TestCallback();
- mRepo.registerForConnectionUpdates(SLOT_0, ImsFeature.FEATURE_MMTEL, cb, Runnable::run);
- bindAndConnectService(testFeatures);
- verify(mMockServiceControllerBinder).createMmTelFeature(SLOT_0);
- verify(mMockServiceControllerBinder).addFeatureStatusCallback(eq(SLOT_0),
- eq(ImsFeature.FEATURE_MMTEL), any());
- verify(mMockCallbacks).imsServiceFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL),
- eq(mTestImsServiceController));
- validateMmTelFeatureContainerExists(SLOT_0);
- assertEquals(mMockMmTelBinder, cb.container.imsFeature);
- assertTrue((ImsService.CAPABILITY_EMERGENCY_OVER_MMTEL
- & cb.container.getCapabilities()) == 0);
-
- // Add Emergency calling
- HashSet<ImsFeatureConfiguration.FeatureSlotPair> testFeaturesWithAddition = new HashSet<>(
- testFeatures);
- testFeaturesWithAddition.add(new ImsFeatureConfiguration.FeatureSlotPair(SLOT_0,
- ImsFeature.FEATURE_EMERGENCY_MMTEL));
-
- mTestImsServiceController.changeImsServiceFeatures(testFeaturesWithAddition);
-
- verify(mMockCallbacks).imsServiceFeatureCreated(eq(SLOT_0),
- eq(ImsFeature.FEATURE_EMERGENCY_MMTEL),
- eq(mTestImsServiceController));
- validateMmTelFeatureContainerExistsWithEmergency(SLOT_0);
- assertEquals(mMockMmTelBinder, cb.container.imsFeature);
-
- assertTrue((ImsService.CAPABILITY_EMERGENCY_OVER_MMTEL
- | cb.container.getCapabilities()) > 0);
-
- // Remove Emergency calling
- mTestImsServiceController.changeImsServiceFeatures(testFeatures);
-
- verify(mMockCallbacks).imsServiceFeatureRemoved(eq(SLOT_0),
- eq(ImsFeature.FEATURE_EMERGENCY_MMTEL),
- eq(mTestImsServiceController));
- validateMmTelFeatureContainerExists(SLOT_0);
- assertEquals(mMockMmTelBinder, cb.container.imsFeature);
- assertTrue((ImsService.CAPABILITY_EMERGENCY_OVER_MMTEL
- & cb.container.getCapabilities()) == 0);
+ verify(mMockProxyCallbacks).imsFeatureCreated(eq(SLOT_1), eq(ImsFeature.FEATURE_MMTEL));
}
/**
@@ -644,12 +392,10 @@ public class ImsServiceControllerTest extends ImsTestBase {
testFeatures.add(new ImsFeatureConfiguration.FeatureSlotPair(SLOT_0,
ImsFeature.FEATURE_RCS));
bindAndConnectService(testFeatures);
- verify(mMockServiceControllerBinder).createRcsFeature(SLOT_0);
- verify(mMockServiceControllerBinder).addFeatureStatusCallback(eq(SLOT_0),
- eq(ImsFeature.FEATURE_RCS), any());
+ verify(mMockServiceControllerBinder).createRcsFeature(eq(SLOT_0), any());
verify(mMockCallbacks).imsServiceFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_RCS),
eq(mTestImsServiceController));
- validateRcsFeatureContainerExists(SLOT_0);
+ verify(mMockProxyCallbacks).imsFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_RCS));
// Add FEATURE_EMERGENCY_MMTEL and ensure it doesn't cause MMTEL bind
HashSet<ImsFeatureConfiguration.FeatureSlotPair> testFeaturesWithAddition = new HashSet<>(
testFeatures);
@@ -658,13 +404,12 @@ public class ImsServiceControllerTest extends ImsTestBase {
mTestImsServiceController.changeImsServiceFeatures(testFeaturesWithAddition);
- verify(mMockServiceControllerBinder, never()).createMmTelFeature(SLOT_1);
- verify(mMockServiceControllerBinder, never()).addFeatureStatusCallback(eq(SLOT_1),
- eq(ImsFeature.FEATURE_MMTEL), any());
+ verify(mMockServiceControllerBinder, never()).createMmTelFeature(eq(SLOT_1), any());
verify(mMockCallbacks, never()).imsServiceFeatureCreated(eq(SLOT_1),
eq(ImsFeature.FEATURE_MMTEL),
eq(mTestImsServiceController));
- validateMmTelFeatureContainerDoesntExist(SLOT_1);
+ verify(mMockProxyCallbacks, never()).imsFeatureCreated(eq(SLOT_1),
+ eq(ImsFeature.FEATURE_MMTEL));
}
/**
@@ -678,28 +423,22 @@ public class ImsServiceControllerTest extends ImsTestBase {
testFeatures.add(new ImsFeatureConfiguration.FeatureSlotPair(SLOT_0,
ImsFeature.FEATURE_MMTEL));
bindAndConnectService(testFeatures);
- verify(mMockServiceControllerBinder).createMmTelFeature(SLOT_0);
- verify(mMockServiceControllerBinder).addFeatureStatusCallback(eq(SLOT_0),
- eq(ImsFeature.FEATURE_MMTEL), any());
+ verify(mMockServiceControllerBinder).createMmTelFeature(eq(SLOT_0), any());
verify(mMockCallbacks).imsServiceFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL),
eq(mTestImsServiceController));
- validateMmTelFeatureContainerExists(SLOT_0);
+ verify(mMockProxyCallbacks).imsFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL));
// Call change with the same features and make sure it is disregarded
mTestImsServiceController.changeImsServiceFeatures(testFeatures);
- verify(mMockServiceControllerBinder, times(1)).createMmTelFeature(SLOT_0);
- verify(mMockServiceControllerBinder, times(1)).addFeatureStatusCallback(eq(SLOT_0),
- eq(ImsFeature.FEATURE_MMTEL), any());
- verify(mMockServiceControllerBinder, never()).removeImsFeature(anyInt(), anyInt());
-
-
- verify(mMockServiceControllerBinder, never()).removeFeatureStatusCallback(anyInt(),
- anyInt(), any());
+ verify(mMockServiceControllerBinder, times(1)).createMmTelFeature(eq(SLOT_0), any());
+ verify(mMockServiceControllerBinder, never()).removeImsFeature(anyInt(), anyInt(), any());
verify(mMockCallbacks, times(1)).imsServiceFeatureCreated(eq(SLOT_0),
eq(ImsFeature.FEATURE_MMTEL), eq(mTestImsServiceController));
verify(mMockCallbacks, never()).imsServiceFeatureRemoved(anyInt(), anyInt(), any());
- validateMmTelFeatureContainerExists(SLOT_0);
+ verify(mMockProxyCallbacks, times(1)).imsFeatureCreated(eq(SLOT_0),
+ eq(ImsFeature.FEATURE_MMTEL));
+ verify(mMockProxyCallbacks, never()).imsFeatureRemoved(anyInt(), anyInt());
}
/**
@@ -714,18 +453,14 @@ public class ImsServiceControllerTest extends ImsTestBase {
testFeatures.add(new ImsFeatureConfiguration.FeatureSlotPair(SLOT_1,
ImsFeature.FEATURE_MMTEL));
bindAndConnectService(testFeatures);
- verify(mMockServiceControllerBinder).createMmTelFeature(SLOT_0);
- verify(mMockServiceControllerBinder).addFeatureStatusCallback(eq(SLOT_0),
- eq(ImsFeature.FEATURE_MMTEL), any());
+ verify(mMockServiceControllerBinder).createMmTelFeature(eq(SLOT_0), any());
verify(mMockCallbacks).imsServiceFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL),
eq(mTestImsServiceController));
- verify(mMockServiceControllerBinder).createMmTelFeature(SLOT_1);
- verify(mMockServiceControllerBinder).addFeatureStatusCallback(eq(SLOT_1),
- eq(ImsFeature.FEATURE_MMTEL), any());
+ verify(mMockProxyCallbacks).imsFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL));
+ verify(mMockServiceControllerBinder).createMmTelFeature(eq(SLOT_1), any());
verify(mMockCallbacks).imsServiceFeatureCreated(eq(SLOT_1), eq(ImsFeature.FEATURE_MMTEL),
eq(mTestImsServiceController));
- validateMmTelFeatureContainerExists(SLOT_0);
- validateMmTelFeatureContainerExists(SLOT_1);
+ verify(mMockProxyCallbacks).imsFeatureCreated(eq(SLOT_1), eq(ImsFeature.FEATURE_MMTEL));
// Create a new list with one less item
HashSet<ImsFeatureConfiguration.FeatureSlotPair> testFeaturesWithSubtraction =
new HashSet<>(testFeatures);
@@ -735,13 +470,10 @@ public class ImsServiceControllerTest extends ImsTestBase {
mTestImsServiceController.changeImsServiceFeatures(testFeaturesWithSubtraction);
verify(mMockServiceControllerBinder).removeImsFeature(eq(SLOT_1),
- eq(ImsFeature.FEATURE_MMTEL));
- verify(mMockServiceControllerBinder).removeFeatureStatusCallback(eq(SLOT_1),
eq(ImsFeature.FEATURE_MMTEL), any());
verify(mMockCallbacks).imsServiceFeatureRemoved(eq(SLOT_1), eq(ImsFeature.FEATURE_MMTEL),
eq(mTestImsServiceController));
- validateMmTelFeatureContainerExists(SLOT_0);
- validateMmTelFeatureContainerDoesntExist(SLOT_1);
+ verify(mMockProxyCallbacks).imsFeatureRemoved(eq(SLOT_1), eq(ImsFeature.FEATURE_MMTEL));
}
/**
@@ -756,36 +488,28 @@ public class ImsServiceControllerTest extends ImsTestBase {
testFeatures.add(new ImsFeatureConfiguration.FeatureSlotPair(SLOT_1,
ImsFeature.FEATURE_MMTEL));
bindAndConnectService(testFeatures);
- verify(mMockServiceControllerBinder).createMmTelFeature(SLOT_0);
- verify(mMockServiceControllerBinder).addFeatureStatusCallback(eq(SLOT_0),
- eq(ImsFeature.FEATURE_MMTEL), any());
+ verify(mMockServiceControllerBinder).createMmTelFeature(eq(SLOT_0), any());
verify(mMockCallbacks).imsServiceFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL),
eq(mTestImsServiceController));
- verify(mMockServiceControllerBinder).createMmTelFeature(SLOT_1);
- verify(mMockServiceControllerBinder).addFeatureStatusCallback(eq(SLOT_1),
- eq(ImsFeature.FEATURE_MMTEL), any());
+ verify(mMockProxyCallbacks).imsFeatureCreated(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL));
+ verify(mMockServiceControllerBinder).createMmTelFeature(eq(SLOT_1), any());
verify(mMockCallbacks).imsServiceFeatureCreated(eq(SLOT_1), eq(ImsFeature.FEATURE_MMTEL),
eq(mTestImsServiceController));
- validateMmTelFeatureContainerExists(SLOT_0);
- validateMmTelFeatureContainerExists(SLOT_1);
+ verify(mMockProxyCallbacks).imsFeatureCreated(eq(SLOT_1), eq(ImsFeature.FEATURE_MMTEL));
// Create a new empty list
mTestImsServiceController.changeImsServiceFeatures(new HashSet<>());
verify(mMockServiceControllerBinder).removeImsFeature(eq(SLOT_0),
- eq(ImsFeature.FEATURE_MMTEL));
- verify(mMockServiceControllerBinder).removeFeatureStatusCallback(eq(SLOT_0),
eq(ImsFeature.FEATURE_MMTEL), any());
verify(mMockCallbacks).imsServiceFeatureRemoved(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL),
eq(mTestImsServiceController));
+ verify(mMockProxyCallbacks).imsFeatureRemoved(eq(SLOT_0), eq(ImsFeature.FEATURE_MMTEL));
verify(mMockServiceControllerBinder).removeImsFeature(eq(SLOT_1),
- eq(ImsFeature.FEATURE_MMTEL));
- verify(mMockServiceControllerBinder).removeFeatureStatusCallback(eq(SLOT_1),
eq(ImsFeature.FEATURE_MMTEL), any());
verify(mMockCallbacks).imsServiceFeatureRemoved(eq(SLOT_1), eq(ImsFeature.FEATURE_MMTEL),
eq(mTestImsServiceController));
- validateMmTelFeatureContainerDoesntExist(SLOT_0);
- validateMmTelFeatureContainerDoesntExist(SLOT_1);
+ verify(mMockProxyCallbacks).imsFeatureRemoved(eq(SLOT_1), eq(ImsFeature.FEATURE_MMTEL));
}
/**
@@ -808,13 +532,11 @@ public class ImsServiceControllerTest extends ImsTestBase {
mTestImsServiceController.changeImsServiceFeatures(testFeaturesWithAddition);
- verify(mMockServiceControllerBinder, never()).createRcsFeature(eq(SLOT_0));
- verify(mMockServiceControllerBinder, never()).removeFeatureStatusCallback(eq(SLOT_0),
- eq(ImsFeature.FEATURE_RCS), any());
+ verify(mMockServiceControllerBinder, never()).createRcsFeature(eq(SLOT_0), any());
verify(mMockCallbacks, never()).imsServiceFeatureCreated(eq(SLOT_0),
eq(ImsFeature.FEATURE_RCS), eq(mTestImsServiceController));
- validateMmTelFeatureContainerDoesntExist(SLOT_0);
- validateRcsFeatureContainerDoesntExist(SLOT_0);
+ verify(mMockProxyCallbacks, never()).imsFeatureCreated(eq(SLOT_0),
+ eq(ImsFeature.FEATURE_RCS));
}
/**
@@ -840,30 +562,6 @@ public class ImsServiceControllerTest extends ImsTestBase {
}
/**
- * Due to a bug in ServiceConnection, we will sometimes receive a null binding after the binding
- * dies. Ignore null binding in this case.
- */
- @SmallTest
- @Test
- public void testAutoBindAfterBinderDiedIgnoreNullBinding() throws RemoteException {
- HashSet<ImsFeatureConfiguration.FeatureSlotPair> testFeatures = new HashSet<>();
- testFeatures.add(new ImsFeatureConfiguration.FeatureSlotPair(SLOT_0,
- ImsFeature.FEATURE_MMTEL));
- testFeatures.add(new ImsFeatureConfiguration.FeatureSlotPair(SLOT_0,
- ImsFeature.FEATURE_RCS));
- ServiceConnection conn = bindAndConnectService(testFeatures);
-
- conn.onBindingDied(null);
- // null binding should be ignored in this case.
- conn.onNullBinding(null);
-
- long delay = mTestImsServiceController.getRebindDelay();
- waitForHandlerActionDelayed(mHandler, delay, 2 * delay);
- // The service should autobind after rebind event occurs
- verify(mMockContext, times(2)).bindService(any(), any(), anyInt());
- }
-
- /**
* Ensure that bindService has only been called once before automatic rebind occurs.
*/
@SmallTest
@@ -927,67 +625,6 @@ public class ImsServiceControllerTest extends ImsTestBase {
verify(mMockContext, times(2)).bindService(any(), any(), anyInt());
}
- private void validateMmTelFeatureContainerExists(int slotId) {
-
- ImsFeatureContainer fc =
- mRepo.getIfExists(slotId, ImsFeature.FEATURE_MMTEL).orElse(null);
- assertNotNull("MMTEL FeatureContainer should not be null", fc);
- assertEquals("ImsServiceController did not report MmTelFeature to service repo correctly",
- mMockMmTelBinder, fc.imsFeature);
- assertTrue((ImsService.CAPABILITY_EMERGENCY_OVER_MMTEL & fc.getCapabilities()) == 0);
- }
-
- private void validateMmTelFeatureContainerExistsWithEmergency(int slotId) {
- ImsFeatureContainer fc =
- mRepo.getIfExists(slotId, ImsFeature.FEATURE_MMTEL).orElse(null);
- assertNotNull("MMTEL FeatureContainer should not be null", fc);
- assertEquals("ImsServiceController did not report MmTelFeature to service repo correctly",
- mMockMmTelBinder, fc.imsFeature);
- assertTrue((ImsService.CAPABILITY_EMERGENCY_OVER_MMTEL | fc.getCapabilities()) > 0);
- }
-
- private void validateFeatureContainerExistsWithSipDelegate(int featureType, int slotId) {
- ImsFeatureContainer fc =
- mRepo.getIfExists(slotId, featureType).orElse(null);
- assertNotNull("FeatureContainer should not be null", fc);
- assertTrue((ImsService.CAPABILITY_SIP_DELEGATE_CREATION | fc.getCapabilities()) > 0);
- }
-
- private void validateFeatureContainerDoesNotHaveSipDelegate(int featureType, int slotId) {
- ImsFeatureContainer fc =
- mRepo.getIfExists(slotId, featureType).orElse(null);
- assertNotNull("FeatureContainer should not be null", fc);
- assertEquals(0, (ImsService.CAPABILITY_SIP_DELEGATE_CREATION & fc.getCapabilities()));
- }
-
-
- private void validateMmTelFeatureExistsInCallback(int slotId, long expectedCaps) {
- TestCallback cb = new TestCallback();
- mRepo.registerForConnectionUpdates(slotId, ImsFeature.FEATURE_MMTEL, cb, Runnable::run);
- assertEquals(mMockMmTelBinder, cb.container.imsFeature);
- assertEquals(expectedCaps, cb.container.getCapabilities());
- }
-
- private void validateRcsFeatureContainerExists(int slotId) {
- ImsFeatureContainer fc =
- mRepo.getIfExists(slotId, ImsFeature.FEATURE_RCS).orElse(null);
- assertNotNull("RCS FeatureContainer should not be null", fc);
- assertEquals("ImsServiceController did not report RcsFeature to service repo correctly",
- mMockRcsBinder, fc.imsFeature);
- }
-
- private void validateMmTelFeatureContainerDoesntExist(int slotId) {
- ImsFeatureContainer fc =
- mRepo.getIfExists(slotId, ImsFeature.FEATURE_MMTEL).orElse(null);
- assertNull("FeatureContainer should be null", fc);
- }
-
- private void validateRcsFeatureContainerDoesntExist(int slotId) {
- ImsFeatureContainer fc =
- mRepo.getIfExists(slotId, ImsFeature.FEATURE_RCS).orElse(null);
- assertNull("FeatureContainer should be null", fc);
- }
-
private void bindAndNullServiceError(
HashSet<ImsFeatureConfiguration.FeatureSlotPair> testFeatures) {
ServiceConnection connection = bindService(testFeatures);
diff --git a/tests/telephonytests/src/com/android/internal/telephony/ims/ImsTestBase.java b/tests/telephonytests/src/com/android/internal/telephony/ims/ImsTestBase.java
index 086390ad98..ad8cd47469 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/ims/ImsTestBase.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/ims/ImsTestBase.java
@@ -16,19 +16,14 @@
package com.android.internal.telephony.ims;
-import static org.junit.Assert.fail;
-
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
-import android.testing.TestableLooper;
import androidx.test.InstrumentationRegistry;
import org.mockito.MockitoAnnotations;
-import java.util.ArrayList;
-import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -38,8 +33,6 @@ import java.util.concurrent.TimeUnit;
public class ImsTestBase {
protected Context mContext;
- protected List<TestableLooper> mTestableLoopers = new ArrayList<>();
- protected TestableLooper mTestableLooper;
public void setUp() throws Exception {
mContext = InstrumentationRegistry.getTargetContext();
@@ -48,16 +41,9 @@ public class ImsTestBase {
if (Looper.myLooper() == null) {
Looper.prepare();
}
- mTestableLooper = TestableLooper.get(ImsTestBase.this);
- monitorTestableLooper(mTestableLooper);
}
public void tearDown() throws Exception {
- unmonitorTestableLooper(mTestableLooper);
- for (TestableLooper looper : mTestableLoopers) {
- looper.destroy();
- }
- TestableLooper.remove(ImsTestBase.this);
}
protected final void waitForHandlerAction(Handler h, long timeoutMillis) {
@@ -75,49 +61,4 @@ public class ImsTestBase {
}
}
}
-
- /**
- * Add a TestableLooper to the list of monitored loopers
- * @param looper looper to be added if it doesn't already exist
- */
- public void monitorTestableLooper(TestableLooper looper) {
- if (looper != null && !mTestableLoopers.contains(looper)) {
- mTestableLoopers.add(looper);
- }
- }
-
- /**
- * Remove a TestableLooper from the list of monitored loopers
- * @param looper looper to be removed if it exists
- */
- public void unmonitorTestableLooper(TestableLooper looper) {
- if (looper != null && mTestableLoopers.contains(looper)) {
- mTestableLoopers.remove(looper);
- }
- }
-
- /**
- * Process all messages at the current time for all monitored TestableLoopers
- */
- public void processAllMessages() {
- if (mTestableLoopers.isEmpty()) {
- fail("mTestableLoopers is empty. Please make sure to add @RunWithLooper annotation");
- }
- while (!areAllTestableLoopersIdle()) {
- for (TestableLooper looper : mTestableLoopers) looper.processAllMessages();
- }
- }
-
- /**
- * Check if there are any messages to be processed in any monitored TestableLooper
- * Delayed messages to be handled at a later time will be ignored
- * @return true if there are no messages that can be handled at the current time
- * across all monitored TestableLoopers
- */
- private boolean areAllTestableLoopersIdle() {
- for (TestableLooper looper : mTestableLoopers) {
- if (!looper.getLooper().getQueue().isIdle()) return false;
- }
- return true;
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/ims/ImsUtTest.java b/tests/telephonytests/src/com/android/internal/telephony/ims/ImsUtTest.java
new file mode 100644
index 0000000000..4948a67a33
--- /dev/null
+++ b/tests/telephonytests/src/com/android/internal/telephony/ims/ImsUtTest.java
@@ -0,0 +1,153 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.telephony.ims;
+
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertNotNull;
+import static junit.framework.TestCase.fail;
+
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.verify;
+
+import android.os.AsyncResult;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.Message;
+import android.telephony.ims.ImsSsInfo;
+import android.telephony.ims.ImsUtListener;
+import android.testing.AndroidTestingRunner;
+import android.testing.TestableLooper;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.ims.ImsUt;
+import com.android.ims.internal.IImsUt;
+import com.android.internal.telephony.TelephonyTest;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+
+@RunWith(AndroidTestingRunner.class)
+@TestableLooper.RunWithLooper
+public class ImsUtTest extends TelephonyTest {
+
+ private static final int MSG_QUERY = 1;
+ private static final int TEST_TIMEOUT_MS = 5000;
+
+ private class TestHandler extends Handler {
+
+ TestHandler(Looper looper) {
+ super(looper);
+ }
+
+ private final LinkedBlockingQueue<ImsSsInfo> mPendingSsInfos = new LinkedBlockingQueue<>(1);
+ @Override
+ public void handleMessage(Message msg) {
+ if (msg.what == MSG_QUERY) {
+ AsyncResult ar = (AsyncResult) msg.obj;
+ mPendingSsInfos.offer((ImsSsInfo) ar.result);
+ }
+ }
+ public ImsSsInfo getPendingImsSsInfo() {
+ try {
+ return mPendingSsInfos.poll(TEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException e) {
+ fail("test interrupted!");
+ }
+ return null;
+ }
+ }
+
+ @Mock IImsUt mImsUtBinder;
+
+ private TestHandler mHandler;
+
+ @Before
+ public void setUp() throws Exception {
+ super.setUp("ImsUtTest");
+ mHandler = new TestHandler(Looper.myLooper());
+ processAllMessages();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ @Test
+ @SmallTest
+ public void testClirConversionCompat() throws Exception {
+ ArgumentCaptor<ImsUt.IImsUtListenerProxy> captor =
+ ArgumentCaptor.forClass(ImsUt.IImsUtListenerProxy.class);
+ ImsUt mImsUt = new ImsUt(mImsUtBinder);
+ verify(mImsUtBinder).setListener(captor.capture());
+ ImsUt.IImsUtListenerProxy proxy = captor.getValue();
+ assertNotNull(proxy);
+
+ doReturn(2).when(mImsUtBinder).queryCLIR();
+ mImsUt.queryCLIR(Message.obtain(mHandler, MSG_QUERY));
+
+ Bundle result = new Bundle();
+ result.putIntArray(ImsUtListener.BUNDLE_KEY_CLIR, new int[] {
+ ImsSsInfo.CLIR_OUTGOING_INVOCATION, ImsSsInfo.CLIR_STATUS_PROVISIONED_PERMANENT});
+ // This is deprecated, will be converted from Bundle -> ImsSsInfo
+ proxy.utConfigurationQueried(null, 2 /*id*/, result);
+ processAllMessages();
+
+
+ ImsSsInfo info = mHandler.getPendingImsSsInfo();
+ assertNotNull(info);
+ assertEquals(ImsSsInfo.CLIR_OUTGOING_INVOCATION, info.getClirOutgoingState());
+ assertEquals(ImsSsInfo.CLIR_STATUS_PROVISIONED_PERMANENT,
+ info.getClirInterrogationStatus());
+ }
+
+ @Test
+ @SmallTest
+ public void testClipConversionCompat() throws Exception {
+ ArgumentCaptor<ImsUt.IImsUtListenerProxy> captor =
+ ArgumentCaptor.forClass(ImsUt.IImsUtListenerProxy.class);
+ ImsUt mImsUt = new ImsUt(mImsUtBinder);
+ verify(mImsUtBinder).setListener(captor.capture());
+ ImsUt.IImsUtListenerProxy proxy = captor.getValue();
+ assertNotNull(proxy);
+
+ doReturn(2).when(mImsUtBinder).queryCLIP();
+ mImsUt.queryCLIP(Message.obtain(mHandler, MSG_QUERY));
+
+ ImsSsInfo info = new ImsSsInfo.Builder(ImsSsInfo.ENABLED).setProvisionStatus(
+ ImsSsInfo.CLIR_STATUS_PROVISIONED_PERMANENT).build();
+ Bundle result = new Bundle();
+ result.putParcelable(ImsUtListener.BUNDLE_KEY_SSINFO, info);
+ // This is deprecated, will be converted from Bundle -> ImsSsInfo
+ proxy.utConfigurationQueried(null, 2 /*id*/, result);
+ processAllMessages();
+
+ ImsSsInfo resultInfo = mHandler.getPendingImsSsInfo();
+ assertNotNull(resultInfo);
+ assertEquals(info.getStatus(), resultInfo.getStatus());
+ assertEquals(info.getProvisionStatus(), resultInfo.getProvisionStatus());
+ }
+}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/ims/MmTelFeatureConnectionTest.java b/tests/telephonytests/src/com/android/internal/telephony/ims/MmTelFeatureConnectionTest.java
new file mode 100644
index 0000000000..87b8a56896
--- /dev/null
+++ b/tests/telephonytests/src/com/android/internal/telephony/ims/MmTelFeatureConnectionTest.java
@@ -0,0 +1,296 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.telephony.ims;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
+import android.content.Context;
+import android.os.Binder;
+import android.os.IBinder;
+import android.os.IInterface;
+import android.os.Looper;
+import android.telephony.SubscriptionInfo;
+import android.telephony.SubscriptionManager;
+import android.test.suitebuilder.annotation.SmallTest;
+
+import com.android.ims.ImsCallbackAdapterManager;
+import com.android.internal.telephony.TelephonyTest;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class MmTelFeatureConnectionTest extends TelephonyTest {
+
+ private class TestCallback extends Binder implements IInterface {
+
+ @Override
+ public IBinder asBinder() {
+ return this;
+ }
+ }
+
+ private class CallbackManagerTest extends
+ ImsCallbackAdapterManager<TestCallback> {
+
+ List<TestCallback> mCallbacks = new ArrayList<>();
+
+ CallbackManagerTest(Context context, Object lock) {
+ super(context, lock, 0 /*slotId*/);
+ }
+
+ // A callback has been registered. Register that callback with the MmTelFeature.
+ @Override
+ public void registerCallback(TestCallback localCallback) {
+ mCallbacks.add(localCallback);
+ }
+
+ // A callback has been removed, unregister that callback with the MmTelFeature.
+ @Override
+ public void unregisterCallback(TestCallback localCallback) {
+ mCallbacks.remove(localCallback);
+ }
+
+ public boolean doesCallbackExist(TestCallback callback) {
+ return mCallbacks.contains(callback);
+ }
+ }
+ private CallbackManagerTest mCallbackManagerUT;
+
+ @Before
+ public void setUp() throws Exception {
+ super.setUp("MmTelFeatureConnectionTest");
+ if (Looper.myLooper() == null) {
+ Looper.prepare();
+ }
+ mCallbackManagerUT = new CallbackManagerTest(mContext, this);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ mCallbackManagerUT = null;
+ super.tearDown();
+ }
+
+ /**
+ * Basic test of deprecated functionality, ensure that adding the callback directly triggers the
+ * appropriate registerCallback and unregisterCallback calls.
+ */
+ @Test
+ @SmallTest
+ public void testCallbackAdapter_addAndRemoveCallback() throws Exception {
+ TestCallback testCallback = new TestCallback();
+ mCallbackManagerUT.addCallback(testCallback);
+ assertTrue(mCallbackManagerUT.doesCallbackExist(testCallback));
+ // The subscriptions changed listener should only be added for callbacks that are being
+ // linked to a subscription.
+ verify(mSubscriptionManager, never()).addOnSubscriptionsChangedListener(
+ any(SubscriptionManager.OnSubscriptionsChangedListener.class));
+
+ mCallbackManagerUT.removeCallback(testCallback);
+ assertFalse(mCallbackManagerUT.doesCallbackExist(testCallback));
+ // The subscriptions changed listener should only be removed for callbacks that are
+ // linked to a subscription.
+ verify(mSubscriptionManager, never()).removeOnSubscriptionsChangedListener(
+ any(SubscriptionManager.OnSubscriptionsChangedListener.class));
+ }
+
+ /**
+ * Ensure that adding the callback and linking subId triggers the appropriate registerCallback
+ * and unregisterCallback calls as well as the subscriptionChanged listener.
+ */
+ @Test
+ @SmallTest
+ public void testCallbackAdapter_addAndRemoveCallbackForSub() throws Exception {
+ TestCallback testCallback = new TestCallback();
+ int testSub = 1;
+ mCallbackManagerUT.addCallbackForSubscription(testCallback, testSub);
+ assertTrue(mCallbackManagerUT.doesCallbackExist(testCallback));
+ verify(mSubscriptionManager, times(1)).addOnSubscriptionsChangedListener(
+ any(SubscriptionManager.OnSubscriptionsChangedListener.class));
+
+ mCallbackManagerUT.removeCallbackForSubscription(testCallback, testSub);
+ assertFalse(mCallbackManagerUT.doesCallbackExist(testCallback));
+ verify(mSubscriptionManager, times(1)).removeOnSubscriptionsChangedListener(
+ any(SubscriptionManager.OnSubscriptionsChangedListener.class));
+ }
+
+ /**
+ * Ensure that adding the callback and linking multiple subIds trigger the appropriate
+ * registerCallback and unregisterCallback calls as well as the subscriptionChanged listener.
+ * When removing the callbacks, the subscriptionChanged listener shoud only be removed when all
+ * callbacks have been removed.
+ */
+ @Test
+ @SmallTest
+ public void testCallbackAdapter_addAndRemoveCallbackForMultipleSubs() throws Exception {
+ TestCallback testCallback1 = new TestCallback();
+ TestCallback testCallback2 = new TestCallback();
+ int testSub1 = 1;
+ int testSub2 = 2;
+ mCallbackManagerUT.addCallbackForSubscription(testCallback1, testSub1);
+ assertTrue(mCallbackManagerUT.doesCallbackExist(testCallback1));
+ mCallbackManagerUT.addCallbackForSubscription(testCallback2, testSub2);
+ assertTrue(mCallbackManagerUT.doesCallbackExist(testCallback2));
+ // This should only happen once.
+ verify(mSubscriptionManager, times(1)).addOnSubscriptionsChangedListener(
+ any(SubscriptionManager.OnSubscriptionsChangedListener.class));
+
+ mCallbackManagerUT.removeCallbackForSubscription(testCallback1, testSub1);
+ assertFalse(mCallbackManagerUT.doesCallbackExist(testCallback1));
+ // removing the listener should not happen until the second callback is removed.
+ verify(mSubscriptionManager, never()).removeOnSubscriptionsChangedListener(
+ any(SubscriptionManager.OnSubscriptionsChangedListener.class));
+
+ mCallbackManagerUT.removeCallbackForSubscription(testCallback2, testSub2);
+ assertFalse(mCallbackManagerUT.doesCallbackExist(testCallback2));
+ verify(mSubscriptionManager, times(1)).removeOnSubscriptionsChangedListener(
+ any(SubscriptionManager.OnSubscriptionsChangedListener.class));
+ }
+
+ /**
+ * The subscriptions have changed, ensure that the callbacks registered to the original
+ * subscription testSub1 are removed, while keeping the callbacks for testSub2, since it was not
+ * removed.
+ */
+ @Test
+ @SmallTest
+ public void testCallbackAdapter_onSubscriptionsChangedMultipleSubs() throws Exception {
+ TestCallback testCallback1 = new TestCallback();
+ TestCallback testCallback2 = new TestCallback();
+ int testSub1 = 1;
+ int testSub2 = 2;
+ int testSub3 = 3;
+ mCallbackManagerUT.addCallbackForSubscription(testCallback1, testSub1);
+ assertTrue(mCallbackManagerUT.doesCallbackExist(testCallback1));
+ mCallbackManagerUT.addCallbackForSubscription(testCallback2, testSub2);
+ assertTrue(mCallbackManagerUT.doesCallbackExist(testCallback2));
+ verify(mSubscriptionManager, times(1)).addOnSubscriptionsChangedListener(
+ any(SubscriptionManager.OnSubscriptionsChangedListener.class));
+
+ // Simulate subscriptions changed, where testSub1 is no longer active
+ doReturn(createSubscriptionInfoList(new int[] {testSub2, testSub3}))
+ .when(mSubscriptionManager).getActiveSubscriptionInfoList(anyBoolean());
+ mCallbackManagerUT.mSubChangedListener.onSubscriptionsChanged();
+ assertFalse(mCallbackManagerUT.doesCallbackExist(testCallback1));
+ // verify that the subscription changed listener is not removed, since we still have a
+ // callback on testSub2
+ verify(mSubscriptionManager, never()).removeOnSubscriptionsChangedListener(
+ any(SubscriptionManager.OnSubscriptionsChangedListener.class));
+ }
+
+ /**
+ * The active subscription has changed, ensure that the callback registered to the original
+ * subscription testSub1 are removed as well as the subscription changed listener, since
+ * there are mo more active callbacks.
+ */
+ @Test
+ @SmallTest
+ public void testCallbackAdapter_onSubscriptionsChangedOneSub() throws Exception {
+ TestCallback testCallback1 = new TestCallback();
+ int testSub1 = 1;
+ int testSub2 = 2;
+ mCallbackManagerUT.addCallbackForSubscription(testCallback1, testSub1);
+ assertTrue(mCallbackManagerUT.doesCallbackExist(testCallback1));
+ verify(mSubscriptionManager, times(1)).addOnSubscriptionsChangedListener(
+ any(SubscriptionManager.OnSubscriptionsChangedListener.class));
+
+ // Simulate subscriptions changed, where testSub1 is no longer active
+ doReturn(createSubscriptionInfoList(new int[] {testSub2}))
+ .when(mSubscriptionManager).getActiveSubscriptionInfoList(anyBoolean());
+ mCallbackManagerUT.mSubChangedListener.onSubscriptionsChanged();
+ assertFalse(mCallbackManagerUT.doesCallbackExist(testCallback1));
+ // verify that the subscription listener is removed, since the only active callback has been
+ // removed.
+ verify(mSubscriptionManager, times(1)).removeOnSubscriptionsChangedListener(
+ any(SubscriptionManager.OnSubscriptionsChangedListener.class));
+ }
+
+ /**
+ * The close() method has been called, so al callbacks should be cleaned up and notified
+ * that they have been removed. The subscriptions changed listener should also be removed.
+ */
+ @Test
+ @SmallTest
+ public void testCallbackAdapter_closeMultipleSubs() throws Exception {
+ TestCallback testCallback1 = new TestCallback();
+ TestCallback testCallback2 = new TestCallback();
+ int testSub1 = 1;
+ int testSub2 = 2;
+ mCallbackManagerUT.addCallbackForSubscription(testCallback1, testSub1);
+ assertTrue(mCallbackManagerUT.doesCallbackExist(testCallback1));
+ mCallbackManagerUT.addCallbackForSubscription(testCallback2, testSub2);
+ assertTrue(mCallbackManagerUT.doesCallbackExist(testCallback2));
+ verify(mSubscriptionManager, times(1)).addOnSubscriptionsChangedListener(
+ any(SubscriptionManager.OnSubscriptionsChangedListener.class));
+
+ // Close the manager, ensure all subscription callbacks are removed
+ mCallbackManagerUT.close();
+ assertFalse(mCallbackManagerUT.doesCallbackExist(testCallback1));
+ assertFalse(mCallbackManagerUT.doesCallbackExist(testCallback2));
+ // verify that the subscription changed listener is removed.
+ verify(mSubscriptionManager, times(1)).removeOnSubscriptionsChangedListener(
+ any(SubscriptionManager.OnSubscriptionsChangedListener.class));
+ }
+
+ /**
+ * The close() method has been called, so all callbacks should be cleaned up. Since they are
+ * not associated with any subscriptions, no subscription based logic should be called.
+ */
+ @Test
+ @SmallTest
+ public void testCallbackAdapter_closeSlotBasedCallbacks() throws Exception {
+ TestCallback testCallback1 = new TestCallback();
+ TestCallback testCallback2 = new TestCallback();
+ mCallbackManagerUT.addCallback(testCallback1);
+ assertTrue(mCallbackManagerUT.doesCallbackExist(testCallback1));
+ mCallbackManagerUT.addCallback(testCallback2);
+ assertTrue(mCallbackManagerUT.doesCallbackExist(testCallback2));
+ // verify that the subscription changed listener is never called for these callbacks
+ // because they are not associated with any subscriptions.
+ verify(mSubscriptionManager, never()).addOnSubscriptionsChangedListener(
+ any(SubscriptionManager.OnSubscriptionsChangedListener.class));
+
+ // Close the manager, ensure all subscription callbacks are removed
+ mCallbackManagerUT.close();
+ assertFalse(mCallbackManagerUT.doesCallbackExist(testCallback1));
+ assertFalse(mCallbackManagerUT.doesCallbackExist(testCallback2));
+ // verify that the subscription changed removed method is never called
+ verify(mSubscriptionManager, never()).removeOnSubscriptionsChangedListener(
+ any(SubscriptionManager.OnSubscriptionsChangedListener.class));
+ }
+
+ private List<SubscriptionInfo> createSubscriptionInfoList(int[] subIds) {
+ List<SubscriptionInfo> infos = new ArrayList<>();
+ for (int i = 0; i < subIds.length; i++) {
+ SubscriptionInfo info = new SubscriptionInfo(subIds[i], null, -1, null, null, -1, -1,
+ null, -1, null, null, null, null, false, null, null);
+ infos.add(info);
+ }
+ return infos;
+ }
+}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/ims/TestImsServiceControllerAdapter.java b/tests/telephonytests/src/com/android/internal/telephony/ims/TestImsServiceControllerAdapter.java
new file mode 100644
index 0000000000..38b3203ddf
--- /dev/null
+++ b/tests/telephonytests/src/com/android/internal/telephony/ims/TestImsServiceControllerAdapter.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.telephony.ims;
+
+import android.os.RemoteException;
+import android.telephony.ims.aidl.IImsConfig;
+import android.telephony.ims.aidl.IImsMmTelFeature;
+import android.telephony.ims.aidl.IImsRcsFeature;
+import android.telephony.ims.aidl.IImsRegistration;
+import android.telephony.ims.aidl.IImsServiceController;
+import android.telephony.ims.aidl.IImsServiceControllerListener;
+import android.telephony.ims.stub.ImsConfigImplBase;
+import android.telephony.ims.stub.ImsFeatureConfiguration;
+import android.telephony.ims.stub.ImsRegistrationImplBase;
+
+import com.android.ims.internal.IImsFeatureStatusCallback;
+
+import static org.mockito.Mockito.spy;
+
+/**
+ * Test base implementation of the ImsServiceController, which is used as a mockito spy.
+ */
+
+public class TestImsServiceControllerAdapter {
+
+ public IImsFeatureStatusCallback mStatusCallback;
+
+ public class ImsServiceControllerBinder extends IImsServiceController.Stub {
+
+ @Override
+ public void setListener(IImsServiceControllerListener l) {
+ }
+
+ @Override
+ public IImsMmTelFeature createMmTelFeature(int slotId, IImsFeatureStatusCallback c) {
+ return TestImsServiceControllerAdapter.this.createMMTelFeature(slotId);
+ }
+
+ @Override
+ public IImsRcsFeature createRcsFeature(int slotId, IImsFeatureStatusCallback c) {
+ return TestImsServiceControllerAdapter.this.createRcsFeature(slotId);
+ }
+
+ @Override
+ public void removeImsFeature(int slotId, int featureType, IImsFeatureStatusCallback c)
+ throws RemoteException {
+ TestImsServiceControllerAdapter.this.removeImsFeature(slotId, featureType);
+ }
+
+ @Override
+ public ImsFeatureConfiguration querySupportedImsFeatures() {
+ return null;
+ }
+
+ @Override
+ public void notifyImsServiceReadyForFeatureCreation() {
+ }
+
+ @Override
+ public IImsConfig getConfig(int slotId) throws RemoteException {
+ return new ImsConfigImplBase().getIImsConfig();
+ }
+
+ @Override
+ public IImsRegistration getRegistration(int slotId) throws RemoteException {
+ return new ImsRegistrationImplBase().getBinder();
+ }
+
+ @Override
+ public void enableIms(int slotId) {
+ }
+
+ @Override
+ public void disableIms(int slotId) {
+
+ }
+
+ }
+
+ private ImsServiceControllerBinder mBinder;
+
+ public IImsServiceController getBinder() {
+ if (mBinder == null) {
+ mBinder = spy(new ImsServiceControllerBinder());
+ }
+
+ return mBinder;
+ }
+
+ // Used by Mockito for verification that this method is being called in spy
+ public IImsMmTelFeature createMMTelFeature(int slotId) {
+ return null;
+ }
+
+ // Used by Mockito for verification that this method is being called in spy
+ public IImsRcsFeature createRcsFeature(int slotId) {
+ return null;
+ }
+
+ // Used by Mockito for verification that this method is being called in spy
+ public void removeImsFeature(int subId, int feature) throws RemoteException {
+ }
+}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsCallTest.java b/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsCallTest.java
index 306a503596..9327414c88 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsCallTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsCallTest.java
@@ -22,16 +22,11 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
import android.os.Bundle;
import android.telephony.ServiceState;
import android.telephony.TelephonyManager;
import android.telephony.ims.ImsCallProfile;
-import android.telephony.ims.ImsCallSession;
-import android.telephony.ims.ImsStreamMediaProfile;
import android.test.suitebuilder.annotation.SmallTest;
import com.android.ims.ImsCall;
@@ -40,7 +35,6 @@ import com.android.internal.telephony.TelephonyTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-import org.mockito.ArgumentCaptor;
public class ImsCallTest extends TelephonyTest {
@@ -61,36 +55,6 @@ public class ImsCallTest extends TelephonyTest {
@Test
@SmallTest
- public void testCallSessionProgressingAppliedMediaCaps() throws Exception {
- ImsCallSession mockSession = mock(ImsCallSession.class);
- ImsCall testImsCall = new ImsCall(mContext, mTestCallProfile);
- ImsCallProfile profile = new ImsCallProfile();
- when(mockSession.getCallProfile()).thenReturn(profile);
- testImsCall.attachSession(mockSession);
-
- ArgumentCaptor<ImsCallSession.Listener> listenerCaptor =
- ArgumentCaptor.forClass(ImsCallSession.Listener.class);
- verify(mockSession).setListener(listenerCaptor.capture());
- ImsCallSession.Listener listener = listenerCaptor.getValue();
- assertNotNull(listener);
-
- // Set new profile with direction of none
- ImsStreamMediaProfile newProfile = new ImsStreamMediaProfile(
- ImsStreamMediaProfile.AUDIO_QUALITY_AMR_WB,
- ImsStreamMediaProfile.DIRECTION_INACTIVE,
- ImsStreamMediaProfile.VIDEO_QUALITY_NONE,
- ImsStreamMediaProfile.DIRECTION_INACTIVE,
- ImsStreamMediaProfile.RTT_MODE_DISABLED);
- listener.callSessionProgressing(mockSession, newProfile);
-
- ImsStreamMediaProfile testProfile = testImsCall.getCallProfile().getMediaProfile();
- assertNotNull(testProfile);
- // Assert that the new direction was applied to the profile
- assertEquals(ImsStreamMediaProfile.DIRECTION_INACTIVE, testProfile.getAudioDirection());
- }
-
- @Test
- @SmallTest
public void testSetWifiDeprecated() {
ImsCall mTestImsCall = new ImsCall(mContext, mTestCallProfile);
assertFalse(mTestImsCall.isWifiCall());
@@ -123,20 +87,6 @@ public class ImsCallTest extends TelephonyTest {
@Test
@SmallTest
- public void testNullCallProfileAfterNonNull() {
- ImsCallProfile profile = new ImsCallProfile();
- profile.mCallType = ImsCallProfile.CALL_TYPE_VT_TX;
-
- ImsCall imsCall = new ImsCall(mContext, profile);
- assertNotNull(imsCall);
- assertTrue(imsCall.wasVideoCall());
-
- imsCall.setCallProfile(null);
- assertTrue(imsCall.wasVideoCall());
- }
-
- @Test
- @SmallTest
public void testSetWifi() {
ImsCall mTestImsCall = new ImsCall(mContext, mTestCallProfile);
assertFalse(mTestImsCall.isWifiCall());
diff --git a/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneCallTest.java b/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneCallTest.java
index 68ba403ae2..31fbfad319 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneCallTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneCallTest.java
@@ -21,7 +21,6 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
-import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -140,63 +139,6 @@ public class ImsPhoneCallTest extends TelephonyTest {
assertEquals(Call.State.ACTIVE, mImsCallUT.getState());
}
- /**
- * Verifies we can handle starting ringback between call state changes.
- */
- @Test
- @SmallTest
- public void testUpdateRingBackToneBetweenStateChange() {
- mMediaProfile.mAudioDirection = ImsStreamMediaProfile.DIRECTION_SEND_RECEIVE;
- mImsCallProfile.mMediaProfile = mMediaProfile;
-
- // This call state change should NOT start ringback since it the direction is wrong.
- mImsCallUT.update(null, mImsCall, Call.State.ALERTING);
- verify(mImsPhone, never()).startRingbackTone();
- assertEquals(Call.State.ALERTING, mImsCallUT.getState());
-
- // Simulate a change to the profile without a state change.
- mMediaProfile.mAudioDirection = ImsStreamMediaProfile.DIRECTION_INACTIVE;
- mImsCallUT.maybeChangeRingbackState(mImsCall);
- verify(mImsPhone, times(1)).startRingbackTone();
-
- // And then assume the call goes active, which would stop the ringback.
- mImsCallUT.update(null, mImsCall, Call.State.ACTIVE);
- verify(mImsPhone, times(1)).stopRingbackTone();
- assertEquals(Call.State.ACTIVE, mImsCallUT.getState());
- }
-
- /**
- * Verifies we can handle ringback start/stop entirely between call state changes.
- */
- @Test
- @SmallTest
- public void testUpdateRingBackToneBetweenStateChangeTwo() {
- mMediaProfile.mAudioDirection = ImsStreamMediaProfile.DIRECTION_SEND_RECEIVE;
- mImsCallProfile.mMediaProfile = mMediaProfile;
-
- // This call state change should NOT start ringback since it the direction is wrong.
- mImsCallUT.update(null, mImsCall, Call.State.ALERTING);
- verify(mImsPhone, never()).startRingbackTone();
- assertEquals(Call.State.ALERTING, mImsCallUT.getState());
-
- // Simulate a change to the profile without a state change.
- mMediaProfile.mAudioDirection = ImsStreamMediaProfile.DIRECTION_INACTIVE;
- mImsCallUT.maybeChangeRingbackState(mImsCall);
- verify(mImsPhone, times(1)).startRingbackTone();
-
- // Simulate another change to the profile without a state change.
- mMediaProfile.mAudioDirection = ImsStreamMediaProfile.DIRECTION_SEND_RECEIVE;
- mImsCallUT.maybeChangeRingbackState(mImsCall);
- verify(mImsPhone, times(1)).stopRingbackTone();
-
- // And then assume the call goes active, which should not impact ringback state.
- mImsCallUT.update(null, mImsCall, Call.State.ACTIVE);
- assertEquals(Call.State.ACTIVE, mImsCallUT.getState());
- // Should still have only started and stopped once
- verify(mImsPhone, times(1)).startRingbackTone();
- verify(mImsPhone, times(1)).stopRingbackTone();
- }
-
@Test
@SmallTest
public void testStopRingingOnHandover() {
diff --git a/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneCallTrackerTest.java b/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneCallTrackerTest.java
index d1826d51e6..0a972ab7f0 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneCallTrackerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneCallTrackerTest.java
@@ -25,11 +25,11 @@ import static android.net.NetworkStats.UID_ALL;
import static com.android.testutils.NetworkStatsUtilsKt.assertNetworkStatsEquals;
import static junit.framework.Assert.assertNotNull;
+import static junit.framework.TestCase.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.any;
@@ -71,7 +71,6 @@ import android.telephony.ims.ImsConferenceState;
import android.telephony.ims.ImsMmTelManager;
import android.telephony.ims.ImsReasonInfo;
import android.telephony.ims.ImsStreamMediaProfile;
-import android.telephony.ims.RtpHeaderExtensionType;
import android.telephony.ims.feature.ImsFeature;
import android.telephony.ims.feature.MmTelFeature;
import android.telephony.ims.stub.ImsRegistrationImplBase;
@@ -81,11 +80,9 @@ import android.testing.TestableLooper;
import androidx.test.filters.FlakyTest;
-import com.android.ims.FeatureConnector;
import com.android.ims.ImsCall;
import com.android.ims.ImsConfig;
import com.android.ims.ImsException;
-import com.android.ims.ImsManager;
import com.android.ims.internal.IImsCallSession;
import com.android.internal.telephony.Call;
import com.android.internal.telephony.CallStateException;
@@ -93,7 +90,6 @@ import com.android.internal.telephony.CommandsInterface;
import com.android.internal.telephony.Connection;
import com.android.internal.telephony.PhoneConstants;
import com.android.internal.telephony.TelephonyTest;
-import com.android.internal.telephony.d2d.RtpTransport;
import com.android.internal.telephony.imsphone.ImsPhoneCallTracker.VtDataUsageProvider;
import org.junit.After;
@@ -103,19 +99,15 @@ import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
-import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
-import java.util.Set;
-
@RunWith(AndroidTestingRunner.class)
@TestableLooper.RunWithLooper
public class ImsPhoneCallTrackerTest extends TelephonyTest {
private ImsPhoneCallTracker mCTUT;
private MmTelFeature.Listener mMmTelListener;
- private FeatureConnector.Listener<ImsManager> mConnectorListener;
private ImsMmTelManager.CapabilityCallback mCapabilityCallback;
private ImsCall.Listener mImsCallListener;
private ImsCall mImsCall;
@@ -134,12 +126,6 @@ public class ImsPhoneCallTrackerTest extends TelephonyTest {
private ImsPhoneConnection mImsPhoneConnection;
@Mock
private INetworkStatsProviderCallback mVtDataUsageProviderCb;
- @Mock
- private ImsPhoneCallTracker.ConnectorFactory mConnectorFactory;
- @Mock
- private FeatureConnector<ImsManager> mMockConnector;
- @Captor
- private ArgumentCaptor<Set<RtpHeaderExtensionType>> mRtpHeaderExtensionTypeCaptor;
private void imsCallMocking(final ImsCall imsCall) throws Exception {
@@ -191,13 +177,13 @@ public class ImsPhoneCallTrackerTest extends TelephonyTest {
imsCall.attachSession(mImsCallSession);
doReturn("1").when(mImsCallSession).getCallId();
- doReturn(mImsCallProfile).when(mImsCallSession).getCallProfile();
}
@Before
public void setUp() throws Exception {
super.setUp(this.getClass().getSimpleName());
mImsCallProfile.mCallExtras = mBundle;
+ mImsManagerInstances.put(mImsPhone.getPhoneId(), mImsManager);
mImsCall = spy(new ImsCall(mContext, mImsCallProfile));
mSecondImsCall = spy(new ImsCall(mContext, mImsCallProfile));
mImsPhoneConnectionListener = mock(ImsPhoneConnection.Listener.class);
@@ -211,7 +197,8 @@ public class ImsPhoneCallTrackerTest extends TelephonyTest {
doAnswer(invocation -> {
mMmTelListener = (MmTelFeature.Listener) invocation.getArguments()[0];
return null;
- }).when(mImsManager).open(any(), any(), any());
+ }).when(mImsManager).open(any(MmTelFeature.Listener.class));
+
doAnswer(new Answer<ImsCall>() {
@Override
@@ -238,18 +225,13 @@ public class ImsPhoneCallTrackerTest extends TelephonyTest {
mCapabilityCallback = (ImsMmTelManager.CapabilityCallback) invocation.getArguments()[0];
return mCapabilityCallback;
- }).when(mImsManager).addCapabilitiesCallback(
- any(ImsMmTelManager.CapabilityCallback.class), any());
+ }).when(mImsManager).addCapabilitiesCallback(any(ImsMmTelManager.CapabilityCallback.class));
doReturn(mImsConfig).when(mImsManager).getConfigInterface();
- doAnswer((Answer<FeatureConnector<ImsManager>>) invocation -> {
- mConnectorListener =
- (FeatureConnector.Listener<ImsManager>) invocation.getArguments()[3];
- return mMockConnector;
- }).when(mConnectorFactory).create(any(), anyInt(), anyString(), any(), any());
+ doNothing().when(mImsManager).addNotifyStatusChangedCallbackIfAvailable(any());
- mCTUT = new ImsPhoneCallTracker(mImsPhone, mConnectorFactory, Runnable::run);
+ mCTUT = new ImsPhoneCallTracker(mImsPhone, Runnable::run);
mCTUT.addReasonCodeRemapping(null, "Wifi signal lost.", ImsReasonInfo.CODE_WIFI_LOST);
mCTUT.addReasonCodeRemapping(501, "Call answered elsewhere.",
ImsReasonInfo.CODE_ANSWERED_ELSEWHERE);
@@ -275,9 +257,6 @@ public class ImsPhoneCallTrackerTest extends TelephonyTest {
logd("ImsPhoneCallTracker initiated");
processAllMessages();
-
- verify(mMockConnector).connect();
- mConnectorListener.connectionReady(mImsManager);
}
@After
@@ -327,7 +306,7 @@ public class ImsPhoneCallTrackerTest extends TelephonyTest {
public void testImsFeatureCapabilityChange() {
doReturn(ImsRegistrationImplBase.REGISTRATION_TECH_LTE).when(
mImsManager).getRegistrationTech();
- assertFalse(mCTUT.isVoiceOverCellularImsEnabled());
+ assertFalse(mCTUT.isVolteEnabled());
assertFalse(mCTUT.isVideoCallEnabled());
// enable only Voice
@@ -336,7 +315,7 @@ public class ImsPhoneCallTrackerTest extends TelephonyTest {
mCapabilityCallback.onCapabilitiesStatusChanged(caps);
processAllMessages();
- assertTrue(mCTUT.isVoiceOverCellularImsEnabled());
+ assertTrue(mCTUT.isVolteEnabled());
assertFalse(mCTUT.isVideoCallEnabled());
// video call not enabled
verify(mImsPhone, times(0)).notifyForVideoCapabilityChanged(anyBoolean());
@@ -530,54 +509,6 @@ public class ImsPhoneCallTrackerTest extends TelephonyTest {
assertEquals(Call.State.HOLDING, mCTUT.mBackgroundCall.getState());
}
- @Test
- @SmallTest
- public void testImsMTActiveHoldServiceDisconnect() {
- testImsMTCallAccept();
-
- assertEquals(Call.State.ACTIVE, mCTUT.mForegroundCall.getState());
- assertEquals(PhoneConstants.State.OFFHOOK, mCTUT.getState());
- // mock a new MT
- try {
- doReturn(mSecondImsCall).when(mImsManager).takeCall(any(IImsCallSession.class),
- any(ImsCall.Listener.class));
- } catch (Exception ex) {
- ex.printStackTrace();
- Assert.fail("unexpected exception thrown" + ex.getMessage());
- }
- mMmTelListener.onIncomingCall(mock(IImsCallSession.class), Bundle.EMPTY);
-
- verify(mImsPhone, times(2)).notifyNewRingingConnection((Connection) any());
- verify(mImsPhone, times(2)).notifyIncomingRing();
- assertEquals(Call.State.ACTIVE, mCTUT.mForegroundCall.getState());
- assertEquals(ImsPhoneCall.State.WAITING, mCTUT.mRingingCall.getState());
- assertEquals(PhoneConstants.State.RINGING, mCTUT.getState());
-
- //hold the foreground active call, accept the new ringing call
- try {
- mCTUT.acceptCall(ImsCallProfile.CALL_TYPE_VOICE);
- verify(mImsCall, times(1)).hold();
- } catch (Exception ex) {
- ex.printStackTrace();
- Assert.fail("unexpected exception thrown" + ex.getMessage());
- }
-
- processAllMessages();
- assertEquals(Call.State.ACTIVE, mCTUT.mForegroundCall.getState());
- assertFalse(mCTUT.mRingingCall.isRinging());
- assertEquals(Call.State.HOLDING, mCTUT.mBackgroundCall.getState());
-
- // Now fake the ImsService crashing
- mCTUT.hangupAllOrphanedConnections(DisconnectCause.LOST_SIGNAL);
- assertEquals(PhoneConstants.State.IDLE, mCTUT.getState());
- try {
- // ensure new calls are not blocked by any lingering state after crash.
- mCTUT.checkForDialIssues();
- } catch (CallStateException e) {
- fail("checkForDialIssues should not generate a CallStateException: " + e.getMessage());
- }
- }
-
/**
* Ensures that the dial method will perform a shared preferences lookup using the correct
* shared preference key to determine the CLIR mode.
@@ -610,25 +541,25 @@ public class ImsPhoneCallTrackerTest extends TelephonyTest {
@Test
@SmallTest
public void testEmergencyDialSuppressClir() {
- String dialString = "+17005554141";
mCTUT.setSharedPreferenceProxy((Context context) -> {
return mSharedPreferences;
});
-
- doReturn(true).when(mTelephonyManager).isEmergencyNumber(dialString);
-
+ // Mock implementation of phone number utils treats everything as an emergency.
+ mCTUT.setPhoneNumberUtilsProxy((String string) -> {
+ return true;
+ });
// Set preference to hide caller ID.
ArgumentCaptor<String> stringCaptor = ArgumentCaptor.forClass(String.class);
doReturn(CommandsInterface.CLIR_INVOCATION).when(mSharedPreferences).getInt(
stringCaptor.capture(), anyInt());
try {
- mCTUT.dial(dialString, new ImsPhone.ImsDialArgs.Builder().setIsEmergency(true).build());
+ mCTUT.dial("+17005554141", VideoProfile.STATE_AUDIO_ONLY, null);
ArgumentCaptor<ImsCallProfile> profileCaptor = ArgumentCaptor.forClass(
ImsCallProfile.class);
verify(mImsManager, times(1)).makeCall(eq(mImsCallProfile),
- eq(new String[]{dialString}), any());
+ eq(new String[]{"+17005554141"}), any());
// Because this is an emergency call, we expect caller id to be visible now.
assertEquals(mImsCallProfile.getCallExtraInt(ImsCallProfile.EXTRA_OIR),
@@ -642,32 +573,17 @@ public class ImsPhoneCallTrackerTest extends TelephonyTest {
}
}
+ @FlakyTest
+ @Ignore
@Test
@SmallTest
public void testImsMOCallDial() {
startOutgoingCall();
//call established
mImsCallListener.onCallProgressing(mSecondImsCall);
- processAllMessages();
assertEquals(Call.State.ALERTING, mCTUT.mForegroundCall.getState());
}
- @Test
- @SmallTest
- public void testImsMoCallCrash() {
- startOutgoingCall();
- // Now fake the ImsService crashing
- mCTUT.hangupAllOrphanedConnections(DisconnectCause.LOST_SIGNAL);
- processAllMessages();
- assertEquals(PhoneConstants.State.IDLE, mCTUT.getState());
- try {
- // ensure new calls are not blocked by any lingering state after crash.
- mCTUT.checkForDialIssues();
- } catch (CallStateException e) {
- fail("checkForDialIssues should not generate a CallStateException: " + e.getMessage());
- }
- }
-
private void startOutgoingCall() {
assertEquals(Call.State.IDLE, mCTUT.mForegroundCall.getState());
assertEquals(PhoneConstants.State.IDLE, mCTUT.getState());
@@ -680,7 +596,6 @@ public class ImsPhoneCallTrackerTest extends TelephonyTest {
ex.printStackTrace();
Assert.fail("unexpected exception thrown" + ex.getMessage());
}
- processAllMessages();
assertEquals(PhoneConstants.State.OFFHOOK, mCTUT.getState());
assertEquals(Call.State.DIALING, mCTUT.mForegroundCall.getState());
}
@@ -776,6 +691,7 @@ public class ImsPhoneCallTrackerTest extends TelephonyTest {
public void testDialImsServiceUnavailable() throws ImsException {
doThrow(new ImsException("Test Exception", ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN)).when(
mImsManager).createCallProfile(anyInt(), anyInt());
+ mCTUT.setRetryTimeout(() -> 0);
assertEquals(Call.State.IDLE, mCTUT.mForegroundCall.getState());
assertEquals(PhoneConstants.State.IDLE, mCTUT.getState());
@@ -786,14 +702,12 @@ public class ImsPhoneCallTrackerTest extends TelephonyTest {
}
processAllMessages();
-
- // Simulate ImsManager getting reconnected.
- mConnectorListener.connectionReady(mImsManager);
verify(mImsManager, never()).makeCall(nullable(ImsCallProfile.class),
eq(new String[]{"+17005554141"}), nullable(ImsCall.Listener.class));
// Make sure that open is called in ImsPhoneCallTracker when it was first connected and
// again after retry.
- verify(mImsManager, times(2)).open(any(), any(), any());
+ verify(mImsManager, times(2)).open(
+ nullable(MmTelFeature.Listener.class));
}
@FlakyTest
@@ -804,13 +718,16 @@ public class ImsPhoneCallTrackerTest extends TelephonyTest {
doThrow(new ImsException("Test Exception", ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN)).when(
mImsManager).setUiTTYMode(nullable(Context.class), anyInt(),
nullable(Message.class));
+ // Remove retry timeout delay
+ mCTUT.setRetryTimeout(() -> 0); //ms
mCTUT.setUiTTYMode(0, new Message());
processAllMessages();
// Make sure that open is called in ImsPhoneCallTracker to re-establish connection to
// ImsService
- verify(mImsManager, times(2)).open(any(), any(), any());
+ verify(mImsManager, times(2)).open(
+ nullable(MmTelFeature.Listener.class));
}
@Test
@@ -1149,13 +1066,19 @@ public class ImsPhoneCallTrackerTest extends TelephonyTest {
@SmallTest
public void testNoHoldErrorMessageWhenCallDisconnected() {
when(mImsPhoneConnection.getImsCall()).thenReturn(mImsCall);
+ doAnswer(new Answer<Void>() {
+ @Override
+ public Void answer(InvocationOnMock invocationOnMock) {
+ fail("Error message showed when the call has already been disconnected!");
+ return null;
+ }
+ }).when(mImsPhoneConnection)
+ .onConnectionEvent(eq(android.telecom.Connection.EVENT_CALL_HOLD_FAILED), any());
mCTUT.getConnections().add(mImsPhoneConnection);
when(mImsPhoneConnection.getState()).thenReturn(ImsPhoneCall.State.DISCONNECTED);
- final ImsReasonInfo info = new ImsReasonInfo(ImsReasonInfo.CODE_UNSPECIFIED,
+ ImsReasonInfo info = new ImsReasonInfo(ImsReasonInfo.CODE_UNSPECIFIED,
ImsReasonInfo.CODE_UNSPECIFIED, null);
mCTUT.getImsCallListener().onCallHoldFailed(mImsPhoneConnection.getImsCall(), info);
- verify(mImsPhoneConnection, never()).onConnectionEvent(
- eq(android.telecom.Connection.EVENT_CALL_HOLD_FAILED), any());
}
@Test
@@ -1193,55 +1116,6 @@ public class ImsPhoneCallTrackerTest extends TelephonyTest {
@Test
@SmallTest
- public void testEndRingbackOnSrvcc() throws RemoteException {
- mSecondImsCall.getCallProfile().mMediaProfile = new ImsStreamMediaProfile();
- mSecondImsCall.getCallProfile().mMediaProfile.mAudioDirection =
- ImsStreamMediaProfile.DIRECTION_INACTIVE;
-
- startOutgoingCall();
- mImsCallListener.onCallProgressing(mSecondImsCall);
-
- assertTrue(mCTUT.mForegroundCall.isRingbackTonePlaying());
-
- // Move the connection to the handover state.
- mCTUT.notifySrvccState(Call.SrvccState.COMPLETED);
-
- assertFalse(mCTUT.mForegroundCall.isRingbackTonePlaying());
- }
-
- @Test
- @SmallTest
- public void testClearHoldSwapStateOnSrvcc() throws Exception {
- // Answer an incoming call
- testImsMTCall();
- assertTrue(mCTUT.mRingingCall.isRinging());
- try {
- mCTUT.acceptCall(ImsCallProfile.CALL_TYPE_VOICE);
- verify(mImsCall, times(1)).accept(eq(ImsCallProfile
- .getCallTypeFromVideoState(ImsCallProfile.CALL_TYPE_VOICE)));
- } catch (Exception ex) {
- ex.printStackTrace();
- Assert.fail("set active, unexpected exception thrown" + ex.getMessage());
- }
- assertEquals(Call.State.ACTIVE, mCTUT.mForegroundCall.getState());
- // Hold the call
- doNothing().when(mImsCall).hold();
- try {
- mCTUT.holdActiveCall();
- assertTrue(mCTUT.isHoldOrSwapInProgress());
- } catch (Exception ex) {
- ex.printStackTrace();
- Assert.fail("hold, unexpected exception thrown" + ex.getMessage());
- }
-
- // Move the connection to the handover state.
- mCTUT.notifySrvccState(Call.SrvccState.COMPLETED);
- // Ensure we are no longer tracking hold.
- assertFalse(mCTUT.isHoldOrSwapInProgress());
- }
-
- @Test
- @SmallTest
public void testHangupHandoverCall() throws RemoteException {
doReturn("1").when(mImsCallSession).getCallId();
assertEquals(PhoneConstants.State.IDLE, mCTUT.getState());
@@ -1303,84 +1177,6 @@ public class ImsPhoneCallTrackerTest extends TelephonyTest {
assertEquals(PhoneConstants.State.IDLE, mCTUT.getState());
}
- /**
- * Ensures when both RTP and SDP is supported that we register the expected header extension
- * types.
- * @throws Exception
- */
- @Test
- @SmallTest
- public void testConfigureRtpHeaderExtensionTypes() throws Exception {
-
- mContextFixture.getCarrierConfigBundle().putBoolean(
- CarrierConfigManager.KEY_SUPPORTS_DEVICE_TO_DEVICE_COMMUNICATION_USING_RTP_BOOL,
- true);
- mContextFixture.getCarrierConfigBundle().putBoolean(
- CarrierConfigManager.KEY_SUPPORTS_SDP_NEGOTIATION_OF_D2D_RTP_HEADER_EXTENSIONS_BOOL,
- true);
- // Hacky but ImsPhoneCallTracker caches carrier config, so necessary.
- mCTUT.updateCarrierConfigCache(mContextFixture.getCarrierConfigBundle());
-
- ImsPhoneCallTracker.Config config = new ImsPhoneCallTracker.Config();
- config.isD2DCommunicationSupported = true;
- mCTUT.setConfig(config);
- mConnectorListener.connectionReady(mImsManager);
-
- // Expect to get offered header extensions since d2d is supported.
- verify(mImsManager).setOfferedRtpHeaderExtensionTypes(
- mRtpHeaderExtensionTypeCaptor.capture());
- Set<RtpHeaderExtensionType> types = mRtpHeaderExtensionTypeCaptor.getValue();
- assertEquals(2, types.size());
- assertTrue(types.contains(RtpTransport.CALL_STATE_RTP_HEADER_EXTENSION_TYPE));
- assertTrue(types.contains(RtpTransport.DEVICE_STATE_RTP_HEADER_EXTENSION_TYPE));
- }
-
- /**
- * Ensures when SDP is not supported (by RTP is) we don't register any extensions.
- * @throws Exception
- */
- @Test
- @SmallTest
- public void testRtpButNoSdp() throws Exception {
-
- mContextFixture.getCarrierConfigBundle().putBoolean(
- CarrierConfigManager.KEY_SUPPORTS_DEVICE_TO_DEVICE_COMMUNICATION_USING_RTP_BOOL,
- true);
- mContextFixture.getCarrierConfigBundle().putBoolean(
- CarrierConfigManager.KEY_SUPPORTS_SDP_NEGOTIATION_OF_D2D_RTP_HEADER_EXTENSIONS_BOOL,
- false);
- // Hacky but ImsPhoneCallTracker caches carrier config, so necessary.
- mCTUT.updateCarrierConfigCache(mContextFixture.getCarrierConfigBundle());
-
- ImsPhoneCallTracker.Config config = new ImsPhoneCallTracker.Config();
- config.isD2DCommunicationSupported = true;
- mCTUT.setConfig(config);
- mConnectorListener.connectionReady(mImsManager);
-
- // Expect to get offered header extensions since d2d is supported.
- verify(mImsManager).setOfferedRtpHeaderExtensionTypes(
- mRtpHeaderExtensionTypeCaptor.capture());
- Set<RtpHeaderExtensionType> types = mRtpHeaderExtensionTypeCaptor.getValue();
- assertEquals(0, types.size());
- }
-
- /**
- * Ensures when D2D communication is not supported that we don't register the D2D RTP header
- * extension types.
- * @throws Exception
- */
- @Test
- @SmallTest
- public void testDontConfigureRtpHeaderExtensionTypes() throws Exception {
- ImsPhoneCallTracker.Config config = new ImsPhoneCallTracker.Config();
- config.isD2DCommunicationSupported = false;
- mCTUT.setConfig(config);
- mConnectorListener.connectionReady(mImsManager);
-
- // Expect no offered header extensions since d2d is not supported.
- verify(mImsManager, never()).setOfferedRtpHeaderExtensionTypes(any());
- }
-
private void assertVtDataUsageUpdated(int expectedToken, long rxBytes, long txBytes)
throws RemoteException {
final ArgumentCaptor<NetworkStats> ifaceStatsCaptor = ArgumentCaptor.forClass(
@@ -1399,7 +1195,7 @@ public class ImsPhoneCallTrackerTest extends TelephonyTest {
if (rxBytes != 0 || txBytes != 0) {
expectedStats = expectedStats.addEntry(
- new Entry(mCTUT.getVtInterface(), UID_ALL, SET_FOREGROUND,
+ new Entry(NetworkStats.IFACE_VT, UID_ALL, SET_FOREGROUND,
TAG_NONE, METERED_YES, ROAMING_NO, DEFAULT_NETWORK_YES, rxBytes, 0L,
txBytes, 0L, 0L));
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneConnectionTest.java b/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneConnectionTest.java
index 5e98e5054f..205b92dc1e 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneConnectionTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneConnectionTest.java
@@ -15,9 +15,6 @@
*/
package com.android.internal.telephony.imsphone;
-import static android.telephony.ims.ImsStreamMediaProfile.AUDIO_QUALITY_AMR_WB;
-import static android.telephony.ims.ImsStreamMediaProfile.AUDIO_QUALITY_EVS_SWB;
-
import static com.android.internal.telephony.TelephonyTestUtils.waitForMs;
import static org.junit.Assert.assertEquals;
@@ -30,10 +27,8 @@ import static org.mockito.Mockito.anyChar;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
-import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
import android.os.AsyncResult;
import android.os.Bundle;
@@ -45,21 +40,16 @@ import android.telephony.PhoneNumberUtils;
import android.telephony.ServiceState;
import android.telephony.TelephonyManager;
import android.telephony.ims.ImsCallProfile;
-import android.telephony.ims.ImsStreamMediaProfile;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
-import com.android.ims.ImsCall;
-import com.android.ims.ImsException;
import com.android.internal.telephony.Call;
import com.android.internal.telephony.Connection;
import com.android.internal.telephony.GsmCdmaCall;
import com.android.internal.telephony.PhoneConstants;
import com.android.internal.telephony.TelephonyTest;
-import com.android.internal.telephony.metrics.TelephonyMetrics;
-import com.android.internal.telephony.metrics.VoiceCallSessionStats;
import org.junit.After;
import org.junit.Assert;
@@ -71,15 +61,10 @@ import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
@RunWith(AndroidTestingRunner.class)
@TestableLooper.RunWithLooper
public class ImsPhoneConnectionTest extends TelephonyTest {
- private static final int TIMEOUT_MILLIS = 5000;
-
private ImsPhoneConnection mConnectionUT;
private Bundle mBundle = new Bundle();
@Mock
@@ -109,18 +94,6 @@ public class ImsPhoneConnectionTest extends TelephonyTest {
@Test
@SmallTest
- public void testNullExtras() {
- mImsCallProfile.mCallExtras = null;
- try {
- mConnectionUT = new ImsPhoneConnection(mImsPhone, mImsCall, mImsCT, mForeGroundCall,
- false);
- } catch (NullPointerException npe) {
- Assert.fail("Should not get NPE updating extras.");
- }
- }
-
- @Test
- @SmallTest
public void testImsIncomingConnectionCorrectness() {
logd("Testing initial state of MT ImsPhoneConnection");
mConnectionUT = new ImsPhoneConnection(mImsPhone, mImsCall, mImsCT, mForeGroundCall, false);
@@ -141,7 +114,7 @@ public class ImsPhoneConnectionTest extends TelephonyTest {
logd("Testing initial state of MO ImsPhoneConnection");
mConnectionUT = new ImsPhoneConnection(mImsPhone, String.format("+1 (700).555-41NN%c1234",
- PhoneNumberUtils.PAUSE), mImsCT, mForeGroundCall, false, false);
+ PhoneNumberUtils.PAUSE), mImsCT, mForeGroundCall, false);
assertEquals(PhoneConstants.PRESENTATION_ALLOWED, mConnectionUT.getNumberPresentation());
assertEquals(PhoneConstants.PRESENTATION_ALLOWED, mConnectionUT.getCnapNamePresentation());
assertEquals("+1 (700).555-41NN,1234", mConnectionUT.getOrigDialString());
@@ -154,7 +127,7 @@ public class ImsPhoneConnectionTest extends TelephonyTest {
public void testImsUpdateStateForeGround() {
// MO Foreground Connection dailing -> active
mConnectionUT = new ImsPhoneConnection(mImsPhone, "+1 (700).555-41NN1234", mImsCT,
- mForeGroundCall, false, false);
+ mForeGroundCall, false);
// initially in dialing state
doReturn(Call.State.DIALING).when(mForeGroundCall).getState();
assertTrue(mConnectionUT.update(mImsCall, Call.State.ACTIVE));
@@ -166,16 +139,6 @@ public class ImsPhoneConnectionTest extends TelephonyTest {
@Test
@SmallTest
- public void testUpdateCodec() {
- // MO Foreground Connection dailing -> active
- mConnectionUT = new ImsPhoneConnection(mImsPhone, "+1 (700).555-41NN1234", mImsCT,
- mForeGroundCall, false, false);
- doReturn(Call.State.ACTIVE).when(mForeGroundCall).getState();
- assertTrue(mConnectionUT.updateMediaCapabilities(mImsCall));
- }
-
- @Test
- @SmallTest
public void testImsUpdateStateBackGround() {
// MT background Connection dialing -> active
mConnectionUT = new ImsPhoneConnection(mImsPhone, mImsCall, mImsCT, mBackGroundCall, false);
@@ -192,7 +155,7 @@ public class ImsPhoneConnectionTest extends TelephonyTest {
@SmallTest
public void testImsUpdateStatePendingHold() {
mConnectionUT = new ImsPhoneConnection(mImsPhone, "+1 (700).555-41NN1234", mImsCT,
- mForeGroundCall, false, false);
+ mForeGroundCall, false);
doReturn(true).when(mImsCall).isPendingHold();
assertFalse(mConnectionUT.update(mImsCall, Call.State.ACTIVE));
verify(mForeGroundCall, times(0)).update(eq(mConnectionUT), eq(mImsCall),
@@ -237,7 +200,7 @@ public class ImsPhoneConnectionTest extends TelephonyTest {
@SmallTest
public void testPostDialWait() {
mConnectionUT = new ImsPhoneConnection(mImsPhone, String.format("+1 (700).555-41NN%c1234",
- PhoneNumberUtils.WAIT), mImsCT, mForeGroundCall, false, false);
+ PhoneNumberUtils.WAIT), mImsCT, mForeGroundCall, false);
doReturn(Call.State.DIALING).when(mForeGroundCall).getState();
doAnswer(new Answer() {
@Override
@@ -260,7 +223,7 @@ public class ImsPhoneConnectionTest extends TelephonyTest {
@MediumTest
public void testPostDialPause() {
mConnectionUT = new ImsPhoneConnection(mImsPhone, String.format("+1 (700).555-41NN%c1234",
- PhoneNumberUtils.PAUSE), mImsCT, mForeGroundCall, false, false);
+ PhoneNumberUtils.PAUSE), mImsCT, mForeGroundCall, false);
doReturn(Call.State.DIALING).when(mForeGroundCall).getState();
doAnswer(new Answer() {
@Override
@@ -388,7 +351,7 @@ public class ImsPhoneConnectionTest extends TelephonyTest {
{"12345*00000", "12346", "12346"}};
for (String[] testAddress : testAddressMappingSet) {
mConnectionUT = new ImsPhoneConnection(mImsPhone, testAddress[0], mImsCT,
- mForeGroundCall, false, false);
+ mForeGroundCall, false);
mConnectionUT.setIsIncoming(true);
mImsCallProfile.setCallExtra(ImsCallProfile.EXTRA_OI, testAddress[1]);
mConnectionUT.updateAddressDisplay(mImsCall);
@@ -406,7 +369,7 @@ public class ImsPhoneConnectionTest extends TelephonyTest {
String updateAddress = "6789";
mConnectionUT = new ImsPhoneConnection(mImsPhone, inputAddress, mImsCT, mForeGroundCall,
- false, false);
+ false);
mConnectionUT.setIsIncoming(false);
mImsCallProfile.setCallExtra(ImsCallProfile.EXTRA_OI, updateAddress);
mConnectionUT.updateAddressDisplay(mImsCall);
@@ -428,56 +391,4 @@ public class ImsPhoneConnectionTest extends TelephonyTest {
assertEquals(android.telecom.Connection.VERIFICATION_STATUS_NOT_VERIFIED,
ImsPhoneConnection.toTelecomVerificationStatus(90210));
}
-
- @Test
- @SmallTest
- public void testSetRedirectingAddress() {
- mConnectionUT = new ImsPhoneConnection(mImsPhone, mImsCall, mImsCT, mForeGroundCall, false);
- ArrayList<String> forwardedNumber = new ArrayList<String>();
- forwardedNumber.add("11111");
- forwardedNumber.add("22222");
- forwardedNumber.add("33333");
-
- assertEquals(mConnectionUT.getForwardedNumber(), null);
- mBundle.putStringArrayList(ImsCallProfile.EXTRA_FORWARDED_NUMBER, forwardedNumber);
- assertTrue(mConnectionUT.update(mImsCall, Call.State.ACTIVE));
- assertEquals(forwardedNumber, mConnectionUT.getForwardedNumber());
- }
-
- @Test
- @SmallTest
- public void testReportMediaCodecChange() throws InterruptedException, ImsException {
- ImsCall imsCall = mock(ImsCall.class);
- ImsStreamMediaProfile mediaProfile = new ImsStreamMediaProfile();
- ImsCallProfile profile = new ImsCallProfile();
- profile.mMediaProfile = mediaProfile;
- mediaProfile.mAudioQuality = AUDIO_QUALITY_AMR_WB;
- when(imsCall.getLocalCallProfile()).thenReturn(profile);
-
- // Blech; mocks required which are unrelated to this test
- when(mImsCT.getPhone()).thenReturn(mImsPhone);
- VoiceCallSessionStats stats = mock(VoiceCallSessionStats.class);
- when(mImsPhone.getVoiceCallSessionStats()).thenReturn(stats);
-
- mConnectionUT = new ImsPhoneConnection(mImsPhone, imsCall, mImsCT, mForeGroundCall, false);
- mConnectionUT.setTelephonyMetrics(mock(TelephonyMetrics.class));
- CountDownLatch latch = new CountDownLatch(1);
- boolean[] receivedCountCallback = new boolean[1];
- mConnectionUT.addListener(new Connection.ListenerBase() {
- @Override
- public void onMediaAttributesChanged() {
- receivedCountCallback[0] = true;
- latch.countDown();
- }
- });
-
- mConnectionUT.updateMediaCapabilities(imsCall);
-
- // Make an update to the media caps
- mediaProfile.mAudioQuality = AUDIO_QUALITY_EVS_SWB;
- mConnectionUT.updateMediaCapabilities(imsCall);
-
- latch.await(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
- assertTrue(receivedCountCallback[0]);
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneMmiCodeTest.java b/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneMmiCodeTest.java
deleted file mode 100644
index aee46b728c..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneMmiCodeTest.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.internal.telephony.imsphone;
-
-import static junit.framework.Assert.fail;
-
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.Mockito.doReturn;
-
-import android.os.PersistableBundle;
-import android.telephony.CarrierConfigManager;
-import android.telephony.ServiceState;
-import android.testing.AndroidTestingRunner;
-import android.testing.TestableLooper;
-
-import com.android.internal.telephony.TelephonyTest;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.util.concurrent.Executor;
-
-/**
- * Unit tests for the {@link ImsPhoneMmiCodeTest}.
- */
-@RunWith(AndroidTestingRunner.class)
-@TestableLooper.RunWithLooper
-public class ImsPhoneMmiCodeTest extends TelephonyTest {
- private static final String TEST_DIAL_STRING_SERVICE_CODE = "*67911";
- private static final String TEST_DIAL_STRING_NO_SERVICE_CODE = "*767911";
- private static final String TEST_DIAL_STRING_NON_EMERGENCY_NUMBER = "11976";
- private ImsPhoneMmiCode mImsPhoneMmiCode;
- private ImsPhone mImsPhoneUT;
- @Mock private ServiceState mServiceState;
-
- private Executor mExecutor = new Executor() {
- @Override
- public void execute(Runnable r) {
- r.run();
- }
- };
-
- @Before
- public void setUp() throws Exception {
- super.setUp(getClass().getSimpleName());
- MockitoAnnotations.initMocks(this);
- doReturn(mExecutor).when(mContext).getMainExecutor();
- doReturn(mPhone).when(mPhone).getDefaultPhone();
- doReturn(mServiceState).when(mPhone).getServiceState();
- doReturn(false).when(mServiceState).getVoiceRoaming();
- doReturn(false).when(mPhone).supportsConversionOfCdmaCallerIdMmiCodesWhileRoaming();
- mImsPhoneUT = new ImsPhone(mContext, mNotifier, mPhone);
- setCarrierSupportsCallerIdVerticalServiceCodesCarrierConfig();
- }
-
- @After
- public void tearDown() throws Exception {
- super.tearDown();
- }
-
- @Test
- public void testIsTemporaryModeCLIRFromCarrierConfig() {
- // Test *67911 is treated as temporary mode CLIR
- doReturn(true).when(mTelephonyManager).isEmergencyNumber(TEST_DIAL_STRING_SERVICE_CODE);
- mImsPhoneMmiCode = ImsPhoneMmiCode.newFromDialString(TEST_DIAL_STRING_SERVICE_CODE,
- mImsPhoneUT);
- assertTrue(mImsPhoneMmiCode.isTemporaryModeCLIR());
- }
-
- @Test
- public void testIsTemporaryModeCLIRForNonServiceCode() {
- // Test if prefix isn't *67 or *82
- doReturn(true).when(mTelephonyManager).isEmergencyNumber(TEST_DIAL_STRING_NO_SERVICE_CODE);
- mImsPhoneMmiCode = ImsPhoneMmiCode.newFromDialString(TEST_DIAL_STRING_NO_SERVICE_CODE,
- mImsPhoneUT);
- assertTrue(mImsPhoneMmiCode == null);
- }
-
- @Test
- public void testIsTemporaryModeCLIRForNonEmergencyNumber() {
- // Test if dialing string isn't an emergency number
- mImsPhoneMmiCode = ImsPhoneMmiCode.newFromDialString(TEST_DIAL_STRING_NON_EMERGENCY_NUMBER,
- mImsPhoneUT);
- assertTrue(mImsPhoneMmiCode == null);
- }
-
- @Test
- public void testNoCrashOnEmptyMessage() {
- ImsPhoneMmiCode mmi = ImsPhoneMmiCode.newNetworkInitiatedUssd(null, true, mImsPhoneUT);
- try {
- mmi.onUssdFinishedError();
- } catch (Exception e) {
- fail("Shouldn't crash!!!");
- }
- }
-
- private void setCarrierSupportsCallerIdVerticalServiceCodesCarrierConfig() {
- final PersistableBundle bundle = new PersistableBundle();
- bundle.putBoolean(CarrierConfigManager
- .KEY_CARRIER_SUPPORTS_CALLER_ID_VERTICAL_SERVICE_CODES_BOOL, true);
- doReturn(bundle).when(mCarrierConfigManager).getConfigForSubId(anyInt());
- }
-}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneTest.java b/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneTest.java
index be037d9ef5..0531d721b9 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/imsphone/ImsPhoneTest.java
@@ -16,11 +16,6 @@
package com.android.internal.telephony.imsphone;
-import static android.telephony.CarrierConfigManager.USSD_OVER_CS_ONLY;
-import static android.telephony.CarrierConfigManager.USSD_OVER_CS_PREFERRED;
-import static android.telephony.CarrierConfigManager.USSD_OVER_IMS_ONLY;
-import static android.telephony.CarrierConfigManager.USSD_OVER_IMS_PREFERRED;
-
import static com.android.internal.telephony.CommandsInterface.CF_ACTION_ENABLE;
import static com.android.internal.telephony.CommandsInterface.CF_REASON_UNCONDITIONAL;
@@ -80,7 +75,6 @@ import com.android.internal.telephony.PhoneConstants;
import com.android.internal.telephony.TelephonyIntents;
import com.android.internal.telephony.TelephonyTest;
import com.android.internal.telephony.gsm.SuppServiceNotification;
-import com.android.internal.telephony.imsphone.ImsPhone.SS;
import org.junit.After;
import org.junit.Before;
@@ -126,7 +120,6 @@ public class ImsPhoneTest extends TelephonyTest {
private static final int EVENT_SUPP_SERVICE_FAILED = 2;
private static final int EVENT_INCOMING_RING = 3;
private static final int EVENT_EMERGENCY_CALLBACK_MODE_EXIT = 4;
- private static final int EVENT_CALL_RING_CONTINUE = 15;
private boolean mIsPhoneUtInEcm = false;
@@ -144,7 +137,7 @@ public class ImsPhoneTest extends TelephonyTest {
doReturn(true).when(mTelephonyManager).isVoiceCapable();
- mImsPhoneUT = new ImsPhone(mContext, mNotifier, mPhone, (c, p) -> mImsManager, true);
+ mImsPhoneUT = new ImsPhone(mContext, mNotifier, mPhone, true);
mDoesRilSendMultipleCallRing = TelephonyProperties.ril_sends_multiple_call_ring()
.orElse(true);
@@ -157,7 +150,6 @@ public class ImsPhoneTest extends TelephonyTest {
mImsPhoneUT.registerForIncomingRing(mTestHandler,
EVENT_INCOMING_RING, null);
mImsPhoneUT.setVoiceCallSessionStats(mVoiceCallSessionStats);
- mImsPhoneUT.setImsStats(mImsStats);
doReturn(mImsUtInterface).when(mImsCT).getUtInterface();
// When the mock GsmCdmaPhone gets setIsInEcbm called, ensure isInEcm matches.
doAnswer(invocation -> {
@@ -483,15 +475,11 @@ public class ImsPhoneTest extends TelephonyTest {
ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
verify(mImsUtInterface).queryCLIR(messageArgumentCaptor.capture());
- assertNotNull(messageArgumentCaptor.getValue().obj);
- SS ss = (SS) messageArgumentCaptor.getValue().obj;
- assertEquals(msg, ss.mOnComplete);
+ assertEquals(msg, messageArgumentCaptor.getValue().obj);
mImsPhoneUT.setOutgoingCallerIdDisplay(1234, msg);
verify(mImsUtInterface).updateCLIR(eq(1234), messageArgumentCaptor.capture());
- assertNotNull(messageArgumentCaptor.getValue().obj);
- ss = (SS) messageArgumentCaptor.getValue().obj;
- assertEquals(msg, ss.mOnComplete);
+ assertEquals(msg, messageArgumentCaptor.getValue().obj);
}
@FlakyTest
@@ -521,16 +509,12 @@ public class ImsPhoneTest extends TelephonyTest {
ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
verify(mImsUtInterface).queryCallWaiting(messageArgumentCaptor.capture());
- assertNotNull(messageArgumentCaptor.getValue().obj);
- SS ss = (SS) messageArgumentCaptor.getValue().obj;
- assertEquals(msg, ss.mOnComplete);
+ assertEquals(msg, messageArgumentCaptor.getValue().obj);
mImsPhoneUT.setCallWaiting(true, msg);
verify(mImsUtInterface).updateCallWaiting(eq(true),
eq(CommandsInterface.SERVICE_CLASS_VOICE), messageArgumentCaptor.capture());
- assertNotNull(messageArgumentCaptor.getValue().obj);
- ss = (SS) messageArgumentCaptor.getValue().obj;
- assertEquals(msg, ss.mOnComplete);
+ assertEquals(msg, messageArgumentCaptor.getValue().obj);
}
@Test
@@ -561,18 +545,14 @@ public class ImsPhoneTest extends TelephonyTest {
ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
verify(mImsUtInterface).queryCallBarring(eq(ImsUtImplBase.CALL_BARRING_ALL_OUTGOING),
messageArgumentCaptor.capture(), eq(CommandsInterface.SERVICE_CLASS_NONE));
- assertNotNull(messageArgumentCaptor.getValue().obj);
- SS ss = (SS) messageArgumentCaptor.getValue().obj;
- assertEquals(msg, ss.mOnComplete);
+ assertEquals(msg, messageArgumentCaptor.getValue().obj);
mImsPhoneUT.setCallBarring(CommandsInterface.CB_FACILITY_BAOIC, true, "abc", msg,
CommandsInterface.SERVICE_CLASS_NONE);
verify(mImsUtInterface).updateCallBarring(eq(ImsUtImplBase.CALL_BARRING_OUTGOING_INTL),
eq(CommandsInterface.CF_ACTION_ENABLE), messageArgumentCaptor.capture(),
(String[]) eq(null), eq(CommandsInterface.SERVICE_CLASS_NONE), eq("abc"));
- assertNotNull(messageArgumentCaptor.getValue().obj);
- ss = (SS) messageArgumentCaptor.getValue().obj;
- assertEquals(msg, ss.mOnComplete);
+ assertEquals(msg, messageArgumentCaptor.getValue().obj);
mImsPhoneUT.setCallBarring(CommandsInterface.CB_FACILITY_BAOICxH, false, "abc", msg,
CommandsInterface.SERVICE_CLASS_NONE);
@@ -580,9 +560,7 @@ public class ImsPhoneTest extends TelephonyTest {
eq(ImsUtImplBase.CALL_BARRING_OUTGOING_INTL_EXCL_HOME),
eq(CommandsInterface.CF_ACTION_DISABLE), messageArgumentCaptor.capture(),
(String[]) eq(null), eq(CommandsInterface.SERVICE_CLASS_NONE), eq("abc"));
- assertNotNull(messageArgumentCaptor.getValue().obj);
- ss = (SS) messageArgumentCaptor.getValue().obj;
- assertEquals(msg, ss.mOnComplete);
+ assertEquals(msg, messageArgumentCaptor.getValue().obj);
}
@Test
@@ -668,7 +646,7 @@ public class ImsPhoneTest extends TelephonyTest {
@SmallTest
public void testImsRegistered() throws Exception {
mImsPhoneUT.setServiceState(ServiceState.STATE_IN_SERVICE);
- mImsPhoneUT.setImsRegistered(true);
+ mImsPhoneUT.setImsRegistrationState(RegistrationManager.REGISTRATION_STATE_REGISTERED);
assertTrue(mImsPhoneUT.isImsRegistered());
LinkedBlockingQueue<Integer> result = new LinkedBlockingQueue<>(1);
@@ -680,9 +658,23 @@ public class ImsPhoneTest extends TelephonyTest {
@Test
@SmallTest
+ public void testImsRegistering() throws Exception {
+ mImsPhoneUT.setServiceState(ServiceState.STATE_OUT_OF_SERVICE);
+ mImsPhoneUT.setImsRegistrationState(RegistrationManager.REGISTRATION_STATE_REGISTERING);
+ assertFalse(mImsPhoneUT.isImsRegistered());
+
+ LinkedBlockingQueue<Integer> result = new LinkedBlockingQueue<>(1);
+ mImsPhoneUT.getImsRegistrationState(result::offer);
+ Integer regResult = result.poll(1000, TimeUnit.MILLISECONDS);
+ assertNotNull(regResult);
+ assertEquals(RegistrationManager.REGISTRATION_STATE_REGISTERING, regResult.intValue());
+ }
+
+ @Test
+ @SmallTest
public void testImsDeregistered() throws Exception {
mImsPhoneUT.setServiceState(ServiceState.STATE_OUT_OF_SERVICE);
- mImsPhoneUT.setImsRegistered(false);
+ mImsPhoneUT.setImsRegistrationState(RegistrationManager.REGISTRATION_STATE_NOT_REGISTERED);
assertFalse(mImsPhoneUT.isImsRegistered());
LinkedBlockingQueue<Integer> result = new LinkedBlockingQueue<>(1);
@@ -712,7 +704,6 @@ public class ImsPhoneTest extends TelephonyTest {
@SmallTest
public void testRoamingDuplicateMessages() throws Exception {
doReturn(PhoneConstants.State.IDLE).when(mImsCT).getState();
- doReturn(true).when(mPhone).isRadioOn();
//roaming - data registration only on LTE
Message m = getServiceStateChangedMessage(getServiceStateDataOnly(
@@ -730,40 +721,12 @@ public class ImsPhoneTest extends TelephonyTest {
verify(mImsManager, times(1)).setWfcMode(anyInt(), anyBoolean());
}
- @Test
- @SmallTest
- public void testRoamingToAirplanModeIwlanInService() throws Exception {
- doReturn(true).when(mTransportManager).isInLegacyMode();
- doReturn(PhoneConstants.State.IDLE).when(mImsCT).getState();
- doReturn(true).when(mPhone).isRadioOn();
-
- //roaming - data registration only on LTE
- Message m = getServiceStateChangedMessage(getServiceStateDataOnly(
- ServiceState.RIL_RADIO_TECHNOLOGY_LTE, ServiceState.STATE_IN_SERVICE, true));
- // Inject the message synchronously instead of waiting for the thread to do it.
- mImsPhoneUT.handleMessage(m);
- m.recycle();
-
- verify(mImsManager, times(1)).setWfcMode(anyInt(), eq(true));
-
- // move to airplane mode + IWLAN in service
- doReturn(false).when(mPhone).isRadioOn();
- m = getServiceStateChangedMessage(getServiceStateDataOnly(
- ServiceState.RIL_RADIO_TECHNOLOGY_IWLAN, ServiceState.STATE_IN_SERVICE, false));
- mImsPhoneUT.handleMessage(m);
- m.recycle();
-
- // setWfcMode should not be called again, airplane mode should not trigger move out of
- // roaming.
- verify(mImsManager, times(1)).setWfcMode(anyInt(), anyBoolean());
- }
@Test
@SmallTest
public void testRoamingToOutOfService() throws Exception {
doReturn(true).when(mTransportManager).isInLegacyMode();
doReturn(PhoneConstants.State.IDLE).when(mImsCT).getState();
- doReturn(true).when(mPhone).isRadioOn();
//roaming - data registration only on LTE
Message m = getServiceStateChangedMessage(getServiceStateDataOnly(
@@ -789,7 +752,6 @@ public class ImsPhoneTest extends TelephonyTest {
public void testRoamingChangeForLteInLegacyMode() throws Exception {
doReturn(true).when(mTransportManager).isInLegacyMode();
doReturn(PhoneConstants.State.IDLE).when(mImsCT).getState();
- doReturn(true).when(mPhone).isRadioOn();
//roaming - data registration only on LTE
Message m = getServiceStateChangedMessage(getServiceStateDataOnly(
@@ -814,7 +776,6 @@ public class ImsPhoneTest extends TelephonyTest {
public void testDataOnlyRoamingCellToIWlanInLegacyMode() throws Exception {
doReturn(true).when(mTransportManager).isInLegacyMode();
doReturn(PhoneConstants.State.IDLE).when(mImsCT).getState();
- doReturn(true).when(mPhone).isRadioOn();
//roaming - data registration only on LTE
Message m = getServiceStateChangedMessage(getServiceStateDataOnly(
@@ -840,7 +801,6 @@ public class ImsPhoneTest extends TelephonyTest {
public void testCellVoiceDataChangeToWlanInLegacyMode() throws Exception {
doReturn(true).when(mTransportManager).isInLegacyMode();
doReturn(PhoneConstants.State.IDLE).when(mImsCT).getState();
- doReturn(true).when(mPhone).isRadioOn();
//roaming - voice/data registration on LTE
ServiceState ss = getServiceStateDataAndVoice(
@@ -872,8 +832,6 @@ public class ImsPhoneTest extends TelephonyTest {
public void testSendUssdAllowUssdOverImsInOutOfService() throws Exception {
Resources resources = mContext.getResources();
- mBundle.putInt(CarrierConfigManager.KEY_CARRIER_USSD_METHOD_INT,
- USSD_OVER_CS_PREFERRED);
doReturn(true).when(resources).getBoolean(
com.android.internal.R.bool.config_allow_ussd_over_ims);
doReturn(ServiceState.STATE_OUT_OF_SERVICE).when(mSST.mSS).getState();
@@ -888,8 +846,6 @@ public class ImsPhoneTest extends TelephonyTest {
String errorCode = "";
Resources resources = mContext.getResources();
- mBundle.putInt(CarrierConfigManager.KEY_CARRIER_USSD_METHOD_INT,
- USSD_OVER_CS_PREFERRED);
doReturn(true).when(resources).getBoolean(
com.android.internal.R.bool.config_allow_ussd_over_ims);
doReturn(ServiceState.STATE_IN_SERVICE).when(mSST.mSS).getState();
@@ -919,63 +875,6 @@ public class ImsPhoneTest extends TelephonyTest {
assertEquals(Phone.CS_FALLBACK, errorCode);
}
- @Test
- @SmallTest
- public void testSendUssdAllowUssdOverImswithIMSPreferred() throws Exception {
- Resources resources = mContext.getResources();
-
- mBundle.putInt(CarrierConfigManager.KEY_CARRIER_USSD_METHOD_INT,
- USSD_OVER_IMS_PREFERRED);
- doReturn(true).when(resources).getBoolean(
- com.android.internal.R.bool.config_allow_ussd_over_ims);
- doReturn(ServiceState.STATE_IN_SERVICE).when(mSST.mSS).getState();
-
- mImsPhoneUT.dial("*135#", new ImsPhone.ImsDialArgs.Builder().build());
- verify(mImsCT).sendUSSD(eq("*135#"), any());
- }
-
- @Test
- @SmallTest
- public void testSendUssdAllowUssdOverImswithCSOnly() throws Exception {
- String errorCode = "";
- Resources resources = mContext.getResources();
-
- mBundle.putInt(CarrierConfigManager.KEY_CARRIER_USSD_METHOD_INT,
- USSD_OVER_CS_ONLY);
- doReturn(true).when(resources).getBoolean(
- com.android.internal.R.bool.config_allow_ussd_over_ims);
- doReturn(ServiceState.STATE_IN_SERVICE).when(mSST.mSS).getState();
-
- try {
- mImsPhoneUT.dial("*135#", new ImsPhone.ImsDialArgs.Builder().build());
- } catch (CallStateException e) {
- errorCode = e.getMessage();
- }
- assertEquals(Phone.CS_FALLBACK, errorCode);
- }
-
- @Test
- @SmallTest
- public void testSendUssdAllowUssdOverImswithIMSOnly() throws Exception {
- Resources resources = mContext.getResources();
-
- mBundle.putInt(CarrierConfigManager.KEY_CARRIER_USSD_METHOD_INT,
- USSD_OVER_IMS_ONLY);
- doReturn(true).when(resources).getBoolean(
- com.android.internal.R.bool.config_allow_ussd_over_ims);
- doReturn(ServiceState.STATE_IN_SERVICE).when(mSST.mSS).getState();
-
- mImsPhoneUT.dial("*135#", new ImsPhone.ImsDialArgs.Builder().build());
- verify(mImsCT).sendUSSD(eq("*135#"), any());
- }
-
- @Test
- @SmallTest
- public void testHandleMessageCallRingContinue() throws Exception {
- Message m = Message.obtain(mImsPhoneUT.getHandler(), EVENT_CALL_RING_CONTINUE);
- mImsPhoneUT.handleMessage(m);
- }
-
private ServiceState getServiceStateDataAndVoice(int rat, int regState, boolean isRoaming) {
ServiceState ss = new ServiceState();
ss.setStateOutOfService();
diff --git a/tests/telephonytests/src/com/android/internal/telephony/metrics/ImsStatsTest.java b/tests/telephonytests/src/com/android/internal/telephony/metrics/ImsStatsTest.java
deleted file mode 100644
index c2b690f92c..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/metrics/ImsStatsTest.java
+++ /dev/null
@@ -1,725 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.internal.telephony.metrics;
-
-import static android.telephony.AccessNetworkConstants.TRANSPORT_TYPE_WLAN;
-import static android.telephony.AccessNetworkConstants.TRANSPORT_TYPE_WWAN;
-import static android.telephony.NetworkRegistrationInfo.DOMAIN_PS;
-import static android.telephony.ims.feature.MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_SMS;
-import static android.telephony.ims.feature.MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_UT;
-import static android.telephony.ims.feature.MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VIDEO;
-import static android.telephony.ims.feature.MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE;
-import static android.telephony.ims.stub.ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN;
-import static android.telephony.ims.stub.ImsRegistrationImplBase.REGISTRATION_TECH_LTE;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-
-import android.telephony.NetworkRegistrationInfo;
-import android.telephony.TelephonyManager;
-import android.telephony.ims.ImsReasonInfo;
-import android.telephony.ims.ProvisioningManager;
-import android.telephony.ims.feature.MmTelFeature.MmTelCapabilities;
-import android.telephony.ims.feature.MmTelFeature.MmTelCapabilities.MmTelCapability;
-import android.test.suitebuilder.annotation.SmallTest;
-
-import com.android.internal.telephony.Phone;
-import com.android.internal.telephony.TelephonyTest;
-import com.android.internal.telephony.imsphone.ImsPhone;
-import com.android.internal.telephony.nano.PersistAtomsProto.ImsRegistrationStats;
-import com.android.internal.telephony.nano.PersistAtomsProto.ImsRegistrationTermination;
-import com.android.internal.telephony.uicc.IccCardStatus.CardState;
-import com.android.internal.telephony.uicc.UiccSlot;
-
-import com.google.common.collect.ImmutableMap;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mock;
-
-import java.util.Map;
-
-public class ImsStatsTest extends TelephonyTest {
- private static final long START_TIME_MILLIS = 2000L;
- private static final int CARRIER1_ID = 1;
- private static final int CARRIER2_ID = 1187;
-
- @MmTelCapability
- private static final int CAPABILITY_TYPE_ALL =
- MmTelCapabilities.CAPABILITY_TYPE_VOICE
- | MmTelCapabilities.CAPABILITY_TYPE_VIDEO
- | MmTelCapabilities.CAPABILITY_TYPE_SMS
- | MmTelCapabilities.CAPABILITY_TYPE_UT;
-
- @Mock private UiccSlot mPhysicalSlot0;
- @Mock private UiccSlot mPhysicalSlot1;
- @Mock private Phone mSecondPhone;
- @Mock private ImsPhone mSecondImsPhone;
-
- private TestableImsStats mImsStats;
-
- private static class TestableImsStats extends ImsStats {
- private long mTimeMillis = START_TIME_MILLIS;
-
- TestableImsStats(ImsPhone imsPhone) {
- super(imsPhone);
- }
-
- @Override
- protected long getTimeMillis() {
- // NOTE: super class constructor will be executed before private field is set, which
- // gives the wrong start time (mTimeMillis will have its default value of 0L)
- return mTimeMillis == 0L ? START_TIME_MILLIS : mTimeMillis;
- }
-
- private void setTimeMillis(long timeMillis) {
- mTimeMillis = timeMillis;
- }
-
- private void incTimeMillis(long timeMillis) {
- mTimeMillis += timeMillis;
- }
- }
-
- @Before
- public void setUp() throws Exception {
- super.setUp(getClass().getSimpleName());
-
- doReturn(CARRIER1_ID).when(mPhone).getCarrierId();
- doReturn(mImsPhone).when(mPhone).getImsPhone();
- doReturn(mSST).when(mImsPhone).getServiceStateTracker();
-
- // WWAN PS RAT is LTE
- doReturn(
- new NetworkRegistrationInfo.Builder()
- .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_LTE)
- .build())
- .when(mServiceState)
- .getNetworkRegistrationInfo(DOMAIN_PS, TRANSPORT_TYPE_WWAN);
-
- // Single physical SIM
- doReturn(true).when(mPhysicalSlot0).isActive();
- doReturn(CardState.CARDSTATE_PRESENT).when(mPhysicalSlot0).getCardState();
- doReturn(false).when(mPhysicalSlot0).isEuicc();
- doReturn(new UiccSlot[] {mPhysicalSlot0}).when(mUiccController).getUiccSlots();
- doReturn(mPhysicalSlot0).when(mUiccController).getUiccSlot(0);
- doReturn(mPhysicalSlot0).when(mUiccController).getUiccSlotForPhone(0);
-
- mImsStats = new TestableImsStats(mImsPhone);
- }
-
- @After
- public void tearDown() throws Exception {
- super.tearDown();
- }
-
- @Test
- @SmallTest
- public void conclude_registered() throws Exception {
- // IMS over LTE
- mImsStats.onSetFeatureResponse(
- CAPABILITY_TYPE_VOICE,
- REGISTRATION_TECH_LTE,
- ProvisioningManager.PROVISIONING_VALUE_ENABLED);
- mImsStats.onSetFeatureResponse(
- CAPABILITY_TYPE_VIDEO,
- REGISTRATION_TECH_LTE,
- ProvisioningManager.PROVISIONING_VALUE_ENABLED);
- mImsStats.onSetFeatureResponse(
- CAPABILITY_TYPE_UT,
- REGISTRATION_TECH_LTE,
- ProvisioningManager.PROVISIONING_VALUE_ENABLED);
- mImsStats.onSetFeatureResponse(
- CAPABILITY_TYPE_SMS,
- REGISTRATION_TECH_LTE,
- ProvisioningManager.PROVISIONING_VALUE_ENABLED);
- mImsStats.onImsRegistered(TRANSPORT_TYPE_WWAN);
- mImsStats.onImsCapabilitiesChanged(
- REGISTRATION_TECH_LTE, new MmTelCapabilities(CAPABILITY_TYPE_ALL));
-
- mImsStats.incTimeMillis(2000L);
- mImsStats.conclude();
-
- // Duration should be counted
- ArgumentCaptor<ImsRegistrationStats> captor =
- ArgumentCaptor.forClass(ImsRegistrationStats.class);
- verify(mPersistAtomsStorage).addImsRegistrationStats(captor.capture());
- ImsRegistrationStats stats = captor.getValue();
- assertEquals(CARRIER1_ID, stats.carrierId);
- assertEquals(0, stats.simSlotIndex);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, stats.rat);
- assertEquals(2000L, stats.registeredMillis);
- assertEquals(2000L, stats.voiceCapableMillis);
- assertEquals(2000L, stats.voiceAvailableMillis);
- assertEquals(2000L, stats.videoCapableMillis);
- assertEquals(2000L, stats.videoAvailableMillis);
- assertEquals(2000L, stats.utCapableMillis);
- assertEquals(2000L, stats.utAvailableMillis);
- assertEquals(2000L, stats.smsCapableMillis);
- assertEquals(2000L, stats.smsAvailableMillis);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void conclude_registeredPartialFeatures() throws Exception {
- // IMS over LTE
- mImsStats.onSetFeatureResponse(
- CAPABILITY_TYPE_VOICE,
- REGISTRATION_TECH_LTE,
- ProvisioningManager.PROVISIONING_VALUE_ENABLED);
- mImsStats.onSetFeatureResponse(
- CAPABILITY_TYPE_VIDEO,
- REGISTRATION_TECH_LTE,
- ProvisioningManager.PROVISIONING_VALUE_ENABLED);
- mImsStats.onSetFeatureResponse(
- CAPABILITY_TYPE_UT,
- REGISTRATION_TECH_LTE,
- ProvisioningManager.PROVISIONING_VALUE_ENABLED);
- mImsStats.onSetFeatureResponse(
- CAPABILITY_TYPE_SMS,
- REGISTRATION_TECH_LTE,
- ProvisioningManager.PROVISIONING_VALUE_ENABLED);
- mImsStats.onImsRegistered(TRANSPORT_TYPE_WWAN);
- mImsStats.onImsCapabilitiesChanged(
- REGISTRATION_TECH_LTE, new MmTelCapabilities(CAPABILITY_TYPE_VOICE));
-
- mImsStats.incTimeMillis(2000L);
- mImsStats.conclude();
-
- // Duration should be counted
- ArgumentCaptor<ImsRegistrationStats> captor =
- ArgumentCaptor.forClass(ImsRegistrationStats.class);
- verify(mPersistAtomsStorage).addImsRegistrationStats(captor.capture());
- ImsRegistrationStats stats = captor.getValue();
- assertEquals(CARRIER1_ID, stats.carrierId);
- assertEquals(0, stats.simSlotIndex);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, stats.rat);
- assertEquals(2000L, stats.registeredMillis);
- assertEquals(2000L, stats.voiceCapableMillis);
- assertEquals(2000L, stats.voiceAvailableMillis);
- assertEquals(2000L, stats.videoCapableMillis);
- assertEquals(0L, stats.videoAvailableMillis);
- assertEquals(2000L, stats.utCapableMillis);
- assertEquals(0L, stats.utAvailableMillis);
- assertEquals(2000L, stats.smsCapableMillis);
- assertEquals(0L, stats.smsAvailableMillis);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void conclude_registeredVoiceOnly() throws Exception {
- // Wifi calling
- mImsStats.onSetFeatureResponse(
- CAPABILITY_TYPE_VOICE,
- REGISTRATION_TECH_LTE,
- ProvisioningManager.PROVISIONING_VALUE_ENABLED);
- mImsStats.onSetFeatureResponse(
- CAPABILITY_TYPE_VOICE,
- REGISTRATION_TECH_IWLAN,
- ProvisioningManager.PROVISIONING_VALUE_ENABLED);
- mImsStats.onSetFeatureResponse(
- CAPABILITY_TYPE_VIDEO,
- REGISTRATION_TECH_LTE,
- ProvisioningManager.PROVISIONING_VALUE_ENABLED);
- mImsStats.onSetFeatureResponse(
- CAPABILITY_TYPE_UT,
- REGISTRATION_TECH_LTE,
- ProvisioningManager.PROVISIONING_VALUE_ENABLED);
- mImsStats.onImsRegistered(TRANSPORT_TYPE_WLAN);
- mImsStats.onImsCapabilitiesChanged(
- REGISTRATION_TECH_IWLAN, new MmTelCapabilities(CAPABILITY_TYPE_VOICE));
-
- mImsStats.incTimeMillis(2000L);
- mImsStats.conclude();
-
- // Duration should be counted
- ArgumentCaptor<ImsRegistrationStats> captor =
- ArgumentCaptor.forClass(ImsRegistrationStats.class);
- verify(mPersistAtomsStorage).addImsRegistrationStats(captor.capture());
- ImsRegistrationStats stats = captor.getValue();
- assertEquals(CARRIER1_ID, stats.carrierId);
- assertEquals(0, stats.simSlotIndex);
- assertEquals(TelephonyManager.NETWORK_TYPE_IWLAN, stats.rat);
- assertEquals(2000L, stats.registeredMillis);
- assertEquals(2000L, stats.voiceCapableMillis);
- assertEquals(2000L, stats.voiceAvailableMillis);
- assertEquals(0L, stats.videoCapableMillis);
- assertEquals(0L, stats.videoAvailableMillis);
- assertEquals(0L, stats.utCapableMillis);
- assertEquals(0L, stats.utAvailableMillis);
- assertEquals(0L, stats.smsCapableMillis);
- assertEquals(0L, stats.smsAvailableMillis);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void conclude_notRegistered() throws Exception {
- // IMS over LTE
- mImsStats.onSetFeatureResponse(
- CAPABILITY_TYPE_VOICE,
- REGISTRATION_TECH_LTE,
- ProvisioningManager.PROVISIONING_VALUE_ENABLED);
- mImsStats.onSetFeatureResponse(
- CAPABILITY_TYPE_VIDEO,
- REGISTRATION_TECH_LTE,
- ProvisioningManager.PROVISIONING_VALUE_ENABLED);
- mImsStats.onSetFeatureResponse(
- CAPABILITY_TYPE_UT,
- REGISTRATION_TECH_LTE,
- ProvisioningManager.PROVISIONING_VALUE_ENABLED);
- mImsStats.onSetFeatureResponse(
- CAPABILITY_TYPE_SMS,
- REGISTRATION_TECH_LTE,
- ProvisioningManager.PROVISIONING_VALUE_ENABLED);
- mImsStats.onImsCapabilitiesChanged(
- REGISTRATION_TECH_LTE, new MmTelCapabilities(CAPABILITY_TYPE_ALL));
-
- mImsStats.incTimeMillis(2000L);
- mImsStats.conclude();
-
- // No atom should be generated
- ArgumentCaptor<ImsRegistrationStats> captor =
- ArgumentCaptor.forClass(ImsRegistrationStats.class);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void onImsCapabilitiesChanged_sameTech() throws Exception {
- mImsStats.onSetFeatureResponse(
- CAPABILITY_TYPE_VOICE,
- REGISTRATION_TECH_LTE,
- ProvisioningManager.PROVISIONING_VALUE_ENABLED);
- mImsStats.onImsRegistered(TRANSPORT_TYPE_WWAN);
-
- mImsStats.incTimeMillis(2000L);
- mImsStats.onImsCapabilitiesChanged(
- REGISTRATION_TECH_LTE, new MmTelCapabilities(CAPABILITY_TYPE_VOICE));
-
- // Atom with previous feature availability should be generated
- ArgumentCaptor<ImsRegistrationStats> captor =
- ArgumentCaptor.forClass(ImsRegistrationStats.class);
- verify(mPersistAtomsStorage).addImsRegistrationStats(captor.capture());
- ImsRegistrationStats stats = captor.getValue();
- assertEquals(CARRIER1_ID, stats.carrierId);
- assertEquals(0, stats.simSlotIndex);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, stats.rat);
- assertEquals(2000L, stats.registeredMillis);
- assertEquals(2000L, stats.voiceCapableMillis);
- assertEquals(0L, stats.voiceAvailableMillis);
- assertEquals(0L, stats.videoCapableMillis);
- assertEquals(0L, stats.videoAvailableMillis);
- assertEquals(0L, stats.utCapableMillis);
- assertEquals(0L, stats.utAvailableMillis);
- assertEquals(0L, stats.smsCapableMillis);
- assertEquals(0L, stats.smsAvailableMillis);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void onSetFeatureResponse_sameTech() throws Exception {
- mImsStats.onSetFeatureResponse(
- CAPABILITY_TYPE_VOICE,
- REGISTRATION_TECH_LTE,
- ProvisioningManager.PROVISIONING_VALUE_ENABLED);
- mImsStats.onImsRegistered(TRANSPORT_TYPE_WWAN);
-
- mImsStats.incTimeMillis(2000L);
- mImsStats.onSetFeatureResponse(
- CAPABILITY_TYPE_VIDEO,
- REGISTRATION_TECH_LTE,
- ProvisioningManager.PROVISIONING_VALUE_ENABLED);
-
- // Atom with previous capability should be generated
- ArgumentCaptor<ImsRegistrationStats> captor =
- ArgumentCaptor.forClass(ImsRegistrationStats.class);
- verify(mPersistAtomsStorage).addImsRegistrationStats(captor.capture());
- ImsRegistrationStats stats = captor.getValue();
- assertEquals(CARRIER1_ID, stats.carrierId);
- assertEquals(0, stats.simSlotIndex);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, stats.rat);
- assertEquals(2000L, stats.registeredMillis);
- assertEquals(2000L, stats.voiceCapableMillis);
- assertEquals(0L, stats.voiceAvailableMillis);
- assertEquals(0L, stats.videoCapableMillis);
- assertEquals(0L, stats.videoAvailableMillis);
- assertEquals(0L, stats.utCapableMillis);
- assertEquals(0L, stats.utAvailableMillis);
- assertEquals(0L, stats.smsCapableMillis);
- assertEquals(0L, stats.smsAvailableMillis);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void onImsRegistered_differentTech() throws Exception {
- mImsStats.onImsRegistered(TRANSPORT_TYPE_WWAN);
- mImsStats.incTimeMillis(2000L);
- mImsStats.onImsRegistered(TRANSPORT_TYPE_WLAN);
- mImsStats.incTimeMillis(2000L);
- mImsStats.onImsRegistered(TRANSPORT_TYPE_WWAN);
-
- // At this point, the first 2 registrations should have their durations counted
- ArgumentCaptor<ImsRegistrationStats> captor =
- ArgumentCaptor.forClass(ImsRegistrationStats.class);
- verify(mPersistAtomsStorage, times(2)).addImsRegistrationStats(captor.capture());
- assertEquals(2, captor.getAllValues().size());
- ImsRegistrationStats statsLte = captor.getAllValues().get(0);
- assertEquals(CARRIER1_ID, statsLte.carrierId);
- assertEquals(0, statsLte.simSlotIndex);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, statsLte.rat);
- assertEquals(2000L, statsLte.registeredMillis);
- assertEquals(0L, statsLte.voiceCapableMillis);
- assertEquals(0L, statsLte.voiceAvailableMillis);
- assertEquals(0L, statsLte.videoCapableMillis);
- assertEquals(0L, statsLte.videoAvailableMillis);
- assertEquals(0L, statsLte.utCapableMillis);
- assertEquals(0L, statsLte.utAvailableMillis);
- assertEquals(0L, statsLte.smsCapableMillis);
- assertEquals(0L, statsLte.smsAvailableMillis);
- ImsRegistrationStats statsWifi = captor.getAllValues().get(1);
- assertEquals(CARRIER1_ID, statsWifi.carrierId);
- assertEquals(0, statsWifi.simSlotIndex);
- assertEquals(TelephonyManager.NETWORK_TYPE_IWLAN, statsWifi.rat);
- assertEquals(2000L, statsWifi.registeredMillis);
- assertEquals(0L, statsWifi.voiceCapableMillis);
- assertEquals(0L, statsWifi.voiceAvailableMillis);
- assertEquals(0L, statsWifi.videoCapableMillis);
- assertEquals(0L, statsWifi.videoAvailableMillis);
- assertEquals(0L, statsWifi.utCapableMillis);
- assertEquals(0L, statsWifi.utAvailableMillis);
- assertEquals(0L, statsWifi.smsCapableMillis);
- assertEquals(0L, statsWifi.smsAvailableMillis);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void onImsUnregistered_setupFailure() throws Exception {
- mImsStats.onImsUnregistered(
- new ImsReasonInfo(ImsReasonInfo.CODE_REGISTRATION_ERROR, 999, "Timeout"));
-
- // Atom with termination info should be generated
- ArgumentCaptor<ImsRegistrationTermination> captor =
- ArgumentCaptor.forClass(ImsRegistrationTermination.class);
- verify(mPersistAtomsStorage).addImsRegistrationTermination(captor.capture());
- ImsRegistrationTermination termination = captor.getValue();
- assertEquals(CARRIER1_ID, termination.carrierId);
- assertFalse(termination.isMultiSim);
- assertEquals(TelephonyManager.NETWORK_TYPE_UNKNOWN, termination.ratAtEnd);
- assertTrue(termination.setupFailed);
- assertEquals(ImsReasonInfo.CODE_REGISTRATION_ERROR, termination.reasonCode);
- assertEquals(999, termination.extraCode);
- assertEquals("Timeout", termination.extraMessage);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void onImsUnregistered_setupFailureWithProgress() throws Exception {
- mImsStats.onImsRegistering(REGISTRATION_TECH_LTE);
- mImsStats.incTimeMillis(2000L);
- mImsStats.onImsUnregistered(
- new ImsReasonInfo(ImsReasonInfo.CODE_REGISTRATION_ERROR, 999, "Timeout"));
-
- // Atom with termination info should be generated
- ArgumentCaptor<ImsRegistrationTermination> captor =
- ArgumentCaptor.forClass(ImsRegistrationTermination.class);
- verify(mPersistAtomsStorage).addImsRegistrationTermination(captor.capture());
- ImsRegistrationTermination termination = captor.getValue();
- assertEquals(CARRIER1_ID, termination.carrierId);
- assertFalse(termination.isMultiSim);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, termination.ratAtEnd);
- assertTrue(termination.setupFailed);
- assertEquals(ImsReasonInfo.CODE_REGISTRATION_ERROR, termination.reasonCode);
- assertEquals(999, termination.extraCode);
- assertEquals("Timeout", termination.extraMessage);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void onImsUnregistered_afterRegistered() throws Exception {
- mImsStats.onImsRegistered(TRANSPORT_TYPE_WWAN);
- mImsStats.incTimeMillis(2000L);
- mImsStats.onImsUnregistered(
- new ImsReasonInfo(ImsReasonInfo.CODE_REGISTRATION_ERROR, 999, "Timeout"));
-
- // Atom with termination info and durations should be generated
- ArgumentCaptor<ImsRegistrationStats> statsCaptor =
- ArgumentCaptor.forClass(ImsRegistrationStats.class);
- verify(mPersistAtomsStorage).addImsRegistrationStats(statsCaptor.capture());
- ImsRegistrationStats stats = statsCaptor.getValue();
- assertEquals(CARRIER1_ID, stats.carrierId);
- assertEquals(0, stats.simSlotIndex);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, stats.rat);
- assertEquals(2000L, stats.registeredMillis);
- assertEquals(0L, stats.voiceCapableMillis);
- assertEquals(0L, stats.voiceAvailableMillis);
- assertEquals(0L, stats.videoCapableMillis);
- assertEquals(0L, stats.videoAvailableMillis);
- assertEquals(0L, stats.utCapableMillis);
- assertEquals(0L, stats.utAvailableMillis);
- assertEquals(0L, stats.smsCapableMillis);
- assertEquals(0L, stats.smsAvailableMillis);
- ArgumentCaptor<ImsRegistrationTermination> terminationCaptor =
- ArgumentCaptor.forClass(ImsRegistrationTermination.class);
- verify(mPersistAtomsStorage).addImsRegistrationTermination(terminationCaptor.capture());
- ImsRegistrationTermination termination = terminationCaptor.getValue();
- assertEquals(CARRIER1_ID, termination.carrierId);
- assertFalse(termination.isMultiSim);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, termination.ratAtEnd);
- assertFalse(termination.setupFailed);
- assertEquals(ImsReasonInfo.CODE_REGISTRATION_ERROR, termination.reasonCode);
- assertEquals(999, termination.extraCode);
- assertEquals("Timeout", termination.extraMessage);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void onImsUnregistered_nullMessage() throws Exception {
- mImsStats.onImsUnregistered(
- new ImsReasonInfo(ImsReasonInfo.CODE_REGISTRATION_ERROR, 0, null));
-
- // Atom with termination info should be generated, null string should be sanitized
- ArgumentCaptor<ImsRegistrationTermination> captor =
- ArgumentCaptor.forClass(ImsRegistrationTermination.class);
- verify(mPersistAtomsStorage).addImsRegistrationTermination(captor.capture());
- ImsRegistrationTermination termination = captor.getValue();
- assertEquals(CARRIER1_ID, termination.carrierId);
- assertFalse(termination.isMultiSim);
- assertEquals(TelephonyManager.NETWORK_TYPE_UNKNOWN, termination.ratAtEnd);
- assertTrue(termination.setupFailed);
- assertEquals(ImsReasonInfo.CODE_REGISTRATION_ERROR, termination.reasonCode);
- assertEquals(0, termination.extraCode);
- assertEquals("", termination.extraMessage);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void onImsUnregistered_longMessage() throws Exception {
- String longExtraMessage =
- "This message is too long -- it has more than 128 characters: "
- + "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"
- + "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"
- + " This is the end of the message.";
- mImsStats.onImsUnregistered(
- new ImsReasonInfo(ImsReasonInfo.CODE_REGISTRATION_ERROR, 0, longExtraMessage));
-
- // Atom with termination info should be generated, null string should be sanitized
- ArgumentCaptor<ImsRegistrationTermination> captor =
- ArgumentCaptor.forClass(ImsRegistrationTermination.class);
- verify(mPersistAtomsStorage).addImsRegistrationTermination(captor.capture());
- ImsRegistrationTermination termination = captor.getValue();
- assertEquals(CARRIER1_ID, termination.carrierId);
- assertFalse(termination.isMultiSim);
- assertEquals(TelephonyManager.NETWORK_TYPE_UNKNOWN, termination.ratAtEnd);
- assertTrue(termination.setupFailed);
- assertEquals(ImsReasonInfo.CODE_REGISTRATION_ERROR, termination.reasonCode);
- assertEquals(0, termination.extraCode);
- assertEquals(128, termination.extraMessage.length());
- assertTrue(longExtraMessage.startsWith(termination.extraMessage));
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void filterExtraMessage_noNeedToFilter() throws Exception {
- final String[] messages = {
- "Q.850;cause=16",
- "SIP;cause=200",
- "q.850",
- "600",
- "Call ended during conference merge process.",
- "cc_term_noreply_tmr_expired",
- "[e] user triggered",
- "normal end of call",
- "cc_q850_017_user_busy",
- "service unavailable (1:223)",
- "IP Change",
- "rtp-rtcp timeout",
- "0x0000030b",
- "CD-021: ISP Problem",
- "IP;cause=487;text=\"Originator canceled;Canceled(t),iCode=CC_SIP_REQUEST_TERMINATED\"",
- "pt: asr: insufficient_bearer_resources",
- "po: aaa: result_code=0 exp_result_code=5065",
- "a peer released.total external peer:1. allowed:2. clear the remain parties(o),"
- + "icode=cc_sip_request_timeout"
- };
-
- for (String message : messages) {
- assertEquals(message, ImsStats.filterExtraMessage(message));
- }
- }
-
- @Test
- @SmallTest
- public void filterExtraMessage_needToFilter() throws Exception {
- Map<String, String> originalAndExpectedMessages = ImmutableMap.<String, String>builder()
- // UUIDs
- .put(
- "Q.850;cause=34;text=\"12345678-abcd-ef12-34ab-000000000012;"
- + "User is busy and currently active on another call.\"",
- "Q.850;cause=34;text=\"<UUID_REDACTED>;"
- + "User is busy and currently active on another call.\"")
- .put(
- "Q.850;cause=34;text=\"12345678-ABCD-EF12-34AB-000000000012;"
- + "User is busy and currently active on another call.\"",
- "Q.850;cause=34;text=\"<UUID_REDACTED>;"
- + "User is busy and currently active on another call.\"")
- // URIs
- .put(
- "SIP;cause=500;text=\"sip:+1234567890@irps.voip.telefonica.de;user=phone"
- + " clear the call.;Canceled(t)\"",
- "SIP;cause=500;text=\"sip:<REDACTED>;user=phone"
- + " clear the call.;Canceled(t)\"")
- .put(
- "SIP;cause=500;text=\"SIP:+1234567890@irps.voip.telefonica.de;user=phone"
- + " clear the call.;Canceled(t)\"",
- "SIP;cause=500;text=\"SIP:<REDACTED>;user=phone"
- + " clear the call.;Canceled(t)\"")
- // IP addresses
- .put(
- "dtls handshake error[timeout][2607:F8B0::1] and client disconnected",
- "dtls handshake error[timeout][<IPV6_REDACTED>] and client disconnected")
- .put(
- "dtls handshake error[timeout][2607:f8b0::1] and client disconnected",
- "dtls handshake error[timeout][<IPV6_REDACTED>] and client disconnected")
- .put(
- "dtls handshake error 2607:f8b0:1:2:3:4:56:789",
- "dtls handshake error <IPV6_REDACTED>")
- .put(
- "dtls handshake error[timeout][8.8.8.8] and client disconnected",
- "dtls handshake error[timeout][<IPV4_REDACTED>] and client disconnected")
- .put("8.8.8.8 client disconnected", "<IPV4_REDACTED> client disconnected")
- // IMEIs/IMSIs
- .put(
- "call completed elsewhere by instance 313460000000001",
- "call completed elsewhere by instance <IMEI_IMSI_REDACTED>")
- .put(
- "call completed elsewhere by instance 31346000-000000-1",
- "call completed elsewhere by instance <IMEI_REDACTED>")
- .put(
- "call completed elsewhere by instance 31-346000-000000-1",
- "call completed elsewhere by instance <IMEI_REDACTED>")
- .put(
- "call completed elsewhere by instance 31-346000-000000-12",
- "call completed elsewhere by instance <IMEI_REDACTED>")
- .put(
- "399 123.4567.89.ATS.blah.ims.mnc123.mcc456.3gppnetwork.org"
- + " \"Failure cause code is sip status code.\"",
- "399 <HOSTNAME_REDACTED> \"Failure cause code is sip status code.\"")
- // Unknown IDs
- .put(
- "01200.30004.a.560.789.123.0.0.00045.00000006"
- + " released the session because of netfail by no media",
- // "123.0.0.0" looks like IPv4
- "<ID_REDACTED><IPV4_REDACTED><ID_REDACTED>"
- + " released the session because of netfail by no media")
- .put(
- "example.cpp,1234,12-300-450-67-89123456:-12345678,"
- + "tyringtimeout:timer b expired(t)",
- "example.cpp,1234,<ID_REDACTED>:-<ID_REDACTED>,"
- + "tyringtimeout:timer b expired(t)")
- .put(
- "ss120000f123l1234 invite 2xx after cancel rsp has been received",
- "ss<ID_REDACTED>l1234 invite 2xx after cancel rsp has been received")
- .put(
- "X.int;reasoncode=0x00000123;add-info=0123.00AB.0001",
- "X.int;reasoncode=0x00000123;add-info=<ID_REDACTED>")
- .put(
- "X.int;reasoncode=0x00123abc;add-info=0123.00AB.0001",
- "X.int;reasoncode=0x<ID_REDACTED>;add-info=<ID_REDACTED>")
- .put(
- "Cx Unable To Comply 1203045067D8009",
- "Cx Unable To Comply <ID_REDACTED>")
- .build();
-
- for (Map.Entry<String, String> entry : originalAndExpectedMessages.entrySet()) {
- assertEquals(entry.getValue(), ImsStats.filterExtraMessage(entry.getKey()));
- }
- }
-
- @Test
- @SmallTest
- public void onImsUnregistered_multiSim() throws Exception {
- doReturn(mSecondImsPhone).when(mSecondPhone).getImsPhone();
- doReturn(mSecondPhone).when(mSecondImsPhone).getDefaultPhone();
- doReturn(1).when(mSecondPhone).getPhoneId();
- doReturn(1).when(mSecondImsPhone).getPhoneId();
- doReturn(CARRIER2_ID).when(mSecondPhone).getCarrierId();
- doReturn(true).when(mPhysicalSlot1).isActive();
- doReturn(CardState.CARDSTATE_PRESENT).when(mPhysicalSlot1).getCardState();
- doReturn(false).when(mPhysicalSlot1).isEuicc();
- doReturn(new UiccSlot[] {mPhysicalSlot0, mPhysicalSlot1})
- .when(mUiccController)
- .getUiccSlots();
- doReturn(mPhysicalSlot1).when(mUiccController).getUiccSlot(1);
- doReturn(mPhysicalSlot1).when(mUiccController).getUiccSlotForPhone(1);
- // Reusing service state tracker from phone 0 for simplicity
- doReturn(mSST).when(mSecondPhone).getServiceStateTracker();
- doReturn(mSST).when(mSecondImsPhone).getServiceStateTracker();
- mImsStats = new TestableImsStats(mSecondImsPhone);
- mImsStats.onImsRegistered(TRANSPORT_TYPE_WWAN);
- mImsStats.incTimeMillis(2000L);
- mImsStats.onImsUnregistered(
- new ImsReasonInfo(ImsReasonInfo.CODE_REGISTRATION_ERROR, 999, "Timeout"));
-
- // Atom with termination info and durations should be generated
- ArgumentCaptor<ImsRegistrationStats> statsCaptor =
- ArgumentCaptor.forClass(ImsRegistrationStats.class);
- verify(mPersistAtomsStorage).addImsRegistrationStats(statsCaptor.capture());
- ImsRegistrationStats stats = statsCaptor.getValue();
- assertEquals(CARRIER2_ID, stats.carrierId);
- assertEquals(1, stats.simSlotIndex);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, stats.rat);
- assertEquals(2000L, stats.registeredMillis);
- assertEquals(0L, stats.voiceCapableMillis);
- assertEquals(0L, stats.voiceAvailableMillis);
- assertEquals(0L, stats.videoCapableMillis);
- assertEquals(0L, stats.videoAvailableMillis);
- assertEquals(0L, stats.utCapableMillis);
- assertEquals(0L, stats.utAvailableMillis);
- assertEquals(0L, stats.smsCapableMillis);
- assertEquals(0L, stats.smsAvailableMillis);
- ArgumentCaptor<ImsRegistrationTermination> terminationCaptor =
- ArgumentCaptor.forClass(ImsRegistrationTermination.class);
- verify(mPersistAtomsStorage).addImsRegistrationTermination(terminationCaptor.capture());
- ImsRegistrationTermination termination = terminationCaptor.getValue();
- assertEquals(CARRIER2_ID, termination.carrierId);
- assertTrue(termination.isMultiSim);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, termination.ratAtEnd);
- assertFalse(termination.setupFailed);
- assertEquals(ImsReasonInfo.CODE_REGISTRATION_ERROR, termination.reasonCode);
- assertEquals(999, termination.extraCode);
- assertEquals("Timeout", termination.extraMessage);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/metrics/MetricsCollectorTest.java b/tests/telephonytests/src/com/android/internal/telephony/metrics/MetricsCollectorTest.java
index cd156867bc..103cae1dce 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/metrics/MetricsCollectorTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/metrics/MetricsCollectorTest.java
@@ -16,8 +16,6 @@
package com.android.internal.telephony.metrics;
-import static com.android.internal.telephony.TelephonyStatsLog.CELLULAR_DATA_SERVICE_SWITCH;
-import static com.android.internal.telephony.TelephonyStatsLog.CELLULAR_SERVICE_STATE;
import static com.android.internal.telephony.TelephonyStatsLog.SIM_SLOT_STATE;
import static com.android.internal.telephony.TelephonyStatsLog.SUPPORTED_RADIO_ACCESS_FAMILY;
import static com.android.internal.telephony.TelephonyStatsLog.VOICE_CALL_RAT_USAGE;
@@ -40,9 +38,7 @@ import android.util.StatsEvent;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneFactory;
import com.android.internal.telephony.TelephonyTest;
-import com.android.internal.telephony.nano.PersistAtomsProto.CellularDataServiceSwitch;
-import com.android.internal.telephony.nano.PersistAtomsProto.CellularServiceState;
-import com.android.internal.telephony.nano.PersistAtomsProto.VoiceCallRatUsage;
+import com.android.internal.telephony.nano.PersistAtomsProto.RawVoiceCallRatUsage;
import com.android.internal.telephony.nano.PersistAtomsProto.VoiceCallSession;
import com.android.internal.telephony.uicc.IccCardStatus.CardState;
import com.android.internal.telephony.uicc.UiccCard;
@@ -86,8 +82,6 @@ public class MetricsCollectorTest extends TelephonyTest {
@Mock private UiccSlot mEsimSlot;
@Mock private UiccCard mActiveCard;
- @Mock private ServiceStateStats mServiceStateStats;
-
private MetricsCollector mMetricsCollector;
@Before
@@ -95,8 +89,6 @@ public class MetricsCollectorTest extends TelephonyTest {
super.setUp(getClass().getSimpleName());
mMetricsCollector = new MetricsCollector(mContext);
mMetricsCollector.setPersistAtomsStorage(mPersistAtomsStorage);
- doReturn(mSST).when(mSecondPhone).getServiceStateTracker();
- doReturn(mServiceStateStats).when(mSST).getServiceStateStats();
}
@After
@@ -224,7 +216,7 @@ public class MetricsCollectorTest extends TelephonyTest {
@Test
@SmallTest
public void onPullAtom_voiceCallRatUsage_empty() throws Exception {
- doReturn(new VoiceCallRatUsage[0])
+ doReturn(new RawVoiceCallRatUsage[0])
.when(mPersistAtomsStorage)
.getVoiceCallRatUsages(anyLong());
List<StatsEvent> actualAtoms = new ArrayList<>();
@@ -252,11 +244,11 @@ public class MetricsCollectorTest extends TelephonyTest {
@Test
@SmallTest
public void onPullAtom_voiceCallRatUsage_bucketWithTooFewCalls() throws Exception {
- VoiceCallRatUsage usage1 = new VoiceCallRatUsage();
+ RawVoiceCallRatUsage usage1 = new RawVoiceCallRatUsage();
usage1.callCount = MIN_CALLS_PER_BUCKET;
- VoiceCallRatUsage usage2 = new VoiceCallRatUsage();
+ RawVoiceCallRatUsage usage2 = new RawVoiceCallRatUsage();
usage2.callCount = MIN_CALLS_PER_BUCKET - 1L;
- doReturn(new VoiceCallRatUsage[] {usage1, usage1, usage1, usage2})
+ doReturn(new RawVoiceCallRatUsage[] {usage1, usage1, usage1, usage2})
.when(mPersistAtomsStorage)
.getVoiceCallRatUsages(anyLong());
List<StatsEvent> actualAtoms = new ArrayList<>();
@@ -311,95 +303,4 @@ public class MetricsCollectorTest extends TelephonyTest {
assertThat(result).isEqualTo(StatsManager.PULL_SUCCESS);
// TODO(b/153196254): verify atom contents
}
-
- @Test
- @SmallTest
- public void onPullAtom_cellularDataServiceSwitch_empty() throws Exception {
- doReturn(new CellularDataServiceSwitch[0])
- .when(mPersistAtomsStorage)
- .getCellularDataServiceSwitches(anyLong());
- List<StatsEvent> actualAtoms = new ArrayList<>();
-
- int result = mMetricsCollector.onPullAtom(CELLULAR_DATA_SERVICE_SWITCH, actualAtoms);
-
- assertThat(actualAtoms).hasSize(0);
- assertThat(result).isEqualTo(StatsManager.PULL_SUCCESS);
- // TODO(b/153196254): verify atom contents
- }
-
- @Test
- @SmallTest
- public void onPullAtom_cellularDataServiceSwitch_tooFrequent() throws Exception {
- doReturn(null).when(mPersistAtomsStorage).getCellularDataServiceSwitches(anyLong());
- List<StatsEvent> actualAtoms = new ArrayList<>();
-
- int result = mMetricsCollector.onPullAtom(CELLULAR_DATA_SERVICE_SWITCH, actualAtoms);
-
- assertThat(actualAtoms).hasSize(0);
- assertThat(result).isEqualTo(StatsManager.PULL_SKIP);
- verify(mPersistAtomsStorage, times(1))
- .getCellularDataServiceSwitches(eq(MIN_COOLDOWN_MILLIS));
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void onPullAtom_cellularDataServiceSwitch_multipleSwitches() throws Exception {
- CellularDataServiceSwitch serviceSwitch = new CellularDataServiceSwitch();
- doReturn(new CellularDataServiceSwitch[] {serviceSwitch, serviceSwitch, serviceSwitch})
- .when(mPersistAtomsStorage)
- .getCellularDataServiceSwitches(anyLong());
- List<StatsEvent> actualAtoms = new ArrayList<>();
-
- int result = mMetricsCollector.onPullAtom(CELLULAR_DATA_SERVICE_SWITCH, actualAtoms);
-
- assertThat(actualAtoms).hasSize(3);
- assertThat(result).isEqualTo(StatsManager.PULL_SUCCESS);
- // TODO(b/153196254): verify atom contents
- }
-
- @Test
- @SmallTest
- public void onPullAtom_cellularServiceState_empty() throws Exception {
- doReturn(new CellularServiceState[0])
- .when(mPersistAtomsStorage)
- .getCellularServiceStates(anyLong());
- List<StatsEvent> actualAtoms = new ArrayList<>();
-
- int result = mMetricsCollector.onPullAtom(CELLULAR_SERVICE_STATE, actualAtoms);
-
- assertThat(actualAtoms).hasSize(0);
- assertThat(result).isEqualTo(StatsManager.PULL_SUCCESS);
- // TODO(b/153196254): verify atom contents
- }
-
- @Test
- @SmallTest
- public void onPullAtom_cellularServiceState_tooFrequent() throws Exception {
- doReturn(null).when(mPersistAtomsStorage).getCellularServiceStates(anyLong());
- List<StatsEvent> actualAtoms = new ArrayList<>();
-
- int result = mMetricsCollector.onPullAtom(CELLULAR_SERVICE_STATE, actualAtoms);
-
- assertThat(actualAtoms).hasSize(0);
- assertThat(result).isEqualTo(StatsManager.PULL_SKIP);
- verify(mPersistAtomsStorage, times(1)).getCellularServiceStates(eq(MIN_COOLDOWN_MILLIS));
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void onPullAtom_cellularServiceState_multipleStates() throws Exception {
- CellularServiceState state = new CellularServiceState();
- doReturn(new CellularServiceState[] {state, state, state})
- .when(mPersistAtomsStorage)
- .getCellularServiceStates(anyLong());
- List<StatsEvent> actualAtoms = new ArrayList<>();
-
- int result = mMetricsCollector.onPullAtom(CELLULAR_SERVICE_STATE, actualAtoms);
-
- assertThat(actualAtoms).hasSize(3);
- assertThat(result).isEqualTo(StatsManager.PULL_SUCCESS);
- // TODO(b/153196254): verify atom contents
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/metrics/PersistAtomsStorageTest.java b/tests/telephonytests/src/com/android/internal/telephony/metrics/PersistAtomsStorageTest.java
index df158c1551..ac1d73f886 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/metrics/PersistAtomsStorageTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/metrics/PersistAtomsStorageTest.java
@@ -37,20 +37,14 @@ import static org.mockito.Mockito.times;
import android.annotation.Nullable;
import android.content.Context;
-import android.os.Build;
import android.telephony.DisconnectCause;
-import android.telephony.ServiceState;
import android.telephony.TelephonyManager;
import android.telephony.ims.ImsReasonInfo;
import android.test.suitebuilder.annotation.SmallTest;
import com.android.internal.telephony.TelephonyTest;
-import com.android.internal.telephony.nano.PersistAtomsProto.CellularDataServiceSwitch;
-import com.android.internal.telephony.nano.PersistAtomsProto.CellularServiceState;
-import com.android.internal.telephony.nano.PersistAtomsProto.ImsRegistrationStats;
-import com.android.internal.telephony.nano.PersistAtomsProto.ImsRegistrationTermination;
import com.android.internal.telephony.nano.PersistAtomsProto.PersistAtoms;
-import com.android.internal.telephony.nano.PersistAtomsProto.VoiceCallRatUsage;
+import com.android.internal.telephony.nano.PersistAtomsProto.RawVoiceCallRatUsage;
import com.android.internal.telephony.nano.PersistAtomsProto.VoiceCallSession;
import com.android.internal.telephony.nano.TelephonyProto.TelephonyCallSession.Event.AudioCodec;
import com.android.internal.telephony.protobuf.nano.MessageNano;
@@ -69,8 +63,6 @@ import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Comparator;
-import java.util.LinkedList;
-import java.util.Queue;
public class PersistAtomsStorageTest extends TelephonyTest {
private static final String TEST_FILE = "PersistAtomsStorageTest.pb";
@@ -96,39 +88,14 @@ public class PersistAtomsStorageTest extends TelephonyTest {
// failed call
private VoiceCallSession mCall4Proto;
- private VoiceCallRatUsage mCarrier1LteUsageProto;
- private VoiceCallRatUsage mCarrier1UmtsUsageProto;
- private VoiceCallRatUsage mCarrier2LteUsageProto;
- private VoiceCallRatUsage mCarrier3LteUsageProto;
- private VoiceCallRatUsage mCarrier3GsmUsageProto;
+ private RawVoiceCallRatUsage mCarrier1LteUsageProto;
+ private RawVoiceCallRatUsage mCarrier1UmtsUsageProto;
+ private RawVoiceCallRatUsage mCarrier2LteUsageProto;
+ private RawVoiceCallRatUsage mCarrier3LteUsageProto;
+ private RawVoiceCallRatUsage mCarrier3GsmUsageProto;
private VoiceCallSession[] mVoiceCallSessions;
- private VoiceCallRatUsage[] mVoiceCallRatUsages;
-
- // data service state switch for slot 0 and 1
- private CellularDataServiceSwitch mServiceSwitch1Proto;
- private CellularDataServiceSwitch mServiceSwitch2Proto;
-
- // service states for slot 0 and 1
- private CellularServiceState mServiceState1Proto;
- private CellularServiceState mServiceState2Proto;
- private CellularServiceState mServiceState3Proto;
- private CellularServiceState mServiceState4Proto;
-
- private CellularDataServiceSwitch[] mServiceSwitches;
- private CellularServiceState[] mServiceStates;
-
- // IMS registrations for slot 0 and 1
- private ImsRegistrationStats mImsRegistrationStatsLte0;
- private ImsRegistrationStats mImsRegistrationStatsWifi0;
- private ImsRegistrationStats mImsRegistrationStatsLte1;
-
- // IMS registration terminations for slot 0 and 1
- private ImsRegistrationTermination mImsRegistrationTerminationLte;
- private ImsRegistrationTermination mImsRegistrationTerminationWifi;
-
- private ImsRegistrationStats[] mImsRegistrationStats;
- private ImsRegistrationTermination[] mImsRegistrationTerminations;
+ private RawVoiceCallRatUsage[] mVoiceCallRatUsages;
private void makeTestData() {
// MO call with SRVCC (LTE to UMTS)
@@ -246,38 +213,38 @@ public class PersistAtomsStorageTest extends TelephonyTest {
mCall4Proto.isEmergency = false;
mCall4Proto.isRoaming = true;
- mCarrier1LteUsageProto = new VoiceCallRatUsage();
+ mCarrier1LteUsageProto = new RawVoiceCallRatUsage();
mCarrier1LteUsageProto.carrierId = CARRIER1_ID;
mCarrier1LteUsageProto.rat = TelephonyManager.NETWORK_TYPE_LTE;
mCarrier1LteUsageProto.callCount = 1L;
mCarrier1LteUsageProto.totalDurationMillis = 8000L;
- mCarrier1UmtsUsageProto = new VoiceCallRatUsage();
+ mCarrier1UmtsUsageProto = new RawVoiceCallRatUsage();
mCarrier1UmtsUsageProto.carrierId = CARRIER1_ID;
mCarrier1UmtsUsageProto.rat = TelephonyManager.NETWORK_TYPE_UMTS;
mCarrier1UmtsUsageProto.callCount = 1L;
mCarrier1UmtsUsageProto.totalDurationMillis = 6000L;
- mCarrier2LteUsageProto = new VoiceCallRatUsage();
+ mCarrier2LteUsageProto = new RawVoiceCallRatUsage();
mCarrier2LteUsageProto.carrierId = CARRIER2_ID;
mCarrier2LteUsageProto.rat = TelephonyManager.NETWORK_TYPE_LTE;
mCarrier2LteUsageProto.callCount = 2L;
mCarrier2LteUsageProto.totalDurationMillis = 20000L;
- mCarrier3LteUsageProto = new VoiceCallRatUsage();
+ mCarrier3LteUsageProto = new RawVoiceCallRatUsage();
mCarrier3LteUsageProto.carrierId = CARRIER3_ID;
mCarrier3LteUsageProto.rat = TelephonyManager.NETWORK_TYPE_LTE;
mCarrier3LteUsageProto.callCount = 1L;
mCarrier3LteUsageProto.totalDurationMillis = 1000L;
- mCarrier3GsmUsageProto = new VoiceCallRatUsage();
+ mCarrier3GsmUsageProto = new RawVoiceCallRatUsage();
mCarrier3GsmUsageProto.carrierId = CARRIER3_ID;
mCarrier3GsmUsageProto.rat = TelephonyManager.NETWORK_TYPE_GSM;
mCarrier3GsmUsageProto.callCount = 1L;
mCarrier3GsmUsageProto.totalDurationMillis = 100000L;
mVoiceCallRatUsages =
- new VoiceCallRatUsage[] {
+ new RawVoiceCallRatUsage[] {
mCarrier1UmtsUsageProto,
mCarrier1LteUsageProto,
mCarrier2LteUsageProto,
@@ -286,152 +253,6 @@ public class PersistAtomsStorageTest extends TelephonyTest {
};
mVoiceCallSessions =
new VoiceCallSession[] {mCall1Proto, mCall2Proto, mCall3Proto, mCall4Proto};
-
- // OOS to LTE on slot 0
- mServiceSwitch1Proto = new CellularDataServiceSwitch();
- mServiceSwitch1Proto.ratFrom = TelephonyManager.NETWORK_TYPE_UNKNOWN;
- mServiceSwitch1Proto.ratTo = TelephonyManager.NETWORK_TYPE_LTE;
- mServiceSwitch1Proto.simSlotIndex = 0;
- mServiceSwitch1Proto.isMultiSim = true;
- mServiceSwitch1Proto.carrierId = CARRIER1_ID;
- mServiceSwitch1Proto.switchCount = 1;
-
- // LTE to UMTS on slot 1
- mServiceSwitch2Proto = new CellularDataServiceSwitch();
- mServiceSwitch2Proto.ratFrom = TelephonyManager.NETWORK_TYPE_LTE;
- mServiceSwitch2Proto.ratTo = TelephonyManager.NETWORK_TYPE_UMTS;
- mServiceSwitch2Proto.simSlotIndex = 0;
- mServiceSwitch2Proto.isMultiSim = true;
- mServiceSwitch2Proto.carrierId = CARRIER2_ID;
- mServiceSwitch2Proto.switchCount = 2;
-
- // OOS on slot 0
- mServiceState1Proto = new CellularServiceState();
- mServiceState1Proto.voiceRat = TelephonyManager.NETWORK_TYPE_UNKNOWN;
- mServiceState1Proto.dataRat = TelephonyManager.NETWORK_TYPE_UNKNOWN;
- mServiceState1Proto.voiceRoamingType = ServiceState.ROAMING_TYPE_NOT_ROAMING;
- mServiceState1Proto.dataRoamingType = ServiceState.ROAMING_TYPE_NOT_ROAMING;
- mServiceState1Proto.isEndc = false;
- mServiceState1Proto.simSlotIndex = 0;
- mServiceState1Proto.isMultiSim = true;
- mServiceState1Proto.carrierId = CARRIER1_ID;
- mServiceState1Proto.totalTimeMillis = 5000L;
-
- // LTE with ENDC on slot 0
- mServiceState2Proto = new CellularServiceState();
- mServiceState2Proto.voiceRat = TelephonyManager.NETWORK_TYPE_LTE;
- mServiceState2Proto.dataRat = TelephonyManager.NETWORK_TYPE_LTE;
- mServiceState2Proto.voiceRoamingType = ServiceState.ROAMING_TYPE_NOT_ROAMING;
- mServiceState2Proto.dataRoamingType = ServiceState.ROAMING_TYPE_NOT_ROAMING;
- mServiceState2Proto.isEndc = true;
- mServiceState2Proto.simSlotIndex = 0;
- mServiceState2Proto.isMultiSim = true;
- mServiceState2Proto.carrierId = CARRIER1_ID;
- mServiceState2Proto.totalTimeMillis = 15000L;
-
- // LTE with WFC and roaming on slot 1
- mServiceState3Proto = new CellularServiceState();
- mServiceState3Proto.voiceRat = TelephonyManager.NETWORK_TYPE_IWLAN;
- mServiceState3Proto.dataRat = TelephonyManager.NETWORK_TYPE_LTE;
- mServiceState3Proto.voiceRoamingType = ServiceState.ROAMING_TYPE_INTERNATIONAL;
- mServiceState3Proto.dataRoamingType = ServiceState.ROAMING_TYPE_INTERNATIONAL;
- mServiceState3Proto.isEndc = false;
- mServiceState3Proto.simSlotIndex = 1;
- mServiceState3Proto.isMultiSim = true;
- mServiceState3Proto.carrierId = CARRIER2_ID;
- mServiceState3Proto.totalTimeMillis = 10000L;
-
- // UMTS with roaming on slot 1
- mServiceState4Proto = new CellularServiceState();
- mServiceState4Proto.voiceRat = TelephonyManager.NETWORK_TYPE_UMTS;
- mServiceState4Proto.dataRat = TelephonyManager.NETWORK_TYPE_UMTS;
- mServiceState4Proto.voiceRoamingType = ServiceState.ROAMING_TYPE_INTERNATIONAL;
- mServiceState4Proto.dataRoamingType = ServiceState.ROAMING_TYPE_INTERNATIONAL;
- mServiceState4Proto.isEndc = false;
- mServiceState4Proto.simSlotIndex = 1;
- mServiceState4Proto.isMultiSim = true;
- mServiceState4Proto.carrierId = CARRIER2_ID;
- mServiceState4Proto.totalTimeMillis = 10000L;
-
- mServiceSwitches =
- new CellularDataServiceSwitch[] {mServiceSwitch1Proto, mServiceSwitch2Proto};
- mServiceStates =
- new CellularServiceState[] {
- mServiceState1Proto,
- mServiceState2Proto,
- mServiceState3Proto,
- mServiceState4Proto
- };
-
- // IMS over LTE on slot 0, registered for 5 seconds
- mImsRegistrationStatsLte0 = new ImsRegistrationStats();
- mImsRegistrationStatsLte0.carrierId = CARRIER1_ID;
- mImsRegistrationStatsLte0.simSlotIndex = 0;
- mImsRegistrationStatsLte0.rat = TelephonyManager.NETWORK_TYPE_LTE;
- mImsRegistrationStatsLte0.registeredMillis = 5000L;
- mImsRegistrationStatsLte0.voiceCapableMillis = 5000L;
- mImsRegistrationStatsLte0.voiceAvailableMillis = 5000L;
- mImsRegistrationStatsLte0.smsCapableMillis = 5000L;
- mImsRegistrationStatsLte0.smsAvailableMillis = 5000L;
- mImsRegistrationStatsLte0.videoCapableMillis = 5000L;
- mImsRegistrationStatsLte0.videoAvailableMillis = 5000L;
- mImsRegistrationStatsLte0.utCapableMillis = 5000L;
- mImsRegistrationStatsLte0.utAvailableMillis = 5000L;
-
- // IMS over WiFi on slot 0, registered for 10 seconds (voice only)
- mImsRegistrationStatsWifi0 = new ImsRegistrationStats();
- mImsRegistrationStatsWifi0.carrierId = CARRIER2_ID;
- mImsRegistrationStatsWifi0.simSlotIndex = 0;
- mImsRegistrationStatsWifi0.rat = TelephonyManager.NETWORK_TYPE_IWLAN;
- mImsRegistrationStatsWifi0.registeredMillis = 10000L;
- mImsRegistrationStatsWifi0.voiceCapableMillis = 10000L;
- mImsRegistrationStatsWifi0.voiceAvailableMillis = 10000L;
-
- // IMS over LTE on slot 1, registered for 20 seconds
- mImsRegistrationStatsLte1 = new ImsRegistrationStats();
- mImsRegistrationStatsLte1.carrierId = CARRIER1_ID;
- mImsRegistrationStatsLte1.simSlotIndex = 0;
- mImsRegistrationStatsLte1.rat = TelephonyManager.NETWORK_TYPE_LTE;
- mImsRegistrationStatsLte1.registeredMillis = 20000L;
- mImsRegistrationStatsLte1.voiceCapableMillis = 20000L;
- mImsRegistrationStatsLte1.voiceAvailableMillis = 20000L;
- mImsRegistrationStatsLte1.smsCapableMillis = 20000L;
- mImsRegistrationStatsLte1.smsAvailableMillis = 20000L;
- mImsRegistrationStatsLte1.videoCapableMillis = 20000L;
- mImsRegistrationStatsLte1.videoAvailableMillis = 20000L;
- mImsRegistrationStatsLte1.utCapableMillis = 20000L;
- mImsRegistrationStatsLte1.utAvailableMillis = 20000L;
-
- // IMS terminations on LTE
- mImsRegistrationTerminationLte = new ImsRegistrationTermination();
- mImsRegistrationTerminationLte.carrierId = CARRIER1_ID;
- mImsRegistrationTerminationLte.isMultiSim = true;
- mImsRegistrationTerminationLte.ratAtEnd = TelephonyManager.NETWORK_TYPE_LTE;
- mImsRegistrationTerminationLte.setupFailed = false;
- mImsRegistrationTerminationLte.reasonCode = ImsReasonInfo.CODE_REGISTRATION_ERROR;
- mImsRegistrationTerminationLte.extraCode = 999;
- mImsRegistrationTerminationLte.extraMessage = "Request Timeout";
- mImsRegistrationTerminationLte.count = 2;
-
- // IMS terminations on WiFi
- mImsRegistrationTerminationWifi = new ImsRegistrationTermination();
- mImsRegistrationTerminationWifi.carrierId = CARRIER2_ID;
- mImsRegistrationTerminationWifi.isMultiSim = true;
- mImsRegistrationTerminationWifi.ratAtEnd = TelephonyManager.NETWORK_TYPE_IWLAN;
- mImsRegistrationTerminationWifi.setupFailed = false;
- mImsRegistrationTerminationWifi.reasonCode = ImsReasonInfo.CODE_REGISTRATION_ERROR;
- mImsRegistrationTerminationWifi.extraCode = 0;
- mImsRegistrationTerminationWifi.extraMessage = "";
- mImsRegistrationTerminationWifi.count = 1;
-
- mImsRegistrationStats =
- new ImsRegistrationStats[] {
- mImsRegistrationStatsLte0, mImsRegistrationStatsWifi0, mImsRegistrationStatsLte1
- };
- mImsRegistrationTerminations =
- new ImsRegistrationTermination[] {
- mImsRegistrationTerminationLte, mImsRegistrationTerminationWifi
- };
}
private static class TestablePersistAtomsStorage extends PersistAtomsStorage {
@@ -439,8 +260,6 @@ public class PersistAtomsStorageTest extends TelephonyTest {
TestablePersistAtomsStorage(Context context) {
super(context);
- // Remove delay for saving to persistent storage during tests.
- mSaveImmediately = true;
}
@Override
@@ -459,8 +278,7 @@ public class PersistAtomsStorageTest extends TelephonyTest {
}
private PersistAtoms getAtomsProto() {
- // NOTE: unlike other methods in PersistAtomsStorage, this is not synchronized, but
- // should be fine since the test is single-threaded
+ // NOTE: not guarded by mLock as usual, should be fine since the test is single-threaded
return mAtoms;
}
}
@@ -511,8 +329,18 @@ public class PersistAtomsStorageTest extends TelephonyTest {
mPersistAtomsStorage.incTimeMillis(100L);
// no exception should be thrown, storage should be empty, pull time should be start time
- assertAllPullTimestampEquals(START_TIME_MILLIS);
- assertStorageIsEmptyForAllAtoms();
+ assertEquals(
+ START_TIME_MILLIS,
+ mPersistAtomsStorage.getAtomsProto().rawVoiceCallRatUsagePullTimestampMillis);
+ assertEquals(
+ START_TIME_MILLIS,
+ mPersistAtomsStorage.getAtomsProto().voiceCallSessionPullTimestampMillis);
+ RawVoiceCallRatUsage[] voiceCallRatUsage = mPersistAtomsStorage.getVoiceCallRatUsages(0L);
+ VoiceCallSession[] voiceCallSession = mPersistAtomsStorage.getVoiceCallSessions(0L);
+ assertNotNull(voiceCallRatUsage);
+ assertEquals(0, voiceCallRatUsage.length);
+ assertNotNull(voiceCallSession);
+ assertEquals(0, voiceCallSession.length);
}
@Test
@@ -525,8 +353,18 @@ public class PersistAtomsStorageTest extends TelephonyTest {
mPersistAtomsStorage.incTimeMillis(100L);
// no exception should be thrown, storage should be empty, pull time should be start time
- assertAllPullTimestampEquals(START_TIME_MILLIS);
- assertStorageIsEmptyForAllAtoms();
+ assertEquals(
+ START_TIME_MILLIS,
+ mPersistAtomsStorage.getAtomsProto().rawVoiceCallRatUsagePullTimestampMillis);
+ assertEquals(
+ START_TIME_MILLIS,
+ mPersistAtomsStorage.getAtomsProto().voiceCallSessionPullTimestampMillis);
+ RawVoiceCallRatUsage[] voiceCallRatUsage = mPersistAtomsStorage.getVoiceCallRatUsages(0L);
+ VoiceCallSession[] voiceCallSession = mPersistAtomsStorage.getVoiceCallSessions(0L);
+ assertNotNull(voiceCallRatUsage);
+ assertEquals(0, voiceCallRatUsage.length);
+ assertNotNull(voiceCallSession);
+ assertEquals(0, voiceCallSession.length);
}
@Test
@@ -538,8 +376,18 @@ public class PersistAtomsStorageTest extends TelephonyTest {
mPersistAtomsStorage.incTimeMillis(100L);
// no exception should be thrown, storage should be empty, pull time should be start time
- assertAllPullTimestampEquals(START_TIME_MILLIS);
- assertStorageIsEmptyForAllAtoms();
+ assertEquals(
+ START_TIME_MILLIS,
+ mPersistAtomsStorage.getAtomsProto().rawVoiceCallRatUsagePullTimestampMillis);
+ assertEquals(
+ START_TIME_MILLIS,
+ mPersistAtomsStorage.getAtomsProto().voiceCallSessionPullTimestampMillis);
+ RawVoiceCallRatUsage[] voiceCallRatUsage = mPersistAtomsStorage.getVoiceCallRatUsages(0L);
+ VoiceCallSession[] voiceCallSession = mPersistAtomsStorage.getVoiceCallSessions(0L);
+ assertNotNull(voiceCallRatUsage);
+ assertEquals(0, voiceCallRatUsage.length);
+ assertNotNull(voiceCallSession);
+ assertEquals(0, voiceCallSession.length);
}
@Test
@@ -553,44 +401,57 @@ public class PersistAtomsStorageTest extends TelephonyTest {
mPersistAtomsStorage.incTimeMillis(100L);
// no exception should be thrown, storage should be empty, pull time should be start time
- assertAllPullTimestampEquals(START_TIME_MILLIS);
- assertStorageIsEmptyForAllAtoms();
+ assertEquals(
+ START_TIME_MILLIS,
+ mPersistAtomsStorage.getAtomsProto().rawVoiceCallRatUsagePullTimestampMillis);
+ assertEquals(
+ START_TIME_MILLIS,
+ mPersistAtomsStorage.getAtomsProto().voiceCallSessionPullTimestampMillis);
+ RawVoiceCallRatUsage[] voiceCallRatUsage = mPersistAtomsStorage.getVoiceCallRatUsages(0L);
+ VoiceCallSession[] voiceCallSession = mPersistAtomsStorage.getVoiceCallSessions(0L);
+ assertNotNull(voiceCallRatUsage);
+ assertEquals(0, voiceCallRatUsage.length);
+ assertNotNull(voiceCallSession);
+ assertEquals(0, voiceCallSession.length);
}
@Test
@SmallTest
public void loadAtoms_pullTimeMissing() throws Exception {
- // create test file with lastPullTimeMillis = 0L, i.e. default/unknown
createTestFile(0L);
mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
mPersistAtomsStorage.incTimeMillis(100L);
// no exception should be thrown, storage should be match, pull time should be start time
- assertAllPullTimestampEquals(START_TIME_MILLIS);
- assertProtoArrayEquals(mVoiceCallRatUsages, mPersistAtomsStorage.getVoiceCallRatUsages(0L));
- assertProtoArrayEquals(mVoiceCallSessions, mPersistAtomsStorage.getVoiceCallSessions(0L));
- assertProtoArrayEqualsIgnoringOrder(
- mServiceStates, mPersistAtomsStorage.getCellularServiceStates(0L));
- assertProtoArrayEqualsIgnoringOrder(
- mServiceSwitches, mPersistAtomsStorage.getCellularDataServiceSwitches(0L));
+ assertEquals(
+ START_TIME_MILLIS,
+ mPersistAtomsStorage.getAtomsProto().rawVoiceCallRatUsagePullTimestampMillis);
+ assertEquals(
+ START_TIME_MILLIS,
+ mPersistAtomsStorage.getAtomsProto().voiceCallSessionPullTimestampMillis);
+ RawVoiceCallRatUsage[] voiceCallRatUsage = mPersistAtomsStorage.getVoiceCallRatUsages(0L);
+ VoiceCallSession[] voiceCallSession = mPersistAtomsStorage.getVoiceCallSessions(0L);
+ assertProtoArrayEquals(mVoiceCallRatUsages, voiceCallRatUsage);
+ assertProtoArrayEquals(mVoiceCallSessions, voiceCallSession);
}
@Test
@SmallTest
public void loadAtoms_validContents() throws Exception {
- createTestFile(/* lastPullTimeMillis= */ 100L);
+ createTestFile(100L);
mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
// no exception should be thrown, storage and pull time should match
- assertAllPullTimestampEquals(100L);
- assertProtoArrayEquals(mVoiceCallRatUsages, mPersistAtomsStorage.getVoiceCallRatUsages(0L));
- assertProtoArrayEquals(mVoiceCallSessions, mPersistAtomsStorage.getVoiceCallSessions(0L));
- assertProtoArrayEqualsIgnoringOrder(
- mServiceStates, mPersistAtomsStorage.getCellularServiceStates(0L));
- assertProtoArrayEqualsIgnoringOrder(
- mServiceSwitches, mPersistAtomsStorage.getCellularDataServiceSwitches(0L));
+ assertEquals(
+ 100L, mPersistAtomsStorage.getAtomsProto().rawVoiceCallRatUsagePullTimestampMillis);
+ assertEquals(
+ 100L, mPersistAtomsStorage.getAtomsProto().voiceCallSessionPullTimestampMillis);
+ RawVoiceCallRatUsage[] voiceCallRatUsage = mPersistAtomsStorage.getVoiceCallRatUsages(0L);
+ VoiceCallSession[] voiceCallSession = mPersistAtomsStorage.getVoiceCallSessions(0L);
+ assertProtoArrayEquals(mVoiceCallRatUsages, voiceCallRatUsage);
+ assertProtoArrayEquals(mVoiceCallSessions, voiceCallSession);
}
@Test
@@ -603,31 +464,46 @@ public class PersistAtomsStorageTest extends TelephonyTest {
mPersistAtomsStorage.incTimeMillis(100L);
// call should be added successfully, there should be no RAT usage, changes should be saved
- verifyCurrentStateSavedToFileOnce();
- assertProtoArrayIsEmpty(mPersistAtomsStorage.getVoiceCallRatUsages(0L));
+ RawVoiceCallRatUsage[] voiceCallRatUsage = mPersistAtomsStorage.getVoiceCallRatUsages(0L);
VoiceCallSession[] voiceCallSession = mPersistAtomsStorage.getVoiceCallSessions(0L);
+ assertNotNull(voiceCallRatUsage);
+ assertEquals(0, voiceCallRatUsage.length);
assertProtoArrayEquals(new VoiceCallSession[] {mCall1Proto}, voiceCallSession);
+ InOrder inOrder = inOrder(mTestFileOutputStream);
+ inOrder.verify(mTestFileOutputStream, times(1))
+ .write(eq(PersistAtoms.toByteArray(mPersistAtomsStorage.getAtomsProto())));
+ inOrder.verify(mTestFileOutputStream, times(1)).close();
+ inOrder.verifyNoMoreInteractions();
}
@Test
@SmallTest
public void addVoiceCallSession_withExistingCalls() throws Exception {
- createTestFile(START_TIME_MILLIS);
+ createTestFile(100L);
mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
mPersistAtomsStorage.addVoiceCallSession(mCall1Proto);
mPersistAtomsStorage.incTimeMillis(100L);
// call should be added successfully, RAT usages should not change, changes should be saved
- assertProtoArrayEquals(mVoiceCallRatUsages, mPersistAtomsStorage.getVoiceCallRatUsages(0L));
+ RawVoiceCallRatUsage[] voiceCallRatUsage = mPersistAtomsStorage.getVoiceCallRatUsages(0L);
+ VoiceCallSession[] voiceCallSession = mPersistAtomsStorage.getVoiceCallSessions(0L);
+ assertNotNull(voiceCallRatUsage);
+ assertEquals(mVoiceCallRatUsages.length, voiceCallRatUsage.length);
+ assertNotNull(voiceCallSession);
+ // call lists are randomized, but sorted version should be identical
VoiceCallSession[] expectedVoiceCallSessions =
new VoiceCallSession[] {
mCall1Proto, mCall1Proto, mCall2Proto, mCall3Proto, mCall4Proto
};
- // call list is randomized at this point
- verifyCurrentStateSavedToFileOnce();
- assertProtoArrayEqualsIgnoringOrder(
- expectedVoiceCallSessions, mPersistAtomsStorage.getVoiceCallSessions(0L));
+ Arrays.sort(expectedVoiceCallSessions, sProtoComparator);
+ Arrays.sort(voiceCallSession, sProtoComparator);
+ assertProtoArrayEquals(expectedVoiceCallSessions, voiceCallSession);
+ InOrder inOrder = inOrder(mTestFileOutputStream);
+ inOrder.verify(mTestFileOutputStream, times(1))
+ .write(eq(PersistAtoms.toByteArray(mPersistAtomsStorage.getAtomsProto())));
+ inOrder.verify(mTestFileOutputStream, times(1)).close();
+ inOrder.verifyNoMoreInteractions();
}
@Test
@@ -641,10 +517,9 @@ public class PersistAtomsStorageTest extends TelephonyTest {
mPersistAtomsStorage.incTimeMillis(100L);
// one previous call should be evicted, the new call should be added
- verifyCurrentStateSavedToFileOnce();
VoiceCallSession[] calls = mPersistAtomsStorage.getVoiceCallSessions(0L);
- assertHasCall(calls, mCall1Proto, /* expectedCount= */ 49);
- assertHasCall(calls, mCall2Proto, /* expectedCount= */ 1);
+ assertHasCall(calls, mCall1Proto, 49);
+ assertHasCall(calls, mCall2Proto, 1);
}
@Test
@@ -658,16 +533,25 @@ public class PersistAtomsStorageTest extends TelephonyTest {
mPersistAtomsStorage.incTimeMillis(100L);
// RAT should be added successfully, calls should not change, changes should be saved
- verifyCurrentStateSavedToFileOnce();
- assertProtoArrayEqualsIgnoringOrder(
- mVoiceCallRatUsages, mPersistAtomsStorage.getVoiceCallRatUsages(0L));
- assertProtoArrayIsEmpty(mPersistAtomsStorage.getVoiceCallSessions(0L));
+ RawVoiceCallRatUsage[] voiceCallRatUsage = mPersistAtomsStorage.getVoiceCallRatUsages(0L);
+ VoiceCallSession[] voiceCallSession = mPersistAtomsStorage.getVoiceCallSessions(0L);
+ RawVoiceCallRatUsage[] expectedVoiceCallRatUsage = mVoiceCallRatUsages.clone();
+ Arrays.sort(expectedVoiceCallRatUsage, sProtoComparator);
+ Arrays.sort(voiceCallRatUsage, sProtoComparator);
+ assertProtoArrayEquals(expectedVoiceCallRatUsage, voiceCallRatUsage);
+ assertNotNull(voiceCallSession);
+ assertEquals(0, voiceCallSession.length);
+ InOrder inOrder = inOrder(mTestFileOutputStream);
+ inOrder.verify(mTestFileOutputStream, times(1))
+ .write(eq(PersistAtoms.toByteArray(mPersistAtomsStorage.getAtomsProto())));
+ inOrder.verify(mTestFileOutputStream, times(1)).close();
+ inOrder.verifyNoMoreInteractions();
}
@Test
@SmallTest
public void addVoiceCallRatUsage_withExistingUsages() throws Exception {
- createTestFile(START_TIME_MILLIS);
+ createTestFile(100L);
VoiceCallRatTracker ratTracker = VoiceCallRatTracker.fromProto(mVoiceCallRatUsages);
mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
@@ -675,30 +559,42 @@ public class PersistAtomsStorageTest extends TelephonyTest {
mPersistAtomsStorage.incTimeMillis(100L);
// RAT should be added successfully, calls should not change, changes should be saved
+ RawVoiceCallRatUsage[] voiceCallRatUsage = mPersistAtomsStorage.getVoiceCallRatUsages(0L);
+ VoiceCallSession[] voiceCallSession = mPersistAtomsStorage.getVoiceCallSessions(0L);
// call count and duration should become doubled since mVoiceCallRatUsages applied through
// both file and addVoiceCallRatUsage()
- verifyCurrentStateSavedToFileOnce();
- VoiceCallRatUsage[] expectedVoiceCallRatUsage =
+ RawVoiceCallRatUsage[] expectedVoiceCallRatUsage =
multiplyVoiceCallRatUsage(mVoiceCallRatUsages, 2);
- assertProtoArrayEqualsIgnoringOrder(
- expectedVoiceCallRatUsage, mPersistAtomsStorage.getVoiceCallRatUsages(0L));
- assertProtoArrayEquals(mVoiceCallSessions, mPersistAtomsStorage.getVoiceCallSessions(0L));
+ Arrays.sort(expectedVoiceCallRatUsage, sProtoComparator);
+ Arrays.sort(voiceCallRatUsage, sProtoComparator);
+ assertProtoArrayEquals(expectedVoiceCallRatUsage, voiceCallRatUsage);
+ assertNotNull(voiceCallSession);
+ assertEquals(mVoiceCallSessions.length, voiceCallSession.length);
+ InOrder inOrder = inOrder(mTestFileOutputStream);
+ inOrder.verify(mTestFileOutputStream, times(1))
+ .write(eq(PersistAtoms.toByteArray(mPersistAtomsStorage.getAtomsProto())));
+ inOrder.verify(mTestFileOutputStream, times(1)).close();
+ inOrder.verifyNoMoreInteractions();
}
@Test
@SmallTest
public void addVoiceCallRatUsage_empty() throws Exception {
createEmptyTestFile();
- VoiceCallRatTracker ratTracker = VoiceCallRatTracker.fromProto(new VoiceCallRatUsage[0]);
+ VoiceCallRatTracker ratTracker = VoiceCallRatTracker.fromProto(new RawVoiceCallRatUsage[0]);
mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
mPersistAtomsStorage.addVoiceCallRatUsage(ratTracker);
mPersistAtomsStorage.incTimeMillis(100L);
// RAT should be added successfully, calls should not change
- // in this case saving is unnecessarily
- assertProtoArrayIsEmpty(mPersistAtomsStorage.getVoiceCallRatUsages(0L));
- assertProtoArrayIsEmpty(mPersistAtomsStorage.getVoiceCallSessions(0L));
+ // in this case it does not necessarily need to save
+ RawVoiceCallRatUsage[] voiceCallRatUsage = mPersistAtomsStorage.getVoiceCallRatUsages(0L);
+ VoiceCallSession[] voiceCallSession = mPersistAtomsStorage.getVoiceCallSessions(0L);
+ assertNotNull(voiceCallRatUsage);
+ assertEquals(0, voiceCallRatUsage.length);
+ assertNotNull(voiceCallSession);
+ assertEquals(0, voiceCallSession.length);
}
@Test
@@ -708,7 +604,7 @@ public class PersistAtomsStorageTest extends TelephonyTest {
mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
mPersistAtomsStorage.incTimeMillis(50L); // pull interval less than minimum
- VoiceCallRatUsage[] voiceCallRatUsage = mPersistAtomsStorage.getVoiceCallRatUsages(100L);
+ RawVoiceCallRatUsage[] voiceCallRatUsage = mPersistAtomsStorage.getVoiceCallRatUsages(100L);
// should be denied
assertNull(voiceCallRatUsage);
@@ -721,9 +617,9 @@ public class PersistAtomsStorageTest extends TelephonyTest {
mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
mPersistAtomsStorage.incTimeMillis(100L);
- VoiceCallRatUsage[] voiceCallRatUsage1 = mPersistAtomsStorage.getVoiceCallRatUsages(50L);
+ RawVoiceCallRatUsage[] voiceCallRatUsage1 = mPersistAtomsStorage.getVoiceCallRatUsages(50L);
mPersistAtomsStorage.incTimeMillis(100L);
- VoiceCallRatUsage[] voiceCallRatUsage2 = mPersistAtomsStorage.getVoiceCallRatUsages(50L);
+ RawVoiceCallRatUsage[] voiceCallRatUsage2 = mPersistAtomsStorage.getVoiceCallRatUsages(50L);
long voiceCallSessionPullTimestampMillis =
mPersistAtomsStorage.getAtomsProto().voiceCallSessionPullTimestampMillis;
VoiceCallSession[] voiceCallSession = mPersistAtomsStorage.getVoiceCallSessions(50L);
@@ -731,19 +627,19 @@ public class PersistAtomsStorageTest extends TelephonyTest {
// first set of results should equal to file contents, second should be empty, corresponding
// pull timestamp should be updated and saved, other fields should be unaffected
assertProtoArrayEquals(mVoiceCallRatUsages, voiceCallRatUsage1);
- assertProtoArrayIsEmpty(voiceCallRatUsage2);
+ assertProtoArrayEquals(new RawVoiceCallRatUsage[0], voiceCallRatUsage2);
assertEquals(
START_TIME_MILLIS + 200L,
- mPersistAtomsStorage.getAtomsProto().voiceCallRatUsagePullTimestampMillis);
+ mPersistAtomsStorage.getAtomsProto().rawVoiceCallRatUsagePullTimestampMillis);
assertProtoArrayEquals(mVoiceCallSessions, voiceCallSession);
assertEquals(START_TIME_MILLIS, voiceCallSessionPullTimestampMillis);
InOrder inOrder = inOrder(mTestFileOutputStream);
assertEquals(
START_TIME_MILLIS + 100L,
- getAtomsWritten(inOrder).voiceCallRatUsagePullTimestampMillis);
+ getAtomsWritten(inOrder).rawVoiceCallRatUsagePullTimestampMillis);
assertEquals(
START_TIME_MILLIS + 200L,
- getAtomsWritten(inOrder).voiceCallRatUsagePullTimestampMillis);
+ getAtomsWritten(inOrder).rawVoiceCallRatUsagePullTimestampMillis);
assertEquals(
START_TIME_MILLIS + 200L,
getAtomsWritten(inOrder).voiceCallSessionPullTimestampMillis);
@@ -774,13 +670,13 @@ public class PersistAtomsStorageTest extends TelephonyTest {
mPersistAtomsStorage.incTimeMillis(100L);
VoiceCallSession[] voiceCallSession2 = mPersistAtomsStorage.getVoiceCallSessions(50L);
long voiceCallRatUsagePullTimestampMillis =
- mPersistAtomsStorage.getAtomsProto().voiceCallRatUsagePullTimestampMillis;
- VoiceCallRatUsage[] voiceCallRatUsage = mPersistAtomsStorage.getVoiceCallRatUsages(50L);
+ mPersistAtomsStorage.getAtomsProto().rawVoiceCallRatUsagePullTimestampMillis;
+ RawVoiceCallRatUsage[] voiceCallRatUsage = mPersistAtomsStorage.getVoiceCallRatUsages(50L);
// first set of results should equal to file contents, second should be empty, corresponding
// pull timestamp should be updated and saved, other fields should be unaffected
assertProtoArrayEquals(mVoiceCallSessions, voiceCallSession1);
- assertProtoArrayIsEmpty(voiceCallSession2);
+ assertProtoArrayEquals(new VoiceCallSession[0], voiceCallSession2);
assertEquals(
START_TIME_MILLIS + 200L,
mPersistAtomsStorage.getAtomsProto().voiceCallSessionPullTimestampMillis);
@@ -795,486 +691,10 @@ public class PersistAtomsStorageTest extends TelephonyTest {
getAtomsWritten(inOrder).voiceCallSessionPullTimestampMillis);
assertEquals(
START_TIME_MILLIS + 200L,
- getAtomsWritten(inOrder).voiceCallRatUsagePullTimestampMillis);
- inOrder.verifyNoMoreInteractions();
- }
-
- @Test
- @SmallTest
- public void addCellularServiceStateAndCellularDataServiceSwitch_emptyProto() throws Exception {
- createEmptyTestFile();
-
- mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
- mPersistAtomsStorage.addCellularServiceStateAndCellularDataServiceSwitch(
- mServiceState1Proto, mServiceSwitch1Proto);
- mPersistAtomsStorage.incTimeMillis(100L);
-
- // service state and service switch should be added successfully
- verifyCurrentStateSavedToFileOnce();
- CellularServiceState[] serviceStates = mPersistAtomsStorage.getCellularServiceStates(0L);
- CellularDataServiceSwitch[] serviceSwitches =
- mPersistAtomsStorage.getCellularDataServiceSwitches(0L);
- assertProtoArrayEquals(new CellularServiceState[] {mServiceState1Proto}, serviceStates);
- assertProtoArrayEquals(
- new CellularDataServiceSwitch[] {mServiceSwitch1Proto}, serviceSwitches);
- }
-
- @Test
- @SmallTest
- public void addCellularServiceStateAndCellularDataServiceSwitch_withExistingEntries()
- throws Exception {
- createEmptyTestFile();
- mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
- mPersistAtomsStorage.addCellularServiceStateAndCellularDataServiceSwitch(
- mServiceState1Proto, mServiceSwitch1Proto);
-
- mPersistAtomsStorage.addCellularServiceStateAndCellularDataServiceSwitch(
- mServiceState2Proto, mServiceSwitch2Proto);
- mPersistAtomsStorage.incTimeMillis(100L);
-
- // service state and service switch should be added successfully
- verifyCurrentStateSavedToFileOnce();
- CellularServiceState[] serviceStates = mPersistAtomsStorage.getCellularServiceStates(0L);
- CellularDataServiceSwitch[] serviceSwitches =
- mPersistAtomsStorage.getCellularDataServiceSwitches(0L);
- assertProtoArrayEqualsIgnoringOrder(
- new CellularServiceState[] {mServiceState1Proto, mServiceState2Proto},
- serviceStates);
- assertProtoArrayEqualsIgnoringOrder(
- new CellularDataServiceSwitch[] {mServiceSwitch1Proto, mServiceSwitch2Proto},
- serviceSwitches);
- }
-
- @Test
- @SmallTest
- public void addCellularServiceStateAndCellularDataServiceSwitch_updateExistingEntries()
- throws Exception {
- createTestFile(START_TIME_MILLIS);
- CellularServiceState newServiceState1Proto = copyOf(mServiceState1Proto);
- CellularDataServiceSwitch newServiceSwitch1Proto = copyOf(mServiceSwitch1Proto);
- mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
-
- mPersistAtomsStorage.addCellularServiceStateAndCellularDataServiceSwitch(
- copyOf(mServiceState1Proto), copyOf(mServiceSwitch1Proto));
- mPersistAtomsStorage.incTimeMillis(100L);
-
- // mServiceState1Proto's duration and mServiceSwitch1Proto's switch should be doubled
- verifyCurrentStateSavedToFileOnce();
- CellularServiceState[] serviceStates = mPersistAtomsStorage.getCellularServiceStates(0L);
- newServiceState1Proto.totalTimeMillis *= 2;
- assertProtoArrayEqualsIgnoringOrder(
- new CellularServiceState[] {
- newServiceState1Proto,
- mServiceState2Proto,
- mServiceState3Proto,
- mServiceState4Proto
- },
- serviceStates);
- CellularDataServiceSwitch[] serviceSwitches =
- mPersistAtomsStorage.getCellularDataServiceSwitches(0L);
- newServiceSwitch1Proto.switchCount *= 2;
- assertProtoArrayEqualsIgnoringOrder(
- new CellularDataServiceSwitch[] {newServiceSwitch1Proto, mServiceSwitch2Proto},
- serviceSwitches);
- }
-
- @Test
- @SmallTest
- public void addCellularServiceStateAndCellularDataServiceSwitch_tooManyServiceStates()
- throws Exception {
- createEmptyTestFile();
- mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
- Queue<CellularServiceState> expectedServiceStates = new LinkedList<>();
- Queue<CellularDataServiceSwitch> expectedServiceSwitches = new LinkedList<>();
-
- // Add 51 service states, with the first being least recent
- for (int i = 0; i < 51; i++) {
- CellularServiceState state = new CellularServiceState();
- state.voiceRat = i / 10;
- state.dataRat = i % 10;
- expectedServiceStates.add(state);
- CellularDataServiceSwitch serviceSwitch = new CellularDataServiceSwitch();
- serviceSwitch.ratFrom = i / 10;
- serviceSwitch.ratTo = i % 10;
- expectedServiceSwitches.add(serviceSwitch);
- mPersistAtomsStorage.addCellularServiceStateAndCellularDataServiceSwitch(
- copyOf(state), copyOf(serviceSwitch));
- mPersistAtomsStorage.incTimeMillis(100L);
- }
-
- // The least recent (the first) service state should be evicted
- verifyCurrentStateSavedToFileOnce();
- CellularServiceState[] serviceStates = mPersistAtomsStorage.getCellularServiceStates(0L);
- expectedServiceStates.remove();
- assertProtoArrayEqualsIgnoringOrder(
- expectedServiceStates.toArray(new CellularServiceState[0]), serviceStates);
- CellularDataServiceSwitch[] serviceSwitches =
- mPersistAtomsStorage.getCellularDataServiceSwitches(0L);
- expectedServiceSwitches.remove();
- assertProtoArrayEqualsIgnoringOrder(
- expectedServiceSwitches.toArray(new CellularDataServiceSwitch[0]), serviceSwitches);
- }
-
- @Test
- @SmallTest
- public void getCellularDataServiceSwitches_tooFrequent() throws Exception {
- createTestFile(START_TIME_MILLIS);
-
- mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
- mPersistAtomsStorage.incTimeMillis(50L); // pull interval less than minimum
- CellularDataServiceSwitch[] serviceSwitches =
- mPersistAtomsStorage.getCellularDataServiceSwitches(100L);
-
- // should be denied
- assertNull(serviceSwitches);
- }
-
- @Test
- @SmallTest
- public void getCellularDataServiceSwitches_withSavedAtoms() throws Exception {
- createTestFile(START_TIME_MILLIS);
-
- mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
- mPersistAtomsStorage.incTimeMillis(100L);
- CellularDataServiceSwitch[] serviceSwitches1 =
- mPersistAtomsStorage.getCellularDataServiceSwitches(50L);
- mPersistAtomsStorage.incTimeMillis(100L);
- CellularDataServiceSwitch[] serviceSwitches2 =
- mPersistAtomsStorage.getCellularDataServiceSwitches(50L);
-
- // first set of results should equal to file contents, second should be empty, corresponding
- // pull timestamp should be updated and saved
- assertProtoArrayEqualsIgnoringOrder(
- new CellularDataServiceSwitch[] {mServiceSwitch1Proto, mServiceSwitch2Proto},
- serviceSwitches1);
- assertProtoArrayEquals(new CellularDataServiceSwitch[0], serviceSwitches2);
- assertEquals(
- START_TIME_MILLIS + 200L,
- mPersistAtomsStorage.getAtomsProto().cellularDataServiceSwitchPullTimestampMillis);
- InOrder inOrder = inOrder(mTestFileOutputStream);
- assertEquals(
- START_TIME_MILLIS + 100L,
- getAtomsWritten(inOrder).cellularDataServiceSwitchPullTimestampMillis);
- assertEquals(
- START_TIME_MILLIS + 200L,
- getAtomsWritten(inOrder).cellularDataServiceSwitchPullTimestampMillis);
- inOrder.verifyNoMoreInteractions();
- }
-
- @Test
- @SmallTest
- public void getCellularServiceStates_tooFrequent() throws Exception {
- createTestFile(START_TIME_MILLIS);
-
- mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
- mPersistAtomsStorage.incTimeMillis(50L); // pull interval less than minimum
- CellularServiceState[] serviceStates = mPersistAtomsStorage.getCellularServiceStates(100L);
-
- // should be denied
- assertNull(serviceStates);
- }
-
- @Test
- @SmallTest
- public void getCellularServiceStates_withSavedAtoms() throws Exception {
- createTestFile(START_TIME_MILLIS);
-
- mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
- mPersistAtomsStorage.incTimeMillis(100L);
- CellularServiceState[] serviceStates1 = mPersistAtomsStorage.getCellularServiceStates(50L);
- mPersistAtomsStorage.incTimeMillis(100L);
- CellularServiceState[] serviceStates2 = mPersistAtomsStorage.getCellularServiceStates(50L);
-
- // first set of results should equal to file contents, second should be empty, corresponding
- // pull timestamp should be updated and saved
- assertProtoArrayEqualsIgnoringOrder(
- new CellularServiceState[] {
- mServiceState1Proto,
- mServiceState2Proto,
- mServiceState3Proto,
- mServiceState4Proto
- },
- serviceStates1);
- assertProtoArrayEquals(new CellularServiceState[0], serviceStates2);
- assertEquals(
- START_TIME_MILLIS + 200L,
- mPersistAtomsStorage.getAtomsProto().cellularServiceStatePullTimestampMillis);
- InOrder inOrder = inOrder(mTestFileOutputStream);
- assertEquals(
- START_TIME_MILLIS + 100L,
- getAtomsWritten(inOrder).cellularServiceStatePullTimestampMillis);
- assertEquals(
- START_TIME_MILLIS + 200L,
- getAtomsWritten(inOrder).cellularServiceStatePullTimestampMillis);
- inOrder.verifyNoMoreInteractions();
- }
-
- @Test
- @SmallTest
- public void addImsRegistrationStats_emptyProto() throws Exception {
- createEmptyTestFile();
-
- mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
- mPersistAtomsStorage.addImsRegistrationStats(mImsRegistrationStatsLte0);
- mPersistAtomsStorage.incTimeMillis(100L);
-
- // service state and service switch should be added successfully
- verifyCurrentStateSavedToFileOnce();
- ImsRegistrationStats[] regStats = mPersistAtomsStorage.getImsRegistrationStats(0L);
- assertProtoArrayEquals(new ImsRegistrationStats[] {mImsRegistrationStatsLte0}, regStats);
- }
-
- @Test
- @SmallTest
- public void addImsRegistrationStats_withExistingEntries() throws Exception {
- createEmptyTestFile();
- mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
- mPersistAtomsStorage.addImsRegistrationStats(mImsRegistrationStatsLte0);
-
- mPersistAtomsStorage.addImsRegistrationStats(mImsRegistrationStatsWifi0);
- mPersistAtomsStorage.incTimeMillis(100L);
-
- // service state and service switch should be added successfully
- verifyCurrentStateSavedToFileOnce();
- ImsRegistrationStats[] regStats = mPersistAtomsStorage.getImsRegistrationStats(0L);
- assertProtoArrayEqualsIgnoringOrder(
- new ImsRegistrationStats[] {mImsRegistrationStatsLte0, mImsRegistrationStatsWifi0},
- regStats);
- }
-
- @Test
- @SmallTest
- public void addImsRegistrationStats_updateExistingEntries() throws Exception {
- createTestFile(START_TIME_MILLIS);
- ImsRegistrationStats newImsRegistrationStatsLte0 = copyOf(mImsRegistrationStatsLte0);
- mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
-
- mPersistAtomsStorage.addImsRegistrationStats(copyOf(mImsRegistrationStatsLte0));
- mPersistAtomsStorage.incTimeMillis(100L);
-
- // mImsRegistrationStatsLte0's durations should be doubled
- verifyCurrentStateSavedToFileOnce();
- ImsRegistrationStats[] serviceStates = mPersistAtomsStorage.getImsRegistrationStats(0L);
- newImsRegistrationStatsLte0.registeredMillis *= 2;
- newImsRegistrationStatsLte0.voiceCapableMillis *= 2;
- newImsRegistrationStatsLte0.voiceAvailableMillis *= 2;
- newImsRegistrationStatsLte0.smsCapableMillis *= 2;
- newImsRegistrationStatsLte0.smsAvailableMillis *= 2;
- newImsRegistrationStatsLte0.videoCapableMillis *= 2;
- newImsRegistrationStatsLte0.videoAvailableMillis *= 2;
- newImsRegistrationStatsLte0.utCapableMillis *= 2;
- newImsRegistrationStatsLte0.utAvailableMillis *= 2;
- assertProtoArrayEqualsIgnoringOrder(
- new ImsRegistrationStats[] {
- newImsRegistrationStatsLte0,
- mImsRegistrationStatsWifi0,
- mImsRegistrationStatsLte1
- },
- serviceStates);
- }
-
- @Test
- @SmallTest
- public void addImsRegistrationStats_tooManyRegistrationStats() throws Exception {
- createEmptyTestFile();
- mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
- Queue<ImsRegistrationStats> expectedRegistrationStats = new LinkedList<>();
-
- // Add 11 registration stats
- for (int i = 0; i < 11; i++) {
- ImsRegistrationStats stats = copyOf(mImsRegistrationStatsLte0);
- stats.rat = i;
- expectedRegistrationStats.add(stats);
- mPersistAtomsStorage.addImsRegistrationStats(stats);
- mPersistAtomsStorage.incTimeMillis(100L);
- }
-
- // The least recent (the first) registration stats should be evicted
- verifyCurrentStateSavedToFileOnce();
- ImsRegistrationStats[] stats = mPersistAtomsStorage.getImsRegistrationStats(0L);
- expectedRegistrationStats.remove();
- assertProtoArrayEqualsIgnoringOrder(
- expectedRegistrationStats.toArray(new ImsRegistrationStats[0]), stats);
- }
-
- @Test
- @SmallTest
- public void addImsRegistrationTermination_emptyProto() throws Exception {
- createEmptyTestFile();
-
- mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
- mPersistAtomsStorage.addImsRegistrationTermination(mImsRegistrationTerminationLte);
- mPersistAtomsStorage.incTimeMillis(100L);
-
- // service state and service switch should be added successfully
- verifyCurrentStateSavedToFileOnce();
- ImsRegistrationTermination[] terminations =
- mPersistAtomsStorage.getImsRegistrationTerminations(0L);
- assertProtoArrayEquals(
- new ImsRegistrationTermination[] {mImsRegistrationTerminationLte}, terminations);
- }
-
- @Test
- @SmallTest
- public void addImsRegistrationTermination_withExistingEntries() throws Exception {
- createEmptyTestFile();
- mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
- mPersistAtomsStorage.addImsRegistrationTermination(mImsRegistrationTerminationLte);
-
- mPersistAtomsStorage.addImsRegistrationTermination(mImsRegistrationTerminationWifi);
- mPersistAtomsStorage.incTimeMillis(100L);
-
- // service state and service switch should be added successfully
- verifyCurrentStateSavedToFileOnce();
- ImsRegistrationTermination[] terminations =
- mPersistAtomsStorage.getImsRegistrationTerminations(0L);
- assertProtoArrayEqualsIgnoringOrder(
- new ImsRegistrationTermination[] {
- mImsRegistrationTerminationLte, mImsRegistrationTerminationWifi
- },
- terminations);
- }
-
- @Test
- @SmallTest
- public void addImsRegistrationTermination_updateExistingEntries() throws Exception {
- createTestFile(START_TIME_MILLIS);
- ImsRegistrationTermination newTermination = copyOf(mImsRegistrationTerminationWifi);
- mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
-
- mPersistAtomsStorage.addImsRegistrationTermination(copyOf(mImsRegistrationTerminationWifi));
- mPersistAtomsStorage.incTimeMillis(100L);
-
- // mImsRegistrationTerminationWifi's count should be doubled
- verifyCurrentStateSavedToFileOnce();
- ImsRegistrationTermination[] terminations =
- mPersistAtomsStorage.getImsRegistrationTerminations(0L);
- newTermination.count *= 2;
- assertProtoArrayEqualsIgnoringOrder(
- new ImsRegistrationTermination[] {mImsRegistrationTerminationLte, newTermination},
- terminations);
- }
-
- @Test
- @SmallTest
- public void addImsRegistrationTermination_tooManyTerminations() throws Exception {
- createEmptyTestFile();
- mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
- Queue<ImsRegistrationTermination> expectedTerminations = new LinkedList<>();
-
- // Add 11 registration terminations
- for (int i = 0; i < 11; i++) {
- ImsRegistrationTermination termination = copyOf(mImsRegistrationTerminationLte);
- termination.reasonCode = i;
- expectedTerminations.add(termination);
- mPersistAtomsStorage.addImsRegistrationTermination(termination);
- mPersistAtomsStorage.incTimeMillis(100L);
- }
-
- // The least recent (the first) registration termination should be evicted
- verifyCurrentStateSavedToFileOnce();
- ImsRegistrationTermination[] terminations =
- mPersistAtomsStorage.getImsRegistrationTerminations(0L);
- expectedTerminations.remove();
- assertProtoArrayEqualsIgnoringOrder(
- expectedTerminations.toArray(new ImsRegistrationTermination[0]), terminations);
- }
-
- @Test
- @SmallTest
- public void getImsRegistrationStats_tooFrequent() throws Exception {
- createTestFile(START_TIME_MILLIS);
-
- mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
- mPersistAtomsStorage.incTimeMillis(50L); // pull interval less than minimum
- ImsRegistrationStats[] stats = mPersistAtomsStorage.getImsRegistrationStats(100L);
-
- // should be denied
- assertNull(stats);
- }
-
- @Test
- @SmallTest
- public void getImsRegistrationStats_withSavedAtoms() throws Exception {
- createTestFile(START_TIME_MILLIS);
-
- mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
- mPersistAtomsStorage.incTimeMillis(100L);
- ImsRegistrationStats[] stats1 = mPersistAtomsStorage.getImsRegistrationStats(50L);
- mPersistAtomsStorage.incTimeMillis(100L);
- ImsRegistrationStats[] stats2 = mPersistAtomsStorage.getImsRegistrationStats(50L);
-
- // first set of results should equal to file contents, second should be empty, corresponding
- // pull timestamp should be updated and saved
- assertProtoArrayEqualsIgnoringOrder(
- new ImsRegistrationStats[] {
- mImsRegistrationStatsLte0, mImsRegistrationStatsWifi0, mImsRegistrationStatsLte1
- },
- stats1);
- assertProtoArrayEquals(new ImsRegistrationStats[0], stats2);
- assertEquals(
- START_TIME_MILLIS + 200L,
- mPersistAtomsStorage.getAtomsProto().imsRegistrationStatsPullTimestampMillis);
- InOrder inOrder = inOrder(mTestFileOutputStream);
- assertEquals(
- START_TIME_MILLIS + 100L,
- getAtomsWritten(inOrder).imsRegistrationStatsPullTimestampMillis);
- assertEquals(
- START_TIME_MILLIS + 200L,
- getAtomsWritten(inOrder).imsRegistrationStatsPullTimestampMillis);
+ getAtomsWritten(inOrder).rawVoiceCallRatUsagePullTimestampMillis);
inOrder.verifyNoMoreInteractions();
}
- @Test
- @SmallTest
- public void getImsRegistrationTerminations_tooFrequent() throws Exception {
- createTestFile(START_TIME_MILLIS);
-
- mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
- mPersistAtomsStorage.incTimeMillis(50L); // pull interval less than minimum
- ImsRegistrationTermination[] terminations =
- mPersistAtomsStorage.getImsRegistrationTerminations(100L);
-
- // should be denied
- assertNull(terminations);
- }
-
- @Test
- @SmallTest
- public void getImsRegistrationTerminations_withSavedAtoms() throws Exception {
- createTestFile(START_TIME_MILLIS);
-
- mPersistAtomsStorage = new TestablePersistAtomsStorage(mContext);
- mPersistAtomsStorage.incTimeMillis(100L);
- ImsRegistrationTermination[] terminations1 =
- mPersistAtomsStorage.getImsRegistrationTerminations(50L);
- mPersistAtomsStorage.incTimeMillis(100L);
- ImsRegistrationTermination[] terminations2 =
- mPersistAtomsStorage.getImsRegistrationTerminations(50L);
-
- // first set of results should equal to file contents, second should be empty, corresponding
- // pull timestamp should be updated and saved
- assertProtoArrayEqualsIgnoringOrder(
- new ImsRegistrationTermination[] {
- mImsRegistrationTerminationLte, mImsRegistrationTerminationWifi
- },
- terminations1);
- assertProtoArrayEquals(new ImsRegistrationTermination[0], terminations2);
- assertEquals(
- START_TIME_MILLIS + 200L,
- mPersistAtomsStorage.getAtomsProto().imsRegistrationTerminationPullTimestampMillis);
- InOrder inOrder = inOrder(mTestFileOutputStream);
- assertEquals(
- START_TIME_MILLIS + 100L,
- getAtomsWritten(inOrder).imsRegistrationTerminationPullTimestampMillis);
- assertEquals(
- START_TIME_MILLIS + 200L,
- getAtomsWritten(inOrder).imsRegistrationTerminationPullTimestampMillis);
- inOrder.verifyNoMoreInteractions();
- }
-
- /* Utilities */
-
private void createEmptyTestFile() throws Exception {
PersistAtoms atoms = new PersistAtoms();
FileOutputStream stream = new FileOutputStream(mTestFile);
@@ -1284,19 +704,10 @@ public class PersistAtomsStorageTest extends TelephonyTest {
private void createTestFile(long lastPullTimeMillis) throws Exception {
PersistAtoms atoms = new PersistAtoms();
- atoms.buildFingerprint = Build.FINGERPRINT;
- atoms.voiceCallRatUsagePullTimestampMillis = lastPullTimeMillis;
- atoms.voiceCallRatUsage = mVoiceCallRatUsages;
+ atoms.rawVoiceCallRatUsagePullTimestampMillis = lastPullTimeMillis;
atoms.voiceCallSessionPullTimestampMillis = lastPullTimeMillis;
+ atoms.rawVoiceCallRatUsage = mVoiceCallRatUsages;
atoms.voiceCallSession = mVoiceCallSessions;
- atoms.cellularServiceStatePullTimestampMillis = lastPullTimeMillis;
- atoms.cellularServiceState = mServiceStates;
- atoms.cellularDataServiceSwitchPullTimestampMillis = lastPullTimeMillis;
- atoms.cellularDataServiceSwitch = mServiceSwitches;
- atoms.imsRegistrationStatsPullTimestampMillis = lastPullTimeMillis;
- atoms.imsRegistrationStats = mImsRegistrationStats;
- atoms.imsRegistrationTerminationPullTimestampMillis = lastPullTimeMillis;
- atoms.imsRegistrationTermination = mImsRegistrationTerminations;
FileOutputStream stream = new FileOutputStream(mTestFile);
stream.write(PersistAtoms.toByteArray(atoms));
stream.close();
@@ -1320,11 +731,11 @@ public class PersistAtomsStorageTest extends TelephonyTest {
}
}
- private static VoiceCallRatUsage[] multiplyVoiceCallRatUsage(
- VoiceCallRatUsage[] usages, int times) {
- VoiceCallRatUsage[] multipliedUsages = new VoiceCallRatUsage[usages.length];
+ private static RawVoiceCallRatUsage[] multiplyVoiceCallRatUsage(
+ RawVoiceCallRatUsage[] usages, int times) {
+ RawVoiceCallRatUsage[] multipliedUsages = new RawVoiceCallRatUsage[usages.length];
for (int i = 0; i < usages.length; i++) {
- multipliedUsages[i] = new VoiceCallRatUsage();
+ multipliedUsages[i] = new RawVoiceCallRatUsage();
multipliedUsages[i].carrierId = usages[i].carrierId;
multipliedUsages[i].rat = usages[i].rat;
multipliedUsages[i].callCount = usages[i].callCount * 2;
@@ -1333,73 +744,19 @@ public class PersistAtomsStorageTest extends TelephonyTest {
return multipliedUsages;
}
- private static CellularServiceState copyOf(CellularServiceState source) throws Exception {
- return CellularServiceState.parseFrom(MessageNano.toByteArray(source));
- }
-
- private static CellularDataServiceSwitch copyOf(CellularDataServiceSwitch source)
- throws Exception {
- return CellularDataServiceSwitch.parseFrom(MessageNano.toByteArray(source));
- }
-
- private static ImsRegistrationStats copyOf(ImsRegistrationStats source) throws Exception {
- return ImsRegistrationStats.parseFrom(MessageNano.toByteArray(source));
- }
-
- private static ImsRegistrationTermination copyOf(ImsRegistrationTermination source)
- throws Exception {
- return ImsRegistrationTermination.parseFrom(MessageNano.toByteArray(source));
- }
-
- private void assertAllPullTimestampEquals(long timestamp) {
- assertEquals(
- timestamp,
- mPersistAtomsStorage.getAtomsProto().voiceCallRatUsagePullTimestampMillis);
- assertEquals(
- timestamp,
- mPersistAtomsStorage.getAtomsProto().voiceCallSessionPullTimestampMillis);
- assertEquals(
- timestamp,
- mPersistAtomsStorage.getAtomsProto().cellularServiceStatePullTimestampMillis);
- assertEquals(
- timestamp,
- mPersistAtomsStorage.getAtomsProto().cellularDataServiceSwitchPullTimestampMillis);
- }
-
- private void assertStorageIsEmptyForAllAtoms() {
- assertProtoArrayIsEmpty(mPersistAtomsStorage.getVoiceCallRatUsages(0L));
- assertProtoArrayIsEmpty(mPersistAtomsStorage.getVoiceCallSessions(0L));
- assertProtoArrayIsEmpty(mPersistAtomsStorage.getCellularServiceStates(0L));
- assertProtoArrayIsEmpty(mPersistAtomsStorage.getCellularDataServiceSwitches(0L));
- }
-
- private static <T extends MessageNano> void assertProtoArrayIsEmpty(T[] array) {
- assertNotNull(array);
- assertEquals(0, array.length);
- }
-
private static void assertProtoArrayEquals(MessageNano[] expected, MessageNano[] actual) {
assertNotNull(expected);
assertNotNull(actual);
- String message =
- "Expected:\n" + Arrays.toString(expected) + "\nGot:\n" + Arrays.toString(actual);
- assertEquals(message, expected.length, actual.length);
+ assertEquals(expected.length, actual.length);
for (int i = 0; i < expected.length; i++) {
- assertTrue(message, MessageNano.messageNanoEquals(expected[i], actual[i]));
+ assertTrue(
+ String.format(
+ "Message %d of %d differs:\n=== expected ===\n%s=== got ===\n%s",
+ i + 1, expected.length, expected[i].toString(), actual[i].toString()),
+ MessageNano.messageNanoEquals(expected[i], actual[i]));
}
}
- private static void assertProtoArrayEqualsIgnoringOrder(
- MessageNano[] expected, MessageNano[] actual) {
- assertNotNull(expected);
- assertNotNull(actual);
- expected = expected.clone();
- actual = actual.clone();
- Arrays.sort(expected, sProtoComparator);
- Arrays.sort(actual, sProtoComparator);
- assertProtoArrayEquals(expected, actual);
- }
-
private static void assertHasCall(
VoiceCallSession[] calls, @Nullable VoiceCallSession expectedCall, int expectedCount) {
assertNotNull(calls);
@@ -1413,12 +770,4 @@ public class PersistAtomsStorageTest extends TelephonyTest {
}
assertEquals(expectedCount, actualCount);
}
-
- private void verifyCurrentStateSavedToFileOnce() throws Exception {
- InOrder inOrder = inOrder(mTestFileOutputStream);
- inOrder.verify(mTestFileOutputStream, times(1))
- .write(eq(PersistAtoms.toByteArray(mPersistAtomsStorage.getAtomsProto())));
- inOrder.verify(mTestFileOutputStream, times(1)).close();
- inOrder.verifyNoMoreInteractions();
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/metrics/ServiceStateStatsTest.java b/tests/telephonytests/src/com/android/internal/telephony/metrics/ServiceStateStatsTest.java
deleted file mode 100644
index 8c6752c6e4..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/metrics/ServiceStateStatsTest.java
+++ /dev/null
@@ -1,826 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.internal.telephony.metrics;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.eq;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-
-import android.telephony.AccessNetworkConstants;
-import android.telephony.Annotation.NetworkType;
-import android.telephony.NetworkRegistrationInfo;
-import android.telephony.ServiceState;
-import android.telephony.TelephonyManager;
-import android.test.suitebuilder.annotation.SmallTest;
-
-import com.android.internal.telephony.Phone;
-import com.android.internal.telephony.TelephonyTest;
-import com.android.internal.telephony.nano.PersistAtomsProto.CellularDataServiceSwitch;
-import com.android.internal.telephony.nano.PersistAtomsProto.CellularServiceState;
-import com.android.internal.telephony.uicc.IccCardStatus.CardState;
-import com.android.internal.telephony.uicc.UiccSlot;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mock;
-
-public class ServiceStateStatsTest extends TelephonyTest {
- private static final long START_TIME_MILLIS = 2000L;
- private static final int CARRIER1_ID = 1;
- private static final int CARRIER2_ID = 1187;
-
- @Mock private UiccSlot mPhysicalSlot0;
- @Mock private UiccSlot mPhysicalSlot1;
- @Mock private Phone mSecondPhone;
-
- private TestableServiceStateStats mServiceStateStats;
-
- private static class TestableServiceStateStats extends ServiceStateStats {
- private long mTimeMillis = START_TIME_MILLIS;
-
- TestableServiceStateStats(Phone phone) {
- super(phone);
- }
-
- @Override
- protected long getTimeMillis() {
- // NOTE: super class constructor will be executed before private field is set, which
- // gives the wrong start time (mTimeMillis will have its default value of 0L)
- return mTimeMillis == 0L ? START_TIME_MILLIS : mTimeMillis;
- }
-
- private void setTimeMillis(long timeMillis) {
- mTimeMillis = timeMillis;
- }
-
- private void incTimeMillis(long timeMillis) {
- mTimeMillis += timeMillis;
- }
- }
-
- @Before
- public void setUp() throws Exception {
- super.setUp(getClass().getSimpleName());
-
- doReturn(CARRIER1_ID).when(mPhone).getCarrierId();
- doReturn(mImsPhone).when(mPhone).getImsPhone();
-
- // Single physical SIM
- doReturn(true).when(mPhysicalSlot0).isActive();
- doReturn(CardState.CARDSTATE_PRESENT).when(mPhysicalSlot0).getCardState();
- doReturn(false).when(mPhysicalSlot0).isEuicc();
- doReturn(new UiccSlot[] {mPhysicalSlot0}).when(mUiccController).getUiccSlots();
- doReturn(mPhysicalSlot0).when(mUiccController).getUiccSlot(0);
- doReturn(mPhysicalSlot0).when(mUiccController).getUiccSlotForPhone(0);
-
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getVoiceNetworkType();
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- mockWwanPsRat(TelephonyManager.NETWORK_TYPE_LTE);
-
- mServiceStateStats = new TestableServiceStateStats(mPhone);
- }
-
- @After
- public void tearDown() throws Exception {
- super.tearDown();
- }
-
- @Test
- @SmallTest
- public void conclude_inService() throws Exception {
- // Using default service state for LTE
- mServiceStateStats.onServiceStateChanged(mServiceState);
-
- mServiceStateStats.incTimeMillis(100L);
- mServiceStateStats.conclude();
-
- // Duration should be counted and there should not be any switch
- ArgumentCaptor<CellularServiceState> captor =
- ArgumentCaptor.forClass(CellularServiceState.class);
- verify(mPersistAtomsStorage)
- .addCellularServiceStateAndCellularDataServiceSwitch(captor.capture(), eq(null));
- CellularServiceState state = captor.getValue();
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(100L, state.totalTimeMillis);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void conclude_outOfService() throws Exception {
- doReturn(ServiceState.STATE_OUT_OF_SERVICE).when(mServiceState).getVoiceRegState();
- doReturn(ServiceState.STATE_OUT_OF_SERVICE).when(mServiceState).getDataRegState();
- doReturn(TelephonyManager.NETWORK_TYPE_UNKNOWN).when(mServiceState).getVoiceNetworkType();
- doReturn(TelephonyManager.NETWORK_TYPE_UNKNOWN).when(mServiceState).getDataNetworkType();
- mockWwanPsRat(TelephonyManager.NETWORK_TYPE_UNKNOWN);
- mServiceStateStats.onServiceStateChanged(mServiceState);
-
- mServiceStateStats.incTimeMillis(100L);
- mServiceStateStats.conclude();
-
- // Duration should be counted and there should not be any switch
- ArgumentCaptor<CellularServiceState> captor =
- ArgumentCaptor.forClass(CellularServiceState.class);
- verify(mPersistAtomsStorage)
- .addCellularServiceStateAndCellularDataServiceSwitch(captor.capture(), eq(null));
- CellularServiceState state = captor.getValue();
- assertEquals(TelephonyManager.NETWORK_TYPE_UNKNOWN, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_UNKNOWN, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(100L, state.totalTimeMillis);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void conclude_airplaneMode() throws Exception {
- doReturn(ServiceState.STATE_POWER_OFF).when(mServiceState).getVoiceRegState();
- doReturn(ServiceState.STATE_POWER_OFF).when(mServiceState).getDataRegState();
- doReturn(TelephonyManager.NETWORK_TYPE_UNKNOWN).when(mServiceState).getVoiceNetworkType();
- doReturn(TelephonyManager.NETWORK_TYPE_UNKNOWN).when(mServiceState).getDataNetworkType();
- mockWwanPsRat(TelephonyManager.NETWORK_TYPE_UNKNOWN);
- doReturn(-1).when(mPhone).getCarrierId();
- mServiceStateStats.onServiceStateChanged(mServiceState);
-
- mServiceStateStats.incTimeMillis(100L);
- mServiceStateStats.conclude();
-
- // There should be no new switches, service states, or added durations
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void conclude_airplaneModeWithWifiCalling() throws Exception {
- doReturn(ServiceState.STATE_POWER_OFF).when(mServiceState).getVoiceRegState();
- doReturn(ServiceState.STATE_IN_SERVICE).when(mServiceState).getDataRegState();
- doReturn(TelephonyManager.NETWORK_TYPE_UNKNOWN).when(mServiceState).getVoiceNetworkType();
- doReturn(TelephonyManager.NETWORK_TYPE_IWLAN).when(mServiceState).getDataNetworkType();
- mockWwanPsRat(TelephonyManager.NETWORK_TYPE_UNKNOWN);
- doReturn(true).when(mImsPhone).isWifiCallingEnabled();
- mServiceStateStats.onServiceStateChanged(mServiceState);
-
- mServiceStateStats.incTimeMillis(100L);
- mServiceStateStats.conclude();
-
- // There should be no new switches, service states, or added durations
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void conclude_noSimCardEmergencyOnly() throws Exception {
- // Using default service state for LTE
- doReturn(CardState.CARDSTATE_ABSENT).when(mPhysicalSlot0).getCardState();
- doReturn(ServiceState.STATE_EMERGENCY_ONLY).when(mServiceState).getVoiceRegState();
- doReturn(ServiceState.STATE_EMERGENCY_ONLY).when(mServiceState).getDataRegState();
- doReturn(-1).when(mPhone).getCarrierId();
- mServiceStateStats.onServiceStateChanged(mServiceState);
-
- mServiceStateStats.incTimeMillis(100L);
- mServiceStateStats.conclude();
-
- // Duration should be counted and there should not be any switch
- ArgumentCaptor<CellularServiceState> captor =
- ArgumentCaptor.forClass(CellularServiceState.class);
- verify(mPersistAtomsStorage)
- .addCellularServiceStateAndCellularDataServiceSwitch(captor.capture(), eq(null));
- CellularServiceState state = captor.getValue();
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(-1, state.carrierId);
- assertEquals(100L, state.totalTimeMillis);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void conclude_noSimCardOutOfService() throws Exception {
- doReturn(CardState.CARDSTATE_ABSENT).when(mPhysicalSlot0).getCardState();
- doReturn(ServiceState.STATE_OUT_OF_SERVICE).when(mServiceState).getVoiceRegState();
- doReturn(ServiceState.STATE_OUT_OF_SERVICE).when(mServiceState).getDataRegState();
- doReturn(TelephonyManager.NETWORK_TYPE_UNKNOWN).when(mServiceState).getVoiceNetworkType();
- doReturn(TelephonyManager.NETWORK_TYPE_UNKNOWN).when(mServiceState).getDataNetworkType();
- mockWwanPsRat(TelephonyManager.NETWORK_TYPE_UNKNOWN);
- doReturn(-1).when(mPhone).getCarrierId();
- mServiceStateStats.onServiceStateChanged(mServiceState);
-
- mServiceStateStats.incTimeMillis(100L);
- mServiceStateStats.conclude();
-
- // Duration should be counted and there should not be any switch
- ArgumentCaptor<CellularServiceState> captor =
- ArgumentCaptor.forClass(CellularServiceState.class);
- verify(mPersistAtomsStorage)
- .addCellularServiceStateAndCellularDataServiceSwitch(captor.capture(), eq(null));
- CellularServiceState state = captor.getValue();
- assertEquals(TelephonyManager.NETWORK_TYPE_UNKNOWN, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_UNKNOWN, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(-1, state.carrierId);
- assertEquals(100L, state.totalTimeMillis);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void conclude_longOnGoingServiceState() throws Exception {
- // Using default service state for LTE
- mServiceStateStats.onServiceStateChanged(mServiceState);
-
- mServiceStateStats.incTimeMillis(100L);
- mServiceStateStats.conclude();
- mServiceStateStats.incTimeMillis(100L);
- mServiceStateStats.conclude();
-
- // There should be 2 separate service state updates, which should be different objects
- ArgumentCaptor<CellularServiceState> captor =
- ArgumentCaptor.forClass(CellularServiceState.class);
- verify(mPersistAtomsStorage, times(2))
- .addCellularServiceStateAndCellularDataServiceSwitch(captor.capture(), eq(null));
- assertNotSame(captor.getAllValues().get(0), captor.getAllValues().get(1));
- CellularServiceState state = captor.getAllValues().get(0);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(100L, state.totalTimeMillis);
- state = captor.getAllValues().get(1);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(100L, state.totalTimeMillis);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void update_sameRats() throws Exception {
- // Using default service state for LTE
-
- mServiceStateStats.onServiceStateChanged(mServiceState);
- mServiceStateStats.incTimeMillis(100L);
- mServiceStateStats.onServiceStateChanged(mServiceState);
-
- // Should produce 1 service state atom with LTE and no data service switch
- ArgumentCaptor<CellularServiceState> captor =
- ArgumentCaptor.forClass(CellularServiceState.class);
- verify(mPersistAtomsStorage)
- .addCellularServiceStateAndCellularDataServiceSwitch(captor.capture(), eq(null));
- CellularServiceState state = captor.getValue();
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(100L, state.totalTimeMillis);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void update_differentDataRats() throws Exception {
- doReturn(TelephonyManager.NETWORK_TYPE_UNKNOWN).when(mServiceState).getDataNetworkType();
- mockWwanPsRat(TelephonyManager.NETWORK_TYPE_UNKNOWN);
-
- mServiceStateStats.onServiceStateChanged(mServiceState);
- mServiceStateStats.incTimeMillis(100L);
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- mockWwanPsRat(TelephonyManager.NETWORK_TYPE_LTE);
- mServiceStateStats.onServiceStateChanged(mServiceState);
- mServiceStateStats.incTimeMillis(100L);
-
- // There should be 2 service states and a data service switch
- mServiceStateStats.conclude();
- ArgumentCaptor<CellularServiceState> serviceStateCaptor =
- ArgumentCaptor.forClass(CellularServiceState.class);
- ArgumentCaptor<CellularDataServiceSwitch> serviceSwitchCaptor =
- ArgumentCaptor.forClass(CellularDataServiceSwitch.class);
- verify(mPersistAtomsStorage, times(2))
- .addCellularServiceStateAndCellularDataServiceSwitch(
- serviceStateCaptor.capture(), serviceSwitchCaptor.capture());
- CellularServiceState state = serviceStateCaptor.getAllValues().get(0);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_UNKNOWN, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(100L, state.totalTimeMillis);
- state = serviceStateCaptor.getAllValues().get(1);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(100L, state.totalTimeMillis);
- CellularDataServiceSwitch serviceSwitch = serviceSwitchCaptor.getAllValues().get(0);
- assertEquals(TelephonyManager.NETWORK_TYPE_UNKNOWN, serviceSwitch.ratFrom);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, serviceSwitch.ratTo);
- assertEquals(0, serviceSwitch.simSlotIndex);
- assertFalse(serviceSwitch.isMultiSim);
- assertEquals(CARRIER1_ID, serviceSwitch.carrierId);
- assertEquals(1, serviceSwitch.switchCount);
- assertNull(serviceSwitchCaptor.getAllValues().get(1)); // produced by conclude()
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void update_differentVoiceRats() throws Exception {
- // Using default service state for LTE
-
- mServiceStateStats.onServiceStateChanged(mServiceState);
- mServiceStateStats.incTimeMillis(100L);
- // Voice RAT changes to IWLAN and data RAT stays in LTE according to WWAN PS RAT
- doReturn(TelephonyManager.NETWORK_TYPE_IWLAN).when(mServiceState).getDataNetworkType();
- doReturn(true).when(mImsPhone).isWifiCallingEnabled();
- mServiceStateStats.onServiceStateChanged(mServiceState);
- mServiceStateStats.incTimeMillis(100L);
-
- // There should be 2 service states but no data service switch
- mServiceStateStats.conclude();
- ArgumentCaptor<CellularServiceState> captor =
- ArgumentCaptor.forClass(CellularServiceState.class);
- verify(mPersistAtomsStorage, times(2))
- .addCellularServiceStateAndCellularDataServiceSwitch(captor.capture(), eq(null));
- CellularServiceState state = captor.getAllValues().get(0);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(100L, state.totalTimeMillis);
- state = captor.getAllValues().get(1);
- assertEquals(TelephonyManager.NETWORK_TYPE_IWLAN, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(100L, state.totalTimeMillis);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void update_iwlanButNotWifiCalling() throws Exception {
- // Using default service state for LTE as WWAN PS RAT
- doReturn(TelephonyManager.NETWORK_TYPE_IWLAN).when(mServiceState).getDataNetworkType();
- doReturn(false).when(mImsPhone).isWifiCallingEnabled();
-
- mServiceStateStats.onServiceStateChanged(mServiceState);
-
- // Should produce 1 service state atom with voice and data (WWAN PS) RAT as LTE
- mServiceStateStats.conclude();
- ArgumentCaptor<CellularServiceState> captor =
- ArgumentCaptor.forClass(CellularServiceState.class);
- verify(mPersistAtomsStorage)
- .addCellularServiceStateAndCellularDataServiceSwitch(captor.capture(), eq(null));
- CellularServiceState state = captor.getValue();
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(0L, state.totalTimeMillis);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void update_endc() throws Exception {
- // Using default service state for LTE without ENDC
-
- mServiceStateStats.onServiceStateChanged(mServiceState);
- mServiceStateStats.incTimeMillis(100L);
- // ENDC should stay false
- doReturn(NetworkRegistrationInfo.NR_STATE_RESTRICTED).when(mServiceState).getNrState();
- mServiceStateStats.onServiceStateChanged(mServiceState);
- mServiceStateStats.incTimeMillis(200L);
- // ENDC should become true
- doReturn(NetworkRegistrationInfo.NR_STATE_NOT_RESTRICTED).when(mServiceState).getNrState();
- mServiceStateStats.onServiceStateChanged(mServiceState);
- mServiceStateStats.incTimeMillis(400L);
- // ENDC should stay true
- doReturn(NetworkRegistrationInfo.NR_STATE_CONNECTED).when(mServiceState).getNrState();
- mServiceStateStats.onServiceStateChanged(mServiceState);
- mServiceStateStats.incTimeMillis(800L);
-
- // There should be 4 service state updates (2 distinct service states) but no service switch
- mServiceStateStats.conclude();
- ArgumentCaptor<CellularServiceState> captor =
- ArgumentCaptor.forClass(CellularServiceState.class);
- verify(mPersistAtomsStorage, times(4))
- .addCellularServiceStateAndCellularDataServiceSwitch(captor.capture(), eq(null));
- CellularServiceState state = captor.getAllValues().get(0);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(100L, state.totalTimeMillis);
- state = captor.getAllValues().get(1);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(200L, state.totalTimeMillis);
- state = captor.getAllValues().get(2);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertTrue(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(400L, state.totalTimeMillis);
- state = captor.getAllValues().get(3);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertTrue(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(800L, state.totalTimeMillis);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void update_simSwapSameRat() throws Exception {
- // Using default service state for LTE
-
- mServiceStateStats.onServiceStateChanged(mServiceState);
- mServiceStateStats.incTimeMillis(100L);
- // SIM removed, emergency call only
- doReturn(CardState.CARDSTATE_ABSENT).when(mPhysicalSlot0).getCardState();
- doReturn(TelephonyManager.NETWORK_TYPE_UMTS).when(mServiceState).getVoiceNetworkType();
- doReturn(TelephonyManager.NETWORK_TYPE_UNKNOWN).when(mServiceState).getDataNetworkType();
- mockWwanPsRat(TelephonyManager.NETWORK_TYPE_UNKNOWN);
- doReturn(-1).when(mPhone).getCarrierId();
- mServiceStateStats.onServiceStateChanged(mServiceState);
- mServiceStateStats.incTimeMillis(5000L);
- // New SIM inserted
- doReturn(CardState.CARDSTATE_PRESENT).when(mPhysicalSlot0).getCardState();
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getVoiceNetworkType();
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- mockWwanPsRat(TelephonyManager.NETWORK_TYPE_LTE);
- doReturn(CARRIER2_ID).when(mPhone).getCarrierId();
- mServiceStateStats.onServiceStateChanged(mServiceState);
- mServiceStateStats.incTimeMillis(200L);
-
- // There should be 3 service states, but there should be no switches due to carrier change
- mServiceStateStats.conclude();
- ArgumentCaptor<CellularServiceState> captor =
- ArgumentCaptor.forClass(CellularServiceState.class);
- verify(mPersistAtomsStorage, times(3))
- .addCellularServiceStateAndCellularDataServiceSwitch(captor.capture(), eq(null));
- CellularServiceState state = captor.getAllValues().get(0);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(100L, state.totalTimeMillis);
- state = captor.getAllValues().get(1);
- assertEquals(TelephonyManager.NETWORK_TYPE_UMTS, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_UNKNOWN, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(-1, state.carrierId);
- assertEquals(5000L, state.totalTimeMillis);
- state = captor.getAllValues().get(2);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(CARRIER2_ID, state.carrierId);
- assertEquals(200L, state.totalTimeMillis);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void update_roaming() throws Exception {
- // Using default service state for LTE
-
- mServiceStateStats.onServiceStateChanged(mServiceState);
- mServiceStateStats.incTimeMillis(100L);
- // Voice roaming
- doReturn(TelephonyManager.NETWORK_TYPE_UMTS).when(mServiceState).getVoiceNetworkType();
- doReturn(TelephonyManager.NETWORK_TYPE_UMTS).when(mServiceState).getDataNetworkType();
- mockWwanPsRat(TelephonyManager.NETWORK_TYPE_UMTS);
- doReturn(ServiceState.ROAMING_TYPE_INTERNATIONAL).when(mServiceState).getVoiceRoamingType();
- mServiceStateStats.onServiceStateChanged(mServiceState);
- mServiceStateStats.incTimeMillis(200L);
- // Voice and data roaming
- doReturn(ServiceState.ROAMING_TYPE_INTERNATIONAL).when(mServiceState).getDataRoamingType();
- mServiceStateStats.onServiceStateChanged(mServiceState);
- mServiceStateStats.incTimeMillis(400L);
-
- // There should be 3 service states and 1 data service switch (LTE to UMTS)
- mServiceStateStats.conclude();
- ArgumentCaptor<CellularServiceState> serviceStateCaptor =
- ArgumentCaptor.forClass(CellularServiceState.class);
- ArgumentCaptor<CellularDataServiceSwitch> serviceSwitchCaptor =
- ArgumentCaptor.forClass(CellularDataServiceSwitch.class);
- verify(mPersistAtomsStorage, times(3))
- .addCellularServiceStateAndCellularDataServiceSwitch(
- serviceStateCaptor.capture(), serviceSwitchCaptor.capture());
- CellularServiceState state = serviceStateCaptor.getAllValues().get(0);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(100L, state.totalTimeMillis);
- state = serviceStateCaptor.getAllValues().get(1);
- assertEquals(TelephonyManager.NETWORK_TYPE_UMTS, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_UMTS, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_INTERNATIONAL, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(200L, state.totalTimeMillis);
- state = serviceStateCaptor.getAllValues().get(2);
- assertEquals(TelephonyManager.NETWORK_TYPE_UMTS, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_UMTS, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_INTERNATIONAL, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_INTERNATIONAL, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(400L, state.totalTimeMillis);
- CellularDataServiceSwitch serviceSwitch = serviceSwitchCaptor.getAllValues().get(0);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, serviceSwitch.ratFrom);
- assertEquals(TelephonyManager.NETWORK_TYPE_UMTS, serviceSwitch.ratTo);
- assertEquals(0, serviceSwitch.simSlotIndex);
- assertFalse(serviceSwitch.isMultiSim);
- assertEquals(CARRIER1_ID, serviceSwitch.carrierId);
- assertEquals(1, serviceSwitch.switchCount);
- assertNull(serviceSwitchCaptor.getAllValues().get(1));
- assertNull(serviceSwitchCaptor.getAllValues().get(2)); // produced by conclude()
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void update_dualSim() throws Exception {
- // Using default service state for LTE
- // Only difference between the 2 slots is slot index
- mockDualSim(CARRIER1_ID);
- TestableServiceStateStats mSecondServiceStateStats =
- new TestableServiceStateStats(mSecondPhone);
-
- mServiceStateStats.onServiceStateChanged(mServiceState);
- mServiceStateStats.incTimeMillis(100L);
- mSecondServiceStateStats.onServiceStateChanged(mServiceState);
- mSecondServiceStateStats.incTimeMillis(100L);
- doReturn(TelephonyManager.NETWORK_TYPE_UMTS).when(mServiceState).getVoiceNetworkType();
- doReturn(TelephonyManager.NETWORK_TYPE_UMTS).when(mServiceState).getDataNetworkType();
- mockWwanPsRat(TelephonyManager.NETWORK_TYPE_UMTS);
- mServiceStateStats.onServiceStateChanged(mServiceState);
- mServiceStateStats.incTimeMillis(200L);
- mSecondServiceStateStats.onServiceStateChanged(mServiceState);
- mSecondServiceStateStats.incTimeMillis(200L);
-
- // There should be 4 service states and 2 data service switches
- mServiceStateStats.conclude();
- mSecondServiceStateStats.conclude();
- ArgumentCaptor<CellularServiceState> serviceStateCaptor =
- ArgumentCaptor.forClass(CellularServiceState.class);
- ArgumentCaptor<CellularDataServiceSwitch> serviceSwitchCaptor =
- ArgumentCaptor.forClass(CellularDataServiceSwitch.class);
- verify(mPersistAtomsStorage, times(4))
- .addCellularServiceStateAndCellularDataServiceSwitch(
- serviceStateCaptor.capture(), serviceSwitchCaptor.capture());
- CellularServiceState state = serviceStateCaptor.getAllValues().get(0);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertTrue(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(100L, state.totalTimeMillis);
- state = serviceStateCaptor.getAllValues().get(1);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(1, state.simSlotIndex);
- assertTrue(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(100L, state.totalTimeMillis);
- state = serviceStateCaptor.getAllValues().get(2);
- assertEquals(TelephonyManager.NETWORK_TYPE_UMTS, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_UMTS, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertTrue(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(200L, state.totalTimeMillis);
- state = serviceStateCaptor.getAllValues().get(3);
- assertEquals(TelephonyManager.NETWORK_TYPE_UMTS, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_UMTS, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(1, state.simSlotIndex);
- assertTrue(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(200L, state.totalTimeMillis);
- CellularDataServiceSwitch serviceSwitch = serviceSwitchCaptor.getAllValues().get(0);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, serviceSwitch.ratFrom);
- assertEquals(TelephonyManager.NETWORK_TYPE_UMTS, serviceSwitch.ratTo);
- assertEquals(0, serviceSwitch.simSlotIndex);
- assertTrue(serviceSwitch.isMultiSim);
- assertEquals(CARRIER1_ID, serviceSwitch.carrierId);
- assertEquals(1, serviceSwitch.switchCount);
- serviceSwitch = serviceSwitchCaptor.getAllValues().get(1);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, serviceSwitch.ratFrom);
- assertEquals(TelephonyManager.NETWORK_TYPE_UMTS, serviceSwitch.ratTo);
- assertEquals(1, serviceSwitch.simSlotIndex);
- assertTrue(serviceSwitch.isMultiSim);
- assertEquals(CARRIER1_ID, serviceSwitch.carrierId);
- assertEquals(1, serviceSwitch.switchCount);
- assertNull(serviceSwitchCaptor.getAllValues().get(2)); // produced by conclude()
- assertNull(serviceSwitchCaptor.getAllValues().get(3)); // produced by conclude()
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- @Test
- @SmallTest
- public void update_airplaneMode() throws Exception {
- // Using default service state for LTE
-
- mServiceStateStats.onServiceStateChanged(mServiceState);
- mServiceStateStats.incTimeMillis(100L);
- doReturn(ServiceState.STATE_POWER_OFF).when(mServiceState).getVoiceRegState();
- doReturn(ServiceState.STATE_POWER_OFF).when(mServiceState).getDataRegState();
- doReturn(TelephonyManager.NETWORK_TYPE_UNKNOWN).when(mServiceState).getVoiceNetworkType();
- doReturn(TelephonyManager.NETWORK_TYPE_UNKNOWN).when(mServiceState).getDataNetworkType();
- mockWwanPsRat(TelephonyManager.NETWORK_TYPE_UNKNOWN);
- doReturn(-1).when(mPhone).getCarrierId();
- mServiceStateStats.onServiceStateChanged(mServiceState);
- mServiceStateStats.incTimeMillis(5000L);
- doReturn(ServiceState.STATE_IN_SERVICE).when(mServiceState).getVoiceRegState();
- doReturn(ServiceState.STATE_IN_SERVICE).when(mServiceState).getDataRegState();
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getVoiceNetworkType();
- doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getDataNetworkType();
- mockWwanPsRat(TelephonyManager.NETWORK_TYPE_LTE);
- doReturn(CARRIER1_ID).when(mPhone).getCarrierId();
- mServiceStateStats.onServiceStateChanged(mServiceState);
- mServiceStateStats.incTimeMillis(200L);
-
- // There should be 2 service state updates (1 distinct service state) and no switches
- mServiceStateStats.conclude();
- ArgumentCaptor<CellularServiceState> captor =
- ArgumentCaptor.forClass(CellularServiceState.class);
- verify(mPersistAtomsStorage, times(2))
- .addCellularServiceStateAndCellularDataServiceSwitch(captor.capture(), eq(null));
- CellularServiceState state = captor.getAllValues().get(0);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(100L, state.totalTimeMillis);
- state = captor.getAllValues().get(1);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.voiceRat);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, state.dataRat);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.voiceRoamingType);
- assertEquals(ServiceState.ROAMING_TYPE_NOT_ROAMING, state.dataRoamingType);
- assertFalse(state.isEndc);
- assertEquals(0, state.simSlotIndex);
- assertFalse(state.isMultiSim);
- assertEquals(CARRIER1_ID, state.carrierId);
- assertEquals(200L, state.totalTimeMillis);
- verifyNoMoreInteractions(mPersistAtomsStorage);
- }
-
- private void mockWwanPsRat(@NetworkType int rat) {
- doReturn(new NetworkRegistrationInfo.Builder().setAccessNetworkTechnology(rat).build())
- .when(mServiceState)
- .getNetworkRegistrationInfo(
- NetworkRegistrationInfo.DOMAIN_PS,
- AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
- }
-
- private void mockDualSim(int carrierId) {
- doReturn(1).when(mSecondPhone).getPhoneId();
- doReturn(1).when(mUiccController).getSlotIdFromPhoneId(1);
- doReturn(carrierId).when(mSecondPhone).getCarrierId();
-
- doReturn(true).when(mPhysicalSlot1).isActive();
- doReturn(CardState.CARDSTATE_PRESENT).when(mPhysicalSlot1).getCardState();
- doReturn(false).when(mPhysicalSlot1).isEuicc();
- doReturn(new UiccSlot[] {mPhysicalSlot0, mPhysicalSlot1})
- .when(mUiccController)
- .getUiccSlots();
- doReturn(mPhysicalSlot1).when(mUiccController).getUiccSlot(1);
- doReturn(mPhysicalSlot1).when(mUiccController).getUiccSlotForPhone(1);
- }
-}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/metrics/SimSlotStateTest.java b/tests/telephonytests/src/com/android/internal/telephony/metrics/SimSlotStateTest.java
index e05faecc53..0f1196f27b 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/metrics/SimSlotStateTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/metrics/SimSlotStateTest.java
@@ -17,8 +17,6 @@
package com.android.internal.telephony.metrics;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
@@ -75,12 +73,10 @@ public class SimSlotStateTest extends TelephonyTest {
doReturn(new UiccSlot[] {}).when(mUiccController).getUiccSlots();
SimSlotState state = SimSlotState.getCurrentState();
- boolean isMultiSim = SimSlotState.isMultiSim();
assertEquals(0, state.numActiveSlots);
assertEquals(0, state.numActiveSims);
assertEquals(0, state.numActiveEsims);
- assertFalse(isMultiSim);
}
@Test
@@ -89,12 +85,10 @@ public class SimSlotStateTest extends TelephonyTest {
setupSingleSim(null);
SimSlotState state = SimSlotState.getCurrentState();
- boolean isMultiSim = SimSlotState.isMultiSim();
assertEquals(0, state.numActiveSlots);
assertEquals(0, state.numActiveSims);
assertEquals(0, state.numActiveEsims);
- assertFalse(isMultiSim);
}
@Test
@@ -103,12 +97,10 @@ public class SimSlotStateTest extends TelephonyTest {
setupSingleSim(mInactiveSlot);
SimSlotState state = SimSlotState.getCurrentState();
- boolean isMultiSim = SimSlotState.isMultiSim();
assertEquals(0, state.numActiveSlots);
assertEquals(0, state.numActiveSims);
assertEquals(0, state.numActiveEsims);
- assertFalse(isMultiSim);
}
@Test
@@ -117,12 +109,10 @@ public class SimSlotStateTest extends TelephonyTest {
setupSingleSim(mEmptySlot);
SimSlotState state = SimSlotState.getCurrentState();
- boolean isMultiSim = SimSlotState.isMultiSim();
assertEquals(1, state.numActiveSlots);
assertEquals(0, state.numActiveSims);
assertEquals(0, state.numActiveEsims);
- assertFalse(isMultiSim);
}
@Test
@@ -132,12 +122,10 @@ public class SimSlotStateTest extends TelephonyTest {
setupSingleSim(mPhysicalSlot);
SimSlotState state = SimSlotState.getCurrentState();
- boolean isMultiSim = SimSlotState.isMultiSim();
assertEquals(1, state.numActiveSlots);
assertEquals(1, state.numActiveSims);
assertEquals(0, state.numActiveEsims);
- assertFalse(isMultiSim);
}
@Test
@@ -147,12 +135,10 @@ public class SimSlotStateTest extends TelephonyTest {
setupSingleSim(mPhysicalSlot);
SimSlotState state = SimSlotState.getCurrentState();
- boolean isMultiSim = SimSlotState.isMultiSim();
assertEquals(1, state.numActiveSlots);
assertEquals(0, state.numActiveSims);
assertEquals(0, state.numActiveEsims);
- assertFalse(isMultiSim);
}
@Test
@@ -162,13 +148,11 @@ public class SimSlotStateTest extends TelephonyTest {
setupSingleSim(mPhysicalSlot);
SimSlotState state = SimSlotState.getCurrentState();
- boolean isMultiSim = SimSlotState.isMultiSim();
// the metrics should not count restricted cards since they cannot be used
assertEquals(1, state.numActiveSlots);
assertEquals(0, state.numActiveSims);
assertEquals(0, state.numActiveEsims);
- assertFalse(isMultiSim);
}
@Test
@@ -178,12 +162,10 @@ public class SimSlotStateTest extends TelephonyTest {
setupSingleSim(mEsimSlot);
SimSlotState state = SimSlotState.getCurrentState();
- boolean isMultiSim = SimSlotState.isMultiSim();
assertEquals(1, state.numActiveSlots);
assertEquals(0, state.numActiveSims);
assertEquals(0, state.numActiveEsims);
- assertFalse(isMultiSim);
}
@Test
@@ -193,12 +175,10 @@ public class SimSlotStateTest extends TelephonyTest {
setupSingleSim(mEsimSlot);
SimSlotState state = SimSlotState.getCurrentState();
- boolean isMultiSim = SimSlotState.isMultiSim();
assertEquals(1, state.numActiveSlots);
assertEquals(0, state.numActiveSims);
assertEquals(0, state.numActiveEsims);
- assertFalse(isMultiSim);
}
@Test
@@ -208,12 +188,10 @@ public class SimSlotStateTest extends TelephonyTest {
setupSingleSim(mEsimSlot);
SimSlotState state = SimSlotState.getCurrentState();
- boolean isMultiSim = SimSlotState.isMultiSim();
assertEquals(1, state.numActiveSlots);
assertEquals(1, state.numActiveSims);
assertEquals(1, state.numActiveEsims);
- assertFalse(isMultiSim);
}
@Test
@@ -222,12 +200,10 @@ public class SimSlotStateTest extends TelephonyTest {
setupDualSim(mEmptySlot, mInactiveSlot);
SimSlotState state = SimSlotState.getCurrentState();
- boolean isMultiSim = SimSlotState.isMultiSim();
assertEquals(1, state.numActiveSlots);
assertEquals(0, state.numActiveSims);
assertEquals(0, state.numActiveEsims);
- assertFalse(isMultiSim);
}
@Test
@@ -236,12 +212,10 @@ public class SimSlotStateTest extends TelephonyTest {
setupDualSim(mPhysicalSlot, mInactiveSlot);
SimSlotState state = SimSlotState.getCurrentState();
- boolean isMultiSim = SimSlotState.isMultiSim();
assertEquals(1, state.numActiveSlots);
assertEquals(1, state.numActiveSims);
assertEquals(0, state.numActiveEsims);
- assertFalse(isMultiSim);
}
@Test
@@ -251,12 +225,10 @@ public class SimSlotStateTest extends TelephonyTest {
setupDualSim(mInactiveSlot, mEsimSlot);
SimSlotState state = SimSlotState.getCurrentState();
- boolean isMultiSim = SimSlotState.isMultiSim();
assertEquals(1, state.numActiveSlots);
assertEquals(0, state.numActiveSims);
assertEquals(0, state.numActiveEsims);
- assertFalse(isMultiSim);
}
@Test
@@ -266,12 +238,10 @@ public class SimSlotStateTest extends TelephonyTest {
setupDualSim(mInactiveSlot, mEsimSlot);
SimSlotState state = SimSlotState.getCurrentState();
- boolean isMultiSim = SimSlotState.isMultiSim();
assertEquals(1, state.numActiveSlots);
assertEquals(1, state.numActiveSims);
assertEquals(1, state.numActiveEsims);
- assertFalse(isMultiSim);
}
@Test
@@ -281,12 +251,10 @@ public class SimSlotStateTest extends TelephonyTest {
setupDualSim(mEmptySlot, mEsimSlot);
SimSlotState state = SimSlotState.getCurrentState();
- boolean isMultiSim = SimSlotState.isMultiSim();
assertEquals(2, state.numActiveSlots);
assertEquals(0, state.numActiveSims);
assertEquals(0, state.numActiveEsims);
- assertFalse(isMultiSim);
}
@Test
@@ -296,12 +264,10 @@ public class SimSlotStateTest extends TelephonyTest {
setupDualSim(mPhysicalSlot, mEsimSlot);
SimSlotState state = SimSlotState.getCurrentState();
- boolean isMultiSim = SimSlotState.isMultiSim();
assertEquals(2, state.numActiveSlots);
assertEquals(1, state.numActiveSims);
assertEquals(0, state.numActiveEsims);
- assertFalse(isMultiSim);
}
@Test
@@ -311,12 +277,10 @@ public class SimSlotStateTest extends TelephonyTest {
setupDualSim(mEmptySlot, mEsimSlot);
SimSlotState state = SimSlotState.getCurrentState();
- boolean isMultiSim = SimSlotState.isMultiSim();
assertEquals(2, state.numActiveSlots);
assertEquals(1, state.numActiveSims);
assertEquals(1, state.numActiveEsims);
- assertFalse(isMultiSim);
}
@Test
@@ -326,12 +290,10 @@ public class SimSlotStateTest extends TelephonyTest {
setupDualSim(mPhysicalSlot, mEsimSlot);
SimSlotState state = SimSlotState.getCurrentState();
- boolean isMultiSim = SimSlotState.isMultiSim();
assertEquals(2, state.numActiveSlots);
assertEquals(2, state.numActiveSims);
assertEquals(1, state.numActiveEsims);
- assertTrue(isMultiSim);
}
@Test
@@ -340,45 +302,10 @@ public class SimSlotStateTest extends TelephonyTest {
setupDualSim(mPhysicalSlot, mPhysicalSlot);
SimSlotState state = SimSlotState.getCurrentState();
- boolean isMultiSim = SimSlotState.isMultiSim();
assertEquals(2, state.numActiveSlots);
assertEquals(2, state.numActiveSims);
assertEquals(0, state.numActiveEsims);
- assertTrue(isMultiSim);
- }
-
- @Test
- @SmallTest
- public void isEsim_singlePhysicalSim() {
- doReturn(mPhysicalSlot).when(mUiccController).getUiccSlotForPhone(eq(0));
-
- boolean isEsim = SimSlotState.isEsim(0);
-
- assertFalse(isEsim);
- }
-
- @Test
- @SmallTest
- public void isEsim_singleEsim() {
- doReturn(mEsimSlot).when(mUiccController).getUiccSlotForPhone(eq(0));
-
- boolean isEsim = SimSlotState.isEsim(0);
-
- assertTrue(isEsim);
- }
-
- @Test
- @SmallTest
- public void isEsim_dualSim() {
- doReturn(mPhysicalSlot).when(mUiccController).getUiccSlotForPhone(eq(0));
- doReturn(mEsimSlot).when(mUiccController).getUiccSlotForPhone(eq(1));
-
- boolean isEsim0 = SimSlotState.isEsim(0);
- boolean isEsim1 = SimSlotState.isEsim(1);
-
- assertFalse(isEsim0);
- assertTrue(isEsim1);
}
private void setupSingleSim(UiccSlot slot0) {
diff --git a/tests/telephonytests/src/com/android/internal/telephony/metrics/TelephonyMetricsTest.java b/tests/telephonytests/src/com/android/internal/telephony/metrics/TelephonyMetricsTest.java
index c4e6e27d4e..44c9e8418a 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/metrics/TelephonyMetricsTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/metrics/TelephonyMetricsTest.java
@@ -29,7 +29,6 @@ import static com.android.internal.telephony.dataconnection.DcTrackerTest.FAKE_D
import static com.android.internal.telephony.dataconnection.DcTrackerTest.FAKE_GATEWAY;
import static com.android.internal.telephony.dataconnection.DcTrackerTest.FAKE_IFNAME;
import static com.android.internal.telephony.dataconnection.DcTrackerTest.FAKE_PCSCF_ADDRESS;
-import static com.android.internal.telephony.dataconnection.LinkBandwidthEstimator.NUM_SIGNAL_LEVEL;
import static com.android.internal.telephony.nano.TelephonyProto.PdpType.PDP_TYPE_IPV4V6;
import static org.junit.Assert.assertArrayEquals;
@@ -60,11 +59,8 @@ import com.android.internal.telephony.PhoneConstants;
import com.android.internal.telephony.SmsResponse;
import com.android.internal.telephony.TelephonyTest;
import com.android.internal.telephony.UUSInfo;
-import com.android.internal.telephony.dataconnection.LinkBandwidthEstimator;
import com.android.internal.telephony.nano.TelephonyProto;
-import com.android.internal.telephony.nano.TelephonyProto.BandwidthEstimatorStats;
import com.android.internal.telephony.nano.TelephonyProto.ImsConnectionState;
-import com.android.internal.telephony.nano.TelephonyProto.NrMode;
import com.android.internal.telephony.nano.TelephonyProto.RadioAccessTechnology;
import com.android.internal.telephony.nano.TelephonyProto.SmsSession;
import com.android.internal.telephony.nano.TelephonyProto.TelephonyCallSession;
@@ -77,7 +73,6 @@ import com.android.internal.telephony.nano.TelephonyProto.TelephonyServiceState;
import com.android.internal.telephony.nano.TelephonyProto.TelephonyServiceState.FrequencyRange;
import com.android.internal.telephony.nano.TelephonyProto.TelephonyServiceState.NrState;
import com.android.internal.telephony.nano.TelephonyProto.TelephonyServiceState.RoamingType;
-import com.android.internal.telephony.nano.TelephonyProto.TelephonySettings.RilNetworkMode;
import org.junit.After;
import org.junit.Before;
@@ -424,36 +419,6 @@ public class TelephonyMetricsTest extends TelephonyTest {
assertTrue(log.callSessions[0].events[1].settings.isEnhanced4GLteModeEnabled);
}
- // Test multiple events impacting TelephonySettings.
- @Test
- @SmallTest
- public void testTelephonySettingsEvents() throws Exception {
- mMetrics.writeImsSetFeatureValue(mPhone.getPhoneId(),
- MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
- ImsRegistrationImplBase.REGISTRATION_TECH_LTE, 1);
- mMetrics.writeSetPreferredNetworkType(mPhone.getPhoneId(),
- TelephonyManager.NETWORK_MODE_LTE_ONLY);
- mMetrics.writeImsSetFeatureValue(mPhone.getPhoneId(),
- MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
- ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN, 1);
-
- TelephonyLog log = buildProto();
-
- assertEquals(3, log.events.length);
- assertTrue(log.events[0].settings.isEnhanced4GLteModeEnabled);
- assertFalse(log.events[0].settings.isWifiCallingEnabled);
- assertEquals(log.events[0].settings.preferredNetworkMode,
- RilNetworkMode.NETWORK_MODE_UNKNOWN);
- assertTrue(log.events[1].settings.isEnhanced4GLteModeEnabled);
- assertFalse(log.events[1].settings.isWifiCallingEnabled);
- assertEquals(log.events[1].settings.preferredNetworkMode,
- RilNetworkMode.NETWORK_MODE_LTE_ONLY);
- assertTrue(log.events[2].settings.isEnhanced4GLteModeEnabled);
- assertTrue(log.events[2].settings.isWifiCallingEnabled);
- assertEquals(log.events[2].settings.preferredNetworkMode,
- RilNetworkMode.NETWORK_MODE_LTE_ONLY);
- }
-
// Test write on ims call handover event
@Test
@SmallTest
@@ -541,7 +506,7 @@ public class TelephonyMetricsTest extends TelephonyTest {
public void testWriteOnSetupDataCallResponse() throws Exception {
DataCallResponse response = new DataCallResponse.Builder()
.setCause(5)
- .setRetryDurationMillis(6)
+ .setSuggestedRetryTime(6)
.setId(7)
.setLinkStatus(8)
.setProtocolType(ApnSetting.PROTOCOL_IPV4V6)
@@ -571,7 +536,7 @@ public class TelephonyMetricsTest extends TelephonyTest {
assertEquals(6, respProto.suggestedRetryTimeMillis);
assertEquals(7, respProto.call.cid);
assertEquals(PDP_TYPE_IPV4V6, respProto.call.type);
- assertEquals(FAKE_IFNAME, respProto.call.ifname);
+ assertEquals(FAKE_IFNAME, respProto.call.iframe);
}
// Test write on deactivate data call response
@@ -595,17 +560,14 @@ public class TelephonyMetricsTest extends TelephonyTest {
@Test
@SmallTest
public void testWriteRilSendSms() throws Exception {
- long fakeMessageId1 = 123123L;
- long fakeMessageId2 = -987L;
+ mMetrics.writeRilSendSms(mPhone.getPhoneId(), 1, 2, 1);
+ mMetrics.writeRilSendSms(mPhone.getPhoneId(), 4, 5, 2);
- mMetrics.writeRilSendSms(mPhone.getPhoneId(), 1, 2, 1, fakeMessageId1);
- mMetrics.writeRilSendSms(mPhone.getPhoneId(), 4, 5, 2, fakeMessageId2);
-
- SmsResponse response = new SmsResponse(0, null, 123, fakeMessageId1);
+ SmsResponse response = new SmsResponse(0, null, 123);
mMetrics.writeOnRilSolicitedResponse(mPhone.getPhoneId(), 1, 0, RIL_REQUEST_SEND_SMS,
response);
- response = new SmsResponse(0, null, 456, fakeMessageId2);
+ response = new SmsResponse(0, null, 456);
mMetrics.writeOnRilSolicitedResponse(mPhone.getPhoneId(), 4, 0, RIL_REQUEST_SEND_SMS,
response);
TelephonyLog log = buildProto();
@@ -621,25 +583,21 @@ public class TelephonyMetricsTest extends TelephonyTest {
assertEquals(1, events[0].rilRequestId);
assertEquals(2, events[0].tech);
assertEquals(1, events[0].format);
- assertEquals(fakeMessageId1, events[0].messageId);
assertEquals(SmsSession.Event.Type.SMS_SEND, events[1].type);
assertEquals(4, events[1].rilRequestId);
assertEquals(5, events[1].tech);
assertEquals(2, events[1].format);
- assertEquals(fakeMessageId2, events[1].messageId);
assertEquals(SmsSession.Event.Type.SMS_SEND_RESULT, events[2].type);
assertEquals(1, events[2].rilRequestId);
assertEquals(1, events[2].error);
assertEquals(123, events[2].errorCode);
- assertEquals(fakeMessageId1, events[2].messageId);
assertEquals(SmsSession.Event.Type.SMS_SEND_RESULT, events[3].type);
assertEquals(4, events[3].rilRequestId);
assertEquals(1, events[3].error);
assertEquals(456, events[3].errorCode);
- assertEquals(fakeMessageId2, events[3].messageId);
}
// Test write phone state
@@ -876,39 +834,4 @@ public class TelephonyMetricsTest extends TelephonyTest {
assertEquals(false, event.imsCapabilities.videoOverLte);
assertEquals(false, event.imsCapabilities.utOverLte);
}
-
-
- // Test write Bandwidth Stats
- @Test
- @SmallTest
- public void testWriteBandwidthStats() throws Exception {
- addBandwidthStats(LinkBandwidthEstimator.LINK_TX, TelephonyManager.NETWORK_TYPE_LTE,
- NrMode.NR_NSA_MMWAVE);
- addBandwidthStats(LinkBandwidthEstimator.LINK_RX, TelephonyManager.NETWORK_TYPE_LTE,
- NrMode.NR_NSA_MMWAVE);
- addBandwidthStats(LinkBandwidthEstimator.LINK_RX, TelephonyManager.NETWORK_TYPE_NR,
- NrMode.NR_SA_MMWAVE);
- TelephonyLog log = buildProto();
-
- BandwidthEstimatorStats stats = log.bandwidthEstimatorStats;
- assertEquals(1, stats.perRatTx.length);
- assertEquals(2, stats.perRatRx.length);
- assertEquals(TelephonyManager.NETWORK_TYPE_LTE, stats.perRatTx[0].rat);
- assertEquals(NrMode.NR_NSA_MMWAVE, stats.perRatTx[0].nrMode);
- assertEquals(NUM_SIGNAL_LEVEL - 1, stats.perRatTx[0].perLevel.length);
- assertEquals(2, stats.perRatTx[0].perLevel[0].count);
- assertEquals(0, stats.perRatTx[0].perLevel[0].signalLevel);
- assertEquals(400_000, stats.perRatTx[0].perLevel[0].avgBwKbps);
- assertEquals(40, stats.perRatTx[0].perLevel[0].staticBwErrorPercent);
- assertEquals(30, stats.perRatTx[0].perLevel[0].bwEstErrorPercent);
- }
-
- private void addBandwidthStats(int link, int dataRat, int nrMode) {
- for (int i = 0; i < NUM_SIGNAL_LEVEL - 1; i++) {
- mMetrics.writeBandwidthStats(link, dataRat, nrMode,
- i, 20, 30, 300_000);
- mMetrics.writeBandwidthStats(link, dataRat, nrMode,
- i, 40, 50, 500_000);
- }
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/metrics/VoiceCallSessionStatsTest.java b/tests/telephonytests/src/com/android/internal/telephony/metrics/VoiceCallSessionStatsTest.java
index f64bc6ea16..d8db445183 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/metrics/VoiceCallSessionStatsTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/metrics/VoiceCallSessionStatsTest.java
@@ -20,12 +20,11 @@ import static com.android.internal.telephony.TelephonyStatsLog.VOICE_CALL_SESSIO
import static com.android.internal.telephony.TelephonyStatsLog.VOICE_CALL_SESSION__BEARER_AT_END__CALL_BEARER_IMS;
import static com.android.internal.telephony.TelephonyStatsLog.VOICE_CALL_SESSION__DIRECTION__CALL_DIRECTION_MO;
import static com.android.internal.telephony.TelephonyStatsLog.VOICE_CALL_SESSION__DIRECTION__CALL_DIRECTION_MT;
-import static com.android.internal.telephony.TelephonyStatsLog.VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
-import static com.android.internal.telephony.TelephonyStatsLog.VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_SUPER_WIDEBAND;
-import static com.android.internal.telephony.TelephonyStatsLog.VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_UNKNOWN;
import static com.android.internal.telephony.TelephonyStatsLog.VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_EXTREMELY_FAST;
+import static com.android.internal.telephony.TelephonyStatsLog.VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_FAST;
import static com.android.internal.telephony.TelephonyStatsLog.VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_ULTRA_FAST;
import static com.android.internal.telephony.TelephonyStatsLog.VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_UNKNOWN;
+import static com.android.internal.telephony.TelephonyStatsLog.VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_VERY_FAST;
import static com.android.internal.telephony.TelephonyStatsLog.VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_VERY_SLOW;
import static com.google.common.truth.Truth.assertThat;
@@ -42,6 +41,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
import android.telephony.DisconnectCause;
import android.telephony.PreciseDisconnectCause;
import android.telephony.ServiceState;
+import android.telephony.SubscriptionInfo;
import android.telephony.TelephonyManager;
import android.telephony.ims.ImsReasonInfo;
import android.telephony.ims.ImsStreamMediaProfile;
@@ -58,7 +58,7 @@ import com.android.internal.telephony.ServiceStateTracker;
import com.android.internal.telephony.TelephonyTest;
import com.android.internal.telephony.imsphone.ImsPhoneCall;
import com.android.internal.telephony.imsphone.ImsPhoneConnection;
-import com.android.internal.telephony.nano.PersistAtomsProto.VoiceCallRatUsage;
+import com.android.internal.telephony.nano.PersistAtomsProto.RawVoiceCallRatUsage;
import com.android.internal.telephony.nano.PersistAtomsProto.VoiceCallSession;
import com.android.internal.telephony.nano.TelephonyProto.TelephonyCallSession.Event.AudioCodec;
import com.android.internal.telephony.protobuf.nano.MessageNano;
@@ -102,6 +102,10 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
@Mock private ImsPhoneCall mImsCall0;
@Mock private ImsPhoneCall mImsCall1;
+ @Mock private SubscriptionInfo mSubInfo0;
+ @Mock private SubscriptionInfo mSubInfo1;
+ private List<SubscriptionInfo> mSubInfos;
+
private static class TestableVoiceCallSessionStats extends VoiceCallSessionStats {
private long mTimeMillis = 0L;
@@ -131,10 +135,7 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
super.setUp(getClass().getSimpleName());
replaceInstance(PhoneFactory.class, "sPhones", null, new Phone[] {mPhone, mSecondPhone});
- doReturn(CARRIER_ID_SLOT_0).when(mPhone).getCarrierId();
// mPhone's mSST/mServiceState has been set up by TelephonyTest
- doReturn(CARRIER_ID_SLOT_1).when(mSecondPhone).getCarrierId();
- doReturn(mSignalStrength).when(mSecondPhone).getSignalStrength();
doReturn(mSecondServiceStateTracker).when(mSecondPhone).getServiceStateTracker();
doReturn(mSecondServiceState).when(mSecondServiceStateTracker).getServiceState();
@@ -162,7 +163,6 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
doReturn(new UiccSlot[] {mPhysicalSlot}).when(mUiccController).getUiccSlots();
doReturn(mPhysicalSlot).when(mUiccController).getUiccSlot(eq(0));
- doReturn(mPhysicalSlot).when(mUiccController).getUiccSlotForPhone(eq(0));
doReturn(0).when(mUiccController).getSlotIdFromPhoneId(0);
doReturn(1).when(mUiccController).getSlotIdFromPhoneId(1);
@@ -176,9 +176,17 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
doReturn(PhoneConstants.PHONE_TYPE_GSM).when(mGsmConnection1).getPhoneType();
doReturn(false).when(mGsmConnection1).isEmergencyCall();
+ mSubInfos = List.of(mSubInfo0, mSubInfo1);
+ doReturn(0).when(mSubInfo0).getSimSlotIndex();
+ doReturn(CARRIER_ID_SLOT_0).when(mSubInfo0).getCarrierId();
+ doReturn(1).when(mSubInfo1).getSimSlotIndex();
+ doReturn(CARRIER_ID_SLOT_1).when(mSubInfo1).getCarrierId();
+
mVoiceCallSessionStats0 = new TestableVoiceCallSessionStats(0, mPhone);
+ mVoiceCallSessionStats0.onActiveSubscriptionInfoChanged(mSubInfos);
mVoiceCallSessionStats0.onServiceStateChanged(mServiceState);
mVoiceCallSessionStats1 = new TestableVoiceCallSessionStats(1, mSecondPhone);
+ mVoiceCallSessionStats1.onActiveSubscriptionInfoChanged(mSubInfos);
mVoiceCallSessionStats1.onServiceStateChanged(mSecondServiceState);
}
@@ -202,18 +210,13 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_LTE,
ImsReasonInfo.CODE_REMOTE_CALL_DECLINE);
expectedCall.setupDuration =
- VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_EXTREMELY_FAST;
- expectedCall.setupDurationMillis = 200;
+ VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_VERY_FAST;
expectedCall.setupFailed = true;
- expectedCall.ratAtConnected = TelephonyManager.NETWORK_TYPE_UNKNOWN;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_EVS_SWB;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_SUPER_WIDEBAND;
- expectedCall.ratAtConnected = TelephonyManager.NETWORK_TYPE_UNKNOWN;
- VoiceCallRatUsage expectedRatUsage =
+ RawVoiceCallRatUsage expectedRatUsage =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_LTE, 2000L, 12000L, 1L);
- final AtomicReference<VoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
+ final AtomicReference<RawVoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
mVoiceCallSessionStats0.setTimeMillis(2000L);
doReturn(Call.State.DIALING).when(mImsCall0).getState();
@@ -255,11 +258,10 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_LTE,
ImsReasonInfo.CODE_SIP_FORBIDDEN);
expectedCall.setupFailed = true;
- expectedCall.ratAtConnected = TelephonyManager.NETWORK_TYPE_UNKNOWN;
- VoiceCallRatUsage expectedRatUsage =
+ RawVoiceCallRatUsage expectedRatUsage =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_LTE, 2000L, 2200L, 1L);
- final AtomicReference<VoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
+ final AtomicReference<RawVoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
mVoiceCallSessionStats0.setTimeMillis(2000L);
doReturn(Call.State.DIALING).when(mImsCall0).getState();
@@ -294,17 +296,14 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_LTE,
ImsReasonInfo.CODE_USER_TERMINATED_BY_REMOTE);
expectedCall.setupDuration =
- VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_EXTREMELY_FAST;
- expectedCall.setupDurationMillis = 200;
+ VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_VERY_FAST;
expectedCall.setupFailed = false;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_EVS_SWB;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_SUPER_WIDEBAND;
expectedCall.disconnectExtraMessage = "normal call clearing";
- VoiceCallRatUsage expectedRatUsage =
+ RawVoiceCallRatUsage expectedRatUsage =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_LTE, 2000L, 100000L, 1L);
- final AtomicReference<VoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
+ final AtomicReference<RawVoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
mVoiceCallSessionStats0.setTimeMillis(2000L);
doReturn(Call.State.DIALING).when(mImsCall0).getState();
@@ -352,14 +351,11 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_LTE,
ImsReasonInfo.CODE_LOCAL_CALL_DECLINE);
expectedCall.setupFailed = true;
- expectedCall.ratAtConnected = TelephonyManager.NETWORK_TYPE_UNKNOWN;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
- VoiceCallRatUsage expectedRatUsage =
+ RawVoiceCallRatUsage expectedRatUsage =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_LTE, 2000L, 8000L, 1L);
- final AtomicReference<VoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
+ final AtomicReference<RawVoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
mVoiceCallSessionStats0.setTimeMillis(2000L);
doReturn(Call.State.INCOMING).when(mImsCall0).getState();
@@ -397,16 +393,13 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_LTE,
ImsReasonInfo.CODE_USER_TERMINATED);
expectedCall.setupDuration =
- VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_EXTREMELY_FAST;
- expectedCall.setupDurationMillis = 80;
+ VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_ULTRA_FAST;
expectedCall.setupFailed = false;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
- VoiceCallRatUsage expectedRatUsage =
+ RawVoiceCallRatUsage expectedRatUsage =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_LTE, 2000L, 12000L, 1L);
- final AtomicReference<VoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
+ final AtomicReference<RawVoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
mVoiceCallSessionStats0.setTimeMillis(2000L);
doReturn(Call.State.INCOMING).when(mImsCall0).getState();
@@ -441,7 +434,6 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
doReturn(mInactiveCard).when(mEsimSlot).getUiccCard();
doReturn(new UiccSlot[] {mPhysicalSlot, mEsimSlot}).when(mUiccController).getUiccSlots();
doReturn(mEsimSlot).when(mUiccController).getUiccSlot(eq(1));
- doReturn(mEsimSlot).when(mUiccController).getUiccSlotForPhone(eq(1));
doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getVoiceNetworkType();
doReturn(true).when(mImsConnection0).isIncoming();
doReturn(2000L).when(mImsConnection0).getCreateTime();
@@ -454,10 +446,7 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_LTE,
ImsReasonInfo.CODE_LOCAL_CALL_DECLINE);
expectedCall.setupFailed = true;
- expectedCall.ratAtConnected = TelephonyManager.NETWORK_TYPE_UNKNOWN;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
expectedCall.isMultiSim = false; // DSDS with one active SIM profile should not count
mVoiceCallSessionStats0.setTimeMillis(2000L);
@@ -485,7 +474,6 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
doReturn(mActiveCard).when(mEsimSlot).getUiccCard();
doReturn(new UiccSlot[] {mPhysicalSlot, mEsimSlot}).when(mUiccController).getUiccSlots();
doReturn(mEsimSlot).when(mUiccController).getUiccSlot(eq(1));
- doReturn(mEsimSlot).when(mUiccController).getUiccSlotForPhone(eq(1));
doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getVoiceNetworkType();
doReturn(true).when(mImsConnection0).isIncoming();
doReturn(2000L).when(mImsConnection0).getCreateTime();
@@ -498,10 +486,7 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_LTE,
ImsReasonInfo.CODE_LOCAL_CALL_DECLINE);
expectedCall.setupFailed = true;
- expectedCall.ratAtConnected = TelephonyManager.NETWORK_TYPE_UNKNOWN;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
expectedCall.isMultiSim = true;
mVoiceCallSessionStats0.setTimeMillis(2000L);
@@ -529,7 +514,6 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
doReturn(mActiveCard).when(mEsimSlot).getUiccCard();
doReturn(new UiccSlot[] {mPhysicalSlot, mEsimSlot}).when(mUiccController).getUiccSlots();
doReturn(mEsimSlot).when(mUiccController).getUiccSlot(eq(1));
- doReturn(mEsimSlot).when(mUiccController).getUiccSlotForPhone(eq(1));
doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mSecondServiceState).getVoiceNetworkType();
doReturn(true).when(mImsConnection1).isIncoming();
doReturn(2000L).when(mImsConnection1).getCreateTime();
@@ -542,10 +526,7 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_LTE,
ImsReasonInfo.CODE_LOCAL_CALL_DECLINE);
expectedCall.setupFailed = true;
- expectedCall.ratAtConnected = TelephonyManager.NETWORK_TYPE_UNKNOWN;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
mVoiceCallSessionStats1.setTimeMillis(2000L);
doReturn(Call.State.INCOMING).when(mImsCall1).getState();
@@ -582,10 +563,7 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_LTE,
ImsReasonInfo.CODE_LOCAL_CALL_DECLINE);
expectedCall.setupFailed = true;
- expectedCall.ratAtConnected = TelephonyManager.NETWORK_TYPE_UNKNOWN;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
expectedCall.isEmergency = true;
mVoiceCallSessionStats0.setTimeMillis(2000L);
@@ -623,10 +601,7 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_LTE,
ImsReasonInfo.CODE_LOCAL_CALL_DECLINE);
expectedCall.setupFailed = true;
- expectedCall.ratAtConnected = TelephonyManager.NETWORK_TYPE_UNKNOWN;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
expectedCall.isRoaming = true;
mVoiceCallSessionStats0.setTimeMillis(2000L);
@@ -663,13 +638,10 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_LTE,
ImsReasonInfo.CODE_USER_TERMINATED);
expectedCall.setupDuration =
- VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_EXTREMELY_FAST;
- expectedCall.setupDurationMillis = 80;
+ VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_ULTRA_FAST;
expectedCall.setupFailed = false;
expectedCall.codecBitmask =
1L << AudioCodec.AUDIO_CODEC_AMR | 1L << AudioCodec.AUDIO_CODEC_EVS_SWB;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
mVoiceCallSessionStats0.setTimeMillis(2000L);
doReturn(Call.State.INCOMING).when(mImsCall0).getState();
@@ -714,25 +686,21 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_LTE,
ImsReasonInfo.CODE_USER_TERMINATED);
expectedCall.setupDuration =
- VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_EXTREMELY_FAST;
- expectedCall.setupDurationMillis = 80;
+ VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_ULTRA_FAST;
expectedCall.setupFailed = false;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
expectedCall.ratSwitchCount = 2L;
expectedCall.ratAtEnd = TelephonyManager.NETWORK_TYPE_UMTS;
- expectedCall.bandAtEnd = 0;
- VoiceCallRatUsage expectedRatUsageLte =
+ RawVoiceCallRatUsage expectedRatUsageLte =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_LTE, 2000L, 4000L, 1L);
- VoiceCallRatUsage expectedRatUsageHspa =
+ RawVoiceCallRatUsage expectedRatUsageHspa =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_HSPA, 4000L, 6000L, 1L);
- VoiceCallRatUsage expectedRatUsageUmts =
+ RawVoiceCallRatUsage expectedRatUsageUmts =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_UMTS, 6000L, 8000L, 1L);
- final AtomicReference<VoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
+ final AtomicReference<RawVoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
mVoiceCallSessionStats0.setTimeMillis(2000L);
doReturn(Call.State.INCOMING).when(mImsCall0).getState();
@@ -764,7 +732,7 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
verifyNoMoreInteractions(mPersistAtomsStorage);
assertProtoEquals(expectedCall, callCaptor.getValue());
assertSortedProtoArrayEquals(
- new VoiceCallRatUsage[] {
+ new RawVoiceCallRatUsage[] {
expectedRatUsageLte, expectedRatUsageHspa, expectedRatUsageUmts
},
ratUsage.get());
@@ -786,10 +754,7 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_LTE,
ImsReasonInfo.CODE_LOCAL_CALL_DECLINE);
expectedCall.setupFailed = true;
- expectedCall.ratAtConnected = TelephonyManager.NETWORK_TYPE_UNKNOWN;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
expectedCall.rttEnabled = true;
mVoiceCallSessionStats0.setTimeMillis(2000L);
@@ -826,12 +791,9 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_LTE,
ImsReasonInfo.CODE_USER_TERMINATED);
expectedCall.setupDuration =
- VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_EXTREMELY_FAST;
- expectedCall.setupDurationMillis = 80;
+ VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_ULTRA_FAST;
expectedCall.setupFailed = false;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
expectedCall.rttEnabled = true;
mVoiceCallSessionStats0.setTimeMillis(2000L);
@@ -877,17 +839,13 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_LTE,
ImsReasonInfo.CODE_USER_TERMINATED_BY_REMOTE);
expectedCall0.setupDuration =
- VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_EXTREMELY_FAST;
- expectedCall0.setupDurationMillis = 80;
+ VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_ULTRA_FAST;
expectedCall0.setupFailed = false;
expectedCall0.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall0.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
expectedCall0.concurrentCallCountAtStart = 0;
expectedCall0.concurrentCallCountAtEnd = 1;
expectedCall0.ratSwitchCount = 1L;
expectedCall0.ratAtEnd = TelephonyManager.NETWORK_TYPE_HSPA;
- expectedCall0.bandAtEnd = 0;
// call 1 starts later, MT
doReturn(true).when(mImsConnection1).isIncoming();
doReturn(60000L).when(mImsConnection1).getCreateTime();
@@ -901,30 +859,26 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
ImsReasonInfo.CODE_USER_TERMINATED);
expectedCall1.setupDuration =
VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_EXTREMELY_FAST;
- expectedCall1.setupDurationMillis = 20;
expectedCall1.setupFailed = false;
expectedCall1.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall1.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
expectedCall1.concurrentCallCountAtStart = 1;
expectedCall1.concurrentCallCountAtEnd = 0;
expectedCall1.ratSwitchCount = 2L;
expectedCall1.ratAtEnd = TelephonyManager.NETWORK_TYPE_UMTS;
- expectedCall1.bandAtEnd = 0;
- VoiceCallRatUsage expectedRatUsageLte =
+ RawVoiceCallRatUsage expectedRatUsageLte =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_LTE, 2000L, 80000L, 2L);
- VoiceCallRatUsage expectedRatUsageHspa =
+ RawVoiceCallRatUsage expectedRatUsageHspa =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_HSPA, 80000L, 100000L, 2L);
- VoiceCallRatUsage expectedRatUsageUmts =
+ RawVoiceCallRatUsage expectedRatUsageUmts =
makeRatUsageProto(
CARRIER_ID_SLOT_0,
TelephonyManager.NETWORK_TYPE_UMTS,
100000L,
120000L,
1L);
- final AtomicReference<VoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
+ final AtomicReference<RawVoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
// call 0 dial
mVoiceCallSessionStats0.setTimeMillis(2000L);
@@ -983,7 +937,7 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
new VoiceCallSession[] {expectedCall0, expectedCall1},
callCaptor.getAllValues().stream().toArray(VoiceCallSession[]::new));
assertSortedProtoArrayEquals(
- new VoiceCallRatUsage[] {
+ new RawVoiceCallRatUsage[] {
expectedRatUsageLte, expectedRatUsageHspa, expectedRatUsageUmts
},
ratUsage.get());
@@ -1005,17 +959,13 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_LTE,
ImsReasonInfo.CODE_USER_TERMINATED);
expectedCall0.setupDuration =
- VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_EXTREMELY_FAST;
- expectedCall0.setupDurationMillis = 80;
+ VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_ULTRA_FAST;
expectedCall0.setupFailed = false;
expectedCall0.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall0.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
expectedCall0.concurrentCallCountAtStart = 0;
expectedCall0.concurrentCallCountAtEnd = 0;
expectedCall0.ratSwitchCount = 2L;
expectedCall0.ratAtEnd = TelephonyManager.NETWORK_TYPE_UMTS;
- expectedCall0.bandAtEnd = 0;
// call 1 starts later, MT
doReturn(true).when(mImsConnection1).isIncoming();
doReturn(60000L).when(mImsConnection1).getCreateTime();
@@ -1029,30 +979,26 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
ImsReasonInfo.CODE_USER_TERMINATED_BY_REMOTE);
expectedCall1.setupDuration =
VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_EXTREMELY_FAST;
- expectedCall1.setupDurationMillis = 20;
expectedCall1.setupFailed = false;
expectedCall1.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall1.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
expectedCall1.concurrentCallCountAtStart = 1;
expectedCall1.concurrentCallCountAtEnd = 1;
expectedCall1.ratSwitchCount = 1L;
expectedCall1.ratAtEnd = TelephonyManager.NETWORK_TYPE_HSPA;
- expectedCall1.bandAtEnd = 0;
- VoiceCallRatUsage expectedRatUsageLte =
+ RawVoiceCallRatUsage expectedRatUsageLte =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_LTE, 2000L, 80000L, 2L);
- VoiceCallRatUsage expectedRatUsageHspa =
+ RawVoiceCallRatUsage expectedRatUsageHspa =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_HSPA, 80000L, 100000L, 2L);
- VoiceCallRatUsage expectedRatUsageUmts =
+ RawVoiceCallRatUsage expectedRatUsageUmts =
makeRatUsageProto(
CARRIER_ID_SLOT_0,
TelephonyManager.NETWORK_TYPE_UMTS,
100000L,
120000L,
1L);
- final AtomicReference<VoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
+ final AtomicReference<RawVoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
// call 0 dial
mVoiceCallSessionStats0.setTimeMillis(2000L);
@@ -1111,7 +1057,7 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
new VoiceCallSession[] {expectedCall0, expectedCall1},
callCaptor.getAllValues().stream().toArray(VoiceCallSession[]::new));
assertSortedProtoArrayEquals(
- new VoiceCallRatUsage[] {
+ new RawVoiceCallRatUsage[] {
expectedRatUsageLte, expectedRatUsageHspa, expectedRatUsageUmts
},
ratUsage.get());
@@ -1133,12 +1079,9 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_LTE,
ImsReasonInfo.CODE_USER_TERMINATED);
expectedCall0.setupDuration =
- VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_EXTREMELY_FAST;
- expectedCall0.setupDurationMillis = 80;
+ VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_ULTRA_FAST;
expectedCall0.setupFailed = false;
expectedCall0.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall0.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
expectedCall0.concurrentCallCountAtStart = 0;
expectedCall0.concurrentCallCountAtEnd = 1;
expectedCall0.ratSwitchCount = 0L;
@@ -1156,23 +1099,19 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
ImsReasonInfo.CODE_USER_TERMINATED_BY_REMOTE);
expectedCall1.setupDuration =
VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_EXTREMELY_FAST;
- expectedCall1.setupDurationMillis = 20;
expectedCall1.setupFailed = false;
expectedCall1.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall1.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
expectedCall1.concurrentCallCountAtStart = 1;
expectedCall1.concurrentCallCountAtEnd = 0;
expectedCall1.ratSwitchCount = 1L;
expectedCall1.ratAtEnd = TelephonyManager.NETWORK_TYPE_HSPA;
- expectedCall1.bandAtEnd = 0;
- VoiceCallRatUsage expectedRatUsageLte =
+ RawVoiceCallRatUsage expectedRatUsageLte =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_LTE, 2000L, 80000L, 2L);
- VoiceCallRatUsage expectedRatUsageHspa =
+ RawVoiceCallRatUsage expectedRatUsageHspa =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_HSPA, 80000L, 90000L, 1L);
- final AtomicReference<VoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
+ final AtomicReference<RawVoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
// call 0 dial
mVoiceCallSessionStats0.setTimeMillis(2000L);
@@ -1227,7 +1166,7 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
new VoiceCallSession[] {expectedCall0, expectedCall1},
callCaptor.getAllValues().stream().toArray(VoiceCallSession[]::new));
assertSortedProtoArrayEquals(
- new VoiceCallRatUsage[] {expectedRatUsageLte, expectedRatUsageHspa},
+ new RawVoiceCallRatUsage[] {expectedRatUsageLte, expectedRatUsageHspa},
ratUsage.get());
}
@@ -1244,24 +1183,19 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_LTE,
DisconnectCause.NORMAL);
expectedCall.ratAtEnd = TelephonyManager.NETWORK_TYPE_UMTS;
- expectedCall.bandAtEnd = 0;
expectedCall.setupDuration =
VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_VERY_SLOW;
- expectedCall.setupDurationMillis = 5000;
expectedCall.disconnectExtraCode = PreciseDisconnectCause.CALL_REJECTED;
expectedCall.ratSwitchCount = 1L;
expectedCall.setupFailed = true;
- expectedCall.ratAtConnected = TelephonyManager.NETWORK_TYPE_UNKNOWN;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
- VoiceCallRatUsage expectedRatUsageLte =
+ RawVoiceCallRatUsage expectedRatUsageLte =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_LTE, 2000L, 3000L, 1L);
- VoiceCallRatUsage expectedRatUsageUmts =
+ RawVoiceCallRatUsage expectedRatUsageUmts =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_UMTS, 3000L, 15000L, 1L);
- final AtomicReference<VoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
+ final AtomicReference<RawVoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
mVoiceCallSessionStats0.setTimeMillis(2000L);
doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getVoiceNetworkType();
@@ -1292,7 +1226,7 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
verifyNoMoreInteractions(mPersistAtomsStorage);
assertProtoEquals(expectedCall, callCaptor.getValue());
assertSortedProtoArrayEquals(
- new VoiceCallRatUsage[] {expectedRatUsageLte, expectedRatUsageUmts},
+ new RawVoiceCallRatUsage[] {expectedRatUsageLte, expectedRatUsageUmts},
ratUsage.get());
}
@@ -1309,20 +1243,16 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_LTE,
DisconnectCause.LOST_SIGNAL);
expectedCall.ratAtEnd = TelephonyManager.NETWORK_TYPE_UMTS;
- expectedCall.bandAtEnd = 0;
expectedCall.ratSwitchCount = 1L;
expectedCall.setupFailed = true;
- expectedCall.ratAtConnected = TelephonyManager.NETWORK_TYPE_UNKNOWN;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
- VoiceCallRatUsage expectedRatUsageLte =
+ RawVoiceCallRatUsage expectedRatUsageLte =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_LTE, 2000L, 3000L, 1L);
- VoiceCallRatUsage expectedRatUsageUmts =
+ RawVoiceCallRatUsage expectedRatUsageUmts =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_UMTS, 3000L, 15000L, 1L);
- final AtomicReference<VoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
+ final AtomicReference<RawVoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
mVoiceCallSessionStats0.setTimeMillis(2000L);
doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getVoiceNetworkType();
@@ -1346,7 +1276,7 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
verifyNoMoreInteractions(mPersistAtomsStorage);
assertProtoEquals(expectedCall, callCaptor.getValue());
assertSortedProtoArrayEquals(
- new VoiceCallRatUsage[] {expectedRatUsageLte, expectedRatUsageUmts},
+ new RawVoiceCallRatUsage[] {expectedRatUsageLte, expectedRatUsageUmts},
ratUsage.get());
}
@@ -1362,25 +1292,20 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
VOICE_CALL_SESSION__DIRECTION__CALL_DIRECTION_MO,
TelephonyManager.NETWORK_TYPE_LTE,
DisconnectCause.NORMAL);
- expectedCall.ratAtConnected = TelephonyManager.NETWORK_TYPE_UMTS;
expectedCall.ratAtEnd = TelephonyManager.NETWORK_TYPE_UMTS;
- expectedCall.bandAtEnd = 0;
expectedCall.setupDuration =
VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_VERY_SLOW;
- expectedCall.setupDurationMillis = 5000;
expectedCall.disconnectExtraCode = PreciseDisconnectCause.NORMAL;
expectedCall.ratSwitchCount = 1L;
expectedCall.setupFailed = false;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
- VoiceCallRatUsage expectedRatUsageLte =
+ RawVoiceCallRatUsage expectedRatUsageLte =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_LTE, 2000L, 3000L, 1L);
- VoiceCallRatUsage expectedRatUsageUmts =
+ RawVoiceCallRatUsage expectedRatUsageUmts =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_UMTS, 3000L, 100000L, 1L);
- final AtomicReference<VoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
+ final AtomicReference<RawVoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
mVoiceCallSessionStats0.setTimeMillis(2000L);
doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mServiceState).getVoiceNetworkType();
@@ -1413,7 +1338,7 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
verifyNoMoreInteractions(mPersistAtomsStorage);
assertProtoEquals(expectedCall, callCaptor.getValue());
assertSortedProtoArrayEquals(
- new VoiceCallRatUsage[] {expectedRatUsageLte, expectedRatUsageUmts},
+ new RawVoiceCallRatUsage[] {expectedRatUsageLte, expectedRatUsageUmts},
ratUsage.get());
}
@@ -1432,18 +1357,13 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
DisconnectCause.NORMAL);
expectedCall.setupDuration =
VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_UNKNOWN;
- expectedCall.setupDurationMillis = 0;
expectedCall.disconnectExtraCode = PreciseDisconnectCause.CALL_REJECTED;
expectedCall.setupFailed = true;
- expectedCall.ratAtConnected = TelephonyManager.NETWORK_TYPE_UNKNOWN;
- expectedCall.bandAtEnd = 0;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
- VoiceCallRatUsage expectedRatUsage =
+ RawVoiceCallRatUsage expectedRatUsage =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_UMTS, 2500L, 15000L, 1L);
- final AtomicReference<VoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
+ final AtomicReference<RawVoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
mVoiceCallSessionStats0.setTimeMillis(2000L);
mVoiceCallSessionStats0.onServiceStateChanged(mServiceState);
@@ -1484,19 +1404,14 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
VOICE_CALL_SESSION__DIRECTION__CALL_DIRECTION_MT,
TelephonyManager.NETWORK_TYPE_UMTS,
DisconnectCause.NORMAL);
- expectedCall.setupDuration =
- VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_ULTRA_FAST;
- expectedCall.setupDurationMillis = 500;
+ expectedCall.setupDuration = VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_FAST;
expectedCall.disconnectExtraCode = PreciseDisconnectCause.NORMAL;
expectedCall.setupFailed = false;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
- expectedCall.bandAtEnd = 0;
- VoiceCallRatUsage expectedRatUsage =
+ RawVoiceCallRatUsage expectedRatUsage =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_UMTS, 2500L, 100000L, 1L);
- final AtomicReference<VoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
+ final AtomicReference<RawVoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
mVoiceCallSessionStats0.setTimeMillis(2000L);
mVoiceCallSessionStats0.onServiceStateChanged(mServiceState);
@@ -1545,23 +1460,19 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_LTE,
ImsReasonInfo.CODE_LOCAL_HO_NOT_FEASIBLE);
expectedCall.setupDuration =
- VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_EXTREMELY_FAST;
- expectedCall.setupDurationMillis = 80;
+ VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_ULTRA_FAST;
expectedCall.setupFailed = false;
expectedCall.srvccFailureCount = 2L;
expectedCall.ratSwitchCount = 1L;
expectedCall.ratAtEnd = TelephonyManager.NETWORK_TYPE_UMTS;
- expectedCall.bandAtEnd = 0;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
- VoiceCallRatUsage expectedRatUsageLte =
+ RawVoiceCallRatUsage expectedRatUsageLte =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_LTE, 2000L, 10000L, 1L);
- VoiceCallRatUsage expectedRatUsageUmts =
+ RawVoiceCallRatUsage expectedRatUsageUmts =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_UMTS, 10000L, 12000L, 1L);
- final AtomicReference<VoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
+ final AtomicReference<RawVoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
mVoiceCallSessionStats0.setTimeMillis(2000L);
doReturn(Call.State.INCOMING).when(mImsCall0).getState();
@@ -1602,7 +1513,7 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
verifyNoMoreInteractions(mPersistAtomsStorage);
assertProtoEquals(expectedCall, callCaptor.getValue());
assertSortedProtoArrayEquals(
- new VoiceCallRatUsage[] {expectedRatUsageLte, expectedRatUsageUmts},
+ new RawVoiceCallRatUsage[] {expectedRatUsageLte, expectedRatUsageUmts},
ratUsage.get());
}
@@ -1623,17 +1534,14 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_LTE,
ImsReasonInfo.CODE_USER_TERMINATED);
expectedCall.setupDuration =
- VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_EXTREMELY_FAST;
- expectedCall.setupDurationMillis = 80;
+ VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_ULTRA_FAST;
expectedCall.setupFailed = false;
expectedCall.srvccCancellationCount = 2L;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
- VoiceCallRatUsage expectedRatUsage =
+ RawVoiceCallRatUsage expectedRatUsage =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_LTE, 2000L, 12000L, 1L);
- final AtomicReference<VoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
+ final AtomicReference<RawVoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
mVoiceCallSessionStats0.setTimeMillis(2000L);
doReturn(Call.State.INCOMING).when(mImsCall0).getState();
@@ -1694,8 +1602,7 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
DisconnectCause.NORMAL);
expectedCall.disconnectExtraCode = PreciseDisconnectCause.NORMAL;
expectedCall.setupDuration =
- VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_EXTREMELY_FAST;
- expectedCall.setupDurationMillis = 80;
+ VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_ULTRA_FAST;
expectedCall.setupFailed = false;
expectedCall.srvccCancellationCount = 1L;
expectedCall.srvccFailureCount = 1L;
@@ -1703,17 +1610,14 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
expectedCall.bearerAtEnd = VOICE_CALL_SESSION__BEARER_AT_END__CALL_BEARER_CS;
expectedCall.ratSwitchCount = 1L;
expectedCall.ratAtEnd = TelephonyManager.NETWORK_TYPE_UMTS;
- expectedCall.bandAtEnd = 0;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
- VoiceCallRatUsage expectedRatUsageLte =
+ RawVoiceCallRatUsage expectedRatUsageLte =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_LTE, 2000L, 7000L, 1L);
- VoiceCallRatUsage expectedRatUsageUmts =
+ RawVoiceCallRatUsage expectedRatUsageUmts =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_UMTS, 7000L, 12000L, 1L);
- final AtomicReference<VoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
+ final AtomicReference<RawVoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
// IMS call created
mVoiceCallSessionStats0.setTimeMillis(2000L);
@@ -1763,7 +1667,7 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
verifyNoMoreInteractions(mPersistAtomsStorage);
assertProtoEquals(expectedCall, callCaptor.getValue());
assertSortedProtoArrayEquals(
- new VoiceCallRatUsage[] {expectedRatUsageLte, expectedRatUsageUmts},
+ new RawVoiceCallRatUsage[] {expectedRatUsageLte, expectedRatUsageUmts},
ratUsage.get());
}
@@ -1789,17 +1693,13 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
DisconnectCause.NORMAL);
expectedCall0.disconnectExtraCode = PreciseDisconnectCause.NORMAL;
expectedCall0.setupDuration =
- VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_EXTREMELY_FAST;
- expectedCall0.setupDurationMillis = 80;
+ VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_ULTRA_FAST;
expectedCall0.setupFailed = false;
expectedCall0.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall0.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
expectedCall0.concurrentCallCountAtStart = 0;
expectedCall0.concurrentCallCountAtEnd = 1;
expectedCall0.ratSwitchCount = 1L;
expectedCall0.ratAtEnd = TelephonyManager.NETWORK_TYPE_UMTS;
- expectedCall0.bandAtEnd = 0;
expectedCall0.srvccCompleted = true;
expectedCall0.bearerAtEnd = VOICE_CALL_SESSION__BEARER_AT_END__CALL_BEARER_CS;
// call 1 starts later, MT
@@ -1818,25 +1718,21 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
expectedCall1.disconnectExtraCode = PreciseDisconnectCause.NORMAL;
expectedCall1.setupDuration =
VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_EXTREMELY_FAST;
- expectedCall1.setupDurationMillis = 20;
expectedCall1.setupFailed = false;
expectedCall1.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall1.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
expectedCall1.concurrentCallCountAtStart = 1;
expectedCall1.concurrentCallCountAtEnd = 0;
expectedCall1.ratSwitchCount = 1L;
expectedCall1.ratAtEnd = TelephonyManager.NETWORK_TYPE_UMTS;
- expectedCall1.bandAtEnd = 0;
expectedCall1.srvccCompleted = true;
expectedCall1.bearerAtEnd = VOICE_CALL_SESSION__BEARER_AT_END__CALL_BEARER_CS;
- VoiceCallRatUsage expectedRatUsageLte =
+ RawVoiceCallRatUsage expectedRatUsageLte =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_LTE, 2000L, 80000L, 2L);
- VoiceCallRatUsage expectedRatUsageUmts =
+ RawVoiceCallRatUsage expectedRatUsageUmts =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_UMTS, 80000L, 120000L, 2L);
- final AtomicReference<VoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
+ final AtomicReference<RawVoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
// call 0 dial
mVoiceCallSessionStats0.setTimeMillis(2000L);
@@ -1899,7 +1795,7 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
new VoiceCallSession[] {expectedCall0, expectedCall1},
callCaptor.getAllValues().stream().toArray(VoiceCallSession[]::new));
assertSortedProtoArrayEquals(
- new VoiceCallRatUsage[] {expectedRatUsageLte, expectedRatUsageUmts},
+ new RawVoiceCallRatUsage[] {expectedRatUsageLte, expectedRatUsageUmts},
ratUsage.get());
}
@@ -1921,15 +1817,11 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_IWLAN,
ImsReasonInfo.CODE_LOCAL_CALL_DECLINE);
expectedCall.setupFailed = true;
- expectedCall.ratAtConnected = TelephonyManager.NETWORK_TYPE_UNKNOWN;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
- expectedCall.bandAtEnd = 0;
- VoiceCallRatUsage expectedRatUsage =
+ RawVoiceCallRatUsage expectedRatUsage =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_IWLAN, 2000L, 8000L, 1L);
- final AtomicReference<VoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
+ final AtomicReference<RawVoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
mVoiceCallSessionStats0.setTimeMillis(2000L);
doReturn(Call.State.INCOMING).when(mImsCall0).getState();
@@ -1970,15 +1862,11 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
TelephonyManager.NETWORK_TYPE_IWLAN,
ImsReasonInfo.CODE_LOCAL_CALL_DECLINE);
expectedCall.setupFailed = true;
- expectedCall.ratAtConnected = TelephonyManager.NETWORK_TYPE_UNKNOWN;
- expectedCall.bandAtEnd = 0;
expectedCall.codecBitmask = 1L << AudioCodec.AUDIO_CODEC_AMR;
- expectedCall.mainCodecQuality =
- VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_NARROWBAND;
- VoiceCallRatUsage expectedRatUsage =
+ RawVoiceCallRatUsage expectedRatUsage =
makeRatUsageProto(
CARRIER_ID_SLOT_0, TelephonyManager.NETWORK_TYPE_IWLAN, 2000L, 8000L, 1L);
- final AtomicReference<VoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
+ final AtomicReference<RawVoiceCallRatUsage[]> ratUsage = setupRatUsageCapture();
mVoiceCallSessionStats0.setTimeMillis(2000L);
doReturn(Call.State.INCOMING).when(mImsCall0).getState();
@@ -2001,8 +1889,8 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
assertProtoEquals(expectedRatUsage, ratUsage.get()[0]);
}
- private AtomicReference<VoiceCallRatUsage[]> setupRatUsageCapture() {
- final AtomicReference<VoiceCallRatUsage[]> ratUsage = new AtomicReference<>(null);
+ private AtomicReference<RawVoiceCallRatUsage[]> setupRatUsageCapture() {
+ final AtomicReference<RawVoiceCallRatUsage[]> ratUsage = new AtomicReference<>(null);
doAnswer(invocation -> {
VoiceCallRatTracker tracker = (VoiceCallRatTracker) invocation.getArguments()[0];
ratUsage.set(tracker.toProto());
@@ -2018,18 +1906,14 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
call.bearerAtEnd = bearer;
call.direction = direction;
call.setupDuration = VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_UNKNOWN;
- call.setupDurationMillis = 0;
call.setupFailed = true;
call.disconnectReasonCode = reason;
call.disconnectExtraCode = 0;
call.disconnectExtraMessage = "";
call.ratAtStart = rat;
- call.ratAtConnected = rat;
call.ratAtEnd = rat;
- call.bandAtEnd = 1;
call.ratSwitchCount = 0L;
call.codecBitmask = 0L;
- call.mainCodecQuality = VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_UNKNOWN;
call.simSlotIndex = 0;
call.isMultiSim = false;
call.isEsim = false;
@@ -2041,7 +1925,6 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
call.isEmergency = false;
call.isRoaming = false;
call.setupBeginMillis = 0L;
- call.signalStrengthAtEnd = 2;
return call;
}
@@ -2052,18 +1935,14 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
call.bearerAtEnd = bearer;
call.direction = direction;
call.setupDuration = VOICE_CALL_SESSION__SETUP_DURATION__CALL_SETUP_DURATION_UNKNOWN;
- call.setupDurationMillis = 0;
call.setupFailed = true;
call.disconnectReasonCode = reason;
call.disconnectExtraCode = 0;
call.disconnectExtraMessage = "";
call.ratAtStart = rat;
- call.ratAtConnected = rat;
call.ratAtEnd = rat;
- call.bandAtEnd = 1;
call.ratSwitchCount = 0L;
call.codecBitmask = 0L;
- call.mainCodecQuality = VOICE_CALL_SESSION__MAIN_CODEC_QUALITY__CODEC_QUALITY_UNKNOWN;
call.simSlotIndex = 1;
call.isMultiSim = true;
call.isEsim = true;
@@ -2075,13 +1954,12 @@ public class VoiceCallSessionStatsTest extends TelephonyTest {
call.isEmergency = false;
call.isRoaming = false;
call.setupBeginMillis = 0L;
- call.signalStrengthAtEnd = 2;
return call;
}
- private static VoiceCallRatUsage makeRatUsageProto(
+ private static RawVoiceCallRatUsage makeRatUsageProto(
int carrierId, int rat, long beginMillis, long endMillis, long callCount) {
- VoiceCallRatUsage usage = new VoiceCallRatUsage();
+ RawVoiceCallRatUsage usage = new RawVoiceCallRatUsage();
usage.carrierId = carrierId;
usage.rat = rat;
usage.totalDurationMillis = endMillis - beginMillis;
diff --git a/tests/telephonytests/src/com/android/internal/telephony/nitz/NitzStateMachineImplTest.java b/tests/telephonytests/src/com/android/internal/telephony/nitz/NitzStateMachineImplTest.java
index c433bd0dcb..19d57f92a3 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/nitz/NitzStateMachineImplTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/nitz/NitzStateMachineImplTest.java
@@ -621,7 +621,7 @@ public class NitzStateMachineImplTest extends TelephonyTest {
void commitLatest() {
if (hasBeenSet()) {
- mInitialValue = mValues.getFirst();
+ mInitialValue = mValues.getLast();
mValues.clear();
}
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/nitz/TimeZoneLookupHelperTest.java b/tests/telephonytests/src/com/android/internal/telephony/nitz/TimeZoneLookupHelperTest.java
index 990f568695..af1be4cafc 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/nitz/TimeZoneLookupHelperTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/nitz/TimeZoneLookupHelperTest.java
@@ -24,7 +24,6 @@ import static com.android.internal.telephony.nitz.TimeZoneLookupHelper.CountryRe
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@@ -38,10 +37,8 @@ import com.android.internal.telephony.nitz.TimeZoneLookupHelper.CountryResult;
import org.junit.Before;
import org.junit.Test;
-import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
-import java.util.List;
import java.util.concurrent.TimeUnit;
public class TimeZoneLookupHelperTest {
@@ -450,18 +447,6 @@ public class TimeZoneLookupHelperTest {
assertTrue(mTimeZoneLookupHelper.countryUsesUtc("gb", NH_WINTER_TIME_MILLIS));
}
- @Test
- public void regressionTest_Bug167653885() {
- // This NITZ caused an error in Android R because lookupByNitz was returning a time zone
- // known to android.icu.util.TimeZone but not java.util.TimeZone.
- NitzData nitzData = NitzData.parse("20/05/08,04:15:48+08,00");
- OffsetResult offsetResult = mTimeZoneLookupHelper.lookupByNitz(nitzData);
- assertNotNull(offsetResult);
-
- List<String> knownIds = Arrays.asList(java.util.TimeZone.getAvailableIDs());
- assertTrue(knownIds.contains(offsetResult.getTimeZone().getID()));
- }
-
/**
* Assert the time zone in the OffsetResult has the expected properties at the specified time.
*/
diff --git a/tests/telephonytests/src/com/android/internal/telephony/uicc/IccPhoneBookInterfaceManagerTest.java b/tests/telephonytests/src/com/android/internal/telephony/uicc/IccPhoneBookInterfaceManagerTest.java
index 47ebc67ee0..72ff321057 100755..100644
--- a/tests/telephonytests/src/com/android/internal/telephony/uicc/IccPhoneBookInterfaceManagerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/uicc/IccPhoneBookInterfaceManagerTest.java
@@ -15,25 +15,18 @@
*/
package com.android.internal.telephony.uicc;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Mockito.anyInt;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.doReturn;
-
-import android.content.ContentValues;
import android.os.HandlerThread;
import android.os.Message;
import android.os.AsyncResult;
-import android.test.suitebuilder.annotation.SmallTest;
import com.android.internal.telephony.IccPhoneBookInterfaceManager;
-import com.android.internal.telephony.IccProvider;
import com.android.internal.telephony.TelephonyTest;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
+
+import android.test.suitebuilder.annotation.SmallTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -41,6 +34,10 @@ import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.mockito.Mockito.anyInt;
+
import java.util.Arrays;
import java.util.List;
@@ -50,8 +47,6 @@ public class IccPhoneBookInterfaceManagerTest extends TelephonyTest {
private AdnRecordCache mAdnRecordCache;
@Mock
private AdnRecord mAdnRecord;
- @Mock
- private SimPhonebookRecordCache mSimPhonebookRecordCache;
private IccPhoneBookInterfaceManager mIccPhoneBookInterfaceMgr;
private IccPhoneBookInterfaceManagerHandler mIccPhoneBookInterfaceManagerHandler;
private List<AdnRecord> mAdnList = Arrays.asList(mAdnRecord);
@@ -87,19 +82,9 @@ public class IccPhoneBookInterfaceManagerTest extends TelephonyTest {
}
}).when(mAdnRecordCache).requestLoadAllAdnLike(anyInt(), anyInt(), (Message) anyObject());
- doAnswer(invocation -> {
- Message response = (Message) invocation.getArguments()[0];
- //set result for load ADN EF
- AsyncResult.forMessage(response).result = mAdnList;
- response.sendToTarget();
- return null;
- }).when(mSimPhonebookRecordCache).requestLoadAllPbRecords((Message)anyObject());
mIccPhoneBookInterfaceManagerHandler = new IccPhoneBookInterfaceManagerHandler(TAG);
mIccPhoneBookInterfaceManagerHandler.start();
-
waitUntilReady();
- replaceInstance(IccPhoneBookInterfaceManager.class,
- "mSimPbRecordCache", mIccPhoneBookInterfaceMgr, mSimPhonebookRecordCache);
}
@After
@@ -108,11 +93,9 @@ public class IccPhoneBookInterfaceManagerTest extends TelephonyTest {
mIccPhoneBookInterfaceManagerHandler.join();
super.tearDown();
}
-
@Test
@SmallTest
public void testAdnEFLoadWithFailure() {
- doReturn(false).when(mSimPhonebookRecordCache).isEnabled();
List<AdnRecord> adnListResult = mIccPhoneBookInterfaceMgr.getAdnRecordsInEf(
IccConstants.EF_ADN);
assertEquals(mAdnList, adnListResult);
@@ -133,88 +116,4 @@ public class IccPhoneBookInterfaceManagerTest extends TelephonyTest {
//verify the previous read is not got affected
assertEquals(mAdnList, adnListResult);
}
-
- @Test
- @SmallTest
- public void testAdnEFLoadByPbCacheWithFailure() {
- doReturn(true).when(mSimPhonebookRecordCache).isEnabled();
- List<AdnRecord> adnListResult = mIccPhoneBookInterfaceMgr.getAdnRecordsInEf(
- IccConstants.EF_ADN);
- assertEquals(mAdnList, adnListResult);
- //mock a ADN Ef load failure
- doAnswer(invocation -> {
- Message response = (Message) invocation.getArguments()[0];
- AsyncResult.forMessage(response).exception = new RuntimeException();
- response.sendToTarget();
- return null;
- }).when(mSimPhonebookRecordCache).requestLoadAllPbRecords((Message) anyObject());
- List<AdnRecord> adnListResultNew = mIccPhoneBookInterfaceMgr.getAdnRecordsInEf(
- IccConstants.EF_ADN);
- //the later read return null due to exception
- assertNull(adnListResultNew);
- //verify the previous read is not got affected
- assertEquals(mAdnList, adnListResult);
- }
-
- @Test
- @SmallTest
- public void testUpdateAdnRecord() {
- doReturn(false).when(mSimPhonebookRecordCache).isEnabled();
- doAnswer(new Answer<Void>() {
- @Override
- public Void answer(InvocationOnMock invocation) throws Throwable {
- Message response = (Message) invocation.getArguments()[4];
- //set result for update ADN EF
- AsyncResult.forMessage(response).exception = null;
- response.sendToTarget();
- return null;
- }
- }).when(mAdnRecordCache).updateAdnBySearch(
- anyInt(), any(), any(),
- any(), (Message) anyObject());
-
- ContentValues values = new ContentValues();
- values.put(IccProvider.STR_TAG, "");
- values.put(IccProvider.STR_NUMBER, "");
- values.put(IccProvider.STR_EMAILS, "");
- values.put(IccProvider.STR_ANRS, "");
- values.put(IccProvider.STR_NEW_TAG, "test");
- values.put(IccProvider.STR_NEW_NUMBER, "123456");
- values.put(IccProvider.STR_NEW_EMAILS, "");
- values.put(IccProvider.STR_NEW_ANRS, "");
-
- boolean result = mIccPhoneBookInterfaceMgr.updateAdnRecordsInEfBySearchForSubscriber(
- IccConstants.EF_ADN, values , null);
-
- assertTrue(result);
- }
-
- @Test
- @SmallTest
- public void testUpdateAdnRecordByPbCache() {
- doReturn(true).when(mSimPhonebookRecordCache).isEnabled();
- doAnswer(invocation -> {
- Message response = (Message) invocation.getArguments()[2];
- //set result for update ADN EF
- AsyncResult.forMessage(response).exception = null;
- response.sendToTarget();
- return null;
- }).when(mSimPhonebookRecordCache).updateSimPbAdnBySearch(any(),
- any(), (Message) anyObject());
-
- ContentValues values = new ContentValues();
- values.put(IccProvider.STR_TAG, "");
- values.put(IccProvider.STR_NUMBER, "");
- values.put(IccProvider.STR_EMAILS, "");
- values.put(IccProvider.STR_ANRS, "");
- values.put(IccProvider.STR_NEW_TAG, "test");
- values.put(IccProvider.STR_NEW_NUMBER, "123456");
- values.put(IccProvider.STR_NEW_EMAILS, "");
- values.put(IccProvider.STR_NEW_ANRS, "");
-
- boolean result = mIccPhoneBookInterfaceMgr.updateAdnRecordsInEfBySearchForSubscriber(
- IccConstants.EF_ADN, values , "12");
-
- assertTrue(result);
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/uicc/IccRecordsTest.java b/tests/telephonytests/src/com/android/internal/telephony/uicc/IccRecordsTest.java
index 500821b4ff..417c532f53 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/uicc/IccRecordsTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/uicc/IccRecordsTest.java
@@ -48,16 +48,11 @@ import android.util.Log;
import android.util.Pair;
import com.android.internal.telephony.TelephonyTest;
-import com.android.internal.telephony.uicc.IccRecords.OperatorPlmnInfo;
-import com.android.internal.telephony.uicc.IccRecords.PlmnNetworkName;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-import java.util.ArrayList;
-import java.util.List;
-
public class IccRecordsTest extends TelephonyTest {
private IccRecords mIccRecords;
@@ -249,102 +244,4 @@ public class IccRecordsTest extends TelephonyTest {
assertTrue("Two responses must be different.", !response.equals(response2));
}
- @Test
- public void testOperatorPlmnInfo() {
- String plmn = "123456";
- int lacTacStart = 0x0000;
- int lacTacEnd = 0xFFFE;
- int pnnIndex = 2;
-
- OperatorPlmnInfo opi = new OperatorPlmnInfo(plmn, lacTacStart, lacTacEnd, pnnIndex);
- assertEquals(opi.getPnnIdx(plmn, lacTacStart), pnnIndex - 1);
- assertEquals(opi.getPnnIdx(plmn, lacTacEnd), pnnIndex - 1);
- assertEquals(opi.getPnnIdx(plmn, 0xFFFF), pnnIndex - 1);
- assertEquals(opi.getPnnIdx("654321", 0xFFFF), -1);
- assertEquals(opi.getPnnIdx("12345", 0xFFFF), -1);
-
- lacTacStart = 0x0001;
- lacTacEnd = 0x1FFF;
- opi = new OperatorPlmnInfo(plmn, lacTacStart, lacTacEnd, pnnIndex);
- assertEquals(opi.getPnnIdx(plmn, 2), pnnIndex - 1);
- assertEquals(opi.getPnnIdx(plmn, 0x2FFF), -1);
- assertEquals(opi.getPnnIdx(plmn, 0xFFFF), -1);
-
- plmn = "123DDD";
- opi = new OperatorPlmnInfo(plmn, lacTacStart, lacTacEnd, pnnIndex);
- assertEquals(opi.getPnnIdx("123123", lacTacStart), pnnIndex - 1);
- assertEquals(opi.getPnnIdx("12345", lacTacStart), -1);
- }
-
- @Test
- public void testGetNetworkNameForPlmn() {
- // Set up PNN
- String fullName1 = "Name full 1";
- String shortName1 = "Name short 1";
- String fullName2 = "Name full 2";
- String shortName2 = "Name short 2";
- List<PlmnNetworkName> pnns = new ArrayList<PlmnNetworkName>();
- pnns.add(new PlmnNetworkName(fullName1, shortName1));
- pnns.add(new PlmnNetworkName(fullName2, shortName2));
- pnns.add(new PlmnNetworkName(null, shortName2));
- PlmnNetworkName[] pnnsArray = pnns.toArray(new PlmnNetworkName[0]);
-
- // Set up OPL
- String plmn1 = "345678";
- String plmn2 = "456789";
- String plmn3 = "567890";
- int lacTacStart = 0x0000;
- int lacTacEnd = 0xFFFE;
- int pnnIndex = 1;
- List<OperatorPlmnInfo> opl = new ArrayList<OperatorPlmnInfo>();
- opl.add(new OperatorPlmnInfo(plmn1, lacTacStart, lacTacEnd, pnnIndex));
- opl.add(new OperatorPlmnInfo(plmn2, lacTacStart, lacTacEnd, pnnIndex + 1));
- opl.add(new OperatorPlmnInfo(plmn3, lacTacStart, lacTacEnd, pnnIndex + 2));
- OperatorPlmnInfo[] oplArray = opl.toArray(new OperatorPlmnInfo[0]);
-
- // Test
- assertNull(IccRecords.getNetworkNameForPlmnFromPnnOpl(pnnsArray, oplArray, null, 0));
- assertEquals(fullName1, IccRecords.getNetworkNameForPlmnFromPnnOpl(pnnsArray, oplArray,
- plmn1, 0));
- assertEquals(fullName2, IccRecords.getNetworkNameForPlmnFromPnnOpl(pnnsArray, oplArray,
- plmn2, 0));
- assertEquals(shortName2, IccRecords.getNetworkNameForPlmnFromPnnOpl(pnnsArray, oplArray,
- plmn3, 0));
- }
-
- @Test
- public void testGetNetworkNameForPlmnFromPnnOpl() {
- // Set up PNN
- String fullName1 = "Name full 1";
- String shortName1 = "Name short 1";
- String fullName2 = "Name full 2";
- String shortName2 = "Name short 2";
- List<PlmnNetworkName> pnns = new ArrayList<PlmnNetworkName>();
- pnns.add(new PlmnNetworkName(fullName1, shortName1));
- pnns.add(new PlmnNetworkName(fullName2, shortName2));
- pnns.add(new PlmnNetworkName(null, shortName2));
- PlmnNetworkName[] pnnsArray = pnns.toArray(new PlmnNetworkName[0]);
-
- // Set up OPL
- String plmn1 = "345678";
- String plmn2 = "456789";
- String plmn3 = "567890";
- int lacTacStart = 0x0000;
- int lacTacEnd = 0xFFFE;
- int pnnIndex = 1;
- List<OperatorPlmnInfo> opl = new ArrayList<OperatorPlmnInfo>();
- opl.add(new OperatorPlmnInfo(plmn1, lacTacStart, lacTacEnd, pnnIndex));
- opl.add(new OperatorPlmnInfo(plmn2, lacTacStart, lacTacEnd, pnnIndex + 1));
- opl.add(new OperatorPlmnInfo(plmn3, lacTacStart, lacTacEnd, pnnIndex + 2));
- OperatorPlmnInfo[] oplArray = opl.toArray(new OperatorPlmnInfo[0]);
-
- // Test
- assertNull(IccRecords.getNetworkNameForPlmnFromPnnOpl(pnnsArray, oplArray, null, 0));
- assertEquals(fullName1, IccRecords.getNetworkNameForPlmnFromPnnOpl(pnnsArray, oplArray,
- plmn1, 0));
- assertEquals(fullName2, IccRecords.getNetworkNameForPlmnFromPnnOpl(pnnsArray, oplArray,
- plmn2, 0));
- assertEquals(shortName2, IccRecords.getNetworkNameForPlmnFromPnnOpl(pnnsArray, oplArray,
- plmn3, 0));
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/uicc/IccUtilsTest.java b/tests/telephonytests/src/com/android/internal/telephony/uicc/IccUtilsTest.java
index 02603828a1..d2cebb330d 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/uicc/IccUtilsTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/uicc/IccUtilsTest.java
@@ -16,29 +16,20 @@
package com.android.internal.telephony.uicc;
-import static com.google.common.truth.Truth.assertThat;
-
-import static org.junit.Assert.assertEquals;
-
+import android.test.AndroidTestCase;
+import android.test.suitebuilder.annotation.SmallTest;
import android.text.TextUtils;
-import androidx.test.ext.junit.runners.AndroidJUnit4;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
import java.util.Arrays;
import java.util.List;
-@RunWith(AndroidJUnit4.class)
-public class IccUtilsTest {
+public class IccUtilsTest extends AndroidTestCase {
private static final int NUM_FPLMN = 3;
private static final List<String> FPLMNS_SAMPLE = Arrays.asList("123456", "12345", "54321");
private static final int DATA_LENGTH = 12;
- private static final String EMOJI = new String(Character.toChars(0x1F642));
- @Test
- public void encodeFplmns() {
+ @SmallTest
+ public void testEncodeFplmns() {
byte[] encodedFplmns = IccUtils.encodeFplmns(FPLMNS_SAMPLE, DATA_LENGTH);
int numValidPlmns = 0;
for (int i = 0; i < NUM_FPLMN; i++) {
@@ -49,58 +40,4 @@ public class IccUtilsTest {
}
assertEquals(NUM_FPLMN, numValidPlmns);
}
-
- @Test
- public void stringToAdnStringField_gsmBasic() {
- String alphaTag = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 1234567890"
- + "!@#$%&*()_+,.?;:<>";
-
- byte[] result = IccUtils.stringToAdnStringField(alphaTag);
- assertThat(result.length).isEqualTo(alphaTag.length());
- assertThat(IccUtils.adnStringFieldToString(result, 0, result.length))
- .isEqualTo(alphaTag);
- }
-
- @Test
- public void stringToAdnStringField_nonGsm() {
- String alphaTag = "日本";
-
- byte[] result = IccUtils.stringToAdnStringField(alphaTag);
- assertThat(result.length).isEqualTo(alphaTag.length() * 2 + 1);
- assertThat(result[0]).isEqualTo((byte) 0x80);
- assertThat(IccUtils.adnStringFieldToString(result, 0, result.length))
- .isEqualTo(alphaTag);
- }
-
- @Test
- public void stringToAdnStringField_mixed() {
- String alphaTag = "ni=日;hon=本;";
-
- byte[] result = IccUtils.stringToAdnStringField(alphaTag);
- assertThat(result.length).isEqualTo(alphaTag.length() * 2 + 1);
- assertThat(result[0]).isEqualTo((byte) 0x80);
- assertThat(IccUtils.adnStringFieldToString(result, 0, result.length))
- .isEqualTo(alphaTag);
- }
-
- @Test
- public void stringToAdnStringField_gsmWithEmoji() {
- String alphaTag = ":)=" + EMOJI + ";";
-
- byte[] result = IccUtils.stringToAdnStringField(alphaTag);
- assertThat(result.length).isEqualTo(alphaTag.length() * 2 + 1);
- assertThat(IccUtils.adnStringFieldToString(result, 0, result.length))
- .isEqualTo(alphaTag);
- }
-
- @Test
- public void stringToAdnStringField_mixedWithEmoji() {
- String alphaTag = "ni=日;hon=本;:)=" + EMOJI + ";";
-
- byte[] result = IccUtils.stringToAdnStringField(alphaTag);
- assertThat(result.length).isEqualTo(alphaTag.length() * 2 + 1);
- assertThat(result[0]).isEqualTo((byte) 0x80);
- assertThat(IccUtils.adnStringFieldToString(result, 0, result.length))
- .isEqualTo(alphaTag);
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/uicc/PinStorageTest.java b/tests/telephonytests/src/com/android/internal/telephony/uicc/PinStorageTest.java
deleted file mode 100644
index a26c0f905a..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/uicc/PinStorageTest.java
+++ /dev/null
@@ -1,414 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.internal.telephony.uicc;
-
-import static com.android.internal.telephony.uicc.IccCardStatus.PinState.PINSTATE_ENABLED_VERIFIED;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import static org.mockito.Mockito.anyInt;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.when;
-
-import android.content.Intent;
-import android.os.PersistableBundle;
-import android.preference.PreferenceManager;
-import android.provider.Settings;
-import android.telephony.CarrierConfigManager;
-import android.telephony.TelephonyManager;
-import android.testing.AndroidTestingRunner;
-import android.testing.TestableLooper;
-
-import androidx.test.InstrumentationRegistry;
-import androidx.test.filters.SmallTest;
-
-import com.android.internal.R;
-import com.android.internal.telephony.PhoneConstants;
-import com.android.internal.telephony.TelephonyTest;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-@RunWith(AndroidTestingRunner.class)
-@TestableLooper.RunWithLooper
-public class PinStorageTest extends TelephonyTest {
- private static final String ICCID_1 = "89010003006562472370";
- private static final String ICCID_2 = "89010003006562472399";
- private static final String ICCID_INVALID = "1234";
-
- private int mBootCount;
- private int mSimulatedRebootsCount;
- private PinStorage mPinStorage;
-
- private void simulateReboot() {
- mSimulatedRebootsCount++;
- Settings.Global.putInt(mContext.getContentResolver(),
- Settings.Global.BOOT_COUNT, mBootCount + mSimulatedRebootsCount);
-
- mPinStorage = new PinStorage(mContext);
- mPinStorage.mShortTermSecretKeyDurationMinutes = 0;
- }
-
- @Before
- public void setUp() throws Exception {
- super.setUp(this.getClass().getSimpleName());
-
- // Store boot count, so that correct value can be restored at the end.
- mBootCount = Settings.Global.getInt(
- mContext.getContentResolver(), Settings.Global.BOOT_COUNT, -1);
- mSimulatedRebootsCount = 0;
-
- // Clear shared preferences.
- PreferenceManager.getDefaultSharedPreferences(InstrumentationRegistry.getContext())
- .edit().clear().commit();
- // Enable PIN storage in resources
- mContextFixture.putBooleanResource(
- R.bool.config_allow_pin_storage_for_unattended_reboot, true);
- // Remaining setup
- doReturn(ICCID_1).when(mPhone).getFullIccSerialNumber();
- // Simulate the device is not secure by default
- when(mKeyguardManager.isDeviceSecure()).thenReturn(false);
- when(mKeyguardManager.isDeviceLocked()).thenReturn(false);
-
- mPinStorage = new PinStorage(mContext);
- mPinStorage.mShortTermSecretKeyDurationMinutes = 0;
- }
-
- @After
- public void tearDown() throws Exception {
- super.tearDown();
-
- // Restore boot count
- if (mBootCount == -1) {
- Settings.Global.resetToDefaults(
- mContext.getContentResolver(), Settings.Global.BOOT_COUNT);
- } else {
- Settings.Global.putInt(
- mContext.getContentResolver(), Settings.Global.BOOT_COUNT, mBootCount);
- }
- }
-
- @Test
- @SmallTest
- public void storePin_withoutReboot_pinCannotBeRetrieved() {
- mPinStorage.storePin("1234", 0);
-
- assertThat(mPinStorage.getPin(0, ICCID_1)).isEqualTo("");
- }
-
- @Test
- @SmallTest
- public void storePin_normalReboot_pinCannotBeRetrieved() {
- mPinStorage.storePin("1234", 0);
-
- simulateReboot();
-
- assertThat(mPinStorage.getPin(0, ICCID_1)).isEqualTo("");
- }
-
- @Test
- @SmallTest
- public void storePin_crash_pinCannotBeRetrieved() {
- mPinStorage.storePin("1234", 0);
-
- // Simulate crash
- mPinStorage = new PinStorage(mContext);
- mPinStorage.mShortTermSecretKeyDurationMinutes = 0;
-
- assertThat(mPinStorage.getPin(0, ICCID_1)).isEqualTo("");
- }
-
- @Test
- @SmallTest
- public void storePin_unattendedReboot_pinCanBeRetrievedOnce() {
- mPinStorage.storePin("1234", 0);
-
- int result = mPinStorage.prepareUnattendedReboot();
- assertThat(result).isEqualTo(TelephonyManager.PREPARE_UNATTENDED_REBOOT_SUCCESS);
-
- simulateReboot();
-
- // PIN can be retrieved only once after unattended reboot
- assertThat(mPinStorage.getPin(0, ICCID_1)).isEqualTo("1234");
- assertThat(mPinStorage.getPin(0, ICCID_1)).isEqualTo("");
- }
-
- @Test
- @SmallTest
- public void storePin_unattendedReboot_deviceIsLocked() {
- // Simulate the device is still locked
- when(mKeyguardManager.isDeviceSecure()).thenReturn(true);
- when(mKeyguardManager.isDeviceLocked()).thenReturn(true);
- simulateReboot();
-
- mPinStorage.storePin("1234", 0);
-
- int result = mPinStorage.prepareUnattendedReboot();
- assertThat(result).isEqualTo(TelephonyManager.PREPARE_UNATTENDED_REBOOT_ERROR);
-
- simulateReboot();
-
- // PIN cannot be retrieved
- assertThat(mPinStorage.getPin(0, ICCID_1)).isEqualTo("");
- }
-
- @Test
- @SmallTest
- public void storePin_unattendedReboot_pinIsRemovedAfterDelay() {
- mPinStorage.storePin("1234", 0);
-
- int result = mPinStorage.prepareUnattendedReboot();
- assertThat(result).isEqualTo(TelephonyManager.PREPARE_UNATTENDED_REBOOT_SUCCESS);
-
- simulateReboot();
-
- // Move time forward by 60 seconds
- moveTimeForward(60000);
- processAllMessages();
-
- assertThat(mPinStorage.getPin(0, ICCID_1)).isEqualTo("");
-
- // Simulate a second unattended reboot to make sure that PIN was deleted.
- result = mPinStorage.prepareUnattendedReboot();
- assertThat(result).isEqualTo(TelephonyManager.PREPARE_UNATTENDED_REBOOT_SUCCESS);
-
- simulateReboot();
-
- assertThat(mPinStorage.getPin(0, ICCID_1)).isEqualTo("");
- }
-
- @Test
- @SmallTest
- public void storePin_unattendedRebootNotDone_pinCannotBeRetrieved() {
- mPinStorage.storePin("1234", 0);
-
- int result = mPinStorage.prepareUnattendedReboot();
- assertThat(result).isEqualTo(TelephonyManager.PREPARE_UNATTENDED_REBOOT_SUCCESS);
-
- // Move time forward by 60 seconds before simulating reboot
- moveTimeForward(60000);
- processAllMessages();
- simulateReboot();
-
- assertThat(mPinStorage.getPin(0, ICCID_1)).isEqualTo("");
- }
-
- @Test
- @SmallTest
- public void storePin_unattendedReboot_iccidChange() {
- mPinStorage.storePin("1234", 0);
-
- int result = mPinStorage.prepareUnattendedReboot();
- assertThat(result).isEqualTo(TelephonyManager.PREPARE_UNATTENDED_REBOOT_SUCCESS);
-
- simulateReboot();
-
- // Switch to a different ICCID in the device after the reboot
- doReturn(ICCID_2).when(mPhone).getFullIccSerialNumber();
-
- assertThat(mPinStorage.getPin(0, ICCID_2)).isEqualTo("");
-
- // Switch back to the initial ICCID to make sure that PIN was deleted.
- doReturn(ICCID_1).when(mPhone).getFullIccSerialNumber();
-
- assertThat(mPinStorage.getPin(0, ICCID_1)).isEqualTo("");
- }
-
- @Test
- @SmallTest
- public void clearPin_pinCannotBeRetrieved() {
- mPinStorage.storePin("1234", 0);
- mPinStorage.clearPin(0);
-
- int result = mPinStorage.prepareUnattendedReboot();
- assertThat(result).isEqualTo(TelephonyManager.PREPARE_UNATTENDED_REBOOT_SUCCESS);
-
- simulateReboot();
-
- assertThat(mPinStorage.getPin(0, ICCID_1)).isEqualTo("");
- }
-
- @Test
- @SmallTest
- public void storePin_pinChanged_pinIsUpdated() {
- mPinStorage.storePin("1234", 0);
- mPinStorage.storePin("5678", 0);
-
- int result = mPinStorage.prepareUnattendedReboot();
- assertThat(result).isEqualTo(TelephonyManager.PREPARE_UNATTENDED_REBOOT_SUCCESS);
-
- simulateReboot();
-
- assertThat(mPinStorage.getPin(0, ICCID_1)).isEqualTo("5678");
- }
-
- @Test
- @SmallTest
- public void storePin_pinTooShort_pinIsNotStored() {
- mPinStorage.storePin("12", 0);
-
- int result = mPinStorage.prepareUnattendedReboot();
- assertThat(result).isEqualTo(TelephonyManager.PREPARE_UNATTENDED_REBOOT_SUCCESS);
-
- simulateReboot();
-
- assertThat(mPinStorage.getPin(0, ICCID_1)).isEqualTo("");
- }
-
- @Test
- @SmallTest
- public void storePin_pinTooLong_pinIsNotStored() {
- mPinStorage.storePin("123456789", 0);
-
- int result = mPinStorage.prepareUnattendedReboot();
- assertThat(result).isEqualTo(TelephonyManager.PREPARE_UNATTENDED_REBOOT_SUCCESS);
-
- simulateReboot();
-
- assertThat(mPinStorage.getPin(0, ICCID_1)).isEqualTo("");
- }
-
- @Test
- @SmallTest
- public void storePin_invalidIccid_pinIsNotStored() {
- doReturn(ICCID_INVALID).when(mPhone).getFullIccSerialNumber();
-
- mPinStorage.storePin("1234", 0);
- int result = mPinStorage.prepareUnattendedReboot();
-
- simulateReboot();
-
- assertThat(mPinStorage.getPin(0, ICCID_INVALID)).isEqualTo("");
- }
-
- @Test
- @SmallTest
- public void storePin_disabledInResources_pinIsNotStored() {
- mContextFixture.putBooleanResource(
- R.bool.config_allow_pin_storage_for_unattended_reboot, false);
-
- mPinStorage.storePin("1234", 0);
-
- int result = mPinStorage.prepareUnattendedReboot();
- assertThat(result).isEqualTo(TelephonyManager.PREPARE_UNATTENDED_REBOOT_SUCCESS);
-
- simulateReboot();
-
- assertThat(mPinStorage.getPin(0, ICCID_1)).isEqualTo("");
- }
-
- @Test
- @SmallTest
- public void storePin_disabledInResources_containsSimWithPinEnabledAndVerified() {
- mContextFixture.putBooleanResource(
- R.bool.config_allow_pin_storage_for_unattended_reboot, false);
-
- when(mUiccController.getUiccProfileForPhone(anyInt())).thenReturn(mUiccProfile);
- when(mUiccCardApplication3gpp.getPin1State()).thenReturn(PINSTATE_ENABLED_VERIFIED);
-
- mPinStorage.storePin("1234", 0);
-
- int result = mPinStorage.prepareUnattendedReboot();
- assertThat(result).isEqualTo(TelephonyManager.PREPARE_UNATTENDED_REBOOT_PIN_REQUIRED);
-
- simulateReboot();
-
- assertThat(mPinStorage.getPin(0, ICCID_1)).isEqualTo("");
- }
-
- @Test
- @SmallTest
- public void storePin_disabledInCarrierConfig_pinIsNotStored() {
- PersistableBundle carrierConfigs = new PersistableBundle();
- carrierConfigs.putBoolean(
- CarrierConfigManager.KEY_STORE_SIM_PIN_FOR_UNATTENDED_REBOOT_BOOL, false);
- when(mCarrierConfigManager.getConfigForSubId(anyInt())).thenReturn(carrierConfigs);
-
- mPinStorage.storePin("1234", 0);
-
- int result = mPinStorage.prepareUnattendedReboot();
- assertThat(result).isEqualTo(TelephonyManager.PREPARE_UNATTENDED_REBOOT_SUCCESS);
-
- simulateReboot();
-
- assertThat(mPinStorage.getPin(0, ICCID_1)).isEqualTo("");
- }
-
- @Test
- @SmallTest
- public void storePin_changeToDisabledInCarrierConfig_pinIsRemoved() {
- mPinStorage.storePin("1234", 0);
-
- // Simulate change in the carrier configuration
- PersistableBundle carrierConfigs = new PersistableBundle();
- carrierConfigs.putBoolean(
- CarrierConfigManager.KEY_STORE_SIM_PIN_FOR_UNATTENDED_REBOOT_BOOL, false);
- when(mCarrierConfigManager.getConfigForSubId(anyInt())).thenReturn(carrierConfigs);
- final Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
- intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, 0);
- mContext.sendBroadcast(intent);
- processAllMessages();
-
- int result = mPinStorage.prepareUnattendedReboot();
- assertThat(result).isEqualTo(TelephonyManager.PREPARE_UNATTENDED_REBOOT_SUCCESS);
-
- simulateReboot();
-
- assertThat(mPinStorage.getPin(0, ICCID_1)).isEqualTo("");
- }
-
- @Test
- @SmallTest
- public void storePin_simIsRemoved_pinIsRemoved() {
- mPinStorage.storePin("1234", 0);
-
- // SIM is removed
- final Intent intent = new Intent(TelephonyManager.ACTION_SIM_CARD_STATE_CHANGED);
- intent.putExtra(PhoneConstants.PHONE_KEY, 0);
- intent.putExtra(TelephonyManager.EXTRA_SIM_STATE, TelephonyManager.SIM_STATE_ABSENT);
- mContext.sendBroadcast(intent);
- processAllMessages();
-
- int result = mPinStorage.prepareUnattendedReboot();
- assertThat(result).isEqualTo(TelephonyManager.PREPARE_UNATTENDED_REBOOT_SUCCESS);
-
- simulateReboot();
-
- assertThat(mPinStorage.getPin(0, ICCID_1)).isEqualTo("");
- }
-
- @Test
- @SmallTest
- public void storePin_simReadyAfterUnattendedReboot_pinIsRemoved() {
- mPinStorage.storePin("1234", 0);
-
- int result = mPinStorage.prepareUnattendedReboot();
- assertThat(result).isEqualTo(TelephonyManager.PREPARE_UNATTENDED_REBOOT_SUCCESS);
-
- simulateReboot();
-
- // SIM is fully loaded before cached PIN is used.
- final Intent intent = new Intent(TelephonyManager.ACTION_SIM_APPLICATION_STATE_CHANGED);
- intent.putExtra(PhoneConstants.PHONE_KEY, 0);
- intent.putExtra(TelephonyManager.EXTRA_SIM_STATE, TelephonyManager.SIM_STATE_LOADED);
- mContext.sendBroadcast(intent);
- processAllMessages();
-
- assertThat(mPinStorage.getPin(0, ICCID_1)).isEqualTo("");
- }
-}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/uicc/RuimRecordsTest.java b/tests/telephonytests/src/com/android/internal/telephony/uicc/RuimRecordsTest.java
deleted file mode 100755
index 70a1577a49..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/uicc/RuimRecordsTest.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.internal.telephony.uicc;
-
-import android.content.Context;
-import android.os.AsyncResult;
-import android.os.HandlerThread;
-import com.android.internal.telephony.TelephonyTest;
-
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.*;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.MockitoAnnotations;
-
-
-public class RuimRecordsTest extends TelephonyTest {
-
- private RuimRecords mRuimRecords;
-
- private class RuimRecordsTestHandler extends HandlerThread {
- private RuimRecordsTestHandler(String name) {
- super(name);
- }
-
- @Override
- public void onLooperPrepared() {
- mRuimRecords = new RuimRecords(mUiccCardApplication3gpp2, mContext, mSimulatedCommands);
- setReady(true);
- }
- }
-
- @Before
- public void setUp() throws Exception {
- super.setUp(this.getClass().getSimpleName());
- new RuimRecordsTestHandler(TAG).start();
- waitUntilReady();
- }
-
- @After
- public void tearDown() throws Exception {
- super.tearDown();
- }
-
- @Test
- public void testCsimImsiLoaded() {
- RuimRecords.EfCsimImsimLoaded mImsiLoaded = mRuimRecords.new EfCsimImsimLoaded();
- AsyncResult ar = new AsyncResult(null, null, null);
- mImsiLoaded.onRecordLoaded(ar);
- String mccmnc = mRuimRecords.getRUIMOperatorNumeric();
- assertNull(mccmnc);
-
- byte[] byteArray = new byte[]{0, 19, 3, 75, 68, 88, 99, (byte)128, (byte)209, 0};
- AsyncResult ar2 = new AsyncResult(null, byteArray, null);
- mImsiLoaded.onRecordLoaded(ar2);
- mccmnc = mRuimRecords.getRUIMOperatorNumeric();
- assertNotNull(mccmnc);
- assertEquals("310008", mccmnc);
- }
-
- @Test
- public void testCsimImsiDecode() {
- RuimRecords.EfCsimImsimLoaded efCsimImsimLoaded = mRuimRecords.new EfCsimImsimLoaded();
-
- // mcc + mnc + min
- byte[] byteArray = new byte[]{0, 19, 3, 75, 68, 88, 99, (byte)128, (byte)209, 0};
- String imsi = efCsimImsimLoaded.decodeImsi(byteArray);
-
- assertEquals("310008984641186", imsi);
- }
-}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/uicc/SIMRecordsTest.java b/tests/telephonytests/src/com/android/internal/telephony/uicc/SIMRecordsTest.java
index 2e375755f8..80f88670ec 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/uicc/SIMRecordsTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/uicc/SIMRecordsTest.java
@@ -19,7 +19,6 @@ package com.android.internal.telephony.uicc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Matchers.eq;
@@ -36,10 +35,7 @@ import androidx.test.runner.AndroidJUnit4;
import com.android.internal.telephony.CommandException;
import com.android.internal.telephony.CommandsInterface;
-import com.android.internal.telephony.GsmAlphabet;
import com.android.internal.telephony.TelephonyTest;
-import com.android.internal.telephony.uicc.IccRecords.OperatorPlmnInfo;
-import com.android.internal.telephony.uicc.IccRecords.PlmnNetworkName;
import org.junit.After;
import org.junit.Before;
@@ -290,113 +286,4 @@ public class SIMRecordsTest extends TelephonyTest {
assertNull(ar.exception);
assertNull(ar.result);
}
-
- @Test
- public void testGetEfPnn() {
- ArrayList<byte[]> rawPnns = new ArrayList<byte[]>();
- List<PlmnNetworkName> targetPnns = new ArrayList<PlmnNetworkName>();
-
- String name = "Test 1";
- rawPnns.add(encodePnn(name));
- targetPnns.add(new PlmnNetworkName(name, null));
- name = "Test 2";
- rawPnns.add(encodePnn(name));
- targetPnns.add(new PlmnNetworkName(name, null));
-
- Message message = mSIMRecordsUT.obtainMessage(SIMRecords.EVENT_GET_PNN_DONE);
- AsyncResult ar = AsyncResult.forMessage(message, rawPnns, null);
- mSIMRecordsUT.handleMessage(message);
- List<PlmnNetworkName> parsedPnns = Arrays.asList(mSIMRecordsUT.getPnns());
-
- assertEquals(parsedPnns, targetPnns);
- }
-
- private static byte[] encodePnn(String name) {
- byte[] gsm7BitName = new byte[] {};
- try {
- gsm7BitName = GsmAlphabet.stringToGsm7BitPacked(name);
- gsm7BitName[0] = (byte) (name.length() % 8 | 0x80);
- } catch (Exception ex) {
- fail("SimRecordsTest: GsmAlphabet.stringToGsm7BitPacked() exception:" + ex);
- }
-
- byte[] encodedName = new byte[gsm7BitName.length + 2];
- encodedName[0] = 0x43;
- encodedName[1] = (byte) gsm7BitName.length;
- System.arraycopy(gsm7BitName, 0, encodedName, 2, gsm7BitName.length);
-
- return encodedName;
- }
-
- @Test
- public void testGetEfOpl() {
- ArrayList<byte[]> rawOpl = new ArrayList<byte[]>();
- List<OperatorPlmnInfo> targetOpl = new ArrayList<OperatorPlmnInfo>();
-
- // OperatorPlmnInfo 1
- String plmn = "123456";
- int lacTacStart = 0x0000;
- int lacTacEnd = 0xFFFE;
- int pnnIndex = 0;
-
- rawOpl.add(encodeOpl(plmn, lacTacStart, lacTacEnd, pnnIndex));
- targetOpl.add(new OperatorPlmnInfo(plmn, lacTacStart, lacTacEnd, pnnIndex));
-
- Message message = mSIMRecordsUT.obtainMessage(SIMRecords.EVENT_GET_OPL_DONE);
- AsyncResult ar = AsyncResult.forMessage(message, rawOpl, null);
- mSIMRecordsUT.handleMessage(message);
- List<OperatorPlmnInfo> parsedOpl = Arrays.asList(mSIMRecordsUT.getOpl());
-
- assertEquals(targetOpl, parsedOpl);
-
- // OperatorPlmnInfo 2
- plmn = "123DDD";
- lacTacStart = 0x0000;
- lacTacEnd = 0xFFFE;
- pnnIndex = 123;
-
- rawOpl.add(encodeOpl(plmn, lacTacStart, lacTacEnd, pnnIndex));
- targetOpl.add(new OperatorPlmnInfo(plmn, lacTacStart, lacTacEnd, pnnIndex));
-
- message = mSIMRecordsUT.obtainMessage(SIMRecords.EVENT_GET_OPL_DONE);
- ar = AsyncResult.forMessage(message, rawOpl, null);
- mSIMRecordsUT.handleMessage(message);
- parsedOpl = Arrays.asList(mSIMRecordsUT.getOpl());
-
- assertEquals(targetOpl, parsedOpl);
-
- // OperatorPlmnInfo 3
- plmn = "123";
- lacTacStart = 0x0000;
- lacTacEnd = 0xFFFE;
- pnnIndex = 123;
-
- rawOpl.add(encodeOpl(plmn, lacTacStart, lacTacEnd, pnnIndex));
-
- message = mSIMRecordsUT.obtainMessage(SIMRecords.EVENT_GET_OPL_DONE);
- ar = AsyncResult.forMessage(message, rawOpl, null);
- mSIMRecordsUT.handleMessage(message);
- parsedOpl = Arrays.asList(mSIMRecordsUT.getOpl());
-
- assertEquals(targetOpl, parsedOpl);
- }
-
- private byte[] encodeOpl(String plmn, int lacTacStart, int lacTacEnd, int pnnIndex) {
- byte[] data = new byte[8];
-
- if (plmn.length() == 5 || plmn.length() == 6) {
- IccUtils.stringToBcdPlmn(plmn, data, 0);
- } else {
- data[0] = (byte) 0xFF;
- data[1] = (byte) 0xFF;
- data[2] = (byte) 0xFF;
- }
- data[3] = (byte) (lacTacStart >>> 8);
- data[4] = (byte) lacTacStart;
- data[5] = (byte) (lacTacEnd >>> 8);
- data[6] = (byte) lacTacEnd;
- data[7] = (byte) pnnIndex;
-
- return data;
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/uicc/SimPhonebookRecordCacheTest.java b/tests/telephonytests/src/com/android/internal/telephony/uicc/SimPhonebookRecordCacheTest.java
deleted file mode 100644
index 24db77daa2..0000000000
--- a/tests/telephonytests/src/com/android/internal/telephony/uicc/SimPhonebookRecordCacheTest.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.internal.telephony.uicc;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import android.os.AsyncResult;
-import android.os.HandlerThread;
-import android.os.Handler;
-import android.os.Message;
-
-import com.android.internal.telephony.TelephonyTest;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-public class SimPhonebookRecordCacheTest extends TelephonyTest {
- private static final int EVENT_PHONEBOOK_RECORDS_RECEIVED = 2;
-
- private SimPhonebookRecordCache mSimPhonebookRecordCacheUt;
- private SimPhonebookRecordHandler mSimPhonebookRecordHandler;
-
- private class SimPhonebookRecordHandler extends HandlerThread {
- SimPhonebookRecordHandler(String name) {
- super(name);
- }
-
- @Override
- public void onLooperPrepared() {
- mSimPhonebookRecordCacheUt =
- new SimPhonebookRecordCache(mContext, 0, mSimulatedCommands);
- setReady(true);
- }
-
- };
-
- @Before
- public void setUp() throws Exception {
- super.setUp(this.getClass().getSimpleName());
- mSimPhonebookRecordHandler = new SimPhonebookRecordHandler(this.getClass().getSimpleName());
- mSimPhonebookRecordHandler.start();
- waitUntilReady();
- }
-
- @After
- public void tearDown() throws Exception {
- mSimPhonebookRecordHandler.quit();
- mSimPhonebookRecordHandler.join();
- super.tearDown();
- }
-
- @Test
- public void testSimPhonebookChangedOnBootup() {
- mSimulatedCommands.notifySimPhonebookChanged();
- waitForLastHandlerAction(mSimPhonebookRecordCacheUt);
- AdnCapacity capacity = mSimPhonebookRecordCacheUt.getAdnCapacity();
- AdnCapacity capVerifer = new AdnCapacity(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
- assertNotNull(capacity);
- assertTrue(capVerifer.equals(capacity));
- mSimulatedCommands.notifySimPhonebookChanged();
- waitForLastHandlerAction(mSimPhonebookRecordCacheUt);
- assertTrue(capacity != mSimPhonebookRecordCacheUt.getAdnCapacity());
- assertTrue(capVerifer.equals(capacity));
- }
-
- @Test
- public void testGetPhonebookRecords() {
- assertFalse(mSimPhonebookRecordCacheUt.isLoading());
- mSimulatedCommands.notifySimPhonebookChanged();
- waitForLastHandlerAction(mSimPhonebookRecordCacheUt);
- assertFalse(mSimPhonebookRecordCacheUt.isLoading());
- mSimPhonebookRecordCacheUt.requestLoadAllPbRecords(null);
- waitForLastHandlerAction(mSimPhonebookRecordCacheUt);
-
- List<SimPhonebookRecord> records = new ArrayList<SimPhonebookRecord>();
- records.add(new SimPhonebookRecord(10, "ABC", "12345", null, null));
- AsyncResult ar = new AsyncResult(null, new ReceivedPhonebookRecords(4, records), null);
- Message msg = Message.obtain(mSimPhonebookRecordCacheUt,
- EVENT_PHONEBOOK_RECORDS_RECEIVED, ar);
- mSimPhonebookRecordCacheUt.handleMessage(msg);
-
- assertFalse(mSimPhonebookRecordCacheUt.isLoading());
- List<AdnRecord> adnRecords = mSimPhonebookRecordCacheUt.getAdnRecords();
- assertEquals(adnRecords.size(), 1);
- assertEquals(adnRecords.get(0).getRecId(), 10);
- }
-
- @Test
- public void testGetPhonebookRecordsWithoutInitization() {
- assertFalse(mSimPhonebookRecordCacheUt.isLoading());
- mSimPhonebookRecordCacheUt.requestLoadAllPbRecords(null);
- assertTrue(mSimPhonebookRecordCacheUt.isLoading());
- waitForLastHandlerAction(mSimPhonebookRecordCacheUt);
- assertFalse(mSimPhonebookRecordCacheUt.isLoading());
- }
-
- @Test
- public void testUpdatePhonebookRecord() {
- List<AdnRecord> adnRecords = mSimPhonebookRecordCacheUt.getAdnRecords();
- assertEquals(adnRecords.size(), 0);
-
- AdnRecord newAdn = new AdnRecord(0, 20, "AB", "123", null, null);
- // add
- mSimPhonebookRecordCacheUt.updateSimPbAdnBySearch(null, newAdn, null);
- waitForLastHandlerAction(mSimPhonebookRecordCacheUt);
- adnRecords = mSimPhonebookRecordCacheUt.getAdnRecords();
- assertEquals(adnRecords.size(), 1);
- AdnRecord oldAdn = adnRecords.get(0);
- assertEquals(oldAdn.getRecId(), 20);
- assertEquals(oldAdn.getAlphaTag(), "AB");
- assertEquals(oldAdn.getNumber(), "123");
- // update
- newAdn = new AdnRecord(0, 20, "ABCD", "123456789", null, null);
- mSimPhonebookRecordCacheUt.updateSimPbAdnBySearch(oldAdn, newAdn, null);
- waitForLastHandlerAction(mSimPhonebookRecordCacheUt);
- adnRecords = mSimPhonebookRecordCacheUt.getAdnRecords();
- assertEquals(adnRecords.size(), 1);
- oldAdn = adnRecords.get(0);
- assertEquals(oldAdn.getRecId(), 20);
- assertEquals(oldAdn.getAlphaTag(), "ABCD");
- assertEquals(oldAdn.getNumber(), "123456789");
- // Delete
- newAdn = new AdnRecord(0, 20, null, null, null, null);
- mSimPhonebookRecordCacheUt.updateSimPbAdnBySearch(oldAdn, newAdn, null);
- waitForLastHandlerAction(mSimPhonebookRecordCacheUt);
- adnRecords = mSimPhonebookRecordCacheUt.getAdnRecords();
- assertEquals(adnRecords.size(), 0);
- }
-}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/uicc/UiccCardTest.java b/tests/telephonytests/src/com/android/internal/telephony/uicc/UiccCardTest.java
index 5ff4aed36e..23a7ec980d 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/uicc/UiccCardTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/uicc/UiccCardTest.java
@@ -78,8 +78,8 @@ public class UiccCardTest extends TelephonyTest {
@Test
@SmallTest
- public void testUiccCartdInfoCorrectness() {
- /* before update correctness test */
+ public void tesUiccCartdInfoSanity() {
+ /* before update sanity test */
assertEquals(0, mUiccCard.getNumApplications());
assertEquals(IccCardStatus.CardState.CARDSTATE_PRESENT, mUiccCard.getCardState());
assertNull(mUiccCard.getUniversalPinState());
diff --git a/tests/telephonytests/src/com/android/internal/telephony/uicc/UiccCarrierPrivilegeRulesTest.java b/tests/telephonytests/src/com/android/internal/telephony/uicc/UiccCarrierPrivilegeRulesTest.java
index 7a16e5bf97..b383bfa8e2 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/uicc/UiccCarrierPrivilegeRulesTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/uicc/UiccCarrierPrivilegeRulesTest.java
@@ -26,7 +26,6 @@ import static org.mockito.Mockito.doAnswer;
import android.content.pm.Signature;
import android.os.AsyncResult;
import android.os.Message;
-import android.telephony.UiccAccessRule;
import android.test.suitebuilder.annotation.SmallTest;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
@@ -42,20 +41,11 @@ import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicReference;
-
@RunWith(AndroidTestingRunner.class)
@TestableLooper.RunWithLooper
public class UiccCarrierPrivilegeRulesTest extends TelephonyTest {
private UiccCarrierPrivilegeRules mUiccCarrierPrivilegeRules;
- private static final String ARAM = "A00000015141434C00";
- private static final String ARAD = "A00000015144414300";
- private static final String PKCS15_AID = "A000000063504B43532D3135";
-
@Mock
private UiccProfile mUiccProfile;
@@ -299,6 +289,10 @@ public class UiccCarrierPrivilegeRulesTest extends TelephonyTest {
assertTrue(!mUiccCarrierPrivilegeRules.shouldRetry(ar, 0));
}
+ private static final String ARAM = "A00000015141434C00";
+ private static final String ARAD = "A00000015144414300";
+ private static final String PKCS15_AID = "A000000063504B43532D3135";
+
@Test
@SmallTest
public void testAID_OnlyARAM() {
@@ -482,7 +476,7 @@ public class UiccCarrierPrivilegeRulesTest extends TelephonyTest {
@Test
@SmallTest
- public void testAID_ARFFailed() {
+ public void testAID_NeitherARAMorARAD() {
final String hexString =
"FF4045E243E135C114ABCD92CBB156B280FA4E1429A6ECEEB6E5C1BFE4CA1D636F6D2E676F6F676"
+ "C652E616E64726F69642E617070732E6D79617070E30ADB080000000000000001";
@@ -521,233 +515,8 @@ public class UiccCarrierPrivilegeRulesTest extends TelephonyTest {
assertTrue(!mUiccCarrierPrivilegeRules.hasCarrierPrivilegeRules());
}
- @Test
- @SmallTest
- public void testAID_ARFSucceed() {
- /**
- * PKCS#15 application (AID: A0 00 00 00 63 50 4B 43 53 2D 31 35)
- * -ODF (5031)
- * A7 06 30 04 04 02 52 07
- * -DODF (5207)
- * A1 29 30 00 30 0F 0C 0D 47 50 20 53 45 20 41 63 63 20 43 74 6C A1 14 30 12
- * 06 0A 2A 86 48 86 FC 6B 81 48 01 01 30 04 04 02 42 00
- * -EF ACMain (4200)
- * 30 10 04 08 01 02 03 04 05 06 07 08 30 04 04 02 43 00
- * -EF ACRules (4300)
- * 30 10 A0 08 04 06 A0 00 00 01 51 01 30 04 04 02 43 10
- * -EF ACConditions1 (4310)
- * 30 22
- * 04 20
- * B9CFCE1C47A6AC713442718F15EF55B00B3A6D1A6D48CB46249FA8EB51465350
- * 30 22
- * 04 20
- * 4C36AF4A5BDAD97C1F3D8B283416D244496C2AC5EAFE8226079EF6F676FD1859
- */
- doAnswer(new Answer<Void>() {
- @Override
- public Void answer(InvocationOnMock invocation) throws Throwable {
- String aid = (String) invocation.getArguments()[0];
- Message message = (Message) invocation.getArguments()[2];
- AsyncResult ar = new AsyncResult(null, null, null);
- if (aid.equals(ARAM)) {
- message.arg2 = 1;
- } else if (aid.equals(ARAD)) {
- message.arg2 = 0;
- } else {
- // PKCS15
- ar = new AsyncResult(null, new int[]{2}, null);
- }
- message.obj = ar;
- message.sendToTarget();
- return null;
- }
- }).when(mUiccProfile).iccOpenLogicalChannel(anyString(), anyInt(), any(Message.class));
-
- // Select files
- AtomicReference<String> currentFileId = new AtomicReference<>();
- doAnswer(new Answer<Void>() {
- @Override
- public Void answer(InvocationOnMock invocation) throws Throwable {
- currentFileId.set((String) invocation.getArguments()[6]);
- Message message = (Message) invocation.getArguments()[7];
- AsyncResult ar = new AsyncResult(null, new int[]{2}, null);
- message.obj = ar;
- message.sendToTarget();
- return null;
- }
- }).when(mUiccProfile).iccTransmitApduLogicalChannel(anyInt(), eq(0x00), eq(0xA4), eq(0x00),
- eq(0x04), eq(0x02), anyString(), any(Message.class));
-
- // Read binary - since params are identical across files, we need to keep track of which
- // file was selected most recently and give back that content.
- Map<String, String> binaryContent =
- new HashMap<>() {
- {
- // ODF
- put("5031", "A706300404025207");
- // DODF
- put(
- "5207",
- "A1293000300F0C0D4750205345204163632043746CA1143012060A2A864886FC6B"
- + "81480101300404024200");
- // ACMF
- put("4200", "301004080102030405060708300404024300");
- // ACRF
- put("4300", "3010A0080406FFFFFFFFFFFF300404024310");
- // ACCF
- put(
- "4310",
- "30220420B9CFCE1C47A6AC713442718F15EF55B00B3A6D1A6D48CB46249FA8EB51"
- + "465350302204204C36AF4A5BDAD97C1F3D8B283416D244496C2AC5EA"
- + "FE8226079EF6F676FD1859");
- }
- };
- doAnswer(new Answer<Void>() {
- @Override
- public Void answer(InvocationOnMock invocation) throws Throwable {
- Message message = (Message) invocation.getArguments()[7];
- IccIoResult iir =
- new IccIoResult(0x90, 0x00,
- IccUtils.hexStringToBytes(binaryContent.get(currentFileId.get())));
- AsyncResult ar = new AsyncResult(null, iir, null);
- message.obj = ar;
- message.sendToTarget();
- return null;
- }
- }).when(mUiccProfile).iccTransmitApduLogicalChannel(anyInt(), eq(0x00), eq(0xB0), eq(0x00),
- eq(0x00), eq(0x00), eq(""), any(Message.class));
-
- doAnswer(new Answer<Void>() {
- @Override
- public Void answer(InvocationOnMock invocation) throws Throwable {
- Message message = (Message) invocation.getArguments()[1];
- message.sendToTarget();
- return null;
- }
- }).when(mUiccProfile).iccCloseLogicalChannel(anyInt(), any(Message.class));
-
- mUiccCarrierPrivilegeRules = new UiccCarrierPrivilegeRules(mUiccProfile, null);
- processAllMessages();
-
- assertTrue(mUiccCarrierPrivilegeRules.hasCarrierPrivilegeRules());
- assertEquals(2, mUiccCarrierPrivilegeRules.getAccessRules().size());
- List<UiccAccessRule> accessRules = mUiccCarrierPrivilegeRules.getAccessRules();
- UiccAccessRule accessRule1 = new UiccAccessRule(
- IccUtils.hexStringToBytes(
- "B9CFCE1C47A6AC713442718F15EF55B00B3A6D1A6D48CB46249FA8EB51465350"),
- "",
- 0x00);
- assertTrue(accessRules.contains(accessRule1));
- UiccAccessRule accessRule2 = new UiccAccessRule(
- IccUtils.hexStringToBytes(
- "4C36AF4A5BDAD97C1F3D8B283416D244496C2AC5EAFE8226079EF6F676FD1859"),
- "",
- 0x00);
- assertTrue(accessRules.contains(accessRule2));
- }
-
- @Test
- @SmallTest
- public void testAID_ARFFallbackToACRF() {
- doAnswer(new Answer<Void>() {
- @Override
- public Void answer(InvocationOnMock invocation) throws Throwable {
- String aid = (String) invocation.getArguments()[0];
- Message message = (Message) invocation.getArguments()[2];
- AsyncResult ar = new AsyncResult(null, null, null);
- if (aid.equals(ARAM)) {
- message.arg2 = 1;
- } else if (aid.equals(ARAD)) {
- message.arg2 = 0;
- } else {
- // PKCS15
- ar = new AsyncResult(null, new int[]{2}, null);
- }
- message.obj = ar;
- message.sendToTarget();
- return null;
- }
- }).when(mUiccProfile).iccOpenLogicalChannel(anyString(), anyInt(), any(Message.class));
-
- // Select files
- AtomicReference<String> currentFileId = new AtomicReference<>();
- doAnswer(new Answer<Void>() {
- @Override
- public Void answer(InvocationOnMock invocation) throws Throwable {
- currentFileId.set((String) invocation.getArguments()[6]);
- Message message = (Message) invocation.getArguments()[7];
- AsyncResult ar = new AsyncResult(null, new int[]{2}, null);
- message.obj = ar;
- message.sendToTarget();
- return null;
- }
- }).when(mUiccProfile).iccTransmitApduLogicalChannel(anyInt(), eq(0x00), eq(0xA4), eq(0x00),
- eq(0x04), eq(0x02), anyString(), any(Message.class));
-
- // Read binary - since params are identical across files, we need to keep track of which
- // file was selected most recently and give back that content.
- Map<String, String> binaryContent =
- new HashMap<>() {
- {
- // ODF fails
- put("5031", "");
- // ACRF
- put("4300", "3010A0080406FFFFFFFFFFFF300404024310");
- // ACCF
- put(
- "4310",
- "30220420B9CFCE1C47A6AC713442718F15EF55B00B3A6D1A6D48CB46249FA8EB51"
- + "465350302204204C36AF4A5BDAD97C1F3D8B283416D244496C2AC5EA"
- + "FE8226079EF6F676FD1859");
- }
- };
- doAnswer(new Answer<Void>() {
- @Override
- public Void answer(InvocationOnMock invocation) throws Throwable {
- Message message = (Message) invocation.getArguments()[7];
- IccIoResult iir =
- new IccIoResult(0x90, 0x00,
- IccUtils.hexStringToBytes(binaryContent.get(currentFileId.get())));
- AsyncResult ar = new AsyncResult(null, iir, null);
- message.obj = ar;
- message.sendToTarget();
- return null;
- }
- }).when(mUiccProfile).iccTransmitApduLogicalChannel(anyInt(), eq(0x00), eq(0xB0), eq(0x00),
- eq(0x00), eq(0x00), eq(""), any(Message.class));
-
- doAnswer(new Answer<Void>() {
- @Override
- public Void answer(InvocationOnMock invocation) throws Throwable {
- Message message = (Message) invocation.getArguments()[1];
- message.sendToTarget();
- return null;
- }
- }).when(mUiccProfile).iccCloseLogicalChannel(anyInt(), any(Message.class));
-
- mUiccCarrierPrivilegeRules = new UiccCarrierPrivilegeRules(mUiccProfile, null);
- processAllMessages();
-
- assertTrue(mUiccCarrierPrivilegeRules.hasCarrierPrivilegeRules());
- assertEquals(2, mUiccCarrierPrivilegeRules.getAccessRules().size());
- List<UiccAccessRule> accessRules = mUiccCarrierPrivilegeRules.getAccessRules();
- UiccAccessRule accessRule1 = new UiccAccessRule(
- IccUtils.hexStringToBytes(
- "B9CFCE1C47A6AC713442718F15EF55B00B3A6D1A6D48CB46249FA8EB51465350"),
- "",
- 0x00);
- assertTrue(accessRules.contains(accessRule1));
- UiccAccessRule accessRule2 = new UiccAccessRule(
- IccUtils.hexStringToBytes(
- "4C36AF4A5BDAD97C1F3D8B283416D244496C2AC5EAFE8226079EF6F676FD1859"),
- "",
- 0x00);
- assertTrue(accessRules.contains(accessRule2));
- }
-
private static final int P2 = 0x40;
private static final int P2_EXTENDED_DATA = 0x60;
-
@Test
@SmallTest
public void testAID_RetransmitLogicalChannel() {
diff --git a/tests/telephonytests/src/com/android/internal/telephony/uicc/UiccControllerTest.java b/tests/telephonytests/src/com/android/internal/telephony/uicc/UiccControllerTest.java
index a00e110f5a..e518f3ec0f 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/uicc/UiccControllerTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/uicc/UiccControllerTest.java
@@ -18,7 +18,6 @@ package com.android.internal.telephony.uicc;
import static junit.framework.Assert.fail;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@@ -61,7 +60,6 @@ public class UiccControllerTest extends TelephonyTest {
private static final int ICC_CHANGED_EVENT = 0;
private static final int EVENT_GET_ICC_STATUS_DONE = 3;
private static final int EVENT_GET_SLOT_STATUS_DONE = 4;
- private static final int EVENT_SIM_REFRESH = 8;
private static final int EVENT_EID_READY = 9;
@Mock
private Handler mMockedHandler;
@@ -75,8 +73,6 @@ public class UiccControllerTest extends TelephonyTest {
private UiccCard mMockCard;
@Mock
private EuiccCard mMockEuiccCard;
- @Mock
- private UiccProfile mMockProfile;
private IccCardApplicationStatus composeUiccApplicationStatus(
IccCardApplicationStatus.AppType appType,
@@ -635,32 +631,4 @@ public class UiccControllerTest extends TelephonyTest {
assertEquals(mUiccControllerUT.convertToPublicCardId(knownEidFromApdu),
mUiccControllerUT.getCardIdForDefaultEuicc());
}
-
- @Test
- public void testSlotStatusChanged() {
- // simulate slot status loaded so that the UiccController sets the last slot status
- IccSlotStatus iss1 = new IccSlotStatus();
- iss1.setSlotState(1 /* active */);
- iss1.eid = "eid1";
- IccSlotStatus iss2 = new IccSlotStatus();
- iss2.setSlotState(1 /* active */);
- iss2.eid = "eid2";
- ArrayList<IccSlotStatus> status = new ArrayList<IccSlotStatus>();
- status.add(iss1);
- status.add(iss2);
- AsyncResult ar = new AsyncResult(null, status, null);
- Message msg = Message.obtain(mUiccControllerUT, EVENT_GET_SLOT_STATUS_DONE, ar);
- mUiccControllerUT.handleMessage(msg);
- processAllMessages();
-
- assertFalse(mUiccControllerUT.slotStatusChanged(status));
-
- // change the order of the IccSlotStatus in the list
- status = new ArrayList<>();
- status.add(iss2);
- status.add(iss1);
-
- // status should be treated different from last status
- assertTrue(mUiccControllerUT.slotStatusChanged(status));
- }
}
diff --git a/tests/telephonytests/src/com/android/internal/telephony/uicc/UiccProfileTest.java b/tests/telephonytests/src/com/android/internal/telephony/uicc/UiccProfileTest.java
index 199ff344c6..61a5e13bb9 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/uicc/UiccProfileTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/uicc/UiccProfileTest.java
@@ -19,7 +19,6 @@ import static com.android.internal.telephony.TelephonyTestUtils.waitForMs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -38,7 +37,6 @@ import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.telephony.CarrierConfigManager;
-import android.telephony.ServiceState;
import android.telephony.SubscriptionInfo;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
@@ -137,21 +135,21 @@ public class UiccProfileTest extends TelephonyTest {
@Test
@SmallTest
- public void testParseAllowListMapFromString() {
- String allowList = "";
- Map<String, String> parsedMap = UiccProfile.parseToCertificateToPackageMap(allowList);
+ public void testParseWhitelistMapFromString() {
+ String whitelist = "";
+ Map<String, String> parsedMap = UiccProfile.parseToCertificateToPackageMap(whitelist);
assertTrue(parsedMap.isEmpty());
- allowList = "nokey;value;separation";
- parsedMap = UiccProfile.parseToCertificateToPackageMap(allowList);
+ whitelist = "nokey;value;separation";
+ parsedMap = UiccProfile.parseToCertificateToPackageMap(whitelist);
assertTrue(parsedMap.isEmpty());
- allowList = "KEY1:value1";
- parsedMap = UiccProfile.parseToCertificateToPackageMap(allowList);
+ whitelist = "KEY1:value1";
+ parsedMap = UiccProfile.parseToCertificateToPackageMap(whitelist);
assertEquals("value1", parsedMap.get("KEY1"));
- allowList = "KEY1:value1; KEY2:value2 ;KEY3:value3";
- parsedMap = UiccProfile.parseToCertificateToPackageMap(allowList);
+ whitelist = "KEY1:value1; KEY2:value2 ;KEY3:value3";
+ parsedMap = UiccProfile.parseToCertificateToPackageMap(whitelist);
assertEquals("value1", parsedMap.get("KEY1"));
assertEquals("value2", parsedMap.get("KEY2"));
assertEquals("value3", parsedMap.get("KEY3"));
@@ -562,19 +560,13 @@ public class UiccProfileTest extends TelephonyTest {
String fakeBrand = "operator";
mUiccProfile.getApplicationIndex(0).getIccRecords().mIccId = fakeIccId;
+ doReturn(fakeIccId).when(mSubscriptionInfo).getIccId();
+ doReturn(mSubscriptionInfo).when(mSubscriptionController)
+ .getActiveSubscriptionInfoForSimSlotIndex(eq(0), any(), any());
- doReturn(false).when(mSubscriptionController)
- .checkPhoneIdAndIccIdMatch(anyInt(), anyString());
mUiccProfile.setOperatorBrandOverride(fakeBrand);
String brandInSharedPreference = mContext.getSharedPreferences("file name", 0)
.getString("operator_branding_" + fakeIccId, null);
- assertNotEquals(fakeBrand, brandInSharedPreference);
-
- doReturn(true).when(mSubscriptionController)
- .checkPhoneIdAndIccIdMatch(anyInt(), anyString());
- mUiccProfile.setOperatorBrandOverride(fakeBrand);
- brandInSharedPreference = mContext.getSharedPreferences("file name", 0)
- .getString("operator_branding_" + fakeIccId, null);
assertEquals(fakeBrand, brandInSharedPreference);
}
@@ -614,44 +606,4 @@ public class UiccProfileTest extends TelephonyTest {
assertTrue(mUiccProfile.isEmptyProfile());
}
-
- private void testUpdateUiccProfileApplicationNoCsim() {
- /* update app status and index */
- IccCardApplicationStatus imsApp = composeUiccApplicationStatus(
- IccCardApplicationStatus.AppType.APPTYPE_ISIM,
- IccCardApplicationStatus.AppState.APPSTATE_UNKNOWN, "0xA1");
- IccCardApplicationStatus umtsApp = composeUiccApplicationStatus(
- IccCardApplicationStatus.AppType.APPTYPE_USIM,
- IccCardApplicationStatus.AppState.APPSTATE_UNKNOWN, "0xA2");
- mIccCardStatus.mApplications = new IccCardApplicationStatus[]{imsApp, umtsApp};
- mIccCardStatus.mCdmaSubscriptionAppIndex = -1;
- mIccCardStatus.mImsSubscriptionAppIndex = 0;
- mIccCardStatus.mGsmUmtsSubscriptionAppIndex = 1;
- logd("Update UICC Profile Applications");
- mUiccProfile.update(mContext, mSimulatedCommands, mIccCardStatus);
- processAllMessages();
-
- assertEquals(2, mUiccProfile.getNumApplications());
- assertFalse(mUiccProfile.isApplicationOnIcc(IccCardApplicationStatus.AppType.APPTYPE_CSIM));
- assertTrue(mUiccProfile.isApplicationOnIcc(IccCardApplicationStatus.AppType.APPTYPE_ISIM));
- assertTrue(mUiccProfile.isApplicationOnIcc(IccCardApplicationStatus.AppType.APPTYPE_USIM));
- }
-
- @Test
- @SmallTest
- public void testSetVoiceRadioTech() {
- // if voice rat is GSM, mCurrentAppType should be 3gpp
- mUiccProfile.setVoiceRadioTech(ServiceState.RIL_RADIO_TECHNOLOGY_GSM);
- assertEquals(UiccController.APP_FAM_3GPP, mUiccProfile.mCurrentAppType);
-
- // if voice rat is CDMA, mCurrentAppType should be 3gpp2
- mUiccProfile.setVoiceRadioTech(ServiceState.RIL_RADIO_TECHNOLOGY_IS95A);
- assertEquals(UiccController.APP_FAM_3GPP2, mUiccProfile.mCurrentAppType);
-
- // if voice rat is CDMA, there is no CSIM app, and there is a SIM/USIM app, then
- // mCurrentAppType should be 3gpp
- testUpdateUiccProfileApplicationNoCsim();
- mUiccProfile.setVoiceRadioTech(ServiceState.RIL_RADIO_TECHNOLOGY_IS95A);
- assertEquals(UiccController.APP_FAM_3GPP, mUiccProfile.mCurrentAppType);
- }
}