本文整理汇总了Python中fs.memoryfs.MemoryFS类的典型用法代码示例。如果您正苦于以下问题:Python MemoryFS类的具体用法?Python MemoryFS怎么用?Python MemoryFS使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MemoryFS类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_metadata_import_export
def test_metadata_import_export(self):
"""Two checks:
- unknown metadata is preserved across import-export
- inherited metadata doesn't leak to children.
"""
system = self.get_system()
v = 'March 20 17:00'
url_name = 'test1'
start_xml = '''
<course org="{org}" course="{course}"
due="{due}" url_name="{url_name}" unicorn="purple">
<chapter url="hi" url_name="ch" display_name="CH">
<html url_name="h" display_name="H">Two houses, ...</html>
</chapter>
</course>'''.format(due=v, org=ORG, course=COURSE, url_name=url_name)
descriptor = system.process_xml(start_xml)
compute_inherited_metadata(descriptor)
print(descriptor, descriptor._model_data)
self.assertEqual(descriptor.lms.due, Date().from_json(v))
# Check that the child inherits due correctly
child = descriptor.get_children()[0]
self.assertEqual(child.lms.due, Date().from_json(v))
self.assertEqual(child._inheritable_metadata, child._inherited_metadata)
self.assertEqual(2, len(child._inherited_metadata))
self.assertEqual('1970-01-01T00:00:00Z', child._inherited_metadata['start'])
self.assertEqual(v, child._inherited_metadata['due'])
# Now export and check things
resource_fs = MemoryFS()
exported_xml = descriptor.export_to_xml(resource_fs)
# Check that the exported xml is just a pointer
print("Exported xml:", exported_xml)
pointer = etree.fromstring(exported_xml)
self.assertTrue(is_pointer_tag(pointer))
# but it's a special case course pointer
self.assertEqual(pointer.attrib['course'], COURSE)
self.assertEqual(pointer.attrib['org'], ORG)
# Does the course still have unicorns?
with resource_fs.open('course/{url_name}.xml'.format(url_name=url_name)) as f:
course_xml = etree.fromstring(f.read())
self.assertEqual(course_xml.attrib['unicorn'], 'purple')
# the course and org tags should be _only_ in the pointer
self.assertTrue('course' not in course_xml.attrib)
self.assertTrue('org' not in course_xml.attrib)
# did we successfully strip the url_name from the definition contents?
self.assertTrue('url_name' not in course_xml.attrib)
# Does the chapter tag now have a due attribute?
# hardcoded path to child
with resource_fs.open('chapter/ch.xml') as f:
chapter_xml = etree.fromstring(f.read())
self.assertEqual(chapter_xml.tag, 'chapter')
self.assertFalse('due' in chapter_xml.attrib)
示例2: test_writefs_returns_none_if_all_fs_closed
def test_writefs_returns_none_if_all_fs_closed(self):
# Arrange
multifs = WritableMultiFS()
fs1 = MemoryFS()
multifs.addfs("fs1", fs1)
fs1.close()
# Act
assert multifs.writefs is None
示例3: test_free_space_returns_meta_if_has_meta
def test_free_space_returns_meta_if_has_meta(self):
# Arrange
fs = MemoryFS()
fs.getmeta = Mock(return_value=mb(230))
# Act
space = free_space(fs)
# Assert
assert space == mb(230)
示例4: test_safety_wrapper
def test_safety_wrapper(self):
rawfs = MemoryFS()
safefs = dokan.Win32SafetyFS(rawfs)
rawfs.setcontents("autoRun.inf", b("evilcodeevilcode"))
self.assertTrue(safefs.exists("_autoRun.inf"))
self.assertTrue("autoRun.inf" not in safefs.listdir("/"))
safefs.setcontents("file:stream",b("test"))
self.assertFalse(rawfs.exists("file:stream"))
self.assertTrue(rawfs.exists("file__colon__stream"))
self.assertTrue("file:stream" in safefs.listdir("/"))
示例5: TestFileCache
class TestFileCache(unittest.TestCase, CacheTests, NamespacesTests):
__test__ = True
def setUp(self):
self.fs = MemoryFS()
self.cache = cache.filecache.FileCache("test", "ns1", fs=self.fs)
self.cache2 = cache.filecache.FileCache("test", "ns2", fs=self.fs)
def tearDown(self):
self.fs.close()
self.fs = None
示例6: check_property
def check_property(self, descriptor):
xmodule_api_fs = MemoryFS()
xblock_api_fs = MemoryFS()
descriptor.runtime.export_fs = xblock_api_fs
xblock_node = etree.Element('unknown')
descriptor.add_xml_to_node(xblock_node)
xmodule_node = etree.fromstring(descriptor.export_to_xml(xmodule_api_fs))
self.assertEquals(list(xmodule_api_fs.walk()), list(xblock_api_fs.walk()))
self.assertEquals(etree.tostring(xmodule_node), etree.tostring(xblock_node))
示例7: test_copydir_indir
def test_copydir_indir(self):
"""Test copydir in a directory"""
fs1 = MemoryFS()
fs2 = MemoryFS()
self._make_fs(fs1)
utils.copydir(fs1, (fs2, "copy"))
self._check_fs(fs2.opendir("copy"))
fs1 = TempFS()
fs2 = TempFS()
self._make_fs(fs1)
utils.copydir(fs1, (fs2, "copy"))
self._check_fs(fs2.opendir("copy"))
示例8: test_movedir_indir
def test_movedir_indir(self):
"""Test movedir in a directory"""
fs1 = MemoryFS()
fs2 = MemoryFS()
fs1sub = fs1.makeopendir("from")
self._make_fs(fs1sub)
utils.movedir((fs1, "from"), (fs2, "copy"))
self.assert_(not fs1.exists("from"))
self._check_fs(fs2.opendir("copy"))
fs1 = TempFS()
fs2 = TempFS()
fs1sub = fs1.makeopendir("from")
self._make_fs(fs1sub)
utils.movedir((fs1, "from"), (fs2, "copy"))
self.assert_(not fs1.exists("from"))
self._check_fs(fs2.opendir("copy"))
示例9: test_mountfile
def test_mountfile(self):
"""Test mounting a file"""
quote = b"""If you wish to make an apple pie from scratch, you must first invent the universe."""
mem_fs = MemoryFS()
mem_fs.makedir('foo')
mem_fs.setcontents('foo/bar.txt', quote)
foo_dir = mem_fs.opendir('foo')
mount_fs = MountFS()
mount_fs.mountfile('bar.txt', foo_dir.open, foo_dir.getinfo)
self.assert_(mount_fs.isdir('/'))
self.assert_(mount_fs.isdir('./'))
self.assert_(mount_fs.isdir(''))
# Check we can see the mounted file in the dir list
self.assertEqual(mount_fs.listdir(), ["bar.txt"])
self.assert_(not mount_fs.exists('nobodyhere.txt'))
self.assert_(mount_fs.exists('bar.txt'))
self.assert_(mount_fs.isfile('bar.txt'))
self.assert_(not mount_fs.isdir('bar.txt'))
# Check open and getinfo callables
self.assertEqual(mount_fs.getcontents('bar.txt'), quote)
self.assertEqual(mount_fs.getsize('bar.txt'), len(quote))
# Check changes are written back
mem_fs.setcontents('foo/bar.txt', 'baz')
self.assertEqual(mount_fs.getcontents('bar.txt'), b'baz')
self.assertEqual(mount_fs.getsize('bar.txt'), len('baz'))
# Check changes are written to the original fs
self.assertEqual(mem_fs.getcontents('foo/bar.txt'), b'baz')
self.assertEqual(mem_fs.getsize('foo/bar.txt'), len('baz'))
# Check unmount
self.assert_(mount_fs.unmount("bar.txt"))
self.assertEqual(mount_fs.listdir(), [])
self.assert_(not mount_fs.exists('bar.txt'))
# Check unount a second time is a null op, and returns False
self.assertFalse(mount_fs.unmount("bar.txt"))
示例10: TestWalk
class TestWalk(unittest.TestCase):
def setUp(self):
self.fs = MemoryFS()
self.fs.setcontents('a.txt', 'hello')
self.fs.setcontents('b.txt', 'world')
self.fs.makeopendir('foo').setcontents('c', '123')
self.fs.makeopendir('.svn').setcontents('ignored', '')
def test_wildcard(self):
for dir_path, paths in self.fs.walk(wildcard='*.txt'):
for path in paths:
self.assert_(path.endswith('.txt'))
for dir_path, paths in self.fs.walk(wildcard=lambda fn:fn.endswith('.txt')):
for path in paths:
self.assert_(path.endswith('.txt'))
def test_dir_wildcard(self):
for dir_path, paths in self.fs.walk(dir_wildcard=lambda fn:not fn.endswith('.svn')):
for path in paths:
self.assert_('.svn' not in path)
示例11: __init__
def __init__(self, root, cmd_channel):
AbstractedFS.__init__(self, root, cmd_channel)
self.cwd = root
self.type = cmd_channel.type
self.s3_bucket = cmd_channel.s3_bucket
self.aws_access_key = cmd_channel.aws_access_key
self.aws_secret_key = cmd_channel.aws_secret_key
self.seperator = cmd_channel.seperator
self.thread_synchronize = cmd_channel.thread_synchronize
self.key_sync_timeout = cmd_channel.key_sync_timeout
if not self.cmd_channel.fs_obj:
if self.type == "memory":
self.fs_obj = MemoryFS()
elif self.type == "s3":
self.fs_obj = S3FS(bucket=self.bucket, prefix=self.prefix, aws_access_key=self.aws_access_key, aws_secret_key=self.aws_secret_key, separator=self.seperator, thread_synchronize=self.thread_synchronize, key_sync_timeout=self.key_sync_timeout)
self.cmd_channel.fs_obj = self.fs_obj
else:
self.fs_obj = self.cmd_channel.fs_obj
示例12: __init__
def __init__(self, slf_filename):
super(SlfFS, self).__init__()
if isinstance(slf_filename, str):
slf_filename = os.path.expanduser(os.path.expandvars(slf_filename))
slf_filename = os.path.normpath(os.path.abspath(slf_filename))
try:
self.file_name = slf_filename
self.file = open(slf_filename, 'rb')
except FileNotFoundError as e:
raise CreateFailedError(
'Slf file not found ({0})'.format(slf_filename),
details=e
)
else:
self.file_name = 'file-like'
self.file = slf_filename
self.header = SlfHeader.from_bytes(self.file.read(SlfHeader.get_size()))
self.entries = list(map(self._read_entry, range(self.header['number_of_entries'])))
self.library_name = self.header['library_name']
self.library_path = self.header['library_path']
self.sort = self.header['sort']
self.version = self.header['version']
self._path_fs = MemoryFS()
for e in self.entries:
path = _get_normalized_filename(e['file_name']).split('/')
directory = '/'.join(path[:-1]) if len(path) > 2 else '/'
if self._path_fs.isfile(directory):
# Sometimes there exists a file that has the same name as a directory
# Solution: Rename it with a _DIRECTORY_CONFLICT suffix
self._path_fs.move(directory, directory + DIRECTORY_CONFLICT_SUFFIX)
if self._path_fs.isdir('/'.join(path)):
self._path_fs.createfile('/'.join(path) + DIRECTORY_CONFLICT_SUFFIX)
else:
self._path_fs.makedir(directory, recursive=True, allow_recreate=True)
self._path_fs.createfile('/'.join(path))
示例13: test_movedir_root
def test_movedir_root(self):
"""Test movedir to root dir"""
fs1 = MemoryFS()
fs2 = MemoryFS()
fs1sub = fs1.makeopendir("from")
self._make_fs(fs1sub)
utils.movedir((fs1, "from"), fs2)
self.assert_(not fs1.exists("from"))
self._check_fs(fs2)
fs1 = TempFS()
fs2 = TempFS()
fs1sub = fs1.makeopendir("from")
self._make_fs(fs1sub)
utils.movedir((fs1, "from"), fs2)
self.assert_(not fs1.exists("from"))
self._check_fs(fs2)
示例14: __init__
def __init__(self, filename, mode="r", thread_synchronize=True):
"""Create a FS that maps on to a big file.
:param filename: A (system) path, or a file-like object
:param mode: Mode to open file: 'r' for reading, 'w' and 'a' not supported
:param thread_synchronize: -- Set to True (default) to enable thread-safety
"""
super(BigFS, self).__init__(thread_synchronize=thread_synchronize)
if len(mode) > 1 or mode not in "r":
raise ValueError("mode must be 'r'")
self.file_mode = mode
self.big_path = str(filename)
self.entries = {}
try:
self.bf = open(filename, "rb")
except IOError:
raise ResourceNotFoundError(str(filename), msg="BIG file does not exist: %(path)s")
self._path_fs = MemoryFS()
if mode in 'ra':
self._parse_resource_list(self.bf)
示例15: parted_file
def parted_file(self):
fs = MemoryFS()
mode = "wb+"
path = "cuckoo.tar"
parts = [FilePart(fs.open("cuckoo.tar.part0", mode)), (fs.open("cuckoo.tar.part1", mode))]
return PartedFile(path=path, mode=mode, fs=fs, max_part_size=kb(4), parts=parts)