File: pending_beacon_browsertest.cc

package info (click to toggle)
chromium 120.0.6099.224-1~deb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,112,112 kB
  • sloc: cpp: 32,907,025; ansic: 8,148,123; javascript: 3,679,536; python: 2,031,248; asm: 959,718; java: 804,675; xml: 617,256; sh: 111,417; objc: 100,835; perl: 88,443; cs: 53,032; makefile: 29,579; fortran: 24,137; php: 21,162; tcl: 21,147; sql: 20,809; ruby: 17,735; pascal: 12,864; yacc: 8,045; lisp: 3,388; lex: 1,323; ada: 727; awk: 329; jsp: 267; csh: 117; exp: 43; sed: 37
file content (979 lines) | stat: -rw-r--r-- 39,065 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
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
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <type_traits>
#include <unordered_map>

#include "base/feature_list.h"
#include "base/location.h"
#include "base/strings/strcat.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_callback.h"
#include "base/test/scoped_feature_list.h"
#include "components/ukm/test_ukm_recorder.h"
#include "content/browser/back_forward_cache_test_util.h"
#include "content/browser/renderer_host/pending_beacon_host.h"
#include "content/browser/renderer_host/render_frame_host_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/permission_controller_delegate.h"
#include "content/public/browser/permission_request_description.h"
#include "content/public/browser/permission_result.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/test_utils.h"
#include "content/shell/browser/shell.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/default_handlers.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/permissions/permission_utils.h"

namespace content {

namespace {

void PermissionRequestResponseCallbackWrapper(
    base::OnceCallback<void(blink::mojom::PermissionStatus)> callback,
    const std::vector<blink::mojom::PermissionStatus>& vector) {
  DCHECK_EQ(vector.size(), 1ul);
  std::move(callback).Run(vector.at(0));
}

}  // namespace

MATCHER(IsFrameVisible,
        base::StrCat({"Frame is", negation ? " not" : "", " visible"})) {
  return arg->GetVisibilityState() == PageVisibilityState::kVisible;
}

MATCHER(IsFrameHidden,
        base::StrCat({"Frame is", negation ? " not" : "", " hidden"})) {
  return arg->GetVisibilityState() == PageVisibilityState::kHidden;
}

class PendingBeaconTimeoutBrowserTestBase : public ContentBrowserTest {
 protected:
  using FeaturesType = std::vector<base::test::FeatureRefAndParams>;
  using DisabledFeaturesType = std::vector<base::test::FeatureRef>;

  void SetUp() override {
    feature_list_.InitWithFeaturesAndParameters(GetEnabledFeatures(),
                                                GetDisabledFeatures());
    ContentBrowserTest::SetUp();
  }
  virtual const FeaturesType& GetEnabledFeatures() = 0;
  virtual const DisabledFeaturesType& GetDisabledFeatures() {
    static const DisabledFeaturesType disabled_features = {};
    return disabled_features;
  }

  void SetUpOnMainThread() override {
    histogram_tester_ = std::make_unique<base::HistogramTester>();
    CheckPermissionStatus(blink::PermissionType::BACKGROUND_SYNC,
                          blink::mojom::PermissionStatus::GRANTED);
    // TODO(crbug.com/1293679): Update ContentBrowserTest to support overriding
    // permissions.

    host_resolver()->AddRule("*", "127.0.0.1");

    // Initializes an HTTPS server, as the PendingBeacon API is only supported
    // in secure context.
    https_test_server_ = std::make_unique<net::EmbeddedTestServer>(
        net::EmbeddedTestServer::TYPE_HTTPS);
    https_test_server_->ServeFilesFromSourceDirectory(GetTestDataFilePath());
    https_test_server_->SetSSLConfig(net::EmbeddedTestServer::CERT_TEST_NAMES);
    net::test_server::RegisterDefaultHandlers(https_test_server_.get());
    // Using `base::Unretained()` as `https_test_server()` is owned by this
    // class and and should not be able to outlive.
    https_test_server_->RegisterDefaultHandler(base::BindRepeating(
        &PendingBeaconTimeoutBrowserTestBase::HandleBeaconRequest,
        base::Unretained(this)));
  }
  void TearDownOnMainThread() override {
    histogram_tester_.reset();
    ContentBrowserTest::SetUpOnMainThread();
  }

  net::EmbeddedTestServer* https_test_server() {
    return https_test_server_.get();
  }

  // Runs JS `script` in page A, and then navigates to page B.
  void RunScriptInANavigateToB(const std::string& script) {
    RunScriptInA(script);

    // Navigate to B.
    ASSERT_TRUE(
        NavigateToURL(https_test_server()->GetURL("b.test", "/title1.html")));
  }

  // Runs JS `script` in page A.
  void RunScriptInA(const std::string& script) {
    // Navigate to A.
    ASSERT_TRUE(
        NavigateToURL(https_test_server()->GetURL("a.test", "/title1.html")));
    // Execute `script` in A.
    ASSERT_TRUE(ExecJs(web_contents(), script));
  }

  // Registers a request monitor to wait for `total_beacon` beacons received,
  // and then starts the test server.
  void RegisterBeaconRequestMonitor(const size_t total_beacon) {
    // Using base::Unretained() as `https_test_server()` is owned by
    // `content::BrowserTestBase` and should not be able to outlive.
    https_test_server()->RegisterRequestMonitor(base::BindRepeating(
        &PendingBeaconTimeoutBrowserTestBase::MonitorBeaconRequest,
        base::Unretained(this), total_beacon));
    ASSERT_TRUE(https_test_server()->Start());
  }

  // Waits for `kBeaconEndpoint` to be requested `total_beacon` times.
  // If `sent_beacon_count_` does not yet reach `total_beacon`, a RunLoop will
  // be created and runs until it is stopped by `MonitorBeaconRequest`.
  void WaitForAllBeaconsSent(size_t total_beacon) {
    {
      base::AutoLock auto_lock(count_lock_);
      if (sent_beacon_count_ >= total_beacon)
        return;
    }
    {
      base::AutoLock auto_lock(count_lock_);
      waiting_run_loop_ = std::make_unique<base::RunLoop>(
          base::RunLoop::Type::kNestableTasksAllowed);
    }
    waiting_run_loop_->Run();
    {
      base::AutoLock auto_lock(count_lock_);
      waiting_run_loop_.reset();
    }

    // Tries to wait such that browser can process the responses from http
    // server. (No guarantee)
    base::RunLoop().RunUntilIdle();
  }

  WebContents* web_contents() const { return shell()->web_contents(); }

  RenderFrameHostWrapper& current_document() {
    current_document_ =
        std::make_unique<RenderFrameHostWrapper>(current_frame_host());
    return *current_document_;
  }
  // Caution: the returned might already be killed if BFCache it not working.
  RenderFrameHostWrapper& previous_document() {
    CHECK(previous_document_);
    CHECK(!previous_document_->IsDestroyed());
    return *previous_document_;
  }
  bool WaitUntilPreviousDocumentDeleted() {
    CHECK(previous_document_);
    return previous_document_->WaitUntilRenderFrameDeleted();
  }

  bool NavigateToURL(const GURL& url) {
    previous_document_ =
        std::make_unique<RenderFrameHostWrapper>(current_frame_host());
    return content::NavigateToURL(web_contents(), url);
  }

  size_t sent_beacon_count() {
    base::AutoLock auto_lock(count_lock_);
    return sent_beacon_count_;
  }

  void CheckPermissionStatus(blink::PermissionType permission_type,
                             blink::mojom::PermissionStatus permission_status) {
    auto* permission_controller_delegate =
        web_contents()->GetBrowserContext()->GetPermissionControllerDelegate();

    base::MockOnceCallback<void(blink::mojom::PermissionStatus)> callback;
    EXPECT_CALL(callback, Run(permission_status));
    permission_controller_delegate->RequestPermissions(
        current_frame_host(),
        PermissionRequestDescription(permission_type,
                                     /*user_gesture=*/true, GURL("127.0.0.1")),
        base::BindOnce(&PermissionRequestResponseCallbackWrapper,
                       callback.Get()));
  }

  const base::HistogramTester& histogram_tester() { return *histogram_tester_; }

  void ExpectActions(
      const std::unordered_map<PendingBeaconHost::Action, size_t>& actions) {
    for (const auto& [action, count] : actions) {
      histogram_tester().ExpectBucketCount("PendingBeaconHost.Action", action,
                                           count);
    }
  }
  void ExpectBatchActions(
      const std::unordered_map<PendingBeaconHost::BatchAction, size_t>&
          batch_actions) {
    for (const auto& [batch_action, count] : batch_actions) {
      histogram_tester().ExpectBucketCount("PendingBeaconHost.BatchAction",
                                           batch_action, count);
    }
  }
  void ExpectBatchAction(const PendingBeaconHost::BatchAction& batch_action,
                         size_t count) {
    for (auto e = PendingBeaconHost::BatchAction::kNone;
         e != PendingBeaconHost::BatchAction::kMaxValue;
         e = PendingBeaconHost::BatchAction(static_cast<int>(e) + 1)) {
      const size_t expected_count = e == batch_action ? count : 0;
      histogram_tester().ExpectBucketCount("PendingBeaconHost.BatchAction", e,
                                           expected_count);
    }
  }
  void ExpectNoBatchAction() {
    ExpectBatchActions(
        {{PendingBeaconHost::BatchAction::kSendAllOnNavigation, 0},
         {PendingBeaconHost::BatchAction::kSendAllOnProcessExit, 0},
         {PendingBeaconHost::BatchAction::kSendAllOnHostDestroy, 0}});
  }
  // Expect the given `count` number of beacons are sent by `batch_action`.
  void ExpectSendByBrowserBatchAction(
      const PendingBeaconHost::BatchAction& batch_action,
      size_t count) {
    ExpectActions({{PendingBeaconHost::Action::kCreate, count},
                   // Expect to not be sent by single beacon's sendNow().
                   {PendingBeaconHost::Action::kSend, 0},
                   {PendingBeaconHost::Action::kNetworkSend, count},
                   // No guarantee RFH can be alive when receiving response.
                   // {PendingBeaconHost::Action::kNetworkComplete, count},
                   {PendingBeaconHost::Action::kDelete, 0}});
    ExpectBatchAction(batch_action, count);
  }
  // Expect the given `count` number of beacons are sent by a `sendNow() request
  // from renderer. Note that `sendNow()` can be triggered either by JS call or
  // by timers for `backgroundTimeout`/`timeout`.
  void ExpectSendByRendererAction(size_t count) {
    ExpectActions({{PendingBeaconHost::Action::kCreate, count},
                   // Expect to be sent by beacon's sendNow() from renderer.
                   {PendingBeaconHost::Action::kSend, count},
                   {PendingBeaconHost::Action::kNetworkSend, count},
                   // No guarantee RFH can be alive when receiving response.
                   // {PendingBeaconHost::Action::kNetworkComplete, count},
                   {PendingBeaconHost::Action::kDelete, 0}});
    ExpectNoBatchAction();
  }

  static constexpr char kBeaconEndpoint[] = "/pending_beacon/timeout";

 private:
  // Waits until `total_beacon` beacons received and stops `waiting_run_loop_`.
  // Invoked on `https_test_server()`'s IO Thread, so it's required to use
  // a lock to protect shared data `sent_beacon_count_` access.
  void MonitorBeaconRequest(const size_t total_beacon,
                            const net::test_server::HttpRequest& request) {
    if (request.relative_url == kBeaconEndpoint) {
      {
        base::AutoLock auto_lock(count_lock_);
        sent_beacon_count_++;
        if (sent_beacon_count_ < total_beacon) {
          return;
        }
      }

      base::AutoLock auto_lock(count_lock_);
      if (waiting_run_loop_) {
        waiting_run_loop_->Quit();
      }
    }
  }

  // Invoked on `https_test_server()`'s IO Thread.
  // PendingBeacon doesn't really look into its response, so this method just
  // returns OK status.
  std::unique_ptr<net::test_server::HttpResponse> HandleBeaconRequest(
      const net::test_server::HttpRequest& request) {
    if (request.relative_url != kBeaconEndpoint) {
      return nullptr;
    }
    auto response = std::make_unique<net::test_server::BasicHttpResponse>();
    response->set_code(net::HTTP_OK);
    return response;
  }

  RenderFrameHost* current_frame_host() {
    return web_contents()->GetPrimaryMainFrame();
  }

  base::test::ScopedFeatureList feature_list_;

  std::unique_ptr<net::EmbeddedTestServer> https_test_server_ = nullptr;

  base::Lock count_lock_;
  size_t sent_beacon_count_ GUARDED_BY(count_lock_) = 0;
  std::unique_ptr<base::RunLoop> waiting_run_loop_;

  std::unique_ptr<RenderFrameHostWrapper> current_document_ = nullptr;
  std::unique_ptr<RenderFrameHostWrapper> previous_document_ = nullptr;

  std::unique_ptr<base::HistogramTester> histogram_tester_;
};

class PendingBeaconWithBackForwardCacheMetricsBrowserTestBase
    : public PendingBeaconTimeoutBrowserTestBase,
      public BackForwardCacheMetricsTestMatcher {
 protected:
  void SetUpOnMainThread() override {
    // TestAutoSetUkmRecorder's constructor requires a sequenced context.
    ukm_recorder_ = std::make_unique<ukm::TestAutoSetUkmRecorder>();
    PendingBeaconTimeoutBrowserTestBase::SetUpOnMainThread();
  }

  void TearDownOnMainThread() override {
    ukm_recorder_.reset();
    PendingBeaconTimeoutBrowserTestBase::TearDownOnMainThread();
  }

  // `BackForwardCacheMetricsTestMatcher` implementation.
  const ukm::TestAutoSetUkmRecorder& ukm_recorder() override {
    return *ukm_recorder_;
  }
  // `BackForwardCacheMetricsTestMatcher` implementation.
  const base::HistogramTester& histogram_tester() override {
    return PendingBeaconTimeoutBrowserTestBase::histogram_tester();
  }

 private:
  std::unique_ptr<ukm::TestAutoSetUkmRecorder> ukm_recorder_;
};

struct TestTimeoutType {
  std::string test_case_name;
  int32_t timeout;

  // Returns true if `timeout` is too short for the test browser to complete a
  // navigation.
  // Empirically picking 1 second here.
  bool IsShortTimeout() const { return timeout < 1000 && timeout >= 0; }
};

// Tests to cover PendingBeacon's backgroundTimeout & timeout behaviors when
// BackForwardCache is off.
//
// Disables BackForwardCache such that a page is discarded right away on user
// navigating to another page.
// And on page discard, pending beacons should be sent out no matter what value
// its backgroundTimeout/timeout is.
class PendingBeaconTimeoutNoBackForwardCacheBrowserTest
    : public PendingBeaconTimeoutBrowserTestBase,
      public testing::WithParamInterface<TestTimeoutType> {
 protected:
  const FeaturesType& GetEnabledFeatures() override {
    static const FeaturesType enabled_features = {
        {blink::features::kPendingBeaconAPI, {{"send_on_navigation", "true"}}}};
    return enabled_features;
  }
  const DisabledFeaturesType& GetDisabledFeatures() override {
    static const DisabledFeaturesType disabled_features = {
        features::kBackForwardCache};
    return disabled_features;
  }
};

INSTANTIATE_TEST_SUITE_P(
    All,
    PendingBeaconTimeoutNoBackForwardCacheBrowserTest,
    testing::ValuesIn<std::vector<TestTimeoutType>>({
        {"LongTimeout", 600000},
        {"OneSecondTimeout", 1000},
        {"ShortTimeout", 1},
        {"ZeroTimeout", 0},
        {"DefaultTimeout", -1},        // default.
        {"NegativeTimeout", -600000},  // behaves the same as default.
    }),
    [](const testing::TestParamInfo<TestTimeoutType>& info) {
      return info.param.test_case_name;
    });

IN_PROC_BROWSER_TEST_P(PendingBeaconTimeoutNoBackForwardCacheBrowserTest,
                       SendOnPageDiscardNotUsingBackgroundTimeout) {
  const size_t total_beacon = 1;
  RegisterBeaconRequestMonitor(total_beacon);

  // Creates a pending beacon with various backgroundTimeout, which should all
  // be sent on page A discard.
  RunScriptInANavigateToB(JsReplace(R"(
    let p = new PendingGetBeacon($1, {backgroundTimeout: $2});
  )",
                                    kBeaconEndpoint, GetParam().timeout));
  ASSERT_TRUE(WaitUntilPreviousDocumentDeleted());

  // The beacon should have been sent out after the page is gone.
  WaitForAllBeaconsSent(total_beacon);
  EXPECT_EQ(sent_beacon_count(), total_beacon);
  // As "send_on_navigation" is on, beacons are not send on page discard.
  // TODO(crbug.com/1378833): Update to `kSendAllOnHostDestroy` once completed.
  ExpectSendByBrowserBatchAction(
      PendingBeaconHost::BatchAction::kSendAllOnNavigation, total_beacon);
}

IN_PROC_BROWSER_TEST_P(PendingBeaconTimeoutNoBackForwardCacheBrowserTest,
                       SendOnPageDiscardNotUsingLongerTimeout) {
  const size_t total_beacon = 1;
  RegisterBeaconRequestMonitor(total_beacon);

  // Creates a pending beacon with various timeout, which should all be sent on
  // page A discard.
  RunScriptInANavigateToB(JsReplace(R"(
    let p = new PendingGetBeacon($1, {timeout: $2});
  )",
                                    kBeaconEndpoint, GetParam().timeout));
  ASSERT_TRUE(WaitUntilPreviousDocumentDeleted());

  // The beacon should have been sent out after the page is gone.
  WaitForAllBeaconsSent(total_beacon);
  EXPECT_EQ(sent_beacon_count(), total_beacon);
  if (GetParam().IsShortTimeout()) {
    // If timeout is too short, beacon sending **may** complete before
    // navigating away from page A, which means it won't be triggered by the
    // "send on page discard" batch action but by the sendNow() from renderer.
    ExpectActions({{PendingBeaconHost::Action::kCreate, total_beacon},
                   // No guarantee to be sent by single beacon's sendNow().
                   // {PendingBeaconHost::Action::kSend, 0},
                   {PendingBeaconHost::Action::kNetworkSend, total_beacon},
                   // No guarantee RFH can be alive when receiving response.
                   // {PendingBeaconHost::Action::kNetworkComplete, count},
                   {PendingBeaconHost::Action::kDelete, 0}});
    // No guarantee it won't be send on navigation.
    ExpectBatchActions(
        {{PendingBeaconHost::BatchAction::kSendAllOnProcessExit, 0},
         {PendingBeaconHost::BatchAction::kSendAllOnHostDestroy, 0}});
  } else {
    // As "send_on_navigation" is on, beacons are not send on page discard.
    // TODO(crbug.com/1378833): Update to `kSendAllOnHostDestroy` once
    // completed.
    ExpectSendByBrowserBatchAction(
        PendingBeaconHost::BatchAction::kSendAllOnNavigation, total_beacon);
  }
}

// Tests to cover PendingBeacon's backgroundTimeout behaviors.
// Setting a long `PendingBeaconMaxBackgroundTimeoutInMs` (1min) > BFCache
// timeout (5s) so that beacon sending cannot be caused by reaching max
// background timeout limit but only by BFCache eviction if backgroundTimeout
// set >= 5s.
class PendingBeaconBackgroundTimeoutBrowserTest
    : public PendingBeaconTimeoutBrowserTestBase {
 protected:
  const FeaturesType& GetEnabledFeatures() override {
    static const FeaturesType enabled_features = {
        {blink::features::kPendingBeaconAPI,
         {{"PendingBeaconMaxBackgroundTimeoutInMs", "60000"},
          // Don't force sending out beacons on pagehide.
          {"send_on_navigation", "false"}}},
        {features::kBackForwardCache, {{}}},
        {features::kBackForwardCacheTimeToLiveControl,
         {{"time_to_live_seconds", "5"}}},
        // Forces BFCache to work in low memory device.
        {features::kBackForwardCacheMemoryControls,
         {{"memory_threshold_for_back_forward_cache_in_mb", "0"}}}};
    return enabled_features;
  }
};

IN_PROC_BROWSER_TEST_F(PendingBeaconBackgroundTimeoutBrowserTest,
                       SendOnHiddenAfterNavigation) {
  const size_t total_beacon = 1;
  RegisterBeaconRequestMonitor(total_beacon);

  // Creates a pending beacon with 0s backgroundTimeout.
  // It should be sent out right on entering `hidden` state after navigating
  // away from A.
  RunScriptInANavigateToB(JsReplace(R"(
    let p = new PendingGetBeacon($1, {backgroundTimeout: 0});
  )",
                                    kBeaconEndpoint));
  ASSERT_THAT(previous_document(), IsFrameHidden());

  WaitForAllBeaconsSent(total_beacon);
  EXPECT_EQ(sent_beacon_count(), total_beacon);
  // Triggered by backgroundTimeout's 0s timer from renderer.
  ExpectSendByRendererAction(total_beacon);
}

IN_PROC_BROWSER_TEST_F(PendingBeaconBackgroundTimeoutBrowserTest,
                       SendOnBackgroundTimeout) {
  const size_t total_beacon = 1;
  RegisterBeaconRequestMonitor(total_beacon);

  // Creates a pending beacon with backgroundTimeout (1s) < BFCache TTL (5s).
  // The beacon should be sent out on entering `hidden` state but before
  // page deletion.
  RunScriptInANavigateToB(JsReplace(R"(
    let p = new PendingGetBeacon($1, {backgroundTimeout: 1000});
  )",
                                    kBeaconEndpoint));
  ASSERT_THAT(previous_document(), IsFrameHidden());

  WaitForAllBeaconsSent(total_beacon);
  EXPECT_EQ(sent_beacon_count(), total_beacon);
  // Triggered by backgroundTimeout's timer from renderer.
  ExpectSendByRendererAction(total_beacon);
}

// When backgroundTimeout is set, its timer resets every time when the page
// becomes visible if it has not yet expired.
IN_PROC_BROWSER_TEST_F(
    PendingBeaconBackgroundTimeoutBrowserTest,
    NotSendWhenPageIsRestoredBeforeBackgroundTimeoutExpires) {
  const size_t total_beacon = 0;
  RegisterBeaconRequestMonitor(total_beacon);

  // Creates a pending beacon with backgroundTimeout (3s) < BFCache TTL (5s).
  RunScriptInANavigateToB(JsReplace(R"(
    let p = new PendingGetBeacon($1, {backgroundTimeout: 3000});
  )",
                                    kBeaconEndpoint));
  ASSERT_THAT(previous_document(), IsFrameHidden());

  // Navigate back to A.
  ASSERT_TRUE(HistoryGoBack(web_contents()));
  // The page A becomes visible again, so backgroundTimeout timer should stop.
  ASSERT_THAT(current_document(), IsFrameVisible());

  // Verify that beacon is not sent.
  EXPECT_EQ(sent_beacon_count(), total_beacon);
}

IN_PROC_BROWSER_TEST_F(PendingBeaconBackgroundTimeoutBrowserTest,
                       SendOnBackForwardCacheEviction) {
  const size_t total_beacon = 1;
  RegisterBeaconRequestMonitor(total_beacon);

  // Creates a pending beacon with backgroundTimeout (8s) > BFCache TTL (5s)
  // The beacon should be sent out on page deletion.
  RunScriptInANavigateToB(JsReplace(R"(
    let p = new PendingGetBeacon($1, {backgroundTimeout: 8000});
  )",
                                    kBeaconEndpoint));
  ASSERT_TRUE(previous_document().WaitUntilRenderFrameDeleted());

  WaitForAllBeaconsSent(total_beacon);
  EXPECT_EQ(sent_beacon_count(), total_beacon);
}

// TODO(crbug.com/1491942): This fails with the field trial testing config.
class PendingBeaconBackgroundTimeoutBrowserTestNoTestingConfig
    : public PendingBeaconBackgroundTimeoutBrowserTest {
 public:
  void SetUpCommandLine(base::CommandLine* command_line) override {
    PendingBeaconBackgroundTimeoutBrowserTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch("disable-field-trial-config");
  }
};

IN_PROC_BROWSER_TEST_F(PendingBeaconBackgroundTimeoutBrowserTestNoTestingConfig,
                       SendMultipleOnBackgroundTimeout) {
  const size_t total_beacon = 5;
  RegisterBeaconRequestMonitor(total_beacon);

  RunScriptInANavigateToB(JsReplace(R"(
    let p1 = new PendingGetBeacon($1, {backgroundTimeout: 200});
    let p2 = new PendingGetBeacon($1, {backgroundTimeout: 100});
    let p3 = new PendingGetBeacon($1, {backgroundTimeout: 500});
    let p4 = new PendingGetBeacon($1, {backgroundTimeout: 700});
    let p5 = new PendingGetBeacon($1, {backgroundTimeout: 300});
  )",
                                    kBeaconEndpoint));
  ASSERT_THAT(previous_document(), IsFrameHidden());

  WaitForAllBeaconsSent(total_beacon);
  EXPECT_EQ(sent_beacon_count(), total_beacon);
  // Triggered by backgroundTimeout's timer from renderer.
  ExpectSendByRendererAction(total_beacon);
}

// Tests to cover PendingBeacon's timeout behaviors.
// Sets `BeaconTimeToLiveInMs` (10s) > BFCache timeout (5s) to also cover beacon
// sending on page eviction.
using PendingBeaconTimeoutBrowserTest =
    PendingBeaconBackgroundTimeoutBrowserTest;

IN_PROC_BROWSER_TEST_F(PendingBeaconTimeoutBrowserTest, SendOnZeroTimeout) {
  const size_t total_beacon = 1;
  RegisterBeaconRequestMonitor(total_beacon);

  // Creates a pending beacon with 0s timeout. It should be sent out right away
  // (without the page entering 'hidden' state).
  RunScriptInA(JsReplace(R"(
    let p = new PendingGetBeacon($1, {timeout: 0});
  )",
                         kBeaconEndpoint));
  ASSERT_THAT(current_document(), IsFrameVisible());

  WaitForAllBeaconsSent(total_beacon);
  EXPECT_EQ(sent_beacon_count(), total_beacon);
}

// When timeout is set, it's not relevant whether the page is hidden or not.
IN_PROC_BROWSER_TEST_F(PendingBeaconTimeoutBrowserTest,
                       SendOnTimeoutWhenPageIsHidden) {
  const size_t total_beacon = 1;
  RegisterBeaconRequestMonitor(total_beacon);

  // Creates a pending beacon with a timeout which should expire when the page A
  // is still hidden.
  RunScriptInANavigateToB(JsReplace(R"(
    let p = new PendingGetBeacon($1, {timeout: 1000});
  )",
                                    kBeaconEndpoint));
  ASSERT_THAT(previous_document(), IsFrameHidden());

  WaitForAllBeaconsSent(total_beacon);
  // Verify that beacon is sent.
  EXPECT_EQ(sent_beacon_count(), total_beacon);
}

// When timeout is set, it's not relevant whether the page is visible or not.
IN_PROC_BROWSER_TEST_F(PendingBeaconTimeoutBrowserTest,
                       SendOnTimeoutWhenPageIsVisible) {
  const size_t total_beacon = 1;
  RegisterBeaconRequestMonitor(total_beacon);

  // Creates a pending beacon with a timeout longer enough such that page can
  // experience visible -> hidden -> visible.
  RunScriptInANavigateToB(JsReplace(R"(
    let p = new PendingGetBeacon($1, {timeout: 4000});
  )",
                                    kBeaconEndpoint));
  ASSERT_THAT(previous_document(), IsFrameHidden());
  // beacon is not yet sent.
  ASSERT_EQ(sent_beacon_count(), 0u);

  // Navigate back to A.
  ASSERT_TRUE(HistoryGoBack(web_contents()));
  // The page A becomes visible again, but timeout timer never stops.
  ASSERT_THAT(current_document(), IsFrameVisible());

  WaitForAllBeaconsSent(total_beacon);
  // Verify that beacon is sent.
  EXPECT_EQ(sent_beacon_count(), total_beacon);
}

IN_PROC_BROWSER_TEST_F(PendingBeaconTimeoutBrowserTest, SendOnShorterTimeout) {
  const size_t total_beacon = 1;
  RegisterBeaconRequestMonitor(total_beacon);

  // Creates a pending beacon with long (5s) timeout. And then quickly updates
  // to a very short (0.01s) timeout. The beacon should be sent out right away.
  RunScriptInA(JsReplace(R"(
    let p = new PendingGetBeacon($1, {timeout: 5000});
    p.timeout = 10;
  )",
                         kBeaconEndpoint));
  ASSERT_THAT(current_document(), IsFrameVisible());

  WaitForAllBeaconsSent(total_beacon);
  EXPECT_EQ(sent_beacon_count(), total_beacon);
}

IN_PROC_BROWSER_TEST_F(PendingBeaconTimeoutBrowserTest, SendOnlyOnce) {
  const size_t total_beacon = 1;
  RegisterBeaconRequestMonitor(total_beacon);

  // Creates a pending beacon which should be sent out right way.
  // But it won't be sent out twice.
  RunScriptInA(JsReplace(R"(
    let p = new PendingGetBeacon($1, {timeout: 0});
    p.timeout = 1;
  )",
                         kBeaconEndpoint));
  ASSERT_THAT(current_document(), IsFrameVisible());

  WaitForAllBeaconsSent(total_beacon);
  EXPECT_EQ(sent_beacon_count(), total_beacon);
}

IN_PROC_BROWSER_TEST_F(PendingBeaconTimeoutBrowserTest, SendMultipleOnTimeout) {
  const size_t total_beacon = 5;
  RegisterBeaconRequestMonitor(total_beacon);

  RunScriptInA(JsReplace(R"(
    let p1 = new PendingGetBeacon($1, {timeout: 200});
    let p2 = new PendingGetBeacon($1, {timeout: 100});
    let p3 = new PendingGetBeacon($1, {timeout: 500});
    let p4 = new PendingGetBeacon($1, {timeout: 700});
    let p5 = new PendingGetBeacon($1, {timeout: 300});
  )",
                         kBeaconEndpoint));
  ASSERT_THAT(current_document(), IsFrameVisible());

  WaitForAllBeaconsSent(total_beacon);
  EXPECT_EQ(sent_beacon_count(), total_beacon);
}

// Tests to cover PendingBeacon's backgroundTimeout & timeout mutual behaviors.
// Sets a long BFCache timeout (1min) so that beacon won't be sent out due to
// page eviction.
class PendingBeaconMutualTimeoutWithLongBackForwardCacheTTLBrowserTest
    : public PendingBeaconWithBackForwardCacheMetricsBrowserTestBase {
 protected:
  const FeaturesType& GetEnabledFeatures() override {
    static const FeaturesType enabled_features = {
        {blink::features::kPendingBeaconAPI,
         {// Don't force sending out beacons on pagehide.
          {"send_on_navigation", "false"}}},
        {features::kBackForwardCache, {{}}},
        {features::kBackForwardCacheTimeToLiveControl,
         {{"time_to_live_seconds", "60"}}},
        // Forces BFCache to work in low memory device.
        {features::kBackForwardCacheMemoryControls,
         {{"memory_threshold_for_back_forward_cache_in_mb", "0"}}}};
    return enabled_features;
  }
};

IN_PROC_BROWSER_TEST_F(
    PendingBeaconMutualTimeoutWithLongBackForwardCacheTTLBrowserTest,
    NotSendWhenPageIsRestoredBeforeBeingEvictedFromBackForwardCache) {
  const size_t total_beacon = 0;
  RegisterBeaconRequestMonitor(total_beacon);

  // Creates a pending beacon with default backgroundTimeout & timeout.
  // It should not be sent out as long as the page is alive (not evicted from
  // BackForwardCache).
  RunScriptInANavigateToB(JsReplace(R"(
    let p = new PendingGetBeacon($1);
  )",
                                    kBeaconEndpoint));
  ASSERT_THAT(previous_document(), IsFrameHidden());
  // Navigate back to A.
  ASSERT_TRUE(HistoryGoBack(web_contents()));
  // The same page A is still alive.
  ExpectRestored(FROM_HERE);

  // Verify that beacon is not sent.
  EXPECT_EQ(sent_beacon_count(), total_beacon);
}

// When both backgroundTimeout & timeout is set, whichever expires earlier will
// trigger beacon sending (part 1).
IN_PROC_BROWSER_TEST_F(
    PendingBeaconMutualTimeoutWithLongBackForwardCacheTTLBrowserTest,
    SendOnEarlierTimeout) {
  const size_t total_beacon = 1;
  RegisterBeaconRequestMonitor(total_beacon);

  // Creates a pending beacon with long backgroundTimeout (60s) & short
  // timeout (1s).
  // The shorter one, i.e. timeout, should be reachable such that the beacon
  // can be sent before this test case times out.
  RunScriptInANavigateToB(JsReplace(R"(
    let p = new PendingGetBeacon($1, {backgroundTimeout: 60000, timeout: 1000});
  )",
                                    kBeaconEndpoint));
  ASSERT_THAT(previous_document(), IsFrameHidden());

  WaitForAllBeaconsSent(total_beacon);
  // Verify that beacon is sent.
  EXPECT_EQ(sent_beacon_count(), total_beacon);
}

// When both backgroundTimeout & timeout is set, whichever expires earlier will
// trigger beacon sending (part 2).
IN_PROC_BROWSER_TEST_F(
    PendingBeaconMutualTimeoutWithLongBackForwardCacheTTLBrowserTest,
    SendOnEarlierBackgroundTimeout) {
  const size_t total_beacon = 1;
  RegisterBeaconRequestMonitor(total_beacon);

  // Creates a pending beacon with short backgroundTimeout (1s) & long
  // timeout (60s).
  // The shorter one, i.e. backgroundTimeout, should be reachable such that the
  // beacon can be sent before this test case times out.
  RunScriptInANavigateToB(JsReplace(R"(
    let p = new PendingGetBeacon($1, {backgroundTimeout: 1000, timeout: 60000});
  )",
                                    kBeaconEndpoint));
  ASSERT_THAT(previous_document(), IsFrameHidden());

  WaitForAllBeaconsSent(total_beacon);
  // Verify that beacon is sent.
  EXPECT_EQ(sent_beacon_count(), total_beacon);
}

// Tests to cover PendingBeacon's behaviors when enabled forced sending on
// pagehide event.
//
// Setting a long `PendingBeaconMaxBackgroundTimeoutInMs` (1min), and a long
// BFCache timeout (1min) so that beacon sending cannot be caused by reaching
// max background timeout limit, and cannot be caused by BFCache eviction.
class PendingBeaconSendOnPagehideBrowserTest
    : public PendingBeaconWithBackForwardCacheMetricsBrowserTestBase {
 protected:
  const FeaturesType& GetEnabledFeatures() override {
    static const FeaturesType enabled_features = {
        {blink::features::kPendingBeaconAPI,
         {{"PendingBeaconMaxBackgroundTimeoutInMs", "60000"},
          {"send_on_navigation", "true"}}},
        {features::kBackForwardCache, {{}}},
        {features::kBackForwardCacheTimeToLiveControl,
         {{"time_to_live_seconds", "60"}}},
        // Forces BFCache to work in low memory device.
        {features::kBackForwardCacheMemoryControls,
         {{"memory_threshold_for_back_forward_cache_in_mb", "0"}}}};
    return enabled_features;
  }
};

IN_PROC_BROWSER_TEST_F(PendingBeaconSendOnPagehideBrowserTest,
                       SendOnPagehideWhenPageIsPersisted) {
  const size_t total_beacon = 3;
  RegisterBeaconRequestMonitor(total_beacon);

  // Creates 3 pending beacons with default backgroundTimeout & timeout.
  // They should be sent out on transitioning to pagehide event.
  RunScriptInANavigateToB(JsReplace(R"(
    document.title = '';
    let p1 = new PendingGetBeacon($1);
    let p2 = new PendingPostBeacon($1);
    let p3 = new PendingGetBeacon($1);
    window.addEventListener('pagehide', (e) => {
      document.title = e.persisted + '/' + p1.pending + '/' + p2.pending +
                       '/' + p3.pending;
    });
  )",
                                    kBeaconEndpoint));
  ASSERT_THAT(previous_document(), IsFrameHidden());

  // Navigate back to A.
  ASSERT_TRUE(HistoryGoBack(web_contents()));
  // The same page A is still alive.
  ExpectRestored(FROM_HERE);
  // All beacons should have been sent out before previous pagehide.
  std::u16string expected_title = u"true/false/false/false";
  TitleWatcher title_watcher(web_contents(), expected_title);
  EXPECT_EQ(title_watcher.WaitAndGetTitle(), expected_title);
  WaitForAllBeaconsSent(total_beacon);
  EXPECT_EQ(sent_beacon_count(), total_beacon);
}

IN_PROC_BROWSER_TEST_F(PendingBeaconSendOnPagehideBrowserTest,
                       SendOnPagehideBeforeBackgroundTimeout) {
  const size_t total_beacon = 3;
  RegisterBeaconRequestMonitor(total_beacon);

  // Creates 3 pending beacons with long backgroundTimeout < BFCache TTL (1min).
  // They should be sent out on transitioning to pagehide but before the end of
  // backgroundTimeout and before BFCache TTL.
  RunScriptInANavigateToB(JsReplace(R"(
    document.title = '';
    let p1 = new PendingGetBeacon($1, {backgroundTimeout: 20000});
    let p2 = new PendingPostBeacon($1, {backgroundTimeout: 15000});
    let p3 = new PendingGetBeacon($1, {backgroundTimeout: 10000});
    window.addEventListener('pagehide', (e) => {
      document.title = e.persisted + '/' + p1.pending + '/' + p2.pending +
                       '/' + p3.pending;
    });
  )",
                                    kBeaconEndpoint));
  ASSERT_THAT(previous_document(), IsFrameHidden());

  // Navigate back to A.
  ASSERT_TRUE(HistoryGoBack(web_contents()));
  // The same page A is still alive.
  ExpectRestored(FROM_HERE);
  // All beacons should have been sent out.
  std::u16string expected_title = u"true/false/false/false";
  TitleWatcher title_watcher(web_contents(), expected_title);
  EXPECT_EQ(title_watcher.WaitAndGetTitle(), expected_title);
  WaitForAllBeaconsSent(total_beacon);
  EXPECT_EQ(sent_beacon_count(), total_beacon);
}

IN_PROC_BROWSER_TEST_F(PendingBeaconSendOnPagehideBrowserTest,
                       SendOnPagehideBeforeTimeout) {
  const size_t total_beacon = 3;
  RegisterBeaconRequestMonitor(total_beacon);

  // Creates 3 pending beacons with long timeout < BFCache TTL (1min).
  // They should be sent out on transitioning to pagehide but before the end of
  // timeout and before BFCache TTL.
  RunScriptInANavigateToB(JsReplace(R"(
    document.title = '';
    let p1 = new PendingGetBeacon($1, {timeout: 20000});
    let p2 = new PendingPostBeacon($1, {timeout: 10000});
    let p3 = new PendingGetBeacon($1, {timeout: 15000});
    window.addEventListener('pagehide', (e) => {
      document.title = e.persisted + '/' + p1.pending + '/' + p2.pending +
                       '/' + p3.pending;
    });
  )",
                                    kBeaconEndpoint));
  ASSERT_THAT(previous_document(), IsFrameHidden());

  // Navigate back to A.
  ASSERT_TRUE(HistoryGoBack(web_contents()));
  // The same page A is still alive.
  ExpectRestored(FROM_HERE);
  // All beacons should have been sent out.
  std::u16string expected_title = u"true/false/false/false";
  TitleWatcher title_watcher(web_contents(), expected_title);
  EXPECT_EQ(title_watcher.WaitAndGetTitle(), expected_title);
  WaitForAllBeaconsSent(total_beacon);
  EXPECT_EQ(sent_beacon_count(), total_beacon);
}

class PendingBeaconRendererProcessExitBrowserTest
    : public PendingBeaconTimeoutBrowserTestBase {
 protected:
  const FeaturesType& GetEnabledFeatures() override {
    static const FeaturesType enabled_features = {
        {blink::features::kPendingBeaconAPI, {}},
        // Forces BFCache to work in low memory device so that a page won't be
        // killed by normal page discard.
        {features::kBackForwardCacheMemoryControls,
         {{"memory_threshold_for_back_forward_cache_in_mb", "0"}}}};
    return enabled_features;
  }
};

#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID)
// Disabled due to failures on various Mac/Linux builders.
// TODO(crbug.com/1382713) Reenable the test.
#define MAYBE_SendAllOnProcessCrash DISABLED_SendAllOnProcessCrash
#else
#define MAYBE_SendAllOnProcessCrash SendAllOnProcessCrash
#endif
IN_PROC_BROWSER_TEST_F(PendingBeaconRendererProcessExitBrowserTest,
                       MAYBE_SendAllOnProcessCrash) {
  const size_t total_beacon = 2;
  RegisterBeaconRequestMonitor(total_beacon);

  // Creates a pending beacon that will only be sent on page discard or crash.
  // Make beacon creations within a Promise to ensure they can all be created
  // before executing next statement.
  RunScriptInA(JsReplace(R"(
    new Promise(resolve => {
      new PendingGetBeacon($1);
      new PendingPostBeacon($1);
      resolve();
    });
  )",
                         kBeaconEndpoint));
  ASSERT_EQ(sent_beacon_count(), 0u);
  ASSERT_TRUE(
      PendingBeaconHost::GetForCurrentDocument(current_document().get()));

  // Make the renderer crash.
  CrashTab(web_contents());
  // The RenderFrame is dead but the attached beacon host is still alive.
  ASSERT_FALSE(current_document()->IsRenderFrameLive());
  ASSERT_TRUE(
      PendingBeaconHost::GetForCurrentDocument(current_document().get()));

  WaitForAllBeaconsSent(total_beacon);
  EXPECT_EQ(sent_beacon_count(), total_beacon);
  ExpectSendByBrowserBatchAction(
      PendingBeaconHost::BatchAction::kSendAllOnProcessExit, total_beacon);
}

}  // namespace content