1 /* 2 * Copyright (C) 2021 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.bedstead.dpmwrapper; 17 18 import static org.mockito.ArgumentMatchers.any; 19 import static org.mockito.Mockito.doAnswer; 20 import static org.mockito.Mockito.doReturn; 21 22 import android.content.Context; 23 import android.os.UserManager; 24 import android.util.Log; 25 26 import com.android.bedstead.dpmwrapper.TestAppSystemServiceFactory.ServiceManagerWrapper; 27 28 import org.mockito.Mockito; 29 import org.mockito.stubbing.Answer; 30 31 import java.util.HashMap; 32 33 final class UserManagerWrapper extends ServiceManagerWrapper<UserManager> { 34 35 private static final String TAG = UserManagerWrapper.class.getSimpleName(); 36 37 private static final HashMap<Context, UserManager> sSpies = new HashMap<>(); 38 39 @Override getWrapper(Context context, UserManager manager, Answer<?> answer)40 UserManager getWrapper(Context context, UserManager manager, Answer<?> answer) { 41 int userId = context.getUserId(); 42 UserManager spy = sSpies.get(context); 43 if (spy != null) { 44 Log.d(TAG, "get(): returning cached spy for user " + userId); 45 return spy; 46 } 47 48 spy = Mockito.spy(manager); 49 String spyString = "UserManagerWrapper#" + System.identityHashCode(spy); 50 Log.d(TAG, "get(): created spy for user " + context.getUserId() + ": " + spyString); 51 52 // TODO(b/176993670): ideally there should be a way to automatically mock all DPM methods, 53 // but that's probably not doable, as there is no contract (such as an interface) to specify 54 // which ones should be spied and which ones should not (in fact, if there was an interface, 55 // we wouldn't need Mockito and could wrap the calls using java's DynamicProxy 56 try { 57 doReturn(spyString).when(spy).toString(); 58 59 // Used by HardwarePropertiesManagerTest 60 doAnswer(answer).when(spy).getApplicationRestrictions(any()); 61 } catch (Exception e) { 62 // Should never happen, but needs to be catch as some methods declare checked exceptions 63 Log.wtf("Exception setting mocks", e); 64 } 65 66 sSpies.put(context, spy); 67 Log.d(TAG, "get(): returning new spy for context " + context + " and user " + userId); 68 69 return spy; 70 } 71 } 72