/nose/importer.py

https://bitbucket.org/jpellerin/nose/ · Python · 154 lines · 107 code · 17 blank · 30 comment · 32 complexity · 21e2d2549ef8e87454a9d8bea9b6ad08 MD5 · raw file

  1. """Implements an importer that looks only in specific path (ignoring
  2. sys.path), and uses a per-path cache in addition to sys.modules. This is
  3. necessary because test modules in different directories frequently have the
  4. same names, which means that the first loaded would mask the rest when using
  5. the builtin importer.
  6. """
  7. import logging
  8. import os
  9. import sys
  10. from nose.config import Config
  11. from imp import find_module, load_module, acquire_lock, release_lock
  12. log = logging.getLogger(__name__)
  13. class Importer(object):
  14. """An importer class that does only path-specific imports. That
  15. is, the given module is not searched for on sys.path, but only at
  16. the path or in the directory specified.
  17. """
  18. def __init__(self, config=None):
  19. if config is None:
  20. config = Config()
  21. self.config = config
  22. def importFromPath(self, path, fqname):
  23. """Import a dotted-name package whose tail is at path. In other words,
  24. given foo.bar and path/to/foo/bar.py, import foo from path/to/foo then
  25. bar from path/to/foo/bar, returning bar.
  26. """
  27. # find the base dir of the package
  28. path_parts = os.path.normpath(os.path.abspath(path)).split(os.sep)
  29. name_parts = fqname.split('.')
  30. if path_parts[-1].startswith('__init__'):
  31. path_parts.pop()
  32. path_parts = path_parts[:-(len(name_parts))]
  33. dir_path = os.sep.join(path_parts)
  34. # then import fqname starting from that dir
  35. return self.importFromDir(dir_path, fqname)
  36. def importFromDir(self, dir, fqname):
  37. """Import a module *only* from path, ignoring sys.path and
  38. reloading if the version in sys.modules is not the one we want.
  39. """
  40. dir = os.path.normpath(os.path.abspath(dir))
  41. log.debug("Import %s from %s", fqname, dir)
  42. # FIXME reimplement local per-dir cache?
  43. # special case for __main__
  44. if fqname == '__main__':
  45. return sys.modules[fqname]
  46. if self.config.addPaths:
  47. add_path(dir, self.config)
  48. path = [dir]
  49. parts = fqname.split('.')
  50. part_fqname = ''
  51. mod = parent = fh = None
  52. for part in parts:
  53. if part_fqname == '':
  54. part_fqname = part
  55. else:
  56. part_fqname = "%s.%s" % (part_fqname, part)
  57. try:
  58. acquire_lock()
  59. log.debug("find module part %s (%s) in %s",
  60. part, part_fqname, path)
  61. fh, filename, desc = find_module(part, path)
  62. old = sys.modules.get(part_fqname)
  63. if old is not None:
  64. # test modules frequently have name overlap; make sure
  65. # we get a fresh copy of anything we are trying to load
  66. # from a new path
  67. log.debug("sys.modules has %s as %s", part_fqname, old)
  68. if (self.sameModule(old, filename)
  69. or (self.config.firstPackageWins and
  70. getattr(old, '__path__', None))):
  71. mod = old
  72. else:
  73. del sys.modules[part_fqname]
  74. mod = load_module(part_fqname, fh, filename, desc)
  75. else:
  76. mod = load_module(part_fqname, fh, filename, desc)
  77. finally:
  78. if fh:
  79. fh.close()
  80. release_lock()
  81. if parent:
  82. setattr(parent, part, mod)
  83. if hasattr(mod, '__path__'):
  84. path = mod.__path__
  85. parent = mod
  86. return mod
  87. def sameModule(self, mod, filename):
  88. mod_paths = []
  89. if hasattr(mod, '__path__'):
  90. for path in mod.__path__:
  91. mod_paths.append(os.path.dirname(
  92. os.path.normpath(
  93. os.path.abspath(path))))
  94. elif hasattr(mod, '__file__'):
  95. mod_paths.append(os.path.dirname(
  96. os.path.normpath(
  97. os.path.abspath(mod.__file__))))
  98. else:
  99. # builtin or other module-like object that
  100. # doesn't have __file__; must be new
  101. return False
  102. new_path = os.path.dirname(os.path.normpath(filename))
  103. for mod_path in mod_paths:
  104. log.debug(
  105. "module already loaded? mod: %s new: %s",
  106. mod_path, new_path)
  107. if mod_path == new_path:
  108. return True
  109. return False
  110. def add_path(path, config=None):
  111. """Ensure that the path, or the root of the current package (if
  112. path is in a package), is in sys.path.
  113. """
  114. # FIXME add any src-looking dirs seen too... need to get config for that
  115. log.debug('Add path %s' % path)
  116. if not path:
  117. return []
  118. added = []
  119. parent = os.path.dirname(path)
  120. if (parent
  121. and os.path.exists(os.path.join(path, '__init__.py'))):
  122. added.extend(add_path(parent, config))
  123. elif not path in sys.path:
  124. log.debug("insert %s into sys.path", path)
  125. sys.path.insert(0, path)
  126. added.append(path)
  127. if config and config.srcDirs:
  128. for dirname in config.srcDirs:
  129. dirpath = os.path.join(path, dirname)
  130. if os.path.isdir(dirpath):
  131. sys.path.insert(0, dirpath)
  132. added.append(dirpath)
  133. return added
  134. def remove_path(path):
  135. log.debug('Remove path %s' % path)
  136. if path in sys.path:
  137. sys.path.remove(path)