comparison tests/mockutil.py @ 394:65db6df28120

tests: Also mock `open` in Jinja to be able to use templates in bake tests. This also required raising the proper exception in the mock function. We are now raising `IOError` and set the `errno` attribute on it.
author Ludovic Chabant <ludovic@chabant.com>
date Sun, 17 May 2015 15:28:00 -0700
parents 4b1019bb2533
children e7b865f8f335
comparison
equal deleted inserted replaced
393:89c1e2a91468 394:65db6df28120
1 import io 1 import io
2 import time 2 import time
3 import errno
3 import random 4 import random
4 import codecs 5 import codecs
5 import shutil 6 import shutil
6 import os.path 7 import os.path
7 import mock 8 import mock
250 def __exit__(self, type, value, traceback): 251 def __exit__(self, type, value, traceback):
251 self._endMock() 252 self._endMock()
252 253
253 def _startMock(self): 254 def _startMock(self):
254 # TODO: sadly, there seems to be no way to replace `open` everywhere? 255 # TODO: sadly, there seems to be no way to replace `open` everywhere?
255 modules = self.open_patches + ['__main__', 'piecrust.records'] 256 modules = self.open_patches + [
257 '__main__',
258 'piecrust.records',
259 'jinja2.utils']
256 for m in modules: 260 for m in modules:
257 self._createMock('%s.open' % m, open, self._open, create=True) 261 self._createMock('%s.open' % m, open, self._open, create=True)
258 262
259 self._createMock('codecs.open', codecs.open, self._codecsOpen) 263 self._createMock('codecs.open', codecs.open, self._codecsOpen)
260 self._createMock('os.listdir', os.listdir, self._listdir) 264 self._createMock('os.listdir', os.listdir, self._listdir)
294 contents = bytes() 298 contents = bytes()
295 self._fs._createFile(path, contents) 299 self._fs._createFile(path, contents)
296 e = self._getFsEntry(path) 300 e = self._getFsEntry(path)
297 assert e is not None 301 assert e is not None
298 elif 'x' in mode: 302 elif 'x' in mode:
299 raise OSError("File '%s' already exists" % path) 303 err = IOError("File '%s' already exists" % path)
304 err.errno = errno.EEXIST
305 raise err
300 else: 306 else:
301 raise OSError("Unsupported open mode: %s" % mode) 307 err = IOError("Unsupported open mode: %s" % mode)
308 err.errno = errno.EINVAL
309 raise err
302 310
303 if e is None: 311 if e is None:
304 raise OSError("No such file: %s" % path) 312 err = IOError("No such file: %s" % path)
313 err.errno = errno.ENOENT
314 raise err
305 if not isinstance(e, _MockFsEntry): 315 if not isinstance(e, _MockFsEntry):
306 raise OSError("'%s' is not a file %s" % (path, e)) 316 err = IOError("'%s' is not a file %s" % (path, e))
317 err.errno = errno.EISDIR
318 raise err
307 319
308 return _MockFsEntryWriter(e, mode) 320 return _MockFsEntryWriter(e, mode)
309 321
310 def _open(self, path, mode, *args, **kwargs): 322 def _open(self, path, mode, *args, **kwargs):
311 return self._doOpen('__main__.open', path, mode, *args, **kwargs) 323 return self._doOpen('__main__.open', path, mode, *args, **kwargs)