1
# This Source Code Form is subject to the terms of the Mozilla Public
2
# License, v. 2.0. If a copy of the MPL was not distributed with this
3
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
from __future__ import with_statement
8
from mozunit import main, MockedOpen
10
from tempfile import mkstemp
12
class TestMozUnit(unittest.TestCase):
13
def test_mocked_open(self):
14
# Create a temporary file on the file system.
15
(fd, path) = mkstemp()
16
with os.fdopen(fd, 'w') as file:
19
with MockedOpen({'file1': 'content1',
20
'file2': 'content2'}):
21
# Check the contents of the files given at MockedOpen creation.
22
self.assertEqual(open('file1', 'r').read(), 'content1')
23
self.assertEqual(open('file2', 'r').read(), 'content2')
25
# Check that overwriting these files alters their content.
26
with open('file1', 'w') as file:
28
self.assertEqual(open('file1', 'r').read(), 'foo')
30
# ... but not until the file is closed.
31
file = open('file2', 'w')
33
self.assertEqual(open('file2', 'r').read(), 'content2')
35
self.assertEqual(open('file2', 'r').read(), 'bar')
37
# Check that appending to a file does append
38
with open('file1', 'a') as file:
40
self.assertEqual(open('file1', 'r').read(), 'foobar')
42
# Opening a non-existing file ought to fail.
43
self.assertRaises(IOError, open, 'file3', 'r')
45
# Check that writing a new file does create the file.
46
with open('file3', 'w') as file:
48
self.assertEqual(open('file3', 'r').read(), 'baz')
50
# Check the content of the file created outside MockedOpen.
51
self.assertEqual(open(path, 'r').read(), 'foobar')
53
# Check that overwriting a file existing on the file system
54
# does modify its content.
55
with open(path, 'w') as file:
57
self.assertEqual(open(path, 'r').read(), 'bazqux')
60
# Check that appending to a file existing on the file system
61
# does modify its content.
62
with open(path, 'a') as file:
64
self.assertEqual(open(path, 'r').read(), 'foobarbazqux')
66
# Check that the file was not actually modified on the file system.
67
self.assertEqual(open(path, 'r').read(), 'foobar')
70
# Check that the file created inside MockedOpen wasn't actually
72
self.assertRaises(IOError, open, 'file3', 'r')
74
if __name__ == "__main__":