WifiMetricsTest.java revision da22e3d28b62005dce5fddd75207bd3d7a1745e1
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.getElapsedSinceBootMillis()).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.getElapsedSinceBootMillis()).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    private static final int NUM_LAST_RESORT_WATCHDOG_SUCCESSES = 5;
158    private static final int NUM_RSSI_LEVELS_TO_INCREMENT = 20;
159    private static final int FIRST_RSSI_LEVEL = -80;
160    /**
161     * Set simple metrics, increment others
162     */
163    public void setAndIncrementMetrics() throws Exception {
164        mWifiMetrics.setNumSavedNetworks(NUM_SAVED_NETWORKS);
165        mWifiMetrics.setNumOpenNetworks(NUM_OPEN_NETWORKS);
166        mWifiMetrics.setNumPersonalNetworks(NUM_PERSONAL_NETWORKS);
167        mWifiMetrics.setNumEnterpriseNetworks(NUM_ENTERPRISE_NETWORKS);
168        mWifiMetrics.setNumNetworksAddedByUser(NUM_NEWTORKS_ADDED_BY_USER);
169        mWifiMetrics.setNumNetworksAddedByApps(NUM_NEWTORKS_ADDED_BY_APPS);
170        mWifiMetrics.setIsLocationEnabled(TEST_VAL_IS_LOCATION_ENABLED);
171        mWifiMetrics.setIsScanningAlwaysEnabled(IS_SCANNING_ALWAYS_ENABLED);
172
173        for (int i = 0; i < NUM_EMPTY_SCAN_RESULTS; i++) {
174            mWifiMetrics.incrementEmptyScanResultCount();
175        }
176        for (int i = 0; i < NUM_NON_EMPTY_SCAN_RESULTS; i++) {
177            mWifiMetrics.incrementNonEmptyScanResultCount();
178        }
179        mWifiMetrics.incrementScanReturnEntry(WifiMetricsProto.WifiLog.SCAN_UNKNOWN,
180                NUM_SCAN_UNKNOWN);
181        mWifiMetrics.incrementScanReturnEntry(WifiMetricsProto.WifiLog.SCAN_SUCCESS,
182                NUM_SCAN_SUCCESS);
183        mWifiMetrics.incrementScanReturnEntry(
184                WifiMetricsProto.WifiLog.SCAN_FAILURE_INTERRUPTED,
185                NUM_SCAN_FAILURE_INTERRUPTED);
186        mWifiMetrics.incrementScanReturnEntry(
187                WifiMetricsProto.WifiLog.SCAN_FAILURE_INVALID_CONFIGURATION,
188                NUM_SCAN_FAILURE_INVALID_CONFIGURATION);
189        for (int i = 0; i < NUM_WIFI_UNKNOWN_SCREEN_OFF; i++) {
190            mWifiMetrics.incrementWifiSystemScanStateCount(WifiMetricsProto.WifiLog.WIFI_UNKNOWN,
191                    false);
192        }
193        for (int i = 0; i < NUM_WIFI_UNKNOWN_SCREEN_ON; i++) {
194            mWifiMetrics.incrementWifiSystemScanStateCount(WifiMetricsProto.WifiLog.WIFI_UNKNOWN,
195                    true);
196        }
197        for (int i = 0; i < NUM_WIFI_ASSOCIATED_SCREEN_OFF; i++) {
198            mWifiMetrics.incrementWifiSystemScanStateCount(WifiMetricsProto.WifiLog.WIFI_ASSOCIATED,
199                    false);
200        }
201        for (int i = 0; i < NUM_WIFI_ASSOCIATED_SCREEN_ON; i++) {
202            mWifiMetrics.incrementWifiSystemScanStateCount(WifiMetricsProto.WifiLog.WIFI_ASSOCIATED,
203                    true);
204        }
205        for (int i = 0; i < NUM_CONNECTIVITY_WATCHDOG_PNO_GOOD; i++) {
206            mWifiMetrics.incrementNumConnectivityWatchdogPnoGood();
207        }
208        for (int i = 0; i < NUM_CONNECTIVITY_WATCHDOG_PNO_BAD; i++) {
209            mWifiMetrics.incrementNumConnectivityWatchdogPnoBad();
210        }
211        for (int i = 0; i < NUM_CONNECTIVITY_WATCHDOG_BACKGROUND_GOOD; i++) {
212            mWifiMetrics.incrementNumConnectivityWatchdogBackgroundGood();
213        }
214        for (int i = 0; i < NUM_CONNECTIVITY_WATCHDOG_BACKGROUND_BAD; i++) {
215            mWifiMetrics.incrementNumConnectivityWatchdogBackgroundBad();
216        }
217        for (int i = 0; i < NUM_LAST_RESORT_WATCHDOG_TRIGGERS; i++) {
218            mWifiMetrics.incrementNumLastResortWatchdogTriggers();
219        }
220        mWifiMetrics.addCountToNumLastResortWatchdogBadAssociationNetworksTotal(
221                NUM_LAST_RESORT_WATCHDOG_BAD_ASSOCIATION_NETWORKS_TOTAL);
222        mWifiMetrics.addCountToNumLastResortWatchdogBadAuthenticationNetworksTotal(
223                NUM_LAST_RESORT_WATCHDOG_BAD_AUTHENTICATION_NETWORKS_TOTAL);
224        mWifiMetrics.addCountToNumLastResortWatchdogBadDhcpNetworksTotal(
225                NUM_LAST_RESORT_WATCHDOG_BAD_DHCP_NETWORKS_TOTAL);
226        mWifiMetrics.addCountToNumLastResortWatchdogBadOtherNetworksTotal(
227                NUM_LAST_RESORT_WATCHDOG_BAD_OTHER_NETWORKS_TOTAL);
228        mWifiMetrics.addCountToNumLastResortWatchdogAvailableNetworksTotal(
229                NUM_LAST_RESORT_WATCHDOG_AVAILABLE_NETWORKS_TOTAL);
230        for (int i = 0; i < NUM_LAST_RESORT_WATCHDOG_TRIGGERS_WITH_BAD_ASSOCIATION; i++) {
231            mWifiMetrics.incrementNumLastResortWatchdogTriggersWithBadAssociation();
232        }
233        for (int i = 0; i < NUM_LAST_RESORT_WATCHDOG_TRIGGERS_WITH_BAD_AUTHENTICATION; i++) {
234            mWifiMetrics.incrementNumLastResortWatchdogTriggersWithBadAuthentication();
235        }
236        for (int i = 0; i < NUM_LAST_RESORT_WATCHDOG_TRIGGERS_WITH_BAD_DHCP; i++) {
237            mWifiMetrics.incrementNumLastResortWatchdogTriggersWithBadDhcp();
238        }
239        for (int i = 0; i < NUM_LAST_RESORT_WATCHDOG_TRIGGERS_WITH_BAD_OTHER; i++) {
240            mWifiMetrics.incrementNumLastResortWatchdogTriggersWithBadOther();
241        }
242        for (int i = 0; i < NUM_LAST_RESORT_WATCHDOG_SUCCESSES; i++) {
243            mWifiMetrics.incrementNumLastResortWatchdogSuccesses();
244        }
245        for (int i = 0; i < NUM_RSSI_LEVELS_TO_INCREMENT; i++) {
246            for (int j = 0; j <= i; j++) {
247                mWifiMetrics.incrementRssiPollRssiCount(FIRST_RSSI_LEVEL + i);
248            }
249        }
250    }
251
252    /**
253     * Assert that values in deserializedWifiMetrics match those set in 'setAndIncrementMetrics'
254     */
255    public void assertDeserializedMetricsCorrect() throws Exception {
256        assertEquals("mDeserializedWifiMetrics.numSavedNetworks == NUM_SAVED_NETWORKS",
257                mDeserializedWifiMetrics.numSavedNetworks, NUM_SAVED_NETWORKS);
258        assertEquals("mDeserializedWifiMetrics.numOpenNetworks == NUM_OPEN_NETWORKS",
259                mDeserializedWifiMetrics.numOpenNetworks, NUM_OPEN_NETWORKS);
260        assertEquals("mDeserializedWifiMetrics.numPersonalNetworks == NUM_PERSONAL_NETWORKS",
261                mDeserializedWifiMetrics.numPersonalNetworks, NUM_PERSONAL_NETWORKS);
262        assertEquals("mDeserializedWifiMetrics.numEnterpriseNetworks "
263                        + "== NUM_ENTERPRISE_NETWORKS",
264                mDeserializedWifiMetrics.numEnterpriseNetworks, NUM_ENTERPRISE_NETWORKS);
265        assertEquals("mDeserializedWifiMetrics.numNetworksAddedByUser "
266                        + "== NUM_NEWTORKS_ADDED_BY_USER",
267                mDeserializedWifiMetrics.numNetworksAddedByUser, NUM_NEWTORKS_ADDED_BY_USER);
268        assertEquals("mDeserializedWifiMetrics.numNetworksAddedByApps "
269                        + "== NUM_NEWTORKS_ADDED_BY_APPS",
270                mDeserializedWifiMetrics.numNetworksAddedByApps, NUM_NEWTORKS_ADDED_BY_APPS);
271        assertEquals("mDeserializedWifiMetrics.isLocationEnabled == TEST_VAL_IS_LOCATION_ENABLED",
272                mDeserializedWifiMetrics.isLocationEnabled, TEST_VAL_IS_LOCATION_ENABLED);
273        assertEquals("mDeserializedWifiMetrics.isScanningAlwaysEnabled "
274                        + "== IS_SCANNING_ALWAYS_ENABLED",
275                mDeserializedWifiMetrics.isScanningAlwaysEnabled, IS_SCANNING_ALWAYS_ENABLED);
276        assertEquals("mDeserializedWifiMetrics.numEmptyScanResults == NUM_EMPTY_SCAN_RESULTS",
277                mDeserializedWifiMetrics.numEmptyScanResults, NUM_EMPTY_SCAN_RESULTS);
278        assertEquals("mDeserializedWifiMetrics.numNonEmptyScanResults == "
279                        + "NUM_NON_EMPTY_SCAN_RESULTS",
280                mDeserializedWifiMetrics.numNonEmptyScanResults, NUM_NON_EMPTY_SCAN_RESULTS);
281        assertScanReturnEntryEquals(WifiMetricsProto.WifiLog.SCAN_UNKNOWN,
282                NUM_SCAN_UNKNOWN);
283        assertScanReturnEntryEquals(WifiMetricsProto.WifiLog.SCAN_SUCCESS,
284                NUM_SCAN_SUCCESS);
285        assertScanReturnEntryEquals(WifiMetricsProto.WifiLog.SCAN_FAILURE_INTERRUPTED,
286                NUM_SCAN_FAILURE_INTERRUPTED);
287        assertScanReturnEntryEquals(WifiMetricsProto.WifiLog.SCAN_FAILURE_INVALID_CONFIGURATION,
288                NUM_SCAN_FAILURE_INVALID_CONFIGURATION);
289        assertSystemStateEntryEquals(WifiMetricsProto.WifiLog.WIFI_UNKNOWN, false,
290                NUM_WIFI_UNKNOWN_SCREEN_OFF);
291        assertSystemStateEntryEquals(WifiMetricsProto.WifiLog.WIFI_UNKNOWN, true,
292                NUM_WIFI_UNKNOWN_SCREEN_ON);
293        assertSystemStateEntryEquals(
294                WifiMetricsProto.WifiLog.WIFI_ASSOCIATED, false, NUM_WIFI_ASSOCIATED_SCREEN_OFF);
295        assertSystemStateEntryEquals(WifiMetricsProto.WifiLog.WIFI_ASSOCIATED, true,
296                NUM_WIFI_ASSOCIATED_SCREEN_ON);
297        assertEquals(mDeserializedWifiMetrics.numConnectivityWatchdogPnoGood,
298                NUM_CONNECTIVITY_WATCHDOG_PNO_GOOD);
299        assertEquals(mDeserializedWifiMetrics.numConnectivityWatchdogPnoBad,
300                NUM_CONNECTIVITY_WATCHDOG_PNO_BAD);
301        assertEquals(mDeserializedWifiMetrics.numConnectivityWatchdogBackgroundGood,
302                NUM_CONNECTIVITY_WATCHDOG_BACKGROUND_GOOD);
303        assertEquals(mDeserializedWifiMetrics.numConnectivityWatchdogBackgroundBad,
304                NUM_CONNECTIVITY_WATCHDOG_BACKGROUND_BAD);
305        assertEquals(NUM_LAST_RESORT_WATCHDOG_TRIGGERS,
306                mDeserializedWifiMetrics.numLastResortWatchdogTriggers);
307        assertEquals(NUM_LAST_RESORT_WATCHDOG_BAD_ASSOCIATION_NETWORKS_TOTAL,
308                mDeserializedWifiMetrics.numLastResortWatchdogBadAssociationNetworksTotal);
309        assertEquals(NUM_LAST_RESORT_WATCHDOG_BAD_AUTHENTICATION_NETWORKS_TOTAL,
310                mDeserializedWifiMetrics.numLastResortWatchdogBadAuthenticationNetworksTotal);
311        assertEquals(NUM_LAST_RESORT_WATCHDOG_BAD_DHCP_NETWORKS_TOTAL,
312                mDeserializedWifiMetrics.numLastResortWatchdogBadDhcpNetworksTotal);
313        assertEquals(NUM_LAST_RESORT_WATCHDOG_BAD_OTHER_NETWORKS_TOTAL,
314                mDeserializedWifiMetrics.numLastResortWatchdogBadOtherNetworksTotal);
315        assertEquals(NUM_LAST_RESORT_WATCHDOG_AVAILABLE_NETWORKS_TOTAL,
316                mDeserializedWifiMetrics.numLastResortWatchdogAvailableNetworksTotal);
317        assertEquals(NUM_LAST_RESORT_WATCHDOG_TRIGGERS_WITH_BAD_ASSOCIATION,
318                mDeserializedWifiMetrics.numLastResortWatchdogTriggersWithBadAssociation);
319        assertEquals(NUM_LAST_RESORT_WATCHDOG_TRIGGERS_WITH_BAD_AUTHENTICATION,
320                mDeserializedWifiMetrics.numLastResortWatchdogTriggersWithBadAuthentication);
321        assertEquals(NUM_LAST_RESORT_WATCHDOG_TRIGGERS_WITH_BAD_DHCP,
322                mDeserializedWifiMetrics.numLastResortWatchdogTriggersWithBadDhcp);
323        assertEquals(NUM_LAST_RESORT_WATCHDOG_TRIGGERS_WITH_BAD_OTHER,
324                mDeserializedWifiMetrics.numLastResortWatchdogTriggersWithBadOther);
325        assertEquals(NUM_LAST_RESORT_WATCHDOG_SUCCESSES,
326                mDeserializedWifiMetrics.numLastResortWatchdogSuccesses);
327        assertEquals(TEST_RECORD_DURATION_SEC,
328                mDeserializedWifiMetrics.recordDurationSec);
329        for (int i = 0; i < NUM_RSSI_LEVELS_TO_INCREMENT; i++) {
330            assertEquals(FIRST_RSSI_LEVEL + i, mDeserializedWifiMetrics.rssiPollRssiCount[i].rssi);
331            assertEquals(i + 1, mDeserializedWifiMetrics.rssiPollRssiCount[i].count);
332        }
333    }
334
335    /**
336     *  Assert deserialized metrics Scan Return Entry equals count
337     */
338    public void assertScanReturnEntryEquals(int returnCode, int count) {
339        for (int i = 0; i < mDeserializedWifiMetrics.scanReturnEntries.length; i++) {
340            if (mDeserializedWifiMetrics.scanReturnEntries[i].scanReturnCode == returnCode) {
341                assertEquals(mDeserializedWifiMetrics.scanReturnEntries[i].scanResultsCount, count);
342                return;
343            }
344        }
345        assertEquals(null, count);
346    }
347
348    /**
349     *  Assert deserialized metrics SystemState entry equals count
350     */
351    public void assertSystemStateEntryEquals(int state, boolean screenOn, int count) {
352        for (int i = 0; i < mDeserializedWifiMetrics.wifiSystemStateEntries.length; i++) {
353            if (mDeserializedWifiMetrics.wifiSystemStateEntries[i].wifiState == state
354                    && mDeserializedWifiMetrics.wifiSystemStateEntries[i].isScreenOn == screenOn) {
355                assertEquals(mDeserializedWifiMetrics.wifiSystemStateEntries[i].wifiStateCount,
356                        count);
357                return;
358            }
359        }
360        assertEquals(null, count);
361    }
362    /**
363     * Combination of all other WifiMetrics unit tests, an internal-integration test, or functional
364     * test
365     */
366    @Test
367    public void setMetricsSerializeDeserializeAssertMetricsSame() throws Exception {
368        setAndIncrementMetrics();
369        startAndEndConnectionEventSucceeds();
370        dumpProtoAndDeserialize();
371        assertDeserializedMetricsCorrect();
372        assertEquals("mDeserializedWifiMetrics.connectionEvent.length",
373                2, mDeserializedWifiMetrics.connectionEvent.length);
374        //<TODO> test individual connectionEvents for correctness,
375        // check scanReturnEntries & wifiSystemStateEntries counts and individual elements
376        // pending their implementation</TODO>
377    }
378
379    private static final String SSID = "red";
380    private static final int CONFIG_DTIM = 3;
381    private static final int NETWORK_DETAIL_WIFIMODE = 5;
382    private static final int NETWORK_DETAIL_DTIM = 7;
383    private static final int SCAN_RESULT_LEVEL = -30;
384    /**
385     * Test that WifiMetrics is correctly getting data from ScanDetail and WifiConfiguration
386     */
387    @Test
388    public void testScanDetailAndWifiConfigurationUsage() throws Exception {
389        //Setup mock configs and scan details
390        NetworkDetail networkDetail = mock(NetworkDetail.class);
391        when(networkDetail.getWifiMode()).thenReturn(NETWORK_DETAIL_WIFIMODE);
392        when(networkDetail.getSSID()).thenReturn(SSID);
393        when(networkDetail.getDtimInterval()).thenReturn(NETWORK_DETAIL_DTIM);
394        ScanResult scanResult = mock(ScanResult.class);
395        scanResult.level = SCAN_RESULT_LEVEL;
396        WifiConfiguration config = mock(WifiConfiguration.class);
397        config.SSID = "\"" + SSID + "\"";
398        config.dtimInterval = CONFIG_DTIM;
399        WifiConfiguration.NetworkSelectionStatus networkSelectionStat =
400                mock(WifiConfiguration.NetworkSelectionStatus.class);
401        when(networkSelectionStat.getCandidate()).thenReturn(scanResult);
402        when(config.getNetworkSelectionStatus()).thenReturn(networkSelectionStat);
403        ScanDetail scanDetail = mock(ScanDetail.class);
404        when(scanDetail.getNetworkDetail()).thenReturn(networkDetail);
405        when(scanDetail.getScanResult()).thenReturn(scanResult);
406
407        //Create a connection event using only the config
408        mWifiMetrics.startConnectionEvent(config, "Red",
409                WifiMetricsProto.ConnectionEvent.ROAM_NONE);
410        mWifiMetrics.endConnectionEvent(
411                WifiMetrics.ConnectionEvent.FAILURE_NONE,
412                WifiMetricsProto.ConnectionEvent.HLF_NONE);
413
414        //Create a connection event using the config and a scan detail
415        mWifiMetrics.startConnectionEvent(config, "Green",
416                WifiMetricsProto.ConnectionEvent.ROAM_NONE);
417        mWifiMetrics.setConnectionScanDetail(scanDetail);
418        mWifiMetrics.endConnectionEvent(
419                WifiMetrics.ConnectionEvent.FAILURE_NONE,
420                WifiMetricsProto.ConnectionEvent.HLF_NONE);
421
422        //Dump proto from mWifiMetrics and deserialize it to mDeserializedWifiMetrics
423        dumpProtoAndDeserialize();
424
425        //Check that the correct values are being flowed through
426        assertEquals(mDeserializedWifiMetrics.connectionEvent.length, 2);
427        assertEquals(mDeserializedWifiMetrics.connectionEvent[0].routerFingerprint.dtim,
428                CONFIG_DTIM);
429        assertEquals(mDeserializedWifiMetrics.connectionEvent[0].signalStrength, SCAN_RESULT_LEVEL);
430        assertEquals(mDeserializedWifiMetrics.connectionEvent[1].routerFingerprint.dtim,
431                NETWORK_DETAIL_DTIM);
432        assertEquals(mDeserializedWifiMetrics.connectionEvent[1].signalStrength,
433                SCAN_RESULT_LEVEL);
434        assertEquals(mDeserializedWifiMetrics.connectionEvent[1].routerFingerprint.routerTechnology,
435                NETWORK_DETAIL_WIFIMODE);
436    }
437
438    /**
439     * Test that WifiMetrics is being cleared after dumping via proto
440     */
441    @Test
442    public void testMetricsClearedAfterProtoRequested() throws Exception {
443        // Create 3 ConnectionEvents
444        mWifiMetrics.startConnectionEvent(null, "RED",
445                WifiMetricsProto.ConnectionEvent.ROAM_ENTERPRISE);
446        mWifiMetrics.endConnectionEvent(
447                WifiMetrics.ConnectionEvent.FAILURE_NONE,
448                WifiMetricsProto.ConnectionEvent.HLF_NONE);
449        mWifiMetrics.startConnectionEvent(null, "YELLOW",
450                WifiMetricsProto.ConnectionEvent.ROAM_ENTERPRISE);
451        mWifiMetrics.endConnectionEvent(
452                WifiMetrics.ConnectionEvent.FAILURE_NONE,
453                WifiMetricsProto.ConnectionEvent.HLF_NONE);
454        mWifiMetrics.startConnectionEvent(null, "GREEN",
455                WifiMetricsProto.ConnectionEvent.ROAM_ENTERPRISE);
456        mWifiMetrics.endConnectionEvent(
457                WifiMetrics.ConnectionEvent.FAILURE_NONE,
458                WifiMetricsProto.ConnectionEvent.HLF_NONE);
459        mWifiMetrics.startConnectionEvent(null, "ORANGE",
460                WifiMetricsProto.ConnectionEvent.ROAM_ENTERPRISE);
461        mWifiMetrics.endConnectionEvent(
462                WifiMetrics.ConnectionEvent.FAILURE_NONE,
463                WifiMetricsProto.ConnectionEvent.HLF_NONE);
464
465        //Dump proto and deserialize
466        //This should clear all the metrics in mWifiMetrics,
467        dumpProtoAndDeserialize();
468        //Check there are only 3 connection events
469        assertEquals(mDeserializedWifiMetrics.connectionEvent.length, 4);
470
471        // Create 2 ConnectionEvents
472        mWifiMetrics.startConnectionEvent(null,  "BLUE",
473                WifiMetricsProto.ConnectionEvent.ROAM_ENTERPRISE);
474        mWifiMetrics.endConnectionEvent(
475                WifiMetrics.ConnectionEvent.FAILURE_NONE,
476                WifiMetricsProto.ConnectionEvent.HLF_NONE);
477        mWifiMetrics.startConnectionEvent(null, "RED",
478                WifiMetricsProto.ConnectionEvent.ROAM_ENTERPRISE);
479        mWifiMetrics.endConnectionEvent(
480                WifiMetrics.ConnectionEvent.FAILURE_NONE,
481                WifiMetricsProto.ConnectionEvent.HLF_NONE);
482
483        //Dump proto and deserialize
484        dumpProtoAndDeserialize();
485        //Check there are only 2 connection events
486        assertEquals(mDeserializedWifiMetrics.connectionEvent.length, 2);
487    }
488}
489