Debian Codegraph @

tests/test_sftp.py

raw
1 # Copyright (C) 2003-2009 Robey Pointer <[email protected]>
2 #
3 # This file is part of paramiko.
4 #
5 # Paramiko is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU Lesser General Public License as published by the Free
7 # Software Foundation; either version 2.1 of the License, or (at your option)
8 # any later version.
9 #
10 # Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
13 # details.
14 #
15 # You should have received a copy of the GNU Lesser General Public License
16 # along with Paramiko; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18
19 """
20 some unit tests to make sure sftp works.
21
22 a real actual sftp server is contacted, and a new folder is created there to
23 do test file operations in (so no existing files will be harmed).
24 """
25
26 import os
27 import socket
28 import sys
29 import warnings
30 from binascii import hexlify
31 from io import StringIO
32 from tempfile import mkstemp
33
34 import pytest
35
36 from paramiko.common import o777, o600, o666, o644
37 from paramiko.sftp_attr import SFTPAttributes
38 from paramiko.util import b, u
39 from tests import requireNonAsciiLocale
40
41 from ._util import needs_builtin
42 from ._util import slow
43
44
45 ARTICLE = """
46 Insulin sensitivity and liver insulin receptor structure in ducks from two
47 genera
48
49 T. Constantine, B. Chevalier, M. Derouet and J. Simon
50 Station de Recherches Avicoles, Institut National de la Recherche Agronomique,
51 Nouzilly, France.
52
53 Insulin sensitivity and liver insulin receptor structure were studied in
54 5-wk-old ducks from two genera (Muscovy and Pekin). In the fasting state, both
55 duck types were equally resistant to exogenous insulin compared with chicken.
56 Despite the low potency of duck insulin, the number of insulin receptors was
57 lower in Muscovy duck and similar in Pekin duck and chicken liver membranes.
58 After 125I-insulin cross-linking, the size of the alpha-subunit of the
59 receptors from the three species was 135,000. Wheat germ agglutinin-purified
60 receptors from the three species were contaminated by an active and unusual
61 adenosinetriphosphatase (ATPase) contaminant (highest activity in Muscovy
62 duck). Sequential purification of solubilized receptor from both duck types on
63 lentil and then wheat germ agglutinin lectins led to a fraction of receptors
64 very poor in ATPase activity that exhibited a beta-subunit size (95,000) and
65 tyrosine kinase activity similar to those of ATPase-free chicken insulin
66 receptors. Therefore the ducks from the two genera exhibit an alpha-beta-
67 structure for liver insulin receptors and a clear difference in the number of
68 liver insulin receptors. Their sensitivity to insulin is, however, similarly
69 decreased compared with chicken.
70 """
71
72
73 # Here is how unicode characters are encoded over 1 to 6 bytes in utf-8
74 # U-00000000 - U-0000007F:
75 # 0xxxxxxx
76 # U-00000080 - U-000007FF:
77 # 110xxxxx 10xxxxxx
78 # U-00000800 - U-0000FFFF:
79 # 1110xxxx 10xxxxxx 10xxxxxx
80 # U-00010000 - U-001FFFFF:
81 # 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
82 # U-00200000 - U-03FFFFFF:
83 # 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
84 # U-04000000 - U-7FFFFFFF:
85 # 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
86 # Note that: hex(int('11000011',2)) == '0xc3'
87 # Thus, the following 2-bytes sequence is not valid utf8: "invalid continuation
88 # byte"
89 NON_UTF8_DATA = b"\xC3\xC3"
90
91 unicode_folder = "\u00fcnic\u00f8de"
92 utf8_folder = b"/\xc3\xbcnic\xc3\xb8\x64\x65"
93
94
95 @slow
96 class TestSFTP:
97 def test_file(self, sftp):
98 """
99 verify that we can create a file.
100 """
101 f = sftp.open(sftp.FOLDER + "/test", "w")
102 try:
103 assert f.stat().st_size == 0
104 finally:
105 f.close()
106 sftp.remove(sftp.FOLDER + "/test")
107
108 def test_close(self, sftp):
109 """
110 Verify that SFTP session close() causes a socket error on next action.
111 """
112 sftp.close()
113 with pytest.raises(socket.error, match="Socket is closed"):
114 sftp.open(sftp.FOLDER + "/test2", "w")
115
116 def test_sftp_can_be_used_as_context_manager(self, sftp):
117 """
118 verify that the sftp session is closed when exiting the context manager
119 """
120 with sftp:
121 pass
122 with pytest.raises(socket.error, match="Socket is closed"):
123 sftp.open(sftp.FOLDER + "/test2", "w")
124
125 def test_write(self, sftp):
126 """
127 verify that a file can be created and written, and the size is correct.
128 """
129 try:
130 with sftp.open(sftp.FOLDER + "/duck.txt", "w") as f:
131 f.write(ARTICLE)
132 assert sftp.stat(sftp.FOLDER + "/duck.txt").st_size == 1486
133 finally:
134 sftp.remove(sftp.FOLDER + "/duck.txt")
135
136 def test_sftp_file_can_be_used_as_context_manager(self, sftp):
137 """
138 verify that an opened file can be used as a context manager
139 """
140 try:
141 with sftp.open(sftp.FOLDER + "/duck.txt", "w") as f:
142 f.write(ARTICLE)
143 assert sftp.stat(sftp.FOLDER + "/duck.txt").st_size == 1486
144 finally:
145 sftp.remove(sftp.FOLDER + "/duck.txt")
146
147 def test_append(self, sftp):
148 """
149 verify that a file can be opened for append, and tell() still works.
150 """
151 try:
152 with sftp.open(sftp.FOLDER + "/append.txt", "w") as f:
153 f.write("first line\nsecond line\n")
154 assert f.tell() == 23
155
156 with sftp.open(sftp.FOLDER + "/append.txt", "a+") as f:
157 f.write("third line!!!\n")
158 assert f.tell() == 37
159 assert f.stat().st_size == 37
160 f.seek(-26, f.SEEK_CUR)
161 assert f.readline() == "second line\n"
162 finally:
163 sftp.remove(sftp.FOLDER + "/append.txt")
164
165 def test_rename(self, sftp):
166 """
167 verify that renaming a file works.
168 """
169 try:
170 with sftp.open(sftp.FOLDER + "/first.txt", "w") as f:
171 f.write("content!\n")
172 sftp.rename(
173 sftp.FOLDER + "/first.txt", sftp.FOLDER + "/second.txt"
174 )
175 with pytest.raises(IOError, match="No such file"):
176 sftp.open(sftp.FOLDER + "/first.txt", "r")
177 with sftp.open(sftp.FOLDER + "/second.txt", "r") as f:
178 f.seek(-6, f.SEEK_END)
179 assert u(f.read(4)) == "tent"
180 finally:
181 # TODO: this is gross, make some sort of 'remove if possible' / 'rm
182 # -f' a-like, jeez
183 try:
184 sftp.remove(sftp.FOLDER + "/first.txt")
185 except:
186 pass
187 try:
188 sftp.remove(sftp.FOLDER + "/second.txt")
189 except:
190 pass
191
192 def testa_posix_rename(self, sftp):
193 """Test [email protected] protocol extension."""
194 try:
195 # first check that the normal rename works as specified
196 with sftp.open(sftp.FOLDER + "/a", "w") as f:
197 f.write("one")
198 sftp.rename(sftp.FOLDER + "/a", sftp.FOLDER + "/b")
199 with sftp.open(sftp.FOLDER + "/a", "w") as f:
200 f.write("two")
201 with pytest.raises(IOError): # actual message seems generic
202 sftp.rename(sftp.FOLDER + "/a", sftp.FOLDER + "/b")
203
204 # now check with the posix_rename
205 sftp.posix_rename(sftp.FOLDER + "/a", sftp.FOLDER + "/b")
206 with sftp.open(sftp.FOLDER + "/b", "r") as f:
207 data = u(f.read())
208 err = "Contents of renamed file not the same as original file"
209 assert "two" == data, err
210
211 finally:
212 try:
213 sftp.remove(sftp.FOLDER + "/a")
214 except:
215 pass
216 try:
217 sftp.remove(sftp.FOLDER + "/b")
218 except:
219 pass
220
221 def test_folder(self, sftp):
222 """
223 create a temporary folder, verify that we can create a file in it, then
224 remove the folder and verify that we can't create a file in it anymore.
225 """
226 sftp.mkdir(sftp.FOLDER + "/subfolder")
227 sftp.open(sftp.FOLDER + "/subfolder/test", "w").close()
228 sftp.remove(sftp.FOLDER + "/subfolder/test")
229 sftp.rmdir(sftp.FOLDER + "/subfolder")
230 # shouldn't be able to create that file if dir removed
231 with pytest.raises(IOError, match="No such file"):
232 sftp.open(sftp.FOLDER + "/subfolder/test")
233
234 def test_listdir(self, sftp):
235 """
236 verify that a folder can be created, a bunch of files can be placed in
237 it, and those files show up in sftp.listdir.
238 """
239 try:
240 sftp.open(sftp.FOLDER + "/duck.txt", "w").close()
241 sftp.open(sftp.FOLDER + "/fish.txt", "w").close()
242 sftp.open(sftp.FOLDER + "/tertiary.py", "w").close()
243
244 x = sftp.listdir(sftp.FOLDER)
245 assert len(x) == 3
246 assert "duck.txt" in x
247 assert "fish.txt" in x
248 assert "tertiary.py" in x
249 assert "random" not in x
250 finally:
251 sftp.remove(sftp.FOLDER + "/duck.txt")
252 sftp.remove(sftp.FOLDER + "/fish.txt")
253 sftp.remove(sftp.FOLDER + "/tertiary.py")
254
255 def test_listdir_iter(self, sftp):
256 """
257 listdir_iter version of above test
258 """
259 try:
260 sftp.open(sftp.FOLDER + "/duck.txt", "w").close()
261 sftp.open(sftp.FOLDER + "/fish.txt", "w").close()
262 sftp.open(sftp.FOLDER + "/tertiary.py", "w").close()
263
264 x = [x.filename for x in sftp.listdir_iter(sftp.FOLDER)]
265 assert len(x) == 3
266 assert "duck.txt" in x
267 assert "fish.txt" in x
268 assert "tertiary.py" in x
269 assert "random" not in x
270 finally:
271 sftp.remove(sftp.FOLDER + "/duck.txt")
272 sftp.remove(sftp.FOLDER + "/fish.txt")
273 sftp.remove(sftp.FOLDER + "/tertiary.py")
274
275 @requireNonAsciiLocale()
276 def test_listdir_in_locale(self, sftp):
277 """Test listdir under a locale that uses non-ascii text."""
278 sftp.open(sftp.FOLDER + "/canard.txt", "w").close()
279 try:
280 folder_contents = sftp.listdir(sftp.FOLDER)
281 assert ["canard.txt"] == folder_contents
282 finally:
283 sftp.remove(sftp.FOLDER + "/canard.txt")
284
285 def test_setstat(self, sftp):
286 """
287 verify that the setstat functions (chown, chmod, utime, truncate) work.
288 """
289 try:
290 with sftp.open(sftp.FOLDER + "/special", "w") as f:
291 f.write("x" * 1024)
292
293 stat = sftp.stat(sftp.FOLDER + "/special")
294 sftp.chmod(sftp.FOLDER + "/special", (stat.st_mode & ~o777) | o600)
295 stat = sftp.stat(sftp.FOLDER + "/special")
296 expected_mode = o600
297 if sys.platform == "win32":
298 # chmod not really functional on windows
299 expected_mode = o666
300 if sys.platform == "cygwin":
301 # even worse.
302 expected_mode = o644
303 assert stat.st_mode & o777 == expected_mode
304 assert stat.st_size == 1024
305
306 mtime = stat.st_mtime - 3600
307 atime = stat.st_atime - 1800
308 sftp.utime(sftp.FOLDER + "/special", (atime, mtime))
309 stat = sftp.stat(sftp.FOLDER + "/special")
310 assert stat.st_mtime == mtime
311 if sys.platform not in ("win32", "cygwin"):
312 assert stat.st_atime == atime
313
314 # can't really test chown, since we'd have to know a valid uid.
315
316 sftp.truncate(sftp.FOLDER + "/special", 512)
317 stat = sftp.stat(sftp.FOLDER + "/special")
318 assert stat.st_size == 512
319 finally:
320 sftp.remove(sftp.FOLDER + "/special")
321
322 def test_fsetstat(self, sftp):
323 """
324 verify that the fsetstat functions (chown, chmod, utime, truncate)
325 work on open files.
326 """
327 try:
328 with sftp.open(sftp.FOLDER + "/special", "w") as f:
329 f.write("x" * 1024)
330
331 with sftp.open(sftp.FOLDER + "/special", "r+") as f:
332 stat = f.stat()
333 f.chmod((stat.st_mode & ~o777) | o600)
334 stat = f.stat()
335
336 expected_mode = o600
337 if sys.platform == "win32":
338 # chmod not really functional on windows
339 expected_mode = o666
340 if sys.platform == "cygwin":
341 # even worse.
342 expected_mode = o644
343 assert stat.st_mode & o777 == expected_mode
344 assert stat.st_size == 1024
345
346 mtime = stat.st_mtime - 3600
347 atime = stat.st_atime - 1800
348 f.utime((atime, mtime))
349 stat = f.stat()
350 assert stat.st_mtime == mtime
351 if sys.platform not in ("win32", "cygwin"):
352 assert stat.st_atime == atime
353
354 # can't really test chown, since we'd have to know a valid uid.
355
356 f.truncate(512)
357 stat = f.stat()
358 assert stat.st_size == 512
359 finally:
360 sftp.remove(sftp.FOLDER + "/special")
361
362 def test_readline_seek(self, sftp):
363 """
364 create a text file and write a bunch of text into it. then count the
365 lines in the file, and seek around to retrieve particular lines. this
366 should verify that read buffering and 'tell' work well together, and
367 that read buffering is reset on 'seek'.
368 """
369 try:
370 with sftp.open(sftp.FOLDER + "/duck.txt", "w") as f:
371 f.write(ARTICLE)
372
373 with sftp.open(sftp.FOLDER + "/duck.txt", "r+") as f:
374 line_number = 0
375 loc = 0
376 pos_list = []
377 for line in f:
378 line_number += 1
379 pos_list.append(loc)
380 loc = f.tell()
381 assert f.seekable()
382 f.seek(pos_list[6], f.SEEK_SET)
383 assert f.readline(), "Nouzilly == France.\n"
384 f.seek(pos_list[17], f.SEEK_SET)
385 assert f.readline()[:4] == "duck"
386 f.seek(pos_list[10], f.SEEK_SET)
387 expected = "duck types were equally resistant to exogenous insulin compared with chicken.\n" # noqa
388 assert f.readline() == expected
389 finally:
390 sftp.remove(sftp.FOLDER + "/duck.txt")
391
392 def test_write_seek(self, sftp):
393 """
394 Create a text file, seek back, change it, and verify.
395 """
396 try:
397 with sftp.open(sftp.FOLDER + "/testing.txt", "w") as f:
398 f.write("hello kitty.\n")
399 f.seek(-5, f.SEEK_CUR)
400 f.write("dd")
401
402 assert sftp.stat(sftp.FOLDER + "/testing.txt").st_size == 13
403 with sftp.open(sftp.FOLDER + "/testing.txt", "r") as f:
404 data = f.read(20)
405 assert data == b"hello kiddy.\n"
406 finally:
407 sftp.remove(sftp.FOLDER + "/testing.txt")
408
409 def test_symlink(self, sftp):
410 """
411 create a symlink and then check that lstat doesn't follow it.
412 """
413 if not hasattr(os, "symlink"):
414 # skip symlink tests on windows
415 return
416
417 try:
418 with sftp.open(sftp.FOLDER + "/original.txt", "w") as f:
419 f.write("original\n")
420 sftp.symlink("original.txt", sftp.FOLDER + "/link.txt")
421 assert sftp.readlink(sftp.FOLDER + "/link.txt") == "original.txt"
422
423 with sftp.open(sftp.FOLDER + "/link.txt", "r") as f:
424 assert f.readlines() == ["original\n"]
425
426 cwd = sftp.normalize(".")
427 if cwd[-1] == "/":
428 cwd = cwd[:-1]
429 abs_path = cwd + "/" + sftp.FOLDER + "/original.txt"
430 sftp.symlink(abs_path, sftp.FOLDER + "/link2.txt")
431 assert abs_path == sftp.readlink(sftp.FOLDER + "/link2.txt")
432
433 assert sftp.lstat(sftp.FOLDER + "/link.txt").st_size == 12
434 assert sftp.stat(sftp.FOLDER + "/link.txt").st_size == 9
435 # the sftp server may be hiding extra path members from us, so the
436 # length may be longer than we expect:
437 assert sftp.lstat(sftp.FOLDER + "/link2.txt").st_size >= len(
438 abs_path
439 )
440 assert sftp.stat(sftp.FOLDER + "/link2.txt").st_size == 9
441 assert sftp.stat(sftp.FOLDER + "/original.txt").st_size == 9
442 finally:
443 try:
444 sftp.remove(sftp.FOLDER + "/link.txt")
445 except:
446 pass
447 try:
448 sftp.remove(sftp.FOLDER + "/link2.txt")
449 except:
450 pass
451 try:
452 sftp.remove(sftp.FOLDER + "/original.txt")
453 except:
454 pass
455
456 def test_flush_seek(self, sftp):
457 """
458 verify that buffered writes are automatically flushed on seek.
459 """
460 try:
461 with sftp.open(sftp.FOLDER + "/happy.txt", "w", 1) as f:
462 f.write("full line.\n")
463 f.write("partial")
464 f.seek(9, f.SEEK_SET)
465 f.write("?\n")
466
467 with sftp.open(sftp.FOLDER + "/happy.txt", "r") as f:
468 assert f.readline() == u("full line?\n")
469 assert f.read(7) == b"partial"
470 finally:
471 try:
472 sftp.remove(sftp.FOLDER + "/happy.txt")
473 except:
474 pass
475
476 def test_realpath(self, sftp):
477 """
478 test that realpath is returning something non-empty and not an
479 error.
480 """
481 pwd = sftp.normalize(".")
482 assert len(pwd) > 0
483 f = sftp.normalize("./" + sftp.FOLDER)
484 assert len(f) > 0
485 assert os.path.join(pwd, sftp.FOLDER) == f
486
487 def test_mkdir(self, sftp):
488 """
489 verify that mkdir/rmdir work.
490 """
491 sftp.mkdir(sftp.FOLDER + "/subfolder")
492 with pytest.raises(IOError): # generic msg only
493 sftp.mkdir(sftp.FOLDER + "/subfolder")
494 sftp.rmdir(sftp.FOLDER + "/subfolder")
495 with pytest.raises(IOError, match="No such file"):
496 sftp.rmdir(sftp.FOLDER + "/subfolder")
497
498 def test_chdir(self, sftp):
499 """
500 verify that chdir/getcwd work.
501 """
502 root = sftp.normalize(".")
503 if root[-1] != "/":
504 root += "/"
505 try:
506 sftp.mkdir(sftp.FOLDER + "/alpha")
507 sftp.chdir(sftp.FOLDER + "/alpha")
508 sftp.mkdir("beta")
509 assert root + sftp.FOLDER + "/alpha" == sftp.getcwd()
510 assert ["beta"] == sftp.listdir(".")
511
512 sftp.chdir("beta")
513 with sftp.open("fish", "w") as f:
514 f.write("hello\n")
515 sftp.chdir("..")
516 assert ["fish"] == sftp.listdir("beta")
517 sftp.chdir("..")
518 assert ["fish"] == sftp.listdir("alpha/beta")
519 finally:
520 sftp.chdir(root)
521 try:
522 sftp.unlink(sftp.FOLDER + "/alpha/beta/fish")
523 except:
524 pass
525 try:
526 sftp.rmdir(sftp.FOLDER + "/alpha/beta")
527 except:
528 pass
529 try:
530 sftp.rmdir(sftp.FOLDER + "/alpha")
531 except:
532 pass
533
534 def test_get_put(self, sftp):
535 """
536 verify that get/put work.
537 """
538 warnings.filterwarnings("ignore", "tempnam.*")
539
540 fd, localname = mkstemp()
541 os.close(fd)
542 text = b"All I wanted was a plastic bunny rabbit.\n"
543 with open(localname, "wb") as f:
544 f.write(text)
545 saved_progress = []
546
547 def progress_callback(x, y):
548 saved_progress.append((x, y))
549
550 sftp.put(localname, sftp.FOLDER + "/bunny.txt", progress_callback)
551
552 with sftp.open(sftp.FOLDER + "/bunny.txt", "rb") as f:
553 assert text == f.read(128)
554 assert [(41, 41)] == saved_progress
555
556 os.unlink(localname)
557 fd, localname = mkstemp()
558 os.close(fd)
559 saved_progress = []
560 sftp.get(sftp.FOLDER + "/bunny.txt", localname, progress_callback)
561
562 with open(localname, "rb") as f:
563 assert text == f.read(128)
564 assert [(41, 41)] == saved_progress
565
566 os.unlink(localname)
567 sftp.unlink(sftp.FOLDER + "/bunny.txt")
568
569 def test_get_without_prefetch(self, sftp):
570 """
571 Create a 4MB file. Verify that pull works without prefetching
572 using a lager file.
573 """
574
575 sftp_filename = sftp.FOLDER + "/dummy_file"
576 num_chars = 1024 * 1024 * 4
577
578 fd, localname = mkstemp()
579 os.close(fd)
580
581 with open(localname, "wb") as f:
582 f.write(b"0" * num_chars)
583
584 sftp.put(localname, sftp_filename)
585
586 os.unlink(localname)
587 fd, localname = mkstemp()
588 os.close(fd)
589
590 sftp.get(sftp_filename, localname, prefetch=False)
591
592 assert os.stat(localname).st_size == num_chars
593
594 os.unlink(localname)
595 sftp.unlink(sftp_filename)
596
597 def test_check(self, sftp):
598 """
599 verify that file.check() works against our own server.
600 (it's an sftp extension that we support, and may be the only ones who
601 support it.)
602 """
603 with sftp.open(sftp.FOLDER + "/kitty.txt", "w") as f:
604 f.write("here kitty kitty" * 64)
605
606 try:
607 with sftp.open(sftp.FOLDER + "/kitty.txt", "r") as f:
608 sum = f.check("sha1")
609 assert (
610 "91059CFC6615941378D413CB5ADAF4C5EB293402"
611 == u(hexlify(sum)).upper()
612 )
613 sum = f.check("md5", 0, 512)
614 assert (
615 "93DE4788FCA28D471516963A1FE3856A"
616 == u(hexlify(sum)).upper()
617 )
618 sum = f.check("md5", 0, 0, 510)
619 expected = "EB3B45B8CD55A0707D99B177544A319F373183D241432BB2157AB9E46358C4AC90370B5CADE5D90336FC1716F90B36D6" # noqa
620 assert u(hexlify(sum)).upper() == expected
621 finally:
622 sftp.unlink(sftp.FOLDER + "/kitty.txt")
623
624 def test_x_flag(self, sftp):
625 """
626 verify that the 'x' flag works when opening a file.
627 """
628 sftp.open(sftp.FOLDER + "/unusual.txt", "wx").close()
629
630 try:
631 with pytest.raises(IOError):
632 sftp.open(sftp.FOLDER + "/unusual.txt", "wx")
633 finally:
634 sftp.unlink(sftp.FOLDER + "/unusual.txt")
635
636 def test_utf8(self, sftp):
637 """
638 verify that unicode strings are encoded into utf8 correctly.
639 """
640 with sftp.open(sftp.FOLDER + "/something", "w") as f:
641 f.write("okay")
642 try:
643 sftp.rename(
644 sftp.FOLDER + "/something", sftp.FOLDER + "/" + unicode_folder
645 )
646 sftp.open(b(sftp.FOLDER) + utf8_folder, "r")
647 finally:
648 sftp.unlink(b(sftp.FOLDER) + utf8_folder)
649
650 def test_utf8_chdir(self, sftp):
651 sftp.mkdir(sftp.FOLDER + "/" + unicode_folder)
652 try:
653 sftp.chdir(sftp.FOLDER + "/" + unicode_folder)
654 with sftp.open("something", "w") as f:
655 f.write("okay")
656 sftp.unlink("something")
657 finally:
658 sftp.chdir()
659 sftp.rmdir(sftp.FOLDER + "/" + unicode_folder)
660
661 def test_bad_readv(self, sftp):
662 """
663 verify that readv at the end of the file doesn't essplode.
664 """
665 sftp.open(sftp.FOLDER + "/zero", "w").close()
666 try:
667 with sftp.open(sftp.FOLDER + "/zero", "r") as f:
668 f.readv([(0, 12)])
669
670 with sftp.open(sftp.FOLDER + "/zero", "r") as f:
671 file_size = f.stat().st_size
672 f.prefetch(file_size)
673 f.read(100)
674 finally:
675 sftp.unlink(sftp.FOLDER + "/zero")
676
677 def test_put_without_confirm(self, sftp):
678 """
679 verify that get/put work without confirmation.
680 """
681 warnings.filterwarnings("ignore", "tempnam.*")
682
683 fd, localname = mkstemp()
684 os.close(fd)
685 text = b"All I wanted was a plastic bunny rabbit.\n"
686 with open(localname, "wb") as f:
687 f.write(text)
688 saved_progress = []
689
690 def progress_callback(x, y):
691 saved_progress.append((x, y))
692
693 res = sftp.put(
694 localname, sftp.FOLDER + "/bunny.txt", progress_callback, False
695 )
696
697 assert SFTPAttributes().attr == res.attr
698
699 with sftp.open(sftp.FOLDER + "/bunny.txt", "r") as f:
700 assert text == f.read(128)
701 assert (41, 41) == saved_progress[-1]
702
703 os.unlink(localname)
704 sftp.unlink(sftp.FOLDER + "/bunny.txt")
705
706 def test_getcwd(self, sftp):
707 """
708 verify that chdir/getcwd work.
709 """
710 assert sftp.getcwd() is None
711 root = sftp.normalize(".")
712 if root[-1] != "/":
713 root += "/"
714 try:
715 sftp.mkdir(sftp.FOLDER + "/alpha")
716 sftp.chdir(sftp.FOLDER + "/alpha")
717 assert sftp.getcwd() == "/" + sftp.FOLDER + "/alpha"
718 finally:
719 sftp.chdir(root)
720 try:
721 sftp.rmdir(sftp.FOLDER + "/alpha")
722 except:
723 pass
724
725 def test_seek_append(self, sftp):
726 """
727 verify that seek doesn't affect writes during append.
728
729 does not work except through paramiko. :( openssh fails.
730 """
731 try:
732 with sftp.open(sftp.FOLDER + "/append.txt", "a") as f:
733 f.write("first line\nsecond line\n")
734 f.seek(11, f.SEEK_SET)
735 f.write("third line\n")
736
737 with sftp.open(sftp.FOLDER + "/append.txt", "r") as f:
738 assert f.stat().st_size == 34
739 assert f.readline() == "first line\n"
740 assert f.readline() == "second line\n"
741 assert f.readline() == "third line\n"
742 finally:
743 sftp.remove(sftp.FOLDER + "/append.txt")
744
745 def test_putfo_empty_file(self, sftp):
746 """
747 Send an empty file and confirm it is sent.
748 """
749 target = sftp.FOLDER + "/empty file.txt"
750 stream = StringIO()
751 try:
752 attrs = sftp.putfo(stream, target)
753 # the returned attributes should not be null
754 assert attrs is not None
755 finally:
756 sftp.remove(target)
757
758 # TODO: this test doesn't actually fail if the regression (removing '%'
759 # expansion to '%%' within sftp.py's def _log()) is removed - stacktraces
760 # appear but they're clearly emitted from subthreads that have no error
761 # handling. No point running it until that is fixed somehow.
762 @pytest.mark.skip("Doesn't prove anything right now")
763 def test_file_with_percent(self, sftp):
764 """
765 verify that we can create a file with a '%' in the filename.
766 ( it needs to be properly escaped by _log() )
767 """
768 f = sftp.open(sftp.FOLDER + "/test%file", "w")
769 try:
770 assert f.stat().st_size == 0
771 finally:
772 f.close()
773 sftp.remove(sftp.FOLDER + "/test%file")
774
775 def test_non_utf8_data(self, sftp):
776 """Test write() and read() of non utf8 data"""
777 try:
778 with sftp.open(f"{sftp.FOLDER}/nonutf8data", "w") as f:
779 f.write(NON_UTF8_DATA)
780 with sftp.open(f"{sftp.FOLDER}/nonutf8data", "r") as f:
781 data = f.read()
782 assert data == NON_UTF8_DATA
783 with sftp.open(f"{sftp.FOLDER}/nonutf8data", "wb") as f:
784 f.write(NON_UTF8_DATA)
785 with sftp.open(f"{sftp.FOLDER}/nonutf8data", "rb") as f:
786 data = f.read()
787 assert data == NON_UTF8_DATA
788 finally:
789 sftp.remove(f"{sftp.FOLDER}/nonutf8data")
790
791 @requireNonAsciiLocale("LC_TIME")
792 def test_sftp_attributes_locale_time(self, sftp):
793 """Test SFTPAttributes under a locale with non-ascii time strings."""
794 some_stat = os.stat(sftp.FOLDER)
795 sftp_attributes = SFTPAttributes.from_stat(some_stat, u("a_directory"))
796 assert b"a_directory" in sftp_attributes.asbytes()
797
798 def test_sftp_attributes_empty_str(self, sftp):
799 sftp_attributes = SFTPAttributes()
800 assert (
801 str(sftp_attributes)
802 == "?--------- 1 0 0 0 (unknown date) ?"
803 )
804
805 @needs_builtin("buffer")
806 def test_write_buffer(self, sftp):
807 """Test write() using a buffer instance."""
808 data = 3 * b"A potentially large block of data to chunk up.\n"
809 try:
810 with sftp.open(f"{sftp.FOLDER}/write_buffer", "wb") as f:
811 for offset in range(0, len(data), 8):
812 f.write(buffer(data, offset, 8)) # noqa
813
814 with sftp.open(f"{sftp.FOLDER}/write_buffer", "rb") as f:
815 assert f.read() == data
816 finally:
817 sftp.remove(f"{sftp.FOLDER}/write_buffer")
818
819 @needs_builtin("memoryview")
820 def test_write_memoryview(self, sftp):
821 """Test write() using a memoryview instance."""
822 data = 3 * b"A potentially large block of data to chunk up.\n"
823 try:
824 with sftp.open(f"{sftp.FOLDER}/write_memoryview", "wb") as f:
825 view = memoryview(data)
826 for offset in range(0, len(data), 8):
827 f.write(view[offset : offset + 8])
828
829 with sftp.open(f"{sftp.FOLDER}/write_memoryview", "rb") as f:
830 assert f.read() == data
831 finally:
832 sftp.remove(f"{sftp.FOLDER}/write_memoryview")