PageRenderTime 23ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/ctypes/test/__init__.py

https://github.com/jdhardy/ironpython
Python | 208 lines | 198 code | 3 blank | 7 comment | 0 complexity | 3091bd60458317c128af6f5db2618bfc MD5 | raw file
  1. import os, sys, unittest, getopt, time
  2. use_resources = []
  3. class ResourceDenied(Exception):
  4. """Test skipped because it requested a disallowed resource.
  5. This is raised when a test calls requires() for a resource that
  6. has not be enabled. Resources are defined by test modules.
  7. """
  8. def is_resource_enabled(resource):
  9. """Test whether a resource is enabled.
  10. If the caller's module is __main__ then automatically return True."""
  11. if sys._getframe().f_back.f_globals.get("__name__") == "__main__":
  12. return True
  13. result = use_resources is not None and \
  14. (resource in use_resources or "*" in use_resources)
  15. if not result:
  16. _unavail[resource] = None
  17. return result
  18. _unavail = {}
  19. def requires(resource, msg=None):
  20. """Raise ResourceDenied if the specified resource is not available.
  21. If the caller's module is __main__ then automatically return True."""
  22. # see if the caller's module is __main__ - if so, treat as if
  23. # the resource was set
  24. if sys._getframe().f_back.f_globals.get("__name__") == "__main__":
  25. return
  26. if not is_resource_enabled(resource):
  27. if msg is None:
  28. msg = "Use of the `%s' resource not enabled" % resource
  29. raise ResourceDenied(msg)
  30. def find_package_modules(package, mask):
  31. import fnmatch
  32. if (hasattr(package, "__loader__") and
  33. hasattr(package.__loader__, '_files')):
  34. path = package.__name__.replace(".", os.path.sep)
  35. mask = os.path.join(path, mask)
  36. for fnm in package.__loader__._files.iterkeys():
  37. if fnmatch.fnmatchcase(fnm, mask):
  38. yield os.path.splitext(fnm)[0].replace(os.path.sep, ".")
  39. else:
  40. path = package.__path__[0]
  41. for fnm in os.listdir(path):
  42. if fnmatch.fnmatchcase(fnm, mask):
  43. yield "%s.%s" % (package.__name__, os.path.splitext(fnm)[0])
  44. def get_tests(package, mask, verbosity, exclude=()):
  45. """Return a list of skipped test modules, and a list of test cases."""
  46. tests = []
  47. skipped = []
  48. for modname in find_package_modules(package, mask):
  49. if modname.split(".")[-1] in exclude:
  50. skipped.append(modname)
  51. if verbosity > 1:
  52. print >> sys.stderr, "Skipped %s: excluded" % modname
  53. continue
  54. try:
  55. mod = __import__(modname, globals(), locals(), ['*'])
  56. except ResourceDenied, detail:
  57. skipped.append(modname)
  58. if verbosity > 1:
  59. print >> sys.stderr, "Skipped %s: %s" % (modname, detail)
  60. continue
  61. for name in dir(mod):
  62. if name.startswith("_"):
  63. continue
  64. o = getattr(mod, name)
  65. if type(o) is type(unittest.TestCase) and issubclass(o, unittest.TestCase):
  66. tests.append(o)
  67. return skipped, tests
  68. def usage():
  69. print __doc__
  70. return 1
  71. def test_with_refcounts(runner, verbosity, testcase):
  72. """Run testcase several times, tracking reference counts."""
  73. import gc
  74. import ctypes
  75. ptc = ctypes._pointer_type_cache.copy()
  76. cfc = ctypes._c_functype_cache.copy()
  77. wfc = ctypes._win_functype_cache.copy()
  78. # when searching for refcount leaks, we have to manually reset any
  79. # caches that ctypes has.
  80. def cleanup():
  81. ctypes._pointer_type_cache = ptc.copy()
  82. ctypes._c_functype_cache = cfc.copy()
  83. ctypes._win_functype_cache = wfc.copy()
  84. gc.collect()
  85. test = unittest.makeSuite(testcase)
  86. for i in range(5):
  87. rc = sys.gettotalrefcount()
  88. runner.run(test)
  89. cleanup()
  90. COUNT = 5
  91. refcounts = [None] * COUNT
  92. for i in range(COUNT):
  93. rc = sys.gettotalrefcount()
  94. runner.run(test)
  95. cleanup()
  96. refcounts[i] = sys.gettotalrefcount() - rc
  97. if filter(None, refcounts):
  98. print "%s leaks:\n\t" % testcase, refcounts
  99. elif verbosity:
  100. print "%s: ok." % testcase
  101. class TestRunner(unittest.TextTestRunner):
  102. def run(self, test, skipped):
  103. "Run the given test case or test suite."
  104. # Same as unittest.TextTestRunner.run, except that it reports
  105. # skipped tests.
  106. result = self._makeResult()
  107. startTime = time.time()
  108. test(result)
  109. stopTime = time.time()
  110. timeTaken = stopTime - startTime
  111. result.printErrors()
  112. self.stream.writeln(result.separator2)
  113. run = result.testsRun
  114. if _unavail: #skipped:
  115. requested = _unavail.keys()
  116. requested.sort()
  117. self.stream.writeln("Ran %d test%s in %.3fs (%s module%s skipped)" %
  118. (run, run != 1 and "s" or "", timeTaken,
  119. len(skipped),
  120. len(skipped) != 1 and "s" or ""))
  121. self.stream.writeln("Unavailable resources: %s" % ", ".join(requested))
  122. else:
  123. self.stream.writeln("Ran %d test%s in %.3fs" %
  124. (run, run != 1 and "s" or "", timeTaken))
  125. self.stream.writeln()
  126. if not result.wasSuccessful():
  127. self.stream.write("FAILED (")
  128. failed, errored = map(len, (result.failures, result.errors))
  129. if failed:
  130. self.stream.write("failures=%d" % failed)
  131. if errored:
  132. if failed: self.stream.write(", ")
  133. self.stream.write("errors=%d" % errored)
  134. self.stream.writeln(")")
  135. else:
  136. self.stream.writeln("OK")
  137. return result
  138. def main(*packages):
  139. try:
  140. opts, args = getopt.getopt(sys.argv[1:], "rqvu:x:")
  141. except getopt.error:
  142. return usage()
  143. verbosity = 1
  144. search_leaks = False
  145. exclude = []
  146. for flag, value in opts:
  147. if flag == "-q":
  148. verbosity -= 1
  149. elif flag == "-v":
  150. verbosity += 1
  151. elif flag == "-r":
  152. try:
  153. sys.gettotalrefcount
  154. except AttributeError:
  155. print >> sys.stderr, "-r flag requires Python debug build"
  156. return -1
  157. search_leaks = True
  158. elif flag == "-u":
  159. use_resources.extend(value.split(","))
  160. elif flag == "-x":
  161. exclude.extend(value.split(","))
  162. mask = "test_*.py"
  163. if args:
  164. mask = args[0]
  165. for package in packages:
  166. run_tests(package, mask, verbosity, search_leaks, exclude)
  167. def run_tests(package, mask, verbosity, search_leaks, exclude):
  168. skipped, testcases = get_tests(package, mask, verbosity, exclude)
  169. runner = TestRunner(verbosity=verbosity)
  170. suites = [unittest.makeSuite(o) for o in testcases]
  171. suite = unittest.TestSuite(suites)
  172. result = runner.run(suite, skipped)
  173. if search_leaks:
  174. # hunt for refcount leaks
  175. runner = BasicTestRunner()
  176. for t in testcases:
  177. test_with_refcounts(runner, verbosity, t)
  178. return bool(result.errors)
  179. class BasicTestRunner:
  180. def run(self, test):
  181. result = unittest.TestResult()
  182. test(result)
  183. return result