File: tabs_api_unittest.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; 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 (1849 lines) | stat: -rw-r--r-- 81,050 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
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
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
// Copyright 2016 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/extensions/api/tabs/tabs_api.h"

#include <array>
#include <memory>
#include <optional>
#include <utility>

#include "base/containers/contains.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/values_test_util.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/api/tabs/tabs_constants.h"
#include "chrome/browser/extensions/extension_service_test_base.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/session_tab_helper_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/tabs/saved_tab_groups/saved_tab_group_utils.h"
#include "chrome/browser/ui/tabs/tab_group_model.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/ui_features.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/test_browser_window.h"
#include "components/saved_tab_groups/public/features.h"
#include "components/saved_tab_groups/public/saved_tab_group.h"
#include "components/saved_tab_groups/public/tab_group_sync_service.h"
#include "components/saved_tab_groups/public/types.h"
#include "components/sessions/content/session_tab_helper.h"
#include "components/tab_groups/tab_group_id.h"
#include "components/tabs/public/split_tab_collection.h"
#include "components/tabs/public/split_tab_visual_data.h"
#include "components/tabs/public/tab_group.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/test/navigation_simulator.h"
#include "content/public/test/web_contents_tester.h"
#include "extensions/browser/api_test_utils.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension_builder.h"

#if BUILDFLAG(IS_CHROMEOS)
#include "ash/test/ash_test_helper.h"
#include "ash/test/test_window_builder.h"
#include "ash/wm/window_pin_util.h"
#include "chrome/browser/chromeos/policy/dlp/test/mock_dlp_content_manager.h"
#endif  // BUILDFLAG(IS_CHROMEOS)

namespace extensions {

namespace {

base::Value::List RunTabsQueryFunction(content::BrowserContext* browser_context,
                                       const Extension* extension,
                                       const std::string& query_info) {
  auto function = base::MakeRefCounted<TabsQueryFunction>();
  function->set_extension(extension);
  std::optional<base::Value> value =
      api_test_utils::RunFunctionAndReturnSingleResult(
          function.get(), query_info, browser_context,
          api_test_utils::FunctionMode::kNone);
  return std::move(*value).TakeList();
}

// Creates an extension with "tabs" permission.
scoped_refptr<const Extension> CreateTabsExtension() {
  return ExtensionBuilder("Extension with tabs permission")
      .AddAPIPermission("tabs")
      .Build();
}

// Creates a WebContents, attaches it to the tab strip, and navigates so we
// have |urls| as history.
content::WebContents* CreateAndAppendWebContentsWithHistory(
    Profile* profile,
    TabStripModel* tab_strip_model,
    const std::vector<GURL>& urls) {
  std::unique_ptr<content::WebContents> web_contents =
      content::WebContentsTester::CreateTestWebContents(profile, nullptr);
  content::WebContents* raw_web_contents = web_contents.get();

  tab_strip_model->AppendWebContents(std::move(web_contents), true);

  for (const auto& url : urls) {
    content::NavigationSimulator::NavigateAndCommitFromBrowser(raw_web_contents,
                                                               url);
    EXPECT_EQ(url, raw_web_contents->GetLastCommittedURL());
    EXPECT_EQ(url, raw_web_contents->GetVisibleURL());
  }

  return raw_web_contents;
}

}  // namespace

class TabsApiUnitTest : public ExtensionServiceTestBase {
 public:
  TabsApiUnitTest(const TabsApiUnitTest&) = delete;
  TabsApiUnitTest& operator=(const TabsApiUnitTest&) = delete;

 protected:
  TabsApiUnitTest()
      : ExtensionServiceTestBase(
            std::make_unique<content::BrowserTaskEnvironment>(
                base::test::TaskEnvironment::MainThreadType::UI)) {}
  ~TabsApiUnitTest() override = default;

  Browser* browser() { return browser_.get(); }
  TestBrowserWindow* browser_window() { return browser_window_.get(); }

  TabStripModel* GetTabStripModel() { return browser_->tab_strip_model(); }
  content::WebContents* GetActiveWebContents() {
    return GetTabStripModel()->GetActiveWebContents();
  }

  tab_groups::TabGroupSyncService* sync_service() {
    return tab_groups::SavedTabGroupUtils::GetServiceForProfile(
        browser()->profile());
  }

#if BUILDFLAG(IS_CHROMEOS)
  aura::Window* root_window() { return test_helper_.GetContext(); }
#endif

  // Returns whether the commit succeeded or not.
  bool CommitPendingLoadForController(
      content::NavigationController& controller);

 private:
  // ExtensionServiceTestBase:
  void SetUp() override;
  void TearDown() override;

  // The browser (and accompanying window).
  std::unique_ptr<TestBrowserWindow> browser_window_;
  std::unique_ptr<Browser> browser_;

#if BUILDFLAG(IS_CHROMEOS)
  ash::AshTestHelper test_helper_;
#endif
};

void TabsApiUnitTest::SetUp() {
#if BUILDFLAG(IS_CHROMEOS)
  ash::AshTestHelper::InitParams ash_params;
  ash_params.start_session = true;
  test_helper_.SetUp(std::move(ash_params));
#endif
  // Force TabManager/TabLifecycleUnitSource creation.
  g_browser_process->GetTabManager();

  ExtensionServiceTestBase::SetUp();
  InitializeEmptyExtensionService();

  browser_window_ = std::make_unique<TestBrowserWindow>();
  Browser::CreateParams params(profile(), true);
  params.type = Browser::TYPE_NORMAL;
  params.window = browser_window_.get();
  browser_.reset(Browser::Create(params));

  tab_groups::TabGroupSyncService* saved_service = sync_service();
  ASSERT_TRUE(saved_service);
  saved_service->SetIsInitializedForTesting(true);
}

void TabsApiUnitTest::TearDown() {
  // Do this first before resetting `browser_`.
  GetTabStripModel()->CloseAllTabs();

  browser_.reset();
  browser_window_.reset();
  ExtensionServiceTestBase::TearDown();
#if BUILDFLAG(IS_CHROMEOS)
  test_helper_.TearDown();
#endif
}

bool TabsApiUnitTest::CommitPendingLoadForController(
    content::NavigationController& controller) {
  if (!controller.GetPendingEntry()) {
    return false;
  }

  content::RenderFrameHostTester::CommitPendingLoad(&controller);
  return true;
}

// Bug fix for crbug.com/1196309. Ensure that an extension can't update the tab
// strip while a tab drag is in progress.
TEST_F(TabsApiUnitTest, IsTabStripEditable) {
  // Add a couple of web contents to the browser and get their tab IDs.
  constexpr int kNumTabs = 2;
  std::vector<int> tab_ids;
  std::vector<content::WebContents*> web_contentses;
  for (int i = 0; i < kNumTabs; ++i) {
    std::unique_ptr<content::WebContents> contents(
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr));
    CreateSessionServiceTabHelper(contents.get());
    tab_ids.push_back(
        sessions::SessionTabHelper::IdForTab(contents.get()).id());
    web_contentses.push_back(contents.get());
    GetTabStripModel()->AppendWebContents(std::move(contents),
                                          /*foreground=*/true);
  }
  ASSERT_EQ(kNumTabs, GetTabStripModel()->count());

  ASSERT_TRUE(browser_window()->IsTabStripEditable());
  auto extension = CreateTabsExtension();

  // Succeed while tab drag not in progress.
  {
    std::string args = base::StringPrintf("[{\"tabs\": [%d]}]", 0);
    scoped_refptr<TabsHighlightFunction> function =
        base::MakeRefCounted<TabsHighlightFunction>();
    function->set_extension(extension);
    ASSERT_TRUE(api_test_utils::RunFunction(
        function.get(), args, profile(), api_test_utils::FunctionMode::kNone));
  }

  // Start logical drag.
  browser_window()->SetTabStripNotEditableForTesting();
  ASSERT_FALSE(browser_window()->IsTabStripEditable());

  // Succeed with updates that don't interact with the tab strip model.
  {
    const char* url = "https://example.com/";
    std::string args =
        base::StringPrintf("[%d, {\"url\": \"%s\"}]", tab_ids[0], url);
    scoped_refptr<TabsUpdateFunction> function =
        base::MakeRefCounted<TabsUpdateFunction>();
    function->set_extension(extension);
    std::optional<base::Value> value =
        api_test_utils::RunFunctionAndReturnSingleResult(
            function.get(), args, profile(),
            api_test_utils::FunctionMode::kNone);
    ASSERT_TRUE(value && value->is_dict());
    EXPECT_EQ(*value->GetDict().FindString(tabs_constants::kPendingUrlKey),
              url);
  }

  // Succeed while edit in progress and calling chrome.tabs.query.
  {
    const char* args = "[{}]";
    scoped_refptr<TabsQueryFunction> function =
        base::MakeRefCounted<TabsQueryFunction>();
    function->set_extension(extension);
    ASSERT_TRUE(api_test_utils::RunFunction(
        function.get(), args, profile(), api_test_utils::FunctionMode::kNone));
  }

  // Succeed while edit in progress and calling chrome.tabs.get.
  {
    std::string args = base::StringPrintf("[%d]", tab_ids[0]);
    scoped_refptr<TabsGetFunction> function =
        base::MakeRefCounted<TabsGetFunction>();
    function->set_extension(extension);
    ASSERT_TRUE(api_test_utils::RunFunction(
        function.get(), args, profile(), api_test_utils::FunctionMode::kNone));
  }

  // Bug fix for crbug.com/1198717. Error updating tabs while drag in progress.
  {
    std::string args =
        base::StringPrintf("[%d, {\"highlighted\": true}]", tab_ids[0]);
    auto function = base::MakeRefCounted<TabsUpdateFunction>();
    function->set_extension(extension);
    std::string error = api_test_utils::RunFunctionAndReturnError(
        function.get(), args, profile());
    EXPECT_EQ(ExtensionTabUtil::kTabStripNotEditableError, error);
  }

  // Error highlighting tab while drag in progress.
  {
    std::string args = base::StringPrintf("[{\"tabs\": [%d]}]", tab_ids[0]);
    auto function = base::MakeRefCounted<TabsHighlightFunction>();
    function->set_extension(extension);
    std::string error = api_test_utils::RunFunctionAndReturnError(
        function.get(), args, profile(), api_test_utils::FunctionMode::kNone);
    EXPECT_EQ(ExtensionTabUtil::kTabStripNotEditableError, error);
  }

  // Bug fix for crbug.com/1197146. Tab group modification during drag.
  {
    std::string args = base::StringPrintf("[{\"tabIds\": [%d]}]", tab_ids[0]);
    scoped_refptr<TabsGroupFunction> function =
        base::MakeRefCounted<TabsGroupFunction>();
    function->set_extension(extension);
    std::string error = api_test_utils::RunFunctionAndReturnError(
        function.get(), args, profile());
    EXPECT_EQ(ExtensionTabUtil::kTabStripNotEditableError, error);
  }

  // TODO(solomonkinard): Consider adding tests for drag cancellation.
}

TEST_F(TabsApiUnitTest, QueryWithoutTabsPermission) {
  auto tab_urls = std::to_array<GURL>({
      GURL("http://www.google.com"),
      GURL("http://www.example.com"),
      GURL("https://www.google.com"),
  });
  auto tab_titles =
      std::to_array<std::string>({"", "Sample title", "Sample title"});

  // Add 3 web contentses to the browser.
  std::array<content::WebContents*, std::size(tab_urls)> web_contentses;
  for (size_t i = 0; i < std::size(tab_urls); ++i) {
    std::unique_ptr<content::WebContents> web_contents =
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr);
    content::WebContents* raw_web_contents = web_contents.get();
    web_contentses[i] = raw_web_contents;
    GetTabStripModel()->AppendWebContents(std::move(web_contents), true);
    EXPECT_EQ(GetActiveWebContents(), raw_web_contents);
    content::WebContentsTester* web_contents_tester =
        content::WebContentsTester::For(raw_web_contents);
    web_contents_tester->NavigateAndCommit(tab_urls[i]);
    raw_web_contents->GetController().GetVisibleEntry()->SetTitle(
        base::ASCIIToUTF16(tab_titles[i]));
  }

  const char* kTitleAndURLQueryInfo =
      "[{\"title\": \"Sample title\", \"url\": \"*://www.google.com/*\"}]";

  // An extension without "tabs" permission will see none of the 3 tabs.
  scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build();
  base::Value::List tabs_list_without_permission =
      RunTabsQueryFunction(profile(), extension.get(), kTitleAndURLQueryInfo);
  EXPECT_EQ(0u, tabs_list_without_permission.size());

  // An extension with "tabs" permission however will see the third tab.
  scoped_refptr<const Extension> extension_with_permission =
      ExtensionBuilder()
          .SetManifest(
              base::Value::Dict()
                  .Set("name", "Extension with tabs permission")
                  .Set("version", "1.0")
                  .Set("manifest_version", 2)
                  .Set("permissions", base::Value::List().Append("tabs")))
          .Build();
  base::Value::List tabs_list_with_permission = RunTabsQueryFunction(
      profile(), extension_with_permission.get(), kTitleAndURLQueryInfo);
  ASSERT_EQ(1u, tabs_list_with_permission.size());

  const base::Value& third_tab_info = tabs_list_with_permission[0];
  ASSERT_TRUE(third_tab_info.is_dict());
  std::optional<int> third_tab_id = third_tab_info.GetDict().FindInt("id");
  EXPECT_EQ(ExtensionTabUtil::GetTabId(web_contentses[2]), third_tab_id);
}

TEST_F(TabsApiUnitTest, QueryWithHostPermission) {
  auto tab_urls = std::to_array<GURL>({
      GURL("http://www.google.com"),
      GURL("http://www.example.com"),
      GURL("https://www.google.com/test"),
  });
  auto tab_titles =
      std::to_array<std::string>({"", "Sample title", "Sample title"});

  // Add 3 web contentses to the browser.
  std::array<content::WebContents*, std::size(tab_urls)> web_contentses;
  for (size_t i = 0; i < std::size(tab_urls); ++i) {
    std::unique_ptr<content::WebContents> web_contents =
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr);
    content::WebContents* raw_web_contents = web_contents.get();
    web_contentses[i] = raw_web_contents;
    GetTabStripModel()->AppendWebContents(std::move(web_contents), true);
    EXPECT_EQ(GetActiveWebContents(), raw_web_contents);
    content::WebContentsTester* web_contents_tester =
        content::WebContentsTester::For(raw_web_contents);
    web_contents_tester->NavigateAndCommit(tab_urls[i]);
    raw_web_contents->GetController().GetVisibleEntry()->SetTitle(
        base::ASCIIToUTF16(tab_titles[i]));
  }

  const char* kTitleAndURLQueryInfo =
      "[{\"title\": \"Sample title\", \"url\": \"*://www.google.com/*\"}]";

  // An extension with "host" permission will only see the third tab.
  scoped_refptr<const Extension> extension_with_permission =
      ExtensionBuilder()
          .SetManifest(base::Value::Dict()
                           .Set("name", "Extension with tabs permission")
                           .Set("version", "1.0")
                           .Set("manifest_version", 2)
                           .Set("permissions", base::Value::List().Append(
                                                   "*://www.google.com/*")))
          .Build();

  {
    base::Value::List tabs_list_with_permission = RunTabsQueryFunction(
        profile(), extension_with_permission.get(), kTitleAndURLQueryInfo);
    ASSERT_EQ(1u, tabs_list_with_permission.size());

    const base::Value& third_tab_info = tabs_list_with_permission[0];
    ASSERT_TRUE(third_tab_info.is_dict());
    std::optional<int> third_tab_id = third_tab_info.GetDict().FindInt("id");
    EXPECT_EQ(ExtensionTabUtil::GetTabId(web_contentses[2]), third_tab_id);
  }

  // Try the same without title, first and third tabs will match.
  const char* kURLQueryInfo = "[{\"url\": \"*://www.google.com/*\"}]";
  {
    base::Value::List tabs_list_with_permission = RunTabsQueryFunction(
        profile(), extension_with_permission.get(), kURLQueryInfo);
    ASSERT_EQ(2u, tabs_list_with_permission.size());

    const base::Value& first_tab_info = tabs_list_with_permission[0];
    ASSERT_TRUE(first_tab_info.is_dict());
    const base::Value& third_tab_info = tabs_list_with_permission[1];
    ASSERT_TRUE(third_tab_info.is_dict());

    std::vector<int> expected_tabs_ids;
    expected_tabs_ids.push_back(ExtensionTabUtil::GetTabId(web_contentses[0]));
    expected_tabs_ids.push_back(ExtensionTabUtil::GetTabId(web_contentses[2]));

    std::optional<int> first_tab_id = first_tab_info.GetDict().FindInt("id");
    ASSERT_TRUE(first_tab_id);
    EXPECT_TRUE(base::Contains(expected_tabs_ids, *first_tab_id));

    std::optional<int> third_tab_id = third_tab_info.GetDict().FindInt("id");
    ASSERT_TRUE(third_tab_id);
    EXPECT_TRUE(base::Contains(expected_tabs_ids, *third_tab_id));
  }
}

// Test that using the PDF extension for tab updates is treated as a
// renderer-initiated navigation. crbug.com/660498
TEST_F(TabsApiUnitTest, PDFExtensionNavigation) {
  auto manifest = base::Value::Dict()
                      .Set("name", "pdfext")
                      .Set("description", "desc")
                      .Set("version", "0.1")
                      .Set("manifest_version", 2)
                      .Set("permissions", base::Value::List().Append("tabs"));
  scoped_refptr<const Extension> extension =
      ExtensionBuilder()
          .SetManifest(std::move(manifest))
          .SetID(extension_misc::kPdfExtensionId)
          .Build();
  ASSERT_TRUE(extension);

  std::unique_ptr<content::WebContents> web_contents =
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr);
  content::WebContents* raw_web_contents = web_contents.get();
  ASSERT_TRUE(raw_web_contents);
  GetTabStripModel()->AppendWebContents(std::move(web_contents), true);
  content::WebContentsTester* web_contents_tester =
      content::WebContentsTester::For(raw_web_contents);
  const GURL kGoogle("http://www.google.com");
  web_contents_tester->NavigateAndCommit(kGoogle);
  EXPECT_EQ(kGoogle, raw_web_contents->GetLastCommittedURL());
  EXPECT_EQ(kGoogle, raw_web_contents->GetVisibleURL());

  CreateSessionServiceTabHelper(raw_web_contents);
  int tab_id = sessions::SessionTabHelper::IdForTab(raw_web_contents).id();

  auto function = base::MakeRefCounted<TabsUpdateFunction>();
  function->SetBrowserContextForTesting(profile());
  function->set_extension(extension.get());
  function->SetArgs(base::test::ParseJsonList(
      base::StringPrintf(R"([%d, {"url":"http://example.com"}])", tab_id)));
  api_test_utils::SendResponseHelper response_helper(function.get());
  function->RunWithValidation().Execute();

  EXPECT_EQ(kGoogle, raw_web_contents->GetLastCommittedURL());
  EXPECT_EQ(kGoogle, raw_web_contents->GetVisibleURL());

  // Clean up.
  response_helper.WaitForResponse();
  base::RunLoop().RunUntilIdle();
}

// Tests that non-validation failure in tabs.executeScript results in error, and
// not bad_message.
// Regression test for https://crbug.com/642794.
TEST_F(TabsApiUnitTest, ExecuteScriptNoTabIsNonFatalError) {
  scoped_refptr<const Extension> extension_with_tabs_permission =
      CreateTabsExtension();
  auto function = base::MakeRefCounted<TabsExecuteScriptFunction>();
  function->set_extension(extension_with_tabs_permission);
  const char* kArgs = R"(["", {"code": ""}])";
  std::string error = api_test_utils::RunFunctionAndReturnError(
      function.get(), kArgs,
      profile(),  // profile() doesn't have any tabs.
      api_test_utils::FunctionMode::kNone);
  EXPECT_EQ(tabs_constants::kNoTabInBrowserWindowError, error);
}

// Tests that calling chrome.tabs.update updates the URL as expected.
TEST_F(TabsApiUnitTest, TabsUpdate) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("UpdateTest").Build();
  const GURL kExampleCom("http://example.com");
  const GURL kChromiumOrg("https://chromium.org");

  // Add a web contents to the browser.
  std::unique_ptr<content::WebContents> contents(
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr));
  content::WebContents* raw_contents = contents.get();
  GetTabStripModel()->AppendWebContents(std::move(contents), true);
  EXPECT_EQ(GetActiveWebContents(), raw_contents);
  CreateSessionServiceTabHelper(raw_contents);
  int tab_id = sessions::SessionTabHelper::IdForTab(raw_contents).id();

  // Navigate the browser to example.com
  content::WebContentsTester* web_contents_tester =
      content::WebContentsTester::For(raw_contents);
  web_contents_tester->NavigateAndCommit(kExampleCom);
  EXPECT_EQ(kExampleCom, raw_contents->GetLastCommittedURL());

  // Use the TabsUpdateFunction to navigate to chromium.org
  auto function = base::MakeRefCounted<TabsUpdateFunction>();
  function->set_extension(extension);
  static constexpr char kFormatArgs[] = R"([%d, {"url": "%s"}])";
  const std::string args =
      base::StringPrintf(kFormatArgs, tab_id, kChromiumOrg.spec().c_str());
  ASSERT_TRUE(api_test_utils::RunFunction(function.get(), args, profile(),
                                          api_test_utils::FunctionMode::kNone));
  ASSERT_TRUE(
      CommitPendingLoadForController(GetActiveWebContents()->GetController()));
  EXPECT_EQ(kChromiumOrg, raw_contents->GetLastCommittedURL());
}

// Tests that calling chrome.tabs.update does not update a saved tab.
TEST_F(TabsApiUnitTest, TabsUpdateSavedTabGroupTab) {
  const GURL kExampleCom("http://example.com");
  const GURL kChromiumOrg("https://chromium.org");

  // Add a web contents to the browser.
  content::WebContents* raw_contents;
  {
    std::unique_ptr<content::WebContents> contents =
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr);
    raw_contents = contents.get();
    GetTabStripModel()->AppendWebContents(std::move(contents), true);
  }

  // contents used to test active state by taking active state first.
  content::WebContents* raw_non_updated_contents;
  {
    std::unique_ptr<content::WebContents> non_updated_contents =
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr);
    raw_non_updated_contents = non_updated_contents.get();
    GetTabStripModel()->AppendWebContents(std::move(non_updated_contents),
                                          false);
  }
  ASSERT_NE(raw_contents, nullptr);
  ASSERT_NE(raw_non_updated_contents, nullptr);

  EXPECT_EQ(GetActiveWebContents(), raw_contents);
  CreateSessionServiceTabHelper(raw_contents);
  int tab_id = sessions::SessionTabHelper::IdForTab(raw_contents).id();
  int non_updated_tab_id =
      sessions::SessionTabHelper::IdForTab(raw_non_updated_contents).id();

  // Navigate the browser to example.com
  content::WebContentsTester* web_contents_tester =
      content::WebContentsTester::For(raw_contents);
  web_contents_tester->NavigateAndCommit(kExampleCom);
  EXPECT_EQ(kExampleCom, raw_contents->GetLastCommittedURL());

  tab_groups::TabGroupSyncService* saved_service = sync_service();
  ASSERT_TRUE(saved_service);

  // Group the tab and save it.
  tab_groups::TabGroupId group = GetTabStripModel()->AddToNewGroup(
      {GetTabStripModel()->GetIndexOfWebContents(raw_contents)});
  tab_groups::TabGroupVisualData visual_data(
      u"Initial title", tab_groups::TabGroupColorId::kBlue);
  browser()->tab_strip_model()->ChangeTabGroupVisuals(group, visual_data);

  EXPECT_TRUE(
      ExtensionTabUtil::TabIsInSavedTabGroup(raw_contents, GetTabStripModel()));

  {  // Test the active state change for a saved tab.
    GetTabStripModel()->ActivateTabAt(
        GetTabStripModel()->GetIndexOfWebContents(raw_non_updated_contents));
    scoped_refptr<const Extension> extension =
        ExtensionBuilder("UpdateTest").Build();
    auto function = base::MakeRefCounted<TabsUpdateFunction>();
    function->set_extension(extension);
    static constexpr char kFormatArgs[] = R"([%d, {"active": true}])";
    const std::string args = base::StringPrintf(kFormatArgs, tab_id);
    EXPECT_TRUE(api_test_utils::RunFunction(
        function.get(), args, profile(), api_test_utils::FunctionMode::kNone));
    EXPECT_EQ(GetActiveWebContents(), raw_contents);
  }

  ASSERT_TRUE(saved_service->GetGroup(group));

  {  // Reset the active states, and then test highlighted for a saved tab.
    GetTabStripModel()->ActivateTabAt(
        GetTabStripModel()->GetIndexOfWebContents(raw_non_updated_contents));
    GetTabStripModel()->DeselectTabAt(
        GetTabStripModel()->GetIndexOfWebContents(raw_contents));

    scoped_refptr<const Extension> extension =
        ExtensionBuilder("UpdateTest").Build();
    auto function = base::MakeRefCounted<TabsUpdateFunction>();
    function->set_extension(extension);
    static constexpr char kFormatArgs[] = R"([%d, {"highlighted": true}])";
    const std::string args = base::StringPrintf(kFormatArgs, tab_id);
    EXPECT_TRUE(api_test_utils::RunFunction(
        function.get(), args, profile(), api_test_utils::FunctionMode::kNone));
    EXPECT_EQ(GetActiveWebContents(), raw_contents);
  }

  ASSERT_TRUE(saved_service->GetGroup(group));

  {  // Reset the active states, and then test selected state for a saved tab.
    GetTabStripModel()->ActivateTabAt(
        GetTabStripModel()->GetIndexOfWebContents(raw_non_updated_contents));
    GetTabStripModel()->DeselectTabAt(
        GetTabStripModel()->GetIndexOfWebContents(raw_contents));

    scoped_refptr<const Extension> extension =
        ExtensionBuilder("UpdateTest").Build();
    auto function = base::MakeRefCounted<TabsUpdateFunction>();
    function->set_extension(extension);
    static constexpr char kFormatArgs[] = R"([%d, {"selected": true}])";
    const std::string args = base::StringPrintf(kFormatArgs, tab_id);
    EXPECT_TRUE(api_test_utils::RunFunction(
        function.get(), args, profile(), api_test_utils::FunctionMode::kNone));
    EXPECT_TRUE(GetTabStripModel()->IsTabSelected(
        GetTabStripModel()->GetIndexOfWebContents(raw_contents)));
  }

  ASSERT_TRUE(saved_service->GetGroup(group));

  {  // Test Muted state.
    scoped_refptr<const Extension> extension =
        ExtensionBuilder("UpdateTest").Build();
    auto function = base::MakeRefCounted<TabsUpdateFunction>();
    function->set_extension(extension);
    static constexpr char kFormatArgs[] = R"([%d, {"muted": true}])";
    const std::string args = base::StringPrintf(kFormatArgs, tab_id);
    EXPECT_TRUE(api_test_utils::RunFunction(
        function.get(), args, profile(), api_test_utils::FunctionMode::kNone));
  }

  ASSERT_TRUE(saved_service->GetGroup(group));

  {  // Test setting the opener.
    scoped_refptr<const Extension> extension =
        ExtensionBuilder("UpdateTest").Build();
    auto function = base::MakeRefCounted<TabsUpdateFunction>();
    function->set_extension(extension);
    static constexpr char kFormatArgs[] = R"([%d, {"openerTabId": %d}])";
    const std::string args =
        base::StringPrintf(kFormatArgs, tab_id, non_updated_tab_id);
    EXPECT_TRUE(api_test_utils::RunFunction(
        function.get(), args, profile(), api_test_utils::FunctionMode::kNone));
  }

  ASSERT_TRUE(saved_service->GetGroup(group));

  {  // Test setting the disard state.
    scoped_refptr<const Extension> extension =
        ExtensionBuilder("UpdateTest").Build();
    auto function = base::MakeRefCounted<TabsUpdateFunction>();
    function->set_extension(extension);
    static constexpr char kFormatArgs[] = R"([%d, {"autoDiscardable": true}])";
    const std::string args = base::StringPrintf(kFormatArgs, tab_id);
    EXPECT_TRUE(api_test_utils::RunFunction(
        function.get(), args, profile(), api_test_utils::FunctionMode::kNone));
  }

  ASSERT_TRUE(saved_service->GetGroup(group));

  {  // Test setting URL should pass.
    scoped_refptr<const Extension> extension =
        ExtensionBuilder("UpdateTest").Build();
    auto function = base::MakeRefCounted<TabsUpdateFunction>();
    function->set_extension(extension);
    static constexpr char kFormatArgs[] = R"([%d, {"url": "%s"}])";
    const std::string args =
        base::StringPrintf(kFormatArgs, tab_id, kChromiumOrg.spec().c_str());
    EXPECT_TRUE(api_test_utils::RunFunction(
        function.get(), args, profile(), api_test_utils::FunctionMode::kNone));
  }

  ASSERT_TRUE(saved_service->GetGroup(group));

  // Test setting pinned state should pass. This must be done last since pinning
  // destroys the group.
  {
    scoped_refptr<const Extension> extension =
        ExtensionBuilder("UpdateTest").Build();
    auto function = base::MakeRefCounted<TabsUpdateFunction>();
    function->set_extension(extension);
    static constexpr char kFormatArgs[] = R"([%d, {"pinned": true}])";
    const std::string args = base::StringPrintf(kFormatArgs, tab_id);
    EXPECT_TRUE(api_test_utils::RunFunction(
        function.get(), args, profile(), api_test_utils::FunctionMode::kNone));
  }

  ASSERT_FALSE(saved_service->GetGroup(group));
}

// Tests that calling chrome.tabs.update with a JavaScript URL results
// in an error.
TEST_F(TabsApiUnitTest, TabsUpdateJavaScriptUrlNotAllowed) {
  // An extension with access to www.example.com.
  scoped_refptr<const Extension> extension =
      ExtensionBuilder()
          .SetManifest(base::Value::Dict()
                           .Set("name", "Extension with a host permission")
                           .Set("version", "1.0")
                           .Set("manifest_version", 2)
                           .Set("permissions", base::Value::List().Append(
                                                   "http://www.example.com/*")))
          .Build();
  auto function = base::MakeRefCounted<TabsUpdateFunction>();
  function->set_extension(extension);

  // Add a web contents to the browser.
  std::unique_ptr<content::WebContents> contents(
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr));
  content::WebContents* raw_contents = contents.get();
  GetTabStripModel()->AppendWebContents(std::move(contents), true);
  EXPECT_EQ(GetActiveWebContents(), raw_contents);
  content::WebContentsTester* web_contents_tester =
      content::WebContentsTester::For(raw_contents);
  web_contents_tester->NavigateAndCommit(GURL("http://www.example.com"));
  CreateSessionServiceTabHelper(raw_contents);
  int tab_id = sessions::SessionTabHelper::IdForTab(raw_contents).id();

  static constexpr char kFormatArgs[] = R"([%d, {"url": "%s"}])";
  const std::string args = base::StringPrintf(
      kFormatArgs, tab_id, "javascript:void(document.title = 'Won't work')");
  std::string error = api_test_utils::RunFunctionAndReturnError(
      function.get(), args, profile(), api_test_utils::FunctionMode::kNone);
  EXPECT_EQ(ExtensionTabUtil::kJavaScriptUrlsNotAllowedInExtensionNavigations,
            error);
}

// Test that the tabs.move() function correctly rearranges sets of tabs within a
// single window.
TEST_F(TabsApiUnitTest, TabsMoveWithinWindow) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("MoveWithinWindowTest").Build();

  // Add several web contents to the browser and get their tab IDs.
  constexpr int kNumTabs = 5;
  std::vector<int> tab_ids;
  std::vector<content::WebContents*> web_contentses;
  for (int i = 0; i < kNumTabs; ++i) {
    std::unique_ptr<content::WebContents> contents(
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr));

    CreateSessionServiceTabHelper(contents.get());
    tab_ids.push_back(
        sessions::SessionTabHelper::IdForTab(contents.get()).id());
    web_contentses.push_back(contents.get());

    GetTabStripModel()->AppendWebContents(std::move(contents),
                                          /*foreground=*/true);
  }
  ASSERT_EQ(kNumTabs, GetTabStripModel()->count());

  // Use the TabsMoveFunction to move tabs 0, 2, and 4 to index 1.
  auto function = base::MakeRefCounted<TabsMoveFunction>();
  function->set_extension(extension);
  constexpr char kFormatArgs[] = R"([[%d, %d, %d], {"index": 1}])";
  const std::string args =
      base::StringPrintf(kFormatArgs, tab_ids[0], tab_ids[2], tab_ids[4]);
  ASSERT_TRUE(api_test_utils::RunFunction(function.get(), args, profile(),
                                          api_test_utils::FunctionMode::kNone));

  TabStripModel* tab_strip_model = GetTabStripModel();
  EXPECT_EQ(tab_strip_model->GetWebContentsAt(0), web_contentses[1]);
  EXPECT_EQ(tab_strip_model->GetWebContentsAt(1), web_contentses[0]);
  EXPECT_EQ(tab_strip_model->GetWebContentsAt(2), web_contentses[2]);
  EXPECT_EQ(tab_strip_model->GetWebContentsAt(3), web_contentses[4]);
  EXPECT_EQ(tab_strip_model->GetWebContentsAt(4), web_contentses[3]);
}

// Test that the tabs.move() function correctly rearranges sets of tabs across
// windows.
TEST_F(TabsApiUnitTest, TabsMoveAcrossWindows) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("MoveAcrossWindowTest").Build();

  // Add several web contents to the original browser and get their tab IDs.
  constexpr int kNumTabs = 5;
  std::vector<int> tab_ids;
  std::vector<content::WebContents*> web_contentses;
  for (int i = 0; i < kNumTabs; ++i) {
    std::unique_ptr<content::WebContents> contents(
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr));

    CreateSessionServiceTabHelper(contents.get());
    tab_ids.push_back(
        sessions::SessionTabHelper::IdForTab(contents.get()).id());
    web_contentses.push_back(contents.get());

    GetTabStripModel()->AppendWebContents(std::move(contents),
                                          /*foreground=*/true);
  }
  ASSERT_EQ(kNumTabs, GetTabStripModel()->count());

  // Create a new window and add a few tabs, getting the ID of the last tab.
  auto window2 = std::make_unique<TestBrowserWindow>();
  Browser::CreateParams params(profile(), /* user_gesture */ true);
  params.type = Browser::TYPE_NORMAL;
  params.window = window2.get();
  // TestBrowserWindowOwner handles its own lifetime, and also cleans up
  // |window2|.
  new TestBrowserWindowOwner(std::move(window2));
  std::unique_ptr<Browser> browser2(Browser::Create(params));
  BrowserList::SetLastActive(browser2.get());
  int window_id2 = ExtensionTabUtil::GetWindowId(browser2.get());

  constexpr int kNumTabs2 = 3;
  for (int i = 0; i < kNumTabs2; ++i) {
    std::unique_ptr<content::WebContents> contents(
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr));
    CreateSessionServiceTabHelper(contents.get());
    browser2->tab_strip_model()->AppendWebContents(std::move(contents),
                                                   /*foreground=*/true);
  }
  ASSERT_EQ(kNumTabs2, browser2->tab_strip_model()->count());

  content::WebContents* web_contents2 =
      browser2->tab_strip_model()->GetWebContentsAt(2);
  int tab_id2 = sessions::SessionTabHelper::IdForTab(web_contents2).id();

  // Use the TabsMoveFunction to move tab 2 from browser2 and tabs 0, 2, and 4
  // from the original browser to index 1 of browser2.
  constexpr int kNumTabsMovedAcrossWindows = 3;
  auto function = base::MakeRefCounted<TabsMoveFunction>();
  function->set_extension(extension);
  constexpr char kFormatArgs[] =
      R"([[%d, %d, %d, %d], {"windowId": %d, "index": 1}])";
  const std::string args = base::StringPrintf(
      kFormatArgs, tab_id2, tab_ids[0], tab_ids[2], tab_ids[4], window_id2);
  ASSERT_TRUE(api_test_utils::RunFunction(function.get(), args, profile(),
                                          api_test_utils::FunctionMode::kNone));

  TabStripModel* tab_strip_model2 = browser2->tab_strip_model();
  ASSERT_EQ(kNumTabs2 + kNumTabsMovedAcrossWindows, tab_strip_model2->count());
  EXPECT_EQ(tab_strip_model2->GetWebContentsAt(1), web_contents2);
  EXPECT_EQ(tab_strip_model2->GetWebContentsAt(2), web_contentses[0]);
  EXPECT_EQ(tab_strip_model2->GetWebContentsAt(3), web_contentses[2]);
  EXPECT_EQ(tab_strip_model2->GetWebContentsAt(4), web_contentses[4]);

  // Clean up.
  browser2->tab_strip_model()->CloseAllTabs();
}

TEST_F(TabsApiUnitTest, TabsMoveAcrossWindowsShouldRespectGroupContiguity) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("MoveAcrossWindowWithInvalidIndexTest").Build();

  // Add several web contents to the original browser and get their tab IDs.
  constexpr int kNumTabs = 5;
  std::vector<int> tab_ids;
  std::vector<content::WebContents*> web_contentses;
  for (int i = 0; i < kNumTabs; ++i) {
    std::unique_ptr<content::WebContents> contents(
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr));

    CreateSessionServiceTabHelper(contents.get());
    tab_ids.push_back(
        sessions::SessionTabHelper::IdForTab(contents.get()).id());
    web_contentses.push_back(contents.get());

    GetTabStripModel()->AppendWebContents(std::move(contents),
                                          /*foreground=*/true);
  }
  ASSERT_EQ(kNumTabs, GetTabStripModel()->count());

  // Create a new window and add a few tabs, getting the ID of the last tab.
  auto window2 = std::make_unique<TestBrowserWindow>();
  Browser::CreateParams params(profile(), /* user_gesture */ true);
  params.type = Browser::TYPE_NORMAL;
  params.window = window2.get();
  // TestBrowserWindowOwner handles its own lifetime, and also cleans up
  // |window2|.
  new TestBrowserWindowOwner(std::move(window2));
  std::unique_ptr<Browser> browser2(Browser::Create(params));
  BrowserList::SetLastActive(browser2.get());
  int window_id2 = ExtensionTabUtil::GetWindowId(browser2.get());

  constexpr int kNumTabs2 = 3;
  for (int i = 0; i < kNumTabs2; ++i) {
    std::unique_ptr<content::WebContents> contents(
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr));
    CreateSessionServiceTabHelper(contents.get());
    browser2->tab_strip_model()->AppendWebContents(std::move(contents),
                                                   /*foreground=*/true);
  }
  browser2->tab_strip_model()->AddToNewGroup({0, 1});
  ASSERT_EQ(kNumTabs2, browser2->tab_strip_model()->count());

  content::WebContents* web_contents2 = GetTabStripModel()->GetWebContentsAt(2);
  int tab_extension_id =
      sessions::SessionTabHelper::IdForTab(web_contents2).id();

  // Use the TabsMoveFunction to move tab at index 2 from browser2 to the middle
  // of a group in browser1.
  auto function = base::MakeRefCounted<TabsMoveFunction>();
  function->set_extension(extension);
  constexpr char kFormatArgs[] = R"([[%d], {"windowId": %d, "index": 1}])";
  const std::string args =
      base::StringPrintf(kFormatArgs, tab_extension_id, window_id2);

  std::string error = api_test_utils::RunFunctionAndReturnError(
      function.get(), args, profile(), api_test_utils::FunctionMode::kNone);
  EXPECT_EQ(tabs_constants::kInvalidTabIndexBreaksGroupContiguity, error);

  // Clean up.
  browser2->tab_strip_model()->CloseAllTabs();
}

// Tests that calling chrome.tabs.move doesn't move a saved tab.
TEST_F(TabsApiUnitTest, TabsMoveSavedTabGroupTabAllowed) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("MoveWithinWindowTest").Build();

  // Add several web contents to the browser and get their tab IDs.
  constexpr int kNumTabs = 5;
  std::vector<int> tab_ids;
  std::vector<content::WebContents*> web_contentses;
  for (int i = 0; i < kNumTabs; ++i) {
    std::unique_ptr<content::WebContents> contents(
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr));

    CreateSessionServiceTabHelper(contents.get());
    tab_ids.push_back(
        sessions::SessionTabHelper::IdForTab(contents.get()).id());
    web_contentses.push_back(contents.get());

    GetTabStripModel()->AppendWebContents(std::move(contents),
                                          /*foreground=*/true);
  }
  ASSERT_EQ(kNumTabs, GetTabStripModel()->count());

  tab_groups::TabGroupSyncService* saved_service = sync_service();
  ASSERT_TRUE(saved_service);

  // Group the tab and save it.
  tab_groups::TabGroupId group = GetTabStripModel()->AddToNewGroup({0, 1, 2});
  tab_groups::TabGroupVisualData visual_data(
      u"Initial title", tab_groups::TabGroupColorId::kBlue);
  browser()->tab_strip_model()->ChangeTabGroupVisuals(group, visual_data);

  // Use the TabsUpdateFunction to navigate to chromium.org
  int tab_extension_id = sessions::SessionTabHelper::IdForTab(
                             GetTabStripModel()->GetWebContentsAt(0))
                             .id();
  auto function = base::MakeRefCounted<TabsMoveFunction>();
  function->set_extension(extension);
  constexpr char kFormatArgs[] = R"([[%d], {"index": 1}])";
  const std::string args = base::StringPrintf(kFormatArgs, tab_extension_id);

  EXPECT_TRUE(api_test_utils::RunFunction(function.get(), args, profile(),
                                          api_test_utils::FunctionMode::kNone));

  EXPECT_EQ(GetTabStripModel()->GetWebContentsAt(0), web_contentses[1]);
  EXPECT_EQ(GetTabStripModel()->GetWebContentsAt(1), web_contentses[0]);
}

// Test that the tabs.group() function correctly rearranges sets of tabs within
// a single window before grouping.
TEST_F(TabsApiUnitTest, TabsGroupWithinWindow) {
  ASSERT_TRUE(GetTabStripModel()->SupportsTabGroups());

  scoped_refptr<const Extension> extension =
      ExtensionBuilder("GroupWithinWindowTest").Build();

  // Add several web contents to the browser and get their tab IDs.
  constexpr int kNumTabs = 5;
  std::vector<int> tab_ids;
  std::vector<content::WebContents*> web_contentses;
  for (int i = 0; i < kNumTabs; ++i) {
    std::unique_ptr<content::WebContents> contents(
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr));

    CreateSessionServiceTabHelper(contents.get());
    tab_ids.push_back(
        sessions::SessionTabHelper::IdForTab(contents.get()).id());
    web_contentses.push_back(contents.get());

    GetTabStripModel()->AppendWebContents(std::move(contents),
                                          /* foreground */ true);
  }
  ASSERT_EQ(kNumTabs, GetTabStripModel()->count());

  // Use the TabsGroupFunction to group tabs 0, 2, and 4.
  auto function = base::MakeRefCounted<TabsGroupFunction>();
  function->set_extension(extension);
  constexpr char kFormatArgs[] = R"([{"tabIds": [%d, %d, %d]}])";
  const std::string args =
      base::StringPrintf(kFormatArgs, tab_ids[0], tab_ids[2], tab_ids[4]);
  ASSERT_TRUE(api_test_utils::RunFunction(function.get(), args, profile(),
                                          api_test_utils::FunctionMode::kNone));

  TabStripModel* tab_strip_model = GetTabStripModel();
  EXPECT_EQ(tab_strip_model->GetWebContentsAt(0), web_contentses[0]);
  EXPECT_EQ(tab_strip_model->GetWebContentsAt(1), web_contentses[2]);
  EXPECT_EQ(tab_strip_model->GetWebContentsAt(2), web_contentses[4]);
  EXPECT_EQ(tab_strip_model->GetWebContentsAt(3), web_contentses[1]);
  EXPECT_EQ(tab_strip_model->GetWebContentsAt(4), web_contentses[3]);

  std::optional<tab_groups::TabGroupId> group =
      tab_strip_model->GetTabGroupForTab(0);
  EXPECT_TRUE(group.has_value());
  EXPECT_EQ(group, tab_strip_model->GetTabGroupForTab(1));
  EXPECT_EQ(group, tab_strip_model->GetTabGroupForTab(2));
  EXPECT_FALSE(tab_strip_model->GetTabGroupForTab(3));
  EXPECT_FALSE(tab_strip_model->GetTabGroupForTab(4));
}

// Test that the tabs.group() function correctly groups tabs even when given
// out-of-order or duplicate tab IDs.
TEST_F(TabsApiUnitTest, TabsGroupMixedTabIds) {
  ASSERT_TRUE(GetTabStripModel()->SupportsTabGroups());

  scoped_refptr<const Extension> extension =
      ExtensionBuilder("GroupMixedTabIdsTest").Build();

  // Add several web contents to the browser and get their tab IDs.
  constexpr int kNumTabs = 5;
  std::vector<int> tab_ids;
  std::vector<content::WebContents*> web_contentses;
  for (int i = 0; i < kNumTabs; ++i) {
    std::unique_ptr<content::WebContents> contents(
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr));

    CreateSessionServiceTabHelper(contents.get());
    tab_ids.push_back(
        sessions::SessionTabHelper::IdForTab(contents.get()).id());
    web_contentses.push_back(contents.get());

    GetTabStripModel()->AppendWebContents(std::move(contents),
                                          /*foreground=*/true);
  }
  ASSERT_EQ(kNumTabs, GetTabStripModel()->count());

  // Use the TabsGroupFunction to group tab 1 twice, along with tabs 3 and 2.
  auto function = base::MakeRefCounted<TabsGroupFunction>();
  function->set_extension(extension);
  constexpr char kFormatArgs[] = R"([{"tabIds": [%d, %d, %d, %d]}])";
  const std::string args = base::StringPrintf(
      kFormatArgs, tab_ids[1], tab_ids[1], tab_ids[3], tab_ids[2]);
  ASSERT_TRUE(api_test_utils::RunFunction(function.get(), args, profile(),
                                          api_test_utils::FunctionMode::kNone));

  TabStripModel* tab_strip_model = GetTabStripModel();
  EXPECT_EQ(tab_strip_model->GetWebContentsAt(0), web_contentses[0]);
  EXPECT_EQ(tab_strip_model->GetWebContentsAt(1), web_contentses[1]);
  EXPECT_EQ(tab_strip_model->GetWebContentsAt(2), web_contentses[2]);
  EXPECT_EQ(tab_strip_model->GetWebContentsAt(3), web_contentses[3]);
  EXPECT_EQ(tab_strip_model->GetWebContentsAt(4), web_contentses[4]);

  std::optional<tab_groups::TabGroupId> group =
      tab_strip_model->GetTabGroupForTab(1);
  EXPECT_TRUE(group.has_value());
  EXPECT_FALSE(tab_strip_model->GetTabGroupForTab(0));
  EXPECT_EQ(group, tab_strip_model->GetTabGroupForTab(1));
  EXPECT_EQ(group, tab_strip_model->GetTabGroupForTab(2));
  EXPECT_EQ(group, tab_strip_model->GetTabGroupForTab(3));
  EXPECT_FALSE(tab_strip_model->GetTabGroupForTab(4));
}

// Test that the tabs.group() function throws an error if both createProperties
// and groupId are specified.
TEST_F(TabsApiUnitTest, TabsGroupParamsError) {
  ASSERT_TRUE(GetTabStripModel()->SupportsTabGroups());

  scoped_refptr<const Extension> extension =
      ExtensionBuilder("GroupParamsErrorTest").Build();

  // Add several web contents to the browser and get their tab IDs.
  constexpr int kNumTabs = 5;
  std::vector<int> tab_ids;
  std::vector<content::WebContents*> web_contentses;
  for (int i = 0; i < kNumTabs; ++i) {
    std::unique_ptr<content::WebContents> contents(
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr));

    CreateSessionServiceTabHelper(contents.get());
    tab_ids.push_back(
        sessions::SessionTabHelper::IdForTab(contents.get()).id());
    web_contentses.push_back(contents.get());

    GetTabStripModel()->AppendWebContents(std::move(contents),
                                          /*foreground=*/true);
  }
  ASSERT_EQ(kNumTabs, GetTabStripModel()->count());

  // Add a tab to a group to have an existing group ID.
  tab_groups::TabGroupId group = GetTabStripModel()->AddToNewGroup({1});
  int group_id = ExtensionTabUtil::GetGroupId(group);

  // Attempt to specify both createProperties and groupId.
  auto function = base::MakeRefCounted<TabsGroupFunction>();
  function->set_extension(extension);
  constexpr char kFormatArgs[] =
      R"([{"tabIds": [%d, %d, %d],
           "groupId": %d, "createProperties": {"windowId": -1}}])";
  const std::string args = base::StringPrintf(kFormatArgs, tab_ids[0],
                                              tab_ids[2], tab_ids[4], group_id);
  std::string error = api_test_utils::RunFunctionAndReturnError(
      function.get(), args, profile(), api_test_utils::FunctionMode::kNone);
  EXPECT_EQ(tabs_constants::kGroupParamsError, error);
}

// Test that the tabs.group() function correctly rearranges sets of tabs across
// windows before grouping.
TEST_F(TabsApiUnitTest, TabsGroupAcrossWindows) {
  ASSERT_TRUE(GetTabStripModel()->SupportsTabGroups());

  scoped_refptr<const Extension> extension =
      ExtensionBuilder("GroupAcrossWindowsTest").Build();

  // Add several web contents to the original browser and get their tab IDs.
  constexpr int kNumTabs = 5;
  std::vector<int> tab_ids;
  std::vector<content::WebContents*> web_contentses;
  for (int i = 0; i < kNumTabs; ++i) {
    std::unique_ptr<content::WebContents> contents(
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr));

    CreateSessionServiceTabHelper(contents.get());
    tab_ids.push_back(
        sessions::SessionTabHelper::IdForTab(contents.get()).id());
    web_contentses.push_back(contents.get());

    GetTabStripModel()->AppendWebContents(std::move(contents),
                                          /*foreground=*/true);
  }
  ASSERT_EQ(kNumTabs, GetTabStripModel()->count());

  // Create a new window and add a few tabs, adding one to a group.
  auto window2 = std::make_unique<TestBrowserWindow>();
  Browser::CreateParams params(profile(), /* user_gesture */ true);
  params.type = Browser::TYPE_NORMAL;
  params.window = window2.get();
  // TestBrowserWindowOwner handles its own lifetime, and also cleans up
  // |window2|.
  new TestBrowserWindowOwner(std::move(window2));
  std::unique_ptr<Browser> browser2(Browser::Create(params));

  constexpr int kNumTabs2 = 3;
  for (int i = 0; i < kNumTabs2; ++i) {
    std::unique_ptr<content::WebContents> contents(
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr));
    CreateSessionServiceTabHelper(contents.get());
    browser2->tab_strip_model()->AppendWebContents(std::move(contents),
                                                   /*foreground=*/true);
  }
  ASSERT_EQ(kNumTabs2, browser2->tab_strip_model()->count());

  tab_groups::TabGroupId group2 =
      browser2->tab_strip_model()->AddToNewGroup({1});
  int group_id2 = ExtensionTabUtil::GetGroupId(group2);

  // Use the TabsGroupFunction to group tabs 0, 2, and 4 from the original
  // browser into the same group as the one in browser2.
  constexpr int kNumTabsMovedAcrossWindows = 3;
  auto function = base::MakeRefCounted<TabsGroupFunction>();
  function->set_extension(extension);
  constexpr char kFormatArgs[] = R"([{"tabIds": [%d, %d, %d], "groupId": %d}])";
  const std::string args = base::StringPrintf(
      kFormatArgs, tab_ids[0], tab_ids[2], tab_ids[4], group_id2);
  ASSERT_TRUE(api_test_utils::RunFunction(function.get(), args, profile(),
                                          api_test_utils::FunctionMode::kNone));

  TabStripModel* tab_strip_model2 = browser2->tab_strip_model();
  ASSERT_EQ(kNumTabs2 + kNumTabsMovedAcrossWindows, tab_strip_model2->count());
  EXPECT_EQ(tab_strip_model2->GetWebContentsAt(2), web_contentses[0]);
  EXPECT_EQ(tab_strip_model2->GetWebContentsAt(3), web_contentses[2]);
  EXPECT_EQ(tab_strip_model2->GetWebContentsAt(4), web_contentses[4]);

  EXPECT_EQ(group2, tab_strip_model2->GetTabGroupForTab(1).value());
  EXPECT_EQ(group2, tab_strip_model2->GetTabGroupForTab(2).value());
  EXPECT_EQ(group2, tab_strip_model2->GetTabGroupForTab(3).value());
  EXPECT_EQ(group2, tab_strip_model2->GetTabGroupForTab(4).value());

  // Clean up.
  browser2->tab_strip_model()->CloseAllTabs();
}

// Test that grouping tabs that are in a saved group should fail.
TEST_F(TabsApiUnitTest, TabsGroupForSavedTabGroupTab) {
  ASSERT_TRUE(GetTabStripModel()->SupportsTabGroups());

  scoped_refptr<const Extension> extension =
      ExtensionBuilder("GroupWithinWindowTest").Build();

  // create 2 tabs
  std::vector<int> tab_ids;
  for (int i = 0; i < 2; ++i) {
    std::unique_ptr<content::WebContents> contents(
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr));

    CreateSessionServiceTabHelper(contents.get());
    tab_ids.push_back(
        sessions::SessionTabHelper::IdForTab(contents.get()).id());

    GetTabStripModel()->AppendWebContents(std::move(contents),
                                          /*foreground=*/true);
  }

  // group the first tab. make sure its saved.
  tab_groups::TabGroupId old_group = GetTabStripModel()->AddToNewGroup({0});

  // with extensions group the 2 tabs into a new group.
  auto function = base::MakeRefCounted<TabsGroupFunction>();
  function->set_extension(extension);
  constexpr char kFormatArgs[] = R"([{"tabIds": [%d, %d]}])";
  const std::string args =
      base::StringPrintf(kFormatArgs, tab_ids[0], tab_ids[1]);
  EXPECT_TRUE(api_test_utils::RunFunction(function.get(), args, profile(),
                                          api_test_utils::FunctionMode::kNone));

  // make sure the new group exists and is different than the old group.
  EXPECT_TRUE(GetTabStripModel()->GetTabGroupForTab(0).has_value());
  EXPECT_NE(old_group, GetTabStripModel()->GetTabGroupForTab(0).value());
  EXPECT_EQ(GetTabStripModel()->GetTabGroupForTab(0),
            GetTabStripModel()->GetTabGroupForTab(1));
}

// Test that the tabs.ungroup() function correctly ungroups tabs from a single
// group and deletes it.
TEST_F(TabsApiUnitTest, TabsUngroupSingleGroup) {
  ASSERT_TRUE(GetTabStripModel()->SupportsTabGroups());

  scoped_refptr<const Extension> extension =
      ExtensionBuilder("UngroupSingleGroupTest").Build();

  // Add several web contents to the browser and get their tab IDs.
  constexpr int kNumTabs = 5;
  std::vector<int> tab_ids;
  std::vector<content::WebContents*> web_contentses;
  for (int i = 0; i < kNumTabs; ++i) {
    std::unique_ptr<content::WebContents> contents(
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr));

    CreateSessionServiceTabHelper(contents.get());
    tab_ids.push_back(
        sessions::SessionTabHelper::IdForTab(contents.get()).id());
    web_contentses.push_back(contents.get());

    GetTabStripModel()->AppendWebContents(std::move(contents),
                                          /*foreground=*/true);
  }
  ASSERT_EQ(kNumTabs, GetTabStripModel()->count());

  // Add tabs 1, 2, and 3 to a group.
  tab_groups::TabGroupId group = GetTabStripModel()->AddToNewGroup({1, 2, 3});

  // Use the TabsUngroupFunction to ungroup tabs 1, 2, and 3.
  auto function = base::MakeRefCounted<TabsUngroupFunction>();
  function->set_extension(extension);
  constexpr char kFormatArgs[] = R"([[%d, %d, %d]])";
  const std::string args =
      base::StringPrintf(kFormatArgs, tab_ids[1], tab_ids[2], tab_ids[3]);
  ASSERT_TRUE(api_test_utils::RunFunction(function.get(), args, profile(),
                                          api_test_utils::FunctionMode::kNone));

  // Expect the group to be deleted because all tabs were ungrouped from it.
  TabStripModel* tab_strip_model = GetTabStripModel();
  EXPECT_FALSE(tab_strip_model->GetTabGroupForTab(1));
  EXPECT_FALSE(tab_strip_model->GetTabGroupForTab(2));
  EXPECT_FALSE(tab_strip_model->GetTabGroupForTab(3));
  EXPECT_FALSE(tab_strip_model->group_model()->ContainsTabGroup(group));
}

// Saved groups should be ungroupable from extensions.
TEST_F(TabsApiUnitTest, TabsUngroupSingleGroupForSavedTabGroup) {
  ASSERT_TRUE(GetTabStripModel()->SupportsTabGroups());

  scoped_refptr<const Extension> extension =
      ExtensionBuilder("UngroupSingleGroupTest").Build();

  int tab_id;

  {
    std::unique_ptr<content::WebContents> web_contents(
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr));

    CreateSessionServiceTabHelper(web_contents.get());
    tab_id = sessions::SessionTabHelper::IdForTab(web_contents.get()).id();

    GetTabStripModel()->AppendWebContents(std::move(web_contents),
                                          /*foreground=*/true);
  }
  ASSERT_EQ(1, GetTabStripModel()->count());

  tab_groups::TabGroupSyncService* saved_service = sync_service();
  ASSERT_TRUE(saved_service);

  // Group the tab and save it.
  tab_groups::TabGroupId group = GetTabStripModel()->AddToNewGroup({0});
  tab_groups::TabGroupVisualData visual_data(
      u"Initial title", tab_groups::TabGroupColorId::kBlue);
  browser()->tab_strip_model()->ChangeTabGroupVisuals(group, visual_data);

  auto function = base::MakeRefCounted<TabsUngroupFunction>();
  function->set_extension(extension);
  constexpr char kFormatArgs[] = R"([[%d]])";
  const std::string args = base::StringPrintf(kFormatArgs, tab_id);
  EXPECT_TRUE(api_test_utils::RunFunction(function.get(), args, profile(),
                                          api_test_utils::FunctionMode::kNone));

  // The tab should no longer be in the group.
  TabStripModel* tab_strip_model = GetTabStripModel();
  EXPECT_EQ(std::nullopt, tab_strip_model->GetTabGroupForTab(0));
}

// Test that the tabs.ungroup() function correctly ungroups tabs from several
// different groups and deletes any empty ones.
TEST_F(TabsApiUnitTest, TabsUngroupFromMultipleGroups) {
  ASSERT_TRUE(GetTabStripModel()->SupportsTabGroups());

  TabStripModel* tab_strip_model = GetTabStripModel();
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("UngroupFromMultipleGroupsTest").Build();

  // Add several web contents to the browser and get their tab IDs.
  constexpr int kNumTabs = 5;
  std::vector<int> tab_ids;
  std::vector<content::WebContents*> web_contentses;
  for (int i = 0; i < kNumTabs; ++i) {
    std::unique_ptr<content::WebContents> contents(
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr));

    CreateSessionServiceTabHelper(contents.get());
    tab_ids.push_back(
        sessions::SessionTabHelper::IdForTab(contents.get()).id());
    web_contentses.push_back(contents.get());

    tab_strip_model->AppendWebContents(std::move(contents),
                                       /*foreground=*/true);
  }
  ASSERT_EQ(kNumTabs, tab_strip_model->count());

  // Add tabs 1, 2, and 3 to a group1, and tab 4 to group2.
  tab_groups::TabGroupId group1 = tab_strip_model->AddToNewGroup({1, 2, 3});
  tab_groups::TabGroupId group2 = tab_strip_model->AddToNewGroup({4});

  // Use the TabsUngroupFunction to ungroup tabs 2, 3, and 4.
  auto function = base::MakeRefCounted<TabsUngroupFunction>();
  function->set_extension(extension);
  constexpr char kFormatArgs[] = R"([[%d, %d, %d]])";
  const std::string args =
      base::StringPrintf(kFormatArgs, tab_ids[2], tab_ids[3], tab_ids[4]);
  ASSERT_TRUE(api_test_utils::RunFunction(function.get(), args, profile(),
                                          api_test_utils::FunctionMode::kNone));

  // Expect group2 to be deleted because all tabs were ungrouped from it.
  EXPECT_EQ(group1, tab_strip_model->GetTabGroupForTab(1));
  EXPECT_FALSE(tab_strip_model->GetTabGroupForTab(2));
  EXPECT_FALSE(tab_strip_model->GetTabGroupForTab(3));
  EXPECT_FALSE(tab_strip_model->GetTabGroupForTab(4));
  EXPECT_TRUE(tab_strip_model->group_model()->ContainsTabGroup(group1));
  EXPECT_FALSE(tab_strip_model->group_model()->ContainsTabGroup(group2));
}

TEST_F(TabsApiUnitTest, TabsGoForwardNoSelectedTabError) {
  scoped_refptr<const Extension> extension = CreateTabsExtension();
  auto function = base::MakeRefCounted<TabsGoForwardFunction>();
  function->set_extension(extension);
  // No active tab results in an error.
  std::string error = api_test_utils::RunFunctionAndReturnError(
      function.get(), "[]",
      profile(),  // profile() doesn't have any tabs.
      api_test_utils::FunctionMode::kNone);
  EXPECT_EQ(tabs_constants::kNoSelectedTabError, error);
}

TEST_F(TabsApiUnitTest, TabsGoForwardAndBack) {
  scoped_refptr<const Extension> extension_with_tabs_permission =
      CreateTabsExtension();

  const std::vector<GURL> urls = {GURL("http://www.foo.com"),
                                  GURL("http://www.bar.com")};
  content::WebContents* web_contents = CreateAndAppendWebContentsWithHistory(
      profile(), GetTabStripModel(), urls);
  ASSERT_TRUE(web_contents);

  CreateSessionServiceTabHelper(web_contents);
  const int tab_id = sessions::SessionTabHelper::IdForTab(web_contents).id();
  // Go back with chrome.tabs.goBack.
  auto goback_function = base::MakeRefCounted<TabsGoBackFunction>();
  goback_function->set_extension(extension_with_tabs_permission.get());
  api_test_utils::RunFunction(goback_function.get(),
                              base::StringPrintf("[%d]", tab_id), profile(),
                              api_test_utils::FunctionMode::kIncognito);

  content::WebContents* active_webcontent = GetActiveWebContents();
  content::NavigationController& controller =
      active_webcontent->GetController();
  ASSERT_TRUE(CommitPendingLoadForController(controller));
  EXPECT_EQ(urls[0], web_contents->GetLastCommittedURL());
  EXPECT_EQ(urls[0], web_contents->GetVisibleURL());
  EXPECT_TRUE(ui::PAGE_TRANSITION_FORWARD_BACK &
              controller.GetLastCommittedEntry()->GetTransitionType());

  // Go forward with chrome.tabs.goForward.
  auto goforward_function = base::MakeRefCounted<TabsGoForwardFunction>();
  goforward_function->set_extension(extension_with_tabs_permission.get());
  api_test_utils::RunFunction(goforward_function.get(),
                              base::StringPrintf("[%d]", tab_id), profile(),
                              api_test_utils::FunctionMode::kIncognito);

  ASSERT_TRUE(CommitPendingLoadForController(controller));
  EXPECT_EQ(urls[1], web_contents->GetLastCommittedURL());
  EXPECT_EQ(urls[1], web_contents->GetVisibleURL());
  EXPECT_TRUE(ui::PAGE_TRANSITION_FORWARD_BACK &
              controller.GetLastCommittedEntry()->GetTransitionType());

  // If there's no next page, chrome.tabs.goForward should return an error.
  auto goforward_function2 = base::MakeRefCounted<TabsGoForwardFunction>();
  goforward_function2->set_extension(extension_with_tabs_permission.get());
  std::string error = api_test_utils::RunFunctionAndReturnError(
      goforward_function2.get(), base::StringPrintf("[%d]", tab_id), profile(),
      api_test_utils::FunctionMode::kNone);
  EXPECT_EQ(tabs_constants::kNotFoundNextPageError, error);
  EXPECT_EQ(urls[1], web_contents->GetLastCommittedURL());
  EXPECT_EQ(urls[1], web_contents->GetVisibleURL());
}

TEST_F(TabsApiUnitTest, TabsGoForwardAndBackSavedTabGroupTab) {
  scoped_refptr<const Extension> extension_with_tabs_permission =
      CreateTabsExtension();

  const std::vector<GURL> urls = {GURL("http://www.foo.com"),
                                  GURL("http://www.bar.com"),
                                  GURL("http://www.baz.com")};
  content::WebContents* web_contents = CreateAndAppendWebContentsWithHistory(
      profile(), GetTabStripModel(), urls);
  ASSERT_TRUE(web_contents);

  CreateSessionServiceTabHelper(web_contents);
  const int tab_id = sessions::SessionTabHelper::IdForTab(web_contents).id();

  {
    // Go back with chrome.tabs.goBack.
    auto goback_function = base::MakeRefCounted<TabsGoBackFunction>();
    goback_function->set_extension(extension_with_tabs_permission.get());
    api_test_utils::RunFunction(goback_function.get(),
                                base::StringPrintf("[%d]", tab_id), profile(),
                                api_test_utils::FunctionMode::kIncognito);
    ASSERT_TRUE(CommitPendingLoadForController(web_contents->GetController()));
  }

  EXPECT_EQ(urls[1], web_contents->GetLastCommittedURL());
  EXPECT_EQ(urls[1], web_contents->GetVisibleURL());

  tab_groups::TabGroupSyncService* saved_service = sync_service();
  ASSERT_TRUE(saved_service);

  // Save the tab and expect that it can not be navigated forwards or backwards.
  tab_groups::TabGroupId group = GetTabStripModel()->AddToNewGroup(
      {GetTabStripModel()->GetIndexOfWebContents(web_contents)});
  tab_groups::TabGroupVisualData visual_data(
      u"Initial title", tab_groups::TabGroupColorId::kBlue);
  browser()->tab_strip_model()->ChangeTabGroupVisuals(group, visual_data);

  {
    auto goback_function = base::MakeRefCounted<TabsGoBackFunction>();
    goback_function->set_extension(extension_with_tabs_permission.get());
    EXPECT_TRUE(api_test_utils::RunFunction(
        goback_function.get(), base::StringPrintf("[%d]", tab_id), profile(),
        api_test_utils::FunctionMode::kNone));
  }

  {
    auto goforward_function = base::MakeRefCounted<TabsGoForwardFunction>();
    goforward_function->set_extension(extension_with_tabs_permission.get());
    EXPECT_TRUE(api_test_utils::RunFunction(
        goforward_function.get(), base::StringPrintf("[%d]", tab_id), profile(),
        api_test_utils::FunctionMode::kNone));
  }

  EXPECT_EQ(urls[1], web_contents->GetLastCommittedURL());
  EXPECT_EQ(urls[1], web_contents->GetVisibleURL());
}

TEST_F(TabsApiUnitTest, TabsGoForwardAndBackWithoutTabId) {
  scoped_refptr<const Extension> extension_with_tabs_permission =
      CreateTabsExtension();
  TabStripModel* tab_strip_model = GetTabStripModel();

  // Create first tab with history.
  const std::vector<GURL> tab1_urls = {GURL("http://www.foo.com"),
                                       GURL("http://www.bar.com")};
  content::WebContents* tab1_webcontents =
      CreateAndAppendWebContentsWithHistory(profile(), tab_strip_model,
                                            tab1_urls);
  ASSERT_TRUE(tab1_webcontents);
  EXPECT_EQ(tab1_urls[1], tab1_webcontents->GetLastCommittedURL());
  EXPECT_EQ(tab1_urls[1], tab1_webcontents->GetVisibleURL());
  const int tab1_index =
      tab_strip_model->GetIndexOfWebContents(tab1_webcontents);

  // Create second tab with history.
  const std::vector<GURL> tab2_urls = {GURL("http://www.chrome.com"),
                                       GURL("http://www.google.com")};
  content::WebContents* tab2_webcontents =
      CreateAndAppendWebContentsWithHistory(profile(), tab_strip_model,
                                            tab2_urls);
  ASSERT_TRUE(tab2_webcontents);
  EXPECT_EQ(tab2_urls[1], tab2_webcontents->GetLastCommittedURL());
  EXPECT_EQ(tab2_urls[1], tab2_webcontents->GetVisibleURL());
  const int tab2_index =
      tab_strip_model->GetIndexOfWebContents(tab2_webcontents);
  ASSERT_EQ(2, tab_strip_model->count());

  // Activate first tab.
  tab_strip_model->ActivateTabAt(
      tab1_index, TabStripUserGestureDetails(
                      TabStripUserGestureDetails::GestureType::kOther));

  // Go back without tab_id. But first tab should be navigated since it's
  // activated.
  auto goback_function = base::MakeRefCounted<TabsGoBackFunction>();
  goback_function->set_extension(extension_with_tabs_permission.get());
  api_test_utils::RunFunction(goback_function.get(), "[]", profile(),
                              api_test_utils::FunctionMode::kIncognito);

  content::NavigationController& controller = tab1_webcontents->GetController();
  ASSERT_TRUE(CommitPendingLoadForController(controller));
  EXPECT_EQ(tab1_urls[0], tab1_webcontents->GetLastCommittedURL());
  EXPECT_EQ(tab1_urls[0], tab1_webcontents->GetVisibleURL());
  EXPECT_TRUE(ui::PAGE_TRANSITION_FORWARD_BACK &
              controller.GetLastCommittedEntry()->GetTransitionType());

  // Go forward without tab_id.
  auto goforward_function = base::MakeRefCounted<TabsGoForwardFunction>();
  goforward_function->set_extension(extension_with_tabs_permission.get());
  api_test_utils::RunFunction(goforward_function.get(), "[]", profile(),
                              api_test_utils::FunctionMode::kIncognito);

  ASSERT_TRUE(CommitPendingLoadForController(controller));
  EXPECT_EQ(tab1_urls[1], tab1_webcontents->GetLastCommittedURL());
  EXPECT_EQ(tab1_urls[1], tab1_webcontents->GetVisibleURL());
  EXPECT_TRUE(ui::PAGE_TRANSITION_FORWARD_BACK &
              controller.GetLastCommittedEntry()->GetTransitionType());

  // Activate second tab.
  tab_strip_model->ActivateTabAt(
      tab2_index, TabStripUserGestureDetails(
                      TabStripUserGestureDetails::GestureType::kOther));

  auto goback_function2 = base::MakeRefCounted<TabsGoBackFunction>();
  goback_function2->set_extension(extension_with_tabs_permission.get());
  api_test_utils::RunFunction(goback_function2.get(), "[]", profile(),
                              api_test_utils::FunctionMode::kIncognito);

  content::NavigationController& controller2 =
      tab2_webcontents->GetController();
  ASSERT_TRUE(CommitPendingLoadForController(controller2));
  EXPECT_EQ(tab2_urls[0], tab2_webcontents->GetLastCommittedURL());
  EXPECT_EQ(tab2_urls[0], tab2_webcontents->GetVisibleURL());
  EXPECT_TRUE(ui::PAGE_TRANSITION_FORWARD_BACK &
              controller2.GetLastCommittedEntry()->GetTransitionType());
}

#if BUILDFLAG(IS_CHROMEOS)
// Ensure tabs.captureVisibleTab respects any Data Leak Prevention restrictions.
TEST_F(TabsApiUnitTest, ScreenshotsRestricted) {
  // Setup the function and extension.
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("Screenshot")
          .AddAPIPermission("tabs")
          .AddHostPermission("<all_urls>")
          .Build();
  auto function = base::MakeRefCounted<TabsCaptureVisibleTabFunction>();
  function->set_extension(extension.get());

  // Add a visible tab.
  std::unique_ptr<content::WebContents> web_contents =
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr);
  content::WebContentsTester* web_contents_tester =
      content::WebContentsTester::For(web_contents.get());
  const GURL kGoogle("http://www.google.com");
  GetTabStripModel()->AppendWebContents(std::move(web_contents),
                                        /*foreground=*/true);
  web_contents_tester->NavigateAndCommit(kGoogle);

  // Setup Data Leak Prevention restriction.
  policy::MockDlpContentManager mock_dlp_content_manager;
  policy::ScopedDlpContentObserverForTesting scoped_dlp_content_observer_(
      &mock_dlp_content_manager);
  EXPECT_CALL(mock_dlp_content_manager, IsScreenshotApiRestricted(testing::_))
      .Times(1)
      .WillOnce(testing::Return(true));

  // Run the function and check result.
  std::string error = api_test_utils::RunFunctionAndReturnError(
      function.get(), "[{}]", profile(), api_test_utils::FunctionMode::kNone);
  EXPECT_EQ(tabs_constants::kScreenshotsDisabledByDlp, error);
}
#endif  // BUILDFLAG(IS_CHROMEOS)

#if BUILDFLAG(IS_CHROMEOS)
TEST_F(TabsApiUnitTest, DontCreateTabsInLockedFullscreenMode) {
  scoped_refptr<const Extension> extension_with_tabs_permission =
      CreateTabsExtension();

  ash::TestWindowBuilder builder;
  std::unique_ptr<aura::Window> window =
      builder.SetTestWindowDelegate().AllowAllWindowStates().Build();
  browser_window()->SetNativeWindow(window.get());

  auto function = base::MakeRefCounted<TabsCreateFunction>();

  function->set_extension(extension_with_tabs_permission.get());

  // In locked fullscreen mode we should not be able to create any tabs.
  PinWindow(browser_window()->GetNativeWindow(), /*trusted=*/true);

  EXPECT_EQ(ExtensionTabUtil::kLockedFullscreenModeNewTabError,
            api_test_utils::RunFunctionAndReturnError(
                function.get(), "[{}]", profile(),
                api_test_utils::FunctionMode::kNone));
}

// Screenshot should return an error when disabled in user profile preferences.
TEST_F(TabsApiUnitTest, ScreenshotDisabledInProfilePreferences) {
  // Setup the function and extension.
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("Screenshot")
          .AddAPIPermission("tabs")
          .AddHostPermission("<all_urls>")
          .Build();
  auto function = base::MakeRefCounted<TabsCaptureVisibleTabFunction>();
  function->set_extension(extension.get());

  // Add a visible tab.
  std::unique_ptr<content::WebContents> web_contents =
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr);
  content::WebContentsTester* web_contents_tester =
      content::WebContentsTester::For(web_contents.get());
  const GURL kGoogle("http://www.google.com");
  GetTabStripModel()->AppendWebContents(std::move(web_contents),
                                        /*foreground=*/true);
  web_contents_tester->NavigateAndCommit(kGoogle);

  // Disable screenshot.
  browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableScreenshots,
                                               true);

  // Run the function and check result.
  std::string error = api_test_utils::RunFunctionAndReturnError(
      function.get(), "[{}]", profile(), api_test_utils::FunctionMode::kNone);
  EXPECT_EQ(tabs_constants::kScreenshotsDisabled, error);
}
#endif  // BUILDFLAG(IS_CHROMEOS)

TEST_F(TabsApiUnitTest, CannotDuplicatePictureInPictureWindows) {
  // Create picture-in-picture browser.
  auto pip_window = std::make_unique<TestBrowserWindow>();
  Browser::CreateParams params(profile(), true);
  params.type = Browser::TYPE_PICTURE_IN_PICTURE;
  params.window = pip_window.get();
  std::unique_ptr<Browser> pip_browser;
  pip_browser.reset(Browser::Create(params));
  std::unique_ptr<content::WebContents> contents(
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr));
  CreateSessionServiceTabHelper(contents.get());
  int pip_tab_id = sessions::SessionTabHelper::IdForTab(contents.get()).id();
  pip_browser->tab_strip_model()->AppendWebContents(std::move(contents),
                                                    /*foreground=*/true);

  // Attempt to duplicate the picture-in-picture tab. This should fail as
  // picture-in-picture tabs are not allowed to be duplicated.
  auto function = base::MakeRefCounted<TabsDuplicateFunction>();
  auto extension = CreateTabsExtension();
  function->set_extension(extension);
  std::string args = base::StringPrintf("[%d]", pip_tab_id);
  std::string error = api_test_utils::RunFunctionAndReturnError(
      function.get(), args, pip_browser->profile(),
      api_test_utils::FunctionMode::kNone);
  EXPECT_EQ(ErrorUtils::FormatErrorMessage(tabs_constants::kCannotDuplicateTab,
                                           base::NumberToString(pip_tab_id)),
            error);

  // Tear down picture-in-picture browser.
  pip_browser->tab_strip_model()->DetachAndDeleteWebContentsAt(0);
  pip_browser.reset();
  pip_window.reset();
}

// Tests that calling chrome.tabs.discard discards the tab.
TEST_F(TabsApiUnitTest, TabsDiscard) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("DiscardTest").Build();
  const GURL kExampleCom("http://example.com");

  // Add a web contents to the browser.
  std::unique_ptr<content::WebContents> contents(
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr));
  content::WebContents* web_contents = contents.get();
  GetTabStripModel()->AppendWebContents(std::move(contents), true);
  EXPECT_EQ(GetActiveWebContents(), web_contents);
  CreateSessionServiceTabHelper(web_contents);
  int index = GetTabStripModel()->GetIndexOfWebContents(web_contents);
  int tab_id = sessions::SessionTabHelper::IdForTab(web_contents).id();

  // Navigate the browser to example.com
  content::WebContentsTester* web_contents_tester =
      content::WebContentsTester::For(web_contents);
  web_contents_tester->NavigateAndCommit(kExampleCom);
  EXPECT_EQ(kExampleCom, web_contents->GetLastCommittedURL());

  // Use the TabsDiscardFunction to discard the tab.
  auto function = base::MakeRefCounted<TabsDiscardFunction>();
  function->set_extension(extension);
  static constexpr char kFormatArgs[] = R"([%d])";
  const std::string args = base::StringPrintf(kFormatArgs, tab_id);
  ASSERT_TRUE(api_test_utils::RunFunction(function.get(), args, profile(),
                                          api_test_utils::FunctionMode::kNone));
  // check that the tab has discarded
  content::WebContents* new_contents_at_index =
      GetTabStripModel()->GetWebContentsAt(index);
  EXPECT_TRUE(new_contents_at_index->WasDiscarded());
}

// Tests that calling chrome.tabs.discard on a saved tab does not discard.
TEST_F(TabsApiUnitTest, TabsDiscardSavedTabGroupTabNotAllowed) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("DiscardTest").Build();
  const GURL kExampleCom("http://example.com");

  // Add a web contents to the browser.
  std::unique_ptr<content::WebContents> contents(
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr));
  content::WebContents* web_contents = contents.get();
  GetTabStripModel()->AppendWebContents(std::move(contents), true);
  EXPECT_EQ(GetActiveWebContents(), web_contents);
  CreateSessionServiceTabHelper(web_contents);
  int tab_id = sessions::SessionTabHelper::IdForTab(web_contents).id();

  // Navigate the browser to example.com
  content::WebContentsTester* web_contents_tester =
      content::WebContentsTester::For(web_contents);
  web_contents_tester->NavigateAndCommit(kExampleCom);
  EXPECT_EQ(kExampleCom, web_contents->GetLastCommittedURL());

  tab_groups::TabGroupSyncService* saved_service = sync_service();
  ASSERT_TRUE(saved_service);

  // Group the tab and save it.
  tab_groups::TabGroupId group = GetTabStripModel()->AddToNewGroup(
      {GetTabStripModel()->GetIndexOfWebContents(web_contents)});
  tab_groups::TabGroupVisualData visual_data(
      u"Initial title", tab_groups::TabGroupColorId::kBlue);
  browser()->tab_strip_model()->ChangeTabGroupVisuals(group, visual_data);

  // The tab discard function should fail.
  auto function = base::MakeRefCounted<TabsDiscardFunction>();
  function->set_extension(extension);
  EXPECT_TRUE(api_test_utils::RunFunction(
      function.get(), base::StringPrintf("[%d]", tab_id), profile(),
      api_test_utils::FunctionMode::kNone));
}

TEST_F(TabsApiUnitTest, SplitTabsWithHighlightFunction) {
  // Add a couple of web contents to the browser and mark them as split.
  for (int i = 0; i < /*numTabs=*/2; ++i) {
    std::unique_ptr<content::WebContents> contents(
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr));
    CreateSessionServiceTabHelper(contents.get());
    GetTabStripModel()->AppendWebContents(std::move(contents),
                                          /*foreground=*/true);
  }
  GetTabStripModel()->ActivateTabAt(0);
  GetTabStripModel()->AddToNewSplit({1}, split_tabs::SplitTabVisualData());

  // Run extension to highlight tabs
  auto extension = CreateTabsExtension();
  std::string args = base::StringPrintf("[{\"tabs\": [%d]}]", 0);
  scoped_refptr<TabsHighlightFunction> function =
      base::MakeRefCounted<TabsHighlightFunction>();
  function->set_extension(extension);
  ASSERT_TRUE(api_test_utils::RunFunction(function.get(), args, profile(),
                                          api_test_utils::FunctionMode::kNone));

  // Check that both sides of the split are selected.
  ASSERT_TRUE(GetTabStripModel()->selection_model().IsSelected(0));
  ASSERT_TRUE(GetTabStripModel()->selection_model().IsSelected(1));
}

#if BUILDFLAG(IS_CHROMEOS)
// Tests that calling chrome.tabs.discard on a saved tab does discard for
// extensions with locked fullscreen permission. Locked fullscreen permission
// is ChromeOS only.
TEST_F(TabsApiUnitTest,
       TabsDiscardSavedTabGroupTabAllowedForLockedFullscreenPermission) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("DiscardTest")
          .SetID("pmgljoohajacndjcjlajcopidgnhphcl")
          .AddAPIPermission("lockWindowFullscreenPrivate")
          .Build();
  const GURL kExampleCom("http://example.com");

  // Add a web contents to the browser.
  std::unique_ptr<content::WebContents> contents(
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr));
  content::WebContents* web_contents = contents.get();
  GetTabStripModel()->AppendWebContents(std::move(contents), true);
  EXPECT_EQ(GetActiveWebContents(), web_contents);
  CreateSessionServiceTabHelper(web_contents);
  int index = GetTabStripModel()->GetIndexOfWebContents(web_contents);
  int tab_id = sessions::SessionTabHelper::IdForTab(web_contents).id();

  // Navigate the browser to example.com
  content::WebContentsTester* web_contents_tester =
      content::WebContentsTester::For(web_contents);
  web_contents_tester->NavigateAndCommit(kExampleCom);
  EXPECT_EQ(kExampleCom, web_contents->GetLastCommittedURL());

  tab_groups::TabGroupSyncService* saved_service = sync_service();
  ASSERT_TRUE(saved_service);

  // Group the tab and save it.
  tab_groups::TabGroupId group = GetTabStripModel()->AddToNewGroup(
      {GetTabStripModel()->GetIndexOfWebContents(web_contents)});
  tab_groups::TabGroupVisualData visual_data(
      u"Initial title", tab_groups::TabGroupColorId::kBlue);
  browser()->tab_strip_model()->ChangeTabGroupVisuals(group, visual_data);

  // The tab discard function should not fail.
  auto function = base::MakeRefCounted<TabsDiscardFunction>();
  function->set_extension(extension);
  ASSERT_TRUE(api_test_utils::RunFunction(
      function.get(), base::StringPrintf("[%d]", tab_id), profile(),
      api_test_utils::FunctionMode::kNone));
  // Check that the tab was discarded.
  content::WebContents* new_contents_at_index =
      GetTabStripModel()->GetWebContentsAt(index);
  EXPECT_TRUE(new_contents_at_index->WasDiscarded());
}
#endif  // BUILDFLAG(IS_CHROMEOS)

}  // namespace extensions