3

Using Python/Selenium/Behave:

I'm wondering how to correctly add wait/sleep decorators to steps functions?

I have setup a helper.py with my decorator function:

import time

def wait(secs):
    def decorator(func):
        def wrapper(*args, **kwargs):
            ret = func(*args, **kwargs)
            time.sleep(secs)
            return ret
        return wrapper
    return decorator

class Helper(object):
    pass

In my steps file, I'm calling the wait decorator after the behave decorator to match the step:

from behave import step
from features.helper import wait

@step('I observe a login error')
@wait(3)
def step_impl(context):
    #time.sleep(3)
    assert context.login_page.check_login_error() is not None

But when I execute the step from my feature file, there is no wait/sleep being executed, and the assert fails. How can I execute the wait decorator in this case?

dogstar
  • 67
  • 1
  • 5
  • You cannot add parameters to decorators like that, see: https://stackoverflow.com/questions/5929107/decorators-with-parameters – Mandera May 28 '20 at 08:18
  • You're calling your decorated function, _before_ waiting the 3 seconds. Then you're waiting 3 seconds after the decorated function is finished. Is that really the behavior you wanted? If not, try to just move the `time.sleep` call to before the function-call. – Hampus Larsson May 28 '20 at 08:29
  • Personally, I think using that wait decorator is obscuring your tests. I would include a `Then I wait for 3 seconds` step to be more explicit. Even better, if you are using Selenium I would use an explicit wait to find the error element when it shows up, rather than hardcoding a sleep into your code. – Levi Noecker May 28 '20 at 10:41

1 Answers1

5

I guess the problem is due to call the target function before sleep. So you can just swap func and time.sleep calling:

def wait(secs):
     def decorator(func):
         def wrapper(*args, **kwargs):
             time.sleep(secs)
             return func(*args, **kwargs)
         return wrapper
     return decorator
SimfikDuke
  • 943
  • 6
  • 21