-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
fixtures.py
319 lines (238 loc) · 9.64 KB
/
fixtures.py
1
2
3
4
5
6
7
8
9
10
11
12
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
from __future__ import print_function
import copy
import json
import os
import urlparse
import re
import sys
import webdriver
from tests.support.http_request import HTTPRequest
from tests.support.wait import wait
default_host = "http://127.0.0.1"
default_port = "4444"
default_script_timeout = 30
default_page_load_timeout = 300
default_implicit_wait_timeout = 0
default_window_size = (800, 600)
_current_session = None
_custom_session = False
def ignore_exceptions(f):
def inner(*args, **kwargs):
try:
return f(*args, **kwargs)
except webdriver.error.WebDriverException as e:
print("Ignored exception %s" % e, file=sys.stderr)
inner.__name__ = f.__name__
return inner
def cleanup_session(session):
"""Clean-up the current session for a clean state."""
@ignore_exceptions
def _dismiss_user_prompts(session):
"""Dismiss any open user prompts in windows."""
current_window = session.window_handle
for window in _windows(session):
session.window_handle = window
try:
session.alert.dismiss()
except webdriver.NoSuchAlertException:
pass
session.window_handle = current_window
@ignore_exceptions
def _ensure_valid_window(session):
"""If current window was closed, ensure to have a valid one selected."""
try:
session.window_handle
except webdriver.NoSuchWindowException:
session.window_handle = session.handles[0]
@ignore_exceptions
def _restore_timeouts(session):
"""Restore modified timeouts to their default values."""
session.timeouts.implicit = default_implicit_wait_timeout
session.timeouts.page_load = default_page_load_timeout
session.timeouts.script = default_script_timeout
@ignore_exceptions
def _restore_window_state(session):
"""Reset window to an acceptable size.
This also includes bringing it out of maximized, minimized,
or fullscreened state.
"""
session.window.size = default_window_size
@ignore_exceptions
def _restore_windows(session):
"""Close superfluous windows opened by the test.
It will not end the session implicitly by closing the last window.
"""
current_window = session.window_handle
for window in _windows(session, exclude=[current_window]):
session.window_handle = window
if len(session.handles) > 1:
session.close()
session.window_handle = current_window
_restore_timeouts(session)
_ensure_valid_window(session)
_dismiss_user_prompts(session)
_restore_windows(session)
_restore_window_state(session)
_switch_to_top_level_browsing_context(session)
@ignore_exceptions
def _switch_to_top_level_browsing_context(session):
"""If the current browsing context selected by WebDriver is a
`<frame>` or an `<iframe>`, switch it back to the top-level
browsing context.
"""
session.switch_frame(None)
def _windows(session, exclude=None):
"""Set of window handles, filtered by an `exclude` list if
provided.
"""
if exclude is None:
exclude = []
wins = [w for w in session.handles if w not in exclude]
return set(wins)
def add_event_listeners(session):
"""Register listeners for tracked events on element."""
def add_event_listeners(element, tracked_events):
element.session.execute_script("""
let element = arguments[0];
let trackedEvents = arguments[1];
if (!("events" in window)) {
window.events = [];
}
for (var i = 0; i < trackedEvents.length; i++) {
element.addEventListener(trackedEvents[i], function (event) {
window.events.push(event.type);
});
}
""", args=(element, tracked_events))
return add_event_listeners
def create_cookie(session, url):
"""Create a cookie"""
def create_cookie(name, value, **kwargs):
if kwargs.get("path", None) is not None:
session.url = url(kwargs["path"])
session.set_cookie(name, value, **kwargs)
return session.cookies(name)
return create_cookie
def create_frame(session):
"""Create an `iframe` element in the current browsing context and insert it
into the document. Return a reference to the newly-created element."""
def create_frame():
append = """
var frame = document.createElement('iframe');
document.body.appendChild(frame);
return frame;
"""
return session.execute_script(append)
return create_frame
def create_window(session):
"""Open new window and return the window handle."""
def create_window():
windows_before = session.handles
name = session.execute_script("window.open()")
assert len(session.handles) == len(windows_before) + 1
new_windows = list(set(session.handles) - set(windows_before))
return new_windows.pop()
return create_window
def http(configuration):
return HTTPRequest(configuration["host"], configuration["port"])
def server_config():
return json.loads(os.environ.get("WD_SERVER_CONFIG"))
def configuration():
host = os.environ.get("WD_HOST", default_host)
port = int(os.environ.get("WD_PORT", default_port))
capabilities = json.loads(os.environ.get("WD_CAPABILITIES", "{}"))
return {
"host": host,
"port": port,
"capabilities": capabilities
}
def session(capabilities, configuration, request):
"""Create and start a session for a test that does not itself test session creation.
By default the session will stay open after each test, but we always try to start a
new one and assume that if that fails there is already a valid session. This makes it
possible to recover from some errors that might leave the session in a bad state, but
does not demand that we start a new session per test."""
global _current_session
# Update configuration capabilities with custom ones from the
# capabilities fixture, which can be set by tests
caps = copy.deepcopy(configuration["capabilities"])
if "alwaysMatch" in caps or "firstMatch" in caps:
caps.setdefault("alwaysMatch", {}).update(capabilities)
else:
caps.update(capabilities)
caps = {"alwaysMatch": caps}
# If there is a session with different capabilities active, end it now
if _current_session is not None and (
caps != _current_session.requested_capabilities):
_current_session.end()
_current_session = None
if _current_session is None:
_current_session = webdriver.Session(
configuration["host"],
configuration["port"],
capabilities=caps)
try:
_current_session.start()
except webdriver.error.SessionNotCreatedException:
if not _current_session.session_id:
raise
# Enforce a fixed default window size
_current_session.window.size = default_window_size
yield _current_session
cleanup_session(_current_session)
def current_session():
return _current_session
def url(server_config):
def inner(path, protocol="http", query="", fragment=""):
port = server_config["ports"][protocol][0]
host = "%s:%s" % (server_config["browser_host"], port)
return urlparse.urlunsplit((protocol, host, path, query, fragment))
inner.__name__ = "url"
return inner
def create_dialog(session):
"""Create a dialog (one of "alert", "prompt", or "confirm") and provide a
function to validate that the dialog has been "handled" (either accepted or
dismissed) by returning some value."""
def create_dialog(dialog_type, text=None):
assert dialog_type in ("alert", "confirm", "prompt"), (
"Invalid dialog type: '%s'" % dialog_type)
if text is None:
text = ""
assert isinstance(text, basestring), "`text` parameter must be a string"
# Script completes itself when the user prompt has been opened.
session.execute_async_script("""
let dialog_type = arguments[0];
let text = arguments[1];
setTimeout(function() {
window.dialog_return_value = window[dialog_type](text);
}, 0);
""", args=(dialog_type, text))
wait(session,
lambda s: s.alert.text == text,
"No user prompt with text '{}' detected".format(text),
timeout=15,
ignored_exceptions=webdriver.NoSuchAlertException)
return create_dialog
def clear_all_cookies(session):
"""Removes all cookies associated with the current active document"""
session.transport.send("DELETE", "session/%s/cookie" % session.session_id)
def closed_window(session, create_window):
new_handle = create_window()
original_handle = session.window_handle
session.window_handle = new_handle
session.close()
assert new_handle not in session.handles, "Unable to close window {}".format(new_handle)
yield new_handle
session.window_handle = original_handle
def is_element_in_viewport(session, element):
"""Check if element is outside of the viewport"""
return session.execute_script("""
let el = arguments[0];
let rect = el.getBoundingClientRect();
let viewport = {
height: window.innerHeight || document.documentElement.clientHeight,
width: window.innerWidth || document.documentElement.clientWidth,
};
return !(rect.right < 0 || rect.bottom < 0 ||
rect.left > viewport.width || rect.top > viewport.height)
""", args=(element,))