File: history_tab_helper_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 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 (671 lines) | stat: -rw-r--r-- 28,174 bytes parent folder | download | duplicates (5)
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
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/history/history_tab_helper.h"

#include <memory>
#include <set>
#include <string>
#include <utility>

#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/cancelable_task_tracker.h"
#include "base/test/bind.h"
#include "build/build_config.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "chrome/test/base/testing_profile.h"
#include "components/history/core/browser/history_constants.h"
#include "components/history/core/browser/history_service.h"
#include "components/history/core/browser/history_types.h"
#include "components/history/core/browser/url_row.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/mock_navigation_handle.h"
#include "content/public/test/navigation_simulator.h"
#include "content/public/test/prerender_test_util.h"
#include "content/public/test/web_contents_tester.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/features.h"
#include "ui/base/page_transition_types.h"

#if BUILDFLAG(IS_ANDROID)
#include "chrome/browser/feed/feed_service_factory.h"
#include "components/feed/core/v2/public/feed_service.h"
#include "components/feed/core/v2/public/test/stub_feed_api.h"
#endif  // BUILDFLAG(IS_ANDROID)

using testing::NiceMock;

namespace {

#if BUILDFLAG(IS_ANDROID)
class TestFeedApi : public feed::StubFeedApi {
 public:
  MOCK_METHOD1(WasUrlRecentlyNavigatedFromFeed, bool(const GURL&));
};
#endif  // BUILDFLAG(IS_ANDROID)

}  // namespace

class HistoryTabHelperTest : public ChromeRenderViewHostTestHarness {
 protected:
  HistoryTabHelperTest() = default;

  HistoryTabHelperTest(const HistoryTabHelperTest&) = delete;
  HistoryTabHelperTest& operator=(const HistoryTabHelperTest&) = delete;

  // ChromeRenderViewHostTestHarness:
  void SetUp() override {
    ChromeRenderViewHostTestHarness::SetUp();
#if BUILDFLAG(IS_ANDROID)
    feed::FeedServiceFactory::GetInstance()->SetTestingFactory(
        profile(),
        base::BindLambdaForTesting([&](content::BrowserContext* context) {
          std::unique_ptr<KeyedService> result =
              feed::FeedService::CreateForTesting(&test_feed_api_);
          return result;
        }));
#endif  // BUILDFLAG(IS_ANDROID)
    history_service_ = HistoryServiceFactory::GetForProfile(
        profile(), ServiceAccessType::IMPLICIT_ACCESS);
    ASSERT_TRUE(history_service_);
    history_service_->AddPage(
        page_url_, base::Time::Now(), /*context_id=*/0,
        /*nav_entry_id=*/0,
        /*referrer=*/GURL(), history::RedirectList(), ui::PAGE_TRANSITION_TYPED,
        history::SOURCE_BROWSED, /*did_replace_entry=*/false);
    HistoryTabHelper::CreateForWebContents(web_contents());
    HistoryTabHelper::FromWebContents(web_contents())
        ->SetForceEligibleTabForTesting(true);
  }

  void TearDown() override {
    // Drop unowned reference before destroying object that owns it.
    history_service_ = nullptr;
    ChromeRenderViewHostTestHarness::TearDown();
  }

  TestingProfile::TestingFactories GetTestingFactories() const override {
    return {TestingProfile::TestingFactory{
        HistoryServiceFactory::GetInstance(),
        HistoryServiceFactory::GetDefaultFactory()}};
  }

  HistoryTabHelper* history_tab_helper() {
    return HistoryTabHelper::FromWebContents(web_contents());
  }

  content::WebContentsTester* web_contents_tester() {
    return content::WebContentsTester::For(web_contents());
  }

  std::string QueryPageTitleFromHistory(const GURL& url) {
    std::string title;
    base::RunLoop loop;
    history_service_->QueryURL(
        url, /*want_visits=*/false,
        base::BindLambdaForTesting([&](history::QueryURLResult result) {
          EXPECT_TRUE(result.success);
          title = base::UTF16ToUTF8(result.row.title());
          loop.Quit();
        }),
        &tracker_);
    loop.Run();
    return title;
  }

  base::TimeDelta QueryLastVisitDurationFromHistory(const GURL& url) {
    base::TimeDelta visit_duration;
    base::RunLoop loop;
    history_service_->QueryURL(
        url, /*want_visits=*/true,
        base::BindLambdaForTesting([&](history::QueryURLResult result) {
          EXPECT_TRUE(result.success);
          if (!result.visits.empty()) {
            visit_duration = result.visits.back().visit_duration;
          }
          loop.Quit();
        }),
        &tracker_);
    loop.Run();
    return visit_duration;
  }

  history::MostVisitedURLList QueryMostVisitedURLs() {
    history::MostVisitedURLList result;
    std::string title;
    base::RunLoop loop;
    history_service_->QueryMostVisitedURLs(
        /*result_count=*/10,
        base::BindLambdaForTesting([&](history::MostVisitedURLList v) {
          result = v;
          loop.Quit();
        }),
        &tracker_);
    loop.Run();
    return result;
  }

  std::set<GURL> GetMostVisitedURLSet() {
    std::set<GURL> result;
    for (const history::MostVisitedURL& mv_url : QueryMostVisitedURLs()) {
      result.insert(mv_url.url);
    }
    return result;
  }

  const GURL page_url_ = GURL("http://foo.com");

 protected:
  base::CancelableTaskTracker tracker_;
  raw_ptr<history::HistoryService> history_service_;
#if BUILDFLAG(IS_ANDROID)
  TestFeedApi test_feed_api_;
#endif  // BUILDFLAG(IS_ANDROID)
};

TEST_F(HistoryTabHelperTest, ShouldUpdateTitleInHistory) {
  web_contents_tester()->NavigateAndCommit(page_url_);

  content::NavigationEntry* entry =
      web_contents()->GetController().GetLastCommittedEntry();
  ASSERT_NE(nullptr, entry);

  web_contents()->UpdateTitleForEntry(entry, u"title1");
  EXPECT_EQ("title1", QueryPageTitleFromHistory(page_url_));
}

TEST_F(HistoryTabHelperTest, ShouldLimitTitleUpdatesPerPage) {
  web_contents_tester()->NavigateAndCommit(page_url_);

  content::NavigationEntry* entry =
      web_contents()->GetController().GetLastCommittedEntry();
  ASSERT_NE(nullptr, entry);

  // The first 10 title updates are accepted and update history, as per
  // history::kMaxTitleChanges.
  for (int i = 1; i <= history::kMaxTitleChanges; ++i) {
    const std::string title = base::StringPrintf("title%d", i);
    web_contents()->UpdateTitleForEntry(entry, base::UTF8ToUTF16(title));
  }

  ASSERT_EQ("title10", QueryPageTitleFromHistory(page_url_));

  // Further updates should be ignored.
  web_contents()->UpdateTitleForEntry(entry, u"title11");
  EXPECT_EQ("title10", QueryPageTitleFromHistory(page_url_));
}

TEST_F(HistoryTabHelperTest, ShouldUpdateVisitDurationInHistory) {
  const GURL url1("https://url1.com");
  const GURL url2("https://url2.com");

  web_contents_tester()->NavigateAndCommit(url1);
  // The duration shouldn't be set yet, since the visit is still open.
  EXPECT_TRUE(QueryLastVisitDurationFromHistory(url1).is_zero());

  // Once the user navigates on, the duration of the first visit should be
  // populated.
  web_contents_tester()->NavigateAndCommit(url2);
  EXPECT_FALSE(QueryLastVisitDurationFromHistory(url1).is_zero());
  EXPECT_TRUE(QueryLastVisitDurationFromHistory(url2).is_zero());

  // Closing the tab should finish the second visit and populate its duration.
  DeleteContents();
  EXPECT_FALSE(QueryLastVisitDurationFromHistory(url2).is_zero());
}

TEST_F(HistoryTabHelperTest, CreateAddPageArgsReferringURLMainFrameNoReferrer) {
  NiceMock<content::MockNavigationHandle> navigation_handle(web_contents());
  navigation_handle.set_redirect_chain({GURL("https://someurl.com")});
  navigation_handle.set_previous_primary_main_frame_url(
      GURL("http://previousurl.com"));
  history::HistoryAddPageArgs args =
      history_tab_helper()->CreateHistoryAddPageArgs(
          GURL("http://someurl.com"), base::Time(), 1, &navigation_handle);

  EXPECT_TRUE(args.referrer.is_empty());
}

TEST_F(HistoryTabHelperTest, CreateAddPageArgsHistoryTitleAfterPageReload) {
  NiceMock<content::MockNavigationHandle> navigation_handle(web_contents());
  navigation_handle.set_redirect_chain({GURL("https://someurl.com")});
  navigation_handle.set_previous_primary_main_frame_url(
      GURL("http://previousurl.com"));
  navigation_handle.set_reload_type(content::ReloadType::NORMAL);
  history::HistoryAddPageArgs args =
      history_tab_helper()->CreateHistoryAddPageArgs(
          GURL("http://someurl.com"), base::Time(), 1, &navigation_handle);

  EXPECT_EQ(args.title, web_contents()->GetTitle());
}

TEST_F(HistoryTabHelperTest,
       CreateAddPageArgsHistoryTitleAfterPageReloadBypassingCache) {
  NiceMock<content::MockNavigationHandle> navigation_handle(web_contents());
  navigation_handle.set_redirect_chain({GURL("https://someurl.com")});
  navigation_handle.set_previous_primary_main_frame_url(
      GURL("http://previousurl.com"));
  navigation_handle.set_reload_type(content::ReloadType::BYPASSING_CACHE);
  history::HistoryAddPageArgs args =
      history_tab_helper()->CreateHistoryAddPageArgs(
          GURL("http://someurl.com"), base::Time(), 1, &navigation_handle);

  EXPECT_EQ(args.title, web_contents()->GetTitle());
}

TEST_F(HistoryTabHelperTest,
       CreateAddPageArgsReferringURLMainFrameSameOriginReferrer) {
  NiceMock<content::MockNavigationHandle> navigation_handle(web_contents());
  navigation_handle.set_redirect_chain({GURL("https://someurl.com")});
  navigation_handle.set_previous_primary_main_frame_url(
      GURL("http://previousurl.com/abc"));
  auto referrer = blink::mojom::Referrer::New();
  referrer->url = navigation_handle.GetPreviousPrimaryMainFrameURL()
                      .DeprecatedGetOriginAsURL();
  referrer->policy = network::mojom::ReferrerPolicy::kDefault;
  navigation_handle.SetReferrer(std::move(referrer));
  history::HistoryAddPageArgs args =
      history_tab_helper()->CreateHistoryAddPageArgs(
          GURL("http://someurl.com"), base::Time(), 1, &navigation_handle);

  EXPECT_EQ(args.referrer, GURL("http://previousurl.com/abc"));
}

TEST_F(HistoryTabHelperTest,
       CreateAddPageArgsReferringURLMainFrameSameOriginReferrerDifferentPath) {
  NiceMock<content::MockNavigationHandle> navigation_handle(web_contents());
  navigation_handle.set_redirect_chain({GURL("https://someurl.com")});
  navigation_handle.set_previous_primary_main_frame_url(
      GURL("http://previousurl.com/def"));
  auto referrer = blink::mojom::Referrer::New();
  referrer->url = GURL("http://previousurl.com/abc");
  referrer->policy = network::mojom::ReferrerPolicy::kDefault;
  navigation_handle.SetReferrer(std::move(referrer));
  history::HistoryAddPageArgs args =
      history_tab_helper()->CreateHistoryAddPageArgs(
          GURL("http://someurl.com"), base::Time(), 1, &navigation_handle);

  EXPECT_EQ(args.referrer, GURL("http://previousurl.com/abc"));
}

TEST_F(HistoryTabHelperTest,
       CreateAddPageArgsReferringURLMainFrameCrossOriginReferrer) {
  NiceMock<content::MockNavigationHandle> navigation_handle(web_contents());
  auto referrer = blink::mojom::Referrer::New();
  referrer->url = GURL("http://crossorigin.com");
  referrer->policy = network::mojom::ReferrerPolicy::kDefault;
  navigation_handle.SetReferrer(std::move(referrer));
  navigation_handle.set_redirect_chain({GURL("https://someurl.com")});
  navigation_handle.set_previous_primary_main_frame_url(
      GURL("http://previousurl.com"));
  history::HistoryAddPageArgs args =
      history_tab_helper()->CreateHistoryAddPageArgs(
          GURL("http://someurl.com"), base::Time(), 1, &navigation_handle);

  EXPECT_EQ(args.referrer, GURL("http://crossorigin.com"));
}

TEST_F(HistoryTabHelperTest, CreateAddPageArgsReferringURLNotMainFrame) {
  content::RenderFrameHostTester* main_rfh_tester =
      content::RenderFrameHostTester::For(main_rfh());
  main_rfh_tester->InitializeRenderFrameIfNeeded();
  content::RenderFrameHost* subframe = main_rfh_tester->AppendChild("subframe");
  NiceMock<content::MockNavigationHandle> navigation_handle(
      GURL("http://someurl.com"), subframe);
  navigation_handle.set_redirect_chain({GURL("https://someurl.com")});
  navigation_handle.set_previous_primary_main_frame_url(
      GURL("http://previousurl.com"));
  history::HistoryAddPageArgs args =
      history_tab_helper()->CreateHistoryAddPageArgs(
          GURL("http://someurl.com"), base::Time(), 1, &navigation_handle);

  // Should default to referrer if not in main frame and the referrer should not
  // be sent to the arbitrary previous URL that is set.
  EXPECT_NE(args.referrer, GURL("http://previousurl.com"));
}

TEST_F(HistoryTabHelperTest, CreateAddPageArgsFrameUrlWithValidInitiator) {
  // Create our initiator RenderFrameHost.
  content::RenderFrameHostTester* main_rfh_tester =
      content::RenderFrameHostTester::For(main_rfh());
  main_rfh_tester->InitializeRenderFrameIfNeeded();
  content::RenderFrameHost* subframe = main_rfh_tester->AppendChild("subframe");
  const GURL initiator_url = GURL("http://previousurl.com");

  // Prepare a mock navigation from that initiator frame.
  const GURL test_url = GURL("http://testurl.com");
  NiceMock<content::MockNavigationHandle> navigation_handle(test_url, subframe);
  navigation_handle.set_initiator_origin(url::Origin::Create(initiator_url));
  // Simulate a navigation that is marked no-referrer (the value of which we
  // should ignore in favor of initiator origin).
  auto referrer = blink::mojom::Referrer::New();
  referrer->url = GURL();
  referrer->policy = network::mojom::ReferrerPolicy::kNever;
  navigation_handle.SetReferrer(std::move(referrer));
  history::HistoryAddPageArgs args =
      history_tab_helper()->CreateHistoryAddPageArgs(test_url, base::Time(), 1,
                                                     &navigation_handle);

  // `frame_url` should default to the last committed URL of the initiator
  // RenderFrameHost.
  ASSERT_TRUE(args.frame_url.has_value());
  EXPECT_EQ(args.frame_url.value(), initiator_url);
}

TEST_F(HistoryTabHelperTest, CreateAddPageArgsFrameUrlWithInvalidInitiator) {
  // Create our initiator RenderFrameHost but do not set the initiator origin.
  // This simulates an invalid or missing initiator frame.
  content::RenderFrameHostTester* main_rfh_tester =
      content::RenderFrameHostTester::For(main_rfh());
  main_rfh_tester->InitializeRenderFrameIfNeeded();
  content::RenderFrameHost* subframe = main_rfh_tester->AppendChild("subframe");

  // Prepare a mock navigation from that initiator frame.
  const GURL test_url = GURL("http://testurl.com");
  NiceMock<content::MockNavigationHandle> navigation_handle(test_url, subframe);
  // Set a valid referrer with a default referrer policy.
  auto referrer = blink::mojom::Referrer::New();
  referrer->url = test_url;
  referrer->policy = network::mojom::ReferrerPolicy::kDefault;
  navigation_handle.SetReferrer(std::move(referrer));
  history::HistoryAddPageArgs args =
      history_tab_helper()->CreateHistoryAddPageArgs(test_url, base::Time(), 1,
                                                     &navigation_handle);

  // `frame_url` should fall back on referrer when we have an invalid initiator
  // origin.
  ASSERT_TRUE(args.frame_url.has_value());
  EXPECT_EQ(args.frame_url.value(), test_url);
}

TEST_F(HistoryTabHelperTest, CreateAddPageArgsHasOpenerWebContentsFirstPage) {
  std::unique_ptr<content::WebContents> opener_web_contents =
      CreateTestWebContents();
  content::WebContentsTester* opener_web_contents_tester =
      content::WebContentsTester::For(opener_web_contents.get());
  opener_web_contents_tester->NavigateAndCommit(
      GURL("https://opensnewtab.com/"));
  HistoryTabHelper::CreateForWebContents(opener_web_contents.get());
  HistoryTabHelper::FromWebContents(opener_web_contents.get())
      ->DidOpenRequestedURL(web_contents(), nullptr,
                            GURL("http://someurl.com/"), content::Referrer(),
                            WindowOpenDisposition::NEW_WINDOW,
                            ui::PAGE_TRANSITION_LINK, false, true);

  content::RenderFrameHostTester* main_rfh_tester =
      content::RenderFrameHostTester::For(main_rfh());
  main_rfh_tester->InitializeRenderFrameIfNeeded();
  content::RenderFrameHost* subframe = main_rfh_tester->AppendChild("subframe");
  NiceMock<content::MockNavigationHandle> navigation_handle(
      GURL("http://someurl.com"), subframe);
  navigation_handle.set_redirect_chain({GURL("http://someurl.com")});
  history::HistoryAddPageArgs args =
      history_tab_helper()->CreateHistoryAddPageArgs(
          GURL("http://someurl.com"), base::Time(), 1, &navigation_handle);

  ASSERT_TRUE(args.opener.has_value());
  EXPECT_EQ(args.opener->url, GURL("https://opensnewtab.com/"));

  // When previous primary main frame is empty and our navigation type is LINK,
  // the top_level_url should be replaced by a valid opener URL.
  ASSERT_TRUE(args.top_level_url.has_value());
  EXPECT_EQ(args.top_level_url.value(), args.opener->url);
}

TEST_F(HistoryTabHelperTest, CreateAddPageArgsHasLiveOriginalOpenerChain) {
  // Prepare the original opener WebContents that will serve as the root of the
  // live original opener chain.
  std::unique_ptr<content::WebContents> live_original_opener =
      CreateTestWebContents();
  content::WebContentsTester* live_original_tester =
      content::WebContentsTester::For(live_original_opener.get());
  live_original_tester->NavigateAndCommit(GURL("https://opensnewtab.com/"));

  // The web_contents() for this test will have an empty opener property
  // but a valid live original opener chain. This mimics behavior such as
  // clicking on a link which opens in a new tab.
  content::WebContentsTester::For(web_contents())
      ->SetOriginalOpener(live_original_opener.get());

  // We want to create a HistoryTabHelper for the WebContents with an empty
  // opener, so the `top_level_url` is forced to be constructed with the live
  // original opener chain instead.
  HistoryTabHelper::CreateForWebContents(web_contents());
  HistoryTabHelper::FromWebContents(web_contents())
      ->DidOpenRequestedURL(web_contents(), nullptr,
                            GURL("http://someurl.com/"), content::Referrer(),
                            WindowOpenDisposition::NEW_WINDOW,
                            ui::PAGE_TRANSITION_LINK, false, true);

  // Preparing the NavigationHandle that HistoryTabHelper will use to construct
  // the HistoryAddPageArgs.
  content::RenderFrameHostTester* main_rfh_tester =
      content::RenderFrameHostTester::For(main_rfh());
  main_rfh_tester->InitializeRenderFrameIfNeeded();
  content::RenderFrameHost* subframe = main_rfh_tester->AppendChild("subframe");
  NiceMock<content::MockNavigationHandle> navigation_handle(
      GURL("http://someurl.com"), subframe);
  navigation_handle.set_redirect_chain({GURL("http://someurl.com")});

  // Construct the HistoryAddPageArgs taking into consideration the WebContents
  // environment and NavigationHandle.
  history::HistoryAddPageArgs args =
      history_tab_helper()->CreateHistoryAddPageArgs(
          GURL("http://someurl.com"), base::Time(), 1, &navigation_handle);

  // When previous primary main frame and opener URLs are invalid, the
  // `top_level_url` should be populated with the live original opener URL.
  ASSERT_TRUE(args.top_level_url.has_value());
  EXPECT_EQ(args.top_level_url.value(), GURL("https://opensnewtab.com/"));
}

TEST_F(HistoryTabHelperTest, CreateAddPageArgsSameDocNavigationUsesOpener) {
  content::RenderFrameHostTester* main_rfh_tester =
      content::RenderFrameHostTester::For(main_rfh());
  main_rfh_tester->InitializeRenderFrameIfNeeded();
  content::RenderFrameHost* subframe = main_rfh_tester->AppendChild("subframe");
  NiceMock<content::MockNavigationHandle> navigation_handle(
      GURL("http://someurl.com"), subframe);
  navigation_handle.set_redirect_chain({GURL("https://someurl.com")});
  navigation_handle.set_previous_primary_main_frame_url(
      GURL("http://previousurl.com"));
  navigation_handle.set_is_same_document(true);
  history::HistoryAddPageArgs args =
      history_tab_helper()->CreateHistoryAddPageArgs(
          GURL("http://someurl.com"), base::Time(), 1, &navigation_handle);

  ASSERT_TRUE(args.opener.has_value());
  EXPECT_EQ(args.opener->url, GURL("http://previousurl.com/"));
}

TEST_F(HistoryTabHelperTest,
       CreateAddPageArgsHasOpenerWebContentsNotFirstPage) {
  std::unique_ptr<content::WebContents> opener_web_contents =
      CreateTestWebContents();
  content::WebContentsTester* opener_web_contents_tester =
      content::WebContentsTester::For(opener_web_contents.get());
  opener_web_contents_tester->NavigateAndCommit(
      GURL("https://opensnewtab.com/"));

  HistoryTabHelper::CreateForWebContents(opener_web_contents.get());
  HistoryTabHelper::FromWebContents(opener_web_contents.get())
      ->DidOpenRequestedURL(web_contents(), nullptr,
                            GURL("http://someurl.com/"), content::Referrer(),
                            WindowOpenDisposition::NEW_WINDOW,
                            ui::PAGE_TRANSITION_LINK, false, true);

  content::RenderFrameHostTester* main_rfh_tester =
      content::RenderFrameHostTester::For(main_rfh());
  main_rfh_tester->InitializeRenderFrameIfNeeded();
  content::RenderFrameHost* subframe = main_rfh_tester->AppendChild("subframe");
  NiceMock<content::MockNavigationHandle> navigation_handle(
      GURL("http://someurl.com/2"), subframe);
  navigation_handle.set_redirect_chain({GURL("http://someurl.com/2")});
  navigation_handle.set_previous_primary_main_frame_url(
      GURL("http://someurl.com"));
  history::HistoryAddPageArgs args =
      history_tab_helper()->CreateHistoryAddPageArgs(
          GURL("http://someurl.com"), base::Time(), 1, &navigation_handle);

  EXPECT_FALSE(args.opener.has_value());

  // When there is a valid previous primary main frame, top-level url should
  // not be overwritten by an opener or live opener chain URL.
  ASSERT_TRUE(args.top_level_url.has_value());
  ASSERT_EQ(args.top_level_url.value(), GURL("http://someurl.com"));
}

TEST_F(HistoryTabHelperTest,
       CreateAddPageArgsPopulatesOnVisitContextAnnotations) {
  NiceMock<content::MockNavigationHandle> navigation_handle(web_contents());
  navigation_handle.set_redirect_chain({GURL("https://someurl.com")});

  std::string raw_response_headers = "HTTP/1.1 234 OK\r\n\r\n";
  scoped_refptr<net::HttpResponseHeaders> response_headers =
      net::HttpResponseHeaders::TryToCreate(raw_response_headers);
  DCHECK(response_headers);
  navigation_handle.set_response_headers(response_headers);

  history::HistoryAddPageArgs args =
      history_tab_helper()->CreateHistoryAddPageArgs(
          GURL("https://someurl.com"), base::Time(), 1, &navigation_handle);

  // Make sure the `context_annotations` are populated.
  ASSERT_TRUE(args.context_annotations.has_value());
  // Most of the actual fields can't be verified here, because the corresponding
  // data sources don't exist in this unit test (e.g. there's no Browser, no
  // other TabHelpers, etc). At least check the response code that was set up
  // above.
  EXPECT_EQ(args.context_annotations->response_code, 234);
}

#if BUILDFLAG(IS_ANDROID)
TEST_F(HistoryTabHelperTest, CreateAddPageArgsPopulatesAppId) {
  NiceMock<content::MockNavigationHandle> navigation_handle(web_contents());
  navigation_handle.set_redirect_chain({GURL("https://someurl.com")});

  std::string raw_response_headers = "HTTP/1.1 234 OK\r\n\r\n";
  scoped_refptr<net::HttpResponseHeaders> response_headers =
      net::HttpResponseHeaders::TryToCreate(raw_response_headers);
  DCHECK(response_headers);
  navigation_handle.set_response_headers(response_headers);

  history_tab_helper()->SetAppId("org.chromium.testapp");

  history::HistoryAddPageArgs args =
      history_tab_helper()->CreateHistoryAddPageArgs(
          GURL("https://someurl.com"), base::Time(), 1, &navigation_handle);

  // Make sure the `app_id` is populated.
  ASSERT_EQ(*args.app_id, "org.chromium.testapp");
}

TEST_F(HistoryTabHelperTest, NonFeedNavigationsDoContributeToMostVisited) {
  GURL new_url("http://newurl.com");

  EXPECT_CALL(test_feed_api_, WasUrlRecentlyNavigatedFromFeed(new_url))
      .WillOnce(testing::Return(false));
  web_contents_tester()->NavigateAndCommit(new_url,
                                           ui::PAGE_TRANSITION_AUTO_BOOKMARK);

  EXPECT_THAT(GetMostVisitedURLSet(), testing::Contains(new_url));
}

TEST_F(HistoryTabHelperTest, FeedNavigationsDoNotContributeToMostVisited) {
  GURL new_url("http://newurl.com");
  EXPECT_CALL(test_feed_api_, WasUrlRecentlyNavigatedFromFeed(new_url))
      .WillOnce(testing::Return(true));
  web_contents_tester()->NavigateAndCommit(new_url,
                                           ui::PAGE_TRANSITION_AUTO_BOOKMARK);

  EXPECT_THAT(GetMostVisitedURLSet(), testing::Not(testing::Contains(new_url)));
}

#endif  // BUILDFLAG(IS_ANDROID)

enum class MPArchType {
  kFencedFrame,
  kPrerender,
};
class HistoryTabHelperMPArchTest
    : public HistoryTabHelperTest,
      public testing::WithParamInterface<MPArchType> {
 public:
  HistoryTabHelperMPArchTest() {
    switch (GetParam()) {
      case MPArchType::kFencedFrame:
        scoped_feature_list_.InitAndEnableFeatureWithParameters(
            blink::features::kFencedFrames,
            {{"implementation_type", "mparch"}});
        break;
      case MPArchType::kPrerender:
        scoped_feature_list_.InitAndDisableFeature(
            // Disable the memory requirement of Prerender2 so the test can run
            // on any bot.
            blink::features::kPrerender2MemoryControls);
        break;
    }
  }
  ~HistoryTabHelperMPArchTest() override = default;

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
};

INSTANTIATE_TEST_SUITE_P(All,
                         HistoryTabHelperMPArchTest,
                         testing::Values(MPArchType::kFencedFrame,
                                         MPArchType::kPrerender));

TEST_P(HistoryTabHelperMPArchTest, DoNotAffectToLimitTitleUpdates) {
  content::test::ScopedPrerenderWebContentsDelegate web_contents_delegate(
      *web_contents());

  web_contents_tester()->NavigateAndCommit(page_url_);

  content::NavigationEntry* entry =
      web_contents()->GetController().GetLastCommittedEntry();
  ASSERT_NE(nullptr, entry);

  // The first 10 title updates are accepted and update history, as per
  // history::kMaxTitleChanges.
  for (int i = 1; i <= history::kMaxTitleChanges; ++i) {
    const std::string title = base::StringPrintf("title%d", i);
    web_contents()->UpdateTitleForEntry(entry, base::UTF8ToUTF16(title));
  }

  ASSERT_EQ("title10", QueryPageTitleFromHistory(page_url_));

  // Further updates should be ignored.
  web_contents()->UpdateTitleForEntry(entry, u"title11");
  EXPECT_EQ("title10", QueryPageTitleFromHistory(page_url_));

  std::unique_ptr<content::NavigationSimulator> simulator;
  if (GetParam() == MPArchType::kFencedFrame) {
    // Navigate a fenced frame.
    GURL fenced_frame_url = GURL("https://fencedframe.com");
    content::RenderFrameHost* fenced_frame_root =
        content::RenderFrameHostTester::For(main_rfh())->AppendFencedFrame();
    simulator = content::NavigationSimulator::CreateRendererInitiated(
        fenced_frame_url, fenced_frame_root);
  } else if (GetParam() == MPArchType::kPrerender) {
    // Navigate a prerendering page.
    const GURL prerender_url = page_url_.Resolve("?prerendering");
    simulator = content::WebContentsTester::For(web_contents())
                    ->AddPrerenderAndStartNavigation(prerender_url);
  }
  ASSERT_NE(nullptr, simulator);
  simulator->Commit();

  // Further updates should be ignored.
  web_contents()->UpdateTitleForEntry(entry, u"title12");
  EXPECT_EQ("title10", QueryPageTitleFromHistory(page_url_));
}