PageRenderTime 48ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/pypy/pypy/
Python | 1533 lines | 1486 code | 33 blank | 14 comment | 39 complexity | 8b87c235b707a963a75f414ebf7b1221 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0

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

Large files files are truncated, but you can click here to view the full file