Module: Chemlab::Support::Repeater

Included in:
Waiter
Defined in:
lib/chemlab/support/repeater.rb

Constant Summary collapse

DEFAULT_MAX_WAIT_TIME =
60
RetriesExceededError =
Class.new(RuntimeError)
WaitExceededError =
Class.new(RuntimeError)

Instance Method Summary collapse

Instance Method Details

#repeat_until(max_attempts: nil, max_duration: nil, reload_page: nil, sleep_interval: 0, raise_on_failure: true, retry_on_exception: false, log: true) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/chemlab/support/repeater.rb', line 13

def repeat_until(max_attempts: nil, max_duration: nil, reload_page: nil, sleep_interval: 0, raise_on_failure: true, retry_on_exception: false, log: true)
  attempts = 0
  start = Time.now

  begin
    while remaining_attempts?(attempts, max_attempts) && remaining_time?(start, max_duration)
      QA::Runtime::Logger.debug("Attempt number #{attempts + 1}") if max_attempts && log

      result = yield
      return result if result

      sleep_and_reload_if_needed(sleep_interval, reload_page)
      attempts += 1
    end
  rescue StandardError, RSpec::Expectations::ExpectationNotMetError
    raise unless retry_on_exception

    attempts += 1
    if remaining_attempts?(attempts, max_attempts) && remaining_time?(start, max_duration)
      sleep_and_reload_if_needed(sleep_interval, reload_page)

      retry
    else
      raise
    end
  end

  if raise_on_failure
    raise RetriesExceededError, "Retry condition not met after #{max_attempts} #{'attempt'.pluralize(max_attempts)}" unless remaining_attempts?(attempts, max_attempts)

    raise WaitExceededError, "Wait condition not met after #{max_duration} #{'second'.pluralize(max_duration)}"
  end

  false
end