runner.py 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  1. # -*- test-case-name: twisted.trial.test.test_runner -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. A miscellany of code used to run Trial tests.
  6. Maintainer: Jonathan Lange
  7. """
  8. from __future__ import absolute_import, division
  9. __all__ = [
  10. 'TestSuite',
  11. 'DestructiveTestSuite', 'ErrorHolder', 'LoggedSuite',
  12. 'TestHolder', 'TestLoader', 'TrialRunner', 'TrialSuite',
  13. 'filenameToModule', 'isPackage', 'isPackageDirectory', 'isTestCase',
  14. 'name', 'samefile', 'NOT_IN_TEST',
  15. ]
  16. import doctest
  17. import inspect
  18. import os
  19. import sys
  20. import time
  21. import types
  22. import warnings
  23. from twisted.python import reflect, log, failure, modules, filepath
  24. from twisted.python.compat import _PY3, _PY35PLUS
  25. from twisted.internet import defer
  26. from twisted.trial import util, unittest
  27. from twisted.trial.itrial import ITestCase
  28. from twisted.trial.reporter import _ExitWrapper, UncleanWarningsReporterWrapper
  29. from twisted.trial._asyncrunner import _ForceGarbageCollectionDecorator, _iterateTests
  30. from twisted.trial._synctest import _logObserver
  31. # These are imported so that they remain in the public API for t.trial.runner
  32. from twisted.trial.unittest import TestSuite
  33. from zope.interface import implementer
  34. pyunit = __import__('unittest')
  35. def isPackage(module):
  36. """Given an object return True if the object looks like a package"""
  37. if not isinstance(module, types.ModuleType):
  38. return False
  39. basename = os.path.splitext(os.path.basename(module.__file__))[0]
  40. return basename == '__init__'
  41. def isPackageDirectory(dirname):
  42. """
  43. Is the directory at path 'dirname' a Python package directory?
  44. Returns the name of the __init__ file (it may have a weird extension)
  45. if dirname is a package directory. Otherwise, returns False
  46. """
  47. def _getSuffixes():
  48. if _PY3:
  49. import importlib
  50. return importlib.machinery.all_suffixes()
  51. else:
  52. import imp
  53. return list(zip(*imp.get_suffixes()))[0]
  54. for ext in _getSuffixes():
  55. initFile = '__init__' + ext
  56. if os.path.exists(os.path.join(dirname, initFile)):
  57. return initFile
  58. return False
  59. def samefile(filename1, filename2):
  60. """
  61. A hacky implementation of C{os.path.samefile}. Used by L{filenameToModule}
  62. when the platform doesn't provide C{os.path.samefile}. Do not use this.
  63. """
  64. return os.path.abspath(filename1) == os.path.abspath(filename2)
  65. def filenameToModule(fn):
  66. """
  67. Given a filename, do whatever possible to return a module object matching
  68. that file.
  69. If the file in question is a module in Python path, properly import and
  70. return that module. Otherwise, load the source manually.
  71. @param fn: A filename.
  72. @return: A module object.
  73. @raise ValueError: If C{fn} does not exist.
  74. """
  75. if not os.path.exists(fn):
  76. raise ValueError("%r doesn't exist" % (fn,))
  77. try:
  78. ret = reflect.namedAny(reflect.filenameToModuleName(fn))
  79. except (ValueError, AttributeError):
  80. # Couldn't find module. The file 'fn' is not in PYTHONPATH
  81. return _importFromFile(fn)
  82. # >=3.7 has __file__ attribute as None, previously __file__ was not present
  83. if getattr(ret, "__file__", None) is None:
  84. # This isn't a Python module in a package, so import it from a file
  85. return _importFromFile(fn)
  86. # ensure that the loaded module matches the file
  87. retFile = os.path.splitext(ret.__file__)[0] + '.py'
  88. # not all platforms (e.g. win32) have os.path.samefile
  89. same = getattr(os.path, 'samefile', samefile)
  90. if os.path.isfile(fn) and not same(fn, retFile):
  91. del sys.modules[ret.__name__]
  92. ret = _importFromFile(fn)
  93. return ret
  94. def _importFromFile(fn, moduleName=None):
  95. fn = _resolveDirectory(fn)
  96. if not moduleName:
  97. moduleName = os.path.splitext(os.path.split(fn)[-1])[0]
  98. if moduleName in sys.modules:
  99. return sys.modules[moduleName]
  100. if _PY35PLUS:
  101. import importlib
  102. spec = importlib.util.spec_from_file_location(moduleName, fn)
  103. if not spec:
  104. raise SyntaxError(fn)
  105. module = importlib.util.module_from_spec(spec)
  106. spec.loader.exec_module(module)
  107. sys.modules[moduleName] = module
  108. else:
  109. import imp
  110. with open(fn, 'r') as fd:
  111. module = imp.load_source(moduleName, fn, fd)
  112. return module
  113. def _resolveDirectory(fn):
  114. if os.path.isdir(fn):
  115. initFile = isPackageDirectory(fn)
  116. if initFile:
  117. fn = os.path.join(fn, initFile)
  118. else:
  119. raise ValueError('%r is not a package directory' % (fn,))
  120. return fn
  121. def _getMethodNameInClass(method):
  122. """
  123. Find the attribute name on the method's class which refers to the method.
  124. For some methods, notably decorators which have not had __name__ set correctly:
  125. getattr(method.im_class, method.__name__) != method
  126. """
  127. if getattr(method.im_class, method.__name__, object()) != method:
  128. for alias in dir(method.im_class):
  129. if getattr(method.im_class, alias, object()) == method:
  130. return alias
  131. return method.__name__
  132. class DestructiveTestSuite(TestSuite):
  133. """
  134. A test suite which remove the tests once run, to minimize memory usage.
  135. """
  136. def run(self, result):
  137. """
  138. Almost the same as L{TestSuite.run}, but with C{self._tests} being
  139. empty at the end.
  140. """
  141. while self._tests:
  142. if result.shouldStop:
  143. break
  144. test = self._tests.pop(0)
  145. test(result)
  146. return result
  147. # When an error occurs outside of any test, the user will see this string
  148. # in place of a test's name.
  149. NOT_IN_TEST = "<not in test>"
  150. class LoggedSuite(TestSuite):
  151. """
  152. Any errors logged in this suite will be reported to the L{TestResult}
  153. object.
  154. """
  155. def run(self, result):
  156. """
  157. Run the suite, storing all errors in C{result}. If an error is logged
  158. while no tests are running, then it will be added as an error to
  159. C{result}.
  160. @param result: A L{TestResult} object.
  161. """
  162. observer = _logObserver
  163. observer._add()
  164. super(LoggedSuite, self).run(result)
  165. observer._remove()
  166. for error in observer.getErrors():
  167. result.addError(TestHolder(NOT_IN_TEST), error)
  168. observer.flushErrors()
  169. class TrialSuite(TestSuite):
  170. """
  171. Suite to wrap around every single test in a C{trial} run. Used internally
  172. by Trial to set up things necessary for Trial tests to work, regardless of
  173. what context they are run in.
  174. """
  175. def __init__(self, tests=(), forceGarbageCollection=False):
  176. if forceGarbageCollection:
  177. newTests = []
  178. for test in tests:
  179. test = unittest.decorate(
  180. test, _ForceGarbageCollectionDecorator)
  181. newTests.append(test)
  182. tests = newTests
  183. suite = LoggedSuite(tests)
  184. super(TrialSuite, self).__init__([suite])
  185. def _bail(self):
  186. from twisted.internet import reactor
  187. d = defer.Deferred()
  188. reactor.addSystemEventTrigger('after', 'shutdown',
  189. lambda: d.callback(None))
  190. reactor.fireSystemEvent('shutdown') # radix's suggestion
  191. # As long as TestCase does crap stuff with the reactor we need to
  192. # manually shutdown the reactor here, and that requires util.wait
  193. # :(
  194. # so that the shutdown event completes
  195. unittest.TestCase('mktemp')._wait(d)
  196. def run(self, result):
  197. try:
  198. TestSuite.run(self, result)
  199. finally:
  200. self._bail()
  201. def name(thing):
  202. """
  203. @param thing: an object from modules (instance of PythonModule,
  204. PythonAttribute), a TestCase subclass, or an instance of a TestCase.
  205. """
  206. if isTestCase(thing):
  207. # TestCase subclass
  208. theName = reflect.qual(thing)
  209. else:
  210. # thing from trial, or thing from modules.
  211. # this monstrosity exists so that modules' objects do not have to
  212. # implement id(). -jml
  213. try:
  214. theName = thing.id()
  215. except AttributeError:
  216. theName = thing.name
  217. return theName
  218. def isTestCase(obj):
  219. """
  220. @return: C{True} if C{obj} is a class that contains test cases, C{False}
  221. otherwise. Used to find all the tests in a module.
  222. """
  223. try:
  224. return issubclass(obj, pyunit.TestCase)
  225. except TypeError:
  226. return False
  227. @implementer(ITestCase)
  228. class TestHolder(object):
  229. """
  230. Placeholder for a L{TestCase} inside a reporter. As far as a L{TestResult}
  231. is concerned, this looks exactly like a unit test.
  232. """
  233. failureException = None
  234. def __init__(self, description):
  235. """
  236. @param description: A string to be displayed L{TestResult}.
  237. """
  238. self.description = description
  239. def __call__(self, result):
  240. return self.run(result)
  241. def id(self):
  242. return self.description
  243. def countTestCases(self):
  244. return 0
  245. def run(self, result):
  246. """
  247. This test is just a placeholder. Run the test successfully.
  248. @param result: The C{TestResult} to store the results in.
  249. @type result: L{twisted.trial.itrial.IReporter}.
  250. """
  251. result.startTest(self)
  252. result.addSuccess(self)
  253. result.stopTest(self)
  254. def shortDescription(self):
  255. return self.description
  256. class ErrorHolder(TestHolder):
  257. """
  258. Used to insert arbitrary errors into a test suite run. Provides enough
  259. methods to look like a C{TestCase}, however, when it is run, it simply adds
  260. an error to the C{TestResult}. The most common use-case is for when a
  261. module fails to import.
  262. """
  263. def __init__(self, description, error):
  264. """
  265. @param description: A string used by C{TestResult}s to identify this
  266. error. Generally, this is the name of a module that failed to import.
  267. @param error: The error to be added to the result. Can be an `exc_info`
  268. tuple or a L{twisted.python.failure.Failure}.
  269. """
  270. super(ErrorHolder, self).__init__(description)
  271. self.error = util.excInfoOrFailureToExcInfo(error)
  272. def __repr__(self):
  273. return "<ErrorHolder description=%r error=%r>" % (
  274. self.description, self.error[1])
  275. def run(self, result):
  276. """
  277. Run the test, reporting the error.
  278. @param result: The C{TestResult} to store the results in.
  279. @type result: L{twisted.trial.itrial.IReporter}.
  280. """
  281. result.startTest(self)
  282. result.addError(self, self.error)
  283. result.stopTest(self)
  284. class TestLoader(object):
  285. """
  286. I find tests inside function, modules, files -- whatever -- then return
  287. them wrapped inside a Test (either a L{TestSuite} or a L{TestCase}).
  288. @ivar methodPrefix: A string prefix. C{TestLoader} will assume that all the
  289. methods in a class that begin with C{methodPrefix} are test cases.
  290. @ivar modulePrefix: A string prefix. Every module in a package that begins
  291. with C{modulePrefix} is considered a module full of tests.
  292. @ivar forceGarbageCollection: A flag applied to each C{TestCase} loaded.
  293. See L{unittest.TestCase} for more information.
  294. @ivar sorter: A key function used to sort C{TestCase}s, test classes,
  295. modules and packages.
  296. @ivar suiteFactory: A callable which is passed a list of tests (which
  297. themselves may be suites of tests). Must return a test suite.
  298. """
  299. methodPrefix = 'test'
  300. modulePrefix = 'test_'
  301. def __init__(self):
  302. self.suiteFactory = TestSuite
  303. self.sorter = name
  304. self._importErrors = []
  305. def sort(self, xs):
  306. """
  307. Sort the given things using L{sorter}.
  308. @param xs: A list of test cases, class or modules.
  309. """
  310. return sorted(xs, key=self.sorter)
  311. def findTestClasses(self, module):
  312. """Given a module, return all Trial test classes"""
  313. classes = []
  314. for name, val in inspect.getmembers(module):
  315. if isTestCase(val):
  316. classes.append(val)
  317. return self.sort(classes)
  318. def findByName(self, name):
  319. """
  320. Return a Python object given a string describing it.
  321. @param name: a string which may be either a filename or a
  322. fully-qualified Python name.
  323. @return: If C{name} is a filename, return the module. If C{name} is a
  324. fully-qualified Python name, return the object it refers to.
  325. """
  326. if os.path.exists(name):
  327. return filenameToModule(name)
  328. return reflect.namedAny(name)
  329. def loadModule(self, module):
  330. """
  331. Return a test suite with all the tests from a module.
  332. Included are TestCase subclasses and doctests listed in the module's
  333. __doctests__ module. If that's not good for you, put a function named
  334. either C{testSuite} or C{test_suite} in your module that returns a
  335. TestSuite, and I'll use the results of that instead.
  336. If C{testSuite} and C{test_suite} are both present, then I'll use
  337. C{testSuite}.
  338. """
  339. ## XXX - should I add an optional parameter to disable the check for
  340. ## a custom suite.
  341. ## OR, should I add another method
  342. if not isinstance(module, types.ModuleType):
  343. raise TypeError("%r is not a module" % (module,))
  344. if hasattr(module, 'testSuite'):
  345. return module.testSuite()
  346. elif hasattr(module, 'test_suite'):
  347. return module.test_suite()
  348. suite = self.suiteFactory()
  349. for testClass in self.findTestClasses(module):
  350. suite.addTest(self.loadClass(testClass))
  351. if not hasattr(module, '__doctests__'):
  352. return suite
  353. docSuite = self.suiteFactory()
  354. for docTest in module.__doctests__:
  355. docSuite.addTest(self.loadDoctests(docTest))
  356. return self.suiteFactory([suite, docSuite])
  357. loadTestsFromModule = loadModule
  358. def loadClass(self, klass):
  359. """
  360. Given a class which contains test cases, return a sorted list of
  361. C{TestCase} instances.
  362. """
  363. if not (isinstance(klass, type) or isinstance(klass, types.ClassType)):
  364. raise TypeError("%r is not a class" % (klass,))
  365. if not isTestCase(klass):
  366. raise ValueError("%r is not a test case" % (klass,))
  367. names = self.getTestCaseNames(klass)
  368. tests = self.sort([self._makeCase(klass, self.methodPrefix+name)
  369. for name in names])
  370. return self.suiteFactory(tests)
  371. loadTestsFromTestCase = loadClass
  372. def getTestCaseNames(self, klass):
  373. """
  374. Given a class that contains C{TestCase}s, return a list of names of
  375. methods that probably contain tests.
  376. """
  377. return reflect.prefixedMethodNames(klass, self.methodPrefix)
  378. def loadMethod(self, method):
  379. """
  380. Given a method of a C{TestCase} that represents a test, return a
  381. C{TestCase} instance for that test.
  382. """
  383. if not isinstance(method, types.MethodType):
  384. raise TypeError("%r not a method" % (method,))
  385. return self._makeCase(method.im_class, _getMethodNameInClass(method))
  386. def _makeCase(self, klass, methodName):
  387. return klass(methodName)
  388. def loadPackage(self, package, recurse=False):
  389. """
  390. Load tests from a module object representing a package, and return a
  391. TestSuite containing those tests.
  392. Tests are only loaded from modules whose name begins with 'test_'
  393. (or whatever C{modulePrefix} is set to).
  394. @param package: a types.ModuleType object (or reasonable facsimile
  395. obtained by importing) which may contain tests.
  396. @param recurse: A boolean. If True, inspect modules within packages
  397. within the given package (and so on), otherwise, only inspect modules
  398. in the package itself.
  399. @raise: TypeError if 'package' is not a package.
  400. @return: a TestSuite created with my suiteFactory, containing all the
  401. tests.
  402. """
  403. if not isPackage(package):
  404. raise TypeError("%r is not a package" % (package,))
  405. pkgobj = modules.getModule(package.__name__)
  406. if recurse:
  407. discovery = pkgobj.walkModules()
  408. else:
  409. discovery = pkgobj.iterModules()
  410. discovered = []
  411. for disco in discovery:
  412. if disco.name.split(".")[-1].startswith(self.modulePrefix):
  413. discovered.append(disco)
  414. suite = self.suiteFactory()
  415. for modinfo in self.sort(discovered):
  416. try:
  417. module = modinfo.load()
  418. except:
  419. thingToAdd = ErrorHolder(modinfo.name, failure.Failure())
  420. else:
  421. thingToAdd = self.loadModule(module)
  422. suite.addTest(thingToAdd)
  423. return suite
  424. def loadDoctests(self, module):
  425. """
  426. Return a suite of tests for all the doctests defined in C{module}.
  427. @param module: A module object or a module name.
  428. """
  429. if isinstance(module, str):
  430. try:
  431. module = reflect.namedAny(module)
  432. except:
  433. return ErrorHolder(module, failure.Failure())
  434. if not inspect.ismodule(module):
  435. warnings.warn("trial only supports doctesting modules")
  436. return
  437. extraArgs = {}
  438. # Work around Python issue2604: DocTestCase.tearDown clobbers globs
  439. def saveGlobals(test):
  440. """
  441. Save C{test.globs} and replace it with a copy so that if
  442. necessary, the original will be available for the next test
  443. run.
  444. """
  445. test._savedGlobals = getattr(test, '_savedGlobals', test.globs)
  446. test.globs = test._savedGlobals.copy()
  447. extraArgs['setUp'] = saveGlobals
  448. return doctest.DocTestSuite(module, **extraArgs)
  449. def loadAnything(self, thing, recurse=False, parent=None, qualName=None):
  450. """
  451. Given a Python object, return whatever tests that are in it. Whatever
  452. 'in' might mean.
  453. @param thing: A Python object. A module, method, class or package.
  454. @param recurse: Whether or not to look in subpackages of packages.
  455. Defaults to False.
  456. @param parent: For compatibility with the Python 3 loader, does
  457. nothing.
  458. @param qualname: For compatibility with the Python 3 loader, does
  459. nothing.
  460. @return: A C{TestCase} or C{TestSuite}.
  461. """
  462. if isinstance(thing, types.ModuleType):
  463. if isPackage(thing):
  464. return self.loadPackage(thing, recurse)
  465. return self.loadModule(thing)
  466. elif isinstance(thing, types.ClassType):
  467. return self.loadClass(thing)
  468. elif isinstance(thing, type):
  469. return self.loadClass(thing)
  470. elif isinstance(thing, types.MethodType):
  471. return self.loadMethod(thing)
  472. raise TypeError("No loader for %r. Unrecognized type" % (thing,))
  473. def loadByName(self, name, recurse=False):
  474. """
  475. Given a string representing a Python object, return whatever tests
  476. are in that object.
  477. If C{name} is somehow inaccessible (e.g. the module can't be imported,
  478. there is no Python object with that name etc) then return an
  479. L{ErrorHolder}.
  480. @param name: The fully-qualified name of a Python object.
  481. """
  482. try:
  483. thing = self.findByName(name)
  484. except:
  485. return ErrorHolder(name, failure.Failure())
  486. return self.loadAnything(thing, recurse)
  487. loadTestsFromName = loadByName
  488. def loadByNames(self, names, recurse=False):
  489. """
  490. Construct a TestSuite containing all the tests found in 'names', where
  491. names is a list of fully qualified python names and/or filenames. The
  492. suite returned will have no duplicate tests, even if the same object
  493. is named twice.
  494. """
  495. things = []
  496. errors = []
  497. for name in names:
  498. try:
  499. things.append(self.findByName(name))
  500. except:
  501. errors.append(ErrorHolder(name, failure.Failure()))
  502. suites = [self.loadAnything(thing, recurse)
  503. for thing in self._uniqueTests(things)]
  504. suites.extend(errors)
  505. return self.suiteFactory(suites)
  506. def _uniqueTests(self, things):
  507. """
  508. Gather unique suite objects from loaded things. This will guarantee
  509. uniqueness of inherited methods on TestCases which would otherwise hash
  510. to same value and collapse to one test unexpectedly if using simpler
  511. means: e.g. set().
  512. """
  513. seen = set()
  514. for thing in things:
  515. if isinstance(thing, types.MethodType):
  516. thing = (thing, thing.im_class)
  517. else:
  518. thing = (thing,)
  519. if thing not in seen:
  520. yield thing[0]
  521. seen.add(thing)
  522. class Py3TestLoader(TestLoader):
  523. """
  524. A test loader finds tests from the functions, modules, and files that is
  525. asked to and loads them into a L{TestSuite} or L{TestCase}.
  526. See L{TestLoader} for further details.
  527. """
  528. def loadFile(self, fileName, recurse=False):
  529. """
  530. Load a file, and then the tests in that file.
  531. @param fileName: The file name to load.
  532. @param recurse: A boolean. If True, inspect modules within packages
  533. within the given package (and so on), otherwise, only inspect
  534. modules in the package itself.
  535. """
  536. from importlib.machinery import SourceFileLoader
  537. name = reflect.filenameToModuleName(fileName)
  538. try:
  539. module = SourceFileLoader(name, fileName).load_module()
  540. return self.loadAnything(module, recurse=recurse)
  541. except OSError:
  542. raise ValueError("{} is not a Python file.".format(fileName))
  543. def findByName(self, _name, recurse=False):
  544. """
  545. Find and load tests, given C{name}.
  546. This partially duplicates the logic in C{unittest.loader.TestLoader}.
  547. @param name: The qualified name of the thing to load.
  548. @param recurse: A boolean. If True, inspect modules within packages
  549. within the given package (and so on), otherwise, only inspect
  550. modules in the package itself.
  551. """
  552. if os.sep in _name:
  553. # It's a file, try and get the module name for this file.
  554. name = reflect.filenameToModuleName(_name)
  555. try:
  556. # Try and import it, if it's on the path.
  557. # CAVEAT: If you have two twisteds, and you try and import the
  558. # one NOT on your path, it'll load the one on your path. But
  559. # that's silly, nobody should do that, and existing Trial does
  560. # that anyway.
  561. __import__(name)
  562. except ImportError:
  563. # If we can't import it, look for one NOT on the path.
  564. return self.loadFile(_name, recurse=recurse)
  565. else:
  566. name = _name
  567. obj = parent = remaining = None
  568. for searchName, remainingName in _qualNameWalker(name):
  569. # Walk down the qualified name, trying to import a module. For
  570. # example, `twisted.test.test_paths.FilePathTests` would try
  571. # the full qualified name, then just up to test_paths, and then
  572. # just up to test, and so forth.
  573. # This gets us the highest level thing which is a module.
  574. try:
  575. obj = reflect.namedModule(searchName)
  576. # If we reach here, we have successfully found a module.
  577. # obj will be the module, and remaining will be the remaining
  578. # part of the qualified name.
  579. remaining = remainingName
  580. break
  581. except ImportError:
  582. # Check to see where the ImportError happened. If it happened
  583. # in this file, ignore it.
  584. tb = sys.exc_info()[2]
  585. # Walk down to the deepest frame, where it actually happened.
  586. while tb.tb_next is not None:
  587. tb = tb.tb_next
  588. # Get the filename that the ImportError originated in.
  589. filenameWhereHappened = tb.tb_frame.f_code.co_filename
  590. # If it originated in the reflect file, then it's because it
  591. # doesn't exist. If it originates elsewhere, it's because an
  592. # ImportError happened in a module that does exist.
  593. if filenameWhereHappened != reflect.__file__:
  594. raise
  595. if remaining == "":
  596. raise reflect.ModuleNotFound(
  597. "The module {} does not exist.".format(name)
  598. )
  599. if obj is None:
  600. # If it's none here, we didn't get to import anything.
  601. # Try something drastic.
  602. obj = reflect.namedAny(name)
  603. remaining = name.split(".")[len(".".split(obj.__name__))+1:]
  604. try:
  605. for part in remaining:
  606. # Walk down the remaining modules. Hold on to the parent for
  607. # methods, as on Python 3, you can no longer get the parent
  608. # class from just holding onto the method.
  609. parent, obj = obj, getattr(obj, part)
  610. except AttributeError:
  611. raise AttributeError("{} does not exist.".format(name))
  612. return self.loadAnything(obj, parent=parent, qualName=remaining,
  613. recurse=recurse)
  614. def loadAnything(self, obj, recurse=False, parent=None, qualName=None):
  615. """
  616. Load absolutely anything (as long as that anything is a module,
  617. package, class, or method (with associated parent class and qualname).
  618. @param obj: The object to load.
  619. @param recurse: A boolean. If True, inspect modules within packages
  620. within the given package (and so on), otherwise, only inspect
  621. modules in the package itself.
  622. @param parent: If C{obj} is a method, this is the parent class of the
  623. method. C{qualName} is also required.
  624. @param qualName: If C{obj} is a method, this a list containing is the
  625. qualified name of the method. C{parent} is also required.
  626. """
  627. if isinstance(obj, types.ModuleType):
  628. # It looks like a module
  629. if isPackage(obj):
  630. # It's a package, so recurse down it.
  631. return self.loadPackage(obj, recurse=recurse)
  632. # Otherwise get all the tests in the module.
  633. return self.loadTestsFromModule(obj)
  634. elif isinstance(obj, type) and issubclass(obj, pyunit.TestCase):
  635. # We've found a raw test case, get the tests from it.
  636. return self.loadTestsFromTestCase(obj)
  637. elif (isinstance(obj, types.FunctionType) and
  638. isinstance(parent, type) and
  639. issubclass(parent, pyunit.TestCase)):
  640. # We've found a method, and its parent is a TestCase. Instantiate
  641. # it with the name of the method we want.
  642. name = qualName[-1]
  643. inst = parent(name)
  644. # Sanity check to make sure that the method we have got from the
  645. # test case is the same one as was passed in. This doesn't actually
  646. # use the function we passed in, because reasons.
  647. assert getattr(inst, inst._testMethodName).__func__ == obj
  648. return inst
  649. elif isinstance(obj, TestSuite):
  650. # We've found a test suite.
  651. return obj
  652. else:
  653. raise TypeError("don't know how to make test from: %s" % (obj,))
  654. def loadByName(self, name, recurse=False):
  655. """
  656. Load some tests by name.
  657. @param name: The qualified name for the test to load.
  658. @param recurse: A boolean. If True, inspect modules within packages
  659. within the given package (and so on), otherwise, only inspect
  660. modules in the package itself.
  661. """
  662. try:
  663. return self.suiteFactory([self.findByName(name, recurse=recurse)])
  664. except:
  665. return self.suiteFactory([ErrorHolder(name, failure.Failure())])
  666. def loadByNames(self, names, recurse=False):
  667. """
  668. Load some tests by a list of names.
  669. @param names: A L{list} of qualified names.
  670. @param recurse: A boolean. If True, inspect modules within packages
  671. within the given package (and so on), otherwise, only inspect
  672. modules in the package itself.
  673. """
  674. things = []
  675. errors = []
  676. for name in names:
  677. try:
  678. things.append(self.loadByName(name, recurse=recurse))
  679. except:
  680. errors.append(ErrorHolder(name, failure.Failure()))
  681. things.extend(errors)
  682. return self.suiteFactory(self._uniqueTests(things))
  683. def loadClass(self, klass):
  684. """
  685. Given a class which contains test cases, return a list of L{TestCase}s.
  686. @param klass: The class to load tests from.
  687. """
  688. if not isinstance(klass, type):
  689. raise TypeError("%r is not a class" % (klass,))
  690. if not isTestCase(klass):
  691. raise ValueError("%r is not a test case" % (klass,))
  692. names = self.getTestCaseNames(klass)
  693. tests = self.sort([self._makeCase(klass, self.methodPrefix+name)
  694. for name in names])
  695. return self.suiteFactory(tests)
  696. def loadMethod(self, method):
  697. raise NotImplementedError("Can't happen on Py3")
  698. def _uniqueTests(self, things):
  699. """
  700. Gather unique suite objects from loaded things. This will guarantee
  701. uniqueness of inherited methods on TestCases which would otherwise hash
  702. to same value and collapse to one test unexpectedly if using simpler
  703. means: e.g. set().
  704. """
  705. seen = set()
  706. for testthing in things:
  707. testthings = testthing._tests
  708. for thing in testthings:
  709. # This is horrible.
  710. if str(thing) not in seen:
  711. yield thing
  712. seen.add(str(thing))
  713. def _qualNameWalker(qualName):
  714. """
  715. Given a Python qualified name, this function yields a 2-tuple of the most
  716. specific qualified name first, followed by the next-most-specific qualified
  717. name, and so on, paired with the remainder of the qualified name.
  718. @param qualName: A Python qualified name.
  719. @type qualName: L{str}
  720. """
  721. # Yield what we were just given
  722. yield (qualName, [])
  723. # If they want more, split the qualified name up
  724. qualParts = qualName.split(".")
  725. for index in range(1, len(qualParts)):
  726. # This code here will produce, from the example walker.texas.ranger:
  727. # (walker.texas, ["ranger"])
  728. # (walker, ["texas", "ranger"])
  729. yield (".".join(qualParts[:-index]), qualParts[-index:])
  730. if _PY3:
  731. del TestLoader
  732. TestLoader = Py3TestLoader
  733. class TrialRunner(object):
  734. """
  735. A specialised runner that the trial front end uses.
  736. """
  737. DEBUG = 'debug'
  738. DRY_RUN = 'dry-run'
  739. def _setUpTestdir(self):
  740. self._tearDownLogFile()
  741. currentDir = os.getcwd()
  742. base = filepath.FilePath(self.workingDirectory)
  743. testdir, self._testDirLock = util._unusedTestDirectory(base)
  744. os.chdir(testdir.path)
  745. return currentDir
  746. def _tearDownTestdir(self, oldDir):
  747. os.chdir(oldDir)
  748. self._testDirLock.unlock()
  749. _log = log
  750. def _makeResult(self):
  751. reporter = self.reporterFactory(self.stream, self.tbformat,
  752. self.rterrors, self._log)
  753. if self._exitFirst:
  754. reporter = _ExitWrapper(reporter)
  755. if self.uncleanWarnings:
  756. reporter = UncleanWarningsReporterWrapper(reporter)
  757. return reporter
  758. def __init__(self, reporterFactory,
  759. mode=None,
  760. logfile='test.log',
  761. stream=sys.stdout,
  762. profile=False,
  763. tracebackFormat='default',
  764. realTimeErrors=False,
  765. uncleanWarnings=False,
  766. workingDirectory=None,
  767. forceGarbageCollection=False,
  768. debugger=None,
  769. exitFirst=False):
  770. self.reporterFactory = reporterFactory
  771. self.logfile = logfile
  772. self.mode = mode
  773. self.stream = stream
  774. self.tbformat = tracebackFormat
  775. self.rterrors = realTimeErrors
  776. self.uncleanWarnings = uncleanWarnings
  777. self._result = None
  778. self.workingDirectory = workingDirectory or '_trial_temp'
  779. self._logFileObserver = None
  780. self._logFileObject = None
  781. self._forceGarbageCollection = forceGarbageCollection
  782. self.debugger = debugger
  783. self._exitFirst = exitFirst
  784. if profile:
  785. self.run = util.profiled(self.run, 'profile.data')
  786. def _tearDownLogFile(self):
  787. if self._logFileObserver is not None:
  788. log.removeObserver(self._logFileObserver.emit)
  789. self._logFileObserver = None
  790. if self._logFileObject is not None:
  791. self._logFileObject.close()
  792. self._logFileObject = None
  793. def _setUpLogFile(self):
  794. self._tearDownLogFile()
  795. if self.logfile == '-':
  796. logFile = sys.stdout
  797. else:
  798. logFile = open(self.logfile, 'a')
  799. self._logFileObject = logFile
  800. self._logFileObserver = log.FileLogObserver(logFile)
  801. log.startLoggingWithObserver(self._logFileObserver.emit, 0)
  802. def run(self, test):
  803. """
  804. Run the test or suite and return a result object.
  805. """
  806. test = unittest.decorate(test, ITestCase)
  807. return self._runWithoutDecoration(test, self._forceGarbageCollection)
  808. def _runWithoutDecoration(self, test, forceGarbageCollection=False):
  809. """
  810. Private helper that runs the given test but doesn't decorate it.
  811. """
  812. result = self._makeResult()
  813. # decorate the suite with reactor cleanup and log starting
  814. # This should move out of the runner and be presumed to be
  815. # present
  816. suite = TrialSuite([test], forceGarbageCollection)
  817. startTime = time.time()
  818. if self.mode == self.DRY_RUN:
  819. for single in _iterateTests(suite):
  820. result.startTest(single)
  821. result.addSuccess(single)
  822. result.stopTest(single)
  823. else:
  824. if self.mode == self.DEBUG:
  825. run = lambda: self.debugger.runcall(suite.run, result)
  826. else:
  827. run = lambda: suite.run(result)
  828. oldDir = self._setUpTestdir()
  829. try:
  830. self._setUpLogFile()
  831. run()
  832. finally:
  833. self._tearDownLogFile()
  834. self._tearDownTestdir(oldDir)
  835. endTime = time.time()
  836. done = getattr(result, 'done', None)
  837. if done is None:
  838. warnings.warn(
  839. "%s should implement done() but doesn't. Falling back to "
  840. "printErrors() and friends." % reflect.qual(result.__class__),
  841. category=DeprecationWarning, stacklevel=3)
  842. result.printErrors()
  843. result.writeln(result.separator)
  844. result.writeln('Ran %d tests in %.3fs', result.testsRun,
  845. endTime - startTime)
  846. result.write('\n')
  847. result.printSummary()
  848. else:
  849. result.done()
  850. return result
  851. def runUntilFailure(self, test):
  852. """
  853. Repeatedly run C{test} until it fails.
  854. """
  855. count = 0
  856. while True:
  857. count += 1
  858. self.stream.write("Test Pass %d\n" % (count,))
  859. if count == 1:
  860. result = self.run(test)
  861. else:
  862. result = self._runWithoutDecoration(test)
  863. if result.testsRun == 0:
  864. break
  865. if not result.wasSuccessful():
  866. break
  867. return result