循环中的Jython异常处理

2024-05-20 17:59:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用马拉松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是“wait property”的缩写,它接受3个强制参数和1个可选参数(参数的名称很容易解释),它的作用是等待指定组件的特定属性等于指定值。在

上面的方法(Jython)打算使用一个额外的参数times,该参数指定尝试wait_p的次数,直到最后一次尝试为止都禁止异常。在

但是,这种方法对我不起作用,我担心其中可能有一些语法或逻辑错误。python/jython专家有什么评论吗?在

谢谢!在


Tags: thename脚本应用程序参数isvalue时间
2条回答

两件事:

  • range(1, times)几乎可以肯定是range(times);您所写的相当于{}
  • 因为我刚刚解释过,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"

@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上执行不同的“最后一次”操作)。如果循环中没有执行break,那么循环上的else子句将执行

相关问题 更多 >