loader.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. """Loading unittests."""
  2. import os
  3. import re
  4. import sys
  5. import traceback
  6. import types
  7. import functools
  8. import warnings
  9. from fnmatch import fnmatch, fnmatchcase
  10. from . import case, suite, util
  11. __unittest = True
  12. # what about .pyc (etc)
  13. # we would need to avoid loading the same tests multiple times
  14. # from '.py', *and* '.pyc'
  15. VALID_MODULE_NAME = re.compile(r'[_a-z]\w*\.py$', re.IGNORECASE)
  16. class _FailedTest(case.TestCase):
  17. _testMethodName = None
  18. def __init__(self, method_name, exception):
  19. self._exception = exception
  20. super(_FailedTest, self).__init__(method_name)
  21. def __getattr__(self, name):
  22. if name != self._testMethodName:
  23. return super(_FailedTest, self).__getattr__(name)
  24. def testFailure():
  25. raise self._exception
  26. return testFailure
  27. def _make_failed_import_test(name, suiteClass):
  28. message = 'Failed to import test module: %s\n%s' % (
  29. name, traceback.format_exc())
  30. return _make_failed_test(name, ImportError(message), suiteClass, message)
  31. def _make_failed_load_tests(name, exception, suiteClass):
  32. message = 'Failed to call load_tests:\n%s' % (traceback.format_exc(),)
  33. return _make_failed_test(
  34. name, exception, suiteClass, message)
  35. def _make_failed_test(methodname, exception, suiteClass, message):
  36. test = _FailedTest(methodname, exception)
  37. return suiteClass((test,)), message
  38. def _make_skipped_test(methodname, exception, suiteClass):
  39. @case.skip(str(exception))
  40. def testSkipped(self):
  41. pass
  42. attrs = {methodname: testSkipped}
  43. TestClass = type("ModuleSkipped", (case.TestCase,), attrs)
  44. return suiteClass((TestClass(methodname),))
  45. def _jython_aware_splitext(path):
  46. if path.lower().endswith('$py.class'):
  47. return path[:-9]
  48. return os.path.splitext(path)[0]
  49. class TestLoader(object):
  50. """
  51. This class is responsible for loading tests according to various criteria
  52. and returning them wrapped in a TestSuite
  53. """
  54. testMethodPrefix = 'test'
  55. sortTestMethodsUsing = staticmethod(util.three_way_cmp)
  56. testNamePatterns = None
  57. suiteClass = suite.TestSuite
  58. _top_level_dir = None
  59. def __init__(self):
  60. super(TestLoader, self).__init__()
  61. self.errors = []
  62. # Tracks packages which we have called into via load_tests, to
  63. # avoid infinite re-entrancy.
  64. self._loading_packages = set()
  65. def loadTestsFromTestCase(self, testCaseClass):
  66. """Return a suite of all test cases contained in testCaseClass"""
  67. if issubclass(testCaseClass, suite.TestSuite):
  68. raise TypeError("Test cases should not be derived from "
  69. "TestSuite. Maybe you meant to derive from "
  70. "TestCase?")
  71. testCaseNames = self.getTestCaseNames(testCaseClass)
  72. if not testCaseNames and hasattr(testCaseClass, 'runTest'):
  73. testCaseNames = ['runTest']
  74. loaded_suite = self.suiteClass(map(testCaseClass, testCaseNames))
  75. return loaded_suite
  76. # XXX After Python 3.5, remove backward compatibility hacks for
  77. # use_load_tests deprecation via *args and **kws. See issue 16662.
  78. def loadTestsFromModule(self, module, *args, pattern=None, **kws):
  79. """Return a suite of all test cases contained in the given module"""
  80. # This method used to take an undocumented and unofficial
  81. # use_load_tests argument. For backward compatibility, we still
  82. # accept the argument (which can also be the first position) but we
  83. # ignore it and issue a deprecation warning if it's present.
  84. if len(args) > 0 or 'use_load_tests' in kws:
  85. warnings.warn('use_load_tests is deprecated and ignored',
  86. DeprecationWarning)
  87. kws.pop('use_load_tests', None)
  88. if len(args) > 1:
  89. # Complain about the number of arguments, but don't forget the
  90. # required `module` argument.
  91. complaint = len(args) + 1
  92. raise TypeError('loadTestsFromModule() takes 1 positional argument but {} were given'.format(complaint))
  93. if len(kws) != 0:
  94. # Since the keyword arguments are unsorted (see PEP 468), just
  95. # pick the alphabetically sorted first argument to complain about,
  96. # if multiple were given. At least the error message will be
  97. # predictable.
  98. complaint = sorted(kws)[0]
  99. raise TypeError("loadTestsFromModule() got an unexpected keyword argument '{}'".format(complaint))
  100. tests = []
  101. for name in dir(module):
  102. obj = getattr(module, name)
  103. if isinstance(obj, type) and issubclass(obj, case.TestCase):
  104. tests.append(self.loadTestsFromTestCase(obj))
  105. load_tests = getattr(module, 'load_tests', None)
  106. tests = self.suiteClass(tests)
  107. if load_tests is not None:
  108. try:
  109. return load_tests(self, tests, pattern)
  110. except Exception as e:
  111. error_case, error_message = _make_failed_load_tests(
  112. module.__name__, e, self.suiteClass)
  113. self.errors.append(error_message)
  114. return error_case
  115. return tests
  116. def loadTestsFromName(self, name, module=None):
  117. """Return a suite of all test cases given a string specifier.
  118. The name may resolve either to a module, a test case class, a
  119. test method within a test case class, or a callable object which
  120. returns a TestCase or TestSuite instance.
  121. The method optionally resolves the names relative to a given module.
  122. """
  123. parts = name.split('.')
  124. error_case, error_message = None, None
  125. if module is None:
  126. parts_copy = parts[:]
  127. while parts_copy:
  128. try:
  129. module_name = '.'.join(parts_copy)
  130. module = __import__(module_name)
  131. break
  132. except ImportError:
  133. next_attribute = parts_copy.pop()
  134. # Last error so we can give it to the user if needed.
  135. error_case, error_message = _make_failed_import_test(
  136. next_attribute, self.suiteClass)
  137. if not parts_copy:
  138. # Even the top level import failed: report that error.
  139. self.errors.append(error_message)
  140. return error_case
  141. parts = parts[1:]
  142. obj = module
  143. for part in parts:
  144. try:
  145. parent, obj = obj, getattr(obj, part)
  146. except AttributeError as e:
  147. # We can't traverse some part of the name.
  148. if (getattr(obj, '__path__', None) is not None
  149. and error_case is not None):
  150. # This is a package (no __path__ per importlib docs), and we
  151. # encountered an error importing something. We cannot tell
  152. # the difference between package.WrongNameTestClass and
  153. # package.wrong_module_name so we just report the
  154. # ImportError - it is more informative.
  155. self.errors.append(error_message)
  156. return error_case
  157. else:
  158. # Otherwise, we signal that an AttributeError has occurred.
  159. error_case, error_message = _make_failed_test(
  160. part, e, self.suiteClass,
  161. 'Failed to access attribute:\n%s' % (
  162. traceback.format_exc(),))
  163. self.errors.append(error_message)
  164. return error_case
  165. if isinstance(obj, types.ModuleType):
  166. return self.loadTestsFromModule(obj)
  167. elif isinstance(obj, type) and issubclass(obj, case.TestCase):
  168. return self.loadTestsFromTestCase(obj)
  169. elif (isinstance(obj, types.FunctionType) and
  170. isinstance(parent, type) and
  171. issubclass(parent, case.TestCase)):
  172. name = parts[-1]
  173. inst = parent(name)
  174. # static methods follow a different path
  175. if not isinstance(getattr(inst, name), types.FunctionType):
  176. return self.suiteClass([inst])
  177. elif isinstance(obj, suite.TestSuite):
  178. return obj
  179. if callable(obj):
  180. test = obj()
  181. if isinstance(test, suite.TestSuite):
  182. return test
  183. elif isinstance(test, case.TestCase):
  184. return self.suiteClass([test])
  185. else:
  186. raise TypeError("calling %s returned %s, not a test" %
  187. (obj, test))
  188. else:
  189. raise TypeError("don't know how to make test from: %s" % obj)
  190. def loadTestsFromNames(self, names, module=None):
  191. """Return a suite of all test cases found using the given sequence
  192. of string specifiers. See 'loadTestsFromName()'.
  193. """
  194. suites = [self.loadTestsFromName(name, module) for name in names]
  195. return self.suiteClass(suites)
  196. def getTestCaseNames(self, testCaseClass):
  197. """Return a sorted sequence of method names found within testCaseClass
  198. """
  199. def shouldIncludeMethod(attrname):
  200. if not attrname.startswith(self.testMethodPrefix):
  201. return False
  202. testFunc = getattr(testCaseClass, attrname)
  203. if not callable(testFunc):
  204. return False
  205. fullName = f'%s.%s.%s' % (
  206. testCaseClass.__module__, testCaseClass.__qualname__, attrname
  207. )
  208. return self.testNamePatterns is None or \
  209. any(fnmatchcase(fullName, pattern) for pattern in self.testNamePatterns)
  210. testFnNames = list(filter(shouldIncludeMethod, dir(testCaseClass)))
  211. if self.sortTestMethodsUsing:
  212. testFnNames.sort(key=functools.cmp_to_key(self.sortTestMethodsUsing))
  213. return testFnNames
  214. def discover(self, start_dir, pattern='test*.py', top_level_dir=None):
  215. """Find and return all test modules from the specified start
  216. directory, recursing into subdirectories to find them and return all
  217. tests found within them. Only test files that match the pattern will
  218. be loaded. (Using shell style pattern matching.)
  219. All test modules must be importable from the top level of the project.
  220. If the start directory is not the top level directory then the top
  221. level directory must be specified separately.
  222. If a test package name (directory with '__init__.py') matches the
  223. pattern then the package will be checked for a 'load_tests' function. If
  224. this exists then it will be called with (loader, tests, pattern) unless
  225. the package has already had load_tests called from the same discovery
  226. invocation, in which case the package module object is not scanned for
  227. tests - this ensures that when a package uses discover to further
  228. discover child tests that infinite recursion does not happen.
  229. If load_tests exists then discovery does *not* recurse into the package,
  230. load_tests is responsible for loading all tests in the package.
  231. The pattern is deliberately not stored as a loader attribute so that
  232. packages can continue discovery themselves. top_level_dir is stored so
  233. load_tests does not need to pass this argument in to loader.discover().
  234. Paths are sorted before being imported to ensure reproducible execution
  235. order even on filesystems with non-alphabetical ordering like ext3/4.
  236. """
  237. set_implicit_top = False
  238. if top_level_dir is None and self._top_level_dir is not None:
  239. # make top_level_dir optional if called from load_tests in a package
  240. top_level_dir = self._top_level_dir
  241. elif top_level_dir is None:
  242. set_implicit_top = True
  243. top_level_dir = start_dir
  244. top_level_dir = os.path.abspath(top_level_dir)
  245. if not top_level_dir in sys.path:
  246. # all test modules must be importable from the top level directory
  247. # should we *unconditionally* put the start directory in first
  248. # in sys.path to minimise likelihood of conflicts between installed
  249. # modules and development versions?
  250. sys.path.insert(0, top_level_dir)
  251. self._top_level_dir = top_level_dir
  252. is_not_importable = False
  253. is_namespace = False
  254. tests = []
  255. if os.path.isdir(os.path.abspath(start_dir)):
  256. start_dir = os.path.abspath(start_dir)
  257. if start_dir != top_level_dir:
  258. is_not_importable = not os.path.isfile(os.path.join(start_dir, '__init__.py'))
  259. else:
  260. # support for discovery from dotted module names
  261. try:
  262. __import__(start_dir)
  263. except ImportError:
  264. is_not_importable = True
  265. else:
  266. the_module = sys.modules[start_dir]
  267. top_part = start_dir.split('.')[0]
  268. try:
  269. start_dir = os.path.abspath(
  270. os.path.dirname((the_module.__file__)))
  271. except AttributeError:
  272. # look for namespace packages
  273. try:
  274. spec = the_module.__spec__
  275. except AttributeError:
  276. spec = None
  277. if spec and spec.loader is None:
  278. if spec.submodule_search_locations is not None:
  279. is_namespace = True
  280. for path in the_module.__path__:
  281. if (not set_implicit_top and
  282. not path.startswith(top_level_dir)):
  283. continue
  284. self._top_level_dir = \
  285. (path.split(the_module.__name__
  286. .replace(".", os.path.sep))[0])
  287. tests.extend(self._find_tests(path,
  288. pattern,
  289. namespace=True))
  290. elif the_module.__name__ in sys.builtin_module_names:
  291. # builtin module
  292. raise TypeError('Can not use builtin modules '
  293. 'as dotted module names') from None
  294. else:
  295. raise TypeError(
  296. 'don\'t know how to discover from {!r}'
  297. .format(the_module)) from None
  298. if set_implicit_top:
  299. if not is_namespace:
  300. self._top_level_dir = \
  301. self._get_directory_containing_module(top_part)
  302. sys.path.remove(top_level_dir)
  303. else:
  304. sys.path.remove(top_level_dir)
  305. if is_not_importable:
  306. raise ImportError('Start directory is not importable: %r' % start_dir)
  307. if not is_namespace:
  308. tests = list(self._find_tests(start_dir, pattern))
  309. return self.suiteClass(tests)
  310. def _get_directory_containing_module(self, module_name):
  311. module = sys.modules[module_name]
  312. full_path = os.path.abspath(module.__file__)
  313. if os.path.basename(full_path).lower().startswith('__init__.py'):
  314. return os.path.dirname(os.path.dirname(full_path))
  315. else:
  316. # here we have been given a module rather than a package - so
  317. # all we can do is search the *same* directory the module is in
  318. # should an exception be raised instead
  319. return os.path.dirname(full_path)
  320. def _get_name_from_path(self, path):
  321. if path == self._top_level_dir:
  322. return '.'
  323. path = _jython_aware_splitext(os.path.normpath(path))
  324. _relpath = os.path.relpath(path, self._top_level_dir)
  325. assert not os.path.isabs(_relpath), "Path must be within the project"
  326. assert not _relpath.startswith('..'), "Path must be within the project"
  327. name = _relpath.replace(os.path.sep, '.')
  328. return name
  329. def _get_module_from_name(self, name):
  330. __import__(name)
  331. return sys.modules[name]
  332. def _match_path(self, path, full_path, pattern):
  333. # override this method to use alternative matching strategy
  334. return fnmatch(path, pattern)
  335. def _find_tests(self, start_dir, pattern, namespace=False):
  336. """Used by discovery. Yields test suites it loads."""
  337. # Handle the __init__ in this package
  338. name = self._get_name_from_path(start_dir)
  339. # name is '.' when start_dir == top_level_dir (and top_level_dir is by
  340. # definition not a package).
  341. if name != '.' and name not in self._loading_packages:
  342. # name is in self._loading_packages while we have called into
  343. # loadTestsFromModule with name.
  344. tests, should_recurse = self._find_test_path(
  345. start_dir, pattern, namespace)
  346. if tests is not None:
  347. yield tests
  348. if not should_recurse:
  349. # Either an error occurred, or load_tests was used by the
  350. # package.
  351. return
  352. # Handle the contents.
  353. paths = sorted(os.listdir(start_dir))
  354. for path in paths:
  355. full_path = os.path.join(start_dir, path)
  356. tests, should_recurse = self._find_test_path(
  357. full_path, pattern, namespace)
  358. if tests is not None:
  359. yield tests
  360. if should_recurse:
  361. # we found a package that didn't use load_tests.
  362. name = self._get_name_from_path(full_path)
  363. self._loading_packages.add(name)
  364. try:
  365. yield from self._find_tests(full_path, pattern, namespace)
  366. finally:
  367. self._loading_packages.discard(name)
  368. def _find_test_path(self, full_path, pattern, namespace=False):
  369. """Used by discovery.
  370. Loads tests from a single file, or a directories' __init__.py when
  371. passed the directory.
  372. Returns a tuple (None_or_tests_from_file, should_recurse).
  373. """
  374. basename = os.path.basename(full_path)
  375. if os.path.isfile(full_path):
  376. if not VALID_MODULE_NAME.match(basename):
  377. # valid Python identifiers only
  378. return None, False
  379. if not self._match_path(basename, full_path, pattern):
  380. return None, False
  381. # if the test file matches, load it
  382. name = self._get_name_from_path(full_path)
  383. try:
  384. module = self._get_module_from_name(name)
  385. except case.SkipTest as e:
  386. return _make_skipped_test(name, e, self.suiteClass), False
  387. except:
  388. error_case, error_message = \
  389. _make_failed_import_test(name, self.suiteClass)
  390. self.errors.append(error_message)
  391. return error_case, False
  392. else:
  393. mod_file = os.path.abspath(
  394. getattr(module, '__file__', full_path))
  395. realpath = _jython_aware_splitext(
  396. os.path.realpath(mod_file))
  397. fullpath_noext = _jython_aware_splitext(
  398. os.path.realpath(full_path))
  399. if realpath.lower() != fullpath_noext.lower():
  400. module_dir = os.path.dirname(realpath)
  401. mod_name = _jython_aware_splitext(
  402. os.path.basename(full_path))
  403. expected_dir = os.path.dirname(full_path)
  404. msg = ("%r module incorrectly imported from %r. Expected "
  405. "%r. Is this module globally installed?")
  406. raise ImportError(
  407. msg % (mod_name, module_dir, expected_dir))
  408. return self.loadTestsFromModule(module, pattern=pattern), False
  409. elif os.path.isdir(full_path):
  410. if (not namespace and
  411. not os.path.isfile(os.path.join(full_path, '__init__.py'))):
  412. return None, False
  413. load_tests = None
  414. tests = None
  415. name = self._get_name_from_path(full_path)
  416. try:
  417. package = self._get_module_from_name(name)
  418. except case.SkipTest as e:
  419. return _make_skipped_test(name, e, self.suiteClass), False
  420. except:
  421. error_case, error_message = \
  422. _make_failed_import_test(name, self.suiteClass)
  423. self.errors.append(error_message)
  424. return error_case, False
  425. else:
  426. load_tests = getattr(package, 'load_tests', None)
  427. # Mark this package as being in load_tests (possibly ;))
  428. self._loading_packages.add(name)
  429. try:
  430. tests = self.loadTestsFromModule(package, pattern=pattern)
  431. if load_tests is not None:
  432. # loadTestsFromModule(package) has loaded tests for us.
  433. return tests, False
  434. return tests, True
  435. finally:
  436. self._loading_packages.discard(name)
  437. else:
  438. return None, False
  439. defaultTestLoader = TestLoader()
  440. def _makeLoader(prefix, sortUsing, suiteClass=None, testNamePatterns=None):
  441. loader = TestLoader()
  442. loader.sortTestMethodsUsing = sortUsing
  443. loader.testMethodPrefix = prefix
  444. loader.testNamePatterns = testNamePatterns
  445. if suiteClass:
  446. loader.suiteClass = suiteClass
  447. return loader
  448. def getTestCaseNames(testCaseClass, prefix, sortUsing=util.three_way_cmp, testNamePatterns=None):
  449. return _makeLoader(prefix, sortUsing, testNamePatterns=testNamePatterns).getTestCaseNames(testCaseClass)
  450. def makeSuite(testCaseClass, prefix='test', sortUsing=util.three_way_cmp,
  451. suiteClass=suite.TestSuite):
  452. return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(
  453. testCaseClass)
  454. def findTestCases(module, prefix='test', sortUsing=util.three_way_cmp,
  455. suiteClass=suite.TestSuite):
  456. return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(\
  457. module)