File: legacymetrics_client_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,122,156 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (710 lines) | stat: -rw-r--r-- 24,184 bytes parent folder | download | duplicates (7)
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
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <fuchsia/legacymetrics/cpp/fidl.h>
#include <fuchsia/legacymetrics/cpp/fidl_test_base.h>
#include <cmath>
#include <string>
#include <utility>

#include "base/fuchsia/scoped_service_binding.h"
#include "base/fuchsia/test_component_context_for_process.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/metrics/histogram_macros.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/bind.h"
#include "base/test/task_environment.h"
#include "base/test/test_future.h"
#include "base/time/time.h"
#include "components/fuchsia_legacymetrics/legacymetrics_client.h"
#include "components/fuchsia_legacymetrics/legacymetrics_histogram_flattener.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace fuchsia_legacymetrics {
namespace {

using ::testing::Property;
using ::testing::UnorderedElementsAreArray;

constexpr base::TimeDelta kReportInterval = base::Minutes(1);
constexpr base::TimeDelta kShortDuration = base::Seconds(1);

class TestMetricsRecorder
    : public fuchsia::legacymetrics::testing::MetricsRecorder_TestBase {
 public:
  TestMetricsRecorder() = default;
  ~TestMetricsRecorder() override = default;

  bool IsRecordInFlight() const { return ack_callback_.has_value(); }

  bool IsEmpty() const { return recorded_events_.empty(); }

  std::vector<fuchsia::legacymetrics::Event> WaitForEvents() {
    if (recorded_events_.empty()) {
      base::RunLoop run_loop;
      on_record_cb_ = run_loop.QuitClosure();
      run_loop.Run();
    }
    return std::move(recorded_events_);
  }

  void DropAck() { ack_callback_ = std::nullopt; }

  void SendAck() {
    (*ack_callback_)();
    ack_callback_ = std::nullopt;
  }

  void set_expect_ack_dropped(bool expect_dropped) {
    expect_ack_dropped_ = expect_dropped;
  }

  // fuchsia::legacymetrics::MetricsRecorder implementation.
  void Record(std::vector<fuchsia::legacymetrics::Event> events,
              RecordCallback callback) override {
    std::move(events.begin(), events.end(),
              std::back_inserter(recorded_events_));

    // Received a call to Record() before the previous one was acknowledged,
    // which can happen in some cases (e.g. flushing).
    if (ack_callback_)
      EXPECT_TRUE(expect_ack_dropped_);

    ack_callback_ = std::move(callback);

    if (on_record_cb_)
      std::move(on_record_cb_).Run();
  }

  void NotImplemented_(const std::string& name) override { FAIL() << name; }

 private:
  std::vector<fuchsia::legacymetrics::Event> recorded_events_;
  base::OnceClosure on_record_cb_;
  std::optional<RecordCallback> ack_callback_;
  bool expect_ack_dropped_ = false;
};

class LegacyMetricsClientTest : public testing::Test {
 public:
  LegacyMetricsClientTest()
      : task_environment_(base::test::TaskEnvironment::TimeSource::MOCK_TIME,
                          base::test::TaskEnvironment::MainThreadType::IO) {}
  ~LegacyMetricsClientTest() override = default;

  void SetUp() override {
    service_binding_ = MakeServiceBinding();
    base::SetRecordActionTaskRunner(
        base::SingleThreadTaskRunner::GetCurrentDefault());

    // Flush any dirty histograms from previous test runs in this process.
    GetLegacyMetricsDeltas();
  }

  std::unique_ptr<base::ScopedSingleClientServiceBinding<
      fuchsia::legacymetrics::MetricsRecorder>>
  MakeServiceBinding() {
    return std::make_unique<base::ScopedSingleClientServiceBinding<
        fuchsia::legacymetrics::MetricsRecorder>>(
        test_context_.additional_services(), &test_recorder_);
  }

  void StartClientAndExpectConnection() {
    client_.Start(kReportInterval);
    base::RunLoop().RunUntilIdle();
    EXPECT_TRUE(service_binding_->has_clients());
  }

  // Disconnects the service side of the metrics FIDL channel and replaces the
  // binding with a new instance.
  void DisconnectAndRestartMetricsService() {
    service_binding_.reset();
    service_binding_ = MakeServiceBinding();
    base::RunLoop().RunUntilIdle();
  }

  void ExpectReconnectAfterDelay(const base::TimeDelta& delay) {
    // Just before the expected delay, the client shouldn't reconnect yet.
    task_environment_.FastForwardBy(delay - kShortDuration);
    EXPECT_FALSE(service_binding_->has_clients())
        << "Expected delay: " << delay;

    // Complete the full expected reconnect delay. Client should reconnect.
    task_environment_.FastForwardBy(kShortDuration);
    EXPECT_TRUE(service_binding_->has_clients()) << "Expected delay: " << delay;
  }

  void SetMetricsRecorder() {
    fidl::InterfaceHandle<fuchsia::legacymetrics::MetricsRecorder>
        metrics_recorder;
    direct_binding_.Bind(metrics_recorder.NewRequest());
    client_.SetMetricsRecorder(std::move(metrics_recorder));
  }

 protected:
  base::test::TaskEnvironment task_environment_;
  base::TestComponentContextForProcess test_context_;
  TestMetricsRecorder test_recorder_;
  std::unique_ptr<base::ScopedSingleClientServiceBinding<
      fuchsia::legacymetrics::MetricsRecorder>>
      service_binding_;
  fidl::Binding<fuchsia::legacymetrics::MetricsRecorder> direct_binding_{
      &test_recorder_};

  LegacyMetricsClient client_;
};

TEST_F(LegacyMetricsClientTest, ReportIntervalBoundary) {
  client_.Start(kReportInterval);

  task_environment_.FastForwardBy(kReportInterval - base::Seconds(1));
  EXPECT_FALSE(test_recorder_.IsRecordInFlight());
  UMA_HISTOGRAM_COUNTS_1M("foo", 20);
  task_environment_.FastForwardBy(base::Seconds(1));
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());
}

void PopulateAdditionalEvents(
    base::OnceCallback<void(std::vector<fuchsia::legacymetrics::Event>)>
        callback) {
  fuchsia::legacymetrics::ImplementationDefinedEvent impl_event;
  impl_event.set_name("baz");

  fuchsia::legacymetrics::Event event;
  event.set_impl_defined_event(std::move(impl_event));

  std::vector<fuchsia::legacymetrics::Event> events;
  events.push_back(std::move(event));
  std::move(callback).Run(std::move(events));
}

TEST_F(LegacyMetricsClientTest, AllTypes) {
  client_.SetReportAdditionalMetricsCallback(
      base::BindRepeating(&PopulateAdditionalEvents));
  client_.Start(kReportInterval);

  UMA_HISTOGRAM_COUNTS_1M("foo", 20);
  base::RecordComputedAction("bar");

  task_environment_.FastForwardBy(kReportInterval);
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());

  auto events = test_recorder_.WaitForEvents();
  EXPECT_EQ(3u, events.size());
  EXPECT_EQ("baz", events[0].impl_defined_event().name());
  EXPECT_EQ("foo", events[1].histogram().name());
  EXPECT_EQ("bar", events[2].user_action_event().name());
}

TEST_F(LegacyMetricsClientTest, DisconnectWhileCollectingAdditionalEvents) {
  // Hold the completion callback for later execution.
  base::OnceCallback<void(std::vector<fuchsia::legacymetrics::Event>)>
      on_report_done;
  client_.SetReportAdditionalMetricsCallback(base::BindRepeating(
      [](base::OnceCallback<void(std::vector<fuchsia::legacymetrics::Event>)>*
             stored_on_report_done,
         base::OnceCallback<void(std::vector<fuchsia::legacymetrics::Event>)>
             on_report_done) {
        *stored_on_report_done = std::move(on_report_done);
      },
      base::Unretained(&on_report_done)));

  client_.Start(kReportInterval);

  task_environment_.FastForwardBy(kReportInterval);

  // Disconnect the service.
  service_binding_.reset();
  base::RunLoop().RunUntilIdle();

  // Fulfill the report additional metrics callback.
  std::move(on_report_done).Run({});
}

TEST_F(LegacyMetricsClientTest, ReportSkippedNoEvents) {
  client_.Start(kReportInterval);

  // Verify that Record() is not invoked if there is no data to report.
  task_environment_.FastForwardBy(kReportInterval);
  EXPECT_FALSE(test_recorder_.IsRecordInFlight());

  // Add some events and allow the interval to lapse. Verify that the data is
  // reported.
  UMA_HISTOGRAM_COUNTS_1M("foo", 20);
  task_environment_.FastForwardBy(kReportInterval);
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());
  test_recorder_.SendAck();

  // Verify that Record() is skipped again for no-data.
  task_environment_.FastForwardBy(kReportInterval);
  EXPECT_FALSE(test_recorder_.IsRecordInFlight());
}

TEST_F(LegacyMetricsClientTest, MultipleReports) {
  client_.Start(kReportInterval);

  UMA_HISTOGRAM_COUNTS_1M("foo", 20);
  task_environment_.FastForwardBy(kReportInterval);
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());
  test_recorder_.SendAck();
  EXPECT_FALSE(test_recorder_.IsRecordInFlight());

  UMA_HISTOGRAM_COUNTS_1M("foo", 20);
  task_environment_.FastForwardBy(kReportInterval);
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());
  test_recorder_.SendAck();
}

TEST_F(LegacyMetricsClientTest, NoReportIfNeverAcked) {
  client_.Start(kReportInterval);

  UMA_HISTOGRAM_COUNTS_1M("foo", 20);
  task_environment_.FastForwardBy(kReportInterval);
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());
  test_recorder_.DropAck();
  EXPECT_FALSE(test_recorder_.IsRecordInFlight());

  UMA_HISTOGRAM_COUNTS_1M("foo", 20);
  task_environment_.FastForwardBy(kReportInterval);
  EXPECT_FALSE(test_recorder_.IsRecordInFlight());
}

TEST_F(LegacyMetricsClientTest, ReconnectAfterServiceDisconnect) {
  StartClientAndExpectConnection();
  DisconnectAndRestartMetricsService();
  EXPECT_FALSE(service_binding_->has_clients());
  task_environment_.FastForwardBy(LegacyMetricsClient::kInitialReconnectDelay);
  EXPECT_TRUE(service_binding_->has_clients());

  base::RecordComputedAction("foo");
  task_environment_.FastForwardBy(kReportInterval);
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());
  test_recorder_.SendAck();
  EXPECT_FALSE(test_recorder_.IsRecordInFlight());
}

TEST_F(LegacyMetricsClientTest, ServiceDisconnectWhileRecordPending) {
  StartClientAndExpectConnection();

  base::RecordComputedAction("foo");
  task_environment_.FastForwardBy(kReportInterval);
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());

  DisconnectAndRestartMetricsService();
  EXPECT_FALSE(service_binding_->has_clients());
  test_recorder_.DropAck();

  task_environment_.FastForwardBy(LegacyMetricsClient::kInitialReconnectDelay);
  EXPECT_TRUE(service_binding_->has_clients());

  base::RecordComputedAction("foo");
  task_environment_.FastForwardBy(kReportInterval);
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());
}

TEST_F(LegacyMetricsClientTest, ServiceDisconnectWhileFlushing) {
  StartClientAndExpectConnection();

  base::RecordComputedAction("foo");
  client_.FlushAndDisconnect(base::OnceClosure());
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());

  DisconnectAndRestartMetricsService();
  test_recorder_.DropAck();
  EXPECT_FALSE(service_binding_->has_clients());

  task_environment_.FastForwardBy(LegacyMetricsClient::kInitialReconnectDelay);
  EXPECT_TRUE(service_binding_->has_clients());

  base::RecordComputedAction("foo");
  task_environment_.FastForwardBy(kReportInterval);
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());
}

TEST_F(LegacyMetricsClientTest,
       ReconnectConsecutivelyWithoutRecordBacksOffExponentially) {
  StartClientAndExpectConnection();

  for (base::TimeDelta expected_delay =
           LegacyMetricsClient::kInitialReconnectDelay;
       expected_delay <= LegacyMetricsClient::kMaxReconnectDelay;
       expected_delay *= LegacyMetricsClient::kReconnectBackoffFactor) {
    DisconnectAndRestartMetricsService();
    ExpectReconnectAfterDelay(expected_delay);
  }
}

// The test is flaky.
// TODO: crbug.com/326659366 - Reenable the test.
TEST_F(LegacyMetricsClientTest, DISABLED_ReconnectDelayNeverExceedsMax) {
  StartClientAndExpectConnection();

  // Find the theoretical maximum number of consecutive failed connections. Also
  // add a few extra iterations to ensure that we never exceed the max delay.
  const size_t num_iterations =
      3 + log(LegacyMetricsClient::kMaxReconnectDelay /
              LegacyMetricsClient::kInitialReconnectDelay) /
              log(LegacyMetricsClient::kReconnectBackoffFactor);

  // As a heuristic, starting with 1 second and a factor of 2 reaches 24 hours
  // in about 17 iterations. So the expected number of iterations needed to
  // reach the maximum delay should be less than about 20.
  EXPECT_LE(num_iterations, 20u);

  for (size_t i = 0; i < num_iterations; i++) {
    DisconnectAndRestartMetricsService();
    EXPECT_FALSE(service_binding_->has_clients()) << "Iteration " << i;
    task_environment_.FastForwardBy(LegacyMetricsClient::kMaxReconnectDelay);
    EXPECT_TRUE(service_binding_->has_clients()) << "Iteration " << i;
  }
}

TEST_F(LegacyMetricsClientTest, RecordCompletionResetsReconnectDelay) {
  StartClientAndExpectConnection();

  // First reconnect has initial delay.
  DisconnectAndRestartMetricsService();
  ExpectReconnectAfterDelay(LegacyMetricsClient::kInitialReconnectDelay);

  // Another reconnect without a successful Record() call increases the delay.
  DisconnectAndRestartMetricsService();
  ExpectReconnectAfterDelay(LegacyMetricsClient::kInitialReconnectDelay *
                            LegacyMetricsClient::kReconnectBackoffFactor);

  // Record and report an event, invoking a FIDL Record().
  base::RecordComputedAction("ArbitraryEvent");
  task_environment_.FastForwardBy(kReportInterval);
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());
  test_recorder_.SendAck();
  base::RunLoop().RunUntilIdle();

  // Reconnect after a successful Record() uses the initial delay again.
  DisconnectAndRestartMetricsService();
  ExpectReconnectAfterDelay(LegacyMetricsClient::kInitialReconnectDelay);
}

TEST_F(LegacyMetricsClientTest, ContinueRecordingUserActionsAfterDisconnect) {
  StartClientAndExpectConnection();

  base::RecordComputedAction("BeforeDisconnect");
  DisconnectAndRestartMetricsService();
  base::RecordComputedAction("DuringDisconnect");
  ExpectReconnectAfterDelay(LegacyMetricsClient::kInitialReconnectDelay);
  base::RecordComputedAction("AfterReconnect");

  // Fast forward to report metrics.
  task_environment_.FastForwardBy(kReportInterval);
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());

  auto events = test_recorder_.WaitForEvents();
  EXPECT_THAT(
      events,
      UnorderedElementsAreArray({
          Property(&fuchsia::legacymetrics::Event::user_action_event,
                   Property(&fuchsia::legacymetrics::UserActionEvent::name,
                            "BeforeDisconnect")),
          Property(&fuchsia::legacymetrics::Event::user_action_event,
                   Property(&fuchsia::legacymetrics::UserActionEvent::name,
                            "DuringDisconnect")),
          Property(&fuchsia::legacymetrics::Event::user_action_event,
                   Property(&fuchsia::legacymetrics::UserActionEvent::name,
                            "AfterReconnect")),
      }));
}

TEST_F(LegacyMetricsClientTest, Batching) {
  client_.Start(kReportInterval);

  // Log enough actions that the list will be split across multiple batches.
  // Batches are read out in reverse order, so even though it is being logged
  // first, it will be emitted in the final batch.
  base::RecordComputedAction("batch2");

  for (size_t i = 0; i < LegacyMetricsClient::kMaxBatchSize; ++i)
    base::RecordComputedAction("batch1");

  task_environment_.FastForwardBy(kReportInterval);
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());

  // First batch.
  auto events = test_recorder_.WaitForEvents();
  EXPECT_EQ(LegacyMetricsClient::kMaxBatchSize, events.size());
  for (const auto& event : events)
    EXPECT_EQ(event.user_action_event().name(), "batch1");
  test_recorder_.SendAck();

  // Second batch (remainder).
  events = test_recorder_.WaitForEvents();
  EXPECT_EQ(1u, events.size());
  for (const auto& event : events)
    EXPECT_EQ(event.user_action_event().name(), "batch2");
  test_recorder_.SendAck();
}

TEST_F(LegacyMetricsClientTest, FlushWithPending) {
  client_.Start(kReportInterval);
  base::RunLoop().RunUntilIdle();

  UMA_HISTOGRAM_COUNTS_1M("foo", 20);

  EXPECT_FALSE(test_recorder_.IsRecordInFlight());
  service_binding_->events().OnCloseSoon();
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());

  // The service should be unbound once all data is drained.
  EXPECT_TRUE(service_binding_->has_clients());
  auto events = test_recorder_.WaitForEvents();
  test_recorder_.SendAck();
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(1u, events.size());
  EXPECT_EQ("foo", events[0].histogram().name());
  EXPECT_FALSE(service_binding_->has_clients());
}

TEST_F(LegacyMetricsClientTest, FlushNoData) {
  client_.Start(kReportInterval);
  base::RunLoop().RunUntilIdle();

  EXPECT_TRUE(service_binding_->has_clients());
  EXPECT_FALSE(test_recorder_.IsRecordInFlight());
  service_binding_->events().OnCloseSoon();
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(service_binding_->has_clients());
}

TEST_F(LegacyMetricsClientTest, FlushWithOutstandingAck) {
  client_.Start(kReportInterval);
  base::RunLoop().RunUntilIdle();

  // Send "foo", but don't ack.
  UMA_HISTOGRAM_COUNTS_1M("foo", 20);
  task_environment_.FastForwardBy(kReportInterval);
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());

  // Allow the flush operation to call Record() without waiting for a prior ack.
  test_recorder_.set_expect_ack_dropped(true);

  // Buffer another event and trigger a flush.
  UMA_HISTOGRAM_COUNTS_1M("bar", 20);
  EXPECT_TRUE(service_binding_->has_clients());
  service_binding_->events().OnCloseSoon();

  // Simulate an asynchronous ack from the recorder, which be delivered around
  // the same time as the flush's Record() call. The ack should be gracefully
  // ignored by the client.
  test_recorder_.SendAck();

  base::RunLoop().RunUntilIdle();

  auto events = test_recorder_.WaitForEvents();
  test_recorder_.SendAck();
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(2u, events.size());
  EXPECT_EQ("foo", events[0].histogram().name());
  EXPECT_EQ("bar", events[1].histogram().name());
  EXPECT_FALSE(service_binding_->has_clients());
}

TEST_F(LegacyMetricsClientTest, ExternalFlushSignal) {
  base::test::TestFuture<base::OnceClosure> flush_receiver;
  client_.SetNotifyFlushCallback(flush_receiver.GetCallback());
  client_.Start(kReportInterval);
  base::RunLoop().RunUntilIdle();

  UMA_HISTOGRAM_COUNTS_1M("foo", 20);

  // Verify that reporting does not start until the flush completion callback is
  // run.
  EXPECT_FALSE(test_recorder_.IsRecordInFlight());
  service_binding_->events().OnCloseSoon();
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(test_recorder_.IsRecordInFlight());

  // Verify that invoking the completion callback unblocks reporting.
  EXPECT_TRUE(flush_receiver.IsReady());
  flush_receiver.Take().Run();
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());
}

TEST_F(LegacyMetricsClientTest, ExplicitFlush) {
  client_.Start(kReportInterval);

  base::RecordComputedAction("bar");
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(test_recorder_.IsRecordInFlight());

  bool called = false;
  client_.FlushAndDisconnect(
      base::BindLambdaForTesting([&called] { called = true; }));
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());
  EXPECT_FALSE(called);

  auto events = test_recorder_.WaitForEvents();
  EXPECT_EQ(1u, events.size());
  EXPECT_EQ("bar", events[0].user_action_event().name());

  test_recorder_.SendAck();
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(called);
}

TEST_F(LegacyMetricsClientTest, DoubleFlush) {
  client_.Start(kReportInterval);

  base::RecordComputedAction("bar");
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(test_recorder_.IsRecordInFlight());

  bool called = false;
  client_.FlushAndDisconnect(
      base::BindLambdaForTesting([&called] { called = true; }));
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());
  EXPECT_FALSE(called);

  bool called2 = false;
  client_.FlushAndDisconnect(
      base::BindLambdaForTesting([&called2] { called2 = true; }));

  test_recorder_.WaitForEvents();
  test_recorder_.SendAck();
  base::RunLoop().RunUntilIdle();

  // Verify that both FlushAndDisconnect() callbacks were called.
  EXPECT_TRUE(called);
  EXPECT_TRUE(called2);
}

TEST_F(LegacyMetricsClientTest, ExplicitFlushMultipleBatches) {
  const size_t kSizeForMultipleBatches = LegacyMetricsClient::kMaxBatchSize * 2;
  client_.Start(kReportInterval);

  for (size_t i = 0; i < kSizeForMultipleBatches; ++i)
    base::RecordComputedAction("bar");

  client_.FlushAndDisconnect(base::DoNothing());
  base::RunLoop().RunUntilIdle();
  test_recorder_.SendAck();
  base::RunLoop().RunUntilIdle();

  auto events = test_recorder_.WaitForEvents();
  EXPECT_EQ(kSizeForMultipleBatches, events.size());
  for (size_t i = 0; i < kSizeForMultipleBatches; ++i)
    EXPECT_EQ("bar", events[i].user_action_event().name());
}

TEST_F(LegacyMetricsClientTest, UseInjectedMetricsRecorder) {
  client_.DisableAutoConnect();
  SetMetricsRecorder();

  client_.Start(kReportInterval);

  base::RecordComputedAction("bar");

  task_environment_.FastForwardBy(kReportInterval);
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());

  auto events = test_recorder_.WaitForEvents();
  EXPECT_EQ(1u, events.size());
  EXPECT_EQ("bar", events[0].user_action_event().name());

  // Verify that /svc wasn't used.
  EXPECT_FALSE(service_binding_->has_clients());

  // Verify that LegacyMetricsClient doesn't try to reconnect after
  // MetricsRecorder has been disconnected.
  direct_binding_.Unbind();
  task_environment_.FastForwardBy(LegacyMetricsClient::kInitialReconnectDelay *
                                  2);
  EXPECT_FALSE(service_binding_->has_clients());
}

TEST_F(LegacyMetricsClientTest, UseInjectedMetricsRecorderReconnect) {
  client_.DisableAutoConnect();
  SetMetricsRecorder();

  client_.Start(kReportInterval);

  bool flush_complete = false;
  client_.FlushAndDisconnect(
      base::BindLambdaForTesting([&flush_complete] { flush_complete = true; }));
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(flush_complete);

  EXPECT_TRUE(test_recorder_.IsEmpty());

  // Set recorder again and verify that it receives metrics now.
  SetMetricsRecorder();

  base::RecordComputedAction("bar");

  task_environment_.FastForwardBy(kReportInterval);
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());

  auto events = test_recorder_.WaitForEvents();
  EXPECT_EQ(1u, events.size());
}

TEST_F(LegacyMetricsClientTest, SetMetricsRecorderDuringRecord) {
  client_.DisableAutoConnect();
  SetMetricsRecorder();

  client_.Start(kReportInterval);

  base::RecordComputedAction("bar");

  task_environment_.FastForwardBy(kReportInterval);
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());
  test_recorder_.DropAck();

  // Set recorder again and verify that it can receive metrics.
  SetMetricsRecorder();

  base::RecordComputedAction("bar");

  task_environment_.FastForwardBy(kReportInterval);
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());

  auto events = test_recorder_.WaitForEvents();
  EXPECT_EQ(2u, events.size());
}

TEST_F(LegacyMetricsClientTest, SetMetricsRecorderDuringFlush) {
  client_.DisableAutoConnect();
  SetMetricsRecorder();

  client_.Start(kReportInterval);

  base::RecordComputedAction("bar");

  bool flush_complete = false;
  client_.FlushAndDisconnect(
      base::BindLambdaForTesting([&flush_complete] { flush_complete = true; }));
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());
  test_recorder_.DropAck();
  EXPECT_FALSE(flush_complete);

  // Set recorder again. It's expected to complete the Flush().
  SetMetricsRecorder();
  EXPECT_TRUE(flush_complete);

  // Verify that metrics are sent to the new MetricsRecorder instance.
  base::RecordComputedAction("bar");

  task_environment_.FastForwardBy(kReportInterval);
  EXPECT_TRUE(test_recorder_.IsRecordInFlight());

  auto events = test_recorder_.WaitForEvents();
  EXPECT_EQ(2u, events.size());
}

}  // namespace
}  // namespace fuchsia_legacymetrics