Exemple #1
0
 def testComplex(self):
     if sys.hexversion < 0x2030000:
         # no kw-args to dict in 2.2 - not worth converting!
         return
     clsid = pythoncom.MakeIID("{CD637886-DB8B-4b04-98B5-25731E1495BE}")
     d = dict(cFileName="foo.txt",
              clsid=clsid,
              sizel=(1, 2),
              pointl=(3, 4),
              dwFileAttributes=win32con.FILE_ATTRIBUTE_NORMAL,
              ftCreationTime=pythoncom.MakeTime(10),
              ftLastAccessTime=pythoncom.MakeTime(11),
              ftLastWriteTime=pythoncom.MakeTime(12),
              nFileSize=sys.maxint + 1)
     self._testRT(d)
Exemple #2
0
	def getPyDateTime(self, dTDate):
		"""
		@param dTDate: A python datetime object
		@return: a pytime datetime object suitable for use with COM or Excel
		"""
		# Ignore the error in eclipse about not being able to locate the function
		return pythoncom.MakeTime(dTDate)
Exemple #3
0
def TextExcel(xl):
    xl.Visible = 0
    if xl.Visible:
        raise error("Visible property is true.")
    xl.Visible = 1
    if not xl.Visible:
        raise error("Visible property not true.")

    if int(xl.Version[0]) >= 8:
        xl.Workbooks.Add()
    else:
        xl.Workbooks().Add()

    xl.Range("A1:C1").Value = (1, 2, 3)
    xl.Range("A2:C2").Value = ("x", "y", "z")
    xl.Range("A3:C3").Value = ("3", "2", "1")

    for i in range(20):
        xl.Cells(i + 1, i + 1).Value = "Hi %d" % i

    if xl.Range("A1").Value != "Hi 0":
        raise error("Single cell range failed")

    if xl.Range("A1:B1").Value != ((Unicode("Hi 0"), 2), ):
        raise error("flat-horizontal cell range failed")

    if xl.Range("A1:A2").Value != ((Unicode("Hi 0"), ), (Unicode("x"), )):
        raise error("flat-vertical cell range failed")

    if xl.Range("A1:C3").Value != (
        (Unicode("Hi 0"), 2, 3),
        (Unicode("x"), Unicode("Hi 1"), Unicode("z")),
        (3, 2, Unicode("Hi 2")),
    ):
        raise error("square cell range failed")

    xl.Range("A1:C3").Value = ((3, 2, 1), ("x", "y", "z"), (1, 2, 3))

    if xl.Range("A1:C3").Value != (
        (3, 2, 1),
        (Unicode("x"), Unicode("y"), Unicode("z")),
        (1, 2, 3),
    ):
        raise error("Range was not what I set it to!")

    # test dates out with Excel
    xl.Cells(5, 1).Value = "Excel time"
    xl.Cells(5, 2).Formula = "=Now()"

    import time

    xl.Cells(6, 1).Value = "Python time"
    xl.Cells(6, 2).Value = pythoncom.MakeTime(time.time())
    xl.Cells(6, 2).NumberFormat = "d/mm/yy h:mm"
    xl.Columns("A:B").EntireColumn.AutoFit()

    xl.Workbooks(1).Close(0)
    xl.Quit()
def TestDict(quiet=None):
    if quiet is None:
        quiet = not "-v" in sys.argv
    Register(quiet)

    if not quiet: print("Simple enum test")
    dict = MakeTestDictionary()
    checkDict = {}
    TestDictAgainst(dict, checkDict)

    dict["NewKey"] = "NewValue"
    checkDict["NewKey"] = "NewValue"
    TestDictAgainst(dict, checkDict)

    dict["NewKey"] = None
    del checkDict["NewKey"]
    TestDictAgainst(dict, checkDict)

    if issubclass(pywintypes.TimeType, datetime.datetime):
        now = win32timezone.now()
        # We want to keep the milliseconds but discard microseconds as they
        # don't survive the conversion.
        now = now.replace(microsecond = round(now.microsecond / 1000) * 1000)
    else:
        now = pythoncom.MakeTime(time.gmtime(time.time()))
    dict["Now"] = now
    checkDict["Now"] = now
    TestDictAgainst(dict, checkDict)

    if not quiet:
        print("Failure tests")
    try:
        dict()
        raise Exception("default method with no args worked when it shouldnt have!")
    except pythoncom.com_error as xxx_todo_changeme:
        (hr, desc, exc, argErr) = xxx_todo_changeme.args
        if hr != winerror.DISP_E_BADPARAMCOUNT:
            raise Exception("Expected DISP_E_BADPARAMCOUNT - got %d (%s)" % (hr, desc))

    try:
        dict("hi", "there")
        raise Exception("multiple args worked when it shouldnt have!")
    except pythoncom.com_error as xxx_todo_changeme1:
        (hr, desc, exc, argErr) = xxx_todo_changeme1.args
        if hr != winerror.DISP_E_BADPARAMCOUNT:
            raise Exception("Expected DISP_E_BADPARAMCOUNT - got %d (%s)" % (hr, desc))

    try:
        dict(0)
        raise Exception("int key worked when it shouldnt have!")
    except pythoncom.com_error as xxx_todo_changeme2:
        (hr, desc, exc, argErr) = xxx_todo_changeme2.args
        if hr != winerror.DISP_E_TYPEMISMATCH:
            raise Exception("Expected DISP_E_TYPEMISMATCH - got %d (%s)" % (hr, desc))

    if not quiet:
        print("Python.Dictionary tests complete.")
Exemple #5
0
 def testUnicode(self):
     # exercise a bug fixed in build 210 - multiple unicode objects failed.
     if sys.hexversion < 0x2030000:
         # no kw-args to dict in 2.2 - not worth converting!
         return
     d = [
         dict(cFileName=u"foo.txt",
              sizel=(1, 2),
              pointl=(3, 4),
              dwFileAttributes=win32con.FILE_ATTRIBUTE_NORMAL,
              ftCreationTime=pythoncom.MakeTime(10),
              ftLastAccessTime=pythoncom.MakeTime(11),
              ftLastWriteTime=pythoncom.MakeTime(12),
              nFileSize=sys.maxint + 1),
         dict(cFileName=u"foo2.txt",
              sizel=(1, 2),
              pointl=(3, 4),
              dwFileAttributes=win32con.FILE_ATTRIBUTE_NORMAL,
              ftCreationTime=pythoncom.MakeTime(10),
              ftLastAccessTime=pythoncom.MakeTime(11),
              ftLastWriteTime=pythoncom.MakeTime(12),
              nFileSize=sys.maxint + 1),
         dict(cFileName=u"foo\xa9.txt",
              sizel=(1, 2),
              pointl=(3, 4),
              dwFileAttributes=win32con.FILE_ATTRIBUTE_NORMAL,
              ftCreationTime=pythoncom.MakeTime(10),
              ftLastAccessTime=pythoncom.MakeTime(11),
              ftLastWriteTime=pythoncom.MakeTime(12),
              nFileSize=sys.maxint + 1),
     ]
     s = shell.FILEGROUPDESCRIPTORAsString(d, 1)
     d2 = shell.StringAsFILEGROUPDESCRIPTOR(s)
     # clobber 'dwFlags' - they are not expected to be identical
     for t in d2:
         del t['dwFlags']
     self.assertEqual(d, d2)
Exemple #6
0
def TestCommon(o, is_generated):
    progress("Getting counter")
    counter = o.GetSimpleCounter()
    TestCounter(counter, is_generated)

    progress("Checking default args")
    rc = o.TestOptionals()
    if  rc[:-1] != ("def", 0, 1) or abs(rc[-1]-3.14)>.01:
        print(rc)
        raise error("Did not get the optional values correctly")
    rc = o.TestOptionals("Hi", 2, 3, 1.1)
    if  rc[:-1] != ("Hi", 2, 3) or abs(rc[-1]-1.1)>.01:
        print(rc)
        raise error("Did not get the specified optional values correctly")
    rc = o.TestOptionals2(0)
    if  rc != (0, "", 1):
        print(rc)
        raise error("Did not get the optional2 values correctly")
    rc = o.TestOptionals2(1.1, "Hi", 2)
    if  rc[1:] != ("Hi", 2) or abs(rc[0]-1.1)>.01:
        print(rc)
        raise error("Did not get the specified optional2 values correctly")

    progress("Checking getting/passing IUnknown")
    check_get_set(o.GetSetUnknown, o)
    progress("Checking getting/passing IDispatch")
    if not isinstance(o.GetSetDispatch(o), o.__class__):
        raise error("GetSetDispatch failed: %r" % (o.GetSetDispatch(o),))
    progress("Checking getting/passing IDispatch of known type")
    if o.GetSetInterface(o).__class__ != o.__class__:
        raise error("GetSetDispatch failed")

    progress("Checking misc args")
    check_get_set(o.GetSetVariant, 4)
    check_get_set(o.GetSetVariant, "foo")
    check_get_set(o.GetSetVariant, o)

    # signed/unsigned.
    check_get_set(o.GetSetInt, 0)
    check_get_set(o.GetSetInt, -1)
    check_get_set(o.GetSetInt, 1)

    check_get_set(o.GetSetUnsignedInt, 0)
    check_get_set(o.GetSetUnsignedInt, 1)
    check_get_set(o.GetSetUnsignedInt, 0x80000000)
    if o.GetSetUnsignedInt(-1) != 0xFFFFFFFF:
    # -1 is a special case - we accept a negative int (silently converting to
    # unsigned) but when getting it back we convert it to a long.
        raise error("unsigned -1 failed")

    check_get_set(o.GetSetLong, 0)
    check_get_set(o.GetSetLong, -1)
    check_get_set(o.GetSetLong, 1)

    check_get_set(o.GetSetUnsignedLong, 0)
    check_get_set(o.GetSetUnsignedLong, 1)
    check_get_set(o.GetSetUnsignedLong, 0x80000000)
    # -1 is a special case - see above.
    if o.GetSetUnsignedLong(-1) != 0xFFFFFFFF:
        raise error("unsigned -1 failed")

    # We want to explicitly test > 32 bits.  py3k has no 'maxint' and
    # 'maxsize+1' is no good on 64bit platforms as its 65 bits!
    big = 2147483647 # sys.maxint on py2k
    for l in big, big+1, 1 << 65:
        check_get_set(o.GetSetVariant, l)

    progress("Checking structs")
    r = o.GetStruct()
    assert r.int_value == 99 and str(r.str_value)=="Hello from C++"
    assert o.DoubleString("foo") == "foofoo"

    progress("Checking var args")
    o.SetVarArgs("Hi", "There", "From", "Python", 1)
    if o.GetLastVarArgs() != ("Hi", "There", "From", "Python", 1):
        raise error("VarArgs failed -" + str(o.GetLastVarArgs()))

    progress("Checking arrays")
    l=[]
    TestApplyResult(o.SetVariantSafeArray, (l,), len(l))
    l=[1,2,3,4]
    TestApplyResult(o.SetVariantSafeArray, (l,), len(l))
    TestApplyResult(o.CheckVariantSafeArray, ((1,2,3,4,),), 1)

    # and binary
    TestApplyResult(o.SetBinSafeArray, (str2memory('foo\0bar'),), 7)

    progress("Checking properties")
    o.LongProp = 3
    if o.LongProp != 3 or o.IntProp != 3:
        raise error("Property value wrong - got %d/%d" % (o.LongProp,o.IntProp))
    o.LongProp = o.IntProp = -3
    if o.LongProp != -3 or o.IntProp != -3:
        raise error("Property value wrong - got %d/%d" % (o.LongProp,o.IntProp))
    # This number fits in an unsigned long.  Attempting to set it to a normal
    # long will involve overflow, which is to be expected. But we do
    # expect it to work in a property explicitly a VT_UI4.
    check = 3 *10 **9
    o.ULongProp = check
    if o.ULongProp != check:
        raise error("Property value wrong - got %d (expected %d)" % (o.ULongProp, check))

    TestApplyResult(o.Test, ("Unused", 99), 1) # A bool function
    TestApplyResult(o.Test, ("Unused", -1), 1) # A bool function
    TestApplyResult(o.Test, ("Unused", 1==1), 1) # A bool function
    TestApplyResult(o.Test, ("Unused", 0), 0)
    TestApplyResult(o.Test, ("Unused", 1==0), 0)

    assert o.DoubleString("foo") == "foofoo"

    TestConstant("ULongTest1", ensure_long(0xFFFFFFFF))
    TestConstant("ULongTest2", ensure_long(0x7FFFFFFF))
    TestConstant("LongTest1", ensure_long(-0x7FFFFFFF))
    TestConstant("LongTest2", ensure_long(0x7FFFFFFF))
    TestConstant("UCharTest", 255)
    TestConstant("CharTest", -1)
    # 'Hello Loraine', but the 'r' is the "Registered" sign (\xae)
    TestConstant("StringTest", "Hello Lo\xaeaine") 

    progress("Checking dates and times")
    if issubclass(pywintypes.TimeType, datetime.datetime):
        # For now *all* times passed must be tz-aware.
        now = win32timezone.now()
        # but conversion to and from a VARIANT loses sub-second...
        now = now.replace(microsecond=0)
        later = now + datetime.timedelta(seconds=1)
        TestApplyResult(o.EarliestDate, (now, later), now)
    else:
        # old PyTime object
        now = pythoncom.MakeTime(time.gmtime(time.time()))
        later = pythoncom.MakeTime(time.gmtime(time.time()+1))
        TestApplyResult(o.EarliestDate, (now, later), now)
        # But it can still *accept* tz-naive datetime objects...
        now = datetime.datetime.now()
        expect = pythoncom.MakeTime(now)
        TestApplyResult(o.EarliestDate, (now, now), expect)

    progress("Checking currency")
    # currency.
    pythoncom.__future_currency__ = 1
    if o.CurrencyProp != 0:
        raise error("Expecting 0, got %r" % (o.CurrencyProp,))
    for val in ("1234.5678", "1234.56", "1234"):
        o.CurrencyProp = decimal.Decimal(val)
        if o.CurrencyProp != decimal.Decimal(val):
            raise error("%s got %r" % (val, o.CurrencyProp))
    v1 = decimal.Decimal("1234.5678")
    TestApplyResult(o.DoubleCurrency, (v1,), v1*2)

    v2 = decimal.Decimal("9012.3456")
    TestApplyResult(o.AddCurrencies, (v1, v2), v1+v2)

    TestTrickyTypesWithVariants(o, is_generated)
    progress("Checking win32com.client.VARIANT")
    TestPyVariant(o, is_generated)
Exemple #7
0
 def ToCOMTime(self):
     """Convert a date into COM format."""
     return pythoncom.MakeTime(self.ToUnixTime())
Exemple #8
0
def TestGenerated():
    # Create an instance of the server.
    from win32com.client.gencache import EnsureDispatch
    o = EnsureDispatch("PyCOMTest.PyCOMTest")
    counter = o.GetSimpleCounter()
    TestCounter(counter, 1)

    counter = EnsureDispatch("PyCOMTest.SimpleCounter")
    TestCounter(counter, 1)

    i1, i2 = o.GetMultipleInterfaces()
    if not isinstance(i1, DispatchBaseClass) or not isinstance(i2, DispatchBaseClass):
        # Yay - is now an instance returned!
        raise error("GetMultipleInterfaces did not return instances - got '%s', '%s'" % (i1, i2))
    del i1
    del i2

    progress("Checking default args")
    rc = o.TestOptionals()
    if  rc[:-1] != ("def", 0, 1) or abs(rc[-1]-3.14)>.01:
        print rc
        raise error("Did not get the optional values correctly")
    rc = o.TestOptionals("Hi", 2, 3, 1.1)
    if  rc[:-1] != ("Hi", 2, 3) or abs(rc[-1]-1.1)>.01:
        print rc
        raise error("Did not get the specified optional values correctly")
    rc = o.TestOptionals2(0)
    if  rc != (0, "", 1):
        print rc
        raise error("Did not get the optional2 values correctly")
    rc = o.TestOptionals2(1.1, "Hi", 2)
    if  rc[1:] != ("Hi", 2) or abs(rc[0]-1.1)>.01:
        print rc
        raise error("Did not get the specified optional2 values correctly")

    progress("Checking var args")
    o.SetVarArgs("Hi", "There", "From", "Python", 1)
    if o.GetLastVarArgs() != ("Hi", "There", "From", "Python", 1):
        raise error("VarArgs failed -" + str(o.GetLastVarArgs()))
    progress("Checking getting/passing IUnknown")
    if o.GetSetUnknown(o) != o:
        raise error("GetSetUnknown failed")
    progress("Checking getting/passing IDispatch")
    if not isinstance(o.GetSetDispatch(o), DispatchBaseClass):
        raise error("GetSetDispatch failed")
    progress("Checking getting/passing IDispatch of known type")
    if o.GetSetInterface(o).__class__ != o.__class__:
        raise error("GetSetDispatch failed")
    if o.GetSetVariant(4) != 4:
        raise error("GetSetVariant (int) failed")
    if o.GetSetVariant("foo") != "foo":
        raise error("GetSetVariant (str) failed")
    if o.GetSetVariant(o) != o:
        raise error("GetSetVariant (dispatch) failed")
    # We want to explicitly test > 32 bits.  py3k has no 'maxint' and
    # 'maxsize+1' is no good on 64bit platforms as its 65 bits!
    big = 2147483647 # sys.maxint on py2k
    for l in big, big+1, 1 << 65:
        if o.GetSetVariant(l) != l:
            raise error("GetSetVariant (long) failed")
    if o.TestByRefVariant(2) != 4:
        raise error("TestByRefVariant failed")
    if o.TestByRefString("Foo") != "FooFoo":
        raise error("TestByRefString failed")

    # Pass some non-sequence objects to our array decoder, and watch it fail.
    try:
        o.SetVariantSafeArray("foo")
        raise error("Expected a type error")
    except TypeError:
        pass
    try:
        o.SetVariantSafeArray(666)
        raise error("Expected a type error")
    except TypeError:
        pass

    o.GetSimpleSafeArray(None)
    TestApplyResult(o.GetSimpleSafeArray, (None,), tuple(range(10)))
    resultCheck = tuple(range(5)), tuple(range(10)), tuple(range(20))
    TestApplyResult(o.GetSafeArrays, (None, None, None), resultCheck)

    l=[1,2,3,4]
    TestApplyResult(o.SetVariantSafeArray, (l,), len(l))
    TestApplyResult(o.SetIntSafeArray, (l,), len(l))
    ll=[1,2,3,0x100000000]
    TestApplyResult(o.SetLongLongSafeArray, (ll,), len(ll))
    TestApplyResult(o.SetULongLongSafeArray, (ll,), len(ll))
    # check we can pass ints as a VT_UI1
    TestApplyResult(o.SetBinSafeArray, (l,), len(l))
    # and binary
    TestApplyResult(o.SetBinSafeArray, (str2memory('foo\0bar'),), 7)

    l=[]
    TestApplyResult(o.SetVariantSafeArray, (l,), len(l))
    TestApplyResult(o.SetIntSafeArray, (l,), len(l))
    # Tell the server to do what it does!
    TestApplyResult(o.Test, ("Unused", 99), 1) # A bool function
    TestApplyResult(o.Test, ("Unused", -1), 1) # A bool function
    TestApplyResult(o.Test, ("Unused", 1==1), 1) # A bool function
    TestApplyResult(o.Test, ("Unused", 0), 0)
    TestApplyResult(o.Test, ("Unused", 1==0), 0)
    TestApplyResult(o.Test2, (constants.Attr2,), constants.Attr2)
    TestApplyResult(o.Test3, (constants.Attr2,), constants.Attr2)
    TestApplyResult(o.Test4, (constants.Attr2,), constants.Attr2)
    TestApplyResult(o.Test5, (constants.Attr2,), constants.Attr2)

    TestApplyResult(o.Test6, (constants.WideAttr1,), constants.WideAttr1)
    TestApplyResult(o.Test6, (constants.WideAttr2,), constants.WideAttr2)
    TestApplyResult(o.Test6, (constants.WideAttr3,), constants.WideAttr3)
    TestApplyResult(o.Test6, (constants.WideAttr4,), constants.WideAttr4)
    TestApplyResult(o.Test6, (constants.WideAttr5,), constants.WideAttr5)

    TestConstant("ULongTest1", ensure_long(0xFFFFFFFF))
    TestConstant("ULongTest2", ensure_long(0x7FFFFFFF))
    TestConstant("LongTest1", ensure_long(-0x7FFFFFFF))
    TestConstant("LongTest2", ensure_long(0x7FFFFFFF))
    TestConstant("UCharTest", 255)
    TestConstant("CharTest", -1)
    # 'Hello Loraine', but the 'r' is the "Registered" sign (\xae)
    TestConstant("StringTest", u"Hello Lo\xaeaine") 

    if issubclass(pywintypes.TimeType, datetime.datetime):
        # For now *all* times passed must be tz-aware.
        now = win32timezone.now()
        # but conversion to and from a VARIANT loses sub-second...
        now = now.replace(microsecond=0)
        later = now + datetime.timedelta(seconds=1)
        TestApplyResult(o.EarliestDate, (now, later), now)
    else:
        # old PyTime object
        now = pythoncom.MakeTime(time.gmtime(time.time()))
        later = pythoncom.MakeTime(time.gmtime(time.time()+1))
        TestApplyResult(o.EarliestDate, (now, later), now)
        # But it can still *accept* tz-naive datetime objects...
        now = datetime.datetime.now()
        expect = pythoncom.MakeTime(now)
        TestApplyResult(o.EarliestDate, (now, now), expect)

    assert o.DoubleString("foo") == "foofoo"
    assert o.DoubleInOutString("foo") == "foofoo"

    o.LongProp = 3
    if o.LongProp != 3 or o.IntProp != 3:
        raise error("Property value wrong - got %d/%d" % (o.LongProp,o.IntProp))

    o.LongProp = o.IntProp = -3
    if o.LongProp != -3 or o.IntProp != -3:
        raise error("Property value wrong - got %d/%d" % (o.LongProp,o.IntProp))

    check = 3 *10 **9
    o.ULongProp = check
    if o.ULongProp != check:
        raise error("Property value wrong - got %d (expected %d)" % (o.ULongProp, check))

    # currency.
    pythoncom.__future_currency__ = 1
    if o.CurrencyProp != 0:
        raise error("Expecting 0, got %r" % (o.CurrencyProp,))
    try:
        import decimal
    except ImportError:
        import win32com.decimal_23 as decimal
    for val in ("1234.5678", "1234.56", "1234"):
        o.CurrencyProp = decimal.Decimal(val)
        if o.CurrencyProp != decimal.Decimal(val):
            raise error("%s got %r" % (val, o.CurrencyProp))
    v1 = decimal.Decimal("1234.5678")
    TestApplyResult(o.DoubleCurrency, (v1,), v1*2)
    TestApplyResult(o.DoubleCurrencyByVal, (v1,), v1*2)
    v2 = decimal.Decimal("9012.3456")
    TestApplyResult(o.AddCurrencies, (v1, v2), v1+v2)

    o.SetParamProp(0, 1)
    if o.ParamProp(0) != 1:
        raise RuntimeError(o.paramProp(0))

    # Do the connection point thing...
    # Create a connection object.
    progress("Testing connection points")
    sessions = []
    o = win32com.client.DispatchWithEvents( o, RandomEventHandler)
    o._Init()

    try:
        for i in range(3):
            session = o.Start()
            sessions.append(session)
        time.sleep(.5)
    finally:
        # Stop the servers
        for session in sessions:
            o.Stop(session)
        o._DumpFireds()
    progress("Finished generated .py test.")
Exemple #9
0
def TestDynamic():
    progress("Testing Dynamic")
    import win32com.client.dynamic
    o = win32com.client.dynamic.DumbDispatch("PyCOMTest.PyCOMTest")

    progress("Getting counter")
    counter = o.GetSimpleCounter()
    TestCounter(counter, 0)

    progress("Checking default args")
    rc = o.TestOptionals()
    if  rc[:-1] != ("def", 0, 1) or abs(rc[-1]-3.14)>.01:
        print rc
        raise error("Did not get the optional values correctly")
    rc = o.TestOptionals("Hi", 2, 3, 1.1)
    if  rc[:-1] != ("Hi", 2, 3) or abs(rc[-1]-1.1)>.01:
        print rc
        raise error("Did not get the specified optional values correctly")
    rc = o.TestOptionals2(0)
    if  rc != (0, "", 1):
        print rc
        raise error("Did not get the optional2 values correctly")
    rc = o.TestOptionals2(1.1, "Hi", 2)
    if  rc[1:] != ("Hi", 2) or abs(rc[0]-1.1)>.01:
        print rc
        raise error("Did not get the specified optional2 values correctly")

#       if verbose: print "Testing structs"
    r = o.GetStruct()
    assert r.int_value == 99 and str(r.str_value)=="Hello from C++"
    counter = win32com.client.dynamic.DumbDispatch("PyCOMTest.SimpleCounter")
    TestCounter(counter, 0)
    assert o.DoubleString("foo") == "foofoo"

    l=[]
    TestApplyResult(o.SetVariantSafeArray, (l,), len(l))
    l=[1,2,3,4]
    TestApplyResult(o.SetVariantSafeArray, (l,), len(l))
#       TestApplyResult(o.SetIntSafeArray, (l,), len(l))       Still fails, and probably always will.
    TestApplyResult(o.CheckVariantSafeArray, ((1,2,3,4,),), 1)
    o.LongProp = 3
    if o.LongProp != 3 or o.IntProp != 3:
        raise error("Property value wrong - got %d/%d" % (o.LongProp,o.IntProp))
    o.LongProp = o.IntProp = -3
    if o.LongProp != -3 or o.IntProp != -3:
        raise error("Property value wrong - got %d/%d" % (o.LongProp,o.IntProp))
    # This number fits in an unsigned long.  Attempting to set it to a normal
    # long will involve overflow, which is to be expected. But we do
    # expect it to work in a property explicitly a VT_UI4.
    check = 3 *10 **9
    o.ULongProp = check
    if o.ULongProp != check:
        raise error("Property value wrong - got %d (expected %d)" % (o.ULongProp, check))
    # currency.
    pythoncom.__future_currency__ = 1
    if o.CurrencyProp != 0:
        raise error("Expecting 0, got %r" % (o.CurrencyProp,))
    try:
        import decimal
    except ImportError:
        import win32com.decimal_23 as decimal
    o.CurrencyProp = decimal.Decimal("1234.5678")
    if o.CurrencyProp != decimal.Decimal("1234.5678"):
        raise error("got %r" % (o.CurrencyProp,))
    v1 = decimal.Decimal("1234.5678")
    # can't do "DoubleCurrencyByVal" in dynamic files.
    TestApplyResult(o.DoubleCurrency, (v1,), v1*2)
    v2 = decimal.Decimal("9012.3456")
    TestApplyResult(o.AddCurrencies, (v1, v2), v1+v2)

    # damn - props with params don't work for dynamic objects :(
    # o.SetParamProp(0, 1)
    # if o.ParamProp(0) != 1:
    #    raise RuntimeError, o.paramProp(0)

    if issubclass(pywintypes.TimeType, datetime.datetime):
        # For now *all* times passed must be tz-aware.
        now = win32timezone.now()
        # but conversion to and from a VARIANT loses sub-second...
        now = now.replace(microsecond=0)
        later = now + datetime.timedelta(seconds=1)
        TestApplyResult(o.EarliestDate, (now, later), now)
    else:
        # old PyTime object
        now = pythoncom.MakeTime(time.gmtime(time.time()))
        later = pythoncom.MakeTime(time.gmtime(time.time()+1))
        TestApplyResult(o.EarliestDate, (now, later), now)
        # But it can still *accept* tz-naive datetime objects...
        now = datetime.datetime.now()
        expect = pythoncom.MakeTime(now)
        TestApplyResult(o.EarliestDate, (now, now), expect)
Exemple #10
0
    #Windows message pump is required for COM objects to be able to raise events
    pythoncom.PumpWaitingMessages()

    if connectedToEikon:
        #This creates an instance of AdxYieldCurveModule object from AdfinX Analytics library
        curveModule = connectionToEikon.CreateAdxYieldCurveModule()

        #Inputs required for AdCalibrate function
        rateStructure = "RM:HW ZCTYPE:RATE IM:CUBR"
        calcStructure = "CMT:FORM"

        inputArray = [[0 for x in range(9)] for x in range(2)]
        zeroCurve = [[0 for x in range(2)] for x in range(6)]

        inputArray[0][0] = "S"
        inputArray[0][1] = pythoncom.MakeTime(datetime.date(2017, 11, 20))
        inputArray[0][2] = pythoncom.MakeTime(datetime.date(2017, 12, 20))
        inputArray[0][3] = "1Y"
        inputArray[0][4] = 0
        inputArray[0][5] = pythoncom.MakeTime(datetime.date(2017, 12, 20))
        inputArray[0][6] = 0.1
        inputArray[0][7] = "CALL EXM:E"
        inputArray[0][8] = "EUR_AB6E"

        inputArray[1][0] = "S"
        inputArray[1][1] = pythoncom.MakeTime(datetime.date(2017, 11, 20))
        inputArray[1][2] = pythoncom.MakeTime(datetime.date(2019, 11, 22))
        inputArray[1][3] = "2Y"
        inputArray[1][4] = 0
        inputArray[1][5] = pythoncom.MakeTime(datetime.date(2019, 11, 22))
        inputArray[1][6] = 0.11
Exemple #11
0
def TestGenerated():
    # Create an instance of the server.
    from win32com.client.gencache import EnsureDispatch
    o = EnsureDispatch("PyCOMTest.PyCOMTest")
    counter = o.GetSimpleCounter()
    TestCounter(counter, 1)

    counter = EnsureDispatch("PyCOMTest.SimpleCounter")
    TestCounter(counter, 1)

    i1, i2 = o.GetMultipleInterfaces()
    if type(i1) != types.InstanceType or type(i2) != types.InstanceType:
        # Yay - is now an instance returned!
        raise error, "GetMultipleInterfaces did not return instances - got '%s', '%s'" % (
            i1, i2)
    del i1
    del i2

    progress("Checking default args")
    rc = o.TestOptionals()
    if rc[:-1] != ("def", 0, 1) or abs(rc[-1] - 3.14) > .01:
        print rc
        raise error, "Did not get the optional values correctly"
    rc = o.TestOptionals("Hi", 2, 3, 1.1)
    if rc[:-1] != ("Hi", 2, 3) or abs(rc[-1] - 1.1) > .01:
        print rc
        raise error, "Did not get the specified optional values correctly"
    rc = o.TestOptionals2(0)
    if rc != (0, "", 1):
        print rc
        raise error, "Did not get the optional2 values correctly"
    rc = o.TestOptionals2(1.1, "Hi", 2)
    if rc[1:] != ("Hi", 2) or abs(rc[0] - 1.1) > .01:
        print rc
        raise error, "Did not get the specified optional2 values correctly"

    progress("Checking var args")
    o.SetVarArgs("Hi", "There", "From", "Python", 1)
    if o.GetLastVarArgs() != ("Hi", "There", "From", "Python", 1):
        raise error, "VarArgs failed -" + str(o.GetLastVarArgs())
    progress("Checking getting/passing IUnknown")
    if o.GetSetUnknown(o) != o:
        raise error, "GetSetUnknown failed"
    progress("Checking getting/passing IDispatch")
    if type(o.GetSetDispatch(o)) != types.InstanceType:
        raise error, "GetSetDispatch failed"
    progress("Checking getting/passing IDispatch of known type")
    if o.GetSetInterface(o).__class__ != o.__class__:
        raise error, "GetSetDispatch failed"
    if o.GetSetVariant(4) != 4:
        raise error, "GetSetVariant (int) failed"
    if o.GetSetVariant("foo") != "foo":
        raise error, "GetSetVariant (str) failed"
    if o.GetSetVariant(o) != o:
        raise error, "GetSetVariant (dispatch) failed"
    for l in sys.maxint, sys.maxint + 1, 1 << 65L:
        if o.GetSetVariant(l) != l:
            raise error, "GetSetVariant (long) failed"
    if o.TestByRefVariant(2) != 4:
        raise error, "TestByRefVariant failed"
    if o.TestByRefString("Foo") != "FooFoo":
        raise error, "TestByRefString failed"

    # Pass some non-sequence objects to our array decoder, and watch it fail.
    try:
        o.SetVariantSafeArray("foo")
        raise error, "Expected a type error"
    except TypeError:
        pass
    try:
        o.SetVariantSafeArray(666)
        raise error, "Expected a type error"
    except TypeError:
        pass

    o.GetSimpleSafeArray(None)
    TestApplyResult(o.GetSimpleSafeArray, (None, ), tuple(range(10)))
    resultCheck = tuple(range(5)), tuple(range(10)), tuple(range(20))
    TestApplyResult(o.GetSafeArrays, (None, None, None), resultCheck)

    l = [1, 2, 3, 4]
    TestApplyResult(o.SetVariantSafeArray, (l, ), len(l))
    TestApplyResult(o.SetIntSafeArray, (l, ), len(l))
    l = []
    TestApplyResult(o.SetVariantSafeArray, (l, ), len(l))
    TestApplyResult(o.SetIntSafeArray, (l, ), len(l))
    # Tell the server to do what it does!
    TestApplyResult(o.Test, ("Unused", 99), 1)  # A bool function
    TestApplyResult(o.Test, ("Unused", -1), 1)  # A bool function
    TestApplyResult(o.Test, ("Unused", 1 == 1), 1)  # A bool function
    TestApplyResult(o.Test, ("Unused", 0), 0)
    TestApplyResult(o.Test, ("Unused", 1 == 0), 0)
    TestApplyResult(o.Test2, (constants.Attr2, ), constants.Attr2)
    TestApplyResult(o.Test3, (constants.Attr2, ), constants.Attr2)
    TestApplyResult(o.Test4, (constants.Attr2, ), constants.Attr2)
    TestApplyResult(o.Test5, (constants.Attr2, ), constants.Attr2)

    TestApplyResult(o.Test6, (constants.WideAttr1, ), constants.WideAttr1)
    TestApplyResult(o.Test6, (constants.WideAttr2, ), constants.WideAttr2)
    TestApplyResult(o.Test6, (constants.WideAttr3, ), constants.WideAttr3)
    TestApplyResult(o.Test6, (constants.WideAttr4, ), constants.WideAttr4)
    TestApplyResult(o.Test6, (constants.WideAttr5, ), constants.WideAttr5)

    TestConstant("ULongTest1", 0xFFFFFFFFL)
    TestConstant("ULongTest2", 0x7FFFFFFFL)
    TestConstant("LongTest1", -0x7FFFFFFFL)
    TestConstant("LongTest2", 0x7FFFFFFFL)
    TestConstant("UCharTest", 255)
    TestConstant("CharTest", -1)
    # 'Hello Loraine', but the 'r' is the "Registered" sign (\xae)
    TestConstant("StringTest", u"Hello Lo\xaeaine")

    now = pythoncom.MakeTime(time.gmtime(time.time()))
    later = pythoncom.MakeTime(time.gmtime(time.time() + 1))
    TestApplyResult(o.EarliestDate, (now, later), now)
    try:
        import datetime
        now = datetime.datetime.now()
        expect = pythoncom.MakeTime(now)
        TestApplyResult(o.EarliestDate, (now, now), expect)
    except ImportError:
        pass  # py 2.2 - no datetime

    assert o.DoubleString("foo") == "foofoo"
    assert o.DoubleInOutString("foo") == "foofoo"

    o.LongProp = 3
    if o.LongProp != 3 or o.IntProp != 3:
        raise error, "Property value wrong - got %d/%d" % (o.LongProp,
                                                           o.IntProp)

    o.LongProp = o.IntProp = -3
    if o.LongProp != -3 or o.IntProp != -3:
        raise error, "Property value wrong - got %d/%d" % (o.LongProp,
                                                           o.IntProp)

    check = 3 * 10**9
    o.ULongProp = check
    if o.ULongProp != check:
        raise error, "Property value wrong - got %d (expected %d)" % (
            o.ULongProp, check)

    # currency.
    pythoncom.__future_currency__ = 1
    if o.CurrencyProp != 0:
        raise error, "Expecting 0, got %r" % (o.CurrencyProp, )
    try:
        import decimal
    except ImportError:
        import win32com.decimal_23 as decimal
    for val in ("1234.5678", "1234.56", "1234"):
        o.CurrencyProp = decimal.Decimal(val)
        if o.CurrencyProp != decimal.Decimal(val):
            raise error, "%s got %r" % (val, o.CurrencyProp)
    v1 = decimal.Decimal("1234.5678")
    TestApplyResult(o.DoubleCurrency, (v1, ), v1 * 2)
    TestApplyResult(o.DoubleCurrencyByVal, (v1, ), v1 * 2)
    v2 = decimal.Decimal("9012.3456")
    TestApplyResult(o.AddCurrencies, (v1, v2), v1 + v2)

    o.SetParamProp(0, 1)
    if o.ParamProp(0) != 1:
        raise RuntimeError, o.paramProp(0)

    # Do the connection point thing...
    # Create a connection object.
    progress("Testing connection points")
    sessions = []
    o = win32com.client.DispatchWithEvents(o, RandomEventHandler)
    o._Init()

    try:
        for i in range(3):
            session = o.Start()
            sessions.append(session)
        time.sleep(.5)
    finally:
        # Stop the servers
        for session in sessions:
            o.Stop(session)
        o._DumpFireds()
    progress("Finished generated .py test.")
Exemple #12
0
 def COMDateFromTuple(self, YMDHMSmsTuple):
     t = pythoncom.MakeTime(YMDHMSmsTuple)
     return float(t)
Exemple #13
0
 def COMDate(self, timeobj):
     return float(pythoncom.MakeTime(time.mktime(timeobj)))