testPyComTest.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. # NOTE - Still seems to be a leak here somewhere
  2. # gateway count doesnt hit zero. Hence the print statements!
  3. import sys; sys.coinit_flags=0 # Must be free-threaded!
  4. import win32api, pythoncom, time
  5. import pywintypes
  6. import os
  7. import winerror
  8. import win32com
  9. import win32com.client.connect
  10. from win32com.test.util import CheckClean
  11. from win32com.client import constants, DispatchBaseClass, CastTo, VARIANT
  12. from win32com.test.util import RegisterPythonServer
  13. from pywin32_testutil import str2memory
  14. import datetime
  15. import decimal
  16. import win32timezone
  17. importMsg = "**** PyCOMTest is not installed ***\n PyCOMTest is a Python test specific COM client and server.\n It is likely this server is not installed on this machine\n To install the server, you must get the win32com sources\n and build it using MS Visual C++"
  18. error = Exception
  19. # This test uses a Python implemented COM server - ensure correctly registered.
  20. RegisterPythonServer(os.path.join(os.path.dirname(__file__), '..', "servers", "test_pycomtest.py"),
  21. "Python.Test.PyCOMTest")
  22. from win32com.client import gencache
  23. try:
  24. gencache.EnsureModule('{6BCDCB60-5605-11D0-AE5F-CADD4C000000}', 0, 1, 1)
  25. except pythoncom.com_error:
  26. print("The PyCOMTest module can not be located or generated.")
  27. print(importMsg)
  28. raise RuntimeError(importMsg)
  29. # We had a bg where RegisterInterfaces would fail if gencache had
  30. # already been run - exercise that here
  31. from win32com import universal
  32. universal.RegisterInterfaces('{6BCDCB60-5605-11D0-AE5F-CADD4C000000}', 0, 1, 1)
  33. verbose = 0
  34. # convert a normal int to a long int - used to avoid, eg, '1L' for py3k
  35. # friendliness
  36. def ensure_long(int_val):
  37. if sys.version_info > (3,):
  38. # py3k - no such thing as a 'long'
  39. return int_val
  40. # on py2x, we just use an expression that results in a long
  41. return 0x100000000-0x100000000+int_val
  42. def check_get_set(func, arg):
  43. got = func(arg)
  44. if got != arg:
  45. raise error("%s failed - expected %r, got %r" % (func, arg, got))
  46. def check_get_set_raises(exc, func, arg):
  47. try:
  48. got = func(arg)
  49. except exc as e:
  50. pass # what we expect!
  51. else:
  52. raise error("%s with arg %r didn't raise %s - returned %r" % (func, arg, exc, got))
  53. def progress(*args):
  54. if verbose:
  55. for arg in args:
  56. print(arg, end=' ')
  57. print()
  58. def TestApplyResult(fn, args, result):
  59. try:
  60. fnName = str(fn).split()[1]
  61. except:
  62. fnName = str(fn)
  63. progress("Testing ", fnName)
  64. pref = "function " + fnName
  65. rc = fn(*args)
  66. if rc != result:
  67. raise error("%s failed - result not %r but %r" % (pref, result, rc))
  68. def TestConstant(constName, pyConst):
  69. try:
  70. comConst = getattr(constants, constName)
  71. except:
  72. raise error("Constant %s missing" % (constName,))
  73. if comConst != pyConst:
  74. raise error("Constant value wrong for %s - got %s, wanted %s" % (constName, comConst, pyConst))
  75. # Simple handler class. This demo only fires one event.
  76. class RandomEventHandler:
  77. def _Init(self):
  78. self.fireds = {}
  79. def OnFire(self, no):
  80. try:
  81. self.fireds[no] = self.fireds[no] + 1
  82. except KeyError:
  83. self.fireds[no] = 0
  84. def OnFireWithNamedParams(self, no, a_bool, out1, out2):
  85. # This test exists mainly to help with an old bug, where named
  86. # params would come in reverse.
  87. Missing = pythoncom.Missing
  88. if no is not Missing:
  89. # We know our impl called 'OnFire' with the same ID
  90. assert no in self.fireds
  91. assert no+1==out1, "expecting 'out1' param to be ID+1"
  92. assert no+2==out2, "expecting 'out2' param to be ID+2"
  93. # The middle must be a boolean.
  94. assert a_bool is Missing or type(a_bool)==bool, "middle param not a bool"
  95. return out1+2, out2+2
  96. def _DumpFireds(self):
  97. if not self.fireds:
  98. print("ERROR: Nothing was received!")
  99. for firedId, no in self.fireds.items():
  100. progress("ID %d fired %d times" % (firedId, no))
  101. # A simple handler class that derives from object (ie, a "new style class") -
  102. # only relevant for Python 2.x (ie, the 2 classes should be identical in 3.x)
  103. class NewStyleRandomEventHandler(object):
  104. def _Init(self):
  105. self.fireds = {}
  106. def OnFire(self, no):
  107. try:
  108. self.fireds[no] = self.fireds[no] + 1
  109. except KeyError:
  110. self.fireds[no] = 0
  111. def OnFireWithNamedParams(self, no, a_bool, out1, out2):
  112. # This test exists mainly to help with an old bug, where named
  113. # params would come in reverse.
  114. Missing = pythoncom.Missing
  115. if no is not Missing:
  116. # We know our impl called 'OnFire' with the same ID
  117. assert no in self.fireds
  118. assert no+1==out1, "expecting 'out1' param to be ID+1"
  119. assert no+2==out2, "expecting 'out2' param to be ID+2"
  120. # The middle must be a boolean.
  121. assert a_bool is Missing or type(a_bool)==bool, "middle param not a bool"
  122. return out1+2, out2+2
  123. def _DumpFireds(self):
  124. if not self.fireds:
  125. print("ERROR: Nothing was received!")
  126. for firedId, no in self.fireds.items():
  127. progress("ID %d fired %d times" % (firedId, no))
  128. # Test everything which can be tested using both the "dynamic" and "generated"
  129. # COM objects (or when there are very subtle differences)
  130. def TestCommon(o, is_generated):
  131. progress("Getting counter")
  132. counter = o.GetSimpleCounter()
  133. TestCounter(counter, is_generated)
  134. progress("Checking default args")
  135. rc = o.TestOptionals()
  136. if rc[:-1] != ("def", 0, 1) or abs(rc[-1]-3.14)>.01:
  137. print(rc)
  138. raise error("Did not get the optional values correctly")
  139. rc = o.TestOptionals("Hi", 2, 3, 1.1)
  140. if rc[:-1] != ("Hi", 2, 3) or abs(rc[-1]-1.1)>.01:
  141. print(rc)
  142. raise error("Did not get the specified optional values correctly")
  143. rc = o.TestOptionals2(0)
  144. if rc != (0, "", 1):
  145. print(rc)
  146. raise error("Did not get the optional2 values correctly")
  147. rc = o.TestOptionals2(1.1, "Hi", 2)
  148. if rc[1:] != ("Hi", 2) or abs(rc[0]-1.1)>.01:
  149. print(rc)
  150. raise error("Did not get the specified optional2 values correctly")
  151. progress("Checking getting/passing IUnknown")
  152. check_get_set(o.GetSetUnknown, o)
  153. progress("Checking getting/passing IDispatch")
  154. # This might be called with either the interface or the CoClass - but these
  155. # functions always return from the interface.
  156. expected_class = o.__class__
  157. # CoClass instances have `default_interface`
  158. expected_class = getattr(expected_class, "default_interface", expected_class)
  159. if not isinstance(o.GetSetDispatch(o), expected_class):
  160. raise error("GetSetDispatch failed: %r" % (o.GetSetDispatch(o),))
  161. progress("Checking getting/passing IDispatch of known type")
  162. expected_class = o.__class__
  163. expected_class = getattr(expected_class, "default_interface", expected_class)
  164. if o.GetSetInterface(o).__class__ != expected_class:
  165. raise error("GetSetDispatch failed")
  166. progress("Checking misc args")
  167. check_get_set(o.GetSetVariant, 4)
  168. check_get_set(o.GetSetVariant, "foo")
  169. check_get_set(o.GetSetVariant, o)
  170. # signed/unsigned.
  171. check_get_set(o.GetSetInt, 0)
  172. check_get_set(o.GetSetInt, -1)
  173. check_get_set(o.GetSetInt, 1)
  174. check_get_set(o.GetSetUnsignedInt, 0)
  175. check_get_set(o.GetSetUnsignedInt, 1)
  176. check_get_set(o.GetSetUnsignedInt, 0x80000000)
  177. if o.GetSetUnsignedInt(-1) != 0xFFFFFFFF:
  178. # -1 is a special case - we accept a negative int (silently converting to
  179. # unsigned) but when getting it back we convert it to a long.
  180. raise error("unsigned -1 failed")
  181. check_get_set(o.GetSetLong, 0)
  182. check_get_set(o.GetSetLong, -1)
  183. check_get_set(o.GetSetLong, 1)
  184. check_get_set(o.GetSetUnsignedLong, 0)
  185. check_get_set(o.GetSetUnsignedLong, 1)
  186. check_get_set(o.GetSetUnsignedLong, 0x80000000)
  187. # -1 is a special case - see above.
  188. if o.GetSetUnsignedLong(-1) != 0xFFFFFFFF:
  189. raise error("unsigned -1 failed")
  190. # We want to explicitly test > 32 bits. py3k has no 'maxint' and
  191. # 'maxsize+1' is no good on 64bit platforms as its 65 bits!
  192. big = 2147483647 # sys.maxint on py2k
  193. for l in big, big+1, 1 << 65:
  194. check_get_set(o.GetSetVariant, l)
  195. progress("Checking structs")
  196. r = o.GetStruct()
  197. assert r.int_value == 99 and str(r.str_value)=="Hello from C++"
  198. assert o.DoubleString("foo") == "foofoo"
  199. progress("Checking var args")
  200. o.SetVarArgs("Hi", "There", "From", "Python", 1)
  201. if o.GetLastVarArgs() != ("Hi", "There", "From", "Python", 1):
  202. raise error("VarArgs failed -" + str(o.GetLastVarArgs()))
  203. progress("Checking arrays")
  204. l=[]
  205. TestApplyResult(o.SetVariantSafeArray, (l,), len(l))
  206. l=[1,2,3,4]
  207. TestApplyResult(o.SetVariantSafeArray, (l,), len(l))
  208. TestApplyResult(o.CheckVariantSafeArray, ((1,2,3,4,),), 1)
  209. # and binary
  210. TestApplyResult(o.SetBinSafeArray, (str2memory('foo\0bar'),), 7)
  211. progress("Checking properties")
  212. o.LongProp = 3
  213. if o.LongProp != 3 or o.IntProp != 3:
  214. raise error("Property value wrong - got %d/%d" % (o.LongProp,o.IntProp))
  215. o.LongProp = o.IntProp = -3
  216. if o.LongProp != -3 or o.IntProp != -3:
  217. raise error("Property value wrong - got %d/%d" % (o.LongProp,o.IntProp))
  218. # This number fits in an unsigned long. Attempting to set it to a normal
  219. # long will involve overflow, which is to be expected. But we do
  220. # expect it to work in a property explicitly a VT_UI4.
  221. check = 3 *10 **9
  222. o.ULongProp = check
  223. if o.ULongProp != check:
  224. raise error("Property value wrong - got %d (expected %d)" % (o.ULongProp, check))
  225. TestApplyResult(o.Test, ("Unused", 99), 1) # A bool function
  226. TestApplyResult(o.Test, ("Unused", -1), 1) # A bool function
  227. TestApplyResult(o.Test, ("Unused", 1==1), 1) # A bool function
  228. TestApplyResult(o.Test, ("Unused", 0), 0)
  229. TestApplyResult(o.Test, ("Unused", 1==0), 0)
  230. assert o.DoubleString("foo") == "foofoo"
  231. TestConstant("ULongTest1", ensure_long(0xFFFFFFFF))
  232. TestConstant("ULongTest2", ensure_long(0x7FFFFFFF))
  233. TestConstant("LongTest1", ensure_long(-0x7FFFFFFF))
  234. TestConstant("LongTest2", ensure_long(0x7FFFFFFF))
  235. TestConstant("UCharTest", 255)
  236. TestConstant("CharTest", -1)
  237. # 'Hello World', but the 'r' is the "Registered" sign (\xae)
  238. TestConstant("StringTest", "Hello Wo\xaeld")
  239. progress("Checking dates and times")
  240. # For now *all* times passed must be tz-aware.
  241. now = win32timezone.now()
  242. # but conversion to and from a VARIANT loses sub-second...
  243. now = now.replace(microsecond=0)
  244. later = now + datetime.timedelta(seconds=1)
  245. TestApplyResult(o.EarliestDate, (now, later), now)
  246. # The below used to fail with `ValueError: microsecond must be in 0..999999` - see #1655
  247. # https://planetcalc.com/7027/ says that float is: Sun, 25 Mar 1951 7:23:49 am
  248. assert o.MakeDate(18712.308206013888) == datetime.datetime.fromisoformat("1951-03-25 07:23:49+00:00")
  249. progress("Checking currency")
  250. # currency.
  251. pythoncom.__future_currency__ = 1
  252. if o.CurrencyProp != 0:
  253. raise error("Expecting 0, got %r" % (o.CurrencyProp,))
  254. for val in ("1234.5678", "1234.56", "1234"):
  255. o.CurrencyProp = decimal.Decimal(val)
  256. if o.CurrencyProp != decimal.Decimal(val):
  257. raise error("%s got %r" % (val, o.CurrencyProp))
  258. v1 = decimal.Decimal("1234.5678")
  259. TestApplyResult(o.DoubleCurrency, (v1,), v1*2)
  260. v2 = decimal.Decimal("9012.3456")
  261. TestApplyResult(o.AddCurrencies, (v1, v2), v1+v2)
  262. TestTrickyTypesWithVariants(o, is_generated)
  263. progress("Checking win32com.client.VARIANT")
  264. TestPyVariant(o, is_generated)
  265. def TestTrickyTypesWithVariants(o, is_generated):
  266. # Test tricky stuff with type handling and generally only works with
  267. # "generated" support but can be worked around using VARIANT.
  268. if is_generated:
  269. got = o.TestByRefVariant(2)
  270. else:
  271. v = VARIANT(pythoncom.VT_BYREF | pythoncom.VT_VARIANT, 2)
  272. o.TestByRefVariant(v)
  273. got = v.value
  274. if got != 4:
  275. raise error("TestByRefVariant failed")
  276. if is_generated:
  277. got = o.TestByRefString("Foo")
  278. else:
  279. v = VARIANT(pythoncom.VT_BYREF | pythoncom.VT_BSTR, "Foo")
  280. o.TestByRefString(v)
  281. got = v.value
  282. if got != "FooFoo":
  283. raise error("TestByRefString failed")
  284. # check we can pass ints as a VT_UI1
  285. vals=[1,2,3,4]
  286. if is_generated:
  287. arg = vals
  288. else:
  289. arg = VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_UI1, vals)
  290. TestApplyResult(o.SetBinSafeArray, (arg,), len(vals))
  291. # safearrays of doubles and floats
  292. vals = [0, 1.1, 2.2, 3.3]
  293. if is_generated:
  294. arg = vals
  295. else:
  296. arg = VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_R8, vals)
  297. TestApplyResult(o.SetDoubleSafeArray, (arg,), len(vals))
  298. if is_generated:
  299. arg = vals
  300. else:
  301. arg = VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_R4, vals)
  302. TestApplyResult(o.SetFloatSafeArray, (arg,), len(vals))
  303. vals=[1.1, 2.2, 3.3, 4.4]
  304. expected = (1.1*2, 2.2*2, 3.3*2, 4.4*2)
  305. if is_generated:
  306. TestApplyResult(o.ChangeDoubleSafeArray, (vals,), expected)
  307. else:
  308. arg = VARIANT(pythoncom.VT_BYREF | pythoncom.VT_ARRAY | pythoncom.VT_R8, vals)
  309. o.ChangeDoubleSafeArray(arg)
  310. if arg.value != expected:
  311. raise error("ChangeDoubleSafeArray got the wrong value")
  312. if is_generated:
  313. got = o.DoubleInOutString("foo")
  314. else:
  315. v = VARIANT(pythoncom.VT_BYREF | pythoncom.VT_BSTR, "foo")
  316. o.DoubleInOutString(v)
  317. got = v.value
  318. assert got == "foofoo", got
  319. val = decimal.Decimal("1234.5678")
  320. if is_generated:
  321. got = o.DoubleCurrencyByVal(val)
  322. else:
  323. v = VARIANT(pythoncom.VT_BYREF | pythoncom.VT_CY, val)
  324. o.DoubleCurrencyByVal(v)
  325. got = v.value
  326. assert got == val * 2
  327. def TestDynamic():
  328. progress("Testing Dynamic")
  329. import win32com.client.dynamic
  330. o = win32com.client.dynamic.DumbDispatch("PyCOMTest.PyCOMTest")
  331. TestCommon(o, False)
  332. counter = win32com.client.dynamic.DumbDispatch("PyCOMTest.SimpleCounter")
  333. TestCounter(counter, False)
  334. # Dynamic doesn't know this should be an int, so we get a COM
  335. # TypeMismatch error.
  336. try:
  337. check_get_set_raises(ValueError, o.GetSetInt, "foo")
  338. raise error("no exception raised")
  339. except pythoncom.com_error as exc:
  340. if exc.hresult != winerror.DISP_E_TYPEMISMATCH:
  341. raise
  342. arg1 = VARIANT(pythoncom.VT_R4 | pythoncom.VT_BYREF, 2.0)
  343. arg2 = VARIANT(pythoncom.VT_BOOL | pythoncom.VT_BYREF, True)
  344. arg3 = VARIANT(pythoncom.VT_I4 | pythoncom.VT_BYREF, 4)
  345. o.TestInOut(arg1, arg2, arg3)
  346. assert arg1.value == 4.0, arg1
  347. assert arg2.value == False
  348. assert arg3.value == 8
  349. # damn - props with params don't work for dynamic objects :(
  350. # o.SetParamProp(0, 1)
  351. # if o.ParamProp(0) != 1:
  352. # raise RuntimeError, o.paramProp(0)
  353. def TestGenerated():
  354. # Create an instance of the server.
  355. from win32com.client.gencache import EnsureDispatch
  356. o = EnsureDispatch("PyCOMTest.PyCOMTest")
  357. TestCommon(o, True)
  358. counter = EnsureDispatch("PyCOMTest.SimpleCounter")
  359. TestCounter(counter, True)
  360. # This dance lets us get a CoClass even though it's not explicitly registered.
  361. # This is `CoPyComTest`
  362. from win32com.client.CLSIDToClass import GetClass
  363. coclass_o = GetClass("{8EE0C520-5605-11D0-AE5F-CADD4C000000}")()
  364. TestCommon(coclass_o, True)
  365. # This is `CoSimpleCounter` and the counter tests should work.
  366. coclass = GetClass("{B88DD310-BAE8-11D0-AE86-76F2C1000000}")()
  367. TestCounter(coclass, True)
  368. # XXX - this is failing in dynamic tests, but should work fine.
  369. i1, i2 = o.GetMultipleInterfaces()
  370. if not isinstance(i1, DispatchBaseClass) or not isinstance(i2, DispatchBaseClass):
  371. # Yay - is now an instance returned!
  372. raise error("GetMultipleInterfaces did not return instances - got '%s', '%s'" % (i1, i2))
  373. del i1
  374. del i2
  375. # Generated knows to only pass a 32bit int, so should fail.
  376. check_get_set_raises(OverflowError, o.GetSetInt, 0x80000000)
  377. check_get_set_raises(OverflowError, o.GetSetLong, 0x80000000)
  378. # Generated knows this should be an int, so raises ValueError
  379. check_get_set_raises(ValueError, o.GetSetInt, "foo")
  380. check_get_set_raises(ValueError, o.GetSetLong, "foo")
  381. # Pass some non-sequence objects to our array decoder, and watch it fail.
  382. try:
  383. o.SetVariantSafeArray("foo")
  384. raise error("Expected a type error")
  385. except TypeError:
  386. pass
  387. try:
  388. o.SetVariantSafeArray(666)
  389. raise error("Expected a type error")
  390. except TypeError:
  391. pass
  392. o.GetSimpleSafeArray(None)
  393. TestApplyResult(o.GetSimpleSafeArray, (None,), tuple(range(10)))
  394. resultCheck = tuple(range(5)), tuple(range(10)), tuple(range(20))
  395. TestApplyResult(o.GetSafeArrays, (None, None, None), resultCheck)
  396. l=[]
  397. TestApplyResult(o.SetIntSafeArray, (l,), len(l))
  398. l=[1,2,3,4]
  399. TestApplyResult(o.SetIntSafeArray, (l,), len(l))
  400. ll=[1,2,3,0x100000000]
  401. TestApplyResult(o.SetLongLongSafeArray, (ll,), len(ll))
  402. TestApplyResult(o.SetULongLongSafeArray, (ll,), len(ll))
  403. # Tell the server to do what it does!
  404. TestApplyResult(o.Test2, (constants.Attr2,), constants.Attr2)
  405. TestApplyResult(o.Test3, (constants.Attr2,), constants.Attr2)
  406. TestApplyResult(o.Test4, (constants.Attr2,), constants.Attr2)
  407. TestApplyResult(o.Test5, (constants.Attr2,), constants.Attr2)
  408. TestApplyResult(o.Test6, (constants.WideAttr1,), constants.WideAttr1)
  409. TestApplyResult(o.Test6, (constants.WideAttr2,), constants.WideAttr2)
  410. TestApplyResult(o.Test6, (constants.WideAttr3,), constants.WideAttr3)
  411. TestApplyResult(o.Test6, (constants.WideAttr4,), constants.WideAttr4)
  412. TestApplyResult(o.Test6, (constants.WideAttr5,), constants.WideAttr5)
  413. TestApplyResult(o.TestInOut, (2.0, True, 4), (4.0, False, 8))
  414. o.SetParamProp(0, 1)
  415. if o.ParamProp(0) != 1:
  416. raise RuntimeError(o.paramProp(0))
  417. # Make sure CastTo works - even though it is only casting it to itself!
  418. o2 = CastTo(o, "IPyCOMTest")
  419. if o != o2:
  420. raise error("CastTo should have returned the same object")
  421. # Do the connection point thing...
  422. # Create a connection object.
  423. progress("Testing connection points")
  424. o2 = win32com.client.DispatchWithEvents(o, RandomEventHandler)
  425. TestEvents(o2, o2)
  426. o2 = win32com.client.DispatchWithEvents(o, NewStyleRandomEventHandler)
  427. TestEvents(o2, o2)
  428. # and a plain "WithEvents".
  429. handler = win32com.client.WithEvents(o, RandomEventHandler)
  430. TestEvents(o, handler)
  431. handler = win32com.client.WithEvents(o, NewStyleRandomEventHandler)
  432. TestEvents(o, handler)
  433. progress("Finished generated .py test.")
  434. def TestEvents(o, handler):
  435. sessions = []
  436. handler._Init()
  437. try:
  438. for i in range(3):
  439. session = o.Start()
  440. sessions.append(session)
  441. time.sleep(.5)
  442. finally:
  443. # Stop the servers
  444. for session in sessions:
  445. o.Stop(session)
  446. handler._DumpFireds()
  447. handler.close()
  448. def _TestPyVariant(o, is_generated, val, checker = None):
  449. if is_generated:
  450. vt, got = o.GetVariantAndType(val)
  451. else:
  452. # Gotta supply all 3 args with the last 2 being explicit variants to
  453. # get the byref behaviour.
  454. var_vt = VARIANT(pythoncom.VT_UI2 | pythoncom.VT_BYREF, 0)
  455. var_result = VARIANT(pythoncom.VT_VARIANT | pythoncom.VT_BYREF, 0)
  456. o.GetVariantAndType(val, var_vt, var_result)
  457. vt = var_vt.value
  458. got = var_result.value
  459. if checker is not None:
  460. checker(got)
  461. return
  462. # default checking.
  463. assert vt == val.varianttype, (vt, val.varianttype)
  464. # Handle our safe-array test - if the passed value is a list of variants,
  465. # compare against the actual values.
  466. if type(val.value) in (tuple, list):
  467. check = [v.value if isinstance(v, VARIANT) else v for v in val.value]
  468. # pythoncom always returns arrays as tuples.
  469. got = list(got)
  470. else:
  471. check = val.value
  472. assert type(check) == type(got), (type(check), type(got))
  473. assert check == got, (check, got)
  474. def _TestPyVariantFails(o, is_generated, val, exc):
  475. try:
  476. _TestPyVariant(o, is_generated, val)
  477. raise error("Setting %r didn't raise %s" % (val, exc))
  478. except exc:
  479. pass
  480. def TestPyVariant(o, is_generated):
  481. _TestPyVariant(o, is_generated, VARIANT(pythoncom.VT_UI1, 1))
  482. _TestPyVariant(o, is_generated, VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_UI4, [1,2,3]))
  483. _TestPyVariant(o, is_generated, VARIANT(pythoncom.VT_BSTR, "hello"))
  484. _TestPyVariant(o, is_generated, VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_BSTR, ["hello", "there"]))
  485. def check_dispatch(got):
  486. assert isinstance(got._oleobj_, pythoncom.TypeIIDs[pythoncom.IID_IDispatch])
  487. _TestPyVariant(o, is_generated, VARIANT(pythoncom.VT_DISPATCH, o), check_dispatch)
  488. _TestPyVariant(o, is_generated, VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_DISPATCH, [o]))
  489. # an array of variants each with a specific type.
  490. v = VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_VARIANT,
  491. [VARIANT(pythoncom.VT_UI4, 1),
  492. VARIANT(pythoncom.VT_UI4, 2),
  493. VARIANT(pythoncom.VT_UI4, 3)
  494. ]
  495. )
  496. _TestPyVariant(o, is_generated, v)
  497. # and failures
  498. _TestPyVariantFails(o, is_generated, VARIANT(pythoncom.VT_UI1, "foo"), ValueError)
  499. def TestCounter(counter, bIsGenerated):
  500. # Test random access into container
  501. progress("Testing counter", repr(counter))
  502. import random
  503. for i in range(50):
  504. num = int(random.random() * len(counter))
  505. try:
  506. # XXX - this appears broken by commit 08a14d4deb374eaa06378509cf44078ad467b9dc -
  507. # We shouldn't need to do generated differently than dynamic.
  508. if bIsGenerated:
  509. ret = counter.Item(num+1)
  510. else:
  511. ret = counter[num]
  512. if ret != num+1:
  513. raise error("Random access into element %d failed - return was %s" % (num,repr(ret)))
  514. except IndexError:
  515. raise error("** IndexError accessing collection element %d" % num)
  516. num = 0
  517. if bIsGenerated:
  518. counter.SetTestProperty(1)
  519. counter.TestProperty = 1 # Note this has a second, default arg.
  520. counter.SetTestProperty(1,2)
  521. if counter.TestPropertyWithDef != 0:
  522. raise error("Unexpected property set value!")
  523. if counter.TestPropertyNoDef(1) != 1:
  524. raise error("Unexpected property set value!")
  525. else:
  526. pass
  527. # counter.TestProperty = 1
  528. counter.LBound=1
  529. counter.UBound=10
  530. if counter.LBound != 1 or counter.UBound!=10:
  531. print("** Error - counter did not keep its properties")
  532. if bIsGenerated:
  533. bounds = counter.GetBounds()
  534. if bounds[0]!=1 or bounds[1]!=10:
  535. raise error("** Error - counter did not give the same properties back")
  536. counter.SetBounds(bounds[0], bounds[1])
  537. for item in counter:
  538. num = num + 1
  539. if num != len(counter):
  540. raise error("*** Length of counter and loop iterations dont match ***")
  541. if num != 10:
  542. raise error("*** Unexpected number of loop iterations ***")
  543. try:
  544. counter = iter(counter)._iter_.Clone() # Test Clone() and enum directly
  545. except AttributeError:
  546. # *sob* - sometimes this is a real iterator and sometimes not :/
  547. progress("Finished testing counter (but skipped the iterator stuff")
  548. return
  549. counter.Reset()
  550. num = 0
  551. for item in counter:
  552. num = num + 1
  553. if num != 10:
  554. raise error("*** Unexpected number of loop iterations - got %d ***" % num)
  555. progress("Finished testing counter")
  556. def TestLocalVTable(ob):
  557. # Python doesn't fully implement this interface.
  558. if ob.DoubleString("foo") != "foofoo":
  559. raise error("couldn't foofoo")
  560. ###############################
  561. ##
  562. ## Some vtable tests of the interface
  563. ##
  564. def TestVTable(clsctx=pythoncom.CLSCTX_ALL):
  565. # Any vtable interfaces marked as dual *should* be able to be
  566. # correctly implemented as IDispatch.
  567. ob = win32com.client.Dispatch("Python.Test.PyCOMTest")
  568. TestLocalVTable(ob)
  569. # Now test it via vtable - use some C++ code to help here as Python can't do it directly yet.
  570. tester = win32com.client.Dispatch("PyCOMTest.PyCOMTest")
  571. testee = pythoncom.CoCreateInstance("Python.Test.PyCOMTest", None, clsctx, pythoncom.IID_IUnknown)
  572. # check we fail gracefully with None passed.
  573. try:
  574. tester.TestMyInterface(None)
  575. except pythoncom.com_error as details:
  576. pass
  577. # and a real object.
  578. tester.TestMyInterface(testee)
  579. def TestVTable2():
  580. # We once crashed creating our object with the native interface as
  581. # the first IID specified. We must do it _after_ the tests, so that
  582. # Python has already had the gateway registered from last run.
  583. ob = win32com.client.Dispatch("Python.Test.PyCOMTest")
  584. iid = pythoncom.InterfaceNames["IPyCOMTest"]
  585. clsid = "Python.Test.PyCOMTest"
  586. clsctx = pythoncom.CLSCTX_SERVER
  587. try:
  588. testee = pythoncom.CoCreateInstance(clsid, None, clsctx, iid)
  589. except TypeError:
  590. # Python can't actually _use_ this interface yet, so this is
  591. # "expected". Any COM error is not.
  592. pass
  593. def TestVTableMI():
  594. clsctx = pythoncom.CLSCTX_SERVER
  595. ob = pythoncom.CoCreateInstance("Python.Test.PyCOMTestMI", None, clsctx, pythoncom.IID_IUnknown)
  596. # This inherits from IStream.
  597. ob.QueryInterface(pythoncom.IID_IStream)
  598. # This implements IStorage, specifying the IID as a string
  599. ob.QueryInterface(pythoncom.IID_IStorage)
  600. # IDispatch should always work
  601. ob.QueryInterface(pythoncom.IID_IDispatch)
  602. iid = pythoncom.InterfaceNames["IPyCOMTest"]
  603. try:
  604. ob.QueryInterface(iid)
  605. except TypeError:
  606. # Python can't actually _use_ this interface yet, so this is
  607. # "expected". Any COM error is not.
  608. pass
  609. def TestQueryInterface(long_lived_server = 0, iterations=5):
  610. tester = win32com.client.Dispatch("PyCOMTest.PyCOMTest")
  611. if long_lived_server:
  612. # Create a local server
  613. t0 = win32com.client.Dispatch("Python.Test.PyCOMTest", clsctx=pythoncom.CLSCTX_LOCAL_SERVER)
  614. # Request custom interfaces a number of times
  615. prompt = [
  616. "Testing QueryInterface without long-lived local-server #%d of %d...",
  617. "Testing QueryInterface with long-lived local-server #%d of %d..."
  618. ]
  619. for i in range(iterations):
  620. progress(prompt[long_lived_server!=0] % (i+1, iterations))
  621. tester.TestQueryInterface()
  622. class Tester(win32com.test.util.TestCase):
  623. def testVTableInProc(self):
  624. # We used to crash running this the second time - do it a few times
  625. for i in range(3):
  626. progress("Testing VTables in-process #%d..." % (i+1))
  627. TestVTable(pythoncom.CLSCTX_INPROC_SERVER)
  628. def testVTableLocalServer(self):
  629. for i in range(3):
  630. progress("Testing VTables out-of-process #%d..." % (i+1))
  631. TestVTable(pythoncom.CLSCTX_LOCAL_SERVER)
  632. def testVTable2(self):
  633. for i in range(3):
  634. TestVTable2()
  635. def testVTableMI(self):
  636. for i in range(3):
  637. TestVTableMI()
  638. def testMultiQueryInterface(self):
  639. TestQueryInterface(0,6)
  640. # When we use the custom interface in the presence of a long-lived
  641. # local server, i.e. a local server that is already running when
  642. # we request an instance of our COM object, and remains afterwards,
  643. # then after repeated requests to create an instance of our object
  644. # the custom interface disappears -- i.e. QueryInterface fails with
  645. # E_NOINTERFACE. Set the upper range of the following test to 2 to
  646. # pass this test, i.e. TestQueryInterface(1,2)
  647. TestQueryInterface(1,6)
  648. def testDynamic(self):
  649. TestDynamic()
  650. def testGenerated(self):
  651. TestGenerated()
  652. if __name__=='__main__':
  653. # XXX - todo - Complete hack to crank threading support.
  654. # Should NOT be necessary
  655. def NullThreadFunc():
  656. pass
  657. import _thread
  658. _thread.start_new( NullThreadFunc, () )
  659. if "-v" in sys.argv: verbose = 1
  660. win32com.test.util.testmain()