1/*
2 * Copyright (C) 2016 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 */
16package com.android.server.wifi;
17
18import static org.junit.Assert.assertEquals;
19import static org.junit.Assert.assertTrue;
20import static org.mockito.Mockito.*;
21
22import android.net.wifi.ScanResult;
23import android.net.wifi.WifiConfiguration;
24import android.test.suitebuilder.annotation.SmallTest;
25import android.util.Base64;
26
27import com.android.server.wifi.hotspot2.NetworkDetail;
28
29import org.junit.Before;
30import org.junit.Test;
31import org.mockito.Mock;
32import org.mockito.MockitoAnnotations;
33
34import java.io.ByteArrayOutputStream;
35import java.io.PrintWriter;
36import java.util.regex.Matcher;
37import java.util.regex.Pattern;
38
39/**
40 * Unit tests for {@link com.android.server.wifi.WifiMetrics}.
41 */
42@SmallTest
43public class WifiMetricsTest {
44
45    WifiMetrics mWifiMetrics;
46    WifiMetricsProto.WifiLog mDeserializedWifiMetrics;
47    @Mock Clock mClock;
48
49    @Before
50    public void setUp() throws Exception {
51        MockitoAnnotations.initMocks(this);
52        mDeserializedWifiMetrics = null;
53        when(mClock.elapsedRealtime()).thenReturn((long) 0);
54        mWifiMetrics = new WifiMetrics(mClock);
55    }
56
57    /**
58     * Test that startConnectionEvent and endConnectionEvent can be called repeatedly and out of
59     * order. Only tests no exception occurs. Creates 3 ConnectionEvents.
60     */
61    @Test
62    public void startAndEndConnectionEventSucceeds() throws Exception {
63        //Start and end Connection event
64        mWifiMetrics.startConnectionEvent(null, "RED",
65                WifiMetricsProto.ConnectionEvent.ROAM_ENTERPRISE);
66        mWifiMetrics.endConnectionEvent(
67                WifiMetrics.ConnectionEvent.FAILURE_AUTHENTICATION_FAILURE,
68                WifiMetricsProto.ConnectionEvent.HLF_DHCP);
69        //end Connection event without starting one
70        mWifiMetrics.endConnectionEvent(
71                WifiMetrics.ConnectionEvent.FAILURE_AUTHENTICATION_FAILURE,
72                WifiMetricsProto.ConnectionEvent.HLF_DHCP);
73        //start two ConnectionEvents in a row
74        mWifiMetrics.startConnectionEvent(null, "BLUE",
75                WifiMetricsProto.ConnectionEvent.ROAM_ENTERPRISE);
76        mWifiMetrics.startConnectionEvent(null, "GREEN",
77                WifiMetricsProto.ConnectionEvent.ROAM_ENTERPRISE);
78    }
79
80    private static final long TEST_RECORD_DURATION_SEC = 12 * 60 * 60;
81    private static final long TEST_RECORD_DURATION_MILLIS = TEST_RECORD_DURATION_SEC * 1000;
82
83    /**
84     * Simulate how dumpsys gets the proto from mWifiMetrics, filter the proto bytes out and
85     * deserialize them into mDeserializedWifiMetrics
86     */
87    public void dumpProtoAndDeserialize() throws Exception {
88        ByteArrayOutputStream stream = new ByteArrayOutputStream();
89        PrintWriter writer = new PrintWriter(stream);
90        String[] args = new String[0];
91
92        when(mClock.elapsedRealtime()).thenReturn(TEST_RECORD_DURATION_MILLIS);
93        //Test proto dump, by passing in proto arg option
94        args = new String[]{WifiMetrics.PROTO_DUMP_ARG};
95        mWifiMetrics.dump(null, writer, args);
96        writer.flush();
97        Pattern pattern = Pattern.compile(
98                "(?<=WifiMetrics:\\n)([\\s\\S]*)(?=EndWifiMetrics)");
99        Matcher matcher = pattern.matcher(stream.toString());
100        assertTrue("Proto Byte string found in WifiMetrics.dump():\n" + stream.toString(),
101                matcher.find());
102        String protoByteString = matcher.group(1);
103        byte[] protoBytes = Base64.decode(protoByteString, Base64.DEFAULT);
104        mDeserializedWifiMetrics = WifiMetricsProto.WifiLog.parseFrom(protoBytes);
105    }
106
107    @Test
108    public void dumpHumanReadable() throws Exception {
109        ByteArrayOutputStream stream = new ByteArrayOutputStream();
110        PrintWriter writer = new PrintWriter(stream);
111        String[] args = new String[0];
112        mWifiMetrics.dump(null, writer, args);
113        writer.flush();
114        assertTrue("stream.toString().contains(\"WifiMetrics\")",
115                stream.toString().contains("WifiMetrics"));
116    }
117
118    @Test
119    public void testDumpProtoAndDeserialize() throws Exception {
120        setAndIncrementMetrics();
121        dumpProtoAndDeserialize();
122        assertDeserializedMetricsCorrect();
123    }
124
125    private static final int NUM_SAVED_NETWORKS = 1;
126    private static final int NUM_OPEN_NETWORKS = 2;
127    private static final int NUM_PERSONAL_NETWORKS = 3;
128    private static final int NUM_ENTERPRISE_NETWORKS = 5;
129    private static final boolean TEST_VAL_IS_LOCATION_ENABLED = true;
130    private static final boolean IS_SCANNING_ALWAYS_ENABLED = true;
131    private static final int NUM_NEWTORKS_ADDED_BY_USER = 13;
132    private static final int NUM_NEWTORKS_ADDED_BY_APPS = 17;
133    private static final int NUM_EMPTY_SCAN_RESULTS = 19;
134    private static final int NUM_NON_EMPTY_SCAN_RESULTS = 23;
135    private static final int NUM_SCAN_UNKNOWN = 1;
136    private static final int NUM_SCAN_SUCCESS = 2;
137    private static final int NUM_SCAN_FAILURE_INTERRUPTED = 3;
138    private static final int NUM_SCAN_FAILURE_INVALID_CONFIGURATION = 5;
139    private static final int NUM_WIFI_UNKNOWN_SCREEN_OFF = 3;
140    private static final int NUM_WIFI_UNKNOWN_SCREEN_ON = 5;
141    private static final int NUM_WIFI_ASSOCIATED_SCREEN_OFF = 7;
142    private static final int NUM_WIFI_ASSOCIATED_SCREEN_ON = 11;
143    private static final int NUM_CONNECTIVITY_WATCHDOG_PNO_GOOD = 11;
144    private static final int NUM_CONNECTIVITY_WATCHDOG_PNO_BAD = 12;
145    private static final int NUM_CONNECTIVITY_WATCHDOG_BACKGROUND_GOOD = 13;
146    private static final int NUM_CONNECTIVITY_WATCHDOG_BACKGROUND_BAD = 14;
147    private static final int NUM_LAST_RESORT_WATCHDOG_TRIGGERS = 1;
148    private static final int NUM_LAST_RESORT_WATCHDOG_BAD_ASSOCIATION_NETWORKS_TOTAL = 2;
149    private static final int NUM_LAST_RESORT_WATCHDOG_BAD_AUTHENTICATION_NETWORKS_TOTAL = 3;
150    private static final int NUM_LAST_RESORT_WATCHDOG_BAD_DHCP_NETWORKS_TOTAL = 4;
151    private static final int NUM_LAST_RESORT_WATCHDOG_BAD_OTHER_NETWORKS_TOTAL = 5;
152    private static final int NUM_LAST_RESORT_WATCHDOG_AVAILABLE_NETWORKS_TOTAL = 6;
153    private static final int NUM_LAST_RESORT_WATCHDOG_TRIGGERS_WITH_BAD_ASSOCIATION = 7;
154    private static final int NUM_LAST_RESORT_WATCHDOG_TRIGGERS_WITH_BAD_AUTHENTICATION = 8;
155    private static final int NUM_LAST_RESORT_WATCHDOG_TRIGGERS_WITH_BAD_DHCP = 9;
156    private static final int NUM_LAST_RESORT_WATCHDOG_TRIGGERS_WITH_BAD_OTHER = 10;
157    /**
158     * Set simple metrics, increment others
159     */
160    public void setAndIncrementMetrics() throws Exception {
161        mWifiMetrics.setNumSavedNetworks(NUM_SAVED_NETWORKS);
162        mWifiMetrics.setNumOpenNetworks(NUM_OPEN_NETWORKS);
163        mWifiMetrics.setNumPersonalNetworks(NUM_PERSONAL_NETWORKS);
164        mWifiMetrics.setNumEnterpriseNetworks(NUM_ENTERPRISE_NETWORKS);
165        mWifiMetrics.setNumNetworksAddedByUser(NUM_NEWTORKS_ADDED_BY_USER);
166        mWifiMetrics.setNumNetworksAddedByApps(NUM_NEWTORKS_ADDED_BY_APPS);
167        mWifiMetrics.setIsLocationEnabled(TEST_VAL_IS_LOCATION_ENABLED);
168        mWifiMetrics.setIsScanningAlwaysEnabled(IS_SCANNING_ALWAYS_ENABLED);
169
170        for (int i = 0; i < NUM_EMPTY_SCAN_RESULTS; i++) {
171            mWifiMetrics.incrementEmptyScanResultCount();
172        }
173        for (int i = 0; i < NUM_NON_EMPTY_SCAN_RESULTS; i++) {
174            mWifiMetrics.incrementNonEmptyScanResultCount();
175        }
176        mWifiMetrics.incrementScanReturnEntry(WifiMetricsProto.WifiLog.SCAN_UNKNOWN,
177                NUM_SCAN_UNKNOWN);
178        mWifiMetrics.incrementScanReturnEntry(WifiMetricsProto.WifiLog.SCAN_SUCCESS,
179                NUM_SCAN_SUCCESS);
180        mWifiMetrics.incrementScanReturnEntry(
181                WifiMetricsProto.WifiLog.SCAN_FAILURE_INTERRUPTED,
182                NUM_SCAN_FAILURE_INTERRUPTED);
183        mWifiMetrics.incrementScanReturnEntry(
184                WifiMetricsProto.WifiLog.SCAN_FAILURE_INVALID_CONFIGURATION,
185                NUM_SCAN_FAILURE_INVALID_CONFIGURATION);
186        for (int i = 0; i < NUM_WIFI_UNKNOWN_SCREEN_OFF; i++) {
187            mWifiMetrics.incrementWifiSystemScanStateCount(WifiMetricsProto.WifiLog.WIFI_UNKNOWN,
188                    false);
189        }
190        for (int i = 0; i < NUM_WIFI_UNKNOWN_SCREEN_ON; i++) {
191            mWifiMetrics.incrementWifiSystemScanStateCount(WifiMetricsProto.WifiLog.WIFI_UNKNOWN,
192                    true);
193        }
194        for (int i = 0; i < NUM_WIFI_ASSOCIATED_SCREEN_OFF; i++) {
195            mWifiMetrics.incrementWifiSystemScanStateCount(WifiMetricsProto.WifiLog.WIFI_ASSOCIATED,
196                    false);
197        }
198        for (int i = 0; i < NUM_WIFI_ASSOCIATED_SCREEN_ON; i++) {
199            mWifiMetrics.incrementWifiSystemScanStateCount(WifiMetricsProto.WifiLog.WIFI_ASSOCIATED,
200                    true);
201        }
202        for (int i = 0; i < NUM_CONNECTIVITY_WATCHDOG_PNO_GOOD; i++) {
203            mWifiMetrics.incrementNumConnectivityWatchdogPnoGood();
204        }
205        for (int i = 0; i < NUM_CONNECTIVITY_WATCHDOG_PNO_BAD; i++) {
206            mWifiMetrics.incrementNumConnectivityWatchdogPnoBad();
207        }
208        for (int i = 0; i < NUM_CONNECTIVITY_WATCHDOG_BACKGROUND_GOOD; i++) {
209            mWifiMetrics.incrementNumConnectivityWatchdogBackgroundGood();
210        }
211        for (int i = 0; i < NUM_CONNECTIVITY_WATCHDOG_BACKGROUND_BAD; i++) {
212            mWifiMetrics.incrementNumConnectivityWatchdogBackgroundBad();
213        }
214        for (int i = 0; i < NUM_LAST_RESORT_WATCHDOG_TRIGGERS; i++) {
215            mWifiMetrics.incrementNumLastResortWatchdogTriggers();
216        }
217        mWifiMetrics.addCountToNumLastResortWatchdogBadAssociationNetworksTotal(
218                NUM_LAST_RESORT_WATCHDOG_BAD_ASSOCIATION_NETWORKS_TOTAL);
219        mWifiMetrics.addCountToNumLastResortWatchdogBadAuthenticationNetworksTotal(
220                NUM_LAST_RESORT_WATCHDOG_BAD_AUTHENTICATION_NETWORKS_TOTAL);
221        mWifiMetrics.addCountToNumLastResortWatchdogBadDhcpNetworksTotal(
222                NUM_LAST_RESORT_WATCHDOG_BAD_DHCP_NETWORKS_TOTAL);
223        mWifiMetrics.addCountToNumLastResortWatchdogBadOtherNetworksTotal(
224                NUM_LAST_RESORT_WATCHDOG_BAD_OTHER_NETWORKS_TOTAL);
225        mWifiMetrics.addCountToNumLastResortWatchdogAvailableNetworksTotal(
226                NUM_LAST_RESORT_WATCHDOG_AVAILABLE_NETWORKS_TOTAL);
227        for (int i = 0; i < NUM_LAST_RESORT_WATCHDOG_TRIGGERS_WITH_BAD_ASSOCIATION; i++) {
228            mWifiMetrics.incrementNumLastResortWatchdogTriggersWithBadAssociation();
229        }
230        for (int i = 0; i < NUM_LAST_RESORT_WATCHDOG_TRIGGERS_WITH_BAD_AUTHENTICATION; i++) {
231            mWifiMetrics.incrementNumLastResortWatchdogTriggersWithBadAuthentication();
232        }
233        for (int i = 0; i < NUM_LAST_RESORT_WATCHDOG_TRIGGERS_WITH_BAD_DHCP; i++) {
234            mWifiMetrics.incrementNumLastResortWatchdogTriggersWithBadDhcp();
235        }
236        for (int i = 0; i < NUM_LAST_RESORT_WATCHDOG_TRIGGERS_WITH_BAD_OTHER; i++) {
237            mWifiMetrics.incrementNumLastResortWatchdogTriggersWithBadOther();
238        }
239    }
240
241    /**
242     * Assert that values in deserializedWifiMetrics match those set in 'setAndIncrementMetrics'
243     */
244    public void assertDeserializedMetricsCorrect() throws Exception {
245        assertEquals("mDeserializedWifiMetrics.numSavedNetworks == NUM_SAVED_NETWORKS",
246                mDeserializedWifiMetrics.numSavedNetworks, NUM_SAVED_NETWORKS);
247        assertEquals("mDeserializedWifiMetrics.numOpenNetworks == NUM_OPEN_NETWORKS",
248                mDeserializedWifiMetrics.numOpenNetworks, NUM_OPEN_NETWORKS);
249        assertEquals("mDeserializedWifiMetrics.numPersonalNetworks == NUM_PERSONAL_NETWORKS",
250                mDeserializedWifiMetrics.numPersonalNetworks, NUM_PERSONAL_NETWORKS);
251        assertEquals("mDeserializedWifiMetrics.numEnterpriseNetworks "
252                        + "== NUM_ENTERPRISE_NETWORKS",
253                mDeserializedWifiMetrics.numEnterpriseNetworks, NUM_ENTERPRISE_NETWORKS);
254        assertEquals("mDeserializedWifiMetrics.numNetworksAddedByUser "
255                        + "== NUM_NEWTORKS_ADDED_BY_USER",
256                mDeserializedWifiMetrics.numNetworksAddedByUser, NUM_NEWTORKS_ADDED_BY_USER);
257        assertEquals("mDeserializedWifiMetrics.numNetworksAddedByApps "
258                        + "== NUM_NEWTORKS_ADDED_BY_APPS",
259                mDeserializedWifiMetrics.numNetworksAddedByApps, NUM_NEWTORKS_ADDED_BY_APPS);
260        assertEquals("mDeserializedWifiMetrics.isLocationEnabled == TEST_VAL_IS_LOCATION_ENABLED",
261                mDeserializedWifiMetrics.isLocationEnabled, TEST_VAL_IS_LOCATION_ENABLED);
262        assertEquals("mDeserializedWifiMetrics.isScanningAlwaysEnabled "
263                        + "== IS_SCANNING_ALWAYS_ENABLED",
264                mDeserializedWifiMetrics.isScanningAlwaysEnabled, IS_SCANNING_ALWAYS_ENABLED);
265        assertEquals("mDeserializedWifiMetrics.numEmptyScanResults == NUM_EMPTY_SCAN_RESULTS",
266                mDeserializedWifiMetrics.numEmptyScanResults, NUM_EMPTY_SCAN_RESULTS);
267        assertEquals("mDeserializedWifiMetrics.numNonEmptyScanResults == "
268                        + "NUM_NON_EMPTY_SCAN_RESULTS",
269                mDeserializedWifiMetrics.numNonEmptyScanResults, NUM_NON_EMPTY_SCAN_RESULTS);
270        assertScanReturnEntryEquals(WifiMetricsProto.WifiLog.SCAN_UNKNOWN,
271                NUM_SCAN_UNKNOWN);
272        assertScanReturnEntryEquals(WifiMetricsProto.WifiLog.SCAN_SUCCESS,
273                NUM_SCAN_SUCCESS);
274        assertScanReturnEntryEquals(WifiMetricsProto.WifiLog.SCAN_FAILURE_INTERRUPTED,
275                NUM_SCAN_FAILURE_INTERRUPTED);
276        assertScanReturnEntryEquals(WifiMetricsProto.WifiLog.SCAN_FAILURE_INVALID_CONFIGURATION,
277                NUM_SCAN_FAILURE_INVALID_CONFIGURATION);
278        assertSystemStateEntryEquals(WifiMetricsProto.WifiLog.WIFI_UNKNOWN, false,
279                NUM_WIFI_UNKNOWN_SCREEN_OFF);
280        assertSystemStateEntryEquals(WifiMetricsProto.WifiLog.WIFI_UNKNOWN, true,
281                NUM_WIFI_UNKNOWN_SCREEN_ON);
282        assertSystemStateEntryEquals(
283                WifiMetricsProto.WifiLog.WIFI_ASSOCIATED, false, NUM_WIFI_ASSOCIATED_SCREEN_OFF);
284        assertSystemStateEntryEquals(WifiMetricsProto.WifiLog.WIFI_ASSOCIATED, true,
285                NUM_WIFI_ASSOCIATED_SCREEN_ON);
286        assertEquals(mDeserializedWifiMetrics.numConnectivityWatchdogPnoGood,
287                NUM_CONNECTIVITY_WATCHDOG_PNO_GOOD);
288        assertEquals(mDeserializedWifiMetrics.numConnectivityWatchdogPnoBad,
289                NUM_CONNECTIVITY_WATCHDOG_PNO_BAD);
290        assertEquals(mDeserializedWifiMetrics.numConnectivityWatchdogBackgroundGood,
291                NUM_CONNECTIVITY_WATCHDOG_BACKGROUND_GOOD);
292        assertEquals(mDeserializedWifiMetrics.numConnectivityWatchdogBackgroundBad,
293                NUM_CONNECTIVITY_WATCHDOG_BACKGROUND_BAD);
294        assertEquals(NUM_LAST_RESORT_WATCHDOG_TRIGGERS,
295                mDeserializedWifiMetrics.numLastResortWatchdogTriggers);
296        assertEquals(NUM_LAST_RESORT_WATCHDOG_BAD_ASSOCIATION_NETWORKS_TOTAL,
297                mDeserializedWifiMetrics.numLastResortWatchdogBadAssociationNetworksTotal);
298        assertEquals(NUM_LAST_RESORT_WATCHDOG_BAD_AUTHENTICATION_NETWORKS_TOTAL,
299                mDeserializedWifiMetrics.numLastResortWatchdogBadAuthenticationNetworksTotal);
300        assertEquals(NUM_LAST_RESORT_WATCHDOG_BAD_DHCP_NETWORKS_TOTAL,
301                mDeserializedWifiMetrics.numLastResortWatchdogBadDhcpNetworksTotal);
302        assertEquals(NUM_LAST_RESORT_WATCHDOG_BAD_OTHER_NETWORKS_TOTAL,
303                mDeserializedWifiMetrics.numLastResortWatchdogBadOtherNetworksTotal);
304        assertEquals(NUM_LAST_RESORT_WATCHDOG_AVAILABLE_NETWORKS_TOTAL,
305                mDeserializedWifiMetrics.numLastResortWatchdogAvailableNetworksTotal);
306        assertEquals(NUM_LAST_RESORT_WATCHDOG_TRIGGERS_WITH_BAD_ASSOCIATION,
307                mDeserializedWifiMetrics.numLastResortWatchdogTriggersWithBadAssociation);
308        assertEquals(NUM_LAST_RESORT_WATCHDOG_TRIGGERS_WITH_BAD_AUTHENTICATION,
309                mDeserializedWifiMetrics.numLastResortWatchdogTriggersWithBadAuthentication);
310        assertEquals(NUM_LAST_RESORT_WATCHDOG_TRIGGERS_WITH_BAD_DHCP,
311                mDeserializedWifiMetrics.numLastResortWatchdogTriggersWithBadDhcp);
312        assertEquals(NUM_LAST_RESORT_WATCHDOG_TRIGGERS_WITH_BAD_OTHER,
313                mDeserializedWifiMetrics.numLastResortWatchdogTriggersWithBadOther);
314        assertEquals(TEST_RECORD_DURATION_SEC,
315                mDeserializedWifiMetrics.recordDurationSec);
316    }
317
318    /**
319     *  Assert deserialized metrics Scan Return Entry equals count
320     */
321    public void assertScanReturnEntryEquals(int returnCode, int count) {
322        for (int i = 0; i < mDeserializedWifiMetrics.scanReturnEntries.length; i++) {
323            if (mDeserializedWifiMetrics.scanReturnEntries[i].scanReturnCode == returnCode) {
324                assertEquals(mDeserializedWifiMetrics.scanReturnEntries[i].scanResultsCount, count);
325                return;
326            }
327        }
328        assertEquals(null, count);
329    }
330
331    /**
332     *  Assert deserialized metrics SystemState entry equals count
333     */
334    public void assertSystemStateEntryEquals(int state, boolean screenOn, int count) {
335        for (int i = 0; i < mDeserializedWifiMetrics.wifiSystemStateEntries.length; i++) {
336            if (mDeserializedWifiMetrics.wifiSystemStateEntries[i].wifiState == state
337                    && mDeserializedWifiMetrics.wifiSystemStateEntries[i].isScreenOn == screenOn) {
338                assertEquals(mDeserializedWifiMetrics.wifiSystemStateEntries[i].wifiStateCount,
339                        count);
340                return;
341            }
342        }
343        assertEquals(null, count);
344    }
345    /**
346     * Combination of all other WifiMetrics unit tests, an internal-integration test, or functional
347     * test
348     */
349    @Test
350    public void setMetricsSerializeDeserializeAssertMetricsSame() throws Exception {
351        setAndIncrementMetrics();
352        startAndEndConnectionEventSucceeds();
353        dumpProtoAndDeserialize();
354        assertDeserializedMetricsCorrect();
355        assertEquals("mDeserializedWifiMetrics.connectionEvent.length",
356                2, mDeserializedWifiMetrics.connectionEvent.length);
357        //<TODO> test individual connectionEvents for correctness,
358        // check scanReturnEntries & wifiSystemStateEntries counts and individual elements
359        // pending their implementation</TODO>
360    }
361
362    private static final String SSID = "red";
363    private static final int CONFIG_DTIM = 3;
364    private static final int NETWORK_DETAIL_WIFIMODE = 5;
365    private static final int NETWORK_DETAIL_DTIM = 7;
366    private static final int SCAN_RESULT_LEVEL = -30;
367    /**
368     * Test that WifiMetrics is correctly getting data from ScanDetail and WifiConfiguration
369     */
370    @Test
371    public void testScanDetailAndWifiConfigurationUsage() throws Exception {
372        //Setup mock configs and scan details
373        NetworkDetail networkDetail = mock(NetworkDetail.class);
374        when(networkDetail.getWifiMode()).thenReturn(NETWORK_DETAIL_WIFIMODE);
375        when(networkDetail.getSSID()).thenReturn(SSID);
376        when(networkDetail.getDtimInterval()).thenReturn(NETWORK_DETAIL_DTIM);
377        ScanResult scanResult = mock(ScanResult.class);
378        scanResult.level = SCAN_RESULT_LEVEL;
379        WifiConfiguration config = mock(WifiConfiguration.class);
380        config.SSID = "\"" + SSID + "\"";
381        config.dtimInterval = CONFIG_DTIM;
382        WifiConfiguration.NetworkSelectionStatus networkSelectionStat =
383                mock(WifiConfiguration.NetworkSelectionStatus.class);
384        when(networkSelectionStat.getCandidate()).thenReturn(scanResult);
385        when(config.getNetworkSelectionStatus()).thenReturn(networkSelectionStat);
386        ScanDetail scanDetail = mock(ScanDetail.class);
387        when(scanDetail.getNetworkDetail()).thenReturn(networkDetail);
388        when(scanDetail.getScanResult()).thenReturn(scanResult);
389
390        //Create a connection event using only the config
391        mWifiMetrics.startConnectionEvent(config, "Red",
392                WifiMetricsProto.ConnectionEvent.ROAM_NONE);
393        mWifiMetrics.endConnectionEvent(
394                WifiMetrics.ConnectionEvent.FAILURE_NONE,
395                WifiMetricsProto.ConnectionEvent.HLF_NONE);
396
397        //Create a connection event using the config and a scan detail
398        mWifiMetrics.startConnectionEvent(config, "Green",
399                WifiMetricsProto.ConnectionEvent.ROAM_NONE);
400        mWifiMetrics.setConnectionScanDetail(scanDetail);
401        mWifiMetrics.endConnectionEvent(
402                WifiMetrics.ConnectionEvent.FAILURE_NONE,
403                WifiMetricsProto.ConnectionEvent.HLF_NONE);
404
405        //Dump proto from mWifiMetrics and deserialize it to mDeserializedWifiMetrics
406        dumpProtoAndDeserialize();
407
408        //Check that the correct values are being flowed through
409        assertEquals(mDeserializedWifiMetrics.connectionEvent.length, 2);
410        assertEquals(mDeserializedWifiMetrics.connectionEvent[0].routerFingerprint.dtim,
411                CONFIG_DTIM);
412        assertEquals(mDeserializedWifiMetrics.connectionEvent[0].signalStrength, SCAN_RESULT_LEVEL);
413        assertEquals(mDeserializedWifiMetrics.connectionEvent[1].routerFingerprint.dtim,
414                NETWORK_DETAIL_DTIM);
415        assertEquals(mDeserializedWifiMetrics.connectionEvent[1].signalStrength,
416                SCAN_RESULT_LEVEL);
417        assertEquals(mDeserializedWifiMetrics.connectionEvent[1].routerFingerprint.routerTechnology,
418                NETWORK_DETAIL_WIFIMODE);
419    }
420
421    /**
422     * Test that WifiMetrics is being cleared after dumping via proto
423     */
424    @Test
425    public void testMetricsClearedAfterProtoRequested() throws Exception {
426        // Create 3 ConnectionEvents
427        mWifiMetrics.startConnectionEvent(null, "RED",
428                WifiMetricsProto.ConnectionEvent.ROAM_ENTERPRISE);
429        mWifiMetrics.endConnectionEvent(
430                WifiMetrics.ConnectionEvent.FAILURE_NONE,
431                WifiMetricsProto.ConnectionEvent.HLF_NONE);
432        mWifiMetrics.startConnectionEvent(null, "YELLOW",
433                WifiMetricsProto.ConnectionEvent.ROAM_ENTERPRISE);
434        mWifiMetrics.endConnectionEvent(
435                WifiMetrics.ConnectionEvent.FAILURE_NONE,
436                WifiMetricsProto.ConnectionEvent.HLF_NONE);
437        mWifiMetrics.startConnectionEvent(null, "GREEN",
438                WifiMetricsProto.ConnectionEvent.ROAM_ENTERPRISE);
439        mWifiMetrics.endConnectionEvent(
440                WifiMetrics.ConnectionEvent.FAILURE_NONE,
441                WifiMetricsProto.ConnectionEvent.HLF_NONE);
442        mWifiMetrics.startConnectionEvent(null, "ORANGE",
443                WifiMetricsProto.ConnectionEvent.ROAM_ENTERPRISE);
444        mWifiMetrics.endConnectionEvent(
445                WifiMetrics.ConnectionEvent.FAILURE_NONE,
446                WifiMetricsProto.ConnectionEvent.HLF_NONE);
447
448        //Dump proto and deserialize
449        //This should clear all the metrics in mWifiMetrics,
450        dumpProtoAndDeserialize();
451        //Check there are only 3 connection events
452        assertEquals(mDeserializedWifiMetrics.connectionEvent.length, 4);
453
454        // Create 2 ConnectionEvents
455        mWifiMetrics.startConnectionEvent(null,  "BLUE",
456                WifiMetricsProto.ConnectionEvent.ROAM_ENTERPRISE);
457        mWifiMetrics.endConnectionEvent(
458                WifiMetrics.ConnectionEvent.FAILURE_NONE,
459                WifiMetricsProto.ConnectionEvent.HLF_NONE);
460        mWifiMetrics.startConnectionEvent(null, "RED",
461                WifiMetricsProto.ConnectionEvent.ROAM_ENTERPRISE);
462        mWifiMetrics.endConnectionEvent(
463                WifiMetrics.ConnectionEvent.FAILURE_NONE,
464                WifiMetricsProto.ConnectionEvent.HLF_NONE);
465
466        //Dump proto and deserialize
467        dumpProtoAndDeserialize();
468        //Check there are only 2 connection events
469        assertEquals(mDeserializedWifiMetrics.connectionEvent.length, 2);
470    }
471}
472