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