1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.internal.telephony;
18 
19 import static com.google.common.truth.Truth.assertThat;
20 
21 import static org.junit.Assert.assertEquals;
22 import static org.junit.Assert.assertFalse;
23 import static org.junit.Assert.assertTrue;
24 import static org.mockito.Matchers.any;
25 import static org.mockito.Matchers.anyLong;
26 import static org.mockito.Matchers.nullable;
27 import static org.mockito.Mockito.anyInt;
28 import static org.mockito.Mockito.anyString;
29 import static org.mockito.Mockito.atLeast;
30 import static org.mockito.Mockito.doReturn;
31 import static org.mockito.Mockito.eq;
32 import static org.mockito.Mockito.mock;
33 import static org.mockito.Mockito.never;
34 import static org.mockito.Mockito.spy;
35 import static org.mockito.Mockito.times;
36 import static org.mockito.Mockito.verify;
37 import static org.mockito.Mockito.when;
38 
39 import android.app.IAlarmManager;
40 import android.app.Notification;
41 import android.app.NotificationManager;
42 import android.content.ComponentName;
43 import android.content.Context;
44 import android.content.Intent;
45 import android.content.IntentFilter;
46 import android.content.pm.ApplicationInfo;
47 import android.content.pm.ServiceInfo;
48 import android.content.res.Resources;
49 import android.graphics.drawable.Drawable;
50 import android.os.AsyncResult;
51 import android.os.Bundle;
52 import android.os.Handler;
53 import android.os.HandlerThread;
54 import android.os.Looper;
55 import android.os.Message;
56 import android.os.PersistableBundle;
57 import android.os.Process;
58 import android.os.SystemClock;
59 import android.os.TimestampedValue;
60 import android.os.UserHandle;
61 import android.os.WorkSource;
62 import android.telephony.AccessNetworkConstants;
63 import android.telephony.CarrierConfigManager;
64 import android.telephony.CellIdentity;
65 import android.telephony.CellIdentityCdma;
66 import android.telephony.CellIdentityGsm;
67 import android.telephony.CellIdentityLte;
68 import android.telephony.CellInfo;
69 import android.telephony.CellInfoGsm;
70 import android.telephony.CellSignalStrength;
71 import android.telephony.CellSignalStrengthCdma;
72 import android.telephony.CellSignalStrengthGsm;
73 import android.telephony.CellSignalStrengthLte;
74 import android.telephony.CellSignalStrengthNr;
75 import android.telephony.CellSignalStrengthTdscdma;
76 import android.telephony.CellSignalStrengthWcdma;
77 import android.telephony.INetworkService;
78 import android.telephony.LteVopsSupportInfo;
79 import android.telephony.NetworkRegistrationInfo;
80 import android.telephony.NetworkService;
81 import android.telephony.PhysicalChannelConfig;
82 import android.telephony.ServiceState;
83 import android.telephony.SignalStrength;
84 import android.telephony.SubscriptionInfo;
85 import android.telephony.SubscriptionManager;
86 import android.telephony.TelephonyManager;
87 import android.telephony.cdma.CdmaCellLocation;
88 import android.telephony.gsm.GsmCellLocation;
89 import android.test.suitebuilder.annotation.MediumTest;
90 import android.test.suitebuilder.annotation.SmallTest;
91 import android.text.TextUtils;
92 import android.util.Pair;
93 
94 import androidx.test.filters.FlakyTest;
95 
96 import com.android.internal.R;
97 import com.android.internal.telephony.cdma.CdmaSubscriptionSourceManager;
98 import com.android.internal.telephony.test.SimulatedCommands;
99 import com.android.internal.telephony.uicc.IccCardApplicationStatus;
100 import com.android.internal.telephony.uicc.IccRecords;
101 
102 import org.junit.After;
103 import org.junit.Before;
104 import org.junit.Ignore;
105 import org.junit.Test;
106 import org.mockito.ArgumentCaptor;
107 import org.mockito.Mock;
108 import org.mockito.Mockito;
109 
110 import java.util.ArrayList;
111 import java.util.Arrays;
112 import java.util.Collections;
113 import java.util.HashSet;
114 import java.util.List;
115 
116 
117 public class ServiceStateTrackerTest extends TelephonyTest {
118     @Mock
119     private ProxyController mProxyController;
120     @Mock
121     private Handler mTestHandler;
122     @Mock
123     protected IAlarmManager mAlarmManager;
124 
125     private CellularNetworkService mCellularNetworkService;
126 
127     @Mock
128     private NetworkService mIwlanNetworkService;
129     @Mock
130     private INetworkService.Stub mIwlanNetworkServiceStub;
131 
132     @Mock
133     private SubscriptionInfo mSubInfo;
134 
135     private ServiceStateTracker sst;
136     private ServiceStateTrackerTestHandler mSSTTestHandler;
137     private PersistableBundle mBundle;
138 
139     private static final int EVENT_REGISTERED_TO_NETWORK = 1;
140     private static final int EVENT_SUBSCRIPTION_INFO_READY = 2;
141     private static final int EVENT_DATA_ROAMING_ON = 3;
142     private static final int EVENT_DATA_ROAMING_OFF = 4;
143     private static final int EVENT_DATA_CONNECTION_ATTACHED = 5;
144     private static final int EVENT_DATA_CONNECTION_DETACHED = 6;
145     private static final int EVENT_DATA_RAT_CHANGED = 7;
146     private static final int EVENT_PS_RESTRICT_ENABLED = 8;
147     private static final int EVENT_PS_RESTRICT_DISABLED = 9;
148     private static final int EVENT_VOICE_ROAMING_ON = 10;
149     private static final int EVENT_VOICE_ROAMING_OFF = 11;
150     private static final int EVENT_VOICE_RAT_CHANGED = 12;
151 
152     private static final int PHONE_ID = 0;
153 
154     private static final String CARRIER_NAME_DISPLAY_NO_SERVICE = "no service";
155     private static final String CARRIER_NAME_DISPLAY_EMERGENCY_CALL = "emergency call";
156     private static final String WIFI_CALLING_VOICE_FORMAT = "%s wifi calling";
157     private static final String WIFI_CALLING_DATA_FORMAT = "%s wifi data";
158     private static final String WIFI_CALLING_FLIGHT_MODE_FORMAT = "%s flight mode";
159 
160     private static final String[] WIFI_CALLING_FORMATTERS = {
161             WIFI_CALLING_VOICE_FORMAT,
162             WIFI_CALLING_DATA_FORMAT,
163             WIFI_CALLING_FLIGHT_MODE_FORMAT };
164 
165     private static final String HOME_PLMN = "310260";
166     private static final String PLMN1 = "480123";
167     private static final String PLMN2 = "586111";
168     private static final String HOME_PNN = "home pnn";
169     private static final String[] CARRIER_CONFIG_SPDI = new String[] {HOME_PLMN, PLMN2};
170     private static final String[] CARRIER_CONFIG_EHPLMN = new String[] {HOME_PLMN, PLMN1};
171     private static final String[] CARRIER_CONFIG_PNN = new String[] {
172             String.format("%s,%s", HOME_PNN, "short"), "f2,s2"
173     };
174 
175     private class ServiceStateTrackerTestHandler extends HandlerThread {
176 
ServiceStateTrackerTestHandler(String name)177         private ServiceStateTrackerTestHandler(String name) {
178             super(name);
179         }
180 
181         @Override
onLooperPrepared()182         public void onLooperPrepared() {
183             sst = new ServiceStateTracker(mPhone, mSimulatedCommands);
184             setReady(true);
185         }
186     }
187 
addNetworkService()188     private void addNetworkService() {
189         mCellularNetworkService = new CellularNetworkService();
190         ServiceInfo CellularServiceInfo = new ServiceInfo();
191         CellularServiceInfo.packageName = "com.android.phone";
192         CellularServiceInfo.name = "CellularNetworkService";
193         CellularServiceInfo.permission = "android.permission.BIND_TELEPHONY_NETWORK_SERVICE";
194         IntentFilter cellularIntentfilter = new IntentFilter();
195         mContextFixture.addService(
196                 NetworkService.SERVICE_INTERFACE,
197                 new ComponentName("com.android.phone",
198                         "com.android.internal.telephony.CellularNetworkService"),
199                 "com.android.phone",
200                 mCellularNetworkService.mBinder,
201                 CellularServiceInfo,
202                 cellularIntentfilter);
203 
204         ServiceInfo iwlanServiceInfo = new ServiceInfo();
205         iwlanServiceInfo.packageName = "com.xyz.iwlan.networkservice";
206         iwlanServiceInfo.name = "IwlanNetworkService";
207         iwlanServiceInfo.permission = "android.permission.BIND_TELEPHONY_NETWORK_SERVICE";
208         IntentFilter iwlanIntentFilter = new IntentFilter();
209         mContextFixture.addService(
210                 NetworkService.SERVICE_INTERFACE,
211                 new ComponentName("com.xyz.iwlan.networkservice",
212                         "com.xyz.iwlan.IwlanNetworkService"),
213                 "com.xyz.iwlan.networkservice",
214                 mIwlanNetworkServiceStub,
215                 iwlanServiceInfo,
216                 iwlanIntentFilter);
217     }
218 
219     @Before
setUp()220     public void setUp() throws Exception {
221 
222         logd("ServiceStateTrackerTest +Setup!");
223         super.setUp("ServiceStateTrackerTest");
224 
225         mContextFixture.putResource(R.string.config_wwan_network_service_package,
226                 "com.android.phone");
227         mContextFixture.putResource(R.string.config_wlan_network_service_package,
228                 "com.xyz.iwlan.networkservice");
229         doReturn(mIwlanNetworkServiceStub).when(mIwlanNetworkServiceStub).asBinder();
230         addNetworkService();
231 
232         doReturn(true).when(mDcTracker).areAllDataDisconnected();
233 
234         doReturn(new ServiceState()).when(mPhone).getServiceState();
235 
236         replaceInstance(ProxyController.class, "sProxyController", null, mProxyController);
237         mBundle = mContextFixture.getCarrierConfigBundle();
238         mBundle.putStringArray(
239                 CarrierConfigManager.KEY_ROAMING_OPERATOR_STRING_ARRAY, new String[]{"123456"});
240 
241         mBundle.putStringArray(
242                 CarrierConfigManager.KEY_NON_ROAMING_OPERATOR_STRING_ARRAY, new String[]{"123456"});
243 
244         mBundle.putStringArray(CarrierConfigManager.KEY_RATCHET_RAT_FAMILIES,
245                 // UMTS < GPRS < EDGE
246                 new String[]{"3,1,2"});
247 
248         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
249         mSimulatedCommands.setVoiceRadioTech(ServiceState.RIL_RADIO_TECHNOLOGY_HSPA);
250         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
251         mSimulatedCommands.setDataRadioTech(ServiceState.RIL_RADIO_TECHNOLOGY_HSPA);
252 
253         doReturn(PHONE_ID).when(mPhone).getPhoneId();
254 
255         int dds = SubscriptionManager.getDefaultDataSubscriptionId();
256         doReturn(dds).when(mPhone).getSubId();
257         doReturn(true).when(mPhone).areAllDataDisconnected();
258 
259         mSSTTestHandler = new ServiceStateTrackerTestHandler(getClass().getSimpleName());
260         mSSTTestHandler.start();
261         waitUntilReady();
262         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
263 
264         Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
265         intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, 0);
266         mContext.sendBroadcast(intent);
267         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
268 
269         // Override SPN related resource
270         mContextFixture.putResource(
271                 com.android.internal.R.string.lockscreen_carrier_default,
272                 CARRIER_NAME_DISPLAY_NO_SERVICE);
273         mContextFixture.putResource(
274                 com.android.internal.R.string.emergency_calls_only,
275                 CARRIER_NAME_DISPLAY_EMERGENCY_CALL);
276         mContextFixture.putStringArrayResource(
277                 com.android.internal.R.array.wfcSpnFormats,
278                 WIFI_CALLING_FORMATTERS);
279 
280         mBundle.putBoolean(
281                 CarrierConfigManager.KEY_ENABLE_CARRIER_DISPLAY_NAME_RESOLVER_BOOL, true);
282         mBundle.putInt(CarrierConfigManager.KEY_WFC_SPN_FORMAT_IDX_INT, 0);
283         mBundle.putInt(CarrierConfigManager.KEY_WFC_DATA_SPN_FORMAT_IDX_INT, 1);
284         mBundle.putInt(CarrierConfigManager.KEY_WFC_FLIGHT_MODE_SPN_FORMAT_IDX_INT, 2);
285 
286         // Show SPN is required when roaming
287         // Show PLMN is required when non-roaming.
288         doReturn(IccRecords.CARRIER_NAME_DISPLAY_CONDITION_BITMASK_PLMN
289                 | IccRecords.CARRIER_NAME_DISPLAY_CONDITION_BITMASK_SPN)
290                 .when(mSimRecords).getCarrierNameDisplayCondition();
291 
292         mBundle.putString(CarrierConfigManager.KEY_CARRIER_NAME_STRING, "SPN from carrier config");
293         mBundle.putInt(CarrierConfigManager.KEY_SPN_DISPLAY_CONDITION_OVERRIDE_INT,
294                 IccRecords.CARRIER_NAME_DISPLAY_CONDITION_BITMASK_PLMN
295                         | IccRecords.CARRIER_NAME_DISPLAY_CONDITION_BITMASK_SPN);
296         mBundle.putStringArray(CarrierConfigManager.KEY_SPDI_OVERRIDE_STRING_ARRAY,
297                 CARRIER_CONFIG_SPDI);
298         mBundle.putStringArray(CarrierConfigManager.KEY_EHPLMN_OVERRIDE_STRING_ARRAY,
299                 CARRIER_CONFIG_EHPLMN);
300         mBundle.putStringArray(CarrierConfigManager.KEY_PNN_OVERRIDE_STRING_ARRAY,
301                 CARRIER_CONFIG_PNN);
302 
303         // Do not force display "No service" when sim is not ready in any locales
304         mContextFixture.putStringArrayResource(
305                 com.android.internal.R.array.config_display_no_service_when_sim_unready,
306                 new String[0]);
307 
308         mBundle.putIntArray(CarrierConfigManager.KEY_5G_NR_SSRSRP_THRESHOLDS_INT_ARRAY,
309                 new int[] {
310                     -110, /* SIGNAL_STRENGTH_POOR */
311                     -90, /* SIGNAL_STRENGTH_MODERATE */
312                     -80, /* SIGNAL_STRENGTH_GOOD */
313                     -65,  /* SIGNAL_STRENGTH_GREAT */
314                 });
315         mBundle.putIntArray(CarrierConfigManager.KEY_5G_NR_SSRSRQ_THRESHOLDS_INT_ARRAY,
316                 new int[] {
317                     -31, /* SIGNAL_STRENGTH_POOR */
318                     -19, /* SIGNAL_STRENGTH_MODERATE */
319                     -7, /* SIGNAL_STRENGTH_GOOD */
320                     6  /* SIGNAL_STRENGTH_GREAT */
321                 });
322         mBundle.putIntArray(CarrierConfigManager.KEY_5G_NR_SSSINR_THRESHOLDS_INT_ARRAY,
323                 new int[] {
324                     -5, /* SIGNAL_STRENGTH_POOR */
325                     5, /* SIGNAL_STRENGTH_MODERATE */
326                     15, /* SIGNAL_STRENGTH_GOOD */
327                     30  /* SIGNAL_STRENGTH_GREAT */
328                 });
329         logd("ServiceStateTrackerTest -Setup!");
330     }
331 
332     @After
tearDown()333     public void tearDown() throws Exception {
334         sst = null;
335         mSSTTestHandler.quit();
336         mSSTTestHandler.join();
337         if (mCellularNetworkService != null) {
338             mCellularNetworkService.onDestroy();
339         }
340         super.tearDown();
341     }
342 
getPlmnFromCellIdentity(final CellIdentity ci)343     private static String getPlmnFromCellIdentity(final CellIdentity ci) {
344         if (ci == null || ci instanceof CellIdentityCdma) return "";
345 
346         final String mcc = ci.getMccString();
347         final String mnc = ci.getMncString();
348 
349         if (TextUtils.isEmpty(mcc) || TextUtils.isEmpty(mnc)) return "";
350 
351         return mcc + mnc;
352     }
353 
354     @Test
355     @MediumTest
testSetRadioPower()356     public void testSetRadioPower() {
357         boolean oldState = (mSimulatedCommands.getRadioState() == TelephonyManager.RADIO_POWER_ON);
358         sst.setRadioPower(!oldState);
359         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
360         assertTrue(oldState
361                 != (mSimulatedCommands.getRadioState() == TelephonyManager.RADIO_POWER_ON));
362     }
363 
364     @Test
365     @SmallTest
testSetRadioPowerOnForEmergencyCall()366     public void testSetRadioPowerOnForEmergencyCall() {
367         // Turn off radio first.
368         sst.setRadioPower(false);
369         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
370         assertTrue(mSimulatedCommands.getRadioState() == TelephonyManager.RADIO_POWER_OFF);
371 
372         // Turn on radio for emergency call.
373         sst.setRadioPower(true, true, true, false);
374         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
375         assertTrue(mSimulatedCommands.mSetRadioPowerForEmergencyCall);
376         assertTrue(mSimulatedCommands.mSetRadioPowerAsSelectedPhoneForEmergencyCall);
377         assertTrue(mSimulatedCommands.getRadioState() == TelephonyManager.RADIO_POWER_ON);
378 
379         // If we try again without forceApply=true, no command should be sent to modem. Because
380         // radio power is already ON.
381         sst.setRadioPower(true, false, false, false);
382         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
383         assertTrue(mSimulatedCommands.mSetRadioPowerForEmergencyCall);
384         assertTrue(mSimulatedCommands.mSetRadioPowerAsSelectedPhoneForEmergencyCall);
385 
386         // Call setRadioPower on with forceApply=true. ForEmergencyCall and isSelectedPhone should
387         // be cleared.
388         sst.setRadioPower(true, false, false, true);
389         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
390         assertFalse(mSimulatedCommands.mSetRadioPowerForEmergencyCall);
391         assertFalse(mSimulatedCommands.mSetRadioPowerAsSelectedPhoneForEmergencyCall);
392     }
393 
394     @Test
395     @MediumTest
testSetRadioPowerFromCarrier()396     public void testSetRadioPowerFromCarrier() {
397         // Carrier disable radio power
398         sst.setRadioPowerFromCarrier(false);
399         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
400         assertFalse(mSimulatedCommands.getRadioState()
401                 == TelephonyManager.RADIO_POWER_ON);
402         assertTrue(sst.getDesiredPowerState());
403         assertFalse(sst.getPowerStateFromCarrier());
404 
405         // User toggle radio power will not overrides carrier settings
406         sst.setRadioPower(true);
407         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
408         assertFalse(mSimulatedCommands.getRadioState()
409                 == TelephonyManager.RADIO_POWER_ON);
410         assertTrue(sst.getDesiredPowerState());
411         assertFalse(sst.getPowerStateFromCarrier());
412 
413         // Carrier re-enable radio power
414         sst.setRadioPowerFromCarrier(true);
415         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
416         assertTrue(mSimulatedCommands.getRadioState() == TelephonyManager.RADIO_POWER_ON);
417         assertTrue(sst.getDesiredPowerState());
418         assertTrue(sst.getPowerStateFromCarrier());
419 
420         // User toggle radio power off (airplane mode) and set carrier on
421         sst.setRadioPower(false);
422         sst.setRadioPowerFromCarrier(true);
423         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
424         assertFalse(mSimulatedCommands.getRadioState()
425                 == TelephonyManager.RADIO_POWER_ON);
426         assertFalse(sst.getDesiredPowerState());
427         assertTrue(sst.getPowerStateFromCarrier());
428     }
429 
430     @Test
431     @MediumTest
testRilTrafficAfterSetRadioPower()432     public void testRilTrafficAfterSetRadioPower() {
433         sst.setRadioPower(true);
434         final int getOperatorCallCount = mSimulatedCommands.getGetOperatorCallCount();
435         final int getDataRegistrationStateCallCount =
436                 mSimulatedCommands.getGetDataRegistrationStateCallCount();
437         final int getVoiceRegistrationStateCallCount =
438                 mSimulatedCommands.getGetVoiceRegistrationStateCallCount();
439         final int getNetworkSelectionModeCallCount =
440                 mSimulatedCommands.getGetNetworkSelectionModeCallCount();
441         sst.setRadioPower(false);
442 
443         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
444         sst.pollState();
445         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
446 
447         // This test was meant to be for *no* ril traffic. However, RADIO_STATE_CHANGED is
448         // considered a modem triggered action and that causes a pollState() to be done
449         assertEquals(getOperatorCallCount + 1, mSimulatedCommands.getGetOperatorCallCount());
450         assertEquals(getDataRegistrationStateCallCount + 1,
451                 mSimulatedCommands.getGetDataRegistrationStateCallCount());
452         assertEquals(getVoiceRegistrationStateCallCount + 1,
453                 mSimulatedCommands.getGetVoiceRegistrationStateCallCount());
454         assertEquals(getNetworkSelectionModeCallCount + 1,
455                 mSimulatedCommands.getGetNetworkSelectionModeCallCount());
456 
457         // Note that if the poll is triggered by a network change notification
458         // and the modem is supposed to be off, we should still do the poll
459         mSimulatedCommands.notifyNetworkStateChanged();
460         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
461 
462         assertEquals(getOperatorCallCount + 2 , mSimulatedCommands.getGetOperatorCallCount());
463         assertEquals(getDataRegistrationStateCallCount + 2,
464                 mSimulatedCommands.getGetDataRegistrationStateCallCount());
465         assertEquals(getVoiceRegistrationStateCallCount + 2,
466                 mSimulatedCommands.getGetVoiceRegistrationStateCallCount());
467         assertEquals(getNetworkSelectionModeCallCount + 2,
468                 mSimulatedCommands.getGetNetworkSelectionModeCallCount());
469     }
470 
471     @FlakyTest
472     @Ignore
473     @Test
474     @MediumTest
testSpnUpdateShowPlmnOnly()475     public void testSpnUpdateShowPlmnOnly() {
476         doReturn(0).when(mSimRecords).getCarrierNameDisplayCondition();
477         doReturn(IccCardApplicationStatus.AppState.APPSTATE_UNKNOWN).
478                 when(mUiccCardApplication3gpp).getState();
479 
480         sst.sendMessage(sst.obtainMessage(ServiceStateTracker.EVENT_NETWORK_STATE_CHANGED, null));
481 
482         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
483 
484         ArgumentCaptor<Intent> intentArgumentCaptor = ArgumentCaptor.forClass(Intent.class);
485         verify(mContextFixture.getTestDouble(), times(3))
486                 .sendStickyBroadcastAsUser(intentArgumentCaptor.capture(), eq(UserHandle.ALL));
487 
488         // We only want to verify the intent SPN_STRINGS_UPDATED_ACTION.
489         List<Intent> intents = intentArgumentCaptor.getAllValues();
490         logd("Total " + intents.size() + " intents");
491         for (Intent intent : intents) {
492             logd("  " + intent.getAction());
493         }
494         Intent intent = intents.get(2);
495         assertEquals(TelephonyIntents.SPN_STRINGS_UPDATED_ACTION, intent.getAction());
496 
497         Bundle b = intent.getExtras();
498 
499         // For boolean we need to make sure the key exists first
500         assertTrue(b.containsKey(TelephonyIntents.EXTRA_SHOW_SPN));
501         assertFalse(b.getBoolean(TelephonyIntents.EXTRA_SHOW_SPN));
502 
503         assertEquals(null, b.getString(TelephonyIntents.EXTRA_SPN));
504         assertEquals(null, b.getString(TelephonyIntents.EXTRA_DATA_SPN));
505 
506         // For boolean we need to make sure the key exists first
507         assertTrue(b.containsKey(TelephonyIntents.EXTRA_SHOW_PLMN));
508         assertTrue(b.getBoolean(TelephonyIntents.EXTRA_SHOW_PLMN));
509 
510         assertEquals(SimulatedCommands.FAKE_LONG_NAME, b.getString(TelephonyIntents.EXTRA_PLMN));
511 
512         ArgumentCaptor<Integer> intArgumentCaptor = ArgumentCaptor.forClass(Integer.class);
513         verify(mTelephonyManager).setDataNetworkTypeForPhone(anyInt(), intArgumentCaptor.capture());
514         assertEquals(ServiceState.RIL_RADIO_TECHNOLOGY_HSPA,
515                 intArgumentCaptor.getValue().intValue());
516     }
517 
getCellInfoGsm()518     private CellInfoGsm getCellInfoGsm() {
519         CellInfoGsm tmp = new CellInfoGsm();
520         tmp.setCellIdentity(new CellIdentityGsm(0, 1, 900, 5, "001", "01", "test", "tst",
521                     Collections.emptyList()));
522         tmp.setCellSignalStrength(new CellSignalStrengthGsm(-85, 2, 3));
523         return tmp;
524     }
525 
526     @Test
527     @MediumTest
testCachedCellInfoList()528     public void testCachedCellInfoList() {
529         ArrayList<CellInfo> list = new ArrayList();
530         list.add(getCellInfoGsm());
531         mSimulatedCommands.setCellInfoList(list);
532 
533         WorkSource workSource = new WorkSource(Process.myUid(),
534                 mContext.getPackageName());
535 
536         // null worksource and no response message will update the writethrough cache
537         sst.requestAllCellInfo(null, null);
538         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
539         assertEquals(sst.getAllCellInfo(), list);
540     }
541 
542     private static class CellInfoHandler extends Handler {
543         // Need to define this here so that it's accessible
544         public List<CellInfo> cellInfoResult;
545 
CellInfoHandler(Looper l)546         CellInfoHandler(Looper l) {
547             super(l);
548         }
549 
550         @Override
handleMessage(Message msg)551         public void handleMessage(Message msg) {
552             synchronized (msg) {
553                 assertTrue("handler received null message", msg.obj != null);
554                 AsyncResult ar = (AsyncResult) msg.obj;
555                 cellInfoResult = (List<CellInfo>) ar.result;
556                 msg.notifyAll();
557             }
558         }
559     }
560 
561     @Test
562     @MediumTest
testGetCellInfoResponse()563     public void testGetCellInfoResponse() throws InterruptedException {
564         mSimulatedCommands.setCellInfoListBehavior(true);
565         ArrayList<CellInfo> list = new ArrayList();
566         list.add(getCellInfoGsm());
567         mSimulatedCommands.setCellInfoList(list);
568         CellInfoHandler cih = new CellInfoHandler(mSSTTestHandler.getLooper());
569 
570         Message rsp = cih.obtainMessage(0x7357);
571 
572         sst.requestAllCellInfo(null, rsp);
573 
574         synchronized (rsp) {
575             if (cih.cellInfoResult == null) rsp.wait(5000);
576         }
577 
578         AsyncResult ar = (AsyncResult) rsp.obj;
579         assertTrue("CellInfo Response Not Received", cih.cellInfoResult != null);
580         assertEquals(getCellInfoGsm(), cih.cellInfoResult.get(0));
581     }
582 
583     @Test
584     @MediumTest
testGetCellInfoResponseTimeout()585     public void testGetCellInfoResponseTimeout() throws InterruptedException {
586         mSimulatedCommands.setCellInfoListBehavior(false);
587         CellInfoHandler cih = new CellInfoHandler(mSSTTestHandler.getLooper());
588 
589         Message rsp = cih.obtainMessage(0x7357);
590 
591         sst.requestAllCellInfo(null, rsp);
592 
593         synchronized (rsp) {
594             if (cih.cellInfoResult == null) rsp.wait(5000);
595         }
596 
597         assertTrue("Spurious CellInfo Response Received", cih.cellInfoResult == null);
598     }
599 
600     @Test
601     @MediumTest
testImsRegState()602     public void testImsRegState() {
603         // Simulate IMS registered
604         mSimulatedCommands.setImsRegistrationState(new int[]{1, PhoneConstants.PHONE_TYPE_GSM});
605 
606         sst.sendMessage(sst.obtainMessage(ServiceStateTracker.EVENT_IMS_STATE_CHANGED, null));
607         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
608 
609         assertTrue(sst.isImsRegistered());
610 
611         // Simulate IMS unregistered
612         mSimulatedCommands.setImsRegistrationState(new int[]{0, PhoneConstants.PHONE_TYPE_GSM});
613 
614         sst.sendMessage(sst.obtainMessage(ServiceStateTracker.EVENT_IMS_STATE_CHANGED, null));
615         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
616 
617         assertFalse(sst.isImsRegistered());
618     }
619 
620     @Test
testOnImsServiceStateChanged()621     public void testOnImsServiceStateChanged() {
622         // The service state of GsmCdmaPhone is STATE_OUT_OF_SERVICE, and IMS is unregistered.
623         ServiceState ss = new ServiceState();
624         ss.setVoiceRegState(ServiceState.STATE_OUT_OF_SERVICE);
625 
626         sst.mSS = ss;
627         sst.sendMessage(sst.obtainMessage(ServiceStateTracker.EVENT_IMS_SERVICE_STATE_CHANGED));
628         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
629 
630         // The listener will be notified that the service state was changed.
631         verify(mPhone).notifyServiceStateChanged(any(ServiceState.class));
632 
633         // The service state of GsmCdmaPhone is STATE_IN_SERVICE, and IMS is registered.
634         ss = new ServiceState();
635         ss.setVoiceRegState(ServiceState.STATE_IN_SERVICE);
636         sst.mSS = ss;
637 
638         sst.sendMessage(sst.obtainMessage(ServiceStateTracker.EVENT_IMS_SERVICE_STATE_CHANGED));
639         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
640 
641         // Nothing happened because the IMS service state was not affected the merged service state.
642         verify(mPhone, times(1)).notifyServiceStateChanged(any(ServiceState.class));
643     }
644 
sendSignalStrength(SignalStrength ss)645     private void sendSignalStrength(SignalStrength ss) {
646         mSimulatedCommands.setSignalStrength(ss);
647         mSimulatedCommands.notifySignalStrength();
648         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
649     }
650 
651     @Test
652     @MediumTest
testSignalStrength()653     public void testSignalStrength() {
654         // Send in GSM Signal Strength Info and expect isGsm == true
655         SignalStrength ss = new SignalStrength(
656                 new CellSignalStrengthCdma(),
657                 new CellSignalStrengthGsm(-53, 0, SignalStrength.INVALID),
658                 new CellSignalStrengthWcdma(),
659                 new CellSignalStrengthTdscdma(),
660                 new CellSignalStrengthLte(),
661                 new CellSignalStrengthNr());
662 
663         sendSignalStrength(ss);
664         assertEquals(sst.getSignalStrength(), ss);
665         assertEquals(sst.getSignalStrength().isGsm(), true);
666 
667         // Send in CDMA+LTE Signal Strength Info and expect isGsm == true
668         ss = new SignalStrength(
669                 new CellSignalStrengthCdma(-90, -12,
670                         SignalStrength.INVALID, SignalStrength.INVALID, SignalStrength.INVALID),
671                 new CellSignalStrengthGsm(),
672                 new CellSignalStrengthWcdma(),
673                 new CellSignalStrengthTdscdma(),
674                 new CellSignalStrengthLte(
675                         -110, -114, -5, 0, SignalStrength.INVALID, SignalStrength.INVALID),
676                 new CellSignalStrengthNr());
677 
678         sendSignalStrength(ss);
679         assertEquals(sst.getSignalStrength(), ss);
680         assertEquals(sst.getSignalStrength().isGsm(), true);
681 
682         // Send in CDMA-only Signal Strength Info and expect isGsm == false
683         ss = new SignalStrength(
684                 new CellSignalStrengthCdma(-90, -12,
685                         SignalStrength.INVALID, SignalStrength.INVALID, SignalStrength.INVALID),
686                 new CellSignalStrengthGsm(),
687                 new CellSignalStrengthWcdma(),
688                 new CellSignalStrengthTdscdma(),
689                 new CellSignalStrengthLte(),
690                 new CellSignalStrengthNr());
691 
692         sendSignalStrength(ss);
693         assertEquals(sst.getSignalStrength(), ss);
694         assertEquals(sst.getSignalStrength().isGsm(), false);
695     }
696 
sendCarrierConfigUpdate()697     private void sendCarrierConfigUpdate() {
698         CarrierConfigManager mockConfigManager = Mockito.mock(CarrierConfigManager.class);
699         when(mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE))
700                 .thenReturn(mockConfigManager);
701         when(mockConfigManager.getConfigForSubId(anyInt())).thenReturn(mBundle);
702 
703         Intent intent = new Intent().setAction(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
704         intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, PHONE_ID);
705         mContext.sendBroadcast(intent);
706         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
707     }
708 
709     @Test
testLteSignalStrengthReportingCriteria()710     public void testLteSignalStrengthReportingCriteria() {
711         SignalStrength ss = new SignalStrength(
712                 new CellSignalStrengthCdma(),
713                 new CellSignalStrengthGsm(),
714                 new CellSignalStrengthWcdma(),
715                 new CellSignalStrengthTdscdma(),
716                 new CellSignalStrengthLte(
717                         -110, /* rssi */
718                         -114, /* rsrp */
719                         -5, /* rsrq */
720                         0, /* rssnr */
721                         SignalStrength.INVALID, /* cqi */
722                         SignalStrength.INVALID /* ta */),
723                 new CellSignalStrengthNr());
724 
725         mBundle.putBoolean(CarrierConfigManager.KEY_USE_ONLY_RSRP_FOR_LTE_SIGNAL_BAR_BOOL,
726                 true);
727 
728         sendCarrierConfigUpdate();
729 
730         mSimulatedCommands.setSignalStrength(ss);
731         mSimulatedCommands.notifySignalStrength();
732         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
733         // Default thresholds are POOR=-115 MODERATE=-105 GOOD=-95 GREAT=-85
734         assertEquals(CellSignalStrength.SIGNAL_STRENGTH_POOR, sst.getSignalStrength().getLevel());
735 
736         int[] lteThresholds = {
737                 -130, // SIGNAL_STRENGTH_POOR
738                 -120, // SIGNAL_STRENGTH_MODERATE
739                 -110, // SIGNAL_STRENGTH_GOOD
740                 -100,  // SIGNAL_STRENGTH_GREAT
741         };
742         mBundle.putIntArray(CarrierConfigManager.KEY_LTE_RSRP_THRESHOLDS_INT_ARRAY,
743                 lteThresholds);
744         sendCarrierConfigUpdate();
745 
746         mSimulatedCommands.setSignalStrength(ss);
747         mSimulatedCommands.notifySignalStrength();
748         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
749         assertEquals(sst.getSignalStrength().getLevel(),
750                 CellSignalStrength.SIGNAL_STRENGTH_MODERATE);
751     }
752 
753     @Test
test5gNrSignalStrengthReportingCriteria_UseSsRsrp()754     public void test5gNrSignalStrengthReportingCriteria_UseSsRsrp() {
755         SignalStrength ss = new SignalStrength(
756                 new CellSignalStrengthCdma(),
757                 new CellSignalStrengthGsm(),
758                 new CellSignalStrengthWcdma(),
759                 new CellSignalStrengthTdscdma(),
760                 new CellSignalStrengthLte(),
761                 new CellSignalStrengthNr(
762                     -139, /** csiRsrp NONE */
763                     -20, /** csiRsrq NONE */
764                     -23, /** CsiSinr NONE */
765                     -44, /** SsRsrp SIGNAL_STRENGTH_GREAT */
766                     -20, /** SsRsrq NONE */
767                     -23) /** SsSinr NONE */
768          );
769 
770         // SSRSRP = 1 << 0
771         mBundle.putInt(CarrierConfigManager.KEY_PARAMETERS_USE_FOR_5G_NR_SIGNAL_BAR_INT,
772                 CellSignalStrengthNr.USE_SSRSRP);
773         sendCarrierConfigUpdate();
774         mSimulatedCommands.setSignalStrength(ss);
775         mSimulatedCommands.notifySignalStrength();
776         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
777         assertEquals(CellSignalStrength.SIGNAL_STRENGTH_GREAT, sst.getSignalStrength().getLevel());
778     }
779 
780     @Test
test5gNrSignalStrengthReportingCriteria_UseSsRsrpAndSsRsrq()781     public void test5gNrSignalStrengthReportingCriteria_UseSsRsrpAndSsRsrq() {
782         SignalStrength ss = new SignalStrength(
783                 new CellSignalStrengthCdma(),
784                 new CellSignalStrengthGsm(),
785                 new CellSignalStrengthWcdma(),
786                 new CellSignalStrengthTdscdma(),
787                 new CellSignalStrengthLte(),
788                 new CellSignalStrengthNr(
789                     -139, /** csiRsrp NONE */
790                     -20, /** csiRsrq NONE */
791                     -23, /** CsiSinr NONE */
792                     -44, /** SsRsrp SIGNAL_STRENGTH_GREAT */
793                     -32, /** SsRsrq NONE */
794                     -23) /** SsSinr NONE */
795         );
796 
797         // SSRSRP = 1 << 0 | SSSINR = 1 << 2
798         mBundle.putInt(CarrierConfigManager.KEY_PARAMETERS_USE_FOR_5G_NR_SIGNAL_BAR_INT,
799                 CellSignalStrengthNr.USE_SSRSRP | CellSignalStrengthNr.USE_SSRSRQ);
800         sendCarrierConfigUpdate();
801         mSimulatedCommands.setSignalStrength(ss);
802         mSimulatedCommands.notifySignalStrength();
803         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
804         assertEquals(CellSignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN,
805                 sst.getSignalStrength().getLevel());
806     }
807 
808     @Test
test5gNrSignalStrengthReportingCriteria_ConfiguredThresholds()809     public void test5gNrSignalStrengthReportingCriteria_ConfiguredThresholds() {
810         SignalStrength ss = new SignalStrength(
811                 new CellSignalStrengthCdma(),
812                 new CellSignalStrengthGsm(),
813                 new CellSignalStrengthWcdma(),
814                 new CellSignalStrengthTdscdma(),
815                 new CellSignalStrengthLte(),
816                 new CellSignalStrengthNr(
817                     -139, /** csiRsrp NONE */
818                     -20, /** csiRsrq NONE */
819                     -23, /** CsiSinr NONE */
820                     -44, /** SsRsrp SIGNAL_STRENGTH_GREAT */
821                     -20, /** SsRsrq NONE */
822                     -23) /** SsSinr NONE */
823         );
824 
825         // SSRSRP = 1 << 0
826         mBundle.putInt(CarrierConfigManager.KEY_PARAMETERS_USE_FOR_5G_NR_SIGNAL_BAR_INT,
827                 CellSignalStrengthNr.USE_SSRSRP);
828         sendCarrierConfigUpdate();
829         mSimulatedCommands.setSignalStrength(ss);
830         mSimulatedCommands.notifySignalStrength();
831         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
832         assertEquals(CellSignalStrength.SIGNAL_STRENGTH_GREAT, sst.getSignalStrength().getLevel());
833 
834         int[] nrSsRsrpThresholds = {
835                 -45, // SIGNAL_STRENGTH_POOR
836                 -40, // SIGNAL_STRENGTH_MODERATE
837                 -37, // SIGNAL_STRENGTH_GOOD
838                 -34,  // SIGNAL_STRENGTH_GREAT
839         };
840         mBundle.putIntArray(CarrierConfigManager.KEY_5G_NR_SSRSRP_THRESHOLDS_INT_ARRAY,
841                 nrSsRsrpThresholds);
842         mBundle.putInt(CarrierConfigManager.KEY_PARAMETERS_USE_FOR_5G_NR_SIGNAL_BAR_INT,
843                 CellSignalStrengthNr.USE_SSRSRP);
844         sendCarrierConfigUpdate();
845         mSimulatedCommands.setSignalStrength(ss);
846         mSimulatedCommands.notifySignalStrength();
847         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
848         assertEquals(CellSignalStrength.SIGNAL_STRENGTH_POOR,
849                 sst.getSignalStrength().getLevel());
850     }
851 
852     @Test
testWcdmaSignalStrengthReportingCriteria()853     public void testWcdmaSignalStrengthReportingCriteria() {
854         SignalStrength ss = new SignalStrength(
855                 new CellSignalStrengthCdma(),
856                 new CellSignalStrengthGsm(),
857                 new CellSignalStrengthWcdma(-79, 0, -85, -5),
858                 new CellSignalStrengthTdscdma(),
859                 new CellSignalStrengthLte(),
860                 new CellSignalStrengthNr());
861 
862         mSimulatedCommands.setSignalStrength(ss);
863         mSimulatedCommands.notifySignalStrength();
864         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
865         assertEquals(sst.getSignalStrength().getLevel(), CellSignalStrength.SIGNAL_STRENGTH_GOOD);
866 
867         int[] wcdmaThresholds = {
868                 -110, // SIGNAL_STRENGTH_POOR
869                 -100, // SIGNAL_STRENGTH_MODERATE
870                 -90, // SIGNAL_STRENGTH_GOOD
871                 -80  // SIGNAL_STRENGTH_GREAT
872         };
873         mBundle.putIntArray(CarrierConfigManager.KEY_WCDMA_RSCP_THRESHOLDS_INT_ARRAY,
874                 wcdmaThresholds);
875         mBundle.putString(
876                 CarrierConfigManager.KEY_WCDMA_DEFAULT_SIGNAL_STRENGTH_MEASUREMENT_STRING,
877                 "rscp");
878         sendCarrierConfigUpdate();
879         mSimulatedCommands.setSignalStrength(ss);
880         mSimulatedCommands.notifySignalStrength();
881         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
882         assertEquals(sst.getSignalStrength().getLevel(), CellSignalStrength.SIGNAL_STRENGTH_GOOD);
883     }
884 
885     @Test
886     @MediumTest
887     // TODO(nharold): we probably should remove support for this procedure (GET_LOC)
testGsmCellLocation()888     public void testGsmCellLocation() {
889         CellIdentityGsm cellIdentityGsm = new CellIdentityGsm(
890                 2, 3, 900, 5, "001", "01", "test", "tst", Collections.emptyList());
891 
892         NetworkRegistrationInfo result = new NetworkRegistrationInfo.Builder()
893                 .setDomain(NetworkRegistrationInfo.DOMAIN_CS)
894                 .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
895                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
896                 .setCellIdentity(cellIdentityGsm)
897                 .setRegisteredPlmn("00101")
898                 .build();
899 
900         sst.sendMessage(sst.obtainMessage(ServiceStateTracker.EVENT_GET_LOC_DONE,
901                 new AsyncResult(null, result, null)));
902 
903         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
904         WorkSource workSource = new WorkSource(Process.myUid(), mContext.getPackageName());
905         GsmCellLocation cl = (GsmCellLocation) sst.getCellIdentity().asCellLocation();
906         assertEquals(2, cl.getLac());
907         assertEquals(3, cl.getCid());
908     }
909 
910     @FlakyTest /* flakes 0.86% of the time */
911     @Test
912     @MediumTest
913     // TODO(nharold): we probably should remove support for this procedure (GET_LOC)
testCdmaCellLocation()914     public void testCdmaCellLocation() {
915         CellIdentityCdma cellIdentityCdma = new CellIdentityCdma(1, 2, 3, 4, 5, "test", "tst");
916 
917         NetworkRegistrationInfo result = new NetworkRegistrationInfo.Builder()
918                 .setDomain(NetworkRegistrationInfo.DOMAIN_CS)
919                 .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
920                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
921                 .setCellIdentity(cellIdentityCdma)
922                 .build();
923 
924         sst.sendMessage(sst.obtainMessage(ServiceStateTracker.EVENT_GET_LOC_DONE,
925                 new AsyncResult(null, result, null)));
926 
927         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
928         WorkSource workSource = new WorkSource(Process.myUid(), mContext.getPackageName());
929         CdmaCellLocation cl = (CdmaCellLocation) sst.getCellIdentity().asCellLocation();
930         assertEquals(5, cl.getBaseStationLatitude());
931         assertEquals(4, cl.getBaseStationLongitude());
932     }
933 
934     @Test
testHasLocationChanged()935     public void testHasLocationChanged() {
936         CellIdentityCdma cellIdentity = null;
937         CellIdentityCdma newCellIdentity = null;
938 
939         boolean hasLocationChanged = (cellIdentity == null ? newCellIdentity != null
940                 : !cellIdentity.isSameCell(newCellIdentity));
941         assertFalse(hasLocationChanged);
942 
943         cellIdentity = new CellIdentityCdma(1, 2, 3, 4, 5, "test", "tst");
944         hasLocationChanged = (cellIdentity == null ? newCellIdentity != null
945                 : !cellIdentity.isSameCell(newCellIdentity));
946         assertTrue(hasLocationChanged);
947 
948         newCellIdentity = new CellIdentityCdma(1, 2, 3, 4, 5, "test", "tst");
949         hasLocationChanged = (cellIdentity == null ? newCellIdentity != null
950                 : !cellIdentity.isSameCell(newCellIdentity));
951         assertFalse(hasLocationChanged);
952     }
953 
954     @Test
955     @MediumTest
testUpdatePhoneType()956     public void testUpdatePhoneType() {
957         doReturn(false).when(mPhone).isPhoneTypeGsm();
958         doReturn(true).when(mPhone).isPhoneTypeCdmaLte();
959         doReturn(CdmaSubscriptionSourceManager.SUBSCRIPTION_FROM_RUIM).when(mCdmaSSM).
960                 getCdmaSubscriptionSource();
961 
962         logd("Calling updatePhoneType");
963         // switch to CDMA
964         sst.updatePhoneType();
965 
966         ArgumentCaptor<Integer> integerArgumentCaptor = ArgumentCaptor.forClass(Integer.class);
967         verify(mRuimRecords).registerForRecordsLoaded(eq(sst), integerArgumentCaptor.capture(),
968                 nullable(Object.class));
969 
970         // response for mRuimRecords.registerForRecordsLoaded()
971         Message msg = Message.obtain();
972         msg.what = integerArgumentCaptor.getValue();
973         msg.obj = new AsyncResult(null, null, null);
974         sst.sendMessage(msg);
975         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
976 
977         // on RUIM_RECORDS_LOADED, sst is expected to call following apis
978         verify(mRuimRecords, times(1)).isProvisioned();
979 
980         // switch back to GSM
981         doReturn(true).when(mPhone).isPhoneTypeGsm();
982         doReturn(false).when(mPhone).isPhoneTypeCdmaLte();
983 
984         // response for mRuimRecords.registerForRecordsLoaded() can be sent after switching to GSM
985         msg = Message.obtain();
986         msg.what = integerArgumentCaptor.getValue();
987         msg.obj = new AsyncResult(null, null, null);
988         sst.sendMessage(msg);
989 
990         // There's no easy way to check if the msg was handled or discarded. Wait to make sure sst
991         // did not crash, and then verify that the functions called records loaded are not called
992         // again
993         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
994 
995         verify(mRuimRecords, times(1)).isProvisioned();
996     }
997 
998     @Test
999     @MediumTest
testRegAndUnregForVoiceRoamingOn()1000     public void testRegAndUnregForVoiceRoamingOn() throws Exception {
1001         sst.registerForVoiceRoamingOn(mTestHandler, EVENT_DATA_ROAMING_ON, null);
1002 
1003         // Enable roaming and trigger events to notify handler registered
1004         doReturn(true).when(mPhone).isPhoneTypeGsm();
1005         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1006         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1007         mSimulatedCommands.notifyNetworkStateChanged();
1008 
1009         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1010 
1011         // verify if registered handler has message posted to it
1012         ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
1013         verify(mTestHandler).sendMessageAtTime(messageArgumentCaptor.capture(), anyLong());
1014         assertEquals(EVENT_DATA_ROAMING_ON, messageArgumentCaptor.getValue().what);
1015 
1016         // Disable roaming
1017         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1018         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1019         mSimulatedCommands.notifyNetworkStateChanged();
1020 
1021         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1022 
1023         // Unregister registrant
1024         sst.unregisterForVoiceRoamingOn(mTestHandler);
1025 
1026         // Enable roaming
1027         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1028         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1029         mSimulatedCommands.notifyNetworkStateChanged();
1030 
1031         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1032 
1033         // verify that no new message posted to handler
1034         verify(mTestHandler, times(1)).sendMessageAtTime(any(Message.class), anyLong());
1035     }
1036 
1037     @Test
1038     @MediumTest
testRegAndUnregForVoiceRoamingOff()1039     public void testRegAndUnregForVoiceRoamingOff() throws Exception {
1040         // Enable roaming
1041         doReturn(true).when(mPhone).isPhoneTypeGsm();
1042         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1043         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1044         mSimulatedCommands.notifyNetworkStateChanged();
1045 
1046         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1047 
1048         sst.registerForVoiceRoamingOff(mTestHandler, EVENT_DATA_ROAMING_OFF, null);
1049 
1050         // Disable roaming
1051         doReturn(true).when(mPhone).isPhoneTypeGsm();
1052         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1053         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1054         mSimulatedCommands.notifyNetworkStateChanged();
1055 
1056         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1057 
1058         // verify if registered handler has message posted to it
1059         ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
1060         verify(mTestHandler).sendMessageAtTime(messageArgumentCaptor.capture(), anyLong());
1061         assertEquals(EVENT_DATA_ROAMING_OFF, messageArgumentCaptor.getValue().what);
1062 
1063         // Enable roaming
1064         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1065         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1066         mSimulatedCommands.notifyNetworkStateChanged();
1067 
1068         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1069 
1070         // Unregister registrant
1071         sst.unregisterForVoiceRoamingOff(mTestHandler);
1072 
1073         // Disable roaming
1074         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1075         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1076         mSimulatedCommands.notifyNetworkStateChanged();
1077 
1078         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1079 
1080         // verify that no new message posted to handler
1081         verify(mTestHandler, times(1)).sendMessageAtTime(any(Message.class), anyLong());
1082     }
1083 
1084     @Test
1085     @MediumTest
testRegAndUnregForDataRoamingOn()1086     public void testRegAndUnregForDataRoamingOn() throws Exception {
1087         sst.registerForDataRoamingOn(mTestHandler, EVENT_DATA_ROAMING_ON, null);
1088 
1089         // Enable roaming and trigger events to notify handler registered
1090         doReturn(true).when(mPhone).isPhoneTypeGsm();
1091         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1092         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1093         mSimulatedCommands.notifyNetworkStateChanged();
1094 
1095         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1096 
1097         // verify if registered handler has message posted to it
1098         ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
1099         verify(mTestHandler).sendMessageAtTime(messageArgumentCaptor.capture(), anyLong());
1100         assertEquals(EVENT_DATA_ROAMING_ON, messageArgumentCaptor.getValue().what);
1101 
1102         // Disable roaming
1103         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1104         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1105         mSimulatedCommands.notifyNetworkStateChanged();
1106 
1107         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1108 
1109         // Unregister registrant
1110         sst.unregisterForDataRoamingOn(mTestHandler);
1111 
1112         // Enable roaming
1113         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1114         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1115         mSimulatedCommands.notifyNetworkStateChanged();
1116 
1117         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1118 
1119         // verify that no new message posted to handler
1120         verify(mTestHandler, times(1)).sendMessageAtTime(any(Message.class), anyLong());
1121     }
1122 
1123     @Test
1124     @MediumTest
testRegAndUnregForDataRoamingOff()1125     public void testRegAndUnregForDataRoamingOff() throws Exception {
1126         // Enable roaming
1127         doReturn(true).when(mPhone).isPhoneTypeGsm();
1128         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1129         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1130         mSimulatedCommands.notifyNetworkStateChanged();
1131 
1132         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1133 
1134         sst.registerForDataRoamingOff(mTestHandler, EVENT_DATA_ROAMING_OFF, null, true);
1135 
1136         // Disable roaming
1137         doReturn(true).when(mPhone).isPhoneTypeGsm();
1138         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1139         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1140         mSimulatedCommands.notifyNetworkStateChanged();
1141 
1142         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1143 
1144         // verify if registered handler has message posted to it
1145         ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
1146         verify(mTestHandler).sendMessageAtTime(messageArgumentCaptor.capture(), anyLong());
1147         assertEquals(EVENT_DATA_ROAMING_OFF, messageArgumentCaptor.getValue().what);
1148 
1149         // Enable roaming
1150         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1151         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1152         mSimulatedCommands.notifyNetworkStateChanged();
1153 
1154         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1155 
1156         // Unregister registrant
1157         sst.unregisterForDataRoamingOff(mTestHandler);
1158 
1159         // Disable roaming
1160         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1161         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
1162         mSimulatedCommands.notifyNetworkStateChanged();
1163 
1164         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1165 
1166         // verify that no new message posted to handler
1167         verify(mTestHandler, times(1)).sendMessageAtTime(any(Message.class), anyLong());
1168     }
1169 
1170     @Test
1171     @MediumTest
testRegAndInvalidregForDataConnAttach()1172     public void testRegAndInvalidregForDataConnAttach() throws Exception {
1173         // Initially set service state out of service
1174         doReturn(true).when(mPhone).isPhoneTypeGsm();
1175         mSimulatedCommands.setVoiceRegState(23);
1176         mSimulatedCommands.setDataRegState(23);
1177         mSimulatedCommands.notifyNetworkStateChanged();
1178 
1179         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1180 
1181         sst.registerForDataConnectionAttached(AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
1182                 mTestHandler, EVENT_DATA_CONNECTION_ATTACHED, null);
1183 
1184         // set service state in service and trigger events to post message on handler
1185         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1186         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1187         mSimulatedCommands.notifyNetworkStateChanged();
1188 
1189         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1190 
1191         // verify if registered handler has message posted to it
1192         ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
1193         verify(mTestHandler).sendMessageAtTime(messageArgumentCaptor.capture(), anyLong());
1194         assertEquals(EVENT_DATA_CONNECTION_ATTACHED, messageArgumentCaptor.getValue().what);
1195 
1196         // set service state out of service
1197         mSimulatedCommands.setVoiceRegState(-1);
1198         mSimulatedCommands.setDataRegState(-1);
1199         mSimulatedCommands.notifyNetworkStateChanged();
1200 
1201         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1202 
1203         // Unregister registrant
1204         sst.unregisterForDataConnectionAttached(AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
1205                 mTestHandler);
1206 
1207         // set service state in service
1208         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1209         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1210         mSimulatedCommands.notifyNetworkStateChanged();
1211 
1212         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1213 
1214         // verify that no new message posted to handler
1215         verify(mTestHandler, times(1)).sendMessageAtTime(any(Message.class), anyLong());
1216     }
1217 
1218     @Test
1219     @MediumTest
testRegAndUnregForDataConnAttach()1220     public void testRegAndUnregForDataConnAttach() throws Exception {
1221         // Initially set service state out of service
1222         doReturn(true).when(mPhone).isPhoneTypeGsm();
1223         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_UNKNOWN);
1224         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_UNKNOWN);
1225         mSimulatedCommands.notifyNetworkStateChanged();
1226 
1227         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1228 
1229         sst.registerForDataConnectionAttached(AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
1230                 mTestHandler, EVENT_DATA_CONNECTION_ATTACHED, null);
1231 
1232         // set service state in service and trigger events to post message on handler
1233         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1234         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1235         mSimulatedCommands.notifyNetworkStateChanged();
1236 
1237         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1238 
1239         // verify if registered handler has message posted to it
1240         ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
1241         verify(mTestHandler).sendMessageAtTime(messageArgumentCaptor.capture(), anyLong());
1242         assertEquals(EVENT_DATA_CONNECTION_ATTACHED, messageArgumentCaptor.getValue().what);
1243 
1244         // set service state out of service
1245         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_UNKNOWN);
1246         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_UNKNOWN);
1247         mSimulatedCommands.notifyNetworkStateChanged();
1248 
1249         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1250 
1251         // Unregister registrant
1252         sst.unregisterForDataConnectionAttached(AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
1253                 mTestHandler);
1254 
1255         // set service state in service
1256         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1257         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1258         mSimulatedCommands.notifyNetworkStateChanged();
1259 
1260         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1261 
1262         // verify that no new message posted to handler
1263         verify(mTestHandler, times(1)).sendMessageAtTime(any(Message.class), anyLong());
1264     }
1265 
1266     @Test
1267     @MediumTest
testRegAndUnregForDataConnDetach()1268     public void testRegAndUnregForDataConnDetach() throws Exception {
1269         // Initially set service state in service
1270         doReturn(true).when(mPhone).isPhoneTypeGsm();
1271         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1272         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1273         mSimulatedCommands.notifyNetworkStateChanged();
1274 
1275         sst.registerForDataConnectionDetached(AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
1276                 mTestHandler, EVENT_DATA_CONNECTION_DETACHED, null);
1277 
1278         // set service state out of service and trigger events to post message on handler
1279         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_UNKNOWN);
1280         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_UNKNOWN);
1281         mSimulatedCommands.notifyNetworkStateChanged();
1282 
1283         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1284 
1285         // verify if registered handler has message posted to it
1286         ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
1287         verify(mTestHandler).sendMessageAtTime(messageArgumentCaptor.capture(), anyLong());
1288         assertEquals(EVENT_DATA_CONNECTION_DETACHED, messageArgumentCaptor.getValue().what);
1289 
1290         // set service state in service
1291         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1292         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1293         mSimulatedCommands.notifyNetworkStateChanged();
1294 
1295         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1296 
1297         // Unregister registrant
1298         sst.unregisterForDataConnectionDetached(AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
1299                 mTestHandler);
1300 
1301         // set service state out of service
1302         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_UNKNOWN);
1303         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_UNKNOWN);
1304         mSimulatedCommands.notifyNetworkStateChanged();
1305 
1306         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1307 
1308         // verify that no new message posted to handler
1309         verify(mTestHandler, times(1)).sendMessageAtTime(any(Message.class), anyLong());
1310     }
1311 
1312     @Test
1313     @MediumTest
testRegisterForVoiceRegStateOrRatChange()1314     public void testRegisterForVoiceRegStateOrRatChange() {
1315         NetworkRegistrationInfo nri = new NetworkRegistrationInfo.Builder()
1316                 .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
1317                 .setDomain(NetworkRegistrationInfo.DOMAIN_CS)
1318                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_LTE)
1319                 .build();
1320         sst.mSS.addNetworkRegistrationInfo(nri);
1321 
1322         sst.registerForVoiceRegStateOrRatChanged(mTestHandler, EVENT_VOICE_RAT_CHANGED, null);
1323 
1324         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1325 
1326         // Verify if message was posted to handler and value of result
1327         ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
1328         verify(mTestHandler).sendMessageAtTime(messageArgumentCaptor.capture(), anyLong());
1329         assertEquals(EVENT_VOICE_RAT_CHANGED, messageArgumentCaptor.getValue().what);
1330         assertEquals(new Pair<Integer, Integer>(ServiceState.STATE_IN_SERVICE,
1331                         ServiceState.RIL_RADIO_TECHNOLOGY_LTE),
1332                 ((AsyncResult)messageArgumentCaptor.getValue().obj).result);
1333     }
1334 
1335     @Test
1336     @MediumTest
testRegisterForDataRegStateOrRatChange()1337     public void testRegisterForDataRegStateOrRatChange() {
1338         NetworkRegistrationInfo nrs = new NetworkRegistrationInfo.Builder()
1339                 .setDomain(NetworkRegistrationInfo.DOMAIN_PS)
1340                 .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
1341                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_LTE)
1342                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
1343                 .build();
1344         sst.mSS.addNetworkRegistrationInfo(nrs);
1345         sst.registerForDataRegStateOrRatChanged(AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
1346                 mTestHandler, EVENT_DATA_RAT_CHANGED, null);
1347 
1348         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1349 
1350         // Verify if message was posted to handler and value of result
1351         ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
1352         verify(mTestHandler).sendMessageAtTime(messageArgumentCaptor.capture(), anyLong());
1353         assertEquals(EVENT_DATA_RAT_CHANGED, messageArgumentCaptor.getValue().what);
1354         assertEquals(new Pair<Integer, Integer>(ServiceState.STATE_IN_SERVICE,
1355                         ServiceState.RIL_RADIO_TECHNOLOGY_LTE),
1356                 ((AsyncResult)messageArgumentCaptor.getValue().obj).result);
1357     }
1358 
1359     @FlakyTest /* flakes 0.43% of the time */
1360     @Test
1361     @MediumTest
testRegAndUnregForNetworkAttached()1362     public void testRegAndUnregForNetworkAttached() throws Exception {
1363         // Initially set service state out of service
1364         doReturn(true).when(mPhone).isPhoneTypeGsm();
1365         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_UNKNOWN);
1366         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_UNKNOWN);
1367         mSimulatedCommands.notifyNetworkStateChanged();
1368 
1369         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1370 
1371         sst.registerForNetworkAttached(mTestHandler, EVENT_REGISTERED_TO_NETWORK, null);
1372 
1373         // set service state in service and trigger events to post message on handler
1374         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1375         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1376         mSimulatedCommands.notifyNetworkStateChanged();
1377 
1378         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1379 
1380         // verify if registered handler has message posted to it
1381         ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
1382         verify(mTestHandler).sendMessageAtTime(messageArgumentCaptor.capture(), anyLong());
1383         assertEquals(EVENT_REGISTERED_TO_NETWORK, messageArgumentCaptor.getValue().what);
1384 
1385         // set service state out of service
1386         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_UNKNOWN);
1387         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_UNKNOWN);
1388         mSimulatedCommands.notifyNetworkStateChanged();
1389 
1390         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1391 
1392         // Unregister registrant
1393         sst.unregisterForNetworkAttached(mTestHandler);
1394 
1395         // set service state in service
1396         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1397         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1398         mSimulatedCommands.notifyNetworkStateChanged();
1399 
1400         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1401 
1402         // verify that no new message posted to handler
1403         verify(mTestHandler, times(1)).sendMessageAtTime(any(Message.class), anyLong());
1404     }
1405 
1406     @Test
1407     @MediumTest
testRegAndInvalidRegForNetworkAttached()1408     public void testRegAndInvalidRegForNetworkAttached() throws Exception {
1409         // Initially set service state out of service
1410         doReturn(true).when(mPhone).isPhoneTypeGsm();
1411         mSimulatedCommands.setVoiceRegState(23);
1412         mSimulatedCommands.setDataRegState(23);
1413         mSimulatedCommands.notifyNetworkStateChanged();
1414 
1415         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1416 
1417         sst.registerForNetworkAttached(mTestHandler, EVENT_REGISTERED_TO_NETWORK, null);
1418 
1419         // set service state in service and trigger events to post message on handler
1420         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1421         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1422         mSimulatedCommands.notifyNetworkStateChanged();
1423 
1424         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1425 
1426         // verify if registered handler has message posted to it
1427         ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
1428         verify(mTestHandler).sendMessageAtTime(messageArgumentCaptor.capture(), anyLong());
1429         assertEquals(EVENT_REGISTERED_TO_NETWORK, messageArgumentCaptor.getValue().what);
1430 
1431         // set service state out of service
1432         mSimulatedCommands.setVoiceRegState(-1);
1433         mSimulatedCommands.setDataRegState(-1);
1434         mSimulatedCommands.notifyNetworkStateChanged();
1435 
1436         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1437 
1438         // Unregister registrant
1439         sst.unregisterForNetworkAttached(mTestHandler);
1440 
1441 
1442         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1443 
1444         sst.registerForNetworkAttached(mTestHandler, EVENT_REGISTERED_TO_NETWORK, null);
1445 
1446         // set service state in service
1447         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1448         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1449         mSimulatedCommands.notifyNetworkStateChanged();
1450 
1451         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1452 
1453         // verify if registered handler has message posted to it
1454         messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
1455         verify(mTestHandler, times(2)).sendMessageAtTime(messageArgumentCaptor.capture(),
1456                 anyLong());
1457         assertEquals(EVENT_REGISTERED_TO_NETWORK, messageArgumentCaptor.getValue().what);
1458     }
1459 
1460     @Test
1461     @MediumTest
testRegisterForPsRestrictedEnabled()1462     public void testRegisterForPsRestrictedEnabled() throws Exception {
1463         sst.mRestrictedState.setPsRestricted(true);
1464         // Since PsRestricted is set to true, registerForPsRestrictedEnabled will
1465         // also post message to handler
1466         sst.registerForPsRestrictedEnabled(mTestHandler, EVENT_PS_RESTRICT_ENABLED, null);
1467 
1468         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1469 
1470         // verify posted message
1471         ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
1472         verify(mTestHandler).sendMessageAtTime(messageArgumentCaptor.capture(), anyLong());
1473         assertEquals(EVENT_PS_RESTRICT_ENABLED, messageArgumentCaptor.getValue().what);
1474     }
1475 
1476     @Test
1477     @MediumTest
testRegisterForPsRestrictedDisabled()1478     public void testRegisterForPsRestrictedDisabled() throws Exception {
1479         sst.mRestrictedState.setPsRestricted(true);
1480         // Since PsRestricted is set to true, registerForPsRestrictedDisabled will
1481         // also post message to handler
1482         sst.registerForPsRestrictedDisabled(mTestHandler, EVENT_PS_RESTRICT_DISABLED, null);
1483 
1484         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1485 
1486         // verify posted message
1487         ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
1488         verify(mTestHandler).sendMessageAtTime(messageArgumentCaptor.capture(), anyLong());
1489         assertEquals(EVENT_PS_RESTRICT_DISABLED, messageArgumentCaptor.getValue().what);
1490     }
1491 
1492     @Test
1493     @MediumTest
testOnRestrictedStateChanged()1494     public void testOnRestrictedStateChanged() throws Exception {
1495         ServiceStateTracker spySst = spy(sst);
1496         doReturn(true).when(mPhone).isPhoneTypeGsm();
1497         doReturn(IccCardApplicationStatus.AppState.APPSTATE_READY).when(
1498                 mUiccCardApplication3gpp).getState();
1499 
1500         ArgumentCaptor<Integer> intArgumentCaptor = ArgumentCaptor.forClass(Integer.class);
1501         verify(mSimulatedCommandsVerifier).setOnRestrictedStateChanged(any(Handler.class),
1502                 intArgumentCaptor.capture(), eq(null));
1503         // Since spy() creates a copy of sst object we need to call
1504         // setOnRestrictedStateChanged() explicitly.
1505         mSimulatedCommands.setOnRestrictedStateChanged(spySst,
1506                 intArgumentCaptor.getValue().intValue(), null);
1507 
1508         // Combination of restricted state and expected notification type.
1509         final int CS_ALL[] = {RILConstants.RIL_RESTRICTED_STATE_CS_ALL,
1510                 ServiceStateTracker.CS_ENABLED};
1511         final int CS_NOR[] = {RILConstants.RIL_RESTRICTED_STATE_CS_NORMAL,
1512                 ServiceStateTracker.CS_NORMAL_ENABLED};
1513         final int CS_EME[] = {RILConstants.RIL_RESTRICTED_STATE_CS_EMERGENCY,
1514                 ServiceStateTracker.CS_EMERGENCY_ENABLED};
1515         final int CS_NON[] = {RILConstants.RIL_RESTRICTED_STATE_NONE,
1516                 ServiceStateTracker.CS_DISABLED};
1517         final int PS_ALL[] = {RILConstants.RIL_RESTRICTED_STATE_PS_ALL,
1518                 ServiceStateTracker.PS_ENABLED};
1519         final int PS_NON[] = {RILConstants.RIL_RESTRICTED_STATE_NONE,
1520                 ServiceStateTracker.PS_DISABLED};
1521 
1522         int notifyCount = 0;
1523         // cs not restricted -> cs emergency/normal restricted
1524         internalCheckForRestrictedStateChange(spySst, ++notifyCount, CS_ALL);
1525         // cs emergency/normal restricted -> cs normal restricted
1526         internalCheckForRestrictedStateChange(spySst, ++notifyCount, CS_NOR);
1527         // cs normal restricted -> cs emergency restricted
1528         internalCheckForRestrictedStateChange(spySst, ++notifyCount, CS_EME);
1529         // cs emergency restricted -> cs not restricted
1530         internalCheckForRestrictedStateChange(spySst, ++notifyCount, CS_NON);
1531         // cs not restricted -> cs normal restricted
1532         internalCheckForRestrictedStateChange(spySst, ++notifyCount, CS_NOR);
1533         // cs normal restricted -> cs emergency/normal restricted
1534         internalCheckForRestrictedStateChange(spySst, ++notifyCount, CS_ALL);
1535         // cs emergency/normal restricted -> cs emergency restricted
1536         internalCheckForRestrictedStateChange(spySst, ++notifyCount, CS_EME);
1537         // cs emergency restricted -> cs emergency/normal restricted
1538         internalCheckForRestrictedStateChange(spySst, ++notifyCount, CS_ALL);
1539         // cs emergency/normal restricted -> cs not restricted
1540         internalCheckForRestrictedStateChange(spySst, ++notifyCount, CS_NON);
1541         // cs not restricted -> cs emergency restricted
1542         internalCheckForRestrictedStateChange(spySst, ++notifyCount, CS_EME);
1543         // cs emergency restricted -> cs normal restricted
1544         internalCheckForRestrictedStateChange(spySst, ++notifyCount, CS_NOR);
1545         // cs normal restricted -> cs not restricted
1546         internalCheckForRestrictedStateChange(spySst, ++notifyCount, CS_NON);
1547 
1548         // ps not restricted -> ps restricted
1549         internalCheckForRestrictedStateChange(spySst, ++notifyCount, PS_ALL);
1550         // ps restricted -> ps not restricted
1551         internalCheckForRestrictedStateChange(spySst, ++notifyCount, PS_NON);
1552     }
1553 
internalCheckForRestrictedStateChange(ServiceStateTracker serviceStateTracker, int times, int[] restrictedState)1554     private void internalCheckForRestrictedStateChange(ServiceStateTracker serviceStateTracker,
1555                 int times, int[] restrictedState) {
1556         mSimulatedCommands.triggerRestrictedStateChanged(restrictedState[0]);
1557         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1558         ArgumentCaptor<Integer> intArgumentCaptor = ArgumentCaptor.forClass(Integer.class);
1559         verify(serviceStateTracker, times(times)).setNotification(intArgumentCaptor.capture());
1560         assertEquals(intArgumentCaptor.getValue().intValue(), restrictedState[1]);
1561     }
1562 
notificationHasTitleSet(Notification n)1563     private boolean notificationHasTitleSet(Notification n) {
1564         // Notification has no methods to check the actual title, but #toString() includes the
1565         // word "tick" if the title is set so we check this as a workaround
1566         return n.toString().contains("tick");
1567     }
1568 
getNotificationTitle(Notification n)1569     private String getNotificationTitle(Notification n) {
1570         return n.extras.getString(Notification.EXTRA_TITLE);
1571     }
1572 
1573     @Test
1574     @SmallTest
testSetPsNotifications()1575     public void testSetPsNotifications() {
1576         int subId = 1;
1577         sst.mSubId = subId;
1578         doReturn(subId).when(mSubInfo).getSubscriptionId();
1579 
1580         doReturn(mSubInfo).when(mSubscriptionController).getActiveSubscriptionInfo(
1581                 anyInt(), anyString(), nullable(String.class));
1582 
1583         final NotificationManager nm = (NotificationManager)
1584                 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
1585         mContextFixture.putBooleanResource(
1586                 R.bool.config_user_notification_of_restrictied_mobile_access, true);
1587         doReturn(new ApplicationInfo()).when(mContext).getApplicationInfo();
1588         Drawable mockDrawable = mock(Drawable.class);
1589         Resources mockResources = mContext.getResources();
1590         when(mockResources.getDrawable(anyInt(), any())).thenReturn(mockDrawable);
1591 
1592         mContextFixture.putResource(com.android.internal.R.string.RestrictedOnDataTitle, "test1");
1593         sst.setNotification(ServiceStateTracker.PS_ENABLED);
1594         ArgumentCaptor<Notification> notificationArgumentCaptor =
1595                 ArgumentCaptor.forClass(Notification.class);
1596         verify(nm).notify(anyString(), anyInt(), notificationArgumentCaptor.capture());
1597         // if the postedNotification has title set then it must have been the correct notification
1598         Notification postedNotification = notificationArgumentCaptor.getValue();
1599         assertTrue(notificationHasTitleSet(postedNotification));
1600         assertEquals("test1", getNotificationTitle(postedNotification));
1601 
1602         sst.setNotification(ServiceStateTracker.PS_DISABLED);
1603         verify(nm).cancel(Integer.toString(sst.mSubId), ServiceStateTracker.PS_NOTIFICATION);
1604     }
1605 
1606     @Test
1607     @SmallTest
testSetCsNotifications()1608     public void testSetCsNotifications() {
1609         int subId = 1;
1610         sst.mSubId = subId;
1611         doReturn(subId).when(mSubInfo).getSubscriptionId();
1612         doReturn(mSubInfo).when(mSubscriptionController)
1613                 .getActiveSubscriptionInfo(anyInt(), anyString(), nullable(String.class));
1614 
1615         final NotificationManager nm = (NotificationManager)
1616                 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
1617         mContextFixture.putBooleanResource(
1618                 R.bool.config_user_notification_of_restrictied_mobile_access, true);
1619         doReturn(new ApplicationInfo()).when(mContext).getApplicationInfo();
1620         Drawable mockDrawable = mock(Drawable.class);
1621         Resources mockResources = mContext.getResources();
1622         when(mockResources.getDrawable(anyInt(), any())).thenReturn(mockDrawable);
1623 
1624         mContextFixture.putResource(com.android.internal.R.string.RestrictedOnAllVoiceTitle,
1625                 "test2");
1626         sst.setNotification(ServiceStateTracker.CS_ENABLED);
1627         ArgumentCaptor<Notification> notificationArgumentCaptor =
1628                 ArgumentCaptor.forClass(Notification.class);
1629         verify(nm).notify(anyString(), anyInt(), notificationArgumentCaptor.capture());
1630         // if the postedNotification has title set then it must have been the correct notification
1631         Notification postedNotification = notificationArgumentCaptor.getValue();
1632         assertTrue(notificationHasTitleSet(postedNotification));
1633         assertEquals("test2", getNotificationTitle(postedNotification));
1634 
1635         sst.setNotification(ServiceStateTracker.CS_DISABLED);
1636         verify(nm).cancel(Integer.toString(sst.mSubId), ServiceStateTracker.CS_NOTIFICATION);
1637     }
1638 
1639     @Test
1640     @SmallTest
testSetCsNormalNotifications()1641     public void testSetCsNormalNotifications() {
1642         int subId = 1;
1643         sst.mSubId = subId;
1644         doReturn(subId).when(mSubInfo).getSubscriptionId();
1645         doReturn(mSubInfo).when(mSubscriptionController)
1646                 .getActiveSubscriptionInfo(anyInt(), anyString(), nullable(String.class));
1647 
1648         final NotificationManager nm = (NotificationManager)
1649                 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
1650         mContextFixture.putBooleanResource(
1651                 R.bool.config_user_notification_of_restrictied_mobile_access, true);
1652         doReturn(new ApplicationInfo()).when(mContext).getApplicationInfo();
1653         Drawable mockDrawable = mock(Drawable.class);
1654         Resources mockResources = mContext.getResources();
1655         when(mockResources.getDrawable(anyInt(), any())).thenReturn(mockDrawable);
1656 
1657         mContextFixture.putResource(com.android.internal.R.string.RestrictedOnNormalTitle, "test3");
1658         sst.setNotification(ServiceStateTracker.CS_NORMAL_ENABLED);
1659         ArgumentCaptor<Notification> notificationArgumentCaptor =
1660                 ArgumentCaptor.forClass(Notification.class);
1661         verify(nm).notify(anyString(), anyInt(), notificationArgumentCaptor.capture());
1662         // if the postedNotification has title set then it must have been the correct notification
1663         Notification postedNotification = notificationArgumentCaptor.getValue();
1664         assertTrue(notificationHasTitleSet(postedNotification));
1665         assertEquals("test3", getNotificationTitle(postedNotification));
1666 
1667         sst.setNotification(ServiceStateTracker.CS_DISABLED);
1668         verify(nm).cancel(Integer.toString(sst.mSubId), ServiceStateTracker.CS_NOTIFICATION);
1669     }
1670 
1671     @Test
1672     @SmallTest
testSetCsEmergencyNotifications()1673     public void testSetCsEmergencyNotifications() {
1674         int subId = 1;
1675         sst.mSubId = subId;
1676         doReturn(subId).when(mSubInfo).getSubscriptionId();
1677         doReturn(mSubInfo).when(mSubscriptionController)
1678                 .getActiveSubscriptionInfo(anyInt(), anyString(), nullable(String.class));
1679 
1680         final NotificationManager nm = (NotificationManager)
1681                 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
1682         mContextFixture.putBooleanResource(
1683                 R.bool.config_user_notification_of_restrictied_mobile_access, true);
1684         doReturn(new ApplicationInfo()).when(mContext).getApplicationInfo();
1685         Drawable mockDrawable = mock(Drawable.class);
1686         Resources mockResources = mContext.getResources();
1687         when(mockResources.getDrawable(anyInt(), any())).thenReturn(mockDrawable);
1688 
1689         mContextFixture.putResource(com.android.internal.R.string.RestrictedOnEmergencyTitle,
1690                 "test4");
1691         sst.setNotification(ServiceStateTracker.CS_EMERGENCY_ENABLED);
1692         ArgumentCaptor<Notification> notificationArgumentCaptor =
1693                 ArgumentCaptor.forClass(Notification.class);
1694         verify(nm).notify(anyString(), anyInt(), notificationArgumentCaptor.capture());
1695         // if the postedNotification has title set then it must have been the correct notification
1696         Notification postedNotification = notificationArgumentCaptor.getValue();
1697         assertTrue(notificationHasTitleSet(postedNotification));
1698         assertEquals("test4", getNotificationTitle(postedNotification));
1699 
1700         sst.setNotification(ServiceStateTracker.CS_DISABLED);
1701         verify(nm).cancel(Integer.toString(sst.mSubId), ServiceStateTracker.CS_NOTIFICATION);
1702         sst.setNotification(ServiceStateTracker.CS_REJECT_CAUSE_ENABLED);
1703     }
1704 
1705     @Test
1706     @SmallTest
testSetNotificationsForGroupedSubs()1707     public void testSetNotificationsForGroupedSubs() {
1708         //if subscription is grouped, no notification should be set whatsoever
1709         int subId = 1;
1710         int otherSubId = 2;
1711         sst.mSubId = otherSubId;
1712         doReturn(subId).when(mSubInfo).getSubscriptionId();
1713 
1714         final NotificationManager nm = (NotificationManager)
1715                 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
1716         mContextFixture.putBooleanResource(
1717                 R.bool.config_user_notification_of_restrictied_mobile_access, true);
1718         doReturn(new ApplicationInfo()).when(mContext).getApplicationInfo();
1719         Drawable mockDrawable = mock(Drawable.class);
1720         Resources mockResources = mContext.getResources();
1721         when(mockResources.getDrawable(anyInt(), any())).thenReturn(mockDrawable);
1722 
1723         mContextFixture.putResource(com.android.internal.R.string.RestrictedOnDataTitle, "test1");
1724 
1725         sst.setNotification(ServiceStateTracker.EVENT_NETWORK_STATE_CHANGED);
1726         ArgumentCaptor<Notification> notificationArgumentCaptor =
1727                 ArgumentCaptor.forClass(Notification.class);
1728         verify(nm, never()).notify(anyString(), anyInt(), notificationArgumentCaptor.capture());
1729 
1730         sst.setNotification(ServiceStateTracker.PS_DISABLED);
1731         verify(nm, never()).cancel(Integer.toString(sst.mSubId),
1732                 ServiceStateTracker.PS_NOTIFICATION);
1733     }
1734 
1735     @Test
1736     @MediumTest
testRegisterForSubscriptionInfoReady()1737     public void testRegisterForSubscriptionInfoReady() {
1738         sst.registerForSubscriptionInfoReady(mTestHandler, EVENT_SUBSCRIPTION_INFO_READY, null);
1739 
1740         // Call functions which would trigger posting of message on test handler
1741         doReturn(false).when(mPhone).isPhoneTypeGsm();
1742         sst.updatePhoneType();
1743         mSimulatedCommands.notifyOtaProvisionStatusChanged();
1744 
1745         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1746 
1747         // verify posted message
1748         ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
1749         verify(mTestHandler).sendMessageAtTime(messageArgumentCaptor.capture(), anyLong());
1750         assertEquals(EVENT_SUBSCRIPTION_INFO_READY, messageArgumentCaptor.getValue().what);
1751     }
1752 
1753     @Test
1754     @MediumTest
testRoamingPhoneTypeSwitch()1755     public void testRoamingPhoneTypeSwitch() {
1756         // Enable roaming
1757         doReturn(true).when(mPhone).isPhoneTypeGsm();
1758 
1759         mSimulatedCommands.setVoiceRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1760         mSimulatedCommands.setDataRegState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
1761         mSimulatedCommands.notifyNetworkStateChanged();
1762 
1763         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1764 
1765         sst.registerForDataRoamingOff(mTestHandler, EVENT_DATA_ROAMING_OFF, null, true);
1766         sst.registerForVoiceRoamingOff(mTestHandler, EVENT_VOICE_ROAMING_OFF, null);
1767         sst.registerForDataConnectionDetached(AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
1768                 mTestHandler, EVENT_DATA_CONNECTION_DETACHED, null);
1769 
1770         // Call functions which would trigger posting of message on test handler
1771         doReturn(false).when(mPhone).isPhoneTypeGsm();
1772         sst.updatePhoneType();
1773 
1774         // verify if registered handler has message posted to it
1775         ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
1776         verify(mTestHandler, atLeast(3)).sendMessageAtTime(
1777                 messageArgumentCaptor.capture(), anyLong());
1778         HashSet<Integer> messageSet = new HashSet<>();
1779         for (Message m : messageArgumentCaptor.getAllValues()) {
1780             messageSet.add(m.what);
1781         }
1782 
1783         assertTrue(messageSet.contains(EVENT_DATA_ROAMING_OFF));
1784         assertTrue(messageSet.contains(EVENT_VOICE_ROAMING_OFF));
1785         assertTrue(messageSet.contains(EVENT_DATA_CONNECTION_DETACHED));
1786     }
1787 
1788     @Test
1789     @SmallTest
testGetDesiredPowerState()1790     public void testGetDesiredPowerState() {
1791         sst.setRadioPower(true);
1792         assertEquals(sst.getDesiredPowerState(), true);
1793     }
1794 
1795     @Test
1796     @SmallTest
testGetCurrentDataRegState()1797     public void testGetCurrentDataRegState() throws Exception {
1798         sst.mSS.setDataRegState(ServiceState.STATE_OUT_OF_SERVICE);
1799         assertEquals(sst.getCurrentDataConnectionState(), ServiceState.STATE_OUT_OF_SERVICE);
1800     }
1801 
1802     @Test
1803     @SmallTest
testIsConcurrentVoiceAndDataAllowed()1804     public void testIsConcurrentVoiceAndDataAllowed() {
1805         doReturn(false).when(mPhone).isPhoneTypeGsm();
1806         sst.mSS.setCssIndicator(1);
1807         assertEquals(true, sst.isConcurrentVoiceAndDataAllowed());
1808         sst.mSS.setCssIndicator(0);
1809         assertEquals(false, sst.isConcurrentVoiceAndDataAllowed());
1810 
1811         doReturn(true).when(mPhone).isPhoneTypeGsm();
1812         NetworkRegistrationInfo nri = new NetworkRegistrationInfo.Builder()
1813                 .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
1814                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_HSPA)
1815                 .setDomain(NetworkRegistrationInfo.DOMAIN_PS)
1816                 .build();
1817         sst.mSS.addNetworkRegistrationInfo(nri);
1818         assertEquals(true, sst.isConcurrentVoiceAndDataAllowed());
1819         nri = new NetworkRegistrationInfo.Builder()
1820                 .setTransportType(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
1821                 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_GPRS)
1822                 .setDomain(NetworkRegistrationInfo.DOMAIN_PS)
1823                 .build();
1824         sst.mSS.addNetworkRegistrationInfo(nri);
1825         assertEquals(false, sst.isConcurrentVoiceAndDataAllowed());
1826         sst.mSS.setCssIndicator(1);
1827         assertEquals(true, sst.isConcurrentVoiceAndDataAllowed());
1828     }
1829 
1830     @Test
1831     @MediumTest
testIsImsRegistered()1832     public void testIsImsRegistered() throws Exception {
1833         mSimulatedCommands.setImsRegistrationState(new int[]{1, PhoneConstants.PHONE_TYPE_GSM});
1834         mSimulatedCommands.notifyImsNetworkStateChanged();
1835         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1836         assertEquals(sst.isImsRegistered(), true);
1837     }
1838 
1839     @Test
1840     @SmallTest
testIsDeviceShuttingDown()1841     public void testIsDeviceShuttingDown() throws Exception {
1842         sst.requestShutdown();
1843         assertEquals(true, sst.isDeviceShuttingDown());
1844     }
1845 
1846     @Test
1847     @SmallTest
testShuttingDownRequest()1848     public void testShuttingDownRequest() throws Exception {
1849         sst.setRadioPower(true);
1850         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1851 
1852         sst.requestShutdown();
1853         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1854         assertFalse(mSimulatedCommands.getRadioState()
1855                 != TelephonyManager.RADIO_POWER_UNAVAILABLE);
1856     }
1857 
1858     @Test
1859     @SmallTest
testShuttingDownRequestWithRadioPowerFailResponse()1860     public void testShuttingDownRequestWithRadioPowerFailResponse() throws Exception {
1861         sst.setRadioPower(true);
1862         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1863 
1864         // Simulate RIL fails the radio power settings.
1865         mSimulatedCommands.setRadioPowerFailResponse(true);
1866         sst.setRadioPower(false);
1867         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1868         assertTrue(mSimulatedCommands.getRadioState() == TelephonyManager.RADIO_POWER_ON);
1869         sst.requestShutdown();
1870         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1871         assertFalse(mSimulatedCommands.getRadioState()
1872                 != TelephonyManager.RADIO_POWER_UNAVAILABLE);
1873     }
1874 
1875     @Test
1876     @SmallTest
testSetTimeFromNITZStr()1877     public void testSetTimeFromNITZStr() throws Exception {
1878         {
1879             // Mock sending incorrect nitz str from RIL
1880             mSimulatedCommands.triggerNITZupdate("38/06/20,00:00:00+0");
1881             waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1882             verify(mNitzStateMachine, times(0)).handleNitzReceived(any());
1883         }
1884         {
1885             // Mock sending correct nitz str from RIL
1886             String nitzStr = "15/06/20,00:00:00+0";
1887             NitzData expectedNitzData = NitzData.parse(nitzStr);
1888             mSimulatedCommands.triggerNITZupdate(nitzStr);
1889             waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1890 
1891             ArgumentCaptor<TimestampedValue<NitzData>> argumentsCaptor =
1892                     ArgumentCaptor.forClass(TimestampedValue.class);
1893             verify(mNitzStateMachine, times(1))
1894                     .handleNitzReceived(argumentsCaptor.capture());
1895 
1896             // Confirm the argument was what we expected.
1897             TimestampedValue<NitzData> actualNitzSignal = argumentsCaptor.getValue();
1898             assertEquals(expectedNitzData, actualNitzSignal.getValue());
1899             assertTrue(actualNitzSignal.getReferenceTimeMillis() <= SystemClock.elapsedRealtime());
1900         }
1901     }
1902 
changeRegState(int state, CellIdentity cid, int rat)1903     private void changeRegState(int state, CellIdentity cid, int rat) {
1904         changeRegState(state, cid, rat, rat);
1905     }
1906 
changeRegState(int state, CellIdentity cid, int voiceRat, int dataRat)1907     private void changeRegState(int state, CellIdentity cid, int voiceRat, int dataRat) {
1908         LteVopsSupportInfo lteVopsSupportInfo =
1909                 new LteVopsSupportInfo(LteVopsSupportInfo.LTE_STATUS_NOT_AVAILABLE,
1910                     LteVopsSupportInfo.LTE_STATUS_NOT_AVAILABLE);
1911         NetworkRegistrationInfo dataResult = new NetworkRegistrationInfo(
1912                 NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
1913                 state, dataRat, 0, false, null, cid, getPlmnFromCellIdentity(cid),
1914                 1, false, false, false, lteVopsSupportInfo);
1915         sst.mPollingContext[0] = 2;
1916         // update data reg state to be in service
1917         sst.sendMessage(sst.obtainMessage(
1918                 ServiceStateTracker.EVENT_POLL_STATE_PS_CELLULAR_REGISTRATION,
1919                 new AsyncResult(sst.mPollingContext, dataResult, null)));
1920         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1921         NetworkRegistrationInfo voiceResult = new NetworkRegistrationInfo(
1922                 NetworkRegistrationInfo.DOMAIN_CS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
1923                 state, voiceRat, 0, false,
1924                 null, cid, getPlmnFromCellIdentity(cid), false, 0, 0, 0);
1925         sst.sendMessage(sst.obtainMessage(
1926                 ServiceStateTracker.EVENT_POLL_STATE_CS_CELLULAR_REGISTRATION,
1927                 new AsyncResult(sst.mPollingContext, voiceResult, null)));
1928         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1929     }
1930 
changeRegStateWithIwlan(int state, CellIdentity cid, int voiceRat, int dataRat, int iwlanState, int iwlanDataRat)1931     private void changeRegStateWithIwlan(int state, CellIdentity cid, int voiceRat, int dataRat,
1932             int iwlanState, int iwlanDataRat) {
1933         LteVopsSupportInfo lteVopsSupportInfo =
1934                 new LteVopsSupportInfo(LteVopsSupportInfo.LTE_STATUS_NOT_AVAILABLE,
1935                         LteVopsSupportInfo.LTE_STATUS_NOT_AVAILABLE);
1936         sst.mPollingContext[0] = 3;
1937 
1938         // PS WWAN
1939         NetworkRegistrationInfo dataResult = new NetworkRegistrationInfo(
1940                 NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
1941                 state, dataRat, 0, false, null, cid, getPlmnFromCellIdentity(cid),
1942                 1, false, false, false, lteVopsSupportInfo);
1943         sst.sendMessage(sst.obtainMessage(
1944                 ServiceStateTracker.EVENT_POLL_STATE_PS_CELLULAR_REGISTRATION,
1945                 new AsyncResult(sst.mPollingContext, dataResult, null)));
1946         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1947 
1948         // CS WWAN
1949         NetworkRegistrationInfo voiceResult = new NetworkRegistrationInfo(
1950                 NetworkRegistrationInfo.DOMAIN_CS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
1951                 state, voiceRat, 0, false, null, cid, getPlmnFromCellIdentity(cid), false, 0, 0, 0);
1952         sst.sendMessage(sst.obtainMessage(
1953                 ServiceStateTracker.EVENT_POLL_STATE_CS_CELLULAR_REGISTRATION,
1954                 new AsyncResult(sst.mPollingContext, voiceResult, null)));
1955         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1956 
1957         // PS WLAN
1958         NetworkRegistrationInfo dataIwlanResult = new NetworkRegistrationInfo(
1959                 NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WLAN,
1960                 iwlanState, iwlanDataRat, 0, false,
1961                 null, null, "", 1, false, false, false, lteVopsSupportInfo);
1962         sst.sendMessage(sst.obtainMessage(
1963                 ServiceStateTracker.EVENT_POLL_STATE_PS_IWLAN_REGISTRATION,
1964                 new AsyncResult(sst.mPollingContext, dataIwlanResult, null)));
1965         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1966     }
1967 
1968     @Test
testPollStateOperatorWhileNotRegistered()1969     public void testPollStateOperatorWhileNotRegistered() {
1970         final String[] oldOpNamesResult = new String[] { "Old carrier long", "Old carrier", "" };
1971         final String[] badOpNamesResult = null;
1972         sst.mPollingContext[0] = 1;
1973         sst.sendMessage(sst.obtainMessage(
1974                 ServiceStateTracker.EVENT_POLL_STATE_OPERATOR,
1975                 new AsyncResult(sst.mPollingContext, oldOpNamesResult, null)));
1976         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1977         assertEquals(oldOpNamesResult[0], sst.getServiceState().getOperatorAlpha());
1978 
1979         // if the device is not registered, the modem returns an invalid operator
1980         sst.mPollingContext[0] = 1;
1981         sst.sendMessage(sst.obtainMessage(
1982                 ServiceStateTracker.EVENT_POLL_STATE_OPERATOR,
1983                 new AsyncResult(sst.mPollingContext, badOpNamesResult, null)));
1984         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
1985         assertEquals(null, sst.getServiceState().getOperatorAlpha());
1986     }
1987 
1988     // Edge and GPRS are grouped under the same family and Edge has higher rate than GPRS.
1989     // Expect no rat update when move from E to G.
1990     @Test
testRatRatchet()1991     public void testRatRatchet() throws Exception {
1992         CellIdentityGsm cellIdentity =
1993                 new CellIdentityGsm(0, 1, 900, 5, "001", "01", "test", "tst",
1994                         Collections.emptyList());
1995         // start on GPRS
1996         changeRegState(1, cellIdentity, 16, 1);
1997         assertEquals(ServiceState.STATE_IN_SERVICE, sst.getCurrentDataConnectionState());
1998         assertEquals(ServiceState.RIL_RADIO_TECHNOLOGY_GPRS, sst.mSS.getRilDataRadioTechnology());
1999         // upgrade to EDGE
2000         changeRegState(1, cellIdentity, 16, 2);
2001         assertEquals(ServiceState.RIL_RADIO_TECHNOLOGY_EDGE, sst.mSS.getRilDataRadioTechnology());
2002         // drop back to GPRS and expect a ratchet
2003         changeRegState(1, cellIdentity, 16, 1);
2004         assertEquals(ServiceState.RIL_RADIO_TECHNOLOGY_EDGE, sst.mSS.getRilDataRadioTechnology());
2005     }
2006 
2007     // Edge and GPRS are grouped under the same family and Edge has higher rate than GPRS.
2008     // Bypass rat rachet when cell id changed. Expect rat update from E to G
2009     @Test
testRatRatchetWithCellChange()2010     public void testRatRatchetWithCellChange() throws Exception {
2011         CellIdentityGsm cellIdentity =
2012                 new CellIdentityGsm(0, 1, 900, 5, "001", "01", "test", "tst",
2013                         Collections.emptyList());
2014         // update data reg state to be in service
2015         changeRegState(1, cellIdentity, 16, 2);
2016         assertEquals(ServiceState.STATE_IN_SERVICE, sst.getCurrentDataConnectionState());
2017         assertEquals(ServiceState.RIL_RADIO_TECHNOLOGY_GSM, sst.mSS.getRilVoiceRadioTechnology());
2018         assertEquals(ServiceState.RIL_RADIO_TECHNOLOGY_EDGE, sst.mSS.getRilDataRadioTechnology());
2019         // RAT: EDGE -> GPRS cell ID: 1 -> 2
2020         cellIdentity = new CellIdentityGsm(0, 2, 900, 5, "001", "01", "test", "tst",
2021                 Collections.emptyList());
2022         changeRegState(1, cellIdentity, 16, 1);
2023         assertEquals(ServiceState.RIL_RADIO_TECHNOLOGY_GPRS, sst.mSS.getRilDataRadioTechnology());
2024 
2025     }
2026 
sendPhyChanConfigChange(int[] bandwidths)2027     private void sendPhyChanConfigChange(int[] bandwidths) {
2028         ArrayList<PhysicalChannelConfig> pc = new ArrayList<>();
2029         int ssType = PhysicalChannelConfig.CONNECTION_PRIMARY_SERVING;
2030         for (int bw : bandwidths) {
2031             pc.add(new PhysicalChannelConfig.Builder()
2032                     .setCellConnectionStatus(ssType)
2033                     .setCellBandwidthDownlinkKhz(bw)
2034                     .build());
2035 
2036             // All cells after the first are secondary serving cells.
2037             ssType = PhysicalChannelConfig.CONNECTION_SECONDARY_SERVING;
2038         }
2039         sst.sendMessage(sst.obtainMessage(ServiceStateTracker.EVENT_PHYSICAL_CHANNEL_CONFIG,
2040                 new AsyncResult(null, pc, null)));
2041         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
2042     }
2043 
sendRegStateUpdateForLteCellId(CellIdentityLte cellId)2044     private void sendRegStateUpdateForLteCellId(CellIdentityLte cellId) {
2045         LteVopsSupportInfo lteVopsSupportInfo =
2046                 new LteVopsSupportInfo(LteVopsSupportInfo.LTE_STATUS_NOT_AVAILABLE,
2047                     LteVopsSupportInfo.LTE_STATUS_NOT_AVAILABLE);
2048         NetworkRegistrationInfo dataResult = new NetworkRegistrationInfo(
2049                 NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
2050                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, TelephonyManager.NETWORK_TYPE_LTE,
2051                 0, false, null, cellId, getPlmnFromCellIdentity(cellId), 1, false, false, false,
2052                 lteVopsSupportInfo);
2053         NetworkRegistrationInfo voiceResult = new NetworkRegistrationInfo(
2054                 NetworkRegistrationInfo.DOMAIN_CS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
2055                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, TelephonyManager.NETWORK_TYPE_LTE,
2056                 0, false, null, cellId, getPlmnFromCellIdentity(cellId), false, 0, 0, 0);
2057         sst.mPollingContext[0] = 2;
2058         // update data reg state to be in service
2059         sst.sendMessage(sst.obtainMessage(
2060                 ServiceStateTracker.EVENT_POLL_STATE_PS_CELLULAR_REGISTRATION,
2061                 new AsyncResult(sst.mPollingContext, dataResult, null)));
2062         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
2063         sst.sendMessage(sst.obtainMessage(
2064                 ServiceStateTracker.EVENT_POLL_STATE_CS_CELLULAR_REGISTRATION,
2065                 new AsyncResult(sst.mPollingContext, voiceResult, null)));
2066         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
2067     }
2068 
2069     @Test
testPhyChanBandwidthUpdatedOnDataRegState()2070     public void testPhyChanBandwidthUpdatedOnDataRegState() throws Exception {
2071         // Cell ID change should trigger hasLocationChanged.
2072         CellIdentityLte cellIdentity5 =
2073                 new CellIdentityLte(1, 1, 5, 1, new int[] {1, 2}, 5000, "001", "01", "test",
2074                         "tst", Collections.emptyList(), null);
2075 
2076         sendPhyChanConfigChange(new int[] {10000});
2077         sendRegStateUpdateForLteCellId(cellIdentity5);
2078         assertTrue(Arrays.equals(new int[] {5000}, sst.mSS.getCellBandwidths()));
2079     }
2080 
2081     @Test
testPhyChanBandwidthNotUpdatedWhenInvalidInCellIdentity()2082     public void testPhyChanBandwidthNotUpdatedWhenInvalidInCellIdentity() throws Exception {
2083         // Cell ID change should trigger hasLocationChanged.
2084         CellIdentityLte cellIdentityInv =
2085                 new CellIdentityLte(1, 1, 5, 1, new int[] {1, 2}, 12345, "001", "01", "test",
2086                         "tst", Collections.emptyList(), null);
2087 
2088         sendPhyChanConfigChange(new int[] {10000});
2089         sendRegStateUpdateForLteCellId(cellIdentityInv);
2090         assertTrue(Arrays.equals(new int[] {10000}, sst.mSS.getCellBandwidths()));
2091     }
2092 
2093     @Test
testPhyChanBandwidthPrefersCarrierAggregationReport()2094     public void testPhyChanBandwidthPrefersCarrierAggregationReport() throws Exception {
2095         // Cell ID change should trigger hasLocationChanged.
2096         CellIdentityLte cellIdentity10 =
2097                 new CellIdentityLte(1, 1, 5, 1, new int[] {1, 2}, 10000, "001", "01", "test",
2098                         "tst", Collections.emptyList(), null);
2099 
2100         sendPhyChanConfigChange(new int[] {10000, 5000});
2101         sendRegStateUpdateForLteCellId(cellIdentity10);
2102         assertTrue(Arrays.equals(new int[] {10000, 5000}, sst.mSS.getCellBandwidths()));
2103     }
2104 
2105     @Test
testPhyChanBandwidthRatchetedOnPhyChanBandwidth()2106     public void testPhyChanBandwidthRatchetedOnPhyChanBandwidth() throws Exception {
2107         // LTE Cell with bandwidth = 10000
2108         CellIdentityLte cellIdentity10 =
2109                 new CellIdentityLte(1, 1, 1, 1, new int[] {1, 2}, 10000, "1", "1", "test",
2110                         "tst", Collections.emptyList(), null);
2111 
2112         sendRegStateUpdateForLteCellId(cellIdentity10);
2113         assertTrue(Arrays.equals(new int[] {10000}, sst.mSS.getCellBandwidths()));
2114         sendPhyChanConfigChange(new int[] {10000, 5000});
2115         assertTrue(Arrays.equals(new int[] {10000, 5000}, sst.mSS.getCellBandwidths()));
2116     }
2117 
2118     @Test
testPhyChanBandwidthResetsOnOos()2119     public void testPhyChanBandwidthResetsOnOos() throws Exception {
2120         testPhyChanBandwidthRatchetedOnPhyChanBandwidth();
2121         LteVopsSupportInfo lteVopsSupportInfo =
2122                 new LteVopsSupportInfo(LteVopsSupportInfo.LTE_STATUS_NOT_AVAILABLE,
2123                     LteVopsSupportInfo.LTE_STATUS_NOT_AVAILABLE);
2124         NetworkRegistrationInfo dataResult = new NetworkRegistrationInfo(
2125                 NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
2126                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING,
2127                 TelephonyManager.NETWORK_TYPE_UNKNOWN, 0, false, null, null, "", 1, false, false,
2128                 false, lteVopsSupportInfo);
2129         NetworkRegistrationInfo voiceResult = new NetworkRegistrationInfo(
2130                 NetworkRegistrationInfo.DOMAIN_CS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
2131                 NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING,
2132                 TelephonyManager.NETWORK_TYPE_UNKNOWN, 0, false, null, null, "", false, 0, 0, 0);
2133         sst.mPollingContext[0] = 2;
2134         sst.sendMessage(sst.obtainMessage(
2135                 ServiceStateTracker.EVENT_POLL_STATE_PS_CELLULAR_REGISTRATION,
2136                 new AsyncResult(sst.mPollingContext, dataResult, null)));
2137         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
2138         sst.sendMessage(sst.obtainMessage(
2139                 ServiceStateTracker.EVENT_POLL_STATE_CS_CELLULAR_REGISTRATION,
2140                 new AsyncResult(sst.mPollingContext, voiceResult, null)));
2141         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
2142         assertTrue(Arrays.equals(new int[0], sst.mSS.getCellBandwidths()));
2143     }
2144 
2145     /**
2146      * Ensure that TransportManager changes due to transport preference changes are picked up in the
2147      * new ServiceState when a poll event occurs. This causes ServiceState#getRilDataRadioTechnology
2148      * to change even though the underlying transports have not changed state.
2149      */
2150     @SmallTest
2151     @Test
testRilDataTechnologyChangeTransportPreference()2152     public void testRilDataTechnologyChangeTransportPreference() {
2153         when(mTransportManager.isAnyApnPreferredOnIwlan()).thenReturn(false);
2154 
2155         // Start state: Cell data only LTE + IWLAN
2156         CellIdentityLte cellIdentity =
2157                 new CellIdentityLte(1, 1, 5, 1, new int[] {1, 2}, 5000, "001", "01", "test",
2158                         "tst", Collections.emptyList(), null);
2159         changeRegStateWithIwlan(
2160                 // WWAN
2161                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, cellIdentity,
2162                 TelephonyManager.NETWORK_TYPE_UNKNOWN, TelephonyManager.NETWORK_TYPE_LTE,
2163                 // WLAN
2164                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME,
2165                 TelephonyManager.NETWORK_TYPE_IWLAN);
2166         assertEquals(ServiceState.RIL_RADIO_TECHNOLOGY_LTE, sst.mSS.getRilDataRadioTechnology());
2167 
2168         sst.registerForDataRegStateOrRatChanged(AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
2169                 mTestHandler, EVENT_DATA_RAT_CHANGED, null);
2170         // transport preference change for a PDN for IWLAN occurred, no registration change, but
2171         // trigger unrelated poll to pick up transport preference.
2172         when(mTransportManager.isAnyApnPreferredOnIwlan()).thenReturn(true);
2173         changeRegStateWithIwlan(
2174                 // WWAN
2175                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, cellIdentity,
2176                 TelephonyManager.NETWORK_TYPE_UNKNOWN, TelephonyManager.NETWORK_TYPE_LTE,
2177                 // WLAN
2178                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME,
2179                 TelephonyManager.NETWORK_TYPE_IWLAN);
2180         // Now check to make sure a transport independent notification occurred for the registrants.
2181         // There will be two, one when the registration happened and another when the transport
2182         // preference changed.
2183         ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
2184         verify(mTestHandler, times(2)).sendMessageAtTime(messageArgumentCaptor.capture(),
2185                 anyLong());
2186         assertEquals(ServiceState.RIL_RADIO_TECHNOLOGY_IWLAN, sst.mSS.getRilDataRadioTechnology());
2187     }
2188 
2189     @Test
testGetServiceProviderNameWithBrandOverride()2190     public void testGetServiceProviderNameWithBrandOverride() {
2191         String brandOverride = "spn from brand override";
2192         doReturn(brandOverride).when(mUiccProfile).getOperatorBrandOverride();
2193 
2194         assertThat(sst.getServiceProviderName()).isEqualTo(brandOverride);
2195     }
2196 
2197     @Test
testGetServiceProviderNameWithCarrierConfigOverride()2198     public void testGetServiceProviderNameWithCarrierConfigOverride() {
2199         String carrierOverride = "spn from carrier override";
2200         mBundle.putBoolean(CarrierConfigManager.KEY_CARRIER_NAME_OVERRIDE_BOOL, true);
2201         mBundle.putString(CarrierConfigManager.KEY_CARRIER_NAME_STRING, carrierOverride);
2202 
2203         assertThat(sst.getServiceProviderName()).isEqualTo(carrierOverride);
2204     }
2205 
2206     @Test
testGetServiceProviderNameWithSimRecord()2207     public void testGetServiceProviderNameWithSimRecord() {
2208         String spn = "spn from sim record";
2209         doReturn(spn).when(mSimRecords).getServiceProviderName();
2210 
2211         assertThat(sst.getServiceProviderName()).isEqualTo(spn);
2212     }
2213 
2214     @Test
testGetServiceProviderNameWithAllSource()2215     public void testGetServiceProviderNameWithAllSource() {
2216         String brandOverride = "spn from brand override";
2217         doReturn(brandOverride).when(mUiccProfile).getOperatorBrandOverride();
2218 
2219         String carrierOverride = "spn from carrier override";
2220         mBundle.putBoolean(CarrierConfigManager.KEY_CARRIER_NAME_OVERRIDE_BOOL, true);
2221         mBundle.putString(CarrierConfigManager.KEY_CARRIER_NAME_STRING, carrierOverride);
2222 
2223         String spn = "spn from sim record";
2224         doReturn(spn).when(mSimRecords).getServiceProviderName();
2225 
2226         // Operator brand override has highest priority
2227         assertThat(sst.getServiceProviderName()).isEqualTo(brandOverride);
2228 
2229         // Remove the brand override
2230         doReturn(null).when(mUiccProfile).getOperatorBrandOverride();
2231 
2232         // Carrier config override has 2nd priority
2233         assertThat(sst.getServiceProviderName()).isEqualTo(carrierOverride);
2234 
2235         // Remove the carrier config override
2236         mBundle.putBoolean(CarrierConfigManager.KEY_CARRIER_NAME_OVERRIDE_BOOL, false);
2237 
2238         // SPN from sim has lowest priority
2239         assertThat(sst.getServiceProviderName()).isEqualTo(spn);
2240     }
2241 
2242     @Test
testGetCarrierNameDisplayConditionWithBrandOverride()2243     public void testGetCarrierNameDisplayConditionWithBrandOverride() {
2244         String brandOverride = "spn from brand override";
2245         doReturn(brandOverride).when(mUiccProfile).getOperatorBrandOverride();
2246 
2247         // Only show spn because all PLMNs will be considered HOME PLMNs.
2248         assertThat(sst.getCarrierNameDisplayBitmask(new ServiceState())).isEqualTo(
2249                 ServiceStateTracker.CARRIER_NAME_DISPLAY_BITMASK_SHOW_SPN);
2250     }
2251 
2252     @Test
2253     @SmallTest
testGetMdn()2254     public void testGetMdn() throws Exception {
2255         doReturn(false).when(mPhone).isPhoneTypeGsm();
2256         doReturn(false).when(mPhone).isPhoneTypeCdma();
2257         doReturn(true).when(mPhone).isPhoneTypeCdmaLte();
2258         doReturn(CdmaSubscriptionSourceManager.SUBSCRIPTION_FROM_RUIM).when(mCdmaSSM)
2259                 .getCdmaSubscriptionSource();
2260 
2261         logd("Calling updatePhoneType");
2262         // switch to CDMA
2263         sst.updatePhoneType();
2264 
2265         // trigger RUIM_RECORDS_LOADED
2266         ArgumentCaptor<Integer> integerArgumentCaptor = ArgumentCaptor.forClass(Integer.class);
2267         verify(mRuimRecords).registerForRecordsLoaded(eq(sst), integerArgumentCaptor.capture(),
2268                 nullable(Object.class));
2269 
2270         // response for mRuimRecords.registerForRecordsLoaded()
2271         Message msg = Message.obtain();
2272         msg.what = integerArgumentCaptor.getValue();
2273         msg.obj = new AsyncResult(null, null, null);
2274         sst.sendMessage(msg);
2275 
2276         // wait for RUIM_RECORDS_LOADED to be handled
2277         waitForHandlerAction(sst, 5000);
2278 
2279         // mdn should be null as nothing populated it
2280         assertEquals(null, sst.getMdnNumber());
2281 
2282         // if ruim is provisioned, mdn should still be null
2283         doReturn(true).when(mRuimRecords).isProvisioned();
2284         assertEquals(null, sst.getMdnNumber());
2285 
2286         // if ruim is not provisioned, and mdn is non null, sst should still return the correct
2287         // value
2288         doReturn(false).when(mRuimRecords).isProvisioned();
2289         String mockMdn = "mockMdn";
2290         doReturn(mockMdn).when(mRuimRecords).getMdn();
2291 
2292         // trigger RUIM_RECORDS_LOADED
2293         Message msg1 = Message.obtain();
2294         msg1.what = integerArgumentCaptor.getValue();
2295         msg1.obj = new AsyncResult(null, null, null);
2296         sst.sendMessage(msg1);
2297 
2298         // wait for RUIM_RECORDS_LOADED to be handled
2299         waitForHandlerAction(sst, 5000);
2300 
2301         assertEquals(mockMdn, sst.getMdnNumber());
2302     }
2303 
2304     @Test
2305     @SmallTest
testOnVopsInfoChanged()2306     public void testOnVopsInfoChanged() {
2307         ServiceState ss = new ServiceState();
2308         ss.setVoiceRegState(ServiceState.STATE_IN_SERVICE);
2309         ss.setDataRegState(ServiceState.STATE_IN_SERVICE);
2310         sst.mSS = ss;
2311 
2312         CellIdentityLte cellId =
2313                 new CellIdentityLte(1, 1, 5, 1, new int[] {1, 2}, 5000, "001", "01", "test",
2314                         "tst", Collections.emptyList(), null);
2315         LteVopsSupportInfo lteVopsSupportInfo =
2316                 new LteVopsSupportInfo(LteVopsSupportInfo.LTE_STATUS_NOT_SUPPORTED,
2317                     LteVopsSupportInfo.LTE_STATUS_NOT_SUPPORTED);
2318 
2319         NetworkRegistrationInfo dataResult = new NetworkRegistrationInfo(
2320                 NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
2321                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME, TelephonyManager.NETWORK_TYPE_LTE,
2322                 0, false, null, cellId, "00101", 1, false, false, false, lteVopsSupportInfo);
2323         sst.mPollingContext[0] = 2;
2324 
2325         sst.sendMessage(sst.obtainMessage(
2326                 ServiceStateTracker.EVENT_POLL_STATE_PS_CELLULAR_REGISTRATION,
2327                 new AsyncResult(sst.mPollingContext, dataResult, null)));
2328         NetworkRegistrationInfo voiceResult = new NetworkRegistrationInfo(
2329                 NetworkRegistrationInfo.DOMAIN_CS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
2330                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME,
2331                 TelephonyManager.NETWORK_TYPE_LTE, 0,
2332                 false, null, cellId, "00101", false, 0, 0, 0);
2333         sst.sendMessage(sst.obtainMessage(
2334                 ServiceStateTracker.EVENT_POLL_STATE_CS_CELLULAR_REGISTRATION,
2335                 new AsyncResult(sst.mPollingContext, voiceResult, null)));
2336 
2337         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
2338         assertEquals(ServiceState.STATE_IN_SERVICE, sst.getCurrentDataConnectionState());
2339         NetworkRegistrationInfo sSnetworkRegistrationInfo =
2340                 sst.mSS.getNetworkRegistrationInfo(NetworkRegistrationInfo.DOMAIN_PS,
2341                         AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
2342         assertEquals(lteVopsSupportInfo,
2343                 sSnetworkRegistrationInfo.getDataSpecificInfo().getLteVopsSupportInfo());
2344 
2345         lteVopsSupportInfo =
2346                 new LteVopsSupportInfo(LteVopsSupportInfo.LTE_STATUS_SUPPORTED,
2347                     LteVopsSupportInfo.LTE_STATUS_NOT_SUPPORTED);
2348         dataResult = new NetworkRegistrationInfo(NetworkRegistrationInfo.DOMAIN_PS,
2349                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
2350                 NetworkRegistrationInfo.REGISTRATION_STATE_HOME,
2351                 TelephonyManager.NETWORK_TYPE_LTE, 0, false, null, cellId, "00101",
2352                 1, false, false, false, lteVopsSupportInfo);
2353         sst.mPollingContext[0] = 1;
2354         sst.sendMessage(sst.obtainMessage(
2355                 ServiceStateTracker.EVENT_POLL_STATE_PS_CELLULAR_REGISTRATION,
2356                 new AsyncResult(sst.mPollingContext, dataResult, null)));
2357         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
2358 
2359         sSnetworkRegistrationInfo =
2360                 sst.mSS.getNetworkRegistrationInfo(2, 1);
2361         assertEquals(lteVopsSupportInfo,
2362                 sSnetworkRegistrationInfo.getDataSpecificInfo().getLteVopsSupportInfo());
2363     }
2364 
2365     @Test
2366     @SmallTest
testEriLoading()2367     public void testEriLoading() {
2368         sst.obtainMessage(GsmCdmaPhone.EVENT_CARRIER_CONFIG_CHANGED, null).sendToTarget();
2369         waitForLastHandlerAction(mSSTTestHandler.getThreadHandler());
2370         verify(mEriManager, times(1)).loadEriFile();
2371     }
2372 
enableCdnr()2373     private void enableCdnr() {
2374         mBundle.putBoolean(
2375                 CarrierConfigManager.KEY_ENABLE_CARRIER_DISPLAY_NAME_RESOLVER_BOOL, true);
2376         sendCarrierConfigUpdate();
2377     }
2378 
2379     @Test
testUpdateSpnDisplay_noService_displayEmergencyCallOnly()2380     public void testUpdateSpnDisplay_noService_displayEmergencyCallOnly() {
2381         enableCdnr();
2382 
2383         // GSM phone
2384         doReturn(true).when(mPhone).isPhoneTypeGsm();
2385 
2386         // Emergency call only
2387         ServiceState ss = new ServiceState();
2388         ss.setVoiceRegState(ServiceState.STATE_EMERGENCY_ONLY);
2389         ss.setDataRegState(ServiceState.STATE_OUT_OF_SERVICE);
2390         ss.setEmergencyOnly(true);
2391         doReturn(ss).when(mSST).getServiceState();
2392 
2393         // update the spn
2394         sst.updateSpnDisplay();
2395 
2396         // Plmn should be shown, and the string is "Emergency call only"
2397         Bundle b = getExtrasFromLastSpnUpdateIntent();
2398         assertThat(b.getString(TelephonyIntents.EXTRA_PLMN))
2399                 .isEqualTo(CARRIER_NAME_DISPLAY_EMERGENCY_CALL);
2400         assertThat(b.getBoolean(TelephonyIntents.EXTRA_SHOW_PLMN)).isTrue();
2401     }
2402 
2403     @Test
testUpdateSpnDisplay_noServiceAndEmergencyCallNotAvailable_displayOOS()2404     public void testUpdateSpnDisplay_noServiceAndEmergencyCallNotAvailable_displayOOS() {
2405         enableCdnr();
2406 
2407         // GSM phone
2408         doReturn(true).when(mPhone).isPhoneTypeGsm();
2409 
2410         // Completely out of service
2411         ServiceState ss = new ServiceState();
2412         ss.setVoiceRegState(ServiceState.STATE_OUT_OF_SERVICE);
2413         ss.setDataRegState(ServiceState.STATE_OUT_OF_SERVICE);
2414         ss.setEmergencyOnly(false);
2415         doReturn(ss).when(mSST).getServiceState();
2416 
2417         // update the spn
2418         sst.updateSpnDisplay();
2419 
2420         // Plmn should be shown, and the string is "No service"
2421         Bundle b = getExtrasFromLastSpnUpdateIntent();
2422         assertThat(b.getString(TelephonyIntents.EXTRA_PLMN))
2423                 .isEqualTo(CARRIER_NAME_DISPLAY_NO_SERVICE);
2424         assertThat(b.getBoolean(TelephonyIntents.EXTRA_SHOW_PLMN)).isTrue();
2425     }
2426 
2427     @Test
testUpdateSpnDisplay_flightMode_displayOOS()2428     public void testUpdateSpnDisplay_flightMode_displayOOS() {
2429         enableCdnr();
2430 
2431         // GSM phone
2432         doReturn(true).when(mPhone).isPhoneTypeGsm();
2433 
2434         // Flight mode
2435         ServiceState ss = new ServiceState();
2436         ss.setVoiceRegState(ServiceState.STATE_POWER_OFF);
2437         ss.setDataRegState(ServiceState.STATE_POWER_OFF);
2438         doReturn(ss).when(mSST).getServiceState();
2439 
2440         // update the spn
2441         sst.updateSpnDisplay();
2442 
2443         // Plmn should be shown, and the string is "No service"
2444         Bundle b = getExtrasFromLastSpnUpdateIntent();
2445         assertThat(b.getString(TelephonyIntents.EXTRA_PLMN))
2446                 .isEqualTo(CARRIER_NAME_DISPLAY_NO_SERVICE);
2447         assertThat(b.getBoolean(TelephonyIntents.EXTRA_SHOW_PLMN)).isTrue();
2448     }
2449 
2450     @Test
testUpdateSpnDisplay_spnNotEmptyAndWifiCallingEnabled_showSpnOnly()2451     public void testUpdateSpnDisplay_spnNotEmptyAndWifiCallingEnabled_showSpnOnly() {
2452         enableCdnr();
2453 
2454         // GSM phone
2455         doReturn(true).when(mPhone).isPhoneTypeGsm();
2456 
2457         // In Service
2458         ServiceState ss = new ServiceState();
2459         ss.setVoiceRegState(ServiceState.STATE_IN_SERVICE);
2460         ss.setDataRegState(ServiceState.STATE_IN_SERVICE);
2461         sst.mSS = ss;
2462 
2463         // wifi-calling is enabled
2464         doReturn(true).when(mPhone).isWifiCallingEnabled();
2465 
2466         // update the spn
2467         sst.updateSpnDisplay();
2468 
2469         // Only spn should be shown
2470         String spn = mBundle.getString(CarrierConfigManager.KEY_CARRIER_NAME_STRING);
2471         Bundle b = getExtrasFromLastSpnUpdateIntent();
2472         assertThat(b.getString(TelephonyIntents.EXTRA_SPN))
2473                 .isEqualTo(String.format(WIFI_CALLING_VOICE_FORMAT, spn));
2474         assertThat(b.getBoolean(TelephonyIntents.EXTRA_SHOW_SPN)).isTrue();
2475         assertThat(b.getString(TelephonyIntents.EXTRA_DATA_SPN))
2476                 .isEqualTo(String.format(WIFI_CALLING_DATA_FORMAT, spn));
2477         assertThat(b.getBoolean(TelephonyIntents.EXTRA_SHOW_PLMN)).isFalse();
2478     }
2479 
2480     @Test
testUpdateSpnDisplay_spnEmptyAndWifiCallingEnabled_showPlmnOnly()2481     public void testUpdateSpnDisplay_spnEmptyAndWifiCallingEnabled_showPlmnOnly() {
2482         // set empty service provider name
2483         mBundle.putString(CarrierConfigManager.KEY_CARRIER_NAME_STRING, "");
2484 
2485         enableCdnr();
2486 
2487         // GSM phone
2488         doReturn(true).when(mPhone).isPhoneTypeGsm();
2489 
2490         // In Service
2491         ServiceState ss = new ServiceState();
2492         ss.setVoiceRegState(ServiceState.STATE_IN_SERVICE);
2493         ss.setDataRegState(ServiceState.STATE_IN_SERVICE);
2494         sst.mSS = ss;
2495 
2496         // wifi-calling is enabled
2497         doReturn(true).when(mPhone).isWifiCallingEnabled();
2498 
2499         // update the spn
2500         sst.updateSpnDisplay();
2501 
2502         // Only plmn should be shown
2503         String plmn = mBundle.getStringArray(CarrierConfigManager.KEY_PNN_OVERRIDE_STRING_ARRAY)[0];
2504         plmn = plmn.split("\\s*,\\s*")[0];
2505         Bundle b = getExtrasFromLastSpnUpdateIntent();
2506         assertThat(b.getString(TelephonyIntents.EXTRA_PLMN))
2507                 .isEqualTo(String.format(WIFI_CALLING_VOICE_FORMAT, plmn));
2508         assertThat(b.getBoolean(TelephonyIntents.EXTRA_SHOW_PLMN)).isTrue();
2509         assertThat(b.getBoolean(TelephonyIntents.EXTRA_SHOW_SPN)).isFalse();
2510     }
2511 
2512     @Test
testUpdateSpnDisplay_inServiceNoWifiCalling_showSpnAndPlmn()2513     public void testUpdateSpnDisplay_inServiceNoWifiCalling_showSpnAndPlmn() {
2514         enableCdnr();
2515 
2516         // GSM phone
2517         doReturn(true).when(mPhone).isPhoneTypeGsm();
2518 
2519         ServiceState ss = new ServiceState();
2520         ss.setVoiceRegState(ServiceState.STATE_IN_SERVICE);
2521         ss.setDataRegState(ServiceState.STATE_IN_SERVICE);
2522         sst.mSS = ss;
2523 
2524         // wifi-calling is disable
2525         doReturn(false).when(mPhone).isWifiCallingEnabled();
2526 
2527         // update the spn
2528         sst.updateSpnDisplay();
2529 
2530         // Show both spn & plmn
2531         String spn = mBundle.getString(CarrierConfigManager.KEY_CARRIER_NAME_STRING);
2532         String plmn = mBundle.getStringArray(CarrierConfigManager.KEY_PNN_OVERRIDE_STRING_ARRAY)[0];
2533         plmn = plmn.split("\\s*,\\s*")[0];
2534         Bundle b = getExtrasFromLastSpnUpdateIntent();
2535         assertThat(b.getString(TelephonyIntents.EXTRA_SPN)).isEqualTo(spn);
2536         assertThat(b.getBoolean(TelephonyIntents.EXTRA_SHOW_SPN)).isTrue();
2537         assertThat(b.getString(TelephonyIntents.EXTRA_PLMN)).isEqualTo(plmn);
2538         assertThat(b.getBoolean(TelephonyIntents.EXTRA_SHOW_PLMN)).isTrue();
2539     }
2540 
2541     @Test
testShouldForceDisplayNoService_forceBasedOnLocale()2542     public void testShouldForceDisplayNoService_forceBasedOnLocale() {
2543         // set up unaffected locale (US) and clear the resource
2544         doReturn("us").when(mLocaleTracker).getCurrentCountry();
2545         mContextFixture.putStringArrayResource(
2546                 com.android.internal.R.array.config_display_no_service_when_sim_unready,
2547                 new String[0]);
2548         assertFalse(sst.shouldForceDisplayNoService());
2549 
2550         // set up the resource to include Germany
2551         mContextFixture.putStringArrayResource(
2552                 com.android.internal.R.array.config_display_no_service_when_sim_unready,
2553                 new String[]{"de"});
2554         doReturn("us").when(mLocaleTracker).getCurrentCountry();
2555         assertFalse(sst.shouldForceDisplayNoService());
2556 
2557         // mock the locale to Germany
2558         doReturn("de").when(mLocaleTracker).getCurrentCountry();
2559         assertTrue(sst.shouldForceDisplayNoService());
2560     }
2561 
getExtrasFromLastSpnUpdateIntent()2562     private Bundle getExtrasFromLastSpnUpdateIntent() {
2563         // Verify the spn update notification was sent
2564         ArgumentCaptor<Intent> intentArgumentCaptor = ArgumentCaptor.forClass(Intent.class);
2565         verify(mContextFixture.getTestDouble(), atLeast(1))
2566                 .sendStickyBroadcastAsUser(intentArgumentCaptor.capture(), eq(UserHandle.ALL));
2567 
2568         List<Intent> intents = intentArgumentCaptor.getAllValues();
2569         return intents.get(intents.size() - 1).getExtras();
2570     }
2571 
makeNetworkRegistrationInfo( int domain, int transport, CellIdentity ci, boolean isRegistered)2572     private static NetworkRegistrationInfo makeNetworkRegistrationInfo(
2573             int domain, int transport, CellIdentity ci, boolean isRegistered) {
2574         return new NetworkRegistrationInfo.Builder()
2575                 .setDomain(domain)
2576                 .setTransportType(transport)
2577                 .setCellIdentity(ci)
2578                 .setRegistrationState(isRegistered
2579                         ? NetworkRegistrationInfo.REGISTRATION_STATE_HOME
2580                         : NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING)
2581                 .build();
2582     }
2583 
2584     @Test
testCellIdentitySort()2585     public void testCellIdentitySort() {
2586         final CellIdentityLte cellIdentityLte =
2587                 new CellIdentityLte(1, 1, 5, 1, new int[] {1, 2}, 5000, "001", "01", "test",
2588                         "tst", Collections.emptyList(), null);
2589         final CellIdentityGsm cellIdentityGsm = new CellIdentityGsm(
2590                 2, 3, 900, 5, "001", "01", "test", "tst", Collections.emptyList());
2591 
2592         ServiceState ss = new ServiceState();
2593         List<CellIdentity> cids;
2594 
2595         // Test that PS WWAN is reported if available
2596         ss.addNetworkRegistrationInfo(makeNetworkRegistrationInfo(
2597                 NetworkRegistrationInfo.DOMAIN_PS,
2598                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
2599                 cellIdentityLte, false));
2600         cids = ServiceStateTracker.getPrioritizedCellIdentities(ss);
2601         assertEquals(cids.size(), 1);
2602         assertEquals(cids.get(0), cellIdentityLte);
2603 
2604         // Test that CS is prioritized over PS
2605         ss.addNetworkRegistrationInfo(makeNetworkRegistrationInfo(
2606                 NetworkRegistrationInfo.DOMAIN_CS,
2607                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
2608                 cellIdentityGsm, false));
2609         cids = ServiceStateTracker.getPrioritizedCellIdentities(ss);
2610         assertEquals(cids.size(), 2);
2611         assertEquals(cids.get(0), cellIdentityGsm);
2612         assertEquals(cids.get(1), cellIdentityLte);
2613 
2614         // Test that WLAN is ignored
2615         ss.addNetworkRegistrationInfo(makeNetworkRegistrationInfo(
2616                 NetworkRegistrationInfo.DOMAIN_PS,
2617                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN,
2618                 cellIdentityGsm, false));
2619         cids = ServiceStateTracker.getPrioritizedCellIdentities(ss);
2620         assertEquals(cids.size(), 2);
2621         assertEquals(cids.get(0), cellIdentityGsm);
2622         assertEquals(cids.get(1), cellIdentityLte);
2623 
2624         // Test that null CellIdentities are ignored
2625         ss.addNetworkRegistrationInfo(makeNetworkRegistrationInfo(
2626                 NetworkRegistrationInfo.DOMAIN_CS,
2627                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN,
2628                 null, false));
2629         cids = ServiceStateTracker.getPrioritizedCellIdentities(ss);
2630         assertEquals(cids.size(), 2);
2631         assertEquals(cids.get(0), cellIdentityGsm);
2632         assertEquals(cids.get(1), cellIdentityLte);
2633 
2634         // Test that registered networks are prioritized over unregistered
2635         ss.addNetworkRegistrationInfo(makeNetworkRegistrationInfo(
2636                 NetworkRegistrationInfo.DOMAIN_PS,
2637                 AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
2638                 cellIdentityLte, true));
2639         cids = ServiceStateTracker.getPrioritizedCellIdentities(ss);
2640         assertEquals(cids.size(), 2);
2641         assertEquals(cids.get(0), cellIdentityLte);
2642         assertEquals(cids.get(1), cellIdentityGsm);
2643     }
2644 }
2645