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.when; 20 21 import android.content.Context; 22 import android.util.Log; 23 24 import com.android.bedstead.dpmwrapper.TestAppSystemServiceFactory.ServiceManagerWrapper; 25 26 import org.mockito.Mockito; 27 import org.mockito.stubbing.Answer; 28 29 import java.util.HashMap; 30 31 final class GenericManagerWrapper extends ServiceManagerWrapper<GenericManager> { 32 33 private static final String TAG = GenericManagerWrapper.class.getSimpleName(); 34 35 private static final HashMap<Context, GenericManager> sMocks = new HashMap<>(); 36 37 @Override getWrapper(Context context, GenericManager manager, Answer<?> answer)38 GenericManager getWrapper(Context context, GenericManager manager, Answer<?> answer) { 39 int userId = context.getUserId(); 40 GenericManager mock = sMocks.get(context); 41 if (mock != null) { 42 Log.d(TAG, "get(): returning cached mock for user " + userId); 43 return mock; 44 } 45 46 mock = Mockito.mock(GenericManager.class); 47 String mockString = "GenericManagerWrapper#" + System.identityHashCode(mock); 48 Log.d(TAG, "get(): creatied mock for user " + context.getUserId() + ": " + mockString); 49 50 // TODO(b/176993670): given that GenericManager is an interface, we could dynamilly mock all 51 // methods (for example, using Java's DynamicProxy), but given that DpmWrapper will 52 // eventually go away, it's not worth the effort 53 try { 54 when(mock.toString()).thenReturn(mockString); 55 when(mock.getSecureIntSettings(any())).thenAnswer(answer); 56 } catch (Exception e) { 57 // Should never happen, but needs to be catch as some methods declare checked exceptions 58 Log.wtf("Exception setting mocks", e); 59 } 60 61 sMocks.put(context, mock); 62 Log.d(TAG, "get(): returning new mock for context " + context + " and user " + userId); 63 64 return mock; 65 } 66 } 67