File: TestURLSession.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (2872 lines) | stat: -rw-r--r-- 136,838 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//

#if NS_FOUNDATION_ALLOWS_TESTABLE_IMPORT
    #if canImport(SwiftFoundationNetworking) && !DEPLOYMENT_RUNTIME_OBJC
        @testable import SwiftFoundationNetworking
    #else
        @testable import FoundationNetworking
    #endif
#endif

@MainActor
final class TestURLSession: LoopbackServerTest, @unchecked Sendable {

    let httpMethods = ["HEAD", "GET", "PUT", "POST", "DELETE"]

    func test_dataTaskWithURL() async {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Nepal"
        let url = URL(string: urlString)!
        let d = DataTask(with: expectation(description: "GET \(urlString): with a delegate"))
        d.run(with: url)
        waitForExpectations(timeout: 12)
        if !d.error {
            XCTAssertEqual(d.capital, "Kathmandu", "test_dataTaskWithURLRequest returned an unexpected result")
        }
    }

    func test_dataTaskWithURLCompletionHandler() async {
        //shared session
        await dataTaskWithURLCompletionHandler(with: URLSession.shared)

        //new session
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 8
        let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
        await dataTaskWithURLCompletionHandler(with: session)
    }

    func dataTaskWithURLCompletionHandler(with session: URLSession) async {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/USA"
        let url = URL(string: urlString)!
        let expect = expectation(description: "GET \(urlString): with a completion handler")
        let task = session.dataTask(with: url) { data, response, error in
            defer { expect.fulfill() }
            XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
            XCTAssertNotNil(response)
            XCTAssertNotNil(data)
            guard let httpResponse = response as? HTTPURLResponse, let data = data else { return }
            XCTAssertEqual(200, httpResponse.statusCode, "HTTP response code is not 200")
            let result = String(data: data, encoding: .utf8) ?? ""
            XCTAssertEqual("Washington, D.C.", result, "Did not receive expected value")
        }
        task.resume()
        waitForExpectations(timeout: 12)
    }
    
    func test_dataTaskWithURLRequest() async {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Peru"
        let urlRequest = URLRequest(url: URL(string: urlString)!)
        let d = DataTask(with: expectation(description: "GET \(urlString): with a delegate"))
        d.run(with: urlRequest)
        waitForExpectations(timeout: 12)
        if !d.error {
            XCTAssertEqual(d.capital, "Lima", "test_dataTaskWithURLRequest returned an unexpected result")
        }
    }
    
    func test_dataTaskWithURLRequestCompletionHandler() async {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Italy"
        let urlRequest = URLRequest(url: URL(string: urlString)!)
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 8
        let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
        let expect = expectation(description: "GET \(urlString): with a completion handler")
        let task = session.dataTask(with: urlRequest) { data, response, error in
            defer { expect.fulfill() }
            XCTAssertNotNil(data)
            XCTAssertNotNil(response)
            XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
            guard let httpResponse = response as? HTTPURLResponse, let data = data else { return }
            XCTAssertEqual(200, httpResponse.statusCode, "HTTP response code is not 200")
            let result = String(data: data, encoding: .utf8) ?? ""
            XCTAssertEqual("Rome", result, "Did not receive expected value")
        }
        task.resume()
        waitForExpectations(timeout: 12)
    }

    func test_asyncDataFromURL() async throws {
        guard #available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) else { return }
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/UK"
        let (data, response) = try await URLSession.shared.data(from: URL(string: urlString)!, delegate: nil)
        guard let httpResponse = response as? HTTPURLResponse else {
            XCTFail("Did not get response")
            return
        }
        XCTAssertEqual(200, httpResponse.statusCode, "HTTP response code is not 200")
        let result = String(data: data, encoding: .utf8) ?? ""
        XCTAssertEqual("London", result, "Did not receive expected value")
    }

    func test_asyncDataFromURLWithDelegate() async throws {
        guard #available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) else { return }
        // Sendable note: Access to ivars is essentially serialized by the XCTestExpectation. It would be better to do it with a lock, but this is sufficient for now.
        final class CapitalDataTaskDelegate: NSObject, URLSessionDataDelegate, @unchecked Sendable {
            var capital: String = "unknown"
            let expectation: XCTestExpectation
            init(expectation: XCTestExpectation) {
                self.expectation = expectation
            }
            
            public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
                defer { expectation.fulfill() }
                capital = String(data: data, encoding: .utf8)!
            }
        }
        let expect = expectation(description: "test_asyncDataFromURLWithDelegate")
        let delegate = CapitalDataTaskDelegate(expectation: expect)

        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/UK"
        let (data, response) = try await URLSession.shared.data(from: URL(string: urlString)!, delegate: delegate)
        guard let httpResponse = response as? HTTPURLResponse else {
            XCTFail("Did not get response")
            return
        }
        waitForExpectations(timeout: 12)
        XCTAssertEqual(200, httpResponse.statusCode, "HTTP response code is not 200")
        let result = String(data: data, encoding: .utf8) ?? ""
        XCTAssertEqual("London", result, "Did not receive expected value")
        XCTAssertEqual("London", delegate.capital)
    }

    func test_dataTaskWithHttpInputStream() async throws {
        throw XCTSkip("This test is disabled (Flaky test)")
        #if false
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/jsonBody"
        let url = try XCTUnwrap(URL(string: urlString))

        let dataString = """
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras congue laoreet facilisis. Sed porta tristique orci. Fusce ut nisl dignissim, tempor tortor id, molestie neque. Nam non tincidunt mi. Integer ac diam quis leo aliquam congue et non magna. In porta mauris suscipit erat pulvinar, sed fringilla quam ornare. Nulla vulputate et ligula vitae sollicitudin. Nulla vel vehicula risus. Quisque eu urna ullamcorper, tincidunt ante vitae, aliquet sem. Suspendisse nec turpis placerat, porttitor ex vel, tristique orci. Maecenas pretium, augue non elementum imperdiet, diam ex vestibulum tortor, non ultrices ante enim iaculis ex.

            Suspendisse ante eros, scelerisque ut molestie vitae, lacinia nec metus. Sed in feugiat sem. Nullam sed congue nulla, id vehicula mauris. Aliquam ultrices ultricies pellentesque. Etiam blandit ultrices quam in egestas. Donec a vulputate est, ut ultricies dui. In non maximus velit.

            Vivamus vehicula faucibus odio vel maximus. Vivamus elementum, quam at accumsan rhoncus, ex ligula maximus sem, sed pretium urna enim ut urna. Donec semper porta augue at faucibus. Quisque vel congue purus. Morbi vitae elit pellentesque, finibus lectus quis, laoreet nulla. Praesent in fermentum felis. Aenean vestibulum dictum lorem quis egestas. Sed dictum elementum est laoreet volutpat.
        """
        let data = try XCTUnwrap(dataString.data(using: .utf8))

        // For all HTTP methods, send data as an input stream with both a Content-Type header and without to check that the
        // header is added correctly for only POST messages with a body.
        // GET will also fail to send a body.
        for method in httpMethods {
            for contentType in ["text/plain; charset=utf-8", nil] {   // nil Content-Type lets URLSession set it
                var urlRequest = URLRequest(url: url)
                urlRequest.httpMethod = method
                urlRequest.httpBodyStream = InputStream(data: data)
                urlRequest.setValue("en-us", forHTTPHeaderField: "Accept-Language")
                urlRequest.setValue("chunked", forHTTPHeaderField: "Transfer-Encoding")
                if let ct = contentType  {
                    urlRequest.setValue(ct, forHTTPHeaderField: "Content-Type")
                }

                let delegate = SessionDelegate(with: expectation(description: "\(method) \(urlString): with HTTP Body as InputStream"))
                delegate.run(with: urlRequest, timeoutInterval: 3)
                await waitForExpectations(timeout: 4)

                let httpResponse = delegate.response as? HTTPURLResponse
                let contentLength = Int(httpResponse?.value(forHTTPHeaderField: "Content-Length") ?? "")
                // Only POST sets a default Content-Type if it is nil
                let postedContentType = contentType ?? ((method == "POST") ? "application/x-www-form-urlencoded" : nil)

                let callBacks: [String]
                switch method {
                    case "HEAD":
                        XCTAssertNil(delegate.error)
                        XCTAssertNotNil(delegate.response)
                        XCTAssertEqual(httpResponse?.statusCode, 200)
                        XCTAssertNil(delegate.receivedData)
                        callBacks = ["urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)",
                                     "urlSession(_:dataTask:didReceive:completionHandler:)",
                                     "urlSession(_:task:didCompleteWithError:)"]

                    case "GET":
                        // GET requests must not have a body, which causes an error
                        XCTAssertNotNil(delegate.error)
                        let error = delegate.error as? URLError
                        XCTAssertEqual(error?.code.rawValue, NSURLErrorDataLengthExceedsMaximum)
                        XCTAssertEqual(error?.localizedDescription, "resource exceeds maximum size")
                        let userInfo = error?.userInfo
                        XCTAssertNotNil(userInfo)
                        let errorURL = userInfo?[NSURLErrorFailingURLErrorKey] as? URL
                        XCTAssertEqual(errorURL, url)

                        XCTAssertNil(delegate.response)
                        XCTAssertNil(delegate.receivedData)
                        callBacks = ["urlSession(_:task:didCompleteWithError:)"]

                    default:
                        XCTAssertNil(delegate.error)
                        XCTAssertNotNil(delegate.response)
                        XCTAssertEqual(httpResponse?.statusCode, 200)

                        XCTAssertNotNil(delegate.receivedData)
                        XCTAssertEqual(delegate.receivedData?.count, contentLength)
                        if let receivedData = delegate.receivedData, let jsonBody = try? JSONSerialization.jsonObject(with: receivedData, options: []) as? [String: String] {
                            XCTAssertEqual(jsonBody["Content-Type"], postedContentType)
                            if let postedBody = jsonBody["x-base64-body"], let decodedBody = Data(base64Encoded: postedBody) {
                                XCTAssertEqual(decodedBody, data)
                            } else {
                                XCTFail("Could not decode Base64 body for \(method)")
                            }
                        } else {
                            XCTFail("No JSON body for \(method)")
                        }
                        callBacks = ["urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)",
                                     "urlSession(_:dataTask:didReceive:completionHandler:)",
                                     "urlSession(_:dataTask:didReceive:)",
                                     "urlSession(_:task:didCompleteWithError:)"]
                }
                XCTAssertEqual(delegate.callbacks.count, callBacks.count)
                XCTAssertEqual(delegate.callbacks, callBacks)
            }
        }
        #endif
    }
    
    func test_dataTaskWithHTTPBodyRedirect() async {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/303?location=Peru"
        let url = URL(string: urlString)!
        let parameters = "foo=bar"
        var postRequest = URLRequest(url: url)
        postRequest.httpBody = parameters.data(using: .utf8)
        postRequest.httpMethod = "POST"
        
        let d = HTTPRedirectionDataTask(with: expectation(description: "POST \(urlString): with HTTP redirection"))
        d.run(with: postRequest)

        waitForExpectations(timeout: 12)
        
        XCTAssertEqual("Lima", String(data: d.receivedData, encoding: .utf8), "\(#function) did not redirect properly.")
    }

    func test_gzippedDataTask() async {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/gzipped-response"
        let url = URL(string: urlString)!
        let d = DataTask(with: expectation(description: "GET \(urlString): gzipped response"))
        d.run(with: url)
        waitForExpectations(timeout: 12)
        if !d.error {
            XCTAssertEqual(d.capital, "Hello World!")
        }
    }

    func test_downloadTaskWithURL() async {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt"
        let url = URL(string: urlString)!
        let d = DownloadTask(testCase: self, description: "Download GET \(urlString): with a delegate")
        d.run(with: url)
        waitForExpectations(timeout: 12)
    }
    
    func test_downloadTaskWithURLRequest() async {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt"
        let urlRequest = URLRequest(url: URL(string: urlString)!)
        let d = DownloadTask(testCase: self, description: "Download GET \(urlString): with a delegate")
        d.run(with: urlRequest)
        waitForExpectations(timeout: 12)
    }
    
    func test_downloadTaskWithRequestAndHandler() async {
        //shared session
        await downloadTaskWithRequestAndHandler(with: URLSession.shared)

        //newly created session
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 8
        let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
        await downloadTaskWithRequestAndHandler(with: session)
    }

    func downloadTaskWithRequestAndHandler(with session: URLSession) async {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt"
        let expect = expectation(description: "Download GET \(urlString): with a completion handler")
        let req = URLRequest(url: URL(string: urlString)!)
        let task = session.downloadTask(with: req) { (_, _, error) -> Void in
            XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
            expect.fulfill()
        }
        task.resume()
        waitForExpectations(timeout: 12)
    }
    
    func test_downloadTaskWithURLAndHandler() async {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 8
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt"
        let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
        let expect = expectation(description: "Download GET \(urlString): with a completion handler")
        let req = URLRequest(url: URL(string: urlString)!)
        let task = session.downloadTask(with: req) { (_, _, error) -> Void in
            if let e = error as? URLError {
                XCTAssertEqual(e.code, .timedOut, "Unexpected error code")
            }
            expect.fulfill()
        }
        task.resume()
        waitForExpectations(timeout: 12)
    }

    func test_asyncDownloadFromURL() async throws {
        guard #available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) else { return }
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt"
        let (location, response) = try await URLSession.shared.download(from: URL(string: urlString)!)
        guard let httpResponse = response as? HTTPURLResponse else {
            XCTFail("Did not get response")
            return
        }
        XCTAssertEqual(200, httpResponse.statusCode, "HTTP response code is not 200")
        XCTAssertNotNil(location, "Download location was nil")
    }

    func test_asyncDownloadFromURLWithDelegate() async throws {
        guard #available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) else { return }
        // Sendable note: Access to ivars is essentially serialized by the XCTestExpectation. It would be better to do it with a lock, but this is sufficient for now.
        class AsyncDownloadDelegate : NSObject, URLSessionDownloadDelegate, @unchecked Sendable {
            init(expectation: XCTestExpectation) {
                self.expectation = expectation
            }
            let expectation: XCTestExpectation
            func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
                XCTFail("Should not be called for async downloads")
            }

            var totalBytesWritten = Int64(0)
            public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64,
                                   totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) -> Void {
                self.totalBytesWritten = totalBytesWritten
                expectation.fulfill()
            }
        }
        let expect = expectation(description: "test_asyncDownloadFromURLWithDelegate")

        let delegate = AsyncDownloadDelegate(expectation: expect)

        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt"
        let (location, response) = try await URLSession.shared.download(from: URL(string: urlString)!, delegate: delegate)
        guard let httpResponse = response as? HTTPURLResponse else {
            XCTFail("Did not get response")
            return
        }
        waitForExpectations(timeout: 12)
        XCTAssertEqual(200, httpResponse.statusCode, "HTTP response code is not 200")
        XCTAssertNotNil(location, "Download location was nil")
        XCTAssertTrue(delegate.totalBytesWritten > 0)
    }

    func test_gzippedDownloadTask() async {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/gzipped-response"
        let url = URL(string: urlString)!
        let d = DownloadTask(testCase: self, description: "GET \(urlString): gzipped response")
        d.run(with: url)
        waitForExpectations(timeout: 12)
        if d.totalBytesWritten != "Hello World!".utf8.count {
            XCTFail("Expected the gzipped-response to be the length of Hello World!")
        }
    }

    func test_finishTasksAndInvalidate() async {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Nepal"
        let invalidateExpectation = expectation(description: "Session invalidation")
        let delegate = SessionDelegate(invalidateExpectation: invalidateExpectation)
        let url = URL(string: urlString)!
        let session = URLSession(configuration: URLSessionConfiguration.default,
                                 delegate: delegate, delegateQueue: nil)
        let completionExpectation = expectation(description: "GET \(urlString): task completion before session invalidation")
        let task = session.dataTask(with: url) { (_, _, _) in
            completionExpectation.fulfill()
        }
        task.resume()
        session.finishTasksAndInvalidate()
        waitForExpectations(timeout: 12)
    }
    
    func test_taskError() async {
        let urlString = "http://127.0.0.0:999999/Nepal"
        let url = URL(string: urlString)!
        let session = URLSession(configuration: URLSessionConfiguration.default,
                                 delegate: nil,
                                 delegateQueue: nil)
        let completionExpectation = expectation(description: "GET \(urlString): Bad URL error")
        let task = session.dataTask(with: url) { (_, _, result) in
            let error = result as? URLError
            XCTAssertNotNil(error)
            XCTAssertEqual(error?.code, .badURL)
            completionExpectation.fulfill()
        }
        //should result in Bad URL error
        task.resume()
        
        waitForExpectations(timeout: 5) { error in
            XCTAssertNil(error)
            
            XCTAssertNotNil(task.error)
            XCTAssertEqual((task.error as? URLError)?.code, .badURL)
        }
    }
    
    func test_taskCopy() {
        let url = URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/Nepal")!
        let session = URLSession(configuration: URLSessionConfiguration.default,
                                 delegate: nil,
                                 delegateQueue: nil)
        let task = session.dataTask(with: url)
        
        XCTAssert(task.isEqual(task.copy()))
    }

    // This test is buggy because the server could respond before the task is cancelled.
    func test_cancelTask() async {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Peru"
        var urlRequest = URLRequest(url: URL(string: urlString)!)
        urlRequest.setValue("2.0", forHTTPHeaderField: "X-Pause")
        let d = DataTask(with: expectation(description: "GET \(urlString): task cancelation"))
        d.cancelExpectation = expectation(description: "GET \(urlString): task canceled")
        d.run(with: urlRequest)
        d.cancel()
        waitForExpectations(timeout: 12)
    }

    func test_unhandledURLProtocol() async {
        let urlString = "foobar://127.0.0.1:\(TestURLSession.serverPort)/Nepal"
        let url = URL(string: urlString)!
        let session = URLSession(configuration: URLSessionConfiguration.default,
                                 delegate: nil,
                                 delegateQueue: nil)
        let completionExpectation = expectation(description: "GET \(urlString): Unsupported URL error")
        let task = session.dataTask(with: url) { (data, response, _error) in
            XCTAssertNil(data)
            XCTAssertNil(response)
            let error = _error as? URLError
            XCTAssertNotNil(error)
            XCTAssertEqual(error?.code, .unsupportedURL)
            completionExpectation.fulfill()
        }
        task.resume()

        waitForExpectations(timeout: 5) { error in
            XCTAssertNil(error)
            XCTAssertEqual((task.error as? URLError)?.code, .unsupportedURL)
        }
    }

    func test_requestToNilURL() async {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Nepal"
        let url = URL(string: urlString)!
        let session = URLSession(configuration: URLSessionConfiguration.default,
                                 delegate: nil,
                                 delegateQueue: nil)
        let completionExpectation = expectation(description: "DataTask with nil URL: Unsupported URL error")
        var request = URLRequest(url: url)
        request.url = nil
        let task = session.dataTask(with: request) { (data, response, _error) in
            XCTAssertNil(data)
            XCTAssertNil(response)
            let error = _error as? URLError
            XCTAssertNotNil(error)
            XCTAssertEqual(error?.code, .unsupportedURL)
            completionExpectation.fulfill()
        }
        task.resume()

        waitForExpectations(timeout: 5) { error in
            XCTAssertNil(error)
            XCTAssertEqual((task.error as? URLError)?.code, .unsupportedURL)
        }
    }

    func test_suspendResumeTask() async throws {
        throw XCTSkip("This test is disabled (occasionally breaks)")
        #if false
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/get"
        let url = try XCTUnwrap(URL(string: urlString))

        let expect = expectation(description: "GET \(urlString)")
        let task = URLSession.shared.dataTask(with: url) { data, response, error in
             guard let httpResponse = response as? HTTPURLResponse else {
                XCTFail("response (\(response.debugDescription)) invalid")
                return
            }
            if httpResponse.statusCode == 200 {
                expect.fulfill()
            }
        }

        // The task starts suspended (1) so this requires 1 extra resume to perform the task
        task.suspend()                          // 2
        XCTAssertEqual(task.state, .suspended)
        task.suspend()                          // 3
        XCTAssertEqual(task.state, .suspended)

        task.resume()                           // 2
        XCTAssertEqual(task.state, .suspended)  // Darwin reports this as .running even though the task hasnt actually resumed
        task.resume()                           // 1
        XCTAssertEqual(task.state, .suspended)  // Darwin reports this as .running even though the task hasnt actually resumed

        task.resume()                           // 0 - Task can run
        XCTAssertEqual(task.state, .running)

        task.resume()                           // -1
        XCTAssertEqual(task.state, .running)
        task.resume()                           // -2
        XCTAssertEqual(task.state, .running)

        waitForExpectations(timeout: 3)
        #endif
    }

    
    func test_verifyRequestHeaders() async {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 5
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/requestHeaders"
        let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
        let expect = expectation(description: "POST \(urlString): get request headers")
        var req = URLRequest(url: URL(string: urlString)!)
        let headers = ["header1": "value1"]
        req.httpMethod = "POST"
        req.allHTTPHeaderFields = headers
        let task = session.dataTask(with: req) { (data, _, error) -> Void in
            defer { expect.fulfill() }
            XCTAssertNotNil(data)
            XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
            guard let data = data else { return }
            let headers = String(data: data, encoding: .utf8) ?? ""
            XCTAssertNotNil(headers.range(of: "header1: value1"))
        }
        task.resume()
        req.allHTTPHeaderFields = nil
        waitForExpectations(timeout: 30)
    }
    
    // Verify httpAdditionalHeaders from session configuration are added to the request
    // and whether it is overriden by Request.allHTTPHeaderFields.
    
    func test_verifyHttpAdditionalHeaders() async {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 5
        config.httpAdditionalHeaders = ["header2": "svalue2", "header3": "svalue3", "header4": "svalue4"]
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/requestHeaders"
        let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
        let expect = expectation(description: "POST \(urlString) with additional headers")
        var req = URLRequest(url: URL(string: urlString)!)
        let headers = ["header1": "rvalue1", "header2": "rvalue2", "Header4": "rvalue4"]
        req.httpMethod = "POST"
        req.allHTTPHeaderFields = headers
        let task = session.dataTask(with: req) { (data, _, error) -> Void in
            defer { expect.fulfill() }
            XCTAssertNotNil(data)
            XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
            guard let data = data else { return }
            let headers = String(data: data, encoding: .utf8) ?? ""
            XCTAssertNotNil(headers.range(of: "header1: rvalue1"))
            XCTAssertNotNil(headers.range(of: "header2: rvalue2"))
            XCTAssertNotNil(headers.range(of: "header3: svalue3"))
            XCTAssertNotNil(headers.range(of: "Header4: rvalue4"))
            XCTAssertNil(headers.range(of: "header4: svalue"))
        }
        task.resume()
        
        waitForExpectations(timeout: 30)
    }
    
    func test_taskTimeout() async {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 5
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Peru"
        let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
        let expect = expectation(description: "GET \(urlString): no timeout")
        let req = URLRequest(url: URL(string: urlString)!)
        let task = session.dataTask(with: req) { (data, _, error) -> Void in
            defer { expect.fulfill() }
            XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
        }
        task.resume()
        
        waitForExpectations(timeout: 30)
    }
    
    func test_httpTimeout() async {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 10
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Peru"
        let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
        let expect = expectation(description: "GET \(urlString): will timeout")
        var req = URLRequest(url: URL(string: urlString)!)
        req.setValue("3", forHTTPHeaderField: "x-pause")
        req.timeoutInterval = 1
        let task = session.dataTask(with: req) { (data, _, error) -> Void in
            defer { expect.fulfill() }
            XCTAssertEqual((error as? URLError)?.code, .timedOut, "Task should fail with URLError.timedOut error")
        }
        task.resume()
        waitForExpectations(timeout: 30)
    }

    func test_connectTimeout() async throws {
        throw XCTSkip("This test is disabled (flaky when all tests are run together)")
        #if false
        // Reconfigure http server for this specific scenario:
        // a slow request keeps web server busy, while other
        // request times out on connection attempt.
        Self.stopServer()
        Self.options = Options(serverBacklog: 1, isAsynchronous: false)
        Self.startServer()
        
        let config = URLSessionConfiguration.default
        let slowUrlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Peru"
        let fastUrlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Italy"
        let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
        let slowReqExpect = expectation(description: "GET \(slowUrlString): will complete")
        let fastReqExpect = expectation(description: "GET \(fastUrlString): will timeout")
        
        var slowReq = URLRequest(url: URL(string: slowUrlString)!)
        slowReq.setValue("3", forHTTPHeaderField: "x-pause")
        
        var fastReq = URLRequest(url: URL(string: fastUrlString)!)
        fastReq.timeoutInterval = 1
        
        let slowTask = session.dataTask(with: slowReq) { (data, _, error) -> Void in
            slowReqExpect.fulfill()
        }
        let fastTask = session.dataTask(with: fastReq) { (data, _, error) -> Void in
            defer { fastReqExpect.fulfill() }
            XCTAssertEqual((error as? URLError)?.code, .timedOut, "Task should fail with URLError.timedOut error")
        }
        slowTask.resume()
        try await Task.sleep(nanoseconds: 100_000_000) // Give slow task some time to start
        fastTask.resume()
        
        waitForExpectations(timeout: 30)

        // Reconfigure http server back to default settings
        Self.stopServer()
        Self.options = .default
        Self.startServer()
        #endif
    }
    
    func test_repeatedRequestsStress() async throws {
        // TODO: try disabling curl connection cache to force socket close early. Or create several url sessions (they have cleanup in deinit)
        
        let config = URLSessionConfiguration.default
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Peru"
        let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
        let req = URLRequest(url: URL(string: urlString)!)
        
        nonisolated(unsafe) var requestsLeft = 3000
        let expect = expectation(description: "\(requestsLeft) x GET \(urlString)")
        
        @Sendable func doRequests(completion: @Sendable @escaping () -> Void) {
            // We only care about completion of one of the tasks,
            // so we could move to next cycle.
            // Some overlapping would happen and that's what we
            // want actually to provoke issue with socket reuse
            // on Windows.
            let task = session.dataTask(with: req) { (_, _, _) -> Void in
            }
            task.resume()
            let task2 = session.dataTask(with: req) { (_, _, _) -> Void in
            }
            task2.resume()
            let task3 = session.dataTask(with: req) { (_, _, _) -> Void in
                completion()
            }
            task3.resume()
        }

        @Sendable func checkCountAndRunNext() {
            guard requestsLeft > 0 else {
                expect.fulfill()
                return
            }
            requestsLeft -= 1
            doRequests(completion: checkCountAndRunNext)
        }
        
        checkCountAndRunNext()

        waitForExpectations(timeout: 30)
    }

    func test_httpRedirectionWithCode300() async throws {
        let statusCode = 300
        for method in httpMethods {
            let testMethod = "\(method) request with statusCode \(statusCode)"
            let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/\(statusCode)?location=jsonBody"
            let url = try XCTUnwrap(URL(string: urlString), "Cant create URL for \(testMethod)")
            var request = URLRequest(url: url)
            request.httpMethod = method
            let d = HTTPRedirectionDataTask(with: expectation(description: "\(method) \(urlString): with HTTP redirection"))
            d.run(with: request)

            waitForExpectations(timeout: 12)
            XCTAssertNil(d.error)

            XCTAssertNil(d.redirectionResponse)
            XCTAssertNotNil(d.response)
            let httpresponse = d.response as? HTTPURLResponse
            XCTAssertEqual(httpresponse?.statusCode, statusCode, "HTTP final response code is invalid for \(testMethod)")

            let callbackMsg = "Bad callback for \(testMethod)"
            switch method {
                case "HEAD":
                    XCTAssertEqual(d.callbackCount, 2, "Callback count for \(testMethod)")
                    XCTAssertEqual(d.callback(0), "urlSession(_:dataTask:didReceive:completionHandler:)", callbackMsg)
                    XCTAssertEqual(d.callback(1), "urlSession(_:task:didCompleteWithError:)", callbackMsg)
                    XCTAssertEqual(d.receivedData.count, 0) // No body for HEAD requests

                default:
                    XCTAssertEqual(d.callbackCount, 3, "Callback count for \(testMethod)")
                    XCTAssertEqual(d.callback(0), "urlSession(_:dataTask:didReceive:completionHandler:)", callbackMsg)
                    XCTAssertEqual(d.callback(1), "urlSession(_:dataTask:didReceive:)", callbackMsg)
                    XCTAssertEqual(d.callback(2), "urlSession(_:task:didCompleteWithError:)", callbackMsg)

                    if let body = String(data: d.receivedData, encoding: .utf8) {
                        XCTAssertEqual(body, "Redirecting to \(method) jsonBody", "URI mismatch for \(testMethod)")
                    } else {
                        XCTFail("No JSON body for \(testMethod)")
                    }
            }
        }
    }

    func test_httpRedirectionWithCode301_302() async throws {
        for statusCode in 301...302 {
            for method in httpMethods {
                let testMethod = "\(method) request with statusCode \(statusCode)"
                let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/\(statusCode)?location=jsonBody"
                let url = try XCTUnwrap(URL(string: urlString), "Cant create URL for \(testMethod)")
                var request = URLRequest(url: url)
                request.httpMethod = method
                let d = HTTPRedirectionDataTask(with: expectation(description: "\(method) \(urlString): with HTTP redirection"))
                d.run(with: request)

                waitForExpectations(timeout: 12)
                XCTAssertNil(d.error)

                XCTAssertNotNil(d.response)
                let httpresponse = d.response as? HTTPURLResponse
                XCTAssertEqual(httpresponse?.statusCode, 200, "HTTP final response code is invalid for \(testMethod)")
                XCTAssertEqual(d.redirectionResponse?.statusCode, statusCode, "HTTP redirection response code is invalid for \(testMethod)")

                let callbackMsg = "Bad callback for \(testMethod)"
                switch method {
                    case "HEAD":
                        XCTAssertEqual(d.callbackCount, 3, "Callback count for \(testMethod)")
                        XCTAssertEqual(d.callback(0), "urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)", callbackMsg)
                        XCTAssertEqual(d.callback(1), "urlSession(_:dataTask:didReceive:completionHandler:)", callbackMsg)
                        XCTAssertEqual(d.callback(2), "urlSession(_:task:didCompleteWithError:)", callbackMsg)
                        XCTAssertEqual(d.receivedData.count, 0) // No body for HEAD requests


                    default:
                        XCTAssertEqual(d.callbackCount, 4, "Callback count for \(testMethod)")
                        XCTAssertEqual(d.callback(0), "urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)", callbackMsg)
                        XCTAssertEqual(d.callback(1), "urlSession(_:dataTask:didReceive:completionHandler:)", callbackMsg)
                        XCTAssertEqual(d.callback(2), "urlSession(_:dataTask:didReceive:)", callbackMsg)
                        XCTAssertEqual(d.callback(3), "urlSession(_:task:didCompleteWithError:)", callbackMsg)

                        if let jsonBody = try? JSONSerialization.jsonObject(with: d.receivedData, options: []) as? [String: String] {
                            let uri = (method == "POST" ? "GET" : method) + " /jsonBody HTTP/1.1"
                            XCTAssertEqual(jsonBody["uri"], uri, "URI mismatch for \(testMethod)")
                        } else {
                            XCTFail("No JSON body for \(testMethod)")
                    }
                }
            }
        }
    }

    func test_httpRedirectionWithCode303() async throws {
        let statusCode = 303
        for method in httpMethods {
            let testMethod = "\(method) request with statusCode \(statusCode)"
            let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/\(statusCode)?location=jsonBody"
            let url = try XCTUnwrap(URL(string: urlString), "Cant create URL for \(testMethod)")
            var request = URLRequest(url: url)
            request.httpMethod = method
            let d = HTTPRedirectionDataTask(with: expectation(description: "\(method) \(urlString): with HTTP redirection"))
            d.run(with: request)

            waitForExpectations(timeout: 12)
            XCTAssertNil(d.error)

            XCTAssertNotNil(d.response)
            let httpresponse = d.response as? HTTPURLResponse
            XCTAssertEqual(httpresponse?.statusCode, 200, "HTTP final response code is invalid for \(testMethod)")
            XCTAssertEqual(d.redirectionResponse?.statusCode, statusCode, "HTTP redirection response code is invalid for \(testMethod)")

            let callbackMsg = "Bad callback for \(testMethod)"
            XCTAssertEqual(d.callbackCount, 4, "Callback count for \(testMethod)")
            XCTAssertEqual(d.callback(0), "urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)", callbackMsg)
            XCTAssertEqual(d.callback(1), "urlSession(_:dataTask:didReceive:completionHandler:)", callbackMsg)
            XCTAssertEqual(d.callback(2), "urlSession(_:dataTask:didReceive:)", callbackMsg)
            XCTAssertEqual(d.callback(3), "urlSession(_:task:didCompleteWithError:)", callbackMsg)
            if let jsonBody = try? JSONSerialization.jsonObject(with: d.receivedData, options: []) as? [String: String] {
                let uri = "GET /jsonBody HTTP/1.1"
                XCTAssertEqual(jsonBody["uri"], uri, "URI mismatch for \(testMethod)")
            } else {
                XCTFail("No jsonBody for \(testMethod)")
            }
        }
    }

    func test_httpRedirectionWithCode304() async throws {
        let statusCode = 304
        for method in httpMethods {
            let testMethod = "\(method) request with statusCode \(statusCode)"
            let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/\(statusCode)?location=jsonBody"
            let url = try XCTUnwrap(URL(string: urlString), "Cant create URL for \(testMethod)")
            var request = URLRequest(url: url)
            request.httpMethod = method
            let d = HTTPRedirectionDataTask(with: expectation(description: "\(method) \(urlString): with HTTP redirection"))
            d.run(with: request)

            waitForExpectations(timeout: 12)
            XCTAssertNil(d.error)

            XCTAssertNotNil(d.response)
            let httpresponse = d.response as? HTTPURLResponse
            XCTAssertEqual(httpresponse?.statusCode, statusCode, "HTTP final response code is invalid for \(testMethod)")
            XCTAssertNil(d.redirectionResponse)

            let callbackMsg = "Bad callback for \(testMethod)"
            XCTAssertEqual(d.callbackCount, 2, "Callback count for \(testMethod)")
            XCTAssertEqual(d.callback(0), "urlSession(_:dataTask:didReceive:completionHandler:)", callbackMsg)
            XCTAssertEqual(d.callback(1), "urlSession(_:task:didCompleteWithError:)", callbackMsg)

            XCTAssertEqual(d.receivedData.count, 0)
            let jsonBody = try? JSONSerialization.jsonObject(with: d.receivedData, options: []) as? [String: String]
            XCTAssertNil(jsonBody)
        }
    }

    func test_httpRedirectionWithCode305_308() async throws {
        for statusCode in 305...308 {
            for method in httpMethods {
                let testMethod = "\(method) request with statusCode \(statusCode)"
                let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/\(statusCode)?location=jsonBody"
                let url = try XCTUnwrap(URL(string: urlString), "Cant create URL for \(testMethod)")
                var request = URLRequest(url: url)
                request.httpMethod = method
                let d = HTTPRedirectionDataTask(with: expectation(description: "\(method) \(urlString): with HTTP redirection"))
                d.run(with: request)

                waitForExpectations(timeout: 12)
                XCTAssertNil(d.error)

                XCTAssertNotNil(d.response)
                let httpresponse = d.response as? HTTPURLResponse
                XCTAssertEqual(httpresponse?.statusCode, 200, "HTTP final response code is invalid for \(testMethod)")
                XCTAssertEqual(d.redirectionResponse?.statusCode, statusCode, "HTTP redirection response code is invalid for \(testMethod)")

                let callbackMsg = "Bad callback for \(testMethod)"
                switch method {
                    case "HEAD":
                        XCTAssertEqual(d.callbackCount, 3, "Callback count for \(testMethod)")
                        XCTAssertEqual(d.callback(0), "urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)", callbackMsg)
                        XCTAssertEqual(d.callback(1), "urlSession(_:dataTask:didReceive:completionHandler:)", callbackMsg)
                        XCTAssertEqual(d.callback(2), "urlSession(_:task:didCompleteWithError:)", callbackMsg)
                        XCTAssertEqual(d.receivedData.count, 0) // No body for HEAD requests

                    default:
                        XCTAssertEqual(d.callbackCount, 4, "Callback count for \(testMethod)")
                        XCTAssertEqual(d.callback(0), "urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)", callbackMsg)
                        XCTAssertEqual(d.callback(1), "urlSession(_:dataTask:didReceive:completionHandler:)", callbackMsg)
                        XCTAssertEqual(d.callback(2), "urlSession(_:dataTask:didReceive:)", callbackMsg)
                        XCTAssertEqual(d.callback(3), "urlSession(_:task:didCompleteWithError:)", callbackMsg)
                        if let jsonBody = try? JSONSerialization.jsonObject(with: d.receivedData, options: []) as? [String: String] {
                            let uri = "\(method) /jsonBody HTTP/1.1"
                            XCTAssertEqual(jsonBody["uri"], uri, "URI mismatch for \(testMethod)")
                        } else {
                            XCTFail("No JSON body for \(testMethod)")
                    }
                }
            }
        }
    }

    func test_httpRedirectDontFollowUsingNil() async throws {
        let statusCode = 302
        for method in httpMethods {
            let testMethod = "\(method) request with statusCode \(statusCode)"
            let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/\(statusCode)?location=jsonBody"
            let url = try XCTUnwrap(URL(string: urlString), "Cant create URL for \(testMethod)")
            var request = URLRequest(url: url)
            request.httpMethod = method
            let delegate = SessionDelegate(with: expectation(description: "\(method) \(urlString): with HTTP redirection"))
            delegate.redirectionHandler = { (response: HTTPURLResponse, request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) in
                // Dont follow the request by calling the completion handler with nil
                completionHandler(nil)
            }
            delegate.run(with: request, timeoutInterval: 2)

            waitForExpectations(timeout: 3)
            XCTAssertNil(delegate.error)

            XCTAssertNotNil(delegate.response)
            let httpResponse = delegate.response as? HTTPURLResponse
            XCTAssertEqual(httpResponse?.statusCode, 302, "HTTP final response code is invalid for \(testMethod)")
            XCTAssertEqual(delegate.redirectionResponse?.statusCode, statusCode, "HTTP redirection response code is invalid for \(testMethod)")

            let callbackMsg = "Bad callback for \(testMethod)"
            switch method {
                case "HEAD":
                    let callbacks = [
                        "urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)",
                        "urlSession(_:dataTask:didReceive:completionHandler:)",
                        "urlSession(_:task:didCompleteWithError:)"
                    ]
                    XCTAssertEqual(delegate.callbacks.count, 3, "Callback count for \(testMethod)")
                    XCTAssertEqual(delegate.callbacks, callbacks, callbackMsg)
                    XCTAssertNil(delegate.receivedData) // No body for HEAD requests

                default:
                    let callbacks = [
                        "urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)",
                        "urlSession(_:dataTask:didReceive:completionHandler:)",
                        "urlSession(_:dataTask:didReceive:)",
                        "urlSession(_:task:didCompleteWithError:)",
                    ]
                    XCTAssertEqual(delegate.callbacks.count, 4, "Callback count for \(testMethod)")
                    XCTAssertEqual(delegate.callbacks, callbacks, callbackMsg)

                    let contentLength = Int(httpResponse?.value(forHTTPHeaderField: "Content-Length") ?? "")
                    let body = "Redirecting to \(method) jsonBody"
                    XCTAssertEqual(contentLength, body.count)
                    XCTAssertEqual(delegate.receivedData?.count, body.count)

                    if let data = delegate.receivedData, let string = String(data: data, encoding: .utf8) {
                        XCTAssertEqual(string, body)
                    } else {
                        XCTFail("No string body for \(testMethod)")
                }
            }
        }
    }

    func test_httpRedirectDontFollowIgnoringHandler() async throws {
        let statusCode = 302
        for method in httpMethods {
            let testMethod = "\(method) request with statusCode \(statusCode)"
            let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/\(statusCode)?location=jsonBody"
            let url = try XCTUnwrap(URL(string: urlString), "Cant create URL for \(testMethod)")
            var request = URLRequest(url: url)
            request.httpMethod = method
            let expect = expectation(description: "\(method) \(urlString): with HTTP redirection")
            expect.isInverted = true
            let delegate = SessionDelegate(with: expect)
            delegate.redirectionHandler = { (response: HTTPURLResponse, request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) in
                // Dont follow the request by not calling the completion handler at all
            }
            delegate.run(with: request, timeoutInterval: 1)

            waitForExpectations(timeout: 2)
            XCTAssertNil(delegate.error)
            XCTAssertNil(delegate.receivedData)
            XCTAssertNil(delegate.response)
            XCTAssertEqual(delegate.redirectionResponse?.statusCode, statusCode, "HTTP redirection response code is invalid for \(testMethod)")

            let callbackMsg = "Bad callback for \(testMethod)"
            XCTAssertEqual(delegate.callbacks.count, 1, "Callback count for \(testMethod)")
            XCTAssertEqual(delegate.callbacks, ["urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)"], callbackMsg)
        }
    }

    func test_httpRedirectionWithCompleteRelativePath() async {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/UnitedStates"
        let url = URL(string: urlString)!
        let d = HTTPRedirectionDataTask(with: expectation(description: "GET \(urlString): with HTTP redirection"))
        d.run(with: url)
        waitForExpectations(timeout: 12)
    }

    func test_httpRedirectionWithInCompleteRelativePath() async {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/UnitedKingdom"
        let url = URL(string: urlString)!
        let d = HTTPRedirectionDataTask(with: expectation(description: "GET \(urlString): with HTTP redirection"))
        d.run(with: url)
        waitForExpectations(timeout: 12)
    }

    func test_httpRedirectionWithDefaultPort() async {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/redirect-with-default-port"
        let url = URL(string: urlString)!
        let d = HTTPRedirectionDataTask(with: expectation(description: "GET \(urlString): with HTTP redirection"))
        d.run(with: url)
        waitForExpectations(timeout: 12)
    }
    
    func test_httpRedirectionWithEncodedQuery() async {
        let location = "echo-query%3Fparam%3Dfoo" // "echo-query?param=foo" url encoded
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/303?location=\(location)"
        let url = URL(string: urlString)!
        let d = HTTPRedirectionDataTask(with: expectation(description: "GET \(urlString): with HTTP redirection"))
        d.run(with: url)
        waitForExpectations(timeout: 12)
        
        if let body = String(data: d.receivedData, encoding: .utf8) {
            XCTAssertEqual(body, "param=foo")
        } else {
            XCTFail("No string body")
        }
    }

     // temporarily disabled (https://bugs.swift.org/browse/SR-5751)
    func test_httpRedirectionTimeout() async {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/UnitedStates"
        var req = URLRequest(url: URL(string: urlString)!)
        req.timeoutInterval = 3
        let config = URLSessionConfiguration.default
        let expect = expectation(description: "GET \(urlString): timeout with redirection ")
        let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
        let task = session.dataTask(with: req) { data, response, error in
            defer { expect.fulfill() }
            if let e = error as? URLError {
                XCTAssertEqual(e.code, .cannotConnectToHost, "Unexpected error code")
                return
            } else {
                XCTFail("test unexpectedly succeeded (response=\(response.debugDescription))")
            }
        }
        task.resume()
        waitForExpectations(timeout: 12)
    }

    func test_httpRedirectionChainInheritsTimeoutInterval() async throws {
        throw XCTSkip("This test is disabled (https://bugs.swift.org/browse/SR-14433)")
        #if false
        let redirectCount = 4
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/redirect/\(redirectCount)"
        let url = try XCTUnwrap(URL(string: urlString))
        let timeoutInterval = 3.0

        for method in httpMethods {
            var request = URLRequest(url: url)
            request.httpMethod = method
            request.timeoutInterval = timeoutInterval
            let delegate = SessionDelegate(with: expectation(description: "\(method) \(urlString): with HTTP redirection"))
            var timeoutIntervals: [Double] = []
            delegate.redirectionHandler = { (response: HTTPURLResponse, request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) in
                timeoutIntervals.append(request.timeoutInterval)
                completionHandler(request)
            }
            delegate.run(with: request, timeoutInterval: timeoutInterval)
            waitForExpectations(timeout: timeoutInterval + 1)
            XCTAssertEqual(timeoutIntervals.count, redirectCount, "Redirect chain count for \(method)")

            // Check the redirect request timeouts are the same as the original request timeout
            XCTAssertFalse(timeoutIntervals.contains { $0 != timeoutInterval }, "Timeout Intervals for \(method)")
            let httpResponse = delegate.response as? HTTPURLResponse
            XCTAssertEqual(httpResponse?.statusCode, 200, ".statusCode for \(method)")
        }
        #endif
    }

    func test_httpRedirectionExceededMaxRedirects() async throws {
        throw XCTSkip("This test is disabled (https://bugs.swift.org/browse/SR-14433)")
        #if false
        let expectedMaxRedirects = 20
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/redirect/99"
        let url = try XCTUnwrap(URL(string: urlString))
        let exceededCountUrlString = "http://127.0.0.1:\(TestURLSession.serverPort)/redirect/\(99 - expectedMaxRedirects)"
        let exceededCountUrl = try XCTUnwrap(URL(string: exceededCountUrlString))

        for method in httpMethods {
            var request = URLRequest(url: url)
            request.httpMethod = method
            let delegate = SessionDelegate(with: expectation(description: "\(method) \(urlString): with HTTP redirection"))

            var redirectRequests: [(HTTPURLResponse, URLRequest)] = []
            delegate.redirectionHandler = { (response: HTTPURLResponse, request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) in
                redirectRequests.append((response, request))
                completionHandler(request)
            }
            delegate.run(with: request, timeoutInterval: 5)
            waitForExpectations(timeout: 20)

            XCTAssertNil(delegate.response)
            XCTAssertNil(delegate.receivedData)

            XCTAssertNotNil(delegate.error)
            let error = delegate.error as? URLError
            XCTAssertEqual(error?.code.rawValue, NSURLErrorHTTPTooManyRedirects)
            XCTAssertEqual(error?.localizedDescription, "too many HTTP redirects")
            let userInfo = error?.userInfo
            XCTAssertNotNil(userInfo)
            let errorURL = userInfo?[NSURLErrorFailingURLErrorKey] as? URL
            XCTAssertEqual(errorURL, exceededCountUrl)

            // Check the last Redirection response/request received.
            XCTAssertEqual(redirectRequests.count, expectedMaxRedirects)
            let lastResponse = redirectRequests.last?.0
            let lastRequest = redirectRequests.last?.1

            XCTAssertEqual(lastResponse?.statusCode, 302)
            XCTAssertEqual(lastRequest?.url, exceededCountUrl)
        }
        #endif
    }

    func test_willPerformRedirect() async throws {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/redirect/1"
        let url = try XCTUnwrap(URL(string: urlString))
        let redirectURL = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/jsonBody"))
        let delegate = SessionDelegate()
        let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)
        let expect = expectation(description: "GET \(urlString)")

        let task = session.dataTask(with: url) { (data, response, error) in
            defer { expect.fulfill() }
            XCTAssertNil(error)
            XCTAssertNotNil(data)
            XCTAssertNotNil(response)
            XCTAssertEqual(delegate.redirectionRequest?.url, redirectURL)

            let callBacks = [
                "urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)",
            ]
            XCTAssertEqual(delegate.callbacks.count, callBacks.count)
            XCTAssertEqual(delegate.callbacks, callBacks)
        }

        task.resume()
        waitForExpectations(timeout: 5)
    }

    func test_httpNotFound() async throws {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/404"
        let url = try XCTUnwrap(URL(string: urlString))

        let delegate = SessionDelegate(with: expectation(description: "GET \(urlString): with a delegate"))
        delegate.run(with: url)

        waitForExpectations(timeout: 4)
        XCTAssertNil(delegate.error)
        XCTAssertNotNil(delegate.response)
        let httpResponse = delegate.response as? HTTPURLResponse
        XCTAssertEqual(httpResponse?.statusCode, 404)

        XCTAssertEqual(delegate.callbacks.count, 3)
        let callbacks = ["urlSession(_:dataTask:didReceive:completionHandler:)",
                         "urlSession(_:dataTask:didReceive:)",
                         "urlSession(_:task:didCompleteWithError:)"
        ]
        XCTAssertEqual(delegate.callbacks, callbacks)

        XCTAssertNotNil(delegate.receivedData)
        if let data = delegate.receivedData, let jsonBody = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: String] {
            XCTAssertEqual(jsonBody["uri"], "GET /404 HTTP/1.1")
        } else {
            XCTFail("Could not decode body as JSON")
        }
    }

    func test_http0_9SimpleResponses() async throws {
        throw XCTSkip("This test is disabled (breaks on Ubuntu 20.04)")
        #if false
        for brokenCity in ["Pompeii", "Sodom"] {
            let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/LandOfTheLostCities/\(brokenCity)"
            let url = URL(string: urlString)!

            let config = URLSessionConfiguration.default
            config.timeoutIntervalForRequest = 8
            let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
            let expect = expectation(description: "GET \(urlString): simple HTTP/0.9 response")
            let task = session.dataTask(with: url) { data, response, error in
                XCTAssertNotNil(data)
                XCTAssertNotNil(response)
                XCTAssertNil(error)

                defer { expect.fulfill() }

                guard let httpResponse = response as? HTTPURLResponse else {
                    XCTFail("response (\(response.debugDescription)) invalid")
                    return
                }
                XCTAssertEqual(200, httpResponse.statusCode, "HTTP response code is not 200")
            }
            task.resume()
            waitForExpectations(timeout: 12)
        }
        #endif
    }

    func test_outOfRangeButCorrectlyFormattedHTTPCode() async {
        let brokenCity = "Kameiros"
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/LandOfTheLostCities/\(brokenCity)"
        let url = URL(string: urlString)!

        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 8
        let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
        let expect = expectation(description: "GET \(urlString): out of range HTTP code")
        let task = session.dataTask(with: url) { data, response, error in
            XCTAssertNotNil(data)
            XCTAssertNotNil(response)
            XCTAssertNil(error)

            defer { expect.fulfill() }

            guard let httpResponse = response as? HTTPURLResponse else {
                XCTFail("response (\(response.debugDescription)) invalid")
                return
            }
            XCTAssertEqual(999, httpResponse.statusCode, "HTTP response code is not 999")
        }
        task.resume()
        waitForExpectations(timeout: 12)
    }

    func test_missingContentLengthButStillABody() async {
        let brokenCity = "Myndus"
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/LandOfTheLostCities/\(brokenCity)"
        let url = URL(string: urlString)!

        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 8
        let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
        let expect = expectation(description: "GET \(urlString): missing content length")
        let task = session.dataTask(with: url) { data, response, error in
            XCTAssertNotNil(data)
            XCTAssertNotNil(response)
            XCTAssertNil(error)

            defer { expect.fulfill() }

            guard let httpResponse = response as? HTTPURLResponse else {
                XCTFail("response (\(response.debugDescription)) invalid")
                return
            }
            XCTAssertEqual(200, httpResponse.statusCode, "HTTP response code is not 200")
        }
        task.resume()
        waitForExpectations(timeout: 12)
    }


    func test_illegalHTTPServerResponses() async {
        for brokenCity in ["Gomorrah", "Dinavar", "Kuhikugu"] {
            let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/LandOfTheLostCities/\(brokenCity)"
            let url = URL(string: urlString)!

            let config = URLSessionConfiguration.default
            config.timeoutIntervalForRequest = 8
            let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
            let expect = expectation(description: "GET \(urlString): illegal response")
            let task = session.dataTask(with: url) { data, response, error in
                XCTAssertNil(data)
                XCTAssertNil(response)
                XCTAssertNotNil(error)

                expect.fulfill()
            }
            task.resume()
            waitForExpectations(timeout: 12)
        }
    }

    func test_dataTaskWithSharedDelegate() async {
        let urlString0 = "http://127.0.0.1:\(TestURLSession.serverPort)/Nepal"
        let sharedDelegate = SharedDelegate(dataCompletionExpectation: expectation(description: "GET \(urlString0)"))
        let session = URLSession(configuration: .default, delegate: sharedDelegate, delegateQueue: nil)

        let dataRequest = URLRequest(url: URL(string: urlString0)!)
        let dataTask = session.dataTask(with: dataRequest)

        dataTask.resume()
        waitForExpectations(timeout: 20)
    }

    func test_simpleUploadWithDelegate() async {
        let delegate = HTTPUploadDelegate()
        let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/upload"
        var request = URLRequest(url: URL(string: urlString)!)
        request.httpMethod = "PUT"

        delegate.uploadCompletedExpectation = expectation(description: "PUT \(urlString): Upload data")

        let fileData = Data(count: 16 * 1024)
        let task = session.uploadTask(with: request, from: fileData)
        task.resume()
        waitForExpectations(timeout: 20)
        XCTAssertEqual(delegate.totalBytesSent, Int64(fileData.count))

    }

    func test_requestWithEmptyBody() async throws {
        for method in httpMethods {
            let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/" + method.lowercased()
            let url = try XCTUnwrap(URL(string: urlString))

            for body in [nil, Data()] as [Data?] {
                for contentType in ["text/plain; charset=utf-8", nil] {   // nil Content-Type lets URLSession set it
                    var urlRequest = URLRequest(url: url)
                    urlRequest.httpMethod = method
                    urlRequest.httpBody = body
                    if let ct = contentType  {
                        urlRequest.setValue(ct, forHTTPHeaderField: "Content-Type")
                    }

                    let delegate = SessionDelegate(with: expectation(description: "\(method) \(urlString): with empty HTTP Body"))
                    delegate.run(with: urlRequest, timeoutInterval: 3)
                    waitForExpectations(timeout: 4)

                    let httpResponse = delegate.response as? HTTPURLResponse
                    let contentLength = Int(httpResponse?.value(forHTTPHeaderField: "Content-Length") ?? "")

                    switch method {
                        case "HEAD":
                            XCTAssertNil(delegate.error, "Expected no errors for \(method) request")
                            XCTAssertNotNil(delegate.response, "Expected a response for \(method) request")
                            XCTAssertEqual(httpResponse?.statusCode, 200, "Status code for \(method) request")
                            XCTAssertEqual(delegate.callbacks.count, 2, "Callback count for \(method) request")
                            let callbacks = ["urlSession(_:dataTask:didReceive:completionHandler:)",
                                             "urlSession(_:task:didCompleteWithError:)"
                            ]
                            XCTAssertEqual(delegate.callbacks, callbacks, "Delegate Callbacks for \(method) request")
                            XCTAssertNil(delegate.receivedData, "Expected no Data for \(method) request")

                        default:
                            XCTAssertNil(delegate.error, "Expected no errors for \(method) request")
                            XCTAssertNotNil(delegate.response, "Expected a response for \(method) request")
                            XCTAssertEqual(httpResponse?.statusCode, 200, "Status code for \(method) request")
                            XCTAssertEqual(delegate.callbacks.count, 3, "Callback count for \(method) request")
                            let callBacks = ["urlSession(_:dataTask:didReceive:completionHandler:)",
                                             "urlSession(_:dataTask:didReceive:)",
                                             "urlSession(_:task:didCompleteWithError:)"
                            ]
                            XCTAssertEqual(delegate.callbacks, callBacks, "Delegate Callbacks for \(method) request")
                            XCTAssertNotNil(delegate.receivedData, "Expected Data for \(method) request")
                            XCTAssertEqual(delegate.receivedData?.count, contentLength, "Content-Length for \(method) request")
                            if let receivedData = delegate.receivedData, let jsonBody = try? JSONSerialization.jsonObject(with: receivedData, options: []) as? [String: String] {
                                XCTAssertEqual(jsonBody["Content-Type"], contentType, "Content-Type for \(method) request")
                            } else {
                                XCTFail("No JSON body for \(method)")
                        }
                    }
                }
            }
        }
    }

    func test_requestWithNonEmptyBody() async throws {
        throw XCTSkip("This test is disabled (started failing for no readily available reason)")
        #if false
        let bodyData = try XCTUnwrap("This is a request body".data(using: .utf8))
        for method in httpMethods {
            let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/" + method.lowercased()
            let url = try XCTUnwrap(URL(string: urlString))

            for contentType in ["text/plain; charset=utf-8", nil] {   // nil Content-Type lets URLSession set it
                var urlRequest = URLRequest(url: url)
                urlRequest.httpMethod = method
                urlRequest.httpBody = bodyData
                if let ct = contentType  {
                    urlRequest.setValue(ct, forHTTPHeaderField: "Content-Type")
                }

                let delegate = SessionDelegate(with: expectation(description: "\(method) \(urlString): with empty HTTP Body"))
                delegate.run(with: urlRequest, timeoutInterval: 3)
                waitForExpectations(timeout: 4)

                let httpResponse = delegate.response as? HTTPURLResponse
                let contentLength = Int(httpResponse?.value(forHTTPHeaderField: "Content-Length") ?? "")
                // Only POST sets a default Content-Type if it is nil
                let postedContentType = contentType ?? ((method == "POST") ? "application/x-www-form-urlencoded" : nil)

                let callBacks: [String]
                switch method {
                    case "HEAD":
                        XCTAssertNil(delegate.error)
                        XCTAssertNotNil(delegate.response)
                        XCTAssertEqual(httpResponse?.statusCode, 200)
                        XCTAssertNil(delegate.receivedData)
                        callBacks = ["urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)",
                                     "urlSession(_:dataTask:didReceive:completionHandler:)",
                                     "urlSession(_:task:didCompleteWithError:)"]

                    case "GET":
                        // GET requests must not have a body, which causes an error
                        XCTAssertNotNil(delegate.error)
                        let error = delegate.error as? URLError
                        XCTAssertEqual(error?.code.rawValue, NSURLErrorDataLengthExceedsMaximum)
                        XCTAssertEqual(error?.localizedDescription, "resource exceeds maximum size")
                        let userInfo = error?.userInfo
                        XCTAssertNotNil(userInfo)
                        let errorURL = userInfo?[NSURLErrorFailingURLErrorKey] as? URL
                        XCTAssertEqual(errorURL, url)

                        XCTAssertNil(delegate.response)
                        XCTAssertNil(delegate.receivedData)
                        callBacks = ["urlSession(_:task:didCompleteWithError:)"]

                    default:
                        XCTAssertNil(delegate.error)
                        XCTAssertNotNil(delegate.response)
                        XCTAssertEqual(httpResponse?.statusCode, 200)
                        XCTAssertNotNil(delegate.receivedData)
                        XCTAssertEqual(delegate.receivedData?.count, contentLength)
                        if let receivedData = delegate.receivedData, let jsonBody = try? JSONSerialization.jsonObject(with: receivedData, options: []) as? [String: String] {
                            XCTAssertEqual(jsonBody["Content-Type"], postedContentType)
                            let uri = "\(method) /" + method.lowercased() + " HTTP/1.1"
                            XCTAssertEqual(jsonBody["uri"], uri)
                            XCTAssertEqual(jsonBody["Content-Length"], "\(bodyData.count)", "Bad Content-Length for \(method) request")
                            if let postedBody = jsonBody["x-base64-body"], let decodedBody = Data(base64Encoded: postedBody) {
                                XCTAssertEqual(decodedBody, bodyData)
                            } else {
                                XCTFail("Could not decode Base64 body for \(method)")
                            }
                        } else {
                            XCTFail("No JSON body for \(method)")
                        }
                        callBacks = ["urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)",
                                     "urlSession(_:dataTask:didReceive:completionHandler:)",
                                     "urlSession(_:dataTask:didReceive:)",
                                     "urlSession(_:task:didCompleteWithError:)"]
                }
                XCTAssertEqual(delegate.callbacks.count, callBacks.count)
                XCTAssertEqual(delegate.callbacks, callBacks)
            }
        }
        #endif
    }


    func test_concurrentRequests() async throws {
        throw XCTSkip("This test is disabled (Intermittent SEGFAULT: rdar://84519512)")
        #if false
        let tasks = 10
        let syncQ = dispatchQueueMake("test_dataTaskWithURL.syncQ")
        var dataTasks: [DataTask] = []
        dataTasks.reserveCapacity(tasks)

        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Nepal"
        let url = try XCTUnwrap(URL(string: urlString))

        let g = dispatchGroupMake()
        for f in 0..<tasks {
            g.enter()
            let expectation = self.expectation(description: "GET \(urlString) [\(f)]: with a delegate")
            globalDispatchQueue.async {
                let d = DataTask(with: expectation)
                d.run(with: url)
                syncQ.sync {
                    dataTasks.append(d)
                }
                g.leave()
            }
        }
        waitForExpectations(timeout: 12)
        XCTAssertEqual(g.wait(timeout: .now() + .milliseconds(1)), .success)
        XCTAssertEqual(dataTasks.count, tasks)
        for task in dataTasks {
            XCTAssertFalse(task.error)
            XCTAssertEqual(task.capital, "Kathmandu", "test_dataTaskWithURLRequest returned an unexpected result")
        }
        #endif
    }

    func emptyCookieStorage(storage: HTTPCookieStorage?) {
        if let storage = storage, let cookies = storage.cookies {
            for cookie in cookies {
                storage.deleteCookie(cookie)
            }
        }
    }

    func test_disableCookiesStorage() async {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 5
        config.httpCookieAcceptPolicy = HTTPCookie.AcceptPolicy.never
        emptyCookieStorage(storage: config.httpCookieStorage)
        XCTAssertEqual(config.httpCookieStorage?.cookies?.count, 0)
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/requestCookies"
        let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
        let expect = expectation(description: "POST \(urlString)")
        var req = URLRequest(url: URL(string: urlString)!)
        req.httpMethod = "POST"
        let task = session.dataTask(with: req) { (data, response, error) -> Void in
            defer { expect.fulfill() }
            XCTAssertNotNil(data)
            XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
            guard let httpResponse = try? XCTUnwrap(response as? HTTPURLResponse) else {
                XCTFail("response should be a non-nil HTTPURLResponse")
                return
            }
            XCTAssertNotNil(httpResponse.allHeaderFields["Set-Cookie"])
        }
        task.resume()
        waitForExpectations(timeout: 30)
        let cookies = HTTPCookieStorage.shared.cookies
        XCTAssertEqual(cookies?.count, 0)
    }

    func test_cookiesStorage() async {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 5
        emptyCookieStorage(storage: config.httpCookieStorage)
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/requestCookies"
        let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
        let expect = expectation(description: "POST \(urlString)")
        var req = URLRequest(url: URL(string: urlString)!)
        req.httpMethod = "POST"
        let task = session.dataTask(with: req) { (data, response, error) -> Void in
            defer { expect.fulfill() }
            XCTAssertNotNil(data)
            XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
            guard let httpResponse = try? XCTUnwrap(response as? HTTPURLResponse) else {
                XCTFail("response should be a non-nil HTTPURLResponse")
                return
            }
            XCTAssertNotNil(httpResponse.allHeaderFields["Set-Cookie"])
        }
        task.resume()
        waitForExpectations(timeout: 30)
        let cookies = HTTPCookieStorage.shared.cookies
        XCTAssertEqual(cookies?.count, 1)
    }

    func test_redirectionWithSetCookies() async {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 5
        emptyCookieStorage(storage: config.httpCookieStorage)
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/redirectToEchoHeaders"
        let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
        let expect = expectation(description: "POST \(urlString)")
        let req = URLRequest(url: URL(string: urlString)!)
        let task = session.dataTask(with: req) { (data, _, error) -> Void in
            defer { expect.fulfill() }
            // Because /redirectToEchoHeaders is a redirection, this is the
            // final result of the redirection, not the redirection itself.
            guard let data = try? XCTUnwrap(data) else {
                XCTFail("data should not be nil")
                return
            }
            XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
            let headers = String(data: data, encoding: String.Encoding.utf8) ?? ""
            XCTAssertNotNil(headers.range(of: "Cookie: redirect=true"))
        }
        task.resume()
        waitForExpectations(timeout: 30)
    }

    func test_previouslySetCookiesAreSentInLaterRequests() async {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 5
        emptyCookieStorage(storage: config.httpCookieStorage)
        let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)

        let urlString1 = "http://127.0.0.1:\(TestURLSession.serverPort)/requestCookies"
        let expect1 = expectation(description: "POST \(urlString1)")
        var req1 = URLRequest(url: URL(string: urlString1)!)
        req1.httpMethod = "POST"

        let urlString2 = "http://127.0.0.1:\(TestURLSession.serverPort)/echoHeaders"
        let expect2 = expectation(description: "POST \(urlString2)")
        
        let task1 = session.dataTask(with: req1) { (data, response, error) -> Void in
            defer { expect1.fulfill() }
            XCTAssertNotNil(data)
            XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
            guard let httpResponse = try? XCTUnwrap(response as? HTTPURLResponse) else {
                XCTFail("response should be a non-nil HTTPURLResponse")
                return
            }
            XCTAssertNotNil(httpResponse.allHeaderFields["Set-Cookie"])

            var req2 = URLRequest(url: URL(string: urlString2)!)
            req2.httpMethod = "POST"

            let task2 = session.dataTask(with: req2) { (data, _, error) -> Void in
                defer { expect2.fulfill() }
                guard let data = try? XCTUnwrap(data) else {
                    XCTFail("data should not be nil")
                    return
                }
                XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
                let headers = String(data: data, encoding: String.Encoding.utf8) ?? ""
                XCTAssertNotNil(headers.range(of: "Cookie: fr=anjd&232"))
            }
            task2.resume()
        }
        task1.resume()

        waitForExpectations(timeout: 30)
    }

    func test_cookieStorageForEphemeralConfiguration() async {
        let config = URLSessionConfiguration.ephemeral
        config.timeoutIntervalForRequest = 5
        emptyCookieStorage(storage: config.httpCookieStorage)

        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/requestCookies"
        let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
        let expect = expectation(description: "POST \(urlString)")
        var req = URLRequest(url: URL(string: urlString)!)
        req.httpMethod = "POST"
        let task = session.dataTask(with: req) { (data, _, error) -> Void in
            defer { expect.fulfill() }
            XCTAssertNotNil(data)
            XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
        }
        task.resume()
        waitForExpectations(timeout: 30)
        let cookies = config.httpCookieStorage?.cookies
        XCTAssertEqual(cookies?.count, 1)

        let config2 = URLSessionConfiguration.ephemeral
        let cookies2 = config2.httpCookieStorage?.cookies
        XCTAssertEqual(cookies2?.count, 0)
    }

    func test_setCookieHeadersCanBeIgnored() async {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 5
        config.httpShouldSetCookies = false
        emptyCookieStorage(storage: config.httpCookieStorage)
        let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)

        let urlString1 = "http://127.0.0.1:\(TestURLSession.serverPort)/requestCookies"
        let expect1 = expectation(description: "POST \(urlString1)")
        var req1 = URLRequest(url: URL(string: urlString1)!)
        req1.httpMethod = "POST"

        let urlString2 = "http://127.0.0.1:\(TestURLSession.serverPort)/echoHeaders"
        let expect2 = expectation(description: "POST \(urlString2)")

        let task1 = session.dataTask(with: req1) { (data, response, error) -> Void in
            defer { expect1.fulfill() }
            XCTAssertNotNil(data)
            XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
            guard let httpResponse = try? XCTUnwrap(response as? HTTPURLResponse) else {
                XCTFail("response should be a non-nil HTTPURLResponse")
                return
            }
            XCTAssertNotNil(httpResponse.allHeaderFields["Set-Cookie"])

            var req2 = URLRequest(url: URL(string: urlString2)!)
            req2.httpMethod = "POST"

            let task2 = session.dataTask(with: req2) { (data, _, error) -> Void in
                defer { expect2.fulfill() }
                guard let data = try? XCTUnwrap(data) else {
                    XCTFail("data should not be nil")
                    return
                }
                XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
                let headers = String(data: data, encoding: String.Encoding.utf8) ?? ""
                XCTAssertNil(headers.range(of: "Cookie: fr=anjd&232"))
            }
            task2.resume()
        }
        task1.resume()

        waitForExpectations(timeout: 30)
    }

    // Validate that the properties are correctly set
    func test_initURLSessionConfiguration() async {
        let config = URLSessionConfiguration.default
        config.requestCachePolicy = .useProtocolCachePolicy
        config.timeoutIntervalForRequest = 30
        config.timeoutIntervalForResource = 604800
        config.networkServiceType = .default
        config.allowsCellularAccess = false
        config.isDiscretionary = true
        config.httpShouldUsePipelining = true
        config.httpShouldSetCookies = true
        config.httpCookieAcceptPolicy = .always
        config.httpMaximumConnectionsPerHost = 2
        config.httpCookieStorage = HTTPCookieStorage.shared
        config.urlCredentialStorage = nil
        config.urlCache = nil
        config.shouldUseExtendedBackgroundIdleMode = true

        XCTAssertEqual(config.requestCachePolicy, NSURLRequest.CachePolicy.useProtocolCachePolicy)
        XCTAssertEqual(config.timeoutIntervalForRequest, 30)
        XCTAssertEqual(config.timeoutIntervalForResource, 604800)
        XCTAssertEqual(config.networkServiceType, NSURLRequest.NetworkServiceType.default)
        XCTAssertEqual(config.allowsCellularAccess, false)
        XCTAssertEqual(config.isDiscretionary, true)
        XCTAssertEqual(config.httpShouldUsePipelining, true)
        XCTAssertEqual(config.httpShouldSetCookies, true)
        XCTAssertEqual(config.httpCookieAcceptPolicy, HTTPCookie.AcceptPolicy.always)
        XCTAssertEqual(config.httpMaximumConnectionsPerHost, 2)
        XCTAssertEqual(config.httpCookieStorage, HTTPCookieStorage.shared)
        XCTAssertEqual(config.urlCredentialStorage, nil)
        XCTAssertEqual(config.urlCache, nil)
        XCTAssertEqual(config.shouldUseExtendedBackgroundIdleMode, true)
   }

   func test_basicAuthRequest() async {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/auth/basic"
        let url = URL(string: urlString)!
        let d = DataTask(with: expectation(description: "GET \(urlString): with a delegate"))
        d.run(with: url)
        waitForExpectations(timeout: 60)
    }

    /* Test for SR-8970 to verify that content-type header is not added to post with empty body */
    func test_postWithEmptyBody() async {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 5
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/emptyPost"
        let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
        let expect = expectation(description: "POST \(urlString): post with empty body")
        var req = URLRequest(url: URL(string: urlString)!)
        req.httpMethod = "POST"
        let task = session.dataTask(with: req) { (_, response, error) -> Void in
            defer { expect.fulfill() }
            XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
            guard let httpresponse = response as? HTTPURLResponse else { fatalError() }
            XCTAssertEqual(200, httpresponse.statusCode, "HTTP response code is not 200")
        }
        task.resume()
        waitForExpectations(timeout: 30)
    }

    func test_basicAuthWithUnauthorizedHeader() async {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/unauthorized"
        let url = URL(string: urlString)!
        let expect = expectation(description: "GET \(urlString): with a completion handler")
        let session = URLSession(configuration: URLSessionConfiguration.default)
        let task = session.dataTask(with: url) { _, response, error in
            defer { expect.fulfill() }
            XCTAssertNotNil(response)
            XCTAssertNil(error)
        }
        task.resume()
        waitForExpectations(timeout: 12, handler: nil)
    }

    func test_checkErrorTypeAfterInvalidateAndCancel() async throws {
        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt"
        let url = try XCTUnwrap(URL(string: urlString))
        var urlRequest = URLRequest(url: url)
        urlRequest.addValue("5", forHTTPHeaderField: "X-Pause")
        let expect = expectation(description: "Check error code of tasks after invalidateAndCancel")
        let delegate = SessionDelegate()
        let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)
        let task = session.dataTask(with: urlRequest) { (_, _, error) in
            XCTAssertNotNil(error as? URLError)
            if let urlError = error as? URLError {
                XCTAssertEqual(urlError._nsError.code, NSURLErrorCancelled)
                XCTAssertEqual(urlError.userInfo[NSURLErrorFailingURLErrorKey] as? URL, URL(string: urlString))
                XCTAssertEqual(urlError.userInfo[NSURLErrorFailingURLStringErrorKey] as? String, urlString)
                XCTAssertEqual(urlError.localizedDescription, "cancelled")
            }

            expect.fulfill()
        }
        task.resume()
        session.invalidateAndCancel()
        waitForExpectations(timeout: 5)
    }

    func test_taskCountAfterInvalidateAndCancel() async throws {
        let expect = expectation(description: "Check task count after invalidateAndCancel")

        let session = URLSession(configuration: .default)
        var request = URLRequest(url: try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt")))
        request.addValue("5", forHTTPHeaderField: "X-Pause")
        let task1 = session.dataTask(with: request)
        request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/requestHeaders"))
        let task2 = session.dataTask(with: request)
        request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/emptyPost"))
        let task3 = session.dataTask(with: request)

        task1.resume()
        task2.resume()
        session.invalidateAndCancel()

        session.getAllTasks { tasksBeforeResume in
            XCTAssertEqual(tasksBeforeResume.count, 0)

            // Resume a task after invalidating a session shouldn't change the task's status
            task3.resume()

            session.getAllTasks { tasksAfterResume in
                XCTAssertEqual(tasksAfterResume.count, 0)
                expect.fulfill()
            }
        }
        waitForExpectations(timeout: 5)
    }

    func test_sessionDelegateAfterInvalidateAndCancel() async throws {
        let delegate = SessionDelegate()
        let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)
        session.invalidateAndCancel()
        try await Task.sleep(nanoseconds: 2_000_000_000)
        XCTAssertNil(session.delegate)
    }

    func test_sessionDelegateCalledIfTaskDelegateDoesNotImplement() async throws {
        let expectation = XCTestExpectation(description: "task finished")
        let delegate = SessionDelegate(with: expectation)
        let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)
        
        final class EmptyTaskDelegate: NSObject, URLSessionTaskDelegate, Sendable { }
        let url = URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt")!
        let request = URLRequest(url: url)
        let task = session.dataTask(with: request)
        task.delegate = EmptyTaskDelegate()
        task.resume()

        await fulfillment(of: [expectation], timeout: 5)
    }

    func test_getAllTasks() async throws {
        throw XCTSkip("This test is disabled (this causes later ones to crash)")
        #if false
        let expect = expectation(description: "Tasks URLSession.getAllTasks")

        let session = URLSession(configuration: .default)
        var request = URLRequest(url: try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt")))
        request.addValue("5", forHTTPHeaderField: "X-Pause")
        let dataTask1 = session.dataTask(with: request)
        request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/requestHeaders"))
        let dataTask2 = session.dataTask(with: request)
        request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/emptyPost"))
        let dataTask3 = session.dataTask(with: request)

        session.getAllTasks { (tasksBeforeResume) in
            XCTAssertEqual(tasksBeforeResume.count, 0)

            dataTask1.cancel()

            dataTask2.resume()
            dataTask2.suspend()
            // dataTask3 is suspended even before it was resumed, so the next call to `getAllTasks` should not include this tasks
            dataTask3.suspend()
            session.getAllTasks { (tasksAfterCancel) in
                // tasksAfterCancel should only contain dataTask2
                XCTAssertEqual(tasksAfterCancel.count, 1)

                // A task will in be in suspended state when it was created.
                // Given that, dataTask3 was suspended once again earlier above, so it should receive `resume()` twice in order to be executed
                // Calling `getAllTasks` next time should not include dataTask3
                dataTask3.resume()

                session.getAllTasks { (tasksAfterFirstResume) in
                    // tasksAfterFirstResume should only contain dataTask2
                    XCTAssertEqual(tasksAfterFirstResume.count, 1)

                    // Now dataTask3 received `resume()` twice, this time `getAllTasks` should include
                    dataTask3.resume()
                    session.getAllTasks { (tasksAfterSecondResume) in
                        // tasksAfterSecondResume should contain dataTask2 and dataTask2 this time
                        XCTAssertEqual(tasksAfterSecondResume.count, 2)
                        expect.fulfill()
                    }
                }
            }
        }

        waitForExpectations(timeout: 20)
        #endif
    }

    func test_getTasksWithCompletion() async throws {
        throw XCTSkip("This test is disabled (Flaky tests)")
        #if false
        let expect = expectation(description: "Test URLSession.getTasksWithCompletion")

        let session = URLSession(configuration: .default)
        var request = URLRequest(url: try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt")))
        request.addValue("5", forHTTPHeaderField: "X-Pause")
        let dataTask1 = session.dataTask(with: request)
        request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/requestHeaders"))
        let dataTask2 = session.dataTask(with: request)
        request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/emptyPost"))
        let dataTask3 = session.dataTask(with: request)

        request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/upload"))
        let uploadTask1 = session.uploadTask(with: request, from: Data())
        request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/echo"))
        let uploadTask2 = session.uploadTask(with: request, from: Data())

        request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/DTDs/PropertyList-1.0.dtd"))
        let downloadTask1 = session.downloadTask(with: request)

        session.getTasksWithCompletionHandler { (dataTasksBeforeCancel, uploadTasksBeforeCancel, downloadTasksBeforeCancel) in
            XCTAssertEqual(dataTasksBeforeCancel.count, 0)
            XCTAssertEqual(uploadTasksBeforeCancel.count, 0)
            XCTAssertEqual(downloadTasksBeforeCancel.count, 0)

            dataTask1.cancel()
            dataTask2.resume()
            // dataTask3 is resumed and suspended, so this task should be a part of `getTasksWithCompletionHandler` response
            dataTask3.resume()
            dataTask3.suspend()

            // uploadTask1 suspended even before it was resumed, so this task shouldn't be a part of `getTasksWithCompletionHandler` response
            uploadTask1.suspend()
            uploadTask2.resume()

            downloadTask1.cancel()

            session.getTasksWithCompletionHandler{ (dataTasksAfterCancel, uploadTasksAfterCancel, downloadTasksAfterCancel) in
                XCTAssertEqual(dataTasksAfterCancel.count, 2)
                XCTAssertEqual(uploadTasksAfterCancel.count, 1)
                XCTAssertEqual(downloadTasksAfterCancel.count, 0)
                expect.fulfill()
            }
        }

        waitForExpectations(timeout: 20)
        #endif
    }

    func test_noDoubleCallbackWhenCancellingAndProtocolFailsFast() async throws {
        throw XCTSkip("This test is disabled (Crashes nondeterministically: https://bugs.swift.org/browse/SR-11310)")
        #if false
        let urlString = "failfast://bogus"
        var callbackCount = 0
        let callback1 = expectation(description: "Callback call #1")
        let callback2 = expectation(description: "Callback call #2")
        callback2.isInverted = true
        let delegate = SessionDelegate()
        let url = try XCTUnwrap(URL(string: urlString))
        let configuration = URLSessionConfiguration.default
        configuration.protocolClasses = [FailFastProtocol.self]
        let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
        let task = session.dataTask(with: url) { (_, _, error) in
            callbackCount += 1
            XCTAssertNotNil(error)
            if let urlError = error as? URLError {
                XCTAssertEqual(urlError._nsError.code, NSURLErrorCancelled)
            }

            if callbackCount == 1 {
                callback1.fulfill()
            } else {
                callback2.fulfill()
            }
        }
        task.resume()
        session.invalidateAndCancel()
        waitForExpectations(timeout: 1)
        #endif
    }

    func test_cancelledTasksCannotBeResumed() async throws {
        throw XCTSkip("This test is disabled (breaks on Ubuntu 18.04)")
        #if false
        let url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/Nepal"))
        let session = URLSession(configuration: .default, delegate: nil, delegateQueue: nil)
        let task = session.dataTask(with: url)

        task.cancel() // should set .cancelling and eventually .completed
        task.resume() // should not change the task to .running

        let e = expectation(description: "getAllTasks callback called")
        session.getAllTasks { tasks in
            XCTAssertEqual(tasks.count, 0)
            e.fulfill()
        }

        waitForExpectations(timeout: 1)
        #endif
    }
    func test_invalidResumeDataForDownloadTask() async throws {
        throw XCTSkip("This test is disabled (Crashes nondeterministically: https://bugs.swift.org/browse/SR-11353)")
        #if false
        let done = expectation(description: "Invalid resume data for download task (with completion block)")
        URLSession.shared.downloadTask(withResumeData: Data()) { (url, response, error) in
            XCTAssertNil(url)
            XCTAssertNil(response)
            XCTAssert(error is URLError)
            XCTAssertEqual((error as? URLError)?.errorCode, URLError.unsupportedURL.rawValue)
            
            done.fulfill()
        }.resume()
        waitForExpectations(timeout: 20)
        
        let d = DownloadTask(testCase: self, description: "Invalid resume data for download task")
        d.run { (session) -> DownloadTask.Configuration in
            return DownloadTask.Configuration(task: session.downloadTask(withResumeData: Data()),
                                              errorExpectation:
                { (error) in
                    XCTAssert(error is URLError)
                    XCTAssertEqual((error as? URLError)?.errorCode, URLError.unsupportedURL.rawValue)
            })
        }
        waitForExpectations(timeout: 20)
        #endif
    }
    
    func test_simpleUploadWithDelegateProvidingInputStream() async throws {
        throw XCTSkip("This test is disabled (Times out frequently: https://bugs.swift.org/browse/SR-11343)")
        #if false
        let fileData = Data(count: 16 * 1024)
        for method in httpMethods {
            let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/" + method.lowercased()
            let url = try XCTUnwrap(URL(string: urlString))
            var request = URLRequest(url: url)
            request.httpMethod = method

            let delegate = SessionDelegate(with: expectation(description: "\(method) \(urlString): Upload data"))
            delegate.newBodyStreamHandler = { (completionHandler: @escaping (InputStream?) -> Void) in
                completionHandler(InputStream(data: fileData))
            }
            delegate.runUploadTask(with: request, timeoutInterval: 4)
            await waitForExpectations(timeout: 5)

            let httpResponse = delegate.response as? HTTPURLResponse
            let callBacks: [String]

            switch method {
                case "HEAD":
                    XCTAssertNil(delegate.error)
                    XCTAssertNotNil(delegate.response)
                    XCTAssertEqual(httpResponse?.statusCode, 200)
                    XCTAssertNil(delegate.receivedData)
                    XCTAssertEqual(delegate.totalBytesSent, Int64(fileData.count))
                    callBacks = ["urlSession(_:task:needNewBodyStream:)",
                                 "urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)",
                                 "urlSession(_:dataTask:didReceive:completionHandler:)",
                                 "urlSession(_:task:didCompleteWithError:)"]

                case "GET":
                    // GET requests must not have a body, which causes an error
                    XCTAssertNotNil(delegate.error)
                    let error = delegate.error as? URLError
                    XCTAssertEqual(error?.code.rawValue, NSURLErrorDataLengthExceedsMaximum)
                    XCTAssertEqual(error?.localizedDescription, "resource exceeds maximum size")
                    let userInfo = error?.userInfo
                    XCTAssertNotNil(userInfo)
                    let errorURL = userInfo?[NSURLErrorFailingURLErrorKey] as? URL
                    XCTAssertEqual(errorURL, url)
                    XCTAssertNil(delegate.response)
                    XCTAssertNil(delegate.receivedData)
                    XCTAssertEqual(delegate.totalBytesSent, 0)
                    callBacks = ["urlSession(_:task:needNewBodyStream:)",
                                 "urlSession(_:task:didCompleteWithError:)"]

                default:
                    XCTAssertNil(delegate.error)
                    XCTAssertNotNil(delegate.response)
                    XCTAssertEqual(httpResponse?.statusCode, 200)
                    XCTAssertEqual(delegate.totalBytesSent, Int64(fileData.count))
                    XCTAssertNotNil(delegate.receivedData)
                    let contentLength = Int(httpResponse?.value(forHTTPHeaderField: "Content-Length") ?? "")

                    XCTAssertEqual(delegate.receivedData?.count, contentLength)
                    if let receivedData = delegate.receivedData, let jsonBody = try? JSONSerialization.jsonObject(with: receivedData, options: []) as? [String: String] {
                        if let postedContentType = (method == "POST") ? "application/x-www-form-urlencoded" : nil {
                            XCTAssertEqual(jsonBody["Content-Type"], postedContentType)
                        } else {
                            XCTAssertNil(jsonBody.index(forKey: "Content-Type"))
                        }
                        if let postedBody = jsonBody["x-base64-body"], let decodedBody = Data(base64Encoded: postedBody) {
                            XCTAssertEqual(decodedBody, fileData)
                        } else {
                            XCTFail("Could not decode Base64 body for \(method)")
                        }
                    } else {
                        XCTFail("No JSON body for \(method)")
                    }
                    callBacks = ["urlSession(_:task:needNewBodyStream:)",
                                 "urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)",
                                 "urlSession(_:dataTask:didReceive:completionHandler:)",
                                 "urlSession(_:dataTask:didReceive:)",
                                 "urlSession(_:task:didCompleteWithError:)"]
            }
            XCTAssertEqual(delegate.callbacks.count, callBacks.count, "Callback count for \(method)")
            XCTAssertEqual(delegate.callbacks, callBacks, "Callbacks for \(method)")
        }
        #endif
    }
    
#if NS_FOUNDATION_ALLOWS_TESTABLE_IMPORT
    func test_webSocket() async throws {
        guard #available(macOS 12, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return }
        guard URLSessionWebSocketTask.supportsWebSockets else {
            print("libcurl lacks WebSockets support, skipping \(#function)")
            return
        }
        
        let urlString = "ws://127.0.0.1:\(TestURLSession.serverPort)/web-socket"
        let url = try XCTUnwrap(URL(string: urlString))
        let request = URLRequest(url: url)
        
        let delegate = SessionDelegate(with: expectation(description: "\(urlString): Connect"))
        let task = delegate.runWebSocketTask(with: request, timeoutInterval: 4)
        
        // We interleave sending and receiving, as the test HTTPServer implementation is barebones, and can't handle receiving more than one frame at a time.  So, this back-and-forth acts as a gating mechanism
        try await task.send(.string("Hello"))
        
        let stringMessage = try await task.receive()
        switch stringMessage {
        case .string(let str):
            XCTAssert(str == "Hello")
        default:
            XCTFail("Unexpected String Message")
        }
        
        try await task.send(.data(Data([0x20, 0x22, 0x10, 0x03])))
        
        let dataMessage = try await task.receive()
        switch dataMessage {
        case .data(let data):
            XCTAssert(data == Data([0x20, 0x22, 0x10, 0x03]))
        default:
            XCTFail("Unexpected Data Message")
        }
        
        do {
            try await task.sendPing()
            // Server hasn't closed the connection yet
        } catch {
            // Server closed the connection before we could process the pong
            let urlError = try XCTUnwrap(error as? URLError)
            XCTAssertEqual(urlError._nsError.code, NSURLErrorNetworkConnectionLost)
        }

        await fulfillment(of: [delegate.expectation], timeout: 50)
        
        do {
            _ = try await task.receive()
            XCTFail("Expected to throw when receiving on closed task")
        } catch {
            let urlError = try XCTUnwrap(error as? URLError)
            XCTAssertEqual(urlError._nsError.code, NSURLErrorNetworkConnectionLost)
        }
        
        let callbacks = [ "urlSession(_:webSocketTask:didOpenWithProtocol:)",
                          "urlSession(_:webSocketTask:didCloseWith:reason:)",
                          "urlSession(_:task:didCompleteWithError:)" ]
        XCTAssertEqual(delegate.callbacks.count, callbacks.count)
        XCTAssertEqual(delegate.callbacks, callbacks, "Callbacks for \(#function)")
    }

    func test_webSocketShared() async throws {
        guard #available(macOS 12, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return }
        guard URLSessionWebSocketTask.supportsWebSockets else {
            print("libcurl lacks WebSockets support, skipping \(#function)")
            return
        }

        let urlString = "ws://127.0.0.1:\(TestURLSession.serverPort)/web-socket"
        let url = try XCTUnwrap(URL(string: urlString))

        let task = URLSession.shared.webSocketTask(with: url)
        task.resume()

        // We interleave sending and receiving, as the test HTTPServer implementation is barebones, and can't handle receiving more than one frame at a time.  So, this back-and-forth acts as a gating mechanism
        try await task.send(.string("Hello"))

        let stringMessage = try await task.receive()
        switch stringMessage {
        case .string(let str):
            XCTAssert(str == "Hello")
        default:
            XCTFail("Unexpected String Message")
        }

        try await task.send(.data(Data([0x20, 0x22, 0x10, 0x03])))

        let dataMessage = try await task.receive()
        switch dataMessage {
        case .data(let data):
            XCTAssert(data == Data([0x20, 0x22, 0x10, 0x03]))
        default:
            XCTFail("Unexpected Data Message")
        }

        do {
            try await task.sendPing()
            // Server hasn't closed the connection yet
        } catch {
            // Server closed the connection before we could process the pong
            let urlError = try XCTUnwrap(error as? URLError)
            XCTAssertEqual(urlError._nsError.code, NSURLErrorNetworkConnectionLost)
        }
    }

    func test_webSocketSpecificProtocol() async throws {
        guard #available(macOS 12, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return }
        guard URLSessionWebSocketTask.supportsWebSockets else {
            print("libcurl lacks WebSockets support, skipping \(#function)")
            return
        }

        let urlString = "ws://127.0.0.1:\(TestURLSession.serverPort)/web-socket/chatbot"
        let url = try XCTUnwrap(URL(string: urlString))
        let request = URLRequest(url: url)
        
        let delegate = SessionDelegate(with: expectation(description: "\(urlString): Connect"))
        let task = delegate.runWebSocketTask(with: request, timeoutInterval: 4, protocols: ["chatbot", "IRC", "BulletinBoard"])
        
        DispatchQueue.global(qos: .default).asyncAfter(wallDeadline: .now() + 1) {
            task.cancel(with: .normalClosure, reason: "BuhBye".data(using: .utf8))
        }
        
        await fulfillment(of: [delegate.expectation], timeout: 50)
        
        let callbacks = [ "urlSession(_:webSocketTask:didOpenWithProtocol:)",
                          "urlSession(_:webSocketTask:didCloseWith:reason:)",
                          "urlSession(_:task:didCompleteWithError:)" ]
        XCTAssertEqual(delegate.callbacks.count, callbacks.count)
        XCTAssertEqual(delegate.callbacks, callbacks, "Callbacks for \(#function)")
        
        XCTAssertEqual(task.closeCode, .normalClosure)
        XCTAssertEqual(task.closeReason, "BuhBye".data(using: .utf8))
    }
    
    func test_webSocketAbruptClose() async throws {
        guard #available(macOS 12, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return }
        guard URLSessionWebSocketTask.supportsWebSockets else {
            print("libcurl lacks WebSockets support, skipping \(#function)")
            return
        }

        let urlString = "ws://127.0.0.1:\(TestURLSession.serverPort)/web-socket/abrupt-close"
        let url = try XCTUnwrap(URL(string: urlString))
        let request = URLRequest(url: url)
        
        let delegate = SessionDelegate(with: expectation(description: "\(urlString): Connect"))
        let task = delegate.runWebSocketTask(with: request, timeoutInterval: 4)
        
        do {
            _ = try await task.receive()
            XCTFail("Expected to throw when server closes connection")
        } catch {
            let urlError = try XCTUnwrap(error as? URLError)
            XCTAssertEqual(urlError._nsError.code, NSURLErrorBadServerResponse)
        }

        await fulfillment(of: [delegate.expectation], timeout: 50)

        do {
            _ = try await task.receive()
            XCTFail("Expected to throw when receiving on closed connection")
        } catch {
            let urlError = try XCTUnwrap(error as? URLError)
            XCTAssertEqual(urlError._nsError.code, NSURLErrorBadServerResponse)
        }

        let callbacks = [ "urlSession(_:task:didCompleteWithError:)" ]
        XCTAssertEqual(delegate.callbacks.count, callbacks.count)
        XCTAssertEqual(delegate.callbacks, callbacks, "Callbacks for \(#function)")
        
        XCTAssertEqual(task.closeCode, .invalid)
        XCTAssertEqual(task.closeReason, nil)
    }

    func test_webSocketSemiAbruptClose() async throws {
        guard #available(macOS 12, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return }
        guard URLSessionWebSocketTask.supportsWebSockets else {
            print("libcurl lacks WebSockets support, skipping \(#function)")
            return
        }

        let urlString = "ws://127.0.0.1:\(TestURLSession.serverPort)/web-socket/semi-abrupt-close"
        let url = try XCTUnwrap(URL(string: urlString))
        let request = URLRequest(url: url)
        
        let delegate = SessionDelegate(with: expectation(description: "\(urlString): Connect"))
        let task = delegate.runWebSocketTask(with: request, timeoutInterval: 4)
        
        do {
            _ = try await task.receive()
            XCTFail("Expected to throw when server closes connection")
        } catch {
            let urlError = try XCTUnwrap(error as? URLError)
            XCTAssertEqual(urlError._nsError.code, NSURLErrorNetworkConnectionLost)
        }

        await fulfillment(of: [delegate.expectation], timeout: 50)

        do {
            _ = try await task.receive()
            XCTFail("Expected to throw when receiving on closed connection")
        } catch {
            let urlError = try XCTUnwrap(error as? URLError)
            XCTAssertEqual(urlError._nsError.code, NSURLErrorNetworkConnectionLost)
        }

        let callbacks = [ "urlSession(_:webSocketTask:didOpenWithProtocol:)",
                          "urlSession(_:webSocketTask:didCloseWith:reason:)",
                          "urlSession(_:task:didCompleteWithError:)" ]
        XCTAssertEqual(delegate.callbacks.count, callbacks.count)
        XCTAssertEqual(delegate.callbacks, callbacks, "Callbacks for \(#function)")
        
        XCTAssertEqual(task.closeCode, .normalClosure)
        XCTAssertEqual(task.closeReason, nil)
    }
#endif
}

class SharedDelegate: NSObject, @unchecked Sendable {
    init(dataCompletionExpectation: XCTestExpectation!) {
        self.dataCompletionExpectation = dataCompletionExpectation
    }
    
    let dataCompletionExpectation: XCTestExpectation
}

extension SharedDelegate: URLSessionDataDelegate {
    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        dataCompletionExpectation.fulfill()
    }
}

extension SharedDelegate: URLSessionDownloadDelegate {
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    }
}


// Sendable note: Access to ivars is essentially serialized by the XCTestExpectation. It would be better to do it with a lock, but this is sufficient for now.
class SessionDelegate: NSObject, URLSessionDelegate, URLSessionWebSocketDelegate, @unchecked Sendable {
    var expectation: XCTestExpectation! = nil
    var session: URLSession! = nil
    var task: URLSessionTask! = nil
    var cancelExpectation: XCTestExpectation? = nil
    var invalidateExpectation: XCTestExpectation? = nil

    // Callbacks
    typealias ChallengeHandler = (URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?)
    var challengeHandler: ChallengeHandler? = nil

    typealias RedirectionHandler = (HTTPURLResponse, URLRequest, @escaping (URLRequest?) -> Void) -> Void
    var redirectionHandler: RedirectionHandler? = nil

    typealias NewBodyStreamHandler = (@escaping (InputStream?) -> Void) -> Void
    var newBodyStreamHandler: NewBodyStreamHandler? = nil


    private(set) var receivedData: Data?
    private(set) var error: Error?
    private(set) var response: URLResponse?
    private(set) var redirectionRequest: URLRequest?
    private(set) var redirectionResponse: HTTPURLResponse?
    private(set) var totalBytesSent: Int64 = 0
    private(set) var callbacks: [String] = []
    private(set) var authenticationChallenges: [URLAuthenticationChallenge] = []


    init(with expectation: XCTestExpectation) {
        self.expectation = expectation
    }

    override init() {
        invalidateExpectation = nil
        super.init()
    }

    init(invalidateExpectation: XCTestExpectation) {
        self.invalidateExpectation = invalidateExpectation
    }

    func run(with url: URL, timeoutInterval: Double = 3) {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = timeoutInterval
        session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
        task = session.dataTask(with: url)
        task.resume()
    }

    func run(with request: URLRequest, timeoutInterval: Double = 3) {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = timeoutInterval
        session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
        task = session.dataTask(with: request)
        task.resume()
    }

    func runUploadTask(with request: URLRequest, timeoutInterval: Double = 3) {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = timeoutInterval
        session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
        task = session.uploadTask(withStreamedRequest: request)
        task.resume()
    }
    
    func runWebSocketTask(with request: URLRequest, timeoutInterval: Double = 3, protocols: [String] = []) -> URLSessionWebSocketTask {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = timeoutInterval
        session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
        let webSocketTask: URLSessionWebSocketTask
        if protocols.isEmpty {
            webSocketTask = session.webSocketTask(with: request)
        } else {
            webSocketTask = session.webSocketTask(with: request.url!, protocols: protocols)
        }
        task = webSocketTask
        task.resume()
        return webSocketTask
    }
        
    func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
        callbacks.append(#function)
        self.error = error
        invalidateExpectation?.fulfill()
    }

    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        callbacks.append(#function)
    }
    
    func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) {
        callbacks.append(#function)
    }
    func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {
        callbacks.append(#function)
    }
}

extension SessionDelegate: URLSessionTaskDelegate {

    public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        callbacks.append(#function)
        self.error = error
        expectation.fulfill()
    }

    public func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
        if callbacks.last != #function {
            callbacks.append(#function)
        }
        self.totalBytesSent = totalBytesSent
    }

    // New Body Stream
    public func urlSession(_ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) {
        callbacks.append(#function)

        if let handler = newBodyStreamHandler {
            handler(completionHandler)
        }
    }

    // HTTP Authentication Challenge
    func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        callbacks.append(#function)
        authenticationChallenges.append(challenge)

        if let handler = challengeHandler {
            let (disposition, credentials) = handler(challenge)
            completionHandler(disposition, credentials)
        }
    }

    // HTTP Redirect
    public func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
        callbacks.append(#function)
        redirectionRequest = request
        redirectionResponse = response

        if let handler = redirectionHandler {
            handler(response, request, completionHandler)
        } else {
            completionHandler(request)
        }
    }
}

extension SessionDelegate: URLSessionDataDelegate {

    public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        if callbacks.last != #function {
            callbacks.append(#function)
        }
        if receivedData == nil {
            receivedData = data
        } else {
            receivedData!.append(data)
        }
    }


    public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
        callbacks.append(#function)

        self.response = response
        completionHandler(.allow)
    }
}

// Sendable note: Access to ivars is essentially serialized by the XCTestExpectation. It would be better to do it with a lock, but this is sufficient for now.
class DataTask : NSObject, @unchecked Sendable {
    let syncQ = dispatchQueueMake("org.swift.TestFoundation.TestURLSession.DataTask.syncQ")
    let dataTaskExpectation: XCTestExpectation!
    let protocols: [AnyClass]?

    /* all the following var _XYZ need to be synchronized on syncQ.
       We can't just assert that we're on main thread here as we're modified in the URLSessionDataDelegate extension
       for DataTask
     */
    var _capital = "unknown"
    var capital: String {
        get {
            return self.syncQ.sync { self._capital }
        }
        set {
            self.syncQ.sync { self._capital = newValue }
        }
    }
    var _session: URLSession! = nil
    var session: URLSession! {
        get {
            return self.syncQ.sync { self._session }
        }
        set {
            self.syncQ.sync { self._session = newValue }
        }
    }
    var _task: URLSessionDataTask! = nil
    var task: URLSessionDataTask! {
        get {
            return self.syncQ.sync { self._task }
        }
        set {
            self.syncQ.sync { self._task = newValue }
        }
    }
    var _cancelExpectation: XCTestExpectation?
    var cancelExpectation: XCTestExpectation? {
        get {
            return self.syncQ.sync { self._cancelExpectation }
        }
        set {
            self.syncQ.sync { self._cancelExpectation = newValue }
        }
    }
    var _responseReceivedExpectation: XCTestExpectation?
    var responseReceivedExpectation: XCTestExpectation? {
        get {
            return self.syncQ.sync { self._responseReceivedExpectation }
        }
        set {
            self.syncQ.sync { self._responseReceivedExpectation = newValue }
        }
    }
    
    private var _error = false
    public var error: Bool {
        get {
            return self.syncQ.sync { self._error }
        }
        set {
            self.syncQ.sync { self._error = newValue }
        }
    }
    
    init(with expectation: XCTestExpectation, protocolClasses: [AnyClass]? = nil) {
        dataTaskExpectation = expectation
        protocols = protocolClasses
    }
    
    func run(with request: URLRequest) {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 8
        if let customProtocols = protocols {
            config.protocolClasses = customProtocols
        }
        session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
        task = session.dataTask(with: request)
        task.resume()
    }
    
    func run(with url: URL) {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 8
        if let customProtocols = protocols {
            config.protocolClasses = customProtocols
        }
        session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
        task = session.dataTask(with: url)
        task.resume()
    }
    
    func cancel() {
        task.cancel()
    }
}

extension DataTask : URLSessionDataDelegate {
    public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        capital = String(data: data, encoding: .utf8)!
    }

    public func urlSession(_ session: URLSession,
                    dataTask: URLSessionDataTask,
                    didReceive response: URLResponse,
                    completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
        if let expectation = responseReceivedExpectation {
            expectation.fulfill()
        }
        completionHandler(.allow)
    }
}

extension DataTask : URLSessionTaskDelegate {
    public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        dataTaskExpectation.fulfill()
        guard (error as? URLError) != nil else { return }
        if let cancellation = cancelExpectation {
            cancellation.fulfill()
        }
        self.error = true
    }

    public func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge:
        URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition,
        URLCredential?) -> Void) {
        completionHandler(.useCredential, URLCredential(user: "user", password: "passwd", persistence: .none))
    }
}

// Sendable note: Access to ivars is essentially serialized by the XCTestExpectation. It would be better to do it with a lock, but this is sufficient for now.
class DownloadTask : NSObject, @unchecked Sendable {
    var totalBytesWritten: Int64 = 0
    var didDownloadExpectation: XCTestExpectation?
    let didCompleteExpectation: XCTestExpectation
    var session: URLSession! = nil
    var task: URLSessionDownloadTask! = nil
    var errorExpectation: ((Error) -> Void)?
    weak var testCase: XCTestCase?
    var expectationsDescription: String
    
    init(testCase: XCTestCase, description: String) {
        self.expectationsDescription = description
        self.testCase = testCase
        self.didCompleteExpectation = testCase.expectation(description: "Did complete \(description)")
    }
    
    private func makeDownloadExpectation() {
        guard didDownloadExpectation == nil else { return }
        self.didDownloadExpectation = testCase!.expectation(description: "Did finish download: \(description)")
        self.testCase = nil // No need for it any more here.
    }
    
    func run(with url: URL) {
        makeDownloadExpectation()
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 8
        session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
        task = session.downloadTask(with: url)
        task.resume()
    }
    
    func run(with urlRequest: URLRequest) {
        makeDownloadExpectation()
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 8
        session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
        task = session.downloadTask(with: urlRequest)
        task.resume()
    }
    
    struct Configuration {
        var task: URLSessionDownloadTask
        var errorExpectation: ((Error) -> Void)?
    }
    
    func run(configuration: (URLSession) -> Configuration) {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 8
        session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
        let taskConfiguration = configuration(session)
        
        task = taskConfiguration.task
        errorExpectation = taskConfiguration.errorExpectation
        if errorExpectation == nil {
            makeDownloadExpectation()
        }
        task.resume()
    }
}

extension DownloadTask : URLSessionDownloadDelegate {
    
    public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64,
                           totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) -> Void {
        self.totalBytesWritten = totalBytesWritten
    }
    
    public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        defer { didDownloadExpectation?.fulfill() }
        
        guard self.errorExpectation == nil else {
            XCTFail("Expected an error, but got …didFinishDownloadingTo… from download task \(downloadTask) (at \(location))")
            return
        }
        
        do {
            let attr = try FileManager.default.attributesOfItem(atPath: location.path)
            XCTAssertEqual((attr[.size]! as? NSNumber)!.int64Value, totalBytesWritten, "Size of downloaded file not equal to total bytes downloaded")
        } catch {
            XCTFail("Unable to calculate size of the downloaded file")
        }
    }
}

extension DownloadTask : URLSessionTaskDelegate {
    public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        defer { didCompleteExpectation.fulfill() }
        
        if let errorExpectation = self.errorExpectation {
            if let error = error {
                errorExpectation(error)
            } else {
                XCTFail("Expected an error, but got a completion without error from download task \(task)")
            }
        } else {
            guard let e = error as? URLError else { return }
            XCTAssertEqual(e.code, .timedOut, "Unexpected error code")
        }
    }
}

class FailFastProtocol: URLProtocol {
    enum Error: Swift.Error {
    case fastError
    }

    override class func canInit(with request: URLRequest) -> Bool {
        return request.url?.scheme == "failfast"
    }

    override class func canonicalRequest(for request: URLRequest) -> URLRequest {
        return request
    }

    override class func canInit(with task: URLSessionTask) -> Bool {
        guard let request = task.currentRequest else { return false }
        return canInit(with: request)
    }

    override func startLoading() {
        client?.urlProtocol(self, didFailWithError: Error.fastError)
    }

    override func stopLoading() {
        // Intentionally blank
    }
}

// Sendable note: Access to ivars is essentially serialized by the XCTestExpectation. It would be better to do it with a lock, but this is sufficient for now.
class HTTPRedirectionDataTask: NSObject, @unchecked Sendable {
    let dataTaskExpectation: XCTestExpectation!
    var session: URLSession! = nil
    var task: URLSessionDataTask! = nil
    var cancelExpectation: XCTestExpectation?
    private(set) var receivedData = Data()
    private(set) var error: Error?
    private(set) var response: URLResponse?
    private(set) var redirectionResponse: HTTPURLResponse?
    private var callbacks: [String] = []

    init(with expectation: XCTestExpectation) {
        dataTaskExpectation = expectation
    }
    
    func run(with request: URLRequest) {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 8
        session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
        task = session.dataTask(with: request)
        task.resume()
    }
    
    func run(with url: URL) {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 4
        session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
        task = session.dataTask(with: url)
        task.resume()
    }
    
    func cancel() {
        task.cancel()
    }

    var callbackCount: Int { callbacks.count }

    func callback(_ idx: Int) -> String? {
        guard idx < callbacks.count else { return nil }
        return callbacks[idx]
    }
}

extension HTTPRedirectionDataTask: URLSessionDataDelegate {

    public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        if callbacks.last != #function {
            callbacks.append(#function)
        }
        receivedData.append(data)
    }

    public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
        callbacks.append(#function)

        self.response = response
        completionHandler(.allow)
    }
}

extension HTTPRedirectionDataTask: URLSessionTaskDelegate {
    public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        callbacks.append(#function)
        dataTaskExpectation.fulfill()

        if let cancellation = cancelExpectation {
            cancellation.fulfill()
        }
        self.error = error
    }
    
    public func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
        callbacks.append(#function)
        redirectionResponse = response

        if let url = response.url, url.path.hasSuffix("/redirect-with-default-port") {
            XCTAssertEqual(request.url?.absoluteString, "http://127.0.0.1/redirected-with-default-port")
            // Don't follow the redirect as the test server is not running on port 80
            completionHandler(nil)
        } else {
            completionHandler(request)
        }
    }
}

// Sendable note: Access to ivars is essentially serialized by the XCTestExpectation. It would be better to do it with a lock, but this is sufficient for now.
class HTTPUploadDelegate: NSObject, @unchecked Sendable {
    private(set) var callbacks: [String] = []

    var uploadCompletedExpectation: XCTestExpectation!
    var totalBytesSent: Int64 = 0
}

extension HTTPUploadDelegate: URLSessionTaskDelegate {
    public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        callbacks.append(#function)
        uploadCompletedExpectation.fulfill()
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
        if callbacks.last != #function {
            callbacks.append(#function)
        }
        self.totalBytesSent = totalBytesSent
    }
}

extension HTTPUploadDelegate: URLSessionDataDelegate {
    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        callbacks.append(#function)
    }
}