summaryrefslogtreecommitdiffstats
path: root/tests/wifitests/src/com/android/server/wifi/WifiDiagnosticsTest.java
blob: 98837379517d7b632e38e2f40f5b95a5478d6e6d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.server.wifi;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.AdditionalMatchers.gt;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.contains;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.anyObject;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import android.app.test.MockAnswerUtil.AnswerWithArguments;
import android.content.Context;

import androidx.test.filters.SmallTest;

import com.android.internal.R;
import com.android.server.am.ActivityManagerService;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;

import java.io.ByteArrayInputStream;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.regex.Pattern;

/**
 * Unit tests for {@link WifiDiagnostics}.
 */
@SmallTest
public class WifiDiagnosticsTest {
    @Mock WifiNative mWifiNative;
    @Mock BuildProperties mBuildProperties;
    @Mock Context mContext;
    @Mock WifiInjector mWifiInjector;
    @Spy FakeWifiLog mLog;
    @Mock LastMileLogger mLastMileLogger;
    @Mock Runtime mJavaRuntime;
    @Mock Process mExternalProcess;
    @Mock ActivityManagerService mActivityManagerService;
    @Mock WifiMetrics mWifiMetrics;
    @Mock Clock mClock;
    WifiDiagnostics mWifiDiagnostics;

    private static final String FAKE_RING_BUFFER_NAME = "fake-ring-buffer";
    private static final String STA_IF_NAME = "wlan0";
    private static final String AP_IF_NAME = "wlan1";
    private static final int SMALL_RING_BUFFER_SIZE_KB = 32;
    private static final int LARGE_RING_BUFFER_SIZE_KB = 1024;
    private static final int BYTES_PER_KBYTE = 1024;
    private static final int ALERT_REASON_CODE = 1;
    private static final byte[] ALERT_DATA = {0 , 4, 5};
    /** Mock resource for fatal firmware alert list */
    private static final int[] FATAL_FW_ALART_LIST = {256, 257, 258};
    /** Mock a non fatal firmware alert */
    private static final int NON_FATAL_FW_ALART = 0;

    private WifiNative.RingBufferStatus mFakeRbs;
    /**
     * Returns the data that we would dump in a bug report, for our ring buffer.
     * @return a 2-D byte array, where the first dimension is the record number, and the second
     * dimension is the byte index within that record.
     */
    private final byte[][] getLoggerRingBufferData() throws Exception {
        return mWifiDiagnostics.getBugReports().get(0).ringBuffers.get(FAKE_RING_BUFFER_NAME);
    }

    /**
     * Initializes common state (e.g. mocks) needed by test cases.
     */
    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);

        mFakeRbs = new WifiNative.RingBufferStatus();
        mFakeRbs.name = FAKE_RING_BUFFER_NAME;
        WifiNative.RingBufferStatus[] ringBufferStatuses = new WifiNative.RingBufferStatus[] {
                mFakeRbs
        };

        when(mWifiNative.getRingBufferStatus()).thenReturn(ringBufferStatuses);
        when(mWifiNative.readKernelLog()).thenReturn("");
        when(mBuildProperties.isEngBuild()).thenReturn(false);
        when(mBuildProperties.isUserdebugBuild()).thenReturn(false);
        when(mBuildProperties.isUserBuild()).thenReturn(true);
        when(mExternalProcess.getInputStream()).thenReturn(new ByteArrayInputStream(new byte[0]));
        when(mExternalProcess.getErrorStream()).thenReturn(new ByteArrayInputStream(new byte[0]));
        when(mJavaRuntime.exec(anyString())).thenReturn(mExternalProcess);

        MockResources resources = new MockResources();
        resources.setInteger(R.integer.config_wifi_logger_ring_buffer_default_size_limit_kb,
                SMALL_RING_BUFFER_SIZE_KB);
        resources.setInteger(R.integer.config_wifi_logger_ring_buffer_verbose_size_limit_kb,
                LARGE_RING_BUFFER_SIZE_KB);
        resources.setIntArray(R.array.config_wifi_fatal_firmware_alert_error_code_list,
                FATAL_FW_ALART_LIST);
        when(mContext.getResources()).thenReturn(resources);
        when(mWifiInjector.makeLog(anyString())).thenReturn(mLog);
        when(mWifiInjector.getJavaRuntime()).thenReturn(mJavaRuntime);
        when(mWifiInjector.getActivityManagerService()).thenReturn(mActivityManagerService);
        when(mWifiInjector.getWifiMetrics()).thenReturn(mWifiMetrics);

        mWifiDiagnostics = new WifiDiagnostics(
                mContext, mWifiInjector, mWifiNative, mBuildProperties, mLastMileLogger, mClock);
        mWifiNative.enableVerboseLogging(0);
    }

    /** Verifies that startLogging() registers a logging event handler. */
    @Test
    public void startLoggingRegistersLogEventHandler() throws Exception {
        mWifiDiagnostics.enableVerboseLogging(false);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        verify(mWifiNative).setLoggingEventHandler(anyObject());
    }

    /**
     * Verifies that a failure to set the logging event handler does not prevent a future
     * startLogging() from setting the logging event handler.
     */
    @Test
    public void startLoggingRegistersLogEventHandlerIfPriorAttemptFailed()
            throws Exception {
        final boolean verbosityToggle = false;  // even default mode registers handler

        when(mWifiNative.setLoggingEventHandler(anyObject())).thenReturn(false);
        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        verify(mWifiNative).setLoggingEventHandler(anyObject());
        mWifiDiagnostics.stopLogging(STA_IF_NAME);
        reset(mWifiNative);

        when(mWifiNative.setLoggingEventHandler(anyObject())).thenReturn(true);
        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        verify(mWifiNative).setLoggingEventHandler(anyObject());
    }

    /** Verifies that startLogging() does not make redundant calls to setLoggingEventHandler(). */
    @Test
    public void startLoggingDoesNotRegisterLogEventHandlerIfPriorAttemptSucceeded()
            throws Exception {
        when(mWifiNative.setLoggingEventHandler(anyObject())).thenReturn(true);
        mWifiDiagnostics.enableVerboseLogging(false);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        verify(mWifiNative).setLoggingEventHandler(anyObject());
        reset(mWifiNative);

        mWifiDiagnostics.enableVerboseLogging(false);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        verify(mWifiNative, never()).setLoggingEventHandler(anyObject());
    }

    /**
     * Verifies that startLogging() restarts HAL ringbuffers.
     *
     * Specifically: verifies that startLogging()
     * a) stops any ring buffer logging that might be already running,
     * b) instructs WifiNative to enable ring buffers of the appropriate log level.
     */
    @Test
    public void startLoggingStopsAndRestartsRingBufferLoggingInVerboseMode() throws Exception {
        final boolean verbosityToggle = true;
        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        verify(mWifiNative).startLoggingRingBuffer(
                eq(WifiDiagnostics.VERBOSE_NO_LOG), anyInt(), anyInt(), anyInt(),
                eq(FAKE_RING_BUFFER_NAME));
        verify(mWifiNative).startLoggingRingBuffer(
                eq(WifiDiagnostics.VERBOSE_LOG_WITH_WAKEUP), anyInt(), anyInt(), anyInt(),
                eq(FAKE_RING_BUFFER_NAME));
    }

    @Test
    public void startLoggingStopsAndThenStartRingBufferLoggingInNormalMode() throws Exception {
        final boolean verbosityToggle = false;
        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        verify(mWifiNative).startLoggingRingBuffer(
                eq(WifiDiagnostics.VERBOSE_NO_LOG), anyInt(), anyInt(), anyInt(),
                eq(FAKE_RING_BUFFER_NAME));
        verify(mWifiNative).startLoggingRingBuffer(
                gt(WifiDiagnostics.VERBOSE_NO_LOG), anyInt(), anyInt(), anyInt(),
                anyString());
    }

    /** Verifies that, if a log handler was registered, then stopLogging() resets it. */
    @Test
    public void stopLoggingResetsLogHandlerIfHandlerWasRegistered() throws Exception {
        final boolean verbosityToggle = false;  // even default mode registers handler

        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        when(mWifiNative.setLoggingEventHandler(anyObject())).thenReturn(true);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        reset(mWifiNative);

        mWifiDiagnostics.stopLogging(STA_IF_NAME);
        verify(mWifiNative).resetLogHandler();
    }

    /** Verifies that, if a log handler is not registered, stopLogging() skips resetLogHandler(). */
    @Test
    public void stopLoggingOnlyResetsLogHandlerIfHandlerWasRegistered() throws Exception {
        mWifiDiagnostics.stopLogging(STA_IF_NAME);
        verify(mWifiNative, never()).resetLogHandler();
    }

    /** Verifies that stopLogging() remembers that we've reset the log handler. */
    @Test
    public void multipleStopLoggingCallsOnlyResetLogHandlerOnce() throws Exception {
        final boolean verbosityToggle = false;  // even default mode registers handler

        when(mWifiNative.setLoggingEventHandler(anyObject())).thenReturn(true);
        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        reset(mWifiNative);

        when(mWifiNative.resetLogHandler()).thenReturn(true);
        mWifiDiagnostics.stopLogging(STA_IF_NAME);
        verify(mWifiNative).resetLogHandler();
        reset(mWifiNative);

        mWifiDiagnostics.stopLogging(STA_IF_NAME);
        verify(mWifiNative, never()).resetLogHandler();
    }

    /**
     * Verifies that we capture ring-buffer data.
     */
    @Test
    public void canCaptureAndStoreRingBufferData() throws Exception {
        final boolean verbosityToggle = false;
        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startLogging(STA_IF_NAME);

        final byte[] data = new byte[SMALL_RING_BUFFER_SIZE_KB * BYTES_PER_KBYTE];
        mWifiDiagnostics.onRingBufferData(mFakeRbs, data);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);

        byte[][] ringBufferData = getLoggerRingBufferData();
        assertEquals(1, ringBufferData.length);
        assertArrayEquals(data, ringBufferData[0]);
    }

    /**
     * Verifies that we discard extraneous ring-buffer data.
     */
    @Ignore("TODO(b/36811399): re-enabled this @Test")
    @Test
    public void loggerDiscardsExtraneousData() throws Exception {
        final boolean verbosityToggle = false;
        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startLogging(STA_IF_NAME);

        final byte[] data1 = new byte[SMALL_RING_BUFFER_SIZE_KB * BYTES_PER_KBYTE];
        final byte[] data2 = {1, 2, 3};
        mWifiDiagnostics.onRingBufferData(mFakeRbs, data1);
        mWifiDiagnostics.onRingBufferData(mFakeRbs, data2);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);

        byte[][] ringBufferData = getLoggerRingBufferData();
        assertEquals(1, ringBufferData.length);
        assertArrayEquals(data2, ringBufferData[0]);
    }

    // Verifies that startPktFateMonitoring(any()) reports failure to start packet fate
    @Test
    public void startPktFateMonitoringReportsStartFailures() {
        when(mWifiNative.startPktFateMonitoring(any())).thenReturn(false);
        mWifiDiagnostics.startPktFateMonitoring(STA_IF_NAME);
        verify(mLog).wC(contains("Failed"));
    }

    /**
     * Verifies that, when verbose mode is not enabled,
     * reportConnectionEvent(WifiDiagnostics.CONNECTION_EVENT_FAILED) still fetches packet fates.
     */
    @Test
    public void reportConnectionFailureIsIgnoredWithoutVerboseMode() {
        final boolean verbosityToggle = false;
        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startPktFateMonitoring(STA_IF_NAME);
        mWifiDiagnostics.reportConnectionEvent(WifiDiagnostics.CONNECTION_EVENT_FAILED);
        verify(mWifiNative).getTxPktFates(any(), anyObject());
        verify(mWifiNative).getRxPktFates(any(), anyObject());
    }

    /**
     * Verifies that, when verbose mode is enabled, reportConnectionFailure() fetches packet fates.
     */
    @Test
    public void reportConnectionFailureFetchesFatesInVerboseMode() {
        final boolean verbosityToggle = true;
        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startPktFateMonitoring(STA_IF_NAME);
        mWifiDiagnostics.reportConnectionEvent(WifiDiagnostics.CONNECTION_EVENT_FAILED);
        verify(mWifiNative).getTxPktFates(any(), anyObject());
        verify(mWifiNative).getRxPktFates(any(), anyObject());
    }

    @Test
    public void reportConnectionEventPropagatesStartToLastMileLogger() {
        final boolean verbosityToggle = false;
        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.reportConnectionEvent(WifiDiagnostics.CONNECTION_EVENT_STARTED);
        verify(mLastMileLogger).reportConnectionEvent(WifiDiagnostics.CONNECTION_EVENT_STARTED);
    }

    @Test
    public void reportConnectionEventPropagatesSuccessToLastMileLogger() {
        final boolean verbosityToggle = false;
        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.reportConnectionEvent(WifiDiagnostics.CONNECTION_EVENT_SUCCEEDED);
        verify(mLastMileLogger).reportConnectionEvent(WifiDiagnostics.CONNECTION_EVENT_SUCCEEDED);
    }

    @Test
    public void reportConnectionEventPropagatesFailureToLastMileLogger() {
        final boolean verbosityToggle = false;
        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.reportConnectionEvent(WifiDiagnostics.CONNECTION_EVENT_FAILED);
        verify(mLastMileLogger).reportConnectionEvent(WifiDiagnostics.CONNECTION_EVENT_FAILED);
    }

    /**
     * Verifies that we are propagating the CONNECTION_EVENT_TIMEOUT event to LastMileLogger.
     */
    @Test
    public void reportConnectionEventPropagatesTimeoutToLastMileLogger() {
        final boolean verbosityToggle = true;
        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.reportConnectionEvent(WifiDiagnostics.CONNECTION_EVENT_TIMEOUT);
        verify(mLastMileLogger).reportConnectionEvent(WifiDiagnostics.CONNECTION_EVENT_TIMEOUT);
    }

    /**
     * Verifies that we try to fetch TX fates, even if fetching RX fates failed.
     */
    @Test
    public void loggerFetchesTxFatesEvenIfFetchingRxFatesFails() {
        final boolean verbosityToggle = true;
        when(mWifiNative.getRxPktFates(any(), anyObject())).thenReturn(false);
        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startPktFateMonitoring(STA_IF_NAME);
        mWifiDiagnostics.reportConnectionEvent(WifiDiagnostics.CONNECTION_EVENT_FAILED);
        verify(mWifiNative).getTxPktFates(any(), anyObject());
        verify(mWifiNative).getRxPktFates(any(), anyObject());
    }

    /**
     * Verifies that we try to fetch RX fates, even if fetching TX fates failed.
     */
    @Test
    public void loggerFetchesRxFatesEvenIfFetchingTxFatesFails() {
        final boolean verbosityToggle = true;
        when(mWifiNative.getTxPktFates(any(), anyObject())).thenReturn(false);
        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startPktFateMonitoring(STA_IF_NAME);
        mWifiDiagnostics.reportConnectionEvent(WifiDiagnostics.CONNECTION_EVENT_FAILED);
        verify(mWifiNative).getTxPktFates(any(), anyObject());
        verify(mWifiNative).getRxPktFates(any(), anyObject());
    }

    /** Verifies that dump() fetches the latest fates. */
    @Test
    public void dumpFetchesFates() {
        final boolean verbosityToggle = false;
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startPktFateMonitoring(STA_IF_NAME);
        mWifiDiagnostics.dump(new FileDescriptor(), pw, new String[]{"bogus", "args"});
        verify(mWifiNative).getTxPktFates(any(), anyObject());
        verify(mWifiNative).getRxPktFates(any(), anyObject());
    }

    /**
     * Verifies that dump() doesn't crash, or generate garbage, in the case where we haven't fetched
     * any fates.
     */
    @Test
    public void dumpSucceedsWhenNoFatesHaveNotBeenFetched() {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        mWifiDiagnostics.dump(new FileDescriptor(), pw, new String[]{"bogus", "args"});

        String fateDumpString = sw.toString();
        assertTrue(fateDumpString.contains("Last failed"));
        // Verify dump terminator is present
        assertTrue(fateDumpString.contains(
                "--------------------------------------------------------------------"));
    }

    /**
     * Verifies that dump() doesn't crash, or generate garbage, in the case where the fates that
     * the HAL-provided fates are empty.
     */
    @Test
    public void dumpSucceedsWhenFatesHaveBeenFetchedButAreEmpty() {
        final boolean verbosityToggle = true;
        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startPktFateMonitoring(STA_IF_NAME);
        mWifiDiagnostics.reportConnectionEvent(WifiDiagnostics.CONNECTION_EVENT_FAILED);
        verify(mWifiNative).getTxPktFates(any(), anyObject());
        verify(mWifiNative).getRxPktFates(any(), anyObject());

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        mWifiDiagnostics.dump(new FileDescriptor(), pw, new String[]{"bogus", "args"});

        String fateDumpString = sw.toString();
        assertTrue(fateDumpString.contains("Last failed"));
        // Verify dump terminator is present
        assertTrue(fateDumpString.contains(
                "--------------------------------------------------------------------"));
    }

    private String getDumpString(boolean verbose) {
        mWifiDiagnostics.enableVerboseLogging(verbose);
        mWifiDiagnostics.startPktFateMonitoring(STA_IF_NAME);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiNative.enableVerboseLogging(verbose ? 1 : 0);
        when(mWifiNative.getTxPktFates(any(), anyObject())).then(new AnswerWithArguments() {
            public boolean answer(String ifaceName, WifiNative.TxFateReport[] fates) {
                fates[0] = new WifiNative.TxFateReport(
                        WifiLoggerHal.TX_PKT_FATE_ACKED, 2, WifiLoggerHal.FRAME_TYPE_ETHERNET_II,
                        new byte[0]
                );
                fates[1] = new WifiNative.TxFateReport(
                        WifiLoggerHal.TX_PKT_FATE_ACKED, 0, WifiLoggerHal.FRAME_TYPE_ETHERNET_II,
                        new byte[0]
                );
                return true;
            }
        });
        when(mWifiNative.getRxPktFates(any(), anyObject())).then(new AnswerWithArguments() {
            public boolean answer(String ifaceName, WifiNative.RxFateReport[] fates) {
                fates[0] = new WifiNative.RxFateReport(
                        WifiLoggerHal.RX_PKT_FATE_SUCCESS, 3, WifiLoggerHal.FRAME_TYPE_ETHERNET_II,
                        new byte[0]
                );
                fates[1] = new WifiNative.RxFateReport(
                        WifiLoggerHal.RX_PKT_FATE_SUCCESS, 1, WifiLoggerHal.FRAME_TYPE_ETHERNET_II,
                        new byte[0]
                );
                return true;
            }
        });
        mWifiDiagnostics.reportConnectionEvent(WifiDiagnostics.CONNECTION_EVENT_FAILED);

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        mWifiDiagnostics.dump(new FileDescriptor(), pw, new String[]{"bogus", "args"});
        return sw.toString();
    }

      /**
     * Verifies that dump() shows both TX, and RX fates in only table form, when verbose
     * logging is not enabled.
     */
    @Test
    public void dumpShowsTxAndRxFates() {
        final boolean verbosityToggle = false;
        String dumpString = getDumpString(verbosityToggle);
        assertTrue(dumpString.contains(WifiNative.FateReport.getTableHeader()));
        assertTrue(Pattern.compile("0 .* TX ").matcher(dumpString).find());
        assertTrue(Pattern.compile("1 .* RX ").matcher(dumpString).find());
        assertTrue(Pattern.compile("2 .* TX ").matcher(dumpString).find());
        assertTrue(Pattern.compile("3 .* RX ").matcher(dumpString).find());
        assertFalse(dumpString.contains("VERBOSE PACKET FATE DUMP"));
        assertFalse(dumpString.contains("Frame bytes"));
    }

    /**
     * Verifies that dump() shows both TX, and RX fates in table and verbose forms, when verbose
     * logging is enabled.
     */
    @Test
    public void dumpShowsTxAndRxFatesVerbose() {
        final boolean verbosityToggle = true;
        String dumpString = getDumpString(verbosityToggle);
        assertTrue(dumpString.contains(WifiNative.FateReport.getTableHeader()));
        assertTrue(Pattern.compile("0 .* TX ").matcher(dumpString).find());
        assertTrue(Pattern.compile("1 .* RX ").matcher(dumpString).find());
        assertTrue(Pattern.compile("2 .* TX ").matcher(dumpString).find());
        assertTrue(Pattern.compile("3 .* RX ").matcher(dumpString).find());
        assertTrue(dumpString.contains("VERBOSE PACKET FATE DUMP"));
        assertTrue(dumpString.contains("Frame bytes"));
    }

    /**
     * Verifies that dump() outputs frames in timestamp order, even though the HAL provided the
     * data out-of-order (order is specified in getDumpString()).
     */
    @Test
    public void dumpIsSortedByTimestamp() {
        final boolean verbosityToggle = true;
        String dumpString = getDumpString(verbosityToggle);
        assertTrue(dumpString.contains(WifiNative.FateReport.getTableHeader()));
        assertTrue(Pattern.compile(
                "0 .* TX .*\n" +
                "1 .* RX .*\n" +
                "2 .* TX .*\n" +
                "3 .* RX "
        ).matcher(dumpString).find());

        int expected_index_of_verbose_frame_0 = dumpString.indexOf(
                "Frame direction: TX\nFrame timestamp: 0\n");
        int expected_index_of_verbose_frame_1 = dumpString.indexOf(
                "Frame direction: RX\nFrame timestamp: 1\n");
        int expected_index_of_verbose_frame_2 = dumpString.indexOf(
                "Frame direction: TX\nFrame timestamp: 2\n");
        int expected_index_of_verbose_frame_3 = dumpString.indexOf(
                "Frame direction: RX\nFrame timestamp: 3\n");
        assertFalse(-1 == expected_index_of_verbose_frame_0);
        assertFalse(-1 == expected_index_of_verbose_frame_1);
        assertFalse(-1 == expected_index_of_verbose_frame_2);
        assertFalse(-1 == expected_index_of_verbose_frame_3);
        assertTrue(expected_index_of_verbose_frame_0 < expected_index_of_verbose_frame_1);
        assertTrue(expected_index_of_verbose_frame_1 < expected_index_of_verbose_frame_2);
        assertTrue(expected_index_of_verbose_frame_2 < expected_index_of_verbose_frame_3);
    }

    /** Verifies that eng builds do not show fate detail outside of verbose mode. */
    @Test
    public void dumpOmitsFateDetailInEngBuildsOutsideOfVerboseMode() throws Exception {
        final boolean verbosityToggle = false;
        when(mBuildProperties.isEngBuild()).thenReturn(true);
        when(mBuildProperties.isUserdebugBuild()).thenReturn(false);
        when(mBuildProperties.isUserBuild()).thenReturn(false);
        String dumpString = getDumpString(verbosityToggle);
        assertFalse(dumpString.contains("VERBOSE PACKET FATE DUMP"));
        assertFalse(dumpString.contains("Frame bytes"));
    }

    /** Verifies that userdebug builds do not show fate detail outside of verbose mode. */
    @Test
    public void dumpOmitsFateDetailInUserdebugBuildsOutsideOfVerboseMode() throws Exception {
        final boolean verbosityToggle = false;
        when(mBuildProperties.isUserdebugBuild()).thenReturn(true);
        when(mBuildProperties.isEngBuild()).thenReturn(false);
        when(mBuildProperties.isUserBuild()).thenReturn(false);
        String dumpString = getDumpString(verbosityToggle);
        assertFalse(dumpString.contains("VERBOSE PACKET FATE DUMP"));
        assertFalse(dumpString.contains("Frame bytes"));
    }

    /**
     * Verifies that, if verbose is disabled after fetching fates, the dump does not include
     * verbose fate logs.
     */
    @Test
    public void dumpOmitsFatesIfVerboseIsDisabledAfterFetch() {
        final boolean verbosityToggle = true;
        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startPktFateMonitoring(STA_IF_NAME);
        when(mWifiNative.getTxPktFates(any(), anyObject())).then(new AnswerWithArguments() {
            public boolean answer(String ifaceName, WifiNative.TxFateReport[] fates) {
                fates[0] = new WifiNative.TxFateReport(
                        WifiLoggerHal.TX_PKT_FATE_ACKED, 0, WifiLoggerHal.FRAME_TYPE_ETHERNET_II,
                        new byte[0]
                );
                return true;
            }
        });
        when(mWifiNative.getRxPktFates(any(), anyObject())).then(new AnswerWithArguments() {
            public boolean answer(String ifaceName, WifiNative.RxFateReport[] fates) {
                fates[0] = new WifiNative.RxFateReport(
                        WifiLoggerHal.RX_PKT_FATE_SUCCESS, 1, WifiLoggerHal.FRAME_TYPE_ETHERNET_II,
                        new byte[0]
                );
                return true;
            }
        });
        mWifiDiagnostics.reportConnectionEvent(WifiDiagnostics.CONNECTION_EVENT_FAILED);
        verify(mWifiNative).getTxPktFates(any(), anyObject());
        verify(mWifiNative).getRxPktFates(any(), anyObject());

        final boolean newVerbosityToggle = false;
        mWifiDiagnostics.enableVerboseLogging(newVerbosityToggle);
        mWifiDiagnostics.startLogging(STA_IF_NAME);

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        mWifiDiagnostics.dump(new FileDescriptor(), pw, new String[]{"bogus", "args"});

        String fateDumpString = sw.toString();
        assertFalse(fateDumpString.contains("VERBOSE PACKET FATE DUMP"));
        assertFalse(fateDumpString.contains("Frame bytes"));
    }

    /** Verifies that the default size of our ring buffers is small. */
    @Ignore("TODO(b/36811399): re-enable this @Test")
    @Test
    public void ringBufferSizeIsSmallByDefault() throws Exception {
        final boolean verbosityToggle = false;
        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.onRingBufferData(
                mFakeRbs, new byte[SMALL_RING_BUFFER_SIZE_KB * BYTES_PER_KBYTE + 1]);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);
        assertEquals(0, getLoggerRingBufferData().length);
    }

    /** Verifies that we use small ring buffers by default, on userdebug builds. */
    @Ignore("TODO(b/36811399): re-enable this @Test")
    @Test
    public void ringBufferSizeIsSmallByDefaultOnUserdebugBuilds() throws Exception {
        final boolean verbosityToggle = false;
        when(mBuildProperties.isUserdebugBuild()).thenReturn(true);
        when(mBuildProperties.isEngBuild()).thenReturn(false);
        when(mBuildProperties.isUserBuild()).thenReturn(false);
        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.onRingBufferData(
                mFakeRbs, new byte[SMALL_RING_BUFFER_SIZE_KB * BYTES_PER_KBYTE + 1]);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);
        assertEquals(0, getLoggerRingBufferData().length);
    }

    /** Verifies that we use small ring buffers by default, on eng builds. */
    @Ignore("TODO(b/36811399): re-enable this @Test")
    @Test
    public void ringBufferSizeIsSmallByDefaultOnEngBuilds() throws Exception {
        final boolean verbosityToggle = false;
        when(mBuildProperties.isEngBuild()).thenReturn(true);
        when(mBuildProperties.isUserdebugBuild()).thenReturn(false);
        when(mBuildProperties.isUserBuild()).thenReturn(false);
        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.onRingBufferData(
                mFakeRbs, new byte[SMALL_RING_BUFFER_SIZE_KB * BYTES_PER_KBYTE + 1]);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);
        assertEquals(0, getLoggerRingBufferData().length);
    }

    /** Verifies that we use large ring buffers when initially started in verbose mode. */
    @Test
    public void ringBufferSizeIsLargeInVerboseMode() throws Exception {
        final boolean verbosityToggle = true;

        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.onRingBufferData(
                mFakeRbs, new byte[LARGE_RING_BUFFER_SIZE_KB * BYTES_PER_KBYTE]);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);
        assertEquals(1, getLoggerRingBufferData().length);
    }

    /** Verifies that we use large ring buffers when switched from normal to verbose mode. */
    @Test
    public void startLoggingGrowsRingBuffersIfNeeded() throws Exception {
        mWifiDiagnostics.enableVerboseLogging(false /* verbose disabled */);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.enableVerboseLogging(true /* verbose enabled */);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.onRingBufferData(
                mFakeRbs, new byte[LARGE_RING_BUFFER_SIZE_KB * BYTES_PER_KBYTE]);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);
        assertEquals(1, getLoggerRingBufferData().length);
    }

    /** Verifies that we use small ring buffers when switched from verbose to normal mode. */
    @Ignore("TODO(b/36811399): re-enabled this @Test")
    @Test
    public void startLoggingShrinksRingBuffersIfNeeded() throws Exception {

        mWifiDiagnostics.enableVerboseLogging(true /* verbose enabled */);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.onRingBufferData(
                mFakeRbs, new byte[SMALL_RING_BUFFER_SIZE_KB * BYTES_PER_KBYTE + 1]);

        // Existing data is nuked (too large).
        mWifiDiagnostics.enableVerboseLogging(false /* verbose disabled */);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);
        assertEquals(0, getLoggerRingBufferData().length);

        // New data must obey limit as well.
        mWifiDiagnostics.onRingBufferData(
                mFakeRbs, new byte[SMALL_RING_BUFFER_SIZE_KB * BYTES_PER_KBYTE + 1]);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);
        assertEquals(0, getLoggerRingBufferData().length);
    }

    /**
     * Verifies that we capture a bugreport & store alert data when WifiNative invokes
     * the alert callback.
     */
    @Test
    public void onWifiAlertCapturesBugreportAndLogsMetrics() throws Exception {
        mWifiDiagnostics.onWifiAlert(ALERT_REASON_CODE, ALERT_DATA);

        assertEquals(1, mWifiDiagnostics.getAlertReports().size());
        WifiDiagnostics.BugReport alertReport = mWifiDiagnostics.getAlertReports().get(0);
        assertEquals(ALERT_REASON_CODE, alertReport.errorCode);
        assertArrayEquals(ALERT_DATA, alertReport.alertData);

        verify(mWifiMetrics).logFirmwareAlert(ALERT_REASON_CODE);
    }

    /** Verifies that we skip the firmware and driver dumps if verbose is not enabled. */
    @Test
    public void captureBugReportSkipsFirmwareAndDriverDumpsByDefault() {
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);
        verify(mWifiNative, never()).getFwMemoryDump();
        verify(mWifiNative, never()).getDriverStateDump();
    }

    /** Verifies that we capture the firmware and driver dumps if verbose is enabled. */
    @Test
    public void captureBugReportTakesFirmwareAndDriverDumpsInVerboseMode() {
        mWifiDiagnostics.enableVerboseLogging(true /* verbose enabled */);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);
        verify(mWifiNative).getFwMemoryDump();
        verify(mWifiNative).getDriverStateDump();
    }

    /** Verifies that the dump includes driver state, if driver state was provided by HAL. */
    @Test
    public void dumpIncludesDriverStateDumpIfAvailable() {
        when(mWifiNative.getDriverStateDump()).thenReturn(new byte[]{0, 1, 2});

        mWifiDiagnostics.enableVerboseLogging(true /* verbose enabled */);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);
        verify(mWifiNative).getDriverStateDump();

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        mWifiDiagnostics.dump(new FileDescriptor(), pw, new String[]{});
        assertTrue(sw.toString().contains(WifiDiagnostics.DRIVER_DUMP_SECTION_HEADER));
    }

    /** Verifies that the dump skips driver state, if driver state was not provided by HAL. */
    @Test
    public void dumpOmitsDriverStateDumpIfUnavailable() {
        mWifiDiagnostics.enableVerboseLogging(true /* verbose enabled */);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);
        verify(mWifiNative).getDriverStateDump();

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        mWifiDiagnostics.dump(new FileDescriptor(), pw, new String[]{});
        assertFalse(sw.toString().contains(WifiDiagnostics.DRIVER_DUMP_SECTION_HEADER));
    }

    /** Verifies that the dump omits driver state, if verbose was disabled after capture. */
    @Test
    public void dumpOmitsDriverStateDumpIfVerboseDisabledAfterCapture() {
        when(mWifiNative.getDriverStateDump()).thenReturn(new byte[]{0, 1, 2});

        mWifiDiagnostics.enableVerboseLogging(true /* verbose enabled */);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);
        verify(mWifiNative).getDriverStateDump();

        mWifiDiagnostics.enableVerboseLogging(false /* verbose disabled */);
        mWifiDiagnostics.startLogging(STA_IF_NAME);

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        mWifiDiagnostics.dump(new FileDescriptor(), pw, new String[]{});
        assertFalse(sw.toString().contains(WifiDiagnostics.DRIVER_DUMP_SECTION_HEADER));
    }

    /** Verifies that the dump includes firmware dump, if firmware dump was provided by HAL. */
    @Test
    public void dumpIncludesFirmwareMemoryDumpIfAvailable() {
        when(mWifiNative.getFwMemoryDump()).thenReturn(new byte[]{0, 1, 2});

        mWifiDiagnostics.enableVerboseLogging(true /* verbose enabled */);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);
        verify(mWifiNative).getFwMemoryDump();

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        mWifiDiagnostics.dump(new FileDescriptor(), pw, new String[]{});
        assertTrue(sw.toString().contains(WifiDiagnostics.FIRMWARE_DUMP_SECTION_HEADER));
    }

    /** Verifies that the dump skips firmware memory, if firmware memory was not provided by HAL. */
    @Test
    public void dumpOmitsFirmwareMemoryDumpIfUnavailable() {
        mWifiDiagnostics.enableVerboseLogging(true /* verbose enabled */);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);
        verify(mWifiNative).getFwMemoryDump();

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        mWifiDiagnostics.dump(new FileDescriptor(), pw, new String[]{});
        assertFalse(sw.toString().contains(WifiDiagnostics.FIRMWARE_DUMP_SECTION_HEADER));
    }

    /** Verifies that the dump omits firmware memory, if verbose was disabled after capture. */
    @Test
    public void dumpOmitsFirmwareMemoryDumpIfVerboseDisabledAfterCapture() {
        when(mWifiNative.getFwMemoryDump()).thenReturn(new byte[]{0, 1, 2});

        mWifiDiagnostics.enableVerboseLogging(true /* verbose enabled */);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);
        verify(mWifiNative).getFwMemoryDump();

        mWifiDiagnostics.enableVerboseLogging(false /* verbose disabled */);
        mWifiDiagnostics.startLogging(STA_IF_NAME);

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        mWifiDiagnostics.dump(new FileDescriptor(), pw, new String[]{});
        assertFalse(sw.toString().contains(WifiDiagnostics.FIRMWARE_DUMP_SECTION_HEADER));
    }

    @Test
    public void dumpRequestsLastMileLoggerDump() {
        mWifiDiagnostics.dump(
                new FileDescriptor(), new PrintWriter(new StringWriter()), new String[]{});
        verify(mLastMileLogger).dump(anyObject());
    }

    @Test
    public void takeBugReportCallsActivityManagerOnUserDebug() {
        when(mBuildProperties.isUserBuild()).thenReturn(false);
        mWifiDiagnostics.takeBugReport("", "");
        verify(mActivityManagerService, times(1)).requestWifiBugReport(
                anyString(), anyString());
    }

    @Test
    public void takeBugReportSwallowsExceptions() {
        when(mBuildProperties.isUserBuild()).thenReturn(false);
        doThrow(new RuntimeException()).when(mActivityManagerService).requestWifiBugReport(
                anyString(), anyString());
        mWifiDiagnostics.takeBugReport("", "");
        verify(mActivityManagerService, times(1)).requestWifiBugReport(
                anyString(), anyString());
    }

    @Test
    public void takeBugReportDoesNothingOnUserBuild() {
        when(mBuildProperties.isUserBuild()).thenReturn(true);
        mWifiDiagnostics.takeBugReport("", "");
        verify(mActivityManagerService, never()).requestWifiBugReport(anyString(), anyString());
    }

    /** Verifies that we flush HAL ringbuffer when capture bugreport. */
    @Test
    public void captureBugReportFlushRingBufferData() {
        when(mBuildProperties.isUserBuild()).thenReturn(false);
        when(mWifiNative.flushRingBufferData()).thenReturn(true);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);
        verify(mWifiNative).flushRingBufferData();
    }

    /** Verifies that we flush HAL ringbuffer when detecting fatal firmware alert. */
    @Test
    public void captureAlertFlushRingBufferData() {
        when(mBuildProperties.isUserBuild()).thenReturn(false);
        when(mWifiNative.flushRingBufferData()).thenReturn(true);
        /** captureAlertData with mock fatal firmware alert*/
        mWifiDiagnostics.captureAlertData(FATAL_FW_ALART_LIST[0], ALERT_DATA);
        verify(mWifiNative).flushRingBufferData();
    }

    /** Verifies that we don't flush HAL ringbuffer when detecting non fatal firmware alert. */
    @Test
    public void captureNonAlertFlushRingBufferData() {
        when(mBuildProperties.isUserBuild()).thenReturn(false);
        when(mWifiNative.flushRingBufferData()).thenReturn(true);
        /** captureAlertData with mock non fatal firmware alert*/
        mWifiDiagnostics.captureAlertData(NON_FATAL_FW_ALART, ALERT_DATA);
        verify(mWifiNative, never()).flushRingBufferData();
    }

    /**
     * Verifies that we can capture ring-buffer data in SoftAp mode
     */
    @Test
    public void canCaptureAndStoreRingBufferDataInSoftApMode() throws Exception {
        final boolean verbosityToggle = false;

        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startLogging(AP_IF_NAME);

        final byte[] data = new byte[SMALL_RING_BUFFER_SIZE_KB * BYTES_PER_KBYTE];
        mWifiDiagnostics.onRingBufferData(mFakeRbs, data);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);

        byte[][] ringBufferData = getLoggerRingBufferData();
        assertEquals(1, ringBufferData.length);
        assertArrayEquals(data, ringBufferData[0]);
    }

    /**
     * Verifies that we capture ring-buffer data in Station + SoftAp
     * Concurrency mode.
     */
    @Test
    public void canCaptureAndStoreRingBufferDataInConcurrencyMode() throws Exception {
        final boolean verbosityToggle = false;

        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.startLogging(AP_IF_NAME);

        final byte[] data = new byte[SMALL_RING_BUFFER_SIZE_KB * BYTES_PER_KBYTE];
        mWifiDiagnostics.onRingBufferData(mFakeRbs, data);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);

        byte[][] ringBufferData = getLoggerRingBufferData();
        assertEquals(1, ringBufferData.length);
        assertArrayEquals(data, ringBufferData[0]);
    }

    /**
     * Verifies that we can continue to capture ring-buffer data
     * after WiFi station is turned off in concurrency mode.
     */
    @Test
    public void canCaptureAndStoreRingBufferDataAfterStaIsTurnedOffInConcurrencyMode()
            throws Exception {
        final boolean verbosityToggle = false;
        final byte[] data = new byte[SMALL_RING_BUFFER_SIZE_KB * BYTES_PER_KBYTE];

        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.startLogging(AP_IF_NAME);

        mWifiDiagnostics.onRingBufferData(mFakeRbs, data);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);

        byte[][] ringBufferData0 = getLoggerRingBufferData();
        assertEquals(1, ringBufferData0.length);
        assertArrayEquals(data, ringBufferData0[0]);

        mWifiDiagnostics.stopLogging(STA_IF_NAME);

        mWifiDiagnostics.onRingBufferData(mFakeRbs, data);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);

        byte[][] ringBufferData1 = getLoggerRingBufferData();
        assertEquals(1, ringBufferData1.length);
        assertArrayEquals(data, ringBufferData1[0]);
    }

    /**
     * Verifies that we can continue to capture ring-buffer data
     * after SoftAp is turned off in concurrency mode.
     */
    @Test
    public void canCaptureAndStoreRingBufferDataAfterSoftApIsTurnedOffInConcurrencyMode()
            throws Exception {
        final boolean verbosityToggle = false;
        final byte[] data = new byte[SMALL_RING_BUFFER_SIZE_KB * BYTES_PER_KBYTE];

        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        mWifiDiagnostics.startLogging(STA_IF_NAME);
        mWifiDiagnostics.startLogging(AP_IF_NAME);

        mWifiDiagnostics.onRingBufferData(mFakeRbs, data);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);

        byte[][] ringBufferData0 = getLoggerRingBufferData();
        assertEquals(1, ringBufferData0.length);
        assertArrayEquals(data, ringBufferData0[0]);

        mWifiDiagnostics.stopLogging(AP_IF_NAME);

        mWifiDiagnostics.onRingBufferData(mFakeRbs, data);
        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_NONE);

        byte[][] ringBufferData1 = getLoggerRingBufferData();
        assertEquals(1, ringBufferData1.length);
        assertArrayEquals(data, ringBufferData1[0]);
    }

    /** Verifies that stoplogging on both the interfaces clean up
     *  all the resources.
     */
    @Test
    public void verifyStopLoggingOnAllInterfacesClearTheResources() throws Exception {
        final boolean verbosityToggle = false;

        mWifiDiagnostics.enableVerboseLogging(verbosityToggle);
        when(mWifiNative.setLoggingEventHandler(any())).thenReturn(true);
        when(mWifiNative.resetLogHandler()).thenReturn(true);

        mWifiDiagnostics.startLogging(STA_IF_NAME);
        verify(mWifiNative).setLoggingEventHandler(any());

        mWifiDiagnostics.startLogging(AP_IF_NAME);

        mWifiDiagnostics.stopLogging(STA_IF_NAME);
        verify(mWifiNative, never()).resetLogHandler();

        mWifiDiagnostics.stopLogging(AP_IF_NAME);

        verify(mWifiNative).resetLogHandler();
    }
}