Debian Codegraph @

pypy/module/imp/test/test_import.py

raw symbols SCIP
1 # coding: utf-8
2 import py
3 from pypy.interpreter.module import Module
4 from pypy.interpreter import gateway
5 from pypy.interpreter.error import OperationError
6 from pypy.interpreter.pycode import PyCode
7 from pypy.interpreter.test.test_fsencode import BaseFSEncodeTest
8 from rpython.tool.udir import udir
9 from rpython.rlib import streamio
10 from pypy.tool.option import make_config
11 from pypy.tool.pytest.objspace import maketestobjspace
12 import pytest
13 import sys, os
14 import tempfile, marshal
15
16 from pypy.module.imp import importing
17
18 from pypy import conftest
19
20
21 def _read_n(stream, n):
22 buf = ''
23 while len(buf) < n:
24 data = stream.read(n - len(buf))
25 if not data:
26 raise streamio.StreamError("end of file")
27 buf += data
28 return buf
29
30 def _r_long(stream):
31 s = _read_n(stream, 4)
32 return importing._get_long(s)
33
34 def _w_long(stream, x):
35 a = x & 0xff
36 x >>= 8
37 b = x & 0xff
38 x >>= 8
39 c = x & 0xff
40 x >>= 8
41 d = x & 0xff
42 stream.write(chr(a) + chr(b) + chr(c) + chr(d))
43
44 def setuppkg(pkgname, **entries):
45 p = udir.join('impsubdir')
46 if pkgname:
47 p = p.join(*pkgname.split('.'))
48 p.ensure(dir=1)
49 with p.join("__init__.py").open('w') as f:
50 print >> f, "# package"
51 for filename, content in entries.items():
52 filename += '.py'
53 with p.join(filename).open('w') as f:
54 print >> f, '#', filename
55 print >> f, content
56 return p
57
58 def setup_directory_structure(cls):
59 space = cls.space
60 root = setuppkg("",
61 a = "imamodule = 1\ninpackage = 0",
62 ambig = "imamodule = 1",
63 test_reload = "def test():\n raise ValueError\n",
64 infinite_reload = "import infinite_reload, imp; imp.reload(infinite_reload)",
65 del_sys_module = "import sys\ndel sys.modules['del_sys_module']\n",
66 gc = "should_never_be_seen = 42\n",
67 )
68 root.ensure("packagenamespace", dir=1) # empty, no __init__.py
69 setuppkg("pkg",
70 a = "imamodule = 1\ninpackage = 1",
71 b = "imamodule = 1\ninpackage = 1",
72 relative_a = "import a",
73 abs_b = "import b",
74 abs_x_y = "import x.y",
75 abs_sys = "import sys",
76 struct = "inpackage = 1",
77 errno = "",
78 # Python 3 note: this __future__ has no effect any more,
79 # kept around for testing and to avoid increasing the diff
80 # with PyPy2
81 absolute = "from __future__ import absolute_import\nimport struct",
82 relative_b = "from __future__ import absolute_import\nfrom . import struct",
83 relative_c = "from __future__ import absolute_import\nfrom .struct import inpackage",
84 relative_f = "from .imp import get_magic",
85 relative_g = "import imp; from .imp import get_magic",
86 inpackage = "inpackage = 1",
87 function_a = "g = {'__name__': 'pkg.a'}; __import__('inpackage', g); print(g)",
88 function_b = "g = {'__name__': 'not.a'}; __import__('inpackage', g); print(g)",
89 )
90 setuppkg("pkg.pkg1",
91 __init__ = 'from . import a',
92 a = '',
93 relative_d = "from __future__ import absolute_import\nfrom ..struct import inpackage",
94 relative_e = "from __future__ import absolute_import\nfrom .. import struct",
95 relative_g = "from .. import pkg1\nfrom ..pkg1 import b",
96 b = "insubpackage = 1",
97 )
98 setuppkg("pkg.pkg2", a='', b='')
99 setuppkg("pkg.withall",
100 __init__ = "__all__ = ['foobar', 'barbaz']",
101 foobar = "found = 123",
102 barbaz = "other = 543")
103 setuppkg("pkg.withoutall",
104 __init__ = "globals()[''] = 456",
105 foobar = "found = 123\n")
106 setuppkg("pkg.bogusall",
107 __init__ = "__all__ = 42")
108 setuppkg("pkg_r", inpkg = "import x.y")
109 setuppkg("pkg_r.x", y='')
110 setuppkg("x")
111 setuppkg("ambig", __init__ = "imapackage = 1")
112 setuppkg("pkg_relative_a",
113 __init__ = "import a",
114 a = "imamodule = 1\ninpackage = 1",
115 )
116 setuppkg("evil_pkg",
117 evil = "import sys\n"
118 "from evil_pkg import good\n"
119 "sys.modules['evil_pkg.evil'] = good",
120 good = "a = 42")
121 p = setuppkg("readonly", x='')
122 p = setuppkg("pkg_univnewlines")
123 p.join('__init__.py').write(
124 'a=5\nb=6\rc="""hello\r\nworld"""\r', mode='wb')
125 p.join('mod.py').write(
126 'a=15\nb=16\rc="""foo\r\nbar"""\r', mode='wb')
127 setuppkg("verbose1pkg", verbosemod='a = 1729')
128 setuppkg("verbose2pkg", verbosemod='a = 1729')
129 setuppkg("verbose0pkg", verbosemod='a = 1729')
130 setuppkg("test_bytecode",
131 a = '',
132 b = '',
133 c = '')
134 setuppkg('circular',
135 circ1="from . import circ2",
136 circ2="from . import circ1")
137 setuppkg('absolute_circular',
138 circ1 = "from absolute_circular.circ2 import a; b = 1",
139 circ2 = "from absolute_circular.circ1 import b; a = 1")
140 setuppkg('circular_subpkg.subpkg2.parent',
141 __init__ = 'import circular_subpkg.subpkg2.parent.child',
142 child = 'import circular_subpkg.subpkg2.parent\n\ncircular_subpkg.subpkg2.parent')
143 setuppkg('module_with_wrong_all',
144 __init__ = "__all__ = ['x', 'y', 3, 'z']; x, y, z = 1, 2, 3")
145
146 p = setuppkg("encoded",
147 # actually a line 2, setuppkg() sets up a line1
148 line2 = "# encoding: iso-8859-1\n",
149 bad = "# encoding: uft-8\n")
150
151 special_char = getattr(cls, 'special_char', None)
152 if special_char is not None:
153 special_char = special_char.encode(sys.getfilesystemencoding())
154 p.join(special_char + '.py').write('pass')
155
156 # create a .pyw file
157 p = setuppkg("windows", x = "x = 78")
158 try:
159 p.join('x.pyw').remove()
160 except py.error.ENOENT:
161 pass
162 p.join('x.py').rename(p.join('x.pyw'))
163
164 if hasattr(p, "mksymlinkto"):
165 p = root.join("devnullpkg")
166 p.ensure(dir=True)
167 p.join("__init__.py").mksymlinkto(os.devnull)
168
169 return str(root)
170
171
172 def _setup(cls):
173 space = cls.space
174 dn = setup_directory_structure(cls)
175 return _setup_path(space, dn)
176
177 def _setup_path(space, path):
178 return space.appexec([space.wrap(path)], """
179 (dn):
180 import sys
181 path = list(sys.path)
182 sys.path.insert(0, dn)
183 return path, sys.modules.copy()
184 """)
185
186 def _teardown(space, w_saved_modules):
187 p = udir.join('impsubdir')
188 if p.check():
189 # On windows when running multi-threaded, tests will hold the resource open
190 p.remove(ignore_errors=True)
191 space.appexec([w_saved_modules], """
192 (path_and_modules):
193 saved_path, saved_modules = path_and_modules
194 import sys
195 sys.path[:] = saved_path
196 sys.modules.clear()
197 sys.modules.update(saved_modules)
198 """)
199
200
201 class AppTestImport(BaseFSEncodeTest):
202 spaceconfig = {
203 "usemodules": ['_md5', 'time', 'struct'],
204 }
205
206 def setup_class(cls):
207 BaseFSEncodeTest.setup_class.im_func(cls)
208 cls.w_runappdirect = cls.space.wrap(conftest.option.runappdirect)
209 cls.w_saved_modules = _setup(cls)
210 #XXX Compile class
211
212 def teardown_class(cls):
213 return
214 _teardown(cls.space, cls.w_saved_modules)
215
216 def w_exec_(self, cmd, ns):
217 exec(cmd, ns)
218
219 def test_set_sys_modules_during_import(self):
220 from evil_pkg import evil
221 assert evil.a == 42
222
223 def test_import_namespace_package(self):
224 import packagenamespace
225 try:
226 from packagenamespace import nothing
227 except ImportError as e:
228 assert str(e) == ("cannot import name 'nothing' from "
229 "'packagenamespace' (unknown location)")
230 else:
231 assert False
232
233 def test_import_sys(self):
234 import sys
235
236 def test_import_a(self):
237 import sys
238 import a
239 assert a == sys.modules.get('a')
240
241 def test_import_a_cache(self):
242 import sys
243 import a
244 a0 = a
245 import a
246 assert a == a0
247
248 def test_trailing_slash(self):
249 import sys
250 try:
251 sys.path[0] += '/'
252 import a
253 finally:
254 sys.path[0] = sys.path[0].rstrip('/')
255
256 def test_import_pkg(self):
257 import sys
258 import pkg
259 assert pkg == sys.modules.get('pkg')
260
261 def test_import_dotted(self):
262 import sys
263 import pkg.a
264 assert pkg == sys.modules.get('pkg')
265 assert pkg.a == sys.modules.get('pkg.a')
266
267 def test_import_keywords(self):
268 __import__(name='sys', level=0)
269
270 def test_import_nonutf8_encodable(self):
271 exc = raises(ImportError, __import__, '\ud800')
272 assert exc.value.args[0].startswith("No module named ")
273
274 def test_import_by_filename(self):
275 import pkg.a
276 filename = pkg.a.__file__
277 assert filename.endswith('.py')
278 exc = raises(ImportError, __import__, filename[:-3])
279 assert exc.value.args[0].startswith("No module named ")
280
281 def test_import_badcase(self):
282 def missing(name):
283 try:
284 __import__(name)
285 except ImportError:
286 pass
287 else:
288 raise Exception("import should not have succeeded: %r" %
289 (name,))
290 missing("Sys")
291 missing("SYS")
292 missing("fuNCTionAl")
293 missing("pKg")
294 missing("pKg.a")
295 missing("pkg.A")
296
297 def test_import_dotted_cache(self):
298 import sys
299 import pkg.a
300 assert pkg == sys.modules.get('pkg')
301 assert pkg.a == sys.modules.get('pkg.a')
302 pkg0 = pkg
303 pkg_a0 = pkg.a
304 import pkg.a
305 assert pkg == pkg0
306 assert pkg.a == pkg_a0
307
308 def test_import_dotted2(self):
309 import sys
310 import pkg.pkg1.a
311 assert pkg == sys.modules.get('pkg')
312 assert pkg.pkg1 == sys.modules.get('pkg.pkg1')
313 assert pkg.pkg1.a == sys.modules.get('pkg.pkg1.a')
314
315 def test_import_ambig(self):
316 import sys
317 import ambig
318 assert ambig == sys.modules.get('ambig')
319 assert hasattr(ambig,'imapackage')
320
321 def test_from_a(self):
322 import sys
323 from a import imamodule
324 assert 'a' in sys.modules
325 assert imamodule == 1
326
327 def test_from_dotted(self):
328 import sys
329 from pkg.a import imamodule
330 assert 'pkg' in sys.modules
331 assert 'pkg.a' in sys.modules
332 assert imamodule == 1
333
334 def test_from_pkg_import_module(self):
335 import sys
336 from pkg import a
337 assert 'pkg' in sys.modules
338 assert 'pkg.a' in sys.modules
339 pkg = sys.modules.get('pkg')
340 assert a == pkg.a
341 aa = sys.modules.get('pkg.a')
342 assert a == aa
343
344 def test_import_absolute(self):
345 from pkg import relative_a
346 assert relative_a.a.inpackage == 0
347
348 def test_import_absolute_dont_default_to_relative(self):
349 def imp():
350 from pkg import abs_b
351 raises(ImportError, imp)
352
353 def test_import_pkg_absolute(self):
354 import pkg_relative_a
355 assert pkg_relative_a.a.inpackage == 0
356
357 def test_import_absolute_partial_success(self):
358 def imp():
359 import pkg_r.inpkg
360 raises(ImportError, imp)
361
362 def test_import_builtin_inpackage(self):
363 def imp():
364 import pkg.sys
365 raises(ImportError,imp)
366
367 import sys, pkg.abs_sys
368 assert pkg.abs_sys.sys is sys
369
370 import errno, pkg.errno
371 assert pkg.errno is not errno
372
373 def test_import_Globals_Are_None(self):
374 import sys
375 m = __import__('sys')
376 assert sys == m
377 n = __import__('sys', None, None, [''])
378 assert sys == n
379 o = __import__('sys', [], [], ['']) # CPython accepts this
380 assert sys == o
381
382 def test_import_fromlist_must_not_contain_bytes(self):
383 raises(TypeError, __import__, 'encodings', None, None, [b'xxx'])
384
385 def test_proper_failure_on_killed__path__(self):
386 import pkg.pkg2.a
387 del pkg.pkg2.__path__
388 def imp_b():
389 import pkg.pkg2.b
390 raises(ImportError,imp_b)
391
392 @pytest.mark.skipif("sys.platform != 'win32'")
393 def test_pyw(self):
394 import windows.x
395 assert windows.x.__file__.endswith('x.pyw')
396
397 def test_cannot_write_pyc(self):
398 import sys, os
399 p = os.path.join(sys.path[0], 'readonly')
400 try:
401 os.chmod(p, 0o555)
402 except:
403 skip("cannot chmod() the test directory to read-only")
404 try:
405 import readonly.x # cannot write x.pyc, but should not crash
406 finally:
407 os.chmod(p, 0o775)
408 assert "__pycache__" in readonly.x.__cached__
409
410 def test__import__empty_string(self):
411 raises(ValueError, __import__, "")
412
413 def test_py_directory(self):
414 import imp, os, sys
415 source = os.path.join(sys.path[0], 'foo.py')
416 os.mkdir(source)
417 try:
418 raises(ImportError, imp.find_module, 'foo')
419 finally:
420 os.rmdir(source)
421
422 def test_invalid__name__(self):
423 glob = {}
424 exec("__name__ = None; import sys", glob)
425 import sys
426 assert glob['sys'] is sys
427
428 def test_future_absolute_import(self):
429 def imp():
430 from pkg import absolute
431 assert hasattr(absolute.struct, 'pack')
432 imp()
433
434 def test_future_relative_import_without_from_name(self):
435 from pkg import relative_b
436 assert relative_b.struct.inpackage == 1
437
438 def test_no_relative_import(self):
439 def imp():
440 from pkg import relative_f
441 exc = raises(ImportError, imp)
442 assert exc.value.args[0] == "No module named 'pkg.imp'"
443
444 def test_no_relative_import_bug(self):
445 def imp():
446 from pkg import relative_g
447 exc = raises(ImportError, imp)
448 assert exc.value.args[0] == "No module named 'pkg.imp'"
449
450 def test_import_msg(self):
451 def imp():
452 import pkg.i_am_not_here.neither_am_i
453 exc = raises(ImportError, imp)
454 assert exc.value.args[0] == "No module named 'pkg.i_am_not_here'"
455
456 def test_future_relative_import_level_1(self):
457 from pkg import relative_c
458 assert relative_c.inpackage == 1
459
460 def test_future_relative_import_level_2(self):
461 from pkg.pkg1 import relative_d
462 assert relative_d.inpackage == 1
463
464 def test_future_relative_import_level_2_without_from_name(self):
465 from pkg.pkg1 import relative_e
466 assert relative_e.struct.inpackage == 1
467
468 def test_future_relative_import_level_3(self):
469 from pkg.pkg1 import relative_g
470 assert relative_g.b.insubpackage == 1
471 import pkg.pkg1
472 assert pkg.pkg1.__package__ == 'pkg.pkg1'
473
474 def test_future_relative_import_error_when_in_non_package(self):
475 ns = {'__name__': __name__}
476 exec("""def imp():
477 print('__name__ =', __name__)
478 from .struct import inpackage
479 """, ns)
480 raises(ImportError, ns['imp'])
481
482 def test_future_relative_import_error_when_in_non_package2(self):
483 ns = {'__name__': __name__}
484 exec("""def imp():
485 from .. import inpackage
486 """, ns)
487 raises(ImportError, ns['imp'])
488
489 def test_relative_import_with___name__(self):
490 import sys
491 mydict = {'__name__': 'sys.foo'}
492 res = __import__('', mydict, mydict, ('bar',), 1)
493 assert res is sys
494
495 def test_relative_import_with___name__and___path__(self):
496 import sys
497 import imp
498 foo = imp.new_module('foo')
499 sys.modules['sys.foo'] = foo
500 mydict = {'__name__': 'sys.foo', '__path__': '/some/path'}
501 res = __import__('', mydict, mydict, ('bar',), 1)
502 assert res is foo
503
504 def test_relative_import_pkg(self):
505 import sys
506 import imp
507 pkg = imp.new_module('newpkg')
508 sys.modules['newpkg'] = pkg
509 sys.modules['newpkg.foo'] = imp.new_module('newpkg.foo')
510 mydict = {'__name__': 'newpkg.foo', '__path__': '/some/path'}
511 res = __import__('', mydict, None, ['bar'], 2)
512 assert res is pkg
513
514 def test__package__(self):
515 # Regression test for http://bugs.python.org/issue3221.
516 def check_absolute():
517 self.exec_("from os import path", ns)
518 def check_relative():
519 self.exec_("from . import a", ns)
520
521 import pkg
522
523 # Check both OK with __package__ and __name__ correct
524 ns = dict(__package__='pkg', __name__='pkg.notarealmodule')
525 check_absolute()
526 check_relative()
527
528 # Check both OK with only __name__ wrong
529 ns = dict(__package__='pkg', __name__='notarealpkg.notarealmodule')
530 check_absolute()
531 check_relative()
532
533 # Check relative fails with only __package__ wrong
534 ns = dict(__package__='foo', __name__='pkg.notarealmodule')
535 check_absolute() # XXX check warnings
536 raises(ModuleNotFoundError, check_relative)
537
538 # Check relative fails with __package__ and __name__ wrong
539 ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule')
540 check_absolute() # XXX check warnings
541 raises(ModuleNotFoundError, check_relative)
542
543 # Check relative fails when __package__ set to a non-string
544 ns = dict(__package__=object())
545 check_absolute()
546 raises(TypeError, check_relative)
547
548 def test_relative_circular(self):
549 import circular.circ1 # doesn't fail
550
551 def test_partially_initialized_circular(self):
552 with raises(ImportError) as info:
553 import absolute_circular.circ1
554
555 assert ("cannot import name 'b' from partially initialized "
556 "module 'absolute_circular.circ1'") in info.value.msg
557
558 def test_absolute_circular_submodule(self):
559 with raises(AttributeError) as cm:
560 import circular_subpkg.subpkg2.parent
561 assert ("cannot access submodule 'parent' of module "
562 "'circular_subpkg.subpkg2' "
563 "(most likely due to a circular import)") in cm.value.args, cm.value.args
564
565 def test_import_function(self):
566 # More tests for __import__
567 import sys
568 raises(ModuleNotFoundError, "from pkg import function_b")
569
570 def test_universal_newlines(self):
571 import pkg_univnewlines
572 assert pkg_univnewlines.a == 5
573 assert pkg_univnewlines.b == 6
574 assert pkg_univnewlines.c == "hello\nworld"
575 from pkg_univnewlines import mod
576 assert mod.a == 15
577 assert mod.b == 16
578 assert mod.c == "foo\nbar"
579
580 def test_reload(self):
581 import test_reload, imp
582 try:
583 test_reload.test()
584 except ValueError:
585 pass
586
587 # If this test runs too quickly, test_reload.py's mtime
588 # attribute will remain unchanged even if the file is rewritten.
589 # Consequently, the file would not reload. So, added a sleep()
590 # delay to assure that a new, distinct timestamp is written.
591 import time
592 time.sleep(1)
593
594 with open(test_reload.__file__, "w") as f:
595 f.write("def test():\n raise NotImplementedError\n")
596 imp.reload(test_reload)
597 try:
598 test_reload.test()
599 except NotImplementedError:
600 pass
601
602 # Ensure that the file is closed
603 # (on windows at least)
604 import os
605 os.unlink(test_reload.__file__)
606
607 # restore it for later tests
608 with open(test_reload.__file__, "w") as f:
609 f.write("def test():\n raise ValueError\n")
610
611 def test_reload_failing(self):
612 import test_reload
613 import time, imp
614 time.sleep(1)
615 with open(test_reload.__file__, "w") as f:
616 f.write("a = 10 // 0\n")
617
618 # A failing reload should leave the previous module in sys.modules
619 raises(ZeroDivisionError, imp.reload, test_reload)
620 import os, sys
621 assert 'test_reload' in sys.modules
622 assert test_reload.test
623 os.unlink(test_reload.__file__)
624
625 def test_reload_submodule(self):
626 import pkg.a, imp
627 imp.reload(pkg.a)
628
629 def test_reload_builtin_doesnt_clear(self):
630 import imp
631 import sys
632 sys.foobar = "baz"
633 try:
634 imp.reload(sys)
635 assert sys.foobar == "baz"
636 finally:
637 del sys.foobar
638
639 def test_reimport_builtin_simple_case_1(self):
640 import sys, time
641 del time.time
642 assert not hasattr(time, 'time')
643 del sys.modules['time']
644 import time
645 assert hasattr(time, 'time')
646
647 def test_reimport_builtin_simple_case_2(self):
648 import sys, time
649 time.foo = "bar"
650 del sys.modules['time']
651 import time
652 assert not hasattr(time, 'foo')
653
654 def test_reimport_builtin(self):
655 import imp, sys, time
656 old_sleep = time.sleep
657 time.sleep = "<test_reimport_builtin removed this>"
658
659 del sys.modules['time']
660 import time as time1
661 assert sys.modules['time'] is time1
662
663 assert time.sleep == "<test_reimport_builtin removed this>"
664
665 imp.reload(time1) # don't leave a broken time.sleep behind
666 import time
667 assert time.sleep is old_sleep
668
669 def test_reload_infinite(self):
670 import infinite_reload
671
672 def test_reload_module_subclass(self):
673 import types, imp
674
675 #MyModType = types.ModuleType
676 class MyModType(types.ModuleType):
677 pass
678
679 m = MyModType("abc")
680 with raises(ImportError):
681 # Fails because the module is not in sys.modules, but *not* because
682 # it's a subtype of ModuleType.
683 imp.reload(m)
684
685
686 def test_explicitly_missing(self):
687 import sys
688 sys.modules['foobarbazmod'] = None
689 try:
690 import foobarbazmod
691 assert False, "should have failed, got instead %r" % (
692 foobarbazmod,)
693 except ImportError:
694 pass
695 finally:
696 del sys.modules['foobarbazmod']
697
698 def test_del_from_sys_modules(self):
699 try:
700 import del_sys_module
701 except KeyError:
702 pass # ok
703 else:
704 assert False, 'should not work'
705
706 def test_cache_from_source(self):
707 import imp, sys
708 if sys.platform == 'win32':
709 sep = '\\'
710 else:
711 sep = '/'
712 tag = sys.implementation.cache_tag
713 pycfile = imp.cache_from_source('a/b/c.py')
714 assert pycfile == sep.join(('a/b', '__pycache__', 'c.%s.pyc' % tag))
715 assert imp.source_from_cache('a/b/__pycache__/c.%s.pyc' % tag
716 ) == sep.join(('a/b', 'c.py'))
717 raises(ValueError, imp.source_from_cache, 'a/b/c.py')
718
719 @pytest.mark.skip("sys.version_info > (3, 6)")
720 def test_invalid_pathname(self):
721 import imp
722 import pkg
723 import os
724 pathname = os.path.join(os.path.dirname(pkg.__file__), 'a.py')
725 with open(pathname) as fid:
726 module = imp.load_module('a', fid,
727 'invalid_path_name', ('.py', 'r', imp.PY_SOURCE))
728 assert module.__name__ == 'a'
729 assert module.__file__ == 'invalid_path_name'
730
731 def test_crash_load_module(self):
732 import imp
733 raises(ValueError, imp.load_module, "", "", "", [1, 2, 3, 4])
734
735 def test_import_star_finds_submodules_with___all__(self):
736 for case in ["not-imported-yet", "already-imported"]:
737 d = {}
738 exec("from pkg.withall import *", d)
739 assert d["foobar"].found == 123
740 assert d["barbaz"].other == 543
741
742 def test_import_star_does_not_find_submodules_without___all__(self):
743 for case in ["not-imported-yet", "already-imported"]:
744 d = {}
745 exec("from pkg.withoutall import *", d)
746 assert "foobar" not in d
747 import pkg.withoutall.foobar # <- import it here only
748 for case in ["not-imported-yet", "already-imported"]:
749 d = {}
750 exec("from pkg.withoutall import *", d)
751 assert d["foobar"].found == 123
752
753 def test_import_star_empty_string(self):
754 for case in ["not-imported-yet", "already-imported"]:
755 d = {}
756 exec("from pkg.withoutall import *", d)
757 assert "" in d
758
759 def test_import_star_with_bogus___all__(self):
760 for case in ["not-imported-yet", "already-imported"]:
761 try:
762 exec("from pkg.bogusall import *", {})
763 except TypeError:
764 pass # 'int' object does not support indexing
765 else:
766 raise AssertionError("should have failed")
767
768 def test_import_star_with_mixed_types___all__(self):
769 with raises(TypeError) as info:
770 exec("from module_with_wrong_all import *")
771
772 assert "module_with_wrong_all.__all__ must be str, not int" in str(info.value)
773
774 def test_verbose_flag_0(self):
775 output = []
776 class StdErr(object):
777 def write(self, line):
778 output.append(line)
779 def flush(self):
780 return
781
782 import sys, imp
783 sys.stderr = StdErr()
784 try:
785 import verbose0pkg.verbosemod
786 finally:
787 imp.reload(sys)
788 assert not output
789
790 def test_source_encoding(self):
791 import imp
792 import encoded
793 fd = imp.find_module('line2', encoded.__path__)[0]
794 assert fd.encoding == 'iso-8859-1'
795 assert fd.tell() == 0
796
797 def test_bad_source_encoding(self):
798 import imp
799 import encoded
800 raises(SyntaxError, imp.find_module, 'bad', encoded.__path__)
801
802 def test_find_module_fsdecode(self):
803 name = self.special_char
804 if not name:
805 import sys
806 skip("can't run this test with %s as filesystem encoding"
807 % sys.getfilesystemencoding())
808 import imp
809 import encoded
810 f, filename, _ = imp.find_module(name, encoded.__path__)
811 assert f is not None
812 assert filename[:-3].endswith(name)
813
814 def test_unencodable(self):
815 if not self.testfn_unencodable:
816 skip("need an unencodable filename")
817 import imp
818 import os
819 name = self.testfn_unencodable
820 os.mkdir(name)
821 try:
822 raises(ImportError, imp.NullImporter, name)
823 finally:
824 os.rmdir(name)
825
826 @pytest.mark.skipif(not hasattr(py.path.local, "mksymlinkto"), reason="requires symlinks")
827 def test_dev_null_init_file(self):
828 import devnullpkg
829
830
831 class TestAbi:
832 def test_abi_tag(self):
833 space1 = maketestobjspace(make_config(None, soabi='footest'))
834 space2 = maketestobjspace(make_config(None, soabi=''))
835 assert importing.get_so_extension(space1).startswith('.footest')
836 if sys.platform == 'win32':
837 assert importing.get_so_extension(space2) == '.pyd'
838 else:
839 assert importing.get_so_extension(space2) == '.so'
840
841 def _getlong(data):
842 x = marshal.dumps(data)
843 return x[-4:]
844
845 def _testfile(space, magic, mtime, co=None):
846 cpathname = str(udir.join('test.pyc'))
847 f = file(cpathname, "wb")
848 f.write(_getlong(magic))
849 f.write(_getlong(mtime))
850 if co:
851 # marshal the code object with the PyPy marshal impl
852 pyco = space.createcompiler().compile(co, '?', 'exec', 0)
853 w_marshal = space.getbuiltinmodule('marshal')
854 w_marshaled_code = space.call_method(w_marshal, 'dumps', pyco)
855 marshaled_code = space.bytes_w(w_marshaled_code)
856 f.write(marshaled_code)
857 f.close()
858 return cpathname
859
860 def _testfilesource(source="x=42"):
861 pathname = str(udir.join('test.py'))
862 f = file(pathname, "wb")
863 f.write(source)
864 f.close()
865 return pathname
866
867 class TestPycStuff:
868 # ___________________ .pyc related stuff _________________
869
870 def test_read_compiled_module(self):
871 space = self.space
872 mtime = 12345
873 co = 'x = 42'
874 cpathname = _testfile(space, importing.get_pyc_magic(space), mtime, co)
875 stream = streamio.open_file_as_stream(cpathname, "rb")
876 try:
877 stream.seek(8, 0)
878 w_code = importing.read_compiled_module(
879 space, cpathname, stream.readall())
880 pycode = w_code
881 finally:
882 stream.close()
883 assert type(pycode) is PyCode
884 w_dic = space.newdict()
885 pycode.exec_code(space, w_dic, w_dic)
886 w_ret = space.getitem(w_dic, space.wrap('x'))
887 ret = space.int_w(w_ret)
888 assert ret == 42
889
890 def test_load_compiled_module(self):
891 space = self.space
892 mtime = 12345
893 co = 'x = 42'
894 cpathname = _testfile(space, importing.get_pyc_magic(space), mtime, co)
895 w_modulename = space.wrap('somemodule')
896 stream = streamio.open_file_as_stream(cpathname, "rb")
897 try:
898 w_mod = space.wrap(Module(space, w_modulename))
899 magic = _r_long(stream)
900 timestamp = _r_long(stream)
901 w_ret = importing.load_compiled_module(space,
902 w_modulename,
903 w_mod,
904 cpathname,
905 magic,
906 stream.readall())
907 finally:
908 stream.close()
909 assert w_mod is w_ret
910 w_ret = space.getattr(w_mod, space.wrap('x'))
911 ret = space.int_w(w_ret)
912 assert ret == 42
913
914 def test_load_compiled_module_nopathname(self):
915 space = self.space
916 mtime = 12345
917 co = 'x = 42'
918 cpathname = _testfile(space, importing.get_pyc_magic(space), mtime, co)
919 w_modulename = space.wrap('somemodule')
920 stream = streamio.open_file_as_stream(cpathname, "rb")
921 try:
922 w_mod = space.wrap(Module(space, w_modulename))
923 magic = _r_long(stream)
924 timestamp = _r_long(stream)
925 w_ret = importing.load_compiled_module(space,
926 w_modulename,
927 w_mod,
928 None,
929 magic,
930 stream.readall())
931 finally:
932 stream.close()
933 filename = space.getattr(w_ret, space.wrap('__file__'))
934 assert space.text_w(filename) == u'?'
935
936 def test_parse_source_module(self):
937 space = self.space
938 pathname = _testfilesource()
939 stream = streamio.open_file_as_stream(pathname, "r")
940 try:
941 w_ret = importing.parse_source_module(space,
942 pathname,
943 stream.readall())
944 finally:
945 stream.close()
946 pycode = w_ret
947 assert type(pycode) is PyCode
948 w_dic = space.newdict()
949 pycode.exec_code(space, w_dic, w_dic)
950 w_ret = space.getitem(w_dic, space.wrap('x'))
951 ret = space.int_w(w_ret)
952 assert ret == 42
953
954 def test_long_writes(self):
955 pathname = str(udir.join('test.dat'))
956 stream = streamio.open_file_as_stream(pathname, "wb")
957 try:
958 _w_long(stream, 42)
959 _w_long(stream, 12312)
960 _w_long(stream, 128397198)
961 finally:
962 stream.close()
963 stream = streamio.open_file_as_stream(pathname, "rb")
964 try:
965 res = _r_long(stream)
966 assert res == 42
967 res = _r_long(stream)
968 assert res == 12312
969 res = _r_long(stream)
970 assert res == 128397198
971 finally:
972 stream.close()
973
974 def test_pyc_magic_changes(self):
975 # skipped: for now, PyPy generates only one kind of .pyc file
976 # per version. Different versions should differ in
977 # sys.implementation.cache_tag, which means that they'll look up
978 # different .pyc files anyway. See test_get_tag() in test_app.py.
979 py.test.skip("For now, PyPy generates only one kind of .pyc files")
980 # test that the pyc files produced by a space are not reimportable
981 # from another, if they differ in what opcodes they support
982 allspaces = [self.space]
983 for opcodename in self.space.config.objspace.opcodes.getpaths():
984 key = 'objspace.opcodes.' + opcodename
985 space2 = maketestobjspace(make_config(None, **{key: True}))
986 allspaces.append(space2)
987 for space1 in allspaces:
988 for space2 in allspaces:
989 if space1 is space2:
990 continue
991 pathname = "whatever"
992 mtime = 12345
993 co = 'x = 42'
994 cpathname = _testfile(space1, importing.get_pyc_magic(space1),
995 mtime, co)
996 w_modulename = space2.wrap('somemodule')
997 stream = streamio.open_file_as_stream(cpathname, "rb")
998 try:
999 w_mod = space2.wrap(Module(space2, w_modulename))
1000 magic = _r_long(stream)
1001 timestamp = _r_long(stream)
1002 space2.raises_w(space2.w_ImportError,
1003 importing.load_compiled_module,
1004 space2,
1005 w_modulename,
1006 w_mod,
1007 cpathname,
1008 magic,
1009 stream.readall())
1010 finally:
1011 stream.close()
1012
1013 def test_annotation(self):
1014 from rpython.annotator.annrpython import RPythonAnnotator
1015 from rpython.annotator import model as annmodel
1016 def f():
1017 return importing.make_compiled_pathname('abc/foo.py')
1018 a = RPythonAnnotator()
1019 s = a.build_types(f, [])
1020 assert isinstance(s, annmodel.SomeString)
1021 assert s.no_nul
1022
1023 def test_pyc_magic_changes2(self):
1024 from pypy.tool.lib_pypy import LIB_PYTHON
1025 from pypy.interpreter.pycode import default_magic
1026 from hashlib import sha256
1027 opcode_path = LIB_PYTHON.join('opcode.py')
1028 h = sha256()
1029 # very simple test: hard-code the hash of lib-python/3/opcode.py and the
1030 # default magic. if you change stdlib_opcode, please update the hash
1031 # below, as well as incrementing the magic number in pycode.py
1032 with opcode_path.open("rb") as f:
1033 h.update(f.read())
1034 assert h.hexdigest() == '4082bd96b9aacf9672a2c5196a6a3b6caf5e9de0071fe4e43aa642b0860381a4'
1035 assert default_magic == 0xa0d01b0
1036
1037
1038
1039 def test_PYTHONPATH_takes_precedence(space):
1040 if sys.platform == "win32":
1041 py.test.skip("unresolved issues with win32 shell quoting rules")
1042 from pypy.interpreter.test.test_zpy import pypypath
1043 extrapath = udir.ensure("pythonpath", dir=1)
1044 extrapath.join("sched.py").write("print(42)\n")
1045 old = os.environ.get('PYTHONPATH', None)
1046 oldlang = os.environ.pop('LANG', None)
1047 try:
1048 os.environ['PYTHONPATH'] = str(extrapath)
1049 output = py.process.cmdexec('''"%s" "%s" -c "import sched"''' %
1050 (sys.executable, pypypath))
1051 assert output.strip() == '42'
1052 finally:
1053 if old:
1054 os.environ['PYTHONPATH'] = old
1055 if oldlang:
1056 os.environ['LANG'] = oldlang
1057
1058
1059 class AppTestImportHooks(object):
1060 spaceconfig = {
1061 "usemodules": ['struct', 'itertools', 'time'],
1062 }
1063
1064 def setup_class(cls):
1065 mydir = os.path.dirname(__file__)
1066 cls.w_hooktest = cls.space.wrap(os.path.join(mydir, 'hooktest'))
1067 cls.w_saved_modules = _setup_path(cls.space, mydir)
1068 cls.space.appexec([], """
1069 ():
1070 # Obscure: manually bootstrap the utf-8/latin1 codecs
1071 # for TextIOs opened by imp.find_module. It's not
1072 # otherwise loaded by the test infrastructure but would
1073 # have been by app_main
1074 import encodings.utf_8
1075 import encodings.latin_1
1076 """)
1077
1078 def teardown_class(cls):
1079 _teardown(cls.space, cls.w_saved_modules)
1080
1081 def w_exec_(self, cmd, ns):
1082 exec(cmd, ns)
1083
1084 def test_meta_path(self):
1085 tried_imports = []
1086 class Importer(object):
1087 def find_module(self, fullname, path=None):
1088 tried_imports.append((fullname, path))
1089
1090 import sys, math
1091 del sys.modules["math"]
1092
1093 sys.meta_path.insert(0, Importer())
1094 try:
1095 import math
1096 # the above line may trigger extra imports, like _operator
1097 # from app_math.py. The first one should be 'math'.
1098 assert len(tried_imports) >= 1
1099 package_name = '.'.join(__name__.split('.')[:-1])
1100 if package_name:
1101 assert tried_imports[0][0] == package_name + ".math"
1102 else:
1103 assert tried_imports[0][0] == "math"
1104 finally:
1105 sys.meta_path.pop(0)
1106
1107 def test_meta_path_block(self):
1108 class ImportBlocker(object):
1109 "Specified modules can't be imported, even if they are built-in"
1110 def __init__(self, *namestoblock):
1111 self.namestoblock = dict.fromkeys(namestoblock)
1112 def find_module(self, fullname, path=None):
1113 if fullname in self.namestoblock:
1114 return self
1115 def load_module(self, fullname):
1116 raise ImportError("blocked")
1117
1118 import sys, imp
1119 modname = "errno" # an arbitrary harmless builtin module
1120 mod = None
1121 if modname in sys.modules:
1122 mod = sys.modules
1123 del sys.modules[modname]
1124 sys.meta_path.insert(0, ImportBlocker(modname))
1125 try:
1126 raises(ImportError, __import__, modname)
1127 # the imp module doesn't use meta_path, and is not blocked
1128 # (until imp.get_loader is implemented, see PEP302)
1129 file, filename, stuff = imp.find_module(modname)
1130 imp.load_module(modname, file, filename, stuff)
1131 finally:
1132 sys.meta_path.pop(0)
1133 if mod:
1134 sys.modules[modname] = mod
1135
1136 def test_path_hooks_leaking(self):
1137 class Importer(object):
1138 def find_module(self, fullname, path=None):
1139 if fullname == "a":
1140 return self
1141
1142 def load_module(self, name):
1143 sys.modules[name] = sys
1144 return sys
1145
1146 def importer_for_path(path):
1147 if path == "xxx":
1148 return Importer()
1149 raise ImportError()
1150 import sys, imp
1151 try:
1152 sys.path_hooks.append(importer_for_path)
1153 sys.path.insert(0, "yyy")
1154 sys.path.insert(0, "xxx")
1155 import a
1156 try:
1157 import b
1158 except ImportError:
1159 pass
1160 assert sys.path_importer_cache['yyy'] is None
1161 finally:
1162 sys.path.pop(0)
1163 sys.path.pop(0)
1164 sys.path_hooks.pop()
1165
1166 def test_imp_wrapper(self):
1167 import sys, os, imp
1168 class ImpWrapper:
1169
1170 def __init__(self, path=None):
1171 if path is not None and not os.path.isdir(path):
1172 raise ImportError
1173 self.path = path
1174
1175 def find_module(self, fullname, path=None):
1176 subname = fullname.split(".")[-1]
1177 if subname != fullname and self.path is None:
1178 return None
1179 if self.path is None:
1180 path = None
1181 else:
1182 path = [self.path]
1183 try:
1184 file, filename, stuff = imp.find_module(subname, path)
1185 except ImportError:
1186 return None
1187 return ImpLoader(file, filename, stuff)
1188
1189 class ImpLoader:
1190
1191 def __init__(self, file, filename, stuff):
1192 self.file = file
1193 self.filename = filename
1194 self.stuff = stuff
1195
1196 def load_module(self, fullname):
1197 mod = imp.load_module(fullname, self.file, self.filename, self.stuff)
1198 if self.file:
1199 self.file.close()
1200 mod.__loader__ = self # for introspection
1201 return mod
1202
1203 i = ImpWrapper()
1204 sys.meta_path.append(i)
1205 sys.path_hooks.append(ImpWrapper)
1206 sys.path_importer_cache.clear()
1207 try:
1208 mnames = ("colorsys", "html.parser")
1209 for mname in mnames:
1210 parent = mname.split(".")[0]
1211 for n in sys.modules.keys():
1212 if n.startswith(parent):
1213 del sys.modules[n]
1214 for mname in mnames:
1215 m = __import__(mname, globals(), locals(), ["__dummy__"])
1216 m.__loader__ # to make sure we actually handled the import
1217 finally:
1218 sys.meta_path.pop()
1219 sys.path_hooks.pop()
1220
1221 def test_path_hooks_module(self):
1222 "Verify that non-sibling imports from module loaded by path hook works"
1223
1224 import sys
1225 import hooktest
1226
1227 hooktest.__path__.append(self.hooktest) # Avoid importing os at applevel
1228
1229 sys.path_hooks.append(hooktest.Importer)
1230
1231 try:
1232 import hooktest.foo
1233 def import_nonexisting():
1234 import hooktest.errno
1235 raises(ImportError, import_nonexisting)
1236 finally:
1237 sys.path_hooks.pop()
1238
1239 def test_meta_path_import_error_1(self):
1240 # check that we get a KeyError somewhere inside
1241 # <frozen importlib._bootstrap>, like CPython 3.5
1242
1243 class ImportHook(object):
1244 def find_module(self, fullname, path=None):
1245 assert not fullname.endswith('*')
1246 if fullname == 'meta_path_pseudo_module':
1247 return self
1248 def load_module(self, fullname):
1249 assert fullname == 'meta_path_pseudo_module'
1250 # we "forget" to update sys.modules
1251 return types.ModuleType('meta_path_pseudo_module')
1252
1253 import sys, types
1254 sys.meta_path.append(ImportHook())
1255 try:
1256 raises(KeyError, "import meta_path_pseudo_module")
1257 finally:
1258 sys.meta_path.pop()
1259
1260 def test_meta_path_import_star_2(self):
1261 class ImportHook(object):
1262 def find_module(self, fullname, path=None):
1263 if fullname.startswith('meta_path_2_pseudo_module'):
1264 return self
1265 def load_module(self, fullname):
1266 assert fullname == 'meta_path_2_pseudo_module'
1267 m = types.ModuleType('meta_path_2_pseudo_module')
1268 m.__path__ = ['/some/random/dir']
1269 sys.modules['meta_path_2_pseudo_module'] = m
1270 return m
1271
1272 import sys, types
1273 sys.meta_path.append(ImportHook())
1274 try:
1275 self.exec_("from meta_path_2_pseudo_module import *", {})
1276 finally:
1277 sys.meta_path.pop()
1278
1279
1280 class AppTestWriteBytecode(object):
1281 spaceconfig = {
1282 "translation.sandbox": False
1283 }
1284
1285 def setup_class(cls):
1286 cls.w_saved_modules = _setup(cls)
1287 sandbox = cls.spaceconfig['translation.sandbox']
1288 cls.w_sandbox = cls.space.wrap(sandbox)
1289
1290 def teardown_class(cls):
1291 _teardown(cls.space, cls.w_saved_modules)
1292 cls.space.appexec([], """
1293 ():
1294 import sys
1295 sys.dont_write_bytecode = False
1296 """)
1297
1298 def test_default(self):
1299 import os.path
1300 from test_bytecode import a
1301 assert a.__file__.endswith('a.py')
1302 assert os.path.exists(a.__cached__) == (not self.sandbox)
1303
1304 def test_write_bytecode(self):
1305 import os.path
1306 import sys
1307 sys.dont_write_bytecode = False
1308 from test_bytecode import b
1309 assert b.__file__.endswith('b.py')
1310 assert os.path.exists(b.__cached__)
1311
1312 def test_dont_write_bytecode(self):
1313 import os.path
1314 import sys
1315 sys.dont_write_bytecode = True
1316 from test_bytecode import c
1317 assert c.__file__.endswith('c.py')
1318 assert not os.path.exists(c.__cached__)
1319
1320
1321 @pytest.mark.skipif('config.option.runappdirect')
1322 class AppTestWriteBytecodeSandbox(AppTestWriteBytecode):
1323 spaceconfig = {
1324 "translation.sandbox": True
1325 }
1326
1327
1328 @pytest.mark.skipif('config.option.runappdirect')
1329 class AppTestImportlibMagic:
1330 spaceconfig = {
1331 "usemodules._frozen_importlib": True
1332 }
1333
1334 def setup_class(cls):
1335 from pypy.module.imp.interp_imp import get_magic
1336 cls.w_magic = get_magic(cls.space)
1337
1338 def test_magic(self):
1339 from importlib import _bootstrap_external
1340 assert _bootstrap_external.MAGIC_NUMBER == self.magic
1341
1342