runner.py 34 KB

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