loader.py 20 KB

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