Project

General

Profile

1
/*
2
* Copyright 2004 ThoughtWorks, Inc
3
*
4
*  Licensed under the Apache License, Version 2.0 (the "License");
5
*  you may not use this file except in compliance with the License.
6
*  You may obtain a copy of the License at
7
*
8
*      http://www.apache.org/licenses/LICENSE-2.0
9
*
10
*  Unless required by applicable law or agreed to in writing, software
11
*  distributed under the License is distributed on an "AS IS" BASIS,
12
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
*  See the License for the specific language governing permissions and
14
*  limitations under the License.
15
*
16
*/
17

    
18
// An object representing the current test, used external
19
var currentTest = null; // TODO: get rid of this global, which mirrors the htmlTestRunner.currentTest
20
var selenium = null;
21

    
22
var htmlTestRunner;
23
var HtmlTestRunner = classCreate();
24
objectExtend(HtmlTestRunner.prototype, {
25
    initialize: function() {
26
        this.metrics = new Metrics();
27
        this.controlPanel = new HtmlTestRunnerControlPanel();
28
        this.testFailed = false;
29
        this.currentTest = null;
30
        this.runAllTests = false;
31
        this.appWindow = null;
32
        // we use a timeout here to make sure the LOG has loaded first, so we can see _every_ error
33
        setTimeout(fnBind(function() {
34
            this.loadSuiteFrame();
35
        }, this), 500);
36
    },
37

    
38
    getTestSuite: function() {
39
        return suiteFrame.getCurrentTestSuite();
40
    },
41

    
42
    markFailed: function() {
43
        this.testFailed = true;
44
        this.getTestSuite().markFailed();
45
    },
46

    
47
    loadSuiteFrame: function() {
48
        if (selenium == null) {
49
            var appWindow = this._getApplicationWindow();
50
            try { appWindow.location; }
51
            catch (e) { 
52
                // when reloading, we may be pointing at an old window (Perm Denied)
53
                setTimeout(fnBind(function() {
54
                    this.loadSuiteFrame();
55
                }, this), 50);
56
                return;
57
            }
58
            selenium = Selenium.createForWindow(appWindow);
59
            this._registerCommandHandlers();
60
        }
61
        this.controlPanel.setHighlightOption();
62
        var testSuiteName = this.controlPanel.getTestSuiteName();
63
        var self = this;
64
        if (testSuiteName) {
65
            suiteFrame.load(testSuiteName, function() {setTimeout(fnBind(self._onloadTestSuite, self), 50)} );
66
            selenium.browserbot.baseUrl = absolutify(testSuiteName, window.location.href);
67
        }
68
        // DGF or should we use the old default?
69
        // selenium.browserbot.baseUrl = window.location.href;
70
        if (this.controlPanel.getBaseUrl()) {
71
            selenium.browserbot.baseUrl = this.controlPanel.getBaseUrl();
72
        }
73
    },
74

    
75
    _getApplicationWindow: function () {
76
        if (this.controlPanel.isMultiWindowMode()) {
77
            return this._getSeparateApplicationWindow();
78
        }
79
        return $('myiframe').contentWindow;
80
    },
81

    
82
    _getSeparateApplicationWindow: function () {
83
        if (this.appWindow == null) {
84
            this.appWindow = openSeparateApplicationWindow('TestRunner-splash.html', this.controlPanel.isAutomatedRun());
85
        }
86
        return this.appWindow;
87
    },
88

    
89
    _onloadTestSuite:function () {
90
        if (! this.getTestSuite().isAvailable()) {
91
            return;
92
        }
93
        if (this.controlPanel.isAutomatedRun()) {
94
            this.startTestSuite();
95
        } else if (this.controlPanel.getAutoUrl()) {
96
            //todo what is the autourl doing, left to check it out
97
            addLoadListener(this._getApplicationWindow(), fnBind(this._startSingleTest, this));
98
            this._getApplicationWindow().src = this.controlPanel.getAutoUrl();
99
        } else {
100
            this.getTestSuite().getSuiteRows()[0].loadTestCase();
101
        }
102
    },
103

    
104
    _startSingleTest:function () {
105
        removeLoadListener(getApplicationWindow(), fnBind(this._startSingleTest, this));
106
        var singleTestName = this.controlPanel.getSingleTestName();
107
        testFrame.load(singleTestName, fnBind(this.startTest, this));
108
    },
109

    
110
    _registerCommandHandlers: function () {
111
        this.commandFactory = new CommandHandlerFactory();
112
        this.commandFactory.registerAll(selenium);
113
    },
114

    
115
    startTestSuite: function() {
116
        this.controlPanel.reset();
117
        this.metrics.resetMetrics();
118
        this.getTestSuite().reset();
119
        this.runAllTests = true;
120
        this.runNextTest();
121
    },
122

    
123
    runNextTest: function () {
124
        this.getTestSuite().updateSuiteWithResultOfPreviousTest();
125
        if (!this.runAllTests) {
126
            return;
127
        }
128
        this.getTestSuite().runNextTestInSuite();
129
    },
130

    
131
    startTest: function () {
132
        this.controlPanel.reset();
133
        testFrame.scrollToTop();
134
        //todo: move testFailed and storedVars to TestCase
135
        this.testFailed = false;
136
        storedVars = new Object();
137
        this.currentTest = new HtmlRunnerTestLoop(testFrame.getCurrentTestCase(), this.metrics, this.commandFactory);
138
        currentTest = this.currentTest;
139
        this.currentTest.start();
140
    },
141

    
142
    runSingleTest:function() {
143
        this.runAllTests = false;
144
        this.metrics.resetMetrics();
145
        this.startTest();
146
    }
147
});
148

    
149
var runInterval = 0;
150

    
151
/** SeleniumFrame encapsulates an iframe element */
152
var SeleniumFrame = classCreate();
153
objectExtend(SeleniumFrame.prototype, {
154

    
155
    initialize : function(frame) {
156
        this.frame = frame;
157
        addLoadListener(this.frame, fnBind(this._handleLoad, this));
158
    },
159

    
160
    getDocument : function() {
161
        return this.frame.contentWindow.document;
162
    },
163

    
164
    _handleLoad: function() {
165
        this._attachStylesheet();
166
        this._onLoad();
167
        if (this.loadCallback) {
168
            this.loadCallback();
169
            this.loadCallback = null;
170
        }
171
    },
172

    
173
    _attachStylesheet: function() {
174
        var d = this.getDocument();
175
        var head = d.getElementsByTagName('head').item(0);
176
        var styleLink = d.createElement("link");
177
        styleLink.rel = "stylesheet";
178
        styleLink.type = "text/css";
179
        if (browserVersion && browserVersion.isChrome) {
180
            // DGF We have to play a clever trick to get the right absolute path.
181
            // This trick works on most browsers, (not IE), but is only needed in
182
            // chrome
183
            var tempLink = window.document.createElement("link");
184
            tempLink.href = "selenium-test.css"; // this will become an absolute href
185
            styleLink.href = tempLink.href;
186
        } else {
187
            // this works in every browser (except Firefox in chrome mode)
188
            var styleSheetPath = window.location.pathname.replace(/[^\/\\]+$/, "selenium-test.css");
189
            if (browserVersion.isIE && window.location.protocol == "file:") {
190
                styleSheetPath = "file://" + styleSheetPath;
191
            }
192
            styleLink.href = styleSheetPath;
193
        }
194
        head.appendChild(styleLink);
195
    },
196

    
197
    _onLoad: function() {
198
    },
199

    
200
    scrollToTop : function() {
201
        this.frame.contentWindow.scrollTo(0, 0);
202
    },
203

    
204
    _setLocation: function(location) {
205
        var isChrome = browserVersion.isChrome || false;
206
        var isHTA = browserVersion.isHTA || false;
207
        // DGF TODO multiWindow
208
        location += "?thisIsChrome=" + isChrome + "&thisIsHTA=" + isHTA;
209
        if (browserVersion.isSafari) {
210
            // safari doesn't reload the page when the location equals to current location.
211
            // hence, set the location to blank so that the page will reload automatically.
212
            this.frame.src = "about:blank";
213
            this.frame.src = location;
214
        } else {
215
            this.frame.contentWindow.location.replace(location);
216
        }
217
    },
218

    
219
    load: function(/* url, [callback] */) {
220
        if (arguments.length > 1) {
221
            this.loadCallback = arguments[1];
222

    
223
        }
224
        this._setLocation(arguments[0]);
225
    }
226

    
227
});
228

    
229
/** HtmlTestSuiteFrame - encapsulates the suite iframe element */
230
var HtmlTestSuiteFrame = classCreate();
231
objectExtend(HtmlTestSuiteFrame.prototype, SeleniumFrame.prototype);
232
objectExtend(HtmlTestSuiteFrame.prototype, {
233

    
234
    getCurrentTestSuite: function() {
235
        if (!this.currentTestSuite) {
236
            this.currentTestSuite = new HtmlTestSuite(this.getDocument());
237
        }
238
        return this.currentTestSuite;
239
    }
240

    
241
});
242

    
243
/** HtmlTestFrame - encapsulates the test-case iframe element */
244
var HtmlTestFrame = classCreate();
245
objectExtend(HtmlTestFrame.prototype, SeleniumFrame.prototype);
246
objectExtend(HtmlTestFrame.prototype, {
247

    
248
    _onLoad: function() {
249
        this.currentTestCase = new HtmlTestCase(this.getDocument(), htmlTestRunner.getTestSuite().getCurrentRow());
250
    },
251

    
252
    getCurrentTestCase: function() {
253
        return this.currentTestCase;
254
    }
255

    
256
});
257

    
258
function onSeleniumLoad() {
259
    suiteFrame = new HtmlTestSuiteFrame(getSuiteFrame());
260
    testFrame = new HtmlTestFrame(getTestFrame());
261
    htmlTestRunner = new HtmlTestRunner();
262
}
263

    
264
var suiteFrame;
265
var testFrame;
266

    
267
function getSuiteFrame() {
268
    var f = $('testSuiteFrame');
269
    if (f == null) {
270
        f = top;
271
        // proxyInjection mode does not set myiframe
272
    }
273
    return f;
274
}
275

    
276
function getTestFrame() {
277
    var f = $('testFrame');
278
    if (f == null) {
279
        f = top;
280
        // proxyInjection mode does not set myiframe
281
    }
282
    return f;
283
}
284

    
285
var HtmlTestRunnerControlPanel = classCreate();
286
objectExtend(HtmlTestRunnerControlPanel.prototype, URLConfiguration.prototype);
287
objectExtend(HtmlTestRunnerControlPanel.prototype, {
288
    initialize: function() {
289
        this._acquireQueryString();
290

    
291
        this.runInterval = 0;
292

    
293
        this.highlightOption = $('highlightOption');
294
        this.pauseButton = $('pauseTest');
295
        this.stepButton = $('stepTest');
296

    
297
        this.highlightOption.onclick = fnBindAsEventListener((function() {
298
            this.setHighlightOption();
299
        }), this);
300
        this.pauseButton.onclick = fnBindAsEventListener(this.pauseCurrentTest, this);
301
        this.stepButton.onclick = fnBindAsEventListener(this.stepCurrentTest, this);
302

    
303

    
304
        this.speedController = new Control.Slider('speedHandle', 'speedTrack', {
305
            range: $R(0, 1000),
306
            onSlide: fnBindAsEventListener(this.setRunInterval, this),
307
            onChange: fnBindAsEventListener(this.setRunInterval, this)
308
        });
309

    
310
        this._parseQueryParameter();
311
    },
312

    
313
    setHighlightOption: function () {
314
        var isHighlight = this.highlightOption.checked;
315
        selenium.browserbot.setShouldHighlightElement(isHighlight);
316
    },
317

    
318
    _parseQueryParameter: function() {
319
        var tempRunInterval = this._getQueryParameter("runInterval");
320
        if (tempRunInterval) {
321
            this.setRunInterval(tempRunInterval);
322
        }
323
        this.highlightOption.checked = this._getQueryParameter("highlight");
324
    },
325

    
326
    setRunInterval: function(runInterval) {
327
        this.runInterval = runInterval;
328
    },
329

    
330
    setToPauseAtNextCommand: function() {
331
        this.runInterval = -1;
332
    },
333

    
334
    pauseCurrentTest: function () {
335
        this.setToPauseAtNextCommand();
336
        this._switchPauseButtonToContinue();
337
    },
338

    
339
    continueCurrentTest: function () {
340
        this.reset();
341
        currentTest.resume();
342
    },
343

    
344
    reset: function() {
345
        // this.runInterval = this.speedController.value;
346
        this._switchContinueButtonToPause();
347
    },
348

    
349
    _switchContinueButtonToPause: function() {
350
        this.pauseButton.className = "cssPauseTest";
351
        this.pauseButton.onclick = fnBindAsEventListener(this.pauseCurrentTest, this);
352
    },
353

    
354
    _switchPauseButtonToContinue: function() {
355
        $('stepTest').disabled = false;
356
        this.pauseButton.className = "cssContinueTest";
357
        this.pauseButton.onclick = fnBindAsEventListener(this.continueCurrentTest, this);
358
    },
359

    
360
    stepCurrentTest: function () {
361
        this.setToPauseAtNextCommand();
362
        currentTest.resume();
363
    },
364

    
365
    isAutomatedRun: function() {
366
        return this._isQueryParameterTrue("auto");
367
    },
368

    
369
    shouldSaveResultsToFile: function() {
370
        return this._isQueryParameterTrue("save");
371
    },
372

    
373
    closeAfterTests: function() {
374
        return this._isQueryParameterTrue("close");
375
    },
376

    
377
    getTestSuiteName: function() {
378
        return this._getQueryParameter("test");
379
    },
380

    
381
    getSingleTestName: function() {
382
        return this._getQueryParameter("singletest");
383
    },
384

    
385
    getAutoUrl: function() {
386
        return this._getQueryParameter("autoURL");
387
    },
388

    
389
    getResultsUrl: function() {
390
        return this._getQueryParameter("resultsUrl");
391
    },
392

    
393
    _acquireQueryString: function() {
394
        if (this.queryString) return;
395
        if (browserVersion.isHTA) {
396
            var args = this._extractArgs();
397
            if (args.length < 2) return null;
398
            this.queryString = args[1];
399
        } else {
400
            this.queryString = location.search.substr(1);
401
        }
402
    }
403

    
404
});
405

    
406
var AbstractResultAwareRow = classCreate();
407
objectExtend(AbstractResultAwareRow.prototype, {
408

    
409
    initialize: function(trElement) {
410
        this.trElement = trElement;
411
    },
412

    
413
    setStatus: function(status) {
414
        this.unselect();
415
        this.trElement.className = this.trElement.className.replace(/status_[a-z]+/, "");
416
        if (status) {
417
            addClassName(this.trElement, "status_" + status);
418
        }
419
    },
420

    
421
    select: function() {
422
        addClassName(this.trElement, "selected");
423
        safeScrollIntoView(this.trElement);
424
    },
425

    
426
    unselect: function() {
427
        removeClassName(this.trElement, "selected");
428
    },
429

    
430
    markPassed: function() {
431
        this.setStatus("passed");
432
    },
433

    
434
    markDone: function() {
435
        this.setStatus("done");
436
    },
437

    
438
    markFailed: function() {
439
        this.setStatus("failed");
440
    }
441

    
442
});
443

    
444
var TitleRow = classCreate();
445
objectExtend(TitleRow.prototype, AbstractResultAwareRow.prototype);
446
objectExtend(TitleRow.prototype, {
447

    
448
    initialize: function(trElement) {
449
        this.trElement = trElement;
450
        trElement.className = "title";
451
    }
452

    
453
});
454

    
455
var HtmlTestCaseRow = classCreate();
456
objectExtend(HtmlTestCaseRow.prototype, AbstractResultAwareRow.prototype);
457
objectExtend(HtmlTestCaseRow.prototype, {
458

    
459
    getCommand: function () {
460
        return new SeleniumCommand(getText(this.trElement.cells[0]),
461
                getText(this.trElement.cells[1]),
462
                getText(this.trElement.cells[2]),
463
                this.isBreakpoint());
464
    },
465

    
466
    markFailed: function(errorMsg) {
467
        AbstractResultAwareRow.prototype.markFailed.call(this, errorMsg);
468
        this.setMessage(errorMsg);
469
    },
470

    
471
    setMessage: function(message) {
472
        setText(this.trElement.cells[2], message);
473
    },
474

    
475
    reset: function() {
476
        this.setStatus(null);
477
        var thirdCell = this.trElement.cells[2];
478
        if (thirdCell) {
479
            if (thirdCell.originalHTML) {
480
                thirdCell.innerHTML = thirdCell.originalHTML;
481
            } else {
482
                thirdCell.originalHTML = thirdCell.innerHTML;
483
            }
484
        }
485
    },
486

    
487
    onClick: function() {
488
        if (this.trElement.isBreakpoint == undefined) {
489
            this.trElement.isBreakpoint = true;
490
            addClassName(this.trElement, "breakpoint");
491
        } else {
492
            this.trElement.isBreakpoint = undefined;
493
            removeClassName(this.trElement, "breakpoint");
494
        }
495
    },
496

    
497
    addBreakpointSupport: function() {
498
        elementSetStyle(this.trElement, {"cursor" : "pointer"});
499
        this.trElement.onclick = fnBindAsEventListener(function() {
500
            this.onClick();
501
        }, this);
502
    },
503

    
504
    isBreakpoint: function() {
505
        if (this.trElement.isBreakpoint == undefined || this.trElement.isBreakpoint == null) {
506
            return false
507
        }
508
        return this.trElement.isBreakpoint;
509
    }
510
});
511

    
512
var HtmlTestSuiteRow = classCreate();
513
objectExtend(HtmlTestSuiteRow.prototype, AbstractResultAwareRow.prototype);
514
objectExtend(HtmlTestSuiteRow.prototype, {
515

    
516
    initialize: function(trElement, testFrame, htmlTestSuite) {
517
        this.trElement = trElement;
518
        this.testFrame = testFrame;
519
        this.htmlTestSuite = htmlTestSuite;
520
        this.link = trElement.getElementsByTagName("a")[0];
521
        this.link.onclick = fnBindAsEventListener(this._onClick, this);
522
    },
523

    
524
    reset: function() {
525
        this.setStatus(null);
526
    },
527

    
528
    _onClick: function() {
529
        this.loadTestCase(null);
530
        return false;
531
    },
532

    
533
    loadTestCase: function(onloadFunction) {
534
        this.htmlTestSuite.unselectCurrentRow();
535
        this.select();
536
        this.htmlTestSuite.currentRowInSuite = this.trElement.rowIndex - 1;
537
        // If the row has a stored results table, use that
538
        var resultsFromPreviousRun = this.trElement.cells[1];
539
        if (resultsFromPreviousRun) {
540
            // todo: delegate to TestFrame, e.g.
541
            //   this.testFrame.restoreTestCase(resultsFromPreviousRun.innerHTML);
542
            var testBody = this.testFrame.getDocument().body;
543
            testBody.innerHTML = resultsFromPreviousRun.innerHTML;
544
            this.testFrame._onLoad();
545
            if (onloadFunction) {
546
                onloadFunction();
547
            }
548
        } else {
549
            this.testFrame.load(this.link.href, onloadFunction);
550
        }
551
    },
552

    
553
    saveTestResults: function() {
554
        // todo: GLOBAL ACCESS!
555
        var resultHTML = this.testFrame.getDocument().body.innerHTML;
556
        if (!resultHTML) return;
557

    
558
        // todo: why create this div?
559
        var divElement = this.trElement.ownerDocument.createElement("div");
560
        divElement.innerHTML = resultHTML;
561

    
562
        var hiddenCell = this.trElement.ownerDocument.createElement("td");
563
        hiddenCell.appendChild(divElement);
564
        hiddenCell.style.display = "none";
565

    
566
        this.trElement.appendChild(hiddenCell);
567
    }
568

    
569
});
570

    
571
var HtmlTestSuite = classCreate();
572
objectExtend(HtmlTestSuite.prototype, {
573

    
574
    initialize: function(suiteDocument) {
575
        this.suiteDocument = suiteDocument;
576
        this.suiteRows = this._collectSuiteRows();
577
        this.titleRow = new TitleRow(this.getTestTable().rows[0]);
578
        this.reset();
579
    },
580

    
581
    reset: function() {
582
        this.failed = false;
583
        this.currentRowInSuite = -1;
584
        this.titleRow.setStatus(null);
585
        for (var i = 0; i < this.suiteRows.length; i++) {
586
            var row = this.suiteRows[i];
587
            row.reset();
588
        }
589
    },
590

    
591
    getSuiteRows: function() {
592
        return this.suiteRows;
593
    },
594

    
595
    getTestTable: function() {
596
        var tables = $A(this.suiteDocument.getElementsByTagName("table"));
597
        return tables[0];
598
    },
599

    
600
    isAvailable: function() {
601
        return this.getTestTable() != null;
602
    },
603

    
604
    _collectSuiteRows: function () {
605
        var result = [];
606
        var tables = $A(this.suiteDocument.getElementsByTagName("table"));
607
        var testTable = tables[0];
608
        for (rowNum = 1; rowNum < testTable.rows.length; rowNum++) {
609
            var rowElement = testTable.rows[rowNum];
610
            result.push(new HtmlTestSuiteRow(rowElement, testFrame, this));
611
        }
612
        
613
        // process the unsuited rows as well
614
        for (var tableNum = 1; tableNum < $A(this.suiteDocument.getElementsByTagName("table")).length; tableNum++) {
615
            testTable = tables[tableNum];
616
            for (rowNum = 1; rowNum < testTable.rows.length; rowNum++) {
617
                var rowElement = testTable.rows[rowNum];
618
                new HtmlTestSuiteRow(rowElement, testFrame, this);
619
            }
620
        }
621
        return result;
622
    },
623

    
624
    getCurrentRow: function() {
625
        if (this.currentRowInSuite == -1) {
626
            return null;
627
        }
628
        return this.suiteRows[this.currentRowInSuite];
629
    },
630

    
631
    unselectCurrentRow: function() {
632
        var currentRow = this.getCurrentRow()
633
        if (currentRow) {
634
            currentRow.unselect();
635
        }
636
    },
637

    
638
    markFailed: function() {
639
        this.failed = true;
640
        this.titleRow.markFailed();
641
    },
642

    
643
    markDone: function() {
644
        if (!this.failed) {
645
            this.titleRow.markPassed();
646
        }
647
    },
648

    
649
    _startCurrentTestCase: function() {
650
        this.getCurrentRow().loadTestCase(fnBind(htmlTestRunner.startTest, htmlTestRunner));
651
    },
652

    
653
    _onTestSuiteComplete: function() {
654
        this.markDone();
655
        new TestResult(this.failed, this.getTestTable()).post();
656
    },
657

    
658
    updateSuiteWithResultOfPreviousTest: function() {
659
        if (this.currentRowInSuite >= 0) {
660
            this.getCurrentRow().saveTestResults();
661
        }
662
    },
663

    
664
    runNextTestInSuite: function() {
665
        this.currentRowInSuite++;
666

    
667
        // If we are done with all of the tests, set the title bar as pass or fail
668
        if (this.currentRowInSuite >= this.suiteRows.length) {
669
            this._onTestSuiteComplete();
670
        } else {
671
            this._startCurrentTestCase();
672
        }
673
    }
674

    
675

    
676

    
677
});
678

    
679
var TestResult = classCreate();
680
objectExtend(TestResult.prototype, {
681

    
682
// Post the results to a servlet, CGI-script, etc.  The URL of the
683
// results-handler defaults to "/postResults", but an alternative location
684
// can be specified by providing a "resultsUrl" query parameter.
685
//
686
// Parameters passed to the results-handler are:
687
//      result:         passed/failed depending on whether the suite passed or failed
688
//      totalTime:      the total running time in seconds for the suite.
689
//
690
//      numTestPasses:  the total number of tests which passed.
691
//      numTestFailures: the total number of tests which failed.
692
//
693
//      numCommandPasses: the total number of commands which passed.
694
//      numCommandFailures: the total number of commands which failed.
695
//      numCommandErrors: the total number of commands which errored.
696
//
697
//      suite:      the suite table, including the hidden column of test results
698
//      testTable.1 to testTable.N: the individual test tables
699
//
700
    initialize: function (suiteFailed, suiteTable) {
701
        this.controlPanel = htmlTestRunner.controlPanel;
702
        this.metrics = htmlTestRunner.metrics;
703
        this.suiteFailed = suiteFailed;
704
        this.suiteTable = suiteTable;
705
    },
706

    
707
    post: function () {
708
        if (!this.controlPanel.isAutomatedRun()) {
709
            return;
710
        }
711
        var form = document.createElement("form");
712
        document.body.appendChild(form);
713

    
714
        form.id = "resultsForm";
715
        form.method = "post";
716
        form.target = "myiframe";
717

    
718
        var resultsUrl = this.controlPanel.getResultsUrl();
719
        if (!resultsUrl) {
720
            resultsUrl = "./postResults";
721
        }
722

    
723
        var actionAndParameters = resultsUrl.split('?', 2);
724
        form.action = actionAndParameters[0];
725
        var resultsUrlQueryString = actionAndParameters[1];
726

    
727
        form.createHiddenField = function(name, value) {
728
            input = document.createElement("input");
729
            input.type = "hidden";
730
            input.name = name;
731
            input.value = value;
732
            this.appendChild(input);
733
        };
734

    
735
        if (resultsUrlQueryString) {
736
            var clauses = resultsUrlQueryString.split('&');
737
            for (var i = 0; i < clauses.length; i++) {
738
                var keyValuePair = clauses[i].split('=', 2);
739
                var key = unescape(keyValuePair[0]);
740
                var value = unescape(keyValuePair[1]);
741
                form.createHiddenField(key, value);
742
            }
743
        }
744

    
745
        form.createHiddenField("selenium.version", Selenium.version);
746
        form.createHiddenField("selenium.revision", Selenium.revision);
747

    
748
        form.createHiddenField("result", this.suiteFailed ? "failed" : "passed");
749

    
750
        form.createHiddenField("totalTime", Math.floor((this.metrics.currentTime - this.metrics.startTime) / 1000));
751
        form.createHiddenField("numTestPasses", this.metrics.numTestPasses);
752
        form.createHiddenField("numTestFailures", this.metrics.numTestFailures);
753
        form.createHiddenField("numCommandPasses", this.metrics.numCommandPasses);
754
        form.createHiddenField("numCommandFailures", this.metrics.numCommandFailures);
755
        form.createHiddenField("numCommandErrors", this.metrics.numCommandErrors);
756

    
757
        // Create an input for each test table.  The inputs are named
758
        // testTable.1, testTable.2, etc.
759
        for (rowNum = 1; rowNum < this.suiteTable.rows.length; rowNum++) {
760
            // If there is a second column, then add a new input
761
            if (this.suiteTable.rows[rowNum].cells.length > 1) {
762
                var resultCell = this.suiteTable.rows[rowNum].cells[1];
763
                form.createHiddenField("testTable." + rowNum, resultCell.innerHTML);
764
                // remove the resultCell, so it's not included in the suite HTML
765
                resultCell.parentNode.removeChild(resultCell);
766
            }
767
        }
768

    
769
        form.createHiddenField("numTestTotal", rowNum);
770

    
771
        // Add HTML for the suite itself
772
        form.createHiddenField("suite", this.suiteTable.parentNode.innerHTML);
773

    
774
        if (this.controlPanel.shouldSaveResultsToFile()) {
775
            this._saveToFile(resultsUrl, form);
776
        } else {
777
            form.submit();
778
        }
779
        document.body.removeChild(form);
780
        if (this.controlPanel.closeAfterTests()) {
781
            window.top.close();
782
        }
783
    },
784

    
785
    _saveToFile: function (fileName, form) {
786
        // This only works when run as an IE HTA
787
        var inputs = new Object();
788
        for (var i = 0; i < form.elements.length; i++) {
789
            inputs[form.elements[i].name] = form.elements[i].value;
790
        }
791
        var objFSO = new ActiveXObject("Scripting.FileSystemObject")
792
        var scriptFile = objFSO.CreateTextFile(fileName);
793
        scriptFile.WriteLine("<html><body>\n<h1>Test suite results </h1>" +
794
                             "\n\n<table>\n<tr>\n<td>result:</td>\n<td>" + inputs["result"] + "</td>\n" +
795
                             "</tr>\n<tr>\n<td>totalTime:</td>\n<td>" + inputs["totalTime"] + "</td>\n</tr>\n" +
796
                             "<tr>\n<td>numTestPasses:</td>\n<td>" + inputs["numTestPasses"] + "</td>\n</tr>\n" +
797
                             "<tr>\n<td>numTestFailures:</td>\n<td>" + inputs["numTestFailures"] + "</td>\n</tr>\n" +
798
                             "<tr>\n<td>numCommandPasses:</td>\n<td>" + inputs["numCommandPasses"] + "</td>\n</tr>\n" +
799
                             "<tr>\n<td>numCommandFailures:</td>\n<td>" + inputs["numCommandFailures"] + "</td>\n</tr>\n" +
800
                             "<tr>\n<td>numCommandErrors:</td>\n<td>" + inputs["numCommandErrors"] + "</td>\n</tr>\n" +
801
                             "<tr>\n<td>" + inputs["suite"] + "</td>\n<td>&nbsp;</td>\n</tr>");
802
        var testNum = inputs["numTestTotal"];
803
        for (var rowNum = 1; rowNum < testNum; rowNum++) {
804
            scriptFile.WriteLine("<tr>\n<td>" + inputs["testTable." + rowNum] + "</td>\n<td>&nbsp;</td>\n</tr>");
805
        }
806
        scriptFile.WriteLine("</table></body></html>");
807
        scriptFile.Close();
808
    }
809
});
810

    
811
/** HtmlTestCase encapsulates an HTML test document */
812
var HtmlTestCase = classCreate();
813
objectExtend(HtmlTestCase.prototype, {
814

    
815
    initialize: function(testDocument, htmlTestSuiteRow) {
816
        if (testDocument == null) {
817
            throw "testDocument should not be null";
818
        }
819
        if (htmlTestSuiteRow == null) {
820
            throw "htmlTestSuiteRow should not be null";
821
        }
822
        this.testDocument = testDocument;
823
        this.htmlTestSuiteRow = htmlTestSuiteRow;
824
        this.headerRow = new TitleRow(this.testDocument.getElementsByTagName("tr")[0]);
825
        this.commandRows = this._collectCommandRows();
826
        this.nextCommandRowIndex = 0;
827
        this._addBreakpointSupport();
828
    },
829

    
830
    _collectCommandRows: function () {
831
        var commandRows = [];
832
        var tables = $A(this.testDocument.getElementsByTagName("table"));
833
        var self = this;
834
        for (var i = 0; i < tables.length; i++) {
835
            var table = tables[i];
836
            var tableRows = $A(table.rows);
837
            for (var j = 0; j < tableRows.length; j++) {
838
                var candidateRow = tableRows[j];
839
                if (self.isCommandRow(candidateRow)) {
840
                    commandRows.push(new HtmlTestCaseRow(candidateRow));
841
                }
842
            }
843
        }
844
        return commandRows;
845
    },
846

    
847
    isCommandRow:  function (row) {
848
        return row.cells.length >= 3;
849
    },
850

    
851
    reset: function() {
852
        /**
853
         * reset the test to runnable state
854
         */
855
        this.nextCommandRowIndex = 0;
856

    
857
        this.setStatus('');
858
        for (var i = 0; i < this.commandRows.length; i++) {
859
            var row = this.commandRows[i];
860
            row.reset();
861
        }
862

    
863
        // remove any additional fake "error" row added to the end of the document
864
        var errorElement = this.testDocument.getElementById('error');
865
        if (errorElement) {
866
            errorElement.parentNode.removeChild(errorElement);
867
        }
868
    },
869

    
870
    getCommandRows: function () {
871
        return this.commandRows;
872
    },
873

    
874
    setStatus: function(status) {
875
        this.headerRow.setStatus(status);
876
    },
877

    
878
    markFailed: function() {
879
        this.setStatus("failed");
880
        this.htmlTestSuiteRow.markFailed();
881
    },
882

    
883
    markPassed: function() {
884
        this.setStatus("passed");
885
        this.htmlTestSuiteRow.markPassed();
886
    },
887

    
888
    addErrorMessage: function(errorMsg, currentRow) {
889
        errorMsg = errorMsg.replace(/ /g, String.fromCharCode(160)).replace("\n", '\\n');
890
        if (currentRow) {
891
            currentRow.markFailed(errorMsg);
892
        } else {
893
            var errorElement = this.testDocument.createElement("p");
894
            errorElement.id = "error";
895
            setText(errorElement, errorMsg);
896
            this.testDocument.body.appendChild(errorElement);
897
            errorElement.className = "status_failed";
898
        }
899
    },
900

    
901
    _addBreakpointSupport: function() {
902
        for (var i = 0; i < this.commandRows.length; i++) {
903
            var row = this.commandRows[i];
904
            row.addBreakpointSupport();
905
        }
906
    },
907

    
908
    hasMoreCommandRows: function() {
909
        return this.nextCommandRowIndex < this.commandRows.length;
910
    },
911

    
912
    getNextCommandRow: function() {
913
        if (this.hasMoreCommandRows()) {
914
            return this.commandRows[this.nextCommandRowIndex++];
915
        }
916
        return null;
917
    }
918

    
919
});
920

    
921

    
922
// TODO: split out an JavascriptTestCase class to handle the "sejs" stuff
923

    
924
var get_new_rows = function() {
925
    var row_array = new Array();
926
    for (var i = 0; i < new_block.length; i++) {
927

    
928
        var new_source = (new_block[i][0].tokenizer.source.slice(new_block[i][0].start,
929
                new_block[i][0].end));
930

    
931
        var row = '<td style="display:none;" class="js">getEval</td>' +
932
                  '<td style="display:none;">currentTest.doNextCommand()</td>' +
933
                  '<td style="white-space: pre;">' + new_source + '</td>' +
934
                  '<td></td>'
935

    
936
        row_array.push(row);
937
    }
938
    return row_array;
939
};
940

    
941

    
942
var Metrics = classCreate();
943
objectExtend(Metrics.prototype, {
944
    initialize: function() {
945
        // The number of tests run
946
        this.numTestPasses = 0;
947
        // The number of tests that have failed
948
        this.numTestFailures = 0;
949
        // The number of commands which have passed
950
        this.numCommandPasses = 0;
951
        // The number of commands which have failed
952
        this.numCommandFailures = 0;
953
        // The number of commands which have caused errors (element not found)
954
        this.numCommandErrors = 0;
955
        // The time that the test was started.
956
        this.startTime = null;
957
        // The current time.
958
        this.currentTime = null;
959
    },
960

    
961
    printMetrics: function() {
962
        setText($('commandPasses'), this.numCommandPasses);
963
        setText($('commandFailures'), this.numCommandFailures);
964
        setText($('commandErrors'), this.numCommandErrors);
965
        setText($('testRuns'), this.numTestPasses + this.numTestFailures);
966
        setText($('testFailures'), this.numTestFailures);
967

    
968
        this.currentTime = new Date().getTime();
969

    
970
        var timeDiff = this.currentTime - this.startTime;
971
        var totalSecs = Math.floor(timeDiff / 1000);
972

    
973
        var minutes = Math.floor(totalSecs / 60);
974
        var seconds = totalSecs % 60;
975

    
976
        setText($('elapsedTime'), this._pad(minutes) + ":" + this._pad(seconds));
977
    },
978

    
979
// Puts a leading 0 on num if it is less than 10
980
    _pad: function(num) {
981
        return (num > 9) ? num : "0" + num;
982
    },
983

    
984
    resetMetrics: function() {
985
        this.numTestPasses = 0;
986
        this.numTestFailures = 0;
987
        this.numCommandPasses = 0;
988
        this.numCommandFailures = 0;
989
        this.numCommandErrors = 0;
990
        this.startTime = new Date().getTime();
991
    }
992

    
993
});
994

    
995
var HtmlRunnerCommandFactory = classCreate();
996
objectExtend(HtmlRunnerCommandFactory.prototype, {
997

    
998
    initialize: function(seleniumCommandFactory, testLoop) {
999
        this.seleniumCommandFactory = seleniumCommandFactory;
1000
        this.testLoop = testLoop;
1001
        this.handlers = {};
1002
        //todo: register commands
1003
    },
1004

    
1005
    getCommandHandler: function(command) {
1006
        if (this.handlers[command]) {
1007
            return this.handlers[command];
1008
        }
1009
        return this.seleniumCommandFactory.getCommandHandler(command);
1010
    }
1011

    
1012
});
1013

    
1014
var HtmlRunnerTestLoop = classCreate();
1015
objectExtend(HtmlRunnerTestLoop.prototype, new TestLoop());
1016
objectExtend(HtmlRunnerTestLoop.prototype, {
1017
    initialize: function(htmlTestCase, metrics, seleniumCommandFactory) {
1018

    
1019
        this.commandFactory = new HtmlRunnerCommandFactory(seleniumCommandFactory, this);
1020
        this.metrics = metrics;
1021

    
1022
        this.htmlTestCase = htmlTestCase;
1023

    
1024
        se = selenium;
1025
        global.se = selenium;
1026

    
1027
        this.currentRow = null;
1028
        this.currentRowIndex = 0;
1029

    
1030
        // used for selenium tests in javascript
1031
        this.currentItem = null;
1032
        this.commandAgenda = new Array();
1033
        this.expectedFailure = null;
1034
        this.expectedFailureType = null;
1035

    
1036
        this.htmlTestCase.reset();
1037

    
1038
        this.sejsElement = this.htmlTestCase.testDocument.getElementById('sejs');
1039
        if (this.sejsElement) {
1040
            var fname = 'Selenium JavaScript';
1041
            parse_result = parse(this.sejsElement.innerHTML, fname, 0);
1042

    
1043
            var x2 = new ExecutionContext(GLOBAL_CODE);
1044
            ExecutionContext.current = x2;
1045

    
1046
            execute(parse_result, x2)
1047
        }
1048
    },
1049

    
1050
    _advanceToNextRow: function() {
1051
        if (this.htmlTestCase.hasMoreCommandRows()) {
1052
            this.currentRow = this.htmlTestCase.getNextCommandRow();
1053
            if (this.sejsElement) {
1054
                this.currentItem = agenda.pop();
1055
                this.currentRowIndex++;
1056
            }
1057
        } else {
1058
            this.currentRow = null;
1059
            this.currentItem = null;
1060
        }
1061
    },
1062

    
1063
    nextCommand : function() {
1064
        this._advanceToNextRow();
1065
        if (this.currentRow == null) {
1066
            return null;
1067
        }
1068
        return this.currentRow.getCommand();
1069
    },
1070

    
1071
    commandStarted : function() {
1072
        $('pauseTest').disabled = false;
1073
        this.currentRow.select();
1074
        this.metrics.printMetrics();
1075
    },
1076

    
1077
    commandComplete : function(result) {
1078
        this._checkExpectedFailure(result);
1079
        if (result.failed) {
1080
            this.metrics.numCommandFailures += 1;
1081
            this._recordFailure(result.failureMessage);
1082
        } else if (result.passed) {
1083
            this.metrics.numCommandPasses += 1;
1084
            this.currentRow.markPassed();
1085
        } else {
1086
            this.currentRow.markDone();
1087
        }
1088
    },
1089

    
1090
    _checkExpectedFailure : function(result) {
1091
        if (this.expectedFailure != null) {
1092
            if (this.expectedFailureJustSet) {
1093
                this.expectedFailureJustSet = false;
1094
                return;
1095
            }
1096
            if (!result.failed) {
1097
                result.passed = false;
1098
                result.failed = true;
1099
                result.failureMessage = "Expected " + this.expectedFailureType + " did not occur.";
1100
            } else {
1101
                if (PatternMatcher.matches(this.expectedFailure, result.failureMessage)) {
1102
                    var failureType = result.error ? "error" : "failure";
1103
                    if (failureType == this.expectedFailureType) {
1104
                        result.failed = false;
1105
                        result.passed = true;
1106
                    } else {
1107
                        result.failed = true;
1108
                        result.failureMessage = "Expected "+this.expectedFailureType+", but "+failureType+" occurred instead";
1109
                    }
1110
                } else {
1111
                    result.failed = true;
1112
                    result.failureMessage = "Expected " + this.expectedFailureType + " message '" + this.expectedFailure
1113
                                            + "' but was '" + result.failureMessage + "'";
1114
                }
1115
            }
1116
            this.expectedFailure = null;
1117
            this.expectedFailureType = null;
1118
        }
1119
    },
1120

    
1121
    commandError : function(errorMessage) {
1122
        var tempResult = {};
1123
        tempResult.passed = false;
1124
        tempResult.failed = true;
1125
        tempResult.error = true;
1126
        tempResult.failureMessage = errorMessage;
1127
        this._checkExpectedFailure(tempResult);
1128
        if (tempResult.passed) {
1129
            this.currentRow.markDone();
1130
            return true;
1131
        }
1132
        errorMessage = tempResult.failureMessage;
1133
        this.metrics.numCommandErrors += 1;
1134
        this._recordFailure(errorMessage);
1135
    },
1136

    
1137
    _recordFailure : function(errorMsg) {
1138
        LOG.warn("currentTest.recordFailure: " + errorMsg);
1139
        htmlTestRunner.markFailed();
1140
        this.htmlTestCase.addErrorMessage(errorMsg, this.currentRow);
1141
    },
1142

    
1143
    testComplete : function() {
1144
        $('pauseTest').disabled = true;
1145
        $('stepTest').disabled = true;
1146
        if (htmlTestRunner.testFailed) {
1147
            this.htmlTestCase.markFailed();
1148
            this.metrics.numTestFailures += 1;
1149
        } else {
1150
            this.htmlTestCase.markPassed();
1151
            this.metrics.numTestPasses += 1;
1152
        }
1153

    
1154
        this.metrics.printMetrics();
1155

    
1156
        window.setTimeout(function() {
1157
            htmlTestRunner.runNextTest();
1158
        }, 1);
1159
    },
1160

    
1161
    getCommandInterval : function() {
1162
        return htmlTestRunner.controlPanel.runInterval;
1163
    },
1164

    
1165
    pause : function() {
1166
        htmlTestRunner.controlPanel.pauseCurrentTest();
1167
    },
1168

    
1169
    doNextCommand: function() {
1170
        var _n = this.currentItem[0];
1171
        var _x = this.currentItem[1];
1172

    
1173
        new_block = new Array()
1174
        execute(_n, _x);
1175
        if (new_block.length > 0) {
1176
            var the_table = this.htmlTestCase.testDocument.getElementById("se-js-table")
1177
            var loc = this.currentRowIndex
1178
            var new_rows = get_new_rows()
1179

    
1180
            // make the new statements visible on screen...
1181
            for (var i = 0; i < new_rows.length; i++) {
1182
                the_table.insertRow(loc + 1);
1183
                the_table.rows[loc + 1].innerHTML = new_rows[i];
1184
                this.commandRows.unshift(the_table.rows[loc + 1])
1185
            }
1186

    
1187
        }
1188
    }
1189

    
1190
});
1191

    
1192
Selenium.prototype.doPause = function(waitTime) {
1193
    /** Wait for the specified amount of time (in milliseconds)
1194
     * @param waitTime the amount of time to sleep (in milliseconds)
1195
     */
1196
    // todo: should not refer to currentTest directly
1197
    currentTest.pauseInterval = waitTime;
1198
};
1199

    
1200
Selenium.prototype.doBreak = function() {
1201
    /** Halt the currently running test, and wait for the user to press the Continue button.
1202
     * This command is useful for debugging, but be careful when using it, because it will
1203
     * force automated tests to hang until a user intervenes manually.
1204
     */
1205
    // todo: should not refer to controlPanel directly
1206
    htmlTestRunner.controlPanel.setToPauseAtNextCommand();
1207
};
1208

    
1209
Selenium.prototype.doStore = function(expression, variableName) {
1210
    /** This command is a synonym for storeExpression.
1211
     * @param expression the value to store
1212
     * @param variableName the name of a <a href="#storedVars">variable</a> in which the result is to be stored.
1213
     */
1214
    storedVars[variableName] = expression;
1215
}
1216

    
1217
/*
1218
 * Click on the located element, and attach a callback to notify
1219
 * when the page is reloaded.
1220
 */
1221
// DGF TODO this code has been broken for some time... what is it trying to accomplish?
1222
Selenium.prototype.XXXdoModalDialogTest = function(returnValue) {
1223
    this.browserbot.doModalDialogTest(returnValue);
1224
};
1225

    
1226
Selenium.prototype.doEcho = function(message) {
1227
    /** Prints the specified message into the third table cell in your Selenese tables.
1228
     * Useful for debugging.
1229
     * @param message the message to print
1230
     */
1231
    currentTest.currentRow.setMessage(message);
1232
}
1233

    
1234
Selenium.prototype.assertSelected = function(selectLocator, optionLocator) {
1235
    /**
1236
     * Verifies that the selected option of a drop-down satisfies the optionSpecifier.  <i>Note that this command is deprecated; you should use assertSelectedLabel, assertSelectedValue, assertSelectedIndex, or assertSelectedId instead.</i>
1237
     *
1238
     * <p>See the select command for more information about option locators.</p>
1239
     *
1240
     * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
1241
     * @param optionLocator an option locator, typically just an option label (e.g. "John Smith")
1242
     */
1243
    var element = this.page().findElement(selectLocator);
1244
    var locator = this.optionLocatorFactory.fromLocatorString(optionLocator);
1245
    if (element.selectedIndex == -1)
1246
    {
1247
        Assert.fail("No option selected");
1248
    }
1249
    locator.assertSelected(element);
1250
};
1251

    
1252
Selenium.prototype.assertFailureOnNext = function(message) {
1253
    /**
1254
     * Tell Selenium to expect a failure on the next command execution. 
1255
     * @param message The failure message we should expect.  This command will fail if the wrong failure message appears.
1256
     */
1257
    if (!message) {
1258
        throw new SeleniumError("Message must be provided");
1259
    }
1260

    
1261
    currentTest.expectedFailure = message;
1262
    currentTest.expectedFailureType = "failure";
1263
    currentTest.expectedFailureJustSet = true;
1264
};
1265

    
1266
Selenium.prototype.assertErrorOnNext = function(message) {
1267
    /**
1268
     * Tell Selenium to expect an error on the next command execution. 
1269
     * @param message The error message we should expect.  This command will fail if the wrong error message appears.
1270
     */
1271
     // This command temporarily installs a CommandFactory that generates
1272
     // CommandHandlers that expect an error.
1273
    if (!message) {
1274
        throw new SeleniumError("Message must be provided");
1275
    }
1276

    
1277
    currentTest.expectedFailure = message;
1278
    currentTest.expectedFailureType = "error";
1279
    currentTest.expectedFailureJustSet = true;
1280
};
1281

    
(17-17/20)