1 /* 2 * Copyright (C) 2015 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 17 package com.android.server.wifi; 18 19 import static org.junit.Assert.assertTrue; 20 import static org.mockito.Mockito.mock; 21 22 import android.os.Handler; 23 import android.os.Message; 24 import android.util.SparseArray; 25 26 import java.util.HashMap; 27 import java.util.Map; 28 29 /** 30 * Creates a mock WifiMonitor. 31 * WARNING: This does not perfectly mock the behavior of WifiMonitor at the moment 32 * ex. startMonitoring does nothing and will not send a connection/disconnection event 33 */ 34 public class MockWifiMonitor extends WifiMonitor { 35 private final Map<String, SparseArray<Handler>> mHandlerMap = new HashMap<>(); 36 37 public MockWifiMonitor() { 38 super(mock(WifiInjector.class)); 39 } 40 41 @Override 42 public void registerHandler(String iface, int what, Handler handler) { 43 SparseArray<Handler> ifaceHandlers = mHandlerMap.get(iface); 44 if (ifaceHandlers == null) { 45 ifaceHandlers = new SparseArray<>(); 46 mHandlerMap.put(iface, ifaceHandlers); 47 } 48 ifaceHandlers.put(what, handler); 49 } 50 51 @Override 52 public synchronized void startMonitoring(String iface, boolean isStaIface) { 53 return; 54 } 55 56 /** 57 * Send a message and assert that it was dispatched to a handler 58 */ 59 public void sendMessage(String iface, int what) { 60 sendMessage(iface, Message.obtain(null, what)); 61 } 62 63 public void sendMessage(String iface, Message message) { 64 SparseArray<Handler> ifaceHandlers = mHandlerMap.get(iface); 65 if (ifaceHandlers != null) { 66 assertTrue("No handler for iface=" + iface + ",what=" + message.what, 67 sendMessage(ifaceHandlers, message)); 68 } else { 69 boolean sent = false; 70 for (Map.Entry<String, SparseArray<Handler>> entry : mHandlerMap.entrySet()) { 71 if (sendMessage(entry.getValue(), Message.obtain(message))) { 72 sent = true; 73 } 74 } 75 assertTrue("No handler for message with nonexistant iface, iface=" + iface 76 + ",what=" + message.what, sent); 77 } 78 } 79 80 private boolean sendMessage(SparseArray<Handler> ifaceHandlers, Message message) { 81 Handler handler = ifaceHandlers.get(message.what); 82 if (handler != null) { 83 message.setTarget(handler); 84 message.sendToTarget(); 85 return true; 86 } 87 return false; 88 } 89 90 } 91