home *** CD-ROM | disk | FTP | other *** search
/ PC World 2002 May / PCWorld_2002-05_cd.bin / Software / TemaCD / activepython / ActivePython-2.1.1.msi / Python21_win32com_test_testPyComTest.py < prev    next >
Encoding:
Python Source  |  2001-07-26  |  10.1 KB  |  311 lines

  1. # NOTE - Still seems to be a leak here somewhere
  2. # gateway count doesnt hit zero.  Hence the print statements!
  3.  
  4. import sys; sys.coinit_flags=0 # Must be free-threaded!
  5. import win32api, types, pythoncom, time
  6. import sys, win32com, win32com.client.connect
  7. from win32com.test.util import CheckClean
  8. from win32com.client import constants
  9.  
  10. 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++"
  11.  
  12. error = "testPyCOMTest error"
  13.  
  14. from win32com.client import gencache
  15. try:
  16.     PyCOMTest = gencache.EnsureModule('{6BCDCB60-5605-11D0-AE5F-CADD4C000000}', 0, 1, 1)
  17. except pythoncom.com_error:
  18.     PyCOMTest = None
  19.  
  20. if PyCOMTest is None:
  21.     print "The PyCOMTest module can not be located or generated."
  22.     print importMsg
  23.     raise RuntimeError, importMsg
  24.  
  25. import sys
  26.  
  27. verbose = 0
  28.  
  29. def TestApplyResult(fn, args, result):
  30.     try:
  31.         import string
  32.         fnName = string.split(str(fn))[1]
  33.     except:    
  34.         fnName = str(fn)
  35.     if verbose: 
  36.         print "Testing ", fnName,
  37.     pref = "function " + fnName
  38.     try:
  39.         rc  = apply(fn, args)
  40.         if rc != result:
  41.             raise error, "%s failed - result not %d but %d" % (pref, result, rc)
  42.     except:
  43.         t, v, tb = sys.exc_info()
  44.         tb = None
  45.         raise error, "%s caused exception %s,%s" % (pref, t, v)
  46.  
  47.     if verbose: print
  48.  
  49.     
  50. # Simple handler class.  This demo only fires one event.
  51. class RandomEventHandler (PyCOMTest.IPyCOMTestEvent):
  52.     def __init__(self, oobj = None):
  53.         PyCOMTest.IPyCOMTestEvent.__init__(self, oobj)
  54.         self.fireds = {}
  55.     def OnFire(self, no):
  56.         try:
  57.             self.fireds[no] = self.fireds[no] + 1
  58.         except KeyError:
  59.             self.fireds[no] = 0
  60.     def _DumpFireds(self):
  61.         if not self.fireds:
  62.             print "ERROR: Nothing was recieved!"
  63.         for firedId, no in self.fireds.items():
  64.             if verbose:
  65.                 print "ID %d fired %d times" % (firedId, no)
  66.  
  67. def TestDynamic():
  68.     if verbose: print "Testing Dynamic"
  69.     import win32com.client.dynamic
  70.     o = win32com.client.dynamic.DumbDispatch("PyCOMTest.PyCOMTest")
  71.  
  72.     if verbose: print "Getting counter"
  73.     counter = o.GetSimpleCounter()
  74.     TestCounter(counter, 0)
  75.  
  76.     if verbose: print "Checking default args"
  77.     rc = o.TestOptionals()
  78.     if  rc[:-1] != ("def", 0, 1) or abs(rc[-1]-3.14)>.01:
  79.         print rc
  80.         raise error, "Did not get the optional values correctly"
  81.     rc = o.TestOptionals("Hi", 2, 3, 1.1)
  82.     if  rc[:-1] != ("Hi", 2, 3) or abs(rc[-1]-1.1)>.01:
  83.         print rc
  84.         raise error, "Did not get the specified optional values correctly"
  85.     rc = o.TestOptionals2(0)
  86.     if  rc != (0, "", 1):
  87.         print rc
  88.         raise error, "Did not get the optional2 values correctly"
  89.     rc = o.TestOptionals2(1.1, "Hi", 2)
  90.     if  rc[1:] != ("Hi", 2) or abs(rc[0]-1.1)>.01:
  91.         print rc
  92.         raise error, "Did not get the specified optional2 values correctly"
  93.  
  94. #    if verbose: print "Testing structs"
  95.     r = o.GetStruct()
  96.     print str(r.str_value)
  97.     assert r.int_value == 99 and str(r.str_value)=="Hello from C++"
  98.     counter = win32com.client.dynamic.DumbDispatch("PyCOMTest.SimpleCounter")
  99.     TestCounter(counter, 0)
  100.     assert o.DoubleString("foo") == "foofoo"
  101.  
  102.     l=[]
  103.     TestApplyResult(o.SetVariantSafeArray, (l,), len(l))
  104.     l=[1,2,3,4]
  105.     TestApplyResult(o.SetVariantSafeArray, (l,), len(l))
  106. #    TestApplyResult(o.SetIntSafeArray, (l,), len(l))       Still fails, and probably always will.
  107.  
  108.  
  109. def TestGenerated():
  110.     # Create an instance of the server.
  111.     o=PyCOMTest.CoPyCOMTest()
  112.     counter = o.GetSimpleCounter()
  113.     TestCounter(counter, 1)
  114.     
  115.     counter = win32com.client.Dispatch("PyCOMTest.SimpleCounter")
  116.     TestCounter(counter, 1)
  117.     
  118.     i1, i2 = o.GetMultipleInterfaces()
  119.     if type(i1) != types.InstanceType or type(i2) != types.InstanceType:
  120.         # Yay - is now an instance returned!
  121.         raise error,  "GetMultipleInterfaces did not return instances - got '%s', '%s'" % (i1, i2)
  122.     del i1
  123.     del i2
  124.  
  125.     if verbose: print "Checking default args"
  126.     rc = o.TestOptionals()
  127.     if  rc[:-1] != ("def", 0, 1) or abs(rc[-1]-3.14)>.01:
  128.         print rc
  129.         raise error, "Did not get the optional values correctly"
  130.     rc = o.TestOptionals("Hi", 2, 3, 1.1)
  131.     if  rc[:-1] != ("Hi", 2, 3) or abs(rc[-1]-1.1)>.01:
  132.         print rc
  133.         raise error, "Did not get the specified optional values correctly"
  134.     rc = o.TestOptionals2(0)
  135.     if  rc != (0, "", 1):
  136.         print rc
  137.         raise error, "Did not get the optional2 values correctly"
  138.     rc = o.TestOptionals2(1.1, "Hi", 2)
  139.     if  rc[1:] != ("Hi", 2) or abs(rc[0]-1.1)>.01:
  140.         print rc
  141.         raise error, "Did not get the specified optional2 values correctly"
  142.  
  143.     if verbose: print "Checking var args"
  144.     o.SetVarArgs("Hi", "There", "From", "Python", 1)
  145.     if o.GetLastVarArgs() != ("Hi", "There", "From", "Python", 1):
  146.         raise error, "VarArgs failed -" + str(o.GetLastVarArgs())
  147.     if verbose: print "Checking getting/passing IUnknown"
  148.     if type(o.GetSetUnknown(o)) !=pythoncom.TypeIIDs[pythoncom.IID_IUnknown]:
  149.         raise error, "GetSetUnknown failed"
  150.     if verbose: print "Checking getting/passing IDispatch"
  151.     if type(o.GetSetDispatch(o)) !=types.InstanceType:
  152.         raise error, "GetSetDispatch failed"
  153.     if verbose: print "Checking getting/passing IDispatch of known type"
  154.     if o.GetSetInterface(o).__class__ != PyCOMTest.IPyCOMTest:
  155.         raise error, "GetSetDispatch failed"
  156.  
  157.     o.GetSimpleSafeArray(None)
  158.     TestApplyResult(o.GetSimpleSafeArray, (None,), tuple(range(10)))
  159.     resultCheck = tuple(range(5)), tuple(range(10)), tuple(range(20))
  160.     TestApplyResult(o.GetSafeArrays, (None, None, None), resultCheck)
  161.  
  162.     l=[1,2,3,4]
  163.     TestApplyResult(o.SetVariantSafeArray, (l,), len(l))
  164.     TestApplyResult(o.SetIntSafeArray, (l,), len(l))
  165.     l=[]
  166.     TestApplyResult(o.SetVariantSafeArray, (l,), len(l))
  167.     TestApplyResult(o.SetIntSafeArray, (l,), len(l))
  168.     # Tell the server to do what it does!
  169.     TestApplyResult(o.Test, ("Unused", 99), 1) # A bool function
  170.     TestApplyResult(o.Test, ("Unused", -1), 1) # A bool function
  171.     TestApplyResult(o.Test, ("Unused", 1==1), 1) # A bool function
  172.     TestApplyResult(o.Test, ("Unused", 0), 0)
  173.     TestApplyResult(o.Test, ("Unused", 1==0), 0)
  174.     TestApplyResult(o.Test2, (constants.Attr2,), constants.Attr2)
  175.     TestApplyResult(o.Test3, (constants.Attr2,), constants.Attr2)
  176.     TestApplyResult(o.Test4, (constants.Attr2,), constants.Attr2)
  177.     TestApplyResult(o.Test5, (constants.Attr2,), constants.Attr2)
  178.  
  179.     assert o.DoubleString("foo") == "foofoo"
  180.     assert o.DoubleInOutString("foo") == "foofoo"
  181.  
  182.     # Do the connection point thing...
  183.     # Create a connection object.
  184.     if verbose: print "Testing connection points"
  185.     sessions = []
  186.     handler = RandomEventHandler()
  187.  
  188.     try:
  189.         for i in range(3):
  190.             session = o.Start()
  191.             # Create an event handler instance, and connect it to the server.
  192.             connection = win32com.client.connect.SimpleConnection(o, handler)
  193.             sessions.append((session, connection))
  194.  
  195.         time.sleep(.5)
  196.     finally:
  197.         # Stop the servers
  198.         for session, connection in sessions:
  199.             o.Stop(session)
  200.             connection.Disconnect()
  201.         if handler: handler._DumpFireds()
  202.     if verbose: print "Finished generated .py test."
  203.  
  204. def TestCounter(counter, bIsGenerated):
  205.     # Test random access into container
  206.     if verbose: print "Testing counter", `counter`
  207.     import random
  208.     for i in xrange(50):
  209.         num = int(random.random() * len(counter))
  210.         try:
  211.             ret = counter[num]
  212.             if ret != num+1:
  213.                 raise error, "Random access into element %d failed - return was %s" % (num,`ret`)
  214.         except IndexError:    
  215.             raise error, "** IndexError accessing collection element %d" % num
  216.  
  217.     num = 0
  218.     if bIsGenerated:
  219.         counter.SetTestProperty(1)
  220.         counter.TestProperty = 1 # Note this has a second, default arg.
  221.         counter.SetTestProperty(1,2)
  222.         if counter.TestPropertyWithDef != 0:
  223.             raise error, "Unexpected property set value!"
  224.         if counter.TestPropertyNoDef(1) != 1:
  225.             raise error, "Unexpected property set value!"
  226.     else:
  227.         pass
  228.         # counter.TestProperty = 1
  229.  
  230.     counter.LBound=1
  231.     counter.UBound=10
  232.     if counter.LBound <> 1 or counter.UBound<>10:
  233.         print "** Error - counter did not keep its properties"
  234.  
  235.     if bIsGenerated:
  236.         bounds = counter.GetBounds()
  237.         if bounds[0]<>1 or bounds[1]<>10:
  238.             raise error, "** Error - counter did not give the same properties back"
  239.         counter.SetBounds(bounds[0], bounds[1])
  240.  
  241.     for item in counter:
  242.         num = num + 1
  243.     if num <> len(counter):
  244.         raise error, "*** Length of counter and loop iterations dont match ***"
  245.     if num <> 10:
  246.         raise error, "*** Unexpected number of loop iterations ***"
  247.  
  248.     counter = counter._enum_.Clone() # Test Clone() and enum directly
  249.     counter.Reset()
  250.     num = 0
  251.     for item in counter:
  252.         num = num + 1
  253.     if num <> 10:
  254.         raise error, "*** Unexpected number of loop iterations - got %d ***" % num
  255.     if verbose: print "Finished testing counter"
  256.  
  257. ###############################
  258. ##
  259. ## Some vtable tests of the interface
  260. ##
  261. def TestVTable():
  262.     tester = win32com.client.Dispatch("PyCOMTest.PyCOMTest")
  263.     testee = pythoncom.CoCreateInstance("Python.Test.PyCOMTest", None, pythoncom.CLSCTX_ALL, pythoncom.IID_IUnknown)
  264.     tester.TestMyInterface(testee)
  265.  
  266.     # We once crashed creating our object with the native interface as
  267.     # the first IID specified.  We must do it _after_ the tests, so that
  268.     # Python has already had the gateway registered from last run.
  269.     iid = pythoncom.InterfaceNames["IPyCOMTest"]
  270.     clsid = "Python.Test.PyCOMTest"
  271.     clsctx = pythoncom.CLSCTX_SERVER
  272.     try:
  273.         testee = pythoncom.CoCreateInstance(clsid, None, clsctx, iid)
  274.     except TypeError:
  275.         # Python can't actually _use_ this interface yet, so this is
  276.         # "expected".  Any COM error is not.
  277.         pass
  278.  
  279.     
  280.  
  281. def TestAll():
  282.     try:
  283.         # Make sure server installed
  284.         import win32com.client.dynamic
  285.         win32com.client.dynamic.DumbDispatch("PyCOMTest.PyCOMTest")
  286.     except pythoncom.com_error:
  287.         print importMsg
  288.         return
  289.  
  290.     print "Testing VTables..."
  291.     TestVTable()
  292.  
  293.     print "Testing Python COM Test Horse..."
  294.     TestDynamic()
  295.     TestGenerated()
  296.  
  297. if __name__=='__main__':
  298.     # XXX - todo - Complete hack to crank threading support.
  299.     # Should NOT be necessary
  300.     def NullThreadFunc():
  301.         pass
  302.     import thread
  303.     thread.start_new( NullThreadFunc, () )
  304.  
  305.     if "-q" not in sys.argv: verbose = 1
  306.     TestAll()
  307.     CheckClean()
  308.     pythoncom.CoUninitialize()
  309.     print "C++ test harness worked OK."
  310.  
  311.