-
Notifications
You must be signed in to change notification settings - Fork 7
/
user-extensions.js
2382 lines (2170 loc) · 82.8 KB
/
user-extensions.js
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
// To use Selblocks commands in Selenium Server, provide this file on the command line.
// Eg: -userExtensions "C:\somewhere\user-extensions.js"
// ================================================================================
// from: name-space.js
// SelBlocks name-space
var selblocks = {
name: "selblocks"
,seleniumEnv: "ide"
,globalContext: this // alias for global Selenium scope
};
(function($$){
$$.fn = {};
/* Starting with FF4 lots of objects are in an XPCNativeWrapper,
* and we need the underlying object for == and for..in operations.
*/
$$.unwrapObject = function(obj) {
if (typeof(obj) === "undefined" || obj == null)
return obj;
if (obj.wrappedJSObject)
return obj.wrappedJSObject;
return obj;
};
$$.fmtCmd = function(cmd) {
var c = cmd.command;
if (cmd.target) { c += "|" + cmd.target; }
if (cmd.value) { c += "|" + cmd.value; }
return c;
}
}(selblocks));
// ================================================================================
// from: logger.js
// selbocks name-space
(function($$){
/* LOG wrapper for SelBlocks-specific behavior
*/
function Logger()
{
this.error = function (msg) { this.logit("error", msg); };
this.warn = function (msg) { this.logit("warn", msg); };
this.info = function (msg) { this.logit("info", msg); };
this.debug = function (msg) { this.logit("debug", msg); };
this.trace = function (msg) { this.logit("debug", msg); }; // selenium doesn't have trace level
this.logit = function (logLevel, msg) {
LOG[logLevel]("[" + $$.name + "] " + msg); // call the Selenium logger
};
// ==================== Stack Tracer ====================
this.genStackTrace = function(err)
{
var e = err || new Error();
var stackTrace = [];
if (!e.stack)
stackTrace.push("No stack trace, (Firefox only)");
else {
var funcCallPattern = /^\s*[A-Za-z0-9\-_\$]+\(/;
var lines = e.stack.split("\n");
for (var i=0; i < lines.length; i++) {
if (lines[i].match(funcCallPattern))
stackTrace.push(lines[i]);
}
if (!err)
stackTrace.shift(); // remove the call to genStackTrace() itself
}
return stackTrace;
};
this.logStackTrace = function(err)
{
var t = this.genStackTrace(err);
if (!err)
t.shift(); // remove the call to logStackTrace() itself
this.warn("__Stack Trace__");
for (var i = 0; i < t.length; i++) {
this.warn("@@ " + t[i]);
}
};
// describe the calling function
this.descCaller = function()
{
var t = this.genStackTrace(new Error());
if (t.length == 0) return "no client function";
t.shift(); // remove the call to descCaller() itself
if (t.length == 0) return "no caller function";
t.shift(); // remove the call to client function
if (t.length == 0) return "undefined caller function";
return "caller: " + t[0];
};
}
$$.LOG = new Logger();
}(selblocks));
// ================================================================================
// from: expression-parser.js
/** Parse basic expressions.
*/
// selbocks name-space
(function($$){
$$.InfixExpressionParser =
{
_objname : "InfixExpressionParser"
,BRACKET_PAIRS : { "(": ")", "{": "}", "[": "]" }
,trimListValues : true
//- Parse a string into a list on the given delimiter character,
// respecting embedded quotes and brackets
,splitList : function(str, delim)
{
var values = [];
var prev = 0, cur = 0;
while (cur < str.length) {
if (str.charAt(cur) != delim) {
cur = this.spanSub(str, cur);
if (cur == -1)
throw new Error("Unbalanced expression grouping at: " + str.substr(prev));
}
else {
var value = str.substring(prev, cur);
if (this.trimListValues)
value = value.trim();
values.push(value);
prev = cur + 1;
}
cur++;
}
values.push(str.substring(prev));
if (values.length == 1 && values[0].trim() == "") {
values.length = 0;
}
return values;
}
//- Scan to the given chr, skipping over intervening matching brackets
,spanTo : function(str, i, chr)
{
while (str.charAt(i) != chr) {
i = this.spanSub(str, i);
if (i == -1 || i >= str.length)
return -1;
i++;
}
return i;
}
//- If character at the given index is a open/quote character, then scan to its matching close/quote
,spanSub : function(str, i)
{
if (i < str.length) {
if (str.charAt(i) == "(") return this.spanTo(str, i+1, ")"); // recursively skip over intervening matching brackets
else if (str.charAt(i) == "[") return this.spanTo(str, i+1, "]");
else if (str.charAt(i) == "{") return this.spanTo(str, i+1, "}");
else if (str.charAt(i) == "'") return str.indexOf("'", i+1); // no special meaning for intervening brackets
else if (str.charAt(i) == '"') return str.indexOf('"', i+1);
}
return i;
}
//- Format the given values array into a delimited list string
// An optional transformFunc operates on each value.
,formatList : function(delim, values, left, transformFunc, right)
{
var buf = "";
for (var i = 0; i < values.length; i++) {
var value = ((transformFunc) ? transformFunc(values[i], i) : values[i]);
if (buf) buf += delim || " ";
if (left) buf += left;
if (value) buf += value;
if (right) buf += right;
}
return buf;
}
};
}(selblocks));
// ================================================================================
// from: function-intercepting.js
// selbocks name-space
(function($$){
/* Function interception
*/
// execute the given function before each call of the specified function
$$.fn.interceptBefore = function(targetObj, targetFnName, _fn) {
var existing_fn = targetObj[targetFnName];
targetObj[targetFnName] = function() {
_fn.call(this);
return existing_fn.call(this);
};
};
// execute the given function after each call of the specified function name
$$.fn.interceptAfter = function(targetObj, targetFnName, _fnAfter) {
var existing_fn = targetObj[targetFnName];
targetObj[targetFnName] = function() {
var args = Array.prototype.slice.call(arguments);
existing_fn.apply(this, args);
return _fnAfter.apply(this, args);
};
};
// replace the specified function with the given function
$$.fn.interceptReplace = function(targetObj, targetFnName, _fn) {
targetObj[targetFnName] = function() {
//var existing_fn = targetObj[targetFnName] = _fn;
return _fn.call(this);
};
};
$$.fn.interceptStack = [];
// replace the specified function, saving the original function on a stack
$$.fn.interceptPush = function(targetObj, targetFnName, _fnTemp, frameAttrs) {
var frame = {
targetObj: targetObj
,targetFnName: targetFnName
,savedFn: targetObj[targetFnName]
,attrs: frameAttrs
};
$$.fn.interceptStack.push(frame);
targetObj[targetFnName] = _fnTemp;
};
// restore the most recent function replacement
$$.fn.interceptPop = function() {
var frame = $$.fn.interceptStack.pop();
frame.targetObj[frame.targetFnName] = frame.savedFn;
};
$$.fn.getInterceptTop = function() {
return $$.fn.interceptStack[$$.fn.interceptStack.length-1];
};
// replace the specified function, but then restore the original function as soon as it is call
$$.fn.interceptOnce = function(targetObj, targetFnName, _fn) {
$$.fn.interceptPush(targetObj, targetFnName, function(){
$$.fn.interceptPop(); // un-intercept
var args = Array.prototype.slice.call(arguments);
_fn.apply(this, args);
});
};
}(selblocks));
// ================================================================================
// from: user-extensions-base.js
/*jslint
indent:2
,maxerr:500
,plusplus:true
,white:true
,nomen:true
*/
/*globals
Selenium:true,
htmlTestRunner:true
*/
(function($$){
$$.seleniumEnv = "server";
// this flag is global so that SelBlocks and SelBench can be used together
$$.globalContext.serverPatchApplied = $$.globalContext.serverPatchApplied || false;
if (!$$.globalContext.serverPatchApplied) {
$$.LOG.info("Applying testCase server patch for " + $$.name);
$$.fn.interceptAfter(Selenium.prototype, "reset", initTestCase);
$$.globalContext.serverPatchApplied = true;
}
// Selenium Core does not have the testCase object
// but the currentTest object can be extended for our purposes
function initTestCase()
{
if (!(typeof htmlTestRunner === "undefined" || htmlTestRunner === null)) {
// TBD: map commands to real types instead of faking it
htmlTestRunner.currentTest.commands = mapCommands(htmlTestRunner.currentTest.htmlTestCase.getCommandRows());
$$.globalContext.testCase = htmlTestRunner.currentTest;
// debugContext isn't on this object, but redirecting to the currentTest seems to work
$$.globalContext.testCase.debugContext = htmlTestRunner.currentTest;
// define pseudo properties with getters/setters on a hidden property,
// so that they both maintain the same value.
Object.defineProperties($$.globalContext.testCase, {
"_nextCommandRowIndex" : {
writable : true
}
,"debugIndex" : { // for IDE
enumerable : true
,get : function () { return this._nextCommandRowIndex; }
,set : function (idx) { this._nextCommandRowIndex = idx; }
}
,"nextCommandRowIndex" : { // for Selenium Server
enumerable : true
,get : function () { return this._nextCommandRowIndex; }
,set : function (idx) { this._nextCommandRowIndex = idx; }
}
});
}
function mapCommands(cmdRows) {
var mappedCmds = [];
for (var i = 0; i < cmdRows.length; ++i) {
mappedCmds.push(importCommand(cmdRows[i]));
}
return mappedCmds;
}
function importCommand(cmdRow) {
var cmd = cmdRow.getCommand();
if (cmdRow.hasOwnProperty("trElement")) {
cmd.type = "command";
} else {
cmd.type = "comment";
}
return cmd;
}
}
}(selblocks));
// ================================================================================
// from: selblocks.js
/*
* SelBlocks 2.1
*
* Provides commands for Javascript-like looping and callable functions,
* with scoped variables, and JSON/XML driven parameterization.
*
* (SelBlocks installs as a Core Extension, not an IDE Extension, because it manipulates the Selenium object)
*
* Concept of operation:
* - Selenium.reset() is intercepted to initialize the block structures.
* - testCase.nextCommand() is overridden for flow branching.
* - TestLoop.resume() is overridden by exitTest, and by try/catch/finally to manage the outcome of errors.
* - The static structure of command blocks is stored in blockDefs[] by script line number.
* E.g., ifDef has pointers to its corresponding elseIf, else, endIf commands.
* - The state of each function-call is pushed/popped on callStack as it begins/ends execution
* The state of each block is pushed/popped on the blockStack as it begins/ends execution.
* An independent blockStack is associated with each function-call. I.e., stacks stored on a stack.
* (Non-block commands do not appear on the blockStack.)
*
* Limitations:
* - Incompatible with flowControl (and derivatives), because they unilaterally override selenium.reset().
* Known to have this issue:
* selenium_ide__flow_control
* goto_while_for_ide
*
* Acknowledgements:
* SelBlocks reuses bits & parts of extensions: flowControl, datadriven, and include.
*
* Wishlist:
* - show line numbers in the IDE
* - validation of JSON & XML input files
* - highlight a command that is failed-but-caught in blue
*
* Changes since 1.5:
* - added try/catch/finally, elseIf, and exitTest commands
* - block boundaries enforced (jumping in-to and/or out-of the middle of blocks)
* - script/endScript is replaced by function/endFunction
* - implicit initialization of for loop variable(s)
* - improved validation of command expressions
*
* NOTE - The only thing special about SelBlocks parameters is that they are activated and deactivated
* as script execution flows into and out of blocks, (for/endFor, function/endFunction, etc).
* They are implemented as regular Selenium variables, and therefore the progress of an executing
* script can be monitored using the Stored Variables Viewer addon.
*/
// =============== global functions as script helpers ===============
// getEval script helpers
// Find an element via locator independent of any selenium commands
// (findElementOrNull returns the first if there are multiple matches)
function $e(locator) {
return selblocks.unwrapObject(selenium.browserbot.findElementOrNull(locator));
}
// Return the singular XPath result as a value of the appropriate type
function $x(xpath, contextNode, resultType) {
var doc = selenium.browserbot.getDocument();
var node;
if (resultType) {
node = selblocks.xp.selectNode(doc, xpath, contextNode, resultType); // mozilla engine only
}
else {
node = selblocks.xp.selectElement(doc, xpath, contextNode);
}
return node;
}
// Return the XPath result set as an array of elements
function $X(xpath, contextNode, resultType) {
var doc = selenium.browserbot.getDocument();
var nodes;
if (resultType) {
nodes = selblocks.xp.selectNodes(doc, xpath, contextNode, resultType); // mozilla engine only
}
else {
nodes = selblocks.xp.selectElements(doc, xpath, contextNode);
}
return nodes;
}
// selbocks name-space
(function($$){
// =============== Javascript extensions as script helpers ===============
// EXTENSION REVIEWERS:
// Global functions are intentional features provided for use by end user's in their Selenium scripts.
// eg: "dilbert".isOneOf("dilbert","dogbert","mordac") => true
String.prototype.isOneOf = function(valuesObj)
{
var values = valuesObj;
if (!(values instanceof Array)) {
// copy function arguments into an array
values = Array.prototype.slice.call(arguments);
}
var i;
for (i = 0; i < this.length; i++) {
if (values[i] == this) {
return true;
}
}
return false;
};
// eg: "red".mapTo("primary", ["red","green","blue"]) => primary
String.prototype.mapTo = function(/* pairs of: string, array */)
{
var errMsg = " The map function requires pairs of argument: string, array";
assert(arguments.length % 2 === 0, errMsg + "; found " + arguments.length);
var i;
for (i = 0; i < arguments.length; i += 2) {
assert((typeof arguments[i].toLowerCase() === "string") && (arguments[i+1] instanceof Array),
errMsg + "; found " + typeof arguments[i] + ", " + typeof arguments[i+1]);
if (this.isOneOf(arguments[i+1])) {
return arguments[i];
}
}
return this;
};
// Return a translated version of a string
// given string args, translate each occurrence of characters in t1 with the corresponding character from t2
// given array args, if the string occurs in t1, return the corresponding string from t2, else null
String.prototype.translate = function(t1, t2)
{
assert(t1.constructor === t2.constructor, "translate() function requires arrays of the same type");
assert(t1.length === t2.length, "translate() function requires arrays of equal size");
var i;
if (t1.constructor === String) {
var buf = "";
for (i = 0; i < this.length; i++) {
var c = this.substr(i,1);
var t;
for (t = 0; t < t1.length; t++) {
if (c === t1.substr(t,1)) {
c = t2.substr(t,1);
break;
}
}
buf += c;
}
return buf;
}
if (t1.constructor === Array) {
for (i = 0; i < t1.length; i++) {
if (t1[i] == this) {
return t2[i];
}
}
}
else {
assert(false, "translate() function requires arguments of type String or Array");
}
return null;
};
//=============== Call/Scope Stack handling ===============
var symbols = {}; // command indexes stored by name: function names
var blockDefs = null; // static command definitions stored by command index
var callStack = null; // command execution stack
// the idx of the currently executing command
function idxHere() {
return testCase.debugContext.debugIndex;
}
// Command structure definitions, stored by command index
function BlockDefs() {
var blkDefs = [];
// initialize blockDef at the given command index
blkDefs.init = function(i, attrs) {
blkDefs[i] = attrs || {};
blkDefs[i].idx = i;
blkDefs[i].cmdName = testCase.commands[i].command;
return blkDefs[i];
};
return blkDefs;
}
// retrieve the blockDef at the given command idx
function blkDefAt(idx) {
return blockDefs[idx];
}
// retrieve the blockDef for the currently executing command
function blkDefHere() {
return blkDefAt(idxHere());
}
// retrieve the blockDef for the given blockDef frame
function blkDefFor(stackFrame) {
if (!stackFrame) {
return null;
}
return blkDefAt(stackFrame.idx);
}
// An Array object with stack functionality
function Stack() {
var stack = [];
stack.isEmpty = function() { return stack.length === 0; };
stack.top = function() { return stack[stack.length-1]; };
stack.findEnclosing = function(_hasCriteria) { return stack[stack.indexWhere(_hasCriteria)]; };
stack.indexWhere = function(_hasCriteria) { // undefined if not found
var i;
for (i = stack.length-1; i >= 0; i--) {
if (_hasCriteria(stack[i])) {
return i;
}
}
};
stack.unwindTo = function(_hasCriteria) {
if (stack.length === 0) {
return null;
}
while (!_hasCriteria(stack.top())) {
stack.pop();
}
return stack.top();
};
stack.isHere = function() {
return (stack.length > 0 && stack.top().idx === idxHere());
};
return stack;
}
// Determine if the given stack frame is one of the given block kinds
Stack.isTryBlock = function(stackFrame) { return (blkDefFor(stackFrame).nature === "try"); };
Stack.isLoopBlock = function(stackFrame) { return (blkDefFor(stackFrame).nature === "loop"); };
Stack.isFunctionBlock = function(stackFrame) { return (blkDefFor(stackFrame).nature === "function"); };
// Flow control - we don't just alter debugIndex on the fly, because the command
// preceding the destination would falsely get marked as successfully executed
var branchIdx = null;
// if testCase.nextCommand() ever changes, this will need to be revisited
// (current as of: selenium-ide-2.8.0)
function nextCommand() {
if (!this.started) {
this.started = true;
this.debugIndex = testCase.startPoint ? testCase.commands.indexOf(testCase.startPoint) : 0;
}
else {
if (branchIdx !== null) {
$$.LOG.info("branch => " + fmtCmdRef(branchIdx));
this.debugIndex = branchIdx;
branchIdx = null;
}
else {
this.debugIndex++;
}
}
// skip over comments, if any
while (this.debugIndex < testCase.commands.length)
{
if ($$.seleniumEnv == "server") {
// increment nextCommandRowIndex, which is the IDE equivalent of debugIndex
// (see pseudo properties in user-extensions-base.js)
// TBD: find a server equivalent of the IDE commands array
this._advanceToNextRow();
if (this.currentRow == null) {
return null; // no more commands
}
}
var command = testCase.commands[this.debugIndex];
if (command.type === "command") {
this.runTimeStamp = Date.now();
return command;
}
this.debugIndex++;
}
return null;
}
// Set index of the next command to execute via nextCommand().
function setNextCommand(cmdIdx) {
assert(cmdIdx >= 0 && cmdIdx < testCase.commands.length,
" Cannot branch to non-existent command @" + (cmdIdx+1));
branchIdx = cmdIdx;
}
// Selenium calls reset():
// * before each single (double-click) command execution
// * before a testcase is run
// * before each testcase runs in a running testsuite
// TBD: skip during single command execution
$$.fn.interceptAfter(Selenium.prototype, "reset", function()
{
$$.LOG.trace("In tail intercept :: Selenium.reset()");
$$.seleniumTestRunner = ($$.seleniumEnv == "server")
? htmlTestRunner // Selenium Server
: editor.selDebugger.runner; // Selenium IDE
try {
compileSelBlocks();
}
catch (err) {
notifyFatalErr("In " + err.fileName + " @" + err.lineNumber + ": " + err);
}
callStack = new Stack();
callStack.push({ blockStack: new Stack() }); // top-level execution state
$$.tcf = { nestingLevel: -1 }; // try/catch/finally nesting
// customize flow control logic
// TBD: this should be a tail intercept rather than brute force replace
$$.LOG.debug("Configuring tail intercept: testCase.debugContext.nextCommand()");
$$.fn.interceptReplace(testCase.debugContext, "nextCommand", nextCommand);
});
// get the blockStack for the currently active callStack
function activeBlockStack() {
return callStack.top().blockStack;
}
// ================================================================================
// Assemble block relationships and symbol locations
function compileSelBlocks()
{
blockDefs = new BlockDefs();
var lexStack = new Stack();
var i;
for (i = 0; i < testCase.commands.length; i++)
{
if (testCase.commands[i].type === "command")
{
var curCmd = testCase.commands[i].command;
var aw = curCmd.indexOf("AndWait");
if (aw !== -1) {
// just ignore the suffix for now, this may or may not be a SelBlocks command
curCmd = curCmd.substring(0, aw);
}
var cmdTarget = testCase.commands[i].target;
var ifDef;
var tryDef;
var expectedCmd;
switch(curCmd)
{
case "label":
assertNotAndWaitSuffix(i);
symbols[cmdTarget] = i;
break;
case "goto": case "gotoIf": case "skipNext":
assertNotAndWaitSuffix(i);
break;
case "if":
assertNotAndWaitSuffix(i);
lexStack.push(blockDefs.init(i, { nature: "if", elseIfIdxs: [] }));
break;
case "elseIf":
assertNotAndWaitSuffix(i);
assertBlockIsPending("elseIf", i, ", is not valid outside of an if/endIf block");
ifDef = lexStack.top();
assertMatching(ifDef.cmdName, "if", i, ifDef.idx);
var eIdx = blkDefFor(ifDef).elseIdx;
if (eIdx) {
notifyFatal(fmtCmdRef(eIdx) + " An else has to come after all elseIfs.");
}
blockDefs.init(i, { ifIdx: ifDef.idx }); // elseIf -> if
blkDefFor(ifDef).elseIfIdxs.push(i); // if -> elseIf(s)
break;
case "else":
assertNotAndWaitSuffix(i);
assertBlockIsPending("if", i, ", is not valid outside of an if/endIf block");
ifDef = lexStack.top();
assertMatching(ifDef.cmdName, "if", i, ifDef.idx);
if (blkDefFor(ifDef).elseIdx) {
notifyFatal(fmtCmdRef(i) + " There can only be one else associated with a given if.");
}
blockDefs.init(i, { ifIdx: ifDef.idx }); // else -> if
blkDefFor(ifDef).elseIdx = i; // if -> else
break;
case "endIf":
assertNotAndWaitSuffix(i);
assertBlockIsPending("if", i);
ifDef = lexStack.pop();
assertMatching(ifDef.cmdName, "if", i, ifDef.idx);
blockDefs.init(i, { ifIdx: ifDef.idx }); // endIf -> if
blkDefFor(ifDef).endIdx = i; // if -> endif
if (ifDef.elseIdx) {
blkDefAt(ifDef.elseIdx).endIdx = i; // else -> endif
}
break;
case "try":
assertNotAndWaitSuffix(i);
lexStack.push(blockDefs.init(i, { nature: "try", name: cmdTarget }));
break;
case "catch":
assertNotAndWaitSuffix(i);
assertBlockIsPending("try", i, ", is not valid without a try block");
tryDef = lexStack.top();
assertMatching(tryDef.cmdName, "try", i, tryDef.idx);
if (blkDefFor(tryDef).catchIdx) {
notifyFatal(fmtCmdRef(i) + " There can only be one catch-block associated with a given try.");
}
var fIdx = blkDefFor(tryDef).finallyIdx;
if (fIdx) {
notifyFatal(fmtCmdRef(fIdx) + " A finally-block has to be last in a try section.");
}
blockDefs.init(i, { tryIdx: tryDef.idx }); // catch -> try
blkDefFor(tryDef).catchIdx = i; // try -> catch
break;
case "finally":
assertNotAndWaitSuffix(i);
assertBlockIsPending("try", i);
tryDef = lexStack.top();
assertMatching(tryDef.cmdName, "try", i, tryDef.idx);
if (blkDefFor(tryDef).finallyIdx) {
notifyFatal(fmtCmdRef(i) + " There can only be one finally-block associated with a given try.");
}
blockDefs.init(i, { tryIdx: tryDef.idx }); // finally -> try
blkDefFor(tryDef).finallyIdx = i; // try -> finally
if (tryDef.catchIdx) {
blkDefAt(tryDef.catchIdx).finallyIdx = i; // catch -> finally
}
break;
case "endTry":
assertNotAndWaitSuffix(i);
assertBlockIsPending("try", i);
tryDef = lexStack.pop();
assertMatching(tryDef.cmdName, "try", i, tryDef.idx);
if (cmdTarget) {
assertMatching(tryDef.name, cmdTarget, i, tryDef.idx); // pair-up on try-name
}
blockDefs.init(i, { tryIdx: tryDef.idx }); // endTry -> try
blkDefFor(tryDef).endIdx = i; // try -> endTry
if (tryDef.catchIdx) {
blkDefAt(tryDef.catchIdx).endIdx = i; // catch -> endTry
}
break;
case "while": case "for": case "foreach": case "forJson": case "forXml":
assertNotAndWaitSuffix(i);
lexStack.push(blockDefs.init(i, { nature: "loop" }));
break;
case "continue": case "break":
assertNotAndWaitSuffix(i);
assertCmd(i, lexStack.findEnclosing(Stack.isLoopBlock), ", is not valid outside of a loop");
blockDefs.init(i, { beginIdx: lexStack.top().idx }); // -> begin
break;
case "endWhile": case "endFor": case "endForeach": case "endForJson": case "endForXml":
assertNotAndWaitSuffix(i);
expectedCmd = curCmd.substr(3).toLowerCase();
assertBlockIsPending(expectedCmd, i);
var beginDef = lexStack.pop();
assertMatching(beginDef.cmdName.toLowerCase(), expectedCmd, i, beginDef.idx);
blkDefFor(beginDef).endIdx = i; // begin -> end
blockDefs.init(i, { beginIdx: beginDef.idx }); // end -> begin
break;
case "loadJsonVars": case "loadXmlVars":
assertNotAndWaitSuffix(i);
break;
case "call":
assertNotAndWaitSuffix(i);
blockDefs.init(i);
break;
case "function": case "script":
assertNotAndWaitSuffix(i);
symbols[cmdTarget] = i;
lexStack.push(blockDefs.init(i, { nature: "function", name: cmdTarget }));
break;
case "return":
assertNotAndWaitSuffix(i);
assertBlockIsPending("function", i, ", is not valid outside of a function/endFunction block");
var funcCmd = lexStack.findEnclosing(Stack.isFunctionBlock);
blockDefs.init(i, { funcIdx: funcCmd.idx }); // return -> function
break;
case "endFunction": case "endScript":
assertNotAndWaitSuffix(i);
expectedCmd = curCmd.substr(3).toLowerCase();
assertBlockIsPending(expectedCmd, i);
var funcDef = lexStack.pop();
assertMatching(funcDef.cmdName.toLowerCase(), expectedCmd, i, funcDef.idx);
if (cmdTarget) {
assertMatching(funcDef.name, cmdTarget, i, funcDef.idx); // pair-up on function name
}
blkDefFor(funcDef).endIdx = i; // function -> endFunction
blockDefs.init(i, { funcIdx: funcDef.idx }); // endFunction -> function
break;
case "exitTest":
assertNotAndWaitSuffix(i);
break;
default:
}
}
}
if (!lexStack.isEmpty()) {
// unterminated block(s)
var cmdErrors = [];
while (!lexStack.isEmpty()) {
var pend = lexStack.pop();
cmdErrors.unshift(fmtCmdRef(pend.idx) + " without a terminating "
+ "'end" + pend.cmdName.substr(0, 1).toUpperCase() + pend.cmdName.substr(1) + "'"
);
}
throw new SyntaxError(cmdErrors.join("; "));
}
//- command validation
function assertNotAndWaitSuffix(cmdIdx) {
assertCmd(cmdIdx, (testCase.commands[cmdIdx].command.indexOf("AndWait") === -1),
", AndWait suffix is not valid for SelBlocks commands");
}
//- active block validation
function assertBlockIsPending(expectedCmd, cmdIdx, desc) {
assertCmd(cmdIdx, !lexStack.isEmpty(), desc || ", without an beginning [" + expectedCmd + "]");
}
//- command-pairing validation
function assertMatching(curCmd, expectedCmd, cmdIdx, pendIdx) {
assertCmd(cmdIdx, curCmd === expectedCmd, ", does not match command " + fmtCmdRef(pendIdx));
}
}
// --------------------------------------------------------------------------------
// prevent jumping in-to and/or out-of loop/function/try blocks
function assertIntraBlockJumpRestriction(fromIdx, toIdx) {
var fromRange = findBlockRange(fromIdx);
var toRange = findBlockRange(toIdx);
if (fromRange || toRange) {
var msg = " Attempt to jump";
if (fromRange) { msg += " out of " + fromRange.desc + fromRange.fmt(); }
if (toRange) { msg += " into " + toRange.desc + toRange.fmt(); }
assert(fromRange && fromRange.equals(toRange), msg
+ ". You cannot jump into, or out of: loops, functions, or try blocks.");
}
}
// ascertain in which, if any, block that an locusIdx occurs
function findBlockRange(locusIdx) {
var idx;
for (idx = locusIdx-1; idx >= 0; idx--) {
var blk = blkDefAt(idx);
if (blk) {
if (locusIdx > blk.endIdx) { // ignore blocks that are inside this same block
continue;
}
switch (blk.nature) {
case "loop": return new CmdRange(blk.idx, blk.endIdx, blk.cmdName + " loop");
case "function": return new CmdRange(blk.idx, blk.endIdx, "function '" + blk.name + "'");
case "try": return isolateTcfRange(locusIdx, blk);
}
}
}
// return as undefined (no enclosing block at all)
}
// pin-point in which sub-block, (try, catch or finally), that the idx occurs
function isolateTcfRange(idx, tryDef) {
// assumptions: idx is known to be between try & endTry, and catch always precedes finally
var RANGES = [
{ ifr: tryDef.finallyIdx, ito: tryDef.endIdx, desc: "finally", desc2: "end" }
,{ ifr: tryDef.catchIdx, ito: tryDef.finallyIdx, desc: "catch", desc2: "finally" }
,{ ifr: tryDef.catchIdx, ito: tryDef.endIdx, desc: "catch", desc2: "end" }
,{ ifr: tryDef.idx, ito: tryDef.catchIdx, desc: "try", desc2: "catch" }
,{ ifr: tryDef.idx, ito: tryDef.finallyIdx, desc: "try", desc2: "finally" }
,{ ifr: tryDef.idx, ito: tryDef.endIdx, desc: "try", desc2: "end" }
];
var i;
for (i = 0; i < RANGES.length; i++) {
var rng = RANGES[i];
if (rng.ifr <= idx && idx < rng.ito) {
var desc = rng.desc + "-block";
if (rng.desc !== "try") { desc += " for"; }
if (tryDef.name) { desc += " '" + tryDef.name + "'"; }
return new CmdRange(rng.ifr, rng.ito, desc);
}
}
}
// represents a range of script lines
function CmdRange(topIdx, bottomIdx, desc) {
this.topIdx = topIdx;
this.bottomIdx = bottomIdx;
this.desc = desc;
this.equals = function(cmdRange) {
return (cmdRange && cmdRange.topIdx === this.topIdx && cmdRange.bottomIdx === this.bottomIdx);
};
this.fmt = function() {
return " @[" + (this.topIdx+1) + "-" + (this.bottomIdx+1) + "]";
};
}
// ==================== SelBlocks Commands (Custom Selenium Actions) ====================
var iexpr = Object.create($$.InfixExpressionParser);
// validate variable/parameter names
function validateNames(names, desc) {
var i;
for (i = 0; i < names.length; i++) {
validateName(names[i], desc);
}
}
function validateName(name, desc) {
var match = name.match(/^[a-zA-Z]\w*$/);
if (!match) {
notifyFatal("Invalid character(s) in " + desc + " name: '" + name + "'");
}
}
Selenium.prototype.doLabel = function() {
// noop
};
// Skip the next N commands (default is 1)
Selenium.prototype.doSkipNext = function(spec)
{
assertRunning();
var n = parseInt($$.evalWithVars(spec), 10);
if (isNaN(n)) {
if (spec.trim() === "") { n = 1; }
else { notifyFatalHere(" Requires a numeric value"); }
}
else if (n < 0) {
notifyFatalHere(" Requires a number > 1");
}
if (n !== 0) { // if n=0, execute the next command as usual
destIdx = idxHere() + n + 1;
assertIntraBlockJumpRestriction(idxHere(), destIdx);
setNextCommand(destIdx);
}
};
Selenium.prototype.doGoto = function(label)
{
assertRunning();
assert(symbols[label]!==undefined, " Target label '" + label + "' is not found.");
assertIntraBlockJumpRestriction(idxHere(), symbols[label]);
setNextCommand(symbols[label]);
};
Selenium.prototype.doGotoIf = function(condExpr, label)
{
assertRunning();
if ($$.evalWithVars(condExpr)) {
this.doGoto(label);
}
};
// ================================================================================
Selenium.prototype.doIf = function(condExpr, locator)
{
assertRunning();
var ifDef = blkDefHere();
var ifState = { idx: idxHere(), elseIfItr: arrayIterator(ifDef.elseIfIdxs) };
activeBlockStack().push(ifState);
cascadeElseIf(ifState, condExpr);
};
Selenium.prototype.doElseIf = function(condExpr)
{
assertRunning();
assertActiveScope(blkDefHere().ifIdx);
var ifState = activeBlockStack().top();
if (ifState.skipElseBlocks) { // if, or previous elseIf, has already been met