Example #1
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) > 0.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) > 0.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) > 0.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")
    # This might be called with either the interface or the CoClass - but these
    # functions always return from the interface.
    expected_class = o.__class__
    # CoClass instances have `default_interface`
    expected_class = getattr(expected_class, "default_interface", expected_class)
    if not isinstance(o.GetSetDispatch(o), expected_class):
        raise error("GetSetDispatch failed: %r" % (o.GetSetDispatch(o),))
    progress("Checking getting/passing IDispatch of known type")
    expected_class = o.__class__
    expected_class = getattr(expected_class, "default_interface", expected_class)
    if o.GetSetInterface(o).__class__ != expected_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 World', but the 'r' is the "Registered" sign (\xae)
    TestConstant("StringTest", "Hello Wo\xaeld")

    progress("Checking dates and times")
    # 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)

    # The below used to fail with `ValueError: microsecond must be in 0..999999` - see #1655
    # https://planetcalc.com/7027/ says that float is: Sun, 25 Mar 1951 7:23:49 am
    assert o.MakeDate(18712.308206013888) == datetime.datetime.fromisoformat(
        "1951-03-25 07:23:49+00:00"
    )

    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)
Example #2
0
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 = str2memory('raw\0data')
    if vbtest.VariantProperty != str2memory('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 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)
Example #4
0
 def testLongBinary(self):
     """ Test a long raw field in excess of internal cursor data size (65536)"""
     self._test_val('longbinaryfield', str2memory('\0\1\2' * 70000))
Example #5
0
 def testRaw(self):
     ## Test binary data
     self._test_val('rawfield', str2memory('\1\2\3\4\0\5\6\7\8'))
Example #6
0
 def testRaw(self):
     ## Test binary data
     self._test_val('rawfield', str2memory('\1\2\3\4\0\5\6\7\8'))
Example #7
0
 def testLongBinary(self):
     """ Test a long raw field in excess of internal cursor data size (65536)"""
     self._test_val('longbinaryfield', str2memory('\0\1\2' * 70000))
Example #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.")
Example #9
0
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 = str2memory('raw\0data')
    if vbtest.VariantProperty != str2memory('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))
Example #10
0
 def testRaw(self):
     ## Test binary data
     self._test_val("rawfield", str2memory("\1\2\3\4\0\5\6\7\8"))