aboutsummaryrefslogtreecommitdiff
path: root/tests/telephonytests/src/com/android/internal/telephony/ContextFixture.java
blob: da3920e8727a44f5d38875a1d383fcc5dda35576 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.internal.telephony;

import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;

import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.AppOpsManager;
import android.app.DownloadManager;
import android.app.KeyguardManager;
import android.app.NotificationManager;
import android.app.UiModeManager;
import android.app.usage.UsageStatsManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkPolicyManager;
import android.net.Uri;
import android.net.vcn.VcnManager;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IInterface;
import android.os.PersistableBundle;
import android.os.PowerManager;
import android.os.PowerWhitelistManager;
import android.os.SystemConfigManager;
import android.os.UserHandle;
import android.os.UserManager;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.telecom.TelecomManager;
import android.telephony.CarrierConfigManager;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.telephony.TelephonyRegistryManager;
import android.telephony.euicc.EuiccManager;
import android.telephony.ims.ImsManager;
import android.test.mock.MockContentProvider;
import android.test.mock.MockContentResolver;
import android.test.mock.MockContext;
import android.util.DisplayMetrics;
import android.util.Log;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

/**
 * Controls a test {@link Context} as would be provided by the Android framework to an
 * {@code Activity}, {@code Service} or other system-instantiated component.
 *
 * Contains {@code Fake<Component>} classes like FakeContext for components that require complex and
 * reusable stubbing. Others can be mocked using Mockito functions in tests or constructor/public
 * methods of this class.
 */
public class ContextFixture implements TestFixture<Context> {
    private static final String TAG = "ContextFixture";
    public static final String PERMISSION_ENABLE_ALL = "android.permission.STUB_PERMISSION";

    public static class FakeContentProvider extends MockContentProvider {
        private HashMap<String, String> mKeyValuePairs = new HashMap<String, String>();
        private int mNumKeyValuePairs = 0;
        private HashMap<String, String> mFlags = new HashMap<>();

        @Override
        public int delete(Uri uri, String selection, String[] selectionArgs) {
            return 0;
        }

        @Override
        public Uri insert(Uri uri, ContentValues values) {
            Uri newUri = null;
            if (values != null) {
                mKeyValuePairs.put(values.getAsString("name"), values.getAsString("value"));
                mNumKeyValuePairs++;
                newUri = Uri.withAppendedPath(uri, "" + mNumKeyValuePairs);
            }
            logd("insert called, new mNumKeyValuePairs: " + mNumKeyValuePairs + " uri: " + uri +
                    " newUri: " + newUri);
            return newUri;
        }

        @Override
        public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
                            String sortOrder) {
            //assuming query will always be of the form 'name = ?'
            logd("query called, mNumKeyValuePairs: " + mNumKeyValuePairs + " uri: " + uri);
            if (mKeyValuePairs.containsKey(selectionArgs[0])) {
                MatrixCursor cursor = new MatrixCursor(projection);
                cursor.addRow(new String[]{mKeyValuePairs.get(selectionArgs[0])});
                return cursor;
            }
            return null;
        }

        @Override
        public Bundle call(String method, String request, Bundle args) {
            logd("call called, mNumKeyValuePairs: " + mNumKeyValuePairs + " method: " + method +
                    " request: " + request + ", args=" + args);
            Bundle bundle = new Bundle();
            switch(method) {
                case Settings.CALL_METHOD_GET_GLOBAL:
                case Settings.CALL_METHOD_GET_SECURE:
                case Settings.CALL_METHOD_GET_SYSTEM:
                    if (mKeyValuePairs.containsKey(request)) {
                        bundle.putCharSequence("value", mKeyValuePairs.get(request));
                        logd("returning value pair: " + mKeyValuePairs.get(request) + " for " +
                                request);
                        return bundle;
                    }
                    break;
                case Settings.CALL_METHOD_PUT_GLOBAL:
                case Settings.CALL_METHOD_PUT_SECURE:
                case Settings.CALL_METHOD_PUT_SYSTEM:
                    logd("adding key-value pair: " + request + "-" + (String)args.get("value"));
                    mKeyValuePairs.put(request, (String)args.get("value"));
                    mNumKeyValuePairs++;
                    break;
                case Settings.CALL_METHOD_PUT_CONFIG:
                    logd("PUT_config called");
                    logd("adding config flag: " + request + "-" + args.getString("value"));
                    mFlags.put(request, args.getString("value"));
                    break;
                case Settings.CALL_METHOD_LIST_CONFIG:
                    logd("LIST_config: " + mFlags);
                    Bundle result = new Bundle();
                    result.putSerializable(Settings.NameValueTable.VALUE, mFlags);
                    return result;
                case Settings.CALL_METHOD_SET_ALL_CONFIG:
                    mFlags = (args != null)
                            ? (HashMap) args.getSerializable(Settings.CALL_METHOD_FLAGS_KEY)
                            : new HashMap<>();
                    bundle.putInt(Settings.KEY_CONFIG_SET_ALL_RETURN,
                            Settings.SET_ALL_RESULT_SUCCESS);
                    return bundle;
                default:
                    logd("Unsupported method " + method);
            }
            return null;
        }
    }

    private final HashMap<String, Object> mSystemServices = new HashMap<String, Object>();

    public void setSystemService(String name, Object service) {
        synchronized (mSystemServices) {
            mSystemServices.put(name, service);
        }
    }

    public class FakeContext extends MockContext {
        @Override
        public PackageManager getPackageManager() {
            return mPackageManager;
        }

        @Override
        public boolean bindService(
                Intent serviceIntent,
                ServiceConnection connection,
                int flags) {
            if (mMockBindingFailureForPackage.contains(serviceIntent.getPackage())) {
                return false;
            }
            if (mServiceByServiceConnection.containsKey(connection)) {
                throw new RuntimeException("ServiceConnection already bound: " + connection);
            }
            IInterface service = mServiceByComponentName.get(serviceIntent.getComponent());
            if (service == null) {
                service = mServiceByPackageName.get(serviceIntent.getPackage());
            }
            if (service == null) {
                throw new RuntimeException(
                        String.format("ServiceConnection not found for component: %s, package: %s",
                                serviceIntent.getComponent(), serviceIntent.getPackage()));
            }
            mServiceByServiceConnection.put(connection, service);
            connection.onServiceConnected(serviceIntent.getComponent(), service.asBinder());
            return true;
        }

        @Override
        public void unbindService(
                ServiceConnection connection) {
            IInterface service = mServiceByServiceConnection.remove(connection);
            if (service != null) {
                connection.onServiceDisconnected(mComponentNameByService.get(service));
            } else {
                logd("unbindService: ServiceConnection not found: " + connection);
            }
        }

        @Override
        public Object getSystemService(String name) {
            synchronized (mSystemServices) {
                Object service = mSystemServices.get(name);
                if (service != null) return service;
            }
            switch (name) {
                case Context.TELEPHONY_SERVICE:
                    return mTelephonyManager;
                case Context.ACTIVITY_SERVICE:
                    return mActivityManager;
                case Context.APP_OPS_SERVICE:
                    return mAppOpsManager;
                case Context.NOTIFICATION_SERVICE:
                    return mNotificationManager;
                case Context.USER_SERVICE:
                    return mUserManager;
                case Context.CARRIER_CONFIG_SERVICE:
                    return mCarrierConfigManager;
                case Context.TELEPHONY_SUBSCRIPTION_SERVICE:
                    return mSubscriptionManager;
                case Context.WIFI_SERVICE:
                    return mWifiManager;
                case Context.ALARM_SERVICE:
                    return mAlarmManager;
                case Context.CONNECTIVITY_SERVICE:
                    return mConnectivityManager;
                case Context.USAGE_STATS_SERVICE:
                    return mUsageStatManager;
                case Context.BATTERY_SERVICE:
                    return mBatteryManager;
                case Context.EUICC_SERVICE:
                    return mEuiccManager;
                case Context.TELECOM_SERVICE:
                    return mTelecomManager;
                case Context.DOWNLOAD_SERVICE:
                    return mDownloadManager;
                case Context.TELEPHONY_REGISTRY_SERVICE:
                    return mTelephonyRegistryManager;
                case Context.SYSTEM_CONFIG_SERVICE:
                    return mSystemConfigManager;
                case Context.KEYGUARD_SERVICE:
                    return mKeyguardManager;
                case Context.VCN_MANAGEMENT_SERVICE:
                    return mVcnManager;
                case Context.BATTERY_STATS_SERVICE:
                case Context.DISPLAY_SERVICE:
                case Context.POWER_SERVICE:
                case Context.PERMISSION_SERVICE:
                case Context.LEGACY_PERMISSION_SERVICE:
                    // These are final classes so cannot be mocked,
                    // return real services.
                    return TestApplication.getAppContext().getSystemService(name);
                case Context.POWER_WHITELIST_MANAGER:
                    return mPowerWhitelistManager;
                case Context.LOCATION_SERVICE:
                    return mLocationManager;
                case Context.NETWORK_POLICY_SERVICE:
                    return mNetworkPolicyManager;
                case Context.TELEPHONY_IMS_SERVICE:
                    return mImsManager;
                default:
                    return null;
            }
        }

        @Override
        public String getSystemServiceName(Class<?> serviceClass) {
            if (serviceClass == SubscriptionManager.class) {
                return Context.TELEPHONY_SUBSCRIPTION_SERVICE;
            } else if (serviceClass == AppOpsManager.class) {
                return Context.APP_OPS_SERVICE;
            } else if (serviceClass == TelecomManager.class) {
                return Context.TELECOM_SERVICE;
            } else if (serviceClass == UserManager.class) {
                return Context.USER_SERVICE;
            } else if (serviceClass == ConnectivityManager.class) {
                return Context.CONNECTIVITY_SERVICE;
            } else if (serviceClass == PowerWhitelistManager.class) {
                return Context.POWER_WHITELIST_MANAGER;
            } else if (serviceClass == SystemConfigManager.class) {
                return Context.SYSTEM_CONFIG_SERVICE;
            } else if (serviceClass == ActivityManager.class) {
                return Context.ACTIVITY_SERVICE;
            } else if (serviceClass == LocationManager.class) {
                return Context.LOCATION_SERVICE;
            } else if (serviceClass == CarrierConfigManager.class) {
                return Context.CARRIER_CONFIG_SERVICE;
            } else if (serviceClass == TelephonyManager.class) {
                return Context.TELEPHONY_SERVICE;
            } else if (serviceClass == UiModeManager.class) {
                return Context.UI_MODE_SERVICE;
            } else if (serviceClass == KeyguardManager.class) {
                return Context.KEYGUARD_SERVICE;
            } else if (serviceClass == VcnManager.class) {
                return Context.VCN_MANAGEMENT_SERVICE;
            } else if (serviceClass == ImsManager.class) {
                return Context.TELEPHONY_IMS_SERVICE;
            } else if (serviceClass == TelephonyRegistryManager.class) {
                return Context.TELEPHONY_REGISTRY_SERVICE;
            } else if (serviceClass == NetworkPolicyManager.class) {
                return Context.NETWORK_POLICY_SERVICE;
            } else if (serviceClass == PowerManager.class) {
                return Context.POWER_SERVICE;
            } else if (serviceClass == EuiccManager.class) {
                return Context.EUICC_SERVICE;
            } else if (serviceClass == AlarmManager.class) {
                return Context.ALARM_SERVICE;
            }
            return super.getSystemServiceName(serviceClass);
        }

        @Override
        public int getUserId() {
            return 0;
        }

        @Override
        public AssetManager getAssets() {
            return mAssetManager;
        }

        @Override
        public Resources getResources() {
            return mResources;
        }

        @Override
        public Context createConfigurationContext(Configuration overrideConfiguration) {
            return spy(new FakeContext());
        }

        @Override
        public ApplicationInfo getApplicationInfo() {
            return mApplicationInfo;
        }

        @Override
        public String getOpPackageName() {
            return "com.android.internal.telephony";
        }

        @Override
        public ContentResolver getContentResolver() {
            return mContentResolver;
        }

        @Override
        public Resources.Theme getTheme() {
            return null;
        }

        @Override
        public void unregisterReceiver(BroadcastReceiver receiver) {
        }

        @Override
        public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
            return registerReceiverFakeImpl(receiver, filter);
        }

        @Override
        public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
                String broadcastPermission, Handler scheduler) {
            return registerReceiverFakeImpl(receiver, filter);
        }

        @Override
        public Intent registerReceiverForAllUsers(BroadcastReceiver receiver,
                IntentFilter filter, String broadcastPermission, Handler scheduler) {
            return registerReceiverFakeImpl(receiver, filter);
        }

        @Override
        public Intent registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user,
                IntentFilter filter, String broadcastPermission, Handler scheduler) {
            return registerReceiverFakeImpl(receiver, filter);
        }

        @Override
        public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, int flags) {
            return registerReceiverFakeImpl(receiver, filter);
        }

        @Override
        public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
                String broadcastPermission, Handler scheduler, int flags) {
            return registerReceiverFakeImpl(receiver, filter);
        }

        private Intent registerReceiverFakeImpl(BroadcastReceiver receiver, IntentFilter filter) {
            Intent result = null;
            synchronized (mBroadcastReceiversByAction) {
                for (int i = 0 ; i < filter.countActions() ; i++) {
                    mBroadcastReceiversByAction.put(filter.getAction(i), receiver);
                    if (result == null) {
                        result = mStickyBroadcastByAction.get(filter.getAction(i));
                    }
                }
            }

            return result;
        }

        @Override
        public void sendBroadcast(Intent intent) {
            logd("sendBroadcast called for " + intent.getAction());
            synchronized (mBroadcastReceiversByAction) {
                for (BroadcastReceiver broadcastReceiver :
                        mBroadcastReceiversByAction.get(intent.getAction())) {
                    broadcastReceiver.onReceive(mContext, intent);
                }
            }
        }

        @Override
        public void sendBroadcast(Intent intent, String receiverPermission) {
            logd("sendBroadcast called for " + intent.getAction());
            sendBroadcast(intent);
        }

        @Override
        public void sendBroadcast(Intent intent, String receiverPermission, Bundle initialExtras) {
            logd("sendBroadcast called for " + intent.getAction());
            sendBroadcast(intent);
        }

        @Override
        public void sendOrderedBroadcast(Intent intent, String receiverPermission) {
            logd("sendOrderedBroadcast called for " + intent.getAction());
            sendBroadcast(intent);
        }

        @Override
        public void sendOrderedBroadcast(Intent intent, String receiverPermission,
                BroadcastReceiver resultReceiver, Handler scheduler, int initialCode,
                String initialData, Bundle initialExtras) {
            sendOrderedBroadcast(intent, receiverPermission);
            if (resultReceiver != null) {
                synchronized (mOrderedBroadcastReceivers) {
                    mOrderedBroadcastReceivers.put(intent, resultReceiver);
                }
            }
        }

        @Override
        public void sendOrderedBroadcast(Intent intent, String receiverPermission, Bundle options,
                BroadcastReceiver resultReceiver, Handler scheduler, int initialCode,
                String initialData, Bundle initialExtras) {
            mLastBroadcastOptions = options;
            sendOrderedBroadcast(intent, receiverPermission, resultReceiver, scheduler,
                    initialCode, initialData, initialExtras);
        }

        @Override
        public void sendOrderedBroadcast(Intent intent, String receiverPermission, int appOp,
                BroadcastReceiver resultReceiver, Handler scheduler, int initialCode,
                String initialData, Bundle initialExtras) {
            sendOrderedBroadcast(intent, receiverPermission, resultReceiver, scheduler,
                    initialCode, initialData, initialExtras);
        }

        @Override
        public void sendBroadcastAsUser(Intent intent, UserHandle user) {
            sendBroadcast(intent);
        }

        @Override
        public void sendBroadcastAsUser(Intent intent, UserHandle user,
                                        String receiverPermission) {
            sendBroadcast(intent);
        }

        @Override
        public void sendBroadcastAsUser(Intent intent, UserHandle user,
                                        String receiverPermission, int appOp) {
            sendBroadcast(intent);
        }

        @Override
        public void sendBroadcastMultiplePermissions(Intent intent,
                String[] includePermissions, String[] excludePermissions) {
            sendBroadcast(intent);
        }

        @Override
        public Context createContextAsUser(UserHandle user, int flags) {
            return this;
        }

        @Override
        public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
                String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler,
                int initialCode, String initialData, Bundle initialExtras) {
            logd("sendOrderedBroadcastAsUser called for " + intent.getAction());
            sendBroadcast(intent);
            if (resultReceiver != null) {
                synchronized (mOrderedBroadcastReceivers) {
                    mOrderedBroadcastReceivers.put(intent, resultReceiver);
                }
            }
        }

        @Override
        public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
                String receiverPermission, int appOp, BroadcastReceiver resultReceiver,
                Handler scheduler, int initialCode, String initialData, Bundle initialExtras) {
            logd("sendOrderedBroadcastAsUser called for " + intent.getAction());
            sendBroadcast(intent);
            if (resultReceiver != null) {
                synchronized (mOrderedBroadcastReceivers) {
                    mOrderedBroadcastReceivers.put(intent, resultReceiver);
                }
            }
        }

        @Override
        public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
                String receiverPermission, int appOp, Bundle options,
                BroadcastReceiver resultReceiver, Handler scheduler, int initialCode,
                String initialData, Bundle initialExtras) {
            logd("sendOrderedBroadcastAsUser called for " + intent.getAction());
            mLastBroadcastOptions = options;
            sendBroadcast(intent);
            if (resultReceiver != null) {
                synchronized (mOrderedBroadcastReceivers) {
                    mOrderedBroadcastReceivers.put(intent, resultReceiver);
                }
            }
        }

        @Override
        public void sendOrderedBroadcast(Intent intent, int initialCode, String receiverPermission,
                String receiverAppOp, BroadcastReceiver resultReceiver, Handler scheduler,
                String initialData, Bundle initialExtras, Bundle options) {
            logd("sendOrderedBroadcast called for " + intent.getAction());
            mLastBroadcastOptions = options;
            sendBroadcast(intent);
            if (resultReceiver != null) {
                synchronized (mOrderedBroadcastReceivers) {
                    mOrderedBroadcastReceivers.put(intent, resultReceiver);
                }
            }
        }

        @Override
        public void sendStickyBroadcast(Intent intent) {
            logd("sendStickyBroadcast called for " + intent.getAction());
            synchronized (mBroadcastReceiversByAction) {
                sendBroadcast(intent);
                mStickyBroadcastByAction.put(intent.getAction(), intent);
            }
        }

        @Override
        public void sendStickyBroadcastAsUser(Intent intent, UserHandle ignored) {
            logd("sendStickyBroadcastAsUser called for " + intent.getAction());
            sendStickyBroadcast(intent);
        }

        @Override
        public Context createPackageContextAsUser(String packageName, int flags, UserHandle user)
                throws PackageManager.NameNotFoundException {
            return this;
        }

        @Override
        public void enforceCallingOrSelfPermission(String permission, String message) {
            if (mPermissionTable.contains(permission)
                    || mPermissionTable.contains(PERMISSION_ENABLE_ALL)) {
                return;
            }
            logd("requested permission: " + permission + " got denied");
            throw new SecurityException(permission + " denied: " + message);
        }

        @Override
        public void enforcePermission(String permission, int pid, int uid, String message) {
            enforceCallingOrSelfPermission(permission, message);
        }

        @Override
        public void enforceCallingPermission(String permission, String message) {
            enforceCallingOrSelfPermission(permission, message);
        }

        @Override
        public int checkCallingOrSelfPermission(String permission) {
            if (mPermissionTable.contains(permission)
                    || mPermissionTable.contains(PERMISSION_ENABLE_ALL)) {
                logd("checkCallingOrSelfPermission: " + permission + " return GRANTED");
                return PackageManager.PERMISSION_GRANTED;
            } else {
                logd("checkCallingOrSelfPermission: " + permission + " return DENIED");
                return PackageManager.PERMISSION_DENIED;
            }
        }

        @Override
        public int checkPermission(String permission, int pid, int uid) {
            return checkCallingOrSelfPermission(permission);
        }

        @Override
        public SharedPreferences getSharedPreferences(String name, int mode) {
            return mSharedPreferences;
        }

        @Override
        public String getPackageName() {
            return "com.android.internal.telephony";
        }

        @Override
        public Context getApplicationContext() {
            return null;
        }

        @Override
        public void startActivity(Intent intent) {}
    }

    private final Multimap<String, ComponentName> mComponentNamesByAction =
            ArrayListMultimap.create();
    private final Map<ComponentName, IInterface> mServiceByComponentName =
            new HashMap<ComponentName, IInterface>();
    private final Map<String, IInterface> mServiceByPackageName =
            new HashMap<String, IInterface>();
    private final Map<ComponentName, ServiceInfo> mServiceInfoByComponentName =
            new HashMap<ComponentName, ServiceInfo>();
    private final Map<ComponentName, IntentFilter> mIntentFilterByComponentName = new HashMap<>();
    private final Map<IInterface, ComponentName> mComponentNameByService =
            new HashMap<IInterface, ComponentName>();
    private final Set<String> mMockBindingFailureForPackage = new HashSet();
    private final Map<ServiceConnection, IInterface> mServiceByServiceConnection =
            new HashMap<ServiceConnection, IInterface>();
    private final Multimap<String, BroadcastReceiver> mBroadcastReceiversByAction =
            ArrayListMultimap.create();
    private final HashMap<String, Intent> mStickyBroadcastByAction =
            new HashMap<String, Intent>();
    private final Multimap<Intent, BroadcastReceiver> mOrderedBroadcastReceivers =
            ArrayListMultimap.create();
    private final HashSet<String> mPermissionTable = new HashSet<>();
    private final HashSet<String> mSystemFeatures = new HashSet<>();
    private Bundle mLastBroadcastOptions;


    // The application context is the most important object this class provides to the system
    // under test.
    private final Context mContext = spy(new FakeContext());
    // We then create a spy on the application context allowing standard Mockito-style
    // when(...) logic to be used to add specific little responses where needed.

    private final Resources mResources = mock(Resources.class);
    private final ApplicationInfo mApplicationInfo = mock(ApplicationInfo.class);
    private final PackageManager mPackageManager = mock(PackageManager.class);
    private final TelephonyManager mTelephonyManager = mock(TelephonyManager.class);
    private final ActivityManager mActivityManager = mock(ActivityManager.class);
    private final DownloadManager mDownloadManager = mock(DownloadManager.class);
    private final AppOpsManager mAppOpsManager = mock(AppOpsManager.class);
    private final NotificationManager mNotificationManager = mock(NotificationManager.class);
    private final UserManager mUserManager = mock(UserManager.class);
    private final CarrierConfigManager mCarrierConfigManager = mock(CarrierConfigManager.class);
    private final SubscriptionManager mSubscriptionManager = mock(SubscriptionManager.class);
    private final AlarmManager mAlarmManager = mock(AlarmManager.class);
    private final AssetManager mAssetManager = new AssetManager();
    private final ConnectivityManager mConnectivityManager = mock(ConnectivityManager.class);
    private final UsageStatsManager mUsageStatManager = null;
    private final WifiManager mWifiManager = mock(WifiManager.class);
    private final BatteryManager mBatteryManager = mock(BatteryManager.class);
    private final EuiccManager mEuiccManager = mock(EuiccManager.class);
    private final TelecomManager mTelecomManager = mock(TelecomManager.class);
    private final PackageInfo mPackageInfo = mock(PackageInfo.class);
    private final TelephonyRegistryManager mTelephonyRegistryManager =
        mock(TelephonyRegistryManager.class);
    private final SystemConfigManager mSystemConfigManager = mock(SystemConfigManager.class);
    private final PowerWhitelistManager mPowerWhitelistManager = mock(PowerWhitelistManager.class);
    private final LocationManager mLocationManager = mock(LocationManager.class);
    private final KeyguardManager mKeyguardManager = mock(KeyguardManager.class);
    private final VcnManager mVcnManager = mock(VcnManager.class);
    private final NetworkPolicyManager mNetworkPolicyManager = mock(NetworkPolicyManager.class);
    private final ImsManager mImsManager = mock(ImsManager.class);
    private final Configuration mConfiguration = new Configuration();
    private final DisplayMetrics mDisplayMetrics = new DisplayMetrics();
    private final SharedPreferences mSharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(TestApplication.getAppContext());
    private final MockContentResolver mContentResolver = new MockContentResolver();
    private final PersistableBundle mBundle = new PersistableBundle();
    private final Network mNetwork = mock(Network.class);
    private int mNetworkId = 200;

    public ContextFixture() {
        MockitoAnnotations.initMocks(this);

        doAnswer(new Answer<List<ResolveInfo>>() {
            @Override
            public List<ResolveInfo> answer(InvocationOnMock invocation) throws Throwable {
                return doQueryIntentServices((Intent) invocation.getArguments()[0]);
            }
        }).when(mPackageManager).queryIntentServices((Intent) any(), anyInt());

        doAnswer(new Answer<List<ResolveInfo>>() {
            @Override
            public List<ResolveInfo> answer(InvocationOnMock invocation) throws Throwable {
                return doQueryIntentServices((Intent) invocation.getArguments()[0]);
            }
        }).when(mPackageManager).queryIntentServicesAsUser((Intent) any(), anyInt(), any());

        try {
            doReturn(mPackageInfo).when(mPackageManager).getPackageInfo(nullable(String.class),
                    anyInt());
        } catch (NameNotFoundException e) {
            Log.d(TAG, "NameNotFoundException: e=" + e);
        }

        doAnswer((Answer<Boolean>)
                invocation -> mSystemFeatures.contains((String) invocation.getArgument(0)))
                .when(mPackageManager).hasSystemFeature(any());

        try {
            doReturn(mResources).when(mPackageManager).getResourcesForApplication(anyString());
        } catch (NameNotFoundException ex) {
            Log.d(TAG, "NameNotFoundException: ex=" + ex);
        }

        doReturn(mBundle).when(mCarrierConfigManager).getConfigForSubId(anyInt());
        doReturn(mBundle).when(mCarrierConfigManager).getConfig();
        doReturn(mBundle).when(mCarrierConfigManager).getConfigForSubId(anyInt(), anyString());
        doAnswer(invocation -> mNetworkId++).when(mNetwork).getNetId();
        doReturn(mNetwork).when(mConnectivityManager).registerNetworkAgent(
                any(), any(), any(), any(), any(), any(), anyInt());

        doReturn(true).when(mEuiccManager).isEnabled();

        mConfiguration.locale = Locale.US;
        doReturn(mConfiguration).when(mResources).getConfiguration();

        mDisplayMetrics.density = 2.25f;
        doReturn(mDisplayMetrics).when(mResources).getDisplayMetrics();
        mPermissionTable.add(PERMISSION_ENABLE_ALL);
    }

    @Override
    public Context getTestDouble() {
        return mContext;
    }

    public void putResource(int id, final String value) {
        when(mResources.getText(eq(id))).thenReturn(value);
        when(mResources.getString(eq(id))).thenReturn(value);
        when(mResources.getString(eq(id), any())).thenAnswer(new Answer<String>() {
            @Override
            public String answer(InvocationOnMock invocation) {
                Object[] args = invocation.getArguments();
                return String.format(value, Arrays.copyOfRange(args, 1, args.length));
            }
        });
    }

    public void putBooleanResource(int id, boolean value) {
        when(mResources.getBoolean(eq(id))).thenReturn(value);
    }

    public void putStringArrayResource(int id, String[] values) {
        doReturn(values).when(mResources).getStringArray(eq(id));
    }

    public void putIntArrayResource(int id, int[] values) {
        doReturn(values).when(mResources).getIntArray(eq(id));
    }

    public void putIntResource(int id, int value) {
        doReturn(value).when(mResources).getInteger(eq(id));
    }

    public PersistableBundle getCarrierConfigBundle() {
        return mBundle;
    }

    public void addService(String action, ComponentName name, String packageName,
                           IInterface service, ServiceInfo serviceInfo) {
        addService(action, name, packageName, service, serviceInfo, null /* filter */);
    }

    public void addService(String action, ComponentName name, String packageName,
            IInterface service, ServiceInfo serviceInfo, IntentFilter filter) {
        mComponentNamesByAction.put(action, name);
        mServiceInfoByComponentName.put(name, serviceInfo);
        mIntentFilterByComponentName.put(name, filter);
        mServiceByComponentName.put(name, service);
        mServiceByPackageName.put(packageName, service);
        mComponentNameByService.put(service, name);
    }

    public void mockBindingFailureForPackage(String packageName) {
        mMockBindingFailureForPackage.add(packageName);
    }

    private List<ResolveInfo> doQueryIntentServices(Intent intent) {
        List<ResolveInfo> result = new ArrayList<ResolveInfo>();
        for (ComponentName componentName : mComponentNamesByAction.get(intent.getAction())) {
            ResolveInfo resolveInfo = new ResolveInfo();
            resolveInfo.serviceInfo = mServiceInfoByComponentName.get(componentName);
            resolveInfo.filter = mIntentFilterByComponentName.get(componentName);
            result.add(resolveInfo);
        }
        return result;
    }

    public void sendBroadcastToOrderedBroadcastReceivers() {
        synchronized (mOrderedBroadcastReceivers) {
            // having a map separate from mOrderedBroadcastReceivers is helpful here as onReceive()
            // call within the loop may lead to sendOrderedBroadcast() which can add to
            // mOrderedBroadcastReceivers
            Collection<Map.Entry<Intent, BroadcastReceiver>> map =
                    mOrderedBroadcastReceivers.entries();
            for (Map.Entry<Intent, BroadcastReceiver> entry : map) {
                entry.getValue().onReceive(mContext, entry.getKey());
                mOrderedBroadcastReceivers.remove(entry.getKey(), entry.getValue());
            }
        }
    }

    public void addCallingOrSelfPermission(String permission) {
        synchronized (mPermissionTable) {
            if (mPermissionTable != null && permission != null) {
                mPermissionTable.remove(PERMISSION_ENABLE_ALL);
                mPermissionTable.add(permission);
            }
        }
    }

    public void addCallingOrSelfPermissionToCurrentPermissions(String permission) {
        synchronized (mPermissionTable) {
            if (mPermissionTable != null && permission != null) {
                mPermissionTable.add(permission);
            }
        }
    }

    public void removeCallingOrSelfPermission(String permission) {
        synchronized (mPermissionTable) {
            if (mPermissionTable != null && permission != null) {
                mPermissionTable.remove(permission);
            }
        }
    }

    public void addSystemFeature(String feature) {
        mSystemFeatures.add(feature);
    }

    public Bundle getLastBroadcastOptions() {
        return mLastBroadcastOptions;
    }

    private static void logd(String s) {
        Log.d(TAG, s);
    }
}