Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
SeleniumHQ
GitHub Repository: SeleniumHQ/Selenium
Path: blob/trunk/rb/lib/selenium/webdriver/common/wait.rb
4009 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
@message_provider = opts[:message_provider]
41
@ignored = Array(opts[:ignore] || Error::NoSuchElementError)
42
end
43
44
#
45
# Wait until the given block returns a true value.
46
#
47
# @raise [Error::TimeoutError]
48
# @return [Object] the result of the block
49
#
50
51
def until
52
end_time = current_time + @timeout
53
last_error = nil
54
55
until current_time > end_time
56
begin
57
result = yield
58
return result if result
59
rescue *@ignored => last_error # rubocop:disable Naming/RescuedExceptionsVariableName
60
# swallowed
61
end
62
63
sleep @interval
64
end
65
66
msg = if @message
67
@message.dup
68
elsif @message_provider
69
@message_provider.call
70
else
71
"timed out after #{@timeout} seconds"
72
end
73
74
msg << " (#{last_error.message})" if last_error
75
76
raise Error::TimeoutError, msg
77
end
78
79
private
80
81
def current_time
82
Process.clock_gettime(Process::CLOCK_MONOTONIC)
83
end
84
end # Wait
85
end # WebDriver
86
end # Selenium
87
88