testPyComTest.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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, 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,
  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.iteritems():
  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.iteritems():
  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. if not isinstance(o.GetSetDispatch(o), o.__class__):
  155. raise error("GetSetDispatch failed: %r" % (o.GetSetDispatch(o),))
  156. progress("Checking getting/passing IDispatch of known type")
  157. if o.GetSetInterface(o).__class__ != o.__class__:
  158. raise error("GetSetDispatch failed")
  159. progress("Checking misc args")
  160. check_get_set(o.GetSetVariant, 4)
  161. check_get_set(o.GetSetVariant, "foo")
  162. check_get_set(o.GetSetVariant, o)
  163. # signed/unsigned.
  164. check_get_set(o.GetSetInt, 0)
  165. check_get_set(o.GetSetInt, -1)
  166. check_get_set(o.GetSetInt, 1)
  167. check_get_set(o.GetSetUnsignedInt, 0)
  168. check_get_set(o.GetSetUnsignedInt, 1)
  169. check_get_set(o.GetSetUnsignedInt, 0x80000000)
  170. if o.GetSetUnsignedInt(-1) != 0xFFFFFFFF:
  171. # -1 is a special case - we accept a negative int (silently converting to
  172. # unsigned) but when getting it back we convert it to a long.
  173. raise error("unsigned -1 failed")
  174. check_get_set(o.GetSetLong, 0)
  175. check_get_set(o.GetSetLong, -1)
  176. check_get_set(o.GetSetLong, 1)
  177. check_get_set(o.GetSetUnsignedLong, 0)
  178. check_get_set(o.GetSetUnsignedLong, 1)
  179. check_get_set(o.GetSetUnsignedLong, 0x80000000)
  180. # -1 is a special case - see above.
  181. if o.GetSetUnsignedLong(-1) != 0xFFFFFFFF:
  182. raise error("unsigned -1 failed")
  183. # We want to explicitly test > 32 bits. py3k has no 'maxint' and
  184. # 'maxsize+1' is no good on 64bit platforms as its 65 bits!
  185. big = 2147483647 # sys.maxint on py2k
  186. for l in big, big+1, 1 << 65:
  187. check_get_set(o.GetSetVariant, l)
  188. progress("Checking structs")
  189. r = o.GetStruct()
  190. assert r.int_value == 99 and str(r.str_value)=="Hello from C++"
  191. assert o.DoubleString("foo") == "foofoo"
  192. progress("Checking var args")
  193. o.SetVarArgs("Hi", "There", "From", "Python", 1)
  194. if o.GetLastVarArgs() != ("Hi", "There", "From", "Python", 1):
  195. raise error("VarArgs failed -" + str(o.GetLastVarArgs()))
  196. progress("Checking arrays")
  197. l=[]
  198. TestApplyResult(o.SetVariantSafeArray, (l,), len(l))
  199. l=[1,2,3,4]
  200. TestApplyResult(o.SetVariantSafeArray, (l,), len(l))
  201. TestApplyResult(o.CheckVariantSafeArray, ((1,2,3,4,),), 1)
  202. # and binary
  203. TestApplyResult(o.SetBinSafeArray, (str2memory('foo\0bar'),), 7)
  204. progress("Checking properties")
  205. o.LongProp = 3
  206. if o.LongProp != 3 or o.IntProp != 3:
  207. raise error("Property value wrong - got %d/%d" % (o.LongProp,o.IntProp))
  208. o.LongProp = o.IntProp = -3
  209. if o.LongProp != -3 or o.IntProp != -3:
  210. raise error("Property value wrong - got %d/%d" % (o.LongProp,o.IntProp))
  211. # This number fits in an unsigned long. Attempting to set it to a normal
  212. # long will involve overflow, which is to be expected. But we do
  213. # expect it to work in a property explicitly a VT_UI4.
  214. check = 3 *10 **9
  215. o.ULongProp = check
  216. if o.ULongProp != check:
  217. raise error("Property value wrong - got %d (expected %d)" % (o.ULongProp, check))
  218. TestApplyResult(o.Test, ("Unused", 99), 1) # A bool function
  219. TestApplyResult(o.Test, ("Unused", -1), 1) # A bool function
  220. TestApplyResult(o.Test, ("Unused", 1==1), 1) # A bool function
  221. TestApplyResult(o.Test, ("Unused", 0), 0)
  222. TestApplyResult(o.Test, ("Unused", 1==0), 0)
  223. assert o.DoubleString("foo") == "foofoo"
  224. TestConstant("ULongTest1", ensure_long(0xFFFFFFFF))
  225. TestConstant("ULongTest2", ensure_long(0x7FFFFFFF))
  226. TestConstant("LongTest1", ensure_long(-0x7FFFFFFF))
  227. TestConstant("LongTest2", ensure_long(0x7FFFFFFF))
  228. TestConstant("UCharTest", 255)
  229. TestConstant("CharTest", -1)
  230. # 'Hello Loraine', but the 'r' is the "Registered" sign (\xae)
  231. TestConstant("StringTest", u"Hello Lo\xaeaine")
  232. progress("Checking dates and times")
  233. if issubclass(pywintypes.TimeType, datetime.datetime):
  234. # For now *all* times passed must be tz-aware.
  235. now = win32timezone.now()
  236. # but conversion to and from a VARIANT loses sub-second...
  237. now = now.replace(microsecond=0)
  238. later = now + datetime.timedelta(seconds=1)
  239. TestApplyResult(o.EarliestDate, (now, later), now)
  240. else:
  241. # old PyTime object
  242. now = pythoncom.MakeTime(time.gmtime(time.time()))
  243. later = pythoncom.MakeTime(time.gmtime(time.time()+1))
  244. TestApplyResult(o.EarliestDate, (now, later), now)
  245. # But it can still *accept* tz-naive datetime objects...
  246. now = datetime.datetime.now()
  247. expect = pythoncom.MakeTime(now)
  248. TestApplyResult(o.EarliestDate, (now, now), expect)
  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, exc:
  340. if exc.hresult != winerror.DISP_E_TYPEMISMATCH:
  341. raise
  342. # damn - props with params don't work for dynamic objects :(
  343. # o.SetParamProp(0, 1)
  344. # if o.ParamProp(0) != 1:
  345. # raise RuntimeError, o.paramProp(0)
  346. def TestGenerated():
  347. # Create an instance of the server.
  348. from win32com.client.gencache import EnsureDispatch
  349. o = EnsureDispatch("PyCOMTest.PyCOMTest")
  350. TestCommon(o, True)
  351. counter = EnsureDispatch("PyCOMTest.SimpleCounter")
  352. TestCounter(counter, True)
  353. # XXX - this is failing in dynamic tests, but should work fine.
  354. i1, i2 = o.GetMultipleInterfaces()
  355. if not isinstance(i1, DispatchBaseClass) or not isinstance(i2, DispatchBaseClass):
  356. # Yay - is now an instance returned!
  357. raise error("GetMultipleInterfaces did not return instances - got '%s', '%s'" % (i1, i2))
  358. del i1
  359. del i2
  360. # Generated knows to only pass a 32bit int, so should fail.
  361. check_get_set_raises(OverflowError, o.GetSetInt, 0x80000000)
  362. check_get_set_raises(OverflowError, o.GetSetLong, 0x80000000)
  363. # Generated knows this should be an int, so raises ValueError
  364. check_get_set_raises(ValueError, o.GetSetInt, "foo")
  365. check_get_set_raises(ValueError, o.GetSetLong, "foo")
  366. # Pass some non-sequence objects to our array decoder, and watch it fail.
  367. try:
  368. o.SetVariantSafeArray("foo")
  369. raise error("Expected a type error")
  370. except TypeError:
  371. pass
  372. try:
  373. o.SetVariantSafeArray(666)
  374. raise error("Expected a type error")
  375. except TypeError:
  376. pass
  377. o.GetSimpleSafeArray(None)
  378. TestApplyResult(o.GetSimpleSafeArray, (None,), tuple(range(10)))
  379. resultCheck = tuple(range(5)), tuple(range(10)), tuple(range(20))
  380. TestApplyResult(o.GetSafeArrays, (None, None, None), resultCheck)
  381. l=[]
  382. TestApplyResult(o.SetIntSafeArray, (l,), len(l))
  383. l=[1,2,3,4]
  384. TestApplyResult(o.SetIntSafeArray, (l,), len(l))
  385. ll=[1,2,3,0x100000000]
  386. TestApplyResult(o.SetLongLongSafeArray, (ll,), len(ll))
  387. TestApplyResult(o.SetULongLongSafeArray, (ll,), len(ll))
  388. # Tell the server to do what it does!
  389. TestApplyResult(o.Test2, (constants.Attr2,), constants.Attr2)
  390. TestApplyResult(o.Test3, (constants.Attr2,), constants.Attr2)
  391. TestApplyResult(o.Test4, (constants.Attr2,), constants.Attr2)
  392. TestApplyResult(o.Test5, (constants.Attr2,), constants.Attr2)
  393. TestApplyResult(o.Test6, (constants.WideAttr1,), constants.WideAttr1)
  394. TestApplyResult(o.Test6, (constants.WideAttr2,), constants.WideAttr2)
  395. TestApplyResult(o.Test6, (constants.WideAttr3,), constants.WideAttr3)
  396. TestApplyResult(o.Test6, (constants.WideAttr4,), constants.WideAttr4)
  397. TestApplyResult(o.Test6, (constants.WideAttr5,), constants.WideAttr5)
  398. o.SetParamProp(0, 1)
  399. if o.ParamProp(0) != 1:
  400. raise RuntimeError(o.paramProp(0))
  401. # Make sure CastTo works - even though it is only casting it to itself!
  402. o2 = CastTo(o, "IPyCOMTest")
  403. if o != o2:
  404. raise error("CastTo should have returned the same object")
  405. # Do the connection point thing...
  406. # Create a connection object.
  407. progress("Testing connection points")
  408. o2 = win32com.client.DispatchWithEvents(o, RandomEventHandler)
  409. TestEvents(o2, o2)
  410. o2 = win32com.client.DispatchWithEvents(o, NewStyleRandomEventHandler)
  411. TestEvents(o2, o2)
  412. # and a plain "WithEvents".
  413. handler = win32com.client.WithEvents(o, RandomEventHandler)
  414. TestEvents(o, handler)
  415. handler = win32com.client.WithEvents(o, NewStyleRandomEventHandler)
  416. TestEvents(o, handler)
  417. progress("Finished generated .py test.")
  418. def TestEvents(o, handler):
  419. sessions = []
  420. handler._Init()
  421. try:
  422. for i in range(3):
  423. session = o.Start()
  424. sessions.append(session)
  425. time.sleep(.5)
  426. finally:
  427. # Stop the servers
  428. for session in sessions:
  429. o.Stop(session)
  430. handler._DumpFireds()
  431. handler.close()
  432. def _TestPyVariant(o, is_generated, val, checker = None):
  433. if is_generated:
  434. vt, got = o.GetVariantAndType(val)
  435. else:
  436. # Gotta supply all 3 args with the last 2 being explicit variants to
  437. # get the byref behaviour.
  438. var_vt = VARIANT(pythoncom.VT_UI2 | pythoncom.VT_BYREF, 0)
  439. var_result = VARIANT(pythoncom.VT_VARIANT | pythoncom.VT_BYREF, 0)
  440. o.GetVariantAndType(val, var_vt, var_result)
  441. vt = var_vt.value
  442. got = var_result.value
  443. if checker is not None:
  444. checker(got)
  445. return
  446. # default checking.
  447. assert vt == val.varianttype, (vt, val.varianttype)
  448. # Handle our safe-array test - if the passed value is a list of variants,
  449. # compare against the actual values.
  450. if type(val.value) in (tuple, list):
  451. check = [v.value if isinstance(v, VARIANT) else v for v in val.value]
  452. # pythoncom always returns arrays as tuples.
  453. got = list(got)
  454. else:
  455. check = val.value
  456. assert type(check) == type(got), (type(check), type(got))
  457. assert check == got, (check, got)
  458. def _TestPyVariantFails(o, is_generated, val, exc):
  459. try:
  460. _TestPyVariant(o, is_generated, val)
  461. raise error("Setting %r didn't raise %s" % (val, exc))
  462. except exc:
  463. pass
  464. def TestPyVariant(o, is_generated):
  465. _TestPyVariant(o, is_generated, VARIANT(pythoncom.VT_UI1, 1))
  466. _TestPyVariant(o, is_generated, VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_UI4, [1,2,3]))
  467. _TestPyVariant(o, is_generated, VARIANT(pythoncom.VT_BSTR, u"hello"))
  468. _TestPyVariant(o, is_generated, VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_BSTR, [u"hello", u"there"]))
  469. def check_dispatch(got):
  470. assert isinstance(got._oleobj_, pythoncom.TypeIIDs[pythoncom.IID_IDispatch])
  471. _TestPyVariant(o, is_generated, VARIANT(pythoncom.VT_DISPATCH, o), check_dispatch)
  472. _TestPyVariant(o, is_generated, VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_DISPATCH, [o]))
  473. # an array of variants each with a specific type.
  474. v = VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_VARIANT,
  475. [VARIANT(pythoncom.VT_UI4, 1),
  476. VARIANT(pythoncom.VT_UI4, 2),
  477. VARIANT(pythoncom.VT_UI4, 3)
  478. ]
  479. )
  480. _TestPyVariant(o, is_generated, v)
  481. # and failures
  482. _TestPyVariantFails(o, is_generated, VARIANT(pythoncom.VT_UI1, "foo"), ValueError)
  483. def TestCounter(counter, bIsGenerated):
  484. # Test random access into container
  485. progress("Testing counter", repr(counter))
  486. import random
  487. for i in xrange(50):
  488. num = int(random.random() * len(counter))
  489. try:
  490. # XXX - this appears broken by commit 08a14d4deb374eaa06378509cf44078ad467b9dc -
  491. # We shouldn't need to do generated differently than dynamic.
  492. if bIsGenerated:
  493. ret = counter.Item(num+1)
  494. else:
  495. ret = counter[num]
  496. if ret != num+1:
  497. raise error("Random access into element %d failed - return was %s" % (num,repr(ret)))
  498. except IndexError:
  499. raise error("** IndexError accessing collection element %d" % num)
  500. num = 0
  501. if bIsGenerated:
  502. counter.SetTestProperty(1)
  503. counter.TestProperty = 1 # Note this has a second, default arg.
  504. counter.SetTestProperty(1,2)
  505. if counter.TestPropertyWithDef != 0:
  506. raise error("Unexpected property set value!")
  507. if counter.TestPropertyNoDef(1) != 1:
  508. raise error("Unexpected property set value!")
  509. else:
  510. pass
  511. # counter.TestProperty = 1
  512. counter.LBound=1
  513. counter.UBound=10
  514. if counter.LBound != 1 or counter.UBound!=10:
  515. print "** Error - counter did not keep its properties"
  516. if bIsGenerated:
  517. bounds = counter.GetBounds()
  518. if bounds[0]!=1 or bounds[1]!=10:
  519. raise error("** Error - counter did not give the same properties back")
  520. counter.SetBounds(bounds[0], bounds[1])
  521. for item in counter:
  522. num = num + 1
  523. if num != len(counter):
  524. raise error("*** Length of counter and loop iterations dont match ***")
  525. if num != 10:
  526. raise error("*** Unexpected number of loop iterations ***")
  527. counter = iter(counter)._iter_.Clone() # Test Clone() and enum directly
  528. counter.Reset()
  529. num = 0
  530. for item in counter:
  531. num = num + 1
  532. if num != 10:
  533. raise error("*** Unexpected number of loop iterations - got %d ***" % num)
  534. progress("Finished testing counter")
  535. def TestLocalVTable(ob):
  536. # Python doesn't fully implement this interface.
  537. if ob.DoubleString("foo") != "foofoo":
  538. raise error("couldn't foofoo")
  539. ###############################
  540. ##
  541. ## Some vtable tests of the interface
  542. ##
  543. def TestVTable(clsctx=pythoncom.CLSCTX_ALL):
  544. # Any vtable interfaces marked as dual *should* be able to be
  545. # correctly implemented as IDispatch.
  546. ob = win32com.client.Dispatch("Python.Test.PyCOMTest")
  547. TestLocalVTable(ob)
  548. # Now test it via vtable - use some C++ code to help here as Python can't do it directly yet.
  549. tester = win32com.client.Dispatch("PyCOMTest.PyCOMTest")
  550. testee = pythoncom.CoCreateInstance("Python.Test.PyCOMTest", None, clsctx, pythoncom.IID_IUnknown)
  551. # check we fail gracefully with None passed.
  552. try:
  553. tester.TestMyInterface(None)
  554. except pythoncom.com_error, details:
  555. pass
  556. # and a real object.
  557. tester.TestMyInterface(testee)
  558. def TestVTable2():
  559. # We once crashed creating our object with the native interface as
  560. # the first IID specified. We must do it _after_ the tests, so that
  561. # Python has already had the gateway registered from last run.
  562. ob = win32com.client.Dispatch("Python.Test.PyCOMTest")
  563. iid = pythoncom.InterfaceNames["IPyCOMTest"]
  564. clsid = "Python.Test.PyCOMTest"
  565. clsctx = pythoncom.CLSCTX_SERVER
  566. try:
  567. testee = pythoncom.CoCreateInstance(clsid, None, clsctx, iid)
  568. except TypeError:
  569. # Python can't actually _use_ this interface yet, so this is
  570. # "expected". Any COM error is not.
  571. pass
  572. def TestVTableMI():
  573. clsctx = pythoncom.CLSCTX_SERVER
  574. ob = pythoncom.CoCreateInstance("Python.Test.PyCOMTestMI", None, clsctx, pythoncom.IID_IUnknown)
  575. # This inherits from IStream.
  576. ob.QueryInterface(pythoncom.IID_IStream)
  577. # This implements IStorage, specifying the IID as a string
  578. ob.QueryInterface(pythoncom.IID_IStorage)
  579. # IDispatch should always work
  580. ob.QueryInterface(pythoncom.IID_IDispatch)
  581. iid = pythoncom.InterfaceNames["IPyCOMTest"]
  582. try:
  583. ob.QueryInterface(iid)
  584. except TypeError:
  585. # Python can't actually _use_ this interface yet, so this is
  586. # "expected". Any COM error is not.
  587. pass
  588. def TestQueryInterface(long_lived_server = 0, iterations=5):
  589. tester = win32com.client.Dispatch("PyCOMTest.PyCOMTest")
  590. if long_lived_server:
  591. # Create a local server
  592. t0 = win32com.client.Dispatch("Python.Test.PyCOMTest", clsctx=pythoncom.CLSCTX_LOCAL_SERVER)
  593. # Request custom interfaces a number of times
  594. prompt = [
  595. "Testing QueryInterface without long-lived local-server #%d of %d...",
  596. "Testing QueryInterface with long-lived local-server #%d of %d..."
  597. ]
  598. for i in range(iterations):
  599. progress(prompt[long_lived_server!=0] % (i+1, iterations))
  600. tester.TestQueryInterface()
  601. class Tester(win32com.test.util.TestCase):
  602. def testVTableInProc(self):
  603. # We used to crash running this the second time - do it a few times
  604. for i in range(3):
  605. progress("Testing VTables in-process #%d..." % (i+1))
  606. TestVTable(pythoncom.CLSCTX_INPROC_SERVER)
  607. def testVTableLocalServer(self):
  608. for i in range(3):
  609. progress("Testing VTables out-of-process #%d..." % (i+1))
  610. TestVTable(pythoncom.CLSCTX_LOCAL_SERVER)
  611. def testVTable2(self):
  612. for i in range(3):
  613. TestVTable2()
  614. def testVTableMI(self):
  615. for i in range(3):
  616. TestVTableMI()
  617. def testMultiQueryInterface(self):
  618. TestQueryInterface(0,6)
  619. # When we use the custom interface in the presence of a long-lived
  620. # local server, i.e. a local server that is already running when
  621. # we request an instance of our COM object, and remains afterwards,
  622. # then after repeated requests to create an instance of our object
  623. # the custom interface disappears -- i.e. QueryInterface fails with
  624. # E_NOINTERFACE. Set the upper range of the following test to 2 to
  625. # pass this test, i.e. TestQueryInterface(1,2)
  626. TestQueryInterface(1,6)
  627. def testDynamic(self):
  628. TestDynamic()
  629. def testGenerated(self):
  630. TestGenerated()
  631. if __name__=='__main__':
  632. # XXX - todo - Complete hack to crank threading support.
  633. # Should NOT be necessary
  634. def NullThreadFunc():
  635. pass
  636. import thread
  637. thread.start_new( NullThreadFunc, () )
  638. if "-v" in sys.argv: verbose = 1
  639. win32com.test.util.testmain()