PageRenderTime 53ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/Languages/IronPython/Tests/test_imp.py

http://github.com/IronLanguages/main
Python | 1365 lines | 1296 code | 39 blank | 30 comment | 23 complexity | 461bdb0196705d1d3950a7906a15d6e4 MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. #####################################################################################
  2. #
  3. # Copyright (c) Microsoft Corporation. All rights reserved.
  4. #
  5. # This source code is subject to terms and conditions of the Apache License, Version 2.0. A
  6. # copy of the license can be found in the License.html file at the root of this distribution. If
  7. # you cannot locate the Apache License, Version 2.0, please send an email to
  8. # ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
  9. # by the terms of the Apache License, Version 2.0.
  10. #
  11. # You must not remove this notice, or any other, from this software.
  12. #
  13. #
  14. #####################################################################################
  15. from iptest.assert_util import *
  16. if not is_silverlight:
  17. from iptest.file_util import *
  18. import sys
  19. import imp
  20. import operator
  21. def get_builtins_dict():
  22. if type(__builtins__) is type(sys):
  23. return __builtins__.__dict__
  24. return __builtins__
  25. def test_imp_new_module():
  26. x = imp.new_module('abc')
  27. sys.modules['abc'] = x
  28. x.foo = 'bar'
  29. import abc
  30. AreEqual(abc.foo, 'bar')
  31. y = imp.new_module('\r\n')
  32. sys.modules['xyz'] = y
  33. y.foo = 'foo'
  34. import xyz
  35. AreEqual(xyz.foo, 'foo')
  36. @skip("silverlight")
  37. def test_imp_in_exec():
  38. _imfp = 'impmodfrmpkg'
  39. _f_imfp_init = path_combine(testpath.public_testdir, _imfp, "__init__.py")
  40. _f_imfp_mod = path_combine(testpath.public_testdir, _imfp, "mod.py")
  41. _f_imfp_start = path_combine(testpath.public_testdir, "imfpstart.tpy")
  42. write_to_file(_f_imfp_init, "")
  43. write_to_file(_f_imfp_mod, "")
  44. write_to_file(_f_imfp_start, """
  45. try:
  46. from impmodfrmpkg.mod import mod
  47. except ImportError, e:
  48. pass
  49. else:
  50. raise AssertionError("Import of mod from pkg.mod unexpectedly succeeded")
  51. """)
  52. # import a package
  53. import impmodfrmpkg
  54. # create a dictionary like that package
  55. glb = {'__name__' : impmodfrmpkg.__name__, '__path__' : impmodfrmpkg.__path__}
  56. loc = {}
  57. exec 'import mod' in glb, loc
  58. Assert('mod' in loc)
  59. glb = {'__name__' : impmodfrmpkg.__name__, '__path__' : impmodfrmpkg.__path__}
  60. loc = {}
  61. exec 'from mod import *' in glb, loc
  62. #Assert('value' in loc) # TODO: Fix me
  63. if is_cli or is_silverlight:
  64. loc = {}
  65. exec 'from System import *' in globals(), loc
  66. Assert('Int32' in loc)
  67. Assert('Int32' not in globals())
  68. if is_cli or is_silverlight:
  69. exec 'from System import *'
  70. Assert('Int32' in dir())
  71. delete_files(_f_imfp_start)
  72. clean_directory(path_combine(testpath.public_testdir, _imfp), remove=True)
  73. def test_imp_basic():
  74. magic = imp.get_magic()
  75. suffixes = imp.get_suffixes()
  76. Assert(isinstance(suffixes, list))
  77. for suffix in suffixes:
  78. Assert(isinstance(suffix, tuple))
  79. AreEqual(len(suffix), 3)
  80. Assert((".py", "U", 1) in suffixes)
  81. if not is_silverlight:
  82. _testdir = "ImpTest"
  83. _imptestdir = path_combine(testpath.public_testdir, _testdir)
  84. _f_init = path_combine(_imptestdir, "__init__.py")
  85. temp_name = ["os",
  86. "os.P_WAIT",
  87. "os.chmod",
  88. "sys.path",
  89. "xxxx"
  90. ]
  91. @skip('silverlight')
  92. def test_imp_package():
  93. write_to_file(_f_init, "my_name = 'imp package test'")
  94. pf, pp, (px, pm, pt) = imp.find_module(_testdir, [testpath.public_testdir])
  95. AreEqual(pt, imp.PKG_DIRECTORY)
  96. AreEqual(pf, None)
  97. AreEqual(px, "")
  98. AreEqual(pm, "")
  99. module = imp.load_module(_testdir, pf, pp, (px, pm, pt))
  100. Assert(_testdir in sys.modules)
  101. AreEqual(module.my_name, 'imp package test')
  102. save_sys_path = sys.path
  103. try:
  104. sys.path = list(sys.path)
  105. sys.path.append(testpath.public_testdir)
  106. fm = imp.find_module(_testdir)
  107. finally:
  108. sys.path = save_sys_path
  109. # unpack the result obtained above
  110. pf, pp, (px, pm, pt) = fm
  111. AreEqual(pt, imp.PKG_DIRECTORY)
  112. AreEqual(pf, None)
  113. AreEqual(px, "")
  114. AreEqual(pm, "")
  115. module = imp.load_module(_testdir, pf, pp, (px, pm, pt))
  116. AreEqual(module.my_name, 'imp package test')
  117. if is_silverlight==False:
  118. _f_module = path_combine(_imptestdir, "imptestmod.py")
  119. @skip('silverlight')
  120. def test_imp_module():
  121. write_to_file(_f_module, "value = 'imp test module'")
  122. pf, pp, (px, pm, pt) = imp.find_module("imptestmod", [_imptestdir])
  123. AreEqual(pt, imp.PY_SOURCE)
  124. Assert(pf != None)
  125. Assert(isinstance(pf, file))
  126. module = imp.load_module("imptestmod", pf, pp, (px, pm, pt))
  127. AreEqual(module.value, 'imp test module')
  128. pf.close()
  129. save_sys_path = sys.path
  130. try:
  131. sys.path = list(sys.path)
  132. sys.path.append(_imptestdir)
  133. fm = imp.find_module("imptestmod")
  134. finally:
  135. sys.path = save_sys_path
  136. # unpack the result obtained above
  137. pf, pp, (px, pm, pt) = fm
  138. AreEqual(pt, imp.PY_SOURCE)
  139. Assert(pf != None)
  140. Assert(isinstance(pf, file))
  141. AreEqual(px, ".py")
  142. AreEqual(pm, "U")
  143. module = imp.load_module("imptestmod", pf, pp, (px, pm, pt))
  144. AreEqual(module.value, 'imp test module')
  145. pf.close()
  146. def test_direct_module_creation():
  147. import math
  148. for baseMod in math, sys:
  149. module = type(baseMod)
  150. x = module.__new__(module)
  151. AreEqual(repr(x), "<module '?' (built-in)>")
  152. #AreEqual(x.__dict__, None)
  153. x.__init__('abc', 'def')
  154. AreEqual(repr(x), "<module 'abc' (built-in)>")
  155. AreEqual(x.__doc__, 'def')
  156. x.__init__('aaa', 'zzz')
  157. AreEqual(repr(x), "<module 'aaa' (built-in)>")
  158. AreEqual(x.__doc__, 'zzz')
  159. # can't assign to module __dict__
  160. try:
  161. x.__dict__ = {}
  162. except TypeError: pass
  163. else: AssertUnreachable()
  164. # can't delete __dict__
  165. try:
  166. del(x.__dict__)
  167. except TypeError: pass
  168. else: AssertUnreachable()
  169. # init doesn't clobber dict, it just re-initializes values
  170. x.__dict__['foo'] = 'xyz'
  171. x.__init__('xyz', 'nnn')
  172. AreEqual(x.foo, 'xyz')
  173. # dict is lazily created on set
  174. x = module.__new__(module)
  175. x.foo = 23
  176. AreEqual(x.__dict__, {'foo':23})
  177. AreEqual(repr(x), "<module '?' (built-in)>")
  178. # can't pass wrong sub-type to new
  179. try:
  180. module.__new__(str)
  181. except TypeError: pass
  182. else: AssertUnreachable()
  183. # dir on non-initialized module raises TypeError
  184. x = module.__new__(module)
  185. x.__name__ = 'module_does_not_exist_in_sys_dot_modules'
  186. AssertError(ImportError, reload, x)
  187. def test_redefine_import():
  188. # redefining global __import__ shouldn't change import semantics
  189. global __import__
  190. global called
  191. called = False
  192. def __import__(*args):
  193. global called
  194. called = True
  195. AreEqual(called, False)
  196. del __import__
  197. called = False
  198. AreEqual(called, False)
  199. def test_module_dict():
  200. currentModule = sys.modules[__name__]
  201. AreEqual(operator.isMappingType(currentModule.__dict__), True)
  202. AreEqual(type({}), type(currentModule.__dict__))
  203. AreEqual(isinstance(currentModule.__dict__, dict), True)
  204. #test release_lock,lock_held,acquire_lock
  205. def test_lock():
  206. i=0
  207. while i<5:
  208. i+=1
  209. if not imp.lock_held():
  210. AssertError(RuntimeError,imp.release_lock)
  211. imp.acquire_lock()
  212. else:
  213. imp.release_lock()
  214. # test is_frozen
  215. def test_is_frozen():
  216. for name in temp_name:
  217. f = imp.is_frozen(name)
  218. if f:
  219. Fail("result should be False")
  220. # test init_frozen
  221. def test_init_frozen():
  222. for name in temp_name:
  223. f = imp.init_frozen(name)
  224. if f != None :
  225. Fail("return object should be None!")
  226. # is_builtin
  227. def test_is_builtin():
  228. AreEqual(imp.is_builtin("xxx"),0)
  229. AreEqual(imp.is_builtin("12324"),0)
  230. AreEqual(imp.is_builtin("&*^^"),0)
  231. AreEqual(imp.is_builtin("dir"),0)
  232. AreEqual(imp.is_builtin("__doc__"),0)
  233. AreEqual(imp.is_builtin("__name__"),0)
  234. AreEqual(imp.is_builtin("_locle"),0)
  235. AreEqual(imp.is_builtin("cPickle"),1)
  236. AreEqual(imp.is_builtin("_random"),1)
  237. # nt module disabled in Silverlight
  238. if not is_silverlight:
  239. if is_posix:
  240. AreEqual(imp.is_builtin("posix"),1)
  241. else:
  242. AreEqual(imp.is_builtin("nt"),1)
  243. AreEqual(imp.is_builtin("thread"),1)
  244. # there are a several differences between ironpython and cpython
  245. if is_cli or is_silverlight:
  246. AreEqual(imp.is_builtin("copy_reg"),1)
  247. else:
  248. AreEqual(imp.is_builtin("copy_reg"),0)
  249. # supposedly you can't re-init these
  250. AreEqual(imp.is_builtin("sys"), -1)
  251. AreEqual(imp.is_builtin("__builtin__"), -1)
  252. AreEqual(imp.is_builtin("exceptions"), -1)
  253. imp.init_builtin("sys")
  254. imp.init_builtin("__builtin__")
  255. imp.init_builtin("exceptions")
  256. @skip("win32", "multiple_execute", "stdlib")
  257. def test_sys_path_none_builtins():
  258. prevPath = sys.path
  259. #import some builtin modules not previously imported
  260. try:
  261. sys.path = [None] + prevPath
  262. Assert('datetime' not in sys.modules.keys())
  263. import datetime
  264. Assert('datetime' in sys.modules.keys())
  265. sys.path = prevPath + [None]
  266. if not imp.is_builtin('copy_reg'):
  267. Assert('copy_reg' not in sys.modules.keys())
  268. import datetime
  269. import copy_reg
  270. Assert('datetime' in sys.modules.keys())
  271. Assert('copy_reg' in sys.modules.keys())
  272. sys.path = [None]
  273. if not imp.is_builtin('binascii'):
  274. Assert('binascii' not in sys.modules.keys())
  275. import datetime
  276. import copy_reg
  277. import binascii
  278. Assert('datetime' in sys.modules.keys())
  279. Assert('copy_reg' in sys.modules.keys())
  280. Assert('binascii' in sys.modules.keys())
  281. finally:
  282. sys.path = prevPath
  283. @skip("silverlight")
  284. def test_sys_path_none_userpy():
  285. prevPath = sys.path
  286. #import a *.py file
  287. temp_syspath_none = path_combine(testpath.public_testdir, "temp_syspath_none.py")
  288. write_to_file(temp_syspath_none, "stuff = 3.14")
  289. try:
  290. sys.path = [None] + prevPath
  291. import temp_syspath_none
  292. AreEqual(temp_syspath_none.stuff, 3.14)
  293. finally:
  294. sys.path = prevPath
  295. delete_files(path_combine(testpath.public_testdir, "temp_syspath_none.py"))
  296. def test_sys_path_none_negative():
  297. prevPath = sys.path
  298. test_paths = [ [None] + prevPath,
  299. prevPath + [None],
  300. [None],
  301. ]
  302. try:
  303. for temp_path in test_paths:
  304. sys.path = temp_path
  305. try:
  306. import does_not_exist
  307. AssertUnerachable()
  308. except ImportError:
  309. pass
  310. finally:
  311. sys.path = prevPath
  312. #init_builtin
  313. def test_init_builtin():
  314. r = imp.init_builtin("c_Pickle")
  315. AreEqual(r,None)
  316. r = imp.init_builtin("2345")
  317. AreEqual(r,None)
  318. r = imp.init_builtin("xxxx")
  319. AreEqual(r,None)
  320. r = imp.init_builtin("^$%$#@")
  321. AreEqual(r,None)
  322. r = imp.init_builtin("_locale")
  323. Assert(r!=None)
  324. #test SEARCH_ERROR, PY_SOURCE,PY_COMPILED,C_EXTENSION,PY_RESOURCE,PKG_DIRECTORY,C_BUILTIN,PY_FROZEN,PY_CODERESOURCE
  325. def test_flags():
  326. AreEqual(imp.SEARCH_ERROR,0)
  327. AreEqual(imp.PY_SOURCE,1)
  328. AreEqual(imp.PY_COMPILED,2)
  329. AreEqual(imp.C_EXTENSION,3)
  330. AreEqual(imp.PY_RESOURCE,4)
  331. AreEqual(imp.PKG_DIRECTORY,5)
  332. AreEqual(imp.C_BUILTIN,6)
  333. AreEqual(imp.PY_FROZEN,7)
  334. AreEqual(imp.PY_CODERESOURCE,8)
  335. def test_user_defined_modules():
  336. """test the importer using user-defined module types"""
  337. class MockModule(object):
  338. def __init__(self, name): self.__name__ = name
  339. def __repr__(self): return 'MockModule("' + self.__name__ + '")'
  340. TopModule = MockModule("TopModule")
  341. sys.modules["TopModule"] = TopModule
  342. SubModule = MockModule("SubModule")
  343. theObj = object()
  344. SubModule.Object = theObj
  345. TopModule.SubModule = SubModule
  346. sys.modules["TopModule.SubModule"] = SubModule
  347. # clear the existing names from our namespace...
  348. x, y = TopModule, SubModule
  349. del TopModule, SubModule
  350. # verify we can import TopModule w/ TopModule.SubModule name
  351. import TopModule.SubModule
  352. AreEqual(TopModule, x)
  353. Assert('SubModule' not in dir())
  354. # verify we can import Object from TopModule.SubModule
  355. from TopModule.SubModule import Object
  356. AreEqual(Object, theObj)
  357. # verify we short-circuit the lookup in TopModule if
  358. # we have a sys.modules entry...
  359. SubModule2 = MockModule("SubModule2")
  360. SubModule2.Object2 = theObj
  361. sys.modules["TopModule.SubModule"] = SubModule2
  362. from TopModule.SubModule import Object2
  363. AreEqual(Object2, theObj)
  364. del sys.modules['TopModule']
  365. del sys.modules['TopModule.SubModule']
  366. def test_constructed_module():
  367. """verify that we don't load arbitrary modules from modules, only truly nested modules"""
  368. ModuleType = type(sys)
  369. TopModule = ModuleType("TopModule")
  370. sys.modules["TopModule"] = TopModule
  371. SubModule = ModuleType("SubModule")
  372. SubModule.Object = object()
  373. TopModule.SubModule = SubModule
  374. try:
  375. import TopModule.SubModule
  376. AssertUnreachable()
  377. except ImportError:
  378. pass
  379. del sys.modules['TopModule']
  380. @skip("multiple_execute")
  381. def test_import_from_custom():
  382. import __builtin__
  383. try:
  384. class foo(object):
  385. b = 'abc'
  386. def __import__(name, globals, locals, fromlist):
  387. global received
  388. received = name, fromlist
  389. return foo()
  390. saved = __builtin__.__import__
  391. __builtin__.__import__ = __import__
  392. from a import b
  393. AreEqual(received, ('a', ('b', )))
  394. finally:
  395. __builtin__.__import__ = saved
  396. def test_module_name():
  397. import imp
  398. m = imp.new_module('foo')
  399. AreEqual(m.__str__(), "<module 'foo' (built-in)>")
  400. m.__name__ = 'bar'
  401. AreEqual(m.__str__(), "<module 'bar' (built-in)>")
  402. m.__name__ = None
  403. AreEqual(m.__str__(), "<module '?' (built-in)>")
  404. m.__name__ = []
  405. AreEqual(m.__str__(), "<module '?' (built-in)>")
  406. m.__file__ = None
  407. AreEqual(m.__str__(), "<module '?' (built-in)>")
  408. m.__file__ = []
  409. AreEqual(m.__str__(), "<module '?' (built-in)>")
  410. m.__file__ = 'foo.py'
  411. AreEqual(m.__str__(), "<module '?' from 'foo.py'>")
  412. @skip('silverlight')
  413. def test_cp7007():
  414. file_contents = '''
  415. called = 3.14
  416. '''
  417. strange_module_names = [ "+",
  418. "+a",
  419. "a+",
  420. "++",
  421. "+++",
  422. "-",
  423. "=",
  424. "$",
  425. "^",
  426. ]
  427. strange_file_names = [ path_combine(testpath.public_testdir, "cp7007", x + ".py") for x in strange_module_names ]
  428. sys.path.append(path_combine(testpath.public_testdir, "cp7007"))
  429. for x in strange_file_names: write_to_file(x, file_contents)
  430. try:
  431. for x in strange_module_names:
  432. temp_mod = __import__(x)
  433. AreEqual(temp_mod.called, 3.14)
  434. finally:
  435. sys.path.remove(path_combine(testpath.public_testdir, "cp7007"))
  436. clean_directory(path_combine(testpath.public_testdir, "cp7007"), remove=True)
  437. def test_relative_control():
  438. """test various flavors of relative/absolute import and ensure the right
  439. arguments are delivered to __import__"""
  440. def myimport(*args):
  441. global importArgs
  442. importArgs = list(args)
  443. importArgs[1] = None # globals, we don't care about this
  444. importArgs[2] = None # locals, we don't care about this either
  445. # we'll pull values out of this class on success, but that's not
  446. # the important part
  447. class X:
  448. abc = 3
  449. absolute_import = 2
  450. bar = 5
  451. return X
  452. old_import = get_builtins_dict()['__import__']
  453. try:
  454. get_builtins_dict()['__import__'] = myimport
  455. import abc
  456. AreEqual(importArgs, ['abc', None, None, None])
  457. from . import abc
  458. AreEqual(importArgs, ['', None, None, ('abc',), 1])
  459. from .. import abc
  460. AreEqual(importArgs, ['', None, None, ('abc',), 2])
  461. from ... import abc
  462. AreEqual(importArgs, ['', None, None, ('abc',), 3])
  463. from ...d import abc
  464. AreEqual(importArgs, ['d', None, None, ('abc',), 3])
  465. from ...d import (abc, bar)
  466. AreEqual(importArgs, ['d', None, None, ('abc', 'bar'), 3])
  467. from d import (
  468. abc,
  469. bar)
  470. AreEqual(importArgs, ['d', None, None, ('abc', 'bar')])
  471. code = """from __future__ import absolute_import\nimport abc"""
  472. exec code in globals(), locals()
  473. AreEqual(importArgs, ['abc', None, None, None, 0])
  474. def f():exec "from import abc"
  475. AssertError(SyntaxError, f)
  476. finally:
  477. get_builtins_dict()['__import__'] = old_import
  478. @skip("multiple_execute") #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=26829
  479. def test_import_relative_error():
  480. def f(): exec 'from . import *'
  481. AssertError(ValueError, f)
  482. @disabled
  483. @skip("silverlight") #No access to CPython stdlib
  484. def test_import_hooks_import_precence():
  485. """__import__ takes precedence over import hooks"""
  486. global myimpCalled
  487. myimpCalled = None
  488. class myimp(object):
  489. def find_module(self, fullname, path=None):
  490. global myimpCalled
  491. myimpCalled = fullname, path
  492. def myimport(*args):
  493. return 'myimport'
  494. import distutils
  495. import distutils.command
  496. mi = myimp()
  497. sys.meta_path.append(mi)
  498. builtinimp = get_builtins_dict()['__import__']
  499. try:
  500. get_builtins_dict()['__import__'] = myimport
  501. import abc
  502. AreEqual(abc, 'myimport')
  503. AreEqual(myimpCalled, None)
  504. # reload on a built-in hits the loader protocol
  505. reload(distutils)
  506. AreEqual(myimpCalled, ('distutils', None))
  507. reload(distutils.command)
  508. AreEqual(myimpCalled[0], 'distutils.command')
  509. AreEqual(myimpCalled[1][0][-7:], 'distutils')
  510. finally:
  511. get_builtins_dict()['__import__'] = builtinimp
  512. sys.meta_path.remove(mi)
  513. def test_import_hooks_bad_importer():
  514. class bad_importer(object): pass
  515. mi = bad_importer()
  516. sys.path.append(mi)
  517. try:
  518. def f(): import does_not_exist
  519. AssertError(ImportError, f)
  520. finally:
  521. sys.path.remove(mi)
  522. sys.path.append(None)
  523. try:
  524. def f(): import does_not_exist
  525. AssertError(ImportError, f)
  526. finally:
  527. sys.path.remove(None)
  528. class inst_importer(object): pass
  529. mi = inst_importer()
  530. def f(*args): raise Exception()
  531. mi.find_module = f
  532. sys.path.append(mi)
  533. try:
  534. def f(): import does_not_exist
  535. AssertError(ImportError, f)
  536. finally:
  537. sys.path.remove(mi)
  538. def test_import_hooks_importer():
  539. """importer tests - verify the importer gets passed correct values, handles
  540. errors coming back out correctly"""
  541. global myimpCalled
  542. myimpCalled = None
  543. class myimp(object):
  544. def find_module(self, fullname, path=None):
  545. global myimpCalled
  546. myimpCalled = fullname, path
  547. if fullname == 'does_not_exist_throw':
  548. raise Exception('hello')
  549. mi = myimp()
  550. sys.meta_path.append(mi)
  551. try:
  552. try:
  553. import does_not_exist
  554. AssertUnreachable()
  555. except ImportError: pass
  556. AreEqual(myimpCalled, ('does_not_exist', None))
  557. try:
  558. from testpkg1 import blah
  559. AssertUnreachable()
  560. except ImportError:
  561. pass
  562. AreEqual(type(myimpCalled[1]), list)
  563. AreEqual(myimpCalled[0], 'testpkg1.blah')
  564. AreEqual(myimpCalled[1][0][-8:], 'testpkg1')
  565. def f(): import does_not_exist_throw
  566. AssertErrorWithMessage(Exception, 'hello', f)
  567. finally:
  568. sys.meta_path.remove(mi)
  569. @skip("multiple_execute")
  570. def test_import_hooks_loader():
  571. """loader tests - verify the loader gets the right values, handles errors correctly"""
  572. global myimpCalled
  573. myimpCalled = None
  574. moduleType = type(sys)
  575. class myloader(object):
  576. loadcount = 0
  577. def __init__(self, fullname, path):
  578. self.fullname = fullname
  579. self.path = path
  580. def load_module(self, fullname):
  581. if fullname == 'does_not_exist_throw':
  582. raise Exception('hello again')
  583. elif fullname == 'does_not_exist_return_none':
  584. return None
  585. else:
  586. myloader.loadcount += 1
  587. module = sys.modules.setdefault(fullname, moduleType(fullname))
  588. module.__file__ = '<myloader file ' + str(myloader.loadcount) + '>'
  589. module.fullname = self.fullname
  590. module.path = self.path
  591. module.__loader__ = self
  592. if fullname[-3:] == 'pkg':
  593. # create a package
  594. module.__path__ = [fullname]
  595. return module
  596. class myimp(object):
  597. def find_module(self, fullname, path=None):
  598. return myloader(fullname, path)
  599. mi = myimp()
  600. sys.meta_path.append(mi)
  601. try:
  602. def f(): import does_not_exist_throw
  603. AssertErrorWithMessage(Exception, 'hello again', f)
  604. def f(): import does_not_exist_return_none
  605. AssertError(ImportError, f)
  606. import does_not_exist_create
  607. AreEqual(does_not_exist_create.__file__, '<myloader file 1>')
  608. AreEqual(does_not_exist_create.fullname, 'does_not_exist_create')
  609. AreEqual(does_not_exist_create.path, None)
  610. reload(does_not_exist_create)
  611. AreEqual(does_not_exist_create.__file__, '<myloader file 2>')
  612. AreEqual(does_not_exist_create.fullname, 'does_not_exist_create')
  613. AreEqual(does_not_exist_create.path, None)
  614. import testpkg1.does_not_exist_create_sub
  615. AreEqual(testpkg1.does_not_exist_create_sub.__file__, '<myloader file 3>')
  616. AreEqual(testpkg1.does_not_exist_create_sub.fullname, 'testpkg1.does_not_exist_create_sub')
  617. AreEqual(testpkg1.does_not_exist_create_sub.path[0][-8:], 'testpkg1')
  618. reload(testpkg1.does_not_exist_create_sub)
  619. AreEqual(testpkg1.does_not_exist_create_sub.__file__, '<myloader file 4>')
  620. AreEqual(testpkg1.does_not_exist_create_sub.fullname, 'testpkg1.does_not_exist_create_sub')
  621. AreEqual(testpkg1.does_not_exist_create_sub.path[0][-8:], 'testpkg1')
  622. import does_not_exist_create_pkg.does_not_exist_create_subpkg
  623. AreEqual(does_not_exist_create_pkg.__file__, '<myloader file 5>')
  624. AreEqual(does_not_exist_create_pkg.fullname, 'does_not_exist_create_pkg')
  625. finally:
  626. sys.meta_path.remove(mi)
  627. def test_path_hooks():
  628. import toimport
  629. def prepare(f):
  630. sys.path_importer_cache = {}
  631. sys.path_hooks = [f]
  632. if 'toimport' in sys.modules: del sys.modules['toimport']
  633. def hook(*args): raise Exception('hello')
  634. prepare(hook)
  635. def f(): import toimport
  636. AssertErrorWithMessage(Exception, 'hello', f)
  637. # ImportError shouldn't propagate out
  638. def hook(*args): raise ImportError('foo')
  639. prepare(hook)
  640. f()
  641. # returning none should be ok
  642. def hook(*args): pass
  643. prepare(hook)
  644. f()
  645. sys.path_hooks = []
  646. class meta_loader(object):
  647. def __init__(self, value):
  648. self.value = value
  649. def load_module(self, fullname):
  650. if type(self.value) is Exception: raise self.value
  651. return self.value
  652. class meta_importer(object):
  653. def find_module(self, fullname, path=None):
  654. AreEqual(path, None)
  655. if fullname == 'does_not_exist_throw': raise Exception('hello')
  656. elif fullname == 'does_not_exist_abc': return meta_loader('abc')
  657. elif fullname == 'does_not_exist_loader_throw': return meta_loader(Exception('loader'))
  658. elif fullname == 'does_not_exist_None': return meta_loader(None)
  659. elif fullname == 'does_not_exist_X':
  660. class X(object):
  661. abc = 3
  662. return meta_loader(X)
  663. def common_meta_import_tests():
  664. def f(): import does_not_exist_throw
  665. AssertErrorWithMessage(Exception, 'hello', f)
  666. import does_not_exist_abc
  667. AreEqual(does_not_exist_abc, 'abc')
  668. def f(): import does_not_exist_loader_throw
  669. AssertErrorWithMessage(Exception, 'loader', f)
  670. def f(): import does_not_exist_loader_None
  671. AssertErrorWithMessage(ImportError, 'No module named does_not_exist_loader_None', f)
  672. from does_not_exist_X import abc
  673. AreEqual(abc, 3)
  674. def test_path_hooks_importer_and_loader():
  675. path = list(sys.path)
  676. hooks = list(sys.path_hooks)
  677. try:
  678. sys.path.append('<myname>')
  679. def hook(name):
  680. if name == "<myname>":
  681. return meta_importer()
  682. sys.path_hooks.append(hook)
  683. common_meta_import_tests()
  684. finally:
  685. sys.path = path
  686. sys.path_hooks = hooks
  687. def test_meta_path():
  688. metapath = list(sys.meta_path)
  689. sys.meta_path.append(meta_importer())
  690. try:
  691. common_meta_import_tests()
  692. finally:
  693. sys.meta_path = metapath
  694. def test_custom_meta_path():
  695. """most special methods invoked by the runtime from Python only invoke on the type, not the instance.
  696. the import methods will invoke on instances including using __getattribute__ for resolution or on
  697. old-style classes. This test verifies we do a full member lookup to find these methods"""
  698. metapath = list(sys.meta_path)
  699. finder = None
  700. loader = None
  701. class K(object):
  702. def __init__(self):
  703. self.calls = []
  704. def __getattribute__(self, name):
  705. if name != 'calls': self.calls.append(name)
  706. if name == 'find_module': return finder
  707. if name == 'load_module': return loader
  708. return object.__getattribute__(self, name)
  709. loaderInst = K()
  710. sys.meta_path.append(loaderInst)
  711. def ok_finder(name, path):
  712. loaderInst.calls.append( (name, path) )
  713. return loaderInst
  714. def ok_loader(name):
  715. loaderInst.calls.append(name)
  716. return 'abc'
  717. try:
  718. # dynamically resolve find_module to None
  719. try:
  720. import xyz
  721. except TypeError:
  722. AreEqual(loaderInst.calls[0], 'find_module')
  723. loaderInst.calls = []
  724. # dynamically resolve find_module to a function,
  725. # and load_module to None.
  726. finder = ok_finder
  727. try:
  728. import xyz
  729. except TypeError:
  730. AreEqual(loaderInst.calls[0], 'find_module')
  731. AreEqual(loaderInst.calls[1], ('xyz', None))
  732. loaderInst.calls = []
  733. loader = ok_loader
  734. import xyz
  735. AreEqual(xyz, 'abc')
  736. AreEqual(loaderInst.calls[0], 'find_module')
  737. AreEqual(loaderInst.calls[1], ('xyz', None))
  738. AreEqual(loaderInst.calls[2], 'load_module')
  739. AreEqual(loaderInst.calls[3], 'xyz')
  740. finally:
  741. sys.meta_path = metapath
  742. def test_import_kw_args():
  743. AreEqual(__import__(name = 'sys', globals = globals(), locals = locals(), fromlist = [], level = -1), sys)
  744. def test_import_list_empty_string():
  745. """importing w/ an empty string in the from list should be ignored"""
  746. x = __import__('testpkg1', {}, {}, [''])
  747. Assert(not '' in dir(x))
  748. @skip("silverlight") #BUG?
  749. def test_cp7050():
  750. '''
  751. This test case complements CPython's test_import.py
  752. '''
  753. try:
  754. import Nt
  755. AssertUnreachable("Should not have been able to import 'Nt'")
  756. except:
  757. pass
  758. AssertError(ImportError, __import__, "Nt")
  759. AssertError(ImportError, __import__, "Lib")
  760. AssertError(ImportError, __import__, "iptest.Assert_Util")
  761. def test_meta_path_before_builtins():
  762. """the meta path should be consulted before builtins are loaded"""
  763. class MyException(Exception): pass
  764. class K:
  765. def find_module(self, name, path):
  766. if name == "time": return self
  767. return None
  768. def load_module(self, name):
  769. raise MyException
  770. if 'time' in sys.modules:
  771. del sys.modules["time"]
  772. loader = K()
  773. sys.meta_path.append(loader)
  774. try:
  775. import time
  776. AssertUnreachable()
  777. except MyException:
  778. pass
  779. sys.meta_path.remove(loader)
  780. import time
  781. @skip("silverlight") # no nt module on silverlight
  782. def test_file_coding():
  783. try:
  784. import os
  785. f = file('test_coding_mod.py', 'wb+')
  786. f.write("# coding: utf-8\nx = '\xe6ble'\n")
  787. f.close()
  788. import test_coding_mod
  789. AreEqual(test_coding_mod.x[0], '\xe6')
  790. finally:
  791. os.unlink('test_coding_mod.py')
  792. try:
  793. f = file('test_coding_2.py', 'wb+')
  794. f.write("\xef\xbb\xbf# -*- coding: utf-8 -*-\n")
  795. f.write("x = u'ABCDE'\n")
  796. f.close()
  797. import test_coding_2
  798. AreEqual(test_coding_2.x, 'ABCDE')
  799. finally:
  800. os.unlink('test_coding_2.py')
  801. try:
  802. f = file('test_coding_3.py', 'wb+')
  803. f.write("# -*- coding: utf-8 -*-\n")
  804. f.write("raise Exception()")
  805. f.close()
  806. try:
  807. import test_coding_3
  808. except Exception, e:
  809. AreEqual(sys.exc_info()[2].tb_next.tb_lineno, 2)
  810. finally:
  811. os.unlink('test_coding_3.py')
  812. def test_module_subtype():
  813. class x(type(sys)):
  814. def __init__(self): self.baz = 100
  815. def __getattr__(self, name):
  816. if name == 'qux': raise AttributeError
  817. return 42
  818. def __getattribute__(self, name):
  819. if name == 'foo' or name == 'qux': raise AttributeError
  820. if name == 'baz': return type(sys).__getattribute__(self, name)
  821. return 23
  822. a = x()
  823. AreEqual(a.foo, 42)
  824. AreEqual(a.bar, 23)
  825. AreEqual(a.baz, 100)
  826. AssertError(AttributeError, lambda : a.qux)
  827. #Real *.py file
  828. import testpkg1.mod1
  829. class x(type(testpkg1.mod1)):
  830. def __init__(self): self.baz = 100
  831. def __getattr__(self, name):
  832. if name == 'qux': raise AttributeError
  833. return 42
  834. def __getattribute__(self, name):
  835. if name == 'foo' or name == 'qux': raise AttributeError
  836. if name == 'baz': return type(sys).__getattribute__(self, name)
  837. return 23
  838. a = x()
  839. AreEqual(a.foo, 42)
  840. AreEqual(a.bar, 23)
  841. AreEqual(a.baz, 100)
  842. AssertError(AttributeError, lambda : a.qux)
  843. #Package
  844. import testpkg1
  845. class x(type(testpkg1)):
  846. def __init__(self): self.baz = 100
  847. def __getattr__(self, name):
  848. if name == 'qux': raise AttributeError
  849. return 42
  850. def __getattribute__(self, name):
  851. if name == 'foo' or name == 'qux': raise AttributeError
  852. if name == 'baz': return type(sys).__getattribute__(self, name)
  853. return 23
  854. a = x()
  855. AreEqual(a.foo, 42)
  856. AreEqual(a.bar, 23)
  857. AreEqual(a.baz, 100)
  858. AssertError(AttributeError, lambda : a.qux)
  859. @runonly("stdlib")
  860. def test_cp13736():
  861. import os
  862. _f_imp_cp13736 = path_combine(testpath.public_testdir, "impcp13736.py")
  863. shortName = _f_imp_cp13736.rsplit(os.sep, 1)[1].split(".")[0]
  864. write_to_file(_f_imp_cp13736, """
  865. class Test(object):
  866. def a(self):
  867. return 34
  868. """)
  869. import sys
  870. if sys.platform=="win32" and "." not in sys.path:
  871. sys.path.append(".")
  872. import new
  873. import imp
  874. moduleInfo = imp.find_module(shortName)
  875. module = imp.load_module(shortName, moduleInfo[0], moduleInfo[1], moduleInfo[2])
  876. t = new.classobj('Test1', (getattr(module, 'Test'),), {})
  877. i = t()
  878. AreEqual(i.a(), 34)
  879. moduleInfo[0].close()
  880. delete_files(_f_imp_cp13736)
  881. def test_import_path_seperator():
  882. """verify using the path seperator in a direct call will result in an ImportError"""
  883. AssertError(ImportError, __import__, 'iptest\\warning_util')
  884. __import__('iptest.warning_util')
  885. def test_load_package():
  886. import testpkg1
  887. pkg = imp.load_package('libcopy', testpkg1.__path__[0])
  888. AreEqual(sys.modules['libcopy'], pkg)
  889. pkg = imp.load_package('some_new_pkg', 'some_path_that_does_not_and_never_will_exist')
  890. AreEqual(sys.modules['some_new_pkg'], pkg)
  891. # NullImporter isn't used on Silverlight because we cannot detect the presence dirs
  892. @skip("silverlight")
  893. def test_NullImporter():
  894. def f():
  895. class x(imp.NullImporter): pass
  896. AssertError(TypeError, f)
  897. AreEqual(imp.NullImporter.__module__, 'imp')
  898. sys.path.append('directory_that_does_not_exist')
  899. try:
  900. import SomeFileThatDoesNotExist
  901. except ImportError:
  902. pass
  903. Assert(isinstance(sys.path_importer_cache['directory_that_does_not_exist'], imp.NullImporter))
  904. def test_get_frozen_object():
  905. # frozen objects not supported, this always fails
  906. AssertError(ImportError, imp.get_frozen_object, 'foo')
  907. def test_cp17459():
  908. AreEqual(imp.IMP_HOOK, 9)
  909. def test_module_getattribute():
  910. mymod = type(sys)('foo', 'bar')
  911. attrs = ['__delattr__', '__doc__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__str__']
  912. for attr in attrs:
  913. d = mymod.__dict__
  914. d[attr] = 42
  915. AreEqual(getattr(mymod, attr), 42)
  916. AreEqual(mymod.__getattribute__(attr), 42)
  917. AreEqual(mymod.__getattribute__(attr), getattr(mymod, attr))
  918. del d[attr]
  919. for x in dir(type(sys)):
  920. AreEqual(mymod.__getattribute__(x), getattr(mymod, x))
  921. @skip("silverlight", "win32")
  922. def test_import_lookup_after():
  923. import os
  924. try:
  925. _x_mod = path_combine(testpath.public_testdir, "x.py")
  926. _y_mod = path_combine(testpath.public_testdir, "y.py")
  927. write_to_file(_x_mod, """
  928. import sys
  929. oldmod = sys.modules['y']
  930. newmod = object()
  931. sys.modules['y'] = newmod
  932. """)
  933. write_to_file(_y_mod, "import x")
  934. import y
  935. AreEqual(type(y), object)
  936. finally:
  937. os.unlink(_x_mod)
  938. os.unlink(_y_mod)
  939. @skip("silverlight", "win32")
  940. def test_imp_load_source():
  941. import os
  942. try:
  943. _x_mod = path_combine(testpath.public_testdir, "x.py")
  944. write_to_file(_x_mod, """
  945. '''some pydoc'''
  946. X = 3.14
  947. """)
  948. with open(_x_mod, "r") as f:
  949. x = imp.load_source("test_imp_load_source_x",
  950. _x_mod,
  951. f)
  952. AreEqual(x.__name__, "test_imp_load_source_x")
  953. AreEqual(x.X, 3.14)
  954. AreEqual(x.__doc__, '''some pydoc''')
  955. finally:
  956. os.unlink(_x_mod)
  957. @skip("silverlight")
  958. def test_imp_load_compiled():
  959. #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=17459
  960. if not is_cpython:
  961. AreEqual(imp.load_compiled("", ""), None)
  962. try:
  963. _x_mod = path_combine(testpath.public_testdir, "x.py")
  964. write_to_file(_x_mod, "")
  965. with open(_x_mod, "r") as f:
  966. AreEqual(imp.load_compiled("", "", f), None)
  967. finally:
  968. os.unlink(_x_mod)
  969. @skip("silverlight")
  970. def test_imp_load_dynamic():
  971. #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=17459
  972. if not is_cpython:
  973. AreEqual(imp.load_dynamic("", ""), None)
  974. try:
  975. _x_mod = path_combine(testpath.public_testdir, "x.py")
  976. write_to_file(_x_mod, "")
  977. with open(_x_mod, "r") as f:
  978. AreEqual(imp.load_dynamic("", "", f), None)
  979. finally:
  980. os.unlink(_x_mod)
  981. def test_override_dict():
  982. class M(type(sys)):
  983. @property
  984. def __dict__(self):
  985. return 'not a dict'
  986. @__dict__.setter
  987. def __dict__(self, value):
  988. global setCalled
  989. setCalled = True
  990. a = M('foo')
  991. AreEqual(a.__dict__, 'not a dict')
  992. a.__dict__ = 42
  993. AreEqual(setCalled, True)
  994. class MyDesc(object):
  995. def __get__(self, instance, context):
  996. return 'abc'
  997. class M(type(sys)):
  998. __dict__ = MyDesc()
  999. a = M('foo')
  1000. AreEqual(a.__dict__, 'abc')
  1001. # instance members won't be found
  1002. class M(type(sys)): pass
  1003. a = M('foo')
  1004. a.__dict__['__dict__'] = 42
  1005. AreEqual(type(a.__dict__), dict)
  1006. AreEqual(a.__getattribute__('__dict__'), a.__dict__)
  1007. class M(type(sys)):
  1008. def baz(self):
  1009. return 'hello'
  1010. @property
  1011. def foo(self):
  1012. return 'hello'
  1013. @foo.setter
  1014. def foo(self, value):
  1015. self.bar = value
  1016. @foo.deleter
  1017. def foo(self):
  1018. del self.bar
  1019. a = M('hello')
  1020. AreEqual(a.__getattribute__('baz'), a.baz)
  1021. AreEqual(a.baz(), 'hello')
  1022. a.__setattr__('foo', 42)
  1023. AreEqual(a.__dict__['bar'], 42)
  1024. a.__delattr__('foo')
  1025. Assert('bar' not in a.__dict__)
  1026. # mix-in an old-style class
  1027. class old_class:
  1028. def old_method(self):
  1029. return 42
  1030. @property
  1031. def old_prop(self):
  1032. return 'abc'
  1033. @old_prop.setter
  1034. def old_prop(self, value):
  1035. self.op = value
  1036. @old_prop.deleter
  1037. def old_prop(self):
  1038. del self.op
  1039. M.__bases__ += (old_class, )
  1040. AreEqual(a.old_method(), 42)
  1041. a.__setattr__('old_prop', 42)
  1042. AreEqual(a.__dict__['op'], 42)
  1043. a.__delattr__('old_prop')
  1044. Assert('op' not in a.__dict__)
  1045. # change the class
  1046. class M2(type(sys)): pass
  1047. a.__setattr__('__class__', M2)
  1048. AreEqual(type(a), M2)
  1049. AssertErrorWithMessage(TypeError, "readonly attribute", a.__setattr__, '__dict__', int)
  1050. AssertErrorWithMessage(TypeError, "readonly attribute", a.__delattr__, '__dict__')
  1051. # __setattr__/__delattr__ no non-derived type
  1052. m = type(sys)('foo')
  1053. AssertErrorWithMessage(TypeError, "__class__ assignment: only for heap types", m.__setattr__, '__class__', int)
  1054. AssertErrorWithMessage(TypeError, "readonly attribute", m.__setattr__, '__dict__', int)
  1055. AssertErrorWithMessage(TypeError, "can't delete __class__ attribute", m.__delattr__, '__class__')
  1056. AssertErrorWithMessage(TypeError, "readonly attribute", m.__delattr__, '__dict__')
  1057. @skip("silverlight")
  1058. def test_ximp_load_module():
  1059. mod = imp.new_module('my_module_test')
  1060. mod.__file__ = 'does_not_exist.py'
  1061. sys.modules['my_module_test'] = mod
  1062. f = file('test.py', 'w+')
  1063. f.write('x = 42')
  1064. f.close()
  1065. with file('test.py') as inp_file:
  1066. imp.load_module('my_module_test', inp_file, 'does_not_exist.py', ('', 'U', 1))
  1067. import os
  1068. os.unlink('test.py')
  1069. AreEqual(mod.x, 42)
  1070. @skip("silverlight") # no stdlib in silverlight
  1071. def test_import_string_from_list_cp26098():
  1072. AreEqual(__import__('email.mime.application', globals(), locals(), 'MIMEApplication').__name__, 'email.mime.application')
  1073. @skip("win32", "silverlight")
  1074. def test_new_builtin_modules():
  1075. import clr
  1076. clr.AddReference('IronPythonTest')
  1077. import test_new_module
  1078. dir(test_new_module)
  1079. # static members should still be accessible
  1080. AreEqual(test_new_module.StaticMethod(), 42)
  1081. AreEqual(test_new_module.StaticField, 42)
  1082. AreEqual(test_new_module.StaticProperty, 42)
  1083. # built-in functions shouldn't appear to be bound
  1084. AreEqual(test_new_module.test_method.__doc__, 'test_method() -> object%s' % line_sep)
  1085. AreEqual(test_new_module.test_method.__self__, None)
  1086. # unassigned attributes should throw as if the callee failed to look them up
  1087. AssertError(NameError, lambda : test_new_module.get_test_attr())
  1088. # unassigned builtins should return the built-in as if the caller looked them up
  1089. AreEqual(test_new_module.get_min(), min)
  1090. # we should be able to assign to values
  1091. test_new_module.test_attr = 42
  1092. # and the built-in module should see them
  1093. AreEqual(test_new_module.get_test_attr(), 42)
  1094. AreEqual(test_new_module.test_attr, 42)
  1095. # static members take precedence over things in globals
  1096. AreEqual(test_new_module.test_overlap_method(), 42)
  1097. AreEqual(type(test_new_module.test_overlap_type), type)
  1098. test_new_module.inc_value()
  1099. AreEqual(test_new_module.get_value(), 1)
  1100. test_new_module.inc_value()
  1101. AreEqual(test_new_module.get_value(), 2)
  1102. # can't access private fields
  1103. AssertError(AttributeError, lambda : test_new_module._value)
  1104. #------------------------------------------------------------------------------
  1105. run_test(__name__)
  1106. if not is_silverlight:
  1107. delete_all_f(__name__, remove_folders=True)