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 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165
|
// Copyright 2012 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/ui/startup/startup_browser_creator.h"
#include <stddef.h>
#include <algorithm>
#include <memory>
#include <string>
#include <string_view>
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/json/json_writer.h"
#include "base/memory/raw_ptr.h"
#include "base/path_service.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind.h"
#include "base/test/mock_callback.h"
#include "base/test/mock_log.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_future.h"
#include "base/version_info/version_info.h"
#include "build/build_config.h"
#include "build/buildflag.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/buildflags.h"
#include "chrome/browser/chrome_browser_main.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/launch_util.h"
#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "chrome/browser/prefs/session_startup_pref.h"
#include "chrome/browser/profiles/keep_alive/profile_keep_alive_types.h"
#include "chrome/browser/profiles/keep_alive/scoped_profile_keep_alive.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_attributes_entry.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/profiles/profile_test_util.h"
#include "chrome/browser/profiles/profile_window.h"
#include "chrome/browser/profiles/profiles_state.h"
#include "chrome/browser/search/search.h"
#include "chrome/browser/sessions/app_session_service_factory.h"
#include "chrome/browser/sessions/exit_type_service.h"
#include "chrome/browser/sessions/session_restore.h"
#include "chrome/browser/sessions/session_restore_test_helper.h"
#include "chrome/browser/sessions/session_restore_test_utils.h"
#include "chrome/browser/sessions/session_service_factory.h"
#include "chrome/browser/signin/signin_promo.h"
#include "chrome/browser/signin/signin_util.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_list_observer.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/profiles/profile_ui_test_utils.h"
#include "chrome/browser/ui/search/ntp_test_utils.h"
#include "chrome/browser/ui/startup/launch_mode_recorder.h"
#include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
#include "chrome/browser/ui/startup/startup_types.h"
#include "chrome/browser/ui/startup/web_app_startup_utils.h"
#include "chrome/browser/ui/web_applications/test/web_app_browsertest_util.h"
#include "chrome/browser/web_applications/test/os_integration_test_override_impl.h"
#include "chrome/browser/web_applications/test/web_app_test_observers.h"
#include "chrome/browser/web_applications/web_app_command_scheduler.h"
#include "chrome/browser/web_applications/web_app_constants.h"
#include "chrome/browser/web_applications/web_app_install_info.h"
#include "chrome/browser/web_applications/web_app_install_params.h"
#include "chrome/browser/web_applications/web_app_provider.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/infobars/content/content_infobar_manager.h"
#include "components/infobars/core/infobar.h"
#include "components/infobars/core/infobar_delegate.h"
#include "components/keep_alive_registry/keep_alive_registry.h"
#include "components/keep_alive_registry/keep_alive_types.h"
#include "components/keep_alive_registry/scoped_keep_alive.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#include "components/policy/core/common/mock_configuration_policy_provider.h"
#include "components/policy/policy_constants.h"
#include "components/prefs/pref_service.h"
#include "components/signin/public/base/signin_switches.h"
#include "components/webapps/browser/install_result_code.h"
#include "components/webapps/browser/installable/installable_metrics.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_launcher.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/test_management_policy.h"
#include "google_apis/gaia/gaia_id.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/strings/ascii.h"
#include "ui/views/controls/webview/webview.h"
#include "url/gurl.h"
#if !BUILDFLAG(IS_CHROMEOS)
#include "base/functional/callback.h"
#include "base/json/values_util.h"
#include "base/run_loop.h"
#include "base/values.h"
#include "chrome/browser/first_run/scoped_relaunch_chrome_browser_override.h"
#include "chrome/browser/ui/profiles/profile_picker.h"
#include "chrome/browser/ui/webui/signin/profile_picker_handler.h"
#include "chrome/browser/ui/webui/signin/profile_picker_ui.h"
#include "components/policy/core/common/external_data_fetcher.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/core/common/policy_types.h"
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
#include "base/json/json_string_value_serializer.h"
#include "chrome/browser/ui/views/web_apps/protocol_handler_launch_dialog_view.h"
#include "chrome/browser/ui/web_applications/app_browser_controller.h"
#include "chrome/browser/web_applications/os_integration/os_integration_manager.h"
#include "chrome/browser/web_applications/test/web_app_install_test_utils.h"
#include "chrome/browser/web_applications/web_app.h"
#include "chrome/browser/web_applications/web_app_registrar.h"
#include "chrome/browser/web_applications/web_app_registry_update.h"
#include "chrome/browser/web_applications/web_app_sync_bridge.h"
#include "third_party/blink/public/common/features.h"
#include "ui/views/widget/any_widget_observer.h"
#include "ui/views/widget/widget.h"
#endif
using testing::Return;
#endif // !BUILDFLAG(IS_CHROMEOS)
#if BUILDFLAG(IS_MAC)
#include "chrome/browser/apps/app_shim/app_shim_manager_mac.h"
#include "chrome/browser/chrome_browser_application_mac.h"
#include "chrome/browser/web_applications/os_integration/mac/app_shim_registry.h"
#endif
#if BUILDFLAG(IS_WIN)
#include "base/base_paths_win.h"
#include "base/test/scoped_path_override.h"
#endif // BUILDFLAG(IS_WIN)
using extensions::Extension;
using testing::_;
using web_app::WebAppProvider;
namespace {
#if !BUILDFLAG(IS_CHROMEOS)
const char kAppId[] = "dofnemchnjfeendjmdhaldenaiabpiad";
const char16_t kAppName[] = u"Test App";
const char kStartUrl[] = "https://test.com";
// Check that there are two browsers. Find the one that is not |browser|.
Browser* FindOneOtherBrowser(Browser* browser) {
// There should only be one other browser.
EXPECT_EQ(2u, chrome::GetBrowserCount(browser->profile()));
// Find the new browser.
Browser* other_browser = nullptr;
for (Browser* b : *BrowserList::GetInstance()) {
if (b != browser) {
other_browser = b;
}
}
return other_browser;
}
void DisableWhatsNewPage() {
PrefService* pref_service = g_browser_process->local_state();
pref_service->SetInteger(prefs::kLastWhatsNewVersion,
version_info::GetMajorVersionNumberAsInt());
}
Browser* OpenNewBrowser(Profile* profile) {
base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
StartupBrowserCreatorImpl creator(base::FilePath(), dummy,
chrome::startup::IsFirstRun::kYes);
ui_test_utils::BrowserChangeObserver new_browser_observer(
nullptr, ui_test_utils::BrowserChangeObserver::ChangeType::kAdded);
creator.Launch(profile, chrome::startup::IsProcessStartup::kNo,
/*restore_tabbed_browser=*/true);
Browser* new_browser = new_browser_observer.Wait();
ui_test_utils::WaitUntilBrowserBecomeActive(new_browser);
return new_browser;
}
bool HasInfoBar(infobars::ContentInfoBarManager* infobar_manager,
const infobars::InfoBarDelegate::InfoBarIdentifier identifier) {
return base::Contains(infobar_manager->infobars(), identifier,
&infobars::InfoBar::GetIdentifier);
}
struct StartupBrowserCreatorFlagTypeValue {
std::string flag;
infobars::InfoBarDelegate::InfoBarIdentifier infobar_identifier;
// True if the infobar is supposed to be shown in every tab, false if it is
// only supposed to be shown once.
bool is_global_infobar;
};
#endif // !BUILDFLAG(IS_CHROMEOS)
typedef std::optional<policy::PolicyLevel> PolicyVariant;
// This class waits until all browser windows are closed, and then runs
// a quit closure.
class AllBrowsersClosedWaiter : public BrowserListObserver {
public:
explicit AllBrowsersClosedWaiter(base::OnceClosure quit_closure);
AllBrowsersClosedWaiter(const AllBrowsersClosedWaiter&) = delete;
AllBrowsersClosedWaiter& operator=(const AllBrowsersClosedWaiter&) = delete;
~AllBrowsersClosedWaiter() override;
// BrowserListObserver:
void OnBrowserRemoved(Browser* browser) override;
private:
base::OnceClosure quit_closure_;
};
AllBrowsersClosedWaiter::AllBrowsersClosedWaiter(base::OnceClosure quit_closure)
: quit_closure_(std::move(quit_closure)) {
BrowserList::AddObserver(this);
}
AllBrowsersClosedWaiter::~AllBrowsersClosedWaiter() {
BrowserList::RemoveObserver(this);
}
void AllBrowsersClosedWaiter::OnBrowserRemoved(Browser* browser) {
if (chrome::GetTotalBrowserCount() == 0) {
std::move(quit_closure_).Run();
}
}
} // namespace
class StartupBrowserCreatorTest : public extensions::ExtensionBrowserTest {
protected:
StartupBrowserCreatorTest() = default;
bool SetUpUserDataDirectory() override {
return extensions::ExtensionBrowserTest::SetUpUserDataDirectory();
}
void SetUpCommandLine(base::CommandLine* command_line) override {
extensions::ExtensionBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(switches::kHomePage, url::kAboutBlankURL);
#if BUILDFLAG(IS_CHROMEOS)
// TODO(nkostylev): Investigate if we can remove this switch.
command_line->AppendSwitch(switches::kCreateBrowserOnStartupForTests);
#endif
}
// Helper functions return void so that we can ASSERT*().
// Use ASSERT_NO_FATAL_FAILURE around calls to these functions to stop the
// test if an assert fails.
void LoadApp(const std::string& app_name,
const Extension** out_app_extension) {
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(app_name.c_str())));
*out_app_extension = extension_registry()->GetExtensionById(
last_loaded_extension_id(), extensions::ExtensionRegistry::ENABLED);
ASSERT_TRUE(*out_app_extension);
// Code that opens a new browser assumes we start with exactly one.
ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile()));
}
void SetAppLaunchPref(const std::string& app_id,
extensions::LaunchType launch_type) {
extensions::SetLaunchType(browser()->profile(), app_id, launch_type);
}
Browser* FindOneOtherBrowserForProfile(Profile* profile,
Browser* not_this_browser) {
for (Browser* browser : *BrowserList::GetInstance()) {
if (browser != not_this_browser && browser->profile() == profile) {
return browser;
}
}
return nullptr;
}
// A helper function that checks the session restore UI (infobar) is shown
// when Chrome starts up after crash.
void EnsureRestoreUIWasShown(content::WebContents* web_contents) {
#if BUILDFLAG(IS_MAC)
infobars::ContentInfoBarManager* infobar_manager =
infobars::ContentInfoBarManager::FromWebContents(web_contents);
EXPECT_EQ(1U, infobar_manager->infobars().size());
#endif // BUILDFLAG(IS_MAC)
}
};
class OpenURLsPopupObserver : public BrowserListObserver {
public:
OpenURLsPopupObserver() = default;
void OnBrowserAdded(Browser* browser) override { added_browser_ = browser; }
void OnBrowserRemoved(Browser* browser) override {}
raw_ptr<Browser> added_browser_ = nullptr;
};
// Test that when there is a popup as the active browser any requests to
// StartupBrowserCreatorImpl::OpenURLsInBrowser don't crash because there's no
// explicit profile given.
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest, OpenURLsPopup) {
std::vector<GURL> urls;
urls.emplace_back("http://localhost");
// Note that in our testing we do not ever query the BrowserList for the "last
// active" browser. That's because the browsers are set as "active" by
// platform UI toolkit messages, and those messages are not sent during unit
// testing sessions.
OpenURLsPopupObserver observer;
BrowserList::AddObserver(&observer);
Browser* popup = Browser::Create(
Browser::CreateParams(Browser::TYPE_POPUP, browser()->profile(), true));
ASSERT_TRUE(popup->is_type_popup());
ASSERT_EQ(popup, observer.added_browser_);
base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
chrome::startup::IsFirstRun first_run =
first_run::IsChromeFirstRun() ? chrome::startup::IsFirstRun::kYes
: chrome::startup::IsFirstRun::kNo;
StartupBrowserCreatorImpl launch(base::FilePath(), dummy, first_run);
// This should create a new window, but re-use the profile from |popup|. If
// it used a null or invalid profile, it would crash.
launch.OpenURLsInBrowser(popup, chrome::startup::IsProcessStartup::kNo, urls);
ASSERT_NE(popup, observer.added_browser_);
BrowserList::RemoveObserver(&observer);
}
// We don't do non-process-startup browser launches on ChromeOS.
// Session restore for process-startup browser launches is tested
// in session_restore_uitest.
#if !BUILDFLAG(IS_CHROMEOS)
// Verify that startup URLs are honored when the process already exists but has
// no tabbed browser windows (eg. as if the process is running only due to a
// background application.
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest,
StartupURLsOnNewWindowWithNoTabbedBrowsers) {
// Use a couple same-site HTTP URLs.
ASSERT_TRUE(embedded_test_server()->Start());
std::vector<GURL> urls;
urls.push_back(embedded_test_server()->GetURL("/title1.html"));
urls.push_back(embedded_test_server()->GetURL("/title2.html"));
Profile* profile = browser()->profile();
DisableWhatsNewPage();
// Set the startup preference to open these URLs.
SessionStartupPref pref(SessionStartupPref::URLS);
pref.urls = urls;
SessionStartupPref::SetStartupPref(profile, pref);
// Keep the browser process running while browsers are closed.
ScopedKeepAlive keep_alive(KeepAliveOrigin::BROWSER,
KeepAliveRestartOption::DISABLED);
ScopedProfileKeepAlive profile_keep_alive(
profile, ProfileKeepAliveOrigin::kBrowserWindow);
// Close the browser.
CloseBrowserAsynchronously(browser());
Browser* new_browser = OpenNewBrowser(profile);
ASSERT_TRUE(new_browser);
std::vector<GURL> expected_urls(urls);
TabStripModel* tab_strip = new_browser->tab_strip_model();
ASSERT_EQ(static_cast<int>(expected_urls.size()), tab_strip->count());
for (size_t i = 0; i < expected_urls.size(); i++) {
EXPECT_EQ(expected_urls[i],
tab_strip->GetWebContentsAt(i)->GetVisibleURL());
}
// The two test_server tabs, despite having the same site, should be in
// different SiteInstances.
EXPECT_NE(
tab_strip->GetWebContentsAt(tab_strip->count() - 2)->GetSiteInstance(),
tab_strip->GetWebContentsAt(tab_strip->count() - 1)->GetSiteInstance());
}
// Verify that startup URLs aren't used when the process already exists
// and has other tabbed browser windows. This is the common case of starting a
// new browser.
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest, StartupURLsOnNewWindow) {
// Use a couple arbitrary URLs.
std::vector<GURL> urls;
urls.push_back(ui_test_utils::GetTestUrl(
base::FilePath(base::FilePath::kCurrentDirectory),
base::FilePath(FILE_PATH_LITERAL("title1.html"))));
urls.push_back(ui_test_utils::GetTestUrl(
base::FilePath(base::FilePath::kCurrentDirectory),
base::FilePath(FILE_PATH_LITERAL("title2.html"))));
// Set the startup preference to open these URLs.
SessionStartupPref pref(SessionStartupPref::URLS);
pref.urls = urls;
SessionStartupPref::SetStartupPref(browser()->profile(), pref);
DisableWhatsNewPage();
Browser* new_browser = OpenNewBrowser(browser()->profile());
ASSERT_TRUE(new_browser);
// The new browser should have exactly one tab (not the startup URLs).
TabStripModel* tab_strip = new_browser->tab_strip_model();
ASSERT_EQ(1, tab_strip->count());
EXPECT_EQ(
chrome::kChromeUINewTabURL,
tab_strip->GetWebContentsAt(0)->GetVisibleURL().possibly_invalid_spec());
}
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest, OpenAppUrlShortcut) {
// Add --app=<url> to the command line. Tests launching legacy apps which may
// have been created by "Add to Desktop" in old versions of Chrome.
// TODO(mgiuca): Delete this feature (https://crbug.com/751029). We are
// keeping it for now to avoid disrupting existing workflows.
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
GURL url = ui_test_utils::GetTestUrl(
base::FilePath(base::FilePath::kCurrentDirectory),
base::FilePath(FILE_PATH_LITERAL("title2.html")));
command_line.AppendSwitchASCII(switches::kApp, url.spec());
ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl(
command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo,
{browser()->profile(), StartupProfileMode::kBrowserWindow}, {}));
Browser* new_browser = FindOneOtherBrowser(browser());
ASSERT_TRUE(new_browser);
// The new window should be an app window.
EXPECT_TRUE(new_browser->is_type_app());
TabStripModel* tab_strip = new_browser->tab_strip_model();
ASSERT_EQ(1, tab_strip->count());
content::WebContents* web_contents = tab_strip->GetWebContentsAt(0);
// At this stage, the web contents' URL should be the one passed in to --app
// (but it will not yet be committed into the navigation controller).
EXPECT_EQ("title2.html", web_contents->GetVisibleURL().ExtractFileName());
// Wait until the navigation is complete. Then the URL will be committed to
// the navigation controller.
content::TestNavigationObserver observer(web_contents, 1);
observer.Wait();
EXPECT_EQ("title2.html",
web_contents->GetLastCommittedURL().ExtractFileName());
}
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest,
KSameTabSwitchReplacesActiveTab) {
// Use a couple of arbitrary URLs.
std::vector<GURL> urls;
urls.push_back(ui_test_utils::GetTestUrl(
base::FilePath(base::FilePath::kCurrentDirectory),
base::FilePath(FILE_PATH_LITERAL("title1.html"))));
urls.push_back(ui_test_utils::GetTestUrl(
base::FilePath(base::FilePath::kCurrentDirectory),
base::FilePath(FILE_PATH_LITERAL("title2.html"))));
urls.push_back(ui_test_utils::GetTestUrl(
base::FilePath(base::FilePath::kCurrentDirectory),
base::FilePath(FILE_PATH_LITERAL("title3.html"))));
DisableWhatsNewPage();
// Open a browser window with some preloaded tabs.
ui_test_utils::NavigateToURLWithDisposition(
browser(), GURL("http://localhost"), WindowOpenDisposition::CURRENT_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
TabStripModel* tab_strip = browser()->tab_strip_model();
EXPECT_EQ(1, tab_strip->count()); // Verify one tab is open.
// Set the first tab as the active tab.
tab_strip->ActivateTabAt(0);
EXPECT_EQ(0, tab_strip->active_index());
// Add the --kSameTab switch and URLs to the command line.
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendSwitch(switches::kSameTab); // Add the switch.
command_line.AppendArg(urls[0].spec()); // First URL.
command_line.AppendArg(urls[1].spec()); // Second URL.
command_line.AppendArg(urls[2].spec()); // Third URL.
// Process the command line to simulate the launch.
ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl(
command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo,
{browser()->profile(), StartupProfileMode::kBrowserWindow}, {}));
// Verify the behavior:
// - The active tab's URL should be replaced by the first URL.
EXPECT_EQ(urls[0], tab_strip->GetWebContentsAt(0)->GetVisibleURL());
// - The remaining URLs should open in new tabs.
EXPECT_EQ(3, tab_strip->count()); // Verify total tabs.
EXPECT_EQ(urls[1], tab_strip->GetWebContentsAt(1)->GetVisibleURL());
EXPECT_EQ(urls[2], tab_strip->GetWebContentsAt(2)->GetVisibleURL());
}
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest, OpenAppUrlIncognitoShortcut) {
// Add --app=<url> and --incognito to the command line. Tests launching
// legacy apps which may have been created by "Add to Desktop" in old versions
// of Chrome. Some existing workflows (especially testing scenarios) also
// use the --incognito command line.
// TODO(mgiuca): Delete this feature (https://crbug.com/751029). We are
// keeping it for now to avoid disrupting existing workflows.
// IMPORTANT NOTE: This is being committed because it is an easy fix, but
// this use case is not officially supported. If a future refactor or
// feature launch causes this to break again, we have no formal
// responsibility to make this continue working. If you rely on the
// combination of these two flags, you WILL be broken in the future.
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
GURL url = ui_test_utils::GetTestUrl(
base::FilePath(base::FilePath::kCurrentDirectory),
base::FilePath(FILE_PATH_LITERAL("title2.html")));
command_line.AppendSwitchASCII(switches::kApp, url.spec());
command_line.AppendSwitch(switches::kIncognito);
Browser* incognito = CreateIncognitoBrowser();
ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl(
command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo,
{incognito->profile(), StartupProfileMode::kBrowserWindow}, {}));
Browser* new_browser = FindOneOtherBrowser(incognito);
ASSERT_TRUE(new_browser);
// The new window should be an app window.
EXPECT_TRUE(new_browser->is_type_app());
TabStripModel* tab_strip = new_browser->tab_strip_model();
ASSERT_EQ(1, tab_strip->count());
content::WebContents* web_contents = tab_strip->GetWebContentsAt(0);
// At this stage, the web contents' URL should be the one passed in to --app
// (but it will not yet be committed into the navigation controller).
EXPECT_EQ("title2.html", web_contents->GetVisibleURL().ExtractFileName());
// Wait until the navigation is complete. Then the URL will be committed to
// the navigation controller.
content::TestNavigationObserver observer(web_contents, 1);
observer.Wait();
EXPECT_EQ("title2.html",
web_contents->GetLastCommittedURL().ExtractFileName());
}
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest,
LaunchWebAppWhileKeepAliveRegistryIsShutdown) {
// Command line to simulate app launch.
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendSwitchASCII(switches::kAppId, "app_id_1");
// Simulate keep alive registry shutdown and try to launch the app and verify
// that we don't crash.
KeepAliveRegistry::GetInstance()->SetIsShuttingDown(true);
web_app::startup::MaybeHandleWebAppLaunch(
command_line, base::FilePath(FILE_PATH_LITERAL("\\path")),
browser()->profile(), chrome::startup::IsFirstRun::kNo);
base::RunLoop().RunUntilIdle();
}
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest,
LaunchWebAppWhileBrowserShutdown) {
// Test callback for verifying browser shutdown is called.
base::test::TestFuture<void> browser_shutdown_complete;
web_app::startup::SetBrowserShutdownCompleteCallbackForTesting(
browser_shutdown_complete.GetCallback());
// Command line to simulate app launch.
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendSwitchASCII(switches::kAppId, "app_id_1");
web_app::startup::MaybeHandleWebAppLaunch(
command_line, base::FilePath(FILE_PATH_LITERAL("\\path")),
browser()->profile(), chrome::startup::IsFirstRun::kNo);
EXPECT_TRUE(KeepAliveRegistry::GetInstance()->IsOriginRegistered(
KeepAliveOrigin::WEB_APP_INTENT_PICKER));
// Start browser shutdown to trigger AppTerminatingCallback()
chrome::AttemptExit();
// Make sure OnBrowserShutdown() is called via AppTerminationCallback
EXPECT_TRUE(browser_shutdown_complete.Wait());
EXPECT_FALSE(KeepAliveRegistry::GetInstance()->IsOriginRegistered(
KeepAliveOrigin::WEB_APP_INTENT_PICKER));
}
namespace {
enum class ChromeAppDeprecationFeatureValue {
kDefault,
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
kEnabledWithNoLaunch,
kDisabled,
#endif
};
std::string ChromeAppDeprecationFeatureValueToString(
const ::testing::TestParamInfo<ChromeAppDeprecationFeatureValue>&
param_info) {
std::string result;
switch (param_info.param) {
case ChromeAppDeprecationFeatureValue::kDefault:
result = "ChromeAppDeprecationFeatureDefault";
break;
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
case ChromeAppDeprecationFeatureValue::kEnabledWithNoLaunch:
result = "ChromeAppDeprecationFeatureEnabledWithNoLaunch";
break;
case ChromeAppDeprecationFeatureValue::kDisabled:
result = "ChromeAppDeprecationFeatureDisabled";
break;
#endif
}
return result;
}
} // namespace
class StartupBrowserCreatorChromeAppShortcutTest
: public StartupBrowserCreatorTest,
public ::testing::WithParamInterface<ChromeAppDeprecationFeatureValue> {
protected:
StartupBrowserCreatorChromeAppShortcutTest() {
switch (GetParam()) {
case ChromeAppDeprecationFeatureValue::kDefault:
break;
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
case ChromeAppDeprecationFeatureValue::kEnabledWithNoLaunch:
scoped_feature_list_.InitAndEnableFeature(
features::kChromeAppsDeprecation);
break;
case ChromeAppDeprecationFeatureValue::kDisabled:
scoped_feature_list_.InitAndDisableFeature(
features::kChromeAppsDeprecation);
break;
#endif
}
}
void SetUpOnMainThread() override {
StartupBrowserCreatorTest::SetUpOnMainThread();
}
void ExpectBlockLaunch(const std::string& app_id, bool force_install_dialog) {
ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile()));
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
auto waiter = views::NamedWidgetShownWaiter(
views::test::AnyWidgetTestPasskey{},
force_install_dialog ? "ForceInstalledDeprecatedAppsDialogView"
: "DeprecatedAppsDialogView");
#endif
// Should have opened the requested homepage about:blank in 1st window.
TabStripModel* tab_strip = browser()->tab_strip_model();
EXPECT_EQ(1, tab_strip->count());
EXPECT_FALSE(browser()->is_type_app());
EXPECT_TRUE(browser()->is_type_normal());
EXPECT_EQ(GURL(url::kAboutBlankURL),
tab_strip->GetWebContentsAt(0)->GetLastCommittedURL());
// Should have opened the chrome://apps unsupported app flow in 2nd window.
Browser* other_browser = FindOneOtherBrowser(browser());
ASSERT_TRUE(other_browser);
TabStripModel* other_tab_strip = other_browser->tab_strip_model();
EXPECT_EQ(1, other_tab_strip->count());
EXPECT_FALSE(other_browser->is_type_app());
EXPECT_TRUE(other_browser->is_type_normal());
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
GURL expected_url =
force_install_dialog
? GURL(chrome::kChromeUIAppsWithForceInstalledDeprecationDialogURL +
app_id)
: GURL(chrome::kChromeUIAppsWithDeprecationDialogURL + app_id);
EXPECT_EQ(expected_url,
other_tab_strip->GetWebContentsAt(0)->GetVisibleURL());
// Verify that the Deprecated Apps Dialog View also shows up.
EXPECT_TRUE(waiter.WaitIfNeededAndGet() != nullptr);
#endif
}
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
enum class ExpectedLaunchBehavior{kLaunchAnywaysInTab, kLaunchAnywaysInWindow,
kNoLaunch};
void ExpectBlockLaunchWithLaunchBehavior(const std::string& app_id,
bool force_install_dialog) {
EXPECT_EQ(2u, chrome::GetBrowserCount(browser()->profile()));
auto waiter = views::NamedWidgetShownWaiter(
views::test::AnyWidgetTestPasskey{},
force_install_dialog ? "ForceInstalledDeprecatedAppsDialogView"
: "DeprecatedAppsDialogView");
// Should have opened the requested homepage about:blank in 1st window.
TabStripModel* tab_strip = browser()->tab_strip_model();
EXPECT_EQ(1, tab_strip->count());
EXPECT_FALSE(browser()->is_type_app());
EXPECT_TRUE(browser()->is_type_normal());
EXPECT_EQ(GURL(url::kAboutBlankURL),
tab_strip->GetWebContentsAt(0)->GetLastCommittedURL());
// Should have opened the chrome://apps unsupported app flow in 2nd window.
Browser* other_browser = FindOneOtherBrowser(browser());
DCHECK(other_browser);
TabStripModel* other_tab_strip = other_browser->tab_strip_model();
EXPECT_EQ(1, other_tab_strip->count());
EXPECT_FALSE(other_browser->is_type_app());
EXPECT_TRUE(other_browser->is_type_normal());
GURL expected_url =
force_install_dialog
? GURL(chrome::kChromeUIAppsWithForceInstalledDeprecationDialogURL +
app_id)
: GURL(chrome::kChromeUIAppsWithDeprecationDialogURL + app_id);
EXPECT_EQ(expected_url,
other_tab_strip->GetWebContentsAt(0)->GetVisibleURL());
std::set<Browser*> initial_browsers;
for (Browser* initial_browser : *BrowserList::GetInstance()) {
initial_browsers.insert(initial_browser);
}
content::TestNavigationObserver same_tab_observer(
other_tab_strip->GetActiveWebContents(), 1,
content::MessageLoopRunner::QuitMode::DEFERRED,
/*ignore_uncommitted_navigations=*/false);
// Verify that the Deprecated Apps Dialog View also shows up.
auto* dialog = waiter.WaitIfNeededAndGet();
EXPECT_TRUE(dialog != nullptr);
if (force_install_dialog) {
// The 'accept' option in the force-install dialog is "launch anyways".
dialog->widget_delegate()->AsDialogDelegate()->Accept();
} else {
// The 'cancel' option in the deprecation dialog is "launch anyways".
dialog->widget_delegate()->AsDialogDelegate()->Cancel();
}
// To ensure that no launch happens, run the run loop until idle.
base::RunLoop().RunUntilIdle();
Browser* app_browser = ui_test_utils::GetBrowserNotInSet(initial_browsers);
EXPECT_EQ(app_browser, nullptr);
}
#endif // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
bool IsExpectedToAllowLaunch() {
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
return false;
#else
return true;
#endif
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_P(StartupBrowserCreatorChromeAppShortcutTest,
OpenAppShortcutNoPref) {
// Load an app with launch.container = 'tab'.
const Extension* extension_app = nullptr;
ASSERT_NO_FATAL_FAILURE(LoadApp("app_with_tab_container", &extension_app));
// When we start, the browser should already have an open tab.
TabStripModel* tab_strip = browser()->tab_strip_model();
EXPECT_EQ(1, tab_strip->count());
ui_test_utils::TabAddedWaiter tab_waiter(browser());
// Add --app-id=<extension->id()> to the command line.
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendSwitchASCII(switches::kAppId, extension_app->id());
ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl(
command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo,
{browser()->profile(), StartupProfileMode::kBrowserWindow}, {}));
if (IsExpectedToAllowLaunch()) {
// No pref was set, so the app should have opened in a tab in the existing
// window.
tab_waiter.Wait();
ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile()));
EXPECT_EQ(2, tab_strip->count());
EXPECT_EQ(tab_strip->GetActiveWebContents(),
tab_strip->GetWebContentsAt(1));
// It should be a standard tabbed window, not an app window.
EXPECT_FALSE(browser()->is_type_app());
EXPECT_TRUE(browser()->is_type_normal());
// It should have loaded the requested app.
const std::u16string expected_title(
u"app_with_tab_container/empty.html title");
content::TitleWatcher title_watcher(tab_strip->GetActiveWebContents(),
expected_title);
EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
} else {
ExpectBlockLaunch(extension_app->id(), /*force_install_dialog=*/false);
}
}
IN_PROC_BROWSER_TEST_P(StartupBrowserCreatorChromeAppShortcutTest,
OpenAppShortcutWindowPref) {
const Extension* extension_app = nullptr;
ASSERT_NO_FATAL_FAILURE(LoadApp("app_with_tab_container", &extension_app));
// Set a pref indicating that the user wants to open this app in a window.
SetAppLaunchPref(extension_app->id(), extensions::LAUNCH_TYPE_WINDOW);
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendSwitchASCII(switches::kAppId, extension_app->id());
ui_test_utils::BrowserChangeObserver browser_waiter(
nullptr, ui_test_utils::BrowserChangeObserver::ChangeType::kAdded);
ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl(
command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo,
{browser()->profile(), StartupProfileMode::kBrowserWindow}, {}));
if (IsExpectedToAllowLaunch()) {
// Pref was set to open in a window, so the app should have opened in a
// window. The launch should have created a new browser. Find the new
// browser.
Browser* new_browser = browser_waiter.Wait();
ASSERT_TRUE(new_browser);
// Expect an app window.
EXPECT_TRUE(new_browser->is_type_app());
// The browser's app_name should include the app's ID.
EXPECT_NE(new_browser->app_name().find(extension_app->id()),
std::string::npos)
<< new_browser->app_name();
} else {
ExpectBlockLaunch(extension_app->id(), /*force_install_dialog=*/false);
}
}
IN_PROC_BROWSER_TEST_P(StartupBrowserCreatorChromeAppShortcutTest,
OpenAppShortcutTabPref) {
// When we start, the browser should already have an open tab.
TabStripModel* tab_strip = browser()->tab_strip_model();
EXPECT_EQ(1, tab_strip->count());
ui_test_utils::TabAddedWaiter tab_waiter(browser());
// Load an app with launch.container = 'tab'.
const Extension* extension_app = nullptr;
ASSERT_NO_FATAL_FAILURE(LoadApp("app_with_tab_container", &extension_app));
// Set a pref indicating that the user wants to open this app in a tab.
SetAppLaunchPref(extension_app->id(), extensions::LAUNCH_TYPE_REGULAR);
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendSwitchASCII(switches::kAppId, extension_app->id());
ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl(
command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo,
{browser()->profile(), StartupProfileMode::kBrowserWindow}, {}));
if (IsExpectedToAllowLaunch()) {
// When an app shortcut is open and the pref indicates a tab should open,
// the tab is open in the existing browser window.
tab_waiter.Wait();
ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile()));
EXPECT_EQ(2, tab_strip->count());
EXPECT_EQ(tab_strip->GetActiveWebContents(),
tab_strip->GetWebContentsAt(1));
// The browser's app_name should not include the app's ID: it is in a normal
// tabbed browser.
EXPECT_EQ(browser()->app_name().find(extension_app->id()),
std::string::npos)
<< browser()->app_name();
// It should have loaded the requested app.
const std::u16string expected_title(
u"app_with_tab_container/empty.html title");
content::TitleWatcher title_watcher(tab_strip->GetActiveWebContents(),
expected_title);
EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
} else {
ExpectBlockLaunch(extension_app->id(), /*force_install_dialog=*/false);
}
}
IN_PROC_BROWSER_TEST_P(StartupBrowserCreatorChromeAppShortcutTest,
OpenPolicyForcedAppShortcut) {
// Load an app with launch.container = 'tab'.
const Extension* extension_app = nullptr;
ASSERT_NO_FATAL_FAILURE(LoadApp("app_with_tab_container", &extension_app));
// Install a test policy provider which will mark the app as force-installed.
extensions::TestManagementPolicyProvider policy_provider(
extensions::TestManagementPolicyProvider::MUST_REMAIN_INSTALLED);
extensions::ExtensionSystem* extension_system =
extensions::ExtensionSystem::Get(browser()->profile());
extension_system->management_policy()->RegisterProvider(&policy_provider);
// When we start, the browser should already have an open tab.
TabStripModel* tab_strip = browser()->tab_strip_model();
EXPECT_EQ(1, tab_strip->count());
ui_test_utils::TabAddedWaiter tab_waiter(browser());
// Add --app-id=<extension->id()> to the command line.
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendSwitchASCII(switches::kAppId, extension_app->id());
ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl(
command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo,
{browser()->profile(), StartupProfileMode::kBrowserWindow}, {}));
if (IsExpectedToAllowLaunch()) {
tab_waiter.Wait();
// Policy force-installed app should be allowed regardless of Chrome App
// Deprecation status.
//
// No app launch pref was set, so the app should have opened in a tab in the
// existing window.
ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile()));
EXPECT_EQ(2, tab_strip->count());
EXPECT_EQ(tab_strip->GetActiveWebContents(),
tab_strip->GetWebContentsAt(1));
// It should be a standard tabbed window, not an app window.
EXPECT_FALSE(browser()->is_type_app());
EXPECT_TRUE(browser()->is_type_normal());
// It should have loaded the requested app.
const std::u16string expected_title(
u"app_with_tab_container/empty.html title");
content::TitleWatcher title_watcher(tab_strip->GetActiveWebContents(),
expected_title);
EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
} else {
ExpectBlockLaunch(extension_app->id(), /*force_install_dialog=*/true);
}
}
INSTANTIATE_TEST_SUITE_P(
All,
StartupBrowserCreatorChromeAppShortcutTest,
::testing::Values(ChromeAppDeprecationFeatureValue::kDefault
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
,
ChromeAppDeprecationFeatureValue::kEnabledWithNoLaunch,
ChromeAppDeprecationFeatureValue::kDisabled
#endif
),
ChromeAppDeprecationFeatureValueToString);
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
using StartupBrowserCreatorChromeAppShortcutTestWithLaunch =
StartupBrowserCreatorChromeAppShortcutTest;
IN_PROC_BROWSER_TEST_P(StartupBrowserCreatorChromeAppShortcutTestWithLaunch,
OpenAppShortcutNoPref) {
// Load an app with launch.container = 'tab'.
const Extension* extension_app = nullptr;
ASSERT_NO_FATAL_FAILURE(LoadApp("app_with_tab_container", &extension_app));
// When we start, the browser should already have an open tab.
TabStripModel* tab_strip = browser()->tab_strip_model();
EXPECT_EQ(1, tab_strip->count());
ui_test_utils::TabAddedWaiter tab_waiter(browser());
// Add --app-id=<extension->id()> to the command line.
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendSwitchASCII(switches::kAppId, extension_app->id());
ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl(
command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo,
{browser()->profile(), StartupProfileMode::kBrowserWindow}, {}));
ExpectBlockLaunchWithLaunchBehavior(extension_app->id(),
/*force_install_dialog=*/false);
ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile()));
}
IN_PROC_BROWSER_TEST_P(StartupBrowserCreatorChromeAppShortcutTestWithLaunch,
OpenAppShortcutWindowPref) {
const Extension* extension_app = nullptr;
ASSERT_NO_FATAL_FAILURE(LoadApp("app_with_tab_container", &extension_app));
// Set a pref indicating that the user wants to open this app in a window.
SetAppLaunchPref(extension_app->id(), extensions::LAUNCH_TYPE_WINDOW);
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendSwitchASCII(switches::kAppId, extension_app->id());
ui_test_utils::BrowserChangeObserver browser_waiter(
nullptr, ui_test_utils::BrowserChangeObserver::ChangeType::kAdded);
ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl(
command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo,
{browser()->profile(), StartupProfileMode::kBrowserWindow}, {}));
ExpectBlockLaunchWithLaunchBehavior(extension_app->id(),
/*force_install_dialog=*/false);
ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile()));
}
IN_PROC_BROWSER_TEST_P(StartupBrowserCreatorChromeAppShortcutTestWithLaunch,
OpenAppShortcutTabPref) {
// When we start, the browser should already have an open tab.
TabStripModel* tab_strip = browser()->tab_strip_model();
EXPECT_EQ(1, tab_strip->count());
ui_test_utils::TabAddedWaiter tab_waiter(browser());
// Load an app with launch.container = 'tab'.
const Extension* extension_app = nullptr;
ASSERT_NO_FATAL_FAILURE(LoadApp("app_with_tab_container", &extension_app));
// Set a pref indicating that the user wants to open this app in a tab.
SetAppLaunchPref(extension_app->id(), extensions::LAUNCH_TYPE_REGULAR);
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendSwitchASCII(switches::kAppId, extension_app->id());
ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl(
command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo,
{browser()->profile(), StartupProfileMode::kBrowserWindow}, {}));
ExpectBlockLaunchWithLaunchBehavior(extension_app->id(),
/*force_install_dialog=*/false);
ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile()));
}
IN_PROC_BROWSER_TEST_P(StartupBrowserCreatorChromeAppShortcutTestWithLaunch,
OpenPolicyForcedAppShortcut) {
// Load an app with launch.container = 'tab'.
const Extension* extension_app = nullptr;
ASSERT_NO_FATAL_FAILURE(LoadApp("app_with_tab_container", &extension_app));
// Install a test policy provider which will mark the app as force-installed.
extensions::TestManagementPolicyProvider policy_provider(
extensions::TestManagementPolicyProvider::MUST_REMAIN_INSTALLED);
extensions::ExtensionSystem* extension_system =
extensions::ExtensionSystem::Get(browser()->profile());
extension_system->management_policy()->RegisterProvider(&policy_provider);
// When we start, the browser should already have an open tab.
TabStripModel* tab_strip = browser()->tab_strip_model();
EXPECT_EQ(1, tab_strip->count());
ui_test_utils::TabAddedWaiter tab_waiter(browser());
// Add --app-id=<extension->id()> to the command line.
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendSwitchASCII(switches::kAppId, extension_app->id());
ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl(
command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo,
{browser()->profile(), StartupProfileMode::kBrowserWindow}, {}));
ExpectBlockLaunchWithLaunchBehavior(extension_app->id(),
/*force_install_dialog=*/true);
ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile()));
}
// These tests are specifically for testing what happens when the "Launch
// Anyways" button is pressed.
INSTANTIATE_TEST_SUITE_P(
All,
StartupBrowserCreatorChromeAppShortcutTestWithLaunch,
::testing::Values(ChromeAppDeprecationFeatureValue::kEnabledWithNoLaunch),
ChromeAppDeprecationFeatureValueToString);
#endif // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
#endif // !BUILDFLAG(IS_CHROMEOS)
#if BUILDFLAG(IS_WIN)
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest, ValidNotificationLaunchId) {
// Simulate a launch from the notification_helper process which appends the
// kNotificationLaunchId switch to the command line.
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendSwitchNative(
switches::kNotificationLaunchId,
L"1|1|0|Default|aumi|0|https://example.com/|notification_id");
ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl(
command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo,
{browser()->profile(), StartupProfileMode::kBrowserWindow}, {}));
// The launch delegates to the notification system and doesn't open any new
// browser window.
ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile()));
}
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest, InvalidNotificationLaunchId) {
// Simulate a launch with invalid launch id, which will fail.
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendSwitchNative(switches::kNotificationLaunchId, L"");
StartupBrowserCreator browser_creator;
ASSERT_FALSE(StartupBrowserCreator().ProcessCmdLineImpl(
command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo,
{browser()->profile(), StartupProfileMode::kBrowserWindow}, {}));
// No new browser window is open.
ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile()));
}
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest,
NotificationLaunchIdDisablesLastOpenProfiles) {
Profile* default_profile = browser()->profile();
ProfileManager* profile_manager = g_browser_process->profile_manager();
// Create another profile.
base::FilePath dest_path = profile_manager->user_data_dir();
dest_path = dest_path.Append(FILE_PATH_LITERAL("New Profile 1"));
Profile& other_profile =
profiles::testing::CreateProfileSync(profile_manager, dest_path);
// Close the browser.
CloseBrowserAsynchronously(browser());
// Simulate a launch.
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendSwitchNative(
switches::kNotificationLaunchId,
L"1|1|0|Default|0|https://example.com/|notification_id");
std::vector<Profile*> last_opened_profiles;
last_opened_profiles.push_back(&other_profile);
StartupBrowserCreator browser_creator;
browser_creator.Start(command_line, profile_manager->user_data_dir(),
{default_profile, StartupProfileMode::kBrowserWindow},
last_opened_profiles);
// |browser()| is still around at this point, even though we've closed its
// window. Thus the browser count for default_profile is 1.
ASSERT_EQ(1u, chrome::GetBrowserCount(default_profile));
// When the kNotificationLaunchId switch is present, any last opened profile
// is ignored. Thus there is no browser for other_profile.
ASSERT_EQ(0u, chrome::GetBrowserCount(&other_profile));
}
#endif // BUILDFLAG(IS_WIN)
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest,
ReadingWasRestartedAfterRestart) {
// Tests that StartupBrowserCreator::WasRestarted reads and resets the
// preference kWasRestarted correctly.
StartupBrowserCreator::was_restarted_read_ = false;
PrefService* pref_service = g_browser_process->local_state();
pref_service->SetBoolean(prefs::kWasRestarted, true);
EXPECT_TRUE(StartupBrowserCreator::WasRestarted());
EXPECT_FALSE(pref_service->GetBoolean(prefs::kWasRestarted));
EXPECT_TRUE(StartupBrowserCreator::WasRestarted());
}
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest,
ReadingWasRestartedAfterNormalStart) {
// Tests that StartupBrowserCreator::WasRestarted reads and resets the
// preference kWasRestarted correctly.
StartupBrowserCreator::was_restarted_read_ = false;
PrefService* pref_service = g_browser_process->local_state();
pref_service->SetBoolean(prefs::kWasRestarted, false);
EXPECT_FALSE(StartupBrowserCreator::WasRestarted());
EXPECT_FALSE(pref_service->GetBoolean(prefs::kWasRestarted));
EXPECT_FALSE(StartupBrowserCreator::WasRestarted());
}
#if !BUILDFLAG(IS_CHROMEOS)
// If startup pref is set as LAST_AND_URLS, startup urls should be opened in a
// new browser window separated from the last-session-restored browser. This
// test does not apply to ChromeOS.
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest, StartupPrefSetAsLastAndURLs) {
ASSERT_TRUE(embedded_test_server()->Start());
ProfileManager* profile_manager = g_browser_process->profile_manager();
// Create a new profile.
base::FilePath dest_path =
profile_manager->user_data_dir().Append(FILE_PATH_LITERAL("New Profile"));
Profile& profile =
profiles::testing::CreateProfileSync(profile_manager, dest_path);
DisableWhatsNewPage();
const GURL t1_url = embedded_test_server()->GetURL("/title1.html");
const GURL t2_url = embedded_test_server()->GetURL("/title2.html");
const GURL t3_url = embedded_test_server()->GetURL("/title3.html");
// Set the profiles to open both urls and last visited pages.
SessionStartupPref startup_pref(SessionStartupPref::LAST_AND_URLS);
std::vector<GURL> urls_to_open;
urls_to_open.push_back(t1_url);
urls_to_open.push_back(t2_url);
startup_pref.urls = urls_to_open;
SessionStartupPref::SetStartupPref(&profile, startup_pref);
// Open |t3_url| in a tab.
Browser* new_browser = Browser::Create(
Browser::CreateParams(Browser::TYPE_NORMAL, &profile, true));
TabStripModel* tab_strip_model = new_browser->tab_strip_model();
ui_test_utils::NavigateToURLWithDisposition(
new_browser, t3_url, WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
ASSERT_EQ(1, tab_strip_model->count());
EXPECT_EQ(t3_url,
tab_strip_model->GetWebContentsAt(0)->GetLastCommittedURL());
// Close the browser without deleting |profile|.
ScopedProfileKeepAlive profile_keep_alive(
&profile, ProfileKeepAliveOrigin::kBrowserWindow);
CloseBrowserSynchronously(new_browser);
// Close the main browser.
CloseBrowserAsynchronously(browser());
// Do a simple non-process-startup browser launch.
base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
StartupBrowserCreator browser_creator;
std::vector<Profile*> last_opened_profiles;
last_opened_profiles.push_back(browser()->profile());
last_opened_profiles.push_back(&profile);
base::RunLoop run_loop;
browser_creator.Start(
dummy, profile_manager->user_data_dir(),
{browser()->profile(), StartupProfileMode::kBrowserWindow},
last_opened_profiles);
testing::SessionsRestoredWaiter restore_waiter(run_loop.QuitClosure(), 1);
run_loop.Run();
const auto wait_for_load_stop_for_browser = [](Browser* browser) {
TabStripModel* tab_strip_model = browser->tab_strip_model();
for (int i = 0; i < tab_strip_model->count(); ++i) {
content::WebContents* contents = tab_strip_model->GetWebContentsAt(i);
EXPECT_TRUE(content::WaitForLoadStop(contents));
}
};
// |profile| restored the last open pages and opened the urls in an active new
// window.
ASSERT_EQ(2u, chrome::GetBrowserCount(&profile));
Browser* pref_urls_opened_browser =
chrome::FindLastActiveWithProfile(&profile);
ASSERT_TRUE(pref_urls_opened_browser);
Browser* last_session_opened_browser =
FindOneOtherBrowserForProfile(&profile, pref_urls_opened_browser);
ASSERT_TRUE(last_session_opened_browser);
// Check the last-session-restored browser.
EXPECT_NO_FATAL_FAILURE(
wait_for_load_stop_for_browser(last_session_opened_browser));
tab_strip_model = last_session_opened_browser->tab_strip_model();
ASSERT_EQ(1, tab_strip_model->count());
EXPECT_EQ(t3_url, tab_strip_model->GetWebContentsAt(0)->GetVisibleURL());
// Check the pref-urls-opened browser.
EXPECT_NO_FATAL_FAILURE(
wait_for_load_stop_for_browser(pref_urls_opened_browser));
tab_strip_model = pref_urls_opened_browser->tab_strip_model();
EXPECT_EQ(2, tab_strip_model->GetTabCount());
EXPECT_EQ(t1_url, tab_strip_model->GetWebContentsAt(0)->GetVisibleURL());
EXPECT_EQ(t2_url, tab_strip_model->GetWebContentsAt(1)->GetVisibleURL());
EXPECT_EQ(0, tab_strip_model->active_index());
}
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest, StartupURLsForTwoProfiles) {
Profile* default_profile = browser()->profile();
ProfileManager* profile_manager = g_browser_process->profile_manager();
// Create another profile.
base::FilePath dest_path = profile_manager->user_data_dir();
dest_path = dest_path.Append(FILE_PATH_LITERAL("New Profile 1"));
Profile& other_profile =
profiles::testing::CreateProfileSync(profile_manager, dest_path);
// Use a couple arbitrary URLs.
std::vector<GURL> urls1;
urls1.push_back(ui_test_utils::GetTestUrl(
base::FilePath(base::FilePath::kCurrentDirectory),
base::FilePath(FILE_PATH_LITERAL("title1.html"))));
std::vector<GURL> urls2;
urls2.push_back(ui_test_utils::GetTestUrl(
base::FilePath(base::FilePath::kCurrentDirectory),
base::FilePath(FILE_PATH_LITERAL("title2.html"))));
// Set different startup preferences for the 2 profiles.
SessionStartupPref pref1(SessionStartupPref::URLS);
pref1.urls = urls1;
SessionStartupPref::SetStartupPref(default_profile, pref1);
SessionStartupPref pref2(SessionStartupPref::URLS);
pref2.urls = urls2;
SessionStartupPref::SetStartupPref(&other_profile, pref2);
DisableWhatsNewPage();
// Close the browser.
CloseBrowserAsynchronously(browser());
// Do a simple non-process-startup browser launch.
base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
StartupBrowserCreator browser_creator;
std::vector<Profile*> last_opened_profiles;
last_opened_profiles.push_back(default_profile);
last_opened_profiles.push_back(&other_profile);
browser_creator.Start(dummy, profile_manager->user_data_dir(),
{default_profile, StartupProfileMode::kBrowserWindow},
last_opened_profiles);
// urls1 were opened in a browser for default_profile, and urls2 were opened
// in a browser for other_profile.
Browser* new_browser = nullptr;
// |browser()| is still around at this point, even though we've closed its
// window. Thus the browser count for default_profile is 2.
ASSERT_EQ(2u, chrome::GetBrowserCount(default_profile));
new_browser = FindOneOtherBrowserForProfile(default_profile, browser());
ASSERT_TRUE(new_browser);
TabStripModel* tab_strip = new_browser->tab_strip_model();
// The new browser should have only the desired URL for the profile.
ASSERT_EQ(1, tab_strip->count());
EXPECT_EQ(urls1[0], tab_strip->GetWebContentsAt(0)->GetVisibleURL());
ASSERT_EQ(1u, chrome::GetBrowserCount(&other_profile));
new_browser = FindOneOtherBrowserForProfile(&other_profile, nullptr);
ASSERT_TRUE(new_browser);
tab_strip = new_browser->tab_strip_model();
ASSERT_EQ(1, tab_strip->count());
EXPECT_EQ(urls2[0], tab_strip->GetWebContentsAt(0)->GetVisibleURL());
}
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest, PRE_UpdateWithTwoProfiles) {
// Simulate a browser restart by creating the profiles in the PRE_ part.
ProfileManager* profile_manager = g_browser_process->profile_manager();
ASSERT_TRUE(embedded_test_server()->Start());
// Create two profiles.
base::FilePath dest_path = profile_manager->user_data_dir();
Profile& profile1 = profiles::testing::CreateProfileSync(
profile_manager, dest_path.Append(FILE_PATH_LITERAL("New Profile 1")));
Profile& profile2 = profiles::testing::CreateProfileSync(
profile_manager, dest_path.Append(FILE_PATH_LITERAL("New Profile 2")));
DisableWhatsNewPage();
// Don't delete Profiles too early.
ScopedProfileKeepAlive profile1_keep_alive(
&profile1, ProfileKeepAliveOrigin::kBrowserWindow);
ScopedProfileKeepAlive profile2_keep_alive(
&profile2, ProfileKeepAliveOrigin::kBrowserWindow);
// Open some urls with the browsers, and close them.
Browser* browser1 = Browser::Create(
Browser::CreateParams(Browser::TYPE_NORMAL, &profile1, true));
chrome::NewTab(browser1);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser1, embedded_test_server()->GetURL("/empty.html")));
CloseBrowserSynchronously(browser1);
Browser* browser2 = Browser::Create(
Browser::CreateParams(Browser::TYPE_NORMAL, &profile2, true));
chrome::NewTab(browser2);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser2, embedded_test_server()->GetURL("/form.html")));
CloseBrowserSynchronously(browser2);
// Set different startup preferences for the 2 profiles.
std::vector<GURL> urls1;
urls1.push_back(ui_test_utils::GetTestUrl(
base::FilePath(base::FilePath::kCurrentDirectory),
base::FilePath(FILE_PATH_LITERAL("title1.html"))));
std::vector<GURL> urls2;
urls2.push_back(ui_test_utils::GetTestUrl(
base::FilePath(base::FilePath::kCurrentDirectory),
base::FilePath(FILE_PATH_LITERAL("title2.html"))));
// Set different startup preferences for the 2 profiles.
SessionStartupPref pref1(SessionStartupPref::URLS);
pref1.urls = urls1;
SessionStartupPref::SetStartupPref(&profile1, pref1);
SessionStartupPref pref2(SessionStartupPref::URLS);
pref2.urls = urls2;
SessionStartupPref::SetStartupPref(&profile2, pref2);
profile1.GetPrefs()->CommitPendingWrite();
profile2.GetPrefs()->CommitPendingWrite();
}
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest, UpdateWithTwoProfiles) {
// Make StartupBrowserCreator::WasRestarted() return true.
StartupBrowserCreator::was_restarted_read_ = false;
PrefService* pref_service = g_browser_process->local_state();
pref_service->SetBoolean(prefs::kWasRestarted, true);
ProfileManager* profile_manager = g_browser_process->profile_manager();
// Open the two profiles.
base::FilePath dest_path = profile_manager->user_data_dir();
Profile& profile1 = profiles::testing::CreateProfileSync(
profile_manager, dest_path.Append(FILE_PATH_LITERAL("New Profile 1")));
Profile& profile2 = profiles::testing::CreateProfileSync(
profile_manager, dest_path.Append(FILE_PATH_LITERAL("New Profile 2")));
// Simulate a launch after a browser update.
base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
StartupBrowserCreator browser_creator;
std::vector<Profile*> last_opened_profiles;
last_opened_profiles.push_back(&profile1);
last_opened_profiles.push_back(&profile2);
base::RunLoop run_loop;
testing::SessionsRestoredWaiter restore_waiter(run_loop.QuitClosure(), 2);
browser_creator.Start(dummy, profile_manager->user_data_dir(),
{&profile1, StartupProfileMode::kBrowserWindow},
last_opened_profiles);
run_loop.Run();
// The startup URLs are ignored, and instead the last open sessions are
// restored.
EXPECT_TRUE(profile1.restored_last_session());
EXPECT_TRUE(profile2.restored_last_session());
Browser* new_browser = nullptr;
ASSERT_EQ(1u, chrome::GetBrowserCount(&profile1));
new_browser = FindOneOtherBrowserForProfile(&profile1, nullptr);
ASSERT_TRUE(new_browser);
TabStripModel* tab_strip = new_browser->tab_strip_model();
ASSERT_EQ(1, tab_strip->count());
EXPECT_EQ("/empty.html",
tab_strip->GetWebContentsAt(0)->GetLastCommittedURL().path());
ASSERT_EQ(1u, chrome::GetBrowserCount(&profile2));
new_browser = FindOneOtherBrowserForProfile(&profile2, nullptr);
ASSERT_TRUE(new_browser);
tab_strip = new_browser->tab_strip_model();
ASSERT_EQ(1, tab_strip->count());
EXPECT_EQ("/form.html",
tab_strip->GetWebContentsAt(0)->GetLastCommittedURL().path());
}
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest,
ProfilesWithoutPagesNotLaunched) {
ASSERT_TRUE(embedded_test_server()->Start());
ProfileManager* profile_manager = g_browser_process->profile_manager();
// Create 4 more profiles.
base::FilePath dest_path1 = profile_manager->user_data_dir().Append(
FILE_PATH_LITERAL("New Profile 1"));
base::FilePath dest_path2 = profile_manager->user_data_dir().Append(
FILE_PATH_LITERAL("New Profile 2"));
base::FilePath dest_path3 = profile_manager->user_data_dir().Append(
FILE_PATH_LITERAL("New Profile 3"));
base::FilePath dest_path4 = profile_manager->user_data_dir().Append(
FILE_PATH_LITERAL("New Profile 4"));
Profile& profile_home1 =
profiles::testing::CreateProfileSync(profile_manager, dest_path1);
Profile& profile_home2 =
profiles::testing::CreateProfileSync(profile_manager, dest_path2);
Profile& profile_last =
profiles::testing::CreateProfileSync(profile_manager, dest_path3);
Profile& profile_urls =
profiles::testing::CreateProfileSync(profile_manager, dest_path4);
DisableWhatsNewPage();
// Set the profiles to open urls, open last visited pages or display the home
// page.
SessionStartupPref pref_home(SessionStartupPref::DEFAULT);
SessionStartupPref::SetStartupPref(&profile_home1, pref_home);
SessionStartupPref::SetStartupPref(&profile_home2, pref_home);
SessionStartupPref pref_last(SessionStartupPref::LAST);
SessionStartupPref::SetStartupPref(&profile_last, pref_last);
std::vector<GURL> urls;
urls.push_back(ui_test_utils::GetTestUrl(
base::FilePath(base::FilePath::kCurrentDirectory),
base::FilePath(FILE_PATH_LITERAL("title1.html"))));
SessionStartupPref pref_urls(SessionStartupPref::URLS);
pref_urls.urls = urls;
SessionStartupPref::SetStartupPref(&profile_urls, pref_urls);
// Open a page with profile_last.
Browser* browser_last = Browser::Create(
Browser::CreateParams(Browser::TYPE_NORMAL, &profile_last, true));
chrome::NewTab(browser_last);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser_last, embedded_test_server()->GetURL("/empty.html")));
// Close the browser without deleting |profile_last|.
ScopedProfileKeepAlive profile_last_keep_alive(
&profile_last, ProfileKeepAliveOrigin::kBrowserWindow);
CloseBrowserSynchronously(browser_last);
// Close the main browser.
CloseBrowserAsynchronously(browser());
// Do a simple non-process-startup browser launch.
base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
StartupBrowserCreator browser_creator;
std::vector<Profile*> last_opened_profiles;
last_opened_profiles.push_back(&profile_home1);
last_opened_profiles.push_back(&profile_home2);
last_opened_profiles.push_back(&profile_last);
last_opened_profiles.push_back(&profile_urls);
base::RunLoop run_loop;
// Only profile_last should get its session restored.
testing::SessionsRestoredWaiter restore_waiter(run_loop.QuitClosure(), 1);
browser_creator.Start(dummy, profile_manager->user_data_dir(),
{&profile_home1, StartupProfileMode::kBrowserWindow},
last_opened_profiles);
run_loop.Run();
Browser* new_browser = nullptr;
// The last open profile (the profile_home1 in this case) will always be
// launched, even if it will open just the NTP.
ASSERT_EQ(1u, chrome::GetBrowserCount(&profile_home1));
new_browser = FindOneOtherBrowserForProfile(&profile_home1, nullptr);
ASSERT_TRUE(new_browser);
TabStripModel* tab_strip = new_browser->tab_strip_model();
// The new browser should have only the NTP.
ASSERT_EQ(1, tab_strip->count());
EXPECT_EQ(ntp_test_utils::GetFinalNtpUrl(new_browser->profile()),
tab_strip->GetWebContentsAt(0)->GetVisibleURL());
// profile_urls opened the urls.
ASSERT_EQ(1u, chrome::GetBrowserCount(&profile_urls));
new_browser = FindOneOtherBrowserForProfile(&profile_urls, nullptr);
ASSERT_TRUE(new_browser);
tab_strip = new_browser->tab_strip_model();
ASSERT_EQ(1, tab_strip->count());
EXPECT_EQ(urls[0], tab_strip->GetWebContentsAt(0)->GetVisibleURL());
// profile_last opened the last open pages.
ASSERT_EQ(1u, chrome::GetBrowserCount(&profile_last));
new_browser = FindOneOtherBrowserForProfile(&profile_last, nullptr);
ASSERT_TRUE(new_browser);
tab_strip = new_browser->tab_strip_model();
ASSERT_EQ(1, tab_strip->count());
EXPECT_EQ("/empty.html",
tab_strip->GetWebContentsAt(0)->GetLastCommittedURL().path());
// profile_home2 was not launched since it would've only opened the home page.
ASSERT_EQ(0u, chrome::GetBrowserCount(&profile_home2));
}
// This tests that opening multiple profiles with session restore enabled,
// shutting down, and then launching with kNoStartupWindow doesn't restore
// the previously opened profiles.
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest, RestoreWithNoStartupWindow) {
ASSERT_TRUE(embedded_test_server()->Start());
ProfileManager* profile_manager = g_browser_process->profile_manager();
// Create 2 more profiles.
base::FilePath dest_path1 = profile_manager->user_data_dir().Append(
FILE_PATH_LITERAL("New Profile 1"));
base::FilePath dest_path2 = profile_manager->user_data_dir().Append(
FILE_PATH_LITERAL("New Profile 2"));
Profile& profile1 =
profiles::testing::CreateProfileSync(profile_manager, dest_path1);
Profile& profile2 =
profiles::testing::CreateProfileSync(profile_manager, dest_path2);
DisableWhatsNewPage();
// Set the profiles to open last visited pages.
SessionStartupPref pref_last(SessionStartupPref::LAST);
SessionStartupPref::SetStartupPref(&profile1, pref_last);
SessionStartupPref::SetStartupPref(&profile2, pref_last);
Profile* default_profile = browser()->profile();
// TODO(crbug.com/40594327): Adapt this test for DestroyProfileOnBrowserClose
// if needed.
ScopedKeepAlive keep_alive(KeepAliveOrigin::SESSION_RESTORE,
KeepAliveRestartOption::DISABLED);
ScopedProfileKeepAlive default_profile_keep_alive(
default_profile, ProfileKeepAliveOrigin::kBrowserWindow);
ScopedProfileKeepAlive profile1_keep_alive(
&profile1, ProfileKeepAliveOrigin::kBrowserWindow);
ScopedProfileKeepAlive profile2_keep_alive(
&profile2, ProfileKeepAliveOrigin::kBrowserWindow);
// Open a page with profile1 and profile2.
Browser* browser1 = Browser::Create({Browser::TYPE_NORMAL, &profile1, true});
chrome::NewTab(browser1);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser1, embedded_test_server()->GetURL("/empty.html")));
Browser* browser2 = Browser::Create({Browser::TYPE_NORMAL, &profile2, true});
chrome::NewTab(browser2);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser2, embedded_test_server()->GetURL("/empty.html")));
// Exit the browser, saving the multi-profile session state.
chrome::ExecuteCommand(browser(), IDC_EXIT);
{
base::RunLoop run_loop;
AllBrowsersClosedWaiter waiter(run_loop.QuitClosure());
run_loop.Run();
}
#if BUILDFLAG(IS_MAC)
// While we closed all the browsers above, this doesn't quit the Mac app,
// leaving the app in a half-closed state. Cancel the termination to put the
// Mac app back into a known state.
chrome_browser_application_mac::CancelTerminate();
#endif
base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
dummy.AppendSwitch(switches::kNoStartupWindow);
StartupBrowserCreator browser_creator;
std::vector<Profile*> last_opened_profiles = {&profile1, &profile2};
browser_creator.Start(dummy, profile_manager->user_data_dir(),
{default_profile, StartupProfileMode::kBrowserWindow},
last_opened_profiles);
// TODO(davidbienvenu): Waiting for some sort of browser is started
// notification would be better. But, we're not opening any browser
// windows, so we'd need to invent a new notification.
content::RunAllTasksUntilIdle();
// No browser windows should be opened.
EXPECT_EQ(chrome::GetBrowserCount(&profile1), 0u);
EXPECT_EQ(chrome::GetBrowserCount(&profile2), 0u);
base::CommandLine empty(base::CommandLine::NO_PROGRAM);
base::RunLoop run_loop;
testing::SessionsRestoredWaiter restore_waiter(run_loop.QuitClosure(), 2);
StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
empty, {}, {dest_path1, StartupProfileModeReason::kWasRestarted});
run_loop.Run();
// profile1 and profile2 browser windows should be opened.
EXPECT_EQ(chrome::GetBrowserCount(&profile1), 1u);
EXPECT_EQ(chrome::GetBrowserCount(&profile2), 1u);
}
// Flaky. See https://crbug.com/819976.
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest,
DISABLED_ProfilesLaunchedAfterCrash) {
// After an unclean exit, all profiles will be launched. However, they won't
// open any pages automatically.
ProfileManager* profile_manager = g_browser_process->profile_manager();
// Create 3 profiles.
base::FilePath dest_path1 = profile_manager->user_data_dir().Append(
FILE_PATH_LITERAL("New Profile 1"));
base::FilePath dest_path2 = profile_manager->user_data_dir().Append(
FILE_PATH_LITERAL("New Profile 2"));
base::FilePath dest_path3 = profile_manager->user_data_dir().Append(
FILE_PATH_LITERAL("New Profile 3"));
Profile& profile_home =
profiles::testing::CreateProfileSync(profile_manager, dest_path1);
Profile& profile_last =
profiles::testing::CreateProfileSync(profile_manager, dest_path2);
Profile& profile_urls =
profiles::testing::CreateProfileSync(profile_manager, dest_path3);
// Set the profiles to open the home page, last visited pages or URLs.
SessionStartupPref pref_home(SessionStartupPref::DEFAULT);
SessionStartupPref::SetStartupPref(&profile_home, pref_home);
SessionStartupPref pref_last(SessionStartupPref::LAST);
SessionStartupPref::SetStartupPref(&profile_last, pref_last);
std::vector<GURL> urls;
urls.push_back(ui_test_utils::GetTestUrl(
base::FilePath(base::FilePath::kCurrentDirectory),
base::FilePath(FILE_PATH_LITERAL("title1.html"))));
SessionStartupPref pref_urls(SessionStartupPref::URLS);
pref_urls.urls = urls;
SessionStartupPref::SetStartupPref(&profile_urls, pref_urls);
// Simulate a launch after an unclear exit.
CloseBrowserAsynchronously(browser());
ExitTypeService::GetInstanceForProfile(&profile_home)
->SetLastSessionExitTypeForTest(ExitType::kCrashed);
ExitTypeService::GetInstanceForProfile(&profile_last)
->SetLastSessionExitTypeForTest(ExitType::kCrashed);
ExitTypeService::GetInstanceForProfile(&profile_urls)
->SetLastSessionExitTypeForTest(ExitType::kCrashed);
base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
dummy.AppendSwitchASCII(switches::kTestType, "browser");
StartupBrowserCreator browser_creator;
std::vector<Profile*> last_opened_profiles;
last_opened_profiles.push_back(&profile_home);
last_opened_profiles.push_back(&profile_last);
last_opened_profiles.push_back(&profile_urls);
browser_creator.Start(dummy, profile_manager->user_data_dir(),
{&profile_home, StartupProfileMode::kBrowserWindow},
last_opened_profiles);
// No profiles are getting restored, since they all display the crash info
// bar.
EXPECT_FALSE(SessionRestore::IsRestoring(&profile_home));
EXPECT_FALSE(SessionRestore::IsRestoring(&profile_last));
EXPECT_FALSE(SessionRestore::IsRestoring(&profile_urls));
// The profile which normally opens the home page displays the new tab page.
Browser* new_browser = nullptr;
ASSERT_EQ(1u, chrome::GetBrowserCount(&profile_home));
new_browser = FindOneOtherBrowserForProfile(&profile_home, nullptr);
ASSERT_TRUE(new_browser);
TabStripModel* tab_strip = new_browser->tab_strip_model();
// The new browser should have only the NTP.
ASSERT_EQ(1, tab_strip->count());
EXPECT_TRUE(search::IsInstantNTP(tab_strip->GetWebContentsAt(0)));
EnsureRestoreUIWasShown(tab_strip->GetWebContentsAt(0));
// The profile which normally opens last open pages displays the new tab page.
ASSERT_EQ(1u, chrome::GetBrowserCount(&profile_last));
new_browser = FindOneOtherBrowserForProfile(&profile_last, nullptr);
ASSERT_TRUE(new_browser);
tab_strip = new_browser->tab_strip_model();
ASSERT_EQ(1, tab_strip->count());
EXPECT_TRUE(search::IsInstantNTP(tab_strip->GetWebContentsAt(0)));
EnsureRestoreUIWasShown(tab_strip->GetWebContentsAt(0));
// The profile which normally opens URLs displays the new tab page.
ASSERT_EQ(1u, chrome::GetBrowserCount(&profile_urls));
new_browser = FindOneOtherBrowserForProfile(&profile_urls, nullptr);
ASSERT_TRUE(new_browser);
tab_strip = new_browser->tab_strip_model();
ASSERT_EQ(1, tab_strip->count());
EXPECT_TRUE(search::IsInstantNTP(tab_strip->GetWebContentsAt(0)));
EnsureRestoreUIWasShown(tab_strip->GetWebContentsAt(0));
}
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest,
LaunchMultipleLockedProfiles) {
signin_util::ScopedForceSigninSetterForTesting force_signin_setter(true);
ASSERT_TRUE(embedded_test_server()->Start());
ProfileManager* profile_manager = g_browser_process->profile_manager();
base::FilePath user_data_dir = profile_manager->user_data_dir();
Profile& profile1 = profiles::testing::CreateProfileSync(
profile_manager,
user_data_dir.Append(FILE_PATH_LITERAL("New Profile 1")));
Profile& profile2 = profiles::testing::CreateProfileSync(
profile_manager,
user_data_dir.Append(FILE_PATH_LITERAL("New Profile 2")));
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
StartupBrowserCreator browser_creator;
std::vector<GURL> urls;
urls.push_back(embedded_test_server()->GetURL("/title1.html"));
std::vector<Profile*> last_opened_profiles;
last_opened_profiles.push_back(&profile1);
last_opened_profiles.push_back(&profile2);
SessionStartupPref pref(SessionStartupPref::URLS);
pref.urls = urls;
SessionStartupPref::SetStartupPref(&profile2, pref);
ProfileAttributesEntry* entry1 =
profile_manager->GetProfileAttributesStorage()
.GetProfileAttributesWithPath(profile1.GetPath());
ASSERT_NE(entry1, nullptr);
entry1->LockForceSigninProfile(true);
ProfileAttributesEntry* entry2 =
profile_manager->GetProfileAttributesStorage()
.GetProfileAttributesWithPath(profile2.GetPath());
ASSERT_NE(entry2, nullptr);
entry2->LockForceSigninProfile(false);
browser_creator.Start(command_line, profile_manager->user_data_dir(),
{&profile1, StartupProfileMode::kBrowserWindow},
last_opened_profiles);
ASSERT_EQ(0u, chrome::GetBrowserCount(&profile1));
ASSERT_EQ(1u, chrome::GetBrowserCount(&profile2));
}
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
webapps::AppId InstallPWAWithName(Profile* profile,
const GURL& start_url,
const std::string& app_name) {
auto web_app_info =
web_app::WebAppInstallInfo::CreateWithStartUrlForTesting(start_url);
web_app_info->scope = start_url.GetWithoutFilename();
web_app_info->user_display_mode =
web_app::mojom::UserDisplayMode::kStandalone;
web_app_info->title = base::UTF8ToUTF16(app_name);
return web_app::test::InstallWebApp(profile, std::move(web_app_info));
}
class StartupBrowserWithListAppsFeature : public StartupBrowserCreatorTest {
public:
StartupBrowserWithListAppsFeature() {
scoped_feature_list_.InitAndEnableFeature(features::kListWebAppsSwitch);
}
private:
web_app::OsIntegrationTestOverrideBlockingRegistration faked_os_integration_;
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(StartupBrowserWithListAppsFeature,
ListAppsForAllProfiles) {
ProfileManager* profile_manager = g_browser_process->profile_manager();
base::FilePath user_data_dir = profile_manager->user_data_dir();
Profile* profile1 = browser()->profile();
// Create a new profile.
Profile& profile2 = profiles::testing::CreateProfileSync(
profile_manager,
user_data_dir.Append(FILE_PATH_LITERAL("New Profile 1")));
// Install web apps for the two profiles.
auto example_url1 = GURL("https://www.example_one.com");
std::string app_name1 = "A Test Web App1";
webapps::AppId app_id1 =
InstallPWAWithName(profile1, example_url1, app_name1);
auto example_url2 = GURL("https://www.example_two.com");
std::string app_name2 = "A Test Web App2";
webapps::AppId app_id2 =
InstallPWAWithName(profile1, example_url2, app_name2);
auto example_url3 = GURL("https://www.example_three.com");
std::string app_name3 = "A Test Web App3";
webapps::AppId app_id3 =
InstallPWAWithName(&profile2, example_url3, app_name3);
auto example_url4 = GURL("https://www.example_four.com");
std::string app_name4 = "A Test Web App4";
webapps::AppId app_id4 =
InstallPWAWithName(&profile2, example_url4, app_name4);
// Launch web apps for the two profiles.
Browser* app_browser1 =
web_app::LaunchWebAppBrowserAndWait(profile1, app_id1);
Browser* app_browser2 =
web_app::LaunchWebAppBrowserAndWait(&profile2, app_id3);
ASSERT_NE(app_browser1, nullptr);
ASSERT_NE(app_browser2, nullptr);
// Expected installed apps for given profile in JSON format as a raw string.
// This is short so it is easier to just directly embed it versus using a
// separate golden file.
// NOTE: The output format uses an indent of 3 spaces and a trailing newline.
std::string expected_info = R"({
"installed_web_apps": [ {
"profile_id": "New Profile 1",
"web_apps": [ {
"id": "dhjmdeeglmiagclobghjoaodgfhkjhgb",
"name": "A Test Web App3"
}, {
"id": "ifgmomgfhabbbbapaeolfmaoamipmegf",
"name": "A Test Web App4"
} ]
}, {
"profile_id": "Default",
"web_apps": [ {
"id": "ghbcfjbejbhpcpbcmbgmffhopeebbkpi",
"name": "A Test Web App1"
}, {
"id": "nlbjkhjncnclobaokfdbpgejplliapkd",
"name": "A Test Web App2"
} ]
} ],
"open_web_apps": [ {
"profile_id": "Default",
"web_apps": [ {
"id": "ghbcfjbejbhpcpbcmbgmffhopeebbkpi",
"name": "A Test Web App1"
} ]
}, {
"profile_id": "New Profile 1",
"web_apps": [ {
"id": "dhjmdeeglmiagclobghjoaodgfhkjhgb",
"name": "A Test Web App3"
} ]
} ]
}
)";
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
base::FilePath output_path =
user_data_dir.Append(FILE_PATH_LITERAL("AppsForAllProfiles.json"));
command_line.AppendSwitchPath(switches::kListApps, output_path);
ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl(
command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo,
{browser()->profile(), StartupProfileMode::kBrowserWindow}, {}));
CloseBrowserSynchronously(app_browser1);
CloseBrowserSynchronously(app_browser2);
CloseBrowserSynchronously(browser());
content::RunAllTasksUntilIdle();
{
base::ScopedAllowBlockingForTesting allow_blocking;
std::string file_contents;
ASSERT_TRUE(base::ReadFileToString(output_path, &file_contents));
// Normalize Windows line endings to Linux line endings used by golden data.
base::ReplaceSubstringsAfterOffset(&file_contents, 0, "\r\n", "\n");
ASSERT_EQ(expected_info, file_contents);
}
}
IN_PROC_BROWSER_TEST_F(StartupBrowserWithListAppsFeature,
ListAppsForGivenProfile) {
ProfileManager* profile_manager = g_browser_process->profile_manager();
base::FilePath user_data_dir = profile_manager->user_data_dir();
Profile* profile1 = browser()->profile();
// Create a new profile.
Profile& profile2 = profiles::testing::CreateProfileSync(
profile_manager,
user_data_dir.Append(FILE_PATH_LITERAL("New Profile 1")));
// Install web apps for the two profiles.
auto example_url1 = GURL("https://www.example_one.com");
std::string app_name1 = "A Test Web App1";
webapps::AppId app_id1 =
InstallPWAWithName(profile1, example_url1, app_name1);
auto example_url2 = GURL("https://www.example_two.com");
std::string app_name2 = "A Test Web App2";
webapps::AppId app_id2 =
InstallPWAWithName(profile1, example_url2, app_name2);
auto example_url3 = GURL("https://www.example_three.com");
std::string app_name3 = "A Test Web App3";
webapps::AppId app_id3 =
InstallPWAWithName(&profile2, example_url3, app_name3);
auto example_url4 = GURL("https://www.example_four.com");
std::string app_name4 = "A Test Web App4";
webapps::AppId app_id4 =
InstallPWAWithName(&profile2, example_url4, app_name4);
// Launch web apps for the two profiles.
Browser* app_browser1 =
web_app::LaunchWebAppBrowserAndWait(profile1, app_id1);
Browser* app_browser2 =
web_app::LaunchWebAppBrowserAndWait(&profile2, app_id3);
ASSERT_NE(app_browser1, nullptr);
ASSERT_NE(app_browser2, nullptr);
// Expected installed apps for given profile in JSON format as a raw string.
// This is short so it is easier to just directly embed it versus using a
// separate golden file.
// NOTE: The output format uses an indent of 3 spaces and a trailing newline.
std::string expected_info = R"({
"installed_web_apps": [ {
"profile_id": "New Profile 1",
"web_apps": [ {
"id": "dhjmdeeglmiagclobghjoaodgfhkjhgb",
"name": "A Test Web App3"
}, {
"id": "ifgmomgfhabbbbapaeolfmaoamipmegf",
"name": "A Test Web App4"
} ]
} ],
"open_web_apps": [ {
"profile_id": "New Profile 1",
"web_apps": [ {
"id": "dhjmdeeglmiagclobghjoaodgfhkjhgb",
"name": "A Test Web App3"
} ]
} ]
}
)";
// Extract actual output using command-line flag.
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
base::FilePath output_path =
user_data_dir.Append(FILE_PATH_LITERAL("AppsForGivenProfile.json"));
command_line.AppendSwitchPath(switches::kListApps, output_path);
command_line.AppendSwitchASCII(switches::kProfileBaseName, "New Profile 1");
ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl(
command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo,
{browser()->profile(), StartupProfileMode::kBrowserWindow}, {}));
CloseBrowserSynchronously(app_browser1);
CloseBrowserSynchronously(app_browser2);
CloseBrowserSynchronously(browser());
content::RunAllTasksUntilIdle();
{
base::ScopedAllowBlockingForTesting allow_blocking;
std::string file_contents;
ASSERT_TRUE(base::ReadFileToString(output_path, &file_contents));
// Normalize Windows line endings to Linux line endings used by golden data.
base::ReplaceSubstringsAfterOffset(&file_contents, 0, "\r\n", "\n");
ASSERT_EQ(expected_info, file_contents);
}
}
#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
#if !BUILDFLAG(IS_CHROMEOS)
webapps::AppId InstallPWA(Profile* profile, const GURL& start_url) {
auto web_app_info =
web_app::WebAppInstallInfo::CreateWithStartUrlForTesting(start_url);
web_app_info->scope = start_url.GetWithoutFilename();
web_app_info->user_display_mode =
web_app::mojom::UserDisplayMode::kStandalone;
web_app_info->title = u"A Web App";
return web_app::test::InstallWebApp(profile, std::move(web_app_info));
}
class StartupBrowserCreatorRestartTest : public StartupBrowserCreatorTest,
public BrowserListObserver {
protected:
StartupBrowserCreatorRestartTest() { BrowserList::AddObserver(this); }
~StartupBrowserCreatorRestartTest() override {
// We might have already been removed but it's safe to call again.
BrowserList::RemoveObserver(this);
}
void SetUpInProcessBrowserTestFixture() override {
std::string_view test_name =
::testing::UnitTest::GetInstance()->current_test_info()->name();
if (base::StartsWith(test_name, "PRE_")) {
// The PRE_ test will call chrome::AttemptRestart().
mock_relaunch_callback_ = std::make_unique<::testing::StrictMock<
base::MockCallback<upgrade_util::RelaunchChromeBrowserCallback>>>();
EXPECT_CALL(*mock_relaunch_callback_, Run);
relaunch_chrome_override_ =
std::make_unique<upgrade_util::ScopedRelaunchChromeBrowserOverride>(
mock_relaunch_callback_->Get());
}
}
void OnBrowserAdded(Browser* browser) override {
std::string_view test_name =
::testing::UnitTest::GetInstance()->current_test_info()->name();
// The non PRE_ test will start up as if it was restarted.
// Check that, then remove the observer.
if (!base::StartsWith(test_name, "PRE_")) {
EXPECT_TRUE(StartupBrowserCreator::WasRestarted());
EXPECT_FALSE(browser_added_check_passed_);
browser_added_check_passed_ = true;
BrowserList::RemoveObserver(this);
}
}
bool browser_added_check_passed_ = false;
private:
web_app::OsIntegrationTestOverrideBlockingRegistration faked_os_integration_;
std::unique_ptr<
base::MockCallback<upgrade_util::RelaunchChromeBrowserCallback>>
mock_relaunch_callback_;
std::unique_ptr<upgrade_util::ScopedRelaunchChromeBrowserOverride>
relaunch_chrome_override_;
};
// Open an App and restart in preparation for the real test.
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorRestartTest,
PRE_ProfileRestartedAppRestore) {
// Ensure services are started.
Profile* test_profile = browser()->profile();
AppSessionServiceFactory::GetForProfileForSessionRestore(test_profile);
SessionStartupPref pref_last(SessionStartupPref::LAST);
SessionStartupPref::SetStartupPref(test_profile, pref_last);
// Install web app
auto example_url = GURL("https://www.example.com");
webapps::AppId app_id = InstallPWA(test_profile, example_url);
Browser* app_browser =
web_app::LaunchWebAppBrowserAndWait(test_profile, app_id);
ASSERT_NE(app_browser, nullptr);
ASSERT_EQ(app_browser->type(), Browser::Type::TYPE_APP);
ASSERT_TRUE(web_app::AppBrowserController::IsForWebApp(app_browser, app_id));
chrome::AttemptRestart();
PrefService* pref_service = g_browser_process->local_state();
EXPECT_TRUE(pref_service->GetBoolean(prefs::kWasRestarted));
}
// This test tests a specific scenario where the browser is marked as restarted
// and a SessionBrowserCreatorImpl::MaybeAsyncRestore is triggered.
// ShouldRestoreApps will return true because the profile is marked as
// restarted which will trigger apps to restore. If apps are open at this point
// and an app restore occurs, apps will be duplicated. This test ensures that
// does not occur. This test doesn't build on non app_session_service
// platforms, hence the buildflag disablement.
//
// TODO(crbug.com/401224321): Flaky on "Mac13 Tests" bot.
#if BUILDFLAG(IS_MAC) && defined(ARCH_CPU_X86_64)
#define MAYBE_ProfileRestartedAppRestore DISABLED_ProfileRestartedAppRestore
#else
#define MAYBE_ProfileRestartedAppRestore ProfileRestartedAppRestore
#endif
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorRestartTest,
MAYBE_ProfileRestartedAppRestore) {
Profile* test_profile = browser()->profile();
// StartupBrowserCreator() has already run in SetUp(), so it would already be
// reset by this point.
EXPECT_FALSE(StartupBrowserCreator::WasRestarted());
EXPECT_TRUE(browser_added_check_passed_);
// Now close the original (and last alive) tabbed browser window
// note: there is still an app open
ASSERT_EQ(2u, BrowserList::GetInstance()->size());
CloseBrowserSynchronously(browser());
ASSERT_EQ(1U, BrowserList::GetInstance()->size());
// Now hit the codepath that would get hit if someone opened chrome
// from a desktop shortcut or similar.
SessionRestoreTestHelper restore_waiter;
base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
StartupBrowserCreatorImpl creator(base::FilePath(), dummy,
chrome::startup::IsFirstRun::kNo);
creator.Launch(test_profile, chrome::startup::IsProcessStartup::kNo,
/*restore_tabbed_browser=*/true);
restore_waiter.Wait();
// We expect a browser to open, but we should NOT get a duplicate app.
// Note at this point, the profile IsRestarted() is still true.
ASSERT_EQ(2u, BrowserList::GetInstance()->size());
bool app_found = false;
bool browser_found = false;
for (Browser* browser : *(BrowserList::GetInstance())) {
if (browser->type() == Browser::Type::TYPE_APP) {
ASSERT_FALSE(app_found);
app_found = true;
} else if (browser->type() == Browser::Type::TYPE_NORMAL) {
ASSERT_FALSE(browser_found);
browser_found = true;
}
}
}
#endif // !BUILDFLAG(IS_CHROMEOS)
// An observer that returns back to test code after a new browser is added to
// the BrowserList.
class BrowserAddedObserver : public BrowserListObserver {
public:
BrowserAddedObserver() { BrowserList::AddObserver(this); }
~BrowserAddedObserver() override { BrowserList::RemoveObserver(this); }
Browser* Wait() {
run_loop_.Run();
return browser_;
}
protected:
// BrowserListObserver:
void OnBrowserAdded(Browser* browser) override {
browser_ = browser;
run_loop_.Quit();
}
private:
raw_ptr<Browser> browser_ = nullptr;
base::RunLoop run_loop_;
};
class StartupBrowserWithWebAppTest : public StartupBrowserCreatorTest {
protected:
void SetUpCommandLine(base::CommandLine* command_line) override {
StartupBrowserCreatorTest::SetUpCommandLine(command_line);
if (GetTestPreCount() == 1) {
// Load an app with launch.container = 'window'.
#if BUILDFLAG(IS_MAC)
// While the non-mac version of this test would pass on macOS, it isn't
// testing a code path that would actually be used on macOS, and thus not
// very useful as a test. Instead test the way an app shim would launch
// Chrome in the background to launch an app.
command_line->AppendSwitch(switches::kNoStartupWindow);
#else
command_line->AppendSwitchASCII(switches::kAppId, kAppId);
command_line->AppendSwitchASCII(switches::kProfileDirectory, "Default");
#endif
}
}
WebAppProvider& provider() { return *WebAppProvider::GetForTest(profile()); }
base::test::ScopedFeatureList scoped_feature_list_;
web_app::OsIntegrationTestOverrideBlockingRegistration faked_os_integration_;
};
IN_PROC_BROWSER_TEST_F(StartupBrowserWithWebAppTest,
PRE_PRE_LastUsedProfilesWithWebApp) {
// Simulate a browser restart by creating the profiles in the PRE_PRE part.
ProfileManager* profile_manager = g_browser_process->profile_manager();
ASSERT_TRUE(embedded_test_server()->Start());
// Create two profiles.
base::FilePath dest_path = profile_manager->user_data_dir();
Profile& profile1 = profiles::testing::CreateProfileSync(
profile_manager, dest_path.Append(FILE_PATH_LITERAL("New Profile 1")));
Profile& profile2 = profiles::testing::CreateProfileSync(
profile_manager, dest_path.Append(FILE_PATH_LITERAL("New Profile 2")));
DisableWhatsNewPage();
// Open some urls with the browsers, and close them.
Browser* browser1 = Browser::Create({Browser::TYPE_NORMAL, &profile1, true});
chrome::NewTab(browser1);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser1, embedded_test_server()->GetURL("/title1.html")));
Browser* browser2 = Browser::Create({Browser::TYPE_NORMAL, &profile2, true});
chrome::NewTab(browser2);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser2, embedded_test_server()->GetURL("/title2.html")));
// Set startup preferences for the 2 profiles to restore last session.
SessionStartupPref pref1(SessionStartupPref::LAST);
SessionStartupPref::SetStartupPref(&profile1, pref1);
SessionStartupPref pref2(SessionStartupPref::LAST);
SessionStartupPref::SetStartupPref(&profile2, pref2);
profile1.GetPrefs()->CommitPendingWrite();
profile2.GetPrefs()->CommitPendingWrite();
// Install a web app that we will launch from the command line in
// the PRE test.
WebAppProvider* const provider =
WebAppProvider::GetForTest(browser()->profile());
// Install web app set to open as a standalone window.
{
std::unique_ptr<web_app::WebAppInstallInfo> info =
web_app::WebAppInstallInfo::CreateWithStartUrlForTesting(
GURL(kStartUrl));
info->title = kAppName;
info->user_display_mode = web_app::mojom::UserDisplayMode::kStandalone;
base::test::TestFuture<const webapps::AppId&, webapps::InstallResultCode>
result;
provider->scheduler().InstallFromInfoWithParams(
std::move(info), /*overwrite_existing_manifest_fields=*/true,
webapps::WebappInstallSource::OMNIBOX_INSTALL_ICON,
result.GetCallback(), web_app::WebAppInstallParams());
EXPECT_EQ(result.Get<webapps::AppId>(), kAppId);
EXPECT_EQ(result.Get<webapps::InstallResultCode>(),
webapps::InstallResultCode::kSuccessNewInstall);
EXPECT_EQ(provider->registrar_unsafe().GetAppUserDisplayMode(kAppId),
web_app::mojom::UserDisplayMode::kStandalone);
#if BUILDFLAG(IS_MAC)
AppShimRegistry::Get()->OnAppInstalledForProfile(
kAppId, browser()->profile()->GetPath());
#endif
}
}
IN_PROC_BROWSER_TEST_F(StartupBrowserWithWebAppTest,
PRE_LastUsedProfilesWithWebApp) {
{
BrowserAddedObserver added_observer;
#if BUILDFLAG(IS_MAC)
// Simulate an app shim connecting and launching an app.
apps::AppShimManager::Get()->LoadAndLaunchAppForTesting(kAppId);
#endif
content::RunAllTasksUntilIdle();
// Launching with an app opens the app window via a task, so the test
// might start before SelectFirstBrowser is called.
if (!browser()) {
added_observer.Wait();
SelectFirstBrowser();
}
}
ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile()));
// An app window should have been launched.
EXPECT_TRUE(browser()->is_type_app());
CloseBrowserSynchronously(browser());
}
// TODO(crbug.com/327256043): Flaky on win
#if BUILDFLAG(IS_WIN)
#define MAYBE_LastUsedProfilesWithWebApp DISABLED_LastUsedProfilesWithWebApp
#else
#define MAYBE_LastUsedProfilesWithWebApp LastUsedProfilesWithWebApp
#endif
IN_PROC_BROWSER_TEST_F(StartupBrowserWithWebAppTest,
MAYBE_LastUsedProfilesWithWebApp) {
ProfileManager* profile_manager = g_browser_process->profile_manager();
base::FilePath dest_path = profile_manager->user_data_dir();
Profile& profile1 = profiles::testing::CreateProfileSync(
profile_manager, dest_path.Append(FILE_PATH_LITERAL("New Profile 1")));
Profile& profile2 = profiles::testing::CreateProfileSync(
profile_manager, dest_path.Append(FILE_PATH_LITERAL("New Profile 2")));
while (SessionRestore::IsRestoring(&profile1) ||
SessionRestore::IsRestoring(&profile2)) {
base::RunLoop().RunUntilIdle();
}
// The last open sessions should be restored.
EXPECT_TRUE(profile1.restored_last_session());
EXPECT_TRUE(profile2.restored_last_session());
Browser* new_browser = nullptr;
ASSERT_EQ(1u, chrome::GetBrowserCount(&profile1));
new_browser = FindOneOtherBrowserForProfile(&profile1, nullptr);
ASSERT_TRUE(new_browser);
TabStripModel* tab_strip = new_browser->tab_strip_model();
EXPECT_EQ("/title1.html",
tab_strip->GetWebContentsAt(0)->GetLastCommittedURL().path());
ASSERT_EQ(1u, chrome::GetBrowserCount(&profile2));
new_browser = FindOneOtherBrowserForProfile(&profile2, nullptr);
ASSERT_TRUE(new_browser);
tab_strip = new_browser->tab_strip_model();
EXPECT_EQ("/title2.html",
tab_strip->GetWebContentsAt(0)->GetLastCommittedURL().path());
}
class StartupBrowserCreatorTestWithGuestParam
: public StartupBrowserCreatorTest,
public testing::WithParamInterface<bool> {
public:
bool IsGuest() const { return GetParam(); }
GURL GetTestURL() const { return GURL("https://www.youtube.com"); }
// Creates a browser for a new profile (which may be Guest, based on
// `IsGuest()`).
Browser* CreateBrowser() {
if (IsGuest()) {
profiles::SwitchToGuestProfile();
} else {
base::FilePath profile_path = g_browser_process->profile_manager()
->GenerateNextProfileDirectoryPath();
profiles::SwitchToProfile(profile_path, /*always_create=*/true);
}
Browser* test_browser = ui_test_utils::WaitForBrowserToOpen();
profiles::SetLastUsedProfile(test_browser->profile()->GetBaseName());
return test_browser;
}
void OpenTabAlreadyRunning() {
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendArg(GetTestURL().spec());
ChromeBrowserMainParts::ProcessSingletonNotificationCallback(
command_line, /*current_directory=*/{});
}
};
// Tests that receiving a launch notification while Chrome is already running
// opens the URL in the current browser window.
IN_PROC_BROWSER_TEST_P(StartupBrowserCreatorTestWithGuestParam,
ProcessCommandLineAlreadyRunning) {
ScopedKeepAlive keep_alive(KeepAliveOrigin::BACKGROUND_MODE_MANAGER,
KeepAliveRestartOption::DISABLED);
CloseBrowserSynchronously(browser());
// Create a browser for a new profile.
Browser* test_browser = CreateBrowser();
ASSERT_TRUE(test_browser);
ASSERT_EQ(test_browser->profile()->IsGuestSession(), IsGuest());
TabStripModel* tab_strip = test_browser->tab_strip_model();
int initial_tab_count = tab_strip->count();
// Open a URL while a browser is already open.
ui_test_utils::AllBrowserTabAddedWaiter tab_waiter;
OpenTabAlreadyRunning();
content::WebContents* contents = tab_waiter.Wait();
EXPECT_EQ(initial_tab_count + 1, tab_strip->count());
EXPECT_EQ(contents, tab_strip->GetWebContentsAt(tab_strip->count() - 1));
EXPECT_EQ(GetTestURL(), contents->GetVisibleURL());
}
// Tests that receiving a launch notification while Chrome is already running,
// but there was no browser window, reopens the last profile if it was regular,
// and opens the profile picker if it was guest.
IN_PROC_BROWSER_TEST_P(StartupBrowserCreatorTestWithGuestParam,
ProcessCommandLineAlreadyRunningAfterBrowserClose) {
ScopedKeepAlive keep_alive(KeepAliveOrigin::BACKGROUND_MODE_MANAGER,
KeepAliveRestartOption::DISABLED);
CloseBrowserSynchronously(browser());
ProfileManager* profile_manager = g_browser_process->profile_manager();
// Create a browser for a new profile.
Browser* test_browser = CreateBrowser();
Profile* last_profile = test_browser->profile();
ASSERT_TRUE(test_browser);
ASSERT_EQ(last_profile->IsGuestSession(), IsGuest());
std::unique_ptr<ScopedProfileKeepAlive> profile_keep_alive;
if (!IsGuest()) {
// Keep the profile alive to avoid unloading and immediately reloading it,
// which causes some flakiness within the HistoryService.
// This is not done for the guest profile because:
// - the test scenario does not involve reloading the guest profile,
// - it is not allowed to take a keep alive on a OTR profile.
profile_keep_alive = std::make_unique<ScopedProfileKeepAlive>(
last_profile, ProfileKeepAliveOrigin::kBackgroundMode);
}
CloseBrowserSynchronously(test_browser);
// Closing the browser did not change the last used profile.
EXPECT_EQ(profile_manager->GetLastUsedProfileDir(), last_profile->GetPath());
ASSERT_FALSE(ProfilePicker::IsOpen());
// Open a URL after the last active browser was closed.
OpenTabAlreadyRunning();
if (IsGuest()) {
// The profile picker opens. There is no browser, the URL is not loaded.
profiles::testing::WaitForPickerWidgetCreated();
EXPECT_EQ(0u, BrowserList::GetInstance()->size());
} else {
// The last used profile is reopened and the URL is loaded.
Browser* browser = ui_test_utils::WaitForBrowserToOpen();
Profile* profile = browser->profile();
EXPECT_FALSE(profile->IsGuestSession());
TabStripModel* tab_strip = browser->tab_strip_model();
EXPECT_EQ(
tab_strip->GetWebContentsAt(tab_strip->count() - 1)->GetVisibleURL(),
GetTestURL());
EXPECT_FALSE(ProfilePicker::IsOpen());
EXPECT_EQ(1u, BrowserList::GetInstance()->size());
EXPECT_EQ(last_profile, profile);
}
}
INSTANTIATE_TEST_SUITE_P(,
StartupBrowserCreatorTestWithGuestParam,
testing::Bool());
class StartupBrowserWithRealWebAppTest : public StartupBrowserCreatorTest {
protected:
StartupBrowserWithRealWebAppTest() = default;
void SetUpCommandLine(base::CommandLine* command_line) override {}
WebAppProvider& provider() { return *WebAppProvider::GetForTest(profile()); }
private:
web_app::OsIntegrationTestOverrideBlockingRegistration faked_os_integration_;
};
IN_PROC_BROWSER_TEST_F(StartupBrowserWithRealWebAppTest,
PRE_PRE_LastUsedProfilesWithRealWebApp) {
ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile()));
// Simulate a browser restart by creating the profiles in the PRE_PRE part.
ProfileManager* profile_manager = g_browser_process->profile_manager();
ASSERT_TRUE(embedded_https_test_server().Start());
// Create a profile.
base::FilePath dest_path = profile_manager->user_data_dir();
Profile& profile1 = profiles::testing::CreateProfileSync(
profile_manager, dest_path.Append(FILE_PATH_LITERAL("New Profile 1")));
DisableWhatsNewPage();
// Open some urls with the browsers, and close them.
SessionServiceFactory::GetForProfileForSessionRestore(&profile1);
Browser* browser1 = Browser::Create({Browser::TYPE_NORMAL, &profile1, true});
chrome::NewTab(browser1);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser1, embedded_https_test_server().GetURL("/title1.html")));
browser1->window()->Show();
browser1->window()->Maximize();
// Set startup preferences to restore last session.
SessionStartupPref pref1(SessionStartupPref::LAST);
SessionStartupPref::SetStartupPref(&profile1, pref1);
profile1.GetPrefs()->CommitPendingWrite();
SessionStartupPref::SetStartupPref(browser()->profile(), pref1);
browser()->profile()->GetPrefs()->CommitPendingWrite();
ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile()));
ASSERT_EQ(1u, chrome::GetBrowserCount(&profile1));
ASSERT_EQ(2u, BrowserList::GetInstance()->size());
}
IN_PROC_BROWSER_TEST_F(StartupBrowserWithRealWebAppTest,
PRE_LastUsedProfilesWithRealWebApp) {
ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile()));
ProfileManager* profile_manager = g_browser_process->profile_manager();
base::FilePath dest_path = profile_manager->user_data_dir();
Profile& profile1 = profiles::testing::CreateProfileSync(
profile_manager, dest_path.Append(FILE_PATH_LITERAL("New Profile 1")));
auto example_url = GURL("https://www.example.com");
webapps::AppId new_app_id = InstallPWA(&profile1, example_url);
Browser* app = web_app::LaunchWebAppBrowserAndWait(&profile1, new_app_id);
ASSERT_TRUE(app);
// destroy session services so we don't record this closure.
// This simulates a user choosing ... -> Exit Chromium.
for (auto* profile : profile_manager->GetLoadedProfiles()) {
// Don't construct SessionServices for every type just to
// shut them down. If they were never created, just skip.
if (SessionServiceFactory::GetForProfileIfExisting(profile)) {
SessionServiceFactory::ShutdownForProfile(profile);
}
if (AppSessionServiceFactory::GetForProfileIfExisting(profile)) {
AppSessionServiceFactory::ShutdownForProfile(profile);
}
}
ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile()));
ASSERT_EQ(2u, chrome::GetBrowserCount(&profile1));
// On ozone-linux, for some reason, these profile 1 windows come back in
// the next test. To reliably ensure they don't, but don't destroy the
// session restore state, close them while the session services are shutdown.
Browser* close_this = FindOneOtherBrowserForProfile(&profile1, app);
CloseBrowserSynchronously(close_this);
CloseBrowserSynchronously(app);
}
#if BUILDFLAG(IS_MAC)
#define MAYBE_LastUsedProfilesWithRealWebApp \
DISABLED_LastUsedProfilesWithRealWebApp
#else
#define MAYBE_LastUsedProfilesWithRealWebApp LastUsedProfilesWithRealWebApp
#endif
// TODO(stahon@microsoft.com) App restores are disabled on mac.
// see http://crbug.com/1194201
IN_PROC_BROWSER_TEST_F(StartupBrowserWithRealWebAppTest,
MAYBE_LastUsedProfilesWithRealWebApp) {
// Make StartupBrowserCreator::WasRestarted() return true.
StartupBrowserCreator::was_restarted_read_ = false;
PrefService* pref_service = g_browser_process->local_state();
pref_service->SetBoolean(prefs::kWasRestarted, true);
ASSERT_TRUE(StartupBrowserCreator::WasRestarted());
ProfileManager* profile_manager = g_browser_process->profile_manager();
base::FilePath dest_path = profile_manager->user_data_dir();
Profile& profile1 = profiles::testing::CreateProfileSync(
profile_manager, dest_path.Append(FILE_PATH_LITERAL("New Profile 1")));
Profile& default_profile = profiles::testing::CreateProfileSync(
profile_manager, dest_path.Append(FILE_PATH_LITERAL("Default")));
// At this point, nothing is open except the basic browser.
ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile()));
ASSERT_EQ(1u, BrowserList::GetInstance()->size());
// Trigger the restore via StartupBrowserCreator.
base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
StartupBrowserCreatorImpl launch(base::FilePath(), dummy,
chrome::startup::IsFirstRun::kNo);
// Fake |process_startup| true.
launch.Launch(&profile1, chrome::startup::IsProcessStartup::kYes,
/*restore_tabbed_browser=*/true);
// We should get two windows from profile1.
ASSERT_EQ(3u, BrowserList::GetInstance()->size());
ASSERT_EQ(1u, chrome::GetBrowserCount(&default_profile));
ASSERT_EQ(2u, chrome::GetBrowserCount(&profile1));
while (SessionRestore::IsRestoring(&profile1)) {
base::RunLoop().RunUntilIdle();
}
// Since there's one app being restored, ensure the provider is ready.
WebAppProvider* provider = WebAppProvider::GetForTest(&profile1);
ASSERT_TRUE(provider->on_registry_ready().is_signaled());
// The last open sessions should be restored.
EXPECT_TRUE(profile1.restored_last_session());
Browser* new_browser = nullptr;
// 2x profile1, 1x default profile here.
ASSERT_EQ(3u, BrowserList::GetInstance()->size());
ASSERT_EQ(2u, chrome::GetBrowserCount(&profile1));
ASSERT_EQ(1u, chrome::GetBrowserCount(&default_profile));
new_browser = FindOneOtherBrowserForProfile(&profile1, nullptr);
if (new_browser->type() != Browser::Type::TYPE_NORMAL) {
new_browser = FindOneOtherBrowserForProfile(&profile1, new_browser);
}
ASSERT_TRUE(new_browser);
EXPECT_EQ(new_browser->type(), Browser::Type::TYPE_NORMAL);
TabStripModel* tab_strip = new_browser->tab_strip_model();
EXPECT_EQ("/title1.html",
tab_strip->GetWebContentsAt(0)->GetLastCommittedURL().path());
// Now get the app, it should just be the other browser from this profile.
new_browser = FindOneOtherBrowserForProfile(&profile1, new_browser);
ASSERT_EQ(new_browser->type(), Browser::Type::TYPE_APP);
}
#endif // !BUILDFLAG(IS_CHROMEOS)
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
class StartupBrowserWebAppProtocolHandlingTest : public InProcessBrowserTest {
protected:
StartupBrowserWebAppProtocolHandlingTest() = default;
void SetUpOnMainThread() override {
InProcessBrowserTest::SetUpOnMainThread();
}
WebAppProvider* provider() {
return WebAppProvider::GetForTest(browser()->profile());
}
// Install a web app with `protocol_handlers` (and optionally `file_handlers`)
// then register it with the ProtocolHandlerRegistry. This is sufficient for
// testing URL translation and launch at startup.
webapps::AppId InstallWebAppWithProtocolHandlers(
const std::vector<apps::ProtocolHandlerInfo>& protocol_handlers,
const std::vector<apps::FileHandler>& file_handlers = {}) {
std::unique_ptr<web_app::WebAppInstallInfo> info =
web_app::WebAppInstallInfo::CreateWithStartUrlForTesting(
GURL(kStartUrl));
info->title = kAppName;
info->user_display_mode = web_app::mojom::UserDisplayMode::kStandalone;
info->protocol_handlers = protocol_handlers;
info->file_handlers = file_handlers;
webapps::AppId app_id =
web_app::test::InstallWebApp(browser()->profile(), std::move(info));
return app_id;
}
void SetUpCommandlineAndStart(const std::string& url,
const webapps::AppId& app_id) {
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendArg(url);
command_line.AppendSwitchASCII(switches::kAppId, app_id);
std::vector<Profile*> last_opened_profiles;
StartupBrowserCreator browser_creator;
browser_creator.Start(
command_line, g_browser_process->profile_manager()->user_data_dir(),
{browser()->profile(), StartupProfileMode::kBrowserWindow},
last_opened_profiles);
}
private:
web_app::OsIntegrationTestOverrideBlockingRegistration faked_os_integration_;
base::test::ScopedFeatureList scoped_feature_list_;
#if BUILDFLAG(IS_WIN)
// This is needed to stop StartupBrowserWebAppProtocolHandlingTests creating a
// shortcut in the Windows start menu. The override needs to last until the
// test is destroyed, because Windows shortcut tasks which create the shortcut
// can run after the test body returns.
base::ScopedPathOverride override_start_dir{base::DIR_START_MENU};
#endif // BUILDFLAG(IS_WIN)
};
IN_PROC_BROWSER_TEST_F(
StartupBrowserWebAppProtocolHandlingTest,
WebAppLaunch_WebAppIsNotLaunchedWithProtocolUrlAndDialogCancel) {
views::NamedWidgetShownWaiter waiter(views::test::AnyWidgetTestPasskey{},
"ProtocolHandlerLaunchDialogView");
// Register web app as a protocol handler that should handle the launch.
apps::ProtocolHandlerInfo protocol_handler;
const std::string handler_url = std::string(kStartUrl) + "/testing=%s";
protocol_handler.url = GURL(handler_url);
protocol_handler.protocol = "web+test";
webapps::AppId app_id = InstallWebAppWithProtocolHandlers({protocol_handler});
// Launch the browser via a command line with a handled protocol URL param.
SetUpCommandlineAndStart("web+test://parameterString", app_id);
// The waiter will get the dialog when it shows up and close it.
waiter.WaitIfNeededAndGet()->CloseWithReason(
views::Widget::ClosedReason::kEscKeyPressed);
// Check that no extra window is launched.
ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile()));
}
IN_PROC_BROWSER_TEST_F(
StartupBrowserWebAppProtocolHandlingTest,
WebAppLaunch_WebAppIsLaunchedWithProtocolUrlAndDialogAccept) {
views::NamedWidgetShownWaiter waiter(views::test::AnyWidgetTestPasskey{},
"ProtocolHandlerLaunchDialogView");
// Register web app as a protocol handler that should handle the launch.
apps::ProtocolHandlerInfo protocol_handler;
const std::string handler_url = std::string(kStartUrl) + "/testing=%s";
protocol_handler.url = GURL(handler_url);
protocol_handler.protocol = "web+test";
webapps::AppId app_id = InstallWebAppWithProtocolHandlers({protocol_handler});
bool allowed_protocols_notified = false;
web_app::WebAppTestRegistryObserverAdapter observer(browser()->profile());
observer.SetWebAppProtocolSettingsChangedDelegate(
base::BindLambdaForTesting([&]() { allowed_protocols_notified = true; }));
web_app::ProtocolHandlerLaunchDialogView::
SetDefaultRememberSelectionForTesting(true);
// Launch the browser via a command line with a handled protocol URL param.
SetUpCommandlineAndStart("web+test://parameterString", app_id);
// The waiter will get the dialog when it shows up and accepts it.
waiter.WaitIfNeededAndGet()->CloseWithReason(
views::Widget::ClosedReason::kAcceptButtonClicked);
web_app::ProtocolHandlerLaunchDialogView::
SetDefaultRememberSelectionForTesting(false);
// Wait for app launch task to complete.
content::RunAllTasksUntilIdle();
// Check that we added this protocol to web app's allowed_launch_protocols
// on accept.
web_app::WebAppRegistrar& registrar = provider()->registrar_unsafe();
EXPECT_TRUE(registrar.IsAllowedLaunchProtocol(app_id, "web+test"));
EXPECT_TRUE(allowed_protocols_notified);
// Check for new app window.
ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile()));
Browser* app_browser;
app_browser = FindOneOtherBrowser(browser());
ASSERT_TRUE(app_browser);
EXPECT_TRUE(web_app::AppBrowserController::IsForWebApp(app_browser, app_id));
// Check the app is launched with the correctly translated URL.
TabStripModel* tab_strip = app_browser->tab_strip_model();
ASSERT_EQ(1, tab_strip->count());
content::WebContents* web_contents = tab_strip->GetWebContentsAt(0);
EXPECT_EQ("https://test.com/testing=web%2Btest%3A%2F%2FparameterString",
web_contents->GetVisibleURL());
}
IN_PROC_BROWSER_TEST_F(
StartupBrowserWebAppProtocolHandlingTest,
WebAppLaunch_WebAppIsNotTranslatedWithUnhandledProtocolUrl) {
// Register web app as a protocol handler that should *not* handle the launch.
apps::ProtocolHandlerInfo protocol_handler;
const std::string handler_url = std::string(kStartUrl) + "/testing=%s";
protocol_handler.url = GURL(handler_url);
protocol_handler.protocol = "web+test";
webapps::AppId app_id = InstallWebAppWithProtocolHandlers({protocol_handler});
// Launch the browser via a command line with an unhandled protocol URL param.
SetUpCommandlineAndStart("web+unhandled://parameterString", app_id);
// Wait for app launch task to complete.
content::RunAllTasksUntilIdle();
// Check an app window is launched.
ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile()));
Browser* app_browser;
app_browser = FindOneOtherBrowser(browser());
ASSERT_TRUE(app_browser);
EXPECT_TRUE(web_app::AppBrowserController::IsForWebApp(app_browser, app_id));
// Check the app is launched to the home page and not the translated URL.
TabStripModel* tab_strip = app_browser->tab_strip_model();
ASSERT_EQ(1, tab_strip->count());
content::WebContents* web_contents = tab_strip->GetWebContentsAt(0);
EXPECT_EQ(GURL(kStartUrl), web_contents->GetVisibleURL());
}
IN_PROC_BROWSER_TEST_F(
StartupBrowserWebAppProtocolHandlingTest,
WebAppLaunch_WebAppIsLaunchedWithAllowedProtocolUrlPref) {
views::NamedWidgetShownWaiter waiter(views::test::AnyWidgetTestPasskey{},
"ProtocolHandlerLaunchDialogView");
// Register web app as a protocol handler that should handle the launch.
apps::ProtocolHandlerInfo protocol_handler;
const std::string handler_url = std::string(kStartUrl) + "/testing=%s";
protocol_handler.url = GURL(handler_url);
protocol_handler.protocol = "web+test";
webapps::AppId app_id = InstallWebAppWithProtocolHandlers({protocol_handler});
web_app::ProtocolHandlerLaunchDialogView::
SetDefaultRememberSelectionForTesting(true);
// Launch the browser via a command line with a handled protocol URL param.
SetUpCommandlineAndStart("web+test://parameterString", app_id);
// The waiter will get the dialog when it shows up and accepts it.
waiter.WaitIfNeededAndGet()->CloseWithReason(
views::Widget::ClosedReason::kAcceptButtonClicked);
web_app::ProtocolHandlerLaunchDialogView::
SetDefaultRememberSelectionForTesting(false);
// Wait for app launch task to complete and launches a new browser.
ui_test_utils::WaitForBrowserToOpen();
// Check that we added this protocol to web app's allowed_launch_protocols
// on accept.
web_app::WebAppRegistrar& registrar = provider()->registrar_unsafe();
EXPECT_TRUE(registrar.IsAllowedLaunchProtocol(app_id, "web+test"));
// Check the first app window is created.
ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile()));
Browser* app_browser1;
app_browser1 = FindOneOtherBrowser(browser());
ASSERT_TRUE(app_browser1);
// Launch the browser via a command line with an handled protocol URL
// param, but this time we expect the permission dialog to not show up.
SetUpCommandlineAndStart("web+test://parameterString", app_id);
// Wait for app launch task to complete and launches a new browser.
ui_test_utils::WaitForBrowserToOpen();
// Check the second app window is launched directly this time. The dialog
// is skipped because we have the allowed protocol scheme for the same
// app launch.
Browser* app_browser2;
// There should be 3 browser windows opened at the moment.
ASSERT_EQ(3u, chrome::GetBrowserCount(browser()->profile()));
for (Browser* b : *BrowserList::GetInstance()) {
if (b != browser() && b != app_browser1) {
app_browser2 = b;
}
}
ASSERT_TRUE(app_browser2);
EXPECT_TRUE(web_app::AppBrowserController::IsForWebApp(app_browser2, app_id));
// Check the app is launched with the correctly translated URL.
TabStripModel* tab_strip = app_browser2->tab_strip_model();
ASSERT_EQ(1, tab_strip->count());
content::WebContents* web_contents = tab_strip->GetWebContentsAt(0);
EXPECT_EQ("https://test.com/testing=web%2Btest%3A%2F%2FparameterString",
web_contents->GetVisibleURL());
}
IN_PROC_BROWSER_TEST_F(StartupBrowserWebAppProtocolHandlingTest,
WebAppLaunch_WebAppIsLaunchedWithAllowedProtocol) {
// Register web app as a protocol handler that should handle the launch.
apps::ProtocolHandlerInfo protocol_handler;
const std::string handler_url = std::string(kStartUrl) + "/testing=%s";
protocol_handler.url = GURL(handler_url);
protocol_handler.protocol = "web+test";
webapps::AppId app_id = InstallWebAppWithProtocolHandlers({protocol_handler});
{
views::NamedWidgetShownWaiter waiter(views::test::AnyWidgetTestPasskey{},
"ProtocolHandlerLaunchDialogView");
// Launch the browser via a command line with a handled protocol URL param.
SetUpCommandlineAndStart("web+test://parameterString", app_id);
// The waiter will get the dialog when it shows up and accepts it.
waiter.WaitIfNeededAndGet()->CloseWithReason(
views::Widget::ClosedReason::kAcceptButtonClicked);
}
// Wait for app launch task to complete and launches a new browser.
ui_test_utils::WaitForBrowserToOpen();
// Check that we did not add this protocol to web app's
// allowed_launch_protocols on accept.
web_app::WebAppRegistrar& registrar = provider()->registrar_unsafe();
EXPECT_FALSE(registrar.IsAllowedLaunchProtocol(app_id, "web+test"));
// Check the first app window is created.
ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile()));
Browser* app_browser1;
app_browser1 = FindOneOtherBrowser(browser());
ASSERT_TRUE(app_browser1);
{
views::NamedWidgetShownWaiter waiter(views::test::AnyWidgetTestPasskey{},
"ProtocolHandlerLaunchDialogView");
// Launch the browser via a command line with a handled protocol URL param.
SetUpCommandlineAndStart("web+test://parameterString", app_id);
// The waiter will get the dialog when it shows up and accepts it.
waiter.WaitIfNeededAndGet()->CloseWithReason(
views::Widget::ClosedReason::kAcceptButtonClicked);
}
// Wait for app launch task to complete and launches a new browser.
ui_test_utils::WaitForBrowserToOpen();
Browser* app_browser2;
// There should be 3 browser windows opened at the moment.
ASSERT_EQ(3u, chrome::GetBrowserCount(browser()->profile()));
for (Browser* b : *BrowserList::GetInstance()) {
if (b != browser() && b != app_browser1) {
app_browser2 = b;
}
}
ASSERT_TRUE(app_browser2);
EXPECT_TRUE(web_app::AppBrowserController::IsForWebApp(app_browser2, app_id));
// Check the app is launched with the correctly translated URL.
TabStripModel* tab_strip = app_browser2->tab_strip_model();
ASSERT_EQ(1, tab_strip->count());
content::WebContents* web_contents = tab_strip->GetWebContentsAt(0);
EXPECT_EQ("https://test.com/testing=web%2Btest%3A%2F%2FparameterString",
web_contents->GetVisibleURL());
}
IN_PROC_BROWSER_TEST_F(
StartupBrowserWebAppProtocolHandlingTest,
WebAppLaunch_WebAppIsLaunchedWithDiallowedProtocolUrlPref) {
views::NamedWidgetShownWaiter waiter(views::test::AnyWidgetTestPasskey{},
"ProtocolHandlerLaunchDialogView");
// Register web app as a protocol handler that should handle the launch.
apps::ProtocolHandlerInfo protocol_handler;
const std::string handler_url = std::string(kStartUrl) + "/testing=%s";
protocol_handler.url = GURL(handler_url);
protocol_handler.protocol = "web+test";
webapps::AppId app_id = InstallWebAppWithProtocolHandlers({protocol_handler});
web_app::ProtocolHandlerLaunchDialogView::
SetDefaultRememberSelectionForTesting(true);
// Launch the browser via a command line with a handled protocol URL param.
SetUpCommandlineAndStart("web+test://parameterString", app_id);
// The waiter will get the dialog when it shows up and accepts it.
waiter.WaitIfNeededAndGet()->CloseWithReason(
views::Widget::ClosedReason::kCancelButtonClicked);
base::RunLoop().RunUntilIdle();
web_app::ProtocolHandlerLaunchDialogView::
SetDefaultRememberSelectionForTesting(false);
// Check that we added this protocol to web app's allowed_launch_protocols
// on accept.
web_app::WebAppRegistrar& registrar = provider()->registrar_unsafe();
EXPECT_TRUE(registrar.IsDisallowedLaunchProtocol(app_id, "web+test"));
// Check the no app window is created.
ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile()));
}
IN_PROC_BROWSER_TEST_F(
StartupBrowserWebAppProtocolHandlingTest,
WebAppLaunch_WebAppIsLaunchedWithDisallowedOnceProtocol) {
// Register web app as a protocol handler that should handle the launch.
apps::ProtocolHandlerInfo protocol_handler;
const std::string handler_url = std::string(kStartUrl) + "/testing=%s";
protocol_handler.url = GURL(handler_url);
protocol_handler.protocol = "web+test";
webapps::AppId app_id = InstallWebAppWithProtocolHandlers({protocol_handler});
{
views::NamedWidgetShownWaiter waiter(views::test::AnyWidgetTestPasskey{},
"ProtocolHandlerLaunchDialogView");
// Launch the browser via a command line with a handled protocol URL param.
SetUpCommandlineAndStart("web+test://parameterString", app_id);
// The waiter will get the dialog when it shows up and cancels it.
waiter.WaitIfNeededAndGet()->CloseWithReason(
views::Widget::ClosedReason::kCancelButtonClicked);
}
// Check that we did not add this protocol to web app's
// allowed_launch_protocols on accept.
web_app::WebAppRegistrar& registrar = provider()->registrar_unsafe();
EXPECT_FALSE(registrar.IsDisallowedLaunchProtocol(app_id, "web+test"));
// Check the no app window is created.
ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile()));
{
views::NamedWidgetShownWaiter waiter(views::test::AnyWidgetTestPasskey{},
"ProtocolHandlerLaunchDialogView");
// Launch the browser via a command line with a handled protocol URL param.
SetUpCommandlineAndStart("web+test://parameterString", app_id);
// The waiter will get the dialog when it shows up and accepts it.
waiter.WaitIfNeededAndGet()->CloseWithReason(
views::Widget::ClosedReason::kCancelButtonClicked);
}
// There should be only 1 browser window opened at the moment.
ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile()));
}
class StartupBrowserWebAppProtocolAndFileHandlingTest
: public StartupBrowserWebAppProtocolHandlingTest {
base::test::ScopedFeatureList feature_list_{
blink::features::kFileHandlingAPI};
};
// Verifies that a "file://" URL on the command line is treated as a file
// handling launch, not a protocol handling or URL launch.
IN_PROC_BROWSER_TEST_F(StartupBrowserWebAppProtocolAndFileHandlingTest,
WebAppLaunch_FileProtocol) {
// Install an app with protocol handlers and a handler for plain text files.
apps::ProtocolHandlerInfo protocol_handler;
const std::string handler_url = std::string(kStartUrl) + "/protocol=%s";
protocol_handler.url = GURL(handler_url);
protocol_handler.protocol = "web+test";
apps::FileHandler file_handler;
file_handler.action = GURL(std::string(kStartUrl) + "/file_handler");
file_handler.accept.emplace_back();
file_handler.accept.back().mime_type = "text/plain";
file_handler.accept.back().file_extensions = {".txt"};
webapps::AppId app_id =
InstallWebAppWithProtocolHandlers({protocol_handler}, {file_handler});
// Skip the file handler dialog by simulating prior user approval of the API.
provider()->sync_bridge_unsafe().SetAppFileHandlerApprovalState(
app_id, web_app::ApiApprovalState::kAllowed);
// Pass a file:// url on the command line.
SetUpCommandlineAndStart("file:///C:/test.txt", app_id);
// Wait for app launch task to complete.
content::RunAllTasksUntilIdle();
// Check an app window is launched.
ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile()));
Browser* app_browser = FindOneOtherBrowser(browser());
ASSERT_TRUE(app_browser);
EXPECT_TRUE(web_app::AppBrowserController::IsForWebApp(app_browser, app_id));
// Check the app is launched to the file handler URL and not the protocol URL.
TabStripModel* tab_strip = app_browser->tab_strip_model();
ASSERT_EQ(1, tab_strip->count());
content::WebContents* web_contents = tab_strip->GetWebContentsAt(0);
EXPECT_EQ(file_handler.action, web_contents->GetVisibleURL());
app_browser->window()->Close();
ui_test_utils::WaitForBrowserToClose(app_browser);
}
#endif // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
// These tests are not applicable to Chrome OS as neither initial preferences
// nor the onboarding promos exist there.
#if !BUILDFLAG(IS_CHROMEOS)
class StartupBrowserCreatorFirstRunTest : public InProcessBrowserTest {
public:
StartupBrowserCreatorFirstRunTest() = default;
StartupBrowserCreatorFirstRunTest(const StartupBrowserCreatorFirstRunTest&) =
delete;
StartupBrowserCreatorFirstRunTest& operator=(
const StartupBrowserCreatorFirstRunTest&) = delete;
protected:
void SetUpCommandLine(base::CommandLine* command_line) override;
void SetUpInProcessBrowserTestFixture() override;
testing::NiceMock<policy::MockConfigurationPolicyProvider> provider_;
policy::PolicyMap policy_map_;
};
void StartupBrowserCreatorFirstRunTest::SetUpCommandLine(
base::CommandLine* command_line) {
command_line->AppendSwitch(switches::kForceFirstRun);
}
void StartupBrowserCreatorFirstRunTest::SetUpInProcessBrowserTestFixture() {
// TODO(crbug.com/382086296): Confirm IS_CHROMEOS is needed here.
#if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && \
BUILDFLAG(GOOGLE_CHROME_BRANDING)
// Set a policy that prevents the first-run dialog from being shown.
policy_map_.Set(
#if BUILDFLAG(IS_CHROMEOS)
policy::key::kDeviceMetricsReportingEnabled,
#else
policy::key::kMetricsReportingEnabled,
#endif
policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER,
policy::POLICY_SOURCE_CLOUD, base::Value(false), nullptr);
provider_.UpdateChromePolicy(policy_map_);
#endif // (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) &&
// BUILDFLAG(GOOGLE_CHROME_BRANDING)
provider_.SetDefaultReturns(/*is_initialization_complete_return=*/true,
/*is_first_policy_load_complete_return=*/true);
policy::BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
}
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorFirstRunTest, AddFirstRunTabs) {
ASSERT_TRUE(embedded_test_server()->Start());
StartupBrowserCreator browser_creator;
browser_creator.AddFirstRunTabs(
{embedded_test_server()->GetURL("/title1.html"),
embedded_test_server()->GetURL("/title2.html")});
// Do a simple non-process-startup browser launch.
base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
StartupBrowserCreatorImpl launch(base::FilePath(), dummy, &browser_creator,
chrome::startup::IsFirstRun::kYes);
launch.Launch(browser()->profile(), chrome::startup::IsProcessStartup::kNo,
/*restore_tabbed_browser=*/true);
// This should have created a new browser window.
Browser* new_browser = FindOneOtherBrowser(browser());
ASSERT_TRUE(new_browser);
TabStripModel* tab_strip = new_browser->tab_strip_model();
EXPECT_EQ(2, tab_strip->count());
EXPECT_EQ("title1.html",
tab_strip->GetWebContentsAt(0)->GetVisibleURL().ExtractFileName());
EXPECT_EQ("title2.html",
tab_strip->GetWebContentsAt(1)->GetVisibleURL().ExtractFileName());
}
#if BUILDFLAG(GOOGLE_CHROME_BRANDING) && BUILDFLAG(IS_MAC)
// http://crbug.com/314819
#define MAYBE_RestoreOnStartupURLsPolicySpecified \
DISABLED_RestoreOnStartupURLsPolicySpecified
#else
#define MAYBE_RestoreOnStartupURLsPolicySpecified \
RestoreOnStartupURLsPolicySpecified
#endif
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorFirstRunTest,
MAYBE_RestoreOnStartupURLsPolicySpecified) {
#if BUILDFLAG(IS_WIN)
return;
#endif // BUILDFLAG(IS_WIN)
ASSERT_TRUE(embedded_test_server()->Start());
StartupBrowserCreator browser_creator;
DisableWhatsNewPage();
// Set the following user policies:
// * RestoreOnStartup = RestoreOnStartupIsURLs
// * RestoreOnStartupURLs = [ "/title1.html" ]
policy_map_.Set(policy::key::kRestoreOnStartup,
policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER,
policy::POLICY_SOURCE_CLOUD,
base::Value(SessionStartupPref::kPrefValueURLs), nullptr);
base::Value::List startup_urls;
startup_urls.Append(embedded_test_server()->GetURL("/title1.html").spec());
policy_map_.Set(policy::key::kRestoreOnStartupURLs,
policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER,
policy::POLICY_SOURCE_CLOUD,
base::Value(std::move(startup_urls)), nullptr);
provider_.UpdateChromePolicy(policy_map_);
base::RunLoop().RunUntilIdle();
// Close the browser.
CloseBrowserAsynchronously(browser());
// Do a process-startup browser launch.
base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
StartupBrowserCreatorImpl launch(base::FilePath(), dummy, &browser_creator,
chrome::startup::IsFirstRun::kYes);
launch.Launch(browser()->profile(), chrome::startup::IsProcessStartup::kYes,
/*restore_tabbed_browser=*/true);
// This should have created a new browser window.
Browser* new_browser = FindOneOtherBrowser(browser());
ASSERT_TRUE(new_browser);
// Verify that the URL specified through policy is shown and no sync promo has
// been added.
TabStripModel* tab_strip = new_browser->tab_strip_model();
ASSERT_EQ(1, tab_strip->count());
EXPECT_EQ("title1.html",
tab_strip->GetWebContentsAt(0)->GetVisibleURL().ExtractFileName());
}
#if BUILDFLAG(GOOGLE_CHROME_BRANDING) && BUILDFLAG(IS_MAC)
// http://crbug.com/314819
#define MAYBE_FirstRunTabsWithRestoreSession \
DISABLED_FirstRunTabsWithRestoreSession
#else
#define MAYBE_FirstRunTabsWithRestoreSession FirstRunTabsWithRestoreSession
#endif
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorFirstRunTest,
MAYBE_FirstRunTabsWithRestoreSession) {
// Simulate the following initial preferences:
// {
// "first_run_tabs" : [
// "/title1.html"
// ],
// "session" : {
// "restore_on_startup" : 1
// },
// "sync_promo" : {
// "user_skipped" : true
// }
// }
ASSERT_TRUE(embedded_test_server()->Start());
StartupBrowserCreator browser_creator;
browser_creator.AddFirstRunTabs(
{embedded_test_server()->GetURL("/title1.html")});
browser()->profile()->GetPrefs()->SetInteger(prefs::kRestoreOnStartup, 1);
// Do a process-startup browser launch.
base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
StartupBrowserCreatorImpl launch(base::FilePath(), dummy, &browser_creator,
chrome::startup::IsFirstRun::kYes);
launch.Launch(browser()->profile(), chrome::startup::IsProcessStartup::kYes,
/*restore_tabbed_browser=*/true);
// This should have created a new browser window.
Browser* new_browser = FindOneOtherBrowser(browser());
ASSERT_TRUE(new_browser);
// Verify that the first-run tab is shown and no other pages are present.
TabStripModel* tab_strip = new_browser->tab_strip_model();
ASSERT_EQ(1, tab_strip->count());
EXPECT_EQ("title1.html",
tab_strip->GetWebContentsAt(0)->GetVisibleURL().ExtractFileName());
}
#endif // !BUILDFLAG(IS_CHROMEOS)
// Validates that prefs::kWasRestarted is automatically reset after next browser
// start.
class StartupBrowserCreatorWasRestartedFlag : public InProcessBrowserTest,
public BrowserListObserver {
public:
StartupBrowserCreatorWasRestartedFlag() { BrowserList::AddObserver(this); }
~StartupBrowserCreatorWasRestartedFlag() override {
BrowserList::RemoveObserver(this);
}
bool SetUpUserDataDirectory() override {
base::FilePath user_data_dir;
base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
std::string json;
base::Value::Dict local_state;
local_state.SetByDottedPath(prefs::kWasRestarted, true);
base::JSONWriter::Write(local_state, &json);
base::FilePath local_state_path =
user_data_dir.Append(chrome::kLocalStateFilename);
if (!base::WriteFile(local_state_path, json)) {
ADD_FAILURE() << "base::WriteFile() failed, " << local_state_path;
return false;
}
return true;
}
protected:
// SetUpCommandLine is setting kWasRestarted, so these tests all start up
// with WasRestarted() true.
void OnBrowserAdded(Browser* browser) override {
EXPECT_TRUE(StartupBrowserCreator::WasRestarted());
EXPECT_FALSE(
g_browser_process->local_state()->GetBoolean(prefs::kWasRestarted));
on_browser_added_hit_ = true;
}
bool on_browser_added_hit_ = false;
};
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorWasRestartedFlag, Test) {
// OnBrowserAdded() should have been hit before the test body began.
EXPECT_TRUE(on_browser_added_hit_);
// This is a bit strange but what occurs is that StartupBrowserCreator runs
// before this test body is hit and ~StartupBrowserCreator() will reset the
// restarted state, so here when we read WasRestarted() it should already be
// reset to false.
EXPECT_FALSE(StartupBrowserCreator::WasRestarted());
EXPECT_FALSE(
g_browser_process->local_state()->GetBoolean(prefs::kWasRestarted));
}
// The kCommandLineFlagSecurityWarningsEnabled policy doesn't exist on ChromeOS.
#if !BUILDFLAG(IS_CHROMEOS)
enum class CommandLineFlagSecurityWarningsPolicy {
kNoPolicy,
kEnabled,
kDisabled,
};
// Verifies that infobars are displayed (or not) depending on enterprise policy.
class StartupBrowserCreatorInfobarsTest
: public InProcessBrowserTest,
public ::testing::WithParamInterface<
std::tuple<StartupBrowserCreatorFlagTypeValue,
CommandLineFlagSecurityWarningsPolicy>> {
public:
StartupBrowserCreatorInfobarsTest()
: flag_type_(std::get<0>(GetParam())), policy_(std::get<1>(GetParam())) {}
protected:
std::pair<Browser*, infobars::ContentInfoBarManager*>
LaunchBrowserAndGetCreatedInfoBarManager(
const base::CommandLine& command_line) {
BrowserAddedObserver added_observer;
base::test::TestFuture<void> app_launch_done;
if (command_line.HasSwitch(switches::kAppId)) {
web_app::startup::SetStartupDoneCallbackForTesting(
app_launch_done.GetCallback());
} else {
std::move(app_launch_done.GetCallback()).Run();
}
EXPECT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl(
command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo,
{browser()->profile(), StartupProfileMode::kBrowserWindow}, {}));
EXPECT_TRUE(app_launch_done.Wait());
// Wait until the new browser window has been created. Using
// `FindOneOtherBrowser` is not sufficient here, because the window may be
// created asynchronously.
Browser* new_browser = added_observer.Wait();
EXPECT_TRUE(new_browser);
infobars::ContentInfoBarManager* infobar_manager =
infobars::ContentInfoBarManager::FromWebContents(
new_browser->tab_strip_model()->GetWebContentsAt(0));
EXPECT_TRUE(infobar_manager);
return std::make_pair(new_browser, infobar_manager);
}
const StartupBrowserCreatorFlagTypeValue flag_type_;
const CommandLineFlagSecurityWarningsPolicy policy_;
private:
void SetUpInProcessBrowserTestFixture() override {
policy_provider_.SetDefaultReturns(
/*is_initialization_complete_return=*/true,
/*is_first_policy_load_complete_return=*/true);
policy::BrowserPolicyConnector::SetPolicyProviderForTesting(
&policy_provider_);
if (policy_ != CommandLineFlagSecurityWarningsPolicy::kNoPolicy) {
bool is_enabled =
policy_ == CommandLineFlagSecurityWarningsPolicy::kEnabled;
policy::PolicyMap policies;
policies.Set(policy::key::kCommandLineFlagSecurityWarningsEnabled,
policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER,
policy::POLICY_SOURCE_PLATFORM, base::Value(is_enabled),
nullptr);
policy_provider_.UpdateChromePolicy(policies);
}
}
web_app::OsIntegrationTestOverrideBlockingRegistration faked_os_integration_;
testing::NiceMock<policy::MockConfigurationPolicyProvider> policy_provider_;
};
IN_PROC_BROWSER_TEST_P(StartupBrowserCreatorInfobarsTest, CheckInfobar) {
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
// We deliberately set the flag on the process command line instead of on the
// command_line passed to the StartupBrowserCreator, because these flags are
// all read from CommandLine::ForCurrentProcess and ignore the command line
// passed to StartupBrowserCreator. In browser tests, this references the
// browser test's instead of the new process.
base::CommandLine::ForCurrentProcess()->AppendSwitch(flag_type_.flag);
auto [browser, infobar_manager] =
LaunchBrowserAndGetCreatedInfoBarManager(command_line);
EXPECT_TRUE(browser->is_type_normal());
EXPECT_EQ(HasInfoBar(infobar_manager, flag_type_.infobar_identifier),
policy_ != CommandLineFlagSecurityWarningsPolicy::kDisabled);
}
IN_PROC_BROWSER_TEST_P(StartupBrowserCreatorInfobarsTest,
CheckInfobarIsShownForWebApps) {
// We deliberately set the flag on the process command line instead of on the
// command_line passed to the StartupBrowserCreator, because these flags are
// all read from CommandLine::ForCurrentProcess and ignore the command line
// passed to StartupBrowserCreator. In browser tests, this references the
// browser test's instead of the new process.
base::CommandLine::ForCurrentProcess()->AppendSwitch(flag_type_.flag);
Profile* test_profile = browser()->profile();
// Install web app
GURL example_url("http://www.example.com");
webapps::AppId app_id = InstallPWA(test_profile, example_url);
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendSwitchASCII(switches::kAppId, app_id);
auto [browser, infobar_manager] =
LaunchBrowserAndGetCreatedInfoBarManager(command_line);
EXPECT_TRUE(browser->is_type_app());
EXPECT_EQ(HasInfoBar(infobar_manager, flag_type_.infobar_identifier),
policy_ != CommandLineFlagSecurityWarningsPolicy::kDisabled);
}
IN_PROC_BROWSER_TEST_P(StartupBrowserCreatorInfobarsTest,
CheckInfobarIsShownForAppUrlShortcuts) {
// We deliberately set the flag on the process command line instead of on the
// command_line passed to the StartupBrowserCreator, because these flags are
// all read from CommandLine::ForCurrentProcess and ignore the command line
// passed to StartupBrowserCreator. In browser tests, this references the
// browser test's instead of the new process.
base::CommandLine::ForCurrentProcess()->AppendSwitch(flag_type_.flag);
// Add --app=<url> to the command line. Tests launching legacy apps which may
// have been created by "Add to Desktop" in old versions of Chrome.
// TODO(mgiuca): Delete this feature (https://crbug.com/751029). We are
// keeping it for now to avoid disrupting existing workflows.
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
GURL url = ui_test_utils::GetTestUrl(
base::FilePath(base::FilePath::kCurrentDirectory),
base::FilePath(FILE_PATH_LITERAL("title2.html")));
command_line.AppendSwitchASCII(switches::kApp, url.spec());
auto [browser, infobar_manager] =
LaunchBrowserAndGetCreatedInfoBarManager(command_line);
EXPECT_TRUE(browser->is_type_app());
EXPECT_EQ(HasInfoBar(infobar_manager, flag_type_.infobar_identifier),
policy_ != CommandLineFlagSecurityWarningsPolicy::kDisabled);
}
// The trybots set the kNoSandbox flag when running browser tests with the
// address sanitizer enabled, which contradicts with the assumption of this test
// that there is no bad flag on the process command line.
#if defined(ADDRESS_SANITIZER)
#define MAYBE_CheckInfobarOnlyUsesProcessCommandLine \
DISABLED_CheckInfobarOnlyUsesProcessCommandLine
#else
#define MAYBE_CheckInfobarOnlyUsesProcessCommandLine \
CheckInfobarOnlyUsesProcessCommandLine
#endif
IN_PROC_BROWSER_TEST_P(StartupBrowserCreatorInfobarsTest,
MAYBE_CheckInfobarOnlyUsesProcessCommandLine) {
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
// The flag should not result in an infobar when not set on the process
// command line via CommandLine::ForCurrentProcess.
command_line.AppendSwitch(flag_type_.flag);
auto [browser, infobar_manager] =
LaunchBrowserAndGetCreatedInfoBarManager(command_line);
EXPECT_TRUE(browser->is_type_normal());
EXPECT_FALSE(HasInfoBar(infobar_manager, flag_type_.infobar_identifier));
}
INSTANTIATE_TEST_SUITE_P(
PolicyControl,
StartupBrowserCreatorInfobarsTest,
::testing::Combine(
::testing::Values(
StartupBrowserCreatorFlagTypeValue{
switches::kEnableAutomation,
infobars::InfoBarDelegate::AUTOMATION_INFOBAR_DELEGATE},
// Test one of the flags from |bad_flags_prompt.cc|. Any of the
// flags should have the same behavior.
StartupBrowserCreatorFlagTypeValue{
switches::kDisableWebSecurity,
infobars::InfoBarDelegate::BAD_FLAGS_INFOBAR_DELEGATE}),
::testing::Values(CommandLineFlagSecurityWarningsPolicy::kNoPolicy,
CommandLineFlagSecurityWarningsPolicy::kEnabled,
CommandLineFlagSecurityWarningsPolicy::kDisabled)),
[](const testing::TestParamInfo<
StartupBrowserCreatorInfobarsTest::ParamType>& info) {
std::string policyState;
switch (std::get<1>(info.param)) {
case CommandLineFlagSecurityWarningsPolicy::kNoPolicy:
policyState = "no policy";
break;
case CommandLineFlagSecurityWarningsPolicy::kEnabled:
policyState = "policy enabled";
break;
case CommandLineFlagSecurityWarningsPolicy::kDisabled:
policyState = "policy disabled";
break;
}
std::string name = std::get<0>(info.param).flag + " " + policyState;
std::replace_if(
name.begin(), name.end(),
[](unsigned char c) { return !absl::ascii_isalnum(c); }, '_');
return name;
});
// Verifies that infobars are displayed in the first browser window, even when
// the browser is started without an initial browser window by passing the
// `switches::kNoStartupWindow` command line switch.
class StartupBrowserCreatorInfobarsWithoutStartupWindowTest
: public InProcessBrowserTest,
public ::testing::WithParamInterface<StartupBrowserCreatorFlagTypeValue> {
public:
StartupBrowserCreatorInfobarsWithoutStartupWindowTest()
: flag_type_(GetParam()) {}
protected:
void SetUpCommandLine(base::CommandLine* command_line) override {
InProcessBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kNoStartupWindow);
command_line->AppendSwitch(switches::kKeepAliveForTest);
}
std::pair<Browser*, infobars::ContentInfoBarManager*>
LaunchBrowserAndGetCreatedInfoBarManager() {
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
Profile* profile = ProfileManager::GetLastUsedProfileIfLoaded();
ui_test_utils::BrowserChangeObserver new_browser_observer(
nullptr, ui_test_utils::BrowserChangeObserver::ChangeType::kAdded);
StartupBrowserCreatorImpl launch(base::FilePath(), command_line,
chrome::startup::IsFirstRun::kNo);
launch.Launch(profile, chrome::startup::IsProcessStartup::kNo,
/*restore_tabbed_browser=*/true);
Browser* new_browser = new_browser_observer.Wait();
if (!new_browser) {
return std::make_pair(nullptr, nullptr);
}
ui_test_utils::WaitUntilBrowserBecomeActive(new_browser);
return std::make_pair(
new_browser, infobars::ContentInfoBarManager::FromWebContents(
new_browser->tab_strip_model()->GetWebContentsAt(0)));
}
const StartupBrowserCreatorFlagTypeValue flag_type_;
};
IN_PROC_BROWSER_TEST_P(StartupBrowserCreatorInfobarsWithoutStartupWindowTest,
CheckInfobar) {
// We deliberately set the flag on the process command line instead of on the
// command_line passed to the StartupBrowserCreator, because these flags are
// all read from `CommandLine::ForCurrentProcess` and ignore the command line
// passed to `StartupBrowserCreator`. In browser tests, this references the
// browser test's instead of the new process.
base::CommandLine::ForCurrentProcess()->AppendSwitch(flag_type_.flag);
EXPECT_EQ(0u, chrome::GetTotalBrowserCount());
auto [browser, infobar_manager] = LaunchBrowserAndGetCreatedInfoBarManager();
EXPECT_TRUE(browser);
EXPECT_EQ(1u, chrome::GetTotalBrowserCount());
ASSERT_TRUE(infobar_manager);
EXPECT_TRUE(HasInfoBar(infobar_manager, flag_type_.infobar_identifier));
// Now close and reopen the browser again - and re-check if the infobar is
// there.
CloseBrowserSynchronously(browser);
EXPECT_EQ(0u, chrome::GetTotalBrowserCount());
auto [browser2, infobar_manager2] =
LaunchBrowserAndGetCreatedInfoBarManager();
EXPECT_TRUE(browser2);
EXPECT_EQ(1u, chrome::GetTotalBrowserCount());
ASSERT_TRUE(infobar_manager2);
EXPECT_EQ(flag_type_.is_global_infobar,
HasInfoBar(infobar_manager2, flag_type_.infobar_identifier));
}
INSTANTIATE_TEST_SUITE_P(
All,
StartupBrowserCreatorInfobarsWithoutStartupWindowTest,
::testing::Values(
StartupBrowserCreatorFlagTypeValue{
switches::kEnableAutomation,
infobars::InfoBarDelegate::AUTOMATION_INFOBAR_DELEGATE, true},
// Test one of the flags from |bad_flags_prompt.cc|. Any of the
// flags should have the same behavior.
StartupBrowserCreatorFlagTypeValue{
switches::kDisableWebSecurity,
infobars::InfoBarDelegate::BAD_FLAGS_INFOBAR_DELEGATE, false}),
[](const testing::TestParamInfo<
StartupBrowserCreatorInfobarsWithoutStartupWindowTest::ParamType>&
info) {
std::string name = info.param.flag;
std::replace_if(
name.begin(), name.end(),
[](unsigned char c) { return !absl::ascii_isalnum(c); }, '_');
return name;
});
#endif // !BUILDFLAG(IS_CHROMEOS)
#if !BUILDFLAG(IS_CHROMEOS)
// Verifies that infobars are not displayed in Kiosk mode.
class StartupBrowserCreatorInfobarsKioskTest : public InProcessBrowserTest {
public:
StartupBrowserCreatorInfobarsKioskTest() = default;
protected:
infobars::ContentInfoBarManager*
LaunchKioskBrowserAndGetCreatedInfoBarManager(
const std::string& extra_switch) {
Profile* profile = browser()->profile();
// CommandLine::ForCurrentProcess is used to determine whether kiosk mode is
// enabled instead of the command-line passed to StartupBrowserCreator. In
// browser tests, this references the browser test's instead of the new
// process.
base::CommandLine::ForCurrentProcess()->AppendSwitch(switches::kKioskMode);
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendSwitch(extra_switch);
StartupBrowserCreatorImpl launch(base::FilePath(), command_line,
chrome::startup::IsFirstRun::kNo);
launch.Launch(profile, chrome::startup::IsProcessStartup::kYes,
/*restore_tabbed_browser=*/true);
// This should have created a new browser window.
Browser* new_browser = FindOneOtherBrowser(browser());
EXPECT_TRUE(new_browser);
if (!new_browser) {
return nullptr;
}
return infobars::ContentInfoBarManager::FromWebContents(
new_browser->tab_strip_model()->GetActiveWebContents());
}
};
// Verify that the Automation Enabled infobar is still shown in Kiosk mode.
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorInfobarsKioskTest,
CheckInfobarForEnableAutomation) {
// CommandLine::ForCurrentProcess is used to determine whether automation is
// enabled instead of the command-line passed to StartupBrowserCreator. In
// browser tests, this references the browser test's instead of the new
// process.
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableAutomation);
// Passing the kEnableAutomation argument here presently does not do
// anything because of the aforementioned limitation.
infobars::ContentInfoBarManager* infobar_manager =
LaunchKioskBrowserAndGetCreatedInfoBarManager(
switches::kEnableAutomation);
ASSERT_TRUE(infobar_manager);
EXPECT_TRUE(HasInfoBar(
infobar_manager, infobars::InfoBarDelegate::AUTOMATION_INFOBAR_DELEGATE));
}
// Verify that the Bad Flags infobar is not shown in kiosk mode.
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorInfobarsKioskTest,
CheckInfobarForBadFlag) {
// BadFlagsPrompt::ShowBadFlagsPrompt uses CommandLine::ForCurrentProcess
// instead of the command-line passed to StartupBrowserCreator. In browser
// tests, this references the browser test's instead of the new process.
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kDisableWebSecurity);
// Passing the kDisableWebSecurity argument here presently does not do
// anything because of the aforementioned limitation.
// https://crbug.com/1060293
infobars::ContentInfoBarManager* infobar_manager =
LaunchKioskBrowserAndGetCreatedInfoBarManager(
switches::kDisableWebSecurity);
ASSERT_TRUE(infobar_manager);
EXPECT_FALSE(HasInfoBar(
infobar_manager, infobars::InfoBarDelegate::BAD_FLAGS_INFOBAR_DELEGATE));
}
// Checks the correct behavior of the profile picker on startup.
class StartupBrowserCreatorPickerTestBase : public InProcessBrowserTest {
public:
StartupBrowserCreatorPickerTestBase() {
// This test configures command line params carefully. Make sure
// InProcessBrowserTest does _not_ add about:blank as a startup URL to the
// command line.
set_open_about_blank_on_browser_launch(false);
}
StartupBrowserCreatorPickerTestBase(
const StartupBrowserCreatorPickerTestBase&) = delete;
StartupBrowserCreatorPickerTestBase& operator=(
const StartupBrowserCreatorPickerTestBase&) = delete;
~StartupBrowserCreatorPickerTestBase() override = default;
void CreateMultipleProfiles() {
ProfileManager* profile_manager = g_browser_process->profile_manager();
// Create two additional profiles because the main test profile is created
// later in the startup process and so we need to have at least 2 fake
// profiles.
base::ScopedAllowBlockingForTesting allow_blocking;
std::vector<base::FilePath> profile_paths = {
profile_manager->user_data_dir().Append(
FILE_PATH_LITERAL("New Profile 1")),
profile_manager->user_data_dir().Append(
FILE_PATH_LITERAL("New Profile 2"))};
for (int i = 0; i < 2; ++i) {
const base::FilePath& profile_path = profile_paths[i];
profiles::testing::CreateProfileSync(profile_manager, profile_path);
// Mark newly created profiles as active.
ProfileAttributesEntry* entry =
profile_manager->GetProfileAttributesStorage()
.GetProfileAttributesWithPath(profile_path);
ASSERT_NE(entry, nullptr);
entry->SetActiveTimeToNow();
entry->SetAuthInfo(
GaiaId(base::StringPrintf("gaia_id_%i", i)),
base::UTF8ToUTF16(base::StringPrintf("user%i@gmail.com", i)),
/*is_consented_primary_account=*/false);
}
}
};
struct ProfilePickerSetup {
enum class ShutdownType {
kNormal, // Normal shutdown (e.g. by closing the browser window).
kExit, // Exit through the application menu.
kRestart // Restart (e.g. after an update).
};
bool expected_to_show;
std::optional<std::string> switch_name;
std::optional<std::string> switch_value_ascii;
std::optional<GURL> url_arg;
ShutdownType shutdown_type = ShutdownType::kNormal;
std::optional<std::string> extra_switch_name = std::nullopt;
};
// Checks the correct behavior of the profile picker on startup. This feature is
// not available on ChromeOS.
class StartupBrowserCreatorPickerTest
: public StartupBrowserCreatorPickerTestBase,
public ::testing::WithParamInterface<ProfilePickerSetup> {
public:
StartupBrowserCreatorPickerTest()
: relaunch_chrome_override_(base::BindRepeating(
[](const base::CommandLine&) { return true; })) {}
StartupBrowserCreatorPickerTest(const StartupBrowserCreatorPickerTest&) =
delete;
StartupBrowserCreatorPickerTest& operator=(
const StartupBrowserCreatorPickerTest&) = delete;
~StartupBrowserCreatorPickerTest() override = default;
void SetUpCommandLine(base::CommandLine* command_line) override {
StartupBrowserCreatorPickerTestBase::SetUpCommandLine(command_line);
if (content::IsPreTest()) {
return; // Don't apply the test parameters to the PRE test.
}
if (GetParam().url_arg) {
command_line->AppendArg(GetParam().url_arg->spec());
}
if (GetParam().switch_value_ascii) {
DCHECK(GetParam().switch_name);
command_line->AppendSwitchASCII(*GetParam().switch_name,
*GetParam().switch_value_ascii);
} else if (GetParam().switch_name) {
command_line->AppendSwitch(*GetParam().switch_name);
}
if (GetParam().extra_switch_name) {
command_line->AppendSwitch(*GetParam().extra_switch_name);
}
}
private:
// Prevent the browser from automatically relaunching in the PRE_ test. The
// browser will be relaunched by the main test.
upgrade_util::ScopedRelaunchChromeBrowserOverride relaunch_chrome_override_;
};
// Create a secondary profile in a separate PRE run because the existence of
// profiles is checked during startup in the actual test.
IN_PROC_BROWSER_TEST_P(StartupBrowserCreatorPickerTest, PRE_TestSetup) {
CreateMultipleProfiles();
switch (GetParam().shutdown_type) {
case ProfilePickerSetup::ShutdownType::kNormal:
// Need to close the browser window manually so that the real test does
// not treat it as session restore.
CloseAllBrowsers();
break;
case ProfilePickerSetup::ShutdownType::kExit:
chrome::AttemptExit();
break;
case ProfilePickerSetup::ShutdownType::kRestart:
chrome::AttemptRestart();
break;
}
ASSERT_EQ(
g_browser_process->local_state()->GetBoolean(prefs::kWasRestarted),
GetParam().shutdown_type == ProfilePickerSetup::ShutdownType::kRestart);
}
// Checks that either the ProfilePicker or a browser window is open at startup.
// Except with switches::kNoStartupWindow, for which neither the picker nor a
// browser is open.
// TODO(crbug.com/394713545): Flaky on all of Win/Mac/Linux
IN_PROC_BROWSER_TEST_P(StartupBrowserCreatorPickerTest, DISABLED_TestSetup) {
ProfilePickerSetup setup_param = GetParam();
// Check the ProfilePicker.
if (setup_param.expected_to_show) {
if (!ProfilePicker::IsOpen()) {
base::RunLoop run_loop;
ProfilePicker::AddOnProfilePickerOpenedCallbackForTesting(
run_loop.QuitClosure());
run_loop.Run();
}
EXPECT_TRUE(ProfilePicker::IsOpen());
} else {
EXPECT_FALSE(ProfilePicker::IsOpen());
}
// Check the browser window.
if (setup_param.expected_to_show ||
setup_param.switch_name == switches::kNoStartupWindow) {
EXPECT_EQ(0u, chrome::GetTotalBrowserCount());
} else {
EXPECT_EQ(1u, chrome::GetTotalBrowserCount());
}
// No Guest profile was created.
for (const Profile* profile :
g_browser_process->profile_manager()->GetLoadedProfiles()) {
EXPECT_FALSE(profile->IsGuestSession());
}
}
INSTANTIATE_TEST_SUITE_P(
All,
StartupBrowserCreatorPickerTest,
::testing::Values(
// Flaky: https://crbug.com/1126886
#if !BUILDFLAG(IS_OZONE) && !BUILDFLAG(IS_WIN)
// Picker should be shown in normal multi-profile startup situation.
ProfilePickerSetup{/*expected_to_show=*/true},
#endif
// Skip the picker for various command-line params and use the last used
// profile, instead.
ProfilePickerSetup{/*expected_to_show=*/false,
/*switch_name=*/switches::kIncognito},
ProfilePickerSetup{/*expected_to_show=*/false,
/*switch_name=*/switches::kApp},
ProfilePickerSetup{/*expected_to_show=*/false,
/*switch_name=*/switches::kAppId},
ProfilePickerSetup{/*expected_to_show=*/false,
/*switch_name=*/switches::kNoStartupWindow},
// Skip the picker when a specific profile is requested (used e.g. by
// profile specific desktop shortcuts on Win).
ProfilePickerSetup{/*expected_to_show=*/false,
/*switch_name=*/switches::kProfileDirectory,
/*switch_value_ascii=*/"Default"},
// Same, but with the kIgnoreProfileDirectoryIfNotExists flag with the
// profile existing.
ProfilePickerSetup{
/*expected_to_show=*/false,
/*switch_name=*/switches::kProfileDirectory,
/*switch_value_ascii=*/"Default",
/*url_arg=*/std::nullopt,
/*shutdown_type=*/ProfilePickerSetup::ShutdownType::kNormal,
/*extra_switch_name=*/
switches::kIgnoreProfileDirectoryIfNotExists},
// Show the picker if the profile is ignored due to it not existing.
ProfilePickerSetup{
/*expected_to_show=*/true,
/*switch_name=*/switches::kProfileDirectory,
/*switch_value_ascii=*/"DoesNotExist",
/*url_arg=*/std::nullopt,
/*shutdown_type=*/ProfilePickerSetup::ShutdownType::kNormal,
/*extra_switch_name=*/switches::kIgnoreProfileDirectoryIfNotExists},
// Skip the picker when a specific profile is requested by email.
ProfilePickerSetup{/*expected_to_show=*/false,
/*switch_name=*/switches::kProfileEmail,
/*switch_value_ascii=*/"user0@gmail.com"},
// Show the picker if the profile email is not found.
ProfilePickerSetup{/*expected_to_show=*/true,
/*switch_name=*/switches::kProfileEmail,
/*switch_value_ascii=*/"unknown@gmail.com"},
// Skip the picker when a URL is provided on command-line (used by the
// OS when Chrome is the default web browser) and use the last used
// profile, instead.
ProfilePickerSetup{/*expected_to_show=*/false,
/*switch_name=*/std::nullopt,
/*switch_value_ascii=*/std::nullopt,
/*url_arg=*/GURL("https://www.foo.com/")},
// Regression test for http://crbug.com/1166192
// Picker should be shown after exit.
ProfilePickerSetup{
/*expected_to_show=*/true,
/*switch_name=*/std::nullopt,
/*switch_value_ascii=*/std::nullopt,
/*url_arg=*/std::nullopt,
/*shutdown_type=*/ProfilePickerSetup::ShutdownType::kExit},
// Regression test for http://crbug.com/1245374
// Picker should not be shown after restart.
ProfilePickerSetup{
/*expected_to_show=*/false,
/*switch_name=*/std::nullopt,
/*switch_value_ascii=*/std::nullopt,
/*url_arg=*/std::nullopt,
/*shutdown_type=*/ProfilePickerSetup::ShutdownType::kRestart},
// Skip the picker when a url is requested and the profile is ignored.
ProfilePickerSetup{
/*expected_to_show=*/false,
/*switch_name=*/switches::kProfileDirectory,
/*switch_value_ascii=*/"DoesNotExist",
/*url_arg=*/GURL("https://www.foo.com/"),
/*shutdown_type=*/ProfilePickerSetup::ShutdownType::kNormal,
/*extra_switch_name=*/
switches::kIgnoreProfileDirectoryIfNotExists}));
class GuestStartupBrowserCreatorPickerTest
: public StartupBrowserCreatorPickerTestBase {
public:
GuestStartupBrowserCreatorPickerTest() = default;
void SetUpCommandLine(base::CommandLine* command_line) override {
command_line->AppendSwitch(switches::kGuest);
}
};
// Create a secondary profile in a separate PRE run because the existence of
// profiles is checked during startup in the actual test.
IN_PROC_BROWSER_TEST_F(GuestStartupBrowserCreatorPickerTest,
PRE_SkipsPickerWithGuest) {
CreateMultipleProfiles();
// Need to close the browser window manually so that the real test does not
// treat it as session restore.
CloseAllBrowsers();
}
IN_PROC_BROWSER_TEST_F(GuestStartupBrowserCreatorPickerTest,
SkipsPickerWithGuest) {
// The picker is skipped which means a browser window is opened on startup.
EXPECT_EQ(1u, chrome::GetTotalBrowserCount());
EXPECT_TRUE(browser()->profile()->IsGuestSession());
}
class StartupBrowserCreatorPickerNoParamsTest
: public StartupBrowserCreatorPickerTestBase {};
// Create a secondary profile in a separate PRE run because the existence of
// profiles is checked during startup in the actual test.
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorPickerNoParamsTest,
PRE_ShowPickerWhenAlreadyLaunched) {
CreateMultipleProfiles();
// Need to close the browser window manually so that the real test does not
// treat it as session restore.
CloseAllBrowsers();
}
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorPickerNoParamsTest,
ShowPickerWhenAlreadyLaunched) {
// Preprequisite: The picker is shown on the first start-up
profiles::testing::WaitForPickerWidgetCreated();
ASSERT_EQ(0u, chrome::GetTotalBrowserCount());
// Close the picker.
ScopedKeepAlive keep_alive(KeepAliveOrigin::BROWSER,
KeepAliveRestartOption::DISABLED);
ProfilePicker::Hide();
profiles::testing::WaitForPickerClosed();
EXPECT_FALSE(ProfilePicker::IsOpen());
// Simulate a second start when the browser is already running.
base::FilePath current_dir = base::FilePath();
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
StartupProfilePathInfo startup_profile_path_info =
GetStartupProfilePath(current_dir, command_line,
/*ignore_profile_picker=*/false);
EXPECT_EQ(startup_profile_path_info.reason,
StartupProfileModeReason::kMultipleProfiles);
StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
command_line, current_dir, startup_profile_path_info);
// The picker is shown again if no profile was previously opened.
profiles::testing::WaitForPickerWidgetCreated();
EXPECT_EQ(0u, chrome::GetTotalBrowserCount());
}
class SearchQueryStartupBrowserCreatorPickerTest
: public StartupBrowserCreatorPickerTestBase {
public:
SearchQueryStartupBrowserCreatorPickerTest() = default;
void SetUpCommandLine(base::CommandLine* command_line) override {
command_line->AppendArg("? Foo");
}
};
// Create a secondary profile in a separate PRE run because the existence of
// profiles is checked during startup in the actual test.
IN_PROC_BROWSER_TEST_F(SearchQueryStartupBrowserCreatorPickerTest,
PRE_SkipsPickerWithCommandLineSearchQuery) {
CreateMultipleProfiles();
// Need to close the browser window manually so that the real test does not
// treat it as session restore.
CloseAllBrowsers();
}
IN_PROC_BROWSER_TEST_F(SearchQueryStartupBrowserCreatorPickerTest,
SkipsPickerWithCommandLineSearchQuery) {
// A browser window is shown on start-up because the command line contains a
// search query.
EXPECT_EQ(1u, chrome::GetTotalBrowserCount());
// Check the return value of `GetStartupProfilePath()` explicitly.
base::FilePath current_dir = base::FilePath();
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendArg("? Foo");
StartupProfilePathInfo startup_profile_path_info =
GetStartupProfilePath(current_dir, command_line,
/*ignore_profile_picker=*/false);
EXPECT_EQ(startup_profile_path_info.reason,
StartupProfileModeReason::kCommandLineTabs);
}
class StartupBrowserCreatorPickerInfobarTest
: public StartupBrowserCreatorPickerTestBase,
public ::testing::WithParamInterface<StartupBrowserCreatorFlagTypeValue> {
public:
StartupBrowserCreatorPickerInfobarTest() : flag_type_(GetParam()) {}
void SetUpCommandLine(base::CommandLine* command_line) override {}
protected:
// Simulates a click on a profile card. The profile picker must be already
// opened.
void OpenProfileFromPicker(const base::FilePath& profile_path,
bool open_settings) {
base::Value::List args;
args.Append(base::FilePathToValue(profile_path));
profile_picker_handler()->HandleLaunchSelectedProfile(open_settings, args);
}
// Returns the profile picker webUI handler. The profile picker must be opened
// before calling this function.
ProfilePickerHandler* profile_picker_handler() {
DCHECK(ProfilePicker::IsOpen());
views::WebView* web_view = ProfilePicker::GetWebViewForTesting();
if (web_view == nullptr) {
return nullptr;
}
return web_view->GetWebContents()
->GetWebUI()
->GetController()
->GetAs<ProfilePickerUI>()
->GetProfilePickerHandlerForTesting();
}
const StartupBrowserCreatorFlagTypeValue flag_type_;
};
// Create a secondary profile in a separate PRE run because the existence of
// profiles is checked during startup in the actual test.
IN_PROC_BROWSER_TEST_P(StartupBrowserCreatorPickerInfobarTest,
PRE_ShowsEnableAutomationInfobar) {
CreateMultipleProfiles();
// Need to close the browser window manually so that the real test does not
// treat it as session restore.
CloseAllBrowsers();
}
IN_PROC_BROWSER_TEST_P(StartupBrowserCreatorPickerInfobarTest,
ShowsEnableAutomationInfobar) {
EXPECT_EQ(0u, chrome::GetTotalBrowserCount());
// We deliberately set the flag on the process command line instead of on the
// command_line passed to the StartupBrowserCreator, because these flags are
// always read from the command line of the current process
base::CommandLine::ForCurrentProcess()->AppendSwitch(flag_type_.flag);
ProfileManager* profile_manager = g_browser_process->profile_manager();
Profile* profile = nullptr;
{
base::ScopedAllowBlockingForTesting allow_blocking;
profile = profile_manager->GetLastUsedProfile();
}
ui_test_utils::BrowserChangeObserver new_browser_observer(
nullptr, ui_test_utils::BrowserChangeObserver::ChangeType::kAdded);
OpenProfileFromPicker(profile->GetPath(), false);
Browser* new_browser = new_browser_observer.Wait();
ui_test_utils::WaitUntilBrowserBecomeActive(new_browser);
infobars::ContentInfoBarManager* infobar_manager =
infobars::ContentInfoBarManager::FromWebContents(
new_browser->tab_strip_model()->GetWebContentsAt(0));
EXPECT_TRUE(HasInfoBar(infobar_manager, flag_type_.infobar_identifier));
}
INSTANTIATE_TEST_SUITE_P(
All,
StartupBrowserCreatorPickerInfobarTest,
::testing::Values(
StartupBrowserCreatorFlagTypeValue{
switches::kEnableAutomation,
infobars::InfoBarDelegate::AUTOMATION_INFOBAR_DELEGATE},
// Test one of the flags from |bad_flags_prompt.cc|. Any of the
// flags should have the same behavior.
StartupBrowserCreatorFlagTypeValue{
switches::kDisableWebSecurity,
infobars::InfoBarDelegate::BAD_FLAGS_INFOBAR_DELEGATE}),
[](const testing::TestParamInfo<
StartupBrowserCreatorPickerInfobarTest::ParamType>& info) {
std::string name = info.param.flag;
std::replace_if(
name.begin(), name.end(),
[](unsigned char c) { return !absl::ascii_isalnum(c); }, '_');
return name;
});
// TODO(crbug.com/40265712): Mocking the logger appears to not work correctly on
// Windows. Investigate why it is not working and enable the test on Windows.
#if !BUILDFLAG(IS_WIN)
class StartupBrowserCreatorIwaCommandLineInstallProfilePickerErrorTest
: public StartupBrowserCreatorPickerTestBase {
protected:
void SetUp() override {
if (!content::IsPreTest()) {
EXPECT_CALL(mock_log_, Log(testing::_, testing::_, testing::_, testing::_,
testing::_))
.Times(testing::AnyNumber());
EXPECT_CALL(
mock_log_,
Log(::logging::LOGGING_ERROR, testing::_, testing::_, testing::_,
testing::HasSubstr("Command line switches to install IWAs are "
"incompatible with the Profile Picker")));
mock_log_.StartCapturingLogs();
}
StartupBrowserCreatorPickerTestBase::SetUp();
}
void SetUpCommandLine(base::CommandLine* command_line) override {
if (!content::IsPreTest()) {
command_line->AppendSwitchASCII("install-isolated-web-app-from-url",
"http://localhost");
}
StartupBrowserCreatorPickerTestBase::SetUpCommandLine(command_line);
}
base::test::MockLog mock_log_;
};
// Create a secondary profile in a separate PRE run because the existence of
// profiles is checked during startup in the actual test.
IN_PROC_BROWSER_TEST_F(
StartupBrowserCreatorIwaCommandLineInstallProfilePickerErrorTest,
PRE_DoesNotInstallIwaIfProfilePickerOpens) {
CreateMultipleProfiles();
// Need to close the browser window manually so that the real test does not
// treat it as session restore.
CloseAllBrowsers();
}
IN_PROC_BROWSER_TEST_F(
StartupBrowserCreatorIwaCommandLineInstallProfilePickerErrorTest,
DoesNotInstallIwaIfProfilePickerOpens) {
EXPECT_EQ(0u, chrome::GetTotalBrowserCount());
// The `EXPECT_CALL` call in `SetUp()` will check that an error message about
// the IWA not being installable is logged.
}
#endif // !BUILDFLAG(IS_WIN)
#endif // !BUILDFLAG(IS_CHROMEOS)
|