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