PageRenderTime 49ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/module/imp/test/test_import.py

https://bitbucket.org/dac_io/pypy
Python | 1214 lines | 1184 code | 24 blank | 6 comment | 32 complexity | 900cdbf0f35555add70d0e7f5edbe91f MD5 | raw file
  1. import py
  2. from pypy.interpreter.module import Module
  3. from pypy.interpreter import gateway
  4. from pypy.interpreter.error import OperationError
  5. import pypy.interpreter.pycode
  6. from pypy.tool.udir import udir
  7. from pypy.rlib import streamio
  8. from pypy.conftest import gettestobjspace
  9. import pytest
  10. import sys, os
  11. import tempfile, marshal
  12. from pypy.module.imp import importing
  13. from pypy import conftest
  14. def setuppkg(pkgname, **entries):
  15. p = udir.join('impsubdir')
  16. if pkgname:
  17. p = p.join(*pkgname.split('.'))
  18. p.ensure(dir=1)
  19. f = p.join("__init__.py").open('w')
  20. print >> f, "# package"
  21. f.close()
  22. for filename, content in entries.items():
  23. filename += '.py'
  24. f = p.join(filename).open('w')
  25. print >> f, '#', filename
  26. print >> f, content
  27. f.close()
  28. return p
  29. def setup_directory_structure(space):
  30. root = setuppkg("",
  31. a = "imamodule = 1\ninpackage = 0",
  32. b = "imamodule = 1\ninpackage = 0",
  33. ambig = "imamodule = 1",
  34. test_reload = "def test():\n raise ValueError\n",
  35. infinite_reload = "import infinite_reload; reload(infinite_reload)",
  36. del_sys_module = "import sys\ndel sys.modules['del_sys_module']\n",
  37. itertools = "hello_world = 42\n",
  38. gc = "should_never_be_seen = 42\n",
  39. )
  40. root.ensure("notapackage", dir=1) # empty, no __init__.py
  41. setuppkg("pkg",
  42. a = "imamodule = 1\ninpackage = 1",
  43. relative_a = "import a",
  44. abs_b = "import b",
  45. abs_x_y = "import x.y",
  46. abs_sys = "import sys",
  47. string = "inpackage = 1",
  48. errno = "",
  49. absolute = "from __future__ import absolute_import\nimport string",
  50. relative_b = "from __future__ import absolute_import\nfrom . import string",
  51. relative_c = "from __future__ import absolute_import\nfrom .string import inpackage",
  52. relative_f = "from .imp import get_magic",
  53. relative_g = "import imp; from .imp import get_magic",
  54. )
  55. setuppkg("pkg.pkg1",
  56. __init__ = 'from . import a',
  57. a = '',
  58. relative_d = "from __future__ import absolute_import\nfrom ..string import inpackage",
  59. relative_e = "from __future__ import absolute_import\nfrom .. import string",
  60. relative_g = "from .. import pkg1\nfrom ..pkg1 import b",
  61. b = "insubpackage = 1",
  62. )
  63. setuppkg("pkg.pkg2", a='', b='')
  64. setuppkg("pkg_r", inpkg = "import x.y")
  65. setuppkg("pkg_r.x")
  66. setuppkg("x", y='')
  67. setuppkg("ambig", __init__ = "imapackage = 1")
  68. setuppkg("pkg_relative_a",
  69. __init__ = "import a",
  70. a = "imamodule = 1\ninpackage = 1",
  71. )
  72. setuppkg("pkg_substituting",
  73. __init__ = "import sys, pkg_substituted\n"
  74. "print 'TOTO', __name__\n"
  75. "sys.modules[__name__] = pkg_substituted")
  76. setuppkg("pkg_substituted", mod='')
  77. setuppkg("evil_pkg",
  78. evil = "import sys\n"
  79. "from evil_pkg import good\n"
  80. "sys.modules['evil_pkg.evil'] = good",
  81. good = "a = 42")
  82. p = setuppkg("readonly", x='')
  83. p = setuppkg("pkg_univnewlines")
  84. p.join('__init__.py').write(
  85. 'a=5\nb=6\rc="""hello\r\nworld"""\r', mode='wb')
  86. p.join('mod.py').write(
  87. 'a=15\nb=16\rc="""foo\r\nbar"""\r', mode='wb')
  88. # create compiled/x.py and a corresponding pyc file
  89. p = setuppkg("compiled", x = "x = 84")
  90. if conftest.option.runappdirect:
  91. import marshal, stat, struct, os, imp
  92. code = py.code.Source(p.join("x.py").read()).compile()
  93. s3 = marshal.dumps(code)
  94. s2 = struct.pack("i", os.stat(str(p.join("x.py")))[stat.ST_MTIME])
  95. p.join("x.pyc").write(imp.get_magic() + s2 + s3, mode='wb')
  96. else:
  97. w = space.wrap
  98. w_modname = w("compiled.x")
  99. filename = str(p.join("x.py"))
  100. stream = streamio.open_file_as_stream(filename, "r")
  101. try:
  102. importing.load_source_module(space,
  103. w_modname,
  104. w(importing.Module(space, w_modname)),
  105. filename,
  106. stream.readall())
  107. finally:
  108. stream.close()
  109. if space.config.objspace.usepycfiles:
  110. # also create a lone .pyc file
  111. p.join('lone.pyc').write(p.join('x.pyc').read(mode='rb'),
  112. mode='wb')
  113. # create a .pyw file
  114. p = setuppkg("windows", x = "x = 78")
  115. try:
  116. p.join('x.pyw').remove()
  117. except py.error.ENOENT:
  118. pass
  119. p.join('x.py').rename(p.join('x.pyw'))
  120. return str(root)
  121. def _setup(space):
  122. dn = setup_directory_structure(space)
  123. return space.appexec([space.wrap(dn)], """
  124. (dn):
  125. import sys
  126. path = list(sys.path)
  127. sys.path.insert(0, dn)
  128. return path, sys.modules.copy()
  129. """)
  130. def _teardown(space, w_saved_modules):
  131. space.appexec([w_saved_modules], """
  132. ((saved_path, saved_modules)):
  133. import sys
  134. sys.path[:] = saved_path
  135. sys.modules.clear()
  136. sys.modules.update(saved_modules)
  137. """)
  138. class AppTestImport:
  139. def setup_class(cls): # interpreter-level
  140. cls.space = gettestobjspace(usemodules=['itertools'])
  141. cls.w_runappdirect = cls.space.wrap(conftest.option.runappdirect)
  142. cls.saved_modules = _setup(cls.space)
  143. #XXX Compile class
  144. def teardown_class(cls): # interpreter-level
  145. _teardown(cls.space, cls.saved_modules)
  146. def test_set_sys_modules_during_import(self):
  147. from evil_pkg import evil
  148. assert evil.a == 42
  149. def test_import_bare_dir_fails(self):
  150. def imp():
  151. import notapackage
  152. raises(ImportError, imp)
  153. def test_import_bare_dir_warns(self):
  154. def imp():
  155. import notapackage
  156. import warnings
  157. warnings.simplefilter('error', ImportWarning)
  158. try:
  159. raises(ImportWarning, imp)
  160. finally:
  161. warnings.simplefilter('default', ImportWarning)
  162. def test_import_sys(self):
  163. import sys
  164. def test_import_a(self):
  165. import sys
  166. import a
  167. assert a == sys.modules.get('a')
  168. def test_import_a_cache(self):
  169. import sys
  170. import a
  171. a0 = a
  172. import a
  173. assert a == a0
  174. def test_trailing_slash(self):
  175. import sys
  176. try:
  177. sys.path[0] += '/'
  178. import a
  179. finally:
  180. sys.path[0] = sys.path[0].rstrip('/')
  181. def test_import_pkg(self):
  182. import sys
  183. import pkg
  184. assert pkg == sys.modules.get('pkg')
  185. def test_import_dotted(self):
  186. import sys
  187. import pkg.a
  188. assert pkg == sys.modules.get('pkg')
  189. assert pkg.a == sys.modules.get('pkg.a')
  190. def test_import_keywords(self):
  191. __import__(name='sys', level=0)
  192. def test_import_by_filename(self):
  193. import pkg.a
  194. filename = pkg.a.__file__
  195. assert filename.endswith('.py')
  196. exc = raises(ImportError, __import__, filename[:-3])
  197. assert exc.value.message == "Import by filename is not supported."
  198. def test_import_badcase(self):
  199. def missing(name):
  200. try:
  201. __import__(name)
  202. except ImportError:
  203. pass
  204. else:
  205. raise Exception("import should not have succeeded: %r" %
  206. (name,))
  207. missing("Sys")
  208. missing("SYS")
  209. missing("fuNCTionAl")
  210. missing("pKg")
  211. missing("pKg.a")
  212. missing("pkg.A")
  213. def test_import_dotted_cache(self):
  214. import sys
  215. import pkg.a
  216. assert pkg == sys.modules.get('pkg')
  217. assert pkg.a == sys.modules.get('pkg.a')
  218. pkg0 = pkg
  219. pkg_a0 = pkg.a
  220. import pkg.a
  221. assert pkg == pkg0
  222. assert pkg.a == pkg_a0
  223. def test_import_dotted2(self):
  224. import sys
  225. import pkg.pkg1.a
  226. assert pkg == sys.modules.get('pkg')
  227. assert pkg.pkg1 == sys.modules.get('pkg.pkg1')
  228. assert pkg.pkg1.a == sys.modules.get('pkg.pkg1.a')
  229. def test_import_ambig(self):
  230. import sys
  231. import ambig
  232. assert ambig == sys.modules.get('ambig')
  233. assert hasattr(ambig,'imapackage')
  234. def test_from_a(self):
  235. import sys
  236. from a import imamodule
  237. assert 'a' in sys.modules
  238. assert imamodule == 1
  239. def test_from_dotted(self):
  240. import sys
  241. from pkg.a import imamodule
  242. assert 'pkg' in sys.modules
  243. assert 'pkg.a' in sys.modules
  244. assert imamodule == 1
  245. def test_from_pkg_import_module(self):
  246. import sys
  247. from pkg import a
  248. assert 'pkg' in sys.modules
  249. assert 'pkg.a' in sys.modules
  250. pkg = sys.modules.get('pkg')
  251. assert a == pkg.a
  252. aa = sys.modules.get('pkg.a')
  253. assert a == aa
  254. def test_import_relative(self):
  255. from pkg import relative_a
  256. assert relative_a.a.inpackage ==1
  257. def test_import_relative_back_to_absolute(self):
  258. from pkg import abs_b
  259. assert abs_b.b.inpackage ==0
  260. import sys
  261. assert sys.modules.get('pkg.b') ==None
  262. def test_import_pkg_relative(self):
  263. import pkg_relative_a
  264. assert pkg_relative_a.a.inpackage ==1
  265. def test_import_relative_partial_success(self):
  266. def imp():
  267. import pkg_r.inpkg
  268. raises(ImportError, imp)
  269. def test_import_builtin_inpackage(self):
  270. def imp():
  271. import pkg.sys
  272. raises(ImportError,imp)
  273. import sys, pkg.abs_sys
  274. assert pkg.abs_sys.sys is sys
  275. import errno, pkg.errno
  276. assert pkg.errno is not errno
  277. def test_import_Globals_Are_None(self):
  278. import sys
  279. m = __import__('sys')
  280. assert sys == m
  281. n = __import__('sys', None, None, [''])
  282. assert sys == n
  283. o = __import__('sys', [], [], ['']) # CPython accepts this
  284. assert sys == o
  285. def test_import_relative_back_to_absolute2(self):
  286. from pkg import abs_x_y
  287. import sys
  288. assert abs_x_y.x.__name__ =='x'
  289. assert abs_x_y.x.y.__name__ =='x.y'
  290. # grrr XXX not needed probably...
  291. #self.assertEquals(sys.modules.get('pkg.x'),None)
  292. #self.assert_('pkg.x.y' not in sys.modules)
  293. def test_substituting_import(self):
  294. from pkg_substituting import mod
  295. assert mod.__name__ =='pkg_substituting.mod'
  296. def test_proper_failure_on_killed__path__(self):
  297. import pkg.pkg2.a
  298. del pkg.pkg2.__path__
  299. def imp_b():
  300. import pkg.pkg2.b
  301. raises(ImportError,imp_b)
  302. def test_pyc(self):
  303. import sys
  304. import compiled.x
  305. assert compiled.x == sys.modules.get('compiled.x')
  306. @pytest.mark.skipif("sys.platform != 'win32'")
  307. def test_pyw(self):
  308. import windows.x
  309. assert windows.x.__file__.endswith('x.pyw')
  310. def test_cannot_write_pyc(self):
  311. import sys, os
  312. p = os.path.join(sys.path[0], 'readonly')
  313. try:
  314. os.chmod(p, 0555)
  315. except:
  316. skip("cannot chmod() the test directory to read-only")
  317. try:
  318. import readonly.x # cannot write x.pyc, but should not crash
  319. finally:
  320. os.chmod(p, 0775)
  321. def test__import__empty_string(self):
  322. raises(ValueError, __import__, "")
  323. def test_invalid__name__(self):
  324. glob = {}
  325. exec "__name__ = None; import sys" in glob
  326. import sys
  327. assert glob['sys'] is sys
  328. def test_future_absolute_import(self):
  329. def imp():
  330. from pkg import absolute
  331. absolute.string.inpackage
  332. raises(AttributeError, imp)
  333. def test_future_relative_import_without_from_name(self):
  334. from pkg import relative_b
  335. assert relative_b.string.inpackage == 1
  336. def test_no_relative_import(self):
  337. def imp():
  338. from pkg import relative_f
  339. exc = raises(ImportError, imp)
  340. assert exc.value.message == "No module named pkg.imp"
  341. def test_no_relative_import_bug(self):
  342. def imp():
  343. from pkg import relative_g
  344. exc = raises(ImportError, imp)
  345. assert exc.value.message == "No module named pkg.imp"
  346. def test_future_relative_import_level_1(self):
  347. from pkg import relative_c
  348. assert relative_c.inpackage == 1
  349. def test_future_relative_import_level_2(self):
  350. from pkg.pkg1 import relative_d
  351. assert relative_d.inpackage == 1
  352. def test_future_relative_import_level_2_without_from_name(self):
  353. from pkg.pkg1 import relative_e
  354. assert relative_e.string.inpackage == 1
  355. def test_future_relative_import_level_3(self):
  356. from pkg.pkg1 import relative_g
  357. assert relative_g.b.insubpackage == 1
  358. import pkg.pkg1
  359. assert pkg.pkg1.__package__ == 'pkg.pkg1'
  360. def test_future_relative_import_error_when_in_non_package(self):
  361. exec """def imp():
  362. from .string import inpackage
  363. """.rstrip()
  364. raises(ValueError, imp)
  365. def test_future_relative_import_error_when_in_non_package2(self):
  366. exec """def imp():
  367. from .. import inpackage
  368. """.rstrip()
  369. raises(ValueError, imp)
  370. def test_relative_import_with___name__(self):
  371. import sys
  372. mydict = {'__name__': 'sys.foo'}
  373. res = __import__('', mydict, mydict, ('bar',), 1)
  374. assert res is sys
  375. def test_relative_import_with___name__and___path__(self):
  376. import sys
  377. import imp
  378. foo = imp.new_module('foo')
  379. sys.modules['sys.foo'] = foo
  380. mydict = {'__name__': 'sys.foo', '__path__': '/some/path'}
  381. res = __import__('', mydict, mydict, ('bar',), 1)
  382. assert res is foo
  383. def test_relative_import_pkg(self):
  384. import sys
  385. import imp
  386. pkg = imp.new_module('newpkg')
  387. sys.modules['newpkg'] = pkg
  388. mydict = {'__name__': 'newpkg.foo', '__path__': '/some/path'}
  389. res = __import__('', mydict, None, ['bar'], 2)
  390. assert res is pkg
  391. def test__package__(self):
  392. # Regression test for http://bugs.python.org/issue3221.
  393. def check_absolute():
  394. exec "from os import path" in ns
  395. def check_relative():
  396. exec "from . import a" in ns
  397. # Check both OK with __package__ and __name__ correct
  398. ns = dict(__package__='pkg', __name__='pkg.notarealmodule')
  399. check_absolute()
  400. check_relative()
  401. # Check both OK with only __name__ wrong
  402. ns = dict(__package__='pkg', __name__='notarealpkg.notarealmodule')
  403. check_absolute()
  404. check_relative()
  405. # Check relative fails with only __package__ wrong
  406. ns = dict(__package__='foo', __name__='pkg.notarealmodule')
  407. check_absolute() # XXX check warnings
  408. raises(SystemError, check_relative)
  409. # Check relative fails with __package__ and __name__ wrong
  410. ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule')
  411. check_absolute() # XXX check warnings
  412. raises(SystemError, check_relative)
  413. # Check both fail with package set to a non-string
  414. ns = dict(__package__=object())
  415. raises(ValueError, check_absolute)
  416. raises(ValueError, check_relative)
  417. def test_universal_newlines(self):
  418. import pkg_univnewlines
  419. assert pkg_univnewlines.a == 5
  420. assert pkg_univnewlines.b == 6
  421. assert pkg_univnewlines.c == "hello\nworld"
  422. from pkg_univnewlines import mod
  423. assert mod.a == 15
  424. assert mod.b == 16
  425. assert mod.c == "foo\nbar"
  426. def test_reload(self):
  427. import test_reload
  428. try:
  429. test_reload.test()
  430. except ValueError:
  431. pass
  432. # If this test runs too quickly, test_reload.py's mtime
  433. # attribute will remain unchanged even if the file is rewritten.
  434. # Consequently, the file would not reload. So, added a sleep()
  435. # delay to assure that a new, distinct timestamp is written.
  436. import time
  437. time.sleep(1)
  438. f = open(test_reload.__file__, "w")
  439. f.write("def test():\n raise NotImplementedError\n")
  440. f.close()
  441. reload(test_reload)
  442. try:
  443. test_reload.test()
  444. except NotImplementedError:
  445. pass
  446. # Ensure that the file is closed
  447. # (on windows at least)
  448. import os
  449. os.unlink(test_reload.__file__)
  450. def test_reload_failing(self):
  451. import test_reload
  452. import time
  453. time.sleep(1)
  454. f = open(test_reload.__file__, "w")
  455. f.write("a = 10 // 0\n")
  456. f.close()
  457. # A failing reload should leave the previous module in sys.modules
  458. raises(ZeroDivisionError, reload, test_reload)
  459. import os, sys
  460. assert 'test_reload' in sys.modules
  461. assert test_reload.test
  462. os.unlink(test_reload.__file__)
  463. def test_reload_submodule(self):
  464. import pkg.a
  465. reload(pkg.a)
  466. def test_reload_builtin(self):
  467. import sys
  468. oldpath = sys.path
  469. try:
  470. del sys.setdefaultencoding
  471. except AttributeError:
  472. pass
  473. reload(sys)
  474. assert sys.path is oldpath
  475. assert 'setdefaultencoding' in dir(sys)
  476. def test_reload_infinite(self):
  477. import infinite_reload
  478. def test_explicitly_missing(self):
  479. import sys
  480. sys.modules['foobarbazmod'] = None
  481. try:
  482. import foobarbazmod
  483. assert False, "should have failed, got instead %r" % (
  484. foobarbazmod,)
  485. except ImportError:
  486. pass
  487. def test_del_from_sys_modules(self):
  488. try:
  489. import del_sys_module
  490. except ImportError:
  491. pass # ok
  492. else:
  493. assert False, 'should not work'
  494. def test_shadow_builtin(self):
  495. if self.runappdirect: skip("hard to test: module is already imported")
  496. # 'import gc' is supposed to always find the built-in module;
  497. # like CPython, it is a built-in module, so it shadows everything,
  498. # even though there is a gc.py.
  499. import sys
  500. assert 'gc' not in sys.modules
  501. import gc
  502. assert not hasattr(gc, 'should_never_be_seen')
  503. assert '(built-in)' in repr(gc)
  504. del sys.modules['gc']
  505. def test_shadow_extension_1(self):
  506. if self.runappdirect: skip("hard to test: module is already imported")
  507. # 'import itertools' is supposed to find itertools.py if there is
  508. # one in sys.path.
  509. import sys
  510. assert 'itertools' not in sys.modules
  511. import itertools
  512. assert hasattr(itertools, 'hello_world')
  513. assert not hasattr(itertools, 'count')
  514. assert '(built-in)' not in repr(itertools)
  515. del sys.modules['itertools']
  516. def test_shadow_extension_2(self):
  517. if self.runappdirect: skip("hard to test: module is already imported")
  518. # 'import itertools' is supposed to find the built-in module even
  519. # if there is also one in sys.path as long as it is *after* the
  520. # special entry '.../lib_pypy/__extensions__'. (Note that for now
  521. # there is one in lib_pypy/itertools.py, which should not be seen
  522. # either; hence the (built-in) test below.)
  523. import sys
  524. assert 'itertools' not in sys.modules
  525. sys.path.append(sys.path.pop(0))
  526. try:
  527. import itertools
  528. assert not hasattr(itertools, 'hello_world')
  529. assert hasattr(itertools, 'izip')
  530. assert '(built-in)' in repr(itertools)
  531. finally:
  532. sys.path.insert(0, sys.path.pop())
  533. del sys.modules['itertools']
  534. class TestAbi:
  535. def test_abi_tag(self):
  536. space1 = gettestobjspace(soabi='TEST')
  537. space2 = gettestobjspace(soabi='')
  538. if sys.platform == 'win32':
  539. assert importing.get_so_extension(space1) == '.TESTi.pyd'
  540. assert importing.get_so_extension(space2) == '.pyd'
  541. else:
  542. assert importing.get_so_extension(space1) == '.TESTi.so'
  543. assert importing.get_so_extension(space2) == '.so'
  544. def _getlong(data):
  545. x = marshal.dumps(data)
  546. return x[-4:]
  547. def _testfile(magic, mtime, co=None):
  548. cpathname = str(udir.join('test.pyc'))
  549. f = file(cpathname, "wb")
  550. f.write(_getlong(magic))
  551. f.write(_getlong(mtime))
  552. if co:
  553. marshal.dump(co, f)
  554. f.close()
  555. return cpathname
  556. def _testfilesource(source="x=42"):
  557. pathname = str(udir.join('test.py'))
  558. f = file(pathname, "wb")
  559. f.write(source)
  560. f.close()
  561. return pathname
  562. class TestPycStuff:
  563. # ___________________ .pyc related stuff _________________
  564. def test_check_compiled_module(self):
  565. space = self.space
  566. mtime = 12345
  567. cpathname = _testfile(importing.get_pyc_magic(space), mtime)
  568. ret = importing.check_compiled_module(space,
  569. cpathname,
  570. mtime)
  571. assert ret is not None
  572. ret.close()
  573. # check for wrong mtime
  574. ret = importing.check_compiled_module(space,
  575. cpathname,
  576. mtime+1)
  577. assert ret is None
  578. # also check with expected mtime==0 (nothing special any more about 0)
  579. ret = importing.check_compiled_module(space,
  580. cpathname,
  581. 0)
  582. assert ret is None
  583. os.remove(cpathname)
  584. # check for wrong version
  585. cpathname = _testfile(importing.get_pyc_magic(space)+1, mtime)
  586. ret = importing.check_compiled_module(space,
  587. cpathname,
  588. mtime)
  589. assert ret is None
  590. # check for empty .pyc file
  591. f = open(cpathname, 'wb')
  592. f.close()
  593. ret = importing.check_compiled_module(space,
  594. cpathname,
  595. mtime)
  596. assert ret is None
  597. os.remove(cpathname)
  598. def test_read_compiled_module(self):
  599. space = self.space
  600. mtime = 12345
  601. co = compile('x = 42', '?', 'exec')
  602. cpathname = _testfile(importing.get_pyc_magic(space), mtime, co)
  603. stream = streamio.open_file_as_stream(cpathname, "rb")
  604. try:
  605. stream.seek(8, 0)
  606. w_code = importing.read_compiled_module(
  607. space, cpathname, stream.readall())
  608. pycode = space.interpclass_w(w_code)
  609. finally:
  610. stream.close()
  611. assert type(pycode) is pypy.interpreter.pycode.PyCode
  612. w_dic = space.newdict()
  613. pycode.exec_code(space, w_dic, w_dic)
  614. w_ret = space.getitem(w_dic, space.wrap('x'))
  615. ret = space.int_w(w_ret)
  616. assert ret == 42
  617. def test_load_compiled_module(self):
  618. space = self.space
  619. mtime = 12345
  620. co = compile('x = 42', '?', 'exec')
  621. cpathname = _testfile(importing.get_pyc_magic(space), mtime, co)
  622. w_modulename = space.wrap('somemodule')
  623. stream = streamio.open_file_as_stream(cpathname, "rb")
  624. try:
  625. w_mod = space.wrap(Module(space, w_modulename))
  626. magic = importing._r_long(stream)
  627. timestamp = importing._r_long(stream)
  628. w_ret = importing.load_compiled_module(space,
  629. w_modulename,
  630. w_mod,
  631. cpathname,
  632. magic,
  633. timestamp,
  634. stream.readall())
  635. finally:
  636. stream.close()
  637. assert w_mod is w_ret
  638. w_ret = space.getattr(w_mod, space.wrap('x'))
  639. ret = space.int_w(w_ret)
  640. assert ret == 42
  641. def test_parse_source_module(self):
  642. space = self.space
  643. pathname = _testfilesource()
  644. stream = streamio.open_file_as_stream(pathname, "r")
  645. try:
  646. w_ret = importing.parse_source_module(space,
  647. pathname,
  648. stream.readall())
  649. finally:
  650. stream.close()
  651. pycode = space.interpclass_w(w_ret)
  652. assert type(pycode) is pypy.interpreter.pycode.PyCode
  653. w_dic = space.newdict()
  654. pycode.exec_code(space, w_dic, w_dic)
  655. w_ret = space.getitem(w_dic, space.wrap('x'))
  656. ret = space.int_w(w_ret)
  657. assert ret == 42
  658. def test_long_writes(self):
  659. pathname = str(udir.join('test.dat'))
  660. stream = streamio.open_file_as_stream(pathname, "wb")
  661. try:
  662. importing._w_long(stream, 42)
  663. importing._w_long(stream, 12312)
  664. importing._w_long(stream, 128397198)
  665. finally:
  666. stream.close()
  667. stream = streamio.open_file_as_stream(pathname, "rb")
  668. try:
  669. res = importing._r_long(stream)
  670. assert res == 42
  671. res = importing._r_long(stream)
  672. assert res == 12312
  673. res = importing._r_long(stream)
  674. assert res == 128397198
  675. finally:
  676. stream.close()
  677. def test_load_source_module(self):
  678. space = self.space
  679. w_modulename = space.wrap('somemodule')
  680. w_mod = space.wrap(Module(space, w_modulename))
  681. pathname = _testfilesource()
  682. stream = streamio.open_file_as_stream(pathname, "r")
  683. try:
  684. w_ret = importing.load_source_module(space,
  685. w_modulename,
  686. w_mod,
  687. pathname,
  688. stream.readall())
  689. finally:
  690. stream.close()
  691. assert w_mod is w_ret
  692. w_ret = space.getattr(w_mod, space.wrap('x'))
  693. ret = space.int_w(w_ret)
  694. assert ret == 42
  695. cpathname = udir.join('test.pyc')
  696. assert cpathname.check()
  697. cpathname.remove()
  698. def test_load_source_module_nowrite(self):
  699. space = self.space
  700. w_modulename = space.wrap('somemodule')
  701. w_mod = space.wrap(Module(space, w_modulename))
  702. pathname = _testfilesource()
  703. stream = streamio.open_file_as_stream(pathname, "r")
  704. try:
  705. w_ret = importing.load_source_module(space,
  706. w_modulename,
  707. w_mod,
  708. pathname,
  709. stream.readall(),
  710. write_pyc=False)
  711. finally:
  712. stream.close()
  713. cpathname = udir.join('test.pyc')
  714. assert not cpathname.check()
  715. def test_load_source_module_dont_write_bytecode(self):
  716. space = self.space
  717. w_modulename = space.wrap('somemodule')
  718. w_mod = space.wrap(Module(space, w_modulename))
  719. pathname = _testfilesource()
  720. stream = streamio.open_file_as_stream(pathname, "r")
  721. try:
  722. space.setattr(space.sys, space.wrap('dont_write_bytecode'),
  723. space.w_True)
  724. w_ret = importing.load_source_module(space,
  725. w_modulename,
  726. w_mod,
  727. pathname,
  728. stream.readall())
  729. finally:
  730. space.setattr(space.sys, space.wrap('dont_write_bytecode'),
  731. space.w_False)
  732. stream.close()
  733. cpathname = udir.join('test.pyc')
  734. assert not cpathname.check()
  735. def test_load_source_module_syntaxerror(self):
  736. # No .pyc file on SyntaxError
  737. space = self.space
  738. w_modulename = space.wrap('somemodule')
  739. w_mod = space.wrap(Module(space, w_modulename))
  740. pathname = _testfilesource(source="<Syntax Error>")
  741. stream = streamio.open_file_as_stream(pathname, "r")
  742. try:
  743. w_ret = importing.load_source_module(space,
  744. w_modulename,
  745. w_mod,
  746. pathname,
  747. stream.readall())
  748. except OperationError:
  749. # OperationError("Syntax Error")
  750. pass
  751. stream.close()
  752. cpathname = udir.join('test.pyc')
  753. assert not cpathname.check()
  754. def test_load_source_module_importerror(self):
  755. # the .pyc file is created before executing the module
  756. space = self.space
  757. w_modulename = space.wrap('somemodule')
  758. w_mod = space.wrap(Module(space, w_modulename))
  759. pathname = _testfilesource(source="a = unknown_name")
  760. stream = streamio.open_file_as_stream(pathname, "r")
  761. try:
  762. w_ret = importing.load_source_module(space,
  763. w_modulename,
  764. w_mod,
  765. pathname,
  766. stream.readall())
  767. except OperationError:
  768. # OperationError("NameError", "global name 'unknown_name' is not defined")
  769. pass
  770. stream.close()
  771. # And the .pyc has been generated
  772. cpathname = udir.join('test.pyc')
  773. assert cpathname.check()
  774. def test_write_compiled_module(self):
  775. space = self.space
  776. pathname = _testfilesource()
  777. os.chmod(pathname, 0777)
  778. stream = streamio.open_file_as_stream(pathname, "r")
  779. try:
  780. w_ret = importing.parse_source_module(space,
  781. pathname,
  782. stream.readall())
  783. finally:
  784. stream.close()
  785. pycode = space.interpclass_w(w_ret)
  786. assert type(pycode) is pypy.interpreter.pycode.PyCode
  787. cpathname = str(udir.join('cpathname.pyc'))
  788. mode = 0777
  789. mtime = 12345
  790. importing.write_compiled_module(space,
  791. pycode,
  792. cpathname,
  793. mode,
  794. mtime)
  795. # check
  796. ret = importing.check_compiled_module(space,
  797. cpathname,
  798. mtime)
  799. assert ret is not None
  800. ret.close()
  801. # Check that the executable bit was removed
  802. assert os.stat(cpathname).st_mode & 0111 == 0
  803. # read compiled module
  804. stream = streamio.open_file_as_stream(cpathname, "rb")
  805. try:
  806. stream.seek(8, 0)
  807. w_code = importing.read_compiled_module(space, cpathname,
  808. stream.readall())
  809. pycode = space.interpclass_w(w_code)
  810. finally:
  811. stream.close()
  812. # check value of load
  813. w_dic = space.newdict()
  814. pycode.exec_code(space, w_dic, w_dic)
  815. w_ret = space.getitem(w_dic, space.wrap('x'))
  816. ret = space.int_w(w_ret)
  817. assert ret == 42
  818. def test_pyc_magic_changes(self):
  819. # test that the pyc files produced by a space are not reimportable
  820. # from another, if they differ in what opcodes they support
  821. allspaces = [self.space]
  822. for opcodename in self.space.config.objspace.opcodes.getpaths():
  823. key = 'objspace.opcodes.' + opcodename
  824. space2 = gettestobjspace(**{key: True})
  825. allspaces.append(space2)
  826. for space1 in allspaces:
  827. for space2 in allspaces:
  828. if space1 is space2:
  829. continue
  830. pathname = "whatever"
  831. mtime = 12345
  832. co = compile('x = 42', '?', 'exec')
  833. cpathname = _testfile(importing.get_pyc_magic(space1),
  834. mtime, co)
  835. w_modulename = space2.wrap('somemodule')
  836. stream = streamio.open_file_as_stream(cpathname, "rb")
  837. try:
  838. w_mod = space2.wrap(Module(space2, w_modulename))
  839. magic = importing._r_long(stream)
  840. timestamp = importing._r_long(stream)
  841. space2.raises_w(space2.w_ImportError,
  842. importing.load_compiled_module,
  843. space2,
  844. w_modulename,
  845. w_mod,
  846. cpathname,
  847. magic,
  848. timestamp,
  849. stream.readall())
  850. finally:
  851. stream.close()
  852. def test_PYTHONPATH_takes_precedence(space):
  853. if sys.platform == "win32":
  854. py.test.skip("unresolved issues with win32 shell quoting rules")
  855. from pypy.interpreter.test.test_zpy import pypypath
  856. extrapath = udir.ensure("pythonpath", dir=1)
  857. extrapath.join("urllib.py").write("print 42\n")
  858. old = os.environ.get('PYTHONPATH', None)
  859. oldlang = os.environ.pop('LANG', None)
  860. try:
  861. os.environ['PYTHONPATH'] = str(extrapath)
  862. output = py.process.cmdexec('''"%s" "%s" -c "import urllib"''' %
  863. (sys.executable, pypypath) )
  864. assert output.strip() == '42'
  865. finally:
  866. if old:
  867. os.environ['PYTHONPATH'] = old
  868. if oldlang:
  869. os.environ['LANG'] = oldlang
  870. class AppTestImportHooks(object):
  871. def setup_class(cls):
  872. cls.space = gettestobjspace(usemodules=('struct',))
  873. def test_meta_path(self):
  874. tried_imports = []
  875. class Importer(object):
  876. def find_module(self, fullname, path=None):
  877. tried_imports.append((fullname, path))
  878. import sys, datetime
  879. del sys.modules["datetime"]
  880. sys.meta_path.append(Importer())
  881. try:
  882. import datetime
  883. assert len(tried_imports) == 1
  884. package_name = '.'.join(__name__.split('.')[:-1])
  885. if package_name:
  886. assert tried_imports[0][0] == package_name + ".datetime"
  887. else:
  888. assert tried_imports[0][0] == "datetime"
  889. finally:
  890. sys.meta_path.pop()
  891. def test_meta_path_block(self):
  892. class ImportBlocker(object):
  893. "Specified modules can't be imported, even if they are built-in"
  894. def __init__(self, *namestoblock):
  895. self.namestoblock = dict.fromkeys(namestoblock)
  896. def find_module(self, fullname, path=None):
  897. if fullname in self.namestoblock:
  898. return self
  899. def load_module(self, fullname):
  900. raise ImportError, "blocked"
  901. import sys, imp
  902. modname = "errno" # an arbitrary harmless builtin module
  903. mod = None
  904. if modname in sys.modules:
  905. mod = sys.modules
  906. del sys.modules[modname]
  907. sys.meta_path.append(ImportBlocker(modname))
  908. try:
  909. raises(ImportError, __import__, modname)
  910. # the imp module doesn't use meta_path, and is not blocked
  911. # (until imp.get_loader is implemented, see PEP302)
  912. file, filename, stuff = imp.find_module(modname)
  913. imp.load_module(modname, file, filename, stuff)
  914. finally:
  915. sys.meta_path.pop()
  916. if mod:
  917. sys.modules[modname] = mod
  918. def test_path_hooks_leaking(self):
  919. class Importer(object):
  920. def find_module(self, fullname, path=None):
  921. if fullname == "a":
  922. return self
  923. def load_module(self, name):
  924. sys.modules[name] = sys
  925. return sys
  926. def importer_for_path(path):
  927. if path == "xxx":
  928. return Importer()
  929. raise ImportError()
  930. import sys, imp
  931. try:
  932. sys.path_hooks.append(importer_for_path)
  933. sys.path.insert(0, "yyy")
  934. sys.path.insert(0, "xxx")
  935. import a
  936. try:
  937. import b
  938. except ImportError:
  939. pass
  940. assert isinstance(sys.path_importer_cache['yyy'],
  941. imp.NullImporter)
  942. finally:
  943. sys.path.pop(0)
  944. sys.path.pop(0)
  945. sys.path_hooks.pop()
  946. def test_imp_wrapper(self):
  947. import sys, os, imp
  948. class ImpWrapper:
  949. def __init__(self, path=None):
  950. if path is not None and not os.path.isdir(path):
  951. raise ImportError
  952. self.path = path
  953. def find_module(self, fullname, path=None):
  954. subname = fullname.split(".")[-1]
  955. if subname != fullname and self.path is None:
  956. return None
  957. if self.path is None:
  958. path = None
  959. else:
  960. path = [self.path]
  961. try:
  962. file, filename, stuff = imp.find_module(subname, path)
  963. except ImportError, e:
  964. return None
  965. return ImpLoader(file, filename, stuff)
  966. class ImpLoader:
  967. def __init__(self, file, filename, stuff):
  968. self.file = file
  969. self.filename = filename
  970. self.stuff = stuff
  971. def load_module(self, fullname):
  972. mod = imp.load_module(fullname, self.file, self.filename, self.stuff)
  973. if self.file:
  974. self.file.close()
  975. mod.__loader__ = self # for introspection
  976. return mod
  977. i = ImpWrapper()
  978. sys.meta_path.append(i)
  979. sys.path_hooks.append(ImpWrapper)
  980. sys.path_importer_cache.clear()
  981. try:
  982. mnames = ("colorsys", "urlparse", "distutils.core", "compiler.misc")
  983. for mname in mnames:
  984. parent = mname.split(".")[0]
  985. for n in sys.modules.keys():
  986. if n.startswith(parent):
  987. del sys.modules[n]
  988. for mname in mnames:
  989. m = __import__(mname, globals(), locals(), ["__dummy__"])
  990. m.__loader__ # to make sure we actually handled the import
  991. finally:
  992. sys.meta_path.pop()
  993. sys.path_hooks.pop()
  994. class AppTestPyPyExtension(object):
  995. def setup_class(cls):
  996. cls.space = gettestobjspace(usemodules=['imp', 'zipimport',
  997. '__pypy__'])
  998. cls.w_udir = cls.space.wrap(str(udir))
  999. def test_run_compiled_module(self):
  1000. # XXX minimal test only
  1001. import imp, new
  1002. module = new.module('foobar')
  1003. raises(IOError, imp._run_compiled_module,
  1004. 'foobar', 'this_file_does_not_exist', None, module)
  1005. def test_getimporter(self):
  1006. import imp, os
  1007. # an existing directory
  1008. importer = imp._getimporter(self.udir)
  1009. assert importer is None
  1010. # an existing file
  1011. path = os.path.join(self.udir, 'test_getimporter')
  1012. open(path, 'w').close()
  1013. importer = imp._getimporter(path)
  1014. assert isinstance(importer, imp.NullImporter)
  1015. # a non-existing path
  1016. path = os.path.join(self.udir, 'does_not_exist_at_all')
  1017. importer = imp._getimporter(path)
  1018. assert isinstance(importer, imp.NullImporter)
  1019. # a mostly-empty zip file
  1020. path = os.path.join(self.udir, 'test_getimporter.zip')
  1021. f = open(path, 'wb')
  1022. f.write('PK\x03\x04\n\x00\x00\x00\x00\x00P\x9eN>\x00\x00\x00\x00\x00'
  1023. '\x00\x00\x00\x00\x00\x00\x00\x05\x00\x15\x00emptyUT\t\x00'
  1024. '\x03wyYMwyYMUx\x04\x00\xf4\x01d\x00PK\x01\x02\x17\x03\n\x00'
  1025. '\x00\x00\x00\x00P\x9eN>\x00\x00\x00\x00\x00\x00\x00\x00\x00'
  1026. '\x00\x00\x00\x05\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00'
  1027. '\xa4\x81\x00\x00\x00\x00emptyUT\x05\x00\x03wyYMUx\x00\x00PK'
  1028. '\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00@\x00\x00\x008\x00'
  1029. '\x00\x00\x00\x00')
  1030. f.close()
  1031. importer = imp._getimporter(path)
  1032. import zipimport
  1033. assert isinstance(importer, zipimport.zipimporter)
  1034. class AppTestNoPycFile(object):
  1035. spaceconfig = {
  1036. "objspace.usepycfiles": False,
  1037. "objspace.lonepycfiles": False
  1038. }
  1039. def setup_class(cls):
  1040. usepycfiles = cls.spaceconfig['objspace.usepycfiles']
  1041. lonepycfiles = cls.spaceconfig['objspace.lonepycfiles']
  1042. cls.w_usepycfiles = cls.space.wrap(usepycfiles)
  1043. cls.w_lonepycfiles = cls.space.wrap(lonepycfiles)
  1044. cls.saved_modules = _setup(cls.space)
  1045. def teardown_class(cls):
  1046. _teardown(cls.space, cls.saved_modules)
  1047. def test_import_possibly_from_pyc(self):
  1048. from compiled import x
  1049. if self.usepycfiles:
  1050. assert x.__file__.endswith('x.pyc')
  1051. else:
  1052. assert x.__file__.endswith('x.py')
  1053. try:
  1054. from compiled import lone
  1055. except ImportError:
  1056. assert not self.lonepycfiles, "should have found 'lone.pyc'"
  1057. else:
  1058. assert self.lonepycfiles, "should not have found 'lone.pyc'"
  1059. assert lone.__file__.endswith('lone.pyc')
  1060. class AppTestNoLonePycFile(AppTestNoPycFile):
  1061. spaceconfig = {
  1062. "objspace.usepycfiles": True,
  1063. "objspace.lonepycfiles": False
  1064. }
  1065. class AppTestLonePycFile(AppTestNoPycFile):
  1066. spaceconfig = {
  1067. "objspace.usepycfiles": True,
  1068. "objspace.lonepycfiles": True
  1069. }