• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 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 package com.android.internal.telephony.euicc;
17 
18 import static android.telephony.euicc.EuiccCardManager.RESET_OPTION_DELETE_OPERATIONAL_PROFILES;
19 import static android.telephony.euicc.EuiccManager.EUICC_OTA_STATUS_UNAVAILABLE;
20 import static android.telephony.euicc.EuiccManager.SWITCH_WITHOUT_PORT_INDEX_EXCEPTION_ON_DISABLE;
21 
22 import static org.junit.Assert.assertEquals;
23 import static org.junit.Assert.assertFalse;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertNull;
26 import static org.junit.Assert.assertTrue;
27 import static org.mockito.ArgumentMatchers.any;
28 import static org.mockito.ArgumentMatchers.anyBoolean;
29 import static org.mockito.ArgumentMatchers.anyInt;
30 import static org.mockito.ArgumentMatchers.anyString;
31 import static org.mockito.ArgumentMatchers.eq;
32 import static org.mockito.Mockito.doAnswer;
33 import static org.mockito.Mockito.doNothing;
34 import static org.mockito.Mockito.doReturn;
35 import static org.mockito.Mockito.doThrow;
36 import static org.mockito.Mockito.never;
37 import static org.mockito.Mockito.verify;
38 import static org.mockito.Mockito.when;
39 
40 import android.Manifest;
41 import android.annotation.Nullable;
42 import android.app.PendingIntent;
43 import android.compat.testing.PlatformCompatChangeRule;
44 import android.content.Context;
45 import android.content.Intent;
46 import android.content.pm.PackageInfo;
47 import android.content.pm.PackageManager;
48 import android.content.pm.Signature;
49 import android.os.Parcelable;
50 import android.os.RemoteException;
51 import android.provider.Settings;
52 import android.service.euicc.DownloadSubscriptionResult;
53 import android.service.euicc.EuiccService;
54 import android.service.euicc.GetDefaultDownloadableSubscriptionListResult;
55 import android.service.euicc.GetDownloadableSubscriptionMetadataResult;
56 import android.telephony.SubscriptionInfo;
57 import android.telephony.SubscriptionManager;
58 import android.telephony.TelephonyManager;
59 import android.telephony.UiccAccessRule;
60 import android.telephony.UiccCardInfo;
61 import android.telephony.UiccPortInfo;
62 import android.telephony.euicc.DownloadableSubscription;
63 import android.telephony.euicc.EuiccInfo;
64 import android.telephony.euicc.EuiccManager;
65 
66 import androidx.test.runner.AndroidJUnit4;
67 
68 import com.android.internal.telephony.Phone;
69 import com.android.internal.telephony.PhoneFactory;
70 import com.android.internal.telephony.TelephonyTest;
71 import com.android.internal.telephony.euicc.EuiccConnector.GetOtaStatusCommandCallback;
72 import com.android.internal.telephony.euicc.EuiccConnector.OtaStatusChangedCallback;
73 import com.android.internal.telephony.uicc.UiccSlot;
74 
75 import libcore.junit.util.compat.CoreCompatChangeRule.DisableCompatChanges;
76 import libcore.junit.util.compat.CoreCompatChangeRule.EnableCompatChanges;
77 
78 import org.junit.After;
79 import org.junit.Before;
80 import org.junit.Rule;
81 import org.junit.Test;
82 import org.junit.rules.TestRule;
83 import org.junit.runner.RunWith;
84 import org.mockito.Mockito;
85 import org.mockito.invocation.InvocationOnMock;
86 import org.mockito.stubbing.Answer;
87 import org.mockito.stubbing.Stubber;
88 
89 import java.security.MessageDigest;
90 import java.security.NoSuchAlgorithmException;
91 import java.util.ArrayList;
92 import java.util.Arrays;
93 import java.util.Collections;
94 import java.util.List;
95 
96 @RunWith(AndroidJUnit4.class)
97 public class EuiccControllerTest extends TelephonyTest {
98     @Rule
99     public TestRule compatChangeRule = new PlatformCompatChangeRule();
100     private static final DownloadableSubscription SUBSCRIPTION =
101             DownloadableSubscription.forActivationCode("abcde");
102 
103     private static final String PACKAGE_NAME = "test.package";
104     private static final String CARRIER_NAME = "test name";
105     private static final String TEST_PACKAGE_NAME = "com.android.frameworks.telephonytests";
106     private static final byte[] SIGNATURE_BYTES = new byte[] {1, 2, 3, 4, 5};
107 
108     private static final UiccAccessRule ACCESS_RULE;
109     static {
110         try {
111             ACCESS_RULE = new UiccAccessRule(
112                     MessageDigest.getInstance("SHA-256").digest(SIGNATURE_BYTES),
113                     PACKAGE_NAME,
114                     0);
115         } catch (NoSuchAlgorithmException e) {
116             throw new RuntimeException("SHA-256 must exist");
117         }
118     }
119 
120     private static final DownloadableSubscription SUBSCRIPTION_WITH_METADATA =
121             DownloadableSubscription.forActivationCode("abcde");
122     static {
123         SUBSCRIPTION_WITH_METADATA.setCarrierName("test name");
124         SUBSCRIPTION_WITH_METADATA.setAccessRules(
Arrays.asList(new UiccAccessRule[] { ACCESS_RULE })125                 Arrays.asList(new UiccAccessRule[] { ACCESS_RULE }));
126     }
127 
128     private static final String OS_VERSION = "1.0";
129     private static final EuiccInfo EUICC_INFO = new EuiccInfo(OS_VERSION);
130 
131     private static final int SUBSCRIPTION_ID = 12345;
132     private static final String ICC_ID = "54321";
133     private static final int CARD_ID = 25;
134     private static final int REMOVABLE_CARD_ID = 26;
135 
136     // Mocked classes
137     private EuiccConnector mMockConnector;
138     private UiccSlot mUiccSlot;
139 
140     private TestEuiccController mController;
141     private int mSavedEuiccProvisionedValue;
142 
143     private static class TestEuiccController extends EuiccController {
144         // Captured arguments to addResolutionIntent
145         private String mResolutionAction;
146         private EuiccOperation mOp;
147 
148         // Captured arguments to sendResult.
149         private PendingIntent mCallbackIntent;
150         private int mResultCode;
151         private Intent mExtrasIntent;
152 
153         // Whether refreshSubscriptionsAndSendResult was called.
154         private boolean mCalledRefreshSubscriptionsAndSendResult;
155 
156         // Number of OTA status changed.
157         private int mNumOtaStatusChanged;
158 
TestEuiccController(Context context, EuiccConnector connector)159         TestEuiccController(Context context, EuiccConnector connector) {
160             super(context, connector);
161             mNumOtaStatusChanged = 0;
162         }
163 
164         @Override
addResolutionIntent( Intent extrasIntent, String resolutionAction, String callingPackage, int resolvableErrors, boolean confirmationCodeRetried, EuiccOperation op, int cardId, int portIndex, boolean usePortIndex, int subscriptionId)165         public void addResolutionIntent(
166                 Intent extrasIntent, String resolutionAction, String callingPackage,
167                 int resolvableErrors, boolean confirmationCodeRetried, EuiccOperation op,
168                 int cardId, int portIndex, boolean usePortIndex, int subscriptionId) {
169             mResolutionAction = resolutionAction;
170             mOp = op;
171         }
172 
173         @Override
sendResult(PendingIntent callbackIntent, int resultCode, Intent extrasIntent)174         public void sendResult(PendingIntent callbackIntent, int resultCode, Intent extrasIntent) {
175             assertNull("sendResult called twice unexpectedly", mCallbackIntent);
176             mCallbackIntent = callbackIntent;
177             mResultCode = resultCode;
178             mExtrasIntent = extrasIntent;
179         }
180 
181         @Override
refreshSubscriptionsAndSendResult( PendingIntent callbackIntent, int resultCode, Intent extrasIntent)182         public void refreshSubscriptionsAndSendResult(
183                 PendingIntent callbackIntent, int resultCode, Intent extrasIntent) {
184             mCalledRefreshSubscriptionsAndSendResult = true;
185             sendResult(callbackIntent, resultCode, extrasIntent);
186         }
187 
188         @Override
sendOtaStatusChangedBroadcast()189         public void sendOtaStatusChangedBroadcast() {
190             ++mNumOtaStatusChanged;
191         }
192     }
193 
194     @Before
setUp()195     public void setUp() throws Exception {
196         super.setUp(getClass().getSimpleName());
197         mMockConnector = Mockito.mock(EuiccConnector.class);
198         mUiccSlot = Mockito.mock(UiccSlot.class);
199         mController = new TestEuiccController(mContext, mMockConnector);
200 
201         PackageInfo pi = new PackageInfo();
202         pi.packageName = PACKAGE_NAME;
203         pi.signatures = new Signature[] { new Signature(SIGNATURE_BYTES) };
204         when(mPackageManager.getPackageInfo(eq(PACKAGE_NAME), anyInt())).thenReturn(pi);
205 
206         mSavedEuiccProvisionedValue = Settings.Global.getInt(mContext.getContentResolver(),
207                 Settings.Global.EUICC_PROVISIONED, 0);
208         Settings.Global.putInt(mContext.getContentResolver(),
209                 Settings.Global.EUICC_PROVISIONED, 0);
210     }
211 
212     @After
tearDown()213     public void tearDown() throws Exception {
214         Settings.Global.putInt(mContext.getContentResolver(),
215                 Settings.Global.EUICC_PROVISIONED, mSavedEuiccProvisionedValue);
216         mController = null;
217         super.tearDown();
218     }
219 
220     @Test(expected = SecurityException.class)
testGetEid_noPrivileges()221     public void testGetEid_noPrivileges() throws Exception {
222         setGetEidPermissions(false /* hasPhoneStatePrivileged */, false /* hasCarrierPrivileges */);
223         callGetEid(true /* success */, "ABCDE" /* eid */, CARD_ID);
224     }
225 
226     @Test
testGetEid_withPhoneStatePrivileged()227     public void testGetEid_withPhoneStatePrivileged() throws Exception {
228         setGetEidPermissions(true /* hasPhoneStatePrivileged */, false /* hasCarrierPrivileges */);
229         assertEquals("ABCDE", callGetEid(true /* success */, "ABCDE" /* eid */, CARD_ID));
230     }
231 
232     @Test
testGetEid_withCarrierPrivileges()233     public void testGetEid_withCarrierPrivileges() throws Exception {
234         setGetEidPermissions(false /* hasPhoneStatePrivileged */, true /* hasCarrierPrivileges */);
235         assertEquals("ABCDE", callGetEid(true /* success */, "ABCDE" /* eid */, CARD_ID));
236     }
237 
238     @Test
testGetEid_failure()239     public void testGetEid_failure() throws Exception {
240         setGetEidPermissions(true /* hasPhoneStatePrivileged */, false /* hasCarrierPrivileges */);
241         assertNull(callGetEid(false /* success */, null /* eid */, CARD_ID));
242     }
243 
244     @Test
testGetEid_nullReturnValue()245     public void testGetEid_nullReturnValue() throws Exception {
246         setGetEidPermissions(true /* hasPhoneStatePrivileged */, false /* hasCarrierPrivileges */);
247         assertNull(callGetEid(true /* success */, null /* eid */, CARD_ID));
248     }
249 
250     @Test
testGetEid_unsupportedCardId()251     public void testGetEid_unsupportedCardId() throws Exception {
252         setGetEidPermissions(false /* hasPhoneStatePrivileged */, true /* hasCarrierPrivileges */);
253         assertEquals("ABCDE", callGetEid(true /* success */, "ABCDE" /* eid */,
254                 TelephonyManager.UNSUPPORTED_CARD_ID));
255     }
256 
257     @Test(expected = SecurityException.class)
testGetOtaStatus_noPrivileges()258     public void testGetOtaStatus_noPrivileges() {
259         setHasWriteEmbeddedPermission(false /* hasPermission */);
260         callGetOtaStatus(true /* success */, 1 /* status */);
261     }
262 
263     @Test
testGetOtaStatus_withWriteEmbeddedPermission()264     public void testGetOtaStatus_withWriteEmbeddedPermission() {
265         setHasWriteEmbeddedPermission(true /* hasPermission */);
266         assertEquals(1, callGetOtaStatus(true /* success */, 1 /* status */));
267     }
268 
269     @Test
testGetOtaStatus_failure()270     public void testGetOtaStatus_failure() {
271         setHasWriteEmbeddedPermission(true /* hasPermission */);
272         assertEquals(
273                 EUICC_OTA_STATUS_UNAVAILABLE,
274                 callGetOtaStatus(false /* success */, 1 /* status */));
275     }
276 
277     @Test
testStartOtaUpdatingIfNecessary_serviceNotAvailable()278     public void testStartOtaUpdatingIfNecessary_serviceNotAvailable() {
279         setHasWriteEmbeddedPermission(true /* hasPermission */);
280         callStartOtaUpdatingIfNecessary(
281                 false /* serviceAvailable */, EuiccManager.EUICC_OTA_IN_PROGRESS);
282         assertEquals(mController.mNumOtaStatusChanged, 0);
283     }
284 
285     @Test
testStartOtaUpdatingIfNecessary_otaStatusChanged()286     public void testStartOtaUpdatingIfNecessary_otaStatusChanged() {
287         setHasWriteEmbeddedPermission(true /* hasPermission */);
288         callStartOtaUpdatingIfNecessary(
289                 true /* serviceAvailable */, EuiccManager.EUICC_OTA_IN_PROGRESS);
290         callStartOtaUpdatingIfNecessary(
291                 true /* serviceAvailable */, EuiccManager.EUICC_OTA_FAILED);
292         callStartOtaUpdatingIfNecessary(
293                 true /* serviceAvailable */, EuiccManager.EUICC_OTA_SUCCEEDED);
294         callStartOtaUpdatingIfNecessary(
295                 true /* serviceAvailable */, EuiccManager.EUICC_OTA_NOT_NEEDED);
296         callStartOtaUpdatingIfNecessary(
297                 true /* serviceAvailable */, EuiccManager.EUICC_OTA_STATUS_UNAVAILABLE);
298 
299         assertEquals(mController.mNumOtaStatusChanged, 5);
300     }
301 
302 
303     @Test
testGetEuiccInfo_success()304     public void testGetEuiccInfo_success() {
305         assertEquals(OS_VERSION, callGetEuiccInfo(true /* success */, EUICC_INFO).getOsVersion());
306     }
307 
308     @Test
testGetEuiccInfo_failure()309     public void testGetEuiccInfo_failure() {
310         assertNull(callGetEuiccInfo(false /* success */, null /* euiccInfo */));
311     }
312 
313     @Test
testGetEuiccInfo_nullReturnValue()314     public void testGetEuiccInfo_nullReturnValue() {
315         assertNull(callGetEuiccInfo(true /* success */, null /* euiccInfo */));
316     }
317 
318     @Test
testGetDownloadableSubscriptionMetadata_serviceUnavailable()319     public void testGetDownloadableSubscriptionMetadata_serviceUnavailable() throws Exception {
320         setHasWriteEmbeddedPermission(true);
321         callGetDownloadableSubscriptionMetadata(
322                 SUBSCRIPTION, false /* complete */, null /* result */);
323         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
324                 0 /* detailedCode */);
325         verify(mMockConnector).getDownloadableSubscriptionMetadata(anyInt(), anyInt(), any(),
326                 anyBoolean(), anyBoolean(), any());
327     }
328 
329     @Test
testGetDownloadableSubscriptionMetadata_error()330     public void testGetDownloadableSubscriptionMetadata_error() throws Exception {
331         setHasWriteEmbeddedPermission(true);
332         GetDownloadableSubscriptionMetadataResult result =
333                 new GetDownloadableSubscriptionMetadataResult(42, null /* subscription */);
334         callGetDownloadableSubscriptionMetadata(SUBSCRIPTION, true /* complete */, result);
335         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
336                 42 /* detailedCode */);
337     }
338 
339     @Test
testGetDownloadableSubscriptionMetadata_mustDeactivateSim()340     public void testGetDownloadableSubscriptionMetadata_mustDeactivateSim()
341             throws Exception {
342         setHasWriteEmbeddedPermission(true);
343         GetDownloadableSubscriptionMetadataResult result =
344                 new GetDownloadableSubscriptionMetadataResult(
345                         EuiccService.RESULT_MUST_DEACTIVATE_SIM, null /* subscription */);
346         callGetDownloadableSubscriptionMetadata(SUBSCRIPTION, true /* complete */, result);
347         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR,
348                 0 /* detailedCode */);
349         verifyResolutionIntent(EuiccService.ACTION_RESOLVE_DEACTIVATE_SIM,
350                 EuiccOperation.ACTION_GET_METADATA_DEACTIVATE_SIM);
351     }
352 
353     @Test
testGetDownloadableSubscriptionMetadata_success()354     public void testGetDownloadableSubscriptionMetadata_success() throws Exception {
355         setHasWriteEmbeddedPermission(true);
356         GetDownloadableSubscriptionMetadataResult result =
357                 new GetDownloadableSubscriptionMetadataResult(
358                         EuiccService.RESULT_OK, SUBSCRIPTION_WITH_METADATA);
359         callGetDownloadableSubscriptionMetadata(SUBSCRIPTION, true /* complete */, result);
360         Intent intent = verifyIntentSent(
361                 EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_OK, 0 /* detailedCode */);
362         DownloadableSubscription receivedSubscription = intent.getParcelableExtra(
363                 EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_DOWNLOADABLE_SUBSCRIPTION);
364         assertNotNull(receivedSubscription);
365         assertEquals(CARRIER_NAME, receivedSubscription.getCarrierName());
366     }
367 
368     @Test
testGetDefaultDownloadableSubscriptionList_serviceUnavailable()369     public void testGetDefaultDownloadableSubscriptionList_serviceUnavailable() throws Exception {
370         setHasWriteEmbeddedPermission(true);
371         callGetDefaultDownloadableSubscriptionList(false /* complete */, null /* result */);
372         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
373                 0 /* detailedCode */);
374     }
375 
376     @Test
testGetDefaultDownloadableSubscriptionList_error()377     public void testGetDefaultDownloadableSubscriptionList_error() throws Exception {
378         setHasWriteEmbeddedPermission(true);
379         GetDefaultDownloadableSubscriptionListResult result =
380                 new GetDefaultDownloadableSubscriptionListResult(42, null /* subscriptions */);
381         callGetDefaultDownloadableSubscriptionList(true /* complete */, result);
382         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
383                 42 /* detailedCode */);
384         verify(mMockConnector).getDefaultDownloadableSubscriptionList(anyInt(), anyBoolean(),
385                 any());
386     }
387 
388     @Test
testGetDefaultDownloadableSubscriptionList_mustDeactivateSim()389     public void testGetDefaultDownloadableSubscriptionList_mustDeactivateSim()
390             throws Exception {
391         setHasWriteEmbeddedPermission(true);
392         GetDefaultDownloadableSubscriptionListResult result =
393                 new GetDefaultDownloadableSubscriptionListResult(
394                         EuiccService.RESULT_MUST_DEACTIVATE_SIM, null /* subscriptions */);
395         callGetDefaultDownloadableSubscriptionList(true /* complete */, result);
396         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR,
397                 0 /* detailedCode */);
398         verifyResolutionIntent(EuiccService.ACTION_RESOLVE_DEACTIVATE_SIM,
399                 EuiccOperation.ACTION_GET_DEFAULT_LIST_DEACTIVATE_SIM);
400     }
401 
402     @Test
testGetDefaultDownloadableSubscriptionList_success()403     public void testGetDefaultDownloadableSubscriptionList_success() throws Exception {
404         setHasWriteEmbeddedPermission(true);
405         GetDefaultDownloadableSubscriptionListResult result =
406                 new GetDefaultDownloadableSubscriptionListResult(
407                         EuiccService.RESULT_OK,
408                         new DownloadableSubscription[] { SUBSCRIPTION_WITH_METADATA });
409         callGetDefaultDownloadableSubscriptionList(true /* complete */, result);
410         Intent intent = verifyIntentSent(
411                 EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_OK, 0 /* detailedCode */);
412         Parcelable[] receivedSubscriptions = intent.getParcelableArrayExtra(
413                 EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_DOWNLOADABLE_SUBSCRIPTIONS);
414         assertNotNull(receivedSubscriptions);
415         assertEquals(1, receivedSubscriptions.length);
416         assertEquals(CARRIER_NAME,
417                 ((DownloadableSubscription) receivedSubscriptions[0]).getCarrierName());
418     }
419 
420     @Test
421     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testDownloadSubscription_serviceUnavailable()422     public void testDownloadSubscription_serviceUnavailable() throws Exception {
423         setHasWriteEmbeddedPermission(true);
424         setUpUiccSlotData();
425         callDownloadSubscription(
426                 SUBSCRIPTION, true /* switchAfterDownload */, false /* complete */,
427                 0 /* result */,  0 /* resolvableError */, "whatever" /* callingPackage */);
428         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
429                 0 /* detailedCode */);
430         verify(mMockConnector).downloadSubscription(anyInt(), anyInt(),
431                     any(), anyBoolean(), anyBoolean(), any(), any());
432     }
433 
434     @Test
435     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testDownloadSubscription_error()436     public void testDownloadSubscription_error() throws Exception {
437         setHasWriteEmbeddedPermission(true);
438         callDownloadSubscription(SUBSCRIPTION, false /* switchAfterDownload */, true /* complete */,
439                 42,  0 /* resolvableError */, "whatever" /* callingPackage */);
440         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
441                 42 /* detailedCode */);
442     }
443 
444     @Test
445     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testDownloadSubscription_mustDeactivateSim()446     public void testDownloadSubscription_mustDeactivateSim() throws Exception {
447         setHasWriteEmbeddedPermission(true);
448         callDownloadSubscription(SUBSCRIPTION, false /* switchAfterDownload */, true /* complete */,
449                 EuiccService.RESULT_MUST_DEACTIVATE_SIM, 0 /* resolvableError */,
450                 "whatever" /* callingPackage */);
451         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR,
452                 0 /* detailedCode */);
453         verifyResolutionIntent(EuiccService.ACTION_RESOLVE_DEACTIVATE_SIM,
454                 EuiccOperation.ACTION_DOWNLOAD_DEACTIVATE_SIM);
455     }
456 
457     @Test
458     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testDownloadSubscription_needConfirmationCode()459     public void testDownloadSubscription_needConfirmationCode() throws Exception {
460         setHasWriteEmbeddedPermission(true);
461         callDownloadSubscription(SUBSCRIPTION, false /* switchAfterDownload */, true /* complete */,
462                 EuiccService.RESULT_RESOLVABLE_ERRORS, 0b01 /* resolvableError */,
463                 "whatever" /* callingPackage */);
464         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR,
465                 0 /* detailedCode */);
466         verifyResolutionIntent(EuiccService.ACTION_RESOLVE_RESOLVABLE_ERRORS,
467                 EuiccOperation.ACTION_DOWNLOAD_RESOLVABLE_ERRORS);
468     }
469 
470     @Test
471     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testDownloadSubscription_success()472     public void testDownloadSubscription_success() throws Exception {
473         setHasWriteEmbeddedPermission(true);
474         setUpUiccSlotData();
475         callDownloadSubscription(SUBSCRIPTION, true /* switchAfterDownload */, true /* complete */,
476                 EuiccService.RESULT_OK, 0 /* resolvableError */, "whatever" /* callingPackage */);
477         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_OK, 0 /* detailedCode */);
478         // switchAfterDownload = true so no refresh should occur.
479         assertFalse(mController.mCalledRefreshSubscriptionsAndSendResult);
480     }
481 
482     @Test
483     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testDownloadSubscription_noSwitch_success()484     public void testDownloadSubscription_noSwitch_success() throws Exception {
485         setHasWriteEmbeddedPermission(true);
486         callDownloadSubscription(SUBSCRIPTION, false /* switchAfterDownload */, true /* complete */,
487                 EuiccService.RESULT_OK, 0 /* resolvableError */, "whatever" /* callingPackage */);
488         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_OK, 0 /* detailedCode */);
489         assertTrue(mController.mCalledRefreshSubscriptionsAndSendResult);
490     }
491 
492     @Test
493     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testDownloadSubscription_noPrivileges_getMetadata_serviceUnavailable()494     public void testDownloadSubscription_noPrivileges_getMetadata_serviceUnavailable()
495             throws Exception {
496         setHasWriteEmbeddedPermission(false);
497         setUpUiccSlotData();
498         prepareGetDownloadableSubscriptionMetadataCall(false /* complete */, null /* result */);
499         callDownloadSubscription(SUBSCRIPTION, true /* switchAfterDownload */, true /* complete */,
500                 12345, 0 /* resolvableError */, PACKAGE_NAME /* callingPackage */);
501         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR,
502                 0 /* detailedCode */);
503         verify(mMockConnector, never()).downloadSubscription(anyInt(), anyInt(),
504                 any(), anyBoolean(), anyBoolean(), any(), any());
505     }
506 
507     @Test
508     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testDownloadSubscription_noPrivileges_getMetadata_serviceUnavailable_canManageSim()509     public void testDownloadSubscription_noPrivileges_getMetadata_serviceUnavailable_canManageSim()
510             throws Exception {
511         setHasWriteEmbeddedPermission(false);
512         setUpUiccSlotData();
513         prepareGetDownloadableSubscriptionMetadataCall(false /* complete */, null /* result */);
514         setCanManageSubscriptionOnTargetSim(true /* isTargetEuicc */, true /* hasPrivileges */);
515         callDownloadSubscription(SUBSCRIPTION, true /* switchAfterDownload */, true /* complete */,
516                 12345, 0 /* resolvableError */, PACKAGE_NAME /* callingPackage */);
517         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
518                 0 /* detailedCode */);
519         verify(mMockConnector, never()).downloadSubscription(anyInt(), anyInt(),
520                 any(), anyBoolean(), anyBoolean(), any(), any());
521     }
522 
523     @Test
524     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testDownloadSubscription_noPrivileges_getMetadata_error()525     public void testDownloadSubscription_noPrivileges_getMetadata_error()
526             throws Exception {
527         setHasWriteEmbeddedPermission(false);
528         setUpUiccSlotData();
529         GetDownloadableSubscriptionMetadataResult result =
530                 new GetDownloadableSubscriptionMetadataResult(42, null /* subscription */);
531         prepareGetDownloadableSubscriptionMetadataCall(true /* complete */, result);
532         callDownloadSubscription(SUBSCRIPTION, true /* switchAfterDownload */, true /* complete */,
533                 12345, 0 /* resolvableError */, PACKAGE_NAME /* callingPackage */);
534         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR,
535                 0 /* detailedCode */);
536         verify(mMockConnector, never()).downloadSubscription(anyInt(), anyInt(),
537                 any(), anyBoolean(), anyBoolean(), any(), any());
538     }
539 
540     @Test
541     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testDownloadSubscription_noPrivileges_getMetadata_error_canManageSim()542     public void testDownloadSubscription_noPrivileges_getMetadata_error_canManageSim()
543             throws Exception {
544         setHasWriteEmbeddedPermission(false);
545         setUpUiccSlotData();
546         GetDownloadableSubscriptionMetadataResult result =
547                 new GetDownloadableSubscriptionMetadataResult(42, null /* subscription */);
548         prepareGetDownloadableSubscriptionMetadataCall(true /* complete */, result);
549         setCanManageSubscriptionOnTargetSim(true /* isTargetEuicc */, true /* hasPrivileges */);
550         callDownloadSubscription(SUBSCRIPTION, true /* switchAfterDownload */, true /* complete */,
551                 12345, 0 /* resolvableError */, PACKAGE_NAME /* callingPackage */);
552         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
553                 42 /* detailedCode */);
554         verify(mMockConnector, never()).downloadSubscription(anyInt(), anyInt(),
555                 any(), anyBoolean(), anyBoolean(), any(), any());
556     }
557 
558     @Test
559     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testDownloadSubscription_noPrivileges_getMetadata_mustDeactivateSim()560     public void testDownloadSubscription_noPrivileges_getMetadata_mustDeactivateSim()
561             throws Exception {
562         setHasWriteEmbeddedPermission(false);
563         setUpUiccSlotData();
564         GetDownloadableSubscriptionMetadataResult result =
565                 new GetDownloadableSubscriptionMetadataResult(
566                         EuiccService.RESULT_MUST_DEACTIVATE_SIM, null /* subscription */);
567         prepareGetDownloadableSubscriptionMetadataCall(true /* complete */, result);
568         callDownloadSubscription(SUBSCRIPTION, true /* switchAfterDownload */, true /* complete */,
569                 12345, 0 /* resolvableError */, PACKAGE_NAME /* callingPackage */);
570         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR,
571                 0 /* detailedCode */);
572         // In this case we go with the potentially stronger NO_PRIVILEGES consent dialog to avoid
573         // double prompting.
574         verifyResolutionIntent(EuiccService.ACTION_RESOLVE_NO_PRIVILEGES,
575                 EuiccOperation.ACTION_DOWNLOAD_NO_PRIVILEGES_OR_DEACTIVATE_SIM_CHECK_METADATA);
576     }
577 
578     @Test
579     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testDownloadSubscription_noPrivileges_getMetadata_mustDeactivateSim_canManageSim()580     public void testDownloadSubscription_noPrivileges_getMetadata_mustDeactivateSim_canManageSim()
581             throws Exception {
582         setHasWriteEmbeddedPermission(false);
583         setUpUiccSlotData();
584         GetDownloadableSubscriptionMetadataResult result =
585                 new GetDownloadableSubscriptionMetadataResult(
586                     EuiccService.RESULT_MUST_DEACTIVATE_SIM, null /* subscription */);
587         prepareGetDownloadableSubscriptionMetadataCall(true /* complete */, result);
588         setCanManageSubscriptionOnTargetSim(true /* isTargetEuicc */, true /* hasPrivileges */);
589         callDownloadSubscription(SUBSCRIPTION, true /* switchAfterDownload */, true /* complete */,
590                 12345, 0 /* resolvableError */, PACKAGE_NAME /* callingPackage */);
591         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR,
592                 0 /* detailedCode */);
593         // In this case we go with the potentially stronger NO_PRIVILEGES consent dialog to avoid
594         // double prompting.
595         verifyResolutionIntent(EuiccService.ACTION_RESOLVE_DEACTIVATE_SIM,
596                 EuiccOperation.ACTION_DOWNLOAD_NO_PRIVILEGES_OR_DEACTIVATE_SIM_CHECK_METADATA);
597     }
598 
599     @Test
600     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testDownloadSubscription_noPrivileges_hasCarrierPrivileges()601     public void testDownloadSubscription_noPrivileges_hasCarrierPrivileges() throws Exception {
602         setHasWriteEmbeddedPermission(false);
603         setUpUiccSlotData();
604         GetDownloadableSubscriptionMetadataResult result =
605                 new GetDownloadableSubscriptionMetadataResult(
606                         EuiccService.RESULT_OK, SUBSCRIPTION_WITH_METADATA);
607         prepareGetDownloadableSubscriptionMetadataCall(true /* complete */, result);
608         when(mTelephonyManager.getPhoneCount()).thenReturn(1);
609         setHasCarrierPrivilegesOnActiveSubscription(true);
610         callDownloadSubscription(SUBSCRIPTION, true /* switchAfterDownload */, true /* complete */,
611                 EuiccService.RESULT_OK, 0 /* resolvableError */, PACKAGE_NAME /* callingPackage */);
612         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_OK, 0 /* detailedCode */);
613         // switchAfterDownload = true so no refresh should occur.
614         assertFalse(mController.mCalledRefreshSubscriptionsAndSendResult);
615     }
616 
617     @Test
618     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testDownloadSubscription_noPrivileges_hasCarrierPrivileges_multiSim()619     public void testDownloadSubscription_noPrivileges_hasCarrierPrivileges_multiSim()
620             throws Exception {
621         setHasWriteEmbeddedPermission(false);
622         setUpUiccSlotData();
623         GetDownloadableSubscriptionMetadataResult result =
624                 new GetDownloadableSubscriptionMetadataResult(
625                     EuiccService.RESULT_OK, SUBSCRIPTION_WITH_METADATA);
626         prepareGetDownloadableSubscriptionMetadataCall(true /* complete */, result);
627         when(mTelephonyManager.getPhoneCount()).thenReturn(2);
628         setCanManageSubscriptionOnTargetSim(true /* isTargetEuicc */, true /* hasPrivileges */);
629         callDownloadSubscription(SUBSCRIPTION, true /* switchAfterDownload */, true /* complete */,
630                 EuiccService.RESULT_OK, 0 /* resolvableError */, PACKAGE_NAME /* callingPackage */);
631         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_OK, 0 /* detailedCode */);
632         // switchAfterDownload = true so no refresh should occur.
633         assertFalse(mController.mCalledRefreshSubscriptionsAndSendResult);
634     }
635 
636     @Test
637     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testDownloadSubscription_noPrivileges_hasCarrierPrivileges_needsConsent()638     public void testDownloadSubscription_noPrivileges_hasCarrierPrivileges_needsConsent()
639             throws Exception {
640         setHasWriteEmbeddedPermission(false);
641         setUpUiccSlotData();
642         GetDownloadableSubscriptionMetadataResult result =
643                 new GetDownloadableSubscriptionMetadataResult(
644                         EuiccService.RESULT_OK, SUBSCRIPTION_WITH_METADATA);
645         prepareGetDownloadableSubscriptionMetadataCall(true /* complete */, result);
646         when(mTelephonyManager.getPhoneCount()).thenReturn(1);
647         setHasCarrierPrivilegesOnActiveSubscription(false);
648         callDownloadSubscription(SUBSCRIPTION, true /* switchAfterDownload */, true /* complete */,
649                 12345, 0 /* resolvableError */, PACKAGE_NAME /* callingPackage */);
650         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR,
651                 0 /* detailedCode */);
652         verify(mMockConnector, never()).downloadSubscription(anyInt(), anyInt(),
653                 any(), anyBoolean(), anyBoolean(), any(), any());
654         verifyResolutionIntent(EuiccService.ACTION_RESOLVE_NO_PRIVILEGES,
655                 EuiccOperation.ACTION_DOWNLOAD_NO_PRIVILEGES_OR_DEACTIVATE_SIM_CHECK_METADATA);
656     }
657 
658     @Test
659     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testDownloadSubscription_noPrivileges_hasCarrierPrivileges_needsConsent_multiSim()660     public void testDownloadSubscription_noPrivileges_hasCarrierPrivileges_needsConsent_multiSim()
661             throws Exception {
662         setHasWriteEmbeddedPermission(false);
663         setUpUiccSlotData();
664         GetDownloadableSubscriptionMetadataResult result =
665                 new GetDownloadableSubscriptionMetadataResult(
666                     EuiccService.RESULT_OK, SUBSCRIPTION_WITH_METADATA);
667         prepareGetDownloadableSubscriptionMetadataCall(true /* complete */, result);
668         when(mTelephonyManager.getPhoneCount()).thenReturn(2);
669         setCanManageSubscriptionOnTargetSim(true /* isTargetEuicc */, false /* hasPrivileges */);
670         callDownloadSubscription(SUBSCRIPTION, true /* switchAfterDownload */, true /* complete */,
671                 12345, 0 /* resolvableError */, PACKAGE_NAME /* callingPackage */);
672         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR,
673                 0 /* detailedCode */);
674         verify(mMockConnector, never()).downloadSubscription(anyInt(), anyInt(),
675                 any(), anyBoolean(), anyBoolean(), any(), any());
676         verifyResolutionIntent(EuiccService.ACTION_RESOLVE_NO_PRIVILEGES,
677                 EuiccOperation.ACTION_DOWNLOAD_NO_PRIVILEGES_OR_DEACTIVATE_SIM_CHECK_METADATA);
678     }
679 
680     @Test
681     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testDownloadSubscription_noPriv_hasCarrierPrivi_needsConsent_multiSim_targetPsim()682     public void testDownloadSubscription_noPriv_hasCarrierPrivi_needsConsent_multiSim_targetPsim()
683             throws Exception {
684         setHasWriteEmbeddedPermission(false);
685         setUpUiccSlotData();
686         GetDownloadableSubscriptionMetadataResult result =
687                 new GetDownloadableSubscriptionMetadataResult(
688                     EuiccService.RESULT_OK, SUBSCRIPTION_WITH_METADATA);
689         prepareGetDownloadableSubscriptionMetadataCall(true /* complete */, result);
690         when(mTelephonyManager.getPhoneCount()).thenReturn(2);
691         setCanManageSubscriptionOnTargetSim(false /* isTargetEuicc */, true /* hasPrivileges */);
692         callDownloadSubscription(SUBSCRIPTION, true /* switchAfterDownload */, true /* complete */,
693                 12345, 0 /* resolvableError */, PACKAGE_NAME /* callingPackage */);
694         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR,
695                 0 /* detailedCode */);
696         verify(mMockConnector, never()).downloadSubscription(anyInt(), anyInt(),
697                 any(), anyBoolean(), anyBoolean(), any(), any());
698         verifyResolutionIntent(EuiccService.ACTION_RESOLVE_NO_PRIVILEGES,
699                 EuiccOperation.ACTION_DOWNLOAD_NO_PRIVILEGES_OR_DEACTIVATE_SIM_CHECK_METADATA);
700     }
701 
702     @Test
703     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testDownloadSubscription_noPrivileges_noCarrierPrivileges()704     public void testDownloadSubscription_noPrivileges_noCarrierPrivileges() throws Exception {
705         setHasWriteEmbeddedPermission(false);
706         setUpUiccSlotData();
707         GetDownloadableSubscriptionMetadataResult result =
708                 new GetDownloadableSubscriptionMetadataResult(
709                         EuiccService.RESULT_OK, SUBSCRIPTION_WITH_METADATA);
710         prepareGetDownloadableSubscriptionMetadataCall(true /* complete */, result);
711         PackageInfo pi = new PackageInfo();
712         pi.packageName = PACKAGE_NAME;
713         pi.signatures = new Signature[] { new Signature(new byte[] { 5, 4, 3, 2, 1 }) };
714         when(mPackageManager.getPackageInfo(eq(PACKAGE_NAME), anyInt())).thenReturn(pi);
715         callDownloadSubscription(SUBSCRIPTION, true /* switchAfterDownload */, true /* complete */,
716                 12345, 0 /* resolvableError */, PACKAGE_NAME /* callingPackage */);
717         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR,
718                 0 /* detailedCode */);
719         verify(mTelephonyManager, never()).checkCarrierPrivilegesForPackage(PACKAGE_NAME);
720         verify(mMockConnector, never()).downloadSubscription(anyInt(), anyInt(),
721                 any(), anyBoolean(), anyBoolean(), any(), any());
722     }
723 
724     @Test
725     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testDownloadSubscription_noPrivileges_noCarrierPrivileges_canManagerTargetSim()726     public void testDownloadSubscription_noPrivileges_noCarrierPrivileges_canManagerTargetSim()
727             throws Exception {
728         setHasWriteEmbeddedPermission(false);
729         setUpUiccSlotData();
730         GetDownloadableSubscriptionMetadataResult result =
731                 new GetDownloadableSubscriptionMetadataResult(
732                     EuiccService.RESULT_OK, SUBSCRIPTION_WITH_METADATA);
733         prepareGetDownloadableSubscriptionMetadataCall(true /* complete */, result);
734         PackageInfo pi = new PackageInfo();
735         pi.packageName = PACKAGE_NAME;
736         pi.signatures = new Signature[] { new Signature(new byte[] { 5, 4, 3, 2, 1 }) };
737         when(mPackageManager.getPackageInfo(eq(PACKAGE_NAME), anyInt())).thenReturn(pi);
738         setCanManageSubscriptionOnTargetSim(true /* isTargetEuicc */, true /* hasPrivileges */);
739         callDownloadSubscription(SUBSCRIPTION, true /* switchAfterDownload */, true /* complete */,
740                 12345, 0 /* resolvableError */, PACKAGE_NAME /* callingPackage */);
741         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
742                 0 /* detailedCode */);
743         verify(mTelephonyManager, never()).checkCarrierPrivilegesForPackage(PACKAGE_NAME);
744         verify(mMockConnector, never()).downloadSubscription(anyInt(), anyInt(),
745                 any(), anyBoolean(), anyBoolean(), any(), any());
746     }
747 
748     @Test
testDeleteSubscription_noSuchSubscription()749     public void testDeleteSubscription_noSuchSubscription() throws Exception {
750         setHasWriteEmbeddedPermission(true);
751         callDeleteSubscription(
752                 SUBSCRIPTION_ID, ICC_ID, false /* complete */,
753                 0 /* result */, "whatever" /* callingPackage */);
754         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
755                 0 /* detailedCode */);
756         verify(mMockConnector, never()).deleteSubscription(anyInt(), anyString(), any());
757     }
758 
759     @Test
testDeleteSubscription_serviceUnavailable()760     public void testDeleteSubscription_serviceUnavailable() throws Exception {
761         setHasWriteEmbeddedPermission(true);
762         prepareOperationSubscription(false /* hasPrivileges */);
763         callDeleteSubscription(
764                 SUBSCRIPTION_ID, ICC_ID, false /* complete */,
765                 0 /* result */, "whatever" /* callingPackage */);
766         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
767                 0 /* detailedCode */);
768     }
769 
770     @Test
testDeleteSubscription_error()771     public void testDeleteSubscription_error() throws Exception {
772         setHasWriteEmbeddedPermission(true);
773         prepareOperationSubscription(false /* hasPrivileges */);
774         callDeleteSubscription(
775                 SUBSCRIPTION_ID, ICC_ID, true /* complete */,
776                 42 /* result */, "whatever" /* callingPackage */);
777         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
778                 42 /* detailedCode */);
779     }
780 
781     @Test
testDeleteSubscription_success()782     public void testDeleteSubscription_success() throws Exception {
783         setHasWriteEmbeddedPermission(true);
784         prepareOperationSubscription(false /* hasPrivileges */);
785         callDeleteSubscription(
786                 SUBSCRIPTION_ID, ICC_ID, true /* complete */,
787                 EuiccService.RESULT_OK, "whatever" /* callingPackage */);
788         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_OK, 0 /* detailedCode */);
789         assertTrue(mController.mCalledRefreshSubscriptionsAndSendResult);
790     }
791 
792     @Test
testGetResolvedPortIndexForSubscriptionSwitchWithOutMEP()793     public void testGetResolvedPortIndexForSubscriptionSwitchWithOutMEP() throws Exception {
794         setUpUiccSlotData();
795         assertEquals(TelephonyManager.DEFAULT_PORT_INDEX,
796                 mController.getResolvedPortIndexForSubscriptionSwitch(CARD_ID));
797     }
798 
799     @Test
testGetResolvedPortIndexForSubscriptionSwitchWithMEP()800     public void testGetResolvedPortIndexForSubscriptionSwitchWithMEP() throws Exception {
801         setUpUiccSlotDataWithMEP();
802         when(mUiccSlot.getPortList()).thenReturn(new int[]{0, 1});
803         when(mUiccSlot.isPortActive(TelephonyManager.DEFAULT_PORT_INDEX)).thenReturn(false);
804         when(mUiccSlot.isPortActive(1)).thenReturn(true);
805         when(mTelephonyManager.getActiveModemCount()).thenReturn(2);
806         assertEquals(1, mController.getResolvedPortIndexForSubscriptionSwitch(CARD_ID));
807     }
808 
809     @Test
testGetResolvedPortIndexForSubscriptionSwitchWithUiccSlotNull()810     public void testGetResolvedPortIndexForSubscriptionSwitchWithUiccSlotNull() throws Exception {
811         assertEquals(TelephonyManager.DEFAULT_PORT_INDEX,
812                 mController.getResolvedPortIndexForSubscriptionSwitch(CARD_ID));
813     }
814 
815     @Test
testGetResolvedPortIndexForSubscriptionSwitchWithPsimActiveAndSS()816     public void testGetResolvedPortIndexForSubscriptionSwitchWithPsimActiveAndSS()
817             throws Exception {
818         when(mUiccController.getUiccSlot(anyInt())).thenReturn(mUiccSlot);
819         when(mUiccSlot.isRemovable()).thenReturn(true);
820         when(mUiccSlot.isEuicc()).thenReturn(false);
821         when(mUiccSlot.isActive()).thenReturn(true);
822         when(mTelephonyManager.getActiveModemCount()).thenReturn(1);
823         assertEquals(TelephonyManager.DEFAULT_PORT_INDEX,
824                 mController.getResolvedPortIndexForSubscriptionSwitch(CARD_ID));
825     }
826 
827     @Test
testGetResolvedPortIndexForSubscriptionSwitchWithPsimInActiveAndSS()828     public void testGetResolvedPortIndexForSubscriptionSwitchWithPsimInActiveAndSS()
829             throws Exception {
830         setUpUiccSlotDataWithMEP();
831         when(mUiccSlot.getPortList()).thenReturn(new int[]{0});
832         when(mUiccSlot.isPortActive(TelephonyManager.DEFAULT_PORT_INDEX)).thenReturn(true);
833         when(mTelephonyManager.getActiveModemCount()).thenReturn(1);
834         assertEquals(TelephonyManager.DEFAULT_PORT_INDEX,
835                 mController.getResolvedPortIndexForSubscriptionSwitch(CARD_ID));
836     }
837 
838     @Test
testgetResolvedPortIndexForDisableSubscriptionForNoActiveSubscription()839     public void testgetResolvedPortIndexForDisableSubscriptionForNoActiveSubscription()
840             throws Exception {
841         when(mSubscriptionManager.getActiveSubscriptionInfoList(anyBoolean())).thenReturn(null);
842         assertEquals(-1,
843                 mController.getResolvedPortIndexForDisableSubscription(
844                         CARD_ID, PACKAGE_NAME, true));
845     }
846 
847     @Test
testgetResolvedPortIndexForDisableSubscriptionForActiveSubscriptions()848     public void testgetResolvedPortIndexForDisableSubscriptionForActiveSubscriptions()
849             throws Exception {
850         setActiveSubscriptionInfoInMEPMode();
851         assertEquals(1,
852                 mController.getResolvedPortIndexForDisableSubscription(
853                         CARD_ID, PACKAGE_NAME, false));
854     }
855 
856     @Test
testDeleteSubscription_noPrivileges()857     public void testDeleteSubscription_noPrivileges() throws Exception {
858         setHasWriteEmbeddedPermission(false);
859         prepareOperationSubscription(false /* hasPrivileges */);
860         callDeleteSubscription(
861                 SUBSCRIPTION_ID, ICC_ID, false /* complete */,
862                 0 /* result */, "whatever" /* callingPackage */);
863         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
864                 0 /* detailedCode */);
865         verify(mMockConnector, never()).deleteSubscription(anyInt(), anyString(), any());
866     }
867 
868     @Test
testDeleteSubscription_carrierPrivileges_success()869     public void testDeleteSubscription_carrierPrivileges_success() throws Exception {
870         setHasWriteEmbeddedPermission(false);
871         prepareOperationSubscription(true /* hasPrivileges */);
872         callDeleteSubscription(
873                 SUBSCRIPTION_ID, ICC_ID, true /* complete */, EuiccService.RESULT_OK, PACKAGE_NAME);
874         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_OK, 0 /* detailedCode */);
875         assertTrue(mController.mCalledRefreshSubscriptionsAndSendResult);
876     }
877 
878     @Test
879     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testSwitchToSubscription_noSuchSubscription()880     public void testSwitchToSubscription_noSuchSubscription() throws Exception {
881         setHasWriteEmbeddedPermission(true);
882         callSwitchToSubscription(
883                 12345, ICC_ID, false /* complete */, 0 /* result */,
884                 "whatever" /* callingPackage */);
885         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
886                 0 /* detailedCode */);
887         verify(mMockConnector, never()).switchToSubscription(anyInt(), anyInt(), anyString(),
888                 anyBoolean(), any(), anyBoolean());
889     }
890 
891     @Test
892     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testSwitchToSubscription_emptySubscription_noPrivileges()893     public void testSwitchToSubscription_emptySubscription_noPrivileges() throws Exception {
894         setHasWriteEmbeddedPermission(false);
895         callSwitchToSubscription(
896                 SubscriptionManager.INVALID_SUBSCRIPTION_ID, null /* iccid */, false /* complete */,
897                 0 /* result */, "whatever" /* callingPackage */);
898         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
899                 0 /* detailedCode */);
900         verify(mMockConnector, never()).switchToSubscription(anyInt(), anyInt(), anyString(),
901                 anyBoolean(), any(), anyBoolean());
902     }
903 
904     @Test
905     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testSwitchToSubscription_serviceUnavailable()906     public void testSwitchToSubscription_serviceUnavailable() throws Exception {
907         setHasWriteEmbeddedPermission(true);
908         prepareOperationSubscription(false /* hasPrivileges */);
909         setUpUiccSlotData();
910         callSwitchToSubscription(
911                 SUBSCRIPTION_ID, ICC_ID, false /* complete */, 0 /* result */,
912                 "whatever" /* callingPackage */);
913         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
914                 0 /* detailedCode */);
915         verify(mMockConnector).switchToSubscription(anyInt(), anyInt(), anyString(), anyBoolean(),
916                 any(), anyBoolean());
917     }
918 
919     @Test
920     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testSwitchToSubscription_error()921     public void testSwitchToSubscription_error() throws Exception {
922         setHasWriteEmbeddedPermission(true);
923         prepareOperationSubscription(false /* hasPrivileges */);
924         setUpUiccSlotData();
925         callSwitchToSubscription(
926                 SUBSCRIPTION_ID, ICC_ID, true /* complete */, 42 /* result */,
927                 "whatever" /* callingPackage */);
928         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
929                 42 /* detailedCode */);
930     }
931 
932     @Test
933     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testSwitchToSubscription_success()934     public void testSwitchToSubscription_success() throws Exception {
935         setHasWriteEmbeddedPermission(true);
936         prepareOperationSubscription(false /* hasPrivileges */);
937         setUpUiccSlotData();
938         callSwitchToSubscription(
939                 SUBSCRIPTION_ID, ICC_ID, true /* complete */, EuiccService.RESULT_OK,
940                 "whatever" /* callingPackage */);
941         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_OK, 0 /* detailedCode */);
942     }
943 
944     @Test
945     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testSwitchToSubscription_emptySubscription_noActiveSubscription()946     public void testSwitchToSubscription_emptySubscription_noActiveSubscription() throws Exception {
947         setHasWriteEmbeddedPermission(true);
948         callSwitchToSubscription(
949                 SubscriptionManager.INVALID_SUBSCRIPTION_ID, null /* iccid */, true /* complete */,
950                 EuiccService.RESULT_OK, "whatever" /* callingPackage */);
951         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
952                 0 /* detailedCode */);
953         verify(mMockConnector, never()).switchToSubscription(anyInt(), anyInt(), anyString(),
954                 anyBoolean(), any(), anyBoolean());
955     }
956 
957     @Test
958     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testSwitchToSubscription_emptySubscription_success()959     public void testSwitchToSubscription_emptySubscription_success() throws Exception {
960         setHasWriteEmbeddedPermission(true);
961         setHasCarrierPrivilegesOnActiveSubscription(false);
962         callSwitchToSubscription(
963                 SubscriptionManager.INVALID_SUBSCRIPTION_ID, null /* iccid */, true /* complete */,
964                 EuiccService.RESULT_OK, "whatever" /* callingPackage */);
965         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_OK, 0 /* detailedCode */);
966     }
967 
968     @Test
969     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testSwitchToSubscription_noPrivileges()970     public void testSwitchToSubscription_noPrivileges() throws Exception {
971         setHasWriteEmbeddedPermission(false);
972         prepareOperationSubscription(false /* hasPrivileges */);
973         callSwitchToSubscription(
974                 SUBSCRIPTION_ID, ICC_ID, false /* complete */, 0 /* result */,
975                 "whatever" /* callingPackage */);
976         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
977                 0 /* detailedCode */);
978         verify(mMockConnector, never()).switchToSubscription(anyInt(), anyInt(), anyString(),
979                 anyBoolean(), any(), anyBoolean());
980     }
981 
982     @Test
983     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testSwitchToSubscription_hasCarrierPrivileges()984     public void testSwitchToSubscription_hasCarrierPrivileges() throws Exception {
985         setHasWriteEmbeddedPermission(false);
986         prepareOperationSubscription(true /* hasPrivileges */);
987         setUpUiccSlotData();
988         when(mTelephonyManager.getPhoneCount()).thenReturn(1);
989         setHasCarrierPrivilegesOnActiveSubscription(true);
990         callSwitchToSubscription(
991                 SUBSCRIPTION_ID, ICC_ID, true /* complete */, EuiccService.RESULT_OK, PACKAGE_NAME);
992         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_OK, 0 /* detailedCode */);
993     }
994 
995     @Test
996     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testSwitchToSubscription_hasCarrierPrivileges_multiSim()997     public void testSwitchToSubscription_hasCarrierPrivileges_multiSim() throws Exception {
998         setHasWriteEmbeddedPermission(false);
999         prepareOperationSubscription(true /* hasPrivileges */);
1000         setUpUiccSlotData();
1001         when(mTelephonyManager.getPhoneCount()).thenReturn(2);
1002         setCanManageSubscriptionOnTargetSim(true /* isTargetEuicc */, true /* hasPrivileges */);
1003         callSwitchToSubscription(
1004                 SUBSCRIPTION_ID, ICC_ID, true /* complete */, EuiccService.RESULT_OK, PACKAGE_NAME);
1005         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_OK, 0 /* detailedCode */);
1006     }
1007 
1008     @Test
1009     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testSwitchToSubscription_hasCarrierPrivileges_needsConsent()1010     public void testSwitchToSubscription_hasCarrierPrivileges_needsConsent() throws Exception {
1011         setHasWriteEmbeddedPermission(false);
1012         prepareOperationSubscription(true /* hasPrivileges */);
1013         setUpUiccSlotData();
1014         setHasCarrierPrivilegesOnActiveSubscription(false);
1015         when(mTelephonyManager.getPhoneCount()).thenReturn(1);
1016         callSwitchToSubscription(
1017                 SUBSCRIPTION_ID, ICC_ID, false /* complete */, 0 /* result */, PACKAGE_NAME);
1018         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR,
1019                 0 /* detailedCode */);
1020         verify(mMockConnector, never()).switchToSubscription(anyInt(), anyInt(), anyString(),
1021                 anyBoolean(), any(), anyBoolean());
1022         verifyResolutionIntent(EuiccService.ACTION_RESOLVE_NO_PRIVILEGES,
1023                 EuiccOperation.ACTION_SWITCH_NO_PRIVILEGES);
1024     }
1025 
1026     @Test
1027     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testSwitchToSubscription_hasCarrierPrivileges_needsConsent_multiSim()1028     public void testSwitchToSubscription_hasCarrierPrivileges_needsConsent_multiSim()
1029             throws Exception {
1030         setHasWriteEmbeddedPermission(false);
1031         prepareOperationSubscription(true /* hasPrivileges */);
1032         setUpUiccSlotData();
1033         when(mTelephonyManager.getPhoneCount()).thenReturn(2);
1034         setCanManageSubscriptionOnTargetSim(true /* isTargetEuicc */, false /* hasPrivileges */);
1035         callSwitchToSubscription(
1036                 SUBSCRIPTION_ID, ICC_ID, false /* complete */, 0 /* result */, PACKAGE_NAME);
1037         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR,
1038                 0 /* detailedCode */);
1039         verify(mMockConnector, never()).switchToSubscription(anyInt(), anyInt(), anyString(),
1040                 anyBoolean(), any(), anyBoolean());
1041         verifyResolutionIntent(EuiccService.ACTION_RESOLVE_NO_PRIVILEGES,
1042                 EuiccOperation.ACTION_SWITCH_NO_PRIVILEGES);
1043     }
1044 
1045     @Test
1046     @DisableCompatChanges({EuiccManager.SHOULD_RESOLVE_PORT_INDEX_FOR_APPS})
testSwitchToSubscription_hasCarrierPrivileges_needsConsent_multiSim_targetPsim()1047     public void testSwitchToSubscription_hasCarrierPrivileges_needsConsent_multiSim_targetPsim()
1048             throws Exception {
1049         setHasWriteEmbeddedPermission(false);
1050         prepareOperationSubscription(true /* hasPrivileges */);
1051         setUpUiccSlotData();
1052         when(mTelephonyManager.getPhoneCount()).thenReturn(2);
1053         setCanManageSubscriptionOnTargetSim(false /* isTargetEuicc */, true /* hasPrivileges */);
1054         callSwitchToSubscription(
1055                 SUBSCRIPTION_ID, ICC_ID, false /* complete */, 0 /* result */, PACKAGE_NAME);
1056         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR,
1057                 0 /* detailedCode */);
1058         verify(mMockConnector, never()).switchToSubscription(anyInt(), anyInt(), anyString(),
1059                 anyBoolean(), any(), anyBoolean());
1060         verifyResolutionIntent(EuiccService.ACTION_RESOLVE_NO_PRIVILEGES,
1061                 EuiccOperation.ACTION_SWITCH_NO_PRIVILEGES);
1062     }
1063 
1064     @Test
testUpdateSubscriptionNickname_noPrivileges()1065     public void testUpdateSubscriptionNickname_noPrivileges() throws Exception {
1066         setHasWriteEmbeddedPermission(false);
1067         prepareOperationSubscription(false);
1068         callUpdateSubscriptionNickname(
1069                 SUBSCRIPTION_ID, ICC_ID, "nickname", false /* complete */, 0 /* result */,
1070                 PACKAGE_NAME);
1071         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
1072                 0 /* detailedCode */);
1073         verify(mMockConnector, never()).updateSubscriptionNickname(anyInt(), anyString(),
1074                 anyString(), any());
1075     }
1076 
1077     @Test
testUpdateSubscriptionNickname_noSuchSubscription()1078     public void testUpdateSubscriptionNickname_noSuchSubscription() throws Exception {
1079         setHasWriteEmbeddedPermission(true);
1080         callUpdateSubscriptionNickname(
1081                 SUBSCRIPTION_ID, ICC_ID, "nickname", false /* complete */, 0 /* result */,
1082                 PACKAGE_NAME);
1083         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
1084                 0 /* detailedCode */);
1085         verify(mMockConnector, never()).updateSubscriptionNickname(anyInt(), anyString(),
1086                 anyString(), any());
1087     }
1088 
1089     @Test
testUpdateSubscriptionNickname_serviceUnavailable()1090     public void testUpdateSubscriptionNickname_serviceUnavailable() throws Exception {
1091         setHasWriteEmbeddedPermission(true);
1092         prepareOperationSubscription(false /* hasPrivileges */);
1093         callUpdateSubscriptionNickname(
1094                 SUBSCRIPTION_ID, ICC_ID, "nickname", false /* complete */, 0 /* result */,
1095                 PACKAGE_NAME);
1096         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
1097                 0 /* detailedCode */);
1098         verify(mMockConnector).updateSubscriptionNickname(anyInt(), anyString(), anyString(),
1099                 any());
1100     }
1101 
1102     @Test
testUpdateSubscriptionNickname_error()1103     public void testUpdateSubscriptionNickname_error() throws Exception {
1104         setHasWriteEmbeddedPermission(true);
1105         prepareOperationSubscription(false /* hasPrivileges */);
1106         callUpdateSubscriptionNickname(
1107                 SUBSCRIPTION_ID, ICC_ID, "nickname", true /* complete */, 42 /* result */,
1108                 PACKAGE_NAME);
1109         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
1110                 42 /* detailedCode */);
1111     }
1112 
1113     @Test
testUpdateSubscriptionNickname_success()1114     public void testUpdateSubscriptionNickname_success() throws Exception {
1115         setHasWriteEmbeddedPermission(true);
1116         prepareOperationSubscription(false /* hasPrivileges */);
1117         callUpdateSubscriptionNickname(
1118                 SUBSCRIPTION_ID, ICC_ID, "nickname", true /* complete */, EuiccService.RESULT_OK,
1119                 PACKAGE_NAME);
1120         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_OK, 0 /* detailedCode */);
1121     }
1122 
1123     @Test(expected = SecurityException.class)
testEraseSubscriptions_noPrivileges()1124     public void testEraseSubscriptions_noPrivileges() throws Exception {
1125         setHasWriteEmbeddedPermission(false);
1126         callEraseSubscriptions(false /* complete */, 0 /* result */);
1127     }
1128 
1129     @Test
testEraseSubscriptions_serviceUnavailable()1130     public void testEraseSubscriptions_serviceUnavailable() throws Exception {
1131         setHasWriteEmbeddedPermission(true);
1132         callEraseSubscriptions(false /* complete */, 0 /* result */);
1133         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
1134                 0 /* detailedCode */);
1135         verify(mMockConnector).eraseSubscriptions(anyInt(), any());
1136     }
1137 
1138     @Test
testEraseSubscriptions_error()1139     public void testEraseSubscriptions_error() throws Exception {
1140         setHasWriteEmbeddedPermission(true);
1141         callEraseSubscriptions(true /* complete */, 42 /* result */);
1142         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR, 42 /* detailedCode */);
1143     }
1144 
1145     @Test
testEraseSubscriptions_success()1146     public void testEraseSubscriptions_success() throws Exception {
1147         setHasWriteEmbeddedPermission(true);
1148         callEraseSubscriptions(true /* complete */, EuiccService.RESULT_OK);
1149         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_OK, 0 /* detailedCode */);
1150         assertTrue(mController.mCalledRefreshSubscriptionsAndSendResult);
1151     }
1152 
1153     @Test(expected = SecurityException.class)
testEraseSubscriptionsWithOptions_noPrivileges()1154     public void testEraseSubscriptionsWithOptions_noPrivileges() throws Exception {
1155         setHasWriteEmbeddedPermission(false);
1156         callEraseSubscriptionsWithOptions(false /* complete */, 0 /* result */);
1157     }
1158 
1159     @Test
testEraseSubscriptionsWithOptions_serviceUnavailable()1160     public void testEraseSubscriptionsWithOptions_serviceUnavailable() throws Exception {
1161         setHasWriteEmbeddedPermission(true);
1162         callEraseSubscriptionsWithOptions(false /* complete */, 0 /* result */);
1163         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR,
1164                 0 /* detailedCode */);
1165         verify(mMockConnector).eraseSubscriptionsWithOptions(anyInt(), anyInt(), any());
1166     }
1167 
1168     @Test
testEraseSubscriptionsWithOptions_error()1169     public void testEraseSubscriptionsWithOptions_error() throws Exception {
1170         setHasWriteEmbeddedPermission(true);
1171         callEraseSubscriptionsWithOptions(true /* complete */, 42 /* result */);
1172         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR, 42 /* detailedCode */);
1173     }
1174 
1175     @Test
testEraseSubscriptionsWithOptions_success()1176     public void testEraseSubscriptionsWithOptions_success() throws Exception {
1177         setHasWriteEmbeddedPermission(true);
1178         callEraseSubscriptionsWithOptions(true /* complete */, EuiccService.RESULT_OK);
1179         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_OK, 0 /* detailedCode */);
1180         assertTrue(mController.mCalledRefreshSubscriptionsAndSendResult);
1181     }
1182 
1183     @Test(expected = SecurityException.class)
testRetainSubscriptionsForFactoryReset_noPrivileges()1184     public void testRetainSubscriptionsForFactoryReset_noPrivileges() throws Exception {
1185         setHasMasterClearPermission(false);
1186         callRetainSubscriptionsForFactoryReset(false /* complete */, 0 /* result */);
1187     }
1188 
1189     @Test
testRetainSubscriptionsForFactoryReset_serviceUnavailable()1190     public void testRetainSubscriptionsForFactoryReset_serviceUnavailable() throws Exception {
1191         setHasMasterClearPermission(true);
1192         callRetainSubscriptionsForFactoryReset(false /* complete */, 0 /* result */);
1193         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR, 0 /* detailedCode */);
1194         verify(mMockConnector).retainSubscriptions(anyInt(), any());
1195     }
1196 
1197     @Test
testRetainSubscriptionsForFactoryReset_error()1198     public void testRetainSubscriptionsForFactoryReset_error() throws Exception {
1199         setHasMasterClearPermission(true);
1200         callRetainSubscriptionsForFactoryReset(true /* complete */, 42 /* result */);
1201         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR, 42 /* detailedCode */);
1202     }
1203 
1204     @Test
testRetainSubscriptionsForFactoryReset_success()1205     public void testRetainSubscriptionsForFactoryReset_success() throws Exception {
1206         setHasMasterClearPermission(true);
1207         callRetainSubscriptionsForFactoryReset(true /* complete */, EuiccService.RESULT_OK);
1208         verifyIntentSent(EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_OK, 0 /* detailedCode */);
1209     }
1210 
1211     @Test
testAddExtrasToResultIntent_withSmdxOperationCode_normal_case()1212     public void testAddExtrasToResultIntent_withSmdxOperationCode_normal_case() {
1213         // Same setup as testGetDownloadableSubscriptionMetadata_error
1214         setHasWriteEmbeddedPermission(true);
1215         GetDownloadableSubscriptionMetadataResult result =
1216                 new GetDownloadableSubscriptionMetadataResult(0xA8b1051 /* result */,
1217                         null /* subscription */);
1218         callGetDownloadableSubscriptionMetadata(SUBSCRIPTION, true /* complete */, result);
1219 
1220         assertEquals(mController.mExtrasIntent.getIntExtra(
1221                 EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_OPERATION_CODE, -1),
1222                 EuiccManager.OPERATION_SMDX_SUBJECT_REASON_CODE);
1223         assertEquals(mController.mExtrasIntent.getStringExtra(
1224                 EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_SMDX_SUBJECT_CODE), "8.11.1");
1225         assertEquals(mController.mExtrasIntent.getStringExtra(
1226                 EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_SMDX_REASON_CODE), "5.1");
1227 
1228     }
1229 
1230     @Test
testAddExtrasToResultIntent_withSmdxOperationCode_general_case()1231     public void testAddExtrasToResultIntent_withSmdxOperationCode_general_case() {
1232         // Same setup as testGetDownloadableSubscriptionMetadata_error
1233         setHasWriteEmbeddedPermission(true);
1234         GetDownloadableSubscriptionMetadataResult result =
1235                 new GetDownloadableSubscriptionMetadataResult(0xA123456 /* result */,
1236                         null /* subscription */);
1237         callGetDownloadableSubscriptionMetadata(SUBSCRIPTION, true /* complete */, result);
1238 
1239         assertEquals(mController.mExtrasIntent.getIntExtra(
1240                 EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_OPERATION_CODE, -1),
1241                 EuiccManager.OPERATION_SMDX_SUBJECT_REASON_CODE);
1242         assertEquals(mController.mExtrasIntent.getStringExtra(
1243                 EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_SMDX_SUBJECT_CODE), "1.2.3");
1244         assertEquals(mController.mExtrasIntent.getStringExtra(
1245                 EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_SMDX_REASON_CODE), "4.5.6");
1246 
1247     }
1248 
1249     @Test
testAddExtrasToResultIntent_withSmdxOperationCode_and_padding()1250     public void testAddExtrasToResultIntent_withSmdxOperationCode_and_padding() {
1251         // Same setup as testGetDownloadableSubscriptionMetadata_error
1252         setHasWriteEmbeddedPermission(true);
1253         GetDownloadableSubscriptionMetadataResult result =
1254                 new GetDownloadableSubscriptionMetadataResult(0xA003006 /* result */,
1255                         null /* subscription */);
1256         callGetDownloadableSubscriptionMetadata(SUBSCRIPTION, true /* complete */, result);
1257 
1258         assertEquals(mController.mExtrasIntent.getIntExtra(
1259                 EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_OPERATION_CODE, -1),
1260                 EuiccManager.OPERATION_SMDX_SUBJECT_REASON_CODE);
1261         assertEquals(mController.mExtrasIntent.getStringExtra(
1262                 EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_SMDX_SUBJECT_CODE), "3");
1263         assertEquals(mController.mExtrasIntent.getStringExtra(
1264                 EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_SMDX_REASON_CODE), "6");
1265     }
1266 
1267     @Test
testAddExtrasToResultIntent_withOperationCode()1268     public void testAddExtrasToResultIntent_withOperationCode() {
1269         // Same setup as testGetDownloadableSubscriptionMetadata_error
1270         setHasWriteEmbeddedPermission(true);
1271         GetDownloadableSubscriptionMetadataResult result =
1272                 new GetDownloadableSubscriptionMetadataResult(0x12345678 /* result */,
1273                         null /* subscription */);
1274         callGetDownloadableSubscriptionMetadata(SUBSCRIPTION, true /* complete */, result);
1275 
1276         assertEquals(mController.mExtrasIntent.getIntExtra(
1277                 EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_OPERATION_CODE, -1),
1278                 0x12);
1279         assertEquals(mController.mExtrasIntent.getIntExtra(
1280                 EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_ERROR_CODE, -1), 0x345678);
1281     }
1282 
1283     @Test
1284     @DisableCompatChanges({SWITCH_WITHOUT_PORT_INDEX_EXCEPTION_ON_DISABLE})
testIsCompactChangeEnabled_disable()1285     public void testIsCompactChangeEnabled_disable() {
1286         assertFalse(mController.isCompatChangeEnabled(TEST_PACKAGE_NAME,
1287                 SWITCH_WITHOUT_PORT_INDEX_EXCEPTION_ON_DISABLE));
1288     }
1289 
1290     @Test
1291     @EnableCompatChanges({SWITCH_WITHOUT_PORT_INDEX_EXCEPTION_ON_DISABLE})
testIsCompactChangeEnabled_enable()1292     public void testIsCompactChangeEnabled_enable() {
1293         assertTrue(mController.isCompatChangeEnabled(TEST_PACKAGE_NAME,
1294                 SWITCH_WITHOUT_PORT_INDEX_EXCEPTION_ON_DISABLE));
1295     }
1296 
1297     @Test
1298     @EnableCompatChanges({EuiccManager.INACTIVE_PORT_AVAILABILITY_CHECK})
testIsSimPortAvailable_invalidCase()1299     public void testIsSimPortAvailable_invalidCase() {
1300         setUiccCardInfos(false, true, true);
1301         // assert non euicc card id
1302         assertFalse(mController.isSimPortAvailable(REMOVABLE_CARD_ID, 0, TEST_PACKAGE_NAME));
1303 
1304         // assert invalid port index
1305         assertFalse(mController.isSimPortAvailable(CARD_ID, 5 /* portIndex */, TEST_PACKAGE_NAME));
1306     }
1307 
1308     @Test
1309     @EnableCompatChanges({EuiccManager.INACTIVE_PORT_AVAILABILITY_CHECK})
testIsSimPortAvailable_port_active()1310     public void testIsSimPortAvailable_port_active() throws Exception {
1311         setUiccCardInfos(false, true, true);
1312 
1313         // port has empty iccid
1314         assertTrue(mController.isSimPortAvailable(CARD_ID, 0, TEST_PACKAGE_NAME));
1315 
1316         // Set port is active, has valid iccid(may be boot profile) and UiccProfile is empty
1317         setUiccCardInfos(false, true, false);
1318         when(mUiccController.getUiccPortForSlot(anyInt(), anyInt())).thenReturn(mUiccPort);
1319         when(mUiccPort.getUiccProfile()).thenReturn(mUiccProfile);
1320         when(mUiccProfile.isEmptyProfile()).thenReturn(true);
1321         assertTrue(mController.isSimPortAvailable(CARD_ID, 0, TEST_PACKAGE_NAME));
1322 
1323         // port is active, valid iccid, not empty profile but Phone object is null
1324         when(mUiccPort.getUiccProfile()).thenReturn(mUiccProfile);
1325         when(mUiccProfile.isEmptyProfile()).thenReturn(false);
1326         replaceInstance(PhoneFactory.class, "sPhones", null, new Phone[] {mPhone});
1327         // logicalSlotIndex of port#0 is 1, Phone object should be null
1328         assertFalse(mController.isSimPortAvailable(CARD_ID, 0, TEST_PACKAGE_NAME));
1329 
1330         // port is active, valid iccid, not empty profile but no carrier privileges
1331         when(mUiccPort.getUiccProfile()).thenReturn(mUiccProfile);
1332         when(mUiccProfile.isEmptyProfile()).thenReturn(false);
1333         replaceInstance(PhoneFactory.class, "sPhones", null, new Phone[] {mPhone, mPhone});
1334         when(mPhone.getCarrierPrivilegesTracker()).thenReturn(null);
1335         assertFalse(mController.isSimPortAvailable(CARD_ID, 0, TEST_PACKAGE_NAME));
1336         when(mPhone.getCarrierPrivilegesTracker()).thenReturn(mCarrierPrivilegesTracker);
1337         when(mCarrierPrivilegesTracker.getCarrierPrivilegeStatusForPackage(TEST_PACKAGE_NAME))
1338                 .thenReturn(TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS);
1339         assertFalse(mController.isSimPortAvailable(CARD_ID, 0, TEST_PACKAGE_NAME));
1340 
1341         // port is active, valid iccid, not empty profile and has carrier privileges
1342         when(mCarrierPrivilegesTracker.getCarrierPrivilegeStatusForPackage(TEST_PACKAGE_NAME))
1343                 .thenReturn(TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS);
1344         assertTrue(mController.isSimPortAvailable(CARD_ID, 0, TEST_PACKAGE_NAME));
1345     }
1346 
1347     @Test
1348     @EnableCompatChanges({EuiccManager.INACTIVE_PORT_AVAILABILITY_CHECK})
testIsSimPortAvailable_port_inActive()1349     public void testIsSimPortAvailable_port_inActive() {
1350         setUiccCardInfos(false, false, true);
1351         when(mUiccController.getUiccSlots()).thenReturn(new UiccSlot[]{mUiccSlot});
1352         when(mUiccSlot.isRemovable()).thenReturn(true);
1353 
1354         // Check getRemovableNonEuiccSlot null case
1355         when(mUiccSlot.isEuicc()).thenReturn(true);
1356         assertFalse(mController.isSimPortAvailable(CARD_ID, 0, TEST_PACKAGE_NAME));
1357 
1358         // Check getRemovableNonEuiccSlot isActive() false case
1359         when(mUiccSlot.isEuicc()).thenReturn(false);
1360         when(mUiccSlot.isActive()).thenReturn(false);
1361         assertFalse(mController.isSimPortAvailable(CARD_ID, 0, TEST_PACKAGE_NAME));
1362 
1363         // assert false,multisim is not enabled
1364         when(mUiccSlot.isEuicc()).thenReturn(false);
1365         when(mUiccSlot.isActive()).thenReturn(true);
1366         when(mTelephonyManager.checkCarrierPrivilegesForPackageAnyPhone(TEST_PACKAGE_NAME))
1367                 .thenReturn(TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS);
1368         when(mTelephonyManager.isMultiSimEnabled()).thenReturn(false);
1369         assertFalse(mController.isSimPortAvailable(CARD_ID, 0, TEST_PACKAGE_NAME));
1370 
1371         // assert false, caller does not have carrier privileges
1372         setHasWriteEmbeddedPermission(false);
1373         when(mTelephonyManager.isMultiSimEnabled()).thenReturn(true);
1374         when(mUiccSlot.getPortList()).thenReturn(new int[] {0});
1375         when(mSubscriptionManager.getActiveSubscriptionInfoForSimSlotIndex(anyInt())).thenReturn(
1376                 new SubscriptionInfo.Builder().build());
1377         when(mTelephonyManager.checkCarrierPrivilegesForPackageAnyPhone(TEST_PACKAGE_NAME))
1378                 .thenReturn(TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS);
1379         assertFalse(mController.isSimPortAvailable(CARD_ID, 0, TEST_PACKAGE_NAME));
1380 
1381         // assert true, caller does not have carrier privileges but has write_embedded permission
1382         setHasWriteEmbeddedPermission(true);
1383         assertTrue(mController.isSimPortAvailable(CARD_ID, 0, TEST_PACKAGE_NAME));
1384 
1385         // assert true, caller has carrier privileges
1386         setHasWriteEmbeddedPermission(false);
1387         when(mTelephonyManager.checkCarrierPrivilegesForPackageAnyPhone(TEST_PACKAGE_NAME))
1388                 .thenReturn(TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS);
1389         assertTrue(mController.isSimPortAvailable(CARD_ID, 0, TEST_PACKAGE_NAME));
1390     }
1391 
1392     @Test
1393     @DisableCompatChanges({EuiccManager.INACTIVE_PORT_AVAILABILITY_CHECK})
testIsSimPortAvailable_port_inActive_disable_compactChange()1394     public void testIsSimPortAvailable_port_inActive_disable_compactChange() {
1395         setUiccCardInfos(false, false, true);
1396         when(mUiccController.getUiccSlots()).thenReturn(new UiccSlot[]{mUiccSlot});
1397         when(mUiccSlot.isRemovable()).thenReturn(true);
1398         when(mUiccSlot.isEuicc()).thenReturn(false);
1399         when(mUiccSlot.isActive()).thenReturn(true);
1400 
1401         when(mTelephonyManager.isMultiSimEnabled()).thenReturn(true);
1402         when(mUiccSlot.getPortList()).thenReturn(new int[] {0});
1403         when(mSubscriptionManager.getActiveSubscriptionInfoForSimSlotIndex(anyInt())).thenReturn(
1404                 new SubscriptionInfo.Builder().build());
1405         when(mTelephonyManager.checkCarrierPrivilegesForPackageAnyPhone(TEST_PACKAGE_NAME))
1406                 .thenReturn(TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS);
1407         setHasWriteEmbeddedPermission(true);
1408 
1409         // Even though all conditions are true, isSimPortAvailable should return false as
1410         // compact change is disabled
1411         assertFalse(mController.isSimPortAvailable(CARD_ID, 0, TEST_PACKAGE_NAME));
1412     }
1413 
1414 
setUiccCardInfos(boolean isMepSupported, boolean isPortActive, boolean isEmptyPort)1415     private void setUiccCardInfos(boolean isMepSupported, boolean isPortActive,
1416             boolean isEmptyPort) {
1417         List<UiccPortInfo> euiccPortInfoList;
1418         if (isMepSupported) {
1419             euiccPortInfoList = Arrays.asList(
1420                     new UiccPortInfo(isEmptyPort ? "" : ICC_ID /* iccId */, 0 /* portIdx */,
1421                             isPortActive ? 1 : -1 /* logicalSlotIdx */,
1422                             isPortActive /* isActive */),
1423                     new UiccPortInfo(isEmptyPort ? "" : ICC_ID /* iccId */, 1 /* portIdx */,
1424                             -1 /* logicalSlotIdx */,
1425                             isPortActive /* isActive */));
1426         } else {
1427             euiccPortInfoList = Collections.singletonList(
1428                     new UiccPortInfo(isEmptyPort ? "" : ICC_ID /* iccId */, 0 /* portIdx */,
1429                             isPortActive ? 1 : -1 /* logicalSlotIdx */,
1430                             isPortActive /* isActive */)
1431                     );
1432         }
1433 
1434         UiccCardInfo cardInfo1 = new UiccCardInfo(true, CARD_ID, "", 0,
1435                 false /* isRemovable */,
1436                 isMepSupported /* isMultipleEnabledProfileSupported */,
1437                 euiccPortInfoList);
1438         UiccCardInfo cardInfo2 = new UiccCardInfo(false /* isEuicc */,
1439                 REMOVABLE_CARD_ID /* cardId */,
1440                 "", 0, true /* isRemovable */,
1441                 false /* isMultipleEnabledProfileSupported */,
1442                 Collections.singletonList(
1443                         new UiccPortInfo("" /* iccId */, 0 /* portIdx */,
1444                                 0 /* logicalSlotIdx */, true /* isActive */)));
1445         ArrayList<UiccCardInfo> cardInfos = new ArrayList<>();
1446         cardInfos.add(cardInfo1);
1447         cardInfos.add(cardInfo2);
1448         when(mTelephonyManager.getUiccCardsInfo()).thenReturn(cardInfos);
1449     }
1450 
setUpUiccSlotData()1451     private void setUpUiccSlotData() {
1452         when(mUiccController.getUiccSlot(anyInt())).thenReturn(mUiccSlot);
1453         // TODO(b/199559633): Add test cases for isMultipleEnabledProfileSupported true case
1454         when(mUiccSlot.isMultipleEnabledProfileSupported()).thenReturn(false);
1455     }
1456 
setUpUiccSlotDataWithMEP()1457     private void setUpUiccSlotDataWithMEP() {
1458         when(mUiccController.getUiccSlot(anyInt())).thenReturn(mUiccSlot);
1459         when(mUiccSlot.isMultipleEnabledProfileSupported()).thenReturn(true);
1460     }
1461 
setGetEidPermissions( boolean hasPhoneStatePrivileged, boolean hasCarrierPrivileges)1462     private void setGetEidPermissions(
1463             boolean hasPhoneStatePrivileged, boolean hasCarrierPrivileges) throws Exception {
1464         doReturn(hasPhoneStatePrivileged
1465                 ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED)
1466                 .when(mContext)
1467                 .checkCallingOrSelfPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE);
1468         when(mTelephonyManager.getPhoneCount()).thenReturn(1);
1469         setHasCarrierPrivilegesOnActiveSubscription(hasCarrierPrivileges);
1470     }
1471 
setHasWriteEmbeddedPermission(boolean hasPermission)1472     private void setHasWriteEmbeddedPermission(boolean hasPermission) {
1473         doReturn(hasPermission
1474                 ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED)
1475                 .when(mContext)
1476                 .checkCallingOrSelfPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS);
1477     }
1478 
setHasMasterClearPermission(boolean hasPermission)1479     private void setHasMasterClearPermission(boolean hasPermission) {
1480         Stubber stubber = hasPermission ? doNothing() : doThrow(new SecurityException());
1481         stubber.when(mContext).enforceCallingPermission(
1482                 eq(Manifest.permission.MASTER_CLEAR), anyString());
1483     }
1484 
setHasCarrierPrivilegesOnActiveSubscription(boolean hasPrivileges)1485     private void setHasCarrierPrivilegesOnActiveSubscription(boolean hasPrivileges)
1486             throws Exception {
1487         SubscriptionInfo.Builder builder = new SubscriptionInfo.Builder()
1488                 .setSimSlotIndex(0)
1489                 .setPortIndex(mTelephonyManager.DEFAULT_PORT_INDEX)
1490                 .setDisplayNameSource(SubscriptionManager.NAME_SOURCE_CARRIER_ID)
1491                 .setEmbedded(true);
1492         if (hasPrivileges) {
1493             builder.setNativeAccessRules(new UiccAccessRule[] { ACCESS_RULE });
1494         }
1495         builder.setCardId(CARD_ID);
1496         SubscriptionInfo subInfo = builder.build();
1497 
1498         when(mSubscriptionManager.canManageSubscription(subInfo, PACKAGE_NAME)).thenReturn(
1499                 hasPrivileges);
1500         when(mSubscriptionManager.getActiveSubscriptionInfoList(anyBoolean())).thenReturn(
1501                 Collections.singletonList(subInfo));
1502     }
1503 
setCanManageSubscriptionOnTargetSim(boolean isTargetEuicc, boolean hasPrivileges)1504     private void setCanManageSubscriptionOnTargetSim(boolean isTargetEuicc, boolean hasPrivileges)
1505             throws Exception {
1506         UiccCardInfo cardInfo1 = new UiccCardInfo(isTargetEuicc, CARD_ID, "", 0,
1507                 false /* isRemovable */,
1508                 false /* isMultipleEnabledProfileSupported */,
1509                 Collections.singletonList(
1510                         new UiccPortInfo("" /* iccId */, 0 /* portIdx */,
1511                                 -1 /* logicalSlotIdx */, false /* isActive */)));
1512         UiccCardInfo cardInfo2 = new UiccCardInfo(true /* isEuicc */, 1 /* cardId */,
1513                 "", 0, false /* isRemovable */,
1514                 false /* isMultipleEnabledProfileSupported */,
1515                 Collections.singletonList(
1516                         new UiccPortInfo("" /* iccId */, 0 /* portIdx */,
1517                                 -1 /* logicalSlotIdx */, false /* isActive */)));
1518         ArrayList<UiccCardInfo> cardInfos = new ArrayList<>();
1519         cardInfos.add(cardInfo1);
1520         cardInfos.add(cardInfo2);
1521         when(mTelephonyManager.getUiccCardsInfo()).thenReturn(cardInfos);
1522 
1523         SubscriptionInfo subInfo1 = new SubscriptionInfo.Builder()
1524                 .setNativeAccessRules(hasPrivileges ? new UiccAccessRule[] { ACCESS_RULE } : null)
1525                 .setEmbedded(true)
1526                 .setCardId(CARD_ID)
1527                 .setPortIndex(mTelephonyManager.DEFAULT_PORT_INDEX)
1528                 .build();
1529         SubscriptionInfo subInfo2 = new SubscriptionInfo.Builder()
1530                 .setNativeAccessRules(hasPrivileges ? new UiccAccessRule[] { ACCESS_RULE } : null)
1531                 .setEmbedded(true)
1532                 .setCardId(2)
1533                 .setPortIndex(TelephonyManager.DEFAULT_PORT_INDEX)
1534                 .build();
1535         when(mSubscriptionManager.canManageSubscription(subInfo1, PACKAGE_NAME)).thenReturn(
1536                 hasPrivileges);
1537         when(mSubscriptionManager.canManageSubscription(subInfo2, PACKAGE_NAME)).thenReturn(
1538                 hasPrivileges);
1539         ArrayList<SubscriptionInfo> subInfos = new ArrayList<>(Arrays.asList(subInfo1, subInfo2));
1540         when(mSubscriptionManager.getActiveSubscriptionInfoList(anyBoolean())).thenReturn(subInfos);
1541     }
1542 
setActiveSubscriptionInfoInMEPMode()1543     private void setActiveSubscriptionInfoInMEPMode()
1544             throws Exception {
1545         SubscriptionInfo subInfo1 = new SubscriptionInfo.Builder()
1546                 .setEmbedded(true)
1547                 .setCardId(CARD_ID)
1548                 .setPortIndex(TelephonyManager.DEFAULT_PORT_INDEX)
1549                 .build();
1550         SubscriptionInfo subInfo2 = new SubscriptionInfo.Builder()
1551                 .setEmbedded(true)
1552                 .setCardId(CARD_ID)
1553                 .setPortIndex(1)
1554                 .build();
1555         when(mSubscriptionManager.canManageSubscription(subInfo1, PACKAGE_NAME)).thenReturn(
1556                 false);
1557         when(mSubscriptionManager.canManageSubscription(subInfo2, PACKAGE_NAME)).thenReturn(
1558                 true);
1559         ArrayList<SubscriptionInfo> subInfos = new ArrayList<>(Arrays.asList(subInfo1, subInfo2));
1560         when(mSubscriptionManager.getActiveSubscriptionInfoList(anyBoolean())).thenReturn(subInfos);
1561     }
1562 
prepareOperationSubscription(boolean hasPrivileges)1563     private void prepareOperationSubscription(boolean hasPrivileges) throws Exception {
1564         SubscriptionInfo subInfo = new SubscriptionInfo.Builder()
1565                 .setId(SUBSCRIPTION_ID)
1566                 .setIccId(ICC_ID)
1567                 .setNativeAccessRules(hasPrivileges ? new UiccAccessRule[] { ACCESS_RULE } : null)
1568                 .setEmbedded(true)
1569                 .setCardId(CARD_ID)
1570                 .build();
1571         when(mSubscriptionManager.canManageSubscription(subInfo, PACKAGE_NAME)).thenReturn(
1572                 hasPrivileges);
1573         when(mSubscriptionManager.getAvailableSubscriptionInfoList()).thenReturn(
1574                 Collections.singletonList(subInfo));
1575     }
1576 
callGetEid(final boolean success, final @Nullable String eid, int cardId)1577     private String callGetEid(final boolean success, final @Nullable String eid, int cardId) {
1578         doAnswer(new Answer<Void>() {
1579             @Override
1580             public Void answer(InvocationOnMock invocation) throws Exception {
1581                 EuiccConnector.GetEidCommandCallback cb = invocation
1582                         .getArgument(1 /* resultCallback */);
1583                 if (success) {
1584                     cb.onGetEidComplete(eid);
1585                 } else {
1586                     cb.onEuiccServiceUnavailable();
1587                 }
1588                 return null;
1589             }
1590         }).when(mMockConnector).getEid(anyInt(),
1591                 Mockito.<EuiccConnector.GetEidCommandCallback>any());
1592         return mController.getEid(cardId, PACKAGE_NAME);
1593     }
1594 
callGetOtaStatus(final boolean success, final int status)1595     private int callGetOtaStatus(final boolean success, final int status) {
1596         doAnswer(new Answer<Void>() {
1597             @Override
1598             public Void answer(InvocationOnMock invocation) throws Exception {
1599                 GetOtaStatusCommandCallback cb = invocation.getArgument(1 /* resultCallback */);
1600                 if (success) {
1601                     cb.onGetOtaStatusComplete(status);
1602                 } else {
1603                     cb.onEuiccServiceUnavailable();
1604                 }
1605                 return null;
1606             }
1607         }).when(mMockConnector).getOtaStatus(anyInt(), Mockito.<GetOtaStatusCommandCallback>any());
1608         return mController.getOtaStatus(CARD_ID);
1609     }
1610 
callStartOtaUpdatingIfNecessary( final boolean serviceAvailable, int status)1611     private void callStartOtaUpdatingIfNecessary(
1612             final boolean serviceAvailable, int status) {
1613         doAnswer(new Answer<Void>() {
1614             @Override
1615             public Void answer(InvocationOnMock invocation) throws Exception {
1616                 OtaStatusChangedCallback cb = invocation.getArgument(1 /* resultCallback */);
1617                 if (!serviceAvailable) {
1618                     cb.onEuiccServiceUnavailable();
1619                 } else {
1620                     cb.onOtaStatusChanged(status);
1621                 }
1622                 return null;
1623             }
1624         }).when(mMockConnector).startOtaIfNecessary(anyInt(),
1625                 Mockito.<OtaStatusChangedCallback>any());
1626 
1627         mController.startOtaUpdatingIfNecessary();
1628     }
1629 
callGetEuiccInfo(final boolean success, final @Nullable EuiccInfo euiccInfo)1630     private EuiccInfo callGetEuiccInfo(final boolean success, final @Nullable EuiccInfo euiccInfo) {
1631         doAnswer(new Answer<Void>() {
1632             @Override
1633             public Void answer(InvocationOnMock invocation) throws Exception {
1634                 EuiccConnector.GetEuiccInfoCommandCallback cb = invocation
1635                         .getArgument(1 /* resultCallback */);
1636                 if (success) {
1637                     cb.onGetEuiccInfoComplete(euiccInfo);
1638                 } else {
1639                     cb.onEuiccServiceUnavailable();
1640                 }
1641                 return null;
1642             }
1643         }).when(mMockConnector).getEuiccInfo(anyInt(), any());
1644         return mController.getEuiccInfo(CARD_ID);
1645     }
1646 
prepareGetDownloadableSubscriptionMetadataCall( final boolean complete, final GetDownloadableSubscriptionMetadataResult result)1647     private void prepareGetDownloadableSubscriptionMetadataCall(
1648             final boolean complete, final GetDownloadableSubscriptionMetadataResult result) {
1649         doAnswer(new Answer<Void>() {
1650             @Override
1651             public Void answer(InvocationOnMock invocation) throws Exception {
1652                 EuiccConnector.GetMetadataCommandCallback cb = invocation
1653                         .getArgument(5 /* resultCallback */);
1654                 if (complete) {
1655                     cb.onGetMetadataComplete(CARD_ID, result);
1656                 } else {
1657                     cb.onEuiccServiceUnavailable();
1658                 }
1659                 return null;
1660             }
1661         }).when(mMockConnector).getDownloadableSubscriptionMetadata(anyInt(), anyInt(), any(),
1662                 anyBoolean(), anyBoolean(), any());
1663     }
1664 
callGetDownloadableSubscriptionMetadata(DownloadableSubscription subscription, boolean complete, GetDownloadableSubscriptionMetadataResult result)1665     private void callGetDownloadableSubscriptionMetadata(DownloadableSubscription subscription,
1666             boolean complete, GetDownloadableSubscriptionMetadataResult result) {
1667         prepareGetDownloadableSubscriptionMetadataCall(complete, result);
1668         PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(),
1669                 PendingIntent.FLAG_IMMUTABLE);
1670         mController.getDownloadableSubscriptionMetadata(0, subscription, PACKAGE_NAME,
1671                 resultCallback);
1672     }
1673 
callGetDefaultDownloadableSubscriptionList( boolean complete, GetDefaultDownloadableSubscriptionListResult result)1674     private void callGetDefaultDownloadableSubscriptionList(
1675             boolean complete, GetDefaultDownloadableSubscriptionListResult result) {
1676         doAnswer(new Answer<Void>() {
1677             @Override
1678             public Void answer(InvocationOnMock invocation) throws Exception {
1679                 EuiccConnector.GetDefaultListCommandCallback cb = invocation
1680                         .getArgument(2 /* resultCallBack */);
1681                 if (complete) {
1682                     cb.onGetDefaultListComplete(CARD_ID, result);
1683                 } else {
1684                     cb.onEuiccServiceUnavailable();
1685                 }
1686                 return null;
1687             }
1688         }).when(mMockConnector).getDefaultDownloadableSubscriptionList(anyInt(), anyBoolean(),
1689                 any());
1690         PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(),
1691                 PendingIntent.FLAG_IMMUTABLE);
1692         mController.getDefaultDownloadableSubscriptionList(CARD_ID, PACKAGE_NAME, resultCallback);
1693     }
1694 
callDownloadSubscription(DownloadableSubscription subscription, boolean switchAfterDownload, final boolean complete, final int result, final int resolvableError, String callingPackage)1695     private void callDownloadSubscription(DownloadableSubscription subscription,
1696             boolean switchAfterDownload, final boolean complete, final int result,
1697             final int resolvableError, String callingPackage) {
1698         PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(),
1699                 PendingIntent.FLAG_IMMUTABLE);
1700         doAnswer(new Answer<Void>() {
1701             @Override
1702             public Void answer(InvocationOnMock invocation) throws Exception {
1703                 EuiccConnector.DownloadCommandCallback cb = invocation
1704                         .getArgument(6 /* resultCallback */);
1705                 if (complete) {
1706                     DownloadSubscriptionResult downloadRes = new DownloadSubscriptionResult(
1707                             result, resolvableError, -1 /* cardId */);
1708                     cb.onDownloadComplete(downloadRes);
1709                 } else {
1710                     cb.onEuiccServiceUnavailable();
1711                 }
1712                 return null;
1713             }
1714         }).when(mMockConnector).downloadSubscription(anyInt(), anyInt(),
1715                 any(), eq(switchAfterDownload), anyBoolean(), any(), any());
1716         mController.downloadSubscription(CARD_ID, subscription, switchAfterDownload, callingPackage,
1717                 null /* resolvedBundle */, resultCallback);
1718         // EUICC_PROVISIONED setting should match whether the download was successful.
1719         assertEquals(complete && result == EuiccService.RESULT_OK ? 1 : 0,
1720                 Settings.Global.getInt(mContext.getContentResolver(),
1721                         Settings.Global.EUICC_PROVISIONED, 0));
1722     }
1723 
callDeleteSubscription(int subscriptionId, String iccid, final boolean complete, final int result, String callingPackage)1724     private void callDeleteSubscription(int subscriptionId, String iccid, final boolean complete,
1725             final int result, String callingPackage) {
1726         PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(),
1727                 PendingIntent.FLAG_IMMUTABLE);
1728         doAnswer(new Answer<Void>() {
1729             @Override
1730             public Void answer(InvocationOnMock invocation) throws Exception {
1731                 EuiccConnector.DeleteCommandCallback cb = invocation
1732                         .getArgument(2 /* resultCallback */);
1733                 if (complete) {
1734                     cb.onDeleteComplete(result);
1735                 } else {
1736                     cb.onEuiccServiceUnavailable();
1737                 }
1738                 return null;
1739             }
1740         }).when(mMockConnector).deleteSubscription(anyInt(), eq(iccid), any());
1741         mController.deleteSubscription(CARD_ID, subscriptionId, callingPackage, resultCallback);
1742     }
1743 
callSwitchToSubscription(int subscriptionId, String iccid, final boolean complete, final int result, String callingPackage)1744     private void callSwitchToSubscription(int subscriptionId, String iccid, final boolean complete,
1745             final int result, String callingPackage) {
1746         PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(),
1747                 PendingIntent.FLAG_IMMUTABLE);
1748         doAnswer(new Answer<Void>() {
1749             @Override
1750             public Void answer(InvocationOnMock invocation) throws Exception {
1751                 EuiccConnector.SwitchCommandCallback cb = invocation
1752                         .getArgument(4 /* resultCallback */);
1753                 if (complete) {
1754                     cb.onSwitchComplete(result);
1755                 } else {
1756                     cb.onEuiccServiceUnavailable();
1757                 }
1758                 return null;
1759             }
1760         }).when(mMockConnector).switchToSubscription(anyInt(), anyInt(), eq(iccid), anyBoolean(),
1761                 any(), anyBoolean());
1762         mController.switchToSubscription(CARD_ID, subscriptionId, callingPackage,
1763                 resultCallback);
1764     }
1765 
callUpdateSubscriptionNickname(int subscriptionId, String iccid, String nickname, final boolean complete, final int result, String callingPackage)1766     private void callUpdateSubscriptionNickname(int subscriptionId, String iccid, String nickname,
1767             final boolean complete, final int result, String callingPackage) {
1768         PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(),
1769                 PendingIntent.FLAG_IMMUTABLE);
1770         doAnswer(new Answer<Void>() {
1771             @Override
1772             public Void answer(InvocationOnMock invocation) throws Exception {
1773                 EuiccConnector.UpdateNicknameCommandCallback cb = invocation
1774                         .getArgument(3 /* resultCallback */);
1775                 if (complete) {
1776                     cb.onUpdateNicknameComplete(result);
1777                 } else {
1778                     cb.onEuiccServiceUnavailable();
1779                 }
1780                 return null;
1781             }
1782         }).when(mMockConnector).updateSubscriptionNickname(anyInt(), eq(iccid), eq(nickname),
1783                 any());
1784         mController.updateSubscriptionNickname(CARD_ID, subscriptionId, nickname, callingPackage,
1785                 resultCallback);
1786     }
1787 
callEraseSubscriptions(final boolean complete, final int result)1788     private void callEraseSubscriptions(final boolean complete, final int result) {
1789         PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(),
1790                 PendingIntent.FLAG_IMMUTABLE);
1791         doAnswer(new Answer<Void>() {
1792             @Override
1793             public Void answer(InvocationOnMock invocation) throws Exception {
1794                 EuiccConnector.EraseCommandCallback cb = invocation
1795                         .getArgument(1 /* resultCallback */);
1796                 if (complete) {
1797                     cb.onEraseComplete(result);
1798                 } else {
1799                     cb.onEuiccServiceUnavailable();
1800                 }
1801                 return null;
1802             }
1803         }).when(mMockConnector).eraseSubscriptions(anyInt(), any());
1804         mController.eraseSubscriptions(CARD_ID, resultCallback);
1805     }
1806 
callEraseSubscriptionsWithOptions(final boolean complete, final int result)1807     private void callEraseSubscriptionsWithOptions(final boolean complete, final int result) {
1808         PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(),
1809                 PendingIntent.FLAG_IMMUTABLE);
1810         doAnswer(new Answer<Void>() {
1811             @Override
1812             public Void answer(InvocationOnMock invocation) throws Exception {
1813                 EuiccConnector.EraseCommandCallback cb = invocation
1814                         .getArgument(2 /* resultCallback */);
1815                 if (complete) {
1816                     cb.onEraseComplete(result);
1817                 } else {
1818                     cb.onEuiccServiceUnavailable();
1819                 }
1820                 return null;
1821             }
1822         }).when(mMockConnector).eraseSubscriptionsWithOptions(anyInt(), anyInt(), any());
1823         mController.eraseSubscriptionsWithOptions(CARD_ID,
1824                 RESET_OPTION_DELETE_OPERATIONAL_PROFILES, resultCallback);
1825     }
1826 
callRetainSubscriptionsForFactoryReset(final boolean complete, final int result)1827     private void callRetainSubscriptionsForFactoryReset(final boolean complete, final int result) {
1828         PendingIntent resultCallback = PendingIntent.getBroadcast(mContext, 0, new Intent(),
1829                 PendingIntent.FLAG_IMMUTABLE);
1830         doAnswer(new Answer<Void>() {
1831             @Override
1832             public Void answer(InvocationOnMock invocation) throws Exception {
1833                 EuiccConnector.RetainSubscriptionsCommandCallback cb = invocation
1834                         .getArgument(1 /* resultCallback */);
1835                 if (complete) {
1836                     cb.onRetainSubscriptionsComplete(result);
1837                 } else {
1838                     cb.onEuiccServiceUnavailable();
1839                 }
1840                 return null;
1841             }
1842         }).when(mMockConnector).retainSubscriptions(anyInt(), any());
1843         mController.retainSubscriptionsForFactoryReset(CARD_ID, resultCallback);
1844     }
1845 
verifyResolutionIntent(String euiccUiAction, @EuiccOperation.Action int action)1846     private void verifyResolutionIntent(String euiccUiAction, @EuiccOperation.Action int action) {
1847         assertEquals(euiccUiAction, mController.mResolutionAction);
1848         assertNotNull(mController.mOp);
1849         assertEquals(action, mController.mOp.mAction);
1850     }
1851 
verifyIntentSent(int resultCode, int detailedCode)1852     private Intent verifyIntentSent(int resultCode, int detailedCode)
1853             throws RemoteException {
1854         assertNotNull(mController.mCallbackIntent);
1855         assertEquals(resultCode, mController.mResultCode);
1856         if (mController.mExtrasIntent == null) {
1857             assertEquals(0, detailedCode);
1858         } else {
1859             assertEquals(detailedCode,
1860                     mController.mExtrasIntent.getIntExtra(
1861                             EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE, 0));
1862         }
1863         return mController.mExtrasIntent;
1864     }
1865 }
1866