Merge pull request #127 from mwilliamson/sftp-file-context-manager
Turn SFTPFile into a context manager
This commit is contained in:
commit
a69abd4606
|
@ -474,3 +474,9 @@ class SFTPFile (BufferedFile):
|
|||
x = self._saved_exception
|
||||
self._saved_exception = None
|
||||
raise x
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, type, value, traceback):
|
||||
self.close()
|
||||
|
|
|
@ -23,6 +23,8 @@ a real actual sftp server is contacted, and a new folder is created there to
|
|||
do test file operations in (so no existing files will be harmed).
|
||||
"""
|
||||
|
||||
from __future__ import with_statement
|
||||
|
||||
from binascii import hexlify
|
||||
import logging
|
||||
import os
|
||||
|
@ -188,6 +190,17 @@ class SFTPTest (unittest.TestCase):
|
|||
finally:
|
||||
sftp.remove(FOLDER + '/duck.txt')
|
||||
|
||||
def test_3_sftp_file_can_be_used_as_context_manager(self):
|
||||
"""
|
||||
verify that an opened file can be used as a context manager
|
||||
"""
|
||||
try:
|
||||
with sftp.open(FOLDER + '/duck.txt', 'w') as f:
|
||||
f.write(ARTICLE)
|
||||
self.assertEqual(sftp.stat(FOLDER + '/duck.txt').st_size, 1483)
|
||||
finally:
|
||||
sftp.remove(FOLDER + '/duck.txt')
|
||||
|
||||
def test_4_append(self):
|
||||
"""
|
||||
verify that a file can be opened for append, and tell() still works.
|
||||
|
|
Loading…
Reference in New Issue