loader.py 21 KB

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