blob: d711cb3e7956560553209ced47a8d22a23fa0f7b [file] [log] [blame]
Brett Cannon45a5e3a2012-07-20 14:48:53 -04001from importlib import machinery
Brett Cannon23cbd8a2009-01-18 00:24:28 +00002import importlib
Brett Cannonc0499522012-05-11 14:48:41 -04003import importlib.abc
Brett Cannon30b047d2009-02-01 02:05:11 +00004from .. import abc
Brett Cannond71bed32010-07-03 22:18:47 +00005from .. import util
Brett Cannon4ee2cda2009-02-01 03:08:31 +00006from . import util as source_util
Brett Cannon23cbd8a2009-01-18 00:24:28 +00007
Antoine Pitroudd21f682012-01-25 03:00:57 +01008import errno
Brett Cannon23cbd8a2009-01-18 00:24:28 +00009import imp
Brett Cannon61b14252010-07-03 21:48:25 +000010import marshal
Brett Cannon23cbd8a2009-01-18 00:24:28 +000011import os
12import py_compile
Brett Cannon186335b2010-08-22 22:11:06 +000013import shutil
Brett Cannone52c9192009-11-07 23:55:05 +000014import stat
Brett Cannon23cbd8a2009-01-18 00:24:28 +000015import sys
16import unittest
17
Barry Warsaw04b56842010-05-18 14:15:20 +000018from test.support import make_legacy_pyc
19
Brett Cannon23cbd8a2009-01-18 00:24:28 +000020
21class SimpleTest(unittest.TestCase):
22
23 """Should have no issue importing a source module [basic]. And if there is
24 a syntax error, it should raise a SyntaxError [syntax error].
25
26 """
27
Brett Cannonc0499522012-05-11 14:48:41 -040028 def test_load_module_API(self):
29 # If fullname is not specified that assume self.name is desired.
30 class TesterMixin(importlib.abc.Loader):
31 def load_module(self, fullname): return fullname
Barry Warsaw0efcf992012-07-31 17:52:32 -040032 def module_repr(self, module): return '<module>'
Brett Cannonc0499522012-05-11 14:48:41 -040033
34 class Tester(importlib.abc.FileLoader, TesterMixin):
35 def get_code(self, _): pass
36 def get_source(self, _): pass
37 def is_package(self, _): pass
38
39 name = 'mod_name'
40 loader = Tester(name, 'some_path')
41 self.assertEqual(name, loader.load_module())
42 self.assertEqual(name, loader.load_module(None))
43 self.assertEqual(name, loader.load_module(name))
44 with self.assertRaises(ImportError):
45 loader.load_module(loader.name + 'XXX')
46
47 def test_get_filename_API(self):
48 # If fullname is not set then assume self.path is desired.
49 class Tester(importlib.abc.FileLoader):
50 def get_code(self, _): pass
51 def get_source(self, _): pass
52 def is_package(self, _): pass
Barry Warsaw0efcf992012-07-31 17:52:32 -040053 def module_repr(self, _): pass
Brett Cannonc0499522012-05-11 14:48:41 -040054
55 path = 'some_path'
56 name = 'some_name'
57 loader = Tester(name, path)
58 self.assertEqual(path, loader.get_filename(name))
59 self.assertEqual(path, loader.get_filename())
60 self.assertEqual(path, loader.get_filename(None))
61 with self.assertRaises(ImportError):
62 loader.get_filename(name + 'XXX')
63
Brett Cannon23cbd8a2009-01-18 00:24:28 +000064 # [basic]
Brett Cannon30b047d2009-02-01 02:05:11 +000065 def test_module(self):
Brett Cannon4ee2cda2009-02-01 03:08:31 +000066 with source_util.create_modules('_temp') as mapping:
Brett Cannon45a5e3a2012-07-20 14:48:53 -040067 loader = machinery.SourceFileLoader('_temp', mapping['_temp'])
Brett Cannon30b047d2009-02-01 02:05:11 +000068 module = loader.load_module('_temp')
Eric V. Smithfaae3ad2012-06-27 15:26:26 -040069 self.assertIn('_temp', sys.modules)
Brett Cannon30b047d2009-02-01 02:05:11 +000070 check = {'__name__': '_temp', '__file__': mapping['_temp'],
Brett Cannon06c9d962009-02-07 01:52:25 +000071 '__package__': ''}
Brett Cannon30b047d2009-02-01 02:05:11 +000072 for attr, value in check.items():
73 self.assertEqual(getattr(module, attr), value)
74
75 def test_package(self):
Brett Cannon4ee2cda2009-02-01 03:08:31 +000076 with source_util.create_modules('_pkg.__init__') as mapping:
Brett Cannon45a5e3a2012-07-20 14:48:53 -040077 loader = machinery.SourceFileLoader('_pkg',
Brett Cannon61b14252010-07-03 21:48:25 +000078 mapping['_pkg.__init__'])
Brett Cannon30b047d2009-02-01 02:05:11 +000079 module = loader.load_module('_pkg')
Eric V. Smithfaae3ad2012-06-27 15:26:26 -040080 self.assertIn('_pkg', sys.modules)
Brett Cannon30b047d2009-02-01 02:05:11 +000081 check = {'__name__': '_pkg', '__file__': mapping['_pkg.__init__'],
82 '__path__': [os.path.dirname(mapping['_pkg.__init__'])],
83 '__package__': '_pkg'}
84 for attr, value in check.items():
85 self.assertEqual(getattr(module, attr), value)
86
87
88 def test_lacking_parent(self):
Brett Cannon4ee2cda2009-02-01 03:08:31 +000089 with source_util.create_modules('_pkg.__init__', '_pkg.mod')as mapping:
Brett Cannon45a5e3a2012-07-20 14:48:53 -040090 loader = machinery.SourceFileLoader('_pkg.mod',
Brett Cannon61b14252010-07-03 21:48:25 +000091 mapping['_pkg.mod'])
Brett Cannon30b047d2009-02-01 02:05:11 +000092 module = loader.load_module('_pkg.mod')
Eric V. Smithfaae3ad2012-06-27 15:26:26 -040093 self.assertIn('_pkg.mod', sys.modules)
Brett Cannon30b047d2009-02-01 02:05:11 +000094 check = {'__name__': '_pkg.mod', '__file__': mapping['_pkg.mod'],
95 '__package__': '_pkg'}
96 for attr, value in check.items():
97 self.assertEqual(getattr(module, attr), value)
98
99 def fake_mtime(self, fxn):
100 """Fake mtime to always be higher than expected."""
101 return lambda name: fxn(name) + 1
102
103 def test_module_reuse(self):
Brett Cannon4ee2cda2009-02-01 03:08:31 +0000104 with source_util.create_modules('_temp') as mapping:
Brett Cannon45a5e3a2012-07-20 14:48:53 -0400105 loader = machinery.SourceFileLoader('_temp', mapping['_temp'])
Brett Cannon30b047d2009-02-01 02:05:11 +0000106 module = loader.load_module('_temp')
107 module_id = id(module)
108 module_dict_id = id(module.__dict__)
109 with open(mapping['_temp'], 'w') as file:
110 file.write("testing_var = 42\n")
Brett Cannon30b047d2009-02-01 02:05:11 +0000111 module = loader.load_module('_temp')
Eric V. Smithfaae3ad2012-06-27 15:26:26 -0400112 self.assertIn('testing_var', module.__dict__,
Brett Cannon30b047d2009-02-01 02:05:11 +0000113 "'testing_var' not in "
114 "{0}".format(list(module.__dict__.keys())))
115 self.assertEqual(module, sys.modules['_temp'])
116 self.assertEqual(id(module), module_id)
117 self.assertEqual(id(module.__dict__), module_dict_id)
118
119 def test_state_after_failure(self):
120 # A failed reload should leave the original module intact.
121 attributes = ('__file__', '__path__', '__package__')
122 value = '<test>'
123 name = '_temp'
Brett Cannon4ee2cda2009-02-01 03:08:31 +0000124 with source_util.create_modules(name) as mapping:
Brett Cannon30b047d2009-02-01 02:05:11 +0000125 orig_module = imp.new_module(name)
126 for attr in attributes:
127 setattr(orig_module, attr, value)
128 with open(mapping[name], 'w') as file:
129 file.write('+++ bad syntax +++')
Brett Cannon45a5e3a2012-07-20 14:48:53 -0400130 loader = machinery.SourceFileLoader('_temp', mapping['_temp'])
Brett Cannon2153dc02009-08-27 23:49:21 +0000131 with self.assertRaises(SyntaxError):
132 loader.load_module(name)
Brett Cannon30b047d2009-02-01 02:05:11 +0000133 for attr in attributes:
134 self.assertEqual(getattr(orig_module, attr), value)
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000135
136 # [syntax error]
137 def test_bad_syntax(self):
Brett Cannon4ee2cda2009-02-01 03:08:31 +0000138 with source_util.create_modules('_temp') as mapping:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000139 with open(mapping['_temp'], 'w') as file:
140 file.write('=')
Brett Cannon45a5e3a2012-07-20 14:48:53 -0400141 loader = machinery.SourceFileLoader('_temp', mapping['_temp'])
Brett Cannon2153dc02009-08-27 23:49:21 +0000142 with self.assertRaises(SyntaxError):
143 loader.load_module('_temp')
Eric V. Smithfaae3ad2012-06-27 15:26:26 -0400144 self.assertNotIn('_temp', sys.modules)
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000145
Brett Cannond71bed32010-07-03 22:18:47 +0000146 def test_file_from_empty_string_dir(self):
147 # Loading a module found from an empty string entry on sys.path should
148 # not only work, but keep all attributes relative.
Brett Cannon186335b2010-08-22 22:11:06 +0000149 file_path = '_temp.py'
150 with open(file_path, 'w') as file:
Brett Cannond71bed32010-07-03 22:18:47 +0000151 file.write("# test file for importlib")
152 try:
153 with util.uncache('_temp'):
Brett Cannon45a5e3a2012-07-20 14:48:53 -0400154 loader = machinery.SourceFileLoader('_temp', file_path)
Brett Cannond71bed32010-07-03 22:18:47 +0000155 mod = loader.load_module('_temp')
Brett Cannon186335b2010-08-22 22:11:06 +0000156 self.assertEqual(file_path, mod.__file__)
157 self.assertEqual(imp.cache_from_source(file_path),
Brett Cannond71bed32010-07-03 22:18:47 +0000158 mod.__cached__)
Brett Cannond71bed32010-07-03 22:18:47 +0000159 finally:
Brett Cannon186335b2010-08-22 22:11:06 +0000160 os.unlink(file_path)
161 pycache = os.path.dirname(imp.cache_from_source(file_path))
Ezio Melottic28f6fa2013-03-16 19:48:51 +0200162 if os.path.exists(pycache):
163 shutil.rmtree(pycache)
Brett Cannond71bed32010-07-03 22:18:47 +0000164
Benjamin Peterson36736702014-02-27 13:49:34 -0500165 @source_util.writes_bytecode_files
Antoine Pitrou2be60af2012-01-24 17:44:06 +0100166 def test_timestamp_overflow(self):
167 # When a modification timestamp is larger than 2**32, it should be
168 # truncated rather than raise an OverflowError.
169 with source_util.create_modules('_temp') as mapping:
170 source = mapping['_temp']
171 compiled = imp.cache_from_source(source)
172 with open(source, 'w') as f:
173 f.write("x = 5")
Antoine Pitroudd21f682012-01-25 03:00:57 +0100174 try:
Antoine Pitrou33d15f72012-01-25 18:01:45 +0100175 os.utime(source, (2 ** 33 - 5, 2 ** 33 - 5))
Antoine Pitroudd21f682012-01-25 03:00:57 +0100176 except OverflowError:
177 self.skipTest("cannot set modification time to large integer")
178 except OSError as e:
179 if e.errno != getattr(errno, 'EOVERFLOW', None):
180 raise
181 self.skipTest("cannot set modification time to large integer ({})".format(e))
Brett Cannon45a5e3a2012-07-20 14:48:53 -0400182 loader = machinery.SourceFileLoader('_temp', mapping['_temp'])
Antoine Pitrou2be60af2012-01-24 17:44:06 +0100183 mod = loader.load_module('_temp')
184 # Sanity checks.
185 self.assertEqual(mod.__cached__, compiled)
186 self.assertEqual(mod.x, 5)
187 # The pyc file was created.
188 os.stat(compiled)
189
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000190
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000191class BadBytecodeTest(unittest.TestCase):
192
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000193 def import_(self, file, module_name):
Brett Cannon61b14252010-07-03 21:48:25 +0000194 loader = self.loader(module_name, file)
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000195 module = loader.load_module(module_name)
Eric V. Smithfaae3ad2012-06-27 15:26:26 -0400196 self.assertIn(module_name, sys.modules)
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000197
Brett Cannon9b3e15f2010-02-19 16:01:06 +0000198 def manipulate_bytecode(self, name, mapping, manipulator, *,
199 del_source=False):
200 """Manipulate the bytecode of a module by passing it into a callable
201 that returns what to use as the new bytecode."""
202 try:
203 del sys.modules['_temp']
204 except KeyError:
205 pass
206 py_compile.compile(mapping[name])
Brett Cannon61b14252010-07-03 21:48:25 +0000207 if not del_source:
208 bytecode_path = imp.cache_from_source(mapping[name])
209 else:
Brett Cannon9b3e15f2010-02-19 16:01:06 +0000210 os.unlink(mapping[name])
Brett Cannon61b14252010-07-03 21:48:25 +0000211 bytecode_path = make_legacy_pyc(mapping[name])
212 if manipulator:
213 with open(bytecode_path, 'rb') as file:
214 bc = file.read()
215 new_bc = manipulator(bc)
216 with open(bytecode_path, 'wb') as file:
217 if new_bc is not None:
218 file.write(new_bc)
Brett Cannon9b3e15f2010-02-19 16:01:06 +0000219 return bytecode_path
220
Brett Cannon61b14252010-07-03 21:48:25 +0000221 def _test_empty_file(self, test, *, del_source=False):
222 with source_util.create_modules('_temp') as mapping:
223 bc_path = self.manipulate_bytecode('_temp', mapping,
224 lambda bc: b'',
225 del_source=del_source)
226 test('_temp', mapping, bc_path)
227
228 @source_util.writes_bytecode_files
229 def _test_partial_magic(self, test, *, del_source=False):
230 # When their are less than 4 bytes to a .pyc, regenerate it if
231 # possible, else raise ImportError.
232 with source_util.create_modules('_temp') as mapping:
233 bc_path = self.manipulate_bytecode('_temp', mapping,
234 lambda bc: bc[:3],
235 del_source=del_source)
236 test('_temp', mapping, bc_path)
237
238 def _test_magic_only(self, test, *, del_source=False):
239 with source_util.create_modules('_temp') as mapping:
240 bc_path = self.manipulate_bytecode('_temp', mapping,
241 lambda bc: bc[:4],
242 del_source=del_source)
243 test('_temp', mapping, bc_path)
244
245 def _test_partial_timestamp(self, test, *, del_source=False):
246 with source_util.create_modules('_temp') as mapping:
247 bc_path = self.manipulate_bytecode('_temp', mapping,
248 lambda bc: bc[:7],
249 del_source=del_source)
250 test('_temp', mapping, bc_path)
251
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100252 def _test_partial_size(self, test, *, del_source=False):
253 with source_util.create_modules('_temp') as mapping:
254 bc_path = self.manipulate_bytecode('_temp', mapping,
255 lambda bc: bc[:11],
256 del_source=del_source)
257 test('_temp', mapping, bc_path)
258
Brett Cannon61b14252010-07-03 21:48:25 +0000259 def _test_no_marshal(self, *, del_source=False):
260 with source_util.create_modules('_temp') as mapping:
261 bc_path = self.manipulate_bytecode('_temp', mapping,
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100262 lambda bc: bc[:12],
Brett Cannon61b14252010-07-03 21:48:25 +0000263 del_source=del_source)
264 file_path = mapping['_temp'] if not del_source else bc_path
265 with self.assertRaises(EOFError):
266 self.import_(file_path, '_temp')
267
268 def _test_non_code_marshal(self, *, del_source=False):
269 with source_util.create_modules('_temp') as mapping:
270 bytecode_path = self.manipulate_bytecode('_temp', mapping,
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100271 lambda bc: bc[:12] + marshal.dumps(b'abcd'),
Brett Cannon61b14252010-07-03 21:48:25 +0000272 del_source=del_source)
273 file_path = mapping['_temp'] if not del_source else bytecode_path
Brett Cannonbbb66802012-04-12 21:09:01 -0400274 with self.assertRaises(ImportError) as cm:
Brett Cannon61b14252010-07-03 21:48:25 +0000275 self.import_(file_path, '_temp')
Brett Cannonbbb66802012-04-12 21:09:01 -0400276 self.assertEqual(cm.exception.name, '_temp')
277 self.assertEqual(cm.exception.path, bytecode_path)
Brett Cannon61b14252010-07-03 21:48:25 +0000278
279 def _test_bad_marshal(self, *, del_source=False):
280 with source_util.create_modules('_temp') as mapping:
281 bytecode_path = self.manipulate_bytecode('_temp', mapping,
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100282 lambda bc: bc[:12] + b'<test>',
Brett Cannon61b14252010-07-03 21:48:25 +0000283 del_source=del_source)
284 file_path = mapping['_temp'] if not del_source else bytecode_path
Vinay Sajip5bdae3b2011-07-02 16:42:47 +0100285 with self.assertRaises(EOFError):
Brett Cannon61b14252010-07-03 21:48:25 +0000286 self.import_(file_path, '_temp')
287
288 def _test_bad_magic(self, test, *, del_source=False):
289 with source_util.create_modules('_temp') as mapping:
290 bc_path = self.manipulate_bytecode('_temp', mapping,
291 lambda bc: b'\x00\x00\x00\x00' + bc[4:])
292 test('_temp', mapping, bc_path)
293
294
295class SourceLoaderBadBytecodeTest(BadBytecodeTest):
296
Brett Cannon45a5e3a2012-07-20 14:48:53 -0400297 loader = machinery.SourceFileLoader
Brett Cannon61b14252010-07-03 21:48:25 +0000298
Brett Cannon9b3e15f2010-02-19 16:01:06 +0000299 @source_util.writes_bytecode_files
300 def test_empty_file(self):
301 # When a .pyc is empty, regenerate it if possible, else raise
302 # ImportError.
Brett Cannon61b14252010-07-03 21:48:25 +0000303 def test(name, mapping, bytecode_path):
304 self.import_(mapping[name], name)
305 with open(bytecode_path, 'rb') as file:
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100306 self.assertGreater(len(file.read()), 12)
Brett Cannon9b3e15f2010-02-19 16:01:06 +0000307
Brett Cannon61b14252010-07-03 21:48:25 +0000308 self._test_empty_file(test)
309
Brett Cannon9b3e15f2010-02-19 16:01:06 +0000310 def test_partial_magic(self):
Brett Cannon61b14252010-07-03 21:48:25 +0000311 def test(name, mapping, bytecode_path):
312 self.import_(mapping[name], name)
313 with open(bytecode_path, 'rb') as file:
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100314 self.assertGreater(len(file.read()), 12)
Brett Cannon61b14252010-07-03 21:48:25 +0000315
316 self._test_partial_magic(test)
Brett Cannon9b3e15f2010-02-19 16:01:06 +0000317
318 @source_util.writes_bytecode_files
319 def test_magic_only(self):
320 # When there is only the magic number, regenerate the .pyc if possible,
321 # else raise EOFError.
Brett Cannon61b14252010-07-03 21:48:25 +0000322 def test(name, mapping, bytecode_path):
323 self.import_(mapping[name], name)
324 with open(bytecode_path, 'rb') as file:
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100325 self.assertGreater(len(file.read()), 12)
Brett Cannon9b3e15f2010-02-19 16:01:06 +0000326
Antoine Pitrou7c9907e2011-12-30 21:25:15 +0100327 self._test_magic_only(test)
328
Brett Cannon1262e7c2009-05-11 01:47:11 +0000329 @source_util.writes_bytecode_files
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000330 def test_bad_magic(self):
Brett Cannon9b3e15f2010-02-19 16:01:06 +0000331 # When the magic number is different, the bytecode should be
332 # regenerated.
Brett Cannon61b14252010-07-03 21:48:25 +0000333 def test(name, mapping, bytecode_path):
334 self.import_(mapping[name], name)
335 with open(bytecode_path, 'rb') as bytecode_file:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000336 self.assertEqual(bytecode_file.read(4), imp.get_magic())
337
Brett Cannon61b14252010-07-03 21:48:25 +0000338 self._test_bad_magic(test)
339
340 @source_util.writes_bytecode_files
341 def test_partial_timestamp(self):
342 # When the timestamp is partial, regenerate the .pyc, else
343 # raise EOFError.
344 def test(name, mapping, bc_path):
345 self.import_(mapping[name], name)
346 with open(bc_path, 'rb') as file:
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100347 self.assertGreater(len(file.read()), 12)
Brett Cannon61b14252010-07-03 21:48:25 +0000348
Antoine Pitrou7c9907e2011-12-30 21:25:15 +0100349 self._test_partial_timestamp(test)
350
Brett Cannon61b14252010-07-03 21:48:25 +0000351 @source_util.writes_bytecode_files
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100352 def test_partial_size(self):
353 # When the size is partial, regenerate the .pyc, else
354 # raise EOFError.
355 def test(name, mapping, bc_path):
356 self.import_(mapping[name], name)
357 with open(bc_path, 'rb') as file:
358 self.assertGreater(len(file.read()), 12)
359
360 self._test_partial_size(test)
361
362 @source_util.writes_bytecode_files
Brett Cannon61b14252010-07-03 21:48:25 +0000363 def test_no_marshal(self):
364 # When there is only the magic number and timestamp, raise EOFError.
365 self._test_no_marshal()
366
367 @source_util.writes_bytecode_files
368 def test_non_code_marshal(self):
369 self._test_non_code_marshal()
370 # XXX ImportError when sourceless
371
372 # [bad marshal]
373 @source_util.writes_bytecode_files
374 def test_bad_marshal(self):
375 # Bad marshal data should raise a ValueError.
376 self._test_bad_marshal()
377
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000378 # [bad timestamp]
Brett Cannon1262e7c2009-05-11 01:47:11 +0000379 @source_util.writes_bytecode_files
Brett Cannon61b14252010-07-03 21:48:25 +0000380 def test_old_timestamp(self):
Brett Cannon9b3e15f2010-02-19 16:01:06 +0000381 # When the timestamp is older than the source, bytecode should be
382 # regenerated.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000383 zeros = b'\x00\x00\x00\x00'
Brett Cannon4ee2cda2009-02-01 03:08:31 +0000384 with source_util.create_modules('_temp') as mapping:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000385 py_compile.compile(mapping['_temp'])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000386 bytecode_path = imp.cache_from_source(mapping['_temp'])
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000387 with open(bytecode_path, 'r+b') as bytecode_file:
388 bytecode_file.seek(4)
389 bytecode_file.write(zeros)
390 self.import_(mapping['_temp'], '_temp')
391 source_mtime = os.path.getmtime(mapping['_temp'])
392 source_timestamp = importlib._w_long(source_mtime)
393 with open(bytecode_path, 'rb') as bytecode_file:
394 bytecode_file.seek(4)
395 self.assertEqual(bytecode_file.read(4), source_timestamp)
396
Brett Cannone52c9192009-11-07 23:55:05 +0000397 # [bytecode read-only]
398 @source_util.writes_bytecode_files
399 def test_read_only_bytecode(self):
Brett Cannon9b3e15f2010-02-19 16:01:06 +0000400 # When bytecode is read-only but should be rewritten, fail silently.
Brett Cannone52c9192009-11-07 23:55:05 +0000401 with source_util.create_modules('_temp') as mapping:
402 # Create bytecode that will need to be re-created.
403 py_compile.compile(mapping['_temp'])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000404 bytecode_path = imp.cache_from_source(mapping['_temp'])
Brett Cannone52c9192009-11-07 23:55:05 +0000405 with open(bytecode_path, 'r+b') as bytecode_file:
406 bytecode_file.seek(0)
407 bytecode_file.write(b'\x00\x00\x00\x00')
408 # Make the bytecode read-only.
409 os.chmod(bytecode_path,
410 stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
411 try:
412 # Should not raise IOError!
413 self.import_(mapping['_temp'], '_temp')
414 finally:
415 # Make writable for eventual clean-up.
416 os.chmod(bytecode_path, stat.S_IWUSR)
417
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000418
Brett Cannon61b14252010-07-03 21:48:25 +0000419class SourcelessLoaderBadBytecodeTest(BadBytecodeTest):
420
Brett Cannon45a5e3a2012-07-20 14:48:53 -0400421 loader = machinery.SourcelessFileLoader
Brett Cannon61b14252010-07-03 21:48:25 +0000422
423 def test_empty_file(self):
424 def test(name, mapping, bytecode_path):
Brett Cannonbbb66802012-04-12 21:09:01 -0400425 with self.assertRaises(ImportError) as cm:
Brett Cannon61b14252010-07-03 21:48:25 +0000426 self.import_(bytecode_path, name)
Brett Cannonbbb66802012-04-12 21:09:01 -0400427 self.assertEqual(cm.exception.name, name)
428 self.assertEqual(cm.exception.path, bytecode_path)
Brett Cannon61b14252010-07-03 21:48:25 +0000429
430 self._test_empty_file(test, del_source=True)
431
432 def test_partial_magic(self):
433 def test(name, mapping, bytecode_path):
Brett Cannonbbb66802012-04-12 21:09:01 -0400434 with self.assertRaises(ImportError) as cm:
Brett Cannon61b14252010-07-03 21:48:25 +0000435 self.import_(bytecode_path, name)
Brett Cannonbbb66802012-04-12 21:09:01 -0400436 self.assertEqual(cm.exception.name, name)
437 self.assertEqual(cm.exception.path, bytecode_path)
Brett Cannon61b14252010-07-03 21:48:25 +0000438 self._test_partial_magic(test, del_source=True)
439
440 def test_magic_only(self):
441 def test(name, mapping, bytecode_path):
442 with self.assertRaises(EOFError):
443 self.import_(bytecode_path, name)
444
445 self._test_magic_only(test, del_source=True)
446
447 def test_bad_magic(self):
448 def test(name, mapping, bytecode_path):
Brett Cannonbbb66802012-04-12 21:09:01 -0400449 with self.assertRaises(ImportError) as cm:
Brett Cannon61b14252010-07-03 21:48:25 +0000450 self.import_(bytecode_path, name)
Brett Cannonbbb66802012-04-12 21:09:01 -0400451 self.assertEqual(cm.exception.name, name)
452 self.assertEqual(cm.exception.path, bytecode_path)
Brett Cannon61b14252010-07-03 21:48:25 +0000453
454 self._test_bad_magic(test, del_source=True)
455
456 def test_partial_timestamp(self):
457 def test(name, mapping, bytecode_path):
458 with self.assertRaises(EOFError):
459 self.import_(bytecode_path, name)
460
461 self._test_partial_timestamp(test, del_source=True)
462
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100463 def test_partial_size(self):
464 def test(name, mapping, bytecode_path):
465 with self.assertRaises(EOFError):
466 self.import_(bytecode_path, name)
467
468 self._test_partial_size(test, del_source=True)
469
Brett Cannon61b14252010-07-03 21:48:25 +0000470 def test_no_marshal(self):
471 self._test_no_marshal(del_source=True)
472
473 def test_non_code_marshal(self):
474 self._test_non_code_marshal(del_source=True)
475
476
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000477def test_main():
478 from test.support import run_unittest
Brett Cannon61b14252010-07-03 21:48:25 +0000479 run_unittest(SimpleTest,
480 SourceLoaderBadBytecodeTest,
481 SourcelessLoaderBadBytecodeTest
Brett Cannon186335b2010-08-22 22:11:06 +0000482 )
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000483
484
485if __name__ == '__main__':
486 test_main()