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/.
1
5
from unittest import TextTestRunner as _TestRunner, TestResult as _TestResult
8
from StringIO import StringIO
4
11
'''Helper to make python unit tests report the way that the Mozilla
5
12
unit test infrastructure expects tests to report.
65
72
result.printErrorList()
75
class MockedFile(StringIO):
76
def __init__(self, context, filename, content = ''):
77
self.context = context
79
StringIO.__init__(self, content)
82
self.context.files[self.name] = self.getvalue()
88
def __exit__(self, type, value, traceback):
91
class MockedOpen(object):
93
Context manager diverting the open builtin such that opening files
94
can open "virtual" file instances given when creating a MockedOpen.
96
with MockedOpen({'foo': 'foo', 'bar': 'bar'}):
99
will thus open the virtual file instance for the file 'foo' to f.
101
MockedOpen also masks writes, so that creating or replacing files
102
doesn't touch the file system, while subsequently opening the file
103
will return the recorded content.
108
self.assertRaises(Exception,f.open('foo', 'r'))
110
def __init__(self, files = {}):
112
for name, content in files.iteritems():
113
self.files[os.path.abspath(name)] = content
115
def __call__(self, name, mode = 'r'):
116
absname = os.path.abspath(name)
118
file = MockedFile(self, absname)
119
elif absname in self.files:
120
file = MockedFile(self, absname, self.files[absname])
122
file = MockedFile(self, absname, self.open(name, 'r').read())
124
file = self.open(name, mode)
126
file.seek(0, os.SEEK_END)
131
self.open = __builtin__.open
132
__builtin__.open = self
134
def __exit__(self, type, value, traceback):
136
__builtin__.open = self.open
139
unittest.main(testRunner=MozTestRunner(),*args)