loader.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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. if os.path.isdir(os.path.abspath(start_dir)):
  254. start_dir = os.path.abspath(start_dir)
  255. if start_dir != top_level_dir:
  256. is_not_importable = not os.path.isfile(os.path.join(start_dir, '__init__.py'))
  257. else:
  258. # support for discovery from dotted module names
  259. try:
  260. __import__(start_dir)
  261. except ImportError:
  262. is_not_importable = True
  263. else:
  264. the_module = sys.modules[start_dir]
  265. top_part = start_dir.split('.')[0]
  266. try:
  267. start_dir = os.path.abspath(
  268. os.path.dirname((the_module.__file__)))
  269. except AttributeError:
  270. if the_module.__name__ in sys.builtin_module_names:
  271. # builtin module
  272. raise TypeError('Can not use builtin modules '
  273. 'as dotted module names') from None
  274. else:
  275. raise TypeError(
  276. f"don't know how to discover from {the_module!r}"
  277. ) from None
  278. if set_implicit_top:
  279. self._top_level_dir = self._get_directory_containing_module(top_part)
  280. sys.path.remove(top_level_dir)
  281. if is_not_importable:
  282. raise ImportError('Start directory is not importable: %r' % start_dir)
  283. tests = list(self._find_tests(start_dir, pattern))
  284. return self.suiteClass(tests)
  285. def _get_directory_containing_module(self, module_name):
  286. module = sys.modules[module_name]
  287. full_path = os.path.abspath(module.__file__)
  288. if os.path.basename(full_path).lower().startswith('__init__.py'):
  289. return os.path.dirname(os.path.dirname(full_path))
  290. else:
  291. # here we have been given a module rather than a package - so
  292. # all we can do is search the *same* directory the module is in
  293. # should an exception be raised instead
  294. return os.path.dirname(full_path)
  295. def _get_name_from_path(self, path):
  296. if path == self._top_level_dir:
  297. return '.'
  298. path = _jython_aware_splitext(os.path.normpath(path))
  299. _relpath = os.path.relpath(path, self._top_level_dir)
  300. assert not os.path.isabs(_relpath), "Path must be within the project"
  301. assert not _relpath.startswith('..'), "Path must be within the project"
  302. name = _relpath.replace(os.path.sep, '.')
  303. return name
  304. def _get_module_from_name(self, name):
  305. __import__(name)
  306. return sys.modules[name]
  307. def _match_path(self, path, full_path, pattern):
  308. # override this method to use alternative matching strategy
  309. return fnmatch(path, pattern)
  310. def _find_tests(self, start_dir, pattern):
  311. """Used by discovery. Yields test suites it loads."""
  312. # Handle the __init__ in this package
  313. name = self._get_name_from_path(start_dir)
  314. # name is '.' when start_dir == top_level_dir (and top_level_dir is by
  315. # definition not a package).
  316. if name != '.' and name not in self._loading_packages:
  317. # name is in self._loading_packages while we have called into
  318. # loadTestsFromModule with name.
  319. tests, should_recurse = self._find_test_path(start_dir, pattern)
  320. if tests is not None:
  321. yield tests
  322. if not should_recurse:
  323. # Either an error occurred, or load_tests was used by the
  324. # package.
  325. return
  326. # Handle the contents.
  327. paths = sorted(os.listdir(start_dir))
  328. for path in paths:
  329. full_path = os.path.join(start_dir, path)
  330. tests, should_recurse = self._find_test_path(full_path, pattern)
  331. if tests is not None:
  332. yield tests
  333. if should_recurse:
  334. # we found a package that didn't use load_tests.
  335. name = self._get_name_from_path(full_path)
  336. self._loading_packages.add(name)
  337. try:
  338. yield from self._find_tests(full_path, pattern)
  339. finally:
  340. self._loading_packages.discard(name)
  341. def _find_test_path(self, full_path, pattern):
  342. """Used by discovery.
  343. Loads tests from a single file, or a directories' __init__.py when
  344. passed the directory.
  345. Returns a tuple (None_or_tests_from_file, should_recurse).
  346. """
  347. basename = os.path.basename(full_path)
  348. if os.path.isfile(full_path):
  349. if not VALID_MODULE_NAME.match(basename):
  350. # valid Python identifiers only
  351. return None, False
  352. if not self._match_path(basename, full_path, pattern):
  353. return None, False
  354. # if the test file matches, load it
  355. name = self._get_name_from_path(full_path)
  356. try:
  357. module = self._get_module_from_name(name)
  358. except case.SkipTest as e:
  359. return _make_skipped_test(name, e, self.suiteClass), False
  360. except:
  361. error_case, error_message = \
  362. _make_failed_import_test(name, self.suiteClass)
  363. self.errors.append(error_message)
  364. return error_case, False
  365. else:
  366. mod_file = os.path.abspath(
  367. getattr(module, '__file__', full_path))
  368. realpath = _jython_aware_splitext(
  369. os.path.realpath(mod_file))
  370. fullpath_noext = _jython_aware_splitext(
  371. os.path.realpath(full_path))
  372. if realpath.lower() != fullpath_noext.lower():
  373. module_dir = os.path.dirname(realpath)
  374. mod_name = _jython_aware_splitext(
  375. os.path.basename(full_path))
  376. expected_dir = os.path.dirname(full_path)
  377. msg = ("%r module incorrectly imported from %r. Expected "
  378. "%r. Is this module globally installed?")
  379. raise ImportError(
  380. msg % (mod_name, module_dir, expected_dir))
  381. return self.loadTestsFromModule(module, pattern=pattern), False
  382. elif os.path.isdir(full_path):
  383. if not os.path.isfile(os.path.join(full_path, '__init__.py')):
  384. return None, False
  385. load_tests = None
  386. tests = None
  387. name = self._get_name_from_path(full_path)
  388. try:
  389. package = self._get_module_from_name(name)
  390. except case.SkipTest as e:
  391. return _make_skipped_test(name, e, self.suiteClass), False
  392. except:
  393. error_case, error_message = \
  394. _make_failed_import_test(name, self.suiteClass)
  395. self.errors.append(error_message)
  396. return error_case, False
  397. else:
  398. load_tests = getattr(package, 'load_tests', None)
  399. # Mark this package as being in load_tests (possibly ;))
  400. self._loading_packages.add(name)
  401. try:
  402. tests = self.loadTestsFromModule(package, pattern=pattern)
  403. if load_tests is not None:
  404. # loadTestsFromModule(package) has loaded tests for us.
  405. return tests, False
  406. return tests, True
  407. finally:
  408. self._loading_packages.discard(name)
  409. else:
  410. return None, False
  411. defaultTestLoader = TestLoader()
  412. # These functions are considered obsolete for long time.
  413. # They will be removed in Python 3.13.
  414. def _makeLoader(prefix, sortUsing, suiteClass=None, testNamePatterns=None):
  415. loader = TestLoader()
  416. loader.sortTestMethodsUsing = sortUsing
  417. loader.testMethodPrefix = prefix
  418. loader.testNamePatterns = testNamePatterns
  419. if suiteClass:
  420. loader.suiteClass = suiteClass
  421. return loader
  422. def getTestCaseNames(testCaseClass, prefix, sortUsing=util.three_way_cmp, testNamePatterns=None):
  423. import warnings
  424. warnings.warn(
  425. "unittest.getTestCaseNames() is deprecated and will be removed in Python 3.13. "
  426. "Please use unittest.TestLoader.getTestCaseNames() instead.",
  427. DeprecationWarning, stacklevel=2
  428. )
  429. return _makeLoader(prefix, sortUsing, testNamePatterns=testNamePatterns).getTestCaseNames(testCaseClass)
  430. def makeSuite(testCaseClass, prefix='test', sortUsing=util.three_way_cmp,
  431. suiteClass=suite.TestSuite):
  432. import warnings
  433. warnings.warn(
  434. "unittest.makeSuite() is deprecated and will be removed in Python 3.13. "
  435. "Please use unittest.TestLoader.loadTestsFromTestCase() instead.",
  436. DeprecationWarning, stacklevel=2
  437. )
  438. return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(
  439. testCaseClass)
  440. def findTestCases(module, prefix='test', sortUsing=util.three_way_cmp,
  441. suiteClass=suite.TestSuite):
  442. import warnings
  443. warnings.warn(
  444. "unittest.findTestCases() is deprecated and will be removed in Python 3.13. "
  445. "Please use unittest.TestLoader.loadTestsFromModule() instead.",
  446. DeprecationWarning, stacklevel=2
  447. )
  448. return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(\
  449. module)