2 Copyright (c) 2010, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
8 YUI.add('test', function(Y) {
11 * YUI JavaScript Testing Framework
20 * Test case containing various tests to run.
21 * @param template An object containing any number of test methods, other methods,
22 * an optional name, and anything else the test case needs.
27 Y.Test.Case = function (template) {
30 * Special rules for the test case. Possible subobjects
31 * are fail, for tests that should fail, and error, for
32 * tests that should throw an error.
36 //copy over all properties from the template to this object
37 for (var prop in template) {
38 this[prop] = template[prop];
41 //check for a valid name
42 if (!Y.Lang.isString(this.name)){
44 * Name for the test case.
46 this.name = "testCase" + Y.guid();
51 Y.Test.Case.prototype = {
54 * Resumes a paused test and runs the given function.
55 * @param {Function} segment (Optional) The function to run.
56 * If omitted, the test automatically passes.
60 resume : function (segment) {
61 Y.Test.Runner.resume(segment);
65 * Causes the test case to wait a specified amount of time and then
66 * continue executing the given code.
67 * @param {Function} segment (Optional) The function to run after the delay.
68 * If omitted, the TestRunner will wait until resume() is called.
69 * @param {int} delay (Optional) The number of milliseconds to wait before running
70 * the function. If omitted, defaults to zero.
74 wait : function (segment, delay){
76 if (Y.Lang.isFunction(args[0])){
77 throw new Y.Test.Wait(args[0], args[1]);
79 throw new Y.Test.Wait(function(){
80 Y.Assert.fail("Timeout: wait() called but resume() never called.");
81 }, (Y.Lang.isNumber(args[0]) ? args[0] : 10000));
85 //-------------------------------------------------------------------------
87 //-------------------------------------------------------------------------
90 * Function to run before each test is executed.
98 * Function to run after each test is executed.
102 tearDown: function () {
107 * Represents a stoppage in test execution to wait for an amount of time before
109 * @param {Function} segment A function to run when the wait is over.
110 * @param {int} delay The number of milliseconds to wait before running the code.
116 Y.Test.Wait = function (segment, delay) {
119 * The segment of code to run when the wait is over.
123 this.segment = (Y.Lang.isFunction(segment) ? segment : null);
126 * The delay before running the segment of code.
130 this.delay = (Y.Lang.isNumber(delay) ? delay : 0);
137 * A test suite that can contain a collection of TestCase and TestSuite objects.
138 * @param {String||Object} data The name of the test suite or an object containing
139 * a name property as well as setUp and tearDown methods.
144 Y.Test.Suite = function (data /*:String||Object*/) {
147 * The name of the test suite.
154 * Array of test suites and
159 //initialize the properties
160 if (Y.Lang.isString(data)){
162 } else if (Y.Lang.isObject(data)){
163 Y.mix(this, data, true);
167 if (this.name === ""){
168 this.name = "testSuite" + Y.guid();
173 Y.Test.Suite.prototype = {
176 * Adds a test suite or test case to the test suite.
177 * @param {Y.Test.Suite||Y.Test.Case} testObject The test suite or test case to add.
181 add : function (testObject /*:Y.Test.Suite*/) {
182 if (testObject instanceof Y.Test.Suite || testObject instanceof Y.Test.Case) {
183 this.items.push(testObject);
188 //-------------------------------------------------------------------------
190 //-------------------------------------------------------------------------
193 * Function to run before each test is executed.
197 setUp : function () {
201 * Function to run after each test is executed.
205 tearDown: function () {
211 * Runs test suites and test cases, providing events to allowing for the
212 * interpretation of test results.
217 Y.Test.Runner = (function(){
219 /* (intentionally not documented)
220 * A node in the test tree structure. May represent a TestSuite, TestCase, or
222 * @param {Variant} testObject A TestSuite, TestCase, or the name of a test function.
227 function TestNode(testObject){
229 /* (intentionally not documented)
230 * The TestSuite, TestCase, or test function represented by this node.
232 * @property testObject
234 this.testObject = testObject;
236 /* (intentionally not documented)
237 * Pointer to this node's first child.
239 * @property firstChild
241 this.firstChild = null;
243 /* (intentionally not documented)
244 * Pointer to this node's last child.
246 * @property lastChild
248 this.lastChild = null;
250 /* (intentionally not documented)
251 * Pointer to this node's parent.
257 /* (intentionally not documented)
258 * Pointer to this node's next sibling.
264 /* (intentionally not documented)
265 * Test results for this test object.
278 if (testObject instanceof Y.Test.Suite){
279 this.results.type = "testsuite";
280 this.results.name = testObject.name;
281 } else if (testObject instanceof Y.Test.Case){
282 this.results.type = "testcase";
283 this.results.name = testObject.name;
288 TestNode.prototype = {
290 /* (intentionally not documented)
291 * Appends a new test object (TestSuite, TestCase, or test function name) as a child
293 * @param {Variant} testObject A TestSuite, TestCase, or the name of a test function.
296 appendChild : function (testObject){
297 var node = new TestNode(testObject);
298 if (this.firstChild === null){
299 this.firstChild = this.lastChild = node;
301 this.lastChild.next = node;
302 this.lastChild = node;
310 * Runs test suites and test cases, providing events to allowing for the
311 * interpretation of test results.
316 function TestRunner(){
318 //inherit from EventProvider
319 TestRunner.superclass.constructor.apply(this,arguments);
322 * Suite on which to attach all TestSuites and TestCases to be run.
324 * @property masterSuite
328 this.masterSuite /*:Y.Test.Suite*/ = new Y.Test.Suite("yuitests" + (new Date()).getTime());
331 * Pointer to the current node in the test tree.
340 * Pointer to the root node in the test tree.
349 * Indicates if the TestRunner will log events or not.
358 * Indicates if the TestRunner is waiting as a result of
359 * wait() being called.
365 this._waiting = false;
368 * Indicates if the TestRunner is currently running tests.
374 this._running = false;
377 * Holds copy of the results object generated when all tests are
381 * @property _lastResults
384 this._lastResults = null;
388 this.TEST_CASE_BEGIN_EVENT,
389 this.TEST_CASE_COMPLETE_EVENT,
390 this.TEST_SUITE_BEGIN_EVENT,
391 this.TEST_SUITE_COMPLETE_EVENT,
392 this.TEST_PASS_EVENT,
393 this.TEST_FAIL_EVENT,
394 this.TEST_IGNORE_EVENT,
398 for (var i=0; i < events.length; i++){
399 this.on(events[i], this._logEvent, this, true);
404 Y.extend(TestRunner, Y.Event.Target, {
406 //-------------------------------------------------------------------------
408 //-------------------------------------------------------------------------
411 * Fires when a test case is opened but before the first
413 * @event testcasebegin
416 TEST_CASE_BEGIN_EVENT : "testcasebegin",
419 * Fires when all tests in a test case have been executed.
420 * @event testcasecomplete
423 TEST_CASE_COMPLETE_EVENT : "testcasecomplete",
426 * Fires when a test suite is opened but before the first
428 * @event testsuitebegin
431 TEST_SUITE_BEGIN_EVENT : "testsuitebegin",
434 * Fires when all test cases in a test suite have been
436 * @event testsuitecomplete
439 TEST_SUITE_COMPLETE_EVENT : "testsuitecomplete",
442 * Fires when a test has passed.
446 TEST_PASS_EVENT : "pass",
449 * Fires when a test has failed.
453 TEST_FAIL_EVENT : "fail",
456 * Fires when a test has been ignored.
460 TEST_IGNORE_EVENT : "ignore",
463 * Fires when all test suites and test cases have been completed.
467 COMPLETE_EVENT : "complete",
470 * Fires when the run() method is called.
474 BEGIN_EVENT : "begin",
476 //-------------------------------------------------------------------------
477 // Logging-Related Methods
478 //-------------------------------------------------------------------------
482 * Disable logging via Y.log(). Test output will not be visible unless
483 * TestRunner events are subscribed to.
485 * @method disableLogging
488 disableLogging: function(){
493 * Enable logging via Y.log(). Test output is published and can be read via
496 * @method enableLogging
499 enableLogging: function(){
504 * Logs TestRunner events using Y.log().
505 * @param {Object} event The event object for the event.
511 _logEvent: function(event){
515 var messageType = "";
518 case this.BEGIN_EVENT:
519 message = "Testing began at " + (new Date()).toString() + ".";
520 messageType = "info";
523 case this.COMPLETE_EVENT:
524 message = Y.substitute("Testing completed at " +
525 (new Date()).toString() + ".\n" +
526 "Passed:{passed} Failed:{failed} " +
527 "Total:{total} ({ignored} ignored)",
529 messageType = "info";
532 case this.TEST_FAIL_EVENT:
533 message = event.testName + ": failed.\n" + event.error.getMessage();
534 messageType = "fail";
537 case this.TEST_IGNORE_EVENT:
538 message = event.testName + ": ignored.";
539 messageType = "ignore";
542 case this.TEST_PASS_EVENT:
543 message = event.testName + ": passed.";
544 messageType = "pass";
547 case this.TEST_SUITE_BEGIN_EVENT:
548 message = "Test suite \"" + event.testSuite.name + "\" started.";
549 messageType = "info";
552 case this.TEST_SUITE_COMPLETE_EVENT:
553 message = Y.substitute("Test suite \"" +
554 event.testSuite.name + "\" completed" + ".\n" +
555 "Passed:{passed} Failed:{failed} " +
556 "Total:{total} ({ignored} ignored)",
558 messageType = "info";
561 case this.TEST_CASE_BEGIN_EVENT:
562 message = "Test case \"" + event.testCase.name + "\" started.";
563 messageType = "info";
566 case this.TEST_CASE_COMPLETE_EVENT:
567 message = Y.substitute("Test case \"" +
568 event.testCase.name + "\" completed.\n" +
569 "Passed:{passed} Failed:{failed} " +
570 "Total:{total} ({ignored} ignored)",
572 messageType = "info";
575 message = "Unexpected event " + event.type;
579 //only log if required
581 Y.log(message, messageType, "TestRunner");
585 //-------------------------------------------------------------------------
586 // Test Tree-Related Methods
587 //-------------------------------------------------------------------------
590 * Adds a test case to the test tree as a child of the specified node.
591 * @param {TestNode} parentNode The node to add the test case to as a child.
592 * @param {Y.Test.Case} testCase The test case to add.
596 * @method _addTestCaseToTestTree
598 _addTestCaseToTestTree : function (parentNode, testCase /*:Y.Test.Case*/){
601 var node = parentNode.appendChild(testCase),
605 //iterate over the items in the test case
606 for (prop in testCase){
607 if ((prop.indexOf("test") === 0 || (prop.toLowerCase().indexOf("should") > -1 && prop.indexOf(" ") > -1 ))&& Y.Lang.isFunction(testCase[prop])){
608 node.appendChild(prop);
615 * Adds a test suite to the test tree as a child of the specified node.
616 * @param {TestNode} parentNode The node to add the test suite to as a child.
617 * @param {Y.Test.Suite} testSuite The test suite to add.
621 * @method _addTestSuiteToTestTree
623 _addTestSuiteToTestTree : function (parentNode, testSuite /*:Y.Test.Suite*/) {
626 var node = parentNode.appendChild(testSuite);
628 //iterate over the items in the master suite
629 for (var i=0; i < testSuite.items.length; i++){
630 if (testSuite.items[i] instanceof Y.Test.Suite) {
631 this._addTestSuiteToTestTree(node, testSuite.items[i]);
632 } else if (testSuite.items[i] instanceof Y.Test.Case) {
633 this._addTestCaseToTestTree(node, testSuite.items[i]);
639 * Builds the test tree based on items in the master suite. The tree is a hierarchical
640 * representation of the test suites, test cases, and test functions. The resulting tree
641 * is stored in _root and the pointer _cur is set to the root initially.
645 * @method _buildTestTree
647 _buildTestTree : function () {
649 this._root = new TestNode(this.masterSuite);
650 //this._cur = this._root;
652 //iterate over the items in the master suite
653 for (var i=0; i < this.masterSuite.items.length; i++){
654 if (this.masterSuite.items[i] instanceof Y.Test.Suite) {
655 this._addTestSuiteToTestTree(this._root, this.masterSuite.items[i]);
656 } else if (this.masterSuite.items[i] instanceof Y.Test.Case) {
657 this._addTestCaseToTestTree(this._root, this.masterSuite.items[i]);
663 //-------------------------------------------------------------------------
665 //-------------------------------------------------------------------------
668 * Handles the completion of a test object's tests. Tallies test results
669 * from one level up to the next.
670 * @param {TestNode} node The TestNode representing the test object.
672 * @method _handleTestObjectComplete
675 _handleTestObjectComplete : function (node) {
676 if (Y.Lang.isObject(node.testObject)){
679 node.parent.results.passed += node.results.passed;
680 node.parent.results.failed += node.results.failed;
681 node.parent.results.total += node.results.total;
682 node.parent.results.ignored += node.results.ignored;
683 //node.parent.results.duration += node.results.duration;
684 node.parent.results[node.testObject.name] = node.results;
687 if (node.testObject instanceof Y.Test.Suite){
688 node.testObject.tearDown();
689 node.results.duration = (new Date()) - node._start;
690 this.fire(this.TEST_SUITE_COMPLETE_EVENT, { testSuite: node.testObject, results: node.results});
691 } else if (node.testObject instanceof Y.Test.Case){
692 node.results.duration = (new Date()) - node._start;
693 this.fire(this.TEST_CASE_COMPLETE_EVENT, { testCase: node.testObject, results: node.results});
698 //-------------------------------------------------------------------------
699 // Navigation Methods
700 //-------------------------------------------------------------------------
703 * Retrieves the next node in the test tree.
704 * @return {TestNode} The next node in the test tree or null if the end is reached.
709 _next : function () {
711 if (this._cur === null){
712 this._cur = this._root;
713 } else if (this._cur.firstChild) {
714 this._cur = this._cur.firstChild;
715 } else if (this._cur.next) {
716 this._cur = this._cur.next;
718 while (this._cur && !this._cur.next && this._cur !== this._root){
719 this._handleTestObjectComplete(this._cur);
720 this._cur = this._cur.parent;
723 this._handleTestObjectComplete(this._cur);
725 if (this._cur == this._root){
726 this._cur.results.type = "report";
727 this._cur.results.timestamp = (new Date()).toLocaleString();
728 this._cur.results.duration = (new Date()) - this._cur._start;
729 this._lastResults = this._cur.results;
730 this._running = false;
731 this.fire(this.COMPLETE_EVENT, { results: this._lastResults});
734 this._cur = this._cur.next;
742 * Runs a test case or test suite, returning the results.
743 * @param {Y.Test.Case|Y.Test.Suite} testObject The test case or test suite to run.
744 * @return {Object} Results of the execution with properties passed, failed, and total.
751 //flag to indicate if the TestRunner should wait before continuing
752 var shouldWait = false;
754 //get the next test node
755 var node = this._next();
759 //set flag to say the testrunner is running
760 this._running = true;
762 //eliminate last results
763 this._lastResult = null;
765 var testObject = node.testObject;
767 //figure out what to do
768 if (Y.Lang.isObject(testObject)){
769 if (testObject instanceof Y.Test.Suite){
770 this.fire(this.TEST_SUITE_BEGIN_EVENT, { testSuite: testObject });
771 node._start = new Date();
773 } else if (testObject instanceof Y.Test.Case){
774 this.fire(this.TEST_CASE_BEGIN_EVENT, { testCase: testObject });
775 node._start = new Date();
778 //some environments don't support setTimeout
779 if (typeof setTimeout != "undefined"){
780 setTimeout(function(){
781 Y.Test.Runner._run();
793 _resumeTest : function (segment) {
795 //get relevant information
796 var node = this._cur;
798 //we know there's no more waiting now
799 this._waiting = false;
801 //if there's no node, it probably means a wait() was called after resume()
803 //TODO: Handle in some way?
804 //console.log("wait() called after resume()");
805 //this.fire("error", { testCase: "(unknown)", test: "(unknown)", error: new Error("wait() called after resume()")} );
809 var testName = node.testObject;
810 var testCase /*:Y.Test.Case*/ = node.parent.testObject;
812 //cancel other waits if available
813 if (testCase.__yui_wait){
814 clearTimeout(testCase.__yui_wait);
815 delete testCase.__yui_wait;
818 //get the "should" test cases
819 var shouldFail = (testCase._should.fail || {})[testName];
820 var shouldError = (testCase._should.error || {})[testName];
822 //variable to hold whether or not the test failed
830 segment.apply(testCase);
832 //if it should fail, and it got here, then it's a fail because it didn't
834 error = new Y.Assert.ShouldFail();
836 } else if (shouldError){
837 error = new Y.Assert.ShouldError();
843 //cancel any pending waits, the test already failed
844 if (testCase.__yui_wait){
845 clearTimeout(testCase.__yui_wait);
846 delete testCase.__yui_wait;
849 //figure out what type of error it was
850 if (thrown instanceof Y.Assert.Error) {
855 } else if (thrown instanceof Y.Test.Wait){
857 if (Y.Lang.isFunction(thrown.segment)){
858 if (Y.Lang.isNumber(thrown.delay)){
860 //some environments don't support setTimeout
861 if (typeof setTimeout != "undefined"){
862 testCase.__yui_wait = setTimeout(function(){
863 Y.Test.Runner._resumeTest(thrown.segment);
865 this._waiting = true;
867 throw new Error("Asynchronous tests not supported in this environment.");
875 //first check to see if it should error
877 error = new Y.Assert.UnexpectedError(thrown);
880 //check to see what type of data we have
881 if (Y.Lang.isString(shouldError)){
883 //if it's a string, check the error message
884 if (thrown.message != shouldError){
885 error = new Y.Assert.UnexpectedError(thrown);
888 } else if (Y.Lang.isFunction(shouldError)){
890 //if it's a function, see if the error is an instance of it
891 if (!(thrown instanceof shouldError)){
892 error = new Y.Assert.UnexpectedError(thrown);
896 } else if (Y.Lang.isObject(shouldError)){
898 //if it's an object, check the instance and message
899 if (!(thrown instanceof shouldError.constructor) ||
900 thrown.message != shouldError.message){
901 error = new Y.Assert.UnexpectedError(thrown);
912 //fire appropriate event
914 this.fire(this.TEST_FAIL_EVENT, { testCase: testCase, testName: testName, error: error });
916 this.fire(this.TEST_PASS_EVENT, { testCase: testCase, testName: testName });
923 var duration = (new Date()) - node._start;
926 node.parent.results[testName] = {
927 result: failed ? "fail" : "pass",
928 message: error ? error.getMessage() : "Test passed",
935 node.parent.results.failed++;
937 node.parent.results.passed++;
939 node.parent.results.total++;
941 //set timeout not supported in all environments
942 if (typeof setTimeout != "undefined"){
943 setTimeout(function(){
944 Y.Test.Runner._run();
953 * Handles an error as if it occurred within the currently executing
954 * test. This is for mock methods that may be called asynchronously
955 * and therefore out of the scope of the TestRunner. Previously, this
956 * error would bubble up to the browser. Now, this method is used
957 * to tell TestRunner about the error. This should never be called
958 * by anyplace other than the Mock object.
959 * @param {Error} error The error object.
961 * @method _handleError
965 _handleError: function(error){
968 this._resumeTest(function(){
978 * Runs a single test based on the data provided in the node.
979 * @param {TestNode} node The TestNode representing the test to run.
985 _runTest : function (node) {
987 //get relevant information
988 var testName = node.testObject;
989 var testCase /*:Y.Test.Case*/ = node.parent.testObject;
990 var test = testCase[testName];
992 //get the "should" test cases
993 var shouldIgnore = (testCase._should.ignore || {})[testName];
995 //figure out if the test should be ignored or not
999 node.parent.results[testName] = {
1001 message: "Test ignored",
1006 node.parent.results.ignored++;
1007 node.parent.results.total++;
1009 this.fire(this.TEST_IGNORE_EVENT, { testCase: testCase, testName: testName });
1011 //some environments don't support setTimeout
1012 if (typeof setTimeout != "undefined"){
1013 setTimeout(function(){
1014 Y.Test.Runner._run();
1022 //mark the start time
1023 node._start = new Date();
1028 //now call the body of the test
1029 this._resumeTest(test);
1034 //-------------------------------------------------------------------------
1036 //-------------------------------------------------------------------------
1039 * Retrieves the name of the current result set.
1040 * @return {String} The name of the result set.
1043 getName: function(){
1044 return this.masterSuite.name;
1048 * The name assigned to the master suite of the TestRunner. This is the name
1049 * that is output as the root's name when results are retrieved.
1050 * @param {String} name The name of the result set.
1054 setName: function(name){
1055 this.masterSuite.name = name;
1058 //-------------------------------------------------------------------------
1059 // Protected Methods
1060 //-------------------------------------------------------------------------
1063 * Fires events for the TestRunner. This overrides the default fire()
1064 * method from EventProvider to add the type property to the data that is
1065 * passed through on each event call.
1066 * @param {String} type The type of event to fire.
1067 * @param {Object} data (Optional) Data for the event.
1072 fire : function (type, data) {
1075 TestRunner.superclass.fire.call(this, type, data);
1078 //-------------------------------------------------------------------------
1080 //-------------------------------------------------------------------------
1083 * Adds a test suite or test case to the list of test objects to run.
1084 * @param testObject Either a TestCase or a TestSuite that should be run.
1089 add : function (testObject) {
1090 this.masterSuite.add(testObject);
1095 * Removes all test objects from the runner.
1100 clear : function () {
1101 this.masterSuite = new Y.Test.Suite("yuitests" + (new Date()).getTime());
1105 * Indicates if the TestRunner is waiting for a test to resume
1106 * @return {Boolean} True if the TestRunner is waiting, false if not.
1110 isWaiting: function() {
1111 return this._waiting;
1115 * Indicates that the TestRunner is busy running tests and therefore can't
1116 * be stopped and results cannot be gathered.
1117 * @return {Boolean} True if the TestRunner is running, false if not.
1120 isRunning: function(){
1121 return this._running;
1125 * Returns the last complete results set from the TestRunner. Null is returned
1126 * if the TestRunner is running or no tests have been run.
1127 * @param {Function} format (Optional) A test format to return the results in.
1128 * @return {Object|String} Either the results object or, if a test format is
1129 * passed as the argument, a string representing the results in a specific
1131 * @method getResults
1133 getResults: function(format){
1134 if (!this._running && this._lastResults){
1135 if (Y.Lang.isFunction(format)){
1136 return format(this._lastResults);
1138 return this._lastResults;
1146 * Returns the coverage report for the files that have been executed.
1147 * This returns only coverage information for files that have been
1148 * instrumented using YUI Test Coverage and only those that were run
1150 * @param {Function} format (Optional) A coverage format to return results in.
1151 * @return {Object|String} Either the coverage object or, if a coverage
1152 * format is specified, a string representing the results in that format.
1153 * @method getCoverage
1155 getCoverage: function(format){
1156 if (!this._running && typeof _yuitest_coverage == "object"){
1157 if (Y.Lang.isFunction(format)){
1158 return format(_yuitest_coverage);
1160 return _yuitest_coverage;
1168 * Resumes the TestRunner after wait() was called.
1169 * @param {Function} segment The function to run as the rest
1170 * of the haulted test.
1175 resume : function (segment) {
1176 if (Y.Test.Runner._waiting){
1177 this._resumeTest(segment || function(){});
1179 throw new Error("resume() called without wait().");
1184 * Runs the test suite.
1185 * @param {Boolean} oldMode (Optional) Specifies that the <= 2.8 way of
1186 * internally managing test suites should be used.
1191 run : function (oldMode) {
1193 //pointer to runner to avoid scope issues
1194 var runner = Y.Test.Runner;
1196 //if there's only one suite on the masterSuite, move it up
1197 if (!oldMode && this.masterSuite.items.length == 1 && this.masterSuite.items[0] instanceof Y.Test.Suite){
1198 this.masterSuite = this.masterSuite.items[0];
1201 //build the test tree
1202 runner._buildTestTree();
1204 //set when the test started
1205 runner._root._start = new Date();
1207 //fire the begin event
1208 runner.fire(runner.BEGIN_EVENT);
1215 return new TestRunner();
1220 * The Assert object provides functions to test JavaScript values against
1221 * known and expected results. Whenever a comparison (assertion) fails,
1222 * an error is thrown.
1230 * The number of assertions performed.
1231 * @property _asserts
1237 //-------------------------------------------------------------------------
1239 //-------------------------------------------------------------------------
1242 * Formats a message so that it can contain the original assertion message
1243 * in addition to the custom message.
1244 * @param {String} customMessage The message passed in by the developer.
1245 * @param {String} defaultMessage The message created by the error by default.
1246 * @return {String} The final error message, containing either or both.
1249 * @method _formatMessage
1251 _formatMessage : function (customMessage, defaultMessage) {
1252 var message = customMessage;
1253 if (Y.Lang.isString(customMessage) && customMessage.length > 0){
1254 return Y.Lang.substitute(customMessage, { message: defaultMessage });
1256 return defaultMessage;
1261 * Returns the number of assertions that have been performed.
1266 _getCount: function(){
1267 return this._asserts;
1271 * Increments the number of assertions that have been performed.
1272 * @method _increment
1276 _increment: function(){
1281 * Resets the number of assertions that have been performed to 0.
1290 //-------------------------------------------------------------------------
1291 // Generic Assertion Methods
1292 //-------------------------------------------------------------------------
1295 * Forces an assertion error to occur.
1296 * @param {String} message (Optional) The message to display with the failure.
1300 fail : function (message) {
1301 throw new Y.Assert.Error(Y.Assert._formatMessage(message, "Test force-failed."));
1304 //-------------------------------------------------------------------------
1305 // Equality Assertion Methods
1306 //-------------------------------------------------------------------------
1309 * Asserts that a value is equal to another. This uses the double equals sign
1310 * so type cohersion may occur.
1311 * @param {Object} expected The expected value.
1312 * @param {Object} actual The actual value to test.
1313 * @param {String} message (Optional) The message to display if the assertion fails.
1317 areEqual : function (expected, actual, message) {
1318 Y.Assert._increment();
1319 if (expected != actual) {
1320 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Values should be equal."), expected, actual);
1325 * Asserts that a value is not equal to another. This uses the double equals sign
1326 * so type cohersion may occur.
1327 * @param {Object} unexpected The unexpected value.
1328 * @param {Object} actual The actual value to test.
1329 * @param {String} message (Optional) The message to display if the assertion fails.
1330 * @method areNotEqual
1333 areNotEqual : function (unexpected, actual,
1335 Y.Assert._increment();
1336 if (unexpected == actual) {
1337 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Values should not be equal."), unexpected);
1342 * Asserts that a value is not the same as another. This uses the triple equals sign
1343 * so no type cohersion may occur.
1344 * @param {Object} unexpected The unexpected value.
1345 * @param {Object} actual The actual value to test.
1346 * @param {String} message (Optional) The message to display if the assertion fails.
1347 * @method areNotSame
1350 areNotSame : function (unexpected, actual, message) {
1351 Y.Assert._increment();
1352 if (unexpected === actual) {
1353 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Values should not be the same."), unexpected);
1358 * Asserts that a value is the same as another. This uses the triple equals sign
1359 * so no type cohersion may occur.
1360 * @param {Object} expected The expected value.
1361 * @param {Object} actual The actual value to test.
1362 * @param {String} message (Optional) The message to display if the assertion fails.
1366 areSame : function (expected, actual, message) {
1367 Y.Assert._increment();
1368 if (expected !== actual) {
1369 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Values should be the same."), expected, actual);
1373 //-------------------------------------------------------------------------
1374 // Boolean Assertion Methods
1375 //-------------------------------------------------------------------------
1378 * Asserts that a value is false. This uses the triple equals sign
1379 * so no type cohersion may occur.
1380 * @param {Object} actual The actual value to test.
1381 * @param {String} message (Optional) The message to display if the assertion fails.
1385 isFalse : function (actual, message) {
1386 Y.Assert._increment();
1387 if (false !== actual) {
1388 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Value should be false."), false, actual);
1393 * Asserts that a value is true. This uses the triple equals sign
1394 * so no type cohersion may occur.
1395 * @param {Object} actual The actual value to test.
1396 * @param {String} message (Optional) The message to display if the assertion fails.
1400 isTrue : function (actual, message) {
1401 Y.Assert._increment();
1402 if (true !== actual) {
1403 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Value should be true."), true, actual);
1408 //-------------------------------------------------------------------------
1409 // Special Value Assertion Methods
1410 //-------------------------------------------------------------------------
1413 * Asserts that a value is not a number.
1414 * @param {Object} actual The value to test.
1415 * @param {String} message (Optional) The message to display if the assertion fails.
1419 isNaN : function (actual, message){
1420 Y.Assert._increment();
1421 if (!isNaN(actual)){
1422 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Value should be NaN."), NaN, actual);
1427 * Asserts that a value is not the special NaN value.
1428 * @param {Object} actual The value to test.
1429 * @param {String} message (Optional) The message to display if the assertion fails.
1433 isNotNaN : function (actual, message){
1434 Y.Assert._increment();
1436 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Values should not be NaN."), NaN);
1441 * Asserts that a value is not null. This uses the triple equals sign
1442 * so no type cohersion may occur.
1443 * @param {Object} actual The actual value to test.
1444 * @param {String} message (Optional) The message to display if the assertion fails.
1448 isNotNull : function (actual, message) {
1449 Y.Assert._increment();
1450 if (Y.Lang.isNull(actual)) {
1451 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Values should not be null."), null);
1456 * Asserts that a value is not undefined. This uses the triple equals sign
1457 * so no type cohersion may occur.
1458 * @param {Object} actual The actual value to test.
1459 * @param {String} message (Optional) The message to display if the assertion fails.
1460 * @method isNotUndefined
1463 isNotUndefined : function (actual, message) {
1464 Y.Assert._increment();
1465 if (Y.Lang.isUndefined(actual)) {
1466 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Value should not be undefined."), undefined);
1471 * Asserts that a value is null. This uses the triple equals sign
1472 * so no type cohersion may occur.
1473 * @param {Object} actual The actual value to test.
1474 * @param {String} message (Optional) The message to display if the assertion fails.
1478 isNull : function (actual, message) {
1479 Y.Assert._increment();
1480 if (!Y.Lang.isNull(actual)) {
1481 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Value should be null."), null, actual);
1486 * Asserts that a value is undefined. This uses the triple equals sign
1487 * so no type cohersion may occur.
1488 * @param {Object} actual The actual value to test.
1489 * @param {String} message (Optional) The message to display if the assertion fails.
1490 * @method isUndefined
1493 isUndefined : function (actual, message) {
1494 Y.Assert._increment();
1495 if (!Y.Lang.isUndefined(actual)) {
1496 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Value should be undefined."), undefined, actual);
1500 //--------------------------------------------------------------------------
1501 // Instance Assertion Methods
1502 //--------------------------------------------------------------------------
1505 * Asserts that a value is an array.
1506 * @param {Object} actual The value to test.
1507 * @param {String} message (Optional) The message to display if the assertion fails.
1511 isArray : function (actual, message) {
1512 Y.Assert._increment();
1513 if (!Y.Lang.isArray(actual)){
1514 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Value should be an array."), actual);
1519 * Asserts that a value is a Boolean.
1520 * @param {Object} actual The value to test.
1521 * @param {String} message (Optional) The message to display if the assertion fails.
1525 isBoolean : function (actual, message) {
1526 Y.Assert._increment();
1527 if (!Y.Lang.isBoolean(actual)){
1528 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Value should be a Boolean."), actual);
1533 * Asserts that a value is a function.
1534 * @param {Object} actual The value to test.
1535 * @param {String} message (Optional) The message to display if the assertion fails.
1536 * @method isFunction
1539 isFunction : function (actual, message) {
1540 Y.Assert._increment();
1541 if (!Y.Lang.isFunction(actual)){
1542 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Value should be a function."), actual);
1547 * Asserts that a value is an instance of a particular object. This may return
1548 * incorrect results when comparing objects from one frame to constructors in
1549 * another frame. For best results, don't use in a cross-frame manner.
1550 * @param {Function} expected The function that the object should be an instance of.
1551 * @param {Object} actual The object to test.
1552 * @param {String} message (Optional) The message to display if the assertion fails.
1553 * @method isInstanceOf
1556 isInstanceOf : function (expected, actual, message) {
1557 Y.Assert._increment();
1558 if (!(actual instanceof expected)){
1559 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Value isn't an instance of expected type."), expected, actual);
1564 * Asserts that a value is a number.
1565 * @param {Object} actual The value to test.
1566 * @param {String} message (Optional) The message to display if the assertion fails.
1570 isNumber : function (actual, message) {
1571 Y.Assert._increment();
1572 if (!Y.Lang.isNumber(actual)){
1573 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Value should be a number."), actual);
1578 * Asserts that a value is an object.
1579 * @param {Object} actual The value to test.
1580 * @param {String} message (Optional) The message to display if the assertion fails.
1584 isObject : function (actual, message) {
1585 Y.Assert._increment();
1586 if (!Y.Lang.isObject(actual)){
1587 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Value should be an object."), actual);
1592 * Asserts that a value is a string.
1593 * @param {Object} actual The value to test.
1594 * @param {String} message (Optional) The message to display if the assertion fails.
1598 isString : function (actual, message) {
1599 Y.Assert._increment();
1600 if (!Y.Lang.isString(actual)){
1601 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Value should be a string."), actual);
1606 * Asserts that a value is of a particular type.
1607 * @param {String} expectedType The expected type of the variable.
1608 * @param {Object} actualValue The actual value to test.
1609 * @param {String} message (Optional) The message to display if the assertion fails.
1613 isTypeOf : function (expectedType, actualValue, message){
1614 Y.Assert._increment();
1615 if (typeof actualValue != expectedType){
1616 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Value should be of type " + expectedType + "."), expected, typeof actualValue);
1622 * Asserts that a given condition is true. If not, then a Y.Assert.Error object is thrown
1623 * and the test fails.
1625 * @param {Boolean} condition The condition to test.
1626 * @param {String} message The message to display if the assertion fails.
1629 Y.assert = function(condition, message){
1630 Y.Assert._increment();
1632 throw new Y.Assert.Error(Y.Assert._formatMessage(message, "Assertion failed."));
1637 * Forces an assertion error to occur. Shortcut for Y.Assert.fail().
1639 * @param {String} message (Optional) The message to display with the failure.
1642 Y.fail = Y.Assert.fail;
1644 //-----------------------------------------------------------------------------
1646 //-----------------------------------------------------------------------------
1649 * Error is thrown whenever an assertion fails. It provides methods
1650 * to more easily get at error information and also provides a base class
1651 * from which more specific assertion errors can be derived.
1653 * @param {String} message The message to display when the error occurs.
1658 Y.Assert.Error = function (message){
1661 arguments.callee.superclass.constructor.call(this, message);
1664 * Error message. Must be duplicated to ensure browser receives it.
1668 this.message = message;
1671 * The name of the error that occurred.
1675 this.name = "Assert Error";
1679 Y.extend(Y.Assert.Error, Error, {
1682 * Returns a fully formatted error for an assertion failure. This should
1683 * be overridden by all subclasses to provide specific information.
1684 * @method getMessage
1685 * @return {String} A string describing the error.
1687 getMessage : function () {
1688 return this.message;
1692 * Returns a string representation of the error.
1694 * @return {String} A string representation of the error.
1696 toString : function () {
1697 return this.name + ": " + this.getMessage();
1701 * Returns a primitive value version of the error. Same as toString().
1703 * @return {String} A primitive value version of the error.
1705 valueOf : function () {
1706 return this.toString();
1712 * ComparisonFailure is subclass of Error that is thrown whenever
1713 * a comparison between two values fails. It provides mechanisms to retrieve
1714 * both the expected and actual value.
1716 * @param {String} message The message to display when the error occurs.
1717 * @param {Object} expected The expected value.
1718 * @param {Object} actual The actual value that caused the assertion to fail.
1720 * @extends Assert.Error
1721 * @class ComparisonFailure
1724 Y.Assert.ComparisonFailure = function (message, expected, actual){
1727 arguments.callee.superclass.constructor.call(this, message);
1730 * The expected value.
1732 * @property expected
1734 this.expected = expected;
1741 this.actual = actual;
1744 * The name of the error that occurred.
1748 this.name = "ComparisonFailure";
1753 Y.extend(Y.Assert.ComparisonFailure, Y.Assert.Error, {
1756 * Returns a fully formatted error for an assertion failure. This message
1757 * provides information about the expected and actual values.
1759 * @return {String} A string describing the error.
1761 getMessage : function () {
1762 return this.message + "\nExpected: " + this.expected + " (" + (typeof this.expected) + ")" +
1763 "\nActual: " + this.actual + " (" + (typeof this.actual) + ")";
1769 * UnexpectedValue is subclass of Error that is thrown whenever
1770 * a value was unexpected in its scope. This typically means that a test
1771 * was performed to determine that a value was *not* equal to a certain
1774 * @param {String} message The message to display when the error occurs.
1775 * @param {Object} unexpected The unexpected value.
1777 * @extends Assert.Error
1778 * @class UnexpectedValue
1781 Y.Assert.UnexpectedValue = function (message, unexpected){
1784 arguments.callee.superclass.constructor.call(this, message);
1787 * The unexpected value.
1789 * @property unexpected
1791 this.unexpected = unexpected;
1794 * The name of the error that occurred.
1798 this.name = "UnexpectedValue";
1803 Y.extend(Y.Assert.UnexpectedValue, Y.Assert.Error, {
1806 * Returns a fully formatted error for an assertion failure. The message
1807 * contains information about the unexpected value that was encountered.
1808 * @method getMessage
1809 * @return {String} A string describing the error.
1811 getMessage : function () {
1812 return this.message + "\nUnexpected: " + this.unexpected + " (" + (typeof this.unexpected) + ") ";
1818 * ShouldFail is subclass of Error that is thrown whenever
1819 * a test was expected to fail but did not.
1821 * @param {String} message The message to display when the error occurs.
1823 * @extends Assert.Error
1827 Y.Assert.ShouldFail = function (message){
1830 arguments.callee.superclass.constructor.call(this, message || "This test should fail but didn't.");
1833 * The name of the error that occurred.
1837 this.name = "ShouldFail";
1842 Y.extend(Y.Assert.ShouldFail, Y.Assert.Error);
1845 * ShouldError is subclass of Error that is thrown whenever
1846 * a test is expected to throw an error but doesn't.
1848 * @param {String} message The message to display when the error occurs.
1850 * @extends Assert.Error
1851 * @class ShouldError
1854 Y.Assert.ShouldError = function (message){
1857 arguments.callee.superclass.constructor.call(this, message || "This test should have thrown an error but didn't.");
1860 * The name of the error that occurred.
1864 this.name = "ShouldError";
1869 Y.extend(Y.Assert.ShouldError, Y.Assert.Error);
1872 * UnexpectedError is subclass of Error that is thrown whenever
1873 * an error occurs within the course of a test and the test was not expected
1874 * to throw an error.
1876 * @param {Error} cause The unexpected error that caused this error to be
1879 * @extends Assert.Error
1880 * @class UnexpectedError
1883 Y.Assert.UnexpectedError = function (cause){
1886 arguments.callee.superclass.constructor.call(this, "Unexpected error: " + cause.message);
1889 * The unexpected error that occurred.
1896 * The name of the error that occurred.
1900 this.name = "UnexpectedError";
1903 * Stack information for the error (if provided).
1907 this.stack = cause.stack;
1912 Y.extend(Y.Assert.UnexpectedError, Y.Assert.Error);
1916 * The ArrayAssert object provides functions to test JavaScript array objects
1917 * for a variety of cases.
1919 * @class ArrayAssert
1926 * Asserts that a value is present in an array. This uses the triple equals
1927 * sign so no type cohersion may occur.
1928 * @param {Object} needle The value that is expected in the array.
1929 * @param {Array} haystack An array of values.
1930 * @param {String} message (Optional) The message to display if the assertion fails.
1934 contains : function (needle, haystack,
1937 Y.Assert._increment();
1939 if (Y.Array.indexOf(haystack, needle) == -1){
1940 Y.Assert.fail(Y.Assert._formatMessage(message, "Value " + needle + " (" + (typeof needle) + ") not found in array [" + haystack + "]."));
1945 * Asserts that a set of values are present in an array. This uses the triple equals
1946 * sign so no type cohersion may occur. For this assertion to pass, all values must
1948 * @param {Object[]} needles An array of values that are expected in the array.
1949 * @param {Array} haystack An array of values to check.
1950 * @param {String} message (Optional) The message to display if the assertion fails.
1951 * @method containsItems
1954 containsItems : function (needles, haystack,
1956 Y.Assert._increment();
1958 //begin checking values
1959 for (var i=0; i < needles.length; i++){
1960 if (Y.Array.indexOf(haystack, needles[i]) == -1){
1961 Y.Assert.fail(Y.Assert._formatMessage(message, "Value " + needles[i] + " (" + (typeof needles[i]) + ") not found in array [" + haystack + "]."));
1967 * Asserts that a value matching some condition is present in an array. This uses
1968 * a function to determine a match.
1969 * @param {Function} matcher A function that returns true if the items matches or false if not.
1970 * @param {Array} haystack An array of values.
1971 * @param {String} message (Optional) The message to display if the assertion fails.
1972 * @method containsMatch
1975 containsMatch : function (matcher, haystack,
1978 Y.Assert._increment();
1979 //check for valid matcher
1980 if (typeof matcher != "function"){
1981 throw new TypeError("ArrayAssert.containsMatch(): First argument must be a function.");
1984 if (!Y.Array.some(haystack, matcher)){
1985 Y.Assert.fail(Y.Assert._formatMessage(message, "No match found in array [" + haystack + "]."));
1990 * Asserts that a value is not present in an array. This uses the triple equals
1991 * Asserts that a value is not present in an array. This uses the triple equals
1992 * sign so no type cohersion may occur.
1993 * @param {Object} needle The value that is expected in the array.
1994 * @param {Array} haystack An array of values.
1995 * @param {String} message (Optional) The message to display if the assertion fails.
1996 * @method doesNotContain
1999 doesNotContain : function (needle, haystack,
2002 Y.Assert._increment();
2004 if (Y.Array.indexOf(haystack, needle) > -1){
2005 Y.Assert.fail(Y.Assert._formatMessage(message, "Value found in array [" + haystack + "]."));
2010 * Asserts that a set of values are not present in an array. This uses the triple equals
2011 * sign so no type cohersion may occur. For this assertion to pass, all values must
2013 * @param {Object[]} needles An array of values that are not expected in the array.
2014 * @param {Array} haystack An array of values to check.
2015 * @param {String} message (Optional) The message to display if the assertion fails.
2016 * @method doesNotContainItems
2019 doesNotContainItems : function (needles, haystack,
2022 Y.Assert._increment();
2024 for (var i=0; i < needles.length; i++){
2025 if (Y.Array.indexOf(haystack, needles[i]) > -1){
2026 Y.Assert.fail(Y.Assert._formatMessage(message, "Value found in array [" + haystack + "]."));
2033 * Asserts that no values matching a condition are present in an array. This uses
2034 * a function to determine a match.
2035 * @param {Function} matcher A function that returns true if the items matches or false if not.
2036 * @param {Array} haystack An array of values.
2037 * @param {String} message (Optional) The message to display if the assertion fails.
2038 * @method doesNotContainMatch
2041 doesNotContainMatch : function (matcher, haystack,
2044 Y.Assert._increment();
2046 //check for valid matcher
2047 if (typeof matcher != "function"){
2048 throw new TypeError("ArrayAssert.doesNotContainMatch(): First argument must be a function.");
2051 if (Y.Array.some(haystack, matcher)){
2052 Y.Assert.fail(Y.Assert._formatMessage(message, "Value found in array [" + haystack + "]."));
2057 * Asserts that the given value is contained in an array at the specified index.
2058 * This uses the triple equals sign so no type cohersion will occur.
2059 * @param {Object} needle The value to look for.
2060 * @param {Array} haystack The array to search in.
2061 * @param {int} index The index at which the value should exist.
2062 * @param {String} message (Optional) The message to display if the assertion fails.
2066 indexOf : function (needle, haystack, index, message) {
2068 Y.Assert._increment();
2070 //try to find the value in the array
2071 for (var i=0; i < haystack.length; i++){
2072 if (haystack[i] === needle){
2074 Y.Assert.fail(Y.Assert._formatMessage(message, "Value exists at index " + i + " but should be at index " + index + "."));
2080 //if it makes it here, it wasn't found at all
2081 Y.Assert.fail(Y.Assert._formatMessage(message, "Value doesn't exist in array [" + haystack + "]."));
2085 * Asserts that the values in an array are equal, and in the same position,
2086 * as values in another array. This uses the double equals sign
2087 * so type cohersion may occur. Note that the array objects themselves
2088 * need not be the same for this test to pass.
2089 * @param {Array} expected An array of the expected values.
2090 * @param {Array} actual Any array of the actual values.
2091 * @param {String} message (Optional) The message to display if the assertion fails.
2092 * @method itemsAreEqual
2095 itemsAreEqual : function (expected, actual,
2098 Y.Assert._increment();
2100 //first check array length
2101 if (expected.length != actual.length){
2102 Y.Assert.fail(Y.Assert._formatMessage(message, "Array should have a length of " + expected.length + " but has a length of " + actual.length));
2105 //begin checking values
2106 for (var i=0; i < expected.length; i++){
2107 if (expected[i] != actual[i]){
2108 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Values in position " + i + " are not equal."), expected[i], actual[i]);
2114 * Asserts that the values in an array are equivalent, and in the same position,
2115 * as values in another array. This uses a function to determine if the values
2116 * are equivalent. Note that the array objects themselves
2117 * need not be the same for this test to pass.
2118 * @param {Array} expected An array of the expected values.
2119 * @param {Array} actual Any array of the actual values.
2120 * @param {Function} comparator A function that returns true if the values are equivalent
2122 * @param {String} message (Optional) The message to display if the assertion fails.
2124 * @method itemsAreEquivalent
2127 itemsAreEquivalent : function (expected, actual,
2128 comparator, message) {
2130 Y.Assert._increment();
2132 //make sure the comparator is valid
2133 if (typeof comparator != "function"){
2134 throw new TypeError("ArrayAssert.itemsAreEquivalent(): Third argument must be a function.");
2137 //first check array length
2138 if (expected.length != actual.length){
2139 Y.Assert.fail(Y.Assert._formatMessage(message, "Array should have a length of " + expected.length + " but has a length of " + actual.length));
2142 //begin checking values
2143 for (var i=0; i < expected.length; i++){
2144 if (!comparator(expected[i], actual[i])){
2145 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Values in position " + i + " are not equivalent."), expected[i], actual[i]);
2151 * Asserts that an array is empty.
2152 * @param {Array} actual The array to test.
2153 * @param {String} message (Optional) The message to display if the assertion fails.
2157 isEmpty : function (actual, message) {
2158 Y.Assert._increment();
2159 if (actual.length > 0){
2160 Y.Assert.fail(Y.Assert._formatMessage(message, "Array should be empty."));
2165 * Asserts that an array is not empty.
2166 * @param {Array} actual The array to test.
2167 * @param {String} message (Optional) The message to display if the assertion fails.
2168 * @method isNotEmpty
2171 isNotEmpty : function (actual, message) {
2172 Y.Assert._increment();
2173 if (actual.length === 0){
2174 Y.Assert.fail(Y.Assert._formatMessage(message, "Array should not be empty."));
2179 * Asserts that the values in an array are the same, and in the same position,
2180 * as values in another array. This uses the triple equals sign
2181 * so no type cohersion will occur. Note that the array objects themselves
2182 * need not be the same for this test to pass.
2183 * @param {Array} expected An array of the expected values.
2184 * @param {Array} actual Any array of the actual values.
2185 * @param {String} message (Optional) The message to display if the assertion fails.
2186 * @method itemsAreSame
2189 itemsAreSame : function (expected, actual,
2192 Y.Assert._increment();
2194 //first check array length
2195 if (expected.length != actual.length){
2196 Y.Assert.fail(Y.Assert._formatMessage(message, "Array should have a length of " + expected.length + " but has a length of " + actual.length));
2199 //begin checking values
2200 for (var i=0; i < expected.length; i++){
2201 if (expected[i] !== actual[i]){
2202 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Values in position " + i + " are not the same."), expected[i], actual[i]);
2208 * Asserts that the given value is contained in an array at the specified index,
2209 * starting from the back of the array.
2210 * This uses the triple equals sign so no type cohersion will occur.
2211 * @param {Object} needle The value to look for.
2212 * @param {Array} haystack The array to search in.
2213 * @param {int} index The index at which the value should exist.
2214 * @param {String} message (Optional) The message to display if the assertion fails.
2215 * @method lastIndexOf
2218 lastIndexOf : function (needle, haystack, index, message) {
2220 //try to find the value in the array
2221 for (var i=haystack.length; i >= 0; i--){
2222 if (haystack[i] === needle){
2224 Y.Assert.fail(Y.Assert._formatMessage(message, "Value exists at index " + i + " but should be at index " + index + "."));
2230 //if it makes it here, it wasn't found at all
2231 Y.Assert.fail(Y.Assert._formatMessage(message, "Value doesn't exist in array."));
2237 * The ObjectAssert object provides functions to test JavaScript objects
2238 * for a variety of cases.
2240 * @class ObjectAssert
2245 areEqual: function(expected, actual, message) {
2246 Y.Assert._increment();
2247 Y.Object.each(expected, function(value, name){
2248 if (expected[name] != actual[name]){
2249 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Values should be equal for property " + name), expected[name], actual[name]);
2255 * Asserts that an object has a property with the given name. The property may exist either
2256 * on the object instance or in its prototype chain. The same as testing
2257 * "property" in object.
2258 * @param {String} propertyName The name of the property to test.
2259 * @param {Object} object The object to search.
2260 * @param {String} message (Optional) The message to display if the assertion fails.
2264 hasKey: function (propertyName, object, message) {
2265 Y.Assert._increment();
2266 if (!(propertyName in object)){
2267 Y.fail(Y.Assert._formatMessage(message, "Property '" + propertyName + "' not found on object."));
2272 * Asserts that an object has all properties of a reference object. The properties may exist either
2273 * on the object instance or in its prototype chain. The same as testing
2274 * "property" in object.
2275 * @param {Array} properties An array of property names that should be on the object.
2276 * @param {Object} object The object to search.
2277 * @param {String} message (Optional) The message to display if the assertion fails.
2281 hasKeys: function (properties, object, message) {
2282 Y.Assert._increment();
2283 for (var i=0; i < properties.length; i++){
2284 if (!(properties[i] in object)){
2285 Y.fail(Y.Assert._formatMessage(message, "Property '" + properties[i] + "' not found on object."));
2291 * Asserts that a property with the given name exists on an object instance (not on its prototype).
2292 * @param {String} propertyName The name of the property to test.
2293 * @param {Object} object The object to search.
2294 * @param {String} message (Optional) The message to display if the assertion fails.
2298 ownsKey: function (propertyName, object, message) {
2299 Y.Assert._increment();
2300 if (!object.hasOwnProperty(propertyName)){
2301 Y.fail(Y.Assert._formatMessage(message, "Property '" + propertyName + "' not found on object instance."));
2306 * Asserts that all properties exist on an object instance (not on its prototype).
2307 * @param {Array} properties An array of property names that should be on the object.
2308 * @param {Object} object The object to search.
2309 * @param {String} message (Optional) The message to display if the assertion fails.
2313 ownsKeys: function (properties, object, message) {
2314 Y.Assert._increment();
2315 for (var i=0; i < properties.length; i++){
2316 if (!object.hasOwnProperty(properties[i])){
2317 Y.fail(Y.Assert._formatMessage(message, "Property '" + properties[i] + "' not found on object instance."));
2323 * Asserts that an object owns no properties.
2324 * @param {Object} object The object to check.
2325 * @param {String} message (Optional) The message to display if the assertion fails.
2326 * @method ownsNoKeys
2329 ownsNoKeys : function (object, message) {
2330 Y.Assert._increment();
2332 var keys = Y.Object.keys(object);
2334 if (keys.length > 0){
2335 Y.fail(Y.Assert._formatMessage(message, "Object owns " + keys.length + " properties but should own none."));
2343 * The DateAssert object provides functions to test JavaScript Date objects
2344 * for a variety of cases.
2354 * Asserts that a date's month, day, and year are equal to another date's.
2355 * @param {Date} expected The expected date.
2356 * @param {Date} actual The actual date to test.
2357 * @param {String} message (Optional) The message to display if the assertion fails.
2358 * @method datesAreEqual
2361 datesAreEqual : function (expected, actual, message){
2362 Y.Assert._increment();
2363 if (expected instanceof Date && actual instanceof Date){
2367 if (expected.getFullYear() != actual.getFullYear()){
2368 msg = "Years should be equal.";
2372 if (expected.getMonth() != actual.getMonth()){
2373 msg = "Months should be equal.";
2376 //last, check the day of the month
2377 if (expected.getDate() != actual.getDate()){
2378 msg = "Days of month should be equal.";
2382 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, msg), expected, actual);
2385 throw new TypeError("Y.Assert.datesAreEqual(): Expected and actual values must be Date objects.");
2390 * Asserts that a date's hour, minutes, and seconds are equal to another date's.
2391 * @param {Date} expected The expected date.
2392 * @param {Date} actual The actual date to test.
2393 * @param {String} message (Optional) The message to display if the assertion fails.
2394 * @method timesAreEqual
2397 timesAreEqual : function (expected, actual, message){
2398 Y.Assert._increment();
2399 if (expected instanceof Date && actual instanceof Date){
2403 if (expected.getHours() != actual.getHours()){
2404 msg = "Hours should be equal.";
2408 if (expected.getMinutes() != actual.getMinutes()){
2409 msg = "Minutes should be equal.";
2412 //last, check the seconds
2413 if (expected.getSeconds() != actual.getSeconds()){
2414 msg = "Seconds should be equal.";
2418 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, msg), expected, actual);
2421 throw new TypeError("DateY.AsserttimesAreEqual(): Expected and actual values must be Date objects.");
2427 Y.namespace("Test.Format");
2429 /* (intentionally not documented)
2430 * Basic XML escaping method. Replaces quotes, less-than, greater-than,
2431 * apostrophe, and ampersand characters with their corresponding entities.
2432 * @param {String} text The text to encode.
2433 * @return {String} The XML-escaped text.
2435 function xmlEscape(text){
2437 return text.replace(/[<>"'&]/g, function(value){
2439 case "<": return "<";
2440 case ">": return ">";
2441 case "\"": return """;
2442 case "'": return "'";
2443 case "&": return "&";
2450 * Contains specific formatting options for test result information.
2457 * Returns test results formatted as a JSON string. Requires JSON utility.
2458 * @param {Object} result The results object created by TestRunner.
2459 * @return {String} A JSON-formatted string of results.
2463 Y.Test.Format.JSON = function(results) {
2464 return Y.JSON.stringify(results);
2468 * Returns test results formatted as an XML string.
2469 * @param {Object} result The results object created by TestRunner.
2470 * @return {String} An XML-formatted string of results.
2474 Y.Test.Format.XML = function(results) {
2476 function serializeToXML(results){
2478 xml = "<" + results.type + " name=\"" + xmlEscape(results.name) + "\"";
2480 if (l.isNumber(results.duration)){
2481 xml += " duration=\"" + results.duration + "\"";
2484 if (results.type == "test"){
2485 xml += " result=\"" + results.result + "\" message=\"" + xmlEscape(results.message) + "\">";
2487 xml += " passed=\"" + results.passed + "\" failed=\"" + results.failed + "\" ignored=\"" + results.ignored + "\" total=\"" + results.total + "\">";
2488 Y.Object.each(results, function(value){
2489 if (l.isObject(value) && !l.isArray(value)){
2490 xml += serializeToXML(value);
2495 xml += "</" + results.type + ">";
2500 return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + serializeToXML(results);
2506 * Returns test results formatted in JUnit XML format.
2507 * @param {Object} result The results object created by TestRunner.
2508 * @return {String} An XML-formatted string of results.
2512 Y.Test.Format.JUnitXML = function(results) {
2514 function serializeToJUnitXML(results){
2518 switch (results.type){
2519 //equivalent to testcase in JUnit
2521 if (results.result != "ignore"){
2522 xml = "<testcase name=\"" + xmlEscape(results.name) + "\" time=\"" + (results.duration/1000) + "\">";
2523 if (results.result == "fail"){
2524 xml += "<failure message=\"" + xmlEscape(results.message) + "\"><![CDATA[" + results.message + "]]></failure>";
2526 xml+= "</testcase>";
2530 //equivalent to testsuite in JUnit
2533 xml = "<testsuite name=\"" + xmlEscape(results.name) + "\" tests=\"" + results.total + "\" failures=\"" + results.failed + "\" time=\"" + (results.duration/1000) + "\">";
2535 Y.Object.each(results, function(value){
2536 if (l.isObject(value) && !l.isArray(value)){
2537 xml += serializeToJUnitXML(value);
2541 xml += "</testsuite>";
2544 //no JUnit equivalent, don't output anything
2546 Y.Object.each(results, function(value){
2547 if (l.isObject(value) && !l.isArray(value)){
2548 xml += serializeToJUnitXML(value);
2553 //top-level, equivalent to testsuites in JUnit
2556 xml = "<testsuites>";
2558 Y.Object.each(results, function(value){
2559 if (l.isObject(value) && !l.isArray(value)){
2560 xml += serializeToJUnitXML(value);
2564 xml += "</testsuites>";
2573 return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + serializeToJUnitXML(results);
2577 * Returns test results formatted in TAP format.
2578 * For more information, see <a href="http://testanything.org/">Test Anything Protocol</a>.
2579 * @param {Object} result The results object created by TestRunner.
2580 * @return {String} A TAP-formatted string of results.
2584 Y.Test.Format.TAP = function(results) {
2586 var currentTestNum = 1;
2588 function serializeToTAP(results){
2592 switch (results.type){
2595 if (results.result != "ignore"){
2597 text = "ok " + (currentTestNum++) + " - " + results.name;
2599 if (results.result == "fail"){
2600 text = "not " + text + " - " + results.message;
2605 text = "#Ignored test " + results.name + "\n";
2611 text = "#Begin testcase " + results.name + "(" + results.failed + " failed of " + results.total + ")\n";
2613 Y.Object.each(results, function(value){
2614 if (l.isObject(value) && !l.isArray(value)){
2615 text += serializeToTAP(value);
2619 text += "#End testcase " + results.name + "\n";
2626 text = "#Begin testsuite " + results.name + "(" + results.failed + " failed of " + results.total + ")\n";
2628 Y.Object.each(results, function(value){
2629 if (l.isObject(value) && !l.isArray(value)){
2630 text += serializeToTAP(value);
2634 text += "#End testsuite " + results.name + "\n";
2639 Y.Object.each(results, function(value){
2640 if (l.isObject(value) && !l.isArray(value)){
2641 text += serializeToTAP(value);
2652 return "1.." + results.total + "\n" + serializeToTAP(results);
2657 Y.namespace("Coverage.Format");
2660 * Contains specific formatting options for coverage information.
2661 * @namespace Coverage
2667 * Returns the coverage report in JSON format. This is the straight
2668 * JSON representation of the native coverage report.
2669 * @param {Object} coverage The coverage report object.
2670 * @return {String} A JSON-formatted string of coverage data.
2674 Y.Coverage.Format.JSON = function(coverage){
2675 return Y.JSON.stringify(coverage);
2679 * Returns the coverage report in a JSON format compatible with
2680 * Xdebug. See <a href="http://www.xdebug.com/docs/code_coverage">Xdebug Documentation</a>
2681 * for more information. Note: function coverage is not available
2683 * @param {Object} coverage The coverage report object.
2684 * @return {String} A JSON-formatted string of coverage data.
2685 * @method XdebugJSON
2688 Y.Coverage.Format.XdebugJSON = function(coverage){
2690 Y.Object.each(coverage, function(value, name){
2691 report[name] = coverage[name].lines;
2693 return Y.JSON.stringify(report);
2699 Y.namespace("Test");
2702 * An object capable of sending test results to a server.
2703 * @param {String} url The URL to submit the results to.
2704 * @param {Function} format (Optiona) A function that outputs the results in a specific format.
2705 * Default is Y.Test.Format.XML.
2710 Y.Test.Reporter = function(url, format) {
2713 * The URL to submit the data to.
2720 * The formatting function to call when submitting the data.
2724 this.format = format || Y.Test.Format.XML;
2727 * Extra fields to submit with the request.
2732 this._fields = new Object();
2735 * The form element used to submit the results.
2736 * @type HTMLFormElement
2743 * Iframe used as a target for form submission.
2744 * @type HTMLIFrameElement
2748 this._iframe = null;
2751 Y.Test.Reporter.prototype = {
2753 //restore missing constructor
2754 constructor: Y.Test.Reporter,
2757 * Adds a field to the form that submits the results.
2758 * @param {String} name The name of the field.
2759 * @param {Variant} value The value of the field.
2763 addField : function (name, value){
2764 this._fields[name] = value;
2768 * Removes all previous defined fields.
2772 clearFields : function(){
2773 this._fields = new Object();
2777 * Cleans up the memory associated with the TestReporter, removing DOM elements
2778 * that were created.
2782 destroy : function() {
2784 this._form.parentNode.removeChild(this._form);
2788 this._iframe.parentNode.removeChild(this._iframe);
2789 this._iframe = null;
2791 this._fields = null;
2795 * Sends the report to the server.
2796 * @param {Object} results The results object created by TestRunner.
2800 report : function(results){
2802 //if the form hasn't been created yet, create it
2804 this._form = document.createElement("form");
2805 this._form.method = "post";
2806 this._form.style.visibility = "hidden";
2807 this._form.style.position = "absolute";
2808 this._form.style.top = 0;
2809 document.body.appendChild(this._form);
2811 // IE won't let you assign a name using the DOM, must do it the hacky way
2812 var iframeContainer = document.createElement("div");
2813 iframeContainer.innerHTML = "<iframe name=\"yuiTestTarget\"></iframe>";
2814 this._iframe = iframeContainer.firstChild;
2816 this._iframe.src = "javascript:false";
2817 this._iframe.style.visibility = "hidden";
2818 this._iframe.style.position = "absolute";
2819 this._iframe.style.top = 0;
2820 document.body.appendChild(this._iframe);
2822 this._form.target = "yuiTestTarget";
2825 //set the form's action
2826 this._form.action = this.url;
2828 //remove any existing fields
2829 while(this._form.hasChildNodes()){
2830 this._form.removeChild(this._form.lastChild);
2833 //create default fields
2834 this._fields.results = this.format(results);
2835 this._fields.useragent = navigator.userAgent;
2836 this._fields.timestamp = (new Date()).toLocaleString();
2838 //add fields to the form
2839 Y.Object.each(this._fields, function(value, prop){
2840 if (typeof value != "function"){
2841 var input = document.createElement("input");
2842 input.type = "hidden";
2844 input.value = value;
2845 this._form.appendChild(input);
2849 //remove default fields
2850 delete this._fields.results;
2851 delete this._fields.useragent;
2852 delete this._fields.timestamp;
2854 if (arguments[1] !== false){
2855 this._form.submit();
2862 * Creates a new mock object.
2865 * @param {Object} template (Optional) An object whose methods
2866 * should be stubbed out on the mock object. This object
2867 * is used as the prototype of the mock object so instanceof
2870 Y.Mock = function(template){
2872 //use blank object is nothing is passed in
2873 template = template || {};
2877 //try to create mock that keeps prototype chain intact
2879 mock = Y.Object(template);
2882 Y.log("Couldn't create mock with prototype.", "warn", "Mock");
2885 //create new versions of the methods so that they don't actually do anything
2886 Y.Object.each(template, function(name){
2887 if (Y.Lang.isFunction(template[name])){
2888 mock[name] = function(){
2889 Y.Assert.fail("Method " + name + "() was called but was not expected to be.");
2899 * Assigns an expectation to a mock object. This is used to create
2900 * methods and properties on the mock object that are monitored for
2901 * calls and changes, respectively.
2902 * @param {Object} mock The object to add the expectation to.
2903 * @param {Object} expectation An object defining the expectation. For
2904 * a method, the keys "method" and "args" are required with
2905 * an optional "returns" key available. For properties, the keys
2906 * "property" and "value" are required.
2911 Y.Mock.expect = function(mock /*:Object*/, expectation /*:Object*/){
2913 //make sure there's a place to store the expectations
2914 if (!mock.__expectations) {
2915 mock.__expectations = {};
2918 //method expectation
2919 if (expectation.method){
2920 var name = expectation.method,
2921 args = expectation.args || expectation.arguments || [],
2922 result = expectation.returns,
2923 callCount = Y.Lang.isNumber(expectation.callCount) ? expectation.callCount : 1,
2924 error = expectation.error,
2925 run = expectation.run || function(){};
2928 mock.__expectations[name] = expectation;
2929 expectation.callCount = callCount;
2930 expectation.actualCallCount = 0;
2933 Y.Array.each(args, function(arg, i, array){
2934 if (!(array[i] instanceof Y.Mock.Value)){
2935 array[i] = Y.Mock.Value(Y.Assert.areSame, [arg], "Argument " + i + " of " + name + "() is incorrect.");
2939 //if the method is expected to be called
2941 mock[name] = function(){
2943 expectation.actualCallCount++;
2944 Y.Assert.areEqual(args.length, arguments.length, "Method " + name + "() passed incorrect number of arguments.");
2945 for (var i=0, len=args.length; i < len; i++){
2947 args[i].verify(arguments[i]);
2949 // Y.Assert.fail("Argument " + i + " (" + arguments[i] + ") was not expected to be used.");
2954 run.apply(this, arguments);
2960 //route through TestRunner for proper handling
2961 Y.Test.Runner._handleError(ex);
2968 //method should fail if called when not expected
2969 mock[name] = function(){
2971 Y.Assert.fail("Method " + name + "() should not have been called.");
2973 //route through TestRunner for proper handling
2974 Y.Test.Runner._handleError(ex);
2978 } else if (expectation.property){
2980 mock.__expectations[name] = expectation;
2985 * Verifies that all expectations of a mock object have been met and
2986 * throws an assertion error if not.
2987 * @param {Object} mock The object to verify..
2992 Y.Mock.verify = function(mock /*:Object*/){
2994 Y.Object.each(mock.__expectations, function(expectation){
2995 if (expectation.method) {
2996 Y.Assert.areEqual(expectation.callCount, expectation.actualCallCount, "Method " + expectation.method + "() wasn't called the expected number of times.");
2997 } else if (expectation.property){
2998 Y.Assert.areEqual(expectation.value, mock[expectation.property], "Property " + expectation.property + " wasn't set to the correct value.");
3002 //route through TestRunner for proper handling
3003 Y.Test.Runner._handleError(ex);
3008 * Defines a custom mock validator for a particular argument.
3009 * @param {Function} method The method to run on the argument. This should
3010 * throw an assertion error if the value is invalid.
3011 * @param {Array} originalArgs The first few arguments to pass in
3012 * to the method. The value to test and failure message are
3013 * always the last two arguments passed into method.
3014 * @param {String} message The message to display if validation fails. If
3015 * not specified, the default assertion error message is displayed.
3018 * @constructor Value
3021 Y.Mock.Value = function(method, originalArgs, message){
3022 if (Y.instanceOf(this, Y.Mock.Value)){
3023 this.verify = function(value){
3024 var args = [].concat(originalArgs || []);
3027 method.apply(null, args);
3030 return new Y.Mock.Value(method, originalArgs, message);
3035 * Mock argument validator that accepts any value as valid.
3036 * @namespace Mock.Value
3041 Y.Mock.Value.Any = Y.Mock.Value(function(){});
3044 * Mock argument validator that accepts only Boolean values as valid.
3045 * @namespace Mock.Value
3050 Y.Mock.Value.Boolean = Y.Mock.Value(Y.Assert.isBoolean);
3053 * Mock argument validator that accepts only numeric values as valid.
3054 * @namespace Mock.Value
3059 Y.Mock.Value.Number = Y.Mock.Value(Y.Assert.isNumber);
3062 * Mock argument validator that accepts only String values as valid.
3063 * @namespace Mock.Value
3068 Y.Mock.Value.String = Y.Mock.Value(Y.Assert.isString);
3071 * Mock argument validator that accepts only non-null objects values as valid.
3072 * @namespace Mock.Value
3077 Y.Mock.Value.Object = Y.Mock.Value(Y.Assert.isObject);
3080 * Mock argument validator that accepts onlyfunctions as valid.
3081 * @namespace Mock.Value
3082 * @property Function
3086 Y.Mock.Value.Function = Y.Mock.Value(Y.Assert.isFunction);
3087 /*Stub for future compatibility*/
3088 if (typeof YUITest == "undefined" || !YUITest) {
3090 TestRunner: Y.Test.Runner,
3091 ResultsFormat: Y.Test.Format,
3092 CoverageFormat: Y.Coverage.Format
3097 }, '3.3.0' ,{requires:['substitute','event-base','json-stringify']});