testDynamic.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # Test dynamic policy, and running object table.
  2. import pythoncom
  3. import winerror
  4. from win32com.server.exception import Exception
  5. error = "testDynamic error"
  6. iid = pythoncom.MakeIID("{b48969a0-784b-11d0-ae71-d23f56000000}")
  7. class VeryPermissive:
  8. def _dynamic_(self, name, lcid, wFlags, args):
  9. if wFlags & pythoncom.DISPATCH_METHOD:
  10. return getattr(self,name)(*args)
  11. if wFlags & pythoncom.DISPATCH_PROPERTYGET:
  12. try:
  13. # to avoid problems with byref param handling, tuple results are converted to lists.
  14. ret = self.__dict__[name]
  15. if type(ret)==type(()):
  16. ret = list(ret)
  17. return ret
  18. except KeyError: # Probably a method request.
  19. raise Exception(scode=winerror.DISP_E_MEMBERNOTFOUND)
  20. if wFlags & (pythoncom.DISPATCH_PROPERTYPUT | pythoncom.DISPATCH_PROPERTYPUTREF):
  21. setattr(self, name, args[0])
  22. return
  23. raise Exception(scode=winerror.E_INVALIDARG, desc="invalid wFlags")
  24. def write(self, *args):
  25. if len(args)==0:
  26. raise Exception(scode=winerror.DISP_E_BADPARAMCOUNT) # Probably call as PROPGET.
  27. for arg in args[:-1]:
  28. print(str(arg), end=' ')
  29. print(str(args[-1]))
  30. def Test():
  31. import win32com.server.util, win32com.server.policy
  32. # import win32dbg;win32dbg.brk()
  33. ob = win32com.server.util.wrap(VeryPermissive(),usePolicy=win32com.server.policy.DynamicPolicy)
  34. try:
  35. handle = pythoncom.RegisterActiveObject(ob, iid, 0)
  36. except pythoncom.com_error as details:
  37. print("Warning - could not register the object in the ROT:", details)
  38. handle = None
  39. try:
  40. import win32com.client.dynamic
  41. client = win32com.client.dynamic.Dispatch(iid)
  42. client.ANewAttr = "Hello"
  43. if client.ANewAttr != "Hello":
  44. raise error("Could not set dynamic property")
  45. v = ["Hello","From","Python",1.4]
  46. client.TestSequence = v
  47. if v != list(client.TestSequence):
  48. raise error("Dynamic sequences not working! %r/%r" % (repr(v), repr(client.testSequence)))
  49. client.write("This","output","has","come","via","testDynamic.py")
  50. # Check our new "_FlagAsMethod" works (kinda!)
  51. client._FlagAsMethod("NotReallyAMethod")
  52. if not callable(client.NotReallyAMethod):
  53. raise error("Method I flagged as callable isn't!")
  54. client = None
  55. finally:
  56. if handle is not None:
  57. pythoncom.RevokeActiveObject(handle)
  58. print("Test worked!")
  59. if __name__=='__main__':
  60. Test()