Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
SeleniumHQ
GitHub Repository: SeleniumHQ/Selenium
Path: blob/trunk/rb/lib/selenium/webdriver/common/wait.rb
1865 views
1
# frozen_string_literal: true
2
3
# Licensed to the Software Freedom Conservancy (SFC) under one
4
# or more contributor license agreements. See the NOTICE file
5
# distributed with this work for additional information
6
# regarding copyright ownership. The SFC licenses this file
7
# to you under the Apache License, Version 2.0 (the
8
# "License"); you may not use this file except in compliance
9
# with the License. You may obtain a copy of the License at
10
#
11
# http://www.apache.org/licenses/LICENSE-2.0
12
#
13
# Unless required by applicable law or agreed to in writing,
14
# software distributed under the License is distributed on an
15
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
# KIND, either express or implied. See the License for the
17
# specific language governing permissions and limitations
18
# under the License.
19
20
module Selenium
21
module WebDriver
22
class Wait
23
DEFAULT_TIMEOUT = 5
24
DEFAULT_INTERVAL = 0.2
25
26
#
27
# Create a new Wait instance
28
#
29
# @param [Hash] opts Options for this instance
30
# @option opts [Numeric] :timeout (5) Seconds to wait before timing out.
31
# @option opts [Numeric] :interval (0.2) Seconds to sleep between polls.
32
# @option opts [String] :message Exception message if timed out.
33
# @option opts [Array, Exception] :ignore Exceptions to ignore while polling (default: Error::NoSuchElementError)
34
#
35
36
def initialize(opts = {})
37
@timeout = opts.fetch(:timeout, DEFAULT_TIMEOUT)
38
@interval = opts.fetch(:interval, DEFAULT_INTERVAL)
39
@message = opts[:message]
40
@ignored = Array(opts[:ignore] || Error::NoSuchElementError)
41
end
42
43
#
44
# Wait until the given block returns a true value.
45
#
46
# @raise [Error::TimeoutError]
47
# @return [Object] the result of the block
48
#
49
50
def until
51
end_time = current_time + @timeout
52
last_error = nil
53
54
until current_time > end_time
55
begin
56
result = yield
57
return result if result
58
rescue *@ignored => last_error # rubocop:disable Naming/RescuedExceptionsVariableName
59
# swallowed
60
end
61
62
sleep @interval
63
end
64
65
msg = if @message
66
@message.dup
67
else
68
"timed out after #{@timeout} seconds"
69
end
70
71
msg << " (#{last_error.message})" if last_error
72
73
raise Error::TimeoutError, msg
74
end
75
76
private
77
78
def current_time
79
Process.clock_gettime(Process::CLOCK_MONOTONIC)
80
end
81
end # Wait
82
end # WebDriver
83
end # Selenium
84
85