def testLogger(): assert not hasattr(win32com, "logger") handler = TestLogHandler() formatter = logging.Formatter("%(message)s") handler.setFormatter(formatter) log = logging.getLogger("win32com_test") log.addHandler(handler) win32com.logger = log # Now throw some exceptions! # Native interfaces com_server = wrap(TestServer(), pythoncom.IID_IStream) try: com_server.Commit(0) raise RuntimeError("should have failed") except pythoncom.error as exc: # `excepinfo` is a tuple with elt 2 being the traceback we captured. message = exc.excepinfo[2] assert message.endswith("Exception: \U0001F600\n") assert handler.num_emits == 1, handler.num_emits assert handler.last_record.startswith( "pythoncom error: Unexpected exception in gateway method 'Commit'") handler.reset() # IDispatch com_server = Dispatch(wrap(TestServer())) try: com_server.Commit(0) raise RuntimeError("should have failed") except pythoncom.error as exc: # `excepinfo` is a tuple with elt 2 being the traceback we captured. message = exc.excepinfo[2] assert message.endswith("Exception: \U0001F600\n") assert handler.num_emits == 1, handler.num_emits handler.reset()
def testLogger(): assert not hasattr(win32com, "logger") handler = TestLogHandler() formatter = logging.Formatter('%(message)s') handler.setFormatter(formatter) log = logging.getLogger("win32com_test") log.addHandler(handler) win32com.logger = log # Now throw some exceptions! # Native interfaces com_server = wrap(TestServer(), pythoncom.IID_IStream) try: com_server.Commit(0) raise RuntimeError("should have failed") except pythoncom.error: pass assert handler.num_emits == 1, handler.num_emits handler.num_emits = 0 # reset com_server = Dispatch(wrap(TestServer())) try: com_server.Commit(0) raise RuntimeError("should have failed") except pythoncom.error: pass assert handler.num_emits == 1, handler.num_emits
def test(): bag = Bag() target = Target() log = Log() target.Save(bag, 1, 1) target.Load(bag, log) comBag = util.wrap(bag, pythoncom.IID_IPropertyBag) comTarget = util.wrap(target, pythoncom.IID_IPersistPropertyBag) comLog = util.wrap(log, pythoncom.IID_IErrorLog) comTarget.Save(comBag, 1, 1) comTarget.Load(comBag, comLog)
def getSite(self, code=None, fam=None, user=None): os.chdir(pywikipediaDir) site = wikipedia.getSite(code, fam, user) site.objectVer = wikipedia.__version__ site.objectName = "WikiSite" site._public_methods_ = [ '__cmp__', '__repr__', 'allmessages_address', 'allpages', 'allpages_address', 'ancientpages', 'ancientpages_address', 'broken_redirects_address', 'categories', 'categories_address', 'category_namespace', 'category_namespaces', 'category_on_one_line', 'checkCharset', 'cookies', 'deadendpages', 'deadendpages_address', 'delete_address', 'double_redirects_address', 'edit_address', 'encoding', 'encodings', 'export_address', 'family', 'forceLogin', 'getSite', 'getToken', 'getUrl', 'get_address', 'hostname', 'image_namespace', 'interwiki_putfirst', 'interwiki_putfirst_doubled', 'language', 'languages', 'linkto', 'loggedin', 'login_address', 'lonelypages', 'lonelypages_address', 'longpages', 'longpages_address', 'namespace', 'namespaces', 'newpages', 'newpages_address', 'purge_address', 'putToken', 'put_address', 'redirect', 'redirectRegex', 'references_address', 'shortpages', 'shortpages_address', 'sitename', 'template_namespace', 'uncategorizedcategories', 'uncategorizedcategories_address', 'uncategorizedpages', 'uncategorizedpages_address', 'unusedcategories', 'unusedcategories_address', 'upload_address', 'version', 'watchlist_address' ] site._public_attrs_ = ['objectVer', 'objectName'] site._readonly_attrs_ = site._public_attrs_ return wrap(site, useDispatcher=useDispatcher)
def __init__(self): message_map = { win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COMMAND: self.OnCommand, win32con.WM_SIZE: self.OnSize, } # Register the Window class. wc = win32gui.WNDCLASS() hinst = wc.hInstance = win32api.GetModuleHandle(None) wc.lpszClassName = "test_explorer_browser" wc.lpfnWndProc = message_map # could also specify a wndproc. classAtom = win32gui.RegisterClass(wc) # Create the Window. style = win32con.WS_OVERLAPPEDWINDOW | win32con.WS_VISIBLE self.hwnd = win32gui.CreateWindow( classAtom, "Python IExplorerBrowser demo", style, \ 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, \ 0, 0, hinst, None) eb = pythoncom.CoCreateInstance(shellcon.CLSID_ExplorerBrowser, None, pythoncom.CLSCTX_ALL, shell.IID_IExplorerBrowser) # as per MSDN docs, hook up events early self.event_cookie = eb.Advise(wrap(EventHandler())) eb.SetOptions(shellcon.EBO_SHOWFRAMES) rect = win32gui.GetClientRect(self.hwnd) # Set the flags such that the folders autoarrange and non web view is presented flags = (shellcon.FVM_LIST, shellcon.FWF_AUTOARRANGE | shellcon.FWF_NOWEBVIEW) eb.Initialize(self.hwnd, rect, (0, shellcon.FVM_DETAILS)) # And start browsing at the root of the namespace. eb.BrowseToIDList([], shellcon.SBSP_ABSOLUTE) #eb.FillFromObject(None, shellcon.EBF_NODROPTARGET); #eb.SetEmptyText("No known folders yet..."); self.eb = eb
def TestEngine(): model = {'Test' : util.wrap(ObjectModel()) } scriptDir = "." site = MySite(model) pyEngine = site._AddEngine("Python") # pyEngine2 = site._AddEngine("Python") vbEngine = site._AddEngine("VBScript") # forthEngine = site._AddEngine("ForthScript") try: # code = open(os.path.join(scriptDir, "debugTest.4ths"),"rb").read() # forthEngine.AddCode(code) code = open(os.path.join(scriptDir, "debugTest.pys"),"rb").read() pyEngine.AddCode(code) code = open(os.path.join(scriptDir, "debugTest.vbs"),"rb").read() vbEngine.AddCode(code) # code = open(os.path.join(scriptDir, "debugTestFail.pys"),"rb").read() # pyEngine2.AddCode(code) # from win32com.axdebug import axdebug # sessionProvider=pythoncom.CoCreateInstance(axdebug.CLSID_DefaultDebugSessionProvider,None,pythoncom.CLSCTX_ALL, axdebug.IID_IDebugSessionProvider) # sessionProvider.StartDebugSession(None) raw_input("Press enter to continue") # forthEngine.Start() pyEngine.Start() # Actually run the Python code vbEngine.Start() # Actually run the VB code except pythoncom.com_error, details: print "Script failed: %s (0x%x)" % (details[1], details[0])
def TestEngine(): model = {'Test': util.wrap(ObjectModel())} scriptDir = "." site = MySite(model) pyEngine = site._AddEngine("Python") # pyEngine2 = site._AddEngine("Python") vbEngine = site._AddEngine("VBScript") # forthEngine = site._AddEngine("ForthScript") try: # code = open(os.path.join(scriptDir, "debugTest.4ths"),"rb").read() # forthEngine.AddCode(code) code = open(os.path.join(scriptDir, "debugTest.pys"), "rb").read() pyEngine.AddCode(code) code = open(os.path.join(scriptDir, "debugTest.vbs"), "rb").read() vbEngine.AddCode(code) # code = open(os.path.join(scriptDir, "debugTestFail.pys"),"rb").read() # pyEngine2.AddCode(code) # from win32com.axdebug import axdebug # sessionProvider=pythoncom.CoCreateInstance(axdebug.CLSID_DefaultDebugSessionProvider,None,pythoncom.CLSCTX_ALL, axdebug.IID_IDebugSessionProvider) # sessionProvider.StartDebugSession(None) raw_input("Press enter to continue") # forthEngine.Start() pyEngine.Start() # Actually run the Python code vbEngine.Start() # Actually run the VB code except pythoncom.com_error, details: print "Script failed: %s (0x%x)" % (details[1], details[0])
def CreateObject(self, typename): try: parts = typename.split(".") item = __import__(".".join(parts[:-1])) for part in parts[1:]: item = getattr(item, part) return util.wrap(item()) except: raise COMException("No such type", winerror.DISP_E_BADVARTYPE)
def getSite(self, code = None, fam = None, user = None): os.chdir(pywikipediaDir) site = wikipedia.getSite(code, fam, user) site.objectVer = wikipedia.__version__ site.objectName = "WikiSite" site._public_methods_ = ['__cmp__', '__repr__', 'allmessages_address', 'allpages', 'allpages_address', 'ancientpages', 'ancientpages_address', 'broken_redirects_address', 'categories', 'categories_address', 'category_namespace', 'category_namespaces', 'category_on_one_line', 'checkCharset', 'cookies', 'deadendpages', 'deadendpages_address', 'delete_address', 'double_redirects_address', 'edit_address', 'encoding', 'encodings', 'export_address', 'family', 'forceLogin', 'getSite', 'getToken', 'getUrl', 'get_address', 'hostname', 'image_namespace', 'interwiki_putfirst', 'interwiki_putfirst_doubled', 'language', 'languages', 'linkto', 'loggedin', 'login_address', 'lonelypages', 'lonelypages_address', 'longpages', 'longpages_address', 'namespace', 'namespaces', 'newpages', 'newpages_address', 'purge_address', 'putToken', 'put_address', 'redirect', 'redirectRegex', 'references_address', 'shortpages', 'shortpages_address', 'sitename', 'template_namespace', 'uncategorizedcategories', 'uncategorizedcategories_address', 'uncategorizedpages', 'uncategorizedpages_address', 'unusedcategories', 'unusedcategories_address', 'upload_address', 'version', 'watchlist_address'] site._public_attrs_ = ['objectVer', 'objectName'] site._readonly_attrs_ = site._public_attrs_ return wrap(site, useDispatcher=useDispatcher)
def __init__(self): message_map = { win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COMMAND: self.OnCommand, win32con.WM_SIZE: self.OnSize, } # Register the Window class. wc = win32gui.WNDCLASS() hinst = wc.hInstance = win32api.GetModuleHandle(None) wc.lpszClassName = "test_explorer_browser" wc.lpfnWndProc = message_map # could also specify a wndproc. classAtom = win32gui.RegisterClass(wc) # Create the Window. style = win32con.WS_OVERLAPPEDWINDOW | win32con.WS_VISIBLE self.hwnd = win32gui.CreateWindow( classAtom, "Python IExplorerBrowser demo", style, \ 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, \ 0, 0, hinst, None) eb = pythoncom.CoCreateInstance(shellcon.CLSID_ExplorerBrowser, None, pythoncom.CLSCTX_ALL, shell.IID_IExplorerBrowser) # as per MSDN docs, hook up events early self.event_cookie = eb.Advise(wrap(EventHandler())) eb.SetOptions(shellcon.EBO_SHOWFRAMES) rect = win32gui.GetClientRect(self.hwnd) # Set the flags such that the folders autoarrange and non web view is presented flags = (shellcon.FVM_LIST, shellcon.FWF_AUTOARRANGE | shellcon.FWF_NOWEBVIEW) eb.Initialize(self.hwnd, rect, (0, shellcon.FVM_DETAILS)) if len(sys.argv)==2: # If an arg was specified, ask the desktop parse it. # You can pass anything explorer accepts as its '/e' argument - # eg, "::{guid}\::{guid}" etc. # "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}" is "My Computer" pidl = shell.SHGetDesktopFolder().ParseDisplayName(0, None, sys.argv[1])[1] else: # And start browsing at the root of the namespace. pidl = [] eb.BrowseToIDList(pidl, shellcon.SBSP_ABSOLUTE) # and for some reason the "Folder" view in the navigator pane doesn't # magically synchronize itself - so let's do that ourself. # Get the tree control. sp = eb.QueryInterface(pythoncom.IID_IServiceProvider) try: tree = sp.QueryService(shell.IID_INameSpaceTreeControl, shell.IID_INameSpaceTreeControl) except pythoncom.com_error as exc: # this should really only fail if no "nav" frame exists... print("Strange - failed to get the tree control even though " \ "we asked for a EBO_SHOWFRAMES") print(exc) else: # get the IShellItem for the selection. si = shell.SHCreateItemFromIDList(pidl, shell.IID_IShellItem) # set it to selected. tree.SetItemState(si, shellcon.NSTCIS_SELECTED, shellcon.NSTCIS_SELECTED) #eb.FillFromObject(None, shellcon.EBF_NODROPTARGET); #eb.SetEmptyText("No known folders yet..."); self.eb = eb
def CreateViewObject(self, hwnd, iid): mod_objects = get_clbr_for_file(self.path) object = mod_objects[self.class_name] if self.method_name is None: lineno = object.lineno else: lineno = object.methods[self.method_name] return wrap(ScintillaShellView(hwnd, self.path, lineno), iid, useDispatcher=debug>0)
def CreateObject(self, typename): try: parts = typename.split('.') item = __import__('.'.join(parts[:-1])) for part in parts[1:]: item = getattr(item, part) return util.wrap(item()) except: raise COMException('No such type', winerror.DISP_E_BADVARTYPE)
def CreateChild(self): # We create a new Child object, and wrap # it up using the default policy # If we are debugging, we also specify the default dispatcher child = Child() print "Our Python child is", child wrapped = wrap(child, useDispatcher=useDispatcher) print "Returing wrapped", wrapped return wrapped
def TestArrays(vbtest, bUseGenerated): # Try and use a safe array (note that the VB code has this declared as a VARIANT # and I cant work out how to force it to use native arrays! # (NOTE Python will convert incoming arrays to tuples, so we pass a tuple, even tho # a list works fine - just makes it easier for us to compare the result! # Empty array _DoTestArray(vbtest, ()) # Empty child array _DoTestArray(vbtest, ((), ())) # ints _DoTestArray(vbtest, tuple(range(1, 100))) # Floats _DoTestArray(vbtest, (1.0, 2.0, 3.0)) # Strings. _DoTestArray(vbtest, tuple("Hello from Python".split())) # Date and Time? # COM objects. _DoTestArray(vbtest, (vbtest, vbtest)) # Mixed _DoTestArray(vbtest, (1, 2.0, "3")) # Array alements containing other arrays _DoTestArray(vbtest, (1, (vbtest, vbtest), ("3", "4"))) # Multi-dimensional _DoTestArray(vbtest, (((1, 2, 3), (4, 5, 6)))) _DoTestArray(vbtest, (((vbtest, vbtest, vbtest), (vbtest, vbtest, vbtest)))) # Another dimension! arrayData = (((1, 2), (3, 4), (5, 6)), ((7, 8), (9, 10), (11, 12))) arrayData = (((vbtest, vbtest), (vbtest, vbtest), (vbtest, vbtest)), ((vbtest, vbtest), (vbtest, vbtest), (vbtest, vbtest))) _DoTestArray(vbtest, arrayData) # Check that when a '__getitem__ that fails' object is the first item # in the structure, we don't mistake it for a sequence. _DoTestArray(vbtest, (vbtest, 2.0, "3")) _DoTestArray(vbtest, (1, 2.0, vbtest)) # Pass arbitrarily sized arrays - these used to fail, but thanks to # Stefan Schukat, they now work! expected_exception = None arrayData = (((1, 2, 1), (3, 4), (5, 6)), ((7, 8), (9, 10), (11, 12))) _DoTestArray(vbtest, arrayData, expected_exception) arrayData = (((vbtest, vbtest), ), ((vbtest, ), )) _DoTestArray(vbtest, arrayData, expected_exception) # Pass bad data - last item wrong size arrayData = (((1, 2), (3, 4), (5, 6, 8)), ((7, 8), (9, 10), (11, 12))) _DoTestArray(vbtest, arrayData, expected_exception) # byref safearray results with incorrect size. callback_ob = wrap(TestObject(), useDispatcher=useDispatcher) print "** Expecting a 'ValueError' exception to be printed next:" try: vbtest.DoCallbackSafeArraySizeFail(callback_ob) except pythoncom.com_error, exc: assert exc.excepinfo[ 1] == "Python COM Server Internal Error", "Didnt get the correct exception - '%s'" % ( exc, )
def _TestEngine(self, engineName, code, expected_exc = None): echoer = Test() model = { 'test.py' : util.wrap(echoer), } site = MySite(model) engine = site._AddEngine(engineName) try: _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED) engine.AddCode(code) engine.Start() _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_STARTED) self.failUnless(not echoer.fail_called, "Fail should not have been called") # Now call into the scripts IDispatch ob = Dispatch(engine.GetScriptDispatch()) try: ob.hello("Goober") self.failUnless(expected_exc is None, "Expected %r, but no exception seen" % (expected_exc,)) except pythoncom.com_error: if expected_exc is None: self.fail("Unexpected failure from script code: %s" % (site.exception_seen,)) if expected_exc not in site.exception_seen[2]: self.fail("Could not find %r in %r" % (expected_exc, site.exception_seen[2])) return self.assertEqual(echoer.last, "Goober") self.assertEqual(str(ob.prop), "Property Value") ob.testcollection() self.failUnless(not echoer.fail_called, "Fail should not have been called") # Now make sure my engines can evaluate stuff. result = engine.eParse.ParseScriptText("1+1", None, None, None, 0, 0, axscript.SCRIPTTEXT_ISEXPRESSION) self.assertEqual(result, 2) # re-initialize to make sure it transitions back to initialized again. engine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED) _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED) engine.Start() _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_STARTED) # Transition back to initialized, then through connected too. engine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED) _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED) engine.SetScriptState(axscript.SCRIPTSTATE_CONNECTED) _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_CONNECTED) engine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED) _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED) engine.SetScriptState(axscript.SCRIPTSTATE_CONNECTED) _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_CONNECTED) engine.SetScriptState(axscript.SCRIPTSTATE_DISCONNECTED) _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_DISCONNECTED) finally: engine.Close() engine = None site = None
def _TestEngine(self, engineName, code, expected_exc = None): echoer = Test() model = { 'test' : util.wrap(echoer), } site = MySite(model) engine = site._AddEngine(engineName) try: _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED) engine.AddCode(code) engine.Start() _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_STARTED) self.failUnless(not echoer.fail_called, "Fail should not have been called") # Now call into the scripts IDispatch ob = Dispatch(engine.GetScriptDispatch()) try: ob.hello("Goober") self.failUnless(expected_exc is None, "Expected %r, but no exception seen" % (expected_exc,)) except pythoncom.com_error: if expected_exc is None: self.fail("Unexpected failure from script code: %s" % (site.exception_seen,)) if expected_exc not in site.exception_seen[2]: self.fail("Could not find %r in %r" % (expected_exc, site.exception_seen[2])) return self.assertEqual(echoer.last, "Goober") self.assertEqual(str(ob.prop), "Property Value") ob.testcollection() self.failUnless(not echoer.fail_called, "Fail should not have been called") # Now make sure my engines can evaluate stuff. result = engine.eParse.ParseScriptText("1+1", None, None, None, 0, 0, axscript.SCRIPTTEXT_ISEXPRESSION) self.assertEqual(result, 2) # re-initialize to make sure it transitions back to initialized again. engine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED) _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED) engine.Start() _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_STARTED) # Transition back to initialized, then through connected too. engine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED) _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED) engine.SetScriptState(axscript.SCRIPTSTATE_CONNECTED) _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_CONNECTED) engine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED) _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED) engine.SetScriptState(axscript.SCRIPTSTATE_CONNECTED) _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_CONNECTED) engine.SetScriptState(axscript.SCRIPTSTATE_DISCONNECTED) _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_DISCONNECTED) finally: engine.Close() engine = None site = None
def MakePythonObject(obj): # For simple types, we just return it objtype = type(obj) if objtype in simpleTypes: return obj else: print "Returning wrapped for", obj return wrap(PythonObject(obj), usePolicy=DynamicPolicy, useDispatcher=DefaultDebugDispatcher)
def _TestEngine(self, engineName, code, bShouldWork = 1): echoer = Test() model = { 'test' : util.wrap(echoer), } try: try: site = MySite(model) engine = site._AddEngine(engineName) _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED) engine.AddCode(code) engine.Start() _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_STARTED) finally: if bShouldWork: self.failUnless(not site.seen_exception, "Script site should not have seen an exception") else: self.failUnless(site.seen_exception, "Script site should have seen an exception") self.failUnless(not echoer.fail_called, "Fail should not have been called") # Now call into the scripts IDispatch from win32com.client.dynamic import Dispatch ob = Dispatch(engine.GetScriptDispatch()) ob.hello("Goober") self.assertEqual(echoer.last, "Goober") self.assertEqual(str(ob.prop), "Property Value") ob.testcollection() self.failUnless(not echoer.fail_called, "Fail should not have been called") # Now make sure my engines can evaluate stuff. result = engine.eParse.ParseScriptText("1+1", None, None, None, 0, 0, axscript.SCRIPTTEXT_ISEXPRESSION) self.assertEqual(result, 2) # re-initialize to make sure it transitions back to initialized again. engine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED) _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED) engine.Start() _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_STARTED) # Transition back to initialized, then through connected too. engine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED) _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED) engine.SetScriptState(axscript.SCRIPTSTATE_CONNECTED) _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_CONNECTED) engine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED) _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED) engine.SetScriptState(axscript.SCRIPTSTATE_CONNECTED) _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_CONNECTED) engine.SetScriptState(axscript.SCRIPTSTATE_DISCONNECTED) _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_DISCONNECTED) finally: engine.Close() engine = None site = None
def TestArrays(vbtest, bUseGenerated): # Try and use a safe array (note that the VB code has this declared as a VARIANT # and I cant work out how to force it to use native arrays! # (NOTE Python will convert incoming arrays to tuples, so we pass a tuple, even tho # a list works fine - just makes it easier for us to compare the result! # Empty array _DoTestArray(vbtest, ()) # Empty child array _DoTestArray(vbtest, ((), ())) # ints _DoTestArray(vbtest, tuple(range(1,100))) # Floats _DoTestArray(vbtest, (1.0, 2.0, 3.0)) # Strings. _DoTestArray(vbtest, tuple(string.split("Hello from Python"))) # Date and Time? # COM objects. _DoTestArray(vbtest, (vbtest, vbtest)) # Mixed _DoTestArray(vbtest, (1, 2.0, "3")) # Array alements containing other arrays _DoTestArray(vbtest, (1,(vbtest, vbtest),("3","4"))) # Multi-dimensional _DoTestArray(vbtest, (( (1,2,3), (4,5,6) ))) _DoTestArray(vbtest, (( (vbtest,vbtest,vbtest), (vbtest,vbtest,vbtest) ))) # Another dimension! arrayData = ( ((1,2),(3,4),(5,6)), ((7,8),(9,10),(11,12)) ) arrayData = ( ((vbtest,vbtest),(vbtest,vbtest),(vbtest,vbtest)), ((vbtest,vbtest),(vbtest,vbtest),(vbtest,vbtest)) ) _DoTestArray(vbtest, arrayData) # Check that when a '__getitem__ that fails' object is the first item # in the structure, we don't mistake it for a sequence. _DoTestArray(vbtest, (vbtest, 2.0, "3")) _DoTestArray(vbtest, (1, 2.0, vbtest)) # Pass arbitrarily sized arrays - these used to fail, but thanks to # Stefan Schukat, they now work! expected_exception = None arrayData = ( ((1,2,1),(3,4),(5,6)), ((7,8),(9,10),(11,12)) ) _DoTestArray(vbtest, arrayData, expected_exception) arrayData = ( ((vbtest,vbtest),), ((vbtest,),)) _DoTestArray(vbtest, arrayData, expected_exception) # Pass bad data - last item wrong size arrayData = ( ((1,2),(3,4),(5,6,8)), ((7,8),(9,10),(11,12)) ) _DoTestArray(vbtest, arrayData, expected_exception) # byref safearray results with incorrect size. callback_ob = wrap(TestObject(), useDispatcher = useDispatcher) print "** Expecting a 'ValueError' exception to be printed next:" try: vbtest.DoCallbackSafeArraySizeFail(callback_ob) except pythoncom.com_error, (hr, msg, exc, arg): assert exc[1] == "Python COM Server Internal Error", "Didnt get the correct exception - '%s'" % (exc,)
def MimeToMapi (self, mimestream, m, flag = 0) : if self.converter == None : ## CLSID_IConverterSession clsid = pywintypes.IID('{4e3a7680-b77a-11d0-9da5-00c04fd65685}') ## IID_IConverterSession iid = pywintypes.IID('{4b401570-b77b-11d0-9da5-00c04fd65685}') tmp = pythoncom.CoCreateInstance (clsid, None, pythoncom.CLSCTX_INPROC_SERVER, pythoncom.IID_IUnknown) self.converter = tmp.QueryInterface (iid) Istrm = util.wrap (util.FileStream(mimestream), pythoncom.IID_IStream) self.converter.MIMEToMAPI(Istrm, m, flag)
def TestEngine(engineName, code, bShouldWork=1): echoer = Test() model = {"test": util.wrap(echoer)} site = MySite(model) engine = site._AddEngine(engineName) engine.AddCode(code, axscript.SCRIPTTEXT_ISPERSISTENT) try: engine.Start() finally: if not bShouldWork: engine.Close() return doTestEngine(engine, echoer) # re-transition the engine back to the UNINITIALIZED state, a-la ASP. engine.eScript.SetScriptState(axscript.SCRIPTSTATE_UNINITIALIZED) engine.eScript.SetScriptSite(util.wrap(site)) print "restarting" engine.Start() # all done! engine.Close()
def test(): # Call via a native interface. com_server = wrap(TestServer(), pythoncom.IID_IStream) try: com_server.Clone() except pythoncom.com_error, com_exc: hr, desc, exc, argErr = com_exc if hr != winerror.E_UNEXPECTED: raise error("Calling the object natively did not yield the correct scode", com_exc) if not exc or exc[-1] != winerror.E_UNEXPECTED: raise error("The scode element of the exception tuple did not yield the correct scode", com_exc) if exc[2] != "Not today": raise error("The description in the exception tuple did not yield the correct string", com_exc)
def AddEngine(self, engine): """Adds a new engine to the site. engine can be a string, or a fully wrapped engine object. """ if type(engine)==type(''): newEngine = AXEngine(util.wrap(self), engine) else: newEngine = engine self.engine = newEngine flags = axscript.SCRIPTITEM_ISVISIBLE | axscript.SCRIPTITEM_NOCODE | axscript.SCRIPTITEM_GLOBALMEMBERS | axscript.SCRIPTITEM_ISPERSISTENT for name in self.objModel.iterkeys(): newEngine.AddNamedItem(name, flags) newEngine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED) return newEngine
def TestEngine(engineName, code, bShouldWork=1): echoer = Test() model = { 'test': util.wrap(echoer), } site = MySite(model) engine = site._AddEngine(engineName) engine.AddCode(code, axscript.SCRIPTTEXT_ISPERSISTENT) try: engine.Start() finally: if not bShouldWork: engine.Close() return doTestEngine(engine, echoer) # re-transition the engine back to the UNINITIALIZED state, a-la ASP. engine.eScript.SetScriptState(axscript.SCRIPTSTATE_UNINITIALIZED) engine.eScript.SetScriptSite(util.wrap(site)) print("restarting") engine.Start() # all done! engine.Close()
def test(): # Call via a native interface. com_server = wrap(TestServer(), pythoncom.IID_IStream) try: com_server.Clone() raise error("Expecting this call to fail!") except pythoncom.com_error, com_exc: if com_exc.hresult != winerror.E_UNEXPECTED: raise error("Calling the object natively did not yield the correct scode", com_exc) exc = com_exc.excepinfo if not exc or exc[-1] != winerror.E_UNEXPECTED: raise error("The scode element of the exception tuple did not yield the correct scode", com_exc) if exc[2] != "Not today": raise error("The description in the exception tuple did not yield the correct string", com_exc)
def TestMultiInterface(): o = wrap(Dummy2(), pythoncom.IID_IPersistStorage) o2 = o.QueryInterface(pythoncom.IID_IExternalConnection) FailObjectIdentity(o, o2, "IID_IPersistStorage->IID_IExternalConnection") # Make the same QI again, to make sure it is stable. o22 = o.QueryInterface(pythoncom.IID_IExternalConnection) FailObjectIdentity(o, o22, "IID_IPersistStorage->IID_IExternalConnection") FailObjectIdentity(o2, o22, "IID_IPersistStorage->IID_IExternalConnection (stability)") o3 = o2.QueryInterface(pythoncom.IID_IPersistStorage) FailObjectIdentity(o2, o3, "IID_IExternalConnection->IID_IPersistStorage") FailObjectIdentity(o, o3, "IID_IPersistStorage->IID_IExternalConnection->IID_IPersistStorage")
def AddEngine(self, engine): """Adds a new engine to the site. engine can be a string, or a fully wrapped engine object. """ if type(engine) == type(''): newEngine = AXEngine(util.wrap(self), engine) else: newEngine = engine self.engine = newEngine flags = axscript.SCRIPTITEM_ISVISIBLE | axscript.SCRIPTITEM_NOCODE | axscript.SCRIPTITEM_GLOBALMEMBERS | axscript.SCRIPTITEM_ISPERSISTENT for name in self.objModel.iterkeys(): newEngine.AddNamedItem(name, flags) newEngine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED) return newEngine
def connect(self, event_driven=True): """ Connects to the RTD server. Set event_driven to false if you to disable update notifications. In this case you'll need to call refresh_data manually. """ dispatch = client.Dispatch(self._classid) self._rtd = client.CastTo(dispatch, 'IRtdServer') if event_driven: self._rtd.ServerStart(wrap(self)) else: self._rtd.ServerStart(None)
def wrap_complex_type(data, data_type): for membername, membertype in data_type.soap_members.items(): member = getattr(data, membername) if isinstance(member, ClassSerializer): member = wrap_complex_type(member, membertype) elif type(member) in [types.ListType, types.TupleType]: newmember = [] for item in member: if isinstance(item, ClassSerializer): item = wrap_complex_type(item, item.__class__) newmember.append(item) member = newmember setattr(data, membername, member) data = util.wrap(data) return data
def create_window(self): message_map = { win32con.WM_SIZE: self.OnSize, win32con.WM_DESTROY: self.OnDestroy, } wc = win32gui.WNDCLASS() wc.lpszClassName = self.wnd_class_name # wc.style = win32con.CS_GLOBALCLASS|win32con.CS_VREDRAW | win32con.CS_HREDRAW # wc.hbrBackground = win32con.COLOR_WINDOW+1 wc.lpfnWndProc = message_map class_atom = win32gui.RegisterClass(wc) self.hwnd = win32gui.CreateWindow( wc.lpszClassName, "Embedded browser", win32con.WS_OVERLAPPEDWINDOW | win32con.WS_VISIBLE, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, 0, None, ) browser = pythoncom.CoCreateInstance( "{8856F961-340A-11D0-A96B-00C04FD705A2}", None, pythoncom.CLSCTX_INPROC_SERVER | pythoncom.CLSCTX_INPROC_HANDLER, axcontrol.IID_IOleObject, ) self.browser = browser site = wrap( SimpleSite(self), axcontrol.IID_IOleClientSite, useDispatcher=debugging ) browser.SetClientSite(site) browser.SetHostNames("IE demo", "Hi there") axcontrol.OleSetContainedObject(self.browser, True) rect = win32gui.GetWindowRect(self.hwnd) browser.DoVerb(axcontrol.OLEIVERB_SHOW, None, site, -1, self.hwnd, rect) b2 = Dispatch(browser.QueryInterface(pythoncom.IID_IDispatch)) self.browser2 = b2 b2.Left = 0 b2.Top = 0 b2.Width = rect[2] b2.Height = rect[3]
def BindToObject(self, pidl, bc, iid): # We may be passed a set of relative PIDLs here - ie # [pidl_of_dir, pidl_of_child_dir, pidl_of_file, pidl_of_function] # But each of our PIDLs keeps the fully qualified name anyway - so # just jump directly to the last. final_pidl = pidl[-1] typ, extra = final_pidl.split('\0', 1) if typ == "directory": klass = ShellFolderDirectory elif typ == "file": klass = ShellFolderFile elif typ == "object": klass = ShellFolderObject else: raise RuntimeError, "What is " + repr(typ) ret = wrap(klass(extra), iid, useDispatcher = (debug>0)) return ret
def BindToObject(self, pidl, bc, iid): # We may be passed a set of relative PIDLs here - ie # [pidl_of_dir, pidl_of_child_dir, pidl_of_file, pidl_of_function] # But each of our PIDLs keeps the fully qualified name anyway - so # just jump directly to the last. final_pidl = pidl[-1] typ, extra = final_pidl.split('\0', 1) if typ == "directory": klass = ShellFolderDirectory elif typ == "file": klass = ShellFolderFile elif typ == "object": klass = ShellFolderObject else: raise RuntimeError("What is " + repr(typ)) ret = wrap(klass(extra), iid, useDispatcher=(debug > 0)) return ret
def test(): # Call via a native interface. com_server = wrap(TestServer(), pythoncom.IID_IStream) try: com_server.Clone() except pythoncom.com_error, com_exc: hr, desc, exc, argErr = com_exc if hr != winerror.E_UNEXPECTED: raise error( "Calling the object natively did not yield the correct scode", com_exc) if not exc or exc[-1] != winerror.E_UNEXPECTED: raise error( "The scode element of the exception tuple did not yield the correct scode", com_exc) if exc[2] != "Not today": raise error( "The description in the exception tuple did not yield the correct string", com_exc)
def MimeToMapi(self, eml, m, flag=0): if self.converter == None: clsid = win32com.mapi.mapi.CLSID_IConverterSession iid = win32com.mapi.mapi.IID_IConverterSession try: tmp = pythoncom.CoCreateInstance( clsid, None, pythoncom.CLSCTX_INPROC_SERVER, pythoncom.IID_IUnknown) self.converter = tmp.QueryInterface(iid) except: # Test for ClickToRun version of Outlook and manually load library and create instance for iconvpath in ("", "16.0", "15.0"): regpath = os.path.join("Software", "Microsoft", "Office", iconvpath, "ClickToRun", "Registry", "Machine", "Software", "Classes") if platform.machine() == "AMD64" and platform.architecture( )[0] == "32bit": # 32bit application on 64bit platform regpath = os.path.join(regpath, "Wow6432Node") regpath = os.path.join(regpath, "CLSID", str(clsid), "InprocServer32") self.converter = self.CoCreateInstanceC2R( winreg.HKEY_LOCAL_MACHINE, regpath, clsid, iid) if self.converter != None: break if self.converter == None: NameError( "mapi:MimeToMapi : Can not create IConverterSession instance" ) # Open file as IStream. Don't use win32com.mapi.mapi.OpenStreamOnFile as it doesn't # handle Unicode file names f = open(eml, "rb") Istrm = util.wrap(FileStream(f), pythoncom.IID_IUnknown, None, True) self.converter.MIMEToMAPI(Istrm, m, flag)
def TestGatewayInheritance(): # By default, wrap() creates and discards a temporary object. # This is not necessary, but just the current implementation of wrap. # As the object is correctly discarded, it doesnt affect this test. o = wrap(Dummy(), pythoncom.IID_IPersistStorage) o2 = o.QueryInterface(pythoncom.IID_IUnknown) FailObjectIdentity(o, o2, "IID_IPersistStorage->IID_IUnknown") o3 = o2.QueryInterface(pythoncom.IID_IDispatch) FailObjectIdentity(o2, o3, "IID_IUnknown->IID_IDispatch") FailObjectIdentity(o, o3, "IID_IPersistStorage->IID_IDispatch") o4 = o3.QueryInterface(pythoncom.IID_IPersistStorage) FailObjectIdentity(o, o4, "IID_IPersistStorage->IID_IPersistStorage(2)") FailObjectIdentity(o2, o4, "IID_IUnknown->IID_IPersistStorage(2)") FailObjectIdentity(o3, o4, "IID_IDispatch->IID_IPersistStorage(2)") o5 = o4.QueryInterface(pythoncom.IID_IPersist) FailObjectIdentity(o, o5, "IID_IPersistStorage->IID_IPersist") FailObjectIdentity(o2, o5, "IID_IUnknown->IID_IPersist") FailObjectIdentity(o3, o5, "IID_IDispatch->IID_IPersist") FailObjectIdentity(o4, o5, "IID_IPersistStorage(2)->IID_IPersist")
print(err.GetErrorDescription()) def JobModification(self, job, reserved): state = job.GetState() print("Job Modification", job.GetDisplayName(), states.get(state)) # Need to catch TRANSIENT_ERROR here, as JobError doesn't get # called (apparently) when the error is transient. if state == bits.BG_JOB_STATE_TRANSIENT_ERROR: print("Error details:") err = job.GetError() self._print_error(err) job = bcm.CreateJob(job_name, bits.BG_JOB_TYPE_DOWNLOAD) job.SetNotifyInterface(wrap(BackgroundJobCallback())) job.SetNotifyFlags(bits.BG_NOTIFY_JOB_TRANSFERRED | bits.BG_NOTIFY_JOB_ERROR | bits.BG_NOTIFY_JOB_MODIFICATION) # The idea here is to intentionally make one of the files fail to be # downloaded. Then the JobError notification will be triggered, where # we do fix the failing file by calling SetRemoteName to a valid URL # and call Resume() on the job, making the job finish successfully. # # Note to self: A domain that cannot be resolved will cause # TRANSIENT_ERROR instead of ERROR, and the JobError notification will # not be triggered! This can bite you during testing depending on how # your DNS is configured. For example, if you use OpenDNS.org's DNS # servers, an invalid hostname will *always* be resolved (they # redirect you to a search page), so be careful when testing. job.AddFile("http://www.python.org/favicon.ico", os.path.join(tempfile.gettempdir(), "bits-favicon.ico"))
def getPage(self, site, title): os.chdir(pywikipediaDir) siteObj = unwrap(site) page = WikiPage(siteObj, title) return wrap(page)
raise error("Expecting this call to fail!") except pythoncom.com_error, com_exc: if com_exc.hresult != winerror.E_FAIL: raise error("The hresult was not E_FAIL for an internal error", com_exc) if com_exc.excepinfo[1] != "Python COM Server Internal Error": raise error( "The description in the exception tuple did not yield the correct string", com_exc) # Check we saw a traceback in stderr if cap.get_captured().find("Traceback") < 0: raise error("Could not find a traceback in stderr: %r" % (cap.get_captured(), )) # Now do it all again, but using IDispatch com_server = Dispatch(wrap(TestServer())) try: com_server.Clone() raise error("Expecting this call to fail!") except pythoncom.com_error, com_exc: if com_exc.hresult != winerror.DISP_E_EXCEPTION: raise error( "Calling the object via IDispatch did not yield the correct scode", com_exc) exc = com_exc.excepinfo if not exc or exc[-1] != winerror.E_UNEXPECTED: raise error( "The scode element of the exception tuple did not yield the correct scode", com_exc) if exc[2] != "Not today": raise error(
def Method1(self): return wrap(CPippo())
def WrapCOMObject(ob, iid=None): return wrap(ob, iid=iid, useDispatcher = 0)
def _CreateInstance_(self, reqClsid, reqIID): if reqClsid == clsid: return serverutil.wrap(XLPython(), reqIID) print reqClsid else: return BaseDefaultPolicy._CreateInstance_(self, clsid, reqIID)
print(err.GetErrorDescription()) def JobModification(self, job, reserved): state = job.GetState() print("Job Modification", job.GetDisplayName(), states.get(state)) # Need to catch TRANSIENT_ERROR here, as JobError doesn't get # called (apparently) when the error is transient. if state == bits.BG_JOB_STATE_TRANSIENT_ERROR: print("Error details:") err = job.GetError() self._print_error(err) job = bcm.CreateJob(job_name, bits.BG_JOB_TYPE_DOWNLOAD) job.SetNotifyInterface(wrap(BackgroundJobCallback())) job.SetNotifyFlags(bits.BG_NOTIFY_JOB_TRANSFERRED | bits.BG_NOTIFY_JOB_ERROR | bits.BG_NOTIFY_JOB_MODIFICATION) # The idea here is to intentionally make one of the files fail to be # downloaded. Then the JobError notification will be triggered, where # we do fix the failing file by calling SetRemoteName to a valid URL # and call Resume() on the job, making the job finish successfully. # # Note to self: A domain that cannot be resolved will cause # TRANSIENT_ERROR instead of ERROR, and the JobError notification will # not be triggered! This can bite you during testing depending on how # your DNS is configured. For example, if you use OpenDNS.org's DNS # servers, an invalid hostname will *always* be resolved (they # redirect you to a search page), so be careful when testing.
try: com_server.Commit(0) finally: cap.release() raise error("Expecting this call to fail!") except pythoncom.com_error, com_exc: if com_exc.hresult != winerror.E_FAIL: raise error("The hresult was not E_FAIL for an internal error", com_exc) if com_exc.excepinfo[1] != "Python COM Server Internal Error": raise error("The description in the exception tuple did not yield the correct string", com_exc) # Check we saw a traceback in stderr if cap.get_captured().find("Traceback")<0: raise error("Could not find a traceback in stderr: %r" % (cap.get_captured(),)) # Now do it all again, but using IDispatch com_server = Dispatch(wrap(TestServer())) try: com_server.Clone() raise error("Expecting this call to fail!") except pythoncom.com_error, com_exc: if com_exc.hresult != winerror.DISP_E_EXCEPTION: raise error("Calling the object via IDispatch did not yield the correct scode", com_exc) exc = com_exc.excepinfo if not exc or exc[-1] != winerror.E_UNEXPECTED: raise error("The scode element of the exception tuple did not yield the correct scode", com_exc) if exc[2] != "Not today": raise error("The description in the exception tuple did not yield the correct string", com_exc) cap.clear() try: cap.capture()
def TestVB( vbtest, bUseGenerated ): vbtest.LongProperty = -1 if vbtest.LongProperty != -1: raise error, "Could not set the long property correctly." vbtest.IntProperty = 10 if vbtest.IntProperty != 10: raise error, "Could not set the integer property correctly." vbtest.VariantProperty = 10 if vbtest.VariantProperty != 10: raise error, "Could not set the variant integer property correctly." vbtest.VariantProperty = buffer('raw\0data') if vbtest.VariantProperty != buffer('raw\0data'): raise error, "Could not set the variant buffer property correctly." vbtest.StringProperty = "Hello from Python" if vbtest.StringProperty != "Hello from Python": raise error, "Could not set the string property correctly." vbtest.VariantProperty = "Hello from Python" if vbtest.VariantProperty != "Hello from Python": raise error, "Could not set the variant string property correctly." vbtest.VariantProperty = (1.0, 2.0, 3.0) if vbtest.VariantProperty != (1.0, 2.0, 3.0): raise error, "Could not set the variant property to an array of floats correctly - '%s'." % (vbtest.VariantProperty,) TestArrays(vbtest, bUseGenerated) TestStructs(vbtest) TestCollections(vbtest) assert vbtest.TakeByValObject(vbtest)==vbtest # Python doesnt support PUTREF properties without a typeref # (although we could) if bUseGenerated: ob = vbtest.TakeByRefObject(vbtest) assert ob[0]==vbtest and ob[1]==vbtest # A property that only has PUTREF defined. vbtest.VariantPutref = vbtest if vbtest.VariantPutref._oleobj_!= vbtest._oleobj_: raise error, "Could not set the VariantPutref property correctly." # Cant test further types for this VariantPutref, as only # COM objects can be stored ByRef. # A "set" type property - only works for generated. # VB recognizes a collection via a few "private" interfaces that we # could later build support in for. # vbtest.CollectionProperty = NewCollection((1,2,"3", "Four")) # if vbtest.CollectionProperty != (1,2,"3", "Four"): # raise error, "Could not set the Collection property correctly - got back " + str(vbtest.CollectionProperty) # These are sub's that have a single byref param # Result should be just the byref. if vbtest.IncrementIntegerParam(1) != 2: raise error, "Could not pass an integer byref" # Sigh - we cant have *both* "ommited byref" and optional args # We really have to opt that args nominated as optional work as optional # rather than simply all byrefs working as optional. # if vbtest.IncrementIntegerParam() != 1: # raise error, "Could not pass an omitted integer byref" if vbtest.IncrementVariantParam(1) != 2: raise error, "Could not pass an int VARIANT byref:"+str(vbtest.IncrementVariantParam(1)) if vbtest.IncrementVariantParam(1.5) != 2.5: raise error, "Could not pass a float VARIANT byref" # Can't test IncrementVariantParam with the param omitted as it # it not declared in the VB code as "Optional" callback_ob = wrap(TestObject(), useDispatcher = useDispatcher) vbtest.DoSomeCallbacks(callback_ob) ret = vbtest.PassIntByVal(1) if ret != 2: raise error, "Could not increment the integer - "+str(ret) TestVBInterface(vbtest) # Python doesnt support byrefs without some sort of generated support. if bUseGenerated: # This is a VB function that takes a single byref # Hence 2 return values - function and byref. ret = vbtest.PassIntByRef(1) if ret != (1,2): raise error, "Could not increment the integer - "+str(ret)
def _CreateInstance_(self, reqClsid, reqIID): if reqClsid == clsid: return serverutil.wrap(XLPython(), reqIID) else: return BaseDefaultPolicy._CreateInstance_(self, clsid, reqIID)
def _query_interface_(self, iid): if iid==pythoncom.IID_IExternalConnection: # This will NEVER work - can only wrap the object once! return wrap(DelegatedDummy())
def GetSetInterface(self, ininterface): return wrap(self)
def SetGames(self, rom_name): """ Return the IGames interface, by wrapping the object. """ games = IGames() wrapped_games = wrap (games) return wrapped_games
def SetSettings(self): settings = ISettings() Settings = wrap( settings ) return Settings