summaryrefslogtreecommitdiff
path: root/src/mongo/idl/idl_test.cpp
blob: 888e30d5dca6de3c6042e5de7c0df752f951d591 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
/**
 *    Copyright (C) 2018-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the Server Side Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#include "mongo/platform/basic.h"

#include <limits>

#include "mongo/bson/bsonmisc.h"
#include "mongo/bson/bsonobj.h"
#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/bson/bsontypes.h"
#include "mongo/bson/oid.h"
#include "mongo/db/auth/authorization_contract.h"
#include "mongo/db/auth/resource_pattern.h"
#include "mongo/db/multitenancy_gen.h"
#include "mongo/db/write_concern_options_gen.h"
#include "mongo/idl/server_parameter_test_util.h"
#include "mongo/idl/unittest_gen.h"
#include "mongo/rpc/op_msg.h"
#include "mongo/unittest/bson_test_util.h"
#include "mongo/unittest/unittest.h"

using namespace mongo::idl::test;
using namespace mongo::idl::import;

namespace mongo {

void mongo::idl::test::checkValuesEqual(StructWithValidator* structToValidate) {
    uassert(
        6253512, "Values not equal", structToValidate->getFirst() == structToValidate->getSecond());
}

namespace {

bool isEquals(ConstDataRange left, const std::vector<uint8_t>& right) {
    ConstDataRange rightCDR(right);
    return std::equal(left.data(),
                      left.data() + left.length(),
                      rightCDR.data(),
                      rightCDR.data() + rightCDR.length());
}

bool isEquals(const std::array<uint8_t, 16>& left, const std::array<uint8_t, 16>& right) {
    return std::equal(
        left.data(), left.data() + left.size(), right.data(), right.data() + right.size());
}

bool isEqual(const ConstDataRange& left, const ConstDataRange& right) {
    return std::equal(
        left.data(), left.data() + left.length(), right.data(), right.data() + right.length());
}

bool isEquals(const std::vector<ConstDataRange>& left,
              const std::vector<std::vector<std::uint8_t>>& rightVector) {
    auto right = transformVector(rightVector);
    return std::equal(
        left.data(), left.data() + left.size(), right.data(), right.data() + right.size(), isEqual);
}

bool isEquals(const std::vector<std::array<std::uint8_t, 16>>& left,
              const std::vector<std::array<std::uint8_t, 16>>& right) {
    return std::equal(
        left.data(), left.data() + left.size(), right.data(), right.data() + right.size());
}

/**
 * Flatten an OpMsgRequest into a BSONObj.
 */
BSONObj flatten(const OpMsgRequest& msg) {
    BSONObjBuilder builder;
    builder.appendElements(msg.body);

    for (auto&& docSeq : msg.sequences) {
        builder.append(docSeq.name, docSeq.objs);
    }

    return builder.obj();
}

/**
 * Validate two OpMsgRequests are the same regardless of whether they both use DocumentSequences.
 */
void assertOpMsgEquals(const OpMsgRequest& left, const OpMsgRequest& right) {
    auto flatLeft = flatten(left);
    auto flatRight = flatten(right);

    ASSERT_BSONOBJ_EQ(flatLeft, flatRight);
}

/**
 * Validate two OpMsgRequests are the same including their DocumentSequences.
 */
void assertOpMsgEqualsExact(const OpMsgRequest& left, const OpMsgRequest& right) {

    ASSERT_BSONOBJ_EQ(left.body, right.body);

    ASSERT_EQUALS(left.sequences.size(), right.sequences.size());

    for (size_t i = 0; i < left.sequences.size(); ++i) {
        auto leftItem = left.sequences[i];
        auto rightItem = right.sequences[i];

        ASSERT_TRUE(std::equal(leftItem.objs.begin(),
                               leftItem.objs.end(),
                               rightItem.objs.begin(),
                               rightItem.objs.end(),
                               [](const BSONObj& leftBson, const BSONObj& rightBson) {
                                   return SimpleBSONObjComparator::kInstance.compare(
                                              leftBson, rightBson) == 0;
                               }));
        ASSERT_EQUALS(leftItem.name, rightItem.name);
    }
}


BSONObj appendDB(const BSONObj& obj, StringData dbName) {
    BSONObjBuilder builder;
    builder.appendElements(obj);
    builder.append("$db", dbName);
    return builder.obj();
}

template <typename T>
BSONObj serializeCmd(const T& cmd) {
    auto reply = cmd.serialize({});
    return reply.body;
}

// Use a separate function to get better error messages when types do not match.
template <typename T1, typename T2>
void assert_same_types() {
    MONGO_STATIC_ASSERT(std::is_same<T1, T2>::value);
}

template <typename ParserT, typename TestT, BSONType Test_bson_type>
void TestLoopback(TestT test_value) {
    auto testDoc = BSON("value" << test_value);
    auto element = testDoc.firstElement();
    ASSERT_EQUALS(element.type(), Test_bson_type);

    auto testStruct = ParserT::parse(IDLParserContext{"test"}, testDoc);
    assert_same_types<decltype(testStruct.getValue()), TestT>();

    // We need to use a different unittest macro for comparing obj/array.
    constexpr bool isObjectTest = std::is_same_v<TestT, const BSONObj&>;
    constexpr bool isArrayTest = std::is_same_v<TestT, const BSONArray&>;
    if constexpr (isObjectTest || isArrayTest) {
        ASSERT_BSONOBJ_EQ(testStruct.getValue(), test_value);
    } else {
        ASSERT_EQUALS(testStruct.getValue(), test_value);
    }

    // Positive: Test we can roundtrip from the just parsed document
    {
        BSONObjBuilder builder;
        testStruct.serialize(&builder);
        auto loopbackDoc = builder.obj();

        ASSERT_BSONOBJ_EQ(testDoc, loopbackDoc);
    }

    // Positive: Test we can roundtrip from the just parsed document
    {
        auto loopbackDoc = testStruct.toBSON();

        ASSERT_BSONOBJ_EQ(testDoc, loopbackDoc);
    }

    // Positive: Test we can serialize from nothing the same document
    {
        BSONObjBuilder builder;
        ParserT one_new;
        one_new.setValue(test_value);
        one_new.serialize(&builder);

        auto serializedDoc = builder.obj();
        ASSERT_BSONOBJ_EQ(testDoc, serializedDoc);

        // Validate the operator == works
        // Use ASSERT instead of ASSERT_EQ to avoid operator<<
        if constexpr (!isArrayTest) {
            // BSONArray comparison not currently implemented.
            ASSERT_TRUE(one_new == testStruct);
        }

        if constexpr (isObjectTest) {
            // Only One_plain_object implements comparison ops
            ASSERT_FALSE(one_new < testStruct);
        }
    }
}

/// Type tests:
// Positive: Test we can serialize the type out and back again
TEST(IDLOneTypeTests, TestLoopbackTest) {
    TestLoopback<One_string, StringData, String>("test_value");
    TestLoopback<One_int, std::int32_t, NumberInt>(123);
    TestLoopback<One_long, std::int64_t, NumberLong>(456);
    TestLoopback<One_double, double, NumberDouble>(3.14159);
    TestLoopback<One_bool, bool, Bool>(true);
    TestLoopback<One_objectid, const OID&, jstOID>(OID::max());
    TestLoopback<One_date, const Date_t&, Date>(Date_t::now());
    TestLoopback<One_timestamp, const Timestamp&, bsonTimestamp>(Timestamp::max());
    TestLoopback<One_plain_object, const BSONObj&, Object>(BSON("Hello"
                                                                << "World"));
    TestLoopback<One_plain_array, const BSONArray&, Array>(BSON_ARRAY("Hello"
                                                                      << "World"));
}

// Test we compare an object with optional BSONObjs correctly
TEST(IDLOneTypeTests, TestOptionalObjectTest) {
    IDLParserContext ctxt("root");

    auto testValue = BSON("Hello"
                          << "World");
    auto testDoc = BSON("value" << testValue << "value2" << testValue << "opt_value" << testValue);

    auto element = testDoc.firstElement();
    ASSERT_EQUALS(element.type(), Object);

    auto testStruct = One_plain_optional_object::parse(ctxt, testDoc);
    assert_same_types<decltype(testStruct.getValue()), const BSONObj&>();

    ASSERT_BSONOBJ_EQ(testStruct.getValue(), testValue);

    One_plain_optional_object testEmptyStruct;
    One_plain_optional_object testEmptyStruct2;

    // Make sure we match the operator semantics for std::optional
    ASSERT_TRUE(testEmptyStruct == testEmptyStruct2);
    ASSERT_FALSE(testEmptyStruct != testEmptyStruct2);
    ASSERT_FALSE(testEmptyStruct < testEmptyStruct2);

    ASSERT_FALSE(testEmptyStruct == testStruct);
    ASSERT_TRUE(testEmptyStruct != testStruct);
    ASSERT_TRUE(testEmptyStruct < testStruct);
    ASSERT_FALSE(testStruct < testEmptyStruct);

    ASSERT_TRUE(testStruct == testStruct);
    ASSERT_FALSE(testStruct != testStruct);
    ASSERT_FALSE(testStruct < testStruct);
}

// Test if a given value for a given bson document parses successfully or fails if the bson types
// mismatch.
template <typename ParserT, BSONType Parser_bson_type, typename TestT, BSONType Test_bson_type>
void TestParse(TestT test_value) {
    IDLParserContext ctxt("root");

    auto testDoc = BSON("value" << test_value);

    auto element = testDoc.firstElement();
    ASSERT_EQUALS(element.type(), Test_bson_type);

    if (Parser_bson_type != Test_bson_type) {
        ASSERT_THROWS(ParserT::parse(ctxt, testDoc), AssertionException);
    } else {
        (void)ParserT::parse(ctxt, testDoc);
    }
}

// Test each of types either fail or succeeded based on the parser's bson type
template <typename ParserT, BSONType Parser_bson_type>
void TestParsers() {
    TestParse<ParserT, Parser_bson_type, StringData, String>("test_value");
    TestParse<ParserT, Parser_bson_type, std::int32_t, NumberInt>(123);
    TestParse<ParserT, Parser_bson_type, std::int64_t, NumberLong>(456);
    TestParse<ParserT, Parser_bson_type, double, NumberDouble>(3.14159);
    TestParse<ParserT, Parser_bson_type, bool, Bool>(true);
    TestParse<ParserT, Parser_bson_type, OID, jstOID>(OID::max());
    TestParse<ParserT, Parser_bson_type, Date_t, Date>(Date_t::now());
    TestParse<ParserT, Parser_bson_type, Timestamp, bsonTimestamp>(Timestamp::max());
}

// Negative: document with wrong types for required field
TEST(IDLOneTypeTests, TestNegativeWrongTypes) {
    TestParsers<One_string, String>();
    TestParsers<One_int, NumberInt>();
    TestParsers<One_long, NumberLong>();
    TestParsers<One_double, NumberDouble>();
    TestParsers<One_bool, Bool>();
    TestParsers<One_objectid, jstOID>();
    TestParsers<One_date, Date>();
    TestParsers<One_timestamp, bsonTimestamp>();
}

// Negative: document with wrong types for required field
TEST(IDLOneTypeTests, TestNegativeRequiredNullTypes) {
    TestParse<One_string, String, NullLabeler, jstNULL>(BSONNULL);
    TestParse<One_int, NumberInt, NullLabeler, jstNULL>(BSONNULL);
    TestParse<One_long, NumberLong, NullLabeler, jstNULL>(BSONNULL);
    TestParse<One_double, NumberDouble, NullLabeler, jstNULL>(BSONNULL);
    TestParse<One_bool, Bool, NullLabeler, jstNULL>(BSONNULL);
    TestParse<One_objectid, jstOID, NullLabeler, jstNULL>(BSONNULL);
    TestParse<One_date, Date, NullLabeler, jstNULL>(BSONNULL);
    TestParse<One_timestamp, bsonTimestamp, NullLabeler, jstNULL>(BSONNULL);
}

// Negative: document with wrong types for required field
TEST(IDLOneTypeTests, TestNegativeRequiredUndefinedTypes) {
    TestParse<One_string, String, UndefinedLabeler, Undefined>(BSONUndefined);
    TestParse<One_int, NumberInt, UndefinedLabeler, Undefined>(BSONUndefined);
    TestParse<One_long, NumberLong, UndefinedLabeler, Undefined>(BSONUndefined);
    TestParse<One_double, NumberDouble, UndefinedLabeler, Undefined>(BSONUndefined);
    TestParse<One_bool, Bool, UndefinedLabeler, Undefined>(BSONUndefined);
    TestParse<One_objectid, jstOID, UndefinedLabeler, Undefined>(BSONUndefined);
    TestParse<One_date, Date, UndefinedLabeler, Undefined>(BSONUndefined);
    TestParse<One_timestamp, bsonTimestamp, UndefinedLabeler, Undefined>(BSONUndefined);
}


// Mixed: test a type that accepts multiple bson types
TEST(IDLOneTypeTests, TestSafeInt64) {
    TestParse<One_safeint64, NumberInt, StringData, String>("test_value");
    TestParse<One_safeint64, NumberInt, std::int32_t, NumberInt>(123);
    TestParse<One_safeint64, NumberLong, std::int64_t, NumberLong>(456);
    TestParse<One_safeint64, NumberDouble, double, NumberDouble>(3.14159);
    TestParse<One_safeint64, NumberInt, bool, Bool>(true);
    TestParse<One_safeint64, NumberInt, OID, jstOID>(OID::max());
    TestParse<One_safeint64, NumberInt, Date_t, Date>(Date_t::now());
    TestParse<One_safeint64, NumberInt, Timestamp, bsonTimestamp>(Timestamp::max());
}

// Mixed: test a type that accepts NamespaceString
TEST(IDLOneTypeTests, TestNamespaceString) {
    IDLParserContext ctxt("root");

    auto testDoc = BSON(One_namespacestring::kValueFieldName << "foo.bar");

    auto element = testDoc.firstElement();
    ASSERT_EQUALS(element.type(), String);

    auto testStruct = One_namespacestring::parse(ctxt, testDoc);
    assert_same_types<decltype(testStruct.getValue()), const NamespaceString&>();

    ASSERT_EQUALS(testStruct.getValue(), NamespaceString::createNamespaceString_forTest("foo.bar"));

    // Positive: Test we can roundtrip from the just parsed document
    {
        BSONObjBuilder builder;
        testStruct.serialize(&builder);
        auto loopbackDoc = builder.obj();

        ASSERT_BSONOBJ_EQ(testDoc, loopbackDoc);
    }

    // Positive: Test we can serialize from nothing the same document
    {
        BSONObjBuilder builder;
        One_namespacestring one_new;
        one_new.setValue(NamespaceString::createNamespaceString_forTest("foo.bar"));
        one_new.serialize(&builder);

        auto serializedDoc = builder.obj();
        ASSERT_BSONOBJ_EQ(testDoc, serializedDoc);
    }

    // Negative: invalid namespace
    {
        auto testBadDoc = BSON("value" << StringData("foo\0bar", 7));

        ASSERT_THROWS(One_namespacestring::parse(ctxt, testBadDoc), AssertionException);
    }
}

// Positive: Test base64 encoded strings.
TEST(IDLOneTypeTests, TestBase64StringPositive) {
    auto doc = BSON("basic"
                    << "ABCD+/0="
                    << "url"
                    << "1234-_0");
    auto parsed = Two_base64string::parse(IDLParserContext{"base64"}, doc);
    ASSERT_EQ(parsed.getBasic(), "\x00\x10\x83\xFB\xFD"_sd);
    ASSERT_EQ(parsed.getUrl(), "\xD7m\xF8\xFB\xFD"_sd);

    BSONObjBuilder builder;
    parsed.serialize(&builder);
    ASSERT_BSONOBJ_EQ(doc, builder.obj());
}

// Negative: Test base64 encoded strings.
TEST(IDLOneTypeTests, TestBase64StringNegative) {
    {
        // No terminator on basic.
        auto doc = BSON("basic"
                        << "ABCD+/0"
                        << "url"
                        << "1234-_0");
        ASSERT_THROWS_CODE_AND_WHAT(Two_base64string::parse(IDLParserContext{"base64"}, doc),
                                    AssertionException,
                                    10270,
                                    "invalid base64");
    }

    {
        // Invalid chars in basic.
        auto doc = BSON("basic"
                        << "ABCD+_0="
                        << "url"
                        << "1234-_0");
        ASSERT_THROWS_CODE_AND_WHAT(Two_base64string::parse(IDLParserContext{"base64"}, doc),
                                    AssertionException,
                                    40537,
                                    "Invalid base64 character");
    }

    {
        // Invalid chars in url
        auto doc = BSON("basic"
                        << "ABCD+/0="
                        << "url"
                        << "1234-/0");
        ASSERT_THROWS_CODE_AND_WHAT(Two_base64string::parse(IDLParserContext{"base64"}, doc),
                                    AssertionException,
                                    40537,
                                    "Invalid base64 character");
    }
}


// BSONElement::exactNumberLong() provides different errors on windows
#ifdef _WIN32
constexpr auto kNANRepr = "-nan(ind)"_sd;
#else
constexpr auto kNANRepr = "nan"_sd;
#endif

TEST(IDLStructTests, DurationParse) {
    IDLParserContext ctxt("duration");

    auto justAMinuteDoc = BSON("secs" << 60);
    auto justAMinute = Struct_with_durations::parse(ctxt, justAMinuteDoc);
    ASSERT_EQ(justAMinute.getSecs().get(), Seconds{60});
    ASSERT_EQ(justAMinute.getSecs().get(), Minutes{1});

    auto floatDurationDoc = BSON("secs" << 123.0);
    auto floatDuration = Struct_with_durations::parse(ctxt, floatDurationDoc);
    ASSERT_EQ(floatDuration.getSecs().get(), Seconds{123});

    auto halfSecondDoc = BSON("secs" << 234.5);
    ASSERT_THROWS_CODE_AND_WHAT(Struct_with_durations::parse(ctxt, halfSecondDoc),
                                AssertionException,
                                ErrorCodes::FailedToParse,
                                "Expected an integer: secs: 234.5");

    auto invalidDurationDoc = BSON("secs"
                                   << "bob");
    ASSERT_THROWS_CODE_AND_WHAT(Struct_with_durations::parse(ctxt, invalidDurationDoc),
                                AssertionException,
                                ErrorCodes::BadValue,
                                "Duration value must be numeric, got: string");

    auto notADurationDoc = BSON("secs" << NAN);
    ASSERT_THROWS_CODE_AND_WHAT(
        Struct_with_durations::parse(ctxt, notADurationDoc),
        AssertionException,
        ErrorCodes::FailedToParse,
        fmt::format("Expected an integer, but found NaN in: secs: {}.0", kNANRepr));

    auto endOfTimeDoc = BSON("secs" << std::numeric_limits<double>::infinity());
    ASSERT_THROWS_CODE_AND_WHAT(Struct_with_durations::parse(ctxt, endOfTimeDoc),
                                AssertionException,
                                ErrorCodes::FailedToParse,
                                "Cannot represent as a 64-bit integer: secs: inf.0");
}

TEST(IDLStructTests, DurationSerialize) {
    Struct_with_durations allDay;
    allDay.setSecs(boost::make_optional(duration_cast<Seconds>(Days{1})));

    BSONObjBuilder builder;
    allDay.serialize(&builder);
    auto obj = builder.obj();

    auto intervalElem = obj["secs"_sd];
    ASSERT_EQ(intervalElem.numberLong(), 86400);
}

TEST(IDLStructTests, EpochsParse) {
    IDLParserContext ctxt("epoch");

    auto sameTimeDoc = BSON("unix" << 1234567890LL << "ecma" << 1234567890000LL);
    auto sameTime = Struct_with_epochs::parse(ctxt, sameTimeDoc);
    ASSERT_EQ(sameTime.getUnix(), sameTime.getEcma());
    ASSERT_EQ(sameTime.getUnix().toDurationSinceEpoch(), Seconds{1234567890});
    ASSERT_EQ(sameTime.getEcma().toDurationSinceEpoch(), Seconds{1234567890});

    auto floatTimeDoc = BSON("unix" << 123.0 << "ecma" << 234000.0);
    auto floatTime = Struct_with_epochs::parse(ctxt, floatTimeDoc);
    ASSERT_EQ(floatTime.getUnix().toDurationSinceEpoch(), Seconds{123});
    ASSERT_EQ(floatTime.getEcma().toDurationSinceEpoch(), Seconds{234});

    auto halfTimeDoc = BSON("unix" << 345.6 << "ecma" << 0);
    ASSERT_THROWS_CODE_AND_WHAT(Struct_with_epochs::parse(ctxt, halfTimeDoc),
                                AssertionException,
                                ErrorCodes::FailedToParse,
                                "Expected an integer: unix: 345.6");

    auto invalidTimeDoc = BSON("unix"
                               << "bob"
                               << "ecma" << 1234567890000LL);
    ASSERT_THROWS_CODE_AND_WHAT(Struct_with_epochs::parse(ctxt, invalidTimeDoc),
                                AssertionException,
                                ErrorCodes::BadValue,
                                "Epoch value must be numeric, got: string");

    auto notATimeDoc = BSON("unix" << 0 << "ecma" << NAN);
    ASSERT_THROWS_CODE_AND_WHAT(
        Struct_with_epochs::parse(ctxt, notATimeDoc),
        AssertionException,
        ErrorCodes::FailedToParse,
        fmt::format("Expected an integer, but found NaN in: ecma: {}.0", kNANRepr));

    auto endOfTimeDoc = BSON("unix" << std::numeric_limits<double>::infinity() << "ecma" << 0);
    ASSERT_THROWS_CODE_AND_WHAT(Struct_with_epochs::parse(ctxt, endOfTimeDoc),
                                AssertionException,
                                ErrorCodes::FailedToParse,
                                "Cannot represent as a 64-bit integer: unix: inf.0");
}

TEST(IDLStructTests, EpochSerialize) {
    Struct_with_epochs writeVal;
    writeVal.setUnix(Date_t::fromDurationSinceEpoch(Days{1}));
    writeVal.setEcma(Date_t::fromDurationSinceEpoch(Days{2}));
    BSONObjBuilder builder;
    writeVal.serialize(&builder);
    auto obj = builder.obj();

    auto unixElem = obj["unix"];
    auto ecmaElem = obj["ecma"];
    ASSERT_EQ(unixElem.type(), NumberLong);
    ASSERT_EQ(unixElem.numberLong(), 86400);
    ASSERT_EQ(ecmaElem.type(), NumberLong);
    ASSERT_EQ(ecmaElem.numberLong(), 2 * 86400 * 1000);
}

// Postive: Test any type
TEST(IDLOneTypeTests, TestAnyType) {
    IDLParserContext ctxt("root");

    // Positive: string field
    {
        auto testDoc = BSON("value"
                            << "Foo");
        auto testStruct = One_any_basic_type::parse(ctxt, testDoc);

        BSONObjBuilder builder;
        testStruct.serialize(&builder);

        auto serializedDoc = builder.obj();
        ASSERT_BSONOBJ_EQ(testDoc, serializedDoc);
    }

    // Positive: int field
    {
        auto testDoc = BSON("value" << 12);
        auto testStruct = One_any_basic_type::parse(ctxt, testDoc);

        BSONObjBuilder builder;
        testStruct.serialize(&builder);

        auto serializedDoc = builder.obj();
        ASSERT_BSONOBJ_EQ(testDoc, serializedDoc);
    }
}

// Postive: Test object type
TEST(IDLOneTypeTests, TestObjectType) {
    IDLParserContext ctxt("root");

    // Positive: object
    {
        auto testDoc = BSON("value" << BSON("value"
                                            << "foo"));
        auto testStruct = One_any_basic_type::parse(ctxt, testDoc);

        BSONObjBuilder builder;
        testStruct.serialize(&builder);

        auto serializedDoc = builder.obj();
        ASSERT_BSONOBJ_EQ(testDoc, serializedDoc);
    }
}


// Negative: Test object type
TEST(IDLOneTypeTests, TestObjectTypeNegative) {
    IDLParserContext ctxt("root");

    // Negative: string field
    {
        auto testDoc = BSON("value"
                            << "Foo");
        One_any_basic_type::parse(ctxt, testDoc);
    }

    // Negative: int field
    {
        auto testDoc = BSON("value" << 12);
        One_any_basic_type::parse(ctxt, testDoc);
    }
}

// Trait check used in TestLoopbackVariant.
template <typename T>
struct IsVector : std::false_type {};
template <typename T>
struct IsVector<std::vector<T>> : std::true_type {};
template <typename T>
constexpr bool isVector = IsVector<T>::value;

// We don't generate comparison operators like "==" for variants, so test only for BSON equality.
template <typename ParserT, typename TestT, BSONType Test_bson_type>
void TestLoopbackVariant(TestT test_value) {
    IDLParserContext ctxt("root");

    BSONObjBuilder bob;
    if constexpr (idl::hasBSONSerialize<TestT>) {
        // TestT might be an IDL struct type like One_string.
        BSONObjBuilder subObj(bob.subobjStart("value"));
        test_value.serialize(&subObj);
    } else if constexpr (isVector<TestT>) {
        BSONArrayBuilder arrayBuilder(bob.subarrayStart("value"));
        for (const auto& item : test_value) {
            if constexpr (idl::hasBSONSerialize<decltype(item)>) {
                BSONObjBuilder subObjBuilder(arrayBuilder.subobjStart());
                item.serialize(&subObjBuilder);
            } else {
                arrayBuilder.append(item);
            }
        }
    } else if constexpr (std::is_same_v<TestT, UUID>) {
        test_value.appendToBuilder(&bob, "value");
    } else {
        bob.append("value", test_value);
    }

    auto obj = bob.obj();
    auto element = obj.firstElement();
    ASSERT_EQUALS(element.type(), Test_bson_type);

    auto parsed = ParserT::parse(ctxt, obj);
    if constexpr (std::is_same_v<TestT, BSONObj>) {
        ASSERT_BSONOBJ_EQ(stdx::get<TestT>(parsed.getValue()), test_value);
    } else {
        // Use ASSERT instead of ASSERT_EQ to avoid operator<<
        ASSERT(stdx::get<TestT>(parsed.getValue()) == test_value);
    }
    ASSERT_BSONOBJ_EQ(obj, parsed.toBSON());

    // Test setValue.
    ParserT assembled;
    assembled.setValue(test_value);
    ASSERT_BSONOBJ_EQ(obj, assembled.toBSON());

    // Test the constructor.
    ParserT constructed(test_value);
    if constexpr (std::is_same_v<TestT, BSONObj>) {
        ASSERT_BSONOBJ_EQ(stdx::get<TestT>(parsed.getValue()), test_value);
    } else {
        ASSERT(stdx::get<TestT>(parsed.getValue()) == test_value);
    }
    ASSERT_BSONOBJ_EQ(obj, constructed.toBSON());
}

TEST(IDLVariantTests, TestVariantRoundtrip) {
    TestLoopbackVariant<One_variant, int, NumberInt>(1);
    TestLoopbackVariant<One_variant, std::string, String>("test_value");

    TestLoopbackVariant<One_variant_uuid, int, NumberInt>(1);
    TestLoopbackVariant<One_variant_uuid, UUID, BinData>(UUID::gen());

    TestLoopbackVariant<One_variant_compound, std::string, String>("test_value");
    TestLoopbackVariant<One_variant_compound, BSONObj, Object>(BSON("x" << 1));
    TestLoopbackVariant<One_variant_compound, std::vector<std::string>, Array>({});
    TestLoopbackVariant<One_variant_compound, std::vector<std::string>, Array>({"a"});
    TestLoopbackVariant<One_variant_compound, std::vector<std::string>, Array>({"a", "b"});

    TestLoopbackVariant<One_variant_struct, int, NumberInt>(1);
    TestLoopbackVariant<One_variant_struct, One_string, Object>(One_string("test_value"));

    TestLoopbackVariant<One_variant_struct_array, int, NumberInt>(1);
    TestLoopbackVariant<One_variant_struct_array, std::vector<One_string>, Array>(
        std::vector<One_string>());
    TestLoopbackVariant<One_variant_struct_array, std::vector<One_string>, Array>(
        {One_string("a")});
    TestLoopbackVariant<One_variant_struct_array, std::vector<One_string>, Array>(
        {One_string("a"), One_string("b")});
}

TEST(IDLVariantTests, TestVariantSafeInt) {
    TestLoopbackVariant<One_variant_safeInt, std::string, String>("test_value");
    TestLoopbackVariant<One_variant_safeInt, int, NumberInt>(1);

    // safeInt accepts all numbers, but always deserializes and serializes as int32.
    IDLParserContext ctxt("root");
    ASSERT_EQ(stdx::get<std::int32_t>(
                  One_variant_safeInt::parse(ctxt, BSON("value" << Decimal128(1))).getValue()),
              1);
    ASSERT_EQ(
        stdx::get<std::int32_t>(One_variant_safeInt::parse(ctxt, BSON("value" << 1LL)).getValue()),
        1);
    ASSERT_EQ(
        stdx::get<std::int32_t>(One_variant_safeInt::parse(ctxt, BSON("value" << 1.0)).getValue()),
        1);
}

TEST(IDLVariantTests, TestVariantSafeIntArray) {
    using int32vec = std::vector<std::int32_t>;

    TestLoopbackVariant<One_variant_safeInt_array, std::string, String>("test_value");
    TestLoopbackVariant<One_variant_safeInt_array, int32vec, Array>({});
    TestLoopbackVariant<One_variant_safeInt_array, int32vec, Array>({1});
    TestLoopbackVariant<One_variant_safeInt_array, int32vec, Array>({1, 2});

    // Use ASSERT instead of ASSERT_EQ to avoid operator<<
    IDLParserContext ctxt("root");
    ASSERT(stdx::get<int32vec>(
               One_variant_safeInt_array::parse(ctxt, BSON("value" << BSON_ARRAY(Decimal128(1))))
                   .getValue()) == int32vec{1});
    ASSERT(
        stdx::get<int32vec>(
            One_variant_safeInt_array::parse(ctxt, BSON("value" << BSON_ARRAY(1LL))).getValue()) ==
        int32vec{1});
    ASSERT(
        stdx::get<int32vec>(
            One_variant_safeInt_array::parse(ctxt, BSON("value" << BSON_ARRAY(1.0))).getValue()) ==
        int32vec{1});
    ASSERT(
        stdx::get<int32vec>(One_variant_safeInt_array::parse(
                                ctxt, BSON("value" << BSON_ARRAY(1.0 << 2LL << 3 << Decimal128(4))))
                                .getValue()) == (int32vec{1, 2, 3, 4}));
}

TEST(IDLVariantTests, TestVariantTwoStructs) {
    auto obj = BSON("value" << BSON("insert" << 1));
    auto parsed = One_variant_two_structs::parse(IDLParserContext{"root"}, obj);
    ASSERT_BSONOBJ_EQ(obj, parsed.toBSON());
    ASSERT_EQ(stdx::get<Insert_variant_struct>(parsed.getValue()).getInsert(), 1);

    obj = BSON("value" << BSON("update"
                               << "foo"));
    parsed = One_variant_two_structs::parse(IDLParserContext{"root"}, obj);
    ASSERT_BSONOBJ_EQ(obj, parsed.toBSON());
    ASSERT_EQ(stdx::get<Update_variant_struct>(parsed.getValue()).getUpdate(), "foo");
}

TEST(IDLVariantTests, TestVariantTwoArrays) {
    TestLoopbackVariant<One_variant_two_arrays, std::vector<int>, Array>({});
    TestLoopbackVariant<One_variant_two_arrays, std::vector<int>, Array>({1});
    TestLoopbackVariant<One_variant_two_arrays, std::vector<int>, Array>({1, 2});
    TestLoopbackVariant<One_variant_two_arrays, std::vector<std::string>, Array>({"a"});
    TestLoopbackVariant<One_variant_two_arrays, std::vector<std::string>, Array>({"a", "b"});

    // This variant can be array<int> or array<string>. It assumes an empty array is array<int>
    // because that type is declared first in the IDL.
    auto obj = BSON("value" << BSONArray());
    auto parsed = One_variant_two_arrays::parse(IDLParserContext{"root"}, obj);
    ASSERT(stdx::get<std::vector<int>>(parsed.getValue()) == std::vector<int>());
    ASSERT_THROWS(stdx::get<std::vector<std::string>>(parsed.getValue()), stdx::bad_variant_access);

    // Corrupt array: its first key isn't "0".
    BSONObjBuilder bob;
    {
        BSONObjBuilder arrayBob(bob.subarrayStart("value"));
        arrayBob.append("1", "test_value");
    }

    ASSERT_THROWS_CODE(One_variant_two_arrays::parse(IDLParserContext{"root"}, bob.obj()),
                       AssertionException,
                       40423);
}

TEST(IDLVariantTests, TestVariantOptional) {
    {
        auto obj = BSON("value" << 1);
        auto parsed = One_variant_optional::parse(IDLParserContext{"root"}, obj);
        ASSERT_BSONOBJ_EQ(obj, parsed.toBSON());
        ASSERT_EQ(stdx::get<int>(*parsed.getValue()), 1);
    }

    {
        auto obj = BSON("value"
                        << "test_value");
        auto parsed = One_variant_optional::parse(IDLParserContext{"root"}, obj);
        ASSERT_BSONOBJ_EQ(obj, parsed.toBSON());
        ASSERT_EQ(stdx::get<std::string>(*parsed.getValue()), "test_value");
    }

    // The optional key is absent.
    auto parsed = One_variant_optional::parse(IDLParserContext{"root"}, BSONObj());
    ASSERT_FALSE(parsed.getValue().has_value());
    ASSERT_BSONOBJ_EQ(BSONObj(), parsed.toBSON());
}

TEST(IDLVariantTests, TestTwoVariants) {
    // Combinations of value0 (int or string) and value1 (object or array<string>). For each, test
    // parse(), toBSON(), getValue0(), getValue1(), and the constructor.
    {
        auto obj = BSON("value0" << 1 << "value1" << BSONObj());
        auto parsed = Two_variants::parse(IDLParserContext{"root"}, obj);
        ASSERT_BSONOBJ_EQ(obj, parsed.toBSON());
        ASSERT_EQ(stdx::get<int>(parsed.getValue0()), 1);
        ASSERT_BSONOBJ_EQ(stdx::get<BSONObj>(parsed.getValue1()), BSONObj());
        ASSERT_BSONOBJ_EQ(Two_variants(1, BSONObj()).toBSON(), obj);
    }

    {
        auto obj = BSON("value0"
                        << "test_value"
                        << "value1" << BSONObj());
        auto parsed = Two_variants::parse(IDLParserContext{"root"}, obj);
        ASSERT_BSONOBJ_EQ(obj, parsed.toBSON());
        ASSERT_EQ(stdx::get<std::string>(parsed.getValue0()), "test_value");
        ASSERT_BSONOBJ_EQ(stdx::get<BSONObj>(parsed.getValue1()), BSONObj());
        ASSERT_BSONOBJ_EQ(Two_variants("test_value", BSONObj()).toBSON(), obj);
    }

    {
        auto obj = BSON("value0" << 1 << "value1"
                                 << BSON_ARRAY("x"
                                               << "y"));
        auto parsed = Two_variants::parse(IDLParserContext{"root"}, obj);
        ASSERT_BSONOBJ_EQ(obj, parsed.toBSON());
        ASSERT_EQ(stdx::get<int>(parsed.getValue0()), 1);
        ASSERT(stdx::get<std::vector<std::string>>(parsed.getValue1()) ==
               (std::vector<std::string>{"x", "y"}));
        ASSERT_BSONOBJ_EQ(Two_variants(1, std::vector<std::string>{"x", "y"}).toBSON(), obj);
    }

    {
        auto obj = BSON("value0"
                        << "test_value"
                        << "value1"
                        << BSON_ARRAY("x"
                                      << "y"));
        auto parsed = Two_variants::parse(IDLParserContext{"root"}, obj);
        ASSERT_BSONOBJ_EQ(obj, parsed.toBSON());
        ASSERT_EQ(stdx::get<std::string>(parsed.getValue0()), "test_value");
        ASSERT(stdx::get<std::vector<std::string>>(parsed.getValue1()) ==
               (std::vector<std::string>{"x", "y"}));
        ASSERT_BSONOBJ_EQ(Two_variants("test_value", std::vector<std::string>{"x", "y"}).toBSON(),
                          obj);
    }
}

TEST(IDLVariantTests, TestChainedStructVariant) {
    IDLParserContext ctxt("root");
    {
        auto obj = BSON("value"
                        << "x"
                        << "field1"
                        << "y");
        auto parsed = Chained_struct_variant::parse(ctxt, obj);
        ASSERT_EQ(stdx::get<std::string>(parsed.getOne_variant_compound().getValue()), "x");
        ASSERT_EQ(parsed.getField1(), "y");
        ASSERT_BSONOBJ_EQ(obj, parsed.toBSON());

        Chained_struct_variant assembled;
        assembled.setOne_variant_compound(One_variant_compound("x"));
        assembled.setField1("y");
        ASSERT_BSONOBJ_EQ(obj, assembled.toBSON());

        // Test the constructor.
        Chained_struct_variant constructed("y");
        constructed.setOne_variant_compound(One_variant_compound("x"));
        ASSERT_EQ(stdx::get<std::string>(constructed.getOne_variant_compound().getValue()), "x");
        ASSERT_EQ(constructed.getField1(), "y");
        ASSERT_BSONOBJ_EQ(obj, constructed.toBSON());
    }
    {
        auto obj = BSON("value" << BSON_ARRAY("x"
                                              << "y")
                                << "field1"
                                << "y");
        auto parsed = Chained_struct_variant::parse(ctxt, obj);
        ASSERT(stdx::get<std::vector<std::string>>(parsed.getOne_variant_compound().getValue()) ==
               (std::vector<std::string>{"x", "y"}));
        ASSERT_EQ(parsed.getField1(), "y");
        ASSERT_BSONOBJ_EQ(obj, parsed.toBSON());

        Chained_struct_variant assembled;
        assembled.setOne_variant_compound(One_variant_compound(std::vector<std::string>{"x", "y"}));
        assembled.setField1("y");
        ASSERT_BSONOBJ_EQ(obj, assembled.toBSON());

        // Test the constructor.
        Chained_struct_variant constructed("y");
        constructed.setOne_variant_compound(
            One_variant_compound(std::vector<std::string>{"x", "y"}));
        ASSERT(
            stdx::get<std::vector<std::string>>(constructed.getOne_variant_compound().getValue()) ==
            (std::vector<std::string>{"x", "y"}));
        ASSERT_EQ(constructed.getField1(), "y");
        ASSERT_BSONOBJ_EQ(obj, constructed.toBSON());
    }
    {
        auto obj = BSON("value" << BSONObj() << "field1"
                                << "y");
        auto parsed = Chained_struct_variant::parse(ctxt, obj);
        ASSERT_BSONOBJ_EQ(stdx::get<BSONObj>(parsed.getOne_variant_compound().getValue()),
                          BSONObj());
        ASSERT_EQ(parsed.getField1(), "y");
        ASSERT_BSONOBJ_EQ(obj, parsed.toBSON());

        Chained_struct_variant assembled;
        assembled.setOne_variant_compound(One_variant_compound(BSONObj()));
        assembled.setField1("y");
        ASSERT_BSONOBJ_EQ(obj, assembled.toBSON());

        // Test the constructor.
        Chained_struct_variant constructed("y");
        constructed.setOne_variant_compound({BSONObj()});
        ASSERT_BSONOBJ_EQ(stdx::get<BSONObj>(constructed.getOne_variant_compound().getValue()),
                          BSONObj());
        ASSERT_EQ(constructed.getField1(), "y");
        ASSERT_BSONOBJ_EQ(obj, constructed.toBSON());
    }
}

TEST(IDLVariantTests, TestChainedStructVariantInline) {
    IDLParserContext ctxt("root");
    {
        auto obj = BSON("value"
                        << "x"
                        << "field1"
                        << "y");
        auto parsed = Chained_struct_variant_inline::parse(ctxt, obj);
        ASSERT_EQ(stdx::get<std::string>(parsed.getValue()), "x");
        ASSERT_EQ(parsed.getField1(), "y");
        ASSERT_BSONOBJ_EQ(obj, parsed.toBSON());

        Chained_struct_variant_inline assembled;
        assembled.setOne_variant_compound(One_variant_compound("x"));
        assembled.setField1("y");
        ASSERT_BSONOBJ_EQ(obj, assembled.toBSON());

        // Test the constructor.
        Chained_struct_variant_inline constructed("y");
        constructed.setOne_variant_compound(One_variant_compound("x"));
        ASSERT_EQ(stdx::get<std::string>(constructed.getValue()), "x");
        ASSERT_EQ(constructed.getField1(), "y");
        ASSERT_BSONOBJ_EQ(obj, constructed.toBSON());
    }
    {
        auto obj = BSON("value" << BSON_ARRAY("x"
                                              << "y")
                                << "field1"
                                << "y");
        auto parsed = Chained_struct_variant_inline::parse(ctxt, obj);
        ASSERT(stdx::get<std::vector<std::string>>(parsed.getValue()) ==
               (std::vector<std::string>{"x", "y"}));
        ASSERT_EQ(parsed.getField1(), "y");
        ASSERT_BSONOBJ_EQ(obj, parsed.toBSON());

        Chained_struct_variant_inline assembled;
        assembled.setOne_variant_compound(One_variant_compound(std::vector<std::string>{"x", "y"}));
        assembled.setField1("y");
        ASSERT_BSONOBJ_EQ(obj, assembled.toBSON());

        // Test the constructor.
        Chained_struct_variant_inline constructed("y");
        constructed.setOne_variant_compound(
            One_variant_compound(std::vector<std::string>{"x", "y"}));
        ASSERT(stdx::get<std::vector<std::string>>(constructed.getValue()) ==
               (std::vector<std::string>{"x", "y"}));
        ASSERT_EQ(constructed.getField1(), "y");
        ASSERT_BSONOBJ_EQ(obj, constructed.toBSON());
    }
    {
        auto obj = BSON("value" << BSONObj() << "field1"
                                << "y");
        auto parsed = Chained_struct_variant_inline::parse(ctxt, obj);
        ASSERT_BSONOBJ_EQ(stdx::get<BSONObj>(parsed.getValue()), BSONObj());
        ASSERT_EQ(parsed.getField1(), "y");
        ASSERT_BSONOBJ_EQ(obj, parsed.toBSON());

        Chained_struct_variant_inline assembled;
        assembled.setOne_variant_compound(One_variant_compound(BSONObj()));
        assembled.setField1("y");
        ASSERT_BSONOBJ_EQ(obj, assembled.toBSON());

        // Test the constructor.
        Chained_struct_variant_inline constructed("y");
        constructed.setOne_variant_compound({BSONObj()});
        ASSERT_BSONOBJ_EQ(stdx::get<BSONObj>(constructed.getValue()), BSONObj());
        ASSERT_EQ(constructed.getField1(), "y");
        ASSERT_BSONOBJ_EQ(obj, constructed.toBSON());
    }
}

TEST(IDLVariantTests, TestChainedStructVariantStruct) {
    IDLParserContext ctxt("root");
    {
        auto obj = BSON("value" << 1 << "field1"
                                << "y");
        auto parsed = Chained_struct_variant_struct::parse(ctxt, obj);
        ASSERT_EQ(stdx::get<int>(parsed.getOne_variant_struct().getValue()), 1);
        ASSERT_EQ(parsed.getField1(), "y");
        ASSERT_BSONOBJ_EQ(obj, parsed.toBSON());

        Chained_struct_variant_struct assembled;
        assembled.setOne_variant_struct(One_variant_struct(1));
        assembled.setField1("y");
        ASSERT_BSONOBJ_EQ(obj, assembled.toBSON());

        // Test the constructor.
        Chained_struct_variant_struct constructed("y");
        constructed.setOne_variant_struct(One_variant_struct(1));
        ASSERT_EQ(stdx::get<int>(constructed.getOne_variant_struct().getValue()), 1);
        ASSERT_EQ(constructed.getField1(), "y");
        ASSERT_BSONOBJ_EQ(obj, constructed.toBSON());
    }
    {
        auto obj = BSON("value" << BSON("value"
                                        << "x")
                                << "field1"
                                << "y");
        auto parsed = Chained_struct_variant_struct::parse(ctxt, obj);
        ASSERT_EQ(stdx::get<One_string>(parsed.getOne_variant_struct().getValue()).getValue(), "x");
        ASSERT_EQ(parsed.getField1(), "y");
        ASSERT_BSONOBJ_EQ(obj, parsed.toBSON());

        Chained_struct_variant_struct assembled;
        assembled.setOne_variant_struct(One_variant_struct(One_string("x")));
        assembled.setField1("y");
        ASSERT_BSONOBJ_EQ(obj, assembled.toBSON());

        // Test the constructor.
        Chained_struct_variant_struct constructed("y");
        constructed.setOne_variant_struct(One_variant_struct(One_string("x")));
        ASSERT_EQ(stdx::get<One_string>(constructed.getOne_variant_struct().getValue()).getValue(),
                  "x");
        ASSERT_EQ(constructed.getField1(), "y");
        ASSERT_BSONOBJ_EQ(obj, constructed.toBSON());
    }
}

TEST(IDLVariantTests, TestChainedStructVariantStructInline) {
    IDLParserContext ctxt("root");
    {
        auto obj = BSON("value" << 1 << "field1"
                                << "y");
        auto parsed = Chained_struct_variant_struct_inline::parse(ctxt, obj);
        ASSERT_EQ(stdx::get<int>(parsed.getValue()), 1);
        ASSERT_EQ(parsed.getField1(), "y");
        ASSERT_BSONOBJ_EQ(obj, parsed.toBSON());

        Chained_struct_variant_struct_inline assembled;
        assembled.setOne_variant_struct(One_variant_struct(1));
        assembled.setField1("y");
        ASSERT_BSONOBJ_EQ(obj, assembled.toBSON());

        // Test the constructor.
        Chained_struct_variant_struct_inline constructed("y");
        constructed.setOne_variant_struct(One_variant_struct(1));
        ASSERT_EQ(stdx::get<int>(constructed.getValue()), 1);
        ASSERT_EQ(constructed.getField1(), "y");
        ASSERT_BSONOBJ_EQ(obj, constructed.toBSON());
    }
    {
        auto obj = BSON("value" << BSON("value"
                                        << "x")
                                << "field1"
                                << "y");
        auto parsed = Chained_struct_variant_struct_inline::parse(ctxt, obj);
        ASSERT_EQ(stdx::get<One_string>(parsed.getValue()).getValue(), "x");
        ASSERT_EQ(parsed.getField1(), "y");
        ASSERT_BSONOBJ_EQ(obj, parsed.toBSON());

        Chained_struct_variant_struct_inline assembled;
        assembled.setOne_variant_struct(One_variant_struct(One_string("x")));
        assembled.setField1("y");
        ASSERT_BSONOBJ_EQ(obj, assembled.toBSON());

        // Test the constructor.
        Chained_struct_variant_struct_inline constructed("y");
        constructed.setOne_variant_struct(One_variant_struct(One_string("x")));
        ASSERT_EQ(stdx::get<One_string>(constructed.getValue()).getValue(), "x");
        ASSERT_EQ(constructed.getField1(), "y");
        ASSERT_BSONOBJ_EQ(obj, constructed.toBSON());
    }
}

/// Struct tests:
// Positive: strict, 3 required fields
// Negative: strict, ensure extra fields fail
// Negative: strict, duplicate fields
TEST(IDLStructTests, TestStrictStruct) {
    IDLParserContext ctxt("root");

    // Positive: Just 3 required fields
    {
        auto testDoc = BSON("field1" << 12 << "field2" << 123 << "field3" << 1234);
        RequiredStrictField3::parse(ctxt, testDoc);
    }

    // Negative: Missing 1 required field
    {
        auto testDoc = BSON("field2" << 123 << "field3" << 1234);
        ASSERT_THROWS(RequiredStrictField3::parse(ctxt, testDoc), AssertionException);
    }
    {
        auto testDoc = BSON("field1" << 12 << "field3" << 1234);
        ASSERT_THROWS(RequiredStrictField3::parse(ctxt, testDoc), AssertionException);
    }
    {
        auto testDoc = BSON("field1" << 12 << "field2" << 123);
        ASSERT_THROWS(RequiredStrictField3::parse(ctxt, testDoc), AssertionException);
    }

    // Negative: Extra field
    {
        auto testDoc =
            BSON("field1" << 12 << "field2" << 123 << "field3" << 1234 << "field4" << 1234);
        ASSERT_THROWS(RequiredStrictField3::parse(ctxt, testDoc), AssertionException);
    }

    // Negative: Duplicate field
    {
        auto testDoc =
            BSON("field1" << 12 << "field2" << 123 << "field3" << 1234 << "field2" << 12345);
        ASSERT_THROWS(RequiredStrictField3::parse(ctxt, testDoc), AssertionException);
    }
}
// Positive: non-strict, ensure extra fields work
// Negative: non-strict, duplicate fields
TEST(IDLStructTests, TestNonStrictStruct) {
    IDLParserContext ctxt("root");

    // Positive: Just 3 required fields
    {
        auto testDoc =
            BSON(RequiredNonStrictField3::kCppField1FieldName << 12 << "2" << 123 << "3" << 1234);
        auto testStruct = RequiredNonStrictField3::parse(ctxt, testDoc);

        assert_same_types<decltype(testStruct.getCppField1()), std::int32_t>();
        assert_same_types<decltype(testStruct.getCppField2()), std::int32_t>();
        assert_same_types<decltype(testStruct.getCppField3()), std::int32_t>();
    }

    // Negative: Missing 1 required field
    {
        auto testDoc = BSON("2" << 123 << "3" << 1234);
        ASSERT_THROWS(RequiredNonStrictField3::parse(ctxt, testDoc), AssertionException);
    }
    {
        auto testDoc = BSON("1" << 12 << "3" << 1234);
        ASSERT_THROWS(RequiredNonStrictField3::parse(ctxt, testDoc), AssertionException);
    }
    {
        auto testDoc = BSON("1" << 12 << "2" << 123);
        ASSERT_THROWS(RequiredNonStrictField3::parse(ctxt, testDoc), AssertionException);
    }

    // Positive: Extra field
    {
        auto testDoc = BSON("1" << 12 << "2" << 123 << "3" << 1234 << "field4" << 1234);
        RequiredNonStrictField3::parse(ctxt, testDoc);
    }

    // Negative: Duplicate field
    {
        auto testDoc = BSON("1" << 12 << "2" << 123 << "3" << 1234 << "2" << 12345);
        ASSERT_THROWS(RequiredNonStrictField3::parse(ctxt, testDoc), AssertionException);
    }

    // Negative: Duplicate extra field
    {
        auto testDoc =
            BSON("field4" << 1234 << "1" << 12 << "2" << 123 << "3" << 1234 << "field4" << 1234);
        ASSERT_THROWS(RequiredNonStrictField3::parse(ctxt, testDoc), AssertionException);
    }

    // Negative: null required field
    {
        auto testDoc = BSON(RequiredNonStrictField3::kCppField1FieldName << 12 << "2" << 123 << "3"
                                                                         << BSONNULL);
        ASSERT_THROWS(RequiredNonStrictField3::parse(ctxt, testDoc), AssertionException);
    }
}

TEST(IDLStructTests, WriteConcernTest) {
    IDLParserContext ctxt("root");
    // Numeric w value
    {
        auto writeConcernDoc = BSON("w" << 1 << "j" << true << "wtimeout" << 5000);
        auto writeConcernStruct = WriteConcernIdl::parse(ctxt, writeConcernDoc);
        BSONObjBuilder builder;
        writeConcernStruct.serialize(&builder);
        ASSERT_BSONOBJ_EQ(builder.obj(), writeConcernDoc);
    }
    // String w value
    {
        auto writeConcernDoc = BSON("w"
                                    << "majority"
                                    << "j" << true << "wtimeout" << 5000);
        auto writeConcernStruct = WriteConcernIdl::parse(ctxt, writeConcernDoc);
        BSONObjBuilder builder;
        writeConcernStruct.serialize(&builder);
        ASSERT_BSONOBJ_EQ(builder.obj(), writeConcernDoc);
    }
    // Ignore options wElectionId, wOpTime, getLastError
    {
        auto writeConcernDoc = BSON("w"
                                    << "majority"
                                    << "j" << true << "wtimeout" << 5000 << "wElectionId" << 12345
                                    << "wOpTime" << 98765 << "getLastError" << true);
        auto writeConcernDocWithoutIgnoredFields = BSON("w"
                                                        << "majority"
                                                        << "j" << true << "wtimeout" << 5000);
        auto writeConcernStruct = WriteConcernIdl::parse(ctxt, writeConcernDoc);
        BSONObjBuilder builder;
        writeConcernStruct.serialize(&builder);
        ASSERT_BSONOBJ_EQ(builder.obj(), writeConcernDocWithoutIgnoredFields);
    }
}

TEST(IDLStructTests, TestValidator) {
    // Parser should assert that the values are equal.
    IDLParserContext ctxt("root");
    auto objToParse = BSON("first" << 1 << "second" << 2);

    ASSERT_THROWS_CODE(StructWithValidator::parse(ctxt, objToParse), AssertionException, 6253512);

    objToParse = BSON("first" << 1 << "second" << 1);
    StructWithValidator::parse(ctxt, objToParse);
}

/// Struct default comparison tests
TEST(IDLCompareTests, TestAllFields) {
    IDLParserContext ctxt("root");

    // Positive: equality works
    {
        CompareAllField3 origStruct;
        origStruct.setField1(12);
        origStruct.setField2(123);
        origStruct.setField3(1234);

        auto testDoc = BSON("field1" << 12 << "field2" << 123 << "field3" << 1234);
        auto parsedStruct = CompareAllField3::parse(ctxt, testDoc);

        // Avoid ASSET_<RelOp> to avoid operator <<
        ASSERT_TRUE(origStruct == parsedStruct);
        ASSERT_FALSE(origStruct != parsedStruct);
        ASSERT_FALSE(origStruct < parsedStruct);
        ASSERT_FALSE(parsedStruct < origStruct);
    }

    // Positive: not equality works in field 3
    {
        CompareAllField3 origStruct;
        origStruct.setField1(12);
        origStruct.setField2(123);
        origStruct.setField3(12345);

        auto testDoc = BSON("field1" << 12 << "field2" << 123 << "field3" << 1234);
        auto parsedStruct = CompareAllField3::parse(ctxt, testDoc);

        // Avoid ASSET_<RelOp> to avoid operator <<
        ASSERT_FALSE(origStruct == parsedStruct);
        ASSERT_TRUE(origStruct != parsedStruct);
        ASSERT_FALSE(origStruct < parsedStruct);
        ASSERT_TRUE(parsedStruct < origStruct);
    }
}


/// Struct partial comparison tests
TEST(IDLCompareTests, TestSomeFields) {
    IDLParserContext ctxt("root");

    // Positive: partial equality works when field 2 is different
    {
        CompareSomeField3 origStruct;
        origStruct.setField1(12);
        origStruct.setField2(12345);
        origStruct.setField3(1234);

        auto testDoc = BSON("field1" << 12 << "field2" << 123 << "field3" << 1234);
        auto parsedStruct = CompareSomeField3::parse(ctxt, testDoc);

        // Avoid ASSET_<RelOp> to avoid operator <<
        ASSERT_TRUE(origStruct == parsedStruct);
        ASSERT_FALSE(origStruct != parsedStruct);
        ASSERT_FALSE(origStruct < parsedStruct);
        ASSERT_FALSE(parsedStruct < origStruct);
    }

    // Positive: partial equality works when field 3 is different
    {
        CompareSomeField3 origStruct;
        origStruct.setField1(12);
        origStruct.setField2(1);
        origStruct.setField3(12345);

        auto testDoc = BSON("field1" << 12 << "field2" << 123 << "field3" << 1234);
        auto parsedStruct = CompareSomeField3::parse(ctxt, testDoc);

        // Avoid ASSET_<RelOp> to avoid operator <<
        ASSERT_FALSE(origStruct == parsedStruct);
        ASSERT_TRUE(origStruct != parsedStruct);
        ASSERT_FALSE(origStruct < parsedStruct);
        ASSERT_TRUE(parsedStruct < origStruct);
    }

    // Positive: partial equality works when field 1 is different
    {
        CompareSomeField3 origStruct;
        origStruct.setField1(123);
        origStruct.setField2(1);
        origStruct.setField3(1234);

        auto testDoc = BSON("field1" << 12 << "field2" << 123 << "field3" << 1234);
        auto parsedStruct = CompareSomeField3::parse(ctxt, testDoc);

        // Avoid ASSET_<RelOp> to avoid operator <<
        ASSERT_FALSE(origStruct == parsedStruct);
        ASSERT_TRUE(origStruct != parsedStruct);
        ASSERT_FALSE(origStruct < parsedStruct);
        ASSERT_TRUE(parsedStruct < origStruct);
    }
}

/// Field tests
// Positive: check ignored field is ignored
TEST(IDLFieldTests, TestStrictStructIgnoredField) {
    IDLParserContext ctxt("root");

    // Positive: Test ignored field is ignored
    {
        auto testDoc = BSON("required_field" << 12 << "ignored_field" << 123);
        IgnoredField::parse(ctxt, testDoc);
    }

    // Positive: Test ignored field is not required
    {
        auto testDoc = BSON("required_field" << 12);
        IgnoredField::parse(ctxt, testDoc);
    }
}

// Negative: check duplicate ignored fields fail
TEST(IDLFieldTests, TestStrictDuplicateIgnoredFields) {
    IDLParserContext ctxt("root");

    // Negative: Test duplicate ignored fields fail
    {
        auto testDoc =
            BSON("required_field" << 12 << "ignored_field" << 123 << "ignored_field" << 456);
        ASSERT_THROWS(IgnoredField::parse(ctxt, testDoc), AssertionException);
    }
}


// First test: test an empty document and the default value
// Second test: test a non-empty document and that we do not get the default value
#define TEST_DEFAULT_VALUES(field_name, default_value, new_value)   \
    {                                                               \
        auto testDoc = BSONObj();                                   \
        auto testStruct = Default_values::parse(ctxt, testDoc);     \
        ASSERT_EQUALS(testStruct.get##field_name(), default_value); \
    }                                                               \
    {                                                               \
        auto testDoc = BSON(#field_name << new_value);              \
        auto testStruct = Default_values::parse(ctxt, testDoc);     \
        ASSERT_EQUALS(testStruct.get##field_name(), new_value);     \
    }

#define TEST_DEFAULT_VALUES_VARIANT(field_name, default_type, default_value, new_type, new_value) \
    {                                                                                             \
        auto testDoc = BSONObj();                                                                 \
        auto testStruct = Default_values::parse(ctxt, testDoc);                                   \
        ASSERT_TRUE(stdx::holds_alternative<default_type>(testStruct.get##field_name()));         \
        ASSERT_EQUALS(stdx::get<default_type>(testStruct.get##field_name()), default_value);      \
    }                                                                                             \
    {                                                                                             \
        auto testDoc = BSON(#field_name << new_value);                                            \
        auto testStruct = Default_values::parse(ctxt, testDoc);                                   \
        ASSERT_TRUE(stdx::holds_alternative<new_type>(testStruct.get##field_name()));             \
        ASSERT_EQUALS(stdx::get<new_type>(testStruct.get##field_name()), new_value);              \
    }

// Mixed: struct strict, and ignored field works
TEST(IDLFieldTests, TestDefaultFields) {
    IDLParserContext ctxt("root");

    TEST_DEFAULT_VALUES(V_string, "a default", "foo");
    TEST_DEFAULT_VALUES(V_int, 42, 3);
    TEST_DEFAULT_VALUES(V_long, 423, 4LL);
    TEST_DEFAULT_VALUES(V_double, 3.14159, 2.8);
    TEST_DEFAULT_VALUES(V_bool, true, false);
    TEST_DEFAULT_VALUES_VARIANT(V_variant_string, std::string, "a default", int, 42);
    TEST_DEFAULT_VALUES_VARIANT(V_variant_int, int, 42, std::string, "a default");
}

// Positive: struct strict, and optional field works
TEST(IDLFieldTests, TestOptionalFields) {
    IDLParserContext ctxt("root");

    // Positive: Test document with only string field
    {
        auto testDoc = BSON("field1"
                            << "Foo");
        auto testStruct = Optional_field::parse(ctxt, testDoc);
        assert_same_types<decltype(testStruct.getField1()), boost::optional<StringData>>();
        assert_same_types<decltype(testStruct.getField2()), boost::optional<int>>();
        assert_same_types<decltype(testStruct.getField3()), const boost::optional<BSONObj>&>();
        assert_same_types<decltype(testStruct.getField4()), boost::optional<ConstDataRange>>();
        assert_same_types<decltype(testStruct.getField5()),
                          boost::optional<std::array<std::uint8_t, 16>>>();

        ASSERT_EQUALS("Foo", testStruct.getField1().value());
        ASSERT_FALSE(testStruct.getField2().has_value());
    }

    // Positive: Serialize struct with only string field
    {
        BSONObjBuilder builder;
        Optional_field testStruct;
        auto field1 = boost::optional<StringData>("Foo");
        testStruct.setField1(field1);
        testStruct.serialize(&builder);
        auto loopbackDoc = builder.obj();

        auto testDoc = BSON("field1"
                            << "Foo");
        ASSERT_BSONOBJ_EQ(testDoc, loopbackDoc);
    }

    // Positive: Test document with only int field
    {
        auto testDoc = BSON("field2" << 123);
        auto testStruct = Optional_field::parse(ctxt, testDoc);
        ASSERT_FALSE(testStruct.getField1().has_value());
        ASSERT_EQUALS(123, testStruct.getField2().value());
    }

    // Positive: Serialize struct with only int field
    {
        BSONObjBuilder builder;
        Optional_field testStruct;
        testStruct.setField2(123);
        testStruct.serialize(&builder);
        auto loopbackDoc = builder.obj();

        auto testDoc = BSON("field2" << 123);
        ASSERT_BSONOBJ_EQ(testDoc, loopbackDoc);
    }
}

TEST(IDLFieldTests, TestAlwaysSerializeFields) {
    IDLParserContext ctxt("root");

    auto testDoc = BSON("field1"
                        << "Foo"
                        << "field3" << BSON("a" << 1234));
    auto testStruct = Always_serialize_field::parse(ctxt, testDoc);

    assert_same_types<decltype(testStruct.getField1()), boost::optional<mongo::StringData>>();
    assert_same_types<decltype(testStruct.getField2()), boost::optional<std::int32_t>>();
    assert_same_types<decltype(testStruct.getField3()), const boost::optional<mongo::BSONObj>&>();
    assert_same_types<decltype(testStruct.getField4()), const boost::optional<mongo::BSONObj>&>();
    assert_same_types<decltype(testStruct.getField5()), const boost::optional<mongo::BSONObj>&>();

    ASSERT_EQUALS("Foo", testStruct.getField1().value());
    ASSERT_FALSE(testStruct.getField2().has_value());
    ASSERT_BSONOBJ_EQ(BSON("a" << 1234), testStruct.getField3().value());
    ASSERT_FALSE(testStruct.getField4().has_value());
    ASSERT_FALSE(testStruct.getField5().has_value());

    BSONObjBuilder builder;
    testStruct.serialize(&builder);
    auto loopbackDoc = builder.obj();
    auto docWithNulls = BSON("field1"
                             << "Foo"
                             << "field2" << BSONNULL << "field3" << BSON("a" << 1234) << "field4"
                             << BSONNULL);
    ASSERT_BSONOBJ_EQ(docWithNulls, loopbackDoc);
}

template <typename TestT>
void TestWeakType(TestT test_value) {
    IDLParserContext ctxt("root");
    auto testDoc = BSON("field1" << test_value << "field2" << test_value << "field3" << test_value
                                 << "field4" << test_value << "field5" << test_value);
    auto testStruct = Optional_field::parse(ctxt, testDoc);

    ASSERT_FALSE(testStruct.getField1().has_value());
    ASSERT_FALSE(testStruct.getField2().has_value());
    ASSERT_FALSE(testStruct.getField3().has_value());
    ASSERT_FALSE(testStruct.getField4().has_value());
    ASSERT_FALSE(testStruct.getField5().has_value());
}

// Positive: struct strict, and optional field works
TEST(IDLFieldTests, TestOptionalFieldsWithNullAndUndefined) {

    TestWeakType<NullLabeler>(BSONNULL);

    TestWeakType<UndefinedLabeler>(BSONUndefined);
}

// Positive: Test a nested struct
TEST(IDLNestedStruct, TestDuplicateTypes) {
    IDLParserContext ctxt("root");


    // Positive: Test document
    auto testDoc = BSON(

        "field1" << BSON("field1" << 1 << "field2" << 2 << "field3" << 3) <<

        "field3" << BSON("field1" << 4 << "field2" << 5 << "field3" << 6));
    auto testStruct = NestedWithDuplicateTypes::parse(ctxt, testDoc);

    assert_same_types<decltype(testStruct.getField1()), RequiredStrictField3&>();
    assert_same_types<decltype(testStruct.getField2()),
                      boost::optional<RequiredNonStrictField3>&>();
    assert_same_types<decltype(testStruct.getField3()), RequiredStrictField3&>();

    ASSERT_EQUALS(1, testStruct.getField1().getField1());
    ASSERT_EQUALS(2, testStruct.getField1().getField2());
    ASSERT_EQUALS(3, testStruct.getField1().getField3());

    ASSERT_FALSE(testStruct.getField2());

    ASSERT_EQUALS(4, testStruct.getField3().getField1());
    ASSERT_EQUALS(5, testStruct.getField3().getField2());
    ASSERT_EQUALS(6, testStruct.getField3().getField3());

    // Positive: Test we can roundtrip from the just parsed document
    {
        BSONObjBuilder builder;
        testStruct.serialize(&builder);
        auto loopbackDoc = builder.obj();

        ASSERT_BSONOBJ_EQ(testDoc, loopbackDoc);
    }

    // Positive: Test we can serialize from nothing the same document
    {
        BSONObjBuilder builder;
        NestedWithDuplicateTypes nested_structs;
        RequiredStrictField3 f1;
        f1.setField1(1);
        f1.setField2(2);
        f1.setField3(3);
        nested_structs.setField1(f1);
        RequiredStrictField3 f3;
        f3.setField1(4);
        f3.setField2(5);
        f3.setField3(6);
        nested_structs.setField3(f3);
        nested_structs.serialize(&builder);

        auto serializedDoc = builder.obj();
        ASSERT_BSONOBJ_EQ(testDoc, serializedDoc);
    }
}

// Positive: Arrays of simple types
TEST(IDLArrayTests, TestSimpleArrays) {
    IDLParserContext ctxt("root");

    // Positive: Test document
    uint8_t array1[] = {1, 2, 3};
    uint8_t array2[] = {4, 6, 8};

    uint8_t array15[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
    uint8_t array16[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};

    auto testDoc = BSON("field1" << BSON_ARRAY("Foo"
                                               << "Bar"
                                               << "???")
                                 << "field2" << BSON_ARRAY(1 << 2 << 3) << "field3"
                                 << BSON_ARRAY(1.2 << 3.4 << 5.6) << "field4"
                                 << BSON_ARRAY(BSONBinData(array1, 3, BinDataGeneral)
                                               << BSONBinData(array2, 3, BinDataGeneral))
                                 << "field5"
                                 << BSON_ARRAY(BSONBinData(array15, 16, newUUID)
                                               << BSONBinData(array16, 16, newUUID)));
    auto testStruct = Simple_array_fields::parse(ctxt, testDoc);

    assert_same_types<decltype(testStruct.getField1()), std::vector<StringData>>();
    assert_same_types<decltype(testStruct.getField2()), const std::vector<std::int32_t>&>();
    assert_same_types<decltype(testStruct.getField3()), const std::vector<double>&>();
    assert_same_types<decltype(testStruct.getField4()), std::vector<ConstDataRange>>();
    assert_same_types<decltype(testStruct.getField5()),
                      const std::vector<std::array<std::uint8_t, 16>>&>();

    std::vector<StringData> field1{"Foo", "Bar", "???"};
    ASSERT_TRUE(field1 == testStruct.getField1());
    std::vector<std::int32_t> field2{1, 2, 3};
    ASSERT_TRUE(field2 == testStruct.getField2());
    std::vector<double> field3{1.2, 3.4, 5.6};
    ASSERT_TRUE(field3 == testStruct.getField3());

    std::vector<std::vector<uint8_t>> field4{{1, 2, 3}, {4, 6, 8}};
    ASSERT_TRUE(isEquals(testStruct.getField4(), field4));

    std::vector<std::array<uint8_t, 16>> field5{
        {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
        {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}};
    ASSERT_TRUE(isEquals(testStruct.getField5(), field5));

    // Positive: Test we can roundtrip from the just parsed document
    {
        BSONObjBuilder builder;
        testStruct.serialize(&builder);
        auto loopbackDoc = builder.obj();

        ASSERT_BSONOBJ_EQ(testDoc, loopbackDoc);
    }

    // Positive: Test we can serialize from nothing the same document
    {
        BSONObjBuilder builder;
        Simple_array_fields array_fields;
        array_fields.setField1(field1);
        array_fields.setField2(field2);
        array_fields.setField3(field3);
        array_fields.setField4(transformVector(field4));
        array_fields.setField5(field5);
        array_fields.serialize(&builder);

        auto serializedDoc = builder.obj();
        ASSERT_BSONOBJ_EQ(testDoc, serializedDoc);
    }
}

// Positive: Optional Arrays
TEST(IDLArrayTests, TestSimpleOptionalArrays) {
    IDLParserContext ctxt("root");

    // Positive: Test document
    auto testDoc = BSON("field1" << BSON_ARRAY("Foo"
                                               << "Bar"
                                               << "???")
                                 << "field2" << BSON_ARRAY(1 << 2 << 3) << "field3"
                                 << BSON_ARRAY(1.2 << 3.4 << 5.6)

    );
    auto testStruct = Optional_array_fields::parse(ctxt, testDoc);

    assert_same_types<decltype(testStruct.getField1()), boost::optional<std::vector<StringData>>>();
    assert_same_types<decltype(testStruct.getField2()),
                      const boost::optional<std::vector<std::int32_t>>&>();
    assert_same_types<decltype(testStruct.getField3()),
                      const boost::optional<std::vector<double>>&>();
    assert_same_types<decltype(testStruct.getField4()),
                      boost::optional<std::vector<ConstDataRange>>>();
    assert_same_types<decltype(testStruct.getField5()),
                      const boost::optional<std::vector<std::array<std::uint8_t, 16>>>&>();

    std::vector<StringData> field1{"Foo", "Bar", "???"};
    ASSERT_TRUE(field1 == testStruct.getField1().value());
    std::vector<std::int32_t> field2{1, 2, 3};
    ASSERT_TRUE(field2 == testStruct.getField2().value());
    std::vector<double> field3{1.2, 3.4, 5.6};
    ASSERT_TRUE(field3 == testStruct.getField3().value());

    // Positive: Test we can roundtrip from the just parsed document
    {
        BSONObjBuilder builder;
        testStruct.serialize(&builder);
        auto loopbackDoc = builder.obj();

        ASSERT_BSONOBJ_EQ(testDoc, loopbackDoc);
    }

    // Positive: Test we can serialize from nothing the same document
    {
        BSONObjBuilder builder;
        Optional_array_fields array_fields;
        array_fields.setField1(field1);
        array_fields.setField2(field2);
        array_fields.setField3(field3);
        array_fields.serialize(&builder);

        auto serializedDoc = builder.obj();
        ASSERT_BSONOBJ_EQ(testDoc, serializedDoc);
    }
}

// Negative: Test mixed type arrays
TEST(IDLArrayTests, TestBadArrays) {
    IDLParserContext ctxt("root");

    // Negative: Test not an array
    {
        auto testDoc = BSON("field1" << 123);

        ASSERT_THROWS(Simple_int_array::parse(ctxt, testDoc), AssertionException);
    }

    // Negative: Test array with mixed types
    {
        auto testDoc = BSON("field1" << BSON_ARRAY(1.2 << 3.4 << 5.6));

        ASSERT_THROWS(Simple_int_array::parse(ctxt, testDoc), AssertionException);
    }
}

// Negative: Test arrays with good field names but made with BSONObjBuilder::subobjStart
TEST(IDLArrayTests, TestGoodArraysWithObjectType) {
    IDLParserContext ctxt("root");

    {
        BSONObjBuilder builder;
        {
            BSONObjBuilder subBuilder(builder.subobjStart("field1"));
            subBuilder.append("0", 1);
            subBuilder.append("1", 2);
        }

        auto testDoc = builder.obj();
        ASSERT_THROWS(Simple_int_array::parse(ctxt, testDoc), AssertionException);
    }
}

// Positive: Test arrays with good field names but made with BSONObjBuilder::subarrayStart
TEST(IDLArrayTests, TestGoodArraysWithArrayType) {
    IDLParserContext ctxt("root");

    {
        BSONObjBuilder builder;
        {
            BSONObjBuilder subBuilder(builder.subarrayStart("field1"));
            subBuilder.append("0", 1);
            subBuilder.append("1", 2);
        }

        auto testDoc = builder.obj();

        Simple_int_array::parse(ctxt, testDoc);
    }
}

// Negative: Test arrays with bad field names
TEST(IDLArrayTests, TestBadArrayFieldNames) {
    IDLParserContext ctxt("root");

    // Negative: string fields
    {
        BSONObjBuilder builder;
        {
            BSONObjBuilder subBuilder(builder.subarrayStart("field1"));
            subBuilder.append("0", 1);
            subBuilder.append("foo", 2);
        }
        auto testDoc = builder.obj();

        ASSERT_THROWS(Simple_int_array::parse(ctxt, testDoc), AssertionException);
    }

    // Negative: bad start
    {
        BSONObjBuilder builder;
        {
            BSONObjBuilder subBuilder(builder.subarrayStart("field1"));
            subBuilder.append("1", 1);
            subBuilder.append("2", 2);
        }
        auto testDoc = builder.obj();

        ASSERT_THROWS(Simple_int_array::parse(ctxt, testDoc), AssertionException);
    }

    // Negative: non-sequentially increasing
    {
        BSONObjBuilder builder;
        {
            BSONObjBuilder subBuilder(builder.subarrayStart("field1"));
            subBuilder.append("0", 1);
            subBuilder.append("2", 2);
        }
        auto testDoc = builder.obj();

        ASSERT_THROWS(Simple_int_array::parse(ctxt, testDoc), AssertionException);
    }
}

// Postitive: Test arrays with complex types
TEST(IDLArrayTests, TestArraysOfComplexTypes) {
    IDLParserContext ctxt("root");

    // Positive: Test document
    auto testDoc = BSON("field1" << BSON_ARRAY(1 << 2 << 3) << "field2"
                                 << BSON_ARRAY("a.b"
                                               << "c.d")
                                 << "field3" << BSON_ARRAY(1 << "2") << "field4"
                                 << BSON_ARRAY(BSONObj() << BSONObj()) << "field5"
                                 << BSON_ARRAY(BSONObj() << BSONObj() << BSONObj()) << "field6"
                                 << BSON_ARRAY(BSON("value"
                                                    << "hello")
                                               << BSON("value"
                                                       << "world"))
                                 << "field1o" << BSON_ARRAY(1 << 2 << 3) << "field2o"
                                 << BSON_ARRAY("a.b"
                                               << "c.d")
                                 << "field3o" << BSON_ARRAY(1 << "2") << "field4o"
                                 << BSON_ARRAY(BSONObj() << BSONObj()) << "field6o"
                                 << BSON_ARRAY(BSON("value"
                                                    << "goodbye")
                                               << BSON("value"
                                                       << "world"))

    );
    auto testStruct = Complex_array_fields::parse(ctxt, testDoc);

    assert_same_types<decltype(testStruct.getField1()), const std::vector<std::int64_t>&>();
    assert_same_types<decltype(testStruct.getField2()),
                      const std::vector<mongo::NamespaceString>&>();
    assert_same_types<decltype(testStruct.getField3()), const std::vector<mongo::AnyBasicType>&>();
    assert_same_types<decltype(testStruct.getField4()),
                      const std::vector<mongo::ObjectBasicType>&>();
    assert_same_types<decltype(testStruct.getField5()), const std::vector<mongo::BSONObj>&>();
    assert_same_types<decltype(testStruct.getField6()), std::vector<idl::import::One_string>&>();

    assert_same_types<decltype(testStruct.getField1o()),
                      const boost::optional<std::vector<std::int64_t>>&>();
    assert_same_types<decltype(testStruct.getField2o()),
                      const boost::optional<std::vector<mongo::NamespaceString>>&>();
    assert_same_types<decltype(testStruct.getField3o()),
                      const boost::optional<std::vector<mongo::AnyBasicType>>&>();
    assert_same_types<decltype(testStruct.getField4o()),
                      const boost::optional<std::vector<mongo::ObjectBasicType>>&>();
    assert_same_types<decltype(testStruct.getField5o()),
                      const boost::optional<std::vector<mongo::BSONObj>>&>();
    assert_same_types<decltype(testStruct.getField6o()),
                      boost::optional<std::vector<idl::import::One_string>>&>();

    std::vector<std::int64_t> field1{1, 2, 3};
    ASSERT_TRUE(field1 == testStruct.getField1());
    std::vector<NamespaceString> field2{{"a", "b"}, {"c", "d"}};
    ASSERT_TRUE(field2 == testStruct.getField2());

    ASSERT_EQUALS(testStruct.getField6().size(), 2u);
    ASSERT_EQUALS(testStruct.getField6()[0].getValue(), "hello");
    ASSERT_EQUALS(testStruct.getField6()[1].getValue(), "world");
    ASSERT_EQUALS(testStruct.getField6o().value().size(), 2u);
    ASSERT_EQUALS(testStruct.getField6o().value()[0].getValue(), "goodbye");
    ASSERT_EQUALS(testStruct.getField6o().value()[1].getValue(), "world");
}

template <typename ParserT, BinDataType bindata_type>
void TestBinDataVector() {
    IDLParserContext ctxt("root");

    // Positive: Test document with only a generic bindata field
    uint8_t testData[] = {1, 2, 3};
    auto testDoc = BSON("value" << BSONBinData(testData, 3, bindata_type));
    auto testStruct = ParserT::parse(ctxt, testDoc);

    assert_same_types<decltype(testStruct.getValue()), ConstDataRange>();

    std::vector<std::uint8_t> expected{1, 2, 3};

    ASSERT_TRUE(isEquals(testStruct.getValue(), expected));

    // Positive: Test we can roundtrip from the just parsed document
    {
        BSONObjBuilder builder;
        testStruct.serialize(&builder);
        auto loopbackDoc = builder.obj();

        ASSERT_BSONOBJ_EQ(testDoc, loopbackDoc);
    }

    // Positive: Test we can serialize from nothing the same document
    {
        BSONObjBuilder builder;
        ParserT one_new;
        one_new.setValue(expected);
        testStruct.serialize(&builder);

        auto serializedDoc = builder.obj();
        ASSERT_BSONOBJ_EQ(testDoc, serializedDoc);

        // Validate the operator == works
        // Use ASSERT instead of ASSERT_EQ to avoid operator<<
        ASSERT(one_new == testStruct);
    }
}

TEST(IDLBinData, TestGeneric) {
    TestBinDataVector<One_bindata, BinDataGeneral>();
}

TEST(IDLBinData, TestFunction) {
    TestBinDataVector<One_function, Function>();
}

template <typename ParserT, BinDataType bindata_type>
void TestBinDataArray() {
    IDLParserContext ctxt("root");

    // Positive: Test document with only a generic bindata field
    uint8_t testData[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
    auto testDoc = BSON("value" << BSONBinData(testData, 16, bindata_type));
    auto testStruct = ParserT::parse(ctxt, testDoc);

    assert_same_types<decltype(testStruct.getValue()), std::array<uint8_t, 16>>();

    std::array<std::uint8_t, 16> expected{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};

    ASSERT_TRUE(isEquals(testStruct.getValue(), expected));

    // Positive: Test we can roundtrip from the just parsed document
    {
        BSONObjBuilder builder;
        testStruct.serialize(&builder);
        auto loopbackDoc = builder.obj();

        ASSERT_BSONOBJ_EQ(testDoc, loopbackDoc);
    }

    // Positive: Test we can serialize from nothing the same document
    {
        BSONObjBuilder builder;
        ParserT one_new;
        one_new.setValue(expected);
        one_new.serialize(&builder);

        auto serializedDoc = builder.obj();
        ASSERT_BSONOBJ_EQ(testDoc, serializedDoc);
    }
}

TEST(IDLBinData, TestUUID) {
    TestBinDataArray<One_uuid, newUUID>();
}

TEST(IDLBinData, TestMD5) {
    TestBinDataArray<One_md5, MD5Type>();

    // Negative: Test document with a incorrectly size md5 field
    {
        IDLParserContext ctxt("root");

        uint8_t testData[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
        auto testDoc = BSON("value" << BSONBinData(testData, 15, MD5Type));
        ASSERT_THROWS(One_md5::parse(ctxt, testDoc), AssertionException);
    }
}

// Test if a given value for a given bson document parses successfully or fails if the bson types
// mismatch.
template <typename ParserT, BinDataType Parser_bindata_type, BinDataType Test_bindata_type>
void TestBinDataParse() {
    IDLParserContext ctxt("root");

    uint8_t testData[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
    auto testDoc = BSON("value" << BSONBinData(testData, 16, Test_bindata_type));

    auto element = testDoc.firstElement();
    ASSERT_EQUALS(element.type(), BinData);
    ASSERT_EQUALS(element.binDataType(), Test_bindata_type);

    if (Parser_bindata_type != Test_bindata_type) {
        ASSERT_THROWS(ParserT::parse(ctxt, testDoc), AssertionException);
    } else {
        (void)ParserT::parse(ctxt, testDoc);
    }
}

template <typename ParserT, BinDataType Parser_bindata_type>
void TestBinDataParser() {
    TestBinDataParse<ParserT, Parser_bindata_type, BinDataGeneral>();
    TestBinDataParse<ParserT, Parser_bindata_type, Function>();
    TestBinDataParse<ParserT, Parser_bindata_type, MD5Type>();
    TestBinDataParse<ParserT, Parser_bindata_type, newUUID>();
}

TEST(IDLBinData, TestParse) {
    TestBinDataParser<One_bindata, BinDataGeneral>();
    TestBinDataParser<One_function, Function>();
    TestBinDataParser<One_uuid, newUUID>();
    TestBinDataParser<One_md5, MD5Type>();
    TestBinDataParser<One_UUID, newUUID>();
}

// Mixed: test a type that accepts a custom bindata type
TEST(IDLBinData, TestCustomType) {
    IDLParserContext ctxt("root");

    uint8_t testData[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
    auto testDoc = BSON("value" << BSONBinData(testData, 14, BinDataGeneral));

    auto element = testDoc.firstElement();
    ASSERT_EQUALS(element.type(), BinData);
    ASSERT_EQUALS(element.binDataType(), BinDataGeneral);

    auto testStruct = One_bindata_custom::parse(ctxt, testDoc);
    std::vector<std::uint8_t> testVector = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
    ASSERT_TRUE(testStruct.getValue().getVector() == testVector);

    // Positive: Test we can roundtrip from the just parsed document
    {
        BSONObjBuilder builder;
        testStruct.serialize(&builder);
        auto loopbackDoc = builder.obj();

        ASSERT_BSONOBJ_EQ(testDoc, loopbackDoc);
    }

    // Positive: Test we can serialize from nothing the same document
    {
        BSONObjBuilder builder;
        One_bindata_custom one_new;
        one_new.setValue(testVector);
        one_new.serialize(&builder);

        auto serializedDoc = builder.obj();
        ASSERT_BSONOBJ_EQ(testDoc, serializedDoc);
    }
}

// Positive: test a type that accepts a custom UUID type
TEST(IDLBinData, TestUUIDclass) {
    IDLParserContext ctxt("root");

    auto uuid = UUID::gen();
    auto testDoc = BSON("value" << uuid);

    auto element = testDoc.firstElement();
    ASSERT_EQUALS(element.type(), BinData);
    ASSERT_EQUALS(element.binDataType(), newUUID);

    auto testStruct = One_UUID::parse(ctxt, testDoc);
    ASSERT_TRUE(testStruct.getValue() == uuid);

    // Positive: Test we can roundtrip from the just parsed document
    {
        BSONObjBuilder builder;
        testStruct.serialize(&builder);
        auto loopbackDoc = builder.obj();

        ASSERT_BSONOBJ_EQ(testDoc, loopbackDoc);
    }

    // Positive: Test we can serialize from nothing the same document
    {
        BSONObjBuilder builder;
        One_UUID one_new;
        one_new.setValue(uuid);
        one_new.serialize(&builder);

        auto serializedDoc = builder.obj();
        ASSERT_BSONOBJ_EQ(testDoc, serializedDoc);
    }
}

/**
 * A simple class that derives from an IDL generated class
 */
class ClassDerivedFromStruct : public DerivedBaseStruct {
public:
    static ClassDerivedFromStruct parseFromBSON(const IDLParserContext& ctxt,
                                                const BSONObj& bsonObject) {
        ClassDerivedFromStruct o;
        o.parseProtected(ctxt, bsonObject);
        o._done = true;
        return o;
    }

    bool aRandomAdditionalMethod() {
        return true;
    }

    bool getDone() const {
        return _done;
    }

private:
    bool _done = false;
};

// Positive: demonstrate a class derived from an IDL parser.
TEST(IDLCustomType, TestDerivedParser) {
    IDLParserContext ctxt("root");

    auto testDoc = BSON("field1" << 3 << "field2" << 5);

    auto testStruct = ClassDerivedFromStruct::parseFromBSON(ctxt, testDoc);
    ASSERT_EQUALS(testStruct.getField1(), 3);
    ASSERT_EQUALS(testStruct.getField2(), 5);

    ASSERT_EQUALS(testStruct.getDone(), true);

    // Positive: Test we can roundtrip from the just parsed document
    {
        BSONObjBuilder builder;
        testStruct.serialize(&builder);
        auto loopbackDoc = builder.obj();

        ASSERT_BSONOBJ_EQ(testDoc, loopbackDoc);
    }

    // Positive: Test we can serialize from nothing the same document
    {
        BSONObjBuilder builder;
        ClassDerivedFromStruct one_new;
        one_new.setField1(3);
        one_new.setField2(5);
        one_new.serialize(&builder);

        auto serializedDoc = builder.obj();
        ASSERT_BSONOBJ_EQ(testDoc, serializedDoc);
    }
}

// Chained type testing
// Check each of types
// Check for round-tripping of fields and documents

// Positive: demonstrate a class struct chained types
TEST(IDLChainedType, TestChainedType) {
    IDLParserContext ctxt("root");

    auto testDoc = BSON("field1"
                        << "abc"
                        << "field2" << 5);

    auto testStruct = Chained_struct_only::parse(ctxt, testDoc);

    assert_same_types<decltype(testStruct.getChainedType()), const mongo::ChainedType&>();
    assert_same_types<decltype(testStruct.getAnotherChainedType()),
                      const mongo::AnotherChainedType&>();

    ASSERT_EQUALS(testStruct.getChainedType().getField1(), "abc");
    ASSERT_EQUALS(testStruct.getAnotherChainedType().getField2(), 5);

    // Positive: Test we can roundtrip from the just parsed document
    {
        BSONObjBuilder builder;
        testStruct.serialize(&builder);
        auto loopbackDoc = builder.obj();

        ASSERT_BSONOBJ_EQ(testDoc, loopbackDoc);
    }

    // Positive: Test we can serialize from nothing the same document
    {
        BSONObjBuilder builder;
        Chained_struct_only one_new;
        ChainedType ct;
        ct.setField1("abc");
        one_new.setChainedType(ct);
        AnotherChainedType act;
        act.setField2(5);
        one_new.setAnotherChainedType(act);
        one_new.serialize(&builder);

        auto serializedDoc = builder.obj();
        ASSERT_BSONOBJ_EQ(testDoc, serializedDoc);
    }
}

// Positive: demonstrate a struct with chained types ignoring extra fields
TEST(IDLChainedType, TestExtraFields) {
    IDLParserContext ctxt("root");

    auto testDoc = BSON("field1"
                        << "abc"
                        << "field2" << 5 << "field3" << 123456);

    auto testStruct = Chained_struct_only::parse(ctxt, testDoc);
    ASSERT_EQUALS(testStruct.getChainedType().getField1(), "abc");
    ASSERT_EQUALS(testStruct.getAnotherChainedType().getField2(), 5);
}


// Negative: demonstrate a struct with chained types with duplicate fields
TEST(IDLChainedType, TestDuplicateFields) {
    IDLParserContext ctxt("root");

    auto testDoc = BSON("field1"
                        << "abc"
                        << "field2" << 5 << "field2" << 123456);

    ASSERT_THROWS(Chained_struct_only::parse(ctxt, testDoc), AssertionException);
}


// Positive: demonstrate a struct with chained structs
TEST(IDLChainedType, TestChainedStruct) {
    IDLParserContext ctxt("root");

    auto testDoc = BSON("anyField" << 123.456 << "objectField"
                                   << BSON("random"
                                           << "pair")
                                   << "field3"
                                   << "abc");

    auto testStruct = Chained_struct_mixed::parse(ctxt, testDoc);

    assert_same_types<decltype(testStruct.getChained_any_basic_type()), Chained_any_basic_type&>();
    assert_same_types<decltype(testStruct.getChainedObjectBasicType()),
                      Chained_object_basic_type&>();

    ASSERT_EQUALS(testStruct.getField3(), "abc");

    // Positive: Test we can roundtrip from the just parsed document
    {
        BSONObjBuilder builder;
        testStruct.serialize(&builder);
        auto loopbackDoc = builder.obj();

        // Serializer should include fields with default values.
        ASSERT_BSONOBJ_EQ(BSON("anyField" << 123.456 << "objectField"
                                          << BSON("random"
                                                  << "pair")
                                          << "enumField"  // Should be ahead of 'field3'.
                                          << "zero"
                                          << "field3"
                                          << "abc"),
                          loopbackDoc);
    }
}

// Negative: demonstrate a struct with chained structs and extra fields
TEST(IDLChainedType, TestChainedStructWithExtraFields) {
    IDLParserContext ctxt("root");

    // Extra field
    {
        auto testDoc = BSON("field3"
                            << "abc"
                            << "anyField" << 123.456 << "objectField"
                            << BSON("random"
                                    << "pair")
                            << "extraField" << 787);
        ASSERT_THROWS(Chained_struct_mixed::parse(ctxt, testDoc), AssertionException);
    }


    // Duplicate any
    {
        auto testDoc = BSON("field3"
                            << "abc"
                            << "anyField" << 123.456 << "objectField"
                            << BSON("random"
                                    << "pair")
                            << "anyField" << 787);
        ASSERT_THROWS(Chained_struct_mixed::parse(ctxt, testDoc), AssertionException);
    }

    // Duplicate object
    {
        auto testDoc = BSON("objectField" << BSON("fake"
                                                  << "thing")
                                          << "field3"
                                          << "abc"
                                          << "anyField" << 123.456 << "objectField"
                                          << BSON("random"
                                                  << "pair"));
        ASSERT_THROWS(Chained_struct_mixed::parse(ctxt, testDoc), AssertionException);
    }

    // Duplicate field3
    {
        auto testDoc = BSON("field3"
                            << "abc"
                            << "anyField" << 123.456 << "objectField"
                            << BSON("random"
                                    << "pair")
                            << "field3"
                            << "def");
        ASSERT_THROWS(Chained_struct_mixed::parse(ctxt, testDoc), AssertionException);
    }
}


// Positive: demonstrate a struct with chained structs and types
TEST(IDLChainedType, TestChainedMixedStruct) {
    IDLParserContext ctxt("root");

    auto testDoc = BSON("field1"
                        << "abc"
                        << "field2" << 5 << "stringField"
                        << "def"
                        << "field3" << 456);

    auto testStruct = Chained_struct_type_mixed::parse(ctxt, testDoc);

    assert_same_types<decltype(testStruct.getChained_type()), const mongo::ChainedType&>();
    assert_same_types<decltype(testStruct.getAnotherChainedType()),
                      const mongo::AnotherChainedType&>();

    ASSERT_EQUALS(testStruct.getChained_type().getField1(), "abc");
    ASSERT_EQUALS(testStruct.getAnotherChainedType().getField2(), 5);
    ASSERT_EQUALS(testStruct.getChainedStringBasicType().getStringField(), "def");
    ASSERT_EQUALS(testStruct.getField3(), 456);

    // Positive: Test we can roundtrip from the just parsed document
    {
        BSONObjBuilder builder;
        testStruct.serialize(&builder);
        auto loopbackDoc = builder.obj();

        ASSERT_BSONOBJ_EQ(testDoc, loopbackDoc);
    }

    // Positive: Test we can serialize from nothing the same document
    {
        BSONObjBuilder builder;
        Chained_struct_type_mixed one_new;
        ChainedType ct;
        ct.setField1("abc");
        one_new.setChained_type(ct);
        AnotherChainedType act;
        act.setField2(5);
        one_new.setAnotherChainedType(act);
        one_new.setField3(456);
        Chained_string_basic_type csbt;
        csbt.setStringField("def");
        one_new.setChainedStringBasicType(csbt);
        one_new.serialize(&builder);

        auto serializedDoc = builder.obj();
        ASSERT_BSONOBJ_EQ(testDoc, serializedDoc);
    }
}
// Positive: demonstrate a class derived from an IDL parser.
TEST(IDLEnum, TestEnum) {

    IDLParserContext ctxt("root");

    auto testDoc = BSON("field1" << 2 << "field2"
                                 << "zero");
    auto testStruct = StructWithEnum::parse(ctxt, testDoc);
    ASSERT_TRUE(testStruct.getField1() == IntEnum::c2);
    ASSERT_TRUE(testStruct.getField2() == StringEnumEnum::s0);
    ASSERT_TRUE(testStruct.getFieldDefault() == StringEnumEnum::s1);

    assert_same_types<decltype(testStruct.getField1()), IntEnum>();
    assert_same_types<decltype(testStruct.getField1o()), boost::optional<IntEnum>>();
    assert_same_types<decltype(testStruct.getField2()), StringEnumEnum>();
    assert_same_types<decltype(testStruct.getField2o()), boost::optional<StringEnumEnum>>();
    assert_same_types<decltype(testStruct.getFieldDefault()), StringEnumEnum>();

    auto testSerializedDoc = BSON("field1" << 2 << "field2"
                                           << "zero"
                                           << "fieldDefault"
                                           << "one");


    // Positive: Test we can roundtrip from the just parsed document
    {
        BSONObjBuilder builder;
        testStruct.serialize(&builder);
        auto loopbackDoc = builder.obj();

        ASSERT_BSONOBJ_EQ(testSerializedDoc, loopbackDoc);
    }

    // Positive: Test we can serialize from nothing the same document
    {
        BSONObjBuilder builder;
        StructWithEnum one_new;
        one_new.setField1(IntEnum::c2);
        one_new.setField2(StringEnumEnum::s0);
        one_new.serialize(&builder);

        auto serializedDoc = builder.obj();
        ASSERT_BSONOBJ_EQ(testSerializedDoc, serializedDoc);
    }
}


// Negative: test bad values
TEST(IDLEnum, TestIntEnumNegative) {
    IDLParserContext ctxt("root");

    //  Test string
    {
        auto testDoc = BSON("value"
                            << "2");
        ASSERT_THROWS(One_int_enum::parse(ctxt, testDoc), AssertionException);
    }

    // Test a value out of range
    {
        auto testDoc = BSON("value" << 4);
        ASSERT_THROWS(One_int_enum::parse(ctxt, testDoc), AssertionException);
    }

    // Test a negative number
    {
        auto testDoc = BSON("value" << -1);
        ASSERT_THROWS(One_int_enum::parse(ctxt, testDoc), AssertionException);
    }
}

TEST(IDLEnum, TestStringEnumNegative) {
    IDLParserContext ctxt("root");

    //  Test int
    {
        auto testDoc = BSON("value" << 2);
        ASSERT_THROWS(One_string_enum::parse(ctxt, testDoc), AssertionException);
    }

    // Test a value out of range
    {
        auto testDoc = BSON("value"
                            << "foo");
        ASSERT_THROWS(One_string_enum::parse(ctxt, testDoc), AssertionException);
    }
}

TEST(IDLEnum, ExtraDataEnum) {
    auto s0Data = ExtraDataEnum_get_extra_data(ExtraDataEnumEnum::s0);
    ASSERT_BSONOBJ_EQ(s0Data, BSONObj());

    auto s1Data = ExtraDataEnum_get_extra_data(ExtraDataEnumEnum::s1);
    ASSERT_BSONOBJ_EQ(s1Data, BSONObj());

    auto s2Data = ExtraDataEnum_get_extra_data(ExtraDataEnumEnum::s2);
    auto s2Expected = fromjson(R"json({ foo: [{bar: "baz"}], baz: "\"qu\\\\nx\"" })json");
    ASSERT_BSONOBJ_EQ(s2Data, s2Expected);
}

OpMsgRequest makeOMR(BSONObj obj) {
    OpMsgRequest request;
    request.body = obj;
    return request;
}

OpMsgRequest makeOMRWithTenant(BSONObj obj, TenantId tenant) {
    OpMsgRequest request;
    request.body = obj;

    using VTS = auth::ValidatedTenancyScope;
    request.validatedTenancyScope = VTS(std::move(tenant), VTS::TenantForTestingTag{});
    return request;
}

// Positive: demonstrate a command with concatenate with db
TEST(IDLCommand, TestConcatentateWithDb) {
    IDLParserContext ctxt("root");

    auto testDoc = BSON(BasicConcatenateWithDbCommand::kCommandName << "coll1"
                                                                    << "field1" << 3 << "field2"
                                                                    << "five"
                                                                    << "$db"
                                                                    << "db");

    auto testStruct = BasicConcatenateWithDbCommand::parse(ctxt, makeOMR(testDoc));
    ASSERT_EQUALS(testStruct.getField1(), 3);
    ASSERT_EQUALS(testStruct.getField2(), "five");
    ASSERT_EQUALS(testStruct.getNamespace(),
                  NamespaceString::createNamespaceString_forTest("db.coll1"));

    assert_same_types<decltype(testStruct.getNamespace()), const NamespaceString&>();

    // Positive: Test we can roundtrip from the just parsed document
    ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(testStruct));

    // Positive: Test we can serialize from nothing the same document except for $db
    {
        auto testDocWithoutDb =
            BSON(BasicConcatenateWithDbCommand::kCommandName << "coll1"
                                                             << "field1" << 3 << "field2"
                                                             << "five");

        BSONObjBuilder builder;
        BasicConcatenateWithDbCommand one_new(
            NamespaceString::createNamespaceString_forTest("db.coll1"));
        one_new.setField1(3);
        one_new.setField2("five");
        one_new.serialize(BSONObj(), &builder);

        auto serializedDoc = builder.obj();
        ASSERT_BSONOBJ_EQ(testDocWithoutDb, serializedDoc);
    }

    // Positive: Test we can serialize from nothing the same document
    {
        BasicConcatenateWithDbCommand one_new(
            NamespaceString::createNamespaceString_forTest("db.coll1"));
        one_new.setField1(3);
        one_new.setField2("five");
        ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(testStruct));
    }
}

TEST(IDLCommand, TestConcatentateWithDb_WithTenant) {
    RAIIServerParameterControllerForTest multitenanyController("multitenancySupport", true);
    IDLParserContext ctxt("root");

    const auto tenantId = TenantId(OID::gen());
    const auto prefixedDb = std::string(str::stream() << tenantId.toString() << "_db");

    auto testDoc = BSONObjBuilder{}
                       .append(BasicConcatenateWithDbCommand::kCommandName, "coll1")
                       .append("field1", 3)
                       .append("field2", "five")
                       .append("$db", prefixedDb)
                       .obj();

    auto testStruct =
        BasicConcatenateWithDbCommand::parse(ctxt, makeOMRWithTenant(testDoc, tenantId));
    ASSERT_EQUALS(testStruct.getDbName(), DatabaseName(tenantId, "db"));
    ASSERT_EQUALS(testStruct.getNamespace(),
                  NamespaceString::createNamespaceString_forTest(tenantId, "db.coll1"));

    assert_same_types<decltype(testStruct.getNamespace()), const NamespaceString&>();

    // Positive: Test we can roundtrip from the just parsed document
    ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(testStruct));
}

TEST(IDLCommand, TestConcatentateWithDb_TestConstructor) {
    const auto tenantId = TenantId(OID::gen());
    const DatabaseName dbName(tenantId, "db");

    const NamespaceString nss = NamespaceString::createNamespaceString_forTest(dbName, "coll1");
    BasicConcatenateWithDbCommand testRequest(nss);
    ASSERT_EQUALS(testRequest.getDbName().tenantId(), dbName.tenantId());
    ASSERT_EQUALS(testRequest.getDbName(), dbName);
}

TEST(IDLCommand, TestConcatentateWithDbSymbol) {
    IDLParserContext ctxt("root");

    // Postive - symbol???
    {
        auto testDoc =
            BSON("BasicConcatenateWithDbCommand" << BSONSymbol("coll1") << "field1" << 3 << "field2"
                                                 << "five"
                                                 << "$db"
                                                 << "db");
        auto testStruct = BasicConcatenateWithDbCommand::parse(ctxt, makeOMR(testDoc));
        ASSERT_EQUALS(testStruct.getNamespace(),
                      NamespaceString::createNamespaceString_forTest("db.coll1"));
    }
}


TEST(IDLCommand, TestConcatentateWithDbNegative) {
    IDLParserContext ctxt("root");

    // Negative - duplicate namespace field
    {
        auto testDoc =
            BSON("BasicConcatenateWithDbCommand" << 1 << "field1" << 3
                                                 << "BasicConcatenateWithDbCommand" << 1 << "field2"
                                                 << "five");
        ASSERT_THROWS(BasicConcatenateWithDbCommand::parse(ctxt, makeOMR(testDoc)),
                      AssertionException);
    }

    // Negative -  namespace field wrong order
    {
        auto testDoc = BSON("field1" << 3 << "BasicConcatenateWithDbCommand" << 1 << "field2"
                                     << "five");
        ASSERT_THROWS(BasicConcatenateWithDbCommand::parse(ctxt, makeOMR(testDoc)),
                      AssertionException);
    }

    // Negative -  namespace missing
    {
        auto testDoc = BSON("field1" << 3 << "field2"
                                     << "five");
        ASSERT_THROWS(BasicConcatenateWithDbCommand::parse(ctxt, makeOMR(testDoc)),
                      AssertionException);
    }

    // Negative - wrong type
    {
        auto testDoc = BSON("BasicConcatenateWithDbCommand" << 1 << "field1" << 3 << "field2"
                                                            << "five");
        ASSERT_THROWS(BasicConcatenateWithDbCommand::parse(ctxt, makeOMR(testDoc)),
                      AssertionException);
    }

    // Negative - bad ns with embedded null
    {
        StringData sd1("db\0foo", 6);
        auto testDoc = BSON("BasicConcatenateWithDbCommand" << sd1 << "field1" << 3 << "field2"
                                                            << "five");
        ASSERT_THROWS(BasicConcatenateWithDbCommand::parse(ctxt, makeOMR(testDoc)),
                      AssertionException);
    }
}

// Positive: demonstrate a command with concatenate with db or uuid - test NSS
TEST(IDLCommand, TestConcatentateWithDbOrUUID_TestNSS) {
    IDLParserContext ctxt("root");

    auto testDoc =
        BSON(BasicConcatenateWithDbOrUUIDCommand::kCommandName << "coll1"
                                                               << "field1" << 3 << "field2"
                                                               << "five"
                                                               << "$db"
                                                               << "db");

    auto testStruct = BasicConcatenateWithDbOrUUIDCommand::parse(ctxt, makeOMR(testDoc));
    ASSERT_EQUALS(testStruct.getField1(), 3);
    ASSERT_EQUALS(testStruct.getField2(), "five");
    ASSERT_EQUALS(testStruct.getNamespaceOrUUID().nss().value(),
                  NamespaceString::createNamespaceString_forTest("db.coll1"));

    assert_same_types<decltype(testStruct.getNamespaceOrUUID()), const NamespaceStringOrUUID&>();

    // Positive: Test we can roundtrip from the just parsed document
    ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(testStruct));

    // Positive: Test we can serialize from nothing the same document except for $db
    {
        auto testDocWithoutDb =
            BSON(BasicConcatenateWithDbOrUUIDCommand::kCommandName << "coll1"
                                                                   << "field1" << 3 << "field2"
                                                                   << "five");

        BSONObjBuilder builder;
        BasicConcatenateWithDbOrUUIDCommand one_new(
            NamespaceString::createNamespaceString_forTest("db.coll1"));
        one_new.setField1(3);
        one_new.setField2("five");
        one_new.serialize(BSONObj(), &builder);

        auto serializedDoc = builder.obj();
        ASSERT_BSONOBJ_EQ(testDocWithoutDb, serializedDoc);
    }

    // Positive: Test we can serialize from nothing the same document
    {
        BasicConcatenateWithDbOrUUIDCommand one_new(
            NamespaceString::createNamespaceString_forTest("db.coll1"));
        one_new.setField1(3);
        one_new.setField2("five");
        ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(one_new));
    }
}

TEST(IDLCommand, TestConcatentateWithDbOrUUID_TestNSS_WithTenant) {
    RAIIServerParameterControllerForTest multitenanyController("multitenancySupport", true);
    IDLParserContext ctxt("root");

    const auto tenantId = TenantId(OID::gen());
    const auto prefixedDb = std::string(str::stream() << tenantId.toString() << "_db");

    auto testDoc = BSONObjBuilder{}
                       .append(BasicConcatenateWithDbOrUUIDCommand::kCommandName, "coll1")
                       .append("field1", 3)
                       .append("field2", "five")
                       .append("$db", prefixedDb)
                       .obj();

    auto testStruct =
        BasicConcatenateWithDbOrUUIDCommand::parse(ctxt, makeOMRWithTenant(testDoc, tenantId));
    ASSERT_EQUALS(testStruct.getDbName(), DatabaseName(tenantId, "db"));
    ASSERT_EQUALS(testStruct.getNamespaceOrUUID().nss().value(),
                  NamespaceString::createNamespaceString_forTest(tenantId, "db.coll1"));

    assert_same_types<decltype(testStruct.getNamespaceOrUUID()), const NamespaceStringOrUUID&>();

    // Positive: Test we can roundtrip from the just parsed document
    ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(testStruct));
}

// Positive: demonstrate a command with concatenate with db or uuid - test UUID
TEST(IDLCommand, TestConcatentateWithDbOrUUID_TestUUID) {
    IDLParserContext ctxt("root");

    UUID uuid = UUID::gen();

    auto testDoc =
        BSON(BasicConcatenateWithDbOrUUIDCommand::kCommandName << uuid << "field1" << 3 << "field2"
                                                               << "five"
                                                               << "$db"
                                                               << "db");

    auto testStruct = BasicConcatenateWithDbOrUUIDCommand::parse(ctxt, makeOMR(testDoc));
    ASSERT_EQUALS(testStruct.getField1(), 3);
    ASSERT_EQUALS(testStruct.getField2(), "five");
    ASSERT_EQUALS(testStruct.getNamespaceOrUUID().uuid().value(), uuid);

    assert_same_types<decltype(testStruct.getNamespaceOrUUID()), const NamespaceStringOrUUID&>();

    // Positive: Test we can roundtrip from the just parsed document
    ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(testStruct));

    // Positive: Test we can serialize from nothing the same document except for $db
    {
        auto testDocWithoutDb = BSON(BasicConcatenateWithDbOrUUIDCommand::kCommandName
                                     << uuid << "field1" << 3 << "field2"
                                     << "five");

        BSONObjBuilder builder;
        BasicConcatenateWithDbOrUUIDCommand one_new(NamespaceStringOrUUID("db", uuid));
        one_new.setField1(3);
        one_new.setField2("five");
        one_new.serialize(BSONObj(), &builder);

        auto serializedDoc = builder.obj();
        ASSERT_BSONOBJ_EQ(testDocWithoutDb, serializedDoc);
    }

    // Positive: Test we can serialize from nothing the same document
    {
        BasicConcatenateWithDbOrUUIDCommand one_new(NamespaceStringOrUUID("db", uuid));
        one_new.setField1(3);
        one_new.setField2("five");
        ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(one_new));
    }
}

TEST(IDLCommand, TestConcatentateWithDbOrUUID_TestUUID_WithTenant) {
    RAIIServerParameterControllerForTest multitenanyController("multitenancySupport", true);
    IDLParserContext ctxt("root");

    UUID uuid = UUID::gen();
    const auto tenantId = TenantId(OID::gen());
    const auto prefixedDb = std::string(str::stream() << tenantId.toString() << "_db");

    auto testDoc =
        BSONObjBuilder{}
            .appendElements(BSON(BasicConcatenateWithDbOrUUIDCommand::kCommandName << uuid))
            .append("field1", 3)
            .append("field2", "five")
            .append("$db", prefixedDb)
            .obj();

    auto testStruct =
        BasicConcatenateWithDbOrUUIDCommand::parse(ctxt, makeOMRWithTenant(testDoc, tenantId));
    ASSERT_EQUALS(testStruct.getDbName(), DatabaseName(tenantId, "db"));
    ASSERT_EQUALS(testStruct.getNamespaceOrUUID().dbName().value(), DatabaseName(tenantId, "db"));

    assert_same_types<decltype(testStruct.getNamespaceOrUUID()), const NamespaceStringOrUUID&>();

    // Positive: Test we can roundtrip from the just parsed document
    ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(testStruct));
}

TEST(IDLCommand, TestConcatentateWithDbOrUUID_TestConstructor) {
    const UUID uuid = UUID::gen();
    const auto tenantId = TenantId(OID::gen());
    const DatabaseName dbName(tenantId, "db");

    const NamespaceStringOrUUID withUUID(dbName, uuid);
    BasicConcatenateWithDbOrUUIDCommand testRequest1(withUUID);
    ASSERT_EQUALS(testRequest1.getDbName().tenantId(), dbName.tenantId());
    ASSERT_EQUALS(testRequest1.getDbName(), dbName);

    const NamespaceStringOrUUID withNss(
        NamespaceString::createNamespaceString_forTest(dbName, "coll1"));
    BasicConcatenateWithDbOrUUIDCommand testRequest2(withNss);
    ASSERT_EQUALS(testRequest2.getDbName().tenantId(), dbName.tenantId());
    ASSERT_EQUALS(testRequest2.getDbName(), dbName);
}

TEST(IDLCommand, TestConcatentateWithDbOrUUIDNegative) {
    IDLParserContext ctxt("root");

    // Negative - duplicate namespace field
    {
        auto testDoc =
            BSON("BasicConcatenateWithDbOrUUIDCommand"
                 << 1 << "field1" << 3 << "BasicConcatenateWithDbOrUUIDCommand" << 1 << "field2"
                 << "five");
        ASSERT_THROWS(BasicConcatenateWithDbOrUUIDCommand::parse(ctxt, makeOMR(testDoc)),
                      AssertionException);
    }

    // Negative -  namespace field wrong order
    {
        auto testDoc = BSON("field1" << 3 << "BasicConcatenateWithDbOrUUIDCommand" << 1 << "field2"
                                     << "five");
        ASSERT_THROWS(BasicConcatenateWithDbOrUUIDCommand::parse(ctxt, makeOMR(testDoc)),
                      AssertionException);
    }

    // Negative -  namespace missing
    {
        auto testDoc = BSON("field1" << 3 << "field2"
                                     << "five");
        ASSERT_THROWS(BasicConcatenateWithDbOrUUIDCommand::parse(ctxt, makeOMR(testDoc)),
                      AssertionException);
    }

    // Negative - wrong type
    {
        auto testDoc = BSON("BasicConcatenateWithDbOrUUIDCommand" << 1 << "field1" << 3 << "field2"
                                                                  << "five");
        ASSERT_THROWS(BasicConcatenateWithDbOrUUIDCommand::parse(ctxt, makeOMR(testDoc)),
                      AssertionException);
    }

    // Negative - bad ns with embedded null
    {
        StringData sd1("db\0foo", 6);
        auto testDoc =
            BSON("BasicConcatenateWithDbOrUUIDCommand" << sd1 << "field1" << 3 << "field2"
                                                       << "five");
        ASSERT_THROWS(BasicConcatenateWithDbOrUUIDCommand::parse(ctxt, makeOMR(testDoc)),
                      AssertionException);
    }
}


// Positive: demonstrate a command with concatenate with db
TEST(IDLCommand, TestIgnore) {
    IDLParserContext ctxt("root");

    auto testDoc = BSON("BasicIgnoredCommand" << 1 << "field1" << 3 << "field2"
                                              << "five");

    auto testDocWithDB = appendDB(testDoc, "admin");

    auto testStruct = BasicIgnoredCommand::parse(ctxt, makeOMR(testDocWithDB));
    ASSERT_EQUALS(testStruct.getField1(), 3);
    ASSERT_EQUALS(testStruct.getField2(), "five");

    // Positive: Test we can roundtrip from the just parsed document
    {
        BSONObjBuilder builder;
        testStruct.serialize(BSONObj(), &builder);
        auto loopbackDoc = builder.obj();

        ASSERT_BSONOBJ_EQ(testDoc, loopbackDoc);
    }

    // Positive: Test we can serialize from nothing the same document
    {
        BasicIgnoredCommand one_new;
        one_new.setField1(3);
        one_new.setField2("five");
        one_new.setDbName(DatabaseName(boost::none, "admin"));
        ASSERT_BSONOBJ_EQ(testDocWithDB, serializeCmd(one_new));
    }
}


TEST(IDLCommand, TestIgnoredNegative) {
    IDLParserContext ctxt("root");

    // Negative - duplicate namespace field
    {
        auto testDoc = BSON("BasicIgnoredCommand" << 1 << "field1" << 3 << "BasicIgnoredCommand"
                                                  << 1 << "field2"
                                                  << "five");
        ASSERT_THROWS(BasicIgnoredCommand::parse(ctxt, makeOMR(testDoc)), AssertionException);
    }

    // Negative -  namespace field wrong order
    {
        auto testDoc = BSON("field1" << 3 << "BasicIgnoredCommand" << 1 << "field2"
                                     << "five");
        ASSERT_THROWS(BasicIgnoredCommand::parse(ctxt, makeOMR(testDoc)), AssertionException);
    }

    // Negative -  namespace missing
    {
        auto testDoc = BSON("field1" << 3 << "field2"
                                     << "five");
        ASSERT_THROWS(BasicIgnoredCommand::parse(ctxt, makeOMR(testDoc)), AssertionException);
    }
}

// We don't generate comparison operators like "==" for variants, so test only for BSON equality.
template <typename CommandT, typename TestT, BSONType Test_bson_type>
void TestLoopbackCommandTypeVariant(TestT test_value) {
    IDLParserContext ctxt("root");

    BSONObjBuilder bob;
    if constexpr (idl::hasBSONSerialize<TestT>) {
        // TestT might be an IDL struct type like One_string.
        BSONObjBuilder subObj(bob.subobjStart(CommandT::kCommandParameterFieldName));
        test_value.serialize(&subObj);
    } else if constexpr (std::is_same_v<TestT, UUID>) {
        test_value.appendToBuilder(&bob, CommandT::kCommandParameterFieldName);
    } else {
        bob.append(CommandT::kCommandParameterFieldName, test_value);
    }

    bob.append("$db", "db");
    auto obj = bob.obj();
    auto element = obj.firstElement();
    ASSERT_EQUALS(element.type(), Test_bson_type);

    auto parsed = CommandT::parse(ctxt, obj);
    if constexpr (std::is_same_v<TestT, BSONObj>) {
        ASSERT_BSONOBJ_EQ(stdx::get<TestT>(parsed.getValue()), test_value);
    } else {
        // Use ASSERT instead of ASSERT_EQ to avoid operator<<
        ASSERT(stdx::get<TestT>(parsed.getCommandParameter()) == test_value);
    }
    ASSERT_BSONOBJ_EQ(obj, serializeCmd(parsed));

    // Test the constructor.
    CommandT constructed(test_value);
    constructed.setDbName(DatabaseName(boost::none, "db"));
    if constexpr (std::is_same_v<TestT, BSONObj>) {
        ASSERT_BSONOBJ_EQ(stdx::get<TestT>(parsed.getValue()), test_value);
    } else {
        ASSERT(stdx::get<TestT>(parsed.getCommandParameter()) == test_value);
    }
    ASSERT_BSONOBJ_EQ(obj, serializeCmd(constructed));
}

TEST(IDLCommand, TestCommandTypeVariant) {
    TestLoopbackCommandTypeVariant<CommandTypeVariantCommand, int, NumberInt>(1);
    TestLoopbackCommandTypeVariant<CommandTypeVariantCommand, std::string, String>("test_value");
    TestLoopbackCommandTypeVariant<CommandTypeVariantCommand, std::vector<std::string>, Array>(
        {"x", "y"});

    TestLoopbackCommandTypeVariant<CommandTypeVariantUUIDCommand, int, NumberInt>(1);
    TestLoopbackCommandTypeVariant<CommandTypeVariantUUIDCommand, UUID, BinData>(UUID::gen());

    TestLoopbackCommandTypeVariant<CommandTypeVariantStructCommand, bool, Bool>(true);
    TestLoopbackCommandTypeVariant<CommandTypeVariantStructCommand, One_string, Object>(
        One_string("test_value"));
}

TEST(IDLDocSequence, TestBasic) {
    IDLParserContext ctxt("root");

    auto testTempDoc = BSON("DocSequenceCommand"
                            << "coll1"
                            << "field1" << 3 << "field2"
                            << "five"
                            << "$db"
                            << "db"
                            << "structs"
                            << BSON_ARRAY(BSON("value"
                                               << "hello")
                                          << BSON("value"
                                                  << "world"))
                            << "objects" << BSON_ARRAY(BSON("foo" << 1)));

    OpMsgRequest request;
    request.body = testTempDoc;

    auto testStruct = DocSequenceCommand::parse(ctxt, request);
    ASSERT_EQUALS(testStruct.getField1(), 3);
    ASSERT_EQUALS(testStruct.getField2(), "five");
    ASSERT_EQUALS(testStruct.getNamespace(),
                  NamespaceString::createNamespaceString_forTest("db.coll1"));

    ASSERT_EQUALS(2UL, testStruct.getStructs().size());
    ASSERT_EQUALS("hello", testStruct.getStructs()[0].getValue());
    ASSERT_EQUALS("world", testStruct.getStructs()[1].getValue());

    assert_same_types<decltype(testStruct.getNamespace()), const NamespaceString&>();

    // Positive: Test we can round trip to a document sequence from the just parsed document
    {
        OpMsgRequest loopbackRequest = testStruct.serialize(BSONObj());

        assertOpMsgEquals(request, loopbackRequest);
        ASSERT_EQUALS(loopbackRequest.sequences.size(), 2UL);
    }

    // Positive: Test we can roundtrip just the body from the just parsed document
    {
        BSONObjBuilder builder;
        testStruct.serialize(BSONObj(), &builder);

        auto testTempDocWithoutDB = testTempDoc.removeField("$db");

        ASSERT_BSONOBJ_EQ(testTempDocWithoutDB, builder.obj());
    }

    // Positive: Test we can serialize from nothing the same document
    {
        BSONObjBuilder builder;
        DocSequenceCommand one_new(NamespaceString::createNamespaceString_forTest("db.coll1"));
        one_new.setField1(3);
        one_new.setField2("five");

        std::vector<One_string> strings;
        One_string one_string;
        one_string.setValue("hello");
        strings.push_back(one_string);
        One_string one_string2;
        one_string2.setValue("world");
        strings.push_back(one_string2);
        one_new.setStructs(strings);

        std::vector<BSONObj> objects;
        objects.push_back(BSON("foo" << 1));
        one_new.setObjects(objects);

        OpMsgRequest serializeRequest = one_new.serialize(BSONObj());

        assertOpMsgEquals(request, serializeRequest);
    }
}

// Negative: Test a OpMsgRequest read without $db
TEST(IDLDocSequence, TestMissingDB) {
    IDLParserContext ctxt("root");

    auto testTempDoc = BSON("DocSequenceCommand"
                            << "coll1"
                            << "field1" << 3 << "field2"
                            << "five"
                            << "structs"
                            << BSON_ARRAY(BSON("value"
                                               << "hello"))
                            << "objects" << BSON_ARRAY(BSON("foo" << 1)));

    OpMsgRequest request;
    request.body = testTempDoc;

    ASSERT_THROWS(DocSequenceCommand::parse(ctxt, request), AssertionException);
}

// Positive: Test a command read and written to OpMsgRequest with content in DocumentSequence works
template <typename TestT>
void TestDocSequence(StringData name) {
    IDLParserContext ctxt("root");

    auto testTempDoc = BSON(name << "coll1"
                                 << "field1" << 3 << "field2"
                                 << "five");

    OpMsgRequest request = OpMsgRequest::fromDBAndBody("db", testTempDoc);
    request.sequences.push_back({"structs",
                                 {BSON("value"
                                       << "hello"),
                                  BSON("value"
                                       << "world")}});
    request.sequences.push_back({"objects", {BSON("foo" << 1)}});

    auto testStruct = TestT::parse(ctxt, request);
    ASSERT_EQUALS(testStruct.getField1(), 3);
    ASSERT_EQUALS(testStruct.getField2(), "five");
    ASSERT_EQUALS(testStruct.getNamespace(),
                  NamespaceString::createNamespaceString_forTest("db.coll1"));

    ASSERT_EQUALS(2UL, testStruct.getStructs().size());
    ASSERT_EQUALS("hello", testStruct.getStructs()[0].getValue());
    ASSERT_EQUALS("world", testStruct.getStructs()[1].getValue());

    auto opmsg = testStruct.serialize(BSONObj());
    ASSERT_EQUALS(2UL, opmsg.sequences.size());

    assertOpMsgEquals(opmsg, request);
    assertOpMsgEqualsExact(opmsg, request);
}

// Positive: Test a command read and written to OpMsgRequest with content in DocumentSequence works
TEST(IDLDocSequence, TestDocSequence) {
    TestDocSequence<DocSequenceCommand>("DocSequenceCommand");
    TestDocSequence<DocSequenceCommandNonStrict>("DocSequenceCommandNonStrict");
}

// Negative: Bad Doc Sequences
template <typename TestT>
void TestBadDocSequences(StringData name, bool extraFieldAllowed) {
    IDLParserContext ctxt("root");

    auto testTempDoc = BSON(name << "coll1"
                                 << "field1" << 3 << "field2"
                                 << "five");

    // Negative: Duplicate fields in doc sequence
    {
        OpMsgRequest request = OpMsgRequest::fromDBAndBody("db", testTempDoc);
        request.sequences.push_back({"structs",
                                     {BSON("value"
                                           << "hello"),
                                      BSON("value"
                                           << "world")}});
        request.sequences.push_back({"structs", {BSON("foo" << 1)}});

        ASSERT_THROWS(TestT::parse(ctxt, request), AssertionException);
    }

    // Negative: Extra field in document sequence
    {
        OpMsgRequest request = OpMsgRequest::fromDBAndBody("db", testTempDoc);
        request.sequences.push_back({"structs",
                                     {BSON("value"
                                           << "hello"),
                                      BSON("value"
                                           << "world")}});
        request.sequences.push_back({"objects", {BSON("foo" << 1)}});
        request.sequences.push_back({"extra", {BSON("foo" << 1)}});

        if (!extraFieldAllowed) {
            ASSERT_THROWS(TestT::parse(ctxt, request), AssertionException);
        } else {
            /*void*/ TestT::parse(ctxt, request);
        }
    }

    // Negative: Missing field in both document sequence and body
    {
        OpMsgRequest request = OpMsgRequest::fromDBAndBody("db", testTempDoc);
        request.sequences.push_back({"objects", {BSON("foo" << 1)}});

        ASSERT_THROWS(TestT::parse(ctxt, request), AssertionException);
    }

    // Negative: Missing field in both document sequence and body
    {
        OpMsgRequest request = OpMsgRequest::fromDBAndBody("db", testTempDoc);
        request.sequences.push_back({"structs",
                                     {BSON("value"
                                           << "hello"),
                                      BSON("value"
                                           << "world")}});

        ASSERT_THROWS(TestT::parse(ctxt, request), AssertionException);
    }
}

// Negative: Bad Doc Sequences
TEST(IDLDocSequence, TestBadDocSequences) {
    TestBadDocSequences<DocSequenceCommand>("DocSequenceCommand", false);
    TestBadDocSequences<DocSequenceCommandNonStrict>("DocSequenceCommandNonStrict", true);
}

// Negative: Duplicate field across body and document sequence
template <typename TestT>
void TestDuplicateDocSequences(StringData name) {
    IDLParserContext ctxt("root");

    // Negative: Duplicate fields in doc sequence and body
    {
        auto testTempDoc = BSON(name << "coll1"
                                     << "field1" << 3 << "field2"
                                     << "five"
                                     << "structs"
                                     << BSON_ARRAY(BSON("value"
                                                        << "hello")
                                                   << BSON("value"
                                                           << "world"))
                                     << "objects" << BSON_ARRAY(BSON("foo" << 1)));

        OpMsgRequest request = OpMsgRequest::fromDBAndBody("db", testTempDoc);
        request.sequences.push_back({"structs",
                                     {BSON("value"
                                           << "hello"),
                                      BSON("value"
                                           << "world")}});

        ASSERT_THROWS(DocSequenceCommand::parse(ctxt, request), AssertionException);
    }

    // Negative: Duplicate fields in doc sequence and body
    {
        auto testTempDoc = BSON(name << "coll1"
                                     << "field1" << 3 << "field2"
                                     << "five"
                                     << "structs"
                                     << BSON_ARRAY(BSON("value"
                                                        << "hello")
                                                   << BSON("value"
                                                           << "world"))
                                     << "objects" << BSON_ARRAY(BSON("foo" << 1)));

        OpMsgRequest request = OpMsgRequest::fromDBAndBody("db", testTempDoc);
        request.sequences.push_back({"objects", {BSON("foo" << 1)}});

        ASSERT_THROWS(DocSequenceCommand::parse(ctxt, request), AssertionException);
    }
}

// Negative: Duplicate field across body and document sequence
TEST(IDLDocSequence, TestDuplicateDocSequences) {
    TestDuplicateDocSequences<DocSequenceCommand>("DocSequenceCommand");
    TestDuplicateDocSequences<DocSequenceCommandNonStrict>("DocSequenceCommandNonStrict");
}

// Positive: Test empty document sequence
TEST(IDLDocSequence, TestEmptySequence) {
    IDLParserContext ctxt("root");

    // Negative: Duplicate fields in doc sequence and body
    {
        auto testTempDoc = BSON("DocSequenceCommand"
                                << "coll1"
                                << "field1" << 3 << "field2"
                                << "five"
                                << "structs"
                                << BSON_ARRAY(BSON("value"
                                                   << "hello")
                                              << BSON("value"
                                                      << "world"))
                                << "objects" << BSON_ARRAY(BSON("foo" << 1)));

        OpMsgRequest request = OpMsgRequest::fromDBAndBody("db", testTempDoc);
        request.sequences.push_back({"structs", {}});

        ASSERT_THROWS(DocSequenceCommand::parse(ctxt, request), AssertionException);
    }

    // Positive: Empty document sequence
    {
        auto testTempDoc = BSON("DocSequenceCommand"
                                << "coll1"
                                << "field1" << 3 << "field2"
                                << "five"
                                << "objects" << BSON_ARRAY(BSON("foo" << 1)));

        OpMsgRequest request = OpMsgRequest::fromDBAndBody("db", testTempDoc);
        request.sequences.push_back({"structs", {}});

        auto testStruct = DocSequenceCommand::parse(ctxt, request);

        ASSERT_EQUALS(0UL, testStruct.getStructs().size());
    }
}

// Positive: Test all the OpMsg well known fields are ignored
TEST(IDLDocSequence, TestWellKnownFieldsAreIgnored) {
    IDLParserContext ctxt("root");

    auto knownFields = {"$audit",
                        "$client",
                        "$configServerState",
                        "$oplogQueryData",
                        "$queryOptions",
                        "$readPreference",
                        "$replData",
                        "$clusterTime",
                        "maxTimeMS",
                        "readConcern",
                        "shardVersion",
                        "tracking_info",
                        "writeConcern"};

    for (auto knownField : knownFields) {
        auto testTempDoc = BSON("DocSequenceCommand"
                                << "coll1"
                                << "field1" << 3 << "field2"
                                << "five" << knownField << "extra"
                                << "structs"
                                << BSON_ARRAY(BSON("value"
                                                   << "hello")
                                              << BSON("value"
                                                      << "world"))
                                << "objects" << BSON_ARRAY(BSON("foo" << 1)));


        OpMsgRequest request = OpMsgRequest::fromDBAndBody("db", testTempDoc);

        // Validate it can be parsed as a OpMsgRequest.
        {
            auto testStruct = DocSequenceCommand::parse(ctxt, request);
            ASSERT_EQUALS(2UL, testStruct.getStructs().size());
        }

        // Validate it can be parsed as just a BSON document.
        {
            auto testStruct = DocSequenceCommand::parse(ctxt, request.body);
            ASSERT_EQUALS(2UL, testStruct.getStructs().size());
        }
    }
}

// Positive: Test all the OpMsg well known fields are passed through except $db.
TEST(IDLDocSequence, TestWellKnownFieldsPassthrough) {
    IDLParserContext ctxt("root");

    auto knownFields = {"$audit",
                        "$client",
                        "$configServerState",
                        "$oplogQueryData",
                        "$queryOptions",
                        "$readPreference",
                        "$replData",
                        "$clusterTime",
                        "maxTimeMS",
                        "readConcern",
                        "shardVersion",
                        "tracking_info",
                        "writeConcern"};

    for (auto knownField : knownFields) {
        auto testTempDoc = BSON("DocSequenceCommand"
                                << "coll1"
                                << "field1" << 3 << "field2"
                                << "five"
                                << "$db"
                                << "db" << knownField << "extra"
                                << "structs"
                                << BSON_ARRAY(BSON("value"
                                                   << "hello")
                                              << BSON("value"
                                                      << "world"))
                                << "objects" << BSON_ARRAY(BSON("foo" << 1)));

        OpMsgRequest request;
        request.body = testTempDoc;
        auto testStruct = DocSequenceCommand::parse(ctxt, request);
        ASSERT_EQUALS(2UL, testStruct.getStructs().size());

        auto reply = testStruct.serialize(testTempDoc);
        assertOpMsgEquals(request, reply);
    }
}

// Postive: Extra Fields in non-strict parser
TEST(IDLDocSequence, TestNonStrict) {
    IDLParserContext ctxt("root");

    // Positive: Extra field in document sequence
    {
        auto testTempDoc = BSON("DocSequenceCommandNonStrict"
                                << "coll1"
                                << "field1" << 3 << "field2"
                                << "five");

        OpMsgRequest request = OpMsgRequest::fromDBAndBody("db", testTempDoc);
        request.sequences.push_back({"structs",
                                     {BSON("value"
                                           << "hello"),
                                      BSON("value"
                                           << "world")}});
        request.sequences.push_back({"objects", {BSON("foo" << 1)}});
        request.sequences.push_back({"extra", {BSON("foo" << 1)}});

        auto testStruct = DocSequenceCommandNonStrict::parse(ctxt, request);
        ASSERT_EQUALS(2UL, testStruct.getStructs().size());
    }

    // Positive: Extra field in body
    {
        auto testTempDoc = BSON("DocSequenceCommandNonStrict"
                                << "coll1"
                                << "field1" << 3 << "field2"
                                << "five"
                                << "extra" << 1);

        OpMsgRequest request = OpMsgRequest::fromDBAndBody("db", testTempDoc);
        request.sequences.push_back({"structs",
                                     {BSON("value"
                                           << "hello"),
                                      BSON("value"
                                           << "world")}});
        request.sequences.push_back({"objects", {BSON("foo" << 1)}});

        auto testStruct = DocSequenceCommandNonStrict::parse(ctxt, request);
        ASSERT_EQUALS(2UL, testStruct.getStructs().size());
    }
}

// Postive: Test a Command known field does not propagate from passthrough to the final BSON if it
// is included as a field in the command.
TEST(IDLCommand, TestKnownFieldDuplicate) {
    IDLParserContext ctxt("root");

    auto testPassthrough = BSON("$db"
                                << "foo"
                                << "maxTimeMS" << 6 << "$client"
                                << "foo");

    auto testDoc = BSON("KnownFieldCommand"
                        << "coll1"
                        << "$db"
                        << "db"
                        << "field1" << 28 << "maxTimeMS" << 42);

    auto testStruct = KnownFieldCommand::parse(ctxt, makeOMR(testDoc));
    ASSERT_EQUALS(28, testStruct.getField1());
    ASSERT_EQUALS(42, testStruct.getMaxTimeMS());

    // OpMsg request serializes original '$db' out because it is part of the OP_MSG request
    auto expectedOpMsgDoc = BSON("KnownFieldCommand"
                                 << "coll1"

                                 << "field1" << 28 << "maxTimeMS" << 42 << "$db"
                                 << "db"

                                 << "$client"
                                 << "foo");

    ASSERT_BSONOBJ_EQ(expectedOpMsgDoc, testStruct.serialize(testPassthrough).body);

    // BSON serialize does not round-trip '$db' because it can passed in passthrough data
    auto expectedBSONDoc = BSON("KnownFieldCommand"
                                << "coll1"

                                << "field1" << 28 << "maxTimeMS" << 42 << "$db"
                                << "foo"

                                << "$client"
                                << "foo");

    ASSERT_BSONOBJ_EQ(expectedBSONDoc, testStruct.toBSON(testPassthrough));
}


// Positive: Test an inline nested chain struct works
TEST(IDLChainedStruct, TestInline) {
    IDLParserContext ctxt("root");

    auto testDoc = BSON("stringField"
                        << "bar"
                        << "field3"
                        << "foo");

    auto testStruct = Chained_struct_inline::parse(ctxt, testDoc);
    ASSERT_EQUALS(testStruct.getChained_string_inline_basic_type().getStringField(), "bar");
    ASSERT_EQUALS(testStruct.getField3(), "foo");

    assert_same_types<decltype(testStruct.getChained_string_inline_basic_type().getStringField()),
                      StringData>();
    assert_same_types<decltype(testStruct.getField3()), StringData>();

    // Positive: Test we can round trip to a document from the just parsed document
    {
        BSONObj loopbackDoc = testStruct.toBSON();

        ASSERT_BSONOBJ_EQ(testDoc, loopbackDoc);
    }

    // Positive: Test we can serialize from nothing the same document
    {
        BSONObjBuilder builder;
        Chained_struct_inline one_new;
        one_new.setField3("foo");

        Chained_string_inline_basic_type f1;
        f1.setStringField("bar");
        one_new.setChained_string_inline_basic_type(f1);

        BSONObj loopbackDoc = one_new.toBSON();

        ASSERT_BSONOBJ_EQ(testDoc, loopbackDoc);
    }
}

TEST(IDLValidatedField, Int_basic_ranges) {
    // Explicitly call setters.
    Int_basic_ranges obj0;
    obj0.setPositive_int(42);
    ASSERT_THROWS(obj0.setPositive_int(0), AssertionException);
    ASSERT_THROWS(obj0.setPositive_int(-42), AssertionException);

    ASSERT_THROWS(obj0.setNegative_int(42), AssertionException);
    ASSERT_THROWS(obj0.setNegative_int(0), AssertionException);
    obj0.setNegative_int(-42);

    obj0.setNon_negative_int(42);
    obj0.setNon_negative_int(0);
    ASSERT_THROWS(obj0.setNon_negative_int(-42), AssertionException);

    ASSERT_THROWS(obj0.setNon_positive_int(42), AssertionException);
    obj0.setNon_positive_int(0);
    obj0.setNon_positive_int(-42);

    ASSERT_THROWS(obj0.setByte_range_int(-1), AssertionException);
    obj0.setByte_range_int(0);
    obj0.setByte_range_int(127);
    obj0.setByte_range_int(128);
    obj0.setByte_range_int(255);
    ASSERT_THROWS(obj0.setByte_range_int(256), AssertionException);

    // IDL ints *are* int32_t, so no number we can pass to the func will actually fail.
    obj0.setRange_int(std::numeric_limits<std::int32_t>::min() + 1);
    obj0.setRange_int(-65536);
    obj0.setRange_int(0);
    obj0.setRange_int(65536);
    obj0.setRange_int(std::numeric_limits<std::int32_t>::max());

    // Positive case parsing.
    const auto tryPass = [](std::int32_t pos,
                            std::int32_t neg,
                            std::int32_t nonneg,
                            std::int32_t nonpos,
                            std::int32_t byte_range,
                            std::int32_t int_range) {
        IDLParserContext ctxt("root");
        auto doc = BSON("positive_int" << pos << "negative_int" << neg << "non_negative_int"
                                       << nonneg << "non_positive_int" << nonpos << "byte_range_int"
                                       << byte_range << "range_int" << int_range);
        auto obj = Int_basic_ranges::parse(ctxt, doc);
        ASSERT_EQUALS(obj.getPositive_int(), pos);
        ASSERT_EQUALS(obj.getNegative_int(), neg);
        ASSERT_EQUALS(obj.getNon_negative_int(), nonneg);
        ASSERT_EQUALS(obj.getNon_positive_int(), nonpos);
        ASSERT_EQUALS(obj.getByte_range_int(), byte_range);
        ASSERT_EQUALS(obj.getRange_int(), int_range);
    };

    // Negative case parsing.
    const auto tryFail = [](std::int32_t pos,
                            std::int32_t neg,
                            std::int32_t nonneg,
                            std::int32_t nonpos,
                            std::int32_t byte_range,
                            std::int32_t int_range) {
        IDLParserContext ctxt("root");
        auto doc = BSON("positive_int" << pos << "negative_int" << neg << "non_negative_int"
                                       << nonneg << "non_positive_int" << nonpos << "byte_range_int"
                                       << byte_range << "range_int" << int_range);
        ASSERT_THROWS(Int_basic_ranges::parse(ctxt, doc), AssertionException);
    };

    tryPass(1, -1, 0, 0, 128, 65537);
    tryFail(0, -1, 0, 0, 128, 65537);
    tryFail(1, 0, 0, 0, 128, 65537);
    tryFail(1, -1, -1, 0, 128, 65537);
    tryFail(1, -1, 0, 1, 128, 65537);
    tryFail(1, -1, 0, 0, 256, 65537);
    tryFail(0, 0, -1, 1, 257, 0);

    tryPass(1000, -1000, 1, -1, 127, 0x7FFFFFFF);
}

TEST(IDLValidatedField, Double_basic_ranges) {
    // Explicitly call setters.
    Double_basic_ranges obj0;
    obj0.setPositive_double(42.0);
    obj0.setPositive_double(0.000000000001);
    ASSERT_THROWS(obj0.setPositive_double(0.0), AssertionException);
    ASSERT_THROWS(obj0.setPositive_double(-42.0), AssertionException);

    ASSERT_THROWS(obj0.setNegative_double(42.0), AssertionException);
    ASSERT_THROWS(obj0.setNegative_double(0.0), AssertionException);
    obj0.setNegative_double(-0.000000000001);
    obj0.setNegative_double(-42.0);

    obj0.setNon_negative_double(42.0);
    obj0.setNon_negative_double(0.0);
    ASSERT_THROWS(obj0.setNon_negative_double(-42.0), AssertionException);

    ASSERT_THROWS(obj0.setNon_positive_double(42.0), AssertionException);
    obj0.setNon_positive_double(0.0);
    obj0.setNon_positive_double(-42.0);

    ASSERT_THROWS(obj0.setRange_double(-12345678901234600000.0), AssertionException);
    obj0.setRange_double(-12345678901234500000.0);
    obj0.setRange_double(-3000000000.0);
    obj0.setRange_double(0);
    obj0.setRange_double(3000000000);
    obj0.setRange_double(12345678901234500000.0);
    ASSERT_THROWS(obj0.setRange_double(12345678901234600000.0), AssertionException);

    // Positive case parsing.
    const auto tryPass =
        [](double pos, double neg, double nonneg, double nonpos, double double_range) {
            IDLParserContext ctxt("root");
            auto doc = BSON("positive_double"
                            << pos << "negative_double" << neg << "non_negative_double" << nonneg
                            << "non_positive_double" << nonpos << "range_double" << double_range);
            auto obj = Double_basic_ranges::parse(ctxt, doc);
            ASSERT_EQUALS(obj.getPositive_double(), pos);
            ASSERT_EQUALS(obj.getNegative_double(), neg);
            ASSERT_EQUALS(obj.getNon_negative_double(), nonneg);
            ASSERT_EQUALS(obj.getNon_positive_double(), nonpos);
            ASSERT_EQUALS(obj.getRange_double(), double_range);
        };

    // Negative case parsing.
    const auto tryFail =
        [](double pos, double neg, double nonneg, double nonpos, double double_range) {
            IDLParserContext ctxt("root");
            auto doc = BSON("positive_double"
                            << pos << "negative_double" << neg << "non_negative_double" << nonneg
                            << "non_positive_double" << nonpos << "range_double" << double_range);
            ASSERT_THROWS(Double_basic_ranges::parse(ctxt, doc), AssertionException);
        };

    tryPass(1, -1, 0, 0, 123456789012345);
    tryFail(0, -1, 0, 0, 123456789012345);
    tryFail(1, 0, 0, 0, 123456789012345);
    tryFail(1, -1, -1, 0, 123456789012345);
    tryFail(1, -1, 0, 1, 123456789012345);
    tryFail(1, -1, 0, -1, 12345678901234600000.0);
    tryPass(0.00000000001, -0.00000000001, 0.0, 0.0, 1.23456789012345);
}

TEST(IDLValidatedField, Callback_validators) {
    // Explicitly call setters.
    Callback_validators obj0;
    obj0.setInt_even(42);
    ASSERT_THROWS(obj0.setInt_even(7), AssertionException);
    obj0.setInt_even(0);
    ASSERT_THROWS(obj0.setInt_even(-7), AssertionException);
    obj0.setInt_even(-42);

    ASSERT_THROWS(obj0.setDouble_nearly_int(3.141592), AssertionException);
    ASSERT_THROWS(obj0.setDouble_nearly_int(-2.71828), AssertionException);
    obj0.setDouble_nearly_int(0.0);
    obj0.setDouble_nearly_int(1.0);
    obj0.setDouble_nearly_int(1.05);
    obj0.setDouble_nearly_int(-123456789.01234500000);

    ASSERT_THROWS(obj0.setString_starts_with_x("whiskey"), AssertionException);
    obj0.setString_starts_with_x("x-ray");
    ASSERT_THROWS(obj0.setString_starts_with_x("yankee"), AssertionException);

    // Positive case parsing.
    const auto tryPass =
        [](std::int32_t int_even, double double_nearly_int, StringData string_starts_with_x) {
            IDLParserContext ctxt("root");
            auto doc = BSON("int_even" << int_even << "double_nearly_int" << double_nearly_int
                                       << "string_starts_with_x" << string_starts_with_x);
            auto obj = Callback_validators::parse(ctxt, doc);
            ASSERT_EQUALS(obj.getInt_even(), int_even);
            ASSERT_EQUALS(obj.getDouble_nearly_int(), double_nearly_int);
            ASSERT_EQUALS(obj.getString_starts_with_x(), string_starts_with_x);
        };

    // Negative case parsing.
    const auto tryFail =
        [](std::int32_t int_even, double double_nearly_int, StringData string_starts_with_x) {
            IDLParserContext ctxt("root");
            auto doc = BSON("int_even" << int_even << "double_nearly_int" << double_nearly_int
                                       << "string_starts_with_x" << string_starts_with_x);
            ASSERT_THROWS(Callback_validators::parse(ctxt, doc), AssertionException);
        };

    tryPass(42, 123456789.01, "x-ray");
    tryFail(43, 123456789.01, "x-ray");
    tryFail(42, 123456789.11, "x-ray");
    tryFail(42, 123456789.01, "uniform");

    Unusual_callback_validators obj1;
    obj1.setInt_even(42);
    ASSERT_THROWS(obj1.setInt_even(7), AssertionException);
    obj1.setArray_of_int({42});
    ASSERT_THROWS(obj1.setArray_of_int({7}), AssertionException);
    obj1.setOne_int(One_int(42));
    ASSERT_THROWS(obj1.setOne_int(One_int(7)), AssertionException);
}

// Test validation of integer array
TEST(IDLValidatedArray, IntArrayValidation) {

    const auto tryPass = [](std::vector<std::int32_t> int_even) {
        IDLParserContext ctxt("root");
        auto doc = BSON("int_even" << int_even);
        auto obj = Int_array_validators::parse(ctxt, doc);

        ASSERT_EQUALS(obj.getInt_even().size(), int_even.size());
        for (size_t i = 0; i < int_even.size(); ++i) {
            ASSERT_EQ(obj.getInt_even()[i], int_even[i]);
        }
    };

    tryPass({2, 4, 6, 10, 100, 200, 2456});
    tryPass({});
    tryPass({344});

    const auto tryFail = [](std::vector<std::int32_t> int_uneven) {
        IDLParserContext ctxt("root");
        auto doc = BSON("int_even" << int_uneven);
        ASSERT_THROWS(Int_array_validators::parse(ctxt, doc), AssertionException);
    };

    tryFail({1, 3, 5, 7});
    tryFail({9, 35, 4});
    tryFail({90, 22, 33});
    tryFail({122, 44, 101, 64});
}

// Test validation of string array
TEST(IDLValidatedArray, StringArrayValidation) {

    const auto tryPass = [](std::vector<std::string> valid) {
        IDLParserContext ctxt("root");
        auto doc = BSON("caps_strings" << valid);
        auto obj = String_array_validators::parse(ctxt, doc);

        ASSERT_EQUALS(obj.getCaps_strings().size(), valid.size());
        for (size_t i = 0; i < valid.size(); ++i) {
            ASSERT_EQ(obj.getCaps_strings()[i], valid[i]);
        }
    };

    tryPass({"HELLO"});
    tryPass({});
    tryPass({"ABC", "DEF", "XYZ"});

    const auto tryFail = [](std::vector<std::string> invalid) {
        IDLParserContext ctxt("root");
        auto doc = BSON("caps_strings" << invalid);
        ASSERT_THROWS(String_array_validators::parse(ctxt, doc), AssertionException);
    };

    tryFail({"hello"});
    tryFail({"AB1"});
    tryFail({"MONGO", "car", "QWERTY"});
    tryFail({"SLD", "SLA", "KS D"});
    tryFail({"S3LD", "SLA", "ED"});
}

// Positive: verify a command a string arg
TEST(IDLTypeCommand, TestString) {
    IDLParserContext ctxt("root");

    auto testDoc = BSON(CommandTypeStringCommand::kCommandName << "foo"
                                                               << "field1" << 3 << "$db"
                                                               << "db");

    auto testStruct = CommandTypeStringCommand::parse(ctxt, makeOMR(testDoc));
    ASSERT_EQUALS(testStruct.getField1(), 3);
    ASSERT_EQUALS(testStruct.getCommandParameter(), "foo");

    assert_same_types<decltype(testStruct.getCommandParameter()), StringData>();

    // Positive: Test we can roundtrip from the just parsed document
    ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(testStruct));

    // Positive: Test we can serialize from nothing the same document except for $db
    {
        auto testDocWithoutDb = BSON(CommandTypeStringCommand::kCommandName << "foo"
                                                                            << "field1" << 3);

        BSONObjBuilder builder;
        CommandTypeStringCommand one_new("foo");
        one_new.setField1(3);
        one_new.setDbName(DatabaseName(boost::none, "db"));
        one_new.serialize(BSONObj(), &builder);

        auto serializedDoc = builder.obj();
        ASSERT_BSONOBJ_EQ(testDocWithoutDb, serializedDoc);
    }

    // Positive: Test we can serialize from nothing the same document
    {
        CommandTypeStringCommand one_new("foo");
        one_new.setField1(3);
        one_new.setDbName(DatabaseName(boost::none, "db"));
        OpMsgRequest reply = one_new.serialize(BSONObj());
        ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(one_new));
    }
}

// Positive: verify a command can take an array of object
TEST(IDLTypeCommand, TestArrayObject) {
    IDLParserContext ctxt("root");

    auto testDoc = BSON(CommandTypeArrayObjectCommand::kCommandName << BSON_ARRAY(BSON("sample"
                                                                                       << "doc"))
                                                                    << "$db"
                                                                    << "db");

    auto testStruct = CommandTypeArrayObjectCommand::parse(ctxt, makeOMR(testDoc));
    ASSERT_EQUALS(testStruct.getCommandParameter().size(), 1UL);

    assert_same_types<decltype(testStruct.getCommandParameter()),
                      const std::vector<mongo::BSONObj>&>();

    // Positive: Test we can roundtrip from the just parsed document
    ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(testStruct));

    // Positive: Test we can serialize from nothing the same document
    {
        std::vector<BSONObj> vec;
        vec.emplace_back(BSON("sample"
                              << "doc"));
        CommandTypeArrayObjectCommand one_new(vec);
        one_new.setDbName(DatabaseName(boost::none, "db"));
        ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(one_new));
    }
}

// Positive: verify a command can take a struct
TEST(IDLTypeCommand, TestStruct) {
    IDLParserContext ctxt("root");

    auto testDoc = BSON(CommandTypeStructCommand::kCommandName << BSON("value"
                                                                       << "sample")
                                                               << "$db"
                                                               << "db");

    auto testStruct = CommandTypeStructCommand::parse(ctxt, makeOMR(testDoc));
    ASSERT_EQUALS(testStruct.getCommandParameter().getValue(), "sample");

    assert_same_types<decltype(testStruct.getCommandParameter()),
                      mongo::idl::import::One_string&>();

    // Negative: Command with struct parameter should disallow 'undefined' input.
    {
        auto invalidDoc = BSON(CommandTypeStructCommand::kCommandName << BSONUndefined << "$db"
                                                                      << "db");
        ASSERT_THROWS(CommandTypeStructCommand::parse(ctxt, makeOMR(invalidDoc)),
                      AssertionException);
    }

    // Positive: Test we can roundtrip from the just parsed document
    ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(testStruct));

    // Positive: Test we can serialize from nothing the same document
    {
        One_string os;
        os.setValue("sample");
        CommandTypeStructCommand one_new(os);
        one_new.setDbName(DatabaseName(boost::none, "db"));
        ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(one_new));
    }
}

// Positive: verify a command can take an array of structs
TEST(IDLTypeCommand, TestStructArray) {
    IDLParserContext ctxt("root");

    auto testDoc = BSON(CommandTypeArrayStructCommand::kCommandName << BSON_ARRAY(BSON("value"
                                                                                       << "sample"))
                                                                    << "$db"
                                                                    << "db");

    auto testStruct = CommandTypeArrayStructCommand::parse(ctxt, makeOMR(testDoc));
    ASSERT_EQUALS(testStruct.getCommandParameter().size(), 1UL);

    assert_same_types<decltype(testStruct.getCommandParameter()),
                      std::vector<mongo::idl::import::One_string>&>();

    // Positive: Test we can roundtrip from the just parsed document
    ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(testStruct));

    // Positive: Test we can serialize from nothing the same document
    {
        std::vector<One_string> vec;
        One_string os;
        os.setValue("sample");
        vec.push_back(os);
        CommandTypeArrayStructCommand one_new(vec);
        one_new.setDbName(DatabaseName(boost::none, "db"));
        ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(one_new));
    }
}

// Positive: verify a command a string arg and alternate C++ name
TEST(IDLTypeCommand, TestUnderscoreCommand) {
    IDLParserContext ctxt("root");

    auto testDoc = BSON(WellNamedCommand::kCommandName << "foo"
                                                       << "field1" << 3 << "$db"
                                                       << "db");

    auto testStruct = WellNamedCommand::parse(ctxt, makeOMR(testDoc));
    ASSERT_EQUALS(testStruct.getField1(), 3);
    ASSERT_EQUALS(testStruct.getCommandParameter(), "foo");

    assert_same_types<decltype(testStruct.getCommandParameter()), StringData>();

    // Positive: Test we can roundtrip from the just parsed document
    ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(testStruct));

    // Positive: Test we can serialize from nothing the same document except for $db
    {
        auto testDocWithoutDb = BSON(WellNamedCommand::kCommandName << "foo"
                                                                    << "field1" << 3);

        BSONObjBuilder builder;
        WellNamedCommand one_new("foo");
        one_new.setField1(3);
        one_new.setDbName(DatabaseName(boost::none, "db"));
        one_new.serialize(BSONObj(), &builder);

        auto serializedDoc = builder.obj();
        ASSERT_BSONOBJ_EQ(testDocWithoutDb, serializedDoc);
    }

    // Positive: Test we can serialize from nothing the same document
    {
        WellNamedCommand one_new("foo");
        one_new.setField1(3);
        one_new.setDbName(DatabaseName(boost::none, "db"));
        ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(one_new));
    }
}

TEST(IDLTypeCommand, TestErrorReplyStruct) {
    // Correctly parse all required fields.
    {
        IDLParserContext ctxt("root");

        auto errorDoc = BSON("ok" << 0.0 << "code" << 123456 << "codeName"
                                  << "blah blah"
                                  << "errmsg"
                                  << "This is an error Message"
                                  << "errorLabels"
                                  << BSON_ARRAY("label1"
                                                << "label2"));
        auto errorReply = ErrorReply::parse(ctxt, errorDoc);
        ASSERT_BSONOBJ_EQ(errorReply.toBSON(), errorDoc);
    }
    // Non-strictness: ensure we parse even if input has extra fields.
    {
        IDLParserContext ctxt("root");

        auto errorDoc = BSON("a"
                             << "b"
                             << "ok" << 0.0 << "code" << 123456 << "codeName"
                             << "blah blah"
                             << "errmsg"
                             << "This is an error Message");
        auto errorReply = ErrorReply::parse(ctxt, errorDoc);
        ASSERT_BSONOBJ_EQ(errorReply.toBSON(),
                          BSON("ok" << 0.0 << "code" << 123456 << "codeName"
                                    << "blah blah"
                                    << "errmsg"
                                    << "This is an error Message"));
    }
    // Ensure that we fail to parse if any required fields are missing.
    {
        IDLParserContext ctxt("root");

        auto missingOk = BSON("code" << 123456 << "codeName"
                                     << "blah blah"
                                     << "errmsg"
                                     << "This is an error Message");
        auto missingCode = BSON("ok" << 0.0 << "codeName"
                                     << "blah blah"
                                     << "errmsg"
                                     << "This is an error Message");
        auto missingCodeName = BSON("ok" << 0.0 << "code" << 123456 << "errmsg"
                                         << "This is an error Message");
        auto missingErrmsg = BSON("ok" << 0.0 << "code" << 123456 << "codeName"
                                       << "blah blah");
        ASSERT_THROWS(ErrorReply::parse(ctxt, missingOk), AssertionException);
        ASSERT_THROWS(ErrorReply::parse(ctxt, missingCode), AssertionException);
        ASSERT_THROWS(ErrorReply::parse(ctxt, missingCodeName), AssertionException);
        ASSERT_THROWS(ErrorReply::parse(ctxt, missingErrmsg), AssertionException);
    }
}

TEST(IDLTypeCommand, TestCommandWithIDLAnyTypeField) {
    IDLParserContext ctxt("root");
    std::vector<BSONObj> differentTypeObjs = {
        BSON(CommandWithAnyTypeMember::kCommandName << 1 << "anyTypeField"
                                                    << "string literal"
                                                    << "$db"
                                                    << "db"),
        BSON(CommandWithAnyTypeMember::kCommandName << 1 << "anyTypeField" << 1234 << "$db"
                                                    << "db"),
        BSON(CommandWithAnyTypeMember::kCommandName << 1 << "anyTypeField" << 1234.5 << "$db"
                                                    << "db"),
        BSON(CommandWithAnyTypeMember::kCommandName << 1 << "anyTypeField" << OID::max() << "$db"
                                                    << "db"),
        BSON(CommandWithAnyTypeMember::kCommandName << 1 << "anyTypeField" << Date_t::now() << "$db"
                                                    << "db"),
        BSON(CommandWithAnyTypeMember::kCommandName << 1 << "anyTypeField"
                                                    << BSON("a"
                                                            << "b")
                                                    << "$db"
                                                    << "db"),
        BSON(CommandWithAnyTypeMember::kCommandName << 1 << "anyTypeField"
                                                    << BSON_ARRAY("a"
                                                                  << "b")
                                                    << "$db"
                                                    << "db"),
        BSON(CommandWithAnyTypeMember::kCommandName << 1 << "anyTypeField" << jstNULL << "$db"
                                                    << "db")};
    for (auto&& obj : differentTypeObjs) {
        auto parsed = CommandWithAnyTypeMember::parse(ctxt, obj);
        ASSERT_BSONELT_EQ(parsed.getAnyTypeField().getElement(), obj["anyTypeField"]);
    }
}

TEST(IDLCommand, BasicNamespaceConstGetterCommand_TestNonConstGetterGeneration) {
    IDLParserContext ctxt("root");
    const auto uuid = UUID::gen();
    auto testDoc =
        BSON(BasicNamespaceConstGetterCommand::kCommandName << uuid << "field1" << 3 << "$db"
                                                            << "db");

    auto testStruct = BasicNamespaceConstGetterCommand::parse(ctxt, makeOMR(testDoc));
    ASSERT_EQUALS(testStruct.getField1(), 3);
    ASSERT_EQUALS(testStruct.getNamespaceOrUUID().uuid().value(), uuid);

    // Verify that both const and non-const getters are generated.
    assert_same_types<
        decltype(std::declval<BasicNamespaceConstGetterCommand>().getNamespaceOrUUID()),
        NamespaceStringOrUUID&>();
    assert_same_types<
        decltype(std::declval<const BasicNamespaceConstGetterCommand>().getNamespaceOrUUID()),
        const NamespaceStringOrUUID&>();

    // Test we can roundtrip from the just parsed document.
    ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(testStruct));

    // Test mutable getter modifies the command object.
    {
        auto& nssOrUuid = testStruct.getNamespaceOrUUID();
        const auto nss = NamespaceString::createNamespaceString_forTest("test.coll");
        nssOrUuid.setNss(nss);
        nssOrUuid.preferNssForSerialization();

        BSONObjBuilder builder;
        testStruct.serialize(BSONObj(), &builder);

        // Verify that nss was used for serialization over uuid.
        ASSERT_BSONOBJ_EQ(builder.obj(),
                          BSON(BasicNamespaceConstGetterCommand::kCommandName << "coll"
                                                                              << "field1" << 3));
    }
}

TEST(IDLTypeCommand, TestCommandWithIDLAnyTypeOwnedField) {
    IDLParserContext ctxt("root");

    auto parsed = CommandWithAnyTypeOwnedMember::parse(
        ctxt,
        BSON(CommandWithAnyTypeOwnedMember::kCommandName << 1 << "anyTypeField"
                                                         << "string literal"
                                                         << "$db"
                                                         << "db"));
    ASSERT_EQ(parsed.getAnyTypeField().getElement().type(), String);
    ASSERT_EQ(parsed.getAnyTypeField().getElement().str(), "string literal");

    parsed = CommandWithAnyTypeOwnedMember::parse(ctxt,
                                                  BSON(CommandWithAnyTypeOwnedMember::kCommandName
                                                       << 1 << "anyTypeField" << 1234 << "$db"
                                                       << "db"));
    ASSERT_EQ(parsed.getAnyTypeField().getElement().type(), NumberInt);
    ASSERT_EQ(parsed.getAnyTypeField().getElement().numberInt(), 1234);

    parsed = CommandWithAnyTypeOwnedMember::parse(ctxt,
                                                  BSON(CommandWithAnyTypeOwnedMember::kCommandName
                                                       << 1 << "anyTypeField" << 1234.5 << "$db"
                                                       << "db"));
    ASSERT_EQ(parsed.getAnyTypeField().getElement().type(), NumberDouble);
    ASSERT_EQ(parsed.getAnyTypeField().getElement().numberDouble(), 1234.5);

    parsed = CommandWithAnyTypeOwnedMember::parse(ctxt,
                                                  BSON(CommandWithAnyTypeOwnedMember::kCommandName
                                                       << 1 << "anyTypeField" << OID::max() << "$db"
                                                       << "db"));
    ASSERT_EQ(parsed.getAnyTypeField().getElement().type(), jstOID);
    ASSERT_EQ(parsed.getAnyTypeField().getElement().OID(), OID::max());

    parsed = CommandWithAnyTypeOwnedMember::parse(ctxt,
                                                  BSON(CommandWithAnyTypeOwnedMember::kCommandName
                                                       << 1 << "anyTypeField"
                                                       << BSON("a"
                                                               << "b")
                                                       << "$db"
                                                       << "db"));
    ASSERT_EQ(parsed.getAnyTypeField().getElement().type(), Object);
    ASSERT_BSONOBJ_EQ(parsed.getAnyTypeField().getElement().Obj(),
                      BSON("a"
                           << "b"));

    parsed = CommandWithAnyTypeOwnedMember::parse(ctxt,
                                                  BSON(CommandWithAnyTypeOwnedMember::kCommandName
                                                       << 1 << "anyTypeField"
                                                       << BSON_ARRAY("a"
                                                                     << "b")
                                                       << "$db"
                                                       << "db"));
    ASSERT_EQ(parsed.getAnyTypeField().getElement().type(), Array);
    ASSERT_BSONELT_EQ(parsed.getAnyTypeField().getElement(),
                      BSON("anyTypeField" << BSON_ARRAY("a"
                                                        << "b"))["anyTypeField"]);
}

TEST(IDLTypeCommand, ReplyTypeKnowsItIsReplyAtCompileTime) {
    Reply_type_struct reply;
    static_assert(reply.getIsCommandReply());
    StructWithEnum nonReply;
    static_assert(!nonReply.getIsCommandReply());
}

TEST(IDLTypeCommand, ReplyTypeCanParseWithGenericFields) {
    // $clusterTime is not a field of Rely_type_struct, but is
    // a field that could be part of any reply.
    StringData genericField = "$clusterTime"_sd;
    // This field is not part of Reply_type_struct and is also
    // not a generic field.
    StringData nonGenericField = "xyz123"_sd;
    IDLParserContext ctxt("root");
    // This contains only fields part of Reply_type_struct and generic fields
    auto bsonValidReply = BSON("reply_field" << 42 << genericField << 1);
    auto parsed = CommandWithReplyType::Reply::parse(ctxt, bsonValidReply);
    ASSERT(parsed.getIsCommandReply());
    ASSERT_EQ(parsed.getReply_field(), 42);

    // This contains a field not part of Reply_type struct, so shouldn't parse
    auto bsonInvalidReply = BSON("reply_field" << 42 << nonGenericField << 1);
    ASSERT_THROWS(CommandWithReplyType::Reply::parse(ctxt, bsonInvalidReply), DBException);
}

TEST(IDLCommand,
     TestCommandTypeNamespaceCommand_WithMultitenancySupportOnFeatureFlagRequireTenantIDOn) {
    RAIIServerParameterControllerForTest multitenanyController("multitenancySupport", true);
    RAIIServerParameterControllerForTest featureFlagController("featureFlagRequireTenantID", true);

    IDLParserContext ctxt("root");

    auto testDoc = BSON(CommandTypeNamespaceCommand::kCommandName << "db.coll1"
                                                                  << "field1" << 3 << "$db"
                                                                  << "admin");

    const auto tenantId = TenantId(OID::gen());
    auto testStruct =
        CommandTypeNamespaceCommand::parse(ctxt, makeOMRWithTenant(testDoc, tenantId));
    ASSERT_EQUALS(testStruct.getDbName(), DatabaseName(tenantId, "admin"));
    ASSERT_EQUALS(testStruct.getCommandParameter(),
                  NamespaceString::createNamespaceString_forTest(tenantId, "db.coll1"));
    assert_same_types<decltype(testStruct.getCommandParameter()), const NamespaceString&>();
    // Positive: Test we can roundtrip from the just parsed document
    ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(testStruct));
}

TEST(IDLCommand, TestCommandTypeNamespaceCommand_WithMultitenancySupportOn) {
    RAIIServerParameterControllerForTest multitenanyController("multitenancySupport", true);
    RAIIServerParameterControllerForTest featureFlagController("featureFlagRequireTenantID", false);

    IDLParserContext ctxt("root");

    const auto tenantId = TenantId(OID::gen());
    const auto nssWithPrefixedTenantId =
        std::string(str::stream() << tenantId.toString() << "_db.coll1");
    const auto prefixedAdminDb = std::string(str::stream() << tenantId.toString() << "_admin");

    auto testDoc = BSON(CommandTypeNamespaceCommand::kCommandName
                        << nssWithPrefixedTenantId << "field1" << 3 << "$db" << prefixedAdminDb);

    auto testStruct = CommandTypeNamespaceCommand::parse(ctxt, makeOMR(testDoc));

    ASSERT_EQUALS(testStruct.getDbName(), DatabaseName(tenantId, "admin"));
    // Deserialize called from parse correctly sets the tenantId field.
    ASSERT_EQUALS(testStruct.getCommandParameter(),
                  NamespaceString::createNamespaceString_forTest(tenantId, "db.coll1"));
    assert_same_types<decltype(testStruct.getCommandParameter()), const NamespaceString&>();
    // Positive: Test we can roundtrip from the just parsed document
    ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(testStruct));
}

TEST(IDLTypeCommand, TestCommandWithNamespaceMember_WithTenant) {
    RAIIServerParameterControllerForTest multitenanyController("multitenancySupport", true);
    RAIIServerParameterControllerForTest featureFlagController("featureFlagRequireTenantID", true);
    IDLParserContext ctxt("root");
    const char* ns1 = "db.coll1";
    const char* ns2 = "a.b";
    const char* ns3 = "c.d";

    auto testDoc = BSONObjBuilder{}
                       .append("CommandWithNamespaceMember", 1)
                       .append("field1", ns1)
                       .append("field2", BSON_ARRAY(ns2 << ns3))
                       .append("$db", "admin")
                       .obj();

    const auto tenantId = TenantId(OID::gen());
    auto testStruct = CommandWithNamespaceMember::parse(ctxt, makeOMRWithTenant(testDoc, tenantId));

    assert_same_types<decltype(testStruct.getField1()), const NamespaceString&>();
    assert_same_types<decltype(testStruct.getField2()),
                      const std::vector<mongo::NamespaceString>&>();

    ASSERT_EQUALS(testStruct.getField1(),
                  NamespaceString::createNamespaceString_forTest(tenantId, ns1));
    std::vector<NamespaceString> field2{
        NamespaceString::createNamespaceString_forTest(tenantId, ns2),
        NamespaceString::createNamespaceString_forTest(tenantId, ns3)};
    ASSERT_TRUE(field2 == testStruct.getField2());

    // Positive: Test we can roundtrip from the just parsed document
    ASSERT_BSONOBJ_EQ(testDoc, serializeCmd(testStruct));
}

TEST(IDLTypeCommand, TestCommandWithNamespaceStruct_WithTenant) {
    RAIIServerParameterControllerForTest multitenanyController("multitenancySupport", true);
    RAIIServerParameterControllerForTest featureFlagController("featureFlagRequireTenantID", true);
    IDLParserContext ctxt("root");
    const char* ns1 = "db.coll1";
    const char* ns2 = "a.b";
    const char* ns3 = "c.d";

    auto nsInfoStructBSON = [&](const char* ns) {
        BSONObjBuilder builder;
        builder.append("ns", ns);
        return builder.obj();
    };
    auto testDoc = BSONObjBuilder{}
                       .append("CommandWithNamespaceStruct", 1)
                       .append("field1", nsInfoStructBSON(ns1))
                       .append("$db", "admin")
                       .append("field2", BSON_ARRAY(nsInfoStructBSON(ns2) << nsInfoStructBSON(ns3)))
                       .obj();

    const auto tenantId = TenantId(OID::gen());
    auto testStruct = CommandWithNamespaceStruct::parse(ctxt, makeOMRWithTenant(testDoc, tenantId));

    assert_same_types<decltype(testStruct.getField1()), NamespaceInfoStruct&>();
    assert_same_types<decltype(testStruct.getField2()), std::vector<NamespaceInfoStruct>&>();

    ASSERT_EQUALS(testStruct.getField1().getNs(),
                  NamespaceString::createNamespaceString_forTest(tenantId, ns1));
    std::vector<NamespaceString> field2Nss{
        NamespaceString::createNamespaceString_forTest(tenantId, ns2),
        NamespaceString::createNamespaceString_forTest(tenantId, ns3)};
    std::vector<NamespaceInfoStruct>& field2 = testStruct.getField2();
    ASSERT_TRUE(field2Nss[0] == field2[0].getNs());
    ASSERT_TRUE(field2Nss[1] == field2[1].getNs());

    // Positive: Test we can round trip to a document sequence from the just parsed document
    {
        OpMsgRequest loopbackRequest = testStruct.serialize(BSONObj());
        OpMsgRequest request = makeOMR(testDoc);

        assertOpMsgEquals(request, loopbackRequest);
        ASSERT_EQUALS(loopbackRequest.sequences.size(), 1UL);
        ASSERT_EQUALS(loopbackRequest.sequences[0].objs.size(), 2UL);
    }
}

TEST(IDLParserContext, TestConstructorWithPredecessorAndDifferentTenant) {
    // Negative: Test the child IDLParserContext cannot has different tenant id from its
    // predecessor.
    RAIIServerParameterControllerForTest multitenanyController("multitenancySupport", true);

    const auto tenantId = TenantId(OID::gen());
    const auto otherTenantId = TenantId(OID::gen());
    IDLParserContext ctxt("root", false, tenantId);

    auto nsInfoStructBSON = [&](const char* ns) {
        BSONObjBuilder builder;
        builder.append("ns", ns);
        return builder.obj();
    };
    auto testDoc =
        BSONObjBuilder{}
            .append("CommandWithNamespaceStruct", 1)
            .append("field1", nsInfoStructBSON("db.coll1"))
            .append("$db", "admin")
            .append("field2", BSON_ARRAY(nsInfoStructBSON("a.b") << nsInfoStructBSON("c.d")))
            .obj();
    ASSERT_THROWS_CODE(
        CommandWithNamespaceStruct::parse(ctxt, makeOMRWithTenant(testDoc, otherTenantId)),
        DBException,
        8423379);
}

void verifyContract(const AuthorizationContract& left, const AuthorizationContract& right) {
    ASSERT_TRUE(left.contains(right));
    ASSERT_TRUE(right.contains(left));
}

TEST(IDLAccessCheck, TestNone) {
    AuthorizationContract empty;

    verifyContract(empty, AccessCheckNone::kAuthorizationContract);
}

TEST(IDLAccessCheck, TestSimpleAccessCheck) {
    AuthorizationContract ac;
    ac.addAccessCheck(AccessCheckEnum::kIsAuthenticated);

    verifyContract(ac, AccessCheckSimpleAccessCheck::kAuthorizationContract);
}

TEST(IDLAccessCheck, TestSimplePrivilegeAccessCheck) {
    AuthorizationContract ac;
    ac.addPrivilege(Privilege(ResourcePattern::forClusterResource(), ActionType::addShard));
    ac.addPrivilege(Privilege(ResourcePattern::forClusterResource(), ActionType::serverStatus));

    verifyContract(ac, AccessCheckSimplePrivilege::kAuthorizationContract);
}

TEST(IDLAccessCheck, TestComplexAccessCheck) {
    AuthorizationContract ac;
    ac.addPrivilege(Privilege(ResourcePattern::forClusterResource(), ActionType::addShard));
    ac.addPrivilege(Privilege(ResourcePattern::forClusterResource(), ActionType::serverStatus));

    ac.addPrivilege(Privilege(ResourcePattern::forDatabaseName("test"), ActionType::trafficRecord));

    ac.addPrivilege(Privilege(ResourcePattern::forAnyResource(), ActionType::splitVector));

    ac.addAccessCheck(AccessCheckEnum::kIsAuthenticated);
    ac.addAccessCheck(AccessCheckEnum::kIsAuthorizedToParseNamespaceElement);

    verifyContract(ac, AccessCheckComplexPrivilege::kAuthorizationContract);
}

TEST(IDLFieldTests, TestOptionalBoolField) {
    IDLParserContext ctxt("root");

    {
        auto testDoc = BSON("optBoolField" << true);
        auto parsed = OptionalBool::parseFromBSON(testDoc.firstElement());
        ASSERT_TRUE(parsed.has_value());
        ASSERT_TRUE(parsed);
        BSONObjBuilder serialized;
        parsed.serializeToBSON("optBoolField", &serialized);
        ASSERT_BSONOBJ_EQ(serialized.obj(), testDoc);
    }

    {
        auto testDoc = BSON("optBoolField" << false);
        auto parsed = OptionalBool::parseFromBSON(testDoc.firstElement());
        ASSERT_TRUE(parsed.has_value());
        ASSERT_FALSE(parsed);
        BSONObjBuilder serialized;
        parsed.serializeToBSON("optBoolField", &serialized);
        ASSERT_BSONOBJ_EQ(serialized.obj(), testDoc);
    }

    {
        auto testDoc = BSONObj();
        auto parsed = OptionalBool::parseFromBSON(testDoc.firstElement());
        ASSERT_FALSE(parsed.has_value());
        ASSERT_FALSE(parsed);
        BSONObjBuilder serialized;
        parsed.serializeToBSON("", &serialized);
        ASSERT_BSONOBJ_EQ(serialized.obj(), testDoc);
    }

    {
        auto testDoc = BSON("optBoolField" << jstNULL);
        ASSERT_THROWS(OptionalBool::parseFromBSON(testDoc.firstElement()), AssertionException);
    }

    {
        auto testDoc = BSON("optBoolField" << BSONUndefined);
        ASSERT_THROWS(OptionalBool::parseFromBSON(testDoc.firstElement()), AssertionException);
    }

    {
        auto testDoc = BSON("optBoolField"
                            << "abc");
        ASSERT_THROWS(OptionalBool::parseFromBSON(testDoc.firstElement()), AssertionException);
    }
}

TEST(IDLFieldTests, TenantOverrideField) {
    const auto mkdoc = [](boost::optional<TenantId> tenantId) {
        BSONObjBuilder doc;
        doc.append("BasicIgnoredCommand", 1);
        doc.append("$db", "admin");
        if (tenantId) {
            tenantId->serializeToBSON("$tenant", &doc);
        }
        doc.append("field1", 42);
        doc.append("field2", "foo");
        return doc.obj();
    };

    // Test optionality of $tenant arg.
    {
        auto obj = BasicIgnoredCommand::parse(IDLParserContext{"nil"}, mkdoc(boost::none));
        auto tenant = obj.getDollarTenant();
        ASSERT(tenant == boost::none);
    }

    // Test passing an tenant id (acting on behalf of a specific tenant)
    {
        auto id = TenantId(OID::gen());
        auto obj = BasicIgnoredCommand::parse(IDLParserContext{"oid"}, mkdoc(id));
        auto tenant = obj.getDollarTenant();
        ASSERT(tenant == id);
    }
}

TEST(IDLFieldTests, TenantOverrideFieldWithInvalidValue) {
    const auto mkdoc = [](auto tenantId) {
        BSONObjBuilder doc;
        doc.append("BasicIgnoredCommand", 1);
        doc.append("$db", "admin");
        doc.append("$tenant", tenantId);
        doc.append("field1", 42);
        doc.append("field2", "foo");
        return doc.obj();
    };

    // Negative: Parse invalid types.
    {
        ASSERT_THROWS(BasicIgnoredCommand::parse(IDLParserContext{"int"}, mkdoc(123)), DBException);
        ASSERT_THROWS(BasicIgnoredCommand::parse(IDLParserContext{"float"}, mkdoc(3.14)),
                      DBException);
        ASSERT_THROWS(BasicIgnoredCommand::parse(IDLParserContext{"string"}, mkdoc("bar")),
                      DBException);
        ASSERT_THROWS(BasicIgnoredCommand::parse(IDLParserContext{"object"}, mkdoc(BSONObj())),
                      DBException);
    }
}

TEST(IDLOwnershipTests, ParseOwnAssumesOwnership) {
    IDLParserContext ctxt("root");
    One_plain_object idlStruct;
    {
        auto tmp = BSON("value" << BSON("x" << 42));
        idlStruct = One_plain_object::parseOwned(ctxt, std::move(tmp));
    }
    // Now that tmp is out of scope, if idlStruct didn't retain ownership, it would be accessing
    // free'd memory which should error on ASAN and debug builds.
    auto obj = idlStruct.getValue();
    ASSERT_BSONOBJ_EQ(obj, BSON("x" << 42));
}

TEST(IDLOwnershipTests, ParseSharingOwnershipTmpBSON) {
    IDLParserContext ctxt("root");
    One_plain_object idlStruct;
    {
        auto tmp = BSON("value" << BSON("x" << 42));
        idlStruct = One_plain_object::parseSharingOwnership(ctxt, tmp);
    }
    // Now that tmp is out of scope, if idlStruct didn't particpate in ownership, it would be
    // accessing free'd memory which should error on ASAN and debug builds.
    auto obj = idlStruct.getValue();
    ASSERT_BSONOBJ_EQ(obj, BSON("x" << 42));
}

TEST(IDLOwnershipTests, ParseSharingOwnershipTmpIDLStruct) {
    IDLParserContext ctxt("root");
    auto bson = BSON("value" << BSON("x" << 42));
    { auto idlStruct = One_plain_object::parseSharingOwnership(ctxt, bson); }
    // Now that idlStruct is out of scope, if bson didn't particpate in ownership, it would be
    // accessing free'd memory which should error on ASAN and debug builds.
    ASSERT_BSONOBJ_EQ(bson["value"].Obj(), BSON("x" << 42));
}
}  // namespace
}  // namespace mongo