def add_factory_info(request): if request.is_ajax(): state = None try: if Factory.objects.filter( name=request.POST.get('txt_factory_name')): state = 'info_exist' return HttpResponse(state) else: new = Factory( name=request.POST.get('txt_factory_name'), Contact=request.POST.get('txt_factory_contact'), qq=request.POST.get('txt_factory_qq'), phone_num=request.POST.get('txt_factory_phone_num'), address=request.POST.get('txt_factory_address'), description=request.POST.get('txt_area_factory_desc'), last_change_date=win32timezone.now(), last_change_user_id=request.user.id) new.save() state = 'success' return HttpResponse(state) except: state = "error" return HttpResponse(state) else: return HttpResponse("")
def add_customer_info(request): if request.is_ajax(): state = None try: if Customer.objects.filter( name=request.POST.get('txt_customer_nick_name')): state = 'info_exist' return HttpResponse(state) else: new = Customer( name=request.POST.get('txt_customer_name'), nick_name=request.POST.get('txt_customer_nick_name'), icon_img=request.FILES.get('file_customer_icon'), description=request.POST.get('txt_area_customer_desc'), last_change_date=win32timezone.now(), last_change_user_id=request.user.id) new.save() state = 'success' return HttpResponse(state) except: state = "error" return HttpResponse(state) else: return HttpResponse('')
def add_parts_info(request): if request.is_ajax(): state = None user = request.user try: if (Parts.objects.filter(oem=request.POST.get("txt_OEM"))): state = 'info_exist' return HttpResponse(state) else: new_parts = Parts( oem=request.POST.get("txt_OEM"), cn_name=request.POST.get("txt_cn_name"), en_name=request.POST.get("txt_en_name"), description=request.POST.get("txt_area_desc"), img=request.FILES.get("file_img"), last_change_date=win32timezone.now(), last_change_user_id=user.id, car_model=request.POST.get('txt_car_model')) new_parts.save() state = 'success' return HttpResponse(state) except: state = 'error' return HttpResponse(state) else: return HttpResponse("")
def send_pbix_file_to_all(self): pbix_path = "C:\\Users\\Anastasia Siedykh\\Documents\\Backup\\KPI report\\MODULE SET V6\\power_bi_package\\main_base.pbix" pbix_file = "main_base.pbix" report_name = "PBIX-файл" tod_date = now() text = f'Добрый день, коллеги, в приложении обновленный PBIX файл по состоянию на {tod_date}' x.send_mail_with_report_file_to_all(pbix_path, pbix_file, report_name, text)
def train_and_evaluate(): last_error_ratio = 1.0 epoch = 0 train_data_set, train_labels = get_training_data_set() test_data_set, test_labels = get_test_data_set() network = Network([784, 300, 10]) while True: epoch += 1 network.train(train_labels, train_data_set, 0.3, 1) print ('%s epoch %d finished' % (now(), epoch)) if epoch % 10 == 0: error_ratio = evaluate(network, test_data_set, test_labels) print ('%s after epoch %d, error ratio is %f' % (now(), epoch, error_ratio)) if error_ratio > last_error_ratio: break else: last_error_ratio = error_ratio
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) 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) 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.")
def _getTestTimes(self): if issubclass(pywintypes.TimeType, datetime.datetime): ctime = win32timezone.now() atime = ctime + datetime.timedelta(seconds=1) wtime = atime + datetime.timedelta(seconds=1) else: ctime = pywintypes.Time(11) atime = pywintypes.Time(12) wtime = pywintypes.Time(13) return ctime, atime, wtime
def _getTestTimes(self): if issubclass(pywintypes.TimeType, datetime.datetime): ctime = win32timezone.now() atime = ctime + datetime.timedelta(seconds=1) wtime = atime + datetime.timedelta(seconds=1) else: ctime = pywintypes.Time(11) atime = pywintypes.Time(12) wtime = pywintypes.Time(13) return ctime, atime, wtime
def main(): print 'starting at:', now() for item in range(16): t = threading.Thread(target=req_worker, args=(item, )) t.setDaemon(True) t.start() # 请求线程开启,共开启16个线程 s = threading.Thread(target=worker, args=()) s.setDaemon(True) s.start() # worker线程开启 response_worker() # response_worker开始工作 print 'all Done at:', now()
def _getTestTimes(self): if issubclass(pywintypes.TimeType, datetime.datetime): ctime = win32timezone.now() # FILETIME only has ms precision... ctime = ctime.replace(microsecond=ctime.microsecond // 1000 * 1000) atime = ctime + datetime.timedelta(seconds=1) wtime = atime + datetime.timedelta(seconds=1) else: ctime = pywintypes.Time(11) atime = pywintypes.Time(12) wtime = pywintypes.Time(13) return ctime, atime, wtime
def rebalance(): sm = SMOTEENN() train_data.replace(to_replace=np.nan, value=0, inplace=True) train_data.replace(to_replace=-np.inf, value=0, inplace=True) train_data.replace(to_replace=np.inf, value=0, inplace=True) print("rebalance data:", now()) X_resampled, y_resampled = sm.fit_resample(train_data[features], train_data[target]) X_resampled = pd.DataFrame(X_resampled, columns=features) y_resampled = pd.DataFrame(y_resampled, columns=target) X_resampled['is_trade'] = y_resampled['is_trade'] del y_resampled gc.collect() return X_resampled
def save_doc_as_file_sqlite(uid=None, code=None, langage=None): '''Crée/Enregistre le document sous la forme d'un fichier data/uid. Return the file name. ''' null = None date_time = now() cmd = request.user_agent.browser hostname = socket.gethostname() IPAddr = socket.gethostbyname(hostname) if uid is None: uid = create_uid_sqlite() code = '# Write your code here...' langage = '' connection = sqlite3.connect('tp.db') cursor = connection.cursor() cursor.execute("INSERT INTO SHARECODE VALUES(?, ?, ?)", (uid, code, langage)) cursor.execute("INSERT INTO USER VALUES(?, ?, ?, ?, ?)", (null, uid, IPAddr, cmd, date_time)) connection.commit() connection.close() connection = sqlite3.connect('tp.db') cursor1 = connection.cursor() cursor1.execute( '''UPDATE SHARECODE SET code = ?, langage = ? WHERE uid = ? ''', (code, langage, uid)) cursor1.execute( '''UPDATE USER SET timestamp = ?, Ip = ?, navigator = ? WHERE uid = ? ''', (date_time, IPAddr, cmd, uid)) connection.commit() connection.close() with open('data/{}'.format(uid), 'w') as fd: fd.write(code) with open('data/{}'.format(uid + '.lang'), 'w') as fd: fd.write(langage) return uid
def train(): # train_data = rebalance() print("starting CV:", now()) best_iter = xgbCV(train_data, test_data, features, target) print('最佳迭代次数:', best_iter) sub(train_data, test_data, features, target, best_iter)
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)
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)
from win32com import storagecon from win32com.test.util import CheckClean import pywintypes import win32ui import win32api import os from pywin32_testutil import str2bytes S_OK = 0 import datetime if issubclass(pywintypes.TimeType, datetime.datetime): import win32timezone now = win32timezone.now() else: now = pywintypes.Time(time.time()) class LockBytes: _public_methods_ = [ 'ReadAt', 'WriteAt', 'Flush', 'SetSize', 'LockRegion', 'UnlockRegion', 'Stat'] _com_interfaces_ = [pythoncom.IID_ILockBytes]
from pywintypes import Unicode from win32com import storagecon from win32com.test.util import CheckClean import pywintypes import win32ui import win32api, os from pywin32_testutil import str2bytes S_OK = 0 import datetime if issubclass(pywintypes.TimeType, datetime.datetime): import win32timezone now = win32timezone.now() else: now = pywintypes.Time(time.time()) class LockBytes: _public_methods_ = [ 'ReadAt', 'WriteAt', 'Flush', 'SetSize', 'LockRegion', 'UnlockRegion', 'Stat' ] _com_interfaces_ = [ pythoncom.IID_ILockBytes ] def __init__(self, data = ""): self.data = str2bytes(data) self.ctime = now self.mtime = now self.atime = now def ReadAt(self, offset, cb): print("ReadAt")
def map_values_to_time_series(self, time_series, values): #mind the lengh of values list mapped_data = pd.Series(time_series, values) return mapped_data def difference_between_time_values(self, mapped_data_from, mapped_data): difference = mapped_data_from - mapped_data return difference if __name__ == '__main__': x = Pandas_workout() start_date = '2021-05-01' end_date = now().date() values = [1, 2, 3, 4, 5, 6, 7] values2 = [6, 2, 6, 4, 7, 6, 1] time_series = x.get_date_range_index(start_date, end_date) #get range of dates mapped_data = x.map_values_to_time_series( values, time_series) #map dates with values mapped_data_from = x.map_values_to_time_series( values2, time_series) #map dates with values 2 difference = x.difference_between_time_values( mapped_data_from, mapped_data) #getting the difference df = pd.DataFrame({ "mapped_data_from": mapped_data_from, "mapped_data": mapped_data })
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)
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.")