Bug 937803 - os.path.exists should work with MockedOpen; r=glandium

--HG--
extra : rebase_source : 567b70b6a75f3c918da2c99ceb490ac569919ed0
This commit is contained in:
Gregory Szorc 2013-11-12 12:30:34 -08:00
parent 6ec3fd72a6
commit e7b3d38b5c
2 changed files with 25 additions and 0 deletions

View File

@ -129,11 +129,24 @@ class MockedOpen(object):
def __enter__(self):
import __builtin__
self.open = __builtin__.open
self._orig_path_exists = os.path.exists
__builtin__.open = self
os.path.exists = self._wrapped_exists
def __exit__(self, type, value, traceback):
import __builtin__
__builtin__.open = self.open
os.path.exists = self._orig_path_exists
def _wrapped_exists(self, p):
if p in self.files:
return True
abspath = os.path.abspath(p)
if abspath in self.files:
return True
return self._orig_path_exists(p)
def main(*args):
unittest.main(testRunner=MozTestRunner(),*args)

View File

@ -15,8 +15,15 @@ class TestMozUnit(unittest.TestCase):
with os.fdopen(fd, 'w') as file:
file.write('foobar');
self.assertFalse(os.path.exists('file1'))
self.assertFalse(os.path.exists('file2'))
with MockedOpen({'file1': 'content1',
'file2': 'content2'}):
self.assertTrue(os.path.exists('file1'))
self.assertTrue(os.path.exists('file2'))
self.assertFalse(os.path.exists('foo/file1'))
# Check the contents of the files given at MockedOpen creation.
self.assertEqual(open('file1', 'r').read(), 'content1')
self.assertEqual(open('file2', 'r').read(), 'content2')
@ -24,6 +31,7 @@ class TestMozUnit(unittest.TestCase):
# Check that overwriting these files alters their content.
with open('file1', 'w') as file:
file.write('foo')
self.assertTrue(os.path.exists('file1'))
self.assertEqual(open('file1', 'r').read(), 'foo')
# ... but not until the file is closed.
@ -38,13 +46,17 @@ class TestMozUnit(unittest.TestCase):
file.write('bar')
self.assertEqual(open('file1', 'r').read(), 'foobar')
self.assertFalse(os.path.exists('file3'))
# Opening a non-existing file ought to fail.
self.assertRaises(IOError, open, 'file3', 'r')
self.assertFalse(os.path.exists('file3'))
# Check that writing a new file does create the file.
with open('file3', 'w') as file:
file.write('baz')
self.assertEqual(open('file3', 'r').read(), 'baz')
self.assertTrue(os.path.exists('file3'))
# Check the content of the file created outside MockedOpen.
self.assertEqual(open(path, 'r').read(), 'foobar')