Jython循环中的异常处理
我正在使用Marathon 2.0b4来自动化测试一个应用程序。
Marathon提供的一个脚本元素叫做wait_p
,它有一个缺点,就是默认的超时时间是固定的,设定为60秒。因为我的应用加载时间比较长,所以我需要更长的超时时间。
[我考虑过修改Marathon的代码,但不想维护多个版本,所以我觉得在测试脚本层面找到一个解决办法会更好。]
def wait_p_long(times, compID_name, ppty_name, ppty_value, compID_cell=None):
from marathon.playback import *
"""Wrapper around wait_p which takes exactly the same parameters as wait_p,
except that an extra first parameter is used to specify the number of times
wait_p is called"""
for i in range(1, times):
try:
wait_p(compID_name, ppty_name, ppty_value, compID_cell)
except:
if (i < times):
print "wait_p failed, trying again"
else:
raise
wait_p
是“等待属性”的缩写,它需要三个必填参数和一个可选参数(这些参数的名字其实挺容易理解的),它的作用是等待指定组件的某个属性等于指定的值。
上面这个方法(Jython)想要做的是多加一个参数times
,这个参数指定了尝试wait_p
的次数,并且在最后一次尝试之前不会抛出异常。
不过,这个方法对我来说并没有奏效,我担心里面可能有语法或逻辑错误。有没有Python或Jython的高手能给点建议?
谢谢!
2 个回答
3
@Hank的解释是对的,但我想推荐一种不同的方法:
def wait_p_long(times, compID_name, ppty_name, ppty_value, compID_cell=None):
from marathon.playback import *
for i in range(times-1):
try:
wait_p(compID_name, ppty_name, ppty_value, compID_cell)
break
except:
pass
else: # try one last time...!
wait_p(compID_name, ppty_name, ppty_value, compID_cell)
对我来说,这种方法在概念上更简单(虽然重复写wait_p
这个调用有点麻烦,但它避免了在“最后一次”时对i
进行检查来做不同的事情)。顺便提一下,循环中的else
部分会在循环中没有执行过break
时执行。
2
有两件事:
range(1, times)
这个写法几乎肯定应该改成range(times)
;你现在的写法就相当于for (int i=1; i < times; i++)
。- 因为我刚才说的原因,
if (i < times)
在你的except
块里总是会返回True
。
如果这些信息对你解决问题没有帮助,请详细描述一下你的结果和你预期的结果有什么不同。
结果可能看起来像这样:
def wait_p_long(times, compID_name, ppty_name, ppty_value, compID_cell=None):
from marathon.playback import *
"""
Wrapper around wait_p which takes exactly the same parameters as wait_p,
except that an extra first parameter is used to specify the number of times
wait_p is called.
"""
for i in range(times):
try:
wait_p(compID_name, ppty_name, ppty_value, compID_cell)
except:
if i == times - 1:
raise
else:
print "wait_p failed, trying again"