util.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. import sys, os
  2. import win32api
  3. import tempfile
  4. import unittest
  5. import gc
  6. import pywintypes
  7. import pythoncom
  8. import winerror
  9. from pythoncom import _GetInterfaceCount, _GetGatewayCount
  10. import win32com
  11. import logging
  12. import winreg
  13. import io as StringIO
  14. import pywin32_testutil
  15. from pywin32_testutil import TestLoader, TestResult, TestRunner, LeakTestCase
  16. def CheckClean():
  17. # Ensure no lingering exceptions - Python should have zero outstanding
  18. # COM objects
  19. try:
  20. sys.exc_clear()
  21. except AttributeError:
  22. pass # py3k
  23. c = _GetInterfaceCount()
  24. if c:
  25. print("Warning - %d com interface objects still alive" % c)
  26. c = _GetGatewayCount()
  27. if c:
  28. print("Warning - %d com gateway objects still alive" % c)
  29. def RegisterPythonServer(filename, progids=None, verbose=0):
  30. if progids:
  31. if isinstance(progids, str):
  32. progids = [progids]
  33. # we know the CLSIDs we need, but we might not be an admin user
  34. # and otherwise unable to register them. So as long as the progids
  35. # exist and the DLL points at our version, assume it already is.
  36. why_not = None
  37. for progid in progids:
  38. try:
  39. clsid = pywintypes.IID(progid)
  40. except pythoncom.com_error:
  41. # not registered.
  42. break
  43. try:
  44. HKCR = winreg.HKEY_CLASSES_ROOT
  45. hk = winreg.OpenKey(HKCR, "CLSID\\%s" % clsid)
  46. dll = winreg.QueryValue(hk, "InprocServer32")
  47. except WindowsError:
  48. # no CLSID or InProcServer32 - not registered
  49. break
  50. ok_files = [os.path.basename(pythoncom.__file__),
  51. 'pythoncomloader%d%d.dll' % (sys.version_info[0], sys.version_info[1])]
  52. if os.path.basename(dll) not in ok_files:
  53. why_not = "%r is registered against a different Python version (%s)" % (progid, dll)
  54. break
  55. else:
  56. #print "Skipping registration of '%s' - already registered" % filename
  57. return
  58. # needs registration - see if its likely!
  59. try:
  60. from win32com.shell.shell import IsUserAnAdmin
  61. except ImportError:
  62. print("Can't import win32com.shell - no idea if you are an admin or not?")
  63. is_admin = False
  64. else:
  65. try:
  66. is_admin = IsUserAnAdmin()
  67. except pythoncom.com_error:
  68. # old, less-secure OS - assume *is* admin.
  69. is_admin = True
  70. if not is_admin:
  71. msg = "%r isn't registered, but I'm not an administrator who can register it." % progids[0]
  72. if why_not:
  73. msg += "\n(registration check failed as %s)" % why_not
  74. # throw a normal "class not registered" exception - we don't report
  75. # them the same way as "real" errors.
  76. raise pythoncom.com_error(winerror.CO_E_CLASSSTRING, msg, None, -1)
  77. # so theoretically we are able to register it.
  78. cmd = '%s "%s" --unattended > nul 2>&1' % (win32api.GetModuleFileName(0), filename)
  79. if verbose:
  80. print("Registering engine", filename)
  81. # print cmd
  82. rc = os.system(cmd)
  83. if rc:
  84. print("Registration command was:")
  85. print(cmd)
  86. raise RuntimeError("Registration of engine '%s' failed" % filename)
  87. def ExecuteShellCommand(cmd, testcase,
  88. expected_output = None, # Set to '' to check for nothing
  89. tracebacks_ok = 0, # OK if the output contains a t/b?
  90. ):
  91. output_name = tempfile.mktemp('win32com_test')
  92. cmd = cmd + ' > "%s" 2>&1' % output_name
  93. rc = os.system(cmd)
  94. output = open(output_name, "r").read().strip()
  95. os.remove(output_name)
  96. class Failed(Exception): pass
  97. try:
  98. if rc:
  99. raise Failed("exit code was " + str(rc))
  100. if expected_output is not None and output != expected_output:
  101. raise Failed("Expected output %r (got %r)" % (expected_output, output))
  102. if not tracebacks_ok and \
  103. output.find("Traceback (most recent call last)")>=0:
  104. raise Failed("traceback in program output")
  105. return output
  106. except Failed as why:
  107. print("Failed to exec command '%r'" % cmd)
  108. print("Failed as", why)
  109. print("** start of program output **")
  110. print(output)
  111. print("** end of program output **")
  112. testcase.fail("Executing '%s' failed as %s" % (cmd, why))
  113. def assertRaisesCOM_HRESULT(testcase, hresult, func, *args, **kw):
  114. try:
  115. func(*args, **kw)
  116. except pythoncom.com_error as details:
  117. if details.hresult==hresult:
  118. return
  119. testcase.fail("Excepected COM exception with HRESULT 0x%x" % hresult)
  120. class CaptureWriter:
  121. def __init__(self):
  122. self.old_err = self.old_out = None
  123. self.clear()
  124. def capture(self):
  125. self.clear()
  126. self.old_out = sys.stdout
  127. self.old_err = sys.stderr
  128. sys.stdout = sys.stderr = self
  129. def release(self):
  130. if self.old_out:
  131. sys.stdout = self.old_out
  132. self.old_out = None
  133. if self.old_err:
  134. sys.stderr = self.old_err
  135. self.old_err = None
  136. def clear(self):
  137. self.captured = []
  138. def write(self, msg):
  139. self.captured.append(msg)
  140. def get_captured(self):
  141. return "".join(self.captured)
  142. def get_num_lines_captured(self):
  143. return len("".join(self.captured).split("\n"))
  144. # Utilities to set the win32com logger to something what just captures
  145. # records written and doesn't print them.
  146. class LogHandler(logging.Handler):
  147. def __init__(self):
  148. self.emitted = []
  149. logging.Handler.__init__(self)
  150. def emit(self, record):
  151. self.emitted.append(record)
  152. _win32com_logger = None
  153. def setup_test_logger():
  154. old_log = getattr(win32com, "logger", None)
  155. global _win32com_logger
  156. if _win32com_logger is None:
  157. _win32com_logger = logging.Logger('test')
  158. handler = LogHandler()
  159. _win32com_logger.addHandler(handler)
  160. win32com.logger = _win32com_logger
  161. handler = _win32com_logger.handlers[0]
  162. handler.emitted = []
  163. return handler.emitted, old_log
  164. def restore_test_logger(prev_logger):
  165. assert prev_logger is None, "who needs this?"
  166. if prev_logger is None:
  167. del win32com.logger
  168. else:
  169. win32com.logger = prev_logger
  170. # We used to override some of this (and may later!)
  171. TestCase = unittest.TestCase
  172. def CapturingFunctionTestCase(*args, **kw):
  173. real_test = _CapturingFunctionTestCase(*args, **kw)
  174. return LeakTestCase(real_test)
  175. class _CapturingFunctionTestCase(unittest.FunctionTestCase):#, TestCaseMixin):
  176. def __call__(self, result=None):
  177. if result is None: result = self.defaultTestResult()
  178. writer = CaptureWriter()
  179. #self._preTest()
  180. writer.capture()
  181. try:
  182. unittest.FunctionTestCase.__call__(self, result)
  183. if getattr(self, "do_leak_tests", 0) and hasattr(sys, "gettotalrefcount"):
  184. self.run_leak_tests(result)
  185. finally:
  186. writer.release()
  187. #self._postTest(result)
  188. output = writer.get_captured()
  189. self.checkOutput(output, result)
  190. if result.showAll:
  191. print(output)
  192. def checkOutput(self, output, result):
  193. if output.find("Traceback")>=0:
  194. msg = "Test output contained a traceback\n---\n%s\n---" % output
  195. result.errors.append((self, msg))
  196. class ShellTestCase(unittest.TestCase):
  197. def __init__(self, cmd, expected_output):
  198. self.__cmd = cmd
  199. self.__eo = expected_output
  200. unittest.TestCase.__init__(self)
  201. def runTest(self):
  202. ExecuteShellCommand(self.__cmd, self, self.__eo)
  203. def __str__(self):
  204. max = 30
  205. if len(self.__cmd)>max:
  206. cmd_repr = self.__cmd[:max] + "..."
  207. else:
  208. cmd_repr = self.__cmd
  209. return "exec: " + cmd_repr
  210. def testmain(*args, **kw):
  211. pywin32_testutil.testmain(*args, **kw)
  212. CheckClean()