Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try - Except in Python for given amount of time

I am using Marathon (Java desktop application testing tool) to automate regression testing. Marathon uses Jython so I can use Java libraries and Python libraries. As my script goes through filling out certain fields, various fields appear (or don't appear) based on values that I entered in previous fields. I need to skip over the fields that aren't there for the obvious reason. When fields are disabled, but still there, this is fine because I can use

    if Component.isEnabled():
        #do something
    else:
        #do something

The problem is when the component doesn't exist. Is there any way, in Java, to test for the existence of a component? For example, Component.exists() would suit my needs, but there isn't such a method in the component class.

I would prefer to solve my problem by using an if Component.exists(): statement, but I am able to get around it using a try, except block. However, this leads to major execution time issues for the script. It tries to find the component for ~2 or 3 minutes before it throws an exception. The only way I could see around this issue is if there was some sort of statement like try for x seconds and move on if component is not found. Is there any way to limit the amount of time you try any given statement?

like image 926
Nick L Avatar asked Oct 20 '22 12:10

Nick L


1 Answers

I found some code to throw a time-out exception in your code as an answer to another Stackoverflow-question: What should I do if socket.setdefaulttimeout() is not working?, it however only works on linux-machines as stated in the link.

Concretely:

import signal, time

class Timeout():
  """Timeout class using ALARM signal"""
  class Timeout(Exception): pass

  def __init__(self, sec):
    self.sec = sec

  def __enter__(self):
    signal.signal(signal.SIGALRM, self.raise_timeout)
    signal.alarm(self.sec)

  def __exit__(self, *args):
    signal.alarm(0) # disable alarm

  def raise_timeout(self, *args):
    raise Timeout.Timeout()

# Run block of code with timeouts
try:
  with Timeout(60):
    #do something

except Timeout.Timeout:
  #do something else

This will try "do something" for 60 seconds and moves on if the execution exceeds 60 seconds...

like image 138
Fematich Avatar answered Oct 23 '22 09:10

Fematich