forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathback_forward_cache_browsertest.cc
9565 lines (8097 loc) · 375 KB
/
back_forward_cache_browsertest.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 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 <memory>
#include <unordered_map>
#include "base/callback_forward.h"
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/hash/hash.h"
#include "base/location.h"
#include "base/metrics/metrics_hashes.h"
#include "base/optional.h"
#include "base/run_loop.h"
#include "base/strings/string_piece_forward.h"
#include "base/system/sys_info.h"
#include "base/task/common/task_annotator.h"
#include "base/task/post_task.h"
#include "base/test/bind.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_mock_time_task_runner.h"
#include "base/test/test_timeouts.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/trace_event/trace_log.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "components/network_session_configurator/common/network_switches.h"
#include "components/ukm/test_ukm_recorder.h"
#include "content/browser/bad_message.h"
#include "content/browser/generic_sensor/sensor_provider_proxy_impl.h"
#include "content/browser/presentation/presentation_test_utils.h"
#include "content/browser/renderer_host/back_forward_cache_impl.h"
#include "content/browser/renderer_host/frame_tree_node.h"
#include "content/browser/renderer_host/page_lifecycle_state_manager.h"
#include "content/browser/renderer_host/render_frame_host_impl.h"
#include "content/browser/renderer_host/should_swap_browsing_instance.h"
#include "content/browser/web_contents/file_chooser_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/common/content_navigation_policy.h"
#include "content/common/render_accessibility.mojom.h"
#include "content/public/browser/back_forward_cache.h"
#include "content/public/browser/frame_service_base.h"
#include "content/public/browser/global_routing_id.h"
#include "content/public/browser/idle_manager.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/site_isolation_policy.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/back_forward_cache_util.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/idle_test_utils.h"
#include "content/public/test/navigation_handle_observer.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_navigation_throttle.h"
#include "content/public/test/test_navigation_throttle_inserter.h"
#include "content/public/test/test_utils.h"
#include "content/public/test/text_input_test_utils.h"
#include "content/public/test/url_loader_interceptor.h"
#include "content/shell/browser/shell.h"
#include "content/shell/browser/shell_javascript_dialog_manager.h"
#include "content/test/content_browser_test_utils_internal.h"
#include "content/test/echo.test-mojom.h"
#include "media/base/media_switches.h"
#include "mojo/public/cpp/bindings/message.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "net/base/filename_util.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/controllable_http_response.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/spawned_test_server/spawned_test_server.h"
#include "net/test/test_data_directory.h"
#include "services/device/public/cpp/test/fake_sensor_and_provider.h"
#include "services/device/public/cpp/test/scoped_geolocation_overrider.h"
#include "services/device/public/mojom/vibration_manager.mojom.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/scheduler/web_scheduler_tracked_feature.h"
#include "third_party/blink/public/mojom/app_banner/app_banner.mojom.h"
using testing::_;
using testing::Each;
using testing::ElementsAre;
using testing::Not;
using testing::UnorderedElementsAreArray;
namespace content {
namespace {
const char kDisabledReasonForTest[] = "DisabledByBackForwardCacheBrowserTest";
const char kSameSiteNavigationDidSwapHistogramName[] =
"BackForwardCache.ProactiveSameSiteBISwap.SameSiteNavigationDidSwap";
const char kEligibilityDuringCommitHistogramName[] =
"BackForwardCache.ProactiveSameSiteBISwap.EligibilityDuringCommit";
const char kUnloadRunsAfterCommitHistogramName[] =
"BackForwardCache.ProactiveSameSiteBISwap.UnloadRunsAfterCommit";
// hash for std::unordered_map.
struct FeatureHash {
size_t operator()(base::Feature feature) const {
return base::FastHash(feature.name);
}
};
// compare operator for std::unordered_map.
struct FeatureEqualOperator {
bool operator()(base::Feature feature1, base::Feature feature2) const {
return std::strcmp(feature1.name, feature2.name) == 0;
}
};
// Test about the BackForwardCache.
class BackForwardCacheBrowserTest : public ContentBrowserTest,
public WebContentsObserver {
public:
~BackForwardCacheBrowserTest() override {
if (fail_for_unexpected_messages_while_cached_) {
ExpectTotalCount(
"BackForwardCache.UnexpectedRendererToBrowserMessage.InterfaceName",
0);
}
}
protected:
using UkmMetrics = ukm::TestUkmRecorder::HumanReadableUkmMetrics;
// Disables checking metrics that are recorded recardless of the domains. By
// default, this class' Expect* function checks the metrics both for the
// specific domain and for all domains at the same time. In the case when the
// test results need to be different, call this function.
void DisableCheckingMetricsForAllSites() { check_all_sites_ = false; }
void SetUpCommandLine(base::CommandLine* command_line) override {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kUseFakeUIForMediaStream);
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kIgnoreCertificateErrors);
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalWebPlatformFeatures);
// TODO(sreejakshetty): Initialize ScopedFeatureLists from test constructor.
EnableFeatureAndSetParams(features::kBackForwardCache,
"TimeToLiveInBackForwardCacheInSeconds", "3600");
EnableFeatureAndSetParams(features::kBackForwardCache,
"message_handling_when_cached", "log");
EnableFeatureAndSetParams(
features::kBackForwardCache, "enable_same_site",
same_site_back_forward_cache_enabled_ ? "true" : "false");
EnableFeatureAndSetParams(
features::kBackForwardCache, "skip_same_site_if_unload_exists",
skip_same_site_if_unload_exists_ ? "true" : "false");
EnableFeatureAndSetParams(
blink::features::kLogUnexpectedIPCPostedToBackForwardCachedDocuments,
"delay_before_tracking_ms", "0");
#if defined(OS_ANDROID)
EnableFeatureAndSetParams(features::kBackForwardCache,
"process_binding_strength", "NORMAL");
#endif
SetupFeaturesAndParameters();
command_line->AppendSwitchASCII(
switches::kAutoplayPolicy,
switches::autoplay::kNoUserGestureRequiredPolicy);
ContentBrowserTest::SetUpCommandLine(command_line);
}
void SetupFeaturesAndParameters() {
std::vector<base::test::ScopedFeatureList::FeatureAndParams>
enabled_features;
for (auto feature_param = features_with_params_.begin();
feature_param != features_with_params_.end(); feature_param++) {
enabled_features.push_back({feature_param->first, feature_param->second});
}
feature_list_.InitWithFeaturesAndParameters(enabled_features,
disabled_features_);
}
void EnableFeatureAndSetParams(base::Feature feature,
std::string param_name,
std::string param_value) {
features_with_params_[feature][param_name] = param_value;
}
void DisableFeature(base::Feature feature) {
disabled_features_.push_back(feature);
}
void SetUpOnMainThread() override {
host_resolver()->AddRule("*", "127.0.0.1");
// TestAutoSetUkmRecorder's constructor requires a sequenced context.
ukm_recorder_ = std::make_unique<ukm::TestAutoSetUkmRecorder>();
ContentBrowserTest::SetUpOnMainThread();
}
void TearDownOnMainThread() override {
ukm_recorder_.reset();
ContentBrowserTest::TearDownOnMainThread();
}
WebContentsImpl* web_contents() const {
return static_cast<WebContentsImpl*>(shell()->web_contents());
}
RenderFrameHostImpl* current_frame_host() {
return web_contents()->GetFrameTree()->root()->current_frame_host();
}
RenderFrameHostManager* render_frame_host_manager() {
return web_contents()->GetFrameTree()->root()->render_manager();
}
std::string DepictFrameTree(FrameTreeNode* node) {
return visualizer_.DepictFrameTree(node);
}
bool HistogramContainsIntValue(base::HistogramBase::Sample sample,
std::vector<base::Bucket> histogram_values) {
auto it = std::find_if(histogram_values.begin(), histogram_values.end(),
[sample](const base::Bucket& bucket) {
return bucket.min == static_cast<int>(sample);
});
return it != histogram_values.end();
}
void ExpectOutcome(BackForwardCacheMetrics::HistoryNavigationOutcome outcome,
base::Location location) {
base::HistogramBase::Sample sample = base::HistogramBase::Sample(outcome);
AddSampleToBuckets(&expected_outcomes_, sample);
EXPECT_THAT(histogram_tester_.GetAllSamples(
"BackForwardCache.HistoryNavigationOutcome"),
UnorderedElementsAreArray(expected_outcomes_))
<< location.ToString();
if (!check_all_sites_)
return;
EXPECT_THAT(histogram_tester_.GetAllSamples(
"BackForwardCache.AllSites.HistoryNavigationOutcome"),
UnorderedElementsAreArray(expected_outcomes_))
<< location.ToString();
std::string is_served_from_bfcache =
"BackForwardCache.IsServedFromBackForwardCache";
bool ukm_outcome =
outcome == BackForwardCacheMetrics::HistoryNavigationOutcome::kRestored;
expected_ukm_outcomes_.push_back(
{{is_served_from_bfcache, static_cast<int64_t>(ukm_outcome)}});
EXPECT_THAT(ukm_recorder_->GetMetrics("HistoryNavigation",
{is_served_from_bfcache}),
expected_ukm_outcomes_)
<< location.ToString();
}
void ExpectOutcomeDidNotChange(base::Location location) {
EXPECT_EQ(expected_outcomes_,
histogram_tester_.GetAllSamples(
"BackForwardCache.HistoryNavigationOutcome"))
<< location.ToString();
if (!check_all_sites_)
return;
EXPECT_EQ(expected_outcomes_,
histogram_tester_.GetAllSamples(
"BackForwardCache.AllSites.HistoryNavigationOutcome"))
<< location.ToString();
std::string is_served_from_bfcache =
"BackForwardCache.IsServedFromBackForwardCache";
EXPECT_THAT(ukm_recorder_->GetMetrics("HistoryNavigation",
{is_served_from_bfcache}),
expected_ukm_outcomes_)
<< location.ToString();
}
void ExpectNotRestored(
std::vector<BackForwardCacheMetrics::NotRestoredReason> reasons,
base::Location location) {
uint64_t not_restored_reasons_bits = 0;
for (BackForwardCacheMetrics::NotRestoredReason reason : reasons) {
base::HistogramBase::Sample sample = base::HistogramBase::Sample(reason);
AddSampleToBuckets(&expected_not_restored_, sample);
not_restored_reasons_bits |= 1ull << static_cast<int>(reason);
}
EXPECT_THAT(histogram_tester_.GetAllSamples(
"BackForwardCache.HistoryNavigationOutcome."
"NotRestoredReason"),
UnorderedElementsAreArray(expected_not_restored_))
<< location.ToString();
if (!check_all_sites_)
return;
EXPECT_THAT(histogram_tester_.GetAllSamples(
"BackForwardCache.AllSites.HistoryNavigationOutcome."
"NotRestoredReason"),
UnorderedElementsAreArray(expected_not_restored_))
<< location.ToString();
std::string not_restored_reasons = "BackForwardCache.NotRestoredReasons";
expected_ukm_not_restored_reasons_.push_back(
{{not_restored_reasons, not_restored_reasons_bits}});
EXPECT_THAT(
ukm_recorder_->GetMetrics("HistoryNavigation", {not_restored_reasons}),
expected_ukm_not_restored_reasons_)
<< location.ToString();
}
void ExpectNotRestoredDidNotChange(base::Location location) {
EXPECT_EQ(expected_not_restored_,
histogram_tester_.GetAllSamples(
"BackForwardCache.HistoryNavigationOutcome."
"NotRestoredReason"))
<< location.ToString();
std::string not_restored_reasons = "BackForwardCache.NotRestoredReasons";
if (!check_all_sites_)
return;
EXPECT_EQ(expected_not_restored_,
histogram_tester_.GetAllSamples(
"BackForwardCache.AllSites.HistoryNavigationOutcome."
"NotRestoredReason"))
<< location.ToString();
EXPECT_THAT(
ukm_recorder_->GetMetrics("HistoryNavigation", {not_restored_reasons}),
expected_ukm_not_restored_reasons_)
<< location.ToString();
}
void ExpectBlocklistedFeature(
blink::scheduler::WebSchedulerTrackedFeature feature,
base::Location location) {
ExpectBlocklistedFeatures({feature}, location);
}
void ExpectBlocklistedFeatures(
std::vector<blink::scheduler::WebSchedulerTrackedFeature> features,
base::Location location) {
for (auto feature : features) {
base::HistogramBase::Sample sample = base::HistogramBase::Sample(feature);
AddSampleToBuckets(&expected_blocklisted_features_, sample);
}
EXPECT_THAT(histogram_tester_.GetAllSamples(
"BackForwardCache.HistoryNavigationOutcome."
"BlocklistedFeature"),
UnorderedElementsAreArray(expected_blocklisted_features_))
<< location.ToString();
if (!check_all_sites_)
return;
EXPECT_THAT(histogram_tester_.GetAllSamples(
"BackForwardCache.AllSites.HistoryNavigationOutcome."
"BlocklistedFeature"),
UnorderedElementsAreArray(expected_blocklisted_features_))
<< location.ToString();
}
void ExpectDisabledWithReason(const std::string& reason,
base::Location location) {
base::HistogramBase::Sample sample =
base::HistogramBase::Sample(base::HashMetricName(reason));
AddSampleToBuckets(&expected_disabled_reasons_, sample);
EXPECT_THAT(histogram_tester_.GetAllSamples(
"BackForwardCache.HistoryNavigationOutcome."
"DisabledForRenderFrameHostReason"),
UnorderedElementsAreArray(expected_disabled_reasons_))
<< location.ToString();
}
void ExpectBrowsingInstanceNotSwappedReason(ShouldSwapBrowsingInstance reason,
base::Location location) {
base::HistogramBase::Sample sample = base::HistogramBase::Sample(reason);
AddSampleToBuckets(&expected_browsing_instance_not_swapped_reasons_,
sample);
EXPECT_THAT(histogram_tester_.GetAllSamples(
"BackForwardCache.HistoryNavigationOutcome."
"BrowsingInstanceNotSwappedReason"),
UnorderedElementsAreArray(
expected_browsing_instance_not_swapped_reasons_))
<< location.ToString();
if (!check_all_sites_)
return;
EXPECT_THAT(histogram_tester_.GetAllSamples(
"BackForwardCache.AllSites.HistoryNavigationOutcome."
"BrowsingInstanceNotSwappedReason"),
UnorderedElementsAreArray(
expected_browsing_instance_not_swapped_reasons_))
<< location.ToString();
}
void ExpectEvictedAfterCommitted(
std::vector<BackForwardCacheMetrics::EvictedAfterDocumentRestoredReason>
reasons,
base::Location location) {
for (BackForwardCacheMetrics::EvictedAfterDocumentRestoredReason reason :
reasons) {
base::HistogramBase::Sample sample = base::HistogramBase::Sample(reason);
AddSampleToBuckets(&expected_eviction_after_committing_, sample);
}
EXPECT_THAT(histogram_tester_.GetAllSamples(
"BackForwardCache.EvictedAfterDocumentRestoredReason"),
UnorderedElementsAreArray(expected_eviction_after_committing_))
<< location.ToString();
if (!check_all_sites_)
return;
EXPECT_THAT(
histogram_tester_.GetAllSamples(
"BackForwardCache.AllSites.EvictedAfterDocumentRestoredReason"),
UnorderedElementsAreArray(expected_eviction_after_committing_))
<< location.ToString();
}
void EvictByJavaScript(RenderFrameHostImpl* rfh) {
// Run JavaScript on a page in the back-forward cache. The page should be
// evicted. As the frame is deleted, ExecJs returns false without executing.
// Run without user gesture to prevent UpdateUserActivationState message
// being sent back to browser.
EXPECT_FALSE(
ExecJs(rfh, "console.log('hi');", EXECUTE_SCRIPT_NO_USER_GESTURE));
}
void StartRecordingEvents(RenderFrameHostImpl* rfh) {
EXPECT_TRUE(ExecJs(rfh, R"(
window.testObservedEvents = [];
let event_list = [
'visibilitychange',
'pagehide',
'pageshow',
'freeze',
'resume',
'unload',
];
for (event_name of event_list) {
let result = event_name;
window.addEventListener(event_name, event => {
if (event.persisted)
result += '.persisted';
window.testObservedEvents.push('window.' + result);
});
document.addEventListener(event_name,
() => window.testObservedEvents.push('document.' + result));
}
)"));
}
void MatchEventList(RenderFrameHostImpl* rfh,
base::ListValue list,
base::Location location = base::Location::Current()) {
EXPECT_EQ(list, EvalJs(rfh, "window.testObservedEvents"))
<< location.ToString();
}
// Creates a minimal HTTPS server, accessible through https_server().
// Returns a pointer to the server.
net::EmbeddedTestServer* CreateHttpsServer() {
https_server_ = std::make_unique<net::EmbeddedTestServer>(
net::EmbeddedTestServer::TYPE_HTTPS);
https_server_->AddDefaultHandlers(GetTestDataFilePath());
https_server_->SetSSLConfig(net::EmbeddedTestServer::CERT_OK);
return https_server();
}
net::EmbeddedTestServer* https_server() { return https_server_.get(); }
void ExpectTotalCount(base::StringPiece name,
base::HistogramBase::Count count) {
histogram_tester_.ExpectTotalCount(name, count);
}
template <typename T>
void ExpectBucketCount(base::StringPiece name,
T sample,
base::HistogramBase::Count expected_count) {
histogram_tester_.ExpectBucketCount(name, sample, expected_count);
}
template <typename T>
void ExpectUniqueSample(base::StringPiece name,
T sample,
base::HistogramBase::Count expected_count) {
histogram_tester_.ExpectUniqueSample(name, sample, expected_count);
}
// Do not fail this test if a message from a renderer arrives at the browser
// for a cached page.
void DoNotFailForUnexpectedMessagesWhileCached() {
fail_for_unexpected_messages_while_cached_ = false;
}
base::HistogramTester histogram_tester_;
protected:
bool same_site_back_forward_cache_enabled_ = true;
bool skip_same_site_if_unload_exists_ = false;
private:
void AddSampleToBuckets(std::vector<base::Bucket>* buckets,
base::HistogramBase::Sample sample) {
auto it = std::find_if(
buckets->begin(), buckets->end(),
[sample](const base::Bucket& bucket) { return bucket.min == sample; });
if (it == buckets->end()) {
buckets->push_back(base::Bucket(sample, 1));
} else {
it->count++;
}
}
base::test::ScopedFeatureList feature_list_;
FrameTreeVisualizer visualizer_;
std::vector<base::Bucket> expected_outcomes_;
std::vector<base::Bucket> expected_not_restored_;
std::vector<base::Bucket> expected_blocklisted_features_;
std::vector<base::Bucket> expected_disabled_reasons_;
std::vector<base::Bucket> expected_browsing_instance_not_swapped_reasons_;
std::vector<base::Bucket> expected_eviction_after_committing_;
std::unique_ptr<net::EmbeddedTestServer> https_server_;
std::unordered_map<base::Feature,
std::map<std::string, std::string>,
FeatureHash,
FeatureEqualOperator>
features_with_params_;
std::vector<base::Feature> disabled_features_;
std::vector<UkmMetrics> expected_ukm_outcomes_;
std::vector<UkmMetrics> expected_ukm_not_restored_reasons_;
std::unique_ptr<ukm::TestAutoSetUkmRecorder> ukm_recorder_;
// Indicates whether metrics for all sites regardless of the domains are
// checked or not.
bool check_all_sites_ = true;
// Whether we should fail the test if a message arrived at the browser from a
// renderer for a bfcached page.
bool fail_for_unexpected_messages_while_cached_ = true;
};
// Match RenderFrameHostImpl* that are in the BackForwardCache.
MATCHER(InBackForwardCache, "") {
return arg->IsInBackForwardCache();
}
// Match RenderFrameDeleteObserver* which observed deletion of the RenderFrame.
MATCHER(Deleted, "") {
return arg->deleted();
}
// Helper function to pass an initializer list to the EXPECT_THAT macro. This is
// indeed the identity function.
std::initializer_list<RenderFrameHostImpl*> Elements(
std::initializer_list<RenderFrameHostImpl*> t) {
return t;
}
// Execute a custom callback when navigation is ready to commit. This is
// useful for simulating race conditions happening when a page enters the
// BackForwardCache and receive inflight messages sent when it wasn't frozen
// yet.
class ReadyToCommitNavigationCallback : public WebContentsObserver {
public:
ReadyToCommitNavigationCallback(
WebContents* content,
base::OnceCallback<void(NavigationHandle*)> callback)
: WebContentsObserver(content), callback_(std::move(callback)) {}
private:
// WebContentsObserver:
void ReadyToCommitNavigation(NavigationHandle* navigation_handle) override {
if (callback_)
std::move(callback_).Run(navigation_handle);
}
base::OnceCallback<void(NavigationHandle*)> callback_;
DISALLOW_COPY_AND_ASSIGN(ReadyToCommitNavigationCallback);
};
class FirstVisuallyNonEmptyPaintObserver : public WebContentsObserver {
public:
explicit FirstVisuallyNonEmptyPaintObserver(WebContents* contents)
: WebContentsObserver(contents) {}
void DidFirstVisuallyNonEmptyPaint() override {
if (observed_)
return;
observed_ = true;
run_loop_.Quit();
}
bool did_fire() const { return observed_; }
void Wait() { run_loop_.Run(); }
private:
bool observed_ = false;
base::RunLoop run_loop_{base::RunLoop::Type::kNestableTasksAllowed};
};
void WaitForFirstVisuallyNonEmptyPaint(WebContents* contents) {
if (contents->CompletedFirstVisuallyNonEmptyPaint())
return;
FirstVisuallyNonEmptyPaintObserver observer(contents);
observer.Wait();
}
class ThemeColorObserver : public WebContentsObserver {
public:
explicit ThemeColorObserver(WebContents* contents)
: WebContentsObserver(contents) {}
void DidChangeThemeColor() override { observed_ = true; }
bool did_fire() const { return observed_; }
private:
bool observed_ = false;
};
class DOMContentLoadedObserver : public WebContentsObserver {
public:
explicit DOMContentLoadedObserver(RenderFrameHostImpl* render_frame_host)
: WebContentsObserver(
WebContents::FromRenderFrameHost(render_frame_host)),
render_frame_host_(render_frame_host) {}
void DOMContentLoaded(RenderFrameHost* render_frame_host) override {
if (render_frame_host_ == render_frame_host)
run_loop_.Quit();
}
void Wait() {
if (render_frame_host_->IsDOMContentLoaded())
run_loop_.Quit();
run_loop_.Run();
}
private:
RenderFrameHostImpl* render_frame_host_;
base::RunLoop run_loop_;
};
void WaitForDOMContentLoaded(RenderFrameHostImpl* rfh) {
DOMContentLoadedObserver observer(rfh);
observer.Wait();
}
class PageLifecycleStateManagerTestDelegate
: public PageLifecycleStateManager::TestDelegate {
public:
explicit PageLifecycleStateManagerTestDelegate(
PageLifecycleStateManager* manager)
: manager_(manager) {
manager->SetDelegateForTesting(this);
}
~PageLifecycleStateManagerTestDelegate() override {
if (manager_)
manager_->SetDelegateForTesting(nullptr);
}
void WaitForInBackForwardCacheAck() {
DCHECK(manager_);
if (manager_->last_acknowledged_state().is_in_back_forward_cache) {
return;
}
base::RunLoop loop;
store_in_back_forward_cache_ack_received_ = loop.QuitClosure();
loop.Run();
}
void OnStoreInBackForwardCacheSent(base::OnceClosure cb) {
store_in_back_forward_cache_sent_ = std::move(cb);
}
void OnDisableJsEvictionSent(base::OnceClosure cb) {
disable_eviction_sent_ = std::move(cb);
}
void OnRestoreFromBackForwardCacheSent(base::OnceClosure cb) {
restore_from_back_forward_cache_sent_ = std::move(cb);
}
private:
void OnLastAcknowledgedStateChanged(
const blink::mojom::PageLifecycleState& old_state,
const blink::mojom::PageLifecycleState& new_state) override {
if (store_in_back_forward_cache_ack_received_ &&
new_state.is_in_back_forward_cache)
std::move(store_in_back_forward_cache_ack_received_).Run();
}
void OnUpdateSentToRenderer(
const blink::mojom::PageLifecycleState& new_state) override {
if (store_in_back_forward_cache_sent_ &&
new_state.is_in_back_forward_cache) {
std::move(store_in_back_forward_cache_sent_).Run();
}
if (disable_eviction_sent_ && new_state.eviction_enabled == false) {
std::move(disable_eviction_sent_).Run();
}
if (restore_from_back_forward_cache_sent_ &&
!new_state.is_in_back_forward_cache) {
std::move(restore_from_back_forward_cache_sent_).Run();
}
}
void OnDeleted() override { manager_ = nullptr; }
PageLifecycleStateManager* manager_;
base::OnceClosure store_in_back_forward_cache_sent_;
base::OnceClosure store_in_back_forward_cache_ack_received_;
base::OnceClosure restore_from_back_forward_cache_sent_;
base::OnceClosure disable_eviction_sent_;
};
class FakeIdleTimeProvider : public IdleManager::IdleTimeProvider {
public:
FakeIdleTimeProvider() = default;
~FakeIdleTimeProvider() override = default;
FakeIdleTimeProvider(const FakeIdleTimeProvider&) = delete;
FakeIdleTimeProvider& operator=(const FakeIdleTimeProvider&) = delete;
base::TimeDelta CalculateIdleTime() override {
return base::TimeDelta::FromSeconds(0);
}
bool CheckIdleStateIsLocked() override { return false; }
};
} // namespace
// Navigate from A to B and go back.
IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTest, Basic) {
ASSERT_TRUE(embedded_test_server()->Start());
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html"));
url::Origin origin_a = url::Origin::Create(url_a);
url::Origin origin_b = url::Origin::Create(url_b);
// 1) Navigate to A.
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = current_frame_host();
RenderFrameDeletedObserver delete_observer_rfh_a(rfh_a);
// 2) Navigate to B.
EXPECT_TRUE(NavigateToURL(shell(), url_b));
RenderFrameHostImpl* rfh_b = current_frame_host();
RenderFrameDeletedObserver delete_observer_rfh_b(rfh_b);
EXPECT_FALSE(delete_observer_rfh_a.deleted());
EXPECT_TRUE(rfh_a->IsInBackForwardCache());
EXPECT_EQ(rfh_a->GetVisibilityState(), PageVisibilityState::kHidden);
EXPECT_EQ(origin_a, rfh_a->GetLastCommittedOrigin());
EXPECT_EQ(origin_b, rfh_b->GetLastCommittedOrigin());
EXPECT_FALSE(rfh_b->IsInBackForwardCache());
EXPECT_EQ(rfh_b->GetVisibilityState(), PageVisibilityState::kVisible);
// 3) Go back to A.
web_contents()->GetController().GoBack();
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
EXPECT_FALSE(delete_observer_rfh_a.deleted());
EXPECT_FALSE(delete_observer_rfh_b.deleted());
EXPECT_EQ(origin_a, rfh_a->GetLastCommittedOrigin());
EXPECT_EQ(origin_b, rfh_b->GetLastCommittedOrigin());
EXPECT_EQ(rfh_a, current_frame_host());
EXPECT_FALSE(rfh_a->IsInBackForwardCache());
EXPECT_EQ(rfh_a->GetVisibilityState(), PageVisibilityState::kVisible);
EXPECT_TRUE(rfh_b->IsInBackForwardCache());
EXPECT_EQ(rfh_b->GetVisibilityState(), PageVisibilityState::kHidden);
ExpectOutcome(BackForwardCacheMetrics::HistoryNavigationOutcome::kRestored,
FROM_HERE);
}
// Navigate from A to B and go back.
IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTest, BasicDocumentInitiated) {
ASSERT_TRUE(embedded_test_server()->Start());
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html"));
// 1) Navigate to A.
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = current_frame_host();
RenderFrameDeletedObserver delete_observer_rfh_a(rfh_a);
// 2) Navigate to B.
EXPECT_TRUE(ExecJs(shell(), JsReplace("location = $1;", url_b.spec())));
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
RenderFrameHostImpl* rfh_b = current_frame_host();
RenderFrameDeletedObserver delete_observer_rfh_b(rfh_b);
EXPECT_FALSE(delete_observer_rfh_a.deleted());
EXPECT_TRUE(rfh_a->IsInBackForwardCache());
EXPECT_FALSE(rfh_b->IsInBackForwardCache());
// The two pages are using different BrowsingInstances.
EXPECT_FALSE(rfh_a->GetSiteInstance()->IsRelatedSiteInstance(
rfh_b->GetSiteInstance()));
// 3) Go back to A.
EXPECT_TRUE(ExecJs(shell(), "history.back();"));
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
EXPECT_FALSE(delete_observer_rfh_a.deleted());
EXPECT_FALSE(delete_observer_rfh_b.deleted());
EXPECT_EQ(rfh_a, current_frame_host());
EXPECT_FALSE(rfh_a->IsInBackForwardCache());
EXPECT_TRUE(rfh_b->IsInBackForwardCache());
ExpectOutcome(BackForwardCacheMetrics::HistoryNavigationOutcome::kRestored,
FROM_HERE);
}
// Navigate from back and forward repeatedly.
IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTest,
NavigateBackForwardRepeatedly) {
// Do not check for unexpected messages because the input task queue is not
// currently frozen, causing flakes in this test: crbug.com/1099395.
DoNotFailForUnexpectedMessagesWhileCached();
ASSERT_TRUE(embedded_test_server()->Start());
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html"));
// 1) Navigate to A.
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = current_frame_host();
RenderFrameDeletedObserver delete_observer_rfh_a(rfh_a);
// 2) Navigate to B.
EXPECT_TRUE(NavigateToURL(shell(), url_b));
RenderFrameHostImpl* rfh_b = current_frame_host();
RenderFrameDeletedObserver delete_observer_rfh_b(rfh_b);
EXPECT_TRUE(rfh_a->IsInBackForwardCache());
EXPECT_FALSE(rfh_b->IsInBackForwardCache());
// 3) Go back to A.
web_contents()->GetController().GoBack();
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
EXPECT_EQ(rfh_a, current_frame_host());
EXPECT_FALSE(rfh_a->IsInBackForwardCache());
EXPECT_TRUE(rfh_b->IsInBackForwardCache());
ExpectOutcome(BackForwardCacheMetrics::HistoryNavigationOutcome::kRestored,
FROM_HERE);
// 4) Go forward to B.
web_contents()->GetController().GoForward();
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
EXPECT_EQ(rfh_b, current_frame_host());
EXPECT_TRUE(rfh_a->IsInBackForwardCache());
EXPECT_FALSE(rfh_b->IsInBackForwardCache());
ExpectOutcome(BackForwardCacheMetrics::HistoryNavigationOutcome::kRestored,
FROM_HERE);
// 5) Go back to A.
web_contents()->GetController().GoBack();
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
EXPECT_EQ(rfh_a, current_frame_host());
EXPECT_FALSE(rfh_a->IsInBackForwardCache());
EXPECT_TRUE(rfh_b->IsInBackForwardCache());
ExpectOutcome(BackForwardCacheMetrics::HistoryNavigationOutcome::kRestored,
FROM_HERE);
// 6) Go forward to B.
web_contents()->GetController().GoForward();
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
EXPECT_EQ(rfh_b, current_frame_host());
EXPECT_TRUE(rfh_a->IsInBackForwardCache());
EXPECT_FALSE(rfh_b->IsInBackForwardCache());
EXPECT_FALSE(delete_observer_rfh_a.deleted());
EXPECT_FALSE(delete_observer_rfh_b.deleted());
ExpectOutcome(BackForwardCacheMetrics::HistoryNavigationOutcome::kRestored,
FROM_HERE);
}
// The current page can't enter the BackForwardCache if another page can script
// it. This can happen when one document opens a popup using window.open() for
// instance. It prevents the BackForwardCache from being used.
IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTest, WindowOpen) {
// This test assumes cross-site navigation staying in the same
// BrowsingInstance to use a different SiteInstance. Otherwise, it will
// timeout at step 2).
if (!SiteIsolationPolicy::UseDedicatedProcessesForAllSites())
return;
ASSERT_TRUE(embedded_test_server()->Start());
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html"));
// 1) Navigate to A and open a popup.
EXPECT_TRUE(NavigateToURL(shell(), url_a));
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
RenderFrameHostImpl* rfh_a = current_frame_host();
RenderFrameDeletedObserver delete_observer_rfh_a(rfh_a);
EXPECT_EQ(1u, rfh_a->GetSiteInstance()->GetRelatedActiveContentsCount());
Shell* popup = OpenPopup(rfh_a, url_a, "");
EXPECT_EQ(2u, rfh_a->GetSiteInstance()->GetRelatedActiveContentsCount());
// 2) Navigate to B. The previous document can't enter the BackForwardCache,
// because of the popup.
EXPECT_TRUE(ExecJs(rfh_a, JsReplace("location = $1;", url_b.spec())));
delete_observer_rfh_a.WaitUntilDeleted();
RenderFrameHostImpl* rfh_b = current_frame_host();
EXPECT_EQ(2u, rfh_b->GetSiteInstance()->GetRelatedActiveContentsCount());
// 3) Go back to A. The previous document can't enter the BackForwardCache,
// because of the popup.
RenderFrameDeletedObserver delete_observer_rfh_b(rfh_b);
EXPECT_TRUE(ExecJs(rfh_b, "history.back();"));
delete_observer_rfh_b.WaitUntilDeleted();
// 4) Make the popup drop the window.opener connection. It happens when the
// user does an omnibox-initiated navigation, which happens in a new
// BrowsingInstance.
RenderFrameHostImpl* rfh_a_new = current_frame_host();
EXPECT_EQ(2u, rfh_a_new->GetSiteInstance()->GetRelatedActiveContentsCount());
EXPECT_TRUE(NavigateToURL(popup, url_b));
EXPECT_EQ(1u, rfh_a_new->GetSiteInstance()->GetRelatedActiveContentsCount());
// 5) Navigate to B again. As the scripting relationship with the popup is
// now severed, the current page (|rfh_a_new|) can enter back-forward cache.
RenderFrameDeletedObserver delete_observer_rfh_a_new(rfh_a_new);
EXPECT_TRUE(ExecJs(rfh_a_new, JsReplace("location = $1;", url_b.spec())));
EXPECT_TRUE(WaitForLoadStop(web_contents()));
EXPECT_FALSE(delete_observer_rfh_a_new.deleted());
EXPECT_TRUE(rfh_a_new->IsInBackForwardCache());
// 6) Go back to A. The current document can finally enter the
// BackForwardCache, because it is alone in its BrowsingInstance and has never
// been related to any other document.
RenderFrameHostImpl* rfh_b_new = current_frame_host();
RenderFrameDeletedObserver delete_observer_rfh_b_new(rfh_b_new);
EXPECT_TRUE(ExecJs(rfh_b_new, "history.back();"));
EXPECT_TRUE(WaitForLoadStop(web_contents()));
EXPECT_FALSE(delete_observer_rfh_b_new.deleted());
EXPECT_TRUE(rfh_b_new->IsInBackForwardCache());
}
// Navigate from A(B) to C and go back.
IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTest, BasicIframe) {
ASSERT_TRUE(embedded_test_server()->Start());
GURL url_a(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b)"));
GURL url_c(embedded_test_server()->GetURL("c.com", "/title1.html"));
// 1) Navigate to A(B).
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = current_frame_host();
RenderFrameHostImpl* rfh_b = rfh_a->child_at(0)->current_frame_host();
RenderFrameDeletedObserver delete_observer_rfh_a(rfh_a);
RenderFrameDeletedObserver delete_observer_rfh_b(rfh_b);
// 2) Navigate to C.
EXPECT_TRUE(NavigateToURL(shell(), url_c));
RenderFrameHostImpl* rfh_c = current_frame_host();
RenderFrameDeletedObserver delete_observer_rfh_c(rfh_c);
EXPECT_FALSE(delete_observer_rfh_a.deleted());
EXPECT_FALSE(delete_observer_rfh_b.deleted());
EXPECT_TRUE(rfh_a->IsInBackForwardCache());
EXPECT_TRUE(rfh_b->IsInBackForwardCache());
EXPECT_FALSE(rfh_c->IsInBackForwardCache());
// 3) Go back to A(B).
web_contents()->GetController().GoBack();
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
EXPECT_FALSE(delete_observer_rfh_a.deleted());
EXPECT_FALSE(delete_observer_rfh_b.deleted());
EXPECT_FALSE(delete_observer_rfh_c.deleted());
EXPECT_EQ(rfh_a, current_frame_host());
EXPECT_FALSE(rfh_a->IsInBackForwardCache());