def waitObjectProperty(self, obj, property_name, waited_value, regularMatch=False): '''通过比较obj.property_name和waited_value,等待属性值出现。 如果属性值obj.property_name是字符类型则waited_value做为正则表达式进行比较。 比较成功则返回,超时则抛出TimeoutError异常。 :param obj: 对象 :param property_name: 要等待的obj对象的属性名 :param waited_value: 要比较的的属性值,支持多层属性 :param regularMatch: 参数 property_name和waited_value是否采用正则表达式的比较。 默认为不采用(False)正则,而是采用恒等比较 ''' start = time.time() waited = 0.0 try_count = 0 isstr = isinstance(waited_value, basestring) while True: objtmp = obj #增加多层属性支持 pro_names = property_name.split('.') for i in range(len(pro_names)): propvalue = getattr(objtmp, pro_names[i]) objtmp = propvalue if isstr and regularMatch: #简化原逻辑 if None != re.search(waited_value, propvalue): return else: if waited_value == propvalue: return try_count +=1 waited = time.time() - start if waited < self.timeout: time.sleep(min(self.interval, self.timeout - waited)) else: raise TimeoutError("对象属性值比较超时(%d秒%d次):期望值:%s,实际值:%s," % (self.timeout, try_count, waited_value, propvalue))
def retry(self, func, args, exceptions=(), resultmatcher=None, nothrow=False): """多次尝试调用函数,成功则并返回调用结果,超时则根据选项决定抛出TimeOutError异常。 :param func: 尝试调用的函数 :type args: dict或tuple :param args: func函数的参数 :type exceptions: tuple类型,tuple元素是异常类定义,如QPathError, 而不是异常实例,如QPathError() :param exceptions: 调用func时抛出这些异常,则重试。 如果是空列表(),则不捕获异常。 :type resultmatcher: 函数指针类型 :param resultmatcher: 函数指针,用于验证第1个参数func的返回值。 默认值为None,表示不验证func的返回值,直接返回。 其函数原型为: def result_match(ret): # 参数ret为func的返回值 pass 当result_match返回True时,直接返回,否则继续retry。 :type nothrow:bool :param nothrow:如果为True,则不抛出TimeOutError异常 :return: 返回成功调用func的结果 :rtype : any """ start = time.time() waited = 0.0 try_count = 0 ret = None while True: try: try_count += 1 if dict == type(args): ret = func(**args) elif tuple == type(args): ret = func(*args) else: raise TypeError("args type %s is not a dict or tuple" % type(args)) if resultmatcher == None or resultmatcher(ret) == True: return ret except exceptions: pass waited = time.time() - start if waited < self.timeout: time.sleep(min(self.interval, self.timeout - waited)) elif try_count == 1: continue else: if nothrow: return ret else: raise TimeoutError("在%d秒里尝试了%d次" % (self.timeout, try_count))
def wait_for_visible(self, timeout=10, interval=0.1): '''等待控件可见 :param timeout: 超时时间 :type timeout: float :param interval:查询间隔时间 :type interval: float ''' from tuia.util import Timeout from tuia.exceptions import TimeoutError try: Timeout(timeout, interval).waitObjectProperty(self, 'visible', True) except TimeoutError: raise TimeoutError('控件:%s 未在%sS内出现,当前坐标为:%s' % (self, timeout, self.BoundingRect))