This repository has been archived by the owner on Jan 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 34
/
query.py
505 lines (385 loc) · 14.7 KB
/
query.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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
"""
Tools for interacting with the DOM inside a browser.
"""
from __future__ import absolute_import
from copy import copy
from collections import Sequence
from itertools import islice
from selenium.common.exceptions import WebDriverException
import six
from bok_choy.promise import Promise
# Mapping of query type to Selenium webdriver query method names
QUERY_TYPES = {
'css': 'find_elements_by_css_selector',
'xpath': 'find_elements_by_xpath',
}
def no_error(func):
"""
Decorator to create a `Promise` check function that is satisfied
only when `func` executes without a Selenium error.
This protects against many common test failures due to timing issues.
For example, accessing an element after it has been modified by JavaScript
ordinarily results in a `StaleElementException`. Methods decorated
with `no_error` will simply retry if that happens, which makes tests
more robust.
Args:
func (callable): The function to execute, with retries if an error occurs.
Returns:
Decorated function
"""
def _inner(*args, **kwargs): # pylint: disable=missing-docstring
try:
return_val = func(*args, **kwargs)
except WebDriverException:
return (False, None)
else:
return (True, return_val)
return _inner
class Query(Sequence):
"""
General mechanism for selecting and transforming values.
"""
def __init__(self, seed_fn, desc=None):
"""
Configure the `Query`.
Args:
seed_fn (callable): Callable with no arguments that produces a list of values.
Keyword Args:
desc (str): A description of the query, used in log messages.
If not provided, defaults to the name of the seed function.
Returns:
Query
"""
if desc is None:
desc = u'Query({})'.format(getattr(seed_fn, '__name__', ''))
self.seed_fn = seed_fn
self.transforms = []
self.desc_stack = []
self.desc = desc
def replace(self, **kwargs):
"""
Return a copy of this `Query`, but with attributes specified
as keyword arguments replaced by the keyword values.
Keyword Args:
Attributes/values to replace in the copy.
Returns:
A copy of the query that has its attributes updated with the specified values.
Raises:
TypeError: The `Query` does not have the specified attribute.
"""
clone = copy(self)
clone.transforms = list(clone.transforms)
for key, value in kwargs.items():
if not hasattr(clone, key):
raise TypeError('replace() got an unexpected keyword argument {!r}'.format(key))
setattr(clone, key, value)
return clone
def transform(self, transform, desc=None):
"""
Create a copy of this query, transformed by `transform`.
Args:
transform (callable): Callable that takes an iterable of values and
returns an iterable of transformed values.
Keyword Args:
desc (str): A description of the transform, to use in log messages.
Defaults to the name of the `transform` function.
Returns:
Query
"""
if desc is None:
desc = u'transform({})'.format(getattr(transform, '__name__', ''))
return self.replace(
transforms=self.transforms + [transform],
desc_stack=self.desc_stack + [desc]
)
def map(self, map_fn, desc=None):
"""
Return a copy of this query, with the values mapped through `map_fn`.
Args:
map_fn (callable): A callable that takes a single argument and returns a new value.
Keyword Args:
desc (str): A description of the mapping transform, for use in log message.
Defaults to the name of the map function.
Returns:
Query
"""
if desc is None:
desc = getattr(map_fn, '__name__', '')
desc = u'map({})'.format(desc)
return self.transform(lambda xs: (map_fn(x) for x in xs), desc=desc)
def filter(self, filter_fn=None, desc=None, **kwargs):
"""
Return a copy of this query, with some values removed.
Example usages:
.. code:: python
# Returns a query that matches even numbers
q.filter(filter_fn=lambda x: x % 2)
# Returns a query that matches elements with el.description == "foo"
q.filter(description="foo")
Keyword Args:
filter_fn (callable): If specified, a function that accepts one argument (the element)
and returns a boolean indicating whether to include that element in the results.
kwargs: Specify attribute values that an element must have to be included in the results.
desc (str): A description of the filter, for use in log messages.
Defaults to the name of the filter function or attribute.
Raises:
TypeError: neither or both of `filter_fn` and `kwargs` are provided.
"""
if filter_fn is not None and kwargs:
raise TypeError('Must supply either a filter_fn or attribute filter parameters to filter(), but not both.')
if filter_fn is None and not kwargs:
raise TypeError('Must supply one of filter_fn or one or more attribute filter parameters to filter().')
if desc is None:
if filter_fn is not None:
desc = getattr(filter_fn, '__name__', '')
elif kwargs:
desc = u", ".join([u"{}={!r}".format(key, value) for key, value in kwargs.items()])
desc = u"filter({})".format(desc)
if kwargs:
def filter_fn(elem): # pylint: disable=function-redefined, missing-docstring
return all(
getattr(elem, filter_key) == filter_value
for filter_key, filter_value
in kwargs.items()
)
return self.transform(lambda xs: (x for x in xs if filter_fn(x)), desc=desc)
def _execute(self):
"""
Run the query, generating data from the `seed_fn` and performing transforms on the results.
"""
data = self.seed_fn()
for transform in self.transforms:
data = transform(data)
return list(data)
def execute(self, try_limit=5, try_interval=0.5, timeout=30):
"""
Execute this query, retrying based on the supplied parameters.
Keyword Args:
try_limit (int): The number of times to retry the query.
try_interval (float): The number of seconds to wait between each try (float).
timeout (float): The maximum number of seconds to spend retrying (float).
Returns:
The transformed results of the query.
Raises:
BrokenPromise: The query did not execute without a Selenium error after one or more attempts.
"""
return Promise(
no_error(self._execute),
u"Executing {!r}".format(self),
try_limit=try_limit,
try_interval=try_interval,
timeout=timeout,
).fulfill()
@property
def results(self):
"""
A list of the results of the query, which are cached.
If you call `results` multiple times on the same query, you will always get the same results.
Use `reset()` to clear the cache and re-run the query.
Returns:
The results from executing the query.
"""
return self.execute()
def __getitem__(self, key):
return self.results[key]
def __len__(self):
return len(self.results)
def is_present(self):
"""
Check whether the query returns any results.
Returns:
Boolean indicating whether the query contains any results.
"""
return bool(self.results)
present = property(is_present)
@property
def first(self):
"""
Return a Query that selects only the first element of this Query.
If no elements are available, returns a query with no results.
Example usage:
.. code:: python
>> q = Query(lambda: list(range(5)))
>> q.first.results
[0]
Returns:
Query
"""
def _transform(xs): # pylint: disable=missing-docstring, invalid-name
try:
return [six.next(iter(xs))]
except StopIteration:
return []
return self.transform(_transform, 'first')
def nth(self, index):
"""
Return a query that selects the element at `index` (starts from 0).
If no elements are available, returns a query with no results.
Example usage:
.. code:: python
>> q = Query(lambda: list(range(5)))
>> q.nth(2).results
[2]
Args:
index (int): The index of the element to select (starts from 0)
Returns:
Query
"""
def _transform(xs): # pylint: disable=missing-docstring, invalid-name
try:
return [next(islice(iter(xs), index, None))]
# Gracefully handle (a) running out of elements, and (b) negative indices
except (StopIteration, ValueError):
return []
return self.transform(_transform, 'nth')
def __repr__(self):
return u".".join([self.desc] + self.desc_stack)
class BrowserQuery(Query):
"""
A Query that operates on a browser.
"""
def __init__(self, browser, **kwargs):
"""
Generate a query over a browser.
Args:
browser (selenium.webdriver): A Selenium-controlled browser.
Keyword Args:
css (str): A CSS selector.
xpath (str): An XPath selector.
Returns:
BrowserQuery
Raises:
TypeError: The query must be passed either a CSS or XPath selector, but not both.
"""
if len(kwargs) > 1:
raise TypeError('BrowserQuery() takes at most 1 keyword argument.')
if not kwargs:
raise TypeError('Must pass a query keyword argument to BrowserQuery().')
query_name, query_value = list(kwargs.items())[0]
if query_name not in QUERY_TYPES:
raise TypeError('{} is not a supported query type for BrowserQuery()'.format(query_name))
def query_fn(): # pylint: disable=missing-docstring
return getattr(browser, QUERY_TYPES[query_name])(query_value)
super(BrowserQuery, self).__init__(
query_fn,
desc=u"BrowserQuery({}={!r})".format(query_name, query_value),
)
self.browser = browser
def attrs(self, attribute_name):
"""
Retrieve HTML attribute values from the elements matched by the query.
Example usage:
.. code:: python
# Assume that the query matches html elements:
# <div class="foo"> and <div class="bar">
>> q.attrs('class')
['foo', 'bar']
Args:
attribute_name (str): The name of the attribute values to retrieve.
Returns:
A list of attribute values for `attribute_name`.
"""
desc = 'attrs({!r})'.format(attribute_name)
return self.map(lambda el: el.get_attribute(attribute_name), desc).results
@property
def text(self):
"""
Retrieve text from each matched element.
Example usage:
.. code:: python
# Assume that the query matches html elements:
# <div>Foo</div> and <div>Bar</div>
>> q.text
['Foo', 'Bar']
Returns:
The text of each element matched by the query.
"""
return self.map(lambda el: el.text, 'text').results
@property
def html(self):
"""
Retrieve the inner HTML of each element matched by the query.
Example usage:
.. code:: python
# Assume that the query matches html elements:
# <div><span>Foo</span></div> and <div>Bar</div>
>> q.html
['<span>Foo</span>', 'Bar']
Returns:
The inner HTML for each element matched by the query.
"""
return self.map(lambda el: el.get_attribute('innerHTML'), 'html').results
@property
def selected(self):
"""
Check whether all the matched elements are selected.
Returns:
bool
"""
query_results = self.map(lambda el: el.is_selected(), 'selected').results
if query_results:
return all(query_results)
else:
return False
@property
def visible(self):
"""
Check whether all matched elements are visible.
Returns:
bool
"""
query_results = self.map(lambda el: el.is_displayed(), 'visible').results
if query_results:
return all(query_results)
else:
return False
@property
def invisible(self):
"""
Check whether all matched elements are present, but not visible.
Returns:
bool
"""
return self.present and not self.visible
def is_focused(self):
"""
Checks that *at least one* matched element is focused. More
specifically, it checks whether the element is document.activeElement.
If no matching element is focused, this returns `False`.
Returns:
bool
"""
active_el = self.browser.execute_script("return document.activeElement")
query_results = self.map(lambda el: el == active_el, 'focused').results
if query_results:
return any(query_results)
else:
return False
focused = property(is_focused)
def click(self):
"""
Click each matched element.
Example usage:
.. code:: python
# Click the first element matched by the query
q.first.click()
Returns:
None
"""
self.map(lambda el: el.click(), 'click()').execute()
def fill(self, text):
"""
Set the text value of each matched element to `text`.
Example usage:
.. code:: python
# Set the text of the first element matched by the query to "Foo"
q.first.fill('Foo')
Args:
text (str): The text used to fill the element (usually a text field or text area).
Returns:
None
"""
def _fill(elem): # pylint: disable=missing-docstring
elem.clear()
elem.send_keys(text)
self.map(_fill, 'fill({!r})'.format(text)).execute()