File: tab_restore_service_unittest.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1338 lines) | stat: -rw-r--r-- 51,037 bytes parent folder | download | duplicates (3)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stddef.h>

#include <map>
#include <memory>
#include <optional>
#include <string>
#include <utility>

#include "base/compiler_specific.h"
#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind.h"
#include "base/time/time.h"
#include "base/uuid.h"
#include "chrome/browser/sessions/chrome_tab_restore_service_client.h"
#include "chrome/browser/sessions/exit_type_service.h"
#include "chrome/browser/sessions/session_service.h"
#include "chrome/browser/sessions/session_service_factory.h"
#include "chrome/browser/sessions/session_service_utils.h"
#include "chrome/browser/sessions/tab_restore_service_factory.h"
#include "chrome/browser/sessions/tab_restore_service_load_waiter.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "chrome/test/base/chrome_render_view_test.h"
#include "chrome/test/base/testing_profile.h"
#include "components/history/core/common/pref_names.h"
#include "components/prefs/pref_service.h"
#include "components/sessions/content/content_live_tab.h"
#include "components/sessions/content/content_test_helper.h"
#include "components/sessions/core/serialized_navigation_entry_test_helper.h"
#include "components/sessions/core/session_types.h"
#include "components/sessions/core/tab_restore_service_client.h"
#include "components/sessions/core/tab_restore_service_impl.h"
#include "components/sessions/core/tab_restore_service_observer.h"
#include "components/tab_groups/tab_group_id.h"
#include "components/tab_groups/tab_group_visual_data.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/render_view_test.h"
#include "content/public/test/test_utils.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/user_agent/user_agent_metadata.h"
#include "ui/base/mojom/window_show_state.mojom.h"

typedef sessions::tab_restore::Entry Entry;
typedef sessions::tab_restore::Tab Tab;
typedef sessions::tab_restore::Window Window;
typedef std::map<std::string, std::string> ExtraData;

using content::NavigationEntry;
using content::WebContentsTester;
using sessions::ContentTestHelper;
using sessions::SerializedNavigationEntry;
using sessions::SerializedNavigationEntryTestHelper;

using ::testing::_;
using ::testing::Return;

class MockLiveTab : public sessions::LiveTab {
 public:
  MockLiveTab() = default;
  ~MockLiveTab() override = default;

  MOCK_METHOD0(IsInitialBlankNavigation, bool());
  MOCK_METHOD0(GetCurrentEntryIndex, int());
  MOCK_METHOD0(GetPendingEntryIndex, int());
  MOCK_METHOD1(GetEntryAtIndex, sessions::SerializedNavigationEntry(int index));
  MOCK_METHOD0(GetPendingEntry, sessions::SerializedNavigationEntry());
  MOCK_METHOD0(GetEntryCount, int());
  MOCK_METHOD0(
      GetPlatformSpecificTabData,
      std::unique_ptr<sessions::tab_restore::PlatformSpecificTabData>());
  MOCK_METHOD0(GetUserAgentOverride, sessions::SerializedUserAgentOverride());
};

class MockLiveTabContext : public sessions::LiveTabContext {
 public:
  MockLiveTabContext() = default;
  ~MockLiveTabContext() override = default;

  MOCK_METHOD0(ShowBrowserWindow, void());
  MOCK_CONST_METHOD0(GetSessionID, SessionID());
  MOCK_CONST_METHOD0(GetWindowType, sessions::SessionWindow::WindowType());
  MOCK_CONST_METHOD0(GetTabCount, int());
  MOCK_CONST_METHOD0(GetSelectedIndex, int());
  MOCK_CONST_METHOD0(GetAppName, std::string());
  MOCK_CONST_METHOD0(GetUserTitle, std::string());
  MOCK_CONST_METHOD1(GetLiveTabAt, sessions::LiveTab*(int index));
  MOCK_CONST_METHOD0(GetActiveLiveTab, sessions::LiveTab*());
  MOCK_CONST_METHOD1(GetExtraDataForTab,
                     std::map<std::string, std::string>(int index));
  MOCK_CONST_METHOD0(GetExtraDataForWindow,
                     std::map<std::string, std::string>());
  MOCK_CONST_METHOD1(GetTabGroupForTab,
                     std::optional<tab_groups::TabGroupId>(int index));
  MOCK_CONST_METHOD1(GetVisualDataForGroup,
                     const tab_groups::TabGroupVisualData*(
                         const tab_groups::TabGroupId& group));
  MOCK_CONST_METHOD1(
      GetSavedTabGroupIdForGroup,
      const std::optional<base::Uuid>(const tab_groups::TabGroupId& group));
  MOCK_CONST_METHOD1(IsTabPinned, bool(int index));
  MOCK_METHOD2(SetVisualDataForGroup,
               void(const tab_groups::TabGroupId& group,
                    const tab_groups::TabGroupVisualData& visual_data));
  MOCK_CONST_METHOD0(GetRestoredBounds, const gfx::Rect());
  MOCK_CONST_METHOD0(GetRestoredState, ui::mojom::WindowShowState());
  MOCK_CONST_METHOD0(GetWorkspace, std::string());
  MOCK_METHOD(sessions::LiveTab*,
              AddRestoredTab,
              ((const sessions::tab_restore::Tab&),
               int,
               bool,
               bool,
               sessions::tab_restore::Type),
              (override));
  MOCK_METHOD(sessions::LiveTab*,
              ReplaceRestoredTab,
              ((const sessions::tab_restore::Tab&)),
              (override));
  MOCK_METHOD0(CloseTab, void());
};

class MockTabRestoreServiceClient : public sessions::TabRestoreServiceClient {
 public:
  MockTabRestoreServiceClient() = default;
  ~MockTabRestoreServiceClient() override = default;

  MOCK_METHOD8(CreateLiveTabContext,
               sessions::LiveTabContext*(
                   sessions::LiveTabContext* existing_context,
                   sessions::SessionWindow::WindowType type,
                   const std::string& app_name,
                   const gfx::Rect& bounds,
                   ui::mojom::WindowShowState show_state,
                   const std::string& workspace,
                   const std::string& user_title,
                   const std::map<std::string, std::string>& extra_data));
  MOCK_METHOD1(FindLiveTabContextForTab,
               sessions::LiveTabContext*(const sessions::LiveTab* tab));
  MOCK_METHOD1(FindLiveTabContextWithID,
               sessions::LiveTabContext*(SessionID desired_id));
  MOCK_METHOD1(FindLiveTabContextWithGroup,
               sessions::LiveTabContext*(tab_groups::TabGroupId group));
  MOCK_METHOD1(ShouldTrackURLForRestore, bool(const GURL& url));
  MOCK_METHOD1(GetExtensionAppIDForTab, std::string(sessions::LiveTab* tab));
  MOCK_METHOD0(GetPathToSaveTo, base::FilePath());
  MOCK_METHOD0(GetNewTabURL, GURL());
  MOCK_METHOD0(HasLastSession, bool());
  MOCK_METHOD1(GetLastSession, void(sessions::GetLastSessionCallback callback));
  MOCK_METHOD1(OnTabRestored, void(const GURL& url));
};

// Create subclass that overrides TimeNow so that we can control the time used
// for closed tabs and windows.
class TabRestoreTimeFactory : public sessions::tab_restore::TimeFactory {
 public:
  TabRestoreTimeFactory() : time_(base::Time::Now()) {}

  ~TabRestoreTimeFactory() override = default;

  base::Time TimeNow() override { return time_; }

 private:
  base::Time time_;
};

class TabRestoreServiceImplTest : public ChromeRenderViewHostTestHarness {
 public:
  TabRestoreServiceImplTest()
      : url1_("http://1"),
        url2_("http://2"),
        url3_("http://3"),
        user_agent_override_(blink::UserAgentOverride::UserAgentOnly(
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.19"
            " (KHTML, like Gecko) Chrome/18.0.1025.45 Safari/535.19")),
        time_factory_(nullptr),
        window_id_(SessionID::FromSerializedValue(1)),
        tab_id_(SessionID::FromSerializedValue(2)) {
    user_agent_override_.ua_metadata_override.emplace();
    user_agent_override_.ua_metadata_override->brand_version_list.emplace_back(
        "Chrome", "18");
    user_agent_override_.ua_metadata_override->brand_full_version_list
        .emplace_back("Chrome", "18.0.1025.45");
    user_agent_override_.ua_metadata_override->full_version = "18.0.1025.45";
    user_agent_override_.ua_metadata_override->platform = "Linux";
    user_agent_override_.ua_metadata_override->architecture = "x86_64";
    user_agent_override_.ua_metadata_override->bitness = "32";
  }

  ~TabRestoreServiceImplTest() override = default;

  SessionID tab_id() const { return tab_id_; }
  SessionID window_id() const { return window_id_; }

 protected:
  enum {
    kMaxEntries = sessions::TabRestoreServiceHelper::kMaxEntries,
  };

  // testing::Test:
  void SetUp() override {
    ChromeRenderViewHostTestHarness::SetUp();
    live_tab_ = base::WrapUnique(new sessions::ContentLiveTab(web_contents()));
    time_factory_ = new TabRestoreTimeFactory();

    CreateService();
  }

  void TearDown() override {
    service_->Shutdown();
    service_.reset();
    delete time_factory_;
    ChromeRenderViewHostTestHarness::TearDown();
  }

  sessions::TabRestoreService::Entries* mutable_entries() {
    return service_->mutable_entries();
  }

  void PruneEntries() { service_->PruneEntries(); }

  void AddThreeNavigations() {
    // Navigate to three URLs.
    NavigateAndCommit(url1_);
    NavigateAndCommit(url2_);
    NavigateAndCommit(url3_);
  }

  void NavigateToIndex(int index) {
    // Navigate back. We have to do this song and dance as NavigationController
    // isn't happy if you navigate immediately while going back.
    controller().GoToIndex(index);
    WebContentsTester::For(web_contents())->CommitPendingNavigation();
  }

  virtual void CreateService() {
    service_ = std::make_unique<sessions::TabRestoreServiceImpl>(
        std::make_unique<ChromeTabRestoreServiceClient>(profile()),
        profile()->GetPrefs(), time_factory_);
  }

  void RecreateService() {
    // Must set service to null first so that it is destroyed before the new
    // one is created.
    service_->Shutdown();
    content::RunAllTasksUntilIdle();
    service_.reset();

    CreateService();
    SynchronousLoadTabsFromLastSession();
  }

  // Adds a window with one tab and url to the profile's session
  // service. If |pinned| is true, the tab is marked as pinned in the
  // session service. If |group| is present, sets the tab's group ID. If
  // |group_visual_data| is also present, sets |group|'s visual data.
  void AddWindowWithOneTabToSessionService(
      bool pinned,
      std::optional<tab_groups::TabGroupId> group = std::nullopt,
      std::optional<tab_groups::TabGroupVisualData> group_visual_data =
          std::nullopt,
      absl ::optional<ExtraData> extra_data = std::nullopt) {
    // Create new window / tab IDs so that these remain distinct.
    window_id_ = SessionID::NewUnique();
    tab_id_ = SessionID::NewUnique();

    SessionService* session_service =
        SessionServiceFactory::GetForProfile(profile());
    session_service->SetWindowType(window_id(), Browser::TYPE_NORMAL);
    session_service->SetTabWindow(window_id(), tab_id());
    session_service->SetTabIndexInWindow(window_id(), tab_id(), 0);
    session_service->SetSelectedTabInWindow(window_id(), 0);
    if (pinned)
      session_service->SetPinnedState(window_id(), tab_id(), true);
    if (group)
      session_service->SetTabGroup(window_id(), tab_id(), group);
    if (group && group_visual_data)
      session_service->SetTabGroupMetadata(window_id(), *group,
                                           &*group_visual_data);

    session_service->UpdateTabNavigation(
        window_id(), tab_id(),
        ContentTestHelper::CreateNavigation(url1_.spec(), "title"));
  }

  // Creates a SessionService and assigns it to the Profile. The SessionService
  // is configured with a single window with a single tab pointing at url1_ by
  // way of AddWindowWithOneTabToSessionService. If |pinned| is true, the
  // tab is marked as pinned in the session service.
  void CreateSessionServiceWithOneWindow(bool pinned) {
    std::unique_ptr<SessionService> session_service(
        new SessionService(profile()));
    SessionServiceFactory::SetForTestProfile(profile(),
                                             std::move(session_service));

    AddWindowWithOneTabToSessionService(pinned);

    // Set this, otherwise previous session won't be loaded.
    ExitTypeService::GetInstanceForProfile(profile())
        ->SetLastSessionExitTypeForTest(ExitType::kCrashed);
  }

  void SynchronousLoadTabsFromLastSession() {
    // Ensures that the load is complete before continuing.
    TabRestoreServiceLoadWaiter waiter(service_.get());
    service_->LoadTabsFromLastSession();
    waiter.Wait();
  }

  sessions::LiveTab* live_tab() { return live_tab_.get(); }

  GURL url1_;
  GURL url2_;
  GURL url3_;
  blink::UserAgentOverride user_agent_override_;
  std::unique_ptr<sessions::LiveTab> live_tab_;
  std::unique_ptr<sessions::TabRestoreServiceImpl> service_;
  raw_ptr<TabRestoreTimeFactory, DanglingUntriaged> time_factory_;
  SessionID window_id_;
  SessionID tab_id_;
};

class TabRestoreServiceImplWithMockClientTest
    : public TabRestoreServiceImplTest {
 public:
  TabRestoreServiceImplWithMockClientTest() = default;
  ~TabRestoreServiceImplWithMockClientTest() override = default;

 protected:
  void CreateService() override {
    std::unique_ptr<MockTabRestoreServiceClient> service_client =
        std::make_unique<testing::NiceMock<MockTabRestoreServiceClient>>();
    mock_tab_restore_service_client_ = service_client.get();
    ON_CALL(*mock_tab_restore_service_client_, GetPathToSaveTo())
        .WillByDefault(Return(profile()->GetPath()));

    service_ = std::make_unique<sessions::TabRestoreServiceImpl>(
        std::move(service_client), profile()->GetPrefs(), time_factory_);
  }

  raw_ptr<MockTabRestoreServiceClient, DanglingUntriaged>
      mock_tab_restore_service_client_;
};

TEST_F(TabRestoreServiceImplTest, Basic) {
  AddThreeNavigations();

  // Have the service record the tab.
  service_->CreateHistoricalTab(live_tab(), -1);

  // Make sure an entry was created.
  ASSERT_EQ(1U, service_->entries().size());

  // Make sure the entry matches.
  Entry* entry = service_->entries().front().get();
  ASSERT_EQ(sessions::tab_restore::Type::TAB, entry->type);
  Tab* tab = static_cast<Tab*>(entry);
  EXPECT_FALSE(tab->pinned);
  EXPECT_TRUE(tab->extension_app_id.empty());
  ASSERT_EQ(3U, tab->navigations.size());
  EXPECT_TRUE(url1_ == tab->navigations[0].virtual_url());
  EXPECT_TRUE(url2_ == tab->navigations[1].virtual_url());
  EXPECT_TRUE(url3_ == tab->navigations[2].virtual_url());
  EXPECT_EQ("", tab->user_agent_override.ua_string_override);
  EXPECT_TRUE(!blink::UserAgentMetadata::Demarshal(
                   tab->user_agent_override.opaque_ua_metadata_override)
                   .has_value());
  EXPECT_EQ(2, tab->current_navigation_index);
  EXPECT_EQ(
      time_factory_->TimeNow().ToDeltaSinceWindowsEpoch().InMicroseconds(),
      tab->timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds());

  NavigateToIndex(1);

  // And check again, but set the user agent override this time.
  web_contents()->SetUserAgentOverride(user_agent_override_, false);
  service_->CreateHistoricalTab(live_tab(), -1);

  // There should be two entries now.
  ASSERT_EQ(2U, service_->entries().size());

  // Make sure the entry matches.
  entry = service_->entries().front().get();
  ASSERT_EQ(sessions::tab_restore::Type::TAB, entry->type);
  tab = static_cast<Tab*>(entry);
  EXPECT_FALSE(tab->pinned);
  ASSERT_EQ(3U, tab->navigations.size());
  EXPECT_EQ(url1_, tab->navigations[0].virtual_url());
  EXPECT_EQ(url2_, tab->navigations[1].virtual_url());
  EXPECT_EQ(url3_, tab->navigations[2].virtual_url());
  EXPECT_EQ(user_agent_override_.ua_string_override,
            tab->user_agent_override.ua_string_override);
  std::optional<blink::UserAgentMetadata> client_hints_override =
      blink::UserAgentMetadata::Demarshal(
          tab->user_agent_override.opaque_ua_metadata_override);
  EXPECT_EQ(user_agent_override_.ua_metadata_override, client_hints_override);
  EXPECT_EQ(1, tab->current_navigation_index);
  EXPECT_EQ(
      time_factory_->TimeNow().ToDeltaSinceWindowsEpoch().InMicroseconds(),
      tab->timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds());
}

TEST_F(TabRestoreServiceImplWithMockClientTest,
       TabExtraDataPresentInHistoricalTab) {
  constexpr char kSampleKey[] = "test";
  constexpr char kSampleValue[] = "true";

  std::unique_ptr<MockLiveTabContext> mock_live_tab_context_ptr(
      new ::testing::NiceMock<MockLiveTabContext>());
  SessionID sample_session_id = SessionID::NewUnique();
  EXPECT_CALL(*mock_live_tab_context_ptr, GetSessionID)
      .WillOnce(Return(sample_session_id));
  EXPECT_CALL(*mock_live_tab_context_ptr, GetExtraDataForTab)
      .WillOnce([kSampleKey, kSampleValue]() {
        std::map<std::string, std::string> sample_extra_data;
        sample_extra_data[kSampleKey] = kSampleValue;
        return sample_extra_data;
      });
  ON_CALL(*mock_tab_restore_service_client_, FindLiveTabContextForTab(_))
      .WillByDefault(Return(mock_live_tab_context_ptr.get()));
  ON_CALL(*mock_tab_restore_service_client_, GetNewTabURL())
      .WillByDefault(Return(GURL("https://www.google.com")));

  NavigateAndCommit(url1_);
  // Have the service record the tab.
  service_->CreateHistoricalTab(live_tab(), -1);

  // Make sure an entry was created.
  ASSERT_EQ(1U, service_->entries().size());
  // Make sure the entry data matches.
  Entry* entry = service_->entries().front().get();
  ASSERT_EQ(sessions::tab_restore::Type::TAB, entry->type);
  Tab* tab = static_cast<Tab*>(entry);
  ASSERT_EQ(1U, tab->navigations.size());
  EXPECT_EQ(url1_, tab->navigations[0].virtual_url());
  ASSERT_EQ(1U, tab->extra_data.size());
  ASSERT_EQ(kSampleValue, tab->extra_data[kSampleKey]);
}

// Ensure fields are written and read from saved state.
TEST_F(TabRestoreServiceImplWithMockClientTest, WindowRestore) {
  ON_CALL(*mock_tab_restore_service_client_, ShouldTrackURLForRestore(_))
      .WillByDefault(Return(true));

  SerializedNavigationEntry navigation_entry =
      SerializedNavigationEntryTestHelper::CreateNavigationForTest();
  testing::NiceMock<MockLiveTab> mock_live_tab;
  ON_CALL(mock_live_tab, GetEntryCount).WillByDefault(Return(1));
  ON_CALL(mock_live_tab, GetEntryAtIndex)
      .WillByDefault(Return(navigation_entry));

  testing::NiceMock<MockLiveTabContext> mock_live_tab_context;
  SessionID session_id = SessionID::NewUnique();
  ON_CALL(mock_live_tab_context, GetSessionID)
      .WillByDefault(Return(session_id));
  ON_CALL(mock_live_tab_context, GetWindowType)
      .WillByDefault(Return(sessions::SessionWindow::TYPE_APP_POPUP));
  ON_CALL(mock_live_tab_context, GetAppName).WillByDefault(Return("app-name"));
  ON_CALL(mock_live_tab_context, GetUserTitle)
      .WillByDefault(Return("user-title"));
  ON_CALL(mock_live_tab_context, GetRestoredBounds)
      .WillByDefault(Return(gfx::Rect(10, 20, 30, 40)));
  ON_CALL(mock_live_tab_context, GetRestoredState)
      .WillByDefault(Return(ui::mojom::WindowShowState::kMaximized));
  ON_CALL(mock_live_tab_context, GetWorkspace)
      .WillByDefault(Return("workspace"));
  ON_CALL(mock_live_tab_context, GetTabCount).WillByDefault(Return(1));
  ON_CALL(mock_live_tab_context, GetLiveTabAt)
      .WillByDefault(Return(&mock_live_tab));

  service_->BrowserClosing(&mock_live_tab_context);

  // Validate while entries are in memory.
  auto validate = [&]() {
    ASSERT_EQ(1u, service_->entries().size());
    Entry* entry = service_->entries().front().get();
    EXPECT_EQ(sessions::tab_restore::Type::WINDOW, entry->type);
    Window* window = static_cast<Window*>(entry);
    EXPECT_EQ(sessions::SessionWindow::TYPE_APP_POPUP, window->type);
    EXPECT_EQ(0, window->selected_tab_index);
    EXPECT_EQ("app-name", window->app_name);
    EXPECT_EQ("user-title", window->user_title);
    EXPECT_EQ(gfx::Rect(10, 20, 30, 40), window->bounds);
    EXPECT_EQ(ui::mojom::WindowShowState::kMaximized, window->show_state);
    EXPECT_EQ("workspace", window->workspace);
  };
  validate();

  // Validate after persisting and reading from storage.
  RecreateService();
  validate();
}

// Make sure TabRestoreService doesn't create an entry for a tab with no
// navigations.
TEST_F(TabRestoreServiceImplTest, DontCreateEmptyTab) {
  service_->CreateHistoricalTab(live_tab(), -1);
  EXPECT_TRUE(service_->entries().empty());
}

// Tests restoring a single tab.
TEST_F(TabRestoreServiceImplTest, Restore) {
  AddThreeNavigations();

  // Have the service record the tab.
  service_->CreateHistoricalTab(live_tab(), -1);
  EXPECT_EQ(1U, service_->entries().size());

  // Recreate the service and have it load the tabs.
  RecreateService();

  // One entry should be created.
  ASSERT_EQ(1U, service_->entries().size());

  // And verify the entry.
  Entry* entry = service_->entries().front().get();
  ASSERT_EQ(sessions::tab_restore::Type::TAB, entry->type);
  Tab* tab = static_cast<Tab*>(entry);
  EXPECT_FALSE(tab->pinned);
  ASSERT_EQ(3U, tab->navigations.size());
  EXPECT_TRUE(url1_ == tab->navigations[0].virtual_url());
  EXPECT_TRUE(url2_ == tab->navigations[1].virtual_url());
  EXPECT_TRUE(url3_ == tab->navigations[2].virtual_url());
  EXPECT_EQ(2, tab->current_navigation_index);
  EXPECT_EQ(
      time_factory_->TimeNow().ToDeltaSinceWindowsEpoch().InMicroseconds(),
      tab->timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds());
}

// Tests restoring a tab with more than gMaxPersistNavigationCount entries.
TEST_F(TabRestoreServiceImplTest, RestoreManyNavigations) {
  AddThreeNavigations();
  AddThreeNavigations();
  AddThreeNavigations();

  // Have the service record the tab.
  service_->CreateHistoricalTab(live_tab(), -1);

  // Recreate the service and have it load the tabs.
  RecreateService();

  // One entry should be created.
  ASSERT_EQ(1U, service_->entries().size());

  // And verify the entry.
  Entry* entry = service_->entries().front().get();
  ASSERT_EQ(sessions::tab_restore::Type::TAB, entry->type);
  Tab* tab = static_cast<Tab*>(entry);
  // Only gMaxPersistNavigationCount + 1 (current navigation) are persisted.
  ASSERT_EQ(7U, tab->navigations.size());
  // Check that they are created with correct indices.
  EXPECT_EQ(0, tab->navigations[0].index());
  EXPECT_EQ(6, tab->navigations[6].index());
  EXPECT_EQ(6, tab->current_navigation_index);
}

// Tests restoring a single pinned tab.
TEST_F(TabRestoreServiceImplTest, RestorePinnedAndApp) {
  AddThreeNavigations();

  // Have the service record the tab.
  service_->CreateHistoricalTab(live_tab(), -1);

  // One entry should be created.
  ASSERT_EQ(1U, service_->entries().size());

  // We have to explicitly mark the tab as pinned as there is no browser for
  // these tests.
  Entry* entry = service_->entries().front().get();
  ASSERT_EQ(sessions::tab_restore::Type::TAB, entry->type);
  Tab* tab = static_cast<Tab*>(entry);
  tab->pinned = true;
  const std::string extension_app_id("test");
  tab->extension_app_id = extension_app_id;

  // Recreate the service and have it load the tabs.
  RecreateService();

  // One entry should be created.
  ASSERT_EQ(1U, service_->entries().size());

  // And verify the entry.
  entry = service_->entries().front().get();
  ASSERT_EQ(sessions::tab_restore::Type::TAB, entry->type);
  tab = static_cast<Tab*>(entry);
  EXPECT_TRUE(tab->pinned);
  ASSERT_EQ(3U, tab->navigations.size());
  EXPECT_TRUE(url1_ == tab->navigations[0].virtual_url());
  EXPECT_TRUE(url2_ == tab->navigations[1].virtual_url());
  EXPECT_TRUE(url3_ == tab->navigations[2].virtual_url());
  EXPECT_EQ(2, tab->current_navigation_index);
  EXPECT_TRUE(extension_app_id == tab->extension_app_id);
}

// Make sure TabRestoreService doesn't create a restored entry.
TEST_F(TabRestoreServiceImplTest, DontCreateRestoredEntry) {
  AddThreeNavigations();

  // Have the service record the tab.
  service_->CreateHistoricalTab(live_tab(), -1);
  EXPECT_EQ(1U, service_->entries().size());

  // Record the tab's id.
  Entry* entry = service_->entries().front().get();
  ASSERT_EQ(sessions::tab_restore::Type::TAB, entry->type);
  SessionID first_id = entry->id;

  // Service record the second tab.
  service_->CreateHistoricalTab(live_tab(), -1);
  EXPECT_EQ(2U, service_->entries().size());

  // Record the tab's id.
  entry = service_->entries().front().get();
  ASSERT_EQ(sessions::tab_restore::Type::TAB, entry->type);
  SessionID second_id = entry->id;

  service_->Shutdown();

  // Add a restored entry command
  service_->CreateRestoredEntryCommandForTest(second_id);

  // Recreate the service
  RecreateService();

  // Only one entry should be created.
  ASSERT_EQ(1U, service_->entries().size());

  // And verify the entry.
  entry = service_->entries().front().get();
  ASSERT_EQ(sessions::tab_restore::Type::TAB, entry->type);
  ASSERT_EQ(first_id, entry->original_id);
}

// Tests deleting entries.
TEST_F(TabRestoreServiceImplTest, DeleteNavigationEntries) {
  SynchronousLoadTabsFromLastSession();
  AddThreeNavigations();

  // Have the service record the tab.
  service_->CreateHistoricalTab(live_tab(), -1);

  service_->DeleteNavigationEntries(
      base::BindLambdaForTesting([&](const SerializedNavigationEntry& entry) {
        return entry.virtual_url() == url2_;
      }));

  // The entry should still exist but url2_ was removed and indices adjusted.
  ASSERT_EQ(1U, service_->entries().size());
  Entry* entry = service_->entries().front().get();
  ASSERT_EQ(sessions::tab_restore::Type::TAB, entry->type);
  Tab* tab = static_cast<Tab*>(entry);
  ASSERT_EQ(2U, tab->navigations.size());
  EXPECT_EQ(url1_, tab->navigations[0].virtual_url());
  EXPECT_EQ(0, tab->navigations[0].index());
  EXPECT_EQ(url3_, tab->navigations[1].virtual_url());
  EXPECT_EQ(1, tab->navigations[1].index());
  EXPECT_EQ(1, tab->current_navigation_index);

  service_->DeleteNavigationEntries(base::BindRepeating(
      [](const SerializedNavigationEntry& entry) { return true; }));

  // The entry should be removed.
  EXPECT_EQ(0U, service_->entries().size());
}

// Tests deleting entries.
TEST_F(TabRestoreServiceImplTest, DeleteCurrentEntry) {
  SynchronousLoadTabsFromLastSession();
  AddThreeNavigations();

  // Have the service record the tab.
  service_->CreateHistoricalTab(live_tab(), -1);

  service_->DeleteNavigationEntries(
      base::BindLambdaForTesting([&](const SerializedNavigationEntry& entry) {
        return entry.virtual_url() == url3_;
      }));

  // The entry should be deleted because the current url was deleted.
  EXPECT_EQ(0U, service_->entries().size());
}

// Tests deleting entries.
TEST_F(TabRestoreServiceImplTest, DeleteEntriesAndRecreate) {
  SynchronousLoadTabsFromLastSession();
  AddThreeNavigations();

  // Have the service record the tab.
  service_->CreateHistoricalTab(live_tab(), -1);

  // Delete the navigation for url2_.
  service_->DeleteNavigationEntries(
      base::BindLambdaForTesting([&](const SerializedNavigationEntry& entry) {
        return entry.virtual_url() == url2_;
      }));
  // Recreate the service and have it load the tabs.
  RecreateService();
  // The entry should still exist but url2_ was removed and indices adjusted.
  ASSERT_EQ(1U, service_->entries().size());
  Entry* entry = service_->entries().front().get();
  ASSERT_EQ(sessions::tab_restore::Type::TAB, entry->type);
  Tab* tab = static_cast<Tab*>(entry);
  ASSERT_EQ(2U, tab->navigations.size());
  EXPECT_EQ(url1_, tab->navigations[0].virtual_url());
  EXPECT_EQ(0, tab->navigations[0].index());
  EXPECT_EQ(url3_, tab->navigations[1].virtual_url());
  EXPECT_EQ(1, tab->navigations[1].index());
  EXPECT_EQ(1, tab->current_navigation_index);

  // Delete all entries.
  service_->DeleteNavigationEntries(base::BindRepeating(
      [](const SerializedNavigationEntry& entry) { return true; }));
  // Recreate the service and have it load the tabs.
  RecreateService();
  // The entry should be removed.
  ASSERT_EQ(0U, service_->entries().size());
}

// Make sure we persist entries to disk that have post data.
TEST_F(TabRestoreServiceImplTest, DontPersistPostData) {
  AddThreeNavigations();
  controller().GetEntryAtIndex(0)->SetHasPostData(true);
  controller().GetEntryAtIndex(1)->SetHasPostData(true);
  controller().GetEntryAtIndex(2)->SetHasPostData(true);

  // Have the service record the tab.
  service_->CreateHistoricalTab(live_tab(), -1);
  ASSERT_EQ(1U, service_->entries().size());

  // Recreate the service and have it load the tabs.
  RecreateService();

  // One entry should be created.
  ASSERT_EQ(1U, service_->entries().size());

  const Entry* restored_entry = service_->entries().front().get();
  ASSERT_EQ(sessions::tab_restore::Type::TAB, restored_entry->type);

  const Tab* restored_tab = static_cast<const Tab*>(restored_entry);
  // There should be 3 navs.
  ASSERT_EQ(3U, restored_tab->navigations.size());
  EXPECT_EQ(
      time_factory_->TimeNow().ToDeltaSinceWindowsEpoch().InMicroseconds(),
      restored_tab->timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds());
}

// Make sure we don't persist entries to disk that have post data. This
// differs from DontPersistPostData1 in that all the navigations have post
// data, so that nothing should be persisted.
TEST_F(TabRestoreServiceImplTest, DontLoadTwice) {
  AddThreeNavigations();

  // Have the service record the tab.
  service_->CreateHistoricalTab(live_tab(), -1);
  ASSERT_EQ(1U, service_->entries().size());

  // Recreate the service and have it load the tabs.
  RecreateService();

  SynchronousLoadTabsFromLastSession();

  // There should only be one entry.
  ASSERT_EQ(1U, service_->entries().size());
}

// Makes sure we load the previous session as necessary.
TEST_F(TabRestoreServiceImplTest, LoadPreviousSession) {
  CreateSessionServiceWithOneWindow(false);

  SessionServiceFactory::GetForProfile(profile())
      ->MoveCurrentSessionToLastSession();

  EXPECT_FALSE(service_->IsLoaded());

  SynchronousLoadTabsFromLastSession();

  // Make sure we get back one entry with one tab whose url is url1.
  ASSERT_EQ(1U, service_->entries().size());
  Entry* entry2 = service_->entries().front().get();
  ASSERT_EQ(sessions::tab_restore::Type::WINDOW, entry2->type);
  sessions::tab_restore::Window* window =
      static_cast<sessions::tab_restore::Window*>(entry2);
  EXPECT_EQ(sessions::SessionWindow::TYPE_NORMAL, window->type);
  ASSERT_EQ(1U, window->tabs.size());
  EXPECT_EQ(0, window->timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds());
  EXPECT_EQ(0, window->selected_tab_index);
  ASSERT_EQ(1U, window->tabs[0]->navigations.size());
  EXPECT_EQ(0, window->tabs[0]->current_navigation_index);
  EXPECT_EQ(
      0,
      window->tabs[0]->timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds());
  EXPECT_TRUE(url1_ == window->tabs[0]->navigations[0].virtual_url());
}

// Makes sure we don't attempt to load previous sessions after a restore.
TEST_F(TabRestoreServiceImplTest, DontLoadAfterRestore) {
  CreateSessionServiceWithOneWindow(false);

  SessionServiceFactory::GetForProfile(profile())
      ->MoveCurrentSessionToLastSession();

  profile()->set_restored_last_session(true);

  SynchronousLoadTabsFromLastSession();

  // Because we restored a session TabRestoreService shouldn't load the tabs.
  ASSERT_EQ(0U, service_->entries().size());
}

// Makes sure we don't attempt to load previous sessions after a clean exit.
TEST_F(TabRestoreServiceImplTest, DontLoadAfterCleanExit) {
  CreateSessionServiceWithOneWindow(false);

  SessionServiceFactory::GetForProfile(profile())
      ->MoveCurrentSessionToLastSession();

  ExitTypeService::GetInstanceForProfile(profile())
      ->SetLastSessionExitTypeForTest(ExitType::kClean);

  SynchronousLoadTabsFromLastSession();

  ASSERT_EQ(0U, service_->entries().size());
}

// Makes sure we don't save sessions when saving history is disabled.
TEST_F(TabRestoreServiceImplTest, DontSaveWhenSavingIsDisabled) {
  profile()->GetPrefs()->SetBoolean(prefs::kSavingBrowserHistoryDisabled, true);

  CreateSessionServiceWithOneWindow(false);

  SessionServiceFactory::GetForProfile(profile())
      ->MoveCurrentSessionToLastSession();

  SynchronousLoadTabsFromLastSession();

  ASSERT_EQ(0U, service_->entries().size());
}

// Makes sure we don't attempt to load previous sessions when saving history is
// disabled.
TEST_F(TabRestoreServiceImplTest, DontLoadWhenSavingIsDisabled) {
  CreateSessionServiceWithOneWindow(false);

  SessionServiceFactory::GetForProfile(profile())
      ->MoveCurrentSessionToLastSession();

  profile()->GetPrefs()->SetBoolean(prefs::kSavingBrowserHistoryDisabled, true);

  SynchronousLoadTabsFromLastSession();

  ASSERT_EQ(0U, service_->entries().size());
}

// Regression test to ensure Window::show_state is set correctly when reading
// TabRestoreSession from saved state.
TEST_F(TabRestoreServiceImplTest, WindowShowStateIsSet) {
  CreateSessionServiceWithOneWindow(false);

  SessionServiceFactory::GetForProfile(profile())
      ->MoveCurrentSessionToLastSession();

  SynchronousLoadTabsFromLastSession();

  RecreateService();

  // There should be at least one window and its show state should be the
  // default.
  bool got_window = false;
  for (auto& entry : service_->entries()) {
    if (entry->type == sessions::tab_restore::Type::WINDOW) {
      got_window = true;
      Window* window = static_cast<Window*>(entry.get());
      EXPECT_EQ(window->show_state, ui::mojom::WindowShowState::kDefault);
    }
  }
  EXPECT_TRUE(got_window);
}

TEST_F(TabRestoreServiceImplTest, LoadPreviousSessionAndTabs) {
  CreateSessionServiceWithOneWindow(false);

  SessionServiceFactory::GetForProfile(profile())
      ->MoveCurrentSessionToLastSession();

  AddThreeNavigations();

  service_->CreateHistoricalTab(live_tab(), -1);

  RecreateService();

  // We should get back two entries, one from the previous session and one from
  // the tab restore service. The previous session entry should be first.
  ASSERT_EQ(2U, service_->entries().size());
  // The first entry should come from the session service.
  Entry* entry = service_->entries().front().get();
  ASSERT_EQ(sessions::tab_restore::Type::WINDOW, entry->type);
  sessions::tab_restore::Window* window =
      static_cast<sessions::tab_restore::Window*>(entry);
  ASSERT_EQ(1U, window->tabs.size());
  EXPECT_EQ(0, window->selected_tab_index);
  EXPECT_EQ(0, window->timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds());
  ASSERT_EQ(1U, window->tabs[0]->navigations.size());
  EXPECT_EQ(0, window->tabs[0]->current_navigation_index);
  EXPECT_EQ(
      0,
      window->tabs[0]->timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds());
  EXPECT_TRUE(url1_ == window->tabs[0]->navigations[0].virtual_url());

  // Then the closed tab.
  entry = (++service_->entries().begin())->get();
  ASSERT_EQ(sessions::tab_restore::Type::TAB, entry->type);
  Tab* tab = static_cast<Tab*>(entry);
  ASSERT_FALSE(tab->pinned);
  ASSERT_EQ(3U, tab->navigations.size());
  EXPECT_EQ(2, tab->current_navigation_index);
  EXPECT_EQ(
      time_factory_->TimeNow().ToDeltaSinceWindowsEpoch().InMicroseconds(),
      tab->timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds());
  EXPECT_TRUE(url1_ == tab->navigations[0].virtual_url());
  EXPECT_TRUE(url2_ == tab->navigations[1].virtual_url());
  EXPECT_TRUE(url3_ == tab->navigations[2].virtual_url());
}

// Make sure window bounds and workspace are properly loaded from the session
// service.
TEST_F(TabRestoreServiceImplTest, LoadWindowBoundsAndWorkspace) {
  constexpr gfx::Rect kBounds(10, 20, 640, 480);
  constexpr ui::mojom::WindowShowState kShowState =
      ui::mojom::WindowShowState::kMinimized;
  constexpr char kWorkspace[] = "workspace";

  CreateSessionServiceWithOneWindow(false);

  // Set the bounds, show state and workspace.
  SessionService* session_service =
      SessionServiceFactory::GetForProfile(profile());
  session_service->SetWindowBounds(window_id(), kBounds, kShowState);
  session_service->SetWindowWorkspace(window_id(), kWorkspace);

  session_service->MoveCurrentSessionToLastSession();

  AddThreeNavigations();

  service_->CreateHistoricalTab(live_tab(), -1);

  RecreateService();

  // We should get back two entries, one from the previous session and one from
  // the tab restore service. The previous session entry should be first.
  ASSERT_EQ(2U, service_->entries().size());

  // The first entry should come from the session service.
  Entry* entry = service_->entries().front().get();
  ASSERT_EQ(sessions::tab_restore::Type::WINDOW, entry->type);
  sessions::tab_restore::Window* window =
      static_cast<sessions::tab_restore::Window*>(entry);
  ASSERT_EQ(kBounds, window->bounds);
  ASSERT_EQ(kShowState, window->show_state);
  ASSERT_EQ(kWorkspace, window->workspace);
  ASSERT_EQ(1U, window->tabs.size());
  EXPECT_EQ(0, window->selected_tab_index);
  EXPECT_FALSE(window->tabs[0]->pinned);
  ASSERT_EQ(1U, window->tabs[0]->navigations.size());
  EXPECT_EQ(0, window->tabs[0]->current_navigation_index);
  EXPECT_TRUE(url1_ == window->tabs[0]->navigations[0].virtual_url());

  // Then the closed tab.
  entry = (++service_->entries().begin())->get();
  ASSERT_EQ(sessions::tab_restore::Type::TAB, entry->type);
  Tab* tab = static_cast<Tab*>(entry);
  ASSERT_FALSE(tab->pinned);
  ASSERT_EQ(3U, tab->navigations.size());
  EXPECT_EQ(2, tab->current_navigation_index);
  EXPECT_TRUE(url1_ == tab->navigations[0].virtual_url());
  EXPECT_TRUE(url2_ == tab->navigations[1].virtual_url());
  EXPECT_TRUE(url3_ == tab->navigations[2].virtual_url());
}

// Make sure pinned state is correctly loaded from session service.
TEST_F(TabRestoreServiceImplTest, LoadPreviousSessionAndTabsPinned) {
  CreateSessionServiceWithOneWindow(true);

  SessionServiceFactory::GetForProfile(profile())
      ->MoveCurrentSessionToLastSession();

  AddThreeNavigations();

  service_->CreateHistoricalTab(live_tab(), -1);

  RecreateService();

  // We should get back two entries, one from the previous session and one from
  // the tab restore service. The previous session entry should be first.
  ASSERT_EQ(2U, service_->entries().size());
  // The first entry should come from the session service.
  Entry* entry = service_->entries().front().get();
  ASSERT_EQ(sessions::tab_restore::Type::WINDOW, entry->type);
  sessions::tab_restore::Window* window =
      static_cast<sessions::tab_restore::Window*>(entry);
  ASSERT_EQ(1U, window->tabs.size());
  EXPECT_EQ(0, window->selected_tab_index);
  EXPECT_TRUE(window->tabs[0]->pinned);
  ASSERT_EQ(1U, window->tabs[0]->navigations.size());
  EXPECT_EQ(0, window->tabs[0]->current_navigation_index);
  EXPECT_TRUE(url1_ == window->tabs[0]->navigations[0].virtual_url());

  // Then the closed tab.
  entry = (++service_->entries().begin())->get();
  ASSERT_EQ(sessions::tab_restore::Type::TAB, entry->type);
  Tab* tab = static_cast<Tab*>(entry);
  ASSERT_FALSE(tab->pinned);
  ASSERT_EQ(3U, tab->navigations.size());
  EXPECT_EQ(2, tab->current_navigation_index);
  EXPECT_TRUE(url1_ == tab->navigations[0].virtual_url());
  EXPECT_TRUE(url2_ == tab->navigations[1].virtual_url());
  EXPECT_TRUE(url3_ == tab->navigations[2].virtual_url());
}

// Creates kMaxEntries + 1 windows in the session service and makes sure we only
// get back kMaxEntries on restore.
TEST_F(TabRestoreServiceImplTest, ManyWindowsInSessionService) {
  CreateSessionServiceWithOneWindow(false);

  for (size_t i = 0; i < kMaxEntries; ++i)
    AddWindowWithOneTabToSessionService(false);

  SessionServiceFactory::GetForProfile(profile())
      ->MoveCurrentSessionToLastSession();

  AddThreeNavigations();

  service_->CreateHistoricalTab(live_tab(), -1);

  RecreateService();

  // We should get back kMaxEntries entries. We added more, but
  // TabRestoreService only allows up to kMaxEntries.
  ASSERT_EQ(static_cast<size_t>(kMaxEntries), service_->entries().size());

  // The first entry should come from the session service.
  Entry* entry = service_->entries().front().get();
  ASSERT_EQ(sessions::tab_restore::Type::WINDOW, entry->type);
  sessions::tab_restore::Window* window =
      static_cast<sessions::tab_restore::Window*>(entry);
  ASSERT_EQ(1U, window->tabs.size());
  EXPECT_EQ(0, window->selected_tab_index);
  EXPECT_EQ(0, window->timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds());
  ASSERT_EQ(1U, window->tabs[0]->navigations.size());
  EXPECT_EQ(0, window->tabs[0]->current_navigation_index);
  EXPECT_EQ(
      0,
      window->tabs[0]->timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds());
  EXPECT_TRUE(url1_ == window->tabs[0]->navigations[0].virtual_url());
}

// Makes sure we restore timestamps correctly.
TEST_F(TabRestoreServiceImplTest, TimestampSurvivesRestore) {
  base::Time tab_timestamp(
      base::Time::FromDeltaSinceWindowsEpoch(base::Microseconds(123456789)));

  AddThreeNavigations();

  // Have the service record the tab.
  service_->CreateHistoricalTab(live_tab(), -1);

  // Make sure an entry was created.
  ASSERT_EQ(1U, service_->entries().size());

  // Make sure the entry matches.
  std::vector<SerializedNavigationEntry> old_navigations;
  {
    // |entry|/|tab| doesn't survive after RecreateService().
    Entry* entry = service_->entries().front().get();
    ASSERT_EQ(sessions::tab_restore::Type::TAB, entry->type);
    Tab* tab = static_cast<Tab*>(entry);
    tab->timestamp = tab_timestamp;
    old_navigations = tab->navigations;
  }

  EXPECT_EQ(3U, old_navigations.size());
  for (size_t i = 0; i < old_navigations.size(); ++i) {
    EXPECT_FALSE(old_navigations[i].timestamp().is_null());
  }

  // Set this, otherwise previous session won't be loaded.
  ExitTypeService::GetInstanceForProfile(profile())
      ->SetLastSessionExitTypeForTest(ExitType::kCrashed);

  RecreateService();

  // One entry should be created.
  ASSERT_EQ(1U, service_->entries().size());

  // And verify the entry.
  Entry* restored_entry = service_->entries().front().get();
  ASSERT_EQ(sessions::tab_restore::Type::TAB, restored_entry->type);
  Tab* restored_tab = static_cast<Tab*>(restored_entry);
  EXPECT_EQ(
      tab_timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds(),
      restored_tab->timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds());
  ASSERT_EQ(old_navigations.size(), restored_tab->navigations.size());
  for (size_t i = 0; i < restored_tab->navigations.size(); ++i) {
    EXPECT_EQ(old_navigations[i].timestamp(),
              restored_tab->navigations[i].timestamp());
  }
}

// Makes sure we restore status codes correctly.
TEST_F(TabRestoreServiceImplTest, StatusCodesSurviveRestore) {
  AddThreeNavigations();

  // Have the service record the tab.
  service_->CreateHistoricalTab(live_tab(), -1);

  // Make sure an entry was created.
  ASSERT_EQ(1U, service_->entries().size());

  // Make sure the entry matches.
  std::vector<sessions::SerializedNavigationEntry> old_navigations;
  {
    // |entry|/|tab| doesn't survive after RecreateService().
    Entry* entry = service_->entries().front().get();
    ASSERT_EQ(sessions::tab_restore::Type::TAB, entry->type);
    Tab* tab = static_cast<Tab*>(entry);
    old_navigations = tab->navigations;
  }

  EXPECT_EQ(3U, old_navigations.size());
  for (size_t i = 0; i < old_navigations.size(); ++i) {
    EXPECT_EQ(200, old_navigations[i].http_status_code());
  }

  // Set this, otherwise previous session won't be loaded.
  ExitTypeService::GetInstanceForProfile(profile())
      ->SetLastSessionExitTypeForTest(ExitType::kCrashed);

  RecreateService();

  // One entry should be created.
  ASSERT_EQ(1U, service_->entries().size());

  // And verify the entry.
  Entry* restored_entry = service_->entries().front().get();
  ASSERT_EQ(sessions::tab_restore::Type::TAB, restored_entry->type);
  Tab* restored_tab = static_cast<Tab*>(restored_entry);
  ASSERT_EQ(old_navigations.size(), restored_tab->navigations.size());
  for (size_t i = 0; i < restored_tab->navigations.size(); ++i) {
    EXPECT_EQ(200, restored_tab->navigations[i].http_status_code());
  }
}

TEST_F(TabRestoreServiceImplTest, PruneEntries) {
  service_->ClearEntries();
  ASSERT_TRUE(service_->entries().empty());

  const size_t max_entries = kMaxEntries;
  for (size_t i = 0; i < max_entries + 5; i++) {
    SerializedNavigationEntry navigation = ContentTestHelper::CreateNavigation(
        base::StringPrintf("http://%d", static_cast<int>(i)),
        base::NumberToString(i));

    auto tab = std::make_unique<Tab>();
    tab->navigations.push_back(navigation);
    tab->current_navigation_index = 0;

    mutable_entries()->push_back(std::move(tab));
  }

  // Only keep kMaxEntries around.
  EXPECT_EQ(max_entries + 5, service_->entries().size());
  PruneEntries();
  EXPECT_EQ(max_entries, service_->entries().size());
  // Pruning again does nothing.
  PruneEntries();
  EXPECT_EQ(max_entries, service_->entries().size());

  // Prune older first.
  const char kRecentUrl[] = "http://recent";
  SerializedNavigationEntry navigation =
      ContentTestHelper::CreateNavigation(kRecentUrl, "Most recent");
  auto tab = std::make_unique<Tab>();
  tab->navigations.push_back(navigation);
  tab->current_navigation_index = 0;
  mutable_entries()->push_front(std::move(tab));
  EXPECT_EQ(max_entries + 1, service_->entries().size());
  PruneEntries();
  EXPECT_EQ(max_entries, service_->entries().size());
  EXPECT_EQ(GURL(kRecentUrl), static_cast<Tab&>(*service_->entries().front())
                                  .navigations[0]
                                  .virtual_url());

  // Ignore NTPs.
  navigation = ContentTestHelper::CreateNavigation(chrome::kChromeUINewTabURL,
                                                   "New tab");

  tab = std::make_unique<Tab>();
  tab->navigations.push_back(navigation);
  tab->current_navigation_index = 0;
  mutable_entries()->push_front(std::move(tab));

  EXPECT_EQ(max_entries + 1, service_->entries().size());
  PruneEntries();
  EXPECT_EQ(max_entries, service_->entries().size());
  EXPECT_EQ(GURL(kRecentUrl), static_cast<Tab&>(*service_->entries().front())
                                  .navigations[0]
                                  .virtual_url());

  // Don't prune pinned NTPs.
  tab = std::make_unique<Tab>();
  tab->pinned = true;
  tab->current_navigation_index = 0;
  tab->navigations.push_back(navigation);
  mutable_entries()->push_front(std::move(tab));
  EXPECT_EQ(max_entries + 1, service_->entries().size());
  PruneEntries();
  EXPECT_EQ(max_entries, service_->entries().size());
  EXPECT_EQ(GURL(chrome::kChromeUINewTabURL),
            static_cast<Tab*>(service_->entries().front().get())
                ->navigations[0]
                .virtual_url());

  // Don't prune NTPs that have multiple navigations.
  // (Erase the last NTP first.)
  mutable_entries()->erase(mutable_entries()->begin());
  tab = std::make_unique<Tab>();
  tab->current_navigation_index = 1;
  tab->navigations.push_back(navigation);
  tab->navigations.push_back(navigation);
  mutable_entries()->push_front(std::move(tab));
  EXPECT_EQ(max_entries, service_->entries().size());
  PruneEntries();
  EXPECT_EQ(max_entries, service_->entries().size());
  EXPECT_EQ(GURL(chrome::kChromeUINewTabURL),
            static_cast<Tab*>(service_->entries().front().get())
                ->navigations[1]
                .virtual_url());
}

// Regression test for crbug.com/106082
TEST_F(TabRestoreServiceImplTest, PruneIsCalled) {
  CreateSessionServiceWithOneWindow(false);

  SessionServiceFactory::GetForProfile(profile())
      ->MoveCurrentSessionToLastSession();

  profile()->set_restored_last_session(true);

  const size_t max_entries = kMaxEntries;
  for (size_t i = 0; i < max_entries + 5; i++) {
    NavigateAndCommit(
        GURL(base::StringPrintf("http://%d", static_cast<int>(i))));
    service_->CreateHistoricalTab(live_tab(), -1);
  }

  EXPECT_EQ(max_entries, service_->entries().size());
  // This should not crash.
  SynchronousLoadTabsFromLastSession();
  EXPECT_EQ(max_entries, service_->entries().size());
}

// Makes sure invoking LoadTabsFromLastSession() when the max number of entries
// have been added results in IsLoaded() returning true and notifies observers.
TEST_F(TabRestoreServiceImplTest, GoToLoadedWhenHaveMaxEntries) {
  const size_t max_entries = kMaxEntries;
  for (size_t i = 0; i < max_entries + 5; i++) {
    NavigateAndCommit(
        GURL(base::StringPrintf("http://%d", static_cast<int>(i))));
    service_->CreateHistoricalTab(live_tab(), -1);
  }

  EXPECT_FALSE(service_->IsLoaded());
  EXPECT_EQ(max_entries, service_->entries().size());
  SynchronousLoadTabsFromLastSession();
  EXPECT_TRUE(service_->IsLoaded());
}

// Ensures tab group data is restored from previous session.
TEST_F(TabRestoreServiceImplTest, TabGroupsRestoredFromSessionData) {
  CreateSessionServiceWithOneWindow(false);

  auto group = tab_groups::TabGroupId::GenerateNew();
  auto group_visual_data = tab_groups::TabGroupVisualData(
      u"Foo", tab_groups::TabGroupColorId::kBlue);
  AddWindowWithOneTabToSessionService(false, group, group_visual_data);

  SessionServiceFactory::GetForProfile(profile())
      ->MoveCurrentSessionToLastSession();
  EXPECT_FALSE(service_->IsLoaded());
  SynchronousLoadTabsFromLastSession();

  ASSERT_EQ(2u, service_->entries().size());
  Entry* entry = service_->entries().back().get();
  ASSERT_EQ(sessions::tab_restore::Type::WINDOW, entry->type);
  auto* window = static_cast<sessions::tab_restore::Window*>(entry);
  ASSERT_EQ(1u, window->tabs.size());
  EXPECT_EQ(group, window->tabs[0]->group);
  EXPECT_EQ(group_visual_data, window->tab_groups[group]->visual_data);
}

// Ensures tab extra data is restored from previous session.
TEST_F(TabRestoreServiceImplTest, TabExtraDataRestoredFromSessionData) {
  const char kSampleKey[] = "test";
  const char kSampleData[] = "true";

  CreateSessionServiceWithOneWindow(false);
  AddWindowWithOneTabToSessionService(false);

  SessionService* session_service =
      SessionServiceFactory::GetForProfile(profile());
  session_service->AddTabExtraData(window_id(), tab_id(), kSampleKey,
                                   kSampleData);

  SessionServiceFactory::GetForProfile(profile())
      ->MoveCurrentSessionToLastSession();
  EXPECT_FALSE(service_->IsLoaded());
  SynchronousLoadTabsFromLastSession();

  ASSERT_EQ(2U, service_->entries().size());
  Entry* entry = service_->entries().back().get();
  ASSERT_EQ(sessions::tab_restore::Type::WINDOW, entry->type);
  auto* window = static_cast<sessions::tab_restore::Window*>(entry);
  ASSERT_EQ(1U, window->tabs.size());
  ASSERT_EQ(1U, window->tabs[0]->extra_data.size());
  EXPECT_EQ(kSampleData, window->tabs[0]->extra_data[kSampleKey]);
}