Skip to content

Instantly share code, notes, and snippets.

@xandfury
Created August 1, 2018 11:08
Show Gist options
  • Save xandfury/f9cbd96879da65cc1b39633f6530fff2 to your computer and use it in GitHub Desktop.
Save xandfury/f9cbd96879da65cc1b39633f6530fff2 to your computer and use it in GitHub Desktop.
Hacking though WrapFS - Example Code
import fs
from fs.wrapfs import WrapFS
from fs import open_fs
from fs.mode import Mode
class _custom_file_wrapper(object):
"""This is a custom file class that does some setup and teardown stuff.."""
def __init__(self,
file_system,
parent_fs,
path,
mode,
buffering=-1,
encoding=None,
newline='',
line_buffering=False):
print('We should see this message when a new file is created!!')
self._file = parent_fs.openbin(path=path,
mode=mode,
buffering=buffering,
encoding=encoding)
# do some setUp stuff with _file.
print('Filesystem: {}, Parent File system: {}'.format(file_system, parent_fs))
def __enter__(self):
return self._file
def __exit__(self, exc_type, exc_value, traceback):
self.close()
return False
def close(self):
# do some tearDown stuff for the _file object.
print('Closing File ....')
self._file.close()
def __getattr__(self, item):
return getattr(self._file, item)
class TestFileSystem(WrapFS):
def __init__(self, path):
super(TestFileSystem, self).__init__(open_fs(path)) # wrap osfs at path
self._wrap_fs._meta['supports_rename'] = False
# ^^^ not sure if this is required as a custom getmeta() is defined below.
# But still - to be safe.
def getmeta(self, namespace="standard"):
"""Defined so that os.rename is never used."""
self.check()
meta = self.delegate_fs().getmeta(namespace=namespace)
meta['supports_rename'] = False
return meta
def openbin(self, path, mode="r", buffering=-1, **options):
print('Inside openbin of TestFileSystem. This is a test!')
return _custom_file_wrapper(parent_fs=self.delegate_fs(),
file_system=self,
path=path,
mode=Mode(mode).to_platform_bin(),
buffering=buffering)
# NOTE: my open() is similar. I omitted it's definition since setbinfile uses openbin rather than open.
if __name__ == '__main__':
print('Starting FS test')
import os
print('Listing files/directories in cwd: {}'.format(os.listdir('.')))
_fs = TestFileSystem('.')
if _fs.getmeta()["supports_rename"] is False:
print('Rename is False. os.rename should not be used')
with _fs.openbin('test_file.txt', mode='w') as _file:
_file.write(b'This is test file!')
assert 'test_file.txt' in _fs.listdir('/')
print('------------- Start Move --------------')
_fs.move('test_file.txt', 'test_file_with_diff_name.txt') # <<<---- This is where the problem is.
# I expect the _fs.move to call either open or openbin as explained by you.
# Ideally it should print 'Inside open of TestFileSystem. This is a test!' or 'Inside openbin of TestFileSystem. This is a test!'
print('------------- Stop Move --------------')
_fs.close()
print('Stopping FS test')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment