File: traffic_stats_amortizer_unittest.cc

package info (click to toggle)
chromium-browser 57.0.2987.98-1~deb8u1
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 2,637,852 kB
  • ctags: 2,544,394
  • sloc: cpp: 12,815,961; ansic: 3,676,222; python: 1,147,112; asm: 526,608; java: 523,212; xml: 286,794; perl: 92,654; sh: 86,408; objc: 73,271; makefile: 27,698; cs: 18,487; yacc: 13,031; tcl: 12,957; pascal: 4,875; ml: 4,716; lex: 3,904; sql: 3,862; ruby: 1,982; lisp: 1,508; php: 1,368; exp: 404; awk: 325; csh: 117; jsp: 39; sed: 37
file content (844 lines) | stat: -rw-r--r-- 36,952 bytes parent folder | download | duplicates (2)
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
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/data_usage/android/traffic_stats_amortizer.h"

#include <stddef.h>
#include <stdint.h>

#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "base/bind.h"
#include "base/macros.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram_base.h"
#include "base/run_loop.h"
#include "base/test/histogram_tester.h"
#include "base/test/simple_test_tick_clock.h"
#include "base/time/tick_clock.h"
#include "base/time/time.h"
#include "base/timer/mock_timer.h"
#include "base/timer/timer.h"
#include "components/data_usage/core/data_use.h"
#include "components/data_usage/core/data_use_amortizer.h"
#include "net/base/network_change_notifier.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"

namespace data_usage {
namespace android {

namespace {

// The delay between receiving DataUse and querying TrafficStats byte counts for
// amortization.
const base::TimeDelta kTrafficStatsQueryDelay =
    base::TimeDelta::FromMilliseconds(50);

// The longest amount of time that an amortization run can be delayed for.
const base::TimeDelta kMaxAmortizationDelay =
    base::TimeDelta::FromMilliseconds(200);

// The maximum allowed size of the DataUse buffer.
const size_t kMaxDataUseBufferSize = 8;

const char kPreAmortizationTxHistogram[] =
    "TrafficStatsAmortizer.PreAmortizationRunDataUseBytes.Tx";
const char kPreAmortizationRxHistogram[] =
    "TrafficStatsAmortizer.PreAmortizationRunDataUseBytes.Rx";
const char kPostAmortizationTxHistogram[] =
    "TrafficStatsAmortizer.PostAmortizationRunDataUseBytes.Tx";
const char kPostAmortizationRxHistogram[] =
    "TrafficStatsAmortizer.PostAmortizationRunDataUseBytes.Rx";
const char kAmortizationDelayHistogram[] =
    "TrafficStatsAmortizer.AmortizationDelay";
const char kBufferSizeOnFlushHistogram[] =
    "TrafficStatsAmortizer.BufferSizeOnFlush";
const char kConcurrentTabs[] = "TrafficStatsAmortizer.ConcurrentTabs";

// The maximum sample value that can be recorded in a histogram.
const base::HistogramBase::Sample kMaxRecordableSample =
    base::HistogramBase::kSampleType_MAX - 1;

// Converts a |delay| into a histogram sample of the number of milliseconds in
// the delay.
base::HistogramBase::Sample GetDelaySample(const base::TimeDelta& delay) {
  return static_cast<base::HistogramBase::Sample>(delay.InMilliseconds());
}

// Synthesizes a fake std::unique_ptr<DataUse> with the given |url|, |tab_id|,
// |tx_bytes| and |rx_bytes|, using arbitrary values for all other fields.
std::unique_ptr<DataUse> CreateDataUseWithURLAndTab(const GURL& url,
                                                    int32_t tab_id,
                                                    int64_t tx_bytes,
                                                    int64_t rx_bytes) {
  return std::unique_ptr<DataUse>(
      new DataUse(url, base::TimeTicks() /* request_start */,
                  GURL("http://examplefirstparty.com"), tab_id,
                  net::NetworkChangeNotifier::CONNECTION_2G, "example_mcc_mnc",
                  tx_bytes, rx_bytes));
}

// Synthesizes a fake std::unique_ptr<DataUse> with the given |url|, |tx_bytes|
// and
// |rx_bytes|, using arbitrary values for all other fields.
std::unique_ptr<DataUse> CreateDataUseWithURL(const GURL& url,
                                              int64_t tx_bytes,
                                              int64_t rx_bytes) {
  return CreateDataUseWithURLAndTab(url, 10, tx_bytes, rx_bytes);
}

// Synthesizes a fake std::unique_ptr<DataUse> with the given |tab_id|,
// |tx_bytes|
// and |rx_bytes|, using arbitrary values for all other fields.
std::unique_ptr<DataUse> CreateDataUseWithTab(int32_t tab_id,
                                              int64_t tx_bytes,
                                              int64_t rx_bytes) {
  return CreateDataUseWithURLAndTab(GURL("http://example.com"), tab_id,
                                    tx_bytes, rx_bytes);
}

// Synthesizes a fake std::unique_ptr<DataUse> with the given |tx_bytes| and
// |rx_bytes|, using arbitrary values for all other fields.
std::unique_ptr<DataUse> CreateDataUse(int64_t tx_bytes, int64_t rx_bytes) {
  return CreateDataUseWithURL(GURL("http://example.com"), tx_bytes, rx_bytes);
}

// Appends |data_use| to |data_use_sequence|. |data_use_sequence| must not be
// NULL.
void AppendDataUseToSequence(
    std::vector<std::unique_ptr<DataUse>>* data_use_sequence,
    std::unique_ptr<DataUse> data_use) {
  data_use_sequence->push_back(std::move(data_use));
}

// Class that represents a base::MockTimer with an attached base::TickClock, so
// that it can update its |desired_run_time()| according to the current time
// when the timer is reset.
class MockTimerWithTickClock : public base::MockTimer {
 public:
  MockTimerWithTickClock(bool retain_user_task,
                         bool is_repeating,
                         base::TickClock* tick_clock)
      : base::MockTimer(retain_user_task, is_repeating),
        tick_clock_(tick_clock) {}

  ~MockTimerWithTickClock() override {}

  void Reset() override {
    base::MockTimer::Reset();
    set_desired_run_time(tick_clock_->NowTicks() + GetCurrentDelay());
  }

 private:
  base::TickClock* tick_clock_;

  DISALLOW_COPY_AND_ASSIGN(MockTimerWithTickClock);
};

// A TrafficStatsAmortizer for testing that allows for tests to simulate the
// byte counts returned from TrafficStats.
class TestTrafficStatsAmortizer : public TrafficStatsAmortizer {
 public:
  TestTrafficStatsAmortizer(
      std::unique_ptr<base::TickClock> tick_clock,
      std::unique_ptr<base::Timer> traffic_stats_query_timer)
      : TrafficStatsAmortizer(std::move(tick_clock),
                              std::move(traffic_stats_query_timer),
                              kTrafficStatsQueryDelay,
                              kMaxAmortizationDelay,
                              kMaxDataUseBufferSize),
        next_traffic_stats_available_(false),
        next_traffic_stats_tx_bytes_(-1),
        next_traffic_stats_rx_bytes_(-1) {}

  ~TestTrafficStatsAmortizer() override {}

  void SetNextTrafficStats(bool available, int64_t tx_bytes, int64_t rx_bytes) {
    next_traffic_stats_available_ = available;
    next_traffic_stats_tx_bytes_ = tx_bytes;
    next_traffic_stats_rx_bytes_ = rx_bytes;
  }

  void AddTrafficStats(int64_t tx_bytes, int64_t rx_bytes) {
    next_traffic_stats_tx_bytes_ += tx_bytes;
    next_traffic_stats_rx_bytes_ += rx_bytes;
  }

 protected:
  bool QueryTrafficStats(int64_t* tx_bytes, int64_t* rx_bytes) const override {
    *tx_bytes = next_traffic_stats_tx_bytes_;
    *rx_bytes = next_traffic_stats_rx_bytes_;
    return next_traffic_stats_available_;
  }

 private:
  bool next_traffic_stats_available_;
  int64_t next_traffic_stats_tx_bytes_;
  int64_t next_traffic_stats_rx_bytes_;

  DISALLOW_COPY_AND_ASSIGN(TestTrafficStatsAmortizer);
};

class TrafficStatsAmortizerTest : public testing::Test {
 public:
  TrafficStatsAmortizerTest()
      : test_tick_clock_(new base::SimpleTestTickClock()),
        mock_timer_(new MockTimerWithTickClock(false, false, test_tick_clock_)),
        amortizer_(std::unique_ptr<base::TickClock>(test_tick_clock_),
                   std::unique_ptr<base::Timer>(mock_timer_)),
        data_use_callback_call_count_(0) {}

  ~TrafficStatsAmortizerTest() override {
    EXPECT_FALSE(mock_timer_->IsRunning());
  }

  // Simulates the passage of time by |delta|, firing timers when appropriate.
  void AdvanceTime(const base::TimeDelta& delta) {
    const base::TimeTicks end_time = test_tick_clock_->NowTicks() + delta;
    base::RunLoop().RunUntilIdle();

    while (test_tick_clock_->NowTicks() < end_time) {
      PumpMockTimer();

      // If |mock_timer_| is scheduled to fire in the future before |end_time|,
      // advance to that time.
      if (mock_timer_->IsRunning() &&
          mock_timer_->desired_run_time() < end_time) {
        test_tick_clock_->Advance(mock_timer_->desired_run_time() -
                                  test_tick_clock_->NowTicks());
      } else {
        // Otherwise, advance to |end_time|.
        test_tick_clock_->Advance(end_time - test_tick_clock_->NowTicks());
      }
    }
    PumpMockTimer();
  }

  // Skip the first amortization run where TrafficStats byte count deltas are
  // unavailable, for convenience.
  void SkipFirstAmortizationRun() {
    // The initial values of TrafficStats shouldn't matter.
    amortizer()->SetNextTrafficStats(true, 0, 0);

    // Do the first amortization run with TrafficStats unavailable.
    amortizer()->OnExtraBytes(100, 1000);
    AdvanceTime(kTrafficStatsQueryDelay);
    EXPECT_EQ(0, data_use_callback_call_count());
  }

  // Expects that |expected| and |actual| are equivalent.
  void ExpectDataUse(std::unique_ptr<DataUse> expected,
                     std::unique_ptr<DataUse> actual) {
    ++data_use_callback_call_count_;

    // Have separate checks for the |tx_bytes| and |rx_bytes|, since those are
    // calculated with floating point arithmetic.
    EXPECT_DOUBLE_EQ(static_cast<double>(expected->tx_bytes),
                     static_cast<double>(actual->tx_bytes));
    EXPECT_DOUBLE_EQ(static_cast<double>(expected->rx_bytes),
                     static_cast<double>(actual->rx_bytes));

    // Copy the byte counts over from |expected| just in case they're only
    // slightly different due to floating point error, so that this doesn't
    // cause the equality comparison below to fail.
    actual->tx_bytes = expected->tx_bytes;
    actual->rx_bytes = expected->rx_bytes;
    EXPECT_EQ(*expected, *actual);
  }

  // Creates an ExpectDataUse callback, as a convenience.
  DataUseAmortizer::AmortizationCompleteCallback ExpectDataUseCallback(
      std::unique_ptr<DataUse> expected) {
    return base::Bind(&TrafficStatsAmortizerTest::ExpectDataUse,
                      base::Unretained(this), base::Passed(&expected));
  }

  base::TimeTicks NowTicks() const { return test_tick_clock_->NowTicks(); }

  TestTrafficStatsAmortizer* amortizer() { return &amortizer_; }

  int data_use_callback_call_count() const {
    return data_use_callback_call_count_;
  }

 private:
  // Pumps |mock_timer_|, firing it while it's scheduled to run now or in the
  // past. After calling this, |mock_timer_| is either not running or is
  // scheduled to run in the future.
  void PumpMockTimer() {
    // Fire the |mock_timer_| if the time has come up. Use a while loop in case
    // the fired task started the timer again to fire immediately.
    while (mock_timer_->IsRunning() &&
           mock_timer_->desired_run_time() <= test_tick_clock_->NowTicks()) {
      mock_timer_->Fire();
      base::RunLoop().RunUntilIdle();
    }
  }

  base::MessageLoop message_loop_;

  // Weak, owned by |amortizer_|.
  base::SimpleTestTickClock* test_tick_clock_;

  // Weak, owned by |amortizer_|.
  MockTimerWithTickClock* mock_timer_;

  TestTrafficStatsAmortizer amortizer_;

  // The number of times ExpectDataUse has been called.
  int data_use_callback_call_count_;

  DISALLOW_COPY_AND_ASSIGN(TrafficStatsAmortizerTest);
};

TEST_F(TrafficStatsAmortizerTest, AmortizeWithTrafficStatsAlwaysUnavailable) {
  amortizer()->SetNextTrafficStats(false, -1, -1);
  // Do it three times for good measure.
  for (int i = 0; i < 3; ++i) {
    base::HistogramTester histogram_tester;

    // Extra bytes should be ignored since TrafficStats are unavailable.
    amortizer()->OnExtraBytes(1337, 9001);
    // The original DataUse should be unchanged.
    amortizer()->AmortizeDataUse(
        CreateDataUse(100, 1000),
        ExpectDataUseCallback(CreateDataUse(100, 1000)));

    AdvanceTime(kTrafficStatsQueryDelay);
    EXPECT_EQ(i + 1, data_use_callback_call_count());

    histogram_tester.ExpectUniqueSample(kPreAmortizationTxHistogram, 100, 1);
    histogram_tester.ExpectUniqueSample(kPreAmortizationRxHistogram, 1000, 1);
    histogram_tester.ExpectUniqueSample(kPostAmortizationTxHistogram, 100, 1);
    histogram_tester.ExpectUniqueSample(kPostAmortizationRxHistogram, 1000, 1);
    histogram_tester.ExpectUniqueSample(kAmortizationDelayHistogram,
                                        GetDelaySample(kTrafficStatsQueryDelay),
                                        1);
    histogram_tester.ExpectUniqueSample(kBufferSizeOnFlushHistogram, 1, 1);
    histogram_tester.ExpectUniqueSample(kConcurrentTabs, 1, 1);
  }
}

TEST_F(TrafficStatsAmortizerTest, AmortizeDataUse) {
  // Simulate the first amortization run.
  {
    base::HistogramTester histogram_tester;

    // The initial values of TrafficStats shouldn't matter.
    amortizer()->SetNextTrafficStats(true, 1337, 9001);

    // The first amortization run should not change any byte counts because
    // there's no TrafficStats delta to work with.
    amortizer()->AmortizeDataUse(CreateDataUse(50, 500),
                                 ExpectDataUseCallback(CreateDataUse(50, 500)));
    amortizer()->AmortizeDataUse(
        CreateDataUse(100, 1000),
        ExpectDataUseCallback(CreateDataUse(100, 1000)));
    AdvanceTime(kTrafficStatsQueryDelay);
    EXPECT_EQ(2, data_use_callback_call_count());

    histogram_tester.ExpectUniqueSample(kPreAmortizationTxHistogram, 150, 1);
    histogram_tester.ExpectUniqueSample(kPreAmortizationRxHistogram, 1500, 1);
    histogram_tester.ExpectUniqueSample(kPostAmortizationTxHistogram, 150, 1);
    histogram_tester.ExpectUniqueSample(kPostAmortizationRxHistogram, 1500, 1);
    histogram_tester.ExpectUniqueSample(kAmortizationDelayHistogram,
                                        GetDelaySample(kTrafficStatsQueryDelay),
                                        1);
    histogram_tester.ExpectUniqueSample(kBufferSizeOnFlushHistogram, 2, 1);
    histogram_tester.ExpectUniqueSample(kConcurrentTabs, 1, 1);
  }

  // Simulate the second amortization run.
  {
    base::HistogramTester histogram_tester;

    // This amortization run, tx_bytes and rx_bytes should be doubled.
    amortizer()->AmortizeDataUse(
        CreateDataUse(50, 500),
        ExpectDataUseCallback(CreateDataUse(100, 1000)));
    AdvanceTime(kTrafficStatsQueryDelay / 2);

    // Another DataUse is reported before the amortizer queries TrafficStats.
    amortizer()->AmortizeDataUse(
        CreateDataUse(100, 1000),
        ExpectDataUseCallback(CreateDataUse(200, 2000)));
    AdvanceTime(kTrafficStatsQueryDelay / 2);

    // Then, the TrafficStats values update with the new bytes. The second run
    // callbacks should not have been called yet.
    amortizer()->AddTrafficStats(300, 3000);
    EXPECT_EQ(2, data_use_callback_call_count());

    // The callbacks should fire once kTrafficStatsQueryDelay has passed since
    // the DataUse was passed to the amortizer.
    AdvanceTime(kTrafficStatsQueryDelay / 2);
    EXPECT_EQ(4, data_use_callback_call_count());

    histogram_tester.ExpectUniqueSample(kPreAmortizationTxHistogram, 150, 1);
    histogram_tester.ExpectUniqueSample(kPreAmortizationRxHistogram, 1500, 1);
    histogram_tester.ExpectUniqueSample(kPostAmortizationTxHistogram, 300, 1);
    histogram_tester.ExpectUniqueSample(kPostAmortizationRxHistogram, 3000, 1);
    histogram_tester.ExpectUniqueSample(
        kAmortizationDelayHistogram,
        GetDelaySample(kTrafficStatsQueryDelay + kTrafficStatsQueryDelay / 2),
        1);
    histogram_tester.ExpectUniqueSample(kBufferSizeOnFlushHistogram, 2, 1);
    histogram_tester.ExpectUniqueSample(kConcurrentTabs, 1, 1);
  }
}

TEST_F(TrafficStatsAmortizerTest, AmortizeWithExtraBytes) {
  SkipFirstAmortizationRun();
  base::HistogramTester histogram_tester;

  // Byte counts should double.
  amortizer()->AmortizeDataUse(CreateDataUse(50, 500),
                               ExpectDataUseCallback(CreateDataUse(100, 1000)));
  amortizer()->OnExtraBytes(500, 5000);
  amortizer()->AddTrafficStats(1100, 11000);
  AdvanceTime(kTrafficStatsQueryDelay);
  EXPECT_EQ(1, data_use_callback_call_count());

  histogram_tester.ExpectUniqueSample(kPreAmortizationTxHistogram, 50, 1);
  histogram_tester.ExpectUniqueSample(kPreAmortizationRxHistogram, 500, 1);
  histogram_tester.ExpectUniqueSample(kPostAmortizationTxHistogram, 100, 1);
  histogram_tester.ExpectUniqueSample(kPostAmortizationRxHistogram, 1000, 1);
  histogram_tester.ExpectUniqueSample(
      kAmortizationDelayHistogram, GetDelaySample(kTrafficStatsQueryDelay), 1);
  histogram_tester.ExpectUniqueSample(kBufferSizeOnFlushHistogram, 1, 1);
  histogram_tester.ExpectUniqueSample(kConcurrentTabs, 1, 1);
}

TEST_F(TrafficStatsAmortizerTest, AmortizeWithNegativeOverhead) {
  SkipFirstAmortizationRun();
  base::HistogramTester histogram_tester;

  // Byte counts should halve.
  amortizer()->AmortizeDataUse(CreateDataUse(50, 500),
                               ExpectDataUseCallback(CreateDataUse(25, 250)));
  amortizer()->AddTrafficStats(25, 250);
  AdvanceTime(kTrafficStatsQueryDelay);
  EXPECT_EQ(1, data_use_callback_call_count());

  histogram_tester.ExpectUniqueSample(kPreAmortizationTxHistogram, 50, 1);
  histogram_tester.ExpectUniqueSample(kPreAmortizationRxHistogram, 500, 1);
  histogram_tester.ExpectUniqueSample(kPostAmortizationTxHistogram, 25, 1);
  histogram_tester.ExpectUniqueSample(kPostAmortizationRxHistogram, 250, 1);
  histogram_tester.ExpectUniqueSample(
      kAmortizationDelayHistogram, GetDelaySample(kTrafficStatsQueryDelay), 1);
  histogram_tester.ExpectUniqueSample(kBufferSizeOnFlushHistogram, 1, 1);
  histogram_tester.ExpectUniqueSample(kConcurrentTabs, 1, 1);
}

TEST_F(TrafficStatsAmortizerTest, AmortizeWithMaxIntByteCounts) {
  SkipFirstAmortizationRun();
  base::HistogramTester histogram_tester;

  // Byte counts should be unchanged.
  amortizer()->AmortizeDataUse(
      CreateDataUse(INT64_MAX, INT64_MAX),
      ExpectDataUseCallback(CreateDataUse(INT64_MAX, INT64_MAX)));
  amortizer()->SetNextTrafficStats(true, INT64_MAX, INT64_MAX);
  AdvanceTime(kTrafficStatsQueryDelay);
  EXPECT_EQ(1, data_use_callback_call_count());

  // Byte count samples should be capped at the maximum Sample value that's
  // valid to be recorded.
  histogram_tester.ExpectUniqueSample(kPreAmortizationTxHistogram,
                                      kMaxRecordableSample, 1);
  histogram_tester.ExpectUniqueSample(kPreAmortizationRxHistogram,
                                      kMaxRecordableSample, 1);
  histogram_tester.ExpectUniqueSample(kPostAmortizationTxHistogram,
                                      kMaxRecordableSample, 1);
  histogram_tester.ExpectUniqueSample(kPostAmortizationRxHistogram,
                                      kMaxRecordableSample, 1);
  histogram_tester.ExpectUniqueSample(
      kAmortizationDelayHistogram, GetDelaySample(kTrafficStatsQueryDelay), 1);
  histogram_tester.ExpectUniqueSample(kBufferSizeOnFlushHistogram, 1, 1);
  histogram_tester.ExpectUniqueSample(kConcurrentTabs, 1, 1);
}

TEST_F(TrafficStatsAmortizerTest, AmortizeWithMaxIntScaleFactor) {
  SkipFirstAmortizationRun();
  base::HistogramTester histogram_tester;

  // Byte counts should be scaled up to INT64_MAX.
  amortizer()->AmortizeDataUse(
      CreateDataUse(1, 1),
      ExpectDataUseCallback(CreateDataUse(INT64_MAX, INT64_MAX)));
  amortizer()->SetNextTrafficStats(true, INT64_MAX, INT64_MAX);
  AdvanceTime(kTrafficStatsQueryDelay);
  EXPECT_EQ(1, data_use_callback_call_count());

  // Post-amortization byte count samples should be capped at the maximum Sample
  // value that's valid to be recorded.
  histogram_tester.ExpectUniqueSample(kPreAmortizationTxHistogram, 1, 1);
  histogram_tester.ExpectUniqueSample(kPreAmortizationRxHistogram, 1, 1);
  histogram_tester.ExpectUniqueSample(kPostAmortizationTxHistogram,
                                      kMaxRecordableSample, 1);
  histogram_tester.ExpectUniqueSample(kPostAmortizationRxHistogram,
                                      kMaxRecordableSample, 1);
  histogram_tester.ExpectUniqueSample(
      kAmortizationDelayHistogram, GetDelaySample(kTrafficStatsQueryDelay), 1);
  histogram_tester.ExpectUniqueSample(kBufferSizeOnFlushHistogram, 1, 1);
  histogram_tester.ExpectUniqueSample(kConcurrentTabs, 1, 1);
}

TEST_F(TrafficStatsAmortizerTest, AmortizeWithZeroScaleFactor) {
  SkipFirstAmortizationRun();
  base::HistogramTester histogram_tester;

  // Byte counts should be scaled down to 0.
  amortizer()->AmortizeDataUse(CreateDataUse(INT64_MAX, INT64_MAX),
                               ExpectDataUseCallback(CreateDataUse(0, 0)));
  amortizer()->SetNextTrafficStats(true, 0, 0);
  AdvanceTime(kTrafficStatsQueryDelay);
  EXPECT_EQ(1, data_use_callback_call_count());

  // Pre-amortization byte count samples should be capped at the maximum Sample
  // value that's valid to be recorded.
  histogram_tester.ExpectUniqueSample(kPreAmortizationTxHistogram,
                                      kMaxRecordableSample, 1);
  histogram_tester.ExpectUniqueSample(kPreAmortizationRxHistogram,
                                      kMaxRecordableSample, 1);
  histogram_tester.ExpectUniqueSample(kPostAmortizationTxHistogram, 0, 1);
  histogram_tester.ExpectUniqueSample(kPostAmortizationRxHistogram, 0, 1);
  histogram_tester.ExpectUniqueSample(
      kAmortizationDelayHistogram, GetDelaySample(kTrafficStatsQueryDelay), 1);
  histogram_tester.ExpectUniqueSample(kBufferSizeOnFlushHistogram, 1, 1);
  histogram_tester.ExpectUniqueSample(kConcurrentTabs, 1, 1);
}

TEST_F(TrafficStatsAmortizerTest, AmortizeWithZeroPreAmortizationBytes) {
  SkipFirstAmortizationRun();

  {
    base::HistogramTester histogram_tester;

    // Both byte counts should stay 0, even though TrafficStats saw bytes, which
    // should be reflected in the next amortization run instead.
    amortizer()->AmortizeDataUse(CreateDataUse(0, 0),
                                 ExpectDataUseCallback(CreateDataUse(0, 0)));
    // Add the TrafficStats byte counts for this and the next amortization run.
    amortizer()->AddTrafficStats(100, 1000);
    AdvanceTime(kTrafficStatsQueryDelay);
    EXPECT_EQ(1, data_use_callback_call_count());

    histogram_tester.ExpectUniqueSample(kPreAmortizationTxHistogram, 0, 1);
    histogram_tester.ExpectUniqueSample(kPreAmortizationRxHistogram, 0, 1);
    histogram_tester.ExpectUniqueSample(kPostAmortizationTxHistogram, 0, 1);
    histogram_tester.ExpectUniqueSample(kPostAmortizationRxHistogram, 0, 1);
    histogram_tester.ExpectUniqueSample(kAmortizationDelayHistogram,
                                        GetDelaySample(kTrafficStatsQueryDelay),
                                        1);
    histogram_tester.ExpectUniqueSample(kBufferSizeOnFlushHistogram, 1, 1);
    histogram_tester.ExpectUniqueSample(kConcurrentTabs, 1, 1);
  }

  {
    base::HistogramTester histogram_tester;

    // Both byte counts should double, even though the TrafficStats byte counts
    // actually updated during the previous amortization run.
    amortizer()->AmortizeDataUse(
        CreateDataUse(50, 500),
        ExpectDataUseCallback(CreateDataUse(100, 1000)));
    AdvanceTime(kTrafficStatsQueryDelay);
    EXPECT_EQ(2, data_use_callback_call_count());

    histogram_tester.ExpectUniqueSample(kPreAmortizationTxHistogram, 50, 1);
    histogram_tester.ExpectUniqueSample(kPreAmortizationRxHistogram, 500, 1);
    histogram_tester.ExpectUniqueSample(kPostAmortizationTxHistogram, 100, 1);
    histogram_tester.ExpectUniqueSample(kPostAmortizationRxHistogram, 1000, 1);
    histogram_tester.ExpectUniqueSample(kAmortizationDelayHistogram,
                                        GetDelaySample(kTrafficStatsQueryDelay),
                                        1);
    histogram_tester.ExpectUniqueSample(kBufferSizeOnFlushHistogram, 1, 1);
    histogram_tester.ExpectUniqueSample(kConcurrentTabs, 1, 1);
  }
}

TEST_F(TrafficStatsAmortizerTest, AmortizeWithZeroTxPreAmortizationBytes) {
  SkipFirstAmortizationRun();

  {
    base::HistogramTester histogram_tester;

    // The count of transmitted bytes starts at 0, so it should stay 0, and be
    // amortized in the next amortization run instead.
    amortizer()->AmortizeDataUse(CreateDataUse(0, 500),
                                 ExpectDataUseCallback(CreateDataUse(0, 1000)));
    // Add the TrafficStats byte counts for this and the next amortization run.
    amortizer()->AddTrafficStats(100, 1000);
    AdvanceTime(kTrafficStatsQueryDelay);
    EXPECT_EQ(1, data_use_callback_call_count());

    histogram_tester.ExpectUniqueSample(kPreAmortizationTxHistogram, 0, 1);
    histogram_tester.ExpectUniqueSample(kPreAmortizationRxHistogram, 500, 1);
    histogram_tester.ExpectUniqueSample(kPostAmortizationTxHistogram, 0, 1);
    histogram_tester.ExpectUniqueSample(kPostAmortizationRxHistogram, 1000, 1);
    histogram_tester.ExpectUniqueSample(kAmortizationDelayHistogram,
                                        GetDelaySample(kTrafficStatsQueryDelay),
                                        1);
    histogram_tester.ExpectUniqueSample(kBufferSizeOnFlushHistogram, 1, 1);
    histogram_tester.ExpectUniqueSample(kConcurrentTabs, 1, 1);
  }

  {
    base::HistogramTester histogram_tester;

    // The count of transmitted bytes should double, even though they actually
    // updated during the previous amortization run.
    amortizer()->AmortizeDataUse(CreateDataUse(50, 0),
                                 ExpectDataUseCallback(CreateDataUse(100, 0)));
    AdvanceTime(kTrafficStatsQueryDelay);
    EXPECT_EQ(2, data_use_callback_call_count());

    histogram_tester.ExpectUniqueSample(kPreAmortizationTxHistogram, 50, 1);
    histogram_tester.ExpectUniqueSample(kPreAmortizationRxHistogram, 0, 1);
    histogram_tester.ExpectUniqueSample(kPostAmortizationTxHistogram, 100, 1);
    histogram_tester.ExpectUniqueSample(kPostAmortizationRxHistogram, 0, 1);
    histogram_tester.ExpectUniqueSample(kAmortizationDelayHistogram,
                                        GetDelaySample(kTrafficStatsQueryDelay),
                                        1);
    histogram_tester.ExpectUniqueSample(kBufferSizeOnFlushHistogram, 1, 1);
    histogram_tester.ExpectUniqueSample(kConcurrentTabs, 1, 1);
  }
}

TEST_F(TrafficStatsAmortizerTest, AmortizeWithZeroRxPreAmortizationBytes) {
  SkipFirstAmortizationRun();

  {
    base::HistogramTester histogram_tester;

    // The count of received bytes starts at 0, so it should stay 0, and be
    // amortized in the next amortization run instead.
    amortizer()->AmortizeDataUse(CreateDataUse(50, 0),
                                 ExpectDataUseCallback(CreateDataUse(100, 0)));
    // Add the TrafficStats byte counts for this and the next amortization run.
    amortizer()->AddTrafficStats(100, 1000);
    AdvanceTime(kTrafficStatsQueryDelay);
    EXPECT_EQ(1, data_use_callback_call_count());

    histogram_tester.ExpectUniqueSample(kPreAmortizationTxHistogram, 50, 1);
    histogram_tester.ExpectUniqueSample(kPreAmortizationRxHistogram, 0, 1);
    histogram_tester.ExpectUniqueSample(kPostAmortizationTxHistogram, 100, 1);
    histogram_tester.ExpectUniqueSample(kPostAmortizationRxHistogram, 0, 1);
    histogram_tester.ExpectUniqueSample(kAmortizationDelayHistogram,
                                        GetDelaySample(kTrafficStatsQueryDelay),
                                        1);
    histogram_tester.ExpectUniqueSample(kBufferSizeOnFlushHistogram, 1, 1);
    histogram_tester.ExpectUniqueSample(kConcurrentTabs, 1, 1);
  }

  {
    base::HistogramTester histogram_tester;

    // The count of received bytes should double, even though they actually
    // updated during the previous amortization run.
    amortizer()->AmortizeDataUse(CreateDataUse(0, 500),
                                 ExpectDataUseCallback(CreateDataUse(0, 1000)));
    AdvanceTime(kTrafficStatsQueryDelay);
    EXPECT_EQ(2, data_use_callback_call_count());

    histogram_tester.ExpectUniqueSample(kPreAmortizationTxHistogram, 0, 1);
    histogram_tester.ExpectUniqueSample(kPreAmortizationRxHistogram, 500, 1);
    histogram_tester.ExpectUniqueSample(kPostAmortizationTxHistogram, 0, 1);
    histogram_tester.ExpectUniqueSample(kPostAmortizationRxHistogram, 1000, 1);
    histogram_tester.ExpectUniqueSample(kAmortizationDelayHistogram,
                                        GetDelaySample(kTrafficStatsQueryDelay),
                                        1);
    histogram_tester.ExpectUniqueSample(kBufferSizeOnFlushHistogram, 1, 1);
    histogram_tester.ExpectUniqueSample(kConcurrentTabs, 1, 1);
  }
}

TEST_F(TrafficStatsAmortizerTest, AmortizeAtMaxDelay) {
  SkipFirstAmortizationRun();
  base::HistogramTester histogram_tester;

  // Byte counts should double.
  amortizer()->AddTrafficStats(1000, 10000);
  amortizer()->AmortizeDataUse(CreateDataUse(50, 500),
                               ExpectDataUseCallback(CreateDataUse(100, 1000)));

  // kSmallDelay is a delay that's shorter than the delay before TrafficStats
  // would be queried, where kMaxAmortizationDelay is a multiple of kSmallDelay.
  const base::TimeDelta kSmallDelay = kMaxAmortizationDelay / 10;
  EXPECT_LT(kSmallDelay, kTrafficStatsQueryDelay);

  // Simulate multiple cases of extra bytes being reported, each before
  // TrafficStats would be queried, until kMaxAmortizationDelay has elapsed.
  AdvanceTime(kSmallDelay);
  for (int64_t i = 0; i < kMaxAmortizationDelay / kSmallDelay - 1; ++i) {
    EXPECT_EQ(0, data_use_callback_call_count());
    amortizer()->OnExtraBytes(50, 500);
    AdvanceTime(kSmallDelay);
  }

  // The final time, the amortizer should have given up on waiting to query
  // TrafficStats and just have amortized as soon as it hit the deadline of
  // kMaxAmortizationDelay.
  EXPECT_EQ(1, data_use_callback_call_count());

  histogram_tester.ExpectUniqueSample(kPreAmortizationTxHistogram, 50, 1);
  histogram_tester.ExpectUniqueSample(kPreAmortizationRxHistogram, 500, 1);
  histogram_tester.ExpectUniqueSample(kPostAmortizationTxHistogram, 100, 1);
  histogram_tester.ExpectUniqueSample(kPostAmortizationRxHistogram, 1000, 1);
  histogram_tester.ExpectUniqueSample(kAmortizationDelayHistogram,
                                      GetDelaySample(kMaxAmortizationDelay), 1);
  histogram_tester.ExpectUniqueSample(kBufferSizeOnFlushHistogram, 1, 1);
  histogram_tester.ExpectUniqueSample(kConcurrentTabs, 1, 1);
}

TEST_F(TrafficStatsAmortizerTest, AmortizeAtMaxBufferSize) {
  SkipFirstAmortizationRun();
  base::HistogramTester histogram_tester;

  // Report (max buffer size + 1) consecutive DataUse objects, which will be
  // amortized immediately once the buffer exceeds maximum size.
  amortizer()->AddTrafficStats(100 * (kMaxDataUseBufferSize + 1),
                               1000 * (kMaxDataUseBufferSize + 1));
  for (size_t i = 0; i < kMaxDataUseBufferSize + 1; ++i) {
    EXPECT_EQ(0, data_use_callback_call_count());
    amortizer()->AmortizeDataUse(
        CreateDataUse(50, 500),
        ExpectDataUseCallback(CreateDataUse(100, 1000)));
  }

  const int kExpectedBufSize = static_cast<int>(kMaxDataUseBufferSize + 1);
  EXPECT_EQ(kExpectedBufSize, data_use_callback_call_count());

  histogram_tester.ExpectUniqueSample(kPreAmortizationTxHistogram,
                                      50 * kExpectedBufSize, 1);
  histogram_tester.ExpectUniqueSample(kPreAmortizationRxHistogram,
                                      500 * kExpectedBufSize, 1);
  histogram_tester.ExpectUniqueSample(kPostAmortizationTxHistogram,
                                      100 * kExpectedBufSize, 1);
  histogram_tester.ExpectUniqueSample(kPostAmortizationRxHistogram,
                                      1000 * kExpectedBufSize, 1);
  histogram_tester.ExpectUniqueSample(kAmortizationDelayHistogram, 0, 1);
  histogram_tester.ExpectUniqueSample(kBufferSizeOnFlushHistogram,
                                      kExpectedBufSize, 1);
  histogram_tester.ExpectUniqueSample(kConcurrentTabs, 1, 1);
}

TEST_F(TrafficStatsAmortizerTest, AmortizeCombinedDataUse) {
  SkipFirstAmortizationRun();
  base::HistogramTester histogram_tester;

  const GURL foo_url("http://foo.com");
  const GURL bar_url("http://bar.com");

  std::vector<std::unique_ptr<DataUse>> baz_sequence;
  const DataUseAmortizer::AmortizationCompleteCallback baz_callback =
      base::Bind(&AppendDataUseToSequence, &baz_sequence);

  std::vector<std::unique_ptr<DataUse>> qux_sequence;
  const DataUseAmortizer::AmortizationCompleteCallback qux_callback =
      base::Bind(&AppendDataUseToSequence, &qux_sequence);

  // Byte counts should double, with some DataUse objects combined together.

  // Two consecutive DataUse objects that are identical except for byte counts
  // and with the same callback should be combined.
  amortizer()->AmortizeDataUse(CreateDataUseWithURL(foo_url, 50, 500),
                               baz_callback);
  amortizer()->AmortizeDataUse(CreateDataUseWithURL(foo_url, 100, 1000),
                               baz_callback);

  // This DataUse object should not be combined with the previous one because it
  // has a different URL.
  amortizer()->AmortizeDataUse(CreateDataUseWithURL(bar_url, 50, 500),
                               baz_callback);

  // This DataUse object should not be combined with the previous one because it
  // has a different callback.
  amortizer()->AmortizeDataUse(CreateDataUseWithURL(bar_url, 50, 500),
                               qux_callback);

  // This DataUse object should not be combined with the previous foo/baz
  // DataUse objects because other DataUse objects were reported in-between.
  amortizer()->AmortizeDataUse(CreateDataUseWithURL(foo_url, 50, 500),
                               baz_callback);

  // Simulate that TrafficStats saw double the number of reported bytes across
  // all reported DataUse.
  amortizer()->AddTrafficStats(600, 6000);
  AdvanceTime(kTrafficStatsQueryDelay);

  EXPECT_EQ(3U, baz_sequence.size());
  ExpectDataUse(CreateDataUseWithURL(foo_url, 300, 3000),
                std::move(baz_sequence[0]));
  ExpectDataUse(CreateDataUseWithURL(bar_url, 100, 1000),
                std::move(baz_sequence[1]));
  ExpectDataUse(CreateDataUseWithURL(foo_url, 100, 1000),
                std::move(baz_sequence[2]));

  EXPECT_EQ(1U, qux_sequence.size());
  ExpectDataUse(CreateDataUseWithURL(bar_url, 100, 1000),
                std::move(qux_sequence[0]));

  histogram_tester.ExpectUniqueSample(kPreAmortizationTxHistogram, 300, 1);
  histogram_tester.ExpectUniqueSample(kPreAmortizationRxHistogram, 3000, 1);
  histogram_tester.ExpectUniqueSample(kPostAmortizationTxHistogram, 600, 1);
  histogram_tester.ExpectUniqueSample(kPostAmortizationRxHistogram, 6000, 1);
  histogram_tester.ExpectUniqueSample(
      kAmortizationDelayHistogram, GetDelaySample(kTrafficStatsQueryDelay), 1);
  histogram_tester.ExpectUniqueSample(kBufferSizeOnFlushHistogram, 4, 1);
  histogram_tester.ExpectUniqueSample(kConcurrentTabs, 1, 1);
}

TEST_F(TrafficStatsAmortizerTest, ConcurrentTabsHistogram) {
  SkipFirstAmortizationRun();

  {
    // Test data usage reported multiple times for two tabs.
    base::HistogramTester histogram_tester;
    amortizer()->SetNextTrafficStats(true, 0, 0);
    amortizer()->AmortizeDataUse(
        CreateDataUseWithTab(1, 50, 500),
        ExpectDataUseCallback(CreateDataUseWithTab(1, 100, 1000)));
    amortizer()->AmortizeDataUse(
        CreateDataUseWithTab(2, 100, 1000),
        ExpectDataUseCallback(CreateDataUseWithTab(2, 200, 2000)));
    amortizer()->AmortizeDataUse(
        CreateDataUseWithTab(1, 50, 500),
        ExpectDataUseCallback(CreateDataUseWithTab(1, 100, 1000)));
    amortizer()->AmortizeDataUse(
        CreateDataUseWithTab(2, 100, 1000),
        ExpectDataUseCallback(CreateDataUseWithTab(2, 200, 2000)));
    amortizer()->SetNextTrafficStats(true, 600, 6000);
    AdvanceTime(kTrafficStatsQueryDelay);
    histogram_tester.ExpectUniqueSample(kConcurrentTabs, 2, 1);
    histogram_tester.ExpectUniqueSample(kPreAmortizationTxHistogram, 300, 1);
    histogram_tester.ExpectUniqueSample(kPreAmortizationRxHistogram, 3000, 1);
    histogram_tester.ExpectUniqueSample(kPostAmortizationTxHistogram, 600, 1);
    histogram_tester.ExpectUniqueSample(kPostAmortizationRxHistogram, 6000, 1);
  }

  // Test data usage for 1-5 tabs.
  for (int32_t total_tabs = 1; total_tabs <= 5; ++total_tabs) {
    base::HistogramTester histogram_tester;

    for (int32_t i = 1; i <= total_tabs; ++i) {
      amortizer()->AmortizeDataUse(
          CreateDataUseWithTab(i, 100, 1000),
          ExpectDataUseCallback(CreateDataUseWithTab(i, 200, 2000)));
    }
    amortizer()->AddTrafficStats(total_tabs * 200, total_tabs * 2000);
    AdvanceTime(kTrafficStatsQueryDelay);
    histogram_tester.ExpectUniqueSample(kConcurrentTabs, total_tabs, 1);
  }
}

}  // namespace

}  // namespace android
}  // namespace data_usage