testHost.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. import sys
  2. import pythoncom
  3. from win32com.axscript.server.error import Exception
  4. from win32com.axscript import axscript
  5. from win32com.axscript.server import axsite
  6. from win32com.server import util, connect
  7. import win32com.server.policy
  8. from win32com.client.dynamic import Dispatch
  9. from win32com.server.exception import COMException
  10. import unittest
  11. import win32com.test.util
  12. verbose = "-v" in sys.argv
  13. class MySite(axsite.AXSite):
  14. def __init__(self, *args):
  15. self.exception_seen = None
  16. axsite.AXSite.__init__(self, *args)
  17. def OnScriptError(self, error):
  18. self.exception_seen = exc = error.GetExceptionInfo()
  19. context, line, char = error.GetSourcePosition()
  20. if not verbose:
  21. return
  22. print(" >Exception:", exc[1])
  23. try:
  24. st = error.GetSourceLineText()
  25. except pythoncom.com_error:
  26. st = None
  27. if st is None: st = ""
  28. text = st + "\n" + (" " * (char-1)) + "^" + "\n" + exc[2]
  29. for line in text.splitlines():
  30. print(" >" + line)
  31. class MyCollection(util.Collection):
  32. def _NewEnum(self):
  33. return util.Collection._NewEnum(self)
  34. class Test:
  35. _public_methods_ = [ 'echo', 'fail' ]
  36. _public_attrs_ = ['collection']
  37. def __init__(self):
  38. self.verbose = verbose
  39. self.collection = util.wrap( MyCollection( [1,'Two',3] ))
  40. self.last = ""
  41. self.fail_called = 0
  42. # self._connect_server_ = TestConnectServer(self)
  43. def echo(self, *args):
  44. self.last = "".join([str(s) for s in args])
  45. if self.verbose:
  46. for arg in args:
  47. print(arg, end=' ')
  48. print()
  49. def fail(self, *args):
  50. print("**** fail() called ***")
  51. for arg in args:
  52. print(arg, end=' ')
  53. print()
  54. self.fail_called = 1
  55. # self._connect_server_.Broadcast(last)
  56. #### Connections currently wont work, as there is no way for the engine to
  57. #### know what events we support. We need typeinfo support.
  58. IID_ITestEvents = pythoncom.MakeIID("{8EB72F90-0D44-11d1-9C4B-00AA00125A98}")
  59. class TestConnectServer(connect.ConnectableServer):
  60. _connect_interfaces_ = [IID_ITestEvents]
  61. # The single public method that the client can call on us
  62. # (ie, as a normal COM server, this exposes just this single method.
  63. def __init__(self, object):
  64. self.object = object
  65. def Broadcast(self,arg):
  66. # Simply broadcast a notification.
  67. self._BroadcastNotify(self.NotifyDoneIt, (arg,))
  68. def NotifyDoneIt(self, interface, arg):
  69. interface.Invoke(1000, 0, pythoncom.DISPATCH_METHOD, 1, arg)
  70. VBScript = """\
  71. prop = "Property Value"
  72. sub hello(arg1)
  73. test.echo arg1
  74. end sub
  75. sub testcollection
  76. if test.collection.Item(0) <> 1 then
  77. test.fail("Index 0 was wrong")
  78. end if
  79. if test.collection.Item(1) <> "Two" then
  80. test.fail("Index 1 was wrong")
  81. end if
  82. if test.collection.Item(2) <> 3 then
  83. test.fail("Index 2 was wrong")
  84. end if
  85. num = 0
  86. for each item in test.collection
  87. num = num + 1
  88. next
  89. if num <> 3 then
  90. test.fail("Collection didn't have 3 items")
  91. end if
  92. end sub
  93. """
  94. PyScript = """\
  95. # A unicode \xa9omment.
  96. prop = "Property Value"
  97. def hello(arg1):
  98. test.echo(arg1)
  99. def testcollection():
  100. # test.collection[1] = "New one"
  101. got = []
  102. for item in test.collection:
  103. got.append(item)
  104. if got != [1, "Two", 3]:
  105. test.fail("Didn't get the collection")
  106. pass
  107. """
  108. # XXX - needs py3k work! Throwing a bytes string with an extended char
  109. # doesn't make much sense, but py2x allows it. What it gets upset with
  110. # is a real unicode arg - which is the only thing py3k allows!
  111. PyScript_Exc = """\
  112. def hello(arg1):
  113. raise RuntimeError("exc with extended \xa9har")
  114. """
  115. ErrScript = """\
  116. bad code for everyone!
  117. """
  118. state_map = {
  119. axscript.SCRIPTSTATE_UNINITIALIZED: "SCRIPTSTATE_UNINITIALIZED",
  120. axscript.SCRIPTSTATE_INITIALIZED: "SCRIPTSTATE_INITIALIZED",
  121. axscript.SCRIPTSTATE_STARTED: "SCRIPTSTATE_STARTED",
  122. axscript.SCRIPTSTATE_CONNECTED: "SCRIPTSTATE_CONNECTED",
  123. axscript.SCRIPTSTATE_DISCONNECTED: "SCRIPTSTATE_DISCONNECTED",
  124. axscript.SCRIPTSTATE_CLOSED: "SCRIPTSTATE_CLOSED",
  125. }
  126. def _CheckEngineState(engine, name, state):
  127. got = engine.engine.eScript.GetScriptState()
  128. if got != state:
  129. got_name = state_map.get(got, str(got))
  130. state_name = state_map.get(state, str(state))
  131. raise RuntimeError("Warning - engine %s has state %s, but expected %s" % (name, got_name, state_name))
  132. class EngineTester(win32com.test.util.TestCase):
  133. def _TestEngine(self, engineName, code, expected_exc = None):
  134. echoer = Test()
  135. model = {
  136. 'test' : util.wrap(echoer),
  137. }
  138. site = MySite(model)
  139. engine = site._AddEngine(engineName)
  140. try:
  141. _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED)
  142. engine.AddCode(code)
  143. engine.Start()
  144. _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_STARTED)
  145. self.failUnless(not echoer.fail_called, "Fail should not have been called")
  146. # Now call into the scripts IDispatch
  147. ob = Dispatch(engine.GetScriptDispatch())
  148. try:
  149. ob.hello("Goober")
  150. self.failUnless(expected_exc is None,
  151. "Expected %r, but no exception seen" % (expected_exc,))
  152. except pythoncom.com_error:
  153. if expected_exc is None:
  154. self.fail("Unexpected failure from script code: %s" % (site.exception_seen,))
  155. if expected_exc not in site.exception_seen[2]:
  156. self.fail("Could not find %r in %r" % (expected_exc, site.exception_seen[2]))
  157. return
  158. self.assertEqual(echoer.last, "Goober")
  159. self.assertEqual(str(ob.prop), "Property Value")
  160. ob.testcollection()
  161. self.failUnless(not echoer.fail_called, "Fail should not have been called")
  162. # Now make sure my engines can evaluate stuff.
  163. result = engine.eParse.ParseScriptText("1+1", None, None, None, 0, 0, axscript.SCRIPTTEXT_ISEXPRESSION)
  164. self.assertEqual(result, 2)
  165. # re-initialize to make sure it transitions back to initialized again.
  166. engine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED)
  167. _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED)
  168. engine.Start()
  169. _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_STARTED)
  170. # Transition back to initialized, then through connected too.
  171. engine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED)
  172. _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED)
  173. engine.SetScriptState(axscript.SCRIPTSTATE_CONNECTED)
  174. _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_CONNECTED)
  175. engine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED)
  176. _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED)
  177. engine.SetScriptState(axscript.SCRIPTSTATE_CONNECTED)
  178. _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_CONNECTED)
  179. engine.SetScriptState(axscript.SCRIPTSTATE_DISCONNECTED)
  180. _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_DISCONNECTED)
  181. finally:
  182. engine.Close()
  183. engine = None
  184. site = None
  185. def testVB(self):
  186. self._TestEngine("VBScript", VBScript)
  187. def testPython(self):
  188. self._TestEngine("Python", PyScript)
  189. def testPythonUnicodeError(self):
  190. self._TestEngine("Python", PyScript)
  191. def testVBExceptions(self):
  192. self.assertRaises(pythoncom.com_error,
  193. self._TestEngine, "VBScript", ErrScript)
  194. def testPythonExceptions(self):
  195. expected = "RuntimeError: exc with extended \xa9har"
  196. self._TestEngine("Python", PyScript_Exc, expected)
  197. if __name__ == '__main__':
  198. unittest.main()