This repository has been archived by the owner on Mar 19, 2024. It is now read-only.
forked from SeleniumHQ/selenium
-
Notifications
You must be signed in to change notification settings - Fork 1
/
wire.py
executable file
·1904 lines (1641 loc) · 81.1 KB
/
wire.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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2008-2010 WebDriver committers
# Copyright 2008-2010 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Script for generating the wire protocol wiki documentation.
This script is probably overkill, but it ensures commands are documented with
consistent formatting.
Usage:
python trunk/wire.py --help
"""
import logging
import optparse
import os
import re
import sys
DEFAULT_WIKI_PATH = os.path.join('..', 'wiki', 'JsonWireProtocol.wiki')
class Resource(object):
def __init__(self, path):
self.path = path
self.methods = []
def __getattribute__(self, attr):
try:
return super(Resource, self).__getattribute__(attr)
except AttributeError, e:
if self.methods:
return self.methods[len(self.methods) - 1].__getattribute__(attr)
raise e
def Post(self, summary):
return self.AddMethod(Method(self, 'POST', summary))
def Get(self, summary):
return self.AddMethod(Method(self, 'GET', summary))
def Delete(self, summary):
return self.AddMethod(Method(self, 'DELETE', summary))
def AddMethod(self, method):
self.methods.append(method)
return self
def ToWikiString(self):
str = '=== %s ===\n' % self.path
for method in self.methods:
str = '%s%s' % (str, method.ToWikiString(self.path))
return str
def ToWikiTableString(self):
return ''.join(m.ToWikiTableString() for m in self.methods)
class SessionResource(Resource):
def AddMethod(self, method):
return (Resource.AddMethod(self, method).
AddUrlParameter(':sessionId',
'ID of the session to route the command to.'))
class ElementResource(SessionResource):
def AddMethod(self, method):
return (SessionResource.AddMethod(self, method).
AddUrlParameter(':id',
'ID of the element to route the command to.').
AddError('StaleElementReference',
'If the element referenced by `:id` is no longer attached '
'to the page\'s DOM.'))
def RequiresVisibility(self):
return self.AddError('ElementNotVisible',
'If the referenced element is not visible on the page '
'(either is hidden by CSS, has 0-width, or has 0-height)')
def RequiresEnabledState(self):
return self.AddError('InvalidElementState',
'If the referenced element is disabled.')
class Method(object):
def __init__(self, parent, method, summary):
self.parent = parent
self.method = method
self.summary = summary
self.url_parameters = []
self.json_parameters = []
self.return_type = None
self.errors = {}
def AddUrlParameter(self, name, description):
self.url_parameters.append({
'name': name,
'desc': description})
return self.parent
def AddJsonParameter(self, name, type, description):
self.json_parameters.append({
'name': name,
'type': type,
'desc': description})
return self.parent
def AddError(self, type, summary):
self.errors[type] = {'type': type, 'summary': summary}
return self.parent
def SetReturnType(self, type, description):
self.return_type = {
'type': type,
'desc': description}
return self.parent
def _GetUrlParametersWikiString(self):
if not self.url_parameters:
return ''
return '''
<dd>
<dl>
<dt>*URL Parameters:*</dt>
%s
</dl>
</dd>''' % '\n'.join('<dd>`%s` - %s</dd>' %
(param['name'], param['desc'])
for param in self.url_parameters)
def _GetJsonParametersWikiString(self):
if not self.json_parameters:
return ''
return '''
<dd>
<dl>
<dt>*JSON Parameters:*</dt>
%s
</dl>
</dd>''' % '\n'.join('<dd>`%s` - `%s` %s</dd>' %
(param['name'], param['type'], param['desc'])
for param in self.json_parameters)
def _GetReturnTypeWikiString(self):
if not self.return_type:
return ''
type = ''
if self.return_type['type']:
type = '`%s` ' % self.return_type['type']
return '''
<dd>
<dl>
<dt>*Returns:*</dt>
<dd>%s%s</dd>
</dl>
</dd>''' % (type, self.return_type['desc'])
def _GetErrorWikiString(self):
if not self.errors.values():
return ''
return '''
<dd>
<dl>
<dt>*Potential Errors:*</dt>
%s
</dl>
</dd>''' % '\n'.join('<dd>`%s` - %s</dd>' %
(error['type'], error['summary'])
for error in self.errors.values())
def ToWikiString(self, path):
return '''
<dl>
<dd>
==== %s %s ====
</dd>
<dd>
<dl>
<dd>%s</dd>%s%s%s%s
</dl>
</dd>
</dl>
''' % (self.method, path, self.summary,
self._GetUrlParametersWikiString(),
self._GetJsonParametersWikiString(),
self._GetReturnTypeWikiString(),
self._GetErrorWikiString())
def ToWikiTableString(self):
return '|| %s || [#%s_%s %s] || %s ||\n' % (
self.method, self.method, self.parent.path, self.parent.path,
self.summary[:self.summary.find('.') + 1].replace('\n', '').strip())
class ErrorCode(object):
def __init__(self, code, summary, detail):
self.code = code
self.summary = summary
self.detail = detail
def ToWikiTableString(self):
return '|| %d || `%s` || %s ||' % (self.code, self.summary, self.detail)
class AbstractErrorCodeGatherer(object):
def __init__(self, name, path_to_error_codes, regex):
self.name = name
self.path_to_error_codes = path_to_error_codes
self.regex = regex
def __str__(self):
return self.name
def get_error_codes(self):
error_codes = {}
error_codes_file = open(self.path_to_error_codes, 'r')
try:
for line in error_codes_file:
match = self.regex.match(line)
if match is not None:
name, code = self.extract_from_match(match)
error_codes[code] = name
finally:
error_codes_file.close()
return error_codes
def extract_from_match(self, match):
raise NotImplementedError
class JavaErrorCodeGatherer(AbstractErrorCodeGatherer):
def __init__(self, path_to_error_codes):
super(JavaErrorCodeGatherer, self).__init__( \
'Java',
path_to_error_codes, \
re.compile('^\s*public static final int ([A-Z_]+) = (\d+);$'))
def extract_from_match(self, match):
return match.group(1), int(match.group(2))
class JavascriptErrorCodeGatherer(AbstractErrorCodeGatherer):
def __init__(self, path_to_error_codes, name):
super(JavascriptErrorCodeGatherer, self).__init__( \
name,
path_to_error_codes, \
re.compile('^\s*([A-Z_]+): (\d+)'))
def extract_from_match(self, match):
return match.group(1), int(match.group(2))
class RubyErrorCodeGatherer(AbstractErrorCodeGatherer):
def __init__(self, path_to_error_codes):
super(RubyErrorCodeGatherer, self).__init__( \
'Ruby',
path_to_error_codes, \
re.compile('^\s*(([A-Z][a-z]*)+),?\s*# (\d+)$'))
def extract_from_match(self, match):
return match.group(1), int(match.group(len(match.groups())))
class PythonErrorCodeGatherer(AbstractErrorCodeGatherer):
def __init__(self, path_to_error_codes):
super(PythonErrorCodeGatherer, self).__init__( \
'Python',
path_to_error_codes, \
re.compile('^\s*([A-Z_]+) = (\d+)$'))
def extract_from_match(self, match):
return match.group(1), int(match.group(2))
class CErrorCodeGatherer(AbstractErrorCodeGatherer):
def __init__(self, path_to_error_codes):
super(CErrorCodeGatherer, self).__init__( \
'C',
path_to_error_codes, \
re.compile('^#define ([A-Z]+)\s+(\d+)$'))
def extract_from_match(self, match):
return match.group(1), int(match.group(2))
class CSharpErrorCodeGatherer(AbstractErrorCodeGatherer):
def __init__(self, path_to_error_codes):
super(CSharpErrorCodeGatherer, self).__init__( \
'C#',
path_to_error_codes, \
re.compile('^\s*(([A-Z][a-z]*)+) = (\d+)'))
def extract_from_match(self, match):
return match.group(1), int(match.group(len(match.groups())))
class ErrorCodeChecker(object):
def __init__(self):
self.gatherers = []
self.inconsistencies = {}
def using(self, gatherer):
self.gatherers.append(gatherer)
return self
def check_error_codes_are_consistent(self, json_error_codes):
logging.info('Checking error codes are consistent across languages and \
browsers')
num_missing = 0
for gatherer in self.gatherers:
if not os.path.exists(gatherer.path_to_error_codes):
logging.warn(' Unable to locate error codes for %s (//%s)',
gatherer, gatherer.path_to_error_codes)
num_missing += 1
else:
self.compare(gatherer, json_error_codes)
if not num_missing and not self.inconsistencies:
logging.info('All error codes are consistent')
return False
for code,(present,missing) in self.inconsistencies.items():
logging.error('Error code %d was present in %s but not %s',
code, present, missing)
return True
def add_inconsistency(self, code, present_in, missing_from):
if self.inconsistencies.has_key(code):
already_present, already_missing = self.inconsistencies[code]
already_present.add(present_in)
already_missing.add(missing_from)
else:
self.inconsistencies[code] = (set([present_in]), set([missing_from]))
def compare(self, gatherer, raw_json_error_codes):
logging.info('Checking %s (%s)' % (gatherer, gatherer.path_to_error_codes))
gathered_error_codes = gatherer.get_error_codes()
json_error_codes = map(lambda code: code.code, raw_json_error_codes)
for json_error_code in json_error_codes:
if not gathered_error_codes.has_key(json_error_code):
self.add_inconsistency(json_error_code, 'JSON', str(gatherer))
for gathered_code,_ in gathered_error_codes.items():
if not gathered_code in json_error_codes:
self.add_inconsistency(gathered_code, str(gatherer), 'JSON')
def GetDefaultWikiPath():
dirname = os.path.dirname(__file__)
if not dirname:
return DEFAULT_WIKI_PATH
return os.path.join('.', dirname, DEFAULT_WIKI_PATH)
def ChangeToTrunk():
dirname = os.path.dirname(__file__)
if dirname:
logging.info('Changing to %s', os.path.abspath(dirname))
os.chdir(dirname)
def main():
logging.basicConfig(format='[ %(filename)s ] %(message)s',
level=logging.INFO)
default_path = GetDefaultWikiPath()
parser = optparse.OptionParser('Usage: %prog [options]')
parser.add_option('-c', '--check_error_codes', dest='check_errors',
default=False,
help='Whether to abort if error codes are inconsistent.')
parser.add_option('-w', '--wiki', dest='wiki', metavar='FILE',
default=default_path,
help='Which file to write to. Defaults to %default')
(options, args) = parser.parse_args()
wiki_path = options.wiki
if wiki_path is not default_path:
wiki_path = os.path.abspath(wiki_path)
if not os.path.exists(wiki_path):
logging.error('Unable to locate wiki file: %s', wiki_path)
parser.print_help()
sys.exit(2)
wiki_path = os.path.abspath(wiki_path)
ChangeToTrunk()
error_codes = [
ErrorCode(0, 'Success', 'The command executed successfully.'),
ErrorCode(6, 'NoSuchDriver', 'A session is either terminated or not started'),
ErrorCode(7, 'NoSuchElement', 'An element could not be located on the \
page using the given search parameters.'),
ErrorCode(8, 'NoSuchFrame', 'A request to switch to a frame could not be \
satisfied because the frame could not be found.'),
ErrorCode(9, 'UnknownCommand', 'The requested resource could not be \
found, or a request was received using an HTTP method that is not supported \
by the mapped resource.'),
ErrorCode(10, 'StaleElementReference', 'An element command failed \
because the referenced element is no longer attached to the DOM.'),
ErrorCode(11, 'ElementNotVisible', 'An element command could not \
be completed because the element is not visible on the page.'),
ErrorCode(12, 'InvalidElementState', 'An element command could not be \
completed because the element is in an invalid state (e.g. attempting to \
click a disabled element).'),
ErrorCode(13, 'UnknownError', 'An unknown server-side error occurred \
while processing the command.'),
ErrorCode(15, 'ElementIsNotSelectable', 'An attempt was made to select \
an element that cannot be selected.'),
ErrorCode(17, 'JavaScriptError', 'An error occurred while executing user \
supplied !JavaScript.'),
ErrorCode(19, 'XPathLookupError', 'An error occurred while searching for \
an element by XPath.'),
ErrorCode(21, 'Timeout', 'An operation did not complete before its \
timeout expired.'),
ErrorCode(23, 'NoSuchWindow', 'A request to switch to a different window \
could not be satisfied because the window could not be found.'),
ErrorCode(24, 'InvalidCookieDomain', 'An illegal attempt was made to set \
a cookie under a different domain than the current page.'),
ErrorCode(25, 'UnableToSetCookie', 'A request to set a cookie\'s value \
could not be satisfied.'),
ErrorCode(26, 'UnexpectedAlertOpen', 'A modal dialog was open, blocking \
this operation'),
ErrorCode(27, 'NoAlertOpenError', 'An attempt was made to operate on a \
modal dialog when one was not open.'),
ErrorCode(28, 'ScriptTimeout', 'A script did not complete before its \
timeout expired.'),
ErrorCode(29, 'InvalidElementCoordinates', 'The coordinates provided to \
an interactions operation are invalid.'),
ErrorCode(30, 'IMENotAvailable', 'IME was not available.'),
ErrorCode(31, 'IMEEngineActivationFailed', 'An IME engine could not be \
started.'),
ErrorCode(32, 'InvalidSelector', 'Argument was an invalid selector \
(e.g. XPath/CSS).'),
ErrorCode(33, 'SessionNotCreatedException', 'A new session could not be created.'),
ErrorCode(34, 'MoveTargetOutOfBounds', 'Target provided for a move action is out of bounds.')
]
error_checker = ErrorCodeChecker() \
.using(JavaErrorCodeGatherer('java/client/src/org/openqa/selenium/remote/ErrorCodes.java')) \
.using(JavascriptErrorCodeGatherer('javascript/atoms/error.js', 'Javascript atoms')) \
.using(JavascriptErrorCodeGatherer('javascript/firefox-driver/js/errorcode.js', 'Javascript firefox driver')) \
.using(RubyErrorCodeGatherer('rb/lib/selenium/webdriver/common/error.rb')) \
.using(PythonErrorCodeGatherer('py/selenium/webdriver/remote/errorhandler.py')) \
.using(CErrorCodeGatherer('cpp/webdriver-interactions/errorcodes.h')) \
.using(CSharpErrorCodeGatherer('dotnet/src/WebDriver/WebDriverResult.cs'))
if (not error_checker.check_error_codes_are_consistent(error_codes)
and options.check_errors):
sys.exit(1)
resources = []
resources.append(Resource('/status').
Get('''
Query the server\'s current status. The server should respond with a general \
"HTTP 200 OK" response if it is alive and accepting commands. The response \
body should be a JSON object describing the state of the server. All server \
implementations should return two basic objects describing the server's \
current platform and when the server was built. All fields are optional; \
if omitted, the client should assume the value is uknown. Furthermore, \
server implementations may include additional fields not listed here.
|| *Key* || *Type* || *Description* ||
|| build || object || ||
|| build.version || string || A generic release label (i.e. "2.0rc3") ||
|| build.revision || string || The revision of the local source control client \
from which the server was built ||
|| build.time || string || A timestamp from when the server was built. ||
|| os || object || ||
|| os.arch || string || The current system architecture. ||
|| os.name || string || The name of the operating system the server is \
currently running on: "windows", "linux", etc. ||
|| os.version || string || The operating system version. ||
''').
SetReturnType('{object}',
'An object describing the general status of the server.'))
resources.append(
Resource('/session').
Post('''
Create a new session. The server should attempt to create a session that most \
closely matches the desired and required capabilities. Required capabilities \
have higher priority than desired capabilities and must be set for the session \
to be created.''').
AddJsonParameter('desiredCapabilities',
'{object}',
'An object describing the session\'s '
'[#Desired_Capabilities desired capabilities].').
AddJsonParameter('requiredCapabilities',
'{object}',
'An object describing the session\'s '
'[#Desired_Capabilities required capabilities] (Optional).').
SetReturnType('{object}',
'An object describing the session\'s '
'[#Actual_Capabilities capabilities].').
AddError('SessionNotCreatedException', 'If a required capability could not be set.'))
resources.append(
Resource('/sessions').
Get('''
Returns a list of the currently active sessions. Each session will be \
returned as a list of JSON objects with the following keys:
|| *Key* || *Type* || *Description ||
|| id || string || The session ID. ||
|| capabilities || object || An object describing the session's \
[#Actual_Capabilities capabilities]. ||
''').
SetReturnType('{Array.<Object>}',
'A list of the currently active sessions.'))
resources.append(
SessionResource('/session/:sessionId').
Get('Retrieve the capabilities of the specified session.').
SetReturnType('{object}',
'An object describing the session\'s '
'[#Actual_Capabilities capabilities].').
Delete('Delete the session.'))
resources.append(
SessionResource('/session/:sessionId/timeouts').
Post('''
Configure the amount of time that a particular type of operation can execute \
for before they are aborted and a |Timeout| error is returned to the \
client.''').
AddJsonParameter('type', '{string}',
'The type of operation to set the timeout for. Valid \
values are: "script" for script timeouts, "implicit" for modifying the \
implicit wait timeout and "page load" for setting a page load timeout.').
AddJsonParameter('ms', '{number}',
'The amount of time, in milliseconds, that time-limited'
' commands are permitted to run.'))
resources.append(
SessionResource('/session/:sessionId/timeouts/async_script').
Post('''Set the amount of time, in milliseconds, that asynchronous \
scripts executed by `/session/:sessionId/execute_async` are permitted to run \
before they are aborted and a |Timeout| error is returned to the client.''').
AddJsonParameter('ms', '{number}',
'The amount of time, in milliseconds, that time-limited'
' commands are permitted to run.'))
resources.append(
SessionResource('/session/:sessionId/timeouts/implicit_wait').
Post('''Set the amount of time the driver should wait when searching for \
elements. When
searching for a single element, the driver should poll the page until an \
element is found or
the timeout expires, whichever occurs first. When searching for multiple \
elements, the driver
should poll the page until at least one element is found or the timeout \
expires, at which point
it should return an empty list.
If this command is never sent, the driver should default to an implicit wait of\
0ms.''').
AddJsonParameter('ms', '{number}',
'The amount of time to wait, in milliseconds. This value'
' has a lower bound of 0.'))
resources.append(
SessionResource('/session/:sessionId/window_handle').
Get('Retrieve the current window handle.').
SetReturnType('{string}', 'The current window handle.').
AddError('NoSuchWindow',
'If the currently selected window has been closed.'))
resources.append(
SessionResource('/session/:sessionId/window_handles').
Get('Retrieve the list of all window handles available to the session.').
SetReturnType('{Array.<string>}', 'A list of window handles.'))
resources.append(
SessionResource('/session/:sessionId/url').
Get('Retrieve the URL of the current page.').
SetReturnType('{string}', 'The current URL.').
AddError('NoSuchWindow',
'If the currently selected window has been closed.').
Post('Navigate to a new URL.').
AddJsonParameter('url', '{string}', 'The URL to navigate to.').
AddError('NoSuchWindow',
'If the currently selected window has been closed.'))
resources.append(
SessionResource('/session/:sessionId/forward').
Post('Navigate forwards in the browser history, if possible.').
AddError('NoSuchWindow',
'If the currently selected window has been closed.'))
resources.append(
SessionResource('/session/:sessionId/back').
Post('Navigate backwards in the browser history, if possible.').
AddError('NoSuchWindow',
'If the currently selected window has been closed.'))
resources.append(
SessionResource('/session/:sessionId/refresh').
Post('Refresh the current page.').
AddError('NoSuchWindow',
'If the currently selected window has been closed.'))
resources.append(
SessionResource('/session/:sessionId/execute').
Post('''
Inject a snippet of !JavaScript into the page for execution in the context of \
the currently selected frame. The executed script is assumed to be \
synchronous and the result of evaluating the script is returned to the client.
The `script` argument defines the script to execute in the form of a \
function body. The value returned by that function will be returned to the \
client. The function will be invoked with the provided `args` array and the \
values may be accessed via the `arguments` object in the order specified.
Arguments may be any JSON-primitive, array, or JSON object. JSON objects that \
define a [#WebElement_JSON_Object WebElement reference] will be converted to \
the corresponding DOM element. Likewise, any !WebElements in the script result \
will be returned to the client as [#WebElement_JSON_Object WebElement \
JSON objects].''').
AddJsonParameter('script', '{string}', 'The script to execute.').
AddJsonParameter('args', '{Array.<*>}', 'The script arguments.').
AddError('JavaScriptError', 'If the script throws an Error.').
AddError('StaleElementReference',
'If one of the script arguments is a !WebElement that is not '
'attached to the page\'s DOM.').
AddError('NoSuchWindow',
'If the currently selected window has been closed.').
SetReturnType('{*}', 'The script result.'))
resources.append(
SessionResource('/session/:sessionId/execute_async').
Post('''
Inject a snippet of !JavaScript into the page for execution in the context of \
the currently selected frame. The executed script is assumed to be \
asynchronous and must signal that is done by invoking the provided callback, \
which is always provided as the final argument to the function. The value \
to this callback will be returned to the client.
Asynchronous script commands may not span page loads. If an `unload` event is \
fired while waiting for a script result, an error should be returned to the \
client.
The `script` argument defines the script to execute in teh form of a function \
body. The function will be invoked with the provided `args` array and the \
values may be accessed via the `arguments` object in the order specified. The \
final argument will always be a callback function that must be invoked to \
signal that the script has finished.
Arguments may be any JSON-primitive, array, or JSON object. JSON objects that \
define a [#WebElement_JSON_Object WebElement reference] will be converted to \
the corresponding DOM element. Likewise, any !WebElements in the script result \
will be returned to the client as [#WebElement_JSON_Object WebElement \
JSON objects].''').
AddJsonParameter('script', '{string}', 'The script to execute.').
AddJsonParameter('args', '{Array.<*>}', 'The script arguments.').
AddError('JavaScriptError',
'If the script throws an Error or if an `unload` event is '
'fired while waiting for the script to finish.').
AddError('StaleElementReference',
'If one of the script arguments is a !WebElement that is not '
'attached to the page\'s DOM.').
AddError('Timeout',
'If the script callback is not invoked before the timout '
'expires. Timeouts are controlled by the '
'`/session/:sessionId/timeout/async_script` command.').
AddError('NoSuchWindow',
'If the currently selected window has been closed.').
SetReturnType('{*}', 'The script result.'))
resources.append(
SessionResource('/session/:sessionId/screenshot').
Get('Take a screenshot of the current page.').
AddError('NoSuchWindow',
'If the currently selected window has been closed.').
SetReturnType('{string}', 'The screenshot as a base64 encoded PNG.'))
resources.append(
SessionResource('/session/:sessionId/ime/available_engines').
Get('List all available engines on the machine. To use an engine, it has to be present in this list.').
AddError('ImeNotAvailableException', 'If the host does not support IME').
SetReturnType('{Array.<string>}', 'A list of available engines'))
resources.append(
SessionResource('/session/:sessionId/ime/active_engine').
Get('Get the name of the active IME engine. The name string is platform specific.').
AddError('ImeNotAvailableException', 'If the host does not support IME').
SetReturnType('{string}', 'The name of the active IME engine.'))
resources.append(
SessionResource('/session/:sessionId/ime/activated').
Get('Indicates whether IME input is active at the moment (not if it\'s available.').
AddError('ImeNotAvailableException', 'If the host does not support IME').
SetReturnType('{boolean}',
'true if IME input is available and currently active, false otherwise'))
resources.append(
SessionResource('/session/:sessionId/ime/deactivate').
Post('De-activates the currently-active IME engine.').
AddError('ImeNotAvailableException', 'If the host does not support IME'))
resources.append(
SessionResource('/session/:sessionId/ime/activate').
Post('''Make an engines that is available (appears on the list
returned by getAvailableEngines) active. After this call, the engine will
be added to the list of engines loaded in the IME daemon and the input sent
using sendKeys will be converted by the active engine.
Note that this is a platform-independent method of activating IME
(the platform-specific way being using keyboard shortcuts''').
AddJsonParameter('engine', '{string}',
'Name of the engine to activate.').
AddError('ImeActivationFailedException',
'If the engine is not available or if the activation fails for other reasons.').
AddError('ImeNotAvailableException', 'If the host does not support IME'))
resources.append(
SessionResource('/session/:sessionId/frame').
Post('''Change focus to another frame on the page. If the frame `id` is \
`null`, the server
should switch to the page's default content.''').
AddJsonParameter('id', '{string|number|null|WebElement JSON Object}',
'Identifier for the frame to change focus to.').
AddError('NoSuchWindow',
'If the currently selected window has been closed.').
AddError('NoSuchFrame', 'If the frame specified by `id` cannot be found.'))
resources.append(
SessionResource('/session/:sessionId/frame/parent').
Post('''Change focus to the parent context. If the current context is the top level \
browsing context, the context remains unchanged.'''))
resources.append(
SessionResource('/session/:sessionId/window').
Post('''Change focus to another window. The window to change focus to \
may be specified by its
server assigned window handle, or by the value of its `name` attribute.''').
AddJsonParameter('name', '{string}', 'The window to change focus to.').
AddError('NoSuchWindow', 'If the window specified by `name` cannot be found.').
Delete('''Close the current window.''').
AddError('NoSuchWindow', 'If the currently selected window is already closed'))
resources.append(
SessionResource('/session/:sessionId/window/:windowHandle/size').
Post('''Change the size of the specified window. If the :windowHandle URL \
parameter is "current", the currently active window will be resized.''').
AddJsonParameter('width', '{number}', 'The new window width.').
AddJsonParameter('height', '{number}', 'The new window height.').
Get('''Get the size of the specified window. If the :windowHandle URL \
parameter is "current", the size of the currently active window will be returned.''').
SetReturnType('{width: number, height: number}', 'The size of the window.').
AddError('NoSuchWindow', 'If the specified window cannot be found.'))
resources.append(
SessionResource('/session/:sessionId/window/:windowHandle/position').
Post('''Change the position of the specified window. If the :windowHandle URL \
parameter is "current", the currently active window will be moved.''').
AddJsonParameter('x', '{number}', 'The X coordinate to position the window at, \
relative to the upper left corner of the screen.').
AddJsonParameter('y', '{number}', 'The Y coordinate to position the window at, \
relative to the upper left corner of the screen.') .
AddError('NoSuchWindow', 'If the specified window cannot be found.').
Get('''Get the position of the specified window. If the :windowHandle URL \
parameter is "current", the position of the currently active window will be returned.''').
SetReturnType('{x: number, y: number}', 'The X and Y coordinates for the window, \
relative to the upper left corner of the screen.').
AddError('NoSuchWindow', 'If the specified window cannot be found.'))
resources.append(
SessionResource('/session/:sessionId/window/:windowHandle/maximize').
Post('''Maximize the specified window if not already maximized. If the \
:windowHandle URL parameter is "current", the currently active window will be \
maximized.''').
AddError('NoSuchWindow', 'If the specified window cannot be found.'))
resources.append(
SessionResource('/session/:sessionId/cookie').
Get('Retrieve all cookies visible to the current page.').
AddError('NoSuchWindow',
'If the currently selected window has been closed.').
SetReturnType('{Array.<object>}', 'A list of [#Cookie_JSON_Object cookies].').
Post('''Set a cookie. If the [#Cookie_JSON_Object cookie] path is not \
specified, it should be set to `"/"`. Likewise, if the domain is omitted, it \
should default to the current page's domain.''').
AddJsonParameter('cookie', '{object}',
'A [#Cookie_JSON_Object JSON object] defining the '
'cookie to add.').
Delete('''Delete all cookies visible to the current page.''').
AddError('InvalidCookieDomain',
'If the cookie\'s `domain` is not visible from the current page.').
AddError('NoSuchWindow',
'If the currently selected window has been closed.').
AddError('UnableToSetCookie',
'If attempting to set a cookie on a page that does not support '
'cookies (e.g. pages with mime-type `text/plain`).'))
resources.append(
SessionResource('/session/:sessionId/cookie/:name').
Delete('''Delete the cookie with the given name. This command should be \
a no-op if there is no
such cookie visible to the current page.''').
AddUrlParameter(':name', 'The name of the cookie to delete.').
AddError('NoSuchWindow',
'If the currently selected window has been closed.'))
resources.append(
SessionResource('/session/:sessionId/source').
Get('Get the current page source.').
SetReturnType('{string}', 'The current page source.').
AddError('NoSuchWindow',
'If the currently selected window has been closed.'))
resources.append(
SessionResource('/session/:sessionId/title').
Get('Get the current page title.').
SetReturnType('{string}', 'The current page title.').
AddError('NoSuchWindow',
'If the currently selected window has been closed.'))
resources.append(
SessionResource('/session/:sessionId/element').
Post('''Search for an element on the page, starting from the document \
root. The located element will be returned as a WebElement JSON object. \
The table below lists the locator strategies that each server should support. \
Each locator must return the first matching element located in the DOM.
|| *Strategy* || *Description* ||
|| class name || Returns an element whose class name contains the search \
value; compound class names are not permitted. ||
|| css selector || Returns an element matching a CSS selector. ||
|| id || Returns an element whose ID attribute matches the search value. ||
|| name || Returns an element whose NAME attribute matches the search value. ||
|| link text || Returns an anchor element whose visible text matches the \
search value. ||
|| partial link text || Returns an anchor element whose visible text \
partially matches the search value. ||
|| tag name || Returns an element whose tag name matches the search value. ||
|| xpath || Returns an element matching an XPath expression. ||
''').
AddJsonParameter('using', '{string}', 'The locator strategy to use.').
AddJsonParameter('value', '{string}', 'The The search target.').
SetReturnType('{ELEMENT:string}',
'A WebElement JSON object for the located element.').
AddError('XPathLookupError', 'If using XPath and the input expression is invalid.').
AddError('NoSuchElement', 'If the element cannot be found.').
AddError('NoSuchWindow',
'If the currently selected window has been closed.'))
resources.append(
SessionResource('/session/:sessionId/elements').
Post('''Search for multiple elements on the page, starting from the \
document root. The located elements will be returned as a WebElement JSON \
objects. The table below lists the locator strategies that each server should \
support. Elements should be returned in the order located in the DOM.
|| *Strategy* || *Description* ||
|| class name || Returns all elements whose class name contains the search \
value; compound class names are not permitted. ||
|| css selector || Returns all elements matching a CSS selector. ||
|| id || Returns all elements whose ID attribute matches the search value. ||
|| name || Returns all elements whose NAME attribute matches the search value. ||
|| link text || Returns all anchor elements whose visible text matches the \
search value. ||
|| partial link text || Returns all anchor elements whose visible text \
partially matches the search value. ||
|| tag name || Returns all elements whose tag name matches the search value. ||
|| xpath || Returns all elements matching an XPath expression. ||
''').
AddJsonParameter('using', '{string}', 'The locator strategy to use.').
AddJsonParameter('value', '{string}', 'The The search target.').
SetReturnType('{Array.<{ELEMENT:string}>}',
'A list of WebElement JSON objects for the located elements.').
AddError('XPathLookupError', 'If using XPath and the input expression is invalid.') .
AddError('NoSuchWindow',
'If the currently selected window has been closed.'))
resources.append(
SessionResource('/session/:sessionId/element/active').
Post('Get the element on the page that currently has focus. The element will be returned as '
'a WebElement JSON object.').
SetReturnType('{ELEMENT:string}', 'A WebElement JSON object for the active element.') .
AddError('NoSuchWindow',
'If the currently selected window has been closed.'))
resources.append(
ElementResource('/session/:sessionId/element/:id').
Get('''Describe the identified element.
*Note:* This command is reserved for future use; its return type is currently \
undefined.''').
AddError('NoSuchWindow',
'If the currently selected window has been closed.'))
resources.append(
ElementResource('/session/:sessionId/element/:id/element').
Post('''Search for an element on the page, starting from the identified \
element. The located element will be returned as a WebElement JSON object. \
The table below lists the locator strategies that each server should support. \
Each locator must return the first matching element located in the DOM.
|| *Strategy* || *Description* ||
|| class name || Returns an element whose class name contains the search \
value; compound class names are not permitted. ||
|| css selector || Returns an element matching a CSS selector. ||
|| id || Returns an element whose ID attribute matches the search value. ||
|| name || Returns an element whose NAME attribute matches the search value. ||
|| link text || Returns an anchor element whose visible text matches the \
search value. ||
|| partial link text || Returns an anchor element whose visible text \
partially matches the search value. ||
|| tag name || Returns an element whose tag name matches the search value. ||
|| xpath || Returns an element matching an XPath expression. The provided \
XPath expression must be applied to the server "as is"; if the expression is \
not relative to the element root, the server should not modify it. \
Consequently, an XPath query may return elements not contained in the root \
element's subtree. ||
''').
AddJsonParameter('using', '{string}', 'The locator strategy to use.').
AddJsonParameter('value', '{string}', 'The The search target.').
SetReturnType('{ELEMENT:string}',
'A WebElement JSON object for the located element.').
AddError('NoSuchElement', 'If the element cannot be found.').
AddError('XPathLookupError', 'If using XPath and the input expression is invalid.').
AddError('NoSuchWindow',
'If the currently selected window has been closed.'))
resources.append(
ElementResource('/session/:sessionId/element/:id/elements').
Post('''Search for multiple elements on the page, starting from the \
identified element. The located elements will be returned as a WebElement \
JSON objects. The table below lists the locator strategies that each server \
should support. Elements should be returned in the order located in the DOM.
|| *Strategy* || *Description* ||
|| class name || Returns all elements whose class name contains the search \
value; compound class names are not permitted. ||
|| css selector || Returns all elements matching a CSS selector. ||
|| id || Returns all elements whose ID attribute matches the search value. ||
|| name || Returns all elements whose NAME attribute matches the search value. ||
|| link text || Returns all anchor elements whose visible text matches the \
search value. ||
|| partial link text || Returns all anchor elements whose visible text \
partially matches the search value. ||
|| tag name || Returns all elements whose tag name matches the search value. ||
|| xpath || Returns all elements matching an XPath expression. The provided \
XPath expression must be applied to the server "as is"; if the expression is \
not relative to the element root, the server should not modify it. \
Consequently, an XPath query may return elements not contained in the root \
element's subtree. ||
''').
AddJsonParameter('using', '{string}', 'The locator strategy to use.').
AddJsonParameter('value', '{string}', 'The The search target.').
SetReturnType('{Array.<{ELEMENT:string}>}',
'A list of WebElement JSON objects for the located elements.').
AddError('XPathLookupError', 'If using XPath and the input expression is invalid.') .
AddError('NoSuchWindow',
'If the currently selected window has been closed.'))
resources.append(
ElementResource('/session/:sessionId/element/:id/click').
Post('Click on an element.').
RequiresVisibility().
AddError('NoSuchWindow',
'If the currently selected window has been closed.'))
resources.append(
ElementResource('/session/:sessionId/element/:id/submit').
Post('Submit a `FORM` element. The submit command may also be applied to any element that is '
'a descendant of a `FORM` element.').
AddError('NoSuchWindow',
'If the currently selected window has been closed.'))
resources.append(
ElementResource('/session/:sessionId/element/:id/text').
Get('Returns the visible text for the element.').
AddError('NoSuchWindow',
'If the currently selected window has been closed.'))
resources.append(
ElementResource('/session/:sessionId/element/:id/value').
Post('''Send a sequence of key strokes to an element.
Any UTF-8 character may be specified, however, if the server does not support \