forked from flyingfisher/selenium-html-js-converter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
JavascriptFormatter.js
1452 lines (1448 loc) · 55.5 KB
/
JavascriptFormatter.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
/// <reference path="typings/node.d.ts" />
"use strict";
var Command = require("./testCase").Command;
var Comment = require("./testCase").Comment;
var jsbute = require('js-beautify').js_beautify;
var fs = require('fs');
var log = console;
log.debug = log.info;
var app = {};
var options = {};
/**
* Format TestCase and return the source.
*
* @param {string} testCase TestCase to format
* @param {object} opts Custom options
* {string} .testCaseName
* The name of the test case. It will be used to embed
* title into the source, and write screenshot files.
* Default: 'Untitled'
* {number} .timeout
* Default number of msecs before timing out in test
* cases with timeouts, and when creating auto-retrying
* test cases.
* Default: 30,000
* {number} .retries
* How many times to retry test cases when they fail.
* If retries are enabled, each generated test case
* will be wrapped in a retry function.
* Default: 0 (disabled)
* {string} .extensions
* User extensions javascript file:
* Default: __dirname + 'extensions/user-extensions.js'
*
* @return {string} The formatted test case.
*/
function format(testCase, opts) {
if (!opts || typeof opts !== 'object')
opts = {};
log.info("Formatting testCase: " + opts.testCaseName);
var result = '';
var header = "";
var footer = "";
var extension, extensions = opts.extensions || __dirname + '/extensions/user-extensions.js';
app.commandCharIndex = 0;
app.testCaseName = opts.testCaseName || '';
app.screenshotsCount = 0;
options.testCaseName = opts.testCaseName || 'Untitled';
options.timeout = typeof opts.timeout === 'number' && !isNaN(opts.timeout) ? opts.timeout : 30000;
options.retries = typeof opts.retries === 'number' && !isNaN(opts.retries) ? opts.retries : 0;
options.screenshotFolder = 'screenshots/' + app.testCaseName;
options.baseUrl = opts.baseUrl || '${baseURL}';
options.extensions = {};
log.info('Importing user extensions from %s ...', extensions);
extensions = require(extensions);
for (extension in extensions) {
if (extensions.hasOwnProperty(extension)) {
log.info('Adding command %s', extension);
options.extensions[extension] = extensions[extension];
}
}
header = formatHeader(testCase);
result += header;
app.commandCharIndex = header.length;
testCase.formatLocal(app.name).header = header;
result += formatCommands(testCase.commands);
footer = formatFooter(testCase);
footer += '\n\n/* User extensions */\n\n';
for (extension in options.extensions) {
footer += options.extensions[extension].toString().replace(/^function/, 'function ' + extension) + '\n\n';
}
result += footer;
testCase.formatLocal(app.name).footer = footer;
return jsbute(result, opts.jsBeautifierOptions || { max_preserve_newlines: 2 });
}
exports.format = format;
function setLogger(logger) {
log = logger;
}
exports.setLogger = setLogger;
/**
* Generates a variable name for storing temporary values in generated scripts.
*/
function getTempVarName() {
if (!app.tmpVarsCount)
app.tmpVarsCount = 1;
return "var" + app.tmpVarsCount++;
}
function retryWrap(code) {
var wrapped = "withRetry(function () {\n";
code.split('\n').forEach(function (line) {
wrapped += line + '\n';
});
wrapped += "});";
return wrapped;
}
function andWait(code) {
var wrapped = "doAndWait(function () {\n";
code.split('\n').forEach(function (line) {
wrapped += line + '\n';
});
wrapped += "});";
return wrapped;
}
function filterForRemoteControl(commands) {
return app.postFilter ? app.postFilter(commands) : commands;
}
function formatCommands(commands) {
commands = filterForRemoteControl(commands);
var result = '';
var line = null;
var command;
var commandName;
var hasAndWaitSuffix;
for (var i = 0; i < commands.length; i++) {
command = commands[i];
app.currentlyParsingCommand = command;
if (command.type == 'line') {
line = command.line;
}
else if (command.type == 'command') {
commandName = command.command;
hasAndWaitSuffix = !!commandName.match(/AndWait$/);
if (hasAndWaitSuffix) {
command.command = commandName.replace(/AndWait$/, '');
}
line = formatCommand(command);
/* If retries are enabled, wrap the code block in a retry wrapper, unless the command is of the waiting type */
if (options.retries && !commandName.match(/(^waitFor)|(AndWait$)/)) {
line = retryWrap(line);
}
else if (hasAndWaitSuffix) {
line = andWait(line);
}
/* For debugging test failures and for screenshotting, we use currentCommand to keep track of what last ran: */
line = 'currentCommand = \'#' + (i + 1) + ': ' + commandName + '(' + '"' + command.target.replace(/(['\\])/g, "\\$1") + '", ' + '"' + command.value.replace(/(['\\])/g, "\\$1") + '")\';\n' + line + '\n';
command.line = line;
}
else if (command.type == 'comment') {
line = formatComment(command);
command.line = line;
}
command.charIndex = app.commandCharIndex;
if (line != null) {
line = line + "\n";
result += line;
app.commandCharIndex += line.length;
}
app.previouslyParsedCommand = command;
}
return result;
}
/* @override
* This function filters the command list and strips away the commands we no longer need
* or changes the command to another one.
* NOTE: do not change the existing command directly or it will also change in the test case.
*/
app.postFilter = function (originalCommands) {
var commands = [];
var commandsToSkip = {};
var rc;
for (var i = 0; i < originalCommands.length; i++) {
var c = originalCommands[i];
if (c.type == 'command') {
if (commandsToSkip[c.command] && commandsToSkip[c.command] == 1) {
}
else if (rc = SeleneseMapper.remap(c)) {
//Remap
commands.push.apply(commands, rc);
}
else {
commands.push(c);
}
}
else {
commands.push(c);
}
}
return commands;
};
/* SeleneseMapper changes one Selenese command to another that is more suitable for WebDriver export
*/
var SeleneseMapper = function () {
};
SeleneseMapper.remap = function (cmd) {
/*
for (var mapper in SeleneseMapper) {
if (SeleneseMapper.hasOwnProperty(mapper) && typeof SeleneseMapper.mapper.isDefined === 'function' && typeof SeleneseMapper.mapper.convert === 'function') {
if (SeleneseMapper.mapper.isDefined(cmd)) {
return SeleneseMapper.mapper.convert(cmd);
}
}
}
*/
// NOTE The above code is useful if there are more than one mappers, since there is just one, it is more efficient to call it directly
if (SeleneseMapper.IsTextPresent.isDefined(cmd)) {
return SeleneseMapper.IsTextPresent.convert(cmd);
}
return null;
};
SeleneseMapper.IsTextPresent = {
isTextPresentRegex: /^(assert|verify|waitFor)Text(Not)?Present$/,
isPatternRegex: /^(regexp|regexpi|regex):/,
exactRegex: /^exact:/,
isDefined: function (cmd) {
return this.isTextPresentRegex.test(cmd.command);
},
convert: function (cmd) {
if (this.isTextPresentRegex.test(cmd.command)) {
var pattern = cmd.target;
if (!this.isPatternRegex.test(pattern)) {
if (this.exactRegex.test(pattern)) {
//TODO how to escape wildcards in an glob pattern?
pattern = pattern.replace(this.exactRegex, 'glob:*') + '*';
}
else {
//glob
pattern = pattern.replace(/^(glob:)?\*?/, 'glob:*');
if (!/\*$/.test(pattern)) {
pattern += '*';
}
}
}
var remappedCmd = new Command(cmd.command.replace(this.isTextPresentRegex, "$1$2Text"), 'css=BODY', pattern);
remappedCmd.remapped = cmd;
return [new Comment('Warning: ' + cmd.command + ' may require manual changes'), remappedCmd];
}
}
};
function formatHeader(testCase) {
var className = testCase.getTitle();
if (!className) {
className = "NewTest";
}
className = testClassName(className);
var formatLocal = testCase.formatLocal(app.name);
var methodName = testMethodName(className.replace(/Test$/i, "").replace(/^Test/i, "").replace(/^[A-Z]/, function (str) {
return str.toLowerCase();
}));
var header = (options.getHeader()).
replace(/\$\{className\}/g, className).
replace(/\$\{methodName\}/g, methodName).
replace(/\$\{baseURL\}/g, testCase.getBaseURL()).
replace(/\$\{([a-zA-Z0-9_]+)\}/g, function (str, name) {
return options[name];
});
formatLocal.header = header;
return formatLocal.header;
}
function formatFooter(testCase) {
var formatLocal = testCase.formatLocal(app.name);
formatLocal.footer = options.footer;
return formatLocal.footer;
}
function capitalize(string) {
return string.replace(/^[a-z]/, function (str) {
return str.toUpperCase();
});
}
function underscore(text) {
return text.replace(/[A-Z]/g, function (str) {
return '_' + str.toLowerCase();
});
}
function notOperator() {
return "!";
}
function logicalAnd(conditions) {
return conditions.join(" && ");
}
function equals(e1, e2) {
return new Equals(e1, e2);
}
function Equals(e1, e2) {
this.e1 = e1;
this.e2 = e2;
}
Equals.prototype.invert = function () {
return new NotEquals(this.e1, this.e2);
};
function NotEquals(e1, e2) {
this.e1 = e1;
this.e2 = e2;
this.negative = true;
}
NotEquals.prototype.invert = function () {
return new Equals(this.e1, this.e2);
};
function RegexpMatch(pattern, expression) {
this.pattern = pattern;
this.expression = expression;
}
RegexpMatch.prototype.invert = function () {
return new RegexpNotMatch(this.pattern, this.expression);
};
RegexpMatch.prototype.assert = function () {
return assertTrue(this.toString());
};
RegexpMatch.prototype.verify = function () {
return verifyTrue(this.toString());
};
function RegexpNotMatch(pattern, expression) {
this.pattern = pattern;
this.expression = expression;
this.negative = true;
}
RegexpNotMatch.prototype.invert = function () {
return new RegexpMatch(this.pattern, this.expression);
};
RegexpNotMatch.prototype.toString = function () {
return notOperator() + RegexpMatch.prototype.toString.call(this);
};
RegexpNotMatch.prototype.assert = function () {
return assertFalse(this.invert());
};
RegexpNotMatch.prototype.verify = function () {
return verifyFalse(this.invert());
};
function seleniumEquals(type, pattern, expression) {
if (type == 'String[]') {
return seleniumEquals('String', pattern.replace(/\\,/g, ','), joinExpression(expression));
}
else if (type == 'String' && pattern.match(/^regexp:/)) {
return new RegexpMatch(pattern.substring(7), expression);
}
else if (type == 'String' && pattern.match(/^regex:/)) {
return new RegexpMatch(pattern.substring(6), expression);
}
else if (type == 'String' && (pattern.match(/^glob:/) || pattern.match(/[\*\?]/))) {
pattern = pattern.replace(/^glob:/, '');
pattern = pattern.replace(/([\]\[\\\{\}\$\(\).])/g, "\\$1");
pattern = pattern.replace(/\?/g, "[\\s\\S]");
pattern = pattern.replace(/\*/g, "[\\s\\S]*");
return new RegexpMatch("^" + pattern + "$", expression);
}
else {
pattern = pattern.replace(/^exact:/, '');
return new Equals(xlateValue(type, pattern), expression);
}
}
function concatString(array) {
return array.filter(function (e) { return e; }).join(" + ");
}
function toArgumentList(array) {
return array.join(", ");
}
// function keyVariable(key) {
// return variableName(key);
// }
app.sendKeysMaping = {};
function xlateKeyVariable(variable) {
var r;
if ((r = /^KEY_(.+)$/.exec(variable))) {
var key = app.sendKeysMaping[r[1]];
if (key) {
return keyVariable(key);
}
}
return null;
}
function xlateArgument(value, type) {
value = value.replace(/^\s+/, '');
value = value.replace(/\s+$/, '');
var r;
var r2;
var parts = [];
if ((r = /^javascript\{([\d\D]*)\}$/.exec(value))) {
var js = r[1];
var prefix = "";
while ((r2 = /storedVars\[['"](.*?)['"]\]/.exec(js))) {
parts.push(string(prefix + js.substring(0, r2.index) + "'"));
parts.push(variableName(r2[1]));
js = js.substring(r2.index + r2[0].length);
prefix = "'";
}
parts.push(string(prefix + js));
return new CallSelenium("getEval", [concatString(parts)]);
}
else if ((r = /\$\{/.exec(value))) {
var regexp = /\$\{(.*?)\}/g;
var lastIndex = 0;
while (r2 = regexp.exec(value)) {
var key = xlateKeyVariable(r2[1]);
if (key || (app.declaredVars && app.declaredVars[r2[1]])) {
if (r2.index - lastIndex > 0) {
parts.push(string(value.substring(lastIndex, r2.index)));
}
parts.push(key ? key : variableName(r2[1]));
lastIndex = regexp.lastIndex;
}
else if (r2[1] == "nbsp") {
if (r2.index - lastIndex > 0) {
parts.push(string(value.substring(lastIndex, r2.index)));
}
parts.push(nonBreakingSpace());
lastIndex = regexp.lastIndex;
}
}
if (lastIndex < value.length) {
parts.push(string(value.substring(lastIndex, value.length)));
}
return (type && type.toLowerCase() == 'args') ? toArgumentList(parts) : concatString(parts);
}
else if (type && type.toLowerCase() == 'number') {
return value;
}
else {
return string(value);
}
}
function xlateArrayElement(value) {
return value.replace(/\\(.)/g, "$1");
}
function xlateValue(type, value) {
if (type == 'String[]') {
return array(parseArray(value));
}
else {
return xlateArgument(value, type);
}
}
function parseArray(value) {
var start = 0;
var list = [];
for (var i = 0; i < value.length; i++) {
if (value.charAt(i) == ',') {
list.push(xlateArrayElement(value.substring(start, i)));
start = i + 1;
}
else if (value.charAt(i) == '\\') {
i++;
}
}
list.push(xlateArrayElement(value.substring(start, value.length)));
return list;
}
function addDeclaredVar(variable) {
if (app.declaredVars == null) {
app.declaredVars = {};
}
app.declaredVars[variable] = true;
}
function newVariable(prefix, index) {
if (index == null)
index = 1;
if (app.declaredVars && app.declaredVars[prefix + index]) {
return newVariable(prefix, index + 1);
}
else {
addDeclaredVar(prefix + index);
return prefix + index;
}
}
function variableName(value) {
return value;
}
function string(value) {
if (value != null) {
//value = value.replace(/^\s+/, '');
//value = value.replace(/\s+$/, '');
value = value.replace(/\\/g, '\\\\');
value = value.replace(/\"/g, '\\"');
value = value.replace(/\r/g, '\\r');
value = value.replace(/\n/g, '\\n');
// Detect URL strings, and wrap them in addBaseUrl() calls:
return value.match(/^http(s)?:\/\//) ? 'addBaseUrl("' + value + '")' : '"' + value + '"';
}
else {
return '""';
}
}
var CallSelenium = function (message, args, rawArgs) {
this.message = message;
if (args) {
this.args = args;
}
else {
this.args = [];
}
if (rawArgs) {
this.rawArgs = rawArgs;
}
else {
this.rawArgs = [];
}
};
CallSelenium.prototype.invert = function () {
var call = new CallSelenium(this.message);
call.args = this.args;
call.rawArgs = this.rawArgs;
call.negative = !this.negative;
return call;
};
CallSelenium.prototype.toString = function () {
log.info('Processing ' + this.message);
var result = '';
var adaptor = new SeleniumWebDriverAdaptor(this.rawArgs);
if (this.message.match(/^(getEval|runScript)/))
adaptor.rawArgs = this.args; // getEval only args available (Daniel: I assume this means we always want escaped stringified args here; that is, the code as converted to a string, for use with browser.safeEval(<code string>), and getEval may be used elsewhere, so we still want to have that pass forth unescaped rawArgs by default...?)
if (adaptor[this.message]) {
var codeBlock = adaptor[this.message].call(adaptor);
if (adaptor.negative) {
this.negative = !this.negative;
}
if (this.negative) {
result += notOperator();
}
result += codeBlock;
}
else {
//unsupported
throw 'ERROR: Unsupported command [' + this.message + ' | ' + (this.rawArgs.length > 0 && this.rawArgs[0] ? this.rawArgs[0] : '') + ' | ' + (this.rawArgs.length > 1 && this.rawArgs[1] ? this.rawArgs[1] : '') + ']';
}
return result;
};
function formatCommand(command) {
var line = null;
try {
var call;
var i;
var eq;
var method;
if (command.type == 'command') {
/* Definitions are extracted from the iedoc-core.xml doc */
var def = command.getDefinition();
if (def && def.isAccessor) {
call = new CallSelenium(def.name);
for (i = 0; i < def.params.length; i++) {
call.rawArgs.push(command.getParameterAt(i));
call.args.push(xlateArgument(command.getParameterAt(i)));
}
var extraArg = command.getParameterAt(def.params.length);
if (def.name.match(/^is/)) {
if (command.command.match(/^assert/) ||
(app.assertOrVerifyFailureOnNext && command.command.match(/^verify/))) {
line = (def.negative ? assertFalse : assertTrue)(call);
}
else if (command.command.match(/^verify/)) {
line = (def.negative ? verifyFalse : verifyTrue)(call);
}
else if (command.command.match(/^store/)) {
addDeclaredVar(extraArg);
line = statement(assignToVariable('boolean', extraArg, call));
}
else if (command.command.match(/^waitFor/)) {
line = waitFor(def.negative ? call.invert() : call);
}
}
else {
if (command.command.match(/^(verify|assert)/)) {
eq = seleniumEquals(def.returnType, extraArg, call);
if (def.negative)
eq = eq.invert();
method = (!app.assertOrVerifyFailureOnNext && command.command.match(/^verify/)) ? 'verify' : 'assert';
line = eq[method]();
}
else if (command.command.match(/^store/)) {
addDeclaredVar(extraArg);
line = statement(assignToVariable(def.returnType, extraArg, call));
}
else if (command.command.match(/^waitFor/)) {
eq = seleniumEquals(def.returnType, extraArg, call);
if (def.negative)
eq = eq.invert();
line = waitFor(eq);
}
else if (command.command.match(/^(getEval|runScript)/)) {
call = new CallSelenium(def.name, xlateArgument(command.getParameterAt(0)), command.getParameterAt(1));
line = statement(call, command);
}
}
}
else if (command.command.match(/setWindowSize|dragAndDrop/)) {
call = new CallSelenium(command.command);
call.rawArgs.push(command.getParameterAt(0));
call.rawArgs.push(command.getParameterAt(1));
line = statement(call, command);
}
else if ('pause' == command.command) {
line = pause(command.target);
}
else if (app.echo && 'echo' == command.command) {
line = echo(command.target);
}
else if ('store' == command.command) {
addDeclaredVar(command.value);
line = statement(assignToVariable('String', command.value, xlateArgument(command.target)));
}
else if (command.command.match(/^(assert|verify)Selected$/)) {
var optionLocator = command.value;
var flavor = 'Label';
var value = optionLocator;
var r = /^(index|label|value|id)=(.*)$/.exec(optionLocator);
if (r) {
flavor = r[1].replace(/^[a-z]/, function (str) {
return str.toUpperCase();
});
value = r[2];
}
method = (!app.assertOrVerifyFailureOnNext && command.command.match(/^verify/)) ? 'verify' : 'assert';
call = new CallSelenium("getSelected" + flavor);
call.rawArgs.push(command.target);
call.args.push(xlateArgument(command.target));
eq = seleniumEquals('String', value, call);
line = statement(eq[method]());
}
else if (def) {
if (def.name.match(/^(assert|verify)(Error|Failure)OnNext$/)) {
app.assertOrVerifyFailureOnNext = true;
app.assertFailureOnNext = def.name.match(/^assert/);
app.verifyFailureOnNext = def.name.match(/^verify/);
}
else {
call = new CallSelenium(def.name);
if ("open" == def.name && options.urlSuffix && !command.target.match(/^\w+:\/\//)) {
// urlSuffix is used to translate core-based test
call.rawArgs.push(options.urlSuffix + command.target);
call.args.push(xlateArgument(options.urlSuffix + command.target));
}
else {
for (i = 0; i < def.params.length; i++) {
call.rawArgs.push(command.getParameterAt(i));
call.args.push(xlateArgument(command.getParameterAt(i)));
}
}
line = statement(call, command);
}
}
else if (options.extensions[command.command]) {
var commandName = command.command;
command.command = 'userCommand';
call = new CallSelenium(command.command);
call.rawArgs.push(command.getParameterAt(0));
call.rawArgs.push(command.getParameterAt(1));
call.rawArgs.push(commandName);
line = statement(call, command);
}
else {
log.info("Unknown command: <" + command.command + ">");
throw 'Unknown command [' + command.command + ']';
}
}
}
catch (e) {
log.error("Caught exception: [" + e + "]. Stack:\n" + e.stack);
// TODO
// var call = new CallSelenium(command.command);
// if ((command.target != null && command.target.length > 0)
// || (command.value != null && command.value.length > 0)) {
// call.rawArgs.push(command.target);
// call.args.push(string(command.target));
// if (command.value != null && command.value.length > 0) {
// call.rawArgs.push(command.value);
// call.args.push(string(command.value));
// }
// }
// line = formatComment(new Comment(statement(call)));
line = formatComment(new Comment('ERROR: Caught exception [' + e + ']'));
}
if (line && app.assertOrVerifyFailureOnNext) {
line = assertOrVerifyFailure(line, app.assertFailureOnNext);
app.assertOrVerifyFailureOnNext = false;
app.assertFailureOnNext = false;
app.verifyFailureOnNext = false;
}
//TODO: convert array to newline separated string -> if(array) return array.join"\n"
if (command.type == 'command' && options.showSelenese && options.showSelenese == 'true') {
if (command.remapped) {
line = formatComment(new Comment(command.remapped.command + ' | ' + command.remapped.target + ' | ' + command.remapped.value)) + "\n" + line;
}
else {
line = formatComment(new Comment(command.command + ' | ' + command.target + ' | ' + command.value)) + "\n" + line;
}
}
return line;
}
app.remoteControl = true;
app.playable = false;
function parse_locator(locator) {
var result = locator.match(/^([A-Za-z]+)=.+/);
if (result) {
var type = result[1].toLowerCase();
var actualLocator = locator.substring(type.length + 1);
return { type: type, string: actualLocator };
}
return { type: 'implicit', string: locator };
}
var SeleniumWebDriverAdaptor = function (rawArgs) {
this.rawArgs = rawArgs;
this.negative = false;
};
// Returns locator.type and locator.string
SeleniumWebDriverAdaptor.prototype._elementLocator = function (sel1Locator) {
var locator = parse_locator(sel1Locator);
if (sel1Locator.match(/^\/\//) || locator.type == 'xpath') {
locator.type = 'xpath';
return locator;
}
if (locator.type == 'css') {
return locator;
}
if (locator.type == 'id') {
return locator;
}
if (locator.type == 'link') {
locator.string = locator.string.replace(/^exact:/, '');
return locator;
}
if (locator.type == 'name') {
return locator;
}
if (sel1Locator.match(/^document/) || locator.type == 'dom') {
throw 'Error: Dom locators are not implemented yet!';
}
if (locator.type == 'ui') {
throw 'Error: UI locators are not supported!';
}
if (locator.type == 'identifier') {
throw 'Error: locator strategy [identifier] has been deprecated. To rectify specify the correct locator strategy id or name explicitly.';
}
if (locator.type == 'implicit') {
throw 'Error: locator strategy either id or name must be specified explicitly.';
}
throw 'Error: unknown strategy [' + locator.type + '] for locator [' + sel1Locator + ']';
};
// Returns locator.elementLocator and locator.attributeName
SeleniumWebDriverAdaptor.prototype._attributeLocator = function (sel1Locator) {
var attributePos = sel1Locator.lastIndexOf("@");
var elementLocator = sel1Locator.slice(0, attributePos);
var attributeName = sel1Locator.slice(attributePos + 1);
return { elementLocator: elementLocator, attributeName: attributeName };
};
SeleniumWebDriverAdaptor.prototype._selectLocator = function (sel1Locator) {
//Figure out which strategy to use
var locator = { type: 'label', string: sel1Locator };
// If there is a locator prefix, use the specified strategy
var result = sel1Locator.match(/^([a-zA-Z]+)=(.*)/);
if (result) {
locator.type = result[1];
locator.string = result[2];
}
//alert(locatorType + ' [' + locatorValue + ']');
if (locator.type == 'index') {
return locator;
}
if (locator.type == 'label') {
return locator;
}
if (locator.type == 'value') {
return locator;
}
throw 'Error: unknown or unsupported strategy [' + locator.type + '] for locator [' + sel1Locator + ']';
};
// Returns an object with a toString method
SeleniumWebDriverAdaptor.SimpleExpression = function (expressionString) {
this.str = expressionString;
};
SeleniumWebDriverAdaptor.SimpleExpression.prototype.toString = function () {
return this.str;
};
//helper method to simplify the ifCondition
SeleniumWebDriverAdaptor.ifCondition = function (conditionString, stmtString) {
return ifCondition(new SeleniumWebDriverAdaptor.SimpleExpression(conditionString), function () {
return statement(new SeleniumWebDriverAdaptor.SimpleExpression(stmtString)) + "\n";
});
};
SeleniumWebDriverAdaptor.prototype.check = function (elementLocator) {
var locator = this._elementLocator(this.rawArgs[0]);
var driver = new WDAPI.Driver();
var webElement = driver.findElement(locator.type, locator.string);
return SeleniumWebDriverAdaptor.ifCondition(notOperator() + webElement.isSelected(), webElement.click());
};
SeleniumWebDriverAdaptor.prototype.click = function (elementLocator) {
var locator = this._elementLocator(this.rawArgs[0]);
var driver = new WDAPI.Driver();
return driver.findElement(locator.type, locator.string).click();
};
SeleniumWebDriverAdaptor.prototype.close = function () {
var driver = new WDAPI.Driver();
return driver.close();
};
SeleniumWebDriverAdaptor.prototype.waitForPageToLoad = function () {
var driver = new WDAPI.Driver();
return driver.waitForPageToLoad();
};
SeleniumWebDriverAdaptor.prototype.openWindow = function () {
var driver = new WDAPI.Driver();
var url = this.rawArgs[0];
var name = this.rawArgs[1];
return driver.openWindow(url, name);
};
SeleniumWebDriverAdaptor.prototype.selectWindow = function () {
var driver = new WDAPI.Driver();
var name = this.rawArgs[0];
return driver.selectWindow(name);
};
SeleniumWebDriverAdaptor.prototype.userCommand = function () {
var driver = new WDAPI.Driver();
var commandName = this.rawArgs[2];
var locator, locator2;
try {
locator = this._elementLocator(this.rawArgs[0]);
locator = WDAPI.Driver.searchContext(locator.type, locator.string);
locator = 'function () { return ' + locator + '; }';
locator2 = this._elementLocator(this.rawArgs[1]);
locator2 = WDAPI.Driver.searchContext(locator2.type, locator2.string);
locator2 = 'function () { return ' + locator2 + '; }';
}
catch (ignore) { }
return driver.userCommand(commandName, this.rawArgs[0], this.rawArgs[1], locator, locator2);
};
/* wd does not support the windowFocus command. window(), called by selectWindow, both selects and focuses a window, so if the previously parsed command was selectWindow, we should be good. */
SeleniumWebDriverAdaptor.prototype.windowFocus = function () {
if (app.previouslyParsedCommand.command !== 'selectWindow') {
throw new Error('windowFocus is not supported by wd.');
}
/* Ignoring windowFocus command, as window focusing is handled implicitly in the previous wd command. */
return "";
};
/* Custom user extension: Resize browser window directly via wd's browser object. */
SeleniumWebDriverAdaptor.prototype.setWindowSize = function () {
var dimensions = this.rawArgs[0].split(/[^0-9]+/);
var driver = new WDAPI.Driver();
return driver.setWindowSize(dimensions[0], dimensions[1]);
};
SeleniumWebDriverAdaptor.prototype.deleteAllVisibleCookies = function () {
var driver = new WDAPI.Driver();
return driver.deleteAllCookies();
};
SeleniumWebDriverAdaptor.prototype.dragAndDrop = function (elementLocator, offset) {
var locator = this._elementLocator(this.rawArgs[0]);
var driver = new WDAPI.Driver();
return driver.dragAndDrop(locator, this.rawArgs[1]);
};
SeleniumWebDriverAdaptor.prototype.focus = function (elementLocator) {
var locator = this._elementLocator(this.rawArgs[0]);
var driver = new WDAPI.Driver();
return driver.focus(locator);
};
SeleniumWebDriverAdaptor.prototype.keyUp = function (elementLocator, key) {
var locator = this._elementLocator(this.rawArgs[0]);
var driver = new WDAPI.Driver();
return driver.keyEvent(locator, 'keyup', this.rawArgs[1]);
};
SeleniumWebDriverAdaptor.prototype.keyDown = function (elementLocator, key) {
var locator = this._elementLocator(this.rawArgs[0]);
var driver = new WDAPI.Driver();
return driver.keyEvent(locator, 'keydown', this.rawArgs[1]);
};
SeleniumWebDriverAdaptor.prototype.keyPress = function (elementLocator, key) {
var locator = this._elementLocator(this.rawArgs[0]);
var driver = new WDAPI.Driver();
return driver.keyEvent(locator, 'keypress', this.rawArgs[1]);
};
SeleniumWebDriverAdaptor.prototype.captureEntirePageScreenshot = function () {
var driver = new WDAPI.Driver();
var fileName = this.rawArgs[0];
return driver.captureEntirePageScreenshot(fileName);
};
SeleniumWebDriverAdaptor.prototype.getAttribute = function (attributeLocator) {
var attrLocator = this._attributeLocator(this.rawArgs[0]);
var locator = this._elementLocator(attrLocator.elementLocator);
var driver = new WDAPI.Driver();
var webElement = driver.findElement(locator.type, locator.string);
return webElement.getAttribute(attrLocator.attributeName);
};
SeleniumWebDriverAdaptor.prototype.getBodyText = function () {
var driver = new WDAPI.Driver();
return driver.findElement('tag_name', 'BODY').getText();
};
SeleniumWebDriverAdaptor.prototype.getCssCount = function (elementLocator) {
var locator = this._elementLocator(this.rawArgs[0]);
var driver = new WDAPI.Driver();
return driver.findElements(locator.type, locator.string).getSize();
};
SeleniumWebDriverAdaptor.prototype.getLocation = function () {
var driver = new WDAPI.Driver();
return driver.getCurrentUrl();
};
SeleniumWebDriverAdaptor.prototype.getText = function (elementLocator) {
var locator = this._elementLocator(this.rawArgs[0]);
var driver = new WDAPI.Driver();
return driver.findElement(locator.type, locator.string).getText();
};
SeleniumWebDriverAdaptor.prototype.getTitle = function () {
var driver = new WDAPI.Driver();
return driver.getTitle();
};
SeleniumWebDriverAdaptor.prototype.getAlert = function () {
var driver = new WDAPI.Driver();
return driver.getAlert();
};
SeleniumWebDriverAdaptor.prototype.isAlertPresent = function () {
return WDAPI.Utils.isAlertPresent();
};
SeleniumWebDriverAdaptor.prototype.getConfirmation = function () {
var driver = new WDAPI.Driver();
return driver.getAlert();
};
SeleniumWebDriverAdaptor.prototype.isConfirmationPresent = function () {
return WDAPI.Utils.isAlertPresent();
};
SeleniumWebDriverAdaptor.prototype.chooseOkOnNextConfirmation = function () {
var driver = new WDAPI.Driver();
return driver.chooseOkOnNextConfirmation();
};
SeleniumWebDriverAdaptor.prototype.chooseCancelOnNextConfirmation = function () {
var driver = new WDAPI.Driver();
return driver.chooseCancelOnNextConfirmation();
};
SeleniumWebDriverAdaptor.prototype.getValue = function (elementLocator) {
var locator = this._elementLocator(this.rawArgs[0]);
var driver = new WDAPI.Driver();
return driver.findElement(locator.type, locator.string).getAttribute('value');
};
SeleniumWebDriverAdaptor.prototype.getXpathCount = function (elementLocator) {
var locator = this._elementLocator(this.rawArgs[0]);
var driver = new WDAPI.Driver();
return driver.findElements(locator.type, locator.string).getSize();
};
SeleniumWebDriverAdaptor.prototype.goBack = function () {
var driver = new WDAPI.Driver();
return driver.back();
};
SeleniumWebDriverAdaptor.prototype.isChecked = function (elementLocator) {
var locator = this._elementLocator(this.rawArgs[0]);
var driver = new WDAPI.Driver();
return driver.findElement(locator.type, locator.string).isSelected();
};
SeleniumWebDriverAdaptor.prototype.isElementPresent = function (elementLocator) {
var locator = this._elementLocator(this.rawArgs[0]);
//var driver = new WDAPI.Driver();
//TODO: enough to just find element, but since this is an accessor, we will need to make a not null comparison
//return driver.findElement(locator.type, locator.string);
return WDAPI.Utils.isElementPresent(locator.type, locator.string);
};
SeleniumWebDriverAdaptor.prototype.isVisible = function (elementLocator) {
var locator = this._elementLocator(this.rawArgs[0]);
var driver = new WDAPI.Driver();
return driver.findElement(locator.type, locator.string).isDisplayed();
};
SeleniumWebDriverAdaptor.prototype.open = function (url) {
//TODO process the relative and absolute urls
var absUrl = xlateArgument(this.rawArgs[0]);
var driver = new WDAPI.Driver();
return driver.get(absUrl);
};
SeleniumWebDriverAdaptor.prototype.refresh = function () {
var driver = new WDAPI.Driver();
return driver.refresh();
};
SeleniumWebDriverAdaptor.prototype.submit = function (elementLocator) {
var locator = this._elementLocator(this.rawArgs[0]);
var driver = new WDAPI.Driver();
return driver.findElement(locator.type, locator.string).submit();
};
SeleniumWebDriverAdaptor.prototype.type = function (elementLocator, text) {
var locator = this._elementLocator(this.rawArgs[0]);
var driver = new WDAPI.Driver();
var webElement = driver.findElement(locator.type, locator.string);
return statement(new SeleniumWebDriverAdaptor.SimpleExpression(webElement.clear())) + "\n" + webElement.sendKeys(this.rawArgs[1]);
};
SeleniumWebDriverAdaptor.prototype.sendKeys = function (elementLocator, text) {
var locator = this._elementLocator(this.rawArgs[0]);
var driver = new WDAPI.Driver();
return driver.findElement(locator.type, locator.string).sendKeys(this.rawArgs[1]);
};
SeleniumWebDriverAdaptor.prototype.uncheck = function (elementLocator) {
var locator = this._elementLocator(this.rawArgs[0]);
var driver = new WDAPI.Driver();
var webElement = driver.findElement(locator.type, locator.string);
return SeleniumWebDriverAdaptor.ifCondition(webElement.isSelected(), webElement.click());
};
SeleniumWebDriverAdaptor.prototype.select = function (elementLocator, label) {
var locator = this._elementLocator(this.rawArgs[0]);
var driver = new WDAPI.Driver();
return driver.findElement(locator.type, locator.string).select(this._selectLocator(this.rawArgs[1]));
};
SeleniumWebDriverAdaptor.prototype.getEval = SeleniumWebDriverAdaptor.prototype.runScript = function (script) {
var driver = new WDAPI.Driver();
return driver.eval(this.rawArgs[0]);
};
var WDAPI = function () {
};
/*
* Formatter for Selenium 2 / WebDriver JavaScript client.
*/
function useSeparateEqualsForArray() {
return true;
}
function testClassName(testName) {
return testName.split(/[^0-9A-Za-z]+/).map(function (x) { return capitalize(x); }).join('');
}
function testMethodName(testName) {
return "test" + testClassName(testName);
}
function nonBreakingSpace() {
return "\"\\u00a0\"";
}
function array(value) {
return JSON.stringify(value);