File: ConvertActionTests.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (3488 lines) | stat: -rw-r--r-- 158,707 bytes parent folder | download
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
/*
 This source file is part of the Swift.org open source project

 Copyright (c) 2021-2024 Apple Inc. and the Swift project authors
 Licensed under Apache License v2.0 with Runtime Library Exception

 See https://swift.org/LICENSE.txt for license information
 See https://swift.org/CONTRIBUTORS.txt for Swift project authors
*/

import XCTest
import Foundation
@testable @_spi(ExternalLinks) import SwiftDocC
@testable import SwiftDocCUtilities
import SymbolKit
import Markdown
@testable import SwiftDocCTestUtilities

class ConvertActionTests: XCTestCase {
    // TODO: Change this back to `#if !os(iOS)` once https://github.com/apple/swift-corelibs-foundation/issues/5028 is resolved
    #if os(macOS)
    let imageFile = Bundle.module.url(
        forResource: "TestBundle", withExtension: "docc", subdirectory: "Test Bundles")!
        .appendingPathComponent("figure1.png")
    
    let symbolGraphFile = Bundle.module.url(
        forResource: "TestBundle", withExtension: "docc", subdirectory: "Test Bundles")!
        .appendingPathComponent("FillIntroduced.symbols.json")
    
    let objectiveCSymbolGraphFile = Bundle.module.url(
        forResource: "DeckKit-Objective-C",
        withExtension: "symbols.json",
        subdirectory: "Test Resources"
    )!

    let projectZipFile = Bundle.module.url(
        forResource: "TestBundle", withExtension: "docc", subdirectory: "Test Bundles")!
        .appendingPathComponent("project.zip")
    
    /// A symbol graph file that has missing symbols.
    let incompleteSymbolGraphFile = TextFile(name: "TechnologyX.symbols.json", utf8Content: """
        {
          "metadata": {
              "formatVersion" : {
                  "major" : 1
              },
              "generator" : "app/1.0"
          },
          "module" : {
            "name" : "MyKit",
            "platform" : {
              "architecture" : "x86_64",
              "vendor" : "apple",
              "operatingSystem" : {
                "name" : "ios",
                "minimumVersion" : {
                  "major" : 13,
                  "minor" : 0,
                  "patch" : 0
                }
              }
            }
          },
          "symbols" : [],
          "relationships" : [
            {
              "source" : "s:5MyKit0A5ProtocolP",
              "target" : "s:5Foundation0A5EarhartP",
              "kind" : "conformsTo"
            }
          ]
        }
        """
    )
    
    func testCopyingImageAssets() throws {
        XCTAssert(FileManager.default.fileExists(atPath: imageFile.path))
        let testImageName = "TestImage.png"
        
        // Documentation bundle that contains an image
        let bundle = Folder(name: "unit-test.docc", content: [
            CopyOfFile(original: imageFile, newName: testImageName),
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
        ])

        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)
        
        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory())
        let result = try action.perform(logHandle: .none)
        
        // Verify that the following files and folder exist at the output location
        let expectedOutput = Folder(name: ".docc-build", content: [
            Folder(name: "images", content: [
                Folder(name: "com.test.example", content: [
                    CopyOfFile(original: imageFile, newName: testImageName),
                ]),
            ]),
        ])
        expectedOutput.assertExist(at: result.outputs[0], fileManager: testDataProvider)
        
        // Verify that the copied image has the same capitalization as the original
        let copiedImageOutput = testDataProvider.files.keys
            .filter({ $0.hasPrefix(result.outputs[0].appendingPathComponent("images/com.test.example").path + "/") })
            .map({ $0.replacingOccurrences(of: result.outputs[0].appendingPathComponent("images/com.test.example").path + "/", with: "") })
        
        XCTAssertEqual(copiedImageOutput, [testImageName])
    }
    
    func testCopyingVideoAssets() throws {
        let videoFile = Bundle.module.url(
            forResource: "TestBundle", withExtension: "docc", subdirectory: "Test Bundles")!
                .appendingPathComponent("introvideo.mp4")
        
        XCTAssert(FileManager.default.fileExists(atPath: videoFile.path))
        let testVideoName = "TestVideo.mp4"
        
        // Documentation bundle that contains a video
        let bundle = Folder(name: "unit-test.docc", content: [
            CopyOfFile(original: videoFile, newName: testVideoName),
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
        ])

        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)
        
        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory())
        let result = try action.perform(logHandle: .none)
        
        // Verify that the following files and folder exist at the output location
        let expectedOutput = Folder(name: ".docc-build", content: [
            Folder(name: "videos", content: [
                Folder(name: "com.test.example", content: [
                    CopyOfFile(original: videoFile, newName: testVideoName),
                ]),
            ]),
        ])
        expectedOutput.assertExist(at: result.outputs[0], fileManager: testDataProvider)
        
        // Verify that the copied video has the same capitalization as the original
        let copiedVideoOutput = testDataProvider.files.keys
            .filter({ $0.hasPrefix(result.outputs[0].appendingPathComponent("videos/com.test.example").path + "/") })
            .map({ $0.replacingOccurrences(of: result.outputs[0].appendingPathComponent("videos/com.test.example").path + "/", with: "") })
        
        XCTAssertEqual(copiedVideoOutput, [testVideoName])
    }
    
    // Ensures we don't regress on copying download assets to the build folder (72599615)
    func testCopyingDownloadAssets() throws {
        let downloadFile = Bundle.module.url(
            forResource: "TestBundle", withExtension: "docc", subdirectory: "Test Bundles")!
                .appendingPathComponent("project.zip")
        
        let tutorialFile = Bundle.module.url(
            forResource: "TestBundle", withExtension: "docc", subdirectory: "Test Bundles")!
                .appendingPathComponent("TestTutorial.tutorial")
        
        let tutorialOverviewFile = Bundle.module.url(
            forResource: "TestBundle", withExtension: "docc", subdirectory: "Test Bundles")!
                .appendingPathComponent("TestOverview.tutorial")
        
        XCTAssert(FileManager.default.fileExists(atPath: downloadFile.path))
        XCTAssert(FileManager.default.fileExists(atPath: tutorialFile.path))
        XCTAssert(FileManager.default.fileExists(atPath: tutorialOverviewFile.path))
        
        // Documentation bundle that contains a download and a tutorial that references it
        let bundle = Folder(name: "unit-test.docc", content: [
            CopyOfFile(original: downloadFile),
            CopyOfFile(original: tutorialFile),
            CopyOfFile(original: tutorialOverviewFile),
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
        ])

        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)
        
        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory())
        let result = try action.perform(logHandle: .none)
        
        // Verify that the following files and folder exist at the output location
        let expectedOutput = Folder(name: ".docc-build", content: [
            Folder(name: "downloads", content: [
                Folder(name: "com.test.example", content: [
                    CopyOfFile(original: downloadFile),
                ]),
            ]),
        ])
        expectedOutput.assertExist(at: result.outputs[0], fileManager: testDataProvider)
    }
    
    // Ensures we always create the required asset folders even if no assets are explicitly
    // provided
    func testCreationOfAssetFolders() throws {
        // Empty documentation bundle
        let bundle = Folder(name: "unit-test.docc", content: [
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
        ])

        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)
        
        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory())
        let result = try action.perform(logHandle: .none)
        
        // Verify that the following files and folder exist at the output location
        let expectedOutput = Folder(name: ".docc-build", content: [
            Folder(name: "downloads", content: []),
            Folder(name: "images", content: []),
            Folder(name: "videos", content: []),
        ])
        expectedOutput.assertExist(at: result.outputs[0], fileManager: testDataProvider)
    }
    
    func testConvertsWithoutErrorsWhenBundleIsNotAtRoot() throws {
        let bundle = Folder(name: "unit-test.docc", content: [
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
        ])

        let input = Folder(name: "nested", content: [Folder(name: "folders", content: [bundle, Folder.emptyHTMLTemplateDirectory])])

        let testDataProvider = try TestFileSystem(folders: [input, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)

        var action = try ConvertAction(
            documentationBundleURL: input.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory())
        let result = try action.perform(logHandle: .none)
        XCTAssertEqual(result.problems.count, 0)
    }
    
    func testConvertWithoutBundle() throws {
        let myKitSymbolGraph = Bundle.module.url(forResource: "TestBundle", withExtension: "docc", subdirectory: "Test Bundles")!
            .appendingPathComponent("mykit-iOS.symbols.json")
        
        XCTAssert(FileManager.default.fileExists(atPath: myKitSymbolGraph.path))
        let symbolGraphFiles = Folder(name: "Not-a-doc-bundle", content: [
            CopyOfFile(original: myKitSymbolGraph, newName: "MyKit.symbols.json")
        ])
        
        let outputLocation = Folder(name: "output", content: [])
        
        let testDataProvider = try TestFileSystem(folders: [Folder.emptyHTMLTemplateDirectory, symbolGraphFiles, outputLocation])
        
        var infoPlistFallbacks = [String: Any]()
        infoPlistFallbacks["CFBundleDisplayName"] = "MyKit" // same as the symbol graph
        infoPlistFallbacks["CFBundleIdentifier"] = "com.example.test"
        infoPlistFallbacks["CFBundleVersion"] = "1.2.3"
        infoPlistFallbacks["CDDefaultCodeListingLanguage"] = "swift"
        
        var action = try ConvertAction(
            documentationBundleURL: nil,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: outputLocation.absoluteURL,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: nil,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory(),
            bundleDiscoveryOptions: BundleDiscoveryOptions(
                infoPlistFallbacks: infoPlistFallbacks,
                additionalSymbolGraphFiles: [URL(fileURLWithPath: "/Not-a-doc-bundle/MyKit.symbols.json")]
            )
        )
        
        let result = try action.perform(logHandle: .none)
        XCTAssertEqual(result.problems.count, 0)
        XCTAssertEqual(result.outputs, [outputLocation.absoluteURL])
        
        let outputData = testDataProvider.files.filter { $0.key.hasPrefix("/output/data/documentation/") }
        
        XCTAssertEqual(outputData.keys.sorted(), [
            "/output/data/documentation/mykit",
            "/output/data/documentation/mykit.json",
            "/output/data/documentation/mykit/myclass",
            "/output/data/documentation/mykit/myclass.json",
            "/output/data/documentation/mykit/myclass/init()-33vaw.json",
            "/output/data/documentation/mykit/myclass/init()-3743d.json",
            "/output/data/documentation/mykit/myclass/myfunction().json",
            "/output/data/documentation/mykit/myprotocol.json",
            "/output/data/documentation/mykit/globalfunction(_:considering:).json",
        ].sorted())
        
        let myKitNodeData = try XCTUnwrap(outputData["/output/data/documentation/mykit.json"])
        let myKitNode = try JSONDecoder().decode(RenderNode.self, from: myKitNodeData)
        
        // Verify that framework page doesn't get automatic abstract
        XCTAssertNil(myKitNode.abstract)
        XCTAssertTrue(myKitNode.primaryContentSections.isEmpty)
        XCTAssertEqual(myKitNode.topicSections.count, 3) // Automatic curation of the symbols in the symbol graph file
        
        // Verify that non-framework symbols also do not get automatic abstracts.
        let myProtocolNodeData = try XCTUnwrap(outputData["/output/data/documentation/mykit/myprotocol.json"])
        let myProtocolNode = try JSONDecoder().decode(RenderNode.self, from: myProtocolNodeData)
        XCTAssertNil(myProtocolNode.abstract)
    }

    func testMoveOutputCreatesTargetFolderParent() throws {
        // Source folder to test moving
        let source = Folder(name: "source", content: [
            TextFile(name: "index.html", utf8Content: ""),
        ])

        // The target location to test moving to
        let target = Folder(name: "target", content: [
            Folder(name: "output", content: []),
        ])
        
        // We add only the source to the file system
        let testDataProvider = try TestFileSystem(folders: [source, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)
        
        let action = try ConvertAction(
            documentationBundleURL: source.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory())
        
        let targetURL = target.absoluteURL.appendingPathComponent("output")
        
        XCTAssertNoThrow(try action.moveOutput(from: source.absoluteURL, to: targetURL))
        XCTAssertTrue(testDataProvider.fileExists(atPath: targetURL.path, isDirectory: nil))
        XCTAssertFalse(testDataProvider.fileExists(atPath: source.absoluteURL.path, isDirectory: nil))
    }
    
    func testMoveOutputDoesNotCreateIntermediateTargetFolderParents() throws {
        // Source folder to test moving
        let source = Folder(name: "source", content: [
            TextFile(name: "index.html", utf8Content: ""),
        ])

        // The target location to test moving to
        let target = Folder(name: "intermediate", content: [
            Folder(name: "target", content: [
                Folder(name: "output", content: []),
            ])
        ])
        
        // We add only the source to the file system
        let testDataProvider = try TestFileSystem(folders: [source, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)
        
        let action = try ConvertAction(
            documentationBundleURL: source.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory())
        
        let targetURL = target.absoluteURL.appendingPathComponent("target").appendingPathComponent("output")
        
        XCTAssertThrowsError(try action.moveOutput(from: source.absoluteURL, to: targetURL))
    }

    func testConvertDoesNotLowercasesResourceFileNames() throws {
        // Documentation bundle that contains an image
        let bundle = Folder(name: "unit-test.docc", content: [
            CopyOfFile(original: imageFile, newName: "TEST.png"),
            CopyOfFile(original: imageFile, newName: "VIDEO.mov"),
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
        ])

        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)
        
        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory())
        let result = try action.perform(logHandle: .none)
        
        // Verify that the following files and folder exist at the output location
        let expectedOutput = Folder(name: ".docc-build", content: [
            Folder(name: "images", content: [
                Folder(name: "com.test.example", content: [
                    CopyOfFile(original: imageFile, newName: "TEST.png"),
                ]),
            ]),
            Folder(name: "videos", content: [
                Folder(name: "com.test.example", content: [
                    CopyOfFile(original: imageFile, newName: "VIDEO.mov"),
                ]),
            ]),
        ])
        expectedOutput.assertExist(at: result.outputs[0], fileManager: testDataProvider)
    }
    
    // Ensures that render JSON produced by the convert action
    // does not include file location information for symbols.
    func testConvertDoesNotIncludeFilePathsInRenderNodes() throws {
        // Documentation bundle that contains a symbol graph.
        // The symbol graph contains symbols that include location information.
        let bundle = Folder(name: "unit-test.docc", content: [
            CopyOfFile(original: symbolGraphFile),
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
        ])

        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)
        
        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory())
        let result = try action.perform(logHandle: .none)
        
        // Construct the URLs for the produced render json:
        
        let documentationDataDirectoryURL = result.outputs[0]
            .appendingPathComponent("data", isDirectory: true)
            .appendingPathComponent("documentation", isDirectory: true)
        
        let fillIntroducedDirectoryURL = documentationDataDirectoryURL
            .appendingPathComponent("fillintroduced", isDirectory: true)
            
        let renderNodeURLs = [
            documentationDataDirectoryURL
                .appendingPathComponent("fillintroduced.json", isDirectory: false),
            fillIntroducedDirectoryURL
                .appendingPathComponent("macosonlydeprecated().json", isDirectory: false),
            fillIntroducedDirectoryURL
                .appendingPathComponent("macosonlyintroduced().json", isDirectory: false),
            fillIntroducedDirectoryURL
                .appendingPathComponent("iosmacosonly().json", isDirectory: false),
            fillIntroducedDirectoryURL
                .appendingPathComponent("iosonlydeprecated().json", isDirectory: false),
            fillIntroducedDirectoryURL
                .appendingPathComponent("iosonlyintroduced().json", isDirectory: false),
            fillIntroducedDirectoryURL
                .appendingPathComponent("maccatalystonlydeprecated().json", isDirectory: false),
            fillIntroducedDirectoryURL
                .appendingPathComponent("maccatalystonlyintroduced().json", isDirectory: false),
        ]
        
        let decoder = JSONDecoder()
        
        // Process all of the render JSON:
        try renderNodeURLs.forEach { renderNodeURL in
            // Get the data for the render json
            let renderNodeJSON = try testDataProvider.contentsOfURL(renderNodeURL)
            
            // Decode the render node
            let renderNode = try decoder.decode(RenderNode.self, from: renderNodeJSON)
            
            // Confirm that the render node didn't contain the location information
            // from the symbol graph
            XCTAssertNil(renderNode.metadata.sourceFileURI)
        }
    }
    
    // Ensures that render JSON produced by the convert action does not include symbol access level information.
    func testConvertDoesNotIncludeSymbolAccessLevelsInRenderNodes() throws {
        // Documentation bundle that contains a symbol graph.
        // The symbol graph contains symbols that include access level information.
        let bundle = Folder(name: "unit-test.docc", content: [
            CopyOfFile(original: symbolGraphFile),
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
        ])

        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)
        
        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory())
        let result = try action.perform(logHandle: .none)
        
        // Construct the URLs for the produced render json:
        
        let documentationDataDirectoryURL = result.outputs[0]
            .appendingPathComponent("data", isDirectory: true)
            .appendingPathComponent("documentation", isDirectory: true)
        
        let fillIntroducedDirectoryURL = documentationDataDirectoryURL
            .appendingPathComponent("fillintroduced", isDirectory: true)
            
        let renderNodeURLs = [
            documentationDataDirectoryURL
                .appendingPathComponent("fillintroduced.json", isDirectory: false),
            fillIntroducedDirectoryURL
                .appendingPathComponent("macosonlydeprecated().json", isDirectory: false),
            fillIntroducedDirectoryURL
                .appendingPathComponent("macosonlyintroduced().json", isDirectory: false),
            fillIntroducedDirectoryURL
                .appendingPathComponent("iosmacosonly().json", isDirectory: false),
            fillIntroducedDirectoryURL
                .appendingPathComponent("iosonlydeprecated().json", isDirectory: false),
            fillIntroducedDirectoryURL
                .appendingPathComponent("iosonlyintroduced().json", isDirectory: false),
            fillIntroducedDirectoryURL
                .appendingPathComponent("maccatalystonlydeprecated().json", isDirectory: false),
            fillIntroducedDirectoryURL
                .appendingPathComponent("maccatalystonlyintroduced().json", isDirectory: false),
        ]
        
        let decoder = JSONDecoder()
        
        // Process all of the render JSON:
        try renderNodeURLs.forEach { renderNodeURL in
            // Get the data for the render json
            let renderNodeJSON = try testDataProvider.contentsOfURL(renderNodeURL)
            
            // Decode the render node
            let renderNode = try decoder.decode(RenderNode.self, from: renderNodeJSON)
            
            // Confirm that the render node didn't contain the access level of symbols.
            XCTAssertNil(renderNode.metadata.symbolAccessLevel)
        }
    }

    func testOutputFolderContainsDiagnosticJSONWhenThereAreWarnings() throws {
        // Documentation bundle that contains an image
        let bundle = Folder(name: "unit-test.docc", content: [
            CopyOfFile(original: imageFile, newName: "referenced-tutorials-image.png"),
            TextFile(name: "TechnologyX.tutorial", utf8Content: """
                @Tutorials(name: "Technology X") {
                   @Intro(title: "Technology X") {
                      You'll learn all about Technology X.
                   }
                   
                   @Volume(name: "Volume 1") {
                      This volume contains Chapter 1.

                      @Image(source: referenced-tutorials-image, alt: "Some alt text")

                      @Chapter(name: "Chapter 1") {
                         In this chapter, you'll learn about Tutorial 1.

                         @Image(source: referenced-tutorials-image, alt: "Some alt text")
                      }
                   }
                }
                """
            ),
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
        ])

        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)

        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: true,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory())
        let result = try action.perform(logHandle: .none)

        // Verify that the following files and folder exist at the output location
        let expectedOutput = Folder(name: ".docc-build", content: [
            Folder(name: "images", content: [
                Folder(name: "com.test.example", content: [
                    CopyOfFile(original: imageFile, newName: "referenced-tutorials-image.png"),
                ]),
            ]),
            Folder(name: "videos", content: [
                Folder(name: "com.test.example", content: []),
            ]),
            JSONFile(name: "diagnostics.json", content: [
                Digest.Diagnostic(
                    start: .init(line: 11, column: 7),
                    source: URL(string: "TechnologyX.tutorial"),
                    severity: .warning,
                    summary: "Missing required 'TutorialReference' child directive",
                    explanation: "The 'Chapter' directive requires at least one 'TutorialReference' child directive",
                    notes: []
                ),
            ]),
        ])
        expectedOutput.assertExist(at: result.outputs[0], fileManager: testDataProvider)
    }
    
    /// Ensures that we always generate diagnosticJSON when there are errors. (rdar://72345373)
    func testOutputFolderContainsDiagnosticJSONWhenThereAreErrorsAndNoTemplate() throws {
        // Documentation bundle that contains an image
        let bundle = Folder(name: "unit-test.docc", content: [
            TextFile(name: "TechnologyX.tutorial", utf8Content: """
                @Article(time: 10) {
                   @Intro(title: "Technology X") {
                      You'll learn all about Technology X.
                   }
                
                   @Intro(title: "Technology X") {
                      You'll learn all about Technology X.
                   }
                }
                """
            ),
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
        ])

        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)

        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: nil,
            emitDigest: true,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory(),
            diagnosticLevel: "hint") // report all errors during the test
        let result = try action.perform(logHandle: .none)

        // Verify that the following files and folder exist at the output location
        let expectedOutput = Folder(name: ".docc-build", content: [
            JSONFile(name: "diagnostics.json", content: [
                Digest.Diagnostic(
                    start: .init(line: 6, column: 4),
                    source: URL(string: "TechnologyX.tutorial"),
                    severity: .warning,
                    summary: "Duplicate 'Intro' child directive",
                    explanation: "The 'Article' directive must have exactly one 'Intro' child directive",
                    notes: []
                ),
                Digest.Diagnostic(
                    start: nil,
                    source: URL(string: "TechnologyX.tutorial"),
                    severity: .warning,
                    summary: "The article 'TechnologyX' must be referenced from a Tutorial Table of Contents",
                    explanation: nil,
                    notes: []
                ),
                Digest.Diagnostic(
                    start: nil,
                    source: URL(string: "TechnologyX.tutorial"),
                    severity: .information,
                    summary: "You haven't curated 'doc://com.test.example/tutorials/TestBundle/TechnologyX'",
                    explanation: nil,
                    notes: []
                ),
            ]),
        ])
        expectedOutput.assertExist(at: result.outputs[0], fileManager: testDataProvider)
    }
    
    func testWarningForUncuratedTutorial() throws {
        // Documentation bundle that contains an image
        let bundle = Folder(name: "unit-test.docc", content: [
            TextFile(name: "TechnologyX.tutorial", utf8Content: """
                @Tutorial(time: 10) {
                  @Intro(title: "TechologyX") {}

                  @Section(title: "Section") {
                    @Steps {}
                  }

                  @Assessments {
                    @MultipleChoice {
                      text
                      @Choice(isCorrect: true) {
                        text
                        @Justification(reaction: "reaction text") {}
                      }

                      @Choice(isCorrect: false) {
                        text
                        @Justification(reaction: "reaction text") {}
                      }
                    }
                  }
                }
                """
            ),
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
        ])

        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)

        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: nil,
            emitDigest: true,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory(),
            diagnosticLevel: "hint") // report all errors during the test
        let result = try action.perform(logHandle: .none)

        // Verify that the following files and folder exist at the output location
        let expectedOutput = Folder(name: ".docc-build", content: [
            JSONFile(name: "diagnostics.json", content: [
                Digest.Diagnostic(
                    start: nil,
                    source: URL(string: "TechnologyX.tutorial"),
                    severity: .warning,
                    summary: "The tutorial 'TechnologyX' must be referenced from a Tutorial Table of Contents",
                    explanation: nil,
                    notes: []
                ),
                Digest.Diagnostic(
                    start: nil,
                    source: URL(string: "TechnologyX.tutorial"),
                    severity: .information,
                    summary: "You haven't curated 'doc://com.test.example/tutorials/TestBundle/TechnologyX'",
                    explanation: nil,
                    notes: []
                ),
            ])
        ])
        expectedOutput.assertExist(at: result.outputs[0], fileManager: testDataProvider)
    }
    
    /// Ensures we never delete an existing build folder if conversion fails (rdar://72339050)
    func testOutputFolderIsNotRemovedWhenThereAreErrors() throws {
        let tutorialsFile = TextFile(name: "TechnologyX.tutorial", utf8Content: """
            @Tutorials(name: "Technology Z") {
               @Intro(title: "Technology Z") {
                  Intro text.
               }
               
               @Volume(name: "Volume A") {
                  This is a volume.

                  @Chapter(name: "Getting Started") {
                     In this chapter, you'll learn about Tutorial 1. Feel free to add more `TutorialReference`s below.

                     @TutorialReference(tutorial: "doc:Tutorial" )
                  }
               }
            }
            """
        )
        
        let tutorialFile = TextFile(name: "Tutorial.tutorial", utf8Content: """
            @Article(time: 20) {
               @Intro(title: "Basic Augmented Reality App") {
                  This is curated under a Swift page and and ObjC page.
               }
            }
            """
        )
        
        let bundleInfoPlist = InfoPlist(displayName: "TestBundle", identifier: "com.test.example")
        
        let goodBundle = Folder(name: "unit-test.docc", content: [
            tutorialsFile,
            tutorialFile,
            bundleInfoPlist,
        ])
        
        let badBundle = Folder(name: "unit-test.docc", content: [
            incompleteSymbolGraphFile,
            bundleInfoPlist,
        ])
        
        let testDataProvider = try TestFileSystem(folders: [goodBundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)
        
        do {
            var action = try ConvertAction(
                documentationBundleURL: goodBundle.absoluteURL,
                outOfProcessResolver: nil,
                analyze: false,
                targetDirectory: targetDirectory,
                htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
                emitDigest: false,
                currentPlatforms: nil,
                dataProvider: testDataProvider,
                fileManager: testDataProvider,
                temporaryDirectory: testDataProvider.uniqueTemporaryDirectory())
            let result = try action.perform(logHandle: .none)
            
            XCTAssertFalse(
                result.didEncounterError,
                "Unexpected error occurred during conversion of test bundle."
            )
            
            // Verify that the build output folder was successfully created
            let expectedOutput = Folder(name: ".docc-build", content: [
                Folder(name: "data", content: [
                    Folder(name: "tutorials", content: []),
                ]),
            ])
            expectedOutput.assertExist(at: targetDirectory, fileManager: testDataProvider)
        }
        
        try testDataProvider.updateDocumentationBundles(withFolders: [badBundle])
        
        do {
            var action = try ConvertAction(
                documentationBundleURL: badBundle.absoluteURL,
                outOfProcessResolver: nil,
                analyze: false,
                targetDirectory: targetDirectory,
                htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
                emitDigest: false,
                currentPlatforms: nil,
                dataProvider: testDataProvider,
                fileManager: testDataProvider,
                temporaryDirectory: testDataProvider.uniqueTemporaryDirectory())
            let result = try action.perform(logHandle: .none)

            XCTAssert(
                result.didEncounterError,
                "We expect errors to occur during during conversion of the bad test bundle."
            )

            // Verify that the build output folder from the former successful conversion
            // still exists after this failure.
            let expectedOutput = Folder(name: ".docc-build", content: [
                Folder(name: "data", content: [
                ]),
            ])
            expectedOutput.assertExist(at: targetDirectory, fileManager: testDataProvider)
        }
    }
    
    func testOutputFolderContainsDiagnosticJSONWhenThereAreErrors() throws {
        // Documentation bundle that contains an image
        let bundle = Folder(name: "unit-test.docc", content: [
            incompleteSymbolGraphFile,
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
        ])

        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)

        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: true,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory())
        let result = try action.perform(logHandle: .none)

        // Verify that the following files and folder exist at the output location
        let expectedOutput = Folder(name: ".docc-build", content: [
            JSONFile(name: "diagnostics.json", content: [
                Digest.Diagnostic(
                    start: nil,
                    source: nil,
                    severity: .error,
                    summary: "Symbol with identifier 's:5MyKit0A5ProtocolP' couldn't be found",
                    explanation: nil,
                    notes: []
                ),
            ]),
        ])
        expectedOutput.assertExist(at: result.outputs[0], fileManager: testDataProvider)
    }

    /// Verifies that digest is correctly emitted for API documentation topics
    /// like module pages, symbols, and articles.
    func testMetadataIsWrittenToOutputFolderAPIDocumentation() throws {
        // Example documentation bundle that contains an image
        let bundle = Folder(name: "unit-test.docc", content: [
            // An asset
            CopyOfFile(original: imageFile, newName: "image.png"),
            
            // An Article
            TextFile(name: "Article.md", utf8Content: """
                # This is an article
                Article abstract.
                
                Discussion content
                
                ![my image](image.png)
                
                ## Article Section
                
                This is another section of the __article__.
                """
            ),

            TextFile(name: "SampleArticle.md", utf8Content: """
                # Sample Article

                @Metadata {
                    @PageKind(sampleCode)
                }

                Sample abstract.

                Discussion content
                """
            ),

            // A module page
            TextFile(name: "TestBed.md", utf8Content: """
                # ``TestBed``
                TestBed abstract.
                
                TestBed discussion __content__.
                ## Topics
                ### Basics
                - <doc:Article>
                """
            ),

            // A symbol doc extensions
            TextFile(name: "A.md", utf8Content: """
                # ``TestBed/A``
                An abstract.
                
                `A` discussion __content__.
                """
            ),

            // A symbol graph
            CopyOfFile(original: Bundle.module.url(forResource: "TopLevelCuration.symbols", withExtension: "json", subdirectory: "Test Resources")!),
            
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
        ])
        
        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)

        func contentsOfJSONFile<Result: Decodable>(url: URL) -> Result? {
            guard let data = testDataProvider.contents(atPath: url.path) else {
                return nil
            }
            return try? JSONDecoder().decode(Result.self, from: data)
        }

        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: true,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory())
        let result = try action.perform(logHandle: .none)

        // Because the page order isn't deterministic, we create the indexing records and linkable entities in the same order as the pages.
        let indexingRecords: [IndexingRecord] = action.context.knownPages.compactMap { reference in
            switch reference.path {
            case "/documentation/TestBed":
                return IndexingRecord(
                    kind: .symbol,
                    location: .topLevelPage(reference),
                    title: "TestBed",
                    summary: "TestBed abstract.",
                    headings: ["Overview"],
                    rawIndexableTextContent: "TestBed abstract. Overview TestBed discussion content."
                )
            case "/documentation/TestBed/A":
                return IndexingRecord(
                    kind: .symbol,
                    location: .topLevelPage(reference),
                    title: "A",
                    summary: "An abstract.",
                    headings: ["Overview"],
                    rawIndexableTextContent: "An abstract. Overview A discussion content."
                )
            case "/documentation/TestBundle/Article":
                return IndexingRecord(
                    kind: .article,
                    location: .topLevelPage(reference),
                    title: "This is an article",
                    summary: "Article abstract.",
                    headings: ["Overview", "Article Section"],
                    rawIndexableTextContent: "Article abstract. Overview Discussion content  Article Section This is another section of the article."
                )
            case "/documentation/TestBundle/SampleArticle":
                return IndexingRecord(
                    kind: .article,
                    location: .topLevelPage(reference),
                    title: "Sample Article",
                    summary: "Sample abstract.",
                    headings: ["Overview"],
                    rawIndexableTextContent: "Sample abstract. Overview Discussion content"
                )
            default:
                XCTFail("Encountered unexpected page '\(reference)'")
                return nil
            }
        }
        let linkableEntities = action.context.knownPages.flatMap { (reference: ResolvedTopicReference) -> [LinkDestinationSummary] in
            switch reference.path {
            case "/documentation/TestBed":
                return [
                    LinkDestinationSummary(
                        kind: .module,
                        relativePresentationURL: URL(string: "/documentation/testbed")!,
                        referenceURL: reference.url,
                        title: "TestBed",
                        language: .swift,
                        abstract: "TestBed abstract.",
                        taskGroups: [
                            .init(title: "Basics", identifiers: ["doc://com.test.example/documentation/TestBundle/Article"]),
                            .init(title: "Articles", identifiers: ["doc://com.test.example/documentation/TestBundle/SampleArticle"]),
                            .init(title: "Structures", identifiers: ["doc://com.test.example/documentation/TestBed/A"]),
                        ],
                        usr: "TestBed",
                        availableLanguages: [.swift],
                        platforms: nil,
                        topicImages: nil,
                        references: nil,
                        redirects: nil
                    ),
                ]
            case "/documentation/TestBed/A":
                return [
                    LinkDestinationSummary(
                        kind: .structure,
                        relativePresentationURL: URL(string: "/documentation/testbed/a")!,
                        referenceURL: reference.url,
                        title: "A",
                        language: .swift,
                        abstract: "An abstract.",
                        taskGroups: [],
                        usr: "s:7TestBed1AV",
                        availableLanguages: [.swift],
                        platforms: nil,
                        topicImages: nil,
                        references: nil,
                        redirects: nil
                    ),
                ]
            case "/documentation/TestBundle/Article":
                return [
                    LinkDestinationSummary(
                        kind: .article,
                        relativePresentationURL: URL(string: "/documentation/testbundle/article")!,
                        referenceURL: reference.url,
                        title: "This is an article",
                        language: .swift,
                        abstract: "Article abstract.",
                        taskGroups: [],
                        availableLanguages: [.swift],
                        platforms: nil,
                        topicImages: nil,
                        references: nil,
                        redirects: nil
                    ),
                ]
            case "/documentation/TestBundle/SampleArticle":
                return [
                    LinkDestinationSummary(
                        kind: .sampleCode,
                        relativePresentationURL: URL(string: "/documentation/testbundle/samplearticle")!,
                        referenceURL: reference.url,
                        title: "Sample Article",
                        language: .swift,
                        abstract: "Sample abstract.",
                        taskGroups: [],
                        availableLanguages: [.swift],
                        platforms: nil,
                        topicImages: nil,
                        references: nil,
                        redirects: nil
                    )
                ]
            default:
                XCTFail("Encountered unexpected page '\(reference)'")
                return []
            }
        }
        let images: [ImageReference] = action.context.knownPages.flatMap {
            reference -> [ImageReference] in
            switch reference.path {
            case "/documentation/TestBundle/Article":
                return [ImageReference(
                    name: "image.png",
                    altText: "my image",
                    userInterfaceStyle: .light,
                    displayScale: .standard
                )]
            default:
                return []
            }
        }

        // Verify diagnostics
        guard let resultDiagnostics: [Digest.Diagnostic] = contentsOfJSONFile(url: result.outputs[0].appendingPathComponent("diagnostics.json")) else {
            XCTFail("Can't find diagnostics.json in output")
            return
        }
        XCTAssertTrue(resultDiagnostics.isEmpty)
        
        // Verify indexing records
        let indexingRecordSort: (IndexingRecord, IndexingRecord) -> Bool = { return $0.title < $1.title }
        guard let resultIndexingRecords: [IndexingRecord] = contentsOfJSONFile(url: result.outputs[0].appendingPathComponent("indexing-records.json")) else {
            XCTFail("Can't find indexing-records.json in output")
            return
        }
        XCTAssertEqual(resultIndexingRecords.sorted(by: indexingRecordSort), indexingRecords.sorted(by: indexingRecordSort))

        // Verify linkable entities
        let linkableEntitiesSort: (LinkDestinationSummary, LinkDestinationSummary) -> Bool = { return $0.referenceURL.absoluteString < $1.referenceURL.absoluteString }
        guard let resultLikableEntities: [LinkDestinationSummary] = contentsOfJSONFile(url: result.outputs[0].appendingPathComponent("linkable-entities.json")) else {
            XCTFail("Can't find linkable-entities.json in output")
            return
        }
        XCTAssertEqual(resultLikableEntities.count, linkableEntities.count)
        for (resultEntity, entity) in zip(resultLikableEntities.sorted(by: linkableEntitiesSort), linkableEntities.sorted(by: linkableEntitiesSort)) {
            XCTAssertEqual(resultEntity, entity)
        }
        
        // Verify images
        guard let resultAssets: Digest.Assets = contentsOfJSONFile(url: result.outputs[0].appendingPathComponent("assets.json")) else {
            XCTFail("Can't find assets.json in output")
            return
        }
        XCTAssertEqual(resultAssets.images.map({ $0.identifier.identifier }).sorted(), images.map({ $0.identifier.identifier }).sorted())
    }

    func testLinkableEntitiesMetadataIncludesOverloads() throws {
        enableFeatureFlag(\.isExperimentalOverloadedSymbolPresentationEnabled)

        let bundle = try Folder.createFromDisk(
            url: Bundle.module.url(
                forResource: "OverloadedSymbols",
                withExtension: "docc",
                subdirectory: "Test Bundles")!
        )

        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)

        func contentsOfJSONFile<Result: Decodable>(url: URL) -> Result? {
            guard let data = testDataProvider.contents(atPath: url.path) else {
                return nil
            }
            return try? JSONDecoder().decode(Result.self, from: data)
        }

        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: true,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory())
        let result = try action.perform(logHandle: .none)

        guard let resultLikableEntities: [LinkDestinationSummary] = contentsOfJSONFile(url: result.outputs[0].appendingPathComponent("linkable-entities.json")) else {
            XCTFail("Can't find linkable-entities.json in output")
            return
        }

        // Rather than comparing all the linkable entities in the file, pull out one overload group
        // and check its task groups
        let overloadGroupEntity = try XCTUnwrap(resultLikableEntities.first(where: { $0.usr == "s:8ShapeKit18OverloadedProtocolP20fourthTestMemberName4testSdSS_tF::OverloadGroup" }))

        let taskGroups = try XCTUnwrap(overloadGroupEntity.taskGroups)
        guard taskGroups.count == 1, let overloadTaskGroup = taskGroups.first else {
            XCTFail("Expected one task group, found \(taskGroups.count): \(taskGroups.map(\.title?.singleQuoted))")
            return
        }

        XCTAssertEqual(overloadTaskGroup.title, "Overloads")
        XCTAssertEqual(Set(overloadTaskGroup.identifiers), [
            "doc://com.shapes.ShapeKit/documentation/ShapeKit/OverloadedProtocol/fourthTestMemberName(test:)-91hxs",
            "doc://com.shapes.ShapeKit/documentation/ShapeKit/OverloadedProtocol/fourthTestMemberName(test:)-961zx",
            "doc://com.shapes.ShapeKit/documentation/ShapeKit/OverloadedProtocol/fourthTestMemberName(test:)-8iuz7",
            "doc://com.shapes.ShapeKit/documentation/ShapeKit/OverloadedProtocol/fourthTestMemberName(test:)-1h173",
        ])
    }

    func testDownloadMetadataIsWritenToOutputFolder() throws {
        let bundle = Folder(name: "unit-test.docc", content: [
            CopyOfFile(original: projectZipFile),
            CopyOfFile(original: imageFile, newName: "referenced-tutorials-image.png"),

            TextFile(name: "MyTechnology.tutorial", utf8Content: """
            @Tutorial(time: 10, projectFiles: project.zip) {
              @Intro(title: "TechologyX") {}

              @Section(title: "Section") {
                @Steps {}
              }

              @Assessments {
                @MultipleChoice {
                  text
                  @Choice(isCorrect: true) {
                    text
                    @Justification(reaction: "reaction text") {}
                  }

                  @Choice(isCorrect: false) {
                    text
                    @Justification(reaction: "reaction text") {}
                  }
                }
              }
            }
            """),

            TextFile(name: "TechnologyX.tutorial", utf8Content: """
            @Tutorials(name: TechnologyX) {
               @Intro(title: "Technology X") {
                  Learn about some stuff in Technology X.
               }

               @Volume(name: "Volume 1") {
                  This volume contains Chapter 1.

                  @Image(source: referenced-tutorials-image.png, alt: "Some alt text")

                  @Chapter(name: "Chapter 1") {
                     In this chapter, you'll learn about Tutorial 1.

                     @Image(source: referenced-tutorials-image.png, alt: "Some alt text")
                     @TutorialReference(tutorial: "doc:MyTechnology")
                  }
               }
            }
            """),

            TextFile(name: "MySample.md", utf8Content: """
            # My Sample

            @Metadata {
                @CallToAction(url: "https://example.com/sample.zip", purpose: download)
            }

            This is a page with a download button.
            """),

            TextFile(name: "TestBundle.md", utf8Content: """
            # ``TestBundle``

            This is a test.

            ## Topics

            ### Pages

            - <doc:TechnologyX>
            - <doc:MySample>
            """),

            // A symbol graph
            CopyOfFile(original: Bundle.module.url(forResource: "TopLevelCuration.symbols", withExtension: "json", subdirectory: "Test Resources")!),

            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
        ])

        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)

        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: true,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory()
        )
        let result = try action.perform(logHandle: .none)

        func contentsOfJSONFile<Result: Decodable>(url: URL) -> Result? {
            guard let data = testDataProvider.contents(atPath: url.path) else {
                return nil
            }
            return try? JSONDecoder().decode(Result.self, from: data)
        }

        // Verify downloads
        guard let resultAssets: Digest.Assets = contentsOfJSONFile(url: result.outputs[0].appendingPathComponent("assets.json")) else {
            XCTFail("Can't find assets.json in output")
            return
        }
        XCTAssertEqual(resultAssets.downloads.count, 2)

        XCTAssert(resultAssets.downloads.contains(where: {
            $0.identifier.identifier == "project.zip"
        }))
        XCTAssert(resultAssets.downloads.contains(where: {
            $0.identifier.identifier == "https://example.com/sample.zip"
        }))
    }

    func testMetadataIsWrittenToOutputFolder() throws {
        // Example documentation bundle that contains an image
        let bundle = Folder(name: "unit-test.docc", content: [
            CopyOfFile(original: imageFile, newName: "referenced-article-image.png"),
            CopyOfFile(original: imageFile, newName: "referenced-tutorials-image.png"),
            CopyOfFile(original: imageFile, newName: "UNreferenced-image.png"),
            
            TextFile(name: "Article.tutorial", utf8Content: """
                @Article(time: 20) {
                   @Intro(title: "Making an Augmented Reality App") {
                      This is an abstract for the intro.
                   }
                   
                   ## Section Name
                   
                   ![full width image](referenced-article-image.png)
                }
                """
            ),
            TextFile(name: "TechnologyX.tutorial", utf8Content: """
                @Tutorials(name: TechnologyX) {
                   @Intro(title: "Technology X") {
                      Learn about some stuff in Technology X.
                   }
                   
                   @Volume(name: "Volume 1") {
                      This volume contains Chapter 1.

                      @Image(source: referenced-tutorials-image.png, alt: "Some alt text")

                      @Chapter(name: "Chapter 1") {
                         In this chapter, you'll learn about Tutorial 1.

                         @Image(source: referenced-tutorials-image.png, alt: "Some alt text")
                         @TutorialReference(tutorial: "doc:Article")
                      }
                   }

                }
                """
            ),
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
        ])

        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)

        func contentsOfJSONFile<Result: Decodable>(url: URL) -> Result? {
            guard let data = testDataProvider.contents(atPath: url.path) else {
                return nil
            }
            return try? JSONDecoder().decode(Result.self, from: data)
        }

        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: true,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory()
        )
        let result = try action.perform(logHandle: .none)
        
        // Because the page order isn't deterministic, we create the indexing records and linkable entities in the same order as the pages.
        let indexingRecords: [IndexingRecord] = action.context.knownPages.compactMap { reference in
            switch reference.path {
            case "/tutorials/TestBundle/Article":
                return IndexingRecord(
                    kind: .article,
                    location: .topLevelPage(reference),
                    title: "Making an Augmented Reality App",
                    summary: "This is an abstract for the intro.",
                    headings: ["Section Name"],
                    rawIndexableTextContent: "This is an abstract for the intro. Section Name "
                )
            case "/tutorials/TechnologyX":
                return IndexingRecord(
                    kind: .overview,
                    location: .topLevelPage(reference),
                    title: "Technology X",
                    summary: "Learn about some stuff in Technology X.",
                    headings: ["Volume 1"],
                    rawIndexableTextContent: "Learn about some stuff in Technology X. This volume contains Chapter 1."
                )
            case "/": return nil
            default:
                XCTFail("Encountered unexpected page '\(reference)'")
                return nil
            }
        }
        let linkableEntities = action.context.knownPages.flatMap { (reference: ResolvedTopicReference) -> [LinkDestinationSummary] in
            switch reference.path {
            case "/tutorials/TestBundle/Article":
                return [
                    LinkDestinationSummary(
                        kind: .tutorialArticle,
                        relativePresentationURL: URL(string: "/tutorials/testbundle/article")!,
                        referenceURL: reference.url,
                        title: "Making an Augmented Reality App",
                        language: .swift,
                        abstract: "This is an abstract for the intro.",
                        taskGroups: [.init(title: nil, identifiers: [reference.withFragment("Section-Name").absoluteString])],
                        availableLanguages: [.swift],
                        platforms: nil,
                        topicImages: nil,
                        references: nil,
                        redirects: nil
                    ),
                    LinkDestinationSummary(
                        kind: .onPageLandmark,
                        relativePresentationURL: URL(string: "/tutorials/testbundle/article#Section-Name")!,
                        referenceURL: reference.withFragment("Section-Name").url,
                        title: "Section Name",
                        language: .swift,
                        abstract: nil,
                        taskGroups: [],
                        availableLanguages: [.swift],
                        platforms: nil,
                        topicImages: nil,
                        references: nil,
                        redirects: nil
                    ),
                ]
            case "/tutorials/TechnologyX":
                return [
                    LinkDestinationSummary(
                        kind: .technology,
                        relativePresentationURL: URL(string: "/tutorials/technologyx")!,
                        referenceURL: reference.url,
                        title: "Technology X",
                        language: .swift,
                        abstract: "Learn about some stuff in Technology X.",
                        taskGroups: [.init(title: nil, identifiers: [reference.appendingPath("Volume-1").absoluteString])],
                        availableLanguages: [.swift],
                        platforms: nil,
                        topicImages: nil,
                        references: nil,
                        redirects: nil
                    ),
                ]
            default:
                XCTFail("Encountered unexpected page '\(reference)'")
                return []
            }
        }
        let images: [ImageReference] = action.context.knownPages.flatMap {
            reference -> [ImageReference] in
            switch reference.path {
            case "/tutorials/TestBundle/Article":
                return [ImageReference(
                    name: "referenced-article-image.png",
                    altText: "full width image",
                    userInterfaceStyle: .light,
                    displayScale: .standard
                )]
            case "/tutorials/TechnologyX":
                return [ImageReference(
                    name: "referenced-tutorials-image.png",
                    altText: "Some alt text",
                    userInterfaceStyle: .light,
                    displayScale: .standard
                )]
            default:
                XCTFail("Encountered unexpected page '\(reference)'")
                return []
            }
        }
        
        // Verify diagnostics
        guard let resultDiagnostics: [Digest.Diagnostic] = contentsOfJSONFile(url: result.outputs[0].appendingPathComponent("diagnostics.json")) else {
            XCTFail("Can't find diagnostics.json in output")
            return
        }
        XCTAssertTrue(resultDiagnostics.isEmpty)
        
        // Verify indexing records
        let indexingRecordSort: (IndexingRecord, IndexingRecord) -> Bool = { return $0.title < $1.title }
        guard let resultIndexingRecords: [IndexingRecord] = contentsOfJSONFile(url: result.outputs[0].appendingPathComponent("indexing-records.json")) else {
            XCTFail("Can't find indexing-records.json in output")
            return
        }
        XCTAssertEqual(resultIndexingRecords.sorted(by: indexingRecordSort), indexingRecords.sorted(by: indexingRecordSort))
        
        // Verify linkable entities
        let linkableEntitiesSort: (LinkDestinationSummary, LinkDestinationSummary) -> Bool = { return $0.referenceURL.absoluteString < $1.referenceURL.absoluteString }
        guard let resultLikableEntities: [LinkDestinationSummary] = contentsOfJSONFile(url: result.outputs[0].appendingPathComponent("linkable-entities.json")) else {
            XCTFail("Can't find linkable-entities.json in output")
            return
        }
        XCTAssertEqual(resultLikableEntities.sorted(by: linkableEntitiesSort), linkableEntities.sorted(by: linkableEntitiesSort))
        
        // Verify images
        guard let resultAssets: Digest.Assets = contentsOfJSONFile(url: result.outputs[0].appendingPathComponent("assets.json")) else {
            XCTFail("Can't find assets.json in output")
            return
        }
        XCTAssertEqual(resultAssets.images.map({ $0.identifier.identifier }).sorted(), images.map({ $0.identifier.identifier }).sorted())
    }
    
    func testMetadataIsOnlyWrittenToOutputFolderWhenEmitDigestFlagIsSet() throws {
        
        // An empty documentation bundle
        let bundle = Folder(name: "unit-test.docc", content: [
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
        ])

        // Check that they're all written when `--emit-digest` is set
        do {
            let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
            let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
                .appendingPathComponent("target", isDirectory: true)

            var action = try ConvertAction(
                documentationBundleURL: bundle.absoluteURL,
                outOfProcessResolver: nil,
                analyze: false,
                targetDirectory: targetDirectory,
                htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
                emitDigest: true, // emit digest files
                currentPlatforms: nil,
                dataProvider: testDataProvider,
                fileManager: testDataProvider,
                temporaryDirectory: testDataProvider.uniqueTemporaryDirectory()
            )
            let result = try action.perform(logHandle: .none)
            
            XCTAssertTrue(testDataProvider.fileExists(atPath: result.outputs[0].appendingPathComponent("assets.json").path))
            XCTAssertTrue(testDataProvider.fileExists(atPath: result.outputs[0].appendingPathComponent("diagnostics.json").path))
            XCTAssertTrue(testDataProvider.fileExists(atPath: result.outputs[0].appendingPathComponent("indexing-records.json").path))
            XCTAssertTrue(testDataProvider.fileExists(atPath: result.outputs[0].appendingPathComponent("linkable-entities.json").path))
        }
        
        // Check that they're not written when `--emit-digest` is not set
        do {
            let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
            let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
                .appendingPathComponent("target", isDirectory: true)

            var action = try ConvertAction(
                documentationBundleURL: bundle.absoluteURL,
                outOfProcessResolver: nil,
                analyze: false,
                targetDirectory: targetDirectory,
                htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
                emitDigest: false, // don't emit digest files
                currentPlatforms: nil,
                dataProvider: testDataProvider,
                fileManager: testDataProvider,
                temporaryDirectory: testDataProvider.uniqueTemporaryDirectory()
            )
            let result = try action.perform(logHandle: .none)
            
            XCTAssertFalse(testDataProvider.fileExists(atPath: result.outputs[0].appendingPathComponent("assets.json").path))
            XCTAssertFalse(testDataProvider.fileExists(atPath: result.outputs[0].appendingPathComponent("diagnostics.json").path))
            XCTAssertFalse(testDataProvider.fileExists(atPath: result.outputs[0].appendingPathComponent("indexing-records.json").path))
            XCTAssertFalse(testDataProvider.fileExists(atPath: result.outputs[0].appendingPathComponent("linkable-entities.json").path))
        }
    }

    /// An empty implementation of `ConvertOutputConsumer` that purposefully does nothing except
    /// to pass the number of documentation coverage info structs received to the given handler
    struct TestDocumentationCoverageConsumer: ConvertOutputConsumer {

        let coverageConsumeHandler: (Int) -> Void

        init(coverageConsumeHandler: @escaping (Int) -> Void) {
            self.coverageConsumeHandler = coverageConsumeHandler
        }

        func consume(renderNode: RenderNode) throws { }
        func consume(problems: [Problem]) throws { }
        func consume(assetsInBundle bundle: DocumentationBundle) throws {}
        func consume(linkableElementSummaries: [LinkDestinationSummary]) throws {}
        func consume(indexingRecords: [IndexingRecord]) throws {}
        func consume(assets: [RenderReferenceType: [RenderReference]]) throws {}
        func consume(benchmarks: Benchmark) throws {}

        // Call the handler with the number of coverage items consumed here
        func consume(documentationCoverageInfo: [CoverageDataEntry]) throws {
            coverageConsumeHandler(documentationCoverageInfo.count)
        }
    }

    func testMetadataIsOnlyWrittenToOutputFolderWhenDocumentationCoverage() throws {

        // An empty documentation bundle, except for a single symbol graph file
        // containing 8 symbols.
        let bundle = Folder(name: "unit-test.docc", content: [
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
            CopyOfFile(original: symbolGraphFile, newName: "MyKit.symbols.json"),
        ])

        // Count the number of coverage info structs consumed by each test below,
        // using TestDocumentationCoverageConsumer and this handler.
        var coverageInfoCount = 0
        let coverageInfoHandler = { count in coverageInfoCount += count }

        // Check that they're nothing is written for `.noCoverage`
        do {
            let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
            let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
                .appendingPathComponent("target", isDirectory: true)

            var action = try ConvertAction(
                documentationBundleURL: bundle.absoluteURL,
                outOfProcessResolver: nil,
                analyze: false,
                targetDirectory: targetDirectory,
                htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
                emitDigest: false,
                currentPlatforms: nil,
                dataProvider: testDataProvider,
                fileManager: testDataProvider,
                temporaryDirectory: testDataProvider.uniqueTemporaryDirectory(),
                documentationCoverageOptions: .noCoverage)
            let result = try action.perform(logHandle: .none)

            XCTAssertFalse(testDataProvider.fileExists(atPath: result.outputs[0].appendingPathComponent("documentation-coverage.json").path))

            // Rerun the convert and test no coverage info structs were consumed
            let _ = try action.converter.convert(outputConsumer: TestDocumentationCoverageConsumer(coverageConsumeHandler: coverageInfoHandler))
            XCTAssertEqual(coverageInfoCount, 0)
        }

        // Check that JSON is written for `.brief`
        do {
            let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
            let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
                .appendingPathComponent("target", isDirectory: true)

            var action = try ConvertAction(
                documentationBundleURL: bundle.absoluteURL,
                outOfProcessResolver: nil,
                analyze: false,
                targetDirectory: targetDirectory,
                htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
                emitDigest: false,
                currentPlatforms: nil,
                dataProvider: testDataProvider,
                fileManager: testDataProvider,
                temporaryDirectory: testDataProvider.uniqueTemporaryDirectory(),
                documentationCoverageOptions: DocumentationCoverageOptions(level: .brief))
            let result = try action.perform(logHandle: .none)

            XCTAssertTrue(testDataProvider.fileExists(atPath: result.outputs[0].appendingPathComponent("documentation-coverage.json").path))

            // Rerun the convert and test one coverage info structs was consumed for each symbol page (8)
            coverageInfoCount = 0
            let _ = try action.converter.convert(outputConsumer: TestDocumentationCoverageConsumer(coverageConsumeHandler: coverageInfoHandler))
            XCTAssertEqual(coverageInfoCount, 8)
        }

        // Check that JSON is written for `.detailed`
        do {
            let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
            let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
                .appendingPathComponent("target", isDirectory: true)

            var action = try ConvertAction(
                documentationBundleURL: bundle.absoluteURL,
                outOfProcessResolver: nil,
                analyze: false,
                targetDirectory: targetDirectory,
                htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
                emitDigest: false,
                currentPlatforms: nil,
                dataProvider: testDataProvider,
                fileManager: testDataProvider,
                temporaryDirectory: testDataProvider.uniqueTemporaryDirectory(),
                documentationCoverageOptions: DocumentationCoverageOptions(level: .detailed))
            let result = try action.perform(logHandle: .none)

            XCTAssertTrue(testDataProvider.fileExists(atPath: result.outputs[0].appendingPathComponent("documentation-coverage.json").path))

            // Rerun the convert and test one coverage info structs was consumed for each symbol page (8)
            coverageInfoCount = 0
            let _ = try action.converter.convert(outputConsumer: TestDocumentationCoverageConsumer(coverageConsumeHandler: coverageInfoHandler))
            XCTAssertEqual(coverageInfoCount, 8)
        }
    }
    
    /// Test context gets the current platforms provided by command line.
    func testRelaysCurrentPlatformsToContext() throws {
        // Empty documentation bundle that's nested inside some other directories.
        let bundle = Folder(name: "nested", content: [
            Folder(name: "folders", content: [
                Folder(name: "unit-test.docc", content: [
                    InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
                ]),
            ])
        ])
        
        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)
        
        let action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: [
                "platform1": PlatformVersion(.init(10, 11, 12), beta: false),
                "platform2": PlatformVersion(.init(11, 12, 13), beta: false),
            ],
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory()
        )
        
        XCTAssertEqual(action.context.externalMetadata.currentPlatforms, [
            "platform1" : PlatformVersion(.init(10, 11, 12), beta: false),
            "platform2" : PlatformVersion(.init(11, 12, 13), beta: false),
        ])
    }
    
    func testBetaInAvailabilityFallbackPlatforms() throws {
        
        func generateConvertAction(currentPlatforms: [String : PlatformVersion]) throws -> ConvertAction {
            try ConvertAction(
                documentationBundleURL: bundle.absoluteURL,
                outOfProcessResolver: nil,
                analyze: false,
                targetDirectory: targetDirectory,
                htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
                emitDigest: false,
                currentPlatforms: currentPlatforms,
                dataProvider: testDataProvider,
                fileManager: testDataProvider,
                temporaryDirectory: testDataProvider.uniqueTemporaryDirectory()
            )
        }
        let bundle = Folder(name: "nested", content: [
            Folder(name: "folders", content: [
                Folder(name: "unit-test.docc", content: [
                    InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
                ]),
            ])
        ])
        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)
        
        // Test whether the missing platforms copy the availability information from the fallback platform.
        var action = try generateConvertAction(currentPlatforms: ["iOS": PlatformVersion(.init(10, 0, 0), beta: true)])
        XCTAssertEqual(action.context.externalMetadata.currentPlatforms, [
            "iOS" : PlatformVersion(.init(10, 0, 0), beta: true),
            "Mac Catalyst" : PlatformVersion(.init(10, 0, 0), beta: true),
            "iPadOS" : PlatformVersion(.init(10, 0, 0), beta: true),
        ])
        // Test whether the non-missing platforms don't copy the availability information from the fallback platform.
        action = try generateConvertAction(currentPlatforms: [
            "iOS": PlatformVersion(.init(10, 0, 0), beta: true),
            "Mac Catalyst": PlatformVersion(.init(11, 0, 0), beta: false)
        ])
        XCTAssertEqual(action.context.externalMetadata.currentPlatforms, [
            "iOS" : PlatformVersion(.init(10, 0, 0), beta: true),
            "Mac Catalyst" : PlatformVersion(.init(11, 0, 0), beta: false),
            "iPadOS" : PlatformVersion(.init(10, 0, 0), beta: true)
        ])
        action = try generateConvertAction(currentPlatforms: [
            "iOS": PlatformVersion(.init(10, 0, 0), beta: true),
            "Mac Catalyst" : PlatformVersion(.init(11, 0, 0), beta: true),
            "iPadOS": PlatformVersion(.init(12, 0, 0), beta: false),
            
        ])
        XCTAssertEqual(action.context.externalMetadata.currentPlatforms, [
            "iOS" : PlatformVersion(.init(10, 0, 0), beta: true),
            "Mac Catalyst" : PlatformVersion(.init(11, 0, 0), beta: true),
            "iPadOS" : PlatformVersion(.init(12, 0, 0), beta: false),
        ])
        // Test whether the non-missing platforms don't copy the availability information from the non-fallback platform.
        action = try generateConvertAction(currentPlatforms: [
            "tvOS": PlatformVersion(.init(13, 0, 0), beta: true)
            
        ])
        XCTAssertEqual(action.context.externalMetadata.currentPlatforms, [
            "tvOS": PlatformVersion(.init(13, 0, 0), beta: true)
        ])
    }
    
    func testResolvedTopicReferencesAreCachedByDefaultWhenConverting() throws {
        let bundle = Folder(
            name: "unit-test.docc",
            content: [
                InfoPlist(displayName: "TestBundle", identifier: #function),
                CopyOfFile(original: symbolGraphFile),
            ]
        )
        
        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)
        
        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: [:],
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory()
        )
        
        _ = try action.perform(logHandle: .none)
        
        XCTAssertEqual(ResolvedTopicReference._numberOfCachedReferences(bundleID: #function), 8)
    }

    func testIgnoresAnalyzerHintsByDefault() throws {
        func runCompiler(analyze: Bool) throws -> [Problem] {
            // This bundle has both non-analyze and analyze style warnings.
            let testBundleURL = Bundle.module.url(
                forResource: "TestBundle", withExtension: "docc", subdirectory: "Test Bundles")!
            let bundle = try Folder.createFromDisk(url: testBundleURL)

            let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
            let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
                .appendingPathComponent("target", isDirectory: true)

            let engine = DiagnosticEngine()
            var action = try ConvertAction(
                documentationBundleURL: bundle.absoluteURL,
                outOfProcessResolver: nil,
                analyze: analyze, // Turn on/off the analyzer.
                targetDirectory: targetDirectory,
                htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
                emitDigest: false,
                currentPlatforms: nil,
                dataProvider: testDataProvider,
                fileManager: testDataProvider,
                temporaryDirectory: testDataProvider.uniqueTemporaryDirectory(),
                diagnosticEngine: engine)
            let result = try action.perform(logHandle: .none)
            XCTAssertFalse(result.didEncounterError)
            return engine.problems
        }

        let analyzeDiagnostics = try runCompiler(analyze: true)
        let noAnalyzeDiagnostics = try runCompiler(analyze: false)
        
        XCTAssertTrue(analyzeDiagnostics.contains { $0.diagnostic.severity == .information })
        XCTAssertFalse(noAnalyzeDiagnostics.contains { $0.diagnostic.severity == .information })

        XCTAssertTrue(
            analyzeDiagnostics.count > noAnalyzeDiagnostics.count,
            """
                The number of diagnostics with '--analyze' should be more than without '--analyze' \
                (\(analyzeDiagnostics.count) vs \(noAnalyzeDiagnostics.count))
                """
        )
    }
    
    /// Verify that the conversion of the same input given high concurrency and no concurrency,
    /// and also with and without generating digest produces the same results
    func testConvertTestBundleWithHighConcurrency() throws {
        let testBundleURL = Bundle.module.url(
            forResource: "TestBundle", withExtension: "docc", subdirectory: "Test Bundles")!
        let bundle = try Folder.createFromDisk(url: testBundleURL)

        struct TestReferenceResolver: ExternalDocumentationSource {
            func resolve(_ reference: TopicReference) -> TopicReferenceResolutionResult {
                return .success(ResolvedTopicReference(bundleIdentifier: "com.example.test", path: reference.url!.path, sourceLanguage: .swift))
            }

            func entity(with reference: ResolvedTopicReference) -> LinkResolver.ExternalEntity {
                fatalError("This test never asks for the external entity.")
            }
        }
        
        func convertTestBundle(batchSize: Int, emitDigest: Bool, targetURL: URL, testDataProvider: DocumentationWorkspaceDataProvider & FileManagerProtocol) throws -> ActionResult {
            // Run the create ConvertAction
            var action = try ConvertAction(
                documentationBundleURL: bundle.absoluteURL,
                outOfProcessResolver: nil,
                analyze: false,
                targetDirectory: targetURL,
                htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
                emitDigest: emitDigest,
                currentPlatforms: nil,
                dataProvider: testDataProvider,
                fileManager: testDataProvider,
                temporaryDirectory: testDataProvider.uniqueTemporaryDirectory()
            )
            
            action.converter.batchNodeCount = batchSize
            
            action.context.externalDocumentationSources["com.example.test"] = TestReferenceResolver()
            
            return try action.perform(logHandle: .none)
        }

        for withDigest in [false, true] {
            let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])

            // Set a batch size to a high number to have no concurrency
            let serialOutputURL = URL(string: "/serialOutput")!
            let serialResult = try convertTestBundle(batchSize: 10_000, emitDigest: withDigest, targetURL: serialOutputURL, testDataProvider: testDataProvider)

            // Set a batch size to 1 to have maximum concurrency (this is bad for performance maximizes our chances of encountering an issue).
            let parallelOutputURL = URL(string: "/parallelOutput")!
            let parallelResult = try convertTestBundle(batchSize: 1, emitDigest: withDigest, targetURL: parallelOutputURL, testDataProvider: testDataProvider)
            
            // Compare the results
            XCTAssertEqual(
                uniformlyPrintDiagnosticMessages(serialResult.problems),
                uniformlyPrintDiagnosticMessages(parallelResult.problems)
            )
            
            XCTAssertEqual(parallelResult.outputs.count, 1)
            XCTAssertEqual(serialResult.outputs.count, 1)
            
            guard let serialOutput = serialResult.outputs.first, let parallelOutput = parallelResult.outputs.first else {
                XCTFail("Missing output to compare")
                return
            }
            
            let serialContent = testDataProvider.files.keys.filter({ $0.hasPrefix(serialOutput.path) })
            let parallelContent = testDataProvider.files.keys.filter({ $0.hasPrefix(parallelOutput.path) })

            XCTAssertFalse(serialContent.isEmpty)
            XCTAssertEqual(serialContent.count, parallelContent.count)
            
            let relativePathsSerialContent = serialContent.map({ $0.replacingOccurrences(of: serialOutput.path, with: "") })
            let relativePathsParallelContent = parallelContent.map({ $0.replacingOccurrences(of: parallelOutput.path, with: "") })

            XCTAssertEqual(relativePathsSerialContent.sorted(), relativePathsParallelContent.sorted())
        }
    }
    
    func testConvertActionProducesDeterministicOutput() throws {
        // Pretty printing the output JSON also enables sorting keys during encoding
        // which is required for testing if the conversion output is deterministic.
        let priorPrettyPrintValue = shouldPrettyPrintOutputJSON
        shouldPrettyPrintOutputJSON = true
        defer {
            // Because this value is being modified in-process (not in the environment)
            // it will not affect the outcome of other tests, even when running tests in parallel.
            // Even when tests are run in parallel,
            // there is only one test being executed per process at a time.
            shouldPrettyPrintOutputJSON = priorPrettyPrintValue
        }
        
        let testBundleURL = try XCTUnwrap(
            Bundle.module.url(
                forResource: "TestBundle",
                withExtension: "docc",
                subdirectory: "Test Bundles"
            )
        )
        let bundle = try Folder.createFromDisk(url: testBundleURL)
        
        func performConvertAction(outputURL: URL, testFileSystem: TestFileSystem) throws {
            var action = try ConvertAction(
                documentationBundleURL: bundle.absoluteURL,
                outOfProcessResolver: nil,
                analyze: false,
                targetDirectory: outputURL,
                htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
                emitDigest: false,
                currentPlatforms: nil,
                dataProvider: testFileSystem,
                fileManager: testFileSystem,
                temporaryDirectory: testFileSystem.uniqueTemporaryDirectory()
            )
            action.diagnosticEngine.consumers.sync { $0.removeAll() } 
            
            _ = try action.perform(logHandle: .none)
        }
        
        // We'll perform 3 sets of conversions to confirm the output is deterministic
        for _ in 1...3 {
            let testFileSystem = try TestFileSystem(
                folders: [bundle, Folder.emptyHTMLTemplateDirectory]
            )
            
            // Convert the same bundle three times and place the output in
            // separate directories.
            
            try performConvertAction(
                outputURL: URL(fileURLWithPath: "/1", isDirectory: true),
                testFileSystem: testFileSystem
            )
            try performConvertAction(
                outputURL: URL(fileURLWithPath: "/2", isDirectory: true),
                testFileSystem: testFileSystem
            )
            
            // Extract and sort the RenderJSON output of each conversion
            
            let firstConversionFiles = testFileSystem.files.lazy.filter { key, _ in
                key.hasPrefix("/1/data/")
            }.map { (key, value) in
                return (String(key.dropFirst("/1".count)), value)
            }.sorted(by: \.0)
            
            let secondConversionFiles = testFileSystem.files.lazy.filter { key, _ in
                key.hasPrefix("/2/data/")
            }.map { (key, value) in
                return (String(key.dropFirst("/2".count)), value)
            }.sorted(by: \.0)
            
            // Zip the two sets of sorted files and loop through them, ensuring that
            // each conversion produced the same RenderJSON output.
            
            XCTAssertEqual(
                firstConversionFiles.map(\.0),
                secondConversionFiles.map(\.0),
                "The produced file paths are nondeterministic."
            )
            
            for (first, second) in zip(firstConversionFiles, secondConversionFiles) {
                let firstString = String(data: first.1, encoding: .utf8)
                let secondString = String(data: second.1, encoding: .utf8)
                
                XCTAssertEqual(firstString, secondString, "The contents of '\(first.0)' is nondeterministic.")
            }
        }
    }
    
    func testConvertActionNavigatorIndexGeneration() throws {
        // The navigator index needs to test with the real file manager
        let bundleURL = Bundle.module.url(forResource: "TestBundle", withExtension: "docc", subdirectory: "Test Bundles")!
        
        let targetURL = try createTemporaryDirectory()
        let templateURL = try createTemporaryDirectory().appendingPathComponent("template")
        try Folder.emptyHTMLTemplateDirectory.write(to: templateURL)
        
        // Convert the documentation and create an index
        
        var action = try ConvertAction(
            documentationBundleURL: bundleURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetURL,
            htmlTemplateDirectory: templateURL,
            emitDigest: false,
            currentPlatforms: nil,
            buildIndex: true,
            temporaryDirectory: createTemporaryDirectory() // Create an index
        )
        _ = try action.perform(logHandle: .none)
        
        let indexURL = targetURL.appendingPathComponent("index")
        
        let indexFromConvertAction = try NavigatorIndex.readNavigatorIndex(url: indexURL)
        XCTAssertEqual(indexFromConvertAction.count, 37)
        
        indexFromConvertAction.environment?.close()
        try FileManager.default.removeItem(at: indexURL)
        
        // Run just the index command over the built documentation
        
        var indexAction = try IndexAction(
            documentationBundleURL: targetURL,
            outputURL: indexURL,
            bundleIdentifier: indexFromConvertAction.bundleIdentifier
        )
        _ = try indexAction.perform(logHandle: .none)
        
        let indexFromIndexAction = try NavigatorIndex.readNavigatorIndex(url: indexURL)
        XCTAssertEqual(indexFromIndexAction.count, 37)
        
        XCTAssertEqual(
            indexFromConvertAction.navigatorTree.root.dumpTree(),
            indexFromIndexAction.navigatorTree.root.dumpTree()
        )
    }
    
    func testObjectiveCNavigatorIndexGeneration() throws {
        let bundle = Folder(name: "unit-test-objc.docc", content: [
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
            CopyOfFile(original: objectiveCSymbolGraphFile),
        ])
        
        // The navigator index needs to test with the real File Manager
        let testTemporaryDirectory = try createTemporaryDirectory()
        
        let bundleDirectory = testTemporaryDirectory.appendingPathComponent(
            bundle.name,
            isDirectory: true
        )
        try bundle.write(to: bundleDirectory)
        
        let targetDirectory = testTemporaryDirectory.appendingPathComponent(
            "output",
            isDirectory: true
        )
        
        var action = try ConvertAction(
            documentationBundleURL: bundleDirectory,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: nil,
            emitDigest: false,
            currentPlatforms: nil,
            buildIndex: true,
            temporaryDirectory: createTemporaryDirectory()
        )
        
        _ = try action.perform(logHandle: .none)
        
        let index = try NavigatorIndex.readNavigatorIndex(url: targetDirectory.appendingPathComponent("index"))
        func assertAllChildrenAreObjectiveC(_ node: NavigatorTree.Node) {
            XCTAssertEqual(
                node.item.languageID,
                InterfaceLanguage.objc.mask,
                """
                Node from Objective-C symbol graph did not have Objective-C language ID: \
                '\(node.item.usrIdentifier ?? node.item.title)'"
                """
            )
            
            for childNode in node.children {
                assertAllChildrenAreObjectiveC(childNode)
            }
        }
        
        XCTAssertEqual(
            index.navigatorTree.root.children.count, 1,
            "The root of the navigator tree unexpectedly contained more than one child."
        )
        
        let firstChild = try XCTUnwrap(index.navigatorTree.root.children.first)
        assertAllChildrenAreObjectiveC(firstChild)
    }
    
    func testMixedLanguageNavigatorIndexGeneration() throws {
        // The navigator index needs to test with the real File Manager
        let temporaryTestOutputDirectory = try createTemporaryDirectory()
        
        let bundleDirectory = try XCTUnwrap(
            Bundle.module.url(
                forResource: "MixedLanguageFramework",
                withExtension: "docc",
                subdirectory: "Test Bundles"
            ),
            "Unexpectedly failed to find 'MixedLanguageFramework.docc' test bundle."
        )
        
        var action = try ConvertAction(
            documentationBundleURL: bundleDirectory,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: temporaryTestOutputDirectory,
            htmlTemplateDirectory: nil,
            emitDigest: false,
            currentPlatforms: nil,
            buildIndex: true,
            temporaryDirectory: createTemporaryDirectory()
        )
        
        _ = try action.perform(logHandle: .none)
        
        let index = try NavigatorIndex.readNavigatorIndex(
            url: temporaryTestOutputDirectory.appendingPathComponent("index")
        )
        
        func assertForAllChildren(
            _ node: NavigatorTree.Node,
            assert: (_ node: NavigatorTree.Node) -> ()
        ) {
            assert(node)
            
            for childNode in node.children {
                assertForAllChildren(childNode, assert: assert)
            }
        }
        
        XCTAssertEqual(
            index.navigatorTree.root.children.count, 2,
            "The root of the navigator tree should contain '2' children, one for each language"
        )
        
        let swiftRootNode = try XCTUnwrap(
            index.navigatorTree.root.children.first { node in
                return node.item.languageID == InterfaceLanguage.swift.mask
            },
            "The navigator tree should contain a Swift item at the root."
        )
        
        let objectiveCRootNode = try XCTUnwrap(
            index.navigatorTree.root.children.first { node in
                return node.item.languageID == InterfaceLanguage.objc.mask
            },
            "The navigator tree should contain an Objective-C item at the root."
        )
        
        var swiftNavigatorEntries = [String]()
        assertForAllChildren(swiftRootNode) { node in
            XCTAssertEqual(
                node.item.languageID,
                InterfaceLanguage.swift.mask,
                """
                Node from Swift root node did not have Swift language ID: \
                '\(node.item.usrIdentifier ?? node.item.title)'"
                """
            )
            
            swiftNavigatorEntries.append(node.item.title)
        }
        
        let expectedSwiftNavigatorEntires = [
            "Swift",
            "MixedLanguageFramework",
            "Classes",
            "Bar",
            "Type Methods",
            "class func myStringFunction(String) throws -> String",
            "Structures",
            "Foo",
            "Initializers",
            "init(rawValue: UInt)",
            "Type Properties",
            "static var first: Foo",
            "static var fourth: Foo",
            "static var second: Foo",
            "static var third: Foo",
            "SwiftOnlyStruct",
            "Instance Methods",
            "func tada()",
        ]
        
        XCTAssertEqual(
            swiftNavigatorEntries,
            expectedSwiftNavigatorEntires,
            "Swift navigator contained unexpected content."
        )
        
        var objectiveCNavigatorEntries = [String]()
        assertForAllChildren(objectiveCRootNode) { node in
            XCTAssertEqual(
                node.item.languageID,
                InterfaceLanguage.objc.mask,
                """
                Node from Objective-C symbol graph did not have Objective-C language ID: \
                '\(node.item.usrIdentifier ?? node.item.title)'"
                """
            )
            
            objectiveCNavigatorEntries.append(node.item.title)
        }
        
        let expectedObjectiveNavigatorEntries = [
            "Objective-C",
            "MixedLanguageFramework",
            "Classes",
            "Bar",
            "Type Methods",
            "myStringFunction:error: (navigator title)",
            "Custom",
            "Foo",
            "Variables",
            "_MixedLanguageFrameworkVersionNumber",
            "_MixedLanguageFrameworkVersionString",
            "Enumerations",
            "Foo",
            "Enumeration Cases",
            "first",
            "fourth",
            "second",
            "third",
        ]
        
        XCTAssertEqual(
            objectiveCNavigatorEntries,
            expectedObjectiveNavigatorEntries,
            "Objective-C navigator contained unexpected content."
        )
    }
    
    func testDiagnosticLevel() throws {
        let bundle = Folder(name: "unit-test.docc", content: [
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
            CopyOfFile(original: symbolGraphFile, newName: "MyKit.symbols.json"),
            TextFile(name: "Article.md", utf8Content: """
            Bad title

            This article has a malformed title and can't be analyzed, so it
            produces one warning.
            """),
            incompleteSymbolGraphFile,
        ])

        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)

        let engine = DiagnosticEngine()
        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory(),
            diagnosticLevel: "error",
            diagnosticEngine: engine
        )
        let result = try action.perform(logHandle: .none)

        XCTAssertEqual(engine.problems.count, 1, "\(ConvertAction.self) didn't filter out diagnostics above the 'error' level.")
        XCTAssert(result.didEncounterError)
    }

    func testDiagnosticLevelIgnoredWhenAnalyzeIsPresent() throws {
        let bundle = Folder(name: "unit-test.docc", content: [
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
            CopyOfFile(original: symbolGraphFile, newName: "MyKit.symbols.json"),
            TextFile(name: "Article.md", utf8Content: """
            Bad title

            This article has a malformed title and can't be analyzed, so it
            produces one warning.
            """),
            incompleteSymbolGraphFile,
        ])

        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)

        let engine = DiagnosticEngine()
        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: true,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory(),
            diagnosticLevel: "error",
            diagnosticEngine: engine
        )
        let result = try action.perform(logHandle: .none)

        XCTAssertEqual(engine.problems.count, 2, "\(ConvertAction.self) shouldn't filter out diagnostics when the '--analyze' flag is passed")
        XCTAssertEqual(engine.problems.map { $0.diagnostic.identifier }, ["org.swift.docc.Article.Title.NotFound", "org.swift.docc.SymbolNodeNotFound"])
        XCTAssert(result.didEncounterError)
        XCTAssert(engine.problems.contains(where: { $0.diagnostic.severity == .warning }))
    }

    func testDoesNotIncludeDiagnosticsInThrownError() throws {
        let bundle = Folder(name: "unit-test.docc", content: [
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
            CopyOfFile(original: symbolGraphFile, newName: "MyKit.symbols.json"),
            TextFile(name: "Article.md", utf8Content: """
            Bad title

            This article has a malformed title and can't be analyzed, so it
            produces one warning.
            """),
            incompleteSymbolGraphFile,
        ])

        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)

        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: true,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory(),
            diagnosticLevel: "error"
        )
        XCTAssertThrowsError(try action.performAndHandleResult(logHandle: .none)) { error in
            XCTAssert(error is ErrorsEncountered, "Unexpected error type thrown by \(ConvertAction.self)")
        }
    }
    
    func testWritesDiagnosticFileWhenThrowingError() throws {
        let bundle = Folder(name: "unit-test.docc", content: [
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
            CopyOfFile(original: symbolGraphFile, newName: "MyKit.symbols.json"),
            TextFile(name: "Article.md", utf8Content: """
            Bad title

            This article has a malformed title and can't be analyzed, so it
            produces one warning.
            """),
            incompleteSymbolGraphFile,
        ])

        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)

        // TODO: Support TestFileSystem in DiagnosticFileWriter
        let diagnosticFile = try createTemporaryDirectory().appendingPathComponent("test-diagnostics.json")
        
        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: true,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory(),
            diagnosticLevel: "error",
            diagnosticFilePath: diagnosticFile
        )
        
        // TODO: Support TestFileSystem in DiagnosticFileWriter
        XCTAssertFalse(FileManager.default.fileExists(atPath: diagnosticFile.path), "Diagnostic file doesn't exist before")
        XCTAssertThrowsError(try action.performAndHandleResult(logHandle: .none)) { error in
            XCTAssert(error is ErrorsEncountered, "Unexpected error type thrown by \(ConvertAction.self)")
        }
        XCTAssertTrue(FileManager.default.fileExists(atPath: diagnosticFile.path), "Diagnostic file exist after")
    }

    // Verifies setting convert inherit docs flag
    func testConvertInheritDocsOption() throws {
        // Empty documentation bundle
        let bundle = Folder(name: "unit-test.documentation", content: [
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
        ])
        
        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)
        
        // Verify setting the flag explicitly
        for flag in [false, true] {
            let action = try ConvertAction(
                documentationBundleURL: bundle.absoluteURL,
                outOfProcessResolver: nil,
                analyze: false,
                targetDirectory: targetDirectory,
                htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
                emitDigest: false,
                currentPlatforms: nil,
                dataProvider: testDataProvider,
                fileManager: testDataProvider,
                temporaryDirectory: testDataProvider.uniqueTemporaryDirectory(),
                inheritDocs: flag)
            XCTAssertEqual(action.context.externalMetadata.inheritDocs, flag)
        }
        
        // Verify implicit value
        let action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory())
        XCTAssertEqual(action.context.externalMetadata.inheritDocs, false)
    }
    
    func testEmitsDigest() throws {
        let bundle = Folder(name: "unit-test.docc", content: [
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
            CopyOfFile(original: symbolGraphFile, newName: "MyKit.symbols.json"),
            incompleteSymbolGraphFile,
        ])

        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath).appendingPathComponent("target", isDirectory: true)

        let digestFileURL = targetDirectory
            .appendingPathComponent("diagnostics.json")
        
        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: true,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory()
        )
        
        XCTAssertThrowsError(try action.performAndHandleResult(logHandle: .none), "The test bundle should have thrown an error about an incomplete symbol graph file")
        XCTAssert(testDataProvider.fileExists(atPath: digestFileURL.path), "The digest file should have been written even though compilation errors occurred")
        
        let data = try testDataProvider.contentsOfURL(digestFileURL)
        let diagnostics = try RenderJSONDecoder.makeDecoder().decode([Digest.Diagnostic].self, from: data)
        XCTAssertEqual(diagnostics.count, 1)

    }
    
    func testRenderIndexJSONGeneration() throws {
        let catalog = Folder(name: "unit-test.docc", content: [
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
            CopyOfFile(original: symbolGraphFile, newName: "MyKit.symbols.json"),
        ])

        let temporaryDirectory = try createTemporaryDirectory()
        let catalogURL = try catalog.write(inside: temporaryDirectory)
        
        let targetDirectory = temporaryDirectory.appendingPathComponent("target", isDirectory: true)
        let dataProvider = try LocalFileSystemDataProvider(rootURL: catalogURL)
        
        var action = try ConvertAction(
            documentationBundleURL: catalog.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: nil,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: dataProvider,
            fileManager: FileManager.default,
            temporaryDirectory: createTemporaryDirectory()
        )
        
        try action.performAndHandleResult(logHandle: .none)
        
        let indexDirectory = targetDirectory.appendingPathComponent("index", isDirectory: true)
        let renderIndexJSON = indexDirectory.appendingPathComponent("index.json", isDirectory: false)
        
        try action.performAndHandleResult(logHandle: .none)
        XCTAssertTrue(FileManager.default.directoryExists(atPath: indexDirectory.path))
        XCTAssertTrue(FileManager.default.fileExists(atPath: renderIndexJSON.path))
        try XCTAssertEqual(FileManager.default.contentsOfDirectory(at: indexDirectory, includingPropertiesForKeys: nil).count, 1)
    }
    
    /// Verifies that a metadata.json file is created in the output folder with additional metadata.
    func testCreatesBuildMetadataFileForBundleWithInfoPlistValues() throws {
        let bundle = Folder(
            name: "unit-test.docc",
            content: [InfoPlist(displayName: "TestBundle", identifier: "com.test.example")]
        )
        
        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)
        
        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory()
        )
        let result = try action.perform(logHandle: .none)
        
        let expectedOutput = Folder(name: ".docc-build", content: [
            JSONFile(
                name: "metadata.json",
                content: BuildMetadata(bundleDisplayName: "TestBundle", bundleIdentifier: "com.test.example")
            ),
        ])
        
        expectedOutput.assertExist(at: result.outputs[0], fileManager: testDataProvider)
    }
    
    // Tests that the default behavior of `docc convert` on the command-line does not throw an error
    // when processing a DocC catalog that does not actually produce documentation. (r91790147)
    func testConvertDocCCatalogThatProducesNoDocumentationDoesNotThrowError() throws {
        let emptyCatalog = Folder(
            name: "unit-test.docc",
            content: [InfoPlist(displayName: "TestBundle", identifier: "com.test.example")]
        )
        
        let temporaryDirectory = try createTemporaryDirectory()
        let outputDirectory = temporaryDirectory.appendingPathComponent("output", isDirectory: true)
        let doccCatalogDirectory = try emptyCatalog.write(inside: temporaryDirectory)
        let htmlTemplateDirectory = try Folder.emptyHTMLTemplateDirectory.write(inside: temporaryDirectory)
        
        SetEnvironmentVariable(TemplateOption.environmentVariableKey, htmlTemplateDirectory.path)
        defer {
            UnsetEnvironmentVariable(TemplateOption.environmentVariableKey)
        }
        
        let convertCommand = try Docc.Convert.parse(
            [
                doccCatalogDirectory.path,
                "--output-path", outputDirectory.path,
            ]
        )
        
        var action = try ConvertAction(fromConvertCommand: convertCommand)
        _ = try action.perform(logHandle: .none)
    }
    
    func emitEmptySymbolGraph(moduleName: String, destination: URL) throws {
        let symbolGraph = SymbolGraph(
            metadata: .init(
                formatVersion: .init(major: 0, minor: 0, patch: 1),
                generator: "unit-test"
            ),
            module: .init(
                name: moduleName,
                platform: .init()
            ),
            symbols: [],
            relationships: []
        )
        
        // Create a unique subfolder to place the symbol graph in
        // in case we're emitting multiple symbol graphs with the same filename.
        let uniqueSubfolder = destination.appendingPathComponent(
            ProcessInfo.processInfo.globallyUniqueString
        )
        try FileManager.default.createDirectory(
            at: uniqueSubfolder,
            withIntermediateDirectories: false
        )
        
        try JSONEncoder().encode(symbolGraph).write(
            to: uniqueSubfolder
                .appendingPathComponent(moduleName, isDirectory: false)
                .appendingPathExtension("symbols.json")
        )
    }

    // Tests that when `docc convert` is given input that produces multiple pages at the same path
    // on disk it does not throw an error when attempting to transform it for static hosting. (94311195)
    func testConvertDocCCatalogThatProducesMultipleDocumentationPagesAtTheSamePathDoesNotThrowError() throws {
        let temporaryDirectory = try createTemporaryDirectory()
        
        let catalogURL = try Folder(
            name: "unit-test.docc",
            content: [
                InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
            ]
        ).write(inside: temporaryDirectory)
        try emitEmptySymbolGraph(moduleName: "docc", destination: catalogURL)
        try emitEmptySymbolGraph(moduleName: "DocC", destination: catalogURL)
        
        let htmlTemplateDirectory = try Folder.emptyHTMLTemplateDirectory.write(
            inside: temporaryDirectory
        )
        
        let targetDirectory = temporaryDirectory.appendingPathComponent("target.doccarchive", isDirectory: true)
        let dataProvider = try LocalFileSystemDataProvider(rootURL: catalogURL)
        
        var action = try ConvertAction(
            documentationBundleURL: catalogURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: htmlTemplateDirectory,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: dataProvider,
            fileManager: FileManager.default,
            temporaryDirectory: createTemporaryDirectory(),
            transformForStaticHosting: true
        )
        
        XCTAssertNoThrow(try action.performAndHandleResult(logHandle: .none))
    }
    func testConvertWithCustomTemplates() throws {
        let info = InfoPlist(displayName: "TestConvertWithCustomTemplates", identifier: "com.test.example")
        let index = TextFile(name: "index.html", utf8Content: """
        <!DOCTYPE html>
        <html lang="en">
            <head>
                <title>Test</title>
            </head>
            <body data-color-scheme="auto"><p>hello</p></body>
        </html>
        """)
        let template = Folder(name: "template", content: [index])
        let header = TextFile(name: "header.html", utf8Content: """
        <style>
            header { background-color: rebeccapurple; }
        </style>
        <header>custom header</header>
        """)
        let footer = TextFile(name: "footer.html", utf8Content: """
        <style>
            footer { background-color: #fff; }
        </style>
        <footer>custom footer</footer>
        """)
        let bundle = Folder(name: "TestConvertWithCustomTemplates.docc", content: [
            info,
            header,
            footer,
        ])

        let tempURL = try createTemporaryDirectory()
        let targetURL = tempURL.appendingPathComponent("target", isDirectory: true)

        let bundleURL = try bundle.write(inside: tempURL)
        let templateURL = try template.write(inside: tempURL)

        let dataProvider = try LocalFileSystemDataProvider(rootURL: bundleURL)

        var action = try ConvertAction(
            documentationBundleURL: bundleURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetURL,
            htmlTemplateDirectory: templateURL,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: dataProvider,
            fileManager: FileManager.default,
            temporaryDirectory: createTemporaryDirectory(),
            experimentalEnableCustomTemplates: true
        )
        let result = try action.perform(logHandle: .none)

        // The custom template contents should be wrapped in <template> tags and
        // prepended to the <body>
        let expectedIndex = TextFile(name: "index.html", utf8Content: """
        <!DOCTYPE html>
        <html lang="en">
            <head>
                <title>Test</title>
            </head>
            <body data-color-scheme="auto"><template id="custom-footer">\(footer.utf8Content)</template><template id="custom-header">\(header.utf8Content)</template><p>hello</p></body>
        </html>
        """)
        let expectedOutput = Folder(name: ".docc-build", content: [expectedIndex])
        expectedOutput.assertExist(at: result.outputs[0], fileManager: FileManager.default)
    }

    // Tests that custom templates are injected into the extra index.html files generated for static hosting.
    func testConvertWithCustomTemplatesForStaticHosting() throws {
        let info = InfoPlist(displayName: "TestConvertWithCustomTemplatesForStaticHosting", identifier: "com.test.example")
        let index = TextFile(name: "index.html", utf8Content: """
        <!DOCTYPE html>
        <html lang="en">
            <head>
                <title>Test</title>
            </head>
            <body data-color-scheme="auto"><p>test for custom templates in static hosting</p></body>
        </html>
        """)
        let template = Folder(name: "template", content: [index])
        let header = TextFile(name: "header.html", utf8Content: """
        <header>custom text for header</header>
        """)
        let footer = TextFile(name: "footer.html", utf8Content: """
        <footer>custom text for footer</footer>
        """)

        // Adding this page will generate a file named:
        // /documentation/testconvertwithcustomtemplatesforstatichosting/index.html
        // ...which should have the custom header/footer if they're propagated correctly.
        let technologyPage = TextFile(name: "TestConvertWithCustomTemplatesForStaticHosting.md", utf8Content: """
        # TestConvertWithCustomTemplatesForStaticHosting

        @Metadata {
            @TechnologyRoot
        }

        An abstract.

        ## Overview

        Text for a paragraph.
        """)
        let bundle = Folder(name: "TestConvertWithCustomTemplatesForStaticHosting.docc", content: [
            info,
            header,
            footer,
            technologyPage
        ])

        let tempURL = try createTemporaryDirectory()
        let targetURL = tempURL.appendingPathComponent("target", isDirectory: true)

        let bundleURL = try bundle.write(inside: tempURL)
        let templateURL = try template.write(inside: tempURL)

        let dataProvider = try LocalFileSystemDataProvider(rootURL: bundleURL)

        var action = try ConvertAction(
            documentationBundleURL: bundleURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetURL,
            htmlTemplateDirectory: templateURL,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: dataProvider,
            fileManager: FileManager.default,
            temporaryDirectory: createTemporaryDirectory(),
            experimentalEnableCustomTemplates: true,
            transformForStaticHosting: true
        )
        let result = try action.perform(logHandle: .none)

        // The custom template contents should be wrapped in <template> tags and
        // prepended to the <body>
        let expectedIndex = TextFile(name: "index.html", utf8Content: """
        <!DOCTYPE html>
        <html lang="en">
            <head>
                <title>Test</title>
            </head>
            <body data-color-scheme="auto"><template id="custom-footer">\(footer.utf8Content)</template><template id="custom-header">\(header.utf8Content)</template><p>test for custom templates in static hosting</p></body>
        </html>
        """)
        
        let expectedTechnologyFolder = Folder(name: "TestConvertWithCustomTemplatesForStaticHosting".lowercased(), content: [expectedIndex])
        let expectedDocsFolder = Folder(name: "documentation", content: [expectedTechnologyFolder])
        let expectedOutput = Folder(name: ".docc-build", content: [expectedDocsFolder])
        expectedOutput.assertExist(at: result.outputs[0], fileManager: FileManager.default)
    }

    func testConvertWithThemeSettings() throws {
        let info = InfoPlist(displayName: "TestConvertWithThemeSettings", identifier: "com.test.example")
        let index = TextFile(name: "index.html", utf8Content: """
        <!DOCTYPE html>
        <html lang="en">
            <head>
                <title>Test</title>
            </head>
            <body data-color-scheme="auto"><p>hello</p></body>
        </html>
        """)
        let themeSettings = TextFile(name: "theme-settings.json", utf8Content: """
        {
          "meta": {},
          "theme": {
            "colors": {
              "text": "#ff0000"
            }
          },
          "features": {}
        }
        """)
        let template = Folder(name: "template", content: [index])
        let bundle = Folder(name: "TestConvertWithThemeSettings.docc", content: [
            info,
            themeSettings,
        ])

        let tempURL = try createTemporaryDirectory()
        let targetURL = tempURL.appendingPathComponent("target", isDirectory: true)

        let bundleURL = try bundle.write(inside: tempURL)
        let templateURL = try template.write(inside: tempURL)

        let dataProvider = try LocalFileSystemDataProvider(rootURL: bundleURL)

        var action = try ConvertAction(
            documentationBundleURL: bundleURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetURL,
            htmlTemplateDirectory: templateURL,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: dataProvider,
            fileManager: FileManager.default,
            temporaryDirectory: createTemporaryDirectory(),
            experimentalEnableCustomTemplates: true
        )
        let result = try action.perform(logHandle: .none)

        let expectedOutput = Folder(name: ".docc-build", content: [
            index,
            themeSettings,
        ])
        expectedOutput.assertExist(at: result.outputs[0], fileManager: FileManager.default)
    }
    
    func testTreatWarningsAsErrors() throws {
        let bundle = Folder(name: "unit-test.docc", content: [
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
            CopyOfFile(original: symbolGraphFile, newName: "MyKit.symbols.json"),
            TextFile(name: "Article.md", utf8Content: """
            Bad title

            This article has a malformed title and can't be analyzed, so it
            produces one warning.
            """),
        ])

        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath)
            .appendingPathComponent("target", isDirectory: true)

        // Test DiagnosticEngine with "treatWarningsAsErrors" set to false
        do {
            let engine = DiagnosticEngine(treatWarningsAsErrors: false)
            var action = try ConvertAction(
                documentationBundleURL: bundle.absoluteURL,
                outOfProcessResolver: nil,
                analyze: true,
                targetDirectory: targetDirectory,
                htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
                emitDigest: false,
                currentPlatforms: nil,
                dataProvider: testDataProvider,
                fileManager: testDataProvider,
                temporaryDirectory: testDataProvider.uniqueTemporaryDirectory(),
                diagnosticEngine: engine
            )
            let result = try action.perform(logHandle: .none)
            XCTAssertEqual(engine.problems.count, 1)
            XCTAssertTrue(engine.problems.contains(where: { $0.diagnostic.severity == .warning }))
            XCTAssertFalse(result.didEncounterError)
        }
        
        // Test DiagnosticEngine with "treatWarningsAsErrors" set to true
        do {
            let engine = DiagnosticEngine(treatWarningsAsErrors: true)
            var action = try ConvertAction(
                documentationBundleURL: bundle.absoluteURL,
                outOfProcessResolver: nil,
                analyze: true,
                targetDirectory: targetDirectory,
                htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
                emitDigest: false,
                currentPlatforms: nil,
                dataProvider: testDataProvider,
                fileManager: testDataProvider,
                temporaryDirectory: testDataProvider.uniqueTemporaryDirectory(),
                diagnosticEngine: engine
            )
            let result = try action.perform(logHandle: .none)
            XCTAssertEqual(engine.problems.count, 1)
            XCTAssertTrue(result.didEncounterError)
        }
        
        do {
            var action = try ConvertAction(
                documentationBundleURL: bundle.absoluteURL,
                outOfProcessResolver: nil,
                analyze: true,
                targetDirectory: targetDirectory,
                htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
                emitDigest: false,
                currentPlatforms: nil,
                dataProvider: testDataProvider,
                fileManager: testDataProvider,
                temporaryDirectory: testDataProvider.uniqueTemporaryDirectory(),
                diagnosticEngine: nil,
                treatWarningsAsErrors: true
            )
            let result = try action.perform(logHandle: .none)
            XCTAssertTrue(result.didEncounterError)
        }

    }

    func testConvertWithoutBundleDerivesDisplayNameAndIdentifierFromSingleModuleSymbolGraph() throws {
        let myKitSymbolGraph = Bundle.module.url(forResource: "TestBundle", withExtension: "docc", subdirectory: "Test Bundles")!
            .appendingPathComponent("mykit-iOS.symbols.json")
        
        XCTAssert(FileManager.default.fileExists(atPath: myKitSymbolGraph.path))
        let symbolGraphFiles = Folder(name: "Not-a-doc-bundle", content: [
            CopyOfFile(original: myKitSymbolGraph, newName: "MyKit.symbols.json"),
        ])
        
        let outputLocation = Folder(name: "output", content: [])
        
        let testDataProvider = try TestFileSystem(folders: [Folder.emptyHTMLTemplateDirectory, symbolGraphFiles, outputLocation])
        
        var action = try ConvertAction(
            documentationBundleURL: nil,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: outputLocation.absoluteURL,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: nil,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory(),
            bundleDiscoveryOptions: BundleDiscoveryOptions(
                additionalSymbolGraphFiles: [URL(fileURLWithPath: "/Not-a-doc-bundle/MyKit.symbols.json")]
            )
        )
        
        XCTAssert(action.context.registeredBundles.isEmpty)
        XCTAssertNoThrow(try action.perform(logHandle: .none))

        XCTAssertEqual(action.context.registeredBundles.count, 1)
        let bundle = try XCTUnwrap(action.context.registeredBundles.first, "Should have registered the generated test bundle.")
        XCTAssertEqual(bundle.displayName, "MyKit")
        XCTAssertEqual(bundle.identifier, "MyKit")
    }
    
    func testConvertWithoutBundleErrorsForMultipleModulesSymbolGraph() throws {
        let testBundle = Bundle.module.url(forResource: "TestBundle", withExtension: "docc", subdirectory: "Test Bundles")!
        let myKitSymbolGraph = testBundle
            .appendingPathComponent("mykit-iOS.symbols.json")
        let sideKitSymbolGraph = testBundle
            .appendingPathComponent("sidekit.symbols.json")
        
        XCTAssert(FileManager.default.fileExists(atPath: myKitSymbolGraph.path))
        XCTAssert(FileManager.default.fileExists(atPath: sideKitSymbolGraph.path))
        let symbolGraphFiles = Folder(name: "Not-a-doc-bundle", content: [
            CopyOfFile(original: myKitSymbolGraph, newName: "MyKit.symbols.json"),
            CopyOfFile(original: sideKitSymbolGraph, newName: "SideKit.symbols.json")
        ])
        
        let outputLocation = Folder(name: "output", content: [])
        
        let testDataProvider = try TestFileSystem(
            folders: [Folder.emptyHTMLTemplateDirectory, symbolGraphFiles, outputLocation]
        )
        
        var infoPlistFallbacks = [String: Any]()
        infoPlistFallbacks["CFBundleIdentifier"] = "com.example.test"
        
        var action = try ConvertAction(
            documentationBundleURL: nil,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: outputLocation.absoluteURL,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: nil,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory(),
            bundleDiscoveryOptions: BundleDiscoveryOptions(
                infoPlistFallbacks: infoPlistFallbacks,
                additionalSymbolGraphFiles: [
                    URL(fileURLWithPath: "/Not-a-doc-bundle/MyKit.symbols.json"),
                    URL(fileURLWithPath: "/Not-a-doc-bundle/SideKit.symbols.json")
                ]
            )
        )
        
        let logStorage = LogHandle.LogStorage()
        XCTAssertThrowsError(try action.perform(logHandle: .memory(logStorage))) { error in
            XCTAssertEqual(error.localizedDescription, """
            The information provided as command line arguments is not enough to generate a documentation bundle:
            
            Missing value for 'CFBundleDisplayName'.
            Use the '--fallback-display-name' argument or add 'CFBundleDisplayName' to the bundle Info.plist.
            
            """)
        }
    }
    
    func testConvertWithBundleDerivesDisplayNameFromBundle() throws {
        let emptyDoccCatalog = try createTemporaryDirectory(named: "Something.docc")
        let outputLocation = try createTemporaryDirectory(named: "output")

        var infoPlistFallbacks = [String: Any]()
        infoPlistFallbacks["CFBundleIdentifier"] = "com.example.test"

        var action = try ConvertAction(
            documentationBundleURL: emptyDoccCatalog,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: outputLocation.absoluteURL,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.write(inside: createTemporaryDirectory(named: "template")),
            emitDigest: false,
            currentPlatforms: nil,
            temporaryDirectory: createTemporaryDirectory(),
            bundleDiscoveryOptions: BundleDiscoveryOptions(
                infoPlistFallbacks: infoPlistFallbacks,
                additionalSymbolGraphFiles: []
            )
        )
        XCTAssert(action.context.registeredBundles.isEmpty)
        XCTAssertNoThrow(try action.perform(logHandle: .none))

        XCTAssertEqual(action.context.registeredBundles.count, 1)
        let bundle = try XCTUnwrap(action.context.registeredBundles.first, "Should have registered the generated test bundle.")
        XCTAssertEqual(bundle.displayName, "Something")
        XCTAssertEqual(bundle.identifier, "com.example.test")
    }

    private func uniformlyPrintDiagnosticMessages(_ problems: [Problem]) -> String {
        return problems.sorted(by: { (lhs, rhs) -> Bool in
            guard lhs.diagnostic.identifier != rhs.diagnostic.identifier else {
                return lhs.diagnostic.summary < rhs.diagnostic.summary
            }
            return lhs.diagnostic.identifier < rhs.diagnostic.identifier
        }) .map { DiagnosticConsoleWriter.formattedDescription(for: $0.diagnostic) }.sorted().joined(separator: "\n")
    }
    
    // Tests that when converting a catalog with no technology root a warning is raised (r93371988)
    func testConvertWithNoTechnologyRoot() throws {
        func problemsFromConverting(_ catalogContent: [File]) throws -> [Problem] {
            let catalog = Folder(name: "unit-test.docc", content: catalogContent)
            let testDataProvider = try TestFileSystem(folders: [catalog, Folder.emptyHTMLTemplateDirectory])
            let engine = DiagnosticEngine()
            var action = try ConvertAction(
                documentationBundleURL: catalog.absoluteURL,
                outOfProcessResolver: nil,
                analyze: false,
                targetDirectory: URL(fileURLWithPath: "/output"),
                htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
                emitDigest: false,
                currentPlatforms: nil,
                dataProvider: testDataProvider,
                fileManager: testDataProvider,
                temporaryDirectory: URL(fileURLWithPath: "/tmp"),
                diagnosticEngine: engine
            )
            _ = try action.perform(logHandle: .none)
            return engine.problems
        }
        
        let onlyTutorialArticleProblems = try problemsFromConverting([
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
            TextFile(name: "Article.tutorial", utf8Content: """
                @Article(time: 20) {
                   @Intro(title: "Slothy Tutorials") {
                      This is an abstract for the intro.
                   }
                }
                """
            ),
        ])
        XCTAssert(onlyTutorialArticleProblems.contains(where: {
            $0.diagnostic.identifier == "org.swift.docc.MissingTableOfContents"
        }))
        
        let tutorialTableOfContentProblem = try problemsFromConverting([
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
            TextFile(name: "table-of-contents.tutorial", utf8Content: """
                """
            ),
            TextFile(name: "article.tutorial", utf8Content: """
                @Article(time: 20) {
                   @Intro(title: "Slothy Tutorials") {
                      This is an abstract for the intro.
                   }
                }
                """
            ),
        ])
        XCTAssert(tutorialTableOfContentProblem.contains(where: {
            $0.diagnostic.identifier == "org.swift.docc.MissingTableOfContents"
        }))
        
        let incompleteTutorialFile = try problemsFromConverting([
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
            TextFile(name: "article.tutorial", utf8Content: """
                @Chapter(name: "SlothCreator Essentials") {
                    @Image(source: "chapter1-slothcreatorEssentials.png", alt: "A wireframe of an app interface that has an outline of a sloth and four buttons below the sloth. The buttons display the following symbols, from left to right: snowflake, fire, wind, and lightning.")
                    
                    Create custom sloths and edit their attributes and powers using SlothCreator.
                    
                    @TutorialReference(tutorial: "doc:Creating-Custom-Sloths")
                }
                """
            ),
        ])
        XCTAssert(incompleteTutorialFile.contains(where: {
            $0.diagnostic.identifier == "org.swift.docc.missingTopLevelChild"
        }))
        XCTAssertFalse(incompleteTutorialFile.contains(where: {
            $0.diagnostic.identifier == "org.swift.docc.MissingTableOfContents"
        }))
    }
    
    func testWrittenDiagnosticsAfterConvert() throws {
        let bundle = Folder(name: "unit-test.docc", content: [
            InfoPlist(displayName: "TestBundle", identifier: "com.test.example"),
            TextFile(name: "Documentation.md", utf8Content: """
            # ``ModuleThatDoesNotExist``

            This will result in two errors from two different phases of the build
            """)
        ])
        let testDataProvider = try TestFileSystem(folders: [bundle, Folder.emptyHTMLTemplateDirectory])
        let targetDirectory = URL(fileURLWithPath: testDataProvider.currentDirectoryPath).appendingPathComponent("target", isDirectory: true)
        let diagnosticFile = try createTemporaryDirectory().appendingPathComponent("test-diagnostics.json")
        let fileConsumer = DiagnosticFileWriter(outputPath: diagnosticFile)
        
        let engine = DiagnosticEngine()
        engine.add(fileConsumer)
        
        let logStorage = LogHandle.LogStorage()
        let consoleConsumer = DiagnosticConsoleWriter(LogHandle.memory(logStorage), formattingOptions: [], baseURL: nil, highlight: false)
        engine.add(consoleConsumer)
        
        var action = try ConvertAction(
            documentationBundleURL: bundle.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetDirectory,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: testDataProvider,
            fileManager: testDataProvider,
            temporaryDirectory: testDataProvider.uniqueTemporaryDirectory(),
            diagnosticEngine: engine
        )
        
        let _ = try action.perform(logHandle: .none)
        XCTAssertEqual(engine.problems.count, 1)
        
        XCTAssert(FileManager.default.fileExists(atPath: diagnosticFile.path))
        
        let diagnosticFileContent = try JSONDecoder().decode(DiagnosticFile.self, from: Data(contentsOf: diagnosticFile))
        XCTAssertEqual(diagnosticFileContent.diagnostics.count, 1)
        
        XCTAssertEqual(diagnosticFileContent.diagnostics.map(\.summary).sorted(), [
            "No symbol matched 'ModuleThatDoesNotExist'. Can't resolve 'ModuleThatDoesNotExist'."
        ].sorted())
        
        let logLines = logStorage.text.splitByNewlines
        XCTAssertEqual(logLines.filter { $0.hasPrefix("warning: No symbol matched 'ModuleThatDoesNotExist'. Can't resolve 'ModuleThatDoesNotExist'.") }.count, 1)
    }
    
    func testEncodedImagePaths() throws {
        let catalog = Folder(name: "unit-test.docc", content: [
            TextFile(name: "Something.md", utf8Content: """
            # Something
            
            This article links to some assets
            
            ![Some alt text](image-name)
            """),
            
            // Image variants
            DataFile(name: "image-name.png", data: Data()),
            DataFile(name: "image-name~dark.png", data: Data()),
            DataFile(name: "image-name@2x.png", data: Data()),
            DataFile(name: "image-name~dark@2x.png", data: Data()),
        ])
    
        let fileSystem = try TestFileSystem(folders: [catalog])
        let targetURL = URL(fileURLWithPath: "/Output.doccarchive")
        
        var action = try ConvertAction(
            documentationBundleURL: catalog.absoluteURL,
            outOfProcessResolver: nil,
            analyze: false,
            targetDirectory: targetURL,
            htmlTemplateDirectory: Folder.emptyHTMLTemplateDirectory.absoluteURL,
            emitDigest: false,
            currentPlatforms: nil,
            dataProvider: fileSystem,
            fileManager: fileSystem,
            temporaryDirectory: fileSystem.uniqueTemporaryDirectory()
        )
        
        let result = try action.perform(logHandle: .none)
        XCTAssertEqual(result.outputs, [targetURL])
        
        XCTAssertEqual(fileSystem.dump(subHierarchyFrom: targetURL.path), """
        Output.doccarchive/
        ├─ data/
        │  ╰─ documentation/
        │     ╰─ something.json
        ├─ downloads/
        │  ╰─ unit-test/
        ├─ images/
        │  ╰─ unit-test/
        │     ├─ image-name.png
        │     ├─ image-name@2x.png
        │     ├─ image-name~dark.png
        │     ╰─ image-name~dark@2x.png
        ├─ metadata.json
        ╰─ videos/
           ╰─ unit-test/
        """)
        
        XCTAssert(fileSystem.fileExists(atPath: targetURL.appendingPathComponent("images/unit-test/image-name.png").path))
        let pageURL = targetURL.appendingPathComponent("data/documentation/something.json")
        XCTAssert(fileSystem.fileExists(atPath: pageURL.path))
        
        let renderNode = try JSONDecoder().decode(RenderNode.self, from: fileSystem.contentsOfURL(pageURL))
        
        XCTAssertEqual(renderNode.references.keys.sorted(), ["image-name"])
        let imageReference = try XCTUnwrap(renderNode.references["image-name"] as? ImageReference)
        
        XCTAssertEqual(imageReference.altText, "Some alt text")
        XCTAssertEqual(imageReference.asset.variants.values.map(\.absoluteString).sorted(), [
            "/images/unit-test/image-name.png",
            "/images/unit-test/image-name@2x.png",
            "/images/unit-test/image-name~dark.png",
            "/images/unit-test/image-name~dark@2x.png"
        ])
    }
    
    #endif
}

private extension LinkDestinationSummary {
    // A convenience initializer for test data.
    init(
        kind: DocumentationNode.Kind,
        relativePresentationURL: URL,
        referenceURL: URL,
        title: String,
        language: SourceLanguage,
        abstract: String?,
        taskGroups: [TaskGroup],
        usr: String? = nil,
        availableLanguages: Set<SourceLanguage>,
        platforms: [PlatformAvailability]?,
        topicImages: [TopicImage]?,
        references: [RenderReference]?,
        redirects: [URL]?
    ) {
        self.init(
            kind: kind,
            language: language,
            relativePresentationURL: relativePresentationURL,
            referenceURL: referenceURL,
            title: title,
            abstract: abstract.map { [.text($0)] },
            availableLanguages: availableLanguages,
            platforms: platforms,
            taskGroups: taskGroups,
            usr: usr,
            declarationFragments: nil,
            redirects: redirects,
            topicImages: topicImages,
            references: references,
            variants: []
        )
    }
}

private extension ImageReference {
    // A convenience initializer for test data.
    init(name: String, altText: String?, userInterfaceStyle: UserInterfaceStyle, displayScale: DisplayScale) {
        var asset = DataAsset()
        asset.register(
            URL(string: "/images/\(name)")!,
            with: DataTraitCollection(userInterfaceStyle: userInterfaceStyle, displayScale: displayScale)
        )
        self.init(
            identifier: RenderReferenceIdentifier(name),
            altText: altText,
            imageAsset: asset
        )
    }
}

extension File {
    /// A URL of the file node if it was located in the root of the file system.
    var absoluteURL: URL { return URL(string: "/\(name)")! }
}

extension Folder {
    /// Recreates a disk-based directory as a `Folder`.
    static func createFromDisk(url: URL) throws -> Folder {
        var content = [File]()
        if let enumerator = FileManager.default.enumerator(at: url, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles, .skipsSubdirectoryDescendants]) {
            for case let fileURL as URL in enumerator {
                if FileManager.default.fileExists(atPath: fileURL.path), fileURL.hasDirectoryPath {
                    content.append(try createFromDisk(url: fileURL))
                } else {
                    if fileURL.lastPathComponent == "Info.plist",
                       let infoPlistData = FileManager.default.contents(atPath: fileURL.path),
                       let infoPlist = try? PropertyListSerialization.propertyList(from: infoPlistData, options: [], format: nil) as? [String: Any],
                       let displayName = infoPlist["CFBundleDisplayName"] as? String,
                       let identifier = infoPlist["CFBundleIdentifier"] as? String {
                        content.append(InfoPlist(displayName: displayName, identifier: identifier))
                    } else {
                        content.append(CopyOfFile(original: fileURL, newName: fileURL.lastPathComponent))
                    }
                }
            }
        }
        return Folder(name: url.lastPathComponent, content: content)
    }
}