Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(292)

Side by Side Diff: pkg/unittest/interactive_html_config.dart

Issue 11301046: Restructure pkg/unittest and pkg/webdriver to follow the pub conventions. (Closed) Base URL: http://dart.googlecode.com/svn/branches/bleeding_edge/dart/
Patch Set: Created 8 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 /**
6 * This configuration can be used to rerun selected tests, as well
7 * as see diagnostic output from tests. It runs each test in its own
8 * IFrame, so the configuration consists of two parts - a 'parent'
9 * config that manages all the tests, and a 'child' config for the
10 * IFrame that runs the individual tests.
11 */
12 #library('unittest_interactive_html_config');
13
14 // TODO(gram) - add options for: remove IFrame on done/keep
15 // IFrame for failed tests/keep IFrame for all tests.
16
17 #import('dart:html');
18 #import('dart:math');
19 #import('unittest.dart');
20
21 /** The messages exchanged between parent and child. */
22
23 class _Message {
24 static const START = 'start';
25 static const LOG = 'log';
26 static const STACK = 'stack';
27 static const PASS = 'pass';
28 static const FAIL = 'fail';
29 static const ERROR = 'error';
30
31 String messageType;
32 int elapsed;
33 String body;
34
35 static String text(String messageType,
36 [int elapsed = 0, String body = '']) =>
37 '$messageType $elapsed $body';
38
39 _Message(this.messageType, [this.elapsed = 0, this.body = '']);
40
41 _Message.fromString(String msg) {
42 int idx = msg.indexOf(' ');
43 messageType = msg.substring(0, idx);
44 ++idx;
45 int idx2 = msg.indexOf(' ', idx);
46 elapsed = int.parse(msg.substring(idx, idx2));
47 ++idx2;
48 body = msg.substring(idx2);
49 }
50
51 String toString() => text(messageType, elapsed, body);
52 }
53
54
55 class HtmlConfiguration extends Configuration {
56 // TODO(rnystrom): Get rid of this if we get canonical closures for methods.
57 EventListener _onErrorClosure;
58
59 void _installErrorHandler() {
60 if (_onErrorClosure == null) {
61 _onErrorClosure =
62 (e) => handleExternalError(e, '(DOM callback has errors)');
63 // Listen for uncaught errors.
64 window.on.error.add(_onErrorClosure);
65 }
66 }
67
68 void _uninstallErrorHandler() {
69 if (_onErrorClosure != null) {
70 window.on.error.remove(_onErrorClosure);
71 _onErrorClosure = null;
72 }
73 }
74 }
75
76 /**
77 * The child configuration that is used to run individual tests in
78 * an IFrame and post the results back to the parent. In principle
79 * this can run more than one test in the IFrame but currently only
80 * one is used.
81 */
82 class ChildInteractiveHtmlConfiguration extends HtmlConfiguration {
83
84 /** The window to which results must be posted. */
85 Window parentWindow;
86
87 /** The time at which tests start. */
88 Map<int,Date> _testStarts;
89
90 ChildInteractiveHtmlConfiguration() :
91 _testStarts = new Map<int,Date>();
92
93 /** Don't start running tests automatically. */
94 get autoStart => false;
95
96 void onInit() {
97 _installErrorHandler();
98
99 /**
100 * The parent posts a 'start' message to kick things off,
101 * which is handled by this handler. It saves the parent
102 * window, gets the test ID from the query parameter in the
103 * IFrame URL, sets that as a solo test and starts test execution.
104 */
105 window.on.message.add((MessageEvent e) {
106 // Get the result, do any logging, then do a pass/fail.
107 var m = new _Message.fromString(e.data);
108 if (m.messageType == _Message.START) {
109 parentWindow = e.source;
110 String search = window.location.search;
111 int pos = search.indexOf('t=');
112 String ids = search.substring(pos+2);
113 int id = int.parse(ids);
114 setSoloTest(id);
115 runTests();
116 }
117 });
118 }
119
120 void onStart() {
121 _installErrorHandler();
122 }
123
124 /** Record the start time of the test. */
125 void onTestStart(TestCase testCase) {
126 super.onTestStart(testCase);
127 _testStarts[testCase.id]= new Date.now();
128 }
129
130 /**
131 * Tests can call [logMessage] for diagnostic output. These log
132 * messages in turn get passed to this method, which adds
133 * a timestamp and posts them back to the parent window.
134 */
135 void logTestCaseMessage(TestCase testCase, String message) {
136 int elapsed;
137 if (testCase == null) {
138 elapsed = -1;
139 } else {
140 Date end = new Date.now();
141 elapsed = end.difference(_testStarts[testCase.id]).inMilliseconds;
142 }
143 parentWindow.postMessage(
144 _Message.text(_Message.LOG, elapsed, message).toString(), '*');
145 }
146
147 /**
148 * Get the elapsed time for the test, anbd post the test result
149 * back to the parent window. If the test failed due to an exception
150 * the stack is posted back too (before the test result).
151 */
152 void onTestResult(TestCase testCase) {
153 super.onTestResult(testCase);
154 Date end = new Date.now();
155 int elapsed = end.difference(_testStarts[testCase.id]).inMilliseconds;
156 if (testCase.stackTrace != null) {
157 parentWindow.postMessage(
158 _Message.text(_Message.STACK, elapsed, testCase.stackTrace), '*');
159 }
160 parentWindow.postMessage(
161 _Message.text(testCase.result, elapsed, testCase.message), '*');
162 }
163
164 void onDone(int passed, int failed, int errors, List<TestCase> results,
165 String uncaughtError) {
166 _uninstallErrorHandler();
167 }
168 }
169
170 /**
171 * The parent configuration runs in the top-level window; it wraps the tests
172 * in new functions that create child IFrames and run the real tests.
173 */
174 class ParentInteractiveHtmlConfiguration extends HtmlConfiguration {
175 Map<int,Date> _testStarts;
176
177
178 /** The stack that was posted back from the child, if any. */
179 String _stack;
180
181 int _testTime;
182 /**
183 * Whether or not we have already wrapped the TestCase test functions
184 * in new closures that instead create an IFrame and get it to run the
185 * test.
186 */
187 bool _doneWrap = false;
188
189 /**
190 * We use this to make a single closure from _handleMessage so we
191 * can remove the handler later.
192 */
193 Function _messageHandler;
194
195 ParentInteractiveHtmlConfiguration() :
196 _testStarts = new Map<int,Date>();
197
198 // We need to block until the test is done, so we make a
199 // dummy async callback that we will use to flag completion.
200 Function completeTest = null;
201
202 wrapTest(TestCase testCase) {
203 String baseUrl = window.location.toString();
204 String url = '${baseUrl}?t=${testCase.id}';
205 return () {
206 // Rebuild the child IFrame.
207 Element childDiv = document.query('#child');
208 childDiv.nodes.clear();
209 IFrameElement child = new Element.html("""
210 <iframe id='childFrame${testCase.id}' src='$url' style='display:none'>
211 </iframe>""");
212 childDiv.nodes.add(child);
213 completeTest = expectAsync0((){ });
214 // Kick off the test when the IFrame is loaded.
215 child.on.load.add((e) {
216 child.contentWindow.postMessage(_Message.text(_Message.START), '*');
217 });
218 };
219 }
220
221 void _handleMessage(MessageEvent e) {
222 // Get the result, do any logging, then do a pass/fail.
223 var msg = new _Message.fromString(e.data);
224 if (msg.messageType == _Message.LOG) {
225 logMessage(e.data);
226 } else if (msg.messageType == _Message.STACK) {
227 _stack = msg.body;
228 } else {
229 _testTime = msg.elapsed;
230 logMessage(_Message.text(_Message.LOG, _testTime, 'Complete'));
231 if (msg.messageType == _Message.PASS) {
232 currentTestCase.pass();
233 } else if (msg.messageType == _Message.FAIL) {
234 currentTestCase.fail(msg.body, _stack);
235 } else if (msg.messageType == _Message.ERROR) {
236 currentTestCase.error(msg.body, _stack);
237 }
238 completeTest();
239 }
240 }
241
242 void onInit() {
243 _installErrorHandler();
244 _messageHandler = _handleMessage; // We need to make just one closure.
245 document.query('#group-divs').innerHTML = "";
246 }
247
248 void onStart() {
249 _installErrorHandler();
250 if (!_doneWrap) {
251 _doneWrap = true;
252 for (int i = 0; i < testCases.length; i++) {
253 testCases[i].test = wrapTest(testCases[i]);
254 testCases[i].setUp = null;
255 testCases[i].tearDown = null;
256 }
257 }
258 window.on.message.add(_messageHandler);
259 }
260
261 static const _notAlphaNumeric = const RegExp('[^a-z0-9A-Z]');
262
263 String _stringToDomId(String s) {
264 if (s.length == 0) {
265 return '-None-';
266 }
267 return s.trim().replaceAll(_notAlphaNumeric, '-');
268 }
269
270 // Used for DOM element IDs for tests result list entries.
271 static const _testIdPrefix = 'test-';
272 // Used for DOM element IDs for test log message lists.
273 static const _actionIdPrefix = 'act-';
274 // Used for DOM element IDs for test checkboxes.
275 static const _selectedIdPrefix = 'selected-';
276
277 void onTestStart(TestCase testCase) {
278 var id = testCase.id;
279 _testStarts[testCase.id]= new Date.now();
280 super.onTestStart(testCase);
281 _stack = null;
282 // Convert the group name to a DOM id.
283 String groupId = _stringToDomId(testCase.currentGroup);
284 // Get the div for the group. If it doesn't exist,
285 // create it.
286 var groupDiv = document.query('#$groupId');
287 if (groupDiv == null) {
288 groupDiv = new Element.html("""
289 <div class='test-describe' id='$groupId'>
290 <h2>
291 <input type='checkbox' checked='true' class='groupselect'>
292 Group: ${testCase.currentGroup}
293 </h2>
294 <ul class='tests'>
295 </ul>
296 </div>""");
297 document.query('#group-divs').nodes.add(groupDiv);
298 groupDiv.query('.groupselect').on.click.add((e) {
299 var parent = document.query('#$groupId');
300 InputElement cb = parent.query('.groupselect');
301 var state = cb.checked;
302 var tests = parent.query('.tests');
303 for (Element t in tests.elements) {
304 cb = t.query('.testselect') as InputElement;
305 cb.checked = state;
306 var testId = int.parse(t.id.substring(_testIdPrefix.length));
307 if (state) {
308 enableTest(testId);
309 } else {
310 disableTest(testId);
311 }
312 }
313 });
314 }
315 var list = groupDiv.query('.tests');
316 var testItem = list.query('#$_testIdPrefix$id');
317 if (testItem == null) {
318 // Create the li element for the test.
319 testItem = new Element.html("""
320 <li id='$_testIdPrefix$id' class='test-it status-pending'>
321 <div class='test-info'>
322 <p class='test-title'>
323 <input type='checkbox' checked='true' class='testselect'
324 id='$_selectedIdPrefix$id'>
325 <span class='test-label'>
326 <span class='timer-result test-timer-result'></span>
327 <span class='test-name closed'>${testCase.description}</span>
328 </span>
329 </p>
330 </div>
331 <div class='scrollpane'>
332 <ol class='test-actions' id='$_actionIdPrefix$id'></ol>
333 </div>
334 </li>""");
335 list.nodes.add(testItem);
336 testItem.query('#$_selectedIdPrefix$id').on.change.add((e) {
337 InputElement cb = testItem.query('#$_selectedIdPrefix$id');
338 testCase.enabled = cb.checked;
339 });
340 testItem.query('.test-label').on.click.add((e) {
341 var _testItem = document.query('#$_testIdPrefix$id');
342 var _actions = _testItem.query('#$_actionIdPrefix$id');
343 var _label = _testItem.query('.test-name');
344 if (_actions.style.display == 'none') {
345 _actions.style.display = 'table';
346 _label.classes.remove('closed');
347 _label.classes.add('open');
348 } else {
349 _actions.style.display = 'none';
350 _label.classes.remove('open');
351 _label.classes.add('closed');
352 }
353 });
354 } else { // Reset the test element.
355 testItem.classes.clear();
356 testItem.classes.add('test-it');
357 testItem.classes.add('status-pending');
358 testItem.query('#$_actionIdPrefix$id').innerHTML = '';
359 }
360 }
361
362 // Actually test logging is handled by the child, then posted
363 // back to the parent. So here we know that the [message] argument
364 // is in the format used by [_Message].
365 void logTestCaseMessage(TestCase testCase, String message) {
366 var msg = new _Message.fromString(message);
367 if (msg.elapsed < 0) { // No associated test case.
368 document.query('#otherlogs').nodes.add(
369 new Element.html('<p>${msg.body}</p>'));
370 } else {
371 var actions = document.query('#$_testIdPrefix${testCase.id}').
372 query('.test-actions');
373 String elapsedText = msg.elapsed >= 0 ? "${msg.elapsed}ms" : "";
374 actions.nodes.add(new Element.html(
375 "<li style='list-style-stype:none>"
376 "<div class='timer-result'>${elapsedText}</div>"
377 "<div class='test-title'>${msg.body}</div>"
378 "</li>"));
379 }
380 }
381
382 void onTestResult(TestCase testCase) {
383 if (!testCase.enabled) return;
384 super.onTestResult(testCase);
385 if (testCase.message != '') {
386 logTestCaseMessage(testCase,
387 _Message.text(_Message.LOG, -1, testCase.message));
388 }
389 int id = testCase.id;
390 var testItem = document.query('#$_testIdPrefix$id');
391 var timeSpan = testItem.query('.test-timer-result');
392 timeSpan.text = '${_testTime}ms';
393 // Convert status into what we need for our CSS.
394 String result = 'status-error';
395 if (testCase.result == 'pass') {
396 result = 'status-success';
397 } else if (testCase.result == 'fail') {
398 result = 'status-failure';
399 }
400 testItem.classes.remove('status-pending');
401 testItem.classes.add(result);
402 // hide the actions
403 var actions = testItem.query('.test-actions');
404 for (Element e in actions.nodes) {
405 e.classes.add(result);
406 }
407 actions.style.display = 'none';
408 }
409
410 void onDone(int passed, int failed, int errors, List<TestCase> results,
411 String uncaughtError) {
412 window.on.message.remove(_messageHandler);
413 _uninstallErrorHandler();
414 document.query('#busy').style.display = 'none';
415 InputElement startButton = document.query('#start');
416 startButton.disabled = false;
417 }
418 }
419
420 /**
421 * Add the divs to the DOM if they are not present. We have a 'controls'
422 * div for control, 'specs' div with test results, a 'busy' div for the
423 * animated GIF used to indicate tests are running, and a 'child' div to
424 * hold the iframe for the test.
425 */
426 void _prepareDom() {
427 if (document.query('#control') == null) {
428 // Use this as an opportunity for adding the CSS too.
429 // I wanted to avoid having to include a css element explicitly
430 // in the main html file. I considered moving all the styles
431 // inline as attributes but that started getting very messy,
432 // so we do it this way.
433 document.body.nodes.add(new Element.html("<style>$_CSS</style>"));
434 document.body.nodes.add(new Element.html(
435 "<div id='control'>"
436 "<input id='start' disabled='true' type='button' value='Run'>"
437 "</div>"));
438 document.query('#start').on.click.add((e) {
439 InputElement startButton = document.query('#start');
440 startButton.disabled = true;
441 rerunTests();
442 });
443 }
444 if (document.query('#otherlogs') == null) {
445 document.body.nodes.add(new Element.html(
446 "<div id='otherlogs'></div>"));
447 }
448 if (document.query('#specs') == null) {
449 document.body.nodes.add(new Element.html(
450 "<div id='specs'><div id='group-divs'></div></div>"));
451 }
452 if (document.query('#busy') == null) {
453 document.body.nodes.add(new Element.html(
454 "<div id='busy' style='display:none'><img src='googleballs.gif'>"
455 "</img></div>"));
456 }
457 if (document.query('#child') == null) {
458 document.body.nodes.add(new Element.html("<div id='child'></div>"));
459 }
460 }
461
462 /**
463 * Allocate a Configuration. We allocate either a parent or
464 * child, depedning on whether the URL has a search part.
465 */
466 void useInteractiveHtmlConfiguration() {
467 if (window.location.search == '') { // This is the parent.
468 _prepareDom();
469 configure(new ParentInteractiveHtmlConfiguration());
470 } else {
471 configure(new ChildInteractiveHtmlConfiguration());
472 }
473 }
474
475 String _CSS = """
476 body {
477 font-family: Arial, sans-serif;
478 margin: 0;
479 font-size: 14px;
480 }
481
482 #application h2,
483 #specs h2 {
484 margin: 0;
485 padding: 0.5em;
486 font-size: 1.1em;
487 }
488
489 #header,
490 #application,
491 .test-info,
492 .test-actions li {
493 overflow: hidden;
494 }
495
496 #application {
497 margin: 10px;
498 }
499
500 #application iframe {
501 width: 100%;
502 height: 758px;
503 }
504
505 #application iframe {
506 border: none;
507 }
508
509 #specs {
510 padding-top: 50px
511 }
512
513 .test-describe h2 {
514 border-top: 2px solid #BABAD1;
515 background-color: #efefef;
516 }
517
518 .tests,
519 .test-it ol,
520 .status-display {
521 margin: 0;
522 padding: 0;
523 }
524
525 .test-info {
526 margin-left: 1em;
527 margin-top: 0.5em;
528 border-radius: 8px 0 0 8px;
529 -webkit-border-radius: 8px 0 0 8px;
530 -moz-border-radius: 8px 0 0 8px;
531 cursor: pointer;
532 }
533
534 .test-info:hover .test-name {
535 text-decoration: underline;
536 }
537
538 .test-info .closed:before {
539 content: '\\25b8\\00A0';
540 }
541
542 .test-info .open:before {
543 content: '\\25be\\00A0';
544 font-weight: bold;
545 }
546
547 .test-it ol {
548 margin-left: 2.5em;
549 }
550
551 .status-display,
552 .status-display li {
553 float: right;
554 }
555
556 .status-display li {
557 padding: 5px 10px;
558 }
559
560 .timer-result,
561 .test-title {
562 display: inline-block;
563 margin: 0;
564 padding: 4px;
565 }
566
567 .test-actions .test-title,
568 .test-actions .test-result {
569 display: table-cell;
570 padding-left: 0.5em;
571 padding-right: 0.5em;
572 }
573
574 .test-it {
575 list-style-type: none;
576 }
577
578 .test-actions {
579 display: table;
580 }
581
582 .test-actions li {
583 display: table-row;
584 }
585
586 .timer-result {
587 width: 4em;
588 padding: 0 10px;
589 text-align: right;
590 font-family: monospace;
591 }
592
593 .test-it pre,
594 .test-actions pre {
595 clear: left;
596 color: black;
597 margin-left: 6em;
598 }
599
600 .test-describe {
601 margin: 5px 5px 10px 2em;
602 border-left: 1px solid #BABAD1;
603 border-right: 1px solid #BABAD1;
604 border-bottom: 1px solid #BABAD1;
605 padding-bottom: 0.5em;
606 }
607
608 .test-actions .status-pending .test-title:before {
609 content: \\'\\\\00bb\\\\00A0\\';
610 }
611
612 .scrollpane {
613 max-height: 20em;
614 overflow: auto;
615 }
616
617 #busy {
618 display: block;
619 }
620 /** Colors */
621
622 #header {
623 background-color: #F2C200;
624 }
625
626 #application {
627 border: 1px solid #BABAD1;
628 }
629
630 .status-pending .test-info {
631 background-color: #F9EEBC;
632 }
633
634 .status-success .test-info {
635 background-color: #B1D7A1;
636 }
637
638 .status-failure .test-info {
639 background-color: #FF8286;
640 }
641
642 .status-error .test-info {
643 background-color: black;
644 color: white;
645 }
646
647 .test-actions .status-success .test-title {
648 color: #30B30A;
649 }
650
651 .test-actions .status-failure .test-title {
652 color: #DF0000;
653 }
654
655 .test-actions .status-error .test-title {
656 color: black;
657 }
658
659 .test-actions .timer-result {
660 color: #888;
661 }
662
663 ul, menu, dir {
664 display: block;
665 list-style-type: disc;
666 -webkit-margin-before: 1em;
667 -webkit-margin-after: 1em;
668 -webkit-margin-start: 0px;
669 -webkit-margin-end: 0px;
670 -webkit-padding-start: 40px;
671 }
672
673 """;
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698