1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
|
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QtCore/QCryptographicHash>
#include <QtCore/QDataStream>
#include <QtCore/QUrl>
#include <QtCore/QEventLoop>
#include <QtCore/QFile>
#include <QtCore/QSharedPointer>
#include <QtCore/QTemporaryFile>
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>
#include <QtNetwork/QLocalSocket>
#include <QtNetwork/QLocalServer>
#include <QtNetwork/QHostInfo>
#include <QtNetwork/QFtp>
#include <QtNetwork/QAbstractNetworkCache>
#include <QtNetwork/qauthenticator.h>
#include <QtNetwork/qnetworkaccessmanager.h>
#include <QtNetwork/qnetworkrequest.h>
#include <QtNetwork/qnetworkreply.h>
#include <QtNetwork/qnetworkcookie.h>
#ifndef QT_NO_OPENSSL
#include <QtNetwork/qsslerror.h>
#include <QtNetwork/qsslconfiguration.h>
#endif
#include <time.h>
#include "private/qnetworkaccessmanager_p.h"
#ifdef Q_OS_SYMBIAN
#define SRCDIR "."
#endif
#include "../network-settings.h"
Q_DECLARE_METATYPE(QNetworkReply*)
Q_DECLARE_METATYPE(QAuthenticator*)
Q_DECLARE_METATYPE(QNetworkProxy)
Q_DECLARE_METATYPE(QNetworkProxyQuery)
Q_DECLARE_METATYPE(QList<QNetworkProxy>)
Q_DECLARE_METATYPE(QNetworkReply::NetworkError)
Q_DECLARE_METATYPE(QBuffer*)
class QNetworkReplyPtr: public QSharedPointer<QNetworkReply>
{
public:
inline QNetworkReplyPtr(QNetworkReply *ptr = 0)
: QSharedPointer<QNetworkReply>(ptr)
{ }
inline operator QNetworkReply *() const { return data(); }
};
class MyCookieJar;
class tst_QNetworkReply: public QObject
{
Q_OBJECT
struct ProxyData {
ProxyData(const QNetworkProxy &p, const QByteArray &t, bool auth)
: tag(t), proxy(p), requiresAuthentication(auth)
{ }
QByteArray tag;
QNetworkProxy proxy;
bool requiresAuthentication;
};
QEventLoop *loop;
enum RunSimpleRequestReturn { Timeout = 0, Success, Failure };
int returnCode;
QString testFileName;
#if !defined Q_OS_WIN
QString wronlyFileName;
#endif
QString uniqueExtension;
QList<ProxyData> proxies;
QNetworkAccessManager manager;
MyCookieJar *cookieJar;
#ifndef QT_NO_OPENSSL
QSslConfiguration storedSslConfiguration;
QList<QSslError> storedExpectedSslErrors;
#endif
public:
tst_QNetworkReply();
~tst_QNetworkReply();
QString runSimpleRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request,
QNetworkReplyPtr &reply, const QByteArray &data = QByteArray());
QString runCustomRequest(const QNetworkRequest &request, QNetworkReplyPtr &reply,
const QByteArray &verb, QIODevice *data);
public Q_SLOTS:
void finished();
void gotError();
void authenticationRequired(QNetworkReply*,QAuthenticator*);
void proxyAuthenticationRequired(const QNetworkProxy &,QAuthenticator*);
#ifndef QT_NO_OPENSSL
void sslErrors(QNetworkReply*,const QList<QSslError> &);
void storeSslConfiguration();
void ignoreSslErrorListSlot(QNetworkReply *reply, const QList<QSslError> &);
#endif
protected Q_SLOTS:
void nestedEventLoops_slot();
private Q_SLOTS:
void init();
void cleanup();
void initTestCase();
void cleanupTestCase();
void stateChecking();
void invalidProtocol();
void getFromData_data();
void getFromData();
void getFromFile();
void getFromFileSpecial_data();
void getFromFileSpecial();
void getFromFtp_data();
void getFromFtp();
void getFromHttp_data();
void getFromHttp();
void getErrors_data();
void getErrors();
void putToFile_data();
void putToFile();
void putToFtp_data();
void putToFtp();
void putToHttp_data();
void putToHttp();
void postToHttp_data();
void postToHttp();
void deleteFromHttp_data();
void deleteFromHttp();
void putGetDeleteGetFromHttp_data();
void putGetDeleteGetFromHttp();
void sendCustomRequestToHttp_data();
void sendCustomRequestToHttp();
void ioGetFromData_data();
void ioGetFromData();
void ioGetFromFileSpecial_data();
void ioGetFromFileSpecial();
void ioGetFromFile_data();
void ioGetFromFile();
void ioGetFromFtp_data();
void ioGetFromFtp();
void ioGetFromFtpWithReuse();
void ioGetFromHttp();
void ioGetFromHttpWithReuseParallel();
void ioGetFromHttpWithReuseSequential();
void ioGetFromHttpWithAuth();
void ioGetFromHttpWithProxyAuth();
void ioGetFromHttpWithSocksProxy();
#ifndef QT_NO_OPENSSL
void ioGetFromHttpsWithSslErrors();
void ioGetFromHttpsWithIgnoreSslErrors();
void ioGetFromHttpsWithSslHandshakeError();
#endif
void ioGetFromHttpBrokenServer_data();
void ioGetFromHttpBrokenServer();
void ioGetFromHttpStatus100_data();
void ioGetFromHttpStatus100();
void ioGetFromHttpNoHeaders_data();
void ioGetFromHttpNoHeaders();
void ioGetFromHttpWithCache_data();
void ioGetFromHttpWithCache();
void ioGetWithManyProxies_data();
void ioGetWithManyProxies();
void ioPutToFileFromFile_data();
void ioPutToFileFromFile();
void ioPutToFileFromSocket_data();
void ioPutToFileFromSocket();
void ioPutToFileFromLocalSocket_data();
void ioPutToFileFromLocalSocket();
void ioPutToFileFromProcess_data();
void ioPutToFileFromProcess();
void ioPutToFtpFromFile_data();
void ioPutToFtpFromFile();
void ioPutToHttpFromFile_data();
void ioPutToHttpFromFile();
void ioPostToHttpFromFile_data();
void ioPostToHttpFromFile();
void ioPostToHttpFromSocket_data();
void ioPostToHttpFromSocket();
void ioPostToHttpFromMiddleOfFileToEnd();
void ioPostToHttpFromMiddleOfFileFiveBytes();
void ioPostToHttpFromMiddleOfQBufferFiveBytes();
void ioPostToHttpNoBufferFlag();
void ioPostToHttpUploadProgress();
void ioPostToHttpEmptyUploadProgress();
void lastModifiedHeaderForFile();
void lastModifiedHeaderForHttp();
void httpCanReadLine();
void rateControl_data();
void rateControl();
void downloadProgress_data();
void downloadProgress();
void uploadProgress_data();
void uploadProgress();
void chaining_data();
void chaining();
void receiveCookiesFromHttp_data();
void receiveCookiesFromHttp();
void sendCookies_data();
void sendCookies();
void nestedEventLoops();
void httpProxyCommands_data();
void httpProxyCommands();
void proxyChange();
void authorizationError_data();
void authorizationError();
void httpConnectionCount();
void httpReUsingConnectionSequential_data();
void httpReUsingConnectionSequential();
void httpReUsingConnectionFromFinishedSlot_data();
void httpReUsingConnectionFromFinishedSlot();
void httpRecursiveCreation();
#ifndef QT_NO_OPENSSL
void ioPostToHttpsUploadProgress();
void ignoreSslErrorsList_data();
void ignoreSslErrorsList();
void ignoreSslErrorsListWithSlot_data();
void ignoreSslErrorsListWithSlot();
#endif
// NOTE: This test must be last!
void parentingRepliesToTheApp();
};
QT_BEGIN_NAMESPACE
namespace QTest {
template<>
char *toString(const QNetworkReply::NetworkError& code)
{
const QMetaObject *mo = &QNetworkReply::staticMetaObject;
int index = mo->indexOfEnumerator("NetworkError");
if (index == -1)
return qstrdup("");
QMetaEnum qme = mo->enumerator(index);
return qstrdup(qme.valueToKey(code));
}
template<>
char *toString(const QNetworkCookie &cookie)
{
return qstrdup(cookie.toRawForm());
}
template<>
char *toString(const QList<QNetworkCookie> &list)
{
QString result = "QList(";
bool first = true;
foreach (QNetworkCookie cookie, list) {
if (!first)
result += ", ";
first = false;
result += QString::fromLatin1("QNetworkCookie(%1)").arg(QLatin1String(cookie.toRawForm()));
}
return qstrdup(result.append(')').toLocal8Bit());
}
}
QT_END_NAMESPACE
#define RUN_REQUEST(call) \
do { \
QString errorMsg = call; \
if (!errorMsg.isEmpty()) \
QFAIL(qPrintable(errorMsg)); \
} while (0);
// Does not work for POST/PUT!
class MiniHttpServer: public QTcpServer
{
Q_OBJECT
public:
QTcpSocket *client; // always the last one that was received
QByteArray dataToTransmit;
QByteArray receivedData;
bool doClose;
bool multiple;
int totalConnections;
MiniHttpServer(const QByteArray &data) : client(0), dataToTransmit(data), doClose(true), multiple(false), totalConnections(0)
{
listen();
connect(this, SIGNAL(newConnection()), this, SLOT(doAccept()));
}
public slots:
void doAccept()
{
client = nextPendingConnection();
client->setParent(this);
++totalConnections;
connect(client, SIGNAL(readyRead()), this, SLOT(readyReadSlot()));
}
void readyReadSlot()
{
receivedData += client->readAll();
int doubleEndlPos = receivedData.indexOf("\r\n\r\n");
if (doubleEndlPos != -1) {
// multiple requests incoming. remove the bytes of the current one
if (multiple)
receivedData.remove(0, doubleEndlPos+4);
client->write(dataToTransmit);
if (doClose) {
client->disconnectFromHost();
disconnect(client, 0, this, 0);
client = 0;
}
}
}
};
class MyCookieJar: public QNetworkCookieJar
{
public:
inline QList<QNetworkCookie> allCookies() const
{ return QNetworkCookieJar::allCookies(); }
inline void setAllCookies(const QList<QNetworkCookie> &cookieList)
{ QNetworkCookieJar::setAllCookies(cookieList); }
};
class MyProxyFactory: public QNetworkProxyFactory
{
public:
int callCount;
QList<QNetworkProxy> toReturn;
QNetworkProxyQuery lastQuery;
inline MyProxyFactory() { clear(); }
inline void clear()
{
callCount = 0;
toReturn = QList<QNetworkProxy>() << QNetworkProxy::DefaultProxy;
lastQuery = QNetworkProxyQuery();
}
virtual QList<QNetworkProxy> queryProxy(const QNetworkProxyQuery &query)
{
lastQuery = query;
++callCount;
return toReturn;
}
};
class MyMemoryCache: public QAbstractNetworkCache
{
public:
typedef QPair<QNetworkCacheMetaData, QByteArray> CachedContent;
typedef QHash<QByteArray, CachedContent> CacheData;
CacheData cache;
MyMemoryCache(QObject *parent) : QAbstractNetworkCache(parent) {}
QNetworkCacheMetaData metaData(const QUrl &url)
{
return cache.value(url.toEncoded()).first;
}
void updateMetaData(const QNetworkCacheMetaData &metaData)
{
cache[metaData.url().toEncoded()].first = metaData;
}
QIODevice *data(const QUrl &url)
{
CacheData::ConstIterator it = cache.find(url.toEncoded());
if (it == cache.constEnd())
return 0;
QBuffer *io = new QBuffer(this);
io->setData(it->second);
io->open(QIODevice::ReadOnly);
io->seek(0);
return io;
}
bool remove(const QUrl &url)
{
cache.remove(url.toEncoded());
return true;
}
qint64 cacheSize() const
{
qint64 total = 0;
foreach (const CachedContent &entry, cache)
total += entry.second.size();
return total;
}
QIODevice *prepare(const QNetworkCacheMetaData &)
{ Q_ASSERT(0 && "Should not have tried to add to the cache"); return 0; }
void insert(QIODevice *)
{ Q_ASSERT(0 && "Should not have tried to add to the cache"); }
void clear() { cache.clear(); }
};
Q_DECLARE_METATYPE(MyMemoryCache::CachedContent)
Q_DECLARE_METATYPE(MyMemoryCache::CacheData)
class DataReader: public QObject
{
Q_OBJECT
public:
qint64 totalBytes;
QByteArray data;
QIODevice *device;
bool accumulate;
DataReader(QIODevice *dev, bool acc = true) : totalBytes(0), device(dev), accumulate(acc)
{
connect(device, SIGNAL(readyRead()), SLOT(doRead()));
}
public slots:
void doRead()
{
QByteArray buffer;
buffer.resize(device->bytesAvailable());
qint64 bytesRead = device->read(buffer.data(), device->bytesAvailable());
if (bytesRead == -1) {
QTestEventLoop::instance().exitLoop();
return;
}
buffer.truncate(bytesRead);
totalBytes += bytesRead;
if (accumulate)
data += buffer;
}
};
class SocketPair: public QObject
{
Q_OBJECT
public:
QIODevice *endPoints[2];
SocketPair(QObject *parent = 0)
: QObject(parent)
{
endPoints[0] = endPoints[1] = 0;
}
bool create()
{
QTcpServer server;
server.listen();
QTcpSocket *active = new QTcpSocket(this);
active->connectToHost("127.0.0.1", server.serverPort());
#ifndef Q_OS_SYMBIAN
// need more time as working with embedded
// device and testing from emualtor
// things tend to get slower
if (!active->waitForConnected(1000))
return false;
if (!server.waitForNewConnection(1000))
return false;
#else
if (!active->waitForConnected(100))
return false;
if (!server.waitForNewConnection(100))
return false;
#endif
QTcpSocket *passive = server.nextPendingConnection();
passive->setParent(this);
endPoints[0] = active;
endPoints[1] = passive;
return true;
}
};
class FastSender: public QThread
{
Q_OBJECT
QSemaphore ready;
qint64 wantedSize;
int port;
public:
int transferRate;
QWaitCondition cond;
FastSender(qint64 size)
: wantedSize(size), port(-1), transferRate(-1)
{
start();
ready.acquire();
}
inline int serverPort() const { return port; }
protected:
void run()
{
QTcpServer server;
server.listen();
port = server.serverPort();
ready.release();
server.waitForNewConnection(-1);
QTcpSocket *client = server.nextPendingConnection();
// get the "request" packet
if (!client->waitForReadyRead(2000)) {
qDebug() << client->error() << "waiting for \"request\" packet";
return;
}
client->readAll(); // we're not interested in the actual contents
enum { BlockSize = 256 };
QByteArray data;
{
QDataStream stream(&data, QIODevice::WriteOnly);
stream << QVariantMap() << QByteArray(BlockSize, 'a');
}
qint32 size = data.size();
// write a bunch of bytes to fill up the buffers
do {
client->write((char*)&size, sizeof size);
client->write(data);
while (client->bytesToWrite() > 0)
if (!client->waitForBytesWritten(0))
break;
} while (client->bytesToWrite() == 0);
// the kernel buffer is full
// clean up QAbstractSocket's residue:
while (client->bytesToWrite() > 0)
if (!client->waitForBytesWritten(2000)) {
qDebug() << client->error() << "cleaning up residue";
return;
}
// now write in "blocking mode"
QTime timer;
timer.start();
qint64 totalBytes = 0;
while (totalBytes < wantedSize) {
int bytesToWrite = wantedSize - totalBytes;
Q_ASSERT(bytesToWrite);
if (bytesToWrite > BlockSize) {
bytesToWrite = BlockSize;
} else {
QDataStream stream(&data, QIODevice::WriteOnly);
stream << QVariantMap() << QByteArray(bytesToWrite, 'b');
}
size = data.size();
client->write((char*)&size, sizeof size);
client->write(data);
totalBytes += bytesToWrite;
while (client->bytesToWrite() > 0)
if (!client->waitForBytesWritten(2000)) {
qDebug() << client->error() << "blocking write";
return;
}
// qDebug() << bytesToWrite << "bytes written now;"
// << totalBytes << "total ("
// << totalBytes*100/wantedSize << "% complete);"
// << timer.elapsed() << "ms elapsed";
}
transferRate = totalBytes * 1000 / timer.elapsed();
qDebug() << "flushed" << totalBytes << "bytes in" << timer.elapsed() << "ms: rate =" << transferRate;
// write a "close connection" packet
{
QDataStream stream(&data, QIODevice::WriteOnly);
stream << QVariantMap() << QByteArray();
}
size = data.size();
client->write((char*)&size, sizeof size);
client->write(data);
}
};
class RateControlledReader: public QObject
{
Q_OBJECT
QIODevice *device;
int bytesToRead;
int interval;
public:
qint64 totalBytesRead;
RateControlledReader(QIODevice *dev, int kbPerSec)
: device(dev), totalBytesRead(0)
{
// determine how often we have to wake up
bytesToRead = kbPerSec * 1024 / 20;
interval = 50;
qDebug() << "RateControlledReader: going to read" << bytesToRead
<< "bytes every" << interval << "ms";
qDebug() << "actual rate will be"
<< (bytesToRead * 1000 / interval) << "bytes/sec (wanted"
<< kbPerSec * 1024 << "bytes/sec)";
startTimer(interval);
}
protected:
void timerEvent(QTimerEvent *)
{
qint64 bytesRead = 0;
QTime stopWatch;
stopWatch.start();
do {
if (device->bytesAvailable() == 0)
if (stopWatch.elapsed() > 10 || !device->waitForReadyRead(5))
break;
QByteArray data = device->read(bytesToRead - bytesRead);
bytesRead += data.size();
} while (bytesRead < bytesToRead);// && stopWatch.elapsed() < interval/4);
totalBytesRead += bytesRead;
if (bytesRead < bytesToRead)
qWarning() << bytesToRead - bytesRead << "bytes not read";
}
};
tst_QNetworkReply::tst_QNetworkReply()
{
Q_SET_DEFAULT_IAP
testFileName = QDir::currentPath() + "/testfile";
#ifndef Q_OS_WINCE
uniqueExtension = QString("%1%2%3").arg((qulonglong)this).arg(rand()).arg((qulonglong)time(0));
#else
uniqueExtension = QString("%1%2").arg((qulonglong)this).arg(rand());
#endif
cookieJar = new MyCookieJar;
manager.setCookieJar(cookieJar);
QHostInfo hostInfo = QHostInfo::fromName(QtNetworkSettings::serverName());
proxies << ProxyData(QNetworkProxy::NoProxy, "", false);
if (hostInfo.error() == QHostInfo::NoError && !hostInfo.addresses().isEmpty()) {
QString proxyserver = hostInfo.addresses().first().toString();
proxies << ProxyData(QNetworkProxy(QNetworkProxy::HttpProxy, proxyserver, 3128), "+proxy", false)
<< ProxyData(QNetworkProxy(QNetworkProxy::HttpProxy, proxyserver, 3129), "+proxyauth", true)
// currently unsupported
// << ProxyData(QNetworkProxy(QNetworkProxy::HttpProxy, proxyserver, 3130), "+proxyauth-ntlm", true);
<< ProxyData(QNetworkProxy(QNetworkProxy::Socks5Proxy, proxyserver, 1080), "+socks", false)
<< ProxyData(QNetworkProxy(QNetworkProxy::Socks5Proxy, proxyserver, 1081), "+socksauth", true);
} else {
printf("==================================================================\n");
printf("Proxy could not be looked up. No proxy will be used while testing!\n");
printf("==================================================================\n");
}
}
tst_QNetworkReply::~tst_QNetworkReply()
{
}
void tst_QNetworkReply::authenticationRequired(QNetworkReply*, QAuthenticator* auth)
{
auth->setUser("httptest");
auth->setPassword("httptest");
}
void tst_QNetworkReply::proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator* auth)
{
auth->setUser("qsockstest");
auth->setPassword("password");
}
#ifndef QT_NO_OPENSSL
void tst_QNetworkReply::sslErrors(QNetworkReply *reply, const QList<QSslError> &errors)
{
reply->ignoreSslErrors();
QVERIFY(!errors.isEmpty());
QVERIFY(!reply->sslConfiguration().isNull());
}
void tst_QNetworkReply::storeSslConfiguration()
{
storedSslConfiguration = QSslConfiguration();
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
if (reply)
storedSslConfiguration = reply->sslConfiguration();
}
#endif
QString tst_QNetworkReply::runSimpleRequest(QNetworkAccessManager::Operation op,
const QNetworkRequest &request,
QNetworkReplyPtr &reply,
const QByteArray &data)
{
switch (op) {
case QNetworkAccessManager::HeadOperation:
reply = manager.head(request);
break;
case QNetworkAccessManager::GetOperation:
reply = manager.get(request);
break;
case QNetworkAccessManager::PutOperation:
reply = manager.put(request, data);
break;
case QNetworkAccessManager::PostOperation:
reply = manager.post(request, data);
break;
case QNetworkAccessManager::DeleteOperation:
reply = manager.deleteResource(request);
break;
default:
Q_ASSERT_X(false, "tst_QNetworkReply", "Invalid/unknown operation requested");
}
reply->setParent(this);
connect(reply, SIGNAL(finished()), SLOT(finished()));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(gotError()));
returnCode = Timeout;
loop = new QEventLoop;
QTimer::singleShot(20000, loop, SLOT(quit()));
int code = returnCode == Timeout ? loop->exec() : returnCode;
delete loop;
loop = 0;
switch (code) {
case Failure:
return "Request failed: " + reply->errorString();
case Timeout:
return "Network timeout";
}
return QString();
}
QString tst_QNetworkReply::runCustomRequest(const QNetworkRequest &request,
QNetworkReplyPtr &reply,
const QByteArray &verb,
QIODevice *data)
{
reply = manager.sendCustomRequest(request, verb, data);
reply->setParent(this);
connect(reply, SIGNAL(finished()), SLOT(finished()));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(gotError()));
returnCode = Timeout;
loop = new QEventLoop;
QTimer::singleShot(20000, loop, SLOT(quit()));
int code = returnCode == Timeout ? loop->exec() : returnCode;
delete loop;
loop = 0;
switch (code) {
case Failure:
return "Request failed: " + reply->errorString();
case Timeout:
return "Network timeout";
}
return QString();
}
void tst_QNetworkReply::finished()
{
loop->exit(returnCode = Success);
}
void tst_QNetworkReply::gotError()
{
loop->exit(returnCode = Failure);
disconnect(QObject::sender(), SIGNAL(finished()), this, 0);
}
void tst_QNetworkReply::initTestCase()
{
#if !defined Q_OS_WIN
wronlyFileName = QDir::currentPath() + "/write-only";
QFile wr(wronlyFileName);
QVERIFY(wr.open(QIODevice::WriteOnly | QIODevice::Truncate));
wr.setPermissions(QFile::WriteOwner | QFile::WriteUser);
wr.close();
#endif
QDir::setSearchPaths("srcdir", QStringList() << SRCDIR);
}
void tst_QNetworkReply::cleanupTestCase()
{
#if !defined Q_OS_WIN
QFile::remove(wronlyFileName);
#endif
}
void tst_QNetworkReply::init()
{
cleanup();
}
void tst_QNetworkReply::cleanup()
{
QFile file(testFileName);
QVERIFY(!file.exists() || file.remove());
// clear the internal cache
QNetworkAccessManagerPrivate::clearCache(&manager);
manager.setProxy(QNetworkProxy());
manager.setCache(0);
// clear cookies
cookieJar->setAllCookies(QList<QNetworkCookie>());
}
void tst_QNetworkReply::stateChecking()
{
QUrl url = QUrl("file:///");
QNetworkRequest req(url); // you can't open this file, I know
QNetworkReplyPtr reply = manager.get(req);
QVERIFY(reply.data());
QVERIFY(reply->isOpen());
QVERIFY(reply->isReadable());
QVERIFY(!reply->isWritable());
// both behaviours are OK since we might change underlying behaviour again
if (!reply->isFinished())
QCOMPARE(reply->errorString(), QString("Unknown error"));
else
QVERIFY(!reply->errorString().isEmpty());
QCOMPARE(reply->manager(), &manager);
QCOMPARE(reply->request(), req);
QCOMPARE(int(reply->operation()), int(QNetworkAccessManager::GetOperation));
// error and not error are OK since we might change underlying behaviour again
if (!reply->isFinished())
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->url(), url);
reply->abort();
}
void tst_QNetworkReply::invalidProtocol()
{
QUrl url = QUrl::fromEncoded("not-a-known-protocol://foo/bar");
QNetworkRequest req(url);
QNetworkReplyPtr reply;
QString errorMsg = "Request failed: Protocol \"not-a-known-protocol\" is unknown";
QString result = runSimpleRequest(QNetworkAccessManager::GetOperation, req, reply);
QCOMPARE(result, errorMsg);
QCOMPARE(reply->url(), url);
QCOMPARE(reply->error(), QNetworkReply::ProtocolUnknownError);
}
void tst_QNetworkReply::getFromData_data()
{
QTest::addColumn<QString>("request");
QTest::addColumn<QByteArray>("expected");
QTest::addColumn<QString>("mimeType");
const QString defaultMimeType("text/plain;charset=US-ASCII");
//QTest::newRow("empty") << "data:" << QByteArray() << defaultMimeType;
QTest::newRow("empty2") << "data:," << QByteArray() << defaultMimeType;
QTest::newRow("just-charset_1") << "data:charset=iso-8859-1,"
<< QByteArray() << "text/plain;charset=iso-8859-1";
QTest::newRow("just-charset_2") << "data:charset = iso-8859-1 ,"
<< QByteArray() << "text/plain;charset = iso-8859-1";
//QTest::newRow("just-media") << "data:text/xml" << QByteArray() << "text/xml";
QTest::newRow("just-media2") << "data:text/xml," << QByteArray() << "text/xml";
QTest::newRow("plain_1") << "data:,foo" << QByteArray("foo") << defaultMimeType;
QTest::newRow("plain_2") << "data:text/html,Hello World" << QByteArray("Hello World")
<< "text/html";
QTest::newRow("plain_3") << "data:text/html;charset=utf-8,Hello World"
<< QByteArray("Hello World") << "text/html;charset=utf-8";
QTest::newRow("pct_1") << "data:,%3Cbody%20contentEditable%3Dtrue%3E%0D%0A"
<< QByteArray("<body contentEditable=true>\r\n") << defaultMimeType;
QTest::newRow("pct_2") << "data:text/html;charset=utf-8,%3Cbody%20contentEditable%3Dtrue%3E%0D%0A"
<< QByteArray("<body contentEditable=true>\r\n")
<< "text/html;charset=utf-8";
QTest::newRow("base64-empty_1") << "data:;base64," << QByteArray() << defaultMimeType;
QTest::newRow("base64-empty_2") << "data:charset=utf-8;base64," << QByteArray()
<< "text/plain;charset=utf-8";
QTest::newRow("base64-empty_3") << "data:text/html;charset=utf-8;base64,"
<< QByteArray() << "text/html;charset=utf-8";
QTest::newRow("base64_1") << "data:;base64,UXQgaXMgZ3JlYXQh" << QByteArray("Qt is great!")
<< defaultMimeType;
QTest::newRow("base64_2") << "data:charset=utf-8;base64,UXQgaXMgZ3JlYXQh"
<< QByteArray("Qt is great!") << "text/plain;charset=utf-8";
QTest::newRow("base64_3") << "data:text/html;charset=utf-8;base64,UXQgaXMgZ3JlYXQh"
<< QByteArray("Qt is great!") << "text/html;charset=utf-8";
QTest::newRow("pct-nul") << "data:,a%00g" << QByteArray("a\0g", 3) << defaultMimeType;
QTest::newRow("base64-nul") << "data:;base64,YQBn" << QByteArray("a\0g", 3) << defaultMimeType;
QTest::newRow("pct-nonutf8") << "data:,a%E1g" << QByteArray("a\xE1g", 3) << defaultMimeType;
QTest::newRow("base64")
<< QString::fromLatin1("data:application/xml;base64,PGUvPg==")
<< QByteArray("<e/>")
<< "application/xml";
QTest::newRow("base64, no media type")
<< QString::fromLatin1("data:;base64,PGUvPg==")
<< QByteArray("<e/>")
<< defaultMimeType;
QTest::newRow("Percent encoding")
<< QString::fromLatin1("data:application/xml,%3Ce%2F%3E")
<< QByteArray("<e/>")
<< "application/xml";
QTest::newRow("Percent encoding, no media type")
<< QString::fromLatin1("data:,%3Ce%2F%3E")
<< QByteArray("<e/>")
<< defaultMimeType;
QTest::newRow("querychars")
<< QString::fromLatin1("data:,foo?x=0&y=0")
<< QByteArray("foo?x=0&y=0")
<< defaultMimeType;
QTest::newRow("css") << "data:text/css,div%20{%20border-right:%20solid;%20}"
<< QByteArray("div { border-right: solid; }")
<< "text/css";
}
void tst_QNetworkReply::getFromData()
{
QFETCH(QString, request);
QFETCH(QByteArray, expected);
QFETCH(QString, mimeType);
QUrl url = QUrl::fromEncoded(request.toLatin1());
QNetworkRequest req(url);
QNetworkReplyPtr reply;
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::GetOperation, req, reply));
QCOMPARE(reply->url(), url);
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->header(QNetworkRequest::ContentTypeHeader).toString(), mimeType);
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), qint64(expected.size()));
QCOMPARE(reply->readAll(), expected);
}
void tst_QNetworkReply::getFromFile()
{
// create the file:
QTemporaryFile file(QDir::currentPath() + "/temp-XXXXXX");
file.setAutoRemove(true);
QVERIFY(file.open());
QNetworkRequest request(QUrl::fromLocalFile(file.fileName()));
QNetworkReplyPtr reply;
static const char fileData[] = "This is some data that is in the file.\r\n";
QByteArray data = QByteArray::fromRawData(fileData, sizeof fileData - 1);
QVERIFY(file.write(data) == data.size());
file.flush();
QCOMPARE(file.size(), qint64(data.size()));
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::GetOperation, request, reply));
QCOMPARE(reply->url(), request.url());
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), file.size());
QCOMPARE(reply->readAll(), data);
// make the file bigger
file.resize(0);
const int multiply = (128 * 1024) / (sizeof fileData - 1);
for (int i = 0; i < multiply; ++i)
file.write(fileData, sizeof fileData - 1);
file.flush();
// run again
reply = 0;
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::GetOperation, request, reply));
QCOMPARE(reply->url(), request.url());
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), file.size());
QCOMPARE(qint64(reply->readAll().size()), file.size());
}
void tst_QNetworkReply::getFromFileSpecial_data()
{
QTest::addColumn<QString>("fileName");
QTest::addColumn<QString>("url");
QTest::newRow("resource") << ":/resource" << "qrc:/resource";
QTest::newRow("search-path") << "srcdir:/rfc3252.txt" << "srcdir:/rfc3252.txt";
QTest::newRow("bigfile-path") << "srcdir:/bigfile" << "srcdir:/bigfile";
}
void tst_QNetworkReply::getFromFileSpecial()
{
QFETCH(QString, fileName);
QFETCH(QString, url);
// open the resource so we can find out its size
QFile resource(fileName);
QVERIFY(resource.open(QIODevice::ReadOnly));
QNetworkRequest request;
QNetworkReplyPtr reply;
request.setUrl(url);
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::GetOperation, request, reply));
QCOMPARE(reply->url(), request.url());
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), resource.size());
QCOMPARE(reply->readAll(), resource.readAll());
}
void tst_QNetworkReply::getFromFtp_data()
{
QTest::addColumn<QString>("referenceName");
QTest::addColumn<QString>("url");
QTest::newRow("rfc3252.txt") << SRCDIR "/rfc3252.txt" << "ftp://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt";
QTest::newRow("bigfile") << SRCDIR "/bigfile" << "ftp://" + QtNetworkSettings::serverName() + "/qtest/bigfile";
}
void tst_QNetworkReply::getFromFtp()
{
QFETCH(QString, referenceName);
QFETCH(QString, url);
QFile reference(referenceName);
QVERIFY(reference.open(QIODevice::ReadOnly));
QNetworkRequest request(url);
QNetworkReplyPtr reply;
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::GetOperation, request, reply));
QCOMPARE(reply->url(), request.url());
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), reference.size());
QCOMPARE(reply->readAll(), reference.readAll());
}
void tst_QNetworkReply::getFromHttp_data()
{
QTest::addColumn<QString>("referenceName");
QTest::addColumn<QString>("url");
QTest::newRow("success-internal") << SRCDIR "/rfc3252.txt" << "http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt";
QTest::newRow("success-external") << SRCDIR "/rfc3252.txt" << "http://www.ietf.org/rfc/rfc3252.txt";
QTest::newRow("bigfile-internal") << SRCDIR "/bigfile" << "http://" + QtNetworkSettings::serverName() + "/qtest/bigfile";
}
void tst_QNetworkReply::getFromHttp()
{
QFETCH(QString, referenceName);
QFETCH(QString, url);
QFile reference(referenceName);
QVERIFY(reference.open(QIODevice::ReadOnly));
QNetworkRequest request(url);
QNetworkReplyPtr reply;
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::GetOperation, request, reply));
QCOMPARE(reply->url(), request.url());
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QCOMPARE(reply->size(), reference.size());
// only compare when the header is set.
if (reply->header(QNetworkRequest::ContentLengthHeader).isValid())
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), reference.size());
QCOMPARE(reply->readAll(), reference.readAll());
}
void tst_QNetworkReply::getErrors_data()
{
QTest::addColumn<QString>("url");
QTest::addColumn<int>("error");
QTest::addColumn<int>("httpStatusCode");
QTest::addColumn<bool>("dataIsEmpty");
// file: errors
QTest::newRow("file-host") << "file://this-host-doesnt-exist.troll.no/foo.txt"
#if !defined Q_OS_WIN
<< int(QNetworkReply::ProtocolInvalidOperationError) << 0 << true;
#else
<< int(QNetworkReply::ContentNotFoundError) << 0 << true;
#endif
QTest::newRow("file-no-path") << "file://localhost"
<< int(QNetworkReply::ContentOperationNotPermittedError) << 0 << true;
QTest::newRow("file-is-dir") << QUrl::fromLocalFile(QDir::currentPath()).toString()
<< int(QNetworkReply::ContentOperationNotPermittedError) << 0 << true;
QTest::newRow("file-exist") << QUrl::fromLocalFile(QDir::currentPath() + "/this-file-doesnt-exist.txt").toString()
<< int(QNetworkReply::ContentNotFoundError) << 0 << true;
#if !defined Q_OS_WIN && !defined(Q_OS_SYMBIAN)
QTest::newRow("file-is-wronly") << QUrl::fromLocalFile(wronlyFileName).toString()
<< int(QNetworkReply::ContentAccessDenied) << 0 << true;
#endif
if (QFile::exists("/etc/shadow"))
QTest::newRow("file-permissions") << "file:/etc/shadow"
<< int(QNetworkReply::ContentAccessDenied) << 0 << true;
// ftp: errors
QTest::newRow("ftp-host") << "ftp://this-host-doesnt-exist.troll.no/foo.txt"
<< int(QNetworkReply::HostNotFoundError) << 0 << true;
QTest::newRow("ftp-no-path") << "ftp://" + QtNetworkSettings::serverName()
<< int(QNetworkReply::ContentOperationNotPermittedError) << 0 << true;
QTest::newRow("ftp-is-dir") << "ftp://" + QtNetworkSettings::serverName() + "/qtest"
<< int(QNetworkReply::ContentOperationNotPermittedError) << 0 << true;
QTest::newRow("ftp-dir-not-readable") << "ftp://" + QtNetworkSettings::serverName() + "/pub/dir-not-readable/foo.txt"
<< int(QNetworkReply::ContentAccessDenied) << 0 << true;
QTest::newRow("ftp-file-not-readable") << "ftp://" + QtNetworkSettings::serverName() + "/pub/file-not-readable.txt"
<< int(QNetworkReply::ContentAccessDenied) << 0 << true;
QTest::newRow("ftp-exist") << "ftp://" + QtNetworkSettings::serverName() + "/pub/this-file-doesnt-exist.txt"
<< int(QNetworkReply::ContentNotFoundError) << 0 << true;
// http: errors
QTest::newRow("http-host") << "http://this-host-will-never-exist.troll.no/"
<< int(QNetworkReply::HostNotFoundError) << 0 << true;
QTest::newRow("http-exist") << "http://" + QtNetworkSettings::serverName() + "/this-file-doesnt-exist.txt"
<< int(QNetworkReply::ContentNotFoundError) << 404 << false;
QTest::newRow("http-authentication") << "http://" + QtNetworkSettings::serverName() + "/qtest/rfcs-auth"
<< int(QNetworkReply::AuthenticationRequiredError) << 401 << false;
}
void tst_QNetworkReply::getErrors()
{
QFETCH(QString, url);
QNetworkRequest request(url);
QNetworkReplyPtr reply = manager.get(request);
reply->setParent(this); // we have expect-fails
if (!reply->isFinished())
QCOMPARE(reply->error(), QNetworkReply::NoError);
// now run the request:
connect(reply, SIGNAL(finished()),
&QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
//qDebug() << reply->errorString();
QFETCH(int, error);
QEXPECT_FAIL("ftp-is-dir", "QFtp cannot provide enough detail", Abort);
// the line below is not necessary
QEXPECT_FAIL("ftp-dir-not-readable", "QFtp cannot provide enough detail", Abort);
QCOMPARE(reply->error(), QNetworkReply::NetworkError(error));
QTEST(reply->readAll().isEmpty(), "dataIsEmpty");
QVERIFY(reply->isFinished());
QVERIFY(!reply->isRunning());
QFETCH(int, httpStatusCode);
if (httpStatusCode != 0) {
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), httpStatusCode);
}
}
static inline QByteArray md5sum(const QByteArray &data)
{
return QCryptographicHash::hash(data, QCryptographicHash::Md5);
}
void tst_QNetworkReply::putToFile_data()
{
QTest::addColumn<QByteArray>("data");
QTest::addColumn<QByteArray>("md5sum");
QByteArray data;
data = "";
QTest::newRow("empty") << data << md5sum(data);
data = "This is a normal message.";
QTest::newRow("generic") << data << md5sum(data);
data = "This is a message to show that Qt rocks!\r\n\n";
QTest::newRow("small") << data << md5sum(data);
data = QByteArray("abcd\0\1\2\abcd",12);
QTest::newRow("with-nul") << data << md5sum(data);
data = QByteArray(4097, '\4');
QTest::newRow("4k+1") << data << md5sum(data);
data = QByteArray(128*1024+1, '\177');
QTest::newRow("128k+1") << data << md5sum(data);
}
void tst_QNetworkReply::putToFile()
{
QFile file(testFileName);
QUrl url = QUrl::fromLocalFile(file.fileName());
QNetworkRequest request(url);
QNetworkReplyPtr reply;
QFETCH(QByteArray, data);
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::PutOperation, request, reply, data));
QCOMPARE(reply->url(), url);
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), Q_INT64_C(0));
QVERIFY(reply->readAll().isEmpty());
QVERIFY(file.open(QIODevice::ReadOnly));
QCOMPARE(file.size(), qint64(data.size()));
QByteArray contents = file.readAll();
QCOMPARE(contents, data);
}
void tst_QNetworkReply::putToFtp_data()
{
putToFile_data();
}
void tst_QNetworkReply::putToFtp()
{
QUrl url("ftp://" + QtNetworkSettings::serverName());
url.setPath(QString("/qtest/upload/qnetworkaccess-putToFtp-%1-%2")
.arg(QTest::currentDataTag())
.arg(uniqueExtension));
QNetworkRequest request(url);
QNetworkReplyPtr reply;
QFETCH(QByteArray, data);
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::PutOperation, request, reply, data));
QCOMPARE(reply->url(), url);
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), Q_INT64_C(0));
QVERIFY(reply->readAll().isEmpty());
// download the file again from FTP to make sure it was uploaded
// correctly
QFtp ftp;
ftp.connectToHost(url.host());
ftp.login();
ftp.get(url.path());
QObject::connect(&ftp, SIGNAL(done(bool)), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QObject::disconnect(&ftp, SIGNAL(done(bool)), &QTestEventLoop::instance(), SLOT(exitLoop()));
QByteArray uploaded = ftp.readAll();
QCOMPARE(uploaded.size(), data.size());
QCOMPARE(uploaded, data);
ftp.close();
QObject::connect(&ftp, SIGNAL(done(bool)), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QObject::disconnect(&ftp, SIGNAL(done(bool)), &QTestEventLoop::instance(), SLOT(exitLoop()));
}
void tst_QNetworkReply::putToHttp_data()
{
putToFile_data();
}
void tst_QNetworkReply::putToHttp()
{
QUrl url("http://" + QtNetworkSettings::serverName());
url.setPath(QString("/dav/qnetworkaccess-putToHttp-%1-%2")
.arg(QTest::currentDataTag())
.arg(uniqueExtension));
QNetworkRequest request(url);
QNetworkReplyPtr reply;
QFETCH(QByteArray, data);
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::PutOperation, request, reply, data));
QCOMPARE(reply->url(), url);
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 201); // 201 Created
// download the file again from HTTP to make sure it was uploaded
// correctly. HTTP/0.9 is enough
QTcpSocket socket;
socket.connectToHost(QtNetworkSettings::serverName(), 80);
socket.write("GET " + url.toEncoded(QUrl::RemoveScheme | QUrl::RemoveAuthority) + "\r\n");
if (!socket.waitForDisconnected(10000))
QFAIL("Network timeout");
QByteArray uploadedData = socket.readAll();
QCOMPARE(uploadedData, data);
}
void tst_QNetworkReply::postToHttp_data()
{
putToFile_data();
}
void tst_QNetworkReply::postToHttp()
{
QUrl url("http://" + QtNetworkSettings::serverName() + "/qtest/cgi-bin/md5sum.cgi");
QNetworkRequest request(url);
QNetworkReplyPtr reply;
QFETCH(QByteArray, data);
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::PostOperation, request, reply, data));
QCOMPARE(reply->url(), url);
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok
QFETCH(QByteArray, md5sum);
QByteArray uploadedData = reply->readAll().trimmed();
QCOMPARE(uploadedData, md5sum.toHex());
}
void tst_QNetworkReply::deleteFromHttp_data()
{
QTest::addColumn<QUrl>("url");
QTest::addColumn<int>("resultCode");
QTest::addColumn<QNetworkReply::NetworkError>("error");
// for status codes to expect, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
QTest::newRow("405-method-not-allowed") << QUrl("http://" + QtNetworkSettings::serverName() + "/index.html") << 405 << QNetworkReply::ContentOperationNotPermittedError;
QTest::newRow("200-ok") << QUrl("http://" + QtNetworkSettings::serverName() + "/qtest/cgi-bin/http-delete.cgi?200-ok") << 200 << QNetworkReply::NoError;
QTest::newRow("202-accepted") << QUrl("http://" + QtNetworkSettings::serverName() + "/qtest/cgi-bin/http-delete.cgi?202-accepted") << 202 << QNetworkReply::NoError;
QTest::newRow("204-no-content") << QUrl("http://" + QtNetworkSettings::serverName() + "/qtest/cgi-bin/http-delete.cgi?204-no-content") << 204 << QNetworkReply::NoError;
QTest::newRow("404-not-found") << QUrl("http://" + QtNetworkSettings::serverName() + "/qtest/cgi-bin/http-delete.cgi?404-not-found") << 404 << QNetworkReply::ContentNotFoundError;
}
void tst_QNetworkReply::deleteFromHttp()
{
QFETCH(QUrl, url);
QFETCH(int, resultCode);
QFETCH(QNetworkReply::NetworkError, error);
QNetworkRequest request(url);
QNetworkReplyPtr reply;
runSimpleRequest(QNetworkAccessManager::DeleteOperation, request, reply, 0);
QCOMPARE(reply->url(), url);
QCOMPARE(reply->error(), error);
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), resultCode);
}
void tst_QNetworkReply::putGetDeleteGetFromHttp_data()
{
QTest::addColumn<QUrl>("putUrl");
QTest::addColumn<int>("putResultCode");
QTest::addColumn<QNetworkReply::NetworkError>("putError");
QTest::addColumn<QUrl>("deleteUrl");
QTest::addColumn<int>("deleteResultCode");
QTest::addColumn<QNetworkReply::NetworkError>("deleteError");
QTest::addColumn<QUrl>("get2Url");
QTest::addColumn<int>("get2ResultCode");
QTest::addColumn<QNetworkReply::NetworkError>("get2Error");
QUrl url("http://" + QtNetworkSettings::serverName());
url.setPath(QString("/dav/qnetworkaccess-putToHttp-%1-%2")
.arg(QTest::currentDataTag())
.arg(uniqueExtension));
// first use case: put, get (to check it is there), delete, get (to check it is not there anymore)
QTest::newRow("success") << url << 201 << QNetworkReply::NoError << url << 204 << QNetworkReply::NoError << url << 404 << QNetworkReply::ContentNotFoundError;
QUrl wrongUrl("http://" + QtNetworkSettings::serverName());
wrongUrl.setPath(QString("/dav/qnetworkaccess-thisURLisNotAvailable"));
// second use case: put, get (to check it is there), delete wrong URL, get (to check it is still there)
QTest::newRow("delete-error") << url << 201 << QNetworkReply::NoError << wrongUrl << 404 << QNetworkReply::ContentNotFoundError << url << 200 << QNetworkReply::NoError;
}
void tst_QNetworkReply::putGetDeleteGetFromHttp()
{
QFETCH(QUrl, putUrl);
QFETCH(int, putResultCode);
QFETCH(QNetworkReply::NetworkError, putError);
QFETCH(QUrl, deleteUrl);
QFETCH(int, deleteResultCode);
QFETCH(QNetworkReply::NetworkError, deleteError);
QFETCH(QUrl, get2Url);
QFETCH(int, get2ResultCode);
QFETCH(QNetworkReply::NetworkError, get2Error);
QNetworkRequest putRequest(putUrl);
QNetworkRequest deleteRequest(deleteUrl);
QNetworkRequest get2Request(get2Url);
QNetworkReplyPtr reply;
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::PutOperation, putRequest, reply, 0));
QCOMPARE(reply->error(), putError);
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), putResultCode);
runSimpleRequest(QNetworkAccessManager::GetOperation, putRequest, reply, 0);
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
runSimpleRequest(QNetworkAccessManager::DeleteOperation, deleteRequest, reply, 0);
QCOMPARE(reply->error(), deleteError);
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), deleteResultCode);
runSimpleRequest(QNetworkAccessManager::GetOperation, get2Request, reply, 0);
QCOMPARE(reply->error(), get2Error);
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), get2ResultCode);
}
void tst_QNetworkReply::sendCustomRequestToHttp_data()
{
QTest::addColumn<QUrl>("url");
QTest::addColumn<QByteArray>("verb");
QTest::addColumn<QBuffer *>("device");
QTest::addColumn<int>("resultCode");
QTest::addColumn<QNetworkReply::NetworkError>("error");
QTest::addColumn<QByteArray>("expectedContent");
QTest::newRow("options") << QUrl("http://" + QtNetworkSettings::serverName()) <<
QByteArray("OPTIONS") << (QBuffer *) 0 << 200 << QNetworkReply::NoError << QByteArray();
QTest::newRow("trace") << QUrl("http://" + QtNetworkSettings::serverName()) <<
QByteArray("TRACE") << (QBuffer *) 0 << 200 << QNetworkReply::NoError << QByteArray();
QTest::newRow("connect") << QUrl("http://" + QtNetworkSettings::serverName()) <<
QByteArray("CONNECT") << (QBuffer *) 0 << 400 << QNetworkReply::UnknownContentError << QByteArray(); // 400 = Bad Request
QTest::newRow("nonsense") << QUrl("http://" + QtNetworkSettings::serverName()) <<
QByteArray("NONSENSE") << (QBuffer *) 0 << 501 << QNetworkReply::ProtocolUnknownError << QByteArray(); // 501 = Method Not Implemented
QByteArray ba("test");
QBuffer *buffer = new QBuffer;
buffer->setData(ba);
buffer->open(QIODevice::ReadOnly);
QTest::newRow("post") << QUrl("http://" + QtNetworkSettings::serverName() + "/qtest/cgi-bin/md5sum.cgi") << QByteArray("POST")
<< buffer << 200 << QNetworkReply::NoError << QByteArray("098f6bcd4621d373cade4e832627b4f6\n");
QByteArray ba2("test");
QBuffer *buffer2 = new QBuffer;
buffer2->setData(ba2);
buffer2->open(QIODevice::ReadOnly);
QTest::newRow("put") << QUrl("http://" + QtNetworkSettings::serverName() + "/qtest/cgi-bin/md5sum.cgi") << QByteArray("PUT")
<< buffer2 << 200 << QNetworkReply::NoError << QByteArray("098f6bcd4621d373cade4e832627b4f6\n");
}
void tst_QNetworkReply::sendCustomRequestToHttp()
{
QFETCH(QUrl, url);
QNetworkRequest request(url);
QNetworkReplyPtr reply;
QFETCH(QByteArray, verb);
QFETCH(QBuffer *, device);
runCustomRequest(request, reply, verb, device);
QCOMPARE(reply->url(), url);
QFETCH(QNetworkReply::NetworkError, error);
QCOMPARE(reply->error(), error);
QFETCH(int, resultCode);
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), resultCode);
QFETCH(QByteArray, expectedContent);
if (! expectedContent.isEmpty())
QCOMPARE(reply->readAll(), expectedContent);
}
void tst_QNetworkReply::ioGetFromData_data()
{
QTest::addColumn<QString>("urlStr");
QTest::addColumn<QByteArray>("data");
QTest::newRow("data-empty") << "data:," << QByteArray();
QTest::newRow("data-literal") << "data:,foo" << QByteArray("foo");
QTest::newRow("data-pct") << "data:,%3Cbody%20contentEditable%3Dtrue%3E%0D%0A"
<< QByteArray("<body contentEditable=true>\r\n");
QTest::newRow("data-base64") << "data:;base64,UXQgaXMgZ3JlYXQh" << QByteArray("Qt is great!");
}
void tst_QNetworkReply::ioGetFromData()
{
QFETCH(QString, urlStr);
QUrl url = QUrl::fromEncoded(urlStr.toLatin1());
QNetworkRequest request(url);
QNetworkReplyPtr reply = manager.get(request);
DataReader reader(reply);
connect(reply, SIGNAL(finished()),
&QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->url(), request.url());
QCOMPARE(reply->error(), QNetworkReply::NoError);
QFETCH(QByteArray, data);
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toInt(), data.size());
QCOMPARE(reader.data.size(), data.size());
QCOMPARE(reader.data, data);
}
void tst_QNetworkReply::ioGetFromFileSpecial_data()
{
getFromFileSpecial_data();
}
void tst_QNetworkReply::ioGetFromFileSpecial()
{
QFETCH(QString, fileName);
QFETCH(QString, url);
QFile resource(fileName);
QVERIFY(resource.open(QIODevice::ReadOnly));
QNetworkRequest request;
request.setUrl(url);
QNetworkReplyPtr reply = manager.get(request);
DataReader reader(reply);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->url(), request.url());
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), resource.size());
QCOMPARE(qint64(reader.data.size()), resource.size());
QCOMPARE(reader.data, resource.readAll());
}
void tst_QNetworkReply::ioGetFromFile_data()
{
putToFile_data();
}
void tst_QNetworkReply::ioGetFromFile()
{
QTemporaryFile file(QDir::currentPath() + "/temp-XXXXXX");
file.setAutoRemove(true);
QVERIFY(file.open());
QFETCH(QByteArray, data);
QVERIFY(file.write(data) == data.size());
file.flush();
QCOMPARE(file.size(), qint64(data.size()));
QNetworkRequest request(QUrl::fromLocalFile(file.fileName()));
QNetworkReplyPtr reply = manager.get(request);
QVERIFY(reply->isFinished()); // a file should immediatly be done
DataReader reader(reply);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->url(), request.url());
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), file.size());
QCOMPARE(qint64(reader.data.size()), file.size());
QCOMPARE(reader.data, data);
}
void tst_QNetworkReply::ioGetFromFtp_data()
{
QTest::addColumn<QString>("fileName");
QTest::addColumn<qint64>("expectedSize");
QTest::newRow("bigfile") << "bigfile" << Q_INT64_C(519240);
QFile file(SRCDIR "/rfc3252.txt");
QTest::newRow("rfc3252.txt") << "rfc3252.txt" << file.size();
}
void tst_QNetworkReply::ioGetFromFtp()
{
QFETCH(QString, fileName);
QFile reference(fileName);
reference.open(QIODevice::ReadOnly); // will fail for bigfile
QNetworkRequest request("ftp://" + QtNetworkSettings::serverName() + "/qtest/" + fileName);
QNetworkReplyPtr reply = manager.get(request);
DataReader reader(reply);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->url(), request.url());
QCOMPARE(reply->error(), QNetworkReply::NoError);
QFETCH(qint64, expectedSize);
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), expectedSize);
QCOMPARE(qint64(reader.data.size()), expectedSize);
if (reference.isOpen())
QCOMPARE(reader.data, reference.readAll());
}
void tst_QNetworkReply::ioGetFromFtpWithReuse()
{
QString fileName = SRCDIR "/rfc3252.txt";
QFile reference(fileName);
reference.open(QIODevice::ReadOnly);
QNetworkRequest request(QUrl("ftp://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"));
// two concurrent (actually, consecutive) gets:
QNetworkReplyPtr reply1 = manager.get(request);
DataReader reader1(reply1);
QNetworkReplyPtr reply2 = manager.get(request);
DataReader reader2(reply2);
QSignalSpy spy(reply1, SIGNAL(finished()));
connect(reply2, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
if (spy.count() == 0) {
connect(reply1, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
}
QCOMPARE(reply1->url(), request.url());
QCOMPARE(reply2->url(), request.url());
QCOMPARE(reply1->error(), QNetworkReply::NoError);
QCOMPARE(reply2->error(), QNetworkReply::NoError);
QCOMPARE(qint64(reader1.data.size()), reference.size());
QCOMPARE(qint64(reader2.data.size()), reference.size());
QCOMPARE(reply1->header(QNetworkRequest::ContentLengthHeader).toLongLong(), reference.size());
QCOMPARE(reply2->header(QNetworkRequest::ContentLengthHeader).toLongLong(), reference.size());
QByteArray referenceData = reference.readAll();
QCOMPARE(reader1.data, referenceData);
QCOMPARE(reader2.data, referenceData);
}
void tst_QNetworkReply::ioGetFromHttp()
{
QFile reference(SRCDIR "/rfc3252.txt");
QVERIFY(reference.open(QIODevice::ReadOnly));
QNetworkRequest request(QUrl("http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"));
QNetworkReplyPtr reply = manager.get(request);
DataReader reader(reply);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->url(), request.url());
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), reference.size());
QCOMPARE(qint64(reader.data.size()), reference.size());
QCOMPARE(reader.data, reference.readAll());
}
void tst_QNetworkReply::ioGetFromHttpWithReuseParallel()
{
QFile reference(SRCDIR "/rfc3252.txt");
QVERIFY(reference.open(QIODevice::ReadOnly));
QNetworkRequest request(QUrl("http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"));
QNetworkReplyPtr reply1 = manager.get(request);
QNetworkReplyPtr reply2 = manager.get(request);
DataReader reader1(reply1);
DataReader reader2(reply2);
QSignalSpy spy(reply1, SIGNAL(finished()));
connect(reply2, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
if (spy.count() == 0) {
connect(reply1, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
}
QCOMPARE(reply1->url(), request.url());
QCOMPARE(reply2->url(), request.url());
QCOMPARE(reply1->error(), QNetworkReply::NoError);
QCOMPARE(reply2->error(), QNetworkReply::NoError);
QCOMPARE(reply1->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QCOMPARE(reply2->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QCOMPARE(reply1->header(QNetworkRequest::ContentLengthHeader).toLongLong(), reference.size());
QCOMPARE(reply2->header(QNetworkRequest::ContentLengthHeader).toLongLong(), reference.size());
QCOMPARE(qint64(reader1.data.size()), reference.size());
QCOMPARE(qint64(reader2.data.size()), reference.size());
QByteArray referenceData = reference.readAll();
QCOMPARE(reader1.data, referenceData);
QCOMPARE(reader2.data, referenceData);
}
void tst_QNetworkReply::ioGetFromHttpWithReuseSequential()
{
QFile reference(SRCDIR "/rfc3252.txt");
QVERIFY(reference.open(QIODevice::ReadOnly));
QNetworkRequest request(QUrl("http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"));
{
QNetworkReplyPtr reply = manager.get(request);
DataReader reader(reply);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->url(), request.url());
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), reference.size());
QCOMPARE(qint64(reader.data.size()), reference.size());
QCOMPARE(reader.data, reference.readAll());
}
reference.seek(0);
// rinse and repeat:
{
QNetworkReplyPtr reply = manager.get(request);
DataReader reader(reply);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->url(), request.url());
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), reference.size());
QCOMPARE(qint64(reader.data.size()), reference.size());
QCOMPARE(reader.data, reference.readAll());
}
}
void tst_QNetworkReply::ioGetFromHttpWithAuth()
{
qRegisterMetaType<QNetworkReply *>(); // for QSignalSpy
qRegisterMetaType<QAuthenticator *>();
// This test sends three requests
// The first two in parallel
// The third after the first two finished
QFile reference(SRCDIR "/rfc3252.txt");
QVERIFY(reference.open(QIODevice::ReadOnly));
QNetworkRequest request(QUrl("http://" + QtNetworkSettings::serverName() + "/qtest/rfcs-auth/rfc3252.txt"));
{
QNetworkReplyPtr reply1 = manager.get(request);
QNetworkReplyPtr reply2 = manager.get(request);
DataReader reader1(reply1);
DataReader reader2(reply2);
QSignalSpy finishedspy(reply1, SIGNAL(finished()));
QSignalSpy authspy(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)));
connect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*)));
connect(reply2, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
if (finishedspy.count() == 0) {
connect(reply1, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
}
manager.disconnect(SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
this, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*)));
QCOMPARE(reply1->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QCOMPARE(reply2->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QByteArray referenceData = reference.readAll();
QCOMPARE(reader1.data, referenceData);
QCOMPARE(reader2.data, referenceData);
QCOMPARE(authspy.count(), 1);
}
reference.seek(0);
// rinse and repeat:
{
QNetworkReplyPtr reply = manager.get(request);
DataReader reader(reply);
QSignalSpy authspy(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)));
connect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*)));
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
manager.disconnect(SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
this, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*)));
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QCOMPARE(reader.data, reference.readAll());
QCOMPARE(authspy.count(), 0);
}
}
void tst_QNetworkReply::ioGetFromHttpWithProxyAuth()
{
qRegisterMetaType<QNetworkProxy>(); // for QSignalSpy
qRegisterMetaType<QAuthenticator *>();
// This test sends three requests
// The first two in parallel
// The third after the first two finished
QFile reference(SRCDIR "/rfc3252.txt");
QVERIFY(reference.open(QIODevice::ReadOnly));
QNetworkProxy proxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3129);
QNetworkRequest request(QUrl("http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"));
{
manager.setProxy(proxy);
QNetworkReplyPtr reply1 = manager.get(request);
QNetworkReplyPtr reply2 = manager.get(request);
manager.setProxy(QNetworkProxy());
DataReader reader1(reply1);
DataReader reader2(reply2);
QSignalSpy finishedspy(reply1, SIGNAL(finished()));
QSignalSpy authspy(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
connect(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
connect(reply2, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
if (finishedspy.count() == 0) {
connect(reply1, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
}
manager.disconnect(SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
this, SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
QCOMPARE(reply1->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QCOMPARE(reply2->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QByteArray referenceData = reference.readAll();
QCOMPARE(reader1.data, referenceData);
QCOMPARE(reader2.data, referenceData);
QCOMPARE(authspy.count(), 1);
}
reference.seek(0);
// rinse and repeat:
{
manager.setProxy(proxy);
QNetworkReplyPtr reply = manager.get(request);
DataReader reader(reply);
manager.setProxy(QNetworkProxy());
QSignalSpy authspy(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
connect(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
manager.disconnect(SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
this, SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QCOMPARE(reader.data, reference.readAll());
QCOMPARE(authspy.count(), 0);
}
}
void tst_QNetworkReply::ioGetFromHttpWithSocksProxy()
{
// HTTP caching proxies are tested by the above function
// test SOCKSv5 proxies too
qRegisterMetaType<QNetworkProxy>(); // for QSignalSpy
qRegisterMetaType<QAuthenticator *>();
QFile reference(SRCDIR "/rfc3252.txt");
QVERIFY(reference.open(QIODevice::ReadOnly));
QNetworkProxy proxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1080);
QNetworkRequest request(QUrl("http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"));
{
manager.setProxy(proxy);
QNetworkReplyPtr reply = manager.get(request);
DataReader reader(reply);
manager.setProxy(QNetworkProxy());
QSignalSpy authspy(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
connect(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
manager.disconnect(SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
this, SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QCOMPARE(reader.data, reference.readAll());
QCOMPARE(authspy.count(), 0);
}
// set an invalid proxy just to make sure that we can't load
proxy = QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1079);
{
manager.setProxy(proxy);
QNetworkReplyPtr reply = manager.get(request);
DataReader reader(reply);
manager.setProxy(QNetworkProxy());
QSignalSpy authspy(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
connect(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
manager.disconnect(SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
this, SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
QVERIFY(!reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).isValid());
QVERIFY(reader.data.isEmpty());
QVERIFY(int(reply->error()) > 0);
QEXPECT_FAIL("", "QTcpSocket doesn't return enough information yet", Continue);
QCOMPARE(int(reply->error()), int(QNetworkReply::ProxyConnectionRefusedError));
QCOMPARE(authspy.count(), 0);
}
}
#ifndef QT_NO_OPENSSL
void tst_QNetworkReply::ioGetFromHttpsWithSslErrors()
{
qRegisterMetaType<QNetworkReply*>(); // for QSignalSpy
qRegisterMetaType<QList<QSslError> >();
QFile reference(SRCDIR "/rfc3252.txt");
QVERIFY(reference.open(QIODevice::ReadOnly));
QNetworkRequest request(QUrl("https://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"));
QNetworkReplyPtr reply = manager.get(request);
DataReader reader(reply);
QSignalSpy sslspy(&manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)));
connect(&manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
SLOT(sslErrors(QNetworkReply*,QList<QSslError>)));
connect(reply, SIGNAL(metaDataChanged()), SLOT(storeSslConfiguration()));
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
manager.disconnect(SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
this, SLOT(sslErrors(QNetworkReply*,QList<QSslError>)));
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QCOMPARE(reader.data, reference.readAll());
QCOMPARE(sslspy.count(), 1);
QVERIFY(!storedSslConfiguration.isNull());
QVERIFY(!reply->sslConfiguration().isNull());
}
void tst_QNetworkReply::ioGetFromHttpsWithIgnoreSslErrors()
{
// same as above, except that we call ignoreSslErrors and don't connect
// to the sslErrors() signal (which is *still* emitted)
qRegisterMetaType<QNetworkReply*>(); // for QSignalSpy
qRegisterMetaType<QList<QSslError> >();
QFile reference(SRCDIR "/rfc3252.txt");
QVERIFY(reference.open(QIODevice::ReadOnly));
QNetworkRequest request(QUrl("https://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"));
QNetworkReplyPtr reply = manager.get(request);
reply->ignoreSslErrors();
DataReader reader(reply);
QSignalSpy sslspy(&manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)));
connect(reply, SIGNAL(metaDataChanged()), SLOT(storeSslConfiguration()));
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QCOMPARE(reader.data, reference.readAll());
QCOMPARE(sslspy.count(), 1);
QVERIFY(!storedSslConfiguration.isNull());
QVERIFY(!reply->sslConfiguration().isNull());
}
void tst_QNetworkReply::ioGetFromHttpsWithSslHandshakeError()
{
qRegisterMetaType<QNetworkReply*>(); // for QSignalSpy
qRegisterMetaType<QList<QSslError> >();
QFile reference(SRCDIR "/rfc3252.txt");
QVERIFY(reference.open(QIODevice::ReadOnly));
QNetworkRequest request(QUrl("https://" + QtNetworkSettings::serverName() + ":80"));
QNetworkReplyPtr reply = manager.get(request);
reply->ignoreSslErrors();
DataReader reader(reply);
QSignalSpy sslspy(&manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)));
connect(reply, SIGNAL(metaDataChanged()), SLOT(storeSslConfiguration()));
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->error(), QNetworkReply::SslHandshakeFailedError);
QCOMPARE(sslspy.count(), 0);
}
#endif
void tst_QNetworkReply::ioGetFromHttpBrokenServer_data()
{
QTest::addColumn<QByteArray>("dataToSend");
QTest::addColumn<bool>("doDisconnect");
QTest::newRow("no-newline") << QByteArray("Hello World") << false;
// these are OK now, we just eat the lonely newlines
//QTest::newRow("just-newline") << QByteArray("\r\n") << false;
//QTest::newRow("just-2newline") << QByteArray("\r\n\r\n") << false;
QTest::newRow("with-newlines") << QByteArray("Long first line\r\nLong second line") << false;
QTest::newRow("with-newlines2") << QByteArray("\r\nSecond line") << false;
QTest::newRow("with-newlines3") << QByteArray("ICY\r\nSecond line") << false;
QTest::newRow("invalid-version") << QByteArray("HTTP/123 200 \r\n") << false;
QTest::newRow("invalid-version2") << QByteArray("HTTP/a.\033 200 \r\n") << false;
QTest::newRow("invalid-reply-code") << QByteArray("HTTP/1.0 fuu \r\n") << false;
QTest::newRow("empty+disconnect") << QByteArray() << true;
QTest::newRow("no-newline+disconnect") << QByteArray("Hello World") << true;
QTest::newRow("just-newline+disconnect") << QByteArray("\r\n") << true;
QTest::newRow("just-2newline+disconnect") << QByteArray("\r\n\r\n") << true;
QTest::newRow("with-newlines+disconnect") << QByteArray("Long first line\r\nLong second line") << true;
QTest::newRow("with-newlines2+disconnect") << QByteArray("\r\nSecond line") << true;
QTest::newRow("with-newlines3+disconnect") << QByteArray("ICY\r\nSecond line") << true;
QTest::newRow("invalid-version+disconnect") << QByteArray("HTTP/123 200 ") << true;
QTest::newRow("invalid-version2+disconnect") << QByteArray("HTTP/a.\033 200 ") << true;
QTest::newRow("invalid-reply-code+disconnect") << QByteArray("HTTP/1.0 fuu ") << true;
QTest::newRow("immediate disconnect") << QByteArray("") << true;
QTest::newRow("justHalfStatus+disconnect") << QByteArray("HTTP/1.1") << true;
QTest::newRow("justStatus+disconnect") << QByteArray("HTTP/1.1 200 OK\r\n") << true;
QTest::newRow("justStatusAndHalfHeaders+disconnect") << QByteArray("HTTP/1.1 200 OK\r\nContent-L") << true;
}
void tst_QNetworkReply::ioGetFromHttpBrokenServer()
{
QFETCH(QByteArray, dataToSend);
QFETCH(bool, doDisconnect);
MiniHttpServer server(dataToSend);
server.doClose = doDisconnect;
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort())));
QNetworkReplyPtr reply = manager.get(request);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->url(), request.url());
QVERIFY(reply->error() != QNetworkReply::NoError);
}
void tst_QNetworkReply::ioGetFromHttpStatus100_data()
{
QTest::addColumn<QByteArray>("dataToSend");
QTest::newRow("normal") << QByteArray("HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
QTest::newRow("minimal") << QByteArray("HTTP/1.1 100 Continue\n\nHTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
QTest::newRow("minimal2") << QByteArray("HTTP/1.1 100 Continue\n\nHTTP/1.0 200 OK\r\n\r\n");
QTest::newRow("minimal3") << QByteArray("HTTP/1.1 100 Continue\n\nHTTP/1.0 200 OK\n\n");
QTest::newRow("with_headers") << QByteArray("HTTP/1.1 100 Continue\r\nBla: x\r\n\r\nHTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
QTest::newRow("with_headers2") << QByteArray("HTTP/1.1 100 Continue\nBla: x\n\nHTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
}
void tst_QNetworkReply::ioGetFromHttpStatus100()
{
QFETCH(QByteArray, dataToSend);
MiniHttpServer server(dataToSend);
server.doClose = true;
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort())));
QNetworkReplyPtr reply = manager.get(request);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->url(), request.url());
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QVERIFY(reply->rawHeader("bla").isNull());
}
void tst_QNetworkReply::ioGetFromHttpNoHeaders_data()
{
QTest::addColumn<QByteArray>("dataToSend");
QTest::newRow("justStatus+noheaders+disconnect") << QByteArray("HTTP/1.0 200 OK\r\n\r\n");
}
void tst_QNetworkReply::ioGetFromHttpNoHeaders()
{
QFETCH(QByteArray, dataToSend);
MiniHttpServer server(dataToSend);
server.doClose = true;
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort())));
QNetworkReplyPtr reply = manager.get(request);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->url(), request.url());
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
}
void tst_QNetworkReply::ioGetFromHttpWithCache_data()
{
qRegisterMetaType<MyMemoryCache::CachedContent>();
QTest::addColumn<QByteArray>("dataToSend");
QTest::addColumn<QString>("body");
QTest::addColumn<MyMemoryCache::CachedContent>("cachedReply");
QTest::addColumn<int>("cacheMode");
QTest::addColumn<bool>("loadedFromCache");
QTest::addColumn<bool>("networkUsed");
QByteArray reply200 =
"HTTP/1.0 200\r\n"
"Connection: keep-alive\r\n"
"Content-Type: text/plain\r\n"
"Cache-control: no-cache\r\n"
"Content-length: 8\r\n"
"\r\n"
"Reloaded";
QByteArray reply304 =
"HTTP/1.0 304 Use Cache\r\n"
"Connection: keep-alive\r\n"
"\r\n";
QTest::newRow("not-cached,always-network")
<< reply200 << "Reloaded" << MyMemoryCache::CachedContent() << int(QNetworkRequest::AlwaysNetwork) << false << true;
QTest::newRow("not-cached,prefer-network")
<< reply200 << "Reloaded" << MyMemoryCache::CachedContent() << int(QNetworkRequest::PreferNetwork) << false << true;
QTest::newRow("not-cached,prefer-cache")
<< reply200 << "Reloaded" << MyMemoryCache::CachedContent() << int(QNetworkRequest::PreferCache) << false << true;
QDateTime present = QDateTime::currentDateTime().toUTC();
QDateTime past = present.addSecs(-3600);
QDateTime future = present.addSecs(3600);
static const char dateFormat[] = "ddd, dd MMM yyyy hh:mm:ss 'GMT'";
QNetworkCacheMetaData::RawHeaderList rawHeaders;
MyMemoryCache::CachedContent content;
content.second = "Not-reloaded";
content.first.setLastModified(past);
//
// Set to expired
//
rawHeaders.clear();
rawHeaders << QNetworkCacheMetaData::RawHeader("Date", QLocale::c().toString(past, dateFormat).toLatin1())
<< QNetworkCacheMetaData::RawHeader("Cache-control", "max-age=0"); // isn't used in cache loading
content.first.setRawHeaders(rawHeaders);
content.first.setLastModified(past);
QTest::newRow("expired,200,prefer-network")
<< reply200 << "Reloaded" << content << int(QNetworkRequest::PreferNetwork) << false << true;
QTest::newRow("expired,200,prefer-cache")
<< reply200 << "Reloaded" << content << int(QNetworkRequest::PreferCache) << false << true;
QTest::newRow("expired,304,prefer-network")
<< reply304 << "Not-reloaded" << content << int(QNetworkRequest::PreferNetwork) << true << true;
QTest::newRow("expired,304,prefer-cache")
<< reply304 << "Not-reloaded" << content << int(QNetworkRequest::PreferCache) << true << true;
//
// Set to not-expired
//
rawHeaders.clear();
rawHeaders << QNetworkCacheMetaData::RawHeader("Date", QLocale::c().toString(past, dateFormat).toLatin1())
<< QNetworkCacheMetaData::RawHeader("Cache-control", "max-age=7200"); // isn't used in cache loading
content.first.setRawHeaders(rawHeaders);
content.first.setExpirationDate(future);
QTest::newRow("not-expired,200,always-network")
<< reply200 << "Reloaded" << content << int(QNetworkRequest::AlwaysNetwork) << false << true;
QTest::newRow("not-expired,200,prefer-network")
<< reply200 << "Not-reloaded" << content << int(QNetworkRequest::PreferNetwork) << true << false;
QTest::newRow("not-expired,200,prefer-cache")
<< reply200 << "Not-reloaded" << content << int(QNetworkRequest::PreferCache) << true << false;
QTest::newRow("not-expired,200,always-cache")
<< reply200 << "Not-reloaded" << content << int(QNetworkRequest::AlwaysCache) << true << false;
QTest::newRow("not-expired,304,prefer-network")
<< reply304 << "Not-reloaded" << content << int(QNetworkRequest::PreferNetwork) << true << false;
QTest::newRow("not-expired,304,prefer-cache")
<< reply304 << "Not-reloaded" << content << int(QNetworkRequest::PreferCache) << true << false;
QTest::newRow("not-expired,304,always-cache")
<< reply304 << "Not-reloaded" << content << int(QNetworkRequest::AlwaysCache) << true << false;
//
// Set must-revalidate now
//
rawHeaders.clear();
rawHeaders << QNetworkCacheMetaData::RawHeader("Date", QLocale::c().toString(past, dateFormat).toLatin1())
<< QNetworkCacheMetaData::RawHeader("Cache-control", "max-age=7200, must-revalidate"); // must-revalidate is used
content.first.setRawHeaders(rawHeaders);
QTest::newRow("must-revalidate,200,always-network")
<< reply200 << "Reloaded" << content << int(QNetworkRequest::AlwaysNetwork) << false << true;
QTest::newRow("must-revalidate,200,prefer-network")
<< reply200 << "Reloaded" << content << int(QNetworkRequest::PreferNetwork) << false << true;
QTest::newRow("must-revalidate,200,prefer-cache")
<< reply200 << "Not-reloaded" << content << int(QNetworkRequest::PreferCache) << true << false;
QTest::newRow("must-revalidate,200,always-cache")
<< reply200 << "Not-reloaded" << content << int(QNetworkRequest::AlwaysCache) << true << false;
QTest::newRow("must-revalidate,304,prefer-network")
<< reply304 << "Not-reloaded" << content << int(QNetworkRequest::PreferNetwork) << true << true;
QTest::newRow("must-revalidate,304,prefer-cache")
<< reply304 << "Not-reloaded" << content << int(QNetworkRequest::PreferCache) << true << false;
QTest::newRow("must-revalidate,304,always-cache")
<< reply304 << "Not-reloaded" << content << int(QNetworkRequest::AlwaysCache) << true << false;
}
void tst_QNetworkReply::ioGetFromHttpWithCache()
{
QFETCH(QByteArray, dataToSend);
MiniHttpServer server(dataToSend);
server.doClose = false;
MyMemoryCache *memoryCache = new MyMemoryCache(&manager);
manager.setCache(memoryCache);
QFETCH(MyMemoryCache::CachedContent, cachedReply);
QUrl url = "http://localhost:" + QString::number(server.serverPort());
cachedReply.first.setUrl(url);
if (!cachedReply.second.isNull())
memoryCache->cache.insert(url.toEncoded(), cachedReply);
QFETCH(int, cacheMode);
QNetworkRequest request(url);
request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, cacheMode);
request.setAttribute(QNetworkRequest::CacheSaveControlAttribute, false);
QNetworkReplyPtr reply = manager.get(request);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QTEST(reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(), "loadedFromCache");
QTEST(server.totalConnections > 0, "networkUsed");
QFETCH(QString, body);
QCOMPARE(reply->readAll().constData(), qPrintable(body));
}
void tst_QNetworkReply::ioGetWithManyProxies_data()
{
QTest::addColumn<QList<QNetworkProxy> >("proxyList");
QTest::addColumn<QNetworkProxy>("proxyUsed");
QTest::addColumn<QString>("url");
QTest::addColumn<QNetworkReply::NetworkError>("expectedError");
QList<QNetworkProxy> proxyList;
// All of the other functions test DefaultProxy
// So let's test something else
// Simple tests that work:
// HTTP request with HTTP caching proxy
proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3129);
QTest::newRow("http-on-http")
<< proxyList << proxyList.at(0)
<< "http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"
<< QNetworkReply::NoError;
// HTTP request with HTTP transparent proxy
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::HttpProxy, QtNetworkSettings::serverName(), 3129);
QTest::newRow("http-on-http2")
<< proxyList << proxyList.at(0)
<< "http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"
<< QNetworkReply::NoError;
// HTTP request with SOCKS transparent proxy
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1081);
QTest::newRow("http-on-socks")
<< proxyList << proxyList.at(0)
<< "http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"
<< QNetworkReply::NoError;
// FTP request with FTP caching proxy
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::serverName(), 2121);
QTest::newRow("ftp-on-ftp")
<< proxyList << proxyList.at(0)
<< "ftp://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"
<< QNetworkReply::NoError;
// The following test doesn't work because QFtp is too limited
// It can only talk to its own kind of proxies
// FTP request with SOCKSv5 transparent proxy
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1081);
QTest::newRow("ftp-on-socks")
<< proxyList << proxyList.at(0)
<< "ftp://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"
<< QNetworkReply::NoError;
#ifndef QT_NO_OPENSSL
// HTTPS with HTTP transparent proxy
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::HttpProxy, QtNetworkSettings::serverName(), 3129);
QTest::newRow("https-on-http")
<< proxyList << proxyList.at(0)
<< "https://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"
<< QNetworkReply::NoError;
// HTTPS request with SOCKS transparent proxy
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1081);
QTest::newRow("https-on-socks")
<< proxyList << proxyList.at(0)
<< "https://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"
<< QNetworkReply::NoError;
#endif
// Tests that fail:
// HTTP request with FTP caching proxy
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::serverName(), 2121);
QTest::newRow("http-on-ftp")
<< proxyList << QNetworkProxy()
<< "http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"
<< QNetworkReply::ProxyNotFoundError;
// FTP request with HTTP caching proxy
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3129);
QTest::newRow("ftp-on-http")
<< proxyList << QNetworkProxy()
<< "ftp://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"
<< QNetworkReply::ProxyNotFoundError;
// FTP request with HTTP caching proxies
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3129)
<< QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3130);
QTest::newRow("ftp-on-multiple-http")
<< proxyList << QNetworkProxy()
<< "ftp://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"
<< QNetworkReply::ProxyNotFoundError;
#ifndef QT_NO_OPENSSL
// HTTPS with HTTP caching proxy
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3129);
QTest::newRow("https-on-httptransparent")
<< proxyList << QNetworkProxy()
<< "https://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"
<< QNetworkReply::ProxyNotFoundError;
// HTTPS with FTP caching proxy
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::serverName(), 2121);
QTest::newRow("https-on-ftp")
<< proxyList << QNetworkProxy()
<< "https://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"
<< QNetworkReply::ProxyNotFoundError;
#endif
// Complex requests:
// HTTP request with more than one HTTP proxy
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3129)
<< QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3130);
QTest::newRow("http-on-multiple-http")
<< proxyList << proxyList.at(0)
<< "http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"
<< QNetworkReply::NoError;
// HTTP request with HTTP + SOCKS
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3129)
<< QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1081);
QTest::newRow("http-on-http+socks")
<< proxyList << proxyList.at(0)
<< "http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"
<< QNetworkReply::NoError;
// HTTP request with FTP + HTTP + SOCKS
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::serverName(), 2121)
<< QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3129)
<< QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1081);
QTest::newRow("http-on-ftp+http+socks")
<< proxyList << proxyList.at(1) // second proxy should be used
<< "http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"
<< QNetworkReply::NoError;
// HTTP request with NoProxy + HTTP
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::NoProxy)
<< QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3129);
QTest::newRow("http-on-noproxy+http")
<< proxyList << proxyList.at(0)
<< "http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"
<< QNetworkReply::NoError;
// HTTP request with FTP + NoProxy
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::serverName(), 2121)
<< QNetworkProxy(QNetworkProxy::NoProxy);
QTest::newRow("http-on-ftp+noproxy")
<< proxyList << proxyList.at(1) // second proxy should be used
<< "http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"
<< QNetworkReply::NoError;
// FTP request with HTTP Caching + FTP
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3129)
<< QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::serverName(), 2121);
QTest::newRow("ftp-on-http+ftp")
<< proxyList << proxyList.at(1) // second proxy should be used
<< "ftp://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"
<< QNetworkReply::NoError;
#ifndef QT_NO_OPENSSL
// HTTPS request with HTTP Caching + HTTP transparent
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3129)
<< QNetworkProxy(QNetworkProxy::HttpProxy, QtNetworkSettings::serverName(), 3129);
QTest::newRow("https-on-httpcaching+http")
<< proxyList << proxyList.at(1) // second proxy should be used
<< "https://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"
<< QNetworkReply::NoError;
// HTTPS request with FTP + HTTP C + HTTP T
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::serverName(), 2121)
<< QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3129)
<< QNetworkProxy(QNetworkProxy::HttpProxy, QtNetworkSettings::serverName(), 3129);
QTest::newRow("https-on-ftp+httpcaching+http")
<< proxyList << proxyList.at(2) // skip the first two
<< "https://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"
<< QNetworkReply::NoError;
#endif
}
void tst_QNetworkReply::ioGetWithManyProxies()
{
// Test proxy factories
qRegisterMetaType<QNetworkProxy>(); // for QSignalSpy
qRegisterMetaType<QAuthenticator *>();
QFile reference(SRCDIR "/rfc3252.txt");
QVERIFY(reference.open(QIODevice::ReadOnly));
// set the proxy factory:
QFETCH(QList<QNetworkProxy>, proxyList);
MyProxyFactory *proxyFactory = new MyProxyFactory;
proxyFactory->toReturn = proxyList;
manager.setProxyFactory(proxyFactory);
QFETCH(QString, url);
QUrl theUrl(url);
QNetworkRequest request(theUrl);
QNetworkReplyPtr reply = manager.get(request);
DataReader reader(reply);
QSignalSpy authspy(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
connect(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
#ifndef QT_NO_OPENSSL
connect(&manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
SLOT(sslErrors(QNetworkReply*,QList<QSslError>)));
#endif
QTestEventLoop::instance().enterLoop(15);
QVERIFY(!QTestEventLoop::instance().timeout());
manager.disconnect(SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
this, SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
#ifndef QT_NO_OPENSSL
manager.disconnect(SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
this, SLOT(sslErrors(QNetworkReply*,QList<QSslError>)));
#endif
QFETCH(QNetworkReply::NetworkError, expectedError);
QEXPECT_FAIL("ftp-on-socks", "QFtp is too limited and won't accept non-FTP proxies", Abort);
QCOMPARE(reply->error(), expectedError);
// Verify that the factory was called properly
QCOMPARE(proxyFactory->callCount, 1);
QCOMPARE(proxyFactory->lastQuery, QNetworkProxyQuery(theUrl));
if (expectedError == QNetworkReply::NoError) {
// request succeeded
QCOMPARE(reader.data, reference.readAll());
// now verify that the proxies worked:
QFETCH(QNetworkProxy, proxyUsed);
if (proxyUsed.type() == QNetworkProxy::NoProxy) {
QCOMPARE(authspy.count(), 0);
} else {
if (QByteArray(QTest::currentDataTag()).startsWith("ftp-"))
return; // No authentication with current FTP or with FTP proxies
QCOMPARE(authspy.count(), 1);
QCOMPARE(qvariant_cast<QNetworkProxy>(authspy.at(0).at(0)), proxyUsed);
}
} else {
// request failed
QCOMPARE(authspy.count(), 0);
}
}
void tst_QNetworkReply::ioPutToFileFromFile_data()
{
QTest::addColumn<QString>("fileName");
QTest::newRow("empty") << SRCDIR "/empty";
QTest::newRow("real-file") << SRCDIR "/rfc3252.txt";
QTest::newRow("resource") << ":/resource";
QTest::newRow("search-path") << "srcdir:/rfc3252.txt";
}
void tst_QNetworkReply::ioPutToFileFromFile()
{
QFETCH(QString, fileName);
QFile sourceFile(fileName);
QFile targetFile(testFileName);
QVERIFY(sourceFile.open(QIODevice::ReadOnly));
QUrl url = QUrl::fromLocalFile(targetFile.fileName());
QNetworkRequest request(url);
QNetworkReplyPtr reply = manager.put(request, &sourceFile);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->url(), url);
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), Q_INT64_C(0));
QVERIFY(reply->readAll().isEmpty());
QVERIFY(sourceFile.atEnd());
sourceFile.seek(0); // reset it to the beginning
QVERIFY(targetFile.open(QIODevice::ReadOnly));
QCOMPARE(targetFile.size(), sourceFile.size());
QCOMPARE(targetFile.readAll(), sourceFile.readAll());
}
void tst_QNetworkReply::ioPutToFileFromSocket_data()
{
putToFile_data();
}
void tst_QNetworkReply::ioPutToFileFromSocket()
{
QFile file(testFileName);
QUrl url = QUrl::fromLocalFile(file.fileName());
QNetworkRequest request(url);
QFETCH(QByteArray, data);
SocketPair socketpair;
socketpair.create();
QVERIFY(socketpair.endPoints[0] && socketpair.endPoints[1]);
socketpair.endPoints[0]->write(data);
QNetworkReplyPtr reply = manager.put(QNetworkRequest(url), socketpair.endPoints[1]);
socketpair.endPoints[0]->close();
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QCOMPARE(reply->error(), QNetworkReply::NoError);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->url(), url);
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), Q_INT64_C(0));
QVERIFY(reply->readAll().isEmpty());
QVERIFY(file.open(QIODevice::ReadOnly));
QCOMPARE(file.size(), qint64(data.size()));
QByteArray contents = file.readAll();
QCOMPARE(contents, data);
}
void tst_QNetworkReply::ioPutToFileFromLocalSocket_data()
{
putToFile_data();
}
void tst_QNetworkReply::ioPutToFileFromLocalSocket()
{
QString socketname = "networkreplytest";
QLocalServer server;
if (!server.listen(socketname)) {
if (QFile::exists(server.fullServerName()))
QFile::remove(server.fullServerName());
QVERIFY(server.listen(socketname));
}
QLocalSocket active;
active.connectToServer(socketname);
QVERIFY2(server.waitForNewConnection(10), server.errorString().toLatin1().constData());
QVERIFY2(active.waitForConnected(10), active.errorString().toLatin1().constData());
QVERIFY2(server.hasPendingConnections(), server.errorString().toLatin1().constData());
QLocalSocket *passive = server.nextPendingConnection();
QFile file(testFileName);
QUrl url = QUrl::fromLocalFile(file.fileName());
QNetworkRequest request(url);
QFETCH(QByteArray, data);
active.write(data);
active.close();
QNetworkReplyPtr reply = manager.put(QNetworkRequest(url), passive);
passive->setParent(reply);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QCOMPARE(reply->error(), QNetworkReply::NoError);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->url(), url);
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), Q_INT64_C(0));
QVERIFY(reply->readAll().isEmpty());
QVERIFY(file.open(QIODevice::ReadOnly));
QCOMPARE(file.size(), qint64(data.size()));
QByteArray contents = file.readAll();
QCOMPARE(contents, data);
}
void tst_QNetworkReply::ioPutToFileFromProcess_data()
{
putToFile_data();
}
void tst_QNetworkReply::ioPutToFileFromProcess()
{
#if defined(Q_OS_WINCE) || defined (Q_OS_SYMBIAN)
QSKIP("Currently no stdin/out supported for Windows CE / Symbian OS", SkipAll);
#endif
#ifdef Q_OS_WIN
if (qstrcmp(QTest::currentDataTag(), "small") == 0)
QSKIP("When passing a CR-LF-LF sequence through Windows stdio, it gets converted, "
"so this test fails. Disabled on Windows", SkipSingle);
#endif
#if defined(QT_NO_PROCESS)
QSKIP("Qt was compiled with QT_NO_PROCESS", SkipAll);
#else
QFile file(testFileName);
QUrl url = QUrl::fromLocalFile(file.fileName());
QNetworkRequest request(url);
QFETCH(QByteArray, data);
QProcess process;
process.start("echo/echo all");
process.write(data);
process.closeWriteChannel();
QNetworkReplyPtr reply = manager.put(QNetworkRequest(url), &process);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->url(), url);
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), Q_INT64_C(0));
QVERIFY(reply->readAll().isEmpty());
QVERIFY(file.open(QIODevice::ReadOnly));
QCOMPARE(file.size(), qint64(data.size()));
QByteArray contents = file.readAll();
QCOMPARE(contents, data);
#endif
}
void tst_QNetworkReply::ioPutToFtpFromFile_data()
{
ioPutToFileFromFile_data();
}
void tst_QNetworkReply::ioPutToFtpFromFile()
{
QFETCH(QString, fileName);
QFile sourceFile(fileName);
QVERIFY(sourceFile.open(QIODevice::ReadOnly));
QUrl url("ftp://" + QtNetworkSettings::serverName());
url.setPath(QString("/qtest/upload/qnetworkaccess-ioPutToFtpFromFile-%1-%2")
.arg(QTest::currentDataTag())
.arg(uniqueExtension));
QNetworkRequest request(url);
QNetworkReplyPtr reply = manager.put(request, &sourceFile);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->url(), url);
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), Q_INT64_C(0));
QVERIFY(reply->readAll().isEmpty());
QVERIFY(sourceFile.atEnd());
sourceFile.seek(0); // reset it to the beginning
// download the file again from FTP to make sure it was uploaded
// correctly
QFtp ftp;
ftp.connectToHost(url.host());
ftp.login();
ftp.get(url.path());
QObject::connect(&ftp, SIGNAL(done(bool)), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(3);
QObject::disconnect(&ftp, SIGNAL(done(bool)), &QTestEventLoop::instance(), SLOT(exitLoop()));
QByteArray uploaded = ftp.readAll();
QCOMPARE(qint64(uploaded.size()), sourceFile.size());
QCOMPARE(uploaded, sourceFile.readAll());
ftp.close();
QObject::connect(&ftp, SIGNAL(done(bool)), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QObject::disconnect(&ftp, SIGNAL(done(bool)), &QTestEventLoop::instance(), SLOT(exitLoop()));
}
void tst_QNetworkReply::ioPutToHttpFromFile_data()
{
ioPutToFileFromFile_data();
}
void tst_QNetworkReply::ioPutToHttpFromFile()
{
QFETCH(QString, fileName);
QFile sourceFile(fileName);
QVERIFY(sourceFile.open(QIODevice::ReadOnly));
QUrl url("http://" + QtNetworkSettings::serverName());
url.setPath(QString("/dav/qnetworkaccess-ioPutToHttpFromFile-%1-%2")
.arg(QTest::currentDataTag())
.arg(uniqueExtension));
QNetworkRequest request(url);
QNetworkReplyPtr reply = manager.put(request, &sourceFile);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->url(), url);
QCOMPARE(reply->error(), QNetworkReply::NoError);
// verify that the HTTP status code is 201 Created
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 201);
QVERIFY(sourceFile.atEnd());
sourceFile.seek(0); // reset it to the beginning
// download the file again from HTTP to make sure it was uploaded
// correctly
reply = manager.get(request);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->url(), url);
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok
QCOMPARE(reply->readAll(), sourceFile.readAll());
}
void tst_QNetworkReply::ioPostToHttpFromFile_data()
{
ioPutToFileFromFile_data();
}
void tst_QNetworkReply::ioPostToHttpFromFile()
{
QFETCH(QString, fileName);
QFile sourceFile(fileName);
QVERIFY(sourceFile.open(QIODevice::ReadOnly));
QUrl url("http://" + QtNetworkSettings::serverName() + "/qtest/cgi-bin/md5sum.cgi");
QNetworkRequest request(url);
QNetworkReplyPtr reply = manager.post(request, &sourceFile);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->url(), url);
QCOMPARE(reply->error(), QNetworkReply::NoError);
// verify that the HTTP status code is 200 Ok
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QVERIFY(sourceFile.atEnd());
sourceFile.seek(0); // reset it to the beginning
QCOMPARE(reply->readAll().trimmed(), md5sum(sourceFile.readAll()).toHex());
}
void tst_QNetworkReply::ioPostToHttpFromSocket_data()
{
QTest::addColumn<QByteArray>("data");
QTest::addColumn<QByteArray>("md5sum");
QTest::addColumn<QUrl>("url");
QTest::addColumn<QNetworkProxy>("proxy");
QTest::addColumn<int>("authenticationRequiredCount");
QTest::addColumn<int>("proxyAuthenticationRequiredCount");
for (int i = 0; i < proxies.count(); ++i)
for (int auth = 0; auth < 2; ++auth) {
QUrl url;
if (auth)
url = "http://" + QtNetworkSettings::serverName() + "/qtest/protected/cgi-bin/md5sum.cgi";
else
url = "http://" + QtNetworkSettings::serverName() + "/qtest/cgi-bin/md5sum.cgi";
QNetworkProxy proxy = proxies.at(i).proxy;
QByteArray testsuffix = QByteArray(auth ? "+auth" : "") + proxies.at(i).tag;
int proxyauthcount = proxies.at(i).requiresAuthentication;
QByteArray data;
data = "";
QTest::newRow("empty" + testsuffix) << data << md5sum(data) << url << proxy << auth << proxyauthcount;
data = "This is a normal message.";
QTest::newRow("generic" + testsuffix) << data << md5sum(data) << url << proxy << auth << proxyauthcount;
data = "This is a message to show that Qt rocks!\r\n\n";
QTest::newRow("small" + testsuffix) << data << md5sum(data) << url << proxy << auth << proxyauthcount;
data = QByteArray("abcd\0\1\2\abcd",12);
QTest::newRow("with-nul" + testsuffix) << data << md5sum(data) << url << proxy << auth << proxyauthcount;
data = QByteArray(4097, '\4');
QTest::newRow("4k+1" + testsuffix) << data << md5sum(data) << url << proxy << auth << proxyauthcount;
data = QByteArray(128*1024+1, '\177');
QTest::newRow("128k+1" + testsuffix) << data << md5sum(data) << url << proxy << auth << proxyauthcount;
}
}
void tst_QNetworkReply::ioPostToHttpFromSocket()
{
qRegisterMetaType<QNetworkProxy>(); // for QSignalSpy
qRegisterMetaType<QAuthenticator *>();
qRegisterMetaType<QNetworkReply *>();
QFETCH(QByteArray, data);
QFETCH(QUrl, url);
QFETCH(QNetworkProxy, proxy);
SocketPair socketpair;
socketpair.create();
QVERIFY(socketpair.endPoints[0] && socketpair.endPoints[1]);
socketpair.endPoints[0]->write(data);
QNetworkRequest request(url);
manager.setProxy(proxy);
QNetworkReplyPtr reply = manager.post(QNetworkRequest(url), socketpair.endPoints[1]);
socketpair.endPoints[0]->close();
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
connect(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
connect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*)));
QSignalSpy authenticationRequiredSpy(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)));
QSignalSpy proxyAuthenticationRequiredSpy(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
QTestEventLoop::instance().enterLoop(12);
disconnect(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
this, SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
disconnect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
this, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*)));
QCOMPARE(reply->error(), QNetworkReply::NoError);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->url(), url);
QCOMPARE(reply->error(), QNetworkReply::NoError);
// verify that the HTTP status code is 200 Ok
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QCOMPARE(reply->readAll().trimmed(), md5sum(data).toHex());
QTEST(authenticationRequiredSpy.count(), "authenticationRequiredCount");
QTEST(proxyAuthenticationRequiredSpy.count(), "proxyAuthenticationRequiredCount");
}
// this tests checks if rewinding the POST-data to some place in the middle
// worked.
void tst_QNetworkReply::ioPostToHttpFromMiddleOfFileToEnd()
{
QFile sourceFile(SRCDIR "/rfc3252.txt");
QVERIFY(sourceFile.open(QIODevice::ReadOnly));
// seeking to the middle
sourceFile.seek(sourceFile.size() / 2);
QUrl url = "http://" + QtNetworkSettings::serverName() + "/qtest/protected/cgi-bin/md5sum.cgi";
QNetworkRequest request(url);
QNetworkReplyPtr reply = manager.post(QNetworkRequest(url), &sourceFile);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
connect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*)));
QTestEventLoop::instance().enterLoop(2);
disconnect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
this, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*)));
QVERIFY(!QTestEventLoop::instance().timeout());
// compare half data
sourceFile.seek(sourceFile.size() / 2);
QByteArray data = sourceFile.readAll();
QCOMPARE(reply->readAll().trimmed(), md5sum(data).toHex());
}
void tst_QNetworkReply::ioPostToHttpFromMiddleOfFileFiveBytes()
{
QFile sourceFile(SRCDIR "/rfc3252.txt");
QVERIFY(sourceFile.open(QIODevice::ReadOnly));
// seeking to the middle
sourceFile.seek(sourceFile.size() / 2);
QUrl url = "http://" + QtNetworkSettings::serverName() + "/qtest/protected/cgi-bin/md5sum.cgi";
QNetworkRequest request(url);
// only send 5 bytes
request.setHeader(QNetworkRequest::ContentLengthHeader, 5);
QVERIFY(request.header(QNetworkRequest::ContentLengthHeader).isValid());
QNetworkReplyPtr reply = manager.post(request, &sourceFile);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
connect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*)));
QTestEventLoop::instance().enterLoop(2);
disconnect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
this, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*)));
QVERIFY(!QTestEventLoop::instance().timeout());
// compare half data
sourceFile.seek(sourceFile.size() / 2);
QByteArray data = sourceFile.read(5);
QCOMPARE(reply->readAll().trimmed(), md5sum(data).toHex());
}
void tst_QNetworkReply::ioPostToHttpFromMiddleOfQBufferFiveBytes()
{
// test needed since a QBuffer goes with a different codepath than the QFile
// tested in ioPostToHttpFromMiddleOfFileFiveBytes
QBuffer uploadBuffer;
uploadBuffer.open(QIODevice::ReadWrite);
uploadBuffer.write("1234567890");
uploadBuffer.seek(5);
QUrl url = "http://" + QtNetworkSettings::serverName() + "/qtest/protected/cgi-bin/md5sum.cgi";
QNetworkRequest request(url);
QNetworkReplyPtr reply = manager.post(request, &uploadBuffer);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
connect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*)));
QTestEventLoop::instance().enterLoop(2);
disconnect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
this, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*)));
QVERIFY(!QTestEventLoop::instance().timeout());
// compare half data
uploadBuffer.seek(5);
QByteArray data = uploadBuffer.read(5);
QCOMPARE(reply->readAll().trimmed(), md5sum(data).toHex());
}
void tst_QNetworkReply::ioPostToHttpNoBufferFlag()
{
QByteArray data = QByteArray("daaaaaaataaaaaaa");
// create a sequential QIODevice by feeding the data into a local TCP server
SocketPair socketpair;
socketpair.create();
QVERIFY(socketpair.endPoints[0] && socketpair.endPoints[1]);
socketpair.endPoints[0]->write(data);
QUrl url = "http://" + QtNetworkSettings::serverName() + "/qtest/protected/cgi-bin/md5sum.cgi";
QNetworkRequest request(url);
// disallow buffering
request.setAttribute(QNetworkRequest::DoNotBufferUploadDataAttribute, true);
request.setHeader(QNetworkRequest::ContentLengthHeader, data.size());
QNetworkReplyPtr reply = manager.post(request, socketpair.endPoints[1]);
socketpair.endPoints[0]->close();
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
connect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*)));
QTestEventLoop::instance().enterLoop(2);
disconnect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
this, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*)));
// verify: error code is QNetworkReply::ContentReSendError
QCOMPARE(reply->error(), QNetworkReply::ContentReSendError);
}
#ifndef QT_NO_OPENSSL
class SslServer : public QTcpServer {
Q_OBJECT
public:
SslServer() : socket(0) {};
void incomingConnection(int socketDescriptor) {
QSslSocket *serverSocket = new QSslSocket;
serverSocket->setParent(this);
if (serverSocket->setSocketDescriptor(socketDescriptor)) {
connect(serverSocket, SIGNAL(encrypted()), this, SLOT(encryptedSlot()));
serverSocket->setProtocol(QSsl::AnyProtocol);
connect(serverSocket, SIGNAL(sslErrors(const QList<QSslError>&)), serverSocket, SLOT(ignoreSslErrors()));
serverSocket->setLocalCertificate (SRCDIR "/certs/server.pem");
serverSocket->setPrivateKey (SRCDIR "/certs/server.key");
serverSocket->startServerEncryption();
} else {
delete serverSocket;
}
}
signals:
void newEncryptedConnection();
public slots:
void encryptedSlot() {
socket = (QSslSocket*) sender();
emit newEncryptedConnection();
}
public:
QSslSocket *socket;
};
// very similar to ioPostToHttpUploadProgress but for SSL
void tst_QNetworkReply::ioPostToHttpsUploadProgress()
{
QFile sourceFile(SRCDIR "/bigfile");
QVERIFY(sourceFile.open(QIODevice::ReadOnly));
// emulate a minimal https server
SslServer server;
server.listen(QHostAddress(QHostAddress::LocalHost), 0);
// create the request
QUrl url = QUrl(QString("https://127.0.0.1:%1/").arg(server.serverPort()));
QNetworkRequest request(url);
QNetworkReplyPtr reply = manager.post(request, &sourceFile);
QSignalSpy spy(reply, SIGNAL(uploadProgress(qint64,qint64)));
connect(&server, SIGNAL(newEncryptedConnection()), &QTestEventLoop::instance(), SLOT(exitLoop()));
connect(reply, SIGNAL(sslErrors(const QList<QSslError>&)), reply, SLOT(ignoreSslErrors()));
// get the request started and the incoming socket connected
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QTcpSocket *incomingSocket = server.socket;
QVERIFY(incomingSocket);
disconnect(&server, SIGNAL(newEncryptedConnection()), &QTestEventLoop::instance(), SLOT(exitLoop()));
incomingSocket->setReadBufferSize(1*1024);
QTestEventLoop::instance().enterLoop(2);
// some progress should have been made
QList<QVariant> args = spy.last();
qDebug() << "tst_QNetworkReply::ioPostToHttpsUploadProgress"
<< args.at(0).toLongLong()
<< sourceFile.size()
<< spy.size();
QVERIFY(!args.isEmpty());
QVERIFY(args.at(0).toLongLong() > 0);
// FIXME this is where it messes up
QEXPECT_FAIL("", "Either the readBufferSize of QSslSocket is broken or we do upload too much. Hm.", Abort);
QVERIFY(args.at(0).toLongLong() != sourceFile.size());
incomingSocket->setReadBufferSize(32*1024);
incomingSocket->read(16*1024);
QTestEventLoop::instance().enterLoop(2);
// some more progress than before
QList<QVariant> args2 = spy.last();
QVERIFY(!args2.isEmpty());
QVERIFY(args2.at(0).toLongLong() > args.at(0).toLongLong());
// set the read buffer to unlimited
incomingSocket->setReadBufferSize(0);
QTestEventLoop::instance().enterLoop(10);
// progress should be finished
QList<QVariant> args3 = spy.last();
QVERIFY(!args3.isEmpty());
QVERIFY(args3.at(0).toLongLong() > args2.at(0).toLongLong());
QCOMPARE(args3.at(0).toLongLong(), args3.at(1).toLongLong());
QCOMPARE(args3.at(0).toLongLong(), sourceFile.size());
// after sending this, the QNAM should emit finished()
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
incomingSocket->write("HTTP/1.0 200 OK\r\n");
incomingSocket->write("Content-Length: 0\r\n");
incomingSocket->write("\r\n");
QTestEventLoop::instance().enterLoop(10);
// not timeouted -> finished() was emitted
QVERIFY(!QTestEventLoop::instance().timeout());
incomingSocket->close();
server.close();
}
#endif
void tst_QNetworkReply::ioPostToHttpUploadProgress()
{
QFile sourceFile(SRCDIR "/bigfile");
QVERIFY(sourceFile.open(QIODevice::ReadOnly));
// emulate a minimal http server
QTcpServer server;
server.listen(QHostAddress(QHostAddress::LocalHost), 0);
// create the request
QUrl url = QUrl(QString("http://127.0.0.1:%1/").arg(server.serverPort()));
QNetworkRequest request(url);
QNetworkReplyPtr reply = manager.post(request, &sourceFile);
QSignalSpy spy(reply, SIGNAL(uploadProgress(qint64,qint64)));
connect(&server, SIGNAL(newConnection()), &QTestEventLoop::instance(), SLOT(exitLoop()));
// get the request started and the incoming socket connected
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QTcpSocket *incomingSocket = server.nextPendingConnection();
QVERIFY(incomingSocket);
disconnect(&server, SIGNAL(newConnection()), &QTestEventLoop::instance(), SLOT(exitLoop()));
incomingSocket->setReadBufferSize(1*1024);
QTestEventLoop::instance().enterLoop(2);
// some progress should have been made
QList<QVariant> args = spy.last();
QVERIFY(!args.isEmpty());
QVERIFY(args.at(0).toLongLong() > 0);
incomingSocket->setReadBufferSize(32*1024);
incomingSocket->read(16*1024);
QTestEventLoop::instance().enterLoop(2);
// some more progress than before
QList<QVariant> args2 = spy.last();
QVERIFY(!args2.isEmpty());
QVERIFY(args2.at(0).toLongLong() > args.at(0).toLongLong());
// set the read buffer to unlimited
incomingSocket->setReadBufferSize(0);
QTestEventLoop::instance().enterLoop(10);
// progress should be finished
QList<QVariant> args3 = spy.last();
QVERIFY(!args3.isEmpty());
QVERIFY(args3.at(0).toLongLong() > args2.at(0).toLongLong());
QCOMPARE(args3.at(0).toLongLong(), args3.at(1).toLongLong());
QCOMPARE(args3.at(0).toLongLong(), sourceFile.size());
// after sending this, the QNAM should emit finished()
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
incomingSocket->write("HTTP/1.0 200 OK\r\n");
incomingSocket->write("Content-Length: 0\r\n");
incomingSocket->write("\r\n");
QTestEventLoop::instance().enterLoop(10);
// not timeouted -> finished() was emitted
QVERIFY(!QTestEventLoop::instance().timeout());
incomingSocket->close();
server.close();
}
void tst_QNetworkReply::ioPostToHttpEmptyUploadProgress()
{
QByteArray ba;
ba.resize(0);
QBuffer buffer(&ba,0);
QVERIFY(buffer.open(QIODevice::ReadOnly));
// emulate a minimal http server
QTcpServer server;
server.listen(QHostAddress(QHostAddress::LocalHost), 0);
// create the request
QUrl url = QUrl(QString("http://127.0.0.1:%1/").arg(server.serverPort()));
QNetworkRequest request(url);
QNetworkReplyPtr reply = manager.post(request, &buffer);
QSignalSpy spy(reply, SIGNAL(uploadProgress(qint64,qint64)));
connect(&server, SIGNAL(newConnection()), &QTestEventLoop::instance(), SLOT(exitLoop()));
// get the request started and the incoming socket connected
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QTcpSocket *incomingSocket = server.nextPendingConnection();
QVERIFY(incomingSocket);
// after sending this, the QNAM should emit finished()
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
incomingSocket->write("HTTP/1.0 200 OK\r\n");
incomingSocket->write("Content-Length: 0\r\n");
incomingSocket->write("\r\n");
incomingSocket->flush();
QTestEventLoop::instance().enterLoop(10);
// not timeouted -> finished() was emitted
QVERIFY(!QTestEventLoop::instance().timeout());
// final check: only 1 uploadProgress has been emitted
QVERIFY(spy.length() == 1);
QList<QVariant> args = spy.last();
QVERIFY(!args.isEmpty());
QCOMPARE(args.at(0).toLongLong(), buffer.size());
QCOMPARE(args.at(0).toLongLong(), buffer.size());
incomingSocket->close();
server.close();
}
void tst_QNetworkReply::lastModifiedHeaderForFile()
{
QFileInfo fileInfo(SRCDIR "/bigfile");
QVERIFY(fileInfo.exists());
QUrl url = QUrl::fromLocalFile(fileInfo.filePath());
QNetworkRequest request(url);
QNetworkReplyPtr reply = manager.head(request);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QDateTime header = reply->header(QNetworkRequest::LastModifiedHeader).toDateTime();
QCOMPARE(header, fileInfo.lastModified());
}
void tst_QNetworkReply::lastModifiedHeaderForHttp()
{
// Tue, 22 May 2007 12:04:57 GMT according to webserver
QUrl url = "http://" + QtNetworkSettings::serverName() + "/gif/fluke.gif";
QNetworkRequest request(url);
QNetworkReplyPtr reply = manager.head(request);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QDateTime header = reply->header(QNetworkRequest::LastModifiedHeader).toDateTime();
QDateTime realDate = QDateTime::fromString("2007-05-22T12:04:57", Qt::ISODate);
realDate.setTimeSpec(Qt::UTC);
QCOMPARE(header, realDate);
}
void tst_QNetworkReply::httpCanReadLine()
{
QNetworkRequest request(QUrl("http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt"));
QNetworkReplyPtr reply = manager.get(request);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->error(), QNetworkReply::NoError);
QVERIFY(reply->canReadLine());
QVERIFY(!reply->readAll().isEmpty());
QVERIFY(!reply->canReadLine());
}
void tst_QNetworkReply::rateControl_data()
{
QTest::addColumn<int>("rate");
QTest::newRow("15") << 15;
QTest::newRow("40") << 40;
QTest::newRow("73") << 73;
QTest::newRow("80") << 80;
QTest::newRow("125") << 125;
QTest::newRow("250") << 250;
QTest::newRow("1024") << 1024;
}
void tst_QNetworkReply::rateControl()
{
QSKIP("Test disabled -- only for manual purposes", SkipAll);
// this function tests that we aren't reading from the network
// faster than the data is being consumed.
QFETCH(int, rate);
// ask for 20 seconds worth of data
FastSender sender(20 * rate * 1024);
QNetworkRequest request("debugpipe://localhost:" + QString::number(sender.serverPort()));
QNetworkReplyPtr reply = manager.get(request);
reply->setReadBufferSize(32768);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
RateControlledReader reader(reply, rate);
// this test is designed to run for 25 seconds at most
QTime loopTime;
loopTime.start();
QTestEventLoop::instance().enterLoop(40);
int elapsedTime = loopTime.elapsed();
qDebug() << "tst_QNetworkReply::rateControl" << "send rate:" << sender.transferRate;
qDebug() << "tst_QNetworkReply::rateControl" << "receive rate:" << reader.totalBytesRead * 1000 / elapsedTime
<< "(it received" << reader.totalBytesRead << "bytes in" << elapsedTime << "ms)";
sender.wait();
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->url(), request.url());
QCOMPARE(reply->error(), QNetworkReply::NoError);
QVERIFY(sender.transferRate != -1);
int minRate = rate * 1024 * 9 / 10;
int maxRate = rate * 1024 * 11 / 10;
QVERIFY(sender.transferRate >= minRate);
QVERIFY(sender.transferRate <= maxRate);
}
void tst_QNetworkReply::downloadProgress_data()
{
QTest::addColumn<int>("loopCount");
QTest::newRow("empty") << 0;
QTest::newRow("small") << 4;
#ifndef Q_OS_SYMBIAN
QTest::newRow("big") << 4096;
#else
// it can run even with 4096
// but it takes lot time
//especially on emulator
QTest::newRow("big") << 1024;
#endif
}
void tst_QNetworkReply::downloadProgress()
{
QTcpServer server;
QVERIFY(server.listen());
QNetworkRequest request("debugpipe://127.0.0.1:" + QString::number(server.serverPort()) + "/?bare=1");
QNetworkReplyPtr reply = manager.get(request);
QSignalSpy spy(reply, SIGNAL(downloadProgress(qint64,qint64)));
connect(reply, SIGNAL(downloadProgress(qint64,qint64)),
&QTestEventLoop::instance(), SLOT(exitLoop()));
QVERIFY(spy.isValid());
QVERIFY(!reply->isFinished());
QVERIFY(reply->isRunning());
QCoreApplication::instance()->processEvents();
if (!server.hasPendingConnections())
server.waitForNewConnection(1000);
QVERIFY(server.hasPendingConnections());
QCOMPARE(spy.count(), 0);
QByteArray data(128, 'a');
QTcpSocket *sender = server.nextPendingConnection();
QVERIFY(sender);
QFETCH(int, loopCount);
for (int i = 1; i <= loopCount; ++i) {
sender->write(data);
QVERIFY2(sender->waitForBytesWritten(2000), "Network timeout");
spy.clear();
QTestEventLoop::instance().enterLoop(2);
QVERIFY(!QTestEventLoop::instance().timeout());
QVERIFY(spy.count() > 0);
QVERIFY(!reply->isFinished());
QVERIFY(reply->isRunning());
QList<QVariant> args = spy.last();
QCOMPARE(args.at(0).toInt(), i*data.size());
QCOMPARE(args.at(1).toInt(), -1);
}
// close the connection:
delete sender;
spy.clear();
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(reply->error(), QNetworkReply::NoError);
QVERIFY(!QTestEventLoop::instance().timeout());
QVERIFY(spy.count() > 0);
QVERIFY(!reply->isRunning());
QVERIFY(reply->isFinished());
QList<QVariant> args = spy.last();
QCOMPARE(args.at(0).toInt(), loopCount * data.size());
QCOMPARE(args.at(1).toInt(), loopCount * data.size());
}
void tst_QNetworkReply::uploadProgress_data()
{
putToFile_data();
}
void tst_QNetworkReply::uploadProgress()
{
QFETCH(QByteArray, data);
QTcpServer server;
QVERIFY(server.listen());
QNetworkRequest request("debugpipe://127.0.0.1:" + QString::number(server.serverPort()) + "/?bare=1");
QNetworkReplyPtr reply = manager.put(request, data);
QSignalSpy spy(reply, SIGNAL(uploadProgress(qint64,qint64)));
QSignalSpy finished(reply, SIGNAL(finished()));
QVERIFY(spy.isValid());
QVERIFY(finished.isValid());
QCoreApplication::instance()->processEvents();
if (!server.hasPendingConnections())
server.waitForNewConnection(1000);
QVERIFY(server.hasPendingConnections());
QTcpSocket *receiver = server.nextPendingConnection();
if (finished.count() == 0) {
// it's not finished yet, so wait for it to be
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(2);
QVERIFY(!QTestEventLoop::instance().timeout());
}
delete receiver;
QVERIFY(finished.count() > 0);
QVERIFY(spy.count() > 0);
QList<QVariant> args = spy.last();
QCOMPARE(args.at(0).toInt(), data.size());
QCOMPARE(args.at(1).toInt(), data.size());
}
void tst_QNetworkReply::chaining_data()
{
putToFile_data();
}
void tst_QNetworkReply::chaining()
{
QTemporaryFile sourceFile(QDir::currentPath() + "/temp-XXXXXX");
sourceFile.setAutoRemove(true);
QVERIFY(sourceFile.open());
QFETCH(QByteArray, data);
QVERIFY(sourceFile.write(data) == data.size());
sourceFile.flush();
QCOMPARE(sourceFile.size(), qint64(data.size()));
QNetworkRequest request(QUrl::fromLocalFile(sourceFile.fileName()));
QNetworkReplyPtr getReply = manager.get(request);
QFile targetFile(testFileName);
QUrl url = QUrl::fromLocalFile(targetFile.fileName());
request.setUrl(url);
QNetworkReplyPtr putReply = manager.put(request, getReply);
connect(putReply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(getReply->url(), QUrl::fromLocalFile(sourceFile.fileName()));
QCOMPARE(getReply->error(), QNetworkReply::NoError);
QCOMPARE(getReply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), sourceFile.size());
QCOMPARE(putReply->url(), url);
QCOMPARE(putReply->error(), QNetworkReply::NoError);
QCOMPARE(putReply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), Q_INT64_C(0));
QVERIFY(putReply->readAll().isEmpty());
QVERIFY(sourceFile.atEnd());
sourceFile.seek(0); // reset it to the beginning
QVERIFY(targetFile.open(QIODevice::ReadOnly));
QCOMPARE(targetFile.size(), sourceFile.size());
QCOMPARE(targetFile.readAll(), sourceFile.readAll());
}
void tst_QNetworkReply::receiveCookiesFromHttp_data()
{
QTest::addColumn<QString>("cookieString");
QTest::addColumn<QList<QNetworkCookie> >("expectedCookiesFromHttp");
QTest::addColumn<QList<QNetworkCookie> >("expectedCookiesInJar");
QTest::newRow("empty") << "" << QList<QNetworkCookie>() << QList<QNetworkCookie>();
QList<QNetworkCookie> header, jar;
QNetworkCookie cookie("a", "b");
header << cookie;
cookie.setDomain(QtNetworkSettings::serverName());
cookie.setPath("/qtest/cgi-bin/");
jar << cookie;
QTest::newRow("simple-cookie") << "a=b" << header << jar;
header << QNetworkCookie("c", "d");
cookie.setName("c");
cookie.setValue("d");
jar << cookie;
QTest::newRow("two-cookies") << "a=b, c=d" << header << jar;
QTest::newRow("two-cookies-2") << "a=b\nc=d" << header << jar;
header.clear();
jar.clear();
cookie = QNetworkCookie("a", "b");
cookie.setPath("/not/part-of-path");
header << cookie;
cookie.setDomain(QtNetworkSettings::serverName());
jar << cookie;
QTest::newRow("invalid-cookie-path") << "a=b; path=/not/part-of-path" << header << jar;
jar.clear();
cookie = QNetworkCookie("a", "b");
cookie.setDomain(".example.com");
header.clear();
header << cookie;
QTest::newRow("invalid-cookie-domain") << "a=b; domain=.example.com" << header << jar;
}
void tst_QNetworkReply::receiveCookiesFromHttp()
{
QFETCH(QString, cookieString);
QByteArray data = cookieString.toLatin1() + '\n';
QUrl url("http://" + QtNetworkSettings::serverName() + "/qtest/cgi-bin/set-cookie.cgi");
QNetworkRequest request(url);
QNetworkReplyPtr reply;
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::PostOperation, request, reply, data));
QCOMPARE(reply->url(), url);
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok
QList<QNetworkCookie> setCookies =
qvariant_cast<QList<QNetworkCookie> >(reply->header(QNetworkRequest::SetCookieHeader));
QTEST(setCookies, "expectedCookiesFromHttp");
QTEST(cookieJar->allCookies(), "expectedCookiesInJar");
}
void tst_QNetworkReply::sendCookies_data()
{
QTest::addColumn<QList<QNetworkCookie> >("cookiesToSet");
QTest::addColumn<QString>("expectedCookieString");
QList<QNetworkCookie> list;
QTest::newRow("empty") << list << "";
QNetworkCookie cookie("a", "b");
cookie.setPath("/");
cookie.setDomain("example.com");
list << cookie;
QTest::newRow("no-match-domain") << list << "";
cookie.setDomain(QtNetworkSettings::serverName());
cookie.setPath("/something/else");
list << cookie;
QTest::newRow("no-match-path") << list << "";
cookie.setPath("/");
list << cookie;
QTest::newRow("simple-cookie") << list << "a=b";
cookie.setPath("/qtest");
cookie.setValue("longer");
list << cookie;
QTest::newRow("two-cookies") << list << "a=longer; a=b";
list.clear();
cookie = QNetworkCookie("a", "b");
cookie.setPath("/");
cookie.setDomain("." + QtNetworkSettings::serverDomainName());
list << cookie;
QTest::newRow("domain-match") << list << "a=b";
// but it shouldn't match this:
cookie.setDomain(QtNetworkSettings::serverDomainName());
list << cookie;
QTest::newRow("domain-match-2") << list << "a=b";
}
void tst_QNetworkReply::sendCookies()
{
QFETCH(QString, expectedCookieString);
QFETCH(QList<QNetworkCookie>, cookiesToSet);
cookieJar->setAllCookies(cookiesToSet);
QUrl url("http://" + QtNetworkSettings::serverName() + "/qtest/cgi-bin/get-cookie.cgi");
QNetworkRequest request(url);
QNetworkReplyPtr reply;
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::GetOperation, request, reply));
QCOMPARE(reply->url(), url);
QCOMPARE(reply->error(), QNetworkReply::NoError);
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok
QCOMPARE(QString::fromLatin1(reply->readAll()).trimmed(), expectedCookieString);
}
void tst_QNetworkReply::nestedEventLoops_slot()
{
QEventLoop subloop;
// 16 seconds: fluke times out in 15 seconds, which triggers a QTcpSocket error
QTimer::singleShot(16000, &subloop, SLOT(quit()));
subloop.exec();
QTestEventLoop::instance().exitLoop();
}
void tst_QNetworkReply::nestedEventLoops()
{
// Slightly fragile test, it may not be testing anything
// This is certifying that we're not running into the same issue
// that QHttp had (task 200432): the QTcpSocket connection is
// closed by the remote end because of the kept-alive HTTP
// connection timed out.
//
// The exact time required for this to happen is not exactly
// defined. Our server (Apache httpd) times out after 15
// seconds. (see above)
qDebug("Takes 16 seconds to run, please wait");
qRegisterMetaType<QNetworkReply::NetworkError>();
QUrl url("http://" + QtNetworkSettings::serverName());
QNetworkRequest request(url);
QNetworkReplyPtr reply = manager.get(request);
QSignalSpy finishedspy(reply, SIGNAL(finished()));
QSignalSpy errorspy(reply, SIGNAL(error(QNetworkReply::NetworkError)));
connect(reply, SIGNAL(finished()), SLOT(nestedEventLoops_slot()));
QTestEventLoop::instance().enterLoop(20);
QVERIFY2(!QTestEventLoop::instance().timeout(), "Network timeout");
QCOMPARE(finishedspy.count(), 1);
QCOMPARE(errorspy.count(), 0);
}
void tst_QNetworkReply::httpProxyCommands_data()
{
QTest::addColumn<QUrl>("url");
QTest::addColumn<QByteArray>("responseToSend");
QTest::addColumn<QString>("expectedCommand");
QTest::newRow("http")
<< QUrl("http://0.0.0.0:4443/http-request")
<< QByteArray("HTTP/1.0 200 OK\r\nProxy-Connection: close\r\nContent-Length: 1\r\n\r\n1")
<< "GET http://0.0.0.0:4443/http-request HTTP/1.";
#ifndef QT_NO_OPENSSL
QTest::newRow("https")
<< QUrl("https://0.0.0.0:4443/https-request")
<< QByteArray("HTTP/1.0 200 Connection Established\r\n\r\n")
<< "CONNECT 0.0.0.0:4443 HTTP/1.";
#endif
}
void tst_QNetworkReply::httpProxyCommands()
{
QFETCH(QUrl, url);
QFETCH(QByteArray, responseToSend);
QFETCH(QString, expectedCommand);
MiniHttpServer proxyServer(responseToSend);
QNetworkProxy proxy(QNetworkProxy::HttpProxy, "127.0.0.1", proxyServer.serverPort());
manager.setProxy(proxy);
QNetworkReplyPtr reply = manager.get(QNetworkRequest(url));
manager.setProxy(QNetworkProxy());
// wait for the finished signal
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(1);
QVERIFY(!QTestEventLoop::instance().timeout());
//qDebug() << reply->error() << reply->errorString();
// we don't really care if the request succeeded
// especially since it won't succeed in the HTTPS case
// so just check that the command was correct
QString receivedHeader = proxyServer.receivedData.left(expectedCommand.length());
QCOMPARE(receivedHeader, expectedCommand);
}
void tst_QNetworkReply::proxyChange()
{
MiniHttpServer proxyServer(
"HTTP/1.0 200 OK\r\nProxy-Connection: keep-alive\r\n"
"Content-Length: 1\r\n\r\n1");
QNetworkProxy dummyProxy(QNetworkProxy::HttpProxy, "127.0.0.1", proxyServer.serverPort());
QNetworkRequest req(QUrl("http://" + QtNetworkSettings::serverName()));
proxyServer.doClose = false;
manager.setProxy(dummyProxy);
QNetworkReplyPtr reply1 = manager.get(req);
QSignalSpy finishedspy(reply1, SIGNAL(finished()));
manager.setProxy(QNetworkProxy());
QNetworkReplyPtr reply2 = manager.get(req);
connect(reply2, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
#ifdef Q_OS_SYMBIAN
// we need more time as:
// 1. running from the emulator
// 2. not perfect POSIX implementation
// 3. embedded device
QTestEventLoop::instance().enterLoop(20);
#else
QTestEventLoop::instance().enterLoop(10);
#endif
QVERIFY(!QTestEventLoop::instance().timeout());
if (finishedspy.count() == 0) {
// wait for the second reply as well
connect(reply1, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(1);
QVERIFY(!QTestEventLoop::instance().timeout());
}
// verify that the replies succeeded
QCOMPARE(reply1->error(), QNetworkReply::NoError);
QCOMPARE(reply1->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QVERIFY(reply1->size() == 1);
QCOMPARE(reply2->error(), QNetworkReply::NoError);
QCOMPARE(reply2->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QVERIFY(reply2->size() > 1);
// now try again and get an error
// this verifies that we reuse the already-open connection
proxyServer.doClose = true;
proxyServer.dataToTransmit =
"HTTP/1.0 403 Forbidden\r\nProxy-Connection: close\r\n"
"Content-Length: 1\r\n\r\n1";
manager.setProxy(dummyProxy);
QNetworkReplyPtr reply3 = manager.get(req);
connect(reply3, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(1);
QVERIFY(!QTestEventLoop::instance().timeout());
QVERIFY(int(reply3->error()) > 0);
}
void tst_QNetworkReply::authorizationError_data()
{
QTest::addColumn<QString>("url");
QTest::addColumn<int>("errorSignalCount");
QTest::addColumn<int>("finishedSignalCount");
QTest::addColumn<int>("error");
QTest::addColumn<int>("httpStatusCode");
QTest::addColumn<QString>("httpBody");
QTest::newRow("unknown-authorization-method") << "http://" + QtNetworkSettings::serverName() +
"/qtest/cgi-bin/http-unknown-authentication-method.cgi?401-authorization-required" << 1 << 1
<< int(QNetworkReply::AuthenticationRequiredError) << 401 << "authorization required";
QTest::newRow("unknown-proxy-authorization-method") << "http://" + QtNetworkSettings::serverName() +
"/qtest/cgi-bin/http-unknown-authentication-method.cgi?407-proxy-authorization-required" << 1 << 1
<< int(QNetworkReply::ProxyAuthenticationRequiredError) << 407
<< "authorization required";
}
void tst_QNetworkReply::authorizationError()
{
QFETCH(QString, url);
QNetworkRequest request(url);
QNetworkReplyPtr reply = manager.get(request);
QCOMPARE(reply->error(), QNetworkReply::NoError);
qRegisterMetaType<QNetworkReply::NetworkError>("QNetworkReply::NetworkError");
QSignalSpy errorSpy(reply, SIGNAL(error(QNetworkReply::NetworkError)));
QSignalSpy finishedSpy(reply, SIGNAL(finished()));
// now run the request:
connect(reply, SIGNAL(finished()),
&QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QFETCH(int, errorSignalCount);
QCOMPARE(errorSpy.count(), errorSignalCount);
QFETCH(int, finishedSignalCount);
QCOMPARE(finishedSpy.count(), finishedSignalCount);
QFETCH(int, error);
QCOMPARE(reply->error(), QNetworkReply::NetworkError(error));
QFETCH(int, httpStatusCode);
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), httpStatusCode);
QFETCH(QString, httpBody);
QCOMPARE(QString(reply->readAll()), httpBody);
}
void tst_QNetworkReply::httpConnectionCount()
{
QTcpServer server;
QVERIFY(server.listen());
QCoreApplication::instance()->processEvents();
for (int i = 0; i < 10; i++) {
QNetworkRequest request (QUrl("http://127.0.0.1:" + QString::number(server.serverPort()) + "/" + QString::number(i)));
QNetworkReply* reply = manager.get(request);
reply->setParent(&server);
}
int pendingConnectionCount = 0;
QTime time;
time.start();
while(pendingConnectionCount <= 20) {
QTestEventLoop::instance().enterLoop(1);
QTcpSocket *socket = server.nextPendingConnection();
while (socket != 0) {
pendingConnectionCount++;
socket->setParent(&server);
socket = server.nextPendingConnection();
}
// at max. wait 10 sec
if (time.elapsed() > 10000)
break;
}
#ifdef Q_OS_SYMBIAN
// see in qhttpnetworkconnection.cpp
// hardcoded defaultChannelCount = 3
QCOMPARE(pendingConnectionCount, 3);
#else
QCOMPARE(pendingConnectionCount, 6);
#endif
}
void tst_QNetworkReply::httpReUsingConnectionSequential_data()
{
QTest::addColumn<bool>("doDeleteLater");
QTest::newRow("deleteLater") << true;
QTest::newRow("noDeleteLater") << false;
}
void tst_QNetworkReply::httpReUsingConnectionSequential()
{
QFETCH(bool, doDeleteLater);
QByteArray response("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
MiniHttpServer server(response);
server.multiple = true;
server.doClose = false;
QUrl url;
url.setScheme("http");
url.setPort(server.serverPort());
url.setHost("127.0.0.1");
// first request
QNetworkReply* reply1 = manager.get(QNetworkRequest(url));
connect(reply1, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(2);
QVERIFY(!QTestEventLoop::instance().timeout());
QVERIFY(!reply1->error());
int reply1port = server.client->peerPort();
if (doDeleteLater)
reply1->deleteLater();
// finished received, send the next one
QNetworkReply*reply2 = manager.get(QNetworkRequest(url));
connect(reply2, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(2);
QVERIFY(!QTestEventLoop::instance().timeout());
QVERIFY(!reply2->error());
int reply2port = server.client->peerPort(); // should still be the same object
QVERIFY(reply1port > 0);
QCOMPARE(server.totalConnections, 1);
QCOMPARE(reply2port, reply1port);
if (!doDeleteLater)
reply1->deleteLater(); // only do it if it was not done earlier
reply2->deleteLater();
}
class HttpReUsingConnectionFromFinishedSlot : public QObject {
Q_OBJECT
public:
QNetworkReply* reply1;
QNetworkReply* reply2;
QUrl url;
QNetworkAccessManager manager;
public slots:
void finishedSlot() {
QVERIFY(!reply1->error());
QFETCH(bool, doDeleteLater);
if (doDeleteLater) {
reply1->deleteLater();
reply1 = 0;
}
// kick off 2nd request and exit the loop when it is done
reply2 = manager.get(QNetworkRequest(url));
reply2->setParent(this);
connect(reply2, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
}
};
void tst_QNetworkReply::httpReUsingConnectionFromFinishedSlot_data()
{
httpReUsingConnectionSequential_data();
}
void tst_QNetworkReply::httpReUsingConnectionFromFinishedSlot()
{
QByteArray response("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
MiniHttpServer server(response);
server.multiple = true;
server.doClose = false;
HttpReUsingConnectionFromFinishedSlot helper;
helper.reply1 = 0;
helper.reply2 = 0;
helper.url.setScheme("http");
helper.url.setPort(server.serverPort());
helper.url.setHost("127.0.0.1");
// first request
helper.reply1 = helper.manager.get(QNetworkRequest(helper.url));
helper.reply1->setParent(&helper);
connect(helper.reply1, SIGNAL(finished()), &helper, SLOT(finishedSlot()));
QTestEventLoop::instance().enterLoop(4);
QVERIFY(!QTestEventLoop::instance().timeout());
QVERIFY(helper.reply2);
QVERIFY(!helper.reply2->error());
QCOMPARE(server.totalConnections, 1);
}
class HttpRecursiveCreationHelper : public QObject {
Q_OBJECT
public:
HttpRecursiveCreationHelper():
QObject(0),
requestsStartedCount_finished(0),
requestsStartedCount_readyRead(0),
requestsFinishedCount(0)
{
}
QNetworkAccessManager manager;
int requestsStartedCount_finished;
int requestsStartedCount_readyRead;
int requestsFinishedCount;
public slots:
void finishedSlot() {
requestsFinishedCount++;
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
QVERIFY(!reply->error());
QVERIFY(reply->bytesAvailable() == 27906);
if (requestsFinishedCount == 60) {
QTestEventLoop::instance().exitLoop();
return;
}
if (requestsStartedCount_finished < 30) {
startOne();
requestsStartedCount_finished++;
}
reply->deleteLater();
}
void readyReadSlot() {
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
QVERIFY(!reply->error());
if (requestsStartedCount_readyRead < 30 && reply->bytesAvailable() > 27906/2) {
startOne();
requestsStartedCount_readyRead++;
}
}
void startOne() {
QUrl url = "http://" + QtNetworkSettings::serverName() + "/gif/fluke.gif";
QNetworkRequest request(url);
QNetworkReply *reply = manager.get(request);
reply->setParent(this);
connect(reply, SIGNAL(finished()), this, SLOT(finishedSlot()));
connect(reply, SIGNAL(readyRead()), this, SLOT(readyReadSlot()));
}
};
void tst_QNetworkReply::httpRecursiveCreation()
{
// this test checks if creation of new requests to the same host properly works
// from readyRead() and finished() signals
HttpRecursiveCreationHelper helper;
helper.startOne();
QTestEventLoop::instance().enterLoop(30);
QVERIFY(!QTestEventLoop::instance().timeout());
}
#ifndef QT_NO_OPENSSL
void tst_QNetworkReply::ignoreSslErrorsList_data()
{
QTest::addColumn<QString>("url");
QTest::addColumn<QList<QSslError> >("expectedSslErrors");
QTest::addColumn<QNetworkReply::NetworkError>("expectedNetworkError");
QList<QSslError> expectedSslErrors;
// apparently, because of some weird behaviour of SRCDIR, the file name below needs to start with a slash
QList<QSslCertificate> certs = QSslCertificate::fromPath(QLatin1String(SRCDIR "/certs/qt-test-server-cacert.pem"));
QSslError rightError(QSslError::SelfSignedCertificate, certs.at(0));
QSslError wrongError(QSslError::SelfSignedCertificate);
QTest::newRow("SSL-failure-empty-list") << "https://" + QtNetworkSettings::serverName() + "/index.html" << expectedSslErrors << QNetworkReply::SslHandshakeFailedError;
expectedSslErrors.append(wrongError);
QTest::newRow("SSL-failure-wrong-error") << "https://" + QtNetworkSettings::serverName() + "/index.html" << expectedSslErrors << QNetworkReply::SslHandshakeFailedError;
expectedSslErrors.append(rightError);
QTest::newRow("allErrorsInExpectedList1") << "https://" + QtNetworkSettings::serverName() + "/index.html" << expectedSslErrors << QNetworkReply::NoError;
expectedSslErrors.removeAll(wrongError);
QTest::newRow("allErrorsInExpectedList2") << "https://" + QtNetworkSettings::serverName() + "/index.html" << expectedSslErrors << QNetworkReply::NoError;
expectedSslErrors.removeAll(rightError);
QTest::newRow("SSL-failure-empty-list-again") << "https://" + QtNetworkSettings::serverName() + "/index.html" << expectedSslErrors << QNetworkReply::SslHandshakeFailedError;
}
void tst_QNetworkReply::ignoreSslErrorsList()
{
QFETCH(QString, url);
QNetworkRequest request(url);
QNetworkReplyPtr reply = manager.get(request);
QFETCH(QList<QSslError>, expectedSslErrors);
reply->ignoreSslErrors(expectedSslErrors);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QFETCH(QNetworkReply::NetworkError, expectedNetworkError);
QCOMPARE(reply->error(), expectedNetworkError);
}
void tst_QNetworkReply::ignoreSslErrorsListWithSlot_data()
{
ignoreSslErrorsList_data();
}
// this is not a test, just a slot called in the test below
void tst_QNetworkReply::ignoreSslErrorListSlot(QNetworkReply *reply, const QList<QSslError> &)
{
reply->ignoreSslErrors(storedExpectedSslErrors);
}
// do the same as in ignoreSslErrorsList, but ignore the errors in the slot
void tst_QNetworkReply::ignoreSslErrorsListWithSlot()
{
QFETCH(QString, url);
QNetworkRequest request(url);
QNetworkReplyPtr reply = manager.get(request);
QFETCH(QList<QSslError>, expectedSslErrors);
// store the errors to ignore them later in the slot connected below
storedExpectedSslErrors = expectedSslErrors;
connect(&manager, SIGNAL(sslErrors(QNetworkReply *, const QList<QSslError> &)),
this, SLOT(ignoreSslErrorListSlot(QNetworkReply *, const QList<QSslError> &)));
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QFETCH(QNetworkReply::NetworkError, expectedNetworkError);
QCOMPARE(reply->error(), expectedNetworkError);
}
#endif // QT_NO_OPENSSL
// NOTE: This test must be last testcase in tst_qnetworkreply!
void tst_QNetworkReply::parentingRepliesToTheApp()
{
QNetworkRequest request (QUrl("http://" + QtNetworkSettings::serverName()));
manager.get(request)->setParent(this); // parent to this object
manager.get(request)->setParent(qApp); // parent to the app
}
QTEST_MAIN(tst_QNetworkReply)
#include "tst_qnetworkreply.moc"
|