diff --git a/README.md b/README.md index 5fbfaf20..ce2d3ce8 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ The PyTest plugin provides the `fs` fixture for use in your test. For example: ```python def my_fakefs_test(fs): # "fs" is the reference to the fake file system - fs.CreateFile('/var/data/xx1.txt') + fs.create_file('/var/data/xx1.txt') assert os.path.exists('/var/data/xx1.txt') ``` @@ -59,7 +59,7 @@ from fake_filesystem_unittest import Patcher with Patcher() as patcher: # access the fake_filesystem object via patcher.fs - patcher.fs.CreateFile('/foo/bar', contents='test') + patcher.fs.create_file('/foo/bar', contents='test') # the following code works on the fake filesystem with open('/foo/bar') as f: diff --git a/docs/modules.rst b/docs/modules.rst index 360ab3d2..02585890 100644 --- a/docs/modules.rst +++ b/docs/modules.rst @@ -4,10 +4,6 @@ Public Modules and Classes are shown. Methods that mimic the behavior of standard Python functions are not listed - you may always use the standard functions. -*Style note:* most method names conform to the original Google style that does -not match PEP-8. In the next version, we plan to change the API to conform -to PEP-8 (maintaining upwards compatibility). - Fake filesystem module ---------------------- .. automodule:: pyfakefs.fake_filesystem @@ -15,17 +11,17 @@ Fake filesystem module Fake filesystem classes ----------------------- .. autoclass:: pyfakefs.fake_filesystem.FakeFilesystem - :members: AddMountPoint, - GetDiskUsage, SetDiskUsage, ChangeDiskUsage, + :members: add_mount_point, + get_disk_usage, set_disk_usage, change_disk_usage, add_real_directory, add_real_file, add_real_paths, - CreateDirectory, CreateFile + create_dir, create_file, create_symlink .. autoclass:: pyfakefs.fake_filesystem.FakeFile - :members: byte_contents, contents, GetPath, GetSize, - IsLargeFile, SetContents, SetSize + :members: byte_contents, contents, path, size, + is_large_file, set_contents .. autoclass:: pyfakefs.fake_filesystem.FakeDirectory - :members: contents, GetEntry, GetSize, RemoveEntry + :members: contents, get_entry, size, remove_entry Unittest module classes ----------------------- diff --git a/docs/usage.rst b/docs/usage.rst index c1a160f1..0e364b5b 100644 --- a/docs/usage.rst +++ b/docs/usage.rst @@ -24,7 +24,7 @@ The PyTest plugin provides the ``fs`` fixture for use in your test. For example: def my_fakefs_test(fs): # "fs" is the reference to the fake file system - fs.CreateFile('/var/data/xx1.txt') + fs.create_file('/var/data/xx1.txt') assert os.path.exists('/var/data/xx1.txt') Patch using fake_filesystem_unittest.Patcher @@ -83,7 +83,7 @@ The following modules and functions can be patched: fs = fake_fs.FakeFilesystem() # Do some setup on the faked file system - fs.CreateFile('/foo/bar', contents='test') + fs.create_file('/foo/bar', contents='test') # Replace some built-in file system related modules you use with faked ones diff --git a/dynamic_patch_test.py b/dynamic_patch_test.py index e6bea6ca..943ab991 100644 --- a/dynamic_patch_test.py +++ b/dynamic_patch_test.py @@ -36,28 +36,28 @@ def testOsPatch(self): import os os.mkdir('test') - self.assertTrue(self.fs.Exists('test')) + self.assertTrue(self.fs.exists('test')) self.assertTrue(os.path.exists('test')) def testOsImportAsPatch(self): import os as _os _os.mkdir('test') - self.assertTrue(self.fs.Exists('test')) + self.assertTrue(self.fs.exists('test')) self.assertTrue(_os.path.exists('test')) def testOsPathPatch(self): import os.path os.mkdir('test') - self.assertTrue(self.fs.Exists('test')) + self.assertTrue(self.fs.exists('test')) self.assertTrue(os.path.exists('test')) @unittest.skipIf(sys.version_info < (3, 3), 'disk_usage new in Python 3.3') def testShutilPatch(self): import shutil - self.fs.SetDiskUsage(100) + self.fs.set_disk_usage(100) self.assertEqual(100, shutil.disk_usage('/').total) @unittest.skipIf(sys.version_info < (3, 4), 'pathlib new in Python 3.4') @@ -69,8 +69,8 @@ def testPathlibPatch(self): with path.open('w') as f: f.write('test') - self.assertTrue(self.fs.Exists(file_path)) - file_object = self.fs.GetObject(file_path) + self.assertTrue(self.fs.exists(file_path)) + file_object = self.fs.get_object(file_path) self.assertEqual('test', file_object.contents) diff --git a/example_test.py b/example_test.py index 76ee4243..6beaef0e 100644 --- a/example_test.py +++ b/example_test.py @@ -19,11 +19,11 @@ Test the :py:class`pyfakefs.example` module to demonstrate the usage of the :py:class`pyfakefs.fake_filesystem_unittest.TestCase` base class. -Fake filesystem functions like `CreateFile()`, `CreateDirectory()` or `CreateLink()` +Fake filesystem functions like `create_file()`, `create_dir()` or `symlink()` are often used to set up file structures at the beginning of a test. While you could also use the familiar `open()`, `os.mkdirs()` and similar functions, these functions can make the test code shorter and more readable. -`CreateFile()` is particularly convenient because it creates all parent directories +`create_file()` is particularly convenient because it creates all parent directories and allows you to specify the contents or the size of the file. """ @@ -85,8 +85,8 @@ def test_create_file(self): def test_delete_file(self): """Test example.delete_file() which uses `os.remove()`.""" - self.fs.CreateFile('/test/full.txt', - contents='First line\n' + self.fs.create_file('/test/full.txt', + contents='First line\n' 'Second Line\n') self.assertTrue(os.path.exists('/test/full.txt')) example.delete_file('/test/full.txt') @@ -95,13 +95,13 @@ def test_delete_file(self): def test_file_exists(self): """Test example.path_exists() which uses `os.path.exists()`.""" self.assertFalse(example.path_exists('/test/empty.txt')) - self.fs.CreateFile('/test/empty.txt') + self.fs.create_file('/test/empty.txt') self.assertTrue(example.path_exists('/test/empty.txt')) def test_get_globs(self): """Test example.get_glob().""" self.assertFalse(os.path.isdir('/test')) - self.fs.CreateDirectory('/test/dir1/dir2a') + self.fs.create_dir('/test/dir1/dir2a') self.assertTrue(os.path.isdir('/test/dir1/dir2a')) # os.mkdirs() works, too. os.makedirs('/test/dir1/dir2b') @@ -118,7 +118,7 @@ def test_get_globs(self): def test_rm_tree(self): """Test example.rm_tree() using `shutil.rmtree()`.""" - self.fs.CreateDirectory('/test/dir1/dir2a') + self.fs.create_dir('/test/dir1/dir2a') # os.mkdirs() works, too. os.makedirs('/test/dir1/dir2b') self.assertTrue(os.path.isdir('/test/dir1/dir2b')) @@ -135,10 +135,10 @@ def test_os_scandir(self): The os module has been replaced with the fake os module so the fake filesystem path entries are returned instead of `os.DirEntry` objects. """ - self.fs.CreateFile('/test/text.txt') - self.fs.CreateDirectory('/test/dir') - self.fs.CreateFile('/linktest/linked') - self.fs.CreateLink('/test/linked_file', '/linktest/linked') + self.fs.create_file('/test/text.txt') + self.fs.create_dir('/test/dir') + self.fs.create_file('/linktest/linked') + self.fs.create_symlink('/test/linked_file', '/linktest/linked') entries = sorted(example.scan_dir('/test'), key=lambda e: e.name) self.assertEqual(3, len(entries)) diff --git a/fake_filesystem_glob_test.py b/fake_filesystem_glob_test.py index 1e939857..fa61ce39 100755 --- a/fake_filesystem_glob_test.py +++ b/fake_filesystem_glob_test.py @@ -27,11 +27,11 @@ class FakeGlobUnitTest(fake_filesystem_unittest.TestCase): def setUp(self): self.setUpPyfakefs() directory = './xyzzy' - self.fs.CreateDirectory(directory) - self.fs.CreateDirectory('%s/subdir' % directory) - self.fs.CreateDirectory('%s/subdir2' % directory) - self.fs.CreateFile('%s/subfile' % directory) - self.fs.CreateFile('[Temp]') + self.fs.create_dir(directory) + self.fs.create_dir('%s/subdir' % directory) + self.fs.create_dir('%s/subdir2' % directory) + self.fs.create_file('%s/subfile' % directory) + self.fs.create_file('[Temp]') def testGlobEmpty(self): self.assertEqual(glob.glob(''), []) diff --git a/fake_filesystem_shutil_test.py b/fake_filesystem_shutil_test.py index 49d7782c..30274101 100755 --- a/fake_filesystem_shutil_test.py +++ b/fake_filesystem_shutil_test.py @@ -39,8 +39,8 @@ def setUp(self): self.filesystem = self.fs self.os = os self.open = open - self.fs.SetDiskUsage(1000) - self.fs.CreateDirectory(self.base_path) + self.fs.set_disk_usage(1000) + self.fs.create_dir(self.base_path) def tearDown(self): if self.useRealFs(): @@ -257,7 +257,7 @@ def testMoveFileInSameFilesystem(self): self.skipRealFs() src_file = '/original_xyzzy' dst_file = '/moved_xyzzy' - src_object = self.fs.CreateFile(src_file) + src_object = self.fs.create_file(src_file) src_ino = src_object.st_ino src_dev = src_object.st_dev @@ -267,16 +267,16 @@ def testMoveFileInSameFilesystem(self): self.assertTrue(os.path.exists(dst_file)) self.assertFalse(os.path.exists(src_file)) - dst_object = self.fs.GetObject(dst_file) + dst_object = self.fs.get_object(dst_file) self.assertEqual(src_ino, dst_object.st_ino) self.assertEqual(src_dev, dst_object.st_dev) def testMoveFileIntoOtherFilesystem(self): self.skipRealFs() - self.fs.AddMountPoint('/mount') + self.fs.add_mount_point('/mount') src_file = '/original_xyzzy' dst_file = '/mount/moved_xyzzy' - src_object = self.fs.CreateFile(src_file) + src_object = self.fs.create_file(src_file) src_ino = src_object.st_ino src_dev = src_object.st_dev @@ -284,7 +284,7 @@ def testMoveFileIntoOtherFilesystem(self): self.assertTrue(os.path.exists(dst_file)) self.assertFalse(os.path.exists(src_file)) - dst_object = self.fs.GetObject(dst_file) + dst_object = self.fs.get_object(dst_file) self.assertNotEqual(src_ino, dst_object.st_ino) self.assertNotEqual(src_dev, dst_object.st_dev) @@ -317,15 +317,15 @@ def testMoveDirectory(self): @unittest.skipIf(sys.version_info < (3, 3), 'New in Python 3.3') def testDiskUsage(self): self.skipRealFs() - self.fs.CreateFile('/foo/bar', st_size=400) + self.fs.create_file('/foo/bar', st_size=400) disk_usage = shutil.disk_usage('/') self.assertEqual(1000, disk_usage.total) self.assertEqual(400, disk_usage.used) self.assertEqual(600, disk_usage.free) self.assertEqual((1000, 400, 600), disk_usage) - self.fs.AddMountPoint('/mount', total_size=500) - self.fs.CreateFile('/mount/foo/bar', st_size=400) + self.fs.add_mount_point('/mount', total_size=500) + self.fs.create_file('/mount/foo/bar', st_size=400) disk_usage = shutil.disk_usage('/mount/foo/') self.assertEqual((500, 400, 100), disk_usage) diff --git a/fake_filesystem_test.py b/fake_filesystem_test.py index 0328430b..d9df6fb2 100755 --- a/fake_filesystem_test.py +++ b/fake_filesystem_test.py @@ -313,44 +313,50 @@ def testNewFileAndDirectory(self): self.assertEqual(10, self.fake_file.st_ctime) def testAddEntry(self): - self.fake_dir.AddEntry(self.fake_file) + self.fake_dir.add_entry(self.fake_file) self.assertEqual({'foobar': self.fake_file}, self.fake_dir.contents) def testGetEntry(self): - self.fake_dir.AddEntry(self.fake_file) - self.assertEqual(self.fake_file, self.fake_dir.GetEntry('foobar')) + self.fake_dir.add_entry(self.fake_file) + self.assertEqual(self.fake_file, self.fake_dir.get_entry('foobar')) - def testGetPath(self): - self.filesystem.root.AddEntry(self.fake_dir) - self.fake_dir.AddEntry(self.fake_file) - self.assertEqual('/somedir/foobar', self.fake_file.GetPath()) + def testPath(self): + self.filesystem.root.add_entry(self.fake_dir) + self.fake_dir.add_entry(self.fake_file) + self.assertEqual('/somedir/foobar', self.fake_file.path) def testRemoveEntry(self): - self.fake_dir.AddEntry(self.fake_file) - self.assertEqual(self.fake_file, self.fake_dir.GetEntry('foobar')) - self.fake_dir.RemoveEntry('foobar') - self.assertRaises(KeyError, self.fake_dir.GetEntry, 'foobar') + self.fake_dir.add_entry(self.fake_file) + self.assertEqual(self.fake_file, self.fake_dir.get_entry('foobar')) + self.fake_dir.remove_entry('foobar') + self.assertRaises(KeyError, self.fake_dir.get_entry, 'foobar') def testShouldThrowIfSetSizeIsNotInteger(self): - self.assertRaisesIOError(errno.ENOSPC, self.fake_file.SetSize, 0.1) + def set_size(): + self.fake_file.size = 0.1 + + self.assertRaisesIOError(errno.ENOSPC, set_size) def testShouldThrowIfSetSizeIsNegative(self): - self.assertRaisesIOError(errno.ENOSPC, self.fake_file.SetSize, -1) + def set_size(): + self.fake_file.size = -1 + + self.assertRaisesIOError(errno.ENOSPC, set_size) def testProduceEmptyFileIfSetSizeIsZero(self): - self.fake_file.SetSize(0) + self.fake_file.size = 0 self.assertEqual('', self.fake_file.contents) def testSetsContentEmptyIfSetSizeIsZero(self): - self.fake_file.SetSize(0) + self.fake_file.size = 0 self.assertEqual('', self.fake_file.contents) def testTruncateFileIfSizeIsSmallerThanCurrentSize(self): - self.fake_file.SetSize(6) + self.fake_file.size = 6 self.assertEqual('dummy_', self.fake_file.contents) def testLeaveFileUnchangedIfSizeIsEqualToCurrentSize(self): - self.fake_file.SetSize(10) + self.fake_file.size = 10 self.assertEqual('dummy_file', self.fake_file.contents) def testSetContentsToDirRaises(self): @@ -358,51 +364,51 @@ def testSetContentsToDirRaises(self): self.filesystem.is_windows_fs = True error_check = (self.assertRaisesIOError if self.is_python2 else self.assertRaisesOSError) - error_check(errno.EISDIR, self.fake_dir.SetContents, 'a') + error_check(errno.EISDIR, self.fake_dir.set_contents, 'a') self.filesystem.is_windows_fs = False - self.assertRaisesIOError(errno.EISDIR, self.fake_dir.SetContents, 'a') + self.assertRaisesIOError(errno.EISDIR, self.fake_dir.set_contents, 'a') def testPadsFileContentWithNullBytesIfSizeIsGreaterThanCurrentSize(self): - self.fake_file.SetSize(13) + self.fake_file.size = 13 self.assertEqual('dummy_file\0\0\0', self.fake_file.contents) def testSetMTime(self): self.assertEqual(10, self.fake_file.st_mtime) - self.fake_file.SetMTime(13) + self.fake_file.st_mtime = 13 self.assertEqual(13, self.fake_file.st_mtime) - self.fake_file.SetMTime(131) + self.fake_file.st_mtime = 131 self.assertEqual(131, self.fake_file.st_mtime) def testFileInode(self): filesystem = fake_filesystem.FakeFilesystem(path_separator='/') fake_os = fake_filesystem.FakeOsModule(filesystem) file_path = 'some_file1' - filesystem.CreateFile(file_path, contents='contents here1') + filesystem.create_file(file_path, contents='contents here1') self.assertLess(0, fake_os.stat(file_path)[stat.ST_INO]) - file_obj = filesystem.GetObject(file_path) - file_obj.SetIno(43) + file_obj = filesystem.get_object(file_path) + file_obj.st_ino = 43 self.assertEqual(43, fake_os.stat(file_path)[stat.ST_INO]) def testDirectoryInode(self): filesystem = fake_filesystem.FakeFilesystem(path_separator='/') fake_os = fake_filesystem.FakeOsModule(filesystem) dirpath = 'testdir' - filesystem.CreateDirectory(dirpath) + filesystem.create_dir(dirpath) self.assertLess(0, fake_os.stat(dirpath)[stat.ST_INO]) - dir_obj = filesystem.GetObject(dirpath) - dir_obj.SetIno(43) + dir_obj = filesystem.get_object(dirpath) + dir_obj.st_ino = 43 self.assertEqual(43, fake_os.stat(dirpath)[stat.ST_INO]) def testOrderedDirs(self): filesystem = fake_filesystem.FakeFilesystem(path_separator='/') - filesystem.CreateDirectory('/foo') - filesystem.CreateFile('/foo/2') - filesystem.CreateFile('/foo/4') - filesystem.CreateFile('/foo/1') - filesystem.CreateFile('/foo/3') - fake_dir = filesystem.GetObject('/foo') + filesystem.create_dir('/foo') + filesystem.create_file('/foo/2') + filesystem.create_file('/foo/4') + filesystem.create_file('/foo/1') + filesystem.create_file('/foo/3') + fake_dir = filesystem.get_object('/foo') self.assertEqual(['2', '4', '1', '3'], fake_dir.ordered_dirs) @@ -413,15 +419,15 @@ def setUp(self): filesystem=filesystem) def testShouldThrowIfSizeIsNotInteger(self): - self.assertRaisesIOError(errno.ENOSPC, self.fake_file.SetLargeFileSize, - 0.1) + self.assertRaisesIOError(errno.ENOSPC, + self.fake_file.set_large_file_size, 0.1) def testShouldThrowIfSizeIsNegative(self): - self.assertRaisesIOError(errno.ENOSPC, self.fake_file.SetLargeFileSize, - -1) + self.assertRaisesIOError(errno.ENOSPC, + self.fake_file.set_large_file_size, -1) def testSetsContentNoneIfSizeIsNonNegativeInteger(self): - self.fake_file.SetLargeFileSize(1000000000) + self.fake_file.set_large_file_size(1000000000) self.assertEqual(None, self.fake_file.contents) self.assertEqual(1000000000, self.fake_file.st_size) @@ -432,30 +438,30 @@ def setUp(self): self.root_name = '/' def testEmptyPathShouldGetNormalizedToRootPath(self): - self.assertEqual(self.root_name, self.filesystem.NormalizePath('')) + self.assertEqual(self.root_name, self.filesystem.absnormpath('')) def testRootPathRemainsUnchanged(self): self.assertEqual(self.root_name, - self.filesystem.NormalizePath(self.root_name)) + self.filesystem.absnormpath(self.root_name)) def testRelativePathForcedToCwd(self): path = 'bar' self.filesystem.cwd = '/foo' - self.assertEqual('/foo/bar', self.filesystem.NormalizePath(path)) + self.assertEqual('/foo/bar', self.filesystem.absnormpath(path)) def testAbsolutePathRemainsUnchanged(self): path = '/foo/bar' - self.assertEqual(path, self.filesystem.NormalizePath(path)) + self.assertEqual(path, self.filesystem.absnormpath(path)) def testDottedPathIsNormalized(self): path = '/foo/..' - self.assertEqual('/', self.filesystem.NormalizePath(path)) + self.assertEqual('/', self.filesystem.absnormpath(path)) path = 'foo/../bar' - self.assertEqual('/bar', self.filesystem.NormalizePath(path)) + self.assertEqual('/bar', self.filesystem.absnormpath(path)) def testDotPathIsNormalized(self): path = '.' - self.assertEqual('/', self.filesystem.NormalizePath(path)) + self.assertEqual('/', self.filesystem.absnormpath(path)) class GetPathComponentsTest(TestCase): @@ -464,24 +470,24 @@ def setUp(self): self.root_name = '/' def testRootPathShouldReturnEmptyList(self): - self.assertEqual([], self.filesystem.GetPathComponents(self.root_name)) + self.assertEqual([], self.filesystem._path_components(self.root_name)) def testEmptyPathShouldReturnEmptyList(self): - self.assertEqual([], self.filesystem.GetPathComponents('')) + self.assertEqual([], self.filesystem._path_components('')) def testRelativePathWithOneComponentShouldReturnComponent(self): - self.assertEqual(['foo'], self.filesystem.GetPathComponents('foo')) + self.assertEqual(['foo'], self.filesystem._path_components('foo')) def testAbsolutePathWithOneComponentShouldReturnComponent(self): - self.assertEqual(['foo'], self.filesystem.GetPathComponents('/foo')) + self.assertEqual(['foo'], self.filesystem._path_components('/foo')) def testTwoLevelRelativePathShouldReturnComponents(self): self.assertEqual(['foo', 'bar'], - self.filesystem.GetPathComponents('foo/bar')) + self.filesystem._path_components('foo/bar')) def testTwoLevelAbsolutePathShouldReturnComponents(self): self.assertEqual(['foo', 'bar'], - self.filesystem.GetPathComponents('/foo/bar')) + self.filesystem._path_components('/foo/bar')) class FakeFilesystemUnitTest(TestCase): @@ -502,51 +508,51 @@ def testNewFilesystem(self): self.assertEqual({}, self.filesystem.root.contents) def testNoneRaisesTypeError(self): - self.assertRaises(TypeError, self.filesystem.Exists, None) + self.assertRaises(TypeError, self.filesystem.exists, None) def testEmptyStringDoesNotExist(self): - self.assertFalse(self.filesystem.Exists('')) + self.assertFalse(self.filesystem.exists('')) def testExistsRoot(self): - self.assertTrue(self.filesystem.Exists(self.root_name)) + self.assertTrue(self.filesystem.exists(self.root_name)) def testExistsUnaddedFile(self): - self.assertFalse(self.filesystem.Exists(self.fake_file.name)) + self.assertFalse(self.filesystem.exists(self.fake_file.name)) def testNotExistsSubpathNamedLikeFileContents(self): # Regression test for #219 file_path = "/foo/bar" - self.filesystem.CreateFile(file_path, contents='baz') - self.assertFalse(self.filesystem.Exists(file_path + "/baz")) + self.filesystem.create_file(file_path, contents='baz') + self.assertFalse(self.filesystem.exists(file_path + "/baz")) def testGetRootObject(self): self.assertEqual(self.filesystem.root, - self.filesystem.GetObject(self.root_name)) + self.filesystem.get_object(self.root_name)) def testAddObjectToRoot(self): - self.filesystem.AddObject(self.root_name, self.fake_file) + self.filesystem.add_object(self.root_name, self.fake_file) self.assertEqual({'foobar': self.fake_file}, self.filesystem.root.contents) def testExistsAddedFile(self): - self.filesystem.AddObject(self.root_name, self.fake_file) - self.assertTrue(self.filesystem.Exists(self.fake_file.name)) + self.filesystem.add_object(self.root_name, self.fake_file) + self.assertTrue(self.filesystem.exists(self.fake_file.name)) def testExistsRelativePathPosix(self): self.filesystem.is_windows_fs = False - self.filesystem.CreateFile('/a/b/file_one') - self.filesystem.CreateFile('/a/c/file_two') - self.assertTrue(self.filesystem.Exists('a/b/../c/file_two')) - self.assertTrue(self.filesystem.Exists('/a/c/../b/file_one')) - self.assertTrue(self.filesystem.Exists('/a/c/../../a/b/file_one')) - self.assertFalse(self.filesystem.Exists('a/b/../z/d')) - self.assertFalse(self.filesystem.Exists('a/b/../z/../c/file_two')) + self.filesystem.create_file('/a/b/file_one') + self.filesystem.create_file('/a/c/file_two') + self.assertTrue(self.filesystem.exists('a/b/../c/file_two')) + self.assertTrue(self.filesystem.exists('/a/c/../b/file_one')) + self.assertTrue(self.filesystem.exists('/a/c/../../a/b/file_one')) + self.assertFalse(self.filesystem.exists('a/b/../z/d')) + self.assertFalse(self.filesystem.exists('a/b/../z/../c/file_two')) self.filesystem.cwd = '/a/c' - self.assertTrue(self.filesystem.Exists('../b/file_one')) - self.assertTrue(self.filesystem.Exists('../../a/b/file_one')) - self.assertTrue(self.filesystem.Exists('../../a/b/../../a/c/file_two')) - self.assertFalse(self.filesystem.Exists('../z/file_one')) - self.assertFalse(self.filesystem.Exists('../z/../c/file_two')) + self.assertTrue(self.filesystem.exists('../b/file_one')) + self.assertTrue(self.filesystem.exists('../../a/b/file_one')) + self.assertTrue(self.filesystem.exists('../../a/b/../../a/c/file_two')) + self.assertFalse(self.filesystem.exists('../z/file_one')) + self.assertFalse(self.filesystem.exists('../z/../c/file_two')) def testExistsRelativePathWindows(self): self.filesystem.is_windows_fs = True @@ -566,42 +572,42 @@ def testExistsRelativePathWindows(self): self.assertTrue(self.filesystem.Exists('../z/../c/file_two')) def testGetObjectFromRoot(self): - self.filesystem.AddObject(self.root_name, self.fake_file) - self.assertEqual(self.fake_file, self.filesystem.GetObject('foobar')) + self.filesystem.add_object(self.root_name, self.fake_file) + self.assertEqual(self.fake_file, self.filesystem.get_object('foobar')) def testGetNonexistentObjectFromRootError(self): - self.filesystem.AddObject(self.root_name, self.fake_file) - self.assertEqual(self.fake_file, self.filesystem.GetObject('foobar')) - self.assertRaisesIOError(errno.ENOENT, self.filesystem.GetObject, - 'some_bogus_filename') + self.filesystem.add_object(self.root_name, self.fake_file) + self.assertEqual(self.fake_file, self.filesystem.get_object('foobar')) + self.assertRaisesIOError( + errno.ENOENT, self.filesystem.get_object, 'some_bogus_filename') def testRemoveObjectFromRoot(self): - self.filesystem.AddObject(self.root_name, self.fake_file) - self.filesystem.RemoveObject(self.fake_file.name) - self.assertRaisesIOError(errno.ENOENT, self.filesystem.GetObject, - self.fake_file.name) + self.filesystem.add_object(self.root_name, self.fake_file) + self.filesystem.remove_object(self.fake_file.name) + self.assertRaisesIOError( + errno.ENOENT, self.filesystem.get_object, self.fake_file.name) def testRemoveNonexistenObjectFromRootError(self): - self.assertRaisesIOError(errno.ENOENT, self.filesystem.RemoveObject, - 'some_bogus_filename') + self.assertRaisesIOError( + errno.ENOENT, self.filesystem.remove_object, 'some_bogus_filename') def testExistsRemovedFile(self): - self.filesystem.AddObject(self.root_name, self.fake_file) - self.filesystem.RemoveObject(self.fake_file.name) - self.assertFalse(self.filesystem.Exists(self.fake_file.name)) + self.filesystem.add_object(self.root_name, self.fake_file) + self.filesystem.remove_object(self.fake_file.name) + self.assertFalse(self.filesystem.exists(self.fake_file.name)) def testAddObjectToChild(self): - self.filesystem.AddObject(self.root_name, self.fake_child) - self.filesystem.AddObject(self.fake_child.name, self.fake_file) + self.filesystem.add_object(self.root_name, self.fake_child) + self.filesystem.add_object(self.fake_child.name, self.fake_file) self.assertEqual( {self.fake_file.name: self.fake_file}, - self.filesystem.root.GetEntry(self.fake_child.name).contents) + self.filesystem.root.get_entry(self.fake_child.name).contents) def testAddObjectToRegularFileErrorPosix(self): self.filesystem.is_windows_fs = False - self.filesystem.AddObject(self.root_name, self.fake_file) + self.filesystem.add_object(self.root_name, self.fake_file) self.assertRaisesOSError(errno.ENOTDIR, - self.filesystem.AddObject, + self.filesystem.add_object, self.fake_file.name, self.fake_file) def testAddObjectToRegularFileErrorWindows(self): @@ -612,168 +618,167 @@ def testAddObjectToRegularFileErrorWindows(self): self.fake_file.name, self.fake_file) def testExistsFileAddedToChild(self): - self.filesystem.AddObject(self.root_name, self.fake_child) - self.filesystem.AddObject(self.fake_child.name, self.fake_file) - path = self.filesystem.JoinPaths(self.fake_child.name, + self.filesystem.add_object(self.root_name, self.fake_child) + self.filesystem.add_object(self.fake_child.name, self.fake_file) + path = self.filesystem.joinpaths(self.fake_child.name, self.fake_file.name) - self.assertTrue(self.filesystem.Exists(path)) + self.assertTrue(self.filesystem.exists(path)) def testGetObjectFromChild(self): - self.filesystem.AddObject(self.root_name, self.fake_child) - self.filesystem.AddObject(self.fake_child.name, self.fake_file) + self.filesystem.add_object(self.root_name, self.fake_child) + self.filesystem.add_object(self.fake_child.name, self.fake_file) self.assertEqual(self.fake_file, - self.filesystem.GetObject( - self.filesystem.JoinPaths(self.fake_child.name, + self.filesystem.get_object( + self.filesystem.joinpaths(self.fake_child.name, self.fake_file.name))) def testGetNonexistentObjectFromChildError(self): - self.filesystem.AddObject(self.root_name, self.fake_child) - self.filesystem.AddObject(self.fake_child.name, self.fake_file) - self.assertRaisesIOError(errno.ENOENT, self.filesystem.GetObject, - self.filesystem.JoinPaths( + self.filesystem.add_object(self.root_name, self.fake_child) + self.filesystem.add_object(self.fake_child.name, self.fake_file) + self.assertRaisesIOError(errno.ENOENT, self.filesystem.get_object, + self.filesystem.joinpaths( self.fake_child.name, 'some_bogus_filename')) def testRemoveObjectFromChild(self): - self.filesystem.AddObject(self.root_name, self.fake_child) - self.filesystem.AddObject(self.fake_child.name, self.fake_file) - target_path = self.filesystem.JoinPaths(self.fake_child.name, + self.filesystem.add_object(self.root_name, self.fake_child) + self.filesystem.add_object(self.fake_child.name, self.fake_file) + target_path = self.filesystem.joinpaths(self.fake_child.name, self.fake_file.name) - self.filesystem.RemoveObject(target_path) - self.assertRaisesIOError(errno.ENOENT, self.filesystem.GetObject, + self.filesystem.remove_object(target_path) + self.assertRaisesIOError(errno.ENOENT, self.filesystem.get_object, target_path) def testRemoveObjectFromChildError(self): - self.filesystem.AddObject(self.root_name, self.fake_child) - self.assertRaisesIOError(errno.ENOENT, self.filesystem.RemoveObject, - self.filesystem.JoinPaths( + self.filesystem.add_object(self.root_name, self.fake_child) + self.assertRaisesIOError(errno.ENOENT, self.filesystem.remove_object, + self.filesystem.joinpaths( self.fake_child.name, 'some_bogus_filename')) def testRemoveObjectFromNonDirectoryError(self): - self.filesystem.AddObject(self.root_name, self.fake_file) - self.assertRaisesIOError(errno.ENOTDIR, self.filesystem.RemoveObject, - self.filesystem.JoinPaths( + self.filesystem.add_object(self.root_name, self.fake_file) + self.assertRaisesIOError(errno.ENOTDIR, self.filesystem.remove_object, + self.filesystem.joinpaths( '%s' % self.fake_file.name, 'file_does_not_matter_since_parent_not_a_directory')) def testExistsFileRemovedFromChild(self): - self.filesystem.AddObject(self.root_name, self.fake_child) - self.filesystem.AddObject(self.fake_child.name, self.fake_file) - path = self.filesystem.JoinPaths(self.fake_child.name, + self.filesystem.add_object(self.root_name, self.fake_child) + self.filesystem.add_object(self.fake_child.name, self.fake_file) + path = self.filesystem.joinpaths(self.fake_child.name, self.fake_file.name) - self.filesystem.RemoveObject(path) - self.assertFalse(self.filesystem.Exists(path)) + self.filesystem.remove_object(path) + self.assertFalse(self.filesystem.exists(path)) def testOperateOnGrandchildDirectory(self): - self.filesystem.AddObject(self.root_name, self.fake_child) - self.filesystem.AddObject(self.fake_child.name, self.fake_grandchild) - grandchild_directory = self.filesystem.JoinPaths(self.fake_child.name, + self.filesystem.add_object(self.root_name, self.fake_child) + self.filesystem.add_object(self.fake_child.name, self.fake_grandchild) + grandchild_directory = self.filesystem.joinpaths(self.fake_child.name, self.fake_grandchild.name) - grandchild_file = self.filesystem.JoinPaths(grandchild_directory, + grandchild_file = self.filesystem.joinpaths(grandchild_directory, self.fake_file.name) - self.assertRaises(IOError, self.filesystem.GetObject, grandchild_file) - self.filesystem.AddObject(grandchild_directory, self.fake_file) + self.assertRaises(IOError, self.filesystem.get_object, grandchild_file) + self.filesystem.add_object(grandchild_directory, self.fake_file) self.assertEqual(self.fake_file, - self.filesystem.GetObject(grandchild_file)) - self.assertTrue(self.filesystem.Exists(grandchild_file)) - self.filesystem.RemoveObject(grandchild_file) - self.assertRaises(IOError, self.filesystem.GetObject, grandchild_file) - self.assertFalse(self.filesystem.Exists(grandchild_file)) + self.filesystem.get_object(grandchild_file)) + self.assertTrue(self.filesystem.exists(grandchild_file)) + self.filesystem.remove_object(grandchild_file) + self.assertRaises(IOError, self.filesystem.get_object, grandchild_file) + self.assertFalse(self.filesystem.exists(grandchild_file)) def testCreateDirectoryInRootDirectory(self): path = 'foo' - self.filesystem.CreateDirectory(path) - new_dir = self.filesystem.GetObject(path) + self.filesystem.create_dir(path) + new_dir = self.filesystem.get_object(path) self.assertEqual(os.path.basename(path), new_dir.name) self.assertTrue(stat.S_IFDIR & new_dir.st_mode) def testCreateDirectoryInRootDirectoryAlreadyExistsError(self): path = 'foo' - self.filesystem.CreateDirectory(path) - self.assertRaisesOSError(errno.EEXIST, self.filesystem.CreateDirectory, - path) + self.filesystem.create_dir(path) + self.assertRaisesOSError( + errno.EEXIST, self.filesystem.create_dir, path) def testCreateDirectory(self): path = 'foo/bar/baz' - self.filesystem.CreateDirectory(path) - new_dir = self.filesystem.GetObject(path) + self.filesystem.create_dir(path) + new_dir = self.filesystem.get_object(path) self.assertEqual(os.path.basename(path), new_dir.name) self.assertTrue(stat.S_IFDIR & new_dir.st_mode) # Create second directory to make sure first is OK. path = '%s/quux' % path - self.filesystem.CreateDirectory(path) - new_dir = self.filesystem.GetObject(path) + self.filesystem.create_dir(path) + new_dir = self.filesystem.get_object(path) self.assertEqual(os.path.basename(path), new_dir.name) self.assertTrue(stat.S_IFDIR & new_dir.st_mode) def testCreateDirectoryAlreadyExistsError(self): path = 'foo/bar/baz' - self.filesystem.CreateDirectory(path) - self.assertRaisesOSError(errno.EEXIST, self.filesystem.CreateDirectory, - path) + self.filesystem.create_dir(path) + self.assertRaisesOSError( + errno.EEXIST, self.filesystem.create_dir, path) def testCreateFileInReadOnlyDirectoryRaisesInPosix(self): self.filesystem.is_windows_fs = False dir_path = '/foo/bar' - self.filesystem.CreateDirectory(dir_path, perm_bits=0o555) + self.filesystem.create_dir(dir_path, perm_bits=0o555) file_path = dir_path + '/baz' if sys.version_info[0] < 3: - self.assertRaisesIOError(errno.EACCES, self.filesystem.CreateFile, + self.assertRaisesIOError(errno.EACCES, self.filesystem.create_file, file_path) else: - self.assertRaisesOSError(errno.EACCES, self.filesystem.CreateFile, + self.assertRaisesOSError(errno.EACCES, self.filesystem.create_file, file_path) - def testCreateFileInReadOnlyDirectoryPossibleInWindows(self): self.filesystem.is_windows_fs = True dir_path = 'C:/foo/bar' - self.filesystem.CreateDirectory(dir_path, perm_bits=0o555) + self.filesystem.create_dir(dir_path, perm_bits=0o555) file_path = dir_path + '/baz' - self.filesystem.CreateFile(file_path) - self.assertTrue(self.filesystem.Exists(file_path)) + self.filesystem.create_file(file_path) + self.assertTrue(self.filesystem.exists(file_path)) def testCreateFileInCurrentDirectory(self): path = 'foo' contents = 'dummy data' - self.filesystem.CreateFile(path, contents=contents) - self.assertTrue(self.filesystem.Exists(path)) - self.assertFalse(self.filesystem.Exists(os.path.dirname(path))) + self.filesystem.create_file(path, contents=contents) + self.assertTrue(self.filesystem.exists(path)) + self.assertFalse(self.filesystem.exists(os.path.dirname(path))) path = './%s' % path - self.assertTrue(self.filesystem.Exists(os.path.dirname(path))) + self.assertTrue(self.filesystem.exists(os.path.dirname(path))) def testCreateFileInRootDirectory(self): path = '/foo' contents = 'dummy data' - self.filesystem.CreateFile(path, contents=contents) - new_file = self.filesystem.GetObject(path) - self.assertTrue(self.filesystem.Exists(path)) - self.assertTrue(self.filesystem.Exists(os.path.dirname(path))) + self.filesystem.create_file(path, contents=contents) + new_file = self.filesystem.get_object(path) + self.assertTrue(self.filesystem.exists(path)) + self.assertTrue(self.filesystem.exists(os.path.dirname(path))) self.assertEqual(os.path.basename(path), new_file.name) self.assertTrue(stat.S_IFREG & new_file.st_mode) self.assertEqual(contents, new_file.contents) def testCreateFileWithSizeButNoContentCreatesLargeFile(self): path = 'large_foo_bar' - self.filesystem.CreateFile(path, st_size=100000000) - new_file = self.filesystem.GetObject(path) + self.filesystem.create_file(path, st_size=100000000) + new_file = self.filesystem.get_object(path) self.assertEqual(None, new_file.contents) self.assertEqual(100000000, new_file.st_size) def testCreateFileInRootDirectoryAlreadyExistsError(self): path = 'foo' - self.filesystem.CreateFile(path) - self.assertRaisesOSError(errno.EEXIST, self.filesystem.CreateFile, - path) + self.filesystem.create_file(path) + self.assertRaisesOSError( + errno.EEXIST, self.filesystem.create_file, path) def testCreateFile(self): path = 'foo/bar/baz' - retval = self.filesystem.CreateFile(path, contents='dummy_data') - self.assertTrue(self.filesystem.Exists(path)) - self.assertTrue(self.filesystem.Exists(os.path.dirname(path))) - new_file = self.filesystem.GetObject(path) + retval = self.filesystem.create_file(path, contents='dummy_data') + self.assertTrue(self.filesystem.exists(path)) + self.assertTrue(self.filesystem.exists(os.path.dirname(path))) + new_file = self.filesystem.get_object(path) self.assertEqual(os.path.basename(path), new_file.name) self.assertTrue(stat.S_IFREG & new_file.st_mode) self.assertEqual(new_file, retval) @@ -783,26 +788,26 @@ def testCreateFileWithIncorrectModeType(self): def testCreateFileAlreadyExistsError(self): path = 'foo/bar/baz' - self.filesystem.CreateFile(path, contents='dummy_data') - self.assertRaisesOSError(errno.EEXIST, self.filesystem.CreateFile, - path) + self.filesystem.create_file(path, contents='dummy_data') + self.assertRaisesOSError( + errno.EEXIST, self.filesystem.create_file, path) @unittest.skipIf(TestCase.is_windows and sys.version_info < (3, 3), 'Links are not supported under Windows before Python 3.3') def testCreateLink(self): path = 'foo/bar/baz' target_path = 'foo/bar/quux' - new_file = self.filesystem.CreateLink(path, 'quux') + new_file = self.filesystem.create_symlink(path, 'quux') # Neither the path not the final target exists before we actually write to # one of them, even though the link appears in the file system. - self.assertFalse(self.filesystem.Exists(path)) - self.assertFalse(self.filesystem.Exists(target_path)) + self.assertFalse(self.filesystem.exists(path)) + self.assertFalse(self.filesystem.exists(target_path)) self.assertTrue(stat.S_IFLNK & new_file.st_mode) # but once we write the linked to file, they both will exist. - self.filesystem.CreateFile(target_path) - self.assertTrue(self.filesystem.Exists(path)) - self.assertTrue(self.filesystem.Exists(target_path)) + self.filesystem.create_file(target_path) + self.assertTrue(self.filesystem.exists(path)) + self.assertTrue(self.filesystem.exists(target_path)) @unittest.skipIf(TestCase.is_windows and sys.version_info < (3, 3), 'Links are not supported under Windows before Python 3.3') @@ -810,10 +815,10 @@ def testResolveObject(self): target_path = 'dir/target' target_contents = '0123456789ABCDEF' link_name = 'x' - self.filesystem.CreateDirectory('dir') - self.filesystem.CreateFile('dir/target', contents=target_contents) - self.filesystem.CreateLink(link_name, target_path) - obj = self.filesystem.ResolveObject(link_name) + self.filesystem.create_dir('dir') + self.filesystem.create_file('dir/target', contents=target_contents) + self.filesystem.create_symlink(link_name, target_path) + obj = self.filesystem.resolve(link_name) self.assertEqual('target', obj.name) self.assertEqual(target_contents, obj.contents) @@ -823,10 +828,10 @@ def checkLresolveObject(self): target_path = 'dir/target' target_contents = '0123456789ABCDEF' link_name = 'x' - self.filesystem.CreateDirectory('dir') - self.filesystem.CreateFile('dir/target', contents=target_contents) - self.filesystem.CreateLink(link_name, target_path) - obj = self.filesystem.LResolveObject(link_name) + self.filesystem.create_dir('dir') + self.filesystem.create_file('dir/target', contents=target_contents) + self.filesystem.create_symlink(link_name, target_path) + obj = self.filesystem.lresolve(link_name) self.assertEqual(link_name, obj.name) self.assertEqual(target_path, obj.contents) @@ -841,16 +846,11 @@ def testLresolveObjectPosix(self): self.checkLresolveObject() def checkDirectoryAccessOnFile(self, error_subtype): - self.filesystem.CreateFile('not_a_dir') - self.assertRaisesIOError(error_subtype, self.filesystem.ResolveObject, - 'not_a_dir/foo') - self.assertRaisesIOError(error_subtype, self.filesystem.ResolveObject, - 'not_a_dir/foo/bar') - self.assertRaisesIOError(error_subtype, self.filesystem.LResolveObject, - 'not_a_dir/foo') - self.assertRaisesIOError(error_subtype, - self.filesystem.LResolveObject, - 'not_a_dir/foo/bar') + self.filesystem.create_file('not_a_dir') + self.assertRaisesIOError( + error_subtype, self.filesystem.resolve, 'not_a_dir/foo') + self.assertRaisesIOError( + error_subtype, self.filesystem.lresolve, 'not_a_dir/foo/bar') def testDirectoryAccessOnFileWindows(self): self.filesystem.is_windows_fs = True @@ -869,49 +869,49 @@ def setUp(self): self.path = self.os.path def testGetObject(self): - self.filesystem.CreateDirectory('/foo/bar') - self.filesystem.CreateFile('/foo/bar/baz') - self.assertTrue(self.filesystem.GetObject('/Foo/Bar/Baz')) + self.filesystem.create_dir('/foo/bar') + self.filesystem.create_file('/foo/bar/baz') + self.assertTrue(self.filesystem.get_object('/Foo/Bar/Baz')) def testRemoveObject(self): - self.filesystem.CreateDirectory('/foo/bar') - self.filesystem.CreateFile('/foo/bar/baz') - self.filesystem.RemoveObject('/Foo/Bar/Baz') - self.assertFalse(self.filesystem.Exists('/foo/bar/baz')) + self.filesystem.create_dir('/foo/bar') + self.filesystem.create_file('/foo/bar/baz') + self.filesystem.remove_object('/Foo/Bar/Baz') + self.assertFalse(self.filesystem.exists('/foo/bar/baz')) def testExists(self): - self.filesystem.CreateDirectory('/Foo/Bar') - self.assertTrue(self.filesystem.Exists('/Foo/Bar')) - self.assertTrue(self.filesystem.Exists('/foo/bar')) + self.filesystem.create_dir('/Foo/Bar') + self.assertTrue(self.filesystem.exists('/Foo/Bar')) + self.assertTrue(self.filesystem.exists('/foo/bar')) - self.filesystem.CreateFile('/foo/Bar/baz') - self.assertTrue(self.filesystem.Exists('/Foo/bar/BAZ')) - self.assertTrue(self.filesystem.Exists('/foo/bar/baz')) + self.filesystem.create_file('/foo/Bar/baz') + self.assertTrue(self.filesystem.exists('/Foo/bar/BAZ')) + self.assertTrue(self.filesystem.exists('/foo/bar/baz')) def testCreateDirectoryWithDifferentCaseRoot(self): - self.filesystem.CreateDirectory('/Foo/Bar') - self.filesystem.CreateDirectory('/foo/bar/baz') - dir1 = self.filesystem.GetObject('/Foo/Bar') - dir2 = self.filesystem.GetObject('/foo/bar') + self.filesystem.create_dir('/Foo/Bar') + self.filesystem.create_dir('/foo/bar/baz') + dir1 = self.filesystem.get_object('/Foo/Bar') + dir2 = self.filesystem.get_object('/foo/bar') self.assertEqual(dir1, dir2) def testCreateFileWithDifferentCaseDir(self): - self.filesystem.CreateDirectory('/Foo/Bar') - self.filesystem.CreateFile('/foo/bar/baz') - dir1 = self.filesystem.GetObject('/Foo/Bar') - dir2 = self.filesystem.GetObject('/foo/bar') + self.filesystem.create_dir('/Foo/Bar') + self.filesystem.create_file('/foo/bar/baz') + dir1 = self.filesystem.get_object('/Foo/Bar') + dir2 = self.filesystem.get_object('/foo/bar') self.assertEqual(dir1, dir2) @unittest.skipIf(TestCase.is_windows and sys.version_info < (3, 3), 'Links are not supported under Windows before Python 3.3') def testResolvePath(self): - self.filesystem.CreateDirectory('/foo/baz') - self.filesystem.CreateLink('/Foo/Bar', './baz/bip') + self.filesystem.create_dir('/foo/baz') + self.filesystem.create_symlink('/Foo/Bar', './baz/bip') self.assertEqual('/foo/baz/bip', - self.filesystem.ResolvePath('/foo/bar')) + self.filesystem.resolve_path('/foo/bar')) def testIsdirIsfile(self): - self.filesystem.CreateFile('foo/bar') + self.filesystem.create_file('foo/bar') self.assertTrue(self.path.isdir('Foo')) self.assertFalse(self.path.isfile('Foo')) self.assertTrue(self.path.isfile('Foo/Bar')) @@ -919,26 +919,26 @@ def testIsdirIsfile(self): def testGetsize(self): file_path = 'foo/bar/baz' - self.filesystem.CreateFile(file_path, contents='1234567') + self.filesystem.create_file(file_path, contents='1234567') self.assertEqual(7, self.path.getsize('FOO/BAR/BAZ')) def testGetsizeWithLoopingSymlink(self): self.filesystem.is_windows_fs = False dir_path = '/foo/bar' - self.filesystem.CreateDirectory(dir_path) + self.filesystem.create_dir(dir_path) link_path = dir_path + "/link" link_target = link_path + "/link" self.os.symlink(link_target, link_path) self.assertRaisesOSError(errno.ELOOP, self.os.path.getsize, link_path) def testGetMtime(self): - test_file = self.filesystem.CreateFile('foo/bar1.txt') - test_file.SetMTime(24) + test_file = self.filesystem.create_file('foo/bar1.txt') + test_file.st_mtime = 24 self.assertEqual(24, self.path.getmtime('Foo/Bar1.TXT')) def testGetObjectWithFileSize(self): - self.filesystem.CreateFile('/Foo/Bar', st_size=10) - self.assertTrue(self.filesystem.GetObject('/foo/bar')) + self.filesystem.create_file('/Foo/Bar', st_size=10) + self.assertTrue(self.filesystem.get_object('/foo/bar')) class CaseSensitiveFakeFilesystemTest(TestCase): @@ -949,42 +949,42 @@ def setUp(self): self.path = self.os.path def testGetObject(self): - self.filesystem.CreateDirectory('/foo/bar') - self.filesystem.CreateFile('/foo/bar/baz') - self.assertRaises(IOError, self.filesystem.GetObject, '/Foo/Bar/Baz') + self.filesystem.create_dir('/foo/bar') + self.filesystem.create_file('/foo/bar/baz') + self.assertRaises(IOError, self.filesystem.get_object, '/Foo/Bar/Baz') def testRemoveObject(self): - self.filesystem.CreateDirectory('/foo/bar') - self.filesystem.CreateFile('/foo/bar/baz') - self.assertRaises(IOError, self.filesystem.RemoveObject, - '/Foo/Bar/Baz') - self.assertTrue(self.filesystem.Exists('/foo/bar/baz')) + self.filesystem.create_dir('/foo/bar') + self.filesystem.create_file('/foo/bar/baz') + self.assertRaises( + IOError, self.filesystem.remove_object, '/Foo/Bar/Baz') + self.assertTrue(self.filesystem.exists('/foo/bar/baz')) def testExists(self): - self.filesystem.CreateDirectory('/Foo/Bar') - self.assertTrue(self.filesystem.Exists('/Foo/Bar')) - self.assertFalse(self.filesystem.Exists('/foo/bar')) + self.filesystem.create_dir('/Foo/Bar') + self.assertTrue(self.filesystem.exists('/Foo/Bar')) + self.assertFalse(self.filesystem.exists('/foo/bar')) - self.filesystem.CreateFile('/foo/Bar/baz') - self.assertFalse(self.filesystem.Exists('/Foo/bar/BAZ')) - self.assertFalse(self.filesystem.Exists('/foo/bar/baz')) + self.filesystem.create_file('/foo/Bar/baz') + self.assertFalse(self.filesystem.exists('/Foo/bar/BAZ')) + self.assertFalse(self.filesystem.exists('/foo/bar/baz')) def testCreateDirectoryWithDifferentCaseRoot(self): - self.filesystem.CreateDirectory('/Foo/Bar') - self.filesystem.CreateDirectory('/foo/bar/baz') - dir1 = self.filesystem.GetObject('/Foo/Bar') - dir2 = self.filesystem.GetObject('/foo/bar') + self.filesystem.create_dir('/Foo/Bar') + self.filesystem.create_dir('/foo/bar/baz') + dir1 = self.filesystem.get_object('/Foo/Bar') + dir2 = self.filesystem.get_object('/foo/bar') self.assertNotEqual(dir1, dir2) def testCreateFileWithDifferentCaseDir(self): - self.filesystem.CreateDirectory('/Foo/Bar') - self.filesystem.CreateFile('/foo/bar/baz') - dir1 = self.filesystem.GetObject('/Foo/Bar') - dir2 = self.filesystem.GetObject('/foo/bar') + self.filesystem.create_dir('/Foo/Bar') + self.filesystem.create_file('/foo/bar/baz') + dir1 = self.filesystem.get_object('/Foo/Bar') + dir2 = self.filesystem.get_object('/foo/bar') self.assertNotEqual(dir1, dir2) def testIsdirIsfile(self): - self.filesystem.CreateFile('foo/bar') + self.filesystem.create_file('foo/bar') self.assertFalse(self.path.isdir('Foo')) self.assertFalse(self.path.isfile('Foo')) self.assertFalse(self.path.isfile('Foo/Bar')) @@ -992,14 +992,14 @@ def testIsdirIsfile(self): def testGetsize(self): file_path = 'foo/bar/baz' - self.filesystem.CreateFile(file_path, contents='1234567') + self.filesystem.create_file(file_path, contents='1234567') self.assertRaises(os.error, self.path.getsize, 'FOO/BAR/BAZ') def testGetMtime(self): - test_file = self.filesystem.CreateFile('foo/bar1.txt') - test_file.SetMTime(24) - self.assertRaisesOSError(errno.ENOENT, self.path.getmtime, - 'Foo/Bar1.TXT') + test_file = self.filesystem.create_file('foo/bar1.txt') + test_file.st_mtime = 24 + self.assertRaisesOSError( + errno.ENOENT, self.path.getmtime, 'Foo/Bar1.TXT') class FakeOsModuleTestBase(RealFsTestCase): @@ -1062,7 +1062,7 @@ def testBackwardsChdir(self): rootdir = self.os.getcwd() dirname = 'foo' abs_dirname = self.os.path.abspath(dirname) - self.filesystem.CreateDirectory(dirname) + self.filesystem.create_dir(dirname) self.os.chdir(dirname) self.assertEqual(abs_dirname, self.os.getcwd()) self.os.chdir('..') @@ -1791,7 +1791,7 @@ def testRenameToAnotherDeviceShouldRaise(self): self.filesystem.AddMountPoint('/mount') old_path = '/foo/bar' new_path = '/mount/bar' - self.filesystem.CreateFile(old_path) + self.filesystem.create_file(old_path) self.assertRaisesOSError(errno.EXDEV, self.os.rename, old_path, new_path) @@ -1921,7 +1921,7 @@ def testRenamePreservesStat(self): new_file = self.filesystem.GetObject(new_file_path) self.assertNotEqual(new_file.st_mtime, old_file.st_mtime) self.os.rename(old_file_path, new_file_path) - new_file = self.filesystem.GetObject(new_file_path) + new_file = self.filesystem.get_object(new_file_path) self.assertEqual(new_file.st_mtime, old_file.st_mtime) self.assertEqual(new_file.st_mode, old_file.st_mode) self.assertEqual(new_file.st_uid, old_file.st_uid) @@ -2094,13 +2094,13 @@ def testMkdir(self): """mkdir can create a relative directory.""" self.skipRealFs() directory = 'xyzzy' - self.assertFalse(self.filesystem.Exists(directory)) + self.assertFalse(self.filesystem.exists(directory)) self.os.mkdir(directory) - self.assertTrue(self.filesystem.Exists('/%s' % directory)) + self.assertTrue(self.filesystem.exists('/%s' % directory)) self.os.chdir(directory) self.os.mkdir(directory) self.assertTrue( - self.filesystem.Exists('/%s/%s' % (directory, directory))) + self.filesystem.exists('/%s/%s' % (directory, directory))) self.os.chdir(directory) self.os.mkdir('../abccb') self.assertTrue(self.os.path.exists('/%s/abccb' % directory)) @@ -4021,7 +4021,7 @@ def testUtimeFollowSymlinks(self): path = self.makePath('some_file') self.createTestFile(path) link_path = '/link_to_some_file' - self.filesystem.CreateLink(link_path, path) + self.filesystem.create_symlink(link_path, path) self.os.utime(link_path, (1, 2)) st = self.os.stat(link_path) @@ -4034,7 +4034,7 @@ def testUtimeNoFollowSymlinks(self): path = self.makePath('some_file') self.createTestFile(path) link_path = '/link_to_some_file' - self.filesystem.CreateLink(link_path, path) + self.filesystem.create_symlink(link_path, path) self.os.utime(link_path, (1, 2), follow_symlinks=False) st = self.os.stat(link_path) @@ -4075,7 +4075,7 @@ def testUtimeSetsSpecifiedTimeInNs(self): @unittest.skipIf(sys.version_info < (3, 3), 'ns new in Python 3.3') def testUtimeIncorrectNsArgumentRaises(self): file_path = 'some_file' - self.filesystem.CreateFile(file_path) + self.filesystem.create_file(file_path) self.assertRaises(TypeError, self.os.utime, file_path, ns=(200000000)) self.assertRaises(TypeError, self.os.utime, file_path, ns=('a', 'b')) @@ -4681,9 +4681,9 @@ def setUp(self): super(FakeOsModuleDirFdTest, self).setUp() self.os.supports_dir_fd = set() self.filesystem.is_windows_fs = False - self.filesystem.CreateDirectory('/foo/bar') + self.filesystem.create_dir('/foo/bar') self.dir_fd = self.os.open('/foo', os.O_RDONLY) - self.filesystem.CreateFile('/foo/baz') + self.filesystem.create_file('/foo/baz') def testAccess(self): self.assertRaises( @@ -4731,8 +4731,8 @@ def testSymlink(self): self.assertTrue(self.os.path.exists('/bat')) def testReadlink(self): - self.filesystem.CreateLink('/meyer/lemon/pie', '/foo/baz') - self.filesystem.CreateLink('/geo/metro', '/meyer') + self.filesystem.create_symlink('/meyer/lemon/pie', '/foo/baz') + self.filesystem.create_symlink('/geo/metro', '/meyer') self.assertRaises( NotImplementedError, self.os.readlink, '/geo/metro/lemon/pie', dir_fd=self.dir_fd) @@ -4960,45 +4960,45 @@ def testFileSizeUpdatedViaClose(self): self.os.mkdir(file_dir) fh = self.open(file_path, 'w') self.assertEqual(0, self.os.stat(file_path)[stat.ST_SIZE]) - self.assertEqual('', self.filesystem.GetObject(file_path).contents) + self.assertEqual('', self.filesystem.get_object(file_path).contents) fh.write(content) self.assertEqual(0, self.os.stat(file_path)[stat.ST_SIZE]) - self.assertEqual('', self.filesystem.GetObject(file_path).contents) + self.assertEqual('', self.filesystem.get_object(file_path).contents) fh.close() self.assertEqual(len(content), self.os.stat(file_path)[stat.ST_SIZE]) self.assertEqual(content, - self.filesystem.GetObject(file_path).contents) + self.filesystem.get_object(file_path).contents) def testFileSizeNotResetAfterClose(self): file_dir = 'xyzzy' file_path = 'xyzzy/close' self.os.mkdir(file_dir) size = 1234 - # The file has size, but no content. When the file is opened - # for reading, its size should be preserved. - self.filesystem.CreateFile(file_path, st_size=size) + # The file has size, but no content. When the file is opened for reading, + # its size should be preserved. + self.filesystem.create_file(file_path, st_size=size) fh = self.open(file_path, 'r') fh.close() - self.assertEqual(size, self.open(file_path, 'r').Size()) + self.assertEqual(size, self.open(file_path, 'r').size()) def testFileSizeAfterWrite(self): file_path = 'test_file' original_content = 'abcdef' original_size = len(original_content) - self.filesystem.CreateFile(file_path, contents=original_content) + self.filesystem.create_file(file_path, contents=original_content) added_content = 'foo bar' expected_size = original_size + len(added_content) fh = self.open(file_path, 'a') fh.write(added_content) - self.assertEqual(original_size, fh.Size()) + self.assertEqual(original_size, fh.size()) fh.close() - self.assertEqual(expected_size, self.open(file_path, 'r').Size()) + self.assertEqual(expected_size, self.open(file_path, 'r').size()) def testLargeFileSizeAfterWrite(self): file_path = 'test_file' original_content = 'abcdef' original_size = len(original_content) - self.filesystem.CreateFile(file_path, st_size=original_size) + self.filesystem.create_file(file_path, st_size=original_size) added_content = 'foo bar' fh = self.open(file_path, 'a') self.assertRaises(fake_filesystem.FakeLargeFileIoException, @@ -5013,18 +5013,18 @@ def testFileSizeUpdatedViaFlush(self): self.os.mkdir(file_dir) fh = self.open(file_path, 'w') self.assertEqual(0, self.os.stat(file_path)[stat.ST_SIZE]) - self.assertEqual('', self.filesystem.GetObject(file_path).contents) + self.assertEqual('', self.filesystem.get_object(file_path).contents) fh.write(content) self.assertEqual(0, self.os.stat(file_path)[stat.ST_SIZE]) - self.assertEqual('', self.filesystem.GetObject(file_path).contents) + self.assertEqual('', self.filesystem.get_object(file_path).contents) fh.flush() self.assertEqual(len(content), self.os.stat(file_path)[stat.ST_SIZE]) self.assertEqual(content, - self.filesystem.GetObject(file_path).contents) + self.filesystem.get_object(file_path).contents) fh.close() self.assertEqual(len(content), self.os.stat(file_path)[stat.ST_SIZE]) self.assertEqual(content, - self.filesystem.GetObject(file_path).contents) + self.filesystem.get_object(file_path).contents) def testFileSizeTruncation(self): """test that file size gets updated via open().""" @@ -5039,12 +5039,12 @@ def testFileSizeTruncation(self): fh.close() self.assertEqual(len(content), self.os.stat(file_path)[stat.ST_SIZE]) self.assertEqual(content, - self.filesystem.GetObject(file_path).contents) + self.filesystem.get_object(file_path).contents) # test file truncation fh = self.open(file_path, 'w') self.assertEqual(0, self.os.stat(file_path)[stat.ST_SIZE]) - self.assertEqual('', self.filesystem.GetObject(file_path).contents) + self.assertEqual('', self.filesystem.get_object(file_path).contents) fh.close() @@ -5069,15 +5069,15 @@ def tearDown(self): def testCreateTopLevelDirectory(self): top_level_dir = '/x' - self.assertFalse(self.filesystem.Exists(top_level_dir)) - self.filesystem.CreateDirectory(top_level_dir) - self.assertTrue(self.filesystem.Exists('/')) - self.assertTrue(self.filesystem.Exists(top_level_dir)) - self.filesystem.CreateDirectory('%s/po' % top_level_dir) - self.filesystem.CreateFile('%s/po/control' % top_level_dir) - self.filesystem.CreateFile('%s/po/experiment' % top_level_dir) - self.filesystem.CreateDirectory('%s/gv' % top_level_dir) - self.filesystem.CreateFile('%s/gv/control' % top_level_dir) + self.assertFalse(self.filesystem.exists(top_level_dir)) + self.filesystem.create_dir(top_level_dir) + self.assertTrue(self.filesystem.exists('/')) + self.assertTrue(self.filesystem.exists(top_level_dir)) + self.filesystem.create_dir('%s/po' % top_level_dir) + self.filesystem.create_file('%s/po/control' % top_level_dir) + self.filesystem.create_file('%s/po/experiment' % top_level_dir) + self.filesystem.create_dir('%s/gv' % top_level_dir) + self.filesystem.create_file('%s/gv/control' % top_level_dir) expected = [ ('/', ['x'], []), @@ -5111,7 +5111,7 @@ def checkAbspath(self, is_windows): self.filesystem.is_windows_fs = is_windows filename = u'foo' abspath = u'!%s' % filename - self.filesystem.CreateFile(abspath) + self.filesystem.create_file(abspath) self.assertEqual(abspath, self.path.abspath(abspath)) self.assertEqual(abspath, self.path.abspath(filename)) self.assertEqual(abspath, self.path.abspath(u'..!%s' % filename)) @@ -5128,7 +5128,7 @@ def checkAbspathBytes(self, is_windows): self.filesystem.is_windows_fs = is_windows filename = b'foo' abspath = b'!' + filename - self.filesystem.CreateFile(abspath) + self.filesystem.create_file(abspath) self.assertEqual(abspath, self.path.abspath(abspath)) self.assertEqual(abspath, self.path.abspath(filename)) self.assertEqual(abspath, self.path.abspath(b'..!' + filename)) @@ -5148,7 +5148,7 @@ def testAbspathDealsWithRelativeNonRootPath(self): filename = '!foo!bar!baz' file_components = filename.split(self.path.sep) basedir = '!%s' % (file_components[0],) - self.filesystem.CreateFile(filename) + self.filesystem.create_file(filename) self.os.chdir(basedir) self.assertEqual(basedir, self.path.abspath(self.path.curdir)) self.assertEqual('!', self.path.abspath('..')) @@ -5186,8 +5186,8 @@ def testRelpath(self): def testRealpathVsAbspath(self): self.filesystem.is_windows_fs = False - self.filesystem.CreateFile('!george!washington!bridge') - self.filesystem.CreateLink('!first!president', '!george!washington') + self.filesystem.create_file('!george!washington!bridge') + self.filesystem.create_symlink('!first!president', '!george!washington') self.assertEqual('!first!president!bridge', self.os.path.abspath('!first!president!bridge')) self.assertEqual('!george!washington!bridge', @@ -5201,8 +5201,8 @@ def testRealpathVsAbspath(self): def testSamefile(self): file_path1 = '!foo!bar!baz' file_path2 = '!foo!bar!boo' - self.filesystem.CreateFile(file_path1) - self.filesystem.CreateFile(file_path2) + self.filesystem.create_file(file_path1) + self.filesystem.create_file(file_path2) self.assertTrue(self.path.samefile(file_path1, file_path1)) self.assertFalse(self.path.samefile(file_path1, file_path2)) self.assertTrue( @@ -5210,7 +5210,7 @@ def testSamefile(self): def testExists(self): file_path = 'foo!bar!baz' - self.filesystem.CreateFile(file_path) + self.filesystem.create_file(file_path) self.assertTrue(self.path.exists(file_path)) self.assertFalse(self.path.exists('!some!other!bogus!path')) @@ -5218,11 +5218,11 @@ def testExists(self): 'Links are not supported under Windows before Python 3.3') def testLexists(self): file_path = 'foo!bar!baz' - self.filesystem.CreateDirectory('foo!bar') - self.filesystem.CreateLink(file_path, 'bogus') + self.filesystem.create_dir('foo!bar') + self.filesystem.create_symlink(file_path, 'bogus') self.assertTrue(self.path.lexists(file_path)) self.assertFalse(self.path.exists(file_path)) - self.filesystem.CreateFile('foo!bar!bogus') + self.filesystem.create_file('foo!bar!bogus') self.assertTrue(self.path.exists(file_path)) def testDirnameWithDrive(self): @@ -5277,18 +5277,18 @@ def testGetsizePathNonexistent(self): def testGetsizeFileEmpty(self): file_path = 'foo!bar!baz' - self.filesystem.CreateFile(file_path) + self.filesystem.create_file(file_path) self.assertEqual(0, self.path.getsize(file_path)) def testGetsizeFileNonZeroSize(self): file_path = 'foo!bar!baz' - self.filesystem.CreateFile(file_path, contents='1234567') + self.filesystem.create_file(file_path, contents='1234567') self.assertEqual(7, self.path.getsize(file_path)) def testGetsizeDirEmpty(self): # For directories, only require that the size is non-negative. dir_path = 'foo!bar' - self.filesystem.CreateDirectory(dir_path) + self.filesystem.create_dir(dir_path) size = self.path.getsize(dir_path) self.assertFalse(int(size) < 0, 'expected non-negative size; actual: %s' % size) @@ -5296,19 +5296,19 @@ def testGetsizeDirEmpty(self): def testGetsizeDirNonZeroSize(self): # For directories, only require that the size is non-negative. dir_path = 'foo!bar' - self.filesystem.CreateFile(self.filesystem.JoinPaths(dir_path, 'baz')) + self.filesystem.create_file(self.filesystem.joinpaths(dir_path, 'baz')) size = self.path.getsize(dir_path) self.assertFalse(int(size) < 0, 'expected non-negative size; actual: %s' % size) def testIsdir(self): - self.filesystem.CreateFile('foo!bar') + self.filesystem.create_file('foo!bar') self.assertTrue(self.path.isdir('foo')) self.assertFalse(self.path.isdir('foo!bar')) self.assertFalse(self.path.isdir('it_dont_exist')) def testIsdirWithCwdChange(self): - self.filesystem.CreateFile('!foo!bar!baz') + self.filesystem.create_file('!foo!bar!baz') self.assertTrue(self.path.isdir('!foo')) self.assertTrue(self.path.isdir('!foo!bar')) self.assertTrue(self.path.isdir('foo')) @@ -5319,16 +5319,16 @@ def testIsdirWithCwdChange(self): self.assertTrue(self.path.isdir('bar')) def testIsfile(self): - self.filesystem.CreateFile('foo!bar') + self.filesystem.create_file('foo!bar') self.assertFalse(self.path.isfile('foo')) self.assertTrue(self.path.isfile('foo!bar')) self.assertFalse(self.path.isfile('it_dont_exist')) def testGetMtime(self): - test_file = self.filesystem.CreateFile('foo!bar1.txt') + test_file = self.filesystem.create_file('foo!bar1.txt') time.time.start() self.assertEqual(10, test_file.st_mtime) - test_file.SetMTime(24) + test_file.st_mtime = 24 self.assertEqual(24, self.path.getmtime('foo!bar1.txt')) def testGetMtimeRaisesOSError(self): @@ -5339,9 +5339,9 @@ def testGetMtimeRaisesOSError(self): @unittest.skipIf(TestCase.is_windows and sys.version_info < (3, 3), 'Links are not supported under Windows before Python 3.3') def testIslink(self): - self.filesystem.CreateDirectory('foo') - self.filesystem.CreateFile('foo!regular_file') - self.filesystem.CreateLink('foo!link_to_file', 'regular_file') + self.filesystem.create_dir('foo') + self.filesystem.create_file('foo!regular_file') + self.filesystem.create_symlink('foo!link_to_file', 'regular_file') self.assertFalse(self.path.islink('foo')) # An object can be both a link and a file or file, according to the @@ -5367,7 +5367,7 @@ def testIsmount(self): self.assertFalse(self.path.ismount('')) self.assertTrue(self.path.ismount('!')) self.assertFalse(self.path.ismount('!mount!')) - self.filesystem.AddMountPoint('!mount') + self.filesystem.add_mount_point('!mount') self.assertTrue(self.path.ismount('!mount')) self.assertTrue(self.path.ismount('!mount!')) @@ -5377,7 +5377,7 @@ def testIsmountWithDriveLetters(self): self.assertTrue(self.path.ismount('c:!')) self.assertFalse(self.path.ismount('c:')) self.assertTrue(self.path.ismount('z:!')) - self.filesystem.AddMountPoint('!mount') + self.filesystem.add_mount_point('!mount') self.assertTrue(self.path.ismount('!mount')) self.assertTrue(self.path.ismount('!mount!')) @@ -5393,7 +5393,7 @@ def testIsmountWithUncPaths(self): def testIsmountWithAlternatePathSeparator(self): self.filesystem.alternative_path_separator = '!' - self.filesystem.AddMountPoint('!mount') + self.filesystem.add_mount_point('!mount') self.assertTrue(self.path.ismount('!mount')) self.assertTrue(self.path.ismount('!mount!')) self.assertTrue(self.path.ismount('!mount!!')) @@ -5403,8 +5403,8 @@ def testIsmountWithAlternatePathSeparator(self): @unittest.skipIf(sys.version_info >= (3, 0), 'os.path.walk removed in Python 3') def testWalk(self): - self.filesystem.CreateFile('!foo!bar!baz') - self.filesystem.CreateFile('!foo!bar!xyzzy!plugh') + self.filesystem.create_file('!foo!bar!baz') + self.filesystem.create_file('!foo!bar!xyzzy!plugh') visited_nodes = [] def RecordVisitedNodes(visited, dirname, fnames): @@ -5476,8 +5476,8 @@ def testDeleteOnClose(self): self.open = fake_filesystem.FakeFileOpen(self.filesystem, delete_on_close=True) with self.open(file_path, 'w'): - self.assertTrue(self.filesystem.Exists(file_path)) - self.assertFalse(self.filesystem.Exists(file_path)) + self.assertTrue(self.filesystem.exists(file_path)) + self.assertFalse(self.filesystem.exists(file_path)) def testNoDeleteOnCloseByDefault(self): file_path = self.makePath('czar') @@ -6162,8 +6162,8 @@ def testOpenRaisesIOErrorIfParentIsFileWindows(self): def testCanReadFromBlockDevice(self): self.skipRealFs() device_path = 'device' - self.filesystem.CreateFile(device_path, stat.S_IFBLK - | fake_filesystem.PERM_ALL) + self.filesystem.create_file(device_path, stat.S_IFBLK + | fake_filesystem.PERM_ALL) with self.open(device_path, 'r') as fh: self.assertEqual('', fh.read()) @@ -6546,7 +6546,8 @@ def setUp(self): self.os = fake_filesystem.FakeOsModule(self.filesystem) self.file_path = 'some_file' self.file_contents = b'real binary contents: \x1f\x8b' - self.filesystem.CreateFile(self.file_path, contents=self.file_contents) + self.filesystem.create_file(self.file_path, + contents=self.file_contents) def OpenFakeFile(self, mode): return self.open(self.file_path, mode=mode) @@ -6600,7 +6601,8 @@ def setUp(self): # For python 3.x, text file newlines are converted to \n if sys.version_info >= (3, 0): self.read_contents = 'two\nlines' - self.filesystem.CreateFile(self.file_path, contents=self.file_contents) + self.filesystem.create_file(self.file_path, + contents=self.file_contents) # It's reasonable to assume the file exists at this point def OpenFakeFile(self, mode): @@ -6684,55 +6686,55 @@ def testEmptyFilepathRaisesIOError(self): def testNormalPath(self): self.__WriteToFile('foo') - self.assertTrue(self.filesystem.Exists('foo')) + self.assertTrue(self.filesystem.exists('foo')) def testLinkWithinSameDirectory(self): self.skipIfSymlinkNotSupported() final_target = '!foo!baz' - self.filesystem.CreateLink('!foo!bar', 'baz') + self.filesystem.create_symlink('!foo!bar', 'baz') self.__WriteToFile('!foo!bar') - self.assertTrue(self.filesystem.Exists(final_target)) + self.assertTrue(self.filesystem.exists(final_target)) self.assertEqual(1, self.os.stat(final_target)[stat.ST_SIZE]) def testLinkToSubDirectory(self): self.skipIfSymlinkNotSupported() final_target = '!foo!baz!bip' - self.filesystem.CreateDirectory('!foo!baz') - self.filesystem.CreateLink('!foo!bar', 'baz!bip') + self.filesystem.create_dir('!foo!baz') + self.filesystem.create_symlink('!foo!bar', 'baz!bip') self.__WriteToFile('!foo!bar') - self.assertTrue(self.filesystem.Exists(final_target)) + self.assertTrue(self.filesystem.exists(final_target)) self.assertEqual(1, self.os.stat(final_target)[stat.ST_SIZE]) - self.assertTrue(self.filesystem.Exists('!foo!baz')) + self.assertTrue(self.filesystem.exists('!foo!baz')) # Make sure that intermediate directory got created. - new_dir = self.filesystem.GetObject('!foo!baz') + new_dir = self.filesystem.get_object('!foo!baz') self.assertTrue(stat.S_IFDIR & new_dir.st_mode) def testLinkToParentDirectory(self): self.skipIfSymlinkNotSupported() final_target = '!baz!bip' - self.filesystem.CreateDirectory('!foo') - self.filesystem.CreateDirectory('!baz') - self.filesystem.CreateLink('!foo!bar', '..!baz') + self.filesystem.create_dir('!foo') + self.filesystem.create_dir('!baz') + self.filesystem.create_symlink('!foo!bar', '..!baz') self.__WriteToFile('!foo!bar!bip') - self.assertTrue(self.filesystem.Exists(final_target)) + self.assertTrue(self.filesystem.exists(final_target)) self.assertEqual(1, self.os.stat(final_target)[stat.ST_SIZE]) - self.assertTrue(self.filesystem.Exists('!foo!bar')) + self.assertTrue(self.filesystem.exists('!foo!bar')) def testLinkToAbsolutePath(self): self.skipIfSymlinkNotSupported() final_target = '!foo!baz!bip' - self.filesystem.CreateDirectory('!foo!baz') - self.filesystem.CreateLink('!foo!bar', final_target) + self.filesystem.create_dir('!foo!baz') + self.filesystem.create_symlink('!foo!bar', final_target) self.__WriteToFile('!foo!bar') - self.assertTrue(self.filesystem.Exists(final_target)) + self.assertTrue(self.filesystem.exists(final_target)) def testRelativeLinksWorkAfterChdir(self): self.skipIfSymlinkNotSupported() final_target = '!foo!baz!bip' - self.filesystem.CreateDirectory('!foo!baz') - self.filesystem.CreateLink('!foo!bar', '.!baz!bip') + self.filesystem.create_dir('!foo!baz') + self.filesystem.create_symlink('!foo!bar', '.!baz!bip') self.assertEqual(final_target, - self.filesystem.ResolvePath('!foo!bar')) + self.filesystem.resolve_path('!foo!bar')) self.assertTrue(self.os.path.islink('!foo!bar')) self.os.chdir('!foo') @@ -6740,18 +6742,18 @@ def testRelativeLinksWorkAfterChdir(self): self.assertTrue(self.os.path.islink('bar')) self.assertEqual('!foo!baz!bip', - self.filesystem.ResolvePath('bar')) + self.filesystem.resolve_path('bar')) self.__WriteToFile('!foo!bar') - self.assertTrue(self.filesystem.Exists(final_target)) + self.assertTrue(self.filesystem.exists(final_target)) def testAbsoluteLinksWorkAfterChdir(self): self.skipIfSymlinkNotSupported() final_target = '!foo!baz!bip' - self.filesystem.CreateDirectory('!foo!baz') - self.filesystem.CreateLink('!foo!bar', final_target) + self.filesystem.create_dir('!foo!baz') + self.filesystem.create_symlink('!foo!bar', final_target) self.assertEqual(final_target, - self.filesystem.ResolvePath('!foo!bar')) + self.filesystem.resolve_path('!foo!bar')) os_module = fake_filesystem.FakeOsModule(self.filesystem) self.assertTrue(os_module.path.islink('!foo!bar')) @@ -6760,21 +6762,21 @@ def testAbsoluteLinksWorkAfterChdir(self): self.assertTrue(os_module.path.islink('bar')) self.assertEqual('!foo!baz!bip', - self.filesystem.ResolvePath('bar')) + self.filesystem.resolve_path('bar')) self.__WriteToFile('!foo!bar') - self.assertTrue(self.filesystem.Exists(final_target)) + self.assertTrue(self.filesystem.exists(final_target)) def testChdirThroughRelativeLink(self): self.skipIfSymlinkNotSupported() - self.filesystem.CreateDirectory('!x!foo') - self.filesystem.CreateDirectory('!x!bar') - self.filesystem.CreateLink('!x!foo!bar', '..!bar') - self.assertEqual('!x!bar', self.filesystem.ResolvePath('!x!foo!bar')) + self.filesystem.create_dir('!x!foo') + self.filesystem.create_dir('!x!bar') + self.filesystem.create_symlink('!x!foo!bar', '..!bar') + self.assertEqual('!x!bar', self.filesystem.resolve_path('!x!foo!bar')) self.os.chdir('!x!foo') self.assertEqual('!x!foo', self.os.getcwd()) - self.assertEqual('!x!bar', self.filesystem.ResolvePath('bar')) + self.assertEqual('!x!bar', self.filesystem.resolve_path('bar')) self.os.chdir('bar') self.assertEqual('!x!bar', self.os.getcwd()) @@ -6785,7 +6787,7 @@ def testChdirUsesOpenFdAsPath(self): self.filesystem.is_windows_fs = False self.assertRaisesOSError(errno.EBADF, self.os.chdir, 5) dir_path = '!foo!bar' - self.filesystem.CreateDirectory(dir_path) + self.filesystem.create_dir(dir_path) path_des = self.os.open(dir_path, os.O_RDONLY) self.os.chdir(path_des) @@ -6796,8 +6798,8 @@ def testReadLinkToLink(self): # Write into the final link target and read back from a file which will # point to that. self.skipIfSymlinkNotSupported() - self.filesystem.CreateLink('!foo!bar', 'link') - self.filesystem.CreateLink('!foo!link', 'baz') + self.filesystem.create_symlink('!foo!bar', 'link') + self.filesystem.create_symlink('!foo!link', 'baz') self.__WriteToFile('!foo!baz') fh = self.open('!foo!bar', 'r') self.assertEqual('x', fh.read()) @@ -6805,35 +6807,35 @@ def testReadLinkToLink(self): def testWriteLinkToLink(self): self.skipIfSymlinkNotSupported() final_target = '!foo!baz' - self.filesystem.CreateLink('!foo!bar', 'link') - self.filesystem.CreateLink('!foo!link', 'baz') + self.filesystem.create_symlink('!foo!bar', 'link') + self.filesystem.create_symlink('!foo!link', 'baz') self.__WriteToFile('!foo!bar') - self.assertTrue(self.filesystem.Exists(final_target)) + self.assertTrue(self.filesystem.exists(final_target)) def testMultipleLinks(self): self.skipIfSymlinkNotSupported() self.os.makedirs('!a!link1!c!link2') - self.filesystem.CreateLink('!a!b', 'link1') - self.assertEqual('!a!link1', self.filesystem.ResolvePath('!a!b')) - self.assertEqual('!a!link1!c', self.filesystem.ResolvePath('!a!b!c')) + self.filesystem.create_symlink('!a!b', 'link1') + self.assertEqual('!a!link1', self.filesystem.resolve_path('!a!b')) + self.assertEqual('!a!link1!c', self.filesystem.resolve_path('!a!b!c')) - self.filesystem.CreateLink('!a!link1!c!d', 'link2') - self.assertTrue(self.filesystem.Exists('!a!link1!c!d')) - self.assertTrue(self.filesystem.Exists('!a!b!c!d')) + self.filesystem.create_symlink('!a!link1!c!d', 'link2') + self.assertTrue(self.filesystem.exists('!a!link1!c!d')) + self.assertTrue(self.filesystem.exists('!a!b!c!d')) final_target = '!a!link1!c!link2!e' - self.assertFalse(self.filesystem.Exists(final_target)) + self.assertFalse(self.filesystem.exists(final_target)) self.__WriteToFile('!a!b!c!d!e') - self.assertTrue(self.filesystem.Exists(final_target)) + self.assertTrue(self.filesystem.exists(final_target)) def testUtimeLink(self): """os.utime() and os.stat() via symbolic link (issue #49)""" self.skipIfSymlinkNotSupported() - self.filesystem.CreateDirectory('!foo!baz') + self.filesystem.create_dir('!foo!baz') self.__WriteToFile('!foo!baz!bip') link_name = '!foo!bar' - self.filesystem.CreateLink(link_name, '!foo!baz!bip') + self.filesystem.create_symlink(link_name, '!foo!baz!bip') self.os.utime(link_name, (1, 2)) st = self.os.stat(link_name) @@ -6846,20 +6848,20 @@ def testUtimeLink(self): def testTooManyLinks(self): self.filesystem.is_windows_fs = False - self.filesystem.CreateLink('!a!loop', 'loop') - self.assertFalse(self.filesystem.Exists('!a!loop')) + self.filesystem.create_symlink('!a!loop', 'loop') + self.assertFalse(self.filesystem.exists('!a!loop')) def testThatDriveLettersArePreserved(self): self.filesystem.is_windows_fs = True self.assertEqual('c:!foo!bar', - self.filesystem.ResolvePath('c:!foo!!bar')) + self.filesystem.resolve_path('c:!foo!!bar')) @unittest.skipIf(sys.version_info < (2, 7, 8), 'UNC path support since Python 2.7.8') def testThatUncPathsArePreserved(self): self.filesystem.is_windows_fs = True self.assertEqual('!!foo!bar!baz', - self.filesystem.ResolvePath('!!foo!bar!baz!!')) + self.filesystem.resolve_path('!!foo!bar!baz!!')) class PathManipulationTestBase(TestCase): @@ -6872,10 +6874,10 @@ class CollapsePathPipeSeparatorTest(PathManipulationTestBase): as path separator.""" def testEmptyPathBecomesDotPath(self): - self.assertEqual('.', self.filesystem.CollapsePath('')) + self.assertEqual('.', self.filesystem.normpath('')) def testDotPathUnchanged(self): - self.assertEqual('.', self.filesystem.CollapsePath('.')) + self.assertEqual('.', self.filesystem.normpath('.')) def testSlashesAreNotCollapsed(self): """Tests that '/' is not treated specially if the @@ -6883,44 +6885,42 @@ def testSlashesAreNotCollapsed(self): In particular, multiple slashes should not be collapsed. """ - self.assertEqual('/', self.filesystem.CollapsePath('/')) - self.assertEqual('/////', self.filesystem.CollapsePath('/////')) + self.assertEqual('/', self.filesystem.normpath('/')) + self.assertEqual('/////', self.filesystem.normpath('/////')) def testRootPath(self): - self.assertEqual('|', self.filesystem.CollapsePath('|')) + self.assertEqual('|', self.filesystem.normpath('|')) def testMultipleSeparatorsCollapsedIntoRootPath(self): - self.assertEqual('|', self.filesystem.CollapsePath('|||||')) + self.assertEqual('|', self.filesystem.normpath('|||||')) def testAllDotPathsRemovedButOne(self): - self.assertEqual('.', self.filesystem.CollapsePath('.|.|.|.')) + self.assertEqual('.', self.filesystem.normpath('.|.|.|.')) def testAllDotPathsRemovedIfAnotherPathComponentExists(self): - self.assertEqual('|', self.filesystem.CollapsePath('|.|.|.|')) - self.assertEqual('foo|bar', - self.filesystem.CollapsePath('foo|.|.|.|bar')) + self.assertEqual('|', self.filesystem.normpath('|.|.|.|')) + self.assertEqual('foo|bar', self.filesystem.normpath('foo|.|.|.|bar')) def testIgnoresUpLevelReferencesStartingFromRoot(self): - self.assertEqual('|', self.filesystem.CollapsePath('|..|..|..|')) + self.assertEqual('|', self.filesystem.normpath('|..|..|..|')) self.assertEqual( - '|', self.filesystem.CollapsePath('|..|..|foo|bar|..|..|')) - # shall not be handled as UNC path - self.filesystem.is_windows_fs = False - self.assertEqual('|', self.filesystem.CollapsePath('||..|.|..||')) + '|', self.filesystem.normpath('|..|..|foo|bar|..|..|')) + self.filesystem.is_windows_fs = False # shall not be handled as UNC path + self.assertEqual('|', self.filesystem.normpath('||..|.|..||')) def testConservesUpLevelReferencesStartingFromCurrentDirectory(self): self.assertEqual( - '..|..', self.filesystem.CollapsePath('..|foo|bar|..|..|..')) + '..|..', self.filesystem.normpath('..|foo|bar|..|..|..')) def testCombineDotAndUpLevelReferencesInAbsolutePath(self): self.assertEqual( - '|yes', self.filesystem.CollapsePath('|||||.|..|||yes|no|..|.|||')) + '|yes', self.filesystem.normpath('|||||.|..|||yes|no|..|.|||')) def testDotsInPathCollapsesToLastPath(self): self.assertEqual( - 'bar', self.filesystem.CollapsePath('foo|..|bar')) + 'bar', self.filesystem.normpath('foo|..|bar')) self.assertEqual( - 'bar', self.filesystem.CollapsePath('foo|..|yes|..|no|..|bar')) + 'bar', self.filesystem.normpath('foo|..|yes|..|no|..|bar')) class SplitPathTest(PathManipulationTestBase): @@ -6928,70 +6928,70 @@ class SplitPathTest(PathManipulationTestBase): using | as path separator.""" def testEmptyPath(self): - self.assertEqual(('', ''), self.filesystem.SplitPath('')) + self.assertEqual(('', ''), self.filesystem.splitpath('')) def testNoSeparators(self): - self.assertEqual(('', 'ab'), self.filesystem.SplitPath('ab')) + self.assertEqual(('', 'ab'), self.filesystem.splitpath('ab')) def testSlashesDoNotSplit(self): """Tests that '/' is not treated specially if the path separator is '|'.""" - self.assertEqual(('', 'a/b'), self.filesystem.SplitPath('a/b')) + self.assertEqual(('', 'a/b'), self.filesystem.splitpath('a/b')) def testEliminateTrailingSeparatorsFromHead(self): - self.assertEqual(('a', 'b'), self.filesystem.SplitPath('a|b')) - self.assertEqual(('a', 'b'), self.filesystem.SplitPath('a|||b')) - self.assertEqual(('|a', 'b'), self.filesystem.SplitPath('|a||b')) - self.assertEqual(('a|b', 'c'), self.filesystem.SplitPath('a|b|c')) - self.assertEqual(('|a|b', 'c'), self.filesystem.SplitPath('|a|b|c')) + self.assertEqual(('a', 'b'), self.filesystem.splitpath('a|b')) + self.assertEqual(('a', 'b'), self.filesystem.splitpath('a|||b')) + self.assertEqual(('|a', 'b'), self.filesystem.splitpath('|a||b')) + self.assertEqual(('a|b', 'c'), self.filesystem.splitpath('a|b|c')) + self.assertEqual(('|a|b', 'c'), self.filesystem.splitpath('|a|b|c')) def testRootSeparatorIsNotStripped(self): - self.assertEqual(('|', ''), self.filesystem.SplitPath('|||')) - self.assertEqual(('|', 'a'), self.filesystem.SplitPath('|a')) - self.assertEqual(('|', 'a'), self.filesystem.SplitPath('|||a')) + self.assertEqual(('|', ''), self.filesystem.splitpath('|||')) + self.assertEqual(('|', 'a'), self.filesystem.splitpath('|a')) + self.assertEqual(('|', 'a'), self.filesystem.splitpath('|||a')) def testEmptyTailIfPathEndsInSeparator(self): - self.assertEqual(('a|b', ''), self.filesystem.SplitPath('a|b|')) + self.assertEqual(('a|b', ''), self.filesystem.splitpath('a|b|')) def testEmptyPathComponentsArePreservedInHead(self): - self.assertEqual(('|a||b', 'c'), self.filesystem.SplitPath('|a||b||c')) + self.assertEqual(('|a||b', 'c'), self.filesystem.splitpath('|a||b||c')) class JoinPathTest(PathManipulationTestBase): """Tests JoinPath (which mimics os.path.join) using | as path separator.""" def testOneEmptyComponent(self): - self.assertEqual('', self.filesystem.JoinPaths('')) + self.assertEqual('', self.filesystem.joinpaths('')) def testMultipleEmptyComponents(self): - self.assertEqual('', self.filesystem.JoinPaths('', '', '')) + self.assertEqual('', self.filesystem.joinpaths('', '', '')) def testSeparatorsNotStrippedFromSingleComponent(self): - self.assertEqual('||a||', self.filesystem.JoinPaths('||a||')) + self.assertEqual('||a||', self.filesystem.joinpaths('||a||')) def testOneSeparatorAddedBetweenComponents(self): self.assertEqual('a|b|c|d', - self.filesystem.JoinPaths('a', 'b', 'c', 'd')) + self.filesystem.joinpaths('a', 'b', 'c', 'd')) def testNoSeparatorAddedForComponentsEndingInSeparator(self): - self.assertEqual('a|b|c', self.filesystem.JoinPaths('a|', 'b|', 'c')) + self.assertEqual('a|b|c', self.filesystem.joinpaths('a|', 'b|', 'c')) self.assertEqual('a|||b|||c', - self.filesystem.JoinPaths('a|||', 'b|||', 'c')) + self.filesystem.joinpaths('a|||', 'b|||', 'c')) def testComponentsPrecedingAbsoluteComponentAreIgnored(self): self.assertEqual('|c|d', - self.filesystem.JoinPaths('a', '|b', '|c', 'd')) + self.filesystem.joinpaths('a', '|b', '|c', 'd')) def testOneSeparatorAddedForTrailingEmptyComponents(self): - self.assertEqual('a|', self.filesystem.JoinPaths('a', '')) - self.assertEqual('a|', self.filesystem.JoinPaths('a', '', '')) + self.assertEqual('a|', self.filesystem.joinpaths('a', '')) + self.assertEqual('a|', self.filesystem.joinpaths('a', '', '')) def testNoSeparatorAddedForLeadingEmptyComponents(self): - self.assertEqual('a', self.filesystem.JoinPaths('', 'a')) + self.assertEqual('a', self.filesystem.joinpaths('', 'a')) def testInternalEmptyComponentsIgnored(self): - self.assertEqual('a|b', self.filesystem.JoinPaths('a', '', 'b')) - self.assertEqual('a|b|', self.filesystem.JoinPaths('a|', '', 'b|')) + self.assertEqual('a|b', self.filesystem.joinpaths('a', '', 'b')) + self.assertEqual('a|b|', self.filesystem.joinpaths('a|', '', 'b|')) class PathSeparatorTest(TestCase): @@ -7008,24 +7008,26 @@ def setUp(self): self.filesystem.is_case_sensitive = False def testNormalizeCase(self): - self.filesystem.CreateFile('/Foo/Bar') - self.assertEqual('/Foo/Bar', self.filesystem.NormalizeCase('/foo/bar')) - self.assertEqual('/Foo/Bar', self.filesystem.NormalizeCase('/FOO/BAR')) + self.filesystem.create_file('/Foo/Bar') + self.assertEqual('/Foo/Bar', + self.filesystem._original_path('/foo/bar')) + self.assertEqual('/Foo/Bar', + self.filesystem._original_path('/FOO/BAR')) def testNormalizeCaseForDrive(self): self.filesystem.is_windows_fs = True - self.filesystem.CreateFile('C:/Foo/Bar') + self.filesystem.create_file('C:/Foo/Bar') self.assertEqual('C:/Foo/Bar', - self.filesystem.NormalizeCase('c:/foo/bar')) + self.filesystem._original_path('c:/foo/bar')) self.assertEqual('C:/Foo/Bar', - self.filesystem.NormalizeCase('C:/FOO/BAR')) + self.filesystem._original_path('C:/FOO/BAR')) def testNormalizeCaseForNonExistingFile(self): - self.filesystem.CreateDirectory('/Foo/Bar') + self.filesystem.create_dir('/Foo/Bar') self.assertEqual('/Foo/Bar/baz', - self.filesystem.NormalizeCase('/foo/bar/baz')) + self.filesystem._original_path('/foo/bar/baz')) self.assertEqual('/Foo/Bar/BAZ', - self.filesystem.NormalizeCase('/FOO/BAR/BAZ')) + self.filesystem._original_path('/FOO/BAR/BAZ')) @unittest.skipIf(not TestCase.is_windows, 'Regression test for Windows problem only') @@ -7036,7 +7038,7 @@ def testNormalizeCaseForLazilyAddedEmptyFile(self): filesystem.add_real_directory(real_dir_path) initPyPath = os.path.join(real_dir_path, '__init__.py') self.assertEqual(initPyPath, - filesystem.NormalizeCase(initPyPath.upper())) + filesystem._original_path(initPyPath.upper())) class AlternativePathSeparatorTest(TestCase): @@ -7060,17 +7062,17 @@ def testAltSep(self): self.assertEqual('?', fake_os.path.altsep) def testCollapsePathWithMixedSeparators(self): - self.assertEqual('!foo!bar', self.filesystem.CollapsePath('!foo??bar')) + self.assertEqual('!foo!bar', self.filesystem.normpath('!foo??bar')) def testNormalizePathWithMixedSeparators(self): path = 'foo?..?bar' - self.assertEqual('!bar', self.filesystem.NormalizePath(path)) + self.assertEqual('!bar', self.filesystem.absnormpath(path)) def testExistsWithMixedSeparators(self): - self.filesystem.CreateFile('?foo?bar?baz') - self.filesystem.CreateFile('!foo!bar!xyzzy!plugh') - self.assertTrue(self.filesystem.Exists('!foo!bar!baz')) - self.assertTrue(self.filesystem.Exists('?foo?bar?xyzzy?plugh')) + self.filesystem.create_file('?foo?bar?baz') + self.filesystem.create_file('!foo!bar!xyzzy!plugh') + self.assertTrue(self.filesystem.exists('!foo!bar!baz')) + self.assertTrue(self.filesystem.exists('?foo?bar?xyzzy?plugh')) class DriveLetterSupportTest(TestCase): @@ -7087,98 +7089,98 @@ def testInitialValue(self): def testCollapsePath(self): self.assertEqual('c:!foo!bar', - self.filesystem.CollapsePath('c:!!foo!!bar')) + self.filesystem.normpath('c:!!foo!!bar')) @unittest.skipIf(sys.version_info < (2, 7, 8), 'UNC path support since Python 2.7.8') def testCollapseUncPath(self): self.assertEqual('!!foo!bar!baz', - self.filesystem.CollapsePath('!!foo!bar!!baz!!')) + self.filesystem.normpath('!!foo!bar!!baz!!')) def testNormalizePathStr(self): self.filesystem.cwd = u'' self.assertEqual(u'c:!foo!bar', - self.filesystem.NormalizePath(u'c:!foo!!bar')) + self.filesystem.absnormpath(u'c:!foo!!bar')) self.filesystem.cwd = u'c:!foo' - self.assertEqual(u'c:!foo!bar', self.filesystem.NormalizePath(u'bar')) + self.assertEqual(u'c:!foo!bar', self.filesystem.absnormpath(u'bar')) def testNormalizePathBytes(self): self.filesystem.cwd = b'' self.assertEqual(b'c:!foo!bar', - self.filesystem.NormalizePath(b'c:!foo!!bar')) + self.filesystem.absnormpath(b'c:!foo!!bar')) self.filesystem.cwd = b'c:!foo' - self.assertEqual(b'c:!foo!bar', self.filesystem.NormalizePath(b'bar')) + self.assertEqual(b'c:!foo!bar', self.filesystem.absnormpath(b'bar')) def testSplitPathStr(self): self.assertEqual((u'c:!foo', u'bar'), - self.filesystem.SplitPath(u'c:!foo!bar')) + self.filesystem.splitpath(u'c:!foo!bar')) self.assertEqual((u'c:!', u'foo'), - self.filesystem.SplitPath(u'c:!foo')) + self.filesystem.splitpath(u'c:!foo')) self.assertEqual((u'!foo', u'bar'), - self.filesystem.SplitPath(u'!foo!bar')) + self.filesystem.splitpath(u'!foo!bar')) self.assertEqual((u'!', u'foo'), - self.filesystem.SplitPath(u'!foo')) + self.filesystem.splitpath(u'!foo')) self.assertEqual((u'c:foo', u'bar'), - self.filesystem.SplitPath(u'c:foo!bar')) + self.filesystem.splitpath(u'c:foo!bar')) self.assertEqual((u'c:', u'foo'), - self.filesystem.SplitPath(u'c:foo')) + self.filesystem.splitpath(u'c:foo')) self.assertEqual((u'foo', u'bar'), - self.filesystem.SplitPath(u'foo!bar')) + self.filesystem.splitpath(u'foo!bar')) def testSplitPathBytes(self): self.assertEqual((b'c:!foo', b'bar'), - self.filesystem.SplitPath(b'c:!foo!bar')) + self.filesystem.splitpath(b'c:!foo!bar')) self.assertEqual((b'c:!', b'foo'), - self.filesystem.SplitPath(b'c:!foo')) + self.filesystem.splitpath(b'c:!foo')) self.assertEqual((b'!foo', b'bar'), - self.filesystem.SplitPath(b'!foo!bar')) + self.filesystem.splitpath(b'!foo!bar')) self.assertEqual((b'!', b'foo'), - self.filesystem.SplitPath(b'!foo')) + self.filesystem.splitpath(b'!foo')) self.assertEqual((b'c:foo', b'bar'), - self.filesystem.SplitPath(b'c:foo!bar')) + self.filesystem.splitpath(b'c:foo!bar')) self.assertEqual((b'c:', b'foo'), - self.filesystem.SplitPath(b'c:foo')) + self.filesystem.splitpath(b'c:foo')) self.assertEqual((b'foo', b'bar'), - self.filesystem.SplitPath(b'foo!bar')) + self.filesystem.splitpath(b'foo!bar')) def testCharactersBeforeRootIgnoredInJoinPaths(self): - self.assertEqual('c:d', self.filesystem.JoinPaths('b', 'c:', 'd')) + self.assertEqual('c:d', self.filesystem.joinpaths('b', 'c:', 'd')) def testResolvePath(self): self.assertEqual('c:!foo!bar', - self.filesystem.ResolvePath('c:!foo!bar')) + self.filesystem.resolve_path('c:!foo!bar')) def testGetPathComponents(self): self.assertEqual(['c:', 'foo', 'bar'], - self.filesystem.GetPathComponents('c:!foo!bar')) - self.assertEqual(['c:'], self.filesystem.GetPathComponents('c:')) + self.filesystem._path_components('c:!foo!bar')) + self.assertEqual(['c:'], self.filesystem._path_components('c:')) def testSplitDriveStr(self): self.assertEqual((u'c:', u'!foo!bar'), - self.filesystem.SplitDrive(u'c:!foo!bar')) + self.filesystem.splitdrive(u'c:!foo!bar')) self.assertEqual((u'', u'!foo!bar'), - self.filesystem.SplitDrive(u'!foo!bar')) + self.filesystem.splitdrive(u'!foo!bar')) self.assertEqual((u'c:', u'foo!bar'), - self.filesystem.SplitDrive(u'c:foo!bar')) + self.filesystem.splitdrive(u'c:foo!bar')) self.assertEqual((u'', u'foo!bar'), - self.filesystem.SplitDrive(u'foo!bar')) + self.filesystem.splitdrive(u'foo!bar')) def testSplitDriveBytes(self): self.assertEqual((b'c:', b'!foo!bar'), - self.filesystem.SplitDrive(b'c:!foo!bar')) + self.filesystem.splitdrive(b'c:!foo!bar')) self.assertEqual((b'', b'!foo!bar'), - self.filesystem.SplitDrive(b'!foo!bar')) + self.filesystem.splitdrive(b'!foo!bar')) @unittest.skipIf(sys.version_info < (2, 7, 8), 'UNC path support since Python 2.7.8') def testSplitDriveWithUncPath(self): self.assertEqual(('!!foo!bar', '!baz'), - self.filesystem.SplitDrive('!!foo!bar!baz')) - self.assertEqual(('', '!!foo'), self.filesystem.SplitDrive('!!foo')) + self.filesystem.splitdrive('!!foo!bar!baz')) + self.assertEqual(('', '!!foo'), self.filesystem.splitdrive('!!foo')) self.assertEqual(('', '!!foo!!bar'), - self.filesystem.SplitDrive('!!foo!!bar')) + self.filesystem.splitdrive('!!foo!!bar')) self.assertEqual(('!!foo!bar', '!!'), - self.filesystem.SplitDrive('!!foo!bar!!')) + self.filesystem.splitdrive('!!foo!bar!!')) class DiskSpaceTest(TestCase): @@ -7191,7 +7193,7 @@ def testDiskUsageOnFileCreation(self): fake_open = fake_filesystem.FakeFileOpen(self.filesystem) total_size = 100 - self.filesystem.AddMountPoint('mount', total_size) + self.filesystem.add_mount_point('mount', total_size) def create_too_large_file(): with fake_open('!mount!file', 'w') as dest: @@ -7199,216 +7201,222 @@ def create_too_large_file(): self.assertRaises((OSError, IOError), create_too_large_file) - self.assertEqual(0, self.filesystem.GetDiskUsage('!mount').used) + self.assertEqual(0, self.filesystem.get_disk_usage('!mount').used) with fake_open('!mount!file', 'w') as dest: dest.write('a' * total_size) self.assertEqual(total_size, - self.filesystem.GetDiskUsage('!mount').used) + self.filesystem.get_disk_usage('!mount').used) def testFileSystemSizeAfterLargeFileCreation(self): filesystem = fake_filesystem.FakeFilesystem(path_separator='!', total_size=1024 * 1024 * 1024 * 100) - filesystem.CreateFile('!foo!baz', st_size=1024 * 1024 * 1024 * 10) + filesystem.create_file('!foo!baz', st_size=1024 * 1024 * 1024 * 10) self.assertEqual((1024 * 1024 * 1024 * 100, 1024 * 1024 * 1024 * 10, - 1024 * 1024 * 1024 * 90), filesystem.GetDiskUsage()) + 1024 * 1024 * 1024 * 90), + filesystem.get_disk_usage()) def testFileSystemSizeAfterBinaryFileCreation(self): - self.filesystem.CreateFile('!foo!bar', contents=b'xyzzy') - self.assertEqual((100, 5, 95), self.filesystem.GetDiskUsage()) + self.filesystem.create_file('!foo!bar', contents=b'xyzzy') + self.assertEqual((100, 5, 95), self.filesystem.get_disk_usage()) def testFileSystemSizeAfterAsciiStringFileCreation(self): - self.filesystem.CreateFile('!foo!bar', contents=u'complicated') - self.assertEqual((100, 11, 89), self.filesystem.GetDiskUsage()) + self.filesystem.create_file('!foo!bar', contents=u'complicated') + self.assertEqual((100, 11, 89), self.filesystem.get_disk_usage()) def testFileSystemSizeAfter2ByteUnicodeStringFileCreation(self): - self.filesystem.CreateFile('!foo!bar', contents=u'сложно', - encoding='utf-8') - self.assertEqual((100, 12, 88), self.filesystem.GetDiskUsage()) + self.filesystem.create_file('!foo!bar', contents=u'сложно', + encoding='utf-8') + self.assertEqual((100, 12, 88), self.filesystem.get_disk_usage()) def testFileSystemSizeAfter3ByteUnicodeStringFileCreation(self): - self.filesystem.CreateFile('!foo!bar', contents=u'複雑', - encoding='utf-8') - self.assertEqual((100, 6, 94), self.filesystem.GetDiskUsage()) + self.filesystem.create_file('!foo!bar', contents=u'複雑', + encoding='utf-8') + self.assertEqual((100, 6, 94), self.filesystem.get_disk_usage()) def testFileSystemSizeAfterFileDeletion(self): - self.filesystem.CreateFile('!foo!bar', contents=b'xyzzy') - self.filesystem.CreateFile('!foo!baz', st_size=20) - self.filesystem.RemoveObject('!foo!bar') - self.assertEqual((100, 20, 80), self.filesystem.GetDiskUsage()) + self.filesystem.create_file('!foo!bar', contents=b'xyzzy') + self.filesystem.create_file('!foo!baz', st_size=20) + self.filesystem.remove_object('!foo!bar') + self.assertEqual((100, 20, 80), self.filesystem.get_disk_usage()) def testFileSystemSizeAfterDirectoryRemoval(self): - self.filesystem.CreateFile('!foo!bar', st_size=10) - self.filesystem.CreateFile('!foo!baz', st_size=20) - self.filesystem.CreateFile('!foo1!bar', st_size=40) - self.filesystem.RemoveObject('!foo') - self.assertEqual((100, 40, 60), self.filesystem.GetDiskUsage()) + self.filesystem.create_file('!foo!bar', st_size=10) + self.filesystem.create_file('!foo!baz', st_size=20) + self.filesystem.create_file('!foo1!bar', st_size=40) + self.filesystem.remove_object('!foo') + self.assertEqual((100, 40, 60), self.filesystem.get_disk_usage()) def testCreatingFileWithFittingContent(self): - initial_usage = self.filesystem.GetDiskUsage() + initial_usage = self.filesystem.get_disk_usage() try: - self.filesystem.CreateFile('!foo!bar', contents=b'a' * 100) + self.filesystem.create_file('!foo!bar', contents=b'a' * 100) except IOError: self.fail( 'File with contents fitting into disk space could not be written.') self.assertEqual(initial_usage.used + 100, - self.filesystem.GetDiskUsage().used) + self.filesystem.get_disk_usage().used) def testCreatingFileWithContentTooLarge(self): def create_large_file(): - self.filesystem.CreateFile('!foo!bar', contents=b'a' * 101) + self.filesystem.create_file('!foo!bar', contents=b'a' * 101) - initial_usage = self.filesystem.GetDiskUsage() + initial_usage = self.filesystem.get_disk_usage() self.assertRaises(IOError, create_large_file) - self.assertEqual(initial_usage, self.filesystem.GetDiskUsage()) + self.assertEqual(initial_usage, self.filesystem.get_disk_usage()) def testCreatingFileWithFittingSize(self): - initial_usage = self.filesystem.GetDiskUsage() + initial_usage = self.filesystem.get_disk_usage() try: - self.filesystem.CreateFile('!foo!bar', st_size=100) + self.filesystem.create_file('!foo!bar', st_size=100) except IOError: self.fail( 'File with size fitting into disk space could not be written.') self.assertEqual(initial_usage.used + 100, - self.filesystem.GetDiskUsage().used) + self.filesystem.get_disk_usage().used) def testCreatingFileWithSizeTooLarge(self): - initial_usage = self.filesystem.GetDiskUsage() + initial_usage = self.filesystem.get_disk_usage() def create_large_file(): - self.filesystem.CreateFile('!foo!bar', st_size=101) + self.filesystem.create_file('!foo!bar', st_size=101) self.assertRaises(IOError, create_large_file) - self.assertEqual(initial_usage, self.filesystem.GetDiskUsage()) + self.assertEqual(initial_usage, self.filesystem.get_disk_usage()) def testResizeFileWithFittingSize(self): - file_object = self.filesystem.CreateFile('!foo!bar', st_size=50) + file_object = self.filesystem.create_file('!foo!bar', st_size=50) try: - file_object.SetLargeFileSize(100) - file_object.SetContents(b'a' * 100) + file_object.set_large_file_size(100) + file_object.set_contents(b'a' * 100) except IOError: self.fail( 'Resizing file failed although disk space was sufficient.') def testResizeFileWithSizeTooLarge(self): - file_object = self.filesystem.CreateFile('!foo!bar', st_size=50) - self.assertRaisesIOError(errno.ENOSPC, file_object.SetLargeFileSize, + file_object = self.filesystem.create_file('!foo!bar', st_size=50) + self.assertRaisesIOError(errno.ENOSPC, file_object.set_large_file_size, 200) - self.assertRaisesIOError(errno.ENOSPC, file_object.SetContents, + self.assertRaisesIOError(errno.ENOSPC, file_object.set_contents, 'a' * 150) def testFileSystemSizeAfterDirectoryRename(self): - self.filesystem.CreateFile('!foo!bar', st_size=20) + self.filesystem.create_file('!foo!bar', st_size=20) self.os.rename('!foo', '!baz') - self.assertEqual(20, self.filesystem.GetDiskUsage().used) + self.assertEqual(20, self.filesystem.get_disk_usage().used) def testFileSystemSizeAfterFileRename(self): - self.filesystem.CreateFile('!foo!bar', st_size=20) + self.filesystem.create_file('!foo!bar', st_size=20) self.os.rename('!foo!bar', '!foo!baz') - self.assertEqual(20, self.filesystem.GetDiskUsage().used) + self.assertEqual(20, self.filesystem.get_disk_usage().used) @unittest.skipIf(TestCase.is_windows and sys.version_info < (3, 3), 'Links are not supported under Windows before Python 3.3') def testThatHardLinkDoesNotChangeUsedSize(self): file1_path = 'test_file1' file2_path = 'test_file2' - self.filesystem.CreateFile(file1_path, st_size=20) - self.assertEqual(20, self.filesystem.GetDiskUsage().used) + self.filesystem.create_file(file1_path, st_size=20) + self.assertEqual(20, self.filesystem.get_disk_usage().used) # creating a hard link shall not increase used space self.os.link(file1_path, file2_path) - self.assertEqual(20, self.filesystem.GetDiskUsage().used) + self.assertEqual(20, self.filesystem.get_disk_usage().used) # removing a file shall not decrease used space # if a hard link still exists self.os.unlink(file1_path) - self.assertEqual(20, self.filesystem.GetDiskUsage().used) + self.assertEqual(20, self.filesystem.get_disk_usage().used) self.os.unlink(file2_path) - self.assertEqual(0, self.filesystem.GetDiskUsage().used) + self.assertEqual(0, self.filesystem.get_disk_usage().used) def testThatTheSizeOfCorrectMountPointIsUsed(self): - self.filesystem.AddMountPoint('!mount_limited', total_size=50) - self.filesystem.AddMountPoint('!mount_unlimited') + self.filesystem.add_mount_point('!mount_limited', total_size=50) + self.filesystem.add_mount_point('!mount_unlimited') self.assertRaisesIOError(errno.ENOSPC, - self.filesystem.CreateFile, + self.filesystem.create_file, '!mount_limited!foo', st_size=60) - self.assertRaisesIOError(errno.ENOSPC, self.filesystem.CreateFile, + self.assertRaisesIOError(errno.ENOSPC, self.filesystem.create_file, '!bar', st_size=110) try: - self.filesystem.CreateFile('!foo', st_size=60) - self.filesystem.CreateFile('!mount_limited!foo', st_size=40) - self.filesystem.CreateFile('!mount_unlimited!foo', st_size=1000000) + self.filesystem.create_file('!foo', st_size=60) + self.filesystem.create_file('!mount_limited!foo', st_size=40) + self.filesystem.create_file('!mount_unlimited!foo', + st_size=1000000) except IOError: self.fail('File with contents fitting into ' 'disk space could not be written.') def testThatDiskUsageOfCorrectMountPointIsUsed(self): - self.filesystem.AddMountPoint('!mount1', total_size=20) - self.filesystem.AddMountPoint('!mount1!bar!mount2', total_size=50) + self.filesystem.add_mount_point('!mount1', total_size=20) + self.filesystem.add_mount_point('!mount1!bar!mount2', total_size=50) - self.filesystem.CreateFile('!foo!bar', st_size=10) - self.filesystem.CreateFile('!mount1!foo!bar', st_size=10) - self.filesystem.CreateFile('!mount1!bar!mount2!foo!bar', st_size=10) + self.filesystem.create_file('!foo!bar', st_size=10) + self.filesystem.create_file('!mount1!foo!bar', st_size=10) + self.filesystem.create_file('!mount1!bar!mount2!foo!bar', st_size=10) - self.assertEqual(90, self.filesystem.GetDiskUsage('!foo').free) - self.assertEqual(10, self.filesystem.GetDiskUsage('!mount1!foo').free) - self.assertEqual(40, self.filesystem.GetDiskUsage( + self.assertEqual(90, self.filesystem.get_disk_usage('!foo').free) + self.assertEqual(10, + self.filesystem.get_disk_usage('!mount1!foo').free) + self.assertEqual(40, self.filesystem.get_disk_usage( '!mount1!bar!mount2').free) def testSetLargerDiskSize(self): - self.filesystem.AddMountPoint('!mount1', total_size=20) + self.filesystem.add_mount_point('!mount1', total_size=20) self.assertRaisesIOError(errno.ENOSPC, - self.filesystem.CreateFile, '!mount1!foo', + self.filesystem.create_file, '!mount1!foo', st_size=100) - self.filesystem.SetDiskUsage(total_size=200, path='!mount1') - self.filesystem.CreateFile('!mount1!foo', st_size=100) - self.assertEqual(100, self.filesystem.GetDiskUsage('!mount1!foo').free) + self.filesystem.set_disk_usage(total_size=200, path='!mount1') + self.filesystem.create_file('!mount1!foo', st_size=100) + self.assertEqual(100, + self.filesystem.get_disk_usage('!mount1!foo').free) def testSetSmallerDiskSize(self): - self.filesystem.AddMountPoint('!mount1', total_size=200) - self.filesystem.CreateFile('!mount1!foo', st_size=100) + self.filesystem.add_mount_point('!mount1', total_size=200) + self.filesystem.create_file('!mount1!foo', st_size=100) self.assertRaisesIOError(errno.ENOSPC, - self.filesystem.SetDiskUsage, total_size=50, + self.filesystem.set_disk_usage, total_size=50, path='!mount1') - self.filesystem.SetDiskUsage(total_size=150, path='!mount1') - self.assertEqual(50, self.filesystem.GetDiskUsage('!mount1!foo').free) + self.filesystem.set_disk_usage(total_size=150, path='!mount1') + self.assertEqual(50, + self.filesystem.get_disk_usage('!mount1!foo').free) def testDiskSizeOnUnlimitedDisk(self): - self.filesystem.AddMountPoint('!mount1') - self.filesystem.CreateFile('!mount1!foo', st_size=100) - self.filesystem.SetDiskUsage(total_size=1000, path='!mount1') - self.assertEqual(900, self.filesystem.GetDiskUsage('!mount1!foo').free) + self.filesystem.add_mount_point('!mount1') + self.filesystem.create_file('!mount1!foo', st_size=100) + self.filesystem.set_disk_usage(total_size=1000, path='!mount1') + self.assertEqual(900, + self.filesystem.get_disk_usage('!mount1!foo').free) def testDiskSizeOnAutoMountedDriveOnFileCreation(self): self.filesystem.is_windows_fs = True # drive d: shall be auto-mounted and the used size adapted - self.filesystem.CreateFile('d:!foo!bar', st_size=100) - self.filesystem.SetDiskUsage(total_size=1000, path='d:') - self.assertEqual(self.filesystem.GetDiskUsage('d:!foo').free, 900) + self.filesystem.create_file('d:!foo!bar', st_size=100) + self.filesystem.set_disk_usage(total_size=1000, path='d:') + self.assertEqual(self.filesystem.get_disk_usage('d:!foo').free, 900) def testDiskSizeOnAutoMountedDriveOnDirectoryCreation(self): self.filesystem.is_windows_fs = True - self.filesystem.CreateDirectory('d:!foo!bar') - self.filesystem.CreateFile('d:!foo!bar!baz', st_size=100) - self.filesystem.CreateFile('d:!foo!baz', st_size=100) - self.filesystem.SetDiskUsage(total_size=1000, path='d:') - self.assertEqual(self.filesystem.GetDiskUsage('d:!foo').free, 800) + self.filesystem.create_dir('d:!foo!bar') + self.filesystem.create_file('d:!foo!bar!baz', st_size=100) + self.filesystem.create_file('d:!foo!baz', st_size=100) + self.filesystem.set_disk_usage(total_size=1000, path='d:') + self.assertEqual(self.filesystem.get_disk_usage('d:!foo').free, 800) @unittest.skipIf(sys.version_info < (3, 0), 'Tests byte contents in Python3') def testCopyingPreservesByteContents(self): - source_file = self.filesystem.CreateFile('foo', contents=b'somebytes') - dest_file = self.filesystem.CreateFile('bar') - dest_file.SetContents(source_file.contents) + source_file = self.filesystem.create_file('foo', contents=b'somebytes') + dest_file = self.filesystem.create_file('bar') + dest_file.set_contents(source_file.contents) self.assertEqual(dest_file.contents, source_file.contents) @@ -7416,64 +7424,63 @@ class MountPointTest(TestCase): def setUp(self): self.filesystem = fake_filesystem.FakeFilesystem(path_separator='!', total_size=100) - self.filesystem.AddMountPoint('!foo') - self.filesystem.AddMountPoint('!bar') - self.filesystem.AddMountPoint('!foo!baz') + self.filesystem.add_mount_point('!foo') + self.filesystem.add_mount_point('!bar') + self.filesystem.add_mount_point('!foo!baz') def testThatNewMountPointsGetNewDeviceNumber(self): - self.assertEqual(1, self.filesystem.GetObject('!').st_dev) - self.assertEqual(2, self.filesystem.GetObject('!foo').st_dev) - self.assertEqual(3, self.filesystem.GetObject('!bar').st_dev) - self.assertEqual(4, self.filesystem.GetObject('!foo!baz').st_dev) + self.assertEqual(1, self.filesystem.get_object('!').st_dev) + self.assertEqual(2, self.filesystem.get_object('!foo').st_dev) + self.assertEqual(3, self.filesystem.get_object('!bar').st_dev) + self.assertEqual(4, self.filesystem.get_object('!foo!baz').st_dev) def testThatNewDirectoriesGetCorrectDeviceNumber(self): - self.assertEqual(1, - self.filesystem.CreateDirectory('!foo1!bar').st_dev) - self.assertEqual(2, self.filesystem.CreateDirectory('!foo!bar').st_dev) - self.assertEqual(4, self.filesystem.CreateDirectory( - '!foo!baz!foo!bar').st_dev) + self.assertEqual(1, self.filesystem.create_dir('!foo1!bar').st_dev) + self.assertEqual(2, self.filesystem.create_dir('!foo!bar').st_dev) + self.assertEqual(4, + self.filesystem.create_dir('!foo!baz!foo!bar').st_dev) def testThatNewFilesGetCorrectDeviceNumber(self): - self.assertEqual(1, self.filesystem.CreateFile('!foo1!bar').st_dev) - self.assertEqual(2, self.filesystem.CreateFile('!foo!bar').st_dev) - self.assertEqual(4, - self.filesystem.CreateFile('!foo!baz!foo!bar').st_dev) + self.assertEqual(1, self.filesystem.create_file('!foo1!bar').st_dev) + self.assertEqual(2, self.filesystem.create_file('!foo!bar').st_dev) + self.assertEqual(4, self.filesystem.create_file( + '!foo!baz!foo!bar').st_dev) def testThatMountPointCannotBeAddedTwice(self): - self.assertRaisesOSError(errno.EEXIST, self.filesystem.AddMountPoint, + self.assertRaisesOSError(errno.EEXIST, self.filesystem.add_mount_point, '!foo') - self.assertRaisesOSError(errno.EEXIST, self.filesystem.AddMountPoint, + self.assertRaisesOSError(errno.EEXIST, self.filesystem.add_mount_point, '!foo!') def testThatDrivesAreAutoMounted(self): self.filesystem.is_windows_fs = True - self.filesystem.CreateDirectory('d:!foo!bar') - self.filesystem.CreateFile('d:!foo!baz') - self.filesystem.CreateFile('z:!foo!baz') - self.assertEqual(5, self.filesystem.GetObject('d:').st_dev) - self.assertEqual(5, self.filesystem.GetObject('d:!foo!bar').st_dev) - self.assertEqual(5, self.filesystem.GetObject('d:!foo!baz').st_dev) - self.assertEqual(6, self.filesystem.GetObject('z:!foo!baz').st_dev) + self.filesystem.create_dir('d:!foo!bar') + self.filesystem.create_file('d:!foo!baz') + self.filesystem.create_file('z:!foo!baz') + self.assertEqual(5, self.filesystem.get_object('d:').st_dev) + self.assertEqual(5, self.filesystem.get_object('d:!foo!bar').st_dev) + self.assertEqual(5, self.filesystem.get_object('d:!foo!baz').st_dev) + self.assertEqual(6, self.filesystem.get_object('z:!foo!baz').st_dev) def testThatDrivesAreAutoMountedCaseInsensitive(self): self.filesystem.is_windows_fs = True self.filesystem.is_case_sensitive = False - self.filesystem.CreateDirectory('D:!foo!bar') - self.filesystem.CreateFile('e:!foo!baz') - self.assertEqual(5, self.filesystem.GetObject('D:').st_dev) - self.assertEqual(5, self.filesystem.GetObject('d:!foo!bar').st_dev) - self.assertEqual(6, self.filesystem.GetObject('e:!foo').st_dev) - self.assertEqual(6, self.filesystem.GetObject('E:!Foo!Baz').st_dev) + self.filesystem.create_dir('D:!foo!bar') + self.filesystem.create_file('e:!foo!baz') + self.assertEqual(5, self.filesystem.get_object('D:').st_dev) + self.assertEqual(5, self.filesystem.get_object('d:!foo!bar').st_dev) + self.assertEqual(6, self.filesystem.get_object('e:!foo').st_dev) + self.assertEqual(6, self.filesystem.get_object('E:!Foo!Baz').st_dev) @unittest.skipIf(sys.version_info < (2, 7, 8), 'UNC path support since Python 2.7.8') def testThatUncPathsAreAutoMounted(self): self.filesystem.is_windows_fs = True - self.filesystem.CreateDirectory('!!foo!bar!baz') - self.filesystem.CreateFile('!!foo!bar!bip!bop') - self.assertEqual(5, self.filesystem.GetObject('!!foo!bar').st_dev) - self.assertEqual(5, - self.filesystem.GetObject('!!foo!bar!bip!bop').st_dev) + self.filesystem.create_dir('!!foo!bar!baz') + self.filesystem.create_file('!!foo!bar!bip!bop') + self.assertEqual(5, self.filesystem.get_object('!!foo!bar').st_dev) + self.assertEqual(5, self.filesystem.get_object( + '!!foo!bar!bip!bop').st_dev) class RealFileSystemAccessTest(TestCase): @@ -7486,30 +7493,30 @@ def testAddNonExistingRealFileRaises(self): nonexisting_path = os.path.join('nonexisting', 'test.txt') self.assertRaises(OSError, self.filesystem.add_real_file, nonexisting_path) - self.assertFalse(self.filesystem.Exists(nonexisting_path)) + self.assertFalse(self.filesystem.exists(nonexisting_path)) def testAddNonExistingRealDirectoryRaises(self): nonexisting_path = '/nonexisting' self.assertRaisesIOError(errno.ENOENT, self.filesystem.add_real_directory, nonexisting_path) - self.assertFalse(self.filesystem.Exists(nonexisting_path)) + self.assertFalse(self.filesystem.exists(nonexisting_path)) def testExistingFakeFileRaises(self): real_file_path = __file__ - self.filesystem.CreateFile(real_file_path) + self.filesystem.create_file(real_file_path) self.assertRaisesOSError(errno.EEXIST, self.filesystem.add_real_file, real_file_path) def testExistingFakeDirectoryRaises(self): real_dir_path = os.path.dirname(__file__) - self.filesystem.CreateDirectory(real_dir_path) + self.filesystem.create_dir(real_dir_path) self.assertRaisesOSError(errno.EEXIST, self.filesystem.add_real_directory, real_dir_path) def checkFakeFileStat(self, fake_file, real_file_path): - self.assertTrue(self.filesystem.Exists(real_file_path)) + self.assertTrue(self.filesystem.exists(real_file_path)) real_stat = os.stat(real_file_path) self.assertIsNone(fake_file._byte_contents) self.assertEqual(fake_file.st_size, real_stat.st_size) @@ -7561,14 +7568,14 @@ def testAddExistingRealFileReadWrite(self): def testAddExistingRealDirectoryReadOnly(self): real_dir_path = os.path.join(os.path.dirname(__file__), 'pyfakefs') self.filesystem.add_real_directory(real_dir_path) - self.assertTrue(self.filesystem.Exists(real_dir_path)) - self.assertTrue(self.filesystem.Exists( + self.assertTrue(self.filesystem.exists(real_dir_path)) + self.assertTrue(self.filesystem.exists( os.path.join(real_dir_path, 'fake_filesystem.py'))) - self.assertTrue(self.filesystem.Exists( + self.assertTrue(self.filesystem.exists( os.path.join(real_dir_path, 'fake_pathlib.py'))) file_path = os.path.join(real_dir_path, 'fake_filesystem_shutil.py') - fake_file = self.filesystem.ResolveObject(file_path) + fake_file = self.filesystem.resolve(file_path) self.checkFakeFileStat(fake_file, file_path) self.checkReadOnlyFile(fake_file, file_path) @@ -7576,65 +7583,65 @@ def testAddExistingRealDirectoryTree(self): real_dir_path = os.path.dirname(__file__) self.filesystem.add_real_directory(real_dir_path) self.assertTrue( - self.filesystem.Exists( + self.filesystem.exists( os.path.join(real_dir_path, 'fake_filesystem_test.py'))) self.assertTrue( - self.filesystem.Exists( + self.filesystem.exists( os.path.join(real_dir_path, 'pyfakefs', 'fake_filesystem.py'))) self.assertTrue( - self.filesystem.Exists( + self.filesystem.exists( os.path.join(real_dir_path, 'pyfakefs', '__init__.py'))) def testGetObjectFromLazilyAddedRealDirectory(self): self.filesystem.is_case_sensitive = True real_dir_path = os.path.dirname(__file__) self.filesystem.add_real_directory(real_dir_path) - self.assertTrue(self.filesystem.GetObject( + self.assertTrue(self.filesystem.get_object( os.path.join(real_dir_path, 'pyfakefs', 'fake_filesystem.py'))) self.assertTrue( - self.filesystem.GetObject( + self.filesystem.get_object( os.path.join(real_dir_path, 'pyfakefs', '__init__.py'))) def testAddExistingRealDirectoryLazily(self): disk_size = 1024 * 1024 * 1024 real_dir_path = os.path.join(os.path.dirname(__file__), 'pyfakefs') - self.filesystem.SetDiskUsage(disk_size, real_dir_path) + self.filesystem.set_disk_usage(disk_size, real_dir_path) self.filesystem.add_real_directory(real_dir_path) # the directory contents have not been read, the the disk usage # has not changed self.assertEqual(disk_size, - self.filesystem.GetDiskUsage(real_dir_path).free) + self.filesystem.get_disk_usage(real_dir_path).free) # checking for existence shall read the directory contents self.assertTrue( - self.filesystem.GetObject( + self.filesystem.get_object( os.path.join(real_dir_path, 'fake_filesystem.py'))) # so now the free disk space shall have decreased self.assertGreater(disk_size, - self.filesystem.GetDiskUsage(real_dir_path).free) + self.filesystem.get_disk_usage(real_dir_path).free) def testAddExistingRealDirectoryNotLazily(self): disk_size = 1024 * 1024 * 1024 real_dir_path = os.path.join(os.path.dirname(__file__), 'pyfakefs') - self.filesystem.SetDiskUsage(disk_size, real_dir_path) + self.filesystem.set_disk_usage(disk_size, real_dir_path) self.filesystem.add_real_directory(real_dir_path, lazy_read=False) # the directory has been read, so the file sizes have # been subtracted from the free space self.assertGreater(disk_size, - self.filesystem.GetDiskUsage(real_dir_path).free) + self.filesystem.get_disk_usage(real_dir_path).free) def testAddExistingRealDirectoryReadWrite(self): real_dir_path = os.path.join(os.path.dirname(__file__), 'pyfakefs') self.filesystem.add_real_directory(real_dir_path, read_only=False) - self.assertTrue(self.filesystem.Exists(real_dir_path)) - self.assertTrue(self.filesystem.Exists( + self.assertTrue(self.filesystem.exists(real_dir_path)) + self.assertTrue(self.filesystem.exists( os.path.join(real_dir_path, 'fake_filesystem.py'))) - self.assertTrue(self.filesystem.Exists( + self.assertTrue(self.filesystem.exists( os.path.join(real_dir_path, 'fake_pathlib.py'))) file_path = os.path.join(real_dir_path, 'pytest_plugin.py') - fake_file = self.filesystem.ResolveObject(file_path) + fake_file = self.filesystem.resolve(file_path) self.checkFakeFileStat(fake_file, file_path) self.checkWritableFile(fake_file, file_path) @@ -7643,13 +7650,13 @@ def testAddExistingRealPathsReadOnly(self): real_dir_path = os.path.join(os.path.dirname(__file__), 'pyfakefs') self.filesystem.add_real_paths([real_file_path, real_dir_path]) - fake_file = self.filesystem.ResolveObject(real_file_path) + fake_file = self.filesystem.resolve(real_file_path) self.checkFakeFileStat(fake_file, real_file_path) self.checkReadOnlyFile(fake_file, real_file_path) real_file_path = os.path.join(real_dir_path, 'fake_filesystem_shutil.py') - fake_file = self.filesystem.ResolveObject(real_file_path) + fake_file = self.filesystem.resolve(real_file_path) self.checkFakeFileStat(fake_file, real_file_path) self.checkReadOnlyFile(fake_file, real_file_path) @@ -7659,12 +7666,12 @@ def testAddExistingRealPathsReadWrite(self): self.filesystem.add_real_paths([real_file_path, real_dir_path], read_only=False) - fake_file = self.filesystem.ResolveObject(real_file_path) + fake_file = self.filesystem.resolve(real_file_path) self.checkFakeFileStat(fake_file, real_file_path) self.checkWritableFile(fake_file, real_file_path) real_file_path = os.path.join(real_dir_path, 'fake_pathlib.py') - fake_file = self.filesystem.ResolveObject(real_file_path) + fake_file = self.filesystem.resolve(real_file_path) self.checkFakeFileStat(fake_file, real_file_path) self.checkWritableFile(fake_file, real_file_path) diff --git a/fake_filesystem_unittest_test.py b/fake_filesystem_unittest_test.py index c7a4bf24..3278b7d0 100755 --- a/fake_filesystem_unittest_test.py +++ b/fake_filesystem_unittest_test.py @@ -59,7 +59,7 @@ def test_file(self): self.assertFalse(os.path.exists('/fake_file.txt')) with file('/fake_file.txt', 'w') as f: f.write("This test file was created using the file() function.\n") - self.assertTrue(self.fs.Exists('/fake_file.txt')) + self.assertTrue(self.fs.exists('/fake_file.txt')) with file('/fake_file.txt') as f: content = f.read() self.assertEqual(content, @@ -70,7 +70,7 @@ def test_open(self): self.assertFalse(os.path.exists('/fake_file.txt')) with open('/fake_file.txt', 'w') as f: f.write("This test file was created using the open() function.\n") - self.assertTrue(self.fs.Exists('/fake_file.txt')) + self.assertTrue(self.fs.exists('/fake_file.txt')) with open('/fake_file.txt') as f: content = f.read() self.assertEqual(content, @@ -81,7 +81,7 @@ def test_io_open(self): self.assertFalse(os.path.exists('/fake_file.txt')) with io.open('/fake_file.txt', 'w') as f: f.write("This test file was created using the io.open() function.\n") - self.assertTrue(self.fs.Exists('/fake_file.txt')) + self.assertTrue(self.fs.exists('/fake_file.txt')) with open('/fake_file.txt') as f: content = f.read() self.assertEqual(content, @@ -89,22 +89,22 @@ def test_io_open(self): def test_os(self): """Fake os module is bound""" - self.assertFalse(self.fs.Exists('/test/dir1/dir2')) + self.assertFalse(self.fs.exists('/test/dir1/dir2')) os.makedirs('/test/dir1/dir2') - self.assertTrue(self.fs.Exists('/test/dir1/dir2')) + self.assertTrue(self.fs.exists('/test/dir1/dir2')) def test_glob(self): """Fake glob module is bound""" is_windows = sys.platform.startswith('win') self.assertEqual(glob.glob('/test/dir1/dir*'), []) - self.fs.CreateDirectory('/test/dir1/dir2a') + self.fs.create_dir('/test/dir1/dir2a') matching_paths = glob.glob('/test/dir1/dir*') if is_windows: self.assertEqual(matching_paths, [r'\test\dir1\dir2a']) else: self.assertEqual(matching_paths, ['/test/dir1/dir2a']) - self.fs.CreateDirectory('/test/dir1/dir2b') + self.fs.create_dir('/test/dir1/dir2b') matching_paths = sorted(glob.glob('/test/dir1/dir*')) if is_windows: self.assertEqual(matching_paths, [r'\test\dir1\dir2a', r'\test\dir1\dir2b']) @@ -113,13 +113,13 @@ def test_glob(self): def test_shutil(self): """Fake shutil module is bound""" - self.fs.CreateDirectory('/test/dir1/dir2a') - self.fs.CreateDirectory('/test/dir1/dir2b') - self.assertTrue(self.fs.Exists('/test/dir1/dir2b')) - self.assertTrue(self.fs.Exists('/test/dir1/dir2a')) + self.fs.create_dir('/test/dir1/dir2a') + self.fs.create_dir('/test/dir1/dir2b') + self.assertTrue(self.fs.exists('/test/dir1/dir2b')) + self.assertTrue(self.fs.exists('/test/dir1/dir2a')) shutil.rmtree('/test/dir1') - self.assertFalse(self.fs.Exists('/test/dir1')) + self.assertFalse(self.fs.exists('/test/dir1')) @unittest.skipIf(sys.version_info < (3, 4), "pathlib new in Python 3.4") def test_fakepathlib(self): @@ -128,9 +128,9 @@ def test_fakepathlib(self): f.write('text') is_windows = sys.platform.startswith('win') if is_windows: - self.assertTrue(self.fs.Exists(r'\fake_file.txt')) + self.assertTrue(self.fs.exists(r'\fake_file.txt')) else: - self.assertTrue(self.fs.Exists('/fake_file.txt')) + self.assertTrue(self.fs.exists('/fake_file.txt')) class TestImportAsOtherName(fake_filesystem_unittest.TestCase): @@ -144,8 +144,8 @@ def setUp(self): def testFileExists(self): file_path = '/foo/bar/baz' - self.fs.CreateFile(file_path) - self.assertTrue(self.fs.Exists(file_path)) + self.fs.create_file(file_path) + self.assertTrue(self.fs.exists(file_path)) self.assertTrue(check_if_exists(file_path)) @@ -242,10 +242,10 @@ def testCopyRealFile(self): def testCopyRealFileDeprecatedArguments(self): '''Deprecated copyRealFile() arguments''' real_file_path = __file__ - self.assertFalse(self.fs.Exists(real_file_path)) + self.assertFalse(self.fs.exists(real_file_path)) # Specify redundant fake file path self.copyRealFile(real_file_path, real_file_path) - self.assertTrue(self.fs.Exists(real_file_path)) + self.assertTrue(self.fs.exists(real_file_path)) # Test deprecated argument values with self.assertRaises(ValueError): @@ -260,7 +260,7 @@ def testAddRealFile(self): # are done in fake_filesystem_test.RealFileSystemAccessTest real_file_path = __file__ fake_file = self.fs.add_real_file(real_file_path) - self.assertTrue(self.fs.Exists(real_file_path)) + self.assertTrue(self.fs.exists(real_file_path)) self.assertIsNone(fake_file._byte_contents) self.assertEqual(self.real_byte_contents, fake_file.byte_contents) @@ -272,8 +272,8 @@ def testAddRealDirectory(self): # Note: this test fails (add_real_directory raises) if 'genericpath' is not added to SKIPNAMES real_dir_path = os.path.join(os.path.dirname(__file__), 'pyfakefs') self.fs.add_real_directory(real_dir_path) - self.assertTrue(self.fs.Exists(real_dir_path)) - self.assertTrue(self.fs.Exists(os.path.join(real_dir_path, 'fake_filesystem.py'))) + self.assertTrue(self.fs.exists(real_dir_path)) + self.assertTrue(self.fs.exists(os.path.join(real_dir_path, 'fake_filesystem.py'))) if __name__ == "__main__": diff --git a/fake_filesystem_vs_real_test.py b/fake_filesystem_vs_real_test.py index 979345f9..32d99c95 100755 --- a/fake_filesystem_vs_real_test.py +++ b/fake_filesystem_vs_real_test.py @@ -103,7 +103,7 @@ def setUp(self): self.assertTrue(os.access(self.real_base, os.W_OK)) self.fake_filesystem = fake_filesystem.FakeFilesystem() - self.fake_filesystem.CreateDirectory(self.fake_base) + self.fake_filesystem.create_dir(self.fake_base) self.fake_os = fake_filesystem.FakeOsModule(self.fake_filesystem) self.fake_open = fake_filesystem.FakeFileOpen(self.fake_filesystem) self._created_files = [] diff --git a/fake_pathlib_test.py b/fake_pathlib_test.py index 097dfebd..45358e91 100644 --- a/fake_pathlib_test.py +++ b/fake_pathlib_test.py @@ -721,23 +721,23 @@ def test_expanduser(self): def test_getmtime(self): self.skipRealFs() dir1 = self.makePath('foo', 'bar1.txt') - path_obj = self.filesystem.CreateFile(dir1) - path_obj.SetMTime(24) + path_obj = self.filesystem.create_file(dir1) + path_obj._st_mtime = 24 self.assertEqual(self.os.path.getmtime(dir1), self.os.path.getmtime(self.path(dir1))) def test_getctime(self): self.skipRealFs() dir1 = self.makePath('foo', 'bar1.txt') - path_obj = self.filesystem.CreateFile(dir1) - path_obj.SetCTime(42) + path_obj = self.filesystem.create_file(dir1) + path_obj.st_ctime = 42 self.assertEqual(self.os.path.getctime(dir1), self.os.path.getctime(self.path(dir1))) def test_getatime(self): self.skipRealFs() dir1 = self.makePath('foo', 'bar1.txt') - path_obj = self.filesystem.CreateFile(dir1) + path_obj = self.filesystem.create_file(dir1) path_obj.SetATime(11) self.assertEqual(self.os.path.getatime(dir1), self.os.path.getatime(self.path(dir1))) diff --git a/fake_tempfile_test.py b/fake_tempfile_test.py index 66b105bf..cb749b26 100755 --- a/fake_tempfile_test.py +++ b/fake_tempfile_test.py @@ -35,21 +35,21 @@ def setUp(self): def testNamedTemporaryFile(self): obj = tempfile.NamedTemporaryFile() - self.assertTrue(self.fs.GetObject(obj.name)) + self.assertTrue(self.fs.get_object(obj.name)) obj.close() - self.assertRaises(IOError, self.fs.GetObject, obj.name) + self.assertRaises(IOError, self.fs.get_object, obj.name) def testNamedTemporaryFileNoDelete(self): obj = tempfile.NamedTemporaryFile(delete=False) obj.write(b'foo') obj.close() - file_obj = self.fs.GetObject(obj.name) + file_obj = self.fs.get_object(obj.name) contents = file_obj.contents self.assertEqual('foo', contents) obj = tempfile.NamedTemporaryFile(mode='w', delete=False) obj.write('foo') obj.close() - file_obj = self.fs.GetObject(obj.name) + file_obj = self.fs.get_object(obj.name) self.assertEqual('foo', file_obj.contents) def testMkstemp(self): @@ -58,9 +58,9 @@ def testMkstemp(self): self.assertEqual(2, len(temporary)) self.assertTrue(temporary[1].startswith(os.path.join(tempfile.gettempdir(), 'tmp'))) self.assertEqual(next_fd, temporary[0]) - self.assertTrue(self.fs.Exists(temporary[1])) + self.assertTrue(self.fs.exists(temporary[1])) mode = 0o666 if self.fs.is_windows_fs else 0o600 - self.assertEqual(self.fs.GetObject(temporary[1]).st_mode, + self.assertEqual(self.fs.get_object(temporary[1]).st_mode, stat.S_IFREG | mode) fh = os.fdopen(temporary[0], 'w+b') self.assertEqual(temporary[0], fh.fileno()) @@ -70,30 +70,30 @@ def testMkstempDir(self): # expect fail: /dir does not exist self.assertRaises(OSError, tempfile.mkstemp, dir='/dir') # expect pass: /dir exists - self.fs.CreateDirectory('/dir') + self.fs.create_dir('/dir') next_fd = len(self.fs.open_files) temporary = tempfile.mkstemp(dir='/dir') self.assertEqual(2, len(temporary)) self.assertEqual(next_fd, temporary[0]) self.assertTrue(temporary[1].startswith(os.path.join(os.sep, 'dir', 'tmp'))) - self.assertTrue(self.fs.Exists(temporary[1])) + self.assertTrue(self.fs.exists(temporary[1])) mode = 0o666 if self.fs.is_windows_fs else 0o600 - self.assertEqual(self.fs.GetObject(temporary[1]).st_mode, + self.assertEqual(self.fs.get_object(temporary[1]).st_mode, stat.S_IFREG | mode) def testMkdtemp(self): dirname = tempfile.mkdtemp() self.assertTrue(dirname) - self.assertTrue(self.fs.Exists(dirname)) - self.assertEqual(self.fs.GetObject(dirname).st_mode, + self.assertTrue(self.fs.exists(dirname)) + self.assertEqual(self.fs.get_object(dirname).st_mode, stat.S_IFDIR | 0o700) @unittest.skipIf(sys.version_info < (3, 0), "TemporaryDirectory showed up in 3") def testTemporaryDirectory(self): with tempfile.TemporaryDirectory() as tmpdir: self.assertTrue(tmpdir) - self.assertTrue(self.fs.Exists(tmpdir)) - self.assertEqual(self.fs.GetObject(tmpdir).st_mode, + self.assertTrue(self.fs.exists(tmpdir)) + self.assertEqual(self.fs.get_object(tmpdir).st_mode, stat.S_IFDIR | 0o700) diff --git a/pyfakefs/deprecator.py b/pyfakefs/deprecator.py new file mode 100644 index 00000000..9aace1e8 --- /dev/null +++ b/pyfakefs/deprecator.py @@ -0,0 +1,69 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Utilities for handling deprecated functions.""" + +import functools +import warnings + + +class Deprecator(object): + """Decorator class for adding deprecated functions. + + Warnings are switched off by default. + To enable deprecation warnings, use: + + >>> from pyfakefs.deprecator import Deprecator + >>> + >>> Deprecator.show_warnings = True + """ + + show_warnings = False + + def __init__(self, use_instead=None, func_name=None): + self.use_instead = use_instead + self.func_name = func_name + + def __call__(self, func): + """Decorator to mark functions as deprecated. Emit warning + when the function is used.""" + + @functools.wraps(func) + def _new_func(*args, **kwargs): + if self.show_warnings: + warnings.simplefilter('always', DeprecationWarning) + message = '' + if self.use_instead is not None: + message = 'Use {} instead.'.format(self.use_instead) + warnings.warn('Call to deprecated function {}. {}'.format( + self.func_name or func.__name__, message), + category=DeprecationWarning, stacklevel=2) + warnings.simplefilter('default', DeprecationWarning) + return func(*args, **kwargs) + + return _new_func + + @staticmethod + def add(cls, func, deprecated_name): + """Add the deprecated version of a member function to the given class. + Gives a deprecation warning on usage. + + Args: + cls: the class where the deprecated function is to be added + func: the actual function that is called by the deprecated version + deprecated_name: the deprecated name of the function + """ + + @Deprecator(func.__name__, deprecated_name) + def _old_function(*args, **kwargs): + return func(*args, **kwargs) + + setattr(cls, deprecated_name, _old_function) diff --git a/pyfakefs/fake_filesystem.py b/pyfakefs/fake_filesystem.py index ffae28f8..5e9fae99 100644 --- a/pyfakefs/fake_filesystem.py +++ b/pyfakefs/fake_filesystem.py @@ -34,27 +34,27 @@ >>> os_module.path.exists(pathname) False ->>> new_file = filesystem.CreateFile(pathname) +>>> new_file = filesystem.create_file(pathname) File objects can't be overwritten: >>> os_module.path.exists(pathname) True >>> try: -... filesystem.CreateFile(pathname) +... filesystem.create_file(pathname) ... except IOError as e: ... assert e.errno == errno.EEXIST, 'unexpected errno: %d' % e.errno ... assert e.strerror == 'File already exists in fake filesystem' Remove a file object: ->>> filesystem.RemoveObject(pathname) +>>> filesystem.remove_object(pathname) >>> os_module.path.exists(pathname) False Create a new file object at the previous path: ->>> beatles_file = filesystem.CreateFile(pathname, +>>> beatles_file = filesystem.create_file(pathname, ... contents='Dear Prudence\\nWon\\'t you come out to play?\\n') >>> os_module.path.exists(pathname) True @@ -99,11 +99,11 @@ import sys import time import warnings - from collections import namedtuple +from stat import S_IFREG, S_IFDIR, S_ISLNK, S_IFMT, S_ISDIR, S_IFLNK, S_ISREG -import stat from copy import copy +from pyfakefs.deprecator import Deprecator from pyfakefs.fake_scandir import scandir, walk @@ -150,9 +150,11 @@ # on MacOS and Windows, the maximum recursion depth is 32 _MAX_LINK_DEPTH = 32 -FAKE_PATH_MODULE_DEPRECATION = ('Do not instantiate a FakePathModule directly; ' - 'let FakeOsModule instantiate it. See the ' - 'FakeOsModule docstring for details.') +FAKE_PATH_MODULE_DEPRECATION = ( + 'Do not instantiate a FakePathModule directly; ' + 'let FakeOsModule instantiate it. See the ' + 'FakeOsModule docstring for details.' +) NR_STD_STREAMS = 3 @@ -173,7 +175,7 @@ def __init__(self, file_path): 'fake large file: %s' % file_path) -def CopyModule(old): +def _copy_module(old): """Recompiles and creates new module object.""" saved = sys.modules.pop(old.__name__, None) new = __import__(old.__name__) @@ -285,7 +287,7 @@ def st_mtime(self, val): @property def st_size(self): - if self.st_mode & stat.S_IFLNK == stat.S_IFLNK and self.is_windows: + if self.st_mode & S_IFLNK == S_IFLNK and self.is_windows: return 0 return self._st_size @@ -294,6 +296,8 @@ def st_size(self, val): self._st_size = val def __getitem__(self, item): + import stat + """Implement item access to mimic `os.stat_result` behavior.""" if item == stat.ST_MODE: return self.st_mode @@ -356,7 +360,7 @@ class FakeFile(object): Attributes currently faked out: st_mode: user-specified, otherwise S_IFREG st_ctime: the time.time() timestamp of the file change time (updated - each time a file's attributes is modified). + each time a file's attributes is modified). st_atime: the time.time() timestamp when the file was last accessed. st_mtime: the time.time() timestamp when the file was last modified. st_size: the size of the file @@ -364,11 +368,11 @@ class FakeFile(object): st_ino: the inode number - a unique number identifying the file st_dev: a unique number identifying the (fake) file system device the file belongs to - Other attributes needed by os.stat are assigned default value of None - these include: st_uid, st_gid + Other attributes needed by os.stat are assigned a default value of None. + These include: st_uid, st_gid """ - def __init__(self, name, st_mode=stat.S_IFREG | PERM_DEF_FILE, + def __init__(self, name, st_mode=S_IFREG | PERM_DEF_FILE, contents=None, filesystem=None, encoding=None, errors=None): """init. @@ -414,7 +418,40 @@ def contents(self): errors=self.errors) return self.byte_contents - def SetLargeFileSize(self, st_size): + @property + def st_ctime(self): + """Return the creation time of the fake file.""" + return (self._st_ctime if FakeOsModule.stat_float_times() + else int(self._st_ctime)) + + @property + def st_atime(self): + """Return the access time of the fake file.""" + return (self._st_atime if FakeOsModule.stat_float_times() + else int(self._st_atime)) + + @property + def st_mtime(self): + """Return the modification time of the fake file.""" + return (self._st_mtime if FakeOsModule.stat_float_times() + else int(self._st_mtime)) + + @st_ctime.setter + def st_ctime(self, val): + """Set the creation time of the fake file.""" + self._st_ctime = val + + @st_atime.setter + def st_atime(self, val): + """Set the access time of the fake file.""" + self._st_atime = val + + @st_mtime.setter + def st_mtime(self, val): + """Set the modification time of the fake file.""" + self._st_mtime = val + + def set_large_file_size(self, st_size): """Sets the self.st_size attribute and replaces self.content with None. Provided specifically to simulate very large files without regards @@ -430,8 +467,9 @@ def SetLargeFileSize(self, st_size): """ self._check_positive_int(st_size) if self.st_size: - self.SetSize(0) - self.filesystem.ChangeDiskUsage(st_size, self.name, self.st_dev) + self.size = 0 + if self.filesystem: + self.filesystem.change_disk_usage(st_size, self.name, self.st_dev) self.st_size = st_size self._byte_contents = None @@ -443,7 +481,7 @@ def _check_positive_int(self, size): 'Fake file object: size must be a non-negative integer, but is %s' % size, self.name) - def IsLargeFile(self): + def is_large_file(self): """Return True if this file was initialized with size but no contents.""" return self._byte_contents is None @@ -469,14 +507,14 @@ def _set_initial_contents(self, contents): st_size = len(contents) if self._byte_contents: - self.SetSize(0) + self.size = 0 current_size = self.st_size or 0 - self.filesystem.ChangeDiskUsage(st_size - current_size, self.name, self.st_dev) + self.filesystem.change_disk_usage(st_size - current_size, self.name, self.st_dev) self._byte_contents = contents self.st_size = st_size self.epoch += 1 - def SetContents(self, contents, encoding=None): + def set_contents(self, contents, encoding=None): """Sets the file contents and size and increases the modification time. Args: @@ -495,11 +533,14 @@ def SetContents(self, contents, encoding=None): self.st_ctime = current_time self.st_mtime = current_time - def GetSize(self): - """Returns the size in bytes of the file contents.""" + @property + def size(self): + """Returns the size in bytes of the file contents. + """ return self.st_size - def GetPath(self): + @property + def path(self): """Return the full path of the current object.""" names = [] obj = self @@ -507,9 +548,18 @@ def GetPath(self): names.insert(0, obj.name) obj = obj.parent_dir sep = self.filesystem._path_separator(self.name) - return self.filesystem.NormalizePath(sep.join(names[1:])) + return self.filesystem.absnormpath(sep.join(names[1:])) + + @Deprecator('property path') + def GetPath(self): + return self.path - def SetSize(self, st_size): + @Deprecator('property size') + def GetSize(self): + return self.size + + @size.setter + def size(self, st_size): """Resizes file content, padding with nulls if new size exceeds the old. Args: @@ -522,7 +572,7 @@ def SetSize(self, st_size): self._check_positive_int(st_size) current_size = self.st_size or 0 - self.filesystem.ChangeDiskUsage(st_size - current_size, self.name, self.st_dev) + self.filesystem.change_disk_usage(st_size - current_size, self.name, self.st_dev) if self._byte_contents: if st_size < current_size: self._byte_contents = self._byte_contents[:st_size] @@ -535,6 +585,11 @@ def SetSize(self, st_size): self.st_size = st_size self.epoch += 1 + @Deprecator('property size') + def SetSize(self, value): + self.size = value + + @Deprecator('property st_atime') def SetATime(self, st_atime): """Set the self.st_atime attribute. @@ -543,6 +598,7 @@ def SetATime(self, st_atime): """ self.st_atime = st_atime + @Deprecator('property st_mtime') def SetMTime(self, st_mtime): """Set the self.st_mtime attribute. @@ -551,6 +607,7 @@ def SetMTime(self, st_mtime): """ self.st_mtime = st_mtime + @Deprecator('property st_ctime') def SetCTime(self, st_ctime): """Set the self.st_ctime attribute. @@ -574,6 +631,7 @@ def __setattr__(self, key, value): def __str__(self): return '%s(%o)' % (self.name, self.st_mode) + @Deprecator('st_ino') def SetIno(self, st_ino): """Set the self.st_ino attribute. Note that a unique inode is assigned automatically to a new fake file. @@ -585,9 +643,14 @@ def SetIno(self, st_ino): self.st_ino = st_ino +Deprecator.add(FakeFile, FakeFile.set_large_file_size, 'SetLargeFileSize') +Deprecator.add(FakeFile, FakeFile.set_contents, 'SetContents') +Deprecator.add(FakeFile, FakeFile.is_large_file, 'IsLargeFile') + + class FakeFileFromRealFile(FakeFile): """Represents a fake file copied from the real file system. - + The contents of the file are read on demand only. """ @@ -597,8 +660,9 @@ def __init__(self, file_path, filesystem, read_only=True): Args: file_path: path to the existing file. filesystem: the fake filesystem where the file is created. - read_only: if set, the file is treated as read-only, e.g. a write access raises an exception; - otherwise, writing to the file changes the fake file only as usually. + read_only: if set, the file is treated as read-only, e.g. + a write access raises an exception; otherwise, writing + to the file changes the fake file only as usually. Raises: OSError: if the file does not exist in the real file system. @@ -623,7 +687,7 @@ def byte_contents(self): self.st_atime = os.stat(self.file_path).st_atime return self._byte_contents - def IsLargeFile(self): + def is_large_file(self): """The contents are never faked.""" return False @@ -639,11 +703,11 @@ def __init__(self, name, perm_bits=PERM_DEF, filesystem=None): perm_bits: permission bits. defaults to 0o777. filesystem: if set, the fake filesystem where the directory is created """ - FakeFile.__init__(self, name, stat.S_IFDIR | perm_bits, {}, filesystem=filesystem) + FakeFile.__init__(self, name, S_IFDIR | perm_bits, {}, filesystem=filesystem) # directories have the link count of contained entries, inclusing '.' and '..' self.st_nlink += 1 - def SetContents(self, contents, encoding=None): + def set_contents(self, contents, encoding=None): if self.filesystem.is_windows_fs and sys.version_info[0] > 2: error_class = OSError else: @@ -661,7 +725,7 @@ def ordered_dirs(self): return [item[0] for item in sorted( self.byte_contents.items(), key=lambda entry: entry[1].st_ino)] - def AddEntry(self, path_object): + def add_entry(self, path_object): """Adds a child FakeFile to this directory. Args: @@ -673,12 +737,12 @@ def AddEntry(self, path_object): """ if not self.st_mode & PERM_WRITE and not self.filesystem.is_windows_fs: exception = IOError if sys.version_info[0] < 3 else OSError - raise exception(errno.EACCES, 'Permission Denied', self.GetPath()) + raise exception(errno.EACCES, 'Permission Denied', self.path) if path_object.name in self.contents: raise OSError(errno.EEXIST, 'Object already exists in fake filesystem', - self.GetPath()) + self.path) self.contents[path_object.name] = path_object path_object.parent_dir = self @@ -686,9 +750,9 @@ def AddEntry(self, path_object): path_object.st_nlink += 1 path_object.st_dev = self.st_dev if path_object.st_nlink == 1: - self.filesystem.ChangeDiskUsage(path_object.GetSize(), path_object.name, self.st_dev) + self.filesystem.change_disk_usage(path_object.size, path_object.name, self.st_dev) - def GetEntry(self, pathname_name): + def get_entry(self, pathname_name): """Retrieves the specified child file or directory entry. Args: @@ -711,7 +775,7 @@ def _normalized_entryname(self, pathname_name): pathname_name = matching_names[0] return pathname_name - def RemoveEntry(self, pathname_name, recursive=True): + def remove_entry(self, pathname_name, recursive=True): """Removes the specified child file or directory. Args: @@ -732,7 +796,7 @@ def RemoveEntry(self, pathname_name, recursive=True): raise OSError(errno.EACCES, 'Trying to remove object ' 'without write permission', pathname_name) - if self.filesystem.HasOpenFile(entry): + if self.filesystem.has_open_file(entry): raise OSError(errno.EACCES, 'Trying to remove an open file', pathname_name) else: @@ -743,9 +807,9 @@ def RemoveEntry(self, pathname_name, recursive=True): if recursive and isinstance(entry, FakeDirectory): while entry.contents: - entry.RemoveEntry(list(entry.contents)[0]) + entry.remove_entry(list(entry.contents)[0]) elif entry.st_nlink == 1: - self.filesystem.ChangeDiskUsage(-entry.GetSize(), pathname_name, entry.st_dev) + self.filesystem.change_disk_usage(-entry.size, pathname_name, entry.st_dev) self.st_nlink -= 1 entry.st_nlink -= 1 @@ -753,12 +817,17 @@ def RemoveEntry(self, pathname_name, recursive=True): del self.contents[pathname_name] - def GetSize(self): + @property + def size(self): """Return the total size of all files contained in this directory tree. """ - return sum([item[1].GetSize() for item in self.contents.items()]) + return sum([item[1].size for item in self.contents.items()]) + + @Deprecator('property size') + def GetSize(self): + return self.size - def HasParentObject(self, dir_object): + def has_parent_object(self, dir_object): """Return `True` if dir_object is a direct or indirect parent directory, or if both are the same object.""" obj = self @@ -778,9 +847,15 @@ def __str__(self): return description +Deprecator.add(FakeDirectory, FakeDirectory.add_entry, 'AddEntry') +Deprecator.add(FakeDirectory, FakeDirectory.get_entry, 'GetEntry') +Deprecator.add(FakeDirectory, FakeDirectory.set_contents, 'SetContents') +Deprecator.add(FakeDirectory, FakeDirectory.remove_entry, 'RemoveEntry') + + class FakeDirectoryFromRealDirectory(FakeDirectory): """Represents a fake directory copied from the real file system. - + The contents of the directory are read on demand only. """ @@ -824,11 +899,12 @@ def contents(self): read_only=self.read_only) return self.byte_contents - def GetSize(self): + @property + def size(self): # we cannot get the size until the contents are loaded if not self.contents_read: return 0 - return super(FakeDirectoryFromRealDirectory, self).GetSize() + return super(FakeDirectoryFromRealDirectory, self).size class FakeFilesystem(object): @@ -888,7 +964,7 @@ def __init__(self, path_separator=os.path.sep, total_size=None): self._last_ino = 0 self._last_dev = 0 self.mount_points = {} - self.AddMountPoint(self.root.name, total_size) + self.add_mount_point(self.root.name, total_size) self._add_standard_streams() def raise_os_error(self, errno, winerror, message, filename=''): @@ -920,11 +996,11 @@ def _alternative_path_separator(self, path): """Return the alternative path separator as the same type as path""" return self._matching_string(path, self.alternative_path_separator) - def _IsLinkSupported(self): + def _is_link_supported(self): # Python 3.2 supports links in Windows return not self.is_windows_fs or sys.version_info >= (3, 2) - def AddMountPoint(self, path, total_size=None): + def add_mount_point(self, path, total_size=None): """Add a new mount point for a filesystem device. The mount point gets a new unique device number. @@ -940,7 +1016,7 @@ def AddMountPoint(self, path, total_size=None): Raises: OSError: if trying to mount an existing mount point again. """ - path = self.NormalizePath(path) + path = self.absnormpath(path) if path in self.mount_points: raise OSError(errno.EEXIST, 'Mount point cannot be added twice', path) @@ -949,17 +1025,17 @@ def AddMountPoint(self, path, total_size=None): 'idev': self._last_dev, 'total_size': total_size, 'used_size': 0 } # special handling for root path: has been created before - root_dir = self.root if path == self.root.name else self.CreateDirectory(path) + root_dir = self.root if path == self.root.name else self.create_dir(path) root_dir.st_dev = self._last_dev return self.mount_points[path] - def _AutoMountDriveIfNeeded(self, path, force=False): - if self.is_windows_fs and (force or not self._MountPointForPath(path)): - drive = self.SplitDrive(path)[0] + def _auto_mount_drive_if_needed(self, path, force=False): + if self.is_windows_fs and (force or not self._mount_point_for_path(path)): + drive = self.splitdrive(path)[0] if drive: - return self.AddMountPoint(path=drive) + return self.add_mount_point(path=drive) - def _MountPointForPath(self, path): + def _mount_point_for_path(self, path): def to_str(string): """Convert the str, unicode or byte object to a str using the default encoding.""" @@ -970,11 +1046,11 @@ def to_str(string): else: return string.decode(locale.getpreferredencoding(False)) - path = self.NormalizePath(self.NormalizeCase(path)) + path = self.absnormpath(self._original_path(path)) if path in self.mount_points: return self.mount_points[path] mount_path = self._matching_string(path, '') - drive = self.SplitDrive(path)[:1] + drive = self.splitdrive(path)[:1] for root_path in self.mount_points: root_path = self._matching_string(path, root_path) if drive and not root_path.startswith(drive): @@ -983,16 +1059,16 @@ def to_str(string): mount_path = root_path if mount_path: return self.mount_points[to_str(mount_path)] - mount_point = self._AutoMountDriveIfNeeded(path, force=True) + mount_point = self._auto_mount_drive_if_needed(path, force=True) assert mount_point return mount_point - def _MountPointForDevice(self, idev): + def _mount_point_for_device(self, idev): for mount_point in self.mount_points.values(): if mount_point['idev'] == idev: return mount_point - def GetDiskUsage(self, path=None): + def get_disk_usage(self, path=None): """Return the total, used and free disk space in bytes as named tuple, or placeholder values simulating unlimited space if not set. Note: This matches the return value of shutil.disk_usage(). @@ -1006,13 +1082,13 @@ def GetDiskUsage(self, path=None): if path is None: mount_point = self.mount_points[self.root.name] else: - mount_point = self._MountPointForPath(path) + mount_point = self._mount_point_for_path(path) if mount_point and mount_point['total_size'] is not None: return DiskUsage(mount_point['total_size'], mount_point['used_size'], mount_point['total_size'] - mount_point['used_size']) return DiskUsage(1024 * 1024 * 1024 * 1024, 0, 1024 * 1024 * 1024 * 1024) - def SetDiskUsage(self, total_size, path=None): + def set_disk_usage(self, total_size, path=None): """Changes the total size of the file system, preserving the used space. Example usage: set the size of an auto-mounted Windows drive. @@ -1028,14 +1104,14 @@ def SetDiskUsage(self, total_size, path=None): """ if path is None: path = self.root.name - mount_point = self._MountPointForPath(path) + mount_point = self._mount_point_for_path(path) if mount_point['total_size'] is not None and mount_point['used_size'] > total_size: raise IOError(errno.ENOSPC, 'Fake file system: cannot change size to %r bytes - ' 'used space is larger' % total_size, path) mount_point['total_size'] = total_size - def ChangeDiskUsage(self, usage_change, file_path, st_dev): + def change_disk_usage(self, usage_change, file_path, st_dev): """Change the used disk space by the given amount. Args: @@ -1049,7 +1125,7 @@ def ChangeDiskUsage(self, usage_change, file_path, st_dev): Raises: IOError: if usage_change exceeds the free file system space """ - mount_point = self._MountPointForDevice(st_dev) + mount_point = self._mount_point_for_device(st_dev) if mount_point: total_size = mount_point['total_size'] if total_size is not None: @@ -1060,7 +1136,7 @@ def ChangeDiskUsage(self, usage_change, file_path, st_dev): % usage_change, file_path) mount_point['used_size'] += usage_change - def GetStat(self, entry_path, follow_symlinks=True): + def stat(self, entry_path, follow_symlinks=True): """Return the os.stat-like tuple for the FakeFile object of entry_path. Args: @@ -1076,14 +1152,14 @@ def GetStat(self, entry_path, follow_symlinks=True): """ # stat should return the tuple representing return value of os.stat try: - file_object = self.ResolveObject( + file_object = self.resolve( entry_path, follow_symlinks, allow_fd=True) return file_object.stat_result.copy() except IOError as io_error: self.raise_os_error(io_error.errno, io_error.errno, io_error.strerror, entry_path) - def ChangeMode(self, path, mode, follow_symlinks=True): + def chmod(self, path, mode, follow_symlinks=True): """Change the permissions of a file as encoded in integer mode. Args: @@ -1093,7 +1169,7 @@ def ChangeMode(self, path, mode, follow_symlinks=True): the link itself is affected instead of the linked object. """ try: - file_object = self.ResolveObject(path, follow_symlinks, allow_fd=True) + file_object = self.resolve(path, follow_symlinks, allow_fd=True) except IOError as io_error: if io_error.errno == errno.ENOENT: raise OSError(errno.ENOENT, @@ -1110,7 +1186,7 @@ def ChangeMode(self, path, mode, follow_symlinks=True): (mode & PERM_ALL)) file_object.st_ctime = time.time() - def UpdateTime(self, path, times=None, ns=None, follow_symlinks=True): + def utime(self, path, times=None, ns=None, follow_symlinks=True): """Change the access and modified times of a file. Args: @@ -1140,7 +1216,7 @@ def UpdateTime(self, path, times=None, ns=None, follow_symlinks=True): raise TypeError("utime: 'ns' must be a tuple of two ints") try: - file_object = self.ResolveObject(path, follow_symlinks, allow_fd=True) + file_object = self.resolve(path, follow_symlinks, allow_fd=True) except IOError as io_error: if io_error.errno == errno.ENOENT: raise OSError(errno.ENOENT, @@ -1166,6 +1242,8 @@ def UpdateTime(self, path, times=None, ns=None, follow_symlinks=True): file_object.st_atime = current_time file_object.st_mtime = current_time + + @Deprecator def SetIno(self, path, st_ino): """Set the self.st_ino attribute of file at 'path'. Note that a unique inode is assigned automatically to a new fake file. @@ -1176,10 +1254,11 @@ def SetIno(self, path, st_ino): path: Path to file. st_ino: The desired inode. """ - self.GetObject(path).SetIno(st_ino) + self.get_object(path).st_ino = st_ino - def AddOpenFile(self, file_obj): + def _add_open_file(self, file_obj): """Add file_obj to the list of open files on the filesystem. + Used internally to manage open files. The position in the self.open_files array is the file descriptor number. @@ -1197,7 +1276,7 @@ def AddOpenFile(self, file_obj): self.open_files.append(file_obj) return len(self.open_files) - 1 - def CloseOpenFile(self, file_des): + def _close_open_file(self, file_des): """Remove file object with given descriptor from the list of open files. @@ -1210,7 +1289,7 @@ def CloseOpenFile(self, file_des): self.open_files[file_des] = None heapq.heappush(self._free_fd_heap, file_des) - def GetOpenFile(self, file_des): + def _get_open_file(self, file_des): """Return an open file. Args: @@ -1225,12 +1304,11 @@ def GetOpenFile(self, file_des): """ if not is_int_type(file_des): raise TypeError('an integer is required') - if (file_des >= len(self.open_files) or - self.open_files[file_des] is None): + if (file_des >= len(self.open_files) or self.open_files[file_des] is None): raise OSError(errno.EBADF, 'Bad file descriptor', file_des) return self.open_files[file_des] - def HasOpenFile(self, file_object): + def has_open_file(self, file_object): """Return True if the given file object is in the list of open files. Args: @@ -1242,9 +1320,10 @@ def HasOpenFile(self, file_object): return (file_object in [wrapper.GetObject() for wrapper in self.open_files if wrapper]) - def NormalizePathSeparator(self, path): + def normcase(self, path): """Replace all appearances of alternative path separator with path separator. + Do nothing if no alternative separator is set. Args: @@ -1260,12 +1339,12 @@ def NormalizePathSeparator(self, path): return path.replace(self._alternative_path_separator(path), self._path_separator(path)) - def CollapsePath(self, path): + def normpath(self, path): """Mimic os.path.normpath using the specified path_separator. Mimics os.path.normpath using the path_separator that was specified for this FakeFilesystem. Normalizes the path, but unlike the method - NormalizePath, does not make it absolute. Eliminates dot components + absnormpath, does not make it absolute. Eliminates dot components (. and ..) and combines repeated path separators (//). Initial .. components are left in place for relative paths. If the result is an empty path, '.' is returned instead. @@ -1282,8 +1361,8 @@ def CollapsePath(self, path): (str) A copy of path with empty components and dot components removed. """ - path = self.NormalizePathSeparator(path) - drive, path = self.SplitDrive(path) + path = self.normcase(path) + drive, path = self.splitdrive(path) sep = self._path_separator(path) is_absolute_path = path.startswith(sep) ends_with_path_sep = path.endswith(sep) @@ -1310,7 +1389,7 @@ def CollapsePath(self, path): collapsed_path = sep + collapsed_path return drive + collapsed_path or dot - def NormalizeCase(self, path): + def _original_path(self, path): """Return a normalized case version of the given path for case-insensitive file systems. For case-sensitive file systems, return path unchanged. @@ -1332,13 +1411,13 @@ def components_to_path(): if self.is_case_sensitive or not path: return path - path_components = self.GetPathComponents(path) + path_components = self._path_components(path) normalized_components = [] current_dir = self.root for component in path_components: if not isinstance(current_dir, FakeDirectory): return components_to_path() - dir_name, current_dir = self._DirectoryContent(current_dir, component) + dir_name, current_dir = self._directory_content(current_dir, component) if current_dir is None or ( isinstance(current_dir, FakeDirectory) and current_dir._byte_contents is None and @@ -1347,7 +1426,7 @@ def components_to_path(): normalized_components.append(dir_name) return components_to_path() - def NormalizePath(self, path): + def absnormpath(self, path): """Absolutize and minimalize the given path. Forces all relative paths to be absolute, and normalizes the path to @@ -1360,11 +1439,11 @@ def NormalizePath(self, path): The normalized path relative to the current working directory, or the root directory if path is empty. """ - path = self.NormalizePathSeparator(path) + path = self.normcase(path) cwd = self._matching_string(path, self.cwd) if not path: path = self.path_separator - elif not self._StartsWithRootPath(path): + elif not self._starts_with_root_path(path): # Prefix relative paths with cwd, if cwd is not root. root_name = self._matching_string(path, self.root.name) empty = self._matching_string(path, '') @@ -1372,12 +1451,12 @@ def NormalizePath(self, path): (cwd != root_name and cwd or empty, path)) if path == self._matching_string(path, '.'): path = cwd - return self.CollapsePath(path) + return self.normpath(path) - def SplitPath(self, path): - """Mimic os.path.split using the specified path_separator. + def splitpath(self, path): + """Mimic os.path.splitpath using the specified path_separator. - Mimics os.path.split using the path_separator that was specified + Mimics os.path.splitpath using the path_separator that was specified for this FakeFilesystem. Args: @@ -1387,7 +1466,7 @@ def SplitPath(self, path): (str) A duple (pathname, basename) for which pathname does not end with a slash, and basename does not contain a slash. """ - path = self.NormalizePathSeparator(path) + path = self.normcase(path) sep = self._path_separator(path) path_components = path.split(sep) if not path_components: @@ -1418,14 +1497,14 @@ def SplitPath(self, path): # Root path. Collapse all leading separators. return (sep, basename) - def SplitDrive(self, path): + def splitdrive(self, path): """Splits the path into the drive part and the rest of the path. Taken from Windows specific implementation in Python 3.5 and slightly adapted. Args: - path: the full path to be split. + path: the full path to be splitpath. Returns: A tuple of the drive part and the rest of the path, or of @@ -1436,7 +1515,7 @@ def SplitDrive(self, path): path = os.fspath(path) if self.is_windows_fs: if len(path) >= 2: - path = self.NormalizePathSeparator(path) + path = self.normcase(path) sep = self._path_separator(path) # UNC path handling is here since Python 2.7.8, # back-ported from Python 3 @@ -1458,16 +1537,16 @@ def SplitDrive(self, path): return path[:2], path[2:] return path[:0], path - def _JoinPathsWithDriveSupport(self, *all_paths): + def _join_paths_with_drive_support(self, *all_paths): """Taken from Python 3.5 os.path.join() code in ntpath.py and slightly adapted""" base_path = all_paths[0] paths_to_add = all_paths[1:] sep = self._path_separator(base_path) seps = [sep, self._alternative_path_separator(base_path)] - result_drive, result_path = self.SplitDrive(base_path) + result_drive, result_path = self.splitdrive(base_path) for path in paths_to_add: - drive_part, path_part = self.SplitDrive(path) + drive_part, path_part = self.splitdrive(path) if path_part and path_part[:1] in seps: # Second path is absolute if drive_part or not result_drive: @@ -1493,7 +1572,7 @@ def _JoinPathsWithDriveSupport(self, *all_paths): return result_drive + sep + result_path return result_drive + result_path - def JoinPaths(self, *paths): + def joinpaths(self, *paths): """Mimic os.path.join using the specified path_separator. Args: @@ -1508,11 +1587,11 @@ def JoinPaths(self, *paths): if len(paths) == 1: return paths[0] if self.is_windows_fs: - return self._JoinPathsWithDriveSupport(*paths) + return self._join_paths_with_drive_support(*paths) joined_path_segments = [] sep = self._path_separator(paths[0]) for path_segment in paths: - if self._StartsWithRootPath(path_segment): + if self._starts_with_root_path(path_segment): # An absolute path joined_path_segments = [path_segment] else: @@ -1523,21 +1602,21 @@ def JoinPaths(self, *paths): joined_path_segments.append(path_segment) return self._matching_string(paths[0], '').join(joined_path_segments) - def GetPathComponents(self, path): + def _path_components(self, path): """Breaks the path into a list of component names. Does not include the root directory as a component, as all paths are considered relative to the root directory for the FakeFilesystem. Callers should basically follow this pattern: - >>> file_path = self.NormalizePath(file_path) - >>> path_components = self.GetPathComponents(file_path) + >>> file_path = self.absnormpath(file_path) + >>> path_components = self._path_components(file_path) >>> current_dir = self.root >>> for component in path_components: >>> if component not in current_dir.contents: >>> raise IOError >>> DoStuffWithComponent(current_dir, component) - >>> current_dir = current_dir.GetEntry(component) + >>> current_dir = current_dir.get_entry(component) Args: path: Path to tokenize. @@ -1547,7 +1626,7 @@ def GetPathComponents(self, path): """ if not path or path == self._path_separator(path): return [] - drive, path = self.SplitDrive(path) + drive, path = self.splitdrive(path) path_components = path.split(self._path_separator(path)) assert drive or path_components if not path_components[0]: @@ -1557,7 +1636,7 @@ def GetPathComponents(self, path): path_components.insert(0, drive) return path_components - def StartsWithDriveLetter(self, file_path): + def _starts_with_drive_letter(self, file_path): """Return True if file_path starts with a drive letter. Args: @@ -1571,25 +1650,25 @@ def StartsWithDriveLetter(self, file_path): return (self.is_windows_fs and len(file_path) >= 2 and file_path[:1].isalpha and (file_path[1:2]) == colon) - def _StartsWithRootPath(self, file_path): + def _starts_with_root_path(self, file_path): root_name = self._matching_string(file_path, self.root.name) return (file_path.startswith(root_name) or not self.is_case_sensitive and file_path.lower().startswith( root_name.lower()) or - self.StartsWithDriveLetter(file_path)) + self._starts_with_drive_letter(file_path)) - def _IsRootPath(self, file_path): + def _is_root_path(self, file_path): root_name = self._matching_string(file_path, self.root.name) return (file_path == root_name or not self.is_case_sensitive and file_path.lower() == root_name.lower() or - len(file_path) == 2 and self.StartsWithDriveLetter(file_path)) + len(file_path) == 2 and self._starts_with_drive_letter(file_path)) - def _EndsWithPathSeparator(self, file_path): + def _ends_with_path_separator(self, file_path): return file_path and (file_path.endswith(self._path_separator(file_path)) or self.alternative_path_separator is not None and file_path.endswith(self._alternative_path_separator(file_path))) - def _DirectoryContent(self, directory, component): + def _directory_content(self, directory, component): if not isinstance(directory, FakeDirectory): return None, None if component in directory.contents: @@ -1603,7 +1682,7 @@ def _DirectoryContent(self, directory, component): return None, None - def Exists(self, file_path, check_link=False): + def exists(self, file_path, check_link=False): """Return true if a path points to an existing file system object. Args: @@ -1624,15 +1703,15 @@ def Exists(self, file_path, check_link=False): if not file_path: return False try: - file_path = self.ResolvePath(file_path) + file_path = self.resolve_path(file_path) except (IOError, OSError): return False if file_path == self.root.name: return True - path_components = self.GetPathComponents(file_path) + path_components = self._path_components(file_path) current_dir = self.root for component in path_components: - current_dir = self._DirectoryContent(current_dir, component)[1] + current_dir = self._directory_content(current_dir, component)[1] if not current_dir: return False return True @@ -1643,7 +1722,7 @@ def _to_string(path): path = path.decode(locale.getpreferredencoding(False)) return path - def ResolvePath(self, file_path, allow_fd=False, raw_io=True): + def resolve_path(self, file_path, allow_fd=False, raw_io=True): """Follow a path, resolving symlinks. ResolvePath traverses the filesystem along the specified file path, @@ -1682,26 +1761,26 @@ def ResolvePath(self, file_path, allow_fd=False, raw_io=True): IOError: if file_path is '' or a part of the path doesn't exist. """ - def _ComponentsToPath(component_folders): + def _components_to_path(component_folders): sep = self._path_separator( component_folders[0]) if component_folders else self.path_separator path = sep.join(component_folders) - if not self._StartsWithRootPath(path): + if not self._starts_with_root_path(path): path = sep + path return path - def _ValidRelativePath(file_path): + def _valid_relative_path(file_path): if self.is_windows_fs: return True slash_dotdot = self._matching_string( file_path, self.path_separator + '..') while file_path and slash_dotdot in file_path: file_path = file_path[:file_path.rfind(slash_dotdot)] - if not self.Exists(self.NormalizePath(file_path)): + if not self.exists(self.absnormpath(file_path)): return False return True - def _FollowLink(link_path_components, link): + def _follow_link(link_path_components, link): """Follow a link w.r.t. a path resolved so far. The component is either a real file, which is a no-op, or a @@ -1742,36 +1821,35 @@ def _FollowLink(link_path_components, link): link_path = sep.join(components) # Don't call self.NormalizePath(), as we don't want to prepend # self.cwd. - return self.CollapsePath(link_path) + return self.normpath(link_path) if (allow_fd and sys.version_info >= (3, 3) and isinstance(file_path, int)): - return self.GetOpenFile(file_path).GetObject().GetPath() - + return self._get_open_file(file_path).get_object().path if sys.version_info >= (3, 6): file_path = os.fspath(file_path) if file_path is None: # file.open(None) raises TypeError, so mimic that. raise TypeError('Expected file system path string, received None') file_path = self._to_string(file_path) - if not file_path or not _ValidRelativePath(file_path): + if not file_path or not _valid_relative_path(file_path): # file.open('') raises IOError, so mimic that, and validate that # all parts of a relative path exist. raise IOError(errno.ENOENT, 'No such file or directory: \'%s\'' % file_path) - file_path = self.NormalizePath(self.NormalizeCase(file_path)) - if self._IsRootPath(file_path): + file_path = self.absnormpath(self._original_path(file_path)) + if self._is_root_path(file_path): return file_path current_dir = self.root - path_components = self.GetPathComponents(file_path) + path_components = self._path_components(file_path) resolved_components = [] link_depth = 0 while path_components: component = path_components.pop(0) resolved_components.append(component) - current_dir = self._DirectoryContent(current_dir, component)[1] + current_dir = self._directory_content(current_dir, component)[1] if current_dir is None: # The component of the path at this point does not actually # exist in the folder. We can't resolve the path any more. @@ -1783,7 +1861,7 @@ def _FollowLink(link_path_components, link): break # Resolve any possible symlinks in the current path component. - if stat.S_ISLNK(current_dir.st_mode): + if S_ISLNK(current_dir.st_mode): # This link_depth check is not really meant to be an accurate # check. It is just a quick hack to prevent us from looping # forever on cycles. @@ -1792,19 +1870,19 @@ def _FollowLink(link_path_components, link): raise error_class( errno.ELOOP, 'Too many levels of symbolic links: \'%s\'' % - _ComponentsToPath(resolved_components)) - link_path = _FollowLink(resolved_components, current_dir) + _components_to_path(resolved_components)) + link_path = _follow_link(resolved_components, current_dir) # Following the link might result in the complete replacement # of the current_dir, so we evaluate the entire resulting path. - target_components = self.GetPathComponents(link_path) + target_components = self._path_components(link_path) path_components = target_components + path_components resolved_components = [] current_dir = self.root link_depth += 1 - return _ComponentsToPath(resolved_components) + return _components_to_path(resolved_components) - def GetObjectFromNormalizedPath(self, file_path): + def get_object_from_normpath(self, file_path): """Search for the specified filesystem object within the fake filesystem. @@ -1822,14 +1900,15 @@ def GetObjectFromNormalizedPath(self, file_path): file_path = os.fspath(file_path) if file_path == self.root.name: return self.root - file_path = self.NormalizeCase(file_path) - path_components = self.GetPathComponents(file_path) + + file_path = self._original_path(file_path) + path_components = self._path_components(file_path) target_object = self.root try: for component in path_components: - if stat.S_ISLNK(target_object.st_mode): - target_object = self.ResolveObject(target_object.contents) - if not stat.S_ISDIR(target_object.st_mode): + if S_ISLNK(target_object.st_mode): + target_object = self.resolve(target_object.contents) + if not S_ISDIR(target_object.st_mode): if not self.is_windows_fs: raise IOError(errno.ENOTDIR, 'Not a directory in fake filesystem', @@ -1837,14 +1916,14 @@ def GetObjectFromNormalizedPath(self, file_path): raise IOError(errno.ENOENT, 'No such file or directory in fake filesystem', file_path) - target_object = target_object.GetEntry(component) + target_object = target_object.get_entry(component) except KeyError: raise IOError(errno.ENOENT, 'No such file or directory in fake filesystem', file_path) return target_object - def GetObject(self, file_path): + def get_object(self, file_path): """Search for the specified filesystem object within the fake filesystem. @@ -1859,10 +1938,10 @@ def GetObject(self, file_path): """ if sys.version_info >= (3, 6): file_path = os.fspath(file_path) - file_path = self.NormalizePath(file_path) - return self.GetObjectFromNormalizedPath(file_path) + file_path = self.absnormpath(self._original_path(file_path)) + return self.get_object_from_normpath(file_path) - def ResolveObject(self, file_path, follow_symlinks=True, allow_fd=False): + def resolve(self, file_path, follow_symlinks=True, allow_fd=False): """Search for the specified filesystem object, resolving all links. Args: @@ -1879,17 +1958,17 @@ def ResolveObject(self, file_path, follow_symlinks=True, allow_fd=False): """ if isinstance(file_path, int): if allow_fd and sys.version_info >= (3, 3): - return self.GetOpenFile(file_path).GetObject() + return self._get_open_file(file_path).get_object() raise TypeError('path should be string, bytes or ' 'os.PathLike (if supported), not int') if follow_symlinks: if sys.version_info >= (3, 6): file_path = os.fspath(file_path) - return self.GetObjectFromNormalizedPath(self.ResolvePath(file_path)) - return self.LResolveObject(file_path) + return self.get_object_from_normpath(self.resolve_path(file_path)) + return self.lresolve(file_path) - def LResolveObject(self, path): + def lresolve(self, path): """Search for the specified object, resolving only parent links. This is analogous to the stat/lstat difference. This resolves links *to* @@ -1915,13 +1994,13 @@ def LResolveObject(self, path): alt_sep = self._alternative_path_separator(path) if path.endswith(sep) or (alt_sep and path.endswith(alt_sep)): path = path[:-1] - path = self.NormalizeCase(path) + path = self._original_path(path) - parent_directory, child_name = self.SplitPath(path) + parent_directory, child_name = self.splitpath(path) if not parent_directory: parent_directory = self.cwd try: - parent_obj = self.ResolveObject(parent_directory) + parent_obj = self.resolve(parent_directory) assert parent_obj if not isinstance(parent_obj, FakeDirectory): if not self.is_windows_fs and isinstance(parent_obj, FakeFile): @@ -1930,13 +2009,13 @@ def LResolveObject(self, path): raise IOError(errno.ENOENT, 'No such file or directory in fake filesystem', path) - return parent_obj.GetEntry(child_name) + return parent_obj.get_entry(child_name) except KeyError: raise IOError(errno.ENOENT, 'No such file or directory in the fake filesystem', path) - def AddObject(self, file_path, file_object, error_class=OSError): + def add_object(self, file_path, file_object, error_class=OSError): """Add a fake file or directory into the filesystem at file_path. Args: @@ -1952,15 +2031,15 @@ def AddObject(self, file_path, file_object, error_class=OSError): if not file_path: target_directory = self.root else: - target_directory = self.ResolveObject(file_path) - if not stat.S_ISDIR(target_directory.st_mode): + target_directory = self.resolve(file_path) + if not S_ISDIR(target_directory.st_mode): error = errno.ENOENT if self.is_windows_fs else errno.ENOTDIR raise error_class(error, 'Not a directory in the fake filesystem', file_path) - target_directory.AddEntry(file_object) + target_directory.add_entry(file_object) - def RenameObject(self, old_file_path, new_file_path, force_replace=False): + def rename(self, old_file_path, new_file_path, force_replace=False): """Renames a FakeFile object at old_file_path to new_file_path, preserving all properties. @@ -1985,38 +2064,38 @@ def RenameObject(self, old_file_path, new_file_path, force_replace=False): OSError: if the file would be moved to another filesystem (e.g. mount point). """ - old_file_path = self.NormalizeCase(self.NormalizePath(old_file_path)) - new_file_path = self.NormalizePath(new_file_path) - if not self.Exists(old_file_path, check_link=True): + old_file_path = self._original_path(self.absnormpath(old_file_path)) + new_file_path = self.absnormpath(new_file_path) + if not self.exists(old_file_path, check_link=True): self.raise_os_error(errno.ENOENT, 2, 'Fake filesystem object: ' 'can not rename nonexistent file', old_file_path) - old_object = self.LResolveObject(old_file_path) + old_object = self.lresolve(old_file_path) if not self.is_windows_fs: - if (self.IsDir(old_file_path, follow_symlinks=False) and - self.IsLink(new_file_path)): + if (self.isdir(old_file_path, follow_symlinks=False) and + self.islink(new_file_path)): raise OSError(errno.ENOTDIR, 'Cannot rename directory to symlink', new_file_path) - if (self.IsDir(new_file_path, follow_symlinks=False) and - self.IsLink(old_file_path)): + if (self.isdir(new_file_path, follow_symlinks=False) and + self.islink(old_file_path)): raise OSError(errno.EISDIR, 'Cannot rename symlink to directory', new_file_path) - if self.Exists(new_file_path, check_link=True): + if self.exists(new_file_path, check_link=True): if old_file_path == new_file_path: return # Nothing to do here. - new_object = self.GetObject(new_file_path) + new_object = self.get_object(new_file_path) if old_object == new_object: doRename = old_file_path.lower() == new_file_path.lower() if not doRename: try: - real_old_path = self.ResolvePath(old_file_path) - real_new_path = self.ResolvePath(new_file_path) + real_old_path = self.resolve_path(old_file_path) + real_new_path = self.resolve_path(new_file_path) if (real_new_path == real_old_path and new_file_path.lower() != real_new_path.lower()): doRename = not self.is_macos @@ -2025,9 +2104,9 @@ def RenameObject(self, old_file_path, new_file_path, force_replace=False): if doRename: # only case is changed in case-insensitive file system # - do the rename - parent, file_name = self.SplitPath(new_file_path) - new_file_path = self.JoinPaths( - self.NormalizeCase(parent), file_name) + parent, file_name = self.splitpath(new_file_path) + new_file_path = self.joinpaths( + self._original_path(parent), file_name) except (IOError, OSError): # ResolvePath may fail due to symlink loop issues or similar - # in this case just assume the paths different @@ -2036,8 +2115,8 @@ def RenameObject(self, old_file_path, new_file_path, force_replace=False): # hard links to the same file - nothing to do return - elif (stat.S_ISDIR(new_object.st_mode) or - stat.S_ISLNK(new_object.st_mode)): + elif (S_ISDIR(new_object.st_mode) or + S_ISLNK(new_object.st_mode)): if self.is_windows_fs: if force_replace: raise OSError(errno.EACCES, @@ -2049,18 +2128,18 @@ def RenameObject(self, old_file_path, new_file_path, force_replace=False): 'Fake filesystem object: ' 'can not rename to existing directory', new_file_path) - if not stat.S_ISLNK(new_object.st_mode): + if not S_ISLNK(new_object.st_mode): if new_object.contents: raise OSError(errno.ENOTEMPTY, 'Fake filesystem object: ' 'can not rename to non-empty directory', new_file_path) - if stat.S_ISREG(old_object.st_mode): + if S_ISREG(old_object.st_mode): raise OSError(errno.EISDIR, 'Fake filesystem object: ' 'cannot rename file to directory', new_file_path) - elif stat.S_ISDIR(old_object.st_mode): + elif S_ISDIR(old_object.st_mode): error = errno.EEXIST if self.is_windows_fs else errno.ENOTDIR raise OSError(error, 'Fake filesystem object: ' @@ -2073,41 +2152,41 @@ def RenameObject(self, old_file_path, new_file_path, force_replace=False): new_file_path) else: try: - self.RemoveObject(new_file_path) + self.remove_object(new_file_path) except IOError as exc: raise OSError(exc.errno, exc.strerror, exc.filename) - old_dir, old_name = self.SplitPath(old_file_path) - new_dir, new_name = self.SplitPath(new_file_path) - if not self.Exists(new_dir): + old_dir, old_name = self.splitpath(old_file_path) + new_dir, new_name = self.splitpath(new_file_path) + if not self.exists(new_dir): raise OSError(errno.ENOENT, 'No such fake directory', new_dir) - old_dir_object = self.ResolveObject(old_dir) - new_dir_object = self.ResolveObject(new_dir) + old_dir_object = self.resolve(old_dir) + new_dir_object = self.resolve(new_dir) if old_dir_object.st_dev != new_dir_object.st_dev: raise OSError(errno.EXDEV, 'Fake filesystem object: ' 'cannot rename across file systems', old_file_path) - if not stat.S_ISDIR(new_dir_object.st_mode): + if not S_ISDIR(new_dir_object.st_mode): raise OSError(errno.EACCES if self.is_windows_fs else errno.ENOTDIR, 'Fake filesystem object: ' 'target parent is not a directory', new_file_path) - if new_dir_object.HasParentObject(old_object): + if new_dir_object.has_parent_object(old_object): raise OSError(errno.EINVAL, 'Fake filesystem object: invalid target for rename', new_file_path) - object_to_rename = old_dir_object.GetEntry(old_name) - old_dir_object.RemoveEntry(old_name, recursive=False) + object_to_rename = old_dir_object.get_entry(old_name) + old_dir_object.remove_entry(old_name, recursive=False) object_to_rename.name = new_name new_name = new_dir_object._normalized_entryname(new_name) if new_name in new_dir_object.contents: # in case of overwriting remove the old entry first - new_dir_object.RemoveEntry(new_name) - new_dir_object.AddEntry(object_to_rename) + new_dir_object.remove_entry(new_name) + new_dir_object.add_entry(object_to_rename) - def RemoveObject(self, file_path): + def remove_object(self, file_path): """Remove an existing file or directory. Args: @@ -2118,14 +2197,14 @@ def RemoveObject(self, file_path): if part of the path refers to something other than a directory. OSError: if the directory is in use (eg, if it is '/'). """ - file_path = self.NormalizePath(self.NormalizeCase(file_path)) - if self._IsRootPath(file_path): + file_path = self.absnormpath(self._original_path(file_path)) + if self._is_root_path(file_path): raise OSError(errno.EBUSY, 'Fake device or resource busy', file_path) try: - dirname, basename = self.SplitPath(file_path) - target_directory = self.ResolveObject(dirname) - target_directory.RemoveEntry(basename) + dirname, basename = self.splitpath(file_path) + target_directory = self.resolve(dirname) + target_directory.remove_entry(basename) except KeyError: raise IOError(errno.ENOENT, 'No such file or directory in the fake filesystem', @@ -2135,7 +2214,7 @@ def RemoveObject(self, file_path): 'Not a directory in the fake filesystem', file_path) - def CreateDirectory(self, directory_path, perm_bits=PERM_DEF): + def create_dir(self, directory_path, perm_bits=PERM_DEF): """Create directory_path, and all the parent directories. Helper method to set up your test faster. @@ -2150,40 +2229,40 @@ def CreateDirectory(self, directory_path, perm_bits=PERM_DEF): Raises: OSError: if the directory already exists. """ - directory_path = self.NormalizePath(directory_path) - self._AutoMountDriveIfNeeded(directory_path) - if self.Exists(directory_path, check_link=True): + directory_path = self.absnormpath(directory_path) + self._auto_mount_drive_if_needed(directory_path) + if self.exists(directory_path, check_link=True): raise OSError(errno.EEXIST, 'Directory exists in fake filesystem', directory_path) - path_components = self.GetPathComponents(directory_path) + path_components = self._path_components(directory_path) current_dir = self.root new_dirs = [] for component in path_components: - directory = self._DirectoryContent(current_dir, component)[1] + directory = self._directory_content(current_dir, component)[1] if not directory: new_dir = FakeDirectory(component, filesystem=self) new_dirs.append(new_dir) - current_dir.AddEntry(new_dir) + current_dir.add_entry(new_dir) current_dir = new_dir else: - if stat.S_ISLNK(directory.st_mode): - directory = self.ResolveObject(directory.contents) + if S_ISLNK(directory.st_mode): + directory = self.resolve(directory.contents) current_dir = directory - if directory.st_mode & stat.S_IFDIR != stat.S_IFDIR: - raise OSError(errno.ENOTDIR, 'Not a directory', current_dir.GetPath()) + if directory.st_mode & S_IFDIR != S_IFDIR: + raise OSError(errno.ENOTDIR, 'Not a directory', current_dir.path) # set the permission after creating the directories # to allow directory creation inside a read-only directory for new_dir in new_dirs: - new_dir.st_mode = stat.S_IFDIR | perm_bits + new_dir.st_mode = S_IFDIR | perm_bits self._last_ino += 1 - current_dir.SetIno(self._last_ino) + current_dir.st_ino = self._last_ino return current_dir - def CreateFile(self, file_path, st_mode=stat.S_IFREG | PERM_DEF_FILE, + def create_file(self, file_path, st_mode=S_IFREG | PERM_DEF_FILE, contents='', st_size=None, create_missing_dirs=True, apply_umask=False, encoding=None, errors=None): """Create file_path, including all the parent directories along the way. @@ -2208,7 +2287,7 @@ def CreateFile(self, file_path, st_mode=stat.S_IFREG | PERM_DEF_FILE, IOError: if the file already exists. IOError: if the containing directory is required and missing. """ - return self.CreateFileInternally( + return self.create_file_internally( file_path, st_mode, contents, st_size, create_missing_dirs, apply_umask, encoding, errors) @@ -2238,9 +2317,9 @@ def add_real_file(self, file_path, read_only=True): Further, Windows offers the option to enable atime, and older \ versions of Linux may also modify atime. """ - return self.CreateFileInternally(file_path, - read_from_real_fs=True, - read_only=read_only) + return self.create_file_internally(file_path, + read_from_real_fs=True, + read_only=read_only) def add_real_directory(self, dir_path, read_only=True, lazy_read=True): """Create a fake directory corresponding to the real directory at the specified @@ -2271,16 +2350,16 @@ def add_real_directory(self, dir_path, read_only=True, lazy_read=True): raise IOError(errno.ENOENT, 'No such directory', dir_path) if lazy_read: parent_path = os.path.split(dir_path)[0] - if self.Exists(parent_path): - parent_dir = self.GetObject(parent_path) + if self.exists(parent_path): + parent_dir = self.get_object(parent_path) else: - parent_dir = self.CreateDirectory(parent_path) + parent_dir = self.create_dir(parent_path) new_dir = FakeDirectoryFromRealDirectory(dir_path, filesystem=self, read_only=read_only) - parent_dir.AddEntry(new_dir) + parent_dir.add_entry(new_dir) self._last_ino += 1 - new_dir.SetIno(self._last_ino) + new_dir.st_ino = self._last_ino else: - new_dir = self.CreateDirectory(dir_path) + new_dir = self.create_dir(dir_path) for base, _, files in os.walk(dir_path): for fileEntry in files: self.add_real_file(os.path.join(base, fileEntry), read_only) @@ -2300,8 +2379,10 @@ def add_real_paths(self, path_list, read_only=True, lazy_dir_read=True): (see `add_real_directory`) Raises: - OSError: if any of the files and directories in the list does not exist in the real file system. - OSError: if any of the files and directories in the list already exists in the fake file system. + OSError: if any of the files and directories in the list + does not exist in the real file system. + OSError: if any of the files and directories in the list + already exists in the fake file system. """ for path in path_list: if os.path.isdir(path): @@ -2309,10 +2390,10 @@ def add_real_paths(self, path_list, read_only=True, lazy_dir_read=True): else: self.add_real_file(path, read_only) - def CreateFileInternally(self, file_path, st_mode=stat.S_IFREG | PERM_DEF_FILE, - contents='', st_size=None, create_missing_dirs=True, - apply_umask=False, encoding=None, errors=None, - read_from_real_fs=False, read_only=True, raw_io=False): + def create_file_internally(self, file_path, st_mode=S_IFREG | PERM_DEF_FILE, + contents='', st_size=None, create_missing_dirs=True, + apply_umask=False, encoding=None, errors=None, + read_from_real_fs=False, read_only=True, raw_io=False): """Internal fake file creator that supports both normal fake files and fake files based on real files. @@ -2331,49 +2412,50 @@ def CreateFileInternally(self, file_path, st_mode=stat.S_IFREG | PERM_DEF_FILE, raw_io: `True` if called from low-level API (`os.open`) """ error_class = OSError if raw_io else IOError - file_path = self.NormalizePath(file_path) + file_path = self.absnormpath(file_path) if not is_int_type(st_mode): raise TypeError('st_mode must be of int type - did you mean to set contents?') - if self.Exists(file_path, check_link=True): + if self.exists(file_path, check_link=True): raise OSError(errno.EEXIST, 'File already exists in fake filesystem', file_path) - parent_directory, new_file = self.SplitPath(file_path) + parent_directory, new_file = self.splitpath(file_path) if not parent_directory: parent_directory = self.cwd - self._AutoMountDriveIfNeeded(parent_directory) - if not self.Exists(parent_directory): + self._auto_mount_drive_if_needed(parent_directory) + if not self.exists(parent_directory): if not create_missing_dirs: raise error_class(errno.ENOENT, 'No such fake directory', parent_directory) - self.CreateDirectory(parent_directory) + self.create_dir(parent_directory) else: - parent_directory = self.NormalizeCase(parent_directory) + parent_directory = self._original_path(parent_directory) if apply_umask: st_mode &= ~self.umask if read_from_real_fs: file_object = FakeFileFromRealFile(file_path, filesystem=self, read_only=read_only) else: - file_object = FakeFile(new_file, st_mode, filesystem=self, encoding=encoding, errors=errors) + file_object = FakeFile(new_file, st_mode, filesystem=self, encoding=encoding, + errors=errors) self._last_ino += 1 - file_object.SetIno(self._last_ino) - self.AddObject(parent_directory, file_object, error_class) + file_object.st_ino = self._last_ino + self.add_object(parent_directory, file_object, error_class) if not read_from_real_fs and (contents is not None or st_size is not None): try: if st_size is not None: - file_object.SetLargeFileSize(st_size) + file_object.set_large_file_size(st_size) else: file_object._set_initial_contents(contents) except IOError: - self.RemoveObject(file_path) + self.remove_object(file_path) raise return file_object # pylint: disable=unused-argument - def CreateLink(self, file_path, link_target, create_missing_dirs=True): + def create_symlink(self, file_path, link_target, create_missing_dirs=True): """Create the specified symlink, pointed at the specified link target. Args: @@ -2389,27 +2471,27 @@ def CreateLink(self, file_path, link_target, create_missing_dirs=True): OSError: if the symlink could not be created (see `CreateFile`). OSError: if on Windows before Python 3.2. """ - if not self._IsLinkSupported(): + if not self._is_link_supported(): raise OSError("Symbolic links are not supported on Windows before Python 3.2") # the link path cannot end with a path separator - file_path = self.NormalizePathSeparator(file_path) + file_path = self.normcase(file_path) if file_path.endswith(self.path_separator): - if self.Exists(file_path): + if self.exists(file_path): raise OSError(errno.EEXIST, 'File exists') if not self.is_windows_fs: raise OSError(errno.ENOENT, 'No such file or directory') # resolve the link path only if it is not a link itself - if not self.IsLink(file_path): - file_path = self.ResolvePath(file_path) + if not self.islink(file_path): + file_path = self.resolve_path(file_path) if sys.version_info >= (3, 6): link_target = os.fspath(link_target) - return self.CreateFileInternally(file_path, st_mode=stat.S_IFLNK | PERM_DEF, - contents=link_target, create_missing_dirs=create_missing_dirs, - raw_io=True) + return self.create_file_internally(file_path, st_mode=S_IFLNK | PERM_DEF, + contents=link_target, create_missing_dirs=create_missing_dirs, + raw_io=True) - def CreateHardLink(self, old_path, new_path): + def link(self, old_path, new_path): """Create a hard link at new_path, pointing at old_path. Args: @@ -2425,41 +2507,41 @@ def CreateHardLink(self, old_path, new_path): OSError: if the parent directory doesn't exist. OSError: if on Windows before Python 3.2. """ - if not self._IsLinkSupported(): + if not self._is_link_supported(): raise OSError("Links are not supported on Windows before Python 3.2") - new_path_normalized = self.NormalizePath(new_path) - if self.Exists(new_path_normalized, check_link=True): + new_path_normalized = self.absnormpath(new_path) + if self.exists(new_path_normalized, check_link=True): raise OSError(errno.EEXIST, 'File already exists in fake filesystem', new_path) - new_parent_directory, new_basename = self.SplitPath(new_path_normalized) + new_parent_directory, new_basename = self.splitpath(new_path_normalized) if not new_parent_directory: new_parent_directory = self.cwd - if not self.Exists(new_parent_directory): + if not self.exists(new_parent_directory): raise OSError(errno.ENOENT, 'No such fake directory', new_parent_directory) # Retrieve the target file try: - old_file = self.ResolveObject(old_path) + old_file = self.resolve(old_path) except: raise OSError(errno.ENOENT, 'No such file or directory in fake filesystem', old_path) - if old_file.st_mode & stat.S_IFDIR: + if old_file.st_mode & S_IFDIR: raise OSError(errno.EACCES if self.is_windows_fs else errno.EPERM, 'Cannot create hard link to directory', old_path) # abuse the name field to control the filename of the newly created link old_file.name = new_basename - self.AddObject(new_parent_directory, old_file) + self.add_object(new_parent_directory, old_file) return old_file - def ReadLink(self, path): + def readlink(self, path): """Read the target of a symlink. Args: @@ -2476,14 +2558,14 @@ def ReadLink(self, path): if path is None: raise TypeError try: - link_obj = self.LResolveObject(path) + link_obj = self.lresolve(path) except IOError as exc: raise OSError(exc.errno, 'Fake path does not exist', path) - if stat.S_IFMT(link_obj.st_mode) != stat.S_IFLNK: + if S_IFMT(link_obj.st_mode) != S_IFLNK: raise OSError(errno.EINVAL, 'Fake filesystem: not a symlink', path) return link_obj.contents - def MakeDirectory(self, dir_name, mode=PERM_DEF): + def makedir(self, dir_name, mode=PERM_DEF): """Create a leaf Fake directory. Args: @@ -2498,35 +2580,35 @@ def MakeDirectory(self, dir_name, mode=PERM_DEF): """ if sys.version_info >= (3, 6): dir_name = os.fspath(dir_name) - if self._EndsWithPathSeparator(dir_name): + if self._ends_with_path_separator(dir_name): dir_name = dir_name[:-1] if not dir_name: raise OSError(errno.ENOENT, 'Empty directory name') if self.is_windows_fs: - dir_name = self.NormalizePath(dir_name) - parent_dir, _ = self.SplitPath(dir_name) + dir_name = self.absnormpath(dir_name) + parent_dir, _ = self.splitpath(dir_name) if parent_dir: - base_dir = self.CollapsePath(parent_dir) + base_dir = self.normpath(parent_dir) ellipsis = self._matching_string(parent_dir, self.path_separator + '..') if parent_dir.endswith(ellipsis) and not self.is_windows_fs: base_dir, dummy_dotdot, _ = parent_dir.partition(ellipsis) - if not self.Exists(base_dir): + if not self.exists(base_dir): raise OSError(errno.ENOENT, 'No such fake directory', base_dir) - dir_name = self.NormalizePath(dir_name) - if self.Exists(dir_name, check_link=True): + dir_name = self.absnormpath(dir_name) + if self.exists(dir_name, check_link=True): if self.is_windows_fs and dir_name == self.path_separator: error_nr = errno.EACCES else: error_nr = errno.EEXIST raise OSError(error_nr, 'Fake object already exists', dir_name) - head, tail = self.SplitPath(dir_name) + head, tail = self.splitpath(dir_name) - self.AddObject( + self.add_object( head, FakeDirectory(tail, mode & ~self.umask, filesystem=self)) - def MakeDirectories(self, dir_name, mode=PERM_DEF, exist_ok=False): + def makedirs(self, dir_name, mode=PERM_DEF, exist_ok=False): """Create a leaf Fake directory and create any non-existent parent dirs. Args: @@ -2540,10 +2622,10 @@ def MakeDirectories(self, dir_name, mode=PERM_DEF, exist_ok=False): Raises: OSError: if the directory already exists and exist_ok=False, or as per - `FakeFilesystem.CreateDirectory()`. + `FakeFilesystem.create_dir()`. """ - dir_name = self.NormalizePath(dir_name) - path_components = self.GetPathComponents(dir_name) + dir_name = self.absnormpath(dir_name) + path_components = self._path_components(dir_name) # Raise a permission denied error if the first existing directory is not # writeable. @@ -2555,15 +2637,15 @@ def MakeDirectories(self, dir_name, mode=PERM_DEF, exist_ok=False): else: current_dir = current_dir.contents[component] try: - self.CreateDirectory(dir_name, mode & ~self.umask) + self.create_dir(dir_name, mode & ~self.umask) except (IOError, OSError) as e: if (not exist_ok or - not isinstance(self.ResolveObject(dir_name), FakeDirectory)): + not isinstance(self.resolve(dir_name), FakeDirectory)): if self.is_windows_fs and e.errno == errno.ENOTDIR: e.errno = errno.ENOENT raise OSError(e.errno, e.strerror, e.filename) - def _IsType(self, path, st_flag, follow_symlinks=True): + def _istype(self, path, st_flag, follow_symlinks=True): """Helper function to implement isdir(), islink(), etc. See the stat(2) man page for valid stat.S_I* flag values @@ -2583,14 +2665,14 @@ def _IsType(self, path, st_flag, follow_symlinks=True): if path is None: raise TypeError try: - obj = self.ResolveObject(path, follow_symlinks) + obj = self.resolve(path, follow_symlinks) if obj: - return stat.S_IFMT(obj.st_mode) == st_flag + return S_IFMT(obj.st_mode) == st_flag except (IOError, OSError): return False return False - def IsDir(self, path, follow_symlinks=True): + def isdir(self, path, follow_symlinks=True): """Determine if path identifies a directory. Args: @@ -2602,9 +2684,9 @@ def IsDir(self, path, follow_symlinks=True): Raises: TypeError: if path is None. """ - return self._IsType(path, stat.S_IFDIR, follow_symlinks) + return self._istype(path, S_IFDIR, follow_symlinks) - def IsFile(self, path, follow_symlinks=True): + def isfile(self, path, follow_symlinks=True): """Determine if path identifies a regular file. Args: @@ -2616,9 +2698,9 @@ def IsFile(self, path, follow_symlinks=True): Raises: TypeError: if path is None. """ - return self._IsType(path, stat.S_IFREG, follow_symlinks) + return self._istype(path, S_IFREG, follow_symlinks) - def IsLink(self, path): + def islink(self, path): """Determine if path identifies a symbolic link. Args: @@ -2630,9 +2712,9 @@ def IsLink(self, path): Raises: TypeError: if path is None. """ - return self._IsType(path, stat.S_IFLNK, follow_symlinks=False) + return self._istype(path, S_IFLNK, follow_symlinks=False) - def ConfirmDir(self, target_directory): + def confirmdir(self, target_directory): """Test that the target is actually a directory, raising OSError if not. Args: @@ -2646,10 +2728,10 @@ def ConfirmDir(self, target_directory): OSError: if the target is not a directory. """ try: - directory = self.ResolveObject(target_directory) + directory = self.resolve(target_directory) except IOError as exc: raise OSError(exc.errno, exc.strerror, target_directory) - if not directory.st_mode & stat.S_IFDIR: + if not directory.st_mode & S_IFDIR: if self.is_windows_fs and sys.version_info[0] < 3: error_nr = errno.EINVAL else: @@ -2659,7 +2741,7 @@ def ConfirmDir(self, target_directory): target_directory) return directory - def RemoveFile(self, path): + def remove(self, path): """Remove the FakeFile object at the specified file path. Args: @@ -2670,12 +2752,12 @@ def RemoveFile(self, path): OSError: if path does not exist. OSError: if removal failed. """ - path = self.NormalizePath(path) - if self.Exists(path): - obj = self.ResolveObject(path) - if stat.S_IFMT(obj.st_mode) == stat.S_IFDIR: - link_obj = self.LResolveObject(path) - if stat.S_IFMT(link_obj.st_mode) != stat.S_IFLNK: + path = self.absnormpath(path) + if self.exists(path): + obj = self.resolve(path) + if S_IFMT(obj.st_mode) == S_IFDIR: + link_obj = self.lresolve(path) + if S_IFMT(link_obj.st_mode) != S_IFLNK: if self.is_windows_fs: error = errno.EACCES elif self.is_macos: @@ -2685,11 +2767,11 @@ def RemoveFile(self, path): raise OSError(error, "Is a directory: '%s'" % path) try: - self.RemoveObject(path) + self.remove_object(path) except IOError as exc: raise OSError(exc.errno, exc.strerror, exc.filename) - def RemoveDirectory(self, target_directory, allow_symlink=False): + def rmdir(self, target_directory, allow_symlink=False): """Remove a leaf Fake directory. Args: @@ -2706,23 +2788,23 @@ def RemoveDirectory(self, target_directory, allow_symlink=False): if target_directory in (b'.', u'.'): error_nr = errno.EACCES if self.is_windows_fs else errno.EINVAL raise OSError(error_nr, 'Invalid argument: \'.\'') - target_directory = self.NormalizePath(target_directory) - if self.ConfirmDir(target_directory): - if not self.is_windows_fs and self.IsLink(target_directory): + target_directory = self.absnormpath(target_directory) + if self.confirmdir(target_directory): + if not self.is_windows_fs and self.islink(target_directory): if allow_symlink: return raise OSError(errno.ENOTDIR, 'Cannot remove symlink', target_directory) - dir_object = self.ResolveObject(target_directory) + dir_object = self.resolve(target_directory) if dir_object.contents: raise OSError(errno.ENOTEMPTY, 'Fake Directory not empty', target_directory) try: - self.RemoveObject(target_directory) + self.remove_object(target_directory) except IOError as exc: raise OSError(exc.errno, exc.strerror, exc.filename) - def ListDir(self, target_directory): + def listdir(self, target_directory): """Return a list of file names in target_directory. Args: @@ -2735,8 +2817,8 @@ def ListDir(self, target_directory): Raises: OSError: if the target is not a directory. """ - target_directory = self.ResolvePath(target_directory, allow_fd=True) - directory = self.ConfirmDir(target_directory) + target_directory = self.resolve_path(target_directory, allow_fd=True) + directory = self.confirmdir(target_directory) directory_contents = directory.contents return list(directory_contents.keys()) @@ -2749,13 +2831,58 @@ def _add_standard_streams(self): self.AddOpenFile(StandardStreamWrapper(sys.stderr)) +Deprecator.add(FakeFilesystem, FakeFilesystem.get_disk_usage, 'GetDiskUsage') +Deprecator.add(FakeFilesystem, FakeFilesystem.set_disk_usage, 'SetDiskUsage') +Deprecator.add(FakeFilesystem, FakeFilesystem.change_disk_usage, 'ChangeDiskUsage') +Deprecator.add(FakeFilesystem, FakeFilesystem.add_mount_point, 'AddMountPoint') +Deprecator.add(FakeFilesystem, FakeFilesystem.stat, 'GetStat') +Deprecator.add(FakeFilesystem, FakeFilesystem.chmod, 'ChangeMode') +Deprecator.add(FakeFilesystem, FakeFilesystem.utime, 'UpdateTime') +Deprecator.add(FakeFilesystem, FakeFilesystem._add_open_file, 'AddOpenFile') +Deprecator.add(FakeFilesystem, FakeFilesystem._close_open_file, 'CloseOpenFile') +Deprecator.add(FakeFilesystem, FakeFilesystem.has_open_file, 'HasOpenFile') +Deprecator.add(FakeFilesystem, FakeFilesystem._get_open_file, 'GetOpenFile') +Deprecator.add(FakeFilesystem, FakeFilesystem.normcase, 'NormalizePathSeparator') +Deprecator.add(FakeFilesystem, FakeFilesystem.normpath, 'CollapsePath') +Deprecator.add(FakeFilesystem, FakeFilesystem._original_path, 'NormalizeCase') +Deprecator.add(FakeFilesystem, FakeFilesystem.absnormpath, 'NormalizePath') +Deprecator.add(FakeFilesystem, FakeFilesystem.splitpath, 'SplitPath') +Deprecator.add(FakeFilesystem, FakeFilesystem.splitdrive, 'SplitDrive') +Deprecator.add(FakeFilesystem, FakeFilesystem.joinpaths, 'JoinPaths') +Deprecator.add(FakeFilesystem, FakeFilesystem._path_components, 'GetPathComponents') +Deprecator.add(FakeFilesystem, FakeFilesystem._starts_with_drive_letter, 'StartsWithDriveLetter') +Deprecator.add(FakeFilesystem, FakeFilesystem.exists, 'Exists') +Deprecator.add(FakeFilesystem, FakeFilesystem.resolve_path, 'ResolvePath') +Deprecator.add(FakeFilesystem, FakeFilesystem.get_object_from_normpath, 'GetObjectFromNormalizedPath') +Deprecator.add(FakeFilesystem, FakeFilesystem.get_object, 'GetObject') +Deprecator.add(FakeFilesystem, FakeFilesystem.resolve, 'ResolveObject') +Deprecator.add(FakeFilesystem, FakeFilesystem.lresolve, 'LResolveObject') +Deprecator.add(FakeFilesystem, FakeFilesystem.add_object, 'AddObject') +Deprecator.add(FakeFilesystem, FakeFilesystem.remove_object, 'RemoveObject') +Deprecator.add(FakeFilesystem, FakeFilesystem.rename, 'RenameObject') +Deprecator.add(FakeFilesystem, FakeFilesystem.create_dir, 'CreateDirectory') +Deprecator.add(FakeFilesystem, FakeFilesystem.create_file, 'CreateFile') +Deprecator.add(FakeFilesystem, FakeFilesystem.create_symlink, 'CreateLink') +Deprecator.add(FakeFilesystem, FakeFilesystem.link, 'CreateHardLink') +Deprecator.add(FakeFilesystem, FakeFilesystem.readlink, 'ReadLink') +Deprecator.add(FakeFilesystem, FakeFilesystem.makedir, 'MakeDirectory') +Deprecator.add(FakeFilesystem, FakeFilesystem.makedirs, 'MakeDirectories') +Deprecator.add(FakeFilesystem, FakeFilesystem.isdir, 'IsDir') +Deprecator.add(FakeFilesystem, FakeFilesystem.isfile, 'IsFile') +Deprecator.add(FakeFilesystem, FakeFilesystem.islink, 'IsLink') +Deprecator.add(FakeFilesystem, FakeFilesystem.confirmdir, 'ConfirmDir') +Deprecator.add(FakeFilesystem, FakeFilesystem.remove, 'RemoveFile') +Deprecator.add(FakeFilesystem, FakeFilesystem.rmdir, 'RemoveDirectory') +Deprecator.add(FakeFilesystem, FakeFilesystem.listdir, 'ListDir') + + class FakePathModule(object): """Faked os.path module replacement. FakePathModule should *only* be instantiated by FakeOsModule. See the FakeOsModule docstring for details. """ - _OS_PATH_COPY = CopyModule(os.path) + _OS_PATH_COPY = _copy_module(os.path) def __init__(self, filesystem, os_module=None): """Init. @@ -2782,7 +2909,7 @@ def exists(self, path): Returns: (bool) `True` if the file exists. """ - return self.filesystem.Exists(path) + return self.filesystem.exists(path) def lexists(self, path): """Test whether a path exists. Returns True for broken symbolic links. @@ -2805,7 +2932,7 @@ def getsize(self, path): file size in bytes. """ try: - file_obj = self.filesystem.ResolveObject(path) + file_obj = self.filesystem.resolve(path) return file_obj.st_size except IOError as exc: raise os.error(exc.errno, exc.strerror) @@ -2825,11 +2952,11 @@ def isabs(self, path): def isdir(self, path): """Determine if path identifies a directory.""" - return self.filesystem.IsDir(path) + return self.filesystem.isdir(path) def isfile(self, path): """Determine if path identifies a regular file.""" - return self.filesystem.IsFile(path) + return self.filesystem.isfile(path) def islink(self, path): """Determine if path identifies a symbolic link. @@ -2843,7 +2970,7 @@ def islink(self, path): Raises: TypeError: if path is None. """ - return self.filesystem.IsLink(path) + return self.filesystem.islink(path) def getmtime(self, path): """Returns the modification time of the fake file. @@ -2859,7 +2986,7 @@ def getmtime(self, path): OSError: if the file does not exist. """ try: - file_obj = self.filesystem.ResolveObject(path) + file_obj = self.filesystem.resolve(path) except IOError as exc: self.filesystem.raise_os_error(errno.ENOENT, 3, str(exc)) return file_obj.st_mtime @@ -2879,7 +3006,7 @@ def getatime(self, path): OSError: if the file does not exist. """ try: - file_obj = self.filesystem.ResolveObject(path) + file_obj = self.filesystem.resolve(path) except IOError as exc: raise OSError(errno.ENOENT, str(exc)) return file_obj.st_atime @@ -2897,7 +3024,7 @@ def getctime(self, path): OSError: if the file does not exist. """ try: - file_obj = self.filesystem.ResolveObject(path) + file_obj = self.filesystem.resolve(path) except IOError as exc: raise OSError(errno.ENOENT, str(exc)) return file_obj.st_ctime @@ -2926,32 +3053,32 @@ def getcwd(): path.startswith(sep) or altsep is not None and path.startswith(altsep)): cwd = getcwd() - if self.filesystem.StartsWithDriveLetter(cwd): + if self.filesystem._starts_with_drive_letter(cwd): path = self.join(cwd[:2], path) return self.normpath(path) def join(self, *p): """Return the completed path with a separator of the parts.""" - return self.filesystem.JoinPaths(*p) + return self.filesystem.joinpaths(*p) def split(self, path): """Split the path into the directory and the filename of the path. """ - return self.filesystem.SplitPath(path) + return self.filesystem.splitpath(path) def splitdrive(self, path): """Split the path into the drive part and the rest of the path, if supported.""" - return self.filesystem.SplitDrive(path) + return self.filesystem.splitdrive(path) def normpath(self, path): """Normalize path, eliminating double slashes, etc.""" - return self.filesystem.CollapsePath(path) + return self.filesystem.normpath(path) def normcase(self, path): """Convert to lower case under windows, replaces additional path separator.""" - path = self.filesystem.NormalizePathSeparator(path) + path = self.filesystem.normcase(path) if self.filesystem.is_windows_fs: path = path.lower() return path @@ -2998,8 +3125,8 @@ def samefile(self, path1, path2): OSError: if one of the paths does not point to an existing file system object. """ - stat1 = self.filesystem.GetStat(path1) - stat2 = self.filesystem.GetStat(path2) + stat1 = self.filesystem.stat(path1) + stat2 = self.filesystem.stat(path2) return stat1.st_ino == stat2.st_ino and stat1.st_dev == stat2.st_dev def _joinrealpath(self, path, rest, seen): @@ -3023,14 +3150,14 @@ def _joinrealpath(self, path, rest, seen): if name == pardir: # parent dir if path: - path, name = self.filesystem.SplitPath(path) + path, name = self.filesystem.splitpath(path) if name == pardir: - path = self.filesystem.JoinPaths(path, pardir, pardir) + path = self.filesystem.joinpaths(path, pardir, pardir) else: path = pardir continue - newpath = self.filesystem.JoinPaths(path, name) - if not self.filesystem.IsLink(newpath): + newpath = self.filesystem.joinpaths(path, name) + if not self.filesystem.islink(newpath): path = newpath continue # Resolve the symbolic link @@ -3042,11 +3169,11 @@ def _joinrealpath(self, path, rest, seen): continue # The symlink is not resolved, so we must have a symlink loop. # Return already resolved part + rest of the path unchanged. - return self.filesystem.JoinPaths(newpath, rest), False + return self.filesystem.joinpaths(newpath, rest), False seen[newpath] = None # not resolved symlink - path, ok = self._joinrealpath(path, self.filesystem.ReadLink(newpath), seen) + path, ok = self._joinrealpath(path, self.filesystem.readlink(newpath), seen) if not ok: - return self.filesystem.JoinPaths(path, rest), False + return self.filesystem.joinpaths(path, rest), False seen[newpath] = path # resolved symlink return path, True @@ -3075,7 +3202,7 @@ def ismount(self, path): path = os.fspath(path) if not path: return False - normed_path = self.filesystem.NormalizePath(path) + normed_path = self.filesystem.absnormpath(path) sep = self.filesystem._path_separator(path) if self.filesystem.is_windows_fs: if self.filesystem.alternative_path_separator is not None: @@ -3084,7 +3211,7 @@ def ismount(self, path): ) else: path_seps = (sep,) - drive, rest = self.filesystem.SplitDrive(normed_path) + drive, rest = self.filesystem.splitdrive(normed_path) if drive and drive[:1] in path_seps: return (not rest) or (rest in path_seps) if rest in path_seps: @@ -3106,21 +3233,21 @@ def walk(self, top, func, arg): dirname and filenames). """ try: - names = self.filesystem.ListDir(top) + names = self.filesystem.listdir(top) except os.error: return func(arg, top, names) for name in names: - name = self.filesystem.JoinPaths(top, name) + name = self.filesystem.joinpaths(top, name) if self.filesystem.is_windows_fs: - if self.filesystem.IsDir(name): + if self.filesystem.isdir(name): self.walk(name, func, arg) else: try: - st = self.filesystem.GetStat(name, follow_symlinks=False) + st = self.filesystem.stat(name, follow_symlinks=False) except os.error: continue - if stat.S_ISDIR(st.st_mode): + if S_ISDIR(st.st_mode): self.walk(name, func, arg) def __getattr__(self, name): @@ -3203,7 +3330,7 @@ def _fdopen_ver2(self, file_des, mode='r', bufsize=None): # pylint: disable=unu raise TypeError('an integer is required') try: - return FakeFileOpen(self.filesystem).Call(file_des, mode=mode) + return FakeFileOpen(self.filesystem).call(file_des, mode=mode) except IOError as exc: raise OSError(exc) @@ -3263,15 +3390,15 @@ def open(self, file_path, flags, mode=None, dir_fd=None): raise NotImplementedError('O_EXCL without O_CREAT mode is not supported') if (not self.filesystem.is_windows_fs and - self.filesystem.Exists(file_path)): + self.filesystem.exists(file_path)): # handle opening directory - only allowed under Posix with read-only mode - obj = self.filesystem.ResolveObject(file_path) + obj = self.filesystem.resolve(file_path) if isinstance(obj, FakeDirectory): if ((not open_modes.must_exist and not self.filesystem.is_macos) or open_modes.can_write): raise OSError(errno.EISDIR, 'Fake directory exists') dir_wrapper = FakeDirWrapper(obj, file_path, self.filesystem) - file_des = self.filesystem.AddOpenFile(dir_wrapper) + file_des = self.filesystem._add_open_file(dir_wrapper) dir_wrapper.filedes = file_des return file_des @@ -3296,7 +3423,7 @@ def close(self, file_des): OSError: bad file descriptor. TypeError: if file descriptor is not an integer. """ - file_handle = self.filesystem.GetOpenFile(file_des) + file_handle = self.filesystem._get_open_file(file_des) file_handle.close() def read(self, file_des, num_bytes): @@ -3313,7 +3440,7 @@ def read(self, file_des, num_bytes): OSError: bad file descriptor. TypeError: if file descriptor is not an integer. """ - file_handle = self.filesystem.GetOpenFile(file_des) + file_handle = self.filesystem._get_open_file(file_des) file_handle.raw_io = True return file_handle.read(num_bytes) @@ -3331,7 +3458,7 @@ def write(self, file_des, contents): OSError: bad file descriptor. TypeError: if file descriptor is not an integer. """ - file_handle = self.filesystem.GetOpenFile(file_des) + file_handle = self.filesystem._get_open_file(file_des) if isinstance(file_handle, FakeDirWrapper): raise OSError(errno.EBADF, 'Cannot write to directory') file_handle.raw_io = True @@ -3368,7 +3495,7 @@ def fstat(self, file_des): OSError: if the filesystem object doesn't exist. """ # stat should return the tuple representing return value of os.stat - file_object = self.filesystem.GetOpenFile(file_des).GetObject() + file_object = self.filesystem._get_open_file(file_des).get_object() return file_object.stat_result.copy() def umask(self, new_mask): @@ -3399,9 +3526,9 @@ def chdir(self, target_directory): OSError: if user lacks permission to enter the argument directory or if the target is not a directory. """ - target_directory = self.filesystem.ResolvePath(target_directory, allow_fd=True) - self.filesystem.ConfirmDir(target_directory) - directory = self.filesystem.ResolveObject(target_directory) + target_directory = self.filesystem.resolve_path(target_directory, allow_fd=True) + self.filesystem.confirmdir(target_directory) + directory = self.filesystem.resolve(target_directory) # A full implementation would check permissions all the way up the tree. if not directory.st_mode | PERM_EXE: raise OSError(errno.EACCES, 'Fake os module: permission denied', @@ -3436,7 +3563,7 @@ def listdir(self, target_directory): Raises: OSError: if the target is not a directory. """ - return self.filesystem.ListDir(target_directory) + return self.filesystem.listdir(target_directory) if sys.platform.startswith('linux') and sys.version_info >= (3, 3): def listxattr(self, path=None, follow_symlinks=True): @@ -3497,7 +3624,7 @@ def readlink(self, path, dir_fd=None): (with errno=EINVAL) if path is valid, but is not a symlink. """ path = self._path_with_dir_fd(path, self.readlink, dir_fd) - return self.filesystem.ReadLink(path) + return self.filesystem.readlink(path) def stat(self, entry_path, dir_fd=None, follow_symlinks=None): """Return the os.stat-like tuple for the FakeFile object of entry_path. @@ -3522,7 +3649,7 @@ def stat(self, entry_path, dir_fd=None, follow_symlinks=None): elif sys.version_info < (3, 3): raise TypeError("stat() got an unexpected keyword argument 'follow_symlinks'") entry_path = self._path_with_dir_fd(entry_path, self.stat, dir_fd) - return self.filesystem.GetStat(entry_path, follow_symlinks) + return self.filesystem.stat(entry_path, follow_symlinks) def lstat(self, entry_path, dir_fd=None): """Return the os.stat-like tuple for entry_path, not following symlinks. @@ -3541,7 +3668,7 @@ def lstat(self, entry_path, dir_fd=None): """ # stat should return the tuple representing return value of os.stat entry_path = self._path_with_dir_fd(entry_path, self.lstat, dir_fd) - return self.filesystem.GetStat(entry_path, follow_symlinks=False) + return self.filesystem.stat(entry_path, follow_symlinks=False) def remove(self, path, dir_fd=None): """Remove the FakeFile object at the specified file path. @@ -3558,7 +3685,7 @@ def remove(self, path, dir_fd=None): OSError: if removal failed. """ path = self._path_with_dir_fd(path, self.remove, dir_fd) - self.filesystem.RemoveFile(path) + self.filesystem.remove(path) def unlink(self, path, dir_fd=None): """Remove the FakeFile object at the specified file path. @@ -3575,7 +3702,7 @@ def unlink(self, path, dir_fd=None): OSError: if removal failed. """ path = self._path_with_dir_fd(path, self.unlink, dir_fd) - self.filesystem.RemoveFile(path) + self.filesystem.remove(path) def rename(self, old_file_path, new_file_path, dir_fd=None): """Rename a FakeFile object at old_file_path to new_file_path, @@ -3598,7 +3725,7 @@ def rename(self, old_file_path, new_file_path, dir_fd=None): OSError: if the file would be moved to another filesystem (e.g. mount point) """ old_file_path = self._path_with_dir_fd(old_file_path, self.rename, dir_fd) - self.filesystem.RenameObject(old_file_path, new_file_path) + self.filesystem.rename(old_file_path, new_file_path) if sys.version_info >= (3, 3): def replace(self, old_file_path, new_file_path): @@ -3620,7 +3747,7 @@ def replace(self, old_file_path, new_file_path): OSError: if the file would be moved to another filesystem (e.g. mount point) """ - self.filesystem.RenameObject(old_file_path, new_file_path, force_replace=True) + self.filesystem.rename(old_file_path, new_file_path, force_replace=True) def rmdir(self, target_directory, dir_fd=None): """Remove a leaf Fake directory. @@ -3633,10 +3760,10 @@ def rmdir(self, target_directory, dir_fd=None): Raises: OSError: if target_directory does not exist or is not a directory, - or as per FakeFilesystem.RemoveObject. Cannot remove '.'. + or as per FakeFilesystem.remove_object. Cannot remove '.'. """ target_directory= self._path_with_dir_fd(target_directory, self.rmdir, dir_fd) - self.filesystem.RemoveDirectory(target_directory) + self.filesystem.rmdir(target_directory) def removedirs(self, target_directory): """Remove a leaf fake directory and all empty intermediate ones. @@ -3648,8 +3775,8 @@ def removedirs(self, target_directory): OSError: if target_directory does not exist or is not a directory. OSError: if target_directory is not empty. """ - target_directory = self.filesystem.NormalizePath(target_directory) - directory = self.filesystem.ConfirmDir(target_directory) + target_directory = self.filesystem.absnormpath(target_directory) + directory = self.filesystem.confirmdir(target_directory) if directory.contents: raise OSError(errno.ENOTEMPTY, 'Fake Directory not empty', self.path.basename(target_directory)) @@ -3659,11 +3786,11 @@ def removedirs(self, target_directory): if not tail: head, tail = self.path.split(head) while head and tail: - head_dir = self.filesystem.ConfirmDir(head) + head_dir = self.filesystem.confirmdir(head) if head_dir.contents: break # only the top-level dir may not be a symlink - self.filesystem.RemoveDirectory(head, allow_symlink=True) + self.filesystem.rmdir(head, allow_symlink=True) head, tail = self.path.split(head) def mkdir(self, dir_name, mode=PERM_DEF, dir_fd=None): @@ -3680,11 +3807,11 @@ def mkdir(self, dir_name, mode=PERM_DEF, dir_fd=None): Raises: OSError: if the directory name is invalid or parent directory is read only - or as per FakeFilesystem.AddObject. + or as per FakeFilesystem.add_object. """ dir_name = self._path_with_dir_fd(dir_name, self.mkdir, dir_fd) try: - self.filesystem.MakeDirectory(dir_name, mode) + self.filesystem.makedir(dir_name, mode) except IOError as e: if e.errno == errno.EACCES: raise OSError(e.errno, os.strerror(e.errno), dir_name) @@ -3704,13 +3831,13 @@ def makedirs(self, dir_name, mode=PERM_DEF, exist_ok=None): Raises: OSError: if the directory already exists and exist_ok=False, or as per - `FakeFilesystem.CreateDirectory()`. + `FakeFilesystem.create_dir()`. """ if exist_ok is None: exist_ok = False elif sys.version_info < (3, 2): raise TypeError("makedir() got an unexpected keyword argument 'exist_ok'") - self.filesystem.MakeDirectories(dir_name, mode, exist_ok) + self.filesystem.makedirs(dir_name, mode, exist_ok) def _path_with_dir_fd(self, path, fct, dir_fd): """Return the path considering dir_fd. Raise on nmvalid parameters.""" @@ -3727,7 +3854,7 @@ def _path_with_dir_fd(self, path, fct, dir_fd): "%s: Can't specify dir_fd without matching path" % fct.__name__) if not self.path.isabs(path): return self.path.join( - self.filesystem.GetOpenFile(dir_fd).GetObject().GetPath(), path) + self.filesystem._get_open_file(dir_fd).get_object().path, path) return path def access(self, path, mode, dir_fd=None, follow_symlinks=None): @@ -3776,7 +3903,7 @@ def chmod(self, path, mode, dir_fd=None, follow_symlinks=None): elif sys.version_info < (3, 3): raise TypeError("chmod() got an unexpected keyword argument 'follow_symlinks'") path = self._path_with_dir_fd(path, self.chmod, dir_fd) - self.filesystem.ChangeMode(path, mode, follow_symlinks) + self.filesystem.chmod(path, mode, follow_symlinks) def lchmod(self, path, mode): """Change the permissions of a file as encoded in integer mode. @@ -3788,7 +3915,7 @@ def lchmod(self, path, mode): """ if self.filesystem.is_windows_fs: raise (NameError, "name 'lchmod' is not defined") - self.filesystem.ChangeMode(path, mode, follow_symlinks=False) + self.filesystem.chmod(path, mode, follow_symlinks=False) def utime(self, path, times=None, ns=None, dir_fd=None, follow_symlinks=None): """Change the access and modified times of a file. @@ -3823,7 +3950,7 @@ def utime(self, path, times=None, ns=None, dir_fd=None, follow_symlinks=None): if ns is not None and sys.version_info < (3, 3): raise TypeError("utime() got an unexpected keyword argument 'ns'") - self.filesystem.UpdateTime(path, times, ns, follow_symlinks) + self.filesystem.utime(path, times, ns, follow_symlinks) def chown(self, path, uid, gid, dir_fd=None, follow_symlinks=None): """Set ownership of a faked file. @@ -3851,7 +3978,7 @@ def chown(self, path, uid, gid, dir_fd=None, follow_symlinks=None): raise TypeError("chown() got an unexpected keyword argument 'follow_symlinks'") path = self._path_with_dir_fd(path, self.chown, dir_fd) try: - file_object = self.filesystem.ResolveObject(path, follow_symlinks, allow_fd=True) + file_object = self.filesystem.resolve(path, follow_symlinks, allow_fd=True) except IOError as io_error: if io_error.errno == errno.ENOENT: raise OSError(errno.ENOENT, @@ -3892,8 +4019,8 @@ def mknod(self, filename, mode=None, device=None, dir_fd=None): if mode is None: # note that a default value of 0o600 without a device type is # documented - this is not how it seems to work - mode = stat.S_IFREG | 0o600 - if device or not mode & stat.S_IFREG: + mode = S_IFREG | 0o600 + if device or not mode & S_IFREG: raise OSError(errno.EPERM, 'Fake os mknod implementation only supports ' 'regular files.') @@ -3901,7 +4028,7 @@ def mknod(self, filename, mode=None, device=None, dir_fd=None): filename = self._path_with_dir_fd(filename, self.mknod, dir_fd) head, tail = self.path.split(filename) if not tail: - if self.filesystem.Exists(head, check_link=True): + if self.filesystem.exists(head, check_link=True): raise OSError(errno.EEXIST, 'Fake filesystem: %s: %s' % ( os.strerror(errno.EEXIST), filename)) raise OSError(errno.ENOENT, 'Fake filesystem: %s: %s' % ( @@ -3909,11 +4036,11 @@ def mknod(self, filename, mode=None, device=None, dir_fd=None): if tail in (b'.', u'.', b'..', u'..'): raise OSError(errno.ENOENT, 'Fake fileystem: %s: %s' % ( os.strerror(errno.ENOENT), filename)) - if self.filesystem.Exists(filename, check_link=True): + if self.filesystem.exists(filename, check_link=True): raise OSError(errno.EEXIST, 'Fake fileystem: %s: %s' % ( os.strerror(errno.EEXIST), filename)) try: - self.filesystem.AddObject(head, FakeFile( + self.filesystem.add_object(head, FakeFile( tail, mode & ~self.filesystem.umask, filesystem=self.filesystem)) except IOError as e: @@ -3934,7 +4061,7 @@ def symlink(self, link_target, path, dir_fd=None): OSError: if the file already exists. """ link_target = self._path_with_dir_fd(link_target, self.symlink, dir_fd) - self.filesystem.CreateLink(path, link_target, create_missing_dirs=False) + self.filesystem.create_symlink(path, link_target, create_missing_dirs=False) def link(self, oldpath, newpath, dir_fd=None): """Create a hard link at new_path, pointing at old_path. @@ -3955,7 +4082,7 @@ def link(self, oldpath, newpath, dir_fd=None): OSError: if on Windows before Python 3.2. """ oldpath = self._path_with_dir_fd(oldpath, self.link, dir_fd) - self.filesystem.CreateHardLink(oldpath, newpath) + self.filesystem.link(oldpath, newpath) def fsync(self, file_des): """Perform fsync for a fake file (in other words, do nothing). @@ -3970,14 +4097,12 @@ def fsync(self, file_des): # Throw an error if file_des isn't valid if 0 <= file_des < NR_STD_STREAMS: raise OSError(errno.EINVAL, 'Invalid file descriptor') - file_object = self.filesystem.GetOpenFile(file_des) + file_object = self.filesystem._get_open_file(file_des) if self.filesystem.is_windows_fs: if (not hasattr(file_object, 'allow_update') or not file_object.allow_update): raise OSError(errno.EBADF, 'File is not open for writing') - - def fdatasync(self, file_des): """Perform fdatasync for a fake file (in other words, do nothing). @@ -3993,7 +4118,7 @@ def fdatasync(self, file_des): raise AttributeError("module 'os' has no attribute 'fdatasync'") if 0 <= file_des < NR_STD_STREAMS: raise OSError(errno.EINVAL, 'Invalid file descriptor') - self.filesystem.GetOpenFile(file_des) + self.filesystem._get_open_file(file_des) def __getattr__(self, name): """Forwards any unfaked calls to the standard os module.""" @@ -4021,7 +4146,7 @@ def __init__(self, filesystem): def open(self, file_path, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None): """Redirect the call to FakeFileOpen. - See FakeFileOpen.Call() for description. + See FakeFileOpen.call() for description. """ if opener is not None and sys.version_info < (3, 3): raise TypeError("open() got an unexpected keyword argument 'opener'") @@ -4118,7 +4243,7 @@ def _raise(self, message): raise IOError(message) raise io.UnsupportedOperation(message) - def GetObject(self): + def get_object(self): """Return the FakeFile object that is wrapped by the current instance.""" return self._file_object @@ -4133,18 +4258,18 @@ def close(self): return # for raw io, all writes are flushed immediately if self.allow_update and not self.raw_io: - self._file_object.SetContents(self._io.getvalue(), self._encoding) + self._file_object.set_contents(self._io.getvalue(), self._encoding) if self._closefd: - self._filesystem.CloseOpenFile(self.filedes) + self._filesystem._close_open_file(self.filedes) if self.delete_on_close: - self._filesystem.RemoveObject(self.GetObject().GetPath()) + self._filesystem.remove_object(self.get_object().path) def flush(self): """Flush file contents to 'disk'.""" self._check_open_file() if self.allow_update: self._io.flush() - self._file_object.SetContents(self._io.getvalue(), self._encoding) + self._file_object.set_contents(self._io.getvalue(), self._encoding) self._file_epoch = self._file_object.epoch def seek(self, offset, whence=0): @@ -4213,7 +4338,7 @@ def _sync_io(self): self._io.stream.allow_update = False self._file_epoch = self._file_object.epoch - def _read_wrapper(self, name): + def _read_wrappers(self, name): """Wrap a stream attribute in a read wrapper. Returns a read_wrapper which tracks our own read pointer since the @@ -4326,12 +4451,12 @@ def write_wrapper(*args, **kwargs): return write_wrapper - def Size(self): + def size(self): """Return the content size in bytes of the wrapped file.""" return self._file_object.st_size def __getattr__(self, name): - if self._file_object.IsLargeFile(): + if self._file_object.is_large_file(): raise FakeLargeFileIoException(self._file_path) reading = name.startswith('read') or name == 'next' @@ -4367,7 +4492,7 @@ def write_error(*args, **kwargs): return self._truncate_wrapper() if self._append: if reading: - return self._read_wrapper(name) + return self._read_wrappers(name) else: return self._other_wrapper(name, writing) if writing: @@ -4413,7 +4538,7 @@ def __init__(self, file_object, file_path, filesystem): self._filesystem = filesystem self.filedes = None - def GetObject(self): + def get_object(self): """Return the FakeFile object that is wrapped by the current instance.""" return self._file_object @@ -4423,7 +4548,10 @@ def fileno(self): def close(self): """Close the directory.""" - self._filesystem.CloseOpenFile(self.filedes) + self._filesystem._close_open_file(self.filedes) + +Deprecator.add(FakeFileWrapper, FakeFileWrapper.get_object, 'GetObject') +Deprecator.add(FakeFileWrapper, FakeFileWrapper.size, 'Size') class FakeFileOpen(object): @@ -4453,7 +4581,7 @@ def __init__(self, filesystem, delete_on_close=False, use_io=False, raw_io=False def __call__(self, *args, **kwargs): """Redirects calls to file() or open() to appropriate method.""" if self._use_io: - return self.Call(*args, **kwargs) + return self.call(*args, **kwargs) else: return self._call_ver2(*args, **kwargs) @@ -4461,9 +4589,9 @@ def _call_ver2(self, file_path, mode='r', buffering=-1, flags=None, open_modes=N """Limits args of open() or file() for Python 2.x versions.""" # Backwards compatibility, mode arg used to be named flags mode = flags or mode - return self.Call(file_path, mode, buffering, open_modes=open_modes) + return self.call(file_path, mode, buffering, open_modes=open_modes) - def Call(self, file_, mode='r', buffering=-1, encoding=None, + def call(self, file_, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None, open_modes=None): """Return a file-like object with the contents of the target file object. @@ -4510,20 +4638,20 @@ def Call(self, file_, mode='r', buffering=-1, encoding=None, # opening a file descriptor if isinstance(file_, int): filedes = file_ - wrapper = self.filesystem.GetOpenFile(filedes) + wrapper = self.filesystem._get_open_file(filedes) self._delete_on_close = wrapper.delete_on_close - file_object = self.filesystem.GetOpenFile(filedes).GetObject() + file_object = self.filesystem._get_open_file(filedes).get_object() file_path = file_object.name else: file_path = file_ - real_path = self.filesystem.ResolvePath(file_path, raw_io=self.raw_io) - if self.filesystem.Exists(file_path): - file_object = self.filesystem.GetObjectFromNormalizedPath(real_path) + real_path = self.filesystem.resolve_path(file_path, raw_io=self.raw_io) + if self.filesystem.exists(file_path): + file_object = self.filesystem.get_object_from_normpath(real_path) closefd = True error_class = OSError if self.raw_io else IOError if (open_modes.must_not_exist and - (file_object or self.filesystem.IsLink(file_path) and + (file_object or self.filesystem.islink(file_path) and not self.filesystem.is_windows_fs)): raise error_class(errno.EEXIST, 'File exists', file_path) if file_object: @@ -4532,14 +4660,14 @@ def Call(self, file_, mode='r', buffering=-1, encoding=None, raise error_class(errno.EACCES, 'Permission denied', file_path) if open_modes.can_write: if open_modes.truncate: - file_object.SetContents('') + file_object.set_contents('') else: if open_modes.must_exist: raise error_class(errno.ENOENT, 'No such file or directory', file_path) - file_object = self.filesystem.CreateFileInternally( + file_object = self.filesystem.create_file_internally( real_path, create_missing_dirs=False, apply_umask=True, raw_io=self.raw_io) - if stat.S_ISDIR(file_object.st_mode): + if S_ISDIR(file_object.st_mode): if self.filesystem.is_windows_fs: raise error_class(errno.EACCES, 'Fake file object: is a directory', file_path) else: @@ -4568,7 +4696,7 @@ def Call(self, file_, mode='r', buffering=-1, encoding=None, # replace the file wrapper self.filesystem.open_files[filedes] = fakefile else: - fakefile.filedes = self.filesystem.AddOpenFile(fakefile) + fakefile.filedes = self.filesystem._add_open_file(fakefile) return fakefile diff --git a/pyfakefs/fake_filesystem_shutil.py b/pyfakefs/fake_filesystem_shutil.py index d85bf048..7cc04f16 100755 --- a/pyfakefs/fake_filesystem_shutil.py +++ b/pyfakefs/fake_filesystem_shutil.py @@ -52,7 +52,7 @@ def disk_usage(self, path): Args: path: defines the filesystem device which is queried """ - return self.filesystem.GetDiskUsage(path) + return self.filesystem.get_disk_usage(path) def __getattr__(self, name): """Forwards any non-faked calls to the standard shutil module.""" diff --git a/pyfakefs/fake_filesystem_unittest.py b/pyfakefs/fake_filesystem_unittest.py index f6986ab6..71f89b11 100644 --- a/pyfakefs/fake_filesystem_unittest.py +++ b/pyfakefs/fake_filesystem_unittest.py @@ -43,6 +43,8 @@ import sys import tempfile +from pyfakefs.deprecator import Deprecator + try: from importlib.machinery import ModuleSpec except ImportError: @@ -178,6 +180,7 @@ def fs(self): def patches(self): return self._stubber.patches + @Deprecator('add_real_file') def copyRealFile(self, real_file_path, fake_file_path=None, create_missing_dirs=True): """Add the file `real_file_path` in the real file system to the same @@ -234,6 +237,7 @@ def setUpPyfakefs(self): else: sys.meta_path.pop(0) + @DeprecationWarning def tearDownPyfakefs(self): """This method is deprecated and exists only for backward compatibility. It does nothing. @@ -407,7 +411,7 @@ def setUp(self, doctester=None): # the temp directory is assumed to exist at least in `tempfile1, # so we create it here for convenience - self.fs.CreateDirectory(temp_dir) + self.fs.create_dir(temp_dir) def replaceGlobs(self, globs_): diff --git a/pyfakefs/fake_pathlib.py b/pyfakefs/fake_pathlib.py index 4dc0ac9b..f53f143c 100644 --- a/pyfakefs/fake_pathlib.py +++ b/pyfakefs/fake_pathlib.py @@ -78,43 +78,43 @@ def _wrapped(pathobj1, pathobj2, *args): class _FakeAccessor(pathlib._Accessor): # pylint: disable=protected-access """Accessor which forwards some of the functions to FakeFilesystem methods.""" - stat = _wrap_strfunc(FakeFilesystem.GetStat) + stat = _wrap_strfunc(FakeFilesystem.stat) - lstat = _wrap_strfunc(lambda fs, path: FakeFilesystem.GetStat(fs, path, follow_symlinks=False)) + lstat = _wrap_strfunc(lambda fs, path: FakeFilesystem.stat(fs, path, follow_symlinks=False)) - listdir = _wrap_strfunc(FakeFilesystem.ListDir) + listdir = _wrap_strfunc(FakeFilesystem.listdir) - chmod = _wrap_strfunc(FakeFilesystem.ChangeMode) + chmod = _wrap_strfunc(FakeFilesystem.chmod) if sys.version_info >= (3, 6): scandir = _wrap_strfunc(fake_scandir.scandir) if hasattr(os, "lchmod"): - lchmod = _wrap_strfunc(lambda fs, path, mode: FakeFilesystem.ChangeMode( + lchmod = _wrap_strfunc(lambda fs, path, mode: FakeFilesystem.chmod( fs, path, mode, follow_symlinks=False)) else: def lchmod(self, pathobj, mode): """Raises not implemented for Windows systems.""" raise NotImplementedError("lchmod() not available on this system") - mkdir = _wrap_strfunc(FakeFilesystem.MakeDirectory) + mkdir = _wrap_strfunc(FakeFilesystem.makedir) - unlink = _wrap_strfunc(FakeFilesystem.RemoveFile) + unlink = _wrap_strfunc(FakeFilesystem.remove) - rmdir = _wrap_strfunc(FakeFilesystem.RemoveDirectory) + rmdir = _wrap_strfunc(FakeFilesystem.rmdir) - rename = _wrap_binary_strfunc(FakeFilesystem.RenameObject) + rename = _wrap_binary_strfunc(FakeFilesystem.rename) replace = _wrap_binary_strfunc(lambda fs, old_path, new_path: - FakeFilesystem.RenameObject( + FakeFilesystem.rename( fs, old_path, new_path, force_replace=True)) symlink = _wrap_binary_strfunc_reverse( lambda fs, file_path, link_target, target_is_directory: - FakeFilesystem.CreateLink(fs, file_path, link_target, - create_missing_dirs=False)) + FakeFilesystem.create_symlink(fs, file_path, link_target, + create_missing_dirs=False)) - utime = _wrap_strfunc(FakeFilesystem.UpdateTime) + utime = _wrap_strfunc(FakeFilesystem.utime) _fake_accessor = _FakeAccessor() @@ -251,7 +251,7 @@ def _resolve(path, rest): raise RuntimeError("Symlink loop from %r" % newpath) # Resolve the symbolic link try: - target = self.filesystem.ReadLink(newpath) + target = self.filesystem.readlink(newpath) except OSError as e: if e.errno != errno.EINVAL: if strict: @@ -278,21 +278,21 @@ def _resolve_windows(self, path, strict): return os.getcwd() previous_s = None if strict: - if not self.filesystem.Exists(s): + if not self.filesystem.exists(s): raise FileNotFoundError(s) - return self.filesystem.ResolvePath(s) + return self.filesystem.resolve_path(s) else: while True: try: - s = self.filesystem.ResolvePath(s) + s = self.filesystem.resolve_path(s) except FileNotFoundError: previous_s = s - s = self.filesystem.SplitPath(s)[0] + s = self.filesystem.splitpath(s)[0] else: if previous_s is None: return s else: - return self.filesystem.JoinPaths(s, os.path.basename(previous_s)) + return self.filesystem.joinpaths(s, os.path.basename(previous_s)) def resolve(self, path, strict): """Make the path absolute, resolving any symlinks.""" @@ -477,7 +477,7 @@ def resolve(self, strict=None): if path is None: self.stat() path = str(self.absolute()) - path = self.filesystem.NormalizePath(path) + path = self.filesystem.absnormpath(path) return FakePath(path) def open(self, mode='r', buffering=-1, encoding=None, @@ -567,7 +567,7 @@ def samefile(self, other_path): try: other_st = other_path.stat() except AttributeError: - other_st = self.filesystem.GetStat(other_path) + other_st = self.filesystem.stat(other_path) return st.st_ino == other_st.st_ino and st.st_dev == other_st.st_dev def expanduser(self): @@ -592,7 +592,7 @@ def touch(self, mode=0o666, exist_ok=True): self._raise_closed() if self.exists(): if exist_ok: - self.filesystem.UpdateTime(self._path(), None) + self.filesystem.utime(self._path(), None) else: raise FileExistsError else: diff --git a/pyfakefs/pytest_plugin.py b/pyfakefs/pytest_plugin.py index 7c0b2cc1..5b62f1d2 100644 --- a/pyfakefs/pytest_plugin.py +++ b/pyfakefs/pytest_plugin.py @@ -5,7 +5,7 @@ :Usage: def my_fakefs_test(fs): - fs.CreateFile('/var/data/xx1.txt') + fs.create_file('/var/data/xx1.txt') assert os.path.exists('/var/data/xx1.txt') """ import py diff --git a/pytest_plugin_test.py b/pytest_plugin_test.py index 649cbc6b..d722ce7d 100644 --- a/pytest_plugin_test.py +++ b/pytest_plugin_test.py @@ -3,5 +3,5 @@ def test_fs_fixture(fs): - fs.CreateFile('/var/data/xx1.txt') + fs.create_file('/var/data/xx1.txt') assert os.path.exists('/var/data/xx1.txt')