File: test_sftp.py

package info (click to toggle)
python-asyncssh 2.21.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 3,464 kB
  • sloc: python: 40,306; makefile: 11
file content (5867 lines) | stat: -rw-r--r-- 191,878 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
# Copyright (c) 2015-2025 by Ron Frederick <ronf@timeheart.net> and others.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v2.0 which accompanies this
# distribution and is available at:
#
#     http://www.eclipse.org/legal/epl-2.0/
#
# This program may also be made available under the following secondary
# licenses when the conditions for such availability set forth in the
# Eclipse Public License v2.0 are satisfied:
#
#    GNU General Public License, Version 2.0, or any later versions of
#    that license
#
# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
#
# Contributors:
#     Ron Frederick - initial implementation, API, and documentation

"""Unit tests for AsyncSSH SFTP client and server"""

import asyncio
import errno
import functools
import os
from pathlib import Path
import posixpath
import shutil
import stat
import sys
import time
import unittest
from unittest.mock import patch

import asyncssh

from asyncssh import SFTPError, SFTPNoSuchFile, SFTPPermissionDenied
from asyncssh import SFTPFailure, SFTPBadMessage, SFTPNoConnection
from asyncssh import SFTPConnectionLost, SFTPOpUnsupported, SFTPInvalidHandle
from asyncssh import SFTPNoSuchPath, SFTPFileAlreadyExists, SFTPWriteProtect
from asyncssh import SFTPNoMedia, SFTPNoSpaceOnFilesystem, SFTPQuotaExceeded
from asyncssh import SFTPUnknownPrincipal, SFTPLockConflict, SFTPDirNotEmpty
from asyncssh import SFTPNotADirectory, SFTPInvalidFilename, SFTPLinkLoop
from asyncssh import SFTPCannotDelete, SFTPInvalidParameter
from asyncssh import SFTPFileIsADirectory, SFTPByteRangeLockConflict
from asyncssh import SFTPByteRangeLockRefused, SFTPDeletePending
from asyncssh import SFTPFileCorrupt, SFTPOwnerInvalid, SFTPGroupInvalid
from asyncssh import SFTPNoMatchingByteRangeLock
from asyncssh import SFTPAttrs, SFTPVFSAttrs, SFTPName, SFTPServer
from asyncssh import SEEK_CUR, SEEK_END
from asyncssh import FXP_INIT, FXP_VERSION, FXP_OPEN, FXP_READ
from asyncssh import FXP_WRITE, FXP_STATUS, FXP_HANDLE, FXP_DATA
from asyncssh import FXF_WRITE, FXF_APPEND, FXF_CREAT, FXF_TRUNC
from asyncssh import FXF_CREATE_NEW, FXF_CREATE_TRUNCATE, FXF_OPEN_EXISTING
from asyncssh import FXF_OPEN_OR_CREATE, FXF_TRUNCATE_EXISTING
from asyncssh import FXF_APPEND_DATA, FXF_BLOCK_READ
from asyncssh import ACE4_READ_DATA, ACE4_WRITE_DATA, ACE4_APPEND_DATA
from asyncssh import FXR_OVERWRITE
from asyncssh import FXRP_STAT_IF_EXISTS, FXRP_STAT_ALWAYS
from asyncssh import FILEXFER_ATTR_UIDGID, FILEXFER_ATTR_OWNERGROUP
from asyncssh import FILEXFER_TYPE_REGULAR, FILEXFER_TYPE_DIRECTORY
from asyncssh import FILEXFER_TYPE_SYMLINK, FILEXFER_TYPE_SPECIAL
from asyncssh import FILEXFER_TYPE_UNKNOWN, FILEXFER_TYPE_SOCKET
from asyncssh import FILEXFER_TYPE_CHAR_DEVICE, FILEXFER_TYPE_BLOCK_DEVICE
from asyncssh import FILEXFER_TYPE_FIFO
from asyncssh import FILEXFER_ATTR_BITS_READONLY, FILEXFER_ATTR_KNOWN_TEXT
from asyncssh import FX_OK, scp

from asyncssh.misc import make_sparse_file

from asyncssh.packet import SSHPacket, String, UInt32

from asyncssh.sftp import SAFE_SFTP_READ_LEN, SAFE_SFTP_WRITE_LEN
from asyncssh.sftp import LocalFile, SFTPHandler, SFTPLimits, SFTPServerHandler

from .server import ServerTestCase
from .util import asynctest


def _getpwuid_error(uid):
    """Simulate not being able to resolve user name"""

    # pylint: disable=unused-argument

    raise KeyError


def _getgrgid_error(gid):
    """Simulate not being able to resolve group name"""

    # pylint: disable=unused-argument

    raise KeyError


def tuple_to_nsec(sec, nsec):
    """Convert seconds and remainder to nanoseconds since epoch"""

    return sec * 1_000_000_000 + (nsec or 0)


def lookup_user(uid):
    """Return the user name associated with a uid"""

    try:
        # pylint: disable=import-outside-toplevel
        import pwd

        return pwd.getpwuid(uid).pw_name
    except ImportError: # pragma: no cover
        return ''


def lookup_group(gid):
    """Return the group name associated with a gid"""

    try:
        # pylint: disable=import-outside-toplevel
        import grp

        return grp.getgrgid(gid).gr_name
    except ImportError: # pragma: no cover
        return ''


def remove(files):
    """Remove files and directories"""

    for f in files.split():
        try:
            if os.path.isdir(f) and not os.path.islink(f):
                shutil.rmtree(f)
            else:
                os.remove(f)
        except OSError:
            pass


def sftp_test(func):
    """Decorator for running SFTP tests"""

    @asynctest
    @functools.wraps(func)
    async def sftp_wrapper(self):
        """Run a test after opening an SFTP client"""

        async with self.connect() as conn:
            async with conn.start_sftp_client() as sftp:
                await func(self, sftp)

    return sftp_wrapper


def sftp_test_v4(func):
    """Decorator for running SFTPv4 tests"""

    @asynctest
    @functools.wraps(func)
    async def sftp_wrapper(self):
        """Run a test after opening an SFTP client"""

        async with self.connect() as conn:
            async with conn.start_sftp_client(sftp_version=4) as sftp:
                await func(self, sftp)

    return sftp_wrapper


def sftp_test_v5(func):
    """Decorator for running SFTPv5 tests"""

    @asynctest
    @functools.wraps(func)
    async def sftp_wrapper(self):
        """Run a test after opening an SFTP client"""

        async with self.connect() as conn:
            async with conn.start_sftp_client(sftp_version=5) as sftp:
                await func(self, sftp)

    return sftp_wrapper


def sftp_test_v6(func):
    """Decorator for running SFTPv6 tests"""

    @asynctest
    @functools.wraps(func)
    async def sftp_wrapper(self):
        """Run a test after opening an SFTP client"""

        async with self.connect() as conn:
            async with conn.start_sftp_client(sftp_version=6) as sftp:
                await func(self, sftp)

    return sftp_wrapper


class _ResetFileHandleServerHandler(SFTPServerHandler):
    """Reset file handle counter on each request to test handle-in-use check"""

    async def recv_packet(self):
        """Reset next handle counter to test handle-in-use check"""

        self._next_handle = 0
        return await super().recv_packet()


class _IncompleteMessageServerHandler(SFTPServerHandler):
    """Close the SFTP session in the middle of sending a message"""

    async def run(self):
        """Close the session after sending an incomplete message"""

        await self.recv_packet()
        self._writer.write(UInt32(1))
        self._writer.close()


class _WriteCloseServerHandler(SFTPServerHandler):
    """Close the SFTP session in the middle of a write request"""

    async def _process_packet(self, pkttype, pktid, packet):
        """Close the session when a file close request is received"""

        if pkttype == FXP_WRITE:
            await self._cleanup(None)
        else:
            await super()._process_packet(pkttype, pktid, packet)


class _ReorderReadServerHandler(SFTPServerHandler):
    """Reorder first two read requests"""

    _request = 'delay'

    async def _process_packet(self, pkttype, pktid, packet):
        """Close the session when a file close request is received"""

        if pkttype == FXP_READ:
            if self._request == 'delay':
                self._request = pkttype, pktid, packet
            elif self._request:
                await super()._process_packet(pkttype, pktid, packet)

                pkttype, pktid, packet = self._request
                await super()._process_packet(pkttype, pktid, packet)

                self._request = None
            else:
                await super()._process_packet(pkttype, pktid, packet)
        else:
            await super()._process_packet(pkttype, pktid, packet)


class _CheckPropSFTPServer(SFTPServer):
    """Return an FTP server which checks channel properties"""

    def listdir(self, _path):
        """List the contents of a directory"""

        if self.channel.get_connection() == self.connection: # pragma: no branch
            return [SFTPName(k.encode()) for k in self.env.keys()]


class _ChrootSFTPServer(SFTPServer):
    """Return an FTP server with a changed root"""

    def __init__(self, chan):
        os.mkdir('chroot')
        super().__init__(chan, 'chroot')

    def exit(self):
        """Clean up the changed root directory"""

        remove('chroot')

    def stat(self, path):
        """Get attributes of a file or directory, following symlinks"""

        return SFTPAttrs.from_local(super().stat(path))


class _OpenErrorSFTPServer(SFTPServer):
    """Return an error on file open"""

    async def open56(self, path, desired_access, flags, attrs):
        """Return an error when opening a file"""

        err = getattr(errno, path.decode('ascii'))
        raise OSError(err, os.strerror(err))


class _IOErrorSFTPServer(SFTPServer):
    """Return an I/O error during file writing"""

    async def read(self, file_obj, offset, size):
        """Return an error for reads past 4 MB in a file"""

        if offset >= 4*1024*1024:
            raise SFTPFailure('I/O error')
        else:
            return super().read(file_obj, offset, size)

    async def write(self, file_obj, offset, data):
        """Return an error for writes past 4 MB in a file"""

        if offset >= 4*1024*1024:
            raise SFTPFailure('I/O error')
        else:
            super().write(file_obj, offset, data)


class _SmallBlockSizeSFTPServer(SFTPServer):
    """Limit reads to a small block size"""

    async def read(self, file_obj, offset, size):
        """Limit reads to return no more than 4 KB at a time"""

        return super().read(file_obj, offset, min(size, 4096))


class _TruncateSFTPServer(SFTPServer):
    """Truncate a file when it is accessed, simulating a simultaneous writer"""

    async def read(self, file_obj, offset, size):
        """Truncate a file to 32 KB when a read is done"""

        os.truncate('src', 32768)

        return super().read(file_obj, offset, size)


class _NotImplSFTPServer(SFTPServer):
    """Return an error that a request is not implemented"""

    async def symlink(self, oldpath, newpath):
        """Return that symlinks aren't implemented"""

        raise NotImplementedError


class _FileTypeSFTPServer(SFTPServer):
    """Return a list of files of each possible file type"""

    _file_types = ((FILEXFER_TYPE_REGULAR,      stat.S_IFREG),
                   (FILEXFER_TYPE_DIRECTORY,    stat.S_IFDIR),
                   (FILEXFER_TYPE_SYMLINK,      stat.S_IFLNK),
                   (FILEXFER_TYPE_SPECIAL,      0xf000),
                   (FILEXFER_TYPE_UNKNOWN,      0),
                   (FILEXFER_TYPE_SOCKET,       stat.S_IFSOCK),
                   (FILEXFER_TYPE_CHAR_DEVICE,  stat.S_IFCHR),
                   (FILEXFER_TYPE_BLOCK_DEVICE, stat.S_IFBLK),
                   (FILEXFER_TYPE_FIFO,         stat.S_IFIFO))

    def listdir(self, _path):
        """List the contents of a directory"""

        return [SFTPName(str(filetype).encode('ascii'),
                         attrs=SFTPAttrs(permissions=mode))
                for filetype, mode in self._file_types]


class _LongnameSFTPServer(SFTPServer):
    """Return a fixed set of files in response to a listdir request"""

    def listdir(self, _path):
        """List the contents of a directory"""

        # pylint: disable=no-self-use

        return list((b'.',
                     b'..',
                     SFTPName(b'.file'),
                     SFTPName(b'file1'),
                     SFTPName(b'file2', b'', SFTPAttrs(permissions=0, nlink=1,
                                                       uid=0, gid=0,
                                                       size=0, mtime=0)),
                     SFTPName(b'file3', b'', SFTPAttrs(mtime=time.time())),
                     SFTPName(b'file4', 56*b' ' + b'file4')))

    def lstat(self, path):
        """Get attributes of a file, directory, or symlink"""

        return SFTPAttrs.from_local(super().lstat(path))


class _LargeDirSFTPServer(SFTPServer):
    """Return a really large listdir result"""

    async def listdir(self, path):
        """Return a really large listdir result"""

        # pylint: disable=unused-argument

        return 100000 * [SFTPName(b'a', '', SFTPAttrs())]


class _StatVFSSFTPServer(SFTPServer):
    """Return a fixed set of attributes in response to a statvfs request"""

    expected_statvfs = SFTPVFSAttrs(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)

    def statvfs(self, path):
        """Get attributes of the file system containing a file"""

        # pylint: disable=unused-argument

        return self.expected_statvfs

    def fstatvfs(self, file_obj):
        """Return attributes of the file system containing an open file"""

        # pylint: disable=unused-argument

        return self.expected_statvfs


class _ChownSFTPServer(SFTPServer):
    """Simulate file ownership changes"""

    _ownership = {}

    def setstat(self, path, attrs):
        """Get attributes of a file or directory, following symlinks"""

        self._ownership[self.map_path(path)] = \
            (attrs.uid, attrs.gid, attrs.owner, attrs.group)

    def stat(self, path):
        """Get attributes of a file or directory, following symlinks"""

        path = self.map_path(path)
        attrs = SFTPAttrs.from_local(os.stat(path))

        if path in self._ownership: # pragma: no branch
            attrs.uid, attrs.gid, attrs.owner, attrs.group = \
                self._ownership[path]

        return attrs


class _SymlinkSFTPServer(SFTPServer):
    """Implement symlink with non-standard argument order"""

    def symlink(self, oldpath, newpath):
        """Create a symbolic link"""

        # pylint: disable=arguments-out-of-order
        return super().symlink(newpath, oldpath)


class _SFTPAttrsSFTPServer(SFTPServer):
    """Implement stat which returns SFTPAttrs and raises SFTPError"""

    async def stat(self, path):
        """Get attributes of a file or directory, following symlinks"""

        try:
            return SFTPAttrs.from_local(super().stat(path))
        except OSError as exc:
            if exc.errno == errno.EACCES:
                raise SFTPPermissionDenied(exc.strerror) from None
            else:
                raise SFTPError(99, exc.strerror) from None

    async def lstat(self, path):
        """Get attributes of a local file, directory, or symlink"""

        return SFTPAttrs.from_local(super().lstat(path))

    async def fstat(self, file_obj):
        """Get attributes of an open file"""

        return SFTPAttrs.from_local(super().fstat(file_obj))

    async def scandir(self, path):
        """Return names and attributes of the files in a local directory"""

        async for name in super().scandir(path):
            yield name


class _AsyncSFTPServer(SFTPServer):
    """Implement all SFTP callbacks as async methods"""

    # pylint: disable=useless-super-delegation

    async def format_longname(self, name):
        """Format the long name associated with an SFTP name"""

        return super().format_longname(name)

    async def open(self, path, pflags, attrs):
        """Open a file to serve to a remote client"""

        return super().open(path, pflags, attrs)

    async def close(self, file_obj):
        """Close an open file or directory"""

        super().close(file_obj)

    async def read(self, file_obj, offset, size):
        """Read data from an open file"""

        return super().read(file_obj, offset, size)

    async def write(self, file_obj, offset, data):
        """Write data to an open file"""

        return super().write(file_obj, offset, data)

    async def lstat(self, path):
        """Get attributes of a file, directory, or symlink"""

        return super().lstat(path)

    async def fstat(self, file_obj):
        """Get attributes of an open file"""

        return super().fstat(file_obj)

    async def setstat(self, path, attrs):
        """Set attributes of a file or directory, following symlinks"""

        super().setstat(path, attrs)

    async def lsetstat(self, path, attrs):
        """Set attributes of a file, directory, or symlink"""

        super().lsetstat(path, attrs)

    async def fsetstat(self, file_obj, attrs):
        """Set attributes of an open file"""

        super().fsetstat(file_obj, attrs)

    def scandir(self, path):
        """Scan the contents of a directory"""

        return super().scandir(path)

    async def remove(self, path):
        """Remove a file or symbolic link"""

        super().remove(path)

    async def mkdir(self, path, attrs):
        """Create a directory with the specified attributes"""

        super().mkdir(path, attrs)

    async def rmdir(self, path):
        """Remove a directory"""

        super().rmdir(path)

    async def realpath(self, path):
        """Return the canonical version of a path"""

        return super().realpath(path)

    async def stat(self, path):
        """Get attributes of a file or directory, following symlinks"""

        return super().stat(path)

    async def rename(self, oldpath, newpath):
        """Rename a file, directory, or link"""

        super().rename(oldpath, newpath)

    async def readlink(self, path):
        """Return the target of a symbolic link"""

        return super().readlink(path)

    async def symlink(self, oldpath, newpath):
        """Create a symbolic link"""

        super().symlink(oldpath, newpath)

    async def posix_rename(self, oldpath, newpath):
        """Rename a file, directory, or link with POSIX semantics"""

        super().posix_rename(oldpath, newpath)

    async def statvfs(self, path):
        """Get attributes of the file system containing a file"""

        return super().statvfs(path)

    async def fstatvfs(self, file_obj):
        """Return attributes of the file system containing an open file"""

        return super().fstatvfs(file_obj)

    async def link(self, oldpath, newpath):
        """Create a hard link"""

        super().link(oldpath, newpath)

    async def lock(self, file_obj, offset, length, flags):
        """Acquire a byte range lock on an open file"""

        super().lock(file_obj, offset, length, flags)

    async def unlock(self, file_obj, offset, length):
        """Release a byte range lock on an open file"""

        super().unlock(file_obj, offset, length)

    async def fsync(self, file_obj):
        """Force file data to be written to disk"""

        super().fsync(file_obj)

    async def exit(self):
        """Shut down this SFTP server"""

        super().exit()


class _CheckSFTP(ServerTestCase):
    """Utility functions for AsyncSSH SFTP unit tests"""

    @classmethod
    def setUpClass(cls):
        """Check if symlink is available on this platform"""

        super().setUpClass()

        try:
            os.symlink('file', 'link')
            os.remove('link')
            cls._symlink_supported = True
        except OSError: # pragma: no cover
            cls._symlink_supported = False

    def _create_file(self, name, data=(), offsets=(0,), mode=None, utime=None):
        """Create a test file"""

        if data == ():
            data = str(id(self))

        binary = 'b' if isinstance(data, bytes) else ''

        with open(name, 'w' + binary) as f:
            make_sparse_file(f)

            for offset in offsets:
                f.seek(offset)
                f.write(data)

        if mode is not None:
            os.chmod(name, mode)

        if utime is not None:
            os.utime(name, utime)

    def _check_attr(self, name1, name2, follow_symlinks, check_atime):
        """Check if attributes on two files are equal"""

        statfunc = os.stat if follow_symlinks else os.lstat

        attrs1 = statfunc(name1)
        attrs2 = statfunc(name2)

        self.assertEqual(stat.S_IMODE(attrs1.st_mode),
                         stat.S_IMODE(attrs2.st_mode))
        self.assertEqual(attrs1.st_size, attrs2.st_size)
        self.assertEqual(int(attrs1.st_mtime), int(attrs2.st_mtime))

        if check_atime:
            self.assertEqual(int(attrs1.st_atime), int(attrs2.st_atime))

    def _check_file(self, name1, name2, preserve=False, follow_symlinks=False,
                    check_atime=True):
        """Check if two files are equal"""

        if preserve:
            self._check_attr(name1, name2, follow_symlinks, check_atime)

        with open(name1, 'rb') as file1:
            with open(name2, 'rb') as file2:
                self.assertEqual(file1.read(), file2.read())

    async def _check_sparse_file(self, name1, name2):
        """Check if two sparse files are equal"""

        size1 = os.stat(name1).st_size
        size2 = os.stat(name2).st_size
        self.assertEqual(size1, size2)

        with open(name1, 'rb') as file1:
            with open(name2, 'rb') as file2:
                ranges1 = [range async for range in
                           LocalFile(file1).request_ranges(0, size1)]
                ranges2 = [range async for range in
                           LocalFile(file2).request_ranges(0, size2)]

                self.assertEqual(ranges1, ranges2)

    def _check_stat(self, sftp_stat, local_stat):
        """Check if file attributes are equal"""

        self.assertEqual(sftp_stat.size, local_stat.st_size)
        self.assertEqual(sftp_stat.uid, local_stat.st_uid)
        self.assertEqual(sftp_stat.gid, local_stat.st_gid)
        self.assertEqual(sftp_stat.permissions, local_stat.st_mode)
        self.assertEqual(sftp_stat.atime, int(local_stat.st_atime))
        self.assertEqual(sftp_stat.mtime, int(local_stat.st_mtime))

    def _check_stat_v4(self, sftp_stat, local_stat):
        """Check if file attributes are equal"""

        self.assertEqual(sftp_stat.size, local_stat.st_size)

        if sys.platform != 'win32': # pragma: no branch
            self.assertEqual(sftp_stat.owner, lookup_user(local_stat.st_uid))
            self.assertEqual(sftp_stat.group, lookup_group(local_stat.st_gid))

        self.assertEqual(sftp_stat.permissions,
                         stat.S_IMODE(local_stat.st_mode))
        self.assertEqual(tuple_to_nsec(sftp_stat.atime, sftp_stat.atime_ns),
                         local_stat.st_atime_ns)
        self.assertEqual(tuple_to_nsec(sftp_stat.mtime, sftp_stat.mtime_ns),
                         local_stat.st_mtime_ns)

    def _check_link(self, link, target):
        """Check if a symlink points to the right target"""

        link = os.readlink(link)

        if link.startswith('\\\\?\\'): # pragma: no cover
            link = link[4:]

        self.assertEqual(Path(link).resolve(), Path(target).resolve())


class _TestSFTP(_CheckSFTP):
    """Unit tests for AsyncSSH SFTP client and server"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server for the tests to use"""

        return await cls.create_server(sftp_factory=True, sftp_version=6)

    @sftp_test
    async def _dummy_sftp_client(self, sftp):
        """Test starting a new SFTPv3 client session and immediately exiting"""

        self.assertEqual(sftp.version, 3)

    @sftp_test_v5
    async def _dummy_sftp_client_v5(self, sftp):
        """Test starting a new SFTPv5 client session and immediately exiting"""

        self.assertEqual(sftp.version, 5)

    @sftp_test_v6
    async def _dummy_sftp_client_v6(self, sftp):
        """Test starting a new SFTPv6 client session and immediately exiting"""

        self.assertEqual(sftp.version, 6)

    @sftp_test
    async def test_copy(self, sftp):
        """Test copying a file over SFTP"""

        for method in ('get', 'put', 'copy'):
            for src in ('src', b'src', Path('src')):
                with self.subTest(method=method, src=type(src)):
                    try:
                        self._create_file('src')
                        await getattr(sftp, method)(src, 'dst')
                        self._check_file('src', 'dst')
                    finally:
                        remove('src dst')

    @sftp_test
    async def test_sparse_copy(self, sftp):
        """Test putting a sparse file over SFTP"""

        for method in ('get', 'put', 'copy'):
            with self.subTest(method=method):
                try:
                    self._create_file(
                        'src', offsets=(i*1024*1024 for i in
                                        range(24, 3840, 24)))
                    await getattr(sftp, method)('src', 'dst')
                    await self._check_sparse_file('src', 'dst')
                finally:
                    remove('src dst')

    @sftp_test
    async def test_empty_request_range(self, sftp):
        """Test getting ranges from an empty file"""

        try:
            self._create_file('file', data=b'')

            async with sftp.open('file', 'rb') as f:
                result = [data_range async for data_range in
                          f.request_ranges(0, 0)]
                self.assertEqual(result, [])
        finally:
            remove('file')

    @sftp_test
    async def test_nonsparse_put(self, sftp):
        """Test putting a sparse file over SFTP with sparse mode disabled"""

        try:
            self._create_file(
                'src', offsets=(i*1024*1024 for i in range(24, 72, 24)))
            await sftp.put('src', 'dst', sparse=False)
            self._check_file('src', 'dst')
        finally:
            remove('src dst')

    @sftp_test
    async def test_copy_max_requests(self, sftp):
        """Test copying a file over SFTP with max requests set"""

        for method in ('get', 'put', 'copy'):
            for src in ('src', b'src', Path('src')):
                with self.subTest(method=method, src=type(src)):
                    try:
                        self._create_file('src', 16*1024*1024*'\0')
                        await getattr(sftp, method)(src, 'dst',
                                                    max_requests=4)
                        self._check_file('src', 'dst')
                    finally:
                        remove('src dst')

    def test_copy_non_remote(self):
        """Test copying without using remote_copy function"""

        @sftp_test
        async def _test_copy_non_remote(self, sftp):
            """Test copying without using remote_copy function"""

            for method in ('copy', 'mcopy'):
                with self.subTest(method=method):
                    try:
                        self._create_file('src')
                        await getattr(sftp, method)('src', 'dst')
                        self._check_file('src', 'dst')
                    finally:
                        remove('src dst')

        with patch('asyncssh.sftp.SFTPServerHandler._extensions', []):
            # pylint: disable=no-value-for-parameter
            _test_copy_non_remote(self)

    def test_copy_remote_only(self):
        """Test copying while allowing only remote copy"""

        @sftp_test
        async def _test_copy_remote_only(self, sftp):
            """Test copying with only remote copy allowed"""

            for method in ('copy', 'mcopy'):
                with self.subTest(method=method):
                    try:
                        self._create_file('src')

                        with self.assertRaises(SFTPOpUnsupported):
                            await getattr(sftp, method)('src', 'dst',
                                                        remote_only=True)
                    finally:
                        remove('src')

        with patch('asyncssh.sftp.SFTPServerHandler._extensions', []):
            # pylint: disable=no-value-for-parameter
            _test_copy_remote_only(self)

    @sftp_test
    async def test_copy_progress(self, sftp):
        """Test copying a file over SFTP with progress reporting"""

        def _report_progress(_srcpath, _dstpath, bytes_copied, _total_bytes):
            """Monitor progress of copy"""

            reports.append(bytes_copied)

        for method in ('get', 'put', 'copy'):
            for size in (0, 100000):
                with self.subTest(method=method, size=size):
                    reports = []

                    try:
                        self._create_file('src', size * 'a')
                        await getattr(sftp, method)(
                            'src', 'dst', block_size=8192,
                            progress_handler=_report_progress)
                        self._check_file('src', 'dst')

                        if method != 'copy':
                            self.assertEqual(len(reports), (size // 8192) + 1)

                        self.assertEqual(reports[-1], size)
                    finally:
                        remove('src dst')

    @sftp_test
    async def test_copy_preserve(self, sftp):
        """Test copying a file with preserved attributes over SFTP"""

        for method in ('get', 'put', 'copy'):
            with self.subTest(method=method):
                try:
                    self._create_file('src', mode=0o666, utime=(1, 2))
                    await getattr(sftp, method)('src', 'dst', preserve=True)
                    self._check_file('src', 'dst', preserve=True)
                finally:
                    remove('src dst')

    @unittest.skipIf(sys.platform == 'win32', 'skip lsetstat tests on Windows')
    @sftp_test
    async def test_copy_preserve_link(self, sftp):
        """Test copying a symlink with preserved attributes over SFTP"""

        for method in ('get', 'put', 'copy'):
            with self.subTest(method=method):
                try:
                    os.symlink('file', 'link1')
                    os.utime('link1', times=(1, 2), follow_symlinks=False)
                    await getattr(sftp, method)(
                        'link1', 'link2', preserve=True, follow_symlinks=False)
                    self.assertEqual(os.lstat('link2').st_mtime, 2)
                finally:
                    remove('link1 link2')

    @unittest.skipIf(sys.platform == 'win32', 'skip lsetstat tests on Windows')
    def test_copy_preserve_link_unsupported(self):
        """Test preserving symlink attributes over SFTP without lsetstat"""

        @sftp_test
        async def _lsetstat_unsupported(self, sftp):
            """Try copying link attributes without lsetstat"""

            try:
                os.symlink('file', 'link1')
                os.utime('link1', times=(1, 2), follow_symlinks=False)
                await sftp.put('link1', 'link2', preserve=True,
                               follow_symlinks=False)
                self.assertNotEqual(int(os.lstat('link2').st_mtime), 2)
            finally:
                remove('link1 link2')

        with patch('asyncssh.sftp.SFTPServerHandler._extensions', []):
            # pylint: disable=no-value-for-parameter
            _lsetstat_unsupported(self)

    @sftp_test
    async def test_copy_recurse(self, sftp):
        """Test recursively copying a directory over SFTP"""

        for method in ('get', 'put', 'copy'):
            with self.subTest(method=method):
                try:
                    os.mkdir('src')
                    self._create_file('src/file1')

                    if self._symlink_supported: # pragma: no branch
                        os.symlink('file1', 'src/file2')

                    await getattr(sftp, method)('src', 'dst', recurse=True)

                    self._check_file('src/file1', 'dst/file1')

                    if self._symlink_supported: # pragma: no branch
                        self._check_link('dst/file2', 'file1')
                finally:
                    remove('src dst')

    @sftp_test
    async def test_copy_recurse_existing(self, sftp):
        """Test recursively copying over SFTP where target dir exists"""

        for method in ('get', 'put', 'copy'):
            with self.subTest(method=method):
                try:
                    os.mkdir('src')
                    os.mkdir('dst')
                    os.mkdir('dst/src')
                    self._create_file('src/file1')

                    if self._symlink_supported: # pragma: no branch
                        os.symlink('file1', 'src/file2')

                    await getattr(sftp, method)('src', 'dst', recurse=True)

                    self._check_file('src/file1', 'dst/src/file1')

                    if self._symlink_supported: # pragma: no branch
                        self._check_link('dst/src/file2', 'file1')
                finally:
                    remove('src dst')

    @sftp_test
    async def test_copy_follow_symlinks(self, sftp):
        """Test copying a file over SFTP while following symlinks"""

        if not self._symlink_supported: # pragma: no cover
            raise unittest.SkipTest('symlink not available')

        for method in ('get', 'put', 'copy'):
            with self.subTest(method=method):
                try:
                    self._create_file('src')
                    os.symlink('src', 'link')
                    await getattr(sftp, method)('link', 'dst',
                                                follow_symlinks=True)
                    self._check_file('src', 'dst')
                finally:
                    remove('src dst link')

    @sftp_test
    async def test_copy_recurse_follow_symlinks(self, sftp):
        """Test recursively copying over SFTP while following symlinks"""

        if not self._symlink_supported: # pragma: no cover
            raise unittest.SkipTest('symlink not available')

        for method in ('get', 'put', 'copy'):
            with self.subTest(method=method):
                try:
                    os.mkdir('src')
                    self._create_file('src/file1')
                    os.symlink('file1', 'src/file2')
                    await getattr(sftp, method)('src', 'dst', recurse=True,
                                                follow_symlinks=True)
                    self._check_file('src/file1', 'dst/file2')
                finally:
                    remove('src dst')

    @sftp_test
    async def test_copy_invalid_name(self, sftp):
        """Test copying a file with an invalid name over SFTP"""

        for method in ('get', 'put', 'copy', 'mget', 'mput', 'mcopy'):
            with self.subTest(method=method):
                with self.assertRaises((OSError, SFTPNoSuchFile,
                                        SFTPFailure, UnicodeDecodeError)):
                    await getattr(sftp, method)(b'\xff')

    @sftp_test
    async def test_copy_directory_no_recurse(self, sftp):
        """Test copying a directory over SFTP without recurse option"""

        for method in ('get', 'put', 'copy', 'mget', 'mput', 'mcopy'):
            with self.subTest(method=method):
                try:
                    os.mkdir('dir')
                    with self.assertRaises(SFTPFailure):
                        await getattr(sftp, method)('dir')
                finally:
                    remove('dir')

    @sftp_test_v6
    async def test_copy_directory_no_recurse_v6(self, sftp):
        """Test copying a directory over SFTPv6 without recurse option"""

        for method in ('get', 'put', 'copy', 'mget', 'mput', 'mcopy'):
            with self.subTest(method=method):
                try:
                    os.mkdir('dir')
                    with self.assertRaises(SFTPFileIsADirectory):
                        await getattr(sftp, method)('dir')
                finally:
                    remove('dir')

    @sftp_test
    async def test_multiple_copy(self, sftp):
        """Test copying multiple files over SFTP"""

        for method in ('get', 'put', 'copy'):
            for seq in (list, tuple):
                with self.subTest(method=method):
                    try:
                        self._create_file('src1', 'xxx')
                        self._create_file('src2', 'yyy')
                        os.mkdir('dst')

                        await getattr(sftp, method)(seq(('src1', 'src2')),
                                                    'dst')

                        self._check_file('src1', 'dst/src1')
                        self._check_file('src2', 'dst/src2')
                    finally:
                        remove('src1 src2 dst')

    @sftp_test_v4
    async def test_multiple_copy_v4(self, sftp):
        """Test copying multiple files over SFTPv4"""

        for method in ('get', 'put', 'copy'):
            for seq in (list, tuple):
                with self.subTest(method=method):
                    try:
                        self._create_file('src1', 'xxx')
                        self._create_file('src2', 'yyy')
                        os.mkdir('dst')

                        await getattr(sftp, method)(seq(('src1', 'src2')),
                                                    'dst')

                        self._check_file('src1', 'dst/src1')
                        self._check_file('src2', 'dst/src2')
                    finally:
                        remove('src1 src2 dst')

    @sftp_test_v5
    async def test_multiple_copy_v5(self, sftp):
        """Test copying multiple files over SFTPv5"""

        for method in ('get', 'put', 'copy'):
            for seq in (list, tuple):
                with self.subTest(method=method):
                    try:
                        self._create_file('src1', 'xxx')
                        self._create_file('src2', 'yyy')
                        os.mkdir('dst')

                        await getattr(sftp, method)(seq(('src1', 'src2')),
                                                    'dst')

                        self._check_file('src1', 'dst/src1')
                        self._check_file('src2', 'dst/src2')
                    finally:
                        remove('src1 src2 dst')

    @sftp_test_v6
    async def test_multiple_copy_v6(self, sftp):
        """Test copying multiple files over SFTPv6"""

        for method in ('get', 'put', 'copy'):
            for seq in (list, tuple):
                with self.subTest(method=method):
                    try:
                        self._create_file('src1', 'xxx')
                        self._create_file('src2', 'yyy')
                        os.mkdir('dst')

                        await getattr(sftp, method)(seq(('src1', 'src2')),
                                                    'dst')

                        self._check_file('src1', 'dst/src1')
                        self._check_file('src2', 'dst/src2')
                    finally:
                        remove('src1 src2 dst')

    @sftp_test
    async def test_multiple_copy_glob(self, sftp):
        """Test copying multiple files via glob over SFTP"""

        for method in ('mget', 'mput', 'mcopy'):
            with self.subTest(method=method):
                try:
                    self._create_file('src1', 'xxx')
                    self._create_file('src2', 'yyy')
                    os.mkdir('dst')

                    await getattr(sftp, method)(['', 'src*'], 'dst')

                    self._check_file('src1', 'dst/src1')
                    self._check_file('src2', 'dst/src2')
                finally:
                    remove('src1 src2 dst')

    @sftp_test
    async def test_multiple_copy_bytes_path(self, sftp):
        """Test copying multiple files with byte string paths over SFTP"""

        for method in ('mget', 'mput', 'mcopy'):
            with self.subTest(method=method):
                try:
                    self._create_file('src1', 'xxx')
                    self._create_file('src2', 'yyy')
                    os.mkdir('dst')

                    await getattr(sftp, method)(b'src*', b'dst')

                    self._check_file('src1', 'dst/src1')
                    self._check_file('src2', 'dst/src2')
                finally:
                    remove('src1 src2 dst')

    @sftp_test
    async def test_multiple_copy_pathlib_path(self, sftp):
        """Test copying multiple files with pathlib paths over SFTP"""

        for method in ('mget', 'mput', 'mcopy'):
            with self.subTest(method=method):
                try:
                    self._create_file('src1', 'xxx')
                    self._create_file('src2', 'yyy')
                    os.mkdir('dst')

                    await getattr(sftp, method)(Path('src*'), Path('dst'))

                    self._check_file('src1', 'dst/src1')
                    self._check_file('src2', 'dst/src2')
                finally:
                    remove('src1 src2 dst')

    @sftp_test
    async def test_multiple_copy_target_not_dir(self, sftp):
        """Test copying multiple files over SFTP with non-directory target"""

        for method in ('mget', 'mput', 'mcopy'):
            with self.subTest(method=method):
                try:
                    self._create_file('src1')
                    self._create_file('src2')

                    with self.assertRaises(SFTPFailure):
                        await getattr(sftp, method)('src*', 'dst')
                finally:
                    remove('src')

    @sftp_test_v6
    async def test_multiple_copy_target_not_dir_v6(self, sftp):
        """Test copying multiple files over SFTP with non-directory target"""

        for method in ('mget', 'mput', 'mcopy'):
            with self.subTest(method=method):
                try:
                    self._create_file('src1')
                    self._create_file('src2')

                    with self.assertRaises(SFTPNotADirectory):
                        await getattr(sftp, method)('src*', 'dst')
                finally:
                    remove('src')

    @sftp_test
    async def test_multiple_copy_error_handler(self, sftp):
        """Test copying multiple files over SFTP with error handler"""

        def err_handler(exc):
            """Catch error for non-recursive copy of directory"""

            self.assertEqual(exc.reason, 'src2 is a directory')

        for method in ('mget', 'mput', 'mcopy'):
            with self.subTest(method=method):
                try:
                    self._create_file('src1')
                    os.mkdir('src2')
                    os.mkdir('dst')

                    await getattr(sftp, method)('src*', 'dst',
                                                error_handler=err_handler)

                    self._check_file('src1', 'dst/src1')
                finally:
                    remove('src1 src2 dst')

    def test_remote_copy_unsupported(self):
        """Test remote copy on a server which doesn't support it"""

        @sftp_test
        async def _test_remote_copy_unsupported(self, sftp):
            """Test remote copy not being supported"""

            try:
                self._create_file('src')

                with self.assertRaises(SFTPOpUnsupported):
                    await sftp.remote_copy('src', 'dst')
            finally:
                remove('src')

        with patch('asyncssh.sftp.SFTPServerHandler._extensions', []):
            # pylint: disable=no-value-for-parameter
            _test_remote_copy_unsupported(self)

    @sftp_test
    async def test_remote_copy_arguments(self, sftp):
        """Test remote copy arguments"""

        try:
            self._create_file('src', os.urandom(2*1024*1024))

            async with sftp.open('src', 'rb') as src:
                async with sftp.open('dst', 'wb') as dst:
                    await sftp.remote_copy(src, dst, 0, 1024*1024, 0)
                    await sftp.remote_copy(src, dst, 1024*1024, 0, 1024*1024)

            self._check_file('src', 'dst')
        finally:
            remove('src dst')

    @sftp_test
    async def test_remote_copy_closed_file(self, sftp):
        """Test remote copy of a closed file"""

        try:
            self._create_file('file')

            async with sftp.open('file', 'rb') as f:
                await f.close()

                with self.assertRaises(ValueError):
                    await sftp.remote_copy(f, f)
        finally:
            remove('file')

    @sftp_test
    async def test_glob(self, sftp):
        """Test a glob pattern match over SFTP"""

        glob_tests = (
            ('file*',                    ['file1', 'filedir']),
            ('./file*',                  ['./file1', './filedir']),
            (b'file*',                   [b'file1', b'filedir']),
            (['file*'],                  ['file1', 'filedir']),
            (['', 'file*'],              ['file1', 'filedir']),
            (['file*/*2'],               ['filedir/file2', 'filedir/filedir2']),
            (['file*/*[3-9]'],           ['filedir/file3']),
            (['**/file[12]'],            ['file1', 'filedir/file2']),
            (['**/file*/'],              ['filedir/', 'filedir/filedir2/']),
            (['filedir/**'],             ['filedir', 'filedir/file2',
                                          'filedir/file3', 'filedir/filedir2',
                                          'filedir/filedir2/file4',
                                          'filedir/filedir2/file5']),
            ('filedir/file2',            ['filedir/file2']),
            ('./filedir/file2',          ['./filedir/file2']),
            ('filedir/file*',            ['filedir/file2', 'filedir/file3',
                                          'filedir/filedir2']),
            ('./filedir/file*',          ['./filedir/file2', './filedir/file3',
                                          './filedir/filedir2']),
            ('./filedir/filedir2/file*', ['./filedir/filedir2/file4',
                                          './filedir/filedir2/file5']),
            ('filedir/filedir2/file*',   ['filedir/filedir2/file4',
                                          'filedir/filedir2/file5']),
            ('./filedir/*/file4',        ['./filedir/filedir2/file4']),
            ('filedir/*/file4',          ['filedir/filedir2/file4']),
            ('./*/filedir2/file4',       ['./filedir/filedir2/file4']),
            ('*/filedir2/file4',         ['filedir/filedir2/file4']),
            ('*/filedir2/file*4',        ['filedir/filedir2/file4']),
            ('./filedir/filedir*/file*', ['./filedir/filedir2/file4',
                                          './filedir/filedir2/file5']),
            ('filedir/filedir*/file*',   ['filedir/filedir2/file4',
                                          'filedir/filedir2/file5']),
            ('./**/filedir2/file4',      ['./filedir/filedir2/file4']),
            ('**/filedir2/file4',        ['filedir/filedir2/file4']),
            (['file1', '**/file1'],      ['file1']))

        try:
            os.mkdir('filedir')
            self._create_file('file1')
            self._create_file('filedir/file2')
            self._create_file('filedir/file3')
            os.mkdir('filedir/filedir2')
            self._create_file('filedir/filedir2/file4')
            self._create_file('filedir/filedir2/file5')

            for pattern, matches in glob_tests:
                with self.subTest(pattern=pattern):
                    self.assertEqual(sorted(await sftp.glob(pattern)),
                                     matches)

            self.assertEqual((await sftp.glob([b'fil*1', 'fil*dir'])),
                             [b'file1', 'filedir'])
        finally:
            remove('file1 filedir')

    @sftp_test
    async def test_glob_errors(self, sftp):
        """Test glob pattern match errors over SFTP"""

        _glob_errors = (
            'file*',
            'dir/file1/*',
            'dir*/file1/*',
            'dir/dir1/*')

        try:
            os.mkdir('dir')
            self._create_file('dir/file1')
            os.mkdir('dir/dir1')
            os.chmod('dir/dir1', 0)

            for pattern in _glob_errors:
                with self.subTest(pattern=pattern):
                    with self.assertRaises(SFTPNoSuchFile):
                        await sftp.glob(pattern)
        finally:
            os.chmod('dir/dir1', 0o700)
            remove('dir')

    @sftp_test_v4
    async def test_glob_error_v4(self, sftp):
        """Test a glob pattern match error over SFTP"""

        with self.assertRaises(SFTPNoSuchPath):
            await sftp.glob('file*')

    @sftp_test
    async def test_glob_error_handler(self, sftp):
        """Test a glob pattern match with error handler over SFTP"""

        def err_handler(exc):
            """Catch error for nonexistent file1"""

            self.assertEqual(exc.reason, 'No matches found')

        try:
            self._create_file('file2')

            self.assertEqual((await sftp.glob(['file1*', 'file2*'],
                                              error_handler=err_handler)),
                             ['file2'])
        finally:
            remove('file2')

    @sftp_test
    async def test_stat(self, sftp):
        """Test getting attributes on a file"""

        try:
            os.mkdir('dir')
            self._create_file('file')

            if self._symlink_supported: # pragma: no branch
                os.symlink('bad', 'badlink')
                os.symlink('dir', 'dirlink')
                os.symlink('file', 'filelink')

            self._check_stat((await sftp.stat('dir')), os.stat('dir'))
            self._check_stat((await sftp.stat('file')), os.stat('file'))

            if self._symlink_supported: # pragma: no branch
                self._check_stat((await sftp.stat('dirlink')),
                                 os.stat('dir'))
                self._check_stat((await sftp.stat('filelink')),
                                 os.stat('file'))

                with self.assertRaises(SFTPNoSuchFile):
                    await sftp.stat('badlink')

            self.assertTrue(await sftp.isdir('dir'))
            self.assertFalse(await sftp.isdir('file'))

            if self._symlink_supported: # pragma: no branch
                self.assertFalse(await sftp.isdir('badlink'))
                self.assertTrue(await sftp.isdir('dirlink'))
                self.assertFalse(await sftp.isdir('filelink'))

            self.assertFalse(await sftp.isfile('dir'))
            self.assertTrue(await sftp.isfile('file'))

            if self._symlink_supported: # pragma: no branch
                self.assertFalse(await sftp.isfile('badlink'))
                self.assertFalse(await sftp.isfile('dirlink'))
                self.assertTrue(await sftp.isfile('filelink'))

            self.assertFalse(await sftp.islink('dir'))
            self.assertFalse(await sftp.islink('file'))

            if self._symlink_supported: # pragma: no branch
                self.assertTrue(await sftp.islink('badlink'))
                self.assertTrue(await sftp.islink('dirlink'))
                self.assertTrue(await sftp.islink('filelink'))
        finally:
            remove('dir file badlink dirlink filelink')

    @sftp_test
    async def test_lstat(self, sftp):
        """Test getting attributes on a link"""

        if not self._symlink_supported: # pragma: no cover
            raise unittest.SkipTest('symlink not available')

        try:
            os.symlink('file', 'link')
            self._check_stat((await sftp.lstat('link')), os.lstat('link'))
        finally:
            remove('link')

    @sftp_test_v4
    async def test_lstat_v4(self, sftp):
        """Test getting attributes on a link with SFTPv4"""

        if not self._symlink_supported: # pragma: no cover
            raise unittest.SkipTest('symlink not available')

        try:
            os.symlink('file', 'link')
            self._check_stat_v4((await sftp.lstat('link')), os.lstat('link'))
        finally:
            remove('link')

    @sftp_test_v6
    async def test_lstat_v6(self, sftp):
        """Test getting attributes on a link with SFTPv6"""

        if not self._symlink_supported: # pragma: no cover
            raise unittest.SkipTest('symlink not available')

        try:
            os.symlink('file', 'link')
            self._check_stat_v4((await sftp.lstat('link')), os.lstat('link'))
        finally:
            remove('link')

    @sftp_test
    async def test_lstat_via_stat(self, sftp):
        """Test getting attributes on a link by disabling follow_symlinks"""

        if not self._symlink_supported: # pragma: no cover
            raise unittest.SkipTest('symlink not available')

        try:
            os.symlink('file', 'link')
            self._check_stat((await sftp.stat('link', follow_symlinks=False)),
                             os.lstat('link'))
        finally:
            remove('link')

    @sftp_test
    async def test_setstat(self, sftp):
        """Test setting attributes on a file"""

        try:
            self._create_file('file')
            await sftp.setstat('file', SFTPAttrs(permissions=0o666))
            self.assertEqual(stat.S_IMODE(os.stat('file').st_mode), 0o666)

            with self.assertRaises(ValueError):
                await sftp.setstat('file', SFTPAttrs(owner='root',
                                                     group='wheel'))
        finally:
            remove('file')

    @sftp_test_v4
    async def test_setstat_v4(self, sftp):
        """Test setting attributes on a file"""

        try:
            self._create_file('file')

            await sftp.setstat('file', SFTPAttrs(atime=1))

            stat_result = os.stat('file')
            self.assertEqual(stat_result.st_atime, 1)

            await sftp.setstat('file', SFTPAttrs(mtime=2))

            stat_result = os.stat('file')
            self.assertEqual(stat_result.st_mtime, 2)
        finally:
            remove('file')

    @unittest.skipIf(sys.platform == 'win32', 'skip uid/gid tests on Windows')
    @sftp_test_v6
    async def test_setstat_invalid_owner_group_v6(self, sftp):
        """Test setting invalid owner/group on a file"""

        try:
            self._create_file('file')

            with patch('pwd.getpwuid', _getpwuid_error):
                with self.assertRaises(SFTPOwnerInvalid):
                    await sftp.setstat('file', SFTPAttrs(owner='xxx',
                                                         group='0'))

            with patch('grp.getgrgid', _getgrgid_error):
                with self.assertRaises(SFTPGroupInvalid):
                    await sftp.setstat('file', SFTPAttrs(owner='0',
                                                         group='yyy'))
        finally:
            remove('file')

    @unittest.skipIf(sys.platform == 'win32', 'skip lsetstat tests on Windows')
    @sftp_test
    async def test_lsetstat(self, sftp):
        """Test setting attributes on a link"""

        try:
            os.symlink('file', 'link')

            await sftp.setstat('link', SFTPAttrs(atime=1, mtime=2),
                               follow_symlinks=False)

            stat_result = os.lstat('link')
            self.assertEqual(stat_result.st_atime, 1)
            self.assertEqual(stat_result.st_mtime, 2)
        finally:
            remove('link')

    @unittest.skipIf(sys.platform == 'win32', 'skip lsetstat tests on Windows')
    @sftp_test_v4
    async def test_lsetstat_v4(self, sftp):
        """Test setting attributes on a link"""

        try:
            os.symlink('file', 'link')

            await sftp.setstat('link', SFTPAttrs(atime=1),
                               follow_symlinks=False)

            self.assertEqual(os.lstat('link').st_atime, 1)

            await sftp.setstat('link', SFTPAttrs(mtime=2),
                               follow_symlinks=False)

            self.assertEqual(os.lstat('link').st_mtime, 2)
        finally:
            remove('link')

    @unittest.skipIf(sys.platform == 'win32', 'skip lsetstat tests on Windows')
    @sftp_test_v6
    async def test_lsetstat_v6(self, sftp):
        """Test setting attributes on a link"""

        try:
            os.symlink('file', 'link')

            await sftp.setstat('link', SFTPAttrs(atime=1),
                               follow_symlinks=False)

            self.assertEqual(os.lstat('link').st_atime, 1)

            await sftp.setstat('link', SFTPAttrs(mtime=2),
                               follow_symlinks=False)

            self.assertEqual(os.lstat('link').st_mtime, 2)
        finally:
            remove('link')

    @unittest.skipIf(sys.platform == 'win32', 'skip statvfs tests on Windows')
    @sftp_test
    async def test_statvfs(self, sftp):
        """Test getting attributes on a filesystem

           We can't compare the values returned by a live statvfs call since
           they can change at any time. See the separate _TestSFTStatPVFS
           class for a more complete test, but this is left in for code
           coverage purposes.

        """

        self.assertIsInstance((await sftp.statvfs('.')), SFTPVFSAttrs)

    @sftp_test
    async def test_truncate(self, sftp):
        """Test truncating a file"""

        try:
            self._create_file('file', '01234567890123456789')

            await sftp.truncate('file', 10)
            self.assertEqual((await sftp.getsize('file')), 10)

            with open('file') as localf:
                self.assertEqual(localf.read(), '0123456789')
        finally:
            remove('file')

    @unittest.skipIf(sys.platform == 'win32', 'skip chown tests on Windows')
    @sftp_test
    async def test_chown(self, sftp):
        """Test changing ownership of a file

           We can't change to a different user/group here if we're not
           root, so just change to the same user/group. See the separate
           _TestSFTPChown class for a more complete test, but this is
           left in for code coverage purposes.

        """

        try:
            self._create_file('file')
            stat_result = os.stat('file')

            await sftp.chown('file', stat_result.st_uid, stat_result.st_gid)

            new_stat_result = os.stat('file')
            self.assertEqual(new_stat_result.st_uid, stat_result.st_uid)
            self.assertEqual(new_stat_result.st_gid, stat_result.st_gid)
        finally:
            remove('file')

    @unittest.skipIf(sys.platform == 'win32', 'skip chown tests on Windows')
    @sftp_test_v4
    async def test_chown_v4(self, sftp):
        """Test changing ownership of a file

           We can't change to a different user/group here if we're not
           root, so just change to the same user/group. See the separate
           _TestSFTPChown class for a more complete test, but this is
           left in for code coverage purposes.

        """

        try:
            self._create_file('file')
            stat_result = os.stat('file')

            owner = lookup_user(stat_result.st_uid)
            group = lookup_group(stat_result.st_gid)

            await sftp.chown('file', owner, group)

            new_stat_result = os.stat('file')
            self.assertEqual(new_stat_result.st_uid, stat_result.st_uid)
            self.assertEqual(new_stat_result.st_gid, stat_result.st_gid)

            await sftp.chown('file', str(stat_result.st_uid), group)

            new_stat_result = os.stat('file')
            self.assertEqual(new_stat_result.st_uid, stat_result.st_uid)
            self.assertEqual(new_stat_result.st_gid, stat_result.st_gid)

            await sftp.chown('file', owner, str(stat_result.st_gid))

            new_stat_result = os.stat('file')
            self.assertEqual(new_stat_result.st_uid, stat_result.st_uid)
            self.assertEqual(new_stat_result.st_gid, stat_result.st_gid)

            await sftp.chown('file', str(stat_result.st_uid), group)

            new_stat_result = os.stat('file')
            self.assertEqual(new_stat_result.st_uid, stat_result.st_uid)
            self.assertEqual(new_stat_result.st_gid, stat_result.st_gid)

            await sftp.chown('file', owner, str(stat_result.st_gid))

            new_stat_result = os.stat('file')
            self.assertEqual(new_stat_result.st_uid, stat_result.st_uid)
            self.assertEqual(new_stat_result.st_gid, stat_result.st_gid)
        finally:
            remove('file')

    @unittest.skipIf(sys.platform == 'win32', 'skip chmod tests on Windows')
    @sftp_test
    async def test_chmod(self, sftp):
        """Test changing permissions on a file"""

        try:
            self._create_file('file')
            await sftp.chmod('file', 0o4321)
            self.assertEqual(stat.S_IMODE(os.stat('file').st_mode), 0o4321)
        finally:
            remove('file')

    @sftp_test
    async def test_utime(self, sftp):
        """Test changing access and modify times on a file"""

        try:
            self._create_file('file')

            await sftp.utime('file')
            await sftp.utime('file', (1, 2))

            stat_result = os.stat('file')
            self.assertEqual(stat_result.st_atime, 1)
            self.assertEqual(stat_result.st_mtime, 2)
            self.assertEqual((await sftp.getatime('file')), 1)
            self.assertEqual((await sftp.getmtime('file')), 2)
        finally:
            remove('file')

    @sftp_test_v4
    async def test_utime_v4(self, sftp):
        """Test changing access and modify times on a file with SFTPv4"""

        try:
            self._create_file('file')

            await sftp.utime('file')
            await sftp.utime('file', (1.0, 2.25))

            stat_result = os.stat('file')
            self.assertEqual(stat_result.st_atime, 1.0)
            self.assertEqual(stat_result.st_atime_ns, 1000000000)
            self.assertEqual(stat_result.st_mtime, 2.25)
            self.assertEqual(stat_result.st_mtime_ns, 2250000000)
            self.assertEqual((await sftp.getatime('file')), 1.0)
            self.assertEqual((await sftp.getatime_ns('file')), 1000000000)
            self.assertIsNotNone(await sftp.getcrtime('file'))
            self.assertIsNotNone(await sftp.getcrtime_ns('file'))
            self.assertEqual((await sftp.getmtime('file')), 2.25)
            self.assertEqual((await sftp.getmtime_ns('file')), 2250000000)

            await sftp.utime('file', ns=(3500000000, 4750000000))

            stat_result = os.stat('file')
            self.assertEqual(stat_result.st_atime, 3.5)
            self.assertEqual(stat_result.st_atime_ns, 3500000000)
            self.assertEqual(stat_result.st_mtime, 4.75)
            self.assertEqual(stat_result.st_mtime_ns, 4750000000)
            self.assertEqual((await sftp.getatime('file')), 3.5)
            self.assertEqual((await sftp.getatime_ns('file')), 3500000000)
            self.assertIsNotNone(await sftp.getcrtime('file'))
            self.assertIsNotNone(await sftp.getcrtime_ns('file'))
            self.assertEqual((await sftp.getmtime('file')), 4.75)
            self.assertEqual((await sftp.getmtime_ns('file')), 4750000000)
        finally:
            remove('file')

    @sftp_test
    async def test_exists(self, sftp):
        """Test checking whether a file exists"""

        try:
            self._create_file('file1')

            self.assertTrue(await sftp.exists('file1'))
            self.assertFalse(await sftp.exists('file2'))
        finally:
            remove('file1')

    @sftp_test
    async def test_lexists(self, sftp):
        """Test checking whether a link exists"""

        if not self._symlink_supported: # pragma: no cover
            raise unittest.SkipTest('symlink not available')

        try:
            os.symlink('file', 'link1')

            self.assertTrue(await sftp.lexists('link1'))
            self.assertFalse(await sftp.lexists('link2'))
        finally:
            remove('link1')

    @sftp_test
    async def test_remove(self, sftp):
        """Test removing a file"""

        try:
            self._create_file('file')
            await sftp.remove('file')

            with self.assertRaises(FileNotFoundError):
                os.stat('file')

            with self.assertRaises(SFTPNoSuchFile):
                await sftp.remove('file')
        finally:
            remove('file')

    @sftp_test
    async def test_unlink(self, sftp):
        """Test unlinking a file"""

        try:
            self._create_file('file')
            await sftp.unlink('file')

            with self.assertRaises(FileNotFoundError):
                os.stat('file')

            with self.assertRaises(SFTPNoSuchFile):
                await sftp.unlink('file')
        finally:
            remove('file')

    @sftp_test
    async def test_rename(self, sftp):
        """Test renaming a file"""

        try:
            self._create_file('file1', 'xxx')
            self._create_file('file2', 'yyy')

            with self.assertRaises(SFTPFailure):
                await sftp.rename('file1', 'file2')

            await sftp.rename('file1', 'file3')

            with open('file3') as localf:
                self.assertEqual(localf.read(), 'xxx')

            await sftp.rename('file2', 'file3', FXR_OVERWRITE)

            with open('file3') as localf:
                self.assertEqual(localf.read(), 'yyy')
        finally:
            remove('file1 file2 file3')

    @sftp_test_v6
    async def test_rename_v6(self, sftp):
        """Test renaming a file with SFTPv6"""

        try:
            self._create_file('file1', 'xxx')
            self._create_file('file2', 'yyy')

            with self.assertRaises(SFTPFileAlreadyExists):
                await sftp.rename('file1', 'file2')

            await sftp.rename('file1', 'file3')

            with open('file3') as localf:
                self.assertEqual(localf.read(), 'xxx')

            await sftp.rename('file2', 'file3', FXR_OVERWRITE)

            with open('file3') as localf:
                self.assertEqual(localf.read(), 'yyy')
        finally:
            remove('file1 file2 file3')

    @sftp_test
    async def test_posix_rename(self, sftp):
        """Test renaming a file that replaces a target file"""

        try:
            self._create_file('file1', 'xxx')
            self._create_file('file2', 'yyy')

            await sftp.posix_rename('file1', 'file2')

            with open('file2') as localf:
                self.assertEqual(localf.read(), 'xxx')
        finally:
            remove('file1 file2')

    @sftp_test_v6
    async def test_posix_rename_v6(self, sftp):
        """Test renaming a file that replaces a target file"""

        try:
            self._create_file('file1', 'xxx')
            self._create_file('file2', 'yyy')

            await sftp.posix_rename('file1', 'file2')

            with open('file2') as localf:
                self.assertEqual(localf.read(), 'xxx')
        finally:
            remove('file1 file2')

    @sftp_test
    async def test_listdir(self, sftp):
        """Test listing files in a directory"""

        try:
            os.mkdir('dir')
            self._create_file('dir/file1')
            self._create_file('dir/file2')
            self.assertEqual(sorted(await sftp.listdir('dir')),
                             ['.', '..', 'file1', 'file2'])
        finally:
            remove('dir')

    @sftp_test_v4
    async def test_listdir_v4(self, sftp):
        """Test listing files in a directory with SFTPv4"""

        try:
            os.mkdir('dir')
            self._create_file('dir/file1')
            self._create_file('dir/file2')
            self.assertEqual(sorted(await sftp.listdir('dir')),
                             ['.', '..', 'file1', 'file2'])
        finally:
            remove('dir')

    @sftp_test_v4
    async def test_listdir_error_v4(self, sftp):
        """Test error while listing contents of a directory"""

        orig_readdir = asyncssh.sftp.SFTPClientHandler.readdir

        async def _readdir_error(self, handle):
            """Return an error on an SFTP readdir request"""

            # pylint: disable=unused-argument

            return await orig_readdir(self, b'\xff\xff\xff\xff')

        try:
            os.mkdir('dir')

            with patch('asyncssh.sftp.SFTPClientHandler.readdir',
                       _readdir_error):
                with self.assertRaises(SFTPInvalidHandle):
                    await sftp.listdir('dir')
        finally:
            remove('dir')

    @sftp_test
    async def test_mkdir(self, sftp):
        """Test creating a directory"""

        try:
            await sftp.mkdir('dir')
            self.assertTrue(os.path.isdir('dir'))
        finally:
            remove('dir')

    @sftp_test
    async def test_rmdir(self, sftp):
        """Test removing a directory"""

        try:
            os.mkdir('dir')
            await sftp.rmdir('dir')

            with self.assertRaises(FileNotFoundError):
                os.stat('dir')
        finally:
            remove('dir')

    @sftp_test_v6
    async def test_rmdir_not_empty_v6(self, sftp):
        """Test rmdir on a non-empty directory"""

        try:
            os.mkdir('dir')
            self._create_file('dir/file')

            with self.assertRaises(SFTPDirNotEmpty):
                await sftp.rmdir('dir')
        finally:
            remove('dir')

    @sftp_test_v6
    async def test_open_file_dir_v6(self, sftp):
        """Test open on a directory"""

        try:
            os.mkdir('dir')

            with self.assertRaises((SFTPPermissionDenied,
                                    SFTPFileIsADirectory)):
                await sftp.open('dir')
        finally:
            remove('dir')

    @sftp_test
    async def test_rmtree(self, sftp):
        """Test removing a directory tree"""

        try:
            os.mkdir('dir')
            os.mkdir('dir/dir1')
            os.mkdir('dir/dir1/dir2')
            os.mkdir('dir/dir3')
            self._create_file('dir/file1')
            self._create_file('dir/file2')
            self._create_file('dir/dir1/file3')
            await sftp.rmtree('dir')

            with self.assertRaises(FileNotFoundError):
                os.stat('dir')
        finally:
            remove('dir')

    @sftp_test
    async def test_rmtree_non_existent(self, sftp):
        """Test passing a non-existent directory to rmtree"""

        with self.assertRaises(SFTPNoSuchFile):
            await sftp.rmtree('xxx')

    @sftp_test
    async def test_rmtree_ignore_errors(self, sftp):
        """Test ignoring errors in rmtree"""

        await sftp.rmtree('xxx', ignore_errors=True)

    @sftp_test
    async def test_rmtree_onerror(self, sftp):
        """Test onerror callback in rmtree"""

        def _error_handler(*args):
            errors.append(args)

        errors = []

        await sftp.rmtree('xxx', onerror=_error_handler)

        self.assertEqual(errors[0][0], sftp.scandir)
        self.assertEqual(errors[0][1], b'xxx')
        self.assertEqual(errors[0][2][0], SFTPNoSuchFile)

    @sftp_test
    async def test_rmtree_file(self, sftp):
        """Test passing a file to rmtree"""

        try:
            self._create_file('file')

            with self.assertRaises(SFTPNoSuchFile):
                await sftp.rmtree('file')
        finally:
            remove('file')

    @sftp_test
    async def test_rmtree_symlink(self, sftp):
        """Test passing a symlink to rmtree"""

        try:
            os.mkdir('dir')
            os.symlink('dir', 'link')

            with self.assertRaises(SFTPNoSuchFile):
                await sftp.rmtree('link')
        finally:
            remove('dir link')

    @sftp_test
    async def test_rmtree_symlink_onerror(self, sftp):
        """Test passing a symlink to rmtree with onerror callback"""

        def _error_handler(*args):
            errors.append(args)

        errors = []

        try:
            os.mkdir('dir')
            os.symlink('dir', 'link')

            await sftp.rmtree('link', onerror=_error_handler)

            self.assertEqual(errors[0][0], sftp.islink)
            self.assertEqual(errors[0][1], b'link')
            self.assertEqual(errors[0][2][0], SFTPNoSuchFile)
        finally:
            remove('dir link')

    @sftp_test
    async def test_rmtree_rmdir_failure(self, sftp):
        """Test rmdir failing in rmtree"""

        try:
            os.mkdir('dir')
            os.mkdir('dir/subdir')
            os.chmod('dir', 0o555)

            with self.assertRaises(SFTPPermissionDenied):
                await sftp.rmtree('dir')
        finally:
            os.chmod('dir', 0o755)
            remove('dir')

    @sftp_test
    async def test_rmtree_unlink_failure(self, sftp):
        """Test unlink failing in rmtree"""

        try:
            os.mkdir('dir')
            self._create_file('dir/file')
            os.chmod('dir', 0o555)

            with self.assertRaises(SFTPPermissionDenied):
                await sftp.rmtree('dir')
        finally:
            os.chmod('dir', 0o755)
            remove('dir')

    @sftp_test
    async def test_readlink(self, sftp):
        """Test reading a symlink"""

        if not self._symlink_supported: # pragma: no cover
            raise unittest.SkipTest('symlink not available')

        try:
            os.symlink('/file', 'link')
            self.assertEqual((await sftp.readlink('link')), '/file')
            self.assertEqual((await sftp.readlink(b'link')), b'/file')
        finally:
            remove('link')

    @sftp_test_v6
    async def test_readlink_v6(self, sftp):
        """Test reading a symlink with SFTPv6"""

        if not self._symlink_supported: # pragma: no cover
            raise unittest.SkipTest('symlink not available')

        try:
            os.symlink('/file', 'link')
            self.assertEqual((await sftp.readlink('link')), '/file')
            self.assertEqual((await sftp.readlink(b'link')), b'/file')
        finally:
            remove('link')

    @sftp_test
    async def test_readlink_decode_error(self, sftp):
        """Test unicode decode error while reading a symlink"""

        async def _readlink_error(self, path):
            """Return invalid unicode on an SFTP readlink request"""

            # pylint: disable=unused-argument

            return [SFTPName(b'\xff')], False

        with patch('asyncssh.sftp.SFTPClientHandler.readlink',
                   _readlink_error):
            with self.assertRaises(SFTPBadMessage):
                await sftp.readlink('link')

    @sftp_test
    async def test_symlink(self, sftp):
        """Test creating a symlink"""

        if not self._symlink_supported: # pragma: no cover
            raise unittest.SkipTest('symlink not available')

        try:
            await sftp.symlink('file', 'link')
            self._check_link('link', 'file')

            with self.assertRaises(SFTPFailure):
                await sftp.symlink('file', 'link')
        finally:
            remove('file link')

    @sftp_test_v4
    async def test_symlink_v4(self, sftp):
        """Test creating a symlink with SFTPv4"""

        if not self._symlink_supported: # pragma: no cover
            raise unittest.SkipTest('symlink not available')

        try:
            await sftp.symlink('file', 'link')
            self._check_link('link', 'file')

            with self.assertRaises(SFTPFileAlreadyExists):
                await sftp.symlink('file', 'link')
        finally:
            remove('file link')

    @sftp_test_v6
    async def test_symlink_v6(self, sftp):
        """Test creating a symlink with SFTPv6"""

        try:
            await sftp.symlink('file', 'link')
            self._check_link('link', 'file')

            with self.assertRaises(SFTPFileAlreadyExists):
                await sftp.symlink('file', 'link')
        finally:
            remove('file link')

    @asynctest
    async def test_symlink_encode_error(self):
        """Test creating a unicode symlink with no path encoding set"""

        if not self._symlink_supported: # pragma: no cover
            raise unittest.SkipTest('symlink not available')

        async with self.connect() as conn:
            async with conn.start_sftp_client(path_encoding=None) as sftp:
                with self.assertRaises(SFTPBadMessage):
                    await sftp.symlink('file', 'link')

    @asynctest
    async def test_nonstandard_symlink_client(self):
        """Test creating a symlink with opposite argument order"""

        if not self._symlink_supported: # pragma: no cover
            raise unittest.SkipTest('symlink not available')

        try:
            async with self.connect(client_version='OpenSSH') as conn:
                async with conn.start_sftp_client() as sftp:
                    await sftp.symlink('link', 'file')
                    self._check_link('link', 'file')
        finally:
            remove('file link')

    @sftp_test
    async def test_link(self, sftp):
        """Test creating a hard link"""

        try:
            self._create_file('file1')
            await sftp.link('file1', 'file2')
            self._check_file('file1', 'file2')
        finally:
            remove('file1 file2')

    @sftp_test_v6
    async def test_link_v6(self, sftp):
        """Test creating a hard link with SFTPv6"""

        try:
            self._create_file('file1')
            await sftp.link('file1', 'file2')
            self._check_file('file1', 'file2')
        finally:
            remove('file1 file2')

    @sftp_test
    async def test_open_read(self, sftp):
        """Test reading data from a file"""

        f = None

        try:
            self._create_file('file', 'xxx')

            f = await sftp.open('file')
            self.assertEqual((await f.read()), 'xxx')
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test
    async def test_open_read_bytes(self, sftp):
        """Test reading bytes from a file"""

        f = None

        try:
            self._create_file('file', 'xxx')

            f = await sftp.open('file', 'rb')
            self.assertEqual((await f.read()), b'xxx')

            await f.seek(0)
            self.assertEqual([result async for result in
                              await f.read_parallel()], [(0, b'xxx')])
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test
    async def test_open_read_offset_size(self, sftp):
        """Test reading at a specific offset and size"""

        f = None

        try:
            self._create_file('file', 'xxxxyyyy')

            f = await sftp.open('file')
            self.assertEqual((await f.read(4, 2)), 'xxyy')
            self.assertEqual([result async for result in
                              await f.read_parallel(4, 2)], [(2, b'xxyy')])
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test
    async def test_open_read_no_blocksize(self, sftp):
        """Test reading with no block size set"""

        f = None

        try:
            self._create_file('file', 'xxxxyyyy')

            f = await sftp.open('file', block_size=None)
            self.assertEqual((await f.read(4, 2)), 'xxyy')
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test
    async def test_open_read_parallel(self, sftp):
        """Test reading data from a file using parallel I/O"""

        f = None

        try:
            self._create_file('file', 40*1024*'\0')

            f = await sftp.open('file')
            self.assertEqual(len(await f.read(64*1024)), 40*1024)
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test
    async def test_open_read_max_requests(self, sftp):
        """Test reading data from a file with max requests set"""

        f = None

        try:
            self._create_file('file', 16*1024*1024*'\0')

            f = await sftp.open('file', max_requests=4)
            self.assertEqual(len(await f.read()), 16*1024*1024)
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    def test_open_read_out_of_order(self):
        """Test parallel read with out-of-order responses"""

        @sftp_test
        async def _test_read_out_of_order(self, sftp):
            """Test parallel read with out-of-order responses"""

            f = None

            try:
                random_data = os.urandom(12*1024*1024)
                self._create_file('file', random_data)

                async with sftp.open('file', 'rb') as f:
                    self.assertEqual(await f.read(), random_data)
            finally:
                remove('file')

        with patch('asyncssh.sftp.SFTPServerHandler',
                   _ReorderReadServerHandler):
            # pylint: disable=no-value-for-parameter
            _test_read_out_of_order(self)

    @sftp_test
    async def test_open_read_nonexistent(self, sftp):
        """Test reading data from a nonexistent file"""

        f = None

        try:
            with self.assertRaises(SFTPNoSuchFile):
                f = await sftp.open('file')
        finally:
            if f: # pragma: no cover
                await f.close()

    @unittest.skipIf(sys.platform == 'win32',
                     'skip permission tests on Windows')
    @sftp_test
    async def test_open_read_not_permitted(self, sftp):
        """Test reading data from a file with no read permission"""

        f = None

        try:
            self._create_file('file', mode=0)

            with self.assertRaises(SFTPPermissionDenied):
                f = await sftp.open('file')
        finally:
            if f: # pragma: no cover
                await f.close()

            remove('file')

    @sftp_test
    async def test_open_write(self, sftp):
        """Test writing data to a file"""

        f = None

        try:
            f = await sftp.open('file', 'w')
            await f.write('xxx')
            await f.close()

            with open('file') as localf:
                self.assertEqual(localf.read(), 'xxx')
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test
    async def test_open_write_bytes(self, sftp):
        """Test writing bytes to a file"""

        f = None

        try:
            f = await sftp.open('file', 'wb')
            await f.write(b'xxx')
            await f.close()

            with open('file', 'rb') as localf:
                self.assertEqual(localf.read(), b'xxx')
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test_v6
    async def test_open_write_v6(self, sftp):
        """Test writing bytes to a file with SFTPv6 open"""

        f = None

        try:
            f = await sftp.open('file', 'wb')
            await f.write('xxx')
            await f.close()

            with open('file') as localf:
                self.assertEqual(localf.read(), 'xxx')
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test_v6
    async def test_open56_write_v6(self, sftp):
        """Test writing bytes to a file with SFTPv6 open56"""

        f = None

        try:
            f = await sftp.open56('file', ACE4_WRITE_DATA, FXF_CREATE_TRUNCATE)
            await f.write('xxx')
            await f.close()

            with open('file') as localf:
                self.assertEqual(localf.read(), 'xxx')
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test
    async def test_open_truncate(self, sftp):
        """Test truncating a file at open time"""

        f = None

        try:
            self._create_file('file', 'xxxyyy')

            f = await sftp.open('file', 'w')
            await f.write('zzz')
            await f.close()

            with open('file') as localf:
                self.assertEqual(localf.read(), 'zzz')
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test_v6
    async def test_open_truncate_v6(self, sftp):
        """Test truncating a file at open time with SFTPv6 open"""

        f = None

        try:
            self._create_file('file', 'xxxyyy')

            f = await sftp.open('file', FXF_WRITE | FXF_TRUNC)
            await f.write('zzz')
            await f.close()

            with open('file') as localf:
                self.assertEqual(localf.read(), 'zzz')
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test_v6
    async def test_open56_truncate_v6(self, sftp):
        """Test truncating a file at open time with SFTPv6 open56"""

        f = None

        try:
            self._create_file('file', 'xxxyyy')

            f = await sftp.open56('file', ACE4_WRITE_DATA,
                                  FXF_TRUNCATE_EXISTING)
            await f.write('zzz')
            await f.close()

            with open('file') as localf:
                self.assertEqual(localf.read(), 'zzz')
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test
    async def test_open_append(self, sftp):
        """Test appending data to an existing file"""

        f = None

        try:
            self._create_file('file', 'xxx')

            f = await sftp.open('file', 'a+')
            await f.write('yyy')
            self.assertEqual((await f.read()), '')
            self.assertEqual([result async for result in
                              await f.read_parallel()], [])
            await f.close()

            with open('file') as localf:
                self.assertEqual(localf.read(), 'xxxyyy')
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test_v6
    async def test_open_append_v6(self, sftp):
        """Test appending data to an existing file with SFTPv6 open"""

        f = None

        try:
            self._create_file('file', 'xxx')

            f = await sftp.open('file', FXF_WRITE | FXF_APPEND)
            await f.write('yyy')
            self.assertEqual((await f.read()), '')
            await f.close()

            with open('file') as localf:
                self.assertEqual(localf.read(), 'xxxyyy')
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test_v6
    async def test_open56_append_v6(self, sftp):
        """Test appending data to an existing file with SFTPv6 open56"""

        f = None

        try:
            self._create_file('file', 'xxx')

            f = await sftp.open56('file', ACE4_READ_DATA | ACE4_WRITE_DATA |
                                  ACE4_APPEND_DATA, FXF_OPEN_EXISTING |
                                  FXF_APPEND_DATA)
            await f.write('yyy')
            self.assertEqual((await f.read()), '')
            await f.close()

            with open('file') as localf:
                self.assertEqual(localf.read(), 'xxxyyy')
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test
    async def test_open_exclusive_create(self, sftp):
        """Test creating a new file"""

        f = None

        try:
            f = await sftp.open('file', 'x')
            await f.write('xxx')
            await f.close()

            with open('file') as localf:
                self.assertEqual(localf.read(), 'xxx')

            with self.assertRaises(SFTPFailure):
                f = await sftp.open('file', 'x')
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test_v6
    async def test_open_exclusive_create_v6(self, sftp):
        """Test creating a new file with SFTPv6 open"""

        f = None

        try:
            f = await sftp.open('file', 'x')
            await f.write('xxx')
            await f.close()

            with open('file') as localf:
                self.assertEqual(localf.read(), 'xxx')

            with self.assertRaises(SFTPFileAlreadyExists):
                f = await sftp.open('file', 'x')
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test_v6
    async def test_open56_exclusive_create_v6(self, sftp):
        """Test creating a new file with SFTPv6 open56"""

        f = None

        try:
            f = await sftp.open56('file', ACE4_WRITE_DATA, FXF_CREATE_NEW)
            await f.write('xxx')
            await f.close()

            with open('file') as localf:
                self.assertEqual(localf.read(), 'xxx')

            with self.assertRaises(SFTPFileAlreadyExists):
                f = await sftp.open56('file', ACE4_WRITE_DATA, FXF_CREATE_NEW)
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test
    async def test_open_exclusive_create_existing(self, sftp):
        """Test exclusive create of an existing file"""

        f = None

        try:
            self._create_file('file')

            with self.assertRaises(SFTPFailure):
                f = await sftp.open('file', 'x')
        finally:
            if f: # pragma: no cover
                await f.close()

            remove('file')

    @sftp_test_v4
    async def test_open_exclusive_create_existing_v4(self, sftp):
        """Test exclusive create of an existing file with SFTPv4"""

        f = None

        try:
            self._create_file('file')

            with self.assertRaises(SFTPFileAlreadyExists):
                f = await sftp.open('file', 'x')
        finally:
            if f: # pragma: no cover
                await f.close()

            remove('file')

    @sftp_test_v6
    async def test_open56_exclusive_create_existing_v6(self, sftp):
        """Test exclusive create of an existing file with SFTPv6 open56"""

        f = None

        try:
            self._create_file('file')

            with self.assertRaises(SFTPFileAlreadyExists):
                f = await sftp.open56('file', ACE4_WRITE_DATA, FXF_CREATE_NEW)
        finally:
            if f: # pragma: no cover
                await f.close()

            remove('file')

    @sftp_test
    async def test_open_overwrite(self, sftp):
        """Test overwriting part of an existing file"""

        f = None

        try:
            self._create_file('file', 'xxxyyy')

            f = await sftp.open('file', 'r+')
            await f.write('zzz')
            await f.close()

            with open('file') as localf:
                self.assertEqual(localf.read(), 'zzzyyy')
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test_v6
    async def test_open56_overwrite_v6(self, sftp):
        """Test overwriting part of an existing file with SFTPv6 open56"""

        f = None

        try:
            self._create_file('file', 'xxxyyy')

            f = await sftp.open56('file', ACE4_WRITE_DATA, FXF_OPEN_EXISTING)
            await f.write('zzz')
            await f.close()

            with open('file') as localf:
                self.assertEqual(localf.read(), 'zzzyyy')
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test
    async def test_open_overwrite_offset_size(self, sftp):
        """Test writing data at a specific offset"""

        f = None

        try:
            self._create_file('file', 'xxxxyyyy')

            f = await sftp.open('file', 'r+')
            await f.write('zz', 3)
            await f.close()

            with open('file') as localf:
                self.assertEqual(localf.read(), 'xxxzzyyy')
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test_v6
    async def test_open_overwrite_offset_size_v6(self, sftp):
        """Test writing data at a specific offset with SFTPv6 open"""

        f = None

        try:
            self._create_file('file', 'xxxxyyyy')

            f = await sftp.open('file', FXF_WRITE | FXF_CREAT)
            await f.write('zz', 3)
            await f.close()

            with open('file') as localf:
                self.assertEqual(localf.read(), 'xxxzzyyy')
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test_v6
    async def test_open56_overwrite_offset_size_v6(self, sftp):
        """Test writing data at a specific offset with SFTPv6 open56"""

        f = None

        try:
            self._create_file('file', 'xxxxyyyy')

            f = await sftp.open56('file', ACE4_WRITE_DATA, FXF_OPEN_OR_CREATE)
            await f.write('zz', 3)
            await f.close()

            with open('file') as localf:
                self.assertEqual(localf.read(), 'xxxzzyyy')
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test
    async def test_open_overwrite_nonexistent(self, sftp):
        """Test overwriting a nonexistent file"""

        f = None

        try:
            with self.assertRaises(SFTPNoSuchFile):
                f = await sftp.open('file', 'r+')
        finally:
            if f: # pragma: no cover
                await f.close()

    @sftp_test_v6
    async def test_open_link_loop_v6(self, sftp):
        """Test opening a symlink which is a loop"""

        f = None

        try:
            os.symlink('link1', 'link2')
            os.symlink('link2', 'link1')

            with self.assertRaises((SFTPInvalidParameter, SFTPLinkLoop)):
                f = await sftp.open('link1')
        finally:
            if f: # pragma: no cover
                await f.close()

            remove('link1 link2')

    @sftp_test
    async def test_file_seek(self, sftp):
        """Test seeking within a file"""

        f = None

        try:
            f = await sftp.open('file', 'w+')
            await f.write('xxxxyyyy')
            await f.seek(3)
            await f.write('zz')

            await f.seek(-3, SEEK_CUR)
            self.assertEqual((await f.read(4)), 'xzzy')

            await f.seek(-4, SEEK_END)
            self.assertEqual((await f.read()), 'zyyy')
            self.assertEqual((await f.read()), '')
            self.assertEqual((await f.read(1)), '')

            with self.assertRaises(ValueError):
                await f.seek(0, -1)

            await f.close()

            f = await sftp.open('file', 'a+')
            await f.seek(-4, SEEK_CUR)
            self.assertEqual((await f.read()), 'zyyy')

            await f.close()

            with open('file') as localf:
                self.assertEqual(localf.read(), 'xxxzzyyy')
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test
    async def test_file_stat(self, sftp):
        """Test getting attributes on an open file"""

        f = None

        try:
            f = await sftp.open('file', 'w')
            self._check_stat((await f.stat()), os.stat('file'))
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test_v4
    async def test_file_stat_v4(self, sftp):
        """Test getting attributes on an open file with SFTPv4"""

        f = None

        try:
            f = await sftp.open('file', 'w')
            self._check_stat_v4((await f.stat()), os.stat('file'))
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test_v6
    async def test_file_stat_v6(self, sftp):
        """Test getting attributes on an open file with SFTPv6"""

        f = None

        try:
            f = await sftp.open('file', 'w')
            self._check_stat_v4((await f.stat()), os.stat('file'))
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test
    async def test_file_setstat(self, sftp):
        """Test setting attributes on an open file"""

        f = None

        try:
            f = await sftp.open('file', 'w')
            await f.setstat(SFTPAttrs(permissions=0o666))

            self.assertEqual(stat.S_IMODE(os.stat('file').st_mode), 0o666)
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test_v6
    async def test_file_setstat_v6(self, sftp):
        """Test setting attributes on an open file with SFTPv6"""

        f = None

        try:
            f = await sftp.open('file', 'w')
            await f.setstat(SFTPAttrs(permissions=0o666))

            self.assertEqual(stat.S_IMODE(os.stat('file').st_mode), 0o666)
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @unittest.skipIf(sys.platform == 'win32', 'skip chown tests on Windows')
    @sftp_test
    async def test_file_chown(self, sftp):
        """Test changing ownership of an open file

           We can't change to a different user/group here if we're not
           root, so just change to the same user/group. See the separate
           _TestSFTPChown class for a more complete test, but this is
           left in for code coverage purposes.

        """

        f = None

        try:
            f = await sftp.open('file', 'w')
            stat_result = os.stat('file')

            await f.chown(stat_result.st_uid, stat_result.st_gid)

            new_stat_result = os.stat('file')
            self.assertEqual(new_stat_result.st_uid, stat_result.st_uid)
            self.assertEqual(new_stat_result.st_gid, stat_result.st_gid)

            await f.chown(uid=stat_result.st_uid, gid=stat_result.st_gid)

            new_stat_result = os.stat('file')
            self.assertEqual(new_stat_result.st_uid, stat_result.st_uid)
            self.assertEqual(new_stat_result.st_gid, stat_result.st_gid)
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @unittest.skipIf(sys.platform == 'win32', 'skip chown tests on Windows')
    @sftp_test_v4
    async def test_file_chown_v4(self, sftp):
        """Test changing ownership of an open file

           We can't change to a different user/group here if we're not
           root, so just change to the same user/group. See the separate
           _TestSFTPChown class for a more complete test, but this is
           left in for code coverage purposes.

        """

        f = None

        try:
            f = await sftp.open('file', 'w')
            stat_result = os.stat('file')

            owner = lookup_user(stat_result.st_uid)
            group = lookup_group(stat_result.st_gid)

            await f.chown(owner, group)

            new_stat_result = os.stat('file')
            self.assertEqual(new_stat_result.st_uid, stat_result.st_uid)
            self.assertEqual(new_stat_result.st_gid, stat_result.st_gid)

            await f.chown(owner=owner, group=group)

            new_stat_result = os.stat('file')
            self.assertEqual(new_stat_result.st_uid, stat_result.st_uid)
            self.assertEqual(new_stat_result.st_gid, stat_result.st_gid)
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test
    async def test_file_truncate(self, sftp):
        """Test truncating an open file"""

        f = None

        try:
            self._create_file('file', '01234567890123456789')

            f = await sftp.open('file', 'a+')
            await f.truncate(10)
            self.assertEqual((await f.tell()), 10)
            self.assertEqual((await f.read(offset=0)), '0123456789')
            self.assertEqual((await f.tell()), 10)
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test
    async def test_file_utime(self, sftp):
        """Test changing access and modify times on an open file"""

        f = None

        try:
            f = await sftp.open('file', 'w')
            await f.utime()
            await f.utime((1, 2))

            stat_result = os.stat('file')
            self.assertEqual(stat_result.st_atime, 1)
            self.assertEqual(stat_result.st_mtime, 2)
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test_v4
    async def test_file_utime_v4(self, sftp):
        """Test changing access and modify times on an open file with SFTPv4"""

        f = None

        try:
            f = await sftp.open('file', 'w')
            await f.utime()
            await f.utime((1.0, 2.25))

            stat_result = os.stat('file')
            self.assertEqual(stat_result.st_atime, 1.0)
            self.assertEqual(stat_result.st_atime_ns, 1000000000)
            self.assertEqual(stat_result.st_mtime, 2.25)
            self.assertEqual(stat_result.st_mtime_ns, 2250000000)
            self.assertEqual((await sftp.getatime('file')), 1.0)
            self.assertEqual((await sftp.getatime_ns('file')), 1000000000)
            self.assertIsNotNone(await sftp.getcrtime('file'))
            self.assertIsNotNone(await sftp.getcrtime_ns('file'))
            self.assertEqual((await sftp.getmtime('file')), 2.25)
            self.assertEqual((await sftp.getmtime_ns('file')), 2250000000)

            await f.utime('file', ns=(3500000000, 4750000000))

            stat_result = os.stat('file')
            self.assertEqual(stat_result.st_atime, 3.5)
            self.assertEqual(stat_result.st_atime_ns, 3500000000)
            self.assertEqual(stat_result.st_mtime, 4.75)
            self.assertEqual(stat_result.st_mtime_ns, 4750000000)
            self.assertEqual((await sftp.getatime('file')), 3.5)
            self.assertEqual((await sftp.getatime_ns('file')), 3500000000)
            self.assertIsNotNone(await sftp.getcrtime('file'))
            self.assertIsNotNone(await sftp.getcrtime_ns('file'))
            self.assertEqual((await sftp.getmtime('file')), 4.75)
            self.assertEqual((await sftp.getmtime_ns('file')), 4750000000)
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @unittest.skipIf(sys.platform == 'win32', 'skip statvfs tests on Windows')
    @sftp_test
    async def test_file_statvfs(self, sftp):
        """Test getting attributes on the filesystem containing an open file

           We can't compare the values returned by a live statvfs call since
           they can change at any time. See the separate _TestSFTStatPVFS
           class for a more complete test, but this is left in for code
           coverage purposes.

        """

        f = None

        try:
            f = await sftp.open('file', 'w')
            self.assertIsInstance((await f.statvfs()), SFTPVFSAttrs)
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test
    async def test_file_lock(self, sftp):
        """Test file lock against earlier version SFTP server"""

        f = None

        try:
            f = await sftp.open('file', 'w')

            with self.assertRaises(SFTPOpUnsupported):
                await f.lock(0, 0, FXF_BLOCK_READ)

            with self.assertRaises(SFTPOpUnsupported):
                await f.unlock(0, 0)
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test_v6
    async def test_file_lock_v6(self, sftp):
        """Test file lock"""

        f = None

        try:
            f = await sftp.open('file', 'w')

            with self.assertRaises(SFTPOpUnsupported):
                await f.lock(0, 0, FXF_BLOCK_READ)

            with self.assertRaises(SFTPOpUnsupported):
                await f.unlock(0, 0)
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test
    async def test_file_sync(self, sftp):
        """Test file sync"""

        f = None

        try:
            f = await sftp.open('file', 'w')
            self.assertIsNone(await f.fsync())
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test
    async def test_exited_session(self, sftp):
        """Test use of SFTP session after exit"""

        sftp.exit()
        await sftp.wait_closed()

        f = None

        try:
            with self.assertRaises(SFTPNoConnection):
                f = await sftp.open('file')
        finally:
            if f: # pragma: no cover
                await f.close()

    @sftp_test
    async def test_cleanup_open_files(self, sftp):
        """Test cleanup of open file handles on exit"""

        try:
            await sftp.open('file', 'w')
        finally:
            sftp.exit()
            await sftp.wait_closed()

            remove('file')

    @sftp_test
    async def test_invalid_open_mode(self, sftp):
        """Test opening file with invalid mode"""

        with self.assertRaises(ValueError):
            await sftp.open('file', 'z')

    @sftp_test
    async def test_invalid_open56(self, sftp):
        """Test calling open56 on an earlier version SFTP server"""

        with self.assertRaises(SFTPOpUnsupported):
            await sftp.open56('file', ACE4_WRITE_DATA, FXF_OPEN_OR_CREATE)

    @sftp_test_v6
    async def test_invalid_access_flags_v6(self, sftp):
        """Test opening file with invalid access flags with SFTPv6"""

        with self.assertRaises(SFTPInvalidParameter):
            await sftp.open56('file', 0x80000000, FXF_OPEN_OR_CREATE)

    @sftp_test_v6
    async def test_invalid_open_flags_v6(self, sftp):
        """Test opening file with invalid open flags with SFTPv6"""

        with self.assertRaises(SFTPInvalidParameter):
            await sftp.open56('file', ACE4_WRITE_DATA, 0x80000000)

    @sftp_test
    async def test_invalid_handle(self, sftp):
        """Test sending requests associated with an invalid file handle"""

        async def _return_invalid_handle(self, path, pflags, attrs):
            """Return an invalid file handle"""

            # pylint: disable=unused-argument

            return UInt32(0xffffffff)

        with patch('asyncssh.sftp.SFTPClientHandler.open',
                   _return_invalid_handle):
            f = await sftp.open('file')

            with self.assertRaises(SFTPFailure):
                _ = [_ async for _ in f.request_ranges(0, 0)]

            with self.assertRaises(SFTPFailure):
                await f.read()

            with self.assertRaises(SFTPFailure):
                await f.read(1)

            with self.assertRaises(SFTPFailure):
                await f.write('')

            with self.assertRaises(SFTPFailure):
                await f.stat()

            with self.assertRaises(SFTPFailure):
                await f.setstat(SFTPAttrs())

            if sys.platform != 'win32': # pragma: no branch
                with self.assertRaises(SFTPFailure):
                    await f.statvfs()

            with self.assertRaises(SFTPFailure):
                await f.fsync()

            with self.assertRaises(SFTPFailure):
                await sftp.remote_copy(f, f)

            with self.assertRaises(SFTPFailure):
                await f.close()

    @sftp_test_v6
    async def test_invalid_handle_v6(self, sftp):
        """Test sending requests associated with an invalid file handle"""

        async def _return_invalid_handle(self, path, pflags, attrs):
            """Return an invalid file handle"""

            # pylint: disable=unused-argument

            return UInt32(0xffffffff)

        with patch('asyncssh.sftp.SFTPClientHandler.open',
                   _return_invalid_handle):
            f = await sftp.open('file')

            with self.assertRaises(SFTPInvalidHandle):
                await f.lock(0, 0, FXF_BLOCK_READ)

            with self.assertRaises(SFTPInvalidHandle):
                await f.unlock(0, 0)

    @sftp_test
    async def test_closed_file(self, sftp):
        """Test I/O operations on a closed file"""

        f = None

        try:
            self._create_file('file')

            async with sftp.open('file') as f:
                # Do an explicit close to test double-close
                await f.close()

            with self.assertRaises(ValueError):
                await f.read()

            with self.assertRaises(ValueError):
                await f.read_parallel()

            with self.assertRaises(ValueError):
                await f.write('')

            with self.assertRaises(ValueError):
                await f.seek(0)

            with self.assertRaises(ValueError):
                await f.tell()

            with self.assertRaises(ValueError):
                await f.stat()

            with self.assertRaises(ValueError):
                await f.setstat(SFTPAttrs())

            with self.assertRaises(ValueError):
                await f.statvfs()

            with self.assertRaises(ValueError):
                await f.truncate()

            with self.assertRaises(ValueError):
                await f.chown(0, 0)

            with self.assertRaises(ValueError):
                await f.chmod(0)

            with self.assertRaises(ValueError):
                await f.utime()

            with self.assertRaises(ValueError):
                await f.lock(0, 0, FXF_BLOCK_READ)

            with self.assertRaises(ValueError):
                await f.unlock(0, 0)

            with self.assertRaises(ValueError):
                await f.fsync()
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    def test_unexpected_client_close(self):
        """Test an unexpected connection close from client"""

        async def _unexpected_client_close(self):
            """Close the SSH connection before sending an init request"""

            self._writer.channel.get_connection().abort()

        with patch('asyncssh.sftp.SFTPClientHandler.start',
                   _unexpected_client_close):
            # pylint: disable=no-value-for-parameter
            self._dummy_sftp_client()

    def test_unexpected_server_close(self):
        """Test an unexpected connection close from server"""

        async def _unexpected_server_close(self):
            """Close the SSH connection before sending a version response"""

            packet = await SFTPHandler.recv_packet(self)
            self._writer.channel.get_connection().abort()
            return packet

        with patch('asyncssh.sftp.SFTPServerHandler.recv_packet',
                   _unexpected_server_close):
            with self.assertRaises(SFTPConnectionLost):
                # pylint: disable=no-value-for-parameter
                self._dummy_sftp_client()

    def test_incomplete_message(self):
        """Test session cleanup in the middle of a write request"""

        with patch('asyncssh.sftp.SFTPServerHandler',
                   _IncompleteMessageServerHandler):
            with self.assertRaises(SFTPConnectionLost):
                # pylint: disable=no-value-for-parameter
                self._dummy_sftp_client()

    def test_immediate_client_close(self):
        """Test closing SFTP channel immediately after opening"""

        async def _closing_start(self):
            """Immediately close the SFTP channel"""

            self.exit()

        with patch('asyncssh.sftp.SFTPClientHandler.start', _closing_start):
            # pylint: disable=no-value-for-parameter
            self._dummy_sftp_client()

    def test_no_init(self):
        """Test sending non-init request at start"""

        async def _no_init_start(self):
            """Send a non-init request at start"""

            self.send_packet(FXP_OPEN, 0, UInt32(0))

        with patch('asyncssh.sftp.SFTPClientHandler.start', _no_init_start):
            # pylint: disable=no-value-for-parameter
            self._dummy_sftp_client()

    def test_incomplete_init_request(self):
        """Test sending init with missing version"""

        async def _missing_version_start(self):
            """Send an init request with missing version"""

            self.send_packet(FXP_INIT, None)

        with patch('asyncssh.sftp.SFTPClientHandler.start',
                   _missing_version_start):
            # pylint: disable=no-value-for-parameter
            self._dummy_sftp_client()

    def test_incomplete_version_response(self):
        """Test sending an incomplete version response"""

        async def _incomplete_version_response(self):
            """Send an incomplete version response"""

            packet = await SFTPHandler.recv_packet(self)
            self.send_packet(FXP_VERSION, None)
            return packet

        with patch('asyncssh.sftp.SFTPServerHandler.recv_packet',
                   _incomplete_version_response):
            with self.assertRaises(SFTPBadMessage):
                # pylint: disable=no-value-for-parameter
                self._dummy_sftp_client()

    def test_nonstandard_version(self):
        """Test sending init with non-standard version"""

        with patch('asyncssh.sftp.MIN_SFTP_VERSION', 2):
            # pylint: disable=no-value-for-parameter
            self._dummy_sftp_client()

    def test_non_version_response(self):
        """Test sending a non-version message in response to init"""

        async def _non_version_response(self):
            """Send a non-version response to init"""

            packet = await SFTPHandler.recv_packet(self)
            self.send_packet(FXP_STATUS, None)
            return packet

        with patch('asyncssh.sftp.SFTPServerHandler.recv_packet',
                   _non_version_response):
            with self.assertRaises(SFTPBadMessage):
                # pylint: disable=no-value-for-parameter
                self._dummy_sftp_client()

    def test_unsupported_version_response(self):
        """Test sending an unsupported version in response to init"""

        async def _unsupported_version_response(self):
            """Send an unsupported version in response to init"""

            packet = await SFTPHandler.recv_packet(self)
            self.send_packet(FXP_VERSION, None, UInt32(99))
            return packet

        with patch('asyncssh.sftp.SFTPServerHandler.recv_packet',
                   _unsupported_version_response):
            with self.assertRaises(SFTPBadMessage):
                # pylint: disable=no-value-for-parameter
                self._dummy_sftp_client()

    def test_extension_in_init(self):
        """Test sending an extension in version 3 init request"""

        async def _init_extension_start(self):
            """Send an init request with missing version"""

            self.send_packet(FXP_INIT, None, UInt32(3), String(b'xxx'),
                             String(b'1'))

        with patch('asyncssh.sftp.SFTPClientHandler.start',
                   _init_extension_start):
            # pylint: disable=no-value-for-parameter
            self._dummy_sftp_client()

    def test_unknown_extension_response(self):
        """Test sending an unknown extension in version response"""

        with patch('asyncssh.sftp.SFTPServerHandler._extensions',
                   [(b'xxx', b'1')]):
            # pylint: disable=no-value-for-parameter
            self._dummy_sftp_client()

    def test_empty_extension_response_v5(self):
        """Test sending an empty extension list in SFTPv5 version response"""

        with patch('asyncssh.sftp.SFTPServerHandler._extensions', []):
            # pylint: disable=no-value-for-parameter
            self._dummy_sftp_client_v5()

    def test_attrib_extension_response_v6(self):
        """Test sending an attrib extension in version response"""

        with patch('asyncssh.sftp.SFTPServerHandler._attrib_extensions',
                   [b'xxx']):
            # pylint: disable=no-value-for-parameter
            self._dummy_sftp_client_v6()

    def test_close_after_init(self):
        """Test close immediately after init request at start"""

        async def _close_after_init_start(self):
            """Send a close immediately after init request at start"""

            self.send_packet(FXP_INIT, None, UInt32(3))
            await self._cleanup(None)

        with patch('asyncssh.sftp.SFTPClientHandler.start',
                   _close_after_init_start):
            # pylint: disable=no-value-for-parameter
            self._dummy_sftp_client()

    def test_file_handle_skip(self):
        """Test skipping over a file handle already in use"""

        @sftp_test
        async def _reset_file_handle(self, sftp):
            """Open multiple files, resetting next handle each time"""

            file1 = None
            file2 = None

            try:
                self._create_file('file1', 'xxx')
                self._create_file('file2', 'yyy')

                file1 = await sftp.open('file1')
                file2 = await sftp.open('file2')

                self.assertEqual((await file1.read()), 'xxx')
                self.assertEqual((await file2.read()), 'yyy')
            finally:
                if file1: # pragma: no branch
                    await file1.close()

                if file2: # pragma: no branch
                    await file2.close()

                remove('file1 file2')

        with patch('asyncssh.sftp.SFTPServerHandler',
                   _ResetFileHandleServerHandler):
            # pylint: disable=no-value-for-parameter
            _reset_file_handle(self)

    @sftp_test
    async def test_missing_request_pktid(self, sftp):
        """Test sending request without a packet ID"""

        async def _missing_pktid(self, filename, pflags, attrs):
            """Send a request without a packet ID"""

            # pylint: disable=unused-argument

            self.send_packet(FXP_OPEN, None)

        with patch('asyncssh.sftp.SFTPClientHandler.open', _missing_pktid):
            await sftp.open('file')

    @sftp_test
    async def test_malformed_open_request(self, sftp):
        """Test sending malformed open request"""

        async def _malformed_open(self, filename, pflags, attrs):
            """Send a malformed open request"""

            # pylint: disable=unused-argument

            return await self._make_request(FXP_OPEN)

        with patch('asyncssh.sftp.SFTPClientHandler.open', _malformed_open):
            with self.assertRaises(SFTPBadMessage):
                await sftp.open('file')

    @sftp_test
    async def test_unknown_request(self, sftp):
        """Test sending unknown request type"""

        async def _unknown_request(self, filename, pflags, attrs):
            """Send a request with an unknown type"""

            # pylint: disable=unused-argument

            return await self._make_request(0xff)

        with patch('asyncssh.sftp.SFTPClientHandler.open', _unknown_request):
            with self.assertRaises(SFTPOpUnsupported):
                await sftp.open('file')

    @sftp_test
    async def test_unrecognized_response_pktid(self, sftp):
        """Test sending a response with an unrecognized packet ID"""

        async def _unrecognized_response_pktid(self, pkttype, pktid, packet):
            """Send a response with an unrecognized packet ID"""

            # pylint: disable=unused-argument

            self.send_packet(FXP_HANDLE, 0xffffffff,
                             UInt32(0xffffffff), String(''))

        with patch('asyncssh.sftp.SFTPServerHandler._process_packet',
                   _unrecognized_response_pktid):
            with self.assertRaises(SFTPBadMessage):
                await sftp.open('file')

    @sftp_test
    async def test_bad_response_type(self, sftp):
        """Test sending a response with an incorrect response type"""

        async def _bad_response_type(self, pkttype, pktid, packet):
            """Send a response with an incorrect response type"""

            # pylint: disable=unused-argument

            self.send_packet(FXP_DATA, pktid, UInt32(pktid), String(''))

        with patch('asyncssh.sftp.SFTPServerHandler._process_packet',
                   _bad_response_type):
            with self.assertRaises(SFTPBadMessage):
                await sftp.open('file')

    @sftp_test
    async def test_unexpected_ok_response(self, sftp):
        """Test sending an unexpected FX_OK response"""

        async def _unexpected_ok_response(self, pkttype, pktid, packet):
            """Send an unexpected FX_OK response"""

            # pylint: disable=unused-argument

            self.send_packet(FXP_STATUS, pktid, UInt32(pktid), UInt32(FX_OK),
                             String(''), String(''))

        with patch('asyncssh.sftp.SFTPServerHandler._process_packet',
                   _unexpected_ok_response):
            with self.assertRaises(SFTPBadMessage):
                await sftp.open('file')

    @sftp_test
    async def test_malformed_ok_response(self, sftp):
        """Test sending an FX_OK response containing invalid Unicode"""

        async def _malformed_ok_response(self, pkttype, pktid, packet):
            """Send an FX_OK response containing invalid Unicode"""

            # pylint: disable=unused-argument

            self.send_packet(FXP_STATUS, pktid, UInt32(pktid), UInt32(FX_OK),
                             String(b'\xff'), String(''))

        with patch('asyncssh.sftp.SFTPServerHandler._process_packet',
                   _malformed_ok_response):
            with self.assertRaises(SFTPBadMessage):
                await sftp.open('file')

    @sftp_test
    async def test_short_ok_response(self, sftp):
        """Test sending an FX_OK response without a reason and lang"""

        async def _short_ok_response(self, pkttype, pktid, packet):
            """Send an FX_OK response missing reason and lang"""

            # pylint: disable=unused-argument

            self.send_packet(FXP_STATUS, pktid, UInt32(pktid), UInt32(FX_OK))

        with patch('asyncssh.sftp.SFTPServerHandler._process_packet',
                   _short_ok_response):
            self.assertIsNone(await sftp.mkdir('dir'))

    @sftp_test
    async def test_malformed_realpath_response(self, sftp):
        """Test receiving malformed realpath response"""

        async def _malformed_realpath(self, path):
            """Return a malformed realpath response"""

            # pylint: disable=unused-argument

            return [SFTPName(''), SFTPName('')], False

        with patch('asyncssh.sftp.SFTPClientHandler.realpath',
                   _malformed_realpath):
            with self.assertRaises(SFTPBadMessage):
                await sftp.realpath('.')

    @sftp_test
    async def test_malformed_readlink_response(self, sftp):
        """Test receiving malformed readlink response"""

        async def _malformed_readlink(self, path):
            """Return a malformed readlink response"""

            # pylint: disable=unused-argument

            return [SFTPName(''), SFTPName('')], False

        with patch('asyncssh.sftp.SFTPClientHandler.readlink',
                   _malformed_readlink):
            with self.assertRaises(SFTPBadMessage):
                await sftp.readlink('.')

    def test_unsupported_extensions(self):
        """Test using extensions on a server that doesn't support them"""

        @sftp_test
        async def _unsupported_extensions(self, sftp):
            """Try using unsupported extensions"""

            f = None

            try:
                self._create_file('file1', 'xxx')
                self._create_file('file2', 'yyy')

                with self.assertRaises(SFTPOpUnsupported):
                    await sftp.statvfs('.')

                f = await sftp.open('file1')

                with self.assertRaises(SFTPOpUnsupported):
                    await f.statvfs()

                with self.assertRaises(SFTPOpUnsupported):
                    await sftp.posix_rename('file1', 'file2')

                with self.assertRaises(SFTPOpUnsupported):
                    await sftp.rename('file1', 'file2', flags=FXR_OVERWRITE)

                with self.assertRaises(SFTPOpUnsupported):
                    await sftp.link('file1', 'file2')

                with self.assertRaises(SFTPOpUnsupported):
                    await f.fsync()

                with self.assertRaises(SFTPOpUnsupported):
                    await sftp.setstat('file1', SFTPAttrs(),
                                       follow_symlinks=False)
            finally:
                if f: # pragma: no branch
                    await f.close()

                remove('file1')

        with patch('asyncssh.sftp.SFTPServerHandler._extensions', []):
            # pylint: disable=no-value-for-parameter
            _unsupported_extensions(self)

    def test_unsupported_extensions_v6(self):
        """Test using extensions on a server that doesn't support them"""

        @sftp_test_v6
        async def _unsupported_extensions_v6(self, sftp):
            """Try using unsupported extensions"""

            try:
                self._create_file('file1', 'xxx')
                self._create_file('file2', 'yyy')
                self._create_file('file3', 'zzz')

                await sftp.posix_rename('file1', 'file2')

                with open('file2') as localf:
                    self.assertEqual(localf.read(), 'xxx')

                await sftp.rename('file2', 'file3', FXR_OVERWRITE)

                with open('file3') as localf:
                    self.assertEqual(localf.read(), 'xxx')

                await sftp.link('file3', 'file4')

                with open('file4') as localf:
                    self.assertEqual(localf.read(), 'xxx')
            finally:
                remove('file1 file2 file3 file4')

        with patch('asyncssh.sftp.SFTPServerHandler._extensions', []):
            # pylint: disable=no-value-for-parameter
            _unsupported_extensions_v6(self)

    @asynctest
    async def test_zero_limits(self):
        """Test sending a server limits response with zero read/write length"""

        async def _send_zero_read_write_len(self, packet):
            """Send a server limits response with zero read/write length"""

            # pylint: disable=unused-argument

            return SFTPLimits(0, 0, 0, 0)

        with patch.dict('asyncssh.sftp.SFTPServerHandler._packet_handlers',
                        {b'limits@openssh.com': _send_zero_read_write_len}):
            async with self.connect() as conn:
                async with conn.start_sftp_client() as sftp:
                    self.assertEqual(sftp.limits.max_read_len,
                                     SAFE_SFTP_READ_LEN)
                    self.assertEqual(sftp.limits.max_write_len,
                                     SAFE_SFTP_WRITE_LEN)

    def test_write_close(self):
        """Test session cleanup in the middle of a write request"""

        @sftp_test
        async def _write_close(self, sftp):
            """Initiate write that triggers cleanup"""

            try:
                async with sftp.open('file', 'w') as f:
                    with self.assertRaises(SFTPConnectionLost):
                        await f.write('a')
            finally:
                sftp.exit()

                remove('file')

        with patch('asyncssh.sftp.SFTPServerHandler', _WriteCloseServerHandler):
            # pylint: disable=no-value-for-parameter
            _write_close(self)

    @sftp_test_v4
    async def test_write_protect_v4(self, sftp):
        """Test write protect error in SFTPv4"""

        def _write_error(self, file_obj, offset, data):
            """Return read-only FS error when writing to a file"""

            raise OSError(errno.EROFS, 'Read-only filesystem')

        try:
            with patch('asyncssh.sftp.SFTPServer.write', _write_error):
                with self.assertRaises(SFTPWriteProtect):
                    async with sftp.open('file', 'wb') as f:
                        await f.write(b'\0')
        finally:
            remove('file')

    @sftp_test_v4
    async def test_no_media_v4(self, sftp):
        """Test no media error in SFTPv4"""

        def _write_error(self, file_obj, offset, data):
            """Return read-only FS error when writing to a file"""

            raise SFTPNoMedia('No media in requested drive')

        try:
            with patch('asyncssh.sftp.SFTPServer.write', _write_error):
                with self.assertRaises(SFTPNoMedia):
                    async with sftp.open('file', 'wb') as f:
                        await f.write(b'\0')
        finally:
            remove('file')

    @sftp_test_v5
    async def test_no_space_v5(self, sftp):
        """Test no space on filesystem error in SFTPv5"""

        def _write_error(self, file_obj, offset, data):
            """Return no space error when writing to a file"""

            raise OSError(errno.ENOSPC, 'No space left on device')

        try:
            with patch('asyncssh.sftp.SFTPServer.write', _write_error):
                with self.assertRaises(SFTPNoSpaceOnFilesystem):
                    async with sftp.open('file', 'wb') as f:
                        await f.write(b'\0')
        finally:
            remove('file')

    @sftp_test_v5
    async def test_quota_exceeded_v5(self, sftp):
        """Test quota exceeded error in SFTPv5"""

        def _write_error(self, file_obj, offset, data):
            """Return quota exceeded error when writing to a file"""

            raise OSError(errno.EDQUOT, 'Disk quota exceeded')

        try:
            with patch('asyncssh.sftp.SFTPServer.write', _write_error):
                with self.assertRaises(SFTPQuotaExceeded):
                    async with sftp.open('file', 'wb') as f:
                        await f.write(b'\0')
        finally:
            remove('file')

    @sftp_test_v5
    async def test_unknown_principal_v5(self, sftp):
        """Test unknown principal error in SFTPv5"""

        def _open56_error(self, path, desired_access, flags, attrs):
            """Return unknown principal error when opening a file"""

            raise SFTPUnknownPrincipal('Unknown principal',
                unknown_names=(attrs.owner, attrs.group or b'\xff'))

        try:
            with patch('asyncssh.sftp.SFTPServer.open56', _open56_error):
                with self.assertRaises(SFTPUnknownPrincipal):
                    await sftp.open('file', 'wb', SFTPAttrs(owner='aaa',
                                                            group='bbb'))

                with self.assertRaises(SFTPBadMessage):
                    await sftp.open('file', 'wb', SFTPAttrs(owner=b'aaa',
                                                            group=''))
        finally:
            remove('file')

    @sftp_test_v5
    async def test_lock_conflict_v5(self, sftp):
        """Test lock conflict error in SFTPv5"""

        def _open56_error(self, path, desired_access, flags, attrs):
            """Return lock conflict error when opening a file"""

            raise SFTPLockConflict('Lock conflict')

        try:
            with patch('asyncssh.sftp.SFTPServer.open56', _open56_error):
                with self.assertRaises(SFTPLockConflict):
                    await sftp.open56('file', ACE4_WRITE_DATA, FXF_WRITE |
                                      FXF_CREATE_TRUNCATE)
        finally:
            remove('file')

    @sftp_test_v6
    async def test_cannot_delete_v6(self, sftp):
        """Test cannot delete error in SFTPv6"""

        def _remove_error(self, path):
            """Return cannot delete error when removing a file"""

            raise SFTPCannotDelete('Cannot delete file')

        with patch('asyncssh.sftp.SFTPServer.remove', _remove_error):
            with self.assertRaises(SFTPCannotDelete):
                await sftp.remove('file')

    @sftp_test_v6
    async def test_byte_range_lock_conflict_v6(self, sftp):
        """Test byte range lock conflict error in SFTPv6"""

        def _lock_error(self, file_obj, offset, length, flags):
            """Return byte range lock conflict error"""

            raise SFTPByteRangeLockConflict('Byte range lock conflict')

        f = None

        try:
            with patch('asyncssh.sftp.SFTPServer.lock', _lock_error):
                with self.assertRaises(SFTPByteRangeLockConflict):
                    async with sftp.open('file', 'wb') as f:
                        await f.lock(0, 0, FXF_BLOCK_READ)
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test_v6
    async def test_byte_range_lock_refused_v6(self, sftp):
        """Test byte range lock refused error in SFTPv6"""

        def _lock_error(self, file_obj, offset, length, flags):
            """Return byte range lock refused error"""

            raise SFTPByteRangeLockRefused('Byte range lock refused')

        f = None

        try:
            with patch('asyncssh.sftp.SFTPServer.lock', _lock_error):
                with self.assertRaises(SFTPByteRangeLockRefused):
                    async with sftp.open('file', 'wb') as f:
                        await f.lock(0, 0, FXF_BLOCK_READ)
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test_v6
    async def test_delete_pending_v6(self, sftp):
        """Test delete pending error in SFTPv6"""

        def _remove_error(self, path):
            """Return delete pending error when removing a file"""

            raise SFTPDeletePending('Delete of file is pending')

        with patch('asyncssh.sftp.SFTPServer.remove', _remove_error):
            with self.assertRaises(SFTPDeletePending):
                await sftp.remove('file')

    @sftp_test_v6
    async def test_file_corrupt_v6(self, sftp):
        """Test file corrupt error in SFTPv6"""

        def _open56_error(self, path, desired_access, flags, attrs):
            """Return file corrupt  error when opening a file"""

            raise SFTPFileCorrupt('Filesystem is corrupt')

        with patch('asyncssh.sftp.SFTPServer.open56', _open56_error):
            with self.assertRaises(SFTPFileCorrupt):
                await sftp.open('file')

    @sftp_test_v6
    async def test_byte_range_unlock_mismatch_v6(self, sftp):
        """Test byte range unlock mismatch error in SFTPv6"""

        def _unlock_error(self, file_obj, offset, length):
            """Return byte range unlock mismatch error"""

            raise SFTPNoMatchingByteRangeLock('Byte range unlock mismatch')

        f = None

        try:
            with patch('asyncssh.sftp.SFTPServer.unlock', _unlock_error):
                with self.assertRaises(SFTPNoMatchingByteRangeLock):
                    async with sftp.open('file', 'wb') as f:
                        await f.unlock(0, 0)
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')

    @sftp_test
    async def test_log_formatting(self, sftp):
        """Exercise log formatting of SFTP objects"""

        asyncssh.set_sftp_log_level('DEBUG')

        with self.assertLogs(level='DEBUG'):
            await sftp.realpath('.')
            await sftp.stat('.')

            if sys.platform != 'win32': # pragma: no cover
                await sftp.statvfs('.')

        asyncssh.set_sftp_log_level('WARNING')

    @sftp_test
    async def test_makedirs_no_parent_perms(self, sftp):
        """Test creating a directory path without perms for a parent dir"""

        orig_mkdir = sftp.mkdir

        def _mkdir(path, *args, **kwargs):
            if path == b'/':
                raise SFTPPermissionDenied('')
            return orig_mkdir(path, *args, **kwargs)

        try:
            root = os.path.abspath(os.getcwd())
            with patch.object(sftp, 'mkdir', _mkdir):
                await sftp.makedirs(os.path.join(root, 'dir/dir1'))
                self.assertTrue(os.path.isdir(os.path.join(root, 'dir/dir1')))
        finally:
            remove('dir')

    @sftp_test
    async def test_makedirs_no_perms(self, sftp):
        """Test creating a directory path without perms for all parents"""

        root = os.path.abspath(os.getcwd())

        with patch.object(sftp, 'mkdir', side_effect=SFTPPermissionDenied('')):
            with self.assertRaises(SFTPPermissionDenied):
                await sftp.makedirs(os.path.join(root, 'dir/dir1'))


class _TestSFTPCallable(_CheckSFTP):
    """Unit tests for AsyncSSH SFTP factory being a callable"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server using a callable"""

        def sftp_factory(chan):
            """Return an SFTP server"""

            return SFTPServer(chan)

        return await cls.create_server(sftp_factory=sftp_factory)

    @sftp_test
    async def test_stat(self, sftp):
        """Test getting attributes on a file"""

        # pylint: disable=no-self-use

        await sftp.stat('.')


class _TestSFTPCoroutine(_CheckSFTP):
    """Unit tests for AsyncSSH SFTP factory being a coroutine"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server using a coroutine"""

        async def sftp_factory(chan):
            """Return an SFTP server"""

            return SFTPServer(chan)

        return await cls.create_server(sftp_factory=sftp_factory)

    @sftp_test
    async def test_stat(self, sftp):
        """Test getting attributes on a file"""

        # pylint: disable=no-self-use

        await sftp.stat('.')


class _TestSFTPServerProperties(_CheckSFTP):
    """Unit test for checking SFTP server properties"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server which checks channel properties"""

        return await cls.create_server(sftp_factory=_CheckPropSFTPServer)

    @asynctest
    async def test_properties(self):
        """Test SFTP server channel properties"""

        async with self.connect() as conn:
            async with conn.start_sftp_client(env={'A': 1, 'B': 2}) as sftp:
                files = await sftp.listdir()
                self.assertEqual(sorted(files), ['A', 'B'])


class _TestSFTPChroot(_CheckSFTP):
    """Unit test for SFTP server with changed root"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server with a changed root"""

        return await cls.create_server(sftp_factory=_ChrootSFTPServer,
                                       sftp_version=6)

    @sftp_test
    async def test_chroot_copy(self, sftp):
        """Test copying a file to an FTP server with a changed root"""

        try:
            self._create_file('src')
            await sftp.put('src', 'dst')
            self._check_file('src', 'chroot/dst')
        finally:
            remove('src chroot/dst')

    @sftp_test
    async def test_chroot_glob(self, sftp):
        """Test a glob pattern match over SFTP with a changed root"""

        try:
            self._create_file('chroot/file1')
            self._create_file('chroot/file2')
            self.assertEqual(sorted(await sftp.glob('/file*')),
                             ['/file1', '/file2'])
        finally:
            remove('chroot/file1 chroot/file2')

    @sftp_test
    async def test_chroot_realpath(self, sftp):
        """Test canonicalizing a path on an SFTP server with a changed root"""

        self.assertEqual((await sftp.realpath('/dir/../file')), '/file')

        self._create_file('chroot/file1')

        name = await sftp.realpath('/dir/..', 'file1',
                                   check=FXRP_STAT_IF_EXISTS)

        self.assertEqual(name.attrs.type, FILEXFER_TYPE_REGULAR)

        name = await sftp.realpath('/dir/..', 'file2', FXRP_STAT_IF_EXISTS)

        self.assertEqual(name.attrs.type, FILEXFER_TYPE_UNKNOWN)

        with self.assertRaises(SFTPNoSuchFile):
            await sftp.realpath('/dir', '..', 'file2', check=FXRP_STAT_ALWAYS)

    @sftp_test_v6
    async def test_chroot_realpath_v6(self, sftp):
        """Test canonicalizing a path on an SFTP server with a changed root"""

        self.assertEqual((await sftp.realpath('/dir/../file')), '/file')

        self._create_file('chroot/file1')

        name = await sftp.realpath('/dir/..', 'file1', FXRP_STAT_IF_EXISTS)

        self.assertEqual(name.attrs.type, FILEXFER_TYPE_REGULAR)

        name = await sftp.realpath('/dir/..', 'file2',
                                   check=FXRP_STAT_IF_EXISTS)

        self.assertEqual(name.attrs.type, FILEXFER_TYPE_UNKNOWN)

        with self.assertRaises(SFTPNoSuchFile):
            await sftp.realpath('/dir', '..', 'file2', check=FXRP_STAT_ALWAYS)

        with self.assertRaises(SFTPInvalidParameter):
            await sftp.realpath('.', check=99)

    @sftp_test
    async def test_getcwd_and_chdir(self, sftp):
        """Test changing directory on an SFTP server with a changed root"""

        try:
            os.mkdir('chroot/dir')

            self.assertEqual((await sftp.getcwd()), '/')

            await sftp.chdir('dir')
            self.assertEqual((await sftp.getcwd()), '/dir')
        finally:
            remove('chroot/dir')

    @sftp_test
    async def test_chroot_readlink(self, sftp):
        """Test reading symlinks on an FTP server with a changed root"""

        if not self._symlink_supported: # pragma: no cover
            raise unittest.SkipTest('symlink not available')

        try:
            root = os.path.join(os.getcwd(), 'chroot')

            os.symlink(root, 'chroot/link1')
            os.symlink(os.path.join(root, 'file'), 'chroot/link2')
            os.symlink('/xxx', 'chroot/link3')

            self.assertEqual((await sftp.readlink('link1')), '/')
            self.assertEqual((await sftp.readlink('link2')), '/file')
            with self.assertRaises(SFTPNoSuchFile):
                await sftp.readlink('link3')
        finally:
            remove('chroot/link1 chroot/link2 chroot/link3')

    @sftp_test
    async def test_chroot_symlink(self, sftp):
        """Test setting a symlink on an SFTP server with a changed root"""

        if not self._symlink_supported: # pragma: no cover
            raise unittest.SkipTest('symlink not available')

        try:
            await sftp.symlink('/file', 'link1')
            await sftp.symlink('../../file', 'link2')

            self._check_link('chroot/link1', os.path.abspath('chroot/file'))
            self._check_link('chroot/link2', 'file')
        finally:
            remove('chroot/link1 chroot/link2')

    @sftp_test
    async def test_chroot_makedirs(self, sftp):
        """Test creating a directory path"""

        try:
            await sftp.makedirs('dir/dir1')
            self.assertTrue(os.path.isdir('chroot/dir'))
            self.assertTrue(os.path.isdir('chroot/dir/dir1'))

            await sftp.makedirs('dir/dir2')
            self.assertTrue(os.path.isdir('chroot/dir/dir2'))

            await sftp.makedirs('dir/dir2', exist_ok=True)
            self.assertTrue(os.path.isdir('chroot/dir/dir2'))

            with self.assertRaises(SFTPFailure):
                await sftp.makedirs('/dir/dir2')

            self._create_file('chroot/file')
            with self.assertRaises(SFTPFailure):
                await sftp.makedirs('file/dir')
        finally:
            remove('chroot/dir')

    @sftp_test_v6
    async def test_chroot_makedirs_v6(self, sftp):
        """Test creating a directory path with SFTPv6"""

        try:
            await sftp.makedirs('dir/dir1')
            self.assertTrue(os.path.isdir('chroot/dir'))
            self.assertTrue(os.path.isdir('chroot/dir/dir1'))

            await sftp.makedirs('dir/dir2')
            self.assertTrue(os.path.isdir('chroot/dir/dir2'))

            await sftp.makedirs('dir/dir2', exist_ok=True)
            self.assertTrue(os.path.isdir('chroot/dir/dir2'))

            with self.assertRaises(SFTPFileAlreadyExists):
                await sftp.makedirs('/dir/dir2')

            self._create_file('chroot/file')
            with self.assertRaises(SFTPNotADirectory):
                await sftp.makedirs('file/dir')
        finally:
            remove('chroot/dir')


class _TestSFTPReadEOFWithAttrs(_CheckSFTP):
    """Unit test for SFTP server read EOF flags with SFTPAttrs from fstat"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server which returns SFTPAttrs on fstat"""

        return await cls.create_server(sftp_factory=_SFTPAttrsSFTPServer,
                                       sftp_version=6)

    @sftp_test_v6
    async def test_get(self, sftp):
        """Test copying a file over SFTP"""

        try:
            self._create_file('src')
            await sftp.get('src', 'dst')
            self._check_file('src', 'dst')
        finally:
            remove('src dst')


class _TestSFTPUnknownError(_CheckSFTP):
    """Unit test for SFTP server returning unknown error"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server which returns unknown error"""

        return await cls.create_server(sftp_factory=_SFTPAttrsSFTPServer)

    @sftp_test
    async def test_stat_error(self, sftp):
        """Test error when getting attributes of a file on an SFTP server"""

        with self.assertRaises(SFTPError) as exc:
            await sftp.stat('file')

        self.assertEqual(exc.exception.code, 99)


class _TestSFTPOpenError(_CheckSFTP):
    """Unit test for SFTP server returning error on file open"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server which returns file I/O errors"""

        return await cls.create_server(sftp_factory=_OpenErrorSFTPServer,
                                       sftp_version=6)

    @sftp_test_v6
    async def test_open_error_v6(self, sftp):
        """Test error when opening a file on an SFTP server"""

        with self.assertRaises(SFTPInvalidFilename):
            await sftp.open('ENAMETOOLONG')

        with self.assertRaises(SFTPInvalidParameter):
            await sftp.open('EINVAL')

        with self.assertRaises(SFTPFailure):
            await sftp.open('ENXIO')


class _TestSFTPIOError(_CheckSFTP):
    """Unit test for SFTP server returning file I/O error"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server which returns file I/O errors"""

        return await cls.create_server(sftp_factory=_IOErrorSFTPServer)

    def test_copy_error(self):
        """Test error when copying a file on an SFTP server"""

        @sftp_test
        async def _test_copy_error(self, sftp):
            """Test error when copying a file on an SFTP server"""

            try:
                self._create_file('src', 8*1024*1024*'\0')

                with self.assertRaises(SFTPFailure):
                    await sftp.copy('src', 'dst')
            finally:
                remove('src dst')

        with patch('asyncssh.sftp.SFTPServerHandler._extensions', []):
            # pylint: disable=no-value-for-parameter
            _test_copy_error(self)

    @sftp_test
    async def test_read_error(self, sftp):
        """Test error when reading a file on an SFTP server"""

        try:
            self._create_file('file', 8*1024*1024*'\0')

            async with sftp.open('file') as f:
                with self.assertRaises(SFTPFailure):
                    await f.read(8*1024*1024)

                with self.assertRaises(SFTPFailure):
                    async for _ in  await f.read_parallel(8*1024*1024):
                        pass
        finally:
            remove('file')

    @sftp_test
    async def test_write_error(self, sftp):
        """Test error when writing a file on an SFTP server"""

        try:
            with self.assertRaises(SFTPFailure):
                async with sftp.open('file', 'w') as f:
                    await f.write(8*1024*1024*'\0')
        finally:
            remove('file')


class _TestSFTPSmallBlockSize(_CheckSFTP):
    """Unit test for SFTP server returning file I/O error"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server which returns file I/O errors"""

        return (await cls.create_server(
            sftp_factory=_SmallBlockSizeSFTPServer))

    @sftp_test
    async def test_read(self, sftp):
        """Test a large read on a server with a small block size"""

        try:
            data = os.urandom(65536)
            self._create_file('file', data)

            async with sftp.open('file', 'rb', block_size=16384) as f:
                result = await f.read(65536, 16384)

            self.assertEqual(result, data[16384:])
        finally:
            remove('file')

    @sftp_test
    async def test_get(self, sftp):
        """Test getting a file from an SFTP server with a small block size"""

        try:
            data = os.urandom(8*1024*1024)
            self._create_file('src', data)
            await sftp.get('src', 'dst')
            self._check_file('src', 'dst')
        finally:
            remove('src dst')


class _TestSFTPEOFDuringCopy(_CheckSFTP):
    """Unit test for SFTP server returning EOF during a file copy"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server which truncates files when accessed"""

        return await cls.create_server(sftp_factory=_TruncateSFTPServer)

    @sftp_test
    async def test_get(self, sftp):
        """Test getting a file from an SFTP server truncated during the copy"""

        try:
            self._create_file('src', 8*1024*1024*'\0')

            with self.assertRaises(SFTPFailure):
                await sftp.get('src', 'dst', sparse=False)
        finally:
            remove('src dst')


class _TestSFTPNotImplemented(_CheckSFTP):
    """Unit test for SFTP server returning not-implemented error"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server which returns not-implemented errors"""

        return await cls.create_server(sftp_factory=_NotImplSFTPServer)

    @sftp_test
    async def test_symlink_error(self, sftp):
        """Test error when creating a symbolic link on an SFTP server"""

        with self.assertRaises(SFTPOpUnsupported):
            await sftp.symlink('file', 'link')


class _TestSFTPFileType(_CheckSFTP):
    """Unit test for SFTP server formatting directory listings"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server which returns a fixed directory listing"""

        return await cls.create_server(sftp_factory=_FileTypeSFTPServer)

    @sftp_test
    async def test_filetype(self, sftp):
        """Test permission to filetype conversion in SFTP readdir call"""

        for file in await sftp.readdir('/'):
            self.assertEqual(file.filename, str(file.attrs.type))


class _TestSFTPLongname(_CheckSFTP):
    """Unit test for SFTP server formatting directory listings"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server which returns a fixed directory listing"""

        return await cls.create_server(sftp_factory=_LongnameSFTPServer)

    @sftp_test
    async def test_longname(self, sftp):
        """Test long name formatting in SFTP readdir call"""

        for file in await sftp.readdir('/'):
            self.assertEqual(file.longname[56:], file.filename)

    @sftp_test
    async def test_glob_hidden(self, sftp):
        """Test a glob pattern match on hidden files"""

        self.assertEqual((await sftp.glob('/.*')), ['/.file'])

    @unittest.skipIf(sys.platform == 'win32', 'skip uid/gid tests on Windows')
    @sftp_test
    async def test_getpwuid_error(self, sftp):
        """Test long name formatting where user name can't be resolved"""

        with patch('pwd.getpwuid', _getpwuid_error):
            result = await sftp.readdir('/')

        self.assertEqual(result[3].longname[16:24], '        ')
        self.assertEqual(result[4].longname[16:24], '0       ')

    @unittest.skipIf(sys.platform == 'win32', 'skip uid/gid tests on Windows')
    @sftp_test
    async def test_getgrgid_error(self, sftp):
        """Test long name formatting where group name can't be resolved"""

        with patch('grp.getgrgid', _getgrgid_error):
            result = await sftp.readdir('/')

        self.assertEqual(result[3].longname[25:33], '        ')
        self.assertEqual(result[4].longname[25:33], '0       ')

    @sftp_test
    async def test_strftime_error(self, sftp):
        """Test long name formatting with strftime not supporting %e"""

        orig_strftime = time.strftime

        def strftime_error(fmt, t):
            """Simulate Windows srtftime that doesn't support %e"""

            if '%e' in fmt:
                raise ValueError
            else:
                return orig_strftime(fmt, t)

        with patch('time.strftime', strftime_error):
            result = await sftp.readdir('/')

        self.assertEqual(result[3].longname[51:55], '    ')
        self.assertIn(result[4].longname[51:55], ('1969', '1970'))


class _TestSFTPLargeListDir(_CheckSFTP):
    """Unit test for SFTP server returning large listdir result"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server which returns file I/O errors"""

        return await cls.create_server(sftp_factory=_LargeDirSFTPServer)

    @sftp_test
    async def test_large_listdir(self, sftp):
        """Test large listdir result"""

        self.assertEqual(len(await sftp.readdir('/')), 100000)


@unittest.skipIf(sys.platform == 'win32', 'skip statvfs tests on Windows')
class _TestSFTPStatVFS(_CheckSFTP):
    """Unit test for SFTP server filesystem attributes"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server which returns fixed filesystem attrs"""

        return await cls.create_server(sftp_factory=_StatVFSSFTPServer)

    def _check_statvfs(self, sftp_statvfs):
        """Check if filesystem attributes are equal"""

        expected_statvfs = _StatVFSSFTPServer.expected_statvfs

        self.assertEqual(sftp_statvfs.bsize, expected_statvfs.bsize)
        self.assertEqual(sftp_statvfs.frsize, expected_statvfs.frsize)
        self.assertEqual(sftp_statvfs.blocks, expected_statvfs.blocks)
        self.assertEqual(sftp_statvfs.bfree, expected_statvfs.bfree)
        self.assertEqual(sftp_statvfs.bavail, expected_statvfs.bavail)
        self.assertEqual(sftp_statvfs.files, expected_statvfs.files)
        self.assertEqual(sftp_statvfs.ffree, expected_statvfs.ffree)
        self.assertEqual(sftp_statvfs.favail, expected_statvfs.favail)
        self.assertEqual(sftp_statvfs.fsid, expected_statvfs.fsid)
        self.assertEqual(sftp_statvfs.flags, expected_statvfs.flags)
        self.assertEqual(sftp_statvfs.namemax, expected_statvfs.namemax)

        self.assertEqual(repr(sftp_statvfs), repr(expected_statvfs))

    @sftp_test
    async def test_statvfs(self, sftp):
        """Test getting attributes on a filesystem"""

        self._check_statvfs(await sftp.statvfs('.'))

    @sftp_test
    async def test_file_statvfs(self, sftp):
        """Test getting attributes on the filesystem containing an open file"""

        f = None

        try:
            self._create_file('file')

            f = await sftp.open('file')
            self._check_statvfs(await f.statvfs())
        finally:
            if f: # pragma: no branch
                await f.close()

            remove('file')


@unittest.skipIf(sys.platform == 'win32', 'skip chown tests on Windows')
class _TestSFTPChown(_CheckSFTP):
    """Unit test for SFTP server file ownership"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server which simulates file ownership changes"""

        return await cls.create_server(sftp_factory=_ChownSFTPServer,
                                       sftp_version=6)

    @sftp_test
    async def test_chown(self, sftp):
        """Test changing ownership of a file"""

        try:
            self._create_file('file')
            await sftp.chown('file', 1, 2)
            attrs = await sftp.stat('file')
            self.assertEqual(attrs.uid, 1)
            self.assertEqual(attrs.gid, 2)
        finally:
            remove('file')

    @sftp_test_v4
    async def test_chown_v4(self, sftp):
        """Test changing ownership of a file with SFTPv4"""

        try:
            self._create_file('file')
            await sftp.chown('file', owner='root', group='wheel')
            attrs = await sftp.stat('file')
            self.assertEqual(attrs.owner, 'root')
            self.assertEqual(attrs.group, 'wheel')
        finally:
            remove('file')


class _TestSFTPAttrs(unittest.TestCase):
    """Unit test for SFTPAttrs object"""

    def test_attrs(self):
        """Test encoding and decoding of SFTP attributes"""

        for kwargs in ({'size': 1234},
                       {'uid': 1, 'gid': 2},
                       {'permissions': 0o7777},
                       {'atime': 1, 'mtime': 2},
                       {'extended': [(b'a1', b'v1'), (b'a2', b'v2')]}):
            attrs = SFTPAttrs(**kwargs)
            packet = SSHPacket(attrs.encode(3))
            self.assertEqual(repr(SFTPAttrs.decode(packet, 3)), repr(attrs))

        for kwargs in ({'type': FILEXFER_TYPE_REGULAR},
                       {'size': 1234},
                       {'owner': 'a', 'group': 'b'},
                       {'permissions': 0o7777},
                       {'atime': 1, 'atime_ns': 2},
                       {'crtime': 3, 'crtime_ns': 4},
                       {'mtime': 5, 'mtime_ns': 6},
                       {'atime': 7, 'crtime': 8, 'mtime': 9},
                       {'acl': b''}):
            attrs = SFTPAttrs(**kwargs)
            packet = SSHPacket(attrs.encode(4))
            self.assertEqual(repr(SFTPAttrs.decode(packet, 4)), repr(attrs))

            packet = SSHPacket(SFTPAttrs(uid=1, gid=2).encode(4))
            self.assertEqual(repr(SFTPAttrs.decode(packet, 4)),
                             repr(SFTPAttrs(owner='1', group='2')))

        for kwargs in ({'type': FILEXFER_TYPE_REGULAR},
                       {'size': 1234},
                       {'owner': 'a', 'group': 'b'},
                       {'permissions': 0o7777},
                       {'atime': 1, 'atime_ns': 2},
                       {'crtime': 3, 'crtime_ns': 4},
                       {'mtime': 5, 'mtime_ns': 6},
                       {'atime': 7, 'crtime': 8, 'mtime': 9},
                       {'acl': b''},
                       {'attrib_bits': FILEXFER_ATTR_BITS_READONLY,
                        'attrib_valid': FILEXFER_ATTR_BITS_READONLY}):
            attrs = SFTPAttrs(**kwargs)
            packet = SSHPacket(attrs.encode(5))
            self.assertEqual(repr(SFTPAttrs.decode(packet, 5)), repr(attrs))

        for kwargs in ({'type': FILEXFER_TYPE_REGULAR},
                       {'size': 1234, 'alloc_size': 5678},
                       {'owner': 'a', 'group': 'b'},
                       {'permissions': 0o7777},
                       {'atime': 1, 'atime_ns': 2},
                       {'crtime': 3, 'crtime_ns': 4},
                       {'mtime': 5, 'mtime_ns': 6},
                       {'ctime': 7, 'ctime_ns': 8},
                       {'atime': 7, 'crtime': 8, 'mtime': 9, 'ctime': 10},
                       {'acl': b''},
                       {'attrib_bits': FILEXFER_ATTR_BITS_READONLY,
                        'attrib_valid': FILEXFER_ATTR_BITS_READONLY},
                       {'text_hint': FILEXFER_ATTR_KNOWN_TEXT},
                       {'mime_type': 'application/octet-stream'},
                       {'untrans_name': b'\xff'},
                       {'extended': [(b'a1', b'v1'), (b'a2', b'v2')]}):
            attrs = SFTPAttrs(**kwargs)
            packet = SSHPacket(attrs.encode(6))
            self.assertEqual(repr(SFTPAttrs.decode(packet, 6)), repr(attrs))

    def test_illegal_attrs(self):
        """Test decoding illegal SFTP attributes value"""

        with self.assertRaises(SFTPBadMessage):
            SFTPAttrs.decode(SSHPacket(UInt32(FILEXFER_ATTR_OWNERGROUP)), 3)

        for version in range(4, 7):
            with self.assertRaises(SFTPBadMessage):
                SFTPAttrs.decode(SSHPacket(
                    UInt32(FILEXFER_ATTR_UIDGID)), version)

        with self.assertRaises(SFTPOwnerInvalid):
            SFTPAttrs.decode(SSHPacket(
                SFTPAttrs(owner=b'\xff', group='').encode(6)), 6)

        with self.assertRaises(SFTPGroupInvalid):
            SFTPAttrs.decode(SSHPacket(
                SFTPAttrs(owner='', group=b'\xff').encode(6)), 6)

        with self.assertRaises(SFTPBadMessage):
            SFTPAttrs.decode(SSHPacket(
                SFTPAttrs(mime_type=b'\xff').encode(6)), 6)


class _TestSFTPNonstandardSymlink(_CheckSFTP):
    """Unit tests for SFTP server with non-standard symlink order"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server for the tests to use"""

        return await cls.create_server(server_version='OpenSSH',
                                       sftp_factory=_SymlinkSFTPServer)

    @asynctest
    async def test_nonstandard_symlink_client(self):
        """Test creating a symlink with opposite argument order"""

        if not self._symlink_supported: # pragma: no cover
            raise unittest.SkipTest('symlink not available')

        try:
            async with self.connect(client_version='OpenSSH') as conn:
                async with conn.start_sftp_client() as sftp:
                    await sftp.symlink('link', 'file')
                    self._check_link('link', 'file')
        finally:
            remove('file link')


class _TestSFTPAsync(_TestSFTP):
    """Unit test for an async SFTPServer"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server with async callbacks"""

        return await cls.create_server(sftp_factory=_AsyncSFTPServer,
                                       sftp_version=6)

    @sftp_test
    async def test_async_realpath(self, sftp):
        """Test canonicalizing a path on an async SFTP server"""

        self.assertEqual((await sftp.realpath('dir/../file')),
                         posixpath.join((await sftp.getcwd()), 'file'))

    @sftp_test_v6
    async def test_async_realpath_v6(self, sftp):
        """Test canonicalizing a path on an async SFTPv6 server"""

        self._create_file('file1')

        self.assertEqual((await sftp.realpath('dir/../file')),
                         posixpath.join((await sftp.getcwd()), 'file'))

        name = await sftp.realpath('dir/../file1', check=FXRP_STAT_ALWAYS)
        self.assertEqual(name.attrs.type, FILEXFER_TYPE_REGULAR)


class _CheckSCP(_CheckSFTP):
    """Utility functions for AsyncSSH SCP unit tests"""

    @classmethod
    async def asyncSetUpClass(cls):
        """Set up SCP target host/port tuple"""

        await super().asyncSetUpClass()

        cls._scp_server = (cls._server_addr, cls._server_port)

    @classmethod
    async def start_server(cls):
        """Start an SFTP server with SCP enabled for the tests to use"""

        return await cls.create_server(sftp_factory=True, allow_scp=True)

    async def _check_scp(self, src, dst, data=(), **kwargs):
        """Check copying a file over SCP"""

        try:
            self._create_file('src', data)
            await scp(src, dst, **kwargs)
            self._check_file('src', 'dst')
        finally:
            remove('src dst')

    async def _check_progress(self, src, dst):
        """Check copying a file over SCP with progress reporting"""

        def _report_progress(_srcpath, _dstpath, bytes_copied, _total_bytes):
            """Monitor progress of copy"""

            reports.append(bytes_copied)

        for size in (0, 100000):
            with self.subTest(size=size):
                reports = []

                await self._check_scp(src, dst, size * 'a', block_size=8192,
                                      progress_handler=_report_progress)

                self.assertEqual(len(reports), (size // 8192) + 1)
                self.assertEqual(reports[-1], size)

    async def _check_cancel(self, src, dst):
        """Check cancelling a file transfer over SCP"""

        def _cancel(_srcpath, _dstpath, _bytes_copied, _total_bytes):
            """Cancel transfer"""

            task.cancel()

        try:
            self._create_file('src', 1024*8192 * 'a')

            coro = scp(src, dst, block_size=8192, progress_handler=_cancel)

            task = asyncio.create_task(coro)
            await task
        finally:
            remove('src dst')


class _TestSCP(_CheckSCP):
    """Unit tests for AsyncSSH SCP client and server"""

    @asynctest
    async def test_get(self):
        """Test getting a file over SCP"""

        for src in ('src', b'src', Path('src')):
            for dst in ('dst', b'dst', Path('dst')):
                with self.subTest(src=type(src), dst=type(dst)):
                    await self._check_scp((self._scp_server, src), dst)

    @asynctest
    async def test_get_progress(self):
        """Test getting a file over SCP with progress reporting"""

        await self._check_progress((self._scp_server, 'src'), 'dst')

    @asynctest
    async def test_get_cancel(self):
        """Test cancelling a get of a file over SCP"""

        await self._check_cancel((self._scp_server, 'src'), 'dst')

    @asynctest
    async def test_get_preserve(self):
        """Test getting a file with preserved attributes over SCP"""

        try:
            self._create_file('src', utime=(1, 2))
            await scp((self._scp_server, 'src'), 'dst', preserve=True)
            self._check_file('src', 'dst', preserve=True, check_atime=False)
        finally:
            remove('src dst')

    @asynctest
    async def test_get_recurse(self):
        """Test recursively getting a directory over SCP"""

        try:
            os.mkdir('src')
            self._create_file('src/file1')

            await scp((self._scp_server, 'src'), 'dst', recurse=True)

            self._check_file('src/file1', 'dst/file1')
        finally:
            remove('src dst')

    @asynctest
    async def test_get_error_handler(self):
        """Test getting multiple files over SCP with error handler"""

        def err_handler(exc):
            """Catch error for non-recursive copy of directory"""

            self.assertEqual(exc.reason, 'scp: Not a regular file: src2')

        try:
            self._create_file('src1')
            os.mkdir('src2')
            os.mkdir('dst')

            await scp((self._scp_server, 'src*'), 'dst',
                      error_handler=err_handler)

            self._check_file('src1', 'dst/src1')
        finally:
            remove('src1 src2 dst')

    @asynctest
    async def test_get_recurse_existing(self):
        """Test getting a directory over SCP where target dir exists"""

        try:
            os.mkdir('src')
            os.mkdir('dst')
            os.mkdir('dst/src')
            self._create_file('src/file1')

            await scp((self._scp_server, 'src'), 'dst', recurse=True)

            self._check_file('src/file1', 'dst/src/file1')
        finally:
            remove('src dst')

    @unittest.skipIf(sys.platform == 'win32',
                     'skip permission tests on Windows')
    @asynctest
    async def test_get_not_permitted(self):
        """Test getting a file with no read permissions over SCP"""

        try:
            self._create_file('src', mode=0)

            with self.assertRaises(SFTPFailure):
                await scp((self._scp_server, 'src'), 'dst')
        finally:
            remove('src dst')

    @asynctest
    async def test_get_directory_as_file(self):
        """Test getting a file which is actually a directory over SCP"""

        try:
            os.mkdir('src')

            with self.assertRaises(SFTPFailure):
                await scp((self._scp_server, 'src'), 'dst')
        finally:
            remove('src dst')

    @asynctest
    async def test_get_non_directory_in_path(self):
        """Test getting a file with a non-directory in path over SCP"""

        try:
            self._create_file('src')

            with self.assertRaises(SFTPFailure):
                await scp((self._scp_server, 'src/xxx'), 'dst')
        finally:
            remove('src dst')

    @asynctest
    async def test_get_recurse_not_directory(self):
        """Test getting a directory over SCP where target is not directory"""

        try:
            os.mkdir('src')
            self._create_file('dst')
            self._create_file('src/file1')

            with self.assertRaises(SFTPFailure):
                await scp((self._scp_server, 'src'), 'dst', recurse=True)
        finally:
            remove('src dst')

    @asynctest
    async def test_put(self):
        """Test putting a file over SCP"""

        for src in ('src', b'src', Path('src')):
            for dst in ('dst', b'dst', Path('dst')):
                with self.subTest(src=type(src), dst=type(dst)):
                    await self._check_scp(src, (self._scp_server, dst))

    @asynctest
    async def test_put_progress(self):
        """Test putting a file over SCP with progress reporting"""

        await self._check_progress('src', (self._scp_server, 'dst'))

    @asynctest
    async def test_put_cancel(self):
        """Test cancelling a put of a file over SCP"""

        await self._check_cancel('src', (self._scp_server, 'dst'))

    @asynctest
    async def test_put_preserve(self):
        """Test putting a file with preserved attributes over SCP"""

        try:
            self._create_file('src', utime=(1, 2))
            await scp('src', (self._scp_server, 'dst'), preserve=True)
            self._check_file('src', 'dst', preserve=True, check_atime=False)
        finally:
            remove('src dst')

    @asynctest
    async def test_put_recurse(self):
        """Test recursively putting a directory over SCP"""

        try:
            os.mkdir('src')
            self._create_file('src/file1')

            await scp('src', (self._scp_server, 'dst'), recurse=True)

            self._check_file('src/file1', 'dst/file1')
        finally:
            remove('src dst')

    @asynctest
    async def test_put_recurse_existing(self):
        """Test putting a directory over SCP where target dir exists"""

        try:
            os.mkdir('src')
            os.mkdir('dst')
            self._create_file('src/file1')

            await scp('src', (self._scp_server, 'dst'), recurse=True)

            self._check_file('src/file1', 'dst/src/file1')
        finally:
            remove('src dst')

    @asynctest
    async def test_put_must_be_dir(self):
        """Test putting multiple files to a non-directory over SCP"""

        try:
            self._create_file('src1')
            self._create_file('src2')
            self._create_file('dst')

            with self.assertRaises(SFTPFailure):
                await scp(['src1', 'src2'], (self._scp_server, 'dst'))
        finally:
            remove('src1 src2 dst')

    @asynctest
    async def test_put_non_directory_in_path(self):
        """Test putting a file with a non-directory in path over SCP"""

        try:
            self._create_file('src')

            with self.assertRaises(OSError):
                await scp('src/xxx', (self._scp_server, 'dst'))
        finally:
            remove('src')

    @asynctest
    async def test_put_recurse_not_directory(self):
        """Test putting a directory over SCP where target is not directory"""

        try:
            os.mkdir('src')
            self._create_file('dst')
            self._create_file('src/file1')

            with self.assertRaises(SFTPFailure):
                await scp('src', (self._scp_server, 'dst'), recurse=True)
        finally:
            remove('src dst')

    @asynctest
    async def test_put_read_error(self):
        """Test read errors when putting a file over SCP"""

        async def _read_error(self, size, offset):
            """Return an error for reads past 4 MB in a file"""

            if offset >= 4*1024*1024:
                raise OSError(errno.EIO, 'I/O error')
            else:
                return await orig_read(self, size, offset)

        try:
            self._create_file('src', 8*1024*1024*'\0')

            orig_read = LocalFile.read

            with patch('asyncssh.sftp.LocalFile.read', _read_error):
                with self.assertRaises(OSError):
                    await scp('src', (self._scp_server, 'dst'))
        finally:
            remove('src dst')

    @asynctest
    async def test_put_read_early_eof(self):
        """Test getting early EOF when putting a file over SCP"""

        async def _read_early_eof(self, size, offset):
            """Return an early EOF for reads past 4 MB in a file"""

            if offset >= 4*1024*1024:
                return b''
            else:
                return await orig_read(self, size, offset)

        try:
            self._create_file('src', 8*1024*1024*'\0')

            orig_read = LocalFile.read

            with patch('asyncssh.sftp.LocalFile.read', _read_early_eof):
                with self.assertRaises(SFTPFailure):
                    await scp('src', (self._scp_server, 'dst'))
        finally:
            remove('src dst')

    @asynctest
    async def test_put_name_too_long(self):
        """Test putting a file over SCP with too long a name"""

        try:
            self._create_file('src')

            with self.assertRaises(SFTPFailure):
                await scp('src', (self._scp_server, 256*'a'))
        finally:
            remove('src dst')

    @asynctest
    async def test_copy(self):
        """Test copying a file between remote hosts over SCP"""

        for src in ('src', b'src', Path('src')):
            for dst in ('dst', b'dst', Path('dst')):
                with self.subTest(src=type(src), dst=type(dst)):
                    await self._check_scp((self._scp_server, src),
                                          (self._scp_server, dst))

    @asynctest
    async def test_copy_progress(self):
        """Test copying a file over SCP with progress reporting"""

        await self._check_progress((self._scp_server, 'src'),
                                   (self._scp_server, 'dst'))

    @asynctest
    async def test_copy_cancel(self):
        """Test cancelling a copy of a file over SCP"""

        await self._check_cancel((self._scp_server, 'src'),
                                 (self._scp_server, 'dst'))

    @asynctest
    async def test_copy_preserve(self):
        """Test copying a file with preserved attributes between hosts"""

        try:
            self._create_file('src', utime=(1, 2))
            await scp((self._scp_server, 'src'), (self._scp_server, 'dst'),
                      preserve=True)
            self._check_file('src', 'dst', preserve=True, check_atime=False)
        finally:
            remove('src dst')

    @asynctest
    async def test_copy_recurse(self):
        """Test recursively copying a directory between hosts over SCP"""

        try:
            os.mkdir('src')
            self._create_file('src/file1')

            await scp((self._scp_server, 'src'), (self._scp_server, 'dst'),
                      recurse=True)

            self._check_file('src/file1', 'dst/file1')
        finally:
            remove('src dst')

    @asynctest
    async def test_copy_error_handler_source(self):
        """Test copying multiple files over SCP with error handler"""

        def err_handler(exc):
            """Catch error for non-recursive copy of directory"""

            self.assertEqual(exc.reason, 'scp: Not a regular file: src2')

        try:
            self._create_file('src1')
            os.mkdir('src2')
            os.mkdir('dst')

            await scp((self._scp_server, 'src*'), (self._scp_server, 'dst'),
                      error_handler=err_handler)

            self._check_file('src1', 'dst/src1')
        finally:
            remove('src1 src2 dst')

    @asynctest
    async def test_copy_error_handler_sink(self):
        """Test copying multiple files over SCP with error handler"""

        def err_handler(exc):
            """Catch error for non-recursive copy of directory"""

            if sys.platform == 'win32': # pragma: no cover
                self.assertEqual(exc.reason,
                                 'scp: Permission denied: dst\\src2')
            else:
                self.assertEqual(exc.reason, 'scp: Is a directory: dst/src2')

        try:
            self._create_file('src1')
            self._create_file('src2')
            os.mkdir('dst')
            os.mkdir('dst/src2')

            await scp((self._scp_server, 'src*'), (self._scp_server, 'dst'),
                      error_handler=err_handler)

            self._check_file('src1', 'dst/src1')
        finally:
            remove('src1 src2 dst')

    @asynctest
    async def test_copy_recurse_existing(self):
        """Test copying a directory over SCP where target dir exists"""

        try:
            os.mkdir('src')
            os.mkdir('dst')
            self._create_file('src/file1')

            await scp((self._scp_server, 'src'), (self._scp_server, 'dst'),
                      recurse=True)

            self._check_file('src/file1', 'dst/src/file1')
        finally:
            remove('src dst')

    @asynctest
    async def test_local_copy(self):
        """Test for error return when attempting to copy local files"""

        with self.assertRaises(ValueError):
            await scp('src', 'dst')

    @asynctest
    async def test_copy_multiple(self):
        """Test copying multiple files over SCP"""

        try:
            os.mkdir('src')
            self._create_file('src/file1')
            self._create_file('src/file2')
            await scp([(self._scp_server, 'src/file1'),
                       (self._scp_server, 'src/file2')], '.')
            self._check_file('src/file1', 'file1')
            self._check_file('src/file2', 'file2')
        finally:
            remove('src file1 file2')

    @asynctest
    async def test_copy_recurse_not_directory(self):
        """Test copying a directory over SCP where target is not directory"""

        try:
            os.mkdir('src')
            self._create_file('dst')
            self._create_file('src/file1')

            with self.assertRaises(SFTPFailure):
                await scp((self._scp_server, 'src'), (self._scp_server, 'dst'),
                          recurse=True)
        finally:
            remove('src dst')

    @asynctest
    async def test_source_string(self):
        """Test passing a string to SCP"""

        with self.assertRaises(OSError):
            await scp('\xff:xxx', '.')

    @asynctest
    async def test_source_bytes(self):
        """Test passing a byte string to SCP"""

        with self.assertRaises(OSError):
            await scp('\xff:xxx'.encode(), '.')

    @asynctest
    async def test_source_open_connection(self):
        """Test passing an open SSHClientConnection to SCP as source"""

        try:
            async with self.connect() as conn:
                self._create_file('src')
                await scp((conn, 'src'), 'dst')
                self._check_file('src', 'dst')
        finally:
            remove('src dst')

    @asynctest
    async def test_destination_open_connection(self):
        """Test passing an open SSHClientConnection to SCP as destination"""

        try:
            async with self.connect() as conn:
                os.mkdir('src')
                self._create_file('src/file1')
                await scp('src/file1', conn)
                self._check_file('src/file1', 'file1')
        finally:
            remove('src file1')

    @asynctest
    async def test_missing_path(self):
        """Test running SCP with missing path"""

        async with self.connect() as conn:
            result = await conn.run('scp ')
            self.assertEqual(result.stderr, 'scp: the following arguments '
                             'are required: path\n')

    @asynctest
    async def test_missing_direction(self):
        """Test running SCP with missing direction argument"""

        async with self.connect() as conn:
            result = await conn.run('scp xxx')
            self.assertEqual(result.stderr, 'scp: one of the arguments -f -t '
                             'is required\n')

    @asynctest
    async def test_invalid_argument(self):
        """Test running SCP with invalid argument"""

        async with self.connect() as conn:
            result = await conn.run('scp -f -x src')
            self.assertEqual(result.stderr, 'scp: unrecognized arguments: -x\n')

    @asynctest
    async def test_invalid_c_argument(self):
        """Test running SCP with invalid argument to C request"""

        async with self.connect() as conn:
            result = await conn.run('scp -t dst', input='C\n')
            self.assertEqual(result.stdout,
                             '\0\x01scp: Invalid copy or dir request\n')

    @asynctest
    async def test_invalid_t_argument(self):
        """Test running SCP with invalid argument to C request"""

        async with self.connect() as conn:
            result = await conn.run('scp -t -p dst', input='T\n')
            self.assertEqual(result.stdout, '\0\x01scp: Invalid time request\n')


class _TestSCPAsync(_TestSCP):
    """Unit test for AsyncSSH SCP using an async SFTPServer"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server with async callbacks"""

        return await cls.create_server(sftp_factory=_AsyncSFTPServer,
                                       allow_scp=True)


class _TestSCPCoroutine(_TestSCP):
    """Unit test for AsyncSSH SCP with the SFTP factory being a coroutine"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server with async callbacks"""

        async def sftp_factory(chan):
            """Return an SFTP server"""

            return SFTPServer(chan)

        return await cls.create_server(sftp_factory=sftp_factory,
                                       allow_scp=True)


class _TestSCPAttrs(_CheckSCP):
    """Unit test for SCP with SFTP server returning SFTPAttrs"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server which returns SFTPAttrs from stat"""

        return await cls.create_server(sftp_factory=_SFTPAttrsSFTPServer,
                                       allow_scp=True)

    @asynctest
    async def test_get(self):
        """Test getting a file over SCP with stat returning SFTPAttrs"""

        try:
            self._create_file('src')
            await scp((self._scp_server, 'src*'), 'dst')
            self._check_file('src', 'dst')
        finally:
            remove('src dst')

    @asynctest
    async def test_put_recurse_not_directory(self):
        """Test putting a directory over SCP where target is not directory"""

        try:
            os.mkdir('src')
            self._create_file('dst')
            self._create_file('src/file1')

            with self.assertRaises(SFTPFailure):
                await scp('src', (self._scp_server, 'dst'), recurse=True)
        finally:
            remove('src dst')

    @asynctest
    async def test_put_not_permitted(self):
        """Test putting a file over SCP onto an unwritable target"""

        try:
            self._create_file('src')
            os.mkdir('dst')
            os.chmod('dst', 0)

            with self.assertRaises(SFTPFailure):
                await scp('src', (self._scp_server, 'dst/src'))
        finally:
            os.chmod('dst', 0o755)
            remove('src dst')


class _TestSCPIOError(_CheckSCP):
    """Unit test for SCP with SFTP server returning file I/O error"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server which returns file I/O errors"""

        return await cls.create_server(sftp_factory=_IOErrorSFTPServer,
                                       allow_scp=True)

    @asynctest
    async def test_put_error(self):
        """Test error when putting a file over SCP"""

        try:
            self._create_file('src', 8*1024*1024*'\0')

            with self.assertRaises(SFTPFailure):
                await scp('src', (self._scp_server, 'dst'))
        finally:
            remove('src dst')

    @asynctest
    async def test_copy_error(self):
        """Test error when copying a file over SCP"""

        try:
            self._create_file('src', 8*1024*1024*'\0')

            with self.assertRaises(SFTPFailure):
                await scp((self._scp_server, 'src'),
                          (self._scp_server, 'dst'))
        finally:
            remove('src dst')


class _TestSCPErrors(_CheckSCP):
    """Unit test for SCP returning error on startup"""

    @classmethod
    async def start_server(cls):
        """Start an SFTP server which returns file I/O errors"""

        async def _handle_client(process):
            """Handle new client"""

            async with process:
                command = process.command

                if command.endswith('get_connection_lost'):
                    pass
                elif command.endswith('get_dir_no_recurse'):
                    await process.stdin.read(1)
                    process.stdout.write('D0755 0 src\n')
                elif command.endswith('get_early_eof'):
                    await process.stdin.read(1)
                    process.stdout.write('C0644 10 src\n')
                    await process.stdin.read(1)
                elif command.endswith('get_extra_e'):
                    await process.stdin.read(1)
                    process.stdout.write('E\n')
                    await process.stdin.read(1)
                elif command.endswith('get_t_without_preserve'):
                    await process.stdin.read(1)
                    process.stdout.write('T0 0 0 0\n')
                    await process.stdin.read(1)
                elif command.endswith('get_unknown_action'):
                    await process.stdin.read(1)
                    process.stdout.write('X\n')
                    await process.stdin.read(1)
                elif command.endswith('put_connection_lost'):
                    process.stdout.write('\0\0')
                elif command.endswith('put_startup_error'):
                    process.stdout.write('Error starting SCP\n')
                elif command.endswith('recv_early_eof'):
                    process.stdout.write('\0')
                    await process.stdin.readline()
                    try:
                        process.stdout.write('\0')
                    except BrokenPipeError:
                        pass
                else:
                    process.exit(255)

        return await cls.create_server(process_factory=_handle_client)

    @asynctest
    async def test_get_directory_without_recurse(self):
        """Test receiving directory when recurse wasn't requested"""

        try:
            with self.assertRaises((SFTPBadMessage, SFTPConnectionLost)):
                await scp((self._scp_server, 'get_dir_no_recurse'), 'dst')
        finally:
            remove('dst')

    @asynctest
    async def test_get_early_eof(self):
        """Test getting early EOF when getting a file over SCP"""

        try:
            with self.assertRaises(SFTPConnectionLost):
                await scp((self._scp_server, 'get_early_eof'), 'dst')
        finally:
            remove('dst')

    @asynctest
    async def test_get_t_without_preserve(self):
        """Test getting timestamps with requesting preserve"""

        try:
            await scp((self._scp_server, 'get_t_without_preserve'), 'dst')
        finally:
            remove('dst')

    @asynctest
    async def test_get_unknown_action(self):
        """Test getting unknown action from SCP server during get"""

        try:
            with self.assertRaises(SFTPBadMessage):
                await scp((self._scp_server, 'get_unknown_action'), 'dst')
        finally:
            remove('dst')

    @asynctest
    async def test_put_startup_error(self):
        """Test SCP server returning an error on startup"""

        try:
            self._create_file('src')

            with self.assertRaises(SFTPFailure) as exc:
                await scp('src', (self._scp_server, 'put_startup_error'))

            self.assertEqual(exc.exception.reason, 'Error starting SCP')
        finally:
            remove('src')

    @asynctest
    async def test_put_connection_lost(self):
        """Test SCP server abruptly closing connection on put"""

        try:
            self._create_file('src')

            with self.assertRaises(SFTPConnectionLost) as exc:
                await scp('src', (self._scp_server, 'put_connection_lost'))

            self.assertEqual(exc.exception.reason, 'Connection lost')
        finally:
            remove('src')

    @asynctest
    async def test_copy_connection_lost_source(self):
        """Test source abruptly closing connection during SCP copy"""

        with self.assertRaises(SFTPConnectionLost) as exc:
            await scp((self._scp_server, 'get_connection_lost'),
                      (self._scp_server, 'recv_early_eof'))

        self.assertEqual(exc.exception.reason, 'Connection lost')

    @asynctest
    async def test_copy_connection_lost_sink(self):
        """Test sink abruptly closing connection during SCP copy"""

        with self.assertRaises(SFTPConnectionLost) as exc:
            await scp((self._scp_server, 'get_early_eof'),
                      (self._scp_server, 'put_connection_lost'))

        self.assertEqual(exc.exception.reason, 'Connection lost')

    @asynctest
    async def test_copy_early_eof(self):
        """Test getting early EOF when copying a file over SCP"""

        with self.assertRaises(SFTPConnectionLost):
            await scp((self._scp_server, 'get_early_eof'),
                      (self._scp_server, 'recv_early_eof'))

    @asynctest
    async def test_copy_extra_e(self):
        """Test getting extra E when copying a file over SCP"""

        await scp((self._scp_server, 'get_extra_e'),
                  (self._scp_server, 'recv_early_eof'))

    @asynctest
    async def test_copy_unknown_action(self):
        """Test getting unknown action from SCP server during copy"""

        with self.assertRaises(SFTPBadMessage):
            await scp((self._scp_server, 'get_unknown_action'),
                      (self._scp_server, 'recv_early_eof'))

    @asynctest
    async def test_unknown(self):
        """Test unknown SCP server request for code coverage"""

        with self.assertRaises(SFTPConnectionLost):
            await scp('src', (self._scp_server, 'unknown'))