source: Dev/trunk/src/client/util/doh/runner.js @ 483

Last change on this file since 483 was 483, checked in by hendrikvanantwerpen, 11 years ago

Added Dojo 1.9.3 release.

File size: 46.3 KB
Line 
1define("doh/runner", ["dojo/_base/lang"], function(lang){
2
3var doh = {
4        // summary:
5        //              Functions for registering and running automated tests.
6};
7
8// intentionally define global tests and global doh symbols
9// TODO: scrub these globals from tests and remove this pollution for 2.0
10tests = doh;
11this.doh = doh;
12
13doh._line = "------------------------------------------------------------";
14
15doh.debug = function(){
16        // summary:
17        //              takes any number of arguments and sends them to whatever debugging
18        //              or logging facility is available in this environment
19
20        // YOUR TEST RUNNER NEEDS TO IMPLEMENT THIS
21};
22
23doh.error = function(){
24        // summary:
25        //              logging method to be used to send Error objects, so that
26        //              whatever debugging or logging facility you have can decide to treat it
27        //              as an Error object and show additional information - such as stack trace
28
29        // YOUR TEST RUNNER NEEDS TO IMPLEMENT THIS
30};
31
32doh._AssertFailure = function(msg, hint){
33        if (doh.breakOnError) {
34                //>>excludeStart("debuggerCrashesRhino", /^shrinksafe.comments/.test(kwArgs.optimize));
35                debugger;
36                //>>excludeEnd("debuggerCrashesRhino")
37        }
38        if(!(this instanceof doh._AssertFailure)){
39                return new doh._AssertFailure(msg, hint);
40        }
41        if(hint){
42                msg = (new String(msg||""))+" with hint: \n\t\t"+(new String(hint)+"\n");
43        }
44        this.message = new String(msg||"");
45        return this;
46};
47doh._AssertFailure.prototype = new Error();
48doh._AssertFailure.prototype.constructor = doh._AssertFailure;
49doh._AssertFailure.prototype.name = "doh._AssertFailure";
50
51doh.Deferred = function(canceller){
52        this.chain = [];
53        this.id = this._nextId();
54        this.fired = -1;
55        this.paused = 0;
56        this.results = [null, null];
57        this.canceller = canceller;
58        this.silentlyCancelled = false;
59};
60
61lang.extend(doh.Deferred, {
62        getTestErrback: function(cb, scope){
63                // summary:
64                //              Replaces outer getTextCallback's in nested situations to avoid multiple callback(true)'s
65                var _this = this;
66                return function(){
67                        try{
68                                cb.apply(scope||doh.global||_this, arguments);
69                        }catch(e){
70                                _this.reject(e);
71                        }
72                };
73        },
74
75        getTestCallback: function(cb, scope){
76                var _this = this;
77                return function(){
78                        try{
79                                cb.apply(scope||doh.global||_this, arguments);
80                        }catch(e){
81                                _this.reject(e);
82                                return;
83                        }
84                        _this.resolve(true);
85                };
86        },
87
88        _nextId: (function(){
89                var n = 1;
90                return function(){ return n++; };
91        })(),
92
93        cancel: function(){
94                if(this.fired == -1){
95                        if (this.canceller){
96                                this.canceller(this);
97                        }else{
98                                this.silentlyCancelled = true;
99                        }
100                        if(this.fired == -1){
101                                this.reject(new Error("Deferred(unfired)"));
102                        }
103                }else if(this.fired == 0 && this.results[0] && this.results[0].cancel){
104                        this.results[0].cancel();
105                }
106        },
107
108        _pause: function(){
109                this.paused++;
110        },
111
112        _unpause: function(){
113                this.paused--;
114                if ((this.paused == 0) && (this.fired >= 0)) {
115                        this._fire();
116                }
117        },
118
119        _continue: function(res){
120                this._resback(res);
121                this._unpause();
122        },
123
124        _resback: function(res){
125                this.fired = ((res instanceof Error) ? 1 : 0);
126                this.results[this.fired] = res;
127                this._fire();
128        },
129
130        _check: function(){
131                if(this.fired != -1){
132                        if(!this.silentlyCancelled){
133                                throw new Error("already called!");
134                        }
135                        this.silentlyCancelled = false;
136                }
137        },
138
139        resolve: function(res){
140                this._check();
141                this._resback(res);
142        },
143
144        reject: function(res){
145                this._check();
146                if(!(res instanceof Error)){
147                        res = new Error(res);
148                }
149                this._resback(res);
150        },
151
152        then: function(cb, eb){
153                this.chain.push([cb, eb]);
154                if(this.fired >= 0){
155                        this._fire();
156                }
157                return this;
158        },
159
160        always: function(cb){
161                this.then(cb, cb);
162        },
163
164        otherwise: function(eb){
165                this.then(null, eb);
166        },
167
168        isFulfilled: function(){
169                return this.fired >= 0;
170        },
171
172        isResolved: function(){
173                return this.fired == 0;
174        },
175
176        isRejected: function(){
177                return this.fired == 1;
178        },
179
180        _fire: function(){
181                var chain = this.chain;
182                var fired = this.fired;
183                var res = this.results[fired];
184                var self = this;
185                var cb = null;
186                while(chain.length > 0 && this.paused == 0){
187                        // Array
188                        var pair = chain.shift();
189                        var f = pair[fired];
190                        if(f == null){
191                                continue;
192                        }
193                        try {
194                                res = f(res);
195                                fired = ((res instanceof Error) ? 1 : 0);
196                                if(res && res.then){
197                                        cb = function(res){
198                                                self._continue(res);
199                                        };
200                                        this._pause();
201                                }
202                        }catch(err){
203                                fired = 1;
204                                res = err;
205                        }
206                }
207                this.fired = fired;
208                this.results[fired] = res;
209                if((cb)&&(this.paused)){
210                        res.always(cb);
211                }
212        }
213});
214
215lang.extend(doh.Deferred, {
216        // Back compat methods, remove for 2.0
217
218        getFunctionFromArgs: function(){
219                // Like lang.hitch but first arg (context) is optional
220                var a = arguments;
221                if((a[0])&&(!a[1])){
222                        if(typeof a[0] == "function"){
223                                return a[0];
224                        }else if(typeof a[0] == "string"){
225                                return doh.global[a[0]];
226                        }
227                }else if((a[0])&&(a[1])){
228                        return lang.hitch(a[0], a[1]);
229                }
230                return null;
231        },
232
233        addCallbacks: function(cb, eb){
234                this.then(cb, eb);
235        },
236
237        addCallback: function(cb, cbfn){
238                var enclosed = this.getFunctionFromArgs(cb, cbfn);
239                if(arguments.length > 2){
240                        enclosed = lang.hitch(null, enclosed, arguments, 2);
241                }
242                return this.then(enclosed);
243        },
244
245        addErrback: function(cb, cbfn){
246                var enclosed = this.getFunctionFromArgs(cb, cbfn);
247                if(arguments.length > 2){
248                        enclosed = lang.hitch(null, enclosed, arguments, 2);
249                }
250                return this.otherwise(enclosed);
251        },
252
253        addBoth: function(cb, cbfn){
254                var enclosed = this.getFunctionFromArgs(cb, cbfn);
255                if(arguments.length > 2){
256                        enclosed = lang.hitch(null, enclosed, arguments, 2);
257                }
258                return this.always(enclosed);
259        },
260
261        callback: function(val){
262                this.resolve(val);
263        },
264
265        errback: function(val){
266                this.reject(val);
267        }
268});
269
270//
271// State Keeping and Reporting
272//
273
274doh._testCount = 0;
275doh._groupCount = 0;
276doh._errorCount = 0;
277doh._failureCount = 0;
278doh._currentGroup = null;
279doh._currentTest = null;
280doh._paused = true;
281
282doh._init = function(){
283        this._currentGroup = null;
284        this._currentTest = null;
285        this._errorCount = 0;
286        this._failureCount = 0;
287        this.debug(this._testCount, "tests to run in", this._groupCount, "groups");
288};
289
290doh._groups = {};
291
292//
293// Test Types
294//
295doh._testTypes= {};
296
297doh.registerTestType= function(name, initProc){
298        // summary:
299        //              Adds a test type and associates a function used to initialize each test of the given type
300        // name: String
301        //              The name of the type.
302        // initProc: Function
303        //              Type specific test initializer; called after the test object is created.
304        doh._testTypes[name]= initProc;
305};
306
307doh.registerTestType("perf", function(group, tObj, type){
308        // Augment the test with some specific options to make it identifiable as a
309        // particular type of test so it can be executed properly.
310        if(type === "perf" || tObj.testType === "perf"){
311                tObj.testType = "perf";
312
313                // Build an object on the root DOH class to contain all the test results.
314                // Cache it on the test object for quick lookup later for results storage.
315                if(!doh.perfTestResults){
316                        doh.perfTestResults = {};
317                        doh.perfTestResults[group] = {};
318                }
319                if(!doh.perfTestResults[group]){
320                        doh.perfTestResults[group] = {};
321                }
322                if(!doh.perfTestResults[group][tObj.name]){
323                        doh.perfTestResults[group][tObj.name] = {};
324                }
325                tObj.results = doh.perfTestResults[group][tObj.name];
326
327                // If it's not set, then set the trial duration; default to 100ms.
328                if(!("trialDuration" in tObj)){
329                        tObj.trialDuration = 100;
330                }
331
332                // If it's not set, then set the delay between trial runs to 100ms
333                // default to 100ms to allow for GC and to make IE happy.
334                if(!("trialDelay" in tObj)){
335                        tObj.trialDelay = 100;
336                }
337
338                // If it's not set, then set number of times a trial is run to 10.
339                if(!("trialIterations" in tObj)){
340                        tObj.trialIterations = 10;
341                }
342        }
343});
344
345
346//
347// Test Registration
348//
349var
350        createFixture= function(group, test, type){
351                // test is a function, string, or fixture object
352                var tObj = test;
353                if(lang.isString(test)){
354                        tObj = {
355                                name: test.replace("/\s/g", "_"), // FIXME: bad escapement
356                                runTest: new Function("t", test)
357                        };
358                }else if(lang.isFunction(test)){
359                        // if we didn't get a fixture, wrap the function
360                        tObj = { "runTest": test };
361                        if(test["name"]){
362                                tObj.name = test.name;
363                        }else{
364                                try{
365                                        var fStr = "function ";
366                                        var ts = tObj.runTest+"";
367                                        if(0 <= ts.indexOf(fStr)){
368                                                tObj.name = ts.split(fStr)[1].split("(", 1)[0];
369                                        }
370                                        // doh.debug(tObj.runTest.toSource());
371                                }catch(e){
372                                }
373                        }
374                        // FIXME: try harder to get the test name here
375                }else if(lang.isString(tObj.runTest)){
376                        tObj.runTest= new Function("t", tObj.runTest);
377                }
378                if(!tObj.runTest){
379                        return 0;
380                }
381
382                // if the test is designated as a particular type, do type-specific initialization
383                var testType= doh._testTypes[type] || doh._testTypes[tObj.testType];
384                if(testType){
385                        testType(group, tObj);
386                }
387
388                // add the test to this group
389                doh._groups[group].push(tObj);
390                doh._testCount++;
391                doh._testRegistered(group, tObj);
392
393                return tObj;
394        },
395
396        dumpArg= function(arg){
397                if(lang.isString(arg)){
398                        return "string(" + arg + ")";
399                } else {
400                        return typeof arg;
401                }
402        },
403
404        illegalRegister= function(args, testArgPosition){
405                var hint= "\targuments: ";
406                for(var i= 0; i<5; i++){
407                        hint+= dumpArg(args[i]);
408                }
409                doh.debug("ERROR:");
410                if(testArgPosition){
411                        doh.debug("\tillegal arguments provided to doh.register; the test at argument " + testArgPosition + " wasn't a test.");
412                }else{
413                        doh.debug("\tillegal arguments provided to doh.register");
414                }
415                doh.debug(hint);
416        };
417
418doh._testRegistered = function(group, fixture){
419        // slot to be filled in
420};
421
422doh._groupStarted = function(group){
423        // slot to be filled in
424};
425
426doh._groupFinished = function(group, success){
427        // slot to be filled in
428};
429
430doh._testStarted = function(group, fixture){
431        // slot to be filled in
432};
433
434doh._testFinished = function(group, fixture, success){
435        // slot to be filled in
436};
437
438doh._registerTest = function(group, test, type){
439        // summary:
440        //              add the provided test function or fixture object to the specified
441        //              test group.
442        // group: String
443        //              string name of the group to add the test to
444        // test: Function||String||Object
445        //              TODOC
446        // type: String?
447        //              An identifier denoting the type of testing that the test performs, such
448        //              as a performance test. If falsy, defaults to test.type.
449
450        // get, possibly create, the group object
451
452        var groupObj = this._groups[group];
453        if(!groupObj){
454                this._groupCount++;
455                groupObj = this._groups[group] = [];
456                groupObj.inFlight = 0;
457        }
458        if(!test){
459                return groupObj;
460        }
461
462        // create the test fixture
463        var tObj;
464        if(lang.isFunction(test) || lang.isString(test) || "runTest" in test){
465                return createFixture(group, test, type) ? groupObj : 0;
466        }else if(lang.isArray(test)){
467                // a vector of tests...
468                for(var i=0; i<test.length; i++){
469                        tObj = createFixture(group, test[i], type);
470                        if(!tObj){
471                                this.debug("ERROR:");
472                                this.debug("\tillegal test is test array; more information follows...");
473                                return null;
474                        }
475                }
476                return groupObj;
477        }else{
478                // a hash of tests...
479                for(var testName in test){
480                        var theTest = test[testName];
481                        if(lang.isFunction(theTest) || lang.isString(theTest)){
482                                tObj = createFixture(group, {name: testName, runTest: theTest}, type);
483                        }else{
484                                // should be an object
485                                theTest.name = theTest.name || testName;
486                                tObj = createFixture(group, theTest, type);
487                        }
488                        if(!tObj){
489                                this.debug("ERROR:");
490                                this.debug("\tillegal test is test hash; more information follows...");
491                                return null;
492                        }
493                }
494                return groupObj;
495        }
496};
497
498doh._registerTestAndCheck = function(groupId, test, type, testArgPosition, args, setUp, tearDown){
499        var amdMid = 0;
500        if(groupId){
501                if(type){
502                        // explicitly provided type; therefore don't try to get type from groupId
503                        var match = groupId.match(/([^\!]+)\!(.+)/);
504                        if(match){
505                                amdMid = match[1];
506                                groupId = match[2];
507                        }
508                }else{
509                        var parts = groupId && groupId.split("!");
510                        if(parts.length == 3){
511                                amdMid = parts[0];
512                                groupId = parts[1];
513                                type = parts[2];
514                        }else if(parts.length == 2){
515                                // either (amdMid, group) or (group, type)
516                                if(parts[1] in doh._testTypes){
517                                        groupId = parts[0];
518                                        type = parts[1];
519                                }else{
520                                        amdMid = parts[0];
521                                        groupId = parts[1];
522                                }
523                        } // else, no ! and just a groupId
524                }
525        }
526
527        var group = doh._registerTest(groupId, test, type);
528        if(group){
529                if(amdMid){
530                        group.amdMid = amdMid;
531                }
532                if(setUp){
533                        group.setUp = setUp;
534                }
535                if(tearDown){
536                        group.tearDown = tearDown;
537                }
538        }else{
539                illegalRegister(arguments, testArgPosition);
540        }
541};
542
543doh._registerUrl = function(/*String*/ group, /*String*/ url, /*Integer*/ timeout, /*String*/ type, /*object*/ dohArgs){
544        // slot to be filled in
545        this.debug("ERROR:");
546        this.debug("\tNO registerUrl() METHOD AVAILABLE.");
547};
548
549var typeSigs = (function(){
550        // Generate machinery to decode the many register signatures; these are the possible signatures.
551
552        var sigs = [
553                // note: to===timeout, up===setUp, down===tearDown
554
555                // 1 arg
556                "test", function(args, a1){doh._registerTestAndCheck("ungrouped", a1, 0, 0, args, 0, 0);},
557                "url", function(args, a1){doh._registerUrl("ungrouped", a1);},
558
559                // 2 args
560                "group-test", function(args, a1, a2){doh._registerTestAndCheck(a1, a2, 0, 0, args, 0, 0);},
561                "test-type", function(args, a1, a2){doh._registerTestAndCheck("ungrouped", a1, a2, 1, args, 0, 0);},
562                "test-up", function(args, a1, a2){doh._registerTestAndCheck("ungrouped", a1, 0, 0, args, a2, 0);},
563                "group-url", function(args, a1, a2){doh._registerUrl(a1, a2);},
564                "url-to", function(args, a1, a2){doh._registerUrl("ungrouped", a1, a2);},
565                "url-type", function(args, a1, a2){doh._registerUrl("ungrouped", a1, undefined, a2);},
566                "url-args", function(args, a1, a2){doh._registerUrl("ungrouped", a1, undefined, 0, a2);},
567
568                // 3 args
569                "group-test-type", function(args, a1, a2, a3){doh._registerTestAndCheck(a1, a2, a3, 2, args, 0, 0);},
570                "group-test-up", function(args, a1, a2, a3){doh._registerTestAndCheck(a1, a2, 0, 2, args, a3, 0);},
571                "test-type-up", function(args, a1, a2, a3){doh._registerTestAndCheck("ungrouped", a1, a2, 0, args, a3, 0);},
572                "test-up-down", function(args, a1, a2, a3){doh._registerTestAndCheck("ungrouped", a1, 0, 0, args, a2, a3);},
573                "group-url-to", function(args, a1, a2, a3){doh._registerUrl(a1, a2, a3);},
574                "group-url-type", function(args, a1, a2, a3){doh._registerUrl(a1, a2, undefined, a3);},
575                "group-url-args", function(args, a1, a2, a3){doh._registerUrl(a1, a2, undefined, 0, a3);},
576                "url-to-type", function(args, a1, a2, a3){doh._registerUrl("ungrouped", a1, a2, a3);},
577                "url-to-args", function(args, a1, a2, a3){doh._registerUrl("ungrouped", a1, a2, 0, a3);},
578                "url-type-args", function(args, a1, a2, a3){doh._registerUrl("ungrouped", a1, undefined, a2, a3);},
579
580                // 4 args
581                "group-test-type-up", function(args, a1, a2, a3, a4){doh._registerTestAndCheck(a1, a2, a3, 2, args, a4, 0);},
582                "group-test-up-down", function(args, a1, a2, a3, a4){doh._registerTestAndCheck(a1, a2, 0, 2, args, a3, a4);},
583                "test-type-up-down", function(args, a1, a2, a3, a4){doh._registerTestAndCheck("ungrouped", a1, 2, 0, args, a3, a4);},
584                "group-url-to-type", function(args, a1, a2, a3, a4){doh._registerUrl(a1, a2, a3, a4);},
585                "group-url-to-args", function(args, a1, a2, a3, a4){doh._registerUrl(a1, a2, a3, 0, a4);},
586                "group-url-type-args", function(args, a1, a2, a3, a4){doh._registerUrl(a1, a2, undefined, a3, a4);},
587                "url-to-type-args", function(args, a1, a2, a3, a4){doh._registerUrl("ungrouped", a1, a2, a3, a4);},
588
589                // 5 args
590                "group-test-type-up-down", function(args, a1, a2, a3, a4, a5){doh._registerTestAndCheck(a1, a2, a3, 2, args, a4, a5);},
591                "group-url-to-type-args", function(args, a1, a2, a3, a4, a5){doh._registerUrl(a1, a2, a3, a4, a5);}
592        ];
593
594        // type-ids
595        // a - array
596        // st - string, possible type
597        // sf - string, possible function
598        // s - string not a type or function
599        // o - object
600        // f - function
601        // n - number
602    // see getTypeId inside doh.register
603        var argTypes = {
604                group:"st.sf.s",
605                test:"a.sf.o.f",
606                type:"st",
607                up:"f",
608                down:"f",
609                url:"s",
610                to:"n",
611                args:"o"
612        };
613        for(var p in argTypes){
614                argTypes[p]= argTypes[p].split(".");
615        }
616
617        function generateTypeSignature(sig, pattern, dest, func){
618                for(var nextPattern, reducedSig= sig.slice(1), typeList= argTypes[sig[0]], i=0; i<typeList.length; i++){
619                        nextPattern =  pattern + (pattern ? "-" : "") + typeList[i];
620                        if(reducedSig.length){
621                                generateTypeSignature(reducedSig, nextPattern, dest, func);
622                        }else{
623                                dest.push(nextPattern, func);
624                        }
625                }
626        }
627
628        var typeSigs = [];
629        for(var sig, func, dest, i = 0; i<sigs.length; i++){
630                sig = sigs[i++].split("-");
631                func = sigs[i];
632                dest = typeSigs[sig.length-1] || (typeSigs[sig.length-1]= []);
633                generateTypeSignature(sig, "", dest, func);
634        }
635        return typeSigs;
636})();
637
638
639doh.register = function(a1, a2, a3, a4, a5){
640        /*=====
641        doh.register = function(groupId, testOrTests, timeoutOrSetUp, tearDown){
642        // summary:
643        //              Add a test or group of tests.
644        // description:
645        //              Adds the test or tests given by testsOrUrl to the group given by group (if any). For URL tests, unless
646        //              a group is explicitly provided the group given by the URL until the document arrives at which
647        //              point the group is renamed to the title of the document. For non-URL tests, if groupId is
648        //              not provided, then tests are added to the group "ungrouped"; otherwise if the given groupId does not
649        //              exist, it is created; otherwise, tests are added to the already-existing group.
650        //
651        //              groupIds may contain embedded AMD module identifiers as prefixes and/or test types as suffixes. Prefixes
652        //              and suffixes are denoted by a "!". For example
653        // groupId: String?
654        //              The name of the group, optionally with an AMD module identifier prefix and/or
655        //              test type suffix. The value character set for group names and AMD module indentifiers
656        //              is given by [A-Za-z0-9_/.-]. If provided, prefix and suffix are denoted by "!". If
657        //              provided, type must be a valid test type.
658        // testOrTests: Array||Function||Object||String||falsy
659        //              When a function, implies a function that defines a single test. DOH passes the
660        //              DOH object to the function as the sole argument when the test is executed. When
661        //              a string, implies the definition of a single test given by `new Function("t", testOrTests)`.
662        //              When an object that contains the method `runTest` (which *must* be a function),
663        //              implies a single test given by the value of the property `runTest`. In this case,
664        //              the object may also contain the methods `setup` and `tearDown`, and, if provided, these
665        //              will be invoked on either side of the test function. Otherwise when an object (that is,
666        //              an object that does not contain the method `runTest`), then a hash from test name to
667        //              test function (either a function or string as described above); any names that begin
668        //              with "_" are ignored. When an array, the array must exclusively contain functions,
669        //              strings, and/or objects as described above and each item is added to the group as
670        //              per the items semantics.
671        // timeoutOrSetUp: integer||Function?
672        //              If tests is a URL, then must be an integer giving the number milliseconds to wait for the test
673        //              page to load before signaling an error; otherwise, a function for initializing the test group.
674        //              If a tearDown function is given, then a setup function must also be given.
675        // tearDown: Function?
676        //              A function for deinitializing the test group.
677        // example:
678        // | `"myTest/MyGroup"`                                                 // just a group, group ids need not include a slash
679        // | `"myTest/MyGroup!perf"`                                    // group with test type
680        // | `"path/to/amd/module!myTest/MyGroup"`              // group with AMD module identifier
681        // | `"path/to/amd/module!myTest/MyGroup!perf"` // group with both AMD module identifier and test type
682        //
683        //              Groups associated with AMD module identifiers may be unloaded/reloaded if using an AMD loader with
684        //              reload support (dojo's AMD loader includes such support). If no AMD module identifier is given,
685        //              the loader supports reloading, and the user demands a reload, then the groupId will be used
686        //              as the AMD module identifier.
687        //
688        //              For URL tests, the groupId is changed to the document title (if any) upon document arrival. The
689        //              title may include a test type suffix denoted with a "!" as described above.
690        //
691        //              For URL tests, if timeout is a number, then sets the timeout for loading
692        //              the particular URL; otherwise, timeout is set to DOH.iframeTimeout.
693        //
694        //              For non-URL tests, if setUp and/or tearDown are provided, then any previous setUp and/or
695        //              tearDown functions for the group are replaced as given. You may affect just setUp and/or tearDown
696        //              for a group and not provide/add any tests by providing falsy for the test argument.
697        // example:
698        // | var
699        // |    t1= function(t) {
700        // |            // this is a test
701        // |            // t will be set to DOH when the test is executed by DOH
702        // |            // etc.
703        // |    },
704        // |
705        // |    t2= {
706        // |            // this is a test fixture and may be passed as a test
707        // |
708        // |            // runTest is always required...
709        // |            runTest: function(t){
710        // |                    // the test...
711        // |            },
712        // |
713        // |            // name is optional, but recommended...
714        // |            name:"myTest",
715        // |
716        // |            // preamble is optional...
717        // |            setUp: function(){
718        // |                    // will be executed by DOH prior to executing the test
719        // |            },
720        // |
721        // |            // postscript is optional...
722        // |            tearDown: function(){ // op
723        // |                    // will be executed by DOH after executing the test
724        // |            }
725        // |    }
726        // |
727        // |    t3= [
728        // |            // this is a vector of tests...
729        // |            t1, t2
730        // |    ],
731        // |
732        // |    t4= {
733        // |            // this is a map from test name to test or test fixture
734        // |            t5: function(t){
735        // |                    // etc.
736        // |            },
737        // |
738        // |            t6: {
739        // |                    runTest: function(t){
740        // |                    // etc.
741        // |                    }
742        // |                    // name will be automatically added as "t6"
743        // |            }
744        // |    },
745        // |
746        // |    aSetup: function(){
747        // |            // etc.
748        // |    },
749        // |
750        // |    aTearDown: function(){
751        // |            // etc.
752        // |    };
753        // | // (test); note, can't provide setup/tearDown without a group
754        // | doh.register(t1);
755        // |
756        // | // (group, test, setUp, tearDown) test and/or setUp and/or tearDown can be missing
757        // | doh.register("myGroup", 0, aSetUp, aTearDown);
758        // | doh.register("myGroup", t1, aSetUp, aTearDown);
759        // | doh.register("myGroup", t1, aSetUp);
760        // | doh.register("myGroup", t1, 0, aTearDown);
761        // | doh.register("myGroup", t1);
762        // |
763        // | // various kinds of test arguments are allowed
764        // | doh.register("myGroup", t2);
765        // | doh.register("myGroup", t3);
766        // | doh.register("myGroup", t4);
767        // |
768        // | // add a perf test
769        // | doh.register("myGroup!perf", t1);
770        // |
771        // | // add a perf test with an AMD module identifier
772        // | doh.register("path/to/my/module!myGroup!perf", t1);
773        //
774        //      doh.register also supports Dojo, v1.6- signature (group, test, type), although this signature is deprecated.
775        };
776        =====*/
777
778        function getTypeId(a){
779                if(a instanceof Array){
780                        return "a";
781                }else if(typeof a == "function"){
782                        return "f";
783                }else if(typeof a == "number"){
784                        return "n";
785                }else if(typeof a == "string"){
786                        if(a in doh._testTypes){
787                                return "st";
788                        }else if(/\(/.test(a)){
789                                return "sf";
790                        }else{
791                                return "s";
792                        }
793                }else{
794                        return "o";
795                }
796        }
797
798        var
799                arity = arguments.length,
800                search = typeSigs[arity-1],
801                sig = [],
802                i;
803        for(i =0; i<arity; i++){
804                sig.push(getTypeId(arguments[i]));
805        }
806        sig = sig.join("-");
807        for(i=0; i<search.length; i+= 2){
808                if(search[i]==sig){
809                        search[i+1](arguments, a1, a2, a3, a4, a5);
810                        return;
811                }
812        }
813        illegalRegister(arguments);
814};
815
816doh.registerDocTests = function(module){
817        // summary:
818        //              Deprecated.    Won't work unless you manually load dojox.testing.DocTest, and likely not even then.
819        //              Gets all the doctests from the given module and register each of them as a single test case here.
820
821        var docTest = new dojox.testing.DocTest();
822        var docTests = docTest.getTests(module);
823        var len = docTests.length;
824        var tests = [];
825        for (var i=0; i<len; i++){
826                var test = docTests[i];
827                // Extract comment on first line and add to test name.
828                var comment = "";
829                if (test.commands.length && test.commands[0].indexOf("//")!=-1) {
830                        var parts = test.commands[0].split("//");
831                        comment = ", "+parts[parts.length-1]; // Get all after the last //, so we don't get trapped by http:// or alikes :-).
832                }
833                tests.push({
834                        runTest: (function(test){
835                                return function(t){
836                                        var r = docTest.runTest(test.commands, test.expectedResult);
837                                        t.assertTrue(r.success);
838                                };
839                        })(test),
840                        name:"Line "+test.line+comment
841                }
842                );
843        }
844        this.register("DocTests: "+module, tests);
845};
846
847//
848// deprecated v1.6- register API follows
849//
850
851doh.registerTest = function(/*String*/ group, /*Array||Function||Object*/ test, /*String*/ type){
852        // summary:
853        //              Deprecated.  Use doh.register(group/type, test) instead
854        doh.register(group + (type ? "!" + type : ""), test);
855};
856
857doh.registerGroup = function(/*String*/ group, /*Array||Function||Object*/ tests, /*Function*/ setUp, /*Function*/ tearDown, /*String*/ type){
858        // summary:
859        //              Deprecated.  Use doh.register(group/type, tests, setUp, tearDown) instead
860        var args = [(group ? group : "") + (type ? "!" + type : ""), tests];
861        setUp && args.push(setUp);
862        tearDown && args.push(tearDown);
863        doh.register.apply(doh, args);
864};
865
866doh.registerTestNs = function(/*String*/ group, /*Object*/ ns){
867        // summary:
868        //              Deprecated.  Use doh.register(group, ns) instead
869        doh.register(group, ns);
870};
871
872doh.registerTests = function(/*String*/ group, /*Array*/ testArr, /*String*/ type){
873        // summary:
874        //              Deprecated.  Use doh.register(group/type, testArr) instead
875        doh.register(group + (type ? "!" + type : ""), testArr);
876};
877
878doh.registerUrl = function(/*String*/ group, /*String*/ url, /*Integer*/ timeout, /*String*/ type, /*Object*/ args){
879        // summary:
880        //              Deprecated.  Use doh.register(group/type, url, timeout) instead
881        doh.register(group + (type ? "!" + type : ""), url+"", timeout || 10000, args || {});
882};
883
884//
885// Assertions and In-Test Utilities
886//
887doh.t = doh.assertTrue = function(/*Object*/ condition, /*String?*/ hint){
888        // summary:
889        //              is the passed item "truthy"?
890        if(arguments.length < 1){
891                throw new doh._AssertFailure("assertTrue failed because it was not passed at least 1 argument");
892        }
893        //if(lang.isString(condition) && condition.length){
894        //      return true;
895        //}
896        if(!eval(condition)){
897                throw new doh._AssertFailure("assertTrue('" + condition + "') failed", hint);
898        }
899};
900
901doh.f = doh.assertFalse = function(/*Object*/ condition, /*String?*/ hint){
902        // summary:
903        //              is the passed item "falsey"?
904        if(arguments.length < 1){
905                throw new doh._AssertFailure("assertFalse failed because it was not passed at least 1 argument");
906        }
907        if(eval(condition)){
908                throw new doh._AssertFailure("assertFalse('" + condition + "') failed", hint);
909        }
910};
911
912doh.e = doh.assertError = function(/*Error object*/expectedError, /*Object*/scope, /*String*/functionName, /*Array*/args, /*String?*/ hint){
913        // summary:
914        //              Test for a certain error to be thrown by the given function.
915        // example:
916        //              t.assertError(dojox.data.QueryReadStore.InvalidAttributeError, store, "getValue", [item, "NOT THERE"]);
917        //              t.assertError(dojox.data.QueryReadStore.InvalidItemError, store, "getValue", ["not an item", "NOT THERE"]);
918        try{
919                scope[functionName].apply(scope, args);
920        }catch (e){
921                if(e instanceof expectedError){
922
923                        return true;
924                }else{
925                        throw new doh._AssertFailure("assertError() failed:\n\texpected error\n\t\t"+expectedError+"\n\tbut got\n\t\t"+e+"\n\n", hint);
926                }
927        }
928        throw new doh._AssertFailure("assertError() failed:\n\texpected error\n\t\t"+expectedError+"\n\tbut no error caught\n\n", hint);
929};
930
931doh.is = doh.assertEqual = function(/*Object*/ expected, /*Object*/ actual, /*String?*/ hint, doNotThrow){
932        // summary:
933        //              are the passed expected and actual objects/values deeply
934        //              equivalent?
935
936        // Compare undefined always with three equal signs, because undefined==null
937        // is true, but undefined===null is false.
938        if((expected === undefined)&&(actual === undefined)){
939                return true;
940        }
941        if(arguments.length < 2){
942                throw doh._AssertFailure("assertEqual failed because it was not passed 2 arguments");
943        }
944        if((expected === actual)||(expected == actual)||
945                                ( typeof expected == "number" && typeof actual == "number" && isNaN(expected) && isNaN(actual) )){
946
947                return true;
948        }
949        if( (lang.isArray(expected) && lang.isArray(actual))&&
950                (this._arrayEq(expected, actual)) ){
951                return true;
952        }
953        if( ((typeof expected == "object")&&((typeof actual == "object")))&&
954                (this._objPropEq(expected, actual)) ){
955                return true;
956        }
957        if (doNotThrow) {
958                return false;
959        }
960        throw new doh._AssertFailure("assertEqual() failed:\n\texpected\n\t\t"+expected+"\n\tbut got\n\t\t"+actual+"\n\n", hint);
961};
962
963doh.isNot = doh.assertNotEqual = function(/*Object*/ notExpected, /*Object*/ actual, /*String?*/ hint){
964        // summary:
965        //              are the passed notexpected and actual objects/values deeply
966        //              not equivalent?
967
968        // Compare undefined always with three equal signs, because undefined==null
969        // is true, but undefined===null is false.
970        if((notExpected === undefined)&&(actual === undefined)){
971                                throw new doh._AssertFailure("assertNotEqual() failed: not expected |"+notExpected+"| but got |"+actual+"|", hint);
972        }
973        if(arguments.length < 2){
974                throw doh._AssertFailure("assertEqual failed because it was not passed 2 arguments");
975        }
976        if((notExpected === actual)||(notExpected == actual)){
977                                throw new doh._AssertFailure("assertNotEqual() failed: not expected |"+notExpected+"| but got |"+actual+"|", hint);
978        }
979        if( (lang.isArray(notExpected) && lang.isArray(actual))&&
980                (this._arrayEq(notExpected, actual)) ){
981                throw new doh._AssertFailure("assertNotEqual() failed: not expected |"+notExpected+"| but got |"+actual+"|", hint);
982        }
983        if( ((typeof notExpected == "object")&&((typeof actual == "object"))) ){
984                var isequal = false;
985                try{
986                        isequal = this._objPropEq(notExpected, actual);
987                }catch(e){
988                        if(!(e instanceof doh._AssertFailure)){
989                                throw e; // other exceptions, just throw it
990                        }
991                }
992                if(isequal){
993                                throw new doh._AssertFailure("assertNotEqual() failed: not expected |"+notExpected+"| but got |"+actual+"|", hint);
994                }
995        }
996        return true;
997};
998
999doh._arrayEq = function(expected, actual){
1000        if(expected.length != actual.length){ return false; }
1001        // FIXME: we're not handling circular refs. Do we care?
1002        for(var x=0; x<expected.length; x++){
1003                if(!doh.assertEqual(expected[x], actual[x], 0, true)){ return false; }
1004        }
1005        return true;
1006};
1007
1008doh._objPropEq = function(expected, actual){
1009        // Degenerate case: if they are both null, then their "properties" are equal.
1010        if(expected === null && actual === null){
1011                return true;
1012        }
1013        // If only one is null, they aren't equal.
1014        if(expected === null || actual === null){
1015                return false;
1016        }
1017        if(expected instanceof Date){
1018                return actual instanceof Date && expected.getTime()==actual.getTime();
1019        }
1020        var x;
1021        // Make sure ALL THE SAME properties are in both objects!
1022        for(x in actual){ // Lets check "actual" here, expected is checked below.
1023                if(!(x in expected)){
1024                        return false;
1025                }
1026        }
1027
1028        for(x in expected){
1029                if(!(x in actual)){
1030                        return false;
1031                }
1032                if(!doh.assertEqual(expected[x], actual[x], 0, true)){
1033                        return false;
1034                }
1035        }
1036        return true;
1037};
1038
1039//
1040// Runner-Wrapper
1041//
1042
1043doh._setupGroupForRun = function(/*String*/ groupName){
1044        var tg = this._groups[groupName];
1045        this.debug(this._line);
1046        this.debug("GROUP", "\""+groupName+"\"", "has", tg.length, "test"+((tg.length > 1) ? "s" : "")+" to run");
1047        doh._groupStarted(groupName);
1048};
1049
1050doh._handleFailure = function(groupName, fixture, e){
1051        // this.debug("FAILED test:", fixture.name);
1052        // mostly borrowed from JUM
1053        this._groups[groupName].failures++;
1054        var out = "";
1055        if(e instanceof this._AssertFailure){
1056                this._failureCount++;
1057                if(e["fileName"]){ out += e.fileName + ':'; }
1058                if(e["lineNumber"]){ out += e.lineNumber + ' '; }
1059                out += e.message;
1060                this.error("\t_AssertFailure:", out);
1061        }else{
1062                this._errorCount++;
1063                this.error("\tError:", e.message || e); // printing Error on IE9 (and other browsers?) yields "[Object Error]"
1064        }
1065        if(fixture.runTest["toSource"]){
1066                var ss = fixture.runTest.toSource();
1067                this.debug("\tERROR IN:\n\t\t", ss);
1068        }else{
1069                this.debug("\tERROR IN:\n\t\t", fixture.runTest);
1070        }
1071        if(e.rhinoException){
1072                e.rhinoException.printStackTrace();
1073        }else if(e.javaException){
1074                e.javaException.printStackTrace();
1075        }
1076};
1077
1078doh._runPerfFixture = function(/*String*/ groupName, /*Object*/ fixture){
1079        // summary:
1080        //              This function handles how to execute a 'performance' test
1081        //              which is different from a straight UT style test.  These
1082        //              will often do numerous iterations of the same operation and
1083        //              gather execution statistics about it, like max, min, average,
1084        //              etc.    It makes use of the already in place DOH deferred test
1085        //              handling since it is a good idea to put a pause in between each
1086        //              iteration to allow for GC cleanup and the like.
1087        // groupName:
1088        //              The test group that contains this performance test.
1089        // fixture:
1090        //              The performance test fixture.
1091        var tg = this._groups[groupName];
1092        fixture.startTime = new Date();
1093
1094        // Perf tests always need to act in an async manner as there is a
1095        // number of iterations to flow through.
1096        var def = new doh.Deferred();
1097        tg.inFlight++;
1098        def.groupName = groupName;
1099        def.fixture = fixture;
1100
1101        var threw = false;
1102        def.otherwise(function(err){
1103                doh._handleFailure(groupName, fixture, err);
1104                threw = true;
1105        });
1106
1107        // Set up the finalizer.
1108        var fulfilled;
1109        var retEnd = function(){
1110                fulfilled = true;
1111                if(fixture["tearDown"]){ fixture.tearDown(doh); }
1112                tg.inFlight--;
1113                if((!tg.inFlight)&&(tg.iterated)){
1114                        doh._groupFinished(groupName, !tg.failures);
1115                }
1116                doh._testFinished(groupName, fixture, !threw);
1117                if(doh._paused){
1118                        doh.run();
1119                }
1120        };
1121
1122        // Since these can take who knows how long, we don't want to timeout
1123        // unless explicitly set
1124        var timer;
1125        var to = fixture.timeout;
1126        if(to > 0) {
1127                timer = setTimeout(function(){
1128                        def.reject(new Error("test timeout in "+fixture.name.toString()));
1129                }, to);
1130        }
1131
1132        // Set up the end calls to the test into the deferred we'll return.
1133        def.always(function(){
1134                if(timer){
1135                        clearTimeout(timer);
1136                }
1137                retEnd();
1138        });
1139
1140        // Okay, now set up the timing loop for the actual test.
1141        // This is down as an async type test where there is a delay
1142        // between each execution to allow for GC time, etc, so the GC
1143        // has less impact on the tests.
1144        var res = fixture.results;
1145        res.trials = [];
1146
1147        // Try to figure out how many calls are needed to hit a particular threshold.
1148        var itrDef = doh._calcTrialIterations(groupName, fixture);
1149
1150        // Blah, since tests can be deferred, the actual run has to be deferred until after
1151        // we know how many iterations to run.  This is just plain ugly.
1152        itrDef.then(
1153                function(iterations){
1154                        if(iterations){
1155                                var countdown = fixture.trialIterations;
1156                                doh.debug("TIMING TEST: [" + fixture.name +
1157                                                        "]\n\t\tITERATIONS PER TRIAL: " +
1158                                                        iterations + "\n\tTRIALS: " +
1159                                                        countdown);
1160
1161                                // Figure out how many times we want to run our 'trial'.
1162                                // Where each trial consists of 'iterations' of the test.
1163
1164                                var trialRunner = function() {
1165                                        // Set up our function to execute a block of tests
1166                                        var start = new Date();
1167                                        var tTimer = new doh.Deferred();
1168
1169                                        var tState = {
1170                                                countdown: iterations
1171                                        };
1172                                        var testRunner = function(state){
1173                                                while(state){
1174                                                        try{
1175                                                                state.countdown--;
1176                                                                if(state.countdown){
1177                                                                        var ret = fixture.runTest(doh);
1178                                                                        if(ret && ret.then){
1179                                                                                // Deferreds have to be handled async,
1180                                                                                // otherwise we just keep looping.
1181                                                                                var atState = {
1182                                                                                        countdown: state.countdown
1183                                                                                };
1184                                                                                ret.then(
1185                                                                                        function(){
1186                                                                                                testRunner(atState)
1187                                                                                        },
1188                                                                                        function(err){
1189                                                                                                doh._handleFailure(groupName, fixture, err);
1190                                                                                                fixture.endTime = new Date();
1191                                                                                                def.reject(err);
1192                                                                                        }
1193                                                                                );
1194                                                                                state = null;
1195                                                                        }
1196                                                                }else{
1197                                                                        tTimer.resolve(new Date());
1198                                                                        state = null;
1199                                                                }
1200                                                        }catch(err){
1201                                                                fixture.endTime = new Date();
1202                                                                tTimer.reject(err);
1203                                                        }
1204                                                }
1205                                        };
1206                                        tTimer.then(
1207                                                function(end){
1208                                                        // Figure out the results and try to factor out function call costs.
1209                                                        var tResults = {
1210                                                                trial: (fixture.trialIterations - countdown),
1211                                                                testIterations: iterations,
1212                                                                executionTime: (end.getTime() - start.getTime()),
1213                                                                average: (end.getTime() - start.getTime())/iterations
1214                                                        };
1215                                                        res.trials.push(tResults);
1216                                                        doh.debug("\n\t\tTRIAL #: " +
1217                                                                                tResults.trial + "\n\tTIME: " +
1218                                                                                tResults.executionTime + "ms.\n\tAVG TEST TIME: " +
1219                                                                                (tResults.executionTime/tResults.testIterations) + "ms.");
1220
1221                                                        // Okay, have we run all the trials yet?
1222                                                        countdown--;
1223                                                        if(countdown){
1224                                                                setTimeout(trialRunner, fixture.trialDelay);
1225                                                        }else{
1226                                                                // Okay, we're done, let's compute some final performance results.
1227                                                                var t = res.trials;
1228
1229                                                                // We're done.
1230                                                                fixture.endTime = new Date();
1231                                                                def.resolve(true);
1232                                                        }
1233                                                },
1234
1235                                                // Handler if tTimer gets an error
1236                                                function(err){
1237                                                        fixture.endTime = new Date();
1238                                                        def.reject(err);
1239                                                }
1240                                        );
1241                                        testRunner(tState);
1242                                };
1243                                trialRunner();
1244                        }
1245                },
1246
1247                // Handler if itrDef gets an error
1248                function(err){
1249                        fixture.endTime = new Date();
1250                        def.reject(err);
1251                }
1252        );
1253
1254        // Set for a pause, returned the deferred.
1255        if(!fulfilled){
1256                doh.pause();
1257        }
1258        return def;
1259};
1260
1261doh._calcTrialIterations =      function(/*String*/ groupName, /*Object*/ fixture){
1262        // summary:
1263        //              This function determines the rough number of iterations to
1264        //              use to reach a particular MS threshold.  This returns a deferred
1265        //              since tests can theoretically by async.  Async tests aren't going to
1266        //              give great perf #s, though.
1267        //              The callback is passed the # of iterations to hit the requested
1268        //              threshold.
1269        // fixture:
1270        //              The test fixture we want to calculate iterations for.
1271        var def = new doh.Deferred();
1272        var calibrate = function () {
1273                var testFunc = lang.hitch(fixture, fixture.runTest);
1274
1275                // Set the initial state.       We have to do this as a loop instead
1276                // of a recursive function.     Otherwise, it blows the call stack
1277                // on some browsers.
1278                var iState = {
1279                        start: new Date(),
1280                        curIter: 0,
1281                        iterations: 5
1282                };
1283                var handleIteration = function(state){
1284                        while(state){
1285                                if(state.curIter < state.iterations){
1286                                        try{
1287                                                var ret = testFunc(doh);
1288                                                if(ret && ret.then){
1289                                                        var aState = {
1290                                                                start: state.start,
1291                                                                curIter: state.curIter + 1,
1292                                                                iterations: state.iterations
1293                                                        };
1294                                                        ret.then(
1295                                                                function(){
1296                                                                        handleIteration(aState);
1297                                                                },
1298                                                                function(err) {
1299                                                                        fixture.endTime = new Date();
1300                                                                        def.reject(err);
1301                                                                }
1302                                                        );
1303                                                        state = null;
1304                                                }else{
1305                                                        state.curIter++;
1306                                                }
1307                                        }catch(err){
1308                                                fixture.endTime = new Date();
1309                                                def.reject(err);
1310                                                return;
1311                                        }
1312                                }else{
1313                                        var end = new Date();
1314                                        var totalTime = (end.getTime() - state.start.getTime());
1315                                        if(totalTime < fixture.trialDuration){
1316                                                var nState = {
1317                                                        iterations: state.iterations * 2,
1318                                                        curIter: 0
1319                                                };
1320                                                state = null;
1321                                                setTimeout(function(){
1322                                                        nState.start = new Date();
1323                                                        handleIteration(nState);
1324                                                }, 50);
1325                                        }else{
1326                                                var itrs = state.iterations;
1327                                                setTimeout(function(){def.resolve(itrs)}, 50);
1328                                                state = null;
1329                                        }
1330                                }
1331                        }
1332                };
1333                handleIteration(iState);
1334        };
1335        setTimeout(calibrate, 10);
1336        return def;
1337};
1338
1339doh._runRegFixture = function(/*String*/ groupName, /*Object*/ fixture){
1340        // summary:
1341        //              Function to help run a generic doh test.  Called from _runFixture().  These are not
1342        //              specialized tests, like performance groups and such.
1343        // groupName:
1344        //              The groupName of the test.
1345        // fixture:
1346        //              The test fixture to execute.
1347
1348        var tg = this._groups[groupName];
1349
1350        fixture.startTime = new Date();
1351
1352        var ret = fixture.runTest(this);
1353
1354        // if we get a deferred back from the test runner, we know we're
1355        // gonna wait for an async result. It's up to the test code to trap
1356        // errors and give us an errback or callback.
1357        if(ret && ret.then){
1358
1359                // If ret is a dojo/Deferred, get the corresponding Promise; it has some additional methods we need.
1360                if(ret.promise){
1361                        ret = ret.promise;
1362                }
1363
1364                tg.inFlight++;
1365                ret.groupName = groupName;
1366                ret.fixture = fixture;
1367
1368                // Setup handler for when test fails.
1369                var threw = false;
1370                ret.otherwise(function(err){
1371                        if(threw){
1372                                // the fixture timeout (below) must have already fired
1373                                return;
1374                        }
1375                        doh._handleFailure(groupName, fixture, err);
1376                        threw = true;
1377                });
1378
1379                var fulfilled;
1380                var retEnd = function(){
1381                        // summary:
1382                        //              Called when tests finishes successfully, fails, or times out
1383
1384                        if(fulfilled){
1385                                // retEnd() has already executed; probably the timeout above fired and then later ret completed.
1386                                return;
1387                        }
1388                        fulfilled = true;
1389
1390                        fixture.endTime = new Date();
1391
1392                        if(fixture.tearDown){
1393                                try {
1394                                        fixture.tearDown(doh);
1395                                }catch(e){
1396                                        this.debug("Error tearing down test: "+e.message);
1397                                }
1398                        }
1399                        tg.inFlight--;
1400                        doh._testFinished(groupName, fixture, !threw);
1401
1402                        if((!tg.inFlight)&&(tg.iterated)){
1403                                doh._groupFinished(groupName, !tg.failures);
1404                        }
1405
1406                        // Go on to next test
1407                        if(doh._paused){
1408                                doh.run();
1409                        }
1410                };
1411
1412                var timer = setTimeout(function(){
1413                        if(!timer){
1414                                // we already called clearTimeout(), but it fired anyway, due to IE bug; just ignore.
1415                                return;
1416                        }
1417                        // Note: cannot call ret.reject() because ret may be a readonly promise
1418                        doh._handleFailure(groupName, fixture, new Error("test timeout in " + fixture.name.toString()));
1419                        threw = true;
1420                        retEnd();
1421                }, fixture["timeout"]||1000);
1422
1423                ret.always(function(){
1424                        clearTimeout(timer);
1425                        timer = null;
1426                        retEnd();
1427                });
1428
1429                if(!fulfilled){
1430                        doh.pause();
1431                }
1432
1433                return ret;
1434        }else{
1435                // Synchronous test; tearDown etc. handled in _runFixture(), the function that called me
1436        }
1437};
1438
1439doh._runFixture = function(groupName, fixture){
1440        var tg = this._groups[groupName];
1441        this._testStarted(groupName, fixture);
1442        var threw = false;
1443        var err = null;
1444        // run it, catching exceptions and reporting them
1445        try{
1446                // let doh reference "this.group.thinger..." which can be set by
1447                // another test or group-level setUp function
1448                fixture.group = tg;
1449                // only execute the parts of the fixture we've got
1450
1451                if(fixture["setUp"]){ fixture.setUp(this); }
1452                if(fixture["runTest"]){         // should we error out of a fixture doesn't have a runTest?
1453                        if(fixture.testType === "perf"){
1454                                // Always async deferred, so return it.
1455                                return doh._runPerfFixture(groupName, fixture);
1456                        }else{
1457                                // May or may not by async.
1458                                var ret = doh._runRegFixture(groupName, fixture);
1459                                if(ret){
1460                                        // this design is ridiculous, but tearDown etc. is handled in _runRegFixture iff fixture is async;
1461                                        // likewise with runPerfFixture
1462                                        return ret;
1463                                }
1464                        }
1465                }
1466        }catch(e){
1467                threw = true;
1468                err = e;
1469        }
1470
1471        // The rest of the code in this function executes only if test returns synchronously...
1472
1473        fixture.endTime = new Date();
1474
1475        // should try to tear down regardless whether test passed or failed...
1476        try{
1477                if(fixture["tearDown"]){ fixture.tearDown(this); }
1478        }catch(e){
1479                this.debug("Error tearing down test: "+e.message);
1480        }
1481
1482        var d = new doh.Deferred();
1483        setTimeout(lang.hitch(this, function(){
1484                if(threw){
1485                        this._handleFailure(groupName, fixture, err);
1486                }
1487                this._testFinished(groupName, fixture, !threw);
1488
1489                if((!tg.inFlight)&&(tg.iterated)){
1490                        doh._groupFinished(groupName, !tg.failures);
1491                }else if(tg.inFlight > 0){
1492                        setTimeout(lang.hitch(this, function(){
1493                                doh.runGroup(groupName);
1494                        }), 100);
1495                        this._paused = true;
1496                }
1497                if(doh._paused){
1498                        doh.run();
1499                }
1500        }), 30);
1501        doh.pause();
1502        return d;
1503};
1504
1505doh.runGroup = function(/*String*/ groupName, /*Integer*/ idx){
1506        // summary:
1507        //              runs the specified test group
1508
1509        // the general structure of the algorithm is to run through the group's
1510        // list of doh, checking before and after each of them to see if we're in
1511        // a paused state. This can be caused by the test returning a deferred or
1512        // the user hitting the pause button. In either case, we want to halt
1513        // execution of the test until something external to us restarts it. This
1514        // means we need to pickle off enough state to pick up where we left off.
1515
1516        // FIXME: need to make fixture execution async!!
1517
1518        idx = idx || 0;
1519        var tg = this._groups[groupName];
1520        if(tg.skip === true){ return; }
1521        if(lang.isArray(tg)){
1522                if(tg.iterated===undefined){
1523                        tg.iterated = false;
1524                        tg.inFlight = 0;
1525                        tg.failures = 0;
1526                        this._setupGroupForRun(groupName);
1527                        if(tg["setUp"]){ tg.setUp(this); }
1528                }
1529                for(var y=idx; y<tg.length; y++){
1530                        if(this._paused){
1531                                this._currentTest = y;
1532                                // this.debug("PAUSED at:", tg[y].name, this._currentGroup, this._currentTest);
1533                                return;
1534                        }
1535                        doh._runFixture(groupName, tg[y]);
1536                        if(this._paused){
1537                                this._currentTest = y+1;
1538                                if(this._currentTest == tg.length){ // RCG--don't think we need this; the next time through it will be taken care of
1539                                        tg.iterated = true;
1540                                }
1541                                // this.debug("PAUSED at:", tg[y].name, this._currentGroup, this._currentTest);
1542                                return;
1543                        }
1544                }
1545                tg.iterated = true;
1546                if(!tg.inFlight){
1547                        if(tg["tearDown"]){ tg.tearDown(this); }
1548                        doh._groupFinished(groupName, !tg.failures);
1549                }
1550        }
1551};
1552
1553doh._onEnd = function(){};
1554
1555doh._report = function(){
1556        // summary:
1557        //              a private method to be implemented/replaced by the "locally
1558        //              appropriate" test runner
1559
1560        // this.debug("ERROR:");
1561        // this.debug("\tNO REPORTING OUTPUT AVAILABLE.");
1562        // this.debug("\tIMPLEMENT doh._report() IN YOUR TEST RUNNER");
1563
1564        this.debug(this._line);
1565        this.debug("| TEST SUMMARY:");
1566        this.debug(this._line);
1567        this.debug("\t", this._testCount, "tests in", this._groupCount, "groups");
1568        this.debug("\t", this._errorCount, "errors");
1569        this.debug("\t", this._failureCount, "failures");
1570};
1571
1572doh.togglePaused = function(){
1573        this[(this._paused) ? "run" : "pause"]();
1574};
1575
1576doh.pause = function(){
1577        // summary:
1578        //              halt test run. Can be resumed.
1579        this._paused = true;
1580};
1581
1582doh.run = function(){
1583        // summary:
1584        //              begins or resumes the test process.
1585       
1586        this._paused = false;
1587        var cg = this._currentGroup;
1588        var ct = this._currentTest;
1589        var found = false;
1590        if(!cg){
1591                this._init(); // we weren't paused
1592                found = true;
1593        }
1594        this._currentGroup = null;
1595        this._currentTest = null;
1596        for(var x in this._groups){
1597                if(
1598                        ( (!found)&&(x == cg) )||( found )
1599                ){
1600                        if(this._paused){ return; }
1601                        this._currentGroup = x;
1602                        if(!found){
1603                                found = true;
1604                                this.runGroup(x, ct);
1605                        }else{
1606                                this.runGroup(x);
1607                        }
1608                        if(this._paused){ return; }
1609                }
1610        }
1611        this._currentGroup = null;
1612        this._currentTest = null;
1613        this._paused = false;
1614        this._onEnd();
1615        this._report();
1616};
1617
1618doh.runOnLoad = function(){
1619        require(["dojo/ready"], function(ready){
1620                ready(doh, "run");
1621        });
1622};
1623
1624return doh;
1625
1626});
1627
1628// backcompat hack: if in the browser, then loading doh/runner implies loading doh/_browserRunner. This is the
1629// behavior of 1.6- and is leveraged on many test documents that dojo.require("doh.runner"). Note that this
1630// hack will only work in synchronous mode; but if you're not in synchronous mode, you don't care about this.
1631// Remove for 2.0.
1632if (typeof window!="undefined" && typeof location!="undefined" && typeof document!="undefined" && window.location==location && window.document==document) {
1633        require(["doh/_browserRunner"]);
1634}
Note: See TracBrowser for help on using the repository browser.