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/.
7 from mozunit
import main
, MockedOpen
9 from tempfile
import mkstemp
11 class TestMozUnit(unittest
.TestCase
):
12 def test_mocked_open(self
):
13 # Create a temporary file on the file system.
14 (fd
, path
) = mkstemp()
15 with os
.fdopen(fd
, 'w') as file:
18 self
.assertFalse(os
.path
.exists('file1'))
19 self
.assertFalse(os
.path
.exists('file2'))
21 with
MockedOpen({'file1': 'content1',
22 'file2': 'content2'}):
23 self
.assertTrue(os
.path
.exists('file1'))
24 self
.assertTrue(os
.path
.exists('file2'))
25 self
.assertFalse(os
.path
.exists('foo/file1'))
27 # Check the contents of the files given at MockedOpen creation.
28 self
.assertEqual(open('file1', 'r').read(), 'content1')
29 self
.assertEqual(open('file2', 'r').read(), 'content2')
31 # Check that overwriting these files alters their content.
32 with
open('file1', 'w') as file:
34 self
.assertTrue(os
.path
.exists('file1'))
35 self
.assertEqual(open('file1', 'r').read(), 'foo')
37 # ... but not until the file is closed.
38 file = open('file2', 'w')
40 self
.assertEqual(open('file2', 'r').read(), 'content2')
42 self
.assertEqual(open('file2', 'r').read(), 'bar')
44 # Check that appending to a file does append
45 with
open('file1', 'a') as file:
47 self
.assertEqual(open('file1', 'r').read(), 'foobar')
49 self
.assertFalse(os
.path
.exists('file3'))
51 # Opening a non-existing file ought to fail.
52 self
.assertRaises(IOError, open, 'file3', 'r')
53 self
.assertFalse(os
.path
.exists('file3'))
55 # Check that writing a new file does create the file.
56 with
open('file3', 'w') as file:
58 self
.assertEqual(open('file3', 'r').read(), 'baz')
59 self
.assertTrue(os
.path
.exists('file3'))
61 # Check the content of the file created outside MockedOpen.
62 self
.assertEqual(open(path
, 'r').read(), 'foobar')
64 # Check that overwriting a file existing on the file system
65 # does modify its content.
66 with
open(path
, 'w') as file:
68 self
.assertEqual(open(path
, 'r').read(), 'bazqux')
71 # Check that appending to a file existing on the file system
72 # does modify its content.
73 with
open(path
, 'a') as file:
75 self
.assertEqual(open(path
, 'r').read(), 'foobarbazqux')
77 # Check that the file was not actually modified on the file system.
78 self
.assertEqual(open(path
, 'r').read(), 'foobar')
81 # Check that the file created inside MockedOpen wasn't actually
83 self
.assertRaises(IOError, open, 'file3', 'r')
85 if __name__
== "__main__":