Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

testPyComTest.py 28KB

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